blob: 4af94707ef69418cbaf5723fe1cd23b0d9e6d103 [file] [log] [blame]
Laurent Pinchartc0efd232008-06-30 15:04:50 -03001/*
2 * uvc_video.c -- USB Video Class driver - Video handling
3 *
4 * Copyright (C) 2005-2008
5 * Laurent Pinchart (laurent.pinchart@skynet.be)
6 *
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.
11 *
12 */
13
14#include <linux/kernel.h>
15#include <linux/version.h>
16#include <linux/list.h>
17#include <linux/module.h>
18#include <linux/usb.h>
19#include <linux/videodev2.h>
20#include <linux/vmalloc.h>
21#include <linux/wait.h>
22#include <asm/atomic.h>
23#include <asm/unaligned.h>
24
25#include <media/v4l2-common.h>
26
27#include "uvcvideo.h"
28
29/* ------------------------------------------------------------------------
30 * UVC Controls
31 */
32
33static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
34 __u8 intfnum, __u8 cs, void *data, __u16 size,
35 int timeout)
36{
37 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
38 unsigned int pipe;
Laurent Pinchartc0efd232008-06-30 15:04:50 -030039
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;
43
Laurent Pinchart44f00792008-11-08 19:14:50 -030044 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
Laurent Pinchartc0efd232008-06-30 15:04:50 -030045 unit << 8 | intfnum, data, size, timeout);
Laurent Pinchart44f00792008-11-08 19:14:50 -030046}
Laurent Pinchartc0efd232008-06-30 15:04:50 -030047
Laurent Pinchart44f00792008-11-08 19:14:50 -030048int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
49 __u8 intfnum, __u8 cs, void *data, __u16 size)
50{
51 int ret;
52
53 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
54 UVC_CTRL_CONTROL_TIMEOUT);
Laurent Pinchartc0efd232008-06-30 15:04:50 -030055 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;
60 }
61
62 return 0;
63}
64
Laurent Pinchartc0efd232008-06-30 15:04:50 -030065static void uvc_fixup_buffer_size(struct uvc_video_device *video,
66 struct uvc_streaming_control *ctrl)
67{
68 struct uvc_format *format;
69 struct uvc_frame *frame;
70
71 if (ctrl->bFormatIndex <= 0 ||
72 ctrl->bFormatIndex > video->streaming->nformats)
73 return;
74
75 format = &video->streaming->format[ctrl->bFormatIndex - 1];
76
77 if (ctrl->bFrameIndex <= 0 ||
78 ctrl->bFrameIndex > format->nframes)
79 return;
80
81 frame = &format->frame[ctrl->bFrameIndex - 1];
82
83 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
84 (ctrl->dwMaxVideoFrameSize == 0 &&
85 video->dev->uvc_version < 0x0110))
86 ctrl->dwMaxVideoFrameSize =
87 frame->dwMaxVideoFrameBufferSize;
88}
89
90static int uvc_get_video_ctrl(struct uvc_video_device *video,
91 struct uvc_streaming_control *ctrl, int probe, __u8 query)
92{
Laurent Pinchart04793dd2008-07-31 17:11:12 -030093 __u8 *data;
94 __u16 size;
Laurent Pinchartc0efd232008-06-30 15:04:50 -030095 int ret;
96
97 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
Laurent Pinchart04793dd2008-07-31 17:11:12 -030098 data = kmalloc(size, GFP_KERNEL);
99 if (data == NULL)
100 return -ENOMEM;
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300101
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300102 ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
103 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
104 UVC_CTRL_STREAMING_TIMEOUT);
Laurent Pinchart44f00792008-11-08 19:14:50 -0300105
106 if ((query == GET_MIN || query == GET_MAX) && ret == 2) {
107 /* Some cameras, mostly based on Bison Electronics chipsets,
108 * answer a GET_MIN or GET_MAX request with the wCompQuality
109 * field only.
110 */
111 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
112 "compliance - GET_MIN/MAX(PROBE) incorrectly "
113 "supported. Enabling workaround.\n");
114 memset(ctrl, 0, sizeof ctrl);
115 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
116 ret = 0;
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300117 goto out;
Laurent Pinchart44f00792008-11-08 19:14:50 -0300118 } else if (query == GET_DEF && probe == 1) {
119 /* Many cameras don't support the GET_DEF request on their
120 * video probe control. Warn once and return, the caller will
121 * fall back to GET_CUR.
122 */
123 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
124 "compliance - GET_DEF(PROBE) not supported. "
125 "Enabling workaround.\n");
126 ret = -EIO;
127 goto out;
128 } else if (ret != size) {
129 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
130 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
131 ret, size);
132 ret = -EIO;
133 goto out;
134 }
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300135
136 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
137 ctrl->bFormatIndex = data[2];
138 ctrl->bFrameIndex = data[3];
139 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
140 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
141 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
142 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
143 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
144 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
145 ctrl->dwMaxVideoFrameSize =
146 le32_to_cpu(get_unaligned((__le32 *)&data[18]));
147 ctrl->dwMaxPayloadTransferSize =
148 le32_to_cpu(get_unaligned((__le32 *)&data[22]));
149
150 if (size == 34) {
151 ctrl->dwClockFrequency =
152 le32_to_cpu(get_unaligned((__le32 *)&data[26]));
153 ctrl->bmFramingInfo = data[30];
154 ctrl->bPreferedVersion = data[31];
155 ctrl->bMinVersion = data[32];
156 ctrl->bMaxVersion = data[33];
157 } else {
158 ctrl->dwClockFrequency = video->dev->clock_frequency;
159 ctrl->bmFramingInfo = 0;
160 ctrl->bPreferedVersion = 0;
161 ctrl->bMinVersion = 0;
162 ctrl->bMaxVersion = 0;
163 }
164
165 /* Some broken devices return a null or wrong dwMaxVideoFrameSize.
166 * Try to get the value from the format and frame descriptor.
167 */
168 uvc_fixup_buffer_size(video, ctrl);
Laurent Pinchart44f00792008-11-08 19:14:50 -0300169 ret = 0;
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300170
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300171out:
172 kfree(data);
173 return ret;
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300174}
175
Laurent Pinchart44f00792008-11-08 19:14:50 -0300176static int uvc_set_video_ctrl(struct uvc_video_device *video,
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300177 struct uvc_streaming_control *ctrl, int probe)
178{
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300179 __u8 *data;
180 __u16 size;
181 int ret;
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300182
183 size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300184 data = kzalloc(size, GFP_KERNEL);
185 if (data == NULL)
186 return -ENOMEM;
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300187
188 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
189 data[2] = ctrl->bFormatIndex;
190 data[3] = ctrl->bFrameIndex;
191 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
192 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
193 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
194 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
195 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
196 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
197 /* Note: Some of the fields below are not required for IN devices (see
198 * UVC spec, 4.3.1.1), but we still copy them in case support for OUT
199 * devices is added in the future. */
200 put_unaligned(cpu_to_le32(ctrl->dwMaxVideoFrameSize),
201 (__le32 *)&data[18]);
202 put_unaligned(cpu_to_le32(ctrl->dwMaxPayloadTransferSize),
203 (__le32 *)&data[22]);
204
205 if (size == 34) {
206 put_unaligned(cpu_to_le32(ctrl->dwClockFrequency),
207 (__le32 *)&data[26]);
208 data[30] = ctrl->bmFramingInfo;
209 data[31] = ctrl->bPreferedVersion;
210 data[32] = ctrl->bMinVersion;
211 data[33] = ctrl->bMaxVersion;
212 }
213
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300214 ret = __uvc_query_ctrl(video->dev, SET_CUR, 0,
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300215 video->streaming->intfnum,
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300216 probe ? VS_PROBE_CONTROL : VS_COMMIT_CONTROL, data, size,
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300217 UVC_CTRL_STREAMING_TIMEOUT);
Laurent Pinchart44f00792008-11-08 19:14:50 -0300218 if (ret != size) {
219 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
220 "%d (exp. %u).\n", probe ? "probe" : "commit",
221 ret, size);
222 ret = -EIO;
223 }
Laurent Pinchart04793dd2008-07-31 17:11:12 -0300224
225 kfree(data);
226 return ret;
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300227}
228
229int uvc_probe_video(struct uvc_video_device *video,
230 struct uvc_streaming_control *probe)
231{
232 struct uvc_streaming_control probe_min, probe_max;
233 __u16 bandwidth;
234 unsigned int i;
235 int ret;
236
237 mutex_lock(&video->streaming->mutex);
238
239 /* Perform probing. The device should adjust the requested values
240 * according to its capabilities. However, some devices, namely the
241 * first generation UVC Logitech webcams, don't implement the Video
242 * Probe control properly, and just return the needed bandwidth. For
243 * that reason, if the needed bandwidth exceeds the maximum available
244 * bandwidth, try to lower the quality.
245 */
246 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
247 goto done;
248
249 /* Get the minimum and maximum values for compression settings. */
250 if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
251 ret = uvc_get_video_ctrl(video, &probe_min, 1, GET_MIN);
252 if (ret < 0)
253 goto done;
254 ret = uvc_get_video_ctrl(video, &probe_max, 1, GET_MAX);
255 if (ret < 0)
256 goto done;
257
258 probe->wCompQuality = probe_max.wCompQuality;
259 }
260
261 for (i = 0; i < 2; ++i) {
262 if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0 ||
263 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
264 goto done;
265
266 if (video->streaming->intf->num_altsetting == 1)
267 break;
268
269 bandwidth = probe->dwMaxPayloadTransferSize;
270 if (bandwidth <= video->streaming->maxpsize)
271 break;
272
273 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
274 ret = -ENOSPC;
275 goto done;
276 }
277
278 /* TODO: negotiate compression parameters */
279 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
280 probe->wPFrameRate = probe_min.wPFrameRate;
281 probe->wCompQuality = probe_max.wCompQuality;
282 probe->wCompWindowSize = probe_min.wCompWindowSize;
283 }
284
285done:
286 mutex_unlock(&video->streaming->mutex);
287 return ret;
288}
289
Laurent Pinchart44f00792008-11-08 19:14:50 -0300290int uvc_commit_video(struct uvc_video_device *video,
291 struct uvc_streaming_control *probe)
292{
293 return uvc_set_video_ctrl(video, probe, 0);
294}
295
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300296/* ------------------------------------------------------------------------
297 * Video codecs
298 */
299
300/* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
301#define UVC_STREAM_EOH (1 << 7)
302#define UVC_STREAM_ERR (1 << 6)
303#define UVC_STREAM_STI (1 << 5)
304#define UVC_STREAM_RES (1 << 4)
305#define UVC_STREAM_SCR (1 << 3)
306#define UVC_STREAM_PTS (1 << 2)
307#define UVC_STREAM_EOF (1 << 1)
308#define UVC_STREAM_FID (1 << 0)
309
310/* Video payload decoding is handled by uvc_video_decode_start(),
311 * uvc_video_decode_data() and uvc_video_decode_end().
312 *
313 * uvc_video_decode_start is called with URB data at the start of a bulk or
314 * isochronous payload. It processes header data and returns the header size
315 * in bytes if successful. If an error occurs, it returns a negative error
316 * code. The following error codes have special meanings.
317 *
318 * - EAGAIN informs the caller that the current video buffer should be marked
319 * as done, and that the function should be called again with the same data
320 * and a new video buffer. This is used when end of frame conditions can be
321 * reliably detected at the beginning of the next frame only.
322 *
323 * If an error other than -EAGAIN is returned, the caller will drop the current
324 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
325 * made until the next payload. -ENODATA can be used to drop the current
326 * payload if no other error code is appropriate.
327 *
328 * uvc_video_decode_data is called for every URB with URB data. It copies the
329 * data to the video buffer.
330 *
331 * uvc_video_decode_end is called with header data at the end of a bulk or
332 * isochronous payload. It performs any additional header data processing and
333 * returns 0 or a negative error code if an error occured. As header data have
334 * already been processed by uvc_video_decode_start, this functions isn't
335 * required to perform sanity checks a second time.
336 *
337 * For isochronous transfers where a payload is always transfered in a single
338 * URB, the three functions will be called in a row.
339 *
340 * To let the decoder process header data and update its internal state even
341 * when no video buffer is available, uvc_video_decode_start must be prepared
342 * to be called with a NULL buf parameter. uvc_video_decode_data and
343 * uvc_video_decode_end will never be called with a NULL buffer.
344 */
345static int uvc_video_decode_start(struct uvc_video_device *video,
346 struct uvc_buffer *buf, const __u8 *data, int len)
347{
348 __u8 fid;
349
350 /* Sanity checks:
351 * - packet must be at least 2 bytes long
352 * - bHeaderLength value must be at least 2 bytes (see above)
353 * - bHeaderLength value can't be larger than the packet size.
354 */
355 if (len < 2 || data[0] < 2 || data[0] > len)
356 return -EINVAL;
357
358 /* Skip payloads marked with the error bit ("error frames"). */
359 if (data[1] & UVC_STREAM_ERR) {
360 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
361 "set).\n");
362 return -ENODATA;
363 }
364
365 fid = data[1] & UVC_STREAM_FID;
366
367 /* Store the payload FID bit and return immediately when the buffer is
368 * NULL.
369 */
370 if (buf == NULL) {
371 video->last_fid = fid;
372 return -ENODATA;
373 }
374
375 /* Synchronize to the input stream by waiting for the FID bit to be
376 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
377 * queue->last_fid is initialized to -1, so the first isochronous
378 * frame will always be in sync.
379 *
380 * If the device doesn't toggle the FID bit, invert video->last_fid
381 * when the EOF bit is set to force synchronisation on the next packet.
382 */
383 if (buf->state != UVC_BUF_STATE_ACTIVE) {
384 if (fid == video->last_fid) {
385 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
386 "sync).\n");
387 if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
388 (data[1] & UVC_STREAM_EOF))
389 video->last_fid ^= UVC_STREAM_FID;
390 return -ENODATA;
391 }
392
393 /* TODO: Handle PTS and SCR. */
394 buf->state = UVC_BUF_STATE_ACTIVE;
395 }
396
397 /* Mark the buffer as done if we're at the beginning of a new frame.
398 * End of frame detection is better implemented by checking the EOF
399 * bit (FID bit toggling is delayed by one frame compared to the EOF
400 * bit), but some devices don't set the bit at end of frame (and the
401 * last payload can be lost anyway). We thus must check if the FID has
402 * been toggled.
403 *
404 * queue->last_fid is initialized to -1, so the first isochronous
405 * frame will never trigger an end of frame detection.
406 *
407 * Empty buffers (bytesused == 0) don't trigger end of frame detection
408 * as it doesn't make sense to return an empty buffer. This also
409 * avoids detecting and of frame conditions at FID toggling if the
410 * previous payload had the EOF bit set.
411 */
412 if (fid != video->last_fid && buf->buf.bytesused != 0) {
413 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
414 "toggled).\n");
415 buf->state = UVC_BUF_STATE_DONE;
416 return -EAGAIN;
417 }
418
419 video->last_fid = fid;
420
421 return data[0];
422}
423
424static void uvc_video_decode_data(struct uvc_video_device *video,
425 struct uvc_buffer *buf, const __u8 *data, int len)
426{
427 struct uvc_video_queue *queue = &video->queue;
428 unsigned int maxlen, nbytes;
429 void *mem;
430
431 if (len <= 0)
432 return;
433
434 /* Copy the video data to the buffer. */
435 maxlen = buf->buf.length - buf->buf.bytesused;
436 mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
437 nbytes = min((unsigned int)len, maxlen);
438 memcpy(mem, data, nbytes);
439 buf->buf.bytesused += nbytes;
440
441 /* Complete the current frame if the buffer size was exceeded. */
442 if (len > maxlen) {
443 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
444 buf->state = UVC_BUF_STATE_DONE;
445 }
446}
447
448static void uvc_video_decode_end(struct uvc_video_device *video,
449 struct uvc_buffer *buf, const __u8 *data, int len)
450{
451 /* Mark the buffer as done if the EOF marker is set. */
452 if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
453 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
454 if (data[0] == len)
455 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
456 buf->state = UVC_BUF_STATE_DONE;
457 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
458 video->last_fid ^= UVC_STREAM_FID;
459 }
460}
461
462/* ------------------------------------------------------------------------
463 * URB handling
464 */
465
466/*
467 * Completion handler for video URBs.
468 */
469static void uvc_video_decode_isoc(struct urb *urb,
470 struct uvc_video_device *video, struct uvc_buffer *buf)
471{
472 u8 *mem;
473 int ret, i;
474
475 for (i = 0; i < urb->number_of_packets; ++i) {
476 if (urb->iso_frame_desc[i].status < 0) {
477 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
478 "lost (%d).\n", urb->iso_frame_desc[i].status);
479 continue;
480 }
481
482 /* Decode the payload header. */
483 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
484 do {
485 ret = uvc_video_decode_start(video, buf, mem,
486 urb->iso_frame_desc[i].actual_length);
487 if (ret == -EAGAIN)
488 buf = uvc_queue_next_buffer(&video->queue, buf);
489 } while (ret == -EAGAIN);
490
491 if (ret < 0)
492 continue;
493
494 /* Decode the payload data. */
495 uvc_video_decode_data(video, buf, mem + ret,
496 urb->iso_frame_desc[i].actual_length - ret);
497
498 /* Process the header again. */
Laurent Pinchart08ebd002008-08-29 17:37:44 -0300499 uvc_video_decode_end(video, buf, mem,
500 urb->iso_frame_desc[i].actual_length);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300501
502 if (buf->state == UVC_BUF_STATE_DONE ||
503 buf->state == UVC_BUF_STATE_ERROR)
504 buf = uvc_queue_next_buffer(&video->queue, buf);
505 }
506}
507
508static void uvc_video_decode_bulk(struct urb *urb,
509 struct uvc_video_device *video, struct uvc_buffer *buf)
510{
511 u8 *mem;
512 int len, ret;
513
514 mem = urb->transfer_buffer;
515 len = urb->actual_length;
516 video->bulk.payload_size += len;
517
518 /* If the URB is the first of its payload, decode and save the
519 * header.
520 */
521 if (video->bulk.header_size == 0) {
522 do {
523 ret = uvc_video_decode_start(video, buf, mem, len);
524 if (ret == -EAGAIN)
525 buf = uvc_queue_next_buffer(&video->queue, buf);
526 } while (ret == -EAGAIN);
527
528 /* If an error occured skip the rest of the payload. */
529 if (ret < 0 || buf == NULL) {
530 video->bulk.skip_payload = 1;
531 return;
532 }
533
534 video->bulk.header_size = ret;
535 memcpy(video->bulk.header, mem, video->bulk.header_size);
536
537 mem += ret;
538 len -= ret;
539 }
540
541 /* The buffer queue might have been cancelled while a bulk transfer
542 * was in progress, so we can reach here with buf equal to NULL. Make
543 * sure buf is never dereferenced if NULL.
544 */
545
546 /* Process video data. */
547 if (!video->bulk.skip_payload && buf != NULL)
548 uvc_video_decode_data(video, buf, mem, len);
549
550 /* Detect the payload end by a URB smaller than the maximum size (or
551 * a payload size equal to the maximum) and process the header again.
552 */
553 if (urb->actual_length < urb->transfer_buffer_length ||
554 video->bulk.payload_size >= video->bulk.max_payload_size) {
555 if (!video->bulk.skip_payload && buf != NULL) {
556 uvc_video_decode_end(video, buf, video->bulk.header,
Laurent Pinchart08ebd002008-08-29 17:37:44 -0300557 video->bulk.payload_size);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300558 if (buf->state == UVC_BUF_STATE_DONE ||
559 buf->state == UVC_BUF_STATE_ERROR)
560 buf = uvc_queue_next_buffer(&video->queue, buf);
561 }
562
563 video->bulk.header_size = 0;
564 video->bulk.skip_payload = 0;
565 video->bulk.payload_size = 0;
566 }
567}
568
569static void uvc_video_complete(struct urb *urb)
570{
571 struct uvc_video_device *video = urb->context;
572 struct uvc_video_queue *queue = &video->queue;
573 struct uvc_buffer *buf = NULL;
574 unsigned long flags;
575 int ret;
576
577 switch (urb->status) {
578 case 0:
579 break;
580
581 default:
582 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
583 "completion handler.\n", urb->status);
584
585 case -ENOENT: /* usb_kill_urb() called. */
586 if (video->frozen)
587 return;
588
589 case -ECONNRESET: /* usb_unlink_urb() called. */
590 case -ESHUTDOWN: /* The endpoint is being disabled. */
591 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
592 return;
593 }
594
595 spin_lock_irqsave(&queue->irqlock, flags);
596 if (!list_empty(&queue->irqqueue))
597 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
598 queue);
599 spin_unlock_irqrestore(&queue->irqlock, flags);
600
601 video->decode(urb, video, buf);
602
603 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
604 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
605 ret);
606 }
607}
608
609/*
Laurent Pincharte01117c2008-07-04 00:36:21 -0300610 * Free transfer buffers.
611 */
612static void uvc_free_urb_buffers(struct uvc_video_device *video)
613{
614 unsigned int i;
615
616 for (i = 0; i < UVC_URBS; ++i) {
617 if (video->urb_buffer[i]) {
618 usb_buffer_free(video->dev->udev, video->urb_size,
619 video->urb_buffer[i], video->urb_dma[i]);
620 video->urb_buffer[i] = NULL;
621 }
622 }
623
624 video->urb_size = 0;
625}
626
627/*
628 * Allocate transfer buffers. This function can be called with buffers
629 * already allocated when resuming from suspend, in which case it will
630 * return without touching the buffers.
631 *
632 * Return 0 on success or -ENOMEM when out of memory.
633 */
634static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
635 unsigned int size)
636{
637 unsigned int i;
638
639 /* Buffers are already allocated, bail out. */
640 if (video->urb_size)
641 return 0;
642
643 for (i = 0; i < UVC_URBS; ++i) {
644 video->urb_buffer[i] = usb_buffer_alloc(video->dev->udev,
645 size, GFP_KERNEL, &video->urb_dma[i]);
646 if (video->urb_buffer[i] == NULL) {
647 uvc_free_urb_buffers(video);
648 return -ENOMEM;
649 }
650 }
651
652 video->urb_size = size;
653 return 0;
654}
655
656/*
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300657 * Uninitialize isochronous/bulk URBs and free transfer buffers.
658 */
Laurent Pincharte01117c2008-07-04 00:36:21 -0300659static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300660{
661 struct urb *urb;
662 unsigned int i;
663
664 for (i = 0; i < UVC_URBS; ++i) {
665 if ((urb = video->urb[i]) == NULL)
666 continue;
667
668 usb_kill_urb(urb);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300669 usb_free_urb(urb);
670 video->urb[i] = NULL;
671 }
Laurent Pincharte01117c2008-07-04 00:36:21 -0300672
673 if (free_buffers)
674 uvc_free_urb_buffers(video);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300675}
676
677/*
678 * Initialize isochronous URBs and allocate transfer buffers. The packet size
679 * is given by the endpoint.
680 */
681static int uvc_init_video_isoc(struct uvc_video_device *video,
Laurent Pinchart29135872008-07-04 00:35:26 -0300682 struct usb_host_endpoint *ep, gfp_t gfp_flags)
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300683{
684 struct urb *urb;
685 unsigned int npackets, i, j;
686 __u16 psize;
687 __u32 size;
688
689 /* Compute the number of isochronous packets to allocate by dividing
690 * the maximum video frame size by the packet size. Limit the result
691 * to UVC_MAX_ISO_PACKETS.
692 */
693 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
694 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
695
696 size = video->streaming->ctrl.dwMaxVideoFrameSize;
697 if (size > UVC_MAX_FRAME_SIZE)
698 return -EINVAL;
699
Julia Lawalle9e24ce2008-08-20 20:44:53 -0300700 npackets = DIV_ROUND_UP(size, psize);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300701 if (npackets > UVC_MAX_ISO_PACKETS)
702 npackets = UVC_MAX_ISO_PACKETS;
703
704 size = npackets * psize;
705
Laurent Pincharte01117c2008-07-04 00:36:21 -0300706 if (uvc_alloc_urb_buffers(video, size) < 0)
707 return -ENOMEM;
708
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300709 for (i = 0; i < UVC_URBS; ++i) {
Laurent Pinchart29135872008-07-04 00:35:26 -0300710 urb = usb_alloc_urb(npackets, gfp_flags);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300711 if (urb == NULL) {
Laurent Pincharte01117c2008-07-04 00:36:21 -0300712 uvc_uninit_video(video, 1);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300713 return -ENOMEM;
714 }
715
716 urb->dev = video->dev->udev;
717 urb->context = video;
718 urb->pipe = usb_rcvisocpipe(video->dev->udev,
719 ep->desc.bEndpointAddress);
720 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
721 urb->interval = ep->desc.bInterval;
722 urb->transfer_buffer = video->urb_buffer[i];
Laurent Pincharte01117c2008-07-04 00:36:21 -0300723 urb->transfer_dma = video->urb_dma[i];
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300724 urb->complete = uvc_video_complete;
725 urb->number_of_packets = npackets;
726 urb->transfer_buffer_length = size;
727
728 for (j = 0; j < npackets; ++j) {
729 urb->iso_frame_desc[j].offset = j * psize;
730 urb->iso_frame_desc[j].length = psize;
731 }
732
733 video->urb[i] = urb;
734 }
735
736 return 0;
737}
738
739/*
740 * Initialize bulk URBs and allocate transfer buffers. The packet size is
741 * given by the endpoint.
742 */
743static int uvc_init_video_bulk(struct uvc_video_device *video,
Laurent Pinchart29135872008-07-04 00:35:26 -0300744 struct usb_host_endpoint *ep, gfp_t gfp_flags)
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300745{
746 struct urb *urb;
747 unsigned int pipe, i;
748 __u16 psize;
749 __u32 size;
750
751 /* Compute the bulk URB size. Some devices set the maximum payload
752 * size to a value too high for memory-constrained devices. We must
753 * then transfer the payload accross multiple URBs. To be consistant
754 * with isochronous mode, allocate maximum UVC_MAX_ISO_PACKETS per bulk
755 * URB.
756 */
757 psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
758 size = video->streaming->ctrl.dwMaxPayloadTransferSize;
759 video->bulk.max_payload_size = size;
760 if (size > psize * UVC_MAX_ISO_PACKETS)
761 size = psize * UVC_MAX_ISO_PACKETS;
762
Laurent Pincharte01117c2008-07-04 00:36:21 -0300763 if (uvc_alloc_urb_buffers(video, size) < 0)
764 return -ENOMEM;
765
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300766 pipe = usb_rcvbulkpipe(video->dev->udev, ep->desc.bEndpointAddress);
767
768 for (i = 0; i < UVC_URBS; ++i) {
Laurent Pinchart29135872008-07-04 00:35:26 -0300769 urb = usb_alloc_urb(0, gfp_flags);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300770 if (urb == NULL) {
Laurent Pincharte01117c2008-07-04 00:36:21 -0300771 uvc_uninit_video(video, 1);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300772 return -ENOMEM;
773 }
774
775 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
776 video->urb_buffer[i], size, uvc_video_complete,
777 video);
778 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
Laurent Pincharte01117c2008-07-04 00:36:21 -0300779 urb->transfer_dma = video->urb_dma[i];
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300780
781 video->urb[i] = urb;
782 }
783
784 return 0;
785}
786
787/*
788 * Initialize isochronous/bulk URBs and allocate transfer buffers.
789 */
Laurent Pinchart29135872008-07-04 00:35:26 -0300790static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300791{
792 struct usb_interface *intf = video->streaming->intf;
793 struct usb_host_interface *alts;
794 struct usb_host_endpoint *ep = NULL;
795 int intfnum = video->streaming->intfnum;
796 unsigned int bandwidth, psize, i;
797 int ret;
798
799 video->last_fid = -1;
800 video->bulk.header_size = 0;
801 video->bulk.skip_payload = 0;
802 video->bulk.payload_size = 0;
803
804 if (intf->num_altsetting > 1) {
805 /* Isochronous endpoint, select the alternate setting. */
806 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
807
808 if (bandwidth == 0) {
809 uvc_printk(KERN_WARNING, "device %s requested null "
810 "bandwidth, defaulting to lowest.\n",
811 video->vdev->name);
812 bandwidth = 1;
813 }
814
815 for (i = 0; i < intf->num_altsetting; ++i) {
816 alts = &intf->altsetting[i];
817 ep = uvc_find_endpoint(alts,
818 video->streaming->header.bEndpointAddress);
819 if (ep == NULL)
820 continue;
821
822 /* Check if the bandwidth is high enough. */
823 psize = le16_to_cpu(ep->desc.wMaxPacketSize);
824 psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
825 if (psize >= bandwidth)
826 break;
827 }
828
829 if (i >= intf->num_altsetting)
830 return -EIO;
831
832 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
833 return ret;
834
Laurent Pinchart29135872008-07-04 00:35:26 -0300835 ret = uvc_init_video_isoc(video, ep, gfp_flags);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300836 } else {
837 /* Bulk endpoint, proceed to URB initialization. */
838 ep = uvc_find_endpoint(&intf->altsetting[0],
839 video->streaming->header.bEndpointAddress);
840 if (ep == NULL)
841 return -EIO;
842
Laurent Pinchart29135872008-07-04 00:35:26 -0300843 ret = uvc_init_video_bulk(video, ep, gfp_flags);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300844 }
845
846 if (ret < 0)
847 return ret;
848
849 /* Submit the URBs. */
850 for (i = 0; i < UVC_URBS; ++i) {
Laurent Pinchart29135872008-07-04 00:35:26 -0300851 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300852 uvc_printk(KERN_ERR, "Failed to submit URB %u "
853 "(%d).\n", i, ret);
Laurent Pincharte01117c2008-07-04 00:36:21 -0300854 uvc_uninit_video(video, 1);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300855 return ret;
856 }
857 }
858
859 return 0;
860}
861
862/* --------------------------------------------------------------------------
863 * Suspend/resume
864 */
865
866/*
867 * Stop streaming without disabling the video queue.
868 *
869 * To let userspace applications resume without trouble, we must not touch the
870 * video buffers in any way. We mark the device as frozen to make sure the URB
871 * completion handler won't try to cancel the queue when we kill the URBs.
872 */
873int uvc_video_suspend(struct uvc_video_device *video)
874{
875 if (!uvc_queue_streaming(&video->queue))
876 return 0;
877
878 video->frozen = 1;
Laurent Pincharte01117c2008-07-04 00:36:21 -0300879 uvc_uninit_video(video, 0);
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300880 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
881 return 0;
882}
883
884/*
885 * Reconfigure the video interface and restart streaming if it was enable
886 * before suspend.
887 *
888 * If an error occurs, disable the video queue. This will wake all pending
889 * buffers, making sure userspace applications are notified of the problem
890 * instead of waiting forever.
891 */
892int uvc_video_resume(struct uvc_video_device *video)
893{
894 int ret;
895
896 video->frozen = 0;
897
898 if ((ret = uvc_set_video_ctrl(video, &video->streaming->ctrl, 0)) < 0) {
899 uvc_queue_enable(&video->queue, 0);
900 return ret;
901 }
902
903 if (!uvc_queue_streaming(&video->queue))
904 return 0;
905
Laurent Pinchart29135872008-07-04 00:35:26 -0300906 if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
Laurent Pinchartc0efd232008-06-30 15:04:50 -0300907 uvc_queue_enable(&video->queue, 0);
908
909 return ret;
910}
911
912/* ------------------------------------------------------------------------
913 * Video device
914 */
915
916/*
917 * Initialize the UVC video device by retrieving the default format and
918 * committing it.
919 *
920 * Some cameras (namely the Fuji Finepix) set the format and frame
921 * indexes to zero. The UVC standard doesn't clearly make this a spec
922 * violation, so try to silently fix the values if possible.
923 *
924 * This function is called before registering the device with V4L.
925 */
926int uvc_video_init(struct uvc_video_device *video)
927{
928 struct uvc_streaming_control *probe = &video->streaming->ctrl;
929 struct uvc_format *format = NULL;
930 struct uvc_frame *frame = NULL;
931 unsigned int i;
932 int ret;
933
934 if (video->streaming->nformats == 0) {
935 uvc_printk(KERN_INFO, "No supported video formats found.\n");
936 return -EINVAL;
937 }
938
939 /* Alternate setting 0 should be the default, yet the XBox Live Vision
940 * Cam (and possibly other devices) crash or otherwise misbehave if
941 * they don't receive a SET_INTERFACE request before any other video
942 * control request.
943 */
944 usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
945
946 /* Some webcams don't suport GET_DEF request on the probe control. We
947 * fall back to GET_CUR if GET_DEF fails.
948 */
949 if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_DEF)) < 0 &&
950 (ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
951 return ret;
952
953 /* Check if the default format descriptor exists. Use the first
954 * available format otherwise.
955 */
956 for (i = video->streaming->nformats; i > 0; --i) {
957 format = &video->streaming->format[i-1];
958 if (format->index == probe->bFormatIndex)
959 break;
960 }
961
962 if (format->nframes == 0) {
963 uvc_printk(KERN_INFO, "No frame descriptor found for the "
964 "default format.\n");
965 return -EINVAL;
966 }
967
968 /* Zero bFrameIndex might be correct. Stream-based formats (including
969 * MPEG-2 TS and DV) do not support frames but have a dummy frame
970 * descriptor with bFrameIndex set to zero. If the default frame
971 * descriptor is not found, use the first avalable frame.
972 */
973 for (i = format->nframes; i > 0; --i) {
974 frame = &format->frame[i-1];
975 if (frame->bFrameIndex == probe->bFrameIndex)
976 break;
977 }
978
979 /* Commit the default settings. */
980 probe->bFormatIndex = format->index;
981 probe->bFrameIndex = frame->bFrameIndex;
982 if ((ret = uvc_set_video_ctrl(video, probe, 0)) < 0)
983 return ret;
984
985 video->streaming->cur_format = format;
986 video->streaming->cur_frame = frame;
987 atomic_set(&video->active, 0);
988
989 /* Select the video decoding function */
990 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
991 video->decode = uvc_video_decode_isight;
992 else if (video->streaming->intf->num_altsetting > 1)
993 video->decode = uvc_video_decode_isoc;
994 else
995 video->decode = uvc_video_decode_bulk;
996
997 return 0;
998}
999
1000/*
1001 * Enable or disable the video stream.
1002 */
1003int uvc_video_enable(struct uvc_video_device *video, int enable)
1004{
1005 int ret;
1006
1007 if (!enable) {
Laurent Pincharte01117c2008-07-04 00:36:21 -03001008 uvc_uninit_video(video, 1);
Laurent Pinchartc0efd232008-06-30 15:04:50 -03001009 usb_set_interface(video->dev->udev,
1010 video->streaming->intfnum, 0);
1011 uvc_queue_enable(&video->queue, 0);
1012 return 0;
1013 }
1014
Laurent Pinchartd63beb92008-09-15 22:24:29 -03001015 if (video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED)
1016 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1017 else
1018 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1019
Laurent Pinchartc0efd232008-06-30 15:04:50 -03001020 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1021 return ret;
1022
Laurent Pinchart29135872008-07-04 00:35:26 -03001023 return uvc_init_video(video, GFP_KERNEL);
Laurent Pinchartc0efd232008-06-30 15:04:50 -03001024}
Hans Verkuilf87086e2008-07-18 00:50:58 -03001025