]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavdevice/v4l2.c
The v4l2 driver can silently change the pixel format in the
[frescor/ffmpeg.git] / 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 FFmpeg.
14  *
15  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 #ifdef 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
47 static const int desired_video_buffers = 256;
48
49 enum io_method {
50     io_read,
51     io_mmap,
52     io_userptr
53 };
54
55 struct video_data {
56     int fd;
57     int frame_format; /* V4L2_PIX_FMT_* */
58     enum io_method io_method;
59     int width, height;
60     int frame_rate;
61     int frame_rate_base;
62     int frame_size;
63     int top_field_first;
64
65     int buffers;
66     void **buf_start;
67     unsigned int *buf_len;
68 };
69
70 struct buff_data {
71     int index;
72     int fd;
73 };
74
75 struct fmt_map {
76     enum PixelFormat ff_fmt;
77     int32_t v4l2_fmt;
78 };
79
80 static struct fmt_map fmt_conversion_table[] = {
81     {
82         .ff_fmt = PIX_FMT_YUV420P,
83         .v4l2_fmt = V4L2_PIX_FMT_YUV420,
84     },
85     {
86         .ff_fmt = PIX_FMT_YUV422P,
87         .v4l2_fmt = V4L2_PIX_FMT_YUV422P,
88     },
89     {
90         .ff_fmt = PIX_FMT_YUYV422,
91         .v4l2_fmt = V4L2_PIX_FMT_YUYV,
92     },
93     {
94         .ff_fmt = PIX_FMT_UYVY422,
95         .v4l2_fmt = V4L2_PIX_FMT_UYVY,
96     },
97     {
98         .ff_fmt = PIX_FMT_YUV411P,
99         .v4l2_fmt = V4L2_PIX_FMT_YUV411P,
100     },
101     {
102         .ff_fmt = PIX_FMT_YUV410P,
103         .v4l2_fmt = V4L2_PIX_FMT_YUV410,
104     },
105     {
106         .ff_fmt = PIX_FMT_RGB555,
107         .v4l2_fmt = V4L2_PIX_FMT_RGB555,
108     },
109     {
110         .ff_fmt = PIX_FMT_RGB565,
111         .v4l2_fmt = V4L2_PIX_FMT_RGB565,
112     },
113     {
114         .ff_fmt = PIX_FMT_BGR24,
115         .v4l2_fmt = V4L2_PIX_FMT_BGR24,
116     },
117     {
118         .ff_fmt = PIX_FMT_RGB24,
119         .v4l2_fmt = V4L2_PIX_FMT_RGB24,
120     },
121     {
122         .ff_fmt = PIX_FMT_BGRA,
123         .v4l2_fmt = V4L2_PIX_FMT_BGR32,
124     },
125     {
126         .ff_fmt = PIX_FMT_GRAY8,
127         .v4l2_fmt = V4L2_PIX_FMT_GREY,
128     },
129 };
130
131 static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
132 {
133     struct v4l2_capability cap;
134     int fd;
135     int res;
136     int flags = O_RDWR;
137
138     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
139         flags |= O_NONBLOCK;
140     }
141     fd = open(ctx->filename, flags, 0);
142     if (fd < 0) {
143         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
144                  ctx->filename, strerror(errno));
145
146         return -1;
147     }
148
149     res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
150     // ENOIOCTLCMD definition only availble on __KERNEL__
151     if (res < 0 && errno == 515)
152     {
153         av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
154         close(fd);
155
156         return -1;
157     }
158     if (res < 0) {
159         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
160                  strerror(errno));
161         close(fd);
162
163         return -1;
164     }
165     if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
166         av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
167         close(fd);
168
169         return -1;
170     }
171     *capabilities = cap.capabilities;
172
173     return fd;
174 }
175
176 static int device_init(AVFormatContext *ctx, int *width, int *height, int pix_fmt)
177 {
178     struct video_data *s = ctx->priv_data;
179     int fd = s->fd;
180     struct v4l2_format fmt;
181     int res;
182
183     memset(&fmt, 0, sizeof(struct v4l2_format));
184     fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
185     fmt.fmt.pix.width = *width;
186     fmt.fmt.pix.height = *height;
187     fmt.fmt.pix.pixelformat = pix_fmt;
188     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
189     res = ioctl(fd, VIDIOC_S_FMT, &fmt);
190     if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
191         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);
192         *width = fmt.fmt.pix.width;
193         *height = fmt.fmt.pix.height;
194     }
195
196     if (pix_fmt != fmt.fmt.pix.pixelformat) {
197         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);
198         res = -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)
221 {
222     int i;
223
224     for (i = 0; i < sizeof(fmt_conversion_table) / sizeof(struct fmt_map); i++) {
225         if (fmt_conversion_table[i].ff_fmt == pix_fmt) {
226             return fmt_conversion_table[i].v4l2_fmt;
227         }
228     }
229
230     return 0;
231 }
232
233 static enum PixelFormat fmt_v4l2ff(uint32_t pix_fmt)
234 {
235     int i;
236
237     for (i = 0; i < sizeof(fmt_conversion_table) / sizeof(struct fmt_map); i++) {
238         if (fmt_conversion_table[i].v4l2_fmt == pix_fmt) {
239             return fmt_conversion_table[i].ff_fmt;
240         }
241     }
242
243     return PIX_FMT_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 -1;
265     }
266
267     if (req.count < 2) {
268         av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
269
270         return -1;
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 -1;
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 -1;
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 -1;
299         }
300
301         s->buf_len[i] = buf.length;
302         if (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 -1;
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     memset(&buf, 0, sizeof(struct v4l2_buffer));
331     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
332     buf.memory = V4L2_MEMORY_MMAP;
333     buf.index = buf_descriptor->index;
334     fd = buf_descriptor->fd;
335     av_free(buf_descriptor);
336
337     res = ioctl (fd, VIDIOC_QBUF, &buf);
338     if (res < 0) {
339         av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF)\n");
340     }
341     pkt->data = NULL;
342     pkt->size = 0;
343 }
344
345 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
346 {
347     struct video_data *s = ctx->priv_data;
348     struct v4l2_buffer buf;
349     struct buff_data *buf_descriptor;
350     int res;
351
352     memset(&buf, 0, sizeof(struct v4l2_buffer));
353     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
354     buf.memory = V4L2_MEMORY_MMAP;
355
356     /* FIXME: Some special treatment might be needed in case of loss of signal... */
357     while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
358     if (res < 0) {
359         if (errno == EAGAIN) {
360             pkt->size = 0;
361
362             return AVERROR(EAGAIN);
363         }
364         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
365
366         return -1;
367     }
368     assert (buf.index < s->buffers);
369     if (buf.bytesused != s->frame_size) {
370         av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
371
372         return -1;
373     }
374
375     /* Image is at s->buff_start[buf.index] */
376     pkt->data= s->buf_start[buf.index];
377     pkt->size = buf.bytesused;
378     pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
379     pkt->destruct = mmap_release_buffer;
380     buf_descriptor = av_malloc(sizeof(struct buff_data));
381     if (buf_descriptor == NULL) {
382         /* Something went wrong... Since av_malloc() failed, we cannot even
383          * allocate a buffer for memcopying into it
384          */
385         av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
386         res = ioctl (s->fd, VIDIOC_QBUF, &buf);
387
388         return -1;
389     }
390     buf_descriptor->fd = s->fd;
391     buf_descriptor->index = buf.index;
392     pkt->priv = buf_descriptor;
393
394     return s->buf_len[buf.index];
395 }
396
397 static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
398 {
399     return -1;
400 }
401
402 static int mmap_start(AVFormatContext *ctx)
403 {
404     struct video_data *s = ctx->priv_data;
405     enum v4l2_buf_type type;
406     int i, res;
407
408     for (i = 0; i < s->buffers; i++) {
409         struct v4l2_buffer buf;
410
411         memset(&buf, 0, sizeof(struct v4l2_buffer));
412         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
413         buf.memory = V4L2_MEMORY_MMAP;
414         buf.index  = i;
415
416         res = ioctl (s->fd, VIDIOC_QBUF, &buf);
417         if (res < 0) {
418             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
419
420             return -1;
421         }
422     }
423
424     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
425     res = ioctl (s->fd, VIDIOC_STREAMON, &type);
426     if (res < 0) {
427         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
428
429         return -1;
430     }
431
432     return 0;
433 }
434
435 static void mmap_close(struct video_data *s)
436 {
437     enum v4l2_buf_type type;
438     int i;
439
440     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
441     /* We do not check for the result, because we could
442      * not do anything about it anyway...
443      */
444     ioctl(s->fd, VIDIOC_STREAMOFF, &type);
445     for (i = 0; i < s->buffers; i++) {
446         munmap(s->buf_start[i], s->buf_len[i]);
447     }
448     av_free(s->buf_start);
449     av_free(s->buf_len);
450 }
451
452 static int v4l2_set_parameters( AVFormatContext *s1, AVFormatParameters *ap )
453 {
454     struct video_data *s = s1->priv_data;
455     struct v4l2_input input;
456     struct v4l2_standard standard;
457     int i;
458
459     if(ap->channel>=0) {
460         /* set tv video input */
461         memset (&input, 0, sizeof (input));
462         input.index = ap->channel;
463         if(ioctl (s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
464             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
465             return AVERROR(EIO);
466         }
467
468         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
469                ap->channel, input.name);
470         if(ioctl (s->fd, VIDIOC_S_INPUT, &input.index) < 0 ) {
471             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
472                    ap->channel);
473             return AVERROR(EIO);
474         }
475     }
476
477     if(ap->standard) {
478         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
479                ap->standard );
480         /* set tv standard */
481         memset (&standard, 0, sizeof (standard));
482         for(i=0;;i++) {
483             standard.index = i;
484             if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
485                 av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
486                        ap->standard);
487                 return AVERROR(EIO);
488             }
489
490             if(!strcasecmp(standard.name, ap->standard)) {
491                 break;
492             }
493         }
494
495         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
496                ap->standard, standard.id);
497         if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
498             av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
499                    ap->standard);
500             return AVERROR(EIO);
501         }
502     }
503
504     return 0;
505 }
506
507 static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
508 {
509     struct video_data *s = s1->priv_data;
510     AVStream *st;
511     int width, height;
512     int res, frame_rate, frame_rate_base;
513     uint32_t desired_format, capabilities;
514
515     if (ap->width <= 0 || ap->height <= 0) {
516         av_log(s1, AV_LOG_ERROR, "Wrong size (%dx%d)\n", ap->width, ap->height);
517         return -1;
518     }
519     if (ap->time_base.den <= 0) {
520         av_log(s1, AV_LOG_ERROR, "Wrong time base (%d)\n", ap->time_base.den);
521         return -1;
522     }
523
524     width = ap->width;
525     height = ap->height;
526     frame_rate = ap->time_base.den;
527     frame_rate_base = ap->time_base.num;
528
529     if((unsigned)width > 32767 || (unsigned)height > 32767) {
530         av_log(s1, AV_LOG_ERROR, "Wrong size (%dx%d)\n", width, height);
531
532         return -1;
533     }
534
535     st = av_new_stream(s1, 0);
536     if (!st) {
537         return AVERROR(ENOMEM);
538     }
539     av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
540
541     s->width = width;
542     s->height = height;
543     s->frame_rate      = frame_rate;
544     s->frame_rate_base = frame_rate_base;
545
546     capabilities = 0;
547     s->fd = device_open(s1, &capabilities);
548     if (s->fd < 0) {
549         return AVERROR(EIO);
550     }
551     av_log(s1, AV_LOG_INFO, "[%d]Capabilities: %x\n", s->fd, capabilities);
552
553     desired_format = fmt_ff2v4l(ap->pix_fmt);
554     if (desired_format == 0 || (device_init(s1, &width, &height, desired_format) < 0)) {
555         int i, done;
556
557         done = 0; i = 0;
558         while (!done) {
559             desired_format = fmt_conversion_table[i].v4l2_fmt;
560             if (device_init(s1, &width, &height, desired_format) < 0) {
561                 desired_format = 0;
562                 i++;
563             } else {
564                done = 1;
565             }
566             if (i == sizeof(fmt_conversion_table) / sizeof(struct fmt_map)) {
567                done = 1;
568             }
569         }
570     }
571     if (desired_format == 0) {
572         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format.\n");
573         close(s->fd);
574
575         return AVERROR(EIO);
576     }
577     s->frame_format = desired_format;
578
579     if( v4l2_set_parameters( s1, ap ) < 0 )
580         return AVERROR(EIO);
581
582     st->codec->pix_fmt = fmt_v4l2ff(desired_format);
583     s->frame_size = avpicture_get_size(st->codec->pix_fmt, width, height);
584     if (capabilities & V4L2_CAP_STREAMING) {
585         s->io_method = io_mmap;
586         res = mmap_init(s1);
587         if (res == 0) {
588             res = mmap_start(s1);
589         }
590     } else {
591         s->io_method = io_read;
592         res = read_init(s1);
593     }
594     if (res < 0) {
595         close(s->fd);
596
597         return AVERROR(EIO);
598     }
599     s->top_field_first = first_field(s->fd);
600
601     st->codec->codec_type = CODEC_TYPE_VIDEO;
602     st->codec->codec_id = CODEC_ID_RAWVIDEO;
603     st->codec->width = width;
604     st->codec->height = height;
605     st->codec->time_base.den = frame_rate;
606     st->codec->time_base.num = frame_rate_base;
607     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
608
609     return 0;
610 }
611
612 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
613 {
614     struct video_data *s = s1->priv_data;
615     int res;
616
617     if (s->io_method == io_mmap) {
618         av_init_packet(pkt);
619         res = mmap_read_frame(s1, pkt);
620     } else if (s->io_method == io_read) {
621         if (av_new_packet(pkt, s->frame_size) < 0)
622             return AVERROR(EIO);
623
624         res = read_frame(s1, pkt);
625     } else {
626         return AVERROR(EIO);
627     }
628     if (res < 0) {
629         return res;
630     }
631
632     if (s1->streams[0]->codec->coded_frame) {
633         s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
634         s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
635     }
636
637     return s->frame_size;
638 }
639
640 static int v4l2_read_close(AVFormatContext *s1)
641 {
642     struct video_data *s = s1->priv_data;
643
644     if (s->io_method == io_mmap) {
645         mmap_close(s);
646     }
647
648     close(s->fd);
649     return 0;
650 }
651
652 AVInputFormat v4l2_demuxer = {
653     "video4linux2",
654     NULL_IF_CONFIG_SMALL("video grab"),
655     sizeof(struct video_data),
656     NULL,
657     v4l2_read_header,
658     v4l2_read_packet,
659     v4l2_read_close,
660     .flags = AVFMT_NOFILE,
661 };