vfwcap.c 15 KB

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