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.

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