2 * Video4Linux2 grab interface
3 * Copyright (c) 2000,2001 Fabrice Bellard
4 * Copyright (c) 2006 Luca Abeni
6 * Part of this file is based on the V4L2 video capture example
7 * (http://v4l2spec.bytesex.org/v4l2spec/capture.c)
9 * Thanks to Michael Niedermayer for providing the mapping between
10 * V4L2_PIX_FMT_* and PIX_FMT_*
13 * This file is part of FFmpeg.
15 * FFmpeg is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * FFmpeg is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with FFmpeg; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
32 #include "libavformat/avformat.h"
35 #include <sys/ioctl.h>
38 #if HAVE_SYS_VIDEOIO_H
39 #include <sys/videoio.h>
41 #include <asm/types.h>
42 #include <linux/videodev2.h>
46 #include "libavcore/imgutils.h"
48 static const int desired_video_buffers = 256;
58 int frame_format; /* V4L2_PIX_FMT_* */
59 enum io_method io_method;
66 unsigned int *buf_len;
75 enum PixelFormat ff_fmt;
76 enum CodecID codec_id;
80 static struct fmt_map fmt_conversion_table[] = {
81 //ff_fmt codec_id v4l2_fmt
82 { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
83 { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
84 { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
85 { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
86 { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
87 { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
88 { PIX_FMT_RGB555, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
89 { PIX_FMT_RGB565, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
90 { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
91 { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
92 { PIX_FMT_BGRA, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
93 { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
94 { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
95 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
96 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
99 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
101 struct v4l2_capability cap;
106 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
109 fd = open(ctx->filename, flags, 0);
111 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
112 ctx->filename, strerror(errno));
114 return AVERROR(errno);
117 res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
118 // ENOIOCTLCMD definition only availble on __KERNEL__
119 if (res < 0 && ((err = errno) == 515)) {
120 av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
126 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
132 if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
133 av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
136 return AVERROR(ENODEV);
138 *capabilities = cap.capabilities;
143 static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
145 struct video_data *s = ctx->priv_data;
147 struct v4l2_format fmt;
150 memset(&fmt, 0, sizeof(struct v4l2_format));
151 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
152 fmt.fmt.pix.width = *width;
153 fmt.fmt.pix.height = *height;
154 fmt.fmt.pix.pixelformat = pix_fmt;
155 fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
156 res = ioctl(fd, VIDIOC_S_FMT, &fmt);
157 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
158 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);
159 *width = fmt.fmt.pix.width;
160 *height = fmt.fmt.pix.height;
163 if (pix_fmt != fmt.fmt.pix.pixelformat) {
164 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);
171 static int first_field(int fd)
176 res = ioctl(fd, VIDIOC_G_STD, &std);
180 if (std & V4L2_STD_NTSC) {
187 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
191 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
192 if ((codec_id == CODEC_ID_NONE ||
193 fmt_conversion_table[i].codec_id == codec_id) &&
194 (pix_fmt == PIX_FMT_NONE ||
195 fmt_conversion_table[i].ff_fmt == pix_fmt)) {
196 return fmt_conversion_table[i].v4l2_fmt;
203 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
207 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
208 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
209 fmt_conversion_table[i].codec_id == codec_id) {
210 return fmt_conversion_table[i].ff_fmt;
217 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
221 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
222 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
223 return fmt_conversion_table[i].codec_id;
227 return CODEC_ID_NONE;
230 static int mmap_init(AVFormatContext *ctx)
232 struct video_data *s = ctx->priv_data;
233 struct v4l2_requestbuffers req;
236 memset(&req, 0, sizeof(struct v4l2_requestbuffers));
237 req.count = desired_video_buffers;
238 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
239 req.memory = V4L2_MEMORY_MMAP;
240 res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
242 if (errno == EINVAL) {
243 av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
245 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
248 return AVERROR(errno);
252 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
254 return AVERROR(ENOMEM);
256 s->buffers = req.count;
257 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
258 if (s->buf_start == NULL) {
259 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
261 return AVERROR(ENOMEM);
263 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
264 if (s->buf_len == NULL) {
265 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
266 av_free(s->buf_start);
268 return AVERROR(ENOMEM);
271 for (i = 0; i < req.count; i++) {
272 struct v4l2_buffer buf;
274 memset(&buf, 0, sizeof(struct v4l2_buffer));
275 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
276 buf.memory = V4L2_MEMORY_MMAP;
278 res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
280 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
282 return AVERROR(errno);
285 s->buf_len[i] = buf.length;
286 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
287 av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
291 s->buf_start[i] = mmap (NULL, buf.length,
292 PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
293 if (s->buf_start[i] == MAP_FAILED) {
294 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
296 return AVERROR(errno);
303 static int read_init(AVFormatContext *ctx)
308 static void mmap_release_buffer(AVPacket *pkt)
310 struct v4l2_buffer buf;
312 struct buff_data *buf_descriptor = pkt->priv;
314 if (pkt->data == NULL) {
318 memset(&buf, 0, sizeof(struct v4l2_buffer));
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;
337 struct buff_data *buf_descriptor;
340 memset(&buf, 0, sizeof(struct v4l2_buffer));
341 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
342 buf.memory = V4L2_MEMORY_MMAP;
344 /* FIXME: Some special treatment might be needed in case of loss of signal... */
345 while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
347 if (errno == EAGAIN) {
350 return AVERROR(EAGAIN);
352 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
354 return AVERROR(errno);
356 assert (buf.index < s->buffers);
357 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
358 av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
360 return AVERROR_INVALIDDATA;
363 /* Image is at s->buff_start[buf.index] */
364 pkt->data= s->buf_start[buf.index];
365 pkt->size = buf.bytesused;
366 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
367 pkt->destruct = mmap_release_buffer;
368 buf_descriptor = av_malloc(sizeof(struct buff_data));
369 if (buf_descriptor == NULL) {
370 /* Something went wrong... Since av_malloc() failed, we cannot even
371 * allocate a buffer for memcopying into it
373 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
374 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
376 return AVERROR(ENOMEM);
378 buf_descriptor->fd = s->fd;
379 buf_descriptor->index = buf.index;
380 pkt->priv = buf_descriptor;
382 return s->buf_len[buf.index];
385 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
390 static int mmap_start(AVFormatContext *ctx)
392 struct video_data *s = ctx->priv_data;
393 enum v4l2_buf_type type;
396 for (i = 0; i < s->buffers; i++) {
397 struct v4l2_buffer buf;
399 memset(&buf, 0, sizeof(struct v4l2_buffer));
400 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
401 buf.memory = V4L2_MEMORY_MMAP;
404 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
406 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
408 return AVERROR(errno);
412 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
413 res = ioctl(s->fd, VIDIOC_STREAMON, &type);
415 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
417 return AVERROR(errno);
423 static void mmap_close(struct video_data *s)
425 enum v4l2_buf_type type;
428 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
429 /* We do not check for the result, because we could
430 * not do anything about it anyway...
432 ioctl(s->fd, VIDIOC_STREAMOFF, &type);
433 for (i = 0; i < s->buffers; i++) {
434 munmap(s->buf_start[i], s->buf_len[i]);
436 av_free(s->buf_start);
440 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
442 struct video_data *s = s1->priv_data;
443 struct v4l2_input input;
444 struct v4l2_standard standard;
445 struct v4l2_streamparm streamparm = { 0 };
446 struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
449 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
451 if (ap->channel>=0) {
452 /* set tv video input */
453 memset (&input, 0, sizeof (input));
454 input.index = ap->channel;
455 if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
456 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
460 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
461 ap->channel, input.name);
462 if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
463 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
470 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
472 /* set tv standard */
473 memset (&standard, 0, sizeof (standard));
476 if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
477 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
482 if (!strcasecmp(standard.name, ap->standard)) {
487 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
488 ap->standard, (uint64_t)standard.id);
489 if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
490 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
496 if (ap->time_base.num && ap->time_base.den) {
497 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
498 ap->time_base.num, ap->time_base.den);
499 tpf->numerator = ap->time_base.num;
500 tpf->denominator = ap->time_base.den;
501 if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
502 av_log(s1, AV_LOG_ERROR,
503 "ioctl set time per frame(%d/%d) failed\n",
504 ap->time_base.num, ap->time_base.den);
508 if (ap->time_base.den != tpf->denominator ||
509 ap->time_base.num != tpf->numerator) {
510 av_log(s1, AV_LOG_INFO,
511 "The driver changed the time per frame from %d/%d to %d/%d\n",
512 ap->time_base.num, ap->time_base.den,
513 tpf->numerator, tpf->denominator);
516 /* if timebase value is not set in ap, read the timebase value from the driver */
517 if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
518 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
519 return AVERROR(errno);
522 ap->time_base.num = tpf->numerator;
523 ap->time_base.den = tpf->denominator;
528 static uint32_t device_try_init(AVFormatContext *s1,
529 const AVFormatParameters *ap,
532 enum CodecID *codec_id)
534 uint32_t desired_format = fmt_ff2v4l(ap->pix_fmt, s1->video_codec_id);
536 if (desired_format == 0 ||
537 device_init(s1, width, height, desired_format) < 0) {
541 for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
542 if (s1->video_codec_id == CODEC_ID_NONE ||
543 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
544 desired_format = fmt_conversion_table[i].v4l2_fmt;
545 if (device_init(s1, width, height, desired_format) >= 0) {
552 if (desired_format != 0) {
553 *codec_id = fmt_v4l2codec(desired_format);
554 assert(*codec_id != CODEC_ID_NONE);
557 return desired_format;
560 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
562 struct video_data *s = s1->priv_data;
565 uint32_t desired_format, capabilities;
566 enum CodecID codec_id;
568 st = av_new_stream(s1, 0);
570 return AVERROR(ENOMEM);
572 av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
574 s->width = ap->width;
575 s->height = ap->height;
578 s->fd = device_open(s1, &capabilities);
582 av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
584 if (!s->width && !s->height) {
585 struct v4l2_format fmt;
587 av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
588 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
589 if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
590 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
591 return AVERROR(errno);
593 s->width = fmt.fmt.pix.width;
594 s->height = fmt.fmt.pix.height;
595 av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
598 desired_format = device_try_init(s1, ap, &s->width, &s->height, &codec_id);
599 if (desired_format == 0) {
600 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
601 "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, ap->pix_fmt);
606 if (av_image_check_size(s->width, s->height, 0, s1) < 0)
607 return AVERROR(EINVAL);
608 s->frame_format = desired_format;
610 if (v4l2_set_parameters(s1, ap) < 0)
613 st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
614 s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
615 if (capabilities & V4L2_CAP_STREAMING) {
616 s->io_method = io_mmap;
619 res = mmap_start(s1);
622 s->io_method = io_read;
630 s->top_field_first = first_field(s->fd);
632 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
633 st->codec->codec_id = codec_id;
634 st->codec->width = s->width;
635 st->codec->height = s->height;
636 st->codec->time_base.den = ap->time_base.den;
637 st->codec->time_base.num = ap->time_base.num;
638 st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
643 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
645 struct video_data *s = s1->priv_data;
648 if (s->io_method == io_mmap) {
650 res = mmap_read_frame(s1, pkt);
651 } else if (s->io_method == io_read) {
652 if (av_new_packet(pkt, s->frame_size) < 0)
655 res = read_frame(s1, pkt);
663 if (s1->streams[0]->codec->coded_frame) {
664 s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
665 s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
671 static int v4l2_read_close(AVFormatContext *s1)
673 struct video_data *s = s1->priv_data;
675 if (s->io_method == io_mmap) {
683 AVInputFormat ff_v4l2_demuxer = {
685 NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
686 sizeof(struct video_data),
691 .flags = AVFMT_NOFILE,