uvc_video.c 58 KB

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