uvc_video.c 55 KB

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