]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
Merge remote-tracking branch 'qatar/master'
[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://v4l2spec.bytesex.org/v4l2spec/capture.c)
28  *
29  * Thanks to Michael Niedermayer for providing the mapping between
30  * V4L2_PIX_FMT_* and PIX_FMT_*
31  */
32
33 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
34 #include "config.h"
35 #include "libavformat/internal.h"
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/time.h>
41 #include <poll.h>
42 #if HAVE_SYS_VIDEOIO_H
43 #include <sys/videoio.h>
44 #else
45 #if HAVE_ASM_TYPES_H
46 #include <asm/types.h>
47 #endif
48 #include <linux/videodev2.h>
49 #endif
50 #include <time.h>
51 #include "libavutil/imgutils.h"
52 #include "libavutil/log.h"
53 #include "libavutil/opt.h"
54 #include "avdevice.h"
55 #include "libavutil/parseutils.h"
56 #include "libavutil/pixdesc.h"
57 #include "libavutil/avstring.h"
58 #include "libavutil/mathematics.h"
59
60 #if CONFIG_LIBV4L2
61 #include <libv4l2.h>
62 #else
63 #define v4l2_open   open
64 #define v4l2_close  close
65 #define v4l2_dup    dup
66 #define v4l2_ioctl  ioctl
67 #define v4l2_read   read
68 #define v4l2_mmap   mmap
69 #define v4l2_munmap munmap
70 #endif
71
72 static const int desired_video_buffers = 256;
73
74 #define V4L_ALLFORMATS  3
75 #define V4L_RAWFORMATS  1
76 #define V4L_COMPFORMATS 2
77
78 struct video_data {
79     AVClass *class;
80     int fd;
81     int frame_format; /* V4L2_PIX_FMT_* */
82     int width, height;
83     int frame_size;
84     int timeout;
85     int interlaced;
86     int top_field_first;
87
88     int buffers;
89     void **buf_start;
90     unsigned int *buf_len;
91     char *standard;
92     int channel;
93     char *video_size;   /**< String describing video size,
94                              set by a private option. */
95     char *pixel_format; /**< Set by a private option. */
96     int list_format;    /**< Set by a private option. */
97     char *framerate;    /**< Set by a private option. */
98 };
99
100 struct buff_data {
101     int index;
102     int fd;
103 };
104
105 struct fmt_map {
106     enum PixelFormat ff_fmt;
107     enum CodecID codec_id;
108     uint32_t v4l2_fmt;
109 };
110
111 static struct fmt_map fmt_conversion_table[] = {
112     //ff_fmt           codec_id           v4l2_fmt
113     { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
114     { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
115     { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
116     { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
117     { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
118     { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
119     { PIX_FMT_RGB555,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
120     { PIX_FMT_RGB565,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
121     { PIX_FMT_BGR24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
122     { PIX_FMT_RGB24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
123     { PIX_FMT_BGRA,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
124     { PIX_FMT_GRAY8,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
125     { PIX_FMT_NV12,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
126     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
127     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
128 };
129
130 static int device_open(AVFormatContext *ctx)
131 {
132     struct v4l2_capability cap;
133     int fd;
134 #if CONFIG_LIBV4L2
135     int fd_libv4l;
136 #endif
137     int res, err;
138     int flags = O_RDWR;
139
140     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
141         flags |= O_NONBLOCK;
142     }
143
144     fd = v4l2_open(ctx->filename, flags, 0);
145     if (fd < 0) {
146         err = errno;
147
148         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
149                ctx->filename, strerror(err));
150
151         return AVERROR(err);
152     }
153 #if CONFIG_LIBV4L2
154     fd_libv4l = v4l2_fd_open(fd, 0);
155     if (fd < 0) {
156         err = AVERROR(errno);
157         av_log(ctx, AV_LOG_ERROR, "Cannot open video device with libv4l neither %s : %s\n",
158                ctx->filename, strerror(errno));
159         return err;
160     }
161     fd = fd_libv4l;
162 #endif
163
164     res = v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap);
165     if (res < 0) {
166         err = errno;
167         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
168                strerror(err));
169
170         goto fail;
171     }
172
173     av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",
174            fd, cap.capabilities);
175
176     if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
177         av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
178         err = ENODEV;
179
180         goto fail;
181     }
182
183     if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
184         av_log(ctx, AV_LOG_ERROR,
185                "The device does not support the streaming I/O method.\n");
186         err = ENOSYS;
187
188         goto fail;
189     }
190
191     return fd;
192
193 fail:
194     v4l2_close(fd);
195     return AVERROR(err);
196 }
197
198 static int device_init(AVFormatContext *ctx, int *width, int *height,
199                        uint32_t pix_fmt)
200 {
201     struct video_data *s = ctx->priv_data;
202     int fd = s->fd;
203     struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
204     struct v4l2_pix_format *pix = &fmt.fmt.pix;
205
206     int res;
207
208     pix->width = *width;
209     pix->height = *height;
210     pix->pixelformat = pix_fmt;
211     pix->field = V4L2_FIELD_ANY;
212
213     res = v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt);
214
215     if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
216         av_log(ctx, AV_LOG_INFO,
217                "The V4L2 driver changed the video from %dx%d to %dx%d\n",
218                *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
219         *width = fmt.fmt.pix.width;
220         *height = fmt.fmt.pix.height;
221     }
222
223     if (pix_fmt != fmt.fmt.pix.pixelformat) {
224         av_log(ctx, AV_LOG_DEBUG,
225                "The V4L2 driver changed the pixel format "
226                "from 0x%08X to 0x%08X\n",
227                pix_fmt, fmt.fmt.pix.pixelformat);
228         res = -1;
229     }
230
231     if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
232         av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
233         s->interlaced = 1;
234     }
235
236     return res;
237 }
238
239 static int first_field(int fd)
240 {
241     int res;
242     v4l2_std_id std;
243
244     res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
245     if (res < 0) {
246         return 0;
247     }
248     if (std & V4L2_STD_NTSC) {
249         return 0;
250     }
251
252     return 1;
253 }
254
255 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
256 {
257     int i;
258
259     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
260         if ((codec_id == CODEC_ID_NONE ||
261              fmt_conversion_table[i].codec_id == codec_id) &&
262             (pix_fmt == PIX_FMT_NONE ||
263              fmt_conversion_table[i].ff_fmt == pix_fmt)) {
264             return fmt_conversion_table[i].v4l2_fmt;
265         }
266     }
267
268     return 0;
269 }
270
271 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
272 {
273     int i;
274
275     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
276         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
277             fmt_conversion_table[i].codec_id == codec_id) {
278             return fmt_conversion_table[i].ff_fmt;
279         }
280     }
281
282     return PIX_FMT_NONE;
283 }
284
285 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
286 {
287     int i;
288
289     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
290         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
291             return fmt_conversion_table[i].codec_id;
292         }
293     }
294
295     return CODEC_ID_NONE;
296 }
297
298 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
299 static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
300 {
301     struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
302
303     while(!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
304         switch (vfse.type) {
305         case V4L2_FRMSIZE_TYPE_DISCRETE:
306             av_log(ctx, AV_LOG_INFO, " %ux%u",
307                    vfse.discrete.width, vfse.discrete.height);
308         break;
309         case V4L2_FRMSIZE_TYPE_CONTINUOUS:
310         case V4L2_FRMSIZE_TYPE_STEPWISE:
311             av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
312                    vfse.stepwise.min_width,
313                    vfse.stepwise.max_width,
314                    vfse.stepwise.step_width,
315                    vfse.stepwise.min_height,
316                    vfse.stepwise.max_height,
317                    vfse.stepwise.step_height);
318         }
319         vfse.index++;
320     }
321 }
322 #endif
323
324 static void list_formats(AVFormatContext *ctx, int fd, int type)
325 {
326     struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
327
328     while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
329         enum CodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
330         enum PixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
331
332         vfd.index++;
333
334         if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
335             type & V4L_RAWFORMATS) {
336             const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
337             av_log(ctx, AV_LOG_INFO, "R : %9s : %20s :",
338                    fmt_name ? fmt_name : "Unsupported",
339                    vfd.description);
340         } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
341                    type & V4L_COMPFORMATS) {
342             AVCodec *codec = avcodec_find_encoder(codec_id);
343             av_log(ctx, AV_LOG_INFO, "C : %9s : %20s :",
344                    codec ? codec->name : "Unsupported",
345                    vfd.description);
346         } else {
347             continue;
348         }
349
350 #ifdef V4L2_FMT_FLAG_EMULATED
351         if (vfd.flags & V4L2_FMT_FLAG_EMULATED) {
352             av_log(ctx, AV_LOG_WARNING, "%s", "Emulated");
353             continue;
354         }
355 #endif
356 #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
357         list_framesizes(ctx, fd, vfd.pixelformat);
358 #endif
359         av_log(ctx, AV_LOG_INFO, "\n");
360     }
361 }
362
363 static int mmap_init(AVFormatContext *ctx)
364 {
365     int i, res;
366     struct video_data *s = ctx->priv_data;
367     struct v4l2_requestbuffers req = {
368         .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
369         .count  = desired_video_buffers,
370         .memory = V4L2_MEMORY_MMAP
371     };
372
373     res = v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req);
374     if (res < 0) {
375         if (errno == EINVAL) {
376             av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
377         } else {
378             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
379         }
380         return AVERROR(errno);
381     }
382
383     if (req.count < 2) {
384         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
385         return AVERROR(ENOMEM);
386     }
387     s->buffers = req.count;
388     s->buf_start = av_malloc(sizeof(void *) * s->buffers);
389     if (s->buf_start == NULL) {
390         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
391         return AVERROR(ENOMEM);
392     }
393     s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
394     if (s->buf_len == NULL) {
395         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
396         av_free(s->buf_start);
397         return AVERROR(ENOMEM);
398     }
399
400     for (i = 0; i < req.count; i++) {
401         struct v4l2_buffer buf = {
402             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
403             .index  = i,
404             .memory = V4L2_MEMORY_MMAP
405         };
406         res = v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
407         if (res < 0) {
408             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
409             return AVERROR(errno);
410         }
411
412         s->buf_len[i] = buf.length;
413         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
414             av_log(ctx, AV_LOG_ERROR,
415                    "Buffer len [%d] = %d != %d\n",
416                    i, s->buf_len[i], s->frame_size);
417
418             return -1;
419         }
420         s->buf_start[i] = v4l2_mmap(NULL, buf.length,
421                                PROT_READ | PROT_WRITE, MAP_SHARED,
422                                s->fd, buf.m.offset);
423
424         if (s->buf_start[i] == MAP_FAILED) {
425             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
426             return AVERROR(errno);
427         }
428     }
429
430     return 0;
431 }
432
433 static void mmap_release_buffer(AVPacket *pkt)
434 {
435     struct v4l2_buffer buf = { 0 };
436     int res, fd;
437     struct buff_data *buf_descriptor = pkt->priv;
438
439     if (pkt->data == NULL)
440         return;
441
442     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
443     buf.memory = V4L2_MEMORY_MMAP;
444     buf.index = buf_descriptor->index;
445     fd = buf_descriptor->fd;
446     av_free(buf_descriptor);
447
448     res = v4l2_ioctl(fd, VIDIOC_QBUF, &buf);
449     if (res < 0)
450         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
451                strerror(errno));
452
453     pkt->data = NULL;
454     pkt->size = 0;
455 }
456
457 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
458 {
459     struct video_data *s = ctx->priv_data;
460     struct v4l2_buffer buf = {
461         .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
462         .memory = V4L2_MEMORY_MMAP
463     };
464     struct buff_data *buf_descriptor;
465     struct pollfd p = { .fd = s->fd, .events = POLLIN };
466     int res;
467
468     res = poll(&p, 1, s->timeout);
469     if (res < 0)
470         return AVERROR(errno);
471
472     if (!(p.revents & (POLLIN | POLLERR | POLLHUP)))
473         return AVERROR(EAGAIN);
474
475     /* FIXME: Some special treatment might be needed in case of loss of signal... */
476     while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
477     if (res < 0) {
478         if (errno == EAGAIN) {
479             pkt->size = 0;
480             return AVERROR(EAGAIN);
481         }
482         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
483                strerror(errno));
484
485         return AVERROR(errno);
486     }
487     assert(buf.index < s->buffers);
488     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
489         av_log(ctx, AV_LOG_ERROR,
490                "The v4l2 frame is %d bytes, but %d bytes are expected\n",
491                buf.bytesused, s->frame_size);
492
493         return AVERROR_INVALIDDATA;
494     }
495
496     /* Image is at s->buff_start[buf.index] */
497     pkt->data= s->buf_start[buf.index];
498     pkt->size = buf.bytesused;
499     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
500     pkt->destruct = mmap_release_buffer;
501     buf_descriptor = av_malloc(sizeof(struct buff_data));
502     if (buf_descriptor == NULL) {
503         /* Something went wrong... Since av_malloc() failed, we cannot even
504          * allocate a buffer for memcopying into it
505          */
506         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
507         res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
508
509         return AVERROR(ENOMEM);
510     }
511     buf_descriptor->fd = s->fd;
512     buf_descriptor->index = buf.index;
513     pkt->priv = buf_descriptor;
514
515     return s->buf_len[buf.index];
516 }
517
518 static int mmap_start(AVFormatContext *ctx)
519 {
520     struct video_data *s = ctx->priv_data;
521     enum v4l2_buf_type type;
522     int i, res;
523
524     for (i = 0; i < s->buffers; i++) {
525         struct v4l2_buffer buf = {
526             .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
527             .index  = i,
528             .memory = V4L2_MEMORY_MMAP
529         };
530
531         res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
532         if (res < 0) {
533             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
534                    strerror(errno));
535
536             return AVERROR(errno);
537         }
538     }
539
540     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
541     res = v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type);
542     if (res < 0) {
543         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
544                strerror(errno));
545
546         return AVERROR(errno);
547     }
548
549     return 0;
550 }
551
552 static void mmap_close(struct video_data *s)
553 {
554     enum v4l2_buf_type type;
555     int i;
556
557     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
558     /* We do not check for the result, because we could
559      * not do anything about it anyway...
560      */
561     v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
562     for (i = 0; i < s->buffers; i++) {
563         v4l2_munmap(s->buf_start[i], s->buf_len[i]);
564     }
565     av_free(s->buf_start);
566     av_free(s->buf_len);
567 }
568
569 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
570 {
571     struct video_data *s = s1->priv_data;
572     struct v4l2_input input = { 0 };
573     struct v4l2_standard standard = { 0 };
574     struct v4l2_streamparm streamparm = { 0 };
575     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
576     AVRational framerate_q = { 0 };
577     int i, ret;
578
579     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
580
581     if (s->framerate &&
582         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
583         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
584                s->framerate);
585         return ret;
586     }
587
588     /* set tv video input */
589     input.index = s->channel;
590     if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
591         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
592         return AVERROR(EIO);
593     }
594
595     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
596             s->channel, input.name);
597     if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
598         av_log(s1, AV_LOG_ERROR,
599                "The V4L2 driver ioctl set input(%d) failed\n",
600                 s->channel);
601         return AVERROR(EIO);
602     }
603
604     if (s->standard) {
605         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
606                s->standard);
607         /* set tv standard */
608         for(i=0;;i++) {
609             standard.index = i;
610             ret = v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard);
611             if (ret < 0 || !av_strcasecmp(standard.name, s->standard))
612                 break;
613         }
614         if (ret < 0) {
615             av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);
616             return ret;
617         }
618
619         av_log(s1, AV_LOG_DEBUG,
620                "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
621                s->standard, (uint64_t)standard.id);
622         if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
623             av_log(s1, AV_LOG_ERROR,
624                    "The V4L2 driver ioctl set standard(%s) failed\n",
625                    s->standard);
626             return AVERROR(EIO);
627         }
628     }
629
630     if (framerate_q.num && framerate_q.den) {
631         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
632                framerate_q.den, framerate_q.num);
633         tpf->numerator   = framerate_q.den;
634         tpf->denominator = framerate_q.num;
635
636         if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
637             av_log(s1, AV_LOG_ERROR,
638                    "ioctl set time per frame(%d/%d) failed\n",
639                    framerate_q.den, framerate_q.num);
640             return AVERROR(EIO);
641         }
642
643         if (framerate_q.num != tpf->denominator ||
644             framerate_q.den != tpf->numerator) {
645             av_log(s1, AV_LOG_INFO,
646                    "The driver changed the time per frame from "
647                    "%d/%d to %d/%d\n",
648                    framerate_q.den, framerate_q.num,
649                    tpf->numerator, tpf->denominator);
650         }
651     } else {
652         if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
653             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
654                    strerror(errno));
655             return AVERROR(errno);
656         }
657     }
658     s1->streams[0]->codec->time_base.den = tpf->denominator;
659     s1->streams[0]->codec->time_base.num = tpf->numerator;
660
661     s->timeout = 100 +
662         av_rescale_q(1, s1->streams[0]->codec->time_base,
663                         (AVRational){1, 1000});
664
665     return 0;
666 }
667
668 static uint32_t device_try_init(AVFormatContext *s1,
669                                 enum PixelFormat pix_fmt,
670                                 int *width,
671                                 int *height,
672                                 enum CodecID *codec_id)
673 {
674     uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
675
676     if (desired_format == 0 ||
677         device_init(s1, width, height, desired_format) < 0) {
678         int i;
679
680         desired_format = 0;
681         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
682             if (s1->video_codec_id == CODEC_ID_NONE ||
683                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
684                 desired_format = fmt_conversion_table[i].v4l2_fmt;
685                 if (device_init(s1, width, height, desired_format) >= 0) {
686                     break;
687                 }
688                 desired_format = 0;
689             }
690         }
691     }
692
693     if (desired_format != 0) {
694         *codec_id = fmt_v4l2codec(desired_format);
695         assert(*codec_id != CODEC_ID_NONE);
696     }
697
698     return desired_format;
699 }
700
701 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
702 {
703     struct video_data *s = s1->priv_data;
704     AVStream *st;
705     int res = 0;
706     uint32_t desired_format;
707     enum CodecID codec_id;
708     enum PixelFormat pix_fmt = PIX_FMT_NONE;
709
710     st = avformat_new_stream(s1, NULL);
711     if (!st) {
712         res = AVERROR(ENOMEM);
713         goto out;
714     }
715
716     s->fd = device_open(s1);
717     if (s->fd < 0) {
718         res = s->fd;
719         goto out;
720     }
721
722     if (s->list_format) {
723         list_formats(s1, s->fd, s->list_format);
724         res = AVERROR_EXIT;
725         goto out;
726     }
727
728     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
729
730     if (s->video_size &&
731         (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
732         av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
733                s->video_size);
734         goto out;
735     }
736
737     if (s->pixel_format) {
738         AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
739
740         if (codec)
741             s1->video_codec_id = codec->id;
742
743         pix_fmt = av_get_pix_fmt(s->pixel_format);
744
745         if (pix_fmt == PIX_FMT_NONE && !codec) {
746             av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
747                    s->pixel_format);
748
749             res = AVERROR(EINVAL);
750             goto out;
751         }
752     }
753
754     if (!s->width && !s->height) {
755         struct v4l2_format fmt;
756
757         av_log(s1, AV_LOG_VERBOSE,
758                "Querying the device for the current frame size\n");
759         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
760         if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
761             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
762                    strerror(errno));
763             res = AVERROR(errno);
764             goto out;
765         }
766
767         s->width  = fmt.fmt.pix.width;
768         s->height = fmt.fmt.pix.height;
769         av_log(s1, AV_LOG_VERBOSE,
770                "Setting frame size to %dx%d\n", s->width, s->height);
771     }
772
773     desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
774                                      &codec_id);
775     if (desired_format == 0) {
776         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
777                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
778         v4l2_close(s->fd);
779
780         res = AVERROR(EIO);
781         goto out;
782     }
783     if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
784         goto out;
785
786     s->frame_format = desired_format;
787
788     if ((res = v4l2_set_parameters(s1, ap)) < 0)
789         goto out;
790
791     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
792     s->frame_size =
793         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
794
795     if ((res = mmap_init(s1)) ||
796         (res = mmap_start(s1)) < 0) {
797         v4l2_close(s->fd);
798         goto out;
799     }
800
801     s->top_field_first = first_field(s->fd);
802
803     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
804     st->codec->codec_id = codec_id;
805     if (codec_id == CODEC_ID_RAWVIDEO)
806         st->codec->codec_tag =
807             avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
808     st->codec->width = s->width;
809     st->codec->height = s->height;
810     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
811
812 out:
813     return res;
814 }
815
816 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
817 {
818     struct video_data *s = s1->priv_data;
819     AVFrame *frame = s1->streams[0]->codec->coded_frame;
820     int res;
821
822     av_init_packet(pkt);
823     if ((res = mmap_read_frame(s1, pkt)) < 0) {
824         return res;
825     }
826
827     if (frame && s->interlaced) {
828         frame->interlaced_frame = 1;
829         frame->top_field_first = s->top_field_first;
830     }
831
832     return pkt->size;
833 }
834
835 static int v4l2_read_close(AVFormatContext *s1)
836 {
837     struct video_data *s = s1->priv_data;
838
839     mmap_close(s);
840
841     v4l2_close(s->fd);
842     return 0;
843 }
844
845 #define OFFSET(x) offsetof(struct video_data, x)
846 #define DEC AV_OPT_FLAG_DECODING_PARAM
847
848 static const AVOption options[] = {
849     { "standard",     "TV standard, used only by analog frame grabber",            OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
850     { "channel",      "TV channel, used only by frame grabber",                    OFFSET(channel),      AV_OPT_TYPE_INT,    {.dbl = 0 },    0, INT_MAX, DEC },
851     { "video_size",   "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
852     { "pixel_format", "Preferred pixel format",                                    OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
853     { "input_format", "Preferred pixel format (for raw video) or codec name",      OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
854     { "framerate",    "",                                                          OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
855     { "list_formats", "List available formats and exit",                           OFFSET(list_format),  AV_OPT_TYPE_INT,    {.dbl = 0 },  0, INT_MAX, DEC, "list_formats" },
856     { "all",          "Show all available formats",                                OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_ALLFORMATS  },    0, INT_MAX, DEC, "list_formats" },
857     { "raw",          "Show only non-compressed formats",                          OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_RAWFORMATS  },    0, INT_MAX, DEC, "list_formats" },
858     { "compressed",   "Show only compressed formats",                              OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_COMPFORMATS },    0, INT_MAX, DEC, "list_formats" },
859     { NULL },
860 };
861
862 static const AVClass v4l2_class = {
863     .class_name = "V4L2 indev",
864     .item_name  = av_default_item_name,
865     .option     = options,
866     .version    = LIBAVUTIL_VERSION_INT,
867 };
868
869 AVInputFormat ff_v4l2_demuxer = {
870     .name           = "video4linux2,v4l2",
871     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
872     .priv_data_size = sizeof(struct video_data),
873     .read_header    = v4l2_read_header,
874     .read_packet    = v4l2_read_packet,
875     .read_close     = v4l2_read_close,
876     .flags          = AVFMT_NOFILE,
877     .priv_class     = &v4l2_class,
878 };