[media] uvcvideo: Print query name in uvc_query_ctrl()
[linux-2.6/btrfs-unstable.git] / drivers / media / video / uvc / uvc_video.c
blobef55877cc2f34a4ee55af45c69610871222bd59e
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 static const char *uvc_query_name(__u8 query)
50 switch (query) {
51 case UVC_SET_CUR:
52 return "SET_CUR";
53 case UVC_GET_CUR:
54 return "GET_CUR";
55 case UVC_GET_MIN:
56 return "GET_MIN";
57 case UVC_GET_MAX:
58 return "GET_MAX";
59 case UVC_GET_RES:
60 return "GET_RES";
61 case UVC_GET_LEN:
62 return "GET_LEN";
63 case UVC_GET_INFO:
64 return "GET_INFO";
65 case UVC_GET_DEF:
66 return "GET_DEF";
67 default:
68 return "<invalid>";
72 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
73 __u8 intfnum, __u8 cs, void *data, __u16 size)
75 int ret;
77 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
78 UVC_CTRL_CONTROL_TIMEOUT);
79 if (ret != size) {
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,
82 unit, ret, size);
83 return -EIO;
86 return 0;
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;
94 unsigned int i;
96 if (ctrl->bFormatIndex <= 0 ||
97 ctrl->bFormatIndex > stream->nformats)
98 return;
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];
105 break;
109 if (frame == NULL)
110 return;
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) {
121 u32 interval;
122 u32 bandwidth;
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;
136 bandwidth /= 1000;
137 if (stream->dev->udev->speed == USB_SPEED_HIGH)
138 bandwidth /= 8;
139 bandwidth += 12;
141 ctrl->dwMaxPayloadTransferSize = bandwidth;
145 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
146 struct uvc_streaming_control *ctrl, int probe, __u8 query)
148 __u8 *data;
149 __u16 size;
150 int ret;
152 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
153 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
154 query == UVC_GET_DEF)
155 return -EIO;
157 data = kmalloc(size, GFP_KERNEL);
158 if (data == NULL)
159 return -ENOMEM;
161 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
162 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
163 size, uvc_timeout_param);
165 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
166 /* Some cameras, mostly based on Bison Electronics chipsets,
167 * answer a GET_MIN or GET_MAX request with the wCompQuality
168 * field only.
170 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
171 "compliance - GET_MIN/MAX(PROBE) incorrectly "
172 "supported. Enabling workaround.\n");
173 memset(ctrl, 0, sizeof *ctrl);
174 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
175 ret = 0;
176 goto out;
177 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
178 /* Many cameras don't support the GET_DEF request on their
179 * video probe control. Warn once and return, the caller will
180 * fall back to GET_CUR.
182 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
183 "compliance - GET_DEF(PROBE) not supported. "
184 "Enabling workaround.\n");
185 ret = -EIO;
186 goto out;
187 } else if (ret != size) {
188 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
189 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
190 ret, size);
191 ret = -EIO;
192 goto out;
195 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
196 ctrl->bFormatIndex = data[2];
197 ctrl->bFrameIndex = data[3];
198 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
199 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
200 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
201 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
202 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
203 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
204 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
205 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
207 if (size == 34) {
208 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
209 ctrl->bmFramingInfo = data[30];
210 ctrl->bPreferedVersion = data[31];
211 ctrl->bMinVersion = data[32];
212 ctrl->bMaxVersion = data[33];
213 } else {
214 ctrl->dwClockFrequency = stream->dev->clock_frequency;
215 ctrl->bmFramingInfo = 0;
216 ctrl->bPreferedVersion = 0;
217 ctrl->bMinVersion = 0;
218 ctrl->bMaxVersion = 0;
221 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
222 * dwMaxPayloadTransferSize fields. Try to get the value from the
223 * format and frame descriptors.
225 uvc_fixup_video_ctrl(stream, ctrl);
226 ret = 0;
228 out:
229 kfree(data);
230 return ret;
233 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
234 struct uvc_streaming_control *ctrl, int probe)
236 __u8 *data;
237 __u16 size;
238 int ret;
240 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
241 data = kzalloc(size, GFP_KERNEL);
242 if (data == NULL)
243 return -ENOMEM;
245 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
246 data[2] = ctrl->bFormatIndex;
247 data[3] = ctrl->bFrameIndex;
248 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
249 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
250 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
251 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
252 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
253 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
254 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
255 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
257 if (size == 34) {
258 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
259 data[30] = ctrl->bmFramingInfo;
260 data[31] = ctrl->bPreferedVersion;
261 data[32] = ctrl->bMinVersion;
262 data[33] = ctrl->bMaxVersion;
265 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
266 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
267 size, uvc_timeout_param);
268 if (ret != size) {
269 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
270 "%d (exp. %u).\n", probe ? "probe" : "commit",
271 ret, size);
272 ret = -EIO;
275 kfree(data);
276 return ret;
279 int uvc_probe_video(struct uvc_streaming *stream,
280 struct uvc_streaming_control *probe)
282 struct uvc_streaming_control probe_min, probe_max;
283 __u16 bandwidth;
284 unsigned int i;
285 int ret;
287 mutex_lock(&stream->mutex);
289 /* Perform probing. The device should adjust the requested values
290 * according to its capabilities. However, some devices, namely the
291 * first generation UVC Logitech webcams, don't implement the Video
292 * Probe control properly, and just return the needed bandwidth. For
293 * that reason, if the needed bandwidth exceeds the maximum available
294 * bandwidth, try to lower the quality.
296 ret = uvc_set_video_ctrl(stream, probe, 1);
297 if (ret < 0)
298 goto done;
300 /* Get the minimum and maximum values for compression settings. */
301 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
302 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
303 if (ret < 0)
304 goto done;
305 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
306 if (ret < 0)
307 goto done;
309 probe->wCompQuality = probe_max.wCompQuality;
312 for (i = 0; i < 2; ++i) {
313 ret = uvc_set_video_ctrl(stream, probe, 1);
314 if (ret < 0)
315 goto done;
316 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
317 if (ret < 0)
318 goto done;
320 if (stream->intf->num_altsetting == 1)
321 break;
323 bandwidth = probe->dwMaxPayloadTransferSize;
324 if (bandwidth <= stream->maxpsize)
325 break;
327 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
328 ret = -ENOSPC;
329 goto done;
332 /* TODO: negotiate compression parameters */
333 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
334 probe->wPFrameRate = probe_min.wPFrameRate;
335 probe->wCompQuality = probe_max.wCompQuality;
336 probe->wCompWindowSize = probe_min.wCompWindowSize;
339 done:
340 mutex_unlock(&stream->mutex);
341 return ret;
344 int uvc_commit_video(struct uvc_streaming *stream,
345 struct uvc_streaming_control *probe)
347 return uvc_set_video_ctrl(stream, probe, 0);
350 /* ------------------------------------------------------------------------
351 * Video codecs
354 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
355 #define UVC_STREAM_EOH (1 << 7)
356 #define UVC_STREAM_ERR (1 << 6)
357 #define UVC_STREAM_STI (1 << 5)
358 #define UVC_STREAM_RES (1 << 4)
359 #define UVC_STREAM_SCR (1 << 3)
360 #define UVC_STREAM_PTS (1 << 2)
361 #define UVC_STREAM_EOF (1 << 1)
362 #define UVC_STREAM_FID (1 << 0)
364 /* Video payload decoding is handled by uvc_video_decode_start(),
365 * uvc_video_decode_data() and uvc_video_decode_end().
367 * uvc_video_decode_start is called with URB data at the start of a bulk or
368 * isochronous payload. It processes header data and returns the header size
369 * in bytes if successful. If an error occurs, it returns a negative error
370 * code. The following error codes have special meanings.
372 * - EAGAIN informs the caller that the current video buffer should be marked
373 * as done, and that the function should be called again with the same data
374 * and a new video buffer. This is used when end of frame conditions can be
375 * reliably detected at the beginning of the next frame only.
377 * If an error other than -EAGAIN is returned, the caller will drop the current
378 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
379 * made until the next payload. -ENODATA can be used to drop the current
380 * payload if no other error code is appropriate.
382 * uvc_video_decode_data is called for every URB with URB data. It copies the
383 * data to the video buffer.
385 * uvc_video_decode_end is called with header data at the end of a bulk or
386 * isochronous payload. It performs any additional header data processing and
387 * returns 0 or a negative error code if an error occured. As header data have
388 * already been processed by uvc_video_decode_start, this functions isn't
389 * required to perform sanity checks a second time.
391 * For isochronous transfers where a payload is always transfered in a single
392 * URB, the three functions will be called in a row.
394 * To let the decoder process header data and update its internal state even
395 * when no video buffer is available, uvc_video_decode_start must be prepared
396 * to be called with a NULL buf parameter. uvc_video_decode_data and
397 * uvc_video_decode_end will never be called with a NULL buffer.
399 static int uvc_video_decode_start(struct uvc_streaming *stream,
400 struct uvc_buffer *buf, const __u8 *data, int len)
402 __u8 fid;
404 /* Sanity checks:
405 * - packet must be at least 2 bytes long
406 * - bHeaderLength value must be at least 2 bytes (see above)
407 * - bHeaderLength value can't be larger than the packet size.
409 if (len < 2 || data[0] < 2 || data[0] > len)
410 return -EINVAL;
412 /* Skip payloads marked with the error bit ("error frames"). */
413 if (data[1] & UVC_STREAM_ERR) {
414 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
415 "set).\n");
416 return -ENODATA;
419 fid = data[1] & UVC_STREAM_FID;
421 /* Store the payload FID bit and return immediately when the buffer is
422 * NULL.
424 if (buf == NULL) {
425 stream->last_fid = fid;
426 return -ENODATA;
429 /* Synchronize to the input stream by waiting for the FID bit to be
430 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
431 * stream->last_fid is initialized to -1, so the first isochronous
432 * frame will always be in sync.
434 * If the device doesn't toggle the FID bit, invert stream->last_fid
435 * when the EOF bit is set to force synchronisation on the next packet.
437 if (buf->state != UVC_BUF_STATE_ACTIVE) {
438 struct timespec ts;
440 if (fid == stream->last_fid) {
441 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
442 "sync).\n");
443 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
444 (data[1] & UVC_STREAM_EOF))
445 stream->last_fid ^= UVC_STREAM_FID;
446 return -ENODATA;
449 if (uvc_clock_param == CLOCK_MONOTONIC)
450 ktime_get_ts(&ts);
451 else
452 ktime_get_real_ts(&ts);
454 buf->buf.timestamp.tv_sec = ts.tv_sec;
455 buf->buf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
457 /* TODO: Handle PTS and SCR. */
458 buf->state = UVC_BUF_STATE_ACTIVE;
461 /* Mark the buffer as done if we're at the beginning of a new frame.
462 * End of frame detection is better implemented by checking the EOF
463 * bit (FID bit toggling is delayed by one frame compared to the EOF
464 * bit), but some devices don't set the bit at end of frame (and the
465 * last payload can be lost anyway). We thus must check if the FID has
466 * been toggled.
468 * stream->last_fid is initialized to -1, so the first isochronous
469 * frame will never trigger an end of frame detection.
471 * Empty buffers (bytesused == 0) don't trigger end of frame detection
472 * as it doesn't make sense to return an empty buffer. This also
473 * avoids detecting end of frame conditions at FID toggling if the
474 * previous payload had the EOF bit set.
476 if (fid != stream->last_fid && buf->buf.bytesused != 0) {
477 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
478 "toggled).\n");
479 buf->state = UVC_BUF_STATE_READY;
480 return -EAGAIN;
483 stream->last_fid = fid;
485 return data[0];
488 static void uvc_video_decode_data(struct uvc_streaming *stream,
489 struct uvc_buffer *buf, const __u8 *data, int len)
491 struct uvc_video_queue *queue = &stream->queue;
492 unsigned int maxlen, nbytes;
493 void *mem;
495 if (len <= 0)
496 return;
498 /* Copy the video data to the buffer. */
499 maxlen = buf->buf.length - buf->buf.bytesused;
500 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
501 nbytes = min((unsigned int)len, maxlen);
502 memcpy(mem, data, nbytes);
503 buf->buf.bytesused += nbytes;
505 /* Complete the current frame if the buffer size was exceeded. */
506 if (len > maxlen) {
507 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
508 buf->state = UVC_BUF_STATE_READY;
512 static void uvc_video_decode_end(struct uvc_streaming *stream,
513 struct uvc_buffer *buf, const __u8 *data, int len)
515 /* Mark the buffer as done if the EOF marker is set. */
516 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
517 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
518 if (data[0] == len)
519 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
520 buf->state = UVC_BUF_STATE_READY;
521 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
522 stream->last_fid ^= UVC_STREAM_FID;
526 /* Video payload encoding is handled by uvc_video_encode_header() and
527 * uvc_video_encode_data(). Only bulk transfers are currently supported.
529 * uvc_video_encode_header is called at the start of a payload. It adds header
530 * data to the transfer buffer and returns the header size. As the only known
531 * UVC output device transfers a whole frame in a single payload, the EOF bit
532 * is always set in the header.
534 * uvc_video_encode_data is called for every URB and copies the data from the
535 * video buffer to the transfer buffer.
537 static int uvc_video_encode_header(struct uvc_streaming *stream,
538 struct uvc_buffer *buf, __u8 *data, int len)
540 data[0] = 2; /* Header length */
541 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
542 | (stream->last_fid & UVC_STREAM_FID);
543 return 2;
546 static int uvc_video_encode_data(struct uvc_streaming *stream,
547 struct uvc_buffer *buf, __u8 *data, int len)
549 struct uvc_video_queue *queue = &stream->queue;
550 unsigned int nbytes;
551 void *mem;
553 /* Copy video data to the URB buffer. */
554 mem = queue->mem + buf->buf.m.offset + queue->buf_used;
555 nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
556 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
557 nbytes);
558 memcpy(data, mem, nbytes);
560 queue->buf_used += nbytes;
562 return nbytes;
565 /* ------------------------------------------------------------------------
566 * URB handling
570 * Completion handler for video URBs.
572 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
573 struct uvc_buffer *buf)
575 u8 *mem;
576 int ret, i;
578 for (i = 0; i < urb->number_of_packets; ++i) {
579 if (urb->iso_frame_desc[i].status < 0) {
580 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
581 "lost (%d).\n", urb->iso_frame_desc[i].status);
582 /* Mark the buffer as faulty. */
583 if (buf != NULL)
584 buf->error = 1;
585 continue;
588 /* Decode the payload header. */
589 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
590 do {
591 ret = uvc_video_decode_start(stream, buf, mem,
592 urb->iso_frame_desc[i].actual_length);
593 if (ret == -EAGAIN)
594 buf = uvc_queue_next_buffer(&stream->queue,
595 buf);
596 } while (ret == -EAGAIN);
598 if (ret < 0)
599 continue;
601 /* Decode the payload data. */
602 uvc_video_decode_data(stream, buf, mem + ret,
603 urb->iso_frame_desc[i].actual_length - ret);
605 /* Process the header again. */
606 uvc_video_decode_end(stream, buf, mem,
607 urb->iso_frame_desc[i].actual_length);
609 if (buf->state == UVC_BUF_STATE_READY) {
610 if (buf->buf.length != buf->buf.bytesused &&
611 !(stream->cur_format->flags &
612 UVC_FMT_FLAG_COMPRESSED))
613 buf->error = 1;
615 buf = uvc_queue_next_buffer(&stream->queue, buf);
620 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
621 struct uvc_buffer *buf)
623 u8 *mem;
624 int len, ret;
626 if (urb->actual_length == 0)
627 return;
629 mem = urb->transfer_buffer;
630 len = urb->actual_length;
631 stream->bulk.payload_size += len;
633 /* If the URB is the first of its payload, decode and save the
634 * header.
636 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
637 do {
638 ret = uvc_video_decode_start(stream, buf, mem, len);
639 if (ret == -EAGAIN)
640 buf = uvc_queue_next_buffer(&stream->queue,
641 buf);
642 } while (ret == -EAGAIN);
644 /* If an error occured skip the rest of the payload. */
645 if (ret < 0 || buf == NULL) {
646 stream->bulk.skip_payload = 1;
647 } else {
648 memcpy(stream->bulk.header, mem, ret);
649 stream->bulk.header_size = ret;
651 mem += ret;
652 len -= ret;
656 /* The buffer queue might have been cancelled while a bulk transfer
657 * was in progress, so we can reach here with buf equal to NULL. Make
658 * sure buf is never dereferenced if NULL.
661 /* Process video data. */
662 if (!stream->bulk.skip_payload && buf != NULL)
663 uvc_video_decode_data(stream, buf, mem, len);
665 /* Detect the payload end by a URB smaller than the maximum size (or
666 * a payload size equal to the maximum) and process the header again.
668 if (urb->actual_length < urb->transfer_buffer_length ||
669 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
670 if (!stream->bulk.skip_payload && buf != NULL) {
671 uvc_video_decode_end(stream, buf, stream->bulk.header,
672 stream->bulk.payload_size);
673 if (buf->state == UVC_BUF_STATE_READY)
674 buf = uvc_queue_next_buffer(&stream->queue,
675 buf);
678 stream->bulk.header_size = 0;
679 stream->bulk.skip_payload = 0;
680 stream->bulk.payload_size = 0;
684 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
685 struct uvc_buffer *buf)
687 u8 *mem = urb->transfer_buffer;
688 int len = stream->urb_size, ret;
690 if (buf == NULL) {
691 urb->transfer_buffer_length = 0;
692 return;
695 /* If the URB is the first of its payload, add the header. */
696 if (stream->bulk.header_size == 0) {
697 ret = uvc_video_encode_header(stream, buf, mem, len);
698 stream->bulk.header_size = ret;
699 stream->bulk.payload_size += ret;
700 mem += ret;
701 len -= ret;
704 /* Process video data. */
705 ret = uvc_video_encode_data(stream, buf, mem, len);
707 stream->bulk.payload_size += ret;
708 len -= ret;
710 if (buf->buf.bytesused == stream->queue.buf_used ||
711 stream->bulk.payload_size == stream->bulk.max_payload_size) {
712 if (buf->buf.bytesused == stream->queue.buf_used) {
713 stream->queue.buf_used = 0;
714 buf->state = UVC_BUF_STATE_READY;
715 uvc_queue_next_buffer(&stream->queue, buf);
716 stream->last_fid ^= UVC_STREAM_FID;
719 stream->bulk.header_size = 0;
720 stream->bulk.payload_size = 0;
723 urb->transfer_buffer_length = stream->urb_size - len;
726 static void uvc_video_complete(struct urb *urb)
728 struct uvc_streaming *stream = urb->context;
729 struct uvc_video_queue *queue = &stream->queue;
730 struct uvc_buffer *buf = NULL;
731 unsigned long flags;
732 int ret;
734 switch (urb->status) {
735 case 0:
736 break;
738 default:
739 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
740 "completion handler.\n", urb->status);
742 case -ENOENT: /* usb_kill_urb() called. */
743 if (stream->frozen)
744 return;
746 case -ECONNRESET: /* usb_unlink_urb() called. */
747 case -ESHUTDOWN: /* The endpoint is being disabled. */
748 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
749 return;
752 spin_lock_irqsave(&queue->irqlock, flags);
753 if (!list_empty(&queue->irqqueue))
754 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
755 queue);
756 spin_unlock_irqrestore(&queue->irqlock, flags);
758 stream->decode(urb, stream, buf);
760 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
761 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
762 ret);
767 * Free transfer buffers.
769 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
771 unsigned int i;
773 for (i = 0; i < UVC_URBS; ++i) {
774 if (stream->urb_buffer[i]) {
775 usb_free_coherent(stream->dev->udev, stream->urb_size,
776 stream->urb_buffer[i], stream->urb_dma[i]);
777 stream->urb_buffer[i] = NULL;
781 stream->urb_size = 0;
785 * Allocate transfer buffers. This function can be called with buffers
786 * already allocated when resuming from suspend, in which case it will
787 * return without touching the buffers.
789 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
790 * system is too low on memory try successively smaller numbers of packets
791 * until allocation succeeds.
793 * Return the number of allocated packets on success or 0 when out of memory.
795 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
796 unsigned int size, unsigned int psize, gfp_t gfp_flags)
798 unsigned int npackets;
799 unsigned int i;
801 /* Buffers are already allocated, bail out. */
802 if (stream->urb_size)
803 return stream->urb_size / psize;
805 /* Compute the number of packets. Bulk endpoints might transfer UVC
806 * payloads accross multiple URBs.
808 npackets = DIV_ROUND_UP(size, psize);
809 if (npackets > UVC_MAX_PACKETS)
810 npackets = UVC_MAX_PACKETS;
812 /* Retry allocations until one succeed. */
813 for (; npackets > 1; npackets /= 2) {
814 for (i = 0; i < UVC_URBS; ++i) {
815 stream->urb_size = psize * npackets;
816 stream->urb_buffer[i] = usb_alloc_coherent(
817 stream->dev->udev, stream->urb_size,
818 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
819 if (!stream->urb_buffer[i]) {
820 uvc_free_urb_buffers(stream);
821 break;
825 if (i == UVC_URBS) {
826 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
827 "of %ux%u bytes each.\n", UVC_URBS, npackets,
828 psize);
829 return npackets;
833 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
834 "per packet).\n", psize);
835 return 0;
839 * Uninitialize isochronous/bulk URBs and free transfer buffers.
841 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
843 struct urb *urb;
844 unsigned int i;
846 for (i = 0; i < UVC_URBS; ++i) {
847 urb = stream->urb[i];
848 if (urb == NULL)
849 continue;
851 usb_kill_urb(urb);
852 usb_free_urb(urb);
853 stream->urb[i] = NULL;
856 if (free_buffers)
857 uvc_free_urb_buffers(stream);
861 * Initialize isochronous URBs and allocate transfer buffers. The packet size
862 * is given by the endpoint.
864 static int uvc_init_video_isoc(struct uvc_streaming *stream,
865 struct usb_host_endpoint *ep, gfp_t gfp_flags)
867 struct urb *urb;
868 unsigned int npackets, i, j;
869 u16 psize;
870 u32 size;
872 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
873 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
874 size = stream->ctrl.dwMaxVideoFrameSize;
876 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
877 if (npackets == 0)
878 return -ENOMEM;
880 size = npackets * psize;
882 for (i = 0; i < UVC_URBS; ++i) {
883 urb = usb_alloc_urb(npackets, gfp_flags);
884 if (urb == NULL) {
885 uvc_uninit_video(stream, 1);
886 return -ENOMEM;
889 urb->dev = stream->dev->udev;
890 urb->context = stream;
891 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
892 ep->desc.bEndpointAddress);
893 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
894 urb->interval = ep->desc.bInterval;
895 urb->transfer_buffer = stream->urb_buffer[i];
896 urb->transfer_dma = stream->urb_dma[i];
897 urb->complete = uvc_video_complete;
898 urb->number_of_packets = npackets;
899 urb->transfer_buffer_length = size;
901 for (j = 0; j < npackets; ++j) {
902 urb->iso_frame_desc[j].offset = j * psize;
903 urb->iso_frame_desc[j].length = psize;
906 stream->urb[i] = urb;
909 return 0;
913 * Initialize bulk URBs and allocate transfer buffers. The packet size is
914 * given by the endpoint.
916 static int uvc_init_video_bulk(struct uvc_streaming *stream,
917 struct usb_host_endpoint *ep, gfp_t gfp_flags)
919 struct urb *urb;
920 unsigned int npackets, pipe, i;
921 u16 psize;
922 u32 size;
924 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
925 size = stream->ctrl.dwMaxPayloadTransferSize;
926 stream->bulk.max_payload_size = size;
928 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
929 if (npackets == 0)
930 return -ENOMEM;
932 size = npackets * psize;
934 if (usb_endpoint_dir_in(&ep->desc))
935 pipe = usb_rcvbulkpipe(stream->dev->udev,
936 ep->desc.bEndpointAddress);
937 else
938 pipe = usb_sndbulkpipe(stream->dev->udev,
939 ep->desc.bEndpointAddress);
941 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
942 size = 0;
944 for (i = 0; i < UVC_URBS; ++i) {
945 urb = usb_alloc_urb(0, gfp_flags);
946 if (urb == NULL) {
947 uvc_uninit_video(stream, 1);
948 return -ENOMEM;
951 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
952 stream->urb_buffer[i], size, uvc_video_complete,
953 stream);
954 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
955 urb->transfer_dma = stream->urb_dma[i];
957 stream->urb[i] = urb;
960 return 0;
964 * Initialize isochronous/bulk URBs and allocate transfer buffers.
966 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
968 struct usb_interface *intf = stream->intf;
969 struct usb_host_endpoint *ep;
970 unsigned int i;
971 int ret;
973 stream->last_fid = -1;
974 stream->bulk.header_size = 0;
975 stream->bulk.skip_payload = 0;
976 stream->bulk.payload_size = 0;
978 if (intf->num_altsetting > 1) {
979 struct usb_host_endpoint *best_ep = NULL;
980 unsigned int best_psize = 3 * 1024;
981 unsigned int bandwidth;
982 unsigned int uninitialized_var(altsetting);
983 int intfnum = stream->intfnum;
985 /* Isochronous endpoint, select the alternate setting. */
986 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
988 if (bandwidth == 0) {
989 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
990 "bandwidth, defaulting to lowest.\n");
991 bandwidth = 1;
992 } else {
993 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
994 "B/frame bandwidth.\n", bandwidth);
997 for (i = 0; i < intf->num_altsetting; ++i) {
998 struct usb_host_interface *alts;
999 unsigned int psize;
1001 alts = &intf->altsetting[i];
1002 ep = uvc_find_endpoint(alts,
1003 stream->header.bEndpointAddress);
1004 if (ep == NULL)
1005 continue;
1007 /* Check if the bandwidth is high enough. */
1008 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
1009 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1010 if (psize >= bandwidth && psize <= best_psize) {
1011 altsetting = i;
1012 best_psize = psize;
1013 best_ep = ep;
1017 if (best_ep == NULL) {
1018 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1019 "for requested bandwidth.\n");
1020 return -EIO;
1023 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1024 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1026 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1027 if (ret < 0)
1028 return ret;
1030 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1031 } else {
1032 /* Bulk endpoint, proceed to URB initialization. */
1033 ep = uvc_find_endpoint(&intf->altsetting[0],
1034 stream->header.bEndpointAddress);
1035 if (ep == NULL)
1036 return -EIO;
1038 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1041 if (ret < 0)
1042 return ret;
1044 /* Submit the URBs. */
1045 for (i = 0; i < UVC_URBS; ++i) {
1046 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1047 if (ret < 0) {
1048 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1049 "(%d).\n", i, ret);
1050 uvc_uninit_video(stream, 1);
1051 return ret;
1055 return 0;
1058 /* --------------------------------------------------------------------------
1059 * Suspend/resume
1063 * Stop streaming without disabling the video queue.
1065 * To let userspace applications resume without trouble, we must not touch the
1066 * video buffers in any way. We mark the device as frozen to make sure the URB
1067 * completion handler won't try to cancel the queue when we kill the URBs.
1069 int uvc_video_suspend(struct uvc_streaming *stream)
1071 if (!uvc_queue_streaming(&stream->queue))
1072 return 0;
1074 stream->frozen = 1;
1075 uvc_uninit_video(stream, 0);
1076 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1077 return 0;
1081 * Reconfigure the video interface and restart streaming if it was enabled
1082 * before suspend.
1084 * If an error occurs, disable the video queue. This will wake all pending
1085 * buffers, making sure userspace applications are notified of the problem
1086 * instead of waiting forever.
1088 int uvc_video_resume(struct uvc_streaming *stream)
1090 int ret;
1092 stream->frozen = 0;
1094 ret = uvc_commit_video(stream, &stream->ctrl);
1095 if (ret < 0) {
1096 uvc_queue_enable(&stream->queue, 0);
1097 return ret;
1100 if (!uvc_queue_streaming(&stream->queue))
1101 return 0;
1103 ret = uvc_init_video(stream, GFP_NOIO);
1104 if (ret < 0)
1105 uvc_queue_enable(&stream->queue, 0);
1107 return ret;
1110 /* ------------------------------------------------------------------------
1111 * Video device
1115 * Initialize the UVC video device by switching to alternate setting 0 and
1116 * retrieve the default format.
1118 * Some cameras (namely the Fuji Finepix) set the format and frame
1119 * indexes to zero. The UVC standard doesn't clearly make this a spec
1120 * violation, so try to silently fix the values if possible.
1122 * This function is called before registering the device with V4L.
1124 int uvc_video_init(struct uvc_streaming *stream)
1126 struct uvc_streaming_control *probe = &stream->ctrl;
1127 struct uvc_format *format = NULL;
1128 struct uvc_frame *frame = NULL;
1129 unsigned int i;
1130 int ret;
1132 if (stream->nformats == 0) {
1133 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1134 return -EINVAL;
1137 atomic_set(&stream->active, 0);
1139 /* Initialize the video buffers queue. */
1140 uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1142 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1143 * Cam (and possibly other devices) crash or otherwise misbehave if
1144 * they don't receive a SET_INTERFACE request before any other video
1145 * control request.
1147 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1149 /* Set the streaming probe control with default streaming parameters
1150 * retrieved from the device. Webcams that don't suport GET_DEF
1151 * requests on the probe control will just keep their current streaming
1152 * parameters.
1154 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1155 uvc_set_video_ctrl(stream, probe, 1);
1157 /* Initialize the streaming parameters with the probe control current
1158 * value. This makes sure SET_CUR requests on the streaming commit
1159 * control will always use values retrieved from a successful GET_CUR
1160 * request on the probe control, as required by the UVC specification.
1162 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1163 if (ret < 0)
1164 return ret;
1166 /* Check if the default format descriptor exists. Use the first
1167 * available format otherwise.
1169 for (i = stream->nformats; i > 0; --i) {
1170 format = &stream->format[i-1];
1171 if (format->index == probe->bFormatIndex)
1172 break;
1175 if (format->nframes == 0) {
1176 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1177 "default format.\n");
1178 return -EINVAL;
1181 /* Zero bFrameIndex might be correct. Stream-based formats (including
1182 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1183 * descriptor with bFrameIndex set to zero. If the default frame
1184 * descriptor is not found, use the first available frame.
1186 for (i = format->nframes; i > 0; --i) {
1187 frame = &format->frame[i-1];
1188 if (frame->bFrameIndex == probe->bFrameIndex)
1189 break;
1192 probe->bFormatIndex = format->index;
1193 probe->bFrameIndex = frame->bFrameIndex;
1195 stream->cur_format = format;
1196 stream->cur_frame = frame;
1198 /* Select the video decoding function */
1199 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1200 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1201 stream->decode = uvc_video_decode_isight;
1202 else if (stream->intf->num_altsetting > 1)
1203 stream->decode = uvc_video_decode_isoc;
1204 else
1205 stream->decode = uvc_video_decode_bulk;
1206 } else {
1207 if (stream->intf->num_altsetting == 1)
1208 stream->decode = uvc_video_encode_bulk;
1209 else {
1210 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1211 "supported for video output devices.\n");
1212 return -EINVAL;
1216 return 0;
1220 * Enable or disable the video stream.
1222 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1224 int ret;
1226 if (!enable) {
1227 uvc_uninit_video(stream, 1);
1228 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1229 uvc_queue_enable(&stream->queue, 0);
1230 return 0;
1233 ret = uvc_queue_enable(&stream->queue, 1);
1234 if (ret < 0)
1235 return ret;
1237 /* Commit the streaming parameters. */
1238 ret = uvc_commit_video(stream, &stream->ctrl);
1239 if (ret < 0)
1240 return ret;
1242 return uvc_init_video(stream, GFP_KERNEL);