2 * uvc_video.c -- USB Video Class driver - Video handling
4 * Copyright (C) 2005-2008
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/version.h>
16 #include <linux/list.h>
17 #include <linux/module.h>
18 #include <linux/usb.h>
19 #include <linux/videodev2.h>
20 #include <linux/vmalloc.h>
21 #include <linux/wait.h>
22 #include <asm/atomic.h>
23 #include <asm/unaligned.h>
25 #include <media/v4l2-common.h>
29 /* ------------------------------------------------------------------------
33 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
34 __u8 intfnum, __u8 cs, void *data, __u16 size,
37 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
40 pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
41 : usb_sndctrlpipe(dev->udev, 0);
42 type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
44 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45 unit << 8 | intfnum, data, size, timeout);
48 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
49 __u8 intfnum, __u8 cs, void *data, __u16 size)
53 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
54 UVC_CTRL_CONTROL_TIMEOUT);
56 uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
57 "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
65 static void uvc_fixup_buffer_size(struct uvc_video_device *video,
66 struct uvc_streaming_control *ctrl)
68 struct uvc_format *format;
69 struct uvc_frame *frame;
71 if (ctrl->bFormatIndex <= 0 ||
72 ctrl->bFormatIndex > video->streaming->nformats)
75 format = &video->streaming->format[ctrl->bFormatIndex - 1];
77 if (ctrl->bFrameIndex <= 0 ||
78 ctrl->bFrameIndex > format->nframes)
81 frame = &format->frame[ctrl->bFrameIndex - 1];
83 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
84 (ctrl->dwMaxVideoFrameSize == 0 &&
85 video->dev->uvc_version < 0x0110))
86 ctrl->dwMaxVideoFrameSize =
87 frame->dwMaxVideoFrameBufferSize;
90 static int uvc_get_video_ctrl(struct uvc_video_device *video,
91 struct uvc_streaming_control *ctrl, int probe, __u8 query)
97 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
98 data = kmalloc(size, GFP_KERNEL);
102 ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
103 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
104 UVC_CTRL_STREAMING_TIMEOUT);
106 if ((query == GET_MIN || query == GET_MAX) && ret == 2) {
107 /* Some cameras, mostly based on Bison Electronics chipsets,
108 * answer a GET_MIN or GET_MAX request with the wCompQuality
111 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
112 "compliance - GET_MIN/MAX(PROBE) incorrectly "
113 "supported. Enabling workaround.\n");
114 memset(ctrl, 0, sizeof ctrl);
115 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
118 } else if (query == GET_DEF && probe == 1) {
119 /* Many cameras don't support the GET_DEF request on their
120 * video probe control. Warn once and return, the caller will
121 * fall back to GET_CUR.
123 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
124 "compliance - GET_DEF(PROBE) not supported. "
125 "Enabling workaround.\n");
128 } else if (ret != size) {
129 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
130 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
136 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
137 ctrl->bFormatIndex = data[2];
138 ctrl->bFrameIndex = data[3];
139 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
140 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
141 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
142 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
143 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
144 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
145 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
146 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
149 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
150 ctrl->bmFramingInfo = data[30];
151 ctrl->bPreferedVersion = data[31];
152 ctrl->bMinVersion = data[32];
153 ctrl->bMaxVersion = data[33];
155 ctrl->dwClockFrequency = video->dev->clock_frequency;
156 ctrl->bmFramingInfo = 0;
157 ctrl->bPreferedVersion = 0;
158 ctrl->bMinVersion = 0;
159 ctrl->bMaxVersion = 0;
162 /* Some broken devices return a null or wrong dwMaxVideoFrameSize.
163 * Try to get the value from the format and frame descriptor.
165 uvc_fixup_buffer_size(video, ctrl);
173 static int uvc_set_video_ctrl(struct uvc_video_device *video,
174 struct uvc_streaming_control *ctrl, int probe)
180 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
181 data = kzalloc(size, GFP_KERNEL);
185 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
186 data[2] = ctrl->bFormatIndex;
187 data[3] = ctrl->bFrameIndex;
188 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
189 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
190 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
191 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
192 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
193 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
194 /* Note: Some of the fields below are not required for IN devices (see
195 * UVC spec, 4.3.1.1), but we still copy them in case support for OUT
196 * devices is added in the future. */
197 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
198 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
201 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
202 data[30] = ctrl->bmFramingInfo;
203 data[31] = ctrl->bPreferedVersion;
204 data[32] = ctrl->bMinVersion;
205 data[33] = ctrl->bMaxVersion;
208 ret = __uvc_query_ctrl(video->dev, SET_CUR, 0,
209 video->streaming->intfnum,
210 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
211 UVC_CTRL_STREAMING_TIMEOUT);
213 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
214 "%d (exp. %u).\n", probe ? "probe" : "commit",
223 int uvc_probe_video(struct uvc_video_device *video,
224 struct uvc_streaming_control *probe)
226 struct uvc_streaming_control probe_min, probe_max;
231 mutex_lock(&video->streaming->mutex);
233 /* Perform probing. The device should adjust the requested values
234 * according to its capabilities. However, some devices, namely the
235 * first generation UVC Logitech webcams, don't implement the Video
236 * Probe control properly, and just return the needed bandwidth. For
237 * that reason, if the needed bandwidth exceeds the maximum available
238 * bandwidth, try to lower the quality.
240 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
243 /* Get the minimum and maximum values for compression settings. */
244 if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
245 ret = uvc_get_video_ctrl(video, &probe_min, 1, GET_MIN);
248 ret = uvc_get_video_ctrl(video, &probe_max, 1, GET_MAX);
252 probe->wCompQuality = probe_max.wCompQuality;
255 for (i = 0; i < 2; ++i) {
256 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0 ||
257 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
260 if (video->streaming->intf->num_altsetting == 1)
263 bandwidth = probe->dwMaxPayloadTransferSize;
264 if (bandwidth <= video->streaming->maxpsize)
267 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
272 /* TODO: negotiate compression parameters */
273 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
274 probe->wPFrameRate = probe_min.wPFrameRate;
275 probe->wCompQuality = probe_max.wCompQuality;
276 probe->wCompWindowSize = probe_min.wCompWindowSize;
280 mutex_unlock(&video->streaming->mutex);
284 int uvc_commit_video(struct uvc_video_device *video,
285 struct uvc_streaming_control *probe)
287 return uvc_set_video_ctrl(video, probe, 0);
290 /* ------------------------------------------------------------------------
294 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
295 #define UVC_STREAM_EOH (1 << 7)
296 #define UVC_STREAM_ERR (1 << 6)
297 #define UVC_STREAM_STI (1 << 5)
298 #define UVC_STREAM_RES (1 << 4)
299 #define UVC_STREAM_SCR (1 << 3)
300 #define UVC_STREAM_PTS (1 << 2)
301 #define UVC_STREAM_EOF (1 << 1)
302 #define UVC_STREAM_FID (1 << 0)
304 /* Video payload decoding is handled by uvc_video_decode_start(),
305 * uvc_video_decode_data() and uvc_video_decode_end().
307 * uvc_video_decode_start is called with URB data at the start of a bulk or
308 * isochronous payload. It processes header data and returns the header size
309 * in bytes if successful. If an error occurs, it returns a negative error
310 * code. The following error codes have special meanings.
312 * - EAGAIN informs the caller that the current video buffer should be marked
313 * as done, and that the function should be called again with the same data
314 * and a new video buffer. This is used when end of frame conditions can be
315 * reliably detected at the beginning of the next frame only.
317 * If an error other than -EAGAIN is returned, the caller will drop the current
318 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
319 * made until the next payload. -ENODATA can be used to drop the current
320 * payload if no other error code is appropriate.
322 * uvc_video_decode_data is called for every URB with URB data. It copies the
323 * data to the video buffer.
325 * uvc_video_decode_end is called with header data at the end of a bulk or
326 * isochronous payload. It performs any additional header data processing and
327 * returns 0 or a negative error code if an error occured. As header data have
328 * already been processed by uvc_video_decode_start, this functions isn't
329 * required to perform sanity checks a second time.
331 * For isochronous transfers where a payload is always transfered in a single
332 * URB, the three functions will be called in a row.
334 * To let the decoder process header data and update its internal state even
335 * when no video buffer is available, uvc_video_decode_start must be prepared
336 * to be called with a NULL buf parameter. uvc_video_decode_data and
337 * uvc_video_decode_end will never be called with a NULL buffer.
339 static int uvc_video_decode_start(struct uvc_video_device *video,
340 struct uvc_buffer *buf, const __u8 *data, int len)
345 * - packet must be at least 2 bytes long
346 * - bHeaderLength value must be at least 2 bytes (see above)
347 * - bHeaderLength value can't be larger than the packet size.
349 if (len < 2 || data[0] < 2 || data[0] > len)
352 /* Skip payloads marked with the error bit ("error frames"). */
353 if (data[1] & UVC_STREAM_ERR) {
354 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
359 fid = data[1] & UVC_STREAM_FID;
361 /* Store the payload FID bit and return immediately when the buffer is
365 video->last_fid = fid;
369 /* Synchronize to the input stream by waiting for the FID bit to be
370 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
371 * video->last_fid is initialized to -1, so the first isochronous
372 * frame will always be in sync.
374 * If the device doesn't toggle the FID bit, invert video->last_fid
375 * when the EOF bit is set to force synchronisation on the next packet.
377 if (buf->state != UVC_BUF_STATE_ACTIVE) {
378 if (fid == video->last_fid) {
379 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
381 if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
382 (data[1] & UVC_STREAM_EOF))
383 video->last_fid ^= UVC_STREAM_FID;
387 /* TODO: Handle PTS and SCR. */
388 buf->state = UVC_BUF_STATE_ACTIVE;
391 /* Mark the buffer as done if we're at the beginning of a new frame.
392 * End of frame detection is better implemented by checking the EOF
393 * bit (FID bit toggling is delayed by one frame compared to the EOF
394 * bit), but some devices don't set the bit at end of frame (and the
395 * last payload can be lost anyway). We thus must check if the FID has
398 * video->last_fid is initialized to -1, so the first isochronous
399 * frame will never trigger an end of frame detection.
401 * Empty buffers (bytesused == 0) don't trigger end of frame detection
402 * as it doesn't make sense to return an empty buffer. This also
403 * avoids detecting and of frame conditions at FID toggling if the
404 * previous payload had the EOF bit set.
406 if (fid != video->last_fid && buf->buf.bytesused != 0) {
407 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
409 buf->state = UVC_BUF_STATE_DONE;
413 video->last_fid = fid;
418 static void uvc_video_decode_data(struct uvc_video_device *video,
419 struct uvc_buffer *buf, const __u8 *data, int len)
421 struct uvc_video_queue *queue = &video->queue;
422 unsigned int maxlen, nbytes;
428 /* Copy the video data to the buffer. */
429 maxlen = buf->buf.length - buf->buf.bytesused;
430 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
431 nbytes = min((unsigned int)len, maxlen);
432 memcpy(mem, data, nbytes);
433 buf->buf.bytesused += nbytes;
435 /* Complete the current frame if the buffer size was exceeded. */
437 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
438 buf->state = UVC_BUF_STATE_DONE;
442 static void uvc_video_decode_end(struct uvc_video_device *video,
443 struct uvc_buffer *buf, const __u8 *data, int len)
445 /* Mark the buffer as done if the EOF marker is set. */
446 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
447 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
449 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
450 buf->state = UVC_BUF_STATE_DONE;
451 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
452 video->last_fid ^= UVC_STREAM_FID;
456 static int uvc_video_encode_header(struct uvc_video_device *video,
457 struct uvc_buffer *buf, __u8 *data, int len)
459 data[0] = 2; /* Header length */
460 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
461 | (video->last_fid & UVC_STREAM_FID);
465 static int uvc_video_encode_data(struct uvc_video_device *video,
466 struct uvc_buffer *buf, __u8 *data, int len)
468 struct uvc_video_queue *queue = &video->queue;
472 /* Copy video data to the URB buffer. */
473 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
474 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
475 nbytes = min(video->bulk.max_payload_size - video->bulk.payload_size,
477 memcpy(data, mem, nbytes);
479 queue->buf_used += nbytes;
484 /* ------------------------------------------------------------------------
489 * Completion handler for video URBs.
491 static void uvc_video_decode_isoc(struct urb *urb,
492 struct uvc_video_device *video, struct uvc_buffer *buf)
497 for (i = 0; i < urb->number_of_packets; ++i) {
498 if (urb->iso_frame_desc[i].status < 0) {
499 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
500 "lost (%d).\n", urb->iso_frame_desc[i].status);
504 /* Decode the payload header. */
505 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
507 ret = uvc_video_decode_start(video, buf, mem,
508 urb->iso_frame_desc[i].actual_length);
510 buf = uvc_queue_next_buffer(&video->queue, buf);
511 } while (ret == -EAGAIN);
516 /* Decode the payload data. */
517 uvc_video_decode_data(video, buf, mem + ret,
518 urb->iso_frame_desc[i].actual_length - ret);
520 /* Process the header again. */
521 uvc_video_decode_end(video, buf, mem,
522 urb->iso_frame_desc[i].actual_length);
524 if (buf->state == UVC_BUF_STATE_DONE ||
525 buf->state == UVC_BUF_STATE_ERROR)
526 buf = uvc_queue_next_buffer(&video->queue, buf);
530 static void uvc_video_decode_bulk(struct urb *urb,
531 struct uvc_video_device *video, struct uvc_buffer *buf)
536 mem = urb->transfer_buffer;
537 len = urb->actual_length;
538 video->bulk.payload_size += len;
540 /* If the URB is the first of its payload, decode and save the
543 if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
545 ret = uvc_video_decode_start(video, buf, mem, len);
547 buf = uvc_queue_next_buffer(&video->queue, buf);
548 } while (ret == -EAGAIN);
550 /* If an error occured skip the rest of the payload. */
551 if (ret < 0 || buf == NULL) {
552 video->bulk.skip_payload = 1;
554 memcpy(video->bulk.header, mem, ret);
555 video->bulk.header_size = ret;
562 /* The buffer queue might have been cancelled while a bulk transfer
563 * was in progress, so we can reach here with buf equal to NULL. Make
564 * sure buf is never dereferenced if NULL.
567 /* Process video data. */
568 if (!video->bulk.skip_payload && buf != NULL)
569 uvc_video_decode_data(video, buf, mem, len);
571 /* Detect the payload end by a URB smaller than the maximum size (or
572 * a payload size equal to the maximum) and process the header again.
574 if (urb->actual_length < urb->transfer_buffer_length ||
575 video->bulk.payload_size >= video->bulk.max_payload_size) {
576 if (!video->bulk.skip_payload && buf != NULL) {
577 uvc_video_decode_end(video, buf, video->bulk.header,
578 video->bulk.payload_size);
579 if (buf->state == UVC_BUF_STATE_DONE ||
580 buf->state == UVC_BUF_STATE_ERROR)
581 buf = uvc_queue_next_buffer(&video->queue, buf);
584 video->bulk.header_size = 0;
585 video->bulk.skip_payload = 0;
586 video->bulk.payload_size = 0;
590 static void uvc_video_encode_bulk(struct urb *urb,
591 struct uvc_video_device *video, struct uvc_buffer *buf)
593 u8 *mem = urb->transfer_buffer;
594 int len = video->urb_size, ret;
597 urb->transfer_buffer_length = 0;
601 /* If the URB is the first of its payload, add the header. */
602 if (video->bulk.header_size == 0) {
603 ret = uvc_video_encode_header(video, buf, mem, len);
604 video->bulk.header_size = ret;
605 video->bulk.payload_size += ret;
610 /* Process video data. */
611 ret = uvc_video_encode_data(video, buf, mem, len);
613 video->bulk.payload_size += ret;
616 if (buf->buf.bytesused == video->queue.buf_used ||
617 video->bulk.payload_size == video->bulk.max_payload_size) {
618 if (buf->buf.bytesused == video->queue.buf_used) {
619 video->queue.buf_used = 0;
620 buf->state = UVC_BUF_STATE_DONE;
621 uvc_queue_next_buffer(&video->queue, buf);
622 video->last_fid ^= UVC_STREAM_FID;
625 video->bulk.header_size = 0;
626 video->bulk.payload_size = 0;
629 urb->transfer_buffer_length = video->urb_size - len;
632 static void uvc_video_complete(struct urb *urb)
634 struct uvc_video_device *video = urb->context;
635 struct uvc_video_queue *queue = &video->queue;
636 struct uvc_buffer *buf = NULL;
640 switch (urb->status) {
645 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
646 "completion handler.\n", urb->status);
648 case -ENOENT: /* usb_kill_urb() called. */
652 case -ECONNRESET: /* usb_unlink_urb() called. */
653 case -ESHUTDOWN: /* The endpoint is being disabled. */
654 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
658 spin_lock_irqsave(&queue->irqlock, flags);
659 if (!list_empty(&queue->irqqueue))
660 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
662 spin_unlock_irqrestore(&queue->irqlock, flags);
664 video->decode(urb, video, buf);
666 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
667 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
673 * Free transfer buffers.
675 static void uvc_free_urb_buffers(struct uvc_video_device *video)
679 for (i = 0; i < UVC_URBS; ++i) {
680 if (video->urb_buffer[i]) {
681 usb_buffer_free(video->dev->udev, video->urb_size,
682 video->urb_buffer[i], video->urb_dma[i]);
683 video->urb_buffer[i] = NULL;
691 * Allocate transfer buffers. This function can be called with buffers
692 * already allocated when resuming from suspend, in which case it will
693 * return without touching the buffers.
695 * Return 0 on success or -ENOMEM when out of memory.
697 static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
702 /* Buffers are already allocated, bail out. */
706 for (i = 0; i < UVC_URBS; ++i) {
707 video->urb_buffer[i] = usb_buffer_alloc(video->dev->udev,
708 size, GFP_KERNEL, &video->urb_dma[i]);
709 if (video->urb_buffer[i] == NULL) {
710 uvc_free_urb_buffers(video);
715 video->urb_size = size;
720 * Uninitialize isochronous/bulk URBs and free transfer buffers.
722 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
727 for (i = 0; i < UVC_URBS; ++i) {
728 if ((urb = video->urb[i]) == NULL)
733 video->urb[i] = NULL;
737 uvc_free_urb_buffers(video);
741 * Initialize isochronous URBs and allocate transfer buffers. The packet size
742 * is given by the endpoint.
744 static int uvc_init_video_isoc(struct uvc_video_device *video,
745 struct usb_host_endpoint *ep, gfp_t gfp_flags)
748 unsigned int npackets, i, j;
752 /* Compute the number of isochronous packets to allocate by dividing
753 * the maximum video frame size by the packet size. Limit the result
754 * to UVC_MAX_ISO_PACKETS.
756 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
757 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
759 size = video->streaming->ctrl.dwMaxVideoFrameSize;
760 if (size > UVC_MAX_FRAME_SIZE)
763 npackets = DIV_ROUND_UP(size, psize);
764 if (npackets > UVC_MAX_ISO_PACKETS)
765 npackets = UVC_MAX_ISO_PACKETS;
767 size = npackets * psize;
769 if (uvc_alloc_urb_buffers(video, size) < 0)
772 for (i = 0; i < UVC_URBS; ++i) {
773 urb = usb_alloc_urb(npackets, gfp_flags);
775 uvc_uninit_video(video, 1);
779 urb->dev = video->dev->udev;
780 urb->context = video;
781 urb->pipe = usb_rcvisocpipe(video->dev->udev,
782 ep->desc.bEndpointAddress);
783 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
784 urb->interval = ep->desc.bInterval;
785 urb->transfer_buffer = video->urb_buffer[i];
786 urb->transfer_dma = video->urb_dma[i];
787 urb->complete = uvc_video_complete;
788 urb->number_of_packets = npackets;
789 urb->transfer_buffer_length = size;
791 for (j = 0; j < npackets; ++j) {
792 urb->iso_frame_desc[j].offset = j * psize;
793 urb->iso_frame_desc[j].length = psize;
803 * Initialize bulk URBs and allocate transfer buffers. The packet size is
804 * given by the endpoint.
806 static int uvc_init_video_bulk(struct uvc_video_device *video,
807 struct usb_host_endpoint *ep, gfp_t gfp_flags)
810 unsigned int pipe, i;
814 /* Compute the bulk URB size. Some devices set the maximum payload
815 * size to a value too high for memory-constrained devices. We must
816 * then transfer the payload accross multiple URBs. To be consistant
817 * with isochronous mode, allocate maximum UVC_MAX_ISO_PACKETS per bulk
820 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
821 size = video->streaming->ctrl.dwMaxPayloadTransferSize;
822 video->bulk.max_payload_size = size;
823 if (size > psize * UVC_MAX_ISO_PACKETS)
824 size = psize * UVC_MAX_ISO_PACKETS;
826 if (uvc_alloc_urb_buffers(video, size) < 0)
829 if (usb_endpoint_dir_in(&ep->desc))
830 pipe = usb_rcvbulkpipe(video->dev->udev,
831 ep->desc.bEndpointAddress);
833 pipe = usb_sndbulkpipe(video->dev->udev,
834 ep->desc.bEndpointAddress);
836 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
839 for (i = 0; i < UVC_URBS; ++i) {
840 urb = usb_alloc_urb(0, gfp_flags);
842 uvc_uninit_video(video, 1);
846 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
847 video->urb_buffer[i], size, uvc_video_complete,
849 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
850 urb->transfer_dma = video->urb_dma[i];
859 * Initialize isochronous/bulk URBs and allocate transfer buffers.
861 static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
863 struct usb_interface *intf = video->streaming->intf;
864 struct usb_host_interface *alts;
865 struct usb_host_endpoint *ep = NULL;
866 int intfnum = video->streaming->intfnum;
867 unsigned int bandwidth, psize, i;
870 video->last_fid = -1;
871 video->bulk.header_size = 0;
872 video->bulk.skip_payload = 0;
873 video->bulk.payload_size = 0;
875 if (intf->num_altsetting > 1) {
876 /* Isochronous endpoint, select the alternate setting. */
877 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
879 if (bandwidth == 0) {
880 uvc_printk(KERN_WARNING, "device %s requested null "
881 "bandwidth, defaulting to lowest.\n",
886 for (i = 0; i < intf->num_altsetting; ++i) {
887 alts = &intf->altsetting[i];
888 ep = uvc_find_endpoint(alts,
889 video->streaming->header.bEndpointAddress);
893 /* Check if the bandwidth is high enough. */
894 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
895 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
896 if (psize >= bandwidth)
900 if (i >= intf->num_altsetting)
903 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
906 ret = uvc_init_video_isoc(video, ep, gfp_flags);
908 /* Bulk endpoint, proceed to URB initialization. */
909 ep = uvc_find_endpoint(&intf->altsetting[0],
910 video->streaming->header.bEndpointAddress);
914 ret = uvc_init_video_bulk(video, ep, gfp_flags);
920 /* Submit the URBs. */
921 for (i = 0; i < UVC_URBS; ++i) {
922 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
923 uvc_printk(KERN_ERR, "Failed to submit URB %u "
925 uvc_uninit_video(video, 1);
933 /* --------------------------------------------------------------------------
938 * Stop streaming without disabling the video queue.
940 * To let userspace applications resume without trouble, we must not touch the
941 * video buffers in any way. We mark the device as frozen to make sure the URB
942 * completion handler won't try to cancel the queue when we kill the URBs.
944 int uvc_video_suspend(struct uvc_video_device *video)
946 if (!uvc_queue_streaming(&video->queue))
950 uvc_uninit_video(video, 0);
951 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
956 * Reconfigure the video interface and restart streaming if it was enable
959 * If an error occurs, disable the video queue. This will wake all pending
960 * buffers, making sure userspace applications are notified of the problem
961 * instead of waiting forever.
963 int uvc_video_resume(struct uvc_video_device *video)
969 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
970 uvc_queue_enable(&video->queue, 0);
974 if (!uvc_queue_streaming(&video->queue))
977 if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
978 uvc_queue_enable(&video->queue, 0);
983 /* ------------------------------------------------------------------------
988 * Initialize the UVC video device by retrieving the default format and
991 * Some cameras (namely the Fuji Finepix) set the format and frame
992 * indexes to zero. The UVC standard doesn't clearly make this a spec
993 * violation, so try to silently fix the values if possible.
995 * This function is called before registering the device with V4L.
997 int uvc_video_init(struct uvc_video_device *video)
999 struct uvc_streaming_control *probe = &video->streaming->ctrl;
1000 struct uvc_format *format = NULL;
1001 struct uvc_frame *frame = NULL;
1005 if (video->streaming->nformats == 0) {
1006 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1010 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1011 * Cam (and possibly other devices) crash or otherwise misbehave if
1012 * they don't receive a SET_INTERFACE request before any other video
1015 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1017 /* Some webcams don't suport GET_DEF request on the probe control. We
1018 * fall back to GET_CUR if GET_DEF fails.
1020 if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_DEF)) < 0 &&
1021 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
1024 /* Check if the default format descriptor exists. Use the first
1025 * available format otherwise.
1027 for (i = video->streaming->nformats; i > 0; --i) {
1028 format = &video->streaming->format[i-1];
1029 if (format->index == probe->bFormatIndex)
1033 if (format->nframes == 0) {
1034 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1035 "default format.\n");
1039 /* Zero bFrameIndex might be correct. Stream-based formats (including
1040 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1041 * descriptor with bFrameIndex set to zero. If the default frame
1042 * descriptor is not found, use the first avalable frame.
1044 for (i = format->nframes; i > 0; --i) {
1045 frame = &format->frame[i-1];
1046 if (frame->bFrameIndex == probe->bFrameIndex)
1050 probe->bFormatIndex = format->index;
1051 probe->bFrameIndex = frame->bFrameIndex;
1053 video->streaming->cur_format = format;
1054 video->streaming->cur_frame = frame;
1055 atomic_set(&video->active, 0);
1057 /* Select the video decoding function */
1058 if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1059 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1060 video->decode = uvc_video_decode_isight;
1061 else if (video->streaming->intf->num_altsetting > 1)
1062 video->decode = uvc_video_decode_isoc;
1064 video->decode = uvc_video_decode_bulk;
1066 if (video->streaming->intf->num_altsetting == 1)
1067 video->decode = uvc_video_encode_bulk;
1069 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1070 "supported for video output devices.\n");
1079 * Enable or disable the video stream.
1081 int uvc_video_enable(struct uvc_video_device *video, int enable)
1086 uvc_uninit_video(video, 1);
1087 usb_set_interface(video->dev->udev,
1088 video->streaming->intfnum, 0);
1089 uvc_queue_enable(&video->queue, 0);
1093 if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1095 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1097 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1099 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1102 /* Commit the streaming parameters. */
1103 if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1106 return uvc_init_video(video, GFP_KERNEL);