67735b149ed8df7f4e6d9839db7dfa613b476537
[dragonfly.git] / sys / dev / sound / usb / uaudio.c
1 /*      $NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $ */
2 /*      $FreeBSD: src/sys/dev/sound/usb/uaudio.c,v 1.14.2.2 2006/04/04 17:34:10 ariff Exp $ */
3 /*      $DragonFly: src/sys/dev/sound/usb/uaudio.c,v 1.15 2007/07/01 21:24:02 hasso Exp $: */
4
5 /*-
6  * Copyright (c) 1999 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *        This product includes software developed by the NetBSD
24  *        Foundation, Inc. and its contributors.
25  * 4. Neither the name of The NetBSD Foundation nor the names of its
26  *    contributors may be used to endorse or promote products derived
27  *    from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 /*
43  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
44  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
45  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
46  */
47
48 #include <sys/cdefs.h>
49 #if defined(__NetBSD__) || defined(__OpenBSD__)
50 __KERNEL_RCSID(0, "$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $");
51 #endif
52
53 /*
54  * Also merged:
55  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
56  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
57  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
58  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
59  */
60
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/kernel.h>
64 #include <sys/malloc.h>
65 #if defined(__NetBSD__) || defined(__OpenBSD__)
66 #include <sys/device.h>
67 #include <sys/ioctl.h>
68 #endif
69 #include <sys/tty.h>
70 #include <sys/file.h>
71 #include <sys/reboot.h>         /* for bootverbose */
72 #include <sys/select.h>
73 #include <sys/proc.h>
74 #if defined(__NetBSD__) || defined(__OpenBSD__)
75 #include <sys/device.h>
76 #elif defined(__FreeBSD__) || defined(__DragonFly__)
77 #include <sys/module.h>
78 #include <sys/bus.h>
79 #include <sys/conf.h>
80 #endif
81 #include <sys/poll.h>
82 #if defined(__FreeBSD__)
83 #include <sys/sysctl.h>
84 #include <sys/sbuf.h>
85 #elif defined(__DragonFly__)
86 #include <sys/sysctl.h>
87 #include <sys/thread2.h>
88 #endif
89
90 #if defined(__NetBSD__) || defined(__OpenBSD__)
91 #include <sys/audioio.h>
92 #include <dev/audio_if.h>
93 #include <dev/audiovar.h>
94 #include <dev/mulaw.h>
95 #include <dev/auconv.h>
96 #elif defined(__FreeBSD__) || defined(__DragonFly__)
97 #include <dev/sound/pcm/sound.h>        /* XXXXX */
98 #include <dev/sound/chip.h>
99 #include "feeder_if.h"
100 #endif
101
102 #include <bus/usb/usb.h>
103 #include <bus/usb/usbdi.h>
104 #include <bus/usb/usbdi_util.h>
105 #include <bus/usb/usb_quirks.h>
106
107 #if defined(__NetBSD__) || defined(__OpenBSD__)
108 #include <dev/usb/uaudioreg.h>
109 #elif defined(__FreeBSD__) || defined(__DragonFly__)
110 #include <dev/sound/usb/uaudioreg.h>
111 #include <dev/sound/usb/uaudio.h>
112 #endif
113
114 #if defined(__NetBSD__) || defined(__OpenBSD__)
115 /* #define UAUDIO_DEBUG */
116 #else
117 /* #define USB_DEBUG */
118 #endif
119 /* #define UAUDIO_MULTIPLE_ENDPOINTS */
120 #ifdef USB_DEBUG
121 #define DPRINTF(x)      do { if (uaudiodebug) kprintf x; } while (0)
122 #define DPRINTFN(n,x)   do { if (uaudiodebug>(n)) kprintf x; } while (0)
123 int     uaudiodebug = 0;
124 #if defined(__FreeBSD__) || defined(__DragonFly__)
125 SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
126 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
127            &uaudiodebug, 0, "uaudio debug level");
128 #endif
129 #else
130 #define DPRINTF(x)
131 #define DPRINTFN(n,x)
132 #endif
133
134 #define UAUDIO_NCHANBUFS 6      /* number of outstanding request */
135 #if defined(__NetBSD__) || defined(__OpenBSD__)
136 #define UAUDIO_NFRAMES   10     /* ms of sound in each request */
137 #elif defined(__FreeBSD__) || defined(__DragonFly__)
138 #define UAUDIO_NFRAMES   20     /* ms of sound in each request */
139 #endif
140
141
142 #define MIX_MAX_CHAN 8
143 struct mixerctl {
144         uint16_t        wValue[MIX_MAX_CHAN]; /* using nchan */
145         uint16_t        wIndex;
146         uint8_t         nchan;
147         uint8_t         type;
148 #define MIX_ON_OFF      1
149 #define MIX_SIGNED_16   2
150 #define MIX_UNSIGNED_16 3
151 #define MIX_SIGNED_8    4
152 #define MIX_SELECTOR    5
153 #define MIX_SIZE(n) ((n) == MIX_SIGNED_16 || (n) == MIX_UNSIGNED_16 ? 2 : 1)
154 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
155         int             minval, maxval;
156         u_int           delta;
157         u_int           mul;
158 #if defined(__FreeBSD__) || defined(__DragonFly__) /* XXXXX */
159         unsigned        ctl;
160 #define MAX_SELECTOR_INPUT_PIN 256
161         uint8_t         slctrtype[MAX_SELECTOR_INPUT_PIN];
162 #endif
163         uint8_t         class;
164 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
165         char            ctlname[MAX_AUDIO_DEV_LEN];
166         char            *ctlunit;
167 #endif
168 };
169 #define MAKE(h,l) (((h) << 8) | (l))
170
171 struct as_info {
172         uint8_t         alt;
173         uint8_t         encoding;
174         uint8_t         attributes; /* Copy of bmAttributes of
175                                      * usb_audio_streaming_endpoint_descriptor
176                                      */
177         usbd_interface_handle   ifaceh;
178         const usb_interface_descriptor_t *idesc;
179         const usb_endpoint_descriptor_audio_t *edesc;
180         const usb_endpoint_descriptor_audio_t *edesc1;
181         const struct usb_audio_streaming_type1_descriptor *asf1desc;
182         int             sc_busy;        /* currently used */
183 };
184
185 struct chan {
186 #if defined(__NetBSD__) || defined(__OpenBSD__)
187         void    (*intr)(void *);        /* DMA completion intr handler */
188         void    *arg;           /* arg for intr() */
189 #else
190         struct pcm_channel *pcm_ch;
191 #endif
192         usbd_pipe_handle pipe;
193         usbd_pipe_handle sync_pipe;
194
195         u_int   sample_size;
196         u_int   sample_rate;
197         u_int   bytes_per_frame;
198         u_int   fraction;       /* fraction/1000 is the extra samples/frame */
199         u_int   residue;        /* accumulates the fractional samples */
200
201         u_char  *start;         /* upper layer buffer start */
202         u_char  *end;           /* upper layer buffer end */
203         u_char  *cur;           /* current position in upper layer buffer */
204         int     blksize;        /* chunk size to report up */
205         int     transferred;    /* transferred bytes not reported up */
206
207         int     altidx;         /* currently used altidx */
208
209         int     curchanbuf;
210         struct chanbuf {
211                 struct chan     *chan;
212                 usbd_xfer_handle xfer;
213                 u_char          *buffer;
214                 u_int16_t       sizes[UAUDIO_NFRAMES];
215                 u_int16_t       offsets[UAUDIO_NFRAMES];
216                 u_int16_t       size;
217         } chanbufs[UAUDIO_NCHANBUFS];
218
219         struct uaudio_softc *sc; /* our softc */
220 #if defined(__FreeBSD__) || defined(__DragonFly__)
221         u_int32_t format;
222         int     precision;
223         int     channels;
224 #endif
225 };
226
227 struct uaudio_softc {
228         device_t        sc_dev;         /* base device */
229         usbd_device_handle sc_udev;     /* USB device */
230         int             sc_ac_iface;    /* Audio Control interface */
231         usbd_interface_handle   sc_ac_ifaceh;
232         struct chan     sc_playchan;    /* play channel */
233         struct chan     sc_recchan;     /* record channel */
234         int             sc_nullalt;
235         int             sc_audio_rev;
236         struct as_info  *sc_alts;       /* alternate settings */
237         int             sc_nalts;       /* # of alternate settings */
238         int             sc_altflags;
239 #define HAS_8           0x01
240 #define HAS_16          0x02
241 #define HAS_8U          0x04
242 #define HAS_ALAW        0x08
243 #define HAS_MULAW       0x10
244 #define UA_NOFRAC       0x20            /* don't do sample rate adjustment */
245 #define HAS_24          0x40
246 #define HAS_32          0x80
247         int             sc_mode;        /* play/record capability */
248         struct mixerctl *sc_ctls;       /* mixer controls */
249         int             sc_nctls;       /* # of mixer controls */
250         device_t        sc_audiodev;
251         char            sc_dying;
252 #if defined(__FreeBSD__) || defined(__DragonFly__)
253         struct sbuf     uaudio_sndstat;
254         int             uaudio_sndstat_flag;
255 #endif
256 };
257
258 struct terminal_list {
259         int size;
260         uint16_t terminals[1];
261 };
262 #define TERMINAL_LIST_SIZE(N)   (offsetof(struct terminal_list, terminals) \
263                                 + sizeof(uint16_t) * (N))
264
265 struct io_terminal {
266         union {
267                 const usb_descriptor_t *desc;
268                 const struct usb_audio_input_terminal *it;
269                 const struct usb_audio_output_terminal *ot;
270                 const struct usb_audio_mixer_unit *mu;
271                 const struct usb_audio_selector_unit *su;
272                 const struct usb_audio_feature_unit *fu;
273                 const struct usb_audio_processing_unit *pu;
274                 const struct usb_audio_extension_unit *eu;
275         } d;
276         int inputs_size;
277         struct terminal_list **inputs; /* list of source input terminals */
278         struct terminal_list *output; /* list of destination output terminals */
279         int direct;             /* directly connected to an output terminal */
280 };
281
282 #define UAC_OUTPUT      0
283 #define UAC_INPUT       1
284 #define UAC_EQUAL       2
285 #define UAC_RECORD      3
286 #define UAC_NCLASSES    4
287 #ifdef USB_DEBUG
288 #if defined(__FreeBSD__) || defined(__DragonFly__)
289 #define AudioCinputs    "inputs"
290 #define AudioCoutputs   "outputs"
291 #define AudioCrecord    "record"
292 #define AudioCequalization      "equalization"
293 #endif
294 static const char *uac_names[] = {
295         AudioCoutputs, AudioCinputs, AudioCequalization, AudioCrecord,
296 };
297 #endif
298
299 static usbd_status uaudio_identify_ac
300         (struct uaudio_softc *, const usb_config_descriptor_t *);
301 static usbd_status uaudio_identify_as
302         (struct uaudio_softc *, const usb_config_descriptor_t *);
303 static usbd_status uaudio_process_as
304         (struct uaudio_softc *, const char *, int *, int,
305          const usb_interface_descriptor_t *);
306
307 static void     uaudio_add_alt(struct uaudio_softc *, const struct as_info *);
308
309 static const usb_interface_descriptor_t *uaudio_find_iface
310         (const char *, int, int *, int);
311
312 static void     uaudio_mixer_add_ctl(struct uaudio_softc *, struct mixerctl *);
313
314 #if defined(__NetBSD__) || defined(__OpenBSD__)
315 static char     *uaudio_id_name
316         (struct uaudio_softc *, const struct io_terminal *, int);
317 #endif
318
319 #ifdef USB_DEBUG
320 static void     uaudio_dump_cluster(const struct usb_audio_cluster *);
321 #endif
322 static struct usb_audio_cluster uaudio_get_cluster
323         (int, const struct io_terminal *);
324 static void     uaudio_add_input
325         (struct uaudio_softc *, const struct io_terminal *, int);
326 static void     uaudio_add_output
327         (struct uaudio_softc *, const struct io_terminal *, int);
328 static void     uaudio_add_mixer
329         (struct uaudio_softc *, const struct io_terminal *, int);
330 static void     uaudio_add_selector
331         (struct uaudio_softc *, const struct io_terminal *, int);
332 #ifdef USB_DEBUG
333 static const char *uaudio_get_terminal_name(int);
334 #endif
335 static int      uaudio_determine_class
336         (const struct io_terminal *, struct mixerctl *);
337 #if defined(__FreeBSD__) || defined(__DragonFly__)
338 static const int uaudio_feature_name(const struct io_terminal *,
339                     struct mixerctl *);
340 #else
341 static const char *uaudio_feature_name
342         (const struct io_terminal *, struct mixerctl *);
343 #endif
344 static void     uaudio_add_feature
345         (struct uaudio_softc *, const struct io_terminal *, int);
346 static void     uaudio_add_processing_updown
347         (struct uaudio_softc *, const struct io_terminal *, int);
348 static void     uaudio_add_processing
349         (struct uaudio_softc *, const struct io_terminal *, int);
350 static void     uaudio_add_extension
351         (struct uaudio_softc *, const struct io_terminal *, int);
352 static struct terminal_list *uaudio_merge_terminal_list
353         (const struct io_terminal *);
354 static struct terminal_list *uaudio_io_terminaltype
355         (int, struct io_terminal *, int);
356 static usbd_status uaudio_identify
357         (struct uaudio_softc *, const usb_config_descriptor_t *);
358
359 static int      uaudio_signext(int, int);
360 #if defined(__NetBSD__) || defined(__OpenBSD__)
361 static int      uaudio_value2bsd(struct mixerctl *, int);
362 #endif
363 static int      uaudio_bsd2value(struct mixerctl *, int);
364 static int      uaudio_get(struct uaudio_softc *, int, int, int, int, int);
365 #if defined(__NetBSD__) || defined(__OpenBSD__)
366 static int      uaudio_ctl_get
367         (struct uaudio_softc *, int, struct mixerctl *, int);
368 #endif
369 static void     uaudio_set
370         (struct uaudio_softc *, int, int, int, int, int, int);
371 static void     uaudio_ctl_set
372         (struct uaudio_softc *, int, struct mixerctl *, int, int);
373
374 static usbd_status uaudio_set_speed(struct uaudio_softc *, int, u_int);
375
376 static usbd_status uaudio_chan_open(struct uaudio_softc *, struct chan *);
377 static void     uaudio_chan_close(struct uaudio_softc *, struct chan *);
378 static usbd_status uaudio_chan_alloc_buffers
379         (struct uaudio_softc *, struct chan *);
380 static void     uaudio_chan_free_buffers(struct uaudio_softc *, struct chan *);
381
382 #if defined(__NetBSD__) || defined(__OpenBSD__)
383 static void     uaudio_chan_init
384         (struct chan *, int, const struct audio_params *, int);
385 static void     uaudio_chan_set_param(struct chan *, u_char *, u_char *, int);
386 #endif
387
388 static void     uaudio_chan_ptransfer(struct chan *);
389 static void     uaudio_chan_pintr
390         (usbd_xfer_handle, usbd_private_handle, usbd_status);
391
392 static void     uaudio_chan_rtransfer(struct chan *);
393 static void     uaudio_chan_rintr
394         (usbd_xfer_handle, usbd_private_handle, usbd_status);
395
396 #if defined(__NetBSD__) || defined(__OpenBSD__)
397 static int      uaudio_open(void *, int);
398 static void     uaudio_close(void *);
399 static int      uaudio_drain(void *);
400 static int      uaudio_query_encoding(void *, struct audio_encoding *);
401 static void     uaudio_get_minmax_rates
402         (int, const struct as_info *, const struct audio_params *,
403          int, u_long *, u_long *);
404 static int      uaudio_match_alt_sub
405         (int, const struct as_info *, const struct audio_params *, int, u_long);
406 static int      uaudio_match_alt_chan
407         (int, const struct as_info *, struct audio_params *, int);
408 static int      uaudio_match_alt
409         (int, const struct as_info *, struct audio_params *, int);
410 static int      uaudio_set_params
411         (void *, int, int, struct audio_params *, struct audio_params *);
412 static int      uaudio_round_blocksize(void *, int);
413 static int      uaudio_trigger_output
414         (void *, void *, void *, int, void (*)(void *), void *,
415          struct audio_params *);
416 static int      uaudio_trigger_input
417         (void *, void *, void *, int, void (*)(void *), void *,
418          struct audio_params *);
419 static int      uaudio_halt_in_dma(void *);
420 static int      uaudio_halt_out_dma(void *);
421 static int      uaudio_getdev(void *, struct audio_device *);
422 static int      uaudio_mixer_set_port(void *, mixer_ctrl_t *);
423 static int      uaudio_mixer_get_port(void *, mixer_ctrl_t *);
424 static int      uaudio_query_devinfo(void *, mixer_devinfo_t *);
425 static int      uaudio_get_props(void *);
426
427 static const struct audio_hw_if uaudio_hw_if = {
428         uaudio_open,
429         uaudio_close,
430         uaudio_drain,
431         uaudio_query_encoding,
432         uaudio_set_params,
433         uaudio_round_blocksize,
434         NULL,
435         NULL,
436         NULL,
437         NULL,
438         NULL,
439         uaudio_halt_out_dma,
440         uaudio_halt_in_dma,
441         NULL,
442         uaudio_getdev,
443         NULL,
444         uaudio_mixer_set_port,
445         uaudio_mixer_get_port,
446         uaudio_query_devinfo,
447         NULL,
448         NULL,
449         NULL,
450         NULL,
451         uaudio_get_props,
452         uaudio_trigger_output,
453         uaudio_trigger_input,
454         NULL,
455 };
456
457 static struct audio_device uaudio_device = {
458         "USB audio",
459         "",
460         "uaudio"
461 };
462
463 #elif defined(__FreeBSD__) || defined(__DragonFly__)
464 static int      audio_attach_mi(device_t);
465 static int      uaudio_init_params(struct uaudio_softc * sc, struct chan *ch, int mode);
466 static int      uaudio_sndstat_prepare_pcm(struct sbuf *s, device_t dev, int verbose);
467
468 /* for NetBSD compatibirity */
469 #define AUMODE_PLAY     0x01
470 #define AUMODE_RECORD   0x02
471
472 #define AUDIO_PROP_FULLDUPLEX   0x01
473
474 #define AUDIO_ENCODING_ULAW             1
475 #define AUDIO_ENCODING_ALAW             2
476 #define AUDIO_ENCODING_SLINEAR_LE       6
477 #define AUDIO_ENCODING_SLINEAR_BE       7
478 #define AUDIO_ENCODING_ULINEAR_LE       8
479 #define AUDIO_ENCODING_ULINEAR_BE       9
480
481 #endif  /* FreeBSD || DragonFly */
482
483
484 #if defined(__NetBSD__) || defined(__OpenBSD__)
485
486 USB_DECLARE_DRIVER(uaudio);
487
488 #elif defined(__FreeBSD__) || defined(__DragonFly__)
489
490 USB_DECLARE_DRIVER_INIT(uaudio,
491                 DEVMETHOD(device_suspend, bus_generic_suspend),
492                 DEVMETHOD(device_resume, bus_generic_resume),
493                 DEVMETHOD(device_shutdown, bus_generic_shutdown),
494                 DEVMETHOD(bus_print_child, bus_generic_print_child)
495                 );
496 #endif
497
498
499 static int
500 uaudio_match(device_t self)
501 {
502         struct usb_attach_arg *uaa = device_get_ivars(self);
503         usb_interface_descriptor_t *id;
504
505         if (uaa->iface == NULL)
506                 return UMATCH_NONE;
507
508         id = usbd_get_interface_descriptor(uaa->iface);
509         /* Trigger on the control interface. */
510         if (id == NULL ||
511             id->bInterfaceClass != UICLASS_AUDIO ||
512             id->bInterfaceSubClass != UISUBCLASS_AUDIOCONTROL ||
513             (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_AUDIO))
514                 return UMATCH_NONE;
515
516         return UMATCH_IFACECLASS_IFACESUBCLASS;
517 }
518
519 static int
520 uaudio_attach(device_t self)
521 {
522         struct uaudio_softc *sc = device_get_softc(self);
523         struct usb_attach_arg *uaa = device_get_ivars(self);
524         usb_interface_descriptor_t *id;
525         usb_config_descriptor_t *cdesc;
526         char devinfo[1024];
527         usbd_status err;
528         int i, j, found;
529
530 #if defined(__FreeBSD__) || defined(__DragonFly__)
531         usbd_devinfo(uaa->device, 0, devinfo);
532         sc->sc_dev = self;
533         device_set_desc_copy(self, devinfo);
534 #else
535         usbd_devinfo(uaa->device, 0, devinfo, sizeof(devinfo));
536         kprintf(": %s\n", devinfo);
537 #endif
538
539         sc->sc_udev = uaa->device;
540
541         cdesc = usbd_get_config_descriptor(sc->sc_udev);
542         if (cdesc == NULL) {
543                 kprintf("%s: failed to get configuration descriptor\n",
544                        device_get_nameunit(sc->sc_dev));
545                 return ENXIO;
546         }
547
548         err = uaudio_identify(sc, cdesc);
549         if (err) {
550                 kprintf("%s: audio descriptors make no sense, error=%d\n",
551                        device_get_nameunit(sc->sc_dev), err);
552                 return ENXIO;
553         }
554
555         sc->sc_ac_ifaceh = uaa->iface;
556         /* Pick up the AS interface. */
557         for (i = 0; i < uaa->nifaces; i++) {
558                 if (uaa->ifaces[i] == NULL)
559                         continue;
560                 id = usbd_get_interface_descriptor(uaa->ifaces[i]);
561                 if (id == NULL)
562                         continue;
563                 found = 0;
564                 for (j = 0; j < sc->sc_nalts; j++) {
565                         if (id->bInterfaceNumber ==
566                             sc->sc_alts[j].idesc->bInterfaceNumber) {
567                                 sc->sc_alts[j].ifaceh = uaa->ifaces[i];
568                                 found = 1;
569                         }
570                 }
571                 if (found)
572                         uaa->ifaces[i] = NULL;
573         }
574
575         for (j = 0; j < sc->sc_nalts; j++) {
576                 if (sc->sc_alts[j].ifaceh == NULL) {
577                         kprintf("%s: alt %d missing AS interface(s)\n",
578                             device_get_nameunit(sc->sc_dev), j);
579                         return ENXIO;
580                 }
581         }
582
583         kprintf("%s: audio rev %d.%02x\n", device_get_nameunit(sc->sc_dev),
584                sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff);
585
586         sc->sc_playchan.sc = sc->sc_recchan.sc = sc;
587         sc->sc_playchan.altidx = -1;
588         sc->sc_recchan.altidx = -1;
589
590         if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_FRAC)
591                 sc->sc_altflags |= UA_NOFRAC;
592
593 #ifndef USB_DEBUG
594         if (bootverbose)
595 #endif
596                 kprintf("%s: %d mixer controls\n", device_get_nameunit(sc->sc_dev),
597                     sc->sc_nctls);
598
599 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
600         usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
601                            sc->sc_dev);
602 #endif
603
604         DPRINTF(("uaudio_attach: doing audio_attach_mi\n"));
605 #if defined(__OpenBSD__)
606         audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
607 #elif defined(__NetBSD__)
608         sc->sc_audiodev = audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
609 #elif defined(__FreeBSD__) || defined(__DragonFly__)
610         sc->sc_dying = 0;
611         if (audio_attach_mi(sc->sc_dev)) {
612                 kprintf("audio_attach_mi failed\n");
613                 return ENXIO;
614         }
615 #endif
616
617         return 0;
618 }
619
620 #if defined(__NetBSD__) || defined(__OpenBSD__)
621 int
622 uaudio_activate(device_t self, enum devact act)
623 {
624         struct uaudio_softc *sc;
625         int rv;
626
627         sc = (struct uaudio_softc *)self;
628         rv = 0;
629         switch (act) {
630         case DVACT_ACTIVATE:
631                 return EOPNOTSUPP;
632
633         case DVACT_DEACTIVATE:
634                 if (sc->sc_audiodev != NULL)
635                         rv = config_deactivate(sc->sc_audiodev);
636                 sc->sc_dying = 1;
637                 break;
638         }
639         return rv;
640 }
641 #endif
642
643 #if defined(__NetBSD__) || defined(__OpenBSD__)
644 int
645 uaudio_detach(device_t self, int flags)
646 {
647         struct uaudio_softc *sc;
648         int rv;
649
650         sc = (struct uaudio_softc *)self;
651         rv = 0;
652         /* Wait for outstanding requests to complete. */
653         usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
654
655         if (sc->sc_audiodev != NULL)
656                 rv = config_detach(sc->sc_audiodev, flags);
657
658         usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
659                            sc->sc_dev);
660
661         return rv;
662 }
663 #elif defined(__FreeBSD__) || defined(__DragonFly__)
664
665 static int
666 uaudio_detach(device_t self)
667 {
668         struct uaudio_softc *sc = device_get_softc(self);
669
670         sbuf_delete(&(sc->uaudio_sndstat));
671         sc->uaudio_sndstat_flag = 0;
672
673         sc->sc_dying = 1;
674
675 #if 0 /* XXX */
676         /* Wait for outstanding requests to complete. */
677         usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
678 #endif
679
680         /* do nothing ? */
681         return bus_generic_detach(sc->sc_dev);
682 }
683 #endif
684
685 #if defined(__NetBSD__) || defined(__OpenBSD__)
686 static int
687 uaudio_query_encoding(void *addr, struct audio_encoding *fp)
688 {
689         struct uaudio_softc *sc;
690         int flags;
691         int idx;
692
693         sc = addr;
694         flags = sc->sc_altflags;
695         if (sc->sc_dying)
696                 return EIO;
697
698         if (sc->sc_nalts == 0 || flags == 0)
699                 return ENXIO;
700
701         idx = fp->index;
702         switch (idx) {
703         case 0:
704                 strlcpy(fp->name, AudioEulinear, sizeof(fp->name));
705                 fp->encoding = AUDIO_ENCODING_ULINEAR;
706                 fp->precision = 8;
707                 fp->flags = flags&HAS_8U ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
708                 return (0);
709         case 1:
710                 strlcpy(fp->name, AudioEmulaw, sizeof(fp->name));
711                 fp->encoding = AUDIO_ENCODING_ULAW;
712                 fp->precision = 8;
713                 fp->flags = flags&HAS_MULAW ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
714                 return (0);
715         case 2:
716                 strlcpy(fp->name, AudioEalaw, sizeof(fp->name));
717                 fp->encoding = AUDIO_ENCODING_ALAW;
718                 fp->precision = 8;
719                 fp->flags = flags&HAS_ALAW ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
720                 return (0);
721         case 3:
722                 strlcpy(fp->name, AudioEslinear, sizeof(fp->name));
723                 fp->encoding = AUDIO_ENCODING_SLINEAR;
724                 fp->precision = 8;
725                 fp->flags = flags&HAS_8 ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
726                 return (0);
727         case 4:
728                 strlcpy(fp->name, AudioEslinear_le, sizeof(fp->name));
729                 fp->encoding = AUDIO_ENCODING_SLINEAR_LE;
730                 fp->precision = 16;
731                 fp->flags = 0;
732                 return (0);
733         case 5:
734                 strlcpy(fp->name, AudioEulinear_le, sizeof(fp->name));
735                 fp->encoding = AUDIO_ENCODING_ULINEAR_LE;
736                 fp->precision = 16;
737                 fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
738                 return (0);
739         case 6:
740                 strlcpy(fp->name, AudioEslinear_be, sizeof(fp->name));
741                 fp->encoding = AUDIO_ENCODING_SLINEAR_BE;
742                 fp->precision = 16;
743                 fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
744                 return (0);
745         case 7:
746                 strlcpy(fp->name, AudioEulinear_be, sizeof(fp->name));
747                 fp->encoding = AUDIO_ENCODING_ULINEAR_BE;
748                 fp->precision = 16;
749                 fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
750                 return (0);
751         default:
752                 return (EINVAL);
753         }
754 }
755 #endif
756
757 static const usb_interface_descriptor_t *
758 uaudio_find_iface(const char *buf, int size, int *offsp, int subtype)
759 {
760         const usb_interface_descriptor_t *d;
761
762         while (*offsp < size) {
763                 d = (const void *)(buf + *offsp);
764                 *offsp += d->bLength;
765                 if (d->bDescriptorType == UDESC_INTERFACE &&
766                     d->bInterfaceClass == UICLASS_AUDIO &&
767                     d->bInterfaceSubClass == subtype)
768                         return d;
769         }
770         return NULL;
771 }
772
773 static void
774 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct mixerctl *mc)
775 {
776         int res;
777         size_t len;
778         struct mixerctl *nmc;
779
780 #if defined(__FreeBSD__) || defined(__DragonFly__)
781         if (mc->class < UAC_NCLASSES) {
782                 DPRINTF(("%s: adding %s.%d\n",
783                          __func__, uac_names[mc->class], mc->ctl));
784         } else {
785                 DPRINTF(("%s: adding %d\n", __func__, mc->ctl));
786         }
787 #else
788         if (mc->class < UAC_NCLASSES) {
789                 DPRINTF(("%s: adding %s.%s\n",
790                          __func__, uac_names[mc->class], mc->ctlname));
791         } else {
792                 DPRINTF(("%s: adding %s\n", __func__, mc->ctlname));
793         }
794 #endif
795         len = sizeof(*mc) * (sc->sc_nctls + 1);
796         nmc = kmalloc(len, M_USBDEV, M_NOWAIT);
797         if (nmc == NULL) {
798                 kprintf("uaudio_mixer_add_ctl: no memory\n");
799                 return;
800         }
801         /* Copy old data, if there was any */
802         if (sc->sc_nctls != 0) {
803                 memcpy(nmc, sc->sc_ctls, sizeof(*mc) * (sc->sc_nctls));
804                 kfree(sc->sc_ctls, M_USBDEV);
805         }
806         sc->sc_ctls = nmc;
807
808         mc->delta = 0;
809         if (mc->type == MIX_ON_OFF) {
810                 mc->minval = 0;
811                 mc->maxval = 1;
812         } else if (mc->type == MIX_SELECTOR) {
813                 ;
814         } else {
815                 /* Determine min and max values. */
816                 mc->minval = uaudio_signext(mc->type,
817                         uaudio_get(sc, GET_MIN, UT_READ_CLASS_INTERFACE,
818                                    mc->wValue[0], mc->wIndex,
819                                    MIX_SIZE(mc->type)));
820                 mc->maxval = 1 + uaudio_signext(mc->type,
821                         uaudio_get(sc, GET_MAX, UT_READ_CLASS_INTERFACE,
822                                    mc->wValue[0], mc->wIndex,
823                                    MIX_SIZE(mc->type)));
824                 mc->mul = mc->maxval - mc->minval;
825                 if (mc->mul == 0)
826                         mc->mul = 1;
827                 res = uaudio_get(sc, GET_RES, UT_READ_CLASS_INTERFACE,
828                                  mc->wValue[0], mc->wIndex,
829                                  MIX_SIZE(mc->type));
830                 if (res > 0)
831                         mc->delta = (res * 255 + mc->mul/2) / mc->mul;
832         }
833
834         sc->sc_ctls[sc->sc_nctls++] = *mc;
835
836 #ifdef USB_DEBUG
837         if (uaudiodebug > 2) {
838                 int i;
839                 DPRINTF(("uaudio_mixer_add_ctl: wValue=%04x",mc->wValue[0]));
840                 for (i = 1; i < mc->nchan; i++)
841                         DPRINTF((",%04x", mc->wValue[i]));
842 #if defined(__FreeBSD__) || defined(__DragonFly__)
843                 DPRINTF((" wIndex=%04x type=%d ctl='%d' "
844                          "min=%d max=%d\n",
845                          mc->wIndex, mc->type, mc->ctl,
846                          mc->minval, mc->maxval));
847 #else
848                 DPRINTF((" wIndex=%04x type=%d name='%s' unit='%s' "
849                          "min=%d max=%d\n",
850                          mc->wIndex, mc->type, mc->ctlname, mc->ctlunit,
851                          mc->minval, mc->maxval));
852 #endif
853         }
854 #endif
855 }
856
857 #if defined(__NetBSD__) || defined(__OpenBSD__)
858 static char *
859 uaudio_id_name(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
860 {
861         static char buf[32];
862
863         ksnprintf(buf, sizeof(buf), "i%d", id);
864         return buf;
865 }
866 #endif
867
868 #ifdef USB_DEBUG
869 static void
870 uaudio_dump_cluster(const struct usb_audio_cluster *cl)
871 {
872         static const char *channel_names[16] = {
873                 "LEFT", "RIGHT", "CENTER", "LFE",
874                 "LEFT_SURROUND", "RIGHT_SURROUND", "LEFT_CENTER", "RIGHT_CENTER",
875                 "SURROUND", "LEFT_SIDE", "RIGHT_SIDE", "TOP",
876                 "RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15",
877         };
878         int cc, i, first;
879
880         cc = UGETW(cl->wChannelConfig);
881         kprintf("cluster: bNrChannels=%u wChannelConfig=0x%.4x",
882                   cl->bNrChannels, cc);
883         first = TRUE;
884         for (i = 0; cc != 0; i++) {
885                 if (cc & 1) {
886                         kprintf("%c%s", first ? '<' : ',', channel_names[i]);
887                         first = FALSE;
888                 }
889                 cc = cc >> 1;
890         }
891         kprintf("> iChannelNames=%u", cl->iChannelNames);
892 }
893 #endif
894
895 static struct usb_audio_cluster
896 uaudio_get_cluster(int id, const struct io_terminal *iot)
897 {
898         struct usb_audio_cluster r;
899         const usb_descriptor_t *dp;
900         int i;
901
902         for (i = 0; i < 25; i++) { /* avoid infinite loops */
903                 dp = iot[id].d.desc;
904                 if (dp == 0)
905                         goto bad;
906                 switch (dp->bDescriptorSubtype) {
907                 case UDESCSUB_AC_INPUT:
908                         r.bNrChannels = iot[id].d.it->bNrChannels;
909                         USETW(r.wChannelConfig, UGETW(iot[id].d.it->wChannelConfig));
910                         r.iChannelNames = iot[id].d.it->iChannelNames;
911                         return r;
912                 case UDESCSUB_AC_OUTPUT:
913                         id = iot[id].d.ot->bSourceId;
914                         break;
915                 case UDESCSUB_AC_MIXER:
916                         r = *(const struct usb_audio_cluster *)
917                                 &iot[id].d.mu->baSourceId[iot[id].d.mu->bNrInPins];
918                         return r;
919                 case UDESCSUB_AC_SELECTOR:
920                         /* XXX This is not really right */
921                         id = iot[id].d.su->baSourceId[0];
922                         break;
923                 case UDESCSUB_AC_FEATURE:
924                         id = iot[id].d.fu->bSourceId;
925                         break;
926                 case UDESCSUB_AC_PROCESSING:
927                         r = *(const struct usb_audio_cluster *)
928                                 &iot[id].d.pu->baSourceId[iot[id].d.pu->bNrInPins];
929                         return r;
930                 case UDESCSUB_AC_EXTENSION:
931                         r = *(const struct usb_audio_cluster *)
932                                 &iot[id].d.eu->baSourceId[iot[id].d.eu->bNrInPins];
933                         return r;
934                 default:
935                         goto bad;
936                 }
937         }
938  bad:
939         kprintf("uaudio_get_cluster: bad data\n");
940         memset(&r, 0, sizeof r);
941         return r;
942
943 }
944
945 static void
946 uaudio_add_input(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
947 {
948 #ifdef USB_DEBUG
949         const struct usb_audio_input_terminal *d = iot[id].d.it;
950
951         DPRINTFN(2,("uaudio_add_input: bTerminalId=%d wTerminalType=0x%04x "
952                     "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
953                     "iChannelNames=%d iTerminal=%d\n",
954                     d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
955                     d->bNrChannels, UGETW(d->wChannelConfig),
956                     d->iChannelNames, d->iTerminal));
957 #endif
958 }
959
960 static void
961 uaudio_add_output(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
962 {
963 #ifdef USB_DEBUG
964         const struct usb_audio_output_terminal *d;
965
966         d = iot[id].d.ot;
967         DPRINTFN(2,("uaudio_add_output: bTerminalId=%d wTerminalType=0x%04x "
968                     "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
969                     d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
970                     d->bSourceId, d->iTerminal));
971 #endif
972 }
973
974 static void
975 uaudio_add_mixer(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
976 {
977         const struct usb_audio_mixer_unit *d = iot[id].d.mu;
978         const struct usb_audio_mixer_unit_1 *d1;
979         int c, chs, ichs, ochs, i, o, bno, p, mo, mc, k;
980         const uByte *bm;
981         struct mixerctl mix;
982
983         DPRINTFN(2,("uaudio_add_mixer: bUnitId=%d bNrInPins=%d\n",
984                     d->bUnitId, d->bNrInPins));
985
986         /* Compute the number of input channels */
987         ichs = 0;
988         for (i = 0; i < d->bNrInPins; i++)
989                 ichs += uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
990
991         /* and the number of output channels */
992         d1 = (const struct usb_audio_mixer_unit_1 *)&d->baSourceId[d->bNrInPins];
993         ochs = d1->bNrChannels;
994         DPRINTFN(2,("uaudio_add_mixer: ichs=%d ochs=%d\n", ichs, ochs));
995
996         bm = d1->bmControls;
997         mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
998         uaudio_determine_class(&iot[id], &mix);
999         mix.type = MIX_SIGNED_16;
1000 #if !defined(__FreeBSD__) && !defined(__DragonFly__)    /* XXXXX */
1001         mix.ctlunit = AudioNvolume;
1002 #endif
1003
1004 #define BIT(bno) ((bm[bno / 8] >> (7 - bno % 8)) & 1)
1005         for (p = i = 0; i < d->bNrInPins; i++) {
1006                 chs = uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
1007                 mc = 0;
1008                 for (c = 0; c < chs; c++) {
1009                         mo = 0;
1010                         for (o = 0; o < ochs; o++) {
1011                                 bno = (p + c) * ochs + o;
1012                                 if (BIT(bno))
1013                                         mo++;
1014                         }
1015                         if (mo == 1)
1016                                 mc++;
1017                 }
1018                 if (mc == chs && chs <= MIX_MAX_CHAN) {
1019                         k = 0;
1020                         for (c = 0; c < chs; c++)
1021                                 for (o = 0; o < ochs; o++) {
1022                                         bno = (p + c) * ochs + o;
1023                                         if (BIT(bno))
1024                                                 mix.wValue[k++] =
1025                                                         MAKE(p+c+1, o+1);
1026                                 }
1027 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
1028                         ksnprintf(mix.ctlname, sizeof(mix.ctlname), "mix%d-%s",
1029                             d->bUnitId, uaudio_id_name(sc, iot,
1030                             d->baSourceId[i]));
1031 #endif
1032                         mix.nchan = chs;
1033                         uaudio_mixer_add_ctl(sc, &mix);
1034                 } else {
1035                         /* XXX */
1036                 }
1037 #undef BIT
1038                 p += chs;
1039         }
1040
1041 }
1042
1043 static void
1044 uaudio_add_selector(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1045 {
1046         const struct usb_audio_selector_unit *d;
1047         struct mixerctl mix;
1048 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
1049         int i, wp;
1050 #else
1051         int i;
1052         struct mixerctl dummy;
1053 #endif
1054
1055         d = iot[id].d.su;
1056         DPRINTFN(2,("uaudio_add_selector: bUnitId=%d bNrInPins=%d\n",
1057                     d->bUnitId, d->bNrInPins));
1058         mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1059         mix.wValue[0] = MAKE(0, 0);
1060         uaudio_determine_class(&iot[id], &mix);
1061         mix.nchan = 1;
1062         mix.type = MIX_SELECTOR;
1063 #if defined(__FreeBSD__) || defined(__DragonFly__)
1064         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1065         mix.minval = 1;
1066         mix.maxval = d->bNrInPins;
1067         mix.mul = mix.maxval - mix.minval;
1068         for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
1069                 mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
1070         }
1071         for (i = mix.minval; i <= mix.maxval; i++) {
1072                 mix.slctrtype[i - 1] = uaudio_feature_name(&iot[d->baSourceId[i - 1]], &dummy);
1073         }
1074 #else
1075         mix.ctlunit = "";
1076         mix.minval = 1;
1077         mix.maxval = d->bNrInPins;
1078         mix.mul = mix.maxval - mix.minval;
1079         wp = ksnprintf(mix.ctlname, MAX_AUDIO_DEV_LEN, "sel%d-", d->bUnitId);
1080         for (i = 1; i <= d->bNrInPins; i++) {
1081                 wp += ksnprintf(mix.ctlname + wp, MAX_AUDIO_DEV_LEN - wp,
1082                                "i%d", d->baSourceId[i - 1]);
1083                 if (wp > MAX_AUDIO_DEV_LEN - 1)
1084                         break;
1085         }
1086 #endif
1087         uaudio_mixer_add_ctl(sc, &mix);
1088 }
1089
1090 #ifdef USB_DEBUG
1091 static const char *
1092 uaudio_get_terminal_name(int terminal_type)
1093 {
1094         static char buf[100];
1095
1096         switch (terminal_type) {
1097         /* USB terminal types */
1098         case UAT_UNDEFINED:     return "UAT_UNDEFINED";
1099         case UAT_STREAM:        return "UAT_STREAM";
1100         case UAT_VENDOR:        return "UAT_VENDOR";
1101         /* input terminal types */
1102         case UATI_UNDEFINED:    return "UATI_UNDEFINED";
1103         case UATI_MICROPHONE:   return "UATI_MICROPHONE";
1104         case UATI_DESKMICROPHONE:       return "UATI_DESKMICROPHONE";
1105         case UATI_PERSONALMICROPHONE:   return "UATI_PERSONALMICROPHONE";
1106         case UATI_OMNIMICROPHONE:       return "UATI_OMNIMICROPHONE";
1107         case UATI_MICROPHONEARRAY:      return "UATI_MICROPHONEARRAY";
1108         case UATI_PROCMICROPHONEARR:    return "UATI_PROCMICROPHONEARR";
1109         /* output terminal types */
1110         case UATO_UNDEFINED:    return "UATO_UNDEFINED";
1111         case UATO_SPEAKER:      return "UATO_SPEAKER";
1112         case UATO_HEADPHONES:   return "UATO_HEADPHONES";
1113         case UATO_DISPLAYAUDIO: return "UATO_DISPLAYAUDIO";
1114         case UATO_DESKTOPSPEAKER:       return "UATO_DESKTOPSPEAKER";
1115         case UATO_ROOMSPEAKER:  return "UATO_ROOMSPEAKER";
1116         case UATO_COMMSPEAKER:  return "UATO_COMMSPEAKER";
1117         case UATO_SUBWOOFER:    return "UATO_SUBWOOFER";
1118         /* bidir terminal types */
1119         case UATB_UNDEFINED:    return "UATB_UNDEFINED";
1120         case UATB_HANDSET:      return "UATB_HANDSET";
1121         case UATB_HEADSET:      return "UATB_HEADSET";
1122         case UATB_SPEAKERPHONE: return "UATB_SPEAKERPHONE";
1123         case UATB_SPEAKERPHONEESUP:     return "UATB_SPEAKERPHONEESUP";
1124         case UATB_SPEAKERPHONEECANC:    return "UATB_SPEAKERPHONEECANC";
1125         /* telephony terminal types */
1126         case UATT_UNDEFINED:    return "UATT_UNDEFINED";
1127         case UATT_PHONELINE:    return "UATT_PHONELINE";
1128         case UATT_TELEPHONE:    return "UATT_TELEPHONE";
1129         case UATT_DOWNLINEPHONE:        return "UATT_DOWNLINEPHONE";
1130         /* external terminal types */
1131         case UATE_UNDEFINED:    return "UATE_UNDEFINED";
1132         case UATE_ANALOGCONN:   return "UATE_ANALOGCONN";
1133         case UATE_LINECONN:     return "UATE_LINECONN";
1134         case UATE_LEGACYCONN:   return "UATE_LEGACYCONN";
1135         case UATE_DIGITALAUIFC: return "UATE_DIGITALAUIFC";
1136         case UATE_SPDIF:        return "UATE_SPDIF";
1137         case UATE_1394DA:       return "UATE_1394DA";
1138         case UATE_1394DV:       return "UATE_1394DV";
1139         /* embedded function terminal types */
1140         case UATF_UNDEFINED:    return "UATF_UNDEFINED";
1141         case UATF_CALIBNOISE:   return "UATF_CALIBNOISE";
1142         case UATF_EQUNOISE:     return "UATF_EQUNOISE";
1143         case UATF_CDPLAYER:     return "UATF_CDPLAYER";
1144         case UATF_DAT:  return "UATF_DAT";
1145         case UATF_DCC:  return "UATF_DCC";
1146         case UATF_MINIDISK:     return "UATF_MINIDISK";
1147         case UATF_ANALOGTAPE:   return "UATF_ANALOGTAPE";
1148         case UATF_PHONOGRAPH:   return "UATF_PHONOGRAPH";
1149         case UATF_VCRAUDIO:     return "UATF_VCRAUDIO";
1150         case UATF_VIDEODISCAUDIO:       return "UATF_VIDEODISCAUDIO";
1151         case UATF_DVDAUDIO:     return "UATF_DVDAUDIO";
1152         case UATF_TVTUNERAUDIO: return "UATF_TVTUNERAUDIO";
1153         case UATF_SATELLITE:    return "UATF_SATELLITE";
1154         case UATF_CABLETUNER:   return "UATF_CABLETUNER";
1155         case UATF_DSS:  return "UATF_DSS";
1156         case UATF_RADIORECV:    return "UATF_RADIORECV";
1157         case UATF_RADIOXMIT:    return "UATF_RADIOXMIT";
1158         case UATF_MULTITRACK:   return "UATF_MULTITRACK";
1159         case UATF_SYNTHESIZER:  return "UATF_SYNTHESIZER";
1160         default:
1161                 ksnprintf(buf, sizeof(buf), "unknown type (0x%.4x)", terminal_type);
1162                 return buf;
1163         }
1164 }
1165 #endif
1166
1167 static int
1168 uaudio_determine_class(const struct io_terminal *iot, struct mixerctl *mix)
1169 {
1170         int terminal_type;
1171
1172         if (iot == NULL || iot->output == NULL) {
1173                 mix->class = UAC_OUTPUT;
1174                 return 0;
1175         }
1176         terminal_type = 0;
1177         if (iot->output->size == 1)
1178                 terminal_type = iot->output->terminals[0];
1179         /*
1180          * If the only output terminal is USB,
1181          * the class is UAC_RECORD.
1182          */
1183         if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
1184                 mix->class = UAC_RECORD;
1185                 if (iot->inputs_size == 1
1186                     && iot->inputs[0] != NULL
1187                     && iot->inputs[0]->size == 1)
1188                         return iot->inputs[0]->terminals[0];
1189                 else
1190                         return 0;
1191         }
1192         /*
1193          * If the ultimate destination of the unit is just one output
1194          * terminal and the unit is connected to the output terminal
1195          * directly, the class is UAC_OUTPUT.
1196          */
1197         if (terminal_type != 0 && iot->direct) {
1198                 mix->class = UAC_OUTPUT;
1199                 return terminal_type;
1200         }
1201         /*
1202          * If the unit is connected to just one input terminal,
1203          * the class is UAC_INPUT.
1204          */
1205         if (iot->inputs_size == 1 && iot->inputs[0] != NULL
1206             && iot->inputs[0]->size == 1) {
1207                 mix->class = UAC_INPUT;
1208                 return iot->inputs[0]->terminals[0];
1209         }
1210         /*
1211          * Otherwise, the class is UAC_OUTPUT.
1212          */
1213         mix->class = UAC_OUTPUT;
1214         return terminal_type;
1215 }
1216
1217 #if defined(__FreeBSD__) || defined(__DragonFly__)
1218 const int 
1219 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
1220 {
1221         int terminal_type;
1222
1223         terminal_type = uaudio_determine_class(iot, mix);
1224         if (mix->class == UAC_RECORD && terminal_type == 0)
1225                 return SOUND_MIXER_IMIX;
1226         DPRINTF(("%s: terminal_type=%s\n", __func__,
1227                  uaudio_get_terminal_name(terminal_type)));
1228         switch (terminal_type) {
1229         case UAT_STREAM:
1230                 return SOUND_MIXER_PCM;
1231
1232         case UATI_MICROPHONE:
1233         case UATI_DESKMICROPHONE:
1234         case UATI_PERSONALMICROPHONE:
1235         case UATI_OMNIMICROPHONE:
1236         case UATI_MICROPHONEARRAY:
1237         case UATI_PROCMICROPHONEARR:
1238                 return SOUND_MIXER_MIC;
1239
1240         case UATO_SPEAKER:
1241         case UATO_DESKTOPSPEAKER:
1242         case UATO_ROOMSPEAKER:
1243         case UATO_COMMSPEAKER:
1244                 return SOUND_MIXER_SPEAKER;
1245
1246         case UATE_ANALOGCONN:
1247         case UATE_LINECONN:
1248         case UATE_LEGACYCONN:
1249                 return SOUND_MIXER_LINE;
1250
1251         case UATE_DIGITALAUIFC:
1252         case UATE_SPDIF:
1253         case UATE_1394DA:
1254         case UATE_1394DV:
1255                 return SOUND_MIXER_ALTPCM;
1256
1257         case UATF_CDPLAYER:
1258                 return SOUND_MIXER_CD;
1259
1260         case UATF_SYNTHESIZER:
1261                 return SOUND_MIXER_SYNTH;
1262
1263         case UATF_VIDEODISCAUDIO:
1264         case UATF_DVDAUDIO:
1265         case UATF_TVTUNERAUDIO:
1266                 return SOUND_MIXER_VIDEO;
1267
1268 /* telephony terminal types */
1269         case UATT_UNDEFINED:
1270         case UATT_PHONELINE:
1271         case UATT_TELEPHONE:
1272         case UATT_DOWNLINEPHONE:
1273                 return SOUND_MIXER_PHONEIN;
1274 /*              return SOUND_MIXER_PHONEOUT;*/
1275
1276         case UATF_RADIORECV:
1277         case UATF_RADIOXMIT:
1278                 return SOUND_MIXER_RADIO;
1279
1280         case UAT_UNDEFINED:
1281         case UAT_VENDOR:
1282         case UATI_UNDEFINED:
1283 /* output terminal types */
1284         case UATO_UNDEFINED:
1285         case UATO_DISPLAYAUDIO:
1286         case UATO_SUBWOOFER:
1287         case UATO_HEADPHONES:
1288 /* bidir terminal types */
1289         case UATB_UNDEFINED:
1290         case UATB_HANDSET:
1291         case UATB_HEADSET:
1292         case UATB_SPEAKERPHONE:
1293         case UATB_SPEAKERPHONEESUP:
1294         case UATB_SPEAKERPHONEECANC:
1295 /* external terminal types */
1296         case UATE_UNDEFINED:
1297 /* embedded function terminal types */
1298         case UATF_UNDEFINED:
1299         case UATF_CALIBNOISE:
1300         case UATF_EQUNOISE:
1301         case UATF_DAT:
1302         case UATF_DCC:
1303         case UATF_MINIDISK:
1304         case UATF_ANALOGTAPE:
1305         case UATF_PHONOGRAPH:
1306         case UATF_VCRAUDIO:
1307         case UATF_SATELLITE:
1308         case UATF_CABLETUNER:
1309         case UATF_DSS:
1310         case UATF_MULTITRACK:
1311         case 0xffff:
1312         default:
1313                 DPRINTF(("%s: 'master' for 0x%.4x\n", __func__, terminal_type));
1314                 return SOUND_MIXER_VOLUME;
1315         }
1316         return SOUND_MIXER_VOLUME;
1317 }
1318 #else
1319 static const char *
1320 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
1321 {
1322         int terminal_type;
1323
1324         terminal_type = uaudio_determine_class(iot, mix);
1325         if (mix->class == UAC_RECORD && terminal_type == 0)
1326                 return AudioNmixerout;
1327         DPRINTF(("%s: terminal_type=%s\n", __func__,
1328                  uaudio_get_terminal_name(terminal_type)));
1329         switch (terminal_type) {
1330         case UAT_STREAM:
1331                 return AudioNdac;
1332
1333         case UATI_MICROPHONE:
1334         case UATI_DESKMICROPHONE:
1335         case UATI_PERSONALMICROPHONE:
1336         case UATI_OMNIMICROPHONE:
1337         case UATI_MICROPHONEARRAY:
1338         case UATI_PROCMICROPHONEARR:
1339                 return AudioNmicrophone;
1340
1341         case UATO_SPEAKER:
1342         case UATO_DESKTOPSPEAKER:
1343         case UATO_ROOMSPEAKER:
1344         case UATO_COMMSPEAKER:
1345                 return AudioNspeaker;
1346
1347         case UATO_HEADPHONES:
1348                 return AudioNheadphone;
1349
1350         case UATO_SUBWOOFER:
1351                 return AudioNlfe;
1352
1353         /* telephony terminal types */
1354         case UATT_UNDEFINED:
1355         case UATT_PHONELINE:
1356         case UATT_TELEPHONE:
1357         case UATT_DOWNLINEPHONE:
1358                 return "phone";
1359
1360         case UATE_ANALOGCONN:
1361         case UATE_LINECONN:
1362         case UATE_LEGACYCONN:
1363                 return AudioNline;
1364
1365         case UATE_DIGITALAUIFC:
1366         case UATE_SPDIF:
1367         case UATE_1394DA:
1368         case UATE_1394DV:
1369                 return AudioNaux;
1370
1371         case UATF_CDPLAYER:
1372                 return AudioNcd;
1373
1374         case UATF_SYNTHESIZER:
1375                 return AudioNfmsynth;
1376
1377         case UATF_VIDEODISCAUDIO:
1378         case UATF_DVDAUDIO:
1379         case UATF_TVTUNERAUDIO:
1380                 return AudioNvideo;
1381
1382         case UAT_UNDEFINED:
1383         case UAT_VENDOR:
1384         case UATI_UNDEFINED:
1385 /* output terminal types */
1386         case UATO_UNDEFINED:
1387         case UATO_DISPLAYAUDIO:
1388 /* bidir terminal types */
1389         case UATB_UNDEFINED:
1390         case UATB_HANDSET:
1391         case UATB_HEADSET:
1392         case UATB_SPEAKERPHONE:
1393         case UATB_SPEAKERPHONEESUP:
1394         case UATB_SPEAKERPHONEECANC:
1395 /* external terminal types */
1396         case UATE_UNDEFINED:
1397 /* embedded function terminal types */
1398         case UATF_UNDEFINED:
1399         case UATF_CALIBNOISE:
1400         case UATF_EQUNOISE:
1401         case UATF_DAT:
1402         case UATF_DCC:
1403         case UATF_MINIDISK:
1404         case UATF_ANALOGTAPE:
1405         case UATF_PHONOGRAPH:
1406         case UATF_VCRAUDIO:
1407         case UATF_SATELLITE:
1408         case UATF_CABLETUNER:
1409         case UATF_DSS:
1410         case UATF_RADIORECV:
1411         case UATF_RADIOXMIT:
1412         case UATF_MULTITRACK:
1413         case 0xffff:
1414         default:
1415                 DPRINTF(("%s: 'master' for 0x%.4x\n", __func__, terminal_type));
1416                 return AudioNmaster;
1417         }
1418         return AudioNmaster;
1419 }
1420 #endif
1421
1422 static void
1423 uaudio_add_feature(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1424 {
1425         const struct usb_audio_feature_unit *d;
1426         const uByte *ctls;
1427         int ctlsize;
1428         int nchan;
1429         u_int fumask, mmask, cmask;
1430         struct mixerctl mix;
1431         int chan, ctl, i, unit;
1432 #if defined(__FreeBSD__) || defined(__DragonFly__)
1433         int mixernumber;
1434 #else
1435         const char *mixername;
1436 #endif
1437
1438 #define GET(i) (ctls[(i)*ctlsize] | \
1439                 (ctlsize > 1 ? ctls[(i)*ctlsize+1] << 8 : 0))
1440         d = iot[id].d.fu;
1441         ctls = d->bmaControls;
1442         ctlsize = d->bControlSize;
1443         nchan = (d->bLength - 7) / ctlsize;
1444         mmask = GET(0);
1445         /* Figure out what we can control */
1446         for (cmask = 0, chan = 1; chan < nchan; chan++) {
1447                 DPRINTFN(9,("uaudio_add_feature: chan=%d mask=%x\n",
1448                             chan, GET(chan)));
1449                 cmask |= GET(chan);
1450         }
1451
1452 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
1453         DPRINTFN(1,("uaudio_add_feature: bUnitId=%d, "
1454                     "%d channels, mmask=0x%04x, cmask=0x%04x\n",
1455                     d->bUnitId, nchan, mmask, cmask));
1456 #endif
1457
1458         if (nchan > MIX_MAX_CHAN)
1459                 nchan = MIX_MAX_CHAN;
1460         unit = d->bUnitId;
1461         mix.wIndex = MAKE(unit, sc->sc_ac_iface);
1462         for (ctl = MUTE_CONTROL; ctl < LOUDNESS_CONTROL; ctl++) {
1463                 fumask = FU_MASK(ctl);
1464                 DPRINTFN(4,("uaudio_add_feature: ctl=%d fumask=0x%04x\n",
1465                             ctl, fumask));
1466                 if (mmask & fumask) {
1467                         mix.nchan = 1;
1468                         mix.wValue[0] = MAKE(ctl, 0);
1469                 } else if (cmask & fumask) {
1470                         mix.nchan = nchan - 1;
1471                         for (i = 1; i < nchan; i++) {
1472                                 if (GET(i) & fumask)
1473                                         mix.wValue[i-1] = MAKE(ctl, i);
1474                                 else
1475                                         mix.wValue[i-1] = -1;
1476                         }
1477                 } else {
1478                         continue;
1479                 }
1480 #undef GET
1481
1482 #if defined(__FreeBSD__) || defined(__DragonFly__)
1483                 mixernumber = uaudio_feature_name(&iot[id], &mix);
1484 #else
1485                 mixername = uaudio_feature_name(&iot[id], &mix);
1486 #endif
1487                 switch (ctl) {
1488                 case MUTE_CONTROL:
1489                         mix.type = MIX_ON_OFF;
1490 #if defined(__FreeBSD__) || defined(__DragonFly__)
1491                         mix.ctl = SOUND_MIXER_NRDEVICES;
1492 #else
1493                         mix.ctlunit = "";
1494                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1495                                  "%s.%s", mixername, AudioNmute);
1496 #endif
1497                         break;
1498                 case VOLUME_CONTROL:
1499                         mix.type = MIX_SIGNED_16;
1500 #if defined(__FreeBSD__) || defined(__DragonFly__)
1501                         mix.ctl = mixernumber;
1502 #else
1503                         mix.ctlunit = AudioNvolume;
1504                         strlcpy(mix.ctlname, mixername, sizeof(mix.ctlname));
1505 #endif
1506                         break;
1507                 case BASS_CONTROL:
1508                         mix.type = MIX_SIGNED_8;
1509 #if defined(__FreeBSD__) || defined(__DragonFly__)
1510                         mix.ctl = SOUND_MIXER_BASS;
1511 #else
1512                         mix.ctlunit = AudioNbass;
1513                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1514                                  "%s.%s", mixername, AudioNbass);
1515 #endif
1516                         break;
1517                 case MID_CONTROL:
1518                         mix.type = MIX_SIGNED_8;
1519 #if defined(__FreeBSD__) || defined(__DragonFly__)
1520                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1521 #else
1522                         mix.ctlunit = AudioNmid;
1523                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1524                                  "%s.%s", mixername, AudioNmid);
1525 #endif
1526                         break;
1527                 case TREBLE_CONTROL:
1528                         mix.type = MIX_SIGNED_8;
1529 #if defined(__FreeBSD__) || defined(__DragonFly__)
1530                         mix.ctl = SOUND_MIXER_TREBLE;
1531 #else
1532                         mix.ctlunit = AudioNtreble;
1533                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1534                                  "%s.%s", mixername, AudioNtreble);
1535 #endif
1536                         break;
1537                 case GRAPHIC_EQUALIZER_CONTROL:
1538                         continue; /* XXX don't add anything */
1539                         break;
1540                 case AGC_CONTROL:
1541                         mix.type = MIX_ON_OFF;
1542 #if defined(__FreeBSD__) || defined(__DragonFly__)
1543                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1544 #else
1545                         mix.ctlunit = "";
1546                         ksnprintf(mix.ctlname, sizeof(mix.ctlname), "%s.%s",
1547                                  mixername, AudioNagc);
1548 #endif
1549                         break;
1550                 case DELAY_CONTROL:
1551                         mix.type = MIX_UNSIGNED_16;
1552 #if defined(__FreeBSD__) || defined(__DragonFly__)
1553                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1554 #else
1555                         mix.ctlunit = "4 ms";
1556                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1557                                  "%s.%s", mixername, AudioNdelay);
1558 #endif
1559                         break;
1560                 case BASS_BOOST_CONTROL:
1561                         mix.type = MIX_ON_OFF;
1562 #if defined(__FreeBSD__) || defined(__DragonFly__)
1563                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
1564 #else
1565                         mix.ctlunit = "";
1566                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1567                                  "%s.%s", mixername, AudioNbassboost);
1568 #endif
1569                         break;
1570                 case LOUDNESS_CONTROL:
1571                         mix.type = MIX_ON_OFF;
1572 #if defined(__FreeBSD__) || defined(__DragonFly__)
1573                         mix.ctl = SOUND_MIXER_LOUD;     /* Is this correct ? */
1574 #else
1575                         mix.ctlunit = "";
1576                         ksnprintf(mix.ctlname, sizeof(mix.ctlname),
1577                                  "%s.%s", mixername, AudioNloudness);
1578 #endif
1579                         break;
1580                 }
1581                 uaudio_mixer_add_ctl(sc, &mix);
1582         }
1583 }
1584
1585 static void
1586 uaudio_add_processing_updown(struct uaudio_softc *sc,
1587                              const struct io_terminal *iot, int id)
1588 {
1589         const struct usb_audio_processing_unit *d;
1590         const struct usb_audio_processing_unit_1 *d1;
1591         const struct usb_audio_processing_unit_updown *ud;
1592         struct mixerctl mix;
1593         int i;
1594
1595         d = iot[id].d.pu;
1596         d1 = (const struct usb_audio_processing_unit_1 *)
1597                 &d->baSourceId[d->bNrInPins];
1598         ud = (const struct usb_audio_processing_unit_updown *)
1599                 &d1->bmControls[d1->bControlSize];
1600         DPRINTFN(2,("uaudio_add_processing_updown: bUnitId=%d bNrModes=%d\n",
1601                     d->bUnitId, ud->bNrModes));
1602
1603         if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
1604                 DPRINTF(("uaudio_add_processing_updown: no mode select\n"));
1605                 return;
1606         }
1607
1608         mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1609         mix.nchan = 1;
1610         mix.wValue[0] = MAKE(UD_MODE_SELECT_CONTROL, 0);
1611         uaudio_determine_class(&iot[id], &mix);
1612         mix.type = MIX_ON_OFF;  /* XXX */
1613 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
1614         mix.ctlunit = "";
1615         ksnprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d-mode", d->bUnitId);
1616 #endif
1617
1618         for (i = 0; i < ud->bNrModes; i++) {
1619                 DPRINTFN(2,("uaudio_add_processing_updown: i=%d bm=0x%x\n",
1620                             i, UGETW(ud->waModes[i])));
1621                 /* XXX */
1622         }
1623         uaudio_mixer_add_ctl(sc, &mix);
1624 }
1625
1626 static void
1627 uaudio_add_processing(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1628 {
1629         const struct usb_audio_processing_unit *d;
1630         const struct usb_audio_processing_unit_1 *d1;
1631         int ptype;
1632         struct mixerctl mix;
1633
1634         d = iot[id].d.pu;
1635         d1 = (const struct usb_audio_processing_unit_1 *)
1636                 &d->baSourceId[d->bNrInPins];
1637         ptype = UGETW(d->wProcessType);
1638         DPRINTFN(2,("uaudio_add_processing: wProcessType=%d bUnitId=%d "
1639                     "bNrInPins=%d\n", ptype, d->bUnitId, d->bNrInPins));
1640
1641         if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
1642                 mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1643                 mix.nchan = 1;
1644                 mix.wValue[0] = MAKE(XX_ENABLE_CONTROL, 0);
1645                 uaudio_determine_class(&iot[id], &mix);
1646                 mix.type = MIX_ON_OFF;
1647 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
1648                 mix.ctlunit = "";
1649                 ksnprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d.%d-enable",
1650                     d->bUnitId, ptype);
1651 #endif
1652                 uaudio_mixer_add_ctl(sc, &mix);
1653         }
1654
1655         switch(ptype) {
1656         case UPDOWNMIX_PROCESS:
1657                 uaudio_add_processing_updown(sc, iot, id);
1658                 break;
1659         case DOLBY_PROLOGIC_PROCESS:
1660         case P3D_STEREO_EXTENDER_PROCESS:
1661         case REVERBATION_PROCESS:
1662         case CHORUS_PROCESS:
1663         case DYN_RANGE_COMP_PROCESS:
1664         default:
1665 #ifdef USB_DEBUG
1666                 kprintf("uaudio_add_processing: unit %d, type=%d not impl.\n",
1667                        d->bUnitId, ptype);
1668 #endif
1669                 break;
1670         }
1671 }
1672
1673 static void
1674 uaudio_add_extension(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1675 {
1676         const struct usb_audio_extension_unit *d;
1677         const struct usb_audio_extension_unit_1 *d1;
1678         struct mixerctl mix;
1679
1680         d = iot[id].d.eu;
1681         d1 = (const struct usb_audio_extension_unit_1 *)
1682                 &d->baSourceId[d->bNrInPins];
1683         DPRINTFN(2,("uaudio_add_extension: bUnitId=%d bNrInPins=%d\n",
1684                     d->bUnitId, d->bNrInPins));
1685
1686         if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_XU)
1687                 return;
1688
1689         if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
1690                 mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1691                 mix.nchan = 1;
1692                 mix.wValue[0] = MAKE(UA_EXT_ENABLE, 0);
1693                 uaudio_determine_class(&iot[id], &mix);
1694                 mix.type = MIX_ON_OFF;
1695 #if !defined(__FreeBSD__) && !defined(__DragonFly__)
1696                 mix.ctlunit = "";
1697                 ksnprintf(mix.ctlname, sizeof(mix.ctlname), "ext%d-enable",
1698                     d->bUnitId);
1699 #endif
1700                 uaudio_mixer_add_ctl(sc, &mix);
1701         }
1702 }
1703
1704 static struct terminal_list*
1705 uaudio_merge_terminal_list(const struct io_terminal *iot)
1706 {
1707         struct terminal_list *tml;
1708         uint16_t *ptm;
1709         int i, len;
1710
1711         len = 0;
1712         if (iot->inputs == NULL)
1713                 return NULL;
1714         for (i = 0; i < iot->inputs_size; i++) {
1715                 if (iot->inputs[i] != NULL)
1716                         len += iot->inputs[i]->size;
1717         }
1718         tml = kmalloc(TERMINAL_LIST_SIZE(len), M_TEMP, M_NOWAIT);
1719         if (tml == NULL) {
1720                 kprintf("uaudio_merge_terminal_list: no memory\n");
1721                 return NULL;
1722         }
1723         tml->size = 0;
1724         ptm = tml->terminals;
1725         for (i = 0; i < iot->inputs_size; i++) {
1726                 if (iot->inputs[i] == NULL)
1727                         continue;
1728                 if (iot->inputs[i]->size > len)
1729                         break;
1730                 memcpy(ptm, iot->inputs[i]->terminals,
1731                        iot->inputs[i]->size * sizeof(uint16_t));
1732                 tml->size += iot->inputs[i]->size;
1733                 ptm += iot->inputs[i]->size;
1734                 len -= iot->inputs[i]->size;
1735         }
1736         return tml;
1737 }
1738
1739 static struct terminal_list *
1740 uaudio_io_terminaltype(int outtype, struct io_terminal *iot, int id)
1741 {
1742         struct terminal_list *tml;
1743         struct io_terminal *it;
1744         int src_id, i;
1745
1746         it = &iot[id];
1747         if (it->output != NULL) {
1748                 /* already has outtype? */
1749                 for (i = 0; i < it->output->size; i++)
1750                         if (it->output->terminals[i] == outtype)
1751                                 return uaudio_merge_terminal_list(it);
1752                 tml = kmalloc(TERMINAL_LIST_SIZE(it->output->size + 1),
1753                              M_TEMP, M_NOWAIT);
1754                 if (tml == NULL) {
1755                         kprintf("uaudio_io_terminaltype: no memory\n");
1756                         return uaudio_merge_terminal_list(it);
1757                 }
1758                 memcpy(tml, it->output, TERMINAL_LIST_SIZE(it->output->size));
1759                 tml->terminals[it->output->size] = outtype;
1760                 tml->size++;
1761                 kfree(it->output, M_TEMP);
1762                 it->output = tml;
1763                 if (it->inputs != NULL) {
1764                         for (i = 0; i < it->inputs_size; i++)
1765                                 if (it->inputs[i] != NULL)
1766                                         kfree(it->inputs[i], M_TEMP);
1767                         kfree(it->inputs, M_TEMP);
1768                 }
1769                 it->inputs_size = 0;
1770                 it->inputs = NULL;
1771         } else {                /* end `iot[id] != NULL' */
1772                 it->inputs_size = 0;
1773                 it->inputs = NULL;
1774                 it->output = kmalloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1775                 if (it->output == NULL) {
1776                         kprintf("uaudio_io_terminaltype: no memory\n");
1777                         return NULL;
1778                 }
1779                 it->output->terminals[0] = outtype;
1780                 it->output->size = 1;
1781                 it->direct = FALSE;
1782         }
1783
1784         switch (it->d.desc->bDescriptorSubtype) {
1785         case UDESCSUB_AC_INPUT:
1786                 it->inputs = kmalloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1787                 if (it->inputs == NULL) {
1788                         kprintf("uaudio_io_terminaltype: no memory\n");
1789                         return NULL;
1790                 }
1791                 tml = kmalloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1792                 if (tml == NULL) {
1793                         kprintf("uaudio_io_terminaltype: no memory\n");
1794                         kfree(it->inputs, M_TEMP);
1795                         it->inputs = NULL;
1796                         return NULL;
1797                 }
1798                 it->inputs[0] = tml;
1799                 tml->terminals[0] = UGETW(it->d.it->wTerminalType);
1800                 tml->size = 1;
1801                 it->inputs_size = 1;
1802                 return uaudio_merge_terminal_list(it);
1803         case UDESCSUB_AC_FEATURE:
1804                 src_id = it->d.fu->bSourceId;
1805                 it->inputs = kmalloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1806                 if (it->inputs == NULL) {
1807                         kprintf("uaudio_io_terminaltype: no memory\n");
1808                         return uaudio_io_terminaltype(outtype, iot, src_id);
1809                 }
1810                 it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1811                 it->inputs_size = 1;
1812                 return uaudio_merge_terminal_list(it);
1813         case UDESCSUB_AC_OUTPUT:
1814                 it->inputs = kmalloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1815                 if (it->inputs == NULL) {
1816                         kprintf("uaudio_io_terminaltype: no memory\n");
1817                         return NULL;
1818                 }
1819                 src_id = it->d.ot->bSourceId;
1820                 it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1821                 it->inputs_size = 1;
1822                 iot[src_id].direct = TRUE;
1823                 return NULL;
1824         case UDESCSUB_AC_MIXER:
1825                 it->inputs_size = 0;
1826                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1827                                     * it->d.mu->bNrInPins, M_TEMP, M_NOWAIT);
1828                 if (it->inputs == NULL) {
1829                         kprintf("uaudio_io_terminaltype: no memory\n");
1830                         return NULL;
1831                 }
1832                 for (i = 0; i < it->d.mu->bNrInPins; i++) {
1833                         src_id = it->d.mu->baSourceId[i];
1834                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1835                                                                src_id);
1836                         it->inputs_size++;
1837                 }
1838                 return uaudio_merge_terminal_list(it);
1839         case UDESCSUB_AC_SELECTOR:
1840                 it->inputs_size = 0;
1841                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1842                                     * it->d.su->bNrInPins, M_TEMP, M_NOWAIT);
1843                 if (it->inputs == NULL) {
1844                         kprintf("uaudio_io_terminaltype: no memory\n");
1845                         return NULL;
1846                 }
1847                 for (i = 0; i < it->d.su->bNrInPins; i++) {
1848                         src_id = it->d.su->baSourceId[i];
1849                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1850                                                                src_id);
1851                         it->inputs_size++;
1852                 }
1853                 return uaudio_merge_terminal_list(it);
1854         case UDESCSUB_AC_PROCESSING:
1855                 it->inputs_size = 0;
1856                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1857                                     * it->d.pu->bNrInPins, M_TEMP, M_NOWAIT);
1858                 if (it->inputs == NULL) {
1859                         kprintf("uaudio_io_terminaltype: no memory\n");
1860                         return NULL;
1861                 }
1862                 for (i = 0; i < it->d.pu->bNrInPins; i++) {
1863                         src_id = it->d.pu->baSourceId[i];
1864                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1865                                                                src_id);
1866                         it->inputs_size++;
1867                 }
1868                 return uaudio_merge_terminal_list(it);
1869         case UDESCSUB_AC_EXTENSION:
1870                 it->inputs_size = 0;
1871                 it->inputs = kmalloc(sizeof(struct terminal_list *)
1872                                     * it->d.eu->bNrInPins, M_TEMP, M_NOWAIT);
1873                 if (it->inputs == NULL) {
1874                         kprintf("uaudio_io_terminaltype: no memory\n");
1875                         return NULL;
1876                 }
1877                 for (i = 0; i < it->d.eu->bNrInPins; i++) {
1878                         src_id = it->d.eu->baSourceId[i];
1879                         it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1880                                                                src_id);
1881                         it->inputs_size++;
1882                 }
1883                 return uaudio_merge_terminal_list(it);
1884         case UDESCSUB_AC_HEADER:
1885         default:
1886                 return NULL;
1887         }
1888 }
1889
1890 static usbd_status
1891 uaudio_identify(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
1892 {
1893         usbd_status err;
1894
1895         err = uaudio_identify_ac(sc, cdesc);
1896         if (err)
1897                 return err;
1898         return uaudio_identify_as(sc, cdesc);
1899 }
1900
1901 static void
1902 uaudio_add_alt(struct uaudio_softc *sc, const struct as_info *ai)
1903 {
1904         size_t len;
1905         struct as_info *nai;
1906
1907         len = sizeof(*ai) * (sc->sc_nalts + 1);
1908         nai = kmalloc(len, M_USBDEV, M_NOWAIT);
1909         if (nai == NULL) {
1910                 kprintf("uaudio_add_alt: no memory\n");
1911                 return;
1912         }
1913         /* Copy old data, if there was any */
1914         if (sc->sc_nalts != 0) {
1915                 memcpy(nai, sc->sc_alts, sizeof(*ai) * (sc->sc_nalts));
1916                 kfree(sc->sc_alts, M_USBDEV);
1917         }
1918         sc->sc_alts = nai;
1919         DPRINTFN(2,("uaudio_add_alt: adding alt=%d, enc=%d\n",
1920                     ai->alt, ai->encoding));
1921         sc->sc_alts[sc->sc_nalts++] = *ai;
1922 }
1923
1924 static usbd_status
1925 uaudio_process_as(struct uaudio_softc *sc, const char *buf, int *offsp,
1926                   int size, const usb_interface_descriptor_t *id)
1927 #define offs (*offsp)
1928 {
1929         const struct usb_audio_streaming_interface_descriptor *asid;
1930         const struct usb_audio_streaming_type1_descriptor *asf1d;
1931         const usb_endpoint_descriptor_audio_t *ed;
1932         const usb_endpoint_descriptor_audio_t *epdesc1;
1933         const struct usb_audio_streaming_endpoint_descriptor *sed;
1934         int format, chan, prec, enc;
1935         int dir, type, sync;
1936         struct as_info ai;
1937         const char *format_str;
1938
1939         asid = (const void *)(buf + offs);
1940
1941         if (asid->bDescriptorType != UDESC_CS_INTERFACE ||
1942             asid->bDescriptorSubtype != AS_GENERAL)
1943                 return USBD_INVAL;
1944         DPRINTF(("uaudio_process_as: asid: bTerminakLink=%d wFormatTag=%d\n",
1945                  asid->bTerminalLink, UGETW(asid->wFormatTag)));
1946         offs += asid->bLength;
1947         if (offs > size)
1948                 return USBD_INVAL;
1949
1950         asf1d = (const void *)(buf + offs);
1951         if (asf1d->bDescriptorType != UDESC_CS_INTERFACE ||
1952             asf1d->bDescriptorSubtype != FORMAT_TYPE)
1953                 return USBD_INVAL;
1954         offs += asf1d->bLength;
1955         if (offs > size)
1956                 return USBD_INVAL;
1957
1958         if (asf1d->bFormatType != FORMAT_TYPE_I) {
1959                 kprintf("%s: ignored setting with type %d format\n",
1960                        device_get_nameunit(sc->sc_dev), UGETW(asid->wFormatTag));
1961                 return USBD_NORMAL_COMPLETION;
1962         }
1963
1964         ed = (const void *)(buf + offs);
1965         if (ed->bDescriptorType != UDESC_ENDPOINT)
1966                 return USBD_INVAL;
1967         DPRINTF(("uaudio_process_as: endpoint[0] bLength=%d bDescriptorType=%d "
1968                  "bEndpointAddress=%d bmAttributes=0x%x wMaxPacketSize=%d "
1969                  "bInterval=%d bRefresh=%d bSynchAddress=%d\n",
1970                  ed->bLength, ed->bDescriptorType, ed->bEndpointAddress,
1971                  ed->bmAttributes, UGETW(ed->wMaxPacketSize),
1972                  ed->bInterval, ed->bRefresh, ed->bSynchAddress));
1973         offs += ed->bLength;
1974         if (offs > size)
1975                 return USBD_INVAL;
1976         if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
1977                 return USBD_INVAL;
1978
1979         dir = UE_GET_DIR(ed->bEndpointAddress);
1980         type = UE_GET_ISO_TYPE(ed->bmAttributes);
1981         if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_INP_ASYNC) &&
1982             dir == UE_DIR_IN && type == UE_ISO_ADAPT)
1983                 type = UE_ISO_ASYNC;
1984
1985         /* We can't handle endpoints that need a sync pipe yet. */
1986         sync = FALSE;
1987         if (dir == UE_DIR_IN && type == UE_ISO_ADAPT) {
1988                 sync = TRUE;
1989 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
1990                 kprintf("%s: ignored input endpoint of type adaptive\n",
1991                        device_get_nameunit(sc->sc_dev));
1992                 return USBD_NORMAL_COMPLETION;
1993 #endif
1994         }
1995         if (dir != UE_DIR_IN && type == UE_ISO_ASYNC) {
1996                 sync = TRUE;
1997 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
1998                 kprintf("%s: ignored output endpoint of type async\n",
1999                        device_get_nameunit(sc->sc_dev));
2000                 return USBD_NORMAL_COMPLETION;
2001 #endif
2002         }
2003
2004         sed = (const void *)(buf + offs);
2005         if (sed->bDescriptorType != UDESC_CS_ENDPOINT ||
2006             sed->bDescriptorSubtype != AS_GENERAL)
2007                 return USBD_INVAL;
2008         DPRINTF((" streadming_endpoint: offset=%d bLength=%d\n", offs, sed->bLength));
2009         offs += sed->bLength;
2010         if (offs > size)
2011                 return USBD_INVAL;
2012
2013         if (sync && id->bNumEndpoints <= 1) {
2014                 kprintf("%s: a sync-pipe endpoint but no other endpoint\n",
2015                        device_get_nameunit(sc->sc_dev));
2016                 return USBD_INVAL;
2017         }
2018         if (!sync && id->bNumEndpoints > 1) {
2019                 kprintf("%s: non sync-pipe endpoint but multiple endpoints\n",
2020                        device_get_nameunit(sc->sc_dev));
2021                 return USBD_INVAL;
2022         }
2023         epdesc1 = NULL;
2024         if (id->bNumEndpoints > 1) {
2025                 epdesc1 = (const void*)(buf + offs);
2026                 if (epdesc1->bDescriptorType != UDESC_ENDPOINT)
2027                         return USBD_INVAL;
2028                 DPRINTF(("uaudio_process_as: endpoint[1] bLength=%d "
2029                          "bDescriptorType=%d bEndpointAddress=%d "
2030                          "bmAttributes=0x%x wMaxPacketSize=%d bInterval=%d "
2031                          "bRefresh=%d bSynchAddress=%d\n",
2032                          epdesc1->bLength, epdesc1->bDescriptorType,
2033                          epdesc1->bEndpointAddress, epdesc1->bmAttributes,
2034                          UGETW(epdesc1->wMaxPacketSize), epdesc1->bInterval,
2035                          epdesc1->bRefresh, epdesc1->bSynchAddress));
2036                 offs += epdesc1->bLength;
2037                 if (offs > size)
2038                         return USBD_INVAL;
2039                 if (epdesc1->bSynchAddress != 0) {
2040                         kprintf("%s: invalid endpoint: bSynchAddress=0\n",
2041                                device_get_nameunit(sc->sc_dev));
2042                         return USBD_INVAL;
2043                 }
2044                 if (UE_GET_XFERTYPE(epdesc1->bmAttributes) != UE_ISOCHRONOUS) {
2045                         kprintf("%s: invalid endpoint: bmAttributes=0x%x\n",
2046                                device_get_nameunit(sc->sc_dev), epdesc1->bmAttributes);
2047                         return USBD_INVAL;
2048                 }
2049                 if (epdesc1->bEndpointAddress != ed->bSynchAddress) {
2050                         kprintf("%s: invalid endpoint addresses: "
2051                                "ep[0]->bSynchAddress=0x%x "
2052                                "ep[1]->bEndpointAddress=0x%x\n",
2053                                device_get_nameunit(sc->sc_dev), ed->bSynchAddress,
2054                                epdesc1->bEndpointAddress);
2055                         return USBD_INVAL;
2056                 }
2057                 /* UE_GET_ADDR(epdesc1->bEndpointAddress), and epdesc1->bRefresh */
2058         }
2059
2060         format = UGETW(asid->wFormatTag);
2061         chan = asf1d->bNrChannels;
2062         prec = asf1d->bBitResolution;
2063         if (prec != 8 && prec != 16 && prec != 24 && prec != 32) {
2064                 kprintf("%s: ignored setting with precision %d\n",
2065                        device_get_nameunit(sc->sc_dev), prec);
2066                 return USBD_NORMAL_COMPLETION;
2067         }
2068         switch (format) {
2069         case UA_FMT_PCM:
2070                 if (prec == 8) {
2071                         sc->sc_altflags |= HAS_8;
2072                 } else if (prec == 16) {
2073                         sc->sc_altflags |= HAS_16;
2074                 } else if (prec == 24) {
2075                         sc->sc_altflags |= HAS_24;
2076                 } else if (prec == 32) {
2077                         sc->sc_altflags |= HAS_32;
2078                 }
2079                 enc = AUDIO_ENCODING_SLINEAR_LE;
2080                 format_str = "pcm";
2081                 break;
2082         case UA_FMT_PCM8:
2083                 enc = AUDIO_ENCODING_ULINEAR_LE;
2084                 sc->sc_altflags |= HAS_8U;
2085                 format_str = "pcm8";
2086                 break;
2087         case UA_FMT_ALAW:
2088                 enc = AUDIO_ENCODING_ALAW;
2089                 sc->sc_altflags |= HAS_ALAW;
2090                 format_str = "alaw";
2091                 break;
2092         case UA_FMT_MULAW:
2093                 enc = AUDIO_ENCODING_ULAW;
2094                 sc->sc_altflags |= HAS_MULAW;
2095                 format_str = "mulaw";
2096                 break;
2097         case UA_FMT_IEEE_FLOAT:
2098         default:
2099                 kprintf("%s: ignored setting with format %d\n",
2100                        device_get_nameunit(sc->sc_dev), format);
2101                 return USBD_NORMAL_COMPLETION;
2102         }
2103 #ifdef USB_DEBUG
2104         kprintf("%s: %s: %dch, %d/%dbit, %s,", device_get_nameunit(sc->sc_dev),
2105                dir == UE_DIR_IN ? "recording" : "playback",
2106                chan, prec, asf1d->bSubFrameSize * 8, format_str);
2107         if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
2108                 kprintf(" %d-%dHz\n", UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
2109         } else {
2110                 int r;
2111                 kprintf(" %d", UA_GETSAMP(asf1d, 0));
2112                 for (r = 1; r < asf1d->bSamFreqType; r++)
2113                         kprintf(",%d", UA_GETSAMP(asf1d, r));
2114                 kprintf("Hz\n");
2115         }
2116 #endif
2117 #if defined(__FreeBSD__) || defined(__DragonFly__)
2118         if (sc->uaudio_sndstat_flag != 0) {
2119                 sbuf_printf(&(sc->uaudio_sndstat), "\n\t");
2120                 sbuf_printf(&(sc->uaudio_sndstat), 
2121                     "mode %d:(%s) %dch, %d/%dbit, %s,", 
2122                     id->bAlternateSetting,
2123                     dir == UE_DIR_IN ? "input" : "output",
2124                     chan, prec, asf1d->bSubFrameSize * 8, format_str);
2125                 if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
2126                         sbuf_printf(&(sc->uaudio_sndstat), " %d-%dHz", 
2127                             UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
2128                 } else {
2129                         int r;
2130                         sbuf_printf(&(sc->uaudio_sndstat), 
2131                             " %d", UA_GETSAMP(asf1d, 0));
2132                         for (r = 1; r < asf1d->bSamFreqType; r++)
2133                                 sbuf_printf(&(sc->uaudio_sndstat), 
2134                                     ",%d", UA_GETSAMP(asf1d, r));
2135                         sbuf_printf(&(sc->uaudio_sndstat), "Hz");
2136                 }
2137         }
2138 #endif
2139         ai.alt = id->bAlternateSetting;
2140         ai.encoding = enc;
2141         ai.attributes = sed->bmAttributes;
2142         ai.idesc = id;
2143         ai.edesc = ed;
2144         ai.edesc1 = epdesc1;
2145         ai.asf1desc = asf1d;
2146         ai.sc_busy = 0;
2147         uaudio_add_alt(sc, &ai);
2148 #ifdef USB_DEBUG
2149         if (ai.attributes & UA_SED_FREQ_CONTROL)
2150                 DPRINTFN(1, ("uaudio_process_as:  FREQ_CONTROL\n"));
2151         if (ai.attributes & UA_SED_PITCH_CONTROL)
2152                 DPRINTFN(1, ("uaudio_process_as:  PITCH_CONTROL\n"));
2153 #endif
2154         sc->sc_mode |= (dir == UE_DIR_OUT) ? AUMODE_PLAY : AUMODE_RECORD;
2155
2156         return USBD_NORMAL_COMPLETION;
2157 }
2158 #undef offs
2159
2160 static usbd_status
2161 uaudio_identify_as(struct uaudio_softc *sc,
2162                    const usb_config_descriptor_t *cdesc)
2163 {
2164         const usb_interface_descriptor_t *id;
2165         const char *buf;
2166         int size, offs;
2167
2168         size = UGETW(cdesc->wTotalLength);
2169         buf = (const char *)cdesc;
2170
2171         /* Locate the AudioStreaming interface descriptor. */
2172         offs = 0;
2173         id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOSTREAM);
2174         if (id == NULL)
2175                 return USBD_INVAL;
2176
2177 #if defined(__FreeBSD__) || defined(__DragonFly__)
2178         sc->uaudio_sndstat_flag = 0;
2179         if (sbuf_new(&(sc->uaudio_sndstat), NULL, 4096, SBUF_AUTOEXTEND) != NULL)
2180                 sc->uaudio_sndstat_flag = 1;
2181 #endif
2182         /* Loop through all the alternate settings. */
2183         while (offs <= size) {
2184                 DPRINTFN(2, ("uaudio_identify: interface=%d offset=%d\n",
2185                     id->bInterfaceNumber, offs));
2186                 switch (id->bNumEndpoints) {
2187                 case 0:
2188                         DPRINTFN(2, ("uaudio_identify: AS null alt=%d\n",
2189                                      id->bAlternateSetting));
2190                         sc->sc_nullalt = id->bAlternateSetting;
2191                         break;
2192                 case 1:
2193 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
2194                 case 2:
2195 #endif
2196                         uaudio_process_as(sc, buf, &offs, size, id);
2197                         break;
2198                 default:
2199                         kprintf("%s: ignored audio interface with %d "
2200                                "endpoints\n",
2201                                device_get_nameunit(sc->sc_dev), id->bNumEndpoints);
2202                         break;
2203                 }
2204                 id = uaudio_find_iface(buf, size, &offs,UISUBCLASS_AUDIOSTREAM);
2205                 if (id == NULL)
2206                         break;
2207         }
2208 #if defined(__FreeBSD__) || defined(__DragonFly__)
2209         sbuf_finish(&(sc->uaudio_sndstat));
2210 #endif
2211         if (offs > size)
2212                 return USBD_INVAL;
2213         DPRINTF(("uaudio_identify_as: %d alts available\n", sc->sc_nalts));
2214
2215         if (sc->sc_mode == 0) {
2216                 kprintf("%s: no usable endpoint found\n",
2217                        device_get_nameunit(sc->sc_dev));
2218                 return USBD_INVAL;
2219         }
2220
2221         return USBD_NORMAL_COMPLETION;
2222 }
2223
2224 static usbd_status
2225 uaudio_identify_ac(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
2226 {
2227         struct io_terminal* iot;
2228         const usb_interface_descriptor_t *id;
2229         const struct usb_audio_control_descriptor *acdp;
2230         const usb_descriptor_t *dp;
2231         const struct usb_audio_output_terminal *pot;
2232         struct terminal_list *tml;
2233         const char *buf, *ibuf, *ibufend;
2234         int size, offs, aclen, ndps, i, j;
2235
2236         size = UGETW(cdesc->wTotalLength);
2237         buf = (const char *)cdesc;
2238
2239         /* Locate the AudioControl interface descriptor. */
2240         offs = 0;
2241         id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOCONTROL);
2242         if (id == NULL)
2243                 return USBD_INVAL;
2244         if (offs + sizeof *acdp > size)
2245                 return USBD_INVAL;
2246         sc->sc_ac_iface = id->bInterfaceNumber;
2247         DPRINTFN(2,("uaudio_identify_ac: AC interface is %d\n", sc->sc_ac_iface));
2248
2249         /* A class-specific AC interface header should follow. */
2250         ibuf = buf + offs;
2251         acdp = (const struct usb_audio_control_descriptor *)ibuf;
2252         if (acdp->bDescriptorType != UDESC_CS_INTERFACE ||
2253             acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)
2254                 return USBD_INVAL;
2255         aclen = UGETW(acdp->wTotalLength);
2256         if (offs + aclen > size)
2257                 return USBD_INVAL;
2258
2259         if (!(usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_BAD_ADC) &&
2260              UGETW(acdp->bcdADC) != UAUDIO_VERSION)
2261                 return USBD_INVAL;
2262
2263         sc->sc_audio_rev = UGETW(acdp->bcdADC);
2264         DPRINTFN(2,("uaudio_identify_ac: found AC header, vers=%03x, len=%d\n",
2265                  sc->sc_audio_rev, aclen));
2266
2267         sc->sc_nullalt = -1;
2268
2269         /* Scan through all the AC specific descriptors */
2270         ibufend = ibuf + aclen;
2271         dp = (const usb_descriptor_t *)ibuf;
2272         ndps = 0;
2273         iot = kmalloc(sizeof(struct io_terminal) * 256, M_TEMP, M_NOWAIT | M_ZERO);
2274         if (iot == NULL) {
2275                 kprintf("%s: no memory\n", __func__);
2276                 return USBD_NOMEM;
2277         }
2278         for (;;) {
2279                 ibuf += dp->bLength;
2280                 if (ibuf >= ibufend)
2281                         break;
2282                 dp = (const usb_descriptor_t *)ibuf;
2283                 if (ibuf + dp->bLength > ibufend) {
2284                         kfree(iot, M_TEMP);
2285                         return USBD_INVAL;
2286                 }
2287                 if (dp->bDescriptorType != UDESC_CS_INTERFACE) {
2288                         kprintf("uaudio_identify_ac: skip desc type=0x%02x\n",
2289                                dp->bDescriptorType);
2290                         continue;
2291                 }
2292                 i = ((const struct usb_audio_input_terminal *)dp)->bTerminalId;
2293                 iot[i].d.desc = dp;
2294                 if (i > ndps)
2295                         ndps = i;
2296         }
2297         ndps++;
2298
2299         /* construct io_terminal */
2300         for (i = 0; i < ndps; i++) {
2301                 dp = iot[i].d.desc;
2302                 if (dp == NULL)
2303                         continue;
2304                 if (dp->bDescriptorSubtype != UDESCSUB_AC_OUTPUT)
2305                         continue;
2306                 pot = iot[i].d.ot;
2307                 tml = uaudio_io_terminaltype(UGETW(pot->wTerminalType), iot, i);
2308                 if (tml != NULL)
2309                         kfree(tml, M_TEMP);
2310         }
2311
2312 #ifdef USB_DEBUG
2313         for (i = 0; i < 256; i++) {
2314                 struct usb_audio_cluster cluster;
2315
2316                 if (iot[i].d.desc == NULL)
2317                         continue;
2318                 kprintf("id %d:\t", i);
2319                 switch (iot[i].d.desc->bDescriptorSubtype) {
2320                 case UDESCSUB_AC_INPUT:
2321                         kprintf("AC_INPUT type=%s\n", uaudio_get_terminal_name
2322                                   (UGETW(iot[i].d.it->wTerminalType)));
2323                         kprintf("\t");
2324                         cluster = uaudio_get_cluster(i, iot);
2325                         uaudio_dump_cluster(&cluster);
2326                         kprintf("\n");
2327                         break;
2328                 case UDESCSUB_AC_OUTPUT:
2329                         kprintf("AC_OUTPUT type=%s ", uaudio_get_terminal_name
2330                                   (UGETW(iot[i].d.ot->wTerminalType)));
2331                         kprintf("src=%d\n", iot[i].d.ot->bSourceId);
2332                         break;
2333                 case UDESCSUB_AC_MIXER:
2334                         kprintf("AC_MIXER src=");
2335                         for (j = 0; j < iot[i].d.mu->bNrInPins; j++)
2336                                 kprintf("%d ", iot[i].d.mu->baSourceId[j]);
2337                         kprintf("\n\t");
2338                         cluster = uaudio_get_cluster(i, iot);
2339                         uaudio_dump_cluster(&cluster);
2340                         kprintf("\n");
2341                         break;
2342                 case UDESCSUB_AC_SELECTOR:
2343                         kprintf("AC_SELECTOR src=");
2344                         for (j = 0; j < iot[i].d.su->bNrInPins; j++)
2345                                 kprintf("%d ", iot[i].d.su->baSourceId[j]);
2346                         kprintf("\n");
2347                         break;
2348                 case UDESCSUB_AC_FEATURE:
2349                         kprintf("AC_FEATURE src=%d\n", iot[i].d.fu->bSourceId);
2350                         break;
2351                 case UDESCSUB_AC_PROCESSING:
2352                         kprintf("AC_PROCESSING src=");
2353                         for (j = 0; j < iot[i].d.pu->bNrInPins; j++)
2354                                 kprintf("%d ", iot[i].d.pu->baSourceId[j]);
2355                         kprintf("\n\t");
2356                         cluster = uaudio_get_cluster(i, iot);
2357                         uaudio_dump_cluster(&cluster);
2358                         kprintf("\n");
2359                         break;
2360                 case UDESCSUB_AC_EXTENSION:
2361                         kprintf("AC_EXTENSION src=");
2362                         for (j = 0; j < iot[i].d.eu->bNrInPins; j++)
2363                                 kprintf("%d ", iot[i].d.eu->baSourceId[j]);
2364                         kprintf("\n\t");
2365                         cluster = uaudio_get_cluster(i, iot);
2366                         uaudio_dump_cluster(&cluster);
2367                         kprintf("\n");
2368                         break;
2369                 default:
2370                         kprintf("unknown audio control (subtype=%d)\n",
2371                                   iot[i].d.desc->bDescriptorSubtype);
2372                 }
2373                 for (j = 0; j < iot[i].inputs_size; j++) {
2374                         int k;
2375                         kprintf("\tinput%d: ", j);
2376                         tml = iot[i].inputs[j];
2377                         if (tml == NULL) {
2378                                 kprintf("NULL\n");
2379                                 continue;
2380                         }
2381                         for (k = 0; k < tml->size; k++)
2382                                 kprintf("%s ", uaudio_get_terminal_name
2383                                           (tml->terminals[k]));
2384                         kprintf("\n");
2385                 }
2386                 kprintf("\toutput: ");
2387                 tml = iot[i].output;
2388                 for (j = 0; j < tml->size; j++)
2389                         kprintf("%s ", uaudio_get_terminal_name(tml->terminals[j]));
2390                 kprintf("\n");
2391         }
2392 #endif
2393
2394         for (i = 0; i < ndps; i++) {
2395                 dp = iot[i].d.desc;
2396                 if (dp == NULL)
2397                         continue;
2398                 DPRINTF(("uaudio_identify_ac: id=%d subtype=%d\n",
2399                          i, dp->bDescriptorSubtype));
2400                 switch (dp->bDescriptorSubtype) {
2401                 case UDESCSUB_AC_HEADER:
2402                         kprintf("uaudio_identify_ac: unexpected AC header\n");
2403                         break;
2404                 case UDESCSUB_AC_INPUT:
2405                         uaudio_add_input(sc, iot, i);
2406                         break;
2407                 case UDESCSUB_AC_OUTPUT:
2408                         uaudio_add_output(sc, iot, i);
2409                         break;
2410                 case UDESCSUB_AC_MIXER:
2411                         uaudio_add_mixer(sc, iot, i);
2412                         break;
2413                 case UDESCSUB_AC_SELECTOR:
2414                         uaudio_add_selector(sc, iot, i);
2415                         break;
2416                 case UDESCSUB_AC_FEATURE:
2417                         uaudio_add_feature(sc, iot, i);
2418                         break;
2419                 case UDESCSUB_AC_PROCESSING:
2420                         uaudio_add_processing(sc, iot, i);
2421                         break;
2422                 case UDESCSUB_AC_EXTENSION:
2423                         uaudio_add_extension(sc, iot, i);
2424                         break;
2425                 default:
2426                         kprintf("uaudio_identify_ac: bad AC desc subtype=0x%02x\n",
2427                                dp->bDescriptorSubtype);
2428                         break;
2429                 }
2430         }
2431
2432         /* delete io_terminal */
2433         for (i = 0; i < 256; i++) {
2434                 if (iot[i].d.desc == NULL)
2435                         continue;
2436                 if (iot[i].inputs != NULL) {
2437                         for (j = 0; j < iot[i].inputs_size; j++) {
2438                                 if (iot[i].inputs[j] != NULL)
2439                                         kfree(iot[i].inputs[j], M_TEMP);
2440                         }
2441                         kfree(iot[i].inputs, M_TEMP);
2442                 }
2443                 if (iot[i].output != NULL)
2444                         kfree(iot[i].output, M_TEMP);
2445                 iot[i].d.desc = NULL;
2446         }
2447         kfree(iot, M_TEMP);
2448
2449         return USBD_NORMAL_COMPLETION;
2450 }
2451
2452 #if defined(__NetBSD__) || defined(__OpenBSD__)
2453 static int
2454 uaudio_query_devinfo(void *addr, mixer_devinfo_t *mi)
2455 {
2456         struct uaudio_softc *sc;
2457         struct mixerctl *mc;
2458         int n, nctls, i;
2459
2460         sc = addr;
2461         DPRINTFN(2,("uaudio_query_devinfo: index=%d\n", mi->index));
2462         if (sc->sc_dying)
2463                 return EIO;
2464
2465         n = mi->index;
2466         nctls = sc->sc_nctls;
2467
2468         switch (n) {
2469         case UAC_OUTPUT:
2470                 mi->type = AUDIO_MIXER_CLASS;
2471                 mi->mixer_class = UAC_OUTPUT;
2472                 mi->next = mi->prev = AUDIO_MIXER_LAST;
2473                 strlcpy(mi->label.name, AudioCoutputs, sizeof(mi->label.name));
2474                 return 0;
2475         case UAC_INPUT:
2476                 mi->type = AUDIO_MIXER_CLASS;
2477                 mi->mixer_class = UAC_INPUT;
2478                 mi->next = mi->prev = AUDIO_MIXER_LAST;
2479                 strlcpy(mi->label.name, AudioCinputs, sizeof(mi->label.name));
2480                 return 0;
2481         case UAC_EQUAL:
2482                 mi->type = AUDIO_MIXER_CLASS;
2483                 mi->mixer_class = UAC_EQUAL;
2484                 mi->next = mi->prev = AUDIO_MIXER_LAST;
2485                 strlcpy(mi->label.name, AudioCequalization,
2486                     sizeof(mi->label.name));
2487                 return 0;
2488         case UAC_RECORD:
2489                 mi->type = AUDIO_MIXER_CLASS;
2490                 mi->mixer_class = UAC_RECORD;
2491                 mi->next = mi->prev = AUDIO_MIXER_LAST;
2492                 strlcpy(mi->label.name, AudioCrecord, sizeof(mi->label.name));
2493                 return 0;
2494         default:
2495                 break;
2496         }
2497
2498         n -= UAC_NCLASSES;
2499         if (n < 0 || n >= nctls)
2500                 return ENXIO;
2501
2502         mc = &sc->sc_ctls[n];
2503         strlcpy(mi->label.name, mc->ctlname, sizeof(mi->label.name));
2504         mi->mixer_class = mc->class;
2505         mi->next = mi->prev = AUDIO_MIXER_LAST; /* XXX */
2506         switch (mc->type) {
2507         case MIX_ON_OFF:
2508                 mi->type = AUDIO_MIXER_ENUM;
2509                 mi->un.e.num_mem = 2;
2510                 strlcpy(mi->un.e.member[0].label.name, AudioNoff,
2511                     sizeof(mi->un.e.member[0].label.name));
2512                 mi->un.e.member[0].ord = 0;
2513                 strlcpy(mi->un.e.member[1].label.name, AudioNon,
2514                     sizeof(mi->un.e.member[1].label.name));
2515                 mi->un.e.member[1].ord = 1;
2516                 break;
2517         case MIX_SELECTOR:
2518                 mi->type = AUDIO_MIXER_ENUM;
2519                 mi->un.e.num_mem = mc->maxval - mc->minval + 1;
2520                 for (i = 0; i <= mc->maxval - mc->minval; i++) {
2521                         ksnprintf(mi->un.e.member[i].label.name,
2522                                  sizeof(mi->un.e.member[i].label.name),
2523                                  "%d", i + mc->minval);
2524                         mi->un.e.member[i].ord = i + mc->minval;
2525                 }
2526                 break;
2527         default:
2528                 mi->type = AUDIO_MIXER_VALUE;
2529                 strncpy(mi->un.v.units.name, mc->ctlunit, MAX_AUDIO_DEV_LEN);
2530                 mi->un.v.num_channels = mc->nchan;
2531                 mi->un.v.delta = mc->delta;
2532                 break;
2533         }
2534         return 0;
2535 }
2536
2537 static int
2538 uaudio_open(void *addr, int flags)
2539 {
2540         struct uaudio_softc *sc;
2541
2542         sc = addr;
2543         DPRINTF(("uaudio_open: sc=%p\n", sc));
2544         if (sc->sc_dying)
2545                 return EIO;
2546
2547         if ((flags & FWRITE) && !(sc->sc_mode & AUMODE_PLAY))
2548                 return EACCES;
2549         if ((flags & FREAD) && !(sc->sc_mode & AUMODE_RECORD))
2550                 return EACCES;
2551
2552         return 0;
2553 }
2554
2555 /*
2556  * Close function is called at splaudio().
2557  */
2558 static void
2559 uaudio_close(void *addr)
2560 {
2561 }
2562
2563 static int
2564 uaudio_drain(void *addr)
2565 {
2566         struct uaudio_softc *sc;
2567
2568         sc = addr;
2569         usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
2570
2571         return 0;
2572 }
2573
2574 static int
2575 uaudio_halt_out_dma(void *addr)
2576 {
2577         struct uaudio_softc *sc;
2578
2579         sc = addr;
2580         if (sc->sc_dying)
2581                 return EIO;
2582
2583         DPRINTF(("uaudio_halt_out_dma: enter\n"));
2584         if (sc->sc_playchan.pipe != NULL) {
2585                 uaudio_chan_close(sc, &sc->sc_playchan);
2586                 sc->sc_playchan.pipe = NULL;
2587                 uaudio_chan_free_buffers(sc, &sc->sc_playchan);
2588                 sc->sc_playchan.intr = NULL;
2589         }
2590         return 0;
2591 }
2592
2593 static int
2594 uaudio_halt_in_dma(void *addr)
2595 {
2596         struct uaudio_softc *sc;
2597
2598         DPRINTF(("uaudio_halt_in_dma: enter\n"));
2599         sc = addr;
2600         if (sc->sc_recchan.pipe != NULL) {
2601                 uaudio_chan_close(sc, &sc->sc_recchan);
2602                 sc->sc_recchan.pipe = NULL;
2603                 uaudio_chan_free_buffers(sc, &sc->sc_recchan);
2604                 sc->sc_recchan.intr = NULL;
2605         }
2606         return 0;
2607 }
2608
2609 static int
2610 uaudio_getdev(void *addr, struct audio_device *retp)
2611 {
2612         struct uaudio_softc *sc;
2613
2614         DPRINTF(("uaudio_mixer_getdev:\n"));
2615         sc = addr;
2616         if (sc->sc_dying)
2617                 return EIO;
2618
2619         *retp = uaudio_device;
2620         return 0;
2621 }
2622
2623 /*
2624  * Make sure the block size is large enough to hold all outstanding transfers.
2625  */
2626 static int
2627 uaudio_round_blocksize(void *addr, int blk)
2628 {
2629         struct uaudio_softc *sc;
2630         int b;
2631
2632         sc = addr;
2633         DPRINTF(("uaudio_round_blocksize: blk=%d mode=%s\n", blk,
2634                 mode == AUMODE_PLAY ? "AUMODE_PLAY" : "AUMODE_RECORD"));
2635
2636         /* chan.bytes_per_frame can be 0. */
2637         if (mode == AUMODE_PLAY || sc->sc_recchan.bytes_per_frame <= 0) {
2638                 b = param->sample_rate * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
2639
2640                 /*
2641                  * This does not make accurate value in the case
2642                  * of b % USB_FRAMES_PER_SECOND != 0
2643                  */
2644                 b /= USB_FRAMES_PER_SECOND;
2645
2646                 b *= param->precision / 8 * param->channels;
2647         } else {
2648                 /*
2649                  * use wMaxPacketSize in bytes_per_frame.
2650                  * See uaudio_set_params() and uaudio_chan_init()
2651                  */
2652                 b = sc->sc_recchan.bytes_per_frame
2653                         * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
2654         }
2655
2656         if (b <= 0)
2657                 b = 1;
2658         blk = blk <= b ? b : blk / b * b;
2659
2660 #ifdef DIAGNOSTIC
2661         if (blk <= 0) {
2662                 kprintf("uaudio_round_blocksize: blk=%d\n", blk);
2663                 blk = 512;
2664         }
2665 #endif
2666
2667         DPRINTF(("uaudio_round_blocksize: resultant blk=%d\n", blk));
2668         return blk;
2669 }
2670
2671 static int
2672 uaudio_get_props(void *addr)
2673 {
2674         return AUDIO_PROP_FULLDUPLEX | AUDIO_PROP_INDEPENDENT;
2675
2676 }
2677 #endif  /* NetBSD or OpenBSD */
2678
2679 static int
2680 uaudio_get(struct uaudio_softc *sc, int which, int type, int wValue,
2681            int wIndex, int len)
2682 {
2683         usb_device_request_t req;
2684         uint8_t data[4];
2685         usbd_status err;
2686         int val;
2687
2688 #if defined(__FreeBSD__) || defined(__DragonFly__)
2689         if (sc->sc_dying)
2690                 return EIO;
2691 #endif
2692
2693         if (wValue == -1)
2694                 return 0;
2695
2696         req.bmRequestType = type;
2697         req.bRequest = which;
2698         USETW(req.wValue, wValue);
2699         USETW(req.wIndex, wIndex);
2700         USETW(req.wLength, len);
2701         DPRINTFN(2,("uaudio_get: type=0x%02x req=0x%02x wValue=0x%04x "
2702                     "wIndex=0x%04x len=%d\n",
2703                     type, which, wValue, wIndex, len));
2704         err = usbd_do_request(sc->sc_udev, &req, data);
2705         if (err) {
2706                 DPRINTF(("uaudio_get: err=%s\n", usbd_errstr(err)));
2707                 return -1;
2708         }
2709         switch (len) {
2710         case 1:
2711                 val = data[0];
2712                 break;
2713         case 2:
2714                 val = data[0] | (data[1] << 8);
2715                 break;
2716         default:
2717                 DPRINTF(("uaudio_get: bad length=%d\n", len));
2718                 return -1;
2719         }
2720         DPRINTFN(2,("uaudio_get: val=%d\n", val));
2721         return val;
2722 }
2723
2724 static void
2725 uaudio_set(struct uaudio_softc *sc, int which, int type, int wValue,
2726            int wIndex, int len, int val)
2727 {
2728         usb_device_request_t req;
2729         uint8_t data[4];
2730         usbd_status err;
2731
2732 #if defined(__FreeBSD__) || defined(__DragonFly__)
2733         if (sc->sc_dying)
2734                 return;
2735 #endif
2736
2737         if (wValue == -1)
2738                 return;
2739
2740         req.bmRequestType = type;
2741         req.bRequest = which;
2742         USETW(req.wValue, wValue);
2743         USETW(req.wIndex, wIndex);
2744         USETW(req.wLength, len);
2745         switch (len) {
2746         case 1:
2747                 data[0] = val;
2748                 break;
2749         case 2:
2750                 data[0] = val;
2751                 data[1] = val >> 8;
2752                 break;
2753         default:
2754                 return;
2755         }
2756         DPRINTFN(2,("uaudio_set: type=0x%02x req=0x%02x wValue=0x%04x "
2757                     "wIndex=0x%04x len=%d, val=%d\n",
2758                     type, which, wValue, wIndex, len, val & 0xffff));
2759         err = usbd_do_request(sc->sc_udev, &req, data);
2760 #ifdef USB_DEBUG
2761         if (err)
2762                 DPRINTF(("uaudio_set: err=%d\n", err));
2763 #endif
2764 }
2765
2766 static int
2767 uaudio_signext(int type, int val)
2768 {
2769         if (!MIX_UNSIGNED(type)) {
2770                 if (MIX_SIZE(type) == 2)
2771                         val = (int16_t)val;
2772                 else
2773                         val = (int8_t)val;
2774         }
2775         return val;
2776 }
2777
2778 #if defined(__NetBSD__) || defined(__OpenBSD__)
2779 static int
2780 uaudio_value2bsd(struct mixerctl *mc, int val)
2781 {
2782         DPRINTFN(5, ("uaudio_value2bsd: type=%03x val=%d min=%d max=%d ",
2783                      mc->type, val, mc->minval, mc->maxval));
2784         if (mc->type == MIX_ON_OFF) {
2785                 val = (val != 0);
2786         } else if (mc->type == MIX_SELECTOR) {
2787                 if (val < mc->minval || val > mc->maxval)
2788                         val = mc->minval;
2789         } else
2790                 val = ((uaudio_signext(mc->type, val) - mc->minval) * 255
2791                         + mc->mul/2) / mc->mul;
2792         DPRINTFN(5, ("val'=%d\n", val));
2793         return val;
2794 }
2795 #endif
2796
2797 int
2798 uaudio_bsd2value(struct mixerctl *mc, int val)
2799 {
2800         DPRINTFN(5,("uaudio_bsd2value: type=%03x val=%d min=%d max=%d ",
2801                     mc->type, val, mc->minval, mc->maxval));
2802         if (mc->type == MIX_ON_OFF) {
2803                 val = (val != 0);
2804         } else if (mc->type == MIX_SELECTOR) {
2805                 if (val < mc->minval || val > mc->maxval)
2806                         val = mc->minval;
2807         } else
2808                 val = (val + mc->delta/2) * mc->mul / 255 + mc->minval;
2809         DPRINTFN(5, ("val'=%d\n", val));
2810         return val;
2811 }
2812
2813 #if defined(__NetBSD__) || defined(__OpenBSD__)
2814 static int
2815 uaudio_ctl_get(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2816                int chan)
2817 {
2818         int val;
2819
2820         DPRINTFN(5,("uaudio_ctl_get: which=%d chan=%d\n", which, chan));
2821         val = uaudio_get(sc, which, UT_READ_CLASS_INTERFACE, mc->wValue[chan],
2822                          mc->wIndex, MIX_SIZE(mc->type));
2823         return uaudio_value2bsd(mc, val);
2824 }
2825 #endif
2826
2827 static void
2828 uaudio_ctl_set(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2829                int chan, int val)
2830 {
2831         val = uaudio_bsd2value(mc, val);
2832         uaudio_set(sc, which, UT_WRITE_CLASS_INTERFACE, mc->wValue[chan],
2833                    mc->wIndex, MIX_SIZE(mc->type), val);
2834 }
2835
2836 #if defined(__NetBSD__) || defined(__OpenBSD__)
2837 static int
2838 uaudio_mixer_get_port(void *addr, mixer_ctrl_t *cp)
2839 {
2840         struct uaudio_softc *sc;
2841         struct mixerctl *mc;
2842         int i, n, vals[MIX_MAX_CHAN], val;
2843
2844         DPRINTFN(2,("uaudio_mixer_get_port: index=%d\n", cp->dev));
2845         sc = addr;
2846         if (sc->sc_dying)
2847                 return EIO;
2848
2849         n = cp->dev - UAC_NCLASSES;
2850         if (n < 0 || n >= sc->sc_nctls)
2851                 return ENXIO;
2852         mc = &sc->sc_ctls[n];
2853
2854         if (mc->type == MIX_ON_OFF) {
2855                 if (cp->type != AUDIO_MIXER_ENUM)
2856                         return EINVAL;
2857                 cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
2858         } else if (mc->type == MIX_SELECTOR) {
2859                 if (cp->type != AUDIO_MIXER_ENUM)
2860                         return EINVAL;
2861                 cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
2862         } else {
2863                 if (cp->type != AUDIO_MIXER_VALUE)
2864                         return (EINVAL);
2865                 if (cp->un.value.num_channels != 1 &&
2866                     cp->un.value.num_channels != mc->nchan)
2867                         return EINVAL;
2868                 for (i = 0; i < mc->nchan; i++)
2869                         vals[i] = uaudio_ctl_get(sc, GET_CUR, mc, i);
2870                 if (cp->un.value.num_channels == 1 && mc->nchan != 1) {
2871                         for (val = 0, i = 0; i < mc->nchan; i++)
2872                                 val += vals[i];
2873                         vals[0] = val / mc->nchan;
2874                 }
2875                 for (i = 0; i < cp->un.value.num_channels; i++)
2876                         cp->un.value.level[i] = vals[i];
2877         }
2878
2879         return 0;
2880 }
2881
2882 static int
2883 uaudio_mixer_set_port(void *addr, mixer_ctrl_t *cp)
2884 {
2885         struct uaudio_softc *sc;
2886         struct mixerctl *mc;
2887         int i, n, vals[MIX_MAX_CHAN];
2888
2889         DPRINTFN(2,("uaudio_mixer_set_port: index = %d\n", cp->dev));
2890         sc = addr;
2891         if (sc->sc_dying)
2892                 return EIO;
2893
2894         n = cp->dev - UAC_NCLASSES;
2895         if (n < 0 || n >= sc->sc_nctls)
2896                 return ENXIO;
2897         mc = &sc->sc_ctls[n];
2898
2899         if (mc->type == MIX_ON_OFF) {
2900                 if (cp->type != AUDIO_MIXER_ENUM)
2901                         return EINVAL;
2902                 uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
2903         } else if (mc->type == MIX_SELECTOR) {
2904                 if (cp->type != AUDIO_MIXER_ENUM)
2905                         return EINVAL;
2906                 uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
2907         } else {
2908                 if (cp->type != AUDIO_MIXER_VALUE)
2909                         return EINVAL;
2910                 if (cp->un.value.num_channels == 1)
2911                         for (i = 0; i < mc->nchan; i++)
2912                                 vals[i] = cp->un.value.level[0];
2913                 else if (cp->un.value.num_channels == mc->nchan)
2914                         for (i = 0; i < mc->nchan; i++)
2915                                 vals[i] = cp->un.value.level[i];
2916                 else
2917                         return EINVAL;
2918                 for (i = 0; i < mc->nchan; i++)
2919                         uaudio_ctl_set(sc, SET_CUR, mc, i, vals[i]);
2920         }
2921         return 0;
2922 }
2923
2924 static int
2925 uaudio_trigger_input(void *addr, void *start, void *end, int blksize,
2926                      void (*intr)(void *), void *arg,
2927                      struct audio_params *param)
2928 {
2929         struct uaudio_softc *sc;
2930         struct chan *ch;
2931         usbd_status err;
2932         int i, s;
2933
2934         sc = addr;
2935         if (sc->sc_dying)
2936                 return EIO;
2937
2938         DPRINTFN(3,("uaudio_trigger_input: sc=%p start=%p end=%p "
2939                     "blksize=%d\n", sc, start, end, blksize));
2940         ch = &sc->sc_recchan;
2941         uaudio_chan_set_param(ch, start, end, blksize);
2942         DPRINTFN(3,("uaudio_trigger_input: sample_size=%d bytes/frame=%d "
2943                     "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
2944                     ch->fraction));
2945
2946         err = uaudio_chan_alloc_buffers(sc, ch);
2947         if (err)
2948                 return EIO;
2949
2950         err = uaudio_chan_open(sc, ch);
2951         if (err) {
2952                 uaudio_chan_free_buffers(sc, ch);
2953                 return EIO;
2954         }
2955
2956         ch->intr = intr;
2957         ch->arg = arg;
2958
2959         s = splusb();
2960         for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
2961                 uaudio_chan_rtransfer(ch);
2962         splx(s);
2963
2964         return 0;
2965 }
2966
2967 static int
2968 uaudio_trigger_output(void *addr, void *start, void *end, int blksize,
2969                       void (*intr)(void *), void *arg,
2970                       struct audio_params *param)
2971 {
2972         struct uaudio_softc *sc;
2973         struct chan *ch;
2974         usbd_status err;
2975         int i, s;
2976
2977         sc = addr;
2978         if (sc->sc_dying)
2979                 return EIO;
2980
2981         DPRINTFN(3,("uaudio_trigger_output: sc=%p start=%p end=%p "
2982                     "blksize=%d\n", sc, start, end, blksize));
2983         ch = &sc->sc_playchan;
2984         uaudio_chan_set_param(ch, start, end, blksize);
2985         DPRINTFN(3,("uaudio_trigger_output: sample_size=%d bytes/frame=%d "
2986                     "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
2987                     ch->fraction));
2988
2989         err = uaudio_chan_alloc_buffers(sc, ch);
2990         if (err)
2991                 return EIO;
2992
2993         err = uaudio_chan_open(sc, ch);
2994         if (err) {
2995                 uaudio_chan_free_buffers(sc, ch);
2996                 return EIO;
2997         }
2998
2999         ch->intr = intr;
3000         ch->arg = arg;
3001
3002         s = splusb();
3003         for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
3004                 uaudio_chan_ptransfer(ch);
3005         splx(s);
3006
3007         return 0;
3008 }
3009 #endif  /* NetBSD or OpenBSD */
3010
3011 /* Set up a pipe for a channel. */
3012 static usbd_status
3013 uaudio_chan_open(struct uaudio_softc *sc, struct chan *ch)
3014 {
3015         struct as_info *as;
3016         int endpt;
3017         usbd_status err;
3018
3019 #if defined(__FreeBSD__) || defined(__DragonFly__)
3020         if (sc->sc_dying)
3021                 return EIO;
3022 #endif
3023
3024         as = &sc->sc_alts[ch->altidx];
3025         endpt = as->edesc->bEndpointAddress;
3026         DPRINTF(("uaudio_chan_open: endpt=0x%02x, speed=%d, alt=%d\n",
3027                  endpt, ch->sample_rate, as->alt));
3028
3029         /* Set alternate interface corresponding to the mode. */
3030         err = usbd_set_interface(as->ifaceh, as->alt);
3031         if (err)
3032                 return err;
3033
3034         /*
3035          * If just one sampling rate is supported,
3036          * no need to call uaudio_set_speed().
3037          * Roland SD-90 freezes by a SAMPLING_FREQ_CONTROL request.
3038          */
3039         if (as->asf1desc->bSamFreqType != 1) {
3040                 err = uaudio_set_speed(sc, endpt, ch->sample_rate);
3041                 if (err)
3042                         DPRINTF(("uaudio_chan_open: set_speed failed err=%s\n",
3043                                  usbd_errstr(err)));
3044         }
3045
3046         ch->pipe = 0;
3047         ch->sync_pipe = 0;
3048         DPRINTF(("uaudio_chan_open: create pipe to 0x%02x\n", endpt));
3049         err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->pipe);
3050         if (err)
3051                 return err;
3052         if (as->edesc1 != NULL) {
3053                 endpt = as->edesc1->bEndpointAddress;
3054                 DPRINTF(("uaudio_chan_open: create sync-pipe to 0x%02x\n", endpt));
3055                 err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->sync_pipe);
3056         }
3057         return err;
3058 }
3059
3060 static void
3061 uaudio_chan_close(struct uaudio_softc *sc, struct chan *ch)
3062 {
3063         struct as_info *as;
3064
3065 #if defined(__FreeBSD__) || defined(__DragonFly__)
3066         if (sc->sc_dying)
3067                 return ;
3068 #endif
3069
3070         as = &sc->sc_alts[ch->altidx];
3071         as->sc_busy = 0;
3072         if (sc->sc_nullalt >= 0) {
3073                 DPRINTF(("uaudio_chan_close: set null alt=%d\n",
3074                          sc->sc_nullalt));
3075                 usbd_set_interface(as->ifaceh, sc->sc_nullalt);
3076         }
3077         if (ch->pipe) {
3078                 usbd_abort_pipe(ch->pipe);
3079                 usbd_close_pipe(ch->pipe);
3080         }
3081         if (ch->sync_pipe) {
3082                 usbd_abort_pipe(ch->sync_pipe);
3083                 usbd_close_pipe(ch->sync_pipe);
3084         }
3085 }
3086
3087 static usbd_status
3088 uaudio_chan_alloc_buffers(struct uaudio_softc *sc, struct chan *ch)
3089 {
3090         usbd_xfer_handle xfer;
3091         void *buf;
3092         int i, size;
3093
3094         size = (ch->bytes_per_frame + ch->sample_size) * UAUDIO_NFRAMES;
3095         for (i = 0; i < UAUDIO_NCHANBUFS; i++) {
3096                 xfer = usbd_alloc_xfer(sc->sc_udev);
3097                 if (xfer == 0)
3098                         goto bad;
3099                 ch->chanbufs[i].xfer = xfer;
3100                 buf = usbd_alloc_buffer(xfer, size);
3101                 if (buf == 0) {
3102                         i++;
3103                         goto bad;
3104                 }
3105                 ch->chanbufs[i].buffer = buf;
3106                 ch->chanbufs[i].chan = ch;
3107         }
3108
3109         return USBD_NORMAL_COMPLETION;
3110
3111 bad:
3112         while (--i >= 0)
3113                 /* implicit buffer kfree */
3114                 usbd_free_xfer(ch->chanbufs[i].xfer);
3115         return USBD_NOMEM;
3116 }
3117
3118 static void
3119 uaudio_chan_free_buffers(struct uaudio_softc *sc, struct chan *ch)
3120 {
3121         int i;
3122
3123         for (i = 0; i < UAUDIO_NCHANBUFS; i++)
3124                 usbd_free_xfer(ch->chanbufs[i].xfer);
3125 }
3126
3127 /* Called at splusb() */
3128 static void
3129 uaudio_chan_ptransfer(struct chan *ch)
3130 {
3131         struct chanbuf *cb;
3132         int i, n, size, residue, total;
3133
3134         if (ch->sc->sc_dying)
3135                 return;
3136
3137         /* Pick the next channel buffer. */
3138         cb = &ch->chanbufs[ch->curchanbuf];
3139         if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
3140                 ch->curchanbuf = 0;
3141
3142         /* Compute the size of each frame in the next transfer. */
3143         residue = ch->residue;
3144         total = 0;
3145         for (i = 0; i < UAUDIO_NFRAMES; i++) {
3146                 size = ch->bytes_per_frame;
3147                 residue += ch->fraction;
3148                 if (residue >= USB_FRAMES_PER_SECOND) {
3149                         if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
3150                                 size += ch->sample_size;
3151                         residue -= USB_FRAMES_PER_SECOND;
3152                 }
3153                 cb->sizes[i] = size;
3154                 total += size;
3155         }
3156         ch->residue = residue;
3157         cb->size = total;
3158
3159         /*
3160          * Transfer data from upper layer buffer to channel buffer, taking
3161          * care of wrapping the upper layer buffer.
3162          */
3163         n = min(total, ch->end - ch->cur);
3164         memcpy(cb->buffer, ch->cur, n);
3165         ch->cur += n;
3166         if (ch->cur >= ch->end)
3167                 ch->cur = ch->start;
3168         if (total > n) {
3169                 total -= n;
3170                 memcpy(cb->buffer + n, ch->cur, total);
3171                 ch->cur += total;
3172         }
3173
3174 #ifdef USB_DEBUG
3175         if (uaudiodebug > 8) {
3176                 DPRINTF(("uaudio_chan_ptransfer: buffer=%p, residue=0.%03d\n",
3177                          cb->buffer, ch->residue));
3178                 for (i = 0; i < UAUDIO_NFRAMES; i++) {
3179                         DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
3180                 }
3181         }
3182 #endif
3183
3184         DPRINTFN(5,("uaudio_chan_transfer: ptransfer xfer=%p\n", cb->xfer));
3185         /* Fill the request */
3186         usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
3187                              UAUDIO_NFRAMES, USBD_NO_COPY,
3188                              uaudio_chan_pintr);
3189
3190         (void)usbd_transfer(cb->xfer);
3191 }
3192
3193 static void
3194 uaudio_chan_pintr(usbd_xfer_handle xfer, usbd_private_handle priv,
3195                   usbd_status status)
3196 {
3197         struct chanbuf *cb;
3198         struct chan *ch;
3199         u_int32_t count;
3200 #if !defined(__DragonFly__)
3201         int s;
3202 #endif
3203
3204         cb = priv;
3205         ch = cb->chan;
3206         /* Return if we are aborting. */
3207         if (status == USBD_CANCELLED)
3208                 return;
3209
3210         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
3211         DPRINTFN(5,("uaudio_chan_pintr: count=%d, transferred=%d\n",
3212                     count, ch->transferred));
3213 #ifdef DIAGNOSTIC
3214         if (count != cb->size) {
3215                 kprintf("uaudio_chan_pintr: count(%d) != size(%d)\n",
3216                        count, cb->size);
3217         }
3218 #endif
3219
3220         ch->transferred += cb->size;
3221 #if defined(__FreeBSD__)
3222         /* s = spltty(); */
3223         s = splhigh();
3224         chn_intr(ch->pcm_ch);
3225         splx(s);
3226 #elif defined(__DragonFly__)
3227         crit_enter();
3228         chn_intr(ch->pcm_ch);
3229         crit_exit();
3230 #else
3231         s = splaudio();
3232         /* Call back to upper layer */
3233         while (ch->transferred >= ch->blksize) {
3234                 ch->transferred -= ch->blksize;
3235                 DPRINTFN(5,("uaudio_chan_pintr: call %p(%p)\n",
3236                             ch->intr, ch->arg));
3237                 ch->intr(ch->arg);
3238         }
3239         splx(s);
3240 #endif
3241
3242         /* start next transfer */
3243         uaudio_chan_ptransfer(ch);
3244 }
3245
3246 /* Called at splusb() */
3247 static void
3248 uaudio_chan_rtransfer(struct chan *ch)
3249 {
3250         struct chanbuf *cb;
3251         int i, size, residue, total;
3252
3253         if (ch->sc->sc_dying)
3254                 return;
3255
3256         /* Pick the next channel buffer. */
3257         cb = &ch->chanbufs[ch->curchanbuf];
3258         if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
3259                 ch->curchanbuf = 0;
3260
3261         /* Compute the size of each frame in the next transfer. */
3262         residue = ch->residue;
3263         total = 0;
3264         for (i = 0; i < UAUDIO_NFRAMES; i++) {
3265                 size = ch->bytes_per_frame;
3266                 cb->sizes[i] = size;
3267                 cb->offsets[i] = total;
3268                 total += size;
3269         }
3270         ch->residue = residue;
3271         cb->size = total;
3272
3273 #ifdef USB_DEBUG
3274         if (uaudiodebug > 8) {
3275                 DPRINTF(("uaudio_chan_rtransfer: buffer=%p, residue=0.%03d\n",
3276                          cb->buffer, ch->residue));
3277                 for (i = 0; i < UAUDIO_NFRAMES; i++) {
3278                         DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
3279                 }
3280         }
3281 #endif
3282
3283         DPRINTFN(5,("uaudio_chan_rtransfer: transfer xfer=%p\n", cb->xfer));
3284         /* Fill the request */
3285         usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
3286                              UAUDIO_NFRAMES, USBD_NO_COPY,
3287                              uaudio_chan_rintr);
3288
3289         (void)usbd_transfer(cb->xfer);
3290 }
3291
3292 static void
3293 uaudio_chan_rintr(usbd_xfer_handle xfer, usbd_private_handle priv,
3294                   usbd_status status)
3295 {
3296         struct chanbuf *cb = priv;
3297         struct chan *ch = cb->chan;
3298         u_int32_t count;
3299 #if !defined(__DragonFly__)
3300         int s;
3301 #endif
3302         int i, n, frsize;
3303
3304         /* Return if we are aborting. */
3305         if (status == USBD_CANCELLED)
3306                 return;
3307
3308         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
3309         DPRINTFN(5,("uaudio_chan_rintr: count=%d, transferred=%d\n",
3310                     count, ch->transferred));
3311
3312         /* count < cb->size is normal for asynchronous source */
3313 #ifdef DIAGNOSTIC
3314         if (count > cb->size) {
3315                 kprintf("uaudio_chan_rintr: count(%d) > size(%d)\n",
3316                        count, cb->size);
3317         }
3318 #endif
3319
3320         /*
3321          * Transfer data from channel buffer to upper layer buffer, taking
3322          * care of wrapping the upper layer buffer.
3323          */
3324         for(i = 0; i < UAUDIO_NFRAMES; i++) {
3325                 frsize = cb->sizes[i];
3326                 n = min(frsize, ch->end - ch->cur);
3327                 memcpy(ch->cur, cb->buffer + cb->offsets[i], n);
3328                 ch->cur += n;
3329                 if (ch->cur >= ch->end)
3330                         ch->cur = ch->start;
3331                 if (frsize > n) {
3332                         memcpy(ch->cur, cb->buffer + cb->offsets[i] + n,
3333                             frsize - n);
3334                         ch->cur += frsize - n;
3335                 }
3336         }
3337
3338         /* Call back to upper layer */
3339         ch->transferred += count;
3340 #if defined(__FreeBSD__)
3341         s = spltty();
3342         chn_intr(ch->pcm_ch);
3343         splx(s);
3344 #elif defined(__DragonFly__)
3345         crit_enter();
3346         chn_intr(ch->pcm_ch);
3347         crit_exit();
3348 #else
3349         s = splaudio();
3350         while (ch->transferred >= ch->blksize) {
3351                 ch->transferred -= ch->blksize;
3352                 DPRINTFN(5,("uaudio_chan_rintr: call %p(%p)\n",
3353                             ch->intr, ch->arg));
3354                 ch->intr(ch->arg);
3355         }
3356         splx(s);
3357 #endif
3358
3359         /* start next transfer */
3360         uaudio_chan_rtransfer(ch);
3361 }
3362
3363 #if defined(__NetBSD__) || defined(__OpenBSD__)
3364 static void
3365 uaudio_chan_init(struct chan *ch, int altidx, const struct audio_params *param,
3366     int maxpktsize)
3367 {
3368         int samples_per_frame, sample_size;
3369
3370         ch->altidx = altidx;
3371         sample_size = param->precision * param->factor * param->hw_channels / 8;
3372         samples_per_frame = param->hw_sample_rate / USB_FRAMES_PER_SECOND;
3373         ch->sample_size = sample_size;
3374         ch->sample_rate = param->hw_sample_rate;
3375         if (maxpktsize == 0) {
3376                 ch->fraction = param->hw_sample_rate % USB_FRAMES_PER_SECOND;
3377                 ch->bytes_per_frame = samples_per_frame * sample_size;
3378         } else {
3379                 ch->fraction = 0;
3380                 ch->bytes_per_frame = maxpktsize;
3381         }
3382         ch->residue = 0;
3383 }
3384
3385 static void
3386 uaudio_chan_set_param(struct chan *ch, u_char *start, u_char *end, int blksize)
3387 {
3388         ch->start = start;
3389         ch->end = end;
3390         ch->cur = start;
3391         ch->blksize = blksize;
3392         ch->transferred = 0;
3393         ch->curchanbuf = 0;
3394 }
3395
3396 static void
3397 uaudio_get_minmax_rates(int nalts, const struct as_info *alts,
3398                         const struct audio_params *p, int mode,
3399                         u_long *min, u_long *max)
3400 {
3401         const struct usb_audio_streaming_type1_descriptor *a1d;
3402         int i, j;
3403
3404         *min = ULONG_MAX;
3405         *max = 0;
3406         for (i = 0; i < nalts; i++) {
3407                 a1d = alts[i].asf1desc;
3408                 if (alts[i].sc_busy)
3409                         continue;
3410                 if (p->hw_channels != a1d->bNrChannels)
3411                         continue;
3412                 if (p->hw_precision != a1d->bBitResolution)
3413                         continue;
3414                 if (p->hw_encoding != alts[i].encoding)
3415                         continue;
3416                 if (mode != UE_GET_DIR(alts[i].edesc->bEndpointAddress))
3417                         continue;
3418                 if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
3419                         DPRINTFN(2,("uaudio_get_minmax_rates: cont %d-%d\n",
3420                                     UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
3421                         if (UA_SAMP_LO(a1d) < *min)
3422                                 *min = UA_SAMP_LO(a1d);
3423                         if (UA_SAMP_HI(a1d) > *max)
3424                                 *max = UA_SAMP_HI(a1d);
3425                 } else {
3426                         for (j = 0; j < a1d->bSamFreqType; j++) {
3427                                 DPRINTFN(2,("uaudio_get_minmax_rates: disc #%d: %d\n",
3428                                             j, UA_GETSAMP(a1d, j)));
3429                                 if (UA_GETSAMP(a1d, j) < *min)
3430                                         *min = UA_GETSAMP(a1d, j);
3431                                 if (UA_GETSAMP(a1d, j) > *max)
3432                                         *max = UA_GETSAMP(a1d, j);
3433                         }
3434                 }
3435         }
3436 }
3437
3438 static int
3439 uaudio_match_alt_sub(int nalts, const struct as_info *alts,
3440                      const struct audio_params *p, int mode, u_long rate)
3441 {
3442         const struct usb_audio_streaming_type1_descriptor *a1d;
3443         int i, j;
3444
3445         DPRINTF(("uaudio_match_alt_sub: search for %luHz %dch\n",
3446                  rate, p->hw_channels));
3447         for (i = 0; i < nalts; i++) {
3448                 a1d = alts[i].asf1desc;
3449                 if (alts[i].sc_busy)
3450                         continue;
3451                 if (p->hw_channels != a1d->bNrChannels)
3452                         continue;
3453                 if (p->hw_precision != a1d->bBitResolution)
3454                         continue;
3455                 if (p->hw_encoding != alts[i].encoding)
3456                         continue;
3457                 if (mode != UE_GET_DIR(alts[i].edesc->bEndpointAddress))
3458                         continue;
3459                 if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
3460                         DPRINTFN(3,("uaudio_match_alt_sub: cont %d-%d\n",
3461                                     UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
3462                         if (UA_SAMP_LO(a1d) <= rate && rate <= UA_SAMP_HI(a1d))
3463                                 return i;
3464                 } else {
3465                         for (j = 0; j < a1d->bSamFreqType; j++) {
3466                                 DPRINTFN(3,("uaudio_match_alt_sub: disc #%d: %d\n",
3467                                             j, UA_GETSAMP(a1d, j)));
3468                                 /* XXX allow for some slack */
3469                                 if (UA_GETSAMP(a1d, j) == rate)
3470                                         return i;
3471                         }
3472                 }
3473         }
3474         return -1;
3475 }
3476
3477 static int
3478 uaudio_match_alt_chan(int nalts, const struct as_info *alts,
3479                       struct audio_params *p, int mode)
3480 {
3481         int i, n;
3482         u_long min, max;
3483         u_long rate;
3484
3485         /* Exact match */
3486         DPRINTF(("uaudio_match_alt_chan: examine %ldHz %dch %dbit.\n",
3487                  p->sample_rate, p->hw_channels, p->hw_precision));
3488         i = uaudio_match_alt_sub(nalts, alts, p, mode, p->sample_rate);
3489         if (i >= 0)
3490                 return i;
3491
3492         uaudio_get_minmax_rates(nalts, alts, p, mode, &min, &max);
3493         DPRINTF(("uaudio_match_alt_chan: min=%lu max=%lu\n", min, max));
3494         if (max <= 0)
3495                 return -1;
3496         /* Search for biggers */
3497         n = 2;
3498         while ((rate = p->sample_rate * n++) <= max) {
3499                 i = uaudio_match_alt_sub(nalts, alts, p, mode, rate);
3500                 if (i >= 0) {
3501                         p->hw_sample_rate = rate;
3502                         return i;
3503                 }
3504         }
3505         if (p->sample_rate >= min) {
3506                 i = uaudio_match_alt_sub(nalts, alts, p, mode, max);
3507                 if (i >= 0) {
3508                         p->hw_sample_rate = max;
3509                         return i;
3510                 }
3511         } else {
3512                 i = uaudio_match_alt_sub(nalts, alts, p, mode, min);
3513                 if (i >= 0) {
3514                         p->hw_sample_rate = min;
3515                         return i;
3516                 }
3517         }
3518         return -1;
3519 }
3520
3521 static int
3522 uaudio_match_alt(int nalts, const struct as_info *alts,
3523                  struct audio_params *p, int mode)
3524 {
3525         int i, n;
3526
3527         mode = mode == AUMODE_PLAY ? UE_DIR_OUT : UE_DIR_IN;
3528         i = uaudio_match_alt_chan(nalts, alts, p, mode);
3529         if (i >= 0)
3530                 return i;
3531
3532         for (n = p->channels + 1; n <= AUDIO_MAX_CHANNELS; n++) {
3533                 p->hw_channels = n;
3534                 i = uaudio_match_alt_chan(nalts, alts, p, mode);
3535                 if (i >= 0)
3536                         return i;
3537         }
3538
3539         if (p->channels != 2)
3540                 return -1;
3541         p->hw_channels = 1;
3542         return uaudio_match_alt_chan(nalts, alts, p, mode);
3543 }
3544
3545 static int
3546 uaudio_set_params(void *addr, int setmode, int usemode,
3547                   struct audio_params *play, struct audio_params *rec)
3548 {
3549         struct uaudio_softc *sc;
3550         int flags;
3551         int factor;
3552         int enc, i;
3553         int paltidx, raltidx;
3554         void (*swcode)(void *, u_char *buf, int cnt);
3555         struct audio_params *p;
3556         int mode;
3557
3558         sc = addr;
3559         flags = sc->sc_altflags;
3560         paltidx = -1;
3561         raltidx = -1;
3562         if (sc->sc_dying)
3563                 return EIO;
3564
3565         if (((usemode & AUMODE_PLAY) && sc->sc_playchan.pipe != NULL) ||
3566             ((usemode & AUMODE_RECORD) && sc->sc_recchan.pipe != NULL))
3567                 return EBUSY;
3568
3569         if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1)
3570                 sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 0;
3571         if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1)
3572                 sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 0;
3573
3574         /* Some uaudio devices are unidirectional.  Don't try to find a
3575            matching mode for the unsupported direction. */
3576         setmode &= sc->sc_mode;
3577
3578         for (mode = AUMODE_RECORD; mode != -1;
3579              mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
3580                 if ((setmode & mode) == 0)
3581                         continue;
3582
3583                 p = (mode == AUMODE_PLAY) ? play : rec;
3584
3585                 factor = 1;
3586                 swcode = 0;
3587                 enc = p->encoding;
3588                 switch (enc) {
3589                 case AUDIO_ENCODING_SLINEAR_BE:
3590                         /* FALLTHROUGH */
3591                 case AUDIO_ENCODING_SLINEAR_LE:
3592                         if (enc == AUDIO_ENCODING_SLINEAR_BE
3593                             && p->precision == 16 && (flags & HAS_16)) {
3594                                 swcode = swap_bytes;
3595                                 enc = AUDIO_ENCODING_SLINEAR_LE;
3596                         } else if (p->precision == 8) {
3597                                 if (flags & HAS_8) {
3598                                         /* No conversion */
3599                                 } else if (flags & HAS_8U) {
3600                                         swcode = change_sign8;
3601                                         enc = AUDIO_ENCODING_ULINEAR_LE;
3602                                 } else if (flags & HAS_16) {
3603                                         factor = 2;
3604                                         p->hw_precision = 16;
3605                                         if (mode == AUMODE_PLAY)
3606                                                 swcode = linear8_to_linear16_le;
3607                                         else
3608                                                 swcode = linear16_to_linear8_le;
3609                                 }
3610                         }
3611                         break;
3612                 case AUDIO_ENCODING_ULINEAR_BE:
3613                         /* FALLTHROUGH */
3614                 case AUDIO_ENCODING_ULINEAR_LE:
3615                         if (p->precision == 16) {
3616                                 if (enc == AUDIO_ENCODING_ULINEAR_LE)
3617                                         swcode = change_sign16_le;
3618                                 else if (mode == AUMODE_PLAY)
3619                                         swcode = swap_bytes_change_sign16_le;
3620                                 else
3621                                         swcode = change_sign16_swap_bytes_le;
3622                                 enc = AUDIO_ENCODING_SLINEAR_LE;
3623                         } else if (p->precision == 8) {
3624                                 if (flags & HAS_8U) {
3625                                         /* No conversion */
3626                                 } else if (flags & HAS_8) {
3627                                         swcode = change_sign8;
3628                                         enc = AUDIO_ENCODING_SLINEAR_LE;
3629                                 } else if (flags & HAS_16) {
3630                                         factor = 2;
3631                                         p->hw_precision = 16;
3632                                         enc = AUDIO_ENCODING_SLINEAR_LE;
3633                                         if (mode == AUMODE_PLAY)
3634                                                 swcode = ulinear8_to_slinear16_le;
3635                                         else
3636                                                 swcode = slinear16_to_ulinear8_le;
3637                                 }
3638                         }
3639                         break;
3640                 case AUDIO_ENCODING_ULAW:
3641                         if (flags & HAS_MULAW)
3642                                 break;
3643                         if (flags & HAS_16) {
3644                                 if (mode == AUMODE_PLAY)
3645                                         swcode = mulaw_to_slinear16_le;
3646                                 else
3647                                         swcode = slinear16_to_mulaw_le;
3648                                 factor = 2;
3649                                 enc = AUDIO_ENCODING_SLINEAR_LE;
3650                                 p->hw_precision = 16;
3651                         } else if (flags & HAS_8U) {
3652                                 if (mode == AUMODE_PLAY)
3653                                         swcode = mulaw_to_ulinear8;
3654                                 else
3655                                         swcode = ulinear8_to_mulaw;
3656                                 enc = AUDIO_ENCODING_ULINEAR_LE;
3657                         } else if (flags & HAS_8) {
3658                                 if (mode == AUMODE_PLAY)
3659                                         swcode = mulaw_to_slinear8;
3660                                 else
3661                                         swcode = slinear8_to_mulaw;
3662                                 enc = AUDIO_ENCODING_SLINEAR_LE;
3663                         } else
3664                                 return (EINVAL);
3665                         break;
3666                 case AUDIO_ENCODING_ALAW:
3667                         if (flags & HAS_ALAW)
3668                                 break;
3669                         if (mode == AUMODE_PLAY && (flags & HAS_16)) {
3670                                 swcode = alaw_to_slinear16_le;
3671                                 factor = 2;
3672                                 enc = AUDIO_ENCODING_SLINEAR_LE;
3673                                 p->hw_precision = 16;
3674                         } else if (flags & HAS_8U) {
3675                                 if (mode == AUMODE_PLAY)
3676                                         swcode = alaw_to_ulinear8;
3677                                 else
3678                                         swcode = ulinear8_to_alaw;
3679                                 enc = AUDIO_ENCODING_ULINEAR_LE;
3680                         } else if (flags & HAS_8) {
3681                                 if (mode == AUMODE_PLAY)
3682                                         swcode = alaw_to_slinear8;
3683                                 else
3684                                         swcode = slinear8_to_alaw;
3685                                 enc = AUDIO_ENCODING_SLINEAR_LE;
3686                         } else
3687                                 return (EINVAL);
3688                         break;
3689                 default:
3690                         return (EINVAL);
3691                 }
3692                 /* XXX do some other conversions... */
3693
3694                 DPRINTF(("uaudio_set_params: chan=%d prec=%d enc=%d rate=%ld\n",
3695                          p->channels, p->hw_precision, enc, p->sample_rate));
3696
3697                 p->hw_encoding = enc;
3698                 i = uaudio_match_alt(sc->sc_nalts, sc->sc_alts, p, mode);
3699                 if (i < 0)
3700                         return (EINVAL);
3701
3702                 p->sw_code = swcode;
3703                 p->factor  = factor;
3704
3705                 if (mode == AUMODE_PLAY)
3706                         paltidx = i;
3707                 else
3708                         raltidx = i;
3709         }
3710
3711         if ((setmode & AUMODE_PLAY)) {
3712                 /* XXX abort transfer if currently happening? */
3713                 uaudio_chan_init(&sc->sc_playchan, paltidx, play, 0);
3714         }
3715         if ((setmode & AUMODE_RECORD)) {
3716                 /* XXX abort transfer if currently happening? */
3717                 uaudio_chan_init(&sc->sc_recchan, raltidx, rec,
3718                     UGETW(sc->sc_alts[raltidx].edesc->wMaxPacketSize));
3719         }
3720
3721         if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1)
3722                 sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 1;
3723         if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1)
3724                 sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 1;
3725
3726         DPRINTF(("uaudio_set_params: use altidx=p%d/r%d, altno=p%d/r%d\n",
3727                  sc->sc_playchan.altidx, sc->sc_recchan.altidx,
3728                  (sc->sc_playchan.altidx >= 0)
3729                    ?sc->sc_alts[sc->sc_playchan.altidx].idesc->bAlternateSetting
3730                    : -1,
3731                  (sc->sc_recchan.altidx >= 0)
3732                    ? sc->sc_alts[sc->sc_recchan.altidx].idesc->bAlternateSetting
3733                    : -1));
3734
3735         return 0;
3736 }
3737 #endif /* NetBSD or OpenBSD */
3738
3739 static usbd_status
3740 uaudio_set_speed(struct uaudio_softc *sc, int endpt, u_int speed)
3741 {
3742         usb_device_request_t req;
3743         uint8_t data[3];
3744
3745         DPRINTFN(5,("uaudio_set_speed: endpt=%d speed=%u\n", endpt, speed));
3746         req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
3747         req.bRequest = SET_CUR;
3748         USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
3749         USETW(req.wIndex, endpt);
3750         USETW(req.wLength, 3);
3751         data[0] = speed;
3752         data[1] = speed >> 8;
3753         data[2] = speed >> 16;
3754
3755         return usbd_do_request(sc->sc_udev, &req, data);
3756 }
3757
3758
3759 #if defined(__FreeBSD__) || defined(__DragonFly__)
3760 /************************************************************/
3761 int
3762 uaudio_init_params(struct uaudio_softc *sc, struct chan *ch, int mode)
3763 {
3764         int i, j, enc;
3765         int samples_per_frame, sample_size;
3766
3767         if ((sc->sc_playchan.pipe != NULL) || (sc->sc_recchan.pipe != NULL))
3768                 return (-1);
3769
3770         switch(ch->format & 0x000FFFFF) {
3771         case AFMT_U8:
3772                 enc = AUDIO_ENCODING_ULINEAR_LE;
3773                 ch->precision = 8;
3774                 break;
3775         case AFMT_S8:
3776                 enc = AUDIO_ENCODING_SLINEAR_LE;
3777                 ch->precision = 8;
3778                 break;
3779         case AFMT_A_LAW:        /* ? */
3780                 enc = AUDIO_ENCODING_ALAW;
3781                 ch->precision = 8;
3782                 break;
3783         case AFMT_MU_LAW:       /* ? */
3784                 enc = AUDIO_ENCODING_ULAW;
3785                 ch->precision = 8;
3786                 break;
3787         case AFMT_S16_LE:
3788                 enc = AUDIO_ENCODING_SLINEAR_LE;
3789                 ch->precision = 16;
3790                 break;
3791         case AFMT_S16_BE:
3792                 enc = AUDIO_ENCODING_SLINEAR_BE;
3793                 ch->precision = 16;
3794                 break;
3795         case AFMT_U16_LE:
3796                 enc = AUDIO_ENCODING_ULINEAR_LE;
3797                 ch->precision = 16;
3798                 break;
3799         case AFMT_U16_BE:
3800                 enc = AUDIO_ENCODING_ULINEAR_BE;
3801                 ch->precision = 16;
3802                 break;
3803         case AFMT_S24_LE:
3804                 enc = AUDIO_ENCODING_SLINEAR_LE;
3805                 ch->precision = 24;
3806                 break;
3807         case AFMT_S24_BE:
3808                 enc = AUDIO_ENCODING_SLINEAR_BE;
3809                 ch->precision = 24;
3810                 break;
3811         case AFMT_U24_LE:
3812                 enc = AUDIO_ENCODING_ULINEAR_LE;
3813                 ch->precision = 24;
3814                 break;
3815         case AFMT_U24_BE:
3816                 enc = AUDIO_ENCODING_ULINEAR_BE;
3817                 ch->precision = 24;
3818                 break;
3819         case AFMT_S32_LE:
3820                 enc = AUDIO_ENCODING_SLINEAR_LE;
3821                 ch->precision = 32;
3822                 break;
3823         case AFMT_S32_BE:
3824                 enc = AUDIO_ENCODING_SLINEAR_BE;
3825                 ch->precision = 32;
3826                 break;
3827         case AFMT_U32_LE:
3828                 enc = AUDIO_ENCODING_ULINEAR_LE;
3829                 ch->precision = 32;
3830                 break;
3831         case AFMT_U32_BE:
3832                 enc = AUDIO_ENCODING_ULINEAR_BE;
3833                 ch->precision = 32;
3834                 break;
3835         default:
3836                 enc = 0;
3837                 ch->precision = 16;
3838                 kprintf("Unknown format %x\n", ch->format);
3839         }
3840
3841         if (ch->format & AFMT_STEREO) {
3842                 ch->channels = 2;
3843         } else {
3844                 ch->channels = 1;
3845         }
3846
3847 /*      for (mode =  ......      */
3848                 for (i = 0; i < sc->sc_nalts; i++) {
3849                         const struct usb_audio_streaming_type1_descriptor *a1d =
3850                                 sc->sc_alts[i].asf1desc;
3851                         if (ch->channels == a1d->bNrChannels &&
3852                             ch->precision == a1d->bBitResolution &&
3853 #if 0
3854                             enc == sc->sc_alts[i].encoding) {
3855 #else
3856                             enc == sc->sc_alts[i].encoding &&
3857                             (mode == AUMODE_PLAY ? UE_DIR_OUT : UE_DIR_IN) ==
3858                             UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress)) {
3859 #endif
3860                                 if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
3861                                         DPRINTFN(2,("uaudio_set_params: cont %d-%d\n",
3862                                             UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
3863                                         if (UA_SAMP_LO(a1d) <= ch->sample_rate &&
3864                                             ch->sample_rate <= UA_SAMP_HI(a1d)) {
3865                                                 if (mode == AUMODE_PLAY)
3866                                                         sc->sc_playchan.altidx = i;
3867                                                 else
3868                                                         sc->sc_recchan.altidx = i;
3869                                                 goto found;
3870                                         }
3871                                 } else {
3872                                         for (j = 0; j < a1d->bSamFreqType; j++) {
3873                                                 DPRINTFN(2,("uaudio_set_params: disc #"
3874                                                     "%d: %d\n", j, UA_GETSAMP(a1d, j)));
3875                                                 /* XXX allow for some slack */
3876                                                 if (UA_GETSAMP(a1d, j) ==
3877                                                     ch->sample_rate) {
3878                                                         if (mode == AUMODE_PLAY)
3879                                                                 sc->sc_playchan.altidx = i;
3880                                                         else
3881                                                                 sc->sc_recchan.altidx = i;
3882                                                         goto found;
3883                                                 }
3884                                         }
3885                                 }
3886                         }
3887                 }
3888                 /* return (EINVAL); */
3889                 if (mode == AUMODE_PLAY) 
3890                         kprintf("uaudio: This device can't play in rate=%d.\n", ch->sample_rate);
3891                 else
3892                         kprintf("uaudio: This device can't record in rate=%d.\n", ch->sample_rate);
3893                 return (-1);
3894
3895         found:
3896 #if 0 /* XXX */
3897                 p->sw_code = swcode;
3898                 p->factor  = factor;
3899                 if (usemode == mode)
3900                         sc->sc_curaltidx = i;
3901 #endif
3902 /*      } */
3903
3904         sample_size = ch->precision * ch->channels / 8;
3905         samples_per_frame = ch->sample_rate / USB_FRAMES_PER_SECOND;
3906         ch->fraction = ch->sample_rate % USB_FRAMES_PER_SECOND;
3907         ch->sample_size = sample_size;
3908         ch->bytes_per_frame = samples_per_frame * sample_size;
3909         ch->residue = 0;
3910
3911         ch->cur = ch->start;
3912         ch->transferred = 0;
3913         ch->curchanbuf = 0;
3914         return (0);
3915 }
3916
3917 struct uaudio_conversion {
3918         uint8_t uaudio_fmt;
3919         uint8_t uaudio_prec;
3920         uint32_t freebsd_fmt;
3921 };
3922
3923 const struct uaudio_conversion const accepted_conversion[] = {
3924         {AUDIO_ENCODING_ULINEAR_LE, 8, AFMT_U8},
3925         {AUDIO_ENCODING_ULINEAR_LE, 16, AFMT_U16_LE},
3926         {AUDIO_ENCODING_ULINEAR_LE, 24, AFMT_U24_LE},
3927         {AUDIO_ENCODING_ULINEAR_LE, 32, AFMT_U32_LE},
3928         {AUDIO_ENCODING_ULINEAR_BE, 16, AFMT_U16_BE},
3929         {AUDIO_ENCODING_ULINEAR_BE, 24, AFMT_U24_BE},
3930         {AUDIO_ENCODING_ULINEAR_BE, 32, AFMT_U32_BE},
3931         {AUDIO_ENCODING_SLINEAR_LE, 8, AFMT_S8},
3932         {AUDIO_ENCODING_SLINEAR_LE, 16, AFMT_S16_LE},
3933         {AUDIO_ENCODING_SLINEAR_LE, 24, AFMT_S24_LE},
3934         {AUDIO_ENCODING_SLINEAR_LE, 32, AFMT_S32_LE},
3935         {AUDIO_ENCODING_SLINEAR_BE, 16, AFMT_S16_BE},
3936         {AUDIO_ENCODING_SLINEAR_BE, 24, AFMT_S24_BE},
3937         {AUDIO_ENCODING_SLINEAR_BE, 32, AFMT_S32_BE},
3938         {AUDIO_ENCODING_ALAW, 8, AFMT_A_LAW},
3939         {AUDIO_ENCODING_ULAW, 8, AFMT_MU_LAW},
3940         {0,0,0}
3941 };
3942
3943 unsigned
3944 uaudio_query_formats(device_t dev, int reqdir, unsigned maxfmt, struct pcmchan_caps *cap)
3945 {
3946         struct uaudio_softc *sc;
3947         const struct usb_audio_streaming_type1_descriptor *asf1d;
3948         const struct uaudio_conversion *iterator;
3949         unsigned fmtcount, foundcount;
3950         u_int32_t fmt;
3951         uint8_t format, numchan, subframesize, prec, dir, iscontinuous;
3952         int freq, freq_min, freq_max;
3953         char *numchannel_descr;
3954         char freq_descr[64];
3955         int i,r;
3956
3957         sc = device_get_softc(dev);
3958         if (sc == NULL)
3959                 return 0;
3960
3961         cap->minspeed = cap->maxspeed = 0;
3962         foundcount = fmtcount = 0;
3963
3964         for (i = 0; i < sc->sc_nalts; i++) {
3965                 dir = UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress);
3966
3967                 if ((dir == UE_DIR_OUT) != (reqdir == PCMDIR_PLAY))
3968                         continue;
3969
3970                 asf1d = sc->sc_alts[i].asf1desc;
3971                 format = sc->sc_alts[i].encoding;
3972
3973                 numchan = asf1d->bNrChannels;
3974                 subframesize = asf1d->bSubFrameSize;
3975                 prec = asf1d->bBitResolution;   /* precision */
3976                 iscontinuous = asf1d->bSamFreqType == UA_SAMP_CONTNUOUS;
3977
3978                 if (iscontinuous)
3979                         ksnprintf(freq_descr, sizeof(freq_descr), "continous min %d max %d", UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
3980                 else
3981                         ksnprintf(freq_descr, sizeof(freq_descr), "fixed frequency (%d listed formats)", asf1d->bSamFreqType);
3982
3983                 if (numchan == 1)
3984                         numchannel_descr = " (mono)";
3985                 else if (numchan == 2)
3986                         numchannel_descr = " (stereo)";
3987                 else
3988                         numchannel_descr = "";
3989
3990                 if (bootverbose) {
3991                         device_printf(dev, "uaudio_query_formats: found a native %s channel%s %s %dbit %dbytes/subframe X %d channels = %d bytes per sample\n",
3992                                         (dir==UE_DIR_OUT)?"playback":"record",
3993                                         numchannel_descr, freq_descr,
3994                                         prec, subframesize, numchan, subframesize*numchan);
3995                 }
3996                 /*
3997                  * Now start rejecting the ones that don't map to FreeBSD
3998                  */
3999
4000                 if (numchan != 1 && numchan != 2)
4001                         continue;
4002
4003                 for (iterator = accepted_conversion ; iterator->uaudio_fmt != 0 ; iterator++)
4004                         if (iterator->uaudio_fmt == format && iterator->uaudio_prec == prec)
4005                                 break;
4006
4007                 if (iterator->uaudio_fmt == 0)
4008                         continue;
4009
4010                 fmt = iterator->freebsd_fmt;
4011
4012                 if (numchan == 2)
4013                         fmt |= AFMT_STEREO;
4014
4015                 foundcount++;
4016
4017                 if (fmtcount >= maxfmt)
4018                         continue;
4019
4020                 cap->fmtlist[fmtcount++] = fmt;
4021
4022                 if (iscontinuous) {
4023                         freq_min = UA_SAMP_LO(asf1d);
4024                         freq_max = UA_SAMP_HI(asf1d);
4025
4026                         if (cap->minspeed == 0 || freq_min < cap->minspeed)
4027                                 cap->minspeed = freq_min;
4028                         if (cap->maxspeed == 0)
4029                                 cap->maxspeed = cap->minspeed;
4030                         if (freq_max > cap->maxspeed)
4031                                 cap->maxspeed = freq_max;
4032                 } else {
4033                         for (r = 0; r < asf1d->bSamFreqType; r++) {
4034                                 freq = UA_GETSAMP(asf1d, r);
4035                                 if (cap->minspeed == 0 || freq < cap->minspeed)
4036                                         cap->minspeed = freq;
4037                                 if (cap->maxspeed == 0)
4038                                         cap->maxspeed = cap->minspeed;
4039                                 if (freq > cap->maxspeed)
4040                                         cap->maxspeed = freq;
4041                         }
4042                 }
4043         }
4044         cap->fmtlist[fmtcount] = 0;
4045         return foundcount;
4046 }
4047
4048 void
4049 uaudio_chan_set_param_pcm_dma_buff(device_t dev, u_char *start, u_char *end,
4050                 struct pcm_channel *pc, int dir)
4051 {
4052         struct uaudio_softc *sc;
4053         struct chan *ch;
4054
4055         sc = device_get_softc(dev);
4056 #ifndef NO_RECORDING
4057         if (dir == PCMDIR_PLAY)
4058                 ch = &sc->sc_playchan;
4059         else
4060                 ch = &sc->sc_recchan;
4061 #else
4062         ch = &sc->sc_playchan;
4063 #endif
4064
4065         ch->start = start;
4066         ch->end = end;
4067
4068         ch->pcm_ch = pc;
4069
4070         return;
4071 }
4072
4073 void
4074 uaudio_chan_set_param_blocksize(device_t dev, u_int32_t blocksize, int dir)
4075 {
4076         struct uaudio_softc *sc;
4077         struct chan *ch;
4078
4079         sc = device_get_softc(dev);
4080 #ifndef NO_RECORDING
4081         if (dir == PCMDIR_PLAY)
4082                 ch = &sc->sc_playchan;
4083         else
4084                 ch = &sc->sc_recchan;
4085 #else
4086         ch = &sc->sc_playchan;
4087 #endif
4088
4089         ch->blksize = blocksize;
4090
4091         return;
4092 }
4093
4094 int
4095 uaudio_chan_set_param_speed(device_t dev, u_int32_t speed, int reqdir)
4096 {
4097         const struct uaudio_conversion *iterator;
4098         struct uaudio_softc *sc;
4099         struct chan *ch;
4100         int i, r, score, hiscore, bestspeed;
4101
4102         sc = device_get_softc(dev);
4103 #ifndef NO_RECORDING
4104         if (reqdir == PCMDIR_PLAY)
4105                 ch = &sc->sc_playchan;
4106         else
4107                 ch = &sc->sc_recchan;
4108 #else
4109         ch = &sc->sc_playchan;
4110 #endif
4111         /*
4112          * We are successful if we find an endpoint that matches our selected format and it
4113          * supports the requested speed.
4114          */
4115         hiscore = 0;
4116         bestspeed = 1;
4117         for (i = 0; i < sc->sc_nalts; i++) {
4118                 int dir = UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress);
4119                 int format = sc->sc_alts[i].encoding;
4120                 const struct usb_audio_streaming_type1_descriptor *asf1d = sc->sc_alts[i].asf1desc;
4121                 int iscontinuous = asf1d->bSamFreqType == UA_SAMP_CONTNUOUS;
4122
4123                 if ((dir == UE_DIR_OUT) != (reqdir == PCMDIR_PLAY))
4124                         continue;
4125
4126                 for (iterator = accepted_conversion ; iterator->uaudio_fmt != 0 ; iterator++)
4127                         if (iterator->uaudio_fmt != format || iterator->freebsd_fmt != (ch->format&0xfffffff))
4128                                 continue;
4129                         if (iscontinuous) {
4130                                 if (speed >= UA_SAMP_LO(asf1d) && speed <= UA_SAMP_HI(asf1d)) {
4131                                         ch->sample_rate = speed;
4132                                         return speed;
4133                                 } else if (speed < UA_SAMP_LO(asf1d)) {
4134                                         score = 0xfff * speed / UA_SAMP_LO(asf1d);
4135                                         if (score > hiscore) {
4136                                                 bestspeed = UA_SAMP_LO(asf1d);
4137                                                 hiscore = score;
4138                                         }
4139                                 } else if (speed < UA_SAMP_HI(asf1d)) {
4140                                         score = 0xfff * UA_SAMP_HI(asf1d) / speed;
4141                                         if (score > hiscore) {
4142                                                 bestspeed = UA_SAMP_HI(asf1d);
4143                                                 hiscore = score;
4144                                         }
4145                                 }
4146                                 continue;
4147                         }
4148                         for (r = 0; r < asf1d->bSamFreqType; r++) {
4149                                 if (speed == UA_GETSAMP(asf1d, r)) {
4150                                         ch->sample_rate = speed;
4151                                         return speed;
4152                                 }
4153                                 if (speed > UA_GETSAMP(asf1d, r))
4154                                         score = 0xfff * UA_GETSAMP(asf1d, r) / speed;
4155                                 else
4156                                         score = 0xfff * speed / UA_GETSAMP(asf1d, r);
4157                                 if (score > hiscore) { 
4158                                         bestspeed = UA_GETSAMP(asf1d, r);
4159                                         hiscore = score;
4160                                 }
4161                         }
4162         }
4163         if (bestspeed != 1) {
4164                 ch->sample_rate = bestspeed;
4165                 return bestspeed;
4166         }
4167
4168         return 0;
4169 }
4170
4171 int
4172 uaudio_chan_getptr(device_t dev, int dir)
4173 {
4174         struct uaudio_softc *sc;
4175         struct chan *ch;
4176         int ptr;
4177
4178         sc = device_get_softc(dev);
4179 #ifndef NO_RECORDING
4180         if (dir == PCMDIR_PLAY)
4181                 ch = &sc->sc_playchan;
4182         else
4183                 ch = &sc->sc_recchan;
4184 #else
4185         ch = &sc->sc_playchan;
4186 #endif
4187
4188         ptr = ch->cur - ch->start;
4189
4190         return ptr;
4191 }
4192
4193 void
4194 uaudio_chan_set_param_format(device_t dev, u_int32_t format, int dir)
4195 {
4196         struct uaudio_softc *sc;
4197         struct chan *ch;
4198
4199         sc = device_get_softc(dev);
4200 #ifndef NO_RECORDING
4201         if (dir == PCMDIR_PLAY)
4202                 ch = &sc->sc_playchan;
4203         else
4204                 ch = &sc->sc_recchan;
4205 #else
4206         ch = &sc->sc_playchan;
4207 #endif
4208
4209         ch->format = format;
4210
4211         return;
4212 }
4213
4214 int
4215 uaudio_halt_out_dma(device_t dev)
4216 {
4217         struct uaudio_softc *sc;
4218
4219         sc = device_get_softc(dev);
4220
4221         DPRINTF(("uaudio_halt_out_dma: enter\n"));
4222         if (sc->sc_playchan.pipe != NULL) {
4223                 uaudio_chan_close(sc, &sc->sc_playchan);
4224                 sc->sc_playchan.pipe = 0;
4225                 uaudio_chan_free_buffers(sc, &sc->sc_playchan);
4226         }
4227         return (0);
4228 }
4229
4230 int
4231 uaudio_halt_in_dma(device_t dev)
4232 {
4233         struct uaudio_softc *sc;
4234
4235         sc = device_get_softc(dev);
4236
4237         if (sc->sc_dying)
4238                 return (EIO);
4239
4240         DPRINTF(("uaudio_halt_in_dma: enter\n"));
4241         if (sc->sc_recchan.pipe != NULL) {
4242                 uaudio_chan_close(sc, &sc->sc_recchan);
4243                 sc->sc_recchan.pipe = NULL;
4244                 uaudio_chan_free_buffers(sc, &sc->sc_recchan);
4245 /*              sc->sc_recchan.intr = NULL; */
4246         }
4247         return (0);
4248 }
4249
4250 int
4251 uaudio_trigger_input(device_t dev)
4252 {
4253         struct uaudio_softc *sc;
4254         struct chan *ch;
4255         usbd_status err;
4256         int i;
4257 #if !defined(__DragonFly__)
4258         int s;
4259 #endif
4260
4261         sc = device_get_softc(dev);
4262         ch = &sc->sc_recchan;
4263
4264         if (sc->sc_dying)
4265                 return (EIO);
4266
4267 /*      uaudio_chan_set_param(ch, start, end, blksize) */
4268         if (uaudio_init_params(sc, ch, AUMODE_RECORD))
4269                 return (EIO);
4270
4271         err = uaudio_chan_alloc_buffers(sc, ch);
4272         if (err)
4273                 return (EIO);
4274
4275         err = uaudio_chan_open(sc, ch);
4276         if (err) {
4277                 uaudio_chan_free_buffers(sc, ch);
4278                 return (EIO);
4279         }
4280
4281 /*      ch->intr = intr;
4282         ch->arg = arg; */
4283
4284 #if defined(__DragonFly__)
4285         crit_enter();
4286 #else
4287         s = splusb();
4288 #endif
4289         for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
4290                 uaudio_chan_rtransfer(ch);
4291 #if defined(__DragonFly__)
4292         crit_exit();
4293 #else
4294         splx(s);
4295 #endif
4296
4297         return (0);
4298 }
4299
4300 int
4301 uaudio_trigger_output(device_t dev)
4302 {
4303         struct uaudio_softc *sc;
4304         struct chan *ch;
4305         usbd_status err;
4306         int i;
4307 #if !defined(__DragonFly__)
4308         int s;
4309 #endif
4310
4311         sc = device_get_softc(dev);
4312         ch = &sc->sc_playchan;
4313
4314         if (sc->sc_dying)
4315                 return (EIO);
4316
4317         if (uaudio_init_params(sc, ch, AUMODE_PLAY))
4318                 return (EIO);
4319
4320         err = uaudio_chan_alloc_buffers(sc, ch);
4321         if (err)
4322                 return (EIO);
4323
4324         err = uaudio_chan_open(sc, ch);
4325         if (err) {
4326                 uaudio_chan_free_buffers(sc, ch);
4327                 return (EIO);
4328         }
4329
4330 #if defined(__DragonFly__)
4331         crit_enter();
4332 #else
4333         s = splusb();
4334 #endif
4335         for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
4336                 uaudio_chan_ptransfer(ch);
4337 #if defined(__DragonFly__)
4338         crit_exit();
4339 #else
4340         splx(s);
4341 #endif
4342
4343         return (0);
4344 }
4345
4346 u_int32_t
4347 uaudio_query_mix_info(device_t dev)
4348 {
4349         int i;
4350         u_int32_t mask = 0;
4351         struct uaudio_softc *sc;
4352         struct mixerctl *mc;
4353
4354         sc = device_get_softc(dev);
4355         for (i=0; i < sc->sc_nctls; i++) {
4356                 mc = &sc->sc_ctls[i];
4357                 if (mc->ctl != SOUND_MIXER_NRDEVICES) {
4358                         /* Set device mask bits. 
4359                            See /usr/include/machine/soundcard.h */
4360                         mask |= (1 << mc->ctl);
4361                 }
4362         }
4363         return mask;
4364 }
4365
4366 u_int32_t
4367 uaudio_query_recsrc_info(device_t dev)
4368 {
4369         int i, rec_selector_id;
4370         u_int32_t mask = 0;
4371         struct uaudio_softc *sc;
4372         struct mixerctl *mc;
4373
4374         sc = device_get_softc(dev);
4375         rec_selector_id = -1;
4376         for (i=0; i < sc->sc_nctls; i++) {
4377                 mc = &sc->sc_ctls[i];
4378                 if (mc->ctl == SOUND_MIXER_NRDEVICES && 
4379                     mc->type == MIX_SELECTOR && mc->class == UAC_RECORD) {
4380                         if (rec_selector_id == -1) {
4381                                 rec_selector_id = i;
4382                         } else {
4383                                 kprintf("There are many selectors.  Can't recognize which selector is a record source selector.\n");
4384                                 return mask;
4385                         }
4386                 }
4387         }
4388         if (rec_selector_id == -1)
4389                 return mask;
4390         mc = &sc->sc_ctls[rec_selector_id];
4391         for (i = mc->minval; i <= mc->maxval; i++) {
4392                 if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES)
4393                         continue;
4394                 mask |= 1 << mc->slctrtype[i - 1];
4395         }
4396         return mask;
4397 }
4398
4399 void
4400 uaudio_mixer_set(device_t dev, unsigned type, unsigned left, unsigned right)
4401 {
4402         int i;
4403         struct uaudio_softc *sc;
4404         struct mixerctl *mc;
4405
4406         sc = device_get_softc(dev);
4407         for (i=0; i < sc->sc_nctls; i++) {
4408                 mc = &sc->sc_ctls[i];
4409                 if (mc->ctl == type) {
4410                         if (mc->nchan == 2) {
4411                                 /* set Right */
4412                                 uaudio_ctl_set(sc, SET_CUR, mc, 1, (int)(right*255)/100);
4413                         }
4414                         /* set Left or Mono */
4415                         uaudio_ctl_set(sc, SET_CUR, mc, 0, (int)(left*255)/100);
4416                 }
4417         }
4418         return;
4419 }
4420
4421 u_int32_t
4422 uaudio_mixer_setrecsrc(device_t dev, u_int32_t src)
4423 {
4424         int i, rec_selector_id;
4425         struct uaudio_softc *sc;
4426         struct mixerctl *mc;
4427
4428         sc = device_get_softc(dev);
4429         rec_selector_id = -1;
4430         for (i=0; i < sc->sc_nctls; i++) {
4431                 mc = &sc->sc_ctls[i];
4432                 if (mc->ctl == SOUND_MIXER_NRDEVICES && 
4433                     mc->type == MIX_SELECTOR && mc->class == UAC_RECORD) {
4434                         if (rec_selector_id == -1) {
4435                                 rec_selector_id = i;
4436                         } else {
4437                                 return src; /* Can't recognize which selector is record source selector */
4438                         }
4439                 }
4440         }
4441         if (rec_selector_id == -1)
4442                 return src;
4443         mc = &sc->sc_ctls[rec_selector_id];
4444         for (i = mc->minval; i <= mc->maxval; i++) {
4445                 if (src != (1 << mc->slctrtype[i - 1]))
4446                         continue;
4447                 uaudio_ctl_set(sc, SET_CUR, mc, 0, i);
4448                 return (1 << mc->slctrtype[i - 1]);
4449         }
4450         uaudio_ctl_set(sc, SET_CUR, mc, 0, mc->minval);
4451         return (1 << mc->slctrtype[mc->minval - 1]);
4452 }
4453
4454 static int
4455 uaudio_sndstat_prepare_pcm(struct sbuf *s, device_t dev, int verbose)
4456 {
4457         struct snddev_info *d;
4458         struct snddev_channel *sce;
4459         struct pcm_channel *c;
4460         struct pcm_feeder *f;
4461         int pc, rc, vc;
4462         device_t pa_dev = device_get_parent(dev);
4463         struct uaudio_softc *sc = device_get_softc(pa_dev);
4464
4465         if (verbose < 1)
4466                 return 0;
4467
4468         d = device_get_softc(dev);
4469         if (!d)
4470                 return ENXIO;
4471
4472         snd_mtxlock(d->lock);
4473         if (SLIST_EMPTY(&d->channels)) {
4474                 sbuf_printf(s, " (mixer only)");
4475                 snd_mtxunlock(d->lock);
4476                 return 0;
4477         }
4478         pc = rc = vc = 0;
4479         SLIST_FOREACH(sce, &d->channels, link) {
4480                 c = sce->channel;
4481                 if (c->direction == PCMDIR_PLAY) {
4482                         if (c->flags & CHN_F_VIRTUAL)
4483                                 vc++;
4484                         else
4485                                 pc++;
4486                 } else
4487                         rc++;
4488         }
4489         sbuf_printf(s, " (%dp/%dr/%dv channels%s%s)", 
4490                         d->playcount, d->reccount, d->vchancount,
4491                         (d->flags & SD_F_SIMPLEX)? "" : " duplex",
4492 #ifdef USING_DEVFS
4493                         (device_get_unit(dev) == snd_unit)? " default" : ""
4494 #else
4495                         ""
4496 #endif
4497                         );
4498
4499         if (sc->uaudio_sndstat_flag != 0) {
4500                 sbuf_cat(s, sbuf_data(&(sc->uaudio_sndstat)));
4501         }
4502
4503         if (verbose <= 1) {
4504                 snd_mtxunlock(d->lock);
4505                 return 0;
4506         }
4507
4508         SLIST_FOREACH(sce, &d->channels, link) {
4509                 c = sce->channel;
4510                 sbuf_printf(s, "\n\t");
4511
4512                 KASSERT(c->bufhard != NULL && c->bufsoft != NULL,
4513                         ("hosed pcm channel setup"));
4514
4515                 /* it would be better to indent child channels */
4516                 sbuf_printf(s, "%s[%s]: ", c->parentchannel? c->parentchannel->name : "", c->name);
4517                 sbuf_printf(s, "spd %d", c->speed);
4518                 if (c->speed != sndbuf_getspd(c->bufhard))
4519                         sbuf_printf(s, "/%d", sndbuf_getspd(c->bufhard));
4520                 sbuf_printf(s, ", fmt 0x%08x", c->format);
4521                 if (c->format != sndbuf_getfmt(c->bufhard))
4522                         sbuf_printf(s, "/0x%08x", sndbuf_getfmt(c->bufhard));
4523                 sbuf_printf(s, ", flags 0x%08x, 0x%08x", c->flags, c->feederflags);
4524                 if (c->pid != -1)
4525                         sbuf_printf(s, ", pid %d", c->pid);
4526                 sbuf_printf(s, "\n\t");
4527
4528                 sbuf_printf(s, "interrupts %d, ", c->interrupts);
4529                 if (c->direction == PCMDIR_REC)
4530                         sbuf_printf(s, "overruns %d, hfree %d, sfree %d",
4531                                 c->xruns, sndbuf_getfree(c->bufhard), sndbuf_getfree(c->bufsoft));
4532                 else
4533                         sbuf_printf(s, "underruns %d, ready %d",
4534                                 c->xruns, sndbuf_getready(c->bufsoft));
4535                 sbuf_printf(s, "\n\t");
4536
4537                 sbuf_printf(s, "{%s}", (c->direction == PCMDIR_REC)? "hardware" : "userland");
4538                 sbuf_printf(s, " -> ");
4539                 f = c->feeder;
4540                 while (f->source != NULL)
4541                         f = f->source;
4542                 while (f != NULL) {
4543                         sbuf_printf(s, "%s", f->class->name);
4544                         if (f->desc->type == FEEDER_FMT)
4545                                 sbuf_printf(s, "(0x%08x -> 0x%08x)", f->desc->in, f->desc->out);
4546                         if (f->desc->type == FEEDER_RATE)
4547                                 sbuf_printf(s, "(%d -> %d)", FEEDER_GET(f, FEEDRATE_SRC), FEEDER_GET(f, FEEDRATE_DST));
4548                         if (f->desc->type == FEEDER_ROOT || f->desc->type == FEEDER_MIXER)
4549                                 sbuf_printf(s, "(0x%08x)", f->desc->out);
4550                         sbuf_printf(s, " -> ");
4551                         f = f->parent;
4552                 }
4553                 sbuf_printf(s, "{%s}", (c->direction == PCMDIR_REC)? "userland" : "hardware");
4554         }
4555         snd_mtxunlock(d->lock);
4556
4557         return 0;
4558 }
4559
4560 void
4561 uaudio_sndstat_register(device_t dev)
4562 {
4563         struct snddev_info *d = device_get_softc(dev);
4564         sndstat_register(dev, d->status, uaudio_sndstat_prepare_pcm);
4565 }
4566         
4567 static int
4568 audio_attach_mi(device_t dev)
4569 {
4570         device_t child;
4571         struct sndcard_func *func;
4572
4573         /* Attach the children. */
4574         /* PCM Audio */
4575         func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT);
4576         if (func == NULL)
4577                 return (ENOMEM);
4578         bzero(func, sizeof(*func));
4579         func->func = SCF_PCM;
4580         child = device_add_child(dev, "pcm", -1);
4581         device_set_ivars(child, func);
4582
4583         bus_generic_attach(dev);
4584
4585         return 0; /* XXXXX */
4586 }
4587
4588 DRIVER_MODULE(uaudio, uhub, uaudio_driver, uaudio_devclass, usbd_driver_load, 0);
4589 MODULE_VERSION(uaudio, 1);
4590
4591 #endif