dshow.c 49 KB

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