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.

1078 lines
35KB

  1. /*
  2. * Copyright (c) 2000,2001 Fabrice Bellard
  3. * Copyright (c) 2006 Luca Abeni
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Video4Linux2 grab interface
  24. *
  25. * Part of this file is based on the V4L2 video capture example
  26. * (http://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
  27. *
  28. * Thanks to Michael Niedermayer for providing the mapping between
  29. * V4L2_PIX_FMT_* and AV_PIX_FMT_*
  30. */
  31. #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. int fd;
  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(!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(!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_WARNING, "%s", "Emulated");
  328. continue;
  329. }
  330. #endif
  331. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  332. list_framesizes(ctx, fd, vfd.pixelformat);
  333. #endif
  334. av_log(ctx, AV_LOG_INFO, "\n");
  335. }
  336. }
  337. static void list_standards(AVFormatContext *ctx)
  338. {
  339. int ret;
  340. struct video_data *s = ctx->priv_data;
  341. struct v4l2_standard standard;
  342. if (s->std_id == 0)
  343. return;
  344. for (standard.index = 0; ; standard.index++) {
  345. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  346. ret = AVERROR(errno);
  347. if (ret == AVERROR(EINVAL)) {
  348. break;
  349. } else {
  350. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  351. return;
  352. }
  353. }
  354. av_log(ctx, AV_LOG_INFO, "%2d, %16llx, %s\n",
  355. standard.index, standard.id, standard.name);
  356. }
  357. }
  358. static int mmap_init(AVFormatContext *ctx)
  359. {
  360. int i, res;
  361. struct video_data *s = ctx->priv_data;
  362. struct v4l2_requestbuffers req = {
  363. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  364. .count = desired_video_buffers,
  365. .memory = V4L2_MEMORY_MMAP
  366. };
  367. if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
  368. res = AVERROR(errno);
  369. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
  370. return res;
  371. }
  372. if (req.count < 2) {
  373. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  374. return AVERROR(ENOMEM);
  375. }
  376. s->buffers = req.count;
  377. s->buf_start = av_malloc(sizeof(void *) * s->buffers);
  378. if (s->buf_start == NULL) {
  379. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  380. return AVERROR(ENOMEM);
  381. }
  382. s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
  383. if (s->buf_len == NULL) {
  384. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  385. av_free(s->buf_start);
  386. return AVERROR(ENOMEM);
  387. }
  388. for (i = 0; i < req.count; i++) {
  389. struct v4l2_buffer buf = {
  390. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  391. .index = i,
  392. .memory = V4L2_MEMORY_MMAP
  393. };
  394. if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
  395. res = AVERROR(errno);
  396. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
  397. return res;
  398. }
  399. s->buf_len[i] = buf.length;
  400. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  401. av_log(ctx, AV_LOG_ERROR,
  402. "buf_len[%d] = %d < expected frame size %d\n",
  403. i, s->buf_len[i], s->frame_size);
  404. return AVERROR(ENOMEM);
  405. }
  406. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  407. PROT_READ | PROT_WRITE, MAP_SHARED,
  408. s->fd, buf.m.offset);
  409. if (s->buf_start[i] == MAP_FAILED) {
  410. res = AVERROR(errno);
  411. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
  412. return res;
  413. }
  414. }
  415. return 0;
  416. }
  417. #if FF_API_DESTRUCT_PACKET
  418. static void dummy_release_buffer(AVPacket *pkt)
  419. {
  420. av_assert0(0);
  421. }
  422. #endif
  423. static void mmap_release_buffer(void *opaque, uint8_t *data)
  424. {
  425. struct v4l2_buffer buf = { 0 };
  426. int res, fd;
  427. struct buff_data *buf_descriptor = opaque;
  428. struct video_data *s = buf_descriptor->s;
  429. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  430. buf.memory = V4L2_MEMORY_MMAP;
  431. buf.index = buf_descriptor->index;
  432. fd = buf_descriptor->fd;
  433. av_free(buf_descriptor);
  434. if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf) < 0) {
  435. res = AVERROR(errno);
  436. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  437. av_err2str(res));
  438. }
  439. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  440. }
  441. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  442. static int64_t av_gettime_monotonic(void)
  443. {
  444. struct timespec tv;
  445. clock_gettime(CLOCK_MONOTONIC, &tv);
  446. return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
  447. }
  448. #endif
  449. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  450. {
  451. struct video_data *s = ctx->priv_data;
  452. int64_t now;
  453. now = av_gettime();
  454. if (s->ts_mode == V4L_TS_ABS &&
  455. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  456. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  457. s->ts_mode = V4L_TS_CONVERT_READY;
  458. return 0;
  459. }
  460. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  461. now = av_gettime_monotonic();
  462. if (s->ts_mode == V4L_TS_MONO2ABS ||
  463. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  464. int64_t period = av_rescale_q(1, AV_TIME_BASE_Q,
  465. ctx->streams[0]->avg_frame_rate);
  466. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  467. /* microseconds instead of seconds, MHz instead of Hz */
  468. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  469. s->ts_mode = V4L_TS_CONVERT_READY;
  470. return 0;
  471. }
  472. #endif
  473. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  474. return AVERROR(EIO);
  475. }
  476. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  477. {
  478. struct video_data *s = ctx->priv_data;
  479. if (s->ts_mode) {
  480. int r = init_convert_timestamp(ctx, *ts);
  481. if (r < 0)
  482. return r;
  483. }
  484. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  485. if (s->timefilter) {
  486. int64_t nowa = av_gettime();
  487. int64_t nowm = av_gettime_monotonic();
  488. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  489. s->last_time_m = nowm;
  490. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  491. }
  492. #endif
  493. return 0;
  494. }
  495. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  496. {
  497. struct video_data *s = ctx->priv_data;
  498. struct v4l2_buffer buf = {
  499. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  500. .memory = V4L2_MEMORY_MMAP
  501. };
  502. int res;
  503. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  504. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  505. if (res < 0) {
  506. if (errno == EAGAIN) {
  507. pkt->size = 0;
  508. return AVERROR(EAGAIN);
  509. }
  510. res = AVERROR(errno);
  511. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
  512. return res;
  513. }
  514. if (buf.index >= s->buffers) {
  515. av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
  516. return AVERROR(EINVAL);
  517. }
  518. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
  519. // always keep at least one buffer queued
  520. av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
  521. /* CPIA is a compressed format and we don't know the exact number of bytes
  522. * used by a frame, so set it here as the driver announces it.
  523. */
  524. if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
  525. s->frame_size = buf.bytesused;
  526. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  527. av_log(ctx, AV_LOG_ERROR,
  528. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  529. buf.bytesused, s->frame_size);
  530. return AVERROR_INVALIDDATA;
  531. }
  532. /* Image is at s->buff_start[buf.index] */
  533. if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
  534. /* when we start getting low on queued buffers, fallback to copying data */
  535. res = av_new_packet(pkt, buf.bytesused);
  536. if (res < 0) {
  537. av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
  538. return res;
  539. }
  540. memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
  541. res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
  542. if (res < 0) {
  543. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF)\n");
  544. av_free_packet(pkt);
  545. return AVERROR(errno);
  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. res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
  562. return AVERROR(ENOMEM);
  563. }
  564. buf_descriptor->fd = s->fd;
  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_freep(&buf_descriptor);
  571. return AVERROR(ENOMEM);
  572. }
  573. }
  574. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  575. convert_timestamp(ctx, &pkt->pts);
  576. return s->buf_len[buf.index];
  577. }
  578. static int mmap_start(AVFormatContext *ctx)
  579. {
  580. struct video_data *s = ctx->priv_data;
  581. enum v4l2_buf_type type;
  582. int i, res;
  583. for (i = 0; i < s->buffers; i++) {
  584. struct v4l2_buffer buf = {
  585. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  586. .index = i,
  587. .memory = V4L2_MEMORY_MMAP
  588. };
  589. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  590. res = AVERROR(errno);
  591. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  592. return res;
  593. }
  594. }
  595. s->buffers_queued = s->buffers;
  596. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  597. if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
  598. res = AVERROR(errno);
  599. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
  600. return res;
  601. }
  602. return 0;
  603. }
  604. static void mmap_close(struct video_data *s)
  605. {
  606. enum v4l2_buf_type type;
  607. int i;
  608. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  609. /* We do not check for the result, because we could
  610. * not do anything about it anyway...
  611. */
  612. v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  613. for (i = 0; i < s->buffers; i++) {
  614. v4l2_munmap(s->buf_start[i], s->buf_len[i]);
  615. }
  616. av_free(s->buf_start);
  617. av_free(s->buf_len);
  618. }
  619. static int v4l2_set_parameters(AVFormatContext *s1)
  620. {
  621. struct video_data *s = s1->priv_data;
  622. struct v4l2_standard standard = { 0 };
  623. struct v4l2_streamparm streamparm = { 0 };
  624. struct v4l2_fract *tpf;
  625. AVRational framerate_q = { 0 };
  626. int i, ret;
  627. if (s->framerate &&
  628. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  629. av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  630. s->framerate);
  631. return ret;
  632. }
  633. if (s->standard) {
  634. if (s->std_id) {
  635. ret = 0;
  636. av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
  637. /* set tv standard */
  638. for (i = 0; ; i++) {
  639. standard.index = i;
  640. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  641. ret = AVERROR(errno);
  642. break;
  643. }
  644. if (!av_strcasecmp(standard.name, s->standard))
  645. break;
  646. }
  647. if (ret < 0) {
  648. av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
  649. return ret;
  650. }
  651. if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  652. ret = AVERROR(errno);
  653. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
  654. return ret;
  655. }
  656. } else {
  657. av_log(s1, AV_LOG_WARNING,
  658. "This device does not support any standard\n");
  659. }
  660. }
  661. /* get standard */
  662. if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
  663. tpf = &standard.frameperiod;
  664. for (i = 0; ; i++) {
  665. standard.index = i;
  666. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  667. ret = AVERROR(errno);
  668. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  669. return ret;
  670. }
  671. if (standard.id == s->std_id) {
  672. av_log(s1, AV_LOG_DEBUG,
  673. "Current standard: %s, id: %"PRIu64", frameperiod: %d/%d\n",
  674. standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
  675. break;
  676. }
  677. }
  678. } else {
  679. tpf = &streamparm.parm.capture.timeperframe;
  680. }
  681. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  682. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
  683. ret = AVERROR(errno);
  684. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
  685. return ret;
  686. }
  687. if (framerate_q.num && framerate_q.den) {
  688. if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
  689. tpf = &streamparm.parm.capture.timeperframe;
  690. av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  691. framerate_q.den, framerate_q.num);
  692. tpf->numerator = framerate_q.den;
  693. tpf->denominator = framerate_q.num;
  694. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
  695. ret = AVERROR(errno);
  696. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
  697. return ret;
  698. }
  699. if (framerate_q.num != tpf->denominator ||
  700. framerate_q.den != tpf->numerator) {
  701. av_log(s1, AV_LOG_INFO,
  702. "The driver changed the time per frame from "
  703. "%d/%d to %d/%d\n",
  704. framerate_q.den, framerate_q.num,
  705. tpf->numerator, tpf->denominator);
  706. }
  707. } else {
  708. av_log(s1, AV_LOG_WARNING,
  709. "The driver does not allow to change time per frame\n");
  710. }
  711. }
  712. s1->streams[0]->avg_frame_rate.num = tpf->denominator;
  713. s1->streams[0]->avg_frame_rate.den = tpf->numerator;
  714. s1->streams[0]->r_frame_rate = s1->streams[0]->avg_frame_rate;
  715. return 0;
  716. }
  717. static int device_try_init(AVFormatContext *s1,
  718. enum AVPixelFormat pix_fmt,
  719. int *width,
  720. int *height,
  721. uint32_t *desired_format,
  722. enum AVCodecID *codec_id)
  723. {
  724. int ret, i;
  725. *desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
  726. if (*desired_format) {
  727. ret = device_init(s1, width, height, *desired_format);
  728. if (ret < 0) {
  729. *desired_format = 0;
  730. if (ret != AVERROR(EINVAL))
  731. return ret;
  732. }
  733. }
  734. if (!*desired_format) {
  735. for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  736. if (s1->video_codec_id == AV_CODEC_ID_NONE ||
  737. fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  738. av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
  739. avcodec_get_name(fmt_conversion_table[i].codec_id),
  740. (char *)av_x_if_null(av_get_pix_fmt_name(fmt_conversion_table[i].ff_fmt), "none"));
  741. *desired_format = fmt_conversion_table[i].v4l2_fmt;
  742. ret = device_init(s1, width, height, *desired_format);
  743. if (ret >= 0)
  744. break;
  745. else if (ret != AVERROR(EINVAL))
  746. return ret;
  747. *desired_format = 0;
  748. }
  749. }
  750. if (*desired_format == 0) {
  751. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  752. "codec '%s' (id %d), pixel format '%s' (id %d)\n",
  753. avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
  754. (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
  755. ret = AVERROR(EINVAL);
  756. }
  757. }
  758. *codec_id = fmt_v4l2codec(*desired_format);
  759. av_assert0(*codec_id != AV_CODEC_ID_NONE);
  760. return ret;
  761. }
  762. static int v4l2_read_header(AVFormatContext *s1)
  763. {
  764. struct video_data *s = s1->priv_data;
  765. AVStream *st;
  766. int res = 0;
  767. uint32_t desired_format;
  768. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  769. enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
  770. struct v4l2_input input = { 0 };
  771. st = avformat_new_stream(s1, NULL);
  772. if (!st)
  773. return AVERROR(ENOMEM);
  774. s->fd = device_open(s1);
  775. if (s->fd < 0)
  776. return s->fd;
  777. /* set tv video input */
  778. av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
  779. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
  780. res = AVERROR(errno);
  781. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
  782. return res;
  783. }
  784. input.index = s->channel;
  785. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  786. res = AVERROR(errno);
  787. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
  788. return res;
  789. }
  790. s->std_id = input.std;
  791. av_log(s1, AV_LOG_DEBUG, "input_channel: %d, input_name: %s\n",
  792. s->channel, input.name);
  793. if (s->list_format) {
  794. list_formats(s1, s->fd, s->list_format);
  795. return AVERROR_EXIT;
  796. }
  797. if (s->list_standard) {
  798. list_standards(s1);
  799. return AVERROR_EXIT;
  800. }
  801. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  802. if (s->pixel_format) {
  803. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  804. if (codec)
  805. s1->video_codec_id = codec->id;
  806. pix_fmt = av_get_pix_fmt(s->pixel_format);
  807. if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
  808. av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
  809. s->pixel_format);
  810. return AVERROR(EINVAL);
  811. }
  812. }
  813. if (!s->width && !s->height) {
  814. struct v4l2_format fmt;
  815. av_log(s1, AV_LOG_VERBOSE,
  816. "Querying the device for the current frame size\n");
  817. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  818. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  819. res = AVERROR(errno);
  820. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
  821. return res;
  822. }
  823. s->width = fmt.fmt.pix.width;
  824. s->height = fmt.fmt.pix.height;
  825. av_log(s1, AV_LOG_VERBOSE,
  826. "Setting frame size to %dx%d\n", s->width, s->height);
  827. }
  828. res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
  829. if (res < 0) {
  830. v4l2_close(s->fd);
  831. return res;
  832. }
  833. /* If no pixel_format was specified, the codec_id was not known up
  834. * until now. Set video_codec_id in the context, as codec_id will
  835. * not be available outside this function
  836. */
  837. if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
  838. s1->video_codec_id = codec_id;
  839. if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
  840. return res;
  841. s->frame_format = desired_format;
  842. if ((res = v4l2_set_parameters(s1)) < 0)
  843. return res;
  844. st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
  845. s->frame_size =
  846. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  847. if ((res = mmap_init(s1)) ||
  848. (res = mmap_start(s1)) < 0) {
  849. v4l2_close(s->fd);
  850. return res;
  851. }
  852. s->top_field_first = first_field(s->fd);
  853. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  854. st->codec->codec_id = codec_id;
  855. if (codec_id == AV_CODEC_ID_RAWVIDEO)
  856. st->codec->codec_tag =
  857. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  858. if (desired_format == V4L2_PIX_FMT_YVU420)
  859. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  860. else if (desired_format == V4L2_PIX_FMT_YVU410)
  861. st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
  862. st->codec->width = s->width;
  863. st->codec->height = s->height;
  864. st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
  865. return 0;
  866. }
  867. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  868. {
  869. struct video_data *s = s1->priv_data;
  870. AVFrame *frame = s1->streams[0]->codec->coded_frame;
  871. int res;
  872. av_init_packet(pkt);
  873. if ((res = mmap_read_frame(s1, pkt)) < 0) {
  874. return res;
  875. }
  876. if (frame && s->interlaced) {
  877. frame->interlaced_frame = 1;
  878. frame->top_field_first = s->top_field_first;
  879. }
  880. return pkt->size;
  881. }
  882. static int v4l2_read_close(AVFormatContext *s1)
  883. {
  884. struct video_data *s = s1->priv_data;
  885. if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
  886. av_log(s1, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
  887. "close.\n");
  888. mmap_close(s);
  889. v4l2_close(s->fd);
  890. return 0;
  891. }
  892. #define OFFSET(x) offsetof(struct video_data, x)
  893. #define DEC AV_OPT_FLAG_DECODING_PARAM
  894. static const AVOption options[] = {
  895. { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  896. { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC },
  897. { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  898. { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  899. { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  900. { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  901. { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
  902. { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  903. { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  904. { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  905. { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
  906. { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
  907. { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  908. { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  909. { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  910. { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  911. { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  912. { NULL },
  913. };
  914. static const AVClass v4l2_class = {
  915. .class_name = "V4L2 indev",
  916. .item_name = av_default_item_name,
  917. .option = options,
  918. .version = LIBAVUTIL_VERSION_INT,
  919. };
  920. AVInputFormat ff_v4l2_demuxer = {
  921. .name = "video4linux2,v4l2",
  922. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  923. .priv_data_size = sizeof(struct video_data),
  924. .read_header = v4l2_read_header,
  925. .read_packet = v4l2_read_packet,
  926. .read_close = v4l2_read_close,
  927. .flags = AVFMT_NOFILE,
  928. .priv_class = &v4l2_class,
  929. };