win-wasapi.cpp 45 KB

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