vfwcap.c 15 KB

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