uvc_video.c 33 KB

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