RT-AC66 3.0.0.4.374.130 core
[tomato.git] / release / src-rt-6.x / linux / linux-2.6 / drivers / media / video / uvc / uvc_video.c
blobe1b07b11aa769c90e0372d241aecbfe54a1b92e7
1 /*
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/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>
27 #include "uvcvideo.h"
29 /* ------------------------------------------------------------------------
30 * UVC Controls
33 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
34 __u8 intfnum, __u8 cs, void *data, __u16 size,
35 int timeout)
37 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
38 unsigned int pipe;
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)
51 int ret;
53 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
54 UVC_CTRL_CONTROL_TIMEOUT);
55 if (ret != size) {
56 uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
57 "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
58 size);
59 return -EIO;
62 return 0;
65 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
66 struct uvc_streaming_control *ctrl)
68 struct uvc_format *format = NULL;
69 struct uvc_frame *frame = NULL;
70 unsigned int i;
72 for (i = 0; i < stream->nformats; ++i) {
73 if (stream->format[i].index == ctrl->bFormatIndex) {
74 format = &stream->format[i];
75 break;
79 if (format == NULL)
80 return;
82 for (i = 0; i < format->nframes; ++i) {
83 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
84 frame = &format->frame[i];
85 break;
89 if (frame == NULL)
90 return;
92 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
93 (ctrl->dwMaxVideoFrameSize == 0 &&
94 stream->dev->uvc_version < 0x0110))
95 ctrl->dwMaxVideoFrameSize =
96 frame->dwMaxVideoFrameBufferSize;
98 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
99 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
100 stream->intf->num_altsetting > 1) {
101 u32 interval;
102 u32 bandwidth;
104 interval = (ctrl->dwFrameInterval > 100000)
105 ? ctrl->dwFrameInterval
106 : frame->dwFrameInterval[0];
108 /* Compute a bandwidth estimation by multiplying the frame
109 * size by the number of video frames per second, divide the
110 * result by the number of USB frames (or micro-frames for
111 * high-speed devices) per second and add the UVC header size
112 * (assumed to be 12 bytes long).
114 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
115 bandwidth *= 10000000 / interval + 1;
116 bandwidth /= 1000;
117 if (stream->dev->udev->speed == USB_SPEED_HIGH)
118 bandwidth /= 8;
119 bandwidth += 12;
121 ctrl->dwMaxPayloadTransferSize = bandwidth;
125 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
126 struct uvc_streaming_control *ctrl, int probe, __u8 query)
128 __u8 *data;
129 __u16 size;
130 int ret;
132 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
133 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
134 query == UVC_GET_DEF)
135 return -EIO;
137 data = kmalloc(size, GFP_KERNEL);
138 if (data == NULL)
139 return -ENOMEM;
141 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
142 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
143 size, uvc_timeout_param);
145 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
146 /* Some cameras, mostly based on Bison Electronics chipsets,
147 * answer a GET_MIN or GET_MAX request with the wCompQuality
148 * field only.
150 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
151 "compliance - GET_MIN/MAX(PROBE) incorrectly "
152 "supported. Enabling workaround.\n");
153 memset(ctrl, 0, sizeof *ctrl);
154 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
155 ret = 0;
156 goto out;
157 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
158 /* Many cameras don't support the GET_DEF request on their
159 * video probe control. Warn once and return, the caller will
160 * fall back to GET_CUR.
162 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
163 "compliance - GET_DEF(PROBE) not supported. "
164 "Enabling workaround.\n");
165 ret = -EIO;
166 goto out;
167 } else if (ret != size) {
168 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
169 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
170 ret, size);
171 ret = -EIO;
172 goto out;
175 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
176 ctrl->bFormatIndex = data[2];
177 ctrl->bFrameIndex = data[3];
178 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
179 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
180 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
181 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
182 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
183 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
184 ctrl->dwMaxVideoFrameSize = get_unaligned((u32 *)&(data[18]));
185 ctrl->dwMaxPayloadTransferSize = get_unaligned((u32 *)&(data[22]));
187 if (size == 34) {
188 ctrl->dwClockFrequency = get_unaligned((u32 *)&(data[26]));
189 ctrl->bmFramingInfo = data[30];
190 ctrl->bPreferedVersion = data[31];
191 ctrl->bMinVersion = data[32];
192 ctrl->bMaxVersion = data[33];
193 } else {
194 ctrl->dwClockFrequency = stream->dev->clock_frequency;
195 ctrl->bmFramingInfo = 0;
196 ctrl->bPreferedVersion = 0;
197 ctrl->bMinVersion = 0;
198 ctrl->bMaxVersion = 0;
201 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
202 * dwMaxPayloadTransferSize fields. Try to get the value from the
203 * format and frame descriptors.
205 uvc_fixup_video_ctrl(stream, ctrl);
206 ret = 0;
208 out:
209 kfree(data);
210 return ret;
213 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
214 struct uvc_streaming_control *ctrl, int probe)
216 __u8 *data;
217 __u16 size;
218 int ret;
220 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
221 data = kzalloc(size, GFP_KERNEL);
222 if (data == NULL)
223 return -ENOMEM;
225 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
226 data[2] = ctrl->bFormatIndex;
227 data[3] = ctrl->bFrameIndex;
228 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
229 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
230 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
231 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
232 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
233 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
234 put_unaligned(ctrl->dwMaxVideoFrameSize, (u32 *)&(data[18]));
235 put_unaligned(ctrl->dwMaxPayloadTransferSize, (u32 *)&(data[22]));
237 if (size == 34) {
238 put_unaligned(ctrl->dwClockFrequency, (u32 *)&(data[26]));
239 data[30] = ctrl->bmFramingInfo;
240 data[31] = ctrl->bPreferedVersion;
241 data[32] = ctrl->bMinVersion;
242 data[33] = ctrl->bMaxVersion;
245 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
246 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
247 size, uvc_timeout_param);
248 if (ret != size) {
249 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
250 "%d (exp. %u).\n", probe ? "probe" : "commit",
251 ret, size);
252 ret = -EIO;
255 kfree(data);
256 return ret;
259 int uvc_probe_video(struct uvc_streaming *stream,
260 struct uvc_streaming_control *probe)
262 struct uvc_streaming_control probe_min, probe_max;
263 __u16 bandwidth;
264 unsigned int i;
265 int ret;
267 mutex_lock(&stream->mutex);
269 /* Perform probing. The device should adjust the requested values
270 * according to its capabilities. However, some devices, namely the
271 * first generation UVC Logitech webcams, don't implement the Video
272 * Probe control properly, and just return the needed bandwidth. For
273 * that reason, if the needed bandwidth exceeds the maximum available
274 * bandwidth, try to lower the quality.
276 ret = uvc_set_video_ctrl(stream, probe, 1);
277 if (ret < 0)
278 goto done;
280 /* Get the minimum and maximum values for compression settings. */
281 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
282 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
283 if (ret < 0)
284 goto done;
285 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
286 if (ret < 0)
287 goto done;
289 probe->wCompQuality = probe_max.wCompQuality;
292 for (i = 0; i < 2; ++i) {
293 ret = uvc_set_video_ctrl(stream, probe, 1);
294 if (ret < 0)
295 goto done;
296 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
297 if (ret < 0)
298 goto done;
300 if (stream->intf->num_altsetting == 1)
301 break;
303 bandwidth = probe->dwMaxPayloadTransferSize;
304 if (bandwidth <= stream->maxpsize)
305 break;
307 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
308 ret = -ENOSPC;
309 goto done;
312 /* TODO: negotiate compression parameters */
313 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
314 probe->wPFrameRate = probe_min.wPFrameRate;
315 probe->wCompQuality = probe_max.wCompQuality;
316 probe->wCompWindowSize = probe_min.wCompWindowSize;
319 done:
320 mutex_unlock(&stream->mutex);
321 return ret;
324 int uvc_commit_video(struct uvc_streaming *stream,
325 struct uvc_streaming_control *probe)
327 return uvc_set_video_ctrl(stream, probe, 0);
330 /* ------------------------------------------------------------------------
331 * Video codecs
334 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
335 #define UVC_STREAM_EOH (1 << 7)
336 #define UVC_STREAM_ERR (1 << 6)
337 #define UVC_STREAM_STI (1 << 5)
338 #define UVC_STREAM_RES (1 << 4)
339 #define UVC_STREAM_SCR (1 << 3)
340 #define UVC_STREAM_PTS (1 << 2)
341 #define UVC_STREAM_EOF (1 << 1)
342 #define UVC_STREAM_FID (1 << 0)
344 /* Video payload decoding is handled by uvc_video_decode_start(),
345 * uvc_video_decode_data() and uvc_video_decode_end().
347 * uvc_video_decode_start is called with URB data at the start of a bulk or
348 * isochronous payload. It processes header data and returns the header size
349 * in bytes if successful. If an error occurs, it returns a negative error
350 * code. The following error codes have special meanings.
352 * - EAGAIN informs the caller that the current video buffer should be marked
353 * as done, and that the function should be called again with the same data
354 * and a new video buffer. This is used when end of frame conditions can be
355 * reliably detected at the beginning of the next frame only.
357 * If an error other than -EAGAIN is returned, the caller will drop the current
358 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
359 * made until the next payload. -ENODATA can be used to drop the current
360 * payload if no other error code is appropriate.
362 * uvc_video_decode_data is called for every URB with URB data. It copies the
363 * data to the video buffer.
365 * uvc_video_decode_end is called with header data at the end of a bulk or
366 * isochronous payload. It performs any additional header data processing and
367 * returns 0 or a negative error code if an error occured. As header data have
368 * already been processed by uvc_video_decode_start, this functions isn't
369 * required to perform sanity checks a second time.
371 * For isochronous transfers where a payload is always transfered in a single
372 * URB, the three functions will be called in a row.
374 * To let the decoder process header data and update its internal state even
375 * when no video buffer is available, uvc_video_decode_start must be prepared
376 * to be called with a NULL buf parameter. uvc_video_decode_data and
377 * uvc_video_decode_end will never be called with a NULL buffer.
379 static int uvc_video_decode_start(struct uvc_streaming *stream,
380 struct uvc_buffer *buf, const __u8 *data, int len)
382 __u8 fid;
384 /* Sanity checks:
385 * - packet must be at least 2 bytes long
386 * - bHeaderLength value must be at least 2 bytes (see above)
387 * - bHeaderLength value can't be larger than the packet size.
389 if (len < 2 || data[0] < 2 || data[0] > len)
390 return -EINVAL;
392 /* Skip payloads marked with the error bit ("error frames"). */
393 if (data[1] & UVC_STREAM_ERR) {
394 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
395 "set).\n");
396 return -ENODATA;
399 fid = data[1] & UVC_STREAM_FID;
401 /* Store the payload FID bit and return immediately when the buffer is
402 * NULL.
404 if (buf == NULL) {
405 stream->last_fid = fid;
406 return -ENODATA;
409 /* Synchronize to the input stream by waiting for the FID bit to be
410 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
411 * stream->last_fid is initialized to -1, so the first isochronous
412 * frame will always be in sync.
414 * If the device doesn't toggle the FID bit, invert stream->last_fid
415 * when the EOF bit is set to force synchronisation on the next packet.
417 if (buf->state != UVC_BUF_STATE_ACTIVE) {
418 struct timespec ts;
420 if (fid == stream->last_fid) {
421 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
422 "sync).\n");
423 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
424 (data[1] & UVC_STREAM_EOF))
425 stream->last_fid ^= UVC_STREAM_FID;
426 return -ENODATA;
429 if (uvc_clock_param == CLOCK_MONOTONIC)
430 ktime_get_ts(&ts);
431 else
432 ktime_get_real_ts(&ts);
434 buf->buf.timestamp.tv_sec = ts.tv_sec;
435 buf->buf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
437 /* TODO: Handle PTS and SCR. */
438 buf->state = UVC_BUF_STATE_ACTIVE;
441 /* Mark the buffer as done if we're at the beginning of a new frame.
442 * End of frame detection is better implemented by checking the EOF
443 * bit (FID bit toggling is delayed by one frame compared to the EOF
444 * bit), but some devices don't set the bit at end of frame (and the
445 * last payload can be lost anyway). We thus must check if the FID has
446 * been toggled.
448 * stream->last_fid is initialized to -1, so the first isochronous
449 * frame will never trigger an end of frame detection.
451 * Empty buffers (bytesused == 0) don't trigger end of frame detection
452 * as it doesn't make sense to return an empty buffer. This also
453 * avoids detecting end of frame conditions at FID toggling if the
454 * previous payload had the EOF bit set.
456 if (fid != stream->last_fid && buf->buf.bytesused != 0) {
457 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
458 "toggled).\n");
459 buf->state = UVC_BUF_STATE_READY;
460 return -EAGAIN;
463 stream->last_fid = fid;
465 return data[0];
468 static void uvc_video_decode_data(struct uvc_streaming *stream,
469 struct uvc_buffer *buf, const __u8 *data, int len)
471 struct uvc_video_queue *queue = &stream->queue;
472 unsigned int maxlen, nbytes;
473 void *mem;
475 if (len <= 0)
476 return;
478 /* Copy the video data to the buffer. */
479 maxlen = buf->buf.length - buf->buf.bytesused;
480 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
481 nbytes = min((unsigned int)len, maxlen);
482 memcpy(mem, data, nbytes);
483 buf->buf.bytesused += nbytes;
485 /* Complete the current frame if the buffer size was exceeded. */
486 if (len > maxlen) {
487 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
488 buf->state = UVC_BUF_STATE_READY;
492 static void uvc_video_decode_end(struct uvc_streaming *stream,
493 struct uvc_buffer *buf, const __u8 *data, int len)
495 /* Mark the buffer as done if the EOF marker is set. */
496 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
497 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
498 if (data[0] == len)
499 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
500 buf->state = UVC_BUF_STATE_READY;
501 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
502 stream->last_fid ^= UVC_STREAM_FID;
506 /* Video payload encoding is handled by uvc_video_encode_header() and
507 * uvc_video_encode_data(). Only bulk transfers are currently supported.
509 * uvc_video_encode_header is called at the start of a payload. It adds header
510 * data to the transfer buffer and returns the header size. As the only known
511 * UVC output device transfers a whole frame in a single payload, the EOF bit
512 * is always set in the header.
514 * uvc_video_encode_data is called for every URB and copies the data from the
515 * video buffer to the transfer buffer.
517 static int uvc_video_encode_header(struct uvc_streaming *stream,
518 struct uvc_buffer *buf, __u8 *data, int len)
520 data[0] = 2; /* Header length */
521 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
522 | (stream->last_fid & UVC_STREAM_FID);
523 return 2;
526 static int uvc_video_encode_data(struct uvc_streaming *stream,
527 struct uvc_buffer *buf, __u8 *data, int len)
529 struct uvc_video_queue *queue = &stream->queue;
530 unsigned int nbytes;
531 void *mem;
533 /* Copy video data to the URB buffer. */
534 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
535 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
536 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
537 nbytes);
538 memcpy(data, mem, nbytes);
540 queue->buf_used += nbytes;
542 return nbytes;
545 /* ------------------------------------------------------------------------
546 * URB handling
550 * Completion handler for video URBs.
552 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
553 struct uvc_buffer *buf)
555 u8 *mem;
556 int ret, i;
558 for (i = 0; i < urb->number_of_packets; ++i) {
559 if (urb->iso_frame_desc[i].status < 0) {
560 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
561 "lost (%d).\n", urb->iso_frame_desc[i].status);
562 /* Mark the buffer as faulty. */
563 if (buf != NULL)
564 buf->error = 1;
565 continue;
568 /* Decode the payload header. */
569 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
570 do {
571 ret = uvc_video_decode_start(stream, buf, mem,
572 urb->iso_frame_desc[i].actual_length);
573 if (ret == -EAGAIN)
574 buf = uvc_queue_next_buffer(&stream->queue,
575 buf);
576 } while (ret == -EAGAIN);
578 if (ret < 0)
579 continue;
581 /* Decode the payload data. */
582 uvc_video_decode_data(stream, buf, mem + ret,
583 urb->iso_frame_desc[i].actual_length - ret);
585 /* Process the header again. */
586 uvc_video_decode_end(stream, buf, mem,
587 urb->iso_frame_desc[i].actual_length);
589 if (buf->state == UVC_BUF_STATE_READY) {
590 if (buf->buf.length != buf->buf.bytesused &&
591 !(stream->cur_format->flags &
592 UVC_FMT_FLAG_COMPRESSED))
593 buf->error = 1;
595 buf = uvc_queue_next_buffer(&stream->queue, buf);
600 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
601 struct uvc_buffer *buf)
603 u8 *mem;
604 int len, ret;
606 if (urb->actual_length == 0)
607 return;
609 mem = urb->transfer_buffer;
610 len = urb->actual_length;
611 stream->bulk.payload_size += len;
613 /* If the URB is the first of its payload, decode and save the
614 * header.
616 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
617 do {
618 ret = uvc_video_decode_start(stream, buf, mem, len);
619 if (ret == -EAGAIN)
620 buf = uvc_queue_next_buffer(&stream->queue,
621 buf);
622 } while (ret == -EAGAIN);
624 /* If an error occured skip the rest of the payload. */
625 if (ret < 0 || buf == NULL) {
626 stream->bulk.skip_payload = 1;
627 } else {
628 memcpy(stream->bulk.header, mem, ret);
629 stream->bulk.header_size = ret;
631 mem += ret;
632 len -= ret;
636 /* The buffer queue might have been cancelled while a bulk transfer
637 * was in progress, so we can reach here with buf equal to NULL. Make
638 * sure buf is never dereferenced if NULL.
641 /* Process video data. */
642 if (!stream->bulk.skip_payload && buf != NULL)
643 uvc_video_decode_data(stream, buf, mem, len);
645 /* Detect the payload end by a URB smaller than the maximum size (or
646 * a payload size equal to the maximum) and process the header again.
648 if (urb->actual_length < urb->transfer_buffer_length ||
649 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
650 if (!stream->bulk.skip_payload && buf != NULL) {
651 uvc_video_decode_end(stream, buf, stream->bulk.header,
652 stream->bulk.payload_size);
653 if (buf->state == UVC_BUF_STATE_READY)
654 buf = uvc_queue_next_buffer(&stream->queue,
655 buf);
658 stream->bulk.header_size = 0;
659 stream->bulk.skip_payload = 0;
660 stream->bulk.payload_size = 0;
664 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
665 struct uvc_buffer *buf)
667 u8 *mem = urb->transfer_buffer;
668 int len = stream->urb_size, ret;
670 if (buf == NULL) {
671 urb->transfer_buffer_length = 0;
672 return;
675 /* If the URB is the first of its payload, add the header. */
676 if (stream->bulk.header_size == 0) {
677 ret = uvc_video_encode_header(stream, buf, mem, len);
678 stream->bulk.header_size = ret;
679 stream->bulk.payload_size += ret;
680 mem += ret;
681 len -= ret;
684 /* Process video data. */
685 ret = uvc_video_encode_data(stream, buf, mem, len);
687 stream->bulk.payload_size += ret;
688 len -= ret;
690 if (buf->buf.bytesused == stream->queue.buf_used ||
691 stream->bulk.payload_size == stream->bulk.max_payload_size) {
692 if (buf->buf.bytesused == stream->queue.buf_used) {
693 stream->queue.buf_used = 0;
694 buf->state = UVC_BUF_STATE_READY;
695 uvc_queue_next_buffer(&stream->queue, buf);
696 stream->last_fid ^= UVC_STREAM_FID;
699 stream->bulk.header_size = 0;
700 stream->bulk.payload_size = 0;
703 urb->transfer_buffer_length = stream->urb_size - len;
706 static void uvc_video_complete(struct urb *urb)
708 struct uvc_streaming *stream = urb->context;
709 struct uvc_video_queue *queue = &stream->queue;
710 struct uvc_buffer *buf = NULL;
711 unsigned long flags;
712 int ret;
714 switch (urb->status) {
715 case 0:
716 break;
718 default:
719 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
720 "completion handler.\n", urb->status);
722 case -ENOENT: /* usb_kill_urb() called. */
723 if (stream->frozen)
724 return;
726 case -ECONNRESET: /* usb_unlink_urb() called. */
727 case -ESHUTDOWN: /* The endpoint is being disabled. */
728 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
729 return;
732 spin_lock_irqsave(&queue->irqlock, flags);
733 if (!list_empty(&queue->irqqueue))
734 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
735 queue);
736 spin_unlock_irqrestore(&queue->irqlock, flags);
738 stream->decode(urb, stream, buf);
740 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
741 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
742 ret);
747 * Free transfer buffers.
749 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
751 unsigned int i;
753 for (i = 0; i < UVC_URBS; ++i) {
754 if (stream->urb_buffer[i]) {
755 usb_buffer_free(stream->dev->udev, stream->urb_size,
756 stream->urb_buffer[i], stream->urb_dma[i]);
757 stream->urb_buffer[i] = NULL;
761 stream->urb_size = 0;
765 * Allocate transfer buffers. This function can be called with buffers
766 * already allocated when resuming from suspend, in which case it will
767 * return without touching the buffers.
769 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
770 * system is too low on memory try successively smaller numbers of packets
771 * until allocation succeeds.
773 * Return the number of allocated packets on success or 0 when out of memory.
775 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
776 unsigned int size, unsigned int psize, gfp_t gfp_flags)
778 unsigned int npackets;
779 unsigned int i;
781 /* Buffers are already allocated, bail out. */
782 if (stream->urb_size)
783 return stream->urb_size / psize;
785 /* Compute the number of packets. Bulk endpoints might transfer UVC
786 * payloads accross multiple URBs.
788 npackets = DIV_ROUND_UP(size, psize);
789 if (npackets > UVC_MAX_PACKETS)
790 npackets = UVC_MAX_PACKETS;
792 /* Retry allocations until one succeed. */
793 for (; npackets > 1; npackets /= 2) {
794 for (i = 0; i < UVC_URBS; ++i) {
795 stream->urb_size = psize * npackets;
796 stream->urb_buffer[i] = usb_buffer_alloc(
797 stream->dev->udev, stream->urb_size,
798 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
799 if (!stream->urb_buffer[i]) {
800 uvc_free_urb_buffers(stream);
801 break;
805 if (i == UVC_URBS) {
806 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
807 "of %ux%u bytes each.\n", UVC_URBS, npackets,
808 psize);
809 return npackets;
813 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
814 "per packet).\n", psize);
815 return 0;
819 * Uninitialize isochronous/bulk URBs and free transfer buffers.
821 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
823 struct urb *urb;
824 unsigned int i;
826 for (i = 0; i < UVC_URBS; ++i) {
827 urb = stream->urb[i];
828 if (urb == NULL)
829 continue;
831 usb_kill_urb(urb);
832 usb_free_urb(urb);
833 stream->urb[i] = NULL;
836 if (free_buffers)
837 uvc_free_urb_buffers(stream);
841 * Initialize isochronous URBs and allocate transfer buffers. The packet size
842 * is given by the endpoint.
844 static int uvc_init_video_isoc(struct uvc_streaming *stream,
845 struct usb_host_endpoint *ep, gfp_t gfp_flags)
847 struct urb *urb;
848 unsigned int npackets, i, j;
849 u16 psize;
850 u32 size;
852 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
853 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
854 size = stream->ctrl.dwMaxVideoFrameSize;
856 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
857 if (npackets == 0)
858 return -ENOMEM;
860 size = npackets * psize;
862 for (i = 0; i < UVC_URBS; ++i) {
863 urb = usb_alloc_urb(npackets, gfp_flags);
864 if (urb == NULL) {
865 uvc_uninit_video(stream, 1);
866 return -ENOMEM;
869 urb->dev = stream->dev->udev;
870 urb->context = stream;
871 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
872 ep->desc.bEndpointAddress);
873 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
874 urb->interval = ep->desc.bInterval;
875 urb->transfer_buffer = stream->urb_buffer[i];
876 urb->transfer_dma = stream->urb_dma[i];
877 urb->complete = uvc_video_complete;
878 urb->number_of_packets = npackets;
879 urb->transfer_buffer_length = size;
881 for (j = 0; j < npackets; ++j) {
882 urb->iso_frame_desc[j].offset = j * psize;
883 urb->iso_frame_desc[j].length = psize;
886 stream->urb[i] = urb;
889 return 0;
893 * Initialize bulk URBs and allocate transfer buffers. The packet size is
894 * given by the endpoint.
896 static int uvc_init_video_bulk(struct uvc_streaming *stream,
897 struct usb_host_endpoint *ep, gfp_t gfp_flags)
899 struct urb *urb;
900 unsigned int npackets, pipe, i;
901 u16 psize;
902 u32 size;
904 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
905 size = stream->ctrl.dwMaxPayloadTransferSize;
906 stream->bulk.max_payload_size = size;
908 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
909 if (npackets == 0)
910 return -ENOMEM;
912 size = npackets * psize;
914 if (usb_endpoint_dir_in(&ep->desc))
915 pipe = usb_rcvbulkpipe(stream->dev->udev,
916 ep->desc.bEndpointAddress);
917 else
918 pipe = usb_sndbulkpipe(stream->dev->udev,
919 ep->desc.bEndpointAddress);
921 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
922 size = 0;
924 for (i = 0; i < UVC_URBS; ++i) {
925 urb = usb_alloc_urb(0, gfp_flags);
926 if (urb == NULL) {
927 uvc_uninit_video(stream, 1);
928 return -ENOMEM;
931 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
932 stream->urb_buffer[i], size, uvc_video_complete,
933 stream);
934 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
935 urb->transfer_dma = stream->urb_dma[i];
937 stream->urb[i] = urb;
940 return 0;
944 * Initialize isochronous/bulk URBs and allocate transfer buffers.
946 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
948 struct usb_interface *intf = stream->intf;
949 struct usb_host_endpoint *ep;
950 unsigned int i;
951 int ret;
953 stream->last_fid = -1;
954 stream->bulk.header_size = 0;
955 stream->bulk.skip_payload = 0;
956 stream->bulk.payload_size = 0;
958 if (intf->num_altsetting > 1) {
959 struct usb_host_endpoint *best_ep = NULL;
960 unsigned int best_psize = 3 * 1024;
961 unsigned int bandwidth;
962 unsigned int uninitialized_var(altsetting);
963 int intfnum = stream->intfnum;
965 /* Isochronous endpoint, select the alternate setting. */
966 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
968 if (bandwidth == 0) {
969 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
970 "bandwidth, defaulting to lowest.\n");
971 bandwidth = 1;
972 } else {
973 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
974 "B/frame bandwidth.\n", bandwidth);
977 for (i = 0; i < intf->num_altsetting; ++i) {
978 struct usb_host_interface *alts;
979 unsigned int psize;
981 alts = &intf->altsetting[i];
982 ep = uvc_find_endpoint(alts,
983 stream->header.bEndpointAddress);
984 if (ep == NULL)
985 continue;
987 /* Check if the bandwidth is high enough. */
988 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
989 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
990 if (psize >= bandwidth && psize <= best_psize) {
991 altsetting = i;
992 best_psize = psize;
993 best_ep = ep;
997 if (best_ep == NULL) {
998 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
999 "for requested bandwidth.\n");
1000 return -EIO;
1003 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1004 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1006 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1007 if (ret < 0)
1008 return ret;
1010 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1011 } else {
1012 /* Bulk endpoint, proceed to URB initialization. */
1013 ep = uvc_find_endpoint(&intf->altsetting[0],
1014 stream->header.bEndpointAddress);
1015 if (ep == NULL)
1016 return -EIO;
1018 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1021 if (ret < 0)
1022 return ret;
1024 /* Submit the URBs. */
1025 for (i = 0; i < UVC_URBS; ++i) {
1026 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1027 if (ret < 0) {
1028 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1029 "(%d).\n", i, ret);
1030 uvc_uninit_video(stream, 1);
1031 return ret;
1035 return 0;
1038 /* --------------------------------------------------------------------------
1039 * Suspend/resume
1043 * Stop streaming without disabling the video queue.
1045 * To let userspace applications resume without trouble, we must not touch the
1046 * video buffers in any way. We mark the device as frozen to make sure the URB
1047 * completion handler won't try to cancel the queue when we kill the URBs.
1049 int uvc_video_suspend(struct uvc_streaming *stream)
1051 if (!uvc_queue_streaming(&stream->queue))
1052 return 0;
1054 stream->frozen = 1;
1055 uvc_uninit_video(stream, 0);
1056 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1057 return 0;
1061 * Reconfigure the video interface and restart streaming if it was enabled
1062 * before suspend.
1064 * If an error occurs, disable the video queue. This will wake all pending
1065 * buffers, making sure userspace applications are notified of the problem
1066 * instead of waiting forever.
1068 int uvc_video_resume(struct uvc_streaming *stream)
1070 int ret;
1072 stream->frozen = 0;
1074 ret = uvc_commit_video(stream, &stream->ctrl);
1075 if (ret < 0) {
1076 uvc_queue_enable(&stream->queue, 0);
1077 return ret;
1080 if (!uvc_queue_streaming(&stream->queue))
1081 return 0;
1083 ret = uvc_init_video(stream, GFP_NOIO);
1084 if (ret < 0)
1085 uvc_queue_enable(&stream->queue, 0);
1087 return ret;
1090 /* ------------------------------------------------------------------------
1091 * Video device
1095 * Initialize the UVC video device by switching to alternate setting 0 and
1096 * retrieve the default format.
1098 * Some cameras (namely the Fuji Finepix) set the format and frame
1099 * indexes to zero. The UVC standard doesn't clearly make this a spec
1100 * violation, so try to silently fix the values if possible.
1102 * This function is called before registering the device with V4L.
1104 int uvc_video_init(struct uvc_streaming *stream)
1106 struct uvc_streaming_control *probe = &stream->ctrl;
1107 struct uvc_format *format = NULL;
1108 struct uvc_frame *frame = NULL;
1109 unsigned int i;
1110 int ret;
1112 if (stream->nformats == 0) {
1113 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1114 return -EINVAL;
1117 atomic_set(&stream->active, 0);
1119 /* Initialize the video buffers queue. */
1120 uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1122 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1123 * Cam (and possibly other devices) crash or otherwise misbehave if
1124 * they don't receive a SET_INTERFACE request before any other video
1125 * control request.
1127 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1129 /* Set the streaming probe control with default streaming parameters
1130 * retrieved from the device. Webcams that don't suport GET_DEF
1131 * requests on the probe control will just keep their current streaming
1132 * parameters.
1134 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1135 uvc_set_video_ctrl(stream, probe, 1);
1137 /* Initialize the streaming parameters with the probe control current
1138 * value. This makes sure SET_CUR requests on the streaming commit
1139 * control will always use values retrieved from a successful GET_CUR
1140 * request on the probe control, as required by the UVC specification.
1142 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1143 if (ret < 0)
1144 return ret;
1146 /* Check if the default format descriptor exists. Use the first
1147 * available format otherwise.
1149 for (i = stream->nformats; i > 0; --i) {
1150 format = &stream->format[i-1];
1151 if (format->index == probe->bFormatIndex)
1152 break;
1155 if (format->nframes == 0) {
1156 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1157 "default format.\n");
1158 return -EINVAL;
1161 /* Zero bFrameIndex might be correct. Stream-based formats (including
1162 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1163 * descriptor with bFrameIndex set to zero. If the default frame
1164 * descriptor is not found, use the first available frame.
1166 for (i = format->nframes; i > 0; --i) {
1167 frame = &format->frame[i-1];
1168 if (frame->bFrameIndex == probe->bFrameIndex)
1169 break;
1172 probe->bFormatIndex = format->index;
1173 probe->bFrameIndex = frame->bFrameIndex;
1175 stream->cur_format = format;
1176 stream->cur_frame = frame;
1178 /* Select the video decoding function */
1179 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1180 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1181 stream->decode = uvc_video_decode_isight;
1182 else if (stream->intf->num_altsetting > 1)
1183 stream->decode = uvc_video_decode_isoc;
1184 else
1185 stream->decode = uvc_video_decode_bulk;
1186 } else {
1187 if (stream->intf->num_altsetting == 1)
1188 stream->decode = uvc_video_encode_bulk;
1189 else {
1190 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1191 "supported for video output devices.\n");
1192 return -EINVAL;
1196 return 0;
1200 * Enable or disable the video stream.
1202 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1204 int ret;
1206 if (!enable) {
1207 uvc_uninit_video(stream, 1);
1208 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1209 uvc_queue_enable(&stream->queue, 0);
1210 return 0;
1213 ret = uvc_queue_enable(&stream->queue, 1);
1214 if (ret < 0)
1215 return ret;
1217 /* Commit the streaming parameters. */
1218 ret = uvc_commit_video(stream, &stream->ctrl);
1219 if (ret < 0)
1220 return ret;
1222 return uvc_init_video(stream, GFP_KERNEL);