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.

1081 lines
36KB

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