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.

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