vfwcap.c 15 KB

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