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.

968 lines
31KB

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