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://v4l2spec.bytesex.org/v4l2spec/capture.c)
29 * Thanks to Michael Niedermayer for providing the mapping between
30 * V4L2_PIX_FMT_* and 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>
50 #include "libavutil/imgutils.h"
51 #include "libavutil/log.h"
52 #include "libavutil/opt.h"
54 #include "timefilter.h"
55 #include "libavutil/parseutils.h"
56 #include "libavutil/pixdesc.h"
57 #include "libavutil/avstring.h"
62 #define v4l2_open open
63 #define v4l2_close close
65 #define v4l2_ioctl ioctl
66 #define v4l2_read read
67 #define v4l2_mmap mmap
68 #define v4l2_munmap munmap
71 static const int desired_video_buffers = 256;
73 #define V4L_ALLFORMATS 3
74 #define V4L_RAWFORMATS 1
75 #define V4L_COMPFORMATS 2
78 * Return timestamps to the user exactly as returned by the kernel
80 #define V4L_TS_DEFAULT 0
82 * Autodetect the kind of timestamps returned by the kernel and convert to
83 * absolute (wall clock) timestamps.
87 * Assume kernel timestamps are from the monotonic clock and convert to
88 * absolute timestamps.
90 #define V4L_TS_MONO2ABS 2
93 * Once the kind of timestamps returned by the kernel have been detected,
94 * the value of the timefilter (NULL or not) determines whether a conversion
97 #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
102 int frame_format; /* V4L2_PIX_FMT_* */
108 TimeFilter *timefilter;
113 unsigned int *buf_len;
116 char *pixel_format; /**< Set by a private option. */
117 int list_format; /**< Set by a private option. */
118 char *framerate; /**< Set by a private option. */
127 enum PixelFormat ff_fmt;
128 enum CodecID codec_id;
132 static struct fmt_map fmt_conversion_table[] = {
133 //ff_fmt codec_id v4l2_fmt
134 { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
135 { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420 },
136 { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
137 { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
138 { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
139 { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
140 { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
141 { PIX_FMT_RGB555LE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
142 { PIX_FMT_RGB555BE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
143 { PIX_FMT_RGB565LE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
144 { PIX_FMT_RGB565BE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
145 { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
146 { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
147 { PIX_FMT_BGR0, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
148 { PIX_FMT_0RGB, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32 },
149 { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
150 { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
151 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
152 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
155 static int device_open(AVFormatContext *ctx)
157 struct v4l2_capability cap;
165 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
169 fd = v4l2_open(ctx->filename, flags, 0);
173 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
174 ctx->filename, strerror(err));
179 fd_libv4l = v4l2_fd_open(fd, 0);
181 err = AVERROR(errno);
182 av_log(ctx, AV_LOG_ERROR, "Cannot open video device with libv4l neither %s : %s\n",
183 ctx->filename, strerror(errno));
189 res = v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap);
192 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
198 av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",
199 fd, cap.capabilities);
201 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
202 av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
208 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
209 av_log(ctx, AV_LOG_ERROR,
210 "The device does not support the streaming I/O method.\n");
223 static int device_init(AVFormatContext *ctx, int *width, int *height,
226 struct video_data *s = ctx->priv_data;
228 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
229 struct v4l2_pix_format *pix = &fmt.fmt.pix;
234 pix->height = *height;
235 pix->pixelformat = pix_fmt;
236 pix->field = V4L2_FIELD_ANY;
238 res = v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt);
240 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
241 av_log(ctx, AV_LOG_INFO,
242 "The V4L2 driver changed the video from %dx%d to %dx%d\n",
243 *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
244 *width = fmt.fmt.pix.width;
245 *height = fmt.fmt.pix.height;
248 if (pix_fmt != fmt.fmt.pix.pixelformat) {
249 av_log(ctx, AV_LOG_DEBUG,
250 "The V4L2 driver changed the pixel format "
251 "from 0x%08X to 0x%08X\n",
252 pix_fmt, fmt.fmt.pix.pixelformat);
256 if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
257 av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
264 static int first_field(int fd)
269 res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
273 if (std & V4L2_STD_NTSC) {
280 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
284 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
285 if ((codec_id == CODEC_ID_NONE ||
286 fmt_conversion_table[i].codec_id == codec_id) &&
287 (pix_fmt == PIX_FMT_NONE ||
288 fmt_conversion_table[i].ff_fmt == pix_fmt)) {
289 return fmt_conversion_table[i].v4l2_fmt;
296 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
300 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
301 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
302 fmt_conversion_table[i].codec_id == codec_id) {
303 return fmt_conversion_table[i].ff_fmt;
310 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
314 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
315 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
316 return fmt_conversion_table[i].codec_id;
320 return CODEC_ID_NONE;
323 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
324 static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
326 struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
328 while(!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
330 case V4L2_FRMSIZE_TYPE_DISCRETE:
331 av_log(ctx, AV_LOG_INFO, " %ux%u",
332 vfse.discrete.width, vfse.discrete.height);
334 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
335 case V4L2_FRMSIZE_TYPE_STEPWISE:
336 av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
337 vfse.stepwise.min_width,
338 vfse.stepwise.max_width,
339 vfse.stepwise.step_width,
340 vfse.stepwise.min_height,
341 vfse.stepwise.max_height,
342 vfse.stepwise.step_height);
349 static void list_formats(AVFormatContext *ctx, int fd, int type)
351 struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
353 while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
354 enum CodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
355 enum PixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
359 if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
360 type & V4L_RAWFORMATS) {
361 const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
362 av_log(ctx, AV_LOG_INFO, "R : %9s : %20s :",
363 fmt_name ? fmt_name : "Unsupported",
365 } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
366 type & V4L_COMPFORMATS) {
367 AVCodec *codec = avcodec_find_encoder(codec_id);
368 av_log(ctx, AV_LOG_INFO, "C : %9s : %20s :",
369 codec ? codec->name : "Unsupported",
375 #ifdef V4L2_FMT_FLAG_EMULATED
376 if (vfd.flags & V4L2_FMT_FLAG_EMULATED) {
377 av_log(ctx, AV_LOG_WARNING, "%s", "Emulated");
381 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
382 list_framesizes(ctx, fd, vfd.pixelformat);
384 av_log(ctx, AV_LOG_INFO, "\n");
388 static int mmap_init(AVFormatContext *ctx)
391 struct video_data *s = ctx->priv_data;
392 struct v4l2_requestbuffers req = {
393 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
394 .count = desired_video_buffers,
395 .memory = V4L2_MEMORY_MMAP
398 res = v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req);
400 if (errno == EINVAL) {
401 av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
403 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
405 return AVERROR(errno);
409 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
410 return AVERROR(ENOMEM);
412 s->buffers = req.count;
413 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
414 if (s->buf_start == NULL) {
415 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
416 return AVERROR(ENOMEM);
418 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
419 if (s->buf_len == NULL) {
420 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
421 av_free(s->buf_start);
422 return AVERROR(ENOMEM);
425 for (i = 0; i < req.count; i++) {
426 struct v4l2_buffer buf = {
427 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
429 .memory = V4L2_MEMORY_MMAP
431 res = v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
433 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
434 return AVERROR(errno);
437 s->buf_len[i] = buf.length;
438 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
439 av_log(ctx, AV_LOG_ERROR,
440 "Buffer len [%d] = %d != %d\n",
441 i, s->buf_len[i], s->frame_size);
445 s->buf_start[i] = v4l2_mmap(NULL, buf.length,
446 PROT_READ | PROT_WRITE, MAP_SHARED,
447 s->fd, buf.m.offset);
449 if (s->buf_start[i] == MAP_FAILED) {
450 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
451 return AVERROR(errno);
458 static void mmap_release_buffer(AVPacket *pkt)
460 struct v4l2_buffer buf = { 0 };
462 struct buff_data *buf_descriptor = pkt->priv;
464 if (pkt->data == NULL)
467 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
468 buf.memory = V4L2_MEMORY_MMAP;
469 buf.index = buf_descriptor->index;
470 fd = buf_descriptor->fd;
471 av_free(buf_descriptor);
473 res = v4l2_ioctl(fd, VIDIOC_QBUF, &buf);
475 av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
482 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
483 static int64_t av_gettime_monotonic(void)
487 clock_gettime(CLOCK_MONOTONIC, &tv);
488 return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
492 static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
494 struct video_data *s = ctx->priv_data;
498 if (s->ts_mode == V4L_TS_ABS &&
499 ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
500 av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
501 s->ts_mode = V4L_TS_CONVERT_READY;
504 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
505 now = av_gettime_monotonic();
506 if (s->ts_mode == V4L_TS_MONO2ABS ||
507 (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
508 int64_t period = av_rescale_q(1, ctx->streams[0]->codec->time_base,
510 av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
511 /* microseconds instead of seconds, MHz instead of Hz */
512 s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
513 s->ts_mode = V4L_TS_CONVERT_READY;
517 av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
521 static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
523 struct video_data *s = ctx->priv_data;
526 int r = init_convert_timestamp(ctx, *ts);
530 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
532 int64_t nowa = av_gettime();
533 int64_t nowm = av_gettime_monotonic();
534 ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
535 s->last_time_m = nowm;
536 *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
542 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
544 struct video_data *s = ctx->priv_data;
545 struct v4l2_buffer buf = {
546 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
547 .memory = V4L2_MEMORY_MMAP
549 struct buff_data *buf_descriptor;
552 /* FIXME: Some special treatment might be needed in case of loss of signal... */
553 while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
555 if (errno == EAGAIN) {
557 return AVERROR(EAGAIN);
559 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
562 return AVERROR(errno);
564 assert(buf.index < s->buffers);
565 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
566 av_log(ctx, AV_LOG_ERROR,
567 "The v4l2 frame is %d bytes, but %d bytes are expected\n",
568 buf.bytesused, s->frame_size);
570 return AVERROR_INVALIDDATA;
573 /* Image is at s->buff_start[buf.index] */
574 pkt->data= s->buf_start[buf.index];
575 pkt->size = buf.bytesused;
576 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
577 res = convert_timestamp(ctx, &pkt->pts);
580 pkt->destruct = mmap_release_buffer;
581 buf_descriptor = av_malloc(sizeof(struct buff_data));
582 if (buf_descriptor == NULL) {
583 /* Something went wrong... Since av_malloc() failed, we cannot even
584 * allocate a buffer for memcopying into it
586 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
587 res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
589 return AVERROR(ENOMEM);
591 buf_descriptor->fd = s->fd;
592 buf_descriptor->index = buf.index;
593 pkt->priv = buf_descriptor;
595 return s->buf_len[buf.index];
598 static int mmap_start(AVFormatContext *ctx)
600 struct video_data *s = ctx->priv_data;
601 enum v4l2_buf_type type;
604 for (i = 0; i < s->buffers; i++) {
605 struct v4l2_buffer buf = {
606 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
608 .memory = V4L2_MEMORY_MMAP
611 res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
613 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
616 return AVERROR(errno);
620 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
621 res = v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type);
623 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
626 return AVERROR(errno);
632 static void mmap_close(struct video_data *s)
634 enum v4l2_buf_type type;
637 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
638 /* We do not check for the result, because we could
639 * not do anything about it anyway...
641 v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
642 for (i = 0; i < s->buffers; i++) {
643 v4l2_munmap(s->buf_start[i], s->buf_len[i]);
645 av_free(s->buf_start);
649 static int v4l2_set_parameters(AVFormatContext *s1)
651 struct video_data *s = s1->priv_data;
652 struct v4l2_input input = { 0 };
653 struct v4l2_standard standard = { 0 };
654 struct v4l2_streamparm streamparm = { 0 };
655 struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
656 AVRational framerate_q = { 0 };
659 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
662 (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
663 av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
668 /* set tv video input */
669 input.index = s->channel;
670 if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
671 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
675 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
676 s->channel, input.name);
677 if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
678 av_log(s1, AV_LOG_ERROR,
679 "The V4L2 driver ioctl set input(%d) failed\n",
685 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
687 /* set tv standard */
690 ret = v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard);
691 if (ret < 0 || !av_strcasecmp(standard.name, s->standard))
695 av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);
699 av_log(s1, AV_LOG_DEBUG,
700 "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
701 s->standard, (uint64_t)standard.id);
702 if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
703 av_log(s1, AV_LOG_ERROR,
704 "The V4L2 driver ioctl set standard(%s) failed\n",
710 if (framerate_q.num && framerate_q.den) {
711 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
712 framerate_q.den, framerate_q.num);
713 tpf->numerator = framerate_q.den;
714 tpf->denominator = framerate_q.num;
716 if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
717 av_log(s1, AV_LOG_ERROR,
718 "ioctl set time per frame(%d/%d) failed\n",
719 framerate_q.den, framerate_q.num);
723 if (framerate_q.num != tpf->denominator ||
724 framerate_q.den != tpf->numerator) {
725 av_log(s1, AV_LOG_INFO,
726 "The driver changed the time per frame from "
728 framerate_q.den, framerate_q.num,
729 tpf->numerator, tpf->denominator);
732 if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
733 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
735 return AVERROR(errno);
738 s1->streams[0]->codec->time_base.den = tpf->denominator;
739 s1->streams[0]->codec->time_base.num = tpf->numerator;
744 static uint32_t device_try_init(AVFormatContext *s1,
745 enum PixelFormat pix_fmt,
748 enum CodecID *codec_id)
750 uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
752 if (desired_format == 0 ||
753 device_init(s1, width, height, desired_format) < 0) {
757 for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
758 if (s1->video_codec_id == CODEC_ID_NONE ||
759 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
760 desired_format = fmt_conversion_table[i].v4l2_fmt;
761 if (device_init(s1, width, height, desired_format) >= 0) {
769 if (desired_format != 0) {
770 *codec_id = fmt_v4l2codec(desired_format);
771 assert(*codec_id != CODEC_ID_NONE);
774 return desired_format;
777 static int v4l2_read_header(AVFormatContext *s1)
779 struct video_data *s = s1->priv_data;
782 uint32_t desired_format;
783 enum CodecID codec_id;
784 enum PixelFormat pix_fmt = PIX_FMT_NONE;
786 st = avformat_new_stream(s1, NULL);
788 res = AVERROR(ENOMEM);
792 s->fd = device_open(s1);
798 if (s->list_format) {
799 list_formats(s1, s->fd, s->list_format);
804 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
806 if (s->pixel_format) {
807 AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
810 s1->video_codec_id = codec->id;
812 pix_fmt = av_get_pix_fmt(s->pixel_format);
814 if (pix_fmt == PIX_FMT_NONE && !codec) {
815 av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
818 res = AVERROR(EINVAL);
823 if (!s->width && !s->height) {
824 struct v4l2_format fmt;
826 av_log(s1, AV_LOG_VERBOSE,
827 "Querying the device for the current frame size\n");
828 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
829 if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
830 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
832 res = AVERROR(errno);
836 s->width = fmt.fmt.pix.width;
837 s->height = fmt.fmt.pix.height;
838 av_log(s1, AV_LOG_VERBOSE,
839 "Setting frame size to %dx%d\n", s->width, s->height);
842 desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
844 if (desired_format == 0) {
845 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
846 "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
852 if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
855 s->frame_format = desired_format;
857 if ((res = v4l2_set_parameters(s1)) < 0)
860 st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
862 avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
864 if ((res = mmap_init(s1)) ||
865 (res = mmap_start(s1)) < 0) {
870 s->top_field_first = first_field(s->fd);
872 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
873 st->codec->codec_id = codec_id;
874 if (codec_id == CODEC_ID_RAWVIDEO)
875 st->codec->codec_tag =
876 avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
877 if (desired_format == V4L2_PIX_FMT_YVU420)
878 st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
879 st->codec->width = s->width;
880 st->codec->height = s->height;
881 st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
887 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
889 struct video_data *s = s1->priv_data;
890 AVFrame *frame = s1->streams[0]->codec->coded_frame;
894 if ((res = mmap_read_frame(s1, pkt)) < 0) {
898 if (frame && s->interlaced) {
899 frame->interlaced_frame = 1;
900 frame->top_field_first = s->top_field_first;
906 static int v4l2_read_close(AVFormatContext *s1)
908 struct video_data *s = s1->priv_data;
916 #define OFFSET(x) offsetof(struct video_data, x)
917 #define DEC AV_OPT_FLAG_DECODING_PARAM
919 static const AVOption options[] = {
920 { "standard", "TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
921 { "channel", "TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC },
922 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
923 { "pixel_format", "Preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
924 { "input_format", "Preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
925 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
926 { "list_formats", "List available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC, "list_formats" },
927 { "all", "Show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
928 { "raw", "Show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
929 { "compressed", "Show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
930 { "timestamps", "Kind of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, DEC, "timestamps" },
931 { "default", "Use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
932 { "abs", "Use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
933 { "mono2abs", "Force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
934 { "ts", "Kind of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, DEC, "timestamps" },
938 static const AVClass v4l2_class = {
939 .class_name = "V4L2 indev",
940 .item_name = av_default_item_name,
942 .version = LIBAVUTIL_VERSION_INT,
945 AVInputFormat ff_v4l2_demuxer = {
946 .name = "video4linux2,v4l2",
947 .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
948 .priv_data_size = sizeof(struct video_data),
949 .read_header = v4l2_read_header,
950 .read_packet = v4l2_read_packet,
951 .read_close = v4l2_read_close,
952 .flags = AVFMT_NOFILE,
953 .priv_class = &v4l2_class,