uvc_video.c 55 KB

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