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 AV_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"
33 #include "libavformat/internal.h"
36 #include <sys/ioctl.h>
40 #if HAVE_SYS_VIDEOIO_H
41 #include <sys/videoio.h>
43 #include <linux/videodev2.h>
45 #include "libavutil/atomic.h"
46 #include "libavutil/avassert.h"
47 #include "libavutil/imgutils.h"
48 #include "libavutil/internal.h"
49 #include "libavutil/log.h"
50 #include "libavutil/opt.h"
51 #include "libavutil/parseutils.h"
52 #include "libavutil/pixdesc.h"
53 #include "libavutil/avstring.h"
54 #include "libavutil/mathematics.h"
56 static const int desired_video_buffers = 256;
58 #define V4L_ALLFORMATS 3
59 #define V4L_RAWFORMATS 1
60 #define V4L_COMPFORMATS 2
65 int frame_format; /* V4L2_PIX_FMT_* */
73 volatile int buffers_queued;
75 unsigned int *buf_len;
78 char *video_size; /**< String describing video size,
79 set by a private option. */
80 char *pixel_format; /**< Set by a private option. */
81 int list_format; /**< Set by a private option. */
82 char *framerate; /**< Set by a private option. */
92 enum AVPixelFormat ff_fmt;
93 enum AVCodecID codec_id;
97 static struct fmt_map fmt_conversion_table[] = {
98 //ff_fmt codec_id v4l2_fmt
99 { AV_PIX_FMT_YUV420P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
100 { AV_PIX_FMT_YUV422P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
101 { AV_PIX_FMT_YUYV422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
102 { AV_PIX_FMT_UYVY422, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
103 { AV_PIX_FMT_YUV411P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
104 { AV_PIX_FMT_YUV410P, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
105 { AV_PIX_FMT_RGB555, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
106 { AV_PIX_FMT_RGB565, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
107 { AV_PIX_FMT_BGR24, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
108 { AV_PIX_FMT_RGB24, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
109 { AV_PIX_FMT_BGRA, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
110 { AV_PIX_FMT_GRAY8, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
111 { AV_PIX_FMT_NV12, AV_CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
112 { AV_PIX_FMT_NONE, AV_CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
113 { AV_PIX_FMT_NONE, AV_CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
116 static int device_open(AVFormatContext *ctx)
118 struct v4l2_capability cap;
123 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
127 fd = avpriv_open(ctx->filename, flags);
131 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
132 ctx->filename, strerror(err));
137 res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
140 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
146 av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",
147 fd, cap.capabilities);
149 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
150 av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
156 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
157 av_log(ctx, AV_LOG_ERROR,
158 "The device does not support the streaming I/O method.\n");
171 static int device_init(AVFormatContext *ctx, int *width, int *height,
174 struct video_data *s = ctx->priv_data;
176 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
177 struct v4l2_pix_format *pix = &fmt.fmt.pix;
182 pix->height = *height;
183 pix->pixelformat = pix_fmt;
184 pix->field = V4L2_FIELD_ANY;
186 res = ioctl(fd, VIDIOC_S_FMT, &fmt);
188 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
189 av_log(ctx, AV_LOG_INFO,
190 "The V4L2 driver changed the video from %dx%d to %dx%d\n",
191 *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
192 *width = fmt.fmt.pix.width;
193 *height = fmt.fmt.pix.height;
196 if (pix_fmt != fmt.fmt.pix.pixelformat) {
197 av_log(ctx, AV_LOG_DEBUG,
198 "The V4L2 driver changed the pixel format "
199 "from 0x%08X to 0x%08X\n",
200 pix_fmt, fmt.fmt.pix.pixelformat);
204 if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
205 av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
212 static int first_field(int fd)
217 res = ioctl(fd, VIDIOC_G_STD, &std);
221 if (std & V4L2_STD_NTSC) {
228 static uint32_t fmt_ff2v4l(enum AVPixelFormat pix_fmt, enum AVCodecID codec_id)
232 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
233 if ((codec_id == AV_CODEC_ID_NONE ||
234 fmt_conversion_table[i].codec_id == codec_id) &&
235 (pix_fmt == AV_PIX_FMT_NONE ||
236 fmt_conversion_table[i].ff_fmt == pix_fmt)) {
237 return fmt_conversion_table[i].v4l2_fmt;
244 static enum AVPixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum AVCodecID codec_id)
248 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
249 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
250 fmt_conversion_table[i].codec_id == codec_id) {
251 return fmt_conversion_table[i].ff_fmt;
255 return AV_PIX_FMT_NONE;
258 static enum AVCodecID fmt_v4l2codec(uint32_t v4l2_fmt)
262 for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
263 if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
264 return fmt_conversion_table[i].codec_id;
268 return AV_CODEC_ID_NONE;
271 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
272 static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
274 struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
276 while(!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
278 case V4L2_FRMSIZE_TYPE_DISCRETE:
279 av_log(ctx, AV_LOG_INFO, " %ux%u",
280 vfse.discrete.width, vfse.discrete.height);
282 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
283 case V4L2_FRMSIZE_TYPE_STEPWISE:
284 av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
285 vfse.stepwise.min_width,
286 vfse.stepwise.max_width,
287 vfse.stepwise.step_width,
288 vfse.stepwise.min_height,
289 vfse.stepwise.max_height,
290 vfse.stepwise.step_height);
297 static void list_formats(AVFormatContext *ctx, int fd, int type)
299 struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
301 while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
302 enum AVCodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
303 enum AVPixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
307 if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
308 type & V4L_RAWFORMATS) {
309 const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
310 av_log(ctx, AV_LOG_INFO, "R : %9s : %20s :",
311 fmt_name ? fmt_name : "Unsupported",
313 } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
314 type & V4L_COMPFORMATS) {
315 AVCodec *codec = avcodec_find_encoder(codec_id);
316 av_log(ctx, AV_LOG_INFO, "C : %9s : %20s :",
317 codec ? codec->name : "Unsupported",
323 #ifdef V4L2_FMT_FLAG_EMULATED
324 if (vfd.flags & V4L2_FMT_FLAG_EMULATED) {
325 av_log(ctx, AV_LOG_WARNING, "%s", "Emulated");
329 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
330 list_framesizes(ctx, fd, vfd.pixelformat);
332 av_log(ctx, AV_LOG_INFO, "\n");
336 static int mmap_init(AVFormatContext *ctx)
339 struct video_data *s = ctx->priv_data;
340 struct v4l2_requestbuffers req = {
341 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
342 .count = desired_video_buffers,
343 .memory = V4L2_MEMORY_MMAP
346 res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
348 if (errno == EINVAL) {
349 av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
351 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
354 return AVERROR(errno);
358 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
360 return AVERROR(ENOMEM);
362 s->buffers = req.count;
363 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
364 if (s->buf_start == NULL) {
365 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
367 return AVERROR(ENOMEM);
369 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
370 if (s->buf_len == NULL) {
371 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
372 av_free(s->buf_start);
374 return AVERROR(ENOMEM);
377 for (i = 0; i < req.count; i++) {
378 struct v4l2_buffer buf = {
379 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
381 .memory = V4L2_MEMORY_MMAP
384 res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
386 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
388 return AVERROR(errno);
391 s->buf_len[i] = buf.length;
392 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
393 av_log(ctx, AV_LOG_ERROR,
394 "Buffer len [%d] = %d != %d\n",
395 i, s->buf_len[i], s->frame_size);
399 s->buf_start[i] = mmap(NULL, buf.length,
400 PROT_READ | PROT_WRITE, MAP_SHARED,
401 s->fd, buf.m.offset);
403 if (s->buf_start[i] == MAP_FAILED) {
404 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
406 return AVERROR(errno);
413 #if FF_API_DESTRUCT_PACKET
414 static void dummy_release_buffer(AVPacket *pkt)
420 static void mmap_release_buffer(void *opaque, uint8_t *data)
422 struct v4l2_buffer buf = { 0 };
424 struct buff_data *buf_descriptor = opaque;
425 struct video_data *s = buf_descriptor->s;
427 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
428 buf.memory = V4L2_MEMORY_MMAP;
429 buf.index = buf_descriptor->index;
430 fd = buf_descriptor->fd;
431 av_free(buf_descriptor);
433 res = ioctl(fd, VIDIOC_QBUF, &buf);
435 av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
437 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
440 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
442 struct video_data *s = ctx->priv_data;
443 struct v4l2_buffer buf = {
444 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
445 .memory = V4L2_MEMORY_MMAP
447 struct pollfd p = { .fd = s->fd, .events = POLLIN };
450 res = poll(&p, 1, s->timeout);
452 return AVERROR(errno);
454 if (!(p.revents & (POLLIN | POLLERR | POLLHUP)))
455 return AVERROR(EAGAIN);
457 /* FIXME: Some special treatment might be needed in case of loss of signal... */
458 while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
460 if (errno == EAGAIN) {
463 return AVERROR(EAGAIN);
465 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
468 return AVERROR(errno);
471 if (buf.index >= s->buffers) {
472 av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
473 return AVERROR(EINVAL);
475 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
476 // always keep at least one buffer queued
477 av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
479 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
480 av_log(ctx, AV_LOG_ERROR,
481 "The v4l2 frame is %d bytes, but %d bytes are expected\n",
482 buf.bytesused, s->frame_size);
484 return AVERROR_INVALIDDATA;
487 /* Image is at s->buff_start[buf.index] */
488 if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
489 /* when we start getting low on queued buffers, fall back on copying data */
490 res = av_new_packet(pkt, buf.bytesused);
492 av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
495 memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
497 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
499 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF)\n");
501 return AVERROR(errno);
503 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
505 struct buff_data *buf_descriptor;
507 pkt->data = s->buf_start[buf.index];
508 pkt->size = buf.bytesused;
509 #if FF_API_DESTRUCT_PACKET
510 FF_DISABLE_DEPRECATION_WARNINGS
511 pkt->destruct = dummy_release_buffer;
512 FF_ENABLE_DEPRECATION_WARNINGS
515 buf_descriptor = av_malloc(sizeof(struct buff_data));
516 if (buf_descriptor == NULL) {
517 /* Something went wrong... Since av_malloc() failed, we cannot even
518 * allocate a buffer for memcpying into it
520 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
521 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
523 return AVERROR(ENOMEM);
525 buf_descriptor->fd = s->fd;
526 buf_descriptor->index = buf.index;
527 buf_descriptor->s = s;
529 pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
532 av_freep(&buf_descriptor);
533 return AVERROR(ENOMEM);
536 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
538 return s->buf_len[buf.index];
541 static int mmap_start(AVFormatContext *ctx)
543 struct video_data *s = ctx->priv_data;
544 enum v4l2_buf_type type;
547 for (i = 0; i < s->buffers; i++) {
548 struct v4l2_buffer buf = {
549 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
551 .memory = V4L2_MEMORY_MMAP
554 res = ioctl(s->fd, VIDIOC_QBUF, &buf);
556 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
559 return AVERROR(errno);
562 s->buffers_queued = s->buffers;
564 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
565 res = ioctl(s->fd, VIDIOC_STREAMON, &type);
567 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
570 return AVERROR(errno);
576 static void mmap_close(struct video_data *s)
578 enum v4l2_buf_type type;
581 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
582 /* We do not check for the result, because we could
583 * not do anything about it anyway...
585 ioctl(s->fd, VIDIOC_STREAMOFF, &type);
586 for (i = 0; i < s->buffers; i++) {
587 munmap(s->buf_start[i], s->buf_len[i]);
589 av_free(s->buf_start);
593 static int v4l2_set_parameters(AVFormatContext *s1)
595 struct video_data *s = s1->priv_data;
596 struct v4l2_input input = { 0 };
597 struct v4l2_standard standard = { 0 };
598 struct v4l2_streamparm streamparm = { 0 };
599 struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
600 AVRational framerate_q = { 0 };
603 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
606 (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
607 av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
612 /* set tv video input */
613 input.index = s->channel;
614 if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
615 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
619 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
620 s->channel, input.name);
621 if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
622 av_log(s1, AV_LOG_ERROR,
623 "The V4L2 driver ioctl set input(%d) failed\n",
629 av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
631 /* set tv standard */
634 if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
635 av_log(s1, AV_LOG_ERROR,
636 "The V4L2 driver ioctl set standard(%s) failed\n",
641 if (!av_strcasecmp(standard.name, s->standard)) {
646 av_log(s1, AV_LOG_DEBUG,
647 "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
648 s->standard, (uint64_t)standard.id);
649 if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
650 av_log(s1, AV_LOG_ERROR,
651 "The V4L2 driver ioctl set standard(%s) failed\n",
657 if (framerate_q.num && framerate_q.den) {
658 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
659 framerate_q.den, framerate_q.num);
660 tpf->numerator = framerate_q.den;
661 tpf->denominator = framerate_q.num;
663 if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
664 av_log(s1, AV_LOG_ERROR,
665 "ioctl set time per frame(%d/%d) failed\n",
666 framerate_q.den, framerate_q.num);
670 if (framerate_q.num != tpf->denominator ||
671 framerate_q.den != tpf->numerator) {
672 av_log(s1, AV_LOG_INFO,
673 "The driver changed the time per frame from "
675 framerate_q.den, framerate_q.num,
676 tpf->numerator, tpf->denominator);
679 if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
680 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
682 return AVERROR(errno);
685 s1->streams[0]->avg_frame_rate.num = tpf->denominator;
686 s1->streams[0]->avg_frame_rate.den = tpf->numerator;
689 av_rescale_q(1, s1->streams[0]->avg_frame_rate,
690 (AVRational){1, 1000});
695 static uint32_t device_try_init(AVFormatContext *s1,
696 enum AVPixelFormat pix_fmt,
699 enum AVCodecID *codec_id)
701 uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
703 if (desired_format == 0 ||
704 device_init(s1, width, height, desired_format) < 0) {
708 for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
709 if (s1->video_codec_id == AV_CODEC_ID_NONE ||
710 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
711 desired_format = fmt_conversion_table[i].v4l2_fmt;
712 if (device_init(s1, width, height, desired_format) >= 0) {
720 if (desired_format != 0) {
721 *codec_id = fmt_v4l2codec(desired_format);
722 assert(*codec_id != AV_CODEC_ID_NONE);
725 return desired_format;
728 static int v4l2_read_header(AVFormatContext *s1)
730 struct video_data *s = s1->priv_data;
733 uint32_t desired_format;
734 enum AVCodecID codec_id;
735 enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
737 st = avformat_new_stream(s1, NULL);
739 return AVERROR(ENOMEM);
741 s->fd = device_open(s1);
745 if (s->list_format) {
746 list_formats(s1, s->fd, s->list_format);
750 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
753 (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
754 av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
759 if (s->pixel_format) {
760 AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
763 s1->video_codec_id = codec->id;
765 pix_fmt = av_get_pix_fmt(s->pixel_format);
767 if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
768 av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
771 return AVERROR(EINVAL);
775 if (!s->width && !s->height) {
776 struct v4l2_format fmt;
778 av_log(s1, AV_LOG_VERBOSE,
779 "Querying the device for the current frame size\n");
780 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
781 if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
782 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
784 return AVERROR(errno);
787 s->width = fmt.fmt.pix.width;
788 s->height = fmt.fmt.pix.height;
789 av_log(s1, AV_LOG_VERBOSE,
790 "Setting frame size to %dx%d\n", s->width, s->height);
793 desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
795 if (desired_format == 0) {
796 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
797 "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
803 if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
806 s->frame_format = desired_format;
808 if ((res = v4l2_set_parameters(s1) < 0))
811 st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
813 avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
815 if ((res = mmap_init(s1)) ||
816 (res = mmap_start(s1)) < 0) {
821 s->top_field_first = first_field(s->fd);
823 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
824 st->codec->codec_id = codec_id;
825 if (codec_id == AV_CODEC_ID_RAWVIDEO)
826 st->codec->codec_tag =
827 avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
828 st->codec->width = s->width;
829 st->codec->height = s->height;
830 st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
835 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
837 struct video_data *s = s1->priv_data;
838 AVFrame *frame = s1->streams[0]->codec->coded_frame;
842 if ((res = mmap_read_frame(s1, pkt)) < 0) {
846 if (frame && s->interlaced) {
847 frame->interlaced_frame = 1;
848 frame->top_field_first = s->top_field_first;
854 static int v4l2_read_close(AVFormatContext *s1)
856 struct video_data *s = s1->priv_data;
858 if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
859 av_log(s1, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
868 #define OFFSET(x) offsetof(struct video_data, x)
869 #define DEC AV_OPT_FLAG_DECODING_PARAM
870 static const AVOption options[] = {
871 { "standard", "TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
872 { "channel", "TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC },
873 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
874 { "pixel_format", "Preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
875 { "input_format", "Preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
876 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
877 { "list_formats", "List available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
878 { "all", "Show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
879 { "raw", "Show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
880 { "compressed", "Show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
884 static const AVClass v4l2_class = {
885 .class_name = "V4L2 indev",
886 .item_name = av_default_item_name,
888 .version = LIBAVUTIL_VERSION_INT,
891 AVInputFormat ff_v4l2_demuxer = {
892 .name = "video4linux2",
893 .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
894 .priv_data_size = sizeof(struct video_data),
895 .read_header = v4l2_read_header,
896 .read_packet = v4l2_read_packet,
897 .read_close = v4l2_read_close,
898 .flags = AVFMT_NOFILE,
899 .priv_class = &v4l2_class,