uvc_video.c 33 KB

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