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.

1056 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 err;
  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. err = AVERROR(errno);
  133. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
  134. ctx->filename, av_err2str(err));
  135. return err;
  136. }
  137. if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
  138. err = AVERROR(errno);
  139. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  140. av_err2str(err));
  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. err = 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. err = AVERROR(ENOSYS);
  154. goto fail;
  155. }
  156. return fd;
  157. fail:
  158. v4l2_close(fd);
  159. return err;
  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_freep(&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",
  446. av_err2str(res));
  447. return res;
  448. }
  449. if (buf.index >= s->buffers) {
  450. av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
  451. return AVERROR(EINVAL);
  452. }
  453. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
  454. // always keep at least one buffer queued
  455. av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
  456. /* CPIA is a compressed format and we don't know the exact number of bytes
  457. * used by a frame, so set it here as the driver announces it.
  458. */
  459. if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
  460. s->frame_size = buf.bytesused;
  461. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  462. av_log(ctx, AV_LOG_ERROR,
  463. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  464. buf.bytesused, s->frame_size);
  465. enqueue_buffer(s, &buf);
  466. return AVERROR_INVALIDDATA;
  467. }
  468. /* Image is at s->buff_start[buf.index] */
  469. if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
  470. /* when we start getting low on queued buffers, fall back on copying data */
  471. res = av_new_packet(pkt, buf.bytesused);
  472. if (res < 0) {
  473. av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
  474. enqueue_buffer(s, &buf);
  475. return res;
  476. }
  477. memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
  478. res = enqueue_buffer(s, &buf);
  479. if (res) {
  480. av_free_packet(pkt);
  481. return res;
  482. }
  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) {
  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. enqueue_buffer(s, &buf);
  499. return AVERROR(ENOMEM);
  500. }
  501. buf_descriptor->index = buf.index;
  502. buf_descriptor->s = s;
  503. pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
  504. buf_descriptor, 0);
  505. if (!pkt->buf) {
  506. av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
  507. enqueue_buffer(s, &buf);
  508. av_freep(&buf_descriptor);
  509. return AVERROR(ENOMEM);
  510. }
  511. }
  512. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  513. convert_timestamp(ctx, &pkt->pts);
  514. return s->buf_len[buf.index];
  515. }
  516. static int mmap_start(AVFormatContext *ctx)
  517. {
  518. struct video_data *s = ctx->priv_data;
  519. enum v4l2_buf_type type;
  520. int i, res;
  521. for (i = 0; i < s->buffers; i++) {
  522. struct v4l2_buffer buf = {
  523. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  524. .index = i,
  525. .memory = V4L2_MEMORY_MMAP
  526. };
  527. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  528. res = AVERROR(errno);
  529. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  530. av_err2str(res));
  531. return res;
  532. }
  533. }
  534. s->buffers_queued = s->buffers;
  535. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  536. if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
  537. res = AVERROR(errno);
  538. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
  539. 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_freep(&s->buf_start);
  557. av_freep(&s->buf_len);
  558. }
  559. static int v4l2_set_parameters(AVFormatContext *ctx)
  560. {
  561. struct video_data *s = ctx->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(ctx, 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(ctx, 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(ctx, 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(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
  594. return ret;
  595. }
  596. } else {
  597. av_log(ctx, 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. #ifdef ENODATA
  610. || ret == AVERROR(ENODATA)
  611. #endif
  612. ) {
  613. tpf = &streamparm.parm.capture.timeperframe;
  614. break;
  615. }
  616. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  617. return ret;
  618. }
  619. if (standard.id == s->std_id) {
  620. av_log(ctx, AV_LOG_DEBUG,
  621. "Current standard: %s, id: %"PRIx64", frameperiod: %d/%d\n",
  622. standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
  623. break;
  624. }
  625. }
  626. } else {
  627. tpf = &streamparm.parm.capture.timeperframe;
  628. }
  629. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  630. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
  631. ret = AVERROR(errno);
  632. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
  633. return ret;
  634. }
  635. if (framerate_q.num && framerate_q.den) {
  636. if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
  637. tpf = &streamparm.parm.capture.timeperframe;
  638. av_log(ctx, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  639. framerate_q.den, framerate_q.num);
  640. tpf->numerator = framerate_q.den;
  641. tpf->denominator = framerate_q.num;
  642. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
  643. ret = AVERROR(errno);
  644. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n",
  645. av_err2str(ret));
  646. return ret;
  647. }
  648. if (framerate_q.num != tpf->denominator ||
  649. framerate_q.den != tpf->numerator) {
  650. av_log(ctx, AV_LOG_INFO,
  651. "The driver changed the time per frame from "
  652. "%d/%d to %d/%d\n",
  653. framerate_q.den, framerate_q.num,
  654. tpf->numerator, tpf->denominator);
  655. }
  656. } else {
  657. av_log(ctx, AV_LOG_WARNING,
  658. "The driver does not allow to change time per frame\n");
  659. }
  660. }
  661. if (tpf->denominator > 0 && tpf->numerator > 0) {
  662. ctx->streams[0]->avg_frame_rate.num = tpf->denominator;
  663. ctx->streams[0]->avg_frame_rate.den = tpf->numerator;
  664. ctx->streams[0]->r_frame_rate = ctx->streams[0]->avg_frame_rate;
  665. } else
  666. av_log(ctx, AV_LOG_WARNING, "Time per frame unknown\n");
  667. return 0;
  668. }
  669. static int device_try_init(AVFormatContext *ctx,
  670. enum AVPixelFormat pix_fmt,
  671. int *width,
  672. int *height,
  673. uint32_t *desired_format,
  674. enum AVCodecID *codec_id)
  675. {
  676. int ret, i;
  677. *desired_format = ff_fmt_ff2v4l(pix_fmt, ctx->video_codec_id);
  678. if (*desired_format) {
  679. ret = device_init(ctx, width, height, *desired_format);
  680. if (ret < 0) {
  681. *desired_format = 0;
  682. if (ret != AVERROR(EINVAL))
  683. return ret;
  684. }
  685. }
  686. if (!*desired_format) {
  687. for (i = 0; ff_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {
  688. if (ctx->video_codec_id == AV_CODEC_ID_NONE ||
  689. ff_fmt_conversion_table[i].codec_id == ctx->video_codec_id) {
  690. av_log(ctx, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
  691. avcodec_get_name(ff_fmt_conversion_table[i].codec_id),
  692. (char *)av_x_if_null(av_get_pix_fmt_name(ff_fmt_conversion_table[i].ff_fmt), "none"));
  693. *desired_format = ff_fmt_conversion_table[i].v4l2_fmt;
  694. ret = device_init(ctx, width, height, *desired_format);
  695. if (ret >= 0)
  696. break;
  697. else if (ret != AVERROR(EINVAL))
  698. return ret;
  699. *desired_format = 0;
  700. }
  701. }
  702. if (*desired_format == 0) {
  703. av_log(ctx, AV_LOG_ERROR, "Cannot find a proper format for "
  704. "codec '%s' (id %d), pixel format '%s' (id %d)\n",
  705. avcodec_get_name(ctx->video_codec_id), ctx->video_codec_id,
  706. (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
  707. ret = AVERROR(EINVAL);
  708. }
  709. }
  710. *codec_id = ff_fmt_v4l2codec(*desired_format);
  711. av_assert0(*codec_id != AV_CODEC_ID_NONE);
  712. return ret;
  713. }
  714. static int v4l2_read_probe(AVProbeData *p)
  715. {
  716. if (av_strstart(p->filename, "/dev/video", NULL))
  717. return AVPROBE_SCORE_MAX - 1;
  718. return 0;
  719. }
  720. static int v4l2_read_header(AVFormatContext *ctx)
  721. {
  722. struct video_data *s = ctx->priv_data;
  723. AVStream *st;
  724. int res = 0;
  725. uint32_t desired_format;
  726. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  727. enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
  728. struct v4l2_input input = { 0 };
  729. st = avformat_new_stream(ctx, NULL);
  730. if (!st)
  731. return AVERROR(ENOMEM);
  732. #if CONFIG_LIBV4L2
  733. /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
  734. and errors will get sent to stderr */
  735. if (s->use_libv4l2)
  736. v4l2_log_file = fopen("/dev/null", "w");
  737. #endif
  738. s->fd = device_open(ctx);
  739. if (s->fd < 0)
  740. return s->fd;
  741. if (s->channel != -1) {
  742. /* set video input */
  743. av_log(ctx, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
  744. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
  745. res = AVERROR(errno);
  746. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
  747. goto fail;
  748. }
  749. } else {
  750. /* get current video input */
  751. if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
  752. res = AVERROR(errno);
  753. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
  754. goto fail;
  755. }
  756. }
  757. /* enum input */
  758. input.index = s->channel;
  759. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  760. res = AVERROR(errno);
  761. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
  762. goto fail;
  763. }
  764. s->std_id = input.std;
  765. av_log(ctx, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s, input_std: %"PRIx64"\n",
  766. s->channel, input.name, (uint64_t)input.std);
  767. if (s->list_format) {
  768. list_formats(ctx, s->list_format);
  769. res = AVERROR_EXIT;
  770. goto fail;
  771. }
  772. if (s->list_standard) {
  773. list_standards(ctx);
  774. res = AVERROR_EXIT;
  775. goto fail;
  776. }
  777. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  778. if (s->pixel_format) {
  779. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  780. if (codec)
  781. ctx->video_codec_id = codec->id;
  782. pix_fmt = av_get_pix_fmt(s->pixel_format);
  783. if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
  784. av_log(ctx, AV_LOG_ERROR, "No such input format: %s.\n",
  785. s->pixel_format);
  786. res = AVERROR(EINVAL);
  787. goto fail;
  788. }
  789. }
  790. if (!s->width && !s->height) {
  791. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  792. av_log(ctx, AV_LOG_VERBOSE,
  793. "Querying the device for the current frame size\n");
  794. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  795. res = AVERROR(errno);
  796. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
  797. av_err2str(res));
  798. goto fail;
  799. }
  800. s->width = fmt.fmt.pix.width;
  801. s->height = fmt.fmt.pix.height;
  802. av_log(ctx, AV_LOG_VERBOSE,
  803. "Setting frame size to %dx%d\n", s->width, s->height);
  804. }
  805. res = device_try_init(ctx, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
  806. if (res < 0)
  807. goto fail;
  808. /* If no pixel_format was specified, the codec_id was not known up
  809. * until now. Set video_codec_id in the context, as codec_id will
  810. * not be available outside this function
  811. */
  812. if (codec_id != AV_CODEC_ID_NONE && ctx->video_codec_id == AV_CODEC_ID_NONE)
  813. ctx->video_codec_id = codec_id;
  814. if ((res = av_image_check_size(s->width, s->height, 0, ctx)) < 0)
  815. goto fail;
  816. s->pixelformat = desired_format;
  817. if ((res = v4l2_set_parameters(ctx)) < 0)
  818. goto fail;
  819. st->codec->pix_fmt = ff_fmt_v4l2ff(desired_format, codec_id);
  820. s->frame_size =
  821. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  822. if ((res = mmap_init(ctx)) ||
  823. (res = mmap_start(ctx)) < 0)
  824. goto fail;
  825. s->top_field_first = first_field(s);
  826. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  827. st->codec->codec_id = codec_id;
  828. if (codec_id == AV_CODEC_ID_RAWVIDEO)
  829. st->codec->codec_tag =
  830. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  831. else if (codec_id == AV_CODEC_ID_H264) {
  832. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  833. }
  834. if (desired_format == V4L2_PIX_FMT_YVU420)
  835. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  836. else if (desired_format == V4L2_PIX_FMT_YVU410)
  837. st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
  838. st->codec->width = s->width;
  839. st->codec->height = s->height;
  840. if (st->avg_frame_rate.den)
  841. st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
  842. return 0;
  843. fail:
  844. v4l2_close(s->fd);
  845. return res;
  846. }
  847. static int v4l2_read_packet(AVFormatContext *ctx, AVPacket *pkt)
  848. {
  849. struct video_data *s = ctx->priv_data;
  850. AVFrame *frame = ctx->streams[0]->codec->coded_frame;
  851. int res;
  852. av_init_packet(pkt);
  853. if ((res = mmap_read_frame(ctx, pkt)) < 0) {
  854. return res;
  855. }
  856. if (frame && s->interlaced) {
  857. frame->interlaced_frame = 1;
  858. frame->top_field_first = s->top_field_first;
  859. }
  860. return pkt->size;
  861. }
  862. static int v4l2_read_close(AVFormatContext *ctx)
  863. {
  864. struct video_data *s = ctx->priv_data;
  865. if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
  866. av_log(ctx, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
  867. "close.\n");
  868. mmap_close(s);
  869. v4l2_close(s->fd);
  870. return 0;
  871. }
  872. #define OFFSET(x) offsetof(struct video_data, x)
  873. #define DEC AV_OPT_FLAG_DECODING_PARAM
  874. static const AVOption options[] = {
  875. { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  876. { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
  877. { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  878. { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  879. { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  880. { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  881. { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
  882. { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  883. { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  884. { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  885. { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
  886. { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
  887. { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  888. { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  889. { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  890. { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  891. { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  892. { "use_libv4l2", "use libv4l2 (v4l-utils) conversion functions", OFFSET(use_libv4l2), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  893. { NULL },
  894. };
  895. static const AVClass v4l2_class = {
  896. .class_name = "V4L2 indev",
  897. .item_name = av_default_item_name,
  898. .option = options,
  899. .version = LIBAVUTIL_VERSION_INT,
  900. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  901. };
  902. AVInputFormat ff_v4l2_demuxer = {
  903. .name = "video4linux2,v4l2",
  904. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  905. .priv_data_size = sizeof(struct video_data),
  906. .read_probe = v4l2_read_probe,
  907. .read_header = v4l2_read_header,
  908. .read_packet = v4l2_read_packet,
  909. .read_close = v4l2_read_close,
  910. .flags = AVFMT_NOFILE,
  911. .priv_class = &v4l2_class,
  912. };