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.

942 lines
29KB

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