v4l.c 10.8 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1 2
/*
 * Linux video grab interface
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
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
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
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

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

typedef struct {
    int fd;
    int frame_format; /* see VIDEO_PALETTE_xxx */
    int use_mmap;
    int width, height;
41
    int frame_rate;
42
    int frame_rate_base;
43
    int64_t time_frame;
44
    int frame_size;
45 46
    struct video_capability video_cap;
    struct video_audio audio_saved;
47
    uint8_t *video_buf;
48 49 50
    struct video_mbuf gb_buffers;
    struct video_mmap gb_buf;
    int gb_frame;
Fabrice Bellard's avatar
Fabrice Bellard committed
51 52
} VideoData;

53
static const struct {
54 55 56 57 58 59
    int palette;
    int depth;
    enum PixelFormat pix_fmt;
} video_formats [] = {
    {.palette = VIDEO_PALETTE_YUV420P, .depth = 12, .pix_fmt = PIX_FMT_YUV420P },
    {.palette = VIDEO_PALETTE_YUV422,  .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
60 61
    {.palette = VIDEO_PALETTE_UYVY,    .depth = 16, .pix_fmt = PIX_FMT_UYVY422 },
    {.palette = VIDEO_PALETTE_YUYV,    .depth = 16, .pix_fmt = PIX_FMT_YUYV422 },
62 63
    /* NOTE: v4l uses BGR24, not RGB24 */
    {.palette = VIDEO_PALETTE_RGB24,   .depth = 24, .pix_fmt = PIX_FMT_BGR24   },
64
    {.palette = VIDEO_PALETTE_RGB565,  .depth = 16, .pix_fmt = PIX_FMT_BGR565  },
65 66 67 68
    {.palette = VIDEO_PALETTE_GREY,    .depth = 8,  .pix_fmt = PIX_FMT_GRAY8   },
};


69
static int grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
70
{
Fabrice Bellard's avatar
Fabrice Bellard committed
71
    VideoData *s = s1->priv_data;
72
    AVStream *st;
Fabrice Bellard's avatar
Fabrice Bellard committed
73 74
    int width, height;
    int video_fd, frame_size;
75
    int ret, frame_rate, frame_rate_base;
Luca Abeni's avatar
Luca Abeni committed
76
    int desired_palette, desired_depth;
77
    struct video_tuner tuner;
78
    struct video_audio audio;
79
    struct video_picture pict;
80
    int j;
81
    int vformat_num = sizeof(video_formats) / sizeof(video_formats[0]);
82

83 84 85 86 87 88
    if (ap->width <= 0 || ap->height <= 0) {
        av_log(s1, AV_LOG_ERROR, "Wrong size (%dx%d)\n", ap->width, ap->height);
        return -1;
    }
    if (ap->time_base.den <= 0) {
        av_log(s1, AV_LOG_ERROR, "Wrong time base (%d)\n", ap->time_base.den);
89
        return -1;
90
    }
91

92 93
    width = ap->width;
    height = ap->height;
94 95
    frame_rate      = ap->time_base.den;
    frame_rate_base = ap->time_base.num;
96

97 98 99 100
    if((unsigned)width > 32767 || (unsigned)height > 32767) {
        av_log(s1, AV_LOG_ERROR, "Capture size is out of range: %dx%d\n",
            width, height);

101
        return -1;
102
    }
103

Fabrice Bellard's avatar
Fabrice Bellard committed
104 105
    st = av_new_stream(s1, 0);
    if (!st)
106
        return AVERROR(ENOMEM);
Luca Abeni's avatar
Luca Abeni committed
107
    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
108 109 110

    s->width = width;
    s->height = height;
111 112
    s->frame_rate      = frame_rate;
    s->frame_rate_base = frame_rate_base;
Fabrice Bellard's avatar
Fabrice Bellard committed
113

114
    video_fd = open(s1->filename, O_RDWR);
Fabrice Bellard's avatar
Fabrice Bellard committed
115
    if (video_fd < 0) {
116
        av_log(s1, AV_LOG_ERROR, "%s: %s\n", s1->filename, strerror(errno));
117
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
118
    }
119

120
    if (ioctl(video_fd,VIDIOCGCAP, &s->video_cap) < 0) {
121
        av_log(s1, AV_LOG_ERROR, "VIDIOCGCAP: %s\n", strerror(errno));
Fabrice Bellard's avatar
Fabrice Bellard committed
122 123 124
        goto fail;
    }

125
    if (!(s->video_cap.type & VID_TYPE_CAPTURE)) {
126
        av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not handle capture\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
127 128
        goto fail;
    }
129 130

    desired_palette = -1;
Luca Abeni's avatar
Luca Abeni committed
131
    desired_depth = -1;
132 133 134 135 136 137
    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;
        }
138
    }
139 140 141

    /* set tv standard */
    if (ap->standard && !ioctl(video_fd, VIDIOCGTUNER, &tuner)) {
142 143 144 145 146 147 148
        if (!strcasecmp(ap->standard, "pal"))
            tuner.mode = VIDEO_MODE_PAL;
        else if (!strcasecmp(ap->standard, "secam"))
            tuner.mode = VIDEO_MODE_SECAM;
        else
            tuner.mode = VIDEO_MODE_NTSC;
        ioctl(video_fd, VIDIOCSTUNER, &tuner);
149
    }
150

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

158 159 160 161 162 163 164 165 166 167 168
    ioctl(video_fd, VIDIOCGPICT, &pict);
#if 0
    printf("v4l: colour=%d hue=%d brightness=%d constrast=%d whiteness=%d\n",
           pict.colour,
           pict.hue,
           pict.brightness,
           pict.contrast,
           pict.whiteness);
#endif
    /* try to choose a suitable video format */
    pict.palette = desired_palette;
Luca Abeni's avatar
Luca Abeni committed
169
    pict.depth= desired_depth;
170
    if (desired_palette == -1 || (ret = ioctl(video_fd, VIDIOCSPICT, &pict)) < 0) {
171 172 173 174 175
        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;
176
        }
177 178
        if (j >= vformat_num)
            goto fail1;
179 180
    }

181
    ret = ioctl(video_fd,VIDIOCGMBUF,&s->gb_buffers);
Fabrice Bellard's avatar
Fabrice Bellard committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    if (ret < 0) {
        /* try to use read based access */
        struct video_window win;
        int val;

        win.x = 0;
        win.y = 0;
        win.width = width;
        win.height = height;
        win.chromakey = -1;
        win.flags = 0;

        ioctl(video_fd, VIDIOCSWIN, &win);

        s->frame_format = pict.palette;

        val = 1;
        ioctl(video_fd, VIDIOCCAPTURE, &val);

201
        s->time_frame = av_gettime() * s->frame_rate / s->frame_rate_base;
Fabrice Bellard's avatar
Fabrice Bellard committed
202 203
        s->use_mmap = 0;
    } else {
204 205
        s->video_buf = mmap(0,s->gb_buffers.size,PROT_READ|PROT_WRITE,MAP_SHARED,video_fd,0);
        if ((unsigned char*)-1 == s->video_buf) {
206 207
            s->video_buf = mmap(0,s->gb_buffers.size,PROT_READ|PROT_WRITE,MAP_PRIVATE,video_fd,0);
            if ((unsigned char*)-1 == s->video_buf) {
208
                av_log(s1, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
209 210
                goto fail;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
211
        }
212
        s->gb_frame = 0;
213
        s->time_frame = av_gettime() * s->frame_rate / s->frame_rate_base;
214

Fabrice Bellard's avatar
Fabrice Bellard committed
215
        /* start to grab the first frame */
216 217 218
        s->gb_buf.frame = s->gb_frame % s->gb_buffers.frames;
        s->gb_buf.height = height;
        s->gb_buf.width = width;
219 220 221
        s->gb_buf.format = pict.palette;

        ret = ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);
Fabrice Bellard's avatar
Fabrice Bellard committed
222 223 224
        if (ret < 0) {
            if (errno != EAGAIN) {
            fail1:
225
                av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not support suitable format\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
226
            } else {
227
                av_log(s1, AV_LOG_ERROR,"Fatal: grab device does not receive any video signal\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
228 229 230
            }
            goto fail;
        }
231 232 233 234
        for (j = 1; j < s->gb_buffers.frames; j++) {
          s->gb_buf.frame = j;
          ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);
        }
235
        s->frame_format = s->gb_buf.format;
Fabrice Bellard's avatar
Fabrice Bellard committed
236 237 238
        s->use_mmap = 1;
    }

239 240 241 242 243 244
    for (j = 0; j < vformat_num; j++) {
        if (s->frame_format == video_formats[j].palette) {
            frame_size = width * height * video_formats[j].depth / 8;
            st->codec->pix_fmt = video_formats[j].pix_fmt;
            break;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
245
    }
246 247 248 249

    if (j >= vformat_num)
        goto fail;

Fabrice Bellard's avatar
Fabrice Bellard committed
250
    s->fd = video_fd;
251
    s->frame_size = frame_size;
252

253 254 255 256 257 258
    st->codec->codec_type = CODEC_TYPE_VIDEO;
    st->codec->codec_id = CODEC_ID_RAWVIDEO;
    st->codec->width = width;
    st->codec->height = height;
    st->codec->time_base.den      = frame_rate;
    st->codec->time_base.num = frame_rate_base;
Alex Beregszaszi's avatar
Alex Beregszaszi committed
259
    st->codec->bit_rate = frame_size * 1/av_q2d(st->codec->time_base) * 8;
260

Fabrice Bellard's avatar
Fabrice Bellard committed
261 262
    return 0;
 fail:
263 264
    if (video_fd >= 0)
        close(video_fd);
265
    return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
266 267
}

268
static int v4l_mm_read_picture(VideoData *s, uint8_t *buf)
Fabrice Bellard's avatar
Fabrice Bellard committed
269
{
270
    uint8_t *ptr;
Fabrice Bellard's avatar
Fabrice Bellard committed
271

272 273 274 275 276 277
    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);

278
    /* Setup to capture the next frame */
279
    s->gb_buf.frame = s->gb_frame;
280
    if (ioctl(s->fd, VIDIOCMCAPTURE, &s->gb_buf) < 0) {
281
        if (errno == EAGAIN)
282
            av_log(NULL, AV_LOG_ERROR, "Cannot Sync\n");
283
        else
284
            av_log(NULL, AV_LOG_ERROR, "VIDIOCMCAPTURE: %s\n", strerror(errno));
285
        return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
286
    }
287 288

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

291
    return s->frame_size;
Fabrice Bellard's avatar
Fabrice Bellard committed
292 293
}

294
static int grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
Fabrice Bellard's avatar
Fabrice Bellard committed
295
{
296
    VideoData *s = s1->priv_data;
297
    int64_t curtime, delay;
298
    struct timespec ts;
299 300

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

    /* wait based on the frame rate */
304
    for(;;) {
305
        curtime = av_gettime();
306
        delay = s->time_frame  * s->frame_rate_base / s->frame_rate - curtime;
307
        if (delay <= 0) {
308
            if (delay < INT64_C(-1000000) * s->frame_rate_base / s->frame_rate) {
309
                /* printf("grabbing is %d frames late (dropping)\n", (int) -(delay / 16666)); */
310
                s->time_frame += INT64_C(1000000);
311
            }
312
            break;
313
        }
314 315 316 317 318 319
        ts.tv_sec = delay / 1000000;
        ts.tv_nsec = (delay % 1000000) * 1000;
        nanosleep(&ts, NULL);
    }

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

Luca Abeni's avatar
Luca Abeni committed
322
    pkt->pts = curtime;
323

Fabrice Bellard's avatar
Fabrice Bellard committed
324
    /* read one frame */
325
    if (s->use_mmap) {
326
        return v4l_mm_read_picture(s, pkt->data);
Fabrice Bellard's avatar
Fabrice Bellard committed
327
    } else {
328
        if (read(s->fd, pkt->data, pkt->size) != pkt->size)
329
            return AVERROR(EIO);
330
        return s->frame_size;
Fabrice Bellard's avatar
Fabrice Bellard committed
331 332 333
    }
}

334
static int grab_read_close(AVFormatContext *s1)
Fabrice Bellard's avatar
Fabrice Bellard committed
335
{
336
    VideoData *s = s1->priv_data;
337 338

    if (s->use_mmap)
339
        munmap(s->video_buf, s->gb_buffers.size);
340

341 342 343 344
    /* 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);
345

Fabrice Bellard's avatar
Fabrice Bellard committed
346 347 348 349
    close(s->fd);
    return 0;
}

350
AVInputFormat v4l_demuxer = {
351
    "video4linux",
352
    NULL_IF_CONFIG_SMALL("video grab"),
Fabrice Bellard's avatar
Fabrice Bellard committed
353
    sizeof(VideoData),
354 355 356 357
    NULL,
    grab_read_header,
    grab_read_packet,
    grab_read_close,
358
    .flags = AVFMT_NOFILE,
Fabrice Bellard's avatar
Fabrice Bellard committed
359
};