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.
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.
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
17 #include <linux/init.h>
18 #include <linux/slab.h>
19 #include <linux/bitrev.h>
20 #include <linux/ratelimit.h>
21 #include <linux/usb.h>
22 #include <linux/usb/audio.h>
23 #include <linux/usb/audio-v2.h>
25 #include <sound/core.h>
26 #include <sound/pcm.h>
27 #include <sound/pcm_params.h>
39 #define SUBSTREAM_FLAG_DATA_EP_STARTED 0
40 #define SUBSTREAM_FLAG_SYNC_EP_STARTED 1
42 /* return the estimated delay based on USB frame counters */
43 snd_pcm_uframes_t snd_usb_pcm_delay(struct snd_usb_substream *subs,
46 int current_frame_number;
50 if (!subs->last_delay)
51 return 0; /* short path */
53 current_frame_number = usb_get_current_frame_number(subs->dev);
55 * HCD implementations use different widths, use lower 8 bits.
56 * The delay will be managed up to 256ms, which is more than
59 frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
61 /* Approximation based on number of samples per USB frame (ms),
62 some truncation for 44.1 but the estimate is good enough */
63 est_delay = frame_diff * rate / 1000;
64 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
65 est_delay = subs->last_delay - est_delay;
67 est_delay = subs->last_delay + est_delay;
75 * return the current pcm pointer. just based on the hwptr_done value.
77 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
79 struct snd_usb_substream *subs;
80 unsigned int hwptr_done;
82 subs = (struct snd_usb_substream *)substream->runtime->private_data;
83 if (subs->stream->chip->shutdown)
84 return SNDRV_PCM_POS_XRUN;
85 spin_lock(&subs->lock);
86 hwptr_done = subs->hwptr_done;
87 substream->runtime->delay = snd_usb_pcm_delay(subs,
88 substream->runtime->rate);
89 spin_unlock(&subs->lock);
90 return hwptr_done / (substream->runtime->frame_bits >> 3);
94 * find a matching audio format
96 static struct audioformat *find_format(struct snd_usb_substream *subs)
98 struct audioformat *fp;
99 struct audioformat *found = NULL;
100 int cur_attr = 0, attr;
102 list_for_each_entry(fp, &subs->fmt_list, list) {
103 if (!(fp->formats & pcm_format_to_bits(subs->pcm_format)))
105 if (fp->channels != subs->channels)
107 if (subs->cur_rate < fp->rate_min ||
108 subs->cur_rate > fp->rate_max)
110 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
112 for (i = 0; i < fp->nr_rates; i++)
113 if (fp->rate_table[i] == subs->cur_rate)
115 if (i >= fp->nr_rates)
118 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
124 /* avoid async out and adaptive in if the other method
125 * supports the same format.
126 * this is a workaround for the case like
127 * M-audio audiophile USB.
129 if (attr != cur_attr) {
130 if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
131 subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
132 (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
133 subs->direction == SNDRV_PCM_STREAM_CAPTURE))
135 if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
136 subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
137 (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
138 subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
144 /* find the format with the largest max. packet size */
145 if (fp->maxpacksize > found->maxpacksize) {
153 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
154 struct usb_host_interface *alts,
155 struct audioformat *fmt)
157 struct usb_device *dev = chip->dev;
159 unsigned char data[1];
162 ep = get_endpoint(alts, 0)->bEndpointAddress;
165 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
166 USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
167 UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
168 data, sizeof(data))) < 0) {
169 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
170 dev->devnum, iface, ep);
177 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
178 struct usb_host_interface *alts,
179 struct audioformat *fmt)
181 struct usb_device *dev = chip->dev;
182 unsigned char data[1];
186 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
187 USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
188 UAC2_EP_CS_PITCH << 8, 0,
189 data, sizeof(data))) < 0) {
190 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH (v2)\n",
191 dev->devnum, iface, fmt->altsetting);
199 * initialize the pitch control and sample rate
201 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
202 struct usb_host_interface *alts,
203 struct audioformat *fmt)
205 struct usb_interface_descriptor *altsd = get_iface_desc(alts);
207 /* if endpoint doesn't have pitch control, bail out */
208 if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
211 switch (altsd->bInterfaceProtocol) {
214 return init_pitch_v1(chip, iface, alts, fmt);
217 return init_pitch_v2(chip, iface, alts, fmt);
221 static int start_endpoints(struct snd_usb_substream *subs, bool can_sleep)
225 if (!subs->data_endpoint)
228 if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
229 struct snd_usb_endpoint *ep = subs->data_endpoint;
231 snd_printdd(KERN_DEBUG "Starting data EP @%p\n", ep);
233 ep->data_subs = subs;
234 err = snd_usb_endpoint_start(ep, can_sleep);
236 clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
241 if (subs->sync_endpoint &&
242 !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
243 struct snd_usb_endpoint *ep = subs->sync_endpoint;
245 if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
246 subs->data_endpoint->alt_idx != subs->sync_endpoint->alt_idx) {
247 err = usb_set_interface(subs->dev,
248 subs->sync_endpoint->iface,
249 subs->sync_endpoint->alt_idx);
252 "%d:%d:%d: cannot set interface (%d)\n",
254 subs->sync_endpoint->iface,
255 subs->sync_endpoint->alt_idx, err);
260 snd_printdd(KERN_DEBUG "Starting sync EP @%p\n", ep);
262 ep->sync_slave = subs->data_endpoint;
263 err = snd_usb_endpoint_start(ep, can_sleep);
265 clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
273 static void stop_endpoints(struct snd_usb_substream *subs, bool wait)
275 if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags))
276 snd_usb_endpoint_stop(subs->sync_endpoint);
278 if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
279 snd_usb_endpoint_stop(subs->data_endpoint);
282 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
283 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
287 static int deactivate_endpoints(struct snd_usb_substream *subs)
291 reta = snd_usb_endpoint_deactivate(subs->sync_endpoint);
292 retb = snd_usb_endpoint_deactivate(subs->data_endpoint);
304 * find a matching format and set up the interface
306 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
308 struct usb_device *dev = subs->dev;
309 struct usb_host_interface *alts;
310 struct usb_interface_descriptor *altsd;
311 struct usb_interface *iface;
312 unsigned int ep, attr;
313 int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
314 int err, implicit_fb = 0;
316 iface = usb_ifnum_to_if(dev, fmt->iface);
319 alts = &iface->altsetting[fmt->altset_idx];
320 altsd = get_iface_desc(alts);
321 if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
324 if (fmt == subs->cur_audiofmt)
327 /* close the old interface */
328 if (subs->interface >= 0 && subs->interface != fmt->iface) {
329 err = usb_set_interface(subs->dev, subs->interface, 0);
331 snd_printk(KERN_ERR "%d:%d:%d: return to setting 0 failed (%d)\n",
332 dev->devnum, fmt->iface, fmt->altsetting, err);
335 subs->interface = -1;
336 subs->altset_idx = 0;
340 if (subs->interface != fmt->iface ||
341 subs->altset_idx != fmt->altset_idx) {
342 err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
344 snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed (%d)\n",
345 dev->devnum, fmt->iface, fmt->altsetting, err);
348 snd_printdd(KERN_INFO "setting usb interface %d:%d\n",
349 fmt->iface, fmt->altsetting);
350 subs->interface = fmt->iface;
351 subs->altset_idx = fmt->altset_idx;
353 snd_usb_set_interface_quirk(dev);
356 subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
357 alts, fmt->endpoint, subs->direction,
358 SND_USB_ENDPOINT_TYPE_DATA);
359 if (!subs->data_endpoint)
362 /* we need a sync pipe in async OUT or adaptive IN mode */
363 /* check the number of EP, since some devices have broken
364 * descriptors which fool us. if it has only one EP,
365 * assume it as adaptive-out or sync-in.
367 attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
369 switch (subs->stream->chip->usb_id) {
370 case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
371 case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
375 iface = usb_ifnum_to_if(dev, 3);
377 if (!iface || iface->num_altsetting == 0)
380 alts = &iface->altsetting[1];
384 case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
385 case USB_ID(0x0763, 0x2081):
389 iface = usb_ifnum_to_if(dev, 2);
391 if (!iface || iface->num_altsetting == 0)
394 alts = &iface->altsetting[1];
399 if (((is_playback && attr == USB_ENDPOINT_SYNC_ASYNC) ||
400 (!is_playback && attr == USB_ENDPOINT_SYNC_ADAPTIVE)) &&
401 altsd->bNumEndpoints >= 2) {
402 /* check sync-pipe endpoint */
403 /* ... and check descriptor size before accessing bSynchAddress
404 because there is a version of the SB Audigy 2 NX firmware lacking
405 the audio fields in the endpoint descriptors */
406 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
407 (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
408 get_endpoint(alts, 1)->bSynchAddress != 0 &&
410 snd_printk(KERN_ERR "%d:%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
411 dev->devnum, fmt->iface, fmt->altsetting,
412 get_endpoint(alts, 1)->bmAttributes,
413 get_endpoint(alts, 1)->bLength,
414 get_endpoint(alts, 1)->bSynchAddress);
417 ep = get_endpoint(alts, 1)->bEndpointAddress;
419 get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
420 (( is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
421 (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
422 snd_printk(KERN_ERR "%d:%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
423 dev->devnum, fmt->iface, fmt->altsetting,
424 is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
428 implicit_fb = (get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_USAGE_MASK)
429 == USB_ENDPOINT_USAGE_IMPLICIT_FB;
432 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
433 alts, ep, !subs->direction,
435 SND_USB_ENDPOINT_TYPE_DATA :
436 SND_USB_ENDPOINT_TYPE_SYNC);
437 if (!subs->sync_endpoint)
440 subs->data_endpoint->sync_master = subs->sync_endpoint;
443 if ((err = snd_usb_init_pitch(subs->stream->chip, fmt->iface, alts, fmt)) < 0)
446 subs->cur_audiofmt = fmt;
448 snd_usb_set_format_quirk(subs, fmt);
452 "setting done: format = %d, rate = %d..%d, channels = %d\n",
453 fmt->format, fmt->rate_min, fmt->rate_max, fmt->channels);
455 " datapipe = 0x%0x, syncpipe = 0x%0x\n",
456 subs->datapipe, subs->syncpipe);
463 * Return the score of matching two audioformats.
464 * Veto the audioformat if:
465 * - It has no channels for some reason.
466 * - Requested PCM format is not supported.
467 * - Requested sample rate is not supported.
469 static int match_endpoint_audioformats(struct audioformat *fp,
470 struct audioformat *match, int rate,
471 snd_pcm_format_t pcm_format)
476 if (fp->channels < 1) {
477 snd_printdd("%s: (fmt @%p) no channels\n", __func__, fp);
481 if (!(fp->formats & pcm_format_to_bits(pcm_format))) {
482 snd_printdd("%s: (fmt @%p) no match for format %d\n", __func__,
487 for (i = 0; i < fp->nr_rates; i++) {
488 if (fp->rate_table[i] == rate) {
494 snd_printdd("%s: (fmt @%p) no match for rate %d\n", __func__,
499 if (fp->channels == match->channels)
502 snd_printdd("%s: (fmt @%p) score %d\n", __func__, fp, score);
508 * Configure the sync ep using the rate and pcm format of the data ep.
510 static int configure_sync_endpoint(struct snd_usb_substream *subs)
513 struct audioformat *fp;
514 struct audioformat *sync_fp = NULL;
516 int sync_period_bytes = subs->period_bytes;
517 struct snd_usb_substream *sync_subs =
518 &subs->stream->substream[subs->direction ^ 1];
520 if (subs->sync_endpoint->type != SND_USB_ENDPOINT_TYPE_DATA ||
522 return snd_usb_endpoint_set_params(subs->sync_endpoint,
530 /* Try to find the best matching audioformat. */
531 list_for_each_entry(fp, &sync_subs->fmt_list, list) {
532 int score = match_endpoint_audioformats(fp, subs->cur_audiofmt,
533 subs->cur_rate, subs->pcm_format);
535 if (score > cur_score) {
541 if (unlikely(sync_fp == NULL)) {
542 snd_printk(KERN_ERR "%s: no valid audioformat for sync ep %x found\n",
543 __func__, sync_subs->ep_num);
548 * Recalculate the period bytes if channel number differ between
549 * data and sync ep audioformat.
551 if (sync_fp->channels != subs->channels) {
552 sync_period_bytes = (subs->period_bytes / subs->channels) *
554 snd_printdd("%s: adjusted sync ep period bytes (%d -> %d)\n",
555 __func__, subs->period_bytes, sync_period_bytes);
558 ret = snd_usb_endpoint_set_params(subs->sync_endpoint,
570 * configure endpoint params
572 * called during initial setup and upon resume
574 static int configure_endpoint(struct snd_usb_substream *subs)
579 stop_endpoints(subs, true);
580 ret = snd_usb_endpoint_set_params(subs->data_endpoint,
586 subs->sync_endpoint);
590 if (subs->sync_endpoint)
591 ret = configure_sync_endpoint(subs);
599 * allocate a buffer and set the given audio format.
601 * so far we use a physically linear buffer although packetize transfer
602 * doesn't need a continuous area.
603 * if sg buffer is supported on the later version of alsa, we'll follow
606 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
607 struct snd_pcm_hw_params *hw_params)
609 struct snd_usb_substream *subs = substream->runtime->private_data;
610 struct audioformat *fmt;
613 ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
614 params_buffer_bytes(hw_params));
618 subs->pcm_format = params_format(hw_params);
619 subs->period_bytes = params_period_bytes(hw_params);
620 subs->channels = params_channels(hw_params);
621 subs->cur_rate = params_rate(hw_params);
623 fmt = find_format(subs);
625 snd_printd(KERN_DEBUG "cannot set format: format = %#x, rate = %d, channels = %d\n",
626 subs->pcm_format, subs->cur_rate, subs->channels);
630 down_read(&subs->stream->chip->shutdown_rwsem);
631 if (subs->stream->chip->shutdown)
634 ret = set_format(subs, fmt);
635 up_read(&subs->stream->chip->shutdown_rwsem);
639 subs->interface = fmt->iface;
640 subs->altset_idx = fmt->altset_idx;
641 subs->need_setup_ep = true;
649 * reset the audio format and release the buffer
651 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
653 struct snd_usb_substream *subs = substream->runtime->private_data;
655 subs->cur_audiofmt = NULL;
657 subs->period_bytes = 0;
658 down_read(&subs->stream->chip->shutdown_rwsem);
659 if (!subs->stream->chip->shutdown) {
660 stop_endpoints(subs, true);
661 deactivate_endpoints(subs);
663 up_read(&subs->stream->chip->shutdown_rwsem);
664 return snd_pcm_lib_free_vmalloc_buffer(substream);
670 * only a few subtle things...
672 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
674 struct snd_pcm_runtime *runtime = substream->runtime;
675 struct snd_usb_substream *subs = runtime->private_data;
676 struct usb_host_interface *alts;
677 struct usb_interface *iface;
680 if (! subs->cur_audiofmt) {
681 snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
685 down_read(&subs->stream->chip->shutdown_rwsem);
686 if (subs->stream->chip->shutdown) {
690 if (snd_BUG_ON(!subs->data_endpoint)) {
695 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
696 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
698 ret = set_format(subs, subs->cur_audiofmt);
702 iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
703 alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
704 ret = snd_usb_init_sample_rate(subs->stream->chip,
705 subs->cur_audiofmt->iface,
712 if (subs->need_setup_ep) {
713 ret = configure_endpoint(subs);
716 subs->need_setup_ep = false;
719 /* some unit conversions in runtime */
720 subs->data_endpoint->maxframesize =
721 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
722 subs->data_endpoint->curframesize =
723 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
725 /* reset the pointer */
726 subs->hwptr_done = 0;
727 subs->transfer_done = 0;
728 subs->last_delay = 0;
729 subs->last_frame_number = 0;
732 /* for playback, submit the URBs now; otherwise, the first hwptr_done
733 * updates for all URBs would happen at the same time when starting */
734 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
735 ret = start_endpoints(subs, true);
738 up_read(&subs->stream->chip->shutdown_rwsem);
742 static struct snd_pcm_hardware snd_usb_hardware =
744 .info = SNDRV_PCM_INFO_MMAP |
745 SNDRV_PCM_INFO_MMAP_VALID |
746 SNDRV_PCM_INFO_BATCH |
747 SNDRV_PCM_INFO_INTERLEAVED |
748 SNDRV_PCM_INFO_BLOCK_TRANSFER |
749 SNDRV_PCM_INFO_PAUSE,
750 .buffer_bytes_max = 1024 * 1024,
751 .period_bytes_min = 64,
752 .period_bytes_max = 512 * 1024,
757 static int hw_check_valid_format(struct snd_usb_substream *subs,
758 struct snd_pcm_hw_params *params,
759 struct audioformat *fp)
761 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
762 struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
763 struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
764 struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
765 struct snd_mask check_fmts;
768 /* check the format */
769 snd_mask_none(&check_fmts);
770 check_fmts.bits[0] = (u32)fp->formats;
771 check_fmts.bits[1] = (u32)(fp->formats >> 32);
772 snd_mask_intersect(&check_fmts, fmts);
773 if (snd_mask_empty(&check_fmts)) {
774 hwc_debug(" > check: no supported format %d\n", fp->format);
777 /* check the channels */
778 if (fp->channels < ct->min || fp->channels > ct->max) {
779 hwc_debug(" > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
782 /* check the rate is within the range */
783 if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
784 hwc_debug(" > check: rate_min %d > max %d\n", fp->rate_min, it->max);
787 if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
788 hwc_debug(" > check: rate_max %d < min %d\n", fp->rate_max, it->min);
791 /* check whether the period time is >= the data packet interval */
792 if (subs->speed != USB_SPEED_FULL) {
793 ptime = 125 * (1 << fp->datainterval);
794 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
795 hwc_debug(" > check: ptime %u > max %u\n", ptime, pt->max);
802 static int hw_rule_rate(struct snd_pcm_hw_params *params,
803 struct snd_pcm_hw_rule *rule)
805 struct snd_usb_substream *subs = rule->private;
806 struct audioformat *fp;
807 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
808 unsigned int rmin, rmax;
811 hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
814 list_for_each_entry(fp, &subs->fmt_list, list) {
815 if (!hw_check_valid_format(subs, params, fp))
818 if (rmin > fp->rate_min)
820 if (rmax < fp->rate_max)
829 hwc_debug(" --> get empty\n");
835 if (it->min < rmin) {
840 if (it->max > rmax) {
845 if (snd_interval_checkempty(it)) {
849 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
854 static int hw_rule_channels(struct snd_pcm_hw_params *params,
855 struct snd_pcm_hw_rule *rule)
857 struct snd_usb_substream *subs = rule->private;
858 struct audioformat *fp;
859 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
860 unsigned int rmin, rmax;
863 hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
866 list_for_each_entry(fp, &subs->fmt_list, list) {
867 if (!hw_check_valid_format(subs, params, fp))
870 if (rmin > fp->channels)
872 if (rmax < fp->channels)
881 hwc_debug(" --> get empty\n");
887 if (it->min < rmin) {
892 if (it->max > rmax) {
897 if (snd_interval_checkempty(it)) {
901 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
905 static int hw_rule_format(struct snd_pcm_hw_params *params,
906 struct snd_pcm_hw_rule *rule)
908 struct snd_usb_substream *subs = rule->private;
909 struct audioformat *fp;
910 struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
915 hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
917 list_for_each_entry(fp, &subs->fmt_list, list) {
918 if (!hw_check_valid_format(subs, params, fp))
920 fbits |= fp->formats;
923 oldbits[0] = fmt->bits[0];
924 oldbits[1] = fmt->bits[1];
925 fmt->bits[0] &= (u32)fbits;
926 fmt->bits[1] &= (u32)(fbits >> 32);
927 if (!fmt->bits[0] && !fmt->bits[1]) {
928 hwc_debug(" --> get empty\n");
931 changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
932 hwc_debug(" --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
936 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
937 struct snd_pcm_hw_rule *rule)
939 struct snd_usb_substream *subs = rule->private;
940 struct audioformat *fp;
941 struct snd_interval *it;
942 unsigned char min_datainterval;
946 it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
947 hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
948 min_datainterval = 0xff;
949 list_for_each_entry(fp, &subs->fmt_list, list) {
950 if (!hw_check_valid_format(subs, params, fp))
952 min_datainterval = min(min_datainterval, fp->datainterval);
954 if (min_datainterval == 0xff) {
955 hwc_debug(" --> get empty\n");
959 pmin = 125 * (1 << min_datainterval);
961 if (it->min < pmin) {
966 if (snd_interval_checkempty(it)) {
970 hwc_debug(" --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
975 * If the device supports unusual bit rates, does the request meet these?
977 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
978 struct snd_usb_substream *subs)
980 struct audioformat *fp;
982 int count = 0, needs_knot = 0;
985 kfree(subs->rate_list.list);
986 subs->rate_list.list = NULL;
988 list_for_each_entry(fp, &subs->fmt_list, list) {
989 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
991 count += fp->nr_rates;
992 if (fp->rates & SNDRV_PCM_RATE_KNOT)
998 subs->rate_list.list = rate_list =
999 kmalloc(sizeof(int) * count, GFP_KERNEL);
1000 if (!subs->rate_list.list)
1002 subs->rate_list.count = count;
1003 subs->rate_list.mask = 0;
1005 list_for_each_entry(fp, &subs->fmt_list, list) {
1007 for (i = 0; i < fp->nr_rates; i++)
1008 rate_list[count++] = fp->rate_table[i];
1010 err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1020 * set up the runtime hardware information.
1023 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1025 struct audioformat *fp;
1026 unsigned int pt, ptmin;
1027 int param_period_time_if_needed;
1030 runtime->hw.formats = subs->formats;
1032 runtime->hw.rate_min = 0x7fffffff;
1033 runtime->hw.rate_max = 0;
1034 runtime->hw.channels_min = 256;
1035 runtime->hw.channels_max = 0;
1036 runtime->hw.rates = 0;
1038 /* check min/max rates and channels */
1039 list_for_each_entry(fp, &subs->fmt_list, list) {
1040 runtime->hw.rates |= fp->rates;
1041 if (runtime->hw.rate_min > fp->rate_min)
1042 runtime->hw.rate_min = fp->rate_min;
1043 if (runtime->hw.rate_max < fp->rate_max)
1044 runtime->hw.rate_max = fp->rate_max;
1045 if (runtime->hw.channels_min > fp->channels)
1046 runtime->hw.channels_min = fp->channels;
1047 if (runtime->hw.channels_max < fp->channels)
1048 runtime->hw.channels_max = fp->channels;
1049 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1050 /* FIXME: there might be more than one audio formats... */
1051 runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1054 pt = 125 * (1 << fp->datainterval);
1055 ptmin = min(ptmin, pt);
1057 err = snd_usb_autoresume(subs->stream->chip);
1061 param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1062 if (subs->speed == USB_SPEED_FULL)
1063 /* full speed devices have fixed data packet interval */
1066 /* if period time doesn't go below 1 ms, no rules needed */
1067 param_period_time_if_needed = -1;
1068 snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1071 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1073 SNDRV_PCM_HW_PARAM_FORMAT,
1074 SNDRV_PCM_HW_PARAM_CHANNELS,
1075 param_period_time_if_needed,
1078 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1079 hw_rule_channels, subs,
1080 SNDRV_PCM_HW_PARAM_FORMAT,
1081 SNDRV_PCM_HW_PARAM_RATE,
1082 param_period_time_if_needed,
1085 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1086 hw_rule_format, subs,
1087 SNDRV_PCM_HW_PARAM_RATE,
1088 SNDRV_PCM_HW_PARAM_CHANNELS,
1089 param_period_time_if_needed,
1092 if (param_period_time_if_needed >= 0) {
1093 err = snd_pcm_hw_rule_add(runtime, 0,
1094 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1095 hw_rule_period_time, subs,
1096 SNDRV_PCM_HW_PARAM_FORMAT,
1097 SNDRV_PCM_HW_PARAM_CHANNELS,
1098 SNDRV_PCM_HW_PARAM_RATE,
1103 if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
1108 snd_usb_autosuspend(subs->stream->chip);
1112 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
1114 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1115 struct snd_pcm_runtime *runtime = substream->runtime;
1116 struct snd_usb_substream *subs = &as->substream[direction];
1118 subs->interface = -1;
1119 subs->altset_idx = 0;
1120 runtime->hw = snd_usb_hardware;
1121 runtime->private_data = subs;
1122 subs->pcm_substream = substream;
1123 /* runtime PM is also done there */
1125 /* initialize DSD/DOP context */
1126 subs->dsd_dop.byte_idx = 0;
1127 subs->dsd_dop.channel = 0;
1128 subs->dsd_dop.marker = 1;
1130 return setup_hw_info(runtime, subs);
1133 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
1135 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1136 struct snd_usb_substream *subs = &as->substream[direction];
1138 stop_endpoints(subs, true);
1140 if (!as->chip->shutdown && subs->interface >= 0) {
1141 usb_set_interface(subs->dev, subs->interface, 0);
1142 subs->interface = -1;
1145 subs->pcm_substream = NULL;
1146 snd_usb_autosuspend(subs->stream->chip);
1151 /* Since a URB can handle only a single linear buffer, we must use double
1152 * buffering when the data to be transferred overflows the buffer boundary.
1153 * To avoid inconsistencies when updating hwptr_done, we use double buffering
1156 static void retire_capture_urb(struct snd_usb_substream *subs,
1159 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1160 unsigned int stride, frames, bytes, oldptr;
1161 int i, period_elapsed = 0;
1162 unsigned long flags;
1164 int current_frame_number;
1166 /* read frame number here, update pointer in critical section */
1167 current_frame_number = usb_get_current_frame_number(subs->dev);
1169 stride = runtime->frame_bits >> 3;
1171 for (i = 0; i < urb->number_of_packets; i++) {
1172 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1173 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1174 snd_printdd(KERN_ERR "frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
1177 bytes = urb->iso_frame_desc[i].actual_length;
1178 frames = bytes / stride;
1179 if (!subs->txfr_quirk)
1180 bytes = frames * stride;
1181 if (bytes % (runtime->sample_bits >> 3) != 0) {
1182 int oldbytes = bytes;
1183 bytes = frames * stride;
1184 snd_printdd(KERN_ERR "Corrected urb data len. %d->%d\n",
1187 /* update the current pointer */
1188 spin_lock_irqsave(&subs->lock, flags);
1189 oldptr = subs->hwptr_done;
1190 subs->hwptr_done += bytes;
1191 if (subs->hwptr_done >= runtime->buffer_size * stride)
1192 subs->hwptr_done -= runtime->buffer_size * stride;
1193 frames = (bytes + (oldptr % stride)) / stride;
1194 subs->transfer_done += frames;
1195 if (subs->transfer_done >= runtime->period_size) {
1196 subs->transfer_done -= runtime->period_size;
1199 /* capture delay is by construction limited to one URB,
1202 runtime->delay = subs->last_delay = 0;
1204 /* realign last_frame_number */
1205 subs->last_frame_number = current_frame_number;
1206 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1208 spin_unlock_irqrestore(&subs->lock, flags);
1209 /* copy a data chunk */
1210 if (oldptr + bytes > runtime->buffer_size * stride) {
1211 unsigned int bytes1 =
1212 runtime->buffer_size * stride - oldptr;
1213 memcpy(runtime->dma_area + oldptr, cp, bytes1);
1214 memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1216 memcpy(runtime->dma_area + oldptr, cp, bytes);
1221 snd_pcm_period_elapsed(subs->pcm_substream);
1224 static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1225 struct urb *urb, unsigned int bytes)
1227 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1228 unsigned int stride = runtime->frame_bits >> 3;
1229 unsigned int dst_idx = 0;
1230 unsigned int src_idx = subs->hwptr_done;
1231 unsigned int wrap = runtime->buffer_size * stride;
1232 u8 *dst = urb->transfer_buffer;
1233 u8 *src = runtime->dma_area;
1234 u8 marker[] = { 0x05, 0xfa };
1237 * The DSP DOP format defines a way to transport DSD samples over
1238 * normal PCM data endpoints. It requires stuffing of marker bytes
1239 * (0x05 and 0xfa, alternating per sample frame), and then expects
1240 * 2 additional bytes of actual payload. The whole frame is stored
1243 * Hence, for a stereo transport, the buffer layout looks like this,
1244 * where L refers to left channel samples and R to right.
1246 * L1 L2 0x05 R1 R2 0x05 L3 L4 0xfa R3 R4 0xfa
1247 * L5 L6 0x05 R5 R6 0x05 L7 L8 0xfa R7 R8 0xfa
1253 if (++subs->dsd_dop.byte_idx == 3) {
1254 /* frame boundary? */
1255 dst[dst_idx++] = marker[subs->dsd_dop.marker];
1257 subs->dsd_dop.byte_idx = 0;
1259 if (++subs->dsd_dop.channel % runtime->channels == 0) {
1260 /* alternate the marker */
1261 subs->dsd_dop.marker++;
1262 subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1263 subs->dsd_dop.channel = 0;
1266 /* stuff the DSD payload */
1267 int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1269 if (subs->cur_audiofmt->dsd_bitrev)
1270 dst[dst_idx++] = bitrev8(src[idx]);
1272 dst[dst_idx++] = src[idx];
1279 static void prepare_playback_urb(struct snd_usb_substream *subs,
1282 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1283 struct snd_usb_endpoint *ep = subs->data_endpoint;
1284 struct snd_urb_ctx *ctx = urb->context;
1285 unsigned int counts, frames, bytes;
1286 int i, stride, period_elapsed = 0;
1287 unsigned long flags;
1289 stride = runtime->frame_bits >> 3;
1292 urb->number_of_packets = 0;
1293 spin_lock_irqsave(&subs->lock, flags);
1294 for (i = 0; i < ctx->packets; i++) {
1295 if (ctx->packet_size[i])
1296 counts = ctx->packet_size[i];
1298 counts = snd_usb_endpoint_next_packet_size(ep);
1300 /* set up descriptor */
1301 urb->iso_frame_desc[i].offset = frames * ep->stride;
1302 urb->iso_frame_desc[i].length = counts * ep->stride;
1304 urb->number_of_packets++;
1305 subs->transfer_done += counts;
1306 if (subs->transfer_done >= runtime->period_size) {
1307 subs->transfer_done -= runtime->period_size;
1309 if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1310 if (subs->transfer_done > 0) {
1311 /* FIXME: fill-max mode is not
1313 frames -= subs->transfer_done;
1314 counts -= subs->transfer_done;
1315 urb->iso_frame_desc[i].length =
1316 counts * ep->stride;
1317 subs->transfer_done = 0;
1320 if (i < ctx->packets) {
1321 /* add a transfer delimiter */
1322 urb->iso_frame_desc[i].offset =
1323 frames * ep->stride;
1324 urb->iso_frame_desc[i].length = 0;
1325 urb->number_of_packets++;
1330 if (period_elapsed &&
1331 !snd_usb_endpoint_implicit_feedback_sink(subs->data_endpoint)) /* finish at the period boundary */
1334 bytes = frames * ep->stride;
1336 if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1337 subs->cur_audiofmt->dsd_dop)) {
1338 fill_playback_urb_dsd_dop(subs, urb, bytes);
1339 } else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1340 subs->cur_audiofmt->dsd_bitrev)) {
1341 /* bit-reverse the bytes */
1342 u8 *buf = urb->transfer_buffer;
1343 for (i = 0; i < bytes; i++) {
1344 int idx = (subs->hwptr_done + i)
1345 % (runtime->buffer_size * stride);
1346 buf[i] = bitrev8(runtime->dma_area[idx]);
1349 subs->hwptr_done += bytes;
1352 if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1353 /* err, the transferred area goes over buffer boundary. */
1354 unsigned int bytes1 =
1355 runtime->buffer_size * stride - subs->hwptr_done;
1356 memcpy(urb->transfer_buffer,
1357 runtime->dma_area + subs->hwptr_done, bytes1);
1358 memcpy(urb->transfer_buffer + bytes1,
1359 runtime->dma_area, bytes - bytes1);
1361 memcpy(urb->transfer_buffer,
1362 runtime->dma_area + subs->hwptr_done, bytes);
1365 subs->hwptr_done += bytes;
1368 if (subs->hwptr_done >= runtime->buffer_size * stride)
1369 subs->hwptr_done -= runtime->buffer_size * stride;
1371 /* update delay with exact number of samples queued */
1372 runtime->delay = subs->last_delay;
1373 runtime->delay += frames;
1374 subs->last_delay = runtime->delay;
1376 /* realign last_frame_number */
1377 subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1378 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1380 spin_unlock_irqrestore(&subs->lock, flags);
1381 urb->transfer_buffer_length = bytes;
1383 snd_pcm_period_elapsed(subs->pcm_substream);
1387 * process after playback data complete
1388 * - decrease the delay count again
1390 static void retire_playback_urb(struct snd_usb_substream *subs,
1393 unsigned long flags;
1394 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1395 struct snd_usb_endpoint *ep = subs->data_endpoint;
1396 int processed = urb->transfer_buffer_length / ep->stride;
1399 /* ignore the delay accounting when procssed=0 is given, i.e.
1400 * silent payloads are procssed before handling the actual data
1405 spin_lock_irqsave(&subs->lock, flags);
1406 if (!subs->last_delay)
1407 goto out; /* short path */
1409 est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1410 /* update delay with exact number of samples played */
1411 if (processed > subs->last_delay)
1412 subs->last_delay = 0;
1414 subs->last_delay -= processed;
1415 runtime->delay = subs->last_delay;
1418 * Report when delay estimate is off by more than 2ms.
1419 * The error should be lower than 2ms since the estimate relies
1420 * on two reads of a counter updated every ms.
1422 if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1423 snd_printk(KERN_DEBUG "delay: estimated %d, actual %d\n",
1424 est_delay, subs->last_delay);
1426 if (!subs->running) {
1427 /* update last_frame_number for delay counting here since
1428 * prepare_playback_urb won't be called during pause
1430 subs->last_frame_number =
1431 usb_get_current_frame_number(subs->dev) & 0xff;
1435 spin_unlock_irqrestore(&subs->lock, flags);
1438 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
1440 return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
1443 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
1445 return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1448 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
1450 return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
1453 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
1455 return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1458 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1461 struct snd_usb_substream *subs = substream->runtime->private_data;
1464 case SNDRV_PCM_TRIGGER_START:
1465 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1466 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1467 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1470 case SNDRV_PCM_TRIGGER_STOP:
1471 stop_endpoints(subs, false);
1474 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1475 subs->data_endpoint->prepare_data_urb = NULL;
1476 /* keep retire_data_urb for delay calculation */
1477 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1485 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1489 struct snd_usb_substream *subs = substream->runtime->private_data;
1492 case SNDRV_PCM_TRIGGER_START:
1493 err = start_endpoints(subs, false);
1497 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1500 case SNDRV_PCM_TRIGGER_STOP:
1501 stop_endpoints(subs, false);
1504 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1505 subs->data_endpoint->retire_data_urb = NULL;
1508 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1509 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1517 static struct snd_pcm_ops snd_usb_playback_ops = {
1518 .open = snd_usb_playback_open,
1519 .close = snd_usb_playback_close,
1520 .ioctl = snd_pcm_lib_ioctl,
1521 .hw_params = snd_usb_hw_params,
1522 .hw_free = snd_usb_hw_free,
1523 .prepare = snd_usb_pcm_prepare,
1524 .trigger = snd_usb_substream_playback_trigger,
1525 .pointer = snd_usb_pcm_pointer,
1526 .page = snd_pcm_lib_get_vmalloc_page,
1527 .mmap = snd_pcm_lib_mmap_vmalloc,
1530 static struct snd_pcm_ops snd_usb_capture_ops = {
1531 .open = snd_usb_capture_open,
1532 .close = snd_usb_capture_close,
1533 .ioctl = snd_pcm_lib_ioctl,
1534 .hw_params = snd_usb_hw_params,
1535 .hw_free = snd_usb_hw_free,
1536 .prepare = snd_usb_pcm_prepare,
1537 .trigger = snd_usb_substream_capture_trigger,
1538 .pointer = snd_usb_pcm_pointer,
1539 .page = snd_pcm_lib_get_vmalloc_page,
1540 .mmap = snd_pcm_lib_mmap_vmalloc,
1543 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1545 snd_pcm_set_ops(pcm, stream,
1546 stream == SNDRV_PCM_STREAM_PLAYBACK ?
1547 &snd_usb_playback_ops : &snd_usb_capture_ops);