v4l.c 11.8 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1 2
/*
 * Linux video grab interface
3
 * Copyright (c) 2000,2001 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
21

Anton Khirnov's avatar
Anton Khirnov committed
22 23
#include "avdevice.h"

24
#undef __STRICT_ANSI__ //workaround due to broken kernel headers
25
#include "config.h"
26
#include "libavutil/rational.h"
27
#include "libavutil/imgutils.h"
28
#include "libavutil/internal.h"
29 30
#include "libavutil/log.h"
#include "libavutil/opt.h"
31
#include "libavformat/internal.h"
32
#include "libavcodec/dsputil.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
33 34 35 36 37
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/time.h>
38 39
#define _LINUX_TIME_H 1
#include <linux/videodev.h>
40
#include <time.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
41 42

typedef struct {
43
    AVClass *class;
Fabrice Bellard's avatar
Fabrice Bellard committed
44 45 46
    int fd;
    int frame_format; /* see VIDEO_PALETTE_xxx */
    int use_mmap;
47
    AVRational time_base;
48
    int64_t time_frame;
49
    int frame_size;
50 51
    struct video_capability video_cap;
    struct video_audio audio_saved;
52
    struct video_window video_win;
53
    uint8_t *video_buf;
54 55 56
    struct video_mbuf gb_buffers;
    struct video_mmap gb_buf;
    int gb_frame;
57
    int standard;
Fabrice Bellard's avatar
Fabrice Bellard committed
58 59
} VideoData;

60
static const struct {
61 62
    int palette;
    int depth;
63
    enum AVPixelFormat pix_fmt;
64
} video_formats [] = {
65 66 67 68
    {.palette = VIDEO_PALETTE_YUV420P, .depth = 12, .pix_fmt = AV_PIX_FMT_YUV420P },
    {.palette = VIDEO_PALETTE_YUV422,  .depth = 16, .pix_fmt = AV_PIX_FMT_YUYV422 },
    {.palette = VIDEO_PALETTE_UYVY,    .depth = 16, .pix_fmt = AV_PIX_FMT_UYVY422 },
    {.palette = VIDEO_PALETTE_YUYV,    .depth = 16, .pix_fmt = AV_PIX_FMT_YUYV422 },
69
    /* NOTE: v4l uses BGR24, not RGB24 */
70 71 72
    {.palette = VIDEO_PALETTE_RGB24,   .depth = 24, .pix_fmt = AV_PIX_FMT_BGR24   },
    {.palette = VIDEO_PALETTE_RGB565,  .depth = 16, .pix_fmt = AV_PIX_FMT_BGR565  },
    {.palette = VIDEO_PALETTE_GREY,    .depth = 8,  .pix_fmt = AV_PIX_FMT_GRAY8   },
73 74 75
};


76
static int grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
77
{
Fabrice Bellard's avatar
Fabrice Bellard committed
78
    VideoData *s = s1->priv_data;
79
    AVStream *st;
80
    int video_fd;
81
    int desired_palette, desired_depth;
82
    struct video_tuner tuner;
83
    struct video_audio audio;
84
    struct video_picture pict;
85
    int j;
86
    int vformat_num = FF_ARRAY_ELEMS(video_formats);
87

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) {
        av_log(s1, AV_LOG_ERROR, "Wrong time base (%d)\n", ap->time_base.den);
92
        return -1;
93
    }
94
    s->time_base = ap->time_base;
95

96 97
    s->video_win.width = ap->width;
    s->video_win.height = ap->height;
98

99
    st = avformat_new_stream(s1, NULL);
Fabrice Bellard's avatar
Fabrice Bellard committed
100
    if (!st)
101
        return AVERROR(ENOMEM);
102
    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
103

104
    video_fd = open(s1->filename, O_RDWR);
Fabrice Bellard's avatar
Fabrice Bellard committed
105
    if (video_fd < 0) {
106
        av_log(s1, AV_LOG_ERROR, "%s: %s\n", s1->filename, strerror(errno));
107
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
108
    }
109

110
    if (ioctl(video_fd, VIDIOCGCAP, &s->video_cap) < 0) {
111
        av_log(s1, AV_LOG_ERROR, "VIDIOCGCAP: %s\n", strerror(errno));
Fabrice Bellard's avatar
Fabrice Bellard committed
112 113 114
        goto fail;
    }

115
    if (!(s->video_cap.type & VID_TYPE_CAPTURE)) {
116
        av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not handle capture\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
117 118
        goto fail;
    }
119

120 121 122 123 124 125 126 127
    /* no values set, autodetect them */
    if (s->video_win.width <= 0 || s->video_win.height <= 0) {
        if (ioctl(video_fd, VIDIOCGWIN, &s->video_win, sizeof(s->video_win)) < 0) {
            av_log(s1, AV_LOG_ERROR, "VIDIOCGWIN: %s\n", strerror(errno));
            goto fail;
        }
    }

128
    if(av_image_check_size(s->video_win.width, s->video_win.height, 0, s1) < 0)
129 130
        return -1;

131
    desired_palette = -1;
132
    desired_depth = -1;
133 134 135 136 137 138
    for (j = 0; j < vformat_num; j++) {
        if (ap->pix_fmt == video_formats[j].pix_fmt) {
            desired_palette = video_formats[j].palette;
            desired_depth = video_formats[j].depth;
            break;
        }
139
    }
140 141

    /* set tv standard */
142 143
    if (!ioctl(video_fd, VIDIOCGTUNER, &tuner)) {
        tuner.mode = s->standard;
144
        ioctl(video_fd, VIDIOCSTUNER, &tuner);
145
    }
146

Fabrice Bellard's avatar
Fabrice Bellard committed
147
    /* unmute audio */
148
    audio.audio = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
149
    ioctl(video_fd, VIDIOCGAUDIO, &audio);
150
    memcpy(&s->audio_saved, &audio, sizeof(audio));
Fabrice Bellard's avatar
Fabrice Bellard committed
151 152 153
    audio.flags &= ~VIDEO_AUDIO_MUTE;
    ioctl(video_fd, VIDIOCSAUDIO, &audio);

154
    ioctl(video_fd, VIDIOCGPICT, &pict);
155
    ff_dlog(s1, "v4l: colour=%d hue=%d brightness=%d constrast=%d whiteness=%d\n",
156
            pict.colour, pict.hue, pict.brightness, pict.contrast, pict.whiteness);
157 158
    /* try to choose a suitable video format */
    pict.palette = desired_palette;
159
    pict.depth= desired_depth;
160
    if (desired_palette == -1 || ioctl(video_fd, VIDIOCSPICT, &pict) < 0) {
161 162 163 164 165
        for (j = 0; j < vformat_num; j++) {
            pict.palette = video_formats[j].palette;
            pict.depth = video_formats[j].depth;
            if (-1 != ioctl(video_fd, VIDIOCSPICT, &pict))
                break;
166
        }
167 168
        if (j >= vformat_num)
            goto fail1;
169 170
    }

171
    if (ioctl(video_fd, VIDIOCGMBUF, &s->gb_buffers) < 0) {
Fabrice Bellard's avatar
Fabrice Bellard committed
172 173 174
        /* try to use read based access */
        int val;

175 176 177 178
        s->video_win.x = 0;
        s->video_win.y = 0;
        s->video_win.chromakey = -1;
        s->video_win.flags = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
179

180 181 182 183
        if (ioctl(video_fd, VIDIOCSWIN, s->video_win) < 0) {
            av_log(s1, AV_LOG_ERROR, "VIDIOCSWIN: %s\n", strerror(errno));
            goto fail;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
184 185 186 187

        s->frame_format = pict.palette;

        val = 1;
188 189 190 191
        if (ioctl(video_fd, VIDIOCCAPTURE, &val) < 0) {
            av_log(s1, AV_LOG_ERROR, "VIDIOCCAPTURE: %s\n", strerror(errno));
            goto fail;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
192

193
        s->time_frame = av_gettime() * s->time_base.den / s->time_base.num;
Fabrice Bellard's avatar
Fabrice Bellard committed
194 195
        s->use_mmap = 0;
    } else {
196
        s->video_buf = mmap(0, s->gb_buffers.size, PROT_READ|PROT_WRITE, MAP_SHARED, video_fd, 0);
197
        if ((unsigned char*)-1 == s->video_buf) {
198
            s->video_buf = mmap(0, s->gb_buffers.size, PROT_READ|PROT_WRITE, MAP_PRIVATE, video_fd, 0);
199
            if ((unsigned char*)-1 == s->video_buf) {
200
                av_log(s1, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
201 202
                goto fail;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
203
        }
204
        s->gb_frame = 0;
205
        s->time_frame = av_gettime() * s->time_base.den / s->time_base.num;
206

Fabrice Bellard's avatar
Fabrice Bellard committed
207
        /* start to grab the first frame */
208
        s->gb_buf.frame = s->gb_frame % s->gb_buffers.frames;
209 210
        s->gb_buf.height = s->video_win.height;
        s->gb_buf.width = s->video_win.width;
211 212
        s->gb_buf.format = pict.palette;

213
        if (ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
Fabrice Bellard's avatar
Fabrice Bellard committed
214 215
            if (errno != EAGAIN) {
            fail1:
216
                av_log(s1, AV_LOG_ERROR, "VIDIOCMCAPTURE: %s\n", strerror(errno));
Fabrice Bellard's avatar
Fabrice Bellard committed
217
            } else {
218
                av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not receive any video signal\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
219 220 221
            }
            goto fail;
        }
222 223 224 225
        for (j = 1; j < s->gb_buffers.frames; j++) {
          s->gb_buf.frame = j;
          ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);
        }
226
        s->frame_format = s->gb_buf.format;
Fabrice Bellard's avatar
Fabrice Bellard committed
227 228 229
        s->use_mmap = 1;
    }

230 231
    for (j = 0; j < vformat_num; j++) {
        if (s->frame_format == video_formats[j].palette) {
232
            s->frame_size = s->video_win.width * s->video_win.height * video_formats[j].depth / 8;
233 234 235
            st->codec->pix_fmt = video_formats[j].pix_fmt;
            break;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
236
    }
237 238 239 240

    if (j >= vformat_num)
        goto fail;

Fabrice Bellard's avatar
Fabrice Bellard committed
241
    s->fd = video_fd;
242

243
    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
244
    st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
245 246
    st->codec->width = s->video_win.width;
    st->codec->height = s->video_win.height;
247
    st->codec->time_base = s->time_base;
248
    st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
249

Fabrice Bellard's avatar
Fabrice Bellard committed
250 251
    return 0;
 fail:
252 253
    if (video_fd >= 0)
        close(video_fd);
254
    return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
255 256
}

257
static int v4l_mm_read_picture(VideoData *s, uint8_t *buf)
Fabrice Bellard's avatar
Fabrice Bellard committed
258
{
259
    uint8_t *ptr;
Fabrice Bellard's avatar
Fabrice Bellard committed
260

261 262 263 264 265 266
    while (ioctl(s->fd, VIDIOCSYNC, &s->gb_frame) < 0 &&
           (errno == EAGAIN || errno == EINTR));

    ptr = s->video_buf + s->gb_buffers.offsets[s->gb_frame];
    memcpy(buf, ptr, s->frame_size);

267
    /* Setup to capture the next frame */
268
    s->gb_buf.frame = s->gb_frame;
269
    if (ioctl(s->fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
270
        if (errno == EAGAIN)
271
            av_log(NULL, AV_LOG_ERROR, "Cannot Sync\n");
272
        else
273
            av_log(NULL, AV_LOG_ERROR, "VIDIOCMCAPTURE: %s\n", strerror(errno));
274
        return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
275
    }
276 277

    /* This is now the grabbing frame */
278
    s->gb_frame = (s->gb_frame + 1) % s->gb_buffers.frames;
279

280
    return s->frame_size;
Fabrice Bellard's avatar
Fabrice Bellard committed
281 282
}

283
static int grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
Fabrice Bellard's avatar
Fabrice Bellard committed
284
{
285
    VideoData *s = s1->priv_data;
286
    int64_t curtime, delay;
287
    struct timespec ts;
288 289

    /* Calculate the time of the next frame */
290
    s->time_frame += INT64_C(1000000);
Fabrice Bellard's avatar
Fabrice Bellard committed
291 292

    /* wait based on the frame rate */
293
    for(;;) {
294
        curtime = av_gettime();
295
        delay = s->time_frame * s->time_base.num / s->time_base.den - curtime;
296
        if (delay <= 0) {
297
            if (delay < INT64_C(-1000000) * s->time_base.num / s->time_base.den) {
298
                /* printf("grabbing is %d frames late (dropping)\n", (int) -(delay / 16666)); */
299
                s->time_frame += INT64_C(1000000);
300
            }
301
            break;
302
        }
303 304 305 306 307 308
        ts.tv_sec = delay / 1000000;
        ts.tv_nsec = (delay % 1000000) * 1000;
        nanosleep(&ts, NULL);
    }

    if (av_new_packet(pkt, s->frame_size) < 0)
309
        return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
310

Luca Abeni's avatar
Luca Abeni committed
311
    pkt->pts = curtime;
312

Fabrice Bellard's avatar
Fabrice Bellard committed
313
    /* read one frame */
314
    if (s->use_mmap) {
315
        return v4l_mm_read_picture(s, pkt->data);
Fabrice Bellard's avatar
Fabrice Bellard committed
316
    } else {
317
        if (read(s->fd, pkt->data, pkt->size) != pkt->size)
318
            return AVERROR(EIO);
319
        return s->frame_size;
Fabrice Bellard's avatar
Fabrice Bellard committed
320 321 322
    }
}

323
static int grab_read_close(AVFormatContext *s1)
Fabrice Bellard's avatar
Fabrice Bellard committed
324
{
325
    VideoData *s = s1->priv_data;
326 327

    if (s->use_mmap)
328
        munmap(s->video_buf, s->gb_buffers.size);
329

330 331 332 333
    /* mute audio. we must force it because the BTTV driver does not
       return its state correctly */
    s->audio_saved.flags |= VIDEO_AUDIO_MUTE;
    ioctl(s->fd, VIDIOCSAUDIO, &s->audio_saved);
334

Fabrice Bellard's avatar
Fabrice Bellard committed
335 336 337 338
    close(s->fd);
    return 0;
}

339
static const AVOption options[] = {
340
    { "standard", "", offsetof(VideoData, standard), AV_OPT_TYPE_INT, {.i64 = VIDEO_MODE_NTSC}, VIDEO_MODE_PAL, VIDEO_MODE_NTSC, AV_OPT_FLAG_DECODING_PARAM, "standard" },
341 342 343
    { "PAL",   "", 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_MODE_PAL},   0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
    { "SECAM", "", 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_MODE_SECAM}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
    { "NTSC",  "", 0, AV_OPT_TYPE_CONST, {.i64 = VIDEO_MODE_NTSC},  0, 0, AV_OPT_FLAG_DECODING_PARAM, "standard" },
344 345 346 347 348 349 350 351
    { NULL },
};

static const AVClass v4l_class = {
    .class_name = "V4L indev",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
352
    .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
353 354
};

355
AVInputFormat ff_v4l_demuxer = {
356
    .name           = "video4linux,v4l",
357 358 359 360 361 362 363
    .long_name      = NULL_IF_CONFIG_SMALL("Video4Linux device grab"),
    .priv_data_size = sizeof(VideoData),
    .read_header    = grab_read_header,
    .read_packet    = grab_read_packet,
    .read_close     = grab_read_close,
    .flags          = AVFMT_NOFILE,
    .priv_class     = &v4l_class,
Fabrice Bellard's avatar
Fabrice Bellard committed
364
};