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.

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