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