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
},
114 #ifdef V4L2_PIX_FMT_H264
115 { AV_PIX_FMT_NONE
, AV_CODEC_ID_H264
, V4L2_PIX_FMT_H264
},
119 static int device_open(AVFormatContext
*ctx
)
121 struct v4l2_capability cap
;
127 if (ctx
->flags
& AVFMT_FLAG_NONBLOCK
) {
131 fd
= avpriv_open(ctx
->filename
, flags
);
133 err
= AVERROR(errno
);
134 av_strerror(err
, errbuf
, sizeof(errbuf
));
136 av_log(ctx
, AV_LOG_ERROR
, "Cannot open video device %s : %s\n",
137 ctx
->filename
, errbuf
);
142 res
= ioctl(fd
, VIDIOC_QUERYCAP
, &cap
);
144 err
= AVERROR(errno
);
145 av_strerror(err
, errbuf
, sizeof(errbuf
));
146 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_QUERYCAP): %s\n",
152 av_log(ctx
, AV_LOG_VERBOSE
, "[%d]Capabilities: %x\n",
153 fd
, cap
.capabilities
);
155 if (!(cap
.capabilities
& V4L2_CAP_VIDEO_CAPTURE
)) {
156 av_log(ctx
, AV_LOG_ERROR
, "Not a video capture device.\n");
157 err
= AVERROR(ENODEV
);
162 if (!(cap
.capabilities
& V4L2_CAP_STREAMING
)) {
163 av_log(ctx
, AV_LOG_ERROR
,
164 "The device does not support the streaming I/O method.\n");
165 err
= AVERROR(ENOSYS
);
177 static int device_init(AVFormatContext
*ctx
, int *width
, int *height
,
180 struct video_data
*s
= ctx
->priv_data
;
182 struct v4l2_format fmt
= { .type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
};
183 struct v4l2_pix_format
*pix
= &fmt
.fmt
.pix
;
188 pix
->height
= *height
;
189 pix
->pixelformat
= pix_fmt
;
190 pix
->field
= V4L2_FIELD_ANY
;
192 res
= ioctl(fd
, VIDIOC_S_FMT
, &fmt
);
194 if ((*width
!= fmt
.fmt
.pix
.width
) || (*height
!= fmt
.fmt
.pix
.height
)) {
195 av_log(ctx
, AV_LOG_INFO
,
196 "The V4L2 driver changed the video from %dx%d to %dx%d\n",
197 *width
, *height
, fmt
.fmt
.pix
.width
, fmt
.fmt
.pix
.height
);
198 *width
= fmt
.fmt
.pix
.width
;
199 *height
= fmt
.fmt
.pix
.height
;
202 if (pix_fmt
!= fmt
.fmt
.pix
.pixelformat
) {
203 av_log(ctx
, AV_LOG_DEBUG
,
204 "The V4L2 driver changed the pixel format "
205 "from 0x%08X to 0x%08X\n",
206 pix_fmt
, fmt
.fmt
.pix
.pixelformat
);
210 if (fmt
.fmt
.pix
.field
== V4L2_FIELD_INTERLACED
) {
211 av_log(ctx
, AV_LOG_DEBUG
, "The V4L2 driver using the interlaced mode");
218 static int first_field(int fd
)
223 res
= ioctl(fd
, VIDIOC_G_STD
, &std
);
227 if (std
& V4L2_STD_NTSC
) {
234 static uint32_t fmt_ff2v4l(enum AVPixelFormat pix_fmt
, enum AVCodecID codec_id
)
238 for (i
= 0; i
< FF_ARRAY_ELEMS(fmt_conversion_table
); i
++) {
239 if ((codec_id
== AV_CODEC_ID_NONE
||
240 fmt_conversion_table
[i
].codec_id
== codec_id
) &&
241 (pix_fmt
== AV_PIX_FMT_NONE
||
242 fmt_conversion_table
[i
].ff_fmt
== pix_fmt
)) {
243 return fmt_conversion_table
[i
].v4l2_fmt
;
250 static enum AVPixelFormat
fmt_v4l2ff(uint32_t v4l2_fmt
, enum AVCodecID codec_id
)
254 for (i
= 0; i
< FF_ARRAY_ELEMS(fmt_conversion_table
); i
++) {
255 if (fmt_conversion_table
[i
].v4l2_fmt
== v4l2_fmt
&&
256 fmt_conversion_table
[i
].codec_id
== codec_id
) {
257 return fmt_conversion_table
[i
].ff_fmt
;
261 return AV_PIX_FMT_NONE
;
264 static enum AVCodecID
fmt_v4l2codec(uint32_t v4l2_fmt
)
268 for (i
= 0; i
< FF_ARRAY_ELEMS(fmt_conversion_table
); i
++) {
269 if (fmt_conversion_table
[i
].v4l2_fmt
== v4l2_fmt
) {
270 return fmt_conversion_table
[i
].codec_id
;
274 return AV_CODEC_ID_NONE
;
277 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
278 static void list_framesizes(AVFormatContext
*ctx
, int fd
, uint32_t pixelformat
)
280 struct v4l2_frmsizeenum vfse
= { .pixel_format
= pixelformat
};
282 while(!ioctl(fd
, VIDIOC_ENUM_FRAMESIZES
, &vfse
)) {
284 case V4L2_FRMSIZE_TYPE_DISCRETE
:
285 av_log(ctx
, AV_LOG_INFO
, " %ux%u",
286 vfse
.discrete
.width
, vfse
.discrete
.height
);
288 case V4L2_FRMSIZE_TYPE_CONTINUOUS
:
289 case V4L2_FRMSIZE_TYPE_STEPWISE
:
290 av_log(ctx
, AV_LOG_INFO
, " {%u-%u, %u}x{%u-%u, %u}",
291 vfse
.stepwise
.min_width
,
292 vfse
.stepwise
.max_width
,
293 vfse
.stepwise
.step_width
,
294 vfse
.stepwise
.min_height
,
295 vfse
.stepwise
.max_height
,
296 vfse
.stepwise
.step_height
);
303 static void list_formats(AVFormatContext
*ctx
, int fd
, int type
)
305 struct v4l2_fmtdesc vfd
= { .type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
};
307 while(!ioctl(fd
, VIDIOC_ENUM_FMT
, &vfd
)) {
308 enum AVCodecID codec_id
= fmt_v4l2codec(vfd
.pixelformat
);
309 enum AVPixelFormat pix_fmt
= fmt_v4l2ff(vfd
.pixelformat
, codec_id
);
313 if (!(vfd
.flags
& V4L2_FMT_FLAG_COMPRESSED
) &&
314 type
& V4L_RAWFORMATS
) {
315 const char *fmt_name
= av_get_pix_fmt_name(pix_fmt
);
316 av_log(ctx
, AV_LOG_INFO
, "R : %9s : %20s :",
317 fmt_name ? fmt_name
: "Unsupported",
319 } else if (vfd
.flags
& V4L2_FMT_FLAG_COMPRESSED
&&
320 type
& V4L_COMPFORMATS
) {
321 const AVCodecDescriptor
*desc
= avcodec_descriptor_get(codec_id
);
322 av_log(ctx
, AV_LOG_INFO
, "C : %9s : %20s :",
323 desc ? desc
->name
: "Unsupported",
329 #ifdef V4L2_FMT_FLAG_EMULATED
330 if (vfd
.flags
& V4L2_FMT_FLAG_EMULATED
) {
331 av_log(ctx
, AV_LOG_WARNING
, "%s", "Emulated");
335 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
336 list_framesizes(ctx
, fd
, vfd
.pixelformat
);
338 av_log(ctx
, AV_LOG_INFO
, "\n");
342 static int mmap_init(AVFormatContext
*ctx
)
345 struct video_data
*s
= ctx
->priv_data
;
346 struct v4l2_requestbuffers req
= {
347 .type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
,
348 .count
= desired_video_buffers
,
349 .memory
= V4L2_MEMORY_MMAP
352 res
= ioctl(s
->fd
, VIDIOC_REQBUFS
, &req
);
354 res
= AVERROR(errno
);
355 if (res
== AVERROR(EINVAL
)) {
356 av_log(ctx
, AV_LOG_ERROR
, "Device does not support mmap\n");
358 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_REQBUFS)\n");
365 av_log(ctx
, AV_LOG_ERROR
, "Insufficient buffer memory\n");
367 return AVERROR(ENOMEM
);
369 s
->buffers
= req
.count
;
370 s
->buf_start
= av_malloc(sizeof(void *) * s
->buffers
);
372 av_log(ctx
, AV_LOG_ERROR
, "Cannot allocate buffer pointers\n");
374 return AVERROR(ENOMEM
);
376 s
->buf_len
= av_malloc(sizeof(unsigned int) * s
->buffers
);
378 av_log(ctx
, AV_LOG_ERROR
, "Cannot allocate buffer sizes\n");
379 av_free(s
->buf_start
);
381 return AVERROR(ENOMEM
);
384 for (i
= 0; i
< req
.count
; i
++) {
385 struct v4l2_buffer buf
= {
386 .type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
,
388 .memory
= V4L2_MEMORY_MMAP
391 res
= ioctl(s
->fd
, VIDIOC_QUERYBUF
, &buf
);
393 res
= AVERROR(errno
);
394 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_QUERYBUF)\n");
399 s
->buf_len
[i
] = buf
.length
;
400 if (s
->frame_size
> 0 && s
->buf_len
[i
] < s
->frame_size
) {
401 av_log(ctx
, AV_LOG_ERROR
,
402 "Buffer len [%d] = %d != %d\n",
403 i
, s
->buf_len
[i
], s
->frame_size
);
407 s
->buf_start
[i
] = mmap(NULL
, buf
.length
,
408 PROT_READ
| PROT_WRITE
, MAP_SHARED
,
409 s
->fd
, buf
.m
.offset
);
411 if (s
->buf_start
[i
] == MAP_FAILED
) {
413 res
= AVERROR(errno
);
414 av_strerror(res
, errbuf
, sizeof(errbuf
));
415 av_log(ctx
, AV_LOG_ERROR
, "mmap: %s\n", errbuf
);
424 #if FF_API_DESTRUCT_PACKET
425 static void dummy_release_buffer(AVPacket
*pkt
)
431 static void mmap_release_buffer(void *opaque
, uint8_t *data
)
433 struct v4l2_buffer buf
= { 0 };
435 struct buff_data
*buf_descriptor
= opaque
;
436 struct video_data
*s
= buf_descriptor
->s
;
439 buf
.type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
;
440 buf
.memory
= V4L2_MEMORY_MMAP
;
441 buf
.index
= buf_descriptor
->index
;
442 fd
= buf_descriptor
->fd
;
443 av_free(buf_descriptor
);
445 res
= ioctl(fd
, VIDIOC_QBUF
, &buf
);
447 av_strerror(AVERROR(errno
), errbuf
, sizeof(errbuf
));
448 av_log(NULL
, AV_LOG_ERROR
, "ioctl(VIDIOC_QBUF): %s\n",
451 avpriv_atomic_int_add_and_fetch(&s
->buffers_queued
, 1);
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
461 struct pollfd p
= { .fd
= s
->fd
, .events
= POLLIN
};
464 res
= poll(&p
, 1, s
->timeout
);
466 return AVERROR(errno
);
468 if (!(p
.revents
& (POLLIN
| POLLERR
| POLLHUP
)))
469 return AVERROR(EAGAIN
);
471 /* FIXME: Some special treatment might be needed in case of loss of signal... */
472 while ((res
= ioctl(s
->fd
, VIDIOC_DQBUF
, &buf
)) < 0 && (errno
== EINTR
));
475 if (errno
== EAGAIN
) {
478 return AVERROR(EAGAIN
);
480 res
= AVERROR(errno
);
481 av_strerror(res
, errbuf
, sizeof(errbuf
));
482 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_DQBUF): %s\n",
488 if (buf
.index
>= s
->buffers
) {
489 av_log(ctx
, AV_LOG_ERROR
, "Invalid buffer index received.\n");
490 return AVERROR(EINVAL
);
492 avpriv_atomic_int_add_and_fetch(&s
->buffers_queued
, -1);
493 // always keep at least one buffer queued
494 av_assert0(avpriv_atomic_int_get(&s
->buffers_queued
) >= 1);
496 if (s
->frame_size
> 0 && buf
.bytesused
!= s
->frame_size
) {
497 av_log(ctx
, AV_LOG_ERROR
,
498 "The v4l2 frame is %d bytes, but %d bytes are expected\n",
499 buf
.bytesused
, s
->frame_size
);
501 return AVERROR_INVALIDDATA
;
504 /* Image is at s->buff_start[buf.index] */
505 if (avpriv_atomic_int_get(&s
->buffers_queued
) == FFMAX(s
->buffers
/ 8, 1)) {
506 /* when we start getting low on queued buffers, fall back on copying data */
507 res
= av_new_packet(pkt
, buf
.bytesused
);
509 av_log(ctx
, AV_LOG_ERROR
, "Error allocating a packet.\n");
512 memcpy(pkt
->data
, s
->buf_start
[buf
.index
], buf
.bytesused
);
514 res
= ioctl(s
->fd
, VIDIOC_QBUF
, &buf
);
516 res
= AVERROR(errno
);
517 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_QBUF)\n");
521 avpriv_atomic_int_add_and_fetch(&s
->buffers_queued
, 1);
523 struct buff_data
*buf_descriptor
;
525 pkt
->data
= s
->buf_start
[buf
.index
];
526 pkt
->size
= buf
.bytesused
;
527 #if FF_API_DESTRUCT_PACKET
528 FF_DISABLE_DEPRECATION_WARNINGS
529 pkt
->destruct
= dummy_release_buffer
;
530 FF_ENABLE_DEPRECATION_WARNINGS
533 buf_descriptor
= av_malloc(sizeof(struct buff_data
));
534 if (!buf_descriptor
) {
535 /* Something went wrong... Since av_malloc() failed, we cannot even
536 * allocate a buffer for memcpying into it
538 av_log(ctx
, AV_LOG_ERROR
, "Failed to allocate a buffer descriptor\n");
539 res
= ioctl(s
->fd
, VIDIOC_QBUF
, &buf
);
541 return AVERROR(ENOMEM
);
543 buf_descriptor
->fd
= s
->fd
;
544 buf_descriptor
->index
= buf
.index
;
545 buf_descriptor
->s
= s
;
547 pkt
->buf
= av_buffer_create(pkt
->data
, pkt
->size
, mmap_release_buffer
,
550 av_freep(&buf_descriptor
);
551 return AVERROR(ENOMEM
);
554 pkt
->pts
= buf
.timestamp
.tv_sec
* INT64_C(1000000) + buf
.timestamp
.tv_usec
;
556 return s
->buf_len
[buf
.index
];
559 static int mmap_start(AVFormatContext
*ctx
)
561 struct video_data
*s
= ctx
->priv_data
;
562 enum v4l2_buf_type type
;
566 for (i
= 0; i
< s
->buffers
; i
++) {
567 struct v4l2_buffer buf
= {
568 .type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
,
570 .memory
= V4L2_MEMORY_MMAP
573 res
= ioctl(s
->fd
, VIDIOC_QBUF
, &buf
);
575 err
= AVERROR(errno
);
576 av_strerror(err
, errbuf
, sizeof(errbuf
));
577 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_QBUF): %s\n",
583 s
->buffers_queued
= s
->buffers
;
585 type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
;
586 res
= ioctl(s
->fd
, VIDIOC_STREAMON
, &type
);
588 err
= AVERROR(errno
);
589 av_strerror(err
, errbuf
, sizeof(errbuf
));
590 av_log(ctx
, AV_LOG_ERROR
, "ioctl(VIDIOC_STREAMON): %s\n",
599 static void mmap_close(struct video_data
*s
)
601 enum v4l2_buf_type type
;
604 type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
;
605 /* We do not check for the result, because we could
606 * not do anything about it anyway...
608 ioctl(s
->fd
, VIDIOC_STREAMOFF
, &type
);
609 for (i
= 0; i
< s
->buffers
; i
++) {
610 munmap(s
->buf_start
[i
], s
->buf_len
[i
]);
612 av_free(s
->buf_start
);
616 static int v4l2_set_parameters(AVFormatContext
*s1
)
618 struct video_data
*s
= s1
->priv_data
;
619 struct v4l2_input input
= { 0 };
620 struct v4l2_standard standard
= { 0 };
621 struct v4l2_streamparm streamparm
= { 0 };
622 struct v4l2_fract
*tpf
= &streamparm
.parm
.capture
.timeperframe
;
623 AVRational framerate_q
= { 0 };
626 streamparm
.type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
;
629 (ret
= av_parse_video_rate(&framerate_q
, s
->framerate
)) < 0) {
630 av_log(s1
, AV_LOG_ERROR
, "Could not parse framerate '%s'.\n",
635 /* set tv video input */
636 input
.index
= s
->channel
;
637 if (ioctl(s
->fd
, VIDIOC_ENUMINPUT
, &input
) < 0) {
638 av_log(s1
, AV_LOG_ERROR
, "The V4L2 driver ioctl enum input failed:\n");
642 av_log(s1
, AV_LOG_DEBUG
, "The V4L2 driver set input_id: %d, input: %s\n",
643 s
->channel
, input
.name
);
644 if (ioctl(s
->fd
, VIDIOC_S_INPUT
, &input
.index
) < 0) {
645 av_log(s1
, AV_LOG_ERROR
,
646 "The V4L2 driver ioctl set input(%d) failed\n",
652 av_log(s1
, AV_LOG_DEBUG
, "The V4L2 driver set standard: %s\n",
654 /* set tv standard */
657 if (ioctl(s
->fd
, VIDIOC_ENUMSTD
, &standard
) < 0) {
658 av_log(s1
, AV_LOG_ERROR
,
659 "The V4L2 driver ioctl set standard(%s) failed\n",
664 if (!av_strcasecmp(standard
.name
, s
->standard
)) {
669 av_log(s1
, AV_LOG_DEBUG
,
670 "The V4L2 driver set standard: %s, id: %"PRIu64
"\n",
671 s
->standard
, (uint64_t)standard
.id
);
672 if (ioctl(s
->fd
, VIDIOC_S_STD
, &standard
.id
) < 0) {
673 av_log(s1
, AV_LOG_ERROR
,
674 "The V4L2 driver ioctl set standard(%s) failed\n",
680 if (framerate_q
.num
&& framerate_q
.den
) {
681 av_log(s1
, AV_LOG_DEBUG
, "Setting time per frame to %d/%d\n",
682 framerate_q
.den
, framerate_q
.num
);
683 tpf
->numerator
= framerate_q
.den
;
684 tpf
->denominator
= framerate_q
.num
;
686 if (ioctl(s
->fd
, VIDIOC_S_PARM
, &streamparm
) != 0) {
687 av_log(s1
, AV_LOG_ERROR
,
688 "ioctl set time per frame(%d/%d) failed\n",
689 framerate_q
.den
, framerate_q
.num
);
693 if (framerate_q
.num
!= tpf
->denominator
||
694 framerate_q
.den
!= tpf
->numerator
) {
695 av_log(s1
, AV_LOG_INFO
,
696 "The driver changed the time per frame from "
698 framerate_q
.den
, framerate_q
.num
,
699 tpf
->numerator
, tpf
->denominator
);
702 if (ioctl(s
->fd
, VIDIOC_G_PARM
, &streamparm
) != 0) {
704 ret
= AVERROR(errno
);
705 av_strerror(ret
, errbuf
, sizeof(errbuf
));
706 av_log(s1
, AV_LOG_ERROR
, "ioctl(VIDIOC_G_PARM): %s\n",
711 s1
->streams
[0]->avg_frame_rate
.num
= tpf
->denominator
;
712 s1
->streams
[0]->avg_frame_rate
.den
= tpf
->numerator
;
715 av_rescale_q(1, s1
->streams
[0]->avg_frame_rate
,
716 (AVRational
){1, 1000});
721 static uint32_t device_try_init(AVFormatContext
*s1
,
722 enum AVPixelFormat pix_fmt
,
725 enum AVCodecID
*codec_id
)
727 uint32_t desired_format
= fmt_ff2v4l(pix_fmt
, s1
->video_codec_id
);
729 if (desired_format
== 0 ||
730 device_init(s1
, width
, height
, desired_format
) < 0) {
734 for (i
= 0; i
<FF_ARRAY_ELEMS(fmt_conversion_table
); i
++) {
735 if (s1
->video_codec_id
== AV_CODEC_ID_NONE
||
736 fmt_conversion_table
[i
].codec_id
== s1
->video_codec_id
) {
737 desired_format
= fmt_conversion_table
[i
].v4l2_fmt
;
738 if (device_init(s1
, width
, height
, desired_format
) >= 0) {
746 if (desired_format
!= 0) {
747 *codec_id
= fmt_v4l2codec(desired_format
);
748 assert(*codec_id
!= AV_CODEC_ID_NONE
);
751 return desired_format
;
754 static int v4l2_read_header(AVFormatContext
*s1
)
756 struct video_data
*s
= s1
->priv_data
;
759 uint32_t desired_format
;
760 enum AVCodecID codec_id
;
761 enum AVPixelFormat pix_fmt
= AV_PIX_FMT_NONE
;
763 st
= avformat_new_stream(s1
, NULL
);
765 return AVERROR(ENOMEM
);
767 s
->fd
= device_open(s1
);
771 if (s
->list_format
) {
772 list_formats(s1
, s
->fd
, s
->list_format
);
776 avpriv_set_pts_info(st
, 64, 1, 1000000); /* 64 bits pts in us */
779 (res
= av_parse_video_size(&s
->width
, &s
->height
, s
->video_size
)) < 0) {
780 av_log(s1
, AV_LOG_ERROR
, "Could not parse video size '%s'.\n",
785 if (s
->pixel_format
) {
786 AVCodec
*codec
= avcodec_find_decoder_by_name(s
->pixel_format
);
789 s1
->video_codec_id
= codec
->id
;
790 st
->need_parsing
= AVSTREAM_PARSE_HEADERS
;
793 pix_fmt
= av_get_pix_fmt(s
->pixel_format
);
795 if (pix_fmt
== AV_PIX_FMT_NONE
&& !codec
) {
796 av_log(s1
, AV_LOG_ERROR
, "No such input format: %s.\n",
799 return AVERROR(EINVAL
);
803 if (!s
->width
&& !s
->height
) {
804 struct v4l2_format fmt
;
806 av_log(s1
, AV_LOG_VERBOSE
,
807 "Querying the device for the current frame size\n");
808 fmt
.type
= V4L2_BUF_TYPE_VIDEO_CAPTURE
;
809 if (ioctl(s
->fd
, VIDIOC_G_FMT
, &fmt
) < 0) {
811 res
= AVERROR(errno
);
812 av_strerror(res
, errbuf
, sizeof(errbuf
));
813 av_log(s1
, AV_LOG_ERROR
, "ioctl(VIDIOC_G_FMT): %s\n",
818 s
->width
= fmt
.fmt
.pix
.width
;
819 s
->height
= fmt
.fmt
.pix
.height
;
820 av_log(s1
, AV_LOG_VERBOSE
,
821 "Setting frame size to %dx%d\n", s
->width
, s
->height
);
824 desired_format
= device_try_init(s1
, pix_fmt
, &s
->width
, &s
->height
,
826 if (desired_format
== 0) {
827 av_log(s1
, AV_LOG_ERROR
, "Cannot find a proper format for "
828 "codec_id %d, pix_fmt %d.\n", s1
->video_codec_id
, pix_fmt
);
834 if ((res
= av_image_check_size(s
->width
, s
->height
, 0, s1
) < 0))
837 s
->frame_format
= desired_format
;
839 if ((res
= v4l2_set_parameters(s1
) < 0))
842 st
->codec
->pix_fmt
= fmt_v4l2ff(desired_format
, codec_id
);
844 avpicture_get_size(st
->codec
->pix_fmt
, s
->width
, s
->height
);
846 if ((res
= mmap_init(s1
)) ||
847 (res
= mmap_start(s1
)) < 0) {
852 s
->top_field_first
= first_field(s
->fd
);
854 st
->codec
->codec_type
= AVMEDIA_TYPE_VIDEO
;
855 st
->codec
->codec_id
= codec_id
;
856 if (codec_id
== AV_CODEC_ID_RAWVIDEO
)
857 st
->codec
->codec_tag
=
858 avcodec_pix_fmt_to_codec_tag(st
->codec
->pix_fmt
);
859 st
->codec
->width
= s
->width
;
860 st
->codec
->height
= s
->height
;
861 st
->codec
->bit_rate
= s
->frame_size
* av_q2d(st
->avg_frame_rate
) * 8;
866 static int v4l2_read_packet(AVFormatContext
*s1
, AVPacket
*pkt
)
868 struct video_data
*s
= s1
->priv_data
;
869 AVFrame
*frame
= s1
->streams
[0]->codec
->coded_frame
;
873 if ((res
= mmap_read_frame(s1
, pkt
)) < 0) {
877 if (frame
&& s
->interlaced
) {
878 frame
->interlaced_frame
= 1;
879 frame
->top_field_first
= s
->top_field_first
;
885 static int v4l2_read_close(AVFormatContext
*s1
)
887 struct video_data
*s
= s1
->priv_data
;
889 if (avpriv_atomic_int_get(&s
->buffers_queued
) != s
->buffers
)
890 av_log(s1
, AV_LOG_WARNING
, "Some buffers are still owned by the caller on "
899 #define OFFSET(x) offsetof(struct video_data, x)
900 #define DEC AV_OPT_FLAG_DECODING_PARAM
901 static const AVOption options
[] = {
902 { "standard", "TV standard, used only by analog frame grabber", OFFSET(standard
), AV_OPT_TYPE_STRING
, {.str
= NULL
}, 0, 0, DEC
},
903 { "channel", "TV channel, used only by frame grabber", OFFSET(channel
), AV_OPT_TYPE_INT
, {.i64
= 0 }, 0, INT_MAX
, DEC
},
904 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size
), AV_OPT_TYPE_STRING
, {.str
= NULL
}, 0, 0, DEC
},
905 { "pixel_format", "Preferred pixel format", OFFSET(pixel_format
), AV_OPT_TYPE_STRING
, {.str
= NULL
}, 0, 0, DEC
},
906 { "input_format", "Preferred pixel format (for raw video) or codec name", OFFSET(pixel_format
), AV_OPT_TYPE_STRING
, {.str
= NULL
}, 0, 0, DEC
},
907 { "framerate", "", OFFSET(framerate
), AV_OPT_TYPE_STRING
, {.str
= NULL
}, 0, 0, DEC
},
908 { "list_formats", "List available formats and exit", OFFSET(list_format
), AV_OPT_TYPE_INT
, {.i64
= 0 }, 0, INT_MAX
, DEC
, "list_formats" },
909 { "all", "Show all available formats", OFFSET(list_format
), AV_OPT_TYPE_CONST
, {.i64
= V4L_ALLFORMATS
}, 0, INT_MAX
, DEC
, "list_formats" },
910 { "raw", "Show only non-compressed formats", OFFSET(list_format
), AV_OPT_TYPE_CONST
, {.i64
= V4L_RAWFORMATS
}, 0, INT_MAX
, DEC
, "list_formats" },
911 { "compressed", "Show only compressed formats", OFFSET(list_format
), AV_OPT_TYPE_CONST
, {.i64
= V4L_COMPFORMATS
}, 0, INT_MAX
, DEC
, "list_formats" },
915 static const AVClass v4l2_class
= {
916 .class_name
= "V4L2 indev",
917 .item_name
= av_default_item_name
,
919 .version
= LIBAVUTIL_VERSION_INT
,
922 AVInputFormat ff_v4l2_demuxer
= {
923 .name
= "video4linux2",
924 .long_name
= NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
925 .priv_data_size
= sizeof(struct video_data
),
926 .read_header
= v4l2_read_header
,
927 .read_packet
= v4l2_read_packet
,
928 .read_close
= v4l2_read_close
,
929 .flags
= AVFMT_NOFILE
,
930 .priv_class
= &v4l2_class
,