]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavdevice/v4l.c
1978ab4bb245db3282c859a65a6f8edfd305d3dc
[frescor/ffmpeg.git] / libavdevice / v4l.c
1 /*
2  * Linux video grab interface
3  * Copyright (c) 2000,2001 Fabrice Bellard.
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 "libavformat/avformat.h"
26 #include "libavcodec/dsputil.h"
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/ioctl.h>
30 #include <sys/mman.h>
31 #include <sys/time.h>
32 #define _LINUX_TIME_H 1
33 #include <linux/videodev.h>
34 #include <time.h>
35 #include <strings.h>
36
37 typedef struct {
38     int fd;
39     int frame_format; /* see VIDEO_PALETTE_xxx */
40     int use_mmap;
41     AVRational time_base;
42     int64_t time_frame;
43     int frame_size;
44     struct video_capability video_cap;
45     struct video_audio audio_saved;
46     struct video_window video_win;
47     uint8_t *video_buf;
48     struct video_mbuf gb_buffers;
49     struct video_mmap gb_buf;
50     int gb_frame;
51 } VideoData;
52
53 static const struct {
54     int palette;
55     int depth;
56     enum PixelFormat pix_fmt;
57 } video_formats [] = {
58     {.palette = VIDEO_PALETTE_YUV420P, .depth = 12, .pix_fmt = PIX_FMT_YUV420P },
59     {.palette = VIDEO_PALETTE_YUV422,  .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
60     {.palette = VIDEO_PALETTE_UYVY,    .depth = 16, .pix_fmt = PIX_FMT_UYVY422 },
61     {.palette = VIDEO_PALETTE_YUYV,    .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
62     /* NOTE: v4l uses BGR24, not RGB24 */
63     {.palette = VIDEO_PALETTE_RGB24,   .depth = 24, .pix_fmt = PIX_FMT_BGR24   },
64     {.palette = VIDEO_PALETTE_RGB565,  .depth = 16, .pix_fmt = PIX_FMT_BGR565  },
65     {.palette = VIDEO_PALETTE_GREY,    .depth = 8,  .pix_fmt = PIX_FMT_GRAY8   },
66 };
67
68
69 static int grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
70 {
71     VideoData *s = s1->priv_data;
72     AVStream *st;
73     int video_fd, frame_size;
74     int desired_palette, desired_depth;
75     struct video_tuner tuner;
76     struct video_audio audio;
77     struct video_picture pict;
78     int j;
79     int vformat_num = FF_ARRAY_ELEMS(video_formats);
80
81     if (ap->width <= 0 || ap->height <= 0) {
82         av_log(s1, AV_LOG_ERROR, "Wrong size (%dx%d)\n", ap->width, ap->height);
83         return -1;
84     }
85     if (ap->time_base.den <= 0) {
86         av_log(s1, AV_LOG_ERROR, "Wrong time base (%d)\n", ap->time_base.den);
87         return -1;
88     }
89     s->time_base = ap->time_base;
90
91     if((unsigned)ap->width > 32767 || (unsigned)ap->height > 32767) {
92         av_log(s1, AV_LOG_ERROR, "Capture size is out of range: %dx%d\n",
93             ap->width, ap->height);
94         return -1;
95     }
96     s->video_win.width = ap->width;
97     s->video_win.height = ap->height;
98
99     st = av_new_stream(s1, 0);
100     if (!st)
101         return AVERROR(ENOMEM);
102     av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
103
104     video_fd = open(s1->filename, O_RDWR);
105     if (video_fd < 0) {
106         av_log(s1, AV_LOG_ERROR, "%s: %s\n", s1->filename, strerror(errno));
107         goto fail;
108     }
109
110     if (ioctl(video_fd,VIDIOCGCAP, &s->video_cap) < 0) {
111         av_log(s1, AV_LOG_ERROR, "VIDIOCGCAP: %s\n", strerror(errno));
112         goto fail;
113     }
114
115     if (!(s->video_cap.type & VID_TYPE_CAPTURE)) {
116         av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not handle capture\n");
117         goto fail;
118     }
119
120     desired_palette = -1;
121     desired_depth = -1;
122     for (j = 0; j < vformat_num; j++) {
123         if (ap->pix_fmt == video_formats[j].pix_fmt) {
124             desired_palette = video_formats[j].palette;
125             desired_depth = video_formats[j].depth;
126             break;
127         }
128     }
129
130     /* set tv standard */
131     if (ap->standard && !ioctl(video_fd, VIDIOCGTUNER, &tuner)) {
132         if (!strcasecmp(ap->standard, "pal"))
133             tuner.mode = VIDEO_MODE_PAL;
134         else if (!strcasecmp(ap->standard, "secam"))
135             tuner.mode = VIDEO_MODE_SECAM;
136         else
137             tuner.mode = VIDEO_MODE_NTSC;
138         ioctl(video_fd, VIDIOCSTUNER, &tuner);
139     }
140
141     /* unmute audio */
142     audio.audio = 0;
143     ioctl(video_fd, VIDIOCGAUDIO, &audio);
144     memcpy(&s->audio_saved, &audio, sizeof(audio));
145     audio.flags &= ~VIDEO_AUDIO_MUTE;
146     ioctl(video_fd, VIDIOCSAUDIO, &audio);
147
148     ioctl(video_fd, VIDIOCGPICT, &pict);
149 #if 0
150     printf("v4l: colour=%d hue=%d brightness=%d constrast=%d whiteness=%d\n",
151            pict.colour,
152            pict.hue,
153            pict.brightness,
154            pict.contrast,
155            pict.whiteness);
156 #endif
157     /* try to choose a suitable video format */
158     pict.palette = desired_palette;
159     pict.depth= desired_depth;
160     if (desired_palette == -1 || ioctl(video_fd, VIDIOCSPICT, &pict) < 0) {
161         for (j = 0; j < vformat_num; j++) {
162             pict.palette = video_formats[j].palette;
163             pict.depth = video_formats[j].depth;
164             if (-1 != ioctl(video_fd, VIDIOCSPICT, &pict))
165                 break;
166         }
167         if (j >= vformat_num)
168             goto fail1;
169     }
170
171     if (ioctl(video_fd,VIDIOCGMBUF,&s->gb_buffers) < 0) {
172         /* try to use read based access */
173         int val;
174
175         s->video_win.x = 0;
176         s->video_win.y = 0;
177         s->video_win.chromakey = -1;
178         s->video_win.flags = 0;
179
180         ioctl(video_fd, VIDIOCSWIN, s->video_win);
181
182         s->frame_format = pict.palette;
183
184         val = 1;
185         ioctl(video_fd, VIDIOCCAPTURE, &val);
186
187         s->time_frame = av_gettime() * s->time_base.den / s->time_base.num;
188         s->use_mmap = 0;
189     } else {
190         s->video_buf = mmap(0,s->gb_buffers.size,PROT_READ|PROT_WRITE,MAP_SHARED,video_fd,0);
191         if ((unsigned char*)-1 == s->video_buf) {
192             s->video_buf = mmap(0,s->gb_buffers.size,PROT_READ|PROT_WRITE,MAP_PRIVATE,video_fd,0);
193             if ((unsigned char*)-1 == s->video_buf) {
194                 av_log(s1, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
195                 goto fail;
196             }
197         }
198         s->gb_frame = 0;
199         s->time_frame = av_gettime() * s->time_base.den / s->time_base.num;
200
201         /* start to grab the first frame */
202         s->gb_buf.frame = s->gb_frame % s->gb_buffers.frames;
203         s->gb_buf.height = s->video_win.height;
204         s->gb_buf.width = s->video_win.width;
205         s->gb_buf.format = pict.palette;
206
207         if (ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
208             if (errno != EAGAIN) {
209             fail1:
210                 av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not support suitable format\n");
211             } else {
212                 av_log(s1, AV_LOG_ERROR,"Fatal: grab device does not receive any video signal\n");
213             }
214             goto fail;
215         }
216         for (j = 1; j < s->gb_buffers.frames; j++) {
217           s->gb_buf.frame = j;
218           ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);
219         }
220         s->frame_format = s->gb_buf.format;
221         s->use_mmap = 1;
222     }
223
224     for (j = 0; j < vformat_num; j++) {
225         if (s->frame_format == video_formats[j].palette) {
226             frame_size = s->video_win.width * s->video_win.height * video_formats[j].depth / 8;
227             st->codec->pix_fmt = video_formats[j].pix_fmt;
228             break;
229         }
230     }
231
232     if (j >= vformat_num)
233         goto fail;
234
235     s->fd = video_fd;
236     s->frame_size = frame_size;
237
238     st->codec->codec_type = CODEC_TYPE_VIDEO;
239     st->codec->codec_id = CODEC_ID_RAWVIDEO;
240     st->codec->width = s->video_win.width;
241     st->codec->height = s->video_win.height;
242     st->codec->time_base = s->time_base;
243     st->codec->bit_rate = frame_size * 1/av_q2d(st->codec->time_base) * 8;
244
245     return 0;
246  fail:
247     if (video_fd >= 0)
248         close(video_fd);
249     return AVERROR(EIO);
250 }
251
252 static int v4l_mm_read_picture(VideoData *s, uint8_t *buf)
253 {
254     uint8_t *ptr;
255
256     while (ioctl(s->fd, VIDIOCSYNC, &s->gb_frame) < 0 &&
257            (errno == EAGAIN || errno == EINTR));
258
259     ptr = s->video_buf + s->gb_buffers.offsets[s->gb_frame];
260     memcpy(buf, ptr, s->frame_size);
261
262     /* Setup to capture the next frame */
263     s->gb_buf.frame = s->gb_frame;
264     if (ioctl(s->fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
265         if (errno == EAGAIN)
266             av_log(NULL, AV_LOG_ERROR, "Cannot Sync\n");
267         else
268             av_log(NULL, AV_LOG_ERROR, "VIDIOCMCAPTURE: %s\n", strerror(errno));
269         return AVERROR(EIO);
270     }
271
272     /* This is now the grabbing frame */
273     s->gb_frame = (s->gb_frame + 1) % s->gb_buffers.frames;
274
275     return s->frame_size;
276 }
277
278 static int grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
279 {
280     VideoData *s = s1->priv_data;
281     int64_t curtime, delay;
282     struct timespec ts;
283
284     /* Calculate the time of the next frame */
285     s->time_frame += INT64_C(1000000);
286
287     /* wait based on the frame rate */
288     for(;;) {
289         curtime = av_gettime();
290         delay = s->time_frame * s->time_base.num / s->time_base.den - curtime;
291         if (delay <= 0) {
292             if (delay < INT64_C(-1000000) * s->time_base.num / s->time_base.den) {
293                 /* printf("grabbing is %d frames late (dropping)\n", (int) -(delay / 16666)); */
294                 s->time_frame += INT64_C(1000000);
295             }
296             break;
297         }
298         ts.tv_sec = delay / 1000000;
299         ts.tv_nsec = (delay % 1000000) * 1000;
300         nanosleep(&ts, NULL);
301     }
302
303     if (av_new_packet(pkt, s->frame_size) < 0)
304         return AVERROR(EIO);
305
306     pkt->pts = curtime;
307
308     /* read one frame */
309     if (s->use_mmap) {
310         return v4l_mm_read_picture(s, pkt->data);
311     } else {
312         if (read(s->fd, pkt->data, pkt->size) != pkt->size)
313             return AVERROR(EIO);
314         return s->frame_size;
315     }
316 }
317
318 static int grab_read_close(AVFormatContext *s1)
319 {
320     VideoData *s = s1->priv_data;
321
322     if (s->use_mmap)
323         munmap(s->video_buf, s->gb_buffers.size);
324
325     /* mute audio. we must force it because the BTTV driver does not
326        return its state correctly */
327     s->audio_saved.flags |= VIDEO_AUDIO_MUTE;
328     ioctl(s->fd, VIDIOCSAUDIO, &s->audio_saved);
329
330     close(s->fd);
331     return 0;
332 }
333
334 AVInputFormat v4l_demuxer = {
335     "video4linux",
336     NULL_IF_CONFIG_SMALL("video grab"),
337     sizeof(VideoData),
338     NULL,
339     grab_read_header,
340     grab_read_packet,
341     grab_read_close,
342     .flags = AVFMT_NOFILE,
343 };