uvc_video.c 32 KB

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