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 */
116 * The firmware has not properly implemented
117 * the control or there has been a HW error.
120 case 8: /* Invalid value within range */
122 default: /* reserved or unknown */
129 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
130 struct uvc_streaming_control *ctrl)
132 static const struct usb_device_id elgato_cam_link_4k = {
133 USB_DEVICE(0x0fd9, 0x0066)
135 struct uvc_format *format = NULL;
136 struct uvc_frame *frame = NULL;
140 * The response of the Elgato Cam Link 4K is incorrect: The second byte
141 * contains bFormatIndex (instead of being the second byte of bmHint).
142 * The first byte is always zero. The third byte is always 1.
144 * The UVC 1.5 class specification defines the first five bits in the
145 * bmHint bitfield. The remaining bits are reserved and should be zero.
146 * Therefore a valid bmHint will be less than 32.
148 * Latest Elgato Cam Link 4K firmware as of 2021-03-23 needs this fix.
149 * MCU: 20.02.19, FPGA: 67
151 if (usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k) &&
152 ctrl->bmHint > 255) {
153 u8 corrected_format_index = ctrl->bmHint >> 8;
155 /* uvc_dbg(stream->dev, VIDEO,
156 "Correct USB video probe response from {bmHint: 0x%04x, bFormatIndex: %u} to {bmHint: 0x%04x, bFormatIndex: %u}\n",
157 ctrl->bmHint, ctrl->bFormatIndex,
158 1, corrected_format_index); */
160 ctrl->bFormatIndex = corrected_format_index;
163 for (i = 0; i < stream->nformats; ++i) {
164 if (stream->format[i].index == ctrl->bFormatIndex) {
165 format = &stream->format[i];
173 for (i = 0; i < format->nframes; ++i) {
174 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
175 frame = &format->frame[i];
183 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
184 (ctrl->dwMaxVideoFrameSize == 0 &&
185 stream->dev->uvc_version < 0x0110))
186 ctrl->dwMaxVideoFrameSize =
187 frame->dwMaxVideoFrameBufferSize;
189 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
190 * compute the bandwidth on 16 bits and erroneously sign-extend it to
191 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
192 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
194 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
195 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
197 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
198 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
199 stream->intf->num_altsetting > 1) {
203 interval = (ctrl->dwFrameInterval > 100000)
204 ? ctrl->dwFrameInterval
205 : frame->dwFrameInterval[0];
207 /* Compute a bandwidth estimation by multiplying the frame
208 * size by the number of video frames per second, divide the
209 * result by the number of USB frames (or micro-frames for
210 * high-speed devices) per second and add the UVC header size
211 * (assumed to be 12 bytes long).
213 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
214 bandwidth *= 10000000 / interval + 1;
216 if (stream->dev->udev->speed == USB_SPEED_HIGH)
220 /* The bandwidth estimate is too low for many cameras. Don't use
221 * maximum packet sizes lower than 1024 bytes to try and work
222 * around the problem. According to measurements done on two
223 * different camera models, the value is high enough to get most
224 * resolutions working while not preventing two simultaneous
225 * VGA streams at 15 fps.
227 bandwidth = max_t(u32, bandwidth, 1024);
229 ctrl->dwMaxPayloadTransferSize = bandwidth;
233 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
236 * Return the size of the video probe and commit controls, which depends
237 * on the protocol version.
239 if (stream->dev->uvc_version < 0x0110)
241 else if (stream->dev->uvc_version < 0x0150)
247 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
248 struct uvc_streaming_control *ctrl, int probe, u8 query)
250 u16 size = uvc_video_ctrl_size(stream);
254 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
255 query == UVC_GET_DEF)
258 data = kmalloc(size, GFP_KERNEL);
262 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
263 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
264 size, uvc_timeout_param);
266 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
267 /* Some cameras, mostly based on Bison Electronics chipsets,
268 * answer a GET_MIN or GET_MAX request with the wCompQuality
271 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
272 "compliance - GET_MIN/MAX(PROBE) incorrectly "
273 "supported. Enabling workaround.\n");
274 memset(ctrl, 0, sizeof(*ctrl));
275 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
278 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
279 /* Many cameras don't support the GET_DEF request on their
280 * video probe control. Warn once and return, the caller will
281 * fall back to GET_CUR.
283 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
284 "compliance - GET_DEF(PROBE) not supported. "
285 "Enabling workaround.\n");
288 } else if (ret != size) {
289 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
290 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
296 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
297 ctrl->bFormatIndex = data[2];
298 ctrl->bFrameIndex = data[3];
299 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
300 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
301 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
302 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
303 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
304 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
305 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
306 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
309 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
310 ctrl->bmFramingInfo = data[30];
311 ctrl->bPreferedVersion = data[31];
312 ctrl->bMinVersion = data[32];
313 ctrl->bMaxVersion = data[33];
315 ctrl->dwClockFrequency = stream->dev->clock_frequency;
316 ctrl->bmFramingInfo = 0;
317 ctrl->bPreferedVersion = 0;
318 ctrl->bMinVersion = 0;
319 ctrl->bMaxVersion = 0;
322 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
323 * dwMaxPayloadTransferSize fields. Try to get the value from the
324 * format and frame descriptors.
326 uvc_fixup_video_ctrl(stream, ctrl);
334 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
335 struct uvc_streaming_control *ctrl, int probe)
337 u16 size = uvc_video_ctrl_size(stream);
341 data = kzalloc(size, GFP_KERNEL);
345 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
346 data[2] = ctrl->bFormatIndex;
347 data[3] = ctrl->bFrameIndex;
348 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
349 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
350 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
351 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
352 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
353 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
354 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
355 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
358 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
359 data[30] = ctrl->bmFramingInfo;
360 data[31] = ctrl->bPreferedVersion;
361 data[32] = ctrl->bMinVersion;
362 data[33] = ctrl->bMaxVersion;
365 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
366 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
367 size, uvc_timeout_param);
369 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
370 "%d (exp. %u).\n", probe ? "probe" : "commit",
379 int uvc_probe_video(struct uvc_streaming *stream,
380 struct uvc_streaming_control *probe)
382 struct uvc_streaming_control probe_min, probe_max;
387 /* Perform probing. The device should adjust the requested values
388 * according to its capabilities. However, some devices, namely the
389 * first generation UVC Logitech webcams, don't implement the Video
390 * Probe control properly, and just return the needed bandwidth. For
391 * that reason, if the needed bandwidth exceeds the maximum available
392 * bandwidth, try to lower the quality.
394 ret = uvc_set_video_ctrl(stream, probe, 1);
398 /* Get the minimum and maximum values for compression settings. */
399 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
400 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
403 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
407 probe->wCompQuality = probe_max.wCompQuality;
410 for (i = 0; i < 2; ++i) {
411 ret = uvc_set_video_ctrl(stream, probe, 1);
414 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
418 if (stream->intf->num_altsetting == 1)
421 bandwidth = probe->dwMaxPayloadTransferSize;
422 if (bandwidth <= stream->maxpsize)
425 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
430 /* TODO: negotiate compression parameters */
431 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
432 probe->wPFrameRate = probe_min.wPFrameRate;
433 probe->wCompQuality = probe_max.wCompQuality;
434 probe->wCompWindowSize = probe_min.wCompWindowSize;
441 static int uvc_commit_video(struct uvc_streaming *stream,
442 struct uvc_streaming_control *probe)
444 return uvc_set_video_ctrl(stream, probe, 0);
447 /* -----------------------------------------------------------------------------
448 * Clocks and timestamps
451 static inline ktime_t uvc_video_get_time(void)
453 if (uvc_clock_param == CLOCK_MONOTONIC)
456 return ktime_get_real();
460 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
461 const u8 *data, int len)
463 struct uvc_clock_sample *sample;
464 unsigned int header_size;
465 bool has_pts = false;
466 bool has_scr = false;
472 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
473 case UVC_STREAM_PTS | UVC_STREAM_SCR:
491 /* Check for invalid headers. */
492 if (len < header_size)
495 /* Extract the timestamps:
497 * - store the frame PTS in the buffer structure
498 * - if the SCR field is present, retrieve the host SOF counter and
499 * kernel timestamps and store them with the SCR STC and SOF fields
502 if (has_pts && buf != NULL)
503 buf->pts = get_unaligned_le32(&data[2]);
508 /* To limit the amount of data, drop SCRs with an SOF identical to the
511 dev_sof = get_unaligned_le16(&data[header_size - 2]);
512 if (dev_sof == stream->clock.last_sof)
515 stream->clock.last_sof = dev_sof;
517 host_sof = usb_get_current_frame_number(stream->dev->udev);
518 time = uvc_video_get_time();
520 /* The UVC specification allows device implementations that can't obtain
521 * the USB frame number to keep their own frame counters as long as they
522 * match the size and frequency of the frame number associated with USB
523 * SOF tokens. The SOF values sent by such devices differ from the USB
524 * SOF tokens by a fixed offset that needs to be estimated and accounted
525 * for to make timestamp recovery as accurate as possible.
527 * The offset is estimated the first time a device SOF value is received
528 * as the difference between the host and device SOF values. As the two
529 * SOF values can differ slightly due to transmission delays, consider
530 * that the offset is null if the difference is not higher than 10 ms
531 * (negative differences can not happen and are thus considered as an
532 * offset). The video commit control wDelay field should be used to
533 * compute a dynamic threshold instead of using a fixed 10 ms value, but
534 * devices don't report reliable wDelay values.
536 * See uvc_video_clock_host_sof() for an explanation regarding why only
537 * the 8 LSBs of the delta are kept.
539 if (stream->clock.sof_offset == (u16)-1) {
540 u16 delta_sof = (host_sof - dev_sof) & 255;
542 stream->clock.sof_offset = delta_sof;
544 stream->clock.sof_offset = 0;
547 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
549 spin_lock_irqsave(&stream->clock.lock, flags);
551 sample = &stream->clock.samples[stream->clock.head];
552 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
553 sample->dev_sof = dev_sof;
554 sample->host_sof = host_sof;
555 sample->host_time = time;
557 /* Update the sliding window head and count. */
558 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
560 if (stream->clock.count < stream->clock.size)
561 stream->clock.count++;
563 spin_unlock_irqrestore(&stream->clock.lock, flags);
566 static void uvc_video_clock_reset(struct uvc_streaming *stream)
568 struct uvc_clock *clock = &stream->clock;
572 clock->last_sof = -1;
573 clock->sof_offset = -1;
576 static int uvc_video_clock_init(struct uvc_streaming *stream)
578 struct uvc_clock *clock = &stream->clock;
580 spin_lock_init(&clock->lock);
583 clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples),
585 if (clock->samples == NULL)
588 uvc_video_clock_reset(stream);
593 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
595 kfree(stream->clock.samples);
596 stream->clock.samples = NULL;
600 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
602 * Host SOF counters reported by usb_get_current_frame_number() usually don't
603 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
604 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
605 * controller and its configuration.
607 * We thus need to recover the SOF value corresponding to the host frame number.
608 * As the device and host frame numbers are sampled in a short interval, the
609 * difference between their values should be equal to a small delta plus an
610 * integer multiple of 256 caused by the host frame number limited precision.
612 * To obtain the recovered host SOF value, compute the small delta by masking
613 * the high bits of the host frame counter and device SOF difference and add it
614 * to the device SOF value.
616 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
618 /* The delta value can be negative. */
621 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
623 return (sample->dev_sof + delta_sof) & 2047;
627 * uvc_video_clock_update - Update the buffer timestamp
629 * This function converts the buffer PTS timestamp to the host clock domain by
630 * going through the USB SOF clock domain and stores the result in the V4L2
631 * buffer timestamp field.
633 * The relationship between the device clock and the host clock isn't known.
634 * However, the device and the host share the common USB SOF clock which can be
635 * used to recover that relationship.
637 * The relationship between the device clock and the USB SOF clock is considered
638 * to be linear over the clock samples sliding window and is given by
642 * Several methods to compute the slope (m) and intercept (p) can be used. As
643 * the clock drift should be small compared to the sliding window size, we
644 * assume that the line that goes through the points at both ends of the window
645 * is a good approximation. Naming those points P1 and P2, we get
647 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
648 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
652 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
654 * to avoid losing precision in the division. Similarly, the host timestamp is
657 * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
659 * SOF values are coded on 11 bits by USB. We extend their precision with 16
660 * decimal bits, leading to a 11.16 coding.
662 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
663 * be normalized using the nominal device clock frequency reported through the
666 * Both the PTS/STC and SOF counters roll over, after a fixed but device
667 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
668 * sliding window size is smaller than the rollover period, differences computed
669 * on unsigned integers will produce the correct result. However, the p term in
670 * the linear relations will be miscomputed.
672 * To fix the issue, we subtract a constant from the PTS and STC values to bring
673 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
674 * the 32 bit range without any rollover.
676 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
677 * computed by (1) will never be smaller than 0. This offset is then compensated
678 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
679 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
680 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
681 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
682 * SOF value at the end of the sliding window.
684 * Finally we subtract a constant from the host timestamps to bring the first
685 * timestamp of the sliding window to 1s.
687 void uvc_video_clock_update(struct uvc_streaming *stream,
688 struct vb2_v4l2_buffer *vbuf,
689 struct uvc_buffer *buf)
691 struct uvc_clock *clock = &stream->clock;
692 struct uvc_clock_sample *first;
693 struct uvc_clock_sample *last;
703 if (!uvc_hw_timestamps_param)
707 * We will get called from __vb2_queue_cancel() if there are buffers
708 * done but not dequeued by the user, but the sample array has already
709 * been released at that time. Just bail out in that case.
714 spin_lock_irqsave(&clock->lock, flags);
716 if (clock->count < clock->size)
719 first = &clock->samples[clock->head];
720 last = &clock->samples[(clock->head - 1) % clock->size];
722 /* First step, PTS to SOF conversion. */
723 delta_stc = buf->pts - (1UL << 31);
724 x1 = first->dev_stc - delta_stc;
725 x2 = last->dev_stc - delta_stc;
729 y1 = (first->dev_sof + 2048) << 16;
730 y2 = (last->dev_sof + 2048) << 16;
734 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
736 y = div_u64(y, x2 - x1);
740 uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
741 "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
742 stream->dev->name, buf->pts,
743 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
744 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
745 x1, x2, y1, y2, clock->sof_offset);
747 /* Second step, SOF to host clock conversion. */
748 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
749 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
756 y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
758 /* Interpolated and host SOF timestamps can wrap around at slightly
759 * different times. Handle this by adding or removing 2048 to or from
760 * the computed SOF value to keep it close to the SOF samples mean
763 mean = (x1 + x2) / 2;
764 if (mean - (1024 << 16) > sof)
766 else if (sof > mean + (1024 << 16))
769 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
771 y = div_u64(y, x2 - x1);
773 timestamp = ktime_to_ns(first->host_time) + y - y1;
775 uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
776 "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
778 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
779 y, timestamp, vbuf->vb2_buf.timestamp,
780 x1, first->host_sof, first->dev_sof,
781 x2, last->host_sof, last->dev_sof, y1, y2);
783 /* Update the V4L2 buffer. */
784 vbuf->vb2_buf.timestamp = timestamp;
787 spin_unlock_irqrestore(&clock->lock, flags);
790 /* ------------------------------------------------------------------------
794 static void uvc_video_stats_decode(struct uvc_streaming *stream,
795 const u8 *data, int len)
797 unsigned int header_size;
798 bool has_pts = false;
799 bool has_scr = false;
804 if (stream->stats.stream.nb_frames == 0 &&
805 stream->stats.frame.nb_packets == 0)
806 stream->stats.stream.start_ts = ktime_get();
808 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
809 case UVC_STREAM_PTS | UVC_STREAM_SCR:
827 /* Check for invalid headers. */
828 if (len < header_size || data[0] < header_size) {
829 stream->stats.frame.nb_invalid++;
833 /* Extract the timestamps. */
835 pts = get_unaligned_le32(&data[2]);
838 scr_stc = get_unaligned_le32(&data[header_size - 6]);
839 scr_sof = get_unaligned_le16(&data[header_size - 2]);
842 /* Is PTS constant through the whole frame ? */
843 if (has_pts && stream->stats.frame.nb_pts) {
844 if (stream->stats.frame.pts != pts) {
845 stream->stats.frame.nb_pts_diffs++;
846 stream->stats.frame.last_pts_diff =
847 stream->stats.frame.nb_packets;
852 stream->stats.frame.nb_pts++;
853 stream->stats.frame.pts = pts;
856 /* Do all frames have a PTS in their first non-empty packet, or before
857 * their first empty packet ?
859 if (stream->stats.frame.size == 0) {
860 if (len > header_size)
861 stream->stats.frame.has_initial_pts = has_pts;
862 if (len == header_size && has_pts)
863 stream->stats.frame.has_early_pts = true;
866 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
867 if (has_scr && stream->stats.frame.nb_scr) {
868 if (stream->stats.frame.scr_stc != scr_stc)
869 stream->stats.frame.nb_scr_diffs++;
873 /* Expand the SOF counter to 32 bits and store its value. */
874 if (stream->stats.stream.nb_frames > 0 ||
875 stream->stats.frame.nb_scr > 0)
876 stream->stats.stream.scr_sof_count +=
877 (scr_sof - stream->stats.stream.scr_sof) % 2048;
878 stream->stats.stream.scr_sof = scr_sof;
880 stream->stats.frame.nb_scr++;
881 stream->stats.frame.scr_stc = scr_stc;
882 stream->stats.frame.scr_sof = scr_sof;
884 if (scr_sof < stream->stats.stream.min_sof)
885 stream->stats.stream.min_sof = scr_sof;
886 if (scr_sof > stream->stats.stream.max_sof)
887 stream->stats.stream.max_sof = scr_sof;
890 /* Record the first non-empty packet number. */
891 if (stream->stats.frame.size == 0 && len > header_size)
892 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
894 /* Update the frame size. */
895 stream->stats.frame.size += len - header_size;
897 /* Update the packets counters. */
898 stream->stats.frame.nb_packets++;
899 if (len <= header_size)
900 stream->stats.frame.nb_empty++;
902 if (data[1] & UVC_STREAM_ERR)
903 stream->stats.frame.nb_errors++;
906 static void uvc_video_stats_update(struct uvc_streaming *stream)
908 struct uvc_stats_frame *frame = &stream->stats.frame;
910 uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
911 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
912 "last pts/stc/sof %u/%u/%u\n",
913 stream->sequence, frame->first_data,
914 frame->nb_packets - frame->nb_empty, frame->nb_packets,
915 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
916 frame->has_early_pts ? "" : "!",
917 frame->has_initial_pts ? "" : "!",
918 frame->nb_scr_diffs, frame->nb_scr,
919 frame->pts, frame->scr_stc, frame->scr_sof);
921 stream->stats.stream.nb_frames++;
922 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
923 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
924 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
925 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
927 if (frame->has_early_pts)
928 stream->stats.stream.nb_pts_early++;
929 if (frame->has_initial_pts)
930 stream->stats.stream.nb_pts_initial++;
931 if (frame->last_pts_diff <= frame->first_data)
932 stream->stats.stream.nb_pts_constant++;
933 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
934 stream->stats.stream.nb_scr_count_ok++;
935 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
936 stream->stats.stream.nb_scr_diffs_ok++;
938 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
941 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
944 unsigned int scr_sof_freq;
945 unsigned int duration;
948 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
949 * frequency this will not overflow before more than 1h.
951 duration = ktime_ms_delta(stream->stats.stream.stop_ts,
952 stream->stats.stream.start_ts);
954 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
959 count += scnprintf(buf + count, size - count,
960 "frames: %u\npackets: %u\nempty: %u\n"
961 "errors: %u\ninvalid: %u\n",
962 stream->stats.stream.nb_frames,
963 stream->stats.stream.nb_packets,
964 stream->stats.stream.nb_empty,
965 stream->stats.stream.nb_errors,
966 stream->stats.stream.nb_invalid);
967 count += scnprintf(buf + count, size - count,
968 "pts: %u early, %u initial, %u ok\n",
969 stream->stats.stream.nb_pts_early,
970 stream->stats.stream.nb_pts_initial,
971 stream->stats.stream.nb_pts_constant);
972 count += scnprintf(buf + count, size - count,
973 "scr: %u count ok, %u diff ok\n",
974 stream->stats.stream.nb_scr_count_ok,
975 stream->stats.stream.nb_scr_diffs_ok);
976 count += scnprintf(buf + count, size - count,
977 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
978 stream->stats.stream.min_sof,
979 stream->stats.stream.max_sof,
980 scr_sof_freq / 1000, scr_sof_freq % 1000);
985 static void uvc_video_stats_start(struct uvc_streaming *stream)
987 memset(&stream->stats, 0, sizeof(stream->stats));
988 stream->stats.stream.min_sof = 2048;
991 static void uvc_video_stats_stop(struct uvc_streaming *stream)
993 stream->stats.stream.stop_ts = ktime_get();
996 /* ------------------------------------------------------------------------
1000 /* Video payload decoding is handled by uvc_video_decode_start(),
1001 * uvc_video_decode_data() and uvc_video_decode_end().
1003 * uvc_video_decode_start is called with URB data at the start of a bulk or
1004 * isochronous payload. It processes header data and returns the header size
1005 * in bytes if successful. If an error occurs, it returns a negative error
1006 * code. The following error codes have special meanings.
1008 * - EAGAIN informs the caller that the current video buffer should be marked
1009 * as done, and that the function should be called again with the same data
1010 * and a new video buffer. This is used when end of frame conditions can be
1011 * reliably detected at the beginning of the next frame only.
1013 * If an error other than -EAGAIN is returned, the caller will drop the current
1014 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
1015 * made until the next payload. -ENODATA can be used to drop the current
1016 * payload if no other error code is appropriate.
1018 * uvc_video_decode_data is called for every URB with URB data. It copies the
1019 * data to the video buffer.
1021 * uvc_video_decode_end is called with header data at the end of a bulk or
1022 * isochronous payload. It performs any additional header data processing and
1023 * returns 0 or a negative error code if an error occurred. As header data have
1024 * already been processed by uvc_video_decode_start, this functions isn't
1025 * required to perform sanity checks a second time.
1027 * For isochronous transfers where a payload is always transferred in a single
1028 * URB, the three functions will be called in a row.
1030 * To let the decoder process header data and update its internal state even
1031 * when no video buffer is available, uvc_video_decode_start must be prepared
1032 * to be called with a NULL buf parameter. uvc_video_decode_data and
1033 * uvc_video_decode_end will never be called with a NULL buffer.
1035 static int uvc_video_decode_start(struct uvc_streaming *stream,
1036 struct uvc_buffer *buf, const u8 *data, int len)
1041 * - packet must be at least 2 bytes long
1042 * - bHeaderLength value must be at least 2 bytes (see above)
1043 * - bHeaderLength value can't be larger than the packet size.
1045 if (len < 2 || data[0] < 2 || data[0] > len) {
1046 stream->stats.frame.nb_invalid++;
1050 fid = data[1] & UVC_STREAM_FID;
1052 /* Increase the sequence number regardless of any buffer states, so
1053 * that discontinuous sequence numbers always indicate lost frames.
1055 if (stream->last_fid != fid) {
1057 if (stream->sequence)
1058 uvc_video_stats_update(stream);
1061 uvc_video_clock_decode(stream, buf, data, len);
1062 uvc_video_stats_decode(stream, data, len);
1064 /* Store the payload FID bit and return immediately when the buffer is
1068 stream->last_fid = fid;
1072 /* Mark the buffer as bad if the error bit is set. */
1073 if (data[1] & UVC_STREAM_ERR) {
1074 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1079 /* Synchronize to the input stream by waiting for the FID bit to be
1080 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1081 * stream->last_fid is initialized to -1, so the first isochronous
1082 * frame will always be in sync.
1084 * If the device doesn't toggle the FID bit, invert stream->last_fid
1085 * when the EOF bit is set to force synchronisation on the next packet.
1087 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1088 if (fid == stream->last_fid) {
1089 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1091 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1092 (data[1] & UVC_STREAM_EOF))
1093 stream->last_fid ^= UVC_STREAM_FID;
1097 buf->buf.field = V4L2_FIELD_NONE;
1098 buf->buf.sequence = stream->sequence;
1099 buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1101 /* TODO: Handle PTS and SCR. */
1102 buf->state = UVC_BUF_STATE_ACTIVE;
1105 /* Mark the buffer as done if we're at the beginning of a new frame.
1106 * End of frame detection is better implemented by checking the EOF
1107 * bit (FID bit toggling is delayed by one frame compared to the EOF
1108 * bit), but some devices don't set the bit at end of frame (and the
1109 * last payload can be lost anyway). We thus must check if the FID has
1112 * stream->last_fid is initialized to -1, so the first isochronous
1113 * frame will never trigger an end of frame detection.
1115 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1116 * as it doesn't make sense to return an empty buffer. This also
1117 * avoids detecting end of frame conditions at FID toggling if the
1118 * previous payload had the EOF bit set.
1120 if (fid != stream->last_fid && buf->bytesused != 0) {
1121 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1123 buf->state = UVC_BUF_STATE_READY;
1127 stream->last_fid = fid;
1133 * uvc_video_decode_data_work: Asynchronous memcpy processing
1135 * Copy URB data to video buffers in process context, releasing buffer
1136 * references and requeuing the URB when done.
1138 static void uvc_video_copy_data_work(struct work_struct *work)
1140 struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work);
1144 for (i = 0; i < uvc_urb->async_operations; i++) {
1145 struct uvc_copy_op *op = &uvc_urb->copy_operations[i];
1147 memcpy(op->dst, op->src, op->len);
1149 /* Release reference taken on this buffer. */
1150 uvc_queue_buffer_release(op->buf);
1153 ret = usb_submit_urb(uvc_urb->urb, GFP_KERNEL);
1155 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1159 static void uvc_video_decode_data(struct uvc_urb *uvc_urb,
1160 struct uvc_buffer *buf, const u8 *data, int len)
1162 unsigned int active_op = uvc_urb->async_operations;
1163 struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op];
1164 unsigned int maxlen;
1169 maxlen = buf->length - buf->bytesused;
1171 /* Take a buffer reference for async work. */
1172 kref_get(&buf->ref);
1176 op->dst = buf->mem + buf->bytesused;
1177 op->len = min_t(unsigned int, len, maxlen);
1179 buf->bytesused += op->len;
1181 /* Complete the current frame if the buffer size was exceeded. */
1183 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1185 buf->state = UVC_BUF_STATE_READY;
1188 uvc_urb->async_operations++;
1191 static void uvc_video_decode_end(struct uvc_streaming *stream,
1192 struct uvc_buffer *buf, const u8 *data, int len)
1194 /* Mark the buffer as done if the EOF marker is set. */
1195 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1196 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1198 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1199 buf->state = UVC_BUF_STATE_READY;
1200 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1201 stream->last_fid ^= UVC_STREAM_FID;
1205 /* Video payload encoding is handled by uvc_video_encode_header() and
1206 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1208 * uvc_video_encode_header is called at the start of a payload. It adds header
1209 * data to the transfer buffer and returns the header size. As the only known
1210 * UVC output device transfers a whole frame in a single payload, the EOF bit
1211 * is always set in the header.
1213 * uvc_video_encode_data is called for every URB and copies the data from the
1214 * video buffer to the transfer buffer.
1216 static int uvc_video_encode_header(struct uvc_streaming *stream,
1217 struct uvc_buffer *buf, u8 *data, int len)
1219 data[0] = 2; /* Header length */
1220 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1221 | (stream->last_fid & UVC_STREAM_FID);
1225 static int uvc_video_encode_data(struct uvc_streaming *stream,
1226 struct uvc_buffer *buf, u8 *data, int len)
1228 struct uvc_video_queue *queue = &stream->queue;
1229 unsigned int nbytes;
1232 /* Copy video data to the URB buffer. */
1233 mem = buf->mem + queue->buf_used;
1234 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1235 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1237 memcpy(data, mem, nbytes);
1239 queue->buf_used += nbytes;
1244 /* ------------------------------------------------------------------------
1249 * Additionally to the payload headers we also want to provide the user with USB
1250 * Frame Numbers and system time values. The resulting buffer is thus composed
1251 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
1252 * Number, and a copy of the payload header.
1254 * Ideally we want to capture all payload headers for each frame. However, their
1255 * number is unknown and unbound. We thus drop headers that contain no vendor
1256 * data and that either contain no SCR value or an SCR value identical to the
1259 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1260 struct uvc_buffer *meta_buf,
1261 const u8 *mem, unsigned int length)
1263 struct uvc_meta_buf *meta;
1265 bool has_pts, has_scr;
1266 unsigned long flags;
1271 if (!meta_buf || length == 2)
1274 if (meta_buf->length - meta_buf->bytesused <
1275 length + sizeof(meta->ns) + sizeof(meta->sof)) {
1276 meta_buf->error = 1;
1280 has_pts = mem[1] & UVC_STREAM_PTS;
1281 has_scr = mem[1] & UVC_STREAM_SCR;
1293 if (stream->meta.format == V4L2_META_FMT_UVC)
1296 if (length == len_std && (!has_scr ||
1297 !memcmp(scr, stream->clock.last_scr, 6)))
1300 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1301 local_irq_save(flags);
1302 time = uvc_video_get_time();
1303 sof = usb_get_current_frame_number(stream->dev->udev);
1304 local_irq_restore(flags);
1305 put_unaligned(ktime_to_ns(time), &meta->ns);
1306 put_unaligned(sof, &meta->sof);
1309 memcpy(stream->clock.last_scr, scr, 6);
1311 meta->length = mem[0];
1312 meta->flags = mem[1];
1313 memcpy(meta->buf, &mem[2], length - 2);
1314 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1316 uvc_trace(UVC_TRACE_FRAME,
1317 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1318 __func__, ktime_to_ns(time), meta->sof, meta->length,
1320 has_pts ? *(u32 *)meta->buf : 0,
1321 has_scr ? *(u32 *)scr : 0,
1322 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1325 /* ------------------------------------------------------------------------
1330 * Set error flag for incomplete buffer.
1332 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1333 struct uvc_buffer *buf)
1335 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1336 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1341 * Completion handler for video URBs.
1344 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1345 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1347 uvc_video_validate_buffer(stream, *video_buf);
1350 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1351 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1353 vb2_meta->sequence = vb2_video->sequence;
1354 vb2_meta->field = vb2_video->field;
1355 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1357 (*meta_buf)->state = UVC_BUF_STATE_READY;
1358 if (!(*meta_buf)->error)
1359 (*meta_buf)->error = (*video_buf)->error;
1360 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1363 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1366 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb,
1367 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1369 struct urb *urb = uvc_urb->urb;
1370 struct uvc_streaming *stream = uvc_urb->stream;
1374 for (i = 0; i < urb->number_of_packets; ++i) {
1375 if (urb->iso_frame_desc[i].status < 0) {
1376 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1377 "lost (%d).\n", urb->iso_frame_desc[i].status);
1378 /* Mark the buffer as faulty. */
1384 /* Decode the payload header. */
1385 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1387 ret = uvc_video_decode_start(stream, buf, mem,
1388 urb->iso_frame_desc[i].actual_length);
1390 uvc_video_next_buffers(stream, &buf, &meta_buf);
1391 } while (ret == -EAGAIN);
1396 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1398 /* Decode the payload data. */
1399 uvc_video_decode_data(uvc_urb, buf, mem + ret,
1400 urb->iso_frame_desc[i].actual_length - ret);
1402 /* Process the header again. */
1403 uvc_video_decode_end(stream, buf, mem,
1404 urb->iso_frame_desc[i].actual_length);
1406 if (buf->state == UVC_BUF_STATE_READY)
1407 uvc_video_next_buffers(stream, &buf, &meta_buf);
1411 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb,
1412 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1414 struct urb *urb = uvc_urb->urb;
1415 struct uvc_streaming *stream = uvc_urb->stream;
1420 * Ignore ZLPs if they're not part of a frame, otherwise process them
1421 * to trigger the end of payload detection.
1423 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1426 mem = urb->transfer_buffer;
1427 len = urb->actual_length;
1428 stream->bulk.payload_size += len;
1430 /* If the URB is the first of its payload, decode and save the
1433 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1435 ret = uvc_video_decode_start(stream, buf, mem, len);
1437 uvc_video_next_buffers(stream, &buf, &meta_buf);
1438 } while (ret == -EAGAIN);
1440 /* If an error occurred skip the rest of the payload. */
1441 if (ret < 0 || buf == NULL) {
1442 stream->bulk.skip_payload = 1;
1444 memcpy(stream->bulk.header, mem, ret);
1445 stream->bulk.header_size = ret;
1447 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1454 /* The buffer queue might have been cancelled while a bulk transfer
1455 * was in progress, so we can reach here with buf equal to NULL. Make
1456 * sure buf is never dereferenced if NULL.
1459 /* Prepare video data for processing. */
1460 if (!stream->bulk.skip_payload && buf != NULL)
1461 uvc_video_decode_data(uvc_urb, buf, mem, len);
1463 /* Detect the payload end by a URB smaller than the maximum size (or
1464 * a payload size equal to the maximum) and process the header again.
1466 if (urb->actual_length < urb->transfer_buffer_length ||
1467 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1468 if (!stream->bulk.skip_payload && buf != NULL) {
1469 uvc_video_decode_end(stream, buf, stream->bulk.header,
1470 stream->bulk.payload_size);
1471 if (buf->state == UVC_BUF_STATE_READY)
1472 uvc_video_next_buffers(stream, &buf, &meta_buf);
1475 stream->bulk.header_size = 0;
1476 stream->bulk.skip_payload = 0;
1477 stream->bulk.payload_size = 0;
1481 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb,
1482 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1484 struct urb *urb = uvc_urb->urb;
1485 struct uvc_streaming *stream = uvc_urb->stream;
1487 u8 *mem = urb->transfer_buffer;
1488 int len = stream->urb_size, ret;
1491 urb->transfer_buffer_length = 0;
1495 /* If the URB is the first of its payload, add the header. */
1496 if (stream->bulk.header_size == 0) {
1497 ret = uvc_video_encode_header(stream, buf, mem, len);
1498 stream->bulk.header_size = ret;
1499 stream->bulk.payload_size += ret;
1504 /* Process video data. */
1505 ret = uvc_video_encode_data(stream, buf, mem, len);
1507 stream->bulk.payload_size += ret;
1510 if (buf->bytesused == stream->queue.buf_used ||
1511 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1512 if (buf->bytesused == stream->queue.buf_used) {
1513 stream->queue.buf_used = 0;
1514 buf->state = UVC_BUF_STATE_READY;
1515 buf->buf.sequence = ++stream->sequence;
1516 uvc_queue_next_buffer(&stream->queue, buf);
1517 stream->last_fid ^= UVC_STREAM_FID;
1520 stream->bulk.header_size = 0;
1521 stream->bulk.payload_size = 0;
1524 urb->transfer_buffer_length = stream->urb_size - len;
1527 static void uvc_video_complete(struct urb *urb)
1529 struct uvc_urb *uvc_urb = urb->context;
1530 struct uvc_streaming *stream = uvc_urb->stream;
1531 struct uvc_video_queue *queue = &stream->queue;
1532 struct uvc_video_queue *qmeta = &stream->meta.queue;
1533 struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1534 struct uvc_buffer *buf = NULL;
1535 struct uvc_buffer *buf_meta = NULL;
1536 unsigned long flags;
1539 switch (urb->status) {
1544 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1545 "completion handler.\n", urb->status);
1547 case -ENOENT: /* usb_poison_urb() called. */
1551 case -ECONNRESET: /* usb_unlink_urb() called. */
1552 case -ESHUTDOWN: /* The endpoint is being disabled. */
1553 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1555 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1559 buf = uvc_queue_get_current_buffer(queue);
1562 spin_lock_irqsave(&qmeta->irqlock, flags);
1563 if (!list_empty(&qmeta->irqqueue))
1564 buf_meta = list_first_entry(&qmeta->irqqueue,
1565 struct uvc_buffer, queue);
1566 spin_unlock_irqrestore(&qmeta->irqlock, flags);
1569 /* Re-initialise the URB async work. */
1570 uvc_urb->async_operations = 0;
1573 * Process the URB headers, and optionally queue expensive memcpy tasks
1574 * to be deferred to a work queue.
1576 stream->decode(uvc_urb, buf, buf_meta);
1578 /* If no async work is needed, resubmit the URB immediately. */
1579 if (!uvc_urb->async_operations) {
1580 ret = usb_submit_urb(uvc_urb->urb, GFP_ATOMIC);
1582 uvc_printk(KERN_ERR,
1583 "Failed to resubmit video URB (%d).\n",
1588 queue_work(stream->async_wq, &uvc_urb->work);
1592 * Free transfer buffers.
1594 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1596 struct uvc_urb *uvc_urb;
1598 for_each_uvc_urb(uvc_urb, stream) {
1599 if (!uvc_urb->buffer)
1602 #ifndef CONFIG_DMA_NONCOHERENT
1603 usb_free_coherent(stream->dev->udev, stream->urb_size,
1604 uvc_urb->buffer, uvc_urb->dma);
1606 kfree(uvc_urb->buffer);
1608 uvc_urb->buffer = NULL;
1611 stream->urb_size = 0;
1615 * Allocate transfer buffers. This function can be called with buffers
1616 * already allocated when resuming from suspend, in which case it will
1617 * return without touching the buffers.
1619 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1620 * system is too low on memory try successively smaller numbers of packets
1621 * until allocation succeeds.
1623 * Return the number of allocated packets on success or 0 when out of memory.
1625 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1626 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1628 unsigned int npackets;
1631 /* Buffers are already allocated, bail out. */
1632 if (stream->urb_size)
1633 return stream->urb_size / psize;
1635 /* Compute the number of packets. Bulk endpoints might transfer UVC
1636 * payloads across multiple URBs.
1638 npackets = DIV_ROUND_UP(size, psize);
1639 if (npackets > UVC_MAX_PACKETS)
1640 npackets = UVC_MAX_PACKETS;
1642 /* Retry allocations until one succeed. */
1643 for (; npackets > 1; npackets /= 2) {
1644 for (i = 0; i < UVC_URBS; ++i) {
1645 struct uvc_urb *uvc_urb = &stream->uvc_urb[i];
1647 stream->urb_size = psize * npackets;
1648 #ifndef CONFIG_DMA_NONCOHERENT
1649 uvc_urb->buffer = usb_alloc_coherent(
1650 stream->dev->udev, stream->urb_size,
1651 gfp_flags | __GFP_NOWARN, &uvc_urb->dma);
1654 kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1656 if (!uvc_urb->buffer) {
1657 uvc_free_urb_buffers(stream);
1661 uvc_urb->stream = stream;
1664 if (i == UVC_URBS) {
1665 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1666 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1672 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1673 "per packet).\n", psize);
1678 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1680 static void uvc_video_stop_transfer(struct uvc_streaming *stream,
1683 struct uvc_urb *uvc_urb;
1685 uvc_video_stats_stop(stream);
1688 * We must poison the URBs rather than kill them to ensure that even
1689 * after the completion handler returns, any asynchronous workqueues
1690 * will be prevented from resubmitting the URBs.
1692 for_each_uvc_urb(uvc_urb, stream)
1693 usb_poison_urb(uvc_urb->urb);
1695 flush_workqueue(stream->async_wq);
1697 for_each_uvc_urb(uvc_urb, stream) {
1698 usb_free_urb(uvc_urb->urb);
1699 uvc_urb->urb = NULL;
1703 uvc_free_urb_buffers(stream);
1707 * Compute the maximum number of bytes per interval for an endpoint.
1709 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1710 struct usb_host_endpoint *ep)
1715 switch (dev->speed) {
1716 case USB_SPEED_SUPER:
1717 case USB_SPEED_SUPER_PLUS:
1718 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1719 case USB_SPEED_HIGH:
1720 psize = usb_endpoint_maxp(&ep->desc);
1721 mult = usb_endpoint_maxp_mult(&ep->desc);
1722 return psize * mult;
1723 case USB_SPEED_WIRELESS:
1724 psize = usb_endpoint_maxp(&ep->desc);
1727 psize = usb_endpoint_maxp(&ep->desc);
1733 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1734 * is given by the endpoint.
1736 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1737 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1740 struct uvc_urb *uvc_urb;
1741 unsigned int npackets, i;
1745 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1746 size = stream->ctrl.dwMaxVideoFrameSize;
1748 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1752 size = npackets * psize;
1754 for_each_uvc_urb(uvc_urb, stream) {
1755 urb = usb_alloc_urb(npackets, gfp_flags);
1757 uvc_video_stop_transfer(stream, 1);
1761 urb->dev = stream->dev->udev;
1762 urb->context = uvc_urb;
1763 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1764 ep->desc.bEndpointAddress);
1765 #ifndef CONFIG_DMA_NONCOHERENT
1766 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1767 urb->transfer_dma = uvc_urb->dma;
1769 urb->transfer_flags = URB_ISO_ASAP;
1771 urb->interval = ep->desc.bInterval;
1772 urb->transfer_buffer = uvc_urb->buffer;
1773 urb->complete = uvc_video_complete;
1774 urb->number_of_packets = npackets;
1775 urb->transfer_buffer_length = size;
1777 for (i = 0; i < npackets; ++i) {
1778 urb->iso_frame_desc[i].offset = i * psize;
1779 urb->iso_frame_desc[i].length = psize;
1789 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1790 * given by the endpoint.
1792 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1793 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1796 struct uvc_urb *uvc_urb;
1797 unsigned int npackets, pipe;
1801 psize = usb_endpoint_maxp(&ep->desc);
1802 size = stream->ctrl.dwMaxPayloadTransferSize;
1803 stream->bulk.max_payload_size = size;
1805 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1809 size = npackets * psize;
1811 if (usb_endpoint_dir_in(&ep->desc))
1812 pipe = usb_rcvbulkpipe(stream->dev->udev,
1813 ep->desc.bEndpointAddress);
1815 pipe = usb_sndbulkpipe(stream->dev->udev,
1816 ep->desc.bEndpointAddress);
1818 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1821 for_each_uvc_urb(uvc_urb, stream) {
1822 urb = usb_alloc_urb(0, gfp_flags);
1824 uvc_video_stop_transfer(stream, 1);
1828 usb_fill_bulk_urb(urb, stream->dev->udev, pipe, uvc_urb->buffer,
1829 size, uvc_video_complete, uvc_urb);
1830 #ifndef CONFIG_DMA_NONCOHERENT
1831 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1832 urb->transfer_dma = uvc_urb->dma;
1842 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1844 static int uvc_video_start_transfer(struct uvc_streaming *stream,
1847 struct usb_interface *intf = stream->intf;
1848 struct usb_host_endpoint *ep;
1849 struct uvc_urb *uvc_urb;
1853 stream->sequence = -1;
1854 stream->last_fid = -1;
1855 stream->bulk.header_size = 0;
1856 stream->bulk.skip_payload = 0;
1857 stream->bulk.payload_size = 0;
1859 uvc_video_stats_start(stream);
1861 if (intf->num_altsetting > 1) {
1862 struct usb_host_endpoint *best_ep = NULL;
1863 unsigned int best_psize = UINT_MAX;
1864 unsigned int bandwidth;
1865 unsigned int altsetting;
1866 int intfnum = stream->intfnum;
1868 /* Isochronous endpoint, select the alternate setting. */
1869 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1871 if (bandwidth == 0) {
1872 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1873 "bandwidth, defaulting to lowest.\n");
1876 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1877 "B/frame bandwidth.\n", bandwidth);
1880 for (i = 0; i < intf->num_altsetting; ++i) {
1881 struct usb_host_interface *alts;
1884 alts = &intf->altsetting[i];
1885 ep = uvc_find_endpoint(alts,
1886 stream->header.bEndpointAddress);
1890 /* Check if the bandwidth is high enough. */
1891 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1892 if (psize >= bandwidth && psize <= best_psize) {
1893 altsetting = alts->desc.bAlternateSetting;
1899 if (best_ep == NULL) {
1900 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1901 "for requested bandwidth.\n");
1905 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1906 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1909 * Some devices, namely the Logitech C910 and B910, are unable
1910 * to recover from a USB autosuspend, unless the alternate
1911 * setting of the streaming interface is toggled.
1913 if (stream->dev->quirks & UVC_QUIRK_WAKE_AUTOSUSPEND) {
1914 usb_set_interface(stream->dev->udev, intfnum,
1916 usb_set_interface(stream->dev->udev, intfnum, 0);
1919 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1923 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1925 /* Bulk endpoint, proceed to URB initialization. */
1926 ep = uvc_find_endpoint(&intf->altsetting[0],
1927 stream->header.bEndpointAddress);
1931 /* Reject broken descriptors. */
1932 if (usb_endpoint_maxp(&ep->desc) == 0)
1935 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1941 /* Submit the URBs. */
1942 for_each_uvc_urb(uvc_urb, stream) {
1943 ret = usb_submit_urb(uvc_urb->urb, gfp_flags);
1945 uvc_printk(KERN_ERR, "Failed to submit URB %u (%d).\n",
1946 uvc_urb_index(uvc_urb), ret);
1947 uvc_video_stop_transfer(stream, 1);
1952 /* The Logitech C920 temporarily forgets that it should not be adjusting
1953 * Exposure Absolute during init so restore controls to stored values.
1955 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1956 uvc_ctrl_restore_values(stream->dev);
1961 /* --------------------------------------------------------------------------
1966 * Stop streaming without disabling the video queue.
1968 * To let userspace applications resume without trouble, we must not touch the
1969 * video buffers in any way. We mark the device as frozen to make sure the URB
1970 * completion handler won't try to cancel the queue when we kill the URBs.
1972 int uvc_video_suspend(struct uvc_streaming *stream)
1974 if (!uvc_queue_streaming(&stream->queue))
1978 uvc_video_stop_transfer(stream, 0);
1979 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1984 * Reconfigure the video interface and restart streaming if it was enabled
1987 * If an error occurs, disable the video queue. This will wake all pending
1988 * buffers, making sure userspace applications are notified of the problem
1989 * instead of waiting forever.
1991 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1995 /* If the bus has been reset on resume, set the alternate setting to 0.
1996 * This should be the default value, but some devices crash or otherwise
1997 * misbehave if they don't receive a SET_INTERFACE request before any
1998 * other video control request.
2001 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2005 uvc_video_clock_reset(stream);
2007 if (!uvc_queue_streaming(&stream->queue))
2010 ret = uvc_commit_video(stream, &stream->ctrl);
2014 return uvc_video_start_transfer(stream, GFP_NOIO);
2017 /* ------------------------------------------------------------------------
2022 * Initialize the UVC video device by switching to alternate setting 0 and
2023 * retrieve the default format.
2025 * Some cameras (namely the Fuji Finepix) set the format and frame
2026 * indexes to zero. The UVC standard doesn't clearly make this a spec
2027 * violation, so try to silently fix the values if possible.
2029 * This function is called before registering the device with V4L.
2031 int uvc_video_init(struct uvc_streaming *stream)
2033 struct uvc_streaming_control *probe = &stream->ctrl;
2034 struct uvc_format *format = NULL;
2035 struct uvc_frame *frame = NULL;
2036 struct uvc_urb *uvc_urb;
2040 if (stream->nformats == 0) {
2041 uvc_printk(KERN_INFO, "No supported video formats found.\n");
2045 atomic_set(&stream->active, 0);
2047 /* Alternate setting 0 should be the default, yet the XBox Live Vision
2048 * Cam (and possibly other devices) crash or otherwise misbehave if
2049 * they don't receive a SET_INTERFACE request before any other video
2052 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2054 /* Set the streaming probe control with default streaming parameters
2055 * retrieved from the device. Webcams that don't support GET_DEF
2056 * requests on the probe control will just keep their current streaming
2059 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
2060 uvc_set_video_ctrl(stream, probe, 1);
2062 /* Initialize the streaming parameters with the probe control current
2063 * value. This makes sure SET_CUR requests on the streaming commit
2064 * control will always use values retrieved from a successful GET_CUR
2065 * request on the probe control, as required by the UVC specification.
2067 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
2071 /* Check if the default format descriptor exists. Use the first
2072 * available format otherwise.
2074 for (i = stream->nformats; i > 0; --i) {
2075 format = &stream->format[i-1];
2076 if (format->index == probe->bFormatIndex)
2080 if (format->nframes == 0) {
2081 uvc_printk(KERN_INFO, "No frame descriptor found for the "
2082 "default format.\n");
2086 /* Zero bFrameIndex might be correct. Stream-based formats (including
2087 * MPEG-2 TS and DV) do not support frames but have a dummy frame
2088 * descriptor with bFrameIndex set to zero. If the default frame
2089 * descriptor is not found, use the first available frame.
2091 for (i = format->nframes; i > 0; --i) {
2092 frame = &format->frame[i-1];
2093 if (frame->bFrameIndex == probe->bFrameIndex)
2097 probe->bFormatIndex = format->index;
2098 probe->bFrameIndex = frame->bFrameIndex;
2100 stream->def_format = format;
2101 stream->cur_format = format;
2102 stream->cur_frame = frame;
2104 /* Select the video decoding function */
2105 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2106 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
2107 stream->decode = uvc_video_decode_isight;
2108 else if (stream->intf->num_altsetting > 1)
2109 stream->decode = uvc_video_decode_isoc;
2111 stream->decode = uvc_video_decode_bulk;
2113 if (stream->intf->num_altsetting == 1)
2114 stream->decode = uvc_video_encode_bulk;
2116 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
2117 "supported for video output devices.\n");
2122 /* Prepare asynchronous work items. */
2123 for_each_uvc_urb(uvc_urb, stream)
2124 INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work);
2129 int uvc_video_start_streaming(struct uvc_streaming *stream)
2133 ret = uvc_video_clock_init(stream);
2137 /* Commit the streaming parameters. */
2138 ret = uvc_commit_video(stream, &stream->ctrl);
2142 ret = uvc_video_start_transfer(stream, GFP_KERNEL);
2149 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2151 uvc_video_clock_cleanup(stream);
2156 void uvc_video_stop_streaming(struct uvc_streaming *stream)
2158 uvc_video_stop_transfer(stream, 1);
2160 if (stream->intf->num_altsetting > 1) {
2161 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2163 /* UVC doesn't specify how to inform a bulk-based device
2164 * when the video stream is stopped. Windows sends a
2165 * CLEAR_FEATURE(HALT) request to the video streaming
2166 * bulk endpoint, mimic the same behaviour.
2168 unsigned int epnum = stream->header.bEndpointAddress
2169 & USB_ENDPOINT_NUMBER_MASK;
2170 unsigned int dir = stream->header.bEndpointAddress
2171 & USB_ENDPOINT_DIR_MASK;
2174 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
2175 usb_clear_halt(stream->dev->udev, pipe);
2178 uvc_video_clock_cleanup(stream);