]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
0b00abbf108c14c9d3a639526ea60a3ef8e1dea2
[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;
201     struct v4l2_pix_format *pix = &fmt.fmt.pix;
202
203     int res;
204
205     memset(&fmt, 0, sizeof(struct v4l2_format));
206
207     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
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     struct video_data *s = ctx->priv_data;
366     struct v4l2_requestbuffers req = {0};
367     int i, res;
368
369     req.count = desired_video_buffers;
370     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
371     req.memory = V4L2_MEMORY_MMAP;
372     res = v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req);
373     if (res < 0) {
374         if (errno == EINVAL) {
375             av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
376         } else {
377             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
378         }
379         return AVERROR(errno);
380     }
381
382     if (req.count < 2) {
383         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
384         return AVERROR(ENOMEM);
385     }
386     s->buffers = req.count;
387     s->buf_start = av_malloc(sizeof(void *) * s->buffers);
388     if (s->buf_start == NULL) {
389         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
390         return AVERROR(ENOMEM);
391     }
392     s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
393     if (s->buf_len == NULL) {
394         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
395         av_free(s->buf_start);
396         return AVERROR(ENOMEM);
397     }
398
399     for (i = 0; i < req.count; i++) {
400         struct v4l2_buffer buf = {0};
401
402         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
403         buf.memory = V4L2_MEMORY_MMAP;
404         buf.index = i;
405         res = v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
406         if (res < 0) {
407             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
408             return AVERROR(errno);
409         }
410
411         s->buf_len[i] = buf.length;
412         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
413             av_log(ctx, AV_LOG_ERROR,
414                    "Buffer len [%d] = %d != %d\n",
415                    i, s->buf_len[i], s->frame_size);
416
417             return -1;
418         }
419         s->buf_start[i] = v4l2_mmap(NULL, buf.length,
420                                PROT_READ | PROT_WRITE, MAP_SHARED,
421                                s->fd, buf.m.offset);
422
423         if (s->buf_start[i] == MAP_FAILED) {
424             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
425             return AVERROR(errno);
426         }
427     }
428
429     return 0;
430 }
431
432 static void mmap_release_buffer(AVPacket *pkt)
433 {
434     struct v4l2_buffer buf = {0};
435     int res, fd;
436     struct buff_data *buf_descriptor = pkt->priv;
437
438     if (pkt->data == NULL)
439         return;
440
441     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
442     buf.memory = V4L2_MEMORY_MMAP;
443     buf.index = buf_descriptor->index;
444     fd = buf_descriptor->fd;
445     av_free(buf_descriptor);
446
447     res = v4l2_ioctl(fd, VIDIOC_QBUF, &buf);
448     if (res < 0)
449         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
450                strerror(errno));
451
452     pkt->data = NULL;
453     pkt->size = 0;
454 }
455
456 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
457 {
458     struct video_data *s = ctx->priv_data;
459     struct v4l2_buffer buf = {0};
460     struct buff_data *buf_descriptor;
461     int res;
462
463     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
464     buf.memory = V4L2_MEMORY_MMAP;
465
466     /* FIXME: Some special treatment might be needed in case of loss of signal... */
467     while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
468     if (res < 0) {
469         if (errno == EAGAIN) {
470             pkt->size = 0;
471             return AVERROR(EAGAIN);
472         }
473         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
474                strerror(errno));
475
476         return AVERROR(errno);
477     }
478     assert(buf.index < s->buffers);
479     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
480         av_log(ctx, AV_LOG_ERROR,
481                "The v4l2 frame is %d bytes, but %d bytes are expected\n",
482                buf.bytesused, s->frame_size);
483
484         return AVERROR_INVALIDDATA;
485     }
486
487     /* Image is at s->buff_start[buf.index] */
488     pkt->data= s->buf_start[buf.index];
489     pkt->size = buf.bytesused;
490     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
491     pkt->destruct = mmap_release_buffer;
492     buf_descriptor = av_malloc(sizeof(struct buff_data));
493     if (buf_descriptor == NULL) {
494         /* Something went wrong... Since av_malloc() failed, we cannot even
495          * allocate a buffer for memcopying into it
496          */
497         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
498         res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
499
500         return AVERROR(ENOMEM);
501     }
502     buf_descriptor->fd = s->fd;
503     buf_descriptor->index = buf.index;
504     pkt->priv = buf_descriptor;
505
506     return s->buf_len[buf.index];
507 }
508
509 static int mmap_start(AVFormatContext *ctx)
510 {
511     struct video_data *s = ctx->priv_data;
512     enum v4l2_buf_type type;
513     int i, res;
514
515     for (i = 0; i < s->buffers; i++) {
516         struct v4l2_buffer buf = {0};
517
518         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
519         buf.memory = V4L2_MEMORY_MMAP;
520         buf.index  = i;
521
522         res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
523         if (res < 0) {
524             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
525                    strerror(errno));
526
527             return AVERROR(errno);
528         }
529     }
530
531     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
532     res = v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type);
533     if (res < 0) {
534         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
535                strerror(errno));
536
537         return AVERROR(errno);
538     }
539
540     return 0;
541 }
542
543 static void mmap_close(struct video_data *s)
544 {
545     enum v4l2_buf_type type;
546     int i;
547
548     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
549     /* We do not check for the result, because we could
550      * not do anything about it anyway...
551      */
552     v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
553     for (i = 0; i < s->buffers; i++) {
554         v4l2_munmap(s->buf_start[i], s->buf_len[i]);
555     }
556     av_free(s->buf_start);
557     av_free(s->buf_len);
558 }
559
560 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
561 {
562     struct video_data *s = s1->priv_data;
563     struct v4l2_input input = {0};
564     struct v4l2_standard standard = {0};
565     struct v4l2_streamparm streamparm = {0};
566     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
567     int i, ret;
568     AVRational framerate_q={0};
569
570     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
571
572     if (s->framerate &&
573         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
574         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
575                s->framerate);
576         return ret;
577     }
578
579     /* set tv video input */
580     input.index = s->channel;
581     if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
582         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
583         return AVERROR(EIO);
584     }
585
586     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
587             s->channel, input.name);
588     if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
589         av_log(s1, AV_LOG_ERROR,
590                "The V4L2 driver ioctl set input(%d) failed\n",
591                 s->channel);
592         return AVERROR(EIO);
593     }
594
595     if (s->standard) {
596         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
597                s->standard);
598         /* set tv standard */
599         for (i = 0;; i++) {
600             standard.index = i;
601             ret = v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard);
602             if (ret < 0 || !av_strcasecmp(standard.name, s->standard))
603                 break;
604         }
605         if (ret < 0) {
606             av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);
607             return ret;
608         }
609
610         av_log(s1, AV_LOG_DEBUG,
611                "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
612                s->standard, (uint64_t)standard.id);
613         if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
614             av_log(s1, AV_LOG_ERROR,
615                    "The V4L2 driver ioctl set standard(%s) failed\n",
616                    s->standard);
617             return AVERROR(EIO);
618         }
619     }
620
621     if (framerate_q.num && framerate_q.den) {
622         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
623                framerate_q.den, framerate_q.num);
624         tpf->numerator   = framerate_q.den;
625         tpf->denominator = framerate_q.num;
626
627         if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
628             av_log(s1, AV_LOG_ERROR,
629                    "ioctl set time per frame(%d/%d) failed\n",
630                    framerate_q.den, framerate_q.num);
631             return AVERROR(EIO);
632         }
633
634         if (framerate_q.num != tpf->denominator ||
635             framerate_q.den != tpf->numerator) {
636             av_log(s1, AV_LOG_INFO,
637                    "The driver changed the time per frame from "
638                    "%d/%d to %d/%d\n",
639                    framerate_q.den, framerate_q.num,
640                    tpf->numerator, tpf->denominator);
641         }
642     } else {
643         if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
644             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
645                    strerror(errno));
646             return AVERROR(errno);
647         }
648     }
649     s1->streams[0]->codec->time_base.den = tpf->denominator;
650     s1->streams[0]->codec->time_base.num = tpf->numerator;
651
652     return 0;
653 }
654
655 static uint32_t device_try_init(AVFormatContext *s1,
656                                 enum PixelFormat pix_fmt,
657                                 int *width,
658                                 int *height,
659                                 enum CodecID *codec_id)
660 {
661     uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
662
663     if (desired_format == 0 ||
664         device_init(s1, width, height, desired_format) < 0) {
665         int i;
666
667         desired_format = 0;
668         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
669             if (s1->video_codec_id == CODEC_ID_NONE ||
670                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
671                 desired_format = fmt_conversion_table[i].v4l2_fmt;
672                 if (device_init(s1, width, height, desired_format) >= 0) {
673                     break;
674                 }
675                 desired_format = 0;
676             }
677         }
678     }
679
680     if (desired_format != 0) {
681         *codec_id = fmt_v4l2codec(desired_format);
682         assert(*codec_id != CODEC_ID_NONE);
683     }
684
685     return desired_format;
686 }
687
688 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
689 {
690     struct video_data *s = s1->priv_data;
691     AVStream *st;
692     int res = 0;
693     uint32_t desired_format;
694     enum CodecID codec_id;
695     enum PixelFormat pix_fmt = PIX_FMT_NONE;
696
697     st = avformat_new_stream(s1, NULL);
698     if (!st) {
699         res = AVERROR(ENOMEM);
700         goto out;
701     }
702
703     s->fd = device_open(s1);
704     if (s->fd < 0) {
705         res = s->fd;
706         goto out;
707     }
708
709     if (s->list_format) {
710         list_formats(s1, s->fd, s->list_format);
711         res = AVERROR_EXIT;
712         goto out;
713     }
714
715     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
716
717     if (s->video_size &&
718         (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
719         av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
720                s->video_size);
721         goto out;
722     }
723
724     if (s->pixel_format) {
725
726         pix_fmt = av_get_pix_fmt(s->pixel_format);
727
728         if (pix_fmt == PIX_FMT_NONE) {
729             av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n",
730                    s->pixel_format);
731
732             res = AVERROR(EINVAL);
733             goto out;
734         }
735     }
736
737     if (!s->width && !s->height) {
738         struct v4l2_format fmt;
739
740         av_log(s1, AV_LOG_VERBOSE,
741                "Querying the device for the current frame size\n");
742         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
743         if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
744             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
745                    strerror(errno));
746             res = AVERROR(errno);
747             goto out;
748         }
749
750         s->width  = fmt.fmt.pix.width;
751         s->height = fmt.fmt.pix.height;
752         av_log(s1, AV_LOG_VERBOSE,
753                "Setting frame size to %dx%d\n", s->width, s->height);
754     }
755
756     desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
757                                      &codec_id);
758     if (desired_format == 0) {
759         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
760                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
761         v4l2_close(s->fd);
762
763         res = AVERROR(EIO);
764         goto out;
765     }
766     if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
767         goto out;
768
769     s->frame_format = desired_format;
770
771     if ((res = v4l2_set_parameters(s1, ap)) < 0)
772         goto out;
773
774     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
775     s->frame_size =
776         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
777
778     if ((res = mmap_init(s1)) ||
779         (res = mmap_start(s1)) < 0) {
780         v4l2_close(s->fd);
781         goto out;
782     }
783
784     s->top_field_first = first_field(s->fd);
785
786     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
787     st->codec->codec_id = codec_id;
788     if (codec_id == CODEC_ID_RAWVIDEO)
789         st->codec->codec_tag =
790             avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
791     st->codec->width = s->width;
792     st->codec->height = s->height;
793     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
794
795 out:
796     return res;
797 }
798
799 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
800 {
801     struct video_data *s = s1->priv_data;
802     AVFrame *frame = s1->streams[0]->codec->coded_frame;
803     int res;
804
805     av_init_packet(pkt);
806     if ((res = mmap_read_frame(s1, pkt)) < 0) {
807         return res;
808     }
809
810     if (frame && s->interlaced) {
811         frame->interlaced_frame = 1;
812         frame->top_field_first = s->top_field_first;
813     }
814
815     return pkt->size;
816 }
817
818 static int v4l2_read_close(AVFormatContext *s1)
819 {
820     struct video_data *s = s1->priv_data;
821
822     mmap_close(s);
823
824     v4l2_close(s->fd);
825     return 0;
826 }
827
828 #define OFFSET(x) offsetof(struct video_data, x)
829 #define DEC AV_OPT_FLAG_DECODING_PARAM
830
831 static const AVOption options[] = {
832     { "standard",     "TV standard, used only by analog frame grabber",            OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
833     { "channel",      "TV channel, used only by frame grabber",                    OFFSET(channel),      AV_OPT_TYPE_INT,    {.dbl = 0 },    0, INT_MAX, DEC },
834     { "video_size",   "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
835     { "pixel_format", "",                                                          OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
836     { "framerate",    "",                                                          OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
837     { "list_formats", "List available formats and exit",                           OFFSET(list_format),  AV_OPT_TYPE_INT,    {.dbl = 0 },  0, INT_MAX, DEC, "list_formats" },
838     { "all",          "Show all available formats",                                OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_ALLFORMATS  },    0, INT_MAX, DEC, "list_formats" },
839     { "raw",          "Show only non-compressed formats",                          OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_RAWFORMATS  },    0, INT_MAX, DEC, "list_formats" },
840     { "compressed",   "Show only compressed formats",                              OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_COMPFORMATS },    0, INT_MAX, DEC, "list_formats" },
841     { NULL },
842 };
843
844 static const AVClass v4l2_class = {
845     .class_name = "V4L2 indev",
846     .item_name  = av_default_item_name,
847     .option     = options,
848     .version    = LIBAVUTIL_VERSION_INT,
849 };
850
851 AVInputFormat ff_v4l2_demuxer = {
852     .name           = "video4linux2,v4l2",
853     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
854     .priv_data_size = sizeof(struct video_data),
855     .read_header    = v4l2_read_header,
856     .read_packet    = v4l2_read_packet,
857     .read_close     = v4l2_read_close,
858     .flags          = AVFMT_NOFILE,
859     .priv_class     = &v4l2_class,
860 };