uvc_video.c 35.8 KB
Newer Older
1 2 3
/*
 *      uvc_video.c  --  USB Video Class driver - Video handling
 *
4 5
 *      Copyright (C) 2005-2010
 *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 7 8 9 10 11 12 13 14 15 16
 *
 *      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.
 *
 */

#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
17
#include <linux/slab.h>
18 19 20 21
#include <linux/usb.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
A
Arun Sharma 已提交
22
#include <linux/atomic.h>
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include <asm/unaligned.h>

#include <media/v4l2-common.h>

#include "uvcvideo.h"

/* ------------------------------------------------------------------------
 * UVC Controls
 */

static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
			__u8 intfnum, __u8 cs, void *data, __u16 size,
			int timeout)
{
	__u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
	unsigned int pipe;

	pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
			      : usb_sndctrlpipe(dev->udev, 0);
	type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;

44
	return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45
			unit << 8 | intfnum, data, size, timeout);
46 47
}

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
static const char *uvc_query_name(__u8 query)
{
	switch (query) {
	case UVC_SET_CUR:
		return "SET_CUR";
	case UVC_GET_CUR:
		return "GET_CUR";
	case UVC_GET_MIN:
		return "GET_MIN";
	case UVC_GET_MAX:
		return "GET_MAX";
	case UVC_GET_RES:
		return "GET_RES";
	case UVC_GET_LEN:
		return "GET_LEN";
	case UVC_GET_INFO:
		return "GET_INFO";
	case UVC_GET_DEF:
		return "GET_DEF";
	default:
		return "<invalid>";
	}
}

72 73 74 75
int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
			__u8 intfnum, __u8 cs, void *data, __u16 size)
{
	int ret;
76

77 78
	ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
				UVC_CTRL_CONTROL_TIMEOUT);
79
	if (ret != size) {
80 81 82
		uvc_printk(KERN_ERR, "Failed to query (%s) UVC control %u on "
			"unit %u: %d (exp. %u).\n", uvc_query_name(query), cs,
			unit, ret, size);
83 84 85 86 87 88
		return -EIO;
	}

	return 0;
}

89
static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
90 91
	struct uvc_streaming_control *ctrl)
{
92
	struct uvc_format *format = NULL;
93 94
	struct uvc_frame *frame = NULL;
	unsigned int i;
95

96 97 98 99 100 101
	for (i = 0; i < stream->nformats; ++i) {
		if (stream->format[i].index == ctrl->bFormatIndex) {
			format = &stream->format[i];
			break;
		}
	}
102

103 104
	if (format == NULL)
		return;
105

106 107 108 109 110 111
	for (i = 0; i < format->nframes; ++i) {
		if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
			frame = &format->frame[i];
			break;
		}
	}
112

113 114
	if (frame == NULL)
		return;
115 116 117

	if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
	     (ctrl->dwMaxVideoFrameSize == 0 &&
118
	      stream->dev->uvc_version < 0x0110))
119 120
		ctrl->dwMaxVideoFrameSize =
			frame->dwMaxVideoFrameBufferSize;
121

122 123
	if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
	    stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
124
	    stream->intf->num_altsetting > 1) {
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
		u32 interval;
		u32 bandwidth;

		interval = (ctrl->dwFrameInterval > 100000)
			 ? ctrl->dwFrameInterval
			 : frame->dwFrameInterval[0];

		/* Compute a bandwidth estimation by multiplying the frame
		 * size by the number of video frames per second, divide the
		 * result by the number of USB frames (or micro-frames for
		 * high-speed devices) per second and add the UVC header size
		 * (assumed to be 12 bytes long).
		 */
		bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
		bandwidth *= 10000000 / interval + 1;
		bandwidth /= 1000;
141
		if (stream->dev->udev->speed == USB_SPEED_HIGH)
142 143 144
			bandwidth /= 8;
		bandwidth += 12;

145 146 147 148 149 150 151 152 153
		/* The bandwidth estimate is too low for many cameras. Don't use
		 * maximum packet sizes lower than 1024 bytes to try and work
		 * around the problem. According to measurements done on two
		 * different camera models, the value is high enough to get most
		 * resolutions working while not preventing two simultaneous
		 * VGA streams at 15 fps.
		 */
		bandwidth = max_t(u32, bandwidth, 1024);

154 155
		ctrl->dwMaxPayloadTransferSize = bandwidth;
	}
156 157
}

158
static int uvc_get_video_ctrl(struct uvc_streaming *stream,
159 160
	struct uvc_streaming_control *ctrl, int probe, __u8 query)
{
161 162
	__u8 *data;
	__u16 size;
163 164
	int ret;

165
	size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
166 167 168 169
	if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
			query == UVC_GET_DEF)
		return -EIO;

170 171 172 173
	data = kmalloc(size, GFP_KERNEL);
	if (data == NULL)
		return -ENOMEM;

174
	ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
175
		probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
176
		size, uvc_timeout_param);
177

178
	if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
179 180 181 182
		/* Some cameras, mostly based on Bison Electronics chipsets,
		 * answer a GET_MIN or GET_MAX request with the wCompQuality
		 * field only.
		 */
183
		uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
184 185
			"compliance - GET_MIN/MAX(PROBE) incorrectly "
			"supported. Enabling workaround.\n");
186
		memset(ctrl, 0, sizeof *ctrl);
187 188
		ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
		ret = 0;
189
		goto out;
190
	} else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
191 192 193 194
		/* Many cameras don't support the GET_DEF request on their
		 * video probe control. Warn once and return, the caller will
		 * fall back to GET_CUR.
		 */
195
		uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
196 197 198 199 200 201 202 203 204 205 206
			"compliance - GET_DEF(PROBE) not supported. "
			"Enabling workaround.\n");
		ret = -EIO;
		goto out;
	} else if (ret != size) {
		uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
			"%d (exp. %u).\n", query, probe ? "probe" : "commit",
			ret, size);
		ret = -EIO;
		goto out;
	}
207 208 209 210 211 212 213 214 215 216

	ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
	ctrl->bFormatIndex = data[2];
	ctrl->bFrameIndex = data[3];
	ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
	ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
	ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
	ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
	ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
	ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
217 218
	ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
	ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
219 220

	if (size == 34) {
221
		ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
222 223 224 225 226
		ctrl->bmFramingInfo = data[30];
		ctrl->bPreferedVersion = data[31];
		ctrl->bMinVersion = data[32];
		ctrl->bMaxVersion = data[33];
	} else {
227
		ctrl->dwClockFrequency = stream->dev->clock_frequency;
228 229 230 231 232 233
		ctrl->bmFramingInfo = 0;
		ctrl->bPreferedVersion = 0;
		ctrl->bMinVersion = 0;
		ctrl->bMaxVersion = 0;
	}

234 235 236
	/* Some broken devices return null or wrong dwMaxVideoFrameSize and
	 * dwMaxPayloadTransferSize fields. Try to get the value from the
	 * format and frame descriptors.
237
	 */
238
	uvc_fixup_video_ctrl(stream, ctrl);
239
	ret = 0;
240

241 242 243
out:
	kfree(data);
	return ret;
244 245
}

246
static int uvc_set_video_ctrl(struct uvc_streaming *stream,
247 248
	struct uvc_streaming_control *ctrl, int probe)
{
249 250 251
	__u8 *data;
	__u16 size;
	int ret;
252

253
	size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
254 255 256
	data = kzalloc(size, GFP_KERNEL);
	if (data == NULL)
		return -ENOMEM;
257 258 259 260 261 262 263 264 265 266

	*(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
	data[2] = ctrl->bFormatIndex;
	data[3] = ctrl->bFrameIndex;
	*(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
	*(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
	*(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
	*(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
	*(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
	*(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
267 268
	put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
	put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
269 270

	if (size == 34) {
271
		put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
272 273 274 275 276 277
		data[30] = ctrl->bmFramingInfo;
		data[31] = ctrl->bPreferedVersion;
		data[32] = ctrl->bMinVersion;
		data[33] = ctrl->bMaxVersion;
	}

278
	ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
279
		probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
280
		size, uvc_timeout_param);
281 282 283 284 285 286
	if (ret != size) {
		uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
			"%d (exp. %u).\n", probe ? "probe" : "commit",
			ret, size);
		ret = -EIO;
	}
287 288 289

	kfree(data);
	return ret;
290 291
}

292
int uvc_probe_video(struct uvc_streaming *stream,
293 294 295 296 297 298 299 300 301 302 303 304 305 306
	struct uvc_streaming_control *probe)
{
	struct uvc_streaming_control probe_min, probe_max;
	__u16 bandwidth;
	unsigned int i;
	int ret;

	/* Perform probing. The device should adjust the requested values
	 * according to its capabilities. However, some devices, namely the
	 * first generation UVC Logitech webcams, don't implement the Video
	 * Probe control properly, and just return the needed bandwidth. For
	 * that reason, if the needed bandwidth exceeds the maximum available
	 * bandwidth, try to lower the quality.
	 */
307 308
	ret = uvc_set_video_ctrl(stream, probe, 1);
	if (ret < 0)
309 310 311
		goto done;

	/* Get the minimum and maximum values for compression settings. */
312 313
	if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
		ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
314 315
		if (ret < 0)
			goto done;
316
		ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
317 318 319 320 321 322 323
		if (ret < 0)
			goto done;

		probe->wCompQuality = probe_max.wCompQuality;
	}

	for (i = 0; i < 2; ++i) {
324
		ret = uvc_set_video_ctrl(stream, probe, 1);
325 326
		if (ret < 0)
			goto done;
327
		ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
328
		if (ret < 0)
329 330
			goto done;

331
		if (stream->intf->num_altsetting == 1)
332 333 334
			break;

		bandwidth = probe->dwMaxPayloadTransferSize;
335
		if (bandwidth <= stream->maxpsize)
336 337
			break;

338
		if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
			ret = -ENOSPC;
			goto done;
		}

		/* TODO: negotiate compression parameters */
		probe->wKeyFrameRate = probe_min.wKeyFrameRate;
		probe->wPFrameRate = probe_min.wPFrameRate;
		probe->wCompQuality = probe_max.wCompQuality;
		probe->wCompWindowSize = probe_min.wCompWindowSize;
	}

done:
	return ret;
}

354
int uvc_commit_video(struct uvc_streaming *stream,
355 356
	struct uvc_streaming_control *probe)
{
357
	return uvc_set_video_ctrl(stream, probe, 0);
358 359
}

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
/* ------------------------------------------------------------------------
 * Video codecs
 */

/* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
#define UVC_STREAM_EOH	(1 << 7)
#define UVC_STREAM_ERR	(1 << 6)
#define UVC_STREAM_STI	(1 << 5)
#define UVC_STREAM_RES	(1 << 4)
#define UVC_STREAM_SCR	(1 << 3)
#define UVC_STREAM_PTS	(1 << 2)
#define UVC_STREAM_EOF	(1 << 1)
#define UVC_STREAM_FID	(1 << 0)

/* Video payload decoding is handled by uvc_video_decode_start(),
 * uvc_video_decode_data() and uvc_video_decode_end().
 *
 * uvc_video_decode_start is called with URB data at the start of a bulk or
 * isochronous payload. It processes header data and returns the header size
 * in bytes if successful. If an error occurs, it returns a negative error
 * code. The following error codes have special meanings.
 *
 * - EAGAIN informs the caller that the current video buffer should be marked
 *   as done, and that the function should be called again with the same data
 *   and a new video buffer. This is used when end of frame conditions can be
 *   reliably detected at the beginning of the next frame only.
 *
 * If an error other than -EAGAIN is returned, the caller will drop the current
 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
 * made until the next payload. -ENODATA can be used to drop the current
 * payload if no other error code is appropriate.
 *
 * uvc_video_decode_data is called for every URB with URB data. It copies the
 * data to the video buffer.
 *
 * uvc_video_decode_end is called with header data at the end of a bulk or
 * isochronous payload. It performs any additional header data processing and
L
Lucas De Marchi 已提交
397
 * returns 0 or a negative error code if an error occurred. As header data have
398 399 400
 * already been processed by uvc_video_decode_start, this functions isn't
 * required to perform sanity checks a second time.
 *
L
Lucas De Marchi 已提交
401
 * For isochronous transfers where a payload is always transferred in a single
402 403 404 405 406 407 408
 * URB, the three functions will be called in a row.
 *
 * To let the decoder process header data and update its internal state even
 * when no video buffer is available, uvc_video_decode_start must be prepared
 * to be called with a NULL buf parameter. uvc_video_decode_data and
 * uvc_video_decode_end will never be called with a NULL buffer.
 */
409
static int uvc_video_decode_start(struct uvc_streaming *stream,
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
		struct uvc_buffer *buf, const __u8 *data, int len)
{
	__u8 fid;

	/* Sanity checks:
	 * - packet must be at least 2 bytes long
	 * - bHeaderLength value must be at least 2 bytes (see above)
	 * - bHeaderLength value can't be larger than the packet size.
	 */
	if (len < 2 || data[0] < 2 || data[0] > len)
		return -EINVAL;

	/* Skip payloads marked with the error bit ("error frames"). */
	if (data[1] & UVC_STREAM_ERR) {
		uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
			  "set).\n");
		return -ENODATA;
	}

	fid = data[1] & UVC_STREAM_FID;

431 432 433 434 435 436
	/* Increase the sequence number regardless of any buffer states, so
	 * that discontinuous sequence numbers always indicate lost frames.
	 */
	if (stream->last_fid != fid)
		stream->sequence++;

437 438 439 440
	/* Store the payload FID bit and return immediately when the buffer is
	 * NULL.
	 */
	if (buf == NULL) {
441
		stream->last_fid = fid;
442 443 444 445 446
		return -ENODATA;
	}

	/* Synchronize to the input stream by waiting for the FID bit to be
	 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
447
	 * stream->last_fid is initialized to -1, so the first isochronous
448 449
	 * frame will always be in sync.
	 *
450
	 * If the device doesn't toggle the FID bit, invert stream->last_fid
451 452 453
	 * when the EOF bit is set to force synchronisation on the next packet.
	 */
	if (buf->state != UVC_BUF_STATE_ACTIVE) {
454 455
		struct timespec ts;

456
		if (fid == stream->last_fid) {
457 458
			uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
				"sync).\n");
459
			if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
460
			    (data[1] & UVC_STREAM_EOF))
461
				stream->last_fid ^= UVC_STREAM_FID;
462 463 464
			return -ENODATA;
		}

465 466 467 468 469
		if (uvc_clock_param == CLOCK_MONOTONIC)
			ktime_get_ts(&ts);
		else
			ktime_get_real_ts(&ts);

470
		buf->buf.sequence = stream->sequence;
471 472 473
		buf->buf.timestamp.tv_sec = ts.tv_sec;
		buf->buf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;

474 475 476 477 478 479 480 481 482 483 484
		/* TODO: Handle PTS and SCR. */
		buf->state = UVC_BUF_STATE_ACTIVE;
	}

	/* Mark the buffer as done if we're at the beginning of a new frame.
	 * End of frame detection is better implemented by checking the EOF
	 * bit (FID bit toggling is delayed by one frame compared to the EOF
	 * bit), but some devices don't set the bit at end of frame (and the
	 * last payload can be lost anyway). We thus must check if the FID has
	 * been toggled.
	 *
485
	 * stream->last_fid is initialized to -1, so the first isochronous
486 487 488 489
	 * frame will never trigger an end of frame detection.
	 *
	 * Empty buffers (bytesused == 0) don't trigger end of frame detection
	 * as it doesn't make sense to return an empty buffer. This also
490
	 * avoids detecting end of frame conditions at FID toggling if the
491 492
	 * previous payload had the EOF bit set.
	 */
493
	if (fid != stream->last_fid && buf->bytesused != 0) {
494 495
		uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
				"toggled).\n");
496
		buf->state = UVC_BUF_STATE_READY;
497 498 499
		return -EAGAIN;
	}

500
	stream->last_fid = fid;
501 502 503 504

	return data[0];
}

505
static void uvc_video_decode_data(struct uvc_streaming *stream,
506 507 508 509 510 511 512 513 514
		struct uvc_buffer *buf, const __u8 *data, int len)
{
	unsigned int maxlen, nbytes;
	void *mem;

	if (len <= 0)
		return;

	/* Copy the video data to the buffer. */
515 516
	maxlen = buf->length - buf->bytesused;
	mem = buf->mem + buf->bytesused;
517 518
	nbytes = min((unsigned int)len, maxlen);
	memcpy(mem, data, nbytes);
519
	buf->bytesused += nbytes;
520 521 522 523

	/* Complete the current frame if the buffer size was exceeded. */
	if (len > maxlen) {
		uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
524
		buf->state = UVC_BUF_STATE_READY;
525 526 527
	}
}

528
static void uvc_video_decode_end(struct uvc_streaming *stream,
529 530 531
		struct uvc_buffer *buf, const __u8 *data, int len)
{
	/* Mark the buffer as done if the EOF marker is set. */
532
	if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
533 534 535
		uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
		if (data[0] == len)
			uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
536
		buf->state = UVC_BUF_STATE_READY;
537 538
		if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
			stream->last_fid ^= UVC_STREAM_FID;
539 540 541
	}
}

542 543 544 545 546 547 548 549 550 551 552
/* Video payload encoding is handled by uvc_video_encode_header() and
 * uvc_video_encode_data(). Only bulk transfers are currently supported.
 *
 * uvc_video_encode_header is called at the start of a payload. It adds header
 * data to the transfer buffer and returns the header size. As the only known
 * UVC output device transfers a whole frame in a single payload, the EOF bit
 * is always set in the header.
 *
 * uvc_video_encode_data is called for every URB and copies the data from the
 * video buffer to the transfer buffer.
 */
553
static int uvc_video_encode_header(struct uvc_streaming *stream,
554 555 556 557
		struct uvc_buffer *buf, __u8 *data, int len)
{
	data[0] = 2;	/* Header length */
	data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
558
		| (stream->last_fid & UVC_STREAM_FID);
559 560 561
	return 2;
}

562
static int uvc_video_encode_data(struct uvc_streaming *stream,
563 564
		struct uvc_buffer *buf, __u8 *data, int len)
{
565
	struct uvc_video_queue *queue = &stream->queue;
566 567 568 569
	unsigned int nbytes;
	void *mem;

	/* Copy video data to the URB buffer. */
570 571
	mem = buf->mem + queue->buf_used;
	nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
572
	nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
573 574 575 576 577 578 579 580
			nbytes);
	memcpy(data, mem, nbytes);

	queue->buf_used += nbytes;

	return nbytes;
}

581 582 583 584 585 586 587
/* ------------------------------------------------------------------------
 * URB handling
 */

/*
 * Completion handler for video URBs.
 */
588 589
static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
	struct uvc_buffer *buf)
590 591 592 593 594 595 596 597
{
	u8 *mem;
	int ret, i;

	for (i = 0; i < urb->number_of_packets; ++i) {
		if (urb->iso_frame_desc[i].status < 0) {
			uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
				"lost (%d).\n", urb->iso_frame_desc[i].status);
598 599 600
			/* Mark the buffer as faulty. */
			if (buf != NULL)
				buf->error = 1;
601 602 603 604 605 606
			continue;
		}

		/* Decode the payload header. */
		mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
		do {
607
			ret = uvc_video_decode_start(stream, buf, mem,
608 609
				urb->iso_frame_desc[i].actual_length);
			if (ret == -EAGAIN)
610 611
				buf = uvc_queue_next_buffer(&stream->queue,
							    buf);
612 613 614 615 616 617
		} while (ret == -EAGAIN);

		if (ret < 0)
			continue;

		/* Decode the payload data. */
618
		uvc_video_decode_data(stream, buf, mem + ret,
619 620 621
			urb->iso_frame_desc[i].actual_length - ret);

		/* Process the header again. */
622
		uvc_video_decode_end(stream, buf, mem,
623
			urb->iso_frame_desc[i].actual_length);
624

625
		if (buf->state == UVC_BUF_STATE_READY) {
626
			if (buf->length != buf->bytesused &&
627 628 629 630
			    !(stream->cur_format->flags &
			      UVC_FMT_FLAG_COMPRESSED))
				buf->error = 1;

631
			buf = uvc_queue_next_buffer(&stream->queue, buf);
632
		}
633 634 635
	}
}

636 637
static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
	struct uvc_buffer *buf)
638 639 640 641
{
	u8 *mem;
	int len, ret;

642 643 644
	if (urb->actual_length == 0)
		return;

645 646
	mem = urb->transfer_buffer;
	len = urb->actual_length;
647
	stream->bulk.payload_size += len;
648 649 650 651

	/* If the URB is the first of its payload, decode and save the
	 * header.
	 */
652
	if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
653
		do {
654
			ret = uvc_video_decode_start(stream, buf, mem, len);
655
			if (ret == -EAGAIN)
656 657
				buf = uvc_queue_next_buffer(&stream->queue,
							    buf);
658 659
		} while (ret == -EAGAIN);

L
Lucas De Marchi 已提交
660
		/* If an error occurred skip the rest of the payload. */
661
		if (ret < 0 || buf == NULL) {
662
			stream->bulk.skip_payload = 1;
663
		} else {
664 665
			memcpy(stream->bulk.header, mem, ret);
			stream->bulk.header_size = ret;
666

667 668 669
			mem += ret;
			len -= ret;
		}
670 671 672 673 674 675 676 677
	}

	/* The buffer queue might have been cancelled while a bulk transfer
	 * was in progress, so we can reach here with buf equal to NULL. Make
	 * sure buf is never dereferenced if NULL.
	 */

	/* Process video data. */
678 679
	if (!stream->bulk.skip_payload && buf != NULL)
		uvc_video_decode_data(stream, buf, mem, len);
680 681 682 683 684

	/* Detect the payload end by a URB smaller than the maximum size (or
	 * a payload size equal to the maximum) and process the header again.
	 */
	if (urb->actual_length < urb->transfer_buffer_length ||
685 686 687 688
	    stream->bulk.payload_size >= stream->bulk.max_payload_size) {
		if (!stream->bulk.skip_payload && buf != NULL) {
			uvc_video_decode_end(stream, buf, stream->bulk.header,
				stream->bulk.payload_size);
689
			if (buf->state == UVC_BUF_STATE_READY)
690 691
				buf = uvc_queue_next_buffer(&stream->queue,
							    buf);
692 693
		}

694 695 696
		stream->bulk.header_size = 0;
		stream->bulk.skip_payload = 0;
		stream->bulk.payload_size = 0;
697 698 699
	}
}

700 701
static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
	struct uvc_buffer *buf)
702 703
{
	u8 *mem = urb->transfer_buffer;
704
	int len = stream->urb_size, ret;
705 706 707 708 709 710 711

	if (buf == NULL) {
		urb->transfer_buffer_length = 0;
		return;
	}

	/* If the URB is the first of its payload, add the header. */
712 713 714 715
	if (stream->bulk.header_size == 0) {
		ret = uvc_video_encode_header(stream, buf, mem, len);
		stream->bulk.header_size = ret;
		stream->bulk.payload_size += ret;
716 717 718 719 720
		mem += ret;
		len -= ret;
	}

	/* Process video data. */
721
	ret = uvc_video_encode_data(stream, buf, mem, len);
722

723
	stream->bulk.payload_size += ret;
724 725
	len -= ret;

726
	if (buf->bytesused == stream->queue.buf_used ||
727
	    stream->bulk.payload_size == stream->bulk.max_payload_size) {
728
		if (buf->bytesused == stream->queue.buf_used) {
729
			stream->queue.buf_used = 0;
730
			buf->state = UVC_BUF_STATE_READY;
731
			buf->buf.sequence = ++stream->sequence;
732 733
			uvc_queue_next_buffer(&stream->queue, buf);
			stream->last_fid ^= UVC_STREAM_FID;
734 735
		}

736 737
		stream->bulk.header_size = 0;
		stream->bulk.payload_size = 0;
738 739
	}

740
	urb->transfer_buffer_length = stream->urb_size - len;
741 742
}

743 744
static void uvc_video_complete(struct urb *urb)
{
745 746
	struct uvc_streaming *stream = urb->context;
	struct uvc_video_queue *queue = &stream->queue;
747 748 749 750 751 752 753 754 755 756 757 758 759
	struct uvc_buffer *buf = NULL;
	unsigned long flags;
	int ret;

	switch (urb->status) {
	case 0:
		break;

	default:
		uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
			"completion handler.\n", urb->status);

	case -ENOENT:		/* usb_kill_urb() called. */
760
		if (stream->frozen)
761 762 763 764 765 766 767 768 769 770 771 772 773 774
			return;

	case -ECONNRESET:	/* usb_unlink_urb() called. */
	case -ESHUTDOWN:	/* The endpoint is being disabled. */
		uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
		return;
	}

	spin_lock_irqsave(&queue->irqlock, flags);
	if (!list_empty(&queue->irqqueue))
		buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
				       queue);
	spin_unlock_irqrestore(&queue->irqlock, flags);

775
	stream->decode(urb, stream, buf);
776 777 778 779 780 781 782

	if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
		uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
			ret);
	}
}

783 784 785
/*
 * Free transfer buffers.
 */
786
static void uvc_free_urb_buffers(struct uvc_streaming *stream)
787 788 789 790
{
	unsigned int i;

	for (i = 0; i < UVC_URBS; ++i) {
791
		if (stream->urb_buffer[i]) {
792
#ifndef CONFIG_DMA_NONCOHERENT
793
			usb_free_coherent(stream->dev->udev, stream->urb_size,
794
				stream->urb_buffer[i], stream->urb_dma[i]);
795 796 797
#else
			kfree(stream->urb_buffer[i]);
#endif
798
			stream->urb_buffer[i] = NULL;
799 800 801
		}
	}

802
	stream->urb_size = 0;
803 804 805 806 807 808 809
}

/*
 * Allocate transfer buffers. This function can be called with buffers
 * already allocated when resuming from suspend, in which case it will
 * return without touching the buffers.
 *
810 811 812 813 814
 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
 * system is too low on memory try successively smaller numbers of packets
 * until allocation succeeds.
 *
 * Return the number of allocated packets on success or 0 when out of memory.
815
 */
816
static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
817
	unsigned int size, unsigned int psize, gfp_t gfp_flags)
818
{
819
	unsigned int npackets;
820 821 822
	unsigned int i;

	/* Buffers are already allocated, bail out. */
823 824
	if (stream->urb_size)
		return stream->urb_size / psize;
825

826
	/* Compute the number of packets. Bulk endpoints might transfer UVC
L
Lucas De Marchi 已提交
827
	 * payloads across multiple URBs.
828 829 830 831 832 833 834 835
	 */
	npackets = DIV_ROUND_UP(size, psize);
	if (npackets > UVC_MAX_PACKETS)
		npackets = UVC_MAX_PACKETS;

	/* Retry allocations until one succeed. */
	for (; npackets > 1; npackets /= 2) {
		for (i = 0; i < UVC_URBS; ++i) {
836
			stream->urb_size = psize * npackets;
837
#ifndef CONFIG_DMA_NONCOHERENT
838
			stream->urb_buffer[i] = usb_alloc_coherent(
839
				stream->dev->udev, stream->urb_size,
840
				gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
841 842 843 844
#else
			stream->urb_buffer[i] =
			    kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
#endif
845 846
			if (!stream->urb_buffer[i]) {
				uvc_free_urb_buffers(stream);
847 848 849 850 851
				break;
			}
		}

		if (i == UVC_URBS) {
852 853 854
			uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
				"of %ux%u bytes each.\n", UVC_URBS, npackets,
				psize);
855
			return npackets;
856 857 858
		}
	}

859 860
	uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
		"per packet).\n", psize);
861 862 863
	return 0;
}

864 865 866
/*
 * Uninitialize isochronous/bulk URBs and free transfer buffers.
 */
867
static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
868 869 870 871 872
{
	struct urb *urb;
	unsigned int i;

	for (i = 0; i < UVC_URBS; ++i) {
873 874
		urb = stream->urb[i];
		if (urb == NULL)
875 876 877 878
			continue;

		usb_kill_urb(urb);
		usb_free_urb(urb);
879
		stream->urb[i] = NULL;
880
	}
881 882

	if (free_buffers)
883
		uvc_free_urb_buffers(stream);
884 885 886 887 888 889
}

/*
 * Initialize isochronous URBs and allocate transfer buffers. The packet size
 * is given by the endpoint.
 */
890
static int uvc_init_video_isoc(struct uvc_streaming *stream,
891
	struct usb_host_endpoint *ep, gfp_t gfp_flags)
892 893 894
{
	struct urb *urb;
	unsigned int npackets, i, j;
895 896
	u16 psize;
	u32 size;
897 898 899

	psize = le16_to_cpu(ep->desc.wMaxPacketSize);
	psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
900
	size = stream->ctrl.dwMaxVideoFrameSize;
901

902
	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
903 904
	if (npackets == 0)
		return -ENOMEM;
905 906 907 908

	size = npackets * psize;

	for (i = 0; i < UVC_URBS; ++i) {
909
		urb = usb_alloc_urb(npackets, gfp_flags);
910
		if (urb == NULL) {
911
			uvc_uninit_video(stream, 1);
912 913 914
			return -ENOMEM;
		}

915 916 917
		urb->dev = stream->dev->udev;
		urb->context = stream;
		urb->pipe = usb_rcvisocpipe(stream->dev->udev,
918
				ep->desc.bEndpointAddress);
919
#ifndef CONFIG_DMA_NONCOHERENT
920
		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
921 922 923 924
		urb->transfer_dma = stream->urb_dma[i];
#else
		urb->transfer_flags = URB_ISO_ASAP;
#endif
925
		urb->interval = ep->desc.bInterval;
926
		urb->transfer_buffer = stream->urb_buffer[i];
927 928 929 930 931 932 933 934 935
		urb->complete = uvc_video_complete;
		urb->number_of_packets = npackets;
		urb->transfer_buffer_length = size;

		for (j = 0; j < npackets; ++j) {
			urb->iso_frame_desc[j].offset = j * psize;
			urb->iso_frame_desc[j].length = psize;
		}

936
		stream->urb[i] = urb;
937 938 939 940 941 942 943 944 945
	}

	return 0;
}

/*
 * Initialize bulk URBs and allocate transfer buffers. The packet size is
 * given by the endpoint.
 */
946
static int uvc_init_video_bulk(struct uvc_streaming *stream,
947
	struct usb_host_endpoint *ep, gfp_t gfp_flags)
948 949
{
	struct urb *urb;
950 951 952 953
	unsigned int npackets, pipe, i;
	u16 psize;
	u32 size;

954
	psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
955 956
	size = stream->ctrl.dwMaxPayloadTransferSize;
	stream->bulk.max_payload_size = size;
957

958
	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
959
	if (npackets == 0)
960 961
		return -ENOMEM;

962 963
	size = npackets * psize;

964
	if (usb_endpoint_dir_in(&ep->desc))
965
		pipe = usb_rcvbulkpipe(stream->dev->udev,
966 967
				       ep->desc.bEndpointAddress);
	else
968
		pipe = usb_sndbulkpipe(stream->dev->udev,
969 970
				       ep->desc.bEndpointAddress);

971
	if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
972
		size = 0;
973 974

	for (i = 0; i < UVC_URBS; ++i) {
975
		urb = usb_alloc_urb(0, gfp_flags);
976
		if (urb == NULL) {
977
			uvc_uninit_video(stream, 1);
978 979 980
			return -ENOMEM;
		}

981 982 983
		usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
			stream->urb_buffer[i], size, uvc_video_complete,
			stream);
984
#ifndef CONFIG_DMA_NONCOHERENT
985
		urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
986
		urb->transfer_dma = stream->urb_dma[i];
987
#endif
988

989
		stream->urb[i] = urb;
990 991 992 993 994 995 996 997
	}

	return 0;
}

/*
 * Initialize isochronous/bulk URBs and allocate transfer buffers.
 */
998
static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
999
{
1000
	struct usb_interface *intf = stream->intf;
1001 1002
	struct usb_host_endpoint *ep;
	unsigned int i;
1003 1004
	int ret;

1005
	stream->sequence = -1;
1006 1007 1008 1009
	stream->last_fid = -1;
	stream->bulk.header_size = 0;
	stream->bulk.skip_payload = 0;
	stream->bulk.payload_size = 0;
1010 1011

	if (intf->num_altsetting > 1) {
1012 1013 1014 1015 1016 1017
		struct usb_host_endpoint *best_ep = NULL;
		unsigned int best_psize = 3 * 1024;
		unsigned int bandwidth;
		unsigned int uninitialized_var(altsetting);
		int intfnum = stream->intfnum;

1018
		/* Isochronous endpoint, select the alternate setting. */
1019
		bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1020 1021

		if (bandwidth == 0) {
1022 1023
			uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
				"bandwidth, defaulting to lowest.\n");
1024
			bandwidth = 1;
1025 1026 1027
		} else {
			uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
				"B/frame bandwidth.\n", bandwidth);
1028 1029 1030
		}

		for (i = 0; i < intf->num_altsetting; ++i) {
1031 1032 1033
			struct usb_host_interface *alts;
			unsigned int psize;

1034 1035
			alts = &intf->altsetting[i];
			ep = uvc_find_endpoint(alts,
1036
				stream->header.bEndpointAddress);
1037 1038 1039 1040 1041 1042
			if (ep == NULL)
				continue;

			/* Check if the bandwidth is high enough. */
			psize = le16_to_cpu(ep->desc.wMaxPacketSize);
			psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1043 1044 1045 1046 1047
			if (psize >= bandwidth && psize <= best_psize) {
				altsetting = i;
				best_psize = psize;
				best_ep = ep;
			}
1048 1049
		}

1050
		if (best_ep == NULL) {
1051 1052
			uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
				"for requested bandwidth.\n");
1053
			return -EIO;
1054
		}
1055

1056 1057 1058 1059
		uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
			"(%u B/frame bandwidth).\n", altsetting, best_psize);

		ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1060
		if (ret < 0)
1061 1062
			return ret;

1063
		ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1064 1065 1066
	} else {
		/* Bulk endpoint, proceed to URB initialization. */
		ep = uvc_find_endpoint(&intf->altsetting[0],
1067
				stream->header.bEndpointAddress);
1068 1069 1070
		if (ep == NULL)
			return -EIO;

1071
		ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1072 1073 1074 1075 1076 1077 1078
	}

	if (ret < 0)
		return ret;

	/* Submit the URBs. */
	for (i = 0; i < UVC_URBS; ++i) {
1079 1080
		ret = usb_submit_urb(stream->urb[i], gfp_flags);
		if (ret < 0) {
1081 1082
			uvc_printk(KERN_ERR, "Failed to submit URB %u "
					"(%d).\n", i, ret);
1083
			uvc_uninit_video(stream, 1);
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
			return ret;
		}
	}

	return 0;
}

/* --------------------------------------------------------------------------
 * Suspend/resume
 */

/*
 * Stop streaming without disabling the video queue.
 *
 * To let userspace applications resume without trouble, we must not touch the
 * video buffers in any way. We mark the device as frozen to make sure the URB
 * completion handler won't try to cancel the queue when we kill the URBs.
 */
1102
int uvc_video_suspend(struct uvc_streaming *stream)
1103
{
1104
	if (!uvc_queue_streaming(&stream->queue))
1105 1106
		return 0;

1107 1108 1109
	stream->frozen = 1;
	uvc_uninit_video(stream, 0);
	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1110 1111 1112 1113
	return 0;
}

/*
1114
 * Reconfigure the video interface and restart streaming if it was enabled
1115 1116 1117 1118 1119 1120
 * before suspend.
 *
 * If an error occurs, disable the video queue. This will wake all pending
 * buffers, making sure userspace applications are notified of the problem
 * instead of waiting forever.
 */
1121
int uvc_video_resume(struct uvc_streaming *stream, int reset)
1122 1123 1124
{
	int ret;

1125 1126 1127 1128 1129 1130 1131 1132
	/* If the bus has been reset on resume, set the alternate setting to 0.
	 * This should be the default value, but some devices crash or otherwise
	 * misbehave if they don't receive a SET_INTERFACE request before any
	 * other video control request.
	 */
	if (reset)
		usb_set_interface(stream->dev->udev, stream->intfnum, 0);

1133
	stream->frozen = 0;
1134

1135 1136 1137
	ret = uvc_commit_video(stream, &stream->ctrl);
	if (ret < 0) {
		uvc_queue_enable(&stream->queue, 0);
1138 1139 1140
		return ret;
	}

1141
	if (!uvc_queue_streaming(&stream->queue))
1142 1143
		return 0;

1144 1145 1146
	ret = uvc_init_video(stream, GFP_NOIO);
	if (ret < 0)
		uvc_queue_enable(&stream->queue, 0);
1147 1148 1149 1150 1151 1152 1153 1154 1155

	return ret;
}

/* ------------------------------------------------------------------------
 * Video device
 */

/*
1156 1157
 * Initialize the UVC video device by switching to alternate setting 0 and
 * retrieve the default format.
1158 1159 1160 1161 1162 1163 1164
 *
 * Some cameras (namely the Fuji Finepix) set the format and frame
 * indexes to zero. The UVC standard doesn't clearly make this a spec
 * violation, so try to silently fix the values if possible.
 *
 * This function is called before registering the device with V4L.
 */
1165
int uvc_video_init(struct uvc_streaming *stream)
1166
{
1167
	struct uvc_streaming_control *probe = &stream->ctrl;
1168 1169 1170 1171 1172
	struct uvc_format *format = NULL;
	struct uvc_frame *frame = NULL;
	unsigned int i;
	int ret;

1173
	if (stream->nformats == 0) {
1174 1175 1176 1177
		uvc_printk(KERN_INFO, "No supported video formats found.\n");
		return -EINVAL;
	}

1178 1179 1180
	atomic_set(&stream->active, 0);

	/* Initialize the video buffers queue. */
1181
	uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1182

1183 1184 1185 1186 1187
	/* Alternate setting 0 should be the default, yet the XBox Live Vision
	 * Cam (and possibly other devices) crash or otherwise misbehave if
	 * they don't receive a SET_INTERFACE request before any other video
	 * control request.
	 */
1188
	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1189

1190 1191 1192 1193
	/* Set the streaming probe control with default streaming parameters
	 * retrieved from the device. Webcams that don't suport GET_DEF
	 * requests on the probe control will just keep their current streaming
	 * parameters.
1194
	 */
1195 1196
	if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
		uvc_set_video_ctrl(stream, probe, 1);
1197 1198 1199 1200 1201 1202

	/* Initialize the streaming parameters with the probe control current
	 * value. This makes sure SET_CUR requests on the streaming commit
	 * control will always use values retrieved from a successful GET_CUR
	 * request on the probe control, as required by the UVC specification.
	 */
1203
	ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1204
	if (ret < 0)
1205 1206 1207 1208 1209
		return ret;

	/* Check if the default format descriptor exists. Use the first
	 * available format otherwise.
	 */
1210 1211
	for (i = stream->nformats; i > 0; --i) {
		format = &stream->format[i-1];
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
		if (format->index == probe->bFormatIndex)
			break;
	}

	if (format->nframes == 0) {
		uvc_printk(KERN_INFO, "No frame descriptor found for the "
			"default format.\n");
		return -EINVAL;
	}

	/* Zero bFrameIndex might be correct. Stream-based formats (including
	 * MPEG-2 TS and DV) do not support frames but have a dummy frame
	 * descriptor with bFrameIndex set to zero. If the default frame
1225
	 * descriptor is not found, use the first available frame.
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	 */
	for (i = format->nframes; i > 0; --i) {
		frame = &format->frame[i-1];
		if (frame->bFrameIndex == probe->bFrameIndex)
			break;
	}

	probe->bFormatIndex = format->index;
	probe->bFrameIndex = frame->bFrameIndex;

1236 1237
	stream->cur_format = format;
	stream->cur_frame = frame;
1238 1239

	/* Select the video decoding function */
1240 1241 1242 1243 1244
	if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
		if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
			stream->decode = uvc_video_decode_isight;
		else if (stream->intf->num_altsetting > 1)
			stream->decode = uvc_video_decode_isoc;
1245
		else
1246
			stream->decode = uvc_video_decode_bulk;
1247
	} else {
1248 1249
		if (stream->intf->num_altsetting == 1)
			stream->decode = uvc_video_encode_bulk;
1250 1251 1252 1253 1254 1255
		else {
			uvc_printk(KERN_INFO, "Isochronous endpoints are not "
				"supported for video output devices.\n");
			return -EINVAL;
		}
	}
1256 1257 1258 1259 1260 1261 1262

	return 0;
}

/*
 * Enable or disable the video stream.
 */
1263
int uvc_video_enable(struct uvc_streaming *stream, int enable)
1264 1265 1266 1267
{
	int ret;

	if (!enable) {
1268 1269 1270
		uvc_uninit_video(stream, 1);
		usb_set_interface(stream->dev->udev, stream->intfnum, 0);
		uvc_queue_enable(&stream->queue, 0);
1271 1272 1273
		return 0;
	}

1274 1275
	ret = uvc_queue_enable(&stream->queue, 1);
	if (ret < 0)
1276 1277
		return ret;

1278
	/* Commit the streaming parameters. */
1279
	ret = uvc_commit_video(stream, &stream->ctrl);
1280 1281
	if (ret < 0) {
		uvc_queue_enable(&stream->queue, 0);
1282
		return ret;
1283
	}
1284

1285
	return uvc_init_video(stream, GFP_KERNEL);
1286
}
1287