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