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