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 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
123 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
124 stream->intf->num_altsetting > 1) {
128 interval = (ctrl->dwFrameInterval > 100000)
129 ? ctrl->dwFrameInterval
130 : frame->dwFrameInterval[0];
132 /* Compute a bandwidth estimation by multiplying the frame
133 * size by the number of video frames per second, divide the
134 * result by the number of USB frames (or micro-frames for
135 * high-speed devices) per second and add the UVC header size
136 * (assumed to be 12 bytes long).
138 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
139 bandwidth *= 10000000 / interval + 1;
141 if (stream->dev->udev->speed == USB_SPEED_HIGH)
145 /* The bandwidth estimate is too low for many cameras. Don't use
146 * maximum packet sizes lower than 1024 bytes to try and work
147 * around the problem. According to measurements done on two
148 * different camera models, the value is high enough to get most
149 * resolutions working while not preventing two simultaneous
150 * VGA streams at 15 fps.
152 bandwidth = max_t(u32, bandwidth, 1024);
154 ctrl->dwMaxPayloadTransferSize = bandwidth;
158 static int uvc_get_video_ctrl(struct uvc_streaming *stream,
159 struct uvc_streaming_control *ctrl, int probe, __u8 query)
165 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
166 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
167 query == UVC_GET_DEF)
170 data = kmalloc(size, GFP_KERNEL);
174 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
175 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
176 size, uvc_timeout_param);
178 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
179 /* Some cameras, mostly based on Bison Electronics chipsets,
180 * answer a GET_MIN or GET_MAX request with the wCompQuality
183 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
184 "compliance - GET_MIN/MAX(PROBE) incorrectly "
185 "supported. Enabling workaround.\n");
186 memset(ctrl, 0, sizeof *ctrl);
187 ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
190 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
191 /* Many cameras don't support the GET_DEF request on their
192 * video probe control. Warn once and return, the caller will
193 * fall back to GET_CUR.
195 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
196 "compliance - GET_DEF(PROBE) not supported. "
197 "Enabling workaround.\n");
200 } else if (ret != size) {
201 uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
202 "%d (exp. %u).\n", query, probe ? "probe" : "commit",
208 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
209 ctrl->bFormatIndex = data[2];
210 ctrl->bFrameIndex = data[3];
211 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
212 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
213 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
214 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
215 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
216 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
217 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
218 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
221 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
222 ctrl->bmFramingInfo = data[30];
223 ctrl->bPreferedVersion = data[31];
224 ctrl->bMinVersion = data[32];
225 ctrl->bMaxVersion = data[33];
227 ctrl->dwClockFrequency = stream->dev->clock_frequency;
228 ctrl->bmFramingInfo = 0;
229 ctrl->bPreferedVersion = 0;
230 ctrl->bMinVersion = 0;
231 ctrl->bMaxVersion = 0;
234 /* Some broken devices return null or wrong dwMaxVideoFrameSize and
235 * dwMaxPayloadTransferSize fields. Try to get the value from the
236 * format and frame descriptors.
238 uvc_fixup_video_ctrl(stream, ctrl);
246 static int uvc_set_video_ctrl(struct uvc_streaming *stream,
247 struct uvc_streaming_control *ctrl, int probe)
253 size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
254 data = kzalloc(size, GFP_KERNEL);
258 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
259 data[2] = ctrl->bFormatIndex;
260 data[3] = ctrl->bFrameIndex;
261 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
262 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
263 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
264 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
265 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
266 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
267 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
268 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
271 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
272 data[30] = ctrl->bmFramingInfo;
273 data[31] = ctrl->bPreferedVersion;
274 data[32] = ctrl->bMinVersion;
275 data[33] = ctrl->bMaxVersion;
278 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
279 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
280 size, uvc_timeout_param);
282 uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
283 "%d (exp. %u).\n", probe ? "probe" : "commit",
292 int uvc_probe_video(struct uvc_streaming *stream,
293 struct uvc_streaming_control *probe)
295 struct uvc_streaming_control probe_min, probe_max;
300 /* Perform probing. The device should adjust the requested values
301 * according to its capabilities. However, some devices, namely the
302 * first generation UVC Logitech webcams, don't implement the Video
303 * Probe control properly, and just return the needed bandwidth. For
304 * that reason, if the needed bandwidth exceeds the maximum available
305 * bandwidth, try to lower the quality.
307 ret = uvc_set_video_ctrl(stream, probe, 1);
311 /* Get the minimum and maximum values for compression settings. */
312 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
313 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
316 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
320 probe->wCompQuality = probe_max.wCompQuality;
323 for (i = 0; i < 2; ++i) {
324 ret = uvc_set_video_ctrl(stream, probe, 1);
327 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
331 if (stream->intf->num_altsetting == 1)
334 bandwidth = probe->dwMaxPayloadTransferSize;
335 if (bandwidth <= stream->maxpsize)
338 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
343 /* TODO: negotiate compression parameters */
344 probe->wKeyFrameRate = probe_min.wKeyFrameRate;
345 probe->wPFrameRate = probe_min.wPFrameRate;
346 probe->wCompQuality = probe_max.wCompQuality;
347 probe->wCompWindowSize = probe_min.wCompWindowSize;
354 static int uvc_commit_video(struct uvc_streaming *stream,
355 struct uvc_streaming_control *probe)
357 return uvc_set_video_ctrl(stream, probe, 0);
360 /* -----------------------------------------------------------------------------
361 * Clocks and timestamps
364 static inline void uvc_video_get_ts(struct timespec *ts)
366 if (uvc_clock_param == CLOCK_MONOTONIC)
369 ktime_get_real_ts(ts);
373 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
374 const __u8 *data, int len)
376 struct uvc_clock_sample *sample;
377 unsigned int header_size;
378 bool has_pts = false;
379 bool has_scr = false;
385 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
386 case UVC_STREAM_PTS | UVC_STREAM_SCR:
404 /* Check for invalid headers. */
405 if (len < header_size)
408 /* Extract the timestamps:
410 * - store the frame PTS in the buffer structure
411 * - if the SCR field is present, retrieve the host SOF counter and
412 * kernel timestamps and store them with the SCR STC and SOF fields
415 if (has_pts && buf != NULL)
416 buf->pts = get_unaligned_le32(&data[2]);
421 /* To limit the amount of data, drop SCRs with an SOF identical to the
424 dev_sof = get_unaligned_le16(&data[header_size - 2]);
425 if (dev_sof == stream->clock.last_sof)
428 stream->clock.last_sof = dev_sof;
430 host_sof = usb_get_current_frame_number(stream->dev->udev);
431 uvc_video_get_ts(&ts);
433 /* The UVC specification allows device implementations that can't obtain
434 * the USB frame number to keep their own frame counters as long as they
435 * match the size and frequency of the frame number associated with USB
436 * SOF tokens. The SOF values sent by such devices differ from the USB
437 * SOF tokens by a fixed offset that needs to be estimated and accounted
438 * for to make timestamp recovery as accurate as possible.
440 * The offset is estimated the first time a device SOF value is received
441 * as the difference between the host and device SOF values. As the two
442 * SOF values can differ slightly due to transmission delays, consider
443 * that the offset is null if the difference is not higher than 10 ms
444 * (negative differences can not happen and are thus considered as an
445 * offset). The video commit control wDelay field should be used to
446 * compute a dynamic threshold instead of using a fixed 10 ms value, but
447 * devices don't report reliable wDelay values.
449 * See uvc_video_clock_host_sof() for an explanation regarding why only
450 * the 8 LSBs of the delta are kept.
452 if (stream->clock.sof_offset == (u16)-1) {
453 u16 delta_sof = (host_sof - dev_sof) & 255;
455 stream->clock.sof_offset = delta_sof;
457 stream->clock.sof_offset = 0;
460 dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
462 spin_lock_irqsave(&stream->clock.lock, flags);
464 sample = &stream->clock.samples[stream->clock.head];
465 sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
466 sample->dev_sof = dev_sof;
467 sample->host_sof = host_sof;
468 sample->host_ts = ts;
470 /* Update the sliding window head and count. */
471 stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
473 if (stream->clock.count < stream->clock.size)
474 stream->clock.count++;
476 spin_unlock_irqrestore(&stream->clock.lock, flags);
479 static void uvc_video_clock_reset(struct uvc_streaming *stream)
481 struct uvc_clock *clock = &stream->clock;
485 clock->last_sof = -1;
486 clock->sof_offset = -1;
489 static int uvc_video_clock_init(struct uvc_streaming *stream)
491 struct uvc_clock *clock = &stream->clock;
493 spin_lock_init(&clock->lock);
496 clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
498 if (clock->samples == NULL)
501 uvc_video_clock_reset(stream);
506 static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
508 kfree(stream->clock.samples);
509 stream->clock.samples = NULL;
513 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
515 * Host SOF counters reported by usb_get_current_frame_number() usually don't
516 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
517 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
518 * controller and its configuration.
520 * We thus need to recover the SOF value corresponding to the host frame number.
521 * As the device and host frame numbers are sampled in a short interval, the
522 * difference between their values should be equal to a small delta plus an
523 * integer multiple of 256 caused by the host frame number limited precision.
525 * To obtain the recovered host SOF value, compute the small delta by masking
526 * the high bits of the host frame counter and device SOF difference and add it
527 * to the device SOF value.
529 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
531 /* The delta value can be negative. */
534 delta_sof = (sample->host_sof - sample->dev_sof) & 255;
536 return (sample->dev_sof + delta_sof) & 2047;
540 * uvc_video_clock_update - Update the buffer timestamp
542 * This function converts the buffer PTS timestamp to the host clock domain by
543 * going through the USB SOF clock domain and stores the result in the V4L2
544 * buffer timestamp field.
546 * The relationship between the device clock and the host clock isn't known.
547 * However, the device and the host share the common USB SOF clock which can be
548 * used to recover that relationship.
550 * The relationship between the device clock and the USB SOF clock is considered
551 * to be linear over the clock samples sliding window and is given by
555 * Several methods to compute the slope (m) and intercept (p) can be used. As
556 * the clock drift should be small compared to the sliding window size, we
557 * assume that the line that goes through the points at both ends of the window
558 * is a good approximation. Naming those points P1 and P2, we get
560 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
561 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
565 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
567 * to avoid loosing precision in the division. Similarly, the host timestamp is
570 * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
572 * SOF values are coded on 11 bits by USB. We extend their precision with 16
573 * decimal bits, leading to a 11.16 coding.
575 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
576 * be normalized using the nominal device clock frequency reported through the
579 * Both the PTS/STC and SOF counters roll over, after a fixed but device
580 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
581 * sliding window size is smaller than the rollover period, differences computed
582 * on unsigned integers will produce the correct result. However, the p term in
583 * the linear relations will be miscomputed.
585 * To fix the issue, we subtract a constant from the PTS and STC values to bring
586 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
587 * the 32 bit range without any rollover.
589 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
590 * computed by (1) will never be smaller than 0. This offset is then compensated
591 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
592 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
593 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
594 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
595 * SOF value at the end of the sliding window.
597 * Finally we subtract a constant from the host timestamps to bring the first
598 * timestamp of the sliding window to 1s.
600 void uvc_video_clock_update(struct uvc_streaming *stream,
601 struct v4l2_buffer *v4l2_buf,
602 struct uvc_buffer *buf)
604 struct uvc_clock *clock = &stream->clock;
605 struct uvc_clock_sample *first;
606 struct uvc_clock_sample *last;
618 spin_lock_irqsave(&clock->lock, flags);
620 if (clock->count < clock->size)
623 first = &clock->samples[clock->head];
624 last = &clock->samples[(clock->head - 1) % clock->size];
626 /* First step, PTS to SOF conversion. */
627 delta_stc = buf->pts - (1UL << 31);
628 x1 = first->dev_stc - delta_stc;
629 x2 = last->dev_stc - delta_stc;
633 y1 = (first->dev_sof + 2048) << 16;
634 y2 = (last->dev_sof + 2048) << 16;
638 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
640 y = div_u64(y, x2 - x1);
644 uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
645 "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
646 stream->dev->name, buf->pts,
647 y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
648 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
649 x1, x2, y1, y2, clock->sof_offset);
651 /* Second step, SOF to host clock conversion. */
652 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
653 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
659 ts = timespec_sub(last->host_ts, first->host_ts);
661 y2 = (ts.tv_sec + 1) * NSEC_PER_SEC + ts.tv_nsec;
663 /* Interpolated and host SOF timestamps can wrap around at slightly
664 * different times. Handle this by adding or removing 2048 to or from
665 * the computed SOF value to keep it close to the SOF samples mean
668 mean = (x1 + x2) / 2;
669 if (mean - (1024 << 16) > sof)
671 else if (sof > mean + (1024 << 16))
674 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
676 y = div_u64(y, x2 - x1);
678 div = div_u64_rem(y, NSEC_PER_SEC, &rem);
679 ts.tv_sec = first->host_ts.tv_sec - 1 + div;
680 ts.tv_nsec = first->host_ts.tv_nsec + rem;
681 if (ts.tv_nsec >= NSEC_PER_SEC) {
683 ts.tv_nsec -= NSEC_PER_SEC;
686 uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %lu.%06lu "
687 "buf ts %lu.%06lu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
689 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
690 y, ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC,
691 v4l2_buf->timestamp.tv_sec, v4l2_buf->timestamp.tv_usec,
692 x1, first->host_sof, first->dev_sof,
693 x2, last->host_sof, last->dev_sof, y1, y2);
695 /* Update the V4L2 buffer. */
696 v4l2_buf->timestamp.tv_sec = ts.tv_sec;
697 v4l2_buf->timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
700 spin_unlock_irqrestore(&stream->clock.lock, flags);
703 /* ------------------------------------------------------------------------
707 static void uvc_video_stats_decode(struct uvc_streaming *stream,
708 const __u8 *data, int len)
710 unsigned int header_size;
711 bool has_pts = false;
712 bool has_scr = false;
713 u16 uninitialized_var(scr_sof);
714 u32 uninitialized_var(scr_stc);
715 u32 uninitialized_var(pts);
717 if (stream->stats.stream.nb_frames == 0 &&
718 stream->stats.frame.nb_packets == 0)
719 ktime_get_ts(&stream->stats.stream.start_ts);
721 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
722 case UVC_STREAM_PTS | UVC_STREAM_SCR:
740 /* Check for invalid headers. */
741 if (len < header_size || data[0] < header_size) {
742 stream->stats.frame.nb_invalid++;
746 /* Extract the timestamps. */
748 pts = get_unaligned_le32(&data[2]);
751 scr_stc = get_unaligned_le32(&data[header_size - 6]);
752 scr_sof = get_unaligned_le16(&data[header_size - 2]);
755 /* Is PTS constant through the whole frame ? */
756 if (has_pts && stream->stats.frame.nb_pts) {
757 if (stream->stats.frame.pts != pts) {
758 stream->stats.frame.nb_pts_diffs++;
759 stream->stats.frame.last_pts_diff =
760 stream->stats.frame.nb_packets;
765 stream->stats.frame.nb_pts++;
766 stream->stats.frame.pts = pts;
769 /* Do all frames have a PTS in their first non-empty packet, or before
770 * their first empty packet ?
772 if (stream->stats.frame.size == 0) {
773 if (len > header_size)
774 stream->stats.frame.has_initial_pts = has_pts;
775 if (len == header_size && has_pts)
776 stream->stats.frame.has_early_pts = true;
779 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
780 if (has_scr && stream->stats.frame.nb_scr) {
781 if (stream->stats.frame.scr_stc != scr_stc)
782 stream->stats.frame.nb_scr_diffs++;
786 /* Expand the SOF counter to 32 bits and store its value. */
787 if (stream->stats.stream.nb_frames > 0 ||
788 stream->stats.frame.nb_scr > 0)
789 stream->stats.stream.scr_sof_count +=
790 (scr_sof - stream->stats.stream.scr_sof) % 2048;
791 stream->stats.stream.scr_sof = scr_sof;
793 stream->stats.frame.nb_scr++;
794 stream->stats.frame.scr_stc = scr_stc;
795 stream->stats.frame.scr_sof = scr_sof;
797 if (scr_sof < stream->stats.stream.min_sof)
798 stream->stats.stream.min_sof = scr_sof;
799 if (scr_sof > stream->stats.stream.max_sof)
800 stream->stats.stream.max_sof = scr_sof;
803 /* Record the first non-empty packet number. */
804 if (stream->stats.frame.size == 0 && len > header_size)
805 stream->stats.frame.first_data = stream->stats.frame.nb_packets;
807 /* Update the frame size. */
808 stream->stats.frame.size += len - header_size;
810 /* Update the packets counters. */
811 stream->stats.frame.nb_packets++;
812 if (len > header_size)
813 stream->stats.frame.nb_empty++;
815 if (data[1] & UVC_STREAM_ERR)
816 stream->stats.frame.nb_errors++;
819 static void uvc_video_stats_update(struct uvc_streaming *stream)
821 struct uvc_stats_frame *frame = &stream->stats.frame;
823 uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
824 "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
825 "last pts/stc/sof %u/%u/%u\n",
826 stream->sequence, frame->first_data,
827 frame->nb_packets - frame->nb_empty, frame->nb_packets,
828 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
829 frame->has_early_pts ? "" : "!",
830 frame->has_initial_pts ? "" : "!",
831 frame->nb_scr_diffs, frame->nb_scr,
832 frame->pts, frame->scr_stc, frame->scr_sof);
834 stream->stats.stream.nb_frames++;
835 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
836 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
837 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
838 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
840 if (frame->has_early_pts)
841 stream->stats.stream.nb_pts_early++;
842 if (frame->has_initial_pts)
843 stream->stats.stream.nb_pts_initial++;
844 if (frame->last_pts_diff <= frame->first_data)
845 stream->stats.stream.nb_pts_constant++;
846 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
847 stream->stats.stream.nb_scr_count_ok++;
848 if (frame->nb_scr_diffs + 1 == frame->nb_scr)
849 stream->stats.stream.nb_scr_diffs_ok++;
851 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
854 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
857 unsigned int scr_sof_freq;
858 unsigned int duration;
862 ts.tv_sec = stream->stats.stream.stop_ts.tv_sec
863 - stream->stats.stream.start_ts.tv_sec;
864 ts.tv_nsec = stream->stats.stream.stop_ts.tv_nsec
865 - stream->stats.stream.start_ts.tv_nsec;
866 if (ts.tv_nsec < 0) {
868 ts.tv_nsec += 1000000000;
871 /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
872 * frequency this will not overflow before more than 1h.
874 duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
876 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
881 count += scnprintf(buf + count, size - count,
882 "frames: %u\npackets: %u\nempty: %u\n"
883 "errors: %u\ninvalid: %u\n",
884 stream->stats.stream.nb_frames,
885 stream->stats.stream.nb_packets,
886 stream->stats.stream.nb_empty,
887 stream->stats.stream.nb_errors,
888 stream->stats.stream.nb_invalid);
889 count += scnprintf(buf + count, size - count,
890 "pts: %u early, %u initial, %u ok\n",
891 stream->stats.stream.nb_pts_early,
892 stream->stats.stream.nb_pts_initial,
893 stream->stats.stream.nb_pts_constant);
894 count += scnprintf(buf + count, size - count,
895 "scr: %u count ok, %u diff ok\n",
896 stream->stats.stream.nb_scr_count_ok,
897 stream->stats.stream.nb_scr_diffs_ok);
898 count += scnprintf(buf + count, size - count,
899 "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
900 stream->stats.stream.min_sof,
901 stream->stats.stream.max_sof,
902 scr_sof_freq / 1000, scr_sof_freq % 1000);
907 static void uvc_video_stats_start(struct uvc_streaming *stream)
909 memset(&stream->stats, 0, sizeof(stream->stats));
910 stream->stats.stream.min_sof = 2048;
913 static void uvc_video_stats_stop(struct uvc_streaming *stream)
915 ktime_get_ts(&stream->stats.stream.stop_ts);
918 /* ------------------------------------------------------------------------
922 /* Video payload decoding is handled by uvc_video_decode_start(),
923 * uvc_video_decode_data() and uvc_video_decode_end().
925 * uvc_video_decode_start is called with URB data at the start of a bulk or
926 * isochronous payload. It processes header data and returns the header size
927 * in bytes if successful. If an error occurs, it returns a negative error
928 * code. The following error codes have special meanings.
930 * - EAGAIN informs the caller that the current video buffer should be marked
931 * as done, and that the function should be called again with the same data
932 * and a new video buffer. This is used when end of frame conditions can be
933 * reliably detected at the beginning of the next frame only.
935 * If an error other than -EAGAIN is returned, the caller will drop the current
936 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
937 * made until the next payload. -ENODATA can be used to drop the current
938 * payload if no other error code is appropriate.
940 * uvc_video_decode_data is called for every URB with URB data. It copies the
941 * data to the video buffer.
943 * uvc_video_decode_end is called with header data at the end of a bulk or
944 * isochronous payload. It performs any additional header data processing and
945 * returns 0 or a negative error code if an error occurred. As header data have
946 * already been processed by uvc_video_decode_start, this functions isn't
947 * required to perform sanity checks a second time.
949 * For isochronous transfers where a payload is always transferred in a single
950 * URB, the three functions will be called in a row.
952 * To let the decoder process header data and update its internal state even
953 * when no video buffer is available, uvc_video_decode_start must be prepared
954 * to be called with a NULL buf parameter. uvc_video_decode_data and
955 * uvc_video_decode_end will never be called with a NULL buffer.
957 static int uvc_video_decode_start(struct uvc_streaming *stream,
958 struct uvc_buffer *buf, const __u8 *data, int len)
963 * - packet must be at least 2 bytes long
964 * - bHeaderLength value must be at least 2 bytes (see above)
965 * - bHeaderLength value can't be larger than the packet size.
967 if (len < 2 || data[0] < 2 || data[0] > len) {
968 stream->stats.frame.nb_invalid++;
972 fid = data[1] & UVC_STREAM_FID;
974 /* Increase the sequence number regardless of any buffer states, so
975 * that discontinuous sequence numbers always indicate lost frames.
977 if (stream->last_fid != fid) {
979 if (stream->sequence)
980 uvc_video_stats_update(stream);
983 uvc_video_clock_decode(stream, buf, data, len);
984 uvc_video_stats_decode(stream, data, len);
986 /* Store the payload FID bit and return immediately when the buffer is
990 stream->last_fid = fid;
994 /* Mark the buffer as bad if the error bit is set. */
995 if (data[1] & UVC_STREAM_ERR) {
996 uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1001 /* Synchronize to the input stream by waiting for the FID bit to be
1002 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1003 * stream->last_fid is initialized to -1, so the first isochronous
1004 * frame will always be in sync.
1006 * If the device doesn't toggle the FID bit, invert stream->last_fid
1007 * when the EOF bit is set to force synchronisation on the next packet.
1009 if (buf->state != UVC_BUF_STATE_ACTIVE) {
1012 if (fid == stream->last_fid) {
1013 uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1015 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1016 (data[1] & UVC_STREAM_EOF))
1017 stream->last_fid ^= UVC_STREAM_FID;
1021 uvc_video_get_ts(&ts);
1023 buf->buf.v4l2_buf.sequence = stream->sequence;
1024 buf->buf.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
1025 buf->buf.v4l2_buf.timestamp.tv_usec =
1026 ts.tv_nsec / NSEC_PER_USEC;
1028 /* TODO: Handle PTS and SCR. */
1029 buf->state = UVC_BUF_STATE_ACTIVE;
1032 /* Mark the buffer as done if we're at the beginning of a new frame.
1033 * End of frame detection is better implemented by checking the EOF
1034 * bit (FID bit toggling is delayed by one frame compared to the EOF
1035 * bit), but some devices don't set the bit at end of frame (and the
1036 * last payload can be lost anyway). We thus must check if the FID has
1039 * stream->last_fid is initialized to -1, so the first isochronous
1040 * frame will never trigger an end of frame detection.
1042 * Empty buffers (bytesused == 0) don't trigger end of frame detection
1043 * as it doesn't make sense to return an empty buffer. This also
1044 * avoids detecting end of frame conditions at FID toggling if the
1045 * previous payload had the EOF bit set.
1047 if (fid != stream->last_fid && buf->bytesused != 0) {
1048 uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1050 buf->state = UVC_BUF_STATE_READY;
1055 stream->last_fid = fid;
1060 static void uvc_video_decode_data(struct uvc_streaming *stream,
1061 struct uvc_buffer *buf, const __u8 *data, int len)
1063 unsigned int maxlen, nbytes;
1069 /* Copy the video data to the buffer. */
1070 maxlen = buf->length - buf->bytesused;
1071 mem = buf->mem + buf->bytesused;
1072 nbytes = min((unsigned int)len, maxlen);
1073 memcpy(mem, data, nbytes);
1074 buf->bytesused += nbytes;
1076 /* Complete the current frame if the buffer size was exceeded. */
1078 uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1079 buf->state = UVC_BUF_STATE_READY;
1084 static void uvc_video_decode_end(struct uvc_streaming *stream,
1085 struct uvc_buffer *buf, const __u8 *data, int len)
1087 /* Mark the buffer as done if the EOF marker is set. */
1088 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1089 uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1091 uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1092 buf->state = UVC_BUF_STATE_READY;
1093 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1094 stream->last_fid ^= UVC_STREAM_FID;
1098 /* Video payload encoding is handled by uvc_video_encode_header() and
1099 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1101 * uvc_video_encode_header is called at the start of a payload. It adds header
1102 * data to the transfer buffer and returns the header size. As the only known
1103 * UVC output device transfers a whole frame in a single payload, the EOF bit
1104 * is always set in the header.
1106 * uvc_video_encode_data is called for every URB and copies the data from the
1107 * video buffer to the transfer buffer.
1109 static int uvc_video_encode_header(struct uvc_streaming *stream,
1110 struct uvc_buffer *buf, __u8 *data, int len)
1112 data[0] = 2; /* Header length */
1113 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1114 | (stream->last_fid & UVC_STREAM_FID);
1118 static int uvc_video_encode_data(struct uvc_streaming *stream,
1119 struct uvc_buffer *buf, __u8 *data, int len)
1121 struct uvc_video_queue *queue = &stream->queue;
1122 unsigned int nbytes;
1125 /* Copy video data to the URB buffer. */
1126 mem = buf->mem + queue->buf_used;
1127 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1128 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1130 memcpy(data, mem, nbytes);
1132 queue->buf_used += nbytes;
1137 /* ------------------------------------------------------------------------
1142 * Completion handler for video URBs.
1144 static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1145 struct uvc_buffer *buf)
1150 for (i = 0; i < urb->number_of_packets; ++i) {
1151 if (urb->iso_frame_desc[i].status < 0) {
1152 uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1153 "lost (%d).\n", urb->iso_frame_desc[i].status);
1154 /* Mark the buffer as faulty. */
1160 /* Decode the payload header. */
1161 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1163 ret = uvc_video_decode_start(stream, buf, mem,
1164 urb->iso_frame_desc[i].actual_length);
1166 buf = uvc_queue_next_buffer(&stream->queue,
1168 } while (ret == -EAGAIN);
1173 /* Decode the payload data. */
1174 uvc_video_decode_data(stream, buf, mem + ret,
1175 urb->iso_frame_desc[i].actual_length - ret);
1177 /* Process the header again. */
1178 uvc_video_decode_end(stream, buf, mem,
1179 urb->iso_frame_desc[i].actual_length);
1181 if (buf->state == UVC_BUF_STATE_READY) {
1182 if (buf->length != buf->bytesused &&
1183 !(stream->cur_format->flags &
1184 UVC_FMT_FLAG_COMPRESSED))
1187 buf = uvc_queue_next_buffer(&stream->queue, buf);
1192 static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1193 struct uvc_buffer *buf)
1199 * Ignore ZLPs if they're not part of a frame, otherwise process them
1200 * to trigger the end of payload detection.
1202 if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1205 mem = urb->transfer_buffer;
1206 len = urb->actual_length;
1207 stream->bulk.payload_size += len;
1209 /* If the URB is the first of its payload, decode and save the
1212 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1214 ret = uvc_video_decode_start(stream, buf, mem, len);
1216 buf = uvc_queue_next_buffer(&stream->queue,
1218 } while (ret == -EAGAIN);
1220 /* If an error occurred skip the rest of the payload. */
1221 if (ret < 0 || buf == NULL) {
1222 stream->bulk.skip_payload = 1;
1224 memcpy(stream->bulk.header, mem, ret);
1225 stream->bulk.header_size = ret;
1232 /* The buffer queue might have been cancelled while a bulk transfer
1233 * was in progress, so we can reach here with buf equal to NULL. Make
1234 * sure buf is never dereferenced if NULL.
1237 /* Process video data. */
1238 if (!stream->bulk.skip_payload && buf != NULL)
1239 uvc_video_decode_data(stream, buf, mem, len);
1241 /* Detect the payload end by a URB smaller than the maximum size (or
1242 * a payload size equal to the maximum) and process the header again.
1244 if (urb->actual_length < urb->transfer_buffer_length ||
1245 stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1246 if (!stream->bulk.skip_payload && buf != NULL) {
1247 uvc_video_decode_end(stream, buf, stream->bulk.header,
1248 stream->bulk.payload_size);
1249 if (buf->state == UVC_BUF_STATE_READY)
1250 buf = uvc_queue_next_buffer(&stream->queue,
1254 stream->bulk.header_size = 0;
1255 stream->bulk.skip_payload = 0;
1256 stream->bulk.payload_size = 0;
1260 static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1261 struct uvc_buffer *buf)
1263 u8 *mem = urb->transfer_buffer;
1264 int len = stream->urb_size, ret;
1267 urb->transfer_buffer_length = 0;
1271 /* If the URB is the first of its payload, add the header. */
1272 if (stream->bulk.header_size == 0) {
1273 ret = uvc_video_encode_header(stream, buf, mem, len);
1274 stream->bulk.header_size = ret;
1275 stream->bulk.payload_size += ret;
1280 /* Process video data. */
1281 ret = uvc_video_encode_data(stream, buf, mem, len);
1283 stream->bulk.payload_size += ret;
1286 if (buf->bytesused == stream->queue.buf_used ||
1287 stream->bulk.payload_size == stream->bulk.max_payload_size) {
1288 if (buf->bytesused == stream->queue.buf_used) {
1289 stream->queue.buf_used = 0;
1290 buf->state = UVC_BUF_STATE_READY;
1291 buf->buf.v4l2_buf.sequence = ++stream->sequence;
1292 uvc_queue_next_buffer(&stream->queue, buf);
1293 stream->last_fid ^= UVC_STREAM_FID;
1296 stream->bulk.header_size = 0;
1297 stream->bulk.payload_size = 0;
1300 urb->transfer_buffer_length = stream->urb_size - len;
1302 /* ddl@rock-chips.com : uvc_video_complete is run in_interrupt(), so uvc decode operation delay run in tasklet for
1303 * usb host reenable interrupt soon
1305 static void uvc_video_complete_fun (struct urb *urb)
1307 struct uvc_streaming *stream = urb->context;
1308 struct uvc_video_queue *queue = &stream->queue;
1309 struct uvc_buffer *buf = NULL;
1310 unsigned long flags;
1313 atomic_t *urb_state=NULL;
1315 switch (urb->status) {
1320 uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1321 "completion handler.\n", urb->status);
1323 case -ENOENT: /* usb_kill_urb() called. */
1327 case -ECONNRESET: /* usb_unlink_urb() called. */
1328 case -ESHUTDOWN: /* The endpoint is being disabled. */
1329 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1333 for (i = 0; i < UVC_URBS; ++i) {
1334 if (stream->urb[i] == urb) {
1335 urb_state = &stream->urb_state[i];
1340 if (urb_state == NULL) {
1341 printk("urb(%p) cann't be finded in stream->urb(%p, %p, %p, %p, %p)\n",
1342 urb,stream->urb[0],stream->urb[1],stream->urb[2],stream->urb[3],stream->urb[4]);
1344 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1348 if (atomic_read(urb_state)==UrbDeactive) {
1349 printk(KERN_DEBUG "urb is deactive, this urb complete cancel!");
1350 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1354 spin_lock_irqsave(&queue->irqlock, flags);
1355 if (!list_empty(&queue->irqqueue))
1356 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1358 spin_unlock_irqrestore(&queue->irqlock, flags);
1360 stream->decode(urb, stream, buf);
1362 if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1363 uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1365 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1369 static void uvc_video_complete_tasklet(unsigned long data)
1371 struct urb *urb = (struct urb*)data;
1373 uvc_video_complete_fun(urb);
1377 static void uvc_video_complete(struct urb *urb)
1380 struct uvc_streaming *stream = urb->context;
1381 struct tasklet_struct *tasklet = NULL;
1382 atomic_t *urb_state;
1384 for (i = 0; i < UVC_URBS; ++i) {
1385 if (stream->urb[i] == urb) {
1386 tasklet = stream->tasklet[i];
1387 urb_state = &stream->urb_state[i];
1392 if ((tasklet != NULL)&&(atomic_read(urb_state)==UrbActive)) {
1393 tasklet_hi_schedule(tasklet);
1395 uvc_video_complete_fun(urb);
1400 * Free transfer buffers.
1402 static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1406 for (i = 0; i < UVC_URBS; ++i) {
1407 if (stream->urb_buffer[i]) {
1408 #ifndef CONFIG_DMA_NONCOHERENT
1409 usb_free_coherent(stream->dev->udev, stream->urb_size,
1410 stream->urb_buffer[i], stream->urb_dma[i]);
1412 kfree(stream->urb_buffer[i]);
1414 stream->urb_buffer[i] = NULL;
1418 stream->urb_size = 0;
1422 * Allocate transfer buffers. This function can be called with buffers
1423 * already allocated when resuming from suspend, in which case it will
1424 * return without touching the buffers.
1426 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1427 * system is too low on memory try successively smaller numbers of packets
1428 * until allocation succeeds.
1430 * Return the number of allocated packets on success or 0 when out of memory.
1432 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1433 unsigned int size, unsigned int psize, gfp_t gfp_flags)
1435 unsigned int npackets;
1438 /* Buffers are already allocated, bail out. */
1439 if (stream->urb_size)
1440 return stream->urb_size / psize;
1442 /* Compute the number of packets. Bulk endpoints might transfer UVC
1443 * payloads across multiple URBs.
1445 npackets = DIV_ROUND_UP(size, psize);
1446 if (npackets > UVC_MAX_PACKETS)
1447 npackets = UVC_MAX_PACKETS;
1449 /* Retry allocations until one succeed. */
1450 for (; npackets > 1; npackets /= 2) {
1451 for (i = 0; i < UVC_URBS; ++i) {
1452 stream->urb_size = psize * npackets;
1453 #ifndef CONFIG_DMA_NONCOHERENT
1454 stream->urb_buffer[i] = usb_alloc_coherent(
1455 stream->dev->udev, stream->urb_size,
1456 gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1458 stream->urb_buffer[i] =
1459 kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1461 if (!stream->urb_buffer[i]) {
1462 uvc_free_urb_buffers(stream);
1467 if (i == UVC_URBS) {
1468 uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1469 "of %ux%u bytes each.\n", UVC_URBS, npackets,
1475 uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1476 "per packet).\n", psize);
1481 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1483 static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1488 uvc_video_stats_stop(stream);
1490 for (i = 0; i < UVC_URBS; ++i) {
1491 urb = stream->urb[i];
1495 atomic_set(&stream->urb_state[i],UrbDeactive);
1497 if (stream->tasklet[i]) {
1498 tasklet_kill(stream->tasklet[i]);
1499 kfree(stream->tasklet[i]);
1500 stream->tasklet[i] = NULL;
1505 stream->urb[i] = NULL;
1509 uvc_free_urb_buffers(stream);
1513 * Compute the maximum number of bytes per interval for an endpoint.
1515 static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1516 struct usb_host_endpoint *ep)
1520 switch (dev->speed) {
1521 case USB_SPEED_SUPER:
1522 return ep->ss_ep_comp.wBytesPerInterval;
1523 case USB_SPEED_HIGH:
1524 psize = usb_endpoint_maxp(&ep->desc);
1525 return (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
1527 psize = usb_endpoint_maxp(&ep->desc);
1528 return psize & 0x07ff;
1533 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1534 * is given by the endpoint.
1536 static int uvc_init_video_isoc(struct uvc_streaming *stream,
1537 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1540 unsigned int npackets, i, j;
1544 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1545 size = stream->ctrl.dwMaxVideoFrameSize;
1547 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1551 size = npackets * psize;
1553 for (i = 0; i < UVC_URBS; ++i) {
1554 urb = usb_alloc_urb(npackets, gfp_flags);
1556 uvc_uninit_video(stream, 1);
1560 urb->dev = stream->dev->udev;
1561 urb->context = stream;
1562 urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1563 ep->desc.bEndpointAddress);
1564 #ifndef CONFIG_DMA_NONCOHERENT
1565 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1566 urb->transfer_dma = stream->urb_dma[i];
1568 urb->transfer_flags = URB_ISO_ASAP;
1570 urb->interval = ep->desc.bInterval;
1571 urb->transfer_buffer = stream->urb_buffer[i];
1572 urb->complete = uvc_video_complete;
1573 urb->number_of_packets = npackets;
1574 urb->transfer_buffer_length = size;
1576 for (j = 0; j < npackets; ++j) {
1577 urb->iso_frame_desc[j].offset = j * psize;
1578 urb->iso_frame_desc[j].length = psize;
1581 stream->urb[i] = urb;
1582 /* ddl@rock-chips.com */
1583 atomic_set(&stream->urb_state[i],UrbActive);
1584 stream->tasklet[i] = kmalloc(sizeof(struct tasklet_struct), GFP_KERNEL);
1585 if (stream->tasklet[i] == NULL) {
1586 uvc_printk(KERN_ERR, "device %s requested tasklet memory fail!\n",
1589 tasklet_init(stream->tasklet[i], uvc_video_complete_tasklet, (unsigned long)urb);
1597 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1598 * given by the endpoint.
1600 static int uvc_init_video_bulk(struct uvc_streaming *stream,
1601 struct usb_host_endpoint *ep, gfp_t gfp_flags)
1604 unsigned int npackets, pipe, i;
1608 psize = usb_endpoint_maxp(&ep->desc) & 0x7ff;
1609 size = stream->ctrl.dwMaxPayloadTransferSize;
1610 stream->bulk.max_payload_size = size;
1612 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1616 size = npackets * psize;
1618 if (usb_endpoint_dir_in(&ep->desc))
1619 pipe = usb_rcvbulkpipe(stream->dev->udev,
1620 ep->desc.bEndpointAddress);
1622 pipe = usb_sndbulkpipe(stream->dev->udev,
1623 ep->desc.bEndpointAddress);
1625 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1628 for (i = 0; i < UVC_URBS; ++i) {
1629 urb = usb_alloc_urb(0, gfp_flags);
1631 uvc_uninit_video(stream, 1);
1635 usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1636 stream->urb_buffer[i], size, uvc_video_complete,
1638 #ifndef CONFIG_DMA_NONCOHERENT
1639 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1640 urb->transfer_dma = stream->urb_dma[i];
1643 stream->urb[i] = urb;
1645 /* ddl@rock-chips.com */
1646 stream->tasklet[i] = kmalloc(sizeof(struct tasklet_struct), GFP_KERNEL);
1647 if (stream->tasklet[i] == NULL) {
1648 uvc_printk(KERN_ERR, "device %s requested tasklet memory fail!\n",
1651 tasklet_init(stream->tasklet[i], uvc_video_complete_tasklet, (unsigned long)urb);
1659 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1661 static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1663 struct usb_interface *intf = stream->intf;
1664 struct usb_host_endpoint *ep;
1668 stream->sequence = -1;
1669 stream->last_fid = -1;
1670 stream->bulk.header_size = 0;
1671 stream->bulk.skip_payload = 0;
1672 stream->bulk.payload_size = 0;
1674 uvc_video_stats_start(stream);
1676 if (intf->num_altsetting > 1) {
1677 struct usb_host_endpoint *best_ep = NULL;
1678 unsigned int best_psize = UINT_MAX;
1679 unsigned int bandwidth;
1680 unsigned int uninitialized_var(altsetting);
1681 int intfnum = stream->intfnum;
1683 /* Isochronous endpoint, select the alternate setting. */
1684 bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1686 if (bandwidth == 0) {
1687 uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1688 "bandwidth, defaulting to lowest.\n");
1691 uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1692 "B/frame bandwidth.\n", bandwidth);
1695 for (i = 0; i < intf->num_altsetting; ++i) {
1696 struct usb_host_interface *alts;
1699 alts = &intf->altsetting[i];
1700 ep = uvc_find_endpoint(alts,
1701 stream->header.bEndpointAddress);
1705 /* Check if the bandwidth is high enough. */
1706 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1707 if (psize >= bandwidth && psize <= best_psize) {
1708 altsetting = alts->desc.bAlternateSetting;
1714 if (best_ep == NULL) {
1715 uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1716 "for requested bandwidth.\n");
1720 uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1721 "(%u B/frame bandwidth).\n", altsetting, best_psize);
1723 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1727 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1729 /* Bulk endpoint, proceed to URB initialization. */
1730 ep = uvc_find_endpoint(&intf->altsetting[0],
1731 stream->header.bEndpointAddress);
1735 ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1741 /* Submit the URBs. */
1742 for (i = 0; i < UVC_URBS; ++i) {
1743 ret = usb_submit_urb(stream->urb[i], gfp_flags);
1745 uvc_printk(KERN_ERR, "Failed to submit URB %u "
1747 uvc_uninit_video(stream, 1);
1755 /* --------------------------------------------------------------------------
1760 * Stop streaming without disabling the video queue.
1762 * To let userspace applications resume without trouble, we must not touch the
1763 * video buffers in any way. We mark the device as frozen to make sure the URB
1764 * completion handler won't try to cancel the queue when we kill the URBs.
1766 int uvc_video_suspend(struct uvc_streaming *stream)
1768 if (!uvc_queue_streaming(&stream->queue))
1772 uvc_uninit_video(stream, 0);
1773 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1778 * Reconfigure the video interface and restart streaming if it was enabled
1781 * If an error occurs, disable the video queue. This will wake all pending
1782 * buffers, making sure userspace applications are notified of the problem
1783 * instead of waiting forever.
1785 int uvc_video_resume(struct uvc_streaming *stream, int reset)
1789 /* If the bus has been reset on resume, set the alternate setting to 0.
1790 * This should be the default value, but some devices crash or otherwise
1791 * misbehave if they don't receive a SET_INTERFACE request before any
1792 * other video control request.
1795 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1799 uvc_video_clock_reset(stream);
1801 ret = uvc_commit_video(stream, &stream->ctrl);
1803 uvc_queue_enable(&stream->queue, 0);
1807 if (!uvc_queue_streaming(&stream->queue))
1810 ret = uvc_init_video(stream, GFP_NOIO);
1812 uvc_queue_enable(&stream->queue, 0);
1817 /* ------------------------------------------------------------------------
1822 * Initialize the UVC video device by switching to alternate setting 0 and
1823 * retrieve the default format.
1825 * Some cameras (namely the Fuji Finepix) set the format and frame
1826 * indexes to zero. The UVC standard doesn't clearly make this a spec
1827 * violation, so try to silently fix the values if possible.
1829 * This function is called before registering the device with V4L.
1831 int uvc_video_init(struct uvc_streaming *stream)
1833 struct uvc_streaming_control *probe = &stream->ctrl;
1834 struct uvc_format *format = NULL;
1835 struct uvc_frame *frame = NULL;
1839 if (stream->nformats == 0) {
1840 uvc_printk(KERN_INFO, "No supported video formats found.\n");
1844 atomic_set(&stream->active, 0);
1846 /* Initialize the video buffers queue. */
1847 ret = uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1851 /* Alternate setting 0 should be the default, yet the XBox Live Vision
1852 * Cam (and possibly other devices) crash or otherwise misbehave if
1853 * they don't receive a SET_INTERFACE request before any other video
1856 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1858 /* Set the streaming probe control with default streaming parameters
1859 * retrieved from the device. Webcams that don't suport GET_DEF
1860 * requests on the probe control will just keep their current streaming
1863 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1864 uvc_set_video_ctrl(stream, probe, 1);
1866 /* Initialize the streaming parameters with the probe control current
1867 * value. This makes sure SET_CUR requests on the streaming commit
1868 * control will always use values retrieved from a successful GET_CUR
1869 * request on the probe control, as required by the UVC specification.
1871 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1875 /* Check if the default format descriptor exists. Use the first
1876 * available format otherwise.
1878 for (i = stream->nformats; i > 0; --i) {
1879 format = &stream->format[i-1];
1880 if (format->index == probe->bFormatIndex)
1884 if (format->nframes == 0) {
1885 uvc_printk(KERN_INFO, "No frame descriptor found for the "
1886 "default format.\n");
1890 /* Zero bFrameIndex might be correct. Stream-based formats (including
1891 * MPEG-2 TS and DV) do not support frames but have a dummy frame
1892 * descriptor with bFrameIndex set to zero. If the default frame
1893 * descriptor is not found, use the first available frame.
1895 for (i = format->nframes; i > 0; --i) {
1896 frame = &format->frame[i-1];
1897 if (frame->bFrameIndex == probe->bFrameIndex)
1901 probe->bFormatIndex = format->index;
1902 probe->bFrameIndex = frame->bFrameIndex;
1904 stream->def_format = format;
1905 stream->cur_format = format;
1906 stream->cur_frame = frame;
1908 /* Select the video decoding function */
1909 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1910 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1911 stream->decode = uvc_video_decode_isight;
1912 else if (stream->intf->num_altsetting > 1)
1913 stream->decode = uvc_video_decode_isoc;
1915 stream->decode = uvc_video_decode_bulk;
1917 if (stream->intf->num_altsetting == 1)
1918 stream->decode = uvc_video_encode_bulk;
1920 uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1921 "supported for video output devices.\n");
1930 * Enable or disable the video stream.
1932 int uvc_video_enable(struct uvc_streaming *stream, int enable)
1937 uvc_uninit_video(stream, 1);
1938 if (stream->intf->num_altsetting > 1) {
1939 usb_set_interface(stream->dev->udev,
1940 stream->intfnum, 0);
1942 /* UVC doesn't specify how to inform a bulk-based device
1943 * when the video stream is stopped. Windows sends a
1944 * CLEAR_FEATURE(HALT) request to the video streaming
1945 * bulk endpoint, mimic the same behaviour.
1947 unsigned int epnum = stream->header.bEndpointAddress
1948 & USB_ENDPOINT_NUMBER_MASK;
1949 unsigned int dir = stream->header.bEndpointAddress
1950 & USB_ENDPOINT_DIR_MASK;
1953 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
1954 usb_clear_halt(stream->dev->udev, pipe);
1957 uvc_queue_enable(&stream->queue, 0);
1958 uvc_video_clock_cleanup(stream);
1962 ret = uvc_video_clock_init(stream);
1966 ret = uvc_queue_enable(&stream->queue, 1);
1970 /* Commit the streaming parameters. */
1971 ret = uvc_commit_video(stream, &stream->ctrl);
1975 ret = uvc_init_video(stream, GFP_KERNEL);
1982 usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1984 uvc_queue_enable(&stream->queue, 0);
1986 uvc_video_clock_cleanup(stream);