uvc_video.c 59 KB

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