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