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