V4L/DVB (10650): uvcvideo: Initialize streaming parameters with the probe control...
[linux-2.6/btrfs-unstable.git] / drivers / media / video / uvc / uvc_video.c
blob9139086f940afef5baeb109e05bf53234d92cf59
1 /*
2 * uvc_video.c -- USB Video Class driver - Video handling
4 * Copyright (C) 2005-2009
5 * Laurent Pinchart (laurent.pinchart@skynet.be)
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
14 #include <linux/kernel.h>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/usb.h>
18 #include <linux/videodev2.h>
19 #include <linux/vmalloc.h>
20 #include <linux/wait.h>
21 #include <asm/atomic.h>
22 #include <asm/unaligned.h>
24 #include <media/v4l2-common.h>
26 #include "uvcvideo.h"
28 /* ------------------------------------------------------------------------
29 * UVC Controls
32 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
33 __u8 intfnum, __u8 cs, void *data, __u16 size,
34 int timeout)
36 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
37 unsigned int pipe;
39 pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
40 : usb_sndctrlpipe(dev->udev, 0);
41 type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
43 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
44 unit << 8 | intfnum, data, size, timeout);
47 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
48 __u8 intfnum, __u8 cs, void *data, __u16 size)
50 int ret;
52 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
53 UVC_CTRL_CONTROL_TIMEOUT);
54 if (ret != size) {
55 uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
56 "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
57 size);
58 return -EIO;
61 return 0;
64 static void uvc_fixup_buffer_size(struct uvc_video_device *video,
65 struct uvc_streaming_control *ctrl)
67 struct uvc_format *format;
68 struct uvc_frame *frame;
70 if (ctrl->bFormatIndex <= 0 ||
71 ctrl->bFormatIndex > video->streaming->nformats)
72 return;
74 format = &video->streaming->format[ctrl->bFormatIndex - 1];
76 if (ctrl->bFrameIndex <= 0 ||
77 ctrl->bFrameIndex > format->nframes)
78 return;
80 frame = &format->frame[ctrl->bFrameIndex - 1];
82 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
83 (ctrl->dwMaxVideoFrameSize == 0 &&
84 video->dev->uvc_version < 0x0110))
85 ctrl->dwMaxVideoFrameSize =
86 frame->dwMaxVideoFrameBufferSize;
89 static int uvc_get_video_ctrl(struct uvc_video_device *video,
90 struct uvc_streaming_control *ctrl, int probe, __u8 query)
92 __u8 *data;
93 __u16 size;
94 int ret;
96 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
97 data = kmalloc(size, GFP_KERNEL);
98 if (data == NULL)
99 return -ENOMEM;
101 ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
102 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
103 UVC_CTRL_STREAMING_TIMEOUT);
105 if ((query == GET_MIN || query == GET_MAX) && ret == 2) {
106 /* Some cameras, mostly based on Bison Electronics chipsets,
107 * answer a GET_MIN or GET_MAX request with the wCompQuality
108 * field only.
110 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
111 "compliance - GET_MIN/MAX(PROBE) incorrectly "
112 "supported. Enabling workaround.\n");
113 memset(ctrl, 0, sizeof ctrl);
114 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
115 ret = 0;
116 goto out;
117 } else if (query == GET_DEF && probe == 1 && ret != size) {
118 /* Many cameras don't support the GET_DEF request on their
119 * video probe control. Warn once and return, the caller will
120 * fall back to GET_CUR.
122 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
123 "compliance - GET_DEF(PROBE) not supported. "
124 "Enabling workaround.\n");
125 ret = -EIO;
126 goto out;
127 } else if (ret != size) {
128 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
129 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
130 ret, size);
131 ret = -EIO;
132 goto out;
135 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
136 ctrl->bFormatIndex = data[2];
137 ctrl->bFrameIndex = data[3];
138 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
139 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
140 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
141 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
142 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
143 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
144 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
145 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
147 if (size == 34) {
148 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
149 ctrl->bmFramingInfo = data[30];
150 ctrl->bPreferedVersion = data[31];
151 ctrl->bMinVersion = data[32];
152 ctrl->bMaxVersion = data[33];
153 } else {
154 ctrl->dwClockFrequency = video->dev->clock_frequency;
155 ctrl->bmFramingInfo = 0;
156 ctrl->bPreferedVersion = 0;
157 ctrl->bMinVersion = 0;
158 ctrl->bMaxVersion = 0;
161 /* Some broken devices return a null or wrong dwMaxVideoFrameSize.
162 * Try to get the value from the format and frame descriptors.
164 uvc_fixup_buffer_size(video, ctrl);
165 ret = 0;
167 out:
168 kfree(data);
169 return ret;
172 static int uvc_set_video_ctrl(struct uvc_video_device *video,
173 struct uvc_streaming_control *ctrl, int probe)
175 __u8 *data;
176 __u16 size;
177 int ret;
179 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
180 data = kzalloc(size, GFP_KERNEL);
181 if (data == NULL)
182 return -ENOMEM;
184 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
185 data[2] = ctrl->bFormatIndex;
186 data[3] = ctrl->bFrameIndex;
187 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
188 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
189 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
190 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
191 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
192 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
193 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
194 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
196 if (size == 34) {
197 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
198 data[30] = ctrl->bmFramingInfo;
199 data[31] = ctrl->bPreferedVersion;
200 data[32] = ctrl->bMinVersion;
201 data[33] = ctrl->bMaxVersion;
204 ret = __uvc_query_ctrl(video->dev, SET_CUR, 0,
205 video->streaming->intfnum,
206 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
207 UVC_CTRL_STREAMING_TIMEOUT);
208 if (ret != size) {
209 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
210 "%d (exp. %u).\n", probe ? "probe" : "commit",
211 ret, size);
212 ret = -EIO;
215 kfree(data);
216 return ret;
219 int uvc_probe_video(struct uvc_video_device *video,
220 struct uvc_streaming_control *probe)
222 struct uvc_streaming_control probe_min, probe_max;
223 __u16 bandwidth;
224 unsigned int i;
225 int ret;
227 mutex_lock(&video->streaming->mutex);
229 /* Perform probing. The device should adjust the requested values
230 * according to its capabilities. However, some devices, namely the
231 * first generation UVC Logitech webcams, don't implement the Video
232 * Probe control properly, and just return the needed bandwidth. For
233 * that reason, if the needed bandwidth exceeds the maximum available
234 * bandwidth, try to lower the quality.
236 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
237 goto done;
239 /* Get the minimum and maximum values for compression settings. */
240 if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
241 ret = uvc_get_video_ctrl(video, &probe_min, 1, GET_MIN);
242 if (ret < 0)
243 goto done;
244 ret = uvc_get_video_ctrl(video, &probe_max, 1, GET_MAX);
245 if (ret < 0)
246 goto done;
248 probe->wCompQuality = probe_max.wCompQuality;
251 for (i = 0; i < 2; ++i) {
252 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0 ||
253 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
254 goto done;
256 if (video->streaming->intf->num_altsetting == 1)
257 break;
259 bandwidth = probe->dwMaxPayloadTransferSize;
260 if (bandwidth <= video->streaming->maxpsize)
261 break;
263 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
264 ret = -ENOSPC;
265 goto done;
268 /* TODO: negotiate compression parameters */
269 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
270 probe->wPFrameRate = probe_min.wPFrameRate;
271 probe->wCompQuality = probe_max.wCompQuality;
272 probe->wCompWindowSize = probe_min.wCompWindowSize;
275 done:
276 mutex_unlock(&video->streaming->mutex);
277 return ret;
280 int uvc_commit_video(struct uvc_video_device *video,
281 struct uvc_streaming_control *probe)
283 return uvc_set_video_ctrl(video, probe, 0);
286 /* ------------------------------------------------------------------------
287 * Video codecs
290 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
291 #define UVC_STREAM_EOH (1 << 7)
292 #define UVC_STREAM_ERR (1 << 6)
293 #define UVC_STREAM_STI (1 << 5)
294 #define UVC_STREAM_RES (1 << 4)
295 #define UVC_STREAM_SCR (1 << 3)
296 #define UVC_STREAM_PTS (1 << 2)
297 #define UVC_STREAM_EOF (1 << 1)
298 #define UVC_STREAM_FID (1 << 0)
300 /* Video payload decoding is handled by uvc_video_decode_start(),
301 * uvc_video_decode_data() and uvc_video_decode_end().
303 * uvc_video_decode_start is called with URB data at the start of a bulk or
304 * isochronous payload. It processes header data and returns the header size
305 * in bytes if successful. If an error occurs, it returns a negative error
306 * code. The following error codes have special meanings.
308 * - EAGAIN informs the caller that the current video buffer should be marked
309 * as done, and that the function should be called again with the same data
310 * and a new video buffer. This is used when end of frame conditions can be
311 * reliably detected at the beginning of the next frame only.
313 * If an error other than -EAGAIN is returned, the caller will drop the current
314 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
315 * made until the next payload. -ENODATA can be used to drop the current
316 * payload if no other error code is appropriate.
318 * uvc_video_decode_data is called for every URB with URB data. It copies the
319 * data to the video buffer.
321 * uvc_video_decode_end is called with header data at the end of a bulk or
322 * isochronous payload. It performs any additional header data processing and
323 * returns 0 or a negative error code if an error occured. As header data have
324 * already been processed by uvc_video_decode_start, this functions isn't
325 * required to perform sanity checks a second time.
327 * For isochronous transfers where a payload is always transfered in a single
328 * URB, the three functions will be called in a row.
330 * To let the decoder process header data and update its internal state even
331 * when no video buffer is available, uvc_video_decode_start must be prepared
332 * to be called with a NULL buf parameter. uvc_video_decode_data and
333 * uvc_video_decode_end will never be called with a NULL buffer.
335 static int uvc_video_decode_start(struct uvc_video_device *video,
336 struct uvc_buffer *buf, const __u8 *data, int len)
338 __u8 fid;
340 /* Sanity checks:
341 * - packet must be at least 2 bytes long
342 * - bHeaderLength value must be at least 2 bytes (see above)
343 * - bHeaderLength value can't be larger than the packet size.
345 if (len < 2 || data[0] < 2 || data[0] > len)
346 return -EINVAL;
348 /* Skip payloads marked with the error bit ("error frames"). */
349 if (data[1] & UVC_STREAM_ERR) {
350 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
351 "set).\n");
352 return -ENODATA;
355 fid = data[1] & UVC_STREAM_FID;
357 /* Store the payload FID bit and return immediately when the buffer is
358 * NULL.
360 if (buf == NULL) {
361 video->last_fid = fid;
362 return -ENODATA;
365 /* Synchronize to the input stream by waiting for the FID bit to be
366 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
367 * video->last_fid is initialized to -1, so the first isochronous
368 * frame will always be in sync.
370 * If the device doesn't toggle the FID bit, invert video->last_fid
371 * when the EOF bit is set to force synchronisation on the next packet.
373 if (buf->state != UVC_BUF_STATE_ACTIVE) {
374 if (fid == video->last_fid) {
375 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
376 "sync).\n");
377 if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
378 (data[1] & UVC_STREAM_EOF))
379 video->last_fid ^= UVC_STREAM_FID;
380 return -ENODATA;
383 /* TODO: Handle PTS and SCR. */
384 buf->state = UVC_BUF_STATE_ACTIVE;
387 /* Mark the buffer as done if we're at the beginning of a new frame.
388 * End of frame detection is better implemented by checking the EOF
389 * bit (FID bit toggling is delayed by one frame compared to the EOF
390 * bit), but some devices don't set the bit at end of frame (and the
391 * last payload can be lost anyway). We thus must check if the FID has
392 * been toggled.
394 * video->last_fid is initialized to -1, so the first isochronous
395 * frame will never trigger an end of frame detection.
397 * Empty buffers (bytesused == 0) don't trigger end of frame detection
398 * as it doesn't make sense to return an empty buffer. This also
399 * avoids detecting end of frame conditions at FID toggling if the
400 * previous payload had the EOF bit set.
402 if (fid != video->last_fid && buf->buf.bytesused != 0) {
403 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
404 "toggled).\n");
405 buf->state = UVC_BUF_STATE_DONE;
406 return -EAGAIN;
409 video->last_fid = fid;
411 return data[0];
414 static void uvc_video_decode_data(struct uvc_video_device *video,
415 struct uvc_buffer *buf, const __u8 *data, int len)
417 struct uvc_video_queue *queue = &video->queue;
418 unsigned int maxlen, nbytes;
419 void *mem;
421 if (len <= 0)
422 return;
424 /* Copy the video data to the buffer. */
425 maxlen = buf->buf.length - buf->buf.bytesused;
426 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
427 nbytes = min((unsigned int)len, maxlen);
428 memcpy(mem, data, nbytes);
429 buf->buf.bytesused += nbytes;
431 /* Complete the current frame if the buffer size was exceeded. */
432 if (len > maxlen) {
433 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
434 buf->state = UVC_BUF_STATE_DONE;
438 static void uvc_video_decode_end(struct uvc_video_device *video,
439 struct uvc_buffer *buf, const __u8 *data, int len)
441 /* Mark the buffer as done if the EOF marker is set. */
442 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
443 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
444 if (data[0] == len)
445 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
446 buf->state = UVC_BUF_STATE_DONE;
447 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
448 video->last_fid ^= UVC_STREAM_FID;
452 /* Video payload encoding is handled by uvc_video_encode_header() and
453 * uvc_video_encode_data(). Only bulk transfers are currently supported.
455 * uvc_video_encode_header is called at the start of a payload. It adds header
456 * data to the transfer buffer and returns the header size. As the only known
457 * UVC output device transfers a whole frame in a single payload, the EOF bit
458 * is always set in the header.
460 * uvc_video_encode_data is called for every URB and copies the data from the
461 * video buffer to the transfer buffer.
463 static int uvc_video_encode_header(struct uvc_video_device *video,
464 struct uvc_buffer *buf, __u8 *data, int len)
466 data[0] = 2; /* Header length */
467 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
468 | (video->last_fid & UVC_STREAM_FID);
469 return 2;
472 static int uvc_video_encode_data(struct uvc_video_device *video,
473 struct uvc_buffer *buf, __u8 *data, int len)
475 struct uvc_video_queue *queue = &video->queue;
476 unsigned int nbytes;
477 void *mem;
479 /* Copy video data to the URB buffer. */
480 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
481 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
482 nbytes = min(video->bulk.max_payload_size - video->bulk.payload_size,
483 nbytes);
484 memcpy(data, mem, nbytes);
486 queue->buf_used += nbytes;
488 return nbytes;
491 /* ------------------------------------------------------------------------
492 * URB handling
496 * Completion handler for video URBs.
498 static void uvc_video_decode_isoc(struct urb *urb,
499 struct uvc_video_device *video, struct uvc_buffer *buf)
501 u8 *mem;
502 int ret, i;
504 for (i = 0; i < urb->number_of_packets; ++i) {
505 if (urb->iso_frame_desc[i].status < 0) {
506 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
507 "lost (%d).\n", urb->iso_frame_desc[i].status);
508 continue;
511 /* Decode the payload header. */
512 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
513 do {
514 ret = uvc_video_decode_start(video, buf, mem,
515 urb->iso_frame_desc[i].actual_length);
516 if (ret == -EAGAIN)
517 buf = uvc_queue_next_buffer(&video->queue, buf);
518 } while (ret == -EAGAIN);
520 if (ret < 0)
521 continue;
523 /* Decode the payload data. */
524 uvc_video_decode_data(video, buf, mem + ret,
525 urb->iso_frame_desc[i].actual_length - ret);
527 /* Process the header again. */
528 uvc_video_decode_end(video, buf, mem,
529 urb->iso_frame_desc[i].actual_length);
531 if (buf->state == UVC_BUF_STATE_DONE ||
532 buf->state == UVC_BUF_STATE_ERROR)
533 buf = uvc_queue_next_buffer(&video->queue, buf);
537 static void uvc_video_decode_bulk(struct urb *urb,
538 struct uvc_video_device *video, struct uvc_buffer *buf)
540 u8 *mem;
541 int len, ret;
543 mem = urb->transfer_buffer;
544 len = urb->actual_length;
545 video->bulk.payload_size += len;
547 /* If the URB is the first of its payload, decode and save the
548 * header.
550 if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
551 do {
552 ret = uvc_video_decode_start(video, buf, mem, len);
553 if (ret == -EAGAIN)
554 buf = uvc_queue_next_buffer(&video->queue, buf);
555 } while (ret == -EAGAIN);
557 /* If an error occured skip the rest of the payload. */
558 if (ret < 0 || buf == NULL) {
559 video->bulk.skip_payload = 1;
560 } else {
561 memcpy(video->bulk.header, mem, ret);
562 video->bulk.header_size = ret;
564 mem += ret;
565 len -= ret;
569 /* The buffer queue might have been cancelled while a bulk transfer
570 * was in progress, so we can reach here with buf equal to NULL. Make
571 * sure buf is never dereferenced if NULL.
574 /* Process video data. */
575 if (!video->bulk.skip_payload && buf != NULL)
576 uvc_video_decode_data(video, buf, mem, len);
578 /* Detect the payload end by a URB smaller than the maximum size (or
579 * a payload size equal to the maximum) and process the header again.
581 if (urb->actual_length < urb->transfer_buffer_length ||
582 video->bulk.payload_size >= video->bulk.max_payload_size) {
583 if (!video->bulk.skip_payload && buf != NULL) {
584 uvc_video_decode_end(video, buf, video->bulk.header,
585 video->bulk.payload_size);
586 if (buf->state == UVC_BUF_STATE_DONE ||
587 buf->state == UVC_BUF_STATE_ERROR)
588 buf = uvc_queue_next_buffer(&video->queue, buf);
591 video->bulk.header_size = 0;
592 video->bulk.skip_payload = 0;
593 video->bulk.payload_size = 0;
597 static void uvc_video_encode_bulk(struct urb *urb,
598 struct uvc_video_device *video, struct uvc_buffer *buf)
600 u8 *mem = urb->transfer_buffer;
601 int len = video->urb_size, ret;
603 if (buf == NULL) {
604 urb->transfer_buffer_length = 0;
605 return;
608 /* If the URB is the first of its payload, add the header. */
609 if (video->bulk.header_size == 0) {
610 ret = uvc_video_encode_header(video, buf, mem, len);
611 video->bulk.header_size = ret;
612 video->bulk.payload_size += ret;
613 mem += ret;
614 len -= ret;
617 /* Process video data. */
618 ret = uvc_video_encode_data(video, buf, mem, len);
620 video->bulk.payload_size += ret;
621 len -= ret;
623 if (buf->buf.bytesused == video->queue.buf_used ||
624 video->bulk.payload_size == video->bulk.max_payload_size) {
625 if (buf->buf.bytesused == video->queue.buf_used) {
626 video->queue.buf_used = 0;
627 buf->state = UVC_BUF_STATE_DONE;
628 uvc_queue_next_buffer(&video->queue, buf);
629 video->last_fid ^= UVC_STREAM_FID;
632 video->bulk.header_size = 0;
633 video->bulk.payload_size = 0;
636 urb->transfer_buffer_length = video->urb_size - len;
639 static void uvc_video_complete(struct urb *urb)
641 struct uvc_video_device *video = urb->context;
642 struct uvc_video_queue *queue = &video->queue;
643 struct uvc_buffer *buf = NULL;
644 unsigned long flags;
645 int ret;
647 switch (urb->status) {
648 case 0:
649 break;
651 default:
652 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
653 "completion handler.\n", urb->status);
655 case -ENOENT: /* usb_kill_urb() called. */
656 if (video->frozen)
657 return;
659 case -ECONNRESET: /* usb_unlink_urb() called. */
660 case -ESHUTDOWN: /* The endpoint is being disabled. */
661 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
662 return;
665 spin_lock_irqsave(&queue->irqlock, flags);
666 if (!list_empty(&queue->irqqueue))
667 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
668 queue);
669 spin_unlock_irqrestore(&queue->irqlock, flags);
671 video->decode(urb, video, buf);
673 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
674 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
675 ret);
680 * Free transfer buffers.
682 static void uvc_free_urb_buffers(struct uvc_video_device *video)
684 unsigned int i;
686 for (i = 0; i < UVC_URBS; ++i) {
687 if (video->urb_buffer[i]) {
688 usb_buffer_free(video->dev->udev, video->urb_size,
689 video->urb_buffer[i], video->urb_dma[i]);
690 video->urb_buffer[i] = NULL;
694 video->urb_size = 0;
698 * Allocate transfer buffers. This function can be called with buffers
699 * already allocated when resuming from suspend, in which case it will
700 * return without touching the buffers.
702 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
703 * system is too low on memory try successively smaller numbers of packets
704 * until allocation succeeds.
706 * Return the number of allocated packets on success or 0 when out of memory.
708 static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
709 unsigned int size, unsigned int psize, gfp_t gfp_flags)
711 unsigned int npackets;
712 unsigned int i;
714 /* Buffers are already allocated, bail out. */
715 if (video->urb_size)
716 return 0;
718 /* Compute the number of packets. Bulk endpoints might transfer UVC
719 * payloads accross multiple URBs.
721 npackets = DIV_ROUND_UP(size, psize);
722 if (npackets > UVC_MAX_PACKETS)
723 npackets = UVC_MAX_PACKETS;
725 /* Retry allocations until one succeed. */
726 for (; npackets > 1; npackets /= 2) {
727 for (i = 0; i < UVC_URBS; ++i) {
728 video->urb_buffer[i] = usb_buffer_alloc(
729 video->dev->udev, psize * npackets,
730 gfp_flags | __GFP_NOWARN, &video->urb_dma[i]);
731 if (!video->urb_buffer[i]) {
732 uvc_free_urb_buffers(video);
733 break;
737 if (i == UVC_URBS) {
738 video->urb_size = psize * npackets;
739 return npackets;
743 return 0;
747 * Uninitialize isochronous/bulk URBs and free transfer buffers.
749 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
751 struct urb *urb;
752 unsigned int i;
754 for (i = 0; i < UVC_URBS; ++i) {
755 if ((urb = video->urb[i]) == NULL)
756 continue;
758 usb_kill_urb(urb);
759 usb_free_urb(urb);
760 video->urb[i] = NULL;
763 if (free_buffers)
764 uvc_free_urb_buffers(video);
768 * Initialize isochronous URBs and allocate transfer buffers. The packet size
769 * is given by the endpoint.
771 static int uvc_init_video_isoc(struct uvc_video_device *video,
772 struct usb_host_endpoint *ep, gfp_t gfp_flags)
774 struct urb *urb;
775 unsigned int npackets, i, j;
776 u16 psize;
777 u32 size;
779 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
780 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
781 size = video->streaming->ctrl.dwMaxVideoFrameSize;
783 npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
784 if (npackets == 0)
785 return -ENOMEM;
787 size = npackets * psize;
789 for (i = 0; i < UVC_URBS; ++i) {
790 urb = usb_alloc_urb(npackets, gfp_flags);
791 if (urb == NULL) {
792 uvc_uninit_video(video, 1);
793 return -ENOMEM;
796 urb->dev = video->dev->udev;
797 urb->context = video;
798 urb->pipe = usb_rcvisocpipe(video->dev->udev,
799 ep->desc.bEndpointAddress);
800 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
801 urb->interval = ep->desc.bInterval;
802 urb->transfer_buffer = video->urb_buffer[i];
803 urb->transfer_dma = video->urb_dma[i];
804 urb->complete = uvc_video_complete;
805 urb->number_of_packets = npackets;
806 urb->transfer_buffer_length = size;
808 for (j = 0; j < npackets; ++j) {
809 urb->iso_frame_desc[j].offset = j * psize;
810 urb->iso_frame_desc[j].length = psize;
813 video->urb[i] = urb;
816 return 0;
820 * Initialize bulk URBs and allocate transfer buffers. The packet size is
821 * given by the endpoint.
823 static int uvc_init_video_bulk(struct uvc_video_device *video,
824 struct usb_host_endpoint *ep, gfp_t gfp_flags)
826 struct urb *urb;
827 unsigned int npackets, pipe, i;
828 u16 psize;
829 u32 size;
831 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
832 size = video->streaming->ctrl.dwMaxPayloadTransferSize;
833 video->bulk.max_payload_size = size;
835 npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
836 if (npackets == 0)
837 return -ENOMEM;
839 size = npackets * psize;
841 if (usb_endpoint_dir_in(&ep->desc))
842 pipe = usb_rcvbulkpipe(video->dev->udev,
843 ep->desc.bEndpointAddress);
844 else
845 pipe = usb_sndbulkpipe(video->dev->udev,
846 ep->desc.bEndpointAddress);
848 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
849 size = 0;
851 for (i = 0; i < UVC_URBS; ++i) {
852 urb = usb_alloc_urb(0, gfp_flags);
853 if (urb == NULL) {
854 uvc_uninit_video(video, 1);
855 return -ENOMEM;
858 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
859 video->urb_buffer[i], size, uvc_video_complete,
860 video);
861 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
862 urb->transfer_dma = video->urb_dma[i];
864 video->urb[i] = urb;
867 return 0;
871 * Initialize isochronous/bulk URBs and allocate transfer buffers.
873 static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
875 struct usb_interface *intf = video->streaming->intf;
876 struct usb_host_interface *alts;
877 struct usb_host_endpoint *ep = NULL;
878 int intfnum = video->streaming->intfnum;
879 unsigned int bandwidth, psize, i;
880 int ret;
882 video->last_fid = -1;
883 video->bulk.header_size = 0;
884 video->bulk.skip_payload = 0;
885 video->bulk.payload_size = 0;
887 if (intf->num_altsetting > 1) {
888 /* Isochronous endpoint, select the alternate setting. */
889 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
891 if (bandwidth == 0) {
892 uvc_printk(KERN_WARNING, "device %s requested null "
893 "bandwidth, defaulting to lowest.\n",
894 video->vdev->name);
895 bandwidth = 1;
898 for (i = 0; i < intf->num_altsetting; ++i) {
899 alts = &intf->altsetting[i];
900 ep = uvc_find_endpoint(alts,
901 video->streaming->header.bEndpointAddress);
902 if (ep == NULL)
903 continue;
905 /* Check if the bandwidth is high enough. */
906 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
907 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
908 if (psize >= bandwidth)
909 break;
912 if (i >= intf->num_altsetting)
913 return -EIO;
915 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
916 return ret;
918 ret = uvc_init_video_isoc(video, ep, gfp_flags);
919 } else {
920 /* Bulk endpoint, proceed to URB initialization. */
921 ep = uvc_find_endpoint(&intf->altsetting[0],
922 video->streaming->header.bEndpointAddress);
923 if (ep == NULL)
924 return -EIO;
926 ret = uvc_init_video_bulk(video, ep, gfp_flags);
929 if (ret < 0)
930 return ret;
932 /* Submit the URBs. */
933 for (i = 0; i < UVC_URBS; ++i) {
934 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
935 uvc_printk(KERN_ERR, "Failed to submit URB %u "
936 "(%d).\n", i, ret);
937 uvc_uninit_video(video, 1);
938 return ret;
942 return 0;
945 /* --------------------------------------------------------------------------
946 * Suspend/resume
950 * Stop streaming without disabling the video queue.
952 * To let userspace applications resume without trouble, we must not touch the
953 * video buffers in any way. We mark the device as frozen to make sure the URB
954 * completion handler won't try to cancel the queue when we kill the URBs.
956 int uvc_video_suspend(struct uvc_video_device *video)
958 if (!uvc_queue_streaming(&video->queue))
959 return 0;
961 video->frozen = 1;
962 uvc_uninit_video(video, 0);
963 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
964 return 0;
968 * Reconfigure the video interface and restart streaming if it was enabled
969 * before suspend.
971 * If an error occurs, disable the video queue. This will wake all pending
972 * buffers, making sure userspace applications are notified of the problem
973 * instead of waiting forever.
975 int uvc_video_resume(struct uvc_video_device *video)
977 int ret;
979 video->frozen = 0;
981 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
982 uvc_queue_enable(&video->queue, 0);
983 return ret;
986 if (!uvc_queue_streaming(&video->queue))
987 return 0;
989 if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
990 uvc_queue_enable(&video->queue, 0);
992 return ret;
995 /* ------------------------------------------------------------------------
996 * Video device
1000 * Initialize the UVC video device by switching to alternate setting 0 and
1001 * retrieve the default format.
1003 * Some cameras (namely the Fuji Finepix) set the format and frame
1004 * indexes to zero. The UVC standard doesn't clearly make this a spec
1005 * violation, so try to silently fix the values if possible.
1007 * This function is called before registering the device with V4L.
1009 int uvc_video_init(struct uvc_video_device *video)
1011 struct uvc_streaming_control *probe = &video->streaming->ctrl;
1012 struct uvc_format *format = NULL;
1013 struct uvc_frame *frame = NULL;
1014 unsigned int i;
1015 int ret;
1017 if (video->streaming->nformats == 0) {
1018 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1019 return -EINVAL;
1022 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1023 * Cam (and possibly other devices) crash or otherwise misbehave if
1024 * they don't receive a SET_INTERFACE request before any other video
1025 * control request.
1027 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1029 /* Set the streaming probe control with default streaming parameters
1030 * retrieved from the device. Webcams that don't suport GET_DEF
1031 * requests on the probe control will just keep their current streaming
1032 * parameters.
1034 if (uvc_get_video_ctrl(video, probe, 1, GET_DEF) == 0)
1035 uvc_set_video_ctrl(video, probe, 1);
1037 /* Initialize the streaming parameters with the probe control current
1038 * value. This makes sure SET_CUR requests on the streaming commit
1039 * control will always use values retrieved from a successful GET_CUR
1040 * request on the probe control, as required by the UVC specification.
1042 if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
1043 return ret;
1045 /* Check if the default format descriptor exists. Use the first
1046 * available format otherwise.
1048 for (i = video->streaming->nformats; i > 0; --i) {
1049 format = &video->streaming->format[i-1];
1050 if (format->index == probe->bFormatIndex)
1051 break;
1054 if (format->nframes == 0) {
1055 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1056 "default format.\n");
1057 return -EINVAL;
1060 /* Zero bFrameIndex might be correct. Stream-based formats (including
1061 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1062 * descriptor with bFrameIndex set to zero. If the default frame
1063 * descriptor is not found, use the first avalable frame.
1065 for (i = format->nframes; i > 0; --i) {
1066 frame = &format->frame[i-1];
1067 if (frame->bFrameIndex == probe->bFrameIndex)
1068 break;
1071 probe->bFormatIndex = format->index;
1072 probe->bFrameIndex = frame->bFrameIndex;
1074 video->streaming->cur_format = format;
1075 video->streaming->cur_frame = frame;
1076 atomic_set(&video->active, 0);
1078 /* Select the video decoding function */
1079 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1080 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1081 video->decode = uvc_video_decode_isight;
1082 else if (video->streaming->intf->num_altsetting > 1)
1083 video->decode = uvc_video_decode_isoc;
1084 else
1085 video->decode = uvc_video_decode_bulk;
1086 } else {
1087 if (video->streaming->intf->num_altsetting == 1)
1088 video->decode = uvc_video_encode_bulk;
1089 else {
1090 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1091 "supported for video output devices.\n");
1092 return -EINVAL;
1096 return 0;
1100 * Enable or disable the video stream.
1102 int uvc_video_enable(struct uvc_video_device *video, int enable)
1104 int ret;
1106 if (!enable) {
1107 uvc_uninit_video(video, 1);
1108 usb_set_interface(video->dev->udev,
1109 video->streaming->intfnum, 0);
1110 uvc_queue_enable(&video->queue, 0);
1111 return 0;
1114 if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1115 uvc_no_drop_param)
1116 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1117 else
1118 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1120 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1121 return ret;
1123 /* Commit the streaming parameters. */
1124 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1125 return ret;
1127 return uvc_init_video(video, GFP_KERNEL);