uvc_video.c 33 KB

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