uvc_video.c 33 KB

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