You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1039 lines
35KB

  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. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  166. struct v4l2_pix_format *pix = &fmt.fmt.pix;
  167. int res = 0;
  168. pix->width = *width;
  169. pix->height = *height;
  170. pix->pixelformat = pix_fmt;
  171. pix->field = V4L2_FIELD_ANY;
  172. if (v4l2_ioctl(s->fd, VIDIOC_S_FMT, &fmt) < 0)
  173. res = AVERROR(errno);
  174. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  175. av_log(ctx, AV_LOG_INFO,
  176. "The V4L2 driver changed the video from %dx%d to %dx%d\n",
  177. *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  178. *width = fmt.fmt.pix.width;
  179. *height = fmt.fmt.pix.height;
  180. }
  181. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  182. av_log(ctx, AV_LOG_DEBUG,
  183. "The V4L2 driver changed the pixel format "
  184. "from 0x%08X to 0x%08X\n",
  185. pix_fmt, fmt.fmt.pix.pixelformat);
  186. res = AVERROR(EINVAL);
  187. }
  188. if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
  189. av_log(ctx, AV_LOG_DEBUG,
  190. "The V4L2 driver is using the interlaced mode\n");
  191. s->interlaced = 1;
  192. }
  193. return res;
  194. }
  195. static int first_field(const struct video_data *s)
  196. {
  197. int res;
  198. v4l2_std_id std;
  199. res = v4l2_ioctl(s->fd, VIDIOC_G_STD, &std);
  200. if (res < 0)
  201. return 0;
  202. if (std & V4L2_STD_NTSC)
  203. return 0;
  204. return 1;
  205. }
  206. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  207. static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
  208. {
  209. const struct video_data *s = ctx->priv_data;
  210. struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
  211. while(!v4l2_ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
  212. switch (vfse.type) {
  213. case V4L2_FRMSIZE_TYPE_DISCRETE:
  214. av_log(ctx, AV_LOG_INFO, " %ux%u",
  215. vfse.discrete.width, vfse.discrete.height);
  216. break;
  217. case V4L2_FRMSIZE_TYPE_CONTINUOUS:
  218. case V4L2_FRMSIZE_TYPE_STEPWISE:
  219. av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
  220. vfse.stepwise.min_width,
  221. vfse.stepwise.max_width,
  222. vfse.stepwise.step_width,
  223. vfse.stepwise.min_height,
  224. vfse.stepwise.max_height,
  225. vfse.stepwise.step_height);
  226. }
  227. vfse.index++;
  228. }
  229. }
  230. #endif
  231. static void list_formats(AVFormatContext *ctx, int fd, int type)
  232. {
  233. const struct video_data *s = ctx->priv_data;
  234. struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  235. while(!v4l2_ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
  236. enum AVCodecID codec_id = avpriv_fmt_v4l2codec(vfd.pixelformat);
  237. enum AVPixelFormat pix_fmt = avpriv_fmt_v4l2ff(vfd.pixelformat, codec_id);
  238. vfd.index++;
  239. if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
  240. type & V4L_RAWFORMATS) {
  241. const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
  242. av_log(ctx, AV_LOG_INFO, "Raw : %9s : %20s :",
  243. fmt_name ? fmt_name : "Unsupported",
  244. vfd.description);
  245. } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
  246. type & V4L_COMPFORMATS) {
  247. AVCodec *codec = avcodec_find_decoder(codec_id);
  248. av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
  249. codec ? codec->name : "Unsupported",
  250. vfd.description);
  251. } else {
  252. continue;
  253. }
  254. #ifdef V4L2_FMT_FLAG_EMULATED
  255. if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
  256. av_log(ctx, AV_LOG_INFO, " Emulated :");
  257. #endif
  258. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  259. list_framesizes(ctx, fd, vfd.pixelformat);
  260. #endif
  261. av_log(ctx, AV_LOG_INFO, "\n");
  262. }
  263. }
  264. static void list_standards(AVFormatContext *ctx)
  265. {
  266. int ret;
  267. struct video_data *s = ctx->priv_data;
  268. struct v4l2_standard standard;
  269. if (s->std_id == 0)
  270. return;
  271. for (standard.index = 0; ; standard.index++) {
  272. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  273. ret = AVERROR(errno);
  274. if (ret == AVERROR(EINVAL)) {
  275. break;
  276. } else {
  277. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  278. return;
  279. }
  280. }
  281. av_log(ctx, AV_LOG_INFO, "%2d, %16"PRIx64", %s\n",
  282. standard.index, (uint64_t)standard.id, standard.name);
  283. }
  284. }
  285. static int mmap_init(AVFormatContext *ctx)
  286. {
  287. int i, res;
  288. struct video_data *s = ctx->priv_data;
  289. struct v4l2_requestbuffers req = {
  290. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  291. .count = desired_video_buffers,
  292. .memory = V4L2_MEMORY_MMAP
  293. };
  294. if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
  295. res = AVERROR(errno);
  296. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
  297. return res;
  298. }
  299. if (req.count < 2) {
  300. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  301. return AVERROR(ENOMEM);
  302. }
  303. s->buffers = req.count;
  304. s->buf_start = av_malloc_array(s->buffers, sizeof(void *));
  305. if (!s->buf_start) {
  306. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  307. return AVERROR(ENOMEM);
  308. }
  309. s->buf_len = av_malloc_array(s->buffers, sizeof(unsigned int));
  310. if (!s->buf_len) {
  311. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  312. av_free(s->buf_start);
  313. return AVERROR(ENOMEM);
  314. }
  315. for (i = 0; i < req.count; i++) {
  316. struct v4l2_buffer buf = {
  317. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  318. .index = i,
  319. .memory = V4L2_MEMORY_MMAP
  320. };
  321. if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
  322. res = AVERROR(errno);
  323. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
  324. return res;
  325. }
  326. s->buf_len[i] = buf.length;
  327. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  328. av_log(ctx, AV_LOG_ERROR,
  329. "buf_len[%d] = %d < expected frame size %d\n",
  330. i, s->buf_len[i], s->frame_size);
  331. return AVERROR(ENOMEM);
  332. }
  333. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  334. PROT_READ | PROT_WRITE, MAP_SHARED,
  335. s->fd, buf.m.offset);
  336. if (s->buf_start[i] == MAP_FAILED) {
  337. res = AVERROR(errno);
  338. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
  339. return res;
  340. }
  341. }
  342. return 0;
  343. }
  344. #if FF_API_DESTRUCT_PACKET
  345. static void dummy_release_buffer(AVPacket *pkt)
  346. {
  347. av_assert0(0);
  348. }
  349. #endif
  350. static void mmap_release_buffer(void *opaque, uint8_t *data)
  351. {
  352. struct v4l2_buffer buf = { 0 };
  353. int res;
  354. struct buff_data *buf_descriptor = opaque;
  355. struct video_data *s = buf_descriptor->s;
  356. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  357. buf.memory = V4L2_MEMORY_MMAP;
  358. buf.index = buf_descriptor->index;
  359. av_free(buf_descriptor);
  360. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  361. res = AVERROR(errno);
  362. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  363. av_err2str(res));
  364. }
  365. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  366. }
  367. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  368. static int64_t av_gettime_monotonic(void)
  369. {
  370. return av_gettime_relative();
  371. }
  372. #endif
  373. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  374. {
  375. struct video_data *s = ctx->priv_data;
  376. int64_t now;
  377. now = av_gettime();
  378. if (s->ts_mode == V4L_TS_ABS &&
  379. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  380. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  381. s->ts_mode = V4L_TS_CONVERT_READY;
  382. return 0;
  383. }
  384. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  385. if (ctx->streams[0]->avg_frame_rate.num) {
  386. now = av_gettime_monotonic();
  387. if (s->ts_mode == V4L_TS_MONO2ABS ||
  388. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  389. AVRational tb = {AV_TIME_BASE, 1};
  390. int64_t period = av_rescale_q(1, tb, ctx->streams[0]->avg_frame_rate);
  391. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  392. /* microseconds instead of seconds, MHz instead of Hz */
  393. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  394. if (!s->timefilter)
  395. return AVERROR(ENOMEM);
  396. s->ts_mode = V4L_TS_CONVERT_READY;
  397. return 0;
  398. }
  399. }
  400. #endif
  401. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  402. return AVERROR(EIO);
  403. }
  404. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  405. {
  406. struct video_data *s = ctx->priv_data;
  407. if (s->ts_mode) {
  408. int r = init_convert_timestamp(ctx, *ts);
  409. if (r < 0)
  410. return r;
  411. }
  412. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  413. if (s->timefilter) {
  414. int64_t nowa = av_gettime();
  415. int64_t nowm = av_gettime_monotonic();
  416. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  417. s->last_time_m = nowm;
  418. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  419. }
  420. #endif
  421. return 0;
  422. }
  423. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  424. {
  425. struct video_data *s = ctx->priv_data;
  426. struct v4l2_buffer buf = {
  427. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  428. .memory = V4L2_MEMORY_MMAP
  429. };
  430. int res;
  431. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  432. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  433. if (res < 0) {
  434. if (errno == EAGAIN) {
  435. pkt->size = 0;
  436. return AVERROR(EAGAIN);
  437. }
  438. res = AVERROR(errno);
  439. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
  440. return res;
  441. }
  442. if (buf.index >= s->buffers) {
  443. av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
  444. return AVERROR(EINVAL);
  445. }
  446. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
  447. // always keep at least one buffer queued
  448. av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
  449. /* CPIA is a compressed format and we don't know the exact number of bytes
  450. * used by a frame, so set it here as the driver announces it.
  451. */
  452. if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
  453. s->frame_size = buf.bytesused;
  454. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  455. av_log(ctx, AV_LOG_ERROR,
  456. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  457. buf.bytesused, s->frame_size);
  458. return AVERROR_INVALIDDATA;
  459. }
  460. /* Image is at s->buff_start[buf.index] */
  461. if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
  462. /* when we start getting low on queued buffers, fall back on copying data */
  463. res = av_new_packet(pkt, buf.bytesused);
  464. if (res < 0) {
  465. av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
  466. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  467. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  468. return res;
  469. }
  470. memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
  471. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  472. res = AVERROR(errno);
  473. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  474. av_free_packet(pkt);
  475. return res;
  476. }
  477. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  478. } else {
  479. struct buff_data *buf_descriptor;
  480. pkt->data = s->buf_start[buf.index];
  481. pkt->size = buf.bytesused;
  482. #if FF_API_DESTRUCT_PACKET
  483. FF_DISABLE_DEPRECATION_WARNINGS
  484. pkt->destruct = dummy_release_buffer;
  485. FF_ENABLE_DEPRECATION_WARNINGS
  486. #endif
  487. buf_descriptor = av_malloc(sizeof(struct buff_data));
  488. if (!buf_descriptor) {
  489. /* Something went wrong... Since av_malloc() failed, we cannot even
  490. * allocate a buffer for memcpying into it
  491. */
  492. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  493. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  494. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  495. return AVERROR(ENOMEM);
  496. }
  497. buf_descriptor->index = buf.index;
  498. buf_descriptor->s = s;
  499. pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
  500. buf_descriptor, 0);
  501. if (!pkt->buf) {
  502. av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
  503. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  504. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  505. av_freep(&buf_descriptor);
  506. return AVERROR(ENOMEM);
  507. }
  508. }
  509. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  510. convert_timestamp(ctx, &pkt->pts);
  511. return s->buf_len[buf.index];
  512. }
  513. static int mmap_start(AVFormatContext *ctx)
  514. {
  515. struct video_data *s = ctx->priv_data;
  516. enum v4l2_buf_type type;
  517. int i, res;
  518. for (i = 0; i < s->buffers; i++) {
  519. struct v4l2_buffer buf = {
  520. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  521. .index = i,
  522. .memory = V4L2_MEMORY_MMAP
  523. };
  524. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  525. res = AVERROR(errno);
  526. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  527. return res;
  528. }
  529. }
  530. s->buffers_queued = s->buffers;
  531. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  532. if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
  533. res = AVERROR(errno);
  534. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
  535. return res;
  536. }
  537. return 0;
  538. }
  539. static void mmap_close(struct video_data *s)
  540. {
  541. enum v4l2_buf_type type;
  542. int i;
  543. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  544. /* We do not check for the result, because we could
  545. * not do anything about it anyway...
  546. */
  547. v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  548. for (i = 0; i < s->buffers; i++) {
  549. v4l2_munmap(s->buf_start[i], s->buf_len[i]);
  550. }
  551. av_free(s->buf_start);
  552. av_free(s->buf_len);
  553. }
  554. static int v4l2_set_parameters(AVFormatContext *ctx)
  555. {
  556. struct video_data *s = ctx->priv_data;
  557. struct v4l2_standard standard = { 0 };
  558. struct v4l2_streamparm streamparm = { 0 };
  559. struct v4l2_fract *tpf;
  560. AVRational framerate_q = { 0 };
  561. int i, ret;
  562. if (s->framerate &&
  563. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  564. av_log(ctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  565. s->framerate);
  566. return ret;
  567. }
  568. if (s->standard) {
  569. if (s->std_id) {
  570. ret = 0;
  571. av_log(ctx, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
  572. /* set tv standard */
  573. for (i = 0; ; i++) {
  574. standard.index = i;
  575. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  576. ret = AVERROR(errno);
  577. break;
  578. }
  579. if (!av_strcasecmp(standard.name, s->standard))
  580. break;
  581. }
  582. if (ret < 0) {
  583. av_log(ctx, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
  584. return ret;
  585. }
  586. if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  587. ret = AVERROR(errno);
  588. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
  589. return ret;
  590. }
  591. } else {
  592. av_log(ctx, AV_LOG_WARNING,
  593. "This device does not support any standard\n");
  594. }
  595. }
  596. /* get standard */
  597. if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
  598. tpf = &standard.frameperiod;
  599. for (i = 0; ; i++) {
  600. standard.index = i;
  601. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  602. ret = AVERROR(errno);
  603. if (ret == AVERROR(EINVAL)
  604. #ifdef ENODATA
  605. || ret == AVERROR(ENODATA)
  606. #endif
  607. ) {
  608. tpf = &streamparm.parm.capture.timeperframe;
  609. break;
  610. }
  611. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  612. return ret;
  613. }
  614. if (standard.id == s->std_id) {
  615. av_log(ctx, AV_LOG_DEBUG,
  616. "Current standard: %s, id: %"PRIx64", frameperiod: %d/%d\n",
  617. standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
  618. break;
  619. }
  620. }
  621. } else {
  622. tpf = &streamparm.parm.capture.timeperframe;
  623. }
  624. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  625. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
  626. ret = AVERROR(errno);
  627. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
  628. return ret;
  629. }
  630. if (framerate_q.num && framerate_q.den) {
  631. if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
  632. tpf = &streamparm.parm.capture.timeperframe;
  633. av_log(ctx, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  634. framerate_q.den, framerate_q.num);
  635. tpf->numerator = framerate_q.den;
  636. tpf->denominator = framerate_q.num;
  637. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
  638. ret = AVERROR(errno);
  639. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
  640. return ret;
  641. }
  642. if (framerate_q.num != tpf->denominator ||
  643. framerate_q.den != tpf->numerator) {
  644. av_log(ctx, AV_LOG_INFO,
  645. "The driver changed the time per frame from "
  646. "%d/%d to %d/%d\n",
  647. framerate_q.den, framerate_q.num,
  648. tpf->numerator, tpf->denominator);
  649. }
  650. } else {
  651. av_log(ctx, AV_LOG_WARNING,
  652. "The driver does not allow to change time per frame\n");
  653. }
  654. }
  655. if (tpf->denominator > 0 && tpf->numerator > 0) {
  656. ctx->streams[0]->avg_frame_rate.num = tpf->denominator;
  657. ctx->streams[0]->avg_frame_rate.den = tpf->numerator;
  658. ctx->streams[0]->r_frame_rate = ctx->streams[0]->avg_frame_rate;
  659. } else
  660. av_log(ctx, AV_LOG_WARNING, "Time per frame unknown\n");
  661. return 0;
  662. }
  663. static int device_try_init(AVFormatContext *ctx,
  664. enum AVPixelFormat pix_fmt,
  665. int *width,
  666. int *height,
  667. uint32_t *desired_format,
  668. enum AVCodecID *codec_id)
  669. {
  670. int ret, i;
  671. *desired_format = avpriv_fmt_ff2v4l(pix_fmt, ctx->video_codec_id);
  672. if (*desired_format) {
  673. ret = device_init(ctx, width, height, *desired_format);
  674. if (ret < 0) {
  675. *desired_format = 0;
  676. if (ret != AVERROR(EINVAL))
  677. return ret;
  678. }
  679. }
  680. if (!*desired_format) {
  681. for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {
  682. if (ctx->video_codec_id == AV_CODEC_ID_NONE ||
  683. avpriv_fmt_conversion_table[i].codec_id == ctx->video_codec_id) {
  684. av_log(ctx, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
  685. avcodec_get_name(avpriv_fmt_conversion_table[i].codec_id),
  686. (char *)av_x_if_null(av_get_pix_fmt_name(avpriv_fmt_conversion_table[i].ff_fmt), "none"));
  687. *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;
  688. ret = device_init(ctx, width, height, *desired_format);
  689. if (ret >= 0)
  690. break;
  691. else if (ret != AVERROR(EINVAL))
  692. return ret;
  693. *desired_format = 0;
  694. }
  695. }
  696. if (*desired_format == 0) {
  697. av_log(ctx, AV_LOG_ERROR, "Cannot find a proper format for "
  698. "codec '%s' (id %d), pixel format '%s' (id %d)\n",
  699. avcodec_get_name(ctx->video_codec_id), ctx->video_codec_id,
  700. (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
  701. ret = AVERROR(EINVAL);
  702. }
  703. }
  704. *codec_id = avpriv_fmt_v4l2codec(*desired_format);
  705. av_assert0(*codec_id != AV_CODEC_ID_NONE);
  706. return ret;
  707. }
  708. static int v4l2_read_header(AVFormatContext *ctx)
  709. {
  710. struct video_data *s = ctx->priv_data;
  711. AVStream *st;
  712. int res = 0;
  713. uint32_t desired_format;
  714. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  715. enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
  716. struct v4l2_input input = { 0 };
  717. st = avformat_new_stream(ctx, NULL);
  718. if (!st)
  719. return AVERROR(ENOMEM);
  720. #if CONFIG_LIBV4L2
  721. /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
  722. and errors will get sent to stderr */
  723. if (s->use_libv4l2)
  724. v4l2_log_file = fopen("/dev/null", "w");
  725. #endif
  726. s->fd = device_open(ctx);
  727. if (s->fd < 0)
  728. return s->fd;
  729. if (s->channel != -1) {
  730. /* set video input */
  731. av_log(ctx, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
  732. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
  733. res = AVERROR(errno);
  734. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
  735. goto fail;
  736. }
  737. } else {
  738. /* get current video input */
  739. if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
  740. res = AVERROR(errno);
  741. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
  742. goto fail;
  743. }
  744. }
  745. /* enum input */
  746. input.index = s->channel;
  747. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  748. res = AVERROR(errno);
  749. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
  750. goto fail;
  751. }
  752. s->std_id = input.std;
  753. av_log(ctx, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s, input_std: %"PRIx64"\n",
  754. s->channel, input.name, (uint64_t)input.std);
  755. if (s->list_format) {
  756. list_formats(ctx, s->fd, s->list_format);
  757. res = AVERROR_EXIT;
  758. goto fail;
  759. }
  760. if (s->list_standard) {
  761. list_standards(ctx);
  762. res = AVERROR_EXIT;
  763. goto fail;
  764. }
  765. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  766. if ((res = v4l2_set_parameters(ctx)) < 0)
  767. goto fail;
  768. if (s->pixel_format) {
  769. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  770. if (codec)
  771. ctx->video_codec_id = codec->id;
  772. pix_fmt = av_get_pix_fmt(s->pixel_format);
  773. if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
  774. av_log(ctx, AV_LOG_ERROR, "No such input format: %s.\n",
  775. s->pixel_format);
  776. res = AVERROR(EINVAL);
  777. goto fail;
  778. }
  779. }
  780. if (!s->width && !s->height) {
  781. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  782. av_log(ctx, AV_LOG_VERBOSE,
  783. "Querying the device for the current frame size\n");
  784. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  785. res = AVERROR(errno);
  786. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
  787. goto fail;
  788. }
  789. s->width = fmt.fmt.pix.width;
  790. s->height = fmt.fmt.pix.height;
  791. av_log(ctx, AV_LOG_VERBOSE,
  792. "Setting frame size to %dx%d\n", s->width, s->height);
  793. }
  794. res = device_try_init(ctx, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
  795. if (res < 0)
  796. goto fail;
  797. /* If no pixel_format was specified, the codec_id was not known up
  798. * until now. Set video_codec_id in the context, as codec_id will
  799. * not be available outside this function
  800. */
  801. if (codec_id != AV_CODEC_ID_NONE && ctx->video_codec_id == AV_CODEC_ID_NONE)
  802. ctx->video_codec_id = codec_id;
  803. if ((res = av_image_check_size(s->width, s->height, 0, ctx)) < 0)
  804. goto fail;
  805. s->frame_format = desired_format;
  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(ctx)) ||
  810. (res = mmap_start(ctx)) < 0)
  811. goto fail;
  812. s->top_field_first = first_field(s);
  813. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  814. st->codec->codec_id = codec_id;
  815. if (codec_id == AV_CODEC_ID_RAWVIDEO)
  816. st->codec->codec_tag =
  817. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  818. else if (codec_id == AV_CODEC_ID_H264) {
  819. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  820. }
  821. if (desired_format == V4L2_PIX_FMT_YVU420)
  822. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  823. else if (desired_format == V4L2_PIX_FMT_YVU410)
  824. st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
  825. st->codec->width = s->width;
  826. st->codec->height = s->height;
  827. if (st->avg_frame_rate.den)
  828. st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
  829. return 0;
  830. fail:
  831. v4l2_close(s->fd);
  832. return res;
  833. }
  834. static int v4l2_read_packet(AVFormatContext *ctx, AVPacket *pkt)
  835. {
  836. struct video_data *s = ctx->priv_data;
  837. AVFrame *frame = ctx->streams[0]->codec->coded_frame;
  838. int res;
  839. av_init_packet(pkt);
  840. if ((res = mmap_read_frame(ctx, pkt)) < 0) {
  841. return res;
  842. }
  843. if (frame && s->interlaced) {
  844. frame->interlaced_frame = 1;
  845. frame->top_field_first = s->top_field_first;
  846. }
  847. return pkt->size;
  848. }
  849. static int v4l2_read_close(AVFormatContext *ctx)
  850. {
  851. struct video_data *s = ctx->priv_data;
  852. if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
  853. av_log(ctx, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
  854. "close.\n");
  855. mmap_close(s);
  856. v4l2_close(s->fd);
  857. return 0;
  858. }
  859. #define OFFSET(x) offsetof(struct video_data, x)
  860. #define DEC AV_OPT_FLAG_DECODING_PARAM
  861. static const AVOption options[] = {
  862. { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  863. { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
  864. { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  865. { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  866. { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  867. { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  868. { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
  869. { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  870. { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  871. { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  872. { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
  873. { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
  874. { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  875. { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  876. { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  877. { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  878. { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  879. { "use_libv4l2", "use libv4l2 (v4l-utils) conversion functions", OFFSET(use_libv4l2), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  880. { NULL },
  881. };
  882. static const AVClass v4l2_class = {
  883. .class_name = "V4L2 indev",
  884. .item_name = av_default_item_name,
  885. .option = options,
  886. .version = LIBAVUTIL_VERSION_INT,
  887. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  888. };
  889. AVInputFormat ff_v4l2_demuxer = {
  890. .name = "video4linux2,v4l2",
  891. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  892. .priv_data_size = sizeof(struct video_data),
  893. .read_header = v4l2_read_header,
  894. .read_packet = v4l2_read_packet,
  895. .read_close = v4l2_read_close,
  896. .flags = AVFMT_NOFILE,
  897. .priv_class = &v4l2_class,
  898. };