win-wasapi.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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. if (source->reconnectDuration ==
  992. 0) {
  993. blog(LOG_INFO,
  994. "WASAPI: Device '%s' failed to start (source: %s)",
  995. source->device_id
  996. .c_str(),
  997. obs_source_get_name(
  998. source->source));
  999. }
  1000. stop = true;
  1001. reconnect = true;
  1002. source->reconnectDuration =
  1003. RECONNECT_INTERVAL;
  1004. }
  1005. } else {
  1006. stop = !source->ProcessCaptureData();
  1007. if (stop) {
  1008. blog(LOG_INFO,
  1009. "Device '%s' invalidated. Retrying (source: %s)",
  1010. source->device_name.c_str(),
  1011. obs_source_get_name(
  1012. source->source));
  1013. stop = true;
  1014. reconnect = true;
  1015. source->reconnectDuration =
  1016. RECONNECT_INTERVAL;
  1017. }
  1018. }
  1019. break;
  1020. default:
  1021. assert(sigs == active_sigs);
  1022. assert(ret == WAIT_OBJECT_0 + 3);
  1023. stop = true;
  1024. reconnect = true;
  1025. source->reconnectDuration = 0;
  1026. ResetEvent(source->restartSignal);
  1027. }
  1028. } while (!stop);
  1029. sig_count = _countof(inactive_sigs);
  1030. sigs = inactive_sigs;
  1031. if (source->client) {
  1032. source->client->Stop();
  1033. source->capture.Clear();
  1034. source->client.Clear();
  1035. }
  1036. if (idle) {
  1037. SetEvent(source->idleSignal);
  1038. } else if (reconnect) {
  1039. blog(LOG_INFO,
  1040. "Device '%s' invalidated. Retrying (source: %s)",
  1041. source->device_name.c_str(),
  1042. obs_source_get_name(source->source));
  1043. SetEvent(source->reconnectSignal);
  1044. }
  1045. }
  1046. if (handle)
  1047. AvRevertMmThreadCharacteristics(handle);
  1048. if (com_initialized)
  1049. CoUninitialize();
  1050. return 0;
  1051. }
  1052. void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id)
  1053. {
  1054. if (!isDefaultDevice)
  1055. return;
  1056. const bool input = sourceType == SourceType::Input;
  1057. const EDataFlow expectedFlow = input ? eCapture : eRender;
  1058. const ERole expectedRole = input ? eCommunications : eConsole;
  1059. if (flow != expectedFlow || role != expectedRole)
  1060. return;
  1061. if (id) {
  1062. if (default_id.compare(id) == 0)
  1063. return;
  1064. default_id = id;
  1065. } else {
  1066. if (default_id.empty())
  1067. return;
  1068. default_id.clear();
  1069. }
  1070. blog(LOG_INFO, "WASAPI: Default %s device changed",
  1071. input ? "input" : "output");
  1072. SetEvent(restartSignal);
  1073. }
  1074. void WASAPISource::OnStartCapture()
  1075. {
  1076. const DWORD ret = WaitForSingleObject(stopSignal, 0);
  1077. switch (ret) {
  1078. case WAIT_OBJECT_0:
  1079. SetEvent(idleSignal);
  1080. break;
  1081. default:
  1082. assert(ret == WAIT_TIMEOUT);
  1083. if (!TryInitialize()) {
  1084. if (reconnectDuration == 0) {
  1085. blog(LOG_INFO,
  1086. "WASAPI: Device '%s' failed to start (source: %s)",
  1087. device_id.c_str(),
  1088. obs_source_get_name(source));
  1089. }
  1090. reconnectDuration = RECONNECT_INTERVAL;
  1091. SetEvent(reconnectSignal);
  1092. }
  1093. }
  1094. }
  1095. void WASAPISource::OnSampleReady()
  1096. {
  1097. bool stop = false;
  1098. bool reconnect = false;
  1099. if (!ProcessCaptureData()) {
  1100. stop = true;
  1101. reconnect = true;
  1102. reconnectDuration = RECONNECT_INTERVAL;
  1103. }
  1104. if (WaitForSingleObject(restartSignal, 0) == WAIT_OBJECT_0) {
  1105. stop = true;
  1106. reconnect = true;
  1107. reconnectDuration = 0;
  1108. ResetEvent(restartSignal);
  1109. rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult,
  1110. nullptr);
  1111. }
  1112. if (WaitForSingleObject(stopSignal, 0) == WAIT_OBJECT_0) {
  1113. stop = true;
  1114. reconnect = false;
  1115. }
  1116. if (!stop) {
  1117. if (FAILED(rtwq_put_waiting_work_item(receiveSignal, 0,
  1118. sampleReadyAsyncResult,
  1119. nullptr))) {
  1120. blog(LOG_ERROR,
  1121. "Could not requeue sample receive work");
  1122. stop = true;
  1123. reconnect = true;
  1124. reconnectDuration = RECONNECT_INTERVAL;
  1125. }
  1126. }
  1127. if (stop) {
  1128. client->Stop();
  1129. capture.Clear();
  1130. client.Clear();
  1131. if (reconnect) {
  1132. blog(LOG_INFO,
  1133. "Device '%s' invalidated. Retrying (source: %s)",
  1134. device_name.c_str(), obs_source_get_name(source));
  1135. SetEvent(reconnectSignal);
  1136. } else {
  1137. SetEvent(idleSignal);
  1138. }
  1139. }
  1140. }
  1141. void WASAPISource::OnRestart()
  1142. {
  1143. SetEvent(receiveSignal);
  1144. }
  1145. /* ------------------------------------------------------------------------- */
  1146. static const char *GetWASAPIInputName(void *)
  1147. {
  1148. return obs_module_text("AudioInput");
  1149. }
  1150. static const char *GetWASAPIDeviceOutputName(void *)
  1151. {
  1152. return obs_module_text("AudioOutput");
  1153. }
  1154. static const char *GetWASAPIProcessOutputName(void *)
  1155. {
  1156. return obs_module_text("ApplicationAudioCapture");
  1157. }
  1158. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  1159. {
  1160. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  1161. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  1162. }
  1163. static void GetWASAPIDefaultsDeviceOutput(obs_data_t *settings)
  1164. {
  1165. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  1166. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  1167. }
  1168. static void GetWASAPIDefaultsProcessOutput(obs_data_t *) {}
  1169. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  1170. SourceType type)
  1171. {
  1172. try {
  1173. return new WASAPISource(settings, source, type);
  1174. } catch (const char *error) {
  1175. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  1176. }
  1177. return nullptr;
  1178. }
  1179. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  1180. {
  1181. return CreateWASAPISource(settings, source, SourceType::Input);
  1182. }
  1183. static void *CreateWASAPIDeviceOutput(obs_data_t *settings,
  1184. obs_source_t *source)
  1185. {
  1186. return CreateWASAPISource(settings, source, SourceType::DeviceOutput);
  1187. }
  1188. static void *CreateWASAPIProcessOutput(obs_data_t *settings,
  1189. obs_source_t *source)
  1190. {
  1191. return CreateWASAPISource(settings, source, SourceType::ProcessOutput);
  1192. }
  1193. static void DestroyWASAPISource(void *obj)
  1194. {
  1195. delete static_cast<WASAPISource *>(obj);
  1196. }
  1197. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  1198. {
  1199. static_cast<WASAPISource *>(obj)->Update(settings);
  1200. }
  1201. static bool UpdateWASAPIMethod(obs_properties_t *props, obs_property_t *,
  1202. obs_data_t *settings)
  1203. {
  1204. WASAPISource *source = (WASAPISource *)obs_properties_get_param(props);
  1205. if (!source)
  1206. return false;
  1207. source->Update(settings);
  1208. return true;
  1209. }
  1210. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  1211. {
  1212. obs_properties_t *props = obs_properties_create();
  1213. vector<AudioDeviceInfo> devices;
  1214. obs_property_t *device_prop = obs_properties_add_list(
  1215. props, OPT_DEVICE_ID, obs_module_text("Device"),
  1216. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1217. GetWASAPIAudioDevices(devices, true);
  1218. if (devices.size())
  1219. obs_property_list_add_string(
  1220. device_prop, obs_module_text("Default"), "default");
  1221. for (size_t i = 0; i < devices.size(); i++) {
  1222. AudioDeviceInfo &device = devices[i];
  1223. obs_property_list_add_string(device_prop, device.name.c_str(),
  1224. device.id.c_str());
  1225. }
  1226. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  1227. obs_module_text("UseDeviceTiming"));
  1228. return props;
  1229. }
  1230. static obs_properties_t *GetWASAPIPropertiesDeviceOutput(void *)
  1231. {
  1232. obs_properties_t *props = obs_properties_create();
  1233. vector<AudioDeviceInfo> devices;
  1234. obs_property_t *device_prop = obs_properties_add_list(
  1235. props, OPT_DEVICE_ID, obs_module_text("Device"),
  1236. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1237. GetWASAPIAudioDevices(devices, false);
  1238. if (devices.size())
  1239. obs_property_list_add_string(
  1240. device_prop, obs_module_text("Default"), "default");
  1241. for (size_t i = 0; i < devices.size(); i++) {
  1242. AudioDeviceInfo &device = devices[i];
  1243. obs_property_list_add_string(device_prop, device.name.c_str(),
  1244. device.id.c_str());
  1245. }
  1246. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  1247. obs_module_text("UseDeviceTiming"));
  1248. return props;
  1249. }
  1250. static bool wasapi_window_changed(obs_properties_t *props, obs_property_t *p,
  1251. obs_data_t *settings)
  1252. {
  1253. WASAPISource *source = (WASAPISource *)obs_properties_get_param(props);
  1254. if (!source)
  1255. return false;
  1256. source->OnWindowChanged(settings);
  1257. ms_check_window_property_setting(props, p, settings, "window", 0);
  1258. return true;
  1259. }
  1260. static obs_properties_t *GetWASAPIPropertiesProcessOutput(void *data)
  1261. {
  1262. obs_properties_t *props = obs_properties_create();
  1263. obs_properties_set_param(props, data, NULL);
  1264. obs_property_t *const window_prop = obs_properties_add_list(
  1265. props, OPT_WINDOW, obs_module_text("Window"),
  1266. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1267. ms_fill_window_list(window_prop, INCLUDE_MINIMIZED, nullptr);
  1268. obs_property_set_modified_callback(window_prop, wasapi_window_changed);
  1269. obs_property_t *const priority_prop = obs_properties_add_list(
  1270. props, OPT_PRIORITY, obs_module_text("Priority"),
  1271. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1272. obs_property_list_add_int(priority_prop,
  1273. obs_module_text("Priority.Title"),
  1274. WINDOW_PRIORITY_TITLE);
  1275. obs_property_list_add_int(priority_prop,
  1276. obs_module_text("Priority.Class"),
  1277. WINDOW_PRIORITY_CLASS);
  1278. obs_property_list_add_int(priority_prop,
  1279. obs_module_text("Priority.Exe"),
  1280. WINDOW_PRIORITY_EXE);
  1281. return props;
  1282. }
  1283. void RegisterWASAPIInput()
  1284. {
  1285. obs_source_info info = {};
  1286. info.id = "wasapi_input_capture";
  1287. info.type = OBS_SOURCE_TYPE_INPUT;
  1288. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  1289. info.get_name = GetWASAPIInputName;
  1290. info.create = CreateWASAPIInput;
  1291. info.destroy = DestroyWASAPISource;
  1292. info.update = UpdateWASAPISource;
  1293. info.get_defaults = GetWASAPIDefaultsInput;
  1294. info.get_properties = GetWASAPIPropertiesInput;
  1295. info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
  1296. obs_register_source(&info);
  1297. }
  1298. void RegisterWASAPIDeviceOutput()
  1299. {
  1300. obs_source_info info = {};
  1301. info.id = "wasapi_output_capture";
  1302. info.type = OBS_SOURCE_TYPE_INPUT;
  1303. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  1304. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  1305. info.get_name = GetWASAPIDeviceOutputName;
  1306. info.create = CreateWASAPIDeviceOutput;
  1307. info.destroy = DestroyWASAPISource;
  1308. info.update = UpdateWASAPISource;
  1309. info.get_defaults = GetWASAPIDefaultsDeviceOutput;
  1310. info.get_properties = GetWASAPIPropertiesDeviceOutput;
  1311. info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
  1312. obs_register_source(&info);
  1313. }
  1314. void RegisterWASAPIProcessOutput()
  1315. {
  1316. obs_source_info info = {};
  1317. info.id = "wasapi_process_output_capture";
  1318. info.type = OBS_SOURCE_TYPE_INPUT;
  1319. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  1320. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  1321. info.get_name = GetWASAPIProcessOutputName;
  1322. info.create = CreateWASAPIProcessOutput;
  1323. info.destroy = DestroyWASAPISource;
  1324. info.update = UpdateWASAPISource;
  1325. info.get_defaults = GetWASAPIDefaultsProcessOutput;
  1326. info.get_properties = GetWASAPIPropertiesProcessOutput;
  1327. info.icon_type = OBS_ICON_TYPE_PROCESS_AUDIO_OUTPUT;
  1328. obs_register_source(&info);
  1329. }