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