2 * uvc_video.c -- USB Video Class driver - Video handling
4 * Copyright (C) 2005-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
14 #include <linux/kernel.h>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <linux/usb.h>
19 #include <linux/videodev2.h>
20 #include <linux/vmalloc.h>
21 #include <linux/wait.h>
22 #include <linux/atomic.h>
23 #include <asm/unaligned.h>
25 #include <media/v4l2-common.h>
29 /* ------------------------------------------------------------------------
33 static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
34 __u8 intfnum, __u8 cs, void *data, __u16 size,
37 __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
40 pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
41 : usb_sndctrlpipe(dev->udev, 0);
42 type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
44 return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45 unit << 8 | intfnum, data, size, timeout);
48 static const char *uvc_query_name(__u8 query)
72 int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
73 __u8 intfnum, __u8 cs, void *data, __u16 size)
77 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
78 UVC_CTRL_CONTROL_TIMEOUT);
80 uvc_printk(KERN_ERR, "Failed to query (%s) UVC control %u on "
81 "unit %u: %d (exp. %u).\n", uvc_query_name(query), cs,
89 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
90 struct uvc_streaming_control *ctrl)
92 static const struct usb_device_id elgato_cam_link_4k = {
93 USB_DEVICE(0x0fd9, 0x0066)
95 struct uvc_format *format = NULL;
96 struct uvc_frame *frame = NULL;
100 * The response of the Elgato Cam Link 4K is incorrect: The second byte
101 * contains bFormatIndex (instead of being the second byte of bmHint).
102 * The first byte is always zero. The third byte is always 1.
104 * The UVC 1.5 class specification defines the first five bits in the
105 * bmHint bitfield. The remaining bits are reserved and should be zero.
106 * Therefore a valid bmHint will be less than 32.
108 * Latest Elgato Cam Link 4K firmware as of 2021-03-23 needs this fix.
109 * MCU: 20.02.19, FPGA: 67
111 if (usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k) &&
112 ctrl->bmHint > 255) {
113 u8 corrected_format_index = ctrl->bmHint >> 8;
115 /* uvc_dbg(stream->dev, VIDEO,
116 "Correct USB video probe response from {bmHint: 0x%04x, bFormatIndex: %u} to {bmHint: 0x%04x, bFormatIndex: %u}\n",
117 ctrl->bmHint, ctrl->bFormatIndex,
118 1, corrected_format_index); */
120 ctrl->bFormatIndex = corrected_format_index;
123 for (i = 0; i < stream->nformats; ++i) {
124 if (stream->format[i].index == ctrl->bFormatIndex) {
125 format = &stream->format[i];
133 for (i = 0; i < format->nframes; ++i) {
134 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
135 frame = &format->frame[i];
143 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
144 (ctrl->dwMaxVideoFrameSize == 0 &&
145 stream->dev->uvc_version < 0x0110))
146 ctrl->dwMaxVideoFrameSize =
147 frame->dwMaxVideoFrameBufferSize;
149 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
150 * compute the bandwidth on 16 bits and erroneously sign-extend it to
151 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
152 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
154 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
155 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
157 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
158 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
159 stream->intf->num_altsetting > 1) {
163 interval = (ctrl->dwFrameInterval > 100000)
164 ? ctrl->dwFrameInterval
165 : frame->dwFrameInterval[0];
167 /* Compute a bandwidth estimation by multiplying the frame
168 * size by the number of video frames per second, divide the
169 * result by the number of USB frames (or micro-frames for
170 * high-speed devices) per second and add the UVC header size
171 * (assumed to be 12 bytes long).
173 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
174 bandwidth *= 10000000 / interval + 1;
176 if (stream->dev->udev->speed == USB_SPEED_HIGH)
180 /* The bandwidth estimate is too low for many cameras. Don't use
181 * maximum packet sizes lower than 1024 bytes to try and work
182 * around the problem. According to measurements done on two
183 * different camera models, the value is high enough to get most
184 * resolutions working while not preventing two simultaneous
185 * VGA streams at 15 fps.
187 bandwidth = max_t(u32, bandwidth, 1024);
189 ctrl->dwMaxPayloadTransferSize = bandwidth;
193 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
196 * Return the size of the video probe and commit controls, which depends
197 * on the protocol version.
199 if (stream->dev->uvc_version < 0x0110)
201 else if (stream->dev->uvc_version < 0x0150)
207 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
208 struct uvc_streaming_control *ctrl, int probe, __u8 query)
210 __u16 size = uvc_video_ctrl_size(stream);
214 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
215 query == UVC_GET_DEF)
218 data = kmalloc(size, GFP_KERNEL);
222 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
223 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
224 size, uvc_timeout_param);
226 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
227 /* Some cameras, mostly based on Bison Electronics chipsets,
228 * answer a GET_MIN or GET_MAX request with the wCompQuality
231 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
232 "compliance - GET_MIN/MAX(PROBE) incorrectly "
233 "supported. Enabling workaround.\n");
234 memset(ctrl, 0, sizeof *ctrl);
235 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
238 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
239 /* Many cameras don't support the GET_DEF request on their
240 * video probe control. Warn once and return, the caller will
241 * fall back to GET_CUR.
243 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
244 "compliance - GET_DEF(PROBE) not supported. "
245 "Enabling workaround.\n");
248 } else if (ret != size) {
249 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
250 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
256 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
257 ctrl->bFormatIndex = data[2];
258 ctrl->bFrameIndex = data[3];
259 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
260 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
261 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
262 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
263 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
264 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
265 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
266 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
269 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
270 ctrl->bmFramingInfo = data[30];
271 ctrl->bPreferedVersion = data[31];
272 ctrl->bMinVersion = data[32];
273 ctrl->bMaxVersion = data[33];
275 ctrl->dwClockFrequency = stream->dev->clock_frequency;
276 ctrl->bmFramingInfo = 0;
277 ctrl->bPreferedVersion = 0;
278 ctrl->bMinVersion = 0;
279 ctrl->bMaxVersion = 0;
282 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
283 * dwMaxPayloadTransferSize fields. Try to get the value from the
284 * format and frame descriptors.
286 uvc_fixup_video_ctrl(stream, ctrl);
294 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
295 struct uvc_streaming_control *ctrl, int probe)
297 __u16 size = uvc_video_ctrl_size(stream);
301 data = kzalloc(size, GFP_KERNEL);
305 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
306 data[2] = ctrl->bFormatIndex;
307 data[3] = ctrl->bFrameIndex;
308 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
309 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
310 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
311 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
312 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
313 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
314 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
315 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
318 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
319 data[30] = ctrl->bmFramingInfo;
320 data[31] = ctrl->bPreferedVersion;
321 data[32] = ctrl->bMinVersion;
322 data[33] = ctrl->bMaxVersion;
325 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
326 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
327 size, uvc_timeout_param);
329 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
330 "%d (exp. %u).\n", probe ? "probe" : "commit",
339 int uvc_probe_video(struct uvc_streaming *stream,
340 struct uvc_streaming_control *probe)
342 struct uvc_streaming_control probe_min, probe_max;
347 /* Perform probing. The device should adjust the requested values
348 * according to its capabilities. However, some devices, namely the
349 * first generation UVC Logitech webcams, don't implement the Video
350 * Probe control properly, and just return the needed bandwidth. For
351 * that reason, if the needed bandwidth exceeds the maximum available
352 * bandwidth, try to lower the quality.
354 ret = uvc_set_video_ctrl(stream, probe, 1);
358 /* Get the minimum and maximum values for compression settings. */
359 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
360 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
363 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
367 probe->wCompQuality = probe_max.wCompQuality;
370 for (i = 0; i < 2; ++i) {
371 ret = uvc_set_video_ctrl(stream, probe, 1);
374 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
378 if (stream->intf->num_altsetting == 1)
381 bandwidth = probe->dwMaxPayloadTransferSize;
382 if (bandwidth <= stream->maxpsize)
385 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
390 /* TODO: negotiate compression parameters */
391 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
392 probe->wPFrameRate = probe_min.wPFrameRate;
393 probe->wCompQuality = probe_max.wCompQuality;
394 probe->wCompWindowSize = probe_min.wCompWindowSize;
401 static int uvc_commit_video(struct uvc_streaming *stream,
402 struct uvc_streaming_control *probe)
404 return uvc_set_video_ctrl(stream, probe, 0);
407 /* -----------------------------------------------------------------------------
408 * Clocks and timestamps
411 static inline void uvc_video_get_ts(struct timespec *ts)
413 if (uvc_clock_param == CLOCK_MONOTONIC)
416 ktime_get_real_ts(ts);
420 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
421 const __u8 *data, int len)
423 struct uvc_clock_sample *sample;
424 unsigned int header_size;
425 bool has_pts = false;
426 bool has_scr = false;
432 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
433 case UVC_STREAM_PTS | UVC_STREAM_SCR:
451 /* Check for invalid headers. */
452 if (len < header_size)
455 /* Extract the timestamps:
457 * - store the frame PTS in the buffer structure
458 * - if the SCR field is present, retrieve the host SOF counter and
459 * kernel timestamps and store them with the SCR STC and SOF fields
462 if (has_pts && buf != NULL)
463 buf->pts = get_unaligned_le32(&data[2]);
468 /* To limit the amount of data, drop SCRs with an SOF identical to the
471 dev_sof = get_unaligned_le16(&data[header_size - 2]);
472 if (dev_sof == stream->clock.last_sof)
475 stream->clock.last_sof = dev_sof;
477 host_sof = usb_get_current_frame_number(stream->dev->udev);
478 uvc_video_get_ts(&ts);
480 /* The UVC specification allows device implementations that can't obtain
481 * the USB frame number to keep their own frame counters as long as they
482 * match the size and frequency of the frame number associated with USB
483 * SOF tokens. The SOF values sent by such devices differ from the USB
484 * SOF tokens by a fixed offset that needs to be estimated and accounted
485 * for to make timestamp recovery as accurate as possible.
487 * The offset is estimated the first time a device SOF value is received
488 * as the difference between the host and device SOF values. As the two
489 * SOF values can differ slightly due to transmission delays, consider
490 * that the offset is null if the difference is not higher than 10 ms
491 * (negative differences can not happen and are thus considered as an
492 * offset). The video commit control wDelay field should be used to
493 * compute a dynamic threshold instead of using a fixed 10 ms value, but
494 * devices don't report reliable wDelay values.
496 * See uvc_video_clock_host_sof() for an explanation regarding why only
497 * the 8 LSBs of the delta are kept.
499 if (stream->clock.sof_offset == (u16)-1) {
500 u16 delta_sof = (host_sof - dev_sof) & 255;
502 stream->clock.sof_offset = delta_sof;
504 stream->clock.sof_offset = 0;
507 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
509 spin_lock_irqsave(&stream->clock.lock, flags);
511 sample = &stream->clock.samples[stream->clock.head];
512 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
513 sample->dev_sof = dev_sof;
514 sample->host_sof = host_sof;
515 sample->host_ts = ts;
517 /* Update the sliding window head and count. */
518 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
520 if (stream->clock.count < stream->clock.size)
521 stream->clock.count++;
523 spin_unlock_irqrestore(&stream->clock.lock, flags);
526 static void uvc_video_clock_reset(struct uvc_streaming *stream)
528 struct uvc_clock *clock = &stream->clock;
532 clock->last_sof = -1;
533 clock->sof_offset = -1;
536 static int uvc_video_clock_init(struct uvc_streaming *stream)
538 struct uvc_clock *clock = &stream->clock;
540 spin_lock_init(&clock->lock);
543 clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
545 if (clock->samples == NULL)
548 uvc_video_clock_reset(stream);
553 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
555 kfree(stream->clock.samples);
556 stream->clock.samples = NULL;
560 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
562 * Host SOF counters reported by usb_get_current_frame_number() usually don't
563 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
564 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
565 * controller and its configuration.
567 * We thus need to recover the SOF value corresponding to the host frame number.
568 * As the device and host frame numbers are sampled in a short interval, the
569 * difference between their values should be equal to a small delta plus an
570 * integer multiple of 256 caused by the host frame number limited precision.
572 * To obtain the recovered host SOF value, compute the small delta by masking
573 * the high bits of the host frame counter and device SOF difference and add it
574 * to the device SOF value.
576 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
578 /* The delta value can be negative. */
581 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
583 return (sample->dev_sof + delta_sof) & 2047;
587 * uvc_video_clock_update - Update the buffer timestamp
589 * This function converts the buffer PTS timestamp to the host clock domain by
590 * going through the USB SOF clock domain and stores the result in the V4L2
591 * buffer timestamp field.
593 * The relationship between the device clock and the host clock isn't known.
594 * However, the device and the host share the common USB SOF clock which can be
595 * used to recover that relationship.
597 * The relationship between the device clock and the USB SOF clock is considered
598 * to be linear over the clock samples sliding window and is given by
602 * Several methods to compute the slope (m) and intercept (p) can be used. As
603 * the clock drift should be small compared to the sliding window size, we
604 * assume that the line that goes through the points at both ends of the window
605 * is a good approximation. Naming those points P1 and P2, we get
607 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
608 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
612 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
614 * to avoid losing precision in the division. Similarly, the host timestamp is
617 * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
619 * SOF values are coded on 11 bits by USB. We extend their precision with 16
620 * decimal bits, leading to a 11.16 coding.
622 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
623 * be normalized using the nominal device clock frequency reported through the
626 * Both the PTS/STC and SOF counters roll over, after a fixed but device
627 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
628 * sliding window size is smaller than the rollover period, differences computed
629 * on unsigned integers will produce the correct result. However, the p term in
630 * the linear relations will be miscomputed.
632 * To fix the issue, we subtract a constant from the PTS and STC values to bring
633 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
634 * the 32 bit range without any rollover.
636 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
637 * computed by (1) will never be smaller than 0. This offset is then compensated
638 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
639 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
640 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
641 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
642 * SOF value at the end of the sliding window.
644 * Finally we subtract a constant from the host timestamps to bring the first
645 * timestamp of the sliding window to 1s.
647 void uvc_video_clock_update(struct uvc_streaming *stream,
648 struct vb2_v4l2_buffer *vbuf,
649 struct uvc_buffer *buf)
651 struct uvc_clock *clock = &stream->clock;
652 struct uvc_clock_sample *first;
653 struct uvc_clock_sample *last;
665 if (!uvc_hw_timestamps_param)
669 * We will get called from __vb2_queue_cancel() if there are buffers
670 * done but not dequeued by the user, but the sample array has already
671 * been released at that time. Just bail out in that case.
676 spin_lock_irqsave(&clock->lock, flags);
678 if (clock->count < clock->size)
681 first = &clock->samples[clock->head];
682 last = &clock->samples[(clock->head - 1) % clock->size];
684 /* First step, PTS to SOF conversion. */
685 delta_stc = buf->pts - (1UL << 31);
686 x1 = first->dev_stc - delta_stc;
687 x2 = last->dev_stc - delta_stc;
691 y1 = (first->dev_sof + 2048) << 16;
692 y2 = (last->dev_sof + 2048) << 16;
696 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
698 y = div_u64(y, x2 - x1);
702 uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
703 "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
704 stream->dev->name, buf->pts,
705 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
706 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
707 x1, x2, y1, y2, clock->sof_offset);
709 /* Second step, SOF to host clock conversion. */
710 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
711 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
717 ts = timespec_sub(last->host_ts, first->host_ts);
719 y2 = (ts.tv_sec + 1) * NSEC_PER_SEC + ts.tv_nsec;
721 /* Interpolated and host SOF timestamps can wrap around at slightly
722 * different times. Handle this by adding or removing 2048 to or from
723 * the computed SOF value to keep it close to the SOF samples mean
726 mean = (x1 + x2) / 2;
727 if (mean - (1024 << 16) > sof)
729 else if (sof > mean + (1024 << 16))
732 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
734 y = div_u64(y, x2 - x1);
736 div = div_u64_rem(y, NSEC_PER_SEC, &rem);
737 ts.tv_sec = first->host_ts.tv_sec - 1 + div;
738 ts.tv_nsec = first->host_ts.tv_nsec + rem;
739 if (ts.tv_nsec >= NSEC_PER_SEC) {
741 ts.tv_nsec -= NSEC_PER_SEC;
744 uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
745 "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
747 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
748 y, timespec_to_ns(&ts), vbuf->vb2_buf.timestamp,
749 x1, first->host_sof, first->dev_sof,
750 x2, last->host_sof, last->dev_sof, y1, y2);
752 /* Update the V4L2 buffer. */
753 vbuf->vb2_buf.timestamp = timespec_to_ns(&ts);
756 spin_unlock_irqrestore(&clock->lock, flags);
759 /* ------------------------------------------------------------------------
763 static void uvc_video_stats_decode(struct uvc_streaming *stream,
764 const __u8 *data, int len)
766 unsigned int header_size;
767 bool has_pts = false;
768 bool has_scr = false;
769 u16 uninitialized_var(scr_sof);
770 u32 uninitialized_var(scr_stc);
771 u32 uninitialized_var(pts);
773 if (stream->stats.stream.nb_frames == 0 &&
774 stream->stats.frame.nb_packets == 0)
775 ktime_get_ts(&stream->stats.stream.start_ts);
777 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
778 case UVC_STREAM_PTS | UVC_STREAM_SCR:
796 /* Check for invalid headers. */
797 if (len < header_size || data[0] < header_size) {
798 stream->stats.frame.nb_invalid++;
802 /* Extract the timestamps. */
804 pts = get_unaligned_le32(&data[2]);
807 scr_stc = get_unaligned_le32(&data[header_size - 6]);
808 scr_sof = get_unaligned_le16(&data[header_size - 2]);
811 /* Is PTS constant through the whole frame ? */
812 if (has_pts && stream->stats.frame.nb_pts) {
813 if (stream->stats.frame.pts != pts) {
814 stream->stats.frame.nb_pts_diffs++;
815 stream->stats.frame.last_pts_diff =
816 stream->stats.frame.nb_packets;
821 stream->stats.frame.nb_pts++;
822 stream->stats.frame.pts = pts;
825 /* Do all frames have a PTS in their first non-empty packet, or before
826 * their first empty packet ?
828 if (stream->stats.frame.size == 0) {
829 if (len > header_size)
830 stream->stats.frame.has_initial_pts = has_pts;
831 if (len == header_size && has_pts)
832 stream->stats.frame.has_early_pts = true;
835 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
836 if (has_scr && stream->stats.frame.nb_scr) {
837 if (stream->stats.frame.scr_stc != scr_stc)
838 stream->stats.frame.nb_scr_diffs++;
842 /* Expand the SOF counter to 32 bits and store its value. */
843 if (stream->stats.stream.nb_frames > 0 ||
844 stream->stats.frame.nb_scr > 0)
845 stream->stats.stream.scr_sof_count +=
846 (scr_sof - stream->stats.stream.scr_sof) % 2048;
847 stream->stats.stream.scr_sof = scr_sof;
849 stream->stats.frame.nb_scr++;
850 stream->stats.frame.scr_stc = scr_stc;
851 stream->stats.frame.scr_sof = scr_sof;
853 if (scr_sof < stream->stats.stream.min_sof)
854 stream->stats.stream.min_sof = scr_sof;
855 if (scr_sof > stream->stats.stream.max_sof)
856 stream->stats.stream.max_sof = scr_sof;
859 /* Record the first non-empty packet number. */
860 if (stream->stats.frame.size == 0 && len > header_size)
861 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
863 /* Update the frame size. */
864 stream->stats.frame.size += len - header_size;
866 /* Update the packets counters. */
867 stream->stats.frame.nb_packets++;
868 if (len <= header_size)
869 stream->stats.frame.nb_empty++;
871 if (data[1] & UVC_STREAM_ERR)
872 stream->stats.frame.nb_errors++;
875 static void uvc_video_stats_update(struct uvc_streaming *stream)
877 struct uvc_stats_frame *frame = &stream->stats.frame;
879 uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
880 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
881 "last pts/stc/sof %u/%u/%u\n",
882 stream->sequence, frame->first_data,
883 frame->nb_packets - frame->nb_empty, frame->nb_packets,
884 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
885 frame->has_early_pts ? "" : "!",
886 frame->has_initial_pts ? "" : "!",
887 frame->nb_scr_diffs, frame->nb_scr,
888 frame->pts, frame->scr_stc, frame->scr_sof);
890 stream->stats.stream.nb_frames++;
891 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
892 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
893 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
894 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
896 if (frame->has_early_pts)
897 stream->stats.stream.nb_pts_early++;
898 if (frame->has_initial_pts)
899 stream->stats.stream.nb_pts_initial++;
900 if (frame->last_pts_diff <= frame->first_data)
901 stream->stats.stream.nb_pts_constant++;
902 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
903 stream->stats.stream.nb_scr_count_ok++;
904 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
905 stream->stats.stream.nb_scr_diffs_ok++;
907 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
910 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
913 unsigned int scr_sof_freq;
914 unsigned int duration;
918 ts = timespec_sub(stream->stats.stream.stop_ts,
919 stream->stats.stream.start_ts);
921 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
922 * frequency this will not overflow before more than 1h.
924 duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
926 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
931 count += scnprintf(buf + count, size - count,
932 "frames: %u\npackets: %u\nempty: %u\n"
933 "errors: %u\ninvalid: %u\n",
934 stream->stats.stream.nb_frames,
935 stream->stats.stream.nb_packets,
936 stream->stats.stream.nb_empty,
937 stream->stats.stream.nb_errors,
938 stream->stats.stream.nb_invalid);
939 count += scnprintf(buf + count, size - count,
940 "pts: %u early, %u initial, %u ok\n",
941 stream->stats.stream.nb_pts_early,
942 stream->stats.stream.nb_pts_initial,
943 stream->stats.stream.nb_pts_constant);
944 count += scnprintf(buf + count, size - count,
945 "scr: %u count ok, %u diff ok\n",
946 stream->stats.stream.nb_scr_count_ok,
947 stream->stats.stream.nb_scr_diffs_ok);
948 count += scnprintf(buf + count, size - count,
949 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
950 stream->stats.stream.min_sof,
951 stream->stats.stream.max_sof,
952 scr_sof_freq / 1000, scr_sof_freq % 1000);
957 static void uvc_video_stats_start(struct uvc_streaming *stream)
959 memset(&stream->stats, 0, sizeof(stream->stats));
960 stream->stats.stream.min_sof = 2048;
963 static void uvc_video_stats_stop(struct uvc_streaming *stream)
965 ktime_get_ts(&stream->stats.stream.stop_ts);
968 /* ------------------------------------------------------------------------
972 /* Video payload decoding is handled by uvc_video_decode_start(),
973 * uvc_video_decode_data() and uvc_video_decode_end().
975 * uvc_video_decode_start is called with URB data at the start of a bulk or
976 * isochronous payload. It processes header data and returns the header size
977 * in bytes if successful. If an error occurs, it returns a negative error
978 * code. The following error codes have special meanings.
980 * - EAGAIN informs the caller that the current video buffer should be marked
981 * as done, and that the function should be called again with the same data
982 * and a new video buffer. This is used when end of frame conditions can be
983 * reliably detected at the beginning of the next frame only.
985 * If an error other than -EAGAIN is returned, the caller will drop the current
986 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
987 * made until the next payload. -ENODATA can be used to drop the current
988 * payload if no other error code is appropriate.
990 * uvc_video_decode_data is called for every URB with URB data. It copies the
991 * data to the video buffer.
993 * uvc_video_decode_end is called with header data at the end of a bulk or
994 * isochronous payload. It performs any additional header data processing and
995 * returns 0 or a negative error code if an error occurred. As header data have
996 * already been processed by uvc_video_decode_start, this functions isn't
997 * required to perform sanity checks a second time.
999 * For isochronous transfers where a payload is always transferred in a single
1000 * URB, the three functions will be called in a row.
1002 * To let the decoder process header data and update its internal state even
1003 * when no video buffer is available, uvc_video_decode_start must be prepared
1004 * to be called with a NULL buf parameter. uvc_video_decode_data and
1005 * uvc_video_decode_end will never be called with a NULL buffer.
1007 static int uvc_video_decode_start(struct uvc_streaming *stream,
1008 struct uvc_buffer *buf, const __u8 *data, int len)
1013 * - packet must be at least 2 bytes long
1014 * - bHeaderLength value must be at least 2 bytes (see above)
1015 * - bHeaderLength value can't be larger than the packet size.
1017 if (len < 2 || data[0] < 2 || data[0] > len) {
1018 stream->stats.frame.nb_invalid++;
1022 fid = data[1] & UVC_STREAM_FID;
1024 /* Increase the sequence number regardless of any buffer states, so
1025 * that discontinuous sequence numbers always indicate lost frames.
1027 if (stream->last_fid != fid) {
1029 if (stream->sequence)
1030 uvc_video_stats_update(stream);
1033 uvc_video_clock_decode(stream, buf, data, len);
1034 uvc_video_stats_decode(stream, data, len);
1036 /* Store the payload FID bit and return immediately when the buffer is
1040 stream->last_fid = fid;
1044 /* Mark the buffer as bad if the error bit is set. */
1045 if (data[1] & UVC_STREAM_ERR) {
1046 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1051 /* Synchronize to the input stream by waiting for the FID bit to be
1052 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1053 * stream->last_fid is initialized to -1, so the first isochronous
1054 * frame will always be in sync.
1056 * If the device doesn't toggle the FID bit, invert stream->last_fid
1057 * when the EOF bit is set to force synchronisation on the next packet.
1059 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1062 if (fid == stream->last_fid) {
1063 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1065 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1066 (data[1] & UVC_STREAM_EOF))
1067 stream->last_fid ^= UVC_STREAM_FID;
1071 uvc_video_get_ts(&ts);
1073 buf->buf.field = V4L2_FIELD_NONE;
1074 buf->buf.sequence = stream->sequence;
1075 buf->buf.vb2_buf.timestamp = timespec_to_ns(&ts);
1077 /* TODO: Handle PTS and SCR. */
1078 buf->state = UVC_BUF_STATE_ACTIVE;
1081 /* Mark the buffer as done if we're at the beginning of a new frame.
1082 * End of frame detection is better implemented by checking the EOF
1083 * bit (FID bit toggling is delayed by one frame compared to the EOF
1084 * bit), but some devices don't set the bit at end of frame (and the
1085 * last payload can be lost anyway). We thus must check if the FID has
1088 * stream->last_fid is initialized to -1, so the first isochronous
1089 * frame will never trigger an end of frame detection.
1091 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1092 * as it doesn't make sense to return an empty buffer. This also
1093 * avoids detecting end of frame conditions at FID toggling if the
1094 * previous payload had the EOF bit set.
1096 if (fid != stream->last_fid && buf->bytesused != 0) {
1097 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1099 buf->state = UVC_BUF_STATE_READY;
1103 stream->last_fid = fid;
1108 static void uvc_video_decode_data(struct uvc_streaming *stream,
1109 struct uvc_buffer *buf, const __u8 *data, int len)
1111 unsigned int maxlen, nbytes;
1117 /* Copy the video data to the buffer. */
1118 maxlen = buf->length - buf->bytesused;
1119 mem = buf->mem + buf->bytesused;
1120 nbytes = min((unsigned int)len, maxlen);
1121 memcpy(mem, data, nbytes);
1122 buf->bytesused += nbytes;
1124 /* Complete the current frame if the buffer size was exceeded. */
1126 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1127 buf->state = UVC_BUF_STATE_READY;
1131 static void uvc_video_decode_end(struct uvc_streaming *stream,
1132 struct uvc_buffer *buf, const __u8 *data, int len)
1134 /* Mark the buffer as done if the EOF marker is set. */
1135 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1136 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1138 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1139 buf->state = UVC_BUF_STATE_READY;
1140 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1141 stream->last_fid ^= UVC_STREAM_FID;
1145 /* Video payload encoding is handled by uvc_video_encode_header() and
1146 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1148 * uvc_video_encode_header is called at the start of a payload. It adds header
1149 * data to the transfer buffer and returns the header size. As the only known
1150 * UVC output device transfers a whole frame in a single payload, the EOF bit
1151 * is always set in the header.
1153 * uvc_video_encode_data is called for every URB and copies the data from the
1154 * video buffer to the transfer buffer.
1156 static int uvc_video_encode_header(struct uvc_streaming *stream,
1157 struct uvc_buffer *buf, __u8 *data, int len)
1159 data[0] = 2; /* Header length */
1160 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1161 | (stream->last_fid & UVC_STREAM_FID);
1165 static int uvc_video_encode_data(struct uvc_streaming *stream,
1166 struct uvc_buffer *buf, __u8 *data, int len)
1168 struct uvc_video_queue *queue = &stream->queue;
1169 unsigned int nbytes;
1172 /* Copy video data to the URB buffer. */
1173 mem = buf->mem + queue->buf_used;
1174 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1175 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1177 memcpy(data, mem, nbytes);
1179 queue->buf_used += nbytes;
1184 /* ------------------------------------------------------------------------
1189 * Set error flag for incomplete buffer.
1191 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1192 struct uvc_buffer *buf)
1194 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1195 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1200 * Completion handler for video URBs.
1202 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1203 struct uvc_buffer *buf)
1208 for (i = 0; i < urb->number_of_packets; ++i) {
1209 if (urb->iso_frame_desc[i].status < 0) {
1210 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1211 "lost (%d).\n", urb->iso_frame_desc[i].status);
1212 /* Mark the buffer as faulty. */
1218 /* Decode the payload header. */
1219 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1221 ret = uvc_video_decode_start(stream, buf, mem,
1222 urb->iso_frame_desc[i].actual_length);
1223 if (ret == -EAGAIN) {
1224 uvc_video_validate_buffer(stream, buf);
1225 buf = uvc_queue_next_buffer(&stream->queue,
1228 } while (ret == -EAGAIN);
1233 /* Decode the payload data. */
1234 uvc_video_decode_data(stream, buf, mem + ret,
1235 urb->iso_frame_desc[i].actual_length - ret);
1237 /* Process the header again. */
1238 uvc_video_decode_end(stream, buf, mem,
1239 urb->iso_frame_desc[i].actual_length);
1241 if (buf->state == UVC_BUF_STATE_READY) {
1242 uvc_video_validate_buffer(stream, buf);
1243 buf = uvc_queue_next_buffer(&stream->queue, buf);
1248 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1249 struct uvc_buffer *buf)
1255 * Ignore ZLPs if they're not part of a frame, otherwise process them
1256 * to trigger the end of payload detection.
1258 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1261 mem = urb->transfer_buffer;
1262 len = urb->actual_length;
1263 stream->bulk.payload_size += len;
1265 /* If the URB is the first of its payload, decode and save the
1268 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1270 ret = uvc_video_decode_start(stream, buf, mem, len);
1272 buf = uvc_queue_next_buffer(&stream->queue,
1274 } while (ret == -EAGAIN);
1276 /* If an error occurred skip the rest of the payload. */
1277 if (ret < 0 || buf == NULL) {
1278 stream->bulk.skip_payload = 1;
1280 memcpy(stream->bulk.header, mem, ret);
1281 stream->bulk.header_size = ret;
1288 /* The buffer queue might have been cancelled while a bulk transfer
1289 * was in progress, so we can reach here with buf equal to NULL. Make
1290 * sure buf is never dereferenced if NULL.
1293 /* Process video data. */
1294 if (!stream->bulk.skip_payload && buf != NULL)
1295 uvc_video_decode_data(stream, buf, mem, len);
1297 /* Detect the payload end by a URB smaller than the maximum size (or
1298 * a payload size equal to the maximum) and process the header again.
1300 if (urb->actual_length < urb->transfer_buffer_length ||
1301 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1302 if (!stream->bulk.skip_payload && buf != NULL) {
1303 uvc_video_decode_end(stream, buf, stream->bulk.header,
1304 stream->bulk.payload_size);
1305 if (buf->state == UVC_BUF_STATE_READY)
1306 uvc_queue_next_buffer(&stream->queue, buf);
1309 stream->bulk.header_size = 0;
1310 stream->bulk.skip_payload = 0;
1311 stream->bulk.payload_size = 0;
1315 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1316 struct uvc_buffer *buf)
1318 u8 *mem = urb->transfer_buffer;
1319 int len = stream->urb_size, ret;
1322 urb->transfer_buffer_length = 0;
1326 /* If the URB is the first of its payload, add the header. */
1327 if (stream->bulk.header_size == 0) {
1328 ret = uvc_video_encode_header(stream, buf, mem, len);
1329 stream->bulk.header_size = ret;
1330 stream->bulk.payload_size += ret;
1335 /* Process video data. */
1336 ret = uvc_video_encode_data(stream, buf, mem, len);
1338 stream->bulk.payload_size += ret;
1341 if (buf->bytesused == stream->queue.buf_used ||
1342 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1343 if (buf->bytesused == stream->queue.buf_used) {
1344 stream->queue.buf_used = 0;
1345 buf->state = UVC_BUF_STATE_READY;
1346 buf->buf.sequence = ++stream->sequence;
1347 uvc_queue_next_buffer(&stream->queue, buf);
1348 stream->last_fid ^= UVC_STREAM_FID;
1351 stream->bulk.header_size = 0;
1352 stream->bulk.payload_size = 0;
1355 urb->transfer_buffer_length = stream->urb_size - len;
1358 static void uvc_video_complete(struct urb *urb)
1360 struct uvc_streaming *stream = urb->context;
1361 struct uvc_video_queue *queue = &stream->queue;
1362 struct uvc_buffer *buf = NULL;
1363 unsigned long flags;
1366 switch (urb->status) {
1371 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1372 "completion handler.\n", urb->status);
1374 case -ENOENT: /* usb_kill_urb() called. */
1378 case -ECONNRESET: /* usb_unlink_urb() called. */
1379 case -ESHUTDOWN: /* The endpoint is being disabled. */
1380 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1384 spin_lock_irqsave(&queue->irqlock, flags);
1385 if (!list_empty(&queue->irqqueue))
1386 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1388 spin_unlock_irqrestore(&queue->irqlock, flags);
1390 stream->decode(urb, stream, buf);
1392 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1393 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1399 * Free transfer buffers.
1401 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1405 for (i = 0; i < UVC_URBS; ++i) {
1406 if (stream->urb_buffer[i]) {
1407 #ifndef CONFIG_DMA_NONCOHERENT
1408 usb_free_coherent(stream->dev->udev, stream->urb_size,
1409 stream->urb_buffer[i], stream->urb_dma[i]);
1411 kfree(stream->urb_buffer[i]);
1413 stream->urb_buffer[i] = NULL;
1417 stream->urb_size = 0;
1421 * Allocate transfer buffers. This function can be called with buffers
1422 * already allocated when resuming from suspend, in which case it will
1423 * return without touching the buffers.
1425 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1426 * system is too low on memory try successively smaller numbers of packets
1427 * until allocation succeeds.
1429 * Return the number of allocated packets on success or 0 when out of memory.
1431 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1432 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1434 unsigned int npackets;
1437 /* Buffers are already allocated, bail out. */
1438 if (stream->urb_size)
1439 return stream->urb_size / psize;
1441 /* Compute the number of packets. Bulk endpoints might transfer UVC
1442 * payloads across multiple URBs.
1444 npackets = DIV_ROUND_UP(size, psize);
1445 if (npackets > UVC_MAX_PACKETS)
1446 npackets = UVC_MAX_PACKETS;
1448 /* Retry allocations until one succeed. */
1449 for (; npackets > 1; npackets /= 2) {
1450 for (i = 0; i < UVC_URBS; ++i) {
1451 stream->urb_size = psize * npackets;
1452 #ifndef CONFIG_DMA_NONCOHERENT
1453 stream->urb_buffer[i] = usb_alloc_coherent(
1454 stream->dev->udev, stream->urb_size,
1455 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1457 stream->urb_buffer[i] =
1458 kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1460 if (!stream->urb_buffer[i]) {
1461 uvc_free_urb_buffers(stream);
1466 if (i == UVC_URBS) {
1467 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1468 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1474 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1475 "per packet).\n", psize);
1480 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1482 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1487 uvc_video_stats_stop(stream);
1489 for (i = 0; i < UVC_URBS; ++i) {
1490 urb = stream->urb[i];
1496 stream->urb[i] = NULL;
1500 uvc_free_urb_buffers(stream);
1504 * Compute the maximum number of bytes per interval for an endpoint.
1506 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1507 struct usb_host_endpoint *ep)
1512 switch (dev->speed) {
1513 case USB_SPEED_SUPER:
1514 case USB_SPEED_SUPER_PLUS:
1515 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1516 case USB_SPEED_HIGH:
1517 psize = usb_endpoint_maxp(&ep->desc);
1518 mult = usb_endpoint_maxp_mult(&ep->desc);
1519 return (psize & 0x07ff) * mult;
1520 case USB_SPEED_WIRELESS:
1521 psize = usb_endpoint_maxp(&ep->desc);
1524 psize = usb_endpoint_maxp(&ep->desc);
1525 return psize & 0x07ff;
1530 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1531 * is given by the endpoint.
1533 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1534 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1537 unsigned int npackets, i, j;
1541 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1542 size = stream->ctrl.dwMaxVideoFrameSize;
1544 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1548 size = npackets * psize;
1550 for (i = 0; i < UVC_URBS; ++i) {
1551 urb = usb_alloc_urb(npackets, gfp_flags);
1553 uvc_uninit_video(stream, 1);
1557 urb->dev = stream->dev->udev;
1558 urb->context = stream;
1559 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1560 ep->desc.bEndpointAddress);
1561 #ifndef CONFIG_DMA_NONCOHERENT
1562 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1563 urb->transfer_dma = stream->urb_dma[i];
1565 urb->transfer_flags = URB_ISO_ASAP;
1567 urb->interval = ep->desc.bInterval;
1568 urb->transfer_buffer = stream->urb_buffer[i];
1569 urb->complete = uvc_video_complete;
1570 urb->number_of_packets = npackets;
1571 urb->transfer_buffer_length = size;
1573 for (j = 0; j < npackets; ++j) {
1574 urb->iso_frame_desc[j].offset = j * psize;
1575 urb->iso_frame_desc[j].length = psize;
1578 stream->urb[i] = urb;
1585 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1586 * given by the endpoint.
1588 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1589 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1592 unsigned int npackets, pipe, i;
1596 psize = usb_endpoint_maxp(&ep->desc);
1597 size = stream->ctrl.dwMaxPayloadTransferSize;
1598 stream->bulk.max_payload_size = size;
1600 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1604 size = npackets * psize;
1606 if (usb_endpoint_dir_in(&ep->desc))
1607 pipe = usb_rcvbulkpipe(stream->dev->udev,
1608 ep->desc.bEndpointAddress);
1610 pipe = usb_sndbulkpipe(stream->dev->udev,
1611 ep->desc.bEndpointAddress);
1613 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1616 for (i = 0; i < UVC_URBS; ++i) {
1617 urb = usb_alloc_urb(0, gfp_flags);
1619 uvc_uninit_video(stream, 1);
1623 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1624 stream->urb_buffer[i], size, uvc_video_complete,
1626 #ifndef CONFIG_DMA_NONCOHERENT
1627 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1628 urb->transfer_dma = stream->urb_dma[i];
1631 stream->urb[i] = urb;
1638 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1640 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1642 struct usb_interface *intf = stream->intf;
1643 struct usb_host_endpoint *ep;
1647 stream->sequence = -1;
1648 stream->last_fid = -1;
1649 stream->bulk.header_size = 0;
1650 stream->bulk.skip_payload = 0;
1651 stream->bulk.payload_size = 0;
1653 uvc_video_stats_start(stream);
1655 if (intf->num_altsetting > 1) {
1656 struct usb_host_endpoint *best_ep = NULL;
1657 unsigned int best_psize = UINT_MAX;
1658 unsigned int bandwidth;
1659 unsigned int uninitialized_var(altsetting);
1660 int intfnum = stream->intfnum;
1662 /* Isochronous endpoint, select the alternate setting. */
1663 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1665 if (bandwidth == 0) {
1666 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1667 "bandwidth, defaulting to lowest.\n");
1670 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1671 "B/frame bandwidth.\n", bandwidth);
1674 for (i = 0; i < intf->num_altsetting; ++i) {
1675 struct usb_host_interface *alts;
1678 alts = &intf->altsetting[i];
1679 ep = uvc_find_endpoint(alts,
1680 stream->header.bEndpointAddress);
1684 /* Check if the bandwidth is high enough. */
1685 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1686 if (psize >= bandwidth && psize <= best_psize) {
1687 altsetting = alts->desc.bAlternateSetting;
1693 if (best_ep == NULL) {
1694 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1695 "for requested bandwidth.\n");
1699 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1700 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1702 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1706 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1708 /* Bulk endpoint, proceed to URB initialization. */
1709 ep = uvc_find_endpoint(&intf->altsetting[0],
1710 stream->header.bEndpointAddress);
1714 /* Reject broken descriptors. */
1715 if (usb_endpoint_maxp(&ep->desc) == 0)
1718 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1724 /* Submit the URBs. */
1725 for (i = 0; i < UVC_URBS; ++i) {
1726 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1728 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1730 uvc_uninit_video(stream, 1);
1735 /* The Logitech C920 temporarily forgets that it should not be adjusting
1736 * Exposure Absolute during init so restore controls to stored values.
1738 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1739 uvc_ctrl_restore_values(stream->dev);
1744 /* --------------------------------------------------------------------------
1749 * Stop streaming without disabling the video queue.
1751 * To let userspace applications resume without trouble, we must not touch the
1752 * video buffers in any way. We mark the device as frozen to make sure the URB
1753 * completion handler won't try to cancel the queue when we kill the URBs.
1755 int uvc_video_suspend(struct uvc_streaming *stream)
1757 if (!uvc_queue_streaming(&stream->queue))
1761 uvc_uninit_video(stream, 0);
1762 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1767 * Reconfigure the video interface and restart streaming if it was enabled
1770 * If an error occurs, disable the video queue. This will wake all pending
1771 * buffers, making sure userspace applications are notified of the problem
1772 * instead of waiting forever.
1774 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1778 /* If the bus has been reset on resume, set the alternate setting to 0.
1779 * This should be the default value, but some devices crash or otherwise
1780 * misbehave if they don't receive a SET_INTERFACE request before any
1781 * other video control request.
1784 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1788 uvc_video_clock_reset(stream);
1790 if (!uvc_queue_streaming(&stream->queue))
1793 ret = uvc_commit_video(stream, &stream->ctrl);
1797 return uvc_init_video(stream, GFP_NOIO);
1800 /* ------------------------------------------------------------------------
1805 * Initialize the UVC video device by switching to alternate setting 0 and
1806 * retrieve the default format.
1808 * Some cameras (namely the Fuji Finepix) set the format and frame
1809 * indexes to zero. The UVC standard doesn't clearly make this a spec
1810 * violation, so try to silently fix the values if possible.
1812 * This function is called before registering the device with V4L.
1814 int uvc_video_init(struct uvc_streaming *stream)
1816 struct uvc_streaming_control *probe = &stream->ctrl;
1817 struct uvc_format *format = NULL;
1818 struct uvc_frame *frame = NULL;
1822 if (stream->nformats == 0) {
1823 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1827 atomic_set(&stream->active, 0);
1829 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1830 * Cam (and possibly other devices) crash or otherwise misbehave if
1831 * they don't receive a SET_INTERFACE request before any other video
1834 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1836 /* Set the streaming probe control with default streaming parameters
1837 * retrieved from the device. Webcams that don't suport GET_DEF
1838 * requests on the probe control will just keep their current streaming
1841 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1842 uvc_set_video_ctrl(stream, probe, 1);
1844 /* Initialize the streaming parameters with the probe control current
1845 * value. This makes sure SET_CUR requests on the streaming commit
1846 * control will always use values retrieved from a successful GET_CUR
1847 * request on the probe control, as required by the UVC specification.
1849 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1853 /* Check if the default format descriptor exists. Use the first
1854 * available format otherwise.
1856 for (i = stream->nformats; i > 0; --i) {
1857 format = &stream->format[i-1];
1858 if (format->index == probe->bFormatIndex)
1862 if (format->nframes == 0) {
1863 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1864 "default format.\n");
1868 /* Zero bFrameIndex might be correct. Stream-based formats (including
1869 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1870 * descriptor with bFrameIndex set to zero. If the default frame
1871 * descriptor is not found, use the first available frame.
1873 for (i = format->nframes; i > 0; --i) {
1874 frame = &format->frame[i-1];
1875 if (frame->bFrameIndex == probe->bFrameIndex)
1879 probe->bFormatIndex = format->index;
1880 probe->bFrameIndex = frame->bFrameIndex;
1882 stream->def_format = format;
1883 stream->cur_format = format;
1884 stream->cur_frame = frame;
1886 /* Select the video decoding function */
1887 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1888 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1889 stream->decode = uvc_video_decode_isight;
1890 else if (stream->intf->num_altsetting > 1)
1891 stream->decode = uvc_video_decode_isoc;
1893 stream->decode = uvc_video_decode_bulk;
1895 if (stream->intf->num_altsetting == 1)
1896 stream->decode = uvc_video_encode_bulk;
1898 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1899 "supported for video output devices.\n");
1908 * Enable or disable the video stream.
1910 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1915 uvc_uninit_video(stream, 1);
1916 if (stream->intf->num_altsetting > 1) {
1917 usb_set_interface(stream->dev->udev,
1918 stream->intfnum, 0);
1920 /* UVC doesn't specify how to inform a bulk-based device
1921 * when the video stream is stopped. Windows sends a
1922 * CLEAR_FEATURE(HALT) request to the video streaming
1923 * bulk endpoint, mimic the same behaviour.
1925 unsigned int epnum = stream->header.bEndpointAddress
1926 & USB_ENDPOINT_NUMBER_MASK;
1927 unsigned int dir = stream->header.bEndpointAddress
1928 & USB_ENDPOINT_DIR_MASK;
1931 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
1932 usb_clear_halt(stream->dev->udev, pipe);
1935 uvc_video_clock_cleanup(stream);
1939 ret = uvc_video_clock_init(stream);
1943 /* Commit the streaming parameters. */
1944 ret = uvc_commit_video(stream, &stream->ctrl);
1948 ret = uvc_init_video(stream, GFP_KERNEL);
1955 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1957 uvc_video_clock_cleanup(stream);