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_video_ctrl(struct uvc_video_device *video,
65 struct uvc_streaming_control *ctrl)
67 struct uvc_format *format;
68 struct uvc_frame *frame = NULL;
71 if (ctrl->bFormatIndex <= 0 ||
72 ctrl->bFormatIndex > video->streaming->nformats)
75 format = &video->streaming->format[ctrl->bFormatIndex - 1];
77 for (i = 0; i < format->nframes; ++i) {
78 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
79 frame = &format->frame[i];
87 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
88 (ctrl->dwMaxVideoFrameSize == 0 &&
89 video->dev->uvc_version < 0x0110))
90 ctrl->dwMaxVideoFrameSize =
91 frame->dwMaxVideoFrameBufferSize;
93 if (video->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
94 video->streaming->intf->num_altsetting > 1) {
98 interval = (ctrl->dwFrameInterval > 100000)
99 ? ctrl->dwFrameInterval
100 : frame->dwFrameInterval[0];
102 /* Compute a bandwidth estimation by multiplying the frame
103 * size by the number of video frames per second, divide the
104 * result by the number of USB frames (or micro-frames for
105 * high-speed devices) per second and add the UVC header size
106 * (assumed to be 12 bytes long).
108 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
109 bandwidth *= 10000000 / interval + 1;
111 if (video->dev->udev->speed == USB_SPEED_HIGH)
115 ctrl->dwMaxPayloadTransferSize = bandwidth;
119 static int uvc_get_video_ctrl(struct uvc_video_device *video,
120 struct uvc_streaming_control *ctrl, int probe, __u8 query)
126 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
127 data = kmalloc(size, GFP_KERNEL);
131 ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
132 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
133 size, UVC_CTRL_STREAMING_TIMEOUT);
135 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
136 /* Some cameras, mostly based on Bison Electronics chipsets,
137 * answer a GET_MIN or GET_MAX request with the wCompQuality
140 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
141 "compliance - GET_MIN/MAX(PROBE) incorrectly "
142 "supported. Enabling workaround.\n");
143 memset(ctrl, 0, sizeof ctrl);
144 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
147 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
148 /* Many cameras don't support the GET_DEF request on their
149 * video probe control. Warn once and return, the caller will
150 * fall back to GET_CUR.
152 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
153 "compliance - GET_DEF(PROBE) not supported. "
154 "Enabling workaround.\n");
157 } else if (ret != size) {
158 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
159 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
165 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
166 ctrl->bFormatIndex = data[2];
167 ctrl->bFrameIndex = data[3];
168 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
169 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
170 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
171 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
172 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
173 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
174 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
175 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
178 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
179 ctrl->bmFramingInfo = data[30];
180 ctrl->bPreferedVersion = data[31];
181 ctrl->bMinVersion = data[32];
182 ctrl->bMaxVersion = data[33];
184 ctrl->dwClockFrequency = video->dev->clock_frequency;
185 ctrl->bmFramingInfo = 0;
186 ctrl->bPreferedVersion = 0;
187 ctrl->bMinVersion = 0;
188 ctrl->bMaxVersion = 0;
191 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
192 * dwMaxPayloadTransferSize fields. Try to get the value from the
193 * format and frame descriptors.
195 uvc_fixup_video_ctrl(video, ctrl);
203 static int uvc_set_video_ctrl(struct uvc_video_device *video,
204 struct uvc_streaming_control *ctrl, int probe)
210 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
211 data = kzalloc(size, GFP_KERNEL);
215 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
216 data[2] = ctrl->bFormatIndex;
217 data[3] = ctrl->bFrameIndex;
218 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
219 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
220 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
221 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
222 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
223 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
224 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
225 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
228 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
229 data[30] = ctrl->bmFramingInfo;
230 data[31] = ctrl->bPreferedVersion;
231 data[32] = ctrl->bMinVersion;
232 data[33] = ctrl->bMaxVersion;
235 ret = __uvc_query_ctrl(video->dev, UVC_SET_CUR, 0,
236 video->streaming->intfnum,
237 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
238 size, UVC_CTRL_STREAMING_TIMEOUT);
240 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
241 "%d (exp. %u).\n", probe ? "probe" : "commit",
250 int uvc_probe_video(struct uvc_video_device *video,
251 struct uvc_streaming_control *probe)
253 struct uvc_streaming_control probe_min, probe_max;
258 mutex_lock(&video->streaming->mutex);
260 /* Perform probing. The device should adjust the requested values
261 * according to its capabilities. However, some devices, namely the
262 * first generation UVC Logitech webcams, don't implement the Video
263 * Probe control properly, and just return the needed bandwidth. For
264 * that reason, if the needed bandwidth exceeds the maximum available
265 * bandwidth, try to lower the quality.
267 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
270 /* Get the minimum and maximum values for compression settings. */
271 if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
272 ret = uvc_get_video_ctrl(video, &probe_min, 1, UVC_GET_MIN);
275 ret = uvc_get_video_ctrl(video, &probe_max, 1, UVC_GET_MAX);
279 probe->wCompQuality = probe_max.wCompQuality;
282 for (i = 0; i < 2; ++i) {
283 ret = uvc_set_video_ctrl(video, probe, 1);
286 ret = uvc_get_video_ctrl(video, probe, 1, UVC_GET_CUR);
290 if (video->streaming->intf->num_altsetting == 1)
293 bandwidth = probe->dwMaxPayloadTransferSize;
294 if (bandwidth <= video->streaming->maxpsize)
297 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
302 /* TODO: negotiate compression parameters */
303 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
304 probe->wPFrameRate = probe_min.wPFrameRate;
305 probe->wCompQuality = probe_max.wCompQuality;
306 probe->wCompWindowSize = probe_min.wCompWindowSize;
310 mutex_unlock(&video->streaming->mutex);
314 int uvc_commit_video(struct uvc_video_device *video,
315 struct uvc_streaming_control *probe)
317 return uvc_set_video_ctrl(video, probe, 0);
320 /* ------------------------------------------------------------------------
324 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
325 #define UVC_STREAM_EOH (1 << 7)
326 #define UVC_STREAM_ERR (1 << 6)
327 #define UVC_STREAM_STI (1 << 5)
328 #define UVC_STREAM_RES (1 << 4)
329 #define UVC_STREAM_SCR (1 << 3)
330 #define UVC_STREAM_PTS (1 << 2)
331 #define UVC_STREAM_EOF (1 << 1)
332 #define UVC_STREAM_FID (1 << 0)
334 /* Video payload decoding is handled by uvc_video_decode_start(),
335 * uvc_video_decode_data() and uvc_video_decode_end().
337 * uvc_video_decode_start is called with URB data at the start of a bulk or
338 * isochronous payload. It processes header data and returns the header size
339 * in bytes if successful. If an error occurs, it returns a negative error
340 * code. The following error codes have special meanings.
342 * - EAGAIN informs the caller that the current video buffer should be marked
343 * as done, and that the function should be called again with the same data
344 * and a new video buffer. This is used when end of frame conditions can be
345 * reliably detected at the beginning of the next frame only.
347 * If an error other than -EAGAIN is returned, the caller will drop the current
348 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
349 * made until the next payload. -ENODATA can be used to drop the current
350 * payload if no other error code is appropriate.
352 * uvc_video_decode_data is called for every URB with URB data. It copies the
353 * data to the video buffer.
355 * uvc_video_decode_end is called with header data at the end of a bulk or
356 * isochronous payload. It performs any additional header data processing and
357 * returns 0 or a negative error code if an error occured. As header data have
358 * already been processed by uvc_video_decode_start, this functions isn't
359 * required to perform sanity checks a second time.
361 * For isochronous transfers where a payload is always transfered in a single
362 * URB, the three functions will be called in a row.
364 * To let the decoder process header data and update its internal state even
365 * when no video buffer is available, uvc_video_decode_start must be prepared
366 * to be called with a NULL buf parameter. uvc_video_decode_data and
367 * uvc_video_decode_end will never be called with a NULL buffer.
369 static int uvc_video_decode_start(struct uvc_video_device *video,
370 struct uvc_buffer *buf, const __u8 *data, int len)
375 * - packet must be at least 2 bytes long
376 * - bHeaderLength value must be at least 2 bytes (see above)
377 * - bHeaderLength value can't be larger than the packet size.
379 if (len < 2 || data[0] < 2 || data[0] > len)
382 /* Skip payloads marked with the error bit ("error frames"). */
383 if (data[1] & UVC_STREAM_ERR) {
384 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
389 fid = data[1] & UVC_STREAM_FID;
391 /* Store the payload FID bit and return immediately when the buffer is
395 video->last_fid = fid;
399 /* Synchronize to the input stream by waiting for the FID bit to be
400 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
401 * video->last_fid is initialized to -1, so the first isochronous
402 * frame will always be in sync.
404 * If the device doesn't toggle the FID bit, invert video->last_fid
405 * when the EOF bit is set to force synchronisation on the next packet.
407 if (buf->state != UVC_BUF_STATE_ACTIVE) {
408 if (fid == video->last_fid) {
409 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
411 if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
412 (data[1] & UVC_STREAM_EOF))
413 video->last_fid ^= UVC_STREAM_FID;
417 /* TODO: Handle PTS and SCR. */
418 buf->state = UVC_BUF_STATE_ACTIVE;
421 /* Mark the buffer as done if we're at the beginning of a new frame.
422 * End of frame detection is better implemented by checking the EOF
423 * bit (FID bit toggling is delayed by one frame compared to the EOF
424 * bit), but some devices don't set the bit at end of frame (and the
425 * last payload can be lost anyway). We thus must check if the FID has
428 * video->last_fid is initialized to -1, so the first isochronous
429 * frame will never trigger an end of frame detection.
431 * Empty buffers (bytesused == 0) don't trigger end of frame detection
432 * as it doesn't make sense to return an empty buffer. This also
433 * avoids detecting end of frame conditions at FID toggling if the
434 * previous payload had the EOF bit set.
436 if (fid != video->last_fid && buf->buf.bytesused != 0) {
437 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
439 buf->state = UVC_BUF_STATE_DONE;
443 video->last_fid = fid;
448 static void uvc_video_decode_data(struct uvc_video_device *video,
449 struct uvc_buffer *buf, const __u8 *data, int len)
451 struct uvc_video_queue *queue = &video->queue;
452 unsigned int maxlen, nbytes;
458 /* Copy the video data to the buffer. */
459 maxlen = buf->buf.length - buf->buf.bytesused;
460 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
461 nbytes = min((unsigned int)len, maxlen);
462 memcpy(mem, data, nbytes);
463 buf->buf.bytesused += nbytes;
465 /* Complete the current frame if the buffer size was exceeded. */
467 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
468 buf->state = UVC_BUF_STATE_DONE;
472 static void uvc_video_decode_end(struct uvc_video_device *video,
473 struct uvc_buffer *buf, const __u8 *data, int len)
475 /* Mark the buffer as done if the EOF marker is set. */
476 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
477 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
479 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
480 buf->state = UVC_BUF_STATE_DONE;
481 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
482 video->last_fid ^= UVC_STREAM_FID;
486 /* Video payload encoding is handled by uvc_video_encode_header() and
487 * uvc_video_encode_data(). Only bulk transfers are currently supported.
489 * uvc_video_encode_header is called at the start of a payload. It adds header
490 * data to the transfer buffer and returns the header size. As the only known
491 * UVC output device transfers a whole frame in a single payload, the EOF bit
492 * is always set in the header.
494 * uvc_video_encode_data is called for every URB and copies the data from the
495 * video buffer to the transfer buffer.
497 static int uvc_video_encode_header(struct uvc_video_device *video,
498 struct uvc_buffer *buf, __u8 *data, int len)
500 data[0] = 2; /* Header length */
501 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
502 | (video->last_fid & UVC_STREAM_FID);
506 static int uvc_video_encode_data(struct uvc_video_device *video,
507 struct uvc_buffer *buf, __u8 *data, int len)
509 struct uvc_video_queue *queue = &video->queue;
513 /* Copy video data to the URB buffer. */
514 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
515 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
516 nbytes = min(video->bulk.max_payload_size - video->bulk.payload_size,
518 memcpy(data, mem, nbytes);
520 queue->buf_used += nbytes;
525 /* ------------------------------------------------------------------------
530 * Completion handler for video URBs.
532 static void uvc_video_decode_isoc(struct urb *urb,
533 struct uvc_video_device *video, struct uvc_buffer *buf)
538 for (i = 0; i < urb->number_of_packets; ++i) {
539 if (urb->iso_frame_desc[i].status < 0) {
540 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
541 "lost (%d).\n", urb->iso_frame_desc[i].status);
545 /* Decode the payload header. */
546 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
548 ret = uvc_video_decode_start(video, buf, mem,
549 urb->iso_frame_desc[i].actual_length);
551 buf = uvc_queue_next_buffer(&video->queue, buf);
552 } while (ret == -EAGAIN);
557 /* Decode the payload data. */
558 uvc_video_decode_data(video, buf, mem + ret,
559 urb->iso_frame_desc[i].actual_length - ret);
561 /* Process the header again. */
562 uvc_video_decode_end(video, buf, mem,
563 urb->iso_frame_desc[i].actual_length);
565 if (buf->state == UVC_BUF_STATE_DONE ||
566 buf->state == UVC_BUF_STATE_ERROR)
567 buf = uvc_queue_next_buffer(&video->queue, buf);
571 static void uvc_video_decode_bulk(struct urb *urb,
572 struct uvc_video_device *video, struct uvc_buffer *buf)
577 if (urb->actual_length == 0)
580 mem = urb->transfer_buffer;
581 len = urb->actual_length;
582 video->bulk.payload_size += len;
584 /* If the URB is the first of its payload, decode and save the
587 if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
589 ret = uvc_video_decode_start(video, buf, mem, len);
591 buf = uvc_queue_next_buffer(&video->queue, buf);
592 } while (ret == -EAGAIN);
594 /* If an error occured skip the rest of the payload. */
595 if (ret < 0 || buf == NULL) {
596 video->bulk.skip_payload = 1;
598 memcpy(video->bulk.header, mem, ret);
599 video->bulk.header_size = ret;
606 /* The buffer queue might have been cancelled while a bulk transfer
607 * was in progress, so we can reach here with buf equal to NULL. Make
608 * sure buf is never dereferenced if NULL.
611 /* Process video data. */
612 if (!video->bulk.skip_payload && buf != NULL)
613 uvc_video_decode_data(video, buf, mem, len);
615 /* Detect the payload end by a URB smaller than the maximum size (or
616 * a payload size equal to the maximum) and process the header again.
618 if (urb->actual_length < urb->transfer_buffer_length ||
619 video->bulk.payload_size >= video->bulk.max_payload_size) {
620 if (!video->bulk.skip_payload && buf != NULL) {
621 uvc_video_decode_end(video, buf, video->bulk.header,
622 video->bulk.payload_size);
623 if (buf->state == UVC_BUF_STATE_DONE ||
624 buf->state == UVC_BUF_STATE_ERROR)
625 buf = uvc_queue_next_buffer(&video->queue, buf);
628 video->bulk.header_size = 0;
629 video->bulk.skip_payload = 0;
630 video->bulk.payload_size = 0;
634 static void uvc_video_encode_bulk(struct urb *urb,
635 struct uvc_video_device *video, struct uvc_buffer *buf)
637 u8 *mem = urb->transfer_buffer;
638 int len = video->urb_size, ret;
641 urb->transfer_buffer_length = 0;
645 /* If the URB is the first of its payload, add the header. */
646 if (video->bulk.header_size == 0) {
647 ret = uvc_video_encode_header(video, buf, mem, len);
648 video->bulk.header_size = ret;
649 video->bulk.payload_size += ret;
654 /* Process video data. */
655 ret = uvc_video_encode_data(video, buf, mem, len);
657 video->bulk.payload_size += ret;
660 if (buf->buf.bytesused == video->queue.buf_used ||
661 video->bulk.payload_size == video->bulk.max_payload_size) {
662 if (buf->buf.bytesused == video->queue.buf_used) {
663 video->queue.buf_used = 0;
664 buf->state = UVC_BUF_STATE_DONE;
665 uvc_queue_next_buffer(&video->queue, buf);
666 video->last_fid ^= UVC_STREAM_FID;
669 video->bulk.header_size = 0;
670 video->bulk.payload_size = 0;
673 urb->transfer_buffer_length = video->urb_size - len;
676 static void uvc_video_complete(struct urb *urb)
678 struct uvc_video_device *video = urb->context;
679 struct uvc_video_queue *queue = &video->queue;
680 struct uvc_buffer *buf = NULL;
684 switch (urb->status) {
689 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
690 "completion handler.\n", urb->status);
692 case -ENOENT: /* usb_kill_urb() called. */
696 case -ECONNRESET: /* usb_unlink_urb() called. */
697 case -ESHUTDOWN: /* The endpoint is being disabled. */
698 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
702 spin_lock_irqsave(&queue->irqlock, flags);
703 if (!list_empty(&queue->irqqueue))
704 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
706 spin_unlock_irqrestore(&queue->irqlock, flags);
708 video->decode(urb, video, buf);
710 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
711 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
717 * Free transfer buffers.
719 static void uvc_free_urb_buffers(struct uvc_video_device *video)
723 for (i = 0; i < UVC_URBS; ++i) {
724 if (video->urb_buffer[i]) {
725 usb_buffer_free(video->dev->udev, video->urb_size,
726 video->urb_buffer[i], video->urb_dma[i]);
727 video->urb_buffer[i] = NULL;
735 * Allocate transfer buffers. This function can be called with buffers
736 * already allocated when resuming from suspend, in which case it will
737 * return without touching the buffers.
739 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
740 * system is too low on memory try successively smaller numbers of packets
741 * until allocation succeeds.
743 * Return the number of allocated packets on success or 0 when out of memory.
745 static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
746 unsigned int size, unsigned int psize, gfp_t gfp_flags)
748 unsigned int npackets;
751 /* Buffers are already allocated, bail out. */
753 return video->urb_size / psize;
755 /* Compute the number of packets. Bulk endpoints might transfer UVC
756 * payloads accross multiple URBs.
758 npackets = DIV_ROUND_UP(size, psize);
759 if (npackets > UVC_MAX_PACKETS)
760 npackets = UVC_MAX_PACKETS;
762 /* Retry allocations until one succeed. */
763 for (; npackets > 1; npackets /= 2) {
764 for (i = 0; i < UVC_URBS; ++i) {
765 video->urb_buffer[i] = usb_buffer_alloc(
766 video->dev->udev, psize * npackets,
767 gfp_flags | __GFP_NOWARN, &video->urb_dma[i]);
768 if (!video->urb_buffer[i]) {
769 uvc_free_urb_buffers(video);
775 video->urb_size = psize * npackets;
784 * Uninitialize isochronous/bulk URBs and free transfer buffers.
786 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
791 for (i = 0; i < UVC_URBS; ++i) {
792 if ((urb = video->urb[i]) == NULL)
797 video->urb[i] = NULL;
801 uvc_free_urb_buffers(video);
805 * Initialize isochronous URBs and allocate transfer buffers. The packet size
806 * is given by the endpoint.
808 static int uvc_init_video_isoc(struct uvc_video_device *video,
809 struct usb_host_endpoint *ep, gfp_t gfp_flags)
812 unsigned int npackets, i, j;
816 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
817 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
818 size = video->streaming->ctrl.dwMaxVideoFrameSize;
820 npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
824 size = npackets * psize;
826 for (i = 0; i < UVC_URBS; ++i) {
827 urb = usb_alloc_urb(npackets, gfp_flags);
829 uvc_uninit_video(video, 1);
833 urb->dev = video->dev->udev;
834 urb->context = video;
835 urb->pipe = usb_rcvisocpipe(video->dev->udev,
836 ep->desc.bEndpointAddress);
837 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
838 urb->interval = ep->desc.bInterval;
839 urb->transfer_buffer = video->urb_buffer[i];
840 urb->transfer_dma = video->urb_dma[i];
841 urb->complete = uvc_video_complete;
842 urb->number_of_packets = npackets;
843 urb->transfer_buffer_length = size;
845 for (j = 0; j < npackets; ++j) {
846 urb->iso_frame_desc[j].offset = j * psize;
847 urb->iso_frame_desc[j].length = psize;
857 * Initialize bulk URBs and allocate transfer buffers. The packet size is
858 * given by the endpoint.
860 static int uvc_init_video_bulk(struct uvc_video_device *video,
861 struct usb_host_endpoint *ep, gfp_t gfp_flags)
864 unsigned int npackets, pipe, i;
868 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
869 size = video->streaming->ctrl.dwMaxPayloadTransferSize;
870 video->bulk.max_payload_size = size;
872 npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
876 size = npackets * psize;
878 if (usb_endpoint_dir_in(&ep->desc))
879 pipe = usb_rcvbulkpipe(video->dev->udev,
880 ep->desc.bEndpointAddress);
882 pipe = usb_sndbulkpipe(video->dev->udev,
883 ep->desc.bEndpointAddress);
885 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
888 for (i = 0; i < UVC_URBS; ++i) {
889 urb = usb_alloc_urb(0, gfp_flags);
891 uvc_uninit_video(video, 1);
895 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
896 video->urb_buffer[i], size, uvc_video_complete,
898 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
899 urb->transfer_dma = video->urb_dma[i];
908 * Initialize isochronous/bulk URBs and allocate transfer buffers.
910 static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
912 struct usb_interface *intf = video->streaming->intf;
913 struct usb_host_interface *alts;
914 struct usb_host_endpoint *ep = NULL;
915 int intfnum = video->streaming->intfnum;
916 unsigned int bandwidth, psize, i;
919 video->last_fid = -1;
920 video->bulk.header_size = 0;
921 video->bulk.skip_payload = 0;
922 video->bulk.payload_size = 0;
924 if (intf->num_altsetting > 1) {
925 /* Isochronous endpoint, select the alternate setting. */
926 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
928 if (bandwidth == 0) {
929 uvc_printk(KERN_WARNING, "device %s requested null "
930 "bandwidth, defaulting to lowest.\n",
935 for (i = 0; i < intf->num_altsetting; ++i) {
936 alts = &intf->altsetting[i];
937 ep = uvc_find_endpoint(alts,
938 video->streaming->header.bEndpointAddress);
942 /* Check if the bandwidth is high enough. */
943 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
944 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
945 if (psize >= bandwidth)
949 if (i >= intf->num_altsetting)
952 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
955 ret = uvc_init_video_isoc(video, ep, gfp_flags);
957 /* Bulk endpoint, proceed to URB initialization. */
958 ep = uvc_find_endpoint(&intf->altsetting[0],
959 video->streaming->header.bEndpointAddress);
963 ret = uvc_init_video_bulk(video, ep, gfp_flags);
969 /* Submit the URBs. */
970 for (i = 0; i < UVC_URBS; ++i) {
971 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
972 uvc_printk(KERN_ERR, "Failed to submit URB %u "
974 uvc_uninit_video(video, 1);
982 /* --------------------------------------------------------------------------
987 * Stop streaming without disabling the video queue.
989 * To let userspace applications resume without trouble, we must not touch the
990 * video buffers in any way. We mark the device as frozen to make sure the URB
991 * completion handler won't try to cancel the queue when we kill the URBs.
993 int uvc_video_suspend(struct uvc_video_device *video)
995 if (!uvc_queue_streaming(&video->queue))
999 uvc_uninit_video(video, 0);
1000 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1005 * Reconfigure the video interface and restart streaming if it was enabled
1008 * If an error occurs, disable the video queue. This will wake all pending
1009 * buffers, making sure userspace applications are notified of the problem
1010 * instead of waiting forever.
1012 int uvc_video_resume(struct uvc_video_device *video)
1018 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
1019 uvc_queue_enable(&video->queue, 0);
1023 if (!uvc_queue_streaming(&video->queue))
1026 if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
1027 uvc_queue_enable(&video->queue, 0);
1032 /* ------------------------------------------------------------------------
1037 * Initialize the UVC video device by switching to alternate setting 0 and
1038 * retrieve the default format.
1040 * Some cameras (namely the Fuji Finepix) set the format and frame
1041 * indexes to zero. The UVC standard doesn't clearly make this a spec
1042 * violation, so try to silently fix the values if possible.
1044 * This function is called before registering the device with V4L.
1046 int uvc_video_init(struct uvc_video_device *video)
1048 struct uvc_streaming_control *probe = &video->streaming->ctrl;
1049 struct uvc_format *format = NULL;
1050 struct uvc_frame *frame = NULL;
1054 if (video->streaming->nformats == 0) {
1055 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1059 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1060 * Cam (and possibly other devices) crash or otherwise misbehave if
1061 * they don't receive a SET_INTERFACE request before any other video
1064 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1066 /* Set the streaming probe control with default streaming parameters
1067 * retrieved from the device. Webcams that don't suport GET_DEF
1068 * requests on the probe control will just keep their current streaming
1071 if (uvc_get_video_ctrl(video, probe, 1, UVC_GET_DEF) == 0)
1072 uvc_set_video_ctrl(video, probe, 1);
1074 /* Initialize the streaming parameters with the probe control current
1075 * value. This makes sure SET_CUR requests on the streaming commit
1076 * control will always use values retrieved from a successful GET_CUR
1077 * request on the probe control, as required by the UVC specification.
1079 ret = uvc_get_video_ctrl(video, probe, 1, UVC_GET_CUR);
1083 /* Check if the default format descriptor exists. Use the first
1084 * available format otherwise.
1086 for (i = video->streaming->nformats; i > 0; --i) {
1087 format = &video->streaming->format[i-1];
1088 if (format->index == probe->bFormatIndex)
1092 if (format->nframes == 0) {
1093 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1094 "default format.\n");
1098 /* Zero bFrameIndex might be correct. Stream-based formats (including
1099 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1100 * descriptor with bFrameIndex set to zero. If the default frame
1101 * descriptor is not found, use the first available frame.
1103 for (i = format->nframes; i > 0; --i) {
1104 frame = &format->frame[i-1];
1105 if (frame->bFrameIndex == probe->bFrameIndex)
1109 probe->bFormatIndex = format->index;
1110 probe->bFrameIndex = frame->bFrameIndex;
1112 video->streaming->cur_format = format;
1113 video->streaming->cur_frame = frame;
1114 atomic_set(&video->active, 0);
1116 /* Select the video decoding function */
1117 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1118 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1119 video->decode = uvc_video_decode_isight;
1120 else if (video->streaming->intf->num_altsetting > 1)
1121 video->decode = uvc_video_decode_isoc;
1123 video->decode = uvc_video_decode_bulk;
1125 if (video->streaming->intf->num_altsetting == 1)
1126 video->decode = uvc_video_encode_bulk;
1128 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1129 "supported for video output devices.\n");
1138 * Enable or disable the video stream.
1140 int uvc_video_enable(struct uvc_video_device *video, int enable)
1145 uvc_uninit_video(video, 1);
1146 usb_set_interface(video->dev->udev,
1147 video->streaming->intfnum, 0);
1148 uvc_queue_enable(&video->queue, 0);
1152 if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1154 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1156 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1158 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1161 /* Commit the streaming parameters. */
1162 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1165 return uvc_init_video(video, GFP_KERNEL);