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://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
29 * Thanks to Michael Niedermayer for providing the mapping between
30 * V4L2_PIX_FMT_* and AV_PIX_FMT_*
33 #include "v4l2-common.h"
38 #define v4l2_open open
39 #define v4l2_close close
41 #define v4l2_ioctl ioctl
42 #define v4l2_read read
43 #define v4l2_mmap mmap
44 #define v4l2_munmap munmap
47 static const int desired_video_buffers = 256;
49 #define V4L_ALLFORMATS 3
50 #define V4L_RAWFORMATS 1
51 #define V4L_COMPFORMATS 2
54 * Return timestamps to the user exactly as returned by the kernel
56 #define V4L_TS_DEFAULT 0
58 * Autodetect the kind of timestamps returned by the kernel and convert to
59 * absolute (wall clock) timestamps.
63 * Assume kernel timestamps are from the monotonic clock and convert to
64 * absolute timestamps.
66 #define V4L_TS_MONO2ABS 2
69 * Once the kind of timestamps returned by the kernel have been detected,
70 * the value of the timefilter (NULL or not) determines whether a conversion
73 #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
78 int frame_format; /* V4L2_PIX_FMT_* */
84 TimeFilter *timefilter;
88 volatile int buffers_queued;
90 unsigned int *buf_len;
94 char *pixel_format; /**< Set by a private option. */
95 int list_format; /**< Set by a private option. */
96 int list_standard; /**< Set by a private option. */
97 char *framerate; /**< Set by a private option. */
101 struct video_data *s;
105 static int device_open(AVFormatContext *ctx)
107 struct v4l2_capability cap;
112 if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
116 fd = v4l2_open(ctx->filename, flags, 0);
118 ret = AVERROR(errno);
119 av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
120 ctx->filename, av_err2str(ret));
124 if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
125 ret = AVERROR(errno);
126 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
131 av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
132 fd, cap.capabilities);
134 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
135 av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
136 ret = AVERROR(ENODEV);
140 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
141 av_log(ctx, AV_LOG_ERROR,
142 "The device does not support the streaming I/O method.\n");
143 ret = AVERROR(ENOSYS);
154 static int device_init(AVFormatContext *ctx, int *width, int *height,
157 struct video_data *s = ctx->priv_data;
159 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
160 struct v4l2_pix_format *pix = &fmt.fmt.pix;
165 pix->height = *height;
166 pix->pixelformat = pix_fmt;
167 pix->field = V4L2_FIELD_ANY;
169 if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
170 res = AVERROR(errno);
172 if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
173 av_log(ctx, AV_LOG_INFO,
174 "The V4L2 driver changed the video from %dx%d to %dx%d\n",
175 *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
176 *width = fmt.fmt.pix.width;
177 *height = fmt.fmt.pix.height;
180 if (pix_fmt != fmt.fmt.pix.pixelformat) {
181 av_log(ctx, AV_LOG_DEBUG,
182 "The V4L2 driver changed the pixel format "
183 "from 0x%08X to 0x%08X\n",
184 pix_fmt, fmt.fmt.pix.pixelformat);
185 res = AVERROR(EINVAL);
188 if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
189 av_log(ctx, AV_LOG_DEBUG,
190 "The V4L2 driver is using the interlaced mode\n");
197 static int first_field(int fd)
202 res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
206 if (std & V4L2_STD_NTSC) {
213 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
214 static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
216 struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
218 while(!v4l2_ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
220 case V4L2_FRMSIZE_TYPE_DISCRETE:
221 av_log(ctx, AV_LOG_INFO, " %ux%u",
222 vfse.discrete.width, vfse.discrete.height);
224 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
225 case V4L2_FRMSIZE_TYPE_STEPWISE:
226 av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
227 vfse.stepwise.min_width,
228 vfse.stepwise.max_width,
229 vfse.stepwise.step_width,
230 vfse.stepwise.min_height,
231 vfse.stepwise.max_height,
232 vfse.stepwise.step_height);
239 static void list_formats(AVFormatContext *ctx, int fd, int type)
241 struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
243 while(!v4l2_ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
244 enum AVCodecID codec_id = avpriv_fmt_v4l2codec(vfd.pixelformat);
245 enum AVPixelFormat pix_fmt = avpriv_fmt_v4l2ff(vfd.pixelformat, codec_id);
249 if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
250 type & V4L_RAWFORMATS) {
251 const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
252 av_log(ctx, AV_LOG_INFO, "Raw : %9s : %20s :",
253 fmt_name ? fmt_name : "Unsupported",
255 } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
256 type & V4L_COMPFORMATS) {
257 AVCodec *codec = avcodec_find_decoder(codec_id);
258 av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
259 codec ? codec->name : "Unsupported",
265 #ifdef V4L2_FMT_FLAG_EMULATED
266 if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
267 av_log(ctx, AV_LOG_INFO, " Emulated :");
269 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
270 list_framesizes(ctx, fd, vfd.pixelformat);
272 av_log(ctx, AV_LOG_INFO, "\n");
276 static void list_standards(AVFormatContext *ctx)
279 struct video_data *s = ctx->priv_data;
280 struct v4l2_standard standard;
285 for (standard.index = 0; ; standard.index++) {
286 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
287 ret = AVERROR(errno);
288 if (ret == AVERROR(EINVAL)) {
291 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
295 av_log(ctx, AV_LOG_INFO, "%2d, %16llx, %s\n",
296 standard.index, standard.id, standard.name);
300 static int mmap_init(AVFormatContext *ctx)
303 struct video_data *s = ctx->priv_data;
304 struct v4l2_requestbuffers req = {
305 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
306 .count = desired_video_buffers,
307 .memory = V4L2_MEMORY_MMAP
310 if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
311 res = AVERROR(errno);
312 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
317 av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
318 return AVERROR(ENOMEM);
320 s->buffers = req.count;
321 s->buf_start = av_malloc(sizeof(void *) * s->buffers);
322 if (s->buf_start == NULL) {
323 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
324 return AVERROR(ENOMEM);
326 s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
327 if (s->buf_len == NULL) {
328 av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
329 av_free(s->buf_start);
330 return AVERROR(ENOMEM);
333 for (i = 0; i < req.count; i++) {
334 struct v4l2_buffer buf = {
335 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
337 .memory = V4L2_MEMORY_MMAP
339 if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
340 res = AVERROR(errno);
341 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
345 s->buf_len[i] = buf.length;
346 if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
347 av_log(ctx, AV_LOG_ERROR,
348 "buf_len[%d] = %d < expected frame size %d\n",
349 i, s->buf_len[i], s->frame_size);
350 return AVERROR(ENOMEM);
352 s->buf_start[i] = v4l2_mmap(NULL, buf.length,
353 PROT_READ | PROT_WRITE, MAP_SHARED,
354 s->fd, buf.m.offset);
356 if (s->buf_start[i] == MAP_FAILED) {
357 res = AVERROR(errno);
358 av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
366 #if FF_API_DESTRUCT_PACKET
367 static void dummy_release_buffer(AVPacket *pkt)
373 static void mmap_release_buffer(void *opaque, uint8_t *data)
375 struct v4l2_buffer buf = { 0 };
377 struct buff_data *buf_descriptor = opaque;
378 struct video_data *s = buf_descriptor->s;
380 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
381 buf.memory = V4L2_MEMORY_MMAP;
382 buf.index = buf_descriptor->index;
383 av_free(buf_descriptor);
385 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
386 res = AVERROR(errno);
387 av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
391 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
394 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
395 static int64_t av_gettime_monotonic(void)
399 clock_gettime(CLOCK_MONOTONIC, &tv);
400 return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
404 static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
406 struct video_data *s = ctx->priv_data;
410 if (s->ts_mode == V4L_TS_ABS &&
411 ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
412 av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
413 s->ts_mode = V4L_TS_CONVERT_READY;
416 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
417 now = av_gettime_monotonic();
418 if (s->ts_mode == V4L_TS_MONO2ABS ||
419 (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
420 AVRational tb = {AV_TIME_BASE, 1};
421 int64_t period = av_rescale_q(1, tb, ctx->streams[0]->avg_frame_rate);
422 av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
423 /* microseconds instead of seconds, MHz instead of Hz */
424 s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
425 s->ts_mode = V4L_TS_CONVERT_READY;
429 av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
433 static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
435 struct video_data *s = ctx->priv_data;
438 int r = init_convert_timestamp(ctx, *ts);
442 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
444 int64_t nowa = av_gettime();
445 int64_t nowm = av_gettime_monotonic();
446 ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
447 s->last_time_m = nowm;
448 *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
454 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
456 struct video_data *s = ctx->priv_data;
457 struct v4l2_buffer buf = {
458 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
459 .memory = V4L2_MEMORY_MMAP
463 /* FIXME: Some special treatment might be needed in case of loss of signal... */
464 while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
466 if (errno == EAGAIN) {
468 return AVERROR(EAGAIN);
470 res = AVERROR(errno);
471 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
475 if (buf.index >= s->buffers) {
476 av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
477 return AVERROR(EINVAL);
479 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
480 // always keep at least one buffer queued
481 av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
483 /* CPIA is a compressed format and we don't know the exact number of bytes
484 * used by a frame, so set it here as the driver announces it.
486 if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
487 s->frame_size = buf.bytesused;
489 if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
490 av_log(ctx, AV_LOG_ERROR,
491 "The v4l2 frame is %d bytes, but %d bytes are expected\n",
492 buf.bytesused, s->frame_size);
493 return AVERROR_INVALIDDATA;
496 /* Image is at s->buff_start[buf.index] */
497 if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
498 /* when we start getting low on queued buffers, fall back on copying data */
499 res = av_new_packet(pkt, buf.bytesused);
501 av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
502 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
503 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
506 memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
508 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
509 res = AVERROR(errno);
510 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
514 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
516 struct buff_data *buf_descriptor;
518 pkt->data = s->buf_start[buf.index];
519 pkt->size = buf.bytesused;
520 #if FF_API_DESTRUCT_PACKET
521 pkt->destruct = dummy_release_buffer;
524 buf_descriptor = av_malloc(sizeof(struct buff_data));
525 if (buf_descriptor == NULL) {
526 /* Something went wrong... Since av_malloc() failed, we cannot even
527 * allocate a buffer for memcpying into it
529 av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
530 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
531 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
533 return AVERROR(ENOMEM);
535 buf_descriptor->index = buf.index;
536 buf_descriptor->s = s;
538 pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
541 av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
542 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
543 avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
544 av_freep(&buf_descriptor);
545 return AVERROR(ENOMEM);
548 pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
549 convert_timestamp(ctx, &pkt->pts);
551 return s->buf_len[buf.index];
554 static int mmap_start(AVFormatContext *ctx)
556 struct video_data *s = ctx->priv_data;
557 enum v4l2_buf_type type;
560 for (i = 0; i < s->buffers; i++) {
561 struct v4l2_buffer buf = {
562 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
564 .memory = V4L2_MEMORY_MMAP
567 if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
568 res = AVERROR(errno);
569 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
573 s->buffers_queued = s->buffers;
575 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
576 if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
577 res = AVERROR(errno);
578 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
585 static void mmap_close(struct video_data *s)
587 enum v4l2_buf_type type;
590 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
591 /* We do not check for the result, because we could
592 * not do anything about it anyway...
594 v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
595 for (i = 0; i < s->buffers; i++) {
596 v4l2_munmap(s->buf_start[i], s->buf_len[i]);
598 av_free(s->buf_start);
602 static int v4l2_set_parameters(AVFormatContext *s1)
604 struct video_data *s = s1->priv_data;
605 struct v4l2_standard standard = { 0 };
606 struct v4l2_streamparm streamparm = { 0 };
607 struct v4l2_fract *tpf;
608 AVRational framerate_q = { 0 };
612 (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
613 av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
621 av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
622 /* set tv standard */
625 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
626 ret = AVERROR(errno);
629 if (!av_strcasecmp(standard.name, s->standard))
633 av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
637 if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
638 ret = AVERROR(errno);
639 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
643 av_log(s1, AV_LOG_WARNING,
644 "This device does not support any standard\n");
649 if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
650 tpf = &standard.frameperiod;
653 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
654 ret = AVERROR(errno);
655 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
658 if (standard.id == s->std_id) {
659 av_log(s1, AV_LOG_DEBUG,
660 "Current standard: %s, id: %"PRIu64", frameperiod: %d/%d\n",
661 standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
666 tpf = &streamparm.parm.capture.timeperframe;
669 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
670 if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
671 ret = AVERROR(errno);
672 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
676 if (framerate_q.num && framerate_q.den) {
677 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
678 tpf = &streamparm.parm.capture.timeperframe;
680 av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
681 framerate_q.den, framerate_q.num);
682 tpf->numerator = framerate_q.den;
683 tpf->denominator = framerate_q.num;
685 if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
686 ret = AVERROR(errno);
687 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
691 if (framerate_q.num != tpf->denominator ||
692 framerate_q.den != tpf->numerator) {
693 av_log(s1, AV_LOG_INFO,
694 "The driver changed the time per frame from "
696 framerate_q.den, framerate_q.num,
697 tpf->numerator, tpf->denominator);
700 av_log(s1, AV_LOG_WARNING,
701 "The driver does not allow to change time per frame\n");
704 s1->streams[0]->avg_frame_rate.num = tpf->denominator;
705 s1->streams[0]->avg_frame_rate.den = tpf->numerator;
706 s1->streams[0]->r_frame_rate = s1->streams[0]->avg_frame_rate;
711 static int device_try_init(AVFormatContext *s1,
712 enum AVPixelFormat pix_fmt,
715 uint32_t *desired_format,
716 enum AVCodecID *codec_id)
720 *desired_format = avpriv_fmt_ff2v4l(pix_fmt, s1->video_codec_id);
722 if (*desired_format) {
723 ret = device_init(s1, width, height, *desired_format);
726 if (ret != AVERROR(EINVAL))
731 if (!*desired_format) {
732 for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {
733 if (s1->video_codec_id == AV_CODEC_ID_NONE ||
734 avpriv_fmt_conversion_table[i].codec_id == s1->video_codec_id) {
735 av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
736 avcodec_get_name(avpriv_fmt_conversion_table[i].codec_id),
737 (char *)av_x_if_null(av_get_pix_fmt_name(avpriv_fmt_conversion_table[i].ff_fmt), "none"));
739 *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;
740 ret = device_init(s1, width, height, *desired_format);
743 else if (ret != AVERROR(EINVAL))
749 if (*desired_format == 0) {
750 av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
751 "codec '%s' (id %d), pixel format '%s' (id %d)\n",
752 avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
753 (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
754 ret = AVERROR(EINVAL);
758 *codec_id = avpriv_fmt_v4l2codec(*desired_format);
759 av_assert0(*codec_id != AV_CODEC_ID_NONE);
763 static int v4l2_read_header(AVFormatContext *s1)
765 struct video_data *s = s1->priv_data;
768 uint32_t desired_format;
769 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
770 enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
771 struct v4l2_input input = { 0 };
773 st = avformat_new_stream(s1, NULL);
775 return AVERROR(ENOMEM);
778 /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
779 and errors will get sent to stderr */
780 v4l2_log_file = fopen("/dev/null", "w");
783 s->fd = device_open(s1);
787 if (s->channel != -1) {
788 /* set video input */
789 av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
790 if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
791 res = AVERROR(errno);
792 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
796 /* get current video input */
797 if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
798 res = AVERROR(errno);
799 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
805 input.index = s->channel;
806 if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
807 res = AVERROR(errno);
808 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
811 s->std_id = input.std;
812 av_log(s1, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s\n",
813 s->channel, input.name);
815 if (s->list_format) {
816 list_formats(s1, s->fd, s->list_format);
820 if (s->list_standard) {
825 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
827 if (s->pixel_format) {
828 AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
831 s1->video_codec_id = codec->id;
833 pix_fmt = av_get_pix_fmt(s->pixel_format);
835 if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
836 av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
839 return AVERROR(EINVAL);
843 if (!s->width && !s->height) {
844 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
846 av_log(s1, AV_LOG_VERBOSE,
847 "Querying the device for the current frame size\n");
848 if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
849 res = AVERROR(errno);
850 av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
854 s->width = fmt.fmt.pix.width;
855 s->height = fmt.fmt.pix.height;
856 av_log(s1, AV_LOG_VERBOSE,
857 "Setting frame size to %dx%d\n", s->width, s->height);
860 res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
866 /* If no pixel_format was specified, the codec_id was not known up
867 * until now. Set video_codec_id in the context, as codec_id will
868 * not be available outside this function
870 if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
871 s1->video_codec_id = codec_id;
873 if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
876 s->frame_format = desired_format;
878 if ((res = v4l2_set_parameters(s1)) < 0)
881 st->codec->pix_fmt = avpriv_fmt_v4l2ff(desired_format, codec_id);
883 avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
885 if ((res = mmap_init(s1)) ||
886 (res = mmap_start(s1)) < 0) {
891 s->top_field_first = first_field(s->fd);
893 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
894 st->codec->codec_id = codec_id;
895 if (codec_id == AV_CODEC_ID_RAWVIDEO)
896 st->codec->codec_tag =
897 avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
898 if (desired_format == V4L2_PIX_FMT_YVU420)
899 st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
900 else if (desired_format == V4L2_PIX_FMT_YVU410)
901 st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
902 st->codec->width = s->width;
903 st->codec->height = s->height;
904 st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
909 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
911 struct video_data *s = s1->priv_data;
912 AVFrame *frame = s1->streams[0]->codec->coded_frame;
916 if ((res = mmap_read_frame(s1, pkt)) < 0) {
920 if (frame && s->interlaced) {
921 frame->interlaced_frame = 1;
922 frame->top_field_first = s->top_field_first;
928 static int v4l2_read_close(AVFormatContext *s1)
930 struct video_data *s = s1->priv_data;
932 if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
933 av_log(s1, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
942 #define OFFSET(x) offsetof(struct video_data, x)
943 #define DEC AV_OPT_FLAG_DECODING_PARAM
945 static const AVOption options[] = {
946 { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
947 { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
948 { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
949 { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
950 { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
951 { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
953 { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
954 { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
955 { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
956 { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
958 { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
959 { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
961 { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
962 { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
963 { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
964 { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
965 { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
970 static const AVClass v4l2_class = {
971 .class_name = "V4L2 indev",
972 .item_name = av_default_item_name,
974 .version = LIBAVUTIL_VERSION_INT,
977 AVInputFormat ff_v4l2_demuxer = {
978 .name = "video4linux2,v4l2",
979 .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
980 .priv_data_size = sizeof(struct video_data),
981 .read_header = v4l2_read_header,
982 .read_packet = v4l2_read_packet,
983 .read_close = v4l2_read_close,
984 .flags = AVFMT_NOFILE,
985 .priv_class = &v4l2_class,