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