vfwcap.c 15 KB

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