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