uvc_video.c 55 KB

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