vfwcap.c 14 KB

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