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