em28xx-audio.c 24.7 KB
Newer Older
1 2 3 4 5
/*
 *  Empiatech em28x1 audio extension
 *
 *  Copyright (C) 2006 Markus Rechberger <mrechberger@gmail.com>
 *
6
 *  Copyright (C) 2007-2014 Mauro Carvalho Chehab
7
 *	- Port to work with the in-kernel driver
8
 *	- Cleanups, fixes, alsa-controls, etc.
9
 *
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *  This driver is based on my previous au600 usb pstn audio driver
 *  and inherits all the copyrights
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <linux/kernel.h>
#include <linux/usb.h>
#include <linux/init.h>
#include <linux/sound.h>
#include <linux/spinlock.h>
#include <linux/soundcard.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
37
#include <linux/module.h>
38 39 40 41 42 43
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/info.h>
#include <sound/initval.h>
#include <sound/control.h>
44
#include <sound/tlv.h>
45
#include <sound/ac97_codec.h>
46 47 48
#include <media/v4l2-common.h>
#include "em28xx.h"

49 50 51
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "activates debug info");
52

53 54
#define EM28XX_MAX_AUDIO_BUFS		5
#define EM28XX_MIN_AUDIO_PACKETS	64
55

56 57 58
#define dprintk(fmt, arg...) do {					\
	    if (debug)							\
		printk(KERN_INFO "em28xx-audio %s: " fmt,		\
59
				  __func__, ##arg); 		\
60
	} while (0)
61

62
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
63

64
static int em28xx_deinit_isoc_audio(struct em28xx *dev)
65
{
66
	int i;
67

68
	dprintk("Stopping isoc\n");
69
	for (i = 0; i < dev->adev.num_urb; i++) {
70 71
		struct urb *urb = dev->adev.urb[i];

72
		if (!irqs_disabled())
73
			usb_kill_urb(urb);
74
		else
75
			usb_unlink_urb(urb);
76 77 78 79 80 81 82
	}

	return 0;
}

static void em28xx_audio_isocirq(struct urb *urb)
{
83 84 85 86 87 88 89
	struct em28xx            *dev = urb->context;
	int                      i;
	unsigned int             oldptr;
	int                      period_elapsed = 0;
	int                      status;
	unsigned char            *cp;
	unsigned int             stride;
90
	struct snd_pcm_substream *substream;
91
	struct snd_pcm_runtime   *runtime;
92

93 94 95 96 97 98
	if (dev->disconnected) {
		dprintk("device disconnected while streaming. URB status=%d.\n", urb->status);
		atomic_set(&dev->stream_started, 0);
		return;
	}

99 100 101 102 103 104 105 106 107 108 109 110 111
	switch (urb->status) {
	case 0:             /* success */
	case -ETIMEDOUT:    /* NAK */
		break;
	case -ECONNRESET:   /* kill */
	case -ENOENT:
	case -ESHUTDOWN:
		return;
	default:            /* error */
		dprintk("urb completition error %d.\n", urb->status);
		break;
	}

112 113 114
	if (atomic_read(&dev->stream_started) == 0)
		return;

115 116
	if (dev->adev.capture_pcm_substream) {
		substream = dev->adev.capture_pcm_substream;
117
		runtime = substream->runtime;
118
		stride = runtime->frame_bits >> 3;
119

120 121 122 123 124
		for (i = 0; i < urb->number_of_packets; i++) {
			int length =
			    urb->iso_frame_desc[i].actual_length / stride;
			cp = (unsigned char *)urb->transfer_buffer +
			    urb->iso_frame_desc[i].offset;
125

126
			if (!length)
127 128
				continue;

129
			oldptr = dev->adev.hwptr_done_capture;
130 131 132 133 134 135 136 137 138 139 140 141 142 143
			if (oldptr + length >= runtime->buffer_size) {
				unsigned int cnt =
				    runtime->buffer_size - oldptr;
				memcpy(runtime->dma_area + oldptr * stride, cp,
				       cnt * stride);
				memcpy(runtime->dma_area, cp + cnt * stride,
				       length * stride - cnt * stride);
			} else {
				memcpy(runtime->dma_area + oldptr * stride, cp,
				       length * stride);
			}

			snd_pcm_stream_lock(substream);

144 145
			dev->adev.hwptr_done_capture += length;
			if (dev->adev.hwptr_done_capture >=
146
			    runtime->buffer_size)
147
				dev->adev.hwptr_done_capture -=
148
				    runtime->buffer_size;
149

150 151
			dev->adev.capture_transfer_done += length;
			if (dev->adev.capture_transfer_done >=
152
			    runtime->period_size) {
153
				dev->adev.capture_transfer_done -=
154 155
				    runtime->period_size;
				period_elapsed = 1;
156
			}
157

158
			snd_pcm_stream_unlock(substream);
159
		}
160
		if (period_elapsed)
161 162 163
			snd_pcm_period_elapsed(substream);
	}
	urb->status = 0;
164

165 166
	status = usb_submit_urb(urb, GFP_ATOMIC);
	if (status < 0) {
167 168
		em28xx_errdev("resubmit of audio urb failed (error=%i)\n",
			      status);
169 170 171 172 173 174
	}
	return;
}

static int em28xx_init_audio_isoc(struct em28xx *dev)
{
175 176 177
	int       i, errCode;

	dprintk("Starting isoc transfers\n");
178

179
	/* Start streaming */
180
	for (i = 0; i < dev->adev.num_urb; i++) {
181 182
		memset(dev->adev.transfer_buffer[i], 0x80,
		       dev->adev.urb[i]->transfer_buffer_length);
183

184
		errCode = usb_submit_urb(dev->adev.urb[i], GFP_ATOMIC);
185
		if (errCode) {
186
			em28xx_errdev("submit of audio urb failed\n");
187
			em28xx_deinit_isoc_audio(dev);
188
			atomic_set(&dev->stream_started, 0);
189 190
			return errCode;
		}
191

192
	}
193

194 195 196
	return 0;
}

197 198 199 200 201
static int snd_pcm_alloc_vmalloc_buffer(struct snd_pcm_substream *subs,
					size_t size)
{
	struct snd_pcm_runtime *runtime = subs->runtime;

202
	dprintk("Allocating vbuffer\n");
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	if (runtime->dma_area) {
		if (runtime->dma_bytes > size)
			return 0;

		vfree(runtime->dma_area);
	}
	runtime->dma_area = vmalloc(size);
	if (!runtime->dma_area)
		return -ENOMEM;

	runtime->dma_bytes = size;

	return 0;
}

static struct snd_pcm_hardware snd_em28xx_hw_capture = {
	.info = SNDRV_PCM_INFO_BLOCK_TRANSFER |
		SNDRV_PCM_INFO_MMAP           |
		SNDRV_PCM_INFO_INTERLEAVED    |
222
		SNDRV_PCM_INFO_BATCH	      |
223 224 225 226
		SNDRV_PCM_INFO_MMAP_VALID,

	.formats = SNDRV_PCM_FMTBIT_S16_LE,

227
	.rates = SNDRV_PCM_RATE_48000,
228 229 230 231 232 233

	.rate_min = 48000,
	.rate_max = 48000,
	.channels_min = 2,
	.channels_max = 2,
	.buffer_bytes_max = 62720 * 8,	/* just about the value in usbaudio.c */
234 235 236 237 238 239 240 241 242 243 244 245 246


	/*
	 * The period is 12.288 bytes. Allow a 10% of variation along its
	 * value, in order to avoid overruns/underruns due to some clock
	 * drift.
	 *
	 * FIXME: This period assumes 64 packets, and a 48000 PCM rate.
	 * Calculate it dynamically.
	 */
	.period_bytes_min = 11059,
	.period_bytes_max = 13516,

247 248 249 250 251 252 253 254 255 256
	.periods_min = 2,
	.periods_max = 98,		/* 12544, */
};

static int snd_em28xx_capture_open(struct snd_pcm_substream *substream)
{
	struct em28xx *dev = snd_pcm_substream_chip(substream);
	struct snd_pcm_runtime *runtime = substream->runtime;
	int ret = 0;

257
	if (!dev) {
258
		em28xx_err("BUG: em28xx can't find device struct."
259 260 261 262
				" Can't proceed with open\n");
		return -ENODEV;
	}

263 264 265 266 267
	if (dev->disconnected)
		return -ENODEV;

	dprintk("opening device and trying to acquire exclusive lock\n");

268 269
	runtime->hw = snd_em28xx_hw_capture;
	if ((dev->alt == 0 || dev->audio_ifnum) && dev->adev.users == 0) {
270 271 272 273 274 275 276
		int nonblock = !!(substream->f_flags & O_NONBLOCK);

		if (nonblock) {
			if (!mutex_trylock(&dev->lock))
				return -EAGAIN;
		} else
			mutex_lock(&dev->lock);
277 278 279 280
		if (dev->audio_ifnum)
			dev->alt = 1;
		else
			dev->alt = 7;
281

282 283 284
		dprintk("changing alternate number on interface %d to %d\n",
			dev->audio_ifnum, dev->alt);
		usb_set_interface(dev->udev, dev->audio_ifnum, dev->alt);
285

286 287 288 289 290
		/* Sets volume, mute, etc */
		dev->mute = 0;
		ret = em28xx_audio_analog_set(dev);
		if (ret < 0)
			goto err;
291

292 293 294
		dev->adev.users++;
		mutex_unlock(&dev->lock);
	}
295 296

	snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
297
	dev->adev.capture_pcm_substream = substream;
298 299 300

	return 0;
err:
301 302
	mutex_unlock(&dev->lock);

303
	em28xx_err("Error while configuring em28xx mixer\n");
304 305 306 307 308 309 310 311 312 313
	return ret;
}

static int snd_em28xx_pcm_close(struct snd_pcm_substream *substream)
{
	struct em28xx *dev = snd_pcm_substream_chip(substream);

	dprintk("closing device\n");

	dev->mute = 1;
314
	mutex_lock(&dev->lock);
315
	dev->adev.users--;
316 317 318 319 320
	if (atomic_read(&dev->stream_started) > 0) {
		atomic_set(&dev->stream_started, 0);
		schedule_work(&dev->wq_trigger);
	}

321
	em28xx_audio_analog_set(dev);
322 323 324 325 326
	if (substream->runtime->dma_area) {
		dprintk("freeing\n");
		vfree(substream->runtime->dma_area);
		substream->runtime->dma_area = NULL;
	}
327
	mutex_unlock(&dev->lock);
328 329 330 331 332 333 334 335

	return 0;
}

static int snd_em28xx_hw_capture_params(struct snd_pcm_substream *substream,
					struct snd_pcm_hw_params *hw_params)
{
	int ret;
336 337 338 339
	struct em28xx *dev = snd_pcm_substream_chip(substream);

	if (dev->disconnected)
		return -ENODEV;
340 341 342 343 344

	dprintk("Setting capture parameters\n");

	ret = snd_pcm_alloc_vmalloc_buffer(substream,
				params_buffer_bytes(hw_params));
345 346
	if (ret < 0)
		return ret;
347 348 349 350 351 352
#if 0
	/* TODO: set up em28xx audio chip to deliver the correct audio format,
	   current default is 48000hz multiplexed => 96000hz mono
	   which shouldn't matter since analogue TV only supports mono */
	unsigned int channels, rate, format;

353 354 355
	format = params_format(hw_params);
	rate = params_rate(hw_params);
	channels = params_channels(hw_params);
356
#endif
357 358 359 360 361 362 363 364 365 366

	return 0;
}

static int snd_em28xx_hw_capture_free(struct snd_pcm_substream *substream)
{
	struct em28xx *dev = snd_pcm_substream_chip(substream);

	dprintk("Stop capture, if needed\n");

367 368 369 370
	if (atomic_read(&dev->stream_started) > 0) {
		atomic_set(&dev->stream_started, 0);
		schedule_work(&dev->wq_trigger);
	}
371 372 373 374 375 376

	return 0;
}

static int snd_em28xx_prepare(struct snd_pcm_substream *substream)
{
377 378
	struct em28xx *dev = snd_pcm_substream_chip(substream);

379 380 381
	if (dev->disconnected)
		return -ENODEV;

382 383 384
	dev->adev.hwptr_done_capture = 0;
	dev->adev.capture_transfer_done = 0;

385 386 387
	return 0;
}

388 389 390 391 392 393 394 395 396 397 398 399 400
static void audio_trigger(struct work_struct *work)
{
	struct em28xx *dev = container_of(work, struct em28xx, wq_trigger);

	if (atomic_read(&dev->stream_started)) {
		dprintk("starting capture");
		em28xx_init_audio_isoc(dev);
	} else {
		dprintk("stopping capture");
		em28xx_deinit_isoc_audio(dev);
	}
}

401 402 403 404
static int snd_em28xx_capture_trigger(struct snd_pcm_substream *substream,
				      int cmd)
{
	struct em28xx *dev = snd_pcm_substream_chip(substream);
405
	int retval = 0;
406

407 408 409
	if (dev->disconnected)
		return -ENODEV;

410
	switch (cmd) {
411 412
	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: /* fall through */
	case SNDRV_PCM_TRIGGER_RESUME: /* fall through */
413
	case SNDRV_PCM_TRIGGER_START:
414
		atomic_set(&dev->stream_started, 1);
415
		break;
416 417
	case SNDRV_PCM_TRIGGER_PAUSE_PUSH: /* fall through */
	case SNDRV_PCM_TRIGGER_SUSPEND: /* fall through */
418
	case SNDRV_PCM_TRIGGER_STOP:
419
		atomic_set(&dev->stream_started, 0);
420
		break;
421
	default:
422
		retval = -EINVAL;
423
	}
424
	schedule_work(&dev->wq_trigger);
425
	return retval;
426 427
}

428 429
static snd_pcm_uframes_t snd_em28xx_capture_pointer(struct snd_pcm_substream
						    *substream)
430
{
431
	unsigned long flags;
432
	struct em28xx *dev;
433
	snd_pcm_uframes_t hwptr_done;
434

435
	dev = snd_pcm_substream_chip(substream);
436 437 438
	if (dev->disconnected)
		return -ENODEV;

439
	spin_lock_irqsave(&dev->adev.slock, flags);
440
	hwptr_done = dev->adev.hwptr_done_capture;
441
	spin_unlock_irqrestore(&dev->adev.slock, flags);
442

443 444 445 446 447 448 449
	return hwptr_done;
}

static struct page *snd_pcm_get_vmalloc_page(struct snd_pcm_substream *subs,
					     unsigned long offset)
{
	void *pageptr = subs->runtime->dma_area + offset;
450

451 452 453
	return vmalloc_to_page(pageptr);
}

454 455 456 457 458 459
/*
 * AC97 volume control support
 */
static int em28xx_vol_info(struct snd_kcontrol *kcontrol,
				struct snd_ctl_elem_info *info)
{
460 461 462 463 464
	struct em28xx *dev = snd_kcontrol_chip(kcontrol);

	if (dev->disconnected)
		return -ENODEV;

465 466 467 468 469 470 471 472 473 474 475 476
	info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
	info->count = 2;
	info->value.integer.min = 0;
	info->value.integer.max = 0x1f;

	return 0;
}

static int em28xx_vol_put(struct snd_kcontrol *kcontrol,
			       struct snd_ctl_elem_value *value)
{
	struct em28xx *dev = snd_kcontrol_chip(kcontrol);
477
	struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
478 479
	u16 val = (0x1f - (value->value.integer.value[0] & 0x1f)) |
		  (0x1f - (value->value.integer.value[1] & 0x1f)) << 8;
480
	int nonblock = 0;
481 482
	int rc;

483 484 485
	if (dev->disconnected)
		return -ENODEV;

486 487 488 489 490 491 492
	if (substream)
		nonblock = !!(substream->f_flags & O_NONBLOCK);
	if (nonblock) {
		if (!mutex_trylock(&dev->lock))
			return -EAGAIN;
	} else
		mutex_lock(&dev->lock);
493 494 495 496
	rc = em28xx_read_ac97(dev, kcontrol->private_value);
	if (rc < 0)
		goto err;

497
	val |= rc & 0x8000;	/* Preserve the mute flag */
498 499

	rc = em28xx_write_ac97(dev, kcontrol->private_value, val);
500 501 502 503 504 505 506
	if (rc < 0)
		goto err;

	dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n",
		(val & 0x8000) ? "muted " : "",
		0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
		val, (int)kcontrol->private_value);
507 508 509 510 511 512 513 514 515 516

err:
	mutex_unlock(&dev->lock);
	return rc;
}

static int em28xx_vol_get(struct snd_kcontrol *kcontrol,
			       struct snd_ctl_elem_value *value)
{
	struct em28xx *dev = snd_kcontrol_chip(kcontrol);
517 518
	struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
	int nonblock = 0;
519 520
	int val;

521 522 523
	if (dev->disconnected)
		return -ENODEV;

524 525 526 527 528 529 530
	if (substream)
		nonblock = !!(substream->f_flags & O_NONBLOCK);
	if (nonblock) {
		if (!mutex_trylock(&dev->lock))
			return -EAGAIN;
	} else
		mutex_lock(&dev->lock);
531 532 533 534 535
	val = em28xx_read_ac97(dev, kcontrol->private_value);
	mutex_unlock(&dev->lock);
	if (val < 0)
		return val;

536 537 538 539 540
	dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n",
		(val & 0x8000) ? "muted " : "",
		0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
		val, (int)kcontrol->private_value);

541 542
	value->value.integer.value[0] = 0x1f - (val & 0x1f);
	value->value.integer.value[1] = 0x1f - ((val << 8) & 0x1f);
543 544 545 546

	return 0;
}

547 548 549 550 551
static int em28xx_vol_put_mute(struct snd_kcontrol *kcontrol,
			       struct snd_ctl_elem_value *value)
{
	struct em28xx *dev = snd_kcontrol_chip(kcontrol);
	u16 val = value->value.integer.value[0];
552 553
	struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
	int nonblock = 0;
554 555
	int rc;

556 557 558
	if (dev->disconnected)
		return -ENODEV;

559 560 561 562 563 564 565
	if (substream)
		nonblock = !!(substream->f_flags & O_NONBLOCK);
	if (nonblock) {
		if (!mutex_trylock(&dev->lock))
			return -EAGAIN;
	} else
		mutex_lock(&dev->lock);
566 567 568 569 570
	rc = em28xx_read_ac97(dev, kcontrol->private_value);
	if (rc < 0)
		goto err;

	if (val)
571
		rc &= 0x1f1f;
572
	else
573
		rc |= 0x8000;
574 575

	rc = em28xx_write_ac97(dev, kcontrol->private_value, rc);
576 577 578 579 580 581 582
	if (rc < 0)
		goto err;

	dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n",
		(val & 0x8000) ? "muted " : "",
		0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
		val, (int)kcontrol->private_value);
583 584 585 586 587 588 589 590 591 592

err:
	mutex_unlock(&dev->lock);
	return rc;
}

static int em28xx_vol_get_mute(struct snd_kcontrol *kcontrol,
			       struct snd_ctl_elem_value *value)
{
	struct em28xx *dev = snd_kcontrol_chip(kcontrol);
593 594
	struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
	int nonblock = 0;
595 596
	int val;

597 598 599
	if (dev->disconnected)
		return -ENODEV;

600 601 602 603 604 605 606
	if (substream)
		nonblock = !!(substream->f_flags & O_NONBLOCK);
	if (nonblock) {
		if (!mutex_trylock(&dev->lock))
			return -EAGAIN;
	} else
		mutex_lock(&dev->lock);
607 608 609 610 611 612 613
	val = em28xx_read_ac97(dev, kcontrol->private_value);
	mutex_unlock(&dev->lock);
	if (val < 0)
		return val;

	if (val & 0x8000)
		value->value.integer.value[0] = 0;
614 615
	else
		value->value.integer.value[0] = 1;
616

617 618 619 620 621
	dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n",
		(val & 0x8000) ? "muted " : "",
		0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
		val, (int)kcontrol->private_value);

622 623 624
	return 0;
}

625 626 627 628 629 630
static const DECLARE_TLV_DB_SCALE(em28xx_db_scale, -3450, 150, 0);

static int em28xx_cvol_new(struct snd_card *card, struct em28xx *dev,
			   char *name, int id)
{
	int err;
631
	char ctl_name[44];
632
	struct snd_kcontrol *kctl;
633 634 635 636 637 638 639 640 641 642 643 644
	struct snd_kcontrol_new tmp;

	memset (&tmp, 0, sizeof(tmp));
	tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
	tmp.private_value = id,
	tmp.name  = ctl_name,

	/* Add Mute Control */
	sprintf(ctl_name, "%s Switch", name);
	tmp.get  = em28xx_vol_get_mute;
	tmp.put  = em28xx_vol_put_mute;
	tmp.info = snd_ctl_boolean_mono_info;
645
	kctl = snd_ctl_new1(&tmp, dev);
646 647 648
	err = snd_ctl_add(card, kctl);
	if (err < 0)
		return err;
649 650
	dprintk("Added control %s for ac97 volume control 0x%04x\n",
		ctl_name, id);
651

652 653 654 655 656 657 658 659 660 661 662 663
	memset (&tmp, 0, sizeof(tmp));
	tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
	tmp.private_value = id,
	tmp.name  = ctl_name,

	/* Add Volume Control */
	sprintf(ctl_name, "%s Volume", name);
	tmp.get   = em28xx_vol_get;
	tmp.put   = em28xx_vol_put;
	tmp.info  = em28xx_vol_info;
	tmp.tlv.p = em28xx_db_scale,
	kctl = snd_ctl_new1(&tmp, dev);
664 665 666
	err = snd_ctl_add(card, kctl);
	if (err < 0)
		return err;
667 668
	dprintk("Added control %s for ac97 volume control 0x%04x\n",
		ctl_name, id);
669 670 671 672 673 674 675

	return 0;
}

/*
 * register/unregister code and data
 */
676
static struct snd_pcm_ops snd_em28xx_pcm_capture = {
677 678 679
	.open      = snd_em28xx_capture_open,
	.close     = snd_em28xx_pcm_close,
	.ioctl     = snd_pcm_lib_ioctl,
680
	.hw_params = snd_em28xx_hw_capture_params,
681 682 683 684 685
	.hw_free   = snd_em28xx_hw_capture_free,
	.prepare   = snd_em28xx_prepare,
	.trigger   = snd_em28xx_capture_trigger,
	.pointer   = snd_em28xx_capture_pointer,
	.page      = snd_pcm_get_vmalloc_page,
686 687
};

688 689 690 691
static void em28xx_audio_free_urb(struct em28xx *dev)
{
	int i;

692
	for (i = 0; i < dev->adev.num_urb; i++) {
693 694
		struct urb *urb = dev->adev.urb[i];

695
		if (!urb)
696 697
			continue;

698 699 700 701 702
		if (dev->adev.transfer_buffer[i])
			usb_free_coherent(dev->udev,
					  urb->transfer_buffer_length,
					  dev->adev.transfer_buffer[i],
					  urb->transfer_dma);
703 704 705

		usb_free_urb(urb);
	}
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
	kfree(dev->adev.urb);
	kfree(dev->adev.transfer_buffer);
	dev->adev.num_urb = 0;
}

/* high bandwidth multiplier, as encoded in highspeed endpoint descriptors */
static int em28xx_audio_ep_packet_size(struct usb_device *udev,
					struct usb_endpoint_descriptor *e)
{
	int size = le16_to_cpu(e->wMaxPacketSize);

	if (udev->speed == USB_SPEED_HIGH)
		return (size & 0x7ff) *  (1 + (((size) >> 11) & 0x03));

	return size & 0x7ff;
721 722
}

723
static int em28xx_audio_urb_init(struct em28xx *dev)
724
{
725 726
	struct usb_interface *intf;
	struct usb_endpoint_descriptor *e, *ep = NULL;
727
	int                 i, ep_size, interval, num_urb, npackets;
728
	int		    urb_size, bytes_per_transfer;
729
	u8 alt;
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
	if (dev->audio_ifnum)
		alt = 1;
	else
		alt = 7;

	intf = usb_ifnum_to_if(dev->udev, dev->audio_ifnum);

	if (intf->num_altsetting <= alt) {
		em28xx_errdev("alt %d doesn't exist on interface %d\n",
			      dev->audio_ifnum, alt);
		return -ENODEV;
	}

	for (i = 0; i < intf->altsetting[alt].desc.bNumEndpoints; i++) {
		e = &intf->altsetting[alt].endpoint[i].desc;
		if (!usb_endpoint_dir_in(e))
			continue;
		if (e->bEndpointAddress == EM28XX_EP_AUDIO) {
			ep = e;
			break;
		}
	}

	if (!ep) {
		em28xx_errdev("Couldn't find an audio endpoint");
		return -ENODEV;
	}

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
	ep_size = em28xx_audio_ep_packet_size(dev->udev, ep);
	interval = 1 << (ep->bInterval - 1);

	em28xx_info("Endpoint 0x%02x %s on intf %d alt %d interval = %d, size %d\n",
		     EM28XX_EP_AUDIO, usb_speed_string(dev->udev->speed),
		     dev->audio_ifnum, alt,
		     interval,
		     ep_size);

	/* Calculate the number and size of URBs to better fit the audio samples */

	/*
	 * Estimate the number of bytes per DMA transfer.
	 *
	 * This is given by the bit rate (for now, only 48000 Hz) multiplied
	 * by 2 channels and 2 bytes/sample divided by the number of microframe
	 * intervals and by the microframe rate (125 us)
	 */
	bytes_per_transfer = DIV_ROUND_UP(48000 * 2 * 2, 125 * interval);

	/*
	 * Estimate the number of transfer URBs. Don't let it go past the
	 * maximum number of URBs that is known to be supported by the device.
	 */
	num_urb = DIV_ROUND_UP(bytes_per_transfer, ep_size);
	if (num_urb > EM28XX_MAX_AUDIO_BUFS)
		num_urb = EM28XX_MAX_AUDIO_BUFS;

	/*
	 * Now that we know the number of bytes per transfer and the number of
	 * URBs, estimate the typical size of an URB, in order to adjust the
	 * minimal number of packets.
	 */
	urb_size = bytes_per_transfer / num_urb;

	/*
	 * Now, calculate the amount of audio packets to be filled on each
	 * URB. In order to preserve the old behaviour, use a minimal
	 * threshold for this value.
	 */
	npackets = EM28XX_MIN_AUDIO_PACKETS;
	if (urb_size > ep_size * npackets)
		npackets = DIV_ROUND_UP(urb_size, ep_size);

	em28xx_info("Number of URBs: %d, with %d packets and %d size",
		    num_urb, npackets, urb_size);

	/* Allocate space to store the number of URBs to be used */

	dev->adev.transfer_buffer = kcalloc(num_urb,
					    sizeof(*dev->adev.transfer_buffer),
					    GFP_ATOMIC);
	if (!dev->adev.transfer_buffer) {
		return -ENOMEM;
	}

	dev->adev.urb = kcalloc(num_urb, sizeof(*dev->adev.urb), GFP_ATOMIC);
	if (!dev->adev.urb) {
		kfree(dev->adev.transfer_buffer);
		return -ENOMEM;
	}

	/* Alloc memory for each URB and for each transfer buffer */
	dev->adev.num_urb = num_urb;
	for (i = 0; i < num_urb; i++) {
824 825 826 827
		struct urb *urb;
		int j, k;
		void *buf;

828
		urb = usb_alloc_urb(npackets, GFP_ATOMIC);
829 830 831 832 833 834 835
		if (!urb) {
			em28xx_errdev("usb_alloc_urb failed!\n");
			em28xx_audio_free_urb(dev);
			return -ENOMEM;
		}
		dev->adev.urb[i] = urb;

836
		buf = usb_alloc_coherent(dev->udev, npackets * ep_size, GFP_ATOMIC,
837 838 839 840 841 842 843 844 845 846 847 848
					 &urb->transfer_dma);
		if (!buf) {
			em28xx_errdev("usb_alloc_coherent failed!\n");
			em28xx_audio_free_urb(dev);
			return -ENOMEM;
		}
		dev->adev.transfer_buffer[i] = buf;

		urb->dev = dev->udev;
		urb->context = dev;
		urb->pipe = usb_rcvisocpipe(dev->udev, EM28XX_EP_AUDIO);
		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
849 850
		urb->transfer_buffer = buf;
		urb->interval = interval;
851
		urb->complete = em28xx_audio_isocirq;
852 853
		urb->number_of_packets = npackets;
		urb->transfer_buffer_length = ep_size * npackets;
854

855
		for (j = k = 0; j < npackets; j++, k += ep_size) {
856
			urb->iso_frame_desc[j].offset = k;
857
			urb->iso_frame_desc[j].length = ep_size;
858 859 860
		}
	}

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
	return 0;
}

static int em28xx_audio_init(struct em28xx *dev)
{
	struct em28xx_audio *adev = &dev->adev;
	struct snd_pcm      *pcm;
	struct snd_card     *card;
	static int          devnr;
	int		    err;

	if (!dev->has_alsa_audio || dev->audio_ifnum < 0) {
		/* This device does not support the extension (in this case
		   the device is expecting the snd-usb-audio module or
		   doesn't have analog audio support at all) */
		return 0;
	}

	em28xx_info("Binding audio extension\n");

	printk(KERN_INFO "em28xx-audio.c: Copyright (C) 2006 Markus "
			 "Rechberger\n");
	printk(KERN_INFO
	       "em28xx-audio.c: Copyright (C) 2007-2014 Mauro Carvalho Chehab\n");

	err = snd_card_create(index[devnr], "Em28xx Audio", THIS_MODULE, 0,
			      &card);
	if (err < 0)
		return err;

	spin_lock_init(&adev->slock);
	adev->sndcard = card;
	adev->udev = dev->udev;

	err = snd_pcm_new(card, "Em28xx Audio", 0, 0, 1, &pcm);
	if (err < 0) {
		snd_card_free(card);
		return err;
	}

	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_em28xx_pcm_capture);
	pcm->info_flags = 0;
	pcm->private_data = dev;
	strcpy(pcm->name, "Empia 28xx Capture");

	snd_card_set_dev(card, &dev->udev->dev);
	strcpy(card->driver, "Em28xx-Audio");
	strcpy(card->shortname, "Em28xx Audio");
	strcpy(card->longname, "Empia Em28xx Audio");

	INIT_WORK(&dev->wq_trigger, audio_trigger);

	if (dev->audio_mode.ac97 != EM28XX_NO_AC97) {
		em28xx_cvol_new(card, dev, "Video", AC97_VIDEO);
		em28xx_cvol_new(card, dev, "Line In", AC97_LINE);
		em28xx_cvol_new(card, dev, "Phone", AC97_PHONE);
		em28xx_cvol_new(card, dev, "Microphone", AC97_MIC);
		em28xx_cvol_new(card, dev, "CD", AC97_CD);
		em28xx_cvol_new(card, dev, "AUX", AC97_AUX);
		em28xx_cvol_new(card, dev, "PCM", AC97_PCM);

		em28xx_cvol_new(card, dev, "Master", AC97_MASTER);
		em28xx_cvol_new(card, dev, "Line", AC97_HEADPHONE);
		em28xx_cvol_new(card, dev, "Mono", AC97_MASTER_MONO);
		em28xx_cvol_new(card, dev, "LFE", AC97_CENTER_LFE_MASTER);
		em28xx_cvol_new(card, dev, "Surround", AC97_SURROUND_MASTER);
	}

	err = em28xx_audio_urb_init(dev);
	if (err) {
		snd_card_free(card);
		return -ENODEV;
	}

935 936
	err = snd_card_register(card);
	if (err < 0) {
937
		em28xx_audio_free_urb(dev);
938
		snd_card_free(card);
939
		return err;
940
	}
941

942
	em28xx_info("Audio extension successfully initialized\n");
943 944 945 946 947
	return 0;
}

static int em28xx_audio_fini(struct em28xx *dev)
{
948
	if (dev == NULL)
949
		return 0;
950

951
	if (dev->has_alsa_audio != 1) {
952
		/* This device does not support the extension (in this case
953 954
		   the device is expecting the snd-usb-audio module or
		   doesn't have analog audio support at all) */
955 956 957
		return 0;
	}

958 959
	em28xx_audio_free_urb(dev);

960 961 962
	if (dev->adev.sndcard) {
		snd_card_free(dev->adev.sndcard);
		dev->adev.sndcard = NULL;
963
	}
964

965 966 967 968
	return 0;
}

static struct em28xx_ops audio_ops = {
969
	.id   = EM28XX_AUDIO,
970 971 972
	.name = "Em28xx Audio Extension",
	.init = em28xx_audio_init,
	.fini = em28xx_audio_fini,
973 974 975 976 977 978 979 980 981 982 983 984 985 986
};

static int __init em28xx_alsa_register(void)
{
	return em28xx_register_extension(&audio_ops);
}

static void __exit em28xx_alsa_unregister(void)
{
	em28xx_unregister_extension(&audio_ops);
}

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Markus Rechberger <mrechberger@gmail.com>");
987
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
988 989
MODULE_DESCRIPTION(DRIVER_DESC " - audio interface");
MODULE_VERSION(EM28XX_VERSION);
990 991 992

module_init(em28xx_alsa_register);
module_exit(em28xx_alsa_unregister);