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