uvc_video.c 55 KB

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