vfwcap.c 15 KB

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