win-wasapi.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. #include "enum-wasapi.hpp"
  2. #include <obs-module.h>
  3. #include <obs.h>
  4. #include <util/platform.h>
  5. #include <util/windows/HRError.hpp>
  6. #include <util/windows/ComPtr.hpp>
  7. #include <util/windows/WinHandle.hpp>
  8. #include <util/windows/CoTaskMemPtr.hpp>
  9. #include <util/threading.h>
  10. #include <util/util_uint64.h>
  11. #include <atomic>
  12. #include <cinttypes>
  13. #include <avrt.h>
  14. #include <RTWorkQ.h>
  15. using namespace std;
  16. #define OPT_DEVICE_ID "device_id"
  17. #define OPT_USE_DEVICE_TIMING "use_device_timing"
  18. static void GetWASAPIDefaults(obs_data_t *settings);
  19. #define OBS_KSAUDIO_SPEAKER_4POINT1 \
  20. (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY)
  21. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqUnlockWorkQueue)(DWORD);
  22. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqLockSharedWorkQueue)(PCWSTR usageClass,
  23. LONG basePriority,
  24. DWORD *taskId,
  25. DWORD *id);
  26. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqCreateAsyncResult)(IUnknown *,
  27. IRtwqAsyncCallback *,
  28. IUnknown *,
  29. IRtwqAsyncResult **);
  30. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWorkItem)(DWORD, LONG,
  31. IRtwqAsyncResult *);
  32. typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWaitingWorkItem)(HANDLE, LONG,
  33. IRtwqAsyncResult *,
  34. RTWQWORKITEM_KEY *);
  35. class ARtwqAsyncCallback : public IRtwqAsyncCallback {
  36. protected:
  37. ARtwqAsyncCallback(void *source) : source(source) {}
  38. public:
  39. STDMETHOD_(ULONG, AddRef)() { return ++refCount; }
  40. STDMETHOD_(ULONG, Release)() { return --refCount; }
  41. STDMETHOD(QueryInterface)(REFIID riid, void **ppvObject)
  42. {
  43. HRESULT hr = E_NOINTERFACE;
  44. if (riid == __uuidof(IRtwqAsyncCallback) ||
  45. riid == __uuidof(IUnknown)) {
  46. *ppvObject = this;
  47. AddRef();
  48. hr = S_OK;
  49. } else {
  50. *ppvObject = NULL;
  51. }
  52. return hr;
  53. }
  54. STDMETHOD(GetParameters)
  55. (DWORD *pdwFlags, DWORD *pdwQueue)
  56. {
  57. *pdwFlags = 0;
  58. *pdwQueue = queue_id;
  59. return S_OK;
  60. }
  61. STDMETHOD(Invoke)
  62. (IRtwqAsyncResult *) override = 0;
  63. DWORD GetQueueId() const { return queue_id; }
  64. void SetQueueId(DWORD id) { queue_id = id; }
  65. protected:
  66. std::atomic<ULONG> refCount = 1;
  67. void *source;
  68. DWORD queue_id = 0;
  69. };
  70. class WASAPISource {
  71. ComPtr<IMMNotificationClient> notify;
  72. ComPtr<IMMDeviceEnumerator> enumerator;
  73. ComPtr<IAudioClient> client;
  74. ComPtr<IAudioCaptureClient> capture;
  75. obs_source_t *source;
  76. wstring default_id;
  77. string device_id;
  78. string device_name;
  79. PFN_RtwqUnlockWorkQueue rtwq_unlock_work_queue = NULL;
  80. PFN_RtwqLockSharedWorkQueue rtwq_lock_shared_work_queue = NULL;
  81. PFN_RtwqCreateAsyncResult rtwq_create_async_result = NULL;
  82. PFN_RtwqPutWorkItem rtwq_put_work_item = NULL;
  83. PFN_RtwqPutWaitingWorkItem rtwq_put_waiting_work_item = NULL;
  84. bool rtwq_supported = false;
  85. uint64_t lastNotifyTime = 0;
  86. bool isInputDevice;
  87. std::atomic<bool> useDeviceTiming = false;
  88. bool isDefaultDevice = false;
  89. bool previouslyFailed = false;
  90. WinHandle reconnectThread;
  91. class CallbackStartCapture : public ARtwqAsyncCallback {
  92. public:
  93. CallbackStartCapture(WASAPISource *source)
  94. : ARtwqAsyncCallback(source)
  95. {
  96. }
  97. STDMETHOD(Invoke)
  98. (IRtwqAsyncResult *) override
  99. {
  100. ((WASAPISource *)source)->OnStartCapture();
  101. return S_OK;
  102. }
  103. } startCapture;
  104. ComPtr<IRtwqAsyncResult> startCaptureAsyncResult;
  105. class CallbackSampleReady : public ARtwqAsyncCallback {
  106. public:
  107. CallbackSampleReady(WASAPISource *source)
  108. : ARtwqAsyncCallback(source)
  109. {
  110. }
  111. STDMETHOD(Invoke)
  112. (IRtwqAsyncResult *) override
  113. {
  114. ((WASAPISource *)source)->OnSampleReady();
  115. return S_OK;
  116. }
  117. } sampleReady;
  118. ComPtr<IRtwqAsyncResult> sampleReadyAsyncResult;
  119. class CallbackRestart : public ARtwqAsyncCallback {
  120. public:
  121. CallbackRestart(WASAPISource *source)
  122. : ARtwqAsyncCallback(source)
  123. {
  124. }
  125. STDMETHOD(Invoke)
  126. (IRtwqAsyncResult *) override
  127. {
  128. ((WASAPISource *)source)->OnRestart();
  129. return S_OK;
  130. }
  131. } restart;
  132. ComPtr<IRtwqAsyncResult> restartAsyncResult;
  133. WinHandle captureThread;
  134. WinHandle idleSignal;
  135. WinHandle stopSignal;
  136. WinHandle receiveSignal;
  137. WinHandle restartSignal;
  138. WinHandle exitSignal;
  139. WinHandle initSignal;
  140. DWORD reconnectDuration = 0;
  141. WinHandle reconnectSignal;
  142. speaker_layout speakers;
  143. audio_format format;
  144. uint32_t sampleRate;
  145. static DWORD WINAPI ReconnectThread(LPVOID param);
  146. static DWORD WINAPI CaptureThread(LPVOID param);
  147. bool ProcessCaptureData();
  148. void Start();
  149. void Stop();
  150. static ComPtr<IMMDevice> InitDevice(IMMDeviceEnumerator *enumerator,
  151. bool isDefaultDevice,
  152. bool isInputDevice,
  153. const string device_id,
  154. wstring &default_id);
  155. static ComPtr<IAudioClient> InitClient(IMMDevice *device,
  156. bool isInputDevice,
  157. enum speaker_layout &speakers,
  158. enum audio_format &format,
  159. uint32_t &sampleRate);
  160. static void InitFormat(const WAVEFORMATEX *wfex,
  161. enum speaker_layout &speakers,
  162. enum audio_format &format, uint32_t &sampleRate);
  163. static void ClearBuffer(IMMDevice *device);
  164. static ComPtr<IAudioCaptureClient> InitCapture(IAudioClient *client,
  165. HANDLE receiveSignal);
  166. void Initialize();
  167. bool TryInitialize();
  168. void UpdateSettings(obs_data_t *settings);
  169. public:
  170. WASAPISource(obs_data_t *settings, obs_source_t *source_, bool input);
  171. ~WASAPISource();
  172. void Update(obs_data_t *settings);
  173. void SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id);
  174. void OnStartCapture();
  175. void OnSampleReady();
  176. void OnRestart();
  177. };
  178. class WASAPINotify : public IMMNotificationClient {
  179. long refs = 0; /* auto-incremented to 1 by ComPtr */
  180. WASAPISource *source;
  181. public:
  182. WASAPINotify(WASAPISource *source_) : source(source_) {}
  183. STDMETHODIMP_(ULONG) AddRef()
  184. {
  185. return (ULONG)os_atomic_inc_long(&refs);
  186. }
  187. STDMETHODIMP_(ULONG) STDMETHODCALLTYPE Release()
  188. {
  189. long val = os_atomic_dec_long(&refs);
  190. if (val == 0)
  191. delete this;
  192. return (ULONG)val;
  193. }
  194. STDMETHODIMP QueryInterface(REFIID riid, void **ptr)
  195. {
  196. if (riid == IID_IUnknown) {
  197. *ptr = (IUnknown *)this;
  198. } else if (riid == __uuidof(IMMNotificationClient)) {
  199. *ptr = (IMMNotificationClient *)this;
  200. } else {
  201. *ptr = nullptr;
  202. return E_NOINTERFACE;
  203. }
  204. os_atomic_inc_long(&refs);
  205. return S_OK;
  206. }
  207. STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role,
  208. LPCWSTR id)
  209. {
  210. source->SetDefaultDevice(flow, role, id);
  211. return S_OK;
  212. }
  213. STDMETHODIMP OnDeviceAdded(LPCWSTR) { return S_OK; }
  214. STDMETHODIMP OnDeviceRemoved(LPCWSTR) { return S_OK; }
  215. STDMETHODIMP OnDeviceStateChanged(LPCWSTR, DWORD) { return S_OK; }
  216. STDMETHODIMP OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY)
  217. {
  218. return S_OK;
  219. }
  220. };
  221. WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
  222. bool input)
  223. : source(source_),
  224. isInputDevice(input),
  225. startCapture(this),
  226. sampleReady(this),
  227. restart(this)
  228. {
  229. UpdateSettings(settings);
  230. idleSignal = CreateEvent(nullptr, true, false, nullptr);
  231. if (!idleSignal.Valid())
  232. throw "Could not create idle signal";
  233. stopSignal = CreateEvent(nullptr, true, false, nullptr);
  234. if (!stopSignal.Valid())
  235. throw "Could not create stop signal";
  236. receiveSignal = CreateEvent(nullptr, false, false, nullptr);
  237. if (!receiveSignal.Valid())
  238. throw "Could not create receive signal";
  239. restartSignal = CreateEvent(nullptr, true, false, nullptr);
  240. if (!restartSignal.Valid())
  241. throw "Could not create restart signal";
  242. exitSignal = CreateEvent(nullptr, true, false, nullptr);
  243. if (!exitSignal.Valid())
  244. throw "Could not create exit signal";
  245. initSignal = CreateEvent(nullptr, false, false, nullptr);
  246. if (!initSignal.Valid())
  247. throw "Could not create init signal";
  248. reconnectSignal = CreateEvent(nullptr, false, false, nullptr);
  249. if (!reconnectSignal.Valid())
  250. throw "Could not create reconnect signal";
  251. reconnectThread = CreateThread(
  252. nullptr, 0, WASAPISource::ReconnectThread, this, 0, nullptr);
  253. if (!reconnectThread.Valid())
  254. throw "Failed to create reconnect thread";
  255. notify = new WASAPINotify(this);
  256. if (!notify)
  257. throw "Could not create WASAPINotify";
  258. HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
  259. CLSCTX_ALL,
  260. IID_PPV_ARGS(enumerator.Assign()));
  261. if (FAILED(hr))
  262. throw HRError("Failed to create enumerator", hr);
  263. hr = enumerator->RegisterEndpointNotificationCallback(notify);
  264. if (FAILED(hr))
  265. throw HRError("Failed to register endpoint callback", hr);
  266. /* OBS will already load DLL on startup if it exists */
  267. const HMODULE rtwq_module = GetModuleHandle(L"RTWorkQ.dll");
  268. rtwq_supported = rtwq_module != NULL;
  269. if (rtwq_supported) {
  270. rtwq_unlock_work_queue =
  271. (PFN_RtwqUnlockWorkQueue)GetProcAddress(
  272. rtwq_module, "RtwqUnlockWorkQueue");
  273. rtwq_lock_shared_work_queue =
  274. (PFN_RtwqLockSharedWorkQueue)GetProcAddress(
  275. rtwq_module, "RtwqLockSharedWorkQueue");
  276. rtwq_create_async_result =
  277. (PFN_RtwqCreateAsyncResult)GetProcAddress(
  278. rtwq_module, "RtwqCreateAsyncResult");
  279. rtwq_put_work_item = (PFN_RtwqPutWorkItem)GetProcAddress(
  280. rtwq_module, "RtwqPutWorkItem");
  281. rtwq_put_waiting_work_item =
  282. (PFN_RtwqPutWaitingWorkItem)GetProcAddress(
  283. rtwq_module, "RtwqPutWaitingWorkItem");
  284. hr = rtwq_create_async_result(nullptr, &startCapture, nullptr,
  285. &startCaptureAsyncResult);
  286. if (FAILED(hr)) {
  287. enumerator->UnregisterEndpointNotificationCallback(
  288. notify);
  289. throw HRError(
  290. "Could not create startCaptureAsyncResult", hr);
  291. }
  292. hr = rtwq_create_async_result(nullptr, &sampleReady, nullptr,
  293. &sampleReadyAsyncResult);
  294. if (FAILED(hr)) {
  295. enumerator->UnregisterEndpointNotificationCallback(
  296. notify);
  297. throw HRError("Could not create sampleReadyAsyncResult",
  298. hr);
  299. }
  300. hr = rtwq_create_async_result(nullptr, &restart, nullptr,
  301. &restartAsyncResult);
  302. if (FAILED(hr)) {
  303. enumerator->UnregisterEndpointNotificationCallback(
  304. notify);
  305. throw HRError("Could not create restartAsyncResult",
  306. hr);
  307. }
  308. DWORD taskId = 0;
  309. DWORD id = 0;
  310. hr = rtwq_lock_shared_work_queue(L"Capture", 0, &taskId, &id);
  311. if (FAILED(hr)) {
  312. enumerator->UnregisterEndpointNotificationCallback(
  313. notify);
  314. throw HRError("RtwqLockSharedWorkQueue failed", hr);
  315. }
  316. startCapture.SetQueueId(id);
  317. sampleReady.SetQueueId(id);
  318. restart.SetQueueId(id);
  319. } else {
  320. captureThread = CreateThread(nullptr, 0,
  321. WASAPISource::CaptureThread, this,
  322. 0, nullptr);
  323. if (!captureThread.Valid()) {
  324. enumerator->UnregisterEndpointNotificationCallback(
  325. notify);
  326. throw "Failed to create capture thread";
  327. }
  328. }
  329. Start();
  330. }
  331. void WASAPISource::Start()
  332. {
  333. if (rtwq_supported) {
  334. rtwq_put_work_item(startCapture.GetQueueId(), 0,
  335. startCaptureAsyncResult);
  336. } else {
  337. SetEvent(initSignal);
  338. }
  339. }
  340. void WASAPISource::Stop()
  341. {
  342. SetEvent(stopSignal);
  343. blog(LOG_INFO, "WASAPI: Device '%s' Terminated", device_name.c_str());
  344. if (rtwq_supported)
  345. SetEvent(receiveSignal);
  346. WaitForSingleObject(idleSignal, INFINITE);
  347. SetEvent(exitSignal);
  348. WaitForSingleObject(reconnectThread, INFINITE);
  349. if (rtwq_supported)
  350. rtwq_unlock_work_queue(sampleReady.GetQueueId());
  351. else
  352. WaitForSingleObject(captureThread, INFINITE);
  353. }
  354. WASAPISource::~WASAPISource()
  355. {
  356. enumerator->UnregisterEndpointNotificationCallback(notify);
  357. Stop();
  358. }
  359. void WASAPISource::UpdateSettings(obs_data_t *settings)
  360. {
  361. device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
  362. useDeviceTiming = obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
  363. isDefaultDevice = _strcmpi(device_id.c_str(), "default") == 0;
  364. }
  365. void WASAPISource::Update(obs_data_t *settings)
  366. {
  367. const string newDevice = obs_data_get_string(settings, OPT_DEVICE_ID);
  368. const bool restart = newDevice.compare(device_id) != 0;
  369. UpdateSettings(settings);
  370. if (restart)
  371. SetEvent(restartSignal);
  372. }
  373. ComPtr<IMMDevice> WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator,
  374. bool isDefaultDevice,
  375. bool isInputDevice,
  376. const string device_id,
  377. wstring &default_id)
  378. {
  379. ComPtr<IMMDevice> device;
  380. if (isDefaultDevice) {
  381. HRESULT res = enumerator->GetDefaultAudioEndpoint(
  382. isInputDevice ? eCapture : eRender,
  383. isInputDevice ? eCommunications : eConsole,
  384. device.Assign());
  385. if (FAILED(res))
  386. throw HRError("Failed GetDefaultAudioEndpoint", res);
  387. CoTaskMemPtr<wchar_t> id;
  388. res = device->GetId(&id);
  389. if (FAILED(res))
  390. throw HRError("Failed to get default id", res);
  391. default_id = id;
  392. } else {
  393. wchar_t *w_id;
  394. os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
  395. if (!w_id)
  396. throw "Failed to widen device id string";
  397. const HRESULT res =
  398. enumerator->GetDevice(w_id, device.Assign());
  399. bfree(w_id);
  400. if (FAILED(res))
  401. throw HRError("Failed to enumerate device", res);
  402. }
  403. return device;
  404. }
  405. #define BUFFER_TIME_100NS (5 * 10000000)
  406. ComPtr<IAudioClient> WASAPISource::InitClient(IMMDevice *device,
  407. bool isInputDevice,
  408. enum speaker_layout &speakers,
  409. enum audio_format &format,
  410. uint32_t &sampleRate)
  411. {
  412. ComPtr<IAudioClient> client;
  413. HRESULT res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
  414. nullptr, (void **)client.Assign());
  415. if (FAILED(res))
  416. throw HRError("Failed to activate client context", res);
  417. CoTaskMemPtr<WAVEFORMATEX> wfex;
  418. res = client->GetMixFormat(&wfex);
  419. if (FAILED(res))
  420. throw HRError("Failed to get mix format", res);
  421. InitFormat(wfex, speakers, format, sampleRate);
  422. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  423. if (!isInputDevice)
  424. flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
  425. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags,
  426. BUFFER_TIME_100NS, 0, wfex, nullptr);
  427. if (FAILED(res))
  428. throw HRError("Failed to initialize audio client", res);
  429. return client;
  430. }
  431. void WASAPISource::ClearBuffer(IMMDevice *device)
  432. {
  433. CoTaskMemPtr<WAVEFORMATEX> wfex;
  434. HRESULT res;
  435. LPBYTE buffer;
  436. UINT32 frames;
  437. ComPtr<IAudioClient> client;
  438. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
  439. (void **)client.Assign());
  440. if (FAILED(res))
  441. throw HRError("Failed to activate client context", res);
  442. res = client->GetMixFormat(&wfex);
  443. if (FAILED(res))
  444. throw HRError("Failed to get mix format", res);
  445. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS,
  446. 0, wfex, nullptr);
  447. if (FAILED(res))
  448. throw HRError("Failed to initialize audio client", res);
  449. /* Silent loopback fix. Prevents audio stream from stopping and */
  450. /* messing up timestamps and other weird glitches during silence */
  451. /* by playing a silent sample all over again. */
  452. res = client->GetBufferSize(&frames);
  453. if (FAILED(res))
  454. throw HRError("Failed to get buffer size", res);
  455. ComPtr<IAudioRenderClient> render;
  456. res = client->GetService(IID_PPV_ARGS(render.Assign()));
  457. if (FAILED(res))
  458. throw HRError("Failed to get render client", res);
  459. res = render->GetBuffer(frames, &buffer);
  460. if (FAILED(res))
  461. throw HRError("Failed to get buffer", res);
  462. memset(buffer, 0, (size_t)frames * (size_t)wfex->nBlockAlign);
  463. render->ReleaseBuffer(frames, 0);
  464. }
  465. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  466. {
  467. switch (layout) {
  468. case KSAUDIO_SPEAKER_2POINT1:
  469. return SPEAKERS_2POINT1;
  470. case KSAUDIO_SPEAKER_SURROUND:
  471. return SPEAKERS_4POINT0;
  472. case OBS_KSAUDIO_SPEAKER_4POINT1:
  473. return SPEAKERS_4POINT1;
  474. case KSAUDIO_SPEAKER_5POINT1_SURROUND:
  475. return SPEAKERS_5POINT1;
  476. case KSAUDIO_SPEAKER_7POINT1_SURROUND:
  477. return SPEAKERS_7POINT1;
  478. }
  479. return (speaker_layout)channels;
  480. }
  481. void WASAPISource::InitFormat(const WAVEFORMATEX *wfex,
  482. enum speaker_layout &speakers,
  483. enum audio_format &format, uint32_t &sampleRate)
  484. {
  485. DWORD layout = 0;
  486. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  487. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex;
  488. layout = ext->dwChannelMask;
  489. }
  490. /* WASAPI is always float */
  491. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  492. format = AUDIO_FORMAT_FLOAT;
  493. sampleRate = wfex->nSamplesPerSec;
  494. }
  495. ComPtr<IAudioCaptureClient> WASAPISource::InitCapture(IAudioClient *client,
  496. HANDLE receiveSignal)
  497. {
  498. ComPtr<IAudioCaptureClient> capture;
  499. HRESULT res = client->GetService(IID_PPV_ARGS(capture.Assign()));
  500. if (FAILED(res))
  501. throw HRError("Failed to create capture context", res);
  502. res = client->SetEventHandle(receiveSignal);
  503. if (FAILED(res))
  504. throw HRError("Failed to set event handle", res);
  505. res = client->Start();
  506. if (FAILED(res))
  507. throw HRError("Failed to start capture client", res);
  508. return capture;
  509. }
  510. void WASAPISource::Initialize()
  511. {
  512. ComPtr<IMMDevice> device = InitDevice(enumerator, isDefaultDevice,
  513. isInputDevice, device_id,
  514. default_id);
  515. device_name = GetDeviceName(device);
  516. ResetEvent(receiveSignal);
  517. ComPtr<IAudioClient> temp_client =
  518. InitClient(device, isInputDevice, speakers, format, sampleRate);
  519. if (!isInputDevice)
  520. ClearBuffer(device);
  521. ComPtr<IAudioCaptureClient> temp_capture =
  522. InitCapture(temp_client, receiveSignal);
  523. client = std::move(temp_client);
  524. capture = std::move(temp_capture);
  525. if (rtwq_supported) {
  526. HRESULT hr = rtwq_put_waiting_work_item(
  527. receiveSignal, 0, sampleReadyAsyncResult, nullptr);
  528. if (FAILED(hr)) {
  529. capture.Clear();
  530. client.Clear();
  531. throw HRError("RtwqPutWaitingWorkItem failed", hr);
  532. }
  533. hr = rtwq_put_waiting_work_item(restartSignal, 0,
  534. restartAsyncResult, nullptr);
  535. if (FAILED(hr)) {
  536. capture.Clear();
  537. client.Clear();
  538. throw HRError("RtwqPutWaitingWorkItem failed", hr);
  539. }
  540. }
  541. blog(LOG_INFO, "WASAPI: Device '%s' [%" PRIu32 " Hz] initialized",
  542. device_name.c_str(), sampleRate);
  543. }
  544. bool WASAPISource::TryInitialize()
  545. {
  546. bool success = false;
  547. try {
  548. Initialize();
  549. success = true;
  550. } catch (HRError &error) {
  551. if (!previouslyFailed) {
  552. blog(LOG_WARNING,
  553. "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  554. device_name.empty() ? device_id.c_str()
  555. : device_name.c_str(),
  556. error.str, error.hr);
  557. }
  558. } catch (const char *error) {
  559. if (!previouslyFailed) {
  560. blog(LOG_WARNING,
  561. "[WASAPISource::TryInitialize]:[%s] %s",
  562. device_name.empty() ? device_id.c_str()
  563. : device_name.c_str(),
  564. error);
  565. }
  566. }
  567. previouslyFailed = !success;
  568. return success;
  569. }
  570. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  571. {
  572. os_set_thread_name("win-wasapi: reconnect thread");
  573. WASAPISource *source = (WASAPISource *)param;
  574. const HANDLE sigs[] = {
  575. source->exitSignal,
  576. source->reconnectSignal,
  577. };
  578. bool exit = false;
  579. while (!exit) {
  580. const DWORD ret = WaitForMultipleObjects(_countof(sigs), sigs,
  581. false, INFINITE);
  582. switch (ret) {
  583. case WAIT_OBJECT_0:
  584. exit = true;
  585. break;
  586. default:
  587. assert(ret == (WAIT_OBJECT_0 + 1));
  588. if (source->reconnectDuration > 0) {
  589. WaitForSingleObject(source->stopSignal,
  590. source->reconnectDuration);
  591. }
  592. source->Start();
  593. }
  594. }
  595. return 0;
  596. }
  597. bool WASAPISource::ProcessCaptureData()
  598. {
  599. HRESULT res;
  600. LPBYTE buffer;
  601. UINT32 frames;
  602. DWORD flags;
  603. UINT64 pos, ts;
  604. UINT captureSize = 0;
  605. while (true) {
  606. res = capture->GetNextPacketSize(&captureSize);
  607. if (FAILED(res)) {
  608. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  609. blog(LOG_WARNING,
  610. "[WASAPISource::ProcessCaptureData]"
  611. " capture->GetNextPacketSize"
  612. " failed: %lX",
  613. res);
  614. return false;
  615. }
  616. if (!captureSize)
  617. break;
  618. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  619. if (FAILED(res)) {
  620. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  621. blog(LOG_WARNING,
  622. "[WASAPISource::ProcessCaptureData]"
  623. " capture->GetBuffer"
  624. " failed: %lX",
  625. res);
  626. return false;
  627. }
  628. obs_source_audio data = {};
  629. data.data[0] = (const uint8_t *)buffer;
  630. data.frames = (uint32_t)frames;
  631. data.speakers = speakers;
  632. data.samples_per_sec = sampleRate;
  633. data.format = format;
  634. data.timestamp = useDeviceTiming ? ts * 100 : os_gettime_ns();
  635. if (!useDeviceTiming)
  636. data.timestamp -= util_mul_div64(frames, 1000000000ULL,
  637. sampleRate);
  638. obs_source_output_audio(source, &data);
  639. capture->ReleaseBuffer(frames);
  640. }
  641. return true;
  642. }
  643. #define RECONNECT_INTERVAL 3000
  644. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  645. {
  646. os_set_thread_name("win-wasapi: capture thread");
  647. const HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  648. const bool com_initialized = SUCCEEDED(hr);
  649. if (!com_initialized) {
  650. blog(LOG_ERROR,
  651. "[WASAPISource::CaptureThread]"
  652. " CoInitializeEx failed: 0x%08X",
  653. hr);
  654. }
  655. DWORD unused = 0;
  656. const HANDLE handle = AvSetMmThreadCharacteristics(L"Audio", &unused);
  657. WASAPISource *source = (WASAPISource *)param;
  658. const HANDLE inactive_sigs[] = {
  659. source->exitSignal,
  660. source->stopSignal,
  661. source->initSignal,
  662. };
  663. const HANDLE active_sigs[] = {
  664. source->exitSignal,
  665. source->stopSignal,
  666. source->receiveSignal,
  667. source->restartSignal,
  668. };
  669. DWORD sig_count = _countof(inactive_sigs);
  670. const HANDLE *sigs = inactive_sigs;
  671. bool exit = false;
  672. while (!exit) {
  673. bool idle = false;
  674. bool stop = false;
  675. bool reconnect = false;
  676. do {
  677. /* Windows 7 does not seem to wake up for LOOPBACK */
  678. const DWORD dwMilliseconds = ((sigs == active_sigs) &&
  679. !source->isInputDevice)
  680. ? 10
  681. : INFINITE;
  682. const DWORD ret = WaitForMultipleObjects(
  683. sig_count, sigs, false, dwMilliseconds);
  684. switch (ret) {
  685. case WAIT_OBJECT_0: {
  686. exit = true;
  687. stop = true;
  688. idle = true;
  689. break;
  690. }
  691. case WAIT_OBJECT_0 + 1:
  692. stop = true;
  693. idle = true;
  694. break;
  695. case WAIT_OBJECT_0 + 2:
  696. case WAIT_TIMEOUT:
  697. if (sigs == inactive_sigs) {
  698. assert(ret != WAIT_TIMEOUT);
  699. if (source->TryInitialize()) {
  700. sig_count =
  701. _countof(active_sigs);
  702. sigs = active_sigs;
  703. } else {
  704. blog(LOG_INFO,
  705. "WASAPI: Device '%s' failed to start",
  706. source->device_id.c_str());
  707. stop = true;
  708. reconnect = true;
  709. source->reconnectDuration =
  710. RECONNECT_INTERVAL;
  711. }
  712. } else {
  713. stop = !source->ProcessCaptureData();
  714. if (stop) {
  715. blog(LOG_INFO,
  716. "Device '%s' invalidated. Retrying",
  717. source->device_name
  718. .c_str());
  719. stop = true;
  720. reconnect = true;
  721. source->reconnectDuration =
  722. RECONNECT_INTERVAL;
  723. }
  724. }
  725. break;
  726. default:
  727. assert(sigs == active_sigs);
  728. assert(ret == WAIT_OBJECT_0 + 3);
  729. stop = true;
  730. reconnect = true;
  731. source->reconnectDuration = 0;
  732. ResetEvent(source->restartSignal);
  733. }
  734. } while (!stop);
  735. sig_count = _countof(inactive_sigs);
  736. sigs = inactive_sigs;
  737. if (source->client) {
  738. source->client->Stop();
  739. source->capture.Clear();
  740. source->client.Clear();
  741. }
  742. if (idle) {
  743. SetEvent(source->idleSignal);
  744. } else if (reconnect) {
  745. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  746. source->device_name.c_str());
  747. SetEvent(source->reconnectSignal);
  748. }
  749. }
  750. if (handle)
  751. AvRevertMmThreadCharacteristics(handle);
  752. if (com_initialized)
  753. CoUninitialize();
  754. return 0;
  755. }
  756. void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id)
  757. {
  758. if (!isDefaultDevice)
  759. return;
  760. EDataFlow expectedFlow = isInputDevice ? eCapture : eRender;
  761. ERole expectedRole = isInputDevice ? eCommunications : eConsole;
  762. if (flow != expectedFlow || role != expectedRole)
  763. return;
  764. if (id && default_id.compare(id) == 0)
  765. return;
  766. blog(LOG_INFO, "WASAPI: Default %s device changed",
  767. isInputDevice ? "input" : "output");
  768. /* reset device only once every 300ms */
  769. uint64_t t = os_gettime_ns();
  770. if (t - lastNotifyTime < 300000000)
  771. return;
  772. lastNotifyTime = t;
  773. SetEvent(restartSignal);
  774. }
  775. void WASAPISource::OnStartCapture()
  776. {
  777. const DWORD ret = WaitForSingleObject(stopSignal, 0);
  778. switch (ret) {
  779. case WAIT_OBJECT_0:
  780. SetEvent(idleSignal);
  781. break;
  782. default:
  783. assert(ret == WAIT_TIMEOUT);
  784. if (!TryInitialize()) {
  785. blog(LOG_INFO, "WASAPI: Device '%s' failed to start",
  786. device_id.c_str());
  787. reconnectDuration = RECONNECT_INTERVAL;
  788. SetEvent(reconnectSignal);
  789. }
  790. }
  791. }
  792. void WASAPISource::OnSampleReady()
  793. {
  794. bool stop = false;
  795. bool reconnect = false;
  796. if (!ProcessCaptureData()) {
  797. stop = true;
  798. reconnect = true;
  799. reconnectDuration = RECONNECT_INTERVAL;
  800. }
  801. if (WaitForSingleObject(restartSignal, 0) == WAIT_OBJECT_0) {
  802. stop = true;
  803. reconnect = true;
  804. reconnectDuration = 0;
  805. ResetEvent(restartSignal);
  806. rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult,
  807. nullptr);
  808. }
  809. if (WaitForSingleObject(stopSignal, 0) == WAIT_OBJECT_0) {
  810. stop = true;
  811. reconnect = false;
  812. }
  813. if (!stop) {
  814. if (FAILED(rtwq_put_waiting_work_item(receiveSignal, 0,
  815. sampleReadyAsyncResult,
  816. nullptr))) {
  817. blog(LOG_ERROR,
  818. "Could not requeue sample receive work");
  819. stop = true;
  820. reconnect = true;
  821. reconnectDuration = RECONNECT_INTERVAL;
  822. }
  823. }
  824. if (stop) {
  825. client->Stop();
  826. capture.Clear();
  827. client.Clear();
  828. if (reconnect) {
  829. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  830. device_name.c_str());
  831. SetEvent(reconnectSignal);
  832. } else {
  833. SetEvent(idleSignal);
  834. }
  835. }
  836. }
  837. void WASAPISource::OnRestart()
  838. {
  839. SetEvent(receiveSignal);
  840. }
  841. /* ------------------------------------------------------------------------- */
  842. static const char *GetWASAPIInputName(void *)
  843. {
  844. return obs_module_text("AudioInput");
  845. }
  846. static const char *GetWASAPIOutputName(void *)
  847. {
  848. return obs_module_text("AudioOutput");
  849. }
  850. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  851. {
  852. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  853. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  854. }
  855. static void GetWASAPIDefaultsOutput(obs_data_t *settings)
  856. {
  857. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  858. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  859. }
  860. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  861. bool input)
  862. {
  863. try {
  864. return new WASAPISource(settings, source, input);
  865. } catch (const char *error) {
  866. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  867. }
  868. return nullptr;
  869. }
  870. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  871. {
  872. return CreateWASAPISource(settings, source, true);
  873. }
  874. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  875. {
  876. return CreateWASAPISource(settings, source, false);
  877. }
  878. static void DestroyWASAPISource(void *obj)
  879. {
  880. delete static_cast<WASAPISource *>(obj);
  881. }
  882. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  883. {
  884. static_cast<WASAPISource *>(obj)->Update(settings);
  885. }
  886. static obs_properties_t *GetWASAPIProperties(bool input)
  887. {
  888. obs_properties_t *props = obs_properties_create();
  889. vector<AudioDeviceInfo> devices;
  890. obs_property_t *device_prop = obs_properties_add_list(
  891. props, OPT_DEVICE_ID, obs_module_text("Device"),
  892. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  893. GetWASAPIAudioDevices(devices, input);
  894. if (devices.size())
  895. obs_property_list_add_string(
  896. device_prop, obs_module_text("Default"), "default");
  897. for (size_t i = 0; i < devices.size(); i++) {
  898. AudioDeviceInfo &device = devices[i];
  899. obs_property_list_add_string(device_prop, device.name.c_str(),
  900. device.id.c_str());
  901. }
  902. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  903. obs_module_text("UseDeviceTiming"));
  904. return props;
  905. }
  906. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  907. {
  908. return GetWASAPIProperties(true);
  909. }
  910. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  911. {
  912. return GetWASAPIProperties(false);
  913. }
  914. void RegisterWASAPIInput()
  915. {
  916. obs_source_info info = {};
  917. info.id = "wasapi_input_capture";
  918. info.type = OBS_SOURCE_TYPE_INPUT;
  919. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  920. info.get_name = GetWASAPIInputName;
  921. info.create = CreateWASAPIInput;
  922. info.destroy = DestroyWASAPISource;
  923. info.update = UpdateWASAPISource;
  924. info.get_defaults = GetWASAPIDefaultsInput;
  925. info.get_properties = GetWASAPIPropertiesInput;
  926. info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
  927. obs_register_source(&info);
  928. }
  929. void RegisterWASAPIOutput()
  930. {
  931. obs_source_info info = {};
  932. info.id = "wasapi_output_capture";
  933. info.type = OBS_SOURCE_TYPE_INPUT;
  934. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  935. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  936. info.get_name = GetWASAPIOutputName;
  937. info.create = CreateWASAPIOutput;
  938. info.destroy = DestroyWASAPISource;
  939. info.update = UpdateWASAPISource;
  940. info.get_defaults = GetWASAPIDefaultsOutput;
  941. info.get_properties = GetWASAPIPropertiesOutput;
  942. info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
  943. obs_register_source(&info);
  944. }