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;
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;
88 if (video->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
89 video->streaming->intf->num_altsetting > 1) {
93 interval = (ctrl->dwFrameInterval > 100000)
94 ? ctrl->dwFrameInterval
95 : frame->dwFrameInterval[0];
97 /* Compute a bandwidth estimation by multiplying the frame
98 * size by the number of video frames per second, divide the
99 * result by the number of USB frames (or micro-frames for
100 * high-speed devices) per second and add the UVC header size
101 * (assumed to be 12 bytes long).
103 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
104 bandwidth *= 10000000 / interval + 1;
106 if (video->dev->udev->speed == USB_SPEED_HIGH)
110 ctrl->dwMaxPayloadTransferSize = bandwidth;
114 static int uvc_get_video_ctrl(struct uvc_video_device *video,
115 struct uvc_streaming_control *ctrl, int probe, __u8 query)
121 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
122 data = kmalloc(size, GFP_KERNEL);
126 ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
127 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
128 UVC_CTRL_STREAMING_TIMEOUT);
130 if ((query == GET_MIN || query == GET_MAX) && ret == 2) {
131 /* Some cameras, mostly based on Bison Electronics chipsets,
132 * answer a GET_MIN or GET_MAX request with the wCompQuality
135 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
136 "compliance - GET_MIN/MAX(PROBE) incorrectly "
137 "supported. Enabling workaround.\n");
138 memset(ctrl, 0, sizeof ctrl);
139 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
142 } else if (query == GET_DEF && probe == 1 && ret != size) {
143 /* Many cameras don't support the GET_DEF request on their
144 * video probe control. Warn once and return, the caller will
145 * fall back to GET_CUR.
147 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
148 "compliance - GET_DEF(PROBE) not supported. "
149 "Enabling workaround.\n");
152 } else if (ret != size) {
153 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
154 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
160 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
161 ctrl->bFormatIndex = data[2];
162 ctrl->bFrameIndex = data[3];
163 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
164 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
165 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
166 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
167 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
168 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
169 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
170 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
173 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
174 ctrl->bmFramingInfo = data[30];
175 ctrl->bPreferedVersion = data[31];
176 ctrl->bMinVersion = data[32];
177 ctrl->bMaxVersion = data[33];
179 ctrl->dwClockFrequency = video->dev->clock_frequency;
180 ctrl->bmFramingInfo = 0;
181 ctrl->bPreferedVersion = 0;
182 ctrl->bMinVersion = 0;
183 ctrl->bMaxVersion = 0;
186 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
187 * dwMaxPayloadTransferSize fields. Try to get the value from the
188 * format and frame descriptors.
190 uvc_fixup_video_ctrl(video, ctrl);
198 static int uvc_set_video_ctrl(struct uvc_video_device *video,
199 struct uvc_streaming_control *ctrl, int probe)
205 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
206 data = kzalloc(size, GFP_KERNEL);
210 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
211 data[2] = ctrl->bFormatIndex;
212 data[3] = ctrl->bFrameIndex;
213 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
214 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
215 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
216 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
217 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
218 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
219 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
220 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
223 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
224 data[30] = ctrl->bmFramingInfo;
225 data[31] = ctrl->bPreferedVersion;
226 data[32] = ctrl->bMinVersion;
227 data[33] = ctrl->bMaxVersion;
230 ret = __uvc_query_ctrl(video->dev, SET_CUR, 0,
231 video->streaming->intfnum,
232 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
233 UVC_CTRL_STREAMING_TIMEOUT);
235 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
236 "%d (exp. %u).\n", probe ? "probe" : "commit",
245 int uvc_probe_video(struct uvc_video_device *video,
246 struct uvc_streaming_control *probe)
248 struct uvc_streaming_control probe_min, probe_max;
253 mutex_lock(&video->streaming->mutex);
255 /* Perform probing. The device should adjust the requested values
256 * according to its capabilities. However, some devices, namely the
257 * first generation UVC Logitech webcams, don't implement the Video
258 * Probe control properly, and just return the needed bandwidth. For
259 * that reason, if the needed bandwidth exceeds the maximum available
260 * bandwidth, try to lower the quality.
262 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
265 /* Get the minimum and maximum values for compression settings. */
266 if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
267 ret = uvc_get_video_ctrl(video, &probe_min, 1, GET_MIN);
270 ret = uvc_get_video_ctrl(video, &probe_max, 1, GET_MAX);
274 probe->wCompQuality = probe_max.wCompQuality;
277 for (i = 0; i < 2; ++i) {
278 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0 ||
279 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
282 if (video->streaming->intf->num_altsetting == 1)
285 bandwidth = probe->dwMaxPayloadTransferSize;
286 if (bandwidth <= video->streaming->maxpsize)
289 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
294 /* TODO: negotiate compression parameters */
295 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
296 probe->wPFrameRate = probe_min.wPFrameRate;
297 probe->wCompQuality = probe_max.wCompQuality;
298 probe->wCompWindowSize = probe_min.wCompWindowSize;
302 mutex_unlock(&video->streaming->mutex);
306 int uvc_commit_video(struct uvc_video_device *video,
307 struct uvc_streaming_control *probe)
309 return uvc_set_video_ctrl(video, probe, 0);
312 /* ------------------------------------------------------------------------
316 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
317 #define UVC_STREAM_EOH (1 << 7)
318 #define UVC_STREAM_ERR (1 << 6)
319 #define UVC_STREAM_STI (1 << 5)
320 #define UVC_STREAM_RES (1 << 4)
321 #define UVC_STREAM_SCR (1 << 3)
322 #define UVC_STREAM_PTS (1 << 2)
323 #define UVC_STREAM_EOF (1 << 1)
324 #define UVC_STREAM_FID (1 << 0)
326 /* Video payload decoding is handled by uvc_video_decode_start(),
327 * uvc_video_decode_data() and uvc_video_decode_end().
329 * uvc_video_decode_start is called with URB data at the start of a bulk or
330 * isochronous payload. It processes header data and returns the header size
331 * in bytes if successful. If an error occurs, it returns a negative error
332 * code. The following error codes have special meanings.
334 * - EAGAIN informs the caller that the current video buffer should be marked
335 * as done, and that the function should be called again with the same data
336 * and a new video buffer. This is used when end of frame conditions can be
337 * reliably detected at the beginning of the next frame only.
339 * If an error other than -EAGAIN is returned, the caller will drop the current
340 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
341 * made until the next payload. -ENODATA can be used to drop the current
342 * payload if no other error code is appropriate.
344 * uvc_video_decode_data is called for every URB with URB data. It copies the
345 * data to the video buffer.
347 * uvc_video_decode_end is called with header data at the end of a bulk or
348 * isochronous payload. It performs any additional header data processing and
349 * returns 0 or a negative error code if an error occured. As header data have
350 * already been processed by uvc_video_decode_start, this functions isn't
351 * required to perform sanity checks a second time.
353 * For isochronous transfers where a payload is always transfered in a single
354 * URB, the three functions will be called in a row.
356 * To let the decoder process header data and update its internal state even
357 * when no video buffer is available, uvc_video_decode_start must be prepared
358 * to be called with a NULL buf parameter. uvc_video_decode_data and
359 * uvc_video_decode_end will never be called with a NULL buffer.
361 static int uvc_video_decode_start(struct uvc_video_device *video,
362 struct uvc_buffer *buf, const __u8 *data, int len)
367 * - packet must be at least 2 bytes long
368 * - bHeaderLength value must be at least 2 bytes (see above)
369 * - bHeaderLength value can't be larger than the packet size.
371 if (len < 2 || data[0] < 2 || data[0] > len)
374 /* Skip payloads marked with the error bit ("error frames"). */
375 if (data[1] & UVC_STREAM_ERR) {
376 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
381 fid = data[1] & UVC_STREAM_FID;
383 /* Store the payload FID bit and return immediately when the buffer is
387 video->last_fid = fid;
391 /* Synchronize to the input stream by waiting for the FID bit to be
392 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
393 * video->last_fid is initialized to -1, so the first isochronous
394 * frame will always be in sync.
396 * If the device doesn't toggle the FID bit, invert video->last_fid
397 * when the EOF bit is set to force synchronisation on the next packet.
399 if (buf->state != UVC_BUF_STATE_ACTIVE) {
400 if (fid == video->last_fid) {
401 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
403 if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
404 (data[1] & UVC_STREAM_EOF))
405 video->last_fid ^= UVC_STREAM_FID;
409 /* TODO: Handle PTS and SCR. */
410 buf->state = UVC_BUF_STATE_ACTIVE;
413 /* Mark the buffer as done if we're at the beginning of a new frame.
414 * End of frame detection is better implemented by checking the EOF
415 * bit (FID bit toggling is delayed by one frame compared to the EOF
416 * bit), but some devices don't set the bit at end of frame (and the
417 * last payload can be lost anyway). We thus must check if the FID has
420 * video->last_fid is initialized to -1, so the first isochronous
421 * frame will never trigger an end of frame detection.
423 * Empty buffers (bytesused == 0) don't trigger end of frame detection
424 * as it doesn't make sense to return an empty buffer. This also
425 * avoids detecting end of frame conditions at FID toggling if the
426 * previous payload had the EOF bit set.
428 if (fid != video->last_fid && buf->buf.bytesused != 0) {
429 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
431 buf->state = UVC_BUF_STATE_DONE;
435 video->last_fid = fid;
440 static void uvc_video_decode_data(struct uvc_video_device *video,
441 struct uvc_buffer *buf, const __u8 *data, int len)
443 struct uvc_video_queue *queue = &video->queue;
444 unsigned int maxlen, nbytes;
450 /* Copy the video data to the buffer. */
451 maxlen = buf->buf.length - buf->buf.bytesused;
452 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
453 nbytes = min((unsigned int)len, maxlen);
454 memcpy(mem, data, nbytes);
455 buf->buf.bytesused += nbytes;
457 /* Complete the current frame if the buffer size was exceeded. */
459 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
460 buf->state = UVC_BUF_STATE_DONE;
464 static void uvc_video_decode_end(struct uvc_video_device *video,
465 struct uvc_buffer *buf, const __u8 *data, int len)
467 /* Mark the buffer as done if the EOF marker is set. */
468 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
469 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
471 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
472 buf->state = UVC_BUF_STATE_DONE;
473 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
474 video->last_fid ^= UVC_STREAM_FID;
478 /* Video payload encoding is handled by uvc_video_encode_header() and
479 * uvc_video_encode_data(). Only bulk transfers are currently supported.
481 * uvc_video_encode_header is called at the start of a payload. It adds header
482 * data to the transfer buffer and returns the header size. As the only known
483 * UVC output device transfers a whole frame in a single payload, the EOF bit
484 * is always set in the header.
486 * uvc_video_encode_data is called for every URB and copies the data from the
487 * video buffer to the transfer buffer.
489 static int uvc_video_encode_header(struct uvc_video_device *video,
490 struct uvc_buffer *buf, __u8 *data, int len)
492 data[0] = 2; /* Header length */
493 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
494 | (video->last_fid & UVC_STREAM_FID);
498 static int uvc_video_encode_data(struct uvc_video_device *video,
499 struct uvc_buffer *buf, __u8 *data, int len)
501 struct uvc_video_queue *queue = &video->queue;
505 /* Copy video data to the URB buffer. */
506 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
507 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
508 nbytes = min(video->bulk.max_payload_size - video->bulk.payload_size,
510 memcpy(data, mem, nbytes);
512 queue->buf_used += nbytes;
517 /* ------------------------------------------------------------------------
522 * Completion handler for video URBs.
524 static void uvc_video_decode_isoc(struct urb *urb,
525 struct uvc_video_device *video, struct uvc_buffer *buf)
530 for (i = 0; i < urb->number_of_packets; ++i) {
531 if (urb->iso_frame_desc[i].status < 0) {
532 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
533 "lost (%d).\n", urb->iso_frame_desc[i].status);
537 /* Decode the payload header. */
538 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
540 ret = uvc_video_decode_start(video, buf, mem,
541 urb->iso_frame_desc[i].actual_length);
543 buf = uvc_queue_next_buffer(&video->queue, buf);
544 } while (ret == -EAGAIN);
549 /* Decode the payload data. */
550 uvc_video_decode_data(video, buf, mem + ret,
551 urb->iso_frame_desc[i].actual_length - ret);
553 /* Process the header again. */
554 uvc_video_decode_end(video, buf, mem,
555 urb->iso_frame_desc[i].actual_length);
557 if (buf->state == UVC_BUF_STATE_DONE ||
558 buf->state == UVC_BUF_STATE_ERROR)
559 buf = uvc_queue_next_buffer(&video->queue, buf);
563 static void uvc_video_decode_bulk(struct urb *urb,
564 struct uvc_video_device *video, struct uvc_buffer *buf)
569 if (urb->actual_length == 0)
572 mem = urb->transfer_buffer;
573 len = urb->actual_length;
574 video->bulk.payload_size += len;
576 /* If the URB is the first of its payload, decode and save the
579 if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
581 ret = uvc_video_decode_start(video, buf, mem, len);
583 buf = uvc_queue_next_buffer(&video->queue, buf);
584 } while (ret == -EAGAIN);
586 /* If an error occured skip the rest of the payload. */
587 if (ret < 0 || buf == NULL) {
588 video->bulk.skip_payload = 1;
590 memcpy(video->bulk.header, mem, ret);
591 video->bulk.header_size = ret;
598 /* The buffer queue might have been cancelled while a bulk transfer
599 * was in progress, so we can reach here with buf equal to NULL. Make
600 * sure buf is never dereferenced if NULL.
603 /* Process video data. */
604 if (!video->bulk.skip_payload && buf != NULL)
605 uvc_video_decode_data(video, buf, mem, len);
607 /* Detect the payload end by a URB smaller than the maximum size (or
608 * a payload size equal to the maximum) and process the header again.
610 if (urb->actual_length < urb->transfer_buffer_length ||
611 video->bulk.payload_size >= video->bulk.max_payload_size) {
612 if (!video->bulk.skip_payload && buf != NULL) {
613 uvc_video_decode_end(video, buf, video->bulk.header,
614 video->bulk.payload_size);
615 if (buf->state == UVC_BUF_STATE_DONE ||
616 buf->state == UVC_BUF_STATE_ERROR)
617 buf = uvc_queue_next_buffer(&video->queue, buf);
620 video->bulk.header_size = 0;
621 video->bulk.skip_payload = 0;
622 video->bulk.payload_size = 0;
626 static void uvc_video_encode_bulk(struct urb *urb,
627 struct uvc_video_device *video, struct uvc_buffer *buf)
629 u8 *mem = urb->transfer_buffer;
630 int len = video->urb_size, ret;
633 urb->transfer_buffer_length = 0;
637 /* If the URB is the first of its payload, add the header. */
638 if (video->bulk.header_size == 0) {
639 ret = uvc_video_encode_header(video, buf, mem, len);
640 video->bulk.header_size = ret;
641 video->bulk.payload_size += ret;
646 /* Process video data. */
647 ret = uvc_video_encode_data(video, buf, mem, len);
649 video->bulk.payload_size += ret;
652 if (buf->buf.bytesused == video->queue.buf_used ||
653 video->bulk.payload_size == video->bulk.max_payload_size) {
654 if (buf->buf.bytesused == video->queue.buf_used) {
655 video->queue.buf_used = 0;
656 buf->state = UVC_BUF_STATE_DONE;
657 uvc_queue_next_buffer(&video->queue, buf);
658 video->last_fid ^= UVC_STREAM_FID;
661 video->bulk.header_size = 0;
662 video->bulk.payload_size = 0;
665 urb->transfer_buffer_length = video->urb_size - len;
668 static void uvc_video_complete(struct urb *urb)
670 struct uvc_video_device *video = urb->context;
671 struct uvc_video_queue *queue = &video->queue;
672 struct uvc_buffer *buf = NULL;
676 switch (urb->status) {
681 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
682 "completion handler.\n", urb->status);
684 case -ENOENT: /* usb_kill_urb() called. */
688 case -ECONNRESET: /* usb_unlink_urb() called. */
689 case -ESHUTDOWN: /* The endpoint is being disabled. */
690 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
694 spin_lock_irqsave(&queue->irqlock, flags);
695 if (!list_empty(&queue->irqqueue))
696 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
698 spin_unlock_irqrestore(&queue->irqlock, flags);
700 video->decode(urb, video, buf);
702 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
703 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
709 * Free transfer buffers.
711 static void uvc_free_urb_buffers(struct uvc_video_device *video)
715 for (i = 0; i < UVC_URBS; ++i) {
716 if (video->urb_buffer[i]) {
717 usb_buffer_free(video->dev->udev, video->urb_size,
718 video->urb_buffer[i], video->urb_dma[i]);
719 video->urb_buffer[i] = NULL;
727 * Allocate transfer buffers. This function can be called with buffers
728 * already allocated when resuming from suspend, in which case it will
729 * return without touching the buffers.
731 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
732 * system is too low on memory try successively smaller numbers of packets
733 * until allocation succeeds.
735 * Return the number of allocated packets on success or 0 when out of memory.
737 static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
738 unsigned int size, unsigned int psize, gfp_t gfp_flags)
740 unsigned int npackets;
743 /* Buffers are already allocated, bail out. */
747 /* Compute the number of packets. Bulk endpoints might transfer UVC
748 * payloads accross multiple URBs.
750 npackets = DIV_ROUND_UP(size, psize);
751 if (npackets > UVC_MAX_PACKETS)
752 npackets = UVC_MAX_PACKETS;
754 /* Retry allocations until one succeed. */
755 for (; npackets > 1; npackets /= 2) {
756 for (i = 0; i < UVC_URBS; ++i) {
757 video->urb_buffer[i] = usb_buffer_alloc(
758 video->dev->udev, psize * npackets,
759 gfp_flags | __GFP_NOWARN, &video->urb_dma[i]);
760 if (!video->urb_buffer[i]) {
761 uvc_free_urb_buffers(video);
767 video->urb_size = psize * npackets;
776 * Uninitialize isochronous/bulk URBs and free transfer buffers.
778 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
783 for (i = 0; i < UVC_URBS; ++i) {
784 if ((urb = video->urb[i]) == NULL)
789 video->urb[i] = NULL;
793 uvc_free_urb_buffers(video);
797 * Initialize isochronous URBs and allocate transfer buffers. The packet size
798 * is given by the endpoint.
800 static int uvc_init_video_isoc(struct uvc_video_device *video,
801 struct usb_host_endpoint *ep, gfp_t gfp_flags)
804 unsigned int npackets, i, j;
808 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
809 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
810 size = video->streaming->ctrl.dwMaxVideoFrameSize;
812 npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
816 size = npackets * psize;
818 for (i = 0; i < UVC_URBS; ++i) {
819 urb = usb_alloc_urb(npackets, gfp_flags);
821 uvc_uninit_video(video, 1);
825 urb->dev = video->dev->udev;
826 urb->context = video;
827 urb->pipe = usb_rcvisocpipe(video->dev->udev,
828 ep->desc.bEndpointAddress);
829 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
830 urb->interval = ep->desc.bInterval;
831 urb->transfer_buffer = video->urb_buffer[i];
832 urb->transfer_dma = video->urb_dma[i];
833 urb->complete = uvc_video_complete;
834 urb->number_of_packets = npackets;
835 urb->transfer_buffer_length = size;
837 for (j = 0; j < npackets; ++j) {
838 urb->iso_frame_desc[j].offset = j * psize;
839 urb->iso_frame_desc[j].length = psize;
849 * Initialize bulk URBs and allocate transfer buffers. The packet size is
850 * given by the endpoint.
852 static int uvc_init_video_bulk(struct uvc_video_device *video,
853 struct usb_host_endpoint *ep, gfp_t gfp_flags)
856 unsigned int npackets, pipe, i;
860 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
861 size = video->streaming->ctrl.dwMaxPayloadTransferSize;
862 video->bulk.max_payload_size = size;
864 npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
868 size = npackets * psize;
870 if (usb_endpoint_dir_in(&ep->desc))
871 pipe = usb_rcvbulkpipe(video->dev->udev,
872 ep->desc.bEndpointAddress);
874 pipe = usb_sndbulkpipe(video->dev->udev,
875 ep->desc.bEndpointAddress);
877 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
880 for (i = 0; i < UVC_URBS; ++i) {
881 urb = usb_alloc_urb(0, gfp_flags);
883 uvc_uninit_video(video, 1);
887 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
888 video->urb_buffer[i], size, uvc_video_complete,
890 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
891 urb->transfer_dma = video->urb_dma[i];
900 * Initialize isochronous/bulk URBs and allocate transfer buffers.
902 static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
904 struct usb_interface *intf = video->streaming->intf;
905 struct usb_host_interface *alts;
906 struct usb_host_endpoint *ep = NULL;
907 int intfnum = video->streaming->intfnum;
908 unsigned int bandwidth, psize, i;
911 video->last_fid = -1;
912 video->bulk.header_size = 0;
913 video->bulk.skip_payload = 0;
914 video->bulk.payload_size = 0;
916 if (intf->num_altsetting > 1) {
917 /* Isochronous endpoint, select the alternate setting. */
918 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
920 if (bandwidth == 0) {
921 uvc_printk(KERN_WARNING, "device %s requested null "
922 "bandwidth, defaulting to lowest.\n",
927 for (i = 0; i < intf->num_altsetting; ++i) {
928 alts = &intf->altsetting[i];
929 ep = uvc_find_endpoint(alts,
930 video->streaming->header.bEndpointAddress);
934 /* Check if the bandwidth is high enough. */
935 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
936 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
937 if (psize >= bandwidth)
941 if (i >= intf->num_altsetting)
944 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
947 ret = uvc_init_video_isoc(video, ep, gfp_flags);
949 /* Bulk endpoint, proceed to URB initialization. */
950 ep = uvc_find_endpoint(&intf->altsetting[0],
951 video->streaming->header.bEndpointAddress);
955 ret = uvc_init_video_bulk(video, ep, gfp_flags);
961 /* Submit the URBs. */
962 for (i = 0; i < UVC_URBS; ++i) {
963 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
964 uvc_printk(KERN_ERR, "Failed to submit URB %u "
966 uvc_uninit_video(video, 1);
974 /* --------------------------------------------------------------------------
979 * Stop streaming without disabling the video queue.
981 * To let userspace applications resume without trouble, we must not touch the
982 * video buffers in any way. We mark the device as frozen to make sure the URB
983 * completion handler won't try to cancel the queue when we kill the URBs.
985 int uvc_video_suspend(struct uvc_video_device *video)
987 if (!uvc_queue_streaming(&video->queue))
991 uvc_uninit_video(video, 0);
992 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
997 * Reconfigure the video interface and restart streaming if it was enabled
1000 * If an error occurs, disable the video queue. This will wake all pending
1001 * buffers, making sure userspace applications are notified of the problem
1002 * instead of waiting forever.
1004 int uvc_video_resume(struct uvc_video_device *video)
1010 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
1011 uvc_queue_enable(&video->queue, 0);
1015 if (!uvc_queue_streaming(&video->queue))
1018 if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
1019 uvc_queue_enable(&video->queue, 0);
1024 /* ------------------------------------------------------------------------
1029 * Initialize the UVC video device by switching to alternate setting 0 and
1030 * retrieve the default format.
1032 * Some cameras (namely the Fuji Finepix) set the format and frame
1033 * indexes to zero. The UVC standard doesn't clearly make this a spec
1034 * violation, so try to silently fix the values if possible.
1036 * This function is called before registering the device with V4L.
1038 int uvc_video_init(struct uvc_video_device *video)
1040 struct uvc_streaming_control *probe = &video->streaming->ctrl;
1041 struct uvc_format *format = NULL;
1042 struct uvc_frame *frame = NULL;
1046 if (video->streaming->nformats == 0) {
1047 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1051 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1052 * Cam (and possibly other devices) crash or otherwise misbehave if
1053 * they don't receive a SET_INTERFACE request before any other video
1056 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1058 /* Set the streaming probe control with default streaming parameters
1059 * retrieved from the device. Webcams that don't suport GET_DEF
1060 * requests on the probe control will just keep their current streaming
1063 if (uvc_get_video_ctrl(video, probe, 1, GET_DEF) == 0)
1064 uvc_set_video_ctrl(video, probe, 1);
1066 /* Initialize the streaming parameters with the probe control current
1067 * value. This makes sure SET_CUR requests on the streaming commit
1068 * control will always use values retrieved from a successful GET_CUR
1069 * request on the probe control, as required by the UVC specification.
1071 if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
1074 /* Check if the default format descriptor exists. Use the first
1075 * available format otherwise.
1077 for (i = video->streaming->nformats; i > 0; --i) {
1078 format = &video->streaming->format[i-1];
1079 if (format->index == probe->bFormatIndex)
1083 if (format->nframes == 0) {
1084 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1085 "default format.\n");
1089 /* Zero bFrameIndex might be correct. Stream-based formats (including
1090 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1091 * descriptor with bFrameIndex set to zero. If the default frame
1092 * descriptor is not found, use the first avalable frame.
1094 for (i = format->nframes; i > 0; --i) {
1095 frame = &format->frame[i-1];
1096 if (frame->bFrameIndex == probe->bFrameIndex)
1100 probe->bFormatIndex = format->index;
1101 probe->bFrameIndex = frame->bFrameIndex;
1103 video->streaming->cur_format = format;
1104 video->streaming->cur_frame = frame;
1105 atomic_set(&video->active, 0);
1107 /* Select the video decoding function */
1108 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1109 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1110 video->decode = uvc_video_decode_isight;
1111 else if (video->streaming->intf->num_altsetting > 1)
1112 video->decode = uvc_video_decode_isoc;
1114 video->decode = uvc_video_decode_bulk;
1116 if (video->streaming->intf->num_altsetting == 1)
1117 video->decode = uvc_video_encode_bulk;
1119 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1120 "supported for video output devices.\n");
1129 * Enable or disable the video stream.
1131 int uvc_video_enable(struct uvc_video_device *video, int enable)
1136 uvc_uninit_video(video, 1);
1137 usb_set_interface(video->dev->udev,
1138 video->streaming->intfnum, 0);
1139 uvc_queue_enable(&video->queue, 0);
1143 if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1145 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1147 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1149 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1152 /* Commit the streaming parameters. */
1153 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1156 return uvc_init_video(video, GFP_KERNEL);