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
37 #include <sys/ioctl.h>
40 #if HAVE_SYS_VIDEOIO_H
41 #include <sys/videoio.h>
43 #include <asm/types.h>
44 #include <linux/videodev2.h>
48 #include "libavutil/imgutils.h"
49 #include "libavutil/log.h"
50 #include "libavutil/opt.h"
52 #include "libavutil/parseutils.h"
53 #include "libavutil/pixdesc.h"
55 static const int desired_video_buffers = 256;
66 int frame_format; /* V4L2_PIX_FMT_* */
67 enum io_method io_method;
74 unsigned int *buf_len;
77 char *video_size; /**< String describing video size, set by a private option. */
78 char *pixel_format; /**< Set by a private option. */
79 char *framerate; /**< Set by a private option. */
88 enum PixelFormat ff_fmt;
89 enum CodecID codec_id;
93 static struct fmt_map fmt_conversion_table[] = {
94 //ff_fmt codec_id v4l2_fmt
95 { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
96 { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
97 { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
98 { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
99 { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
100 { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
101 { PIX_FMT_RGB555, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
102 { PIX_FMT_RGB565, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
103 { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
104 { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
105 { PIX_FMT_BGRA, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
106 { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
107 { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
108 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
109 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
112 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
114 struct v4l2_capability cap;
119 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
122 fd = open(ctx->filename, flags, 0);
124 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
125 ctx->filename, strerror(errno));
126 return AVERROR(errno);
129 res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
130 // ENOIOCTLCMD definition only availble on __KERNEL__
131 if (res < 0 && ((err = errno) == 515)) {
132 av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
138 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
143 if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
144 av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
146 return AVERROR(ENODEV);
148 *capabilities = cap.capabilities;
153 static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
155 struct video_data *s = ctx->priv_data;
157 struct v4l2_format fmt = {0};
160 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
161 fmt.fmt.pix.width = *width;
162 fmt.fmt.pix.height = *height;
163 fmt.fmt.pix.pixelformat = pix_fmt;
164 fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
165 res = ioctl(fd, VIDIOC_S_FMT, &fmt);
166 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
167 av_log(ctx, AV_LOG_INFO, "The V4L2 driver changed the video from %dx%d to %dx%d\n", *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
168 *width = fmt.fmt.pix.width;
169 *height = fmt.fmt.pix.height;
172 if (pix_fmt != fmt.fmt.pix.pixelformat) {
173 av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver changed the pixel format from 0x%08X to 0x%08X\n", pix_fmt, fmt.fmt.pix.pixelformat);
180 static int first_field(int fd)
185 res = ioctl(fd, VIDIOC_G_STD, &std);
189 if (std & V4L2_STD_NTSC) {
196 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
200 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
201 if ((codec_id == CODEC_ID_NONE ||
202 fmt_conversion_table[i].codec_id == codec_id) &&
203 (pix_fmt == PIX_FMT_NONE ||
204 fmt_conversion_table[i].ff_fmt == pix_fmt)) {
205 return fmt_conversion_table[i].v4l2_fmt;
212 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
216 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
217 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
218 fmt_conversion_table[i].codec_id == codec_id) {
219 return fmt_conversion_table[i].ff_fmt;
226 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
230 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
231 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
232 return fmt_conversion_table[i].codec_id;
236 return CODEC_ID_NONE;
239 static int mmap_init(AVFormatContext *ctx)
241 struct video_data *s = ctx->priv_data;
242 struct v4l2_requestbuffers req = {0};
245 req.count = desired_video_buffers;
246 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
247 req.memory = V4L2_MEMORY_MMAP;
248 res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
250 if (errno == EINVAL) {
251 av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
253 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
255 return AVERROR(errno);
259 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
260 return AVERROR(ENOMEM);
262 s->buffers = req.count;
263 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
264 if (s->buf_start == NULL) {
265 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
266 return AVERROR(ENOMEM);
268 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
269 if (s->buf_len == NULL) {
270 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
271 av_free(s->buf_start);
272 return AVERROR(ENOMEM);
275 for (i = 0; i < req.count; i++) {
276 struct v4l2_buffer buf = {0};
278 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
279 buf.memory = V4L2_MEMORY_MMAP;
281 res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
283 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
284 return AVERROR(errno);
287 s->buf_len[i] = buf.length;
288 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
289 av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
293 s->buf_start[i] = mmap (NULL, buf.length,
294 PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
295 if (s->buf_start[i] == MAP_FAILED) {
296 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
297 return AVERROR(errno);
304 static int read_init(AVFormatContext *ctx)
309 static void mmap_release_buffer(AVPacket *pkt)
311 struct v4l2_buffer buf = {0};
313 struct buff_data *buf_descriptor = pkt->priv;
315 if (pkt->data == NULL) {
319 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
320 buf.memory = V4L2_MEMORY_MMAP;
321 buf.index = buf_descriptor->index;
322 fd = buf_descriptor->fd;
323 av_free(buf_descriptor);
325 res = ioctl(fd, VIDIOC_QBUF, &buf);
327 av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
333 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
335 struct video_data *s = ctx->priv_data;
336 struct v4l2_buffer buf = {0};
337 struct buff_data *buf_descriptor;
340 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
341 buf.memory = V4L2_MEMORY_MMAP;
343 /* FIXME: Some special treatment might be needed in case of loss of signal... */
344 while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
346 if (errno == EAGAIN) {
348 return AVERROR(EAGAIN);
350 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
352 return AVERROR(errno);
354 assert(buf.index < s->buffers);
355 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
356 av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
357 return AVERROR_INVALIDDATA;
360 /* Image is at s->buff_start[buf.index] */
361 pkt->data= s->buf_start[buf.index];
362 pkt->size = buf.bytesused;
363 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
364 pkt->destruct = mmap_release_buffer;
365 buf_descriptor = av_malloc(sizeof(struct buff_data));
366 if (buf_descriptor == NULL) {
367 /* Something went wrong... Since av_malloc() failed, we cannot even
368 * allocate a buffer for memcopying into it
370 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
371 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
373 return AVERROR(ENOMEM);
375 buf_descriptor->fd = s->fd;
376 buf_descriptor->index = buf.index;
377 pkt->priv = buf_descriptor;
379 return s->buf_len[buf.index];
382 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
387 static int mmap_start(AVFormatContext *ctx)
389 struct video_data *s = ctx->priv_data;
390 enum v4l2_buf_type type;
393 for (i = 0; i < s->buffers; i++) {
394 struct v4l2_buffer buf = {0};
396 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
397 buf.memory = V4L2_MEMORY_MMAP;
400 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
402 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
403 return AVERROR(errno);
407 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
408 res = ioctl(s->fd, VIDIOC_STREAMON, &type);
410 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
411 return AVERROR(errno);
417 static void mmap_close(struct video_data *s)
419 enum v4l2_buf_type type;
422 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
423 /* We do not check for the result, because we could
424 * not do anything about it anyway...
426 ioctl(s->fd, VIDIOC_STREAMOFF, &type);
427 for (i = 0; i < s->buffers; i++) {
428 munmap(s->buf_start[i], s->buf_len[i]);
430 av_free(s->buf_start);
434 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
436 struct video_data *s = s1->priv_data;
437 struct v4l2_input input = {0};
438 struct v4l2_standard standard = {0};
439 struct v4l2_streamparm streamparm = {0};
440 struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
444 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
446 if (s->framerate && (ret = av_parse_video_rate(&fps, s->framerate)) < 0) {
447 av_log(s1, AV_LOG_ERROR, "Couldn't parse framerate.\n");
450 #if FF_API_FORMAT_PARAMETERS
452 s->channel = ap->channel;
453 if (ap->time_base.num)
454 fps = (AVRational){ap->time_base.den, ap->time_base.num};
457 /* set tv video input */
458 input.index = s->channel;
459 if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
460 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
464 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
465 s->channel, input.name);
466 if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
467 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
472 #if FF_API_FORMAT_PARAMETERS
474 av_freep(&s->standard);
475 s->standard = av_strdup(ap->standard);
480 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
482 /* set tv standard */
485 ret = ioctl(s->fd, VIDIOC_ENUMSTD, &standard);
486 if (ret < 0 || !strcasecmp(standard.name, s->standard))
490 av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);
494 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
495 s->standard, (uint64_t)standard.id);
496 if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
497 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
503 if (fps.num && fps.den) {
504 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
506 tpf->numerator = fps.den;
507 tpf->denominator = fps.num;
508 if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
509 av_log(s1, AV_LOG_ERROR,
510 "ioctl set time per frame(%d/%d) failed\n",
515 if (fps.num != tpf->denominator ||
516 fps.den != tpf->numerator) {
517 av_log(s1, AV_LOG_INFO,
518 "The driver changed the time per frame from %d/%d to %d/%d\n",
520 tpf->numerator, tpf->denominator);
523 /* if timebase value is not set, read the timebase value from the driver */
524 if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
525 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
526 return AVERROR(errno);
529 s1->streams[0]->codec->time_base.den = tpf->denominator;
530 s1->streams[0]->codec->time_base.num = tpf->numerator;
535 static uint32_t device_try_init(AVFormatContext *s1,
536 enum PixelFormat pix_fmt,
539 enum CodecID *codec_id)
541 uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
543 if (desired_format == 0 ||
544 device_init(s1, width, height, desired_format) < 0) {
548 for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
549 if (s1->video_codec_id == CODEC_ID_NONE ||
550 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
551 desired_format = fmt_conversion_table[i].v4l2_fmt;
552 if (device_init(s1, width, height, desired_format) >= 0) {
559 if (desired_format != 0) {
560 *codec_id = fmt_v4l2codec(desired_format);
561 assert(*codec_id != CODEC_ID_NONE);
564 return desired_format;
567 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
569 struct video_data *s = s1->priv_data;
572 uint32_t desired_format, capabilities;
573 enum CodecID codec_id;
574 enum PixelFormat pix_fmt = PIX_FMT_NONE;
576 st = av_new_stream(s1, 0);
578 res = AVERROR(ENOMEM);
581 av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
583 if (s->video_size && (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
584 av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
587 if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
588 av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
589 res = AVERROR(EINVAL);
592 #if FF_API_FORMAT_PARAMETERS
594 s->width = ap->width;
596 s->height = ap->height;
598 pix_fmt = ap->pix_fmt;
602 s->fd = device_open(s1, &capabilities);
607 av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
609 if (!s->width && !s->height) {
610 struct v4l2_format fmt;
612 av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
613 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
614 if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
615 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
616 res = AVERROR(errno);
619 s->width = fmt.fmt.pix.width;
620 s->height = fmt.fmt.pix.height;
621 av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
624 desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height, &codec_id);
625 if (desired_format == 0) {
626 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
627 "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
633 if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
635 s->frame_format = desired_format;
637 if ((res = v4l2_set_parameters(s1, ap) < 0))
640 st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
641 s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
642 if (capabilities & V4L2_CAP_STREAMING) {
643 s->io_method = io_mmap;
646 res = mmap_start(s1);
649 s->io_method = io_read;
657 s->top_field_first = first_field(s->fd);
659 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
660 st->codec->codec_id = codec_id;
661 st->codec->width = s->width;
662 st->codec->height = s->height;
663 st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
669 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
671 struct video_data *s = s1->priv_data;
674 if (s->io_method == io_mmap) {
676 res = mmap_read_frame(s1, pkt);
677 } else if (s->io_method == io_read) {
678 if (av_new_packet(pkt, s->frame_size) < 0)
681 res = read_frame(s1, pkt);
689 if (s1->streams[0]->codec->coded_frame) {
690 s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
691 s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
697 static int v4l2_read_close(AVFormatContext *s1)
699 struct video_data *s = s1->priv_data;
701 if (s->io_method == io_mmap) {
709 #define OFFSET(x) offsetof(struct video_data, x)
710 #define DEC AV_OPT_FLAG_DECODING_PARAM
712 static const AVOption options[] = {
713 { "standard", "", OFFSET(standard), FF_OPT_TYPE_STRING, {.str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
714 { "channel", "", OFFSET(channel), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
715 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
716 { "pixel_format", "", OFFSET(pixel_format), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
717 { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
721 static const AVClass v4l2_class = {
722 .class_name = "V4L2 indev",
723 .item_name = av_default_item_name,
725 .version = LIBAVUTIL_VERSION_INT,
728 AVInputFormat ff_v4l2_demuxer = {
730 NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
731 sizeof(struct video_data),
736 .flags = AVFMT_NOFILE,
737 .priv_class = &v4l2_class,