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 Libav.
15 * Libav 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 * Libav 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 Libav; 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 "libavutil/imgutils.h"
47 #include "libavutil/log.h"
48 #include "libavutil/opt.h"
50 static const int desired_video_buffers = 256;
61 int frame_format; /* V4L2_PIX_FMT_* */
62 enum io_method io_method;
69 unsigned int *buf_len;
79 enum PixelFormat ff_fmt;
80 enum CodecID codec_id;
84 static struct fmt_map fmt_conversion_table[] = {
85 //ff_fmt codec_id v4l2_fmt
86 { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
87 { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
88 { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
89 { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
90 { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
91 { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
92 { PIX_FMT_RGB555, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
93 { PIX_FMT_RGB565, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
94 { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
95 { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
96 { PIX_FMT_BGRA, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
97 { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
98 { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
99 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
100 { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
103 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
105 struct v4l2_capability cap;
110 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
113 fd = open(ctx->filename, flags, 0);
115 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
116 ctx->filename, strerror(errno));
118 return AVERROR(errno);
121 res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
122 // ENOIOCTLCMD definition only availble on __KERNEL__
123 if (res < 0 && ((err = errno) == 515)) {
124 av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
130 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
136 if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
137 av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
140 return AVERROR(ENODEV);
142 *capabilities = cap.capabilities;
147 static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
149 struct video_data *s = ctx->priv_data;
151 struct v4l2_format fmt;
154 memset(&fmt, 0, sizeof(struct v4l2_format));
155 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
156 fmt.fmt.pix.width = *width;
157 fmt.fmt.pix.height = *height;
158 fmt.fmt.pix.pixelformat = pix_fmt;
159 fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
160 res = ioctl(fd, VIDIOC_S_FMT, &fmt);
161 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
162 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);
163 *width = fmt.fmt.pix.width;
164 *height = fmt.fmt.pix.height;
167 if (pix_fmt != fmt.fmt.pix.pixelformat) {
168 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);
175 static int first_field(int fd)
180 res = ioctl(fd, VIDIOC_G_STD, &std);
184 if (std & V4L2_STD_NTSC) {
191 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
195 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
196 if ((codec_id == CODEC_ID_NONE ||
197 fmt_conversion_table[i].codec_id == codec_id) &&
198 (pix_fmt == PIX_FMT_NONE ||
199 fmt_conversion_table[i].ff_fmt == pix_fmt)) {
200 return fmt_conversion_table[i].v4l2_fmt;
207 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
211 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
212 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
213 fmt_conversion_table[i].codec_id == codec_id) {
214 return fmt_conversion_table[i].ff_fmt;
221 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
225 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
226 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
227 return fmt_conversion_table[i].codec_id;
231 return CODEC_ID_NONE;
234 static int mmap_init(AVFormatContext *ctx)
236 struct video_data *s = ctx->priv_data;
237 struct v4l2_requestbuffers req;
240 memset(&req, 0, sizeof(struct v4l2_requestbuffers));
241 req.count = desired_video_buffers;
242 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
243 req.memory = V4L2_MEMORY_MMAP;
244 res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
246 if (errno == EINVAL) {
247 av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
249 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
252 return AVERROR(errno);
256 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
258 return AVERROR(ENOMEM);
260 s->buffers = req.count;
261 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
262 if (s->buf_start == NULL) {
263 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
265 return AVERROR(ENOMEM);
267 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
268 if (s->buf_len == NULL) {
269 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
270 av_free(s->buf_start);
272 return AVERROR(ENOMEM);
275 for (i = 0; i < req.count; i++) {
276 struct v4l2_buffer buf;
278 memset(&buf, 0, sizeof(struct v4l2_buffer));
279 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
280 buf.memory = V4L2_MEMORY_MMAP;
282 res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
284 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
286 return AVERROR(errno);
289 s->buf_len[i] = buf.length;
290 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
291 av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
295 s->buf_start[i] = mmap (NULL, buf.length,
296 PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
297 if (s->buf_start[i] == MAP_FAILED) {
298 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
300 return AVERROR(errno);
307 static int read_init(AVFormatContext *ctx)
312 static void mmap_release_buffer(AVPacket *pkt)
314 struct v4l2_buffer buf;
316 struct buff_data *buf_descriptor = pkt->priv;
318 if (pkt->data == NULL) {
322 memset(&buf, 0, sizeof(struct v4l2_buffer));
323 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
324 buf.memory = V4L2_MEMORY_MMAP;
325 buf.index = buf_descriptor->index;
326 fd = buf_descriptor->fd;
327 av_free(buf_descriptor);
329 res = ioctl(fd, VIDIOC_QBUF, &buf);
331 av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
337 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
339 struct video_data *s = ctx->priv_data;
340 struct v4l2_buffer buf;
341 struct buff_data *buf_descriptor;
344 memset(&buf, 0, sizeof(struct v4l2_buffer));
345 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
346 buf.memory = V4L2_MEMORY_MMAP;
348 /* FIXME: Some special treatment might be needed in case of loss of signal... */
349 while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
351 if (errno == EAGAIN) {
354 return AVERROR(EAGAIN);
356 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
358 return AVERROR(errno);
360 assert (buf.index < s->buffers);
361 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
362 av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
364 return AVERROR_INVALIDDATA;
367 /* Image is at s->buff_start[buf.index] */
368 pkt->data= s->buf_start[buf.index];
369 pkt->size = buf.bytesused;
370 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
371 pkt->destruct = mmap_release_buffer;
372 buf_descriptor = av_malloc(sizeof(struct buff_data));
373 if (buf_descriptor == NULL) {
374 /* Something went wrong... Since av_malloc() failed, we cannot even
375 * allocate a buffer for memcopying into it
377 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
378 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
380 return AVERROR(ENOMEM);
382 buf_descriptor->fd = s->fd;
383 buf_descriptor->index = buf.index;
384 pkt->priv = buf_descriptor;
386 return s->buf_len[buf.index];
389 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
394 static int mmap_start(AVFormatContext *ctx)
396 struct video_data *s = ctx->priv_data;
397 enum v4l2_buf_type type;
400 for (i = 0; i < s->buffers; i++) {
401 struct v4l2_buffer buf;
403 memset(&buf, 0, sizeof(struct v4l2_buffer));
404 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
405 buf.memory = V4L2_MEMORY_MMAP;
408 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
410 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
412 return AVERROR(errno);
416 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
417 res = ioctl(s->fd, VIDIOC_STREAMON, &type);
419 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
421 return AVERROR(errno);
427 static void mmap_close(struct video_data *s)
429 enum v4l2_buf_type type;
432 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
433 /* We do not check for the result, because we could
434 * not do anything about it anyway...
436 ioctl(s->fd, VIDIOC_STREAMOFF, &type);
437 for (i = 0; i < s->buffers; i++) {
438 munmap(s->buf_start[i], s->buf_len[i]);
440 av_free(s->buf_start);
444 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
446 struct video_data *s = s1->priv_data;
447 struct v4l2_input input;
448 struct v4l2_standard standard;
449 struct v4l2_streamparm streamparm = { 0 };
450 struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
453 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
455 if (ap->channel>=0) {
456 /* set tv video input */
457 memset (&input, 0, sizeof (input));
458 input.index = ap->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 ap->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",
474 av_freep(&s->standard);
475 s->standard = av_strdup(ap->standard);
479 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
481 /* set tv standard */
482 memset (&standard, 0, sizeof (standard));
485 if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
486 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
491 if (!strcasecmp(standard.name, s->standard)) {
496 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
497 s->standard, (uint64_t)standard.id);
498 if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
499 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
504 av_freep(&s->standard);
506 if (ap->time_base.num && ap->time_base.den) {
507 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
508 ap->time_base.num, ap->time_base.den);
509 tpf->numerator = ap->time_base.num;
510 tpf->denominator = ap->time_base.den;
511 if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
512 av_log(s1, AV_LOG_ERROR,
513 "ioctl set time per frame(%d/%d) failed\n",
514 ap->time_base.num, ap->time_base.den);
518 if (ap->time_base.den != tpf->denominator ||
519 ap->time_base.num != tpf->numerator) {
520 av_log(s1, AV_LOG_INFO,
521 "The driver changed the time per frame from %d/%d to %d/%d\n",
522 ap->time_base.num, ap->time_base.den,
523 tpf->numerator, tpf->denominator);
526 /* if timebase value is not set in ap, read the timebase value from the driver */
527 if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
528 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
529 return AVERROR(errno);
532 ap->time_base.num = tpf->numerator;
533 ap->time_base.den = tpf->denominator;
538 static uint32_t device_try_init(AVFormatContext *s1,
539 const AVFormatParameters *ap,
542 enum CodecID *codec_id)
544 uint32_t desired_format = fmt_ff2v4l(ap->pix_fmt, s1->video_codec_id);
546 if (desired_format == 0 ||
547 device_init(s1, width, height, desired_format) < 0) {
551 for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
552 if (s1->video_codec_id == CODEC_ID_NONE ||
553 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
554 desired_format = fmt_conversion_table[i].v4l2_fmt;
555 if (device_init(s1, width, height, desired_format) >= 0) {
562 if (desired_format != 0) {
563 *codec_id = fmt_v4l2codec(desired_format);
564 assert(*codec_id != CODEC_ID_NONE);
567 return desired_format;
570 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
572 struct video_data *s = s1->priv_data;
575 uint32_t desired_format, capabilities;
576 enum CodecID codec_id;
578 st = av_new_stream(s1, 0);
580 return AVERROR(ENOMEM);
582 av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
584 s->width = ap->width;
585 s->height = ap->height;
588 s->fd = device_open(s1, &capabilities);
592 av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
594 if (!s->width && !s->height) {
595 struct v4l2_format fmt;
597 av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
598 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
599 if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
600 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
601 return AVERROR(errno);
603 s->width = fmt.fmt.pix.width;
604 s->height = fmt.fmt.pix.height;
605 av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
608 desired_format = device_try_init(s1, ap, &s->width, &s->height, &codec_id);
609 if (desired_format == 0) {
610 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
611 "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, ap->pix_fmt);
616 if (av_image_check_size(s->width, s->height, 0, s1) < 0)
617 return AVERROR(EINVAL);
618 s->frame_format = desired_format;
620 if (v4l2_set_parameters(s1, ap) < 0)
623 st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
624 s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
625 if (capabilities & V4L2_CAP_STREAMING) {
626 s->io_method = io_mmap;
629 res = mmap_start(s1);
632 s->io_method = io_read;
640 s->top_field_first = first_field(s->fd);
642 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
643 st->codec->codec_id = codec_id;
644 st->codec->width = s->width;
645 st->codec->height = s->height;
646 st->codec->time_base.den = ap->time_base.den;
647 st->codec->time_base.num = ap->time_base.num;
648 st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
653 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
655 struct video_data *s = s1->priv_data;
658 if (s->io_method == io_mmap) {
660 res = mmap_read_frame(s1, pkt);
661 } else if (s->io_method == io_read) {
662 if (av_new_packet(pkt, s->frame_size) < 0)
665 res = read_frame(s1, pkt);
673 if (s1->streams[0]->codec->coded_frame) {
674 s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
675 s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
681 static int v4l2_read_close(AVFormatContext *s1)
683 struct video_data *s = s1->priv_data;
685 if (s->io_method == io_mmap) {
693 static const AVOption options[] = {
694 { "standard", "", offsetof(struct video_data, standard), FF_OPT_TYPE_STRING, {.str = "NTSC" }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
698 static const AVClass v4l2_class = {
699 .class_name = "V4L2 indev",
700 .item_name = av_default_item_name,
702 .version = LIBAVUTIL_VERSION_INT,
705 AVInputFormat ff_v4l2_demuxer = {
707 NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
708 sizeof(struct video_data),
713 .flags = AVFMT_NOFILE,
714 .priv_class = &v4l2_class,