dshow.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. /*
  2. * Directshow capture interface
  3. * Copyright (c) 2010 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 "dshow_capture.h"
  22. #include "libavutil/parseutils.h"
  23. #include "libavutil/pixdesc.h"
  24. #include "libavutil/opt.h"
  25. #include "libavformat/internal.h"
  26. #include "libavformat/riff.h"
  27. #include "avdevice.h"
  28. #include "libavcodec/raw.h"
  29. #include "objidl.h"
  30. #include "shlwapi.h"
  31. static enum AVPixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
  32. {
  33. switch(biCompression) {
  34. case BI_BITFIELDS:
  35. case BI_RGB:
  36. switch(biBitCount) { /* 1-8 are untested */
  37. case 1:
  38. return AV_PIX_FMT_MONOWHITE;
  39. case 4:
  40. return AV_PIX_FMT_RGB4;
  41. case 8:
  42. return AV_PIX_FMT_RGB8;
  43. case 16:
  44. return AV_PIX_FMT_RGB555;
  45. case 24:
  46. return AV_PIX_FMT_BGR24;
  47. case 32:
  48. return AV_PIX_FMT_0RGB32;
  49. }
  50. }
  51. return avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), biCompression); // all others
  52. }
  53. static int
  54. dshow_read_close(AVFormatContext *s)
  55. {
  56. struct dshow_ctx *ctx = s->priv_data;
  57. AVPacketList *pktl;
  58. if (ctx->control) {
  59. IMediaControl_Stop(ctx->control);
  60. IMediaControl_Release(ctx->control);
  61. }
  62. if (ctx->media_event)
  63. IMediaEvent_Release(ctx->media_event);
  64. if (ctx->graph) {
  65. IEnumFilters *fenum;
  66. int r;
  67. r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
  68. if (r == S_OK) {
  69. IBaseFilter *f;
  70. IEnumFilters_Reset(fenum);
  71. while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK) {
  72. if (IGraphBuilder_RemoveFilter(ctx->graph, f) == S_OK)
  73. IEnumFilters_Reset(fenum); /* When a filter is removed,
  74. * the list must be reset. */
  75. IBaseFilter_Release(f);
  76. }
  77. IEnumFilters_Release(fenum);
  78. }
  79. IGraphBuilder_Release(ctx->graph);
  80. }
  81. if (ctx->capture_pin[VideoDevice])
  82. libAVPin_Release(ctx->capture_pin[VideoDevice]);
  83. if (ctx->capture_pin[AudioDevice])
  84. libAVPin_Release(ctx->capture_pin[AudioDevice]);
  85. if (ctx->capture_filter[VideoDevice])
  86. libAVFilter_Release(ctx->capture_filter[VideoDevice]);
  87. if (ctx->capture_filter[AudioDevice])
  88. libAVFilter_Release(ctx->capture_filter[AudioDevice]);
  89. if (ctx->device_pin[VideoDevice])
  90. IPin_Release(ctx->device_pin[VideoDevice]);
  91. if (ctx->device_pin[AudioDevice])
  92. IPin_Release(ctx->device_pin[AudioDevice]);
  93. if (ctx->device_filter[VideoDevice])
  94. IBaseFilter_Release(ctx->device_filter[VideoDevice]);
  95. if (ctx->device_filter[AudioDevice])
  96. IBaseFilter_Release(ctx->device_filter[AudioDevice]);
  97. av_freep(&ctx->device_name[0]);
  98. av_freep(&ctx->device_name[1]);
  99. av_freep(&ctx->device_unique_name[0]);
  100. av_freep(&ctx->device_unique_name[1]);
  101. if(ctx->mutex)
  102. CloseHandle(ctx->mutex);
  103. if(ctx->event[0])
  104. CloseHandle(ctx->event[0]);
  105. if(ctx->event[1])
  106. CloseHandle(ctx->event[1]);
  107. pktl = ctx->pktl;
  108. while (pktl) {
  109. AVPacketList *next = pktl->next;
  110. av_packet_unref(&pktl->pkt);
  111. av_free(pktl);
  112. pktl = next;
  113. }
  114. CoUninitialize();
  115. return 0;
  116. }
  117. static char *dup_wchar_to_utf8(wchar_t *w)
  118. {
  119. char *s = NULL;
  120. int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
  121. s = av_malloc(l);
  122. if (s)
  123. WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
  124. return s;
  125. }
  126. static int shall_we_drop(AVFormatContext *s, int index, enum dshowDeviceType devtype)
  127. {
  128. struct dshow_ctx *ctx = s->priv_data;
  129. static const uint8_t dropscore[] = {62, 75, 87, 100};
  130. const int ndropscores = FF_ARRAY_ELEMS(dropscore);
  131. unsigned int buffer_fullness = (ctx->curbufsize[index]*100)/s->max_picture_buffer;
  132. const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
  133. if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
  134. av_log(s, AV_LOG_ERROR,
  135. "real-time buffer [%s] [%s input] too full or near too full (%d%% of size: %d [rtbufsize parameter])! frame dropped!\n",
  136. ctx->device_name[devtype], devtypename, buffer_fullness, s->max_picture_buffer);
  137. return 1;
  138. }
  139. return 0;
  140. }
  141. static void
  142. callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time, enum dshowDeviceType devtype)
  143. {
  144. AVFormatContext *s = priv_data;
  145. struct dshow_ctx *ctx = s->priv_data;
  146. AVPacketList **ppktl, *pktl_next;
  147. // dump_videohdr(s, vdhdr);
  148. WaitForSingleObject(ctx->mutex, INFINITE);
  149. if(shall_we_drop(s, index, devtype))
  150. goto fail;
  151. pktl_next = av_mallocz(sizeof(AVPacketList));
  152. if(!pktl_next)
  153. goto fail;
  154. if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
  155. av_free(pktl_next);
  156. goto fail;
  157. }
  158. pktl_next->pkt.stream_index = index;
  159. pktl_next->pkt.pts = time;
  160. memcpy(pktl_next->pkt.data, buf, buf_size);
  161. for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
  162. *ppktl = pktl_next;
  163. ctx->curbufsize[index] += buf_size;
  164. SetEvent(ctx->event[1]);
  165. ReleaseMutex(ctx->mutex);
  166. return;
  167. fail:
  168. ReleaseMutex(ctx->mutex);
  169. return;
  170. }
  171. /**
  172. * Cycle through available devices using the device enumerator devenum,
  173. * retrieve the device with type specified by devtype and return the
  174. * pointer to the object found in *pfilter.
  175. * If pfilter is NULL, list all device names.
  176. */
  177. static int
  178. dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,
  179. enum dshowDeviceType devtype, enum dshowSourceFilterType sourcetype,
  180. IBaseFilter **pfilter, char **device_unique_name)
  181. {
  182. struct dshow_ctx *ctx = avctx->priv_data;
  183. IBaseFilter *device_filter = NULL;
  184. IEnumMoniker *classenum = NULL;
  185. IMoniker *m = NULL;
  186. const char *device_name = ctx->device_name[devtype];
  187. int skip = (devtype == VideoDevice) ? ctx->video_device_number
  188. : ctx->audio_device_number;
  189. int r;
  190. const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
  191. &CLSID_AudioInputDeviceCategory };
  192. const char *devtypename = (devtype == VideoDevice) ? "video" : "audio only";
  193. const char *sourcetypename = (sourcetype == VideoSourceDevice) ? "video" : "audio";
  194. r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[sourcetype],
  195. (IEnumMoniker **) &classenum, 0);
  196. if (r != S_OK) {
  197. av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices (or none found).\n",
  198. devtypename);
  199. return AVERROR(EIO);
  200. }
  201. while (!device_filter && IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK) {
  202. IPropertyBag *bag = NULL;
  203. char *friendly_name = NULL;
  204. char *unique_name = NULL;
  205. VARIANT var;
  206. IBindCtx *bind_ctx = NULL;
  207. LPOLESTR olestr = NULL;
  208. LPMALLOC co_malloc = NULL;
  209. int i;
  210. r = CoGetMalloc(1, &co_malloc);
  211. if (r != S_OK)
  212. goto fail1;
  213. r = CreateBindCtx(0, &bind_ctx);
  214. if (r != S_OK)
  215. goto fail1;
  216. /* GetDisplayname works for both video and audio, DevicePath doesn't */
  217. r = IMoniker_GetDisplayName(m, bind_ctx, NULL, &olestr);
  218. if (r != S_OK)
  219. goto fail1;
  220. unique_name = dup_wchar_to_utf8(olestr);
  221. /* replace ':' with '_' since we use : to delineate between sources */
  222. for (i = 0; i < strlen(unique_name); i++) {
  223. if (unique_name[i] == ':')
  224. unique_name[i] = '_';
  225. }
  226. r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
  227. if (r != S_OK)
  228. goto fail1;
  229. var.vt = VT_BSTR;
  230. r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
  231. if (r != S_OK)
  232. goto fail1;
  233. friendly_name = dup_wchar_to_utf8(var.bstrVal);
  234. if (pfilter) {
  235. if (strcmp(device_name, friendly_name) && strcmp(device_name, unique_name))
  236. goto fail1;
  237. if (!skip--) {
  238. r = IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
  239. if (r != S_OK) {
  240. av_log(avctx, AV_LOG_ERROR, "Unable to BindToObject for %s\n", device_name);
  241. goto fail1;
  242. }
  243. *device_unique_name = unique_name;
  244. // success, loop will end now
  245. }
  246. } else {
  247. av_log(avctx, AV_LOG_INFO, " \"%s\"\n", friendly_name);
  248. av_log(avctx, AV_LOG_INFO, " Alternative name \"%s\"\n", unique_name);
  249. av_free(unique_name);
  250. }
  251. fail1:
  252. if (olestr && co_malloc)
  253. IMalloc_Free(co_malloc, olestr);
  254. if (bind_ctx)
  255. IBindCtx_Release(bind_ctx);
  256. av_free(friendly_name);
  257. if (bag)
  258. IPropertyBag_Release(bag);
  259. IMoniker_Release(m);
  260. }
  261. IEnumMoniker_Release(classenum);
  262. if (pfilter) {
  263. if (!device_filter) {
  264. av_log(avctx, AV_LOG_ERROR, "Could not find %s device with name [%s] among source devices of type %s.\n",
  265. devtypename, device_name, sourcetypename);
  266. return AVERROR(EIO);
  267. }
  268. *pfilter = device_filter;
  269. }
  270. return 0;
  271. }
  272. /**
  273. * Cycle through available formats using the specified pin,
  274. * try to set parameters specified through AVOptions and if successful
  275. * return 1 in *pformat_set.
  276. * If pformat_set is NULL, list all pin capabilities.
  277. */
  278. static void
  279. dshow_cycle_formats(AVFormatContext *avctx, enum dshowDeviceType devtype,
  280. IPin *pin, int *pformat_set)
  281. {
  282. struct dshow_ctx *ctx = avctx->priv_data;
  283. IAMStreamConfig *config = NULL;
  284. AM_MEDIA_TYPE *type = NULL;
  285. int format_set = 0;
  286. void *caps = NULL;
  287. int i, n, size, r;
  288. if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
  289. return;
  290. if (IAMStreamConfig_GetNumberOfCapabilities(config, &n, &size) != S_OK)
  291. goto end;
  292. caps = av_malloc(size);
  293. if (!caps)
  294. goto end;
  295. for (i = 0; i < n && !format_set; i++) {
  296. r = IAMStreamConfig_GetStreamCaps(config, i, &type, (void *) caps);
  297. if (r != S_OK)
  298. goto next;
  299. #if DSHOWDEBUG
  300. ff_print_AM_MEDIA_TYPE(type);
  301. #endif
  302. if (devtype == VideoDevice) {
  303. VIDEO_STREAM_CONFIG_CAPS *vcaps = caps;
  304. BITMAPINFOHEADER *bih;
  305. int64_t *fr;
  306. const AVCodecTag *const tags[] = { avformat_get_riff_video_tags(), NULL };
  307. #if DSHOWDEBUG
  308. ff_print_VIDEO_STREAM_CONFIG_CAPS(vcaps);
  309. #endif
  310. if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo)) {
  311. VIDEOINFOHEADER *v = (void *) type->pbFormat;
  312. fr = &v->AvgTimePerFrame;
  313. bih = &v->bmiHeader;
  314. } else if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo2)) {
  315. VIDEOINFOHEADER2 *v = (void *) type->pbFormat;
  316. fr = &v->AvgTimePerFrame;
  317. bih = &v->bmiHeader;
  318. } else {
  319. goto next;
  320. }
  321. if (!pformat_set) {
  322. enum AVPixelFormat pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
  323. if (pix_fmt == AV_PIX_FMT_NONE) {
  324. enum AVCodecID codec_id = av_codec_get_id(tags, bih->biCompression);
  325. AVCodec *codec = avcodec_find_decoder(codec_id);
  326. if (codec_id == AV_CODEC_ID_NONE || !codec) {
  327. av_log(avctx, AV_LOG_INFO, " unknown compression type 0x%X", (int) bih->biCompression);
  328. } else {
  329. av_log(avctx, AV_LOG_INFO, " vcodec=%s", codec->name);
  330. }
  331. } else {
  332. av_log(avctx, AV_LOG_INFO, " pixel_format=%s", av_get_pix_fmt_name(pix_fmt));
  333. }
  334. av_log(avctx, AV_LOG_INFO, " min s=%ldx%ld fps=%g max s=%ldx%ld fps=%g\n",
  335. vcaps->MinOutputSize.cx, vcaps->MinOutputSize.cy,
  336. 1e7 / vcaps->MaxFrameInterval,
  337. vcaps->MaxOutputSize.cx, vcaps->MaxOutputSize.cy,
  338. 1e7 / vcaps->MinFrameInterval);
  339. continue;
  340. }
  341. if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
  342. if (ctx->video_codec_id != av_codec_get_id(tags, bih->biCompression))
  343. goto next;
  344. }
  345. if (ctx->pixel_format != AV_PIX_FMT_NONE &&
  346. ctx->pixel_format != dshow_pixfmt(bih->biCompression, bih->biBitCount)) {
  347. goto next;
  348. }
  349. if (ctx->framerate) {
  350. int64_t framerate = ((int64_t) ctx->requested_framerate.den*10000000)
  351. / ctx->requested_framerate.num;
  352. if (framerate > vcaps->MaxFrameInterval ||
  353. framerate < vcaps->MinFrameInterval)
  354. goto next;
  355. *fr = framerate;
  356. }
  357. if (ctx->requested_width && ctx->requested_height) {
  358. if (ctx->requested_width > vcaps->MaxOutputSize.cx ||
  359. ctx->requested_width < vcaps->MinOutputSize.cx ||
  360. ctx->requested_height > vcaps->MaxOutputSize.cy ||
  361. ctx->requested_height < vcaps->MinOutputSize.cy)
  362. goto next;
  363. bih->biWidth = ctx->requested_width;
  364. bih->biHeight = ctx->requested_height;
  365. }
  366. } else {
  367. AUDIO_STREAM_CONFIG_CAPS *acaps = caps;
  368. WAVEFORMATEX *fx;
  369. #if DSHOWDEBUG
  370. ff_print_AUDIO_STREAM_CONFIG_CAPS(acaps);
  371. #endif
  372. if (IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx)) {
  373. fx = (void *) type->pbFormat;
  374. } else {
  375. goto next;
  376. }
  377. if (!pformat_set) {
  378. av_log(avctx, AV_LOG_INFO, " min ch=%lu bits=%lu rate=%6lu max ch=%lu bits=%lu rate=%6lu\n",
  379. acaps->MinimumChannels, acaps->MinimumBitsPerSample, acaps->MinimumSampleFrequency,
  380. acaps->MaximumChannels, acaps->MaximumBitsPerSample, acaps->MaximumSampleFrequency);
  381. continue;
  382. }
  383. if (ctx->sample_rate) {
  384. if (ctx->sample_rate > acaps->MaximumSampleFrequency ||
  385. ctx->sample_rate < acaps->MinimumSampleFrequency)
  386. goto next;
  387. fx->nSamplesPerSec = ctx->sample_rate;
  388. }
  389. if (ctx->sample_size) {
  390. if (ctx->sample_size > acaps->MaximumBitsPerSample ||
  391. ctx->sample_size < acaps->MinimumBitsPerSample)
  392. goto next;
  393. fx->wBitsPerSample = ctx->sample_size;
  394. }
  395. if (ctx->channels) {
  396. if (ctx->channels > acaps->MaximumChannels ||
  397. ctx->channels < acaps->MinimumChannels)
  398. goto next;
  399. fx->nChannels = ctx->channels;
  400. }
  401. }
  402. if (IAMStreamConfig_SetFormat(config, type) != S_OK)
  403. goto next;
  404. format_set = 1;
  405. next:
  406. if (type->pbFormat)
  407. CoTaskMemFree(type->pbFormat);
  408. CoTaskMemFree(type);
  409. }
  410. end:
  411. IAMStreamConfig_Release(config);
  412. av_free(caps);
  413. if (pformat_set)
  414. *pformat_set = format_set;
  415. }
  416. /**
  417. * Set audio device buffer size in milliseconds (which can directly impact
  418. * latency, depending on the device).
  419. */
  420. static int
  421. dshow_set_audio_buffer_size(AVFormatContext *avctx, IPin *pin)
  422. {
  423. struct dshow_ctx *ctx = avctx->priv_data;
  424. IAMBufferNegotiation *buffer_negotiation = NULL;
  425. ALLOCATOR_PROPERTIES props = { -1, -1, -1, -1 };
  426. IAMStreamConfig *config = NULL;
  427. AM_MEDIA_TYPE *type = NULL;
  428. int ret = AVERROR(EIO);
  429. if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
  430. goto end;
  431. if (IAMStreamConfig_GetFormat(config, &type) != S_OK)
  432. goto end;
  433. if (!IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx))
  434. goto end;
  435. props.cbBuffer = (((WAVEFORMATEX *) type->pbFormat)->nAvgBytesPerSec)
  436. * ctx->audio_buffer_size / 1000;
  437. if (IPin_QueryInterface(pin, &IID_IAMBufferNegotiation, (void **) &buffer_negotiation) != S_OK)
  438. goto end;
  439. if (IAMBufferNegotiation_SuggestAllocatorProperties(buffer_negotiation, &props) != S_OK)
  440. goto end;
  441. ret = 0;
  442. end:
  443. if (buffer_negotiation)
  444. IAMBufferNegotiation_Release(buffer_negotiation);
  445. if (type) {
  446. if (type->pbFormat)
  447. CoTaskMemFree(type->pbFormat);
  448. CoTaskMemFree(type);
  449. }
  450. if (config)
  451. IAMStreamConfig_Release(config);
  452. return ret;
  453. }
  454. /**
  455. * Pops up a user dialog allowing them to adjust properties for the given filter, if possible.
  456. */
  457. void
  458. dshow_show_filter_properties(IBaseFilter *device_filter, AVFormatContext *avctx) {
  459. ISpecifyPropertyPages *property_pages = NULL;
  460. IUnknown *device_filter_iunknown = NULL;
  461. HRESULT hr;
  462. FILTER_INFO filter_info = {0}; /* a warning on this line is false positive GCC bug 53119 AFAICT */
  463. CAUUID ca_guid = {0};
  464. hr = IBaseFilter_QueryInterface(device_filter, &IID_ISpecifyPropertyPages, (void **)&property_pages);
  465. if (hr != S_OK) {
  466. av_log(avctx, AV_LOG_WARNING, "requested filter does not have a property page to show");
  467. goto end;
  468. }
  469. hr = IBaseFilter_QueryFilterInfo(device_filter, &filter_info);
  470. if (hr != S_OK) {
  471. goto fail;
  472. }
  473. hr = IBaseFilter_QueryInterface(device_filter, &IID_IUnknown, (void **)&device_filter_iunknown);
  474. if (hr != S_OK) {
  475. goto fail;
  476. }
  477. hr = ISpecifyPropertyPages_GetPages(property_pages, &ca_guid);
  478. if (hr != S_OK) {
  479. goto fail;
  480. }
  481. hr = OleCreatePropertyFrame(NULL, 0, 0, filter_info.achName, 1, &device_filter_iunknown, ca_guid.cElems,
  482. ca_guid.pElems, 0, 0, NULL);
  483. if (hr != S_OK) {
  484. goto fail;
  485. }
  486. goto end;
  487. fail:
  488. av_log(avctx, AV_LOG_ERROR, "Failure showing property pages for filter");
  489. end:
  490. if (property_pages)
  491. ISpecifyPropertyPages_Release(property_pages);
  492. if (device_filter_iunknown)
  493. IUnknown_Release(device_filter_iunknown);
  494. if (filter_info.pGraph)
  495. IFilterGraph_Release(filter_info.pGraph);
  496. if (ca_guid.pElems)
  497. CoTaskMemFree(ca_guid.pElems);
  498. }
  499. /**
  500. * Cycle through available pins using the device_filter device, of type
  501. * devtype, retrieve the first output pin and return the pointer to the
  502. * object found in *ppin.
  503. * If ppin is NULL, cycle through all pins listing audio/video capabilities.
  504. */
  505. static int
  506. dshow_cycle_pins(AVFormatContext *avctx, enum dshowDeviceType devtype,
  507. enum dshowSourceFilterType sourcetype, IBaseFilter *device_filter, IPin **ppin)
  508. {
  509. struct dshow_ctx *ctx = avctx->priv_data;
  510. IEnumPins *pins = 0;
  511. IPin *device_pin = NULL;
  512. IPin *pin;
  513. int r;
  514. const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
  515. const char *devtypename = (devtype == VideoDevice) ? "video" : "audio only";
  516. const char *sourcetypename = (sourcetype == VideoSourceDevice) ? "video" : "audio";
  517. int set_format = (devtype == VideoDevice && (ctx->framerate ||
  518. (ctx->requested_width && ctx->requested_height) ||
  519. ctx->pixel_format != AV_PIX_FMT_NONE ||
  520. ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO))
  521. || (devtype == AudioDevice && (ctx->channels || ctx->sample_rate));
  522. int format_set = 0;
  523. int should_show_properties = (devtype == VideoDevice) ? ctx->show_video_device_dialog : ctx->show_audio_device_dialog;
  524. if (should_show_properties)
  525. dshow_show_filter_properties(device_filter, avctx);
  526. r = IBaseFilter_EnumPins(device_filter, &pins);
  527. if (r != S_OK) {
  528. av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
  529. return AVERROR(EIO);
  530. }
  531. if (!ppin) {
  532. av_log(avctx, AV_LOG_INFO, "DirectShow %s device options (from %s devices)\n",
  533. devtypename, sourcetypename);
  534. }
  535. while (!device_pin && IEnumPins_Next(pins, 1, &pin, NULL) == S_OK) {
  536. IKsPropertySet *p = NULL;
  537. IEnumMediaTypes *types = NULL;
  538. PIN_INFO info = {0};
  539. AM_MEDIA_TYPE *type;
  540. GUID category;
  541. DWORD r2;
  542. char *name_buf = NULL;
  543. wchar_t *pin_id = NULL;
  544. char *pin_buf = NULL;
  545. char *desired_pin_name = devtype == VideoDevice ? ctx->video_pin_name : ctx->audio_pin_name;
  546. IPin_QueryPinInfo(pin, &info);
  547. IBaseFilter_Release(info.pFilter);
  548. if (info.dir != PINDIR_OUTPUT)
  549. goto next;
  550. if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
  551. goto next;
  552. if (IKsPropertySet_Get(p, &AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
  553. NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
  554. goto next;
  555. if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
  556. goto next;
  557. name_buf = dup_wchar_to_utf8(info.achName);
  558. r = IPin_QueryId(pin, &pin_id);
  559. if (r != S_OK) {
  560. av_log(avctx, AV_LOG_ERROR, "Could not query pin id\n");
  561. return AVERROR(EIO);
  562. }
  563. pin_buf = dup_wchar_to_utf8(pin_id);
  564. if (!ppin) {
  565. av_log(avctx, AV_LOG_INFO, " Pin \"%s\" (alternative pin name \"%s\")\n", name_buf, pin_buf);
  566. dshow_cycle_formats(avctx, devtype, pin, NULL);
  567. goto next;
  568. }
  569. if (desired_pin_name) {
  570. if(strcmp(name_buf, desired_pin_name) && strcmp(pin_buf, desired_pin_name)) {
  571. av_log(avctx, AV_LOG_DEBUG, "skipping pin \"%s\" (\"%s\") != requested \"%s\"\n",
  572. name_buf, pin_buf, desired_pin_name);
  573. goto next;
  574. }
  575. }
  576. if (set_format) {
  577. dshow_cycle_formats(avctx, devtype, pin, &format_set);
  578. if (!format_set) {
  579. goto next;
  580. }
  581. }
  582. if (devtype == AudioDevice && ctx->audio_buffer_size) {
  583. if (dshow_set_audio_buffer_size(avctx, pin) < 0) {
  584. av_log(avctx, AV_LOG_ERROR, "unable to set audio buffer size %d to pin, using pin anyway...", ctx->audio_buffer_size);
  585. }
  586. }
  587. if (IPin_EnumMediaTypes(pin, &types) != S_OK)
  588. goto next;
  589. IEnumMediaTypes_Reset(types);
  590. /* in case format_set was not called, just verify the majortype */
  591. while (!device_pin && IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK) {
  592. if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
  593. device_pin = pin;
  594. av_log(avctx, AV_LOG_DEBUG, "Selecting pin %s on %s\n", name_buf, devtypename);
  595. goto next;
  596. }
  597. CoTaskMemFree(type);
  598. }
  599. next:
  600. if (types)
  601. IEnumMediaTypes_Release(types);
  602. if (p)
  603. IKsPropertySet_Release(p);
  604. if (device_pin != pin)
  605. IPin_Release(pin);
  606. av_free(name_buf);
  607. av_free(pin_buf);
  608. if (pin_id)
  609. CoTaskMemFree(pin_id);
  610. }
  611. IEnumPins_Release(pins);
  612. if (ppin) {
  613. if (set_format && !format_set) {
  614. av_log(avctx, AV_LOG_ERROR, "Could not set %s options\n", devtypename);
  615. return AVERROR(EIO);
  616. }
  617. if (!device_pin) {
  618. av_log(avctx, AV_LOG_ERROR,
  619. "Could not find output pin from %s capture device.\n", devtypename);
  620. return AVERROR(EIO);
  621. }
  622. *ppin = device_pin;
  623. }
  624. return 0;
  625. }
  626. /**
  627. * List options for device with type devtype, source filter type sourcetype
  628. *
  629. * @param devenum device enumerator used for accessing the device
  630. */
  631. static int
  632. dshow_list_device_options(AVFormatContext *avctx, ICreateDevEnum *devenum,
  633. enum dshowDeviceType devtype, enum dshowSourceFilterType sourcetype)
  634. {
  635. struct dshow_ctx *ctx = avctx->priv_data;
  636. IBaseFilter *device_filter = NULL;
  637. char *device_unique_name = NULL;
  638. int r;
  639. if ((r = dshow_cycle_devices(avctx, devenum, devtype, sourcetype, &device_filter, &device_unique_name)) < 0)
  640. return r;
  641. ctx->device_filter[devtype] = device_filter;
  642. if ((r = dshow_cycle_pins(avctx, devtype, sourcetype, device_filter, NULL)) < 0)
  643. return r;
  644. av_freep(&device_unique_name);
  645. return 0;
  646. }
  647. static int
  648. dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
  649. enum dshowDeviceType devtype, enum dshowSourceFilterType sourcetype)
  650. {
  651. struct dshow_ctx *ctx = avctx->priv_data;
  652. IBaseFilter *device_filter = NULL;
  653. char *device_filter_unique_name = NULL;
  654. IGraphBuilder *graph = ctx->graph;
  655. IPin *device_pin = NULL;
  656. libAVPin *capture_pin = NULL;
  657. libAVFilter *capture_filter = NULL;
  658. ICaptureGraphBuilder2 *graph_builder2 = NULL;
  659. int ret = AVERROR(EIO);
  660. int r;
  661. IStream *ifile_stream = NULL;
  662. IStream *ofile_stream = NULL;
  663. IPersistStream *pers_stream = NULL;
  664. enum dshowDeviceType otherDevType = (devtype == VideoDevice) ? AudioDevice : VideoDevice;
  665. const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
  666. if ( ((ctx->audio_filter_load_file) && (strlen(ctx->audio_filter_load_file)>0) && (sourcetype == AudioSourceDevice)) ||
  667. ((ctx->video_filter_load_file) && (strlen(ctx->video_filter_load_file)>0) && (sourcetype == VideoSourceDevice)) ) {
  668. HRESULT hr;
  669. char *filename = NULL;
  670. if (sourcetype == AudioSourceDevice)
  671. filename = ctx->audio_filter_load_file;
  672. else
  673. filename = ctx->video_filter_load_file;
  674. hr = SHCreateStreamOnFile ((LPCSTR) filename, STGM_READ, &ifile_stream);
  675. if (S_OK != hr) {
  676. av_log(avctx, AV_LOG_ERROR, "Could not open capture filter description file.\n");
  677. goto error;
  678. }
  679. hr = OleLoadFromStream(ifile_stream, &IID_IBaseFilter, (void **) &device_filter);
  680. if (hr != S_OK) {
  681. av_log(avctx, AV_LOG_ERROR, "Could not load capture filter from file.\n");
  682. goto error;
  683. }
  684. if (sourcetype == AudioSourceDevice)
  685. av_log(avctx, AV_LOG_INFO, "Audio-");
  686. else
  687. av_log(avctx, AV_LOG_INFO, "Video-");
  688. av_log(avctx, AV_LOG_INFO, "Capture filter loaded successfully from file \"%s\".\n", filename);
  689. } else {
  690. if ((r = dshow_cycle_devices(avctx, devenum, devtype, sourcetype, &device_filter, &device_filter_unique_name)) < 0) {
  691. ret = r;
  692. goto error;
  693. }
  694. }
  695. if (ctx->device_filter[otherDevType]) {
  696. // avoid adding add two instances of the same device to the graph, one for video, one for audio
  697. // a few devices don't support this (could also do this check earlier to avoid double crossbars, etc. but they seem OK)
  698. if (strcmp(device_filter_unique_name, ctx->device_unique_name[otherDevType]) == 0) {
  699. av_log(avctx, AV_LOG_DEBUG, "reusing previous graph capture filter... %s\n", device_filter_unique_name);
  700. IBaseFilter_Release(device_filter);
  701. device_filter = ctx->device_filter[otherDevType];
  702. IBaseFilter_AddRef(ctx->device_filter[otherDevType]);
  703. } else {
  704. av_log(avctx, AV_LOG_DEBUG, "not reusing previous graph capture filter %s != %s\n", device_filter_unique_name, ctx->device_unique_name[otherDevType]);
  705. }
  706. }
  707. ctx->device_filter [devtype] = device_filter;
  708. ctx->device_unique_name [devtype] = device_filter_unique_name;
  709. r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
  710. if (r != S_OK) {
  711. av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
  712. goto error;
  713. }
  714. if ((r = dshow_cycle_pins(avctx, devtype, sourcetype, device_filter, &device_pin)) < 0) {
  715. ret = r;
  716. goto error;
  717. }
  718. ctx->device_pin[devtype] = device_pin;
  719. capture_filter = libAVFilter_Create(avctx, callback, devtype);
  720. if (!capture_filter) {
  721. av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
  722. goto error;
  723. }
  724. ctx->capture_filter[devtype] = capture_filter;
  725. if ( ((ctx->audio_filter_save_file) && (strlen(ctx->audio_filter_save_file)>0) && (sourcetype == AudioSourceDevice)) ||
  726. ((ctx->video_filter_save_file) && (strlen(ctx->video_filter_save_file)>0) && (sourcetype == VideoSourceDevice)) ) {
  727. HRESULT hr;
  728. char *filename = NULL;
  729. if (sourcetype == AudioSourceDevice)
  730. filename = ctx->audio_filter_save_file;
  731. else
  732. filename = ctx->video_filter_save_file;
  733. hr = SHCreateStreamOnFile ((LPCSTR) filename, STGM_CREATE | STGM_READWRITE, &ofile_stream);
  734. if (S_OK != hr) {
  735. av_log(avctx, AV_LOG_ERROR, "Could not create capture filter description file.\n");
  736. goto error;
  737. }
  738. hr = IBaseFilter_QueryInterface(device_filter, &IID_IPersistStream, (void **) &pers_stream);
  739. if (hr != S_OK) {
  740. av_log(avctx, AV_LOG_ERROR, "Query for IPersistStream failed.\n");
  741. goto error;
  742. }
  743. hr = OleSaveToStream(pers_stream, ofile_stream);
  744. if (hr != S_OK) {
  745. av_log(avctx, AV_LOG_ERROR, "Could not save capture filter \n");
  746. goto error;
  747. }
  748. hr = IStream_Commit(ofile_stream, STGC_DEFAULT);
  749. if (S_OK != hr) {
  750. av_log(avctx, AV_LOG_ERROR, "Could not commit capture filter data to file.\n");
  751. goto error;
  752. }
  753. if (sourcetype == AudioSourceDevice)
  754. av_log(avctx, AV_LOG_INFO, "Audio-");
  755. else
  756. av_log(avctx, AV_LOG_INFO, "Video-");
  757. av_log(avctx, AV_LOG_INFO, "Capture filter saved successfully to file \"%s\".\n", filename);
  758. }
  759. r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
  760. filter_name[devtype]);
  761. if (r != S_OK) {
  762. av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
  763. goto error;
  764. }
  765. libAVPin_AddRef(capture_filter->pin);
  766. capture_pin = capture_filter->pin;
  767. ctx->capture_pin[devtype] = capture_pin;
  768. r = CoCreateInstance(&CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER,
  769. &IID_ICaptureGraphBuilder2, (void **) &graph_builder2);
  770. if (r != S_OK) {
  771. av_log(avctx, AV_LOG_ERROR, "Could not create CaptureGraphBuilder2\n");
  772. goto error;
  773. }
  774. ICaptureGraphBuilder2_SetFiltergraph(graph_builder2, graph);
  775. if (r != S_OK) {
  776. av_log(avctx, AV_LOG_ERROR, "Could not set graph for CaptureGraphBuilder2\n");
  777. goto error;
  778. }
  779. r = ICaptureGraphBuilder2_RenderStream(graph_builder2, NULL, NULL, (IUnknown *) device_pin, NULL /* no intermediate filter */,
  780. (IBaseFilter *) capture_filter); /* connect pins, optionally insert intermediate filters like crossbar if necessary */
  781. if (r != S_OK) {
  782. av_log(avctx, AV_LOG_ERROR, "Could not RenderStream to connect pins\n");
  783. goto error;
  784. }
  785. r = dshow_try_setup_crossbar_options(graph_builder2, device_filter, devtype, avctx);
  786. if (r != S_OK) {
  787. av_log(avctx, AV_LOG_ERROR, "Could not setup CrossBar\n");
  788. goto error;
  789. }
  790. ret = 0;
  791. error:
  792. if (graph_builder2 != NULL)
  793. ICaptureGraphBuilder2_Release(graph_builder2);
  794. if (pers_stream)
  795. IPersistStream_Release(pers_stream);
  796. if (ifile_stream)
  797. IStream_Release(ifile_stream);
  798. if (ofile_stream)
  799. IStream_Release(ofile_stream);
  800. return ret;
  801. }
  802. static enum AVCodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
  803. {
  804. switch (sample_fmt) {
  805. case AV_SAMPLE_FMT_U8: return AV_CODEC_ID_PCM_U8;
  806. case AV_SAMPLE_FMT_S16: return AV_CODEC_ID_PCM_S16LE;
  807. case AV_SAMPLE_FMT_S32: return AV_CODEC_ID_PCM_S32LE;
  808. default: return AV_CODEC_ID_NONE; /* Should never happen. */
  809. }
  810. }
  811. static enum AVSampleFormat sample_fmt_bits_per_sample(int bits)
  812. {
  813. switch (bits) {
  814. case 8: return AV_SAMPLE_FMT_U8;
  815. case 16: return AV_SAMPLE_FMT_S16;
  816. case 32: return AV_SAMPLE_FMT_S32;
  817. default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
  818. }
  819. }
  820. static int
  821. dshow_add_device(AVFormatContext *avctx,
  822. enum dshowDeviceType devtype)
  823. {
  824. struct dshow_ctx *ctx = avctx->priv_data;
  825. AM_MEDIA_TYPE type;
  826. AVCodecParameters *par;
  827. AVStream *st;
  828. int ret = AVERROR(EIO);
  829. st = avformat_new_stream(avctx, NULL);
  830. if (!st) {
  831. ret = AVERROR(ENOMEM);
  832. goto error;
  833. }
  834. st->id = devtype;
  835. ctx->capture_filter[devtype]->stream_index = st->index;
  836. libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
  837. par = st->codecpar;
  838. if (devtype == VideoDevice) {
  839. BITMAPINFOHEADER *bih = NULL;
  840. AVRational time_base;
  841. if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
  842. VIDEOINFOHEADER *v = (void *) type.pbFormat;
  843. time_base = (AVRational) { v->AvgTimePerFrame, 10000000 };
  844. bih = &v->bmiHeader;
  845. } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
  846. VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
  847. time_base = (AVRational) { v->AvgTimePerFrame, 10000000 };
  848. bih = &v->bmiHeader;
  849. }
  850. if (!bih) {
  851. av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
  852. goto error;
  853. }
  854. st->avg_frame_rate = av_inv_q(time_base);
  855. st->r_frame_rate = av_inv_q(time_base);
  856. par->codec_type = AVMEDIA_TYPE_VIDEO;
  857. par->width = bih->biWidth;
  858. par->height = bih->biHeight;
  859. par->codec_tag = bih->biCompression;
  860. par->format = dshow_pixfmt(bih->biCompression, bih->biBitCount);
  861. if (bih->biCompression == MKTAG('H', 'D', 'Y', 'C')) {
  862. av_log(avctx, AV_LOG_DEBUG, "attempt to use full range for HDYC...\n");
  863. par->color_range = AVCOL_RANGE_MPEG; // just in case it needs this...
  864. }
  865. if (par->format == AV_PIX_FMT_NONE) {
  866. const AVCodecTag *const tags[] = { avformat_get_riff_video_tags(), NULL };
  867. par->codec_id = av_codec_get_id(tags, bih->biCompression);
  868. if (par->codec_id == AV_CODEC_ID_NONE) {
  869. av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
  870. "Please report type 0x%X.\n", (int) bih->biCompression);
  871. return AVERROR_PATCHWELCOME;
  872. }
  873. par->bits_per_coded_sample = bih->biBitCount;
  874. } else {
  875. par->codec_id = AV_CODEC_ID_RAWVIDEO;
  876. if (bih->biCompression == BI_RGB || bih->biCompression == BI_BITFIELDS) {
  877. par->bits_per_coded_sample = bih->biBitCount;
  878. par->extradata = av_malloc(9 + AV_INPUT_BUFFER_PADDING_SIZE);
  879. if (par->extradata) {
  880. par->extradata_size = 9;
  881. memcpy(par->extradata, "BottomUp", 9);
  882. }
  883. }
  884. }
  885. } else {
  886. WAVEFORMATEX *fx = NULL;
  887. if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
  888. fx = (void *) type.pbFormat;
  889. }
  890. if (!fx) {
  891. av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
  892. goto error;
  893. }
  894. par->codec_type = AVMEDIA_TYPE_AUDIO;
  895. par->format = sample_fmt_bits_per_sample(fx->wBitsPerSample);
  896. par->codec_id = waveform_codec_id(par->format);
  897. par->sample_rate = fx->nSamplesPerSec;
  898. par->channels = fx->nChannels;
  899. }
  900. avpriv_set_pts_info(st, 64, 1, 10000000);
  901. ret = 0;
  902. error:
  903. return ret;
  904. }
  905. static int parse_device_name(AVFormatContext *avctx)
  906. {
  907. struct dshow_ctx *ctx = avctx->priv_data;
  908. char **device_name = ctx->device_name;
  909. char *name = av_strdup(avctx->filename);
  910. char *tmp = name;
  911. int ret = 1;
  912. char *type;
  913. while ((type = strtok(tmp, "="))) {
  914. char *token = strtok(NULL, ":");
  915. tmp = NULL;
  916. if (!strcmp(type, "video")) {
  917. device_name[0] = token;
  918. } else if (!strcmp(type, "audio")) {
  919. device_name[1] = token;
  920. } else {
  921. device_name[0] = NULL;
  922. device_name[1] = NULL;
  923. break;
  924. }
  925. }
  926. if (!device_name[0] && !device_name[1]) {
  927. ret = 0;
  928. } else {
  929. if (device_name[0])
  930. device_name[0] = av_strdup(device_name[0]);
  931. if (device_name[1])
  932. device_name[1] = av_strdup(device_name[1]);
  933. }
  934. av_free(name);
  935. return ret;
  936. }
  937. static int dshow_read_header(AVFormatContext *avctx)
  938. {
  939. struct dshow_ctx *ctx = avctx->priv_data;
  940. IGraphBuilder *graph = NULL;
  941. ICreateDevEnum *devenum = NULL;
  942. IMediaControl *control = NULL;
  943. IMediaEvent *media_event = NULL;
  944. HANDLE media_event_handle;
  945. HANDLE proc;
  946. int ret = AVERROR(EIO);
  947. int r;
  948. CoInitialize(0);
  949. if (!ctx->list_devices && !parse_device_name(avctx)) {
  950. av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
  951. goto error;
  952. }
  953. ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id
  954. : AV_CODEC_ID_RAWVIDEO;
  955. if (ctx->pixel_format != AV_PIX_FMT_NONE) {
  956. if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
  957. av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "
  958. "video codec is not set or set to rawvideo\n");
  959. ret = AVERROR(EINVAL);
  960. goto error;
  961. }
  962. }
  963. if (ctx->framerate) {
  964. r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);
  965. if (r < 0) {
  966. av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
  967. goto error;
  968. }
  969. }
  970. r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
  971. &IID_IGraphBuilder, (void **) &graph);
  972. if (r != S_OK) {
  973. av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
  974. goto error;
  975. }
  976. ctx->graph = graph;
  977. r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
  978. &IID_ICreateDevEnum, (void **) &devenum);
  979. if (r != S_OK) {
  980. av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
  981. goto error;
  982. }
  983. if (ctx->list_devices) {
  984. av_log(avctx, AV_LOG_INFO, "DirectShow video devices (some may be both video and audio devices)\n");
  985. dshow_cycle_devices(avctx, devenum, VideoDevice, VideoSourceDevice, NULL, NULL);
  986. av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");
  987. dshow_cycle_devices(avctx, devenum, AudioDevice, AudioSourceDevice, NULL, NULL);
  988. ret = AVERROR_EXIT;
  989. goto error;
  990. }
  991. if (ctx->list_options) {
  992. if (ctx->device_name[VideoDevice])
  993. if ((r = dshow_list_device_options(avctx, devenum, VideoDevice, VideoSourceDevice))) {
  994. ret = r;
  995. goto error;
  996. }
  997. if (ctx->device_name[AudioDevice]) {
  998. if (dshow_list_device_options(avctx, devenum, AudioDevice, AudioSourceDevice)) {
  999. /* show audio options from combined video+audio sources as fallback */
  1000. if ((r = dshow_list_device_options(avctx, devenum, AudioDevice, VideoSourceDevice))) {
  1001. ret = r;
  1002. goto error;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. if (ctx->device_name[VideoDevice]) {
  1008. if ((r = dshow_open_device(avctx, devenum, VideoDevice, VideoSourceDevice)) < 0 ||
  1009. (r = dshow_add_device(avctx, VideoDevice)) < 0) {
  1010. ret = r;
  1011. goto error;
  1012. }
  1013. }
  1014. if (ctx->device_name[AudioDevice]) {
  1015. if ((r = dshow_open_device(avctx, devenum, AudioDevice, AudioSourceDevice)) < 0 ||
  1016. (r = dshow_add_device(avctx, AudioDevice)) < 0) {
  1017. av_log(avctx, AV_LOG_INFO, "Searching for audio device within video devices for %s\n", ctx->device_name[AudioDevice]);
  1018. /* see if there's a video source with an audio pin with the given audio name */
  1019. if ((r = dshow_open_device(avctx, devenum, AudioDevice, VideoSourceDevice)) < 0 ||
  1020. (r = dshow_add_device(avctx, AudioDevice)) < 0) {
  1021. ret = r;
  1022. goto error;
  1023. }
  1024. }
  1025. }
  1026. if (ctx->list_options) {
  1027. /* allow it to list crossbar options in dshow_open_device */
  1028. ret = AVERROR_EXIT;
  1029. goto error;
  1030. }
  1031. ctx->curbufsize[0] = 0;
  1032. ctx->curbufsize[1] = 0;
  1033. ctx->mutex = CreateMutex(NULL, 0, NULL);
  1034. if (!ctx->mutex) {
  1035. av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
  1036. goto error;
  1037. }
  1038. ctx->event[1] = CreateEvent(NULL, 1, 0, NULL);
  1039. if (!ctx->event[1]) {
  1040. av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
  1041. goto error;
  1042. }
  1043. r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
  1044. if (r != S_OK) {
  1045. av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
  1046. goto error;
  1047. }
  1048. ctx->control = control;
  1049. r = IGraphBuilder_QueryInterface(graph, &IID_IMediaEvent, (void **) &media_event);
  1050. if (r != S_OK) {
  1051. av_log(avctx, AV_LOG_ERROR, "Could not get media event.\n");
  1052. goto error;
  1053. }
  1054. ctx->media_event = media_event;
  1055. r = IMediaEvent_GetEventHandle(media_event, (void *) &media_event_handle);
  1056. if (r != S_OK) {
  1057. av_log(avctx, AV_LOG_ERROR, "Could not get media event handle.\n");
  1058. goto error;
  1059. }
  1060. proc = GetCurrentProcess();
  1061. r = DuplicateHandle(proc, media_event_handle, proc, &ctx->event[0],
  1062. 0, 0, DUPLICATE_SAME_ACCESS);
  1063. if (!r) {
  1064. av_log(avctx, AV_LOG_ERROR, "Could not duplicate media event handle.\n");
  1065. goto error;
  1066. }
  1067. r = IMediaControl_Run(control);
  1068. if (r == S_FALSE) {
  1069. OAFilterState pfs;
  1070. r = IMediaControl_GetState(control, 0, &pfs);
  1071. }
  1072. if (r != S_OK) {
  1073. av_log(avctx, AV_LOG_ERROR, "Could not run graph (sometimes caused by a device already in use by other application)\n");
  1074. goto error;
  1075. }
  1076. ret = 0;
  1077. error:
  1078. if (devenum)
  1079. ICreateDevEnum_Release(devenum);
  1080. if (ret < 0)
  1081. dshow_read_close(avctx);
  1082. return ret;
  1083. }
  1084. /**
  1085. * Checks media events from DirectShow and returns -1 on error or EOF. Also
  1086. * purges all events that might be in the event queue to stop the trigger
  1087. * of event notification.
  1088. */
  1089. static int dshow_check_event_queue(IMediaEvent *media_event)
  1090. {
  1091. LONG_PTR p1, p2;
  1092. long code;
  1093. int ret = 0;
  1094. while (IMediaEvent_GetEvent(media_event, &code, &p1, &p2, 0) != E_ABORT) {
  1095. if (code == EC_COMPLETE || code == EC_DEVICE_LOST || code == EC_ERRORABORT)
  1096. ret = -1;
  1097. IMediaEvent_FreeEventParams(media_event, code, p1, p2);
  1098. }
  1099. return ret;
  1100. }
  1101. static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
  1102. {
  1103. struct dshow_ctx *ctx = s->priv_data;
  1104. AVPacketList *pktl = NULL;
  1105. while (!ctx->eof && !pktl) {
  1106. WaitForSingleObject(ctx->mutex, INFINITE);
  1107. pktl = ctx->pktl;
  1108. if (pktl) {
  1109. *pkt = pktl->pkt;
  1110. ctx->pktl = ctx->pktl->next;
  1111. av_free(pktl);
  1112. ctx->curbufsize[pkt->stream_index] -= pkt->size;
  1113. }
  1114. ResetEvent(ctx->event[1]);
  1115. ReleaseMutex(ctx->mutex);
  1116. if (!pktl) {
  1117. if (dshow_check_event_queue(ctx->media_event) < 0) {
  1118. ctx->eof = 1;
  1119. } else if (s->flags & AVFMT_FLAG_NONBLOCK) {
  1120. return AVERROR(EAGAIN);
  1121. } else {
  1122. WaitForMultipleObjects(2, ctx->event, 0, INFINITE);
  1123. }
  1124. }
  1125. }
  1126. return ctx->eof ? AVERROR(EIO) : pkt->size;
  1127. }
  1128. #define OFFSET(x) offsetof(struct dshow_ctx, x)
  1129. #define DEC AV_OPT_FLAG_DECODING_PARAM
  1130. static const AVOption options[] = {
  1131. { "video_size", "set video size given a string such as 640x480 or hd720.", OFFSET(requested_width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  1132. { "pixel_format", "set video pixel format", OFFSET(pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_NONE}, -1, INT_MAX, DEC },
  1133. { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  1134. { "sample_rate", "set audio sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
  1135. { "sample_size", "set audio sample size", OFFSET(sample_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 16, DEC },
  1136. { "channels", "set number of audio channels, such as 1 or 2", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
  1137. { "audio_buffer_size", "set audio device buffer latency size in milliseconds (default is the device's default)", OFFSET(audio_buffer_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
  1138. { "list_devices", "list available devices", OFFSET(list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, DEC },
  1139. { "list_options", "list available options for specified device", OFFSET(list_options), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, DEC },
  1140. { "video_device_number", "set video device number for devices with same name (starts at 0)", OFFSET(video_device_number), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
  1141. { "audio_device_number", "set audio device number for devices with same name (starts at 0)", OFFSET(audio_device_number), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
  1142. { "video_pin_name", "select video capture pin by name", OFFSET(video_pin_name),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
  1143. { "audio_pin_name", "select audio capture pin by name", OFFSET(audio_pin_name),AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
  1144. { "crossbar_video_input_pin_number", "set video input pin number for crossbar device", OFFSET(crossbar_video_input_pin_number), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, DEC },
  1145. { "crossbar_audio_input_pin_number", "set audio input pin number for crossbar device", OFFSET(crossbar_audio_input_pin_number), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, DEC },
  1146. { "show_video_device_dialog", "display property dialog for video capture device", OFFSET(show_video_device_dialog), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  1147. { "show_audio_device_dialog", "display property dialog for audio capture device", OFFSET(show_audio_device_dialog), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  1148. { "show_video_crossbar_connection_dialog", "display property dialog for crossbar connecting pins filter on video device", OFFSET(show_video_crossbar_connection_dialog), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  1149. { "show_audio_crossbar_connection_dialog", "display property dialog for crossbar connecting pins filter on audio device", OFFSET(show_audio_crossbar_connection_dialog), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  1150. { "show_analog_tv_tuner_dialog", "display property dialog for analog tuner filter", OFFSET(show_analog_tv_tuner_dialog), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  1151. { "show_analog_tv_tuner_audio_dialog", "display property dialog for analog tuner audio filter", OFFSET(show_analog_tv_tuner_audio_dialog), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  1152. { "audio_device_load", "load audio capture filter device (and properties) from file", OFFSET(audio_filter_load_file), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  1153. { "audio_device_save", "save audio capture filter device (and properties) to file", OFFSET(audio_filter_save_file), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  1154. { "video_device_load", "load video capture filter device (and properties) from file", OFFSET(video_filter_load_file), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  1155. { "video_device_save", "save video capture filter device (and properties) to file", OFFSET(video_filter_save_file), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  1156. { NULL },
  1157. };
  1158. static const AVClass dshow_class = {
  1159. .class_name = "dshow indev",
  1160. .item_name = av_default_item_name,
  1161. .option = options,
  1162. .version = LIBAVUTIL_VERSION_INT,
  1163. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  1164. };
  1165. AVInputFormat ff_dshow_demuxer = {
  1166. .name = "dshow",
  1167. .long_name = NULL_IF_CONFIG_SMALL("DirectShow capture"),
  1168. .priv_data_size = sizeof(struct dshow_ctx),
  1169. .read_header = dshow_read_header,
  1170. .read_packet = dshow_read_packet,
  1171. .read_close = dshow_read_close,
  1172. .flags = AVFMT_NOFILE,
  1173. .priv_class = &dshow_class,
  1174. };