1 /*
2 * VFW capture interface
3 * Copyright (c) 2006-2008 Ramiro Polla
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 "libavutil/internal.h"
23 #include "libavutil/log.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/parseutils.h"
26
27 #include "libavcodec/packet_internal.h"
28 #include "libavformat/internal.h"
29
30 // windows.h must no be included before winsock2.h, and libavformat internal
31 // headers may include winsock2.h
32 #include <windows.h>
33 // windows.h needs to be included before vfw.h
34 #include <vfw.h>
35
36 #include "avdevice.h"
37
38 /* Some obsolete versions of MinGW32 before 4.0.0 lack this. */
39 #ifndef HWND_MESSAGE
40 #define HWND_MESSAGE ((HWND) -3)
41 #endif
42
43 struct vfw_ctx {
44 const AVClass *class;
45 HWND hwnd;
46 HANDLE mutex;
47 HANDLE event;
48 PacketListEntry *pktl;
49 unsigned int curbufsize;
50 unsigned int frame_num;
51 char *video_size; /**< A string describing video size, set by a private option. */
52 char *framerate; /**< Set by a private option. */
53 };
54
vfw_pixfmt(DWORD biCompression,WORD biBitCount)55 static enum AVPixelFormat vfw_pixfmt(DWORD biCompression, WORD biBitCount)
56 {
57 switch(biCompression) {
58 case MKTAG('U', 'Y', 'V', 'Y'):
59 return AV_PIX_FMT_UYVY422;
60 case MKTAG('Y', 'U', 'Y', '2'):
61 return AV_PIX_FMT_YUYV422;
62 case MKTAG('I', '4', '2', '0'):
63 return AV_PIX_FMT_YUV420P;
64 case BI_RGB:
65 switch(biBitCount) { /* 1-8 are untested */
66 case 1:
67 return AV_PIX_FMT_MONOWHITE;
68 case 4:
69 return AV_PIX_FMT_RGB4;
70 case 8:
71 return AV_PIX_FMT_RGB8;
72 case 16:
73 return AV_PIX_FMT_RGB555;
74 case 24:
75 return AV_PIX_FMT_BGR24;
76 case 32:
77 return AV_PIX_FMT_RGB32;
78 }
79 }
80 return AV_PIX_FMT_NONE;
81 }
82
vfw_codecid(DWORD biCompression)83 static enum AVCodecID vfw_codecid(DWORD biCompression)
84 {
85 switch(biCompression) {
86 case MKTAG('d', 'v', 's', 'd'):
87 return AV_CODEC_ID_DVVIDEO;
88 case MKTAG('M', 'J', 'P', 'G'):
89 case MKTAG('m', 'j', 'p', 'g'):
90 return AV_CODEC_ID_MJPEG;
91 }
92 return AV_CODEC_ID_NONE;
93 }
94
95 #define dstruct(pctx, sname, var, type) \
96 av_log(pctx, AV_LOG_DEBUG, #var":\t%"type"\n", sname->var)
97
dump_captureparms(AVFormatContext * s,CAPTUREPARMS * cparms)98 static void dump_captureparms(AVFormatContext *s, CAPTUREPARMS *cparms)
99 {
100 av_log(s, AV_LOG_DEBUG, "CAPTUREPARMS\n");
101 dstruct(s, cparms, dwRequestMicroSecPerFrame, "lu");
102 dstruct(s, cparms, fMakeUserHitOKToCapture, "d");
103 dstruct(s, cparms, wPercentDropForError, "u");
104 dstruct(s, cparms, fYield, "d");
105 dstruct(s, cparms, dwIndexSize, "lu");
106 dstruct(s, cparms, wChunkGranularity, "u");
107 dstruct(s, cparms, fUsingDOSMemory, "d");
108 dstruct(s, cparms, wNumVideoRequested, "u");
109 dstruct(s, cparms, fCaptureAudio, "d");
110 dstruct(s, cparms, wNumAudioRequested, "u");
111 dstruct(s, cparms, vKeyAbort, "u");
112 dstruct(s, cparms, fAbortLeftMouse, "d");
113 dstruct(s, cparms, fAbortRightMouse, "d");
114 dstruct(s, cparms, fLimitEnabled, "d");
115 dstruct(s, cparms, wTimeLimit, "u");
116 dstruct(s, cparms, fMCIControl, "d");
117 dstruct(s, cparms, fStepMCIDevice, "d");
118 dstruct(s, cparms, dwMCIStartTime, "lu");
119 dstruct(s, cparms, dwMCIStopTime, "lu");
120 dstruct(s, cparms, fStepCaptureAt2x, "d");
121 dstruct(s, cparms, wStepCaptureAverageFrames, "u");
122 dstruct(s, cparms, dwAudioBufferSize, "lu");
123 dstruct(s, cparms, fDisableWriteCache, "d");
124 dstruct(s, cparms, AVStreamMaster, "u");
125 }
126
dump_videohdr(AVFormatContext * s,VIDEOHDR * vhdr)127 static void dump_videohdr(AVFormatContext *s, VIDEOHDR *vhdr)
128 {
129 #ifdef DEBUG
130 av_log(s, AV_LOG_DEBUG, "VIDEOHDR\n");
131 dstruct(s, vhdr, lpData, "p");
132 dstruct(s, vhdr, dwBufferLength, "lu");
133 dstruct(s, vhdr, dwBytesUsed, "lu");
134 dstruct(s, vhdr, dwTimeCaptured, "lu");
135 dstruct(s, vhdr, dwUser, "lu");
136 dstruct(s, vhdr, dwFlags, "lu");
137 dstruct(s, vhdr, dwReserved[0], "lu");
138 dstruct(s, vhdr, dwReserved[1], "lu");
139 dstruct(s, vhdr, dwReserved[2], "lu");
140 dstruct(s, vhdr, dwReserved[3], "lu");
141 #endif
142 }
143
dump_bih(AVFormatContext * s,BITMAPINFOHEADER * bih)144 static void dump_bih(AVFormatContext *s, BITMAPINFOHEADER *bih)
145 {
146 av_log(s, AV_LOG_DEBUG, "BITMAPINFOHEADER\n");
147 dstruct(s, bih, biSize, "lu");
148 dstruct(s, bih, biWidth, "ld");
149 dstruct(s, bih, biHeight, "ld");
150 dstruct(s, bih, biPlanes, "d");
151 dstruct(s, bih, biBitCount, "d");
152 dstruct(s, bih, biCompression, "lu");
153 av_log(s, AV_LOG_DEBUG, " biCompression:\t\"%.4s\"\n",
154 (char*) &bih->biCompression);
155 dstruct(s, bih, biSizeImage, "lu");
156 dstruct(s, bih, biXPelsPerMeter, "lu");
157 dstruct(s, bih, biYPelsPerMeter, "lu");
158 dstruct(s, bih, biClrUsed, "lu");
159 dstruct(s, bih, biClrImportant, "lu");
160 }
161
shall_we_drop(AVFormatContext * s)162 static int shall_we_drop(AVFormatContext *s)
163 {
164 struct vfw_ctx *ctx = s->priv_data;
165 static const uint8_t dropscore[4] = { 62, 75, 87, 100 };
166 const int ndropscores = FF_ARRAY_ELEMS(dropscore);
167 unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
168
169 if(dropscore[++ctx->frame_num%ndropscores] <= buffer_fullness) {
170 av_log(s, AV_LOG_ERROR,
171 "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
172 return 1;
173 }
174
175 return 0;
176 }
177
videostream_cb(HWND hwnd,LPVIDEOHDR vdhdr)178 static LRESULT CALLBACK videostream_cb(HWND hwnd, LPVIDEOHDR vdhdr)
179 {
180 AVFormatContext *s;
181 struct vfw_ctx *ctx;
182 PacketListEntry **ppktl, *pktl_next;
183
184 s = (AVFormatContext *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
185 ctx = s->priv_data;
186
187 dump_videohdr(s, vdhdr);
188
189 if(shall_we_drop(s))
190 return FALSE;
191
192 WaitForSingleObject(ctx->mutex, INFINITE);
193
194 pktl_next = av_mallocz(sizeof(*pktl_next));
195 if(!pktl_next)
196 goto fail;
197
198 if(av_new_packet(&pktl_next->pkt, vdhdr->dwBytesUsed) < 0) {
199 av_free(pktl_next);
200 goto fail;
201 }
202
203 pktl_next->pkt.pts = vdhdr->dwTimeCaptured;
204 memcpy(pktl_next->pkt.data, vdhdr->lpData, vdhdr->dwBytesUsed);
205
206 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
207 *ppktl = pktl_next;
208
209 ctx->curbufsize += vdhdr->dwBytesUsed;
210
211 SetEvent(ctx->event);
212 ReleaseMutex(ctx->mutex);
213
214 return TRUE;
215 fail:
216 ReleaseMutex(ctx->mutex);
217 return FALSE;
218 }
219
vfw_read_close(AVFormatContext * s)220 static int vfw_read_close(AVFormatContext *s)
221 {
222 struct vfw_ctx *ctx = s->priv_data;
223 PacketListEntry *pktl;
224
225 if(ctx->hwnd) {
226 SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);
227 SendMessage(ctx->hwnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
228 DestroyWindow(ctx->hwnd);
229 }
230 if(ctx->mutex)
231 CloseHandle(ctx->mutex);
232 if(ctx->event)
233 CloseHandle(ctx->event);
234
235 pktl = ctx->pktl;
236 while (pktl) {
237 PacketListEntry *next = pktl->next;
238 av_packet_unref(&pktl->pkt);
239 av_free(pktl);
240 pktl = next;
241 }
242
243 return 0;
244 }
245
vfw_read_header(AVFormatContext * s)246 static int vfw_read_header(AVFormatContext *s)
247 {
248 struct vfw_ctx *ctx = s->priv_data;
249 AVCodecParameters *par;
250 AVStream *st;
251 int devnum;
252 int bisize;
253 BITMAPINFO *bi = NULL;
254 CAPTUREPARMS cparms;
255 DWORD biCompression;
256 WORD biBitCount;
257 int ret;
258 AVRational framerate_q;
259
260 if (!strcmp(s->url, "list")) {
261 for (devnum = 0; devnum <= 9; devnum++) {
262 char driver_name[256];
263 char driver_ver[256];
264 ret = capGetDriverDescription(devnum,
265 driver_name, sizeof(driver_name),
266 driver_ver, sizeof(driver_ver));
267 if (ret) {
268 av_log(s, AV_LOG_INFO, "Driver %d\n", devnum);
269 av_log(s, AV_LOG_INFO, " %s\n", driver_name);
270 av_log(s, AV_LOG_INFO, " %s\n", driver_ver);
271 }
272 }
273 return AVERROR(EIO);
274 }
275
276 ctx->hwnd = capCreateCaptureWindow(NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0);
277 if(!ctx->hwnd) {
278 av_log(s, AV_LOG_ERROR, "Could not create capture window.\n");
279 return AVERROR(EIO);
280 }
281
282 /* If atoi fails, devnum==0 and the default device is used */
283 devnum = atoi(s->url);
284
285 ret = SendMessage(ctx->hwnd, WM_CAP_DRIVER_CONNECT, devnum, 0);
286 if(!ret) {
287 av_log(s, AV_LOG_ERROR, "Could not connect to device.\n");
288 DestroyWindow(ctx->hwnd);
289 return AVERROR(ENODEV);
290 }
291
292 SendMessage(ctx->hwnd, WM_CAP_SET_OVERLAY, 0, 0);
293 SendMessage(ctx->hwnd, WM_CAP_SET_PREVIEW, 0, 0);
294
295 ret = SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0,
296 (LPARAM) videostream_cb);
297 if(!ret) {
298 av_log(s, AV_LOG_ERROR, "Could not set video stream callback.\n");
299 goto fail;
300 }
301
302 SetWindowLongPtr(ctx->hwnd, GWLP_USERDATA, (LONG_PTR) s);
303
304 st = avformat_new_stream(s, NULL);
305 if(!st) {
306 vfw_read_close(s);
307 return AVERROR(ENOMEM);
308 }
309
310 /* Set video format */
311 bisize = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, 0, 0);
312 if(!bisize)
313 goto fail;
314 bi = av_malloc(bisize);
315 if(!bi) {
316 vfw_read_close(s);
317 return AVERROR(ENOMEM);
318 }
319 ret = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, bisize, (LPARAM) bi);
320 if(!ret)
321 goto fail;
322
323 dump_bih(s, &bi->bmiHeader);
324
325 ret = av_parse_video_rate(&framerate_q, ctx->framerate);
326 if (ret < 0) {
327 av_log(s, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
328 goto fail;
329 }
330
331 if (ctx->video_size) {
332 int w, h;
333 ret = av_parse_video_size(&w, &h, ctx->video_size);
334 if (ret < 0) {
335 av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");
336 goto fail;
337 }
338 bi->bmiHeader.biWidth = w;
339 bi->bmiHeader.biHeight = h;
340 }
341
342 if (0) {
343 /* For testing yet unsupported compressions
344 * Copy these values from user-supplied verbose information */
345 bi->bmiHeader.biWidth = 320;
346 bi->bmiHeader.biHeight = 240;
347 bi->bmiHeader.biPlanes = 1;
348 bi->bmiHeader.biBitCount = 12;
349 bi->bmiHeader.biCompression = MKTAG('I','4','2','0');
350 bi->bmiHeader.biSizeImage = 115200;
351 dump_bih(s, &bi->bmiHeader);
352 }
353
354 ret = SendMessage(ctx->hwnd, WM_CAP_SET_VIDEOFORMAT, bisize, (LPARAM) bi);
355 if(!ret) {
356 av_log(s, AV_LOG_ERROR, "Could not set Video Format.\n");
357 goto fail;
358 }
359
360 biCompression = bi->bmiHeader.biCompression;
361 biBitCount = bi->bmiHeader.biBitCount;
362
363 /* Set sequence setup */
364 ret = SendMessage(ctx->hwnd, WM_CAP_GET_SEQUENCE_SETUP, sizeof(cparms),
365 (LPARAM) &cparms);
366 if(!ret)
367 goto fail;
368
369 dump_captureparms(s, &cparms);
370
371 cparms.fYield = 1; // Spawn a background thread
372 cparms.dwRequestMicroSecPerFrame =
373 (framerate_q.den*1000000) / framerate_q.num;
374 cparms.fAbortLeftMouse = 0;
375 cparms.fAbortRightMouse = 0;
376 cparms.fCaptureAudio = 0;
377 cparms.vKeyAbort = 0;
378
379 ret = SendMessage(ctx->hwnd, WM_CAP_SET_SEQUENCE_SETUP, sizeof(cparms),
380 (LPARAM) &cparms);
381 if(!ret)
382 goto fail;
383
384 st->avg_frame_rate = framerate_q;
385
386 par = st->codecpar;
387 par->codec_type = AVMEDIA_TYPE_VIDEO;
388 par->width = bi->bmiHeader.biWidth;
389 par->height = bi->bmiHeader.biHeight;
390 par->format = vfw_pixfmt(biCompression, biBitCount);
391 if (par->format == AV_PIX_FMT_NONE) {
392 par->codec_id = vfw_codecid(biCompression);
393 if (par->codec_id == AV_CODEC_ID_NONE) {
394 avpriv_report_missing_feature(s, "This compression type");
395 vfw_read_close(s);
396 return AVERROR_PATCHWELCOME;
397 }
398 par->bits_per_coded_sample = biBitCount;
399 } else {
400 par->codec_id = AV_CODEC_ID_RAWVIDEO;
401 if(biCompression == BI_RGB) {
402 par->bits_per_coded_sample = biBitCount;
403 par->extradata = av_malloc(9 + AV_INPUT_BUFFER_PADDING_SIZE);
404 if (par->extradata) {
405 par->extradata_size = 9;
406 memcpy(par->extradata, "BottomUp", 9);
407 }
408 }
409 }
410
411 av_freep(&bi);
412
413 avpriv_set_pts_info(st, 32, 1, 1000);
414
415 ctx->mutex = CreateMutex(NULL, 0, NULL);
416 if(!ctx->mutex) {
417 av_log(s, AV_LOG_ERROR, "Could not create Mutex.\n" );
418 goto fail;
419 }
420 ctx->event = CreateEvent(NULL, 1, 0, NULL);
421 if(!ctx->event) {
422 av_log(s, AV_LOG_ERROR, "Could not create Event.\n" );
423 goto fail;
424 }
425
426 ret = SendMessage(ctx->hwnd, WM_CAP_SEQUENCE_NOFILE, 0, 0);
427 if(!ret) {
428 av_log(s, AV_LOG_ERROR, "Could not start capture sequence.\n" );
429 goto fail;
430 }
431
432 return 0;
433
434 fail:
435 av_freep(&bi);
436 vfw_read_close(s);
437 return AVERROR(EIO);
438 }
439
vfw_read_packet(AVFormatContext * s,AVPacket * pkt)440 static int vfw_read_packet(AVFormatContext *s, AVPacket *pkt)
441 {
442 struct vfw_ctx *ctx = s->priv_data;
443 PacketListEntry *pktl = NULL;
444
445 while(!pktl) {
446 WaitForSingleObject(ctx->mutex, INFINITE);
447 pktl = ctx->pktl;
448 if(ctx->pktl) {
449 *pkt = ctx->pktl->pkt;
450 ctx->pktl = ctx->pktl->next;
451 av_free(pktl);
452 }
453 ResetEvent(ctx->event);
454 ReleaseMutex(ctx->mutex);
455 if(!pktl) {
456 if(s->flags & AVFMT_FLAG_NONBLOCK) {
457 return AVERROR(EAGAIN);
458 } else {
459 WaitForSingleObject(ctx->event, INFINITE);
460 }
461 }
462 }
463
464 ctx->curbufsize -= pkt->size;
465
466 return pkt->size;
467 }
468
469 #define OFFSET(x) offsetof(struct vfw_ctx, x)
470 #define DEC AV_OPT_FLAG_DECODING_PARAM
471 static const AVOption options[] = {
472 { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
473 { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
474 { NULL },
475 };
476
477 static const AVClass vfw_class = {
478 .class_name = "VFW indev",
479 .item_name = av_default_item_name,
480 .option = options,
481 .version = LIBAVUTIL_VERSION_INT,
482 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT
483 };
484
485 const AVInputFormat ff_vfwcap_demuxer = {
486 .name = "vfwcap",
487 .long_name = NULL_IF_CONFIG_SMALL("VfW video capture"),
488 .priv_data_size = sizeof(struct vfw_ctx),
489 .read_header = vfw_read_header,
490 .read_packet = vfw_read_packet,
491 .read_close = vfw_read_close,
492 .flags = AVFMT_NOFILE,
493 .priv_class = &vfw_class,
494 };
495