]> bbs.cooldavid.org Git - net-next-2.6.git/blob - drivers/media/video/uvc/uvc_video.c
68468309932dec4a629e8965f37cba62e5576c83
[net-next-2.6.git] / drivers / media / video / uvc / uvc_video.c
1 /*
2  *      uvc_video.c  --  USB Video Class driver - Video handling
3  *
4  *      Copyright (C) 2005-2009
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/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>
23
24 #include <media/v4l2-common.h>
25
26 #include "uvcvideo.h"
27
28 /* ------------------------------------------------------------------------
29  * UVC Controls
30  */
31
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)
35 {
36         __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
37         unsigned int pipe;
38
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;
42
43         return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
44                         unit << 8 | intfnum, data, size, timeout);
45 }
46
47 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
48                         __u8 intfnum, __u8 cs, void *data, __u16 size)
49 {
50         int ret;
51
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;
59         }
60
61         return 0;
62 }
63
64 static void uvc_fixup_video_ctrl(struct uvc_video_device *video,
65         struct uvc_streaming_control *ctrl)
66 {
67         struct uvc_format *format;
68         struct uvc_frame *frame = NULL;
69         unsigned int i;
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         for (i = 0; i < format->nframes; ++i) {
78                 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
79                         frame = &format->frame[i];
80                         break;
81                 }
82         }
83
84         if (frame == NULL)
85                 return;
86
87         if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
88              (ctrl->dwMaxVideoFrameSize == 0 &&
89               video->dev->uvc_version < 0x0110))
90                 ctrl->dwMaxVideoFrameSize =
91                         frame->dwMaxVideoFrameBufferSize;
92
93         if (video->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
94             video->streaming->intf->num_altsetting > 1) {
95                 u32 interval;
96                 u32 bandwidth;
97
98                 interval = (ctrl->dwFrameInterval > 100000)
99                          ? ctrl->dwFrameInterval
100                          : frame->dwFrameInterval[0];
101
102                 /* Compute a bandwidth estimation by multiplying the frame
103                  * size by the number of video frames per second, divide the
104                  * result by the number of USB frames (or micro-frames for
105                  * high-speed devices) per second and add the UVC header size
106                  * (assumed to be 12 bytes long).
107                  */
108                 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
109                 bandwidth *= 10000000 / interval + 1;
110                 bandwidth /= 1000;
111                 if (video->dev->udev->speed == USB_SPEED_HIGH)
112                         bandwidth /= 8;
113                 bandwidth += 12;
114
115                 ctrl->dwMaxPayloadTransferSize = bandwidth;
116         }
117 }
118
119 static int uvc_get_video_ctrl(struct uvc_video_device *video,
120         struct uvc_streaming_control *ctrl, int probe, __u8 query)
121 {
122         __u8 *data;
123         __u16 size;
124         int ret;
125
126         size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
127         data = kmalloc(size, GFP_KERNEL);
128         if (data == NULL)
129                 return -ENOMEM;
130
131         if ((video->dev->quirks & UVC_QUIRK_PROBE_DEF) && query == UVC_GET_DEF)
132                 return -EIO;
133
134         ret = __uvc_query_ctrl(video->dev, query, 0, video->streaming->intfnum,
135                 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
136                 size, UVC_CTRL_STREAMING_TIMEOUT);
137
138         if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
139                 /* Some cameras, mostly based on Bison Electronics chipsets,
140                  * answer a GET_MIN or GET_MAX request with the wCompQuality
141                  * field only.
142                  */
143                 uvc_warn_once(video->dev, UVC_WARN_MINMAX, "UVC non "
144                         "compliance - GET_MIN/MAX(PROBE) incorrectly "
145                         "supported. Enabling workaround.\n");
146                 memset(ctrl, 0, sizeof ctrl);
147                 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
148                 ret = 0;
149                 goto out;
150         } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
151                 /* Many cameras don't support the GET_DEF request on their
152                  * video probe control. Warn once and return, the caller will
153                  * fall back to GET_CUR.
154                  */
155                 uvc_warn_once(video->dev, UVC_WARN_PROBE_DEF, "UVC non "
156                         "compliance - GET_DEF(PROBE) not supported. "
157                         "Enabling workaround.\n");
158                 ret = -EIO;
159                 goto out;
160         } else if (ret != size) {
161                 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
162                         "%d (exp. %u).\n", query, probe ? "probe" : "commit",
163                         ret, size);
164                 ret = -EIO;
165                 goto out;
166         }
167
168         ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
169         ctrl->bFormatIndex = data[2];
170         ctrl->bFrameIndex = data[3];
171         ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
172         ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
173         ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
174         ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
175         ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
176         ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
177         ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
178         ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
179
180         if (size == 34) {
181                 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
182                 ctrl->bmFramingInfo = data[30];
183                 ctrl->bPreferedVersion = data[31];
184                 ctrl->bMinVersion = data[32];
185                 ctrl->bMaxVersion = data[33];
186         } else {
187                 ctrl->dwClockFrequency = video->dev->clock_frequency;
188                 ctrl->bmFramingInfo = 0;
189                 ctrl->bPreferedVersion = 0;
190                 ctrl->bMinVersion = 0;
191                 ctrl->bMaxVersion = 0;
192         }
193
194         /* Some broken devices return null or wrong dwMaxVideoFrameSize and
195          * dwMaxPayloadTransferSize fields. Try to get the value from the
196          * format and frame descriptors.
197          */
198         uvc_fixup_video_ctrl(video, ctrl);
199         ret = 0;
200
201 out:
202         kfree(data);
203         return ret;
204 }
205
206 static int uvc_set_video_ctrl(struct uvc_video_device *video,
207         struct uvc_streaming_control *ctrl, int probe)
208 {
209         __u8 *data;
210         __u16 size;
211         int ret;
212
213         size = video->dev->uvc_version >= 0x0110 ? 34 : 26;
214         data = kzalloc(size, GFP_KERNEL);
215         if (data == NULL)
216                 return -ENOMEM;
217
218         *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
219         data[2] = ctrl->bFormatIndex;
220         data[3] = ctrl->bFrameIndex;
221         *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
222         *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
223         *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
224         *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
225         *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
226         *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
227         put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
228         put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
229
230         if (size == 34) {
231                 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
232                 data[30] = ctrl->bmFramingInfo;
233                 data[31] = ctrl->bPreferedVersion;
234                 data[32] = ctrl->bMinVersion;
235                 data[33] = ctrl->bMaxVersion;
236         }
237
238         ret = __uvc_query_ctrl(video->dev, UVC_SET_CUR, 0,
239                 video->streaming->intfnum,
240                 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
241                 size, UVC_CTRL_STREAMING_TIMEOUT);
242         if (ret != size) {
243                 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
244                         "%d (exp. %u).\n", probe ? "probe" : "commit",
245                         ret, size);
246                 ret = -EIO;
247         }
248
249         kfree(data);
250         return ret;
251 }
252
253 int uvc_probe_video(struct uvc_video_device *video,
254         struct uvc_streaming_control *probe)
255 {
256         struct uvc_streaming_control probe_min, probe_max;
257         __u16 bandwidth;
258         unsigned int i;
259         int ret;
260
261         mutex_lock(&video->streaming->mutex);
262
263         /* Perform probing. The device should adjust the requested values
264          * according to its capabilities. However, some devices, namely the
265          * first generation UVC Logitech webcams, don't implement the Video
266          * Probe control properly, and just return the needed bandwidth. For
267          * that reason, if the needed bandwidth exceeds the maximum available
268          * bandwidth, try to lower the quality.
269          */
270         if ((ret = uvc_set_video_ctrl(video, probe, 1)) < 0)
271                 goto done;
272
273         /* Get the minimum and maximum values for compression settings. */
274         if (!(video->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
275                 ret = uvc_get_video_ctrl(video, &probe_min, 1, UVC_GET_MIN);
276                 if (ret < 0)
277                         goto done;
278                 ret = uvc_get_video_ctrl(video, &probe_max, 1, UVC_GET_MAX);
279                 if (ret < 0)
280                         goto done;
281
282                 probe->wCompQuality = probe_max.wCompQuality;
283         }
284
285         for (i = 0; i < 2; ++i) {
286                 ret = uvc_set_video_ctrl(video, probe, 1);
287                 if (ret < 0)
288                         goto done;
289                 ret = uvc_get_video_ctrl(video, probe, 1, UVC_GET_CUR);
290                 if (ret < 0)
291                         goto done;
292
293                 if (video->streaming->intf->num_altsetting == 1)
294                         break;
295
296                 bandwidth = probe->dwMaxPayloadTransferSize;
297                 if (bandwidth <= video->streaming->maxpsize)
298                         break;
299
300                 if (video->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
301                         ret = -ENOSPC;
302                         goto done;
303                 }
304
305                 /* TODO: negotiate compression parameters */
306                 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
307                 probe->wPFrameRate = probe_min.wPFrameRate;
308                 probe->wCompQuality = probe_max.wCompQuality;
309                 probe->wCompWindowSize = probe_min.wCompWindowSize;
310         }
311
312 done:
313         mutex_unlock(&video->streaming->mutex);
314         return ret;
315 }
316
317 int uvc_commit_video(struct uvc_video_device *video,
318         struct uvc_streaming_control *probe)
319 {
320         return uvc_set_video_ctrl(video, probe, 0);
321 }
322
323 /* ------------------------------------------------------------------------
324  * Video codecs
325  */
326
327 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
328 #define UVC_STREAM_EOH  (1 << 7)
329 #define UVC_STREAM_ERR  (1 << 6)
330 #define UVC_STREAM_STI  (1 << 5)
331 #define UVC_STREAM_RES  (1 << 4)
332 #define UVC_STREAM_SCR  (1 << 3)
333 #define UVC_STREAM_PTS  (1 << 2)
334 #define UVC_STREAM_EOF  (1 << 1)
335 #define UVC_STREAM_FID  (1 << 0)
336
337 /* Video payload decoding is handled by uvc_video_decode_start(),
338  * uvc_video_decode_data() and uvc_video_decode_end().
339  *
340  * uvc_video_decode_start is called with URB data at the start of a bulk or
341  * isochronous payload. It processes header data and returns the header size
342  * in bytes if successful. If an error occurs, it returns a negative error
343  * code. The following error codes have special meanings.
344  *
345  * - EAGAIN informs the caller that the current video buffer should be marked
346  *   as done, and that the function should be called again with the same data
347  *   and a new video buffer. This is used when end of frame conditions can be
348  *   reliably detected at the beginning of the next frame only.
349  *
350  * If an error other than -EAGAIN is returned, the caller will drop the current
351  * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
352  * made until the next payload. -ENODATA can be used to drop the current
353  * payload if no other error code is appropriate.
354  *
355  * uvc_video_decode_data is called for every URB with URB data. It copies the
356  * data to the video buffer.
357  *
358  * uvc_video_decode_end is called with header data at the end of a bulk or
359  * isochronous payload. It performs any additional header data processing and
360  * returns 0 or a negative error code if an error occured. As header data have
361  * already been processed by uvc_video_decode_start, this functions isn't
362  * required to perform sanity checks a second time.
363  *
364  * For isochronous transfers where a payload is always transfered in a single
365  * URB, the three functions will be called in a row.
366  *
367  * To let the decoder process header data and update its internal state even
368  * when no video buffer is available, uvc_video_decode_start must be prepared
369  * to be called with a NULL buf parameter. uvc_video_decode_data and
370  * uvc_video_decode_end will never be called with a NULL buffer.
371  */
372 static int uvc_video_decode_start(struct uvc_video_device *video,
373                 struct uvc_buffer *buf, const __u8 *data, int len)
374 {
375         __u8 fid;
376
377         /* Sanity checks:
378          * - packet must be at least 2 bytes long
379          * - bHeaderLength value must be at least 2 bytes (see above)
380          * - bHeaderLength value can't be larger than the packet size.
381          */
382         if (len < 2 || data[0] < 2 || data[0] > len)
383                 return -EINVAL;
384
385         /* Skip payloads marked with the error bit ("error frames"). */
386         if (data[1] & UVC_STREAM_ERR) {
387                 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
388                           "set).\n");
389                 return -ENODATA;
390         }
391
392         fid = data[1] & UVC_STREAM_FID;
393
394         /* Store the payload FID bit and return immediately when the buffer is
395          * NULL.
396          */
397         if (buf == NULL) {
398                 video->last_fid = fid;
399                 return -ENODATA;
400         }
401
402         /* Synchronize to the input stream by waiting for the FID bit to be
403          * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
404          * video->last_fid is initialized to -1, so the first isochronous
405          * frame will always be in sync.
406          *
407          * If the device doesn't toggle the FID bit, invert video->last_fid
408          * when the EOF bit is set to force synchronisation on the next packet.
409          */
410         if (buf->state != UVC_BUF_STATE_ACTIVE) {
411                 if (fid == video->last_fid) {
412                         uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
413                                 "sync).\n");
414                         if ((video->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
415                             (data[1] & UVC_STREAM_EOF))
416                                 video->last_fid ^= UVC_STREAM_FID;
417                         return -ENODATA;
418                 }
419
420                 /* TODO: Handle PTS and SCR. */
421                 buf->state = UVC_BUF_STATE_ACTIVE;
422         }
423
424         /* Mark the buffer as done if we're at the beginning of a new frame.
425          * End of frame detection is better implemented by checking the EOF
426          * bit (FID bit toggling is delayed by one frame compared to the EOF
427          * bit), but some devices don't set the bit at end of frame (and the
428          * last payload can be lost anyway). We thus must check if the FID has
429          * been toggled.
430          *
431          * video->last_fid is initialized to -1, so the first isochronous
432          * frame will never trigger an end of frame detection.
433          *
434          * Empty buffers (bytesused == 0) don't trigger end of frame detection
435          * as it doesn't make sense to return an empty buffer. This also
436          * avoids detecting end of frame conditions at FID toggling if the
437          * previous payload had the EOF bit set.
438          */
439         if (fid != video->last_fid && buf->buf.bytesused != 0) {
440                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
441                                 "toggled).\n");
442                 buf->state = UVC_BUF_STATE_DONE;
443                 return -EAGAIN;
444         }
445
446         video->last_fid = fid;
447
448         return data[0];
449 }
450
451 static void uvc_video_decode_data(struct uvc_video_device *video,
452                 struct uvc_buffer *buf, const __u8 *data, int len)
453 {
454         struct uvc_video_queue *queue = &video->queue;
455         unsigned int maxlen, nbytes;
456         void *mem;
457
458         if (len <= 0)
459                 return;
460
461         /* Copy the video data to the buffer. */
462         maxlen = buf->buf.length - buf->buf.bytesused;
463         mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
464         nbytes = min((unsigned int)len, maxlen);
465         memcpy(mem, data, nbytes);
466         buf->buf.bytesused += nbytes;
467
468         /* Complete the current frame if the buffer size was exceeded. */
469         if (len > maxlen) {
470                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
471                 buf->state = UVC_BUF_STATE_DONE;
472         }
473 }
474
475 static void uvc_video_decode_end(struct uvc_video_device *video,
476                 struct uvc_buffer *buf, const __u8 *data, int len)
477 {
478         /* Mark the buffer as done if the EOF marker is set. */
479         if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
480                 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
481                 if (data[0] == len)
482                         uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
483                 buf->state = UVC_BUF_STATE_DONE;
484                 if (video->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
485                         video->last_fid ^= UVC_STREAM_FID;
486         }
487 }
488
489 /* Video payload encoding is handled by uvc_video_encode_header() and
490  * uvc_video_encode_data(). Only bulk transfers are currently supported.
491  *
492  * uvc_video_encode_header is called at the start of a payload. It adds header
493  * data to the transfer buffer and returns the header size. As the only known
494  * UVC output device transfers a whole frame in a single payload, the EOF bit
495  * is always set in the header.
496  *
497  * uvc_video_encode_data is called for every URB and copies the data from the
498  * video buffer to the transfer buffer.
499  */
500 static int uvc_video_encode_header(struct uvc_video_device *video,
501                 struct uvc_buffer *buf, __u8 *data, int len)
502 {
503         data[0] = 2;    /* Header length */
504         data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
505                 | (video->last_fid & UVC_STREAM_FID);
506         return 2;
507 }
508
509 static int uvc_video_encode_data(struct uvc_video_device *video,
510                 struct uvc_buffer *buf, __u8 *data, int len)
511 {
512         struct uvc_video_queue *queue = &video->queue;
513         unsigned int nbytes;
514         void *mem;
515
516         /* Copy video data to the URB buffer. */
517         mem = queue->mem + buf->buf.m.offset + queue->buf_used;
518         nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
519         nbytes = min(video->bulk.max_payload_size - video->bulk.payload_size,
520                         nbytes);
521         memcpy(data, mem, nbytes);
522
523         queue->buf_used += nbytes;
524
525         return nbytes;
526 }
527
528 /* ------------------------------------------------------------------------
529  * URB handling
530  */
531
532 /*
533  * Completion handler for video URBs.
534  */
535 static void uvc_video_decode_isoc(struct urb *urb,
536         struct uvc_video_device *video, struct uvc_buffer *buf)
537 {
538         u8 *mem;
539         int ret, i;
540
541         for (i = 0; i < urb->number_of_packets; ++i) {
542                 if (urb->iso_frame_desc[i].status < 0) {
543                         uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
544                                 "lost (%d).\n", urb->iso_frame_desc[i].status);
545                         continue;
546                 }
547
548                 /* Decode the payload header. */
549                 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
550                 do {
551                         ret = uvc_video_decode_start(video, buf, mem,
552                                 urb->iso_frame_desc[i].actual_length);
553                         if (ret == -EAGAIN)
554                                 buf = uvc_queue_next_buffer(&video->queue, buf);
555                 } while (ret == -EAGAIN);
556
557                 if (ret < 0)
558                         continue;
559
560                 /* Decode the payload data. */
561                 uvc_video_decode_data(video, buf, mem + ret,
562                         urb->iso_frame_desc[i].actual_length - ret);
563
564                 /* Process the header again. */
565                 uvc_video_decode_end(video, buf, mem,
566                         urb->iso_frame_desc[i].actual_length);
567
568                 if (buf->state == UVC_BUF_STATE_DONE ||
569                     buf->state == UVC_BUF_STATE_ERROR)
570                         buf = uvc_queue_next_buffer(&video->queue, buf);
571         }
572 }
573
574 static void uvc_video_decode_bulk(struct urb *urb,
575         struct uvc_video_device *video, struct uvc_buffer *buf)
576 {
577         u8 *mem;
578         int len, ret;
579
580         if (urb->actual_length == 0)
581                 return;
582
583         mem = urb->transfer_buffer;
584         len = urb->actual_length;
585         video->bulk.payload_size += len;
586
587         /* If the URB is the first of its payload, decode and save the
588          * header.
589          */
590         if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
591                 do {
592                         ret = uvc_video_decode_start(video, buf, mem, len);
593                         if (ret == -EAGAIN)
594                                 buf = uvc_queue_next_buffer(&video->queue, buf);
595                 } while (ret == -EAGAIN);
596
597                 /* If an error occured skip the rest of the payload. */
598                 if (ret < 0 || buf == NULL) {
599                         video->bulk.skip_payload = 1;
600                 } else {
601                         memcpy(video->bulk.header, mem, ret);
602                         video->bulk.header_size = ret;
603
604                         mem += ret;
605                         len -= ret;
606                 }
607         }
608
609         /* The buffer queue might have been cancelled while a bulk transfer
610          * was in progress, so we can reach here with buf equal to NULL. Make
611          * sure buf is never dereferenced if NULL.
612          */
613
614         /* Process video data. */
615         if (!video->bulk.skip_payload && buf != NULL)
616                 uvc_video_decode_data(video, buf, mem, len);
617
618         /* Detect the payload end by a URB smaller than the maximum size (or
619          * a payload size equal to the maximum) and process the header again.
620          */
621         if (urb->actual_length < urb->transfer_buffer_length ||
622             video->bulk.payload_size >= video->bulk.max_payload_size) {
623                 if (!video->bulk.skip_payload && buf != NULL) {
624                         uvc_video_decode_end(video, buf, video->bulk.header,
625                                 video->bulk.payload_size);
626                         if (buf->state == UVC_BUF_STATE_DONE ||
627                             buf->state == UVC_BUF_STATE_ERROR)
628                                 buf = uvc_queue_next_buffer(&video->queue, buf);
629                 }
630
631                 video->bulk.header_size = 0;
632                 video->bulk.skip_payload = 0;
633                 video->bulk.payload_size = 0;
634         }
635 }
636
637 static void uvc_video_encode_bulk(struct urb *urb,
638         struct uvc_video_device *video, struct uvc_buffer *buf)
639 {
640         u8 *mem = urb->transfer_buffer;
641         int len = video->urb_size, ret;
642
643         if (buf == NULL) {
644                 urb->transfer_buffer_length = 0;
645                 return;
646         }
647
648         /* If the URB is the first of its payload, add the header. */
649         if (video->bulk.header_size == 0) {
650                 ret = uvc_video_encode_header(video, buf, mem, len);
651                 video->bulk.header_size = ret;
652                 video->bulk.payload_size += ret;
653                 mem += ret;
654                 len -= ret;
655         }
656
657         /* Process video data. */
658         ret = uvc_video_encode_data(video, buf, mem, len);
659
660         video->bulk.payload_size += ret;
661         len -= ret;
662
663         if (buf->buf.bytesused == video->queue.buf_used ||
664             video->bulk.payload_size == video->bulk.max_payload_size) {
665                 if (buf->buf.bytesused == video->queue.buf_used) {
666                         video->queue.buf_used = 0;
667                         buf->state = UVC_BUF_STATE_DONE;
668                         uvc_queue_next_buffer(&video->queue, buf);
669                         video->last_fid ^= UVC_STREAM_FID;
670                 }
671
672                 video->bulk.header_size = 0;
673                 video->bulk.payload_size = 0;
674         }
675
676         urb->transfer_buffer_length = video->urb_size - len;
677 }
678
679 static void uvc_video_complete(struct urb *urb)
680 {
681         struct uvc_video_device *video = urb->context;
682         struct uvc_video_queue *queue = &video->queue;
683         struct uvc_buffer *buf = NULL;
684         unsigned long flags;
685         int ret;
686
687         switch (urb->status) {
688         case 0:
689                 break;
690
691         default:
692                 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
693                         "completion handler.\n", urb->status);
694
695         case -ENOENT:           /* usb_kill_urb() called. */
696                 if (video->frozen)
697                         return;
698
699         case -ECONNRESET:       /* usb_unlink_urb() called. */
700         case -ESHUTDOWN:        /* The endpoint is being disabled. */
701                 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
702                 return;
703         }
704
705         spin_lock_irqsave(&queue->irqlock, flags);
706         if (!list_empty(&queue->irqqueue))
707                 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
708                                        queue);
709         spin_unlock_irqrestore(&queue->irqlock, flags);
710
711         video->decode(urb, video, buf);
712
713         if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
714                 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
715                         ret);
716         }
717 }
718
719 /*
720  * Free transfer buffers.
721  */
722 static void uvc_free_urb_buffers(struct uvc_video_device *video)
723 {
724         unsigned int i;
725
726         for (i = 0; i < UVC_URBS; ++i) {
727                 if (video->urb_buffer[i]) {
728                         usb_buffer_free(video->dev->udev, video->urb_size,
729                                 video->urb_buffer[i], video->urb_dma[i]);
730                         video->urb_buffer[i] = NULL;
731                 }
732         }
733
734         video->urb_size = 0;
735 }
736
737 /*
738  * Allocate transfer buffers. This function can be called with buffers
739  * already allocated when resuming from suspend, in which case it will
740  * return without touching the buffers.
741  *
742  * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
743  * system is too low on memory try successively smaller numbers of packets
744  * until allocation succeeds.
745  *
746  * Return the number of allocated packets on success or 0 when out of memory.
747  */
748 static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
749         unsigned int size, unsigned int psize, gfp_t gfp_flags)
750 {
751         unsigned int npackets;
752         unsigned int i;
753
754         /* Buffers are already allocated, bail out. */
755         if (video->urb_size)
756                 return video->urb_size / psize;
757
758         /* Compute the number of packets. Bulk endpoints might transfer UVC
759          * payloads accross multiple URBs.
760          */
761         npackets = DIV_ROUND_UP(size, psize);
762         if (npackets > UVC_MAX_PACKETS)
763                 npackets = UVC_MAX_PACKETS;
764
765         /* Retry allocations until one succeed. */
766         for (; npackets > 1; npackets /= 2) {
767                 for (i = 0; i < UVC_URBS; ++i) {
768                         video->urb_buffer[i] = usb_buffer_alloc(
769                                 video->dev->udev, psize * npackets,
770                                 gfp_flags | __GFP_NOWARN, &video->urb_dma[i]);
771                         if (!video->urb_buffer[i]) {
772                                 uvc_free_urb_buffers(video);
773                                 break;
774                         }
775                 }
776
777                 if (i == UVC_URBS) {
778                         video->urb_size = psize * npackets;
779                         return npackets;
780                 }
781         }
782
783         return 0;
784 }
785
786 /*
787  * Uninitialize isochronous/bulk URBs and free transfer buffers.
788  */
789 static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
790 {
791         struct urb *urb;
792         unsigned int i;
793
794         for (i = 0; i < UVC_URBS; ++i) {
795                 if ((urb = video->urb[i]) == NULL)
796                         continue;
797
798                 usb_kill_urb(urb);
799                 usb_free_urb(urb);
800                 video->urb[i] = NULL;
801         }
802
803         if (free_buffers)
804                 uvc_free_urb_buffers(video);
805 }
806
807 /*
808  * Initialize isochronous URBs and allocate transfer buffers. The packet size
809  * is given by the endpoint.
810  */
811 static int uvc_init_video_isoc(struct uvc_video_device *video,
812         struct usb_host_endpoint *ep, gfp_t gfp_flags)
813 {
814         struct urb *urb;
815         unsigned int npackets, i, j;
816         u16 psize;
817         u32 size;
818
819         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
820         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
821         size = video->streaming->ctrl.dwMaxVideoFrameSize;
822
823         npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
824         if (npackets == 0)
825                 return -ENOMEM;
826
827         size = npackets * psize;
828
829         for (i = 0; i < UVC_URBS; ++i) {
830                 urb = usb_alloc_urb(npackets, gfp_flags);
831                 if (urb == NULL) {
832                         uvc_uninit_video(video, 1);
833                         return -ENOMEM;
834                 }
835
836                 urb->dev = video->dev->udev;
837                 urb->context = video;
838                 urb->pipe = usb_rcvisocpipe(video->dev->udev,
839                                 ep->desc.bEndpointAddress);
840                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
841                 urb->interval = ep->desc.bInterval;
842                 urb->transfer_buffer = video->urb_buffer[i];
843                 urb->transfer_dma = video->urb_dma[i];
844                 urb->complete = uvc_video_complete;
845                 urb->number_of_packets = npackets;
846                 urb->transfer_buffer_length = size;
847
848                 for (j = 0; j < npackets; ++j) {
849                         urb->iso_frame_desc[j].offset = j * psize;
850                         urb->iso_frame_desc[j].length = psize;
851                 }
852
853                 video->urb[i] = urb;
854         }
855
856         return 0;
857 }
858
859 /*
860  * Initialize bulk URBs and allocate transfer buffers. The packet size is
861  * given by the endpoint.
862  */
863 static int uvc_init_video_bulk(struct uvc_video_device *video,
864         struct usb_host_endpoint *ep, gfp_t gfp_flags)
865 {
866         struct urb *urb;
867         unsigned int npackets, pipe, i;
868         u16 psize;
869         u32 size;
870
871         psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
872         size = video->streaming->ctrl.dwMaxPayloadTransferSize;
873         video->bulk.max_payload_size = size;
874
875         npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
876         if (npackets == 0)
877                 return -ENOMEM;
878
879         size = npackets * psize;
880
881         if (usb_endpoint_dir_in(&ep->desc))
882                 pipe = usb_rcvbulkpipe(video->dev->udev,
883                                        ep->desc.bEndpointAddress);
884         else
885                 pipe = usb_sndbulkpipe(video->dev->udev,
886                                        ep->desc.bEndpointAddress);
887
888         if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
889                 size = 0;
890
891         for (i = 0; i < UVC_URBS; ++i) {
892                 urb = usb_alloc_urb(0, gfp_flags);
893                 if (urb == NULL) {
894                         uvc_uninit_video(video, 1);
895                         return -ENOMEM;
896                 }
897
898                 usb_fill_bulk_urb(urb, video->dev->udev, pipe,
899                         video->urb_buffer[i], size, uvc_video_complete,
900                         video);
901                 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
902                 urb->transfer_dma = video->urb_dma[i];
903
904                 video->urb[i] = urb;
905         }
906
907         return 0;
908 }
909
910 /*
911  * Initialize isochronous/bulk URBs and allocate transfer buffers.
912  */
913 static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
914 {
915         struct usb_interface *intf = video->streaming->intf;
916         struct usb_host_interface *alts;
917         struct usb_host_endpoint *ep = NULL;
918         int intfnum = video->streaming->intfnum;
919         unsigned int bandwidth, psize, i;
920         int ret;
921
922         video->last_fid = -1;
923         video->bulk.header_size = 0;
924         video->bulk.skip_payload = 0;
925         video->bulk.payload_size = 0;
926
927         if (intf->num_altsetting > 1) {
928                 /* Isochronous endpoint, select the alternate setting. */
929                 bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
930
931                 if (bandwidth == 0) {
932                         uvc_printk(KERN_WARNING, "device %s requested null "
933                                 "bandwidth, defaulting to lowest.\n",
934                                 video->vdev->name);
935                         bandwidth = 1;
936                 }
937
938                 for (i = 0; i < intf->num_altsetting; ++i) {
939                         alts = &intf->altsetting[i];
940                         ep = uvc_find_endpoint(alts,
941                                 video->streaming->header.bEndpointAddress);
942                         if (ep == NULL)
943                                 continue;
944
945                         /* Check if the bandwidth is high enough. */
946                         psize = le16_to_cpu(ep->desc.wMaxPacketSize);
947                         psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
948                         if (psize >= bandwidth)
949                                 break;
950                 }
951
952                 if (i >= intf->num_altsetting)
953                         return -EIO;
954
955                 if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
956                         return ret;
957
958                 ret = uvc_init_video_isoc(video, ep, gfp_flags);
959         } else {
960                 /* Bulk endpoint, proceed to URB initialization. */
961                 ep = uvc_find_endpoint(&intf->altsetting[0],
962                                 video->streaming->header.bEndpointAddress);
963                 if (ep == NULL)
964                         return -EIO;
965
966                 ret = uvc_init_video_bulk(video, ep, gfp_flags);
967         }
968
969         if (ret < 0)
970                 return ret;
971
972         /* Submit the URBs. */
973         for (i = 0; i < UVC_URBS; ++i) {
974                 if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
975                         uvc_printk(KERN_ERR, "Failed to submit URB %u "
976                                         "(%d).\n", i, ret);
977                         uvc_uninit_video(video, 1);
978                         return ret;
979                 }
980         }
981
982         return 0;
983 }
984
985 /* --------------------------------------------------------------------------
986  * Suspend/resume
987  */
988
989 /*
990  * Stop streaming without disabling the video queue.
991  *
992  * To let userspace applications resume without trouble, we must not touch the
993  * video buffers in any way. We mark the device as frozen to make sure the URB
994  * completion handler won't try to cancel the queue when we kill the URBs.
995  */
996 int uvc_video_suspend(struct uvc_video_device *video)
997 {
998         if (!uvc_queue_streaming(&video->queue))
999                 return 0;
1000
1001         video->frozen = 1;
1002         uvc_uninit_video(video, 0);
1003         usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1004         return 0;
1005 }
1006
1007 /*
1008  * Reconfigure the video interface and restart streaming if it was enabled
1009  * before suspend.
1010  *
1011  * If an error occurs, disable the video queue. This will wake all pending
1012  * buffers, making sure userspace applications are notified of the problem
1013  * instead of waiting forever.
1014  */
1015 int uvc_video_resume(struct uvc_video_device *video)
1016 {
1017         int ret;
1018
1019         video->frozen = 0;
1020
1021         if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
1022                 uvc_queue_enable(&video->queue, 0);
1023                 return ret;
1024         }
1025
1026         if (!uvc_queue_streaming(&video->queue))
1027                 return 0;
1028
1029         if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
1030                 uvc_queue_enable(&video->queue, 0);
1031
1032         return ret;
1033 }
1034
1035 /* ------------------------------------------------------------------------
1036  * Video device
1037  */
1038
1039 /*
1040  * Initialize the UVC video device by switching to alternate setting 0 and
1041  * retrieve the default format.
1042  *
1043  * Some cameras (namely the Fuji Finepix) set the format and frame
1044  * indexes to zero. The UVC standard doesn't clearly make this a spec
1045  * violation, so try to silently fix the values if possible.
1046  *
1047  * This function is called before registering the device with V4L.
1048  */
1049 int uvc_video_init(struct uvc_video_device *video)
1050 {
1051         struct uvc_streaming_control *probe = &video->streaming->ctrl;
1052         struct uvc_format *format = NULL;
1053         struct uvc_frame *frame = NULL;
1054         unsigned int i;
1055         int ret;
1056
1057         if (video->streaming->nformats == 0) {
1058                 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1059                 return -EINVAL;
1060         }
1061
1062         /* Alternate setting 0 should be the default, yet the XBox Live Vision
1063          * Cam (and possibly other devices) crash or otherwise misbehave if
1064          * they don't receive a SET_INTERFACE request before any other video
1065          * control request.
1066          */
1067         usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
1068
1069         /* Set the streaming probe control with default streaming parameters
1070          * retrieved from the device. Webcams that don't suport GET_DEF
1071          * requests on the probe control will just keep their current streaming
1072          * parameters.
1073          */
1074         if (uvc_get_video_ctrl(video, probe, 1, UVC_GET_DEF) == 0)
1075                 uvc_set_video_ctrl(video, probe, 1);
1076
1077         /* Initialize the streaming parameters with the probe control current
1078          * value. This makes sure SET_CUR requests on the streaming commit
1079          * control will always use values retrieved from a successful GET_CUR
1080          * request on the probe control, as required by the UVC specification.
1081          */
1082         ret = uvc_get_video_ctrl(video, probe, 1, UVC_GET_CUR);
1083         if (ret < 0)
1084                 return ret;
1085
1086         /* Check if the default format descriptor exists. Use the first
1087          * available format otherwise.
1088          */
1089         for (i = video->streaming->nformats; i > 0; --i) {
1090                 format = &video->streaming->format[i-1];
1091                 if (format->index == probe->bFormatIndex)
1092                         break;
1093         }
1094
1095         if (format->nframes == 0) {
1096                 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1097                         "default format.\n");
1098                 return -EINVAL;
1099         }
1100
1101         /* Zero bFrameIndex might be correct. Stream-based formats (including
1102          * MPEG-2 TS and DV) do not support frames but have a dummy frame
1103          * descriptor with bFrameIndex set to zero. If the default frame
1104          * descriptor is not found, use the first available frame.
1105          */
1106         for (i = format->nframes; i > 0; --i) {
1107                 frame = &format->frame[i-1];
1108                 if (frame->bFrameIndex == probe->bFrameIndex)
1109                         break;
1110         }
1111
1112         probe->bFormatIndex = format->index;
1113         probe->bFrameIndex = frame->bFrameIndex;
1114
1115         video->streaming->cur_format = format;
1116         video->streaming->cur_frame = frame;
1117         atomic_set(&video->active, 0);
1118
1119         /* Select the video decoding function */
1120         if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1121                 if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1122                         video->decode = uvc_video_decode_isight;
1123                 else if (video->streaming->intf->num_altsetting > 1)
1124                         video->decode = uvc_video_decode_isoc;
1125                 else
1126                         video->decode = uvc_video_decode_bulk;
1127         } else {
1128                 if (video->streaming->intf->num_altsetting == 1)
1129                         video->decode = uvc_video_encode_bulk;
1130                 else {
1131                         uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1132                                 "supported for video output devices.\n");
1133                         return -EINVAL;
1134                 }
1135         }
1136
1137         return 0;
1138 }
1139
1140 /*
1141  * Enable or disable the video stream.
1142  */
1143 int uvc_video_enable(struct uvc_video_device *video, int enable)
1144 {
1145         int ret;
1146
1147         if (!enable) {
1148                 uvc_uninit_video(video, 1);
1149                 usb_set_interface(video->dev->udev,
1150                         video->streaming->intfnum, 0);
1151                 uvc_queue_enable(&video->queue, 0);
1152                 return 0;
1153         }
1154
1155         if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
1156             uvc_no_drop_param)
1157                 video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
1158         else
1159                 video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
1160
1161         if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
1162                 return ret;
1163
1164         /* Commit the streaming parameters. */
1165         if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
1166                 return ret;
1167
1168         return uvc_init_video(video, GFP_KERNEL);
1169 }
1170