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