uvc_video.c 56 KB

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