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