uvc_video.c 54 KB

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