vfwcap.c 15 KB

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