2 * Copyright (c) 2000,2001 Fabrice Bellard
3 * Copyright (c) 2006 Luca Abeni
5 * This file is part of FFmpeg.
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.
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.
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
24 * Video4Linux2 grab interface
26 * Part of this file is based on the V4L2 video capture example
27 * (http://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
29 * Thanks to Michael Niedermayer for providing the mapping between
30 * V4L2_PIX_FMT_* and AV_PIX_FMT_*
33 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
35 #include "libavformat/internal.h"
38 #include <sys/ioctl.h>
41 #if HAVE_SYS_VIDEOIO_H
42 #include <sys/videoio.h>
45 #include <asm/types.h>
47 #include <linux/videodev2.h>
49 #include "libavutil/atomic.h"
50 #include "libavutil/avassert.h"
51 #include "libavutil/imgutils.h"
52 #include "libavutil/log.h"
53 #include "libavutil/opt.h"
55 #include "timefilter.h"
56 #include "libavutil/parseutils.h"
57 #include "libavutil/pixdesc.h"
58 #include "libavutil/time.h"
59 #include "libavutil/avstring.h"
64 #define v4l2_open open
65 #define v4l2_close close
67 #define v4l2_ioctl ioctl
68 #define v4l2_read read
69 #define v4l2_mmap mmap
70 #define v4l2_munmap munmap
73 static const int desired_video_buffers = 256;
75 #define V4L_ALLFORMATS 3
76 #define V4L_RAWFORMATS 1
77 #define V4L_COMPFORMATS 2
80 * Return timestamps to the user exactly as returned by the kernel
82 #define V4L_TS_DEFAULT 0
84 * Autodetect the kind of timestamps returned by the kernel and convert to
85 * absolute (wall clock) timestamps.
89 * Assume kernel timestamps are from the monotonic clock and convert to
90 * absolute timestamps.
92 #define V4L_TS_MONO2ABS 2
95 * Once the kind of timestamps returned by the kernel have been detected,
96 * the value of the timefilter (NULL or not) determines whether a conversion
99 #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
104 int frame_format; /* V4L2_PIX_FMT_* */
110 TimeFilter *timefilter;
114 volatile int buffers_queued;
116 unsigned int *buf_len;
120 char *pixel_format; /**< Set by a private option. */
121 int list_format; /**< Set by a private option. */
122 int list_standard; /**< Set by a private option. */
123 char *framerate; /**< Set by a private option. */
127 struct video_data *s;
132 enum AVPixelFormat ff_fmt;
133 enum AVCodecID codec_id;
137 static struct fmt_map fmt_conversion_table[] = {
138 //ff_fmt codec_id v4l2_fmt
139 { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
140 { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420 },
141 { AV_PIX_FMT_YUV422P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
142 { AV_PIX_FMT_YUYV422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
143 { AV_PIX_FMT_UYVY422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
144 { AV_PIX_FMT_YUV411P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
145 { AV_PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
146 { AV_PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU410 },
147 { AV_PIX_FMT_RGB555LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
148 { AV_PIX_FMT_RGB555BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
149 { AV_PIX_FMT_RGB565LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
150 { AV_PIX_FMT_RGB565BE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
151 { AV_PIX_FMT_BGR24, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
152 { AV_PIX_FMT_RGB24, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
153 { AV_PIX_FMT_BGR0, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
154 { AV_PIX_FMT_0RGB, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32 },
155 { AV_PIX_FMT_GRAY8, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
156 #ifdef V4L2_PIX_FMT_Y16
157 { AV_PIX_FMT_GRAY16LE,AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_Y16 },
159 { AV_PIX_FMT_NV12, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
160 { AV_PIX_FMT_NONE, AV_CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
161 { AV_PIX_FMT_NONE, AV_CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
162 #ifdef V4L2_PIX_FMT_H264
163 { AV_PIX_FMT_NONE, AV_CODEC_ID_H264, V4L2_PIX_FMT_H264 },
165 #ifdef V4L2_PIX_FMT_CPIA1
166 { AV_PIX_FMT_NONE, AV_CODEC_ID_CPIA, V4L2_PIX_FMT_CPIA1 },
170 static int device_open(AVFormatContext *ctx)
172 struct v4l2_capability cap;
177 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
181 fd = v4l2_open(ctx->filename, flags, 0);
183 ret = AVERROR(errno);
184 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
185 ctx->filename, av_err2str(ret));
189 if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
190 ret = AVERROR(errno);
191 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
196 av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
197 fd, cap.capabilities);
199 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
200 av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
201 ret = AVERROR(ENODEV);
205 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
206 av_log(ctx, AV_LOG_ERROR,
207 "The device does not support the streaming I/O method.\n");
208 ret = AVERROR(ENOSYS);
219 static int device_init(AVFormatContext *ctx, int *width, int *height,
222 struct video_data *s = ctx->priv_data;
224 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
225 struct v4l2_pix_format *pix = &fmt.fmt.pix;
230 pix->height = *height;
231 pix->pixelformat = pix_fmt;
232 pix->field = V4L2_FIELD_ANY;
234 if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
235 res = AVERROR(errno);
237 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
238 av_log(ctx, AV_LOG_INFO,
239 "The V4L2 driver changed the video from %dx%d to %dx%d\n",
240 *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
241 *width = fmt.fmt.pix.width;
242 *height = fmt.fmt.pix.height;
245 if (pix_fmt != fmt.fmt.pix.pixelformat) {
246 av_log(ctx, AV_LOG_DEBUG,
247 "The V4L2 driver changed the pixel format "
248 "from 0x%08X to 0x%08X\n",
249 pix_fmt, fmt.fmt.pix.pixelformat);
250 res = AVERROR(EINVAL);
253 if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
254 av_log(ctx, AV_LOG_DEBUG,
255 "The V4L2 driver is using the interlaced mode\n");
262 static int first_field(int fd)
267 res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
271 if (std & V4L2_STD_NTSC) {
278 static uint32_t fmt_ff2v4l(enum AVPixelFormat pix_fmt, enum AVCodecID codec_id)
282 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
283 if ((codec_id == AV_CODEC_ID_NONE ||
284 fmt_conversion_table[i].codec_id == codec_id) &&
285 (pix_fmt == AV_PIX_FMT_NONE ||
286 fmt_conversion_table[i].ff_fmt == pix_fmt)) {
287 return fmt_conversion_table[i].v4l2_fmt;
294 static enum AVPixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum AVCodecID codec_id)
298 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
299 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
300 fmt_conversion_table[i].codec_id == codec_id) {
301 return fmt_conversion_table[i].ff_fmt;
305 return AV_PIX_FMT_NONE;
308 static enum AVCodecID fmt_v4l2codec(uint32_t v4l2_fmt)
312 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
313 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
314 return fmt_conversion_table[i].codec_id;
318 return AV_CODEC_ID_NONE;
321 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
322 static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
324 struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
326 while(!v4l2_ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
328 case V4L2_FRMSIZE_TYPE_DISCRETE:
329 av_log(ctx, AV_LOG_INFO, " %ux%u",
330 vfse.discrete.width, vfse.discrete.height);
332 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
333 case V4L2_FRMSIZE_TYPE_STEPWISE:
334 av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
335 vfse.stepwise.min_width,
336 vfse.stepwise.max_width,
337 vfse.stepwise.step_width,
338 vfse.stepwise.min_height,
339 vfse.stepwise.max_height,
340 vfse.stepwise.step_height);
347 static void list_formats(AVFormatContext *ctx, int fd, int type)
349 struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
351 while(!v4l2_ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
352 enum AVCodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
353 enum AVPixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
357 if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
358 type & V4L_RAWFORMATS) {
359 const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
360 av_log(ctx, AV_LOG_INFO, "Raw : %9s : %20s :",
361 fmt_name ? fmt_name : "Unsupported",
363 } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
364 type & V4L_COMPFORMATS) {
365 AVCodec *codec = avcodec_find_decoder(codec_id);
366 av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
367 codec ? codec->name : "Unsupported",
373 #ifdef V4L2_FMT_FLAG_EMULATED
374 if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
375 av_log(ctx, AV_LOG_INFO, " Emulated :");
377 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
378 list_framesizes(ctx, fd, vfd.pixelformat);
380 av_log(ctx, AV_LOG_INFO, "\n");
384 static void list_standards(AVFormatContext *ctx)
387 struct video_data *s = ctx->priv_data;
388 struct v4l2_standard standard;
393 for (standard.index = 0; ; standard.index++) {
394 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
395 ret = AVERROR(errno);
396 if (ret == AVERROR(EINVAL)) {
399 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
403 av_log(ctx, AV_LOG_INFO, "%2d, %16llx, %s\n",
404 standard.index, standard.id, standard.name);
408 static int mmap_init(AVFormatContext *ctx)
411 struct video_data *s = ctx->priv_data;
412 struct v4l2_requestbuffers req = {
413 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
414 .count = desired_video_buffers,
415 .memory = V4L2_MEMORY_MMAP
418 if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
419 res = AVERROR(errno);
420 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
425 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
426 return AVERROR(ENOMEM);
428 s->buffers = req.count;
429 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
430 if (s->buf_start == NULL) {
431 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
432 return AVERROR(ENOMEM);
434 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
435 if (s->buf_len == NULL) {
436 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
437 av_free(s->buf_start);
438 return AVERROR(ENOMEM);
441 for (i = 0; i < req.count; i++) {
442 struct v4l2_buffer buf = {
443 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
445 .memory = V4L2_MEMORY_MMAP
447 if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
448 res = AVERROR(errno);
449 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
453 s->buf_len[i] = buf.length;
454 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
455 av_log(ctx, AV_LOG_ERROR,
456 "buf_len[%d] = %d < expected frame size %d\n",
457 i, s->buf_len[i], s->frame_size);
458 return AVERROR(ENOMEM);
460 s->buf_start[i] = v4l2_mmap(NULL, buf.length,
461 PROT_READ | PROT_WRITE, MAP_SHARED,
462 s->fd, buf.m.offset);
464 if (s->buf_start[i] == MAP_FAILED) {
465 res = AVERROR(errno);
466 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
474 #if FF_API_DESTRUCT_PACKET
475 static void dummy_release_buffer(AVPacket *pkt)
481 static void mmap_release_buffer(void *opaque, uint8_t *data)
483 struct v4l2_buffer buf = { 0 };
485 struct buff_data *buf_descriptor = opaque;
486 struct video_data *s = buf_descriptor->s;
488 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
489 buf.memory = V4L2_MEMORY_MMAP;
490 buf.index = buf_descriptor->index;
491 av_free(buf_descriptor);
493 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
494 res = AVERROR(errno);
495 av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
499 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
502 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
503 static int64_t av_gettime_monotonic(void)
507 clock_gettime(CLOCK_MONOTONIC, &tv);
508 return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
512 static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
514 struct video_data *s = ctx->priv_data;
518 if (s->ts_mode == V4L_TS_ABS &&
519 ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
520 av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
521 s->ts_mode = V4L_TS_CONVERT_READY;
524 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
525 now = av_gettime_monotonic();
526 if (s->ts_mode == V4L_TS_MONO2ABS ||
527 (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
528 AVRational tb = {AV_TIME_BASE, 1};
529 int64_t period = av_rescale_q(1, tb, ctx->streams[0]->avg_frame_rate);
530 av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
531 /* microseconds instead of seconds, MHz instead of Hz */
532 s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
533 s->ts_mode = V4L_TS_CONVERT_READY;
537 av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
541 static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
543 struct video_data *s = ctx->priv_data;
546 int r = init_convert_timestamp(ctx, *ts);
550 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
552 int64_t nowa = av_gettime();
553 int64_t nowm = av_gettime_monotonic();
554 ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
555 s->last_time_m = nowm;
556 *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
562 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
564 struct video_data *s = ctx->priv_data;
565 struct v4l2_buffer buf = {
566 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
567 .memory = V4L2_MEMORY_MMAP
571 /* FIXME: Some special treatment might be needed in case of loss of signal... */
572 while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
574 if (errno == EAGAIN) {
576 return AVERROR(EAGAIN);
578 res = AVERROR(errno);
579 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
583 if (buf.index >= s->buffers) {
584 av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
585 return AVERROR(EINVAL);
587 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
588 // always keep at least one buffer queued
589 av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
591 /* CPIA is a compressed format and we don't know the exact number of bytes
592 * used by a frame, so set it here as the driver announces it.
594 if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
595 s->frame_size = buf.bytesused;
597 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
598 av_log(ctx, AV_LOG_ERROR,
599 "The v4l2 frame is %d bytes, but %d bytes are expected\n",
600 buf.bytesused, s->frame_size);
601 return AVERROR_INVALIDDATA;
604 /* Image is at s->buff_start[buf.index] */
605 if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
606 /* when we start getting low on queued buffers, fall back on copying data */
607 res = av_new_packet(pkt, buf.bytesused);
609 av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
610 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
611 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
614 memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
616 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
617 res = AVERROR(errno);
618 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
622 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
624 struct buff_data *buf_descriptor;
626 pkt->data = s->buf_start[buf.index];
627 pkt->size = buf.bytesused;
628 #if FF_API_DESTRUCT_PACKET
629 pkt->destruct = dummy_release_buffer;
632 buf_descriptor = av_malloc(sizeof(struct buff_data));
633 if (buf_descriptor == NULL) {
634 /* Something went wrong... Since av_malloc() failed, we cannot even
635 * allocate a buffer for memcpying into it
637 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
638 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
639 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
641 return AVERROR(ENOMEM);
643 buf_descriptor->index = buf.index;
644 buf_descriptor->s = s;
646 pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
649 av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
650 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
651 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
652 av_freep(&buf_descriptor);
653 return AVERROR(ENOMEM);
656 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
657 convert_timestamp(ctx, &pkt->pts);
659 return s->buf_len[buf.index];
662 static int mmap_start(AVFormatContext *ctx)
664 struct video_data *s = ctx->priv_data;
665 enum v4l2_buf_type type;
668 for (i = 0; i < s->buffers; i++) {
669 struct v4l2_buffer buf = {
670 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
672 .memory = V4L2_MEMORY_MMAP
675 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
676 res = AVERROR(errno);
677 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
681 s->buffers_queued = s->buffers;
683 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
684 if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
685 res = AVERROR(errno);
686 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
693 static void mmap_close(struct video_data *s)
695 enum v4l2_buf_type type;
698 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
699 /* We do not check for the result, because we could
700 * not do anything about it anyway...
702 v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
703 for (i = 0; i < s->buffers; i++) {
704 v4l2_munmap(s->buf_start[i], s->buf_len[i]);
706 av_free(s->buf_start);
710 static int v4l2_set_parameters(AVFormatContext *s1)
712 struct video_data *s = s1->priv_data;
713 struct v4l2_standard standard = { 0 };
714 struct v4l2_streamparm streamparm = { 0 };
715 struct v4l2_fract *tpf;
716 AVRational framerate_q = { 0 };
720 (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
721 av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
729 av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
730 /* set tv standard */
733 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
734 ret = AVERROR(errno);
737 if (!av_strcasecmp(standard.name, s->standard))
741 av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
745 if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
746 ret = AVERROR(errno);
747 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
751 av_log(s1, AV_LOG_WARNING,
752 "This device does not support any standard\n");
757 if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
758 tpf = &standard.frameperiod;
761 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
762 ret = AVERROR(errno);
763 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
766 if (standard.id == s->std_id) {
767 av_log(s1, AV_LOG_DEBUG,
768 "Current standard: %s, id: %"PRIu64", frameperiod: %d/%d\n",
769 standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
774 tpf = &streamparm.parm.capture.timeperframe;
777 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
778 if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
779 ret = AVERROR(errno);
780 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
784 if (framerate_q.num && framerate_q.den) {
785 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
786 tpf = &streamparm.parm.capture.timeperframe;
788 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
789 framerate_q.den, framerate_q.num);
790 tpf->numerator = framerate_q.den;
791 tpf->denominator = framerate_q.num;
793 if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
794 ret = AVERROR(errno);
795 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
799 if (framerate_q.num != tpf->denominator ||
800 framerate_q.den != tpf->numerator) {
801 av_log(s1, AV_LOG_INFO,
802 "The driver changed the time per frame from "
804 framerate_q.den, framerate_q.num,
805 tpf->numerator, tpf->denominator);
808 av_log(s1, AV_LOG_WARNING,
809 "The driver does not allow to change time per frame\n");
812 s1->streams[0]->avg_frame_rate.num = tpf->denominator;
813 s1->streams[0]->avg_frame_rate.den = tpf->numerator;
814 s1->streams[0]->r_frame_rate = s1->streams[0]->avg_frame_rate;
819 static int device_try_init(AVFormatContext *s1,
820 enum AVPixelFormat pix_fmt,
823 uint32_t *desired_format,
824 enum AVCodecID *codec_id)
828 *desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
830 if (*desired_format) {
831 ret = device_init(s1, width, height, *desired_format);
834 if (ret != AVERROR(EINVAL))
839 if (!*desired_format) {
840 for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
841 if (s1->video_codec_id == AV_CODEC_ID_NONE ||
842 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
843 av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
844 avcodec_get_name(fmt_conversion_table[i].codec_id),
845 (char *)av_x_if_null(av_get_pix_fmt_name(fmt_conversion_table[i].ff_fmt), "none"));
847 *desired_format = fmt_conversion_table[i].v4l2_fmt;
848 ret = device_init(s1, width, height, *desired_format);
851 else if (ret != AVERROR(EINVAL))
857 if (*desired_format == 0) {
858 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
859 "codec '%s' (id %d), pixel format '%s' (id %d)\n",
860 avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
861 (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
862 ret = AVERROR(EINVAL);
866 *codec_id = fmt_v4l2codec(*desired_format);
867 av_assert0(*codec_id != AV_CODEC_ID_NONE);
871 static int v4l2_read_header(AVFormatContext *s1)
873 struct video_data *s = s1->priv_data;
876 uint32_t desired_format;
877 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
878 enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
879 struct v4l2_input input = { 0 };
881 st = avformat_new_stream(s1, NULL);
883 return AVERROR(ENOMEM);
886 /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
887 and errors will get sent to stderr */
888 v4l2_log_file = fopen("/dev/null", "w");
891 s->fd = device_open(s1);
895 if (s->channel != -1) {
896 /* set video input */
897 av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
898 if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
899 res = AVERROR(errno);
900 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
904 /* get current video input */
905 if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
906 res = AVERROR(errno);
907 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
913 input.index = s->channel;
914 if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
915 res = AVERROR(errno);
916 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
919 s->std_id = input.std;
920 av_log(s1, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s\n",
921 s->channel, input.name);
923 if (s->list_format) {
924 list_formats(s1, s->fd, s->list_format);
928 if (s->list_standard) {
933 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
935 if (s->pixel_format) {
936 AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
939 s1->video_codec_id = codec->id;
941 pix_fmt = av_get_pix_fmt(s->pixel_format);
943 if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
944 av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
947 return AVERROR(EINVAL);
951 if (!s->width && !s->height) {
952 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
954 av_log(s1, AV_LOG_VERBOSE,
955 "Querying the device for the current frame size\n");
956 if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
957 res = AVERROR(errno);
958 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
962 s->width = fmt.fmt.pix.width;
963 s->height = fmt.fmt.pix.height;
964 av_log(s1, AV_LOG_VERBOSE,
965 "Setting frame size to %dx%d\n", s->width, s->height);
968 res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
974 /* If no pixel_format was specified, the codec_id was not known up
975 * until now. Set video_codec_id in the context, as codec_id will
976 * not be available outside this function
978 if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
979 s1->video_codec_id = codec_id;
981 if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
984 s->frame_format = desired_format;
986 if ((res = v4l2_set_parameters(s1)) < 0)
989 st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
991 avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
993 if ((res = mmap_init(s1)) ||
994 (res = mmap_start(s1)) < 0) {
999 s->top_field_first = first_field(s->fd);
1001 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1002 st->codec->codec_id = codec_id;
1003 if (codec_id == AV_CODEC_ID_RAWVIDEO)
1004 st->codec->codec_tag =
1005 avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
1006 if (desired_format == V4L2_PIX_FMT_YVU420)
1007 st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
1008 else if (desired_format == V4L2_PIX_FMT_YVU410)
1009 st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
1010 st->codec->width = s->width;
1011 st->codec->height = s->height;
1012 st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
1017 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
1019 struct video_data *s = s1->priv_data;
1020 AVFrame *frame = s1->streams[0]->codec->coded_frame;
1023 av_init_packet(pkt);
1024 if ((res = mmap_read_frame(s1, pkt)) < 0) {
1028 if (frame && s->interlaced) {
1029 frame->interlaced_frame = 1;
1030 frame->top_field_first = s->top_field_first;
1036 static int v4l2_read_close(AVFormatContext *s1)
1038 struct video_data *s = s1->priv_data;
1040 if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
1041 av_log(s1, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
1050 #define OFFSET(x) offsetof(struct video_data, x)
1051 #define DEC AV_OPT_FLAG_DECODING_PARAM
1053 static const AVOption options[] = {
1054 { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
1055 { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
1056 { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
1057 { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
1058 { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
1059 { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
1061 { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
1062 { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
1063 { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
1064 { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
1066 { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
1067 { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
1069 { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
1070 { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
1071 { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
1072 { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
1073 { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
1078 static const AVClass v4l2_class = {
1079 .class_name = "V4L2 indev",
1080 .item_name = av_default_item_name,
1082 .version = LIBAVUTIL_VERSION_INT,
1085 AVInputFormat ff_v4l2_demuxer = {
1086 .name = "video4linux2,v4l2",
1087 .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
1088 .priv_data_size = sizeof(struct video_data),
1089 .read_header = v4l2_read_header,
1090 .read_packet = v4l2_read_packet,
1091 .read_close = v4l2_read_close,
1092 .flags = AVFMT_NOFILE,
1093 .priv_class = &v4l2_class,