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.

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