Go to the documentation of this file.
33 #include <stdatomic.h>
57 #define V4L_ALLFORMATS 3
58 #define V4L_RAWFORMATS 1
59 #define V4L_COMPFORMATS 2
64 #define V4L_TS_DEFAULT 0
74 #define V4L_TS_MONO2ABS 2
81 #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
117 void *(*mmap_f)(
void *start,
size_t length,
int prot,
int flags,
int fd, int64_t
offset);
129 struct v4l2_capability cap;
134 #define SET_WRAPPERS(prefix) do { \
135 s->open_f = prefix ## open; \
136 s->close_f = prefix ## close; \
137 s->dup_f = prefix ## dup; \
138 s->ioctl_f = prefix ## ioctl; \
139 s->read_f = prefix ## read; \
140 s->mmap_f = prefix ## mmap; \
141 s->munmap_f = prefix ## munmap; \
144 if (
s->use_libv4l2) {
155 #define v4l2_open s->open_f
156 #define v4l2_close s->close_f
157 #define v4l2_dup s->dup_f
158 #define v4l2_ioctl s->ioctl_f
159 #define v4l2_read s->read_f
160 #define v4l2_mmap s->mmap_f
161 #define v4l2_munmap s->munmap_f
175 if (
v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
183 fd, cap.capabilities);
185 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
191 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
193 "The device does not support the streaming I/O method.\n");
206 uint32_t pixelformat)
209 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
212 fmt.fmt.pix.width = *
width;
213 fmt.fmt.pix.height = *
height;
214 fmt.fmt.pix.pixelformat = pixelformat;
215 fmt.fmt.pix.field = V4L2_FIELD_ANY;
222 if ((*
width != fmt.fmt.pix.width) || (*
height != fmt.fmt.pix.height)) {
224 "The V4L2 driver changed the video from %dx%d to %dx%d\n",
225 *
width, *
height, fmt.fmt.pix.width, fmt.fmt.pix.height);
226 *
width = fmt.fmt.pix.width;
227 *
height = fmt.fmt.pix.height;
230 if (pixelformat != fmt.fmt.pix.pixelformat) {
232 "The V4L2 driver changed the pixel format "
233 "from 0x%08X to 0x%08X\n",
234 pixelformat, fmt.fmt.pix.pixelformat);
238 if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
240 "The V4L2 driver is using the interlaced mode\n");
255 if (std & V4L2_STD_NTSC)
261 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
265 struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
267 while(!
v4l2_ioctl(
s->fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
269 case V4L2_FRMSIZE_TYPE_DISCRETE:
271 vfse.discrete.width, vfse.discrete.height);
273 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
274 case V4L2_FRMSIZE_TYPE_STEPWISE:
276 vfse.stepwise.min_width,
277 vfse.stepwise.max_width,
278 vfse.stepwise.step_width,
279 vfse.stepwise.min_height,
280 vfse.stepwise.max_height,
281 vfse.stepwise.step_height);
291 struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
299 if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
303 fmt_name ? fmt_name :
"Unsupported",
305 }
else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
315 #ifdef V4L2_FMT_FLAG_EMULATED
316 if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
319 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
320 list_framesizes(
ctx, vfd.pixelformat);
330 struct v4l2_standard standard;
335 for (standard.index = 0; ; standard.index++) {
336 if (
v4l2_ioctl(
s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
346 standard.index, (uint64_t)standard.id, standard.name);
354 struct v4l2_requestbuffers req = {
355 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
357 .memory = V4L2_MEMORY_MMAP
370 s->buffers = req.count;
383 for (
i = 0;
i < req.count;
i++) {
384 struct v4l2_buffer buf = {
385 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
387 .memory = V4L2_MEMORY_MMAP
389 if (
v4l2_ioctl(
s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
395 s->buf_len[
i] = buf.length;
396 if (
s->frame_size > 0 &&
s->buf_len[
i] <
s->frame_size) {
398 "buf_len[%d] = %d < expected frame size %d\n",
399 i,
s->buf_len[
i],
s->frame_size);
403 PROT_READ | PROT_WRITE, MAP_SHARED,
404 s->fd, buf.m.offset);
406 if (
s->buf_start[
i] == MAP_FAILED) {
432 struct v4l2_buffer buf = { 0 };
433 struct buff_data *buf_descriptor = opaque;
436 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
437 buf.memory = V4L2_MEMORY_MMAP;
438 buf.index = buf_descriptor->
index;
444 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
445 static int64_t av_gettime_monotonic(
void)
458 ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 *
AV_TIME_BASE) {
463 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
465 now = av_gettime_monotonic();
467 (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 *
AV_TIME_BASE)) {
493 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
496 int64_t nowm = av_gettime_monotonic();
498 s->last_time_m = nowm;
508 struct v4l2_buffer buf = {
509 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
510 .memory = V4L2_MEMORY_MMAP
512 struct timeval buf_ts;
518 while ((res =
v4l2_ioctl(
s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
529 buf_ts = buf.timestamp;
531 if (buf.index >=
s->buffers) {
539 #ifdef V4L2_BUF_FLAG_ERROR
540 if (buf.flags & V4L2_BUF_FLAG_ERROR) {
542 "Dequeued v4l2 buffer contains corrupted data (%d bytes).\n",
551 s->frame_size = buf.bytesused;
553 if (
s->frame_size > 0 && buf.bytesused !=
s->frame_size) {
555 "Dequeued v4l2 buffer contains %d bytes, but %d were expected. Flags: 0x%08X.\n",
556 buf.bytesused,
s->frame_size, buf.flags);
570 memcpy(
pkt->
data,
s->buf_start[buf.index], buf.bytesused);
580 pkt->
data =
s->buf_start[buf.index];
584 if (!buf_descriptor) {
593 buf_descriptor->
index = buf.index;
594 buf_descriptor->
s =
s;
605 pkt->
pts = buf_ts.tv_sec * INT64_C(1000000) + buf_ts.tv_usec;
614 enum v4l2_buf_type
type;
617 for (
i = 0;
i <
s->buffers;
i++) {
618 struct v4l2_buffer buf = {
619 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
621 .memory = V4L2_MEMORY_MMAP
633 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
646 enum v4l2_buf_type
type;
649 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
654 for (
i = 0;
i <
s->buffers;
i++) {
664 struct v4l2_standard standard = { 0 };
665 struct v4l2_streamparm streamparm = { 0 };
666 struct v4l2_fract *tpf;
684 if (
v4l2_ioctl(
s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
696 if (
v4l2_ioctl(
s->fd, VIDIOC_S_STD, &standard.id) < 0) {
703 "This device does not support any standard\n");
709 tpf = &standard.frameperiod;
712 if (
v4l2_ioctl(
s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
719 tpf = &streamparm.parm.capture.timeperframe;
725 if (standard.id ==
s->std_id) {
727 "Current standard: %s, id: %"PRIx64
", frameperiod: %d/%d\n",
728 standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
733 tpf = &streamparm.parm.capture.timeperframe;
736 streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
737 if (
v4l2_ioctl(
s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
740 }
else if (framerate_q.
num && framerate_q.
den) {
741 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
742 tpf = &streamparm.parm.capture.timeperframe;
745 framerate_q.
den, framerate_q.
num);
746 tpf->numerator = framerate_q.
den;
747 tpf->denominator = framerate_q.
num;
749 if (
v4l2_ioctl(
s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
756 if (framerate_q.
num != tpf->denominator ||
757 framerate_q.
den != tpf->numerator) {
759 "The driver changed the time per frame from "
761 framerate_q.
den, framerate_q.
num,
762 tpf->numerator, tpf->denominator);
766 "The driver does not permit changing the time per frame\n");
769 if (tpf->denominator > 0 && tpf->numerator > 0) {
783 uint32_t *desired_format,
790 if (*desired_format) {
799 if (!*desired_format) {
817 if (*desired_format == 0) {
819 "codec '%s' (id %d), pixel format '%s' (id %d)\n",
844 uint32_t desired_format;
847 struct v4l2_input
input = { 0 };
857 v4l2_log_file = fopen(
"/dev/null",
"w");
864 if (
s->channel != -1) {
867 if (
v4l2_ioctl(
s->fd, VIDIOC_S_INPUT, &
s->channel) < 0) {
874 if (
v4l2_ioctl(
s->fd, VIDIOC_G_INPUT, &
s->channel) < 0) {
892 if (
s->list_format) {
898 if (
s->list_standard) {
906 if (
s->pixel_format) {
923 if (!
s->width && !
s->height) {
924 struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
927 "Querying the device for the current frame size\n");
935 s->width = fmt.fmt.pix.width;
936 s->height = fmt.fmt.pix.height;
938 "Setting frame size to %dx%d\n",
s->width,
s->height);
955 s->pixelformat = desired_format;
963 s->width,
s->height, 1);
979 if (desired_format == V4L2_PIX_FMT_YVU420)
981 else if (desired_format == V4L2_PIX_FMT_YVU410)
1023 return !strncmp(
name,
"video", 5) ||
1024 !strncmp(
name,
"radio", 5) ||
1025 !strncmp(
name,
"vbi", 3) ||
1026 !strncmp(
name,
"v4l-subdev", 10);
1033 struct dirent *
entry;
1039 dir = opendir(
"/dev");
1045 while ((
entry = readdir(dir))) {
1047 struct v4l2_capability cap;
1049 char device_name[256];
1055 if (
size >=
sizeof(device_name)) {
1064 if (
v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
1102 #define OFFSET(x) offsetof(struct video_data, x)
1103 #define DEC AV_OPT_FLAG_DECODING_PARAM
1113 {
"list_formats",
"list available formats and exit",
OFFSET(list_format),
AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX,
DEC, .unit =
"list_formats" },
1118 {
"list_standards",
"list supported standards and exit",
OFFSET(list_standard),
AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1,
DEC, .unit =
"list_standards" },
1119 {
"all",
"show all supported standards",
OFFSET(list_standard),
AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0,
DEC, .unit =
"list_standards" },
1121 {
"timestamps",
"set type of timestamps for grabbed frames",
OFFSET(ts_mode),
AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2,
DEC, .unit =
"timestamps" },
1122 {
"ts",
"set type of timestamps for grabbed frames",
OFFSET(ts_mode),
AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2,
DEC, .unit =
"timestamps" },
1126 {
"use_libv4l2",
"use libv4l2 (v4l-utils) conversion functions",
OFFSET(use_libv4l2),
AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1,
DEC },
1139 .
p.
name =
"video4linux2,v4l2",
const FFInputFormat ff_v4l2_demuxer
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Opaque type representing a time filter state.
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
#define AV_LOG_WARNING
Something somehow does not look correct.
AVPixelFormat
Pixel format.
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
#define atomic_store(object, desired)
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
enum AVMediaType codec_type
General type of the encoded data.
static const AVClass v4l2_class
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
static int v4l2_set_parameters(AVFormatContext *ctx)
char * device_name
device name, format depends on device
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
int nb_devices
number of autodetected devices
AVStream ** streams
A list of all streams in the file.
AVRational avg_frame_rate
Average framerate.
static int mmap_init(AVFormatContext *ctx)
#define AV_LOG_VERBOSE
Detailed information.
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
enum AVCodecID video_codec_id
Forced video codec_id.
uint32_t ff_fmt_ff2v4l(enum AVPixelFormat pix_fmt, enum AVCodecID codec_id)
const struct fmt_map ff_fmt_conversion_table[]
unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt)
Return a value representing the fourCC code associated to the pixel format pix_fmt,...
double ff_timefilter_eval(TimeFilter *self, double delta)
Evaluate the filter at a specified time.
enum AVCodecID ff_fmt_v4l2codec(uint32_t v4l2_fmt)
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
char * framerate
Set by a private option.
TimeFilter * ff_timefilter_new(double time_base, double period, double bandwidth)
Create a new Delay Locked Loop time filter.
AVDeviceInfo ** devices
list of autodetected devices
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pixelformat)
This struct describes the properties of a single codec described by an AVCodecID.
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
atomic_int buffers_queued
int flags
Flags modifying the (de)muxer behaviour.
static enum AVPixelFormat pix_fmt
static double av_q2d(AVRational a)
Convert an AVRational to a double.
#define av_assert0(cond)
assert() equivalent, that is always enabled.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
#define atomic_load(object)
AVCodecParameters * codecpar
Codec parameters associated with this stream.
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
#define LIBAVUTIL_VERSION_INT
Describe the class of an AVClass context structure.
Rational number (pair of numerator and denominator).
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option keep it simple and lowercase description are in without period
@ AV_OPT_TYPE_IMAGE_SIZE
offset must point to two consecutive integers
const char * av_default_item_name(void *ptr)
Return the context name.
enum AVPixelFormat ff_fmt_v4l2ff(uint32_t v4l2_fmt, enum AVCodecID codec_id)
This structure contains the data a format has to probe a file.
@ AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT
int(* open_f)(const char *file, int oflag,...)
AVBufferRef * av_buffer_create(uint8_t *data, size_t size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
AVCodecID
Identify the syntax and semantics of the bitstream.
static int device_open(AVFormatContext *ctx, const char *device_path)
static void mmap_release_buffer(void *opaque, uint8_t *data)
static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
static int v4l2_read_close(AVFormatContext *ctx)
static void list_formats(AVFormatContext *ctx, int type)
static int v4l2_read_probe(const AVProbeData *p)
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
char * url
input or output URL.
Structure describes basic parameters of the device.
int(* ioctl_f)(int fd, int request,...)
int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align)
Return the size in bytes of the amount of data required to store an image with the given parameters.
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf offset
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
char * device_description
human friendly name
and forward the test the status of outputs and forward it to the corresponding return FFERROR_NOT_READY If the filters stores internally one or a few frame for some input
#define AV_LOG_INFO
Standard information.
void avpriv_stream_set_need_parsing(AVStream *st, enum AVStreamParseType type)
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
int av_parse_video_rate(AVRational *rate, const char *arg)
Parse str and store the detected values in *rate.
void ff_timefilter_destroy(TimeFilter *self)
Free all resources associated with the filter.
#define i(width, name, range_min, range_max)
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
static void mmap_close(struct video_data *s)
static int v4l2_is_v4l_dev(const char *name)
#define AV_TIME_BASE
Internal time base represented as integer.
#define av_malloc_array(a, b)
static const AVOption options[]
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
double ff_timefilter_update(TimeFilter *self, double system_time, double period)
Update the filter.
#define V4L_TS_CONVERT_READY
Once the kind of timestamps returned by the kernel have been detected, the value of the timefilter (N...
static int v4l2_get_device_list(AVFormatContext *ctx, AVDeviceInfoList *device_list)
#define V4L_TS_MONO2ABS
Assume kernel timestamps are from the monotonic clock and convert to absolute timestamps.
ssize_t(* read_f)(int fd, void *buffer, size_t n)
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
enum AVPixelFormat av_get_pix_fmt(const char *name)
Return the pixel format corresponding to name.
int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem)
Add an element to a dynamic array.
the frame and frame reference mechanism is intended to as much as expensive copies of that data while still allowing the filters to produce correct results The data is stored in buffers represented by AVFrame structures Several references can point to the same frame buffer
int list_format
Set by a private option.
#define atomic_fetch_add(object, operand)
int list_standard
Set by a private option.
static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
char * pixel_format
Set by a private option.
int(* munmap_f)(void *_start, size_t length)
AVRational r_frame_rate
Real base framerate of the stream.
int64_t av_gettime(void)
Get the current time in microseconds.
#define SET_WRAPPERS(prefix)
char * av_strdup(const char *s)
Duplicate a string.
static int read_probe(const AVProbeData *p)
static int v4l2_read_header(AVFormatContext *ctx)
static int mmap_start(AVFormatContext *ctx)
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
This structure stores compressed data.
static void list_standards(AVFormatContext *ctx)
static int v4l2_read_packet(AVFormatContext *ctx, AVPacket *pkt)
#define flags(name, subs,...)
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
#define MKTAG(a, b, c, d)
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
#define V4L_TS_DEFAULT
Return timestamps to the user exactly as returned by the kernel.
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
Check if the given dimension of an image is valid, meaning that all bytes of the image can be address...
const AVCodecDescriptor * avcodec_descriptor_get_by_name(const char *name)
static int first_field(const struct video_data *s)
void * priv_data
Format private data.
#define V4L_TS_ABS
Autodetect the kind of timestamps returned by the kernel and convert to absolute (wall clock) timesta...
static void * av_x_if_null(const void *p, const void *x)
Return x default pointer in case p is NULL.
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
static int enqueue_buffer(struct video_data *s, struct v4l2_buffer *buf)
static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
static const int desired_video_buffers
static int device_try_init(AVFormatContext *ctx, enum AVPixelFormat pix_fmt, int *width, int *height, uint32_t *desired_format, enum AVCodecID *codec_id)