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