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 struct uvc_format *format = NULL;
93 struct uvc_frame *frame = NULL;
96 for (i = 0; i < stream->nformats; ++i) {
97 if (stream->format[i].index == ctrl->bFormatIndex) {
98 format = &stream->format[i];
106 for (i = 0; i < format->nframes; ++i) {
107 if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
108 frame = &format->frame[i];
116 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
117 (ctrl->dwMaxVideoFrameSize == 0 &&
118 stream->dev->uvc_version < 0x0110))
119 ctrl->dwMaxVideoFrameSize =
120 frame->dwMaxVideoFrameBufferSize;
122 /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
123 * compute the bandwidth on 16 bits and erroneously sign-extend it to
124 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
125 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
127 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
128 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
130 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
131 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
132 stream->intf->num_altsetting > 1) {
136 interval = (ctrl->dwFrameInterval > 100000)
137 ? ctrl->dwFrameInterval
138 : frame->dwFrameInterval[0];
140 /* Compute a bandwidth estimation by multiplying the frame
141 * size by the number of video frames per second, divide the
142 * result by the number of USB frames (or micro-frames for
143 * high-speed devices) per second and add the UVC header size
144 * (assumed to be 12 bytes long).
146 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
147 bandwidth *= 10000000 / interval + 1;
149 if (stream->dev->udev->speed == USB_SPEED_HIGH)
153 /* The bandwidth estimate is too low for many cameras. Don't use
154 * maximum packet sizes lower than 1024 bytes to try and work
155 * around the problem. According to measurements done on two
156 * different camera models, the value is high enough to get most
157 * resolutions working while not preventing two simultaneous
158 * VGA streams at 15 fps.
160 bandwidth = max_t(u32, bandwidth, 1024);
162 ctrl->dwMaxPayloadTransferSize = bandwidth;
166 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
169 * Return the size of the video probe and commit controls, which depends
170 * on the protocol version.
172 if (stream->dev->uvc_version < 0x0110)
174 else if (stream->dev->uvc_version < 0x0150)
180 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
181 struct uvc_streaming_control *ctrl, int probe, u8 query)
183 u16 size = uvc_video_ctrl_size(stream);
187 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
188 query == UVC_GET_DEF)
191 data = kmalloc(size, GFP_KERNEL);
195 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
196 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
197 size, uvc_timeout_param);
199 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
200 /* Some cameras, mostly based on Bison Electronics chipsets,
201 * answer a GET_MIN or GET_MAX request with the wCompQuality
204 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
205 "compliance - GET_MIN/MAX(PROBE) incorrectly "
206 "supported. Enabling workaround.\n");
207 memset(ctrl, 0, sizeof(*ctrl));
208 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
211 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
212 /* Many cameras don't support the GET_DEF request on their
213 * video probe control. Warn once and return, the caller will
214 * fall back to GET_CUR.
216 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
217 "compliance - GET_DEF(PROBE) not supported. "
218 "Enabling workaround.\n");
221 } else if (ret != size) {
222 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
223 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
229 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
230 ctrl->bFormatIndex = data[2];
231 ctrl->bFrameIndex = data[3];
232 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
233 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
234 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
235 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
236 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
237 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
238 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
239 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
242 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
243 ctrl->bmFramingInfo = data[30];
244 ctrl->bPreferedVersion = data[31];
245 ctrl->bMinVersion = data[32];
246 ctrl->bMaxVersion = data[33];
248 ctrl->dwClockFrequency = stream->dev->clock_frequency;
249 ctrl->bmFramingInfo = 0;
250 ctrl->bPreferedVersion = 0;
251 ctrl->bMinVersion = 0;
252 ctrl->bMaxVersion = 0;
255 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
256 * dwMaxPayloadTransferSize fields. Try to get the value from the
257 * format and frame descriptors.
259 uvc_fixup_video_ctrl(stream, ctrl);
267 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
268 struct uvc_streaming_control *ctrl, int probe)
270 u16 size = uvc_video_ctrl_size(stream);
274 data = kzalloc(size, GFP_KERNEL);
278 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
279 data[2] = ctrl->bFormatIndex;
280 data[3] = ctrl->bFrameIndex;
281 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
282 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
283 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
284 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
285 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
286 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
287 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
288 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
291 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
292 data[30] = ctrl->bmFramingInfo;
293 data[31] = ctrl->bPreferedVersion;
294 data[32] = ctrl->bMinVersion;
295 data[33] = ctrl->bMaxVersion;
298 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
299 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
300 size, uvc_timeout_param);
302 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
303 "%d (exp. %u).\n", probe ? "probe" : "commit",
312 int uvc_probe_video(struct uvc_streaming *stream,
313 struct uvc_streaming_control *probe)
315 struct uvc_streaming_control probe_min, probe_max;
320 /* Perform probing. The device should adjust the requested values
321 * according to its capabilities. However, some devices, namely the
322 * first generation UVC Logitech webcams, don't implement the Video
323 * Probe control properly, and just return the needed bandwidth. For
324 * that reason, if the needed bandwidth exceeds the maximum available
325 * bandwidth, try to lower the quality.
327 ret = uvc_set_video_ctrl(stream, probe, 1);
331 /* Get the minimum and maximum values for compression settings. */
332 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
333 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
336 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
340 probe->wCompQuality = probe_max.wCompQuality;
343 for (i = 0; i < 2; ++i) {
344 ret = uvc_set_video_ctrl(stream, probe, 1);
347 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
351 if (stream->intf->num_altsetting == 1)
354 bandwidth = probe->dwMaxPayloadTransferSize;
355 if (bandwidth <= stream->maxpsize)
358 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
363 /* TODO: negotiate compression parameters */
364 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
365 probe->wPFrameRate = probe_min.wPFrameRate;
366 probe->wCompQuality = probe_max.wCompQuality;
367 probe->wCompWindowSize = probe_min.wCompWindowSize;
374 static int uvc_commit_video(struct uvc_streaming *stream,
375 struct uvc_streaming_control *probe)
377 return uvc_set_video_ctrl(stream, probe, 0);
380 /* -----------------------------------------------------------------------------
381 * Clocks and timestamps
384 static inline ktime_t uvc_video_get_time(void)
386 if (uvc_clock_param == CLOCK_MONOTONIC)
389 return ktime_get_real();
393 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
394 const u8 *data, int len)
396 struct uvc_clock_sample *sample;
397 unsigned int header_size;
398 bool has_pts = false;
399 bool has_scr = false;
405 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
406 case UVC_STREAM_PTS | UVC_STREAM_SCR:
424 /* Check for invalid headers. */
425 if (len < header_size)
428 /* Extract the timestamps:
430 * - store the frame PTS in the buffer structure
431 * - if the SCR field is present, retrieve the host SOF counter and
432 * kernel timestamps and store them with the SCR STC and SOF fields
435 if (has_pts && buf != NULL)
436 buf->pts = get_unaligned_le32(&data[2]);
441 /* To limit the amount of data, drop SCRs with an SOF identical to the
444 dev_sof = get_unaligned_le16(&data[header_size - 2]);
445 if (dev_sof == stream->clock.last_sof)
448 stream->clock.last_sof = dev_sof;
450 host_sof = usb_get_current_frame_number(stream->dev->udev);
451 time = uvc_video_get_time();
453 /* The UVC specification allows device implementations that can't obtain
454 * the USB frame number to keep their own frame counters as long as they
455 * match the size and frequency of the frame number associated with USB
456 * SOF tokens. The SOF values sent by such devices differ from the USB
457 * SOF tokens by a fixed offset that needs to be estimated and accounted
458 * for to make timestamp recovery as accurate as possible.
460 * The offset is estimated the first time a device SOF value is received
461 * as the difference between the host and device SOF values. As the two
462 * SOF values can differ slightly due to transmission delays, consider
463 * that the offset is null if the difference is not higher than 10 ms
464 * (negative differences can not happen and are thus considered as an
465 * offset). The video commit control wDelay field should be used to
466 * compute a dynamic threshold instead of using a fixed 10 ms value, but
467 * devices don't report reliable wDelay values.
469 * See uvc_video_clock_host_sof() for an explanation regarding why only
470 * the 8 LSBs of the delta are kept.
472 if (stream->clock.sof_offset == (u16)-1) {
473 u16 delta_sof = (host_sof - dev_sof) & 255;
475 stream->clock.sof_offset = delta_sof;
477 stream->clock.sof_offset = 0;
480 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
482 spin_lock_irqsave(&stream->clock.lock, flags);
484 sample = &stream->clock.samples[stream->clock.head];
485 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
486 sample->dev_sof = dev_sof;
487 sample->host_sof = host_sof;
488 sample->host_time = time;
490 /* Update the sliding window head and count. */
491 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
493 if (stream->clock.count < stream->clock.size)
494 stream->clock.count++;
496 spin_unlock_irqrestore(&stream->clock.lock, flags);
499 static void uvc_video_clock_reset(struct uvc_streaming *stream)
501 struct uvc_clock *clock = &stream->clock;
505 clock->last_sof = -1;
506 clock->sof_offset = -1;
509 static int uvc_video_clock_init(struct uvc_streaming *stream)
511 struct uvc_clock *clock = &stream->clock;
513 spin_lock_init(&clock->lock);
516 clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples),
518 if (clock->samples == NULL)
521 uvc_video_clock_reset(stream);
526 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
528 kfree(stream->clock.samples);
529 stream->clock.samples = NULL;
533 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
535 * Host SOF counters reported by usb_get_current_frame_number() usually don't
536 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
537 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
538 * controller and its configuration.
540 * We thus need to recover the SOF value corresponding to the host frame number.
541 * As the device and host frame numbers are sampled in a short interval, the
542 * difference between their values should be equal to a small delta plus an
543 * integer multiple of 256 caused by the host frame number limited precision.
545 * To obtain the recovered host SOF value, compute the small delta by masking
546 * the high bits of the host frame counter and device SOF difference and add it
547 * to the device SOF value.
549 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
551 /* The delta value can be negative. */
554 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
556 return (sample->dev_sof + delta_sof) & 2047;
560 * uvc_video_clock_update - Update the buffer timestamp
562 * This function converts the buffer PTS timestamp to the host clock domain by
563 * going through the USB SOF clock domain and stores the result in the V4L2
564 * buffer timestamp field.
566 * The relationship between the device clock and the host clock isn't known.
567 * However, the device and the host share the common USB SOF clock which can be
568 * used to recover that relationship.
570 * The relationship between the device clock and the USB SOF clock is considered
571 * to be linear over the clock samples sliding window and is given by
575 * Several methods to compute the slope (m) and intercept (p) can be used. As
576 * the clock drift should be small compared to the sliding window size, we
577 * assume that the line that goes through the points at both ends of the window
578 * is a good approximation. Naming those points P1 and P2, we get
580 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
581 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
585 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
587 * to avoid losing precision in the division. Similarly, the host timestamp is
590 * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
592 * SOF values are coded on 11 bits by USB. We extend their precision with 16
593 * decimal bits, leading to a 11.16 coding.
595 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
596 * be normalized using the nominal device clock frequency reported through the
599 * Both the PTS/STC and SOF counters roll over, after a fixed but device
600 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
601 * sliding window size is smaller than the rollover period, differences computed
602 * on unsigned integers will produce the correct result. However, the p term in
603 * the linear relations will be miscomputed.
605 * To fix the issue, we subtract a constant from the PTS and STC values to bring
606 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
607 * the 32 bit range without any rollover.
609 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
610 * computed by (1) will never be smaller than 0. This offset is then compensated
611 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
612 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
613 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
614 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
615 * SOF value at the end of the sliding window.
617 * Finally we subtract a constant from the host timestamps to bring the first
618 * timestamp of the sliding window to 1s.
620 void uvc_video_clock_update(struct uvc_streaming *stream,
621 struct vb2_v4l2_buffer *vbuf,
622 struct uvc_buffer *buf)
624 struct uvc_clock *clock = &stream->clock;
625 struct uvc_clock_sample *first;
626 struct uvc_clock_sample *last;
636 if (!uvc_hw_timestamps_param)
639 spin_lock_irqsave(&clock->lock, flags);
641 if (clock->count < clock->size)
644 first = &clock->samples[clock->head];
645 last = &clock->samples[(clock->head - 1) % clock->size];
647 /* First step, PTS to SOF conversion. */
648 delta_stc = buf->pts - (1UL << 31);
649 x1 = first->dev_stc - delta_stc;
650 x2 = last->dev_stc - delta_stc;
654 y1 = (first->dev_sof + 2048) << 16;
655 y2 = (last->dev_sof + 2048) << 16;
659 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
661 y = div_u64(y, x2 - x1);
665 uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
666 "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
667 stream->dev->name, buf->pts,
668 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
669 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
670 x1, x2, y1, y2, clock->sof_offset);
672 /* Second step, SOF to host clock conversion. */
673 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
674 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
681 y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
683 /* Interpolated and host SOF timestamps can wrap around at slightly
684 * different times. Handle this by adding or removing 2048 to or from
685 * the computed SOF value to keep it close to the SOF samples mean
688 mean = (x1 + x2) / 2;
689 if (mean - (1024 << 16) > sof)
691 else if (sof > mean + (1024 << 16))
694 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
696 y = div_u64(y, x2 - x1);
698 timestamp = ktime_to_ns(first->host_time) + y - y1;
700 uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
701 "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
703 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
704 y, timestamp, vbuf->vb2_buf.timestamp,
705 x1, first->host_sof, first->dev_sof,
706 x2, last->host_sof, last->dev_sof, y1, y2);
708 /* Update the V4L2 buffer. */
709 vbuf->vb2_buf.timestamp = timestamp;
712 spin_unlock_irqrestore(&clock->lock, flags);
715 /* ------------------------------------------------------------------------
719 static void uvc_video_stats_decode(struct uvc_streaming *stream,
720 const u8 *data, int len)
722 unsigned int header_size;
723 bool has_pts = false;
724 bool has_scr = false;
725 u16 uninitialized_var(scr_sof);
726 u32 uninitialized_var(scr_stc);
727 u32 uninitialized_var(pts);
729 if (stream->stats.stream.nb_frames == 0 &&
730 stream->stats.frame.nb_packets == 0)
731 stream->stats.stream.start_ts = ktime_get();
733 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
734 case UVC_STREAM_PTS | UVC_STREAM_SCR:
752 /* Check for invalid headers. */
753 if (len < header_size || data[0] < header_size) {
754 stream->stats.frame.nb_invalid++;
758 /* Extract the timestamps. */
760 pts = get_unaligned_le32(&data[2]);
763 scr_stc = get_unaligned_le32(&data[header_size - 6]);
764 scr_sof = get_unaligned_le16(&data[header_size - 2]);
767 /* Is PTS constant through the whole frame ? */
768 if (has_pts && stream->stats.frame.nb_pts) {
769 if (stream->stats.frame.pts != pts) {
770 stream->stats.frame.nb_pts_diffs++;
771 stream->stats.frame.last_pts_diff =
772 stream->stats.frame.nb_packets;
777 stream->stats.frame.nb_pts++;
778 stream->stats.frame.pts = pts;
781 /* Do all frames have a PTS in their first non-empty packet, or before
782 * their first empty packet ?
784 if (stream->stats.frame.size == 0) {
785 if (len > header_size)
786 stream->stats.frame.has_initial_pts = has_pts;
787 if (len == header_size && has_pts)
788 stream->stats.frame.has_early_pts = true;
791 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
792 if (has_scr && stream->stats.frame.nb_scr) {
793 if (stream->stats.frame.scr_stc != scr_stc)
794 stream->stats.frame.nb_scr_diffs++;
798 /* Expand the SOF counter to 32 bits and store its value. */
799 if (stream->stats.stream.nb_frames > 0 ||
800 stream->stats.frame.nb_scr > 0)
801 stream->stats.stream.scr_sof_count +=
802 (scr_sof - stream->stats.stream.scr_sof) % 2048;
803 stream->stats.stream.scr_sof = scr_sof;
805 stream->stats.frame.nb_scr++;
806 stream->stats.frame.scr_stc = scr_stc;
807 stream->stats.frame.scr_sof = scr_sof;
809 if (scr_sof < stream->stats.stream.min_sof)
810 stream->stats.stream.min_sof = scr_sof;
811 if (scr_sof > stream->stats.stream.max_sof)
812 stream->stats.stream.max_sof = scr_sof;
815 /* Record the first non-empty packet number. */
816 if (stream->stats.frame.size == 0 && len > header_size)
817 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
819 /* Update the frame size. */
820 stream->stats.frame.size += len - header_size;
822 /* Update the packets counters. */
823 stream->stats.frame.nb_packets++;
824 if (len <= header_size)
825 stream->stats.frame.nb_empty++;
827 if (data[1] & UVC_STREAM_ERR)
828 stream->stats.frame.nb_errors++;
831 static void uvc_video_stats_update(struct uvc_streaming *stream)
833 struct uvc_stats_frame *frame = &stream->stats.frame;
835 uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
836 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
837 "last pts/stc/sof %u/%u/%u\n",
838 stream->sequence, frame->first_data,
839 frame->nb_packets - frame->nb_empty, frame->nb_packets,
840 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
841 frame->has_early_pts ? "" : "!",
842 frame->has_initial_pts ? "" : "!",
843 frame->nb_scr_diffs, frame->nb_scr,
844 frame->pts, frame->scr_stc, frame->scr_sof);
846 stream->stats.stream.nb_frames++;
847 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
848 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
849 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
850 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
852 if (frame->has_early_pts)
853 stream->stats.stream.nb_pts_early++;
854 if (frame->has_initial_pts)
855 stream->stats.stream.nb_pts_initial++;
856 if (frame->last_pts_diff <= frame->first_data)
857 stream->stats.stream.nb_pts_constant++;
858 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
859 stream->stats.stream.nb_scr_count_ok++;
860 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
861 stream->stats.stream.nb_scr_diffs_ok++;
863 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
866 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
869 unsigned int scr_sof_freq;
870 unsigned int duration;
873 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
874 * frequency this will not overflow before more than 1h.
876 duration = ktime_ms_delta(stream->stats.stream.stop_ts,
877 stream->stats.stream.start_ts);
879 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
884 count += scnprintf(buf + count, size - count,
885 "frames: %u\npackets: %u\nempty: %u\n"
886 "errors: %u\ninvalid: %u\n",
887 stream->stats.stream.nb_frames,
888 stream->stats.stream.nb_packets,
889 stream->stats.stream.nb_empty,
890 stream->stats.stream.nb_errors,
891 stream->stats.stream.nb_invalid);
892 count += scnprintf(buf + count, size - count,
893 "pts: %u early, %u initial, %u ok\n",
894 stream->stats.stream.nb_pts_early,
895 stream->stats.stream.nb_pts_initial,
896 stream->stats.stream.nb_pts_constant);
897 count += scnprintf(buf + count, size - count,
898 "scr: %u count ok, %u diff ok\n",
899 stream->stats.stream.nb_scr_count_ok,
900 stream->stats.stream.nb_scr_diffs_ok);
901 count += scnprintf(buf + count, size - count,
902 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
903 stream->stats.stream.min_sof,
904 stream->stats.stream.max_sof,
905 scr_sof_freq / 1000, scr_sof_freq % 1000);
910 static void uvc_video_stats_start(struct uvc_streaming *stream)
912 memset(&stream->stats, 0, sizeof(stream->stats));
913 stream->stats.stream.min_sof = 2048;
916 static void uvc_video_stats_stop(struct uvc_streaming *stream)
918 stream->stats.stream.stop_ts = ktime_get();
921 /* ------------------------------------------------------------------------
925 /* Video payload decoding is handled by uvc_video_decode_start(),
926 * uvc_video_decode_data() and uvc_video_decode_end().
928 * uvc_video_decode_start is called with URB data at the start of a bulk or
929 * isochronous payload. It processes header data and returns the header size
930 * in bytes if successful. If an error occurs, it returns a negative error
931 * code. The following error codes have special meanings.
933 * - EAGAIN informs the caller that the current video buffer should be marked
934 * as done, and that the function should be called again with the same data
935 * and a new video buffer. This is used when end of frame conditions can be
936 * reliably detected at the beginning of the next frame only.
938 * If an error other than -EAGAIN is returned, the caller will drop the current
939 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
940 * made until the next payload. -ENODATA can be used to drop the current
941 * payload if no other error code is appropriate.
943 * uvc_video_decode_data is called for every URB with URB data. It copies the
944 * data to the video buffer.
946 * uvc_video_decode_end is called with header data at the end of a bulk or
947 * isochronous payload. It performs any additional header data processing and
948 * returns 0 or a negative error code if an error occurred. As header data have
949 * already been processed by uvc_video_decode_start, this functions isn't
950 * required to perform sanity checks a second time.
952 * For isochronous transfers where a payload is always transferred in a single
953 * URB, the three functions will be called in a row.
955 * To let the decoder process header data and update its internal state even
956 * when no video buffer is available, uvc_video_decode_start must be prepared
957 * to be called with a NULL buf parameter. uvc_video_decode_data and
958 * uvc_video_decode_end will never be called with a NULL buffer.
960 static int uvc_video_decode_start(struct uvc_streaming *stream,
961 struct uvc_buffer *buf, const u8 *data, int len)
966 * - packet must be at least 2 bytes long
967 * - bHeaderLength value must be at least 2 bytes (see above)
968 * - bHeaderLength value can't be larger than the packet size.
970 if (len < 2 || data[0] < 2 || data[0] > len) {
971 stream->stats.frame.nb_invalid++;
975 fid = data[1] & UVC_STREAM_FID;
977 /* Increase the sequence number regardless of any buffer states, so
978 * that discontinuous sequence numbers always indicate lost frames.
980 if (stream->last_fid != fid) {
982 if (stream->sequence)
983 uvc_video_stats_update(stream);
986 uvc_video_clock_decode(stream, buf, data, len);
987 uvc_video_stats_decode(stream, data, len);
989 /* Store the payload FID bit and return immediately when the buffer is
993 stream->last_fid = fid;
997 /* Mark the buffer as bad if the error bit is set. */
998 if (data[1] & UVC_STREAM_ERR) {
999 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1004 /* Synchronize to the input stream by waiting for the FID bit to be
1005 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1006 * stream->last_fid is initialized to -1, so the first isochronous
1007 * frame will always be in sync.
1009 * If the device doesn't toggle the FID bit, invert stream->last_fid
1010 * when the EOF bit is set to force synchronisation on the next packet.
1012 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1013 if (fid == stream->last_fid) {
1014 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1016 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1017 (data[1] & UVC_STREAM_EOF))
1018 stream->last_fid ^= UVC_STREAM_FID;
1022 buf->buf.field = V4L2_FIELD_NONE;
1023 buf->buf.sequence = stream->sequence;
1024 buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
1026 /* TODO: Handle PTS and SCR. */
1027 buf->state = UVC_BUF_STATE_ACTIVE;
1030 /* Mark the buffer as done if we're at the beginning of a new frame.
1031 * End of frame detection is better implemented by checking the EOF
1032 * bit (FID bit toggling is delayed by one frame compared to the EOF
1033 * bit), but some devices don't set the bit at end of frame (and the
1034 * last payload can be lost anyway). We thus must check if the FID has
1037 * stream->last_fid is initialized to -1, so the first isochronous
1038 * frame will never trigger an end of frame detection.
1040 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1041 * as it doesn't make sense to return an empty buffer. This also
1042 * avoids detecting end of frame conditions at FID toggling if the
1043 * previous payload had the EOF bit set.
1045 if (fid != stream->last_fid && buf->bytesused != 0) {
1046 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1048 buf->state = UVC_BUF_STATE_READY;
1052 stream->last_fid = fid;
1057 static void uvc_video_decode_data(struct uvc_streaming *stream,
1058 struct uvc_buffer *buf, const u8 *data, int len)
1060 unsigned int maxlen, nbytes;
1066 /* Copy the video data to the buffer. */
1067 maxlen = buf->length - buf->bytesused;
1068 mem = buf->mem + buf->bytesused;
1069 nbytes = min((unsigned int)len, maxlen);
1070 memcpy(mem, data, nbytes);
1071 buf->bytesused += nbytes;
1073 /* Complete the current frame if the buffer size was exceeded. */
1075 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1077 buf->state = UVC_BUF_STATE_READY;
1081 static void uvc_video_decode_end(struct uvc_streaming *stream,
1082 struct uvc_buffer *buf, const u8 *data, int len)
1084 /* Mark the buffer as done if the EOF marker is set. */
1085 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1086 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1088 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1089 buf->state = UVC_BUF_STATE_READY;
1090 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1091 stream->last_fid ^= UVC_STREAM_FID;
1095 /* Video payload encoding is handled by uvc_video_encode_header() and
1096 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1098 * uvc_video_encode_header is called at the start of a payload. It adds header
1099 * data to the transfer buffer and returns the header size. As the only known
1100 * UVC output device transfers a whole frame in a single payload, the EOF bit
1101 * is always set in the header.
1103 * uvc_video_encode_data is called for every URB and copies the data from the
1104 * video buffer to the transfer buffer.
1106 static int uvc_video_encode_header(struct uvc_streaming *stream,
1107 struct uvc_buffer *buf, u8 *data, int len)
1109 data[0] = 2; /* Header length */
1110 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1111 | (stream->last_fid & UVC_STREAM_FID);
1115 static int uvc_video_encode_data(struct uvc_streaming *stream,
1116 struct uvc_buffer *buf, u8 *data, int len)
1118 struct uvc_video_queue *queue = &stream->queue;
1119 unsigned int nbytes;
1122 /* Copy video data to the URB buffer. */
1123 mem = buf->mem + queue->buf_used;
1124 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1125 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1127 memcpy(data, mem, nbytes);
1129 queue->buf_used += nbytes;
1134 /* ------------------------------------------------------------------------
1139 * Additionally to the payload headers we also want to provide the user with USB
1140 * Frame Numbers and system time values. The resulting buffer is thus composed
1141 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
1142 * Number, and a copy of the payload header.
1144 * Ideally we want to capture all payload headers for each frame. However, their
1145 * number is unknown and unbound. We thus drop headers that contain no vendor
1146 * data and that either contain no SCR value or an SCR value identical to the
1149 static void uvc_video_decode_meta(struct uvc_streaming *stream,
1150 struct uvc_buffer *meta_buf,
1151 const u8 *mem, unsigned int length)
1153 struct uvc_meta_buf *meta;
1155 bool has_pts, has_scr;
1156 unsigned long flags;
1161 if (!meta_buf || length == 2)
1164 if (meta_buf->length - meta_buf->bytesused <
1165 length + sizeof(meta->ns) + sizeof(meta->sof)) {
1166 meta_buf->error = 1;
1170 has_pts = mem[1] & UVC_STREAM_PTS;
1171 has_scr = mem[1] & UVC_STREAM_SCR;
1183 if (stream->meta.format == V4L2_META_FMT_UVC)
1186 if (length == len_std && (!has_scr ||
1187 !memcmp(scr, stream->clock.last_scr, 6)))
1190 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
1191 local_irq_save(flags);
1192 time = uvc_video_get_time();
1193 sof = usb_get_current_frame_number(stream->dev->udev);
1194 local_irq_restore(flags);
1195 put_unaligned(ktime_to_ns(time), &meta->ns);
1196 put_unaligned(sof, &meta->sof);
1199 memcpy(stream->clock.last_scr, scr, 6);
1201 memcpy(&meta->length, mem, length);
1202 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
1204 uvc_trace(UVC_TRACE_FRAME,
1205 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
1206 __func__, ktime_to_ns(time), meta->sof, meta->length,
1208 has_pts ? *(u32 *)meta->buf : 0,
1209 has_scr ? *(u32 *)scr : 0,
1210 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
1213 /* ------------------------------------------------------------------------
1218 * Set error flag for incomplete buffer.
1220 static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1221 struct uvc_buffer *buf)
1223 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1224 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1229 * Completion handler for video URBs.
1232 static void uvc_video_next_buffers(struct uvc_streaming *stream,
1233 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
1236 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
1237 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
1239 vb2_meta->sequence = vb2_video->sequence;
1240 vb2_meta->field = vb2_video->field;
1241 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
1243 (*meta_buf)->state = UVC_BUF_STATE_READY;
1244 if (!(*meta_buf)->error)
1245 (*meta_buf)->error = (*video_buf)->error;
1246 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
1249 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
1252 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1253 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1258 for (i = 0; i < urb->number_of_packets; ++i) {
1259 if (urb->iso_frame_desc[i].status < 0) {
1260 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1261 "lost (%d).\n", urb->iso_frame_desc[i].status);
1262 /* Mark the buffer as faulty. */
1268 /* Decode the payload header. */
1269 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1271 ret = uvc_video_decode_start(stream, buf, mem,
1272 urb->iso_frame_desc[i].actual_length);
1273 if (ret == -EAGAIN) {
1274 uvc_video_validate_buffer(stream, buf);
1275 uvc_video_next_buffers(stream, &buf, &meta_buf);
1277 } while (ret == -EAGAIN);
1282 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1284 /* Decode the payload data. */
1285 uvc_video_decode_data(stream, buf, mem + ret,
1286 urb->iso_frame_desc[i].actual_length - ret);
1288 /* Process the header again. */
1289 uvc_video_decode_end(stream, buf, mem,
1290 urb->iso_frame_desc[i].actual_length);
1292 if (buf->state == UVC_BUF_STATE_READY) {
1293 uvc_video_validate_buffer(stream, buf);
1294 uvc_video_next_buffers(stream, &buf, &meta_buf);
1299 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1300 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1306 * Ignore ZLPs if they're not part of a frame, otherwise process them
1307 * to trigger the end of payload detection.
1309 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1312 mem = urb->transfer_buffer;
1313 len = urb->actual_length;
1314 stream->bulk.payload_size += len;
1316 /* If the URB is the first of its payload, decode and save the
1319 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1321 ret = uvc_video_decode_start(stream, buf, mem, len);
1323 uvc_video_next_buffers(stream, &buf, &meta_buf);
1324 } while (ret == -EAGAIN);
1326 /* If an error occurred skip the rest of the payload. */
1327 if (ret < 0 || buf == NULL) {
1328 stream->bulk.skip_payload = 1;
1330 memcpy(stream->bulk.header, mem, ret);
1331 stream->bulk.header_size = ret;
1333 uvc_video_decode_meta(stream, meta_buf, mem, ret);
1340 /* The buffer queue might have been cancelled while a bulk transfer
1341 * was in progress, so we can reach here with buf equal to NULL. Make
1342 * sure buf is never dereferenced if NULL.
1345 /* Process video data. */
1346 if (!stream->bulk.skip_payload && buf != NULL)
1347 uvc_video_decode_data(stream, buf, mem, len);
1349 /* Detect the payload end by a URB smaller than the maximum size (or
1350 * a payload size equal to the maximum) and process the header again.
1352 if (urb->actual_length < urb->transfer_buffer_length ||
1353 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1354 if (!stream->bulk.skip_payload && buf != NULL) {
1355 uvc_video_decode_end(stream, buf, stream->bulk.header,
1356 stream->bulk.payload_size);
1357 if (buf->state == UVC_BUF_STATE_READY)
1358 uvc_video_next_buffers(stream, &buf, &meta_buf);
1361 stream->bulk.header_size = 0;
1362 stream->bulk.skip_payload = 0;
1363 stream->bulk.payload_size = 0;
1367 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1368 struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1370 u8 *mem = urb->transfer_buffer;
1371 int len = stream->urb_size, ret;
1374 urb->transfer_buffer_length = 0;
1378 /* If the URB is the first of its payload, add the header. */
1379 if (stream->bulk.header_size == 0) {
1380 ret = uvc_video_encode_header(stream, buf, mem, len);
1381 stream->bulk.header_size = ret;
1382 stream->bulk.payload_size += ret;
1387 /* Process video data. */
1388 ret = uvc_video_encode_data(stream, buf, mem, len);
1390 stream->bulk.payload_size += ret;
1393 if (buf->bytesused == stream->queue.buf_used ||
1394 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1395 if (buf->bytesused == stream->queue.buf_used) {
1396 stream->queue.buf_used = 0;
1397 buf->state = UVC_BUF_STATE_READY;
1398 buf->buf.sequence = ++stream->sequence;
1399 uvc_queue_next_buffer(&stream->queue, buf);
1400 stream->last_fid ^= UVC_STREAM_FID;
1403 stream->bulk.header_size = 0;
1404 stream->bulk.payload_size = 0;
1407 urb->transfer_buffer_length = stream->urb_size - len;
1410 static void uvc_video_complete(struct urb *urb)
1412 struct uvc_streaming *stream = urb->context;
1413 struct uvc_video_queue *queue = &stream->queue;
1414 struct uvc_video_queue *qmeta = &stream->meta.queue;
1415 struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1416 struct uvc_buffer *buf = NULL;
1417 struct uvc_buffer *buf_meta = NULL;
1418 unsigned long flags;
1421 switch (urb->status) {
1426 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1427 "completion handler.\n", urb->status);
1429 case -ENOENT: /* usb_kill_urb() called. */
1433 case -ECONNRESET: /* usb_unlink_urb() called. */
1434 case -ESHUTDOWN: /* The endpoint is being disabled. */
1435 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1437 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1441 spin_lock_irqsave(&queue->irqlock, flags);
1442 if (!list_empty(&queue->irqqueue))
1443 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1445 spin_unlock_irqrestore(&queue->irqlock, flags);
1448 spin_lock_irqsave(&qmeta->irqlock, flags);
1449 if (!list_empty(&qmeta->irqqueue))
1450 buf_meta = list_first_entry(&qmeta->irqqueue,
1451 struct uvc_buffer, queue);
1452 spin_unlock_irqrestore(&qmeta->irqlock, flags);
1455 stream->decode(urb, stream, buf, buf_meta);
1457 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1458 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1464 * Free transfer buffers.
1466 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1470 for (i = 0; i < UVC_URBS; ++i) {
1471 if (stream->urb_buffer[i]) {
1472 #ifndef CONFIG_DMA_NONCOHERENT
1473 usb_free_coherent(stream->dev->udev, stream->urb_size,
1474 stream->urb_buffer[i], stream->urb_dma[i]);
1476 kfree(stream->urb_buffer[i]);
1478 stream->urb_buffer[i] = NULL;
1482 stream->urb_size = 0;
1486 * Allocate transfer buffers. This function can be called with buffers
1487 * already allocated when resuming from suspend, in which case it will
1488 * return without touching the buffers.
1490 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1491 * system is too low on memory try successively smaller numbers of packets
1492 * until allocation succeeds.
1494 * Return the number of allocated packets on success or 0 when out of memory.
1496 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1497 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1499 unsigned int npackets;
1502 /* Buffers are already allocated, bail out. */
1503 if (stream->urb_size)
1504 return stream->urb_size / psize;
1506 /* Compute the number of packets. Bulk endpoints might transfer UVC
1507 * payloads across multiple URBs.
1509 npackets = DIV_ROUND_UP(size, psize);
1510 if (npackets > UVC_MAX_PACKETS)
1511 npackets = UVC_MAX_PACKETS;
1513 /* Retry allocations until one succeed. */
1514 for (; npackets > 1; npackets /= 2) {
1515 for (i = 0; i < UVC_URBS; ++i) {
1516 stream->urb_size = psize * npackets;
1517 #ifndef CONFIG_DMA_NONCOHERENT
1518 stream->urb_buffer[i] = usb_alloc_coherent(
1519 stream->dev->udev, stream->urb_size,
1520 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1522 stream->urb_buffer[i] =
1523 kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1525 if (!stream->urb_buffer[i]) {
1526 uvc_free_urb_buffers(stream);
1531 if (i == UVC_URBS) {
1532 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1533 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1539 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1540 "per packet).\n", psize);
1545 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1547 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1552 uvc_video_stats_stop(stream);
1554 for (i = 0; i < UVC_URBS; ++i) {
1555 urb = stream->urb[i];
1561 stream->urb[i] = NULL;
1565 uvc_free_urb_buffers(stream);
1569 * Compute the maximum number of bytes per interval for an endpoint.
1571 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1572 struct usb_host_endpoint *ep)
1577 switch (dev->speed) {
1578 case USB_SPEED_SUPER:
1579 case USB_SPEED_SUPER_PLUS:
1580 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1581 case USB_SPEED_HIGH:
1582 psize = usb_endpoint_maxp(&ep->desc);
1583 mult = usb_endpoint_maxp_mult(&ep->desc);
1584 return psize * mult;
1585 case USB_SPEED_WIRELESS:
1586 psize = usb_endpoint_maxp(&ep->desc);
1589 psize = usb_endpoint_maxp(&ep->desc);
1595 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1596 * is given by the endpoint.
1598 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1599 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1602 unsigned int npackets, i, j;
1606 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1607 size = stream->ctrl.dwMaxVideoFrameSize;
1609 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1613 size = npackets * psize;
1615 for (i = 0; i < UVC_URBS; ++i) {
1616 urb = usb_alloc_urb(npackets, gfp_flags);
1618 uvc_uninit_video(stream, 1);
1622 urb->dev = stream->dev->udev;
1623 urb->context = stream;
1624 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1625 ep->desc.bEndpointAddress);
1626 #ifndef CONFIG_DMA_NONCOHERENT
1627 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1628 urb->transfer_dma = stream->urb_dma[i];
1630 urb->transfer_flags = URB_ISO_ASAP;
1632 urb->interval = ep->desc.bInterval;
1633 urb->transfer_buffer = stream->urb_buffer[i];
1634 urb->complete = uvc_video_complete;
1635 urb->number_of_packets = npackets;
1636 urb->transfer_buffer_length = size;
1638 for (j = 0; j < npackets; ++j) {
1639 urb->iso_frame_desc[j].offset = j * psize;
1640 urb->iso_frame_desc[j].length = psize;
1643 stream->urb[i] = urb;
1650 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1651 * given by the endpoint.
1653 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1654 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1657 unsigned int npackets, pipe, i;
1661 psize = usb_endpoint_maxp(&ep->desc);
1662 size = stream->ctrl.dwMaxPayloadTransferSize;
1663 stream->bulk.max_payload_size = size;
1665 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1669 size = npackets * psize;
1671 if (usb_endpoint_dir_in(&ep->desc))
1672 pipe = usb_rcvbulkpipe(stream->dev->udev,
1673 ep->desc.bEndpointAddress);
1675 pipe = usb_sndbulkpipe(stream->dev->udev,
1676 ep->desc.bEndpointAddress);
1678 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1681 for (i = 0; i < UVC_URBS; ++i) {
1682 urb = usb_alloc_urb(0, gfp_flags);
1684 uvc_uninit_video(stream, 1);
1688 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1689 stream->urb_buffer[i], size, uvc_video_complete,
1691 #ifndef CONFIG_DMA_NONCOHERENT
1692 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1693 urb->transfer_dma = stream->urb_dma[i];
1696 stream->urb[i] = urb;
1703 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1705 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1707 struct usb_interface *intf = stream->intf;
1708 struct usb_host_endpoint *ep;
1712 stream->sequence = -1;
1713 stream->last_fid = -1;
1714 stream->bulk.header_size = 0;
1715 stream->bulk.skip_payload = 0;
1716 stream->bulk.payload_size = 0;
1718 uvc_video_stats_start(stream);
1720 if (intf->num_altsetting > 1) {
1721 struct usb_host_endpoint *best_ep = NULL;
1722 unsigned int best_psize = UINT_MAX;
1723 unsigned int bandwidth;
1724 unsigned int uninitialized_var(altsetting);
1725 int intfnum = stream->intfnum;
1727 /* Isochronous endpoint, select the alternate setting. */
1728 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1730 if (bandwidth == 0) {
1731 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1732 "bandwidth, defaulting to lowest.\n");
1735 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1736 "B/frame bandwidth.\n", bandwidth);
1739 for (i = 0; i < intf->num_altsetting; ++i) {
1740 struct usb_host_interface *alts;
1743 alts = &intf->altsetting[i];
1744 ep = uvc_find_endpoint(alts,
1745 stream->header.bEndpointAddress);
1749 /* Check if the bandwidth is high enough. */
1750 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1751 if (psize >= bandwidth && psize <= best_psize) {
1752 altsetting = alts->desc.bAlternateSetting;
1758 if (best_ep == NULL) {
1759 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1760 "for requested bandwidth.\n");
1764 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1765 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1767 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1771 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1773 /* Bulk endpoint, proceed to URB initialization. */
1774 ep = uvc_find_endpoint(&intf->altsetting[0],
1775 stream->header.bEndpointAddress);
1779 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1785 /* Submit the URBs. */
1786 for (i = 0; i < UVC_URBS; ++i) {
1787 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1789 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1791 uvc_uninit_video(stream, 1);
1796 /* The Logitech C920 temporarily forgets that it should not be adjusting
1797 * Exposure Absolute during init so restore controls to stored values.
1799 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
1800 uvc_ctrl_restore_values(stream->dev);
1805 /* --------------------------------------------------------------------------
1810 * Stop streaming without disabling the video queue.
1812 * To let userspace applications resume without trouble, we must not touch the
1813 * video buffers in any way. We mark the device as frozen to make sure the URB
1814 * completion handler won't try to cancel the queue when we kill the URBs.
1816 int uvc_video_suspend(struct uvc_streaming *stream)
1818 if (!uvc_queue_streaming(&stream->queue))
1822 uvc_uninit_video(stream, 0);
1823 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1828 * Reconfigure the video interface and restart streaming if it was enabled
1831 * If an error occurs, disable the video queue. This will wake all pending
1832 * buffers, making sure userspace applications are notified of the problem
1833 * instead of waiting forever.
1835 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1839 /* If the bus has been reset on resume, set the alternate setting to 0.
1840 * This should be the default value, but some devices crash or otherwise
1841 * misbehave if they don't receive a SET_INTERFACE request before any
1842 * other video control request.
1845 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1849 uvc_video_clock_reset(stream);
1851 if (!uvc_queue_streaming(&stream->queue))
1854 ret = uvc_commit_video(stream, &stream->ctrl);
1858 return uvc_init_video(stream, GFP_NOIO);
1861 /* ------------------------------------------------------------------------
1866 * Initialize the UVC video device by switching to alternate setting 0 and
1867 * retrieve the default format.
1869 * Some cameras (namely the Fuji Finepix) set the format and frame
1870 * indexes to zero. The UVC standard doesn't clearly make this a spec
1871 * violation, so try to silently fix the values if possible.
1873 * This function is called before registering the device with V4L.
1875 int uvc_video_init(struct uvc_streaming *stream)
1877 struct uvc_streaming_control *probe = &stream->ctrl;
1878 struct uvc_format *format = NULL;
1879 struct uvc_frame *frame = NULL;
1883 if (stream->nformats == 0) {
1884 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1888 atomic_set(&stream->active, 0);
1890 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1891 * Cam (and possibly other devices) crash or otherwise misbehave if
1892 * they don't receive a SET_INTERFACE request before any other video
1895 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1897 /* Set the streaming probe control with default streaming parameters
1898 * retrieved from the device. Webcams that don't suport GET_DEF
1899 * requests on the probe control will just keep their current streaming
1902 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1903 uvc_set_video_ctrl(stream, probe, 1);
1905 /* Initialize the streaming parameters with the probe control current
1906 * value. This makes sure SET_CUR requests on the streaming commit
1907 * control will always use values retrieved from a successful GET_CUR
1908 * request on the probe control, as required by the UVC specification.
1910 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1914 /* Check if the default format descriptor exists. Use the first
1915 * available format otherwise.
1917 for (i = stream->nformats; i > 0; --i) {
1918 format = &stream->format[i-1];
1919 if (format->index == probe->bFormatIndex)
1923 if (format->nframes == 0) {
1924 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1925 "default format.\n");
1929 /* Zero bFrameIndex might be correct. Stream-based formats (including
1930 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1931 * descriptor with bFrameIndex set to zero. If the default frame
1932 * descriptor is not found, use the first available frame.
1934 for (i = format->nframes; i > 0; --i) {
1935 frame = &format->frame[i-1];
1936 if (frame->bFrameIndex == probe->bFrameIndex)
1940 probe->bFormatIndex = format->index;
1941 probe->bFrameIndex = frame->bFrameIndex;
1943 stream->def_format = format;
1944 stream->cur_format = format;
1945 stream->cur_frame = frame;
1947 /* Select the video decoding function */
1948 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1949 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1950 stream->decode = uvc_video_decode_isight;
1951 else if (stream->intf->num_altsetting > 1)
1952 stream->decode = uvc_video_decode_isoc;
1954 stream->decode = uvc_video_decode_bulk;
1956 if (stream->intf->num_altsetting == 1)
1957 stream->decode = uvc_video_encode_bulk;
1959 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1960 "supported for video output devices.\n");
1969 * Enable or disable the video stream.
1971 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1976 uvc_uninit_video(stream, 1);
1977 if (stream->intf->num_altsetting > 1) {
1978 usb_set_interface(stream->dev->udev,
1979 stream->intfnum, 0);
1981 /* UVC doesn't specify how to inform a bulk-based device
1982 * when the video stream is stopped. Windows sends a
1983 * CLEAR_FEATURE(HALT) request to the video streaming
1984 * bulk endpoint, mimic the same behaviour.
1986 unsigned int epnum = stream->header.bEndpointAddress
1987 & USB_ENDPOINT_NUMBER_MASK;
1988 unsigned int dir = stream->header.bEndpointAddress
1989 & USB_ENDPOINT_DIR_MASK;
1992 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
1993 usb_clear_halt(stream->dev->udev, pipe);
1996 uvc_video_clock_cleanup(stream);
2000 ret = uvc_video_clock_init(stream);
2004 /* Commit the streaming parameters. */
2005 ret = uvc_commit_video(stream, &stream->ctrl);
2009 ret = uvc_init_video(stream, GFP_KERNEL);
2016 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
2018 uvc_video_clock_cleanup(stream);