uvc_video.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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. if (urb->actual_length == 0)
  470. return;
  471. mem = urb->transfer_buffer;
  472. len = urb->actual_length;
  473. video->bulk.payload_size += len;
  474. /* If the URB is the first of its payload, decode and save the
  475. * header.
  476. */
  477. if (video->bulk.header_size == 0 && !video->bulk.skip_payload) {
  478. do {
  479. ret = uvc_video_decode_start(video, buf, mem, len);
  480. if (ret == -EAGAIN)
  481. buf = uvc_queue_next_buffer(&video->queue, buf);
  482. } while (ret == -EAGAIN);
  483. /* If an error occured skip the rest of the payload. */
  484. if (ret < 0 || buf == NULL) {
  485. video->bulk.skip_payload = 1;
  486. } else {
  487. memcpy(video->bulk.header, mem, ret);
  488. video->bulk.header_size = ret;
  489. mem += ret;
  490. len -= ret;
  491. }
  492. }
  493. /* The buffer queue might have been cancelled while a bulk transfer
  494. * was in progress, so we can reach here with buf equal to NULL. Make
  495. * sure buf is never dereferenced if NULL.
  496. */
  497. /* Process video data. */
  498. if (!video->bulk.skip_payload && buf != NULL)
  499. uvc_video_decode_data(video, buf, mem, len);
  500. /* Detect the payload end by a URB smaller than the maximum size (or
  501. * a payload size equal to the maximum) and process the header again.
  502. */
  503. if (urb->actual_length < urb->transfer_buffer_length ||
  504. video->bulk.payload_size >= video->bulk.max_payload_size) {
  505. if (!video->bulk.skip_payload && buf != NULL) {
  506. uvc_video_decode_end(video, buf, video->bulk.header,
  507. video->bulk.payload_size);
  508. if (buf->state == UVC_BUF_STATE_DONE ||
  509. buf->state == UVC_BUF_STATE_ERROR)
  510. buf = uvc_queue_next_buffer(&video->queue, buf);
  511. }
  512. video->bulk.header_size = 0;
  513. video->bulk.skip_payload = 0;
  514. video->bulk.payload_size = 0;
  515. }
  516. }
  517. static void uvc_video_encode_bulk(struct urb *urb,
  518. struct uvc_video_device *video, struct uvc_buffer *buf)
  519. {
  520. u8 *mem = urb->transfer_buffer;
  521. int len = video->urb_size, ret;
  522. if (buf == NULL) {
  523. urb->transfer_buffer_length = 0;
  524. return;
  525. }
  526. /* If the URB is the first of its payload, add the header. */
  527. if (video->bulk.header_size == 0) {
  528. ret = uvc_video_encode_header(video, buf, mem, len);
  529. video->bulk.header_size = ret;
  530. video->bulk.payload_size += ret;
  531. mem += ret;
  532. len -= ret;
  533. }
  534. /* Process video data. */
  535. ret = uvc_video_encode_data(video, buf, mem, len);
  536. video->bulk.payload_size += ret;
  537. len -= ret;
  538. if (buf->buf.bytesused == video->queue.buf_used ||
  539. video->bulk.payload_size == video->bulk.max_payload_size) {
  540. if (buf->buf.bytesused == video->queue.buf_used) {
  541. video->queue.buf_used = 0;
  542. buf->state = UVC_BUF_STATE_DONE;
  543. uvc_queue_next_buffer(&video->queue, buf);
  544. video->last_fid ^= UVC_STREAM_FID;
  545. }
  546. video->bulk.header_size = 0;
  547. video->bulk.payload_size = 0;
  548. }
  549. urb->transfer_buffer_length = video->urb_size - len;
  550. }
  551. static void uvc_video_complete(struct urb *urb)
  552. {
  553. struct uvc_video_device *video = urb->context;
  554. struct uvc_video_queue *queue = &video->queue;
  555. struct uvc_buffer *buf = NULL;
  556. unsigned long flags;
  557. int ret;
  558. switch (urb->status) {
  559. case 0:
  560. break;
  561. default:
  562. uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
  563. "completion handler.\n", urb->status);
  564. case -ENOENT: /* usb_kill_urb() called. */
  565. if (video->frozen)
  566. return;
  567. case -ECONNRESET: /* usb_unlink_urb() called. */
  568. case -ESHUTDOWN: /* The endpoint is being disabled. */
  569. uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
  570. return;
  571. }
  572. spin_lock_irqsave(&queue->irqlock, flags);
  573. if (!list_empty(&queue->irqqueue))
  574. buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
  575. queue);
  576. spin_unlock_irqrestore(&queue->irqlock, flags);
  577. video->decode(urb, video, buf);
  578. if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
  579. uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
  580. ret);
  581. }
  582. }
  583. /*
  584. * Free transfer buffers.
  585. */
  586. static void uvc_free_urb_buffers(struct uvc_video_device *video)
  587. {
  588. unsigned int i;
  589. for (i = 0; i < UVC_URBS; ++i) {
  590. if (video->urb_buffer[i]) {
  591. usb_buffer_free(video->dev->udev, video->urb_size,
  592. video->urb_buffer[i], video->urb_dma[i]);
  593. video->urb_buffer[i] = NULL;
  594. }
  595. }
  596. video->urb_size = 0;
  597. }
  598. /*
  599. * Allocate transfer buffers. This function can be called with buffers
  600. * already allocated when resuming from suspend, in which case it will
  601. * return without touching the buffers.
  602. *
  603. * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
  604. * system is too low on memory try successively smaller numbers of packets
  605. * until allocation succeeds.
  606. *
  607. * Return the number of allocated packets on success or 0 when out of memory.
  608. */
  609. static int uvc_alloc_urb_buffers(struct uvc_video_device *video,
  610. unsigned int size, unsigned int psize, gfp_t gfp_flags)
  611. {
  612. unsigned int npackets;
  613. unsigned int i;
  614. /* Buffers are already allocated, bail out. */
  615. if (video->urb_size)
  616. return 0;
  617. /* Compute the number of packets. Bulk endpoints might transfer UVC
  618. * payloads accross multiple URBs.
  619. */
  620. npackets = DIV_ROUND_UP(size, psize);
  621. if (npackets > UVC_MAX_PACKETS)
  622. npackets = UVC_MAX_PACKETS;
  623. /* Retry allocations until one succeed. */
  624. for (; npackets > 1; npackets /= 2) {
  625. for (i = 0; i < UVC_URBS; ++i) {
  626. video->urb_buffer[i] = usb_buffer_alloc(
  627. video->dev->udev, psize * npackets,
  628. gfp_flags | __GFP_NOWARN, &video->urb_dma[i]);
  629. if (!video->urb_buffer[i]) {
  630. uvc_free_urb_buffers(video);
  631. break;
  632. }
  633. }
  634. if (i == UVC_URBS) {
  635. video->urb_size = psize * npackets;
  636. return npackets;
  637. }
  638. }
  639. return 0;
  640. }
  641. /*
  642. * Uninitialize isochronous/bulk URBs and free transfer buffers.
  643. */
  644. static void uvc_uninit_video(struct uvc_video_device *video, int free_buffers)
  645. {
  646. struct urb *urb;
  647. unsigned int i;
  648. for (i = 0; i < UVC_URBS; ++i) {
  649. if ((urb = video->urb[i]) == NULL)
  650. continue;
  651. usb_kill_urb(urb);
  652. usb_free_urb(urb);
  653. video->urb[i] = NULL;
  654. }
  655. if (free_buffers)
  656. uvc_free_urb_buffers(video);
  657. }
  658. /*
  659. * Initialize isochronous URBs and allocate transfer buffers. The packet size
  660. * is given by the endpoint.
  661. */
  662. static int uvc_init_video_isoc(struct uvc_video_device *video,
  663. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  664. {
  665. struct urb *urb;
  666. unsigned int npackets, i, j;
  667. u16 psize;
  668. u32 size;
  669. psize = le16_to_cpu(ep->desc.wMaxPacketSize);
  670. psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
  671. size = video->streaming->ctrl.dwMaxVideoFrameSize;
  672. npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
  673. if (npackets == 0)
  674. return -ENOMEM;
  675. size = npackets * psize;
  676. for (i = 0; i < UVC_URBS; ++i) {
  677. urb = usb_alloc_urb(npackets, gfp_flags);
  678. if (urb == NULL) {
  679. uvc_uninit_video(video, 1);
  680. return -ENOMEM;
  681. }
  682. urb->dev = video->dev->udev;
  683. urb->context = video;
  684. urb->pipe = usb_rcvisocpipe(video->dev->udev,
  685. ep->desc.bEndpointAddress);
  686. urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
  687. urb->interval = ep->desc.bInterval;
  688. urb->transfer_buffer = video->urb_buffer[i];
  689. urb->transfer_dma = video->urb_dma[i];
  690. urb->complete = uvc_video_complete;
  691. urb->number_of_packets = npackets;
  692. urb->transfer_buffer_length = size;
  693. for (j = 0; j < npackets; ++j) {
  694. urb->iso_frame_desc[j].offset = j * psize;
  695. urb->iso_frame_desc[j].length = psize;
  696. }
  697. video->urb[i] = urb;
  698. }
  699. return 0;
  700. }
  701. /*
  702. * Initialize bulk URBs and allocate transfer buffers. The packet size is
  703. * given by the endpoint.
  704. */
  705. static int uvc_init_video_bulk(struct uvc_video_device *video,
  706. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  707. {
  708. struct urb *urb;
  709. unsigned int npackets, pipe, i;
  710. u16 psize;
  711. u32 size;
  712. psize = le16_to_cpu(ep->desc.wMaxPacketSize) & 0x07ff;
  713. size = video->streaming->ctrl.dwMaxPayloadTransferSize;
  714. video->bulk.max_payload_size = size;
  715. npackets = uvc_alloc_urb_buffers(video, size, psize, gfp_flags);
  716. if (npackets == 0)
  717. return -ENOMEM;
  718. size = npackets * psize;
  719. if (usb_endpoint_dir_in(&ep->desc))
  720. pipe = usb_rcvbulkpipe(video->dev->udev,
  721. ep->desc.bEndpointAddress);
  722. else
  723. pipe = usb_sndbulkpipe(video->dev->udev,
  724. ep->desc.bEndpointAddress);
  725. if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
  726. size = 0;
  727. for (i = 0; i < UVC_URBS; ++i) {
  728. urb = usb_alloc_urb(0, gfp_flags);
  729. if (urb == NULL) {
  730. uvc_uninit_video(video, 1);
  731. return -ENOMEM;
  732. }
  733. usb_fill_bulk_urb(urb, video->dev->udev, pipe,
  734. video->urb_buffer[i], size, uvc_video_complete,
  735. video);
  736. urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  737. urb->transfer_dma = video->urb_dma[i];
  738. video->urb[i] = urb;
  739. }
  740. return 0;
  741. }
  742. /*
  743. * Initialize isochronous/bulk URBs and allocate transfer buffers.
  744. */
  745. static int uvc_init_video(struct uvc_video_device *video, gfp_t gfp_flags)
  746. {
  747. struct usb_interface *intf = video->streaming->intf;
  748. struct usb_host_interface *alts;
  749. struct usb_host_endpoint *ep = NULL;
  750. int intfnum = video->streaming->intfnum;
  751. unsigned int bandwidth, psize, i;
  752. int ret;
  753. video->last_fid = -1;
  754. video->bulk.header_size = 0;
  755. video->bulk.skip_payload = 0;
  756. video->bulk.payload_size = 0;
  757. if (intf->num_altsetting > 1) {
  758. /* Isochronous endpoint, select the alternate setting. */
  759. bandwidth = video->streaming->ctrl.dwMaxPayloadTransferSize;
  760. if (bandwidth == 0) {
  761. uvc_printk(KERN_WARNING, "device %s requested null "
  762. "bandwidth, defaulting to lowest.\n",
  763. video->vdev->name);
  764. bandwidth = 1;
  765. }
  766. for (i = 0; i < intf->num_altsetting; ++i) {
  767. alts = &intf->altsetting[i];
  768. ep = uvc_find_endpoint(alts,
  769. video->streaming->header.bEndpointAddress);
  770. if (ep == NULL)
  771. continue;
  772. /* Check if the bandwidth is high enough. */
  773. psize = le16_to_cpu(ep->desc.wMaxPacketSize);
  774. psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
  775. if (psize >= bandwidth)
  776. break;
  777. }
  778. if (i >= intf->num_altsetting)
  779. return -EIO;
  780. if ((ret = usb_set_interface(video->dev->udev, intfnum, i)) < 0)
  781. return ret;
  782. ret = uvc_init_video_isoc(video, ep, gfp_flags);
  783. } else {
  784. /* Bulk endpoint, proceed to URB initialization. */
  785. ep = uvc_find_endpoint(&intf->altsetting[0],
  786. video->streaming->header.bEndpointAddress);
  787. if (ep == NULL)
  788. return -EIO;
  789. ret = uvc_init_video_bulk(video, ep, gfp_flags);
  790. }
  791. if (ret < 0)
  792. return ret;
  793. /* Submit the URBs. */
  794. for (i = 0; i < UVC_URBS; ++i) {
  795. if ((ret = usb_submit_urb(video->urb[i], gfp_flags)) < 0) {
  796. uvc_printk(KERN_ERR, "Failed to submit URB %u "
  797. "(%d).\n", i, ret);
  798. uvc_uninit_video(video, 1);
  799. return ret;
  800. }
  801. }
  802. return 0;
  803. }
  804. /* --------------------------------------------------------------------------
  805. * Suspend/resume
  806. */
  807. /*
  808. * Stop streaming without disabling the video queue.
  809. *
  810. * To let userspace applications resume without trouble, we must not touch the
  811. * video buffers in any way. We mark the device as frozen to make sure the URB
  812. * completion handler won't try to cancel the queue when we kill the URBs.
  813. */
  814. int uvc_video_suspend(struct uvc_video_device *video)
  815. {
  816. if (!uvc_queue_streaming(&video->queue))
  817. return 0;
  818. video->frozen = 1;
  819. uvc_uninit_video(video, 0);
  820. usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
  821. return 0;
  822. }
  823. /*
  824. * Reconfigure the video interface and restart streaming if it was enabled
  825. * before suspend.
  826. *
  827. * If an error occurs, disable the video queue. This will wake all pending
  828. * buffers, making sure userspace applications are notified of the problem
  829. * instead of waiting forever.
  830. */
  831. int uvc_video_resume(struct uvc_video_device *video)
  832. {
  833. int ret;
  834. video->frozen = 0;
  835. if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0) {
  836. uvc_queue_enable(&video->queue, 0);
  837. return ret;
  838. }
  839. if (!uvc_queue_streaming(&video->queue))
  840. return 0;
  841. if ((ret = uvc_init_video(video, GFP_NOIO)) < 0)
  842. uvc_queue_enable(&video->queue, 0);
  843. return ret;
  844. }
  845. /* ------------------------------------------------------------------------
  846. * Video device
  847. */
  848. /*
  849. * Initialize the UVC video device by switching to alternate setting 0 and
  850. * retrieve the default format.
  851. *
  852. * Some cameras (namely the Fuji Finepix) set the format and frame
  853. * indexes to zero. The UVC standard doesn't clearly make this a spec
  854. * violation, so try to silently fix the values if possible.
  855. *
  856. * This function is called before registering the device with V4L.
  857. */
  858. int uvc_video_init(struct uvc_video_device *video)
  859. {
  860. struct uvc_streaming_control *probe = &video->streaming->ctrl;
  861. struct uvc_format *format = NULL;
  862. struct uvc_frame *frame = NULL;
  863. unsigned int i;
  864. int ret;
  865. if (video->streaming->nformats == 0) {
  866. uvc_printk(KERN_INFO, "No supported video formats found.\n");
  867. return -EINVAL;
  868. }
  869. /* Alternate setting 0 should be the default, yet the XBox Live Vision
  870. * Cam (and possibly other devices) crash or otherwise misbehave if
  871. * they don't receive a SET_INTERFACE request before any other video
  872. * control request.
  873. */
  874. usb_set_interface(video->dev->udev, video->streaming->intfnum, 0);
  875. /* Set the streaming probe control with default streaming parameters
  876. * retrieved from the device. Webcams that don't suport GET_DEF
  877. * requests on the probe control will just keep their current streaming
  878. * parameters.
  879. */
  880. if (uvc_get_video_ctrl(video, probe, 1, GET_DEF) == 0)
  881. uvc_set_video_ctrl(video, probe, 1);
  882. /* Initialize the streaming parameters with the probe control current
  883. * value. This makes sure SET_CUR requests on the streaming commit
  884. * control will always use values retrieved from a successful GET_CUR
  885. * request on the probe control, as required by the UVC specification.
  886. */
  887. if ((ret = uvc_get_video_ctrl(video, probe, 1, GET_CUR)) < 0)
  888. return ret;
  889. /* Check if the default format descriptor exists. Use the first
  890. * available format otherwise.
  891. */
  892. for (i = video->streaming->nformats; i > 0; --i) {
  893. format = &video->streaming->format[i-1];
  894. if (format->index == probe->bFormatIndex)
  895. break;
  896. }
  897. if (format->nframes == 0) {
  898. uvc_printk(KERN_INFO, "No frame descriptor found for the "
  899. "default format.\n");
  900. return -EINVAL;
  901. }
  902. /* Zero bFrameIndex might be correct. Stream-based formats (including
  903. * MPEG-2 TS and DV) do not support frames but have a dummy frame
  904. * descriptor with bFrameIndex set to zero. If the default frame
  905. * descriptor is not found, use the first avalable frame.
  906. */
  907. for (i = format->nframes; i > 0; --i) {
  908. frame = &format->frame[i-1];
  909. if (frame->bFrameIndex == probe->bFrameIndex)
  910. break;
  911. }
  912. probe->bFormatIndex = format->index;
  913. probe->bFrameIndex = frame->bFrameIndex;
  914. video->streaming->cur_format = format;
  915. video->streaming->cur_frame = frame;
  916. atomic_set(&video->active, 0);
  917. /* Select the video decoding function */
  918. if (video->streaming->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
  919. if (video->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
  920. video->decode = uvc_video_decode_isight;
  921. else if (video->streaming->intf->num_altsetting > 1)
  922. video->decode = uvc_video_decode_isoc;
  923. else
  924. video->decode = uvc_video_decode_bulk;
  925. } else {
  926. if (video->streaming->intf->num_altsetting == 1)
  927. video->decode = uvc_video_encode_bulk;
  928. else {
  929. uvc_printk(KERN_INFO, "Isochronous endpoints are not "
  930. "supported for video output devices.\n");
  931. return -EINVAL;
  932. }
  933. }
  934. return 0;
  935. }
  936. /*
  937. * Enable or disable the video stream.
  938. */
  939. int uvc_video_enable(struct uvc_video_device *video, int enable)
  940. {
  941. int ret;
  942. if (!enable) {
  943. uvc_uninit_video(video, 1);
  944. usb_set_interface(video->dev->udev,
  945. video->streaming->intfnum, 0);
  946. uvc_queue_enable(&video->queue, 0);
  947. return 0;
  948. }
  949. if ((video->streaming->cur_format->flags & UVC_FMT_FLAG_COMPRESSED) ||
  950. uvc_no_drop_param)
  951. video->queue.flags &= ~UVC_QUEUE_DROP_INCOMPLETE;
  952. else
  953. video->queue.flags |= UVC_QUEUE_DROP_INCOMPLETE;
  954. if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
  955. return ret;
  956. /* Commit the streaming parameters. */
  957. if ((ret = uvc_commit_video(video, &video->streaming->ctrl)) < 0)
  958. return ret;
  959. return uvc_init_video(video, GFP_KERNEL);
  960. }