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