You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

479 lines
14KB

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