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