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