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.

987 lines
33KB

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