]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
Merge commit '0b6899f154347cdd0aa66c5ec16ed9c65871766f'
[ffmpeg] / libavdevice / v4l2.c
1 /*
2  * Copyright (c) 2000,2001 Fabrice Bellard
3  * Copyright (c) 2006 Luca Abeni
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * Video4Linux2 grab interface
25  *
26  * Part of this file is based on the V4L2 video capture example
27  * (http://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
28  *
29  * Thanks to Michael Niedermayer for providing the mapping between
30  * V4L2_PIX_FMT_* and AV_PIX_FMT_*
31  */
32
33 #include "v4l2-common.h"
34
35 #if CONFIG_LIBV4L2
36 #include <libv4l2.h>
37 #else
38 #define v4l2_open   open
39 #define v4l2_close  close
40 #define v4l2_dup    dup
41 #define v4l2_ioctl  ioctl
42 #define v4l2_read   read
43 #define v4l2_mmap   mmap
44 #define v4l2_munmap munmap
45 #endif
46
47 static const int desired_video_buffers = 256;
48
49 #define V4L_ALLFORMATS  3
50 #define V4L_RAWFORMATS  1
51 #define V4L_COMPFORMATS 2
52
53 /**
54  * Return timestamps to the user exactly as returned by the kernel
55  */
56 #define V4L_TS_DEFAULT  0
57 /**
58  * Autodetect the kind of timestamps returned by the kernel and convert to
59  * absolute (wall clock) timestamps.
60  */
61 #define V4L_TS_ABS      1
62 /**
63  * Assume kernel timestamps are from the monotonic clock and convert to
64  * absolute timestamps.
65  */
66 #define V4L_TS_MONO2ABS 2
67
68 /**
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
71  * takes place.
72  */
73 #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
74
75 struct video_data {
76     AVClass *class;
77     int fd;
78     int frame_format; /* V4L2_PIX_FMT_* */
79     int width, height;
80     int frame_size;
81     int interlaced;
82     int top_field_first;
83     int ts_mode;
84     TimeFilter *timefilter;
85     int64_t last_time_m;
86
87     int buffers;
88     volatile int buffers_queued;
89     void **buf_start;
90     unsigned int *buf_len;
91     char *standard;
92     v4l2_std_id std_id;
93     int channel;
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. */
98 };
99
100 struct buff_data {
101     struct video_data *s;
102     int index;
103 };
104
105 static int device_open(AVFormatContext *ctx)
106 {
107     struct v4l2_capability cap;
108     int fd;
109     int ret;
110     int flags = O_RDWR;
111
112     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
113         flags |= O_NONBLOCK;
114     }
115
116     fd = v4l2_open(ctx->filename, flags, 0);
117     if (fd < 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));
121         return ret;
122     }
123
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",
127                av_err2str(ret));
128         goto fail;
129     }
130
131     av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
132            fd, cap.capabilities);
133
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);
137         goto fail;
138     }
139
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);
144         goto fail;
145     }
146
147     return fd;
148
149 fail:
150     v4l2_close(fd);
151     return ret;
152 }
153
154 static int device_init(AVFormatContext *ctx, int *width, int *height,
155                        uint32_t pix_fmt)
156 {
157     struct video_data *s = ctx->priv_data;
158     int fd = s->fd;
159     struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
160     struct v4l2_pix_format *pix = &fmt.fmt.pix;
161
162     int res = 0;
163
164     pix->width = *width;
165     pix->height = *height;
166     pix->pixelformat = pix_fmt;
167     pix->field = V4L2_FIELD_ANY;
168
169     if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
170         res = AVERROR(errno);
171
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;
178     }
179
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);
186     }
187
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");
191         s->interlaced = 1;
192     }
193
194     return res;
195 }
196
197 static int first_field(int fd)
198 {
199     int res;
200     v4l2_std_id std;
201
202     res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
203     if (res < 0) {
204         return 0;
205     }
206     if (std & V4L2_STD_NTSC) {
207         return 0;
208     }
209
210     return 1;
211 }
212
213 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
214 static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
215 {
216     struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
217
218     while(!v4l2_ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
219         switch (vfse.type) {
220         case V4L2_FRMSIZE_TYPE_DISCRETE:
221             av_log(ctx, AV_LOG_INFO, " %ux%u",
222                    vfse.discrete.width, vfse.discrete.height);
223         break;
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);
233         }
234         vfse.index++;
235     }
236 }
237 #endif
238
239 static void list_formats(AVFormatContext *ctx, int fd, int type)
240 {
241     struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
242
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);
246
247         vfd.index++;
248
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",
254                    vfd.description);
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",
260                    vfd.description);
261         } else {
262             continue;
263         }
264
265 #ifdef V4L2_FMT_FLAG_EMULATED
266         if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
267             av_log(ctx, AV_LOG_INFO, " Emulated :");
268 #endif
269 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
270         list_framesizes(ctx, fd, vfd.pixelformat);
271 #endif
272         av_log(ctx, AV_LOG_INFO, "\n");
273     }
274 }
275
276 static void list_standards(AVFormatContext *ctx)
277 {
278     int ret;
279     struct video_data *s = ctx->priv_data;
280     struct v4l2_standard standard;
281
282     if (s->std_id == 0)
283         return;
284
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)) {
289                 break;
290             } else {
291                 av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
292                 return;
293             }
294         }
295         av_log(ctx, AV_LOG_INFO, "%2d, %16llx, %s\n",
296                standard.index, standard.id, standard.name);
297     }
298 }
299
300 static int mmap_init(AVFormatContext *ctx)
301 {
302     int i, res;
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
308     };
309
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));
313         return res;
314     }
315
316     if (req.count < 2) {
317         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
318         return AVERROR(ENOMEM);
319     }
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);
325     }
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);
331     }
332
333     for (i = 0; i < req.count; i++) {
334         struct v4l2_buffer buf = {
335             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
336             .index  = i,
337             .memory = V4L2_MEMORY_MMAP
338         };
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));
342             return res;
343         }
344
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);
351         }
352         s->buf_start[i] = v4l2_mmap(NULL, buf.length,
353                                PROT_READ | PROT_WRITE, MAP_SHARED,
354                                s->fd, buf.m.offset);
355
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));
359             return res;
360         }
361     }
362
363     return 0;
364 }
365
366 #if FF_API_DESTRUCT_PACKET
367 static void dummy_release_buffer(AVPacket *pkt)
368 {
369     av_assert0(0);
370 }
371 #endif
372
373 static void mmap_release_buffer(void *opaque, uint8_t *data)
374 {
375     struct v4l2_buffer buf = { 0 };
376     int res;
377     struct buff_data *buf_descriptor = opaque;
378     struct video_data *s = buf_descriptor->s;
379
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);
384
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",
388                av_err2str(res));
389     }
390
391     avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
392 }
393
394 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
395 static int64_t av_gettime_monotonic(void)
396 {
397     struct timespec tv;
398
399     clock_gettime(CLOCK_MONOTONIC, &tv);
400     return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
401 }
402 #endif
403
404 static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
405 {
406     struct video_data *s = ctx->priv_data;
407     int64_t now;
408
409     now = av_gettime();
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;
414         return 0;
415     }
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;
426         return 0;
427     }
428 #endif
429     av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
430     return AVERROR(EIO);
431 }
432
433 static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
434 {
435     struct video_data *s = ctx->priv_data;
436
437     if (s->ts_mode) {
438         int r = init_convert_timestamp(ctx, *ts);
439         if (r < 0)
440             return r;
441     }
442 #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
443     if (s->timefilter) {
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);
449     }
450 #endif
451     return 0;
452 }
453
454 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
455 {
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
460     };
461     int res;
462
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));
465     if (res < 0) {
466         if (errno == EAGAIN) {
467             pkt->size = 0;
468             return AVERROR(EAGAIN);
469         }
470         res = AVERROR(errno);
471         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
472         return res;
473     }
474
475     if (buf.index >= s->buffers) {
476         av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
477         return AVERROR(EINVAL);
478     }
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);
482
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.
485      */
486     if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
487         s->frame_size = buf.bytesused;
488
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;
494     }
495
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);
500         if (res < 0) {
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);
504             return res;
505         }
506         memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
507
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));
511             av_free_packet(pkt);
512             return res;
513         }
514         avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
515     } else {
516         struct buff_data *buf_descriptor;
517
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;
522 #endif
523
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
528              */
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);
532
533             return AVERROR(ENOMEM);
534         }
535         buf_descriptor->index = buf.index;
536         buf_descriptor->s     = s;
537
538         pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
539                                     buf_descriptor, 0);
540         if (!pkt->buf) {
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);
546         }
547     }
548     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
549     convert_timestamp(ctx, &pkt->pts);
550
551     return s->buf_len[buf.index];
552 }
553
554 static int mmap_start(AVFormatContext *ctx)
555 {
556     struct video_data *s = ctx->priv_data;
557     enum v4l2_buf_type type;
558     int i, res;
559
560     for (i = 0; i < s->buffers; i++) {
561         struct v4l2_buffer buf = {
562             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
563             .index  = i,
564             .memory = V4L2_MEMORY_MMAP
565         };
566
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));
570             return res;
571         }
572     }
573     s->buffers_queued = s->buffers;
574
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));
579         return res;
580     }
581
582     return 0;
583 }
584
585 static void mmap_close(struct video_data *s)
586 {
587     enum v4l2_buf_type type;
588     int i;
589
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...
593      */
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]);
597     }
598     av_free(s->buf_start);
599     av_free(s->buf_len);
600 }
601
602 static int v4l2_set_parameters(AVFormatContext *s1)
603 {
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 };
609     int i, ret;
610
611     if (s->framerate &&
612         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
613         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
614                s->framerate);
615         return ret;
616     }
617
618     if (s->standard) {
619         if (s->std_id) {
620             ret = 0;
621             av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
622             /* set tv standard */
623             for (i = 0; ; i++) {
624                 standard.index = i;
625                 if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
626                     ret = AVERROR(errno);
627                     break;
628                 }
629                 if (!av_strcasecmp(standard.name, s->standard))
630                     break;
631             }
632             if (ret < 0) {
633                 av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
634                 return ret;
635             }
636
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));
640                 return ret;
641             }
642         } else {
643             av_log(s1, AV_LOG_WARNING,
644                    "This device does not support any standard\n");
645         }
646     }
647
648     /* get standard */
649     if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
650         tpf = &standard.frameperiod;
651         for (i = 0; ; i++) {
652             standard.index = i;
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));
656                 return ret;
657             }
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);
662                 break;
663             }
664         }
665     } else {
666         tpf = &streamparm.parm.capture.timeperframe;
667     }
668
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));
673         return ret;
674     }
675
676     if (framerate_q.num && framerate_q.den) {
677         if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
678             tpf = &streamparm.parm.capture.timeperframe;
679
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;
684
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));
688                 return ret;
689             }
690
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 "
695                        "%d/%d to %d/%d\n",
696                        framerate_q.den, framerate_q.num,
697                        tpf->numerator, tpf->denominator);
698             }
699         } else {
700             av_log(s1, AV_LOG_WARNING,
701                    "The driver does not allow to change time per frame\n");
702         }
703     }
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;
707
708     return 0;
709 }
710
711 static int device_try_init(AVFormatContext *s1,
712                            enum AVPixelFormat pix_fmt,
713                            int *width,
714                            int *height,
715                            uint32_t *desired_format,
716                            enum AVCodecID *codec_id)
717 {
718     int ret, i;
719
720     *desired_format = avpriv_fmt_ff2v4l(pix_fmt, s1->video_codec_id);
721
722     if (*desired_format) {
723         ret = device_init(s1, width, height, *desired_format);
724         if (ret < 0) {
725             *desired_format = 0;
726             if (ret != AVERROR(EINVAL))
727                 return ret;
728         }
729     }
730
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"));
738
739                 *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;
740                 ret = device_init(s1, width, height, *desired_format);
741                 if (ret >= 0)
742                     break;
743                 else if (ret != AVERROR(EINVAL))
744                     return ret;
745                 *desired_format = 0;
746             }
747         }
748
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);
755         }
756     }
757
758     *codec_id = avpriv_fmt_v4l2codec(*desired_format);
759     av_assert0(*codec_id != AV_CODEC_ID_NONE);
760     return ret;
761 }
762
763 static int v4l2_read_header(AVFormatContext *s1)
764 {
765     struct video_data *s = s1->priv_data;
766     AVStream *st;
767     int res = 0;
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 };
772
773     st = avformat_new_stream(s1, NULL);
774     if (!st)
775         return AVERROR(ENOMEM);
776
777 #if CONFIG_LIBV4L2
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");
781 #endif
782
783     s->fd = device_open(s1);
784     if (s->fd < 0)
785         return s->fd;
786
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));
793             return res;
794         }
795     } else {
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));
800             return res;
801         }
802     }
803
804     /* enum input */
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));
809         return res;
810     }
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);
814
815     if (s->list_format) {
816         list_formats(s1, s->fd, s->list_format);
817         return AVERROR_EXIT;
818     }
819
820     if (s->list_standard) {
821         list_standards(s1);
822         return AVERROR_EXIT;
823     }
824
825     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
826
827     if (s->pixel_format) {
828         AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
829
830         if (codec)
831             s1->video_codec_id = codec->id;
832
833         pix_fmt = av_get_pix_fmt(s->pixel_format);
834
835         if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
836             av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
837                    s->pixel_format);
838
839             return AVERROR(EINVAL);
840         }
841     }
842
843     if (!s->width && !s->height) {
844         struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
845
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));
851             return res;
852         }
853
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);
858     }
859
860     res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
861     if (res < 0) {
862         v4l2_close(s->fd);
863         return res;
864     }
865
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
869      */
870     if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
871         s1->video_codec_id = codec_id;
872
873     if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
874         return res;
875
876     s->frame_format = desired_format;
877
878     if ((res = v4l2_set_parameters(s1)) < 0)
879         return res;
880
881     st->codec->pix_fmt = avpriv_fmt_v4l2ff(desired_format, codec_id);
882     s->frame_size =
883         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
884
885     if ((res = mmap_init(s1)) ||
886         (res = mmap_start(s1)) < 0) {
887         v4l2_close(s->fd);
888         return res;
889     }
890
891     s->top_field_first = first_field(s->fd);
892
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;
905
906     return 0;
907 }
908
909 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
910 {
911     struct video_data *s = s1->priv_data;
912     AVFrame *frame = s1->streams[0]->codec->coded_frame;
913     int res;
914
915     av_init_packet(pkt);
916     if ((res = mmap_read_frame(s1, pkt)) < 0) {
917         return res;
918     }
919
920     if (frame && s->interlaced) {
921         frame->interlaced_frame = 1;
922         frame->top_field_first = s->top_field_first;
923     }
924
925     return pkt->size;
926 }
927
928 static int v4l2_read_close(AVFormatContext *s1)
929 {
930     struct video_data *s = s1->priv_data;
931
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 "
934                "close.\n");
935
936     mmap_close(s);
937
938     v4l2_close(s->fd);
939     return 0;
940 }
941
942 #define OFFSET(x) offsetof(struct video_data, x)
943 #define DEC AV_OPT_FLAG_DECODING_PARAM
944
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 },
952
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" },
957
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" },
960
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" },
966
967     { NULL },
968 };
969
970 static const AVClass v4l2_class = {
971     .class_name = "V4L2 indev",
972     .item_name  = av_default_item_name,
973     .option     = options,
974     .version    = LIBAVUTIL_VERSION_INT,
975 };
976
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,
986 };