uvc_video.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. /*
  2. * uvc_video.c -- USB Video Class driver - Video handling
  3. *
  4. * Copyright (C) 2005-2009
  5. * Laurent Pinchart (laurent.pinchart@skynet.be)
  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/usb.h>
  17. #include <linux/videodev2.h>
  18. #include <linux/vmalloc.h>
  19. #include <linux/wait.h>
  20. #include <asm/atomic.h>
  21. #include <asm/unaligned.h>
  22. #include <media/v4l2-common.h>
  23. #include "uvcvideo.h"
  24. /* ------------------------------------------------------------------------
  25. * UVC Controls
  26. */
  27. static int __uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
  28. __u8 intfnum, __u8 cs, void *data, __u16 size,
  29. int timeout)
  30. {
  31. __u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
  32. unsigned int pipe;
  33. pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
  34. : usb_sndctrlpipe(dev->udev, 0);
  35. type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
  36. return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
  37. unit << 8 | intfnum, data, size, timeout);
  38. }
  39. int uvc_query_ctrl(struct uvc_device *dev, __u8 query, __u8 unit,
  40. __u8 intfnum, __u8 cs, void *data, __u16 size)
  41. {
  42. int ret;
  43. ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
  44. UVC_CTRL_CONTROL_TIMEOUT);
  45. if (ret != size) {
  46. uvc_printk(KERN_ERR, "Failed to query (%u) UVC control %u "
  47. "(unit %u) : %d (exp. %u).\n", query, cs, unit, ret,
  48. size);
  49. return -EIO;
  50. }
  51. return 0;
  52. }
  53. static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
  54. struct uvc_streaming_control *ctrl)
  55. {
  56. struct uvc_format *format;
  57. struct uvc_frame *frame = NULL;
  58. unsigned int i;
  59. if (ctrl->bFormatIndex <= 0 ||
  60. ctrl->bFormatIndex > stream->nformats)
  61. return;
  62. format = &stream->format[ctrl->bFormatIndex - 1];
  63. for (i = 0; i < format->nframes; ++i) {
  64. if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
  65. frame = &format->frame[i];
  66. break;
  67. }
  68. }
  69. if (frame == NULL)
  70. return;
  71. if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
  72. (ctrl->dwMaxVideoFrameSize == 0 &&
  73. stream->dev->uvc_version < 0x0110))
  74. ctrl->dwMaxVideoFrameSize =
  75. frame->dwMaxVideoFrameBufferSize;
  76. if (stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
  77. stream->intf->num_altsetting > 1) {
  78. u32 interval;
  79. u32 bandwidth;
  80. interval = (ctrl->dwFrameInterval > 100000)
  81. ? ctrl->dwFrameInterval
  82. : frame->dwFrameInterval[0];
  83. /* Compute a bandwidth estimation by multiplying the frame
  84. * size by the number of video frames per second, divide the
  85. * result by the number of USB frames (or micro-frames for
  86. * high-speed devices) per second and add the UVC header size
  87. * (assumed to be 12 bytes long).
  88. */
  89. bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
  90. bandwidth *= 10000000 / interval + 1;
  91. bandwidth /= 1000;
  92. if (stream->dev->udev->speed == USB_SPEED_HIGH)
  93. bandwidth /= 8;
  94. bandwidth += 12;
  95. ctrl->dwMaxPayloadTransferSize = bandwidth;
  96. }
  97. }
  98. static int uvc_get_video_ctrl(struct uvc_streaming *stream,
  99. struct uvc_streaming_control *ctrl, int probe, __u8 query)
  100. {
  101. __u8 *data;
  102. __u16 size;
  103. int ret;
  104. size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
  105. data = kmalloc(size, GFP_KERNEL);
  106. if (data == NULL)
  107. return -ENOMEM;
  108. if ((video->dev->quirks & UVC_QUIRK_PROBE_DEF) && query == UVC_GET_DEF)
  109. return -EIO;
  110. ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
  111. probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
  112. size, UVC_CTRL_STREAMING_TIMEOUT);
  113. if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
  114. /* Some cameras, mostly based on Bison Electronics chipsets,
  115. * answer a GET_MIN or GET_MAX request with the wCompQuality
  116. * field only.
  117. */
  118. uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
  119. "compliance - GET_MIN/MAX(PROBE) incorrectly "
  120. "supported. Enabling workaround.\n");
  121. memset(ctrl, 0, sizeof ctrl);
  122. ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
  123. ret = 0;
  124. goto out;
  125. } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
  126. /* Many cameras don't support the GET_DEF request on their
  127. * video probe control. Warn once and return, the caller will
  128. * fall back to GET_CUR.
  129. */
  130. uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
  131. "compliance - GET_DEF(PROBE) not supported. "
  132. "Enabling workaround.\n");
  133. ret = -EIO;
  134. goto out;
  135. } else if (ret != size) {
  136. uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
  137. "%d (exp. %u).\n", query, probe ? "probe" : "commit",
  138. ret, size);
  139. ret = -EIO;
  140. goto out;
  141. }
  142. ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
  143. ctrl->bFormatIndex = data[2];
  144. ctrl->bFrameIndex = data[3];
  145. ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
  146. ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
  147. ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
  148. ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
  149. ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
  150. ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
  151. ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
  152. ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
  153. if (size == 34) {
  154. ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
  155. ctrl->bmFramingInfo = data[30];
  156. ctrl->bPreferedVersion = data[31];
  157. ctrl->bMinVersion = data[32];
  158. ctrl->bMaxVersion = data[33];
  159. } else {
  160. ctrl->dwClockFrequency = stream->dev->clock_frequency;
  161. ctrl->bmFramingInfo = 0;
  162. ctrl->bPreferedVersion = 0;
  163. ctrl->bMinVersion = 0;
  164. ctrl->bMaxVersion = 0;
  165. }
  166. /* Some broken devices return null or wrong dwMaxVideoFrameSize and
  167. * dwMaxPayloadTransferSize fields. Try to get the value from the
  168. * format and frame descriptors.
  169. */
  170. uvc_fixup_video_ctrl(stream, ctrl);
  171. ret = 0;
  172. out:
  173. kfree(data);
  174. return ret;
  175. }
  176. static int uvc_set_video_ctrl(struct uvc_streaming *stream,
  177. struct uvc_streaming_control *ctrl, int probe)
  178. {
  179. __u8 *data;
  180. __u16 size;
  181. int ret;
  182. size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
  183. data = kzalloc(size, GFP_KERNEL);
  184. if (data == NULL)
  185. return -ENOMEM;
  186. *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
  187. data[2] = ctrl->bFormatIndex;
  188. data[3] = ctrl->bFrameIndex;
  189. *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
  190. *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
  191. *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
  192. *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
  193. *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
  194. *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
  195. put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
  196. put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
  197. if (size == 34) {
  198. put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
  199. data[30] = ctrl->bmFramingInfo;
  200. data[31] = ctrl->bPreferedVersion;
  201. data[32] = ctrl->bMinVersion;
  202. data[33] = ctrl->bMaxVersion;
  203. }
  204. ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
  205. probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
  206. size, UVC_CTRL_STREAMING_TIMEOUT);
  207. if (ret != size) {
  208. uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
  209. "%d (exp. %u).\n", probe ? "probe" : "commit",
  210. ret, size);
  211. ret = -EIO;
  212. }
  213. kfree(data);
  214. return ret;
  215. }
  216. int uvc_probe_video(struct uvc_streaming *stream,
  217. struct uvc_streaming_control *probe)
  218. {
  219. struct uvc_streaming_control probe_min, probe_max;
  220. __u16 bandwidth;
  221. unsigned int i;
  222. int ret;
  223. mutex_lock(&stream->mutex);
  224. /* Perform probing. The device should adjust the requested values
  225. * according to its capabilities. However, some devices, namely the
  226. * first generation UVC Logitech webcams, don't implement the Video
  227. * Probe control properly, and just return the needed bandwidth. For
  228. * that reason, if the needed bandwidth exceeds the maximum available
  229. * bandwidth, try to lower the quality.
  230. */
  231. ret = uvc_set_video_ctrl(stream, probe, 1);
  232. if (ret < 0)
  233. goto done;
  234. /* Get the minimum and maximum values for compression settings. */
  235. if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
  236. ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
  237. if (ret < 0)
  238. goto done;
  239. ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
  240. if (ret < 0)
  241. goto done;
  242. probe->wCompQuality = probe_max.wCompQuality;
  243. }
  244. for (i = 0; i < 2; ++i) {
  245. ret = uvc_set_video_ctrl(stream, probe, 1);
  246. if (ret < 0)
  247. goto done;
  248. ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
  249. if (ret < 0)
  250. goto done;
  251. if (stream->intf->num_altsetting == 1)
  252. break;
  253. bandwidth = probe->dwMaxPayloadTransferSize;
  254. if (bandwidth <= stream->maxpsize)
  255. break;
  256. if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
  257. ret = -ENOSPC;
  258. goto done;
  259. }
  260. /* TODO: negotiate compression parameters */
  261. probe->wKeyFrameRate = probe_min.wKeyFrameRate;
  262. probe->wPFrameRate = probe_min.wPFrameRate;
  263. probe->wCompQuality = probe_max.wCompQuality;
  264. probe->wCompWindowSize = probe_min.wCompWindowSize;
  265. }
  266. done:
  267. mutex_unlock(&stream->mutex);
  268. return ret;
  269. }
  270. int uvc_commit_video(struct uvc_streaming *stream,
  271. struct uvc_streaming_control *probe)
  272. {
  273. return uvc_set_video_ctrl(stream, probe, 0);
  274. }
  275. /* ------------------------------------------------------------------------
  276. * Video codecs
  277. */
  278. /* Values for bmHeaderInfo (Video and Still Image Payload Headers, 2.4.3.3) */
  279. #define UVC_STREAM_EOH (1 << 7)
  280. #define UVC_STREAM_ERR (1 << 6)
  281. #define UVC_STREAM_STI (1 << 5)
  282. #define UVC_STREAM_RES (1 << 4)
  283. #define UVC_STREAM_SCR (1 << 3)
  284. #define UVC_STREAM_PTS (1 << 2)
  285. #define UVC_STREAM_EOF (1 << 1)
  286. #define UVC_STREAM_FID (1 << 0)
  287. /* Video payload decoding is handled by uvc_video_decode_start(),
  288. * uvc_video_decode_data() and uvc_video_decode_end().
  289. *
  290. * uvc_video_decode_start is called with URB data at the start of a bulk or
  291. * isochronous payload. It processes header data and returns the header size
  292. * in bytes if successful. If an error occurs, it returns a negative error
  293. * code. The following error codes have special meanings.
  294. *
  295. * - EAGAIN informs the caller that the current video buffer should be marked
  296. * as done, and that the function should be called again with the same data
  297. * and a new video buffer. This is used when end of frame conditions can be
  298. * reliably detected at the beginning of the next frame only.
  299. *
  300. * If an error other than -EAGAIN is returned, the caller will drop the current
  301. * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
  302. * made until the next payload. -ENODATA can be used to drop the current
  303. * payload if no other error code is appropriate.
  304. *
  305. * uvc_video_decode_data is called for every URB with URB data. It copies the
  306. * data to the video buffer.
  307. *
  308. * uvc_video_decode_end is called with header data at the end of a bulk or
  309. * isochronous payload. It performs any additional header data processing and
  310. * returns 0 or a negative error code if an error occured. As header data have
  311. * already been processed by uvc_video_decode_start, this functions isn't
  312. * required to perform sanity checks a second time.
  313. *
  314. * For isochronous transfers where a payload is always transfered in a single
  315. * URB, the three functions will be called in a row.
  316. *
  317. * To let the decoder process header data and update its internal state even
  318. * when no video buffer is available, uvc_video_decode_start must be prepared
  319. * to be called with a NULL buf parameter. uvc_video_decode_data and
  320. * uvc_video_decode_end will never be called with a NULL buffer.
  321. */
  322. static int uvc_video_decode_start(struct uvc_streaming *stream,
  323. struct uvc_buffer *buf, const __u8 *data, int len)
  324. {
  325. __u8 fid;
  326. /* Sanity checks:
  327. * - packet must be at least 2 bytes long
  328. * - bHeaderLength value must be at least 2 bytes (see above)
  329. * - bHeaderLength value can't be larger than the packet size.
  330. */
  331. if (len < 2 || data[0] < 2 || data[0] > len)
  332. return -EINVAL;
  333. /* Skip payloads marked with the error bit ("error frames"). */
  334. if (data[1] & UVC_STREAM_ERR) {
  335. uvc_trace(UVC_TRACE_FRAME, "Dropping payload (error bit "
  336. "set).\n");
  337. return -ENODATA;
  338. }
  339. fid = data[1] & UVC_STREAM_FID;
  340. /* Store the payload FID bit and return immediately when the buffer is
  341. * NULL.
  342. */
  343. if (buf == NULL) {
  344. stream->last_fid = fid;
  345. return -ENODATA;
  346. }
  347. /* Synchronize to the input stream by waiting for the FID bit to be
  348. * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
  349. * stream->last_fid is initialized to -1, so the first isochronous
  350. * frame will always be in sync.
  351. *
  352. * If the device doesn't toggle the FID bit, invert stream->last_fid
  353. * when the EOF bit is set to force synchronisation on the next packet.
  354. */
  355. if (buf->state != UVC_BUF_STATE_ACTIVE) {
  356. if (fid == stream->last_fid) {
  357. uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
  358. "sync).\n");
  359. if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
  360. (data[1] & UVC_STREAM_EOF))
  361. stream->last_fid ^= UVC_STREAM_FID;
  362. return -ENODATA;
  363. }
  364. /* TODO: Handle PTS and SCR. */
  365. buf->state = UVC_BUF_STATE_ACTIVE;
  366. }
  367. /* Mark the buffer as done if we're at the beginning of a new frame.
  368. * End of frame detection is better implemented by checking the EOF
  369. * bit (FID bit toggling is delayed by one frame compared to the EOF
  370. * bit), but some devices don't set the bit at end of frame (and the
  371. * last payload can be lost anyway). We thus must check if the FID has
  372. * been toggled.
  373. *
  374. * stream->last_fid is initialized to -1, so the first isochronous
  375. * frame will never trigger an end of frame detection.
  376. *
  377. * Empty buffers (bytesused == 0) don't trigger end of frame detection
  378. * as it doesn't make sense to return an empty buffer. This also
  379. * avoids detecting end of frame conditions at FID toggling if the
  380. * previous payload had the EOF bit set.
  381. */
  382. if (fid != stream->last_fid && buf->buf.bytesused != 0) {
  383. uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
  384. "toggled).\n");
  385. buf->state = UVC_BUF_STATE_DONE;
  386. return -EAGAIN;
  387. }
  388. stream->last_fid = fid;
  389. return data[0];
  390. }
  391. static void uvc_video_decode_data(struct uvc_streaming *stream,
  392. struct uvc_buffer *buf, const __u8 *data, int len)
  393. {
  394. struct uvc_video_queue *queue = &stream->queue;
  395. unsigned int maxlen, nbytes;
  396. void *mem;
  397. if (len <= 0)
  398. return;
  399. /* Copy the video data to the buffer. */
  400. maxlen = buf->buf.length - buf->buf.bytesused;
  401. mem = queue->mem + buf->buf.m.offset + buf->buf.bytesused;
  402. nbytes = min((unsigned int)len, maxlen);
  403. memcpy(mem, data, nbytes);
  404. buf->buf.bytesused += nbytes;
  405. /* Complete the current frame if the buffer size was exceeded. */
  406. if (len > maxlen) {
  407. uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
  408. buf->state = UVC_BUF_STATE_DONE;
  409. }
  410. }
  411. static void uvc_video_decode_end(struct uvc_streaming *stream,
  412. struct uvc_buffer *buf, const __u8 *data, int len)
  413. {
  414. /* Mark the buffer as done if the EOF marker is set. */
  415. if (data[1] & UVC_STREAM_EOF && buf->buf.bytesused != 0) {
  416. uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
  417. if (data[0] == len)
  418. uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
  419. buf->state = UVC_BUF_STATE_DONE;
  420. if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
  421. stream->last_fid ^= UVC_STREAM_FID;
  422. }
  423. }
  424. /* Video payload encoding is handled by uvc_video_encode_header() and
  425. * uvc_video_encode_data(). Only bulk transfers are currently supported.
  426. *
  427. * uvc_video_encode_header is called at the start of a payload. It adds header
  428. * data to the transfer buffer and returns the header size. As the only known
  429. * UVC output device transfers a whole frame in a single payload, the EOF bit
  430. * is always set in the header.
  431. *
  432. * uvc_video_encode_data is called for every URB and copies the data from the
  433. * video buffer to the transfer buffer.
  434. */
  435. static int uvc_video_encode_header(struct uvc_streaming *stream,
  436. struct uvc_buffer *buf, __u8 *data, int len)
  437. {
  438. data[0] = 2; /* Header length */
  439. data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
  440. | (stream->last_fid & UVC_STREAM_FID);
  441. return 2;
  442. }
  443. static int uvc_video_encode_data(struct uvc_streaming *stream,
  444. struct uvc_buffer *buf, __u8 *data, int len)
  445. {
  446. struct uvc_video_queue *queue = &stream->queue;
  447. unsigned int nbytes;
  448. void *mem;
  449. /* Copy video data to the URB buffer. */
  450. mem = queue->mem + buf->buf.m.offset + queue->buf_used;
  451. nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
  452. nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
  453. nbytes);
  454. memcpy(data, mem, nbytes);
  455. queue->buf_used += nbytes;
  456. return nbytes;
  457. }
  458. /* ------------------------------------------------------------------------
  459. * URB handling
  460. */
  461. /*
  462. * Completion handler for video URBs.
  463. */
  464. static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
  465. struct uvc_buffer *buf)
  466. {
  467. u8 *mem;
  468. int ret, i;
  469. for (i = 0; i < urb->number_of_packets; ++i) {
  470. if (urb->iso_frame_desc[i].status < 0) {
  471. uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
  472. "lost (%d).\n", urb->iso_frame_desc[i].status);
  473. continue;
  474. }
  475. /* Decode the payload header. */
  476. mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
  477. do {
  478. ret = uvc_video_decode_start(stream, buf, mem,
  479. urb->iso_frame_desc[i].actual_length);
  480. if (ret == -EAGAIN)
  481. buf = uvc_queue_next_buffer(&stream->queue,
  482. buf);
  483. } while (ret == -EAGAIN);
  484. if (ret < 0)
  485. continue;
  486. /* Decode the payload data. */
  487. uvc_video_decode_data(stream, buf, mem + ret,
  488. urb->iso_frame_desc[i].actual_length - ret);
  489. /* Process the header again. */
  490. uvc_video_decode_end(stream, buf, mem,
  491. urb->iso_frame_desc[i].actual_length);
  492. if (buf->state == UVC_BUF_STATE_DONE ||
  493. buf->state == UVC_BUF_STATE_ERROR)
  494. buf = uvc_queue_next_buffer(&stream->queue, buf);
  495. }
  496. }
  497. static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
  498. struct uvc_buffer *buf)
  499. {
  500. u8 *mem;
  501. int len, ret;
  502. if (urb->actual_length == 0)
  503. return;
  504. mem = urb->transfer_buffer;
  505. len = urb->actual_length;
  506. stream->bulk.payload_size += len;
  507. /* If the URB is the first of its payload, decode and save the
  508. * header.
  509. */
  510. if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
  511. do {
  512. ret = uvc_video_decode_start(stream, buf, mem, len);
  513. if (ret == -EAGAIN)
  514. buf = uvc_queue_next_buffer(&stream->queue,
  515. buf);
  516. } while (ret == -EAGAIN);
  517. /* If an error occured skip the rest of the payload. */
  518. if (ret < 0 || buf == NULL) {
  519. stream->bulk.skip_payload = 1;
  520. } else {
  521. memcpy(stream->bulk.header, mem, ret);
  522. stream->bulk.header_size = ret;
  523. mem += ret;
  524. len -= ret;
  525. }
  526. }
  527. /* The buffer queue might have been cancelled while a bulk transfer
  528. * was in progress, so we can reach here with buf equal to NULL. Make
  529. * sure buf is never dereferenced if NULL.
  530. */
  531. /* Process video data. */
  532. if (!stream->bulk.skip_payload && buf != NULL)
  533. uvc_video_decode_data(stream, buf, mem, len);
  534. /* Detect the payload end by a URB smaller than the maximum size (or
  535. * a payload size equal to the maximum) and process the header again.
  536. */
  537. if (urb->actual_length < urb->transfer_buffer_length ||
  538. stream->bulk.payload_size >= stream->bulk.max_payload_size) {
  539. if (!stream->bulk.skip_payload && buf != NULL) {
  540. uvc_video_decode_end(stream, buf, stream->bulk.header,
  541. stream->bulk.payload_size);
  542. if (buf->state == UVC_BUF_STATE_DONE ||
  543. buf->state == UVC_BUF_STATE_ERROR)
  544. buf = uvc_queue_next_buffer(&stream->queue,
  545. buf);
  546. }
  547. stream->bulk.header_size = 0;
  548. stream->bulk.skip_payload = 0;
  549. stream->bulk.payload_size = 0;
  550. }
  551. }
  552. static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
  553. struct uvc_buffer *buf)
  554. {
  555. u8 *mem = urb->transfer_buffer;
  556. int len = stream->urb_size, ret;
  557. if (buf == NULL) {
  558. urb->transfer_buffer_length = 0;
  559. return;
  560. }
  561. /* If the URB is the first of its payload, add the header. */
  562. if (stream->bulk.header_size == 0) {
  563. ret = uvc_video_encode_header(stream, buf, mem, len);
  564. stream->bulk.header_size = ret;
  565. stream->bulk.payload_size += ret;
  566. mem += ret;
  567. len -= ret;
  568. }
  569. /* Process video data. */
  570. ret = uvc_video_encode_data(stream, buf, mem, len);
  571. stream->bulk.payload_size += ret;
  572. len -= ret;
  573. if (buf->buf.bytesused == stream->queue.buf_used ||
  574. stream->bulk.payload_size == stream->bulk.max_payload_size) {
  575. if (buf->buf.bytesused == stream->queue.buf_used) {
  576. stream->queue.buf_used = 0;
  577. buf->state = UVC_BUF_STATE_DONE;
  578. uvc_queue_next_buffer(&stream->queue, buf);
  579. stream->last_fid ^= UVC_STREAM_FID;
  580. }
  581. stream->bulk.header_size = 0;
  582. stream->bulk.payload_size = 0;
  583. }
  584. urb->transfer_buffer_length = stream->urb_size - len;
  585. }
  586. static void uvc_video_complete(struct urb *urb)
  587. {
  588. struct uvc_streaming *stream = urb->context;
  589. struct uvc_video_queue *queue = &stream->queue;
  590. struct uvc_buffer *buf = NULL;
  591. unsigned long flags;
  592. int ret;
  593. switch (urb->status) {
  594. case 0:
  595. break;
  596. default:
  597. uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
  598. "completion handler.\n", urb->status);
  599. case -ENOENT: /* usb_kill_urb() called. */
  600. if (stream->frozen)
  601. return;
  602. case -ECONNRESET: /* usb_unlink_urb() called. */
  603. case -ESHUTDOWN: /* The endpoint is being disabled. */
  604. uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
  605. return;
  606. }
  607. spin_lock_irqsave(&queue->irqlock, flags);
  608. if (!list_empty(&queue->irqqueue))
  609. buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
  610. queue);
  611. spin_unlock_irqrestore(&queue->irqlock, flags);
  612. stream->decode(urb, stream, buf);
  613. if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
  614. uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
  615. ret);
  616. }
  617. }
  618. /*
  619. * Free transfer buffers.
  620. */
  621. static void uvc_free_urb_buffers(struct uvc_streaming *stream)
  622. {
  623. unsigned int i;
  624. for (i = 0; i < UVC_URBS; ++i) {
  625. if (stream->urb_buffer[i]) {
  626. usb_buffer_free(stream->dev->udev, stream->urb_size,
  627. stream->urb_buffer[i], stream->urb_dma[i]);
  628. stream->urb_buffer[i] = NULL;
  629. }
  630. }
  631. stream->urb_size = 0;
  632. }
  633. /*
  634. * Allocate transfer buffers. This function can be called with buffers
  635. * already allocated when resuming from suspend, in which case it will
  636. * return without touching the buffers.
  637. *
  638. * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
  639. * system is too low on memory try successively smaller numbers of packets
  640. * until allocation succeeds.
  641. *
  642. * Return the number of allocated packets on success or 0 when out of memory.
  643. */
  644. static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
  645. unsigned int size, unsigned int psize, gfp_t gfp_flags)
  646. {
  647. unsigned int npackets;
  648. unsigned int i;
  649. /* Buffers are already allocated, bail out. */
  650. if (stream->urb_size)
  651. return stream->urb_size / psize;
  652. /* Compute the number of packets. Bulk endpoints might transfer UVC
  653. * payloads accross multiple URBs.
  654. */
  655. npackets = DIV_ROUND_UP(size, psize);
  656. if (npackets > UVC_MAX_PACKETS)
  657. npackets = UVC_MAX_PACKETS;
  658. /* Retry allocations until one succeed. */
  659. for (; npackets > 1; npackets /= 2) {
  660. for (i = 0; i < UVC_URBS; ++i) {
  661. stream->urb_buffer[i] = usb_buffer_alloc(
  662. stream->dev->udev, psize * npackets,
  663. gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
  664. if (!stream->urb_buffer[i]) {
  665. uvc_free_urb_buffers(stream);
  666. break;
  667. }
  668. }
  669. if (i == UVC_URBS) {
  670. stream->urb_size = psize * npackets;
  671. return npackets;
  672. }
  673. }
  674. return 0;
  675. }
  676. /*
  677. * Uninitialize isochronous/bulk URBs and free transfer buffers.
  678. */
  679. static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
  680. {
  681. struct urb *urb;
  682. unsigned int i;
  683. for (i = 0; i < UVC_URBS; ++i) {
  684. urb = stream->urb[i];
  685. if (urb == NULL)
  686. continue;
  687. usb_kill_urb(urb);
  688. usb_free_urb(urb);
  689. stream->urb[i] = NULL;
  690. }
  691. if (free_buffers)
  692. uvc_free_urb_buffers(stream);
  693. }
  694. /*
  695. * Initialize isochronous URBs and allocate transfer buffers. The packet size
  696. * is given by the endpoint.
  697. */
  698. static int uvc_init_video_isoc(struct uvc_streaming *stream,
  699. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  700. {
  701. struct urb *urb;
  702. unsigned int npackets, i, j;
  703. u16 psize;
  704. u32 size;
  705. psize = le16_to_cpu(ep->desc.wMaxPacketSize);
  706. psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
  707. size = stream->ctrl.dwMaxVideoFrameSize;
  708. npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
  709. if (npackets == 0)
  710. return -ENOMEM;
  711. size = npackets * psize;
  712. for (i = 0; i < UVC_URBS; ++i) {
  713. urb = usb_alloc_urb(npackets, gfp_flags);
  714. if (urb == NULL) {
  715. uvc_uninit_video(stream, 1);
  716. return -ENOMEM;
  717. }
  718. urb->dev = stream->dev->udev;
  719. urb->context = stream;
  720. urb->pipe = usb_rcvisocpipe(stream->dev->udev,
  721. ep->desc.bEndpointAddress);
  722. urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
  723. urb->interval = ep->desc.bInterval;
  724. urb->transfer_buffer = stream->urb_buffer[i];
  725. urb->transfer_dma = stream->urb_dma[i];
  726. urb->complete = uvc_video_complete;
  727. urb->number_of_packets = npackets;
  728. urb->transfer_buffer_length = size;
  729. for (j = 0; j < npackets; ++j) {
  730. urb->iso_frame_desc[j].offset = j * psize;
  731. urb->iso_frame_desc[j].length = psize;
  732. }
  733. stream->urb[i] = urb;
  734. }
  735. return 0;
  736. }
  737. /*
  738. * Initialize bulk URBs and allocate transfer buffers. The packet size is
  739. * given by the endpoint.
  740. */
  741. static int uvc_init_video_bulk(struct uvc_streaming *stream,
  742. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  743. {
  744. struct urb *urb;
  745. unsigned int npackets, pipe, i;
  746. u16 psize;
  747. u32 size;
  748. psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
  749. size = stream->ctrl.dwMaxPayloadTransferSize;
  750. stream->bulk.max_payload_size = size;
  751. npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
  752. if (npackets == 0)
  753. return -ENOMEM;
  754. size = npackets * psize;
  755. if (usb_endpoint_dir_in(&ep->desc))
  756. pipe = usb_rcvbulkpipe(stream->dev->udev,
  757. ep->desc.bEndpointAddress);
  758. else
  759. pipe = usb_sndbulkpipe(stream->dev->udev,
  760. ep->desc.bEndpointAddress);
  761. if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
  762. size = 0;
  763. for (i = 0; i < UVC_URBS; ++i) {
  764. urb = usb_alloc_urb(0, gfp_flags);
  765. if (urb == NULL) {
  766. uvc_uninit_video(stream, 1);
  767. return -ENOMEM;
  768. }
  769. usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
  770. stream->urb_buffer[i], size, uvc_video_complete,
  771. stream);
  772. urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  773. urb->transfer_dma = stream->urb_dma[i];
  774. stream->urb[i] = urb;
  775. }
  776. return 0;
  777. }
  778. /*
  779. * Initialize isochronous/bulk URBs and allocate transfer buffers.
  780. */
  781. static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
  782. {
  783. struct usb_interface *intf = stream->intf;
  784. struct usb_host_interface *alts;
  785. struct usb_host_endpoint *ep = NULL;
  786. int intfnum = stream->intfnum;
  787. unsigned int bandwidth, psize, i;
  788. int ret;
  789. stream->last_fid = -1;
  790. stream->bulk.header_size = 0;
  791. stream->bulk.skip_payload = 0;
  792. stream->bulk.payload_size = 0;
  793. if (intf->num_altsetting > 1) {
  794. /* Isochronous endpoint, select the alternate setting. */
  795. bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
  796. if (bandwidth == 0) {
  797. uvc_printk(KERN_WARNING, "device %s requested null "
  798. "bandwidth, defaulting to lowest.\n",
  799. stream->dev->name);
  800. bandwidth = 1;
  801. }
  802. for (i = 0; i < intf->num_altsetting; ++i) {
  803. alts = &intf->altsetting[i];
  804. ep = uvc_find_endpoint(alts,
  805. stream->header.bEndpointAddress);
  806. if (ep == NULL)
  807. continue;
  808. /* Check if the bandwidth is high enough. */
  809. psize = le16_to_cpu(ep->desc.wMaxPacketSize);
  810. psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
  811. if (psize >= bandwidth)
  812. break;
  813. }
  814. if (i >= intf->num_altsetting)
  815. return -EIO;
  816. ret = usb_set_interface(stream->dev->udev, intfnum, i);
  817. if (ret < 0)
  818. return ret;
  819. ret = uvc_init_video_isoc(stream, ep, gfp_flags);
  820. } else {
  821. /* Bulk endpoint, proceed to URB initialization. */
  822. ep = uvc_find_endpoint(&intf->altsetting[0],
  823. stream->header.bEndpointAddress);
  824. if (ep == NULL)
  825. return -EIO;
  826. ret = uvc_init_video_bulk(stream, ep, gfp_flags);
  827. }
  828. if (ret < 0)
  829. return ret;
  830. /* Submit the URBs. */
  831. for (i = 0; i < UVC_URBS; ++i) {
  832. ret = usb_submit_urb(stream->urb[i], gfp_flags);
  833. if (ret < 0) {
  834. uvc_printk(KERN_ERR, "Failed to submit URB %u "
  835. "(%d).\n", i, ret);
  836. uvc_uninit_video(stream, 1);
  837. return ret;
  838. }
  839. }
  840. return 0;
  841. }
  842. /* --------------------------------------------------------------------------
  843. * Suspend/resume
  844. */
  845. /*
  846. * Stop streaming without disabling the video queue.
  847. *
  848. * To let userspace applications resume without trouble, we must not touch the
  849. * video buffers in any way. We mark the device as frozen to make sure the URB
  850. * completion handler won't try to cancel the queue when we kill the URBs.
  851. */
  852. int uvc_video_suspend(struct uvc_streaming *stream)
  853. {
  854. if (!uvc_queue_streaming(&stream->queue))
  855. return 0;
  856. stream->frozen = 1;
  857. uvc_uninit_video(stream, 0);
  858. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  859. return 0;
  860. }
  861. /*
  862. * Reconfigure the video interface and restart streaming if it was enabled
  863. * before suspend.
  864. *
  865. * If an error occurs, disable the video queue. This will wake all pending
  866. * buffers, making sure userspace applications are notified of the problem
  867. * instead of waiting forever.
  868. */
  869. int uvc_video_resume(struct uvc_streaming *stream)
  870. {
  871. int ret;
  872. stream->frozen = 0;
  873. ret = uvc_commit_video(stream, &stream->ctrl);
  874. if (ret < 0) {
  875. uvc_queue_enable(&stream->queue, 0);
  876. return ret;
  877. }
  878. if (!uvc_queue_streaming(&stream->queue))
  879. return 0;
  880. ret = uvc_init_video(stream, GFP_NOIO);
  881. if (ret < 0)
  882. uvc_queue_enable(&stream->queue, 0);
  883. return ret;
  884. }
  885. /* ------------------------------------------------------------------------
  886. * Video device
  887. */
  888. /*
  889. * Initialize the UVC video device by switching to alternate setting 0 and
  890. * retrieve the default format.
  891. *
  892. * Some cameras (namely the Fuji Finepix) set the format and frame
  893. * indexes to zero. The UVC standard doesn't clearly make this a spec
  894. * violation, so try to silently fix the values if possible.
  895. *
  896. * This function is called before registering the device with V4L.
  897. */
  898. int uvc_video_init(struct uvc_streaming *stream)
  899. {
  900. struct uvc_streaming_control *probe = &stream->ctrl;
  901. struct uvc_format *format = NULL;
  902. struct uvc_frame *frame = NULL;
  903. unsigned int i;
  904. int ret;
  905. if (stream->nformats == 0) {
  906. uvc_printk(KERN_INFO, "No supported video formats found.\n");
  907. return -EINVAL;
  908. }
  909. atomic_set(&stream->active, 0);
  910. /* Initialize the video buffers queue. */
  911. uvc_queue_init(&stream->queue, stream->type);
  912. /* Alternate setting 0 should be the default, yet the XBox Live Vision
  913. * Cam (and possibly other devices) crash or otherwise misbehave if
  914. * they don't receive a SET_INTERFACE request before any other video
  915. * control request.
  916. */
  917. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  918. /* Set the streaming probe control with default streaming parameters
  919. * retrieved from the device. Webcams that don't suport GET_DEF
  920. * requests on the probe control will just keep their current streaming
  921. * parameters.
  922. */
  923. if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
  924. uvc_set_video_ctrl(stream, probe, 1);
  925. /* Initialize the streaming parameters with the probe control current
  926. * value. This makes sure SET_CUR requests on the streaming commit
  927. * control will always use values retrieved from a successful GET_CUR
  928. * request on the probe control, as required by the UVC specification.
  929. */
  930. ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
  931. if (ret < 0)
  932. return ret;
  933. /* Check if the default format descriptor exists. Use the first
  934. * available format otherwise.
  935. */
  936. for (i = stream->nformats; i > 0; --i) {
  937. format = &stream->format[i-1];
  938. if (format->index == probe->bFormatIndex)
  939. break;
  940. }
  941. if (format->nframes == 0) {
  942. uvc_printk(KERN_INFO, "No frame descriptor found for the "
  943. "default format.\n");
  944. return -EINVAL;
  945. }
  946. /* Zero bFrameIndex might be correct. Stream-based formats (including
  947. * MPEG-2 TS and DV) do not support frames but have a dummy frame
  948. * descriptor with bFrameIndex set to zero. If the default frame
  949. * descriptor is not found, use the first available frame.
  950. */
  951. for (i = format->nframes; i > 0; --i) {
  952. frame = &format->frame[i-1];
  953. if (frame->bFrameIndex == probe->bFrameIndex)
  954. break;
  955. }
  956. probe->bFormatIndex = format->index;
  957. probe->bFrameIndex = frame->bFrameIndex;
  958. stream->cur_format = format;
  959. stream->cur_frame = frame;
  960. /* Select the video decoding function */
  961. if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
  962. if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
  963. stream->decode = uvc_video_decode_isight;
  964. else if (stream->intf->num_altsetting > 1)
  965. stream->decode = uvc_video_decode_isoc;
  966. else
  967. stream->decode = uvc_video_decode_bulk;
  968. } else {
  969. if (stream->intf->num_altsetting == 1)
  970. stream->decode = uvc_video_encode_bulk;
  971. else {
  972. uvc_printk(KERN_INFO, "Isochronous endpoints are not "
  973. "supported for video output devices.\n");
  974. return -EINVAL;
  975. }
  976. }
  977. return 0;
  978. }
  979. /*
  980. * Enable or disable the video stream.
  981. */
  982. int uvc_video_enable(struct uvc_streaming *stream, int enable)
  983. {
  984. int ret;
  985. if (!enable) {
  986. uvc_uninit_video(stream, 1);
  987. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  988. uvc_queue_enable(&stream->queue, 0);
  989. return 0;
  990. }
  991. if ((stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
  992. uvc_no_drop_param)
  993. stream->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
  994. else
  995. stream->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
  996. ret = uvc_queue_enable(&stream->queue, 1);
  997. if (ret < 0)
  998. return ret;
  999. /* Commit the streaming parameters. */
  1000. ret = uvc_commit_video(stream, &stream->ctrl);
  1001. if (ret < 0)
  1002. return ret;
  1003. return uvc_init_video(stream, GFP_KERNEL);
  1004. }