OSDN Git Service

wavpack: Check error codes rather than working around error conditions.
[coroid/libav_saccubus.git] / 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     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
320     if (ctx->video_size) {
321         ret = av_parse_video_size(&bi->bmiHeader.biWidth, &bi->bmiHeader.biHeight, ctx->video_size);
322         if (ret < 0) {
323             av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");
324             goto fail_bi;
325         }
326     }
327
328     if (0) {
329         /* For testing yet unsupported compressions
330          * Copy these values from user-supplied verbose information */
331         bi->bmiHeader.biWidth       = 320;
332         bi->bmiHeader.biHeight      = 240;
333         bi->bmiHeader.biPlanes      = 1;
334         bi->bmiHeader.biBitCount    = 12;
335         bi->bmiHeader.biCompression = MKTAG('I','4','2','0');
336         bi->bmiHeader.biSizeImage   = 115200;
337         dump_bih(s, &bi->bmiHeader);
338     }
339
340     ret = SendMessage(ctx->hwnd, WM_CAP_SET_VIDEOFORMAT, bisize, (LPARAM) bi);
341     if(!ret) {
342         av_log(s, AV_LOG_ERROR, "Could not set Video Format.\n");
343         goto fail_bi;
344     }
345
346     biCompression = bi->bmiHeader.biCompression;
347     biBitCount = bi->bmiHeader.biBitCount;
348
349     av_free(bi);
350
351     /* Set sequence setup */
352     ret = SendMessage(ctx->hwnd, WM_CAP_GET_SEQUENCE_SETUP, sizeof(cparms),
353                       (LPARAM) &cparms);
354     if(!ret)
355         goto fail_io;
356
357     dump_captureparms(s, &cparms);
358
359     cparms.fYield = 1; // Spawn a background thread
360     cparms.dwRequestMicroSecPerFrame =
361                                (framerate_q.den*1000000) / framerate_q.num;
362     cparms.fAbortLeftMouse = 0;
363     cparms.fAbortRightMouse = 0;
364     cparms.fCaptureAudio = 0;
365     cparms.vKeyAbort = 0;
366
367     ret = SendMessage(ctx->hwnd, WM_CAP_SET_SEQUENCE_SETUP, sizeof(cparms),
368                       (LPARAM) &cparms);
369     if(!ret)
370         goto fail_io;
371
372     codec = st->codec;
373     codec->time_base = (AVRational){framerate_q.den, framerate_q.num};
374     codec->codec_type = AVMEDIA_TYPE_VIDEO;
375     codec->width  = bi->bmiHeader.biWidth;
376     codec->height = bi->bmiHeader.biHeight;
377     codec->pix_fmt = vfw_pixfmt(biCompression, biBitCount);
378     if(codec->pix_fmt == PIX_FMT_NONE) {
379         codec->codec_id = vfw_codecid(biCompression);
380         if(codec->codec_id == CODEC_ID_NONE) {
381             av_log(s, AV_LOG_ERROR, "Unknown compression type. "
382                              "Please report verbose (-v 9) debug information.\n");
383             vfw_read_close(s);
384             return AVERROR_PATCHWELCOME;
385         }
386         codec->bits_per_coded_sample = biBitCount;
387     } else {
388         codec->codec_id = CODEC_ID_RAWVIDEO;
389         if(biCompression == BI_RGB) {
390             codec->bits_per_coded_sample = biBitCount;
391             codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
392             if (codec->extradata) {
393                 codec->extradata_size = 9;
394                 memcpy(codec->extradata, "BottomUp", 9);
395             }
396         }
397     }
398
399     av_set_pts_info(st, 32, 1, 1000);
400
401     ctx->mutex = CreateMutex(NULL, 0, NULL);
402     if(!ctx->mutex) {
403         av_log(s, AV_LOG_ERROR, "Could not create Mutex.\n" );
404         goto fail_io;
405     }
406     ctx->event = CreateEvent(NULL, 1, 0, NULL);
407     if(!ctx->event) {
408         av_log(s, AV_LOG_ERROR, "Could not create Event.\n" );
409         goto fail_io;
410     }
411
412     ret = SendMessage(ctx->hwnd, WM_CAP_SEQUENCE_NOFILE, 0, 0);
413     if(!ret) {
414         av_log(s, AV_LOG_ERROR, "Could not start capture sequence.\n" );
415         goto fail_io;
416     }
417
418     return 0;
419
420 fail_bi:
421     av_free(bi);
422
423 fail_io:
424     vfw_read_close(s);
425     return AVERROR(EIO);
426 }
427
428 static int vfw_read_packet(AVFormatContext *s, AVPacket *pkt)
429 {
430     struct vfw_ctx *ctx = s->priv_data;
431     AVPacketList *pktl = NULL;
432
433     while(!pktl) {
434         WaitForSingleObject(ctx->mutex, INFINITE);
435         pktl = ctx->pktl;
436         if(ctx->pktl) {
437             *pkt = ctx->pktl->pkt;
438             ctx->pktl = ctx->pktl->next;
439             av_free(pktl);
440         }
441         ResetEvent(ctx->event);
442         ReleaseMutex(ctx->mutex);
443         if(!pktl) {
444             if(s->flags & AVFMT_FLAG_NONBLOCK) {
445                 return AVERROR(EAGAIN);
446             } else {
447                 WaitForSingleObject(ctx->event, INFINITE);
448             }
449         }
450     }
451
452     ctx->curbufsize -= pkt->size;
453
454     return pkt->size;
455 }
456
457 #define OFFSET(x) offsetof(struct vfw_ctx, x)
458 #define DEC AV_OPT_FLAG_DECODING_PARAM
459 static const AVOption options[] = {
460     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
461     { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
462     { NULL },
463 };
464
465 static const AVClass vfw_class = {
466     .class_name = "VFW indev",
467     .item_name  = av_default_item_name,
468     .option     = options,
469     .version    = LIBAVUTIL_VERSION_INT,
470 };
471
472 AVInputFormat ff_vfwcap_demuxer = {
473     "vfwcap",
474     NULL_IF_CONFIG_SMALL("VFW video capture"),
475     sizeof(struct vfw_ctx),
476     NULL,
477     vfw_read_header,
478     vfw_read_packet,
479     vfw_read_close,
480     .flags = AVFMT_NOFILE,
481     .priv_class = &vfw_class,
482 };