uvc_video.c 33 KB

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