2 * VFW capture interface
3 * Copyright (c) 2006-2008 Ramiro Polla
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/internal.h"
23 #include "libavutil/log.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/parseutils.h"
27 #include "libavformat/internal.h"
29 // windows.h must no be included before winsock2.h, and libavformat internal
30 // headers may include winsock2.h
32 // windows.h needs to be included before vfw.h
37 /* Some obsolete versions of MinGW32 before 4.0.0 lack this. */
39 #define HWND_MESSAGE ((HWND) -3)
48 unsigned int curbufsize;
49 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. */
54 static enum AVPixelFormat vfw_pixfmt(DWORD biCompression, WORD biBitCount)
56 switch(biCompression) {
57 case MKTAG('U', 'Y', 'V', 'Y'):
58 return AV_PIX_FMT_UYVY422;
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;
64 switch(biBitCount) { /* 1-8 are untested */
66 return AV_PIX_FMT_MONOWHITE;
68 return AV_PIX_FMT_RGB4;
70 return AV_PIX_FMT_RGB8;
72 return AV_PIX_FMT_RGB555;
74 return AV_PIX_FMT_BGR24;
76 return AV_PIX_FMT_RGB32;
79 return AV_PIX_FMT_NONE;
82 static enum AVCodecID vfw_codecid(DWORD biCompression)
84 switch(biCompression) {
85 case MKTAG('d', 'v', 's', 'd'):
86 return AV_CODEC_ID_DVVIDEO;
87 case MKTAG('M', 'J', 'P', 'G'):
88 case MKTAG('m', 'j', 'p', 'g'):
89 return AV_CODEC_ID_MJPEG;
91 return AV_CODEC_ID_NONE;
94 #define dstruct(pctx, sname, var, type) \
95 av_log(pctx, AV_LOG_DEBUG, #var":\t%"type"\n", sname->var)
97 static void dump_captureparms(AVFormatContext *s, CAPTUREPARMS *cparms)
99 av_log(s, AV_LOG_DEBUG, "CAPTUREPARMS\n");
100 dstruct(s, cparms, dwRequestMicroSecPerFrame, "lu");
101 dstruct(s, cparms, fMakeUserHitOKToCapture, "d");
102 dstruct(s, cparms, wPercentDropForError, "u");
103 dstruct(s, cparms, fYield, "d");
104 dstruct(s, cparms, dwIndexSize, "lu");
105 dstruct(s, cparms, wChunkGranularity, "u");
106 dstruct(s, cparms, fUsingDOSMemory, "d");
107 dstruct(s, cparms, wNumVideoRequested, "u");
108 dstruct(s, cparms, fCaptureAudio, "d");
109 dstruct(s, cparms, wNumAudioRequested, "u");
110 dstruct(s, cparms, vKeyAbort, "u");
111 dstruct(s, cparms, fAbortLeftMouse, "d");
112 dstruct(s, cparms, fAbortRightMouse, "d");
113 dstruct(s, cparms, fLimitEnabled, "d");
114 dstruct(s, cparms, wTimeLimit, "u");
115 dstruct(s, cparms, fMCIControl, "d");
116 dstruct(s, cparms, fStepMCIDevice, "d");
117 dstruct(s, cparms, dwMCIStartTime, "lu");
118 dstruct(s, cparms, dwMCIStopTime, "lu");
119 dstruct(s, cparms, fStepCaptureAt2x, "d");
120 dstruct(s, cparms, wStepCaptureAverageFrames, "u");
121 dstruct(s, cparms, dwAudioBufferSize, "lu");
122 dstruct(s, cparms, fDisableWriteCache, "d");
123 dstruct(s, cparms, AVStreamMaster, "u");
126 static void dump_videohdr(AVFormatContext *s, VIDEOHDR *vhdr)
129 av_log(s, AV_LOG_DEBUG, "VIDEOHDR\n");
130 dstruct(s, vhdr, lpData, "p");
131 dstruct(s, vhdr, dwBufferLength, "lu");
132 dstruct(s, vhdr, dwBytesUsed, "lu");
133 dstruct(s, vhdr, dwTimeCaptured, "lu");
134 dstruct(s, vhdr, dwUser, "lu");
135 dstruct(s, vhdr, dwFlags, "lu");
136 dstruct(s, vhdr, dwReserved[0], "lu");
137 dstruct(s, vhdr, dwReserved[1], "lu");
138 dstruct(s, vhdr, dwReserved[2], "lu");
139 dstruct(s, vhdr, dwReserved[3], "lu");
143 static void dump_bih(AVFormatContext *s, BITMAPINFOHEADER *bih)
145 av_log(s, AV_LOG_DEBUG, "BITMAPINFOHEADER\n");
146 dstruct(s, bih, biSize, "lu");
147 dstruct(s, bih, biWidth, "ld");
148 dstruct(s, bih, biHeight, "ld");
149 dstruct(s, bih, biPlanes, "d");
150 dstruct(s, bih, biBitCount, "d");
151 dstruct(s, bih, biCompression, "lu");
152 av_log(s, AV_LOG_DEBUG, " biCompression:\t\"%.4s\"\n",
153 (char*) &bih->biCompression);
154 dstruct(s, bih, biSizeImage, "lu");
155 dstruct(s, bih, biXPelsPerMeter, "lu");
156 dstruct(s, bih, biYPelsPerMeter, "lu");
157 dstruct(s, bih, biClrUsed, "lu");
158 dstruct(s, bih, biClrImportant, "lu");
161 static int shall_we_drop(AVFormatContext *s)
163 struct vfw_ctx *ctx = s->priv_data;
164 static const uint8_t dropscore[] = {62, 75, 87, 100};
165 const int ndropscores = FF_ARRAY_ELEMS(dropscore);
166 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,
170 "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
177 static LRESULT CALLBACK videostream_cb(HWND hwnd, LPVIDEOHDR vdhdr)
181 AVPacketList **ppktl, *pktl_next;
183 s = (AVFormatContext *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
186 dump_videohdr(s, vdhdr);
191 WaitForSingleObject(ctx->mutex, INFINITE);
193 pktl_next = av_mallocz(sizeof(AVPacketList));
197 if(av_new_packet(&pktl_next->pkt, vdhdr->dwBytesUsed) < 0) {
202 pktl_next->pkt.pts = vdhdr->dwTimeCaptured;
203 memcpy(pktl_next->pkt.data, vdhdr->lpData, vdhdr->dwBytesUsed);
205 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
208 ctx->curbufsize += vdhdr->dwBytesUsed;
210 SetEvent(ctx->event);
211 ReleaseMutex(ctx->mutex);
215 ReleaseMutex(ctx->mutex);
219 static int vfw_read_close(AVFormatContext *s)
221 struct vfw_ctx *ctx = s->priv_data;
225 SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);
226 SendMessage(ctx->hwnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
227 DestroyWindow(ctx->hwnd);
230 CloseHandle(ctx->mutex);
232 CloseHandle(ctx->event);
236 AVPacketList *next = pktl->next;
237 av_packet_unref(&pktl->pkt);
245 static int vfw_read_header(AVFormatContext *s)
247 struct vfw_ctx *ctx = s->priv_data;
248 AVCodecParameters *par;
252 BITMAPINFO *bi = NULL;
257 AVRational framerate_q;
259 if (!strcmp(s->filename, "list")) {
260 for (devnum = 0; devnum <= 9; devnum++) {
261 char driver_name[256];
262 char driver_ver[256];
263 ret = capGetDriverDescription(devnum,
264 driver_name, sizeof(driver_name),
265 driver_ver, sizeof(driver_ver));
267 av_log(s, AV_LOG_INFO, "Driver %d\n", devnum);
268 av_log(s, AV_LOG_INFO, " %s\n", driver_name);
269 av_log(s, AV_LOG_INFO, " %s\n", driver_ver);
275 ctx->hwnd = capCreateCaptureWindow(NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0);
277 av_log(s, AV_LOG_ERROR, "Could not create capture window.\n");
281 /* If atoi fails, devnum==0 and the default device is used */
282 devnum = atoi(s->filename);
284 ret = SendMessage(ctx->hwnd, WM_CAP_DRIVER_CONNECT, devnum, 0);
286 av_log(s, AV_LOG_ERROR, "Could not connect to device.\n");
287 DestroyWindow(ctx->hwnd);
288 return AVERROR(ENODEV);
291 SendMessage(ctx->hwnd, WM_CAP_SET_OVERLAY, 0, 0);
292 SendMessage(ctx->hwnd, WM_CAP_SET_PREVIEW, 0, 0);
294 ret = SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0,
295 (LPARAM) videostream_cb);
297 av_log(s, AV_LOG_ERROR, "Could not set video stream callback.\n");
301 SetWindowLongPtr(ctx->hwnd, GWLP_USERDATA, (LONG_PTR) s);
303 st = avformat_new_stream(s, NULL);
306 return AVERROR(ENOMEM);
309 /* Set video format */
310 bisize = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, 0, 0);
313 bi = av_malloc(bisize);
316 return AVERROR(ENOMEM);
318 ret = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, bisize, (LPARAM) bi);
322 dump_bih(s, &bi->bmiHeader);
324 ret = av_parse_video_rate(&framerate_q, ctx->framerate);
326 av_log(s, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
330 if (ctx->video_size) {
331 ret = av_parse_video_size(&bi->bmiHeader.biWidth, &bi->bmiHeader.biHeight, ctx->video_size);
333 av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");
339 /* For testing yet unsupported compressions
340 * Copy these values from user-supplied verbose information */
341 bi->bmiHeader.biWidth = 320;
342 bi->bmiHeader.biHeight = 240;
343 bi->bmiHeader.biPlanes = 1;
344 bi->bmiHeader.biBitCount = 12;
345 bi->bmiHeader.biCompression = MKTAG('I','4','2','0');
346 bi->bmiHeader.biSizeImage = 115200;
347 dump_bih(s, &bi->bmiHeader);
350 ret = SendMessage(ctx->hwnd, WM_CAP_SET_VIDEOFORMAT, bisize, (LPARAM) bi);
352 av_log(s, AV_LOG_ERROR, "Could not set Video Format.\n");
356 biCompression = bi->bmiHeader.biCompression;
357 biBitCount = bi->bmiHeader.biBitCount;
359 /* Set sequence setup */
360 ret = SendMessage(ctx->hwnd, WM_CAP_GET_SEQUENCE_SETUP, sizeof(cparms),
365 dump_captureparms(s, &cparms);
367 cparms.fYield = 1; // Spawn a background thread
368 cparms.dwRequestMicroSecPerFrame =
369 (framerate_q.den*1000000) / framerate_q.num;
370 cparms.fAbortLeftMouse = 0;
371 cparms.fAbortRightMouse = 0;
372 cparms.fCaptureAudio = 0;
373 cparms.vKeyAbort = 0;
375 ret = SendMessage(ctx->hwnd, WM_CAP_SET_SEQUENCE_SETUP, sizeof(cparms),
380 st->avg_frame_rate = framerate_q;
383 par->codec_type = AVMEDIA_TYPE_VIDEO;
384 par->width = bi->bmiHeader.biWidth;
385 par->height = bi->bmiHeader.biHeight;
386 par->format = vfw_pixfmt(biCompression, biBitCount);
387 if (par->format == AV_PIX_FMT_NONE) {
388 par->codec_id = vfw_codecid(biCompression);
389 if (par->codec_id == AV_CODEC_ID_NONE) {
390 av_log(s, AV_LOG_ERROR, "Unknown compression type. "
391 "Please report verbose (-v 9) debug information.\n");
393 return AVERROR_PATCHWELCOME;
395 par->bits_per_coded_sample = biBitCount;
397 par->codec_id = AV_CODEC_ID_RAWVIDEO;
398 if(biCompression == BI_RGB) {
399 par->bits_per_coded_sample = biBitCount;
400 par->extradata = av_malloc(9 + AV_INPUT_BUFFER_PADDING_SIZE);
401 if (par->extradata) {
402 par->extradata_size = 9;
403 memcpy(par->extradata, "BottomUp", 9);
410 avpriv_set_pts_info(st, 32, 1, 1000);
412 ctx->mutex = CreateMutex(NULL, 0, NULL);
414 av_log(s, AV_LOG_ERROR, "Could not create Mutex.\n" );
417 ctx->event = CreateEvent(NULL, 1, 0, NULL);
419 av_log(s, AV_LOG_ERROR, "Could not create Event.\n" );
423 ret = SendMessage(ctx->hwnd, WM_CAP_SEQUENCE_NOFILE, 0, 0);
425 av_log(s, AV_LOG_ERROR, "Could not start capture sequence.\n" );
437 static int vfw_read_packet(AVFormatContext *s, AVPacket *pkt)
439 struct vfw_ctx *ctx = s->priv_data;
440 AVPacketList *pktl = NULL;
443 WaitForSingleObject(ctx->mutex, INFINITE);
446 *pkt = ctx->pktl->pkt;
447 ctx->pktl = ctx->pktl->next;
450 ResetEvent(ctx->event);
451 ReleaseMutex(ctx->mutex);
453 if(s->flags & AVFMT_FLAG_NONBLOCK) {
454 return AVERROR(EAGAIN);
456 WaitForSingleObject(ctx->event, INFINITE);
461 ctx->curbufsize -= pkt->size;
466 #define OFFSET(x) offsetof(struct vfw_ctx, x)
467 #define DEC AV_OPT_FLAG_DECODING_PARAM
468 static const AVOption options[] = {
469 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
470 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
474 static const AVClass vfw_class = {
475 .class_name = "VFW indev",
476 .item_name = av_default_item_name,
478 .version = LIBAVUTIL_VERSION_INT,
479 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT
482 AVInputFormat ff_vfwcap_demuxer = {
484 .long_name = NULL_IF_CONFIG_SMALL("VfW video capture"),
485 .priv_data_size = sizeof(struct vfw_ctx),
486 .read_header = vfw_read_header,
487 .read_packet = vfw_read_packet,
488 .read_close = vfw_read_close,
489 .flags = AVFMT_NOFILE,
490 .priv_class = &vfw_class,