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