ALSA: usb-audio: refactor code
[linux-2.6.git] / sound / usb / usbmixer.c
1 /*
2  *   (Tentative) USB Audio Driver for ALSA
3  *
4  *   Mixer control part
5  *
6  *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
7  *
8  *   Many codes borrowed from audio.c by
9  *          Alan Cox (alan@lxorguk.ukuu.org.uk)
10  *          Thomas Sailer (sailer@ife.ee.ethz.ch)
11  *
12  *
13  *   This program is free software; you can redistribute it and/or modify
14  *   it under the terms of the GNU General Public License as published by
15  *   the Free Software Foundation; either version 2 of the License, or
16  *   (at your option) any later version.
17  *
18  *   This program is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with this program; if not, write to the Free Software
25  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
26  *
27  */
28
29 #include <linux/bitops.h>
30 #include <linux/init.h>
31 #include <linux/list.h>
32 #include <linux/slab.h>
33 #include <linux/string.h>
34 #include <linux/usb.h>
35 #include <linux/usb/audio.h>
36
37 #include <sound/core.h>
38 #include <sound/control.h>
39 #include <sound/hwdep.h>
40 #include <sound/info.h>
41 #include <sound/tlv.h>
42
43 #include "usbaudio.h"
44 #include "usbmixer.h"
45 #include "helper.h"
46
47 /*
48  */
49
50 /* ignore error from controls - for debugging */
51 /* #define IGNORE_CTL_ERROR */
52
53 /*
54  * Sound Blaster remote control configuration
55  *
56  * format of remote control data:
57  * Extigy:       xx 00
58  * Audigy 2 NX:  06 80 xx 00 00 00
59  * Live! 24-bit: 06 80 xx yy 22 83
60  */
61 static const struct rc_config {
62         u32 usb_id;
63         u8  offset;
64         u8  length;
65         u8  packet_length;
66         u8  min_packet_length; /* minimum accepted length of the URB result */
67         u8  mute_mixer_id;
68         u32 mute_code;
69 } rc_configs[] = {
70         { USB_ID(0x041e, 0x3000), 0, 1, 2, 1,  18, 0x0013 }, /* Extigy       */
71         { USB_ID(0x041e, 0x3020), 2, 1, 6, 6,  18, 0x0013 }, /* Audigy 2 NX  */
72         { USB_ID(0x041e, 0x3040), 2, 2, 6, 6,  2,  0x6e91 }, /* Live! 24-bit */
73         { USB_ID(0x041e, 0x3048), 2, 2, 6, 6,  2,  0x6e91 }, /* Toshiba SB0500 */
74 };
75
76 #define MAX_ID_ELEMS    256
77
78 struct usb_mixer_interface {
79         struct snd_usb_audio *chip;
80         unsigned int ctrlif;
81         struct list_head list;
82         unsigned int ignore_ctl_error;
83         struct urb *urb;
84         /* array[MAX_ID_ELEMS], indexed by unit id */
85         struct usb_mixer_elem_info **id_elems;
86
87         /* Sound Blaster remote control stuff */
88         const struct rc_config *rc_cfg;
89         u32 rc_code;
90         wait_queue_head_t rc_waitq;
91         struct urb *rc_urb;
92         struct usb_ctrlrequest *rc_setup_packet;
93         u8 rc_buffer[6];
94
95         u8 audigy2nx_leds[3];
96         u8 xonar_u1_status;
97 };
98
99
100 struct usb_audio_term {
101         int id;
102         int type;
103         int channels;
104         unsigned int chconfig;
105         int name;
106 };
107
108 struct usbmix_name_map;
109
110 struct mixer_build {
111         struct snd_usb_audio *chip;
112         struct usb_mixer_interface *mixer;
113         unsigned char *buffer;
114         unsigned int buflen;
115         DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS);
116         struct usb_audio_term oterm;
117         const struct usbmix_name_map *map;
118         const struct usbmix_selector_map *selector_map;
119 };
120
121 #define MAX_CHANNELS    10      /* max logical channels */
122
123 struct usb_mixer_elem_info {
124         struct usb_mixer_interface *mixer;
125         struct usb_mixer_elem_info *next_id_elem; /* list of controls with same id */
126         struct snd_ctl_elem_id *elem_id;
127         unsigned int id;
128         unsigned int control;   /* CS or ICN (high byte) */
129         unsigned int cmask; /* channel mask bitmap: 0 = master */
130         int channels;
131         int val_type;
132         int min, max, res;
133         int dBmin, dBmax;
134         int cached;
135         int cache_val[MAX_CHANNELS];
136         u8 initialized;
137 };
138
139
140 enum {
141         USB_FEATURE_NONE = 0,
142         USB_FEATURE_MUTE = 1,
143         USB_FEATURE_VOLUME,
144         USB_FEATURE_BASS,
145         USB_FEATURE_MID,
146         USB_FEATURE_TREBLE,
147         USB_FEATURE_GEQ,
148         USB_FEATURE_AGC,
149         USB_FEATURE_DELAY,
150         USB_FEATURE_BASSBOOST,
151         USB_FEATURE_LOUDNESS
152 };
153
154 enum {
155         USB_MIXER_BOOLEAN,
156         USB_MIXER_INV_BOOLEAN,
157         USB_MIXER_S8,
158         USB_MIXER_U8,
159         USB_MIXER_S16,
160         USB_MIXER_U16,
161 };
162
163 enum {
164         USB_PROC_UPDOWN = 1,
165         USB_PROC_UPDOWN_SWITCH = 1,
166         USB_PROC_UPDOWN_MODE_SEL = 2,
167
168         USB_PROC_PROLOGIC = 2,
169         USB_PROC_PROLOGIC_SWITCH = 1,
170         USB_PROC_PROLOGIC_MODE_SEL = 2,
171
172         USB_PROC_3DENH = 3,
173         USB_PROC_3DENH_SWITCH = 1,
174         USB_PROC_3DENH_SPACE = 2,
175
176         USB_PROC_REVERB = 4,
177         USB_PROC_REVERB_SWITCH = 1,
178         USB_PROC_REVERB_LEVEL = 2,
179         USB_PROC_REVERB_TIME = 3,
180         USB_PROC_REVERB_DELAY = 4,
181
182         USB_PROC_CHORUS = 5,
183         USB_PROC_CHORUS_SWITCH = 1,
184         USB_PROC_CHORUS_LEVEL = 2,
185         USB_PROC_CHORUS_RATE = 3,
186         USB_PROC_CHORUS_DEPTH = 4,
187
188         USB_PROC_DCR = 6,
189         USB_PROC_DCR_SWITCH = 1,
190         USB_PROC_DCR_RATIO = 2,
191         USB_PROC_DCR_MAX_AMP = 3,
192         USB_PROC_DCR_THRESHOLD = 4,
193         USB_PROC_DCR_ATTACK = 5,
194         USB_PROC_DCR_RELEASE = 6,
195 };
196
197 /*E-mu 0202(0404) eXtension Unit(XU) control*/
198 enum {
199         USB_XU_CLOCK_RATE               = 0xe301,
200         USB_XU_CLOCK_SOURCE             = 0xe302,
201         USB_XU_DIGITAL_IO_STATUS        = 0xe303,
202         USB_XU_DEVICE_OPTIONS           = 0xe304,
203         USB_XU_DIRECT_MONITORING        = 0xe305,
204         USB_XU_METERING                 = 0xe306
205 };
206 enum {
207         USB_XU_CLOCK_SOURCE_SELECTOR = 0x02,    /* clock source*/
208         USB_XU_CLOCK_RATE_SELECTOR = 0x03,      /* clock rate */
209         USB_XU_DIGITAL_FORMAT_SELECTOR = 0x01,  /* the spdif format */
210         USB_XU_SOFT_LIMIT_SELECTOR = 0x03       /* soft limiter */
211 };
212
213 /*
214  * manual mapping of mixer names
215  * if the mixer topology is too complicated and the parsed names are
216  * ambiguous, add the entries in usbmixer_maps.c.
217  */
218 #include "usbmixer_maps.c"
219
220 static const struct usbmix_name_map *
221 find_map(struct mixer_build *state, int unitid, int control)
222 {
223         const struct usbmix_name_map *p = state->map;
224
225         if (!p)
226                 return NULL;
227
228         for (p = state->map; p->id; p++) {
229                 if (p->id == unitid &&
230                     (!control || !p->control || control == p->control))
231                         return p;
232         }
233         return NULL;
234 }
235
236 /* get the mapped name if the unit matches */
237 static int
238 check_mapped_name(const struct usbmix_name_map *p, char *buf, int buflen)
239 {
240         if (!p || !p->name)
241                 return 0;
242
243         buflen--;
244         return strlcpy(buf, p->name, buflen);
245 }
246
247 /* check whether the control should be ignored */
248 static inline int
249 check_ignored_ctl(const struct usbmix_name_map *p)
250 {
251         if (!p || p->name || p->dB)
252                 return 0;
253         return 1;
254 }
255
256 /* dB mapping */
257 static inline void check_mapped_dB(const struct usbmix_name_map *p,
258                                    struct usb_mixer_elem_info *cval)
259 {
260         if (p && p->dB) {
261                 cval->dBmin = p->dB->min;
262                 cval->dBmax = p->dB->max;
263         }
264 }
265
266 /* get the mapped selector source name */
267 static int check_mapped_selector_name(struct mixer_build *state, int unitid,
268                                       int index, char *buf, int buflen)
269 {
270         const struct usbmix_selector_map *p;
271
272         if (! state->selector_map)
273                 return 0;
274         for (p = state->selector_map; p->id; p++) {
275                 if (p->id == unitid && index < p->count)
276                         return strlcpy(buf, p->names[index], buflen);
277         }
278         return 0;
279 }
280
281 /*
282  * find an audio control unit with the given unit id
283  */
284 static void *find_audio_control_unit(struct mixer_build *state, unsigned char unit)
285 {
286         unsigned char *p;
287
288         p = NULL;
289         while ((p = snd_usb_find_desc(state->buffer, state->buflen, p,
290                                       USB_DT_CS_INTERFACE)) != NULL) {
291                 if (p[0] >= 4 && p[2] >= UAC_INPUT_TERMINAL && p[2] <= UAC_EXTENSION_UNIT_V1 && p[3] == unit)
292                         return p;
293         }
294         return NULL;
295 }
296
297
298 /*
299  * copy a string with the given id
300  */
301 static int snd_usb_copy_string_desc(struct mixer_build *state, int index, char *buf, int maxlen)
302 {
303         int len = usb_string(state->chip->dev, index, buf, maxlen - 1);
304         buf[len] = 0;
305         return len;
306 }
307
308 /*
309  * convert from the byte/word on usb descriptor to the zero-based integer
310  */
311 static int convert_signed_value(struct usb_mixer_elem_info *cval, int val)
312 {
313         switch (cval->val_type) {
314         case USB_MIXER_BOOLEAN:
315                 return !!val;
316         case USB_MIXER_INV_BOOLEAN:
317                 return !val;
318         case USB_MIXER_U8:
319                 val &= 0xff;
320                 break;
321         case USB_MIXER_S8:
322                 val &= 0xff;
323                 if (val >= 0x80)
324                         val -= 0x100;
325                 break;
326         case USB_MIXER_U16:
327                 val &= 0xffff;
328                 break;
329         case USB_MIXER_S16:
330                 val &= 0xffff;
331                 if (val >= 0x8000)
332                         val -= 0x10000;
333                 break;
334         }
335         return val;
336 }
337
338 /*
339  * convert from the zero-based int to the byte/word for usb descriptor
340  */
341 static int convert_bytes_value(struct usb_mixer_elem_info *cval, int val)
342 {
343         switch (cval->val_type) {
344         case USB_MIXER_BOOLEAN:
345                 return !!val;
346         case USB_MIXER_INV_BOOLEAN:
347                 return !val;
348         case USB_MIXER_S8:
349         case USB_MIXER_U8:
350                 return val & 0xff;
351         case USB_MIXER_S16:
352         case USB_MIXER_U16:
353                 return val & 0xffff;
354         }
355         return 0; /* not reached */
356 }
357
358 static int get_relative_value(struct usb_mixer_elem_info *cval, int val)
359 {
360         if (! cval->res)
361                 cval->res = 1;
362         if (val < cval->min)
363                 return 0;
364         else if (val >= cval->max)
365                 return (cval->max - cval->min + cval->res - 1) / cval->res;
366         else
367                 return (val - cval->min) / cval->res;
368 }
369
370 static int get_abs_value(struct usb_mixer_elem_info *cval, int val)
371 {
372         if (val < 0)
373                 return cval->min;
374         if (! cval->res)
375                 cval->res = 1;
376         val *= cval->res;
377         val += cval->min;
378         if (val > cval->max)
379                 return cval->max;
380         return val;
381 }
382
383
384 /*
385  * retrieve a mixer value
386  */
387
388 static int get_ctl_value(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
389 {
390         unsigned char buf[2];
391         int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
392         int timeout = 10;
393
394         while (timeout-- > 0) {
395                 if (snd_usb_ctl_msg(cval->mixer->chip->dev,
396                                     usb_rcvctrlpipe(cval->mixer->chip->dev, 0),
397                                     request,
398                                     USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
399                                     validx, cval->mixer->ctrlif | (cval->id << 8),
400                                     buf, val_len, 100) >= val_len) {
401                         *value_ret = convert_signed_value(cval, snd_usb_combine_bytes(buf, val_len));
402                         return 0;
403                 }
404         }
405         snd_printdd(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
406                     request, validx, cval->mixer->ctrlif | (cval->id << 8), cval->val_type);
407         return -EINVAL;
408 }
409
410 static int get_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int *value)
411 {
412         return get_ctl_value(cval, UAC_GET_CUR, validx, value);
413 }
414
415 /* channel = 0: master, 1 = first channel */
416 static inline int get_cur_mix_raw(struct usb_mixer_elem_info *cval,
417                                   int channel, int *value)
418 {
419         return get_ctl_value(cval, UAC_GET_CUR, (cval->control << 8) | channel, value);
420 }
421
422 static int get_cur_mix_value(struct usb_mixer_elem_info *cval,
423                              int channel, int index, int *value)
424 {
425         int err;
426
427         if (cval->cached & (1 << channel)) {
428                 *value = cval->cache_val[index];
429                 return 0;
430         }
431         err = get_cur_mix_raw(cval, channel, value);
432         if (err < 0) {
433                 if (!cval->mixer->ignore_ctl_error)
434                         snd_printd(KERN_ERR "cannot get current value for "
435                                    "control %d ch %d: err = %d\n",
436                                    cval->control, channel, err);
437                 return err;
438         }
439         cval->cached |= 1 << channel;
440         cval->cache_val[index] = *value;
441         return 0;
442 }
443
444
445 /*
446  * set a mixer value
447  */
448
449 static int set_ctl_value(struct usb_mixer_elem_info *cval, int request, int validx, int value_set)
450 {
451         unsigned char buf[2];
452         int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
453         int timeout = 10;
454
455         value_set = convert_bytes_value(cval, value_set);
456         buf[0] = value_set & 0xff;
457         buf[1] = (value_set >> 8) & 0xff;
458         while (timeout-- > 0)
459                 if (snd_usb_ctl_msg(cval->mixer->chip->dev,
460                                     usb_sndctrlpipe(cval->mixer->chip->dev, 0),
461                                     request,
462                                     USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
463                                     validx, cval->mixer->ctrlif | (cval->id << 8),
464                                     buf, val_len, 100) >= 0)
465                         return 0;
466         snd_printdd(KERN_ERR "cannot set ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d, data = %#x/%#x\n",
467                     request, validx, cval->mixer->ctrlif | (cval->id << 8), cval->val_type, buf[0], buf[1]);
468         return -EINVAL;
469 }
470
471 static int set_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int value)
472 {
473         return set_ctl_value(cval, UAC_SET_CUR, validx, value);
474 }
475
476 static int set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel,
477                              int index, int value)
478 {
479         int err;
480         err = set_ctl_value(cval, UAC_SET_CUR, (cval->control << 8) | channel,
481                             value);
482         if (err < 0)
483                 return err;
484         cval->cached |= 1 << channel;
485         cval->cache_val[index] = value;
486         return 0;
487 }
488
489 /*
490  * TLV callback for mixer volume controls
491  */
492 static int mixer_vol_tlv(struct snd_kcontrol *kcontrol, int op_flag,
493                          unsigned int size, unsigned int __user *_tlv)
494 {
495         struct usb_mixer_elem_info *cval = kcontrol->private_data;
496         DECLARE_TLV_DB_MINMAX(scale, 0, 0);
497
498         if (size < sizeof(scale))
499                 return -ENOMEM;
500         scale[2] = cval->dBmin;
501         scale[3] = cval->dBmax;
502         if (copy_to_user(_tlv, scale, sizeof(scale)))
503                 return -EFAULT;
504         return 0;
505 }
506
507 /*
508  * parser routines begin here...
509  */
510
511 static int parse_audio_unit(struct mixer_build *state, int unitid);
512
513
514 /*
515  * check if the input/output channel routing is enabled on the given bitmap.
516  * used for mixer unit parser
517  */
518 static int check_matrix_bitmap(unsigned char *bmap, int ich, int och, int num_outs)
519 {
520         int idx = ich * num_outs + och;
521         return bmap[idx >> 3] & (0x80 >> (idx & 7));
522 }
523
524
525 /*
526  * add an alsa control element
527  * search and increment the index until an empty slot is found.
528  *
529  * if failed, give up and free the control instance.
530  */
531
532 static int add_control_to_empty(struct mixer_build *state, struct snd_kcontrol *kctl)
533 {
534         struct usb_mixer_elem_info *cval = kctl->private_data;
535         int err;
536
537         while (snd_ctl_find_id(state->chip->card, &kctl->id))
538                 kctl->id.index++;
539         if ((err = snd_ctl_add(state->chip->card, kctl)) < 0) {
540                 snd_printd(KERN_ERR "cannot add control (err = %d)\n", err);
541                 return err;
542         }
543         cval->elem_id = &kctl->id;
544         cval->next_id_elem = state->mixer->id_elems[cval->id];
545         state->mixer->id_elems[cval->id] = cval;
546         return 0;
547 }
548
549
550 /*
551  * get a terminal name string
552  */
553
554 static struct iterm_name_combo {
555         int type;
556         char *name;
557 } iterm_names[] = {
558         { 0x0300, "Output" },
559         { 0x0301, "Speaker" },
560         { 0x0302, "Headphone" },
561         { 0x0303, "HMD Audio" },
562         { 0x0304, "Desktop Speaker" },
563         { 0x0305, "Room Speaker" },
564         { 0x0306, "Com Speaker" },
565         { 0x0307, "LFE" },
566         { 0x0600, "External In" },
567         { 0x0601, "Analog In" },
568         { 0x0602, "Digital In" },
569         { 0x0603, "Line" },
570         { 0x0604, "Legacy In" },
571         { 0x0605, "IEC958 In" },
572         { 0x0606, "1394 DA Stream" },
573         { 0x0607, "1394 DV Stream" },
574         { 0x0700, "Embedded" },
575         { 0x0701, "Noise Source" },
576         { 0x0702, "Equalization Noise" },
577         { 0x0703, "CD" },
578         { 0x0704, "DAT" },
579         { 0x0705, "DCC" },
580         { 0x0706, "MiniDisk" },
581         { 0x0707, "Analog Tape" },
582         { 0x0708, "Phonograph" },
583         { 0x0709, "VCR Audio" },
584         { 0x070a, "Video Disk Audio" },
585         { 0x070b, "DVD Audio" },
586         { 0x070c, "TV Tuner Audio" },
587         { 0x070d, "Satellite Rec Audio" },
588         { 0x070e, "Cable Tuner Audio" },
589         { 0x070f, "DSS Audio" },
590         { 0x0710, "Radio Receiver" },
591         { 0x0711, "Radio Transmitter" },
592         { 0x0712, "Multi-Track Recorder" },
593         { 0x0713, "Synthesizer" },
594         { 0 },
595 };
596
597 static int get_term_name(struct mixer_build *state, struct usb_audio_term *iterm,
598                          unsigned char *name, int maxlen, int term_only)
599 {
600         struct iterm_name_combo *names;
601
602         if (iterm->name)
603                 return snd_usb_copy_string_desc(state, iterm->name, name, maxlen);
604
605         /* virtual type - not a real terminal */
606         if (iterm->type >> 16) {
607                 if (term_only)
608                         return 0;
609                 switch (iterm->type >> 16) {
610                 case UAC_SELECTOR_UNIT:
611                         strcpy(name, "Selector"); return 8;
612                 case UAC_PROCESSING_UNIT_V1:
613                         strcpy(name, "Process Unit"); return 12;
614                 case UAC_EXTENSION_UNIT_V1:
615                         strcpy(name, "Ext Unit"); return 8;
616                 case UAC_MIXER_UNIT:
617                         strcpy(name, "Mixer"); return 5;
618                 default:
619                         return sprintf(name, "Unit %d", iterm->id);
620                 }
621         }
622
623         switch (iterm->type & 0xff00) {
624         case 0x0100:
625                 strcpy(name, "PCM"); return 3;
626         case 0x0200:
627                 strcpy(name, "Mic"); return 3;
628         case 0x0400:
629                 strcpy(name, "Headset"); return 7;
630         case 0x0500:
631                 strcpy(name, "Phone"); return 5;
632         }
633
634         for (names = iterm_names; names->type; names++)
635                 if (names->type == iterm->type) {
636                         strcpy(name, names->name);
637                         return strlen(names->name);
638                 }
639         return 0;
640 }
641
642
643 /*
644  * parse the source unit recursively until it reaches to a terminal
645  * or a branched unit.
646  */
647 static int check_input_term(struct mixer_build *state, int id, struct usb_audio_term *term)
648 {
649         unsigned char *p1;
650
651         memset(term, 0, sizeof(*term));
652         while ((p1 = find_audio_control_unit(state, id)) != NULL) {
653                 term->id = id;
654                 switch (p1[2]) {
655                 case UAC_INPUT_TERMINAL:
656                         term->type = combine_word(p1 + 4);
657                         term->channels = p1[7];
658                         term->chconfig = combine_word(p1 + 8);
659                         term->name = p1[11];
660                         return 0;
661                 case UAC_FEATURE_UNIT:
662                         id = p1[4];
663                         break; /* continue to parse */
664                 case UAC_MIXER_UNIT:
665                         term->type = p1[2] << 16; /* virtual type */
666                         term->channels = p1[5 + p1[4]];
667                         term->chconfig = combine_word(p1 + 6 + p1[4]);
668                         term->name = p1[p1[0] - 1];
669                         return 0;
670                 case UAC_SELECTOR_UNIT:
671                         /* call recursively to retrieve the channel info */
672                         if (check_input_term(state, p1[5], term) < 0)
673                                 return -ENODEV;
674                         term->type = p1[2] << 16; /* virtual type */
675                         term->id = id;
676                         term->name = p1[9 + p1[0] - 1];
677                         return 0;
678                 case UAC_PROCESSING_UNIT_V1:
679                 case UAC_EXTENSION_UNIT_V1:
680                         if (p1[6] == 1) {
681                                 id = p1[7];
682                                 break; /* continue to parse */
683                         }
684                         term->type = p1[2] << 16; /* virtual type */
685                         term->channels = p1[7 + p1[6]];
686                         term->chconfig = combine_word(p1 + 8 + p1[6]);
687                         term->name = p1[12 + p1[6] + p1[11 + p1[6]]];
688                         return 0;
689                 default:
690                         return -ENODEV;
691                 }
692         }
693         return -ENODEV;
694 }
695
696
697 /*
698  * Feature Unit
699  */
700
701 /* feature unit control information */
702 struct usb_feature_control_info {
703         const char *name;
704         unsigned int type;      /* control type (mute, volume, etc.) */
705 };
706
707 static struct usb_feature_control_info audio_feature_info[] = {
708         { "Mute",               USB_MIXER_INV_BOOLEAN },
709         { "Volume",             USB_MIXER_S16 },
710         { "Tone Control - Bass",        USB_MIXER_S8 },
711         { "Tone Control - Mid",         USB_MIXER_S8 },
712         { "Tone Control - Treble",      USB_MIXER_S8 },
713         { "Graphic Equalizer",          USB_MIXER_S8 }, /* FIXME: not implemeted yet */
714         { "Auto Gain Control",  USB_MIXER_BOOLEAN },
715         { "Delay Control",      USB_MIXER_U16 },
716         { "Bass Boost",         USB_MIXER_BOOLEAN },
717         { "Loudness",           USB_MIXER_BOOLEAN },
718 };
719
720
721 /* private_free callback */
722 static void usb_mixer_elem_free(struct snd_kcontrol *kctl)
723 {
724         kfree(kctl->private_data);
725         kctl->private_data = NULL;
726 }
727
728
729 /*
730  * interface to ALSA control for feature/mixer units
731  */
732
733 /*
734  * retrieve the minimum and maximum values for the specified control
735  */
736 static int get_min_max(struct usb_mixer_elem_info *cval, int default_min)
737 {
738         /* for failsafe */
739         cval->min = default_min;
740         cval->max = cval->min + 1;
741         cval->res = 1;
742         cval->dBmin = cval->dBmax = 0;
743
744         if (cval->val_type == USB_MIXER_BOOLEAN ||
745             cval->val_type == USB_MIXER_INV_BOOLEAN) {
746                 cval->initialized = 1;
747         } else {
748                 int minchn = 0;
749                 if (cval->cmask) {
750                         int i;
751                         for (i = 0; i < MAX_CHANNELS; i++)
752                                 if (cval->cmask & (1 << i)) {
753                                         minchn = i + 1;
754                                         break;
755                                 }
756                 }
757                 if (get_ctl_value(cval, UAC_GET_MAX, (cval->control << 8) | minchn, &cval->max) < 0 ||
758                     get_ctl_value(cval, UAC_GET_MIN, (cval->control << 8) | minchn, &cval->min) < 0) {
759                         snd_printd(KERN_ERR "%d:%d: cannot get min/max values for control %d (id %d)\n",
760                                    cval->id, cval->mixer->ctrlif, cval->control, cval->id);
761                         return -EINVAL;
762                 }
763                 if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0) {
764                         cval->res = 1;
765                 } else {
766                         int last_valid_res = cval->res;
767
768                         while (cval->res > 1) {
769                                 if (set_ctl_value(cval, UAC_SET_RES, (cval->control << 8) | minchn, cval->res / 2) < 0)
770                                         break;
771                                 cval->res /= 2;
772                         }
773                         if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0)
774                                 cval->res = last_valid_res;
775                 }
776                 if (cval->res == 0)
777                         cval->res = 1;
778
779                 /* Additional checks for the proper resolution
780                  *
781                  * Some devices report smaller resolutions than actually
782                  * reacting.  They don't return errors but simply clip
783                  * to the lower aligned value.
784                  */
785                 if (cval->min + cval->res < cval->max) {
786                         int last_valid_res = cval->res;
787                         int saved, test, check;
788                         get_cur_mix_raw(cval, minchn, &saved);
789                         for (;;) {
790                                 test = saved;
791                                 if (test < cval->max)
792                                         test += cval->res;
793                                 else
794                                         test -= cval->res;
795                                 if (test < cval->min || test > cval->max ||
796                                     set_cur_mix_value(cval, minchn, 0, test) ||
797                                     get_cur_mix_raw(cval, minchn, &check)) {
798                                         cval->res = last_valid_res;
799                                         break;
800                                 }
801                                 if (test == check)
802                                         break;
803                                 cval->res *= 2;
804                         }
805                         set_cur_mix_value(cval, minchn, 0, saved);
806                 }
807
808                 cval->initialized = 1;
809         }
810
811         /* USB descriptions contain the dB scale in 1/256 dB unit
812          * while ALSA TLV contains in 1/100 dB unit
813          */
814         cval->dBmin = (convert_signed_value(cval, cval->min) * 100) / 256;
815         cval->dBmax = (convert_signed_value(cval, cval->max) * 100) / 256;
816         if (cval->dBmin > cval->dBmax) {
817                 /* something is wrong; assume it's either from/to 0dB */
818                 if (cval->dBmin < 0)
819                         cval->dBmax = 0;
820                 else if (cval->dBmin > 0)
821                         cval->dBmin = 0;
822                 if (cval->dBmin > cval->dBmax) {
823                         /* totally crap, return an error */
824                         return -EINVAL;
825                 }
826         }
827
828         return 0;
829 }
830
831
832 /* get a feature/mixer unit info */
833 static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
834 {
835         struct usb_mixer_elem_info *cval = kcontrol->private_data;
836
837         if (cval->val_type == USB_MIXER_BOOLEAN ||
838             cval->val_type == USB_MIXER_INV_BOOLEAN)
839                 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
840         else
841                 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
842         uinfo->count = cval->channels;
843         if (cval->val_type == USB_MIXER_BOOLEAN ||
844             cval->val_type == USB_MIXER_INV_BOOLEAN) {
845                 uinfo->value.integer.min = 0;
846                 uinfo->value.integer.max = 1;
847         } else {
848                 if (! cval->initialized)
849                         get_min_max(cval,  0);
850                 uinfo->value.integer.min = 0;
851                 uinfo->value.integer.max =
852                         (cval->max - cval->min + cval->res - 1) / cval->res;
853         }
854         return 0;
855 }
856
857 /* get the current value from feature/mixer unit */
858 static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
859 {
860         struct usb_mixer_elem_info *cval = kcontrol->private_data;
861         int c, cnt, val, err;
862
863         ucontrol->value.integer.value[0] = cval->min;
864         if (cval->cmask) {
865                 cnt = 0;
866                 for (c = 0; c < MAX_CHANNELS; c++) {
867                         if (!(cval->cmask & (1 << c)))
868                                 continue;
869                         err = get_cur_mix_value(cval, c + 1, cnt, &val);
870                         if (err < 0)
871                                 return cval->mixer->ignore_ctl_error ? 0 : err;
872                         val = get_relative_value(cval, val);
873                         ucontrol->value.integer.value[cnt] = val;
874                         cnt++;
875                 }
876                 return 0;
877         } else {
878                 /* master channel */
879                 err = get_cur_mix_value(cval, 0, 0, &val);
880                 if (err < 0)
881                         return cval->mixer->ignore_ctl_error ? 0 : err;
882                 val = get_relative_value(cval, val);
883                 ucontrol->value.integer.value[0] = val;
884         }
885         return 0;
886 }
887
888 /* put the current value to feature/mixer unit */
889 static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
890 {
891         struct usb_mixer_elem_info *cval = kcontrol->private_data;
892         int c, cnt, val, oval, err;
893         int changed = 0;
894
895         if (cval->cmask) {
896                 cnt = 0;
897                 for (c = 0; c < MAX_CHANNELS; c++) {
898                         if (!(cval->cmask & (1 << c)))
899                                 continue;
900                         err = get_cur_mix_value(cval, c + 1, cnt, &oval);
901                         if (err < 0)
902                                 return cval->mixer->ignore_ctl_error ? 0 : err;
903                         val = ucontrol->value.integer.value[cnt];
904                         val = get_abs_value(cval, val);
905                         if (oval != val) {
906                                 set_cur_mix_value(cval, c + 1, cnt, val);
907                                 changed = 1;
908                         }
909                         cnt++;
910                 }
911         } else {
912                 /* master channel */
913                 err = get_cur_mix_value(cval, 0, 0, &oval);
914                 if (err < 0)
915                         return cval->mixer->ignore_ctl_error ? 0 : err;
916                 val = ucontrol->value.integer.value[0];
917                 val = get_abs_value(cval, val);
918                 if (val != oval) {
919                         set_cur_mix_value(cval, 0, 0, val);
920                         changed = 1;
921                 }
922         }
923         return changed;
924 }
925
926 static struct snd_kcontrol_new usb_feature_unit_ctl = {
927         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
928         .name = "", /* will be filled later manually */
929         .info = mixer_ctl_feature_info,
930         .get = mixer_ctl_feature_get,
931         .put = mixer_ctl_feature_put,
932 };
933
934
935 /*
936  * build a feature control
937  */
938
939 static size_t append_ctl_name(struct snd_kcontrol *kctl, const char *str)
940 {
941         return strlcat(kctl->id.name, str, sizeof(kctl->id.name));
942 }
943
944 static void build_feature_ctl(struct mixer_build *state, unsigned char *desc,
945                               unsigned int ctl_mask, int control,
946                               struct usb_audio_term *iterm, int unitid)
947 {
948         unsigned int len = 0;
949         int mapped_name = 0;
950         int nameid = desc[desc[0] - 1];
951         struct snd_kcontrol *kctl;
952         struct usb_mixer_elem_info *cval;
953         const struct usbmix_name_map *map;
954
955         control++; /* change from zero-based to 1-based value */
956
957         if (control == USB_FEATURE_GEQ) {
958                 /* FIXME: not supported yet */
959                 return;
960         }
961
962         map = find_map(state, unitid, control);
963         if (check_ignored_ctl(map))
964                 return;
965
966         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
967         if (! cval) {
968                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
969                 return;
970         }
971         cval->mixer = state->mixer;
972         cval->id = unitid;
973         cval->control = control;
974         cval->cmask = ctl_mask;
975         cval->val_type = audio_feature_info[control-1].type;
976         if (ctl_mask == 0)
977                 cval->channels = 1;     /* master channel */
978         else {
979                 int i, c = 0;
980                 for (i = 0; i < 16; i++)
981                         if (ctl_mask & (1 << i))
982                                 c++;
983                 cval->channels = c;
984         }
985
986         /* get min/max values */
987         get_min_max(cval, 0);
988
989         kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
990         if (! kctl) {
991                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
992                 kfree(cval);
993                 return;
994         }
995         kctl->private_free = usb_mixer_elem_free;
996
997         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
998         mapped_name = len != 0;
999         if (! len && nameid)
1000                 len = snd_usb_copy_string_desc(state, nameid,
1001                                 kctl->id.name, sizeof(kctl->id.name));
1002
1003         switch (control) {
1004         case USB_FEATURE_MUTE:
1005         case USB_FEATURE_VOLUME:
1006                 /* determine the control name.  the rule is:
1007                  * - if a name id is given in descriptor, use it.
1008                  * - if the connected input can be determined, then use the name
1009                  *   of terminal type.
1010                  * - if the connected output can be determined, use it.
1011                  * - otherwise, anonymous name.
1012                  */
1013                 if (! len) {
1014                         len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 1);
1015                         if (! len)
1016                                 len = get_term_name(state, &state->oterm, kctl->id.name, sizeof(kctl->id.name), 1);
1017                         if (! len)
1018                                 len = snprintf(kctl->id.name, sizeof(kctl->id.name),
1019                                                "Feature %d", unitid);
1020                 }
1021                 /* determine the stream direction:
1022                  * if the connected output is USB stream, then it's likely a
1023                  * capture stream.  otherwise it should be playback (hopefully :)
1024                  */
1025                 if (! mapped_name && ! (state->oterm.type >> 16)) {
1026                         if ((state->oterm.type & 0xff00) == 0x0100) {
1027                                 len = append_ctl_name(kctl, " Capture");
1028                         } else {
1029                                 len = append_ctl_name(kctl, " Playback");
1030                         }
1031                 }
1032                 append_ctl_name(kctl, control == USB_FEATURE_MUTE ?
1033                                 " Switch" : " Volume");
1034                 if (control == USB_FEATURE_VOLUME) {
1035                         kctl->tlv.c = mixer_vol_tlv;
1036                         kctl->vd[0].access |= 
1037                                 SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1038                                 SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1039                         check_mapped_dB(map, cval);
1040                 }
1041                 break;
1042
1043         default:
1044                 if (! len)
1045                         strlcpy(kctl->id.name, audio_feature_info[control-1].name,
1046                                 sizeof(kctl->id.name));
1047                 break;
1048         }
1049
1050         /* volume control quirks */
1051         switch (state->chip->usb_id) {
1052         case USB_ID(0x0471, 0x0101):
1053         case USB_ID(0x0471, 0x0104):
1054         case USB_ID(0x0471, 0x0105):
1055         case USB_ID(0x0672, 0x1041):
1056         /* quirk for UDA1321/N101.
1057          * note that detection between firmware 2.1.1.7 (N101)
1058          * and later 2.1.1.21 is not very clear from datasheets.
1059          * I hope that the min value is -15360 for newer firmware --jk
1060          */
1061                 if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
1062                     cval->min == -15616) {
1063                         snd_printk(KERN_INFO
1064                                  "set volume quirk for UDA1321/N101 chip\n");
1065                         cval->max = -256;
1066                 }
1067                 break;
1068
1069         case USB_ID(0x046d, 0x09a4):
1070                 if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1071                         snd_printk(KERN_INFO
1072                                 "set volume quirk for QuickCam E3500\n");
1073                         cval->min = 6080;
1074                         cval->max = 8768;
1075                         cval->res = 192;
1076                 }
1077                 break;
1078
1079         }
1080
1081         snd_printdd(KERN_INFO "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
1082                     cval->id, kctl->id.name, cval->channels, cval->min, cval->max, cval->res);
1083         add_control_to_empty(state, kctl);
1084 }
1085
1086
1087
1088 /*
1089  * parse a feature unit
1090  *
1091  * most of controlls are defined here.
1092  */
1093 static int parse_audio_feature_unit(struct mixer_build *state, int unitid, void *_ftr)
1094 {
1095         int channels, i, j;
1096         struct usb_audio_term iterm;
1097         unsigned int master_bits, first_ch_bits;
1098         int err, csize;
1099         struct uac_feature_unit_descriptor *ftr = _ftr;
1100
1101         if (ftr->bLength < 7 || ! (csize = ftr->bControlSize) || ftr->bLength < 7 + csize) {
1102                 snd_printk(KERN_ERR "usbaudio: unit %u: invalid UAC_FEATURE_UNIT descriptor\n", unitid);
1103                 return -EINVAL;
1104         }
1105
1106         /* parse the source unit */
1107         if ((err = parse_audio_unit(state, ftr->bSourceID)) < 0)
1108                 return err;
1109
1110         /* determine the input source type and name */
1111         if (check_input_term(state, ftr->bSourceID, &iterm) < 0)
1112                 return -EINVAL;
1113
1114         channels = (ftr->bLength - 7) / csize - 1;
1115
1116         master_bits = snd_usb_combine_bytes(ftr->controls, csize);
1117         /* master configuration quirks */
1118         switch (state->chip->usb_id) {
1119         case USB_ID(0x08bb, 0x2702):
1120                 snd_printk(KERN_INFO
1121                            "usbmixer: master volume quirk for PCM2702 chip\n");
1122                 /* disable non-functional volume control */
1123                 master_bits &= ~(1 << (USB_FEATURE_VOLUME - 1));
1124                 break;
1125         }
1126         if (channels > 0)
1127                 first_ch_bits = snd_usb_combine_bytes(ftr->controls + csize, csize);
1128         else
1129                 first_ch_bits = 0;
1130         /* check all control types */
1131         for (i = 0; i < 10; i++) {
1132                 unsigned int ch_bits = 0;
1133                 for (j = 0; j < channels; j++) {
1134                         unsigned int mask = snd_usb_combine_bytes(ftr->controls + csize * (j+1), csize);
1135                         if (mask & (1 << i))
1136                                 ch_bits |= (1 << j);
1137                 }
1138                 if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
1139                         build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid);
1140                 if (master_bits & (1 << i))
1141                         build_feature_ctl(state, _ftr, 0, i, &iterm, unitid);
1142         }
1143
1144         return 0;
1145 }
1146
1147
1148 /*
1149  * Mixer Unit
1150  */
1151
1152 /*
1153  * build a mixer unit control
1154  *
1155  * the callbacks are identical with feature unit.
1156  * input channel number (zero based) is given in control field instead.
1157  */
1158
1159 static void build_mixer_unit_ctl(struct mixer_build *state, unsigned char *desc,
1160                                  int in_pin, int in_ch, int unitid,
1161                                  struct usb_audio_term *iterm)
1162 {
1163         struct usb_mixer_elem_info *cval;
1164         unsigned int input_pins = desc[4];
1165         unsigned int num_outs = desc[5 + input_pins];
1166         unsigned int i, len;
1167         struct snd_kcontrol *kctl;
1168         const struct usbmix_name_map *map;
1169
1170         map = find_map(state, unitid, 0);
1171         if (check_ignored_ctl(map))
1172                 return;
1173
1174         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1175         if (! cval)
1176                 return;
1177
1178         cval->mixer = state->mixer;
1179         cval->id = unitid;
1180         cval->control = in_ch + 1; /* based on 1 */
1181         cval->val_type = USB_MIXER_S16;
1182         for (i = 0; i < num_outs; i++) {
1183                 if (check_matrix_bitmap(desc + 9 + input_pins, in_ch, i, num_outs)) {
1184                         cval->cmask |= (1 << i);
1185                         cval->channels++;
1186                 }
1187         }
1188
1189         /* get min/max values */
1190         get_min_max(cval, 0);
1191
1192         kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1193         if (! kctl) {
1194                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1195                 kfree(cval);
1196                 return;
1197         }
1198         kctl->private_free = usb_mixer_elem_free;
1199
1200         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1201         if (! len)
1202                 len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 0);
1203         if (! len)
1204                 len = sprintf(kctl->id.name, "Mixer Source %d", in_ch + 1);
1205         append_ctl_name(kctl, " Volume");
1206
1207         snd_printdd(KERN_INFO "[%d] MU [%s] ch = %d, val = %d/%d\n",
1208                     cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
1209         add_control_to_empty(state, kctl);
1210 }
1211
1212
1213 /*
1214  * parse a mixer unit
1215  */
1216 static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, unsigned char *desc)
1217 {
1218         struct usb_audio_term iterm;
1219         int input_pins, num_ins, num_outs;
1220         int pin, ich, err;
1221
1222         if (desc[0] < 11 || ! (input_pins = desc[4]) || ! (num_outs = desc[5 + input_pins])) {
1223                 snd_printk(KERN_ERR "invalid MIXER UNIT descriptor %d\n", unitid);
1224                 return -EINVAL;
1225         }
1226         /* no bmControls field (e.g. Maya44) -> ignore */
1227         if (desc[0] <= 10 + input_pins) {
1228                 snd_printdd(KERN_INFO "MU %d has no bmControls field\n", unitid);
1229                 return 0;
1230         }
1231
1232         num_ins = 0;
1233         ich = 0;
1234         for (pin = 0; pin < input_pins; pin++) {
1235                 err = parse_audio_unit(state, desc[5 + pin]);
1236                 if (err < 0)
1237                         return err;
1238                 err = check_input_term(state, desc[5 + pin], &iterm);
1239                 if (err < 0)
1240                         return err;
1241                 num_ins += iterm.channels;
1242                 for (; ich < num_ins; ++ich) {
1243                         int och, ich_has_controls = 0;
1244
1245                         for (och = 0; och < num_outs; ++och) {
1246                                 if (check_matrix_bitmap(desc + 9 + input_pins,
1247                                                         ich, och, num_outs)) {
1248                                         ich_has_controls = 1;
1249                                         break;
1250                                 }
1251                         }
1252                         if (ich_has_controls)
1253                                 build_mixer_unit_ctl(state, desc, pin, ich,
1254                                                      unitid, &iterm);
1255                 }
1256         }
1257         return 0;
1258 }
1259
1260
1261 /*
1262  * Processing Unit / Extension Unit
1263  */
1264
1265 /* get callback for processing/extension unit */
1266 static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1267 {
1268         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1269         int err, val;
1270
1271         err = get_cur_ctl_value(cval, cval->control << 8, &val);
1272         if (err < 0 && cval->mixer->ignore_ctl_error) {
1273                 ucontrol->value.integer.value[0] = cval->min;
1274                 return 0;
1275         }
1276         if (err < 0)
1277                 return err;
1278         val = get_relative_value(cval, val);
1279         ucontrol->value.integer.value[0] = val;
1280         return 0;
1281 }
1282
1283 /* put callback for processing/extension unit */
1284 static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1285 {
1286         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1287         int val, oval, err;
1288
1289         err = get_cur_ctl_value(cval, cval->control << 8, &oval);
1290         if (err < 0) {
1291                 if (cval->mixer->ignore_ctl_error)
1292                         return 0;
1293                 return err;
1294         }
1295         val = ucontrol->value.integer.value[0];
1296         val = get_abs_value(cval, val);
1297         if (val != oval) {
1298                 set_cur_ctl_value(cval, cval->control << 8, val);
1299                 return 1;
1300         }
1301         return 0;
1302 }
1303
1304 /* alsa control interface for processing/extension unit */
1305 static struct snd_kcontrol_new mixer_procunit_ctl = {
1306         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1307         .name = "", /* will be filled later */
1308         .info = mixer_ctl_feature_info,
1309         .get = mixer_ctl_procunit_get,
1310         .put = mixer_ctl_procunit_put,
1311 };
1312
1313
1314 /*
1315  * predefined data for processing units
1316  */
1317 struct procunit_value_info {
1318         int control;
1319         char *suffix;
1320         int val_type;
1321         int min_value;
1322 };
1323
1324 struct procunit_info {
1325         int type;
1326         char *name;
1327         struct procunit_value_info *values;
1328 };
1329
1330 static struct procunit_value_info updown_proc_info[] = {
1331         { USB_PROC_UPDOWN_SWITCH, "Switch", USB_MIXER_BOOLEAN },
1332         { USB_PROC_UPDOWN_MODE_SEL, "Mode Select", USB_MIXER_U8, 1 },
1333         { 0 }
1334 };
1335 static struct procunit_value_info prologic_proc_info[] = {
1336         { USB_PROC_PROLOGIC_SWITCH, "Switch", USB_MIXER_BOOLEAN },
1337         { USB_PROC_PROLOGIC_MODE_SEL, "Mode Select", USB_MIXER_U8, 1 },
1338         { 0 }
1339 };
1340 static struct procunit_value_info threed_enh_proc_info[] = {
1341         { USB_PROC_3DENH_SWITCH, "Switch", USB_MIXER_BOOLEAN },
1342         { USB_PROC_3DENH_SPACE, "Spaciousness", USB_MIXER_U8 },
1343         { 0 }
1344 };
1345 static struct procunit_value_info reverb_proc_info[] = {
1346         { USB_PROC_REVERB_SWITCH, "Switch", USB_MIXER_BOOLEAN },
1347         { USB_PROC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
1348         { USB_PROC_REVERB_TIME, "Time", USB_MIXER_U16 },
1349         { USB_PROC_REVERB_DELAY, "Delay", USB_MIXER_U8 },
1350         { 0 }
1351 };
1352 static struct procunit_value_info chorus_proc_info[] = {
1353         { USB_PROC_CHORUS_SWITCH, "Switch", USB_MIXER_BOOLEAN },
1354         { USB_PROC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
1355         { USB_PROC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
1356         { USB_PROC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
1357         { 0 }
1358 };
1359 static struct procunit_value_info dcr_proc_info[] = {
1360         { USB_PROC_DCR_SWITCH, "Switch", USB_MIXER_BOOLEAN },
1361         { USB_PROC_DCR_RATIO, "Ratio", USB_MIXER_U16 },
1362         { USB_PROC_DCR_MAX_AMP, "Max Amp", USB_MIXER_S16 },
1363         { USB_PROC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
1364         { USB_PROC_DCR_ATTACK, "Attack Time", USB_MIXER_U16 },
1365         { USB_PROC_DCR_RELEASE, "Release Time", USB_MIXER_U16 },
1366         { 0 }
1367 };
1368
1369 static struct procunit_info procunits[] = {
1370         { USB_PROC_UPDOWN, "Up Down", updown_proc_info },
1371         { USB_PROC_PROLOGIC, "Dolby Prologic", prologic_proc_info },
1372         { USB_PROC_3DENH, "3D Stereo Extender", threed_enh_proc_info },
1373         { USB_PROC_REVERB, "Reverb", reverb_proc_info },
1374         { USB_PROC_CHORUS, "Chorus", chorus_proc_info },
1375         { USB_PROC_DCR, "DCR", dcr_proc_info },
1376         { 0 },
1377 };
1378 /*
1379  * predefined data for extension units
1380  */
1381 static struct procunit_value_info clock_rate_xu_info[] = {
1382        { USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
1383        { 0 }
1384 };
1385 static struct procunit_value_info clock_source_xu_info[] = {
1386         { USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
1387         { 0 }
1388 };
1389 static struct procunit_value_info spdif_format_xu_info[] = {
1390         { USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
1391         { 0 }
1392 };
1393 static struct procunit_value_info soft_limit_xu_info[] = {
1394         { USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
1395         { 0 }
1396 };
1397 static struct procunit_info extunits[] = {
1398         { USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
1399         { USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
1400         { USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
1401         { USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
1402         { 0 }
1403 };
1404 /*
1405  * build a processing/extension unit
1406  */
1407 static int build_audio_procunit(struct mixer_build *state, int unitid, unsigned char *dsc, struct procunit_info *list, char *name)
1408 {
1409         int num_ins = dsc[6];
1410         struct usb_mixer_elem_info *cval;
1411         struct snd_kcontrol *kctl;
1412         int i, err, nameid, type, len;
1413         struct procunit_info *info;
1414         struct procunit_value_info *valinfo;
1415         const struct usbmix_name_map *map;
1416         static struct procunit_value_info default_value_info[] = {
1417                 { 0x01, "Switch", USB_MIXER_BOOLEAN },
1418                 { 0 }
1419         };
1420         static struct procunit_info default_info = {
1421                 0, NULL, default_value_info
1422         };
1423
1424         if (dsc[0] < 13 || dsc[0] < 13 + num_ins || dsc[0] < num_ins + dsc[11 + num_ins]) {
1425                 snd_printk(KERN_ERR "invalid %s descriptor (id %d)\n", name, unitid);
1426                 return -EINVAL;
1427         }
1428
1429         for (i = 0; i < num_ins; i++) {
1430                 if ((err = parse_audio_unit(state, dsc[7 + i])) < 0)
1431                         return err;
1432         }
1433
1434         type = combine_word(&dsc[4]);
1435         for (info = list; info && info->type; info++)
1436                 if (info->type == type)
1437                         break;
1438         if (! info || ! info->type)
1439                 info = &default_info;
1440
1441         for (valinfo = info->values; valinfo->control; valinfo++) {
1442                 /* FIXME: bitmap might be longer than 8bit */
1443                 if (! (dsc[12 + num_ins] & (1 << (valinfo->control - 1))))
1444                         continue;
1445                 map = find_map(state, unitid, valinfo->control);
1446                 if (check_ignored_ctl(map))
1447                         continue;
1448                 cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1449                 if (! cval) {
1450                         snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1451                         return -ENOMEM;
1452                 }
1453                 cval->mixer = state->mixer;
1454                 cval->id = unitid;
1455                 cval->control = valinfo->control;
1456                 cval->val_type = valinfo->val_type;
1457                 cval->channels = 1;
1458
1459                 /* get min/max values */
1460                 if (type == USB_PROC_UPDOWN && cval->control == USB_PROC_UPDOWN_MODE_SEL) {
1461                         /* FIXME: hard-coded */
1462                         cval->min = 1;
1463                         cval->max = dsc[15];
1464                         cval->res = 1;
1465                         cval->initialized = 1;
1466                 } else {
1467                         if (type == USB_XU_CLOCK_RATE) {
1468                                 /* E-Mu USB 0404/0202/TrackerPre
1469                                  * samplerate control quirk
1470                                  */
1471                                 cval->min = 0;
1472                                 cval->max = 5;
1473                                 cval->res = 1;
1474                                 cval->initialized = 1;
1475                         } else
1476                                 get_min_max(cval, valinfo->min_value);
1477                 }
1478
1479                 kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
1480                 if (! kctl) {
1481                         snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1482                         kfree(cval);
1483                         return -ENOMEM;
1484                 }
1485                 kctl->private_free = usb_mixer_elem_free;
1486
1487                 if (check_mapped_name(map, kctl->id.name,
1488                                                 sizeof(kctl->id.name)))
1489                         /* nothing */ ;
1490                 else if (info->name)
1491                         strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
1492                 else {
1493                         nameid = dsc[12 + num_ins + dsc[11 + num_ins]];
1494                         len = 0;
1495                         if (nameid)
1496                                 len = snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
1497                         if (! len)
1498                                 strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
1499                 }
1500                 append_ctl_name(kctl, " ");
1501                 append_ctl_name(kctl, valinfo->suffix);
1502
1503                 snd_printdd(KERN_INFO "[%d] PU [%s] ch = %d, val = %d/%d\n",
1504                             cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
1505                 if ((err = add_control_to_empty(state, kctl)) < 0)
1506                         return err;
1507         }
1508         return 0;
1509 }
1510
1511
1512 static int parse_audio_processing_unit(struct mixer_build *state, int unitid, unsigned char *desc)
1513 {
1514         return build_audio_procunit(state, unitid, desc, procunits, "Processing Unit");
1515 }
1516
1517 static int parse_audio_extension_unit(struct mixer_build *state, int unitid, unsigned char *desc)
1518 {
1519         return build_audio_procunit(state, unitid, desc, extunits, "Extension Unit");
1520 }
1521
1522
1523 /*
1524  * Selector Unit
1525  */
1526
1527 /* info callback for selector unit
1528  * use an enumerator type for routing
1529  */
1530 static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
1531 {
1532         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1533         char **itemlist = (char **)kcontrol->private_value;
1534
1535         if (snd_BUG_ON(!itemlist))
1536                 return -EINVAL;
1537         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
1538         uinfo->count = 1;
1539         uinfo->value.enumerated.items = cval->max;
1540         if ((int)uinfo->value.enumerated.item >= cval->max)
1541                 uinfo->value.enumerated.item = cval->max - 1;
1542         strcpy(uinfo->value.enumerated.name, itemlist[uinfo->value.enumerated.item]);
1543         return 0;
1544 }
1545
1546 /* get callback for selector unit */
1547 static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1548 {
1549         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1550         int val, err;
1551
1552         err = get_cur_ctl_value(cval, 0, &val);
1553         if (err < 0) {
1554                 if (cval->mixer->ignore_ctl_error) {
1555                         ucontrol->value.enumerated.item[0] = 0;
1556                         return 0;
1557                 }
1558                 return err;
1559         }
1560         val = get_relative_value(cval, val);
1561         ucontrol->value.enumerated.item[0] = val;
1562         return 0;
1563 }
1564
1565 /* put callback for selector unit */
1566 static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1567 {
1568         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1569         int val, oval, err;
1570
1571         err = get_cur_ctl_value(cval, 0, &oval);
1572         if (err < 0) {
1573                 if (cval->mixer->ignore_ctl_error)
1574                         return 0;
1575                 return err;
1576         }
1577         val = ucontrol->value.enumerated.item[0];
1578         val = get_abs_value(cval, val);
1579         if (val != oval) {
1580                 set_cur_ctl_value(cval, 0, val);
1581                 return 1;
1582         }
1583         return 0;
1584 }
1585
1586 /* alsa control interface for selector unit */
1587 static struct snd_kcontrol_new mixer_selectunit_ctl = {
1588         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1589         .name = "", /* will be filled later */
1590         .info = mixer_ctl_selector_info,
1591         .get = mixer_ctl_selector_get,
1592         .put = mixer_ctl_selector_put,
1593 };
1594
1595
1596 /* private free callback.
1597  * free both private_data and private_value
1598  */
1599 static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
1600 {
1601         int i, num_ins = 0;
1602
1603         if (kctl->private_data) {
1604                 struct usb_mixer_elem_info *cval = kctl->private_data;
1605                 num_ins = cval->max;
1606                 kfree(cval);
1607                 kctl->private_data = NULL;
1608         }
1609         if (kctl->private_value) {
1610                 char **itemlist = (char **)kctl->private_value;
1611                 for (i = 0; i < num_ins; i++)
1612                         kfree(itemlist[i]);
1613                 kfree(itemlist);
1614                 kctl->private_value = 0;
1615         }
1616 }
1617
1618 /*
1619  * parse a selector unit
1620  */
1621 static int parse_audio_selector_unit(struct mixer_build *state, int unitid, unsigned char *desc)
1622 {
1623         unsigned int num_ins = desc[4];
1624         unsigned int i, nameid, len;
1625         int err;
1626         struct usb_mixer_elem_info *cval;
1627         struct snd_kcontrol *kctl;
1628         const struct usbmix_name_map *map;
1629         char **namelist;
1630
1631         if (! num_ins || desc[0] < 5 + num_ins) {
1632                 snd_printk(KERN_ERR "invalid SELECTOR UNIT descriptor %d\n", unitid);
1633                 return -EINVAL;
1634         }
1635
1636         for (i = 0; i < num_ins; i++) {
1637                 if ((err = parse_audio_unit(state, desc[5 + i])) < 0)
1638                         return err;
1639         }
1640
1641         if (num_ins == 1) /* only one ? nonsense! */
1642                 return 0;
1643
1644         map = find_map(state, unitid, 0);
1645         if (check_ignored_ctl(map))
1646                 return 0;
1647
1648         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1649         if (! cval) {
1650                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1651                 return -ENOMEM;
1652         }
1653         cval->mixer = state->mixer;
1654         cval->id = unitid;
1655         cval->val_type = USB_MIXER_U8;
1656         cval->channels = 1;
1657         cval->min = 1;
1658         cval->max = num_ins;
1659         cval->res = 1;
1660         cval->initialized = 1;
1661
1662         namelist = kmalloc(sizeof(char *) * num_ins, GFP_KERNEL);
1663         if (! namelist) {
1664                 snd_printk(KERN_ERR "cannot malloc\n");
1665                 kfree(cval);
1666                 return -ENOMEM;
1667         }
1668 #define MAX_ITEM_NAME_LEN       64
1669         for (i = 0; i < num_ins; i++) {
1670                 struct usb_audio_term iterm;
1671                 len = 0;
1672                 namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
1673                 if (! namelist[i]) {
1674                         snd_printk(KERN_ERR "cannot malloc\n");
1675                         while (i--)
1676                                 kfree(namelist[i]);
1677                         kfree(namelist);
1678                         kfree(cval);
1679                         return -ENOMEM;
1680                 }
1681                 len = check_mapped_selector_name(state, unitid, i, namelist[i],
1682                                                  MAX_ITEM_NAME_LEN);
1683                 if (! len && check_input_term(state, desc[5 + i], &iterm) >= 0)
1684                         len = get_term_name(state, &iterm, namelist[i], MAX_ITEM_NAME_LEN, 0);
1685                 if (! len)
1686                         sprintf(namelist[i], "Input %d", i);
1687         }
1688
1689         kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
1690         if (! kctl) {
1691                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1692                 kfree(namelist);
1693                 kfree(cval);
1694                 return -ENOMEM;
1695         }
1696         kctl->private_value = (unsigned long)namelist;
1697         kctl->private_free = usb_mixer_selector_elem_free;
1698
1699         nameid = desc[desc[0] - 1];
1700         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1701         if (len)
1702                 ;
1703         else if (nameid)
1704                 snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
1705         else {
1706                 len = get_term_name(state, &state->oterm,
1707                                     kctl->id.name, sizeof(kctl->id.name), 0);
1708                 if (! len)
1709                         strlcpy(kctl->id.name, "USB", sizeof(kctl->id.name));
1710
1711                 if ((state->oterm.type & 0xff00) == 0x0100)
1712                         append_ctl_name(kctl, " Capture Source");
1713                 else
1714                         append_ctl_name(kctl, " Playback Source");
1715         }
1716
1717         snd_printdd(KERN_INFO "[%d] SU [%s] items = %d\n",
1718                     cval->id, kctl->id.name, num_ins);
1719         if ((err = add_control_to_empty(state, kctl)) < 0)
1720                 return err;
1721
1722         return 0;
1723 }
1724
1725
1726 /*
1727  * parse an audio unit recursively
1728  */
1729
1730 static int parse_audio_unit(struct mixer_build *state, int unitid)
1731 {
1732         unsigned char *p1;
1733
1734         if (test_and_set_bit(unitid, state->unitbitmap))
1735                 return 0; /* the unit already visited */
1736
1737         p1 = find_audio_control_unit(state, unitid);
1738         if (!p1) {
1739                 snd_printk(KERN_ERR "usbaudio: unit %d not found!\n", unitid);
1740                 return -EINVAL;
1741         }
1742
1743         switch (p1[2]) {
1744         case UAC_INPUT_TERMINAL:
1745                 return 0; /* NOP */
1746         case UAC_MIXER_UNIT:
1747                 return parse_audio_mixer_unit(state, unitid, p1);
1748         case UAC_SELECTOR_UNIT:
1749                 return parse_audio_selector_unit(state, unitid, p1);
1750         case UAC_FEATURE_UNIT:
1751                 return parse_audio_feature_unit(state, unitid, p1);
1752         case UAC_PROCESSING_UNIT_V1:
1753                 return parse_audio_processing_unit(state, unitid, p1);
1754         case UAC_EXTENSION_UNIT_V1:
1755                 return parse_audio_extension_unit(state, unitid, p1);
1756         default:
1757                 snd_printk(KERN_ERR "usbaudio: unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
1758                 return -EINVAL;
1759         }
1760 }
1761
1762 static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
1763 {
1764         kfree(mixer->id_elems);
1765         if (mixer->urb) {
1766                 kfree(mixer->urb->transfer_buffer);
1767                 usb_free_urb(mixer->urb);
1768         }
1769         usb_free_urb(mixer->rc_urb);
1770         kfree(mixer->rc_setup_packet);
1771         kfree(mixer);
1772 }
1773
1774 static int snd_usb_mixer_dev_free(struct snd_device *device)
1775 {
1776         struct usb_mixer_interface *mixer = device->device_data;
1777         snd_usb_mixer_free(mixer);
1778         return 0;
1779 }
1780
1781 /*
1782  * create mixer controls
1783  *
1784  * walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
1785  */
1786 static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
1787 {
1788         struct uac_output_terminal_descriptor_v1 *desc;
1789         struct mixer_build state;
1790         int err;
1791         const struct usbmix_ctl_map *map;
1792         struct usb_host_interface *hostif;
1793
1794         hostif = &usb_ifnum_to_if(mixer->chip->dev, mixer->ctrlif)->altsetting[0];
1795         memset(&state, 0, sizeof(state));
1796         state.chip = mixer->chip;
1797         state.mixer = mixer;
1798         state.buffer = hostif->extra;
1799         state.buflen = hostif->extralen;
1800
1801         /* check the mapping table */
1802         for (map = usbmix_ctl_maps; map->id; map++) {
1803                 if (map->id == state.chip->usb_id) {
1804                         state.map = map->map;
1805                         state.selector_map = map->selector_map;
1806                         mixer->ignore_ctl_error = map->ignore_ctl_error;
1807                         break;
1808                 }
1809         }
1810
1811         desc = NULL;
1812         while ((desc = snd_usb_find_csint_desc(hostif->extra, hostif->extralen, desc, UAC_OUTPUT_TERMINAL)) != NULL) {
1813                 if (desc->bLength < 9)
1814                         continue; /* invalid descriptor? */
1815                 set_bit(desc->bTerminalID, state.unitbitmap);  /* mark terminal ID as visited */
1816                 state.oterm.id = desc->bTerminalID;
1817                 state.oterm.type = le16_to_cpu(desc->wTerminalType);
1818                 state.oterm.name = desc->iTerminal;
1819                 err = parse_audio_unit(&state, desc->bSourceID);
1820                 if (err < 0)
1821                         return err;
1822         }
1823         return 0;
1824 }
1825
1826 static void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer,
1827                                     int unitid)
1828 {
1829         struct usb_mixer_elem_info *info;
1830
1831         for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem)
1832                 snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
1833                                info->elem_id);
1834 }
1835
1836 static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
1837                                     int unitid,
1838                                     struct usb_mixer_elem_info *cval)
1839 {
1840         static char *val_types[] = {"BOOLEAN", "INV_BOOLEAN",
1841                                     "S8", "U8", "S16", "U16"};
1842         snd_iprintf(buffer, "  Unit: %i\n", unitid);
1843         if (cval->elem_id)
1844                 snd_iprintf(buffer, "    Control: name=\"%s\", index=%i\n",
1845                                 cval->elem_id->name, cval->elem_id->index);
1846         snd_iprintf(buffer, "    Info: id=%i, control=%i, cmask=0x%x, "
1847                             "channels=%i, type=\"%s\"\n", cval->id,
1848                             cval->control, cval->cmask, cval->channels,
1849                             val_types[cval->val_type]);
1850         snd_iprintf(buffer, "    Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
1851                             cval->min, cval->max, cval->dBmin, cval->dBmax);
1852 }
1853
1854 static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
1855                                     struct snd_info_buffer *buffer)
1856 {
1857         struct snd_usb_audio *chip = entry->private_data;
1858         struct usb_mixer_interface *mixer;
1859         struct usb_mixer_elem_info *cval;
1860         int unitid;
1861
1862         list_for_each_entry(mixer, &chip->mixer_list, list) {
1863                 snd_iprintf(buffer,
1864                         "USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
1865                                 chip->usb_id, mixer->ctrlif,
1866                                 mixer->ignore_ctl_error);
1867                 snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
1868                 for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
1869                         for (cval = mixer->id_elems[unitid]; cval;
1870                                                 cval = cval->next_id_elem)
1871                                 snd_usb_mixer_dump_cval(buffer, unitid, cval);
1872                 }
1873         }
1874 }
1875
1876 static void snd_usb_mixer_memory_change(struct usb_mixer_interface *mixer,
1877                                         int unitid)
1878 {
1879         if (!mixer->rc_cfg)
1880                 return;
1881         /* unit ids specific to Extigy/Audigy 2 NX: */
1882         switch (unitid) {
1883         case 0: /* remote control */
1884                 mixer->rc_urb->dev = mixer->chip->dev;
1885                 usb_submit_urb(mixer->rc_urb, GFP_ATOMIC);
1886                 break;
1887         case 4: /* digital in jack */
1888         case 7: /* line in jacks */
1889         case 19: /* speaker out jacks */
1890         case 20: /* headphones out jack */
1891                 break;
1892         /* live24ext: 4 = line-in jack */
1893         case 3: /* hp-out jack (may actuate Mute) */
1894                 if (mixer->chip->usb_id == USB_ID(0x041e, 0x3040) ||
1895                     mixer->chip->usb_id == USB_ID(0x041e, 0x3048))
1896                         snd_usb_mixer_notify_id(mixer, mixer->rc_cfg->mute_mixer_id);
1897                 break;
1898         default:
1899                 snd_printd(KERN_DEBUG "memory change in unknown unit %d\n", unitid);
1900                 break;
1901         }
1902 }
1903
1904 static void snd_usb_mixer_status_complete(struct urb *urb)
1905 {
1906         struct usb_mixer_interface *mixer = urb->context;
1907
1908         if (urb->status == 0) {
1909                 u8 *buf = urb->transfer_buffer;
1910                 int i;
1911
1912                 for (i = urb->actual_length; i >= 2; buf += 2, i -= 2) {
1913                         snd_printd(KERN_DEBUG "status interrupt: %02x %02x\n",
1914                                    buf[0], buf[1]);
1915                         /* ignore any notifications not from the control interface */
1916                         if ((buf[0] & 0x0f) != 0)
1917                                 continue;
1918                         if (!(buf[0] & 0x40))
1919                                 snd_usb_mixer_notify_id(mixer, buf[1]);
1920                         else
1921                                 snd_usb_mixer_memory_change(mixer, buf[1]);
1922                 }
1923         }
1924         if (urb->status != -ENOENT && urb->status != -ECONNRESET) {
1925                 urb->dev = mixer->chip->dev;
1926                 usb_submit_urb(urb, GFP_ATOMIC);
1927         }
1928 }
1929
1930 /* create the handler for the optional status interrupt endpoint */
1931 static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
1932 {
1933         struct usb_host_interface *hostif;
1934         struct usb_endpoint_descriptor *ep;
1935         void *transfer_buffer;
1936         int buffer_length;
1937         unsigned int epnum;
1938
1939         hostif = &usb_ifnum_to_if(mixer->chip->dev, mixer->ctrlif)->altsetting[0];
1940         /* we need one interrupt input endpoint */
1941         if (get_iface_desc(hostif)->bNumEndpoints < 1)
1942                 return 0;
1943         ep = get_endpoint(hostif, 0);
1944         if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
1945                 return 0;
1946
1947         epnum = usb_endpoint_num(ep);
1948         buffer_length = le16_to_cpu(ep->wMaxPacketSize);
1949         transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
1950         if (!transfer_buffer)
1951                 return -ENOMEM;
1952         mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
1953         if (!mixer->urb) {
1954                 kfree(transfer_buffer);
1955                 return -ENOMEM;
1956         }
1957         usb_fill_int_urb(mixer->urb, mixer->chip->dev,
1958                          usb_rcvintpipe(mixer->chip->dev, epnum),
1959                          transfer_buffer, buffer_length,
1960                          snd_usb_mixer_status_complete, mixer, ep->bInterval);
1961         usb_submit_urb(mixer->urb, GFP_KERNEL);
1962         return 0;
1963 }
1964
1965 static void snd_usb_soundblaster_remote_complete(struct urb *urb)
1966 {
1967         struct usb_mixer_interface *mixer = urb->context;
1968         const struct rc_config *rc = mixer->rc_cfg;
1969         u32 code;
1970
1971         if (urb->status < 0 || urb->actual_length < rc->min_packet_length)
1972                 return;
1973
1974         code = mixer->rc_buffer[rc->offset];
1975         if (rc->length == 2)
1976                 code |= mixer->rc_buffer[rc->offset + 1] << 8;
1977
1978         /* the Mute button actually changes the mixer control */
1979         if (code == rc->mute_code)
1980                 snd_usb_mixer_notify_id(mixer, rc->mute_mixer_id);
1981         mixer->rc_code = code;
1982         wmb();
1983         wake_up(&mixer->rc_waitq);
1984 }
1985
1986 static long snd_usb_sbrc_hwdep_read(struct snd_hwdep *hw, char __user *buf,
1987                                      long count, loff_t *offset)
1988 {
1989         struct usb_mixer_interface *mixer = hw->private_data;
1990         int err;
1991         u32 rc_code;
1992
1993         if (count != 1 && count != 4)
1994                 return -EINVAL;
1995         err = wait_event_interruptible(mixer->rc_waitq,
1996                                        (rc_code = xchg(&mixer->rc_code, 0)) != 0);
1997         if (err == 0) {
1998                 if (count == 1)
1999                         err = put_user(rc_code, buf);
2000                 else
2001                         err = put_user(rc_code, (u32 __user *)buf);
2002         }
2003         return err < 0 ? err : count;
2004 }
2005
2006 static unsigned int snd_usb_sbrc_hwdep_poll(struct snd_hwdep *hw, struct file *file,
2007                                             poll_table *wait)
2008 {
2009         struct usb_mixer_interface *mixer = hw->private_data;
2010
2011         poll_wait(file, &mixer->rc_waitq, wait);
2012         return mixer->rc_code ? POLLIN | POLLRDNORM : 0;
2013 }
2014
2015 static int snd_usb_soundblaster_remote_init(struct usb_mixer_interface *mixer)
2016 {
2017         struct snd_hwdep *hwdep;
2018         int err, len, i;
2019
2020         for (i = 0; i < ARRAY_SIZE(rc_configs); ++i)
2021                 if (rc_configs[i].usb_id == mixer->chip->usb_id)
2022                         break;
2023         if (i >= ARRAY_SIZE(rc_configs))
2024                 return 0;
2025         mixer->rc_cfg = &rc_configs[i];
2026
2027         len = mixer->rc_cfg->packet_length;
2028         
2029         init_waitqueue_head(&mixer->rc_waitq);
2030         err = snd_hwdep_new(mixer->chip->card, "SB remote control", 0, &hwdep);
2031         if (err < 0)
2032                 return err;
2033         snprintf(hwdep->name, sizeof(hwdep->name),
2034                  "%s remote control", mixer->chip->card->shortname);
2035         hwdep->iface = SNDRV_HWDEP_IFACE_SB_RC;
2036         hwdep->private_data = mixer;
2037         hwdep->ops.read = snd_usb_sbrc_hwdep_read;
2038         hwdep->ops.poll = snd_usb_sbrc_hwdep_poll;
2039         hwdep->exclusive = 1;
2040
2041         mixer->rc_urb = usb_alloc_urb(0, GFP_KERNEL);
2042         if (!mixer->rc_urb)
2043                 return -ENOMEM;
2044         mixer->rc_setup_packet = kmalloc(sizeof(*mixer->rc_setup_packet), GFP_KERNEL);
2045         if (!mixer->rc_setup_packet) {
2046                 usb_free_urb(mixer->rc_urb);
2047                 mixer->rc_urb = NULL;
2048                 return -ENOMEM;
2049         }
2050         mixer->rc_setup_packet->bRequestType =
2051                 USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE;
2052         mixer->rc_setup_packet->bRequest = UAC_GET_MEM;
2053         mixer->rc_setup_packet->wValue = cpu_to_le16(0);
2054         mixer->rc_setup_packet->wIndex = cpu_to_le16(0);
2055         mixer->rc_setup_packet->wLength = cpu_to_le16(len);
2056         usb_fill_control_urb(mixer->rc_urb, mixer->chip->dev,
2057                              usb_rcvctrlpipe(mixer->chip->dev, 0),
2058                              (u8*)mixer->rc_setup_packet, mixer->rc_buffer, len,
2059                              snd_usb_soundblaster_remote_complete, mixer);
2060         return 0;
2061 }
2062
2063 #define snd_audigy2nx_led_info          snd_ctl_boolean_mono_info
2064
2065 static int snd_audigy2nx_led_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
2066 {
2067         struct usb_mixer_interface *mixer = snd_kcontrol_chip(kcontrol);
2068         int index = kcontrol->private_value;
2069
2070         ucontrol->value.integer.value[0] = mixer->audigy2nx_leds[index];
2071         return 0;
2072 }
2073
2074 static int snd_audigy2nx_led_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
2075 {
2076         struct usb_mixer_interface *mixer = snd_kcontrol_chip(kcontrol);
2077         int index = kcontrol->private_value;
2078         int value = ucontrol->value.integer.value[0];
2079         int err, changed;
2080
2081         if (value > 1)
2082                 return -EINVAL;
2083         changed = value != mixer->audigy2nx_leds[index];
2084         err = snd_usb_ctl_msg(mixer->chip->dev,
2085                               usb_sndctrlpipe(mixer->chip->dev, 0), 0x24,
2086                               USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_OTHER,
2087                               value, index + 2, NULL, 0, 100);
2088         if (err < 0)
2089                 return err;
2090         mixer->audigy2nx_leds[index] = value;
2091         return changed;
2092 }
2093
2094 static struct snd_kcontrol_new snd_audigy2nx_controls[] = {
2095         {
2096                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2097                 .name = "CMSS LED Switch",
2098                 .info = snd_audigy2nx_led_info,
2099                 .get = snd_audigy2nx_led_get,
2100                 .put = snd_audigy2nx_led_put,
2101                 .private_value = 0,
2102         },
2103         {
2104                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2105                 .name = "Power LED Switch",
2106                 .info = snd_audigy2nx_led_info,
2107                 .get = snd_audigy2nx_led_get,
2108                 .put = snd_audigy2nx_led_put,
2109                 .private_value = 1,
2110         },
2111         {
2112                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2113                 .name = "Dolby Digital LED Switch",
2114                 .info = snd_audigy2nx_led_info,
2115                 .get = snd_audigy2nx_led_get,
2116                 .put = snd_audigy2nx_led_put,
2117                 .private_value = 2,
2118         },
2119 };
2120
2121 static int snd_audigy2nx_controls_create(struct usb_mixer_interface *mixer)
2122 {
2123         int i, err;
2124
2125         for (i = 0; i < ARRAY_SIZE(snd_audigy2nx_controls); ++i) {
2126                 if (i > 1 && /* Live24ext has 2 LEDs only */
2127                         (mixer->chip->usb_id == USB_ID(0x041e, 0x3040) ||
2128                          mixer->chip->usb_id == USB_ID(0x041e, 0x3048)))
2129                         break; 
2130                 err = snd_ctl_add(mixer->chip->card,
2131                                   snd_ctl_new1(&snd_audigy2nx_controls[i], mixer));
2132                 if (err < 0)
2133                         return err;
2134         }
2135         mixer->audigy2nx_leds[1] = 1; /* Power LED is on by default */
2136         return 0;
2137 }
2138
2139 static void snd_audigy2nx_proc_read(struct snd_info_entry *entry,
2140                                     struct snd_info_buffer *buffer)
2141 {
2142         static const struct sb_jack {
2143                 int unitid;
2144                 const char *name;
2145         }  jacks_audigy2nx[] = {
2146                 {4,  "dig in "},
2147                 {7,  "line in"},
2148                 {19, "spk out"},
2149                 {20, "hph out"},
2150                 {-1, NULL}
2151         }, jacks_live24ext[] = {
2152                 {4,  "line in"}, /* &1=Line, &2=Mic*/
2153                 {3,  "hph out"}, /* headphones */
2154                 {0,  "RC     "}, /* last command, 6 bytes see rc_config above */
2155                 {-1, NULL}
2156         };
2157         const struct sb_jack *jacks;
2158         struct usb_mixer_interface *mixer = entry->private_data;
2159         int i, err;
2160         u8 buf[3];
2161
2162         snd_iprintf(buffer, "%s jacks\n\n", mixer->chip->card->shortname);
2163         if (mixer->chip->usb_id == USB_ID(0x041e, 0x3020))
2164                 jacks = jacks_audigy2nx;
2165         else if (mixer->chip->usb_id == USB_ID(0x041e, 0x3040) ||
2166                  mixer->chip->usb_id == USB_ID(0x041e, 0x3048))
2167                 jacks = jacks_live24ext;
2168         else
2169                 return;
2170
2171         for (i = 0; jacks[i].name; ++i) {
2172                 snd_iprintf(buffer, "%s: ", jacks[i].name);
2173                 err = snd_usb_ctl_msg(mixer->chip->dev,
2174                                       usb_rcvctrlpipe(mixer->chip->dev, 0),
2175                                       UAC_GET_MEM, USB_DIR_IN | USB_TYPE_CLASS |
2176                                       USB_RECIP_INTERFACE, 0,
2177                                       jacks[i].unitid << 8, buf, 3, 100);
2178                 if (err == 3 && (buf[0] == 3 || buf[0] == 6))
2179                         snd_iprintf(buffer, "%02x %02x\n", buf[1], buf[2]);
2180                 else
2181                         snd_iprintf(buffer, "?\n");
2182         }
2183 }
2184
2185 static int snd_xonar_u1_switch_get(struct snd_kcontrol *kcontrol,
2186                                    struct snd_ctl_elem_value *ucontrol)
2187 {
2188         struct usb_mixer_interface *mixer = snd_kcontrol_chip(kcontrol);
2189
2190         ucontrol->value.integer.value[0] = !!(mixer->xonar_u1_status & 0x02);
2191         return 0;
2192 }
2193
2194 static int snd_xonar_u1_switch_put(struct snd_kcontrol *kcontrol,
2195                                    struct snd_ctl_elem_value *ucontrol)
2196 {
2197         struct usb_mixer_interface *mixer = snd_kcontrol_chip(kcontrol);
2198         u8 old_status, new_status;
2199         int err, changed;
2200
2201         old_status = mixer->xonar_u1_status;
2202         if (ucontrol->value.integer.value[0])
2203                 new_status = old_status | 0x02;
2204         else
2205                 new_status = old_status & ~0x02;
2206         changed = new_status != old_status;
2207         err = snd_usb_ctl_msg(mixer->chip->dev,
2208                               usb_sndctrlpipe(mixer->chip->dev, 0), 0x08,
2209                               USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_OTHER,
2210                               50, 0, &new_status, 1, 100);
2211         if (err < 0)
2212                 return err;
2213         mixer->xonar_u1_status = new_status;
2214         return changed;
2215 }
2216
2217 static struct snd_kcontrol_new snd_xonar_u1_output_switch = {
2218         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2219         .name = "Digital Playback Switch",
2220         .info = snd_ctl_boolean_mono_info,
2221         .get = snd_xonar_u1_switch_get,
2222         .put = snd_xonar_u1_switch_put,
2223 };
2224
2225 static int snd_xonar_u1_controls_create(struct usb_mixer_interface *mixer)
2226 {
2227         int err;
2228
2229         err = snd_ctl_add(mixer->chip->card,
2230                           snd_ctl_new1(&snd_xonar_u1_output_switch, mixer));
2231         if (err < 0)
2232                 return err;
2233         mixer->xonar_u1_status = 0x05;
2234         return 0;
2235 }
2236
2237 void snd_emuusb_set_samplerate(struct snd_usb_audio *chip,
2238                                unsigned char samplerate_id)
2239 {
2240         struct usb_mixer_interface *mixer;
2241         struct usb_mixer_elem_info *cval;
2242         int unitid = 12; /* SamleRate ExtensionUnit ID */
2243
2244         list_for_each_entry(mixer, &chip->mixer_list, list) {
2245                 cval = mixer->id_elems[unitid];
2246                 if (cval) {
2247                         set_cur_ctl_value(cval, cval->control << 8,
2248                                           samplerate_id);
2249                         snd_usb_mixer_notify_id(mixer, unitid);
2250                 }
2251                 break;
2252         }
2253 }
2254
2255 int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif,
2256                          int ignore_error)
2257 {
2258         static struct snd_device_ops dev_ops = {
2259                 .dev_free = snd_usb_mixer_dev_free
2260         };
2261         struct usb_mixer_interface *mixer;
2262         struct snd_info_entry *entry;
2263         struct usb_host_interface *host_iface;
2264         int err, protocol;
2265
2266         strcpy(chip->card->mixername, "USB Mixer");
2267
2268         mixer = kzalloc(sizeof(*mixer), GFP_KERNEL);
2269         if (!mixer)
2270                 return -ENOMEM;
2271         mixer->chip = chip;
2272         mixer->ctrlif = ctrlif;
2273         mixer->ignore_ctl_error = ignore_error;
2274         mixer->id_elems = kcalloc(MAX_ID_ELEMS, sizeof(*mixer->id_elems),
2275                                   GFP_KERNEL);
2276         if (!mixer->id_elems) {
2277                 kfree(mixer);
2278                 return -ENOMEM;
2279         }
2280
2281         host_iface = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
2282         protocol = host_iface->desc.bInterfaceProtocol;
2283
2284         /* FIXME! */
2285         if (protocol != UAC_VERSION_1) {
2286                 snd_printk(KERN_WARNING "mixer interface protocol 0x%02x not yet supported\n",
2287                                         protocol);
2288                 return 0;
2289         }
2290
2291         if ((err = snd_usb_mixer_controls(mixer)) < 0 ||
2292             (err = snd_usb_mixer_status_create(mixer)) < 0)
2293                 goto _error;
2294
2295         if ((err = snd_usb_soundblaster_remote_init(mixer)) < 0)
2296                 goto _error;
2297
2298         if (mixer->chip->usb_id == USB_ID(0x041e, 0x3020) ||
2299             mixer->chip->usb_id == USB_ID(0x041e, 0x3040) ||
2300             mixer->chip->usb_id == USB_ID(0x041e, 0x3048)) {
2301                 if ((err = snd_audigy2nx_controls_create(mixer)) < 0)
2302                         goto _error;
2303                 if (!snd_card_proc_new(chip->card, "audigy2nx", &entry))
2304                         snd_info_set_text_ops(entry, mixer,
2305                                               snd_audigy2nx_proc_read);
2306         }
2307
2308         if (mixer->chip->usb_id == USB_ID(0x0b05, 0x1739) ||
2309             mixer->chip->usb_id == USB_ID(0x0b05, 0x1743)) {
2310                 err = snd_xonar_u1_controls_create(mixer);
2311                 if (err < 0)
2312                         goto _error;
2313         }
2314
2315         err = snd_device_new(chip->card, SNDRV_DEV_LOWLEVEL, mixer, &dev_ops);
2316         if (err < 0)
2317                 goto _error;
2318
2319         if (list_empty(&chip->mixer_list) &&
2320             !snd_card_proc_new(chip->card, "usbmixer", &entry))
2321                 snd_info_set_text_ops(entry, chip, snd_usb_mixer_proc_read);
2322
2323         list_add(&mixer->list, &chip->mixer_list);
2324         return 0;
2325
2326 _error:
2327         snd_usb_mixer_free(mixer);
2328         return err;
2329 }
2330
2331 void snd_usb_mixer_disconnect(struct list_head *p)
2332 {
2333         struct usb_mixer_interface *mixer;
2334         
2335         mixer = list_entry(p, struct usb_mixer_interface, list);
2336         usb_kill_urb(mixer->urb);
2337         usb_kill_urb(mixer->rc_urb);
2338 }