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