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