1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * uvc_video.c -- USB Video Class driver - Video handling
5 * Copyright (C) 2005-2010
6 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
9 #include <linux/kernel.h>
10 #include <linux/list.h>
11 #include <linux/module.h>
12 #include <linux/slab.h>
13 #include <linux/usb.h>
14 #include <linux/videodev2.h>
15 #include <linux/vmalloc.h>
16 #include <linux/wait.h>
17 #include <linux/atomic.h>
18 #include <asm/unaligned.h>
20 #include <media/v4l2-common.h>
24 /* ------------------------------------------------------------------------
28 static int __uvc_query_ctrl(struct uvc_device
*dev
, u8 query
, u8 unit
,
29 u8 intfnum
, u8 cs
, void *data
, u16 size
,
32 u8 type
= USB_TYPE_CLASS
| USB_RECIP_INTERFACE
;
35 pipe
= (query
& 0x80) ? usb_rcvctrlpipe(dev
->udev
, 0)
36 : usb_sndctrlpipe(dev
->udev
, 0);
37 type
|= (query
& 0x80) ? USB_DIR_IN
: USB_DIR_OUT
;
39 return usb_control_msg(dev
->udev
, pipe
, query
, type
, cs
<< 8,
40 unit
<< 8 | intfnum
, data
, size
, timeout
);
43 static const char *uvc_query_name(u8 query
)
67 int uvc_query_ctrl(struct uvc_device
*dev
, u8 query
, u8 unit
,
68 u8 intfnum
, u8 cs
, void *data
, u16 size
)
74 ret
= __uvc_query_ctrl(dev
, query
, unit
, intfnum
, cs
, data
, size
,
75 UVC_CTRL_CONTROL_TIMEOUT
);
76 if (likely(ret
== size
))
80 "Failed to query (%s) UVC control %u on unit %u: %d (exp. %u).\n",
81 uvc_query_name(query
), cs
, unit
, ret
, size
);
88 ret
= __uvc_query_ctrl(dev
, UVC_GET_CUR
, 0, intfnum
,
89 UVC_VC_REQUEST_ERROR_CODE_CONTROL
, data
, 1,
90 UVC_CTRL_CONTROL_TIMEOUT
);
96 return ret
< 0 ? ret
: -EPIPE
;
98 uvc_trace(UVC_TRACE_CONTROL
, "Control error %u\n", error
);
102 /* Cannot happen - we received a STALL */
104 case 1: /* Not ready */
106 case 2: /* Wrong state */
110 case 4: /* Out of range */
112 case 5: /* Invalid unit */
113 case 6: /* Invalid control */
114 case 7: /* Invalid Request */
115 case 8: /* Invalid value within range */
117 default: /* reserved or unknown */
124 static void uvc_fixup_video_ctrl(struct uvc_streaming
*stream
,
125 struct uvc_streaming_control
*ctrl
)
127 struct uvc_format
*format
= NULL
;
128 struct uvc_frame
*frame
= NULL
;
131 for (i
= 0; i
< stream
->nformats
; ++i
) {
132 if (stream
->format
[i
].index
== ctrl
->bFormatIndex
) {
133 format
= &stream
->format
[i
];
141 for (i
= 0; i
< format
->nframes
; ++i
) {
142 if (format
->frame
[i
].bFrameIndex
== ctrl
->bFrameIndex
) {
143 frame
= &format
->frame
[i
];
151 if (!(format
->flags
& UVC_FMT_FLAG_COMPRESSED
) ||
152 (ctrl
->dwMaxVideoFrameSize
== 0 &&
153 stream
->dev
->uvc_version
< 0x0110))
154 ctrl
->dwMaxVideoFrameSize
=
155 frame
->dwMaxVideoFrameBufferSize
;
157 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
158 * compute the bandwidth on 16 bits and erroneously sign-extend it to
159 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
160 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
162 if ((ctrl
->dwMaxPayloadTransferSize
& 0xffff0000) == 0xffff0000)
163 ctrl
->dwMaxPayloadTransferSize
&= ~0xffff0000;
165 if (!(format
->flags
& UVC_FMT_FLAG_COMPRESSED
) &&
166 stream
->dev
->quirks
& UVC_QUIRK_FIX_BANDWIDTH
&&
167 stream
->intf
->num_altsetting
> 1) {
171 interval
= (ctrl
->dwFrameInterval
> 100000)
172 ? ctrl
->dwFrameInterval
173 : frame
->dwFrameInterval
[0];
175 /* Compute a bandwidth estimation by multiplying the frame
176 * size by the number of video frames per second, divide the
177 * result by the number of USB frames (or micro-frames for
178 * high-speed devices) per second and add the UVC header size
179 * (assumed to be 12 bytes long).
181 bandwidth
= frame
->wWidth
* frame
->wHeight
/ 8 * format
->bpp
;
182 bandwidth
*= 10000000 / interval
+ 1;
184 if (stream
->dev
->udev
->speed
== USB_SPEED_HIGH
)
188 /* The bandwidth estimate is too low for many cameras. Don't use
189 * maximum packet sizes lower than 1024 bytes to try and work
190 * around the problem. According to measurements done on two
191 * different camera models, the value is high enough to get most
192 * resolutions working while not preventing two simultaneous
193 * VGA streams at 15 fps.
195 bandwidth
= max_t(u32
, bandwidth
, 1024);
197 ctrl
->dwMaxPayloadTransferSize
= bandwidth
;
201 static size_t uvc_video_ctrl_size(struct uvc_streaming
*stream
)
204 * Return the size of the video probe and commit controls, which depends
205 * on the protocol version.
207 if (stream
->dev
->uvc_version
< 0x0110)
209 else if (stream
->dev
->uvc_version
< 0x0150)
215 static int uvc_get_video_ctrl(struct uvc_streaming
*stream
,
216 struct uvc_streaming_control
*ctrl
, int probe
, u8 query
)
218 u16 size
= uvc_video_ctrl_size(stream
);
222 if ((stream
->dev
->quirks
& UVC_QUIRK_PROBE_DEF
) &&
223 query
== UVC_GET_DEF
)
226 data
= kmalloc(size
, GFP_KERNEL
);
230 ret
= __uvc_query_ctrl(stream
->dev
, query
, 0, stream
->intfnum
,
231 probe
? UVC_VS_PROBE_CONTROL
: UVC_VS_COMMIT_CONTROL
, data
,
232 size
, uvc_timeout_param
);
234 if ((query
== UVC_GET_MIN
|| query
== UVC_GET_MAX
) && ret
== 2) {
235 /* Some cameras, mostly based on Bison Electronics chipsets,
236 * answer a GET_MIN or GET_MAX request with the wCompQuality
239 uvc_warn_once(stream
->dev
, UVC_WARN_MINMAX
, "UVC non "
240 "compliance - GET_MIN/MAX(PROBE) incorrectly "
241 "supported. Enabling workaround.\n");
242 memset(ctrl
, 0, sizeof(*ctrl
));
243 ctrl
->wCompQuality
= le16_to_cpup((__le16
*)data
);
246 } else if (query
== UVC_GET_DEF
&& probe
== 1 && ret
!= size
) {
247 /* Many cameras don't support the GET_DEF request on their
248 * video probe control. Warn once and return, the caller will
249 * fall back to GET_CUR.
251 uvc_warn_once(stream
->dev
, UVC_WARN_PROBE_DEF
, "UVC non "
252 "compliance - GET_DEF(PROBE) not supported. "
253 "Enabling workaround.\n");
256 } else if (ret
!= size
) {
257 uvc_printk(KERN_ERR
, "Failed to query (%u) UVC %s control : "
258 "%d (exp. %u).\n", query
, probe
? "probe" : "commit",
264 ctrl
->bmHint
= le16_to_cpup((__le16
*)&data
[0]);
265 ctrl
->bFormatIndex
= data
[2];
266 ctrl
->bFrameIndex
= data
[3];
267 ctrl
->dwFrameInterval
= le32_to_cpup((__le32
*)&data
[4]);
268 ctrl
->wKeyFrameRate
= le16_to_cpup((__le16
*)&data
[8]);
269 ctrl
->wPFrameRate
= le16_to_cpup((__le16
*)&data
[10]);
270 ctrl
->wCompQuality
= le16_to_cpup((__le16
*)&data
[12]);
271 ctrl
->wCompWindowSize
= le16_to_cpup((__le16
*)&data
[14]);
272 ctrl
->wDelay
= le16_to_cpup((__le16
*)&data
[16]);
273 ctrl
->dwMaxVideoFrameSize
= get_unaligned_le32(&data
[18]);
274 ctrl
->dwMaxPayloadTransferSize
= get_unaligned_le32(&data
[22]);
277 ctrl
->dwClockFrequency
= get_unaligned_le32(&data
[26]);
278 ctrl
->bmFramingInfo
= data
[30];
279 ctrl
->bPreferedVersion
= data
[31];
280 ctrl
->bMinVersion
= data
[32];
281 ctrl
->bMaxVersion
= data
[33];
283 ctrl
->dwClockFrequency
= stream
->dev
->clock_frequency
;
284 ctrl
->bmFramingInfo
= 0;
285 ctrl
->bPreferedVersion
= 0;
286 ctrl
->bMinVersion
= 0;
287 ctrl
->bMaxVersion
= 0;
290 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
291 * dwMaxPayloadTransferSize fields. Try to get the value from the
292 * format and frame descriptors.
294 uvc_fixup_video_ctrl(stream
, ctrl
);
302 static int uvc_set_video_ctrl(struct uvc_streaming
*stream
,
303 struct uvc_streaming_control
*ctrl
, int probe
)
305 u16 size
= uvc_video_ctrl_size(stream
);
309 data
= kzalloc(size
, GFP_KERNEL
);
313 *(__le16
*)&data
[0] = cpu_to_le16(ctrl
->bmHint
);
314 data
[2] = ctrl
->bFormatIndex
;
315 data
[3] = ctrl
->bFrameIndex
;
316 *(__le32
*)&data
[4] = cpu_to_le32(ctrl
->dwFrameInterval
);
317 *(__le16
*)&data
[8] = cpu_to_le16(ctrl
->wKeyFrameRate
);
318 *(__le16
*)&data
[10] = cpu_to_le16(ctrl
->wPFrameRate
);
319 *(__le16
*)&data
[12] = cpu_to_le16(ctrl
->wCompQuality
);
320 *(__le16
*)&data
[14] = cpu_to_le16(ctrl
->wCompWindowSize
);
321 *(__le16
*)&data
[16] = cpu_to_le16(ctrl
->wDelay
);
322 put_unaligned_le32(ctrl
->dwMaxVideoFrameSize
, &data
[18]);
323 put_unaligned_le32(ctrl
->dwMaxPayloadTransferSize
, &data
[22]);
326 put_unaligned_le32(ctrl
->dwClockFrequency
, &data
[26]);
327 data
[30] = ctrl
->bmFramingInfo
;
328 data
[31] = ctrl
->bPreferedVersion
;
329 data
[32] = ctrl
->bMinVersion
;
330 data
[33] = ctrl
->bMaxVersion
;
333 ret
= __uvc_query_ctrl(stream
->dev
, UVC_SET_CUR
, 0, stream
->intfnum
,
334 probe
? UVC_VS_PROBE_CONTROL
: UVC_VS_COMMIT_CONTROL
, data
,
335 size
, uvc_timeout_param
);
337 uvc_printk(KERN_ERR
, "Failed to set UVC %s control : "
338 "%d (exp. %u).\n", probe
? "probe" : "commit",
347 int uvc_probe_video(struct uvc_streaming
*stream
,
348 struct uvc_streaming_control
*probe
)
350 struct uvc_streaming_control probe_min
, probe_max
;
355 /* Perform probing. The device should adjust the requested values
356 * according to its capabilities. However, some devices, namely the
357 * first generation UVC Logitech webcams, don't implement the Video
358 * Probe control properly, and just return the needed bandwidth. For
359 * that reason, if the needed bandwidth exceeds the maximum available
360 * bandwidth, try to lower the quality.
362 ret
= uvc_set_video_ctrl(stream
, probe
, 1);
366 /* Get the minimum and maximum values for compression settings. */
367 if (!(stream
->dev
->quirks
& UVC_QUIRK_PROBE_MINMAX
)) {
368 ret
= uvc_get_video_ctrl(stream
, &probe_min
, 1, UVC_GET_MIN
);
371 ret
= uvc_get_video_ctrl(stream
, &probe_max
, 1, UVC_GET_MAX
);
375 probe
->wCompQuality
= probe_max
.wCompQuality
;
378 for (i
= 0; i
< 2; ++i
) {
379 ret
= uvc_set_video_ctrl(stream
, probe
, 1);
382 ret
= uvc_get_video_ctrl(stream
, probe
, 1, UVC_GET_CUR
);
386 if (stream
->intf
->num_altsetting
== 1)
389 bandwidth
= probe
->dwMaxPayloadTransferSize
;
390 if (bandwidth
<= stream
->maxpsize
)
393 if (stream
->dev
->quirks
& UVC_QUIRK_PROBE_MINMAX
) {
398 /* TODO: negotiate compression parameters */
399 probe
->wKeyFrameRate
= probe_min
.wKeyFrameRate
;
400 probe
->wPFrameRate
= probe_min
.wPFrameRate
;
401 probe
->wCompQuality
= probe_max
.wCompQuality
;
402 probe
->wCompWindowSize
= probe_min
.wCompWindowSize
;
409 static int uvc_commit_video(struct uvc_streaming
*stream
,
410 struct uvc_streaming_control
*probe
)
412 return uvc_set_video_ctrl(stream
, probe
, 0);
415 /* -----------------------------------------------------------------------------
416 * Clocks and timestamps
419 static inline ktime_t
uvc_video_get_time(void)
421 if (uvc_clock_param
== CLOCK_MONOTONIC
)
424 return ktime_get_real();
428 uvc_video_clock_decode(struct uvc_streaming
*stream
, struct uvc_buffer
*buf
,
429 const u8
*data
, int len
)
431 struct uvc_clock_sample
*sample
;
432 unsigned int header_size
;
433 bool has_pts
= false;
434 bool has_scr
= false;
440 switch (data
[1] & (UVC_STREAM_PTS
| UVC_STREAM_SCR
)) {
441 case UVC_STREAM_PTS
| UVC_STREAM_SCR
:
459 /* Check for invalid headers. */
460 if (len
< header_size
)
463 /* Extract the timestamps:
465 * - store the frame PTS in the buffer structure
466 * - if the SCR field is present, retrieve the host SOF counter and
467 * kernel timestamps and store them with the SCR STC and SOF fields
470 if (has_pts
&& buf
!= NULL
)
471 buf
->pts
= get_unaligned_le32(&data
[2]);
476 /* To limit the amount of data, drop SCRs with an SOF identical to the
479 dev_sof
= get_unaligned_le16(&data
[header_size
- 2]);
480 if (dev_sof
== stream
->clock
.last_sof
)
483 stream
->clock
.last_sof
= dev_sof
;
485 host_sof
= usb_get_current_frame_number(stream
->dev
->udev
);
486 time
= uvc_video_get_time();
488 /* The UVC specification allows device implementations that can't obtain
489 * the USB frame number to keep their own frame counters as long as they
490 * match the size and frequency of the frame number associated with USB
491 * SOF tokens. The SOF values sent by such devices differ from the USB
492 * SOF tokens by a fixed offset that needs to be estimated and accounted
493 * for to make timestamp recovery as accurate as possible.
495 * The offset is estimated the first time a device SOF value is received
496 * as the difference between the host and device SOF values. As the two
497 * SOF values can differ slightly due to transmission delays, consider
498 * that the offset is null if the difference is not higher than 10 ms
499 * (negative differences can not happen and are thus considered as an
500 * offset). The video commit control wDelay field should be used to
501 * compute a dynamic threshold instead of using a fixed 10 ms value, but
502 * devices don't report reliable wDelay values.
504 * See uvc_video_clock_host_sof() for an explanation regarding why only
505 * the 8 LSBs of the delta are kept.
507 if (stream
->clock
.sof_offset
== (u16
)-1) {
508 u16 delta_sof
= (host_sof
- dev_sof
) & 255;
510 stream
->clock
.sof_offset
= delta_sof
;
512 stream
->clock
.sof_offset
= 0;
515 dev_sof
= (dev_sof
+ stream
->clock
.sof_offset
) & 2047;
517 spin_lock_irqsave(&stream
->clock
.lock
, flags
);
519 sample
= &stream
->clock
.samples
[stream
->clock
.head
];
520 sample
->dev_stc
= get_unaligned_le32(&data
[header_size
- 6]);
521 sample
->dev_sof
= dev_sof
;
522 sample
->host_sof
= host_sof
;
523 sample
->host_time
= time
;
525 /* Update the sliding window head and count. */
526 stream
->clock
.head
= (stream
->clock
.head
+ 1) % stream
->clock
.size
;
528 if (stream
->clock
.count
< stream
->clock
.size
)
529 stream
->clock
.count
++;
531 spin_unlock_irqrestore(&stream
->clock
.lock
, flags
);
534 static void uvc_video_clock_reset(struct uvc_streaming
*stream
)
536 struct uvc_clock
*clock
= &stream
->clock
;
540 clock
->last_sof
= -1;
541 clock
->sof_offset
= -1;
544 static int uvc_video_clock_init(struct uvc_streaming
*stream
)
546 struct uvc_clock
*clock
= &stream
->clock
;
548 spin_lock_init(&clock
->lock
);
551 clock
->samples
= kmalloc_array(clock
->size
, sizeof(*clock
->samples
),
553 if (clock
->samples
== NULL
)
556 uvc_video_clock_reset(stream
);
561 static void uvc_video_clock_cleanup(struct uvc_streaming
*stream
)
563 kfree(stream
->clock
.samples
);
564 stream
->clock
.samples
= NULL
;
568 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
570 * Host SOF counters reported by usb_get_current_frame_number() usually don't
571 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
572 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
573 * controller and its configuration.
575 * We thus need to recover the SOF value corresponding to the host frame number.
576 * As the device and host frame numbers are sampled in a short interval, the
577 * difference between their values should be equal to a small delta plus an
578 * integer multiple of 256 caused by the host frame number limited precision.
580 * To obtain the recovered host SOF value, compute the small delta by masking
581 * the high bits of the host frame counter and device SOF difference and add it
582 * to the device SOF value.
584 static u16
uvc_video_clock_host_sof(const struct uvc_clock_sample
*sample
)
586 /* The delta value can be negative. */
589 delta_sof
= (sample
->host_sof
- sample
->dev_sof
) & 255;
591 return (sample
->dev_sof
+ delta_sof
) & 2047;
595 * uvc_video_clock_update - Update the buffer timestamp
597 * This function converts the buffer PTS timestamp to the host clock domain by
598 * going through the USB SOF clock domain and stores the result in the V4L2
599 * buffer timestamp field.
601 * The relationship between the device clock and the host clock isn't known.
602 * However, the device and the host share the common USB SOF clock which can be
603 * used to recover that relationship.
605 * The relationship between the device clock and the USB SOF clock is considered
606 * to be linear over the clock samples sliding window and is given by
610 * Several methods to compute the slope (m) and intercept (p) can be used. As
611 * the clock drift should be small compared to the sliding window size, we
612 * assume that the line that goes through the points at both ends of the window
613 * is a good approximation. Naming those points P1 and P2, we get
615 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
616 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
620 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
622 * to avoid losing precision in the division. Similarly, the host timestamp is
625 * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
627 * SOF values are coded on 11 bits by USB. We extend their precision with 16
628 * decimal bits, leading to a 11.16 coding.
630 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
631 * be normalized using the nominal device clock frequency reported through the
634 * Both the PTS/STC and SOF counters roll over, after a fixed but device
635 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
636 * sliding window size is smaller than the rollover period, differences computed
637 * on unsigned integers will produce the correct result. However, the p term in
638 * the linear relations will be miscomputed.
640 * To fix the issue, we subtract a constant from the PTS and STC values to bring
641 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
642 * the 32 bit range without any rollover.
644 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
645 * computed by (1) will never be smaller than 0. This offset is then compensated
646 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
647 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
648 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
649 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
650 * SOF value at the end of the sliding window.
652 * Finally we subtract a constant from the host timestamps to bring the first
653 * timestamp of the sliding window to 1s.
655 void uvc_video_clock_update(struct uvc_streaming
*stream
,
656 struct vb2_v4l2_buffer
*vbuf
,
657 struct uvc_buffer
*buf
)
659 struct uvc_clock
*clock
= &stream
->clock
;
660 struct uvc_clock_sample
*first
;
661 struct uvc_clock_sample
*last
;
671 if (!uvc_hw_timestamps_param
)
675 * We will get called from __vb2_queue_cancel() if there are buffers
676 * done but not dequeued by the user, but the sample array has already
677 * been released at that time. Just bail out in that case.
682 spin_lock_irqsave(&clock
->lock
, flags
);
684 if (clock
->count
< clock
->size
)
687 first
= &clock
->samples
[clock
->head
];
688 last
= &clock
->samples
[(clock
->head
- 1) % clock
->size
];
690 /* First step, PTS to SOF conversion. */
691 delta_stc
= buf
->pts
- (1UL << 31);
692 x1
= first
->dev_stc
- delta_stc
;
693 x2
= last
->dev_stc
- delta_stc
;
697 y1
= (first
->dev_sof
+ 2048) << 16;
698 y2
= (last
->dev_sof
+ 2048) << 16;
702 y
= (u64
)(y2
- y1
) * (1ULL << 31) + (u64
)y1
* (u64
)x2
704 y
= div_u64(y
, x2
- x1
);
708 uvc_trace(UVC_TRACE_CLOCK
, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
709 "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
710 stream
->dev
->name
, buf
->pts
,
711 y
>> 16, div_u64((y
& 0xffff) * 1000000, 65536),
712 sof
>> 16, div_u64(((u64
)sof
& 0xffff) * 1000000LLU, 65536),
713 x1
, x2
, y1
, y2
, clock
->sof_offset
);
715 /* Second step, SOF to host clock conversion. */
716 x1
= (uvc_video_clock_host_sof(first
) + 2048) << 16;
717 x2
= (uvc_video_clock_host_sof(last
) + 2048) << 16;
724 y2
= (u32
)ktime_to_ns(ktime_sub(last
->host_time
, first
->host_time
)) + y1
;
726 /* Interpolated and host SOF timestamps can wrap around at slightly
727 * different times. Handle this by adding or removing 2048 to or from
728 * the computed SOF value to keep it close to the SOF samples mean
731 mean
= (x1
+ x2
) / 2;
732 if (mean
- (1024 << 16) > sof
)
734 else if (sof
> mean
+ (1024 << 16))
737 y
= (u64
)(y2
- y1
) * (u64
)sof
+ (u64
)y1
* (u64
)x2
739 y
= div_u64(y
, x2
- x1
);
741 timestamp
= ktime_to_ns(first
->host_time
) + y
- y1
;
743 uvc_trace(UVC_TRACE_CLOCK
, "%s: SOF %u.%06llu y %llu ts %llu "
744 "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
746 sof
>> 16, div_u64(((u64
)sof
& 0xffff) * 1000000LLU, 65536),
747 y
, timestamp
, vbuf
->vb2_buf
.timestamp
,
748 x1
, first
->host_sof
, first
->dev_sof
,
749 x2
, last
->host_sof
, last
->dev_sof
, y1
, y2
);
751 /* Update the V4L2 buffer. */
752 vbuf
->vb2_buf
.timestamp
= timestamp
;
755 spin_unlock_irqrestore(&clock
->lock
, flags
);
758 /* ------------------------------------------------------------------------
762 static void uvc_video_stats_decode(struct uvc_streaming
*stream
,
763 const u8
*data
, int len
)
765 unsigned int header_size
;
766 bool has_pts
= false;
767 bool has_scr
= false;
772 if (stream
->stats
.stream
.nb_frames
== 0 &&
773 stream
->stats
.frame
.nb_packets
== 0)
774 stream
->stats
.stream
.start_ts
= ktime_get();
776 switch (data
[1] & (UVC_STREAM_PTS
| UVC_STREAM_SCR
)) {
777 case UVC_STREAM_PTS
| UVC_STREAM_SCR
:
795 /* Check for invalid headers. */
796 if (len
< header_size
|| data
[0] < header_size
) {
797 stream
->stats
.frame
.nb_invalid
++;
801 /* Extract the timestamps. */
803 pts
= get_unaligned_le32(&data
[2]);
806 scr_stc
= get_unaligned_le32(&data
[header_size
- 6]);
807 scr_sof
= get_unaligned_le16(&data
[header_size
- 2]);
810 /* Is PTS constant through the whole frame ? */
811 if (has_pts
&& stream
->stats
.frame
.nb_pts
) {
812 if (stream
->stats
.frame
.pts
!= pts
) {
813 stream
->stats
.frame
.nb_pts_diffs
++;
814 stream
->stats
.frame
.last_pts_diff
=
815 stream
->stats
.frame
.nb_packets
;
820 stream
->stats
.frame
.nb_pts
++;
821 stream
->stats
.frame
.pts
= pts
;
824 /* Do all frames have a PTS in their first non-empty packet, or before
825 * their first empty packet ?
827 if (stream
->stats
.frame
.size
== 0) {
828 if (len
> header_size
)
829 stream
->stats
.frame
.has_initial_pts
= has_pts
;
830 if (len
== header_size
&& has_pts
)
831 stream
->stats
.frame
.has_early_pts
= true;
834 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
835 if (has_scr
&& stream
->stats
.frame
.nb_scr
) {
836 if (stream
->stats
.frame
.scr_stc
!= scr_stc
)
837 stream
->stats
.frame
.nb_scr_diffs
++;
841 /* Expand the SOF counter to 32 bits and store its value. */
842 if (stream
->stats
.stream
.nb_frames
> 0 ||
843 stream
->stats
.frame
.nb_scr
> 0)
844 stream
->stats
.stream
.scr_sof_count
+=
845 (scr_sof
- stream
->stats
.stream
.scr_sof
) % 2048;
846 stream
->stats
.stream
.scr_sof
= scr_sof
;
848 stream
->stats
.frame
.nb_scr
++;
849 stream
->stats
.frame
.scr_stc
= scr_stc
;
850 stream
->stats
.frame
.scr_sof
= scr_sof
;
852 if (scr_sof
< stream
->stats
.stream
.min_sof
)
853 stream
->stats
.stream
.min_sof
= scr_sof
;
854 if (scr_sof
> stream
->stats
.stream
.max_sof
)
855 stream
->stats
.stream
.max_sof
= scr_sof
;
858 /* Record the first non-empty packet number. */
859 if (stream
->stats
.frame
.size
== 0 && len
> header_size
)
860 stream
->stats
.frame
.first_data
= stream
->stats
.frame
.nb_packets
;
862 /* Update the frame size. */
863 stream
->stats
.frame
.size
+= len
- header_size
;
865 /* Update the packets counters. */
866 stream
->stats
.frame
.nb_packets
++;
867 if (len
<= header_size
)
868 stream
->stats
.frame
.nb_empty
++;
870 if (data
[1] & UVC_STREAM_ERR
)
871 stream
->stats
.frame
.nb_errors
++;
874 static void uvc_video_stats_update(struct uvc_streaming
*stream
)
876 struct uvc_stats_frame
*frame
= &stream
->stats
.frame
;
878 uvc_trace(UVC_TRACE_STATS
, "frame %u stats: %u/%u/%u packets, "
879 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
880 "last pts/stc/sof %u/%u/%u\n",
881 stream
->sequence
, frame
->first_data
,
882 frame
->nb_packets
- frame
->nb_empty
, frame
->nb_packets
,
883 frame
->nb_pts_diffs
, frame
->last_pts_diff
, frame
->nb_pts
,
884 frame
->has_early_pts
? "" : "!",
885 frame
->has_initial_pts
? "" : "!",
886 frame
->nb_scr_diffs
, frame
->nb_scr
,
887 frame
->pts
, frame
->scr_stc
, frame
->scr_sof
);
889 stream
->stats
.stream
.nb_frames
++;
890 stream
->stats
.stream
.nb_packets
+= stream
->stats
.frame
.nb_packets
;
891 stream
->stats
.stream
.nb_empty
+= stream
->stats
.frame
.nb_empty
;
892 stream
->stats
.stream
.nb_errors
+= stream
->stats
.frame
.nb_errors
;
893 stream
->stats
.stream
.nb_invalid
+= stream
->stats
.frame
.nb_invalid
;
895 if (frame
->has_early_pts
)
896 stream
->stats
.stream
.nb_pts_early
++;
897 if (frame
->has_initial_pts
)
898 stream
->stats
.stream
.nb_pts_initial
++;
899 if (frame
->last_pts_diff
<= frame
->first_data
)
900 stream
->stats
.stream
.nb_pts_constant
++;
901 if (frame
->nb_scr
>= frame
->nb_packets
- frame
->nb_empty
)
902 stream
->stats
.stream
.nb_scr_count_ok
++;
903 if (frame
->nb_scr_diffs
+ 1 == frame
->nb_scr
)
904 stream
->stats
.stream
.nb_scr_diffs_ok
++;
906 memset(&stream
->stats
.frame
, 0, sizeof(stream
->stats
.frame
));
909 size_t uvc_video_stats_dump(struct uvc_streaming
*stream
, char *buf
,
912 unsigned int scr_sof_freq
;
913 unsigned int duration
;
916 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
917 * frequency this will not overflow before more than 1h.
919 duration
= ktime_ms_delta(stream
->stats
.stream
.stop_ts
,
920 stream
->stats
.stream
.start_ts
);
922 scr_sof_freq
= stream
->stats
.stream
.scr_sof_count
* 1000
927 count
+= scnprintf(buf
+ count
, size
- count
,
928 "frames: %u\npackets: %u\nempty: %u\n"
929 "errors: %u\ninvalid: %u\n",
930 stream
->stats
.stream
.nb_frames
,
931 stream
->stats
.stream
.nb_packets
,
932 stream
->stats
.stream
.nb_empty
,
933 stream
->stats
.stream
.nb_errors
,
934 stream
->stats
.stream
.nb_invalid
);
935 count
+= scnprintf(buf
+ count
, size
- count
,
936 "pts: %u early, %u initial, %u ok\n",
937 stream
->stats
.stream
.nb_pts_early
,
938 stream
->stats
.stream
.nb_pts_initial
,
939 stream
->stats
.stream
.nb_pts_constant
);
940 count
+= scnprintf(buf
+ count
, size
- count
,
941 "scr: %u count ok, %u diff ok\n",
942 stream
->stats
.stream
.nb_scr_count_ok
,
943 stream
->stats
.stream
.nb_scr_diffs_ok
);
944 count
+= scnprintf(buf
+ count
, size
- count
,
945 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
946 stream
->stats
.stream
.min_sof
,
947 stream
->stats
.stream
.max_sof
,
948 scr_sof_freq
/ 1000, scr_sof_freq
% 1000);
953 static void uvc_video_stats_start(struct uvc_streaming
*stream
)
955 memset(&stream
->stats
, 0, sizeof(stream
->stats
));
956 stream
->stats
.stream
.min_sof
= 2048;
959 static void uvc_video_stats_stop(struct uvc_streaming
*stream
)
961 stream
->stats
.stream
.stop_ts
= ktime_get();
964 /* ------------------------------------------------------------------------
968 /* Video payload decoding is handled by uvc_video_decode_start(),
969 * uvc_video_decode_data() and uvc_video_decode_end().
971 * uvc_video_decode_start is called with URB data at the start of a bulk or
972 * isochronous payload. It processes header data and returns the header size
973 * in bytes if successful. If an error occurs, it returns a negative error
974 * code. The following error codes have special meanings.
976 * - EAGAIN informs the caller that the current video buffer should be marked
977 * as done, and that the function should be called again with the same data
978 * and a new video buffer. This is used when end of frame conditions can be
979 * reliably detected at the beginning of the next frame only.
981 * If an error other than -EAGAIN is returned, the caller will drop the current
982 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
983 * made until the next payload. -ENODATA can be used to drop the current
984 * payload if no other error code is appropriate.
986 * uvc_video_decode_data is called for every URB with URB data. It copies the
987 * data to the video buffer.
989 * uvc_video_decode_end is called with header data at the end of a bulk or
990 * isochronous payload. It performs any additional header data processing and
991 * returns 0 or a negative error code if an error occurred. As header data have
992 * already been processed by uvc_video_decode_start, this functions isn't
993 * required to perform sanity checks a second time.
995 * For isochronous transfers where a payload is always transferred in a single
996 * URB, the three functions will be called in a row.
998 * To let the decoder process header data and update its internal state even
999 * when no video buffer is available, uvc_video_decode_start must be prepared
1000 * to be called with a NULL buf parameter. uvc_video_decode_data and
1001 * uvc_video_decode_end will never be called with a NULL buffer.
1003 static int uvc_video_decode_start(struct uvc_streaming
*stream
,
1004 struct uvc_buffer
*buf
, const u8
*data
, int len
)
1009 * - packet must be at least 2 bytes long
1010 * - bHeaderLength value must be at least 2 bytes (see above)
1011 * - bHeaderLength value can't be larger than the packet size.
1013 if (len
< 2 || data
[0] < 2 || data
[0] > len
) {
1014 stream
->stats
.frame
.nb_invalid
++;
1018 fid
= data
[1] & UVC_STREAM_FID
;
1020 /* Increase the sequence number regardless of any buffer states, so
1021 * that discontinuous sequence numbers always indicate lost frames.
1023 if (stream
->last_fid
!= fid
) {
1025 if (stream
->sequence
)
1026 uvc_video_stats_update(stream
);
1029 uvc_video_clock_decode(stream
, buf
, data
, len
);
1030 uvc_video_stats_decode(stream
, data
, len
);
1032 /* Store the payload FID bit and return immediately when the buffer is
1036 stream
->last_fid
= fid
;
1040 /* Mark the buffer as bad if the error bit is set. */
1041 if (data
[1] & UVC_STREAM_ERR
) {
1042 uvc_trace(UVC_TRACE_FRAME
, "Marking buffer as bad (error bit "
1047 /* Synchronize to the input stream by waiting for the FID bit to be
1048 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1049 * stream->last_fid is initialized to -1, so the first isochronous
1050 * frame will always be in sync.
1052 * If the device doesn't toggle the FID bit, invert stream->last_fid
1053 * when the EOF bit is set to force synchronisation on the next packet.
1055 if (buf
->state
!= UVC_BUF_STATE_ACTIVE
) {
1056 if (fid
== stream
->last_fid
) {
1057 uvc_trace(UVC_TRACE_FRAME
, "Dropping payload (out of "
1059 if ((stream
->dev
->quirks
& UVC_QUIRK_STREAM_NO_FID
) &&
1060 (data
[1] & UVC_STREAM_EOF
))
1061 stream
->last_fid
^= UVC_STREAM_FID
;
1065 buf
->buf
.field
= V4L2_FIELD_NONE
;
1066 buf
->buf
.sequence
= stream
->sequence
;
1067 buf
->buf
.vb2_buf
.timestamp
= ktime_to_ns(uvc_video_get_time());
1069 /* TODO: Handle PTS and SCR. */
1070 buf
->state
= UVC_BUF_STATE_ACTIVE
;
1073 /* Mark the buffer as done if we're at the beginning of a new frame.
1074 * End of frame detection is better implemented by checking the EOF
1075 * bit (FID bit toggling is delayed by one frame compared to the EOF
1076 * bit), but some devices don't set the bit at end of frame (and the
1077 * last payload can be lost anyway). We thus must check if the FID has
1080 * stream->last_fid is initialized to -1, so the first isochronous
1081 * frame will never trigger an end of frame detection.
1083 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1084 * as it doesn't make sense to return an empty buffer. This also
1085 * avoids detecting end of frame conditions at FID toggling if the
1086 * previous payload had the EOF bit set.
1088 if (fid
!= stream
->last_fid
&& buf
->bytesused
!= 0) {
1089 uvc_trace(UVC_TRACE_FRAME
, "Frame complete (FID bit "
1091 buf
->state
= UVC_BUF_STATE_READY
;
1095 stream
->last_fid
= fid
;
1101 * uvc_video_decode_data_work: Asynchronous memcpy processing
1103 * Copy URB data to video buffers in process context, releasing buffer
1104 * references and requeuing the URB when done.
1106 static void uvc_video_copy_data_work(struct work_struct
*work
)
1108 struct uvc_urb
*uvc_urb
= container_of(work
, struct uvc_urb
, work
);
1112 for (i
= 0; i
< uvc_urb
->async_operations
; i
++) {
1113 struct uvc_copy_op
*op
= &uvc_urb
->copy_operations
[i
];
1115 memcpy(op
->dst
, op
->src
, op
->len
);
1117 /* Release reference taken on this buffer. */
1118 uvc_queue_buffer_release(op
->buf
);
1121 ret
= usb_submit_urb(uvc_urb
->urb
, GFP_KERNEL
);
1123 uvc_printk(KERN_ERR
, "Failed to resubmit video URB (%d).\n",
1127 static void uvc_video_decode_data(struct uvc_urb
*uvc_urb
,
1128 struct uvc_buffer
*buf
, const u8
*data
, int len
)
1130 unsigned int active_op
= uvc_urb
->async_operations
;
1131 struct uvc_copy_op
*op
= &uvc_urb
->copy_operations
[active_op
];
1132 unsigned int maxlen
;
1137 maxlen
= buf
->length
- buf
->bytesused
;
1139 /* Take a buffer reference for async work. */
1140 kref_get(&buf
->ref
);
1144 op
->dst
= buf
->mem
+ buf
->bytesused
;
1145 op
->len
= min_t(unsigned int, len
, maxlen
);
1147 buf
->bytesused
+= op
->len
;
1149 /* Complete the current frame if the buffer size was exceeded. */
1151 uvc_trace(UVC_TRACE_FRAME
, "Frame complete (overflow).\n");
1153 buf
->state
= UVC_BUF_STATE_READY
;
1156 uvc_urb
->async_operations
++;
1159 static void uvc_video_decode_end(struct uvc_streaming
*stream
,
1160 struct uvc_buffer
*buf
, const u8
*data
, int len
)
1162 /* Mark the buffer as done if the EOF marker is set. */
1163 if (data
[1] & UVC_STREAM_EOF
&& buf
->bytesused
!= 0) {
1164 uvc_trace(UVC_TRACE_FRAME
, "Frame complete (EOF found).\n");
1166 uvc_trace(UVC_TRACE_FRAME
, "EOF in empty payload.\n");
1167 buf
->state
= UVC_BUF_STATE_READY
;
1168 if (stream
->dev
->quirks
& UVC_QUIRK_STREAM_NO_FID
)
1169 stream
->last_fid
^= UVC_STREAM_FID
;
1173 /* Video payload encoding is handled by uvc_video_encode_header() and
1174 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1176 * uvc_video_encode_header is called at the start of a payload. It adds header
1177 * data to the transfer buffer and returns the header size. As the only known
1178 * UVC output device transfers a whole frame in a single payload, the EOF bit
1179 * is always set in the header.
1181 * uvc_video_encode_data is called for every URB and copies the data from the
1182 * video buffer to the transfer buffer.
1184 static int uvc_video_encode_header(struct uvc_streaming
*stream
,
1185 struct uvc_buffer
*buf
, u8
*data
, int len
)
1187 data
[0] = 2; /* Header length */
1188 data
[1] = UVC_STREAM_EOH
| UVC_STREAM_EOF
1189 | (stream
->last_fid
& UVC_STREAM_FID
);
1193 static int uvc_video_encode_data(struct uvc_streaming
*stream
,
1194 struct uvc_buffer
*buf
, u8
*data
, int len
)
1196 struct uvc_video_queue
*queue
= &stream
->queue
;
1197 unsigned int nbytes
;
1200 /* Copy video data to the URB buffer. */
1201 mem
= buf
->mem
+ queue
->buf_used
;
1202 nbytes
= min((unsigned int)len
, buf
->bytesused
- queue
->buf_used
);
1203 nbytes
= min(stream
->bulk
.max_payload_size
- stream
->bulk
.payload_size
,
1205 memcpy(data
, mem
, nbytes
);
1207 queue
->buf_used
+= nbytes
;
1212 /* ------------------------------------------------------------------------
1217 * Additionally to the payload headers we also want to provide the user with USB
1218 * Frame Numbers and system time values. The resulting buffer is thus composed
1219 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
1220 * Number, and a copy of the payload header.
1222 * Ideally we want to capture all payload headers for each frame. However, their
1223 * number is unknown and unbound. We thus drop headers that contain no vendor
1224 * data and that either contain no SCR value or an SCR value identical to the
1227 static void uvc_video_decode_meta(struct uvc_streaming
*stream
,
1228 struct uvc_buffer
*meta_buf
,
1229 const u8
*mem
, unsigned int length
)
1231 struct uvc_meta_buf
*meta
;
1233 bool has_pts
, has_scr
;
1234 unsigned long flags
;
1239 if (!meta_buf
|| length
== 2)
1242 if (meta_buf
->length
- meta_buf
->bytesused
<
1243 length
+ sizeof(meta
->ns
) + sizeof(meta
->sof
)) {
1244 meta_buf
->error
= 1;
1248 has_pts
= mem
[1] & UVC_STREAM_PTS
;
1249 has_scr
= mem
[1] & UVC_STREAM_SCR
;
1261 if (stream
->meta
.format
== V4L2_META_FMT_UVC
)
1264 if (length
== len_std
&& (!has_scr
||
1265 !memcmp(scr
, stream
->clock
.last_scr
, 6)))
1268 meta
= (struct uvc_meta_buf
*)((u8
*)meta_buf
->mem
+ meta_buf
->bytesused
);
1269 local_irq_save(flags
);
1270 time
= uvc_video_get_time();
1271 sof
= usb_get_current_frame_number(stream
->dev
->udev
);
1272 local_irq_restore(flags
);
1273 put_unaligned(ktime_to_ns(time
), &meta
->ns
);
1274 put_unaligned(sof
, &meta
->sof
);
1277 memcpy(stream
->clock
.last_scr
, scr
, 6);
1279 memcpy(&meta
->length
, mem
, length
);
1280 meta_buf
->bytesused
+= length
+ sizeof(meta
->ns
) + sizeof(meta
->sof
);
1282 uvc_trace(UVC_TRACE_FRAME
,
1283 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1284 __func__
, ktime_to_ns(time
), meta
->sof
, meta
->length
,
1286 has_pts
? *(u32
*)meta
->buf
: 0,
1287 has_scr
? *(u32
*)scr
: 0,
1288 has_scr
? *(u32
*)(scr
+ 4) & 0x7ff : 0);
1291 /* ------------------------------------------------------------------------
1296 * Set error flag for incomplete buffer.
1298 static void uvc_video_validate_buffer(const struct uvc_streaming
*stream
,
1299 struct uvc_buffer
*buf
)
1301 if (stream
->ctrl
.dwMaxVideoFrameSize
!= buf
->bytesused
&&
1302 !(stream
->cur_format
->flags
& UVC_FMT_FLAG_COMPRESSED
))
1307 * Completion handler for video URBs.
1310 static void uvc_video_next_buffers(struct uvc_streaming
*stream
,
1311 struct uvc_buffer
**video_buf
, struct uvc_buffer
**meta_buf
)
1313 uvc_video_validate_buffer(stream
, *video_buf
);
1316 struct vb2_v4l2_buffer
*vb2_meta
= &(*meta_buf
)->buf
;
1317 const struct vb2_v4l2_buffer
*vb2_video
= &(*video_buf
)->buf
;
1319 vb2_meta
->sequence
= vb2_video
->sequence
;
1320 vb2_meta
->field
= vb2_video
->field
;
1321 vb2_meta
->vb2_buf
.timestamp
= vb2_video
->vb2_buf
.timestamp
;
1323 (*meta_buf
)->state
= UVC_BUF_STATE_READY
;
1324 if (!(*meta_buf
)->error
)
1325 (*meta_buf
)->error
= (*video_buf
)->error
;
1326 *meta_buf
= uvc_queue_next_buffer(&stream
->meta
.queue
,
1329 *video_buf
= uvc_queue_next_buffer(&stream
->queue
, *video_buf
);
1332 static void uvc_video_decode_isoc(struct uvc_urb
*uvc_urb
,
1333 struct uvc_buffer
*buf
, struct uvc_buffer
*meta_buf
)
1335 struct urb
*urb
= uvc_urb
->urb
;
1336 struct uvc_streaming
*stream
= uvc_urb
->stream
;
1340 for (i
= 0; i
< urb
->number_of_packets
; ++i
) {
1341 if (urb
->iso_frame_desc
[i
].status
< 0) {
1342 uvc_trace(UVC_TRACE_FRAME
, "USB isochronous frame "
1343 "lost (%d).\n", urb
->iso_frame_desc
[i
].status
);
1344 /* Mark the buffer as faulty. */
1350 /* Decode the payload header. */
1351 mem
= urb
->transfer_buffer
+ urb
->iso_frame_desc
[i
].offset
;
1353 ret
= uvc_video_decode_start(stream
, buf
, mem
,
1354 urb
->iso_frame_desc
[i
].actual_length
);
1356 uvc_video_next_buffers(stream
, &buf
, &meta_buf
);
1357 } while (ret
== -EAGAIN
);
1362 uvc_video_decode_meta(stream
, meta_buf
, mem
, ret
);
1364 /* Decode the payload data. */
1365 uvc_video_decode_data(uvc_urb
, buf
, mem
+ ret
,
1366 urb
->iso_frame_desc
[i
].actual_length
- ret
);
1368 /* Process the header again. */
1369 uvc_video_decode_end(stream
, buf
, mem
,
1370 urb
->iso_frame_desc
[i
].actual_length
);
1372 if (buf
->state
== UVC_BUF_STATE_READY
)
1373 uvc_video_next_buffers(stream
, &buf
, &meta_buf
);
1377 static void uvc_video_decode_bulk(struct uvc_urb
*uvc_urb
,
1378 struct uvc_buffer
*buf
, struct uvc_buffer
*meta_buf
)
1380 struct urb
*urb
= uvc_urb
->urb
;
1381 struct uvc_streaming
*stream
= uvc_urb
->stream
;
1386 * Ignore ZLPs if they're not part of a frame, otherwise process them
1387 * to trigger the end of payload detection.
1389 if (urb
->actual_length
== 0 && stream
->bulk
.header_size
== 0)
1392 mem
= urb
->transfer_buffer
;
1393 len
= urb
->actual_length
;
1394 stream
->bulk
.payload_size
+= len
;
1396 /* If the URB is the first of its payload, decode and save the
1399 if (stream
->bulk
.header_size
== 0 && !stream
->bulk
.skip_payload
) {
1401 ret
= uvc_video_decode_start(stream
, buf
, mem
, len
);
1403 uvc_video_next_buffers(stream
, &buf
, &meta_buf
);
1404 } while (ret
== -EAGAIN
);
1406 /* If an error occurred skip the rest of the payload. */
1407 if (ret
< 0 || buf
== NULL
) {
1408 stream
->bulk
.skip_payload
= 1;
1410 memcpy(stream
->bulk
.header
, mem
, ret
);
1411 stream
->bulk
.header_size
= ret
;
1413 uvc_video_decode_meta(stream
, meta_buf
, mem
, ret
);
1420 /* The buffer queue might have been cancelled while a bulk transfer
1421 * was in progress, so we can reach here with buf equal to NULL. Make
1422 * sure buf is never dereferenced if NULL.
1425 /* Prepare video data for processing. */
1426 if (!stream
->bulk
.skip_payload
&& buf
!= NULL
)
1427 uvc_video_decode_data(uvc_urb
, buf
, mem
, len
);
1429 /* Detect the payload end by a URB smaller than the maximum size (or
1430 * a payload size equal to the maximum) and process the header again.
1432 if (urb
->actual_length
< urb
->transfer_buffer_length
||
1433 stream
->bulk
.payload_size
>= stream
->bulk
.max_payload_size
) {
1434 if (!stream
->bulk
.skip_payload
&& buf
!= NULL
) {
1435 uvc_video_decode_end(stream
, buf
, stream
->bulk
.header
,
1436 stream
->bulk
.payload_size
);
1437 if (buf
->state
== UVC_BUF_STATE_READY
)
1438 uvc_video_next_buffers(stream
, &buf
, &meta_buf
);
1441 stream
->bulk
.header_size
= 0;
1442 stream
->bulk
.skip_payload
= 0;
1443 stream
->bulk
.payload_size
= 0;
1447 static void uvc_video_encode_bulk(struct uvc_urb
*uvc_urb
,
1448 struct uvc_buffer
*buf
, struct uvc_buffer
*meta_buf
)
1450 struct urb
*urb
= uvc_urb
->urb
;
1451 struct uvc_streaming
*stream
= uvc_urb
->stream
;
1453 u8
*mem
= urb
->transfer_buffer
;
1454 int len
= stream
->urb_size
, ret
;
1457 urb
->transfer_buffer_length
= 0;
1461 /* If the URB is the first of its payload, add the header. */
1462 if (stream
->bulk
.header_size
== 0) {
1463 ret
= uvc_video_encode_header(stream
, buf
, mem
, len
);
1464 stream
->bulk
.header_size
= ret
;
1465 stream
->bulk
.payload_size
+= ret
;
1470 /* Process video data. */
1471 ret
= uvc_video_encode_data(stream
, buf
, mem
, len
);
1473 stream
->bulk
.payload_size
+= ret
;
1476 if (buf
->bytesused
== stream
->queue
.buf_used
||
1477 stream
->bulk
.payload_size
== stream
->bulk
.max_payload_size
) {
1478 if (buf
->bytesused
== stream
->queue
.buf_used
) {
1479 stream
->queue
.buf_used
= 0;
1480 buf
->state
= UVC_BUF_STATE_READY
;
1481 buf
->buf
.sequence
= ++stream
->sequence
;
1482 uvc_queue_next_buffer(&stream
->queue
, buf
);
1483 stream
->last_fid
^= UVC_STREAM_FID
;
1486 stream
->bulk
.header_size
= 0;
1487 stream
->bulk
.payload_size
= 0;
1490 urb
->transfer_buffer_length
= stream
->urb_size
- len
;
1493 static void uvc_video_complete(struct urb
*urb
)
1495 struct uvc_urb
*uvc_urb
= urb
->context
;
1496 struct uvc_streaming
*stream
= uvc_urb
->stream
;
1497 struct uvc_video_queue
*queue
= &stream
->queue
;
1498 struct uvc_video_queue
*qmeta
= &stream
->meta
.queue
;
1499 struct vb2_queue
*vb2_qmeta
= stream
->meta
.vdev
.queue
;
1500 struct uvc_buffer
*buf
= NULL
;
1501 struct uvc_buffer
*buf_meta
= NULL
;
1502 unsigned long flags
;
1505 switch (urb
->status
) {
1510 uvc_printk(KERN_WARNING
, "Non-zero status (%d) in video "
1511 "completion handler.\n", urb
->status
);
1513 case -ENOENT
: /* usb_poison_urb() called. */
1517 case -ECONNRESET
: /* usb_unlink_urb() called. */
1518 case -ESHUTDOWN
: /* The endpoint is being disabled. */
1519 uvc_queue_cancel(queue
, urb
->status
== -ESHUTDOWN
);
1521 uvc_queue_cancel(qmeta
, urb
->status
== -ESHUTDOWN
);
1525 buf
= uvc_queue_get_current_buffer(queue
);
1528 spin_lock_irqsave(&qmeta
->irqlock
, flags
);
1529 if (!list_empty(&qmeta
->irqqueue
))
1530 buf_meta
= list_first_entry(&qmeta
->irqqueue
,
1531 struct uvc_buffer
, queue
);
1532 spin_unlock_irqrestore(&qmeta
->irqlock
, flags
);
1535 /* Re-initialise the URB async work. */
1536 uvc_urb
->async_operations
= 0;
1539 * Process the URB headers, and optionally queue expensive memcpy tasks
1540 * to be deferred to a work queue.
1542 stream
->decode(uvc_urb
, buf
, buf_meta
);
1544 /* If no async work is needed, resubmit the URB immediately. */
1545 if (!uvc_urb
->async_operations
) {
1546 ret
= usb_submit_urb(uvc_urb
->urb
, GFP_ATOMIC
);
1548 uvc_printk(KERN_ERR
,
1549 "Failed to resubmit video URB (%d).\n",
1554 queue_work(stream
->async_wq
, &uvc_urb
->work
);
1558 * Free transfer buffers.
1560 static void uvc_free_urb_buffers(struct uvc_streaming
*stream
)
1562 struct uvc_urb
*uvc_urb
;
1564 for_each_uvc_urb(uvc_urb
, stream
) {
1565 if (!uvc_urb
->buffer
)
1568 #ifndef CONFIG_DMA_NONCOHERENT
1569 usb_free_coherent(stream
->dev
->udev
, stream
->urb_size
,
1570 uvc_urb
->buffer
, uvc_urb
->dma
);
1572 kfree(uvc_urb
->buffer
);
1574 uvc_urb
->buffer
= NULL
;
1577 stream
->urb_size
= 0;
1581 * Allocate transfer buffers. This function can be called with buffers
1582 * already allocated when resuming from suspend, in which case it will
1583 * return without touching the buffers.
1585 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1586 * system is too low on memory try successively smaller numbers of packets
1587 * until allocation succeeds.
1589 * Return the number of allocated packets on success or 0 when out of memory.
1591 static int uvc_alloc_urb_buffers(struct uvc_streaming
*stream
,
1592 unsigned int size
, unsigned int psize
, gfp_t gfp_flags
)
1594 unsigned int npackets
;
1597 /* Buffers are already allocated, bail out. */
1598 if (stream
->urb_size
)
1599 return stream
->urb_size
/ psize
;
1601 /* Compute the number of packets. Bulk endpoints might transfer UVC
1602 * payloads across multiple URBs.
1604 npackets
= DIV_ROUND_UP(size
, psize
);
1605 if (npackets
> UVC_MAX_PACKETS
)
1606 npackets
= UVC_MAX_PACKETS
;
1608 /* Retry allocations until one succeed. */
1609 for (; npackets
> 1; npackets
/= 2) {
1610 for (i
= 0; i
< UVC_URBS
; ++i
) {
1611 struct uvc_urb
*uvc_urb
= &stream
->uvc_urb
[i
];
1613 stream
->urb_size
= psize
* npackets
;
1614 #ifndef CONFIG_DMA_NONCOHERENT
1615 uvc_urb
->buffer
= usb_alloc_coherent(
1616 stream
->dev
->udev
, stream
->urb_size
,
1617 gfp_flags
| __GFP_NOWARN
, &uvc_urb
->dma
);
1620 kmalloc(stream
->urb_size
, gfp_flags
| __GFP_NOWARN
);
1622 if (!uvc_urb
->buffer
) {
1623 uvc_free_urb_buffers(stream
);
1627 uvc_urb
->stream
= stream
;
1630 if (i
== UVC_URBS
) {
1631 uvc_trace(UVC_TRACE_VIDEO
, "Allocated %u URB buffers "
1632 "of %ux%u bytes each.\n", UVC_URBS
, npackets
,
1638 uvc_trace(UVC_TRACE_VIDEO
, "Failed to allocate URB buffers (%u bytes "
1639 "per packet).\n", psize
);
1644 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1646 static void uvc_video_stop_transfer(struct uvc_streaming
*stream
,
1649 struct uvc_urb
*uvc_urb
;
1651 uvc_video_stats_stop(stream
);
1654 * We must poison the URBs rather than kill them to ensure that even
1655 * after the completion handler returns, any asynchronous workqueues
1656 * will be prevented from resubmitting the URBs.
1658 for_each_uvc_urb(uvc_urb
, stream
)
1659 usb_poison_urb(uvc_urb
->urb
);
1661 flush_workqueue(stream
->async_wq
);
1663 for_each_uvc_urb(uvc_urb
, stream
) {
1664 usb_free_urb(uvc_urb
->urb
);
1665 uvc_urb
->urb
= NULL
;
1669 uvc_free_urb_buffers(stream
);
1673 * Compute the maximum number of bytes per interval for an endpoint.
1675 static unsigned int uvc_endpoint_max_bpi(struct usb_device
*dev
,
1676 struct usb_host_endpoint
*ep
)
1681 switch (dev
->speed
) {
1682 case USB_SPEED_SUPER
:
1683 case USB_SPEED_SUPER_PLUS
:
1684 return le16_to_cpu(ep
->ss_ep_comp
.wBytesPerInterval
);
1685 case USB_SPEED_HIGH
:
1686 psize
= usb_endpoint_maxp(&ep
->desc
);
1687 mult
= usb_endpoint_maxp_mult(&ep
->desc
);
1688 return psize
* mult
;
1689 case USB_SPEED_WIRELESS
:
1690 psize
= usb_endpoint_maxp(&ep
->desc
);
1693 psize
= usb_endpoint_maxp(&ep
->desc
);
1699 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1700 * is given by the endpoint.
1702 static int uvc_init_video_isoc(struct uvc_streaming
*stream
,
1703 struct usb_host_endpoint
*ep
, gfp_t gfp_flags
)
1706 struct uvc_urb
*uvc_urb
;
1707 unsigned int npackets
, i
;
1711 psize
= uvc_endpoint_max_bpi(stream
->dev
->udev
, ep
);
1712 size
= stream
->ctrl
.dwMaxVideoFrameSize
;
1714 npackets
= uvc_alloc_urb_buffers(stream
, size
, psize
, gfp_flags
);
1718 size
= npackets
* psize
;
1720 for_each_uvc_urb(uvc_urb
, stream
) {
1721 urb
= usb_alloc_urb(npackets
, gfp_flags
);
1723 uvc_video_stop_transfer(stream
, 1);
1727 urb
->dev
= stream
->dev
->udev
;
1728 urb
->context
= uvc_urb
;
1729 urb
->pipe
= usb_rcvisocpipe(stream
->dev
->udev
,
1730 ep
->desc
.bEndpointAddress
);
1731 #ifndef CONFIG_DMA_NONCOHERENT
1732 urb
->transfer_flags
= URB_ISO_ASAP
| URB_NO_TRANSFER_DMA_MAP
;
1733 urb
->transfer_dma
= uvc_urb
->dma
;
1735 urb
->transfer_flags
= URB_ISO_ASAP
;
1737 urb
->interval
= ep
->desc
.bInterval
;
1738 urb
->transfer_buffer
= uvc_urb
->buffer
;
1739 urb
->complete
= uvc_video_complete
;
1740 urb
->number_of_packets
= npackets
;
1741 urb
->transfer_buffer_length
= size
;
1743 for (i
= 0; i
< npackets
; ++i
) {
1744 urb
->iso_frame_desc
[i
].offset
= i
* psize
;
1745 urb
->iso_frame_desc
[i
].length
= psize
;
1755 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1756 * given by the endpoint.
1758 static int uvc_init_video_bulk(struct uvc_streaming
*stream
,
1759 struct usb_host_endpoint
*ep
, gfp_t gfp_flags
)
1762 struct uvc_urb
*uvc_urb
;
1763 unsigned int npackets
, pipe
;
1767 psize
= usb_endpoint_maxp(&ep
->desc
);
1768 size
= stream
->ctrl
.dwMaxPayloadTransferSize
;
1769 stream
->bulk
.max_payload_size
= size
;
1771 npackets
= uvc_alloc_urb_buffers(stream
, size
, psize
, gfp_flags
);
1775 size
= npackets
* psize
;
1777 if (usb_endpoint_dir_in(&ep
->desc
))
1778 pipe
= usb_rcvbulkpipe(stream
->dev
->udev
,
1779 ep
->desc
.bEndpointAddress
);
1781 pipe
= usb_sndbulkpipe(stream
->dev
->udev
,
1782 ep
->desc
.bEndpointAddress
);
1784 if (stream
->type
== V4L2_BUF_TYPE_VIDEO_OUTPUT
)
1787 for_each_uvc_urb(uvc_urb
, stream
) {
1788 urb
= usb_alloc_urb(0, gfp_flags
);
1790 uvc_video_stop_transfer(stream
, 1);
1794 usb_fill_bulk_urb(urb
, stream
->dev
->udev
, pipe
, uvc_urb
->buffer
,
1795 size
, uvc_video_complete
, uvc_urb
);
1796 #ifndef CONFIG_DMA_NONCOHERENT
1797 urb
->transfer_flags
= URB_NO_TRANSFER_DMA_MAP
;
1798 urb
->transfer_dma
= uvc_urb
->dma
;
1808 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1810 static int uvc_video_start_transfer(struct uvc_streaming
*stream
,
1813 struct usb_interface
*intf
= stream
->intf
;
1814 struct usb_host_endpoint
*ep
;
1815 struct uvc_urb
*uvc_urb
;
1819 stream
->sequence
= -1;
1820 stream
->last_fid
= -1;
1821 stream
->bulk
.header_size
= 0;
1822 stream
->bulk
.skip_payload
= 0;
1823 stream
->bulk
.payload_size
= 0;
1825 uvc_video_stats_start(stream
);
1827 if (intf
->num_altsetting
> 1) {
1828 struct usb_host_endpoint
*best_ep
= NULL
;
1829 unsigned int best_psize
= UINT_MAX
;
1830 unsigned int bandwidth
;
1831 unsigned int altsetting
;
1832 int intfnum
= stream
->intfnum
;
1834 /* Isochronous endpoint, select the alternate setting. */
1835 bandwidth
= stream
->ctrl
.dwMaxPayloadTransferSize
;
1837 if (bandwidth
== 0) {
1838 uvc_trace(UVC_TRACE_VIDEO
, "Device requested null "
1839 "bandwidth, defaulting to lowest.\n");
1842 uvc_trace(UVC_TRACE_VIDEO
, "Device requested %u "
1843 "B/frame bandwidth.\n", bandwidth
);
1846 for (i
= 0; i
< intf
->num_altsetting
; ++i
) {
1847 struct usb_host_interface
*alts
;
1850 alts
= &intf
->altsetting
[i
];
1851 ep
= uvc_find_endpoint(alts
,
1852 stream
->header
.bEndpointAddress
);
1856 /* Check if the bandwidth is high enough. */
1857 psize
= uvc_endpoint_max_bpi(stream
->dev
->udev
, ep
);
1858 if (psize
>= bandwidth
&& psize
<= best_psize
) {
1859 altsetting
= alts
->desc
.bAlternateSetting
;
1865 if (best_ep
== NULL
) {
1866 uvc_trace(UVC_TRACE_VIDEO
, "No fast enough alt setting "
1867 "for requested bandwidth.\n");
1871 uvc_trace(UVC_TRACE_VIDEO
, "Selecting alternate setting %u "
1872 "(%u B/frame bandwidth).\n", altsetting
, best_psize
);
1874 ret
= usb_set_interface(stream
->dev
->udev
, intfnum
, altsetting
);
1878 ret
= uvc_init_video_isoc(stream
, best_ep
, gfp_flags
);
1880 /* Bulk endpoint, proceed to URB initialization. */
1881 ep
= uvc_find_endpoint(&intf
->altsetting
[0],
1882 stream
->header
.bEndpointAddress
);
1886 ret
= uvc_init_video_bulk(stream
, ep
, gfp_flags
);
1892 /* Submit the URBs. */
1893 for_each_uvc_urb(uvc_urb
, stream
) {
1894 ret
= usb_submit_urb(uvc_urb
->urb
, gfp_flags
);
1896 uvc_printk(KERN_ERR
, "Failed to submit URB %u (%d).\n",
1897 uvc_urb_index(uvc_urb
), ret
);
1898 uvc_video_stop_transfer(stream
, 1);
1903 /* The Logitech C920 temporarily forgets that it should not be adjusting
1904 * Exposure Absolute during init so restore controls to stored values.
1906 if (stream
->dev
->quirks
& UVC_QUIRK_RESTORE_CTRLS_ON_INIT
)
1907 uvc_ctrl_restore_values(stream
->dev
);
1912 /* --------------------------------------------------------------------------
1917 * Stop streaming without disabling the video queue.
1919 * To let userspace applications resume without trouble, we must not touch the
1920 * video buffers in any way. We mark the device as frozen to make sure the URB
1921 * completion handler won't try to cancel the queue when we kill the URBs.
1923 int uvc_video_suspend(struct uvc_streaming
*stream
)
1925 if (!uvc_queue_streaming(&stream
->queue
))
1929 uvc_video_stop_transfer(stream
, 0);
1930 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
1935 * Reconfigure the video interface and restart streaming if it was enabled
1938 * If an error occurs, disable the video queue. This will wake all pending
1939 * buffers, making sure userspace applications are notified of the problem
1940 * instead of waiting forever.
1942 int uvc_video_resume(struct uvc_streaming
*stream
, int reset
)
1946 /* If the bus has been reset on resume, set the alternate setting to 0.
1947 * This should be the default value, but some devices crash or otherwise
1948 * misbehave if they don't receive a SET_INTERFACE request before any
1949 * other video control request.
1952 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
1956 uvc_video_clock_reset(stream
);
1958 if (!uvc_queue_streaming(&stream
->queue
))
1961 ret
= uvc_commit_video(stream
, &stream
->ctrl
);
1965 return uvc_video_start_transfer(stream
, GFP_NOIO
);
1968 /* ------------------------------------------------------------------------
1973 * Initialize the UVC video device by switching to alternate setting 0 and
1974 * retrieve the default format.
1976 * Some cameras (namely the Fuji Finepix) set the format and frame
1977 * indexes to zero. The UVC standard doesn't clearly make this a spec
1978 * violation, so try to silently fix the values if possible.
1980 * This function is called before registering the device with V4L.
1982 int uvc_video_init(struct uvc_streaming
*stream
)
1984 struct uvc_streaming_control
*probe
= &stream
->ctrl
;
1985 struct uvc_format
*format
= NULL
;
1986 struct uvc_frame
*frame
= NULL
;
1987 struct uvc_urb
*uvc_urb
;
1991 if (stream
->nformats
== 0) {
1992 uvc_printk(KERN_INFO
, "No supported video formats found.\n");
1996 atomic_set(&stream
->active
, 0);
1998 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1999 * Cam (and possibly other devices) crash or otherwise misbehave if
2000 * they don't receive a SET_INTERFACE request before any other video
2003 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
2005 /* Set the streaming probe control with default streaming parameters
2006 * retrieved from the device. Webcams that don't support GET_DEF
2007 * requests on the probe control will just keep their current streaming
2010 if (uvc_get_video_ctrl(stream
, probe
, 1, UVC_GET_DEF
) == 0)
2011 uvc_set_video_ctrl(stream
, probe
, 1);
2013 /* Initialize the streaming parameters with the probe control current
2014 * value. This makes sure SET_CUR requests on the streaming commit
2015 * control will always use values retrieved from a successful GET_CUR
2016 * request on the probe control, as required by the UVC specification.
2018 ret
= uvc_get_video_ctrl(stream
, probe
, 1, UVC_GET_CUR
);
2022 /* Check if the default format descriptor exists. Use the first
2023 * available format otherwise.
2025 for (i
= stream
->nformats
; i
> 0; --i
) {
2026 format
= &stream
->format
[i
-1];
2027 if (format
->index
== probe
->bFormatIndex
)
2031 if (format
->nframes
== 0) {
2032 uvc_printk(KERN_INFO
, "No frame descriptor found for the "
2033 "default format.\n");
2037 /* Zero bFrameIndex might be correct. Stream-based formats (including
2038 * MPEG-2 TS and DV) do not support frames but have a dummy frame
2039 * descriptor with bFrameIndex set to zero. If the default frame
2040 * descriptor is not found, use the first available frame.
2042 for (i
= format
->nframes
; i
> 0; --i
) {
2043 frame
= &format
->frame
[i
-1];
2044 if (frame
->bFrameIndex
== probe
->bFrameIndex
)
2048 probe
->bFormatIndex
= format
->index
;
2049 probe
->bFrameIndex
= frame
->bFrameIndex
;
2051 stream
->def_format
= format
;
2052 stream
->cur_format
= format
;
2053 stream
->cur_frame
= frame
;
2055 /* Select the video decoding function */
2056 if (stream
->type
== V4L2_BUF_TYPE_VIDEO_CAPTURE
) {
2057 if (stream
->dev
->quirks
& UVC_QUIRK_BUILTIN_ISIGHT
)
2058 stream
->decode
= uvc_video_decode_isight
;
2059 else if (stream
->intf
->num_altsetting
> 1)
2060 stream
->decode
= uvc_video_decode_isoc
;
2062 stream
->decode
= uvc_video_decode_bulk
;
2064 if (stream
->intf
->num_altsetting
== 1)
2065 stream
->decode
= uvc_video_encode_bulk
;
2067 uvc_printk(KERN_INFO
, "Isochronous endpoints are not "
2068 "supported for video output devices.\n");
2073 /* Prepare asynchronous work items. */
2074 for_each_uvc_urb(uvc_urb
, stream
)
2075 INIT_WORK(&uvc_urb
->work
, uvc_video_copy_data_work
);
2080 int uvc_video_start_streaming(struct uvc_streaming
*stream
)
2084 ret
= uvc_video_clock_init(stream
);
2088 /* Commit the streaming parameters. */
2089 ret
= uvc_commit_video(stream
, &stream
->ctrl
);
2093 ret
= uvc_video_start_transfer(stream
, GFP_KERNEL
);
2100 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
2102 uvc_video_clock_cleanup(stream
);
2107 void uvc_video_stop_streaming(struct uvc_streaming
*stream
)
2109 uvc_video_stop_transfer(stream
, 1);
2111 if (stream
->intf
->num_altsetting
> 1) {
2112 usb_set_interface(stream
->dev
->udev
, stream
->intfnum
, 0);
2114 /* UVC doesn't specify how to inform a bulk-based device
2115 * when the video stream is stopped. Windows sends a
2116 * CLEAR_FEATURE(HALT) request to the video streaming
2117 * bulk endpoint, mimic the same behaviour.
2119 unsigned int epnum
= stream
->header
.bEndpointAddress
2120 & USB_ENDPOINT_NUMBER_MASK
;
2121 unsigned int dir
= stream
->header
.bEndpointAddress
2122 & USB_ENDPOINT_DIR_MASK
;
2125 pipe
= usb_sndbulkpipe(stream
->dev
->udev
, epnum
) | dir
;
2126 usb_clear_halt(stream
->dev
->udev
, pipe
);
2129 uvc_video_clock_cleanup(stream
);