• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavdevice/vfwcap.c

Go to the documentation of this file.
00001 /*
00002  * VFW capture interface
00003  * Copyright (c) 2006-2008 Ramiro Polla
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavformat/avformat.h"
00023 #include "libavformat/internal.h"
00024 #include "libavutil/log.h"
00025 #include "libavutil/opt.h"
00026 #include "libavutil/parseutils.h"
00027 #include <windows.h>
00028 #include <vfw.h>
00029 
00030 /* Defines for VFW missing from MinGW.
00031  * Remove this when MinGW incorporates them. */
00032 #define HWND_MESSAGE                ((HWND)-3)
00033 
00034 #define BI_RGB                      0
00035 
00036 /* End of missing MinGW defines */
00037 
00038 struct vfw_ctx {
00039     const AVClass *class;
00040     HWND hwnd;
00041     HANDLE mutex;
00042     HANDLE event;
00043     AVPacketList *pktl;
00044     unsigned int curbufsize;
00045     unsigned int frame_num;
00046     char *video_size;       
00047     char *framerate;        
00048 };
00049 
00050 static enum PixelFormat vfw_pixfmt(DWORD biCompression, WORD biBitCount)
00051 {
00052     switch(biCompression) {
00053     case MKTAG('U', 'Y', 'V', 'Y'):
00054         return PIX_FMT_UYVY422;
00055     case MKTAG('Y', 'U', 'Y', '2'):
00056         return PIX_FMT_YUYV422;
00057     case MKTAG('I', '4', '2', '0'):
00058         return PIX_FMT_YUV420P;
00059     case BI_RGB:
00060         switch(biBitCount) { /* 1-8 are untested */
00061             case 1:
00062                 return PIX_FMT_MONOWHITE;
00063             case 4:
00064                 return PIX_FMT_RGB4;
00065             case 8:
00066                 return PIX_FMT_RGB8;
00067             case 16:
00068                 return PIX_FMT_RGB555;
00069             case 24:
00070                 return PIX_FMT_BGR24;
00071             case 32:
00072                 return PIX_FMT_RGB32;
00073         }
00074     }
00075     return PIX_FMT_NONE;
00076 }
00077 
00078 static enum CodecID vfw_codecid(DWORD biCompression)
00079 {
00080     switch(biCompression) {
00081     case MKTAG('d', 'v', 's', 'd'):
00082         return CODEC_ID_DVVIDEO;
00083     case MKTAG('M', 'J', 'P', 'G'):
00084     case MKTAG('m', 'j', 'p', 'g'):
00085         return CODEC_ID_MJPEG;
00086     }
00087     return CODEC_ID_NONE;
00088 }
00089 
00090 #define dstruct(pctx, sname, var, type) \
00091     av_log(pctx, AV_LOG_DEBUG, #var":\t%"type"\n", sname->var)
00092 
00093 static void dump_captureparms(AVFormatContext *s, CAPTUREPARMS *cparms)
00094 {
00095     av_log(s, AV_LOG_DEBUG, "CAPTUREPARMS\n");
00096     dstruct(s, cparms, dwRequestMicroSecPerFrame, "lu");
00097     dstruct(s, cparms, fMakeUserHitOKToCapture, "d");
00098     dstruct(s, cparms, wPercentDropForError, "u");
00099     dstruct(s, cparms, fYield, "d");
00100     dstruct(s, cparms, dwIndexSize, "lu");
00101     dstruct(s, cparms, wChunkGranularity, "u");
00102     dstruct(s, cparms, fUsingDOSMemory, "d");
00103     dstruct(s, cparms, wNumVideoRequested, "u");
00104     dstruct(s, cparms, fCaptureAudio, "d");
00105     dstruct(s, cparms, wNumAudioRequested, "u");
00106     dstruct(s, cparms, vKeyAbort, "u");
00107     dstruct(s, cparms, fAbortLeftMouse, "d");
00108     dstruct(s, cparms, fAbortRightMouse, "d");
00109     dstruct(s, cparms, fLimitEnabled, "d");
00110     dstruct(s, cparms, wTimeLimit, "u");
00111     dstruct(s, cparms, fMCIControl, "d");
00112     dstruct(s, cparms, fStepMCIDevice, "d");
00113     dstruct(s, cparms, dwMCIStartTime, "lu");
00114     dstruct(s, cparms, dwMCIStopTime, "lu");
00115     dstruct(s, cparms, fStepCaptureAt2x, "d");
00116     dstruct(s, cparms, wStepCaptureAverageFrames, "u");
00117     dstruct(s, cparms, dwAudioBufferSize, "lu");
00118     dstruct(s, cparms, fDisableWriteCache, "d");
00119     dstruct(s, cparms, AVStreamMaster, "u");
00120 }
00121 
00122 static void dump_videohdr(AVFormatContext *s, VIDEOHDR *vhdr)
00123 {
00124 #ifdef DEBUG
00125     av_log(s, AV_LOG_DEBUG, "VIDEOHDR\n");
00126     dstruct(s, vhdr, lpData, "p");
00127     dstruct(s, vhdr, dwBufferLength, "lu");
00128     dstruct(s, vhdr, dwBytesUsed, "lu");
00129     dstruct(s, vhdr, dwTimeCaptured, "lu");
00130     dstruct(s, vhdr, dwUser, "lu");
00131     dstruct(s, vhdr, dwFlags, "lu");
00132     dstruct(s, vhdr, dwReserved[0], "lu");
00133     dstruct(s, vhdr, dwReserved[1], "lu");
00134     dstruct(s, vhdr, dwReserved[2], "lu");
00135     dstruct(s, vhdr, dwReserved[3], "lu");
00136 #endif
00137 }
00138 
00139 static void dump_bih(AVFormatContext *s, BITMAPINFOHEADER *bih)
00140 {
00141     av_log(s, AV_LOG_DEBUG, "BITMAPINFOHEADER\n");
00142     dstruct(s, bih, biSize, "lu");
00143     dstruct(s, bih, biWidth, "ld");
00144     dstruct(s, bih, biHeight, "ld");
00145     dstruct(s, bih, biPlanes, "d");
00146     dstruct(s, bih, biBitCount, "d");
00147     dstruct(s, bih, biCompression, "lu");
00148     av_log(s, AV_LOG_DEBUG, "    biCompression:\t\"%.4s\"\n",
00149                    (char*) &bih->biCompression);
00150     dstruct(s, bih, biSizeImage, "lu");
00151     dstruct(s, bih, biXPelsPerMeter, "lu");
00152     dstruct(s, bih, biYPelsPerMeter, "lu");
00153     dstruct(s, bih, biClrUsed, "lu");
00154     dstruct(s, bih, biClrImportant, "lu");
00155 }
00156 
00157 static int shall_we_drop(AVFormatContext *s)
00158 {
00159     struct vfw_ctx *ctx = s->priv_data;
00160     const uint8_t dropscore[] = {62, 75, 87, 100};
00161     const int ndropscores = FF_ARRAY_ELEMS(dropscore);
00162     unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
00163 
00164     if(dropscore[++ctx->frame_num%ndropscores] <= buffer_fullness) {
00165         av_log(s, AV_LOG_ERROR,
00166               "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
00167         return 1;
00168     }
00169 
00170     return 0;
00171 }
00172 
00173 static LRESULT CALLBACK videostream_cb(HWND hwnd, LPVIDEOHDR vdhdr)
00174 {
00175     AVFormatContext *s;
00176     struct vfw_ctx *ctx;
00177     AVPacketList **ppktl, *pktl_next;
00178 
00179     s = (AVFormatContext *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
00180     ctx = s->priv_data;
00181 
00182     dump_videohdr(s, vdhdr);
00183 
00184     if(shall_we_drop(s))
00185         return FALSE;
00186 
00187     WaitForSingleObject(ctx->mutex, INFINITE);
00188 
00189     pktl_next = av_mallocz(sizeof(AVPacketList));
00190     if(!pktl_next)
00191         goto fail;
00192 
00193     if(av_new_packet(&pktl_next->pkt, vdhdr->dwBytesUsed) < 0) {
00194         av_free(pktl_next);
00195         goto fail;
00196     }
00197 
00198     pktl_next->pkt.pts = vdhdr->dwTimeCaptured;
00199     memcpy(pktl_next->pkt.data, vdhdr->lpData, vdhdr->dwBytesUsed);
00200 
00201     for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
00202     *ppktl = pktl_next;
00203 
00204     ctx->curbufsize += vdhdr->dwBytesUsed;
00205 
00206     SetEvent(ctx->event);
00207     ReleaseMutex(ctx->mutex);
00208 
00209     return TRUE;
00210 fail:
00211     ReleaseMutex(ctx->mutex);
00212     return FALSE;
00213 }
00214 
00215 static int vfw_read_close(AVFormatContext *s)
00216 {
00217     struct vfw_ctx *ctx = s->priv_data;
00218     AVPacketList *pktl;
00219 
00220     if(ctx->hwnd) {
00221         SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);
00222         SendMessage(ctx->hwnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
00223         DestroyWindow(ctx->hwnd);
00224     }
00225     if(ctx->mutex)
00226         CloseHandle(ctx->mutex);
00227     if(ctx->event)
00228         CloseHandle(ctx->event);
00229 
00230     pktl = ctx->pktl;
00231     while (pktl) {
00232         AVPacketList *next = pktl->next;
00233         av_destruct_packet(&pktl->pkt);
00234         av_free(pktl);
00235         pktl = next;
00236     }
00237 
00238     return 0;
00239 }
00240 
00241 static int vfw_read_header(AVFormatContext *s, AVFormatParameters *ap)
00242 {
00243     struct vfw_ctx *ctx = s->priv_data;
00244     AVCodecContext *codec;
00245     AVStream *st;
00246     int devnum;
00247     int bisize;
00248     BITMAPINFO *bi;
00249     CAPTUREPARMS cparms;
00250     DWORD biCompression;
00251     WORD biBitCount;
00252     int ret;
00253     AVRational framerate_q;
00254 
00255     if (!strcmp(s->filename, "list")) {
00256         for (devnum = 0; devnum <= 9; devnum++) {
00257             char driver_name[256];
00258             char driver_ver[256];
00259             ret = capGetDriverDescription(devnum,
00260                                           driver_name, sizeof(driver_name),
00261                                           driver_ver, sizeof(driver_ver));
00262             if (ret) {
00263                 av_log(s, AV_LOG_INFO, "Driver %d\n", devnum);
00264                 av_log(s, AV_LOG_INFO, " %s\n", driver_name);
00265                 av_log(s, AV_LOG_INFO, " %s\n", driver_ver);
00266             }
00267         }
00268         return AVERROR(EIO);
00269     }
00270 
00271     ctx->hwnd = capCreateCaptureWindow(NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0);
00272     if(!ctx->hwnd) {
00273         av_log(s, AV_LOG_ERROR, "Could not create capture window.\n");
00274         return AVERROR(EIO);
00275     }
00276 
00277     /* If atoi fails, devnum==0 and the default device is used */
00278     devnum = atoi(s->filename);
00279 
00280     ret = SendMessage(ctx->hwnd, WM_CAP_DRIVER_CONNECT, devnum, 0);
00281     if(!ret) {
00282         av_log(s, AV_LOG_ERROR, "Could not connect to device.\n");
00283         DestroyWindow(ctx->hwnd);
00284         return AVERROR(ENODEV);
00285     }
00286 
00287     SendMessage(ctx->hwnd, WM_CAP_SET_OVERLAY, 0, 0);
00288     SendMessage(ctx->hwnd, WM_CAP_SET_PREVIEW, 0, 0);
00289 
00290     ret = SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0,
00291                       (LPARAM) videostream_cb);
00292     if(!ret) {
00293         av_log(s, AV_LOG_ERROR, "Could not set video stream callback.\n");
00294         goto fail_io;
00295     }
00296 
00297     SetWindowLongPtr(ctx->hwnd, GWLP_USERDATA, (LONG_PTR) s);
00298 
00299     st = avformat_new_stream(s, NULL);
00300     if(!st) {
00301         vfw_read_close(s);
00302         return AVERROR(ENOMEM);
00303     }
00304 
00305     /* Set video format */
00306     bisize = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, 0, 0);
00307     if(!bisize)
00308         goto fail_io;
00309     bi = av_malloc(bisize);
00310     if(!bi) {
00311         vfw_read_close(s);
00312         return AVERROR(ENOMEM);
00313     }
00314     ret = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, bisize, (LPARAM) bi);
00315     if(!ret)
00316         goto fail_bi;
00317 
00318     dump_bih(s, &bi->bmiHeader);
00319 
00320 
00321     if (ctx->video_size) {
00322         ret = av_parse_video_size(&bi->bmiHeader.biWidth, &bi->bmiHeader.biHeight, ctx->video_size);
00323         if (ret < 0) {
00324             av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");
00325             goto fail_bi;
00326         }
00327     }
00328 
00329     if (0) {
00330         /* For testing yet unsupported compressions
00331          * Copy these values from user-supplied verbose information */
00332         bi->bmiHeader.biWidth       = 320;
00333         bi->bmiHeader.biHeight      = 240;
00334         bi->bmiHeader.biPlanes      = 1;
00335         bi->bmiHeader.biBitCount    = 12;
00336         bi->bmiHeader.biCompression = MKTAG('I','4','2','0');
00337         bi->bmiHeader.biSizeImage   = 115200;
00338         dump_bih(s, &bi->bmiHeader);
00339     }
00340 
00341     ret = SendMessage(ctx->hwnd, WM_CAP_SET_VIDEOFORMAT, bisize, (LPARAM) bi);
00342     if(!ret) {
00343         av_log(s, AV_LOG_ERROR, "Could not set Video Format.\n");
00344         goto fail_bi;
00345     }
00346 
00347     biCompression = bi->bmiHeader.biCompression;
00348     biBitCount = bi->bmiHeader.biBitCount;
00349 
00350     av_free(bi);
00351 
00352     /* Set sequence setup */
00353     ret = SendMessage(ctx->hwnd, WM_CAP_GET_SEQUENCE_SETUP, sizeof(cparms),
00354                       (LPARAM) &cparms);
00355     if(!ret)
00356         goto fail_io;
00357 
00358     dump_captureparms(s, &cparms);
00359 
00360     cparms.fYield = 1; // Spawn a background thread
00361     cparms.dwRequestMicroSecPerFrame =
00362                                (framerate_q.den*1000000) / framerate_q.num;
00363     cparms.fAbortLeftMouse = 0;
00364     cparms.fAbortRightMouse = 0;
00365     cparms.fCaptureAudio = 0;
00366     cparms.vKeyAbort = 0;
00367 
00368     ret = SendMessage(ctx->hwnd, WM_CAP_SET_SEQUENCE_SETUP, sizeof(cparms),
00369                       (LPARAM) &cparms);
00370     if(!ret)
00371         goto fail_io;
00372 
00373     codec = st->codec;
00374     codec->time_base = (AVRational){framerate_q.den, framerate_q.num};
00375     codec->codec_type = AVMEDIA_TYPE_VIDEO;
00376     codec->width  = bi->bmiHeader.biWidth;
00377     codec->height = bi->bmiHeader.biHeight;
00378     codec->pix_fmt = vfw_pixfmt(biCompression, biBitCount);
00379     if(codec->pix_fmt == PIX_FMT_NONE) {
00380         codec->codec_id = vfw_codecid(biCompression);
00381         if(codec->codec_id == CODEC_ID_NONE) {
00382             av_log(s, AV_LOG_ERROR, "Unknown compression type. "
00383                              "Please report verbose (-v 9) debug information.\n");
00384             vfw_read_close(s);
00385             return AVERROR_PATCHWELCOME;
00386         }
00387         codec->bits_per_coded_sample = biBitCount;
00388     } else {
00389         codec->codec_id = CODEC_ID_RAWVIDEO;
00390         if(biCompression == BI_RGB) {
00391             codec->bits_per_coded_sample = biBitCount;
00392             codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
00393             if (codec->extradata) {
00394                 codec->extradata_size = 9;
00395                 memcpy(codec->extradata, "BottomUp", 9);
00396             }
00397         }
00398     }
00399 
00400     avpriv_set_pts_info(st, 32, 1, 1000);
00401 
00402     ctx->mutex = CreateMutex(NULL, 0, NULL);
00403     if(!ctx->mutex) {
00404         av_log(s, AV_LOG_ERROR, "Could not create Mutex.\n" );
00405         goto fail_io;
00406     }
00407     ctx->event = CreateEvent(NULL, 1, 0, NULL);
00408     if(!ctx->event) {
00409         av_log(s, AV_LOG_ERROR, "Could not create Event.\n" );
00410         goto fail_io;
00411     }
00412 
00413     ret = SendMessage(ctx->hwnd, WM_CAP_SEQUENCE_NOFILE, 0, 0);
00414     if(!ret) {
00415         av_log(s, AV_LOG_ERROR, "Could not start capture sequence.\n" );
00416         goto fail_io;
00417     }
00418 
00419     return 0;
00420 
00421 fail_bi:
00422     av_free(bi);
00423 
00424 fail_io:
00425     vfw_read_close(s);
00426     return AVERROR(EIO);
00427 }
00428 
00429 static int vfw_read_packet(AVFormatContext *s, AVPacket *pkt)
00430 {
00431     struct vfw_ctx *ctx = s->priv_data;
00432     AVPacketList *pktl = NULL;
00433 
00434     while(!pktl) {
00435         WaitForSingleObject(ctx->mutex, INFINITE);
00436         pktl = ctx->pktl;
00437         if(ctx->pktl) {
00438             *pkt = ctx->pktl->pkt;
00439             ctx->pktl = ctx->pktl->next;
00440             av_free(pktl);
00441         }
00442         ResetEvent(ctx->event);
00443         ReleaseMutex(ctx->mutex);
00444         if(!pktl) {
00445             if(s->flags & AVFMT_FLAG_NONBLOCK) {
00446                 return AVERROR(EAGAIN);
00447             } else {
00448                 WaitForSingleObject(ctx->event, INFINITE);
00449             }
00450         }
00451     }
00452 
00453     ctx->curbufsize -= pkt->size;
00454 
00455     return pkt->size;
00456 }
00457 
00458 #define OFFSET(x) offsetof(struct vfw_ctx, x)
00459 #define DEC AV_OPT_FLAG_DECODING_PARAM
00460 static const AVOption options[] = {
00461     { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
00462     { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = "ntsc"}, 0, 0, DEC },
00463     { NULL },
00464 };
00465 
00466 static const AVClass vfw_class = {
00467     .class_name = "VFW indev",
00468     .item_name  = av_default_item_name,
00469     .option     = options,
00470     .version    = LIBAVUTIL_VERSION_INT,
00471 };
00472 
00473 AVInputFormat ff_vfwcap_demuxer = {
00474     .name           = "vfwcap",
00475     .long_name      = NULL_IF_CONFIG_SMALL("VfW video capture"),
00476     .priv_data_size = sizeof(struct vfw_ctx),
00477     .read_header    = vfw_read_header,
00478     .read_packet    = vfw_read_packet,
00479     .read_close     = vfw_read_close,
00480     .flags          = AVFMT_NOFILE,
00481     .priv_class     = &vfw_class,
00482 };
Generated on Sat Mar 17 2012 12:57:52 for Libav by doxygen 1.7.1