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.

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