af486a02a4a6f198199d321cd8535f7baff7128f
[dragonfly.git] / sys / dev / sound / usb / uaudio.c
1 /*      $NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $ */
2 /*      $FreeBSD: src/sys/dev/sound/usb/uaudio.c,v 1.14.2.2 2006/04/04 17:34:10 ariff Exp $ */
3 /*      $DragonFly: src/sys/dev/sound/usb/uaudio.c,v 1.20 2008/04/20 13:44:25 swildner Exp $: */
4
5 /*-
6  * Copyright (c) 1999 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *        This product includes software developed by the NetBSD
24  *        Foundation, Inc. and its contributors.
25  * 4. Neither the name of The NetBSD Foundation nor the names of its
26  *    contributors may be used to endorse or promote products derived
27  *    from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 /*
43  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
44  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
45  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
46  */
47
48 #include <sys/cdefs.h>
49
50 /*
51  * Also merged:
52  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
53  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
54  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
55  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
56  */
57
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/kernel.h>
61 #include <sys/malloc.h>
62 #include <sys/tty.h>
63 #include <sys/file.h>
64 #include <sys/reboot.h>         /* for bootverbose */
65 #include <sys/select.h>
66 #include <sys/proc.h>
67 #include <sys/module.h>
68 #include <sys/bus.h>
69 #include <sys/conf.h>
70 #include <sys/poll.h>
71 #include <sys/sysctl.h>
72 #include <sys/thread2.h>
73
74 #include <dev/sound/pcm/sound.h>        /* XXXXX */
75 #include <dev/sound/chip.h>
76 #include "feeder_if.h"
77
78 #include <bus/usb/usb.h>
79 #include <bus/usb/usbdi.h>
80 #include <bus/usb/usbdi_util.h>
81 #include <bus/usb/usb_quirks.h>
82
83 #include <dev/sound/usb/uaudioreg.h>
84 #include <dev/sound/usb/uaudio.h>
85
86 /* #define USB_DEBUG */
87 /* #define UAUDIO_MULTIPLE_ENDPOINTS */
88 #ifdef USB_DEBUG
89 #define DPRINTF(x)      do { if (uaudiodebug) kprintf x; } while (0)
90 #define DPRINTFN(n,x)   do { if (uaudiodebug>(n)) kprintf x; } while (0)
91 int     uaudiodebug = 0;
92 SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
93 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
94            &uaudiodebug, 0, "uaudio debug level");
95 #else
96 #define DPRINTF(x)
97 #define DPRINTFN(n,x)
98 #endif
99
100 #define UAUDIO_NCHANBUFS 6      /* number of outstanding request */
101 #define UAUDIO_NFRAMES   20     /* ms of sound in each request */
102
103
104 #define MIX_MAX_CHAN 8
105 struct mixerctl {
106         uint16_t        wValue[MIX_MAX_CHAN]; /* using nchan */
107         uint16_t        wIndex;
108         uint8_t         nchan;
109         uint8_t         type;
110 #define MIX_ON_OFF      1
111 #define MIX_SIGNED_16   2
112 #define MIX_UNSIGNED_16 3
113 #define MIX_SIGNED_8    4
114 #define MIX_SELECTOR    5
115 #define MIX_SIZE(n) ((n) == MIX_SIGNED_16 || (n) == MIX_UNSIGNED_16 ? 2 : 1)
116 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
117         int             minval, maxval;
118         u_int           delta;
119         u_int           mul;
120         unsigned        ctl;
121 #define MAX_SELECTOR_INPUT_PIN 256
122         uint8_t         slctrtype[MAX_SELECTOR_INPUT_PIN];
123         uint8_t         class;
124 };
125 #define MAKE(h,l) (((h) << 8) | (l))
126
127 struct as_info {
128         uint8_t         alt;
129         uint8_t         encoding;
130         uint8_t         attributes; /* Copy of bmAttributes of
131                                      * usb_audio_streaming_endpoint_descriptor
132                                      */
133         usbd_interface_handle   ifaceh;
134         const usb_interface_descriptor_t *idesc;
135         const usb_endpoint_descriptor_audio_t *edesc;
136         const usb_endpoint_descriptor_audio_t *edesc1;
137         const struct usb_audio_streaming_type1_descriptor *asf1desc;
138         int             sc_busy;        /* currently used */
139 };
140
141 struct chan {
142         struct pcm_channel *pcm_ch;
143         usbd_pipe_handle pipe;
144         usbd_pipe_handle sync_pipe;
145
146         u_int   sample_size;
147         u_int   sample_rate;
148         u_int   bytes_per_frame;
149         u_int   fraction;       /* fraction/1000 is the extra samples/frame */
150         u_int   residue;        /* accumulates the fractional samples */
151
152         u_char  *start;         /* upper layer buffer start */
153         u_char  *end;           /* upper layer buffer end */
154         u_char  *cur;           /* current position in upper layer buffer */
155         int     blksize;        /* chunk size to report up */
156         int     transferred;    /* transferred bytes not reported up */
157
158         int     altidx;         /* currently used altidx */
159
160         int     curchanbuf;
161         struct chanbuf {
162                 struct chan     *chan;
163                 usbd_xfer_handle xfer;
164                 u_char          *buffer;
165                 u_int16_t       sizes[UAUDIO_NFRAMES];
166                 u_int16_t       offsets[UAUDIO_NFRAMES];
167                 u_int16_t       size;
168         } chanbufs[UAUDIO_NCHANBUFS];
169
170         struct uaudio_softc *sc; /* our softc */
171         u_int32_t format;
172         int     precision;
173         int     channels;
174 };
175
176 struct uaudio_softc {
177         device_t        sc_dev;         /* base device */
178         usbd_device_handle sc_udev;     /* USB device */
179         int             sc_ac_iface;    /* Audio Control interface */
180         usbd_interface_handle   sc_ac_ifaceh;
181         struct chan     sc_playchan;    /* play channel */
182         struct chan     sc_recchan;     /* record channel */
183         int             sc_nullalt;
184         int             sc_audio_rev;
185         struct as_info  *sc_alts;       /* alternate settings */
186         int             sc_nalts;       /* # of alternate settings */
187         int             sc_altflags;
188 #define HAS_8           0x01
189 #define HAS_16          0x02
190 #define HAS_8U          0x04
191 #define HAS_ALAW        0x08
192 #define HAS_MULAW       0x10
193 #define UA_NOFRAC       0x20            /* don't do sample rate adjustment */
194 #define HAS_24          0x40
195 #define HAS_32          0x80
196         int             sc_mode;        /* play/record capability */
197         struct mixerctl *sc_ctls;       /* mixer controls */
198         int             sc_nctls;       /* # of mixer controls */
199         device_t        sc_audiodev;
200         char            sc_dying;
201         struct sbuf     uaudio_sndstat;
202         int             uaudio_sndstat_flag;
203 };
204
205 struct terminal_list {
206         int size;
207         uint16_t terminals[1];
208 };
209 #define TERMINAL_LIST_SIZE(N)   (offsetof(struct terminal_list, terminals) \
210                                 + sizeof(uint16_t) * (N))
211
212 struct io_terminal {
213         union {
214                 const usb_descriptor_t *desc;
215                 const struct usb_audio_input_terminal *it;
216                 const struct usb_audio_output_terminal *ot;
217                 const struct usb_audio_mixer_unit *mu;
218                 const struct usb_audio_selector_unit *su;
219                 const struct usb_audio_feature_unit *fu;
220                 const struct usb_audio_processing_unit *pu;
221                 const struct usb_audio_extension_unit *eu;
222         } d;
223         int inputs_size;
224         struct terminal_list **inputs; /* list of source input terminals */
225         struct terminal_list *output; /* list of destination output terminals */
226         int direct;             /* directly connected to an output terminal */
227 };
228
229 #define UAC_OUTPUT      0
230 #define UAC_INPUT       1
231 #define UAC_EQUAL       2
232 #define UAC_RECORD      3
233 #define UAC_NCLASSES    4
234 #ifdef USB_DEBUG
235 #define AudioCinputs    "inputs"
236 #define AudioCoutputs   "outputs"
237 #define AudioCrecord    "record"
238 #define AudioCequalization      "equalization"
239 static const char *uac_names[] = {
240         AudioCoutputs, AudioCinputs, AudioCequalization, AudioCrecord,
241 };
242 #endif
243
244 static usbd_status uaudio_identify_ac
245         (struct uaudio_softc *, const usb_config_descriptor_t *);
246 static usbd_status uaudio_identify_as
247         (struct uaudio_softc *, const usb_config_descriptor_t *);
248 static usbd_status uaudio_process_as
249         (struct uaudio_softc *, const char *, int *, int,
250          const usb_interface_descriptor_t *);
251
252 static void     uaudio_add_alt(struct uaudio_softc *, const struct as_info *);
253
254 static const usb_interface_descriptor_t *uaudio_find_iface
255         (const char *, int, int *, int);
256
257 static void     uaudio_mixer_add_ctl(struct uaudio_softc *, struct mixerctl *);
258
259 #ifdef USB_DEBUG
260 static void     uaudio_dump_cluster(const struct usb_audio_cluster *);
261 #endif
262 static struct usb_audio_cluster uaudio_get_cluster
263         (int, const struct io_terminal *);
264 static void     uaudio_add_input
265         (struct uaudio_softc *, const struct io_terminal *, int);
266 static void     uaudio_add_output
267         (struct uaudio_softc *, const struct io_terminal *, int);
268 static void     uaudio_add_mixer
269         (struct uaudio_softc *, const struct io_terminal *, int);
270 static void     uaudio_add_selector
271         (struct uaudio_softc *, const struct io_terminal *, int);
272 #ifdef USB_DEBUG
273 static const char *uaudio_get_terminal_name(int);
274 #endif
275 static int      uaudio_determine_class
276         (const struct io_terminal *, struct mixerctl *);
277 static int      uaudio_feature_name(const struct io_terminal *,
278                     struct mixerctl *);
279 static void     uaudio_add_feature
280         (struct uaudio_softc *, const struct io_terminal *, int);
281 static void     uaudio_add_processing_updown
282         (struct uaudio_softc *, const struct io_terminal *, int);
283 static void     uaudio_add_processing
284         (struct uaudio_softc *, const struct io_terminal *, int);
285 static void     uaudio_add_extension
286         (struct uaudio_softc *, const struct io_terminal *, int);
287 static struct terminal_list *uaudio_merge_terminal_list
288         (const struct io_terminal *);
289 static struct terminal_list *uaudio_io_terminaltype
290         (int, struct io_terminal *, int);
291 static usbd_status uaudio_identify
292         (struct uaudio_softc *, const usb_config_descriptor_t *);
293
294 static int      uaudio_signext(int, int);
295 static int      uaudio_bsd2value(struct mixerctl *, int);
296 static int      uaudio_get(struct uaudio_softc *, int, int, int, int, int);
297 static void     uaudio_set
298         (struct uaudio_softc *, int, int, int, int, int, int);
299 static void     uaudio_ctl_set
300         (struct uaudio_softc *, int, struct mixerctl *, int, int);
301
302 static usbd_status uaudio_set_speed(struct uaudio_softc *, int, u_int);
303
304 static usbd_status uaudio_chan_open(struct uaudio_softc *, struct chan *);
305 static void     uaudio_chan_close(struct uaudio_softc *, struct chan *);
306 static usbd_status uaudio_chan_alloc_buffers
307         (struct uaudio_softc *, struct chan *);
308 static void     uaudio_chan_free_buffers(struct uaudio_softc *, struct chan *);
309
310 static void     uaudio_chan_ptransfer(struct chan *);
311 static void     uaudio_chan_pintr
312         (usbd_xfer_handle, usbd_private_handle, usbd_status);
313
314 static void     uaudio_chan_rtransfer(struct chan *);
315 static void     uaudio_chan_rintr
316         (usbd_xfer_handle, usbd_private_handle, usbd_status);
317
318 static int      audio_attach_mi(device_t);
319 static int      uaudio_init_params(struct uaudio_softc * sc, struct chan *ch, int mode);
320 static int      uaudio_sndstat_prepare_pcm(struct sbuf *s, device_t dev, int verbose);
321
322 /* for NetBSD compatibility */
323 #define AUMODE_PLAY     0x01
324 #define AUMODE_RECORD   0x02
325
326 #define AUDIO_PROP_FULLDUPLEX   0x01
327
328 #define AUDIO_ENCODING_ULAW             1
329 #define AUDIO_ENCODING_ALAW             2
330 #define AUDIO_ENCODING_SLINEAR_LE       6
331 #define AUDIO_ENCODING_SLINEAR_BE       7
332 #define AUDIO_ENCODING_ULINEAR_LE       8
333 #define AUDIO_ENCODING_ULINEAR_BE       9
334
335 static device_probe_t uaudio_match;
336 static device_attach_t uaudio_attach;
337 static device_detach_t uaudio_detach;
338
339 static devclass_t uaudio_devclass;
340
341 static kobj_method_t uaudio_methods[] = {
342         DEVMETHOD(device_probe, uaudio_match),
343         DEVMETHOD(device_attach, uaudio_attach),
344         DEVMETHOD(device_detach, uaudio_detach),
345         DEVMETHOD(device_suspend, bus_generic_suspend),
346         DEVMETHOD(device_resume, bus_generic_resume),
347         DEVMETHOD(device_shutdown, bus_generic_shutdown),
348         DEVMETHOD(bus_print_child, bus_generic_print_child),
349         {0,0}
350 };
351
352 static driver_t uaudio_driver = {
353         "uaudio",
354         uaudio_methods,
355         sizeof(struct uaudio_softc)
356 };
357
358 MODULE_DEPEND(uaudio, usb, 1, 1, 1);
359
360 static int
361 uaudio_match(device_t self)
362 {
363         struct usb_attach_arg *uaa = device_get_ivars(self);
364         usb_interface_descriptor_t *id;
365
366         if (uaa->iface == NULL)
367                 return UMATCH_NONE;
368
369         id = usbd_get_interface_descriptor(uaa->iface);
370         /* Trigger on the control interface. */
371         if (id == NULL ||
372             id->bInterfaceClass != UICLASS_AUDIO ||
373             id->bInterfaceSubClass != UISUBCLASS_AUDIOCONTROL ||
374             (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_AUDIO))
375                 return UMATCH_NONE;
376
377         return UMATCH_IFACECLASS_IFACESUBCLASS;
378 }
379
380 static int
381 uaudio_attach(device_t self)
382 {
383         struct uaudio_softc *sc = device_get_softc(self);
384         struct usb_attach_arg *uaa = device_get_ivars(self);
385         usb_interface_descriptor_t *id;
386         usb_config_descriptor_t *cdesc;
387         char devinfo[1024];
388         usbd_status err;
389         int i, j, found;
390
391         usbd_devinfo(uaa->device, 0, devinfo);
392         sc->sc_dev = self;
393         device_set_desc_copy(self, devinfo);
394
395         sc->sc_udev = uaa->device;
396
397         cdesc = usbd_get_config_descriptor(sc->sc_udev);
398         if (cdesc == NULL) {
399                 kprintf("%s: failed to get configuration descriptor\n",
400                        device_get_nameunit(sc->sc_dev));
401                 return ENXIO;
402         }
403
404         err = uaudio_identify(sc, cdesc);
405         if (err) {
406                 kprintf("%s: audio descriptors make no sense, error=%d\n",
407                        device_get_nameunit(sc->sc_dev), err);
408                 return ENXIO;
409         }
410
411         sc->sc_ac_ifaceh = uaa->iface;
412         /* Pick up the AS interface. */
413         for (i = 0; i < uaa->nifaces; i++) {
414                 if (uaa->ifaces[i] == NULL)
415                         continue;
416                 id = usbd_get_interface_descriptor(uaa->ifaces[i]);
417                 if (id == NULL)
418                         continue;
419                 found = 0;
420                 for (j = 0; j < sc->sc_nalts; j++) {
421                         if (id->bInterfaceNumber ==
422                             sc->sc_alts[j].idesc->bInterfaceNumber) {
423                                 sc->sc_alts[j].ifaceh = uaa->ifaces[i];
424                                 found = 1;
425                         }
426                 }
427                 if (found)
428                         uaa->ifaces[i] = NULL;
429         }
430
431         for (j = 0; j < sc->sc_nalts; j++) {
432                 if (sc->sc_alts[j].ifaceh == NULL) {
433                         kprintf("%s: alt %d missing AS interface(s)\n",
434                             device_get_nameunit(sc->sc_dev), j);
435                         return ENXIO;
436                 }
437         }
438
439         kprintf("%s: audio rev %d.%02x\n", device_get_nameunit(sc->sc_dev),
440                sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff);
441
442         sc->sc_playchan.sc = sc->sc_recchan.sc = sc;
443         sc->sc_playchan.altidx = -1;
444         sc->sc_recchan.altidx = -1;
445
446         if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_FRAC)
447                 sc->sc_altflags |= UA_NOFRAC;
448
449 #ifndef USB_DEBUG
450         if (bootverbose)
451 #endif
452                 kprintf("%s: %d mixer controls\n", device_get_nameunit(sc->sc_dev),
453                     sc->sc_nctls);
454
455         DPRINTF(("uaudio_attach: doing audio_attach_mi\n"));
456         sc->sc_dying = 0;
457         if (audio_attach_mi(sc->sc_dev)) {
458                 kprintf("audio_attach_mi failed\n");
459                 return ENXIO;
460         }
461
462         return 0;
463 }
464
465 static int
466 uaudio_detach(device_t self)
467 {
468         struct uaudio_softc *sc = device_get_softc(self);
469
470         sbuf_delete(&(sc->uaudio_sndstat));
471         sc->uaudio_sndstat_flag = 0;
472
473         sc->sc_dying = 1;
474
475 #if 0 /* XXX */
476         /* Wait for outstanding requests to complete. */
477         usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
478 #endif
479
480         /* do nothing ? */
481         return bus_generic_detach(sc->sc_dev);
482 }
483
484 static const usb_interface_descriptor_t *
485 uaudio_find_iface(const char *buf, int size, int *offsp, int subtype)
486 {
487         const usb_interface_descriptor_t *d;
488
489         while (*offsp < size) {
490                 d = (const void *)(buf + *offsp);
491                 *offsp += d->bLength;
492                 if (d->bDescriptorType == UDESC_INTERFACE &&
493                     d->bInterfaceClass == UICLASS_AUDIO &&
494                     d->bInterfaceSubClass == subtype)
495                         return d;
496         }
497         return NULL;
498 }
499
500 static void
501 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct mixerctl *mc)
502 {
503         int res;
504         size_t len;
505         struct mixerctl *nmc;
506
507         if (mc->class < UAC_NCLASSES) {
508                 DPRINTF(("%s: adding %s.%d\n",
509                          __func__, uac_names[mc->class], mc->ctl));
510         } else {
511                 DPRINTF(("%s: adding %d\n", __func__, mc->ctl));
512         }
513
514         len = sizeof(*mc) * (sc->sc_nctls + 1);
515         nmc = kmalloc(len, M_USBDEV, M_NOWAIT);
516         if (nmc == NULL) {
517                 kprintf("uaudio_mixer_add_ctl: no memory\n");
518                 return;
519         }
520         /* Copy old data, if there was any */
521         if (sc->sc_nctls != 0) {
522                 memcpy(nmc, sc->sc_ctls, sizeof(*mc) * (sc->sc_nctls));
523                 kfree(sc->sc_ctls, M_USBDEV);
524         }
525         sc->sc_ctls = nmc;
526
527         mc->delta = 0;
528         if (mc->type == MIX_ON_OFF) {
529                 mc->minval = 0;
530                 mc->maxval = 1;
531         } else if (mc->type == MIX_SELECTOR) {
532                 ;
533         } else {
534                 /* Determine min and max values. */
535                 mc->minval = uaudio_signext(mc->type,
536                         uaudio_get(sc, GET_MIN, UT_READ_CLASS_INTERFACE,
537                                    mc->wValue[0], mc->wIndex,
538                                    MIX_SIZE(mc->type)));
539                 mc->maxval = 1 + uaudio_signext(mc->type,
540                         uaudio_get(sc, GET_MAX, UT_READ_CLASS_INTERFACE,
541                                    mc->wValue[0], mc->wIndex,
542                                    MIX_SIZE(mc->type)));
543                 mc->mul = mc->maxval - mc->minval;
544                 if (mc->mul == 0)
545                         mc->mul = 1;
546                 res = uaudio_get(sc, GET_RES, UT_READ_CLASS_INTERFACE,
547                                  mc->wValue[0], mc->wIndex,
548                                  MIX_SIZE(mc->type));
549                 if (res > 0)
550                         mc->delta = (res * 255 + mc->mul/2) / mc->mul;
551         }
552
553         sc->sc_ctls[sc->sc_nctls++] = *mc;
554
555 #ifdef USB_DEBUG
556         if (uaudiodebug > 2) {
557                 int i;
558                 DPRINTF(("uaudio_mixer_add_ctl: wValue=%04x",mc->wValue[0]));
559                 for (i = 1; i < mc->nchan; i++)
560                         DPRINTF((",%04x", mc->wValue[i]));
561                 DPRINTF((" wIndex=%04x type=%d ctl='%d' "
562                          "min=%d max=%d\n",
563                          mc->wIndex, mc->type, mc->ctl,
564                          mc->minval, mc->maxval));
565         }
566 #endif
567 }
568
569 #ifdef USB_DEBUG
570 static void
571 uaudio_dump_cluster(const struct usb_audio_cluster *cl)
572 {
573         static const char *channel_names[16] = {
574                 "LEFT", "RIGHT", "CENTER", "LFE",
575                 "LEFT_SURROUND", "RIGHT_SURROUND", "LEFT_CENTER", "RIGHT_CENTER",
576                 "SURROUND", "LEFT_SIDE", "RIGHT_SIDE", "TOP",
577                 "RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15",
578         };
579         int cc, i, first;
580
581         cc = UGETW(cl->wChannelConfig);
582         kprintf("cluster: bNrChannels=%u wChannelConfig=0x%.4x",
583                   cl->bNrChannels, cc);
584         first = TRUE;
585         for (i = 0; cc != 0; i++) {
586                 if (cc & 1) {
587                         kprintf("%c%s", first ? '<' : ',', channel_names[i]);
588                         first = FALSE;
589                 }
590                 cc = cc >> 1;
591         }
592         kprintf("> iChannelNames=%u", cl->iChannelNames);
593 }
594 #endif
595
596 static struct usb_audio_cluster
597 uaudio_get_cluster(int id, const struct io_terminal *iot)
598 {
599         struct usb_audio_cluster r;
600         const usb_descriptor_t *dp;
601         int i;
602
603         for (i = 0; i < 25; i++) { /* avoid infinite loops */
604                 dp = iot[id].d.desc;
605                 if (dp == 0)
606                         goto bad;
607                 switch (dp->bDescriptorSubtype) {
608                 case UDESCSUB_AC_INPUT:
609                         r.bNrChannels = iot[id].d.it->bNrChannels;
610                         USETW(r.wChannelConfig, UGETW(iot[id].d.it->wChannelConfig));
611                         r.iChannelNames = iot[id].d.it->iChannelNames;
612                         return r;
613                 case UDESCSUB_AC_OUTPUT:
614                         id = iot[id].d.ot->bSourceId;
615                         break;
616                 case UDESCSUB_AC_MIXER:
617                         r = *(const struct usb_audio_cluster *)
618                                 &iot[id].d.mu->baSourceId[iot[id].d.mu->bNrInPins];
619                         return r;
620                 case UDESCSUB_AC_SELECTOR:
621                         /* XXX This is not really right */
622                         id = iot[id].d.su->baSourceId[0];
623                         break;
624                 case UDESCSUB_AC_FEATURE:
625                         id = iot[id].d.fu->bSourceId;
626                         break;
627                 case UDESCSUB_AC_PROCESSING:
628                         r = *(const struct usb_audio_cluster *)
629                                 &iot[id].d.pu->baSourceId[iot[id].d.pu->bNrInPins];
630                         return r;
631                 case UDESCSUB_AC_EXTENSION:
632                         r = *(const struct usb_audio_cluster *)
633                                 &iot[id].d.eu->baSourceId[iot[id].d.eu->bNrInPins];
634                         return r;
635                 default:
636                         goto bad;
637                 }
638         }
639  bad:
640         kprintf("uaudio_get_cluster: bad data\n");
641         memset(&r, 0, sizeof r);
642         return r;
643
644 }
645
646 static void
647 uaudio_add_input(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
648 {
649 #ifdef USB_DEBUG
650         const struct usb_audio_input_terminal *d = iot[id].d.it;
651
652         DPRINTFN(2,("uaudio_add_input: bTerminalId=%d wTerminalType=0x%04x "
653                     "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
654                     "iChannelNames=%d iTerminal=%d\n",
655                     d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
656                     d->bNrChannels, UGETW(d->wChannelConfig),
657                     d->iChannelNames, d->iTerminal));
658 #endif
659 }
660
661 static void
662 uaudio_add_output(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
663 {
664 #ifdef USB_DEBUG
665         const struct usb_audio_output_terminal *d;
666
667         d = iot[id].d.ot;
668         DPRINTFN(2,("uaudio_add_output: bTerminalId=%d wTerminalType=0x%04x "
669                     "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
670                     d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
671                     d->bSourceId, d->iTerminal));
672 #endif
673 }
674
675 static void
676 uaudio_add_mixer(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
677 {
678         const struct usb_audio_mixer_unit *d = iot[id].d.mu;
679         const struct usb_audio_mixer_unit_1 *d1;
680         int c, chs, ichs, ochs, i, o, bno, p, mo, mc, k;
681         const uByte *bm;
682         struct mixerctl mix;
683
684         DPRINTFN(2,("uaudio_add_mixer: bUnitId=%d bNrInPins=%d\n",
685                     d->bUnitId, d->bNrInPins));
686
687         /* Compute the number of input channels */
688         ichs = 0;
689         for (i = 0; i < d->bNrInPins; i++)
690                 ichs += uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
691
692         /* and the number of output channels */
693         d1 = (const struct usb_audio_mixer_unit_1 *)&d->baSourceId[d->bNrInPins];
694         ochs = d1->bNrChannels;
695         DPRINTFN(2,("uaudio_add_mixer: ichs=%d ochs=%d\n", ichs, ochs));
696
697         bm = d1->bmControls;
698         mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
699         uaudio_determine_class(&iot[id], &mix);
700         mix.type = MIX_SIGNED_16;
701
702 #define BIT(bno) ((bm[bno / 8] >> (7 - bno % 8)) & 1)
703         for (p = i = 0; i < d->bNrInPins; i++) {
704                 chs = uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
705                 mc = 0;
706                 for (c = 0; c < chs; c++) {
707                         mo = 0;
708                         for (o = 0; o < ochs; o++) {
709                                 bno = (p + c) * ochs + o;
710                                 if (BIT(bno))
711                                         mo++;
712                         }
713                         if (mo == 1)
714                                 mc++;
715                 }
716                 if (mc == chs && chs <= MIX_MAX_CHAN) {
717                         k = 0;
718                         for (c = 0; c < chs; c++)
719                                 for (o = 0; o < ochs; o++) {
720                                         bno = (p + c) * ochs + o;
721                                         if (BIT(bno))
722                                                 mix.wValue[k++] =
723                                                         MAKE(p+c+1, o+1);
724                                 }
725
726                         mix.nchan = chs;
727                         uaudio_mixer_add_ctl(sc, &mix);
728                 } else {
729                         /* XXX */
730                 }
731 #undef BIT
732                 p += chs;
733         }
734
735 }
736
737 static void
738 uaudio_add_selector(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
739 {
740         const struct usb_audio_selector_unit *d;
741         struct mixerctl mix;
742         int i;
743         struct mixerctl dummy;
744
745         d = iot[id].d.su;
746         DPRINTFN(2,("uaudio_add_selector: bUnitId=%d bNrInPins=%d\n",
747                     d->bUnitId, d->bNrInPins));
748         mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
749         mix.wValue[0] = MAKE(0, 0);
750         uaudio_determine_class(&iot[id], &mix);
751         mix.nchan = 1;
752         mix.type = MIX_SELECTOR;
753         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
754         mix.minval = 1;
755         mix.maxval = d->bNrInPins;
756         mix.mul = mix.maxval - mix.minval;
757         for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
758                 mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
759         }
760         for (i = mix.minval; i <= mix.maxval; i++) {
761                 mix.slctrtype[i - 1] = uaudio_feature_name(&iot[d->baSourceId[i - 1]], &dummy);
762         }
763
764         uaudio_mixer_add_ctl(sc, &mix);
765 }
766
767 #ifdef USB_DEBUG
768 static const char *
769 uaudio_get_terminal_name(int terminal_type)
770 {
771         static char buf[100];
772
773         switch (terminal_type) {
774         /* USB terminal types */
775         case UAT_UNDEFINED:     return "UAT_UNDEFINED";
776         case UAT_STREAM:        return "UAT_STREAM";
777         case UAT_VENDOR:        return "UAT_VENDOR";
778         /* input terminal types */
779         case UATI_UNDEFINED:    return "UATI_UNDEFINED";
780         case UATI_MICROPHONE:   return "UATI_MICROPHONE";
781         case UATI_DESKMICROPHONE:       return "UATI_DESKMICROPHONE";
782         case UATI_PERSONALMICROPHONE:   return "UATI_PERSONALMICROPHONE";
783         case UATI_OMNIMICROPHONE:       return "UATI_OMNIMICROPHONE";
784         case UATI_MICROPHONEARRAY:      return "UATI_MICROPHONEARRAY";
785         case UATI_PROCMICROPHONEARR:    return "UATI_PROCMICROPHONEARR";
786         /* output terminal types */
787         case UATO_UNDEFINED:    return "UATO_UNDEFINED";
788         case UATO_SPEAKER:      return "UATO_SPEAKER";
789         case UATO_HEADPHONES:   return "UATO_HEADPHONES";
790         case UATO_DISPLAYAUDIO: return "UATO_DISPLAYAUDIO";
791         case UATO_DESKTOPSPEAKER:       return "UATO_DESKTOPSPEAKER";
792         case UATO_ROOMSPEAKER:  return "UATO_ROOMSPEAKER";
793         case UATO_COMMSPEAKER:  return "UATO_COMMSPEAKER";
794         case UATO_SUBWOOFER:    return "UATO_SUBWOOFER";
795         /* bidir terminal types */
796         case UATB_UNDEFINED:    return "UATB_UNDEFINED";
797         case UATB_HANDSET:      return "UATB_HANDSET";
798         case UATB_HEADSET:      return "UATB_HEADSET";
799         case UATB_SPEAKERPHONE: return "UATB_SPEAKERPHONE";
800         case UATB_SPEAKERPHONEESUP:     return "UATB_SPEAKERPHONEESUP";
801         case UATB_SPEAKERPHONEECANC:    return "UATB_SPEAKERPHONEECANC";
802         /* telephony terminal types */
803         case UATT_UNDEFINED:    return "UATT_UNDEFINED";
804         case UATT_PHONELINE:    return "UATT_PHONELINE";
805         case UATT_TELEPHONE:    return "UATT_TELEPHONE";
806         case UATT_DOWNLINEPHONE:        return "UATT_DOWNLINEPHONE";
807         /* external terminal types */
808         case UATE_UNDEFINED:    return "UATE_UNDEFINED";
809         case UATE_ANALOGCONN:   return "UATE_ANALOGCONN";
810         case UATE_LINECONN:     return "UATE_LINECONN";
811         case UATE_LEGACYCONN:   return "UATE_LEGACYCONN";
812         case UATE_DIGITALAUIFC: return "UATE_DIGITALAUIFC";
813         case UATE_SPDIF:        return "UATE_SPDIF";
814         case UATE_1394DA:       return "UATE_1394DA";
815         case UATE_1394DV:       return "UATE_1394DV";
816         /* embedded function terminal types */
817         case UATF_UNDEFINED:    return "UATF_UNDEFINED";
818         case UATF_CALIBNOISE:   return "UATF_CALIBNOISE";
819         case UATF_EQUNOISE:     return "UATF_EQUNOISE";
820         case UATF_CDPLAYER:     return "UATF_CDPLAYER";
821         case UATF_DAT:  return "UATF_DAT";
822         case UATF_DCC:  return "UATF_DCC";
823         case UATF_MINIDISK:     return "UATF_MINIDISK";
824         case UATF_ANALOGTAPE:   return "UATF_ANALOGTAPE";
825         case UATF_PHONOGRAPH:   return "UATF_PHONOGRAPH";
826         case UATF_VCRAUDIO:     return "UATF_VCRAUDIO";
827         case UATF_VIDEODISCAUDIO:       return "UATF_VIDEODISCAUDIO";
828         case UATF_DVDAUDIO:     return "UATF_DVDAUDIO";
829         case UATF_TVTUNERAUDIO: return "UATF_TVTUNERAUDIO";
830         case UATF_SATELLITE:    return "UATF_SATELLITE";
831         case UATF_CABLETUNER:   return "UATF_CABLETUNER";
832         case UATF_DSS:  return "UATF_DSS";
833         case UATF_RADIORECV:    return "UATF_RADIORECV";
834         case UATF_RADIOXMIT:    return "UATF_RADIOXMIT";
835         case UATF_MULTITRACK:   return "UATF_MULTITRACK";
836         case UATF_SYNTHESIZER:  return "UATF_SYNTHESIZER";
837         default:
838                 ksnprintf(buf, sizeof(buf), "unknown type (0x%.4x)", terminal_type);
839                 return buf;
840         }
841 }
842 #endif
843
844 static int
845 uaudio_determine_class(const struct io_terminal *iot, struct mixerctl *mix)
846 {
847         int terminal_type;
848
849         if (iot == NULL || iot->output == NULL) {
850                 mix->class = UAC_OUTPUT;
851                 return 0;
852         }
853         terminal_type = 0;
854         if (iot->output->size == 1)
855                 terminal_type = iot->output->terminals[0];
856         /*
857          * If the only output terminal is USB,
858          * the class is UAC_RECORD.
859          */
860         if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
861                 mix->class = UAC_RECORD;
862                 if (iot->inputs_size == 1
863                     && iot->inputs[0] != NULL
864                     && iot->inputs[0]->size == 1)
865                         return iot->inputs[0]->terminals[0];
866                 else
867                         return 0;
868         }
869         /*
870          * If the ultimate destination of the unit is just one output
871          * terminal and the unit is connected to the output terminal
872          * directly, the class is UAC_OUTPUT.
873          */
874         if (terminal_type != 0 && iot->direct) {
875                 mix->class = UAC_OUTPUT;
876                 return terminal_type;
877         }
878         /*
879          * If the unit is connected to just one input terminal,
880          * the class is UAC_INPUT.
881          */
882         if (iot->inputs_size == 1 && iot->inputs[0] != NULL
883             && iot->inputs[0]->size == 1) {
884                 mix->class = UAC_INPUT;
885                 return iot->inputs[0]->terminals[0];
886         }
887         /*
888          * Otherwise, the class is UAC_OUTPUT.
889          */
890         mix->class = UAC_OUTPUT;
891         return terminal_type;
892 }
893
894 static int 
895 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
896 {
897         int terminal_type;
898
899         terminal_type = uaudio_determine_class(iot, mix);
900         if (mix->class == UAC_RECORD && terminal_type == 0)
901                 return SOUND_MIXER_IMIX;
902         DPRINTF(("%s: terminal_type=%s\n", __func__,
903                  uaudio_get_terminal_name(terminal_type)));
904         switch (terminal_type) {
905         case UAT_STREAM:
906                 return SOUND_MIXER_PCM;
907
908         case UATI_MICROPHONE:
909         case UATI_DESKMICROPHONE:
910         case UATI_PERSONALMICROPHONE:
911         case UATI_OMNIMICROPHONE:
912         case UATI_MICROPHONEARRAY:
913         case UATI_PROCMICROPHONEARR:
914                 return SOUND_MIXER_MIC;
915
916         case UATO_SPEAKER:
917         case UATO_DESKTOPSPEAKER:
918         case UATO_ROOMSPEAKER:
919         case UATO_COMMSPEAKER:
920                 return SOUND_MIXER_SPEAKER;
921
922         case UATE_ANALOGCONN:
923         case UATE_LINECONN:
924         case UATE_LEGACYCONN:
925                 return SOUND_MIXER_LINE;
926
927         case UATE_DIGITALAUIFC:
928         case UATE_SPDIF:
929         case UATE_1394DA:
930         case UATE_1394DV:
931                 return SOUND_MIXER_ALTPCM;
932
933         case UATF_CDPLAYER:
934                 return SOUND_MIXER_CD;
935
936         case UATF_SYNTHESIZER:
937                 return SOUND_MIXER_SYNTH;
938
939         case UATF_VIDEODISCAUDIO:
940         case UATF_DVDAUDIO:
941         case UATF_TVTUNERAUDIO:
942                 return SOUND_MIXER_VIDEO;
943
944 /* telephony terminal types */
945         case UATT_UNDEFINED:
946         case UATT_PHONELINE:
947         case UATT_TELEPHONE:
948         case UATT_DOWNLINEPHONE:
949                 return SOUND_MIXER_PHONEIN;
950 /*              return SOUND_MIXER_PHONEOUT;*/
951
952         case UATF_RADIORECV:
953         case UATF_RADIOXMIT:
954                 return SOUND_MIXER_RADIO;
955
956         case UAT_UNDEFINED:
957         case UAT_VENDOR:
958         case UATI_UNDEFINED:
959 /* output terminal types */
960         case UATO_UNDEFINED:
961         case UATO_DISPLAYAUDIO:
962         case UATO_SUBWOOFER:
963         case UATO_HEADPHONES:
964 /* bidir terminal types */
965         case UATB_UNDEFINED:
966         case UATB_HANDSET:
967         case UATB_HEADSET:
968         case UATB_SPEAKERPHONE:
969         case UATB_SPEAKERPHONEESUP:
970         case UATB_SPEAKERPHONEECANC:
971 /* external terminal types */
972         case UATE_UNDEFINED:
973 /* embedded function terminal types */
974         case UATF_UNDEFINED:
975         case UATF_CALIBNOISE:
976         case UATF_EQUNOISE:
977         case UATF_DAT:
978         case UATF_DCC:
979         case UATF_MINIDISK:
980         case UATF_ANALOGTAPE:
981         case UATF_PHONOGRAPH:
982         case UATF_VCRAUDIO:
983         case UATF_SATELLITE:
984         case UATF_CABLETUNER:
985         case UATF_DSS:
986         case UATF_MULTITRACK:
987         case 0xffff:
988         default:
989                 DPRINTF(("%s: 'master' for 0x%.4x\n", __func__, terminal_type));
990                 return SOUND_MIXER_VOLUME;
991         }
992         return SOUND_MIXER_VOLUME;
993 }
994
995 static void
996 uaudio_add_feature(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
997 {
998         const struct usb_audio_feature_unit *d;
999         const uByte *ctls;
1000         int ctlsize;
1001         int nchan;
1002         u_int fumask, mmask, cmask;
1003         struct mixerctl mix;
1004         int chan, ctl, i, unit;
1005         int mixernumber;
1006
1007 #define GET(i) (ctls[(i)*ctlsize] | \
1008                 (ctlsize > 1 ? ctls[(i)*ctlsize+1] << 8 : 0))
1009         d = iot[id].d.fu;
1010         ctls = d->bmaControls;
1011         ctlsize = d->bControlSize;
1012         nchan = (d->bLength - 7) / ctlsize;
1013         mmask = GET(0);
1014         /* Figure out what we can control */
1015         for (cmask = 0, chan = 1; chan < nchan; chan++) {
1016                 DPRINTFN(9,("uaudio_add_feature: chan=%d mask=%x\n",
1017                             chan, GET(chan)));
1018                 cmask |= GET(chan);
1019         }
1020
1021         if (nchan > MIX_MAX_CHAN)
1022                 nchan = MIX_MAX_CHAN;
1023         unit = d->bUnitId;
1024         mix.wIndex = MAKE(unit, sc->sc_ac_iface);
1025         for (ctl = MUTE_CONTROL; ctl < LOUDNESS_CONTROL; ctl++) {
1026                 fumask = FU_MASK(ctl);
1027                 DPRINTFN(4,("uaudio_add_feature: ctl=%d fumask=0x%04x\n",
1028                             ctl, fumask));
1029                 if (mmask & fumask) {
1030                         mix.nchan = 1;
1031                         mix.wValue[0] = MAKE(ctl, 0);
1032                 } else if (cmask & fumask) {
1033                         mix.nchan = nchan - 1;
1034                         for (i = 1; i < nchan; i++) {
1035                                 if (GET(i) & fumask)
1036                                         mix.wValue[i-1] = MAKE(ctl, i);
1037                                 else
1038                                         mix.wValue[i-1] = -1;
1039                         }
1040                 } else {
1041                         continue;
1042                 }
1043 #undef GET
1044
1045                 mixernumber = uaudio_feature_name(&iot[id], &mix);
1046
1047                 switch (ctl) {
1048                 case MUTE_CONTROL:
1049                         mix.type = MIX_ON_OFF;
1050                         mix.ctl = SOUND_MIXER_NRDEVICES;
1051                         break;
1052                 case VOLUME_CONTROL:
1053                         mix.type = MIX_SIGNED_16;
1054                         mix.ctl = mixernumber;
1055                         break;
1056                 case BASS_CONTROL:
1057                         mix.type = MIX_SIGNED_8;
1058                         mix.ctl = SOUND_MIXER_BASS;
1059                         break;
1060                 case MID_CONTROL:
1061                         mix.type = MIX_SIGNED_8;
1062                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1063                         break;
1064                 case TREBLE_CONTROL:
1065                         mix.type = MIX_SIGNED_8;
1066                         mix.ctl = SOUND_MIXER_TREBLE;
1067                         break;
1068                 case GRAPHIC_EQUALIZER_CONTROL:
1069                         continue; /* XXX don't add anything */
1070                         break;
1071                 case AGC_CONTROL:
1072                         mix.type = MIX_ON_OFF;
1073                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1074                         break;
1075                 case DELAY_CONTROL:
1076                         mix.type = MIX_UNSIGNED_16;
1077                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1078                         break;
1079                 case BASS_BOOST_CONTROL:
1080                         mix.type = MIX_ON_OFF;
1081                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1082                         break;
1083                 case LOUDNESS_CONTROL:
1084                         mix.type = MIX_ON_OFF;
1085                         mix.ctl = SOUND_MIXER_LOUD;     /* Is this correct ? */
1086                         break;
1087                 }
1088                 uaudio_mixer_add_ctl(sc, &mix);
1089         }
1090 }
1091
1092 static void
1093 uaudio_add_processing_updown(struct uaudio_softc *sc,
1094                              const struct io_terminal *iot, int id)
1095 {
1096         const struct usb_audio_processing_unit *d;
1097         const struct usb_audio_processing_unit_1 *d1;
1098         const struct usb_audio_processing_unit_updown *ud;
1099         struct mixerctl mix;
1100         int i;
1101
1102         d = iot[id].d.pu;
1103         d1 = (const struct usb_audio_processing_unit_1 *)
1104                 &d->baSourceId[d->bNrInPins];
1105         ud = (const struct usb_audio_processing_unit_updown *)
1106                 &d1->bmControls[d1->bControlSize];
1107         DPRINTFN(2,("uaudio_add_processing_updown: bUnitId=%d bNrModes=%d\n",
1108                     d->bUnitId, ud->bNrModes));
1109
1110         if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
1111                 DPRINTF(("uaudio_add_processing_updown: no mode select\n"));
1112                 return;
1113         }
1114
1115         mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1116         mix.nchan = 1;
1117         mix.wValue[0] = MAKE(UD_MODE_SELECT_CONTROL, 0);
1118         uaudio_determine_class(&iot[id], &mix);
1119         mix.type = MIX_ON_OFF;  /* XXX */
1120
1121         for (i = 0; i < ud->bNrModes; i++) {
1122                 DPRINTFN(2,("uaudio_add_processing_updown: i=%d bm=0x%x\n",
1123                             i, UGETW(ud->waModes[i])));
1124                 /* XXX */
1125         }
1126         uaudio_mixer_add_ctl(sc, &mix);
1127 }
1128
1129 static void
1130 uaudio_add_processing(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1131 {
1132         const struct usb_audio_processing_unit *d;
1133         const struct usb_audio_processing_unit_1 *d1;
1134         int ptype;
1135         struct mixerctl mix;
1136
1137         d = iot[id].d.pu;
1138         d1 = (const struct usb_audio_processing_unit_1 *)
1139                 &d->baSourceId[d->bNrInPins];
1140         ptype = UGETW(d->wProcessType);
1141         DPRINTFN(2,("uaudio_add_processing: wProcessType=%d bUnitId=%d "
1142                     "bNrInPins=%d\n", ptype, d->bUnitId, d->bNrInPins));
1143
1144         if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
1145                 mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1146                 mix.nchan = 1;
1147                 mix.wValue[0] = MAKE(XX_ENABLE_CONTROL, 0);
1148                 uaudio_determine_class(&iot[id], &mix);
1149                 mix.type = MIX_ON_OFF;
1150                 uaudio_mixer_add_ctl(sc, &mix);
1151         }
1152
1153         switch(ptype) {
1154         case UPDOWNMIX_PROCESS:
1155                 uaudio_add_processing_updown(sc, iot, id);
1156                 break;
1157         case DOLBY_PROLOGIC_PROCESS:
1158         case P3D_STEREO_EXTENDER_PROCESS:
1159         case REVERBATION_PROCESS:
1160         case CHORUS_PROCESS:
1161         case DYN_RANGE_COMP_PROCESS:
1162         default:
1163 #ifdef USB_DEBUG
1164                 kprintf("uaudio_add_processing: unit %d, type=%d not impl.\n",
1165                        d->bUnitId, ptype);
1166 #endif
1167                 break;
1168         }
1169 }
1170
1171 static void
1172 uaudio_add_extension(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1173 {
1174         const struct usb_audio_extension_unit *d;
1175         const struct usb_audio_extension_unit_1 *d1;
1176         struct mixerctl mix;
1177
1178         d = iot[id].d.eu;
1179         d1 = (const struct usb_audio_extension_unit_1 *)
1180                 &d->baSourceId[d->bNrInPins];
1181         DPRINTFN(2,("uaudio_add_extension: bUnitId=%d bNrInPins=%d\n",
1182                     d->bUnitId, d->bNrInPins));
1183
1184         if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_XU)
1185                 return;
1186
1187         if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
1188                 mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1189                 mix.nchan = 1;
1190                 mix.wValue[0] = MAKE(UA_EXT_ENABLE, 0);
1191                 uaudio_determine_class(&iot[id], &mix);
1192                 mix.type = MIX_ON_OFF;
1193                 uaudio_mixer_add_ctl(sc, &mix);
1194         }
1195 }
1196
1197 static struct terminal_list*
1198 uaudio_merge_terminal_list(const struct io_terminal *iot)
1199 {
1200         struct terminal_list *tml;
1201         uint16_t *ptm;
1202         int i, len;
1203
1204         len = 0;
1205         if (iot->inputs == NULL)
1206                 return NULL;
1207         for (i = 0; i < iot->inputs_size; i++) {
1208                 if (iot->inputs[i] != NULL)
1209                         len += iot->inputs[i]->size;
1210         }
1211         tml = kmalloc(TERMINAL_LIST_SIZE(len), M_TEMP, M_NOWAIT);
1212         if (tml == NULL) {
1213                 kprintf("uaudio_merge_terminal_list: no memory\n");
1214                 return NULL;
1215         }
1216         tml->size = 0;
1217         ptm = tml->terminals;
1218         for (i = 0; i < iot->inputs_size; i++) {
1219                 if (iot->inputs[i] == NULL)
1220                         continue;
1221                 if (iot->inputs[i]->size > len)
1222                         break;
1223                 memcpy(ptm, iot->inputs[i]->terminals,
1224                        iot->inputs[i]->size * sizeof(uint16_t));
1225                 tml->size += iot->inputs[i]->size;
1226                 ptm += iot->inputs[i]->size;
1227                 len -= iot->inputs[i]->size;
1228         }
1229         return tml;
1230 }
1231
1232 static struct terminal_list *
1233 uaudio_io_terminaltype(int outtype, struct io_terminal *iot, int id)
1234 {
1235         struct terminal_list *tml;
1236         struct io_terminal *it;
1237         int src_id, i;
1238
1239         it = &iot[id];
1240         if (it->output != NULL) {
1241                 /* already has outtype? */
1242                 for (i = 0; i < it->output->size; i++)
1243                         if (it->output->terminals[i] == outtype)
1244                                 return uaudio_merge_terminal_list(it);
1245                 tml = kmalloc(TERMINAL_LIST_SIZE(it->output->size + 1),
1246                              M_TEMP, M_NOWAIT);
1247                 if (tml == NULL) {
1248                         kprintf("uaudio_io_terminaltype: no memory\n");
1249                         return uaudio_merge_terminal_list(it);
1250                 }
1251                 memcpy(tml, it->output, TERMINAL_LIST_SIZE(it->output->size));
1252                 tml->terminals[it->output->size] = outtype;
1253                 tml->size++;
1254                 kfree(it->output, M_TEMP);
1255                 it->output = tml;
1256                 if (it->inputs != NULL) {
1257                         for (i = 0; i < it->inputs_size; i++)
1258                                 if (it->inputs[i] != NULL)
1259                                         kfree(it->inputs[i], M_TEMP);
1260                         kfree(it->inputs, M_TEMP);
1261                 }
1262                 it->inputs_size = 0;
1263                 it->inputs = NULL;
1264         } else {                /* end `iot[id] != NULL' */
1265                 it->inputs_size = 0;
1266                 it->inputs = NULL;
1267                 it->output = kmalloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1268                 if (it->output == NULL) {
1269                         kprintf("uaudio_io_terminaltype: no memory\n");
1270                         return NULL;
1271                 }
1272                 it->output->terminals[0] = outtype;
1273                 it->output->size = 1;
1274                 it->direct = FALSE;
1275         }
1276
1277         switch (it->d.desc->bDescriptorSubtype) {
1278         case UDESCSUB_AC_INPUT:
1279                 it->inputs = kmalloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1280                 if (it->inputs == NULL) {
1281                         kprintf("uaudio_io_terminaltype: no memory\n");
1282                         return NULL;
1283                 }
1284                 tml = kmalloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1285                 if (tml == NULL) {
1286                         kprintf("uaudio_io_terminaltype: no memory\n");
1287                         kfree(it->inputs, M_TEMP);
1288                         it->inputs = NULL;
1289                         return NULL;
1290                 }
1291                 it->inputs[0] = tml;
1292                 tml->terminals[0] = UGETW(it->d.it->wTerminalType);
1293                 tml->size = 1;
1294                 it->inputs_size = 1;
1295                 return uaudio_merge_terminal_list(it);
1296         case UDESCSUB_AC_FEATURE:
1297                 src_id = it->d.fu->bSourceId;
1298                 it->inputs = kmalloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1299                 if (it->inputs == NULL) {
1300                         kprintf("uaudio_io_terminaltype: no memory\n");
1301                         return uaudio_io_terminaltype(outtype, iot, src_id);
1302                 }
1303                 it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1304                 it->inputs_size = 1;
1305                 return uaudio_merge_terminal_list(it);
1306         case UDESCSUB_AC_OUTPUT:
1307                 it->inputs = kmalloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1308                 if (it->inputs == NULL) {
1309                         kprintf("uaudio_io_terminaltype: no memory\n");
1310                         return NULL;
1311                 }
1312                 src_id = it->d.ot->bSourceId;
1313                 it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1314                 it->inputs_size = 1;
1315                 iot[src_id].direct = TRUE;
1316                 return NULL;
1317         case UDESCSUB_AC_MIXER:
1318                 it->inputs_size = 0;
1319                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1320                                     * it->d.mu->bNrInPins, M_TEMP, M_NOWAIT);
1321                 if (it->inputs == NULL) {
1322                         kprintf("uaudio_io_terminaltype: no memory\n");
1323                         return NULL;
1324                 }
1325                 for (i = 0; i < it->d.mu->bNrInPins; i++) {
1326                         src_id = it->d.mu->baSourceId[i];
1327                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1328                                                                src_id);
1329                         it->inputs_size++;
1330                 }
1331                 return uaudio_merge_terminal_list(it);
1332         case UDESCSUB_AC_SELECTOR:
1333                 it->inputs_size = 0;
1334                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1335                                     * it->d.su->bNrInPins, M_TEMP, M_NOWAIT);
1336                 if (it->inputs == NULL) {
1337                         kprintf("uaudio_io_terminaltype: no memory\n");
1338                         return NULL;
1339                 }
1340                 for (i = 0; i < it->d.su->bNrInPins; i++) {
1341                         src_id = it->d.su->baSourceId[i];
1342                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1343                                                                src_id);
1344                         it->inputs_size++;
1345                 }
1346                 return uaudio_merge_terminal_list(it);
1347         case UDESCSUB_AC_PROCESSING:
1348                 it->inputs_size = 0;
1349                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1350                                     * it->d.pu->bNrInPins, M_TEMP, M_NOWAIT);
1351                 if (it->inputs == NULL) {
1352                         kprintf("uaudio_io_terminaltype: no memory\n");
1353                         return NULL;
1354                 }
1355                 for (i = 0; i < it->d.pu->bNrInPins; i++) {
1356                         src_id = it->d.pu->baSourceId[i];
1357                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1358                                                                src_id);
1359                         it->inputs_size++;
1360                 }
1361                 return uaudio_merge_terminal_list(it);
1362         case UDESCSUB_AC_EXTENSION:
1363                 it->inputs_size = 0;
1364                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1365                                     * it->d.eu->bNrInPins, M_TEMP, M_NOWAIT);
1366                 if (it->inputs == NULL) {
1367                         kprintf("uaudio_io_terminaltype: no memory\n");
1368                         return NULL;
1369                 }
1370                 for (i = 0; i < it->d.eu->bNrInPins; i++) {
1371                         src_id = it->d.eu->baSourceId[i];
1372                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1373                                                                src_id);
1374                         it->inputs_size++;
1375                 }
1376                 return uaudio_merge_terminal_list(it);
1377         case UDESCSUB_AC_HEADER:
1378         default:
1379                 return NULL;
1380         }
1381 }
1382
1383 static usbd_status
1384 uaudio_identify(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
1385 {
1386         usbd_status err;
1387
1388         err = uaudio_identify_ac(sc, cdesc);
1389         if (err)
1390                 return err;
1391         return uaudio_identify_as(sc, cdesc);
1392 }
1393
1394 static void
1395 uaudio_add_alt(struct uaudio_softc *sc, const struct as_info *ai)
1396 {
1397         size_t len;
1398         struct as_info *nai;
1399
1400         len = sizeof(*ai) * (sc->sc_nalts + 1);
1401         nai = kmalloc(len, M_USBDEV, M_NOWAIT);
1402         if (nai == NULL) {
1403                 kprintf("uaudio_add_alt: no memory\n");
1404                 return;
1405         }
1406         /* Copy old data, if there was any */
1407         if (sc->sc_nalts != 0) {
1408                 memcpy(nai, sc->sc_alts, sizeof(*ai) * (sc->sc_nalts));
1409                 kfree(sc->sc_alts, M_USBDEV);
1410         }
1411         sc->sc_alts = nai;
1412         DPRINTFN(2,("uaudio_add_alt: adding alt=%d, enc=%d\n",
1413                     ai->alt, ai->encoding));
1414         sc->sc_alts[sc->sc_nalts++] = *ai;
1415 }
1416
1417 static usbd_status
1418 uaudio_process_as(struct uaudio_softc *sc, const char *buf, int *offsp,
1419                   int size, const usb_interface_descriptor_t *id)
1420 #define offs (*offsp)
1421 {
1422         const struct usb_audio_streaming_interface_descriptor *asid;
1423         const struct usb_audio_streaming_type1_descriptor *asf1d;
1424         const usb_endpoint_descriptor_audio_t *ed;
1425         const usb_endpoint_descriptor_audio_t *epdesc1;
1426         const struct usb_audio_streaming_endpoint_descriptor *sed;
1427         int format, chan, prec, enc;
1428         int dir, type, sync;
1429         struct as_info ai;
1430         const char *format_str;
1431
1432         asid = (const void *)(buf + offs);
1433
1434         if (asid->bDescriptorType != UDESC_CS_INTERFACE ||
1435             asid->bDescriptorSubtype != AS_GENERAL)
1436                 return USBD_INVAL;
1437         DPRINTF(("uaudio_process_as: asid: bTerminakLink=%d wFormatTag=%d\n",
1438                  asid->bTerminalLink, UGETW(asid->wFormatTag)));
1439         offs += asid->bLength;
1440         if (offs > size)
1441                 return USBD_INVAL;
1442
1443         asf1d = (const void *)(buf + offs);
1444         if (asf1d->bDescriptorType != UDESC_CS_INTERFACE ||
1445             asf1d->bDescriptorSubtype != FORMAT_TYPE)
1446                 return USBD_INVAL;
1447         offs += asf1d->bLength;
1448         if (offs > size)
1449                 return USBD_INVAL;
1450
1451         if (asf1d->bFormatType != FORMAT_TYPE_I) {
1452                 kprintf("%s: ignored setting with type %d format\n",
1453                        device_get_nameunit(sc->sc_dev), UGETW(asid->wFormatTag));
1454                 return USBD_NORMAL_COMPLETION;
1455         }
1456
1457         ed = (const void *)(buf + offs);
1458         if (ed->bDescriptorType != UDESC_ENDPOINT)
1459                 return USBD_INVAL;
1460         DPRINTF(("uaudio_process_as: endpoint[0] bLength=%d bDescriptorType=%d "
1461                  "bEndpointAddress=%d bmAttributes=0x%x wMaxPacketSize=%d "
1462                  "bInterval=%d bRefresh=%d bSynchAddress=%d\n",
1463                  ed->bLength, ed->bDescriptorType, ed->bEndpointAddress,
1464                  ed->bmAttributes, UGETW(ed->wMaxPacketSize),
1465                  ed->bInterval, ed->bRefresh, ed->bSynchAddress));
1466         offs += ed->bLength;
1467         if (offs > size)
1468                 return USBD_INVAL;
1469         if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
1470                 return USBD_INVAL;
1471
1472         dir = UE_GET_DIR(ed->bEndpointAddress);
1473         type = UE_GET_ISO_TYPE(ed->bmAttributes);
1474         if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_INP_ASYNC) &&
1475             dir == UE_DIR_IN && type == UE_ISO_ADAPT)
1476                 type = UE_ISO_ASYNC;
1477
1478         /* We can't handle endpoints that need a sync pipe yet. */
1479         sync = FALSE;
1480         if (dir == UE_DIR_IN && type == UE_ISO_ADAPT) {
1481                 sync = TRUE;
1482 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
1483                 kprintf("%s: ignored input endpoint of type adaptive\n",
1484                        device_get_nameunit(sc->sc_dev));
1485                 return USBD_NORMAL_COMPLETION;
1486 #endif
1487         }
1488         if (dir != UE_DIR_IN && type == UE_ISO_ASYNC) {
1489                 sync = TRUE;
1490 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
1491                 kprintf("%s: ignored output endpoint of type async\n",
1492                        device_get_nameunit(sc->sc_dev));
1493                 return USBD_NORMAL_COMPLETION;
1494 #endif
1495         }
1496
1497         sed = (const void *)(buf + offs);
1498         if (sed->bDescriptorType != UDESC_CS_ENDPOINT ||
1499             sed->bDescriptorSubtype != AS_GENERAL)
1500                 return USBD_INVAL;
1501         DPRINTF((" streadming_endpoint: offset=%d bLength=%d\n", offs, sed->bLength));
1502         offs += sed->bLength;
1503         if (offs > size)
1504                 return USBD_INVAL;
1505
1506         if (sync && id->bNumEndpoints <= 1) {
1507                 kprintf("%s: a sync-pipe endpoint but no other endpoint\n",
1508                        device_get_nameunit(sc->sc_dev));
1509                 return USBD_INVAL;
1510         }
1511         if (!sync && id->bNumEndpoints > 1) {
1512                 kprintf("%s: non sync-pipe endpoint but multiple endpoints\n",
1513                        device_get_nameunit(sc->sc_dev));
1514                 return USBD_INVAL;
1515         }
1516         epdesc1 = NULL;
1517         if (id->bNumEndpoints > 1) {
1518                 epdesc1 = (const void*)(buf + offs);
1519                 if (epdesc1->bDescriptorType != UDESC_ENDPOINT)
1520                         return USBD_INVAL;
1521                 DPRINTF(("uaudio_process_as: endpoint[1] bLength=%d "
1522                          "bDescriptorType=%d bEndpointAddress=%d "
1523                          "bmAttributes=0x%x wMaxPacketSize=%d bInterval=%d "
1524                          "bRefresh=%d bSynchAddress=%d\n",
1525                          epdesc1->bLength, epdesc1->bDescriptorType,
1526                          epdesc1->bEndpointAddress, epdesc1->bmAttributes,
1527                          UGETW(epdesc1->wMaxPacketSize), epdesc1->bInterval,
1528                          epdesc1->bRefresh, epdesc1->bSynchAddress));
1529                 offs += epdesc1->bLength;
1530                 if (offs > size)
1531                         return USBD_INVAL;
1532                 if (epdesc1->bSynchAddress != 0) {
1533                         kprintf("%s: invalid endpoint: bSynchAddress=0\n",
1534                                device_get_nameunit(sc->sc_dev));
1535                         return USBD_INVAL;
1536                 }
1537                 if (UE_GET_XFERTYPE(epdesc1->bmAttributes) != UE_ISOCHRONOUS) {
1538                         kprintf("%s: invalid endpoint: bmAttributes=0x%x\n",
1539                                device_get_nameunit(sc->sc_dev), epdesc1->bmAttributes);
1540                         return USBD_INVAL;
1541                 }
1542                 if (epdesc1->bEndpointAddress != ed->bSynchAddress) {
1543                         kprintf("%s: invalid endpoint addresses: "
1544                                "ep[0]->bSynchAddress=0x%x "
1545                                "ep[1]->bEndpointAddress=0x%x\n",
1546                                device_get_nameunit(sc->sc_dev), ed->bSynchAddress,
1547                                epdesc1->bEndpointAddress);
1548                         return USBD_INVAL;
1549                 }
1550                 /* UE_GET_ADDR(epdesc1->bEndpointAddress), and epdesc1->bRefresh */
1551         }
1552
1553         format = UGETW(asid->wFormatTag);
1554         chan = asf1d->bNrChannels;
1555         prec = asf1d->bBitResolution;
1556         if (prec != 8 && prec != 16 && prec != 24 && prec != 32) {
1557                 kprintf("%s: ignored setting with precision %d\n",
1558                        device_get_nameunit(sc->sc_dev), prec);
1559                 return USBD_NORMAL_COMPLETION;
1560         }
1561         switch (format) {
1562         case UA_FMT_PCM:
1563                 if (prec == 8) {
1564                         sc->sc_altflags |= HAS_8;
1565                 } else if (prec == 16) {
1566                         sc->sc_altflags |= HAS_16;
1567                 } else if (prec == 24) {
1568                         sc->sc_altflags |= HAS_24;
1569                 } else if (prec == 32) {
1570                         sc->sc_altflags |= HAS_32;
1571                 }
1572                 enc = AUDIO_ENCODING_SLINEAR_LE;
1573                 format_str = "pcm";
1574                 break;
1575         case UA_FMT_PCM8:
1576                 enc = AUDIO_ENCODING_ULINEAR_LE;
1577                 sc->sc_altflags |= HAS_8U;
1578                 format_str = "pcm8";
1579                 break;
1580         case UA_FMT_ALAW:
1581                 enc = AUDIO_ENCODING_ALAW;
1582                 sc->sc_altflags |= HAS_ALAW;
1583                 format_str = "alaw";
1584                 break;
1585         case UA_FMT_MULAW:
1586                 enc = AUDIO_ENCODING_ULAW;
1587                 sc->sc_altflags |= HAS_MULAW;
1588                 format_str = "mulaw";
1589                 break;
1590         case UA_FMT_IEEE_FLOAT:
1591         default:
1592                 kprintf("%s: ignored setting with format %d\n",
1593                        device_get_nameunit(sc->sc_dev), format);
1594                 return USBD_NORMAL_COMPLETION;
1595         }
1596 #ifdef USB_DEBUG
1597         kprintf("%s: %s: %dch, %d/%dbit, %s,", device_get_nameunit(sc->sc_dev),
1598                dir == UE_DIR_IN ? "recording" : "playback",
1599                chan, prec, asf1d->bSubFrameSize * 8, format_str);
1600         if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
1601                 kprintf(" %d-%dHz\n", UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
1602         } else {
1603                 int r;
1604                 kprintf(" %d", UA_GETSAMP(asf1d, 0));
1605                 for (r = 1; r < asf1d->bSamFreqType; r++)
1606                         kprintf(",%d", UA_GETSAMP(asf1d, r));
1607                 kprintf("Hz\n");
1608         }
1609 #endif
1610         if (sc->uaudio_sndstat_flag != 0) {
1611                 sbuf_printf(&(sc->uaudio_sndstat), "\n\t");
1612                 sbuf_printf(&(sc->uaudio_sndstat), 
1613                     "mode %d:(%s) %dch, %d/%dbit, %s,", 
1614                     id->bAlternateSetting,
1615                     dir == UE_DIR_IN ? "input" : "output",
1616                     chan, prec, asf1d->bSubFrameSize * 8, format_str);
1617                 if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
1618                         sbuf_printf(&(sc->uaudio_sndstat), " %d-%dHz", 
1619                             UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
1620                 } else {
1621                         int r;
1622                         sbuf_printf(&(sc->uaudio_sndstat), 
1623                             " %d", UA_GETSAMP(asf1d, 0));
1624                         for (r = 1; r < asf1d->bSamFreqType; r++)
1625                                 sbuf_printf(&(sc->uaudio_sndstat), 
1626                                     ",%d", UA_GETSAMP(asf1d, r));
1627                         sbuf_printf(&(sc->uaudio_sndstat), "Hz");
1628                 }
1629         }
1630
1631         ai.alt = id->bAlternateSetting;
1632         ai.encoding = enc;
1633         ai.attributes = sed->bmAttributes;
1634         ai.idesc = id;
1635         ai.edesc = ed;
1636         ai.edesc1 = epdesc1;
1637         ai.asf1desc = asf1d;
1638         ai.sc_busy = 0;
1639         ai.ifaceh = NULL;
1640         uaudio_add_alt(sc, &ai);
1641 #ifdef USB_DEBUG
1642         if (ai.attributes & UA_SED_FREQ_CONTROL)
1643                 DPRINTFN(1, ("uaudio_process_as:  FREQ_CONTROL\n"));
1644         if (ai.attributes & UA_SED_PITCH_CONTROL)
1645                 DPRINTFN(1, ("uaudio_process_as:  PITCH_CONTROL\n"));
1646 #endif
1647         sc->sc_mode |= (dir == UE_DIR_OUT) ? AUMODE_PLAY : AUMODE_RECORD;
1648
1649         return USBD_NORMAL_COMPLETION;
1650 }
1651 #undef offs
1652
1653 static usbd_status
1654 uaudio_identify_as(struct uaudio_softc *sc,
1655                    const usb_config_descriptor_t *cdesc)
1656 {
1657         const usb_interface_descriptor_t *id;
1658         const char *buf;
1659         int size, offs;
1660
1661         size = UGETW(cdesc->wTotalLength);
1662         buf = (const char *)cdesc;
1663
1664         /* Locate the AudioStreaming interface descriptor. */
1665         offs = 0;
1666         id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOSTREAM);
1667         if (id == NULL)
1668                 return USBD_INVAL;
1669
1670         sc->uaudio_sndstat_flag = 0;
1671         if (sbuf_new(&(sc->uaudio_sndstat), NULL, 4096, SBUF_AUTOEXTEND) != NULL)
1672                 sc->uaudio_sndstat_flag = 1;
1673
1674         /* Loop through all the alternate settings. */
1675         while (offs <= size) {
1676                 DPRINTFN(2, ("uaudio_identify: interface=%d offset=%d\n",
1677                     id->bInterfaceNumber, offs));
1678                 switch (id->bNumEndpoints) {
1679                 case 0:
1680                         DPRINTFN(2, ("uaudio_identify: AS null alt=%d\n",
1681                                      id->bAlternateSetting));
1682                         sc->sc_nullalt = id->bAlternateSetting;
1683                         break;
1684                 case 1:
1685 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
1686                 case 2:
1687 #endif
1688                         uaudio_process_as(sc, buf, &offs, size, id);
1689                         break;
1690                 default:
1691                         kprintf("%s: ignored audio interface with %d "
1692                                "endpoints\n",
1693                                device_get_nameunit(sc->sc_dev), id->bNumEndpoints);
1694                         break;
1695                 }
1696                 id = uaudio_find_iface(buf, size, &offs,UISUBCLASS_AUDIOSTREAM);
1697                 if (id == NULL)
1698                         break;
1699         }
1700
1701         sbuf_finish(&(sc->uaudio_sndstat));
1702
1703         if (offs > size)
1704                 return USBD_INVAL;
1705         DPRINTF(("uaudio_identify_as: %d alts available\n", sc->sc_nalts));
1706
1707         if (sc->sc_mode == 0) {
1708                 kprintf("%s: no usable endpoint found\n",
1709                        device_get_nameunit(sc->sc_dev));
1710                 return USBD_INVAL;
1711         }
1712
1713         return USBD_NORMAL_COMPLETION;
1714 }
1715
1716 static usbd_status
1717 uaudio_identify_ac(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
1718 {
1719         struct io_terminal* iot;
1720         const usb_interface_descriptor_t *id;
1721         const struct usb_audio_control_descriptor *acdp;
1722         const usb_descriptor_t *dp;
1723         const struct usb_audio_output_terminal *pot;
1724         struct terminal_list *tml;
1725         const char *buf, *ibuf, *ibufend;
1726         int size, offs, aclen, ndps, i, j;
1727
1728         size = UGETW(cdesc->wTotalLength);
1729         buf = (const char *)cdesc;
1730
1731         /* Locate the AudioControl interface descriptor. */
1732         offs = 0;
1733         id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOCONTROL);
1734         if (id == NULL)
1735                 return USBD_INVAL;
1736         if (offs + sizeof *acdp > size)
1737                 return USBD_INVAL;
1738         sc->sc_ac_iface = id->bInterfaceNumber;
1739         DPRINTFN(2,("uaudio_identify_ac: AC interface is %d\n", sc->sc_ac_iface));
1740
1741         /* A class-specific AC interface header should follow. */
1742         ibuf = buf + offs;
1743         acdp = (const struct usb_audio_control_descriptor *)ibuf;
1744         if (acdp->bDescriptorType != UDESC_CS_INTERFACE ||
1745             acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)
1746                 return USBD_INVAL;
1747         aclen = UGETW(acdp->wTotalLength);
1748         if (offs + aclen > size)
1749                 return USBD_INVAL;
1750
1751         if (!(usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_BAD_ADC) &&
1752              UGETW(acdp->bcdADC) != UAUDIO_VERSION)
1753                 return USBD_INVAL;
1754
1755         sc->sc_audio_rev = UGETW(acdp->bcdADC);
1756         DPRINTFN(2,("uaudio_identify_ac: found AC header, vers=%03x, len=%d\n",
1757                  sc->sc_audio_rev, aclen));
1758
1759         sc->sc_nullalt = -1;
1760
1761         /* Scan through all the AC specific descriptors */
1762         ibufend = ibuf + aclen;
1763         dp = (const usb_descriptor_t *)ibuf;
1764         ndps = 0;
1765         iot = kmalloc(sizeof(struct io_terminal) * 256, M_TEMP, M_NOWAIT | M_ZERO);
1766         if (iot == NULL) {
1767                 kprintf("%s: no memory\n", __func__);
1768                 return USBD_NOMEM;
1769         }
1770         for (;;) {
1771                 ibuf += dp->bLength;
1772                 if (ibuf >= ibufend)
1773                         break;
1774                 dp = (const usb_descriptor_t *)ibuf;
1775                 if (ibuf + dp->bLength > ibufend) {
1776                         kfree(iot, M_TEMP);
1777                         return USBD_INVAL;
1778                 }
1779                 if (dp->bDescriptorType != UDESC_CS_INTERFACE) {
1780                         kprintf("uaudio_identify_ac: skip desc type=0x%02x\n",
1781                                dp->bDescriptorType);
1782                         continue;
1783                 }
1784                 i = ((const struct usb_audio_input_terminal *)dp)->bTerminalId;
1785                 iot[i].d.desc = dp;
1786                 if (i > ndps)
1787                         ndps = i;
1788         }
1789         ndps++;
1790
1791         /* construct io_terminal */
1792         for (i = 0; i < ndps; i++) {
1793                 dp = iot[i].d.desc;
1794                 if (dp == NULL)
1795                         continue;
1796                 if (dp->bDescriptorSubtype != UDESCSUB_AC_OUTPUT)
1797                         continue;
1798                 pot = iot[i].d.ot;
1799                 tml = uaudio_io_terminaltype(UGETW(pot->wTerminalType), iot, i);
1800                 if (tml != NULL)
1801                         kfree(tml, M_TEMP);
1802         }
1803
1804 #ifdef USB_DEBUG
1805         for (i = 0; i < 256; i++) {
1806                 struct usb_audio_cluster cluster;
1807
1808                 if (iot[i].d.desc == NULL)
1809                         continue;
1810                 kprintf("id %d:\t", i);
1811                 switch (iot[i].d.desc->bDescriptorSubtype) {
1812                 case UDESCSUB_AC_INPUT:
1813                         kprintf("AC_INPUT type=%s\n", uaudio_get_terminal_name
1814                                   (UGETW(iot[i].d.it->wTerminalType)));
1815                         kprintf("\t");
1816                         cluster = uaudio_get_cluster(i, iot);
1817                         uaudio_dump_cluster(&cluster);
1818                         kprintf("\n");
1819                         break;
1820                 case UDESCSUB_AC_OUTPUT:
1821                         kprintf("AC_OUTPUT type=%s ", uaudio_get_terminal_name
1822                                   (UGETW(iot[i].d.ot->wTerminalType)));
1823                         kprintf("src=%d\n", iot[i].d.ot->bSourceId);
1824                         break;
1825                 case UDESCSUB_AC_MIXER:
1826                         kprintf("AC_MIXER src=");
1827                         for (j = 0; j < iot[i].d.mu->bNrInPins; j++)
1828                                 kprintf("%d ", iot[i].d.mu->baSourceId[j]);
1829                         kprintf("\n\t");
1830                         cluster = uaudio_get_cluster(i, iot);
1831                         uaudio_dump_cluster(&cluster);
1832                         kprintf("\n");
1833                         break;
1834                 case UDESCSUB_AC_SELECTOR:
1835                         kprintf("AC_SELECTOR src=");
1836                         for (j = 0; j < iot[i].d.su->bNrInPins; j++)
1837                                 kprintf("%d ", iot[i].d.su->baSourceId[j]);
1838                         kprintf("\n");
1839                         break;
1840                 case UDESCSUB_AC_FEATURE:
1841                         kprintf("AC_FEATURE src=%d\n", iot[i].d.fu->bSourceId);
1842                         break;
1843                 case UDESCSUB_AC_PROCESSING:
1844                         kprintf("AC_PROCESSING src=");
1845                         for (j = 0; j < iot[i].d.pu->bNrInPins; j++)
1846                                 kprintf("%d ", iot[i].d.pu->baSourceId[j]);
1847                         kprintf("\n\t");
1848                         cluster = uaudio_get_cluster(i, iot);
1849                         uaudio_dump_cluster(&cluster);
1850                         kprintf("\n");
1851                         break;
1852                 case UDESCSUB_AC_EXTENSION:
1853                         kprintf("AC_EXTENSION src=");
1854                         for (j = 0; j < iot[i].d.eu->bNrInPins; j++)
1855                                 kprintf("%d ", iot[i].d.eu->baSourceId[j]);
1856                         kprintf("\n\t");
1857                         cluster = uaudio_get_cluster(i, iot);
1858                         uaudio_dump_cluster(&cluster);
1859                         kprintf("\n");
1860                         break;
1861                 default:
1862                         kprintf("unknown audio control (subtype=%d)\n",
1863                                   iot[i].d.desc->bDescriptorSubtype);
1864                 }
1865                 for (j = 0; j < iot[i].inputs_size; j++) {
1866                         int k;
1867                         kprintf("\tinput%d: ", j);
1868                         tml = iot[i].inputs[j];
1869                         if (tml == NULL) {
1870                                 kprintf("NULL\n");
1871                                 continue;
1872                         }
1873                         for (k = 0; k < tml->size; k++)
1874                                 kprintf("%s ", uaudio_get_terminal_name
1875                                           (tml->terminals[k]));
1876                         kprintf("\n");
1877                 }
1878                 kprintf("\toutput: ");
1879                 tml = iot[i].output;
1880                 for (j = 0; j < tml->size; j++)
1881                         kprintf("%s ", uaudio_get_terminal_name(tml->terminals[j]));
1882                 kprintf("\n");
1883         }
1884 #endif
1885
1886         for (i = 0; i < ndps; i++) {
1887                 dp = iot[i].d.desc;
1888                 if (dp == NULL)
1889                         continue;
1890                 DPRINTF(("uaudio_identify_ac: id=%d subtype=%d\n",
1891                          i, dp->bDescriptorSubtype));
1892                 switch (dp->bDescriptorSubtype) {
1893                 case UDESCSUB_AC_HEADER:
1894                         kprintf("uaudio_identify_ac: unexpected AC header\n");
1895                         break;
1896                 case UDESCSUB_AC_INPUT:
1897                         uaudio_add_input(sc, iot, i);
1898                         break;
1899                 case UDESCSUB_AC_OUTPUT:
1900                         uaudio_add_output(sc, iot, i);
1901                         break;
1902                 case UDESCSUB_AC_MIXER:
1903                         uaudio_add_mixer(sc, iot, i);
1904                         break;
1905                 case UDESCSUB_AC_SELECTOR:
1906                         uaudio_add_selector(sc, iot, i);
1907                         break;
1908                 case UDESCSUB_AC_FEATURE:
1909                         uaudio_add_feature(sc, iot, i);
1910                         break;
1911                 case UDESCSUB_AC_PROCESSING:
1912                         uaudio_add_processing(sc, iot, i);
1913                         break;
1914                 case UDESCSUB_AC_EXTENSION:
1915                         uaudio_add_extension(sc, iot, i);
1916                         break;
1917                 default:
1918                         kprintf("uaudio_identify_ac: bad AC desc subtype=0x%02x\n",
1919                                dp->bDescriptorSubtype);
1920                         break;
1921                 }
1922         }
1923
1924         /* delete io_terminal */
1925         for (i = 0; i < 256; i++) {
1926                 if (iot[i].d.desc == NULL)
1927                         continue;
1928                 if (iot[i].inputs != NULL) {
1929                         for (j = 0; j < iot[i].inputs_size; j++) {
1930                                 if (iot[i].inputs[j] != NULL)
1931                                         kfree(iot[i].inputs[j], M_TEMP);
1932                         }
1933                         kfree(iot[i].inputs, M_TEMP);
1934                 }
1935                 if (iot[i].output != NULL)
1936                         kfree(iot[i].output, M_TEMP);
1937                 iot[i].d.desc = NULL;
1938         }
1939         kfree(iot, M_TEMP);
1940
1941         return USBD_NORMAL_COMPLETION;
1942 }
1943
1944 static int
1945 uaudio_get(struct uaudio_softc *sc, int which, int type, int wValue,
1946            int wIndex, int len)
1947 {
1948         usb_device_request_t req;
1949         uint8_t data[4];
1950         usbd_status err;
1951         int val;
1952
1953         if (sc->sc_dying)
1954                 return EIO;
1955
1956         if (wValue == -1)
1957                 return 0;
1958
1959         req.bmRequestType = type;
1960         req.bRequest = which;
1961         USETW(req.wValue, wValue);
1962         USETW(req.wIndex, wIndex);
1963         USETW(req.wLength, len);
1964         DPRINTFN(2,("uaudio_get: type=0x%02x req=0x%02x wValue=0x%04x "
1965                     "wIndex=0x%04x len=%d\n",
1966                     type, which, wValue, wIndex, len));
1967         err = usbd_do_request(sc->sc_udev, &req, data);
1968         if (err) {
1969                 DPRINTF(("uaudio_get: err=%s\n", usbd_errstr(err)));
1970                 return -1;
1971         }
1972         switch (len) {
1973         case 1:
1974                 val = data[0];
1975                 break;
1976         case 2:
1977                 val = data[0] | (data[1] << 8);
1978                 break;
1979         default:
1980                 DPRINTF(("uaudio_get: bad length=%d\n", len));
1981                 return -1;
1982         }
1983         DPRINTFN(2,("uaudio_get: val=%d\n", val));
1984         return val;
1985 }
1986
1987 static void
1988 uaudio_set(struct uaudio_softc *sc, int which, int type, int wValue,
1989            int wIndex, int len, int val)
1990 {
1991         usb_device_request_t req;
1992         uint8_t data[4];
1993         usbd_status err;
1994
1995         if (sc->sc_dying)
1996                 return;
1997
1998         if (wValue == -1)
1999                 return;
2000
2001         req.bmRequestType = type;
2002         req.bRequest = which;
2003         USETW(req.wValue, wValue);
2004         USETW(req.wIndex, wIndex);
2005         USETW(req.wLength, len);
2006         switch (len) {
2007         case 1:
2008                 data[0] = val;
2009                 break;
2010         case 2:
2011                 data[0] = val;
2012                 data[1] = val >> 8;
2013                 break;
2014         default:
2015                 return;
2016         }
2017         DPRINTFN(2,("uaudio_set: type=0x%02x req=0x%02x wValue=0x%04x "
2018                     "wIndex=0x%04x len=%d, val=%d\n",
2019                     type, which, wValue, wIndex, len, val & 0xffff));
2020         err = usbd_do_request(sc->sc_udev, &req, data);
2021 #ifdef USB_DEBUG
2022         if (err)
2023                 DPRINTF(("uaudio_set: err=%d\n", err));
2024 #endif
2025 }
2026
2027 static int
2028 uaudio_signext(int type, int val)
2029 {
2030         if (!MIX_UNSIGNED(type)) {
2031                 if (MIX_SIZE(type) == 2)
2032                         val = (int16_t)val;
2033                 else
2034                         val = (int8_t)val;
2035         }
2036         return val;
2037 }
2038
2039 int
2040 uaudio_bsd2value(struct mixerctl *mc, int val)
2041 {
2042         DPRINTFN(5,("uaudio_bsd2value: type=%03x val=%d min=%d max=%d ",
2043                     mc->type, val, mc->minval, mc->maxval));
2044         if (mc->type == MIX_ON_OFF) {
2045                 val = (val != 0);
2046         } else if (mc->type == MIX_SELECTOR) {
2047                 if (val < mc->minval || val > mc->maxval)
2048                         val = mc->minval;
2049         } else
2050                 val = (val + mc->delta/2) * mc->mul / 255 + mc->minval;
2051         DPRINTFN(5, ("val'=%d\n", val));
2052         return val;
2053 }
2054
2055 static void
2056 uaudio_ctl_set(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2057                int chan, int val)
2058 {
2059         val = uaudio_bsd2value(mc, val);
2060         uaudio_set(sc, which, UT_WRITE_CLASS_INTERFACE, mc->wValue[chan],
2061                    mc->wIndex, MIX_SIZE(mc->type), val);
2062 }
2063
2064 /* Set up a pipe for a channel. */
2065 static usbd_status
2066 uaudio_chan_open(struct uaudio_softc *sc, struct chan *ch)
2067 {
2068         struct as_info *as;
2069         int endpt;
2070         usbd_status err;
2071
2072         if (sc->sc_dying)
2073                 return EIO;
2074
2075         as = &sc->sc_alts[ch->altidx];
2076         endpt = as->edesc->bEndpointAddress;
2077         DPRINTF(("uaudio_chan_open: endpt=0x%02x, speed=%d, alt=%d\n",
2078                  endpt, ch->sample_rate, as->alt));
2079
2080         /* Set alternate interface corresponding to the mode. */
2081         err = usbd_set_interface(as->ifaceh, as->alt);
2082         if (err)
2083                 return err;
2084
2085         /*
2086          * If just one sampling rate is supported,
2087          * no need to call uaudio_set_speed().
2088          * Roland SD-90 freezes by a SAMPLING_FREQ_CONTROL request.
2089          */
2090         if (as->asf1desc->bSamFreqType != 1) {
2091                 err = uaudio_set_speed(sc, endpt, ch->sample_rate);
2092                 if (err)
2093                         DPRINTF(("uaudio_chan_open: set_speed failed err=%s\n",
2094                                  usbd_errstr(err)));
2095         }
2096
2097         ch->pipe = 0;
2098         ch->sync_pipe = 0;
2099         DPRINTF(("uaudio_chan_open: create pipe to 0x%02x\n", endpt));
2100         err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->pipe);
2101         if (err)
2102                 return err;
2103         if (as->edesc1 != NULL) {
2104                 endpt = as->edesc1->bEndpointAddress;
2105                 DPRINTF(("uaudio_chan_open: create sync-pipe to 0x%02x\n", endpt));
2106                 err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->sync_pipe);
2107         }
2108         return err;
2109 }
2110
2111 static void
2112 uaudio_chan_close(struct uaudio_softc *sc, struct chan *ch)
2113 {
2114         struct as_info *as;
2115
2116         if (sc->sc_dying)
2117                 return ;
2118
2119         as = &sc->sc_alts[ch->altidx];
2120         as->sc_busy = 0;
2121         if (sc->sc_nullalt >= 0) {
2122                 DPRINTF(("uaudio_chan_close: set null alt=%d\n",
2123                          sc->sc_nullalt));
2124                 usbd_set_interface(as->ifaceh, sc->sc_nullalt);
2125         }
2126         if (ch->pipe) {
2127                 usbd_abort_pipe(ch->pipe);
2128                 usbd_close_pipe(ch->pipe);
2129         }
2130         if (ch->sync_pipe) {
2131                 usbd_abort_pipe(ch->sync_pipe);
2132                 usbd_close_pipe(ch->sync_pipe);
2133         }
2134 }
2135
2136 static usbd_status
2137 uaudio_chan_alloc_buffers(struct uaudio_softc *sc, struct chan *ch)
2138 {
2139         usbd_xfer_handle xfer;
2140         void *buf;
2141         int i, size;
2142
2143         size = (ch->bytes_per_frame + ch->sample_size) * UAUDIO_NFRAMES;
2144         for (i = 0; i < UAUDIO_NCHANBUFS; i++) {
2145                 xfer = usbd_alloc_xfer(sc->sc_udev);
2146                 if (xfer == 0)
2147                         goto bad;
2148                 ch->chanbufs[i].xfer = xfer;
2149                 buf = usbd_alloc_buffer(xfer, size);
2150                 if (buf == 0) {
2151                         i++;
2152                         goto bad;
2153                 }
2154                 ch->chanbufs[i].buffer = buf;
2155                 ch->chanbufs[i].chan = ch;
2156         }
2157
2158         return USBD_NORMAL_COMPLETION;
2159
2160 bad:
2161         while (--i >= 0)
2162                 /* implicit buffer kfree */
2163                 usbd_free_xfer(ch->chanbufs[i].xfer);
2164         return USBD_NOMEM;
2165 }
2166
2167 static void
2168 uaudio_chan_free_buffers(struct uaudio_softc *sc, struct chan *ch)
2169 {
2170         int i;
2171
2172         for (i = 0; i < UAUDIO_NCHANBUFS; i++)
2173                 usbd_free_xfer(ch->chanbufs[i].xfer);
2174 }
2175
2176 /* Called at splusb() */
2177 static void
2178 uaudio_chan_ptransfer(struct chan *ch)
2179 {
2180         struct chanbuf *cb;
2181         int i, n, size, residue, total;
2182
2183         if (ch->sc->sc_dying)
2184                 return;
2185
2186         /* Pick the next channel buffer. */
2187         cb = &ch->chanbufs[ch->curchanbuf];
2188         if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
2189                 ch->curchanbuf = 0;
2190
2191         /* Compute the size of each frame in the next transfer. */
2192         residue = ch->residue;
2193         total = 0;
2194         for (i = 0; i < UAUDIO_NFRAMES; i++) {
2195                 size = ch->bytes_per_frame;
2196                 residue += ch->fraction;
2197                 if (residue >= USB_FRAMES_PER_SECOND) {
2198                         if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
2199                                 size += ch->sample_size;
2200                         residue -= USB_FRAMES_PER_SECOND;
2201                 }
2202                 cb->sizes[i] = size;
2203                 total += size;
2204         }
2205         ch->residue = residue;
2206         cb->size = total;
2207
2208         /*
2209          * Transfer data from upper layer buffer to channel buffer, taking
2210          * care of wrapping the upper layer buffer.
2211          */
2212         n = min(total, ch->end - ch->cur);
2213         memcpy(cb->buffer, ch->cur, n);
2214         ch->cur += n;
2215         if (ch->cur >= ch->end)
2216                 ch->cur = ch->start;
2217         if (total > n) {
2218                 total -= n;
2219                 memcpy(cb->buffer + n, ch->cur, total);
2220                 ch->cur += total;
2221         }
2222
2223 #ifdef USB_DEBUG
2224         if (uaudiodebug > 8) {
2225                 DPRINTF(("uaudio_chan_ptransfer: buffer=%p, residue=0.%03d\n",
2226                          cb->buffer, ch->residue));
2227                 for (i = 0; i < UAUDIO_NFRAMES; i++) {
2228                         DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
2229                 }
2230         }
2231 #endif
2232
2233         DPRINTFN(5,("uaudio_chan_transfer: ptransfer xfer=%p\n", cb->xfer));
2234         /* Fill the request */
2235         usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
2236                              UAUDIO_NFRAMES, USBD_NO_COPY,
2237                              uaudio_chan_pintr);
2238
2239         (void)usbd_transfer(cb->xfer);
2240 }
2241
2242 static void
2243 uaudio_chan_pintr(usbd_xfer_handle xfer, usbd_private_handle priv,
2244                   usbd_status status)
2245 {
2246         struct chanbuf *cb;
2247         struct chan *ch;
2248         u_int32_t count;
2249
2250         cb = priv;
2251         ch = cb->chan;
2252         /* Return if we are aborting. */
2253         if (status == USBD_CANCELLED)
2254                 return;
2255
2256         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
2257         DPRINTFN(5,("uaudio_chan_pintr: count=%d, transferred=%d\n",
2258                     count, ch->transferred));
2259 #ifdef DIAGNOSTIC
2260         if (count != cb->size) {
2261                 kprintf("uaudio_chan_pintr: count(%d) != size(%d)\n",
2262                        count, cb->size);
2263         }
2264 #endif
2265
2266         ch->transferred += cb->size;
2267
2268         crit_enter();
2269         chn_intr(ch->pcm_ch);
2270         crit_exit();
2271
2272         /* start next transfer */
2273         uaudio_chan_ptransfer(ch);
2274 }
2275
2276 /* Called at splusb() */
2277 static void
2278 uaudio_chan_rtransfer(struct chan *ch)
2279 {
2280         struct chanbuf *cb;
2281         int i, size, residue, total;
2282
2283         if (ch->sc->sc_dying)
2284                 return;
2285
2286         /* Pick the next channel buffer. */
2287         cb = &ch->chanbufs[ch->curchanbuf];
2288         if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
2289                 ch->curchanbuf = 0;
2290
2291         /* Compute the size of each frame in the next transfer. */
2292         residue = ch->residue;
2293         total = 0;
2294         for (i = 0; i < UAUDIO_NFRAMES; i++) {
2295                 size = ch->bytes_per_frame;
2296                 cb->sizes[i] = size;
2297                 cb->offsets[i] = total;
2298                 total += size;
2299         }
2300         ch->residue = residue;
2301         cb->size = total;
2302
2303 #ifdef USB_DEBUG
2304         if (uaudiodebug > 8) {
2305                 DPRINTF(("uaudio_chan_rtransfer: buffer=%p, residue=0.%03d\n",
2306                          cb->buffer, ch->residue));
2307                 for (i = 0; i < UAUDIO_NFRAMES; i++) {
2308                         DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
2309                 }
2310         }
2311 #endif
2312
2313         DPRINTFN(5,("uaudio_chan_rtransfer: transfer xfer=%p\n", cb->xfer));
2314         /* Fill the request */
2315         usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
2316                              UAUDIO_NFRAMES, USBD_NO_COPY,
2317                              uaudio_chan_rintr);
2318
2319         (void)usbd_transfer(cb->xfer);
2320 }
2321
2322 static void
2323 uaudio_chan_rintr(usbd_xfer_handle xfer, usbd_private_handle priv,
2324                   usbd_status status)
2325 {
2326         struct chanbuf *cb = priv;
2327         struct chan *ch = cb->chan;
2328         u_int32_t count;
2329         int i, n, frsize;
2330
2331         /* Return if we are aborting. */
2332         if (status == USBD_CANCELLED)
2333                 return;
2334
2335         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
2336         DPRINTFN(5,("uaudio_chan_rintr: count=%d, transferred=%d\n",
2337                     count, ch->transferred));
2338
2339         /* count < cb->size is normal for asynchronous source */
2340 #ifdef DIAGNOSTIC
2341         if (count > cb->size) {
2342                 kprintf("uaudio_chan_rintr: count(%d) > size(%d)\n",
2343                        count, cb->size);
2344         }
2345 #endif
2346
2347         /*
2348          * Transfer data from channel buffer to upper layer buffer, taking
2349          * care of wrapping the upper layer buffer.
2350          */
2351         for(i = 0; i < UAUDIO_NFRAMES; i++) {
2352                 frsize = cb->sizes[i];
2353                 n = min(frsize, ch->end - ch->cur);
2354                 memcpy(ch->cur, cb->buffer + cb->offsets[i], n);
2355                 ch->cur += n;
2356                 if (ch->cur >= ch->end)
2357                         ch->cur = ch->start;
2358                 if (frsize > n) {
2359                         memcpy(ch->cur, cb->buffer + cb->offsets[i] + n,
2360                             frsize - n);
2361                         ch->cur += frsize - n;
2362                 }
2363         }
2364
2365         /* Call back to upper layer */
2366         ch->transferred += count;
2367
2368         crit_enter();
2369         chn_intr(ch->pcm_ch);
2370         crit_exit();
2371
2372         /* start next transfer */
2373         uaudio_chan_rtransfer(ch);
2374 }
2375
2376 static usbd_status
2377 uaudio_set_speed(struct uaudio_softc *sc, int endpt, u_int speed)
2378 {
2379         usb_device_request_t req;
2380         uint8_t data[3];
2381
2382         DPRINTFN(5,("uaudio_set_speed: endpt=%d speed=%u\n", endpt, speed));
2383         req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
2384         req.bRequest = SET_CUR;
2385         USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
2386         USETW(req.wIndex, endpt);
2387         USETW(req.wLength, 3);
2388         data[0] = speed;
2389         data[1] = speed >> 8;
2390         data[2] = speed >> 16;
2391
2392         return usbd_do_request(sc->sc_udev, &req, data);
2393 }
2394
2395
2396 /************************************************************/
2397 int
2398 uaudio_init_params(struct uaudio_softc *sc, struct chan *ch, int mode)
2399 {
2400         int i, j, enc;
2401         int samples_per_frame, sample_size;
2402
2403         if ((sc->sc_playchan.pipe != NULL) || (sc->sc_recchan.pipe != NULL))
2404                 return (-1);
2405
2406         switch(ch->format & 0x000FFFFF) {
2407         case AFMT_U8:
2408                 enc = AUDIO_ENCODING_ULINEAR_LE;
2409                 ch->precision = 8;
2410                 break;
2411         case AFMT_S8:
2412                 enc = AUDIO_ENCODING_SLINEAR_LE;
2413                 ch->precision = 8;
2414                 break;
2415         case AFMT_A_LAW:        /* ? */
2416                 enc = AUDIO_ENCODING_ALAW;
2417                 ch->precision = 8;
2418                 break;
2419         case AFMT_MU_LAW:       /* ? */
2420                 enc = AUDIO_ENCODING_ULAW;
2421                 ch->precision = 8;
2422                 break;
2423         case AFMT_S16_LE:
2424                 enc = AUDIO_ENCODING_SLINEAR_LE;
2425                 ch->precision = 16;
2426                 break;
2427         case AFMT_S16_BE:
2428                 enc = AUDIO_ENCODING_SLINEAR_BE;
2429                 ch->precision = 16;
2430                 break;
2431         case AFMT_U16_LE:
2432                 enc = AUDIO_ENCODING_ULINEAR_LE;
2433                 ch->precision = 16;
2434                 break;
2435         case AFMT_U16_BE:
2436                 enc = AUDIO_ENCODING_ULINEAR_BE;
2437                 ch->precision = 16;
2438                 break;
2439         case AFMT_S24_LE:
2440                 enc = AUDIO_ENCODING_SLINEAR_LE;
2441                 ch->precision = 24;
2442                 break;
2443         case AFMT_S24_BE:
2444                 enc = AUDIO_ENCODING_SLINEAR_BE;
2445                 ch->precision = 24;
2446                 break;
2447         case AFMT_U24_LE:
2448                 enc = AUDIO_ENCODING_ULINEAR_LE;
2449                 ch->precision = 24;
2450                 break;
2451         case AFMT_U24_BE:
2452                 enc = AUDIO_ENCODING_ULINEAR_BE;
2453                 ch->precision = 24;
2454                 break;
2455         case AFMT_S32_LE:
2456                 enc = AUDIO_ENCODING_SLINEAR_LE;
2457                 ch->precision = 32;
2458                 break;
2459         case AFMT_S32_BE:
2460                 enc = AUDIO_ENCODING_SLINEAR_BE;
2461                 ch->precision = 32;
2462                 break;
2463         case AFMT_U32_LE:
2464                 enc = AUDIO_ENCODING_ULINEAR_LE;
2465                 ch->precision = 32;
2466                 break;
2467         case AFMT_U32_BE:
2468                 enc = AUDIO_ENCODING_ULINEAR_BE;
2469                 ch->precision = 32;
2470                 break;
2471         default:
2472                 enc = 0;
2473                 ch->precision = 16;
2474                 kprintf("Unknown format %x\n", ch->format);
2475         }
2476
2477         if (ch->format & AFMT_STEREO) {
2478                 ch->channels = 2;
2479         } else {
2480                 ch->channels = 1;
2481         }
2482
2483 /*      for (mode =  ......      */
2484                 for (i = 0; i < sc->sc_nalts; i++) {
2485                         const struct usb_audio_streaming_type1_descriptor *a1d =
2486                                 sc->sc_alts[i].asf1desc;
2487                         if (ch->channels == a1d->bNrChannels &&
2488                             ch->precision == a1d->bBitResolution &&
2489 #if 0
2490                             enc == sc->sc_alts[i].encoding) {
2491 #else
2492                             enc == sc->sc_alts[i].encoding &&
2493                             (mode == AUMODE_PLAY ? UE_DIR_OUT : UE_DIR_IN) ==
2494                             UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress)) {
2495 #endif
2496                                 if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
2497                                         DPRINTFN(2,("uaudio_set_params: cont %d-%d\n",
2498                                             UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
2499                                         if (UA_SAMP_LO(a1d) <= ch->sample_rate &&
2500                                             ch->sample_rate <= UA_SAMP_HI(a1d)) {
2501                                                 if (mode == AUMODE_PLAY)
2502                                                         sc->sc_playchan.altidx = i;
2503                                                 else
2504                                                         sc->sc_recchan.altidx = i;
2505                                                 goto found;
2506                                         }
2507                                 } else {
2508                                         for (j = 0; j < a1d->bSamFreqType; j++) {
2509                                                 DPRINTFN(2,("uaudio_set_params: disc #"
2510                                                     "%d: %d\n", j, UA_GETSAMP(a1d, j)));
2511                                                 /* XXX allow for some slack */
2512                                                 if (UA_GETSAMP(a1d, j) ==
2513                                                     ch->sample_rate) {
2514                                                         if (mode == AUMODE_PLAY)
2515                                                                 sc->sc_playchan.altidx = i;
2516                                                         else
2517                                                                 sc->sc_recchan.altidx = i;
2518                                                         goto found;
2519                                                 }
2520                                         }
2521                                 }
2522                         }
2523                 }
2524                 /* return (EINVAL); */
2525                 if (mode == AUMODE_PLAY) 
2526                         kprintf("uaudio: This device can't play in rate=%d.\n", ch->sample_rate);
2527                 else
2528                         kprintf("uaudio: This device can't record in rate=%d.\n", ch->sample_rate);
2529                 return (-1);
2530
2531         found:
2532 #if 0 /* XXX */
2533                 p->sw_code = swcode;
2534                 p->factor  = factor;
2535                 if (usemode == mode)
2536                         sc->sc_curaltidx = i;
2537 #endif
2538 /*      } */
2539
2540         sample_size = ch->precision * ch->channels / 8;
2541         samples_per_frame = ch->sample_rate / USB_FRAMES_PER_SECOND;
2542         ch->fraction = ch->sample_rate % USB_FRAMES_PER_SECOND;
2543         ch->sample_size = sample_size;
2544         ch->bytes_per_frame = samples_per_frame * sample_size;
2545         ch->residue = 0;
2546
2547         ch->cur = ch->start;
2548         ch->transferred = 0;
2549         ch->curchanbuf = 0;
2550         return (0);
2551 }
2552
2553 struct uaudio_conversion {
2554         uint8_t uaudio_fmt;
2555         uint8_t uaudio_prec;
2556         uint32_t freebsd_fmt;
2557 };
2558
2559 const struct uaudio_conversion const accepted_conversion[] = {
2560         {AUDIO_ENCODING_ULINEAR_LE, 8, AFMT_U8},
2561         {AUDIO_ENCODING_ULINEAR_LE, 16, AFMT_U16_LE},
2562         {AUDIO_ENCODING_ULINEAR_LE, 24, AFMT_U24_LE},
2563         {AUDIO_ENCODING_ULINEAR_LE, 32, AFMT_U32_LE},
2564         {AUDIO_ENCODING_ULINEAR_BE, 16, AFMT_U16_BE},
2565         {AUDIO_ENCODING_ULINEAR_BE, 24, AFMT_U24_BE},
2566         {AUDIO_ENCODING_ULINEAR_BE, 32, AFMT_U32_BE},
2567         {AUDIO_ENCODING_SLINEAR_LE, 8, AFMT_S8},
2568         {AUDIO_ENCODING_SLINEAR_LE, 16, AFMT_S16_LE},
2569         {AUDIO_ENCODING_SLINEAR_LE, 24, AFMT_S24_LE},
2570         {AUDIO_ENCODING_SLINEAR_LE, 32, AFMT_S32_LE},
2571         {AUDIO_ENCODING_SLINEAR_BE, 16, AFMT_S16_BE},
2572         {AUDIO_ENCODING_SLINEAR_BE, 24, AFMT_S24_BE},
2573         {AUDIO_ENCODING_SLINEAR_BE, 32, AFMT_S32_BE},
2574         {AUDIO_ENCODING_ALAW, 8, AFMT_A_LAW},
2575         {AUDIO_ENCODING_ULAW, 8, AFMT_MU_LAW},
2576         {0,0,0}
2577 };
2578
2579 unsigned
2580 uaudio_query_formats(device_t dev, int reqdir, unsigned maxfmt, struct pcmchan_caps *cap)
2581 {
2582         struct uaudio_softc *sc;
2583         const struct usb_audio_streaming_type1_descriptor *asf1d;
2584         const struct uaudio_conversion *iterator;
2585         unsigned fmtcount, foundcount;
2586         u_int32_t fmt;
2587         uint8_t format, numchan, subframesize, prec, dir, iscontinuous;
2588         int freq, freq_min, freq_max;
2589         char *numchannel_descr;
2590         char freq_descr[64];
2591         int i,r;
2592
2593         sc = device_get_softc(dev);
2594         if (sc == NULL)
2595                 return 0;
2596
2597         cap->minspeed = cap->maxspeed = 0;
2598         foundcount = fmtcount = 0;
2599
2600         for (i = 0; i < sc->sc_nalts; i++) {
2601                 dir = UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress);
2602
2603                 if ((dir == UE_DIR_OUT) != (reqdir == PCMDIR_PLAY))
2604                         continue;
2605
2606                 asf1d = sc->sc_alts[i].asf1desc;
2607                 format = sc->sc_alts[i].encoding;
2608
2609                 numchan = asf1d->bNrChannels;
2610                 subframesize = asf1d->bSubFrameSize;
2611                 prec = asf1d->bBitResolution;   /* precision */
2612                 iscontinuous = asf1d->bSamFreqType == UA_SAMP_CONTNUOUS;
2613
2614                 if (iscontinuous)
2615                         ksnprintf(freq_descr, sizeof(freq_descr), "continuous min %d max %d", UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
2616                 else
2617                         ksnprintf(freq_descr, sizeof(freq_descr), "fixed frequency (%d listed formats)", asf1d->bSamFreqType);
2618
2619                 if (numchan == 1)
2620                         numchannel_descr = " (mono)";
2621                 else if (numchan == 2)
2622                         numchannel_descr = " (stereo)";
2623                 else
2624                         numchannel_descr = "";
2625
2626                 if (bootverbose) {
2627                         device_printf(dev, "uaudio_query_formats: found a native %s channel%s %s %dbit %dbytes/subframe X %d channels = %d bytes per sample\n",
2628                                         (dir==UE_DIR_OUT)?"playback":"record",
2629                                         numchannel_descr, freq_descr,
2630                                         prec, subframesize, numchan, subframesize*numchan);
2631                 }
2632                 /*
2633                  * Now start rejecting the ones that don't map to FreeBSD
2634                  */
2635
2636                 if (numchan != 1 && numchan != 2)
2637                         continue;
2638
2639                 for (iterator = accepted_conversion ; iterator->uaudio_fmt != 0 ; iterator++)
2640                         if (iterator->uaudio_fmt == format && iterator->uaudio_prec == prec)
2641                                 break;
2642
2643                 if (iterator->uaudio_fmt == 0)
2644                         continue;
2645
2646                 fmt = iterator->freebsd_fmt;
2647
2648                 if (numchan == 2)
2649                         fmt |= AFMT_STEREO;
2650
2651                 foundcount++;
2652
2653                 if (fmtcount >= maxfmt)
2654                         continue;
2655
2656                 cap->fmtlist[fmtcount++] = fmt;
2657
2658                 if (iscontinuous) {
2659                         freq_min = UA_SAMP_LO(asf1d);
2660                         freq_max = UA_SAMP_HI(asf1d);
2661
2662                         if (cap->minspeed == 0 || freq_min < cap->minspeed)
2663                                 cap->minspeed = freq_min;
2664                         if (cap->maxspeed == 0)
2665                                 cap->maxspeed = cap->minspeed;
2666                         if (freq_max > cap->maxspeed)
2667                                 cap->maxspeed = freq_max;
2668                 } else {
2669                         for (r = 0; r < asf1d->bSamFreqType; r++) {
2670                                 freq = UA_GETSAMP(asf1d, r);
2671                                 if (cap->minspeed == 0 || freq < cap->minspeed)
2672                                         cap->minspeed = freq;
2673                                 if (cap->maxspeed == 0)
2674                                         cap->maxspeed = cap->minspeed;
2675                                 if (freq > cap->maxspeed)
2676                                         cap->maxspeed = freq;
2677                         }
2678                 }
2679         }
2680         cap->fmtlist[fmtcount] = 0;
2681         return foundcount;
2682 }
2683
2684 void
2685 uaudio_chan_set_param_pcm_dma_buff(device_t dev, u_char *start, u_char *end,
2686                 struct pcm_channel *pc, int dir)
2687 {
2688         struct uaudio_softc *sc;
2689         struct chan *ch;
2690
2691         sc = device_get_softc(dev);
2692 #ifndef NO_RECORDING
2693         if (dir == PCMDIR_PLAY)
2694                 ch = &sc->sc_playchan;
2695         else
2696                 ch = &sc->sc_recchan;
2697 #else
2698         ch = &sc->sc_playchan;
2699 #endif
2700
2701         ch->start = start;
2702         ch->end = end;
2703
2704         ch->pcm_ch = pc;
2705
2706         return;
2707 }
2708
2709 void
2710 uaudio_chan_set_param_blocksize(device_t dev, u_int32_t blocksize, int dir)
2711 {
2712         struct uaudio_softc *sc;
2713         struct chan *ch;
2714
2715         sc = device_get_softc(dev);
2716 #ifndef NO_RECORDING
2717         if (dir == PCMDIR_PLAY)
2718                 ch = &sc->sc_playchan;
2719         else
2720                 ch = &sc->sc_recchan;
2721 #else
2722         ch = &sc->sc_playchan;
2723 #endif
2724
2725         ch->blksize = blocksize;
2726
2727         return;
2728 }
2729
2730 int
2731 uaudio_chan_set_param_speed(device_t dev, u_int32_t speed, int reqdir)
2732 {
2733         const struct uaudio_conversion *iterator;
2734         struct uaudio_softc *sc;
2735         struct chan *ch;
2736         int i, r, score, hiscore, bestspeed;
2737
2738         sc = device_get_softc(dev);
2739 #ifndef NO_RECORDING
2740         if (reqdir == PCMDIR_PLAY)
2741                 ch = &sc->sc_playchan;
2742         else
2743                 ch = &sc->sc_recchan;
2744 #else
2745         ch = &sc->sc_playchan;
2746 #endif
2747         /*
2748          * We are successful if we find an endpoint that matches our selected format and it
2749          * supports the requested speed.
2750          */
2751         hiscore = 0;
2752         bestspeed = 1;
2753         for (i = 0; i < sc->sc_nalts; i++) {
2754                 int dir = UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress);
2755                 int format = sc->sc_alts[i].encoding;
2756                 const struct usb_audio_streaming_type1_descriptor *asf1d = sc->sc_alts[i].asf1desc;
2757                 int iscontinuous = asf1d->bSamFreqType == UA_SAMP_CONTNUOUS;
2758
2759                 if ((dir == UE_DIR_OUT) != (reqdir == PCMDIR_PLAY))
2760                         continue;
2761
2762                 for (iterator = accepted_conversion ; iterator->uaudio_fmt != 0 ; iterator++)
2763                         if (iterator->uaudio_fmt != format || iterator->freebsd_fmt != (ch->format&0xfffffff))
2764                                 continue;
2765                         if (iscontinuous) {
2766                                 if (speed >= UA_SAMP_LO(asf1d) && speed <= UA_SAMP_HI(asf1d)) {
2767                                         ch->sample_rate = speed;
2768                                         return speed;
2769                                 } else if (speed < UA_SAMP_LO(asf1d)) {
2770                                         score = 0xfff * speed / UA_SAMP_LO(asf1d);
2771                                         if (score > hiscore) {
2772                                                 bestspeed = UA_SAMP_LO(asf1d);
2773                                                 hiscore = score;
2774                                         }
2775                                 } else if (speed < UA_SAMP_HI(asf1d)) {
2776                                         score = 0xfff * UA_SAMP_HI(asf1d) / speed;
2777                                         if (score > hiscore) {
2778                                                 bestspeed = UA_SAMP_HI(asf1d);
2779                                                 hiscore = score;
2780                                         }
2781                                 }
2782                                 continue;
2783                         }
2784                         for (r = 0; r < asf1d->bSamFreqType; r++) {
2785                                 if (speed == UA_GETSAMP(asf1d, r)) {
2786                                         ch->sample_rate = speed;
2787                                         return speed;
2788                                 }
2789                                 if (speed > UA_GETSAMP(asf1d, r))
2790                                         score = 0xfff * UA_GETSAMP(asf1d, r) / speed;
2791                                 else
2792                                         score = 0xfff * speed / UA_GETSAMP(asf1d, r);
2793                                 if (score > hiscore) { 
2794                                         bestspeed = UA_GETSAMP(asf1d, r);
2795                                         hiscore = score;
2796                                 }
2797                         }
2798         }
2799         if (bestspeed != 1) {
2800                 ch->sample_rate = bestspeed;
2801                 return bestspeed;
2802         }
2803
2804         return 0;
2805 }
2806
2807 int
2808 uaudio_chan_getptr(device_t dev, int dir)
2809 {
2810         struct uaudio_softc *sc;
2811         struct chan *ch;
2812         int ptr;
2813
2814         sc = device_get_softc(dev);
2815 #ifndef NO_RECORDING
2816         if (dir == PCMDIR_PLAY)
2817                 ch = &sc->sc_playchan;
2818         else
2819                 ch = &sc->sc_recchan;
2820 #else
2821         ch = &sc->sc_playchan;
2822 #endif
2823
2824         ptr = ch->cur - ch->start;
2825
2826         return ptr;
2827 }
2828
2829 void
2830 uaudio_chan_set_param_format(device_t dev, u_int32_t format, int dir)
2831 {
2832         struct uaudio_softc *sc;
2833         struct chan *ch;
2834
2835         sc = device_get_softc(dev);
2836 #ifndef NO_RECORDING
2837         if (dir == PCMDIR_PLAY)
2838                 ch = &sc->sc_playchan;
2839         else
2840                 ch = &sc->sc_recchan;
2841 #else
2842         ch = &sc->sc_playchan;
2843 #endif
2844
2845         ch->format = format;
2846
2847         return;
2848 }
2849
2850 int
2851 uaudio_halt_out_dma(device_t dev)
2852 {
2853         struct uaudio_softc *sc;
2854
2855         sc = device_get_softc(dev);
2856
2857         DPRINTF(("uaudio_halt_out_dma: enter\n"));
2858         if (sc->sc_playchan.pipe != NULL) {
2859                 uaudio_chan_close(sc, &sc->sc_playchan);
2860                 sc->sc_playchan.pipe = 0;
2861                 uaudio_chan_free_buffers(sc, &sc->sc_playchan);
2862         }
2863         return (0);
2864 }
2865
2866 int
2867 uaudio_halt_in_dma(device_t dev)
2868 {
2869         struct uaudio_softc *sc;
2870
2871         sc = device_get_softc(dev);
2872
2873         if (sc->sc_dying)
2874                 return (EIO);
2875
2876         DPRINTF(("uaudio_halt_in_dma: enter\n"));
2877         if (sc->sc_recchan.pipe != NULL) {
2878                 uaudio_chan_close(sc, &sc->sc_recchan);
2879                 sc->sc_recchan.pipe = NULL;
2880                 uaudio_chan_free_buffers(sc, &sc->sc_recchan);
2881 /*              sc->sc_recchan.intr = NULL; */
2882         }
2883         return (0);
2884 }
2885
2886 int
2887 uaudio_trigger_input(device_t dev)
2888 {
2889         struct uaudio_softc *sc;
2890         struct chan *ch;
2891         usbd_status err;
2892         int i;
2893
2894         sc = device_get_softc(dev);
2895         ch = &sc->sc_recchan;
2896
2897         if (sc->sc_dying)
2898                 return (EIO);
2899
2900 /*      uaudio_chan_set_param(ch, start, end, blksize) */
2901         if (uaudio_init_params(sc, ch, AUMODE_RECORD))
2902                 return (EIO);
2903
2904         err = uaudio_chan_alloc_buffers(sc, ch);
2905         if (err)
2906                 return (EIO);
2907
2908         err = uaudio_chan_open(sc, ch);
2909         if (err) {
2910                 uaudio_chan_free_buffers(sc, ch);
2911                 return (EIO);
2912         }
2913
2914 /*      ch->intr = intr;
2915         ch->arg = arg; */
2916
2917         crit_enter();
2918         for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
2919                 uaudio_chan_rtransfer(ch);
2920         crit_exit();
2921
2922         return (0);
2923 }
2924
2925 int
2926 uaudio_trigger_output(device_t dev)
2927 {
2928         struct uaudio_softc *sc;
2929         struct chan *ch;
2930         usbd_status err;
2931         int i;
2932
2933         sc = device_get_softc(dev);
2934         ch = &sc->sc_playchan;
2935
2936         if (sc->sc_dying)
2937                 return (EIO);
2938
2939         if (uaudio_init_params(sc, ch, AUMODE_PLAY))
2940                 return (EIO);
2941
2942         err = uaudio_chan_alloc_buffers(sc, ch);
2943         if (err)
2944                 return (EIO);
2945
2946         err = uaudio_chan_open(sc, ch);
2947         if (err) {
2948                 uaudio_chan_free_buffers(sc, ch);
2949                 return (EIO);
2950         }
2951
2952         crit_enter();
2953         for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
2954                 uaudio_chan_ptransfer(ch);
2955         crit_exit();
2956
2957         return (0);
2958 }
2959
2960 u_int32_t
2961 uaudio_query_mix_info(device_t dev)
2962 {
2963         int i;
2964         u_int32_t mask = 0;
2965         struct uaudio_softc *sc;
2966         struct mixerctl *mc;
2967
2968         sc = device_get_softc(dev);
2969         for (i=0; i < sc->sc_nctls; i++) {
2970                 mc = &sc->sc_ctls[i];
2971                 if (mc->ctl != SOUND_MIXER_NRDEVICES) {
2972                         /* Set device mask bits. 
2973                            See /usr/include/machine/soundcard.h */
2974                         mask |= (1 << mc->ctl);
2975                 }
2976         }
2977         return mask;
2978 }
2979
2980 u_int32_t
2981 uaudio_query_recsrc_info(device_t dev)
2982 {
2983         int i, rec_selector_id;
2984         u_int32_t mask = 0;
2985         struct uaudio_softc *sc;
2986         struct mixerctl *mc;
2987
2988         sc = device_get_softc(dev);
2989         rec_selector_id = -1;
2990         for (i=0; i < sc->sc_nctls; i++) {
2991                 mc = &sc->sc_ctls[i];
2992                 if (mc->ctl == SOUND_MIXER_NRDEVICES && 
2993                     mc->type == MIX_SELECTOR && mc->class == UAC_RECORD) {
2994                         if (rec_selector_id == -1) {
2995                                 rec_selector_id = i;
2996                         } else {
2997                                 kprintf("There are many selectors.  Can't recognize which selector is a record source selector.\n");
2998                                 return mask;
2999                         }
3000                 }
3001         }
3002         if (rec_selector_id == -1)
3003                 return mask;
3004         mc = &sc->sc_ctls[rec_selector_id];
3005         for (i = mc->minval; i <= mc->maxval; i++) {
3006                 if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES)
3007                         continue;
3008                 mask |= 1 << mc->slctrtype[i - 1];
3009         }
3010         return mask;
3011 }
3012
3013 void
3014 uaudio_mixer_set(device_t dev, unsigned type, unsigned left, unsigned right)
3015 {
3016         int i;
3017         struct uaudio_softc *sc;
3018         struct mixerctl *mc;
3019
3020         sc = device_get_softc(dev);
3021         for (i=0; i < sc->sc_nctls; i++) {
3022                 mc = &sc->sc_ctls[i];
3023                 if (mc->ctl == type) {
3024                         if (mc->nchan == 2) {
3025                                 /* set Right */
3026                                 uaudio_ctl_set(sc, SET_CUR, mc, 1, (int)(right*255)/100);
3027                         }
3028                         /* set Left or Mono */
3029                         uaudio_ctl_set(sc, SET_CUR, mc, 0, (int)(left*255)/100);
3030                 }
3031         }
3032         return;
3033 }
3034
3035 u_int32_t
3036 uaudio_mixer_setrecsrc(device_t dev, u_int32_t src)
3037 {
3038         int i, rec_selector_id;
3039         struct uaudio_softc *sc;
3040         struct mixerctl *mc;
3041
3042         sc = device_get_softc(dev);
3043         rec_selector_id = -1;
3044         for (i=0; i < sc->sc_nctls; i++) {
3045                 mc = &sc->sc_ctls[i];
3046                 if (mc->ctl == SOUND_MIXER_NRDEVICES && 
3047                     mc->type == MIX_SELECTOR && mc->class == UAC_RECORD) {
3048                         if (rec_selector_id == -1) {
3049                                 rec_selector_id = i;
3050                         } else {
3051                                 return src; /* Can't recognize which selector is record source selector */
3052                         }
3053                 }
3054         }
3055         if (rec_selector_id == -1)
3056                 return src;
3057         mc = &sc->sc_ctls[rec_selector_id];
3058         for (i = mc->minval; i <= mc->maxval; i++) {
3059                 if (src != (1 << mc->slctrtype[i - 1]))
3060                         continue;
3061                 uaudio_ctl_set(sc, SET_CUR, mc, 0, i);
3062                 return (1 << mc->slctrtype[i - 1]);
3063         }
3064         uaudio_ctl_set(sc, SET_CUR, mc, 0, mc->minval);
3065         return (1 << mc->slctrtype[mc->minval - 1]);
3066 }
3067
3068 static int
3069 uaudio_sndstat_prepare_pcm(struct sbuf *s, device_t dev, int verbose)
3070 {
3071         struct snddev_info *d;
3072         struct snddev_channel *sce;
3073         struct pcm_channel *c;
3074         struct pcm_feeder *f;
3075         int pc, rc, vc;
3076         device_t pa_dev = device_get_parent(dev);
3077         struct uaudio_softc *sc = device_get_softc(pa_dev);
3078
3079         if (verbose < 1)
3080                 return 0;
3081
3082         d = device_get_softc(dev);
3083         if (!d)
3084                 return ENXIO;
3085
3086         snd_mtxlock(d->lock);
3087         if (SLIST_EMPTY(&d->channels)) {
3088                 sbuf_printf(s, " (mixer only)");
3089                 snd_mtxunlock(d->lock);
3090                 return 0;
3091         }
3092         pc = rc = vc = 0;
3093         SLIST_FOREACH(sce, &d->channels, link) {
3094                 c = sce->channel;
3095                 if (c->direction == PCMDIR_PLAY) {
3096                         if (c->flags & CHN_F_VIRTUAL)
3097                                 vc++;
3098                         else
3099                                 pc++;
3100                 } else
3101                         rc++;
3102         }
3103         sbuf_printf(s, " (%dp/%dr/%dv channels%s%s)", 
3104                         d->playcount, d->reccount, d->vchancount,
3105                         (d->flags & SD_F_SIMPLEX)? "" : " duplex",
3106 #ifdef USING_DEVFS
3107                         (device_get_unit(dev) == snd_unit)? " default" : ""
3108 #else
3109                         ""
3110 #endif
3111                         );
3112
3113         if (sc->uaudio_sndstat_flag != 0) {
3114                 sbuf_cat(s, sbuf_data(&(sc->uaudio_sndstat)));
3115         }
3116
3117         if (verbose <= 1) {
3118                 snd_mtxunlock(d->lock);
3119                 return 0;
3120         }
3121
3122         SLIST_FOREACH(sce, &d->channels, link) {
3123                 c = sce->channel;
3124                 sbuf_printf(s, "\n\t");
3125
3126                 KASSERT(c->bufhard != NULL && c->bufsoft != NULL,
3127                         ("hosed pcm channel setup"));
3128
3129                 /* it would be better to indent child channels */
3130                 sbuf_printf(s, "%s[%s]: ", c->parentchannel? c->parentchannel->name : "", c->name);
3131                 sbuf_printf(s, "spd %d", c->speed);
3132                 if (c->speed != sndbuf_getspd(c->bufhard))
3133                         sbuf_printf(s, "/%d", sndbuf_getspd(c->bufhard));
3134                 sbuf_printf(s, ", fmt 0x%08x", c->format);
3135                 if (c->format != sndbuf_getfmt(c->bufhard))
3136                         sbuf_printf(s, "/0x%08x", sndbuf_getfmt(c->bufhard));
3137                 sbuf_printf(s, ", flags 0x%08x, 0x%08x", c->flags, c->feederflags);
3138                 if (c->pid != -1)
3139                         sbuf_printf(s, ", pid %d", c->pid);
3140                 sbuf_printf(s, "\n\t");
3141
3142                 sbuf_printf(s, "interrupts %d, ", c->interrupts);
3143                 if (c->direction == PCMDIR_REC)
3144                         sbuf_printf(s, "overruns %d, hfree %d, sfree %d",
3145                                 c->xruns, sndbuf_getfree(c->bufhard), sndbuf_getfree(c->bufsoft));
3146                 else
3147                         sbuf_printf(s, "underruns %d, ready %d",
3148                                 c->xruns, sndbuf_getready(c->bufsoft));
3149                 sbuf_printf(s, "\n\t");
3150
3151                 sbuf_printf(s, "{%s}", (c->direction == PCMDIR_REC)? "hardware" : "userland");
3152                 sbuf_printf(s, " -> ");
3153                 f = c->feeder;
3154                 while (f->source != NULL)
3155                         f = f->source;
3156                 while (f != NULL) {
3157                         sbuf_printf(s, "%s", f->class->name);
3158                         if (f->desc->type == FEEDER_FMT)
3159                                 sbuf_printf(s, "(0x%08x -> 0x%08x)", f->desc->in, f->desc->out);
3160                         if (f->desc->type == FEEDER_RATE)
3161                                 sbuf_printf(s, "(%d -> %d)", FEEDER_GET(f, FEEDRATE_SRC), FEEDER_GET(f, FEEDRATE_DST));
3162                         if (f->desc->type == FEEDER_ROOT || f->desc->type == FEEDER_MIXER)
3163                                 sbuf_printf(s, "(0x%08x)", f->desc->out);
3164                         sbuf_printf(s, " -> ");
3165                         f = f->parent;
3166                 }
3167                 sbuf_printf(s, "{%s}", (c->direction == PCMDIR_REC)? "userland" : "hardware");
3168         }
3169         snd_mtxunlock(d->lock);
3170
3171         return 0;
3172 }
3173
3174 void
3175 uaudio_sndstat_register(device_t dev)
3176 {
3177         struct snddev_info *d = device_get_softc(dev);
3178         sndstat_register(dev, d->status, uaudio_sndstat_prepare_pcm);
3179 }
3180         
3181 static int
3182 audio_attach_mi(device_t dev)
3183 {
3184         device_t child;
3185         struct sndcard_func *func;
3186
3187         /* Attach the children. */
3188         /* PCM Audio */
3189         func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO);
3190         if (func == NULL)
3191                 return (ENOMEM);
3192         func->func = SCF_PCM;
3193         child = device_add_child(dev, "pcm", -1);
3194         device_set_ivars(child, func);
3195
3196         bus_generic_attach(dev);
3197
3198         return 0; /* XXXXX */
3199 }
3200
3201 DRIVER_MODULE(uaudio, uhub, uaudio_driver, uaudio_devclass, usbd_driver_load, 0);
3202 MODULE_VERSION(uaudio, 1);
3203