Home | History | Annotate | Line # | Download | only in usb
uaudio.c revision 1.55
      1 /*	$NetBSD: uaudio.c,v 1.55 2002/03/23 16:23:20 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/data/devclass/audio10.pdf
     42  *                  http://www.usb.org/developers/data/devclass/frmts10.pdf
     43  *                  http://www.usb.org/developers/data/devclass/termt10.pdf
     44  */
     45 
     46 #include <sys/cdefs.h>
     47 __KERNEL_RCSID(0, "$NetBSD: uaudio.c,v 1.55 2002/03/23 16:23:20 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/mulaw.h>
     67 #include <dev/auconv.h>
     68 
     69 #include <dev/usb/usb.h>
     70 #include <dev/usb/usbdi.h>
     71 #include <dev/usb/usbdi_util.h>
     72 #include <dev/usb/usb_quirks.h>
     73 
     74 #include <dev/usb/uaudioreg.h>
     75 
     76 #ifdef UAUDIO_DEBUG
     77 #define DPRINTF(x)	if (uaudiodebug) logprintf x
     78 #define DPRINTFN(n,x)	if (uaudiodebug>(n)) logprintf x
     79 int	uaudiodebug = 0;
     80 #else
     81 #define DPRINTF(x)
     82 #define DPRINTFN(n,x)
     83 #endif
     84 
     85 #define UAUDIO_NCHANBUFS 6	/* number of outstanding request */
     86 #define UAUDIO_NFRAMES   10	/* ms of sound in each request */
     87 
     88 
     89 #define MIX_MAX_CHAN 8
     90 struct mixerctl {
     91 	u_int16_t	wValue[MIX_MAX_CHAN]; /* using nchan */
     92 	u_int16_t	wIndex;
     93 	u_int8_t	nchan;
     94 	u_int8_t	type;
     95 #define MIX_ON_OFF	1
     96 #define MIX_SIGNED_16	2
     97 #define MIX_UNSIGNED_16	3
     98 #define MIX_SIGNED_8	4
     99 #define MIX_SIZE(n) ((n) == MIX_SIGNED_16 || (n) == MIX_UNSIGNED_16 ? 2 : 1)
    100 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
    101 	int		minval, maxval;
    102 	u_int		delta;
    103 	u_int		mul;
    104 	u_int8_t	class;
    105 	char		ctlname[MAX_AUDIO_DEV_LEN];
    106 	char		*ctlunit;
    107 };
    108 #define MAKE(h,l) (((h) << 8) | (l))
    109 
    110 struct as_info {
    111 	u_int8_t	alt;
    112 	u_int8_t	encoding;
    113 	u_int8_t	attributes; /* Copy of bmAttributes of
    114 				     * usb_audio_streaming_endpoint_descriptor
    115 				     */
    116 	usbd_interface_handle	ifaceh;
    117 	usb_interface_descriptor_t *idesc;
    118 	usb_endpoint_descriptor_audio_t *edesc;
    119 	struct usb_audio_streaming_type1_descriptor *asf1desc;
    120 	int		sc_busy;	/* currently used */
    121 };
    122 
    123 struct chan {
    124 	void	(*intr)(void *);	/* dma completion intr handler */
    125 	void	*arg;		/* arg for intr() */
    126 	usbd_pipe_handle pipe;
    127 
    128 	u_int	sample_size;
    129 	u_int	sample_rate;
    130 	u_int	bytes_per_frame;
    131 	u_int	fraction;	/* fraction/1000 is the extra samples/frame */
    132 	u_int	residue;	/* accumulates the fractional samples */
    133 
    134 	u_char	*start;		/* upper layer buffer start */
    135 	u_char	*end;		/* upper layer buffer end */
    136 	u_char	*cur;		/* current position in upper layer buffer */
    137 	int	blksize;	/* chunk size to report up */
    138 	int	transferred;	/* transferred bytes not reported up */
    139 
    140 	int	altidx;		/* currently used altidx */
    141 
    142 	int	curchanbuf;
    143 	struct chanbuf {
    144 		struct chan         *chan;
    145 		usbd_xfer_handle xfer;
    146 		u_char              *buffer;
    147 		u_int16_t           sizes[UAUDIO_NFRAMES];
    148 		u_int16_t	    size;
    149 	} chanbufs[UAUDIO_NCHANBUFS];
    150 
    151 	struct uaudio_softc *sc; /* our softc */
    152 };
    153 
    154 struct uaudio_softc {
    155 	USBBASEDEVICE sc_dev;		/* base device */
    156 	usbd_device_handle sc_udev;	/* USB device */
    157 
    158 	int	sc_ac_iface;	/* Audio Control interface */
    159 	usbd_interface_handle	sc_ac_ifaceh;
    160 
    161 	struct chan sc_playchan;	/* play channel */
    162 	struct chan sc_recchan;		/* record channel */
    163 
    164 	int	sc_nullalt;
    165 
    166 	int	sc_audio_rev;
    167 
    168 	struct as_info *sc_alts;
    169 	int	sc_nalts;
    170 
    171 	int	sc_altflags;
    172 #define HAS_8     0x01
    173 #define HAS_16    0x02
    174 #define HAS_8U    0x04
    175 #define HAS_ALAW  0x08
    176 #define HAS_MULAW 0x10
    177 #define UA_NOFRAC	0x20		/* don't do sample rate adjustment */
    178 #define HAS_24		0x40
    179 
    180 	int	sc_mode;		/* play/record capability */
    181 
    182 	struct mixerctl *sc_ctls;
    183 	int	sc_nctls;
    184 
    185 	device_ptr_t sc_audiodev;
    186 	char	sc_dying;
    187 };
    188 
    189 #define UAC_OUTPUT 0
    190 #define UAC_INPUT  1
    191 #define UAC_EQUAL  2
    192 
    193 Static usbd_status	uaudio_identify_ac(struct uaudio_softc *sc,
    194 					   usb_config_descriptor_t *cdesc);
    195 Static usbd_status	uaudio_identify_as(struct uaudio_softc *sc,
    196 					   usb_config_descriptor_t *cdesc);
    197 Static usbd_status	uaudio_process_as(struct uaudio_softc *sc,
    198 			    char *buf, int *offsp, int size,
    199 			    usb_interface_descriptor_t *id);
    200 
    201 Static void 		uaudio_add_alt(struct uaudio_softc *sc,
    202 				       struct as_info *ai);
    203 
    204 Static usb_interface_descriptor_t *uaudio_find_iface(char *buf,
    205 			    int size, int *offsp, int subtype);
    206 
    207 Static void		uaudio_mixer_add_ctl(struct uaudio_softc *sc,
    208 					     struct mixerctl *mp);
    209 Static char 		*uaudio_id_name(struct uaudio_softc *sc,
    210 					usb_descriptor_t **dps, int id);
    211 Static struct usb_audio_cluster uaudio_get_cluster(int id,
    212 						   usb_descriptor_t **dps);
    213 Static void		uaudio_add_input(struct uaudio_softc *sc,
    214 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    215 Static void 		uaudio_add_output(struct uaudio_softc *sc,
    216 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    217 Static void		uaudio_add_mixer(struct uaudio_softc *sc,
    218 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    219 Static void		uaudio_add_selector(struct uaudio_softc *sc,
    220 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    221 Static void		uaudio_add_feature(struct uaudio_softc *sc,
    222 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    223 Static void		uaudio_add_processing_updown(struct uaudio_softc *sc,
    224 			         usb_descriptor_t *v, usb_descriptor_t **dps);
    225 Static void		uaudio_add_processing(struct uaudio_softc *sc,
    226 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    227 Static void		uaudio_add_extension(struct uaudio_softc *sc,
    228 			    usb_descriptor_t *v, usb_descriptor_t **dps);
    229 Static usbd_status	uaudio_identify(struct uaudio_softc *sc,
    230 			    usb_config_descriptor_t *cdesc);
    231 
    232 Static int 		uaudio_signext(int type, int val);
    233 Static int 		uaudio_value2bsd(struct mixerctl *mc, int val);
    234 Static int 		uaudio_bsd2value(struct mixerctl *mc, int val);
    235 Static int 		uaudio_get(struct uaudio_softc *sc, int type,
    236 			    int which, int wValue, int wIndex, int len);
    237 Static int		uaudio_ctl_get(struct uaudio_softc *sc, int which,
    238 			    struct mixerctl *mc, int chan);
    239 Static void		uaudio_set(struct uaudio_softc *sc, int type,
    240 			    int which, int wValue, int wIndex, int l, int v);
    241 Static void 		uaudio_ctl_set(struct uaudio_softc *sc, int which,
    242 			    struct mixerctl *mc, int chan, int val);
    243 
    244 Static usbd_status	uaudio_set_speed(struct uaudio_softc *, int, u_int);
    245 
    246 Static usbd_status	uaudio_chan_open(struct uaudio_softc *sc,
    247 					 struct chan *ch);
    248 Static void		uaudio_chan_close(struct uaudio_softc *sc,
    249 					  struct chan *ch);
    250 Static usbd_status	uaudio_chan_alloc_buffers(struct uaudio_softc *,
    251 						  struct chan *);
    252 Static void		uaudio_chan_free_buffers(struct uaudio_softc *,
    253 						 struct chan *);
    254 Static void		uaudio_chan_init(struct chan *, int,
    255 					 const struct audio_params *);
    256 Static void		uaudio_chan_set_param(struct chan *ch, u_char *start,
    257 			    u_char *end, int blksize);
    258 Static void		uaudio_chan_ptransfer(struct chan *ch);
    259 Static void		uaudio_chan_pintr(usbd_xfer_handle xfer,
    260 			    usbd_private_handle priv, usbd_status status);
    261 
    262 Static void		uaudio_chan_rtransfer(struct chan *ch);
    263 Static void		uaudio_chan_rintr(usbd_xfer_handle xfer,
    264 			    usbd_private_handle priv, usbd_status status);
    265 
    266 Static int		uaudio_open(void *, int);
    267 Static void		uaudio_close(void *);
    268 Static int		uaudio_drain(void *);
    269 Static int		uaudio_query_encoding(void *, struct audio_encoding *);
    270 Static void		uaudio_get_minmax_rates(int, const struct as_info *,
    271 						const struct audio_params *,
    272 						int, u_long *, u_long *);
    273 Static int		uaudio_match_alt_sub(int, const struct as_info *,
    274 					     const struct audio_params *,
    275 					     int, u_long);
    276 Static int		uaudio_match_alt_chan(int, const struct as_info *,
    277 					      struct audio_params *, int);
    278 Static int		uaudio_match_alt(int, const struct as_info *,
    279 					 struct audio_params *, int);
    280 Static int		uaudio_set_params(void *, int, int,
    281 			    struct audio_params *, struct audio_params *);
    282 Static int		uaudio_round_blocksize(void *, int);
    283 Static int		uaudio_trigger_output(void *, void *, void *,
    284 					      int, void (*)(void *), void *,
    285 					      struct audio_params *);
    286 Static int		uaudio_trigger_input (void *, void *, void *,
    287 					      int, void (*)(void *), void *,
    288 					      struct audio_params *);
    289 Static int		uaudio_halt_in_dma(void *);
    290 Static int		uaudio_halt_out_dma(void *);
    291 Static int		uaudio_getdev(void *, struct audio_device *);
    292 Static int		uaudio_mixer_set_port(void *, mixer_ctrl_t *);
    293 Static int		uaudio_mixer_get_port(void *, mixer_ctrl_t *);
    294 Static int		uaudio_query_devinfo(void *, mixer_devinfo_t *);
    295 Static int		uaudio_get_props(void *);
    296 
    297 Static struct audio_hw_if uaudio_hw_if = {
    298 	uaudio_open,
    299 	uaudio_close,
    300 	uaudio_drain,
    301 	uaudio_query_encoding,
    302 	uaudio_set_params,
    303 	uaudio_round_blocksize,
    304 	NULL,
    305 	NULL,
    306 	NULL,
    307 	NULL,
    308 	NULL,
    309 	uaudio_halt_out_dma,
    310 	uaudio_halt_in_dma,
    311 	NULL,
    312 	uaudio_getdev,
    313 	NULL,
    314 	uaudio_mixer_set_port,
    315 	uaudio_mixer_get_port,
    316 	uaudio_query_devinfo,
    317 	NULL,
    318 	NULL,
    319 	NULL,
    320 	NULL,
    321 	uaudio_get_props,
    322 	uaudio_trigger_output,
    323 	uaudio_trigger_input,
    324 	NULL,
    325 };
    326 
    327 Static struct audio_device uaudio_device = {
    328 	"USB audio",
    329 	"",
    330 	"uaudio"
    331 };
    332 
    333 USB_DECLARE_DRIVER(uaudio);
    334 
    335 USB_MATCH(uaudio)
    336 {
    337 	USB_MATCH_START(uaudio, uaa);
    338 	usb_interface_descriptor_t *id;
    339 
    340 	if (uaa->iface == NULL)
    341 		return (UMATCH_NONE);
    342 
    343 	id = usbd_get_interface_descriptor(uaa->iface);
    344 	/* Trigger on the control interface. */
    345 	if (id == NULL ||
    346 	    id->bInterfaceClass != UICLASS_AUDIO ||
    347 	    id->bInterfaceSubClass != UISUBCLASS_AUDIOCONTROL ||
    348 	    (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_AUDIO))
    349 		return (UMATCH_NONE);
    350 
    351 	return (UMATCH_IFACECLASS_IFACESUBCLASS);
    352 }
    353 
    354 USB_ATTACH(uaudio)
    355 {
    356 	USB_ATTACH_START(uaudio, sc, uaa);
    357 	usb_interface_descriptor_t *id;
    358 	usb_config_descriptor_t *cdesc;
    359 	char devinfo[1024];
    360 	usbd_status err;
    361 	int i, j, found;
    362 
    363 	usbd_devinfo(uaa->device, 0, devinfo);
    364 	printf(": %s\n", devinfo);
    365 
    366 	sc->sc_udev = uaa->device;
    367 
    368 	cdesc = usbd_get_config_descriptor(sc->sc_udev);
    369 	if (cdesc == NULL) {
    370 		printf("%s: failed to get configuration descriptor\n",
    371 		       USBDEVNAME(sc->sc_dev));
    372 		USB_ATTACH_ERROR_RETURN;
    373 	}
    374 
    375 	err = uaudio_identify(sc, cdesc);
    376 	if (err) {
    377 		printf("%s: audio descriptors make no sense, error=%d\n",
    378 		       USBDEVNAME(sc->sc_dev), err);
    379 		USB_ATTACH_ERROR_RETURN;
    380 	}
    381 
    382 	sc->sc_ac_ifaceh = uaa->iface;
    383 	/* Pick up the AS interface. */
    384 	for (i = 0; i < uaa->nifaces; i++) {
    385 		if (uaa->ifaces[i] == NULL)
    386 			continue;
    387 		id = usbd_get_interface_descriptor(uaa->ifaces[i]);
    388 		if (id == NULL)
    389 			continue;
    390 		found = 0;
    391 		for (j = 0; j < sc->sc_nalts; j++) {
    392 			if (id->bInterfaceNumber ==
    393 			    sc->sc_alts[j].idesc->bInterfaceNumber) {
    394 				sc->sc_alts[j].ifaceh = uaa->ifaces[i];
    395 				found = 1;
    396 			}
    397 		}
    398 		if (found)
    399 			uaa->ifaces[i] = NULL;
    400 	}
    401 
    402 	for (j = 0; j < sc->sc_nalts; j++) {
    403 		if (sc->sc_alts[j].ifaceh == NULL) {
    404 			printf("%s: alt %d missing AS interface(s)\n",
    405 			    USBDEVNAME(sc->sc_dev), j);
    406 			USB_ATTACH_ERROR_RETURN;
    407 		}
    408 	}
    409 
    410 	printf("%s: audio rev %d.%02x\n", USBDEVNAME(sc->sc_dev),
    411 	       sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff);
    412 
    413 	sc->sc_playchan.sc = sc->sc_recchan.sc = sc;
    414 
    415 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_FRAC)
    416 		sc->sc_altflags |= UA_NOFRAC;
    417 
    418 #ifndef UAUDIO_DEBUG
    419 	if (bootverbose)
    420 #endif
    421 		printf("%s: %d mixer controls\n", USBDEVNAME(sc->sc_dev),
    422 		    sc->sc_nctls);
    423 
    424 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    425 			   USBDEV(sc->sc_dev));
    426 
    427 	DPRINTF(("uaudio_attach: doing audio_attach_mi\n"));
    428 #if defined(__OpenBSD__)
    429 	audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
    430 #else
    431 	sc->sc_audiodev = audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
    432 #endif
    433 
    434 	USB_ATTACH_SUCCESS_RETURN;
    435 }
    436 
    437 int
    438 uaudio_activate(device_ptr_t self, enum devact act)
    439 {
    440 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
    441 	int rv = 0;
    442 
    443 	switch (act) {
    444 	case DVACT_ACTIVATE:
    445 		return (EOPNOTSUPP);
    446 		break;
    447 
    448 	case DVACT_DEACTIVATE:
    449 		if (sc->sc_audiodev != NULL)
    450 			rv = config_deactivate(sc->sc_audiodev);
    451 		sc->sc_dying = 1;
    452 		break;
    453 	}
    454 	return (rv);
    455 }
    456 
    457 int
    458 uaudio_detach(device_ptr_t self, int flags)
    459 {
    460 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
    461 	int rv = 0;
    462 
    463 	/* Wait for outstanding requests to complete. */
    464 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
    465 
    466 	if (sc->sc_audiodev != NULL)
    467 		rv = config_detach(sc->sc_audiodev, flags);
    468 
    469 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    470 			   USBDEV(sc->sc_dev));
    471 
    472 	return (rv);
    473 }
    474 
    475 int
    476 uaudio_query_encoding(void *addr, struct audio_encoding *fp)
    477 {
    478 	struct uaudio_softc *sc = addr;
    479 	int flags = sc->sc_altflags;
    480 	int idx;
    481 
    482 	if (sc->sc_dying)
    483 		return (EIO);
    484 
    485 	if (sc->sc_nalts == 0 || flags == 0)
    486 		return (ENXIO);
    487 
    488 	idx = fp->index;
    489 	switch (idx) {
    490 	case 0:
    491 		strcpy(fp->name, AudioEulinear);
    492 		fp->encoding = AUDIO_ENCODING_ULINEAR;
    493 		fp->precision = 8;
    494 		fp->flags = flags&HAS_8U ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
    495 		return (0);
    496 	case 1:
    497 		strcpy(fp->name, AudioEmulaw);
    498 		fp->encoding = AUDIO_ENCODING_ULAW;
    499 		fp->precision = 8;
    500 		fp->flags = flags&HAS_MULAW ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
    501 		return (0);
    502 	case 2:
    503 		strcpy(fp->name, AudioEalaw);
    504 		fp->encoding = AUDIO_ENCODING_ALAW;
    505 		fp->precision = 8;
    506 		fp->flags = flags&HAS_ALAW ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
    507 		return (0);
    508 	case 3:
    509 		strcpy(fp->name, AudioEslinear);
    510 		fp->encoding = AUDIO_ENCODING_SLINEAR;
    511 		fp->precision = 8;
    512 		fp->flags = flags&HAS_8 ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
    513 		return (0);
    514         case 4:
    515 		strcpy(fp->name, AudioEslinear_le);
    516 		fp->encoding = AUDIO_ENCODING_SLINEAR_LE;
    517 		fp->precision = 16;
    518 		fp->flags = 0;
    519 		return (0);
    520 	case 5:
    521 		strcpy(fp->name, AudioEulinear_le);
    522 		fp->encoding = AUDIO_ENCODING_ULINEAR_LE;
    523 		fp->precision = 16;
    524 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
    525 		return (0);
    526 	case 6:
    527 		strcpy(fp->name, AudioEslinear_be);
    528 		fp->encoding = AUDIO_ENCODING_SLINEAR_BE;
    529 		fp->precision = 16;
    530 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
    531 		return (0);
    532 	case 7:
    533 		strcpy(fp->name, AudioEulinear_be);
    534 		fp->encoding = AUDIO_ENCODING_ULINEAR_BE;
    535 		fp->precision = 16;
    536 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
    537 		return (0);
    538 	default:
    539 		return (EINVAL);
    540 	}
    541 }
    542 
    543 usb_interface_descriptor_t *
    544 uaudio_find_iface(char *buf, int size, int *offsp, int subtype)
    545 {
    546 	usb_interface_descriptor_t *d;
    547 
    548 	while (*offsp < size) {
    549 		d = (void *)(buf + *offsp);
    550 		*offsp += d->bLength;
    551 		if (d->bDescriptorType == UDESC_INTERFACE &&
    552 		    d->bInterfaceClass == UICLASS_AUDIO &&
    553 		    d->bInterfaceSubClass == subtype)
    554 			return (d);
    555 	}
    556 	return (NULL);
    557 }
    558 
    559 void
    560 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct mixerctl *mc)
    561 {
    562 	int res;
    563 	size_t len = sizeof(*mc) * (sc->sc_nctls + 1);
    564 	struct mixerctl *nmc = sc->sc_nctls == 0 ?
    565 	    malloc(len, M_USBDEV, M_NOWAIT) :
    566 	    realloc(sc->sc_ctls, len, M_USBDEV, M_NOWAIT);
    567 
    568 	if (nmc == NULL) {
    569 		printf("uaudio_mixer_add_ctl: no memory\n");
    570 		return;
    571 	}
    572 	sc->sc_ctls = nmc;
    573 
    574 	mc->delta = 0;
    575 	if (mc->type != MIX_ON_OFF) {
    576 		/* Determine min and max values. */
    577 		mc->minval = uaudio_signext(mc->type,
    578 			uaudio_get(sc, GET_MIN, UT_READ_CLASS_INTERFACE,
    579 				   mc->wValue[0], mc->wIndex,
    580 				   MIX_SIZE(mc->type)));
    581 		mc->maxval = 1 + uaudio_signext(mc->type,
    582 			uaudio_get(sc, GET_MAX, UT_READ_CLASS_INTERFACE,
    583 				   mc->wValue[0], mc->wIndex,
    584 				   MIX_SIZE(mc->type)));
    585 		mc->mul = mc->maxval - mc->minval;
    586 		if (mc->mul == 0)
    587 			mc->mul = 1;
    588 		res = uaudio_get(sc, GET_RES, UT_READ_CLASS_INTERFACE,
    589 				 mc->wValue[0], mc->wIndex,
    590 				 MIX_SIZE(mc->type));
    591 		if (res > 0)
    592 			mc->delta = (res * 256 + mc->mul/2) / mc->mul;
    593 	} else {
    594 		mc->minval = 0;
    595 		mc->maxval = 1;
    596 	}
    597 
    598 	sc->sc_ctls[sc->sc_nctls++] = *mc;
    599 
    600 #ifdef UAUDIO_DEBUG
    601 	if (uaudiodebug > 2) {
    602 		int i;
    603 		DPRINTF(("uaudio_mixer_add_ctl: wValue=%04x",mc->wValue[0]));
    604 		for (i = 1; i < mc->nchan; i++)
    605 			DPRINTF((",%04x", mc->wValue[i]));
    606 		DPRINTF((" wIndex=%04x type=%d name='%s' unit='%s' "
    607 			 "min=%d max=%d\n",
    608 			 mc->wIndex, mc->type, mc->ctlname, mc->ctlunit,
    609 			 mc->minval, mc->maxval));
    610 	}
    611 #endif
    612 }
    613 
    614 char *
    615 uaudio_id_name(struct uaudio_softc *sc, usb_descriptor_t **dps, int id)
    616 {
    617 	static char buf[32];
    618 	sprintf(buf, "i%d", id);
    619 	return (buf);
    620 }
    621 
    622 struct usb_audio_cluster
    623 uaudio_get_cluster(int id, usb_descriptor_t **dps)
    624 {
    625 	struct usb_audio_cluster r;
    626 	usb_descriptor_t *dp;
    627 	int i;
    628 
    629 	for (i = 0; i < 25; i++) { /* avoid infinite loops */
    630 		dp = dps[id];
    631 		if (dp == 0)
    632 			goto bad;
    633 		switch (dp->bDescriptorSubtype) {
    634 		case UDESCSUB_AC_INPUT:
    635 #define p ((struct usb_audio_input_terminal *)dp)
    636 			r.bNrChannels = p->bNrChannels;
    637 			USETW(r.wChannelConfig, UGETW(p->wChannelConfig));
    638 			r.iChannelNames = p->iChannelNames;
    639 #undef p
    640 			return (r);
    641 		case UDESCSUB_AC_OUTPUT:
    642 #define p ((struct usb_audio_output_terminal *)dp)
    643 			id = p->bSourceId;
    644 #undef p
    645 			break;
    646 		case UDESCSUB_AC_MIXER:
    647 #define p ((struct usb_audio_mixer_unit *)dp)
    648 			r = *(struct usb_audio_cluster *)
    649 				&p->baSourceId[p->bNrInPins];
    650 #undef p
    651 			return (r);
    652 		case UDESCSUB_AC_SELECTOR:
    653 			/* XXX This is not really right */
    654 #define p ((struct usb_audio_selector_unit *)dp)
    655 			id = p->baSourceId[0];
    656 #undef p
    657 			break;
    658 		case UDESCSUB_AC_FEATURE:
    659 #define p ((struct usb_audio_feature_unit *)dp)
    660 			id = p->bSourceId;
    661 #undef p
    662 			break;
    663 		case UDESCSUB_AC_PROCESSING:
    664 #define p ((struct usb_audio_processing_unit *)dp)
    665 			r = *(struct usb_audio_cluster *)
    666 				&p->baSourceId[p->bNrInPins];
    667 #undef p
    668 			return (r);
    669 		case UDESCSUB_AC_EXTENSION:
    670 #define p ((struct usb_audio_extension_unit *)dp)
    671 			r = *(struct usb_audio_cluster *)
    672 				&p->baSourceId[p->bNrInPins];
    673 #undef p
    674 			return (r);
    675 		default:
    676 			goto bad;
    677 		}
    678 	}
    679  bad:
    680 	printf("uaudio_get_cluster: bad data\n");
    681 	memset(&r, 0, sizeof r);
    682 	return (r);
    683 
    684 }
    685 
    686 void
    687 uaudio_add_input(struct uaudio_softc *sc, usb_descriptor_t *v,
    688 		 usb_descriptor_t **dps)
    689 {
    690 #ifdef UAUDIO_DEBUG
    691 	struct usb_audio_input_terminal *d =
    692 		(struct usb_audio_input_terminal *)v;
    693 
    694 	DPRINTFN(2,("uaudio_add_input: bTerminalId=%d wTerminalType=0x%04x "
    695 		    "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
    696 		    "iChannelNames=%d iTerminal=%d\n",
    697 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
    698 		    d->bNrChannels, UGETW(d->wChannelConfig),
    699 		    d->iChannelNames, d->iTerminal));
    700 #endif
    701 }
    702 
    703 void
    704 uaudio_add_output(struct uaudio_softc *sc, usb_descriptor_t *v,
    705 		  usb_descriptor_t **dps)
    706 {
    707 #ifdef UAUDIO_DEBUG
    708 	struct usb_audio_output_terminal *d =
    709 		(struct usb_audio_output_terminal *)v;
    710 
    711 	DPRINTFN(2,("uaudio_add_output: bTerminalId=%d wTerminalType=0x%04x "
    712 		    "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
    713 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
    714 		    d->bSourceId, d->iTerminal));
    715 #endif
    716 }
    717 
    718 void
    719 uaudio_add_mixer(struct uaudio_softc *sc, usb_descriptor_t *v,
    720 		 usb_descriptor_t **dps)
    721 {
    722 	struct usb_audio_mixer_unit *d = (struct usb_audio_mixer_unit *)v;
    723 	struct usb_audio_mixer_unit_1 *d1;
    724 	int c, chs, ichs, ochs, i, o, bno, p, mo, mc, k;
    725 	uByte *bm;
    726 	struct mixerctl mix;
    727 
    728 	DPRINTFN(2,("uaudio_add_mixer: bUnitId=%d bNrInPins=%d\n",
    729 		    d->bUnitId, d->bNrInPins));
    730 
    731 	/* Compute the number of input channels */
    732 	ichs = 0;
    733 	for (i = 0; i < d->bNrInPins; i++)
    734 		ichs += uaudio_get_cluster(d->baSourceId[i], dps).bNrChannels;
    735 
    736 	/* and the number of output channels */
    737 	d1 = (struct usb_audio_mixer_unit_1 *)&d->baSourceId[d->bNrInPins];
    738 	ochs = d1->bNrChannels;
    739 	DPRINTFN(2,("uaudio_add_mixer: ichs=%d ochs=%d\n", ichs, ochs));
    740 
    741 	bm = d1->bmControls;
    742 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
    743 	mix.class = -1;
    744 	mix.type = MIX_SIGNED_16;
    745 	mix.ctlunit = AudioNvolume;
    746 #define BIT(bno) ((bm[bno / 8] >> (7 - bno % 8)) & 1)
    747 	for (p = i = 0; i < d->bNrInPins; i++) {
    748 		chs = uaudio_get_cluster(d->baSourceId[i], dps).bNrChannels;
    749 		mc = 0;
    750 		for (c = 0; c < chs; c++) {
    751 			mo = 0;
    752 			for (o = 0; o < ochs; o++) {
    753 				bno = (p + c) * ochs + o;
    754 				if (BIT(bno))
    755 					mo++;
    756 			}
    757 			if (mo == 1)
    758 				mc++;
    759 		}
    760 		if (mc == chs && chs <= MIX_MAX_CHAN) {
    761 			k = 0;
    762 			for (c = 0; c < chs; c++)
    763 				for (o = 0; o < ochs; o++) {
    764 					bno = (p + c) * ochs + o;
    765 					if (BIT(bno))
    766 						mix.wValue[k++] =
    767 							MAKE(p+c+1, o+1);
    768 				}
    769 			sprintf(mix.ctlname, "mix%d-%s", d->bUnitId,
    770 				uaudio_id_name(sc, dps, d->baSourceId[i]));
    771 			mix.nchan = chs;
    772 			uaudio_mixer_add_ctl(sc, &mix);
    773 		} else {
    774 			/* XXX */
    775 		}
    776 #undef BIT
    777 		p += chs;
    778 	}
    779 
    780 }
    781 
    782 void
    783 uaudio_add_selector(struct uaudio_softc *sc, usb_descriptor_t *v,
    784 		    usb_descriptor_t **dps)
    785 {
    786 #ifdef UAUDIO_DEBUG
    787 	struct usb_audio_selector_unit *d =
    788 		(struct usb_audio_selector_unit *)v;
    789 
    790 	DPRINTFN(2,("uaudio_add_selector: bUnitId=%d bNrInPins=%d\n",
    791 		    d->bUnitId, d->bNrInPins));
    792 #endif
    793 	printf("uaudio_add_selector: NOT IMPLEMENTED\n");
    794 }
    795 
    796 void
    797 uaudio_add_feature(struct uaudio_softc *sc, usb_descriptor_t *v,
    798 		   usb_descriptor_t **dps)
    799 {
    800 	struct usb_audio_feature_unit *d = (struct usb_audio_feature_unit *)v;
    801 	uByte *ctls = d->bmaControls;
    802 	int ctlsize = d->bControlSize;
    803 	int nchan = (d->bLength - 7) / ctlsize;
    804 	int srcId = d->bSourceId;
    805 	u_int fumask, mmask, cmask;
    806 	struct mixerctl mix;
    807 	int chan, ctl, i, unit;
    808 
    809 #define GET(i) (ctls[(i)*ctlsize] | \
    810 		(ctlsize > 1 ? ctls[(i)*ctlsize+1] << 8 : 0))
    811 
    812 	mmask = GET(0);
    813 	/* Figure out what we can control */
    814 	for (cmask = 0, chan = 1; chan < nchan; chan++) {
    815 		DPRINTFN(9,("uaudio_add_feature: chan=%d mask=%x\n",
    816 			    chan, GET(chan)));
    817 		cmask |= GET(chan);
    818 	}
    819 
    820 	DPRINTFN(1,("uaudio_add_feature: bUnitId=%d bSourceId=%d, "
    821 		    "%d channels, mmask=0x%04x, cmask=0x%04x\n",
    822 		    d->bUnitId, srcId, nchan, mmask, cmask));
    823 
    824 	if (nchan > MIX_MAX_CHAN)
    825 		nchan = MIX_MAX_CHAN;
    826 	unit = d->bUnitId;
    827 	mix.wIndex = MAKE(unit, sc->sc_ac_iface);
    828 	for (ctl = MUTE_CONTROL; ctl < LOUDNESS_CONTROL; ctl++) {
    829 		fumask = FU_MASK(ctl);
    830 		DPRINTFN(4,("uaudio_add_feature: ctl=%d fumask=0x%04x\n",
    831 			    ctl, fumask));
    832 		if (mmask & fumask) {
    833 			mix.nchan = 1;
    834 			mix.wValue[0] = MAKE(ctl, 0);
    835 		} else if (cmask & fumask) {
    836 			mix.nchan = nchan - 1;
    837 			for (i = 1; i < nchan; i++) {
    838 				if (GET(i) & fumask)
    839 					mix.wValue[i-1] = MAKE(ctl, i);
    840 				else
    841 					mix.wValue[i-1] = -1;
    842 			}
    843 		} else {
    844 			continue;
    845 		}
    846 #undef GET
    847 		mix.class = -1;	/* XXX */
    848 		switch (ctl) {
    849 		case MUTE_CONTROL:
    850 			mix.type = MIX_ON_OFF;
    851 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    852 				uaudio_id_name(sc, dps, srcId),
    853 				AudioNmute);
    854 			mix.ctlunit = "";
    855 			break;
    856 		case VOLUME_CONTROL:
    857 			mix.type = MIX_SIGNED_16;
    858 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    859 				uaudio_id_name(sc, dps, srcId),
    860 				AudioNmaster);
    861 			mix.ctlunit = AudioNvolume;
    862 			break;
    863 		case BASS_CONTROL:
    864 			mix.type = MIX_SIGNED_8;
    865 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    866 				uaudio_id_name(sc, dps, srcId),
    867 				AudioNbass);
    868 			mix.ctlunit = AudioNbass;
    869 			break;
    870 		case MID_CONTROL:
    871 			mix.type = MIX_SIGNED_8;
    872 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    873 				uaudio_id_name(sc, dps, srcId),
    874 				AudioNmid);
    875 			mix.ctlunit = AudioNmid;
    876 			break;
    877 		case TREBLE_CONTROL:
    878 			mix.type = MIX_SIGNED_8;
    879 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    880 				uaudio_id_name(sc, dps, srcId),
    881 				AudioNtreble);
    882 			mix.ctlunit = AudioNtreble;
    883 			break;
    884 		case GRAPHIC_EQUALIZER_CONTROL:
    885 			continue; /* XXX don't add anything */
    886 			break;
    887 		case AGC_CONTROL:
    888 			mix.type = MIX_ON_OFF;
    889 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    890 				uaudio_id_name(sc, dps, srcId),
    891 				AudioNagc);
    892 			mix.ctlunit = "";
    893 			break;
    894 		case DELAY_CONTROL:
    895 			mix.type = MIX_UNSIGNED_16;
    896 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    897 				uaudio_id_name(sc, dps, srcId),
    898 				AudioNdelay);
    899 			mix.ctlunit = "4 ms";
    900 			break;
    901 		case BASS_BOOST_CONTROL:
    902 			mix.type = MIX_ON_OFF;
    903 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    904 				uaudio_id_name(sc, dps, srcId),
    905 				AudioNbassboost);
    906 			mix.ctlunit = "";
    907 			break;
    908 		case LOUDNESS_CONTROL:
    909 			mix.type = MIX_ON_OFF;
    910 			sprintf(mix.ctlname, "fea%d-%s-%s", unit,
    911 				uaudio_id_name(sc, dps, srcId),
    912 				AudioNloudness);
    913 			mix.ctlunit = "";
    914 			break;
    915 		}
    916 		uaudio_mixer_add_ctl(sc, &mix);
    917 	}
    918 }
    919 
    920 void
    921 uaudio_add_processing_updown(struct uaudio_softc *sc, usb_descriptor_t *v,
    922 			     usb_descriptor_t **dps)
    923 {
    924 	struct usb_audio_processing_unit *d =
    925 	    (struct usb_audio_processing_unit *)v;
    926 	struct usb_audio_processing_unit_1 *d1 =
    927 	    (struct usb_audio_processing_unit_1 *)&d->baSourceId[d->bNrInPins];
    928 	struct usb_audio_processing_unit_updown *ud =
    929 	    (struct usb_audio_processing_unit_updown *)
    930 		&d1->bmControls[d1->bControlSize];
    931 	struct mixerctl mix;
    932 	int i;
    933 
    934 	DPRINTFN(2,("uaudio_add_processing_updown: bUnitId=%d bNrModes=%d\n",
    935 		    d->bUnitId, ud->bNrModes));
    936 
    937 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
    938 		DPRINTF(("uaudio_add_processing_updown: no mode select\n"));
    939 		return;
    940 	}
    941 
    942 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
    943 	mix.nchan = 1;
    944 	mix.wValue[0] = MAKE(UD_MODE_SELECT_CONTROL, 0);
    945 	mix.class = -1;
    946 	mix.type = MIX_ON_OFF;	/* XXX */
    947 	mix.ctlunit = "";
    948 	sprintf(mix.ctlname, "pro%d-mode", d->bUnitId);
    949 
    950 	for (i = 0; i < ud->bNrModes; i++) {
    951 		DPRINTFN(2,("uaudio_add_processing_updown: i=%d bm=0x%x\n",
    952 			    i, UGETW(ud->waModes[i])));
    953 		/* XXX */
    954 	}
    955 	uaudio_mixer_add_ctl(sc, &mix);
    956 }
    957 
    958 void
    959 uaudio_add_processing(struct uaudio_softc *sc, usb_descriptor_t *v,
    960 		      usb_descriptor_t **dps)
    961 {
    962 	struct usb_audio_processing_unit *d =
    963 	    (struct usb_audio_processing_unit *)v;
    964 	struct usb_audio_processing_unit_1 *d1 =
    965 	    (struct usb_audio_processing_unit_1 *)&d->baSourceId[d->bNrInPins];
    966 	int ptype = UGETW(d->wProcessType);
    967 	struct mixerctl mix;
    968 
    969 	DPRINTFN(2,("uaudio_add_processing: wProcessType=%d bUnitId=%d "
    970 		    "bNrInPins=%d\n", ptype, d->bUnitId, d->bNrInPins));
    971 
    972 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
    973 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
    974 		mix.nchan = 1;
    975 		mix.wValue[0] = MAKE(XX_ENABLE_CONTROL, 0);
    976 		mix.class = -1;
    977 		mix.type = MIX_ON_OFF;
    978 		mix.ctlunit = "";
    979 		sprintf(mix.ctlname, "pro%d.%d-enable", d->bUnitId, ptype);
    980 		uaudio_mixer_add_ctl(sc, &mix);
    981 	}
    982 
    983 	switch(ptype) {
    984 	case UPDOWNMIX_PROCESS:
    985 		uaudio_add_processing_updown(sc, v, dps);
    986 		break;
    987 	case DOLBY_PROLOGIC_PROCESS:
    988 	case P3D_STEREO_EXTENDER_PROCESS:
    989 	case REVERBATION_PROCESS:
    990 	case CHORUS_PROCESS:
    991 	case DYN_RANGE_COMP_PROCESS:
    992 	default:
    993 #ifdef UAUDIO_DEBUG
    994 		printf("uaudio_add_processing: unit %d, type=%d not impl.\n",
    995 		       d->bUnitId, ptype);
    996 #endif
    997 		break;
    998 	}
    999 }
   1000 
   1001 void
   1002 uaudio_add_extension(struct uaudio_softc *sc, usb_descriptor_t *v,
   1003 		     usb_descriptor_t **dps)
   1004 {
   1005 	struct usb_audio_extension_unit *d =
   1006 	    (struct usb_audio_extension_unit *)v;
   1007 	struct usb_audio_extension_unit_1 *d1 =
   1008 	    (struct usb_audio_extension_unit_1 *)&d->baSourceId[d->bNrInPins];
   1009 	struct mixerctl mix;
   1010 
   1011 	DPRINTFN(2,("uaudio_add_extension: bUnitId=%d bNrInPins=%d\n",
   1012 		    d->bUnitId, d->bNrInPins));
   1013 
   1014 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_XU)
   1015 		return;
   1016 
   1017 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
   1018 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
   1019 		mix.nchan = 1;
   1020 		mix.wValue[0] = MAKE(UA_EXT_ENABLE, 0);
   1021 		mix.class = -1;
   1022 		mix.type = MIX_ON_OFF;
   1023 		mix.ctlunit = "";
   1024 		sprintf(mix.ctlname, "ext%d-enable", d->bUnitId);
   1025 		uaudio_mixer_add_ctl(sc, &mix);
   1026 	}
   1027 }
   1028 
   1029 usbd_status
   1030 uaudio_identify(struct uaudio_softc *sc, usb_config_descriptor_t *cdesc)
   1031 {
   1032 	usbd_status err;
   1033 
   1034 	err = uaudio_identify_ac(sc, cdesc);
   1035 	if (err)
   1036 		return (err);
   1037 	return (uaudio_identify_as(sc, cdesc));
   1038 }
   1039 
   1040 void
   1041 uaudio_add_alt(struct uaudio_softc *sc, struct as_info *ai)
   1042 {
   1043 	size_t len = sizeof(*ai) * (sc->sc_nalts + 1);
   1044 	struct as_info *nai = (sc->sc_nalts == 0) ?
   1045 	    malloc(len, M_USBDEV, M_NOWAIT) :
   1046 	    realloc(sc->sc_alts, len, M_USBDEV, M_NOWAIT);
   1047 
   1048 	if (nai == NULL) {
   1049 		printf("uaudio_add_alt: no memory\n");
   1050 		return;
   1051 	}
   1052 
   1053 	sc->sc_alts = nai;
   1054 	DPRINTFN(2,("uaudio_add_alt: adding alt=%d, enc=%d\n",
   1055 		    ai->alt, ai->encoding));
   1056 	sc->sc_alts[sc->sc_nalts++] = *ai;
   1057 }
   1058 
   1059 usbd_status
   1060 uaudio_process_as(struct uaudio_softc *sc, char *buf, int *offsp,
   1061 		  int size, usb_interface_descriptor_t *id)
   1062 #define offs (*offsp)
   1063 {
   1064 	struct usb_audio_streaming_interface_descriptor *asid;
   1065 	struct usb_audio_streaming_type1_descriptor *asf1d;
   1066 	usb_endpoint_descriptor_audio_t *ed;
   1067 	struct usb_audio_streaming_endpoint_descriptor *sed;
   1068 	int format, chan, prec, enc;
   1069 	int dir, type;
   1070 	struct as_info ai;
   1071 
   1072 	asid = (void *)(buf + offs);
   1073 	if (asid->bDescriptorType != UDESC_CS_INTERFACE ||
   1074 	    asid->bDescriptorSubtype != AS_GENERAL)
   1075 		return (USBD_INVAL);
   1076 	offs += asid->bLength;
   1077 	if (offs > size)
   1078 		return (USBD_INVAL);
   1079 	asf1d = (void *)(buf + offs);
   1080 	if (asf1d->bDescriptorType != UDESC_CS_INTERFACE ||
   1081 	    asf1d->bDescriptorSubtype != FORMAT_TYPE)
   1082 		return (USBD_INVAL);
   1083 	offs += asf1d->bLength;
   1084 	if (offs > size)
   1085 		return (USBD_INVAL);
   1086 
   1087 	if (asf1d->bFormatType != FORMAT_TYPE_I) {
   1088 		printf("%s: ignored setting with type %d format\n",
   1089 		       USBDEVNAME(sc->sc_dev), UGETW(asid->wFormatTag));
   1090 		return (USBD_NORMAL_COMPLETION);
   1091 	}
   1092 
   1093 	ed = (void *)(buf + offs);
   1094 	if (ed->bDescriptorType != UDESC_ENDPOINT)
   1095 		return (USBD_INVAL);
   1096 	DPRINTF(("uaudio_process_as: endpoint bLength=%d bDescriptorType=%d "
   1097 		 "bEndpointAddress=%d bmAttributes=0x%x wMaxPacketSize=%d "
   1098 		 "bInterval=%d bRefresh=%d bSynchAddress=%d\n",
   1099 		 ed->bLength, ed->bDescriptorType, ed->bEndpointAddress,
   1100 		 ed->bmAttributes, UGETW(ed->wMaxPacketSize),
   1101 		 ed->bInterval, ed->bRefresh, ed->bSynchAddress));
   1102 	offs += ed->bLength;
   1103 	if (offs > size)
   1104 		return (USBD_INVAL);
   1105 	if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
   1106 		return (USBD_INVAL);
   1107 
   1108 	dir = UE_GET_DIR(ed->bEndpointAddress);
   1109 	type = UE_GET_ISO_TYPE(ed->bmAttributes);
   1110 	if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_INP_ASYNC) &&
   1111 	    dir == UE_DIR_IN && type == UE_ISO_ADAPT)
   1112 		type = UE_ISO_ASYNC;
   1113 
   1114 	/* We can't handle endpoints that need a sync pipe yet. */
   1115 	if (dir == UE_DIR_IN ? type == UE_ISO_ADAPT : type == UE_ISO_ASYNC) {
   1116 		printf("%s: ignored %sput endpoint of type %s\n",
   1117 		       USBDEVNAME(sc->sc_dev),
   1118 		       dir == UE_DIR_IN ? "in" : "out",
   1119 		       dir == UE_DIR_IN ? "adaptive" : "async");
   1120 		return (USBD_NORMAL_COMPLETION);
   1121 	}
   1122 
   1123 	sed = (void *)(buf + offs);
   1124 	if (sed->bDescriptorType != UDESC_CS_ENDPOINT ||
   1125 	    sed->bDescriptorSubtype != AS_GENERAL)
   1126 		return (USBD_INVAL);
   1127 	offs += sed->bLength;
   1128 	if (offs > size)
   1129 		return (USBD_INVAL);
   1130 
   1131 	format = UGETW(asid->wFormatTag);
   1132 	chan = asf1d->bNrChannels;
   1133 	prec = asf1d->bBitResolution;
   1134 	if (prec != 8 && prec != 16 && prec != 24) {
   1135 		printf("%s: ignored setting with precision %d\n",
   1136 		       USBDEVNAME(sc->sc_dev), prec);
   1137 		return (USBD_NORMAL_COMPLETION);
   1138 	}
   1139 	switch (format) {
   1140 	case UA_FMT_PCM:
   1141 		if (prec == 8) {
   1142 			sc->sc_altflags |= HAS_8;
   1143 		} else if (prec == 16) {
   1144 			sc->sc_altflags |= HAS_16;
   1145 		} else if (prec == 24) {
   1146 			sc->sc_altflags |= HAS_24;
   1147 		}
   1148 		enc = AUDIO_ENCODING_SLINEAR_LE;
   1149 		break;
   1150 	case UA_FMT_PCM8:
   1151 		enc = AUDIO_ENCODING_ULINEAR_LE;
   1152 		sc->sc_altflags |= HAS_8U;
   1153 		break;
   1154 	case UA_FMT_ALAW:
   1155 		enc = AUDIO_ENCODING_ALAW;
   1156 		sc->sc_altflags |= HAS_ALAW;
   1157 		break;
   1158 	case UA_FMT_MULAW:
   1159 		enc = AUDIO_ENCODING_ULAW;
   1160 		sc->sc_altflags |= HAS_MULAW;
   1161 		break;
   1162 	default:
   1163 		printf("%s: ignored setting with format %d\n",
   1164 		       USBDEVNAME(sc->sc_dev), format);
   1165 		return (USBD_NORMAL_COMPLETION);
   1166 	}
   1167 	DPRINTFN(1, ("uaudio_process_as: alt=%d enc=%d chan=%d prec=%d\n",
   1168 		     id->bAlternateSetting, enc, chan, prec));
   1169 	ai.alt = id->bAlternateSetting;
   1170 	ai.encoding = enc;
   1171 	ai.attributes = sed->bmAttributes;
   1172 	ai.idesc = id;
   1173 	ai.edesc = ed;
   1174 	ai.asf1desc = asf1d;
   1175 	ai.sc_busy = 0;
   1176 	uaudio_add_alt(sc, &ai);
   1177 #ifdef UAUDIO_DEBUG
   1178 	{
   1179 		int j;
   1180 		if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
   1181 			DPRINTFN(1, ("uaudio_process_as:  rate=%d-%d\n",
   1182 				     UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d)));
   1183 		} else {
   1184 			DPRINTFN(1, ("uaudio_process_as: "));
   1185 			for (j = 0; j < asf1d->bSamFreqType; j++)
   1186 				DPRINTFN(1, (" %d", UA_GETSAMP(asf1d, j)));
   1187 			DPRINTFN(1, ("\n"));
   1188 		}
   1189 		if (ai.attributes & UA_SED_FREQ_CONTROL)
   1190 			DPRINTFN(1, ("uaudio_process_as:  FREQ_CONTROL\n"));
   1191 		if (ai.attributes & UA_SED_PITCH_CONTROL)
   1192 			DPRINTFN(1, ("uaudio_process_as:  PITCH_CONTROL\n"));
   1193 	}
   1194 #endif
   1195 	sc->sc_mode |= (dir == UE_DIR_OUT) ? AUMODE_PLAY : AUMODE_RECORD;
   1196 
   1197 	return (USBD_NORMAL_COMPLETION);
   1198 }
   1199 #undef offs
   1200 
   1201 usbd_status
   1202 uaudio_identify_as(struct uaudio_softc *sc, usb_config_descriptor_t *cdesc)
   1203 {
   1204 	usb_interface_descriptor_t *id;
   1205 	usbd_status err;
   1206 	char *buf;
   1207 	int size, offs;
   1208 
   1209 	size = UGETW(cdesc->wTotalLength);
   1210 	buf = (char *)cdesc;
   1211 
   1212 	/* Locate the AudioStreaming interface descriptor. */
   1213 	offs = 0;
   1214 	id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOSTREAM);
   1215 	if (id == NULL)
   1216 		return (USBD_INVAL);
   1217 
   1218 	/* Loop through all the alternate settings. */
   1219 	while (offs <= size) {
   1220 		DPRINTFN(2, ("uaudio_identify: interface %d\n",
   1221 		    id->bInterfaceNumber));
   1222 		switch (id->bNumEndpoints) {
   1223 		case 0:
   1224 			DPRINTFN(2, ("uaudio_identify: AS null alt=%d\n",
   1225 				     id->bAlternateSetting));
   1226 			sc->sc_nullalt = id->bAlternateSetting;
   1227 			break;
   1228 		case 1:
   1229 			err = uaudio_process_as(sc, buf, &offs, size, id);
   1230 			break;
   1231 		default:
   1232 #ifdef UAUDIO_DEBUG
   1233 			printf("%s: ignored audio interface with %d "
   1234 			       "endpoints\n",
   1235 			       USBDEVNAME(sc->sc_dev), id->bNumEndpoints);
   1236 #endif
   1237 			break;
   1238 		}
   1239 		id = uaudio_find_iface(buf, size, &offs,UISUBCLASS_AUDIOSTREAM);
   1240 		if (id == NULL)
   1241 			break;
   1242 	}
   1243 	if (offs > size)
   1244 		return (USBD_INVAL);
   1245 	DPRINTF(("uaudio_identify_as: %d alts available\n", sc->sc_nalts));
   1246 
   1247 	if ((sc->sc_mode & (AUMODE_PLAY | AUMODE_RECORD)) == 0) {
   1248 		printf("%s: no usable endpoint found\n",
   1249 		       USBDEVNAME(sc->sc_dev));
   1250 		return (USBD_INVAL);
   1251 	}
   1252 
   1253 	return (USBD_NORMAL_COMPLETION);
   1254 }
   1255 
   1256 usbd_status
   1257 uaudio_identify_ac(struct uaudio_softc *sc, usb_config_descriptor_t *cdesc)
   1258 {
   1259 	usb_interface_descriptor_t *id;
   1260 	struct usb_audio_control_descriptor *acdp;
   1261 	usb_descriptor_t *dp, *dps[256];
   1262 	char *buf, *ibuf, *ibufend;
   1263 	int size, offs, aclen, ndps, i;
   1264 
   1265 	size = UGETW(cdesc->wTotalLength);
   1266 	buf = (char *)cdesc;
   1267 
   1268 	/* Locate the AudioControl interface descriptor. */
   1269 	offs = 0;
   1270 	id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOCONTROL);
   1271 	if (id == NULL)
   1272 		return (USBD_INVAL);
   1273 	if (offs + sizeof *acdp > size)
   1274 		return (USBD_INVAL);
   1275 	sc->sc_ac_iface = id->bInterfaceNumber;
   1276 	DPRINTFN(2,("uaudio_identify: AC interface is %d\n", sc->sc_ac_iface));
   1277 
   1278 	/* A class-specific AC interface header should follow. */
   1279 	ibuf = buf + offs;
   1280 	acdp = (struct usb_audio_control_descriptor *)ibuf;
   1281 	if (acdp->bDescriptorType != UDESC_CS_INTERFACE ||
   1282 	    acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)
   1283 		return (USBD_INVAL);
   1284 	aclen = UGETW(acdp->wTotalLength);
   1285 	if (offs + aclen > size)
   1286 		return (USBD_INVAL);
   1287 
   1288 	if (!(usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_BAD_ADC) &&
   1289 	     UGETW(acdp->bcdADC) != UAUDIO_VERSION)
   1290 		return (USBD_INVAL);
   1291 
   1292 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
   1293 	DPRINTFN(2,("uaudio_identify: found AC header, vers=%03x, len=%d\n",
   1294 		 sc->sc_audio_rev, aclen));
   1295 
   1296 	sc->sc_nullalt = -1;
   1297 
   1298 	/* Scan through all the AC specific descriptors */
   1299 	ibufend = ibuf + aclen;
   1300 	dp = (usb_descriptor_t *)ibuf;
   1301 	ndps = 0;
   1302 	memset(dps, 0, sizeof dps);
   1303 	for (;;) {
   1304 		ibuf += dp->bLength;
   1305 		if (ibuf >= ibufend)
   1306 			break;
   1307 		dp = (usb_descriptor_t *)ibuf;
   1308 		if (ibuf + dp->bLength > ibufend)
   1309 			return (USBD_INVAL);
   1310 		if (dp->bDescriptorType != UDESC_CS_INTERFACE) {
   1311 			printf("uaudio_identify: skip desc type=0x%02x\n",
   1312 			       dp->bDescriptorType);
   1313 			continue;
   1314 		}
   1315 		i = ((struct usb_audio_input_terminal *)dp)->bTerminalId;
   1316 		dps[i] = dp;
   1317 		if (i > ndps)
   1318 			ndps = i;
   1319 	}
   1320 	ndps++;
   1321 
   1322 	for (i = 0; i < ndps; i++) {
   1323 		dp = dps[i];
   1324 		if (dp == NULL)
   1325 			continue;
   1326 		DPRINTF(("uaudio_identify: subtype=%d\n",
   1327 			 dp->bDescriptorSubtype));
   1328 		switch (dp->bDescriptorSubtype) {
   1329 		case UDESCSUB_AC_HEADER:
   1330 			printf("uaudio_identify: unexpected AC header\n");
   1331 			break;
   1332 		case UDESCSUB_AC_INPUT:
   1333 			uaudio_add_input(sc, dp, dps);
   1334 			break;
   1335 		case UDESCSUB_AC_OUTPUT:
   1336 			uaudio_add_output(sc, dp, dps);
   1337 			break;
   1338 		case UDESCSUB_AC_MIXER:
   1339 			uaudio_add_mixer(sc, dp, dps);
   1340 			break;
   1341 		case UDESCSUB_AC_SELECTOR:
   1342 			uaudio_add_selector(sc, dp, dps);
   1343 			break;
   1344 		case UDESCSUB_AC_FEATURE:
   1345 			uaudio_add_feature(sc, dp, dps);
   1346 			break;
   1347 		case UDESCSUB_AC_PROCESSING:
   1348 			uaudio_add_processing(sc, dp, dps);
   1349 			break;
   1350 		case UDESCSUB_AC_EXTENSION:
   1351 			uaudio_add_extension(sc, dp, dps);
   1352 			break;
   1353 		default:
   1354 			printf("uaudio_identify: bad AC desc subtype=0x%02x\n",
   1355 			       dp->bDescriptorSubtype);
   1356 			break;
   1357 		}
   1358 	}
   1359 	return (USBD_NORMAL_COMPLETION);
   1360 }
   1361 
   1362 int
   1363 uaudio_query_devinfo(void *addr, mixer_devinfo_t *mi)
   1364 {
   1365 	struct uaudio_softc *sc = addr;
   1366 	struct mixerctl *mc;
   1367 	int n, nctls;
   1368 
   1369 	DPRINTFN(2,("uaudio_query_devinfo: index=%d\n", mi->index));
   1370 	if (sc->sc_dying)
   1371 		return (EIO);
   1372 
   1373 	n = mi->index;
   1374 	nctls = sc->sc_nctls;
   1375 
   1376 	if (n < 0 || n >= nctls) {
   1377 		switch (n - nctls) {
   1378 		case UAC_OUTPUT:
   1379 			mi->type = AUDIO_MIXER_CLASS;
   1380 			mi->mixer_class = nctls + UAC_OUTPUT;
   1381 			mi->next = mi->prev = AUDIO_MIXER_LAST;
   1382 			strcpy(mi->label.name, AudioCoutputs);
   1383 			return (0);
   1384 		case UAC_INPUT:
   1385 			mi->type = AUDIO_MIXER_CLASS;
   1386 			mi->mixer_class = nctls + UAC_INPUT;
   1387 			mi->next = mi->prev = AUDIO_MIXER_LAST;
   1388 			strcpy(mi->label.name, AudioCinputs);
   1389 			return (0);
   1390 		case UAC_EQUAL:
   1391 			mi->type = AUDIO_MIXER_CLASS;
   1392 			mi->mixer_class = nctls + UAC_EQUAL;
   1393 			mi->next = mi->prev = AUDIO_MIXER_LAST;
   1394 			strcpy(mi->label.name, AudioCequalization);
   1395 			return (0);
   1396 		default:
   1397 			return (ENXIO);
   1398 		}
   1399 	}
   1400 	mc = &sc->sc_ctls[n];
   1401 	strncpy(mi->label.name, mc->ctlname, MAX_AUDIO_DEV_LEN);
   1402 	mi->mixer_class = mc->class;
   1403 	mi->next = mi->prev = AUDIO_MIXER_LAST;	/* XXX */
   1404 	switch (mc->type) {
   1405 	case MIX_ON_OFF:
   1406 		mi->type = AUDIO_MIXER_ENUM;
   1407 		mi->un.e.num_mem = 2;
   1408 		strcpy(mi->un.e.member[0].label.name, AudioNoff);
   1409 		mi->un.e.member[0].ord = 0;
   1410 		strcpy(mi->un.e.member[1].label.name, AudioNon);
   1411 		mi->un.e.member[1].ord = 1;
   1412 		break;
   1413 	default:
   1414 		mi->type = AUDIO_MIXER_VALUE;
   1415 		strncpy(mi->un.v.units.name, mc->ctlunit, MAX_AUDIO_DEV_LEN);
   1416 		mi->un.v.num_channels = mc->nchan;
   1417 		mi->un.v.delta = mc->delta;
   1418 		break;
   1419 	}
   1420 	return (0);
   1421 }
   1422 
   1423 int
   1424 uaudio_open(void *addr, int flags)
   1425 {
   1426 	struct uaudio_softc *sc = addr;
   1427 
   1428         DPRINTF(("uaudio_open: sc=%p\n", sc));
   1429 	if (sc->sc_dying)
   1430 		return (EIO);
   1431 
   1432 	if (sc->sc_mode == 0)
   1433 		return (ENXIO);
   1434 
   1435 	if (flags & FREAD) {
   1436 		if ((sc->sc_mode & AUMODE_RECORD) == 0)
   1437 			return (EACCES);
   1438 		sc->sc_recchan.intr = NULL;
   1439 	}
   1440 
   1441 	if (flags & FWRITE) {
   1442 		if ((sc->sc_mode & AUMODE_PLAY) == 0)
   1443 			return (EACCES);
   1444 		sc->sc_playchan.intr = NULL;
   1445 	}
   1446 
   1447         return (0);
   1448 }
   1449 
   1450 /*
   1451  * Close function is called at splaudio().
   1452  */
   1453 void
   1454 uaudio_close(void *addr)
   1455 {
   1456 	struct uaudio_softc *sc = addr;
   1457 
   1458 	DPRINTF(("uaudio_close: sc=%p\n", sc));
   1459 	uaudio_halt_in_dma(sc);
   1460 	uaudio_halt_out_dma(sc);
   1461 
   1462 	sc->sc_playchan.intr = sc->sc_recchan.intr = NULL;
   1463 }
   1464 
   1465 int
   1466 uaudio_drain(void *addr)
   1467 {
   1468 	struct uaudio_softc *sc = addr;
   1469 
   1470 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
   1471 
   1472 	return (0);
   1473 }
   1474 
   1475 int
   1476 uaudio_halt_out_dma(void *addr)
   1477 {
   1478 	struct uaudio_softc *sc = addr;
   1479 
   1480 	DPRINTF(("uaudio_halt_out_dma: enter\n"));
   1481 	if (sc->sc_playchan.pipe != NULL) {
   1482 		uaudio_chan_close(sc, &sc->sc_playchan);
   1483 		sc->sc_playchan.pipe = NULL;
   1484 		uaudio_chan_free_buffers(sc, &sc->sc_playchan);
   1485 	}
   1486         return (0);
   1487 }
   1488 
   1489 int
   1490 uaudio_halt_in_dma(void *addr)
   1491 {
   1492 	struct uaudio_softc *sc = addr;
   1493 
   1494 	DPRINTF(("uaudio_halt_in_dma: enter\n"));
   1495 	if (sc->sc_recchan.pipe != NULL) {
   1496 		uaudio_chan_close(sc, &sc->sc_recchan);
   1497 		sc->sc_recchan.pipe = NULL;
   1498 		uaudio_chan_free_buffers(sc, &sc->sc_recchan);
   1499 	}
   1500         return (0);
   1501 }
   1502 
   1503 int
   1504 uaudio_getdev(void *addr, struct audio_device *retp)
   1505 {
   1506 	struct uaudio_softc *sc = addr;
   1507 
   1508 	DPRINTF(("uaudio_mixer_getdev:\n"));
   1509 	if (sc->sc_dying)
   1510 		return (EIO);
   1511 
   1512 	*retp = uaudio_device;
   1513         return (0);
   1514 }
   1515 
   1516 /*
   1517  * Make sure the block size is large enough to hold all outstanding transfers.
   1518  */
   1519 int
   1520 uaudio_round_blocksize(void *addr, int blk)
   1521 {
   1522 	struct uaudio_softc *sc = addr;
   1523 	int bpf;
   1524 
   1525 	DPRINTF(("uaudio_round_blocksize: p.bpf=%d r.bpf=%d\n",
   1526 		sc->sc_playchan.bytes_per_frame, sc->sc_recchan.bytes_per_frame));
   1527 	if (sc->sc_playchan.bytes_per_frame > sc->sc_recchan.bytes_per_frame) {
   1528 		bpf = sc->sc_playchan.bytes_per_frame
   1529 		    + sc->sc_playchan.sample_size;
   1530 	} else {
   1531 		bpf = sc->sc_recchan.bytes_per_frame
   1532 		    + sc->sc_recchan.sample_size;
   1533 	}
   1534 	/* XXX */
   1535 	bpf *= UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
   1536 
   1537 	bpf = (bpf + 15) &~ 15;
   1538 
   1539 	if (blk < bpf)
   1540 		blk = bpf;
   1541 
   1542 #ifdef DIAGNOSTIC
   1543 	if (blk <= 0) {
   1544 		printf("uaudio_round_blocksize: blk=%d\n", blk);
   1545 		blk = 512;
   1546 	}
   1547 #endif
   1548 
   1549 	DPRINTFN(1,("uaudio_round_blocksize: blk=%d\n", blk));
   1550 	return (blk);
   1551 }
   1552 
   1553 int
   1554 uaudio_get_props(void *addr)
   1555 {
   1556 	return (AUDIO_PROP_FULLDUPLEX | AUDIO_PROP_INDEPENDENT);
   1557 
   1558 }
   1559 
   1560 int
   1561 uaudio_get(struct uaudio_softc *sc, int which, int type, int wValue,
   1562 	   int wIndex, int len)
   1563 {
   1564 	usb_device_request_t req;
   1565 	u_int8_t data[4];
   1566 	usbd_status err;
   1567 	int val;
   1568 
   1569 	if (wValue == -1)
   1570 		return (0);
   1571 
   1572 	req.bmRequestType = type;
   1573 	req.bRequest = which;
   1574 	USETW(req.wValue, wValue);
   1575 	USETW(req.wIndex, wIndex);
   1576 	USETW(req.wLength, len);
   1577 	DPRINTFN(2,("uaudio_get: type=0x%02x req=0x%02x wValue=0x%04x "
   1578 		    "wIndex=0x%04x len=%d\n",
   1579 		    type, which, wValue, wIndex, len));
   1580 	err = usbd_do_request(sc->sc_udev, &req, data);
   1581 	if (err) {
   1582 		DPRINTF(("uaudio_get: err=%s\n", usbd_errstr(err)));
   1583 		return (-1);
   1584 	}
   1585 	switch (len) {
   1586 	case 1:
   1587 		val = data[0];
   1588 		break;
   1589 	case 2:
   1590 		val = data[0] | (data[1] << 8);
   1591 		break;
   1592 	default:
   1593 		DPRINTF(("uaudio_get: bad length=%d\n", len));
   1594 		return (-1);
   1595 	}
   1596 	DPRINTFN(2,("uaudio_get: val=%d\n", val));
   1597 	return (val);
   1598 }
   1599 
   1600 void
   1601 uaudio_set(struct uaudio_softc *sc, int which, int type, int wValue,
   1602 	   int wIndex, int len, int val)
   1603 {
   1604 	usb_device_request_t req;
   1605 	u_int8_t data[4];
   1606 	usbd_status err;
   1607 
   1608 	if (wValue == -1)
   1609 		return;
   1610 
   1611 	req.bmRequestType = type;
   1612 	req.bRequest = which;
   1613 	USETW(req.wValue, wValue);
   1614 	USETW(req.wIndex, wIndex);
   1615 	USETW(req.wLength, len);
   1616 	switch (len) {
   1617 	case 1:
   1618 		data[0] = val;
   1619 		break;
   1620 	case 2:
   1621 		data[0] = val;
   1622 		data[1] = val >> 8;
   1623 		break;
   1624 	default:
   1625 		return;
   1626 	}
   1627 	DPRINTFN(2,("uaudio_set: type=0x%02x req=0x%02x wValue=0x%04x "
   1628 		    "wIndex=0x%04x len=%d, val=%d\n",
   1629 		    type, which, wValue, wIndex, len, val & 0xffff));
   1630 	err = usbd_do_request(sc->sc_udev, &req, data);
   1631 #ifdef UAUDIO_DEBUG
   1632 	if (err)
   1633 		DPRINTF(("uaudio_set: err=%d\n", err));
   1634 #endif
   1635 }
   1636 
   1637 int
   1638 uaudio_signext(int type, int val)
   1639 {
   1640 	if (!MIX_UNSIGNED(type)) {
   1641 		if (MIX_SIZE(type) == 2)
   1642 			val = (int16_t)val;
   1643 		else
   1644 			val = (int8_t)val;
   1645 	}
   1646 	return (val);
   1647 }
   1648 
   1649 int
   1650 uaudio_value2bsd(struct mixerctl *mc, int val)
   1651 {
   1652 	DPRINTFN(5, ("uaudio_value2bsd: type=%03x val=%d min=%d max=%d ",
   1653 		     mc->type, val, mc->minval, mc->maxval));
   1654 	if (mc->type == MIX_ON_OFF)
   1655 		val = (val != 0);
   1656 	else
   1657 		val = ((uaudio_signext(mc->type, val) - mc->minval) * 256
   1658 			+ mc->mul/2) / mc->mul;
   1659 	DPRINTFN(5, ("val'=%d\n", val));
   1660 	return (val);
   1661 }
   1662 
   1663 int
   1664 uaudio_bsd2value(struct mixerctl *mc, int val)
   1665 {
   1666 	DPRINTFN(5,("uaudio_bsd2value: type=%03x val=%d min=%d max=%d ",
   1667 		    mc->type, val, mc->minval, mc->maxval));
   1668 	if (mc->type == MIX_ON_OFF)
   1669 		val = (val != 0);
   1670 	else
   1671 		val = (val + mc->delta/2) * mc->mul / 256 + mc->minval;
   1672 	DPRINTFN(5, ("val'=%d\n", val));
   1673 	return (val);
   1674 }
   1675 
   1676 int
   1677 uaudio_ctl_get(struct uaudio_softc *sc, int which, struct mixerctl *mc,
   1678 	       int chan)
   1679 {
   1680 	int val;
   1681 
   1682 	DPRINTFN(5,("uaudio_ctl_get: which=%d chan=%d\n", which, chan));
   1683 	val = uaudio_get(sc, which, UT_READ_CLASS_INTERFACE, mc->wValue[chan],
   1684 			 mc->wIndex, MIX_SIZE(mc->type));
   1685 	return (uaudio_value2bsd(mc, val));
   1686 }
   1687 
   1688 void
   1689 uaudio_ctl_set(struct uaudio_softc *sc, int which, struct mixerctl *mc,
   1690 	       int chan, int val)
   1691 {
   1692 	val = uaudio_bsd2value(mc, val);
   1693 	uaudio_set(sc, which, UT_WRITE_CLASS_INTERFACE, mc->wValue[chan],
   1694 		   mc->wIndex, MIX_SIZE(mc->type), val);
   1695 }
   1696 
   1697 int
   1698 uaudio_mixer_get_port(void *addr, mixer_ctrl_t *cp)
   1699 {
   1700 	struct uaudio_softc *sc = addr;
   1701 	struct mixerctl *mc;
   1702 	int i, n, vals[MIX_MAX_CHAN], val;
   1703 
   1704 	DPRINTFN(2,("uaudio_mixer_get_port: index=%d\n", cp->dev));
   1705 
   1706 	if (sc->sc_dying)
   1707 		return (EIO);
   1708 
   1709 	n = cp->dev;
   1710 	if (n < 0 || n >= sc->sc_nctls)
   1711 		return (ENXIO);
   1712 	mc = &sc->sc_ctls[n];
   1713 
   1714 	if (mc->type == MIX_ON_OFF) {
   1715 		if (cp->type != AUDIO_MIXER_ENUM)
   1716 			return (EINVAL);
   1717 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
   1718 	} else {
   1719 		if (cp->type != AUDIO_MIXER_VALUE)
   1720 			return (EINVAL);
   1721 		if (cp->un.value.num_channels != 1 &&
   1722 		    cp->un.value.num_channels != mc->nchan)
   1723 			return (EINVAL);
   1724 		for (i = 0; i < mc->nchan; i++)
   1725 			vals[i] = uaudio_ctl_get(sc, GET_CUR, mc, i);
   1726 		if (cp->un.value.num_channels == 1 && mc->nchan != 1) {
   1727 			for (val = 0, i = 0; i < mc->nchan; i++)
   1728 				val += vals[i];
   1729 			vals[0] = val / mc->nchan;
   1730 		}
   1731 		for (i = 0; i < cp->un.value.num_channels; i++)
   1732 			cp->un.value.level[i] = vals[i];
   1733 	}
   1734 
   1735 	return (0);
   1736 }
   1737 
   1738 int
   1739 uaudio_mixer_set_port(void *addr, mixer_ctrl_t *cp)
   1740 {
   1741 	struct uaudio_softc *sc = addr;
   1742 	struct mixerctl *mc;
   1743 	int i, n, vals[MIX_MAX_CHAN];
   1744 
   1745 	DPRINTFN(2,("uaudio_mixer_set_port: index = %d\n", cp->dev));
   1746 	if (sc->sc_dying)
   1747 		return (EIO);
   1748 
   1749 	n = cp->dev;
   1750 	if (n < 0 || n >= sc->sc_nctls)
   1751 		return (ENXIO);
   1752 	mc = &sc->sc_ctls[n];
   1753 
   1754 	if (mc->type == MIX_ON_OFF) {
   1755 		if (cp->type != AUDIO_MIXER_ENUM)
   1756 			return (EINVAL);
   1757 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
   1758 	} else {
   1759 		if (cp->type != AUDIO_MIXER_VALUE)
   1760 			return (EINVAL);
   1761 		if (cp->un.value.num_channels == 1)
   1762 			for (i = 0; i < mc->nchan; i++)
   1763 				vals[i] = cp->un.value.level[0];
   1764 		else if (cp->un.value.num_channels == mc->nchan)
   1765 			for (i = 0; i < mc->nchan; i++)
   1766 				vals[i] = cp->un.value.level[i];
   1767 		else
   1768 			return (EINVAL);
   1769 		for (i = 0; i < mc->nchan; i++)
   1770 			uaudio_ctl_set(sc, SET_CUR, mc, i, vals[i]);
   1771 	}
   1772 	return (0);
   1773 }
   1774 
   1775 int
   1776 uaudio_trigger_input(void *addr, void *start, void *end, int blksize,
   1777 		     void (*intr)(void *), void *arg,
   1778 		     struct audio_params *param)
   1779 {
   1780 	struct uaudio_softc *sc = addr;
   1781 	struct chan *ch = &sc->sc_recchan;
   1782 	usbd_status err;
   1783 	int i, s;
   1784 
   1785 	if (sc->sc_dying)
   1786 		return (EIO);
   1787 
   1788 	DPRINTFN(3,("uaudio_trigger_input: sc=%p start=%p end=%p "
   1789 		    "blksize=%d\n", sc, start, end, blksize));
   1790 
   1791 	uaudio_chan_set_param(ch, start, end, blksize);
   1792 	DPRINTFN(3,("uaudio_trigger_input: sample_size=%d bytes/frame=%d "
   1793 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
   1794 		    ch->fraction));
   1795 
   1796 	err = uaudio_chan_alloc_buffers(sc, ch);
   1797 	if (err)
   1798 		return (EIO);
   1799 
   1800 	err = uaudio_chan_open(sc, ch);
   1801 	if (err) {
   1802 		uaudio_chan_free_buffers(sc, ch);
   1803 		return (EIO);
   1804 	}
   1805 
   1806 	ch->intr = intr;
   1807 	ch->arg = arg;
   1808 
   1809 	s = splusb();
   1810 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
   1811 		uaudio_chan_rtransfer(ch);
   1812 	splx(s);
   1813 
   1814         return (0);
   1815 }
   1816 
   1817 int
   1818 uaudio_trigger_output(void *addr, void *start, void *end, int blksize,
   1819 		      void (*intr)(void *), void *arg,
   1820 		      struct audio_params *param)
   1821 {
   1822 	struct uaudio_softc *sc = addr;
   1823 	struct chan *ch = &sc->sc_playchan;
   1824 	usbd_status err;
   1825 	int i, s;
   1826 
   1827 	if (sc->sc_dying)
   1828 		return (EIO);
   1829 
   1830 	DPRINTFN(3,("uaudio_trigger_output: sc=%p start=%p end=%p "
   1831 		    "blksize=%d\n", sc, start, end, blksize));
   1832 
   1833 	uaudio_chan_set_param(ch, start, end, blksize);
   1834 	DPRINTFN(3,("uaudio_trigger_output: sample_size=%d bytes/frame=%d "
   1835 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
   1836 		    ch->fraction));
   1837 
   1838 	err = uaudio_chan_alloc_buffers(sc, ch);
   1839 	if (err)
   1840 		return (EIO);
   1841 
   1842 	err = uaudio_chan_open(sc, ch);
   1843 	if (err) {
   1844 		uaudio_chan_free_buffers(sc, ch);
   1845 		return (EIO);
   1846 	}
   1847 
   1848 	ch->intr = intr;
   1849 	ch->arg = arg;
   1850 
   1851 	s = splusb();
   1852 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
   1853 		uaudio_chan_ptransfer(ch);
   1854 	splx(s);
   1855 
   1856         return (0);
   1857 }
   1858 
   1859 /* Set up a pipe for a channel. */
   1860 usbd_status
   1861 uaudio_chan_open(struct uaudio_softc *sc, struct chan *ch)
   1862 {
   1863 	struct as_info *as = &sc->sc_alts[ch->altidx];
   1864 	int endpt = as->edesc->bEndpointAddress;
   1865 	usbd_status err;
   1866 
   1867 	DPRINTF(("uaudio_chan_open: endpt=0x%02x, speed=%d, alt=%d\n",
   1868 		 endpt, ch->sample_rate, as->alt));
   1869 
   1870 	/* Set alternate interface corresponding to the mode. */
   1871 	err = usbd_set_interface(as->ifaceh, as->alt);
   1872 	if (err)
   1873 		return (err);
   1874 
   1875 	/* Some devices do not support this request, so ignore errors. */
   1876 #ifdef UAUDIO_DEBUG
   1877 	err = uaudio_set_speed(sc, endpt, ch->sample_rate);
   1878 	if (err)
   1879 		DPRINTF(("uaudio_chan_open: set_speed failed err=%s\n",
   1880 			 usbd_errstr(err)));
   1881 #else
   1882 	(void)uaudio_set_speed(sc, endpt, ch->sample_rate);
   1883 #endif
   1884 
   1885 	DPRINTF(("uaudio_chan_open: create pipe to 0x%02x\n", endpt));
   1886 	err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->pipe);
   1887 	return (err);
   1888 }
   1889 
   1890 void
   1891 uaudio_chan_close(struct uaudio_softc *sc, struct chan *ch)
   1892 {
   1893 	struct as_info *as = &sc->sc_alts[ch->altidx];
   1894 
   1895 	if (sc->sc_nullalt >= 0) {
   1896 		DPRINTF(("uaudio_chan_close: set null alt=%d\n",
   1897 			 sc->sc_nullalt));
   1898 		usbd_set_interface(as->ifaceh, sc->sc_nullalt);
   1899 	}
   1900 	usbd_abort_pipe(ch->pipe);
   1901 	usbd_close_pipe(ch->pipe);
   1902 }
   1903 
   1904 usbd_status
   1905 uaudio_chan_alloc_buffers(struct uaudio_softc *sc, struct chan *ch)
   1906 {
   1907 	usbd_xfer_handle xfer;
   1908 	void *buf;
   1909 	int i, size;
   1910 
   1911 	size = (ch->bytes_per_frame + ch->sample_size) * UAUDIO_NFRAMES;
   1912 	for (i = 0; i < UAUDIO_NCHANBUFS; i++) {
   1913 		xfer = usbd_alloc_xfer(sc->sc_udev);
   1914 		if (xfer == 0)
   1915 			goto bad;
   1916 		ch->chanbufs[i].xfer = xfer;
   1917 		buf = usbd_alloc_buffer(xfer, size);
   1918 		if (buf == 0) {
   1919 			i++;
   1920 			goto bad;
   1921 		}
   1922 		ch->chanbufs[i].buffer = buf;
   1923 		ch->chanbufs[i].chan = ch;
   1924 	}
   1925 
   1926 	return (USBD_NORMAL_COMPLETION);
   1927 
   1928 bad:
   1929 	while (--i >= 0)
   1930 		/* implicit buffer free */
   1931 		usbd_free_xfer(ch->chanbufs[i].xfer);
   1932 	return (USBD_NOMEM);
   1933 }
   1934 
   1935 void
   1936 uaudio_chan_free_buffers(struct uaudio_softc *sc, struct chan *ch)
   1937 {
   1938 	int i;
   1939 
   1940 	for (i = 0; i < UAUDIO_NCHANBUFS; i++)
   1941 		usbd_free_xfer(ch->chanbufs[i].xfer);
   1942 }
   1943 
   1944 /* Called at splusb() */
   1945 void
   1946 uaudio_chan_ptransfer(struct chan *ch)
   1947 {
   1948 	struct chanbuf *cb;
   1949 	int i, n, size, residue, total;
   1950 
   1951 	if (ch->sc->sc_dying)
   1952 		return;
   1953 
   1954 	/* Pick the next channel buffer. */
   1955 	cb = &ch->chanbufs[ch->curchanbuf];
   1956 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
   1957 		ch->curchanbuf = 0;
   1958 
   1959 	/* Compute the size of each frame in the next transfer. */
   1960 	residue = ch->residue;
   1961 	total = 0;
   1962 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
   1963 		size = ch->bytes_per_frame;
   1964 		residue += ch->fraction;
   1965 		if (residue >= USB_FRAMES_PER_SECOND) {
   1966 			if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
   1967 				size += ch->sample_size;
   1968 			residue -= USB_FRAMES_PER_SECOND;
   1969 		}
   1970 		cb->sizes[i] = size;
   1971 		total += size;
   1972 	}
   1973 	ch->residue = residue;
   1974 	cb->size = total;
   1975 
   1976 	/*
   1977 	 * Transfer data from upper layer buffer to channel buffer, taking
   1978 	 * care of wrapping the upper layer buffer.
   1979 	 */
   1980 	n = min(total, ch->end - ch->cur);
   1981 	memcpy(cb->buffer, ch->cur, n);
   1982 	ch->cur += n;
   1983 	if (ch->cur >= ch->end)
   1984 		ch->cur = ch->start;
   1985 	if (total > n) {
   1986 		total -= n;
   1987 		memcpy(cb->buffer + n, ch->cur, total);
   1988 		ch->cur += total;
   1989 	}
   1990 
   1991 #ifdef UAUDIO_DEBUG
   1992 	if (uaudiodebug > 8) {
   1993 		DPRINTF(("uaudio_chan_ptransfer: buffer=%p, residue=0.%03d\n",
   1994 			 cb->buffer, ch->residue));
   1995 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
   1996 			DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
   1997 		}
   1998 	}
   1999 #endif
   2000 
   2001 	DPRINTFN(5,("uaudio_chan_transfer: ptransfer xfer=%p\n", cb->xfer));
   2002 	/* Fill the request */
   2003 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
   2004 			     UAUDIO_NFRAMES, USBD_NO_COPY,
   2005 			     uaudio_chan_pintr);
   2006 
   2007 	(void)usbd_transfer(cb->xfer);
   2008 }
   2009 
   2010 void
   2011 uaudio_chan_pintr(usbd_xfer_handle xfer, usbd_private_handle priv,
   2012 		  usbd_status status)
   2013 {
   2014 	struct chanbuf *cb = priv;
   2015 	struct chan *ch = cb->chan;
   2016 	u_int32_t count;
   2017 	int s;
   2018 
   2019 	/* Return if we are aborting. */
   2020 	if (status == USBD_CANCELLED)
   2021 		return;
   2022 
   2023 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   2024 	DPRINTFN(5,("uaudio_chan_pintr: count=%d, transferred=%d\n",
   2025 		    count, ch->transferred));
   2026 #ifdef DIAGNOSTIC
   2027 	if (count != cb->size) {
   2028 		printf("uaudio_chan_pintr: count(%d) != size(%d)\n",
   2029 		       count, cb->size);
   2030 	}
   2031 #endif
   2032 
   2033 	ch->transferred += cb->size;
   2034 	s = splaudio();
   2035 	/* Call back to upper layer */
   2036 	while (ch->transferred >= ch->blksize) {
   2037 		ch->transferred -= ch->blksize;
   2038 		DPRINTFN(5,("uaudio_chan_pintr: call %p(%p)\n",
   2039 			    ch->intr, ch->arg));
   2040 		ch->intr(ch->arg);
   2041 	}
   2042 	splx(s);
   2043 
   2044 	/* start next transfer */
   2045 	uaudio_chan_ptransfer(ch);
   2046 }
   2047 
   2048 /* Called at splusb() */
   2049 void
   2050 uaudio_chan_rtransfer(struct chan *ch)
   2051 {
   2052 	struct chanbuf *cb;
   2053 	int i, size, residue, total;
   2054 
   2055 	if (ch->sc->sc_dying)
   2056 		return;
   2057 
   2058 	/* Pick the next channel buffer. */
   2059 	cb = &ch->chanbufs[ch->curchanbuf];
   2060 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
   2061 		ch->curchanbuf = 0;
   2062 
   2063 	/* Compute the size of each frame in the next transfer. */
   2064 	residue = ch->residue;
   2065 	total = 0;
   2066 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
   2067 		size = ch->bytes_per_frame;
   2068 		residue += ch->fraction;
   2069 		if (residue >= USB_FRAMES_PER_SECOND) {
   2070 			if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
   2071 				size += ch->sample_size;
   2072 			residue -= USB_FRAMES_PER_SECOND;
   2073 		}
   2074 		cb->sizes[i] = size;
   2075 		total += size;
   2076 	}
   2077 	ch->residue = residue;
   2078 	cb->size = total;
   2079 
   2080 #ifdef UAUDIO_DEBUG
   2081 	if (uaudiodebug > 8) {
   2082 		DPRINTF(("uaudio_chan_rtransfer: buffer=%p, residue=0.%03d\n",
   2083 			 cb->buffer, ch->residue));
   2084 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
   2085 			DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
   2086 		}
   2087 	}
   2088 #endif
   2089 
   2090 	DPRINTFN(5,("uaudio_chan_rtransfer: transfer xfer=%p\n", cb->xfer));
   2091 	/* Fill the request */
   2092 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
   2093 			     UAUDIO_NFRAMES, USBD_NO_COPY,
   2094 			     uaudio_chan_rintr);
   2095 
   2096 	(void)usbd_transfer(cb->xfer);
   2097 }
   2098 
   2099 void
   2100 uaudio_chan_rintr(usbd_xfer_handle xfer, usbd_private_handle priv,
   2101 		  usbd_status status)
   2102 {
   2103 	struct chanbuf *cb = priv;
   2104 	struct chan *ch = cb->chan;
   2105 	u_int32_t count;
   2106 	int s, n;
   2107 
   2108 	/* Return if we are aborting. */
   2109 	if (status == USBD_CANCELLED)
   2110 		return;
   2111 
   2112 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   2113 	DPRINTFN(5,("uaudio_chan_rintr: count=%d, transferred=%d\n",
   2114 		    count, ch->transferred));
   2115 
   2116 	if (count < cb->size) {
   2117 		/* if the device fails to keep up, copy last byte */
   2118 		u_char b = count ? cb->buffer[count-1] : 0;
   2119 		while (count < cb->size)
   2120 			cb->buffer[count++] = b;
   2121 	}
   2122 
   2123 #ifdef DIAGNOSTIC
   2124 	if (count != cb->size) {
   2125 		printf("uaudio_chan_rintr: count(%d) != size(%d)\n",
   2126 		       count, cb->size);
   2127 	}
   2128 #endif
   2129 
   2130 	/*
   2131 	 * Transfer data from channel buffer to upper layer buffer, taking
   2132 	 * care of wrapping the upper layer buffer.
   2133 	 */
   2134 	n = min(count, ch->end - ch->cur);
   2135 	memcpy(ch->cur, cb->buffer, n);
   2136 	ch->cur += n;
   2137 	if (ch->cur >= ch->end)
   2138 		ch->cur = ch->start;
   2139 	if (count > n) {
   2140 		memcpy(ch->cur, cb->buffer + n, count - n);
   2141 		ch->cur += count - n;
   2142 	}
   2143 
   2144 	/* Call back to upper layer */
   2145 	ch->transferred += cb->size;
   2146 	s = splaudio();
   2147 	while (ch->transferred >= ch->blksize) {
   2148 		ch->transferred -= ch->blksize;
   2149 		DPRINTFN(5,("uaudio_chan_rintr: call %p(%p)\n",
   2150 			    ch->intr, ch->arg));
   2151 		ch->intr(ch->arg);
   2152 	}
   2153 	splx(s);
   2154 
   2155 	/* start next transfer */
   2156 	uaudio_chan_rtransfer(ch);
   2157 }
   2158 
   2159 void
   2160 uaudio_chan_init(struct chan *ch, int altidx, const struct audio_params *param)
   2161 {
   2162 	int samples_per_frame, sample_size;
   2163 
   2164 	ch->altidx = altidx;
   2165 	sample_size = param->precision * param->factor * param->hw_channels / 8;
   2166 	samples_per_frame = param->hw_sample_rate / USB_FRAMES_PER_SECOND;
   2167 	ch->fraction = param->hw_sample_rate % USB_FRAMES_PER_SECOND;
   2168 	ch->sample_size = sample_size;
   2169 	ch->sample_rate = param->hw_sample_rate;
   2170 	ch->bytes_per_frame = samples_per_frame * sample_size;
   2171 	ch->residue = 0;
   2172 }
   2173 
   2174 void
   2175 uaudio_chan_set_param(struct chan *ch, u_char *start, u_char *end, int blksize)
   2176 {
   2177 	ch->start = start;
   2178 	ch->end = end;
   2179 	ch->cur = start;
   2180 	ch->blksize = blksize;
   2181 	ch->transferred = 0;
   2182 
   2183 	ch->curchanbuf = 0;
   2184 }
   2185 
   2186 void
   2187 uaudio_get_minmax_rates(int nalts, const struct as_info *alts,
   2188 			const struct audio_params *p, int mode,
   2189 			u_long *min, u_long *max)
   2190 {
   2191 	int i, j;
   2192 	struct usb_audio_streaming_type1_descriptor *a1d;
   2193 
   2194 	*min = ULONG_MAX;
   2195 	*max = 0;
   2196 	for (i = 0; i < nalts; i++) {
   2197 		a1d = alts[i].asf1desc;
   2198 		if (alts[i].sc_busy)
   2199 			continue;
   2200 		if (p->hw_channels != a1d->bNrChannels)
   2201 			continue;
   2202 		if (p->hw_precision != a1d->bBitResolution)
   2203 			continue;
   2204 		if (p->hw_encoding != alts[i].encoding)
   2205 			continue;
   2206 		if (mode != UE_GET_DIR(alts[i].edesc->bEndpointAddress))
   2207 			continue;
   2208 		if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
   2209 			DPRINTFN(2,("uaudio_get_minmax_rates: cont %d-%d\n",
   2210 				    UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
   2211 			if (UA_SAMP_LO(a1d) < *min)
   2212 				*min = UA_SAMP_LO(a1d);
   2213 			if (UA_SAMP_HI(a1d) > *max)
   2214 				*max = UA_SAMP_HI(a1d);
   2215 		} else {
   2216 			for (j = 0; j < a1d->bSamFreqType; j++) {
   2217 				DPRINTFN(2,("uaudio_get_minmax_rates: disc #%d: %d\n",
   2218 					    j, UA_GETSAMP(a1d, j)));
   2219 				if (UA_GETSAMP(a1d, j) < *min)
   2220 					*min = UA_GETSAMP(a1d, j);
   2221 				if (UA_GETSAMP(a1d, j) > *max)
   2222 					*max = UA_GETSAMP(a1d, j);
   2223 			}
   2224 		}
   2225 	}
   2226 }
   2227 
   2228 int
   2229 uaudio_match_alt_sub(int nalts, const struct as_info *alts,
   2230 		     const struct audio_params *p, int mode, u_long rate)
   2231 {
   2232 	int i, j;
   2233 	struct usb_audio_streaming_type1_descriptor *a1d;
   2234 
   2235 	DPRINTF(("uaudio_match_alt_sub: search for %luHz %dch\n",
   2236 		 rate, p->hw_channels));
   2237 	for (i = 0; i < nalts; i++) {
   2238 		a1d = alts[i].asf1desc;
   2239 		if (alts[i].sc_busy)
   2240 			continue;
   2241 		if (p->hw_channels != a1d->bNrChannels)
   2242 			continue;
   2243 		if (p->hw_precision != a1d->bBitResolution)
   2244 			continue;
   2245 		if (p->hw_encoding != alts[i].encoding)
   2246 			continue;
   2247 		if (mode != UE_GET_DIR(alts[i].edesc->bEndpointAddress))
   2248 			continue;
   2249 		if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
   2250 			DPRINTFN(2,("uaudio_match_alt_sub: cont %d-%d\n",
   2251 				    UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
   2252 			if (UA_SAMP_LO(a1d) < rate && rate < UA_SAMP_HI(a1d))
   2253 				return i;
   2254 		} else {
   2255 			for (j = 0; j < a1d->bSamFreqType; j++) {
   2256 				DPRINTFN(2,("uaudio_match_alt_sub: disc #%d: %d\n",
   2257 					    j, UA_GETSAMP(a1d, j)));
   2258 				/* XXX allow for some slack */
   2259 				if (UA_GETSAMP(a1d, j) == rate)
   2260 					return i;
   2261 			}
   2262 		}
   2263 	}
   2264 	return -1;
   2265 }
   2266 
   2267 int
   2268 uaudio_match_alt_chan(int nalts, const struct as_info *alts,
   2269 		      struct audio_params *p, int mode)
   2270 {
   2271 	int i, n;
   2272 	u_long min, max;
   2273 	u_long rate;
   2274 
   2275 	/* Exact match */
   2276 	DPRINTF(("uaudio_match_alt_chan: examine %ldHz %dch %dbit.\n",
   2277 		 p->sample_rate, p->hw_channels, p->hw_precision));
   2278 	i = uaudio_match_alt_sub(nalts, alts, p, mode, p->sample_rate);
   2279 	if (i >= 0)
   2280 		return i;
   2281 
   2282 	uaudio_get_minmax_rates(nalts, alts, p, mode, &min, &max);
   2283 	DPRINTF(("uaudio_match_alt_chan: min=%lu max=%lu\n", min, max));
   2284 	if (max <= 0)
   2285 		return -1;
   2286 	/* Search for biggers */
   2287 	n = 2;
   2288 	while ((rate = p->sample_rate * n++) <= max) {
   2289 		i = uaudio_match_alt_sub(nalts, alts, p, mode, rate);
   2290 		if (i >= 0) {
   2291 			p->hw_sample_rate = rate;
   2292 			return i;
   2293 		}
   2294 	}
   2295 	if (p->sample_rate >= min) {
   2296 		i = uaudio_match_alt_sub(nalts, alts, p, mode, max);
   2297 		if (i >= 0) {
   2298 			p->hw_sample_rate = max;
   2299 			return i;
   2300 		}
   2301 	} else {
   2302 		i = uaudio_match_alt_sub(nalts, alts, p, mode, min);
   2303 		if (i >= 0) {
   2304 			p->hw_sample_rate = min;
   2305 			return i;
   2306 		}
   2307 	}
   2308 	return -1;
   2309 }
   2310 
   2311 int
   2312 uaudio_match_alt(int nalts, const struct as_info *alts,
   2313 		 struct audio_params *p, int mode)
   2314 {
   2315 	int i, n;
   2316 
   2317 	mode = mode == AUMODE_PLAY ? UE_DIR_OUT : UE_DIR_IN;
   2318 	i = uaudio_match_alt_chan(nalts, alts, p, mode);
   2319 	if (i >= 0)
   2320 		return i;
   2321 
   2322 	for (n = p->channels + 1; n <= AUDIO_MAX_CHANNELS; n++) {
   2323 		p->hw_channels = n;
   2324 		i = uaudio_match_alt_chan(nalts, alts, p, mode);
   2325 		if (i >= 0)
   2326 			return i;
   2327 	}
   2328 
   2329 	if (p->channels != 2)
   2330 		return -1;
   2331 	p->hw_channels = 1;
   2332 	return uaudio_match_alt_chan(nalts, alts, p, mode);
   2333 }
   2334 
   2335 int
   2336 uaudio_set_params(void *addr, int setmode, int usemode,
   2337 		  struct audio_params *play, struct audio_params *rec)
   2338 {
   2339 	struct uaudio_softc *sc = addr;
   2340 	int flags = sc->sc_altflags;
   2341 	int factor;
   2342 	int enc, i;
   2343 	int paltidx=-1, raltidx=-1;
   2344 	void (*swcode)(void *, u_char *buf, int cnt);
   2345 	struct audio_params *p;
   2346 	int mode;
   2347 
   2348 	if (sc->sc_dying)
   2349 		return (EIO);
   2350 
   2351 	if ((mode == AUMODE_RECORD && sc->sc_recchan.pipe != NULL)
   2352 	    || (mode == AUMODE_PLAY && sc->sc_playchan.pipe != NULL))
   2353 		return (EBUSY);
   2354 
   2355 	if (usemode & AUMODE_PLAY && sc->sc_playchan.altidx != -1)
   2356 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 0;
   2357 	if (usemode & AUMODE_RECORD && sc->sc_recchan.altidx != -1)
   2358 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 0;
   2359 
   2360 	for (mode = AUMODE_RECORD; mode != -1;
   2361 	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
   2362 		if ((setmode & mode) == 0)
   2363 			continue;
   2364 
   2365 		if ((sc->sc_mode & mode) == 0)
   2366 			continue;
   2367 
   2368 		p = (mode == AUMODE_PLAY) ? play : rec;
   2369 
   2370 		factor = 1;
   2371 		swcode = 0;
   2372 		enc = p->encoding;
   2373 		switch (enc) {
   2374 		case AUDIO_ENCODING_SLINEAR_BE:
   2375 			/* FALLTHROUGH */
   2376 		case AUDIO_ENCODING_SLINEAR_LE:
   2377 			if (enc == AUDIO_ENCODING_SLINEAR_BE
   2378 			    && p->precision == 16 && (flags & HAS_16)) {
   2379 				swcode = swap_bytes;
   2380 				enc = AUDIO_ENCODING_SLINEAR_LE;
   2381 			} else if (p->precision == 8) {
   2382 				if (flags & HAS_8) {
   2383 					/* No conversion */
   2384 				} else if (flags & HAS_8U) {
   2385 					swcode = change_sign8;
   2386 					enc = AUDIO_ENCODING_ULINEAR_LE;
   2387 				} else if (flags & HAS_16) {
   2388 					factor = 2;
   2389 					p->hw_precision = 16;
   2390 					if (mode == AUMODE_PLAY)
   2391 						swcode = linear8_to_linear16_le;
   2392 					else
   2393 						swcode = linear16_to_linear8_le;
   2394 				}
   2395 			}
   2396 			break;
   2397 		case AUDIO_ENCODING_ULINEAR_BE:
   2398 			/* FALLTHROUGH */
   2399 		case AUDIO_ENCODING_ULINEAR_LE:
   2400 			if (p->precision == 16) {
   2401 				if (enc == AUDIO_ENCODING_ULINEAR_LE)
   2402 					swcode = change_sign16_le;
   2403 				else if (mode == AUMODE_PLAY)
   2404 					swcode = swap_bytes_change_sign16_le;
   2405 				else
   2406 					swcode = change_sign16_swap_bytes_le;
   2407 				enc = AUDIO_ENCODING_SLINEAR_LE;
   2408 			} else if (p->precision == 8) {
   2409 				if (flags & HAS_8U) {
   2410 					/* No conversion */
   2411 				} else if (flags & HAS_8) {
   2412 					swcode = change_sign8;
   2413 					enc = AUDIO_ENCODING_SLINEAR_LE;
   2414 				} else if (flags & HAS_16) {
   2415 					factor = 2;
   2416 					p->hw_precision = 16;
   2417 					enc = AUDIO_ENCODING_SLINEAR_LE;
   2418 					if (mode == AUMODE_PLAY)
   2419 						swcode = ulinear8_to_slinear16_le;
   2420 					else
   2421 						swcode = slinear16_to_ulinear8_le;
   2422 				}
   2423 			}
   2424 			break;
   2425 		case AUDIO_ENCODING_ULAW:
   2426 			if (flags & HAS_MULAW)
   2427 				break;
   2428 			if (flags & HAS_16) {
   2429 				if (mode == AUMODE_PLAY)
   2430 					swcode = mulaw_to_slinear16_le;
   2431 				else
   2432 					swcode = slinear16_to_mulaw_le;
   2433 				factor = 2;
   2434 				enc = AUDIO_ENCODING_SLINEAR_LE;
   2435 				p->hw_precision = 16;
   2436 			} else if (flags & HAS_8U) {
   2437 				if (mode == AUMODE_PLAY)
   2438 					swcode = mulaw_to_ulinear8;
   2439 				else
   2440 					swcode = ulinear8_to_mulaw;
   2441 				enc = AUDIO_ENCODING_ULINEAR_LE;
   2442 			} else if (flags & HAS_8) {
   2443 				if (mode == AUMODE_PLAY)
   2444 					swcode = mulaw_to_slinear8;
   2445 				else
   2446 					swcode = slinear8_to_mulaw;
   2447 				enc = AUDIO_ENCODING_SLINEAR_LE;
   2448 			} else
   2449 				return (EINVAL);
   2450 			break;
   2451 		case AUDIO_ENCODING_ALAW:
   2452 			if (flags & HAS_ALAW)
   2453 				break;
   2454 			if (mode == AUMODE_PLAY && (flags & HAS_16)) {
   2455 				swcode = alaw_to_slinear16_le;
   2456 				factor = 2;
   2457 				enc = AUDIO_ENCODING_SLINEAR_LE;
   2458 				p->hw_precision = 16;
   2459 			} else if (flags & HAS_8U) {
   2460 				if (mode == AUMODE_PLAY)
   2461 					swcode = alaw_to_ulinear8;
   2462 				else
   2463 					swcode = ulinear8_to_alaw;
   2464 				enc = AUDIO_ENCODING_ULINEAR_LE;
   2465 			} else if (flags & HAS_8) {
   2466 				if (mode == AUMODE_PLAY)
   2467 					swcode = alaw_to_slinear8;
   2468 				else
   2469 					swcode = slinear8_to_alaw;
   2470 				enc = AUDIO_ENCODING_SLINEAR_LE;
   2471 			} else
   2472 				return (EINVAL);
   2473 			break;
   2474 		default:
   2475 			return (EINVAL);
   2476 		}
   2477 		/* XXX do some other conversions... */
   2478 
   2479 		DPRINTF(("uaudio_set_params: chan=%d prec=%d enc=%d rate=%ld\n",
   2480 			 p->channels, p->hw_precision, enc, p->sample_rate));
   2481 
   2482 		p->hw_encoding = enc;
   2483 		i = uaudio_match_alt(sc->sc_nalts, sc->sc_alts, p, mode);
   2484 		if (i < 0)
   2485 			return (EINVAL);
   2486 
   2487 		p->sw_code = swcode;
   2488 		p->factor  = factor;
   2489 		if (usemode & mode) {
   2490 			if (mode == AUMODE_PLAY) {
   2491 				paltidx = i;
   2492 				sc->sc_alts[i].sc_busy = 1;
   2493 			} else {
   2494 				raltidx = i;
   2495 				sc->sc_alts[i].sc_busy = 1;
   2496 			}
   2497 		}
   2498 	}
   2499 
   2500 	if ((usemode & AUMODE_PLAY) /*&& paltidx != sc->sc_playchan.altidx*/) {
   2501 		/* XXX abort transfer if currently happening? */
   2502 		uaudio_chan_init(&sc->sc_playchan, paltidx, play);
   2503 	}
   2504 	if ((usemode & AUMODE_RECORD) /*&& raltidx != sc->sc_recchan.altidx*/) {
   2505 		/* XXX abort transfer if currently happening? */
   2506 		uaudio_chan_init(&sc->sc_playchan, raltidx, play);
   2507 	}
   2508 
   2509 	DPRINTF(("uaudio_set_params: use altidx=p%d/r%d, altno=p%d/r%d\n",
   2510 		 sc->sc_playchan.altidx, sc->sc_recchan.altidx,
   2511 		 (sc->sc_playchan.altidx >= 0)
   2512 		   ?sc->sc_alts[sc->sc_playchan.altidx].idesc->bAlternateSetting
   2513 		   : -1,
   2514 		 (sc->sc_recchan.altidx >= 0)
   2515 		   ? sc->sc_alts[sc->sc_recchan.altidx].idesc->bAlternateSetting
   2516 		   : -1));
   2517 
   2518 	return (0);
   2519 }
   2520 
   2521 usbd_status
   2522 uaudio_set_speed(struct uaudio_softc *sc, int endpt, u_int speed)
   2523 {
   2524 	usb_device_request_t req;
   2525 	u_int8_t data[3];
   2526 
   2527 	DPRINTFN(5,("uaudio_set_speed: endpt=%d speed=%u\n", endpt, speed));
   2528 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
   2529 	req.bRequest = SET_CUR;
   2530 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
   2531 	USETW(req.wIndex, endpt);
   2532 	USETW(req.wLength, 3);
   2533 	data[0] = speed;
   2534 	data[1] = speed >> 8;
   2535 	data[2] = speed >> 16;
   2536 
   2537 	return (usbd_do_request(sc->sc_udev, &req, data));
   2538 }
   2539 
   2540