2 * uvc_video.c -- USB Video Class driver - Video handling
4 * Copyright (C) 2005-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
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/slab.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 static const char *uvc_query_name(__u8 query)
72 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
73 __u8 intfnum, __u8 cs, void *data, __u16 size)
77 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
78 UVC_CTRL_CONTROL_TIMEOUT);
80 uvc_printk(KERN_ERR, "Failed to query (%s) UVC control %u on "
81 "unit %u: %d (exp. %u).\n", uvc_query_name(query), cs,
89 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
90 struct uvc_streaming_control *ctrl)
92 struct uvc_format *format;
93 struct uvc_frame *frame = NULL;
96 if (ctrl->bFormatIndex <= 0 ||
97 ctrl->bFormatIndex > stream->nformats)
100 format = &stream->format[ctrl->bFormatIndex - 1];
102 for (i = 0; i < format->nframes; ++i) {
103 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
104 frame = &format->frame[i];
112 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
113 (ctrl->dwMaxVideoFrameSize == 0 &&
114 stream->dev->uvc_version < 0x0110))
115 ctrl->dwMaxVideoFrameSize =
116 frame->dwMaxVideoFrameBufferSize;
118 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
119 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
120 stream->intf->num_altsetting > 1) {
124 interval = (ctrl->dwFrameInterval > 100000)
125 ? ctrl->dwFrameInterval
126 : frame->dwFrameInterval[0];
128 /* Compute a bandwidth estimation by multiplying the frame
129 * size by the number of video frames per second, divide the
130 * result by the number of USB frames (or micro-frames for
131 * high-speed devices) per second and add the UVC header size
132 * (assumed to be 12 bytes long).
134 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
135 bandwidth *= 10000000 / interval + 1;
137 if (stream->dev->udev->speed == USB_SPEED_HIGH)
141 /* The bandwidth estimate is too low for many cameras. Don't use
142 * maximum packet sizes lower than 1024 bytes to try and work
143 * around the problem. According to measurements done on two
144 * different camera models, the value is high enough to get most
145 * resolutions working while not preventing two simultaneous
146 * VGA streams at 15 fps.
148 bandwidth = max_t(u32, bandwidth, 1024);
150 ctrl->dwMaxPayloadTransferSize = bandwidth;
154 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
155 struct uvc_streaming_control *ctrl, int probe, __u8 query)
161 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
162 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
163 query == UVC_GET_DEF)
166 data = kmalloc(size, GFP_KERNEL);
170 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
171 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
172 size, uvc_timeout_param);
174 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
175 /* Some cameras, mostly based on Bison Electronics chipsets,
176 * answer a GET_MIN or GET_MAX request with the wCompQuality
179 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
180 "compliance - GET_MIN/MAX(PROBE) incorrectly "
181 "supported. Enabling workaround.\n");
182 memset(ctrl, 0, sizeof *ctrl);
183 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
186 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
187 /* Many cameras don't support the GET_DEF request on their
188 * video probe control. Warn once and return, the caller will
189 * fall back to GET_CUR.
191 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
192 "compliance - GET_DEF(PROBE) not supported. "
193 "Enabling workaround.\n");
196 } else if (ret != size) {
197 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
198 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
204 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
205 ctrl->bFormatIndex = data[2];
206 ctrl->bFrameIndex = data[3];
207 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
208 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
209 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
210 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
211 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
212 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
213 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
214 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
217 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
218 ctrl->bmFramingInfo = data[30];
219 ctrl->bPreferedVersion = data[31];
220 ctrl->bMinVersion = data[32];
221 ctrl->bMaxVersion = data[33];
223 ctrl->dwClockFrequency = stream->dev->clock_frequency;
224 ctrl->bmFramingInfo = 0;
225 ctrl->bPreferedVersion = 0;
226 ctrl->bMinVersion = 0;
227 ctrl->bMaxVersion = 0;
230 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
231 * dwMaxPayloadTransferSize fields. Try to get the value from the
232 * format and frame descriptors.
234 uvc_fixup_video_ctrl(stream, ctrl);
242 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
243 struct uvc_streaming_control *ctrl, int probe)
249 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
250 data = kzalloc(size, GFP_KERNEL);
254 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
255 data[2] = ctrl->bFormatIndex;
256 data[3] = ctrl->bFrameIndex;
257 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
258 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
259 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
260 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
261 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
262 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
263 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
264 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
267 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
268 data[30] = ctrl->bmFramingInfo;
269 data[31] = ctrl->bPreferedVersion;
270 data[32] = ctrl->bMinVersion;
271 data[33] = ctrl->bMaxVersion;
274 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
275 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
276 size, uvc_timeout_param);
278 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
279 "%d (exp. %u).\n", probe ? "probe" : "commit",
288 int uvc_probe_video(struct uvc_streaming *stream,
289 struct uvc_streaming_control *probe)
291 struct uvc_streaming_control probe_min, probe_max;
296 /* Perform probing. The device should adjust the requested values
297 * according to its capabilities. However, some devices, namely the
298 * first generation UVC Logitech webcams, don't implement the Video
299 * Probe control properly, and just return the needed bandwidth. For
300 * that reason, if the needed bandwidth exceeds the maximum available
301 * bandwidth, try to lower the quality.
303 ret = uvc_set_video_ctrl(stream, probe, 1);
307 /* Get the minimum and maximum values for compression settings. */
308 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
309 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
312 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
316 probe->wCompQuality = probe_max.wCompQuality;
319 for (i = 0; i < 2; ++i) {
320 ret = uvc_set_video_ctrl(stream, probe, 1);
323 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
327 if (stream->intf->num_altsetting == 1)
330 bandwidth = probe->dwMaxPayloadTransferSize;
331 if (bandwidth <= stream->maxpsize)
334 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
339 /* TODO: negotiate compression parameters */
340 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
341 probe->wPFrameRate = probe_min.wPFrameRate;
342 probe->wCompQuality = probe_max.wCompQuality;
343 probe->wCompWindowSize = probe_min.wCompWindowSize;
350 int uvc_commit_video(struct uvc_streaming *stream,
351 struct uvc_streaming_control *probe)
353 return uvc_set_video_ctrl(stream, probe, 0);
356 /* ------------------------------------------------------------------------
360 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
361 #define UVC_STREAM_EOH (1 << 7)
362 #define UVC_STREAM_ERR (1 << 6)
363 #define UVC_STREAM_STI (1 << 5)
364 #define UVC_STREAM_RES (1 << 4)
365 #define UVC_STREAM_SCR (1 << 3)
366 #define UVC_STREAM_PTS (1 << 2)
367 #define UVC_STREAM_EOF (1 << 1)
368 #define UVC_STREAM_FID (1 << 0)
370 /* Video payload decoding is handled by uvc_video_decode_start(),
371 * uvc_video_decode_data() and uvc_video_decode_end().
373 * uvc_video_decode_start is called with URB data at the start of a bulk or
374 * isochronous payload. It processes header data and returns the header size
375 * in bytes if successful. If an error occurs, it returns a negative error
376 * code. The following error codes have special meanings.
378 * - EAGAIN informs the caller that the current video buffer should be marked
379 * as done, and that the function should be called again with the same data
380 * and a new video buffer. This is used when end of frame conditions can be
381 * reliably detected at the beginning of the next frame only.
383 * If an error other than -EAGAIN is returned, the caller will drop the current
384 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
385 * made until the next payload. -ENODATA can be used to drop the current
386 * payload if no other error code is appropriate.
388 * uvc_video_decode_data is called for every URB with URB data. It copies the
389 * data to the video buffer.
391 * uvc_video_decode_end is called with header data at the end of a bulk or
392 * isochronous payload. It performs any additional header data processing and
393 * returns 0 or a negative error code if an error occured. As header data have
394 * already been processed by uvc_video_decode_start, this functions isn't
395 * required to perform sanity checks a second time.
397 * For isochronous transfers where a payload is always transfered in a single
398 * URB, the three functions will be called in a row.
400 * To let the decoder process header data and update its internal state even
401 * when no video buffer is available, uvc_video_decode_start must be prepared
402 * to be called with a NULL buf parameter. uvc_video_decode_data and
403 * uvc_video_decode_end will never be called with a NULL buffer.
405 static int uvc_video_decode_start(struct uvc_streaming *stream,
406 struct uvc_buffer *buf, const __u8 *data, int len)
411 * - packet must be at least 2 bytes long
412 * - bHeaderLength value must be at least 2 bytes (see above)
413 * - bHeaderLength value can't be larger than the packet size.
415 if (len < 2 || data[0] < 2 || data[0] > len)
418 /* Skip payloads marked with the error bit ("error frames"). */
419 if (data[1] & UVC_STREAM_ERR) {
420 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
425 fid = data[1] & UVC_STREAM_FID;
427 /* Increase the sequence number regardless of any buffer states, so
428 * that discontinuous sequence numbers always indicate lost frames.
430 if (stream->last_fid != fid)
433 /* Store the payload FID bit and return immediately when the buffer is
437 stream->last_fid = fid;
441 /* Synchronize to the input stream by waiting for the FID bit to be
442 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
443 * stream->last_fid is initialized to -1, so the first isochronous
444 * frame will always be in sync.
446 * If the device doesn't toggle the FID bit, invert stream->last_fid
447 * when the EOF bit is set to force synchronisation on the next packet.
449 if (buf->state != UVC_BUF_STATE_ACTIVE) {
452 if (fid == stream->last_fid) {
453 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
455 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
456 (data[1] & UVC_STREAM_EOF))
457 stream->last_fid ^= UVC_STREAM_FID;
461 if (uvc_clock_param == CLOCK_MONOTONIC)
464 ktime_get_real_ts(&ts);
466 buf->buf.sequence = stream->sequence;
467 buf->buf.timestamp.tv_sec = ts.tv_sec;
468 buf->buf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
470 /* TODO: Handle PTS and SCR. */
471 buf->state = UVC_BUF_STATE_ACTIVE;
474 /* Mark the buffer as done if we're at the beginning of a new frame.
475 * End of frame detection is better implemented by checking the EOF
476 * bit (FID bit toggling is delayed by one frame compared to the EOF
477 * bit), but some devices don't set the bit at end of frame (and the
478 * last payload can be lost anyway). We thus must check if the FID has
481 * stream->last_fid is initialized to -1, so the first isochronous
482 * frame will never trigger an end of frame detection.
484 * Empty buffers (bytesused == 0) don't trigger end of frame detection
485 * as it doesn't make sense to return an empty buffer. This also
486 * avoids detecting end of frame conditions at FID toggling if the
487 * previous payload had the EOF bit set.
489 if (fid != stream->last_fid && buf->buf.bytesused != 0) {
490 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
492 buf->state = UVC_BUF_STATE_READY;
496 stream->last_fid = fid;
501 static void uvc_video_decode_data(struct uvc_streaming *stream,
502 struct uvc_buffer *buf, const __u8 *data, int len)
504 struct uvc_video_queue *queue = &stream->queue;
505 unsigned int maxlen, nbytes;
511 /* Copy the video data to the buffer. */
512 maxlen = buf->buf.length - buf->buf.bytesused;
513 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
514 nbytes = min((unsigned int)len, maxlen);
515 memcpy(mem, data, nbytes);
516 buf->buf.bytesused += nbytes;
518 /* Complete the current frame if the buffer size was exceeded. */
520 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
521 buf->state = UVC_BUF_STATE_READY;
525 static void uvc_video_decode_end(struct uvc_streaming *stream,
526 struct uvc_buffer *buf, const __u8 *data, int len)
528 /* Mark the buffer as done if the EOF marker is set. */
529 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
530 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
532 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
533 buf->state = UVC_BUF_STATE_READY;
534 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
535 stream->last_fid ^= UVC_STREAM_FID;
539 /* Video payload encoding is handled by uvc_video_encode_header() and
540 * uvc_video_encode_data(). Only bulk transfers are currently supported.
542 * uvc_video_encode_header is called at the start of a payload. It adds header
543 * data to the transfer buffer and returns the header size. As the only known
544 * UVC output device transfers a whole frame in a single payload, the EOF bit
545 * is always set in the header.
547 * uvc_video_encode_data is called for every URB and copies the data from the
548 * video buffer to the transfer buffer.
550 static int uvc_video_encode_header(struct uvc_streaming *stream,
551 struct uvc_buffer *buf, __u8 *data, int len)
553 data[0] = 2; /* Header length */
554 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
555 | (stream->last_fid & UVC_STREAM_FID);
559 static int uvc_video_encode_data(struct uvc_streaming *stream,
560 struct uvc_buffer *buf, __u8 *data, int len)
562 struct uvc_video_queue *queue = &stream->queue;
566 /* Copy video data to the URB buffer. */
567 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
568 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
569 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
571 memcpy(data, mem, nbytes);
573 queue->buf_used += nbytes;
578 /* ------------------------------------------------------------------------
583 * Completion handler for video URBs.
585 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
586 struct uvc_buffer *buf)
591 for (i = 0; i < urb->number_of_packets; ++i) {
592 if (urb->iso_frame_desc[i].status < 0) {
593 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
594 "lost (%d).\n", urb->iso_frame_desc[i].status);
595 /* Mark the buffer as faulty. */
601 /* Decode the payload header. */
602 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
604 ret = uvc_video_decode_start(stream, buf, mem,
605 urb->iso_frame_desc[i].actual_length);
607 buf = uvc_queue_next_buffer(&stream->queue,
609 } while (ret == -EAGAIN);
614 /* Decode the payload data. */
615 uvc_video_decode_data(stream, buf, mem + ret,
616 urb->iso_frame_desc[i].actual_length - ret);
618 /* Process the header again. */
619 uvc_video_decode_end(stream, buf, mem,
620 urb->iso_frame_desc[i].actual_length);
622 if (buf->state == UVC_BUF_STATE_READY) {
623 if (buf->buf.length != buf->buf.bytesused &&
624 !(stream->cur_format->flags &
625 UVC_FMT_FLAG_COMPRESSED))
628 buf = uvc_queue_next_buffer(&stream->queue, buf);
633 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
634 struct uvc_buffer *buf)
639 if (urb->actual_length == 0)
642 mem = urb->transfer_buffer;
643 len = urb->actual_length;
644 stream->bulk.payload_size += len;
646 /* If the URB is the first of its payload, decode and save the
649 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
651 ret = uvc_video_decode_start(stream, buf, mem, len);
653 buf = uvc_queue_next_buffer(&stream->queue,
655 } while (ret == -EAGAIN);
657 /* If an error occured skip the rest of the payload. */
658 if (ret < 0 || buf == NULL) {
659 stream->bulk.skip_payload = 1;
661 memcpy(stream->bulk.header, mem, ret);
662 stream->bulk.header_size = ret;
669 /* The buffer queue might have been cancelled while a bulk transfer
670 * was in progress, so we can reach here with buf equal to NULL. Make
671 * sure buf is never dereferenced if NULL.
674 /* Process video data. */
675 if (!stream->bulk.skip_payload && buf != NULL)
676 uvc_video_decode_data(stream, buf, mem, len);
678 /* Detect the payload end by a URB smaller than the maximum size (or
679 * a payload size equal to the maximum) and process the header again.
681 if (urb->actual_length < urb->transfer_buffer_length ||
682 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
683 if (!stream->bulk.skip_payload && buf != NULL) {
684 uvc_video_decode_end(stream, buf, stream->bulk.header,
685 stream->bulk.payload_size);
686 if (buf->state == UVC_BUF_STATE_READY)
687 buf = uvc_queue_next_buffer(&stream->queue,
691 stream->bulk.header_size = 0;
692 stream->bulk.skip_payload = 0;
693 stream->bulk.payload_size = 0;
697 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
698 struct uvc_buffer *buf)
700 u8 *mem = urb->transfer_buffer;
701 int len = stream->urb_size, ret;
704 urb->transfer_buffer_length = 0;
708 /* If the URB is the first of its payload, add the header. */
709 if (stream->bulk.header_size == 0) {
710 ret = uvc_video_encode_header(stream, buf, mem, len);
711 stream->bulk.header_size = ret;
712 stream->bulk.payload_size += ret;
717 /* Process video data. */
718 ret = uvc_video_encode_data(stream, buf, mem, len);
720 stream->bulk.payload_size += ret;
723 if (buf->buf.bytesused == stream->queue.buf_used ||
724 stream->bulk.payload_size == stream->bulk.max_payload_size) {
725 if (buf->buf.bytesused == stream->queue.buf_used) {
726 stream->queue.buf_used = 0;
727 buf->state = UVC_BUF_STATE_READY;
728 buf->buf.sequence = ++stream->sequence;
729 uvc_queue_next_buffer(&stream->queue, buf);
730 stream->last_fid ^= UVC_STREAM_FID;
733 stream->bulk.header_size = 0;
734 stream->bulk.payload_size = 0;
737 urb->transfer_buffer_length = stream->urb_size - len;
740 static void uvc_video_complete(struct urb *urb)
742 struct uvc_streaming *stream = urb->context;
743 struct uvc_video_queue *queue = &stream->queue;
744 struct uvc_buffer *buf = NULL;
748 switch (urb->status) {
753 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
754 "completion handler.\n", urb->status);
756 case -ENOENT: /* usb_kill_urb() called. */
760 case -ECONNRESET: /* usb_unlink_urb() called. */
761 case -ESHUTDOWN: /* The endpoint is being disabled. */
762 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
766 spin_lock_irqsave(&queue->irqlock, flags);
767 if (!list_empty(&queue->irqqueue))
768 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
770 spin_unlock_irqrestore(&queue->irqlock, flags);
772 stream->decode(urb, stream, buf);
774 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
775 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
781 * Free transfer buffers.
783 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
787 for (i = 0; i < UVC_URBS; ++i) {
788 if (stream->urb_buffer[i]) {
789 usb_free_coherent(stream->dev->udev, stream->urb_size,
790 stream->urb_buffer[i], stream->urb_dma[i]);
791 stream->urb_buffer[i] = NULL;
795 stream->urb_size = 0;
799 * Allocate transfer buffers. This function can be called with buffers
800 * already allocated when resuming from suspend, in which case it will
801 * return without touching the buffers.
803 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
804 * system is too low on memory try successively smaller numbers of packets
805 * until allocation succeeds.
807 * Return the number of allocated packets on success or 0 when out of memory.
809 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
810 unsigned int size, unsigned int psize, gfp_t gfp_flags)
812 unsigned int npackets;
815 /* Buffers are already allocated, bail out. */
816 if (stream->urb_size)
817 return stream->urb_size / psize;
819 /* Compute the number of packets. Bulk endpoints might transfer UVC
820 * payloads accross multiple URBs.
822 npackets = DIV_ROUND_UP(size, psize);
823 if (npackets > UVC_MAX_PACKETS)
824 npackets = UVC_MAX_PACKETS;
826 /* Retry allocations until one succeed. */
827 for (; npackets > 1; npackets /= 2) {
828 for (i = 0; i < UVC_URBS; ++i) {
829 stream->urb_size = psize * npackets;
830 stream->urb_buffer[i] = usb_alloc_coherent(
831 stream->dev->udev, stream->urb_size,
832 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
833 if (!stream->urb_buffer[i]) {
834 uvc_free_urb_buffers(stream);
840 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
841 "of %ux%u bytes each.\n", UVC_URBS, npackets,
847 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
848 "per packet).\n", psize);
853 * Uninitialize isochronous/bulk URBs and free transfer buffers.
855 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
860 for (i = 0; i < UVC_URBS; ++i) {
861 urb = stream->urb[i];
867 stream->urb[i] = NULL;
871 uvc_free_urb_buffers(stream);
875 * Initialize isochronous URBs and allocate transfer buffers. The packet size
876 * is given by the endpoint.
878 static int uvc_init_video_isoc(struct uvc_streaming *stream,
879 struct usb_host_endpoint *ep, gfp_t gfp_flags)
882 unsigned int npackets, i, j;
886 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
887 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
888 size = stream->ctrl.dwMaxVideoFrameSize;
890 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
894 size = npackets * psize;
896 for (i = 0; i < UVC_URBS; ++i) {
897 urb = usb_alloc_urb(npackets, gfp_flags);
899 uvc_uninit_video(stream, 1);
903 urb->dev = stream->dev->udev;
904 urb->context = stream;
905 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
906 ep->desc.bEndpointAddress);
907 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
908 urb->interval = ep->desc.bInterval;
909 urb->transfer_buffer = stream->urb_buffer[i];
910 urb->transfer_dma = stream->urb_dma[i];
911 urb->complete = uvc_video_complete;
912 urb->number_of_packets = npackets;
913 urb->transfer_buffer_length = size;
915 for (j = 0; j < npackets; ++j) {
916 urb->iso_frame_desc[j].offset = j * psize;
917 urb->iso_frame_desc[j].length = psize;
920 stream->urb[i] = urb;
927 * Initialize bulk URBs and allocate transfer buffers. The packet size is
928 * given by the endpoint.
930 static int uvc_init_video_bulk(struct uvc_streaming *stream,
931 struct usb_host_endpoint *ep, gfp_t gfp_flags)
934 unsigned int npackets, pipe, i;
938 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
939 size = stream->ctrl.dwMaxPayloadTransferSize;
940 stream->bulk.max_payload_size = size;
942 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
946 size = npackets * psize;
948 if (usb_endpoint_dir_in(&ep->desc))
949 pipe = usb_rcvbulkpipe(stream->dev->udev,
950 ep->desc.bEndpointAddress);
952 pipe = usb_sndbulkpipe(stream->dev->udev,
953 ep->desc.bEndpointAddress);
955 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
958 for (i = 0; i < UVC_URBS; ++i) {
959 urb = usb_alloc_urb(0, gfp_flags);
961 uvc_uninit_video(stream, 1);
965 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
966 stream->urb_buffer[i], size, uvc_video_complete,
968 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
969 urb->transfer_dma = stream->urb_dma[i];
971 stream->urb[i] = urb;
978 * Initialize isochronous/bulk URBs and allocate transfer buffers.
980 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
982 struct usb_interface *intf = stream->intf;
983 struct usb_host_endpoint *ep;
987 stream->sequence = -1;
988 stream->last_fid = -1;
989 stream->bulk.header_size = 0;
990 stream->bulk.skip_payload = 0;
991 stream->bulk.payload_size = 0;
993 if (intf->num_altsetting > 1) {
994 struct usb_host_endpoint *best_ep = NULL;
995 unsigned int best_psize = 3 * 1024;
996 unsigned int bandwidth;
997 unsigned int uninitialized_var(altsetting);
998 int intfnum = stream->intfnum;
1000 /* Isochronous endpoint, select the alternate setting. */
1001 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1003 if (bandwidth == 0) {
1004 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1005 "bandwidth, defaulting to lowest.\n");
1008 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1009 "B/frame bandwidth.\n", bandwidth);
1012 for (i = 0; i < intf->num_altsetting; ++i) {
1013 struct usb_host_interface *alts;
1016 alts = &intf->altsetting[i];
1017 ep = uvc_find_endpoint(alts,
1018 stream->header.bEndpointAddress);
1022 /* Check if the bandwidth is high enough. */
1023 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1024 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1025 if (psize >= bandwidth && psize <= best_psize) {
1032 if (best_ep == NULL) {
1033 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1034 "for requested bandwidth.\n");
1038 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1039 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1041 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1045 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1047 /* Bulk endpoint, proceed to URB initialization. */
1048 ep = uvc_find_endpoint(&intf->altsetting[0],
1049 stream->header.bEndpointAddress);
1053 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1059 /* Submit the URBs. */
1060 for (i = 0; i < UVC_URBS; ++i) {
1061 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1063 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1065 uvc_uninit_video(stream, 1);
1073 /* --------------------------------------------------------------------------
1078 * Stop streaming without disabling the video queue.
1080 * To let userspace applications resume without trouble, we must not touch the
1081 * video buffers in any way. We mark the device as frozen to make sure the URB
1082 * completion handler won't try to cancel the queue when we kill the URBs.
1084 int uvc_video_suspend(struct uvc_streaming *stream)
1086 if (!uvc_queue_streaming(&stream->queue))
1090 uvc_uninit_video(stream, 0);
1091 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1096 * Reconfigure the video interface and restart streaming if it was enabled
1099 * If an error occurs, disable the video queue. This will wake all pending
1100 * buffers, making sure userspace applications are notified of the problem
1101 * instead of waiting forever.
1103 int uvc_video_resume(struct uvc_streaming *stream)
1109 ret = uvc_commit_video(stream, &stream->ctrl);
1111 uvc_queue_enable(&stream->queue, 0);
1115 if (!uvc_queue_streaming(&stream->queue))
1118 ret = uvc_init_video(stream, GFP_NOIO);
1120 uvc_queue_enable(&stream->queue, 0);
1125 /* ------------------------------------------------------------------------
1130 * Initialize the UVC video device by switching to alternate setting 0 and
1131 * retrieve the default format.
1133 * Some cameras (namely the Fuji Finepix) set the format and frame
1134 * indexes to zero. The UVC standard doesn't clearly make this a spec
1135 * violation, so try to silently fix the values if possible.
1137 * This function is called before registering the device with V4L.
1139 int uvc_video_init(struct uvc_streaming *stream)
1141 struct uvc_streaming_control *probe = &stream->ctrl;
1142 struct uvc_format *format = NULL;
1143 struct uvc_frame *frame = NULL;
1147 if (stream->nformats == 0) {
1148 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1152 atomic_set(&stream->active, 0);
1154 /* Initialize the video buffers queue. */
1155 uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1157 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1158 * Cam (and possibly other devices) crash or otherwise misbehave if
1159 * they don't receive a SET_INTERFACE request before any other video
1162 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1164 /* Set the streaming probe control with default streaming parameters
1165 * retrieved from the device. Webcams that don't suport GET_DEF
1166 * requests on the probe control will just keep their current streaming
1169 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1170 uvc_set_video_ctrl(stream, probe, 1);
1172 /* Initialize the streaming parameters with the probe control current
1173 * value. This makes sure SET_CUR requests on the streaming commit
1174 * control will always use values retrieved from a successful GET_CUR
1175 * request on the probe control, as required by the UVC specification.
1177 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1181 /* Check if the default format descriptor exists. Use the first
1182 * available format otherwise.
1184 for (i = stream->nformats; i > 0; --i) {
1185 format = &stream->format[i-1];
1186 if (format->index == probe->bFormatIndex)
1190 if (format->nframes == 0) {
1191 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1192 "default format.\n");
1196 /* Zero bFrameIndex might be correct. Stream-based formats (including
1197 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1198 * descriptor with bFrameIndex set to zero. If the default frame
1199 * descriptor is not found, use the first available frame.
1201 for (i = format->nframes; i > 0; --i) {
1202 frame = &format->frame[i-1];
1203 if (frame->bFrameIndex == probe->bFrameIndex)
1207 probe->bFormatIndex = format->index;
1208 probe->bFrameIndex = frame->bFrameIndex;
1210 stream->cur_format = format;
1211 stream->cur_frame = frame;
1213 /* Select the video decoding function */
1214 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1215 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1216 stream->decode = uvc_video_decode_isight;
1217 else if (stream->intf->num_altsetting > 1)
1218 stream->decode = uvc_video_decode_isoc;
1220 stream->decode = uvc_video_decode_bulk;
1222 if (stream->intf->num_altsetting == 1)
1223 stream->decode = uvc_video_encode_bulk;
1225 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1226 "supported for video output devices.\n");
1235 * Enable or disable the video stream.
1237 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1242 uvc_uninit_video(stream, 1);
1243 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1244 uvc_queue_enable(&stream->queue, 0);
1248 ret = uvc_queue_enable(&stream->queue, 1);
1252 /* Commit the streaming parameters. */
1253 ret = uvc_commit_video(stream, &stream->ctrl);
1257 return uvc_init_video(stream, GFP_KERNEL);