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