1/*
2 *   This program is free software; you can redistribute it and/or modify
3 *   it under the terms of the GNU General Public License as published by
4 *   the Free Software Foundation; either version 2 of the License, or
5 *   (at your option) any later version.
6 *
7 *   This program is distributed in the hope that it will be useful,
8 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *   GNU General Public License for more details.
11 *
12 *   You should have received a copy of the GNU General Public License
13 *   along with this program; if not, write to the Free Software
14 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 *
16 */
17
18#include <linux/init.h>
19#include <linux/slab.h>
20#include <linux/usb.h>
21#include <linux/usb/audio.h>
22#include <linux/usb/audio-v2.h>
23
24#include <sound/core.h>
25#include <sound/pcm.h>
26
27#include "usbaudio.h"
28#include "card.h"
29#include "quirks.h"
30#include "helper.h"
31#include "debug.h"
32#include "clock.h"
33#include "format.h"
34
35/*
36 * parse the audio format type I descriptor
37 * and returns the corresponding pcm format
38 *
39 * @dev: usb device
40 * @fp: audioformat record
41 * @format: the format tag (wFormatTag)
42 * @fmt: the format type descriptor
43 */
44static u64 parse_audio_format_i_type(struct snd_usb_audio *chip,
45				     struct audioformat *fp,
46				     unsigned int format, void *_fmt)
47{
48	int sample_width, sample_bytes;
49	u64 pcm_formats = 0;
50
51	switch (fp->protocol) {
52	case UAC_VERSION_1:
53	default: {
54		struct uac_format_type_i_discrete_descriptor *fmt = _fmt;
55		sample_width = fmt->bBitResolution;
56		sample_bytes = fmt->bSubframeSize;
57		format = 1 << format;
58		break;
59	}
60
61	case UAC_VERSION_2: {
62		struct uac_format_type_i_ext_descriptor *fmt = _fmt;
63		sample_width = fmt->bBitResolution;
64		sample_bytes = fmt->bSubslotSize;
65
66		if (format & UAC2_FORMAT_TYPE_I_RAW_DATA)
67			pcm_formats |= SNDRV_PCM_FMTBIT_SPECIAL;
68
69		format <<= 1;
70		break;
71	}
72	}
73
74	if ((pcm_formats == 0) &&
75	    (format == 0 || format == (1 << UAC_FORMAT_TYPE_I_UNDEFINED))) {
76		/* some devices don't define this correctly... */
77		usb_audio_info(chip, "%u:%d : format type 0 is detected, processed as PCM\n",
78			fp->iface, fp->altsetting);
79		format = 1 << UAC_FORMAT_TYPE_I_PCM;
80	}
81	if (format & (1 << UAC_FORMAT_TYPE_I_PCM)) {
82		if (((chip->usb_id == USB_ID(0x0582, 0x0016)) ||
83		     /* Edirol SD-90 */
84		     (chip->usb_id == USB_ID(0x0582, 0x000c))) &&
85		     /* Roland SC-D70 */
86		    sample_width == 24 && sample_bytes == 2)
87			sample_bytes = 3;
88		else if (sample_width > sample_bytes * 8) {
89			usb_audio_info(chip, "%u:%d : sample bitwidth %d in over sample bytes %d\n",
90				 fp->iface, fp->altsetting,
91				 sample_width, sample_bytes);
92		}
93		/* check the format byte size */
94		switch (sample_bytes) {
95		case 1:
96			pcm_formats |= SNDRV_PCM_FMTBIT_S8;
97			break;
98		case 2:
99			if (snd_usb_is_big_endian_format(chip, fp))
100				pcm_formats |= SNDRV_PCM_FMTBIT_S16_BE; /* grrr, big endian!! */
101			else
102				pcm_formats |= SNDRV_PCM_FMTBIT_S16_LE;
103			break;
104		case 3:
105			if (snd_usb_is_big_endian_format(chip, fp))
106				pcm_formats |= SNDRV_PCM_FMTBIT_S24_3BE; /* grrr, big endian!! */
107			else
108				pcm_formats |= SNDRV_PCM_FMTBIT_S24_3LE;
109			break;
110		case 4:
111			pcm_formats |= SNDRV_PCM_FMTBIT_S32_LE;
112			break;
113		default:
114			usb_audio_info(chip,
115				 "%u:%d : unsupported sample bitwidth %d in %d bytes\n",
116				 fp->iface, fp->altsetting,
117				 sample_width, sample_bytes);
118			break;
119		}
120	}
121	if (format & (1 << UAC_FORMAT_TYPE_I_PCM8)) {
122		/* Dallas DS4201 workaround: it advertises U8 format, but really
123		   supports S8. */
124		if (chip->usb_id == USB_ID(0x04fa, 0x4201))
125			pcm_formats |= SNDRV_PCM_FMTBIT_S8;
126		else
127			pcm_formats |= SNDRV_PCM_FMTBIT_U8;
128	}
129	if (format & (1 << UAC_FORMAT_TYPE_I_IEEE_FLOAT)) {
130		pcm_formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
131	}
132	if (format & (1 << UAC_FORMAT_TYPE_I_ALAW)) {
133		pcm_formats |= SNDRV_PCM_FMTBIT_A_LAW;
134	}
135	if (format & (1 << UAC_FORMAT_TYPE_I_MULAW)) {
136		pcm_formats |= SNDRV_PCM_FMTBIT_MU_LAW;
137	}
138	if (format & ~0x3f) {
139		usb_audio_info(chip,
140			 "%u:%d : unsupported format bits %#x\n",
141			 fp->iface, fp->altsetting, format);
142	}
143
144	pcm_formats |= snd_usb_interface_dsd_format_quirks(chip, fp, sample_bytes);
145
146	return pcm_formats;
147}
148
149
150/*
151 * parse the format descriptor and stores the possible sample rates
152 * on the audioformat table (audio class v1).
153 *
154 * @dev: usb device
155 * @fp: audioformat record
156 * @fmt: the format descriptor
157 * @offset: the start offset of descriptor pointing the rate type
158 *          (7 for type I and II, 8 for type II)
159 */
160static int parse_audio_format_rates_v1(struct snd_usb_audio *chip, struct audioformat *fp,
161				       unsigned char *fmt, int offset)
162{
163	int nr_rates = fmt[offset];
164
165	if (fmt[0] < offset + 1 + 3 * (nr_rates ? nr_rates : 2)) {
166		usb_audio_err(chip,
167			"%u:%d : invalid UAC_FORMAT_TYPE desc\n",
168			fp->iface, fp->altsetting);
169		return -EINVAL;
170	}
171
172	if (nr_rates) {
173		/*
174		 * build the rate table and bitmap flags
175		 */
176		int r, idx;
177
178		fp->rate_table = kmalloc(sizeof(int) * nr_rates, GFP_KERNEL);
179		if (fp->rate_table == NULL) {
180			usb_audio_err(chip, "cannot malloc\n");
181			return -ENOMEM;
182		}
183
184		fp->nr_rates = 0;
185		fp->rate_min = fp->rate_max = 0;
186		for (r = 0, idx = offset + 1; r < nr_rates; r++, idx += 3) {
187			unsigned int rate = combine_triple(&fmt[idx]);
188			if (!rate)
189				continue;
190			/* C-Media CM6501 mislabels its 96 kHz altsetting */
191			/* Terratec Aureon 7.1 USB C-Media 6206, too */
192			if (rate == 48000 && nr_rates == 1 &&
193			    (chip->usb_id == USB_ID(0x0d8c, 0x0201) ||
194			     chip->usb_id == USB_ID(0x0d8c, 0x0102) ||
195			     chip->usb_id == USB_ID(0x0ccd, 0x00b1)) &&
196			    fp->altsetting == 5 && fp->maxpacksize == 392)
197				rate = 96000;
198			/* Creative VF0420/VF0470 Live Cams report 16 kHz instead of 8kHz */
199			if (rate == 16000 &&
200			    (chip->usb_id == USB_ID(0x041e, 0x4064) ||
201			     chip->usb_id == USB_ID(0x041e, 0x4068)))
202				rate = 8000;
203
204			fp->rate_table[fp->nr_rates] = rate;
205			if (!fp->rate_min || rate < fp->rate_min)
206				fp->rate_min = rate;
207			if (!fp->rate_max || rate > fp->rate_max)
208				fp->rate_max = rate;
209			fp->rates |= snd_pcm_rate_to_rate_bit(rate);
210			fp->nr_rates++;
211		}
212		if (!fp->nr_rates) {
213			hwc_debug("All rates were zero. Skipping format!\n");
214			return -EINVAL;
215		}
216	} else {
217		/* continuous rates */
218		fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
219		fp->rate_min = combine_triple(&fmt[offset + 1]);
220		fp->rate_max = combine_triple(&fmt[offset + 4]);
221	}
222	return 0;
223}
224
225/*
226 * Helper function to walk the array of sample rate triplets reported by
227 * the device. The problem is that we need to parse whole array first to
228 * get to know how many sample rates we have to expect.
229 * Then fp->rate_table can be allocated and filled.
230 */
231static int parse_uac2_sample_rate_range(struct snd_usb_audio *chip,
232					struct audioformat *fp, int nr_triplets,
233					const unsigned char *data)
234{
235	int i, nr_rates = 0;
236
237	fp->rates = fp->rate_min = fp->rate_max = 0;
238
239	for (i = 0; i < nr_triplets; i++) {
240		int min = combine_quad(&data[2 + 12 * i]);
241		int max = combine_quad(&data[6 + 12 * i]);
242		int res = combine_quad(&data[10 + 12 * i]);
243		unsigned int rate;
244
245		if ((max < 0) || (min < 0) || (res < 0) || (max < min))
246			continue;
247
248		/*
249		 * for ranges with res == 1, we announce a continuous sample
250		 * rate range, and this function should return 0 for no further
251		 * parsing.
252		 */
253		if (res == 1) {
254			fp->rate_min = min;
255			fp->rate_max = max;
256			fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
257			return 0;
258		}
259
260		for (rate = min; rate <= max; rate += res) {
261			if (fp->rate_table)
262				fp->rate_table[nr_rates] = rate;
263			if (!fp->rate_min || rate < fp->rate_min)
264				fp->rate_min = rate;
265			if (!fp->rate_max || rate > fp->rate_max)
266				fp->rate_max = rate;
267			fp->rates |= snd_pcm_rate_to_rate_bit(rate);
268
269			nr_rates++;
270			if (nr_rates >= MAX_NR_RATES) {
271				usb_audio_err(chip, "invalid uac2 rates\n");
272				break;
273			}
274
275			/* avoid endless loop */
276			if (res == 0)
277				break;
278		}
279	}
280
281	return nr_rates;
282}
283
284/*
285 * parse the format descriptor and stores the possible sample rates
286 * on the audioformat table (audio class v2).
287 */
288static int parse_audio_format_rates_v2(struct snd_usb_audio *chip,
289				       struct audioformat *fp)
290{
291	struct usb_device *dev = chip->dev;
292	unsigned char tmp[2], *data;
293	int nr_triplets, data_size, ret = 0;
294	int clock = snd_usb_clock_find_source(chip, fp->clock, false);
295
296	if (clock < 0) {
297		dev_err(&dev->dev,
298			"%s(): unable to find clock source (clock %d)\n",
299				__func__, clock);
300		goto err;
301	}
302
303	/* get the number of sample rates first by only fetching 2 bytes */
304	ret = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC2_CS_RANGE,
305			      USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
306			      UAC2_CS_CONTROL_SAM_FREQ << 8,
307			      snd_usb_ctrl_intf(chip) | (clock << 8),
308			      tmp, sizeof(tmp));
309
310	if (ret < 0) {
311		dev_err(&dev->dev,
312			"%s(): unable to retrieve number of sample rates (clock %d)\n",
313				__func__, clock);
314		goto err;
315	}
316
317	nr_triplets = (tmp[1] << 8) | tmp[0];
318	data_size = 2 + 12 * nr_triplets;
319	data = kzalloc(data_size, GFP_KERNEL);
320	if (!data) {
321		ret = -ENOMEM;
322		goto err;
323	}
324
325	/* now get the full information */
326	ret = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC2_CS_RANGE,
327			      USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
328			      UAC2_CS_CONTROL_SAM_FREQ << 8,
329			      snd_usb_ctrl_intf(chip) | (clock << 8),
330			      data, data_size);
331
332	if (ret < 0) {
333		dev_err(&dev->dev,
334			"%s(): unable to retrieve sample rate range (clock %d)\n",
335				__func__, clock);
336		ret = -EINVAL;
337		goto err_free;
338	}
339
340	/* Call the triplet parser, and make sure fp->rate_table is NULL.
341	 * We just use the return value to know how many sample rates we
342	 * will have to deal with. */
343	kfree(fp->rate_table);
344	fp->rate_table = NULL;
345	fp->nr_rates = parse_uac2_sample_rate_range(chip, fp, nr_triplets, data);
346
347	if (fp->nr_rates == 0) {
348		/* SNDRV_PCM_RATE_CONTINUOUS */
349		ret = 0;
350		goto err_free;
351	}
352
353	fp->rate_table = kmalloc(sizeof(int) * fp->nr_rates, GFP_KERNEL);
354	if (!fp->rate_table) {
355		ret = -ENOMEM;
356		goto err_free;
357	}
358
359	/* Call the triplet parser again, but this time, fp->rate_table is
360	 * allocated, so the rates will be stored */
361	parse_uac2_sample_rate_range(chip, fp, nr_triplets, data);
362
363err_free:
364	kfree(data);
365err:
366	return ret;
367}
368
369/*
370 * parse the format type I and III descriptors
371 */
372static int parse_audio_format_i(struct snd_usb_audio *chip,
373				struct audioformat *fp, unsigned int format,
374				struct uac_format_type_i_continuous_descriptor *fmt)
375{
376	snd_pcm_format_t pcm_format;
377	int ret;
378
379	if (fmt->bFormatType == UAC_FORMAT_TYPE_III) {
380		/* FIXME: the format type is really IECxxx
381		 *        but we give normal PCM format to get the existing
382		 *        apps working...
383		 */
384		switch (chip->usb_id) {
385
386		case USB_ID(0x0763, 0x2003): /* M-Audio Audiophile USB */
387			if (chip->setup == 0x00 &&
388			    fp->altsetting == 6)
389				pcm_format = SNDRV_PCM_FORMAT_S16_BE;
390			else
391				pcm_format = SNDRV_PCM_FORMAT_S16_LE;
392			break;
393		default:
394			pcm_format = SNDRV_PCM_FORMAT_S16_LE;
395		}
396		fp->formats = pcm_format_to_bits(pcm_format);
397	} else {
398		fp->formats = parse_audio_format_i_type(chip, fp, format, fmt);
399		if (!fp->formats)
400			return -EINVAL;
401	}
402
403	/* gather possible sample rates */
404	/* audio class v1 reports possible sample rates as part of the
405	 * proprietary class specific descriptor.
406	 * audio class v2 uses class specific EP0 range requests for that.
407	 */
408	switch (fp->protocol) {
409	default:
410	case UAC_VERSION_1:
411		fp->channels = fmt->bNrChannels;
412		ret = parse_audio_format_rates_v1(chip, fp, (unsigned char *) fmt, 7);
413		break;
414	case UAC_VERSION_2:
415		/* fp->channels is already set in this case */
416		ret = parse_audio_format_rates_v2(chip, fp);
417		break;
418	}
419
420	if (fp->channels < 1) {
421		usb_audio_err(chip,
422			"%u:%d : invalid channels %d\n",
423			fp->iface, fp->altsetting, fp->channels);
424		return -EINVAL;
425	}
426
427	return ret;
428}
429
430/*
431 * parse the format type II descriptor
432 */
433static int parse_audio_format_ii(struct snd_usb_audio *chip,
434				 struct audioformat *fp,
435				 int format, void *_fmt)
436{
437	int brate, framesize, ret;
438
439	switch (format) {
440	case UAC_FORMAT_TYPE_II_AC3:
441		/* FIXME: there is no AC3 format defined yet */
442		// fp->formats = SNDRV_PCM_FMTBIT_AC3;
443		fp->formats = SNDRV_PCM_FMTBIT_U8; /* temporary hack to receive byte streams */
444		break;
445	case UAC_FORMAT_TYPE_II_MPEG:
446		fp->formats = SNDRV_PCM_FMTBIT_MPEG;
447		break;
448	default:
449		usb_audio_info(chip,
450			 "%u:%d : unknown format tag %#x is detected.  processed as MPEG.\n",
451			 fp->iface, fp->altsetting, format);
452		fp->formats = SNDRV_PCM_FMTBIT_MPEG;
453		break;
454	}
455
456	fp->channels = 1;
457
458	switch (fp->protocol) {
459	default:
460	case UAC_VERSION_1: {
461		struct uac_format_type_ii_discrete_descriptor *fmt = _fmt;
462		brate = le16_to_cpu(fmt->wMaxBitRate);
463		framesize = le16_to_cpu(fmt->wSamplesPerFrame);
464		usb_audio_info(chip, "found format II with max.bitrate = %d, frame size=%d\n", brate, framesize);
465		fp->frame_size = framesize;
466		ret = parse_audio_format_rates_v1(chip, fp, _fmt, 8); /* fmt[8..] sample rates */
467		break;
468	}
469	case UAC_VERSION_2: {
470		struct uac_format_type_ii_ext_descriptor *fmt = _fmt;
471		brate = le16_to_cpu(fmt->wMaxBitRate);
472		framesize = le16_to_cpu(fmt->wSamplesPerFrame);
473		usb_audio_info(chip, "found format II with max.bitrate = %d, frame size=%d\n", brate, framesize);
474		fp->frame_size = framesize;
475		ret = parse_audio_format_rates_v2(chip, fp);
476		break;
477	}
478	}
479
480	return ret;
481}
482
483int snd_usb_parse_audio_format(struct snd_usb_audio *chip,
484			       struct audioformat *fp, unsigned int format,
485			       struct uac_format_type_i_continuous_descriptor *fmt,
486			       int stream)
487{
488	int err;
489
490	switch (fmt->bFormatType) {
491	case UAC_FORMAT_TYPE_I:
492	case UAC_FORMAT_TYPE_III:
493		err = parse_audio_format_i(chip, fp, format, fmt);
494		break;
495	case UAC_FORMAT_TYPE_II:
496		err = parse_audio_format_ii(chip, fp, format, fmt);
497		break;
498	default:
499		usb_audio_info(chip,
500			 "%u:%d : format type %d is not supported yet\n",
501			 fp->iface, fp->altsetting,
502			 fmt->bFormatType);
503		return -ENOTSUPP;
504	}
505	fp->fmt_type = fmt->bFormatType;
506	if (err < 0)
507		return err;
508#if 1
509	/* FIXME: temporary hack for extigy/audigy 2 nx/zs */
510	/* extigy apparently supports sample rates other than 48k
511	 * but not in ordinary way.  so we enable only 48k atm.
512	 */
513	if (chip->usb_id == USB_ID(0x041e, 0x3000) ||
514	    chip->usb_id == USB_ID(0x041e, 0x3020) ||
515	    chip->usb_id == USB_ID(0x041e, 0x3061)) {
516		if (fmt->bFormatType == UAC_FORMAT_TYPE_I &&
517		    fp->rates != SNDRV_PCM_RATE_48000 &&
518		    fp->rates != SNDRV_PCM_RATE_96000)
519			return -ENOTSUPP;
520	}
521#endif
522	return 0;
523}
524
525