win-wasapi.cpp 40 KB

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