1
0

win-wasapi.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  1. #include "enum-wasapi.hpp"
  2. #include <obs-module.h>
  3. #include <obs.h>
  4. #include <util/dstr.h>
  5. #include <util/platform.h>
  6. #include <util/windows/HRError.hpp>
  7. #include <util/windows/ComPtr.hpp>
  8. #include <util/windows/WinHandle.hpp>
  9. #include <util/windows/CoTaskMemPtr.hpp>
  10. #include <util/windows/win-version.h>
  11. #include <util/windows/window-helpers.h>
  12. #include <util/threading.h>
  13. #include <util/util_uint64.h>
  14. #include <atomic>
  15. #include <cinttypes>
  16. #include <audioclientactivationparams.h>
  17. #include <avrt.h>
  18. #include <RTWorkQ.h>
  19. #include <wrl/implements.h>
  20. using namespace std;
  21. #define OPT_DEVICE_ID "device_id"
  22. #define OPT_USE_DEVICE_TIMING "use_device_timing"
  23. #define OPT_WINDOW "window"
  24. #define OPT_PRIORITY "priority"
  25. static void GetWASAPIDefaults(obs_data_t *settings);
  26. #define OBS_KSAUDIO_SPEAKER_4POINT1 \
  27. (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY)
  28. typedef HRESULT(STDAPICALLTYPE *PFN_ActivateAudioInterfaceAsync)(
  29. LPCWSTR, REFIID, PROPVARIANT *,
  30. IActivateAudioInterfaceCompletionHandler *,
  31. IActivateAudioInterfaceAsyncOperation **);
  32. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqUnlockWorkQueue)(DWORD);
  33. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqLockSharedWorkQueue)(PCWSTR usageClass,
  34. LONG basePriority,
  35. DWORD *taskId,
  36. DWORD *id);
  37. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqCreateAsyncResult)(IUnknown *,
  38. IRtwqAsyncCallback *,
  39. IUnknown *,
  40. IRtwqAsyncResult **);
  41. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWorkItem)(DWORD, LONG,
  42. IRtwqAsyncResult *);
  43. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWaitingWorkItem)(HANDLE, LONG,
  44. IRtwqAsyncResult *,
  45. RTWQWORKITEM_KEY *);
  46. class WASAPIActivateAudioInterfaceCompletionHandler
  47. : public Microsoft::WRL::RuntimeClass<
  48. Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
  49. Microsoft::WRL::FtmBase,
  50. IActivateAudioInterfaceCompletionHandler> {
  51. IUnknown *unknown;
  52. HRESULT activationResult;
  53. WinHandle activationSignal;
  54. public:
  55. WASAPIActivateAudioInterfaceCompletionHandler();
  56. HRESULT GetActivateResult(IAudioClient **client);
  57. private:
  58. virtual HRESULT STDMETHODCALLTYPE ActivateCompleted(
  59. IActivateAudioInterfaceAsyncOperation *activateOperation)
  60. override final;
  61. };
  62. WASAPIActivateAudioInterfaceCompletionHandler::
  63. WASAPIActivateAudioInterfaceCompletionHandler()
  64. {
  65. activationSignal = CreateEvent(nullptr, false, false, nullptr);
  66. if (!activationSignal.Valid())
  67. throw "Could not create receive signal";
  68. }
  69. HRESULT
  70. WASAPIActivateAudioInterfaceCompletionHandler::GetActivateResult(
  71. IAudioClient **client)
  72. {
  73. WaitForSingleObject(activationSignal, INFINITE);
  74. *client = static_cast<IAudioClient *>(unknown);
  75. return activationResult;
  76. }
  77. HRESULT
  78. WASAPIActivateAudioInterfaceCompletionHandler::ActivateCompleted(
  79. IActivateAudioInterfaceAsyncOperation *activateOperation)
  80. {
  81. HRESULT hr, hr_activate;
  82. hr = activateOperation->GetActivateResult(&hr_activate, &unknown);
  83. hr = SUCCEEDED(hr) ? hr_activate : hr;
  84. activationResult = hr;
  85. SetEvent(activationSignal);
  86. return hr;
  87. }
  88. enum class SourceType {
  89. Input,
  90. DeviceOutput,
  91. ProcessOutput,
  92. };
  93. class ARtwqAsyncCallback : public IRtwqAsyncCallback {
  94. protected:
  95. ARtwqAsyncCallback(void *source) : source(source) {}
  96. public:
  97. STDMETHOD_(ULONG, AddRef)() { return ++refCount; }
  98. STDMETHOD_(ULONG, Release)() { return --refCount; }
  99. STDMETHOD(QueryInterface)(REFIID riid, void **ppvObject)
  100. {
  101. HRESULT hr = E_NOINTERFACE;
  102. if (riid == __uuidof(IRtwqAsyncCallback) ||
  103. riid == __uuidof(IUnknown)) {
  104. *ppvObject = this;
  105. AddRef();
  106. hr = S_OK;
  107. } else {
  108. *ppvObject = NULL;
  109. }
  110. return hr;
  111. }
  112. STDMETHOD(GetParameters)
  113. (DWORD *pdwFlags, DWORD *pdwQueue)
  114. {
  115. *pdwFlags = 0;
  116. *pdwQueue = queue_id;
  117. return S_OK;
  118. }
  119. STDMETHOD(Invoke)
  120. (IRtwqAsyncResult *) override = 0;
  121. DWORD GetQueueId() const { return queue_id; }
  122. void SetQueueId(DWORD id) { queue_id = id; }
  123. protected:
  124. std::atomic<ULONG> refCount = 1;
  125. void *source;
  126. DWORD queue_id = 0;
  127. };
  128. class WASAPISource {
  129. ComPtr<IMMNotificationClient> notify;
  130. ComPtr<IMMDeviceEnumerator> enumerator;
  131. ComPtr<IAudioClient> client;
  132. ComPtr<IAudioCaptureClient> capture;
  133. obs_source_t *source;
  134. wstring default_id;
  135. string device_id;
  136. string device_name;
  137. WinModule mmdevapi_module;
  138. PFN_ActivateAudioInterfaceAsync activate_audio_interface_async = NULL;
  139. PFN_RtwqUnlockWorkQueue rtwq_unlock_work_queue = NULL;
  140. PFN_RtwqLockSharedWorkQueue rtwq_lock_shared_work_queue = NULL;
  141. PFN_RtwqCreateAsyncResult rtwq_create_async_result = NULL;
  142. PFN_RtwqPutWorkItem rtwq_put_work_item = NULL;
  143. PFN_RtwqPutWaitingWorkItem rtwq_put_waiting_work_item = NULL;
  144. bool rtwq_supported = false;
  145. window_priority priority;
  146. string window_class;
  147. string title;
  148. string executable;
  149. HWND hwnd = NULL;
  150. DWORD process_id = 0;
  151. const SourceType sourceType;
  152. std::atomic<bool> useDeviceTiming = false;
  153. std::atomic<bool> isDefaultDevice = false;
  154. bool previouslyFailed = false;
  155. WinHandle reconnectThread = NULL;
  156. class CallbackStartCapture : public ARtwqAsyncCallback {
  157. public:
  158. CallbackStartCapture(WASAPISource *source)
  159. : ARtwqAsyncCallback(source)
  160. {
  161. }
  162. STDMETHOD(Invoke)
  163. (IRtwqAsyncResult *) override
  164. {
  165. ((WASAPISource *)source)->OnStartCapture();
  166. return S_OK;
  167. }
  168. } startCapture;
  169. ComPtr<IRtwqAsyncResult> startCaptureAsyncResult;
  170. class CallbackSampleReady : public ARtwqAsyncCallback {
  171. public:
  172. CallbackSampleReady(WASAPISource *source)
  173. : ARtwqAsyncCallback(source)
  174. {
  175. }
  176. STDMETHOD(Invoke)
  177. (IRtwqAsyncResult *) override
  178. {
  179. ((WASAPISource *)source)->OnSampleReady();
  180. return S_OK;
  181. }
  182. } sampleReady;
  183. ComPtr<IRtwqAsyncResult> sampleReadyAsyncResult;
  184. class CallbackRestart : public ARtwqAsyncCallback {
  185. public:
  186. CallbackRestart(WASAPISource *source)
  187. : ARtwqAsyncCallback(source)
  188. {
  189. }
  190. STDMETHOD(Invoke)
  191. (IRtwqAsyncResult *) override
  192. {
  193. ((WASAPISource *)source)->OnRestart();
  194. return S_OK;
  195. }
  196. } restart;
  197. ComPtr<IRtwqAsyncResult> restartAsyncResult;
  198. WinHandle captureThread;
  199. WinHandle idleSignal;
  200. WinHandle stopSignal;
  201. WinHandle receiveSignal;
  202. WinHandle restartSignal;
  203. WinHandle reconnectExitSignal;
  204. WinHandle exitSignal;
  205. WinHandle initSignal;
  206. DWORD reconnectDuration = 0;
  207. WinHandle reconnectSignal;
  208. speaker_layout speakers;
  209. audio_format format;
  210. uint32_t sampleRate;
  211. uint64_t framesProcessed = 0;
  212. static DWORD WINAPI ReconnectThread(LPVOID param);
  213. static DWORD WINAPI CaptureThread(LPVOID param);
  214. bool ProcessCaptureData();
  215. void Start();
  216. void Stop();
  217. static ComPtr<IMMDevice> InitDevice(IMMDeviceEnumerator *enumerator,
  218. bool isDefaultDevice,
  219. SourceType type,
  220. const string device_id);
  221. static ComPtr<IAudioClient> InitClient(
  222. IMMDevice *device, SourceType type, DWORD process_id,
  223. PFN_ActivateAudioInterfaceAsync activate_audio_interface_async,
  224. speaker_layout &speakers, audio_format &format,
  225. uint32_t &sampleRate);
  226. static void InitFormat(const WAVEFORMATEX *wfex,
  227. enum speaker_layout &speakers,
  228. enum audio_format &format, uint32_t &sampleRate);
  229. static void ClearBuffer(IMMDevice *device);
  230. static ComPtr<IAudioCaptureClient> InitCapture(IAudioClient *client,
  231. HANDLE receiveSignal);
  232. void Initialize();
  233. bool TryInitialize();
  234. struct UpdateParams {
  235. string device_id;
  236. bool useDeviceTiming;
  237. bool isDefaultDevice;
  238. window_priority priority;
  239. string window_class;
  240. string title;
  241. string executable;
  242. };
  243. UpdateParams BuildUpdateParams(obs_data_t *settings);
  244. void UpdateSettings(UpdateParams &&params);
  245. void LogSettings();
  246. public:
  247. WASAPISource(obs_data_t *settings, obs_source_t *source_,
  248. SourceType type);
  249. ~WASAPISource();
  250. void Update(obs_data_t *settings);
  251. void OnWindowChanged(obs_data_t *settings);
  252. void Activate();
  253. void Deactivate();
  254. void SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id);
  255. void OnStartCapture();
  256. void OnSampleReady();
  257. void OnRestart();
  258. };
  259. class WASAPINotify : public IMMNotificationClient {
  260. long refs = 0; /* auto-incremented to 1 by ComPtr */
  261. WASAPISource *source;
  262. public:
  263. WASAPINotify(WASAPISource *source_) : source(source_) {}
  264. STDMETHODIMP_(ULONG) AddRef()
  265. {
  266. return (ULONG)os_atomic_inc_long(&refs);
  267. }
  268. STDMETHODIMP_(ULONG) STDMETHODCALLTYPE Release()
  269. {
  270. long val = os_atomic_dec_long(&refs);
  271. if (val == 0)
  272. delete this;
  273. return (ULONG)val;
  274. }
  275. STDMETHODIMP QueryInterface(REFIID riid, void **ptr)
  276. {
  277. if (riid == IID_IUnknown) {
  278. *ptr = (IUnknown *)this;
  279. } else if (riid == __uuidof(IMMNotificationClient)) {
  280. *ptr = (IMMNotificationClient *)this;
  281. } else {
  282. *ptr = nullptr;
  283. return E_NOINTERFACE;
  284. }
  285. os_atomic_inc_long(&refs);
  286. return S_OK;
  287. }
  288. STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role,
  289. LPCWSTR id)
  290. {
  291. source->SetDefaultDevice(flow, role, id);
  292. return S_OK;
  293. }
  294. STDMETHODIMP OnDeviceAdded(LPCWSTR) { return S_OK; }
  295. STDMETHODIMP OnDeviceRemoved(LPCWSTR) { return S_OK; }
  296. STDMETHODIMP OnDeviceStateChanged(LPCWSTR, DWORD) { return S_OK; }
  297. STDMETHODIMP OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY)
  298. {
  299. return S_OK;
  300. }
  301. };
  302. WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
  303. SourceType type)
  304. : source(source_),
  305. sourceType(type),
  306. startCapture(this),
  307. sampleReady(this),
  308. restart(this)
  309. {
  310. mmdevapi_module = LoadLibrary(L"Mmdevapi");
  311. if (mmdevapi_module) {
  312. activate_audio_interface_async =
  313. (PFN_ActivateAudioInterfaceAsync)GetProcAddress(
  314. mmdevapi_module, "ActivateAudioInterfaceAsync");
  315. }
  316. UpdateSettings(BuildUpdateParams(settings));
  317. LogSettings();
  318. idleSignal = CreateEvent(nullptr, true, false, nullptr);
  319. if (!idleSignal.Valid())
  320. throw "Could not create idle signal";
  321. stopSignal = CreateEvent(nullptr, true, false, nullptr);
  322. if (!stopSignal.Valid())
  323. throw "Could not create stop signal";
  324. receiveSignal = CreateEvent(nullptr, false, false, nullptr);
  325. if (!receiveSignal.Valid())
  326. throw "Could not create receive signal";
  327. restartSignal = CreateEvent(nullptr, true, false, nullptr);
  328. if (!restartSignal.Valid())
  329. throw "Could not create restart signal";
  330. reconnectExitSignal = CreateEvent(nullptr, true, false, nullptr);
  331. if (!reconnectExitSignal.Valid())
  332. throw "Could not create reconnect exit signal";
  333. exitSignal = CreateEvent(nullptr, true, false, nullptr);
  334. if (!exitSignal.Valid())
  335. throw "Could not create exit signal";
  336. initSignal = CreateEvent(nullptr, false, false, nullptr);
  337. if (!initSignal.Valid())
  338. throw "Could not create init signal";
  339. reconnectSignal = CreateEvent(nullptr, false, false, nullptr);
  340. if (!reconnectSignal.Valid())
  341. throw "Could not create reconnect signal";
  342. notify = new WASAPINotify(this);
  343. if (!notify)
  344. throw "Could not create WASAPINotify";
  345. HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
  346. CLSCTX_ALL,
  347. IID_PPV_ARGS(enumerator.Assign()));
  348. if (FAILED(hr))
  349. throw HRError("Failed to create enumerator", hr);
  350. hr = enumerator->RegisterEndpointNotificationCallback(notify);
  351. if (FAILED(hr))
  352. throw HRError("Failed to register endpoint callback", hr);
  353. /* OBS will already load DLL on startup if it exists */
  354. const HMODULE rtwq_module = GetModuleHandle(L"RTWorkQ.dll");
  355. // while RTWQ was introduced in Win 8.1, it silently fails
  356. // to capture Desktop Audio for some reason. Disable for now.
  357. struct win_version_info win1703 = {};
  358. win1703.major = 10;
  359. win1703.minor = 0;
  360. win1703.build = 15063;
  361. win1703.revis = 0;
  362. struct win_version_info ver;
  363. get_win_ver(&ver);
  364. if (win_version_compare(&ver, &win1703) >= 0)
  365. rtwq_supported = rtwq_module != NULL;
  366. if (rtwq_supported) {
  367. rtwq_unlock_work_queue =
  368. (PFN_RtwqUnlockWorkQueue)GetProcAddress(
  369. rtwq_module, "RtwqUnlockWorkQueue");
  370. rtwq_lock_shared_work_queue =
  371. (PFN_RtwqLockSharedWorkQueue)GetProcAddress(
  372. rtwq_module, "RtwqLockSharedWorkQueue");
  373. rtwq_create_async_result =
  374. (PFN_RtwqCreateAsyncResult)GetProcAddress(
  375. rtwq_module, "RtwqCreateAsyncResult");
  376. rtwq_put_work_item = (PFN_RtwqPutWorkItem)GetProcAddress(
  377. rtwq_module, "RtwqPutWorkItem");
  378. rtwq_put_waiting_work_item =
  379. (PFN_RtwqPutWaitingWorkItem)GetProcAddress(
  380. rtwq_module, "RtwqPutWaitingWorkItem");
  381. try {
  382. hr = rtwq_create_async_result(nullptr, &startCapture,
  383. nullptr,
  384. &startCaptureAsyncResult);
  385. if (FAILED(hr)) {
  386. throw HRError(
  387. "Could not create startCaptureAsyncResult",
  388. hr);
  389. }
  390. hr = rtwq_create_async_result(nullptr, &sampleReady,
  391. nullptr,
  392. &sampleReadyAsyncResult);
  393. if (FAILED(hr)) {
  394. throw HRError(
  395. "Could not create sampleReadyAsyncResult",
  396. hr);
  397. }
  398. hr = rtwq_create_async_result(nullptr, &restart,
  399. nullptr,
  400. &restartAsyncResult);
  401. if (FAILED(hr)) {
  402. throw HRError(
  403. "Could not create restartAsyncResult",
  404. hr);
  405. }
  406. DWORD taskId = 0;
  407. DWORD id = 0;
  408. hr = rtwq_lock_shared_work_queue(L"Capture", 0, &taskId,
  409. &id);
  410. if (FAILED(hr)) {
  411. throw HRError("RtwqLockSharedWorkQueue failed",
  412. hr);
  413. }
  414. startCapture.SetQueueId(id);
  415. sampleReady.SetQueueId(id);
  416. restart.SetQueueId(id);
  417. } catch (HRError &err) {
  418. blog(LOG_ERROR, "RTWQ setup failed: %s (0x%08X)",
  419. err.str, err.hr);
  420. rtwq_supported = false;
  421. }
  422. }
  423. if (!rtwq_supported) {
  424. captureThread = CreateThread(nullptr, 0,
  425. WASAPISource::CaptureThread, this,
  426. 0, nullptr);
  427. if (!captureThread.Valid()) {
  428. enumerator->UnregisterEndpointNotificationCallback(
  429. notify);
  430. throw "Failed to create capture thread";
  431. }
  432. }
  433. Start();
  434. }
  435. void WASAPISource::Start()
  436. {
  437. if (rtwq_supported) {
  438. rtwq_put_work_item(startCapture.GetQueueId(), 0,
  439. startCaptureAsyncResult);
  440. } else {
  441. SetEvent(initSignal);
  442. }
  443. }
  444. void WASAPISource::Stop()
  445. {
  446. SetEvent(stopSignal);
  447. blog(LOG_INFO, "WASAPI: Device '%s' Terminated", device_name.c_str());
  448. if (rtwq_supported)
  449. SetEvent(receiveSignal);
  450. if (reconnectThread.Valid()) {
  451. WaitForSingleObject(idleSignal, INFINITE);
  452. } else {
  453. const HANDLE sigs[] = {reconnectSignal, idleSignal};
  454. WaitForMultipleObjects(_countof(sigs), sigs, false, INFINITE);
  455. }
  456. SetEvent(exitSignal);
  457. if (reconnectThread.Valid()) {
  458. SetEvent(reconnectExitSignal);
  459. WaitForSingleObject(reconnectThread, INFINITE);
  460. }
  461. if (rtwq_supported)
  462. rtwq_unlock_work_queue(sampleReady.GetQueueId());
  463. else
  464. WaitForSingleObject(captureThread, INFINITE);
  465. }
  466. WASAPISource::~WASAPISource()
  467. {
  468. enumerator->UnregisterEndpointNotificationCallback(notify);
  469. Stop();
  470. }
  471. WASAPISource::UpdateParams WASAPISource::BuildUpdateParams(obs_data_t *settings)
  472. {
  473. WASAPISource::UpdateParams params;
  474. params.device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
  475. params.useDeviceTiming =
  476. obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
  477. params.isDefaultDevice =
  478. _strcmpi(params.device_id.c_str(), "default") == 0;
  479. params.priority =
  480. (window_priority)obs_data_get_int(settings, "priority");
  481. params.window_class.clear();
  482. params.title.clear();
  483. params.executable.clear();
  484. if (sourceType != SourceType::Input) {
  485. const char *const window =
  486. obs_data_get_string(settings, OPT_WINDOW);
  487. char *window_class = nullptr;
  488. char *title = nullptr;
  489. char *executable = nullptr;
  490. ms_build_window_strings(window, &window_class, &title,
  491. &executable);
  492. if (window_class) {
  493. params.window_class = window_class;
  494. bfree(window_class);
  495. }
  496. if (title) {
  497. params.title = title;
  498. bfree(title);
  499. }
  500. if (executable) {
  501. params.executable = executable;
  502. bfree(executable);
  503. }
  504. }
  505. return params;
  506. }
  507. void WASAPISource::UpdateSettings(UpdateParams &&params)
  508. {
  509. device_id = std::move(params.device_id);
  510. useDeviceTiming = params.useDeviceTiming;
  511. isDefaultDevice = params.isDefaultDevice;
  512. priority = params.priority;
  513. window_class = std::move(params.window_class);
  514. title = std::move(params.title);
  515. executable = std::move(params.executable);
  516. }
  517. void WASAPISource::LogSettings()
  518. {
  519. if (sourceType == SourceType::ProcessOutput) {
  520. blog(LOG_INFO,
  521. "[win-wasapi: '%s'] update settings:\n"
  522. "\texecutable: %s\n"
  523. "\ttitle: %s\n"
  524. "\tclass: %s\n"
  525. "\tpriority: %d",
  526. obs_source_get_name(source), executable.c_str(),
  527. title.c_str(), window_class.c_str(), (int)priority);
  528. } else {
  529. blog(LOG_INFO,
  530. "[win-wasapi: '%s'] update settings:\n"
  531. "\tdevice id: %s\n"
  532. "\tuse device timing: %d",
  533. obs_source_get_name(source), device_id.c_str(),
  534. (int)useDeviceTiming);
  535. }
  536. }
  537. void WASAPISource::Update(obs_data_t *settings)
  538. {
  539. UpdateParams params = BuildUpdateParams(settings);
  540. const bool restart =
  541. (sourceType == SourceType::ProcessOutput)
  542. ? ((priority != params.priority) ||
  543. (window_class != params.window_class) ||
  544. (title != params.title) ||
  545. (executable != params.executable))
  546. : (device_id.compare(params.device_id) != 0);
  547. UpdateSettings(std::move(params));
  548. LogSettings();
  549. if (restart)
  550. SetEvent(restartSignal);
  551. }
  552. void WASAPISource::OnWindowChanged(obs_data_t *settings)
  553. {
  554. UpdateParams params = BuildUpdateParams(settings);
  555. const bool restart =
  556. (sourceType == SourceType::ProcessOutput)
  557. ? ((priority != params.priority) ||
  558. (window_class != params.window_class) ||
  559. (title != params.title) ||
  560. (executable != params.executable))
  561. : (device_id.compare(params.device_id) != 0);
  562. UpdateSettings(std::move(params));
  563. if (restart)
  564. SetEvent(restartSignal);
  565. }
  566. void WASAPISource::Activate()
  567. {
  568. if (!reconnectThread.Valid()) {
  569. ResetEvent(reconnectExitSignal);
  570. reconnectThread = CreateThread(nullptr, 0,
  571. WASAPISource::ReconnectThread,
  572. this, 0, nullptr);
  573. }
  574. }
  575. void WASAPISource::Deactivate()
  576. {
  577. if (reconnectThread.Valid()) {
  578. SetEvent(reconnectExitSignal);
  579. WaitForSingleObject(reconnectThread, INFINITE);
  580. reconnectThread = NULL;
  581. }
  582. }
  583. ComPtr<IMMDevice> WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator,
  584. bool isDefaultDevice,
  585. SourceType type,
  586. const string device_id)
  587. {
  588. ComPtr<IMMDevice> device;
  589. if (isDefaultDevice) {
  590. const bool input = type == SourceType::Input;
  591. HRESULT res = enumerator->GetDefaultAudioEndpoint(
  592. input ? eCapture : eRender,
  593. input ? eCommunications : eConsole, device.Assign());
  594. if (FAILED(res))
  595. throw HRError("Failed GetDefaultAudioEndpoint", res);
  596. } else {
  597. wchar_t *w_id;
  598. os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
  599. if (!w_id)
  600. throw "Failed to widen device id string";
  601. const HRESULT res =
  602. enumerator->GetDevice(w_id, device.Assign());
  603. bfree(w_id);
  604. if (FAILED(res))
  605. throw HRError("Failed to enumerate device", res);
  606. }
  607. return device;
  608. }
  609. #define BUFFER_TIME_100NS (5 * 10000000)
  610. static DWORD GetSpeakerChannelMask(speaker_layout layout)
  611. {
  612. switch (layout) {
  613. case SPEAKERS_STEREO:
  614. return KSAUDIO_SPEAKER_STEREO;
  615. case SPEAKERS_2POINT1:
  616. return KSAUDIO_SPEAKER_2POINT1;
  617. case SPEAKERS_4POINT0:
  618. return KSAUDIO_SPEAKER_SURROUND;
  619. case SPEAKERS_4POINT1:
  620. return OBS_KSAUDIO_SPEAKER_4POINT1;
  621. case SPEAKERS_5POINT1:
  622. return KSAUDIO_SPEAKER_5POINT1_SURROUND;
  623. case SPEAKERS_7POINT1:
  624. return KSAUDIO_SPEAKER_7POINT1_SURROUND;
  625. }
  626. return (DWORD)layout;
  627. }
  628. ComPtr<IAudioClient> WASAPISource::InitClient(
  629. IMMDevice *device, SourceType type, DWORD process_id,
  630. PFN_ActivateAudioInterfaceAsync activate_audio_interface_async,
  631. speaker_layout &speakers, audio_format &format,
  632. uint32_t &samples_per_sec)
  633. {
  634. WAVEFORMATEXTENSIBLE wfextensible;
  635. CoTaskMemPtr<WAVEFORMATEX> wfex;
  636. const WAVEFORMATEX *pFormat;
  637. HRESULT res;
  638. ComPtr<IAudioClient> client;
  639. if (type == SourceType::ProcessOutput) {
  640. if (activate_audio_interface_async == NULL)
  641. throw "ActivateAudioInterfaceAsync is not available";
  642. struct obs_audio_info oai;
  643. obs_get_audio_info(&oai);
  644. const WORD nChannels = (WORD)get_audio_channels(oai.speakers);
  645. const DWORD nSamplesPerSec = oai.samples_per_sec;
  646. constexpr WORD wBitsPerSample = 32;
  647. const WORD nBlockAlign = nChannels * wBitsPerSample / 8;
  648. WAVEFORMATEX &wf = wfextensible.Format;
  649. wf.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  650. wf.nChannels = nChannels;
  651. wf.nSamplesPerSec = nSamplesPerSec;
  652. wf.nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
  653. wf.nBlockAlign = nBlockAlign;
  654. wf.wBitsPerSample = wBitsPerSample;
  655. wf.cbSize = sizeof(wfextensible) - sizeof(format);
  656. wfextensible.Samples.wValidBitsPerSample = wBitsPerSample;
  657. wfextensible.dwChannelMask =
  658. GetSpeakerChannelMask(oai.speakers);
  659. wfextensible.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  660. AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams;
  661. audioclientActivationParams.ActivationType =
  662. AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK;
  663. audioclientActivationParams.ProcessLoopbackParams
  664. .TargetProcessId = process_id;
  665. audioclientActivationParams.ProcessLoopbackParams
  666. .ProcessLoopbackMode =
  667. PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE;
  668. PROPVARIANT activateParams{};
  669. activateParams.vt = VT_BLOB;
  670. activateParams.blob.cbSize =
  671. sizeof(audioclientActivationParams);
  672. activateParams.blob.pBlobData =
  673. reinterpret_cast<BYTE *>(&audioclientActivationParams);
  674. {
  675. Microsoft::WRL::ComPtr<
  676. WASAPIActivateAudioInterfaceCompletionHandler>
  677. handler = Microsoft::WRL::Make<
  678. WASAPIActivateAudioInterfaceCompletionHandler>();
  679. ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
  680. res = activate_audio_interface_async(
  681. VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
  682. __uuidof(IAudioClient), &activateParams,
  683. handler.Get(), &asyncOp);
  684. if (FAILED(res))
  685. throw HRError(
  686. "Failed to get activate audio client",
  687. res);
  688. res = handler->GetActivateResult(client.Assign());
  689. if (FAILED(res))
  690. throw HRError("Async activation failed", res);
  691. }
  692. pFormat = &wf;
  693. } else {
  694. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
  695. nullptr, (void **)client.Assign());
  696. if (FAILED(res))
  697. throw HRError("Failed to activate client context", res);
  698. res = client->GetMixFormat(&wfex);
  699. if (FAILED(res))
  700. throw HRError("Failed to get mix format", res);
  701. pFormat = wfex.Get();
  702. }
  703. InitFormat(pFormat, speakers, format, samples_per_sec);
  704. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  705. if (type != SourceType::Input)
  706. flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
  707. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags,
  708. BUFFER_TIME_100NS, 0, pFormat, nullptr);
  709. if (FAILED(res))
  710. throw HRError("Failed to initialize audio client", res);
  711. return client;
  712. }
  713. void WASAPISource::ClearBuffer(IMMDevice *device)
  714. {
  715. CoTaskMemPtr<WAVEFORMATEX> wfex;
  716. HRESULT res;
  717. LPBYTE buffer;
  718. UINT32 frames;
  719. ComPtr<IAudioClient> client;
  720. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
  721. (void **)client.Assign());
  722. if (FAILED(res))
  723. throw HRError("Failed to activate client context", res);
  724. res = client->GetMixFormat(&wfex);
  725. if (FAILED(res))
  726. throw HRError("Failed to get mix format", res);
  727. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS,
  728. 0, wfex, nullptr);
  729. if (FAILED(res))
  730. throw HRError("Failed to initialize audio client", res);
  731. /* Silent loopback fix. Prevents audio stream from stopping and */
  732. /* messing up timestamps and other weird glitches during silence */
  733. /* by playing a silent sample all over again. */
  734. res = client->GetBufferSize(&frames);
  735. if (FAILED(res))
  736. throw HRError("Failed to get buffer size", res);
  737. ComPtr<IAudioRenderClient> render;
  738. res = client->GetService(IID_PPV_ARGS(render.Assign()));
  739. if (FAILED(res))
  740. throw HRError("Failed to get render client", res);
  741. res = render->GetBuffer(frames, &buffer);
  742. if (FAILED(res))
  743. throw HRError("Failed to get buffer", res);
  744. memset(buffer, 0, (size_t)frames * (size_t)wfex->nBlockAlign);
  745. render->ReleaseBuffer(frames, 0);
  746. }
  747. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  748. {
  749. switch (layout) {
  750. case KSAUDIO_SPEAKER_2POINT1:
  751. return SPEAKERS_2POINT1;
  752. case KSAUDIO_SPEAKER_SURROUND:
  753. return SPEAKERS_4POINT0;
  754. case OBS_KSAUDIO_SPEAKER_4POINT1:
  755. return SPEAKERS_4POINT1;
  756. case KSAUDIO_SPEAKER_5POINT1_SURROUND:
  757. return SPEAKERS_5POINT1;
  758. case KSAUDIO_SPEAKER_7POINT1_SURROUND:
  759. return SPEAKERS_7POINT1;
  760. }
  761. return (speaker_layout)channels;
  762. }
  763. void WASAPISource::InitFormat(const WAVEFORMATEX *wfex,
  764. enum speaker_layout &speakers,
  765. enum audio_format &format, uint32_t &sampleRate)
  766. {
  767. DWORD layout = 0;
  768. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  769. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex;
  770. layout = ext->dwChannelMask;
  771. }
  772. /* WASAPI is always float */
  773. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  774. format = AUDIO_FORMAT_FLOAT;
  775. sampleRate = wfex->nSamplesPerSec;
  776. }
  777. ComPtr<IAudioCaptureClient> WASAPISource::InitCapture(IAudioClient *client,
  778. HANDLE receiveSignal)
  779. {
  780. ComPtr<IAudioCaptureClient> capture;
  781. HRESULT res = client->GetService(IID_PPV_ARGS(capture.Assign()));
  782. if (FAILED(res))
  783. throw HRError("Failed to create capture context", res);
  784. res = client->SetEventHandle(receiveSignal);
  785. if (FAILED(res))
  786. throw HRError("Failed to set event handle", res);
  787. res = client->Start();
  788. if (FAILED(res))
  789. throw HRError("Failed to start capture client", res);
  790. return capture;
  791. }
  792. void WASAPISource::Initialize()
  793. {
  794. ComPtr<IMMDevice> device;
  795. if (sourceType == SourceType::ProcessOutput) {
  796. device_name = "[VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK]";
  797. hwnd = ms_find_window(INCLUDE_MINIMIZED, priority,
  798. window_class.c_str(), title.c_str(),
  799. executable.c_str());
  800. if (!hwnd)
  801. throw "Failed to find window";
  802. DWORD dwProcessId = 0;
  803. if (!GetWindowThreadProcessId(hwnd, &dwProcessId)) {
  804. hwnd = NULL;
  805. throw "Failed to get process id of window";
  806. }
  807. process_id = dwProcessId;
  808. } else {
  809. device = InitDevice(enumerator, isDefaultDevice, sourceType,
  810. device_id);
  811. device_name = GetDeviceName(device);
  812. }
  813. ResetEvent(receiveSignal);
  814. ComPtr<IAudioClient> temp_client = InitClient(
  815. device, sourceType, process_id, activate_audio_interface_async,
  816. speakers, format, sampleRate);
  817. if (sourceType == SourceType::DeviceOutput)
  818. ClearBuffer(device);
  819. ComPtr<IAudioCaptureClient> temp_capture =
  820. InitCapture(temp_client, receiveSignal);
  821. client = std::move(temp_client);
  822. capture = std::move(temp_capture);
  823. if (rtwq_supported) {
  824. HRESULT hr = rtwq_put_waiting_work_item(
  825. receiveSignal, 0, sampleReadyAsyncResult, nullptr);
  826. if (FAILED(hr)) {
  827. capture.Clear();
  828. client.Clear();
  829. throw HRError("RtwqPutWaitingWorkItem failed", hr);
  830. }
  831. hr = rtwq_put_waiting_work_item(restartSignal, 0,
  832. restartAsyncResult, nullptr);
  833. if (FAILED(hr)) {
  834. capture.Clear();
  835. client.Clear();
  836. throw HRError("RtwqPutWaitingWorkItem failed", hr);
  837. }
  838. }
  839. blog(LOG_INFO, "WASAPI: Device '%s' [%" PRIu32 " Hz] initialized",
  840. device_name.c_str(), sampleRate);
  841. }
  842. bool WASAPISource::TryInitialize()
  843. {
  844. bool success = false;
  845. try {
  846. Initialize();
  847. success = true;
  848. } catch (HRError &error) {
  849. if (!previouslyFailed) {
  850. blog(LOG_WARNING,
  851. "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  852. device_name.empty() ? device_id.c_str()
  853. : device_name.c_str(),
  854. error.str, error.hr);
  855. }
  856. } catch (const char *error) {
  857. if (!previouslyFailed) {
  858. blog(LOG_WARNING,
  859. "[WASAPISource::TryInitialize]:[%s] %s",
  860. device_name.empty() ? device_id.c_str()
  861. : device_name.c_str(),
  862. error);
  863. }
  864. }
  865. previouslyFailed = !success;
  866. return success;
  867. }
  868. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  869. {
  870. os_set_thread_name("win-wasapi: reconnect thread");
  871. WASAPISource *source = (WASAPISource *)param;
  872. const HANDLE sigs[] = {
  873. source->reconnectExitSignal,
  874. source->reconnectSignal,
  875. };
  876. const HANDLE reconnect_sigs[] = {
  877. source->reconnectExitSignal,
  878. source->stopSignal,
  879. };
  880. bool exit = false;
  881. while (!exit) {
  882. const DWORD ret = WaitForMultipleObjects(_countof(sigs), sigs,
  883. false, INFINITE);
  884. switch (ret) {
  885. case WAIT_OBJECT_0:
  886. exit = true;
  887. break;
  888. default:
  889. assert(ret == (WAIT_OBJECT_0 + 1));
  890. if (source->reconnectDuration > 0) {
  891. WaitForMultipleObjects(
  892. _countof(reconnect_sigs),
  893. reconnect_sigs, false,
  894. source->reconnectDuration);
  895. }
  896. source->Start();
  897. }
  898. }
  899. return 0;
  900. }
  901. bool WASAPISource::ProcessCaptureData()
  902. {
  903. HRESULT res;
  904. LPBYTE buffer;
  905. UINT32 frames;
  906. DWORD flags;
  907. UINT64 pos, ts;
  908. UINT captureSize = 0;
  909. while (true) {
  910. if ((sourceType == SourceType::ProcessOutput) &&
  911. !IsWindow(hwnd)) {
  912. blog(LOG_WARNING,
  913. "[WASAPISource::ProcessCaptureData] window disappeared");
  914. return false;
  915. }
  916. res = capture->GetNextPacketSize(&captureSize);
  917. if (FAILED(res)) {
  918. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  919. blog(LOG_WARNING,
  920. "[WASAPISource::ProcessCaptureData]"
  921. " capture->GetNextPacketSize"
  922. " failed: %lX",
  923. res);
  924. return false;
  925. }
  926. if (!captureSize)
  927. break;
  928. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  929. if (FAILED(res)) {
  930. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  931. blog(LOG_WARNING,
  932. "[WASAPISource::ProcessCaptureData]"
  933. " capture->GetBuffer"
  934. " failed: %lX",
  935. res);
  936. return false;
  937. }
  938. obs_source_audio data = {};
  939. data.data[0] = (const uint8_t *)buffer;
  940. data.frames = (uint32_t)frames;
  941. data.speakers = speakers;
  942. data.samples_per_sec = sampleRate;
  943. data.format = format;
  944. if (sourceType == SourceType::ProcessOutput) {
  945. data.timestamp = util_mul_div64(framesProcessed,
  946. UINT64_C(1000000000),
  947. sampleRate);
  948. framesProcessed += frames;
  949. } else {
  950. data.timestamp = useDeviceTiming ? ts * 100
  951. : os_gettime_ns();
  952. if (!useDeviceTiming)
  953. data.timestamp -= util_mul_div64(
  954. frames, UINT64_C(1000000000),
  955. sampleRate);
  956. }
  957. obs_source_output_audio(source, &data);
  958. capture->ReleaseBuffer(frames);
  959. }
  960. return true;
  961. }
  962. #define RECONNECT_INTERVAL 3000
  963. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  964. {
  965. os_set_thread_name("win-wasapi: capture thread");
  966. const HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  967. const bool com_initialized = SUCCEEDED(hr);
  968. if (!com_initialized) {
  969. blog(LOG_ERROR,
  970. "[WASAPISource::CaptureThread]"
  971. " CoInitializeEx failed: 0x%08X",
  972. hr);
  973. }
  974. DWORD unused = 0;
  975. const HANDLE handle = AvSetMmThreadCharacteristics(L"Audio", &unused);
  976. WASAPISource *source = (WASAPISource *)param;
  977. const HANDLE inactive_sigs[] = {
  978. source->exitSignal,
  979. source->stopSignal,
  980. source->initSignal,
  981. };
  982. const HANDLE active_sigs[] = {
  983. source->exitSignal,
  984. source->stopSignal,
  985. source->receiveSignal,
  986. source->restartSignal,
  987. };
  988. DWORD sig_count = _countof(inactive_sigs);
  989. const HANDLE *sigs = inactive_sigs;
  990. bool exit = false;
  991. while (!exit) {
  992. bool idle = false;
  993. bool stop = false;
  994. bool reconnect = false;
  995. do {
  996. /* Windows 7 does not seem to wake up for LOOPBACK */
  997. const DWORD dwMilliseconds =
  998. ((sigs == active_sigs) &&
  999. (source->sourceType != SourceType::Input))
  1000. ? 10
  1001. : INFINITE;
  1002. const DWORD ret = WaitForMultipleObjects(
  1003. sig_count, sigs, false, dwMilliseconds);
  1004. switch (ret) {
  1005. case WAIT_OBJECT_0: {
  1006. exit = true;
  1007. stop = true;
  1008. idle = true;
  1009. break;
  1010. }
  1011. case WAIT_OBJECT_0 + 1:
  1012. stop = true;
  1013. idle = true;
  1014. break;
  1015. case WAIT_OBJECT_0 + 2:
  1016. case WAIT_TIMEOUT:
  1017. if (sigs == inactive_sigs) {
  1018. assert(ret != WAIT_TIMEOUT);
  1019. if (source->TryInitialize()) {
  1020. sig_count =
  1021. _countof(active_sigs);
  1022. sigs = active_sigs;
  1023. } else {
  1024. if (source->reconnectDuration ==
  1025. 0) {
  1026. blog(LOG_INFO,
  1027. "WASAPI: Device '%s' failed to start (source: %s)",
  1028. source->device_id
  1029. .c_str(),
  1030. obs_source_get_name(
  1031. source->source));
  1032. }
  1033. stop = true;
  1034. reconnect = true;
  1035. source->reconnectDuration =
  1036. RECONNECT_INTERVAL;
  1037. }
  1038. } else {
  1039. stop = !source->ProcessCaptureData();
  1040. if (stop) {
  1041. blog(LOG_INFO,
  1042. "Device '%s' invalidated. Retrying (source: %s)",
  1043. source->device_name.c_str(),
  1044. obs_source_get_name(
  1045. source->source));
  1046. stop = true;
  1047. reconnect = true;
  1048. source->reconnectDuration =
  1049. RECONNECT_INTERVAL;
  1050. }
  1051. }
  1052. break;
  1053. default:
  1054. assert(sigs == active_sigs);
  1055. assert(ret == WAIT_OBJECT_0 + 3);
  1056. stop = true;
  1057. reconnect = true;
  1058. source->reconnectDuration = 0;
  1059. ResetEvent(source->restartSignal);
  1060. }
  1061. } while (!stop);
  1062. sig_count = _countof(inactive_sigs);
  1063. sigs = inactive_sigs;
  1064. if (source->client) {
  1065. source->client->Stop();
  1066. source->capture.Clear();
  1067. source->client.Clear();
  1068. }
  1069. if (idle) {
  1070. SetEvent(source->idleSignal);
  1071. } else if (reconnect) {
  1072. blog(LOG_INFO,
  1073. "Device '%s' invalidated. Retrying (source: %s)",
  1074. source->device_name.c_str(),
  1075. obs_source_get_name(source->source));
  1076. SetEvent(source->reconnectSignal);
  1077. }
  1078. }
  1079. if (handle)
  1080. AvRevertMmThreadCharacteristics(handle);
  1081. if (com_initialized)
  1082. CoUninitialize();
  1083. return 0;
  1084. }
  1085. void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id)
  1086. {
  1087. if (!isDefaultDevice)
  1088. return;
  1089. const bool input = sourceType == SourceType::Input;
  1090. const EDataFlow expectedFlow = input ? eCapture : eRender;
  1091. const ERole expectedRole = input ? eCommunications : eConsole;
  1092. if (flow != expectedFlow || role != expectedRole)
  1093. return;
  1094. if (id) {
  1095. if (default_id.compare(id) == 0)
  1096. return;
  1097. default_id = id;
  1098. } else {
  1099. if (default_id.empty())
  1100. return;
  1101. default_id.clear();
  1102. }
  1103. blog(LOG_INFO, "WASAPI: Default %s device changed",
  1104. input ? "input" : "output");
  1105. SetEvent(restartSignal);
  1106. }
  1107. void WASAPISource::OnStartCapture()
  1108. {
  1109. const DWORD ret = WaitForSingleObject(stopSignal, 0);
  1110. switch (ret) {
  1111. case WAIT_OBJECT_0:
  1112. SetEvent(idleSignal);
  1113. break;
  1114. default:
  1115. assert(ret == WAIT_TIMEOUT);
  1116. if (!TryInitialize()) {
  1117. if (reconnectDuration == 0) {
  1118. blog(LOG_INFO,
  1119. "WASAPI: Device '%s' failed to start (source: %s)",
  1120. device_id.c_str(),
  1121. obs_source_get_name(source));
  1122. }
  1123. reconnectDuration = RECONNECT_INTERVAL;
  1124. SetEvent(reconnectSignal);
  1125. }
  1126. }
  1127. }
  1128. void WASAPISource::OnSampleReady()
  1129. {
  1130. bool stop = false;
  1131. bool reconnect = false;
  1132. if (!ProcessCaptureData()) {
  1133. stop = true;
  1134. reconnect = true;
  1135. reconnectDuration = RECONNECT_INTERVAL;
  1136. }
  1137. if (WaitForSingleObject(restartSignal, 0) == WAIT_OBJECT_0) {
  1138. stop = true;
  1139. reconnect = true;
  1140. reconnectDuration = 0;
  1141. ResetEvent(restartSignal);
  1142. rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult,
  1143. nullptr);
  1144. }
  1145. if (WaitForSingleObject(stopSignal, 0) == WAIT_OBJECT_0) {
  1146. stop = true;
  1147. reconnect = false;
  1148. }
  1149. if (!stop) {
  1150. if (FAILED(rtwq_put_waiting_work_item(receiveSignal, 0,
  1151. sampleReadyAsyncResult,
  1152. nullptr))) {
  1153. blog(LOG_ERROR,
  1154. "Could not requeue sample receive work");
  1155. stop = true;
  1156. reconnect = true;
  1157. reconnectDuration = RECONNECT_INTERVAL;
  1158. }
  1159. }
  1160. if (stop) {
  1161. client->Stop();
  1162. capture.Clear();
  1163. client.Clear();
  1164. if (reconnect) {
  1165. blog(LOG_INFO,
  1166. "Device '%s' invalidated. Retrying (source: %s)",
  1167. device_name.c_str(), obs_source_get_name(source));
  1168. SetEvent(reconnectSignal);
  1169. } else {
  1170. SetEvent(idleSignal);
  1171. }
  1172. }
  1173. }
  1174. void WASAPISource::OnRestart()
  1175. {
  1176. SetEvent(receiveSignal);
  1177. }
  1178. /* ------------------------------------------------------------------------- */
  1179. static const char *GetWASAPIInputName(void *)
  1180. {
  1181. return obs_module_text("AudioInput");
  1182. }
  1183. static const char *GetWASAPIDeviceOutputName(void *)
  1184. {
  1185. return obs_module_text("AudioOutput");
  1186. }
  1187. static const char *GetWASAPIProcessOutputName(void *)
  1188. {
  1189. return obs_module_text("ApplicationAudioCapture");
  1190. }
  1191. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  1192. {
  1193. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  1194. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  1195. }
  1196. static void GetWASAPIDefaultsDeviceOutput(obs_data_t *settings)
  1197. {
  1198. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  1199. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  1200. }
  1201. static void GetWASAPIDefaultsProcessOutput(obs_data_t *) {}
  1202. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  1203. SourceType type)
  1204. {
  1205. try {
  1206. return new WASAPISource(settings, source, type);
  1207. } catch (const char *error) {
  1208. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  1209. }
  1210. return nullptr;
  1211. }
  1212. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  1213. {
  1214. return CreateWASAPISource(settings, source, SourceType::Input);
  1215. }
  1216. static void *CreateWASAPIDeviceOutput(obs_data_t *settings,
  1217. obs_source_t *source)
  1218. {
  1219. return CreateWASAPISource(settings, source, SourceType::DeviceOutput);
  1220. }
  1221. static void *CreateWASAPIProcessOutput(obs_data_t *settings,
  1222. obs_source_t *source)
  1223. {
  1224. return CreateWASAPISource(settings, source, SourceType::ProcessOutput);
  1225. }
  1226. static void DestroyWASAPISource(void *obj)
  1227. {
  1228. delete static_cast<WASAPISource *>(obj);
  1229. }
  1230. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  1231. {
  1232. static_cast<WASAPISource *>(obj)->Update(settings);
  1233. }
  1234. static void ActivateWASAPISource(void *obj)
  1235. {
  1236. static_cast<WASAPISource *>(obj)->Activate();
  1237. }
  1238. static void DeactivateWASAPISource(void *obj)
  1239. {
  1240. static_cast<WASAPISource *>(obj)->Deactivate();
  1241. }
  1242. static bool UpdateWASAPIMethod(obs_properties_t *props, obs_property_t *,
  1243. obs_data_t *settings)
  1244. {
  1245. WASAPISource *source = (WASAPISource *)obs_properties_get_param(props);
  1246. if (!source)
  1247. return false;
  1248. source->Update(settings);
  1249. return true;
  1250. }
  1251. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  1252. {
  1253. obs_properties_t *props = obs_properties_create();
  1254. vector<AudioDeviceInfo> devices;
  1255. obs_property_t *device_prop = obs_properties_add_list(
  1256. props, OPT_DEVICE_ID, obs_module_text("Device"),
  1257. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1258. GetWASAPIAudioDevices(devices, true);
  1259. if (devices.size())
  1260. obs_property_list_add_string(
  1261. device_prop, obs_module_text("Default"), "default");
  1262. for (size_t i = 0; i < devices.size(); i++) {
  1263. AudioDeviceInfo &device = devices[i];
  1264. obs_property_list_add_string(device_prop, device.name.c_str(),
  1265. device.id.c_str());
  1266. }
  1267. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  1268. obs_module_text("UseDeviceTiming"));
  1269. return props;
  1270. }
  1271. static obs_properties_t *GetWASAPIPropertiesDeviceOutput(void *)
  1272. {
  1273. obs_properties_t *props = obs_properties_create();
  1274. vector<AudioDeviceInfo> devices;
  1275. obs_property_t *device_prop = obs_properties_add_list(
  1276. props, OPT_DEVICE_ID, obs_module_text("Device"),
  1277. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1278. GetWASAPIAudioDevices(devices, false);
  1279. if (devices.size())
  1280. obs_property_list_add_string(
  1281. device_prop, obs_module_text("Default"), "default");
  1282. for (size_t i = 0; i < devices.size(); i++) {
  1283. AudioDeviceInfo &device = devices[i];
  1284. obs_property_list_add_string(device_prop, device.name.c_str(),
  1285. device.id.c_str());
  1286. }
  1287. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  1288. obs_module_text("UseDeviceTiming"));
  1289. return props;
  1290. }
  1291. static bool wasapi_window_changed(obs_properties_t *props, obs_property_t *p,
  1292. obs_data_t *settings)
  1293. {
  1294. WASAPISource *source = (WASAPISource *)obs_properties_get_param(props);
  1295. if (!source)
  1296. return false;
  1297. source->OnWindowChanged(settings);
  1298. ms_check_window_property_setting(props, p, settings, "window", 0);
  1299. return true;
  1300. }
  1301. static obs_properties_t *GetWASAPIPropertiesProcessOutput(void *data)
  1302. {
  1303. obs_properties_t *props = obs_properties_create();
  1304. obs_properties_set_param(props, data, NULL);
  1305. obs_property_t *const window_prop = obs_properties_add_list(
  1306. props, OPT_WINDOW, obs_module_text("Window"),
  1307. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1308. ms_fill_window_list(window_prop, INCLUDE_MINIMIZED, nullptr);
  1309. obs_property_set_modified_callback(window_prop, wasapi_window_changed);
  1310. obs_property_t *const priority_prop = obs_properties_add_list(
  1311. props, OPT_PRIORITY, obs_module_text("Priority"),
  1312. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1313. obs_property_list_add_int(priority_prop,
  1314. obs_module_text("Priority.Title"),
  1315. WINDOW_PRIORITY_TITLE);
  1316. obs_property_list_add_int(priority_prop,
  1317. obs_module_text("Priority.Class"),
  1318. WINDOW_PRIORITY_CLASS);
  1319. obs_property_list_add_int(priority_prop,
  1320. obs_module_text("Priority.Exe"),
  1321. WINDOW_PRIORITY_EXE);
  1322. return props;
  1323. }
  1324. void RegisterWASAPIInput()
  1325. {
  1326. obs_source_info info = {};
  1327. info.id = "wasapi_input_capture";
  1328. info.type = OBS_SOURCE_TYPE_INPUT;
  1329. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  1330. info.get_name = GetWASAPIInputName;
  1331. info.create = CreateWASAPIInput;
  1332. info.destroy = DestroyWASAPISource;
  1333. info.update = UpdateWASAPISource;
  1334. info.activate = ActivateWASAPISource;
  1335. info.deactivate = DeactivateWASAPISource;
  1336. info.get_defaults = GetWASAPIDefaultsInput;
  1337. info.get_properties = GetWASAPIPropertiesInput;
  1338. info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
  1339. obs_register_source(&info);
  1340. }
  1341. void RegisterWASAPIDeviceOutput()
  1342. {
  1343. obs_source_info info = {};
  1344. info.id = "wasapi_output_capture";
  1345. info.type = OBS_SOURCE_TYPE_INPUT;
  1346. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  1347. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  1348. info.get_name = GetWASAPIDeviceOutputName;
  1349. info.create = CreateWASAPIDeviceOutput;
  1350. info.destroy = DestroyWASAPISource;
  1351. info.update = UpdateWASAPISource;
  1352. info.activate = ActivateWASAPISource;
  1353. info.deactivate = DeactivateWASAPISource;
  1354. info.get_defaults = GetWASAPIDefaultsDeviceOutput;
  1355. info.get_properties = GetWASAPIPropertiesDeviceOutput;
  1356. info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
  1357. obs_register_source(&info);
  1358. }
  1359. void RegisterWASAPIProcessOutput()
  1360. {
  1361. obs_source_info info = {};
  1362. info.id = "wasapi_process_output_capture";
  1363. info.type = OBS_SOURCE_TYPE_INPUT;
  1364. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  1365. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  1366. info.get_name = GetWASAPIProcessOutputName;
  1367. info.create = CreateWASAPIProcessOutput;
  1368. info.destroy = DestroyWASAPISource;
  1369. info.update = UpdateWASAPISource;
  1370. info.activate = ActivateWASAPISource;
  1371. info.deactivate = DeactivateWASAPISource;
  1372. info.get_defaults = GetWASAPIDefaultsProcessOutput;
  1373. info.get_properties = GetWASAPIPropertiesProcessOutput;
  1374. info.icon_type = OBS_ICON_TYPE_PROCESS_AUDIO_OUTPUT;
  1375. obs_register_source(&info);
  1376. }