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.

964 lines
30KB

  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 <time.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 *video_size; /**< String describing video size,
  108. set by a private option. */
  109. char *pixel_format; /**< Set by a private option. */
  110. int list_format; /**< 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 PixelFormat ff_fmt;
  119. enum CodecID codec_id;
  120. uint32_t v4l2_fmt;
  121. };
  122. static struct fmt_map fmt_conversion_table[] = {
  123. //ff_fmt codec_id v4l2_fmt
  124. { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
  125. { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420 },
  126. { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
  127. { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
  128. { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
  129. { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
  130. { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
  131. { PIX_FMT_RGB555LE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
  132. { PIX_FMT_RGB555BE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
  133. { PIX_FMT_RGB565LE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
  134. { PIX_FMT_RGB565BE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
  135. { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
  136. { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
  137. { PIX_FMT_BGR0, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
  138. { PIX_FMT_0RGB, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32 },
  139. { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
  140. { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
  141. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
  142. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
  143. };
  144. static int device_open(AVFormatContext *ctx)
  145. {
  146. struct v4l2_capability cap;
  147. int fd;
  148. #if CONFIG_LIBV4L2
  149. int fd_libv4l;
  150. #endif
  151. int res, err;
  152. int flags = O_RDWR;
  153. if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
  154. flags |= O_NONBLOCK;
  155. }
  156. fd = v4l2_open(ctx->filename, flags, 0);
  157. if (fd < 0) {
  158. err = errno;
  159. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
  160. ctx->filename, strerror(err));
  161. return AVERROR(err);
  162. }
  163. #if CONFIG_LIBV4L2
  164. fd_libv4l = v4l2_fd_open(fd, 0);
  165. if (fd < 0) {
  166. err = AVERROR(errno);
  167. av_log(ctx, AV_LOG_ERROR, "Cannot open video device with libv4l neither %s : %s\n",
  168. ctx->filename, strerror(errno));
  169. return err;
  170. }
  171. fd = fd_libv4l;
  172. #endif
  173. res = v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap);
  174. if (res < 0) {
  175. err = errno;
  176. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  177. strerror(err));
  178. goto fail;
  179. }
  180. av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",
  181. fd, cap.capabilities);
  182. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  183. av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
  184. err = ENODEV;
  185. goto fail;
  186. }
  187. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  188. av_log(ctx, AV_LOG_ERROR,
  189. "The device does not support the streaming I/O method.\n");
  190. err = ENOSYS;
  191. goto fail;
  192. }
  193. return fd;
  194. fail:
  195. v4l2_close(fd);
  196. return AVERROR(err);
  197. }
  198. static int device_init(AVFormatContext *ctx, int *width, int *height,
  199. uint32_t pix_fmt)
  200. {
  201. struct video_data *s = ctx->priv_data;
  202. int fd = s->fd;
  203. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  204. struct v4l2_pix_format *pix = &fmt.fmt.pix;
  205. int res;
  206. pix->width = *width;
  207. pix->height = *height;
  208. pix->pixelformat = pix_fmt;
  209. pix->field = V4L2_FIELD_ANY;
  210. res = v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt);
  211. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  212. av_log(ctx, AV_LOG_INFO,
  213. "The V4L2 driver changed the video from %dx%d to %dx%d\n",
  214. *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  215. *width = fmt.fmt.pix.width;
  216. *height = fmt.fmt.pix.height;
  217. }
  218. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  219. av_log(ctx, AV_LOG_DEBUG,
  220. "The V4L2 driver changed the pixel format "
  221. "from 0x%08X to 0x%08X\n",
  222. pix_fmt, fmt.fmt.pix.pixelformat);
  223. res = -1;
  224. }
  225. if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
  226. av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
  227. s->interlaced = 1;
  228. }
  229. return res;
  230. }
  231. static int first_field(int fd)
  232. {
  233. int res;
  234. v4l2_std_id std;
  235. res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
  236. if (res < 0) {
  237. return 0;
  238. }
  239. if (std & V4L2_STD_NTSC) {
  240. return 0;
  241. }
  242. return 1;
  243. }
  244. static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
  245. {
  246. int i;
  247. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  248. if ((codec_id == CODEC_ID_NONE ||
  249. fmt_conversion_table[i].codec_id == codec_id) &&
  250. (pix_fmt == PIX_FMT_NONE ||
  251. fmt_conversion_table[i].ff_fmt == pix_fmt)) {
  252. return fmt_conversion_table[i].v4l2_fmt;
  253. }
  254. }
  255. return 0;
  256. }
  257. static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
  258. {
  259. int i;
  260. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  261. if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
  262. fmt_conversion_table[i].codec_id == codec_id) {
  263. return fmt_conversion_table[i].ff_fmt;
  264. }
  265. }
  266. return PIX_FMT_NONE;
  267. }
  268. static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
  269. {
  270. int i;
  271. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  272. if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
  273. return fmt_conversion_table[i].codec_id;
  274. }
  275. }
  276. return CODEC_ID_NONE;
  277. }
  278. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  279. static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
  280. {
  281. struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
  282. while(!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
  283. switch (vfse.type) {
  284. case V4L2_FRMSIZE_TYPE_DISCRETE:
  285. av_log(ctx, AV_LOG_INFO, " %ux%u",
  286. vfse.discrete.width, vfse.discrete.height);
  287. break;
  288. case V4L2_FRMSIZE_TYPE_CONTINUOUS:
  289. case V4L2_FRMSIZE_TYPE_STEPWISE:
  290. av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
  291. vfse.stepwise.min_width,
  292. vfse.stepwise.max_width,
  293. vfse.stepwise.step_width,
  294. vfse.stepwise.min_height,
  295. vfse.stepwise.max_height,
  296. vfse.stepwise.step_height);
  297. }
  298. vfse.index++;
  299. }
  300. }
  301. #endif
  302. static void list_formats(AVFormatContext *ctx, int fd, int type)
  303. {
  304. struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  305. while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
  306. enum CodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
  307. enum PixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
  308. vfd.index++;
  309. if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
  310. type & V4L_RAWFORMATS) {
  311. const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
  312. av_log(ctx, AV_LOG_INFO, "R : %9s : %20s :",
  313. fmt_name ? fmt_name : "Unsupported",
  314. vfd.description);
  315. } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
  316. type & V4L_COMPFORMATS) {
  317. AVCodec *codec = avcodec_find_encoder(codec_id);
  318. av_log(ctx, AV_LOG_INFO, "C : %9s : %20s :",
  319. codec ? codec->name : "Unsupported",
  320. vfd.description);
  321. } else {
  322. continue;
  323. }
  324. #ifdef V4L2_FMT_FLAG_EMULATED
  325. if (vfd.flags & V4L2_FMT_FLAG_EMULATED) {
  326. av_log(ctx, AV_LOG_WARNING, "%s", "Emulated");
  327. continue;
  328. }
  329. #endif
  330. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  331. list_framesizes(ctx, fd, vfd.pixelformat);
  332. #endif
  333. av_log(ctx, AV_LOG_INFO, "\n");
  334. }
  335. }
  336. static int mmap_init(AVFormatContext *ctx)
  337. {
  338. int i, res;
  339. struct video_data *s = ctx->priv_data;
  340. struct v4l2_requestbuffers req = {
  341. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  342. .count = desired_video_buffers,
  343. .memory = V4L2_MEMORY_MMAP
  344. };
  345. res = v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req);
  346. if (res < 0) {
  347. if (errno == EINVAL) {
  348. av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
  349. } else {
  350. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
  351. }
  352. return AVERROR(errno);
  353. }
  354. if (req.count < 2) {
  355. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  356. return AVERROR(ENOMEM);
  357. }
  358. s->buffers = req.count;
  359. s->buf_start = av_malloc(sizeof(void *) * s->buffers);
  360. if (s->buf_start == NULL) {
  361. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  362. return AVERROR(ENOMEM);
  363. }
  364. s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
  365. if (s->buf_len == NULL) {
  366. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  367. av_free(s->buf_start);
  368. return AVERROR(ENOMEM);
  369. }
  370. for (i = 0; i < req.count; i++) {
  371. struct v4l2_buffer buf = {
  372. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  373. .index = i,
  374. .memory = V4L2_MEMORY_MMAP
  375. };
  376. res = v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
  377. if (res < 0) {
  378. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
  379. return AVERROR(errno);
  380. }
  381. s->buf_len[i] = buf.length;
  382. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  383. av_log(ctx, AV_LOG_ERROR,
  384. "Buffer len [%d] = %d != %d\n",
  385. i, s->buf_len[i], s->frame_size);
  386. return -1;
  387. }
  388. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  389. PROT_READ | PROT_WRITE, MAP_SHARED,
  390. s->fd, buf.m.offset);
  391. if (s->buf_start[i] == MAP_FAILED) {
  392. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
  393. return AVERROR(errno);
  394. }
  395. }
  396. return 0;
  397. }
  398. static void mmap_release_buffer(AVPacket *pkt)
  399. {
  400. struct v4l2_buffer buf = { 0 };
  401. int res, fd;
  402. struct buff_data *buf_descriptor = pkt->priv;
  403. if (pkt->data == NULL)
  404. return;
  405. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  406. buf.memory = V4L2_MEMORY_MMAP;
  407. buf.index = buf_descriptor->index;
  408. fd = buf_descriptor->fd;
  409. av_free(buf_descriptor);
  410. res = v4l2_ioctl(fd, VIDIOC_QBUF, &buf);
  411. if (res < 0)
  412. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  413. strerror(errno));
  414. pkt->data = NULL;
  415. pkt->size = 0;
  416. }
  417. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  418. static int64_t av_gettime_monotonic(void)
  419. {
  420. struct timespec tv;
  421. clock_gettime(CLOCK_MONOTONIC, &tv);
  422. return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
  423. }
  424. #endif
  425. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  426. {
  427. struct video_data *s = ctx->priv_data;
  428. int64_t now;
  429. now = av_gettime();
  430. if (s->ts_mode == V4L_TS_ABS &&
  431. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  432. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  433. s->ts_mode = V4L_TS_CONVERT_READY;
  434. return 0;
  435. }
  436. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  437. now = av_gettime_monotonic();
  438. if (s->ts_mode == V4L_TS_MONO2ABS ||
  439. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  440. int64_t period = av_rescale_q(1, ctx->streams[0]->codec->time_base,
  441. AV_TIME_BASE_Q);
  442. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  443. /* microseconds instead of seconds, MHz instead of Hz */
  444. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  445. s->ts_mode = V4L_TS_CONVERT_READY;
  446. return 0;
  447. }
  448. #endif
  449. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  450. return AVERROR(EIO);
  451. }
  452. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  453. {
  454. struct video_data *s = ctx->priv_data;
  455. if (s->ts_mode) {
  456. int r = init_convert_timestamp(ctx, *ts);
  457. if (r < 0)
  458. return r;
  459. }
  460. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  461. if (s->timefilter) {
  462. int64_t nowa = av_gettime();
  463. int64_t nowm = av_gettime_monotonic();
  464. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  465. s->last_time_m = nowm;
  466. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  467. }
  468. #endif
  469. return 0;
  470. }
  471. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  472. {
  473. struct video_data *s = ctx->priv_data;
  474. struct v4l2_buffer buf = {
  475. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  476. .memory = V4L2_MEMORY_MMAP
  477. };
  478. struct buff_data *buf_descriptor;
  479. int res;
  480. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  481. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  482. if (res < 0) {
  483. if (errno == EAGAIN) {
  484. pkt->size = 0;
  485. return AVERROR(EAGAIN);
  486. }
  487. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
  488. strerror(errno));
  489. return AVERROR(errno);
  490. }
  491. assert(buf.index < s->buffers);
  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]->codec->time_base.den = tpf->denominator;
  643. s1->streams[0]->codec->time_base.num = tpf->numerator;
  644. return 0;
  645. }
  646. static uint32_t device_try_init(AVFormatContext *s1,
  647. enum PixelFormat pix_fmt,
  648. int *width,
  649. int *height,
  650. enum CodecID *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 == CODEC_ID_NONE ||
  659. fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  660. desired_format = fmt_conversion_table[i].v4l2_fmt;
  661. if (device_init(s1, width, height, desired_format) >= 0) {
  662. break;
  663. }
  664. desired_format = 0;
  665. }
  666. }
  667. }
  668. if (desired_format != 0) {
  669. *codec_id = fmt_v4l2codec(desired_format);
  670. assert(*codec_id != CODEC_ID_NONE);
  671. }
  672. return desired_format;
  673. }
  674. static int v4l2_read_header(AVFormatContext *s1)
  675. {
  676. struct video_data *s = s1->priv_data;
  677. AVStream *st;
  678. int res = 0;
  679. uint32_t desired_format;
  680. enum CodecID codec_id;
  681. enum PixelFormat pix_fmt = PIX_FMT_NONE;
  682. st = avformat_new_stream(s1, NULL);
  683. if (!st) {
  684. res = AVERROR(ENOMEM);
  685. goto out;
  686. }
  687. s->fd = device_open(s1);
  688. if (s->fd < 0) {
  689. res = s->fd;
  690. goto out;
  691. }
  692. if (s->list_format) {
  693. list_formats(s1, s->fd, s->list_format);
  694. res = AVERROR_EXIT;
  695. goto out;
  696. }
  697. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  698. if (s->video_size &&
  699. (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
  700. av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
  701. s->video_size);
  702. goto out;
  703. }
  704. if (s->pixel_format) {
  705. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  706. if (codec)
  707. s1->video_codec_id = codec->id;
  708. pix_fmt = av_get_pix_fmt(s->pixel_format);
  709. if (pix_fmt == PIX_FMT_NONE && !codec) {
  710. av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
  711. s->pixel_format);
  712. res = AVERROR(EINVAL);
  713. goto out;
  714. }
  715. }
  716. if (!s->width && !s->height) {
  717. struct v4l2_format fmt;
  718. av_log(s1, AV_LOG_VERBOSE,
  719. "Querying the device for the current frame size\n");
  720. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  721. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  722. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
  723. strerror(errno));
  724. res = AVERROR(errno);
  725. goto out;
  726. }
  727. s->width = fmt.fmt.pix.width;
  728. s->height = fmt.fmt.pix.height;
  729. av_log(s1, AV_LOG_VERBOSE,
  730. "Setting frame size to %dx%d\n", s->width, s->height);
  731. }
  732. desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
  733. &codec_id);
  734. if (desired_format == 0) {
  735. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  736. "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
  737. v4l2_close(s->fd);
  738. res = AVERROR(EIO);
  739. goto out;
  740. }
  741. if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
  742. goto out;
  743. s->frame_format = desired_format;
  744. if ((res = v4l2_set_parameters(s1)) < 0)
  745. goto out;
  746. st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
  747. s->frame_size =
  748. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  749. if ((res = mmap_init(s1)) ||
  750. (res = mmap_start(s1)) < 0) {
  751. v4l2_close(s->fd);
  752. goto out;
  753. }
  754. s->top_field_first = first_field(s->fd);
  755. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  756. st->codec->codec_id = codec_id;
  757. if (codec_id == CODEC_ID_RAWVIDEO)
  758. st->codec->codec_tag =
  759. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  760. if (desired_format == V4L2_PIX_FMT_YVU420)
  761. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  762. st->codec->width = s->width;
  763. st->codec->height = s->height;
  764. st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
  765. out:
  766. return res;
  767. }
  768. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  769. {
  770. struct video_data *s = s1->priv_data;
  771. AVFrame *frame = s1->streams[0]->codec->coded_frame;
  772. int res;
  773. av_init_packet(pkt);
  774. if ((res = mmap_read_frame(s1, pkt)) < 0) {
  775. return res;
  776. }
  777. if (frame && s->interlaced) {
  778. frame->interlaced_frame = 1;
  779. frame->top_field_first = s->top_field_first;
  780. }
  781. return pkt->size;
  782. }
  783. static int v4l2_read_close(AVFormatContext *s1)
  784. {
  785. struct video_data *s = s1->priv_data;
  786. mmap_close(s);
  787. v4l2_close(s->fd);
  788. return 0;
  789. }
  790. #define OFFSET(x) offsetof(struct video_data, x)
  791. #define DEC AV_OPT_FLAG_DECODING_PARAM
  792. static const AVOption options[] = {
  793. { "standard", "TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  794. { "channel", "TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC },
  795. { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  796. { "pixel_format", "Preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  797. { "input_format", "Preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  798. { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  799. { "list_formats", "List available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC, "list_formats" },
  800. { "all", "Show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  801. { "raw", "Show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  802. { "compressed", "Show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  803. { "timestamps", "Kind of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, DEC, "timestamps" },
  804. { "default", "Use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  805. { "abs", "Use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  806. { "mono2abs", "Force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  807. { "ts", "Kind of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, DEC, "timestamps" },
  808. { NULL },
  809. };
  810. static const AVClass v4l2_class = {
  811. .class_name = "V4L2 indev",
  812. .item_name = av_default_item_name,
  813. .option = options,
  814. .version = LIBAVUTIL_VERSION_INT,
  815. };
  816. AVInputFormat ff_v4l2_demuxer = {
  817. .name = "video4linux2,v4l2",
  818. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  819. .priv_data_size = sizeof(struct video_data),
  820. .read_header = v4l2_read_header,
  821. .read_packet = v4l2_read_packet,
  822. .read_close = v4l2_read_close,
  823. .flags = AVFMT_NOFILE,
  824. .priv_class = &v4l2_class,
  825. };