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