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