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