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