]> git.sesse.net Git - ffmpeg/blob - libavdevice/v4l.c
libdc1394: add a private option for channel.
[ffmpeg] / libavdevice / v4l.c
1 /*
2  * Linux video grab interface
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #undef __STRICT_ANSI__ //workaround due to broken kernel headers
23 #include "config.h"
24 #include "libavutil/rational.h"
25 #include "libavutil/imgutils.h"
26 #include "libavutil/log.h"
27 #include "libavutil/opt.h"
28 #include "libavformat/avformat.h"
29 #include "libavcodec/dsputil.h"
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <sys/ioctl.h>
33 #include <sys/mman.h>
34 #include <sys/time.h>
35 #define _LINUX_TIME_H 1
36 #include <linux/videodev.h>
37 #include <time.h>
38 #include <strings.h>
39
40 typedef struct {
41     AVClass *class;
42     int fd;
43     int frame_format; /* see VIDEO_PALETTE_xxx */
44     int use_mmap;
45     AVRational time_base;
46     int64_t time_frame;
47     int frame_size;
48     struct video_capability video_cap;
49     struct video_audio audio_saved;
50     struct video_window video_win;
51     uint8_t *video_buf;
52     struct video_mbuf gb_buffers;
53     struct video_mmap gb_buf;
54     int gb_frame;
55     int standard;
56 } VideoData;
57
58 static const struct {
59     int palette;
60     int depth;
61     enum PixelFormat pix_fmt;
62 } video_formats [] = {
63     {.palette = VIDEO_PALETTE_YUV420P, .depth = 12, .pix_fmt = PIX_FMT_YUV420P },
64     {.palette = VIDEO_PALETTE_YUV422,  .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
65     {.palette = VIDEO_PALETTE_UYVY,    .depth = 16, .pix_fmt = PIX_FMT_UYVY422 },
66     {.palette = VIDEO_PALETTE_YUYV,    .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
67     /* NOTE: v4l uses BGR24, not RGB24 */
68     {.palette = VIDEO_PALETTE_RGB24,   .depth = 24, .pix_fmt = PIX_FMT_BGR24   },
69     {.palette = VIDEO_PALETTE_RGB565,  .depth = 16, .pix_fmt = PIX_FMT_BGR565  },
70     {.palette = VIDEO_PALETTE_GREY,    .depth = 8,  .pix_fmt = PIX_FMT_GRAY8   },
71 };
72
73
74 static int grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
75 {
76     VideoData *s = s1->priv_data;
77     AVStream *st;
78     int video_fd;
79     int desired_palette, desired_depth;
80     struct video_tuner tuner;
81     struct video_audio audio;
82     struct video_picture pict;
83     int j;
84     int vformat_num = FF_ARRAY_ELEMS(video_formats);
85
86     if (ap->time_base.den <= 0) {
87         av_log(s1, AV_LOG_ERROR, "Wrong time base (%d)\n", ap->time_base.den);
88         return -1;
89     }
90     s->time_base = ap->time_base;
91
92     s->video_win.width = ap->width;
93     s->video_win.height = ap->height;
94
95     st = av_new_stream(s1, 0);
96     if (!st)
97         return AVERROR(ENOMEM);
98     av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
99
100     video_fd = open(s1->filename, O_RDWR);
101     if (video_fd < 0) {
102         av_log(s1, AV_LOG_ERROR, "%s: %s\n", s1->filename, strerror(errno));
103         goto fail;
104     }
105
106     if (ioctl(video_fd, VIDIOCGCAP, &s->video_cap) < 0) {
107         av_log(s1, AV_LOG_ERROR, "VIDIOCGCAP: %s\n", strerror(errno));
108         goto fail;
109     }
110
111     if (!(s->video_cap.type & VID_TYPE_CAPTURE)) {
112         av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not handle capture\n");
113         goto fail;
114     }
115
116     /* no values set, autodetect them */
117     if (s->video_win.width <= 0 || s->video_win.height <= 0) {
118         if (ioctl(video_fd, VIDIOCGWIN, &s->video_win, sizeof(s->video_win)) < 0) {
119             av_log(s1, AV_LOG_ERROR, "VIDIOCGWIN: %s\n", strerror(errno));
120             goto fail;
121         }
122     }
123
124     if(av_image_check_size(s->video_win.width, s->video_win.height, 0, s1) < 0)
125         return -1;
126
127     desired_palette = -1;
128     desired_depth = -1;
129     for (j = 0; j < vformat_num; j++) {
130         if (ap->pix_fmt == video_formats[j].pix_fmt) {
131             desired_palette = video_formats[j].palette;
132             desired_depth = video_formats[j].depth;
133             break;
134         }
135     }
136
137     /* set tv standard */
138     if (!ioctl(video_fd, VIDIOCGTUNER, &tuner)) {
139 #if FF_API_FORMAT_PARAMETERS
140         if (ap->standard) {
141             if (!strcasecmp(ap->standard, "pal"))
142                 s->standard = VIDEO_MODE_PAL;
143             else if (!strcasecmp(ap->standard, "secam"))
144                 s->standard = VIDEO_MODE_SECAM;
145             else
146                 s->standard = VIDEO_MODE_NTSC;
147         }
148 #endif
149         tuner.mode = s->standard;
150         ioctl(video_fd, VIDIOCSTUNER, &tuner);
151     }
152
153     /* unmute audio */
154     audio.audio = 0;
155     ioctl(video_fd, VIDIOCGAUDIO, &audio);
156     memcpy(&s->audio_saved, &audio, sizeof(audio));
157     audio.flags &= ~VIDEO_AUDIO_MUTE;
158     ioctl(video_fd, VIDIOCSAUDIO, &audio);
159
160     ioctl(video_fd, VIDIOCGPICT, &pict);
161     av_dlog(s1, "v4l: colour=%d hue=%d brightness=%d constrast=%d whiteness=%d\n",
162             pict.colour, pict.hue, pict.brightness, pict.contrast, pict.whiteness);
163     /* try to choose a suitable video format */
164     pict.palette = desired_palette;
165     pict.depth= desired_depth;
166     if (desired_palette == -1 || ioctl(video_fd, VIDIOCSPICT, &pict) < 0) {
167         for (j = 0; j < vformat_num; j++) {
168             pict.palette = video_formats[j].palette;
169             pict.depth = video_formats[j].depth;
170             if (-1 != ioctl(video_fd, VIDIOCSPICT, &pict))
171                 break;
172         }
173         if (j >= vformat_num)
174             goto fail1;
175     }
176
177     if (ioctl(video_fd, VIDIOCGMBUF, &s->gb_buffers) < 0) {
178         /* try to use read based access */
179         int val;
180
181         s->video_win.x = 0;
182         s->video_win.y = 0;
183         s->video_win.chromakey = -1;
184         s->video_win.flags = 0;
185
186         if (ioctl(video_fd, VIDIOCSWIN, s->video_win) < 0) {
187             av_log(s1, AV_LOG_ERROR, "VIDIOCSWIN: %s\n", strerror(errno));
188             goto fail;
189         }
190
191         s->frame_format = pict.palette;
192
193         val = 1;
194         if (ioctl(video_fd, VIDIOCCAPTURE, &val) < 0) {
195             av_log(s1, AV_LOG_ERROR, "VIDIOCCAPTURE: %s\n", strerror(errno));
196             goto fail;
197         }
198
199         s->time_frame = av_gettime() * s->time_base.den / s->time_base.num;
200         s->use_mmap = 0;
201     } else {
202         s->video_buf = mmap(0, s->gb_buffers.size, PROT_READ|PROT_WRITE, MAP_SHARED, video_fd, 0);
203         if ((unsigned char*)-1 == s->video_buf) {
204             s->video_buf = mmap(0, s->gb_buffers.size, PROT_READ|PROT_WRITE, MAP_PRIVATE, video_fd, 0);
205             if ((unsigned char*)-1 == s->video_buf) {
206                 av_log(s1, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
207                 goto fail;
208             }
209         }
210         s->gb_frame = 0;
211         s->time_frame = av_gettime() * s->time_base.den / s->time_base.num;
212
213         /* start to grab the first frame */
214         s->gb_buf.frame = s->gb_frame % s->gb_buffers.frames;
215         s->gb_buf.height = s->video_win.height;
216         s->gb_buf.width = s->video_win.width;
217         s->gb_buf.format = pict.palette;
218
219         if (ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
220             if (errno != EAGAIN) {
221             fail1:
222                 av_log(s1, AV_LOG_ERROR, "VIDIOCMCAPTURE: %s\n", strerror(errno));
223             } else {
224                 av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not receive any video signal\n");
225             }
226             goto fail;
227         }
228         for (j = 1; j < s->gb_buffers.frames; j++) {
229           s->gb_buf.frame = j;
230           ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);
231         }
232         s->frame_format = s->gb_buf.format;
233         s->use_mmap = 1;
234     }
235
236     for (j = 0; j < vformat_num; j++) {
237         if (s->frame_format == video_formats[j].palette) {
238             s->frame_size = s->video_win.width * s->video_win.height * video_formats[j].depth / 8;
239             st->codec->pix_fmt = video_formats[j].pix_fmt;
240             break;
241         }
242     }
243
244     if (j >= vformat_num)
245         goto fail;
246
247     s->fd = video_fd;
248
249     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
250     st->codec->codec_id = CODEC_ID_RAWVIDEO;
251     st->codec->width = s->video_win.width;
252     st->codec->height = s->video_win.height;
253     st->codec->time_base = s->time_base;
254     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
255
256     return 0;
257  fail:
258     if (video_fd >= 0)
259         close(video_fd);
260     return AVERROR(EIO);
261 }
262
263 static int v4l_mm_read_picture(VideoData *s, uint8_t *buf)
264 {
265     uint8_t *ptr;
266
267     while (ioctl(s->fd, VIDIOCSYNC, &s->gb_frame) < 0 &&
268            (errno == EAGAIN || errno == EINTR));
269
270     ptr = s->video_buf + s->gb_buffers.offsets[s->gb_frame];
271     memcpy(buf, ptr, s->frame_size);
272
273     /* Setup to capture the next frame */
274     s->gb_buf.frame = s->gb_frame;
275     if (ioctl(s->fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
276         if (errno == EAGAIN)
277             av_log(NULL, AV_LOG_ERROR, "Cannot Sync\n");
278         else
279             av_log(NULL, AV_LOG_ERROR, "VIDIOCMCAPTURE: %s\n", strerror(errno));
280         return AVERROR(EIO);
281     }
282
283     /* This is now the grabbing frame */
284     s->gb_frame = (s->gb_frame + 1) % s->gb_buffers.frames;
285
286     return s->frame_size;
287 }
288
289 static int grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
290 {
291     VideoData *s = s1->priv_data;
292     int64_t curtime, delay;
293     struct timespec ts;
294
295     /* Calculate the time of the next frame */
296     s->time_frame += INT64_C(1000000);
297
298     /* wait based on the frame rate */
299     for(;;) {
300         curtime = av_gettime();
301         delay = s->time_frame * s->time_base.num / s->time_base.den - curtime;
302         if (delay <= 0) {
303             if (delay < INT64_C(-1000000) * s->time_base.num / s->time_base.den) {
304                 /* printf("grabbing is %d frames late (dropping)\n", (int) -(delay / 16666)); */
305                 s->time_frame += INT64_C(1000000);
306             }
307             break;
308         }
309         ts.tv_sec = delay / 1000000;
310         ts.tv_nsec = (delay % 1000000) * 1000;
311         nanosleep(&ts, NULL);
312     }
313
314     if (av_new_packet(pkt, s->frame_size) < 0)
315         return AVERROR(EIO);
316
317     pkt->pts = curtime;
318
319     /* read one frame */
320     if (s->use_mmap) {
321         return v4l_mm_read_picture(s, pkt->data);
322     } else {
323         if (read(s->fd, pkt->data, pkt->size) != pkt->size)
324             return AVERROR(EIO);
325         return s->frame_size;
326     }
327 }
328
329 static int grab_read_close(AVFormatContext *s1)
330 {
331     VideoData *s = s1->priv_data;
332
333     if (s->use_mmap)
334         munmap(s->video_buf, s->gb_buffers.size);
335
336     /* mute audio. we must force it because the BTTV driver does not
337        return its state correctly */
338     s->audio_saved.flags |= VIDEO_AUDIO_MUTE;
339     ioctl(s->fd, VIDIOCSAUDIO, &s->audio_saved);
340
341     close(s->fd);
342     return 0;
343 }
344
345 static const AVOption options[] = {
346     { "standard", "", offsetof(VideoData, standard), FF_OPT_TYPE_INT, {.dbl = VIDEO_MODE_NTSC}, VIDEO_MODE_PAL, VIDEO_MODE_NTSC, AV_OPT_FLAG_DECODING_PARAM, "standard" },
347     { "PAL",   "", 0, FF_OPT_TYPE_CONST, {.dbl = VIDEO_MODE_PAL},   0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
348     { "SECAM", "", 0, FF_OPT_TYPE_CONST, {.dbl = VIDEO_MODE_SECAM}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
349     { "NTSC",  "", 0, FF_OPT_TYPE_CONST, {.dbl = VIDEO_MODE_NTSC},  0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
350     { NULL },
351 };
352
353 static const AVClass v4l_class = {
354     .class_name = "V4L indev",
355     .item_name  = av_default_item_name,
356     .option     = options,
357     .version    = LIBAVUTIL_VERSION_INT,
358 };
359
360 AVInputFormat ff_v4l_demuxer = {
361     "video4linux",
362     NULL_IF_CONFIG_SMALL("Video4Linux device grab"),
363     sizeof(VideoData),
364     NULL,
365     grab_read_header,
366     grab_read_packet,
367     grab_read_close,
368     .flags = AVFMT_NOFILE,
369     .priv_class = &v4l_class,
370 };