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