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>
28 /* ------------------------------------------------------------------------
32 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
33 __u8 intfnum, __u8 cs, void *data, __u16 size,
36 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
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)
52 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
53 UVC_CTRL_CONTROL_TIMEOUT);
55 uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
56 "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
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)
74 format = &video->streaming->format[ctrl->bFormatIndex - 1];
76 if (ctrl->bFrameIndex <= 0 ||
77 ctrl->bFrameIndex > format->nframes)
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)
96 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
97 data = kmalloc(size, GFP_KERNEL);
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
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);
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");
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",
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]);
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];
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);
172 static int uvc_set_video_ctrl(struct uvc_video_device *video,
173 struct uvc_streaming_control *ctrl, int probe)
179 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
180 data = kzalloc(size, GFP_KERNEL);
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]);
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);
209 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
210 "%d (exp. %u).\n", probe ? "probe" : "commit",
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;
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)
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);
244 ret = uvc_get_video_ctrl(video, &probe_max, 1, GET_MAX);
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)
256 if (video->streaming->intf->num_altsetting == 1)
259 bandwidth = probe->dwMaxPayloadTransferSize;
260 if (bandwidth <= video->streaming->maxpsize)
263 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
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;
276 mutex_unlock(&video->streaming->mutex);
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 /* ------------------------------------------------------------------------
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)
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)
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 "
355 fid = data[1] & UVC_STREAM_FID;
357 /* Store the payload FID bit and return immediately when the buffer is
361 video->last_fid = fid;
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 "
377 if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
378 (data[1] & UVC_STREAM_EOF))
379 video->last_fid ^= UVC_STREAM_FID;
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
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 "
405 buf->state = UVC_BUF_STATE_DONE;
409 video->last_fid = fid;
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;
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. */
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");
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);
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;
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,
484 memcpy(data, mem, nbytes);
486 queue->buf_used += nbytes;
491 /* ------------------------------------------------------------------------
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)
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);
511 /* Decode the payload header. */
512 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
514 ret = uvc_video_decode_start(video, buf, mem,
515 urb->iso_frame_desc[i].actual_length);
517 buf = uvc_queue_next_buffer(&video->queue, buf);
518 } while (ret == -EAGAIN);
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)
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
550 if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
552 ret = uvc_video_decode_start(video, buf, mem, len);
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;
561 memcpy(video->bulk.header, mem, ret);
562 video->bulk.header_size = 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;
604 urb->transfer_buffer_length = 0;
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;
617 /* Process video data. */
618 ret = uvc_video_encode_data(video, buf, mem, len);
620 video->bulk.payload_size += 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;
647 switch (urb->status) {
652 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
653 "completion handler.\n", urb->status);
655 case -ENOENT: /* usb_kill_urb() called. */
659 case -ECONNRESET: /* usb_unlink_urb() called. */
660 case -ESHUTDOWN: /* The endpoint is being disabled. */
661 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
665 spin_lock_irqsave(&queue->irqlock, flags);
666 if (!list_empty(&queue->irqqueue))
667 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
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",
680 * Free transfer buffers.
682 static void uvc_free_urb_buffers(struct uvc_video_device *video)
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;
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;
714 /* Buffers are already allocated, bail out. */
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);
738 video->urb_size = psize * npackets;
747 * Uninitialize isochronous/bulk URBs and free transfer buffers.
749 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
754 for (i = 0; i < UVC_URBS; ++i) {
755 if ((urb = video->urb[i]) == NULL)
760 video->urb[i] = NULL;
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)
775 unsigned int npackets, i, j;
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);
787 size = npackets * psize;
789 for (i = 0; i < UVC_URBS; ++i) {
790 urb = usb_alloc_urb(npackets, gfp_flags);
792 uvc_uninit_video(video, 1);
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;
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)
827 unsigned int npackets, pipe, i;
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);
839 size = npackets * psize;
841 if (usb_endpoint_dir_in(&ep->desc))
842 pipe = usb_rcvbulkpipe(video->dev->udev,
843 ep->desc.bEndpointAddress);
845 pipe = usb_sndbulkpipe(video->dev->udev,
846 ep->desc.bEndpointAddress);
848 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
851 for (i = 0; i < UVC_URBS; ++i) {
852 urb = usb_alloc_urb(0, gfp_flags);
854 uvc_uninit_video(video, 1);
858 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
859 video->urb_buffer[i], size, uvc_video_complete,
861 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
862 urb->transfer_dma = video->urb_dma[i];
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;
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",
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);
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)
912 if (i >= intf->num_altsetting)
915 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
918 ret = uvc_init_video_isoc(video, ep, gfp_flags);
920 /* Bulk endpoint, proceed to URB initialization. */
921 ep = uvc_find_endpoint(&intf->altsetting[0],
922 video->streaming->header.bEndpointAddress);
926 ret = uvc_init_video_bulk(video, ep, gfp_flags);
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 "
937 uvc_uninit_video(video, 1);
945 /* --------------------------------------------------------------------------
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))
962 uvc_uninit_video(video, 0);
963 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
968 * Reconfigure the video interface and restart streaming if it was enabled
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)
981 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
982 uvc_queue_enable(&video->queue, 0);
986 if (!uvc_queue_streaming(&video->queue))
989 if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
990 uvc_queue_enable(&video->queue, 0);
995 /* ------------------------------------------------------------------------
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;
1017 if (video->streaming->nformats == 0) {
1018 uvc_printk(KERN_INFO, "No supported video formats found.\n");
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
1027 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1029 /* Some webcams don't suport GET_DEF requests on the probe control. We
1030 * fall back to GET_CUR if GET_DEF fails.
1032 if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_DEF)) < 0 &&
1033 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
1036 /* Check if the default format descriptor exists. Use the first
1037 * available format otherwise.
1039 for (i = video->streaming->nformats; i > 0; --i) {
1040 format = &video->streaming->format[i-1];
1041 if (format->index == probe->bFormatIndex)
1045 if (format->nframes == 0) {
1046 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1047 "default format.\n");
1051 /* Zero bFrameIndex might be correct. Stream-based formats (including
1052 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1053 * descriptor with bFrameIndex set to zero. If the default frame
1054 * descriptor is not found, use the first avalable frame.
1056 for (i = format->nframes; i > 0; --i) {
1057 frame = &format->frame[i-1];
1058 if (frame->bFrameIndex == probe->bFrameIndex)
1062 probe->bFormatIndex = format->index;
1063 probe->bFrameIndex = frame->bFrameIndex;
1065 video->streaming->cur_format = format;
1066 video->streaming->cur_frame = frame;
1067 atomic_set(&video->active, 0);
1069 /* Select the video decoding function */
1070 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1071 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1072 video->decode = uvc_video_decode_isight;
1073 else if (video->streaming->intf->num_altsetting > 1)
1074 video->decode = uvc_video_decode_isoc;
1076 video->decode = uvc_video_decode_bulk;
1078 if (video->streaming->intf->num_altsetting == 1)
1079 video->decode = uvc_video_encode_bulk;
1081 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1082 "supported for video output devices.\n");
1091 * Enable or disable the video stream.
1093 int uvc_video_enable(struct uvc_video_device *video, int enable)
1098 uvc_uninit_video(video, 1);
1099 usb_set_interface(video->dev->udev,
1100 video->streaming->intfnum, 0);
1101 uvc_queue_enable(&video->queue, 0);
1105 if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1107 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1109 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1111 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1114 /* Commit the streaming parameters. */
1115 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1118 return uvc_init_video(video, GFP_KERNEL);