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