uvc_video.c 53 KB

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