2 * uvc_video.c -- USB Video Class driver - Video handling
4 * Copyright (C) 2005-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
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.
14 #include <linux/kernel.h>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/slab.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>
25 #include <media/v4l2-common.h>
29 /* ------------------------------------------------------------------------
33 static int __uvc_query_ctrl(struct uvc_device
*dev
, __u8 query
, __u8 unit
,
34 __u8 intfnum
, __u8 cs
, void *data
, __u16 size
,
37 __u8 type
= USB_TYPE_CLASS
| USB_RECIP_INTERFACE
;
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
;
44 return usb_control_msg(dev
->udev
, pipe
, query
, type
, cs
<< 8,
45 unit
<< 8 | intfnum
, data
, size
, timeout
);
48 static const char *uvc_query_name(__u8 query
)
72 int uvc_query_ctrl(struct uvc_device
*dev
, __u8 query
, __u8 unit
,
73 __u8 intfnum
, __u8 cs
, void *data
, __u16 size
)
77 ret
= __uvc_query_ctrl(dev
, query
, unit
, intfnum
, cs
, data
, size
,
78 UVC_CTRL_CONTROL_TIMEOUT
);
80 uvc_printk(KERN_ERR
, "Failed to query (%s) UVC control %u on "
81 "unit %u: %d (exp. %u).\n", uvc_query_name(query
), cs
,
89 static void uvc_fixup_video_ctrl(struct uvc_streaming
*stream
,
90 struct uvc_streaming_control
*ctrl
)
92 struct uvc_format
*format
;
93 struct uvc_frame
*frame
= NULL
;
96 if (ctrl
->bFormatIndex
<= 0 ||
97 ctrl
->bFormatIndex
> stream
->nformats
)
100 format
= &stream
->format
[ctrl
->bFormatIndex
- 1];
102 for (i
= 0; i
< format
->nframes
; ++i
) {
103 if (format
->frame
[i
].bFrameIndex
== ctrl
->bFrameIndex
) {
104 frame
= &format
->frame
[i
];
112 if (!(format
->flags
& UVC_FMT_FLAG_COMPRESSED
) ||
113 (ctrl
->dwMaxVideoFrameSize
== 0 &&
114 stream
->dev
->uvc_version
< 0x0110))
115 ctrl
->dwMaxVideoFrameSize
=
116 frame
->dwMaxVideoFrameBufferSize
;
118 if (!(format
->flags
& UVC_FMT_FLAG_COMPRESSED
) &&
119 stream
->dev
->quirks
& UVC_QUIRK_FIX_BANDWIDTH
&&
120 stream
->intf
->num_altsetting
> 1) {
124 interval
= (ctrl
->dwFrameInterval
> 100000)
125 ? ctrl
->dwFrameInterval
126 : frame
->dwFrameInterval
[0];
128 /* Compute a bandwidth estimation by multiplying the frame
129 * size by the number of video frames per second, divide the
130 * result by the number of USB frames (or micro-frames for
131 * high-speed devices) per second and add the UVC header size
132 * (assumed to be 12 bytes long).
134 bandwidth
= frame
->wWidth
* frame
->wHeight
/ 8 * format
->bpp
;
135 bandwidth
*= 10000000 / interval
+ 1;
137 if (stream
->dev
->udev
->speed
== USB_SPEED_HIGH
)
141 /* The bandwidth estimate is too low for many cameras. Don't use
142 * maximum packet sizes lower than 1024 bytes to try and work
143 * around the problem. According to measurements done on two
144 * different camera models, the value is high enough to get most
145 * resolutions working while not preventing two simultaneous
146 * VGA streams at 15 fps.
148 bandwidth
= max_t(u32
, bandwidth
, 1024);
150 ctrl
->dwMaxPayloadTransferSize
= bandwidth
;
154 static int uvc_get_video_ctrl(struct uvc_streaming
*stream
,
155 struct uvc_streaming_control
*ctrl
, int probe
, __u8 query
)
161 size
= stream
->dev
->uvc_version
>= 0x0110 ? 34 : 26;
162 if ((stream
->dev
->quirks
& UVC_QUIRK_PROBE_DEF
) &&
163 query
== UVC_GET_DEF
)
166 data
= kmalloc(size
, GFP_KERNEL
);
170 ret
= __uvc_query_ctrl(stream
->dev
, query
, 0, stream
->intfnum
,
171 probe
? UVC_VS_PROBE_CONTROL
: UVC_VS_COMMIT_CONTROL
, data
,
172 size
, uvc_timeout_param
);
174 if ((query
== UVC_GET_MIN
|| query
== UVC_GET_MAX
) && ret
== 2) {
175 /* Some cameras, mostly based on Bison Electronics chipsets,
176 * answer a GET_MIN or GET_MAX request with the wCompQuality
179 uvc_warn_once(stream
->dev
, UVC_WARN_MINMAX
, "UVC non "
180 "compliance - GET_MIN/MAX(PROBE) incorrectly "
181 "supported. Enabling workaround.\n");
182 memset(ctrl
, 0, sizeof *ctrl
);
183 ctrl
->wCompQuality
= le16_to_cpup((__le16
*)data
);
186 } else if (query
== UVC_GET_DEF
&& probe
== 1 && ret
!= size
) {
187 /* Many cameras don't support the GET_DEF request on their
188 * video probe control. Warn once and return, the caller will
189 * fall back to GET_CUR.
191 uvc_warn_once(stream
->dev
, UVC_WARN_PROBE_DEF
, "UVC non "
192 "compliance - GET_DEF(PROBE) not supported. "
193 "Enabling workaround.\n");
196 } else if (ret
!= size
) {
197 uvc_printk(KERN_ERR
, "Failed to query (%u) UVC %s control : "
198 "%d (exp. %u).\n", query
, probe
? "probe" : "commit",
204 ctrl
->bmHint
= le16_to_cpup((__le16
*)&data
[0]);
205 ctrl
->bFormatIndex
= data
[2];
206 ctrl
->bFrameIndex
= data
[3];
207 ctrl
->dwFrameInterval
= le32_to_cpup((__le32
*)&data
[4]);
208 ctrl
->wKeyFrameRate
= le16_to_cpup((__le16
*)&data
[8]);
209 ctrl
->wPFrameRate
= le16_to_cpup((__le16
*)&data
[10]);
210 ctrl
->wCompQuality
= le16_to_cpup((__le16
*)&data
[12]);
211 ctrl
->wCompWindowSize
= le16_to_cpup((__le16
*)&data
[14]);
212 ctrl
->wDelay
= le16_to_cpup((__le16
*)&data
[16]);
213 ctrl
->dwMaxVideoFrameSize
= get_unaligned_le32(&data
[18]);
214 ctrl
->dwMaxPayloadTransferSize
= get_unaligned_le32(&data
[22]);
217 ctrl
->dwClockFrequency
= get_unaligned_le32(&data
[26]);
218 ctrl
->bmFramingInfo
= data
[30];
219 ctrl
->bPreferedVersion
= data
[31];
220 ctrl
->bMinVersion
= data
[32];
221 ctrl
->bMaxVersion
= data
[33];
223 ctrl
->dwClockFrequency
= stream
->dev
->clock_frequency
;
224 ctrl
->bmFramingInfo
= 0;
225 ctrl
->bPreferedVersion
= 0;
226 ctrl
->bMinVersion
= 0;
227 ctrl
->bMaxVersion
= 0;
230 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
231 * dwMaxPayloadTransferSize fields. Try to get the value from the
232 * format and frame descriptors.
234 uvc_fixup_video_ctrl(stream
, ctrl
);
242 static int uvc_set_video_ctrl(struct uvc_streaming
*stream
,
243 struct uvc_streaming_control
*ctrl
, int probe
)
249 size
= stream
->dev
->uvc_version
>= 0x0110 ? 34 : 26;
250 data
= kzalloc(size
, GFP_KERNEL
);
254 *(__le16
*)&data
[0] = cpu_to_le16(ctrl
->bmHint
);
255 data
[2] = ctrl
->bFormatIndex
;
256 data
[3] = ctrl
->bFrameIndex
;
257 *(__le32
*)&data
[4] = cpu_to_le32(ctrl
->dwFrameInterval
);
258 *(__le16
*)&data
[8] = cpu_to_le16(ctrl
->wKeyFrameRate
);
259 *(__le16
*)&data
[10] = cpu_to_le16(ctrl
->wPFrameRate
);
260 *(__le16
*)&data
[12] = cpu_to_le16(ctrl
->wCompQuality
);
261 *(__le16
*)&data
[14] = cpu_to_le16(ctrl
->wCompWindowSize
);
262 *(__le16
*)&data
[16] = cpu_to_le16(ctrl
->wDelay
);
263 put_unaligned_le32(ctrl
->dwMaxVideoFrameSize
, &data
[18]);
264 put_unaligned_le32(ctrl
->dwMaxPayloadTransferSize
, &data
[22]);
267 put_unaligned_le32(ctrl
->dwClockFrequency
, &data
[26]);
268 data
[30] = ctrl
->bmFramingInfo
;
269 data
[31] = ctrl
->bPreferedVersion
;
270 data
[32] = ctrl
->bMinVersion
;
271 data
[33] = ctrl
->bMaxVersion
;
274 ret
= __uvc_query_ctrl(stream
->dev
, UVC_SET_CUR
, 0, stream
->intfnum
,
275 probe
? UVC_VS_PROBE_CONTROL
: UVC_VS_COMMIT_CONTROL
, data
,
276 size
, uvc_timeout_param
);
278 uvc_printk(KERN_ERR
, "Failed to set UVC %s control : "
279 "%d (exp. %u).\n", probe
? "probe" : "commit",
288 int uvc_probe_video(struct uvc_streaming
*stream
,
289 struct uvc_streaming_control
*probe
)
291 struct uvc_streaming_control probe_min
, probe_max
;
296 mutex_lock(&stream
->mutex
);
298 /* Perform probing. The device should adjust the requested values
299 * according to its capabilities. However, some devices, namely the
300 * first generation UVC Logitech webcams, don't implement the Video
301 * Probe control properly, and just return the needed bandwidth. For
302 * that reason, if the needed bandwidth exceeds the maximum available
303 * bandwidth, try to lower the quality.
305 ret
= uvc_set_video_ctrl(stream
, probe
, 1);
309 /* Get the minimum and maximum values for compression settings. */
310 if (!(stream
->dev
->quirks
& UVC_QUIRK_PROBE_MINMAX
)) {
311 ret
= uvc_get_video_ctrl(stream
, &probe_min
, 1, UVC_GET_MIN
);
314 ret
= uvc_get_video_ctrl(stream
, &probe_max
, 1, UVC_GET_MAX
);
318 probe
->wCompQuality
= probe_max
.wCompQuality
;
321 for (i
= 0; i
< 2; ++i
) {
322 ret
= uvc_set_video_ctrl(stream
, probe
, 1);
325 ret
= uvc_get_video_ctrl(stream
, probe
, 1, UVC_GET_CUR
);
329 if (stream
->intf
->num_altsetting
== 1)
332 bandwidth
= probe
->dwMaxPayloadTransferSize
;
333 if (bandwidth
<= stream
->maxpsize
)
336 if (stream
->dev
->quirks
& UVC_QUIRK_PROBE_MINMAX
) {
341 /* TODO: negotiate compression parameters */
342 probe
->wKeyFrameRate
= probe_min
.wKeyFrameRate
;
343 probe
->wPFrameRate
= probe_min
.wPFrameRate
;
344 probe
->wCompQuality
= probe_max
.wCompQuality
;
345 probe
->wCompWindowSize
= probe_min
.wCompWindowSize
;
349 mutex_unlock(&stream
->mutex
);
353 int uvc_commit_video(struct uvc_streaming
*stream
,
354 struct uvc_streaming_control
*probe
)
356 return uvc_set_video_ctrl(stream
, probe
, 0);
359 /* ------------------------------------------------------------------------
363 /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
364 #define UVC_STREAM_EOH (1 << 7)
365 #define UVC_STREAM_ERR (1 << 6)
366 #define UVC_STREAM_STI (1 << 5)
367 #define UVC_STREAM_RES (1 << 4)
368 #define UVC_STREAM_SCR (1 << 3)
369 #define UVC_STREAM_PTS (1 << 2)
370 #define UVC_STREAM_EOF (1 << 1)
371 #define UVC_STREAM_FID (1 << 0)
373 /* Video payload decoding is handled by uvc_video_decode_start(),
374 * uvc_video_decode_data() and uvc_video_decode_end().
376 * uvc_video_decode_start is called with URB data at the start of a bulk or
377 * isochronous payload. It processes header data and returns the header size
378 * in bytes if successful. If an error occurs, it returns a negative error
379 * code. The following error codes have special meanings.
381 * - EAGAIN informs the caller that the current video buffer should be marked
382 * as done, and that the function should be called again with the same data
383 * and a new video buffer. This is used when end of frame conditions can be
384 * reliably detected at the beginning of the next frame only.
386 * If an error other than -EAGAIN is returned, the caller will drop the current
387 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
388 * made until the next payload. -ENODATA can be used to drop the current
389 * payload if no other error code is appropriate.
391 * uvc_video_decode_data is called for every URB with URB data. It copies the
392 * data to the video buffer.
394 * uvc_video_decode_end is called with header data at the end of a bulk or
395 * isochronous payload. It performs any additional header data processing and
396 * returns 0 or a negative error code if an error occured. As header data have
397 * already been processed by uvc_video_decode_start, this functions isn't
398 * required to perform sanity checks a second time.
400 * For isochronous transfers where a payload is always transfered in a single
401 * URB, the three functions will be called in a row.
403 * To let the decoder process header data and update its internal state even
404 * when no video buffer is available, uvc_video_decode_start must be prepared
405 * to be called with a NULL buf parameter. uvc_video_decode_data and
406 * uvc_video_decode_end will never be called with a NULL buffer.
408 static int uvc_video_decode_start(struct uvc_streaming
*stream
,
409 struct uvc_buffer
*buf
, const __u8
*data
, int len
)
414 * - packet must be at least 2 bytes long
415 * - bHeaderLength value must be at least 2 bytes (see above)
416 * - bHeaderLength value can't be larger than the packet size.
418 if (len
< 2 || data
[0] < 2 || data
[0] > len
)
421 /* Skip payloads marked with the error bit ("error frames"). */
422 if (data
[1] & UVC_STREAM_ERR
) {
423 uvc_trace(UVC_TRACE_FRAME
, "Dropping payload (error bit "
428 fid
= data
[1] & UVC_STREAM_FID
;
430 /* Increase the sequence number regardless of any buffer states, so
431 * that discontinuous sequence numbers always indicate lost frames.
433 if (stream
->last_fid
!= fid
)
436 /* Store the payload FID bit and return immediately when the buffer is
440 stream
->last_fid
= fid
;
444 /* Synchronize to the input stream by waiting for the FID bit to be
445 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
446 * stream->last_fid is initialized to -1, so the first isochronous
447 * frame will always be in sync.
449 * If the device doesn't toggle the FID bit, invert stream->last_fid
450 * when the EOF bit is set to force synchronisation on the next packet.
452 if (buf
->state
!= UVC_BUF_STATE_ACTIVE
) {
455 if (fid
== stream
->last_fid
) {
456 uvc_trace(UVC_TRACE_FRAME
, "Dropping payload (out of "
458 if ((stream
->dev
->quirks
& UVC_QUIRK_STREAM_NO_FID
) &&
459 (data
[1] & UVC_STREAM_EOF
))
460 stream
->last_fid
^= UVC_STREAM_FID
;
464 if (uvc_clock_param
== CLOCK_MONOTONIC
)
467 ktime_get_real_ts(&ts
);
469 buf
->buf
.sequence
= stream
->sequence
;
470 buf
->buf
.timestamp
.tv_sec
= ts
.tv_sec
;
471 buf
->buf
.timestamp
.tv_usec
= ts
.tv_nsec
/ NSEC_PER_USEC
;
473 /* TODO: Handle PTS and SCR. */
474 buf
->state
= UVC_BUF_STATE_ACTIVE
;
477 /* Mark the buffer as done if we're at the beginning of a new frame.
478 * End of frame detection is better implemented by checking the EOF
479 * bit (FID bit toggling is delayed by one frame compared to the EOF
480 * bit), but some devices don't set the bit at end of frame (and the
481 * last payload can be lost anyway). We thus must check if the FID has
484 * stream->last_fid is initialized to -1, so the first isochronous
485 * frame will never trigger an end of frame detection.
487 * Empty buffers (bytesused == 0) don't trigger end of frame detection
488 * as it doesn't make sense to return an empty buffer. This also
489 * avoids detecting end of frame conditions at FID toggling if the
490 * previous payload had the EOF bit set.
492 if (fid
!= stream
->last_fid
&& buf
->buf
.bytesused
!= 0) {
493 uvc_trace(UVC_TRACE_FRAME
, "Frame complete (FID bit "
495 buf
->state
= UVC_BUF_STATE_READY
;
499 stream
->last_fid
= fid
;
504 static void uvc_video_decode_data(struct uvc_streaming
*stream
,
505 struct uvc_buffer
*buf
, const __u8
*data
, int len
)
507 struct uvc_video_queue
*queue
= &stream
->queue
;
508 unsigned int maxlen
, nbytes
;
514 /* Copy the video data to the buffer. */
515 maxlen
= buf
->buf
.length
- buf
->buf
.bytesused
;
516 mem
= queue
->mem
+ buf
->buf
.m
.offset
+ buf
->buf
.bytesused
;
517 nbytes
= min((unsigned int)len
, maxlen
);
518 memcpy(mem
, data
, nbytes
);
519 buf
->buf
.bytesused
+= nbytes
;
521 /* Complete the current frame if the buffer size was exceeded. */
523 uvc_trace(UVC_TRACE_FRAME
, "Frame complete (overflow).\n");
524 buf
->state
= UVC_BUF_STATE_READY
;
528 static void uvc_video_decode_end(struct uvc_streaming
*stream
,
529 struct uvc_buffer
*buf
, const __u8
*data
, int len
)
531 /* Mark the buffer as done if the EOF marker is set. */
532 if (data
[1] & UVC_STREAM_EOF
&& buf
->buf
.bytesused
!= 0) {
533 uvc_trace(UVC_TRACE_FRAME
, "Frame complete (EOF found).\n");
535 uvc_trace(UVC_TRACE_FRAME
, "EOF in empty payload.\n");
536 buf
->state
= UVC_BUF_STATE_READY
;
537 if (stream
->dev
->quirks
& UVC_QUIRK_STREAM_NO_FID
)
538 stream
->last_fid
^= UVC_STREAM_FID
;
542 /* Video payload encoding is handled by uvc_video_encode_header() and
543 * uvc_video_encode_data(). Only bulk transfers are currently supported.
545 * uvc_video_encode_header is called at the start of a payload. It adds header
546 * data to the transfer buffer and returns the header size. As the only known
547 * UVC output device transfers a whole frame in a single payload, the EOF bit
548 * is always set in the header.
550 * uvc_video_encode_data is called for every URB and copies the data from the
551 * video buffer to the transfer buffer.
553 static int uvc_video_encode_header(struct uvc_streaming
*stream
,
554 struct uvc_buffer
*buf
, __u8
*data
, int len
)
556 data
[0] = 2; /* Header length */
557 data
[1] = UVC_STREAM_EOH
| UVC_STREAM_EOF
558 | (stream
->last_fid
& UVC_STREAM_FID
);
562 static int uvc_video_encode_data(struct uvc_streaming
*stream
,
563 struct uvc_buffer
*buf
, __u8
*data
, int len
)
565 struct uvc_video_queue
*queue
= &stream
->queue
;
569 /* Copy video data to the URB buffer. */
570 mem
= queue
->mem
+ buf
->buf
.m
.offset
+ queue
->buf_used
;
571 nbytes
= min((unsigned int)len
, buf
->buf
.bytesused
- queue
->buf_used
);
572 nbytes
= min(stream
->bulk
.max_payload_size
- stream
->bulk
.payload_size
,
574 memcpy(data
, mem
, nbytes
);
576 queue
->buf_used
+= nbytes
;
581 /* ------------------------------------------------------------------------
586 * Completion handler for video URBs.
588 static void uvc_video_decode_isoc(struct urb
*urb
, struct uvc_streaming
*stream
,
589 struct uvc_buffer
*buf
)
594 for (i
= 0; i
< urb
->number_of_packets
; ++i
) {
595 if (urb
->iso_frame_desc
[i
].status
< 0) {
596 uvc_trace(UVC_TRACE_FRAME
, "USB isochronous frame "
597 "lost (%d).\n", urb
->iso_frame_desc
[i
].status
);
598 /* Mark the buffer as faulty. */
604 /* Decode the payload header. */
605 mem
= urb
->transfer_buffer
+ urb
->iso_frame_desc
[i
].offset
;
607 ret
= uvc_video_decode_start(stream
, buf
, mem
,
608 urb
->iso_frame_desc
[i
].actual_length
);
610 buf
= uvc_queue_next_buffer(&stream
->queue
,
612 } while (ret
== -EAGAIN
);
617 /* Decode the payload data. */
618 uvc_video_decode_data(stream
, buf
, mem
+ ret
,
619 urb
->iso_frame_desc
[i
].actual_length
- ret
);
621 /* Process the header again. */
622 uvc_video_decode_end(stream
, buf
, mem
,
623 urb
->iso_frame_desc
[i
].actual_length
);
625 if (buf
->state
== UVC_BUF_STATE_READY
) {
626 if (buf
->buf
.length
!= buf
->buf
.bytesused
&&
627 !(stream
->cur_format
->flags
&
628 UVC_FMT_FLAG_COMPRESSED
))
631 buf
= uvc_queue_next_buffer(&stream
->queue
, buf
);
636 static void uvc_video_decode_bulk(struct urb
*urb
, struct uvc_streaming
*stream
,
637 struct uvc_buffer
*buf
)
642 if (urb
->actual_length
== 0)
645 mem
= urb
->transfer_buffer
;
646 len
= urb
->actual_length
;
647 stream
->bulk
.payload_size
+= len
;
649 /* If the URB is the first of its payload, decode and save the
652 if (stream
->bulk
.header_size
== 0 && !stream
->bulk
.skip_payload
) {
654 ret
= uvc_video_decode_start(stream
, buf
, mem
, len
);
656 buf
= uvc_queue_next_buffer(&stream
->queue
,
658 } while (ret
== -EAGAIN
);
660 /* If an error occured skip the rest of the payload. */
661 if (ret
< 0 || buf
== NULL
) {
662 stream
->bulk
.skip_payload
= 1;
664 memcpy(stream
->bulk
.header
, mem
, ret
);
665 stream
->bulk
.header_size
= ret
;
672 /* The buffer queue might have been cancelled while a bulk transfer
673 * was in progress, so we can reach here with buf equal to NULL. Make
674 * sure buf is never dereferenced if NULL.
677 /* Process video data. */
678 if (!stream
->bulk
.skip_payload
&& buf
!= NULL
)
679 uvc_video_decode_data(stream
, buf
, mem
, len
);
681 /* Detect the payload end by a URB smaller than the maximum size (or
682 * a payload size equal to the maximum) and process the header again.
684 if (urb
->actual_length
< urb
->transfer_buffer_length
||
685 stream
->bulk
.payload_size
>= stream
->bulk
.max_payload_size
) {
686 if (!stream
->bulk
.skip_payload
&& buf
!= NULL
) {
687 uvc_video_decode_end(stream
, buf
, stream
->bulk
.header
,
688 stream
->bulk
.payload_size
);
689 if (buf
->state
== UVC_BUF_STATE_READY
)
690 buf
= uvc_queue_next_buffer(&stream
->queue
,
694 stream
->bulk
.header_size
= 0;
695 stream
->bulk
.skip_payload
= 0;
696 stream
->bulk
.payload_size
= 0;
700 static void uvc_video_encode_bulk(struct urb
*urb
, struct uvc_streaming
*stream
,
701 struct uvc_buffer
*buf
)
703 u8
*mem
= urb
->transfer_buffer
;
704 int len
= stream
->urb_size
, ret
;
707 urb
->transfer_buffer_length
= 0;
711 /* If the URB is the first of its payload, add the header. */
712 if (stream
->bulk
.header_size
== 0) {
713 ret
= uvc_video_encode_header(stream
, buf
, mem
, len
);
714 stream
->bulk
.header_size
= ret
;
715 stream
->bulk
.payload_size
+= ret
;
720 /* Process video data. */
721 ret
= uvc_video_encode_data(stream
, buf
, mem
, len
);
723 stream
->bulk
.payload_size
+= ret
;
726 if (buf
->buf
.bytesused
== stream
->queue
.buf_used
||
727 stream
->bulk
.payload_size
== stream
->bulk
.max_payload_size
) {
728 if (buf
->buf
.bytesused
== stream
->queue
.buf_used
) {
729 stream
->queue
.buf_used
= 0;
730 buf
->state
= UVC_BUF_STATE_READY
;
731 buf
->buf
.sequence
= ++stream
->sequence
;
732 uvc_queue_next_buffer(&stream
->queue
, buf
);
733 stream
->last_fid
^= UVC_STREAM_FID
;
736 stream
->bulk
.header_size
= 0;
737 stream
->bulk
.payload_size
= 0;
740 urb
->transfer_buffer_length
= stream
->urb_size
- len
;
743 static void uvc_video_complete(struct urb
*urb
)
745 struct uvc_streaming
*stream
= urb
->context
;
746 struct uvc_video_queue
*queue
= &stream
->queue
;
747 struct uvc_buffer
*buf
= NULL
;
751 switch (urb
->status
) {
756 uvc_printk(KERN_WARNING
, "Non-zero status (%d) in video "
757 "completion handler.\n", urb
->status
);
759 case -ENOENT
: /* usb_kill_urb() called. */
763 case -ECONNRESET
: /* usb_unlink_urb() called. */
764 case -ESHUTDOWN
: /* The endpoint is being disabled. */
765 uvc_queue_cancel(queue
, urb
->status
== -ESHUTDOWN
);
769 spin_lock_irqsave(&queue
->irqlock
, flags
);
770 if (!list_empty(&queue
->irqqueue
))
771 buf
= list_first_entry(&queue
->irqqueue
, struct uvc_buffer
,
773 spin_unlock_irqrestore(&queue
->irqlock
, flags
);
775 stream
->decode(urb
, stream
, buf
);
777 if ((ret
= usb_submit_urb(urb
, GFP_ATOMIC
)) < 0) {
778 uvc_printk(KERN_ERR
, "Failed to resubmit video URB (%d).\n",
784 * Free transfer buffers.
786 static void uvc_free_urb_buffers(struct uvc_streaming
*stream
)
790 for (i
= 0; i
< UVC_URBS
; ++i
) {
791 if (stream
->urb_buffer
[i
]) {
792 usb_free_coherent(stream
->dev
->udev
, stream
->urb_size
,
793 stream
->urb_buffer
[i
], stream
->urb_dma
[i
]);
794 stream
->urb_buffer
[i
] = NULL
;
798 stream
->urb_size
= 0;
802 * Allocate transfer buffers. This function can be called with buffers
803 * already allocated when resuming from suspend, in which case it will
804 * return without touching the buffers.
806 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
807 * system is too low on memory try successively smaller numbers of packets
808 * until allocation succeeds.
810 * Return the number of allocated packets on success or 0 when out of memory.
812 static int uvc_alloc_urb_buffers(struct uvc_streaming
*stream
,
813 unsigned int size
, unsigned int psize
, gfp_t gfp_flags
)
815 unsigned int npackets
;
818 /* Buffers are already allocated, bail out. */
819 if (stream
->urb_size
)
820 return stream
->urb_size
/ psize
;
822 /* Compute the number of packets. Bulk endpoints might transfer UVC
823 * payloads accross multiple URBs.
825 npackets
= DIV_ROUND_UP(size
, psize
);
826 if (npackets
> UVC_MAX_PACKETS
)
827 npackets
= UVC_MAX_PACKETS
;
829 /* Retry allocations until one succeed. */
830 for (; npackets
> 1; npackets
/= 2) {
831 for (i
= 0; i
< UVC_URBS
; ++i
) {
832 stream
->urb_size
= psize
* npackets
;
833 stream
->urb_buffer
[i
] = usb_alloc_coherent(
834 stream
->dev
->udev
, stream
->urb_size
,
835 gfp_flags
| __GFP_NOWARN
, &stream
->urb_dma
[i
]);
836 if (!stream
->urb_buffer
[i
]) {
837 uvc_free_urb_buffers(stream
);
843 uvc_trace(UVC_TRACE_VIDEO
, "Allocated %u URB buffers "
844 "of %ux%u bytes each.\n", UVC_URBS
, npackets
,
850 uvc_trace(UVC_TRACE_VIDEO
, "Failed to allocate URB buffers (%u bytes "
851 "per packet).\n", psize
);
856 * Uninitialize isochronous/bulk URBs and free transfer buffers.
858 static void uvc_uninit_video(struct uvc_streaming
*stream
, int free_buffers
)
863 for (i
= 0; i
< UVC_URBS
; ++i
) {
864 urb
= stream
->urb
[i
];
870 stream
->urb
[i
] = NULL
;
874 uvc_free_urb_buffers(stream
);
878 * Initialize isochronous URBs and allocate transfer buffers. The packet size
879 * is given by the endpoint.
881 static int uvc_init_video_isoc(struct uvc_streaming
*stream
,
882 struct usb_host_endpoint
*ep
, gfp_t gfp_flags
)
885 unsigned int npackets
, i
, j
;
889 psize
= le16_to_cpu(ep
->desc
.wMaxPacketSize
);
890 psize
= (psize
& 0x07ff) * (1 + ((psize
>> 11) & 3));
891 size
= stream
->ctrl
.dwMaxVideoFrameSize
;
893 npackets
= uvc_alloc_urb_buffers(stream
, size
, psize
, gfp_flags
);
897 size
= npackets
* psize
;
899 for (i
= 0; i
< UVC_URBS
; ++i
) {
900 urb
= usb_alloc_urb(npackets
, gfp_flags
);
902 uvc_uninit_video(stream
, 1);
906 urb
->dev
= stream
->dev
->udev
;
907 urb
->context
= stream
;
908 urb
->pipe
= usb_rcvisocpipe(stream
->dev
->udev
,
909 ep
->desc
.bEndpointAddress
);
910 urb
->transfer_flags
= URB_ISO_ASAP
| URB_NO_TRANSFER_DMA_MAP
;
911 urb
->interval
= ep
->desc
.bInterval
;
912 urb
->transfer_buffer
= stream
->urb_buffer
[i
];
913 urb
->transfer_dma
= stream
->urb_dma
[i
];
914 urb
->complete
= uvc_video_complete
;
915 urb
->number_of_packets
= npackets
;
916 urb
->transfer_buffer_length
= size
;
918 for (j
= 0; j
< npackets
; ++j
) {
919 urb
->iso_frame_desc
[j
].offset
= j
* psize
;
920 urb
->iso_frame_desc
[j
].length
= psize
;
923 stream
->urb
[i
] = urb
;
930 * Initialize bulk URBs and allocate transfer buffers. The packet size is
931 * given by the endpoint.
933 static int uvc_init_video_bulk(struct uvc_streaming
*stream
,
934 struct usb_host_endpoint
*ep
, gfp_t gfp_flags
)
937 unsigned int npackets
, pipe
, i
;
941 psize
= le16_to_cpu(ep
->desc
.wMaxPacketSize
) & 0x07ff;
942 size
= stream
->ctrl
.dwMaxPayloadTransferSize
;
943 stream
->bulk
.max_payload_size
= size
;
945 npackets
= uvc_alloc_urb_buffers(stream
, size
, psize
, gfp_flags
);
949 size
= npackets
* psize
;
951 if (usb_endpoint_dir_in(&ep
->desc
))
952 pipe
= usb_rcvbulkpipe(stream
->dev
->udev
,
953 ep
->desc
.bEndpointAddress
);
955 pipe
= usb_sndbulkpipe(stream
->dev
->udev
,
956 ep
->desc
.bEndpointAddress
);
958 if (stream
->type
== V4L2_BUF_TYPE_VIDEO_OUTPUT
)
961 for (i
= 0; i
< UVC_URBS
; ++i
) {
962 urb
= usb_alloc_urb(0, gfp_flags
);
964 uvc_uninit_video(stream
, 1);
968 usb_fill_bulk_urb(urb
, stream
->dev
->udev
, pipe
,
969 stream
->urb_buffer
[i
], size
, uvc_video_complete
,
971 urb
->transfer_flags
= URB_NO_TRANSFER_DMA_MAP
;
972 urb
->transfer_dma
= stream
->urb_dma
[i
];
974 stream
->urb
[i
] = urb
;
981 * Initialize isochronous/bulk URBs and allocate transfer buffers.
983 static int uvc_init_video(struct uvc_streaming
*stream
, gfp_t gfp_flags
)
985 struct usb_interface
*intf
= stream
->intf
;
986 struct usb_host_endpoint
*ep
;
990 stream
->sequence
= -1;
991 stream
->last_fid
= -1;
992 stream
->bulk
.header_size
= 0;
993 stream
->bulk
.skip_payload
= 0;
994 stream
->bulk
.payload_size
= 0;
996 if (intf
->num_altsetting
> 1) {
997 struct usb_host_endpoint
*best_ep
= NULL
;
998 unsigned int best_psize
= 3 * 1024;
999 unsigned int bandwidth
;
1000 unsigned int uninitialized_var(altsetting
);
1001 int intfnum
= stream
->intfnum
;
1003 /* Isochronous endpoint, select the alternate setting. */
1004 bandwidth
= stream
->ctrl
.dwMaxPayloadTransferSize
;
1006 if (bandwidth
== 0) {
1007 uvc_trace(UVC_TRACE_VIDEO
, "Device requested null "
1008 "bandwidth, defaulting to lowest.\n");
1011 uvc_trace(UVC_TRACE_VIDEO
, "Device requested %u "
1012 "B/frame bandwidth.\n", bandwidth
);
1015 for (i
= 0; i
< intf
->num_altsetting
; ++i
) {
1016 struct usb_host_interface
*alts
;
1019 alts
= &intf
->altsetting
[i
];
1020 ep
= uvc_find_endpoint(alts
,
1021 stream
->header
.bEndpointAddress
);
1025 /* Check if the bandwidth is high enough. */
1026 psize
= le16_to_cpu(ep
->desc
.wMaxPacketSize
);
1027 psize
= (psize
& 0x07ff) * (1 + ((psize
>> 11) & 3));
1028 if (psize
>= bandwidth
&& psize
<= best_psize
) {
1035 if (best_ep
== NULL
) {
1036 uvc_trace(UVC_TRACE_VIDEO
, "No fast enough alt setting "
1037 "for requested bandwidth.\n");
1041 uvc_trace(UVC_TRACE_VIDEO
, "Selecting alternate setting %u "
1042 "(%u B/frame bandwidth).\n", altsetting
, best_psize
);
1044 ret
= usb_set_interface(stream
->dev
->udev
, intfnum
, altsetting
);
1048 ret
= uvc_init_video_isoc(stream
, best_ep
, gfp_flags
);
1050 /* Bulk endpoint, proceed to URB initialization. */
1051 ep
= uvc_find_endpoint(&intf
->altsetting
[0],
1052 stream
->header
.bEndpointAddress
);
1056 ret
= uvc_init_video_bulk(stream
, ep
, gfp_flags
);
1062 /* Submit the URBs. */
1063 for (i
= 0; i
< UVC_URBS
; ++i
) {
1064 ret
= usb_submit_urb(stream
->urb
[i
], gfp_flags
);
1066 uvc_printk(KERN_ERR
, "Failed to submit URB %u "
1068 uvc_uninit_video(stream
, 1);
1076 /* --------------------------------------------------------------------------
1081 * Stop streaming without disabling the video queue.
1083 * To let userspace applications resume without trouble, we must not touch the
1084 * video buffers in any way. We mark the device as frozen to make sure the URB
1085 * completion handler won't try to cancel the queue when we kill the URBs.
1087 int uvc_video_suspend(struct uvc_streaming
*stream
)
1089 if (!uvc_queue_streaming(&stream
->queue
))
1093 uvc_uninit_video(stream
, 0);
1094 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
1099 * Reconfigure the video interface and restart streaming if it was enabled
1102 * If an error occurs, disable the video queue. This will wake all pending
1103 * buffers, making sure userspace applications are notified of the problem
1104 * instead of waiting forever.
1106 int uvc_video_resume(struct uvc_streaming
*stream
)
1112 ret
= uvc_commit_video(stream
, &stream
->ctrl
);
1114 uvc_queue_enable(&stream
->queue
, 0);
1118 if (!uvc_queue_streaming(&stream
->queue
))
1121 ret
= uvc_init_video(stream
, GFP_NOIO
);
1123 uvc_queue_enable(&stream
->queue
, 0);
1128 /* ------------------------------------------------------------------------
1133 * Initialize the UVC video device by switching to alternate setting 0 and
1134 * retrieve the default format.
1136 * Some cameras (namely the Fuji Finepix) set the format and frame
1137 * indexes to zero. The UVC standard doesn't clearly make this a spec
1138 * violation, so try to silently fix the values if possible.
1140 * This function is called before registering the device with V4L.
1142 int uvc_video_init(struct uvc_streaming
*stream
)
1144 struct uvc_streaming_control
*probe
= &stream
->ctrl
;
1145 struct uvc_format
*format
= NULL
;
1146 struct uvc_frame
*frame
= NULL
;
1150 if (stream
->nformats
== 0) {
1151 uvc_printk(KERN_INFO
, "No supported video formats found.\n");
1155 atomic_set(&stream
->active
, 0);
1157 /* Initialize the video buffers queue. */
1158 uvc_queue_init(&stream
->queue
, stream
->type
, !uvc_no_drop_param
);
1160 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1161 * Cam (and possibly other devices) crash or otherwise misbehave if
1162 * they don't receive a SET_INTERFACE request before any other video
1165 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
1167 /* Set the streaming probe control with default streaming parameters
1168 * retrieved from the device. Webcams that don't suport GET_DEF
1169 * requests on the probe control will just keep their current streaming
1172 if (uvc_get_video_ctrl(stream
, probe
, 1, UVC_GET_DEF
) == 0)
1173 uvc_set_video_ctrl(stream
, probe
, 1);
1175 /* Initialize the streaming parameters with the probe control current
1176 * value. This makes sure SET_CUR requests on the streaming commit
1177 * control will always use values retrieved from a successful GET_CUR
1178 * request on the probe control, as required by the UVC specification.
1180 ret
= uvc_get_video_ctrl(stream
, probe
, 1, UVC_GET_CUR
);
1184 /* Check if the default format descriptor exists. Use the first
1185 * available format otherwise.
1187 for (i
= stream
->nformats
; i
> 0; --i
) {
1188 format
= &stream
->format
[i
-1];
1189 if (format
->index
== probe
->bFormatIndex
)
1193 if (format
->nframes
== 0) {
1194 uvc_printk(KERN_INFO
, "No frame descriptor found for the "
1195 "default format.\n");
1199 /* Zero bFrameIndex might be correct. Stream-based formats (including
1200 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1201 * descriptor with bFrameIndex set to zero. If the default frame
1202 * descriptor is not found, use the first available frame.
1204 for (i
= format
->nframes
; i
> 0; --i
) {
1205 frame
= &format
->frame
[i
-1];
1206 if (frame
->bFrameIndex
== probe
->bFrameIndex
)
1210 probe
->bFormatIndex
= format
->index
;
1211 probe
->bFrameIndex
= frame
->bFrameIndex
;
1213 stream
->cur_format
= format
;
1214 stream
->cur_frame
= frame
;
1216 /* Select the video decoding function */
1217 if (stream
->type
== V4L2_BUF_TYPE_VIDEO_CAPTURE
) {
1218 if (stream
->dev
->quirks
& UVC_QUIRK_BUILTIN_ISIGHT
)
1219 stream
->decode
= uvc_video_decode_isight
;
1220 else if (stream
->intf
->num_altsetting
> 1)
1221 stream
->decode
= uvc_video_decode_isoc
;
1223 stream
->decode
= uvc_video_decode_bulk
;
1225 if (stream
->intf
->num_altsetting
== 1)
1226 stream
->decode
= uvc_video_encode_bulk
;
1228 uvc_printk(KERN_INFO
, "Isochronous endpoints are not "
1229 "supported for video output devices.\n");
1238 * Enable or disable the video stream.
1240 int uvc_video_enable(struct uvc_streaming
*stream
, int enable
)
1245 uvc_uninit_video(stream
, 1);
1246 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
1247 uvc_queue_enable(&stream
->queue
, 0);
1251 ret
= uvc_queue_enable(&stream
->queue
, 1);
1255 /* Commit the streaming parameters. */
1256 ret
= uvc_commit_video(stream
, &stream
->ctrl
);
1260 return uvc_init_video(stream
, GFP_KERNEL
);