]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
v4l2: cosmetics
[ffmpeg] / libavdevice / v4l2.c
1 /*
2  * Video4Linux2 grab interface
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2006 Luca Abeni
5  *
6  * Part of this file is based on the V4L2 video capture example
7  * (http://v4l2spec.bytesex.org/v4l2spec/capture.c)
8  *
9  * Thanks to Michael Niedermayer for providing the mapping between
10  * V4L2_PIX_FMT_* and PIX_FMT_*
11  *
12  *
13  * This file is part of Libav.
14  *
15  * Libav is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * Libav is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with Libav; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28  */
29
30 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
31 #include "config.h"
32 #include "libavformat/avformat.h"
33 #include "libavformat/internal.h"
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <sys/ioctl.h>
37 #include <sys/mman.h>
38 #include <sys/time.h>
39 #if HAVE_SYS_VIDEOIO_H
40 #include <sys/videoio.h>
41 #else
42 #include <linux/videodev2.h>
43 #endif
44 #include <time.h>
45 #include "libavutil/imgutils.h"
46 #include "libavutil/log.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/pixdesc.h"
50 #include "libavutil/avstring.h"
51
52 static const int desired_video_buffers = 256;
53
54 enum io_method {
55     io_read,
56     io_mmap,
57     io_userptr
58 };
59
60 struct video_data {
61     AVClass *class;
62     int fd;
63     int frame_format; /* V4L2_PIX_FMT_* */
64     enum io_method io_method;
65     int width, height;
66     int frame_size;
67     int interlaced;
68     int top_field_first;
69
70     int buffers;
71     void **buf_start;
72     unsigned int *buf_len;
73     char *standard;
74     int channel;
75     char *video_size; /**< String describing video size, set by a private option. */
76     char *pixel_format; /**< Set by a private option. */
77     char *framerate;    /**< Set by a private option. */
78 };
79
80 struct buff_data {
81     int index;
82     int fd;
83 };
84
85 struct fmt_map {
86     enum PixelFormat ff_fmt;
87     enum CodecID codec_id;
88     uint32_t v4l2_fmt;
89 };
90
91 static struct fmt_map fmt_conversion_table[] = {
92     //ff_fmt           codec_id           v4l2_fmt
93     { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420  },
94     { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
95     { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV    },
96     { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY    },
97     { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
98     { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410  },
99     { PIX_FMT_RGB555,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555  },
100     { PIX_FMT_RGB565,  CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565  },
101     { PIX_FMT_BGR24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24   },
102     { PIX_FMT_RGB24,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24   },
103     { PIX_FMT_BGRA,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32   },
104     { PIX_FMT_GRAY8,   CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY    },
105     { PIX_FMT_NV12,    CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12    },
106     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_MJPEG   },
107     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
108 };
109
110 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
111 {
112     struct v4l2_capability cap;
113     int fd;
114     int res, err;
115     int flags = O_RDWR;
116
117     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
118         flags |= O_NONBLOCK;
119     }
120
121     fd = open(ctx->filename, flags, 0);
122     if (fd < 0) {
123         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
124                ctx->filename, strerror(errno));
125
126         return AVERROR(errno);
127     }
128
129     res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
130     // ENOIOCTLCMD definition only availble on __KERNEL__
131     if (res < 0 && ((err = errno) == 515)) {
132         av_log(ctx, AV_LOG_ERROR,
133                "QUERYCAP not implemented, probably V4L device but "
134                "not supporting V4L2\n");
135         close(fd);
136
137         return AVERROR(515);
138     }
139
140     if (res < 0) {
141         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
142                  strerror(errno));
143         close(fd);
144
145         return AVERROR(err);
146     }
147
148     if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
149         av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
150         close(fd);
151
152         return AVERROR(ENODEV);
153     }
154
155     *capabilities = cap.capabilities;
156
157     return fd;
158 }
159
160 static int device_init(AVFormatContext *ctx, int *width, int *height,
161                        uint32_t pix_fmt)
162 {
163     struct video_data *s = ctx->priv_data;
164     int fd = s->fd;
165     struct v4l2_format fmt;
166     struct v4l2_pix_format *pix = &fmt.fmt.pix;
167
168     int res;
169
170     memset(&fmt, 0, sizeof(struct v4l2_format));
171
172     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
173     pix->width = *width;
174     pix->height = *height;
175     pix->pixelformat = pix_fmt;
176     pix->field = V4L2_FIELD_ANY;
177
178     res = ioctl(fd, VIDIOC_S_FMT, &fmt);
179
180     if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
181         av_log(ctx, AV_LOG_INFO,
182                "The V4L2 driver changed the video from %dx%d to %dx%d\n",
183                *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
184         *width = fmt.fmt.pix.width;
185         *height = fmt.fmt.pix.height;
186     }
187
188     if (pix_fmt != fmt.fmt.pix.pixelformat) {
189         av_log(ctx, AV_LOG_DEBUG,
190                "The V4L2 driver changed the pixel format "
191                "from 0x%08X to 0x%08X\n",
192                pix_fmt, fmt.fmt.pix.pixelformat);
193         res = -1;
194     }
195
196     if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
197         av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
198         s->interlaced = 1;
199     }
200
201     return res;
202 }
203
204 static int first_field(int fd)
205 {
206     int res;
207     v4l2_std_id std;
208
209     res = ioctl(fd, VIDIOC_G_STD, &std);
210     if (res < 0) {
211         return 0;
212     }
213     if (std & V4L2_STD_NTSC) {
214         return 0;
215     }
216
217     return 1;
218 }
219
220 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
221 {
222     int i;
223
224     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
225         if ((codec_id == CODEC_ID_NONE ||
226              fmt_conversion_table[i].codec_id == codec_id) &&
227             (pix_fmt == PIX_FMT_NONE ||
228              fmt_conversion_table[i].ff_fmt == pix_fmt)) {
229             return fmt_conversion_table[i].v4l2_fmt;
230         }
231     }
232
233     return 0;
234 }
235
236 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
237 {
238     int i;
239
240     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
241         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
242             fmt_conversion_table[i].codec_id == codec_id) {
243             return fmt_conversion_table[i].ff_fmt;
244         }
245     }
246
247     return PIX_FMT_NONE;
248 }
249
250 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
251 {
252     int i;
253
254     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
255         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
256             return fmt_conversion_table[i].codec_id;
257         }
258     }
259
260     return CODEC_ID_NONE;
261 }
262
263 static int mmap_init(AVFormatContext *ctx)
264 {
265     struct video_data *s = ctx->priv_data;
266     struct v4l2_requestbuffers req;
267     int i, res;
268
269     memset(&req, 0, sizeof(struct v4l2_requestbuffers));
270     req.count = desired_video_buffers;
271     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
272     req.memory = V4L2_MEMORY_MMAP;
273     res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
274     if (res < 0) {
275         if (errno == EINVAL) {
276             av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
277         } else {
278             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
279         }
280
281         return AVERROR(errno);
282     }
283
284     if (req.count < 2) {
285         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
286
287         return AVERROR(ENOMEM);
288     }
289     s->buffers = req.count;
290     s->buf_start = av_malloc(sizeof(void *) * s->buffers);
291     if (s->buf_start == NULL) {
292         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
293
294         return AVERROR(ENOMEM);
295     }
296     s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
297     if (s->buf_len == NULL) {
298         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
299         av_free(s->buf_start);
300
301         return AVERROR(ENOMEM);
302     }
303
304     for (i = 0; i < req.count; i++) {
305         struct v4l2_buffer buf;
306
307         memset(&buf, 0, sizeof(struct v4l2_buffer));
308         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
309         buf.memory = V4L2_MEMORY_MMAP;
310         buf.index = i;
311         res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
312         if (res < 0) {
313             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
314
315             return AVERROR(errno);
316         }
317
318         s->buf_len[i] = buf.length;
319         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
320             av_log(ctx, AV_LOG_ERROR,
321                    "Buffer len [%d] = %d != %d\n",
322                    i, s->buf_len[i], s->frame_size);
323
324             return -1;
325         }
326         s->buf_start[i] = mmap(NULL, buf.length,
327                                PROT_READ | PROT_WRITE, MAP_SHARED,
328                                s->fd, buf.m.offset);
329
330         if (s->buf_start[i] == MAP_FAILED) {
331             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
332
333             return AVERROR(errno);
334         }
335     }
336
337     return 0;
338 }
339
340 static int read_init(AVFormatContext *ctx)
341 {
342     return -1;
343 }
344
345 static void mmap_release_buffer(AVPacket *pkt)
346 {
347     struct v4l2_buffer buf;
348     int res, fd;
349     struct buff_data *buf_descriptor = pkt->priv;
350
351     if (pkt->data == NULL)
352         return;
353
354     memset(&buf, 0, sizeof(struct v4l2_buffer));
355     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
356     buf.memory = V4L2_MEMORY_MMAP;
357     buf.index = buf_descriptor->index;
358     fd = buf_descriptor->fd;
359     av_free(buf_descriptor);
360
361     res = ioctl(fd, VIDIOC_QBUF, &buf);
362     if (res < 0)
363         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
364                strerror(errno));
365
366     pkt->data = NULL;
367     pkt->size = 0;
368 }
369
370 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
371 {
372     struct video_data *s = ctx->priv_data;
373     struct v4l2_buffer buf;
374     struct buff_data *buf_descriptor;
375     int res;
376
377     memset(&buf, 0, sizeof(struct v4l2_buffer));
378     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
379     buf.memory = V4L2_MEMORY_MMAP;
380
381     /* FIXME: Some special treatment might be needed in case of loss of signal... */
382     while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
383     if (res < 0) {
384         if (errno == EAGAIN) {
385             pkt->size = 0;
386
387             return AVERROR(EAGAIN);
388         }
389         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
390                strerror(errno));
391
392         return AVERROR(errno);
393     }
394     assert (buf.index < s->buffers);
395     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
396         av_log(ctx, AV_LOG_ERROR,
397                "The v4l2 frame is %d bytes, but %d bytes are expected\n",
398                buf.bytesused, s->frame_size);
399
400         return AVERROR_INVALIDDATA;
401     }
402
403     /* Image is at s->buff_start[buf.index] */
404     pkt->data= s->buf_start[buf.index];
405     pkt->size = buf.bytesused;
406     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
407     pkt->destruct = mmap_release_buffer;
408     buf_descriptor = av_malloc(sizeof(struct buff_data));
409     if (buf_descriptor == NULL) {
410         /* Something went wrong... Since av_malloc() failed, we cannot even
411          * allocate a buffer for memcopying into it
412          */
413         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
414         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
415
416         return AVERROR(ENOMEM);
417     }
418     buf_descriptor->fd = s->fd;
419     buf_descriptor->index = buf.index;
420     pkt->priv = buf_descriptor;
421
422     return s->buf_len[buf.index];
423 }
424
425 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
426 {
427     return -1;
428 }
429
430 static int mmap_start(AVFormatContext *ctx)
431 {
432     struct video_data *s = ctx->priv_data;
433     enum v4l2_buf_type type;
434     int i, res;
435
436     for (i = 0; i < s->buffers; i++) {
437         struct v4l2_buffer buf;
438
439         memset(&buf, 0, sizeof(struct v4l2_buffer));
440         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
441         buf.memory = V4L2_MEMORY_MMAP;
442         buf.index  = i;
443
444         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
445         if (res < 0) {
446             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
447                    strerror(errno));
448
449             return AVERROR(errno);
450         }
451     }
452
453     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
454     res = ioctl(s->fd, VIDIOC_STREAMON, &type);
455     if (res < 0) {
456         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
457                strerror(errno));
458
459         return AVERROR(errno);
460     }
461
462     return 0;
463 }
464
465 static void mmap_close(struct video_data *s)
466 {
467     enum v4l2_buf_type type;
468     int i;
469
470     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
471     /* We do not check for the result, because we could
472      * not do anything about it anyway...
473      */
474     ioctl(s->fd, VIDIOC_STREAMOFF, &type);
475     for (i = 0; i < s->buffers; i++) {
476         munmap(s->buf_start[i], s->buf_len[i]);
477     }
478     av_free(s->buf_start);
479     av_free(s->buf_len);
480 }
481
482 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
483 {
484     struct video_data *s = s1->priv_data;
485     struct v4l2_input input;
486     struct v4l2_standard standard;
487     struct v4l2_streamparm streamparm = { 0 };
488     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
489     int i, ret;
490     AVRational framerate_q;
491
492     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
493
494     if (s->framerate &&
495         (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
496         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
497                s->framerate);
498         return ret;
499     }
500
501     /* set tv video input */
502     memset (&input, 0, sizeof (input));
503     input.index = s->channel;
504     if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
505         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
506         return AVERROR(EIO);
507     }
508
509     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
510             s->channel, input.name);
511     if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
512         av_log(s1, AV_LOG_ERROR,
513                "The V4L2 driver ioctl set input(%d) failed\n",
514                 s->channel);
515         return AVERROR(EIO);
516     }
517
518     if (s->standard) {
519         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
520                s->standard);
521         /* set tv standard */
522         memset (&standard, 0, sizeof (standard));
523         for(i=0;;i++) {
524             standard.index = i;
525             if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
526                 av_log(s1, AV_LOG_ERROR,
527                        "The V4L2 driver ioctl set standard(%s) failed\n",
528                        s->standard);
529                 return AVERROR(EIO);
530             }
531
532             if (!av_strcasecmp(standard.name, s->standard)) {
533                 break;
534             }
535         }
536
537         av_log(s1, AV_LOG_DEBUG,
538                "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
539                s->standard, (uint64_t)standard.id);
540         if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
541             av_log(s1, AV_LOG_ERROR,
542                    "The V4L2 driver ioctl set standard(%s) failed\n",
543                    s->standard);
544             return AVERROR(EIO);
545         }
546     }
547
548     if (framerate_q.num && framerate_q.den) {
549         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
550                framerate_q.den, framerate_q.num);
551         tpf->numerator   = framerate_q.den;
552         tpf->denominator = framerate_q.num;
553
554         if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
555             av_log(s1, AV_LOG_ERROR,
556                    "ioctl set time per frame(%d/%d) failed\n",
557                    framerate_q.den, framerate_q.num);
558             return AVERROR(EIO);
559         }
560
561         if (framerate_q.num != tpf->denominator ||
562             framerate_q.den != tpf->numerator) {
563             av_log(s1, AV_LOG_INFO,
564                    "The driver changed the time per frame from "
565                    "%d/%d to %d/%d\n",
566                    framerate_q.den, framerate_q.num,
567                    tpf->numerator, tpf->denominator);
568         }
569     } else {
570         if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
571             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
572                    strerror(errno));
573             return AVERROR(errno);
574         }
575     }
576     s1->streams[0]->codec->time_base.den = tpf->denominator;
577     s1->streams[0]->codec->time_base.num = tpf->numerator;
578
579     return 0;
580 }
581
582 static uint32_t device_try_init(AVFormatContext *s1,
583                                 enum PixelFormat pix_fmt,
584                                 int *width,
585                                 int *height,
586                                 enum CodecID *codec_id)
587 {
588     uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
589
590     if (desired_format == 0 ||
591         device_init(s1, width, height, desired_format) < 0) {
592         int i;
593
594         desired_format = 0;
595         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
596             if (s1->video_codec_id == CODEC_ID_NONE ||
597                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
598                 desired_format = fmt_conversion_table[i].v4l2_fmt;
599                 if (device_init(s1, width, height, desired_format) >= 0) {
600                     break;
601                 }
602                 desired_format = 0;
603             }
604         }
605     }
606
607     if (desired_format != 0) {
608         *codec_id = fmt_v4l2codec(desired_format);
609         assert(*codec_id != CODEC_ID_NONE);
610     }
611
612     return desired_format;
613 }
614
615 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
616 {
617     struct video_data *s = s1->priv_data;
618     AVStream *st;
619     int res = 0;
620     uint32_t desired_format, capabilities = 0;
621     enum CodecID codec_id;
622     enum PixelFormat pix_fmt = PIX_FMT_NONE;
623
624     st = avformat_new_stream(s1, NULL);
625     if (!st) {
626         res = AVERROR(ENOMEM);
627         goto out;
628     }
629
630     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
631
632     if (s->video_size &&
633         (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
634         av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
635                s->video_size);
636         goto out;
637     }
638     if (s->pixel_format &&
639         (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
640         av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n",
641                s->pixel_format);
642         res = AVERROR(EINVAL);
643         goto out;
644     }
645
646     s->fd = device_open(s1, &capabilities);
647     if (s->fd < 0) {
648         res = AVERROR(EIO);
649         goto out;
650     }
651     av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
652
653     if (!s->width && !s->height) {
654         struct v4l2_format fmt;
655
656         av_log(s1, AV_LOG_VERBOSE,
657                "Querying the device for the current frame size\n");
658         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
659         if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
660             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
661                    strerror(errno));
662             res = AVERROR(errno);
663             goto out;
664         }
665
666         s->width  = fmt.fmt.pix.width;
667         s->height = fmt.fmt.pix.height;
668         av_log(s1, AV_LOG_VERBOSE,
669                "Setting frame size to %dx%d\n", s->width, s->height);
670     }
671
672     desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
673                                      &codec_id);
674     if (desired_format == 0) {
675         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
676                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
677         close(s->fd);
678
679         res = AVERROR(EIO);
680         goto out;
681     }
682
683     if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
684         goto out;
685
686     s->frame_format = desired_format;
687
688     if ((res = v4l2_set_parameters(s1, ap) < 0))
689         goto out;
690
691     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
692     s->frame_size =
693         avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
694
695     if (capabilities & V4L2_CAP_STREAMING) {
696         s->io_method = io_mmap;
697         res = mmap_init(s1);
698         if (res == 0) {
699             res = mmap_start(s1);
700         }
701     } else {
702         s->io_method = io_read;
703         res = read_init(s1);
704     }
705     if (res < 0) {
706         close(s->fd);
707
708         res = AVERROR(EIO);
709         goto out;
710     }
711     s->top_field_first = first_field(s->fd);
712
713     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
714     st->codec->codec_id = codec_id;
715     st->codec->width = s->width;
716     st->codec->height = s->height;
717     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
718
719 out:
720     return res;
721 }
722
723 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
724 {
725     struct video_data *s = s1->priv_data;
726     AVFrame *frame = s1->streams[0]->codec->coded_frame;
727     int res;
728
729     if (s->io_method == io_mmap) {
730         av_init_packet(pkt);
731         res = mmap_read_frame(s1, pkt);
732     } else if (s->io_method == io_read) {
733         if (av_new_packet(pkt, s->frame_size) < 0)
734             return AVERROR(EIO);
735
736         res = read_frame(s1, pkt);
737     } else {
738         return AVERROR(EIO);
739     }
740     if (res < 0) {
741         return res;
742     }
743
744     if (frame && s->interlaced) {
745         frame->interlaced_frame = 1;
746         frame->top_field_first = s->top_field_first;
747     }
748
749     return pkt->size;
750 }
751
752 static int v4l2_read_close(AVFormatContext *s1)
753 {
754     struct video_data *s = s1->priv_data;
755
756     if (s->io_method == io_mmap) {
757         mmap_close(s);
758     }
759
760     close(s->fd);
761     return 0;
762 }
763
764 #define OFFSET(x) offsetof(struct video_data, x)
765 #define DEC AV_OPT_FLAG_DECODING_PARAM
766 static const AVOption options[] = {
767     { "standard",     "TV standard, used only by analog frame grabber",            OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
768     { "channel",      "TV channel, used only by frame grabber",                    OFFSET(channel),      AV_OPT_TYPE_INT,    {.dbl = 0 },    0, INT_MAX, DEC },
769     { "video_size",   "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
770     { "pixel_format", "",                                                          OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
771     { "framerate",    "",                                                          OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
772     { NULL },
773 };
774
775 static const AVClass v4l2_class = {
776     .class_name = "V4L2 indev",
777     .item_name  = av_default_item_name,
778     .option     = options,
779     .version    = LIBAVUTIL_VERSION_INT,
780 };
781
782 AVInputFormat ff_v4l2_demuxer = {
783     .name           = "video4linux2",
784     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
785     .priv_data_size = sizeof(struct video_data),
786     .read_header    = v4l2_read_header,
787     .read_packet    = v4l2_read_packet,
788     .read_close     = v4l2_read_close,
789     .flags          = AVFMT_NOFILE,
790     .priv_class     = &v4l2_class,
791 };