vfwcap.c 14.7 KB
Newer Older
Ramiro Polla's avatar
Ramiro Polla committed
1 2
/*
 * VFW capture interface
3
 * Copyright (c) 2006-2008 Ramiro Polla
Ramiro Polla's avatar
Ramiro Polla committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

22
#include "libavutil/internal.h"
23 24 25
#include "libavutil/log.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
26 27

#include "libavformat/internal.h"
Ramiro Polla's avatar
Ramiro Polla committed
28

29 30
// windows.h must no be included before winsock2.h, and libavformat internal
// headers may include winsock2.h
31
#include <windows.h>
32
// windows.h needs to be included before vfw.h
33 34
#include <vfw.h>

35
#include "avdevice.h"
Ramiro Polla's avatar
Ramiro Polla committed
36

37 38 39 40 41
/* Some obsolete versions of MinGW32 before 4.0.0 lack this. */
#ifndef HWND_MESSAGE
#define HWND_MESSAGE ((HWND) -3)
#endif

Ramiro Polla's avatar
Ramiro Polla committed
42
struct vfw_ctx {
43
    const AVClass *class;
Ramiro Polla's avatar
Ramiro Polla committed
44 45 46 47 48 49
    HWND hwnd;
    HANDLE mutex;
    HANDLE event;
    AVPacketList *pktl;
    unsigned int curbufsize;
    unsigned int frame_num;
50
    char *video_size;       /**< A string describing video size, set by a private option. */
51
    char *framerate;        /**< Set by a private option. */
Ramiro Polla's avatar
Ramiro Polla committed
52 53
};

54
static enum AVPixelFormat vfw_pixfmt(DWORD biCompression, WORD biBitCount)
Ramiro Polla's avatar
Ramiro Polla committed
55 56
{
    switch(biCompression) {
57
    case MKTAG('U', 'Y', 'V', 'Y'):
58
        return AV_PIX_FMT_UYVY422;
Ramiro Polla's avatar
Ramiro Polla committed
59
    case MKTAG('Y', 'U', 'Y', '2'):
60
        return AV_PIX_FMT_YUYV422;
61
    case MKTAG('I', '4', '2', '0'):
62
        return AV_PIX_FMT_YUV420P;
Ramiro Polla's avatar
Ramiro Polla committed
63 64 65
    case BI_RGB:
        switch(biBitCount) { /* 1-8 are untested */
            case 1:
66
                return AV_PIX_FMT_MONOWHITE;
Ramiro Polla's avatar
Ramiro Polla committed
67
            case 4:
68
                return AV_PIX_FMT_RGB4;
Ramiro Polla's avatar
Ramiro Polla committed
69
            case 8:
70
                return AV_PIX_FMT_RGB8;
Ramiro Polla's avatar
Ramiro Polla committed
71
            case 16:
72
                return AV_PIX_FMT_RGB555;
Ramiro Polla's avatar
Ramiro Polla committed
73
            case 24:
74
                return AV_PIX_FMT_BGR24;
Ramiro Polla's avatar
Ramiro Polla committed
75
            case 32:
76
                return AV_PIX_FMT_RGB32;
Ramiro Polla's avatar
Ramiro Polla committed
77 78
        }
    }
79
    return AV_PIX_FMT_NONE;
Ramiro Polla's avatar
Ramiro Polla committed
80 81
}

82
static enum AVCodecID vfw_codecid(DWORD biCompression)
83 84 85
{
    switch(biCompression) {
    case MKTAG('d', 'v', 's', 'd'):
86
        return AV_CODEC_ID_DVVIDEO;
87 88
    case MKTAG('M', 'J', 'P', 'G'):
    case MKTAG('m', 'j', 'p', 'g'):
89
        return AV_CODEC_ID_MJPEG;
90
    }
91
    return AV_CODEC_ID_NONE;
92 93
}

Ramiro Polla's avatar
Ramiro Polla committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
#define dstruct(pctx, sname, var, type) \
    av_log(pctx, AV_LOG_DEBUG, #var":\t%"type"\n", sname->var)

static void dump_captureparms(AVFormatContext *s, CAPTUREPARMS *cparms)
{
    av_log(s, AV_LOG_DEBUG, "CAPTUREPARMS\n");
    dstruct(s, cparms, dwRequestMicroSecPerFrame, "lu");
    dstruct(s, cparms, fMakeUserHitOKToCapture, "d");
    dstruct(s, cparms, wPercentDropForError, "u");
    dstruct(s, cparms, fYield, "d");
    dstruct(s, cparms, dwIndexSize, "lu");
    dstruct(s, cparms, wChunkGranularity, "u");
    dstruct(s, cparms, fUsingDOSMemory, "d");
    dstruct(s, cparms, wNumVideoRequested, "u");
    dstruct(s, cparms, fCaptureAudio, "d");
    dstruct(s, cparms, wNumAudioRequested, "u");
    dstruct(s, cparms, vKeyAbort, "u");
    dstruct(s, cparms, fAbortLeftMouse, "d");
    dstruct(s, cparms, fAbortRightMouse, "d");
    dstruct(s, cparms, fLimitEnabled, "d");
    dstruct(s, cparms, wTimeLimit, "u");
    dstruct(s, cparms, fMCIControl, "d");
    dstruct(s, cparms, fStepMCIDevice, "d");
    dstruct(s, cparms, dwMCIStartTime, "lu");
    dstruct(s, cparms, dwMCIStopTime, "lu");
    dstruct(s, cparms, fStepCaptureAt2x, "d");
    dstruct(s, cparms, wStepCaptureAverageFrames, "u");
    dstruct(s, cparms, dwAudioBufferSize, "lu");
    dstruct(s, cparms, fDisableWriteCache, "d");
    dstruct(s, cparms, AVStreamMaster, "u");
}

static void dump_videohdr(AVFormatContext *s, VIDEOHDR *vhdr)
{
128
#ifdef DEBUG
Ramiro Polla's avatar
Ramiro Polla committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    av_log(s, AV_LOG_DEBUG, "VIDEOHDR\n");
    dstruct(s, vhdr, lpData, "p");
    dstruct(s, vhdr, dwBufferLength, "lu");
    dstruct(s, vhdr, dwBytesUsed, "lu");
    dstruct(s, vhdr, dwTimeCaptured, "lu");
    dstruct(s, vhdr, dwUser, "lu");
    dstruct(s, vhdr, dwFlags, "lu");
    dstruct(s, vhdr, dwReserved[0], "lu");
    dstruct(s, vhdr, dwReserved[1], "lu");
    dstruct(s, vhdr, dwReserved[2], "lu");
    dstruct(s, vhdr, dwReserved[3], "lu");
#endif
}

static void dump_bih(AVFormatContext *s, BITMAPINFOHEADER *bih)
{
    av_log(s, AV_LOG_DEBUG, "BITMAPINFOHEADER\n");
    dstruct(s, bih, biSize, "lu");
    dstruct(s, bih, biWidth, "ld");
    dstruct(s, bih, biHeight, "ld");
    dstruct(s, bih, biPlanes, "d");
    dstruct(s, bih, biBitCount, "d");
    dstruct(s, bih, biCompression, "lu");
    av_log(s, AV_LOG_DEBUG, "    biCompression:\t\"%.4s\"\n",
                   (char*) &bih->biCompression);
    dstruct(s, bih, biSizeImage, "lu");
    dstruct(s, bih, biXPelsPerMeter, "lu");
    dstruct(s, bih, biYPelsPerMeter, "lu");
    dstruct(s, bih, biClrUsed, "lu");
    dstruct(s, bih, biClrImportant, "lu");
}

161
static int shall_we_drop(AVFormatContext *s)
Ramiro Polla's avatar
Ramiro Polla committed
162
{
163
    struct vfw_ctx *ctx = s->priv_data;
164
    static const uint8_t dropscore[4] = { 62, 75, 87, 100 };
165
    const int ndropscores = FF_ARRAY_ELEMS(dropscore);
Ramiro Polla's avatar
Ramiro Polla committed
166 167
    unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;

168
    if(dropscore[++ctx->frame_num%ndropscores] <= buffer_fullness) {
169
        av_log(s, AV_LOG_ERROR,
Ramiro Polla's avatar
Ramiro Polla committed
170 171 172 173 174 175 176 177 178
              "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
        return 1;
    }

    return 0;
}

static LRESULT CALLBACK videostream_cb(HWND hwnd, LPVIDEOHDR vdhdr)
{
179
    AVFormatContext *s;
Ramiro Polla's avatar
Ramiro Polla committed
180 181 182
    struct vfw_ctx *ctx;
    AVPacketList **ppktl, *pktl_next;

183 184
    s = (AVFormatContext *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
    ctx = s->priv_data;
Ramiro Polla's avatar
Ramiro Polla committed
185

186
    dump_videohdr(s, vdhdr);
Ramiro Polla's avatar
Ramiro Polla committed
187

188
    if(shall_we_drop(s))
Ramiro Polla's avatar
Ramiro Polla committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        return FALSE;

    WaitForSingleObject(ctx->mutex, INFINITE);

    pktl_next = av_mallocz(sizeof(AVPacketList));
    if(!pktl_next)
        goto fail;

    if(av_new_packet(&pktl_next->pkt, vdhdr->dwBytesUsed) < 0) {
        av_free(pktl_next);
        goto fail;
    }

    pktl_next->pkt.pts = vdhdr->dwTimeCaptured;
    memcpy(pktl_next->pkt.data, vdhdr->lpData, vdhdr->dwBytesUsed);

    for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
    *ppktl = pktl_next;

    ctx->curbufsize += vdhdr->dwBytesUsed;

    SetEvent(ctx->event);
    ReleaseMutex(ctx->mutex);

    return TRUE;
fail:
    ReleaseMutex(ctx->mutex);
    return FALSE;
}

219 220 221
static int vfw_read_close(AVFormatContext *s)
{
    struct vfw_ctx *ctx = s->priv_data;
222
    AVPacketList *pktl;
223 224 225 226 227 228 229 230 231 232 233

    if(ctx->hwnd) {
        SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);
        SendMessage(ctx->hwnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
        DestroyWindow(ctx->hwnd);
    }
    if(ctx->mutex)
        CloseHandle(ctx->mutex);
    if(ctx->event)
        CloseHandle(ctx->event);

234 235 236
    pktl = ctx->pktl;
    while (pktl) {
        AVPacketList *next = pktl->next;
237
        av_packet_unref(&pktl->pkt);
238 239 240 241
        av_free(pktl);
        pktl = next;
    }

242 243
    return 0;
}
Ramiro Polla's avatar
Ramiro Polla committed
244

245
static int vfw_read_header(AVFormatContext *s)
Ramiro Polla's avatar
Ramiro Polla committed
246 247
{
    struct vfw_ctx *ctx = s->priv_data;
248
    AVCodecParameters *par;
Ramiro Polla's avatar
Ramiro Polla committed
249 250 251
    AVStream *st;
    int devnum;
    int bisize;
252
    BITMAPINFO *bi = NULL;
Ramiro Polla's avatar
Ramiro Polla committed
253 254 255 256
    CAPTUREPARMS cparms;
    DWORD biCompression;
    WORD biBitCount;
    int ret;
257
    AVRational framerate_q;
Ramiro Polla's avatar
Ramiro Polla committed
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    if (!strcmp(s->filename, "list")) {
        for (devnum = 0; devnum <= 9; devnum++) {
            char driver_name[256];
            char driver_ver[256];
            ret = capGetDriverDescription(devnum,
                                          driver_name, sizeof(driver_name),
                                          driver_ver, sizeof(driver_ver));
            if (ret) {
                av_log(s, AV_LOG_INFO, "Driver %d\n", devnum);
                av_log(s, AV_LOG_INFO, " %s\n", driver_name);
                av_log(s, AV_LOG_INFO, " %s\n", driver_ver);
            }
        }
        return AVERROR(EIO);
    }

Ramiro Polla's avatar
Ramiro Polla committed
275 276 277
    ctx->hwnd = capCreateCaptureWindow(NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0);
    if(!ctx->hwnd) {
        av_log(s, AV_LOG_ERROR, "Could not create capture window.\n");
278
        return AVERROR(EIO);
Ramiro Polla's avatar
Ramiro Polla committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    }

    /* If atoi fails, devnum==0 and the default device is used */
    devnum = atoi(s->filename);

    ret = SendMessage(ctx->hwnd, WM_CAP_DRIVER_CONNECT, devnum, 0);
    if(!ret) {
        av_log(s, AV_LOG_ERROR, "Could not connect to device.\n");
        DestroyWindow(ctx->hwnd);
        return AVERROR(ENODEV);
    }

    SendMessage(ctx->hwnd, WM_CAP_SET_OVERLAY, 0, 0);
    SendMessage(ctx->hwnd, WM_CAP_SET_PREVIEW, 0, 0);

    ret = SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0,
                      (LPARAM) videostream_cb);
    if(!ret) {
        av_log(s, AV_LOG_ERROR, "Could not set video stream callback.\n");
298
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
299 300
    }

301
    SetWindowLongPtr(ctx->hwnd, GWLP_USERDATA, (LONG_PTR) s);
Ramiro Polla's avatar
Ramiro Polla committed
302

303
    st = avformat_new_stream(s, NULL);
Ramiro Polla's avatar
Ramiro Polla committed
304 305
    if(!st) {
        vfw_read_close(s);
306
        return AVERROR(ENOMEM);
Ramiro Polla's avatar
Ramiro Polla committed
307 308 309 310
    }

    /* Set video format */
    bisize = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, 0, 0);
311
    if(!bisize)
312
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
313 314 315
    bi = av_malloc(bisize);
    if(!bi) {
        vfw_read_close(s);
316
        return AVERROR(ENOMEM);
Ramiro Polla's avatar
Ramiro Polla committed
317 318
    }
    ret = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, bisize, (LPARAM) bi);
319
    if(!ret)
320
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
321 322 323

    dump_bih(s, &bi->bmiHeader);

324 325 326 327 328
    ret = av_parse_video_rate(&framerate_q, ctx->framerate);
    if (ret < 0) {
        av_log(s, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
        goto fail;
    }
329 330 331 332 333

    if (ctx->video_size) {
        ret = av_parse_video_size(&bi->bmiHeader.biWidth, &bi->bmiHeader.biHeight, ctx->video_size);
        if (ret < 0) {
            av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");
334
            goto fail;
335 336
        }
    }
Ramiro Polla's avatar
Ramiro Polla committed
337

338
    if (0) {
Ramiro Polla's avatar
Ramiro Polla committed
339 340 341 342 343 344 345 346 347
        /* For testing yet unsupported compressions
         * Copy these values from user-supplied verbose information */
        bi->bmiHeader.biWidth       = 320;
        bi->bmiHeader.biHeight      = 240;
        bi->bmiHeader.biPlanes      = 1;
        bi->bmiHeader.biBitCount    = 12;
        bi->bmiHeader.biCompression = MKTAG('I','4','2','0');
        bi->bmiHeader.biSizeImage   = 115200;
        dump_bih(s, &bi->bmiHeader);
348
    }
349

Ramiro Polla's avatar
Ramiro Polla committed
350 351 352
    ret = SendMessage(ctx->hwnd, WM_CAP_SET_VIDEOFORMAT, bisize, (LPARAM) bi);
    if(!ret) {
        av_log(s, AV_LOG_ERROR, "Could not set Video Format.\n");
353
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
354 355 356 357 358 359 360 361
    }

    biCompression = bi->bmiHeader.biCompression;
    biBitCount = bi->bmiHeader.biBitCount;

    /* Set sequence setup */
    ret = SendMessage(ctx->hwnd, WM_CAP_GET_SEQUENCE_SETUP, sizeof(cparms),
                      (LPARAM) &cparms);
362
    if(!ret)
363
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
364 365 366 367 368

    dump_captureparms(s, &cparms);

    cparms.fYield = 1; // Spawn a background thread
    cparms.dwRequestMicroSecPerFrame =
369
                               (framerate_q.den*1000000) / framerate_q.num;
Ramiro Polla's avatar
Ramiro Polla committed
370 371 372 373 374 375 376
    cparms.fAbortLeftMouse = 0;
    cparms.fAbortRightMouse = 0;
    cparms.fCaptureAudio = 0;
    cparms.vKeyAbort = 0;

    ret = SendMessage(ctx->hwnd, WM_CAP_SET_SEQUENCE_SETUP, sizeof(cparms),
                      (LPARAM) &cparms);
377
    if(!ret)
378
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
379

380 381 382 383 384 385 386 387 388 389
    st->avg_frame_rate = framerate_q;

    par = st->codecpar;
    par->codec_type = AVMEDIA_TYPE_VIDEO;
    par->width  = bi->bmiHeader.biWidth;
    par->height = bi->bmiHeader.biHeight;
    par->format = vfw_pixfmt(biCompression, biBitCount);
    if (par->format == AV_PIX_FMT_NONE) {
        par->codec_id = vfw_codecid(biCompression);
        if (par->codec_id == AV_CODEC_ID_NONE) {
Ramiro Polla's avatar
Ramiro Polla committed
390 391 392 393
            av_log(s, AV_LOG_ERROR, "Unknown compression type. "
                             "Please report verbose (-v 9) debug information.\n");
            vfw_read_close(s);
            return AVERROR_PATCHWELCOME;
394
        }
395
        par->bits_per_coded_sample = biBitCount;
Ramiro Polla's avatar
Ramiro Polla committed
396
    } else {
397
        par->codec_id = AV_CODEC_ID_RAWVIDEO;
398
        if(biCompression == BI_RGB) {
399 400 401 402 403
            par->bits_per_coded_sample = biBitCount;
            par->extradata = av_malloc(9 + AV_INPUT_BUFFER_PADDING_SIZE);
            if (par->extradata) {
                par->extradata_size = 9;
                memcpy(par->extradata, "BottomUp", 9);
404 405
            }
        }
406
    }
407

408 409
    av_freep(&bi);

410
    avpriv_set_pts_info(st, 32, 1, 1000);
Ramiro Polla's avatar
Ramiro Polla committed
411 412 413 414

    ctx->mutex = CreateMutex(NULL, 0, NULL);
    if(!ctx->mutex) {
        av_log(s, AV_LOG_ERROR, "Could not create Mutex.\n" );
415
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
416 417 418 419
    }
    ctx->event = CreateEvent(NULL, 1, 0, NULL);
    if(!ctx->event) {
        av_log(s, AV_LOG_ERROR, "Could not create Event.\n" );
420
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
421 422 423 424 425
    }

    ret = SendMessage(ctx->hwnd, WM_CAP_SEQUENCE_NOFILE, 0, 0);
    if(!ret) {
        av_log(s, AV_LOG_ERROR, "Could not start capture sequence.\n" );
426
        goto fail;
Ramiro Polla's avatar
Ramiro Polla committed
427 428 429
    }

    return 0;
430

431 432
fail:
    av_freep(&bi);
433
    vfw_read_close(s);
434
    return AVERROR(EIO);
Ramiro Polla's avatar
Ramiro Polla committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
}

static int vfw_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    struct vfw_ctx *ctx = s->priv_data;
    AVPacketList *pktl = NULL;

    while(!pktl) {
        WaitForSingleObject(ctx->mutex, INFINITE);
        pktl = ctx->pktl;
        if(ctx->pktl) {
            *pkt = ctx->pktl->pkt;
            ctx->pktl = ctx->pktl->next;
            av_free(pktl);
        }
        ResetEvent(ctx->event);
        ReleaseMutex(ctx->mutex);
        if(!pktl) {
            if(s->flags & AVFMT_FLAG_NONBLOCK) {
                return AVERROR(EAGAIN);
            } else {
                WaitForSingleObject(ctx->event, INFINITE);
            }
        }
    }

    ctx->curbufsize -= pkt->size;

    return pkt->size;
}

466 467 468
#define OFFSET(x) offsetof(struct vfw_ctx, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM
static const AVOption options[] = {
469 470
    { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
    { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
471 472 473 474 475 476 477 478
    { NULL },
};

static const AVClass vfw_class = {
    .class_name = "VFW indev",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
479
    .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT
480 481
};

482
AVInputFormat ff_vfwcap_demuxer = {
483 484 485 486 487 488 489 490
    .name           = "vfwcap",
    .long_name      = NULL_IF_CONFIG_SMALL("VfW video capture"),
    .priv_data_size = sizeof(struct vfw_ctx),
    .read_header    = vfw_read_header,
    .read_packet    = vfw_read_packet,
    .read_close     = vfw_read_close,
    .flags          = AVFMT_NOFILE,
    .priv_class     = &vfw_class,
Ramiro Polla's avatar
Ramiro Polla committed
491
};