]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l2.c
v4l2: do not force interlaced mode
[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     fd = open(ctx->filename, flags, 0);
121     if (fd < 0) {
122         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
123                  ctx->filename, strerror(errno));
124
125         return AVERROR(errno);
126     }
127
128     res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
129     // ENOIOCTLCMD definition only availble on __KERNEL__
130     if (res < 0 && ((err = errno) == 515)) {
131         av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
132         close(fd);
133
134         return AVERROR(515);
135     }
136     if (res < 0) {
137         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
138                  strerror(errno));
139         close(fd);
140
141         return AVERROR(err);
142     }
143     if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
144         av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
145         close(fd);
146
147         return AVERROR(ENODEV);
148     }
149     *capabilities = cap.capabilities;
150
151     return fd;
152 }
153
154 static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
155 {
156     struct video_data *s = ctx->priv_data;
157     int fd = s->fd;
158     struct v4l2_format fmt;
159     int res;
160
161     memset(&fmt, 0, sizeof(struct v4l2_format));
162     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
163     fmt.fmt.pix.width = *width;
164     fmt.fmt.pix.height = *height;
165     fmt.fmt.pix.pixelformat = pix_fmt;
166     fmt.fmt.pix.field = V4L2_FIELD_ANY;
167     res = ioctl(fd, VIDIOC_S_FMT, &fmt);
168     if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
169         av_log(ctx, AV_LOG_INFO, "The V4L2 driver changed the video from %dx%d to %dx%d\n", *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
170         *width = fmt.fmt.pix.width;
171         *height = fmt.fmt.pix.height;
172     }
173
174     if (pix_fmt != fmt.fmt.pix.pixelformat) {
175         av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver changed the pixel format from 0x%08X to 0x%08X\n", pix_fmt, fmt.fmt.pix.pixelformat);
176         res = -1;
177     }
178
179     if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
180         av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
181         s->interlaced = 1;
182     }
183
184     return res;
185 }
186
187 static int first_field(int fd)
188 {
189     int res;
190     v4l2_std_id std;
191
192     res = ioctl(fd, VIDIOC_G_STD, &std);
193     if (res < 0) {
194         return 0;
195     }
196     if (std & V4L2_STD_NTSC) {
197         return 0;
198     }
199
200     return 1;
201 }
202
203 static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
204 {
205     int i;
206
207     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
208         if ((codec_id == CODEC_ID_NONE ||
209              fmt_conversion_table[i].codec_id == codec_id) &&
210             (pix_fmt == PIX_FMT_NONE ||
211              fmt_conversion_table[i].ff_fmt == pix_fmt)) {
212             return fmt_conversion_table[i].v4l2_fmt;
213         }
214     }
215
216     return 0;
217 }
218
219 static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
220 {
221     int i;
222
223     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
224         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
225             fmt_conversion_table[i].codec_id == codec_id) {
226             return fmt_conversion_table[i].ff_fmt;
227         }
228     }
229
230     return PIX_FMT_NONE;
231 }
232
233 static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
234 {
235     int i;
236
237     for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
238         if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
239             return fmt_conversion_table[i].codec_id;
240         }
241     }
242
243     return CODEC_ID_NONE;
244 }
245
246 static int mmap_init(AVFormatContext *ctx)
247 {
248     struct video_data *s = ctx->priv_data;
249     struct v4l2_requestbuffers req;
250     int i, res;
251
252     memset(&req, 0, sizeof(struct v4l2_requestbuffers));
253     req.count = desired_video_buffers;
254     req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
255     req.memory = V4L2_MEMORY_MMAP;
256     res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
257     if (res < 0) {
258         if (errno == EINVAL) {
259             av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
260         } else {
261             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
262         }
263
264         return AVERROR(errno);
265     }
266
267     if (req.count < 2) {
268         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
269
270         return AVERROR(ENOMEM);
271     }
272     s->buffers = req.count;
273     s->buf_start = av_malloc(sizeof(void *) * s->buffers);
274     if (s->buf_start == NULL) {
275         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
276
277         return AVERROR(ENOMEM);
278     }
279     s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
280     if (s->buf_len == NULL) {
281         av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
282         av_free(s->buf_start);
283
284         return AVERROR(ENOMEM);
285     }
286
287     for (i = 0; i < req.count; i++) {
288         struct v4l2_buffer buf;
289
290         memset(&buf, 0, sizeof(struct v4l2_buffer));
291         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
292         buf.memory = V4L2_MEMORY_MMAP;
293         buf.index = i;
294         res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
295         if (res < 0) {
296             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
297
298             return AVERROR(errno);
299         }
300
301         s->buf_len[i] = buf.length;
302         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
303             av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
304
305             return -1;
306         }
307         s->buf_start[i] = mmap (NULL, buf.length,
308                         PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
309         if (s->buf_start[i] == MAP_FAILED) {
310             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
311
312             return AVERROR(errno);
313         }
314     }
315
316     return 0;
317 }
318
319 static int read_init(AVFormatContext *ctx)
320 {
321     return -1;
322 }
323
324 static void mmap_release_buffer(AVPacket *pkt)
325 {
326     struct v4l2_buffer buf;
327     int res, fd;
328     struct buff_data *buf_descriptor = pkt->priv;
329
330     if (pkt->data == NULL) {
331          return;
332     }
333
334     memset(&buf, 0, sizeof(struct v4l2_buffer));
335     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
336     buf.memory = V4L2_MEMORY_MMAP;
337     buf.index = buf_descriptor->index;
338     fd = buf_descriptor->fd;
339     av_free(buf_descriptor);
340
341     res = ioctl(fd, VIDIOC_QBUF, &buf);
342     if (res < 0) {
343         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
344     }
345     pkt->data = NULL;
346     pkt->size = 0;
347 }
348
349 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
350 {
351     struct video_data *s = ctx->priv_data;
352     struct v4l2_buffer buf;
353     struct buff_data *buf_descriptor;
354     int res;
355
356     memset(&buf, 0, sizeof(struct v4l2_buffer));
357     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
358     buf.memory = V4L2_MEMORY_MMAP;
359
360     /* FIXME: Some special treatment might be needed in case of loss of signal... */
361     while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
362     if (res < 0) {
363         if (errno == EAGAIN) {
364             pkt->size = 0;
365
366             return AVERROR(EAGAIN);
367         }
368         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
369
370         return AVERROR(errno);
371     }
372     assert (buf.index < s->buffers);
373     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
374         av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
375
376         return AVERROR_INVALIDDATA;
377     }
378
379     /* Image is at s->buff_start[buf.index] */
380     pkt->data= s->buf_start[buf.index];
381     pkt->size = buf.bytesused;
382     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
383     pkt->destruct = mmap_release_buffer;
384     buf_descriptor = av_malloc(sizeof(struct buff_data));
385     if (buf_descriptor == NULL) {
386         /* Something went wrong... Since av_malloc() failed, we cannot even
387          * allocate a buffer for memcopying into it
388          */
389         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
390         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
391
392         return AVERROR(ENOMEM);
393     }
394     buf_descriptor->fd = s->fd;
395     buf_descriptor->index = buf.index;
396     pkt->priv = buf_descriptor;
397
398     return s->buf_len[buf.index];
399 }
400
401 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
402 {
403     return -1;
404 }
405
406 static int mmap_start(AVFormatContext *ctx)
407 {
408     struct video_data *s = ctx->priv_data;
409     enum v4l2_buf_type type;
410     int i, res;
411
412     for (i = 0; i < s->buffers; i++) {
413         struct v4l2_buffer buf;
414
415         memset(&buf, 0, sizeof(struct v4l2_buffer));
416         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
417         buf.memory = V4L2_MEMORY_MMAP;
418         buf.index  = i;
419
420         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
421         if (res < 0) {
422             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
423
424             return AVERROR(errno);
425         }
426     }
427
428     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
429     res = ioctl(s->fd, VIDIOC_STREAMON, &type);
430     if (res < 0) {
431         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
432
433         return AVERROR(errno);
434     }
435
436     return 0;
437 }
438
439 static void mmap_close(struct video_data *s)
440 {
441     enum v4l2_buf_type type;
442     int i;
443
444     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
445     /* We do not check for the result, because we could
446      * not do anything about it anyway...
447      */
448     ioctl(s->fd, VIDIOC_STREAMOFF, &type);
449     for (i = 0; i < s->buffers; i++) {
450         munmap(s->buf_start[i], s->buf_len[i]);
451     }
452     av_free(s->buf_start);
453     av_free(s->buf_len);
454 }
455
456 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
457 {
458     struct video_data *s = s1->priv_data;
459     struct v4l2_input input;
460     struct v4l2_standard standard;
461     struct v4l2_streamparm streamparm = { 0 };
462     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
463     int i, ret;
464     AVRational framerate_q;
465
466     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
467
468     if (s->framerate && (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
469         av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", s->framerate);
470         return ret;
471     }
472
473     /* set tv video input */
474     memset (&input, 0, sizeof (input));
475     input.index = s->channel;
476     if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
477         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
478         return AVERROR(EIO);
479     }
480
481     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
482             s->channel, input.name);
483     if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
484         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
485                 s->channel);
486         return AVERROR(EIO);
487     }
488
489     if (s->standard) {
490         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
491                s->standard);
492         /* set tv standard */
493         memset (&standard, 0, sizeof (standard));
494         for(i=0;;i++) {
495             standard.index = i;
496             if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
497                 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
498                        s->standard);
499                 return AVERROR(EIO);
500             }
501
502             if (!av_strcasecmp(standard.name, s->standard)) {
503                 break;
504             }
505         }
506
507         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
508                s->standard, (uint64_t)standard.id);
509         if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
510             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
511                    s->standard);
512             return AVERROR(EIO);
513         }
514     }
515
516     if (framerate_q.num && framerate_q.den) {
517         av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
518                framerate_q.den, framerate_q.num);
519         tpf->numerator   = framerate_q.den;
520         tpf->denominator = framerate_q.num;
521         if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
522             av_log(s1, AV_LOG_ERROR,
523                    "ioctl set time per frame(%d/%d) failed\n",
524                    framerate_q.den, framerate_q.num);
525             return AVERROR(EIO);
526         }
527
528         if (framerate_q.num != tpf->denominator ||
529             framerate_q.den != tpf->numerator) {
530             av_log(s1, AV_LOG_INFO,
531                    "The driver changed the time per frame from %d/%d to %d/%d\n",
532                    framerate_q.den, framerate_q.num,
533                    tpf->numerator, tpf->denominator);
534         }
535     } else {
536         /* if timebase value is not set, read the timebase value from the driver */
537         if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
538             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
539             return AVERROR(errno);
540         }
541     }
542     s1->streams[0]->codec->time_base.den = tpf->denominator;
543     s1->streams[0]->codec->time_base.num = tpf->numerator;
544
545     return 0;
546 }
547
548 static uint32_t device_try_init(AVFormatContext *s1,
549                                 enum PixelFormat pix_fmt,
550                                 int *width,
551                                 int *height,
552                                 enum CodecID *codec_id)
553 {
554     uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
555
556     if (desired_format == 0 ||
557         device_init(s1, width, height, desired_format) < 0) {
558         int i;
559
560         desired_format = 0;
561         for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
562             if (s1->video_codec_id == CODEC_ID_NONE ||
563                 fmt_conversion_table[i].codec_id == s1->video_codec_id) {
564                 desired_format = fmt_conversion_table[i].v4l2_fmt;
565                 if (device_init(s1, width, height, desired_format) >= 0) {
566                     break;
567                 }
568                 desired_format = 0;
569             }
570         }
571     }
572     if (desired_format != 0) {
573         *codec_id = fmt_v4l2codec(desired_format);
574         assert(*codec_id != CODEC_ID_NONE);
575     }
576
577     return desired_format;
578 }
579
580 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
581 {
582     struct video_data *s = s1->priv_data;
583     AVStream *st;
584     int res = 0;
585     uint32_t desired_format, capabilities;
586     enum CodecID codec_id;
587     enum PixelFormat pix_fmt = PIX_FMT_NONE;
588
589     st = avformat_new_stream(s1, NULL);
590     if (!st) {
591         res = AVERROR(ENOMEM);
592         goto out;
593     }
594     avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
595
596     if (s->video_size && (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
597         av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n", s->video_size);
598         goto out;
599     }
600     if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
601         av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
602         res = AVERROR(EINVAL);
603         goto out;
604     }
605
606     capabilities = 0;
607     s->fd = device_open(s1, &capabilities);
608     if (s->fd < 0) {
609         res = AVERROR(EIO);
610         goto out;
611     }
612     av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
613
614     if (!s->width && !s->height) {
615         struct v4l2_format fmt;
616
617         av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
618         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
619         if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
620             av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
621             res = AVERROR(errno);
622             goto out;
623         }
624         s->width  = fmt.fmt.pix.width;
625         s->height = fmt.fmt.pix.height;
626         av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
627     }
628
629     desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height, &codec_id);
630     if (desired_format == 0) {
631         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
632                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
633         close(s->fd);
634
635         res = AVERROR(EIO);
636         goto out;
637     }
638     if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
639         goto out;
640     s->frame_format = desired_format;
641
642     if ((res = v4l2_set_parameters(s1, ap) < 0))
643         goto out;
644
645     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
646     s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
647     if (capabilities & V4L2_CAP_STREAMING) {
648         s->io_method = io_mmap;
649         res = mmap_init(s1);
650         if (res == 0) {
651             res = mmap_start(s1);
652         }
653     } else {
654         s->io_method = io_read;
655         res = read_init(s1);
656     }
657     if (res < 0) {
658         close(s->fd);
659
660         res = AVERROR(EIO);
661         goto out;
662     }
663     s->top_field_first = first_field(s->fd);
664
665     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
666     st->codec->codec_id = codec_id;
667     st->codec->width = s->width;
668     st->codec->height = s->height;
669     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
670
671 out:
672     return res;
673 }
674
675 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
676 {
677     struct video_data *s = s1->priv_data;
678     int res;
679
680     if (s->io_method == io_mmap) {
681         av_init_packet(pkt);
682         res = mmap_read_frame(s1, pkt);
683     } else if (s->io_method == io_read) {
684         if (av_new_packet(pkt, s->frame_size) < 0)
685             return AVERROR(EIO);
686
687         res = read_frame(s1, pkt);
688     } else {
689         return AVERROR(EIO);
690     }
691     if (res < 0) {
692         return res;
693     }
694
695     if (s1->streams[0]->codec->coded_frame && s->interlaced) {
696         s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
697         s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
698     }
699
700     return pkt->size;
701 }
702
703 static int v4l2_read_close(AVFormatContext *s1)
704 {
705     struct video_data *s = s1->priv_data;
706
707     if (s->io_method == io_mmap) {
708         mmap_close(s);
709     }
710
711     close(s->fd);
712     return 0;
713 }
714
715 #define OFFSET(x) offsetof(struct video_data, x)
716 #define DEC AV_OPT_FLAG_DECODING_PARAM
717 static const AVOption options[] = {
718     { "standard", "", offsetof(struct video_data, standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
719     { "channel",  "", offsetof(struct video_data, channel),  AV_OPT_TYPE_INT,    {.dbl = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
720     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
721     { "pixel_format", "", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
722     { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
723     { NULL },
724 };
725
726 static const AVClass v4l2_class = {
727     .class_name = "V4L2 indev",
728     .item_name  = av_default_item_name,
729     .option     = options,
730     .version    = LIBAVUTIL_VERSION_INT,
731 };
732
733 AVInputFormat ff_v4l2_demuxer = {
734     .name           = "video4linux2",
735     .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
736     .priv_data_size = sizeof(struct video_data),
737     .read_header    = v4l2_read_header,
738     .read_packet    = v4l2_read_packet,
739     .read_close     = v4l2_read_close,
740     .flags          = AVFMT_NOFILE,
741     .priv_class     = &v4l2_class,
742 };