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.

1027 lines
33KB

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