v4l2.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. /*
  2. * Copyright (c) 2000,2001 Fabrice Bellard
  3. * Copyright (c) 2006 Luca Abeni
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Video4Linux2 grab interface
  24. *
  25. * Part of this file is based on the V4L2 video capture example
  26. * (http://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
  27. *
  28. * Thanks to Michael Niedermayer for providing the mapping between
  29. * V4L2_PIX_FMT_* and AV_PIX_FMT_*
  30. */
  31. #include "v4l2-common.h"
  32. #if CONFIG_LIBV4L2
  33. #include <libv4l2.h>
  34. #endif
  35. static const int desired_video_buffers = 256;
  36. #define V4L_ALLFORMATS 3
  37. #define V4L_RAWFORMATS 1
  38. #define V4L_COMPFORMATS 2
  39. /**
  40. * Return timestamps to the user exactly as returned by the kernel
  41. */
  42. #define V4L_TS_DEFAULT 0
  43. /**
  44. * Autodetect the kind of timestamps returned by the kernel and convert to
  45. * absolute (wall clock) timestamps.
  46. */
  47. #define V4L_TS_ABS 1
  48. /**
  49. * Assume kernel timestamps are from the monotonic clock and convert to
  50. * absolute timestamps.
  51. */
  52. #define V4L_TS_MONO2ABS 2
  53. /**
  54. * Once the kind of timestamps returned by the kernel have been detected,
  55. * the value of the timefilter (NULL or not) determines whether a conversion
  56. * takes place.
  57. */
  58. #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
  59. struct video_data {
  60. AVClass *class;
  61. int fd;
  62. int frame_format; /* V4L2_PIX_FMT_* */
  63. int width, height;
  64. int frame_size;
  65. int interlaced;
  66. int top_field_first;
  67. int ts_mode;
  68. TimeFilter *timefilter;
  69. int64_t last_time_m;
  70. int buffers;
  71. volatile int buffers_queued;
  72. void **buf_start;
  73. unsigned int *buf_len;
  74. char *standard;
  75. v4l2_std_id std_id;
  76. int channel;
  77. char *pixel_format; /**< Set by a private option. */
  78. int list_format; /**< Set by a private option. */
  79. int list_standard; /**< Set by a private option. */
  80. char *framerate; /**< Set by a private option. */
  81. int use_libv4l2;
  82. int (*open_f)(const char *file, int oflag, ...);
  83. int (*close_f)(int fd);
  84. int (*dup_f)(int fd);
  85. int (*ioctl_f)(int fd, unsigned long int request, ...);
  86. ssize_t (*read_f)(int fd, void *buffer, size_t n);
  87. void *(*mmap_f)(void *start, size_t length, int prot, int flags, int fd, int64_t offset);
  88. int (*munmap_f)(void *_start, size_t length);
  89. };
  90. struct buff_data {
  91. struct video_data *s;
  92. int index;
  93. };
  94. static int device_open(AVFormatContext *ctx)
  95. {
  96. struct video_data *s = ctx->priv_data;
  97. struct v4l2_capability cap;
  98. int fd;
  99. int ret;
  100. int flags = O_RDWR;
  101. #define SET_WRAPPERS(prefix) do { \
  102. s->open_f = prefix ## open; \
  103. s->close_f = prefix ## close; \
  104. s->dup_f = prefix ## dup; \
  105. s->ioctl_f = prefix ## ioctl; \
  106. s->read_f = prefix ## read; \
  107. s->mmap_f = prefix ## mmap; \
  108. s->munmap_f = prefix ## munmap; \
  109. } while (0)
  110. if (s->use_libv4l2) {
  111. #if CONFIG_LIBV4L2
  112. SET_WRAPPERS(v4l2_);
  113. #else
  114. av_log(ctx, AV_LOG_ERROR, "libavdevice is not build with libv4l2 support.\n");
  115. return AVERROR(EINVAL);
  116. #endif
  117. } else {
  118. SET_WRAPPERS();
  119. }
  120. #define v4l2_open s->open_f
  121. #define v4l2_close s->close_f
  122. #define v4l2_dup s->dup_f
  123. #define v4l2_ioctl s->ioctl_f
  124. #define v4l2_read s->read_f
  125. #define v4l2_mmap s->mmap_f
  126. #define v4l2_munmap s->munmap_f
  127. if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
  128. flags |= O_NONBLOCK;
  129. }
  130. fd = v4l2_open(ctx->filename, flags, 0);
  131. if (fd < 0) {
  132. ret = AVERROR(errno);
  133. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
  134. ctx->filename, av_err2str(ret));
  135. return ret;
  136. }
  137. if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
  138. ret = AVERROR(errno);
  139. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  140. av_err2str(ret));
  141. goto fail;
  142. }
  143. av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
  144. fd, cap.capabilities);
  145. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  146. av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
  147. ret = AVERROR(ENODEV);
  148. goto fail;
  149. }
  150. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  151. av_log(ctx, AV_LOG_ERROR,
  152. "The device does not support the streaming I/O method.\n");
  153. ret = AVERROR(ENOSYS);
  154. goto fail;
  155. }
  156. return fd;
  157. fail:
  158. v4l2_close(fd);
  159. return ret;
  160. }
  161. static int device_init(AVFormatContext *ctx, int *width, int *height,
  162. uint32_t pix_fmt)
  163. {
  164. struct video_data *s = ctx->priv_data;
  165. int fd = s->fd;
  166. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  167. struct v4l2_pix_format *pix = &fmt.fmt.pix;
  168. int res = 0;
  169. pix->width = *width;
  170. pix->height = *height;
  171. pix->pixelformat = pix_fmt;
  172. pix->field = V4L2_FIELD_ANY;
  173. if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
  174. res = AVERROR(errno);
  175. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  176. av_log(ctx, AV_LOG_INFO,
  177. "The V4L2 driver changed the video from %dx%d to %dx%d\n",
  178. *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  179. *width = fmt.fmt.pix.width;
  180. *height = fmt.fmt.pix.height;
  181. }
  182. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  183. av_log(ctx, AV_LOG_DEBUG,
  184. "The V4L2 driver changed the pixel format "
  185. "from 0x%08X to 0x%08X\n",
  186. pix_fmt, fmt.fmt.pix.pixelformat);
  187. res = AVERROR(EINVAL);
  188. }
  189. if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
  190. av_log(ctx, AV_LOG_DEBUG,
  191. "The V4L2 driver is using the interlaced mode\n");
  192. s->interlaced = 1;
  193. }
  194. return res;
  195. }
  196. static int first_field(const struct video_data *s, int fd)
  197. {
  198. int res;
  199. v4l2_std_id std;
  200. res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
  201. if (res < 0) {
  202. return 0;
  203. }
  204. if (std & V4L2_STD_NTSC) {
  205. return 0;
  206. }
  207. return 1;
  208. }
  209. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  210. static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
  211. {
  212. const struct video_data *s = ctx->priv_data;
  213. struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
  214. while(!v4l2_ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
  215. switch (vfse.type) {
  216. case V4L2_FRMSIZE_TYPE_DISCRETE:
  217. av_log(ctx, AV_LOG_INFO, " %ux%u",
  218. vfse.discrete.width, vfse.discrete.height);
  219. break;
  220. case V4L2_FRMSIZE_TYPE_CONTINUOUS:
  221. case V4L2_FRMSIZE_TYPE_STEPWISE:
  222. av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
  223. vfse.stepwise.min_width,
  224. vfse.stepwise.max_width,
  225. vfse.stepwise.step_width,
  226. vfse.stepwise.min_height,
  227. vfse.stepwise.max_height,
  228. vfse.stepwise.step_height);
  229. }
  230. vfse.index++;
  231. }
  232. }
  233. #endif
  234. static void list_formats(AVFormatContext *ctx, int fd, int type)
  235. {
  236. const struct video_data *s = ctx->priv_data;
  237. struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  238. while(!v4l2_ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
  239. enum AVCodecID codec_id = avpriv_fmt_v4l2codec(vfd.pixelformat);
  240. enum AVPixelFormat pix_fmt = avpriv_fmt_v4l2ff(vfd.pixelformat, codec_id);
  241. vfd.index++;
  242. if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
  243. type & V4L_RAWFORMATS) {
  244. const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
  245. av_log(ctx, AV_LOG_INFO, "Raw : %9s : %20s :",
  246. fmt_name ? fmt_name : "Unsupported",
  247. vfd.description);
  248. } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
  249. type & V4L_COMPFORMATS) {
  250. AVCodec *codec = avcodec_find_decoder(codec_id);
  251. av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
  252. codec ? codec->name : "Unsupported",
  253. vfd.description);
  254. } else {
  255. continue;
  256. }
  257. #ifdef V4L2_FMT_FLAG_EMULATED
  258. if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
  259. av_log(ctx, AV_LOG_INFO, " Emulated :");
  260. #endif
  261. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  262. list_framesizes(ctx, fd, vfd.pixelformat);
  263. #endif
  264. av_log(ctx, AV_LOG_INFO, "\n");
  265. }
  266. }
  267. static void list_standards(AVFormatContext *ctx)
  268. {
  269. int ret;
  270. struct video_data *s = ctx->priv_data;
  271. struct v4l2_standard standard;
  272. if (s->std_id == 0)
  273. return;
  274. for (standard.index = 0; ; standard.index++) {
  275. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  276. ret = AVERROR(errno);
  277. if (ret == AVERROR(EINVAL)) {
  278. break;
  279. } else {
  280. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  281. return;
  282. }
  283. }
  284. av_log(ctx, AV_LOG_INFO, "%2d, %16"PRIx64", %s\n",
  285. standard.index, (uint64_t)standard.id, standard.name);
  286. }
  287. }
  288. static int mmap_init(AVFormatContext *ctx)
  289. {
  290. int i, res;
  291. struct video_data *s = ctx->priv_data;
  292. struct v4l2_requestbuffers req = {
  293. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  294. .count = desired_video_buffers,
  295. .memory = V4L2_MEMORY_MMAP
  296. };
  297. if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
  298. res = AVERROR(errno);
  299. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
  300. return res;
  301. }
  302. if (req.count < 2) {
  303. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  304. return AVERROR(ENOMEM);
  305. }
  306. s->buffers = req.count;
  307. s->buf_start = av_malloc(sizeof(void *) * s->buffers);
  308. if (s->buf_start == NULL) {
  309. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  310. return AVERROR(ENOMEM);
  311. }
  312. s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
  313. if (s->buf_len == NULL) {
  314. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  315. av_free(s->buf_start);
  316. return AVERROR(ENOMEM);
  317. }
  318. for (i = 0; i < req.count; i++) {
  319. struct v4l2_buffer buf = {
  320. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  321. .index = i,
  322. .memory = V4L2_MEMORY_MMAP
  323. };
  324. if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
  325. res = AVERROR(errno);
  326. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
  327. return res;
  328. }
  329. s->buf_len[i] = buf.length;
  330. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  331. av_log(ctx, AV_LOG_ERROR,
  332. "buf_len[%d] = %d < expected frame size %d\n",
  333. i, s->buf_len[i], s->frame_size);
  334. return AVERROR(ENOMEM);
  335. }
  336. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  337. PROT_READ | PROT_WRITE, MAP_SHARED,
  338. s->fd, buf.m.offset);
  339. if (s->buf_start[i] == MAP_FAILED) {
  340. res = AVERROR(errno);
  341. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
  342. return res;
  343. }
  344. }
  345. return 0;
  346. }
  347. #if FF_API_DESTRUCT_PACKET
  348. static void dummy_release_buffer(AVPacket *pkt)
  349. {
  350. av_assert0(0);
  351. }
  352. #endif
  353. static void mmap_release_buffer(void *opaque, uint8_t *data)
  354. {
  355. struct v4l2_buffer buf = { 0 };
  356. int res;
  357. struct buff_data *buf_descriptor = opaque;
  358. struct video_data *s = buf_descriptor->s;
  359. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  360. buf.memory = V4L2_MEMORY_MMAP;
  361. buf.index = buf_descriptor->index;
  362. av_free(buf_descriptor);
  363. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  364. res = AVERROR(errno);
  365. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  366. av_err2str(res));
  367. }
  368. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  369. }
  370. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  371. static int64_t av_gettime_monotonic(void)
  372. {
  373. struct timespec tv;
  374. clock_gettime(CLOCK_MONOTONIC, &tv);
  375. return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
  376. }
  377. #endif
  378. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  379. {
  380. struct video_data *s = ctx->priv_data;
  381. int64_t now;
  382. now = av_gettime();
  383. if (s->ts_mode == V4L_TS_ABS &&
  384. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  385. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  386. s->ts_mode = V4L_TS_CONVERT_READY;
  387. return 0;
  388. }
  389. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  390. if (ctx->streams[0]->avg_frame_rate.num) {
  391. now = av_gettime_monotonic();
  392. if (s->ts_mode == V4L_TS_MONO2ABS ||
  393. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  394. AVRational tb = {AV_TIME_BASE, 1};
  395. int64_t period = av_rescale_q(1, tb, ctx->streams[0]->avg_frame_rate);
  396. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  397. /* microseconds instead of seconds, MHz instead of Hz */
  398. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  399. if (!s->timefilter)
  400. return AVERROR(ENOMEM);
  401. s->ts_mode = V4L_TS_CONVERT_READY;
  402. return 0;
  403. }
  404. }
  405. #endif
  406. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  407. return AVERROR(EIO);
  408. }
  409. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  410. {
  411. struct video_data *s = ctx->priv_data;
  412. if (s->ts_mode) {
  413. int r = init_convert_timestamp(ctx, *ts);
  414. if (r < 0)
  415. return r;
  416. }
  417. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  418. if (s->timefilter) {
  419. int64_t nowa = av_gettime();
  420. int64_t nowm = av_gettime_monotonic();
  421. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  422. s->last_time_m = nowm;
  423. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  424. }
  425. #endif
  426. return 0;
  427. }
  428. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  429. {
  430. struct video_data *s = ctx->priv_data;
  431. struct v4l2_buffer buf = {
  432. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  433. .memory = V4L2_MEMORY_MMAP
  434. };
  435. int res;
  436. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  437. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  438. if (res < 0) {
  439. if (errno == EAGAIN) {
  440. pkt->size = 0;
  441. return AVERROR(EAGAIN);
  442. }
  443. res = AVERROR(errno);
  444. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
  445. return res;
  446. }
  447. if (buf.index >= s->buffers) {
  448. av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
  449. return AVERROR(EINVAL);
  450. }
  451. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
  452. // always keep at least one buffer queued
  453. av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
  454. /* CPIA is a compressed format and we don't know the exact number of bytes
  455. * used by a frame, so set it here as the driver announces it.
  456. */
  457. if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
  458. s->frame_size = buf.bytesused;
  459. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  460. av_log(ctx, AV_LOG_ERROR,
  461. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  462. buf.bytesused, s->frame_size);
  463. return AVERROR_INVALIDDATA;
  464. }
  465. /* Image is at s->buff_start[buf.index] */
  466. if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
  467. /* when we start getting low on queued buffers, fall back on copying data */
  468. res = av_new_packet(pkt, buf.bytesused);
  469. if (res < 0) {
  470. av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
  471. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  472. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  473. return res;
  474. }
  475. memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
  476. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  477. res = AVERROR(errno);
  478. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  479. av_free_packet(pkt);
  480. return res;
  481. }
  482. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  483. } else {
  484. struct buff_data *buf_descriptor;
  485. pkt->data = s->buf_start[buf.index];
  486. pkt->size = buf.bytesused;
  487. #if FF_API_DESTRUCT_PACKET
  488. FF_DISABLE_DEPRECATION_WARNINGS
  489. pkt->destruct = dummy_release_buffer;
  490. FF_ENABLE_DEPRECATION_WARNINGS
  491. #endif
  492. buf_descriptor = av_malloc(sizeof(struct buff_data));
  493. if (buf_descriptor == NULL) {
  494. /* Something went wrong... Since av_malloc() failed, we cannot even
  495. * allocate a buffer for memcpying into it
  496. */
  497. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  498. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  499. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  500. return AVERROR(ENOMEM);
  501. }
  502. buf_descriptor->index = buf.index;
  503. buf_descriptor->s = s;
  504. pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
  505. buf_descriptor, 0);
  506. if (!pkt->buf) {
  507. av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
  508. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  509. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  510. av_freep(&buf_descriptor);
  511. return AVERROR(ENOMEM);
  512. }
  513. }
  514. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  515. convert_timestamp(ctx, &pkt->pts);
  516. return s->buf_len[buf.index];
  517. }
  518. static int mmap_start(AVFormatContext *ctx)
  519. {
  520. struct video_data *s = ctx->priv_data;
  521. enum v4l2_buf_type type;
  522. int i, res;
  523. for (i = 0; i < s->buffers; i++) {
  524. struct v4l2_buffer buf = {
  525. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  526. .index = i,
  527. .memory = V4L2_MEMORY_MMAP
  528. };
  529. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  530. res = AVERROR(errno);
  531. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  532. return res;
  533. }
  534. }
  535. s->buffers_queued = s->buffers;
  536. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  537. if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
  538. res = AVERROR(errno);
  539. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
  540. return res;
  541. }
  542. return 0;
  543. }
  544. static void mmap_close(struct video_data *s)
  545. {
  546. enum v4l2_buf_type type;
  547. int i;
  548. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  549. /* We do not check for the result, because we could
  550. * not do anything about it anyway...
  551. */
  552. v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  553. for (i = 0; i < s->buffers; i++) {
  554. v4l2_munmap(s->buf_start[i], s->buf_len[i]);
  555. }
  556. av_free(s->buf_start);
  557. av_free(s->buf_len);
  558. }
  559. static int v4l2_set_parameters(AVFormatContext *s1)
  560. {
  561. struct video_data *s = s1->priv_data;
  562. struct v4l2_standard standard = { 0 };
  563. struct v4l2_streamparm streamparm = { 0 };
  564. struct v4l2_fract *tpf;
  565. AVRational framerate_q = { 0 };
  566. int i, ret;
  567. if (s->framerate &&
  568. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  569. av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  570. s->framerate);
  571. return ret;
  572. }
  573. if (s->standard) {
  574. if (s->std_id) {
  575. ret = 0;
  576. av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
  577. /* set tv standard */
  578. for (i = 0; ; i++) {
  579. standard.index = i;
  580. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  581. ret = AVERROR(errno);
  582. break;
  583. }
  584. if (!av_strcasecmp(standard.name, s->standard))
  585. break;
  586. }
  587. if (ret < 0) {
  588. av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
  589. return ret;
  590. }
  591. if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  592. ret = AVERROR(errno);
  593. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
  594. return ret;
  595. }
  596. } else {
  597. av_log(s1, AV_LOG_WARNING,
  598. "This device does not support any standard\n");
  599. }
  600. }
  601. /* get standard */
  602. if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
  603. tpf = &standard.frameperiod;
  604. for (i = 0; ; i++) {
  605. standard.index = i;
  606. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  607. ret = AVERROR(errno);
  608. if (ret == AVERROR(EINVAL)) {
  609. tpf = &streamparm.parm.capture.timeperframe;
  610. break;
  611. }
  612. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  613. return ret;
  614. }
  615. if (standard.id == s->std_id) {
  616. av_log(s1, AV_LOG_DEBUG,
  617. "Current standard: %s, id: %"PRIx64", frameperiod: %d/%d\n",
  618. standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
  619. break;
  620. }
  621. }
  622. } else {
  623. tpf = &streamparm.parm.capture.timeperframe;
  624. }
  625. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  626. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
  627. ret = AVERROR(errno);
  628. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
  629. return ret;
  630. }
  631. if (framerate_q.num && framerate_q.den) {
  632. if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
  633. tpf = &streamparm.parm.capture.timeperframe;
  634. av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  635. framerate_q.den, framerate_q.num);
  636. tpf->numerator = framerate_q.den;
  637. tpf->denominator = framerate_q.num;
  638. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
  639. ret = AVERROR(errno);
  640. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
  641. return ret;
  642. }
  643. if (framerate_q.num != tpf->denominator ||
  644. framerate_q.den != tpf->numerator) {
  645. av_log(s1, AV_LOG_INFO,
  646. "The driver changed the time per frame from "
  647. "%d/%d to %d/%d\n",
  648. framerate_q.den, framerate_q.num,
  649. tpf->numerator, tpf->denominator);
  650. }
  651. } else {
  652. av_log(s1, AV_LOG_WARNING,
  653. "The driver does not allow to change time per frame\n");
  654. }
  655. }
  656. if (tpf->denominator > 0 && tpf->numerator > 0) {
  657. s1->streams[0]->avg_frame_rate.num = tpf->denominator;
  658. s1->streams[0]->avg_frame_rate.den = tpf->numerator;
  659. s1->streams[0]->r_frame_rate = s1->streams[0]->avg_frame_rate;
  660. } else
  661. av_log(s1, AV_LOG_WARNING, "Time per frame unknown\n");
  662. return 0;
  663. }
  664. static int device_try_init(AVFormatContext *s1,
  665. enum AVPixelFormat pix_fmt,
  666. int *width,
  667. int *height,
  668. uint32_t *desired_format,
  669. enum AVCodecID *codec_id)
  670. {
  671. int ret, i;
  672. *desired_format = avpriv_fmt_ff2v4l(pix_fmt, s1->video_codec_id);
  673. if (*desired_format) {
  674. ret = device_init(s1, width, height, *desired_format);
  675. if (ret < 0) {
  676. *desired_format = 0;
  677. if (ret != AVERROR(EINVAL))
  678. return ret;
  679. }
  680. }
  681. if (!*desired_format) {
  682. for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {
  683. if (s1->video_codec_id == AV_CODEC_ID_NONE ||
  684. avpriv_fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  685. av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
  686. avcodec_get_name(avpriv_fmt_conversion_table[i].codec_id),
  687. (char *)av_x_if_null(av_get_pix_fmt_name(avpriv_fmt_conversion_table[i].ff_fmt), "none"));
  688. *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;
  689. ret = device_init(s1, width, height, *desired_format);
  690. if (ret >= 0)
  691. break;
  692. else if (ret != AVERROR(EINVAL))
  693. return ret;
  694. *desired_format = 0;
  695. }
  696. }
  697. if (*desired_format == 0) {
  698. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  699. "codec '%s' (id %d), pixel format '%s' (id %d)\n",
  700. avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
  701. (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
  702. ret = AVERROR(EINVAL);
  703. }
  704. }
  705. *codec_id = avpriv_fmt_v4l2codec(*desired_format);
  706. av_assert0(*codec_id != AV_CODEC_ID_NONE);
  707. return ret;
  708. }
  709. static int v4l2_read_header(AVFormatContext *s1)
  710. {
  711. struct video_data *s = s1->priv_data;
  712. AVStream *st;
  713. int res = 0;
  714. uint32_t desired_format;
  715. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  716. enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
  717. struct v4l2_input input = { 0 };
  718. st = avformat_new_stream(s1, NULL);
  719. if (!st)
  720. return AVERROR(ENOMEM);
  721. #if CONFIG_LIBV4L2
  722. /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
  723. and errors will get sent to stderr */
  724. if (s->use_libv4l2)
  725. v4l2_log_file = fopen("/dev/null", "w");
  726. #endif
  727. s->fd = device_open(s1);
  728. if (s->fd < 0)
  729. return s->fd;
  730. if (s->channel != -1) {
  731. /* set video input */
  732. av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
  733. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
  734. res = AVERROR(errno);
  735. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
  736. return res;
  737. }
  738. } else {
  739. /* get current video input */
  740. if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
  741. res = AVERROR(errno);
  742. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
  743. return res;
  744. }
  745. }
  746. /* enum input */
  747. input.index = s->channel;
  748. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  749. res = AVERROR(errno);
  750. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
  751. return res;
  752. }
  753. s->std_id = input.std;
  754. av_log(s1, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s, input_std: %"PRIx64"\n",
  755. s->channel, input.name, (uint64_t)input.std);
  756. if (s->list_format) {
  757. list_formats(s1, s->fd, s->list_format);
  758. return AVERROR_EXIT;
  759. }
  760. if (s->list_standard) {
  761. list_standards(s1);
  762. return AVERROR_EXIT;
  763. }
  764. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  765. if (s->pixel_format) {
  766. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  767. if (codec)
  768. s1->video_codec_id = codec->id;
  769. pix_fmt = av_get_pix_fmt(s->pixel_format);
  770. if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
  771. av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
  772. s->pixel_format);
  773. return AVERROR(EINVAL);
  774. }
  775. }
  776. if (!s->width && !s->height) {
  777. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  778. av_log(s1, AV_LOG_VERBOSE,
  779. "Querying the device for the current frame size\n");
  780. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  781. res = AVERROR(errno);
  782. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
  783. return res;
  784. }
  785. s->width = fmt.fmt.pix.width;
  786. s->height = fmt.fmt.pix.height;
  787. av_log(s1, AV_LOG_VERBOSE,
  788. "Setting frame size to %dx%d\n", s->width, s->height);
  789. }
  790. res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
  791. if (res < 0) {
  792. v4l2_close(s->fd);
  793. return res;
  794. }
  795. /* If no pixel_format was specified, the codec_id was not known up
  796. * until now. Set video_codec_id in the context, as codec_id will
  797. * not be available outside this function
  798. */
  799. if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
  800. s1->video_codec_id = codec_id;
  801. if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
  802. return res;
  803. s->frame_format = desired_format;
  804. if ((res = v4l2_set_parameters(s1)) < 0)
  805. return res;
  806. st->codec->pix_fmt = avpriv_fmt_v4l2ff(desired_format, codec_id);
  807. s->frame_size =
  808. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  809. if ((res = mmap_init(s1)) ||
  810. (res = mmap_start(s1)) < 0) {
  811. v4l2_close(s->fd);
  812. return res;
  813. }
  814. s->top_field_first = first_field(s, s->fd);
  815. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  816. st->codec->codec_id = codec_id;
  817. if (codec_id == AV_CODEC_ID_RAWVIDEO)
  818. st->codec->codec_tag =
  819. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  820. else if (codec_id == AV_CODEC_ID_H264) {
  821. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  822. }
  823. if (desired_format == V4L2_PIX_FMT_YVU420)
  824. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  825. else if (desired_format == V4L2_PIX_FMT_YVU410)
  826. st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
  827. st->codec->width = s->width;
  828. st->codec->height = s->height;
  829. if (st->avg_frame_rate.den)
  830. st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
  831. return 0;
  832. }
  833. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  834. {
  835. struct video_data *s = s1->priv_data;
  836. AVFrame *frame = s1->streams[0]->codec->coded_frame;
  837. int res;
  838. av_init_packet(pkt);
  839. if ((res = mmap_read_frame(s1, pkt)) < 0) {
  840. return res;
  841. }
  842. if (frame && s->interlaced) {
  843. frame->interlaced_frame = 1;
  844. frame->top_field_first = s->top_field_first;
  845. }
  846. return pkt->size;
  847. }
  848. static int v4l2_read_close(AVFormatContext *s1)
  849. {
  850. struct video_data *s = s1->priv_data;
  851. if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
  852. av_log(s1, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
  853. "close.\n");
  854. mmap_close(s);
  855. v4l2_close(s->fd);
  856. return 0;
  857. }
  858. #define OFFSET(x) offsetof(struct video_data, x)
  859. #define DEC AV_OPT_FLAG_DECODING_PARAM
  860. static const AVOption options[] = {
  861. { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  862. { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
  863. { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  864. { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  865. { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  866. { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  867. { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
  868. { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  869. { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  870. { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  871. { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
  872. { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
  873. { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  874. { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  875. { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  876. { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  877. { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  878. { "use_libv4l2", "use libv4l2 (v4l-utils) convertion functions", OFFSET(use_libv4l2), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  879. { NULL },
  880. };
  881. static const AVClass v4l2_class = {
  882. .class_name = "V4L2 indev",
  883. .item_name = av_default_item_name,
  884. .option = options,
  885. .version = LIBAVUTIL_VERSION_INT,
  886. };
  887. AVInputFormat ff_v4l2_demuxer = {
  888. .name = "video4linux2,v4l2",
  889. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  890. .priv_data_size = sizeof(struct video_data),
  891. .read_header = v4l2_read_header,
  892. .read_packet = v4l2_read_packet,
  893. .read_close = v4l2_read_close,
  894. .flags = AVFMT_NOFILE,
  895. .priv_class = &v4l2_class,
  896. };