win-wasapi.cpp 28 KB

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