2 * Copyright (c) 2005-2009 Ariff Abdullah <ariff@FreeBSD.org>
3 * Portions Copyright (c) Ryan Beasley <ryan.beasley@gmail.com> - GSoC 2006
4 * Copyright (c) 1999 Cameron Grant <cg@FreeBSD.org>
5 * Portions Copyright (c) Luigi Rizzo <luigi@FreeBSD.org> - 1997-99
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #ifdef HAVE_KERNEL_OPTION_HEADERS
36 #include <dev/sound/pcm/sound.h>
37 #include <dev/sound/pcm/vchan.h>
39 #include "feeder_if.h"
41 SND_DECLARE_FILE("$FreeBSD$");
43 int report_soft_formats = 1;
44 SYSCTL_INT(_hw_snd, OID_AUTO, report_soft_formats, CTLFLAG_RW,
45 &report_soft_formats, 1, "report software-emulated formats");
47 int report_soft_matrix = 1;
48 SYSCTL_INT(_hw_snd, OID_AUTO, report_soft_matrix, CTLFLAG_RW,
49 &report_soft_matrix, 1, "report software-emulated channel matrixing");
51 int chn_latency = CHN_LATENCY_DEFAULT;
52 TUNABLE_INT("hw.snd.latency", &chn_latency);
55 sysctl_hw_snd_latency(SYSCTL_HANDLER_ARGS)
60 err = sysctl_handle_int(oidp, &val, 0, req);
61 if (err != 0 || req->newptr == NULL)
63 if (val < CHN_LATENCY_MIN || val > CHN_LATENCY_MAX)
70 SYSCTL_PROC(_hw_snd, OID_AUTO, latency, CTLTYPE_INT | CTLFLAG_RW,
71 0, sizeof(int), sysctl_hw_snd_latency, "I",
72 "buffering latency (0=low ... 10=high)");
74 int chn_latency_profile = CHN_LATENCY_PROFILE_DEFAULT;
75 TUNABLE_INT("hw.snd.latency_profile", &chn_latency_profile);
78 sysctl_hw_snd_latency_profile(SYSCTL_HANDLER_ARGS)
82 val = chn_latency_profile;
83 err = sysctl_handle_int(oidp, &val, 0, req);
84 if (err != 0 || req->newptr == NULL)
86 if (val < CHN_LATENCY_PROFILE_MIN || val > CHN_LATENCY_PROFILE_MAX)
89 chn_latency_profile = val;
93 SYSCTL_PROC(_hw_snd, OID_AUTO, latency_profile, CTLTYPE_INT | CTLFLAG_RW,
94 0, sizeof(int), sysctl_hw_snd_latency_profile, "I",
95 "buffering latency profile (0=aggresive 1=safe)");
97 static int chn_timeout = CHN_TIMEOUT;
98 TUNABLE_INT("hw.snd.timeout", &chn_timeout);
101 sysctl_hw_snd_timeout(SYSCTL_HANDLER_ARGS)
106 err = sysctl_handle_int(oidp, &val, 0, req);
107 if (err != 0 || req->newptr == NULL)
109 if (val < CHN_TIMEOUT_MIN || val > CHN_TIMEOUT_MAX)
116 SYSCTL_PROC(_hw_snd, OID_AUTO, timeout, CTLTYPE_INT | CTLFLAG_RW,
117 0, sizeof(int), sysctl_hw_snd_timeout, "I",
118 "interrupt timeout (1 - 10) seconds");
121 static int chn_vpc_autoreset = 1;
122 TUNABLE_INT("hw.snd.vpc_autoreset", &chn_vpc_autoreset);
123 SYSCTL_INT(_hw_snd, OID_AUTO, vpc_autoreset, CTLFLAG_RW,
124 &chn_vpc_autoreset, 0, "automatically reset channels volume to 0db");
126 static int chn_vol_0db_pcm = SND_VOL_0DB_PCM;
129 chn_vpc_proc(int reset, int db)
131 struct snddev_info *d;
132 struct pcm_channel *c;
135 for (i = 0; pcm_devclass != NULL &&
136 i < devclass_get_maxunit(pcm_devclass); i++) {
137 d = devclass_get_softc(pcm_devclass, i);
138 if (!PCM_REGISTERED(d))
143 CHN_FOREACH(c, d, channels.pcm) {
145 CHN_SETVOLUME(c, SND_VOL_C_PCM, SND_CHN_T_VOL_0DB, db);
147 chn_vpc_reset(c, SND_VOL_C_PCM, 1);
156 sysctl_hw_snd_vpc_0db(SYSCTL_HANDLER_ARGS)
160 val = chn_vol_0db_pcm;
161 err = sysctl_handle_int(oidp, &val, 0, req);
162 if (err != 0 || req->newptr == NULL)
164 if (val < SND_VOL_0DB_MIN || val > SND_VOL_0DB_MAX)
167 chn_vol_0db_pcm = val;
168 chn_vpc_proc(0, val);
172 SYSCTL_PROC(_hw_snd, OID_AUTO, vpc_0db, CTLTYPE_INT | CTLFLAG_RW,
173 0, sizeof(int), sysctl_hw_snd_vpc_0db, "I",
174 "0db relative level");
177 sysctl_hw_snd_vpc_reset(SYSCTL_HANDLER_ARGS)
182 err = sysctl_handle_int(oidp, &val, 0, req);
183 if (err != 0 || req->newptr == NULL || val == 0)
186 chn_vol_0db_pcm = SND_VOL_0DB_PCM;
187 chn_vpc_proc(1, SND_VOL_0DB_PCM);
191 SYSCTL_PROC(_hw_snd, OID_AUTO, vpc_reset, CTLTYPE_INT | CTLFLAG_RW,
192 0, sizeof(int), sysctl_hw_snd_vpc_reset, "I",
193 "reset volume on all channels");
195 static int chn_usefrags = 0;
196 TUNABLE_INT("hw.snd.usefrags", &chn_usefrags);
197 static int chn_syncdelay = -1;
198 TUNABLE_INT("hw.snd.syncdelay", &chn_syncdelay);
200 SYSCTL_INT(_hw_snd, OID_AUTO, usefrags, CTLFLAG_RW,
201 &chn_usefrags, 1, "prefer setfragments() over setblocksize()");
202 SYSCTL_INT(_hw_snd, OID_AUTO, syncdelay, CTLFLAG_RW,
204 "append (0-1000) millisecond trailing buffer delay on each sync");
208 * @brief Channel sync group lock
210 * Clients should acquire this lock @b without holding any channel locks
211 * before touching syncgroups or the main syncgroup list.
213 struct mtx snd_pcm_syncgroups_mtx;
214 MTX_SYSINIT(pcm_syncgroup, &snd_pcm_syncgroups_mtx, "PCM channel sync group lock", MTX_DEF);
216 * @brief syncgroups' master list
218 * Each time a channel syncgroup is created, it's added to this list. This
219 * list should only be accessed with @sa snd_pcm_syncgroups_mtx held.
221 * See SNDCTL_DSP_SYNCGROUP for more information.
223 struct pcm_synclist snd_pcm_syncgroups = SLIST_HEAD_INITIALIZER(head);
226 chn_lockinit(struct pcm_channel *c, int dir)
230 c->lock = snd_mtxcreate(c->name, "pcm play channel");
231 cv_init(&c->intr_cv, "pcmwr");
233 case PCMDIR_PLAY_VIRTUAL:
234 c->lock = snd_mtxcreate(c->name, "pcm virtual play channel");
235 cv_init(&c->intr_cv, "pcmwrv");
238 c->lock = snd_mtxcreate(c->name, "pcm record channel");
239 cv_init(&c->intr_cv, "pcmrd");
241 case PCMDIR_REC_VIRTUAL:
242 c->lock = snd_mtxcreate(c->name, "pcm virtual record channel");
243 cv_init(&c->intr_cv, "pcmrdv");
246 panic("%s(): Invalid direction=%d", __func__, dir);
250 cv_init(&c->cv, "pcmchn");
254 chn_lockdestroy(struct pcm_channel *c)
258 CHN_BROADCAST(&c->cv);
259 CHN_BROADCAST(&c->intr_cv);
262 cv_destroy(&c->intr_cv);
264 snd_mtxfree(c->lock);
268 * @brief Determine channel is ready for I/O
270 * @retval 1 = ready for I/O
271 * @retval 0 = not ready for I/O
274 chn_polltrigger(struct pcm_channel *c)
276 struct snd_dbuf *bs = c->bufsoft;
281 if (c->flags & CHN_F_MMAP) {
282 if (sndbuf_getprevtotal(bs) < c->lw)
285 delta = sndbuf_gettotal(bs) - sndbuf_getprevtotal(bs);
287 if (c->direction == PCMDIR_PLAY)
288 delta = sndbuf_getfree(bs);
290 delta = sndbuf_getready(bs);
293 return ((delta < c->lw) ? 0 : 1);
297 chn_pollreset(struct pcm_channel *c)
301 sndbuf_updateprevtotal(c->bufsoft);
305 chn_wakeup(struct pcm_channel *c)
308 struct pcm_channel *ch;
314 if (CHN_EMPTY(c, children.busy)) {
315 if (SEL_WAITING(sndbuf_getsel(bs)) && chn_polltrigger(c))
316 selwakeuppri(sndbuf_getsel(bs), PRIBIO);
317 if (c->flags & CHN_F_SLEEPING) {
319 * Ok, I can just panic it right here since it is
320 * quite obvious that we never allow multiple waiters
321 * from userland. I'm too generous...
323 CHN_BROADCAST(&c->intr_cv);
326 CHN_FOREACH(ch, c, children.busy) {
335 chn_sleep(struct pcm_channel *c, int timeout)
341 if (c->flags & CHN_F_DEAD)
344 c->flags |= CHN_F_SLEEPING;
345 ret = cv_timedwait_sig(&c->intr_cv, c->lock, timeout);
346 c->flags &= ~CHN_F_SLEEPING;
348 return ((c->flags & CHN_F_DEAD) ? EINVAL : ret);
352 * chn_dmaupdate() tracks the status of a dma transfer,
357 chn_dmaupdate(struct pcm_channel *c)
359 struct snd_dbuf *b = c->bufhard;
360 unsigned int delta, old, hwptr, amt;
362 KASSERT(sndbuf_getsize(b) > 0, ("bufsize == 0"));
365 old = sndbuf_gethwptr(b);
366 hwptr = chn_getptr(c);
367 delta = (sndbuf_getsize(b) + hwptr - old) % sndbuf_getsize(b);
368 sndbuf_sethwptr(b, hwptr);
370 if (c->direction == PCMDIR_PLAY) {
371 amt = min(delta, sndbuf_getready(b));
372 amt -= amt % sndbuf_getalign(b);
374 sndbuf_dispose(b, NULL, amt);
376 amt = min(delta, sndbuf_getfree(b));
377 amt -= amt % sndbuf_getalign(b);
379 sndbuf_acquire(b, NULL, amt);
381 if (snd_verbose > 3 && CHN_STARTED(c) && delta == 0) {
382 device_printf(c->dev, "WARNING: %s DMA completion "
383 "too fast/slow ! hwptr=%u, old=%u "
384 "delta=%u amt=%u ready=%u free=%u\n",
385 CHN_DIRSTR(c), hwptr, old, delta, amt,
386 sndbuf_getready(b), sndbuf_getfree(b));
393 chn_wrfeed(struct pcm_channel *c)
395 struct snd_dbuf *b = c->bufhard;
396 struct snd_dbuf *bs = c->bufsoft;
401 if ((c->flags & CHN_F_MMAP) && !(c->flags & CHN_F_CLOSING))
402 sndbuf_acquire(bs, NULL, sndbuf_getfree(bs));
404 amt = sndbuf_getfree(b);
406 sndbuf_feed(bs, b, c, c->feeder, amt);
409 * Possible xruns. There should be no empty space left in buffer.
411 if (sndbuf_getfree(b) > 0)
414 if (sndbuf_getfree(b) < amt)
420 chn_wrupdate(struct pcm_channel *c)
424 KASSERT(c->direction == PCMDIR_PLAY, ("%s(): bad channel", __func__));
426 if ((c->flags & (CHN_F_MMAP | CHN_F_VIRTUAL)) || CHN_STOPPED(c))
430 /* tell the driver we've updated the primary buffer */
431 chn_trigger(c, PCMTRIG_EMLDMAWR);
436 chn_wrintr(struct pcm_channel *c)
440 /* update pointers in primary buffer */
442 /* ...and feed from secondary to primary */
444 /* tell the driver we've updated the primary buffer */
445 chn_trigger(c, PCMTRIG_EMLDMAWR);
449 * user write routine - uiomove data into secondary buffer, trigger if necessary
450 * if blocking, sleep, rinse and repeat.
452 * called externally, so must handle locking
456 chn_write(struct pcm_channel *c, struct uio *buf)
458 struct snd_dbuf *bs = c->bufsoft;
460 int ret, timeout, sz, t, p;
465 timeout = chn_timeout * hz;
467 while (ret == 0 && buf->uio_resid > 0) {
468 sz = min(buf->uio_resid, sndbuf_getfree(bs));
471 * The following assumes that the free space in
472 * the buffer can never be less around the
473 * unlock-uiomove-lock sequence.
475 while (ret == 0 && sz > 0) {
476 p = sndbuf_getfreeptr(bs);
477 t = min(sz, sndbuf_getsize(bs) - p);
478 off = sndbuf_getbufofs(bs, p);
480 ret = uiomove(off, t, buf);
483 sndbuf_acquire(bs, NULL, t);
486 if (CHN_STOPPED(c) && !(c->flags & CHN_F_NOTRIGGER)) {
487 ret = chn_start(c, 0);
489 c->flags |= CHN_F_DEAD;
491 } else if (c->flags & (CHN_F_NBIO | CHN_F_NOTRIGGER)) {
493 * @todo Evaluate whether EAGAIN is truly desirable.
494 * 4Front drivers behave like this, but I'm
495 * not sure if it at all violates the "write
496 * should be allowed to block" model.
498 * The idea is that, while set with CHN_F_NOTRIGGER,
499 * a channel isn't playing, *but* without this we
500 * end up with "interrupt timeout / channel dead".
504 ret = chn_sleep(c, timeout);
507 c->flags |= CHN_F_DEAD;
508 device_printf(c->dev, "%s(): %s: "
509 "play interrupt timeout, channel dead\n",
511 } else if (ret == ERESTART || ret == EINTR)
512 c->flags |= CHN_F_ABORTING;
520 * Feed new data from the read buffer. Can be called in the bottom half.
523 chn_rdfeed(struct pcm_channel *c)
525 struct snd_dbuf *b = c->bufhard;
526 struct snd_dbuf *bs = c->bufsoft;
531 if (c->flags & CHN_F_MMAP)
532 sndbuf_dispose(bs, NULL, sndbuf_getready(bs));
534 amt = sndbuf_getfree(bs);
536 sndbuf_feed(b, bs, c, c->feeder, amt);
538 amt = sndbuf_getready(b);
541 sndbuf_dispose(b, NULL, amt);
544 if (sndbuf_getready(bs) > 0)
550 chn_rdupdate(struct pcm_channel *c)
554 KASSERT(c->direction == PCMDIR_REC, ("chn_rdupdate on bad channel"));
556 if ((c->flags & (CHN_F_MMAP | CHN_F_VIRTUAL)) || CHN_STOPPED(c))
558 chn_trigger(c, PCMTRIG_EMLDMARD);
564 /* read interrupt routine. Must be called with interrupts blocked. */
566 chn_rdintr(struct pcm_channel *c)
570 /* tell the driver to update the primary buffer if non-dma */
571 chn_trigger(c, PCMTRIG_EMLDMARD);
572 /* update pointers in primary buffer */
574 /* ...and feed from primary to secondary */
579 * user read routine - trigger if necessary, uiomove data from secondary buffer
580 * if blocking, sleep, rinse and repeat.
582 * called externally, so must handle locking
586 chn_read(struct pcm_channel *c, struct uio *buf)
588 struct snd_dbuf *bs = c->bufsoft;
590 int ret, timeout, sz, t, p;
594 if (CHN_STOPPED(c) && !(c->flags & CHN_F_NOTRIGGER)) {
595 ret = chn_start(c, 0);
597 c->flags |= CHN_F_DEAD;
603 timeout = chn_timeout * hz;
605 while (ret == 0 && buf->uio_resid > 0) {
606 sz = min(buf->uio_resid, sndbuf_getready(bs));
609 * The following assumes that the free space in
610 * the buffer can never be less around the
611 * unlock-uiomove-lock sequence.
613 while (ret == 0 && sz > 0) {
614 p = sndbuf_getreadyptr(bs);
615 t = min(sz, sndbuf_getsize(bs) - p);
616 off = sndbuf_getbufofs(bs, p);
618 ret = uiomove(off, t, buf);
621 sndbuf_dispose(bs, NULL, t);
624 } else if (c->flags & (CHN_F_NBIO | CHN_F_NOTRIGGER))
627 ret = chn_sleep(c, timeout);
630 c->flags |= CHN_F_DEAD;
631 device_printf(c->dev, "%s(): %s: "
632 "record interrupt timeout, channel dead\n",
634 } else if (ret == ERESTART || ret == EINTR)
635 c->flags |= CHN_F_ABORTING;
643 chn_intr_locked(struct pcm_channel *c)
650 if (c->direction == PCMDIR_PLAY)
657 chn_intr(struct pcm_channel *c)
660 if (CHN_LOCKOWNED(c)) {
671 chn_start(struct pcm_channel *c, int force)
674 struct snd_dbuf *b = c->bufhard;
675 struct snd_dbuf *bs = c->bufsoft;
679 /* if we're running, or if we're prevented from triggering, bail */
680 if (CHN_STARTED(c) || ((c->flags & CHN_F_NOTRIGGER) && !force))
689 if (c->direction == PCMDIR_REC) {
690 i = sndbuf_getfree(bs);
691 j = (i > 0) ? 1 : sndbuf_getready(b);
693 if (sndbuf_getfree(bs) == 0) {
699 pb = CHN_BUF_PARENT(c, b);
700 i = sndbuf_xbytes(sndbuf_getready(bs), bs, pb);
701 j = sndbuf_getalign(pb);
704 if (snd_verbose > 3 && CHN_EMPTY(c, children))
705 device_printf(c->dev, "%s(): %s (%s) threshold "
706 "i=%d j=%d\n", __func__, CHN_DIRSTR(c),
707 (c->flags & CHN_F_VIRTUAL) ? "virtual" :
712 c->flags |= CHN_F_TRIGGERED;
714 if (c->flags & CHN_F_CLOSING)
721 if (c->parentchannel == NULL) {
722 if (c->direction == PCMDIR_PLAY)
723 sndbuf_fillsilence(b);
725 device_printf(c->dev,
726 "%s(): %s starting! (%s/%s) "
727 "(ready=%d force=%d i=%d j=%d "
728 "intrtimeout=%u latency=%dms)\n",
730 (c->flags & CHN_F_HAS_VCHAN) ?
731 "VCHAN PARENT" : "HW", CHN_DIRSTR(c),
732 (c->flags & CHN_F_CLOSING) ? "closing" :
735 force, i, j, c->timeout,
736 (sndbuf_getsize(b) * 1000) /
737 (sndbuf_getalign(b) * sndbuf_getspd(b)));
739 err = chn_trigger(c, PCMTRIG_START);
746 chn_resetbuf(struct pcm_channel *c)
748 struct snd_dbuf *b = c->bufhard;
749 struct snd_dbuf *bs = c->bufsoft;
757 * chn_sync waits until the space in the given channel goes above
758 * a threshold. The threshold is checked against fl or rl respectively.
759 * Assume that the condition can become true, do not check here...
762 chn_sync(struct pcm_channel *c, int threshold)
764 struct snd_dbuf *b, *bs;
765 int ret, count, hcount, minflush, resid, residp, syncdelay, blksz;
770 if (c->direction != PCMDIR_PLAY)
775 if ((c->flags & (CHN_F_DEAD | CHN_F_ABORTING)) ||
776 (threshold < 1 && sndbuf_getready(bs) < 1))
779 /* if we haven't yet started and nothing is buffered, else start*/
780 if (CHN_STOPPED(c)) {
781 if (threshold > 0 || sndbuf_getready(bs) > 0) {
782 ret = chn_start(c, 1);
789 b = CHN_BUF_PARENT(c, c->bufhard);
791 minflush = threshold + sndbuf_xbytes(sndbuf_getready(b), b, bs);
793 syncdelay = chn_syncdelay;
795 if (syncdelay < 0 && (threshold > 0 || sndbuf_getready(bs) > 0))
796 minflush += sndbuf_xbytes(sndbuf_getsize(b), b, bs);
799 * Append (0-1000) millisecond trailing buffer (if needed)
800 * for slower / high latency hardwares (notably USB audio)
801 * to avoid audible truncation.
804 minflush += (sndbuf_getalign(bs) * sndbuf_getspd(bs) *
805 ((syncdelay > 1000) ? 1000 : syncdelay)) / 1000;
807 minflush -= minflush % sndbuf_getalign(bs);
810 threshold = min(minflush, sndbuf_getfree(bs));
811 sndbuf_clear(bs, threshold);
812 sndbuf_acquire(bs, NULL, threshold);
813 minflush -= threshold;
816 resid = sndbuf_getready(bs);
818 blksz = sndbuf_getblksz(b);
820 device_printf(c->dev,
821 "%s(): WARNING: blksz < 1 ! maxsize=%d [%d/%d/%d]\n",
822 __func__, sndbuf_getmaxsize(b), sndbuf_getsize(b),
823 sndbuf_getblksz(b), sndbuf_getblkcnt(b));
824 if (sndbuf_getblkcnt(b) > 0)
825 blksz = sndbuf_getsize(b) / sndbuf_getblkcnt(b);
829 count = sndbuf_xbytes(minflush + resid, bs, b) / blksz;
834 device_printf(c->dev, "%s(): [begin] timeout=%d count=%d "
835 "minflush=%d resid=%d\n", __func__, c->timeout, count,
838 cflag = c->flags & CHN_F_CLOSING;
839 c->flags |= CHN_F_CLOSING;
840 while (count > 0 && (resid > 0 || minflush > 0)) {
841 ret = chn_sleep(c, c->timeout);
842 if (ret == ERESTART || ret == EINTR) {
843 c->flags |= CHN_F_ABORTING;
845 } else if (ret == 0 || ret == EAGAIN) {
846 resid = sndbuf_getready(bs);
847 if (resid == residp) {
850 device_printf(c->dev,
851 "%s(): [stalled] timeout=%d "
852 "count=%d hcount=%d "
853 "resid=%d minflush=%d\n",
854 __func__, c->timeout, count,
855 hcount, resid, minflush);
856 } else if (resid < residp && count < hcount) {
859 device_printf(c->dev,
860 "%s((): [resume] timeout=%d "
861 "count=%d hcount=%d "
862 "resid=%d minflush=%d\n",
863 __func__, c->timeout, count,
864 hcount, resid, minflush);
866 if (minflush > 0 && sndbuf_getfree(bs) > 0) {
867 threshold = min(minflush,
869 sndbuf_clear(bs, threshold);
870 sndbuf_acquire(bs, NULL, threshold);
871 resid = sndbuf_getready(bs);
872 minflush -= threshold;
878 c->flags &= ~CHN_F_CLOSING;
882 device_printf(c->dev,
883 "%s(): timeout=%d count=%d hcount=%d resid=%d residp=%d "
884 "minflush=%d ret=%d\n",
885 __func__, c->timeout, count, hcount, resid, residp,
891 /* called externally, handle locking */
893 chn_poll(struct pcm_channel *c, int ev, struct thread *td)
895 struct snd_dbuf *bs = c->bufsoft;
900 if (!(c->flags & (CHN_F_MMAP | CHN_F_TRIGGERED))) {
901 ret = chn_start(c, 1);
907 if (chn_polltrigger(c)) {
911 selrecord(td, sndbuf_getsel(bs));
917 * chn_abort terminates a running dma transfer. it may sleep up to 200ms.
918 * it returns the number of bytes that have not been transferred.
920 * called from: dsp_close, dsp_ioctl, with channel locked
923 chn_abort(struct pcm_channel *c)
926 struct snd_dbuf *b = c->bufhard;
927 struct snd_dbuf *bs = c->bufsoft;
932 c->flags |= CHN_F_ABORTING;
934 c->flags &= ~CHN_F_TRIGGERED;
935 /* kill the channel */
936 chn_trigger(c, PCMTRIG_ABORT);
938 if (!(c->flags & CHN_F_VIRTUAL))
940 missing = sndbuf_getready(bs);
942 c->flags &= ~CHN_F_ABORTING;
947 * this routine tries to flush the dma transfer. It is called
948 * on a close of a playback channel.
949 * first, if there is data in the buffer, but the dma has not yet
950 * begun, we need to start it.
951 * next, we wait for the play buffer to drain
952 * finally, we stop the dma.
954 * called from: dsp_close, not valid for record channels.
958 chn_flush(struct pcm_channel *c)
960 struct snd_dbuf *b = c->bufhard;
963 KASSERT(c->direction == PCMDIR_PLAY, ("chn_flush on bad channel"));
964 DEB(printf("chn_flush: c->flags 0x%08x\n", c->flags));
966 c->flags |= CHN_F_CLOSING;
968 c->flags &= ~CHN_F_TRIGGERED;
969 /* kill the channel */
970 chn_trigger(c, PCMTRIG_ABORT);
973 c->flags &= ~CHN_F_CLOSING;
978 snd_fmtvalid(uint32_t fmt, uint32_t *fmtlist)
982 for (i = 0; fmtlist[i] != 0; i++) {
983 if (fmt == fmtlist[i] ||
984 ((fmt & AFMT_PASSTHROUGH) &&
985 (AFMT_ENCODING(fmt) & fmtlist[i])))
992 static const struct {
993 char *name, *alias1, *alias2;
996 { "alaw", NULL, NULL, AFMT_A_LAW },
997 { "mulaw", NULL, NULL, AFMT_MU_LAW },
998 { "u8", "8", NULL, AFMT_U8 },
999 { "s8", NULL, NULL, AFMT_S8 },
1000 #if BYTE_ORDER == LITTLE_ENDIAN
1001 { "s16le", "s16", "16", AFMT_S16_LE },
1002 { "s16be", NULL, NULL, AFMT_S16_BE },
1004 { "s16le", NULL, NULL, AFMT_S16_LE },
1005 { "s16be", "s16", "16", AFMT_S16_BE },
1007 { "u16le", NULL, NULL, AFMT_U16_LE },
1008 { "u16be", NULL, NULL, AFMT_U16_BE },
1009 { "s24le", NULL, NULL, AFMT_S24_LE },
1010 { "s24be", NULL, NULL, AFMT_S24_BE },
1011 { "u24le", NULL, NULL, AFMT_U24_LE },
1012 { "u24be", NULL, NULL, AFMT_U24_BE },
1013 #if BYTE_ORDER == LITTLE_ENDIAN
1014 { "s32le", "s32", "32", AFMT_S32_LE },
1015 { "s32be", NULL, NULL, AFMT_S32_BE },
1017 { "s32le", NULL, NULL, AFMT_S32_LE },
1018 { "s32be", "s32", "32", AFMT_S32_BE },
1020 { "u32le", NULL, NULL, AFMT_U32_LE },
1021 { "u32be", NULL, NULL, AFMT_U32_BE },
1022 { "ac3", NULL, NULL, AFMT_AC3 },
1023 { NULL, NULL, NULL, 0 }
1026 static const struct {
1027 char *name, *alias1, *alias2;
1029 } matrix_id_tab[] = {
1030 { "1.0", "1", "mono", SND_CHN_MATRIX_1_0 },
1031 { "2.0", "2", "stereo", SND_CHN_MATRIX_2_0 },
1032 { "2.1", NULL, NULL, SND_CHN_MATRIX_2_1 },
1033 { "3.0", "3", NULL, SND_CHN_MATRIX_3_0 },
1034 { "4.0", "4", "quad", SND_CHN_MATRIX_4_0 },
1035 { "4.1", NULL, NULL, SND_CHN_MATRIX_4_1 },
1036 { "5.0", "5", NULL, SND_CHN_MATRIX_5_0 },
1037 { "5.1", "6", NULL, SND_CHN_MATRIX_5_1 },
1038 { "6.0", NULL, NULL, SND_CHN_MATRIX_6_0 },
1039 { "6.1", "7", NULL, SND_CHN_MATRIX_6_1 },
1040 { "7.1", "8", NULL, SND_CHN_MATRIX_7_1 },
1041 { NULL, NULL, NULL, SND_CHN_MATRIX_UNKNOWN }
1045 snd_str2afmt(const char *req)
1051 i = sscanf(req, "%5[^:]:%6s", b1, b2);
1054 if (strlen(req) != strlen(b1))
1056 strlcpy(b2, "2.0", sizeof(b2));
1057 } else if (i == 2) {
1058 if (strlen(req) != (strlen(b1) + 1 + strlen(b2)))
1064 matrix_id = SND_CHN_MATRIX_UNKNOWN;
1066 for (i = 0; afmt == 0 && afmt_tab[i].name != NULL; i++) {
1067 if (strcasecmp(afmt_tab[i].name, b1) == 0 ||
1068 (afmt_tab[i].alias1 != NULL &&
1069 strcasecmp(afmt_tab[i].alias1, b1) == 0) ||
1070 (afmt_tab[i].alias2 != NULL &&
1071 strcasecmp(afmt_tab[i].alias2, b1) == 0)) {
1072 afmt = afmt_tab[i].afmt;
1073 strlcpy(b1, afmt_tab[i].name, sizeof(b1));
1080 for (i = 0; matrix_id == SND_CHN_MATRIX_UNKNOWN &&
1081 matrix_id_tab[i].name != NULL; i++) {
1082 if (strcmp(matrix_id_tab[i].name, b2) == 0 ||
1083 (matrix_id_tab[i].alias1 != NULL &&
1084 strcmp(matrix_id_tab[i].alias1, b2) == 0) ||
1085 (matrix_id_tab[i].alias2 != NULL &&
1086 strcasecmp(matrix_id_tab[i].alias2, b2) == 0)) {
1087 matrix_id = matrix_id_tab[i].matrix_id;
1088 strlcpy(b2, matrix_id_tab[i].name, sizeof(b2));
1092 if (matrix_id == SND_CHN_MATRIX_UNKNOWN)
1096 printf("Parse OK: '%s' -> '%s:%s' %d\n", req, b1, b2,
1097 (int)(b2[0]) - '0' + (int)(b2[2]) - '0');
1100 return (SND_FORMAT(afmt, b2[0] - '0' + b2[2] - '0', b2[2] - '0'));
1104 snd_afmt2str(uint32_t afmt, char *buf, size_t len)
1106 uint32_t i, enc, ch, ext;
1107 char tmp[AFMTSTR_LEN];
1109 if (buf == NULL || len < AFMTSTR_LEN)
1113 bzero(tmp, sizeof(tmp));
1115 enc = AFMT_ENCODING(afmt);
1116 ch = AFMT_CHANNEL(afmt);
1117 ext = AFMT_EXTCHANNEL(afmt);
1119 for (i = 0; afmt_tab[i].name != NULL; i++) {
1120 if (enc == afmt_tab[i].afmt) {
1121 strlcpy(tmp, afmt_tab[i].name, sizeof(tmp));
1122 strlcat(tmp, ":", sizeof(tmp));
1127 if (strlen(tmp) == 0)
1130 for (i = 0; matrix_id_tab[i].name != NULL; i++) {
1131 if (ch == (matrix_id_tab[i].name[0] - '0' +
1132 matrix_id_tab[i].name[2] - '0') &&
1133 ext == (matrix_id_tab[i].name[2] - '0')) {
1134 strlcat(tmp, matrix_id_tab[i].name, sizeof(tmp));
1139 if (strlen(tmp) == 0)
1142 strlcpy(buf, tmp, len);
1144 return (snd_str2afmt(buf));
1148 chn_reset(struct pcm_channel *c, uint32_t fmt, uint32_t spd)
1154 c->flags &= CHN_F_RESET;
1159 c->flags |= (pcm_getflags(c->dev) & SD_F_BITPERFECT) ?
1160 CHN_F_BITPERFECT : 0;
1162 r = CHANNEL_RESET(c->methods, c->devinfo);
1163 if (r == 0 && fmt != 0 && spd != 0) {
1164 r = chn_setparam(c, fmt, spd);
1168 if (r == 0 && fmt != 0)
1169 r = chn_setformat(c, fmt);
1170 if (r == 0 && spd != 0)
1171 r = chn_setspeed(c, spd);
1173 r = chn_setlatency(c, chn_latency);
1176 r = CHANNEL_RESETDONE(c->methods, c->devinfo);
1182 chn_init(struct pcm_channel *c, void *devinfo, int dir, int direction)
1184 struct feeder_class *fc;
1185 struct snd_dbuf *b, *bs;
1188 if (chn_timeout < CHN_TIMEOUT_MIN || chn_timeout > CHN_TIMEOUT_MAX)
1189 chn_timeout = CHN_TIMEOUT;
1191 chn_lockinit(c, dir);
1195 CHN_INIT(c, children);
1196 CHN_INIT(c, children.busy);
1203 b = sndbuf_create(c->dev, c->name, "primary", c);
1206 bs = sndbuf_create(c->dev, c->name, "secondary", c);
1213 fc = feeder_getclass(NULL);
1216 if (chn_addfeeder(c, fc, NULL))
1220 * XXX - sndbuf_setup() & sndbuf_resize() expect to be called
1221 * with the channel unlocked because they are also called
1222 * from driver methods that don't know about locking
1225 sndbuf_setup(bs, NULL, 0);
1232 c->format = SND_FORMAT(AFMT_U8, 1, 0);
1233 c->speed = DSP_DEFAULT_SPEED;
1235 c->matrix = *feeder_matrix_id_map(SND_CHN_MATRIX_1_0);
1236 c->matrix.id = SND_CHN_MATRIX_PCMCHANNEL;
1238 for (i = 0; i < SND_CHN_T_MAX; i++) {
1239 c->volume[SND_VOL_C_MASTER][i] = SND_VOL_0DB_MASTER;
1242 c->volume[SND_VOL_C_MASTER][SND_CHN_T_VOL_0DB] = SND_VOL_0DB_MASTER;
1243 c->volume[SND_VOL_C_PCM][SND_CHN_T_VOL_0DB] = chn_vol_0db_pcm;
1245 chn_vpc_reset(c, SND_VOL_C_PCM, 1);
1248 CHN_UNLOCK(c); /* XXX - Unlock for CHANNEL_INIT() malloc() call */
1249 c->devinfo = CHANNEL_INIT(c->methods, devinfo, b, c, direction);
1251 if (c->devinfo == NULL)
1255 if ((sndbuf_getsize(b) == 0) && ((c->flags & CHN_F_VIRTUAL) == 0))
1259 c->direction = direction;
1261 sndbuf_setfmt(b, c->format);
1262 sndbuf_setspd(b, c->speed);
1263 sndbuf_setfmt(bs, c->format);
1264 sndbuf_setspd(bs, c->speed);
1267 * @todo Should this be moved somewhere else? The primary buffer
1268 * is allocated by the driver or via DMA map setup, and tmpbuf
1269 * seems to only come into existence in sndbuf_resize().
1271 if (c->direction == PCMDIR_PLAY) {
1272 bs->sl = sndbuf_getmaxsize(bs);
1273 bs->shadbuf = malloc(bs->sl, M_DEVBUF, M_NOWAIT);
1274 if (bs->shadbuf == NULL) {
1284 if (CHANNEL_FREE(c->methods, c->devinfo))
1292 c->flags |= CHN_F_DEAD;
1302 chn_kill(struct pcm_channel *c)
1304 struct snd_dbuf *b = c->bufhard;
1305 struct snd_dbuf *bs = c->bufsoft;
1307 if (CHN_STARTED(c)) {
1309 chn_trigger(c, PCMTRIG_ABORT);
1312 while (chn_removefeeder(c) == 0)
1314 if (CHANNEL_FREE(c->methods, c->devinfo))
1319 c->flags |= CHN_F_DEAD;
1325 /* XXX Obsolete. Use *_matrix() variant instead. */
1327 chn_setvolume(struct pcm_channel *c, int left, int right)
1331 ret = chn_setvolume_matrix(c, SND_VOL_C_MASTER, SND_CHN_T_FL, left);
1332 ret |= chn_setvolume_matrix(c, SND_VOL_C_MASTER, SND_CHN_T_FR,
1339 chn_setvolume_multi(struct pcm_channel *c, int vc, int left, int right,
1346 for (i = 0; i < SND_CHN_T_MAX; i++) {
1347 if ((1 << i) & SND_CHN_LEFT_MASK)
1348 ret |= chn_setvolume_matrix(c, vc, i, left);
1349 else if ((1 << i) & SND_CHN_RIGHT_MASK)
1350 ret |= chn_setvolume_matrix(c, vc, i, right) << 8;
1352 ret |= chn_setvolume_matrix(c, vc, i, center) << 16;
1359 chn_setvolume_matrix(struct pcm_channel *c, int vc, int vt, int val)
1363 KASSERT(c != NULL && vc >= SND_VOL_C_MASTER && vc < SND_VOL_C_MAX &&
1364 (vc == SND_VOL_C_MASTER || (vc & 1)) &&
1365 (vt == SND_CHN_T_VOL_0DB || (vt >= SND_CHN_T_BEGIN &&
1366 vt <= SND_CHN_T_END)) && (vt != SND_CHN_T_VOL_0DB ||
1367 (val >= SND_VOL_0DB_MIN && val <= SND_VOL_0DB_MAX)),
1368 ("%s(): invalid volume matrix c=%p vc=%d vt=%d val=%d",
1369 __func__, c, vc, vt, val));
1377 c->volume[vc][vt] = val;
1380 * Do relative calculation here and store it into class + 1
1381 * to ease the job of feeder_volume.
1383 if (vc == SND_VOL_C_MASTER) {
1384 for (vc = SND_VOL_C_BEGIN; vc <= SND_VOL_C_END;
1385 vc += SND_VOL_C_STEP)
1386 c->volume[SND_VOL_C_VAL(vc)][vt] =
1387 SND_VOL_CALC_VAL(c->volume, vc, vt);
1388 } else if (vc & 1) {
1389 if (vt == SND_CHN_T_VOL_0DB)
1390 for (i = SND_CHN_T_BEGIN; i <= SND_CHN_T_END;
1391 i += SND_CHN_T_STEP) {
1392 c->volume[SND_VOL_C_VAL(vc)][i] =
1393 SND_VOL_CALC_VAL(c->volume, vc, i);
1396 c->volume[SND_VOL_C_VAL(vc)][vt] =
1397 SND_VOL_CALC_VAL(c->volume, vc, vt);
1404 chn_getvolume_matrix(struct pcm_channel *c, int vc, int vt)
1406 KASSERT(c != NULL && vc >= SND_VOL_C_MASTER && vc < SND_VOL_C_MAX &&
1407 (vt == SND_CHN_T_VOL_0DB ||
1408 (vt >= SND_CHN_T_BEGIN && vt <= SND_CHN_T_END)),
1409 ("%s(): invalid volume matrix c=%p vc=%d vt=%d",
1410 __func__, c, vc, vt));
1413 return (c->volume[vc][vt]);
1416 struct pcmchan_matrix *
1417 chn_getmatrix(struct pcm_channel *c)
1420 KASSERT(c != NULL, ("%s(): NULL channel", __func__));
1423 if (!(c->format & AFMT_CONVERTIBLE))
1426 return (&c->matrix);
1430 chn_setmatrix(struct pcm_channel *c, struct pcmchan_matrix *m)
1433 KASSERT(c != NULL && m != NULL,
1434 ("%s(): NULL channel or matrix", __func__));
1437 if (!(c->format & AFMT_CONVERTIBLE))
1441 c->matrix.id = SND_CHN_MATRIX_PCMCHANNEL;
1443 return (chn_setformat(c, SND_FORMAT(c->format, m->channels, m->ext)));
1447 * XXX chn_oss_* exists for the sake of compatibility.
1450 chn_oss_getorder(struct pcm_channel *c, unsigned long long *map)
1453 KASSERT(c != NULL && map != NULL,
1454 ("%s(): NULL channel or map", __func__));
1457 if (!(c->format & AFMT_CONVERTIBLE))
1460 return (feeder_matrix_oss_get_channel_order(&c->matrix, map));
1464 chn_oss_setorder(struct pcm_channel *c, unsigned long long *map)
1466 struct pcmchan_matrix m;
1469 KASSERT(c != NULL && map != NULL,
1470 ("%s(): NULL channel or map", __func__));
1473 if (!(c->format & AFMT_CONVERTIBLE))
1477 ret = feeder_matrix_oss_set_channel_order(&m, map);
1481 return (chn_setmatrix(c, &m));
1484 #define SND_CHN_OSS_FRONT (SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FR)
1485 #define SND_CHN_OSS_SURR (SND_CHN_T_MASK_SL | SND_CHN_T_MASK_SR)
1486 #define SND_CHN_OSS_CENTER_LFE (SND_CHN_T_MASK_FC | SND_CHN_T_MASK_LF)
1487 #define SND_CHN_OSS_REAR (SND_CHN_T_MASK_BL | SND_CHN_T_MASK_BR)
1490 chn_oss_getmask(struct pcm_channel *c, uint32_t *retmask)
1492 struct pcmchan_matrix *m;
1493 struct pcmchan_caps *caps;
1496 KASSERT(c != NULL && retmask != NULL,
1497 ("%s(): NULL channel or retmask", __func__));
1500 caps = chn_getcaps(c);
1501 if (caps == NULL || caps->fmtlist == NULL)
1504 for (i = 0; caps->fmtlist[i] != 0; i++) {
1505 format = caps->fmtlist[i];
1506 if (!(format & AFMT_CONVERTIBLE)) {
1507 *retmask |= DSP_BIND_SPDIF;
1510 m = CHANNEL_GETMATRIX(c->methods, c->devinfo, format);
1513 if (m->mask & SND_CHN_OSS_FRONT)
1514 *retmask |= DSP_BIND_FRONT;
1515 if (m->mask & SND_CHN_OSS_SURR)
1516 *retmask |= DSP_BIND_SURR;
1517 if (m->mask & SND_CHN_OSS_CENTER_LFE)
1518 *retmask |= DSP_BIND_CENTER_LFE;
1519 if (m->mask & SND_CHN_OSS_REAR)
1520 *retmask |= DSP_BIND_REAR;
1523 /* report software-supported binding mask */
1524 if (!CHN_BITPERFECT(c) && report_soft_matrix)
1525 *retmask |= DSP_BIND_FRONT | DSP_BIND_SURR |
1526 DSP_BIND_CENTER_LFE | DSP_BIND_REAR;
1532 chn_vpc_reset(struct pcm_channel *c, int vc, int force)
1536 KASSERT(c != NULL && vc >= SND_VOL_C_BEGIN && vc <= SND_VOL_C_END,
1537 ("%s(): invalid reset c=%p vc=%d", __func__, c, vc));
1540 if (force == 0 && chn_vpc_autoreset == 0)
1543 for (i = SND_CHN_T_BEGIN; i <= SND_CHN_T_END; i += SND_CHN_T_STEP)
1544 CHN_SETVOLUME(c, vc, i, c->volume[vc][SND_CHN_T_VOL_0DB]);
1548 round_pow2(u_int32_t v)
1557 ret = 1 << (ret - 1);
1564 round_blksz(u_int32_t v, int round)
1571 ret = min(round_pow2(v), CHN_2NDBUFMAXSIZE >> 1);
1573 if (ret > v && (ret >> 1) > 0 && (ret >> 1) >= ((v * 3) >> 2))
1576 tmp = ret - (ret % round);
1577 while (tmp < 16 || tmp < round) {
1579 tmp = ret - (ret % round);
1586 * 4Front call it DSP Policy, while we call it "Latency Profile". The idea
1587 * is to keep 2nd buffer short so that it doesn't cause long queue during
1590 * Latency reference table for 48khz stereo 16bit: (PLAY)
1592 * +---------+------------+-----------+------------+
1593 * | Latency | Blockcount | Blocksize | Buffersize |
1594 * +---------+------------+-----------+------------+
1595 * | 0 | 2 | 64 | 128 |
1596 * +---------+------------+-----------+------------+
1597 * | 1 | 4 | 128 | 512 |
1598 * +---------+------------+-----------+------------+
1599 * | 2 | 8 | 512 | 4096 |
1600 * +---------+------------+-----------+------------+
1601 * | 3 | 16 | 512 | 8192 |
1602 * +---------+------------+-----------+------------+
1603 * | 4 | 32 | 512 | 16384 |
1604 * +---------+------------+-----------+------------+
1605 * | 5 | 32 | 1024 | 32768 |
1606 * +---------+------------+-----------+------------+
1607 * | 6 | 16 | 2048 | 32768 |
1608 * +---------+------------+-----------+------------+
1609 * | 7 | 8 | 4096 | 32768 |
1610 * +---------+------------+-----------+------------+
1611 * | 8 | 4 | 8192 | 32768 |
1612 * +---------+------------+-----------+------------+
1613 * | 9 | 2 | 16384 | 32768 |
1614 * +---------+------------+-----------+------------+
1615 * | 10 | 2 | 32768 | 65536 |
1616 * +---------+------------+-----------+------------+
1618 * Recording need a different reference table. All we care is
1619 * gobbling up everything within reasonable buffering threshold.
1621 * Latency reference table for 48khz stereo 16bit: (REC)
1623 * +---------+------------+-----------+------------+
1624 * | Latency | Blockcount | Blocksize | Buffersize |
1625 * +---------+------------+-----------+------------+
1626 * | 0 | 512 | 32 | 16384 |
1627 * +---------+------------+-----------+------------+
1628 * | 1 | 256 | 64 | 16384 |
1629 * +---------+------------+-----------+------------+
1630 * | 2 | 128 | 128 | 16384 |
1631 * +---------+------------+-----------+------------+
1632 * | 3 | 64 | 256 | 16384 |
1633 * +---------+------------+-----------+------------+
1634 * | 4 | 32 | 512 | 16384 |
1635 * +---------+------------+-----------+------------+
1636 * | 5 | 32 | 1024 | 32768 |
1637 * +---------+------------+-----------+------------+
1638 * | 6 | 16 | 2048 | 32768 |
1639 * +---------+------------+-----------+------------+
1640 * | 7 | 8 | 4096 | 32768 |
1641 * +---------+------------+-----------+------------+
1642 * | 8 | 4 | 8192 | 32768 |
1643 * +---------+------------+-----------+------------+
1644 * | 9 | 2 | 16384 | 32768 |
1645 * +---------+------------+-----------+------------+
1646 * | 10 | 2 | 32768 | 65536 |
1647 * +---------+------------+-----------+------------+
1649 * Calculations for other data rate are entirely based on these reference
1650 * tables. For normal operation, Latency 5 seems give the best, well
1651 * balanced performance for typical workload. Anything below 5 will
1652 * eat up CPU to keep up with increasing context switches because of
1653 * shorter buffer space and usually require the application to handle it
1654 * aggresively through possibly real time programming technique.
1657 #define CHN_LATENCY_PBLKCNT_REF \
1658 {{1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1}, \
1659 {1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1}}
1660 #define CHN_LATENCY_PBUFSZ_REF \
1661 {{7, 9, 12, 13, 14, 15, 15, 15, 15, 15, 16}, \
1662 {11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 17}}
1664 #define CHN_LATENCY_RBLKCNT_REF \
1665 {{9, 8, 7, 6, 5, 5, 4, 3, 2, 1, 1}, \
1666 {9, 8, 7, 6, 5, 5, 4, 3, 2, 1, 1}}
1667 #define CHN_LATENCY_RBUFSZ_REF \
1668 {{14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16}, \
1669 {15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17}}
1671 #define CHN_LATENCY_DATA_REF 192000 /* 48khz stereo 16bit ~ 48000 x 2 x 2 */
1674 chn_calclatency(int dir, int latency, int bps, u_int32_t datarate,
1675 u_int32_t max, int *rblksz, int *rblkcnt)
1677 static int pblkcnts[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1678 CHN_LATENCY_PBLKCNT_REF;
1679 static int pbufszs[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1680 CHN_LATENCY_PBUFSZ_REF;
1681 static int rblkcnts[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1682 CHN_LATENCY_RBLKCNT_REF;
1683 static int rbufszs[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1684 CHN_LATENCY_RBUFSZ_REF;
1686 int lprofile, blksz, blkcnt;
1688 if (latency < CHN_LATENCY_MIN || latency > CHN_LATENCY_MAX ||
1689 bps < 1 || datarate < 1 ||
1690 !(dir == PCMDIR_PLAY || dir == PCMDIR_REC)) {
1692 *rblksz = CHN_2NDBUFMAXSIZE >> 1;
1693 if (rblkcnt != NULL)
1695 printf("%s(): FAILED dir=%d latency=%d bps=%d "
1696 "datarate=%u max=%u\n",
1697 __func__, dir, latency, bps, datarate, max);
1698 return CHN_2NDBUFMAXSIZE;
1701 lprofile = chn_latency_profile;
1703 if (dir == PCMDIR_PLAY) {
1704 blkcnt = pblkcnts[lprofile][latency];
1705 bufsz = pbufszs[lprofile][latency];
1707 blkcnt = rblkcnts[lprofile][latency];
1708 bufsz = rbufszs[lprofile][latency];
1711 bufsz = round_pow2(snd_xbytes(1 << bufsz, CHN_LATENCY_DATA_REF,
1715 blksz = round_blksz(bufsz >> blkcnt, bps);
1719 if (rblkcnt != NULL)
1720 *rblkcnt = 1 << blkcnt;
1722 return blksz << blkcnt;
1726 chn_resizebuf(struct pcm_channel *c, int latency,
1727 int blkcnt, int blksz)
1729 struct snd_dbuf *b, *bs, *pb;
1730 int sblksz, sblkcnt, hblksz, hblkcnt, limit = 1;
1735 if ((c->flags & (CHN_F_MMAP | CHN_F_TRIGGERED)) ||
1736 !(c->direction == PCMDIR_PLAY || c->direction == PCMDIR_REC))
1739 if (latency == -1) {
1741 latency = chn_latency;
1742 } else if (latency == -2) {
1743 latency = c->latency;
1744 if (latency < CHN_LATENCY_MIN || latency > CHN_LATENCY_MAX)
1745 latency = chn_latency;
1746 } else if (latency < CHN_LATENCY_MIN || latency > CHN_LATENCY_MAX)
1749 c->latency = latency;
1756 if (!(blksz == 0 || blkcnt == -1) &&
1757 (blksz < 16 || blksz < sndbuf_getalign(bs) || blkcnt < 2 ||
1758 (blksz * blkcnt) > CHN_2NDBUFMAXSIZE))
1761 chn_calclatency(c->direction, latency, sndbuf_getalign(bs),
1762 sndbuf_getalign(bs) * sndbuf_getspd(bs), CHN_2NDBUFMAXSIZE,
1765 if (blksz == 0 || blkcnt == -1) {
1767 c->flags &= ~CHN_F_HAS_SIZE;
1768 if (c->flags & CHN_F_HAS_SIZE) {
1769 blksz = sndbuf_getblksz(bs);
1770 blkcnt = sndbuf_getblkcnt(bs);
1773 c->flags |= CHN_F_HAS_SIZE;
1775 if (c->flags & CHN_F_HAS_SIZE) {
1777 * The application has requested their own blksz/blkcnt.
1778 * Just obey with it, and let them toast alone. We can
1779 * clamp it to the nearest latency profile, but that would
1780 * defeat the purpose of having custom control. The least
1781 * we can do is round it to the nearest ^2 and align it.
1783 sblksz = round_blksz(blksz, sndbuf_getalign(bs));
1784 sblkcnt = round_pow2(blkcnt);
1788 if (c->parentchannel != NULL) {
1789 pb = CHN_BUF_PARENT(c, NULL);
1791 CHN_LOCK(c->parentchannel);
1792 chn_notify(c->parentchannel, CHN_N_BLOCKSIZE);
1793 CHN_UNLOCK(c->parentchannel);
1795 limit = (limit != 0 && pb != NULL) ?
1796 sndbuf_xbytes(sndbuf_getsize(pb), pb, bs) : 0;
1797 c->timeout = c->parentchannel->timeout;
1800 if (c->flags & CHN_F_HAS_SIZE) {
1801 hblksz = round_blksz(sndbuf_xbytes(sblksz, bs, b),
1802 sndbuf_getalign(b));
1803 hblkcnt = round_pow2(sndbuf_getblkcnt(bs));
1805 chn_calclatency(c->direction, latency,
1807 sndbuf_getalign(b) * sndbuf_getspd(b),
1808 CHN_2NDBUFMAXSIZE, &hblksz, &hblkcnt);
1810 if ((hblksz << 1) > sndbuf_getmaxsize(b))
1811 hblksz = round_blksz(sndbuf_getmaxsize(b) >> 1,
1812 sndbuf_getalign(b));
1814 while ((hblksz * hblkcnt) > sndbuf_getmaxsize(b)) {
1821 hblksz -= hblksz % sndbuf_getalign(b);
1824 hblksz = sndbuf_getmaxsize(b) >> 1;
1825 hblksz -= hblksz % sndbuf_getalign(b);
1830 if (chn_usefrags == 0 ||
1831 CHANNEL_SETFRAGMENTS(c->methods, c->devinfo,
1832 hblksz, hblkcnt) != 0)
1833 sndbuf_setblksz(b, CHANNEL_SETBLOCKSIZE(c->methods,
1834 c->devinfo, hblksz));
1837 if (!CHN_EMPTY(c, children)) {
1838 sblksz = round_blksz(
1839 sndbuf_xbytes(sndbuf_getsize(b) >> 1, b, bs),
1840 sndbuf_getalign(bs));
1843 } else if (limit != 0)
1844 limit = sndbuf_xbytes(sndbuf_getsize(b), b, bs);
1849 c->timeout = ((u_int64_t)hz * sndbuf_getsize(b)) /
1850 ((u_int64_t)sndbuf_getspd(b) * sndbuf_getalign(b));
1855 if (limit > CHN_2NDBUFMAXSIZE)
1856 limit = CHN_2NDBUFMAXSIZE;
1859 while (limit > 0 && (sblksz * sblkcnt) > limit) {
1866 while ((sblksz * sblkcnt) < limit)
1869 while ((sblksz * sblkcnt) > CHN_2NDBUFMAXSIZE) {
1876 sblksz -= sblksz % sndbuf_getalign(bs);
1878 if (sndbuf_getblkcnt(bs) != sblkcnt || sndbuf_getblksz(bs) != sblksz ||
1879 sndbuf_getsize(bs) != (sblkcnt * sblksz)) {
1880 ret = sndbuf_remalloc(bs, sblkcnt, sblksz);
1882 device_printf(c->dev, "%s(): Failed: %d %d\n",
1883 __func__, sblkcnt, sblksz);
1889 * OSSv4 docs: "By default OSS will set the low water level equal
1890 * to the fragment size which is optimal in most cases."
1892 c->lw = sndbuf_getblksz(bs);
1895 if (snd_verbose > 3)
1896 device_printf(c->dev, "%s(): %s (%s) timeout=%u "
1897 "b[%d/%d/%d] bs[%d/%d/%d] limit=%d\n",
1898 __func__, CHN_DIRSTR(c),
1899 (c->flags & CHN_F_VIRTUAL) ? "virtual" : "hardware",
1901 sndbuf_getsize(b), sndbuf_getblksz(b),
1902 sndbuf_getblkcnt(b),
1903 sndbuf_getsize(bs), sndbuf_getblksz(bs),
1904 sndbuf_getblkcnt(bs), limit);
1910 chn_setlatency(struct pcm_channel *c, int latency)
1913 /* Destroy blksz/blkcnt, enforce latency profile. */
1914 return chn_resizebuf(c, latency, -1, 0);
1918 chn_setblocksize(struct pcm_channel *c, int blkcnt, int blksz)
1921 /* Destroy latency profile, enforce blksz/blkcnt */
1922 return chn_resizebuf(c, -1, blkcnt, blksz);
1926 chn_setparam(struct pcm_channel *c, uint32_t format, uint32_t speed)
1928 struct pcmchan_caps *caps;
1929 uint32_t hwspeed, delta;
1934 if (speed < 1 || format == 0 || CHN_STARTED(c))
1940 caps = chn_getcaps(c);
1943 RANGE(hwspeed, caps->minspeed, caps->maxspeed);
1945 sndbuf_setspd(c->bufhard, CHANNEL_SETSPEED(c->methods, c->devinfo,
1947 hwspeed = sndbuf_getspd(c->bufhard);
1949 delta = (hwspeed > speed) ? (hwspeed - speed) : (speed - hwspeed);
1951 if (delta <= feeder_rate_round)
1954 ret = feeder_chain(c);
1957 ret = CHANNEL_SETFORMAT(c->methods, c->devinfo,
1958 sndbuf_getfmt(c->bufhard));
1961 ret = chn_resizebuf(c, -2, 0, 0);
1967 chn_setspeed(struct pcm_channel *c, uint32_t speed)
1969 uint32_t oldformat, oldspeed, format;
1974 if (c->format & AFMT_PASSTHROUGH)
1975 speed = AFMT_PASSTHROUGH_RATE;
1978 oldformat = c->format;
1979 oldspeed = c->speed;
1982 ret = chn_setparam(c, format, speed);
1984 if (snd_verbose > 3)
1985 device_printf(c->dev,
1986 "%s(): Setting speed %d failed, "
1987 "falling back to %d\n",
1988 __func__, speed, oldspeed);
1989 chn_setparam(c, c->format, oldspeed);
1996 chn_setformat(struct pcm_channel *c, uint32_t format)
1998 uint32_t oldformat, oldspeed, speed;
2001 /* XXX force stereo */
2002 if (format & AFMT_PASSTHROUGH)
2003 format = SND_FORMAT(format, AFMT_PASSTHROUGH_CHANNEL,
2004 AFMT_PASSTHROUGH_EXTCHANNEL);
2006 oldformat = c->format;
2007 oldspeed = c->speed;
2010 ret = chn_setparam(c, format, speed);
2012 if (snd_verbose > 3)
2013 device_printf(c->dev,
2014 "%s(): Format change 0x%08x failed, "
2015 "falling back to 0x%08x\n",
2016 __func__, format, oldformat);
2017 chn_setparam(c, oldformat, oldspeed);
2024 chn_syncstate(struct pcm_channel *c)
2026 struct snddev_info *d;
2027 struct snd_mixer *m;
2029 d = (c != NULL) ? c->parentsnddev : NULL;
2030 m = (d != NULL && d->mixer_dev != NULL) ? d->mixer_dev->si_drv1 :
2033 if (d == NULL || m == NULL)
2038 if (c->feederflags & (1 << FEEDER_VOLUME)) {
2040 int vol, pvol, left, right, center;
2042 if (c->direction == PCMDIR_PLAY &&
2043 (d->flags & SD_F_SOFTPCMVOL)) {
2044 /* CHN_UNLOCK(c); */
2045 vol = mix_get(m, SOUND_MIXER_PCM);
2046 parent = mix_getparent(m, SOUND_MIXER_PCM);
2047 if (parent != SOUND_MIXER_NONE)
2048 pvol = mix_get(m, parent);
2050 pvol = 100 | (100 << 8);
2053 vol = 100 | (100 << 8);
2058 device_printf(c->dev,
2059 "Soft PCM Volume: Failed to read pcm "
2061 vol = 100 | (100 << 8);
2065 device_printf(c->dev,
2066 "Soft PCM Volume: Failed to read parent "
2068 pvol = 100 | (100 << 8);
2071 left = ((vol & 0x7f) * (pvol & 0x7f)) / 100;
2072 right = (((vol >> 8) & 0x7f) * ((pvol >> 8) & 0x7f)) / 100;
2073 center = (left + right) >> 1;
2075 chn_setvolume_multi(c, SND_VOL_C_MASTER, left, right, center);
2078 if (c->feederflags & (1 << FEEDER_EQ)) {
2079 struct pcm_feeder *f;
2080 int treble, bass, state;
2082 /* CHN_UNLOCK(c); */
2083 treble = mix_get(m, SOUND_MIXER_TREBLE);
2084 bass = mix_get(m, SOUND_MIXER_BASS);
2090 treble = ((treble & 0x7f) +
2091 ((treble >> 8) & 0x7f)) >> 1;
2096 bass = ((bass & 0x7f) + ((bass >> 8) & 0x7f)) >> 1;
2098 f = chn_findfeeder(c, FEEDER_EQ);
2100 if (FEEDER_SET(f, FEEDEQ_TREBLE, treble) != 0)
2101 device_printf(c->dev,
2102 "EQ: Failed to set treble -- %d\n",
2104 if (FEEDER_SET(f, FEEDEQ_BASS, bass) != 0)
2105 device_printf(c->dev,
2106 "EQ: Failed to set bass -- %d\n",
2108 if (FEEDER_SET(f, FEEDEQ_PREAMP, d->eqpreamp) != 0)
2109 device_printf(c->dev,
2110 "EQ: Failed to set preamp -- %d\n",
2112 if (d->flags & SD_F_EQ_BYPASSED)
2113 state = FEEDEQ_BYPASS;
2114 else if (d->flags & SD_F_EQ_ENABLED)
2115 state = FEEDEQ_ENABLE;
2117 state = FEEDEQ_DISABLE;
2118 if (FEEDER_SET(f, FEEDEQ_STATE, state) != 0)
2119 device_printf(c->dev,
2120 "EQ: Failed to set state -- %d\n", state);
2126 chn_trigger(struct pcm_channel *c, int go)
2129 struct snd_dbuf *b = c->bufhard;
2131 struct snddev_info *d = c->parentsnddev;
2136 if (SND_DMA(b) && (go == PCMTRIG_EMLDMAWR || go == PCMTRIG_EMLDMARD))
2137 sndbuf_dmabounce(b);
2139 if (!PCMTRIG_COMMON(go))
2140 return (CHANNEL_TRIGGER(c->methods, c->devinfo, go));
2142 if (go == c->trigger)
2145 ret = CHANNEL_TRIGGER(c->methods, c->devinfo, go);
2151 if (snd_verbose > 3)
2152 device_printf(c->dev,
2153 "%s() %s: calling go=0x%08x , "
2154 "prev=0x%08x\n", __func__, c->name, go,
2156 if (c->trigger != PCMTRIG_START) {
2160 CHN_INSERT_HEAD(d, c, channels.pcm.busy);
2168 if (snd_verbose > 3)
2169 device_printf(c->dev,
2170 "%s() %s: calling go=0x%08x , "
2171 "prev=0x%08x\n", __func__, c->name, go,
2173 if (c->trigger == PCMTRIG_START) {
2177 CHN_REMOVE(d, c, channels.pcm.busy);
2190 * @brief Queries sound driver for sample-aligned hardware buffer pointer index
2192 * This function obtains the hardware pointer location, then aligns it to
2193 * the current bytes-per-sample value before returning. (E.g., a channel
2194 * running in 16 bit stereo mode would require 4 bytes per sample, so a
2195 * hwptr value ranging from 32-35 would be returned as 32.)
2197 * @param c PCM channel context
2198 * @returns sample-aligned hardware buffer pointer index
2201 chn_getptr(struct pcm_channel *c)
2206 hwptr = (CHN_STARTED(c)) ? CHANNEL_GETPTR(c->methods, c->devinfo) : 0;
2207 return (hwptr - (hwptr % sndbuf_getalign(c->bufhard)));
2210 struct pcmchan_caps *
2211 chn_getcaps(struct pcm_channel *c)
2214 return CHANNEL_GETCAPS(c->methods, c->devinfo);
2218 chn_getformats(struct pcm_channel *c)
2220 u_int32_t *fmtlist, fmts;
2223 fmtlist = chn_getcaps(c)->fmtlist;
2225 for (i = 0; fmtlist[i]; i++)
2228 /* report software-supported formats */
2229 if (!CHN_BITPERFECT(c) && report_soft_formats)
2230 fmts |= AFMT_CONVERTIBLE;
2232 return (AFMT_ENCODING(fmts));
2236 chn_notify(struct pcm_channel *c, u_int32_t flags)
2238 struct pcm_channel *ch;
2239 struct pcmchan_caps *caps;
2240 uint32_t bestformat, bestspeed, besthwformat, *vchanformat, *vchanrate;
2242 int dirty, err, run, nrun;
2246 if (CHN_EMPTY(c, children))
2252 * If the hwchan is running, we can't change its rate, format or
2255 run = (CHN_STARTED(c)) ? 1 : 0;
2257 flags &= CHN_N_VOLUME | CHN_N_TRIGGER;
2259 if (flags & CHN_N_RATE) {
2261 * XXX I'll make good use of this someday.
2262 * However this is currently being superseded by
2263 * the availability of CHN_F_VCHAN_DYNAMIC.
2267 if (flags & CHN_N_FORMAT) {
2269 * XXX I'll make good use of this someday.
2270 * However this is currently being superseded by
2271 * the availability of CHN_F_VCHAN_DYNAMIC.
2275 if (flags & CHN_N_VOLUME) {
2277 * XXX I'll make good use of this someday, though
2278 * soft volume control is currently pretty much
2283 if (flags & CHN_N_BLOCKSIZE) {
2285 * Set to default latency profile
2287 chn_setlatency(c, chn_latency);
2290 if ((flags & CHN_N_TRIGGER) && !(c->flags & CHN_F_VCHAN_DYNAMIC)) {
2291 nrun = CHN_EMPTY(c, children.busy) ? 0 : 1;
2293 err = chn_start(c, 1);
2296 flags &= ~CHN_N_TRIGGER;
2299 if (flags & CHN_N_TRIGGER) {
2300 if (c->direction == PCMDIR_PLAY) {
2301 vchanformat = &c->parentsnddev->pvchanformat;
2302 vchanrate = &c->parentsnddev->pvchanrate;
2304 vchanformat = &c->parentsnddev->rvchanformat;
2305 vchanrate = &c->parentsnddev->rvchanrate;
2308 /* Dynamic Virtual Channel */
2309 if (!(c->flags & CHN_F_VCHAN_ADAPTIVE)) {
2310 bestformat = *vchanformat;
2311 bestspeed = *vchanrate;
2319 caps = chn_getcaps(c);
2323 CHN_FOREACH(ch, c, children.busy) {
2325 if ((ch->format & AFMT_PASSTHROUGH) &&
2326 snd_fmtvalid(ch->format, caps->fmtlist)) {
2327 bestformat = ch->format;
2328 bestspeed = ch->speed;
2330 vpflags = CHN_F_PASSTHROUGH;
2334 if ((ch->flags & CHN_F_EXCLUSIVE) && vpflags == 0) {
2335 if (c->flags & CHN_F_VCHAN_ADAPTIVE) {
2336 bestspeed = ch->speed;
2337 RANGE(bestspeed, caps->minspeed,
2339 besthwformat = snd_fmtbest(ch->format,
2341 if (besthwformat != 0)
2342 bestformat = besthwformat;
2345 vpflags = CHN_F_EXCLUSIVE;
2349 if (!(c->flags & CHN_F_VCHAN_ADAPTIVE) ||
2355 if (ch->speed > bestspeed) {
2356 bestspeed = ch->speed;
2357 RANGE(bestspeed, caps->minspeed,
2360 besthwformat = snd_fmtbest(ch->format, caps->fmtlist);
2361 if (!(besthwformat & AFMT_VCHAN)) {
2366 if (AFMT_CHANNEL(besthwformat) >
2367 AFMT_CHANNEL(bestformat))
2368 bestformat = besthwformat;
2369 else if (AFMT_CHANNEL(besthwformat) ==
2370 AFMT_CHANNEL(bestformat) &&
2371 AFMT_BIT(besthwformat) > AFMT_BIT(bestformat))
2372 bestformat = besthwformat;
2377 if (bestformat == 0)
2378 bestformat = c->format;
2380 bestspeed = c->speed;
2382 if (bestformat != c->format || bestspeed != c->speed)
2385 c->flags &= ~(CHN_F_PASSTHROUGH | CHN_F_EXCLUSIVE);
2386 c->flags |= vpflags;
2390 bestspeed = CHANNEL_SETSPEED(c->methods,
2391 c->devinfo, bestspeed);
2392 err = chn_reset(c, bestformat, bestspeed);
2394 if (err == 0 && dirty) {
2395 CHN_FOREACH(ch, c, children.busy) {
2397 if (VCHAN_SYNC_REQUIRED(ch))
2404 c->flags |= CHN_F_DIRTY;
2405 err = chn_start(c, 1);
2409 if (nrun && run && dirty) {
2411 bestspeed = CHANNEL_SETSPEED(c->methods, c->devinfo,
2413 err = chn_reset(c, bestformat, bestspeed);
2415 CHN_FOREACH(ch, c, children.busy) {
2417 if (VCHAN_SYNC_REQUIRED(ch))
2423 c->flags |= CHN_F_DIRTY;
2424 err = chn_start(c, 1);
2428 if (err == 0 && !(bestformat & AFMT_PASSTHROUGH) &&
2429 (bestformat & AFMT_VCHAN)) {
2430 *vchanformat = bestformat;
2431 *vchanrate = bestspeed;
2435 c->flags &= ~(CHN_F_PASSTHROUGH | CHN_F_EXCLUSIVE);
2436 bestformat = *vchanformat;
2437 bestspeed = *vchanrate;
2439 if (c->format != bestformat || c->speed != bestspeed)
2440 chn_reset(c, bestformat, bestspeed);
2448 * @brief Fetch array of supported discrete sample rates
2450 * Wrapper for CHANNEL_GETRATES. Please see channel_if.m:getrates() for
2451 * detailed information.
2453 * @note If the operation isn't supported, this function will just return 0
2454 * (no rates in the array), and *rates will be set to NULL. Callers
2455 * should examine rates @b only if this function returns non-zero.
2457 * @param c pcm channel to examine
2458 * @param rates pointer to array of integers; rate table will be recorded here
2460 * @return number of rates in the array pointed to be @c rates
2463 chn_getrates(struct pcm_channel *c, int **rates)
2465 KASSERT(rates != NULL, ("rates is null"));
2467 return CHANNEL_GETRATES(c->methods, c->devinfo, rates);
2471 * @brief Remove channel from a sync group, if there is one.
2473 * This function is initially intended for the following conditions:
2474 * - Starting a syncgroup (@c SNDCTL_DSP_SYNCSTART ioctl)
2475 * - Closing a device. (A channel can't be destroyed if it's still in use.)
2477 * @note Before calling this function, the syncgroup list mutex must be
2478 * held. (Consider pcm_channel::sm protected by the SG list mutex
2479 * whether @c c is locked or not.)
2481 * @param c channel device to be started or closed
2482 * @returns If this channel was the only member of a group, the group ID
2483 * is returned to the caller so that the caller can release it
2484 * via free_unr() after giving up the syncgroup lock. Else it
2488 chn_syncdestroy(struct pcm_channel *c)
2490 struct pcmchan_syncmember *sm;
2491 struct pcmchan_syncgroup *sg;
2496 PCM_SG_LOCKASSERT(MA_OWNED);
2498 if (c->sm != NULL) {
2503 KASSERT(sg != NULL, ("syncmember has null parent"));
2505 SLIST_REMOVE(&sg->members, sm, pcmchan_syncmember, link);
2508 if (SLIST_EMPTY(&sg->members)) {
2509 SLIST_REMOVE(&snd_pcm_syncgroups, sg, pcmchan_syncgroup, link);
2518 #ifdef OSSV4_EXPERIMENT
2520 chn_getpeaks(struct pcm_channel *c, int *lpeak, int *rpeak)
2523 return CHANNEL_GETPEAKS(c->methods, c->devinfo, lpeak, rpeak);