uvcvideo: Fix uvc_fixup_video_ctrl() format search
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / drivers / media / video / uvc / uvc_video.c
blob253eed80c0a89f19f4283d2346aa7c6e0e39b6ed
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/usb.h>
18 #include <linux/videodev2.h>
19 #include <linux/vmalloc.h>
20 #include <linux/wait.h>
21 #include <asm/atomic.h>
22 #include <asm/unaligned.h>
24 #include <media/v4l2-common.h>
26 #include "uvcvideo.h"
28 /* ------------------------------------------------------------------------
29 * UVC Controls
32 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
33 __u8 intfnum, __u8 cs, void *data, __u16 size,
34 int timeout)
36 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
37 unsigned int pipe;
39 pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
40 : usb_sndctrlpipe(dev->udev, 0);
41 type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
43 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
44 unit << 8 | intfnum, data, size, timeout);
47 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
48 __u8 intfnum, __u8 cs, void *data, __u16 size)
50 int ret;
52 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
53 UVC_CTRL_CONTROL_TIMEOUT);
54 if (ret != size) {
55 uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
56 "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
57 size);
58 return -EIO;
61 return 0;
64 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
65 struct uvc_streaming_control *ctrl)
67 struct uvc_format *format = NULL;
68 struct uvc_frame *frame = NULL;
69 unsigned int i;
71 for (i = 0; i < stream->nformats; ++i) {
72 if (stream->format[i].index == ctrl->bFormatIndex) {
73 format = &stream->format[i];
74 break;
78 if (format == NULL)
79 return;
81 for (i = 0; i < format->nframes; ++i) {
82 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
83 frame = &format->frame[i];
84 break;
88 if (frame == NULL)
89 return;
91 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
92 (ctrl->dwMaxVideoFrameSize == 0 &&
93 stream->dev->uvc_version < 0x0110))
94 ctrl->dwMaxVideoFrameSize =
95 frame->dwMaxVideoFrameBufferSize;
97 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
98 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
99 stream->intf->num_altsetting > 1) {
100 u32 interval;
101 u32 bandwidth;
103 interval = (ctrl->dwFrameInterval > 100000)
104 ? ctrl->dwFrameInterval
105 : frame->dwFrameInterval[0];
107 /* Compute a bandwidth estimation by multiplying the frame
108 * size by the number of video frames per second, divide the
109 * result by the number of USB frames (or micro-frames for
110 * high-speed devices) per second and add the UVC header size
111 * (assumed to be 12 bytes long).
113 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
114 bandwidth *= 10000000 / interval + 1;
115 bandwidth /= 1000;
116 if (stream->dev->udev->speed == USB_SPEED_HIGH)
117 bandwidth /= 8;
118 bandwidth += 12;
120 ctrl->dwMaxPayloadTransferSize = bandwidth;
124 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
125 struct uvc_streaming_control *ctrl, int probe, __u8 query)
127 __u8 *data;
128 __u16 size;
129 int ret;
131 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
132 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
133 query == UVC_GET_DEF)
134 return -EIO;
136 data = kmalloc(size, GFP_KERNEL);
137 if (data == NULL)
138 return -ENOMEM;
140 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
141 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
142 size, uvc_timeout_param);
144 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
145 /* Some cameras, mostly based on Bison Electronics chipsets,
146 * answer a GET_MIN or GET_MAX request with the wCompQuality
147 * field only.
149 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
150 "compliance - GET_MIN/MAX(PROBE) incorrectly "
151 "supported. Enabling workaround.\n");
152 memset(ctrl, 0, sizeof *ctrl);
153 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
154 ret = 0;
155 goto out;
156 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
157 /* Many cameras don't support the GET_DEF request on their
158 * video probe control. Warn once and return, the caller will
159 * fall back to GET_CUR.
161 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
162 "compliance - GET_DEF(PROBE) not supported. "
163 "Enabling workaround.\n");
164 ret = -EIO;
165 goto out;
166 } else if (ret != size) {
167 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
168 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
169 ret, size);
170 ret = -EIO;
171 goto out;
174 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
175 ctrl->bFormatIndex = data[2];
176 ctrl->bFrameIndex = data[3];
177 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
178 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
179 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
180 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
181 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
182 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
183 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
184 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
186 if (size == 34) {
187 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
188 ctrl->bmFramingInfo = data[30];
189 ctrl->bPreferedVersion = data[31];
190 ctrl->bMinVersion = data[32];
191 ctrl->bMaxVersion = data[33];
192 } else {
193 ctrl->dwClockFrequency = stream->dev->clock_frequency;
194 ctrl->bmFramingInfo = 0;
195 ctrl->bPreferedVersion = 0;
196 ctrl->bMinVersion = 0;
197 ctrl->bMaxVersion = 0;
200 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
201 * dwMaxPayloadTransferSize fields. Try to get the value from the
202 * format and frame descriptors.
204 uvc_fixup_video_ctrl(stream, ctrl);
205 ret = 0;
207 out:
208 kfree(data);
209 return ret;
212 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
213 struct uvc_streaming_control *ctrl, int probe)
215 __u8 *data;
216 __u16 size;
217 int ret;
219 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
220 data = kzalloc(size, GFP_KERNEL);
221 if (data == NULL)
222 return -ENOMEM;
224 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
225 data[2] = ctrl->bFormatIndex;
226 data[3] = ctrl->bFrameIndex;
227 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
228 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
229 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
230 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
231 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
232 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
233 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
234 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
236 if (size == 34) {
237 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
238 data[30] = ctrl->bmFramingInfo;
239 data[31] = ctrl->bPreferedVersion;
240 data[32] = ctrl->bMinVersion;
241 data[33] = ctrl->bMaxVersion;
244 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
245 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
246 size, uvc_timeout_param);
247 if (ret != size) {
248 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
249 "%d (exp. %u).\n", probe ? "probe" : "commit",
250 ret, size);
251 ret = -EIO;
254 kfree(data);
255 return ret;
258 int uvc_probe_video(struct uvc_streaming *stream,
259 struct uvc_streaming_control *probe)
261 struct uvc_streaming_control probe_min, probe_max;
262 __u16 bandwidth;
263 unsigned int i;
264 int ret;
266 mutex_lock(&stream->mutex);
268 /* Perform probing. The device should adjust the requested values
269 * according to its capabilities. However, some devices, namely the
270 * first generation UVC Logitech webcams, don't implement the Video
271 * Probe control properly, and just return the needed bandwidth. For
272 * that reason, if the needed bandwidth exceeds the maximum available
273 * bandwidth, try to lower the quality.
275 ret = uvc_set_video_ctrl(stream, probe, 1);
276 if (ret < 0)
277 goto done;
279 /* Get the minimum and maximum values for compression settings. */
280 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
281 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
282 if (ret < 0)
283 goto done;
284 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
285 if (ret < 0)
286 goto done;
288 probe->wCompQuality = probe_max.wCompQuality;
291 for (i = 0; i < 2; ++i) {
292 ret = uvc_set_video_ctrl(stream, probe, 1);
293 if (ret < 0)
294 goto done;
295 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
296 if (ret < 0)
297 goto done;
299 if (stream->intf->num_altsetting == 1)
300 break;
302 bandwidth = probe->dwMaxPayloadTransferSize;
303 if (bandwidth <= stream->maxpsize)
304 break;
306 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
307 ret = -ENOSPC;
308 goto done;
311 /* TODO: negotiate compression parameters */
312 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
313 probe->wPFrameRate = probe_min.wPFrameRate;
314 probe->wCompQuality = probe_max.wCompQuality;
315 probe->wCompWindowSize = probe_min.wCompWindowSize;
318 done:
319 mutex_unlock(&stream->mutex);
320 return ret;
323 int uvc_commit_video(struct uvc_streaming *stream,
324 struct uvc_streaming_control *probe)
326 return uvc_set_video_ctrl(stream, probe, 0);
329 /* ------------------------------------------------------------------------
330 * Video codecs
333 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
334 #define UVC_STREAM_EOH (1 << 7)
335 #define UVC_STREAM_ERR (1 << 6)
336 #define UVC_STREAM_STI (1 << 5)
337 #define UVC_STREAM_RES (1 << 4)
338 #define UVC_STREAM_SCR (1 << 3)
339 #define UVC_STREAM_PTS (1 << 2)
340 #define UVC_STREAM_EOF (1 << 1)
341 #define UVC_STREAM_FID (1 << 0)
343 /* Video payload decoding is handled by uvc_video_decode_start(),
344 * uvc_video_decode_data() and uvc_video_decode_end().
346 * uvc_video_decode_start is called with URB data at the start of a bulk or
347 * isochronous payload. It processes header data and returns the header size
348 * in bytes if successful. If an error occurs, it returns a negative error
349 * code. The following error codes have special meanings.
351 * - EAGAIN informs the caller that the current video buffer should be marked
352 * as done, and that the function should be called again with the same data
353 * and a new video buffer. This is used when end of frame conditions can be
354 * reliably detected at the beginning of the next frame only.
356 * If an error other than -EAGAIN is returned, the caller will drop the current
357 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
358 * made until the next payload. -ENODATA can be used to drop the current
359 * payload if no other error code is appropriate.
361 * uvc_video_decode_data is called for every URB with URB data. It copies the
362 * data to the video buffer.
364 * uvc_video_decode_end is called with header data at the end of a bulk or
365 * isochronous payload. It performs any additional header data processing and
366 * returns 0 or a negative error code if an error occured. As header data have
367 * already been processed by uvc_video_decode_start, this functions isn't
368 * required to perform sanity checks a second time.
370 * For isochronous transfers where a payload is always transfered in a single
371 * URB, the three functions will be called in a row.
373 * To let the decoder process header data and update its internal state even
374 * when no video buffer is available, uvc_video_decode_start must be prepared
375 * to be called with a NULL buf parameter. uvc_video_decode_data and
376 * uvc_video_decode_end will never be called with a NULL buffer.
378 static int uvc_video_decode_start(struct uvc_streaming *stream,
379 struct uvc_buffer *buf, const __u8 *data, int len)
381 __u8 fid;
383 /* Sanity checks:
384 * - packet must be at least 2 bytes long
385 * - bHeaderLength value must be at least 2 bytes (see above)
386 * - bHeaderLength value can't be larger than the packet size.
388 if (len < 2 || data[0] < 2 || data[0] > len)
389 return -EINVAL;
391 /* Skip payloads marked with the error bit ("error frames"). */
392 if (data[1] & UVC_STREAM_ERR) {
393 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
394 "set).\n");
395 return -ENODATA;
398 fid = data[1] & UVC_STREAM_FID;
400 /* Store the payload FID bit and return immediately when the buffer is
401 * NULL.
403 if (buf == NULL) {
404 stream->last_fid = fid;
405 return -ENODATA;
408 /* Synchronize to the input stream by waiting for the FID bit to be
409 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
410 * stream->last_fid is initialized to -1, so the first isochronous
411 * frame will always be in sync.
413 * If the device doesn't toggle the FID bit, invert stream->last_fid
414 * when the EOF bit is set to force synchronisation on the next packet.
416 if (buf->state != UVC_BUF_STATE_ACTIVE) {
417 if (fid == stream->last_fid) {
418 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
419 "sync).\n");
420 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
421 (data[1] & UVC_STREAM_EOF))
422 stream->last_fid ^= UVC_STREAM_FID;
423 return -ENODATA;
426 /* TODO: Handle PTS and SCR. */
427 buf->state = UVC_BUF_STATE_ACTIVE;
430 /* Mark the buffer as done if we're at the beginning of a new frame.
431 * End of frame detection is better implemented by checking the EOF
432 * bit (FID bit toggling is delayed by one frame compared to the EOF
433 * bit), but some devices don't set the bit at end of frame (and the
434 * last payload can be lost anyway). We thus must check if the FID has
435 * been toggled.
437 * stream->last_fid is initialized to -1, so the first isochronous
438 * frame will never trigger an end of frame detection.
440 * Empty buffers (bytesused == 0) don't trigger end of frame detection
441 * as it doesn't make sense to return an empty buffer. This also
442 * avoids detecting end of frame conditions at FID toggling if the
443 * previous payload had the EOF bit set.
445 if (fid != stream->last_fid && buf->buf.bytesused != 0) {
446 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
447 "toggled).\n");
448 buf->state = UVC_BUF_STATE_READY;
449 return -EAGAIN;
452 stream->last_fid = fid;
454 return data[0];
457 static void uvc_video_decode_data(struct uvc_streaming *stream,
458 struct uvc_buffer *buf, const __u8 *data, int len)
460 struct uvc_video_queue *queue = &stream->queue;
461 unsigned int maxlen, nbytes;
462 void *mem;
464 if (len <= 0)
465 return;
467 /* Copy the video data to the buffer. */
468 maxlen = buf->buf.length - buf->buf.bytesused;
469 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
470 nbytes = min((unsigned int)len, maxlen);
471 memcpy(mem, data, nbytes);
472 buf->buf.bytesused += nbytes;
474 /* Complete the current frame if the buffer size was exceeded. */
475 if (len > maxlen) {
476 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
477 buf->state = UVC_BUF_STATE_READY;
481 static void uvc_video_decode_end(struct uvc_streaming *stream,
482 struct uvc_buffer *buf, const __u8 *data, int len)
484 /* Mark the buffer as done if the EOF marker is set. */
485 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
486 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
487 if (data[0] == len)
488 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
489 buf->state = UVC_BUF_STATE_READY;
490 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
491 stream->last_fid ^= UVC_STREAM_FID;
495 /* Video payload encoding is handled by uvc_video_encode_header() and
496 * uvc_video_encode_data(). Only bulk transfers are currently supported.
498 * uvc_video_encode_header is called at the start of a payload. It adds header
499 * data to the transfer buffer and returns the header size. As the only known
500 * UVC output device transfers a whole frame in a single payload, the EOF bit
501 * is always set in the header.
503 * uvc_video_encode_data is called for every URB and copies the data from the
504 * video buffer to the transfer buffer.
506 static int uvc_video_encode_header(struct uvc_streaming *stream,
507 struct uvc_buffer *buf, __u8 *data, int len)
509 data[0] = 2; /* Header length */
510 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
511 | (stream->last_fid & UVC_STREAM_FID);
512 return 2;
515 static int uvc_video_encode_data(struct uvc_streaming *stream,
516 struct uvc_buffer *buf, __u8 *data, int len)
518 struct uvc_video_queue *queue = &stream->queue;
519 unsigned int nbytes;
520 void *mem;
522 /* Copy video data to the URB buffer. */
523 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
524 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
525 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
526 nbytes);
527 memcpy(data, mem, nbytes);
529 queue->buf_used += nbytes;
531 return nbytes;
534 /* ------------------------------------------------------------------------
535 * URB handling
539 * Completion handler for video URBs.
541 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
542 struct uvc_buffer *buf)
544 u8 *mem;
545 int ret, i;
547 for (i = 0; i < urb->number_of_packets; ++i) {
548 if (urb->iso_frame_desc[i].status < 0) {
549 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
550 "lost (%d).\n", urb->iso_frame_desc[i].status);
551 continue;
554 /* Decode the payload header. */
555 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
556 do {
557 ret = uvc_video_decode_start(stream, buf, mem,
558 urb->iso_frame_desc[i].actual_length);
559 if (ret == -EAGAIN)
560 buf = uvc_queue_next_buffer(&stream->queue,
561 buf);
562 } while (ret == -EAGAIN);
564 if (ret < 0)
565 continue;
567 /* Decode the payload data. */
568 uvc_video_decode_data(stream, buf, mem + ret,
569 urb->iso_frame_desc[i].actual_length - ret);
571 /* Process the header again. */
572 uvc_video_decode_end(stream, buf, mem,
573 urb->iso_frame_desc[i].actual_length);
575 if (buf->state == UVC_BUF_STATE_READY)
576 buf = uvc_queue_next_buffer(&stream->queue, buf);
580 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
581 struct uvc_buffer *buf)
583 u8 *mem;
584 int len, ret;
586 if (urb->actual_length == 0)
587 return;
589 mem = urb->transfer_buffer;
590 len = urb->actual_length;
591 stream->bulk.payload_size += len;
593 /* If the URB is the first of its payload, decode and save the
594 * header.
596 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
597 do {
598 ret = uvc_video_decode_start(stream, buf, mem, len);
599 if (ret == -EAGAIN)
600 buf = uvc_queue_next_buffer(&stream->queue,
601 buf);
602 } while (ret == -EAGAIN);
604 /* If an error occured skip the rest of the payload. */
605 if (ret < 0 || buf == NULL) {
606 stream->bulk.skip_payload = 1;
607 } else {
608 memcpy(stream->bulk.header, mem, ret);
609 stream->bulk.header_size = ret;
611 mem += ret;
612 len -= ret;
616 /* The buffer queue might have been cancelled while a bulk transfer
617 * was in progress, so we can reach here with buf equal to NULL. Make
618 * sure buf is never dereferenced if NULL.
621 /* Process video data. */
622 if (!stream->bulk.skip_payload && buf != NULL)
623 uvc_video_decode_data(stream, buf, mem, len);
625 /* Detect the payload end by a URB smaller than the maximum size (or
626 * a payload size equal to the maximum) and process the header again.
628 if (urb->actual_length < urb->transfer_buffer_length ||
629 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
630 if (!stream->bulk.skip_payload && buf != NULL) {
631 uvc_video_decode_end(stream, buf, stream->bulk.header,
632 stream->bulk.payload_size);
633 if (buf->state == UVC_BUF_STATE_READY)
634 buf = uvc_queue_next_buffer(&stream->queue,
635 buf);
638 stream->bulk.header_size = 0;
639 stream->bulk.skip_payload = 0;
640 stream->bulk.payload_size = 0;
644 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
645 struct uvc_buffer *buf)
647 u8 *mem = urb->transfer_buffer;
648 int len = stream->urb_size, ret;
650 if (buf == NULL) {
651 urb->transfer_buffer_length = 0;
652 return;
655 /* If the URB is the first of its payload, add the header. */
656 if (stream->bulk.header_size == 0) {
657 ret = uvc_video_encode_header(stream, buf, mem, len);
658 stream->bulk.header_size = ret;
659 stream->bulk.payload_size += ret;
660 mem += ret;
661 len -= ret;
664 /* Process video data. */
665 ret = uvc_video_encode_data(stream, buf, mem, len);
667 stream->bulk.payload_size += ret;
668 len -= ret;
670 if (buf->buf.bytesused == stream->queue.buf_used ||
671 stream->bulk.payload_size == stream->bulk.max_payload_size) {
672 if (buf->buf.bytesused == stream->queue.buf_used) {
673 stream->queue.buf_used = 0;
674 buf->state = UVC_BUF_STATE_READY;
675 uvc_queue_next_buffer(&stream->queue, buf);
676 stream->last_fid ^= UVC_STREAM_FID;
679 stream->bulk.header_size = 0;
680 stream->bulk.payload_size = 0;
683 urb->transfer_buffer_length = stream->urb_size - len;
686 static void uvc_video_complete(struct urb *urb)
688 struct uvc_streaming *stream = urb->context;
689 struct uvc_video_queue *queue = &stream->queue;
690 struct uvc_buffer *buf = NULL;
691 unsigned long flags;
692 int ret;
694 switch (urb->status) {
695 case 0:
696 break;
698 default:
699 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
700 "completion handler.\n", urb->status);
702 case -ENOENT: /* usb_kill_urb() called. */
703 if (stream->frozen)
704 return;
706 case -ECONNRESET: /* usb_unlink_urb() called. */
707 case -ESHUTDOWN: /* The endpoint is being disabled. */
708 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
709 return;
712 spin_lock_irqsave(&queue->irqlock, flags);
713 if (!list_empty(&queue->irqqueue))
714 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
715 queue);
716 spin_unlock_irqrestore(&queue->irqlock, flags);
718 stream->decode(urb, stream, buf);
720 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
721 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
722 ret);
727 * Free transfer buffers.
729 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
731 unsigned int i;
733 for (i = 0; i < UVC_URBS; ++i) {
734 if (stream->urb_buffer[i]) {
735 usb_buffer_free(stream->dev->udev, stream->urb_size,
736 stream->urb_buffer[i], stream->urb_dma[i]);
737 stream->urb_buffer[i] = NULL;
741 stream->urb_size = 0;
745 * Allocate transfer buffers. This function can be called with buffers
746 * already allocated when resuming from suspend, in which case it will
747 * return without touching the buffers.
749 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
750 * system is too low on memory try successively smaller numbers of packets
751 * until allocation succeeds.
753 * Return the number of allocated packets on success or 0 when out of memory.
755 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
756 unsigned int size, unsigned int psize, gfp_t gfp_flags)
758 unsigned int npackets;
759 unsigned int i;
761 /* Buffers are already allocated, bail out. */
762 if (stream->urb_size)
763 return stream->urb_size / psize;
765 /* Compute the number of packets. Bulk endpoints might transfer UVC
766 * payloads accross multiple URBs.
768 npackets = DIV_ROUND_UP(size, psize);
769 if (npackets > UVC_MAX_PACKETS)
770 npackets = UVC_MAX_PACKETS;
772 /* Retry allocations until one succeed. */
773 for (; npackets > 1; npackets /= 2) {
774 for (i = 0; i < UVC_URBS; ++i) {
775 stream->urb_size = psize * npackets;
776 stream->urb_buffer[i] = usb_buffer_alloc(
777 stream->dev->udev, stream->urb_size,
778 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
779 if (!stream->urb_buffer[i]) {
780 uvc_free_urb_buffers(stream);
781 break;
785 if (i == UVC_URBS) {
786 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
787 "of %ux%u bytes each.\n", UVC_URBS, npackets,
788 psize);
789 return npackets;
793 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
794 "per packet).\n", psize);
795 return 0;
799 * Uninitialize isochronous/bulk URBs and free transfer buffers.
801 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
803 struct urb *urb;
804 unsigned int i;
806 for (i = 0; i < UVC_URBS; ++i) {
807 urb = stream->urb[i];
808 if (urb == NULL)
809 continue;
811 usb_kill_urb(urb);
812 usb_free_urb(urb);
813 stream->urb[i] = NULL;
816 if (free_buffers)
817 uvc_free_urb_buffers(stream);
821 * Initialize isochronous URBs and allocate transfer buffers. The packet size
822 * is given by the endpoint.
824 static int uvc_init_video_isoc(struct uvc_streaming *stream,
825 struct usb_host_endpoint *ep, gfp_t gfp_flags)
827 struct urb *urb;
828 unsigned int npackets, i, j;
829 u16 psize;
830 u32 size;
832 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
833 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
834 size = stream->ctrl.dwMaxVideoFrameSize;
836 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
837 if (npackets == 0)
838 return -ENOMEM;
840 size = npackets * psize;
842 for (i = 0; i < UVC_URBS; ++i) {
843 urb = usb_alloc_urb(npackets, gfp_flags);
844 if (urb == NULL) {
845 uvc_uninit_video(stream, 1);
846 return -ENOMEM;
849 urb->dev = stream->dev->udev;
850 urb->context = stream;
851 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
852 ep->desc.bEndpointAddress);
853 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
854 urb->interval = ep->desc.bInterval;
855 urb->transfer_buffer = stream->urb_buffer[i];
856 urb->transfer_dma = stream->urb_dma[i];
857 urb->complete = uvc_video_complete;
858 urb->number_of_packets = npackets;
859 urb->transfer_buffer_length = size;
861 for (j = 0; j < npackets; ++j) {
862 urb->iso_frame_desc[j].offset = j * psize;
863 urb->iso_frame_desc[j].length = psize;
866 stream->urb[i] = urb;
869 return 0;
873 * Initialize bulk URBs and allocate transfer buffers. The packet size is
874 * given by the endpoint.
876 static int uvc_init_video_bulk(struct uvc_streaming *stream,
877 struct usb_host_endpoint *ep, gfp_t gfp_flags)
879 struct urb *urb;
880 unsigned int npackets, pipe, i;
881 u16 psize;
882 u32 size;
884 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
885 size = stream->ctrl.dwMaxPayloadTransferSize;
886 stream->bulk.max_payload_size = size;
888 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
889 if (npackets == 0)
890 return -ENOMEM;
892 size = npackets * psize;
894 if (usb_endpoint_dir_in(&ep->desc))
895 pipe = usb_rcvbulkpipe(stream->dev->udev,
896 ep->desc.bEndpointAddress);
897 else
898 pipe = usb_sndbulkpipe(stream->dev->udev,
899 ep->desc.bEndpointAddress);
901 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
902 size = 0;
904 for (i = 0; i < UVC_URBS; ++i) {
905 urb = usb_alloc_urb(0, gfp_flags);
906 if (urb == NULL) {
907 uvc_uninit_video(stream, 1);
908 return -ENOMEM;
911 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
912 stream->urb_buffer[i], size, uvc_video_complete,
913 stream);
914 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
915 urb->transfer_dma = stream->urb_dma[i];
917 stream->urb[i] = urb;
920 return 0;
924 * Initialize isochronous/bulk URBs and allocate transfer buffers.
926 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
928 struct usb_interface *intf = stream->intf;
929 struct usb_host_endpoint *ep;
930 unsigned int i;
931 int ret;
933 stream->last_fid = -1;
934 stream->bulk.header_size = 0;
935 stream->bulk.skip_payload = 0;
936 stream->bulk.payload_size = 0;
938 if (intf->num_altsetting > 1) {
939 struct usb_host_endpoint *best_ep = NULL;
940 unsigned int best_psize = 3 * 1024;
941 unsigned int bandwidth;
942 unsigned int uninitialized_var(altsetting);
943 int intfnum = stream->intfnum;
945 /* Isochronous endpoint, select the alternate setting. */
946 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
948 if (bandwidth == 0) {
949 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
950 "bandwidth, defaulting to lowest.\n");
951 bandwidth = 1;
952 } else {
953 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
954 "B/frame bandwidth.\n", bandwidth);
957 for (i = 0; i < intf->num_altsetting; ++i) {
958 struct usb_host_interface *alts;
959 unsigned int psize;
961 alts = &intf->altsetting[i];
962 ep = uvc_find_endpoint(alts,
963 stream->header.bEndpointAddress);
964 if (ep == NULL)
965 continue;
967 /* Check if the bandwidth is high enough. */
968 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
969 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
970 if (psize >= bandwidth && psize <= best_psize) {
971 altsetting = i;
972 best_psize = psize;
973 best_ep = ep;
977 if (best_ep == NULL) {
978 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
979 "for requested bandwidth.\n");
980 return -EIO;
983 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
984 "(%u B/frame bandwidth).\n", altsetting, best_psize);
986 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
987 if (ret < 0)
988 return ret;
990 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
991 } else {
992 /* Bulk endpoint, proceed to URB initialization. */
993 ep = uvc_find_endpoint(&intf->altsetting[0],
994 stream->header.bEndpointAddress);
995 if (ep == NULL)
996 return -EIO;
998 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1001 if (ret < 0)
1002 return ret;
1004 /* Submit the URBs. */
1005 for (i = 0; i < UVC_URBS; ++i) {
1006 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1007 if (ret < 0) {
1008 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1009 "(%d).\n", i, ret);
1010 uvc_uninit_video(stream, 1);
1011 return ret;
1015 return 0;
1018 /* --------------------------------------------------------------------------
1019 * Suspend/resume
1023 * Stop streaming without disabling the video queue.
1025 * To let userspace applications resume without trouble, we must not touch the
1026 * video buffers in any way. We mark the device as frozen to make sure the URB
1027 * completion handler won't try to cancel the queue when we kill the URBs.
1029 int uvc_video_suspend(struct uvc_streaming *stream)
1031 if (!uvc_queue_streaming(&stream->queue))
1032 return 0;
1034 stream->frozen = 1;
1035 uvc_uninit_video(stream, 0);
1036 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1037 return 0;
1041 * Reconfigure the video interface and restart streaming if it was enabled
1042 * before suspend.
1044 * If an error occurs, disable the video queue. This will wake all pending
1045 * buffers, making sure userspace applications are notified of the problem
1046 * instead of waiting forever.
1048 int uvc_video_resume(struct uvc_streaming *stream)
1050 int ret;
1052 stream->frozen = 0;
1054 ret = uvc_commit_video(stream, &stream->ctrl);
1055 if (ret < 0) {
1056 uvc_queue_enable(&stream->queue, 0);
1057 return ret;
1060 if (!uvc_queue_streaming(&stream->queue))
1061 return 0;
1063 ret = uvc_init_video(stream, GFP_NOIO);
1064 if (ret < 0)
1065 uvc_queue_enable(&stream->queue, 0);
1067 return ret;
1070 /* ------------------------------------------------------------------------
1071 * Video device
1075 * Initialize the UVC video device by switching to alternate setting 0 and
1076 * retrieve the default format.
1078 * Some cameras (namely the Fuji Finepix) set the format and frame
1079 * indexes to zero. The UVC standard doesn't clearly make this a spec
1080 * violation, so try to silently fix the values if possible.
1082 * This function is called before registering the device with V4L.
1084 int uvc_video_init(struct uvc_streaming *stream)
1086 struct uvc_streaming_control *probe = &stream->ctrl;
1087 struct uvc_format *format = NULL;
1088 struct uvc_frame *frame = NULL;
1089 unsigned int i;
1090 int ret;
1092 if (stream->nformats == 0) {
1093 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1094 return -EINVAL;
1097 atomic_set(&stream->active, 0);
1099 /* Initialize the video buffers queue. */
1100 uvc_queue_init(&stream->queue, stream->type);
1102 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1103 * Cam (and possibly other devices) crash or otherwise misbehave if
1104 * they don't receive a SET_INTERFACE request before any other video
1105 * control request.
1107 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1109 /* Set the streaming probe control with default streaming parameters
1110 * retrieved from the device. Webcams that don't suport GET_DEF
1111 * requests on the probe control will just keep their current streaming
1112 * parameters.
1114 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1115 uvc_set_video_ctrl(stream, probe, 1);
1117 /* Initialize the streaming parameters with the probe control current
1118 * value. This makes sure SET_CUR requests on the streaming commit
1119 * control will always use values retrieved from a successful GET_CUR
1120 * request on the probe control, as required by the UVC specification.
1122 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1123 if (ret < 0)
1124 return ret;
1126 /* Check if the default format descriptor exists. Use the first
1127 * available format otherwise.
1129 for (i = stream->nformats; i > 0; --i) {
1130 format = &stream->format[i-1];
1131 if (format->index == probe->bFormatIndex)
1132 break;
1135 if (format->nframes == 0) {
1136 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1137 "default format.\n");
1138 return -EINVAL;
1141 /* Zero bFrameIndex might be correct. Stream-based formats (including
1142 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1143 * descriptor with bFrameIndex set to zero. If the default frame
1144 * descriptor is not found, use the first available frame.
1146 for (i = format->nframes; i > 0; --i) {
1147 frame = &format->frame[i-1];
1148 if (frame->bFrameIndex == probe->bFrameIndex)
1149 break;
1152 probe->bFormatIndex = format->index;
1153 probe->bFrameIndex = frame->bFrameIndex;
1155 stream->cur_format = format;
1156 stream->cur_frame = frame;
1158 /* Select the video decoding function */
1159 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1160 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1161 stream->decode = uvc_video_decode_isight;
1162 else if (stream->intf->num_altsetting > 1)
1163 stream->decode = uvc_video_decode_isoc;
1164 else
1165 stream->decode = uvc_video_decode_bulk;
1166 } else {
1167 if (stream->intf->num_altsetting == 1)
1168 stream->decode = uvc_video_encode_bulk;
1169 else {
1170 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1171 "supported for video output devices.\n");
1172 return -EINVAL;
1176 return 0;
1180 * Enable or disable the video stream.
1182 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1184 int ret;
1186 if (!enable) {
1187 uvc_uninit_video(stream, 1);
1188 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1189 uvc_queue_enable(&stream->queue, 0);
1190 return 0;
1193 if ((stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1194 uvc_no_drop_param)
1195 stream->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1196 else
1197 stream->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1199 ret = uvc_queue_enable(&stream->queue, 1);
1200 if (ret < 0)
1201 return ret;
1203 /* Commit the streaming parameters. */
1204 ret = uvc_commit_video(stream, &stream->ctrl);
1205 if (ret < 0)
1206 return ret;
1208 return uvc_init_video(stream, GFP_KERNEL);