uvc_video.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. /*
  2. * uvc_video.c -- USB Video Class driver - Video handling
  3. *
  4. * Copyright (C) 2005-2010
  5. * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
  6. *
  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.
  11. *
  12. */
  13. #include <linux/kernel.h>
  14. #include <linux/list.h>
  15. #include <linux/module.h>
  16. #include <linux/slab.h>
  17. #include <linux/usb.h>
  18. #include <linux/videodev2.h>
  19. #include <linux/vmalloc.h>
  20. #include <linux/wait.h>
  21. #include <linux/atomic.h>
  22. #include <asm/unaligned.h>
  23. #include <media/v4l2-common.h>
  24. #include "uvcvideo.h"
  25. /* ------------------------------------------------------------------------
  26. * UVC Controls
  27. */
  28. static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
  29. __u8 intfnum, __u8 cs, void *data, __u16 size,
  30. int timeout)
  31. {
  32. __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
  33. unsigned int pipe;
  34. pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
  35. : usb_sndctrlpipe(dev->udev, 0);
  36. type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
  37. return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
  38. unit << 8 | intfnum, data, size, timeout);
  39. }
  40. static const char *uvc_query_name(__u8 query)
  41. {
  42. switch (query) {
  43. case UVC_SET_CUR:
  44. return "SET_CUR";
  45. case UVC_GET_CUR:
  46. return "GET_CUR";
  47. case UVC_GET_MIN:
  48. return "GET_MIN";
  49. case UVC_GET_MAX:
  50. return "GET_MAX";
  51. case UVC_GET_RES:
  52. return "GET_RES";
  53. case UVC_GET_LEN:
  54. return "GET_LEN";
  55. case UVC_GET_INFO:
  56. return "GET_INFO";
  57. case UVC_GET_DEF:
  58. return "GET_DEF";
  59. default:
  60. return "<invalid>";
  61. }
  62. }
  63. int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
  64. __u8 intfnum, __u8 cs, void *data, __u16 size)
  65. {
  66. int ret;
  67. ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
  68. UVC_CTRL_CONTROL_TIMEOUT);
  69. if (ret != size) {
  70. uvc_printk(KERN_ERR, "Failed to query (%s) UVC control %u on "
  71. "unit %u: %d (exp. %u).\n", uvc_query_name(query), cs,
  72. unit, ret, size);
  73. return -EIO;
  74. }
  75. return 0;
  76. }
  77. static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
  78. struct uvc_streaming_control *ctrl)
  79. {
  80. struct uvc_format *format = NULL;
  81. struct uvc_frame *frame = NULL;
  82. unsigned int i;
  83. for (i = 0; i < stream->nformats; ++i) {
  84. if (stream->format[i].index == ctrl->bFormatIndex) {
  85. format = &stream->format[i];
  86. break;
  87. }
  88. }
  89. if (format == NULL)
  90. return;
  91. for (i = 0; i < format->nframes; ++i) {
  92. if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
  93. frame = &format->frame[i];
  94. break;
  95. }
  96. }
  97. if (frame == NULL)
  98. return;
  99. if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
  100. (ctrl->dwMaxVideoFrameSize == 0 &&
  101. stream->dev->uvc_version < 0x0110))
  102. ctrl->dwMaxVideoFrameSize =
  103. frame->dwMaxVideoFrameBufferSize;
  104. if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
  105. stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
  106. stream->intf->num_altsetting > 1) {
  107. u32 interval;
  108. u32 bandwidth;
  109. interval = (ctrl->dwFrameInterval > 100000)
  110. ? ctrl->dwFrameInterval
  111. : frame->dwFrameInterval[0];
  112. /* Compute a bandwidth estimation by multiplying the frame
  113. * size by the number of video frames per second, divide the
  114. * result by the number of USB frames (or micro-frames for
  115. * high-speed devices) per second and add the UVC header size
  116. * (assumed to be 12 bytes long).
  117. */
  118. bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
  119. bandwidth *= 10000000 / interval + 1;
  120. bandwidth /= 1000;
  121. if (stream->dev->udev->speed == USB_SPEED_HIGH)
  122. bandwidth /= 8;
  123. bandwidth += 12;
  124. /* The bandwidth estimate is too low for many cameras. Don't use
  125. * maximum packet sizes lower than 1024 bytes to try and work
  126. * around the problem. According to measurements done on two
  127. * different camera models, the value is high enough to get most
  128. * resolutions working while not preventing two simultaneous
  129. * VGA streams at 15 fps.
  130. */
  131. bandwidth = max_t(u32, bandwidth, 1024);
  132. ctrl->dwMaxPayloadTransferSize = bandwidth;
  133. }
  134. }
  135. static int uvc_get_video_ctrl(struct uvc_streaming *stream,
  136. struct uvc_streaming_control *ctrl, int probe, __u8 query)
  137. {
  138. __u8 *data;
  139. __u16 size;
  140. int ret;
  141. size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
  142. if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
  143. query == UVC_GET_DEF)
  144. return -EIO;
  145. data = kmalloc(size, GFP_KERNEL);
  146. if (data == NULL)
  147. return -ENOMEM;
  148. ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
  149. probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
  150. size, uvc_timeout_param);
  151. if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
  152. /* Some cameras, mostly based on Bison Electronics chipsets,
  153. * answer a GET_MIN or GET_MAX request with the wCompQuality
  154. * field only.
  155. */
  156. uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
  157. "compliance - GET_MIN/MAX(PROBE) incorrectly "
  158. "supported. Enabling workaround.\n");
  159. memset(ctrl, 0, sizeof *ctrl);
  160. ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
  161. ret = 0;
  162. goto out;
  163. } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
  164. /* Many cameras don't support the GET_DEF request on their
  165. * video probe control. Warn once and return, the caller will
  166. * fall back to GET_CUR.
  167. */
  168. uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
  169. "compliance - GET_DEF(PROBE) not supported. "
  170. "Enabling workaround.\n");
  171. ret = -EIO;
  172. goto out;
  173. } else if (ret != size) {
  174. uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
  175. "%d (exp. %u).\n", query, probe ? "probe" : "commit",
  176. ret, size);
  177. ret = -EIO;
  178. goto out;
  179. }
  180. ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
  181. ctrl->bFormatIndex = data[2];
  182. ctrl->bFrameIndex = data[3];
  183. ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
  184. ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
  185. ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
  186. ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
  187. ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
  188. ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
  189. ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
  190. ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
  191. if (size == 34) {
  192. ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
  193. ctrl->bmFramingInfo = data[30];
  194. ctrl->bPreferedVersion = data[31];
  195. ctrl->bMinVersion = data[32];
  196. ctrl->bMaxVersion = data[33];
  197. } else {
  198. ctrl->dwClockFrequency = stream->dev->clock_frequency;
  199. ctrl->bmFramingInfo = 0;
  200. ctrl->bPreferedVersion = 0;
  201. ctrl->bMinVersion = 0;
  202. ctrl->bMaxVersion = 0;
  203. }
  204. /* Some broken devices return null or wrong dwMaxVideoFrameSize and
  205. * dwMaxPayloadTransferSize fields. Try to get the value from the
  206. * format and frame descriptors.
  207. */
  208. uvc_fixup_video_ctrl(stream, ctrl);
  209. ret = 0;
  210. out:
  211. kfree(data);
  212. return ret;
  213. }
  214. static int uvc_set_video_ctrl(struct uvc_streaming *stream,
  215. struct uvc_streaming_control *ctrl, int probe)
  216. {
  217. __u8 *data;
  218. __u16 size;
  219. int ret;
  220. size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
  221. data = kzalloc(size, GFP_KERNEL);
  222. if (data == NULL)
  223. return -ENOMEM;
  224. *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
  225. data[2] = ctrl->bFormatIndex;
  226. data[3] = ctrl->bFrameIndex;
  227. *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
  228. *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
  229. *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
  230. *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
  231. *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
  232. *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
  233. put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
  234. put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
  235. if (size == 34) {
  236. put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
  237. data[30] = ctrl->bmFramingInfo;
  238. data[31] = ctrl->bPreferedVersion;
  239. data[32] = ctrl->bMinVersion;
  240. data[33] = ctrl->bMaxVersion;
  241. }
  242. ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
  243. probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
  244. size, uvc_timeout_param);
  245. if (ret != size) {
  246. uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
  247. "%d (exp. %u).\n", probe ? "probe" : "commit",
  248. ret, size);
  249. ret = -EIO;
  250. }
  251. kfree(data);
  252. return ret;
  253. }
  254. int uvc_probe_video(struct uvc_streaming *stream,
  255. struct uvc_streaming_control *probe)
  256. {
  257. struct uvc_streaming_control probe_min, probe_max;
  258. __u16 bandwidth;
  259. unsigned int i;
  260. int ret;
  261. /* Perform probing. The device should adjust the requested values
  262. * according to its capabilities. However, some devices, namely the
  263. * first generation UVC Logitech webcams, don't implement the Video
  264. * Probe control properly, and just return the needed bandwidth. For
  265. * that reason, if the needed bandwidth exceeds the maximum available
  266. * bandwidth, try to lower the quality.
  267. */
  268. ret = uvc_set_video_ctrl(stream, probe, 1);
  269. if (ret < 0)
  270. goto done;
  271. /* Get the minimum and maximum values for compression settings. */
  272. if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
  273. ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
  274. if (ret < 0)
  275. goto done;
  276. ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
  277. if (ret < 0)
  278. goto done;
  279. probe->wCompQuality = probe_max.wCompQuality;
  280. }
  281. for (i = 0; i < 2; ++i) {
  282. ret = uvc_set_video_ctrl(stream, probe, 1);
  283. if (ret < 0)
  284. goto done;
  285. ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
  286. if (ret < 0)
  287. goto done;
  288. if (stream->intf->num_altsetting == 1)
  289. break;
  290. bandwidth = probe->dwMaxPayloadTransferSize;
  291. if (bandwidth <= stream->maxpsize)
  292. break;
  293. if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
  294. ret = -ENOSPC;
  295. goto done;
  296. }
  297. /* TODO: negotiate compression parameters */
  298. probe->wKeyFrameRate = probe_min.wKeyFrameRate;
  299. probe->wPFrameRate = probe_min.wPFrameRate;
  300. probe->wCompQuality = probe_max.wCompQuality;
  301. probe->wCompWindowSize = probe_min.wCompWindowSize;
  302. }
  303. done:
  304. return ret;
  305. }
  306. static int uvc_commit_video(struct uvc_streaming *stream,
  307. struct uvc_streaming_control *probe)
  308. {
  309. return uvc_set_video_ctrl(stream, probe, 0);
  310. }
  311. /* -----------------------------------------------------------------------------
  312. * Clocks and timestamps
  313. */
  314. static void
  315. uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
  316. const __u8 *data, int len)
  317. {
  318. struct uvc_clock_sample *sample;
  319. unsigned int header_size;
  320. bool has_pts = false;
  321. bool has_scr = false;
  322. unsigned long flags;
  323. struct timespec ts;
  324. u16 host_sof;
  325. u16 dev_sof;
  326. switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
  327. case UVC_STREAM_PTS | UVC_STREAM_SCR:
  328. header_size = 12;
  329. has_pts = true;
  330. has_scr = true;
  331. break;
  332. case UVC_STREAM_PTS:
  333. header_size = 6;
  334. has_pts = true;
  335. break;
  336. case UVC_STREAM_SCR:
  337. header_size = 8;
  338. has_scr = true;
  339. break;
  340. default:
  341. header_size = 2;
  342. break;
  343. }
  344. /* Check for invalid headers. */
  345. if (len < header_size)
  346. return;
  347. /* Extract the timestamps:
  348. *
  349. * - store the frame PTS in the buffer structure
  350. * - if the SCR field is present, retrieve the host SOF counter and
  351. * kernel timestamps and store them with the SCR STC and SOF fields
  352. * in the ring buffer
  353. */
  354. if (has_pts && buf != NULL)
  355. buf->pts = get_unaligned_le32(&data[2]);
  356. if (!has_scr)
  357. return;
  358. /* To limit the amount of data, drop SCRs with an SOF identical to the
  359. * previous one.
  360. */
  361. dev_sof = get_unaligned_le16(&data[header_size - 2]);
  362. if (dev_sof == stream->clock.last_sof)
  363. return;
  364. stream->clock.last_sof = dev_sof;
  365. host_sof = usb_get_current_frame_number(stream->dev->udev);
  366. ktime_get_ts(&ts);
  367. /* The UVC specification allows device implementations that can't obtain
  368. * the USB frame number to keep their own frame counters as long as they
  369. * match the size and frequency of the frame number associated with USB
  370. * SOF tokens. The SOF values sent by such devices differ from the USB
  371. * SOF tokens by a fixed offset that needs to be estimated and accounted
  372. * for to make timestamp recovery as accurate as possible.
  373. *
  374. * The offset is estimated the first time a device SOF value is received
  375. * as the difference between the host and device SOF values. As the two
  376. * SOF values can differ slightly due to transmission delays, consider
  377. * that the offset is null if the difference is not higher than 10 ms
  378. * (negative differences can not happen and are thus considered as an
  379. * offset). The video commit control wDelay field should be used to
  380. * compute a dynamic threshold instead of using a fixed 10 ms value, but
  381. * devices don't report reliable wDelay values.
  382. *
  383. * See uvc_video_clock_host_sof() for an explanation regarding why only
  384. * the 8 LSBs of the delta are kept.
  385. */
  386. if (stream->clock.sof_offset == (u16)-1) {
  387. u16 delta_sof = (host_sof - dev_sof) & 255;
  388. if (delta_sof >= 10)
  389. stream->clock.sof_offset = delta_sof;
  390. else
  391. stream->clock.sof_offset = 0;
  392. }
  393. dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
  394. spin_lock_irqsave(&stream->clock.lock, flags);
  395. sample = &stream->clock.samples[stream->clock.head];
  396. sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
  397. sample->dev_sof = dev_sof;
  398. sample->host_sof = host_sof;
  399. sample->host_ts = ts;
  400. /* Update the sliding window head and count. */
  401. stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
  402. if (stream->clock.count < stream->clock.size)
  403. stream->clock.count++;
  404. spin_unlock_irqrestore(&stream->clock.lock, flags);
  405. }
  406. static int uvc_video_clock_init(struct uvc_streaming *stream)
  407. {
  408. struct uvc_clock *clock = &stream->clock;
  409. spin_lock_init(&clock->lock);
  410. clock->head = 0;
  411. clock->count = 0;
  412. clock->size = 32;
  413. clock->last_sof = -1;
  414. clock->sof_offset = -1;
  415. clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
  416. GFP_KERNEL);
  417. if (clock->samples == NULL)
  418. return -ENOMEM;
  419. return 0;
  420. }
  421. static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
  422. {
  423. kfree(stream->clock.samples);
  424. stream->clock.samples = NULL;
  425. }
  426. /*
  427. * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
  428. *
  429. * Host SOF counters reported by usb_get_current_frame_number() usually don't
  430. * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
  431. * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
  432. * controller and its configuration.
  433. *
  434. * We thus need to recover the SOF value corresponding to the host frame number.
  435. * As the device and host frame numbers are sampled in a short interval, the
  436. * difference between their values should be equal to a small delta plus an
  437. * integer multiple of 256 caused by the host frame number limited precision.
  438. *
  439. * To obtain the recovered host SOF value, compute the small delta by masking
  440. * the high bits of the host frame counter and device SOF difference and add it
  441. * to the device SOF value.
  442. */
  443. static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
  444. {
  445. /* The delta value can be negative. */
  446. s8 delta_sof;
  447. delta_sof = (sample->host_sof - sample->dev_sof) & 255;
  448. return (sample->dev_sof + delta_sof) & 2047;
  449. }
  450. /*
  451. * uvc_video_clock_update - Update the buffer timestamp
  452. *
  453. * This function converts the buffer PTS timestamp to the host clock domain by
  454. * going through the USB SOF clock domain and stores the result in the V4L2
  455. * buffer timestamp field.
  456. *
  457. * The relationship between the device clock and the host clock isn't known.
  458. * However, the device and the host share the common USB SOF clock which can be
  459. * used to recover that relationship.
  460. *
  461. * The relationship between the device clock and the USB SOF clock is considered
  462. * to be linear over the clock samples sliding window and is given by
  463. *
  464. * SOF = m * PTS + p
  465. *
  466. * Several methods to compute the slope (m) and intercept (p) can be used. As
  467. * the clock drift should be small compared to the sliding window size, we
  468. * assume that the line that goes through the points at both ends of the window
  469. * is a good approximation. Naming those points P1 and P2, we get
  470. *
  471. * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
  472. * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
  473. *
  474. * or
  475. *
  476. * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
  477. *
  478. * to avoid loosing precision in the division. Similarly, the host timestamp is
  479. * computed with
  480. *
  481. * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
  482. *
  483. * SOF values are coded on 11 bits by USB. We extend their precision with 16
  484. * decimal bits, leading to a 11.16 coding.
  485. *
  486. * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
  487. * be normalized using the nominal device clock frequency reported through the
  488. * UVC descriptors.
  489. *
  490. * Both the PTS/STC and SOF counters roll over, after a fixed but device
  491. * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
  492. * sliding window size is smaller than the rollover period, differences computed
  493. * on unsigned integers will produce the correct result. However, the p term in
  494. * the linear relations will be miscomputed.
  495. *
  496. * To fix the issue, we subtract a constant from the PTS and STC values to bring
  497. * PTS to half the 32 bit STC range. The sliding window STC values then fit into
  498. * the 32 bit range without any rollover.
  499. *
  500. * Similarly, we add 2048 to the device SOF values to make sure that the SOF
  501. * computed by (1) will never be smaller than 0. This offset is then compensated
  502. * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
  503. * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
  504. * lower than 4096, and the host SOF counters can have rolled over to 2048. This
  505. * case is handled by subtracting 2048 from the SOF value if it exceeds the host
  506. * SOF value at the end of the sliding window.
  507. *
  508. * Finally we subtract a constant from the host timestamps to bring the first
  509. * timestamp of the sliding window to 1s.
  510. */
  511. void uvc_video_clock_update(struct uvc_streaming *stream,
  512. struct v4l2_buffer *v4l2_buf,
  513. struct uvc_buffer *buf)
  514. {
  515. struct uvc_clock *clock = &stream->clock;
  516. struct uvc_clock_sample *first;
  517. struct uvc_clock_sample *last;
  518. unsigned long flags;
  519. struct timespec ts;
  520. u32 delta_stc;
  521. u32 y1, y2;
  522. u32 x1, x2;
  523. u32 mean;
  524. u32 sof;
  525. u32 div;
  526. u32 rem;
  527. u64 y;
  528. spin_lock_irqsave(&clock->lock, flags);
  529. if (clock->count < clock->size)
  530. goto done;
  531. first = &clock->samples[clock->head];
  532. last = &clock->samples[(clock->head - 1) % clock->size];
  533. /* First step, PTS to SOF conversion. */
  534. delta_stc = buf->pts - (1UL << 31);
  535. x1 = first->dev_stc - delta_stc;
  536. x2 = last->dev_stc - delta_stc;
  537. if (x1 == x2)
  538. goto done;
  539. y1 = (first->dev_sof + 2048) << 16;
  540. y2 = (last->dev_sof + 2048) << 16;
  541. if (y2 < y1)
  542. y2 += 2048 << 16;
  543. y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
  544. - (u64)y2 * (u64)x1;
  545. y = div_u64(y, x2 - x1);
  546. sof = y;
  547. uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
  548. "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
  549. stream->dev->name, buf->pts,
  550. y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
  551. sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
  552. x1, x2, y1, y2, clock->sof_offset);
  553. /* Second step, SOF to host clock conversion. */
  554. x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
  555. x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
  556. if (x2 < x1)
  557. x2 += 2048 << 16;
  558. if (x1 == x2)
  559. goto done;
  560. ts = timespec_sub(last->host_ts, first->host_ts);
  561. y1 = NSEC_PER_SEC;
  562. y2 = (ts.tv_sec + 1) * NSEC_PER_SEC + ts.tv_nsec;
  563. /* Interpolated and host SOF timestamps can wrap around at slightly
  564. * different times. Handle this by adding or removing 2048 to or from
  565. * the computed SOF value to keep it close to the SOF samples mean
  566. * value.
  567. */
  568. mean = (x1 + x2) / 2;
  569. if (mean - (1024 << 16) > sof)
  570. sof += 2048 << 16;
  571. else if (sof > mean + (1024 << 16))
  572. sof -= 2048 << 16;
  573. y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
  574. - (u64)y2 * (u64)x1;
  575. y = div_u64(y, x2 - x1);
  576. div = div_u64_rem(y, NSEC_PER_SEC, &rem);
  577. ts.tv_sec = first->host_ts.tv_sec - 1 + div;
  578. ts.tv_nsec = first->host_ts.tv_nsec + rem;
  579. if (ts.tv_nsec >= NSEC_PER_SEC) {
  580. ts.tv_sec++;
  581. ts.tv_nsec -= NSEC_PER_SEC;
  582. }
  583. uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %lu.%06lu "
  584. "buf ts %lu.%06lu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
  585. stream->dev->name,
  586. sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
  587. y, ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC,
  588. v4l2_buf->timestamp.tv_sec, v4l2_buf->timestamp.tv_usec,
  589. x1, first->host_sof, first->dev_sof,
  590. x2, last->host_sof, last->dev_sof, y1, y2);
  591. /* Update the V4L2 buffer. */
  592. v4l2_buf->timestamp.tv_sec = ts.tv_sec;
  593. v4l2_buf->timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
  594. done:
  595. spin_unlock_irqrestore(&stream->clock.lock, flags);
  596. }
  597. /* ------------------------------------------------------------------------
  598. * Stream statistics
  599. */
  600. static void uvc_video_stats_decode(struct uvc_streaming *stream,
  601. const __u8 *data, int len)
  602. {
  603. unsigned int header_size;
  604. bool has_pts = false;
  605. bool has_scr = false;
  606. u16 uninitialized_var(scr_sof);
  607. u32 uninitialized_var(scr_stc);
  608. u32 uninitialized_var(pts);
  609. if (stream->stats.stream.nb_frames == 0 &&
  610. stream->stats.frame.nb_packets == 0)
  611. ktime_get_ts(&stream->stats.stream.start_ts);
  612. switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
  613. case UVC_STREAM_PTS | UVC_STREAM_SCR:
  614. header_size = 12;
  615. has_pts = true;
  616. has_scr = true;
  617. break;
  618. case UVC_STREAM_PTS:
  619. header_size = 6;
  620. has_pts = true;
  621. break;
  622. case UVC_STREAM_SCR:
  623. header_size = 8;
  624. has_scr = true;
  625. break;
  626. default:
  627. header_size = 2;
  628. break;
  629. }
  630. /* Check for invalid headers. */
  631. if (len < header_size || data[0] < header_size) {
  632. stream->stats.frame.nb_invalid++;
  633. return;
  634. }
  635. /* Extract the timestamps. */
  636. if (has_pts)
  637. pts = get_unaligned_le32(&data[2]);
  638. if (has_scr) {
  639. scr_stc = get_unaligned_le32(&data[header_size - 6]);
  640. scr_sof = get_unaligned_le16(&data[header_size - 2]);
  641. }
  642. /* Is PTS constant through the whole frame ? */
  643. if (has_pts && stream->stats.frame.nb_pts) {
  644. if (stream->stats.frame.pts != pts) {
  645. stream->stats.frame.nb_pts_diffs++;
  646. stream->stats.frame.last_pts_diff =
  647. stream->stats.frame.nb_packets;
  648. }
  649. }
  650. if (has_pts) {
  651. stream->stats.frame.nb_pts++;
  652. stream->stats.frame.pts = pts;
  653. }
  654. /* Do all frames have a PTS in their first non-empty packet, or before
  655. * their first empty packet ?
  656. */
  657. if (stream->stats.frame.size == 0) {
  658. if (len > header_size)
  659. stream->stats.frame.has_initial_pts = has_pts;
  660. if (len == header_size && has_pts)
  661. stream->stats.frame.has_early_pts = true;
  662. }
  663. /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
  664. if (has_scr && stream->stats.frame.nb_scr) {
  665. if (stream->stats.frame.scr_stc != scr_stc)
  666. stream->stats.frame.nb_scr_diffs++;
  667. }
  668. if (has_scr) {
  669. /* Expand the SOF counter to 32 bits and store its value. */
  670. if (stream->stats.stream.nb_frames > 0 ||
  671. stream->stats.frame.nb_scr > 0)
  672. stream->stats.stream.scr_sof_count +=
  673. (scr_sof - stream->stats.stream.scr_sof) % 2048;
  674. stream->stats.stream.scr_sof = scr_sof;
  675. stream->stats.frame.nb_scr++;
  676. stream->stats.frame.scr_stc = scr_stc;
  677. stream->stats.frame.scr_sof = scr_sof;
  678. if (scr_sof < stream->stats.stream.min_sof)
  679. stream->stats.stream.min_sof = scr_sof;
  680. if (scr_sof > stream->stats.stream.max_sof)
  681. stream->stats.stream.max_sof = scr_sof;
  682. }
  683. /* Record the first non-empty packet number. */
  684. if (stream->stats.frame.size == 0 && len > header_size)
  685. stream->stats.frame.first_data = stream->stats.frame.nb_packets;
  686. /* Update the frame size. */
  687. stream->stats.frame.size += len - header_size;
  688. /* Update the packets counters. */
  689. stream->stats.frame.nb_packets++;
  690. if (len > header_size)
  691. stream->stats.frame.nb_empty++;
  692. if (data[1] & UVC_STREAM_ERR)
  693. stream->stats.frame.nb_errors++;
  694. }
  695. static void uvc_video_stats_update(struct uvc_streaming *stream)
  696. {
  697. struct uvc_stats_frame *frame = &stream->stats.frame;
  698. uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
  699. "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
  700. "last pts/stc/sof %u/%u/%u\n",
  701. stream->sequence, frame->first_data,
  702. frame->nb_packets - frame->nb_empty, frame->nb_packets,
  703. frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
  704. frame->has_early_pts ? "" : "!",
  705. frame->has_initial_pts ? "" : "!",
  706. frame->nb_scr_diffs, frame->nb_scr,
  707. frame->pts, frame->scr_stc, frame->scr_sof);
  708. stream->stats.stream.nb_frames++;
  709. stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
  710. stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
  711. stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
  712. stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
  713. if (frame->has_early_pts)
  714. stream->stats.stream.nb_pts_early++;
  715. if (frame->has_initial_pts)
  716. stream->stats.stream.nb_pts_initial++;
  717. if (frame->last_pts_diff <= frame->first_data)
  718. stream->stats.stream.nb_pts_constant++;
  719. if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
  720. stream->stats.stream.nb_scr_count_ok++;
  721. if (frame->nb_scr_diffs + 1 == frame->nb_scr)
  722. stream->stats.stream.nb_scr_diffs_ok++;
  723. memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
  724. }
  725. size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
  726. size_t size)
  727. {
  728. unsigned int scr_sof_freq;
  729. unsigned int duration;
  730. struct timespec ts;
  731. size_t count = 0;
  732. ts.tv_sec = stream->stats.stream.stop_ts.tv_sec
  733. - stream->stats.stream.start_ts.tv_sec;
  734. ts.tv_nsec = stream->stats.stream.stop_ts.tv_nsec
  735. - stream->stats.stream.start_ts.tv_nsec;
  736. if (ts.tv_nsec < 0) {
  737. ts.tv_sec--;
  738. ts.tv_nsec += 1000000000;
  739. }
  740. /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
  741. * frequency this will not overflow before more than 1h.
  742. */
  743. duration = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
  744. if (duration != 0)
  745. scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
  746. / duration;
  747. else
  748. scr_sof_freq = 0;
  749. count += scnprintf(buf + count, size - count,
  750. "frames: %u\npackets: %u\nempty: %u\n"
  751. "errors: %u\ninvalid: %u\n",
  752. stream->stats.stream.nb_frames,
  753. stream->stats.stream.nb_packets,
  754. stream->stats.stream.nb_empty,
  755. stream->stats.stream.nb_errors,
  756. stream->stats.stream.nb_invalid);
  757. count += scnprintf(buf + count, size - count,
  758. "pts: %u early, %u initial, %u ok\n",
  759. stream->stats.stream.nb_pts_early,
  760. stream->stats.stream.nb_pts_initial,
  761. stream->stats.stream.nb_pts_constant);
  762. count += scnprintf(buf + count, size - count,
  763. "scr: %u count ok, %u diff ok\n",
  764. stream->stats.stream.nb_scr_count_ok,
  765. stream->stats.stream.nb_scr_diffs_ok);
  766. count += scnprintf(buf + count, size - count,
  767. "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
  768. stream->stats.stream.min_sof,
  769. stream->stats.stream.max_sof,
  770. scr_sof_freq / 1000, scr_sof_freq % 1000);
  771. return count;
  772. }
  773. static void uvc_video_stats_start(struct uvc_streaming *stream)
  774. {
  775. memset(&stream->stats, 0, sizeof(stream->stats));
  776. stream->stats.stream.min_sof = 2048;
  777. }
  778. static void uvc_video_stats_stop(struct uvc_streaming *stream)
  779. {
  780. ktime_get_ts(&stream->stats.stream.stop_ts);
  781. }
  782. /* ------------------------------------------------------------------------
  783. * Video codecs
  784. */
  785. /* Video payload decoding is handled by uvc_video_decode_start(),
  786. * uvc_video_decode_data() and uvc_video_decode_end().
  787. *
  788. * uvc_video_decode_start is called with URB data at the start of a bulk or
  789. * isochronous payload. It processes header data and returns the header size
  790. * in bytes if successful. If an error occurs, it returns a negative error
  791. * code. The following error codes have special meanings.
  792. *
  793. * - EAGAIN informs the caller that the current video buffer should be marked
  794. * as done, and that the function should be called again with the same data
  795. * and a new video buffer. This is used when end of frame conditions can be
  796. * reliably detected at the beginning of the next frame only.
  797. *
  798. * If an error other than -EAGAIN is returned, the caller will drop the current
  799. * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
  800. * made until the next payload. -ENODATA can be used to drop the current
  801. * payload if no other error code is appropriate.
  802. *
  803. * uvc_video_decode_data is called for every URB with URB data. It copies the
  804. * data to the video buffer.
  805. *
  806. * uvc_video_decode_end is called with header data at the end of a bulk or
  807. * isochronous payload. It performs any additional header data processing and
  808. * returns 0 or a negative error code if an error occurred. As header data have
  809. * already been processed by uvc_video_decode_start, this functions isn't
  810. * required to perform sanity checks a second time.
  811. *
  812. * For isochronous transfers where a payload is always transferred in a single
  813. * URB, the three functions will be called in a row.
  814. *
  815. * To let the decoder process header data and update its internal state even
  816. * when no video buffer is available, uvc_video_decode_start must be prepared
  817. * to be called with a NULL buf parameter. uvc_video_decode_data and
  818. * uvc_video_decode_end will never be called with a NULL buffer.
  819. */
  820. static int uvc_video_decode_start(struct uvc_streaming *stream,
  821. struct uvc_buffer *buf, const __u8 *data, int len)
  822. {
  823. __u8 fid;
  824. /* Sanity checks:
  825. * - packet must be at least 2 bytes long
  826. * - bHeaderLength value must be at least 2 bytes (see above)
  827. * - bHeaderLength value can't be larger than the packet size.
  828. */
  829. if (len < 2 || data[0] < 2 || data[0] > len) {
  830. stream->stats.frame.nb_invalid++;
  831. return -EINVAL;
  832. }
  833. fid = data[1] & UVC_STREAM_FID;
  834. /* Increase the sequence number regardless of any buffer states, so
  835. * that discontinuous sequence numbers always indicate lost frames.
  836. */
  837. if (stream->last_fid != fid) {
  838. stream->sequence++;
  839. if (stream->sequence)
  840. uvc_video_stats_update(stream);
  841. }
  842. uvc_video_clock_decode(stream, buf, data, len);
  843. uvc_video_stats_decode(stream, data, len);
  844. /* Store the payload FID bit and return immediately when the buffer is
  845. * NULL.
  846. */
  847. if (buf == NULL) {
  848. stream->last_fid = fid;
  849. return -ENODATA;
  850. }
  851. /* Mark the buffer as bad if the error bit is set. */
  852. if (data[1] & UVC_STREAM_ERR) {
  853. uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
  854. "set).\n");
  855. buf->error = 1;
  856. }
  857. /* Synchronize to the input stream by waiting for the FID bit to be
  858. * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
  859. * stream->last_fid is initialized to -1, so the first isochronous
  860. * frame will always be in sync.
  861. *
  862. * If the device doesn't toggle the FID bit, invert stream->last_fid
  863. * when the EOF bit is set to force synchronisation on the next packet.
  864. */
  865. if (buf->state != UVC_BUF_STATE_ACTIVE) {
  866. struct timespec ts;
  867. if (fid == stream->last_fid) {
  868. uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
  869. "sync).\n");
  870. if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
  871. (data[1] & UVC_STREAM_EOF))
  872. stream->last_fid ^= UVC_STREAM_FID;
  873. return -ENODATA;
  874. }
  875. if (uvc_clock_param == CLOCK_MONOTONIC)
  876. ktime_get_ts(&ts);
  877. else
  878. ktime_get_real_ts(&ts);
  879. buf->buf.v4l2_buf.sequence = stream->sequence;
  880. buf->buf.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
  881. buf->buf.v4l2_buf.timestamp.tv_usec =
  882. ts.tv_nsec / NSEC_PER_USEC;
  883. /* TODO: Handle PTS and SCR. */
  884. buf->state = UVC_BUF_STATE_ACTIVE;
  885. }
  886. /* Mark the buffer as done if we're at the beginning of a new frame.
  887. * End of frame detection is better implemented by checking the EOF
  888. * bit (FID bit toggling is delayed by one frame compared to the EOF
  889. * bit), but some devices don't set the bit at end of frame (and the
  890. * last payload can be lost anyway). We thus must check if the FID has
  891. * been toggled.
  892. *
  893. * stream->last_fid is initialized to -1, so the first isochronous
  894. * frame will never trigger an end of frame detection.
  895. *
  896. * Empty buffers (bytesused == 0) don't trigger end of frame detection
  897. * as it doesn't make sense to return an empty buffer. This also
  898. * avoids detecting end of frame conditions at FID toggling if the
  899. * previous payload had the EOF bit set.
  900. */
  901. if (fid != stream->last_fid && buf->bytesused != 0) {
  902. uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
  903. "toggled).\n");
  904. buf->state = UVC_BUF_STATE_READY;
  905. return -EAGAIN;
  906. }
  907. stream->last_fid = fid;
  908. return data[0];
  909. }
  910. static void uvc_video_decode_data(struct uvc_streaming *stream,
  911. struct uvc_buffer *buf, const __u8 *data, int len)
  912. {
  913. unsigned int maxlen, nbytes;
  914. void *mem;
  915. if (len <= 0)
  916. return;
  917. /* Copy the video data to the buffer. */
  918. maxlen = buf->length - buf->bytesused;
  919. mem = buf->mem + buf->bytesused;
  920. nbytes = min((unsigned int)len, maxlen);
  921. memcpy(mem, data, nbytes);
  922. buf->bytesused += nbytes;
  923. /* Complete the current frame if the buffer size was exceeded. */
  924. if (len > maxlen) {
  925. uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
  926. buf->state = UVC_BUF_STATE_READY;
  927. }
  928. }
  929. static void uvc_video_decode_end(struct uvc_streaming *stream,
  930. struct uvc_buffer *buf, const __u8 *data, int len)
  931. {
  932. /* Mark the buffer as done if the EOF marker is set. */
  933. if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
  934. uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
  935. if (data[0] == len)
  936. uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
  937. buf->state = UVC_BUF_STATE_READY;
  938. if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
  939. stream->last_fid ^= UVC_STREAM_FID;
  940. }
  941. }
  942. /* Video payload encoding is handled by uvc_video_encode_header() and
  943. * uvc_video_encode_data(). Only bulk transfers are currently supported.
  944. *
  945. * uvc_video_encode_header is called at the start of a payload. It adds header
  946. * data to the transfer buffer and returns the header size. As the only known
  947. * UVC output device transfers a whole frame in a single payload, the EOF bit
  948. * is always set in the header.
  949. *
  950. * uvc_video_encode_data is called for every URB and copies the data from the
  951. * video buffer to the transfer buffer.
  952. */
  953. static int uvc_video_encode_header(struct uvc_streaming *stream,
  954. struct uvc_buffer *buf, __u8 *data, int len)
  955. {
  956. data[0] = 2; /* Header length */
  957. data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
  958. | (stream->last_fid & UVC_STREAM_FID);
  959. return 2;
  960. }
  961. static int uvc_video_encode_data(struct uvc_streaming *stream,
  962. struct uvc_buffer *buf, __u8 *data, int len)
  963. {
  964. struct uvc_video_queue *queue = &stream->queue;
  965. unsigned int nbytes;
  966. void *mem;
  967. /* Copy video data to the URB buffer. */
  968. mem = buf->mem + queue->buf_used;
  969. nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
  970. nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
  971. nbytes);
  972. memcpy(data, mem, nbytes);
  973. queue->buf_used += nbytes;
  974. return nbytes;
  975. }
  976. /* ------------------------------------------------------------------------
  977. * URB handling
  978. */
  979. /*
  980. * Completion handler for video URBs.
  981. */
  982. static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
  983. struct uvc_buffer *buf)
  984. {
  985. u8 *mem;
  986. int ret, i;
  987. for (i = 0; i < urb->number_of_packets; ++i) {
  988. if (urb->iso_frame_desc[i].status < 0) {
  989. uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
  990. "lost (%d).\n", urb->iso_frame_desc[i].status);
  991. /* Mark the buffer as faulty. */
  992. if (buf != NULL)
  993. buf->error = 1;
  994. continue;
  995. }
  996. /* Decode the payload header. */
  997. mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
  998. do {
  999. ret = uvc_video_decode_start(stream, buf, mem,
  1000. urb->iso_frame_desc[i].actual_length);
  1001. if (ret == -EAGAIN)
  1002. buf = uvc_queue_next_buffer(&stream->queue,
  1003. buf);
  1004. } while (ret == -EAGAIN);
  1005. if (ret < 0)
  1006. continue;
  1007. /* Decode the payload data. */
  1008. uvc_video_decode_data(stream, buf, mem + ret,
  1009. urb->iso_frame_desc[i].actual_length - ret);
  1010. /* Process the header again. */
  1011. uvc_video_decode_end(stream, buf, mem,
  1012. urb->iso_frame_desc[i].actual_length);
  1013. if (buf->state == UVC_BUF_STATE_READY) {
  1014. if (buf->length != buf->bytesused &&
  1015. !(stream->cur_format->flags &
  1016. UVC_FMT_FLAG_COMPRESSED))
  1017. buf->error = 1;
  1018. buf = uvc_queue_next_buffer(&stream->queue, buf);
  1019. }
  1020. }
  1021. }
  1022. static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
  1023. struct uvc_buffer *buf)
  1024. {
  1025. u8 *mem;
  1026. int len, ret;
  1027. if (urb->actual_length == 0)
  1028. return;
  1029. mem = urb->transfer_buffer;
  1030. len = urb->actual_length;
  1031. stream->bulk.payload_size += len;
  1032. /* If the URB is the first of its payload, decode and save the
  1033. * header.
  1034. */
  1035. if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
  1036. do {
  1037. ret = uvc_video_decode_start(stream, buf, mem, len);
  1038. if (ret == -EAGAIN)
  1039. buf = uvc_queue_next_buffer(&stream->queue,
  1040. buf);
  1041. } while (ret == -EAGAIN);
  1042. /* If an error occurred skip the rest of the payload. */
  1043. if (ret < 0 || buf == NULL) {
  1044. stream->bulk.skip_payload = 1;
  1045. } else {
  1046. memcpy(stream->bulk.header, mem, ret);
  1047. stream->bulk.header_size = ret;
  1048. mem += ret;
  1049. len -= ret;
  1050. }
  1051. }
  1052. /* The buffer queue might have been cancelled while a bulk transfer
  1053. * was in progress, so we can reach here with buf equal to NULL. Make
  1054. * sure buf is never dereferenced if NULL.
  1055. */
  1056. /* Process video data. */
  1057. if (!stream->bulk.skip_payload && buf != NULL)
  1058. uvc_video_decode_data(stream, buf, mem, len);
  1059. /* Detect the payload end by a URB smaller than the maximum size (or
  1060. * a payload size equal to the maximum) and process the header again.
  1061. */
  1062. if (urb->actual_length < urb->transfer_buffer_length ||
  1063. stream->bulk.payload_size >= stream->bulk.max_payload_size) {
  1064. if (!stream->bulk.skip_payload && buf != NULL) {
  1065. uvc_video_decode_end(stream, buf, stream->bulk.header,
  1066. stream->bulk.payload_size);
  1067. if (buf->state == UVC_BUF_STATE_READY)
  1068. buf = uvc_queue_next_buffer(&stream->queue,
  1069. buf);
  1070. }
  1071. stream->bulk.header_size = 0;
  1072. stream->bulk.skip_payload = 0;
  1073. stream->bulk.payload_size = 0;
  1074. }
  1075. }
  1076. static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
  1077. struct uvc_buffer *buf)
  1078. {
  1079. u8 *mem = urb->transfer_buffer;
  1080. int len = stream->urb_size, ret;
  1081. if (buf == NULL) {
  1082. urb->transfer_buffer_length = 0;
  1083. return;
  1084. }
  1085. /* If the URB is the first of its payload, add the header. */
  1086. if (stream->bulk.header_size == 0) {
  1087. ret = uvc_video_encode_header(stream, buf, mem, len);
  1088. stream->bulk.header_size = ret;
  1089. stream->bulk.payload_size += ret;
  1090. mem += ret;
  1091. len -= ret;
  1092. }
  1093. /* Process video data. */
  1094. ret = uvc_video_encode_data(stream, buf, mem, len);
  1095. stream->bulk.payload_size += ret;
  1096. len -= ret;
  1097. if (buf->bytesused == stream->queue.buf_used ||
  1098. stream->bulk.payload_size == stream->bulk.max_payload_size) {
  1099. if (buf->bytesused == stream->queue.buf_used) {
  1100. stream->queue.buf_used = 0;
  1101. buf->state = UVC_BUF_STATE_READY;
  1102. buf->buf.v4l2_buf.sequence = ++stream->sequence;
  1103. uvc_queue_next_buffer(&stream->queue, buf);
  1104. stream->last_fid ^= UVC_STREAM_FID;
  1105. }
  1106. stream->bulk.header_size = 0;
  1107. stream->bulk.payload_size = 0;
  1108. }
  1109. urb->transfer_buffer_length = stream->urb_size - len;
  1110. }
  1111. static void uvc_video_complete(struct urb *urb)
  1112. {
  1113. struct uvc_streaming *stream = urb->context;
  1114. struct uvc_video_queue *queue = &stream->queue;
  1115. struct uvc_buffer *buf = NULL;
  1116. unsigned long flags;
  1117. int ret;
  1118. switch (urb->status) {
  1119. case 0:
  1120. break;
  1121. default:
  1122. uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
  1123. "completion handler.\n", urb->status);
  1124. case -ENOENT: /* usb_kill_urb() called. */
  1125. if (stream->frozen)
  1126. return;
  1127. case -ECONNRESET: /* usb_unlink_urb() called. */
  1128. case -ESHUTDOWN: /* The endpoint is being disabled. */
  1129. uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
  1130. return;
  1131. }
  1132. spin_lock_irqsave(&queue->irqlock, flags);
  1133. if (!list_empty(&queue->irqqueue))
  1134. buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
  1135. queue);
  1136. spin_unlock_irqrestore(&queue->irqlock, flags);
  1137. stream->decode(urb, stream, buf);
  1138. if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
  1139. uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
  1140. ret);
  1141. }
  1142. }
  1143. /*
  1144. * Free transfer buffers.
  1145. */
  1146. static void uvc_free_urb_buffers(struct uvc_streaming *stream)
  1147. {
  1148. unsigned int i;
  1149. for (i = 0; i < UVC_URBS; ++i) {
  1150. if (stream->urb_buffer[i]) {
  1151. #ifndef CONFIG_DMA_NONCOHERENT
  1152. usb_free_coherent(stream->dev->udev, stream->urb_size,
  1153. stream->urb_buffer[i], stream->urb_dma[i]);
  1154. #else
  1155. kfree(stream->urb_buffer[i]);
  1156. #endif
  1157. stream->urb_buffer[i] = NULL;
  1158. }
  1159. }
  1160. stream->urb_size = 0;
  1161. }
  1162. /*
  1163. * Allocate transfer buffers. This function can be called with buffers
  1164. * already allocated when resuming from suspend, in which case it will
  1165. * return without touching the buffers.
  1166. *
  1167. * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
  1168. * system is too low on memory try successively smaller numbers of packets
  1169. * until allocation succeeds.
  1170. *
  1171. * Return the number of allocated packets on success or 0 when out of memory.
  1172. */
  1173. static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
  1174. unsigned int size, unsigned int psize, gfp_t gfp_flags)
  1175. {
  1176. unsigned int npackets;
  1177. unsigned int i;
  1178. /* Buffers are already allocated, bail out. */
  1179. if (stream->urb_size)
  1180. return stream->urb_size / psize;
  1181. /* Compute the number of packets. Bulk endpoints might transfer UVC
  1182. * payloads across multiple URBs.
  1183. */
  1184. npackets = DIV_ROUND_UP(size, psize);
  1185. if (npackets > UVC_MAX_PACKETS)
  1186. npackets = UVC_MAX_PACKETS;
  1187. /* Retry allocations until one succeed. */
  1188. for (; npackets > 1; npackets /= 2) {
  1189. for (i = 0; i < UVC_URBS; ++i) {
  1190. stream->urb_size = psize * npackets;
  1191. #ifndef CONFIG_DMA_NONCOHERENT
  1192. stream->urb_buffer[i] = usb_alloc_coherent(
  1193. stream->dev->udev, stream->urb_size,
  1194. gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
  1195. #else
  1196. stream->urb_buffer[i] =
  1197. kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
  1198. #endif
  1199. if (!stream->urb_buffer[i]) {
  1200. uvc_free_urb_buffers(stream);
  1201. break;
  1202. }
  1203. }
  1204. if (i == UVC_URBS) {
  1205. uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
  1206. "of %ux%u bytes each.\n", UVC_URBS, npackets,
  1207. psize);
  1208. return npackets;
  1209. }
  1210. }
  1211. uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
  1212. "per packet).\n", psize);
  1213. return 0;
  1214. }
  1215. /*
  1216. * Uninitialize isochronous/bulk URBs and free transfer buffers.
  1217. */
  1218. static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
  1219. {
  1220. struct urb *urb;
  1221. unsigned int i;
  1222. uvc_video_stats_stop(stream);
  1223. for (i = 0; i < UVC_URBS; ++i) {
  1224. urb = stream->urb[i];
  1225. if (urb == NULL)
  1226. continue;
  1227. usb_kill_urb(urb);
  1228. usb_free_urb(urb);
  1229. stream->urb[i] = NULL;
  1230. }
  1231. if (free_buffers)
  1232. uvc_free_urb_buffers(stream);
  1233. uvc_video_clock_cleanup(stream);
  1234. }
  1235. /*
  1236. * Initialize isochronous URBs and allocate transfer buffers. The packet size
  1237. * is given by the endpoint.
  1238. */
  1239. static int uvc_init_video_isoc(struct uvc_streaming *stream,
  1240. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  1241. {
  1242. struct urb *urb;
  1243. unsigned int npackets, i, j;
  1244. u16 psize;
  1245. u32 size;
  1246. psize = le16_to_cpu(ep->desc.wMaxPacketSize);
  1247. psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
  1248. size = stream->ctrl.dwMaxVideoFrameSize;
  1249. npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
  1250. if (npackets == 0)
  1251. return -ENOMEM;
  1252. size = npackets * psize;
  1253. for (i = 0; i < UVC_URBS; ++i) {
  1254. urb = usb_alloc_urb(npackets, gfp_flags);
  1255. if (urb == NULL) {
  1256. uvc_uninit_video(stream, 1);
  1257. return -ENOMEM;
  1258. }
  1259. urb->dev = stream->dev->udev;
  1260. urb->context = stream;
  1261. urb->pipe = usb_rcvisocpipe(stream->dev->udev,
  1262. ep->desc.bEndpointAddress);
  1263. #ifndef CONFIG_DMA_NONCOHERENT
  1264. urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
  1265. urb->transfer_dma = stream->urb_dma[i];
  1266. #else
  1267. urb->transfer_flags = URB_ISO_ASAP;
  1268. #endif
  1269. urb->interval = ep->desc.bInterval;
  1270. urb->transfer_buffer = stream->urb_buffer[i];
  1271. urb->complete = uvc_video_complete;
  1272. urb->number_of_packets = npackets;
  1273. urb->transfer_buffer_length = size;
  1274. for (j = 0; j < npackets; ++j) {
  1275. urb->iso_frame_desc[j].offset = j * psize;
  1276. urb->iso_frame_desc[j].length = psize;
  1277. }
  1278. stream->urb[i] = urb;
  1279. }
  1280. return 0;
  1281. }
  1282. /*
  1283. * Initialize bulk URBs and allocate transfer buffers. The packet size is
  1284. * given by the endpoint.
  1285. */
  1286. static int uvc_init_video_bulk(struct uvc_streaming *stream,
  1287. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  1288. {
  1289. struct urb *urb;
  1290. unsigned int npackets, pipe, i;
  1291. u16 psize;
  1292. u32 size;
  1293. psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
  1294. size = stream->ctrl.dwMaxPayloadTransferSize;
  1295. stream->bulk.max_payload_size = size;
  1296. npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
  1297. if (npackets == 0)
  1298. return -ENOMEM;
  1299. size = npackets * psize;
  1300. if (usb_endpoint_dir_in(&ep->desc))
  1301. pipe = usb_rcvbulkpipe(stream->dev->udev,
  1302. ep->desc.bEndpointAddress);
  1303. else
  1304. pipe = usb_sndbulkpipe(stream->dev->udev,
  1305. ep->desc.bEndpointAddress);
  1306. if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
  1307. size = 0;
  1308. for (i = 0; i < UVC_URBS; ++i) {
  1309. urb = usb_alloc_urb(0, gfp_flags);
  1310. if (urb == NULL) {
  1311. uvc_uninit_video(stream, 1);
  1312. return -ENOMEM;
  1313. }
  1314. usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
  1315. stream->urb_buffer[i], size, uvc_video_complete,
  1316. stream);
  1317. #ifndef CONFIG_DMA_NONCOHERENT
  1318. urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  1319. urb->transfer_dma = stream->urb_dma[i];
  1320. #endif
  1321. stream->urb[i] = urb;
  1322. }
  1323. return 0;
  1324. }
  1325. /*
  1326. * Initialize isochronous/bulk URBs and allocate transfer buffers.
  1327. */
  1328. static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
  1329. {
  1330. struct usb_interface *intf = stream->intf;
  1331. struct usb_host_endpoint *ep;
  1332. unsigned int i;
  1333. int ret;
  1334. stream->sequence = -1;
  1335. stream->last_fid = -1;
  1336. stream->bulk.header_size = 0;
  1337. stream->bulk.skip_payload = 0;
  1338. stream->bulk.payload_size = 0;
  1339. uvc_video_stats_start(stream);
  1340. ret = uvc_video_clock_init(stream);
  1341. if (ret < 0)
  1342. return ret;
  1343. if (intf->num_altsetting > 1) {
  1344. struct usb_host_endpoint *best_ep = NULL;
  1345. unsigned int best_psize = 3 * 1024;
  1346. unsigned int bandwidth;
  1347. unsigned int uninitialized_var(altsetting);
  1348. int intfnum = stream->intfnum;
  1349. /* Isochronous endpoint, select the alternate setting. */
  1350. bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
  1351. if (bandwidth == 0) {
  1352. uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
  1353. "bandwidth, defaulting to lowest.\n");
  1354. bandwidth = 1;
  1355. } else {
  1356. uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
  1357. "B/frame bandwidth.\n", bandwidth);
  1358. }
  1359. for (i = 0; i < intf->num_altsetting; ++i) {
  1360. struct usb_host_interface *alts;
  1361. unsigned int psize;
  1362. alts = &intf->altsetting[i];
  1363. ep = uvc_find_endpoint(alts,
  1364. stream->header.bEndpointAddress);
  1365. if (ep == NULL)
  1366. continue;
  1367. /* Check if the bandwidth is high enough. */
  1368. psize = le16_to_cpu(ep->desc.wMaxPacketSize);
  1369. psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
  1370. if (psize >= bandwidth && psize <= best_psize) {
  1371. altsetting = i;
  1372. best_psize = psize;
  1373. best_ep = ep;
  1374. }
  1375. }
  1376. if (best_ep == NULL) {
  1377. uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
  1378. "for requested bandwidth.\n");
  1379. return -EIO;
  1380. }
  1381. uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
  1382. "(%u B/frame bandwidth).\n", altsetting, best_psize);
  1383. ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
  1384. if (ret < 0)
  1385. return ret;
  1386. ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
  1387. } else {
  1388. /* Bulk endpoint, proceed to URB initialization. */
  1389. ep = uvc_find_endpoint(&intf->altsetting[0],
  1390. stream->header.bEndpointAddress);
  1391. if (ep == NULL)
  1392. return -EIO;
  1393. ret = uvc_init_video_bulk(stream, ep, gfp_flags);
  1394. }
  1395. if (ret < 0)
  1396. return ret;
  1397. /* Submit the URBs. */
  1398. for (i = 0; i < UVC_URBS; ++i) {
  1399. ret = usb_submit_urb(stream->urb[i], gfp_flags);
  1400. if (ret < 0) {
  1401. uvc_printk(KERN_ERR, "Failed to submit URB %u "
  1402. "(%d).\n", i, ret);
  1403. uvc_uninit_video(stream, 1);
  1404. return ret;
  1405. }
  1406. }
  1407. return 0;
  1408. }
  1409. /* --------------------------------------------------------------------------
  1410. * Suspend/resume
  1411. */
  1412. /*
  1413. * Stop streaming without disabling the video queue.
  1414. *
  1415. * To let userspace applications resume without trouble, we must not touch the
  1416. * video buffers in any way. We mark the device as frozen to make sure the URB
  1417. * completion handler won't try to cancel the queue when we kill the URBs.
  1418. */
  1419. int uvc_video_suspend(struct uvc_streaming *stream)
  1420. {
  1421. if (!uvc_queue_streaming(&stream->queue))
  1422. return 0;
  1423. stream->frozen = 1;
  1424. uvc_uninit_video(stream, 0);
  1425. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1426. return 0;
  1427. }
  1428. /*
  1429. * Reconfigure the video interface and restart streaming if it was enabled
  1430. * before suspend.
  1431. *
  1432. * If an error occurs, disable the video queue. This will wake all pending
  1433. * buffers, making sure userspace applications are notified of the problem
  1434. * instead of waiting forever.
  1435. */
  1436. int uvc_video_resume(struct uvc_streaming *stream, int reset)
  1437. {
  1438. int ret;
  1439. /* If the bus has been reset on resume, set the alternate setting to 0.
  1440. * This should be the default value, but some devices crash or otherwise
  1441. * misbehave if they don't receive a SET_INTERFACE request before any
  1442. * other video control request.
  1443. */
  1444. if (reset)
  1445. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1446. stream->frozen = 0;
  1447. ret = uvc_commit_video(stream, &stream->ctrl);
  1448. if (ret < 0) {
  1449. uvc_queue_enable(&stream->queue, 0);
  1450. return ret;
  1451. }
  1452. if (!uvc_queue_streaming(&stream->queue))
  1453. return 0;
  1454. ret = uvc_init_video(stream, GFP_NOIO);
  1455. if (ret < 0)
  1456. uvc_queue_enable(&stream->queue, 0);
  1457. return ret;
  1458. }
  1459. /* ------------------------------------------------------------------------
  1460. * Video device
  1461. */
  1462. /*
  1463. * Initialize the UVC video device by switching to alternate setting 0 and
  1464. * retrieve the default format.
  1465. *
  1466. * Some cameras (namely the Fuji Finepix) set the format and frame
  1467. * indexes to zero. The UVC standard doesn't clearly make this a spec
  1468. * violation, so try to silently fix the values if possible.
  1469. *
  1470. * This function is called before registering the device with V4L.
  1471. */
  1472. int uvc_video_init(struct uvc_streaming *stream)
  1473. {
  1474. struct uvc_streaming_control *probe = &stream->ctrl;
  1475. struct uvc_format *format = NULL;
  1476. struct uvc_frame *frame = NULL;
  1477. unsigned int i;
  1478. int ret;
  1479. if (stream->nformats == 0) {
  1480. uvc_printk(KERN_INFO, "No supported video formats found.\n");
  1481. return -EINVAL;
  1482. }
  1483. atomic_set(&stream->active, 0);
  1484. /* Initialize the video buffers queue. */
  1485. uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
  1486. /* Alternate setting 0 should be the default, yet the XBox Live Vision
  1487. * Cam (and possibly other devices) crash or otherwise misbehave if
  1488. * they don't receive a SET_INTERFACE request before any other video
  1489. * control request.
  1490. */
  1491. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1492. /* Set the streaming probe control with default streaming parameters
  1493. * retrieved from the device. Webcams that don't suport GET_DEF
  1494. * requests on the probe control will just keep their current streaming
  1495. * parameters.
  1496. */
  1497. if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
  1498. uvc_set_video_ctrl(stream, probe, 1);
  1499. /* Initialize the streaming parameters with the probe control current
  1500. * value. This makes sure SET_CUR requests on the streaming commit
  1501. * control will always use values retrieved from a successful GET_CUR
  1502. * request on the probe control, as required by the UVC specification.
  1503. */
  1504. ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
  1505. if (ret < 0)
  1506. return ret;
  1507. /* Check if the default format descriptor exists. Use the first
  1508. * available format otherwise.
  1509. */
  1510. for (i = stream->nformats; i > 0; --i) {
  1511. format = &stream->format[i-1];
  1512. if (format->index == probe->bFormatIndex)
  1513. break;
  1514. }
  1515. if (format->nframes == 0) {
  1516. uvc_printk(KERN_INFO, "No frame descriptor found for the "
  1517. "default format.\n");
  1518. return -EINVAL;
  1519. }
  1520. /* Zero bFrameIndex might be correct. Stream-based formats (including
  1521. * MPEG-2 TS and DV) do not support frames but have a dummy frame
  1522. * descriptor with bFrameIndex set to zero. If the default frame
  1523. * descriptor is not found, use the first available frame.
  1524. */
  1525. for (i = format->nframes; i > 0; --i) {
  1526. frame = &format->frame[i-1];
  1527. if (frame->bFrameIndex == probe->bFrameIndex)
  1528. break;
  1529. }
  1530. probe->bFormatIndex = format->index;
  1531. probe->bFrameIndex = frame->bFrameIndex;
  1532. stream->cur_format = format;
  1533. stream->cur_frame = frame;
  1534. /* Select the video decoding function */
  1535. if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
  1536. if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
  1537. stream->decode = uvc_video_decode_isight;
  1538. else if (stream->intf->num_altsetting > 1)
  1539. stream->decode = uvc_video_decode_isoc;
  1540. else
  1541. stream->decode = uvc_video_decode_bulk;
  1542. } else {
  1543. if (stream->intf->num_altsetting == 1)
  1544. stream->decode = uvc_video_encode_bulk;
  1545. else {
  1546. uvc_printk(KERN_INFO, "Isochronous endpoints are not "
  1547. "supported for video output devices.\n");
  1548. return -EINVAL;
  1549. }
  1550. }
  1551. return 0;
  1552. }
  1553. /*
  1554. * Enable or disable the video stream.
  1555. */
  1556. int uvc_video_enable(struct uvc_streaming *stream, int enable)
  1557. {
  1558. int ret;
  1559. if (!enable) {
  1560. uvc_uninit_video(stream, 1);
  1561. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1562. uvc_queue_enable(&stream->queue, 0);
  1563. return 0;
  1564. }
  1565. ret = uvc_queue_enable(&stream->queue, 1);
  1566. if (ret < 0)
  1567. return ret;
  1568. /* Commit the streaming parameters. */
  1569. ret = uvc_commit_video(stream, &stream->ctrl);
  1570. if (ret < 0) {
  1571. uvc_queue_enable(&stream->queue, 0);
  1572. return ret;
  1573. }
  1574. ret = uvc_init_video(stream, GFP_KERNEL);
  1575. if (ret < 0) {
  1576. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1577. uvc_queue_enable(&stream->queue, 0);
  1578. }
  1579. return ret;
  1580. }