win-wasapi.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. using namespace std;
  12. #define OPT_DEVICE_ID "device_id"
  13. #define OPT_USE_DEVICE_TIMING "use_device_timing"
  14. static void GetWASAPIDefaults(obs_data_t *settings);
  15. #define OBS_KSAUDIO_SPEAKER_4POINT1 \
  16. (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY)
  17. class WASAPISource {
  18. ComPtr<IMMDevice> device;
  19. ComPtr<IAudioClient> client;
  20. ComPtr<IAudioCaptureClient> capture;
  21. ComPtr<IAudioRenderClient> render;
  22. obs_source_t *source;
  23. string device_id;
  24. string device_name;
  25. string device_sample = "-";
  26. bool isInputDevice;
  27. bool useDeviceTiming = false;
  28. bool isDefaultDevice = false;
  29. bool reconnecting = false;
  30. bool previouslyFailed = false;
  31. WinHandle reconnectThread;
  32. bool active = false;
  33. WinHandle captureThread;
  34. WinHandle stopSignal;
  35. WinHandle receiveSignal;
  36. speaker_layout speakers;
  37. audio_format format;
  38. uint32_t sampleRate;
  39. static DWORD WINAPI ReconnectThread(LPVOID param);
  40. static DWORD WINAPI CaptureThread(LPVOID param);
  41. bool ProcessCaptureData();
  42. inline void Start();
  43. inline void Stop();
  44. void Reconnect();
  45. bool InitDevice(IMMDeviceEnumerator *enumerator);
  46. void InitName();
  47. void InitClient();
  48. void InitRender();
  49. void InitFormat(WAVEFORMATEX *wfex);
  50. void InitCapture();
  51. void Initialize();
  52. bool TryInitialize();
  53. void UpdateSettings(obs_data_t *settings);
  54. public:
  55. WASAPISource(obs_data_t *settings, obs_source_t *source_, bool input);
  56. inline ~WASAPISource();
  57. void Update(obs_data_t *settings);
  58. };
  59. WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
  60. bool input)
  61. : source(source_), isInputDevice(input)
  62. {
  63. UpdateSettings(settings);
  64. stopSignal = CreateEvent(nullptr, true, false, nullptr);
  65. if (!stopSignal.Valid())
  66. throw "Could not create stop signal";
  67. receiveSignal = CreateEvent(nullptr, false, false, nullptr);
  68. if (!receiveSignal.Valid())
  69. throw "Could not create receive signal";
  70. Start();
  71. }
  72. inline void WASAPISource::Start()
  73. {
  74. if (!TryInitialize()) {
  75. blog(LOG_INFO,
  76. "[WASAPISource::WASAPISource] "
  77. "Device '%s' not found. Waiting for device",
  78. device_id.c_str());
  79. Reconnect();
  80. }
  81. }
  82. inline void WASAPISource::Stop()
  83. {
  84. SetEvent(stopSignal);
  85. if (active) {
  86. blog(LOG_INFO, "WASAPI: Device '%s' Terminated",
  87. device_name.c_str());
  88. WaitForSingleObject(captureThread, INFINITE);
  89. }
  90. if (reconnecting)
  91. WaitForSingleObject(reconnectThread, INFINITE);
  92. ResetEvent(stopSignal);
  93. }
  94. inline WASAPISource::~WASAPISource()
  95. {
  96. Stop();
  97. }
  98. void WASAPISource::UpdateSettings(obs_data_t *settings)
  99. {
  100. device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
  101. useDeviceTiming = obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
  102. isDefaultDevice = _strcmpi(device_id.c_str(), "default") == 0;
  103. }
  104. void WASAPISource::Update(obs_data_t *settings)
  105. {
  106. string newDevice = obs_data_get_string(settings, OPT_DEVICE_ID);
  107. bool restart = newDevice.compare(device_id) != 0;
  108. if (restart)
  109. Stop();
  110. UpdateSettings(settings);
  111. if (restart)
  112. Start();
  113. }
  114. bool WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator)
  115. {
  116. HRESULT res;
  117. if (isDefaultDevice) {
  118. res = enumerator->GetDefaultAudioEndpoint(
  119. isInputDevice ? eCapture : eRender,
  120. isInputDevice ? eCommunications : eConsole,
  121. device.Assign());
  122. } else {
  123. wchar_t *w_id;
  124. os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
  125. res = enumerator->GetDevice(w_id, device.Assign());
  126. bfree(w_id);
  127. }
  128. return SUCCEEDED(res);
  129. }
  130. #define BUFFER_TIME_100NS (5 * 10000000)
  131. void WASAPISource::InitClient()
  132. {
  133. CoTaskMemPtr<WAVEFORMATEX> wfex;
  134. HRESULT res;
  135. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  136. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
  137. (void **)client.Assign());
  138. if (FAILED(res))
  139. throw HRError("Failed to activate client context", res);
  140. res = client->GetMixFormat(&wfex);
  141. if (FAILED(res))
  142. throw HRError("Failed to get mix format", res);
  143. InitFormat(wfex);
  144. if (!isInputDevice)
  145. flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
  146. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags,
  147. BUFFER_TIME_100NS, 0, wfex, nullptr);
  148. if (FAILED(res))
  149. throw HRError("Failed to get initialize audio client", res);
  150. }
  151. void WASAPISource::InitRender()
  152. {
  153. CoTaskMemPtr<WAVEFORMATEX> wfex;
  154. HRESULT res;
  155. LPBYTE buffer;
  156. UINT32 frames;
  157. ComPtr<IAudioClient> client;
  158. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
  159. (void **)client.Assign());
  160. if (FAILED(res))
  161. throw HRError("Failed to activate client context", res);
  162. res = client->GetMixFormat(&wfex);
  163. if (FAILED(res))
  164. throw HRError("Failed to get mix format", res);
  165. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS,
  166. 0, wfex, nullptr);
  167. if (FAILED(res))
  168. throw HRError("Failed to get initialize audio client", res);
  169. /* Silent loopback fix. Prevents audio stream from stopping and */
  170. /* messing up timestamps and other weird glitches during silence */
  171. /* by playing a silent sample all over again. */
  172. res = client->GetBufferSize(&frames);
  173. if (FAILED(res))
  174. throw HRError("Failed to get buffer size", res);
  175. res = client->GetService(__uuidof(IAudioRenderClient),
  176. (void **)render.Assign());
  177. if (FAILED(res))
  178. throw HRError("Failed to get render client", res);
  179. res = render->GetBuffer(frames, &buffer);
  180. if (FAILED(res))
  181. throw HRError("Failed to get buffer", res);
  182. memset(buffer, 0, frames * wfex->nBlockAlign);
  183. render->ReleaseBuffer(frames, 0);
  184. }
  185. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  186. {
  187. switch (layout) {
  188. case KSAUDIO_SPEAKER_2POINT1:
  189. return SPEAKERS_2POINT1;
  190. case KSAUDIO_SPEAKER_SURROUND:
  191. return SPEAKERS_4POINT0;
  192. case OBS_KSAUDIO_SPEAKER_4POINT1:
  193. return SPEAKERS_4POINT1;
  194. case KSAUDIO_SPEAKER_5POINT1_SURROUND:
  195. return SPEAKERS_5POINT1;
  196. case KSAUDIO_SPEAKER_7POINT1_SURROUND:
  197. return SPEAKERS_7POINT1;
  198. }
  199. return (speaker_layout)channels;
  200. }
  201. void WASAPISource::InitFormat(WAVEFORMATEX *wfex)
  202. {
  203. DWORD layout = 0;
  204. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  205. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex;
  206. layout = ext->dwChannelMask;
  207. }
  208. /* WASAPI is always float */
  209. sampleRate = wfex->nSamplesPerSec;
  210. format = AUDIO_FORMAT_FLOAT;
  211. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  212. }
  213. void WASAPISource::InitCapture()
  214. {
  215. HRESULT res = client->GetService(__uuidof(IAudioCaptureClient),
  216. (void **)capture.Assign());
  217. if (FAILED(res))
  218. throw HRError("Failed to create capture context", res);
  219. res = client->SetEventHandle(receiveSignal);
  220. if (FAILED(res))
  221. throw HRError("Failed to set event handle", res);
  222. captureThread = CreateThread(nullptr, 0, WASAPISource::CaptureThread,
  223. this, 0, nullptr);
  224. if (!captureThread.Valid())
  225. throw "Failed to create capture thread";
  226. client->Start();
  227. active = true;
  228. blog(LOG_INFO, "WASAPI: Device '%s' [%s Hz] initialized",
  229. device_name.c_str(), device_sample.c_str());
  230. }
  231. void WASAPISource::Initialize()
  232. {
  233. ComPtr<IMMDeviceEnumerator> enumerator;
  234. HRESULT res;
  235. res = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
  236. CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
  237. (void **)enumerator.Assign());
  238. if (FAILED(res))
  239. throw HRError("Failed to create enumerator", res);
  240. if (!InitDevice(enumerator))
  241. return;
  242. device_name = GetDeviceName(device);
  243. HRESULT resSample;
  244. IPropertyStore *store = nullptr;
  245. PWAVEFORMATEX deviceFormatProperties;
  246. PROPVARIANT prop;
  247. resSample = device->OpenPropertyStore(STGM_READ, &store);
  248. if (!FAILED(resSample)) {
  249. resSample =
  250. store->GetValue(PKEY_AudioEngine_DeviceFormat, &prop);
  251. if (!FAILED(resSample)) {
  252. if (prop.vt != VT_EMPTY && prop.blob.pBlobData) {
  253. deviceFormatProperties =
  254. (PWAVEFORMATEX)prop.blob.pBlobData;
  255. device_sample = std::to_string(
  256. deviceFormatProperties->nSamplesPerSec);
  257. }
  258. }
  259. store->Release();
  260. }
  261. InitClient();
  262. if (!isInputDevice)
  263. InitRender();
  264. InitCapture();
  265. }
  266. bool WASAPISource::TryInitialize()
  267. {
  268. try {
  269. Initialize();
  270. } catch (HRError &error) {
  271. if (previouslyFailed)
  272. return active;
  273. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  274. device_name.empty() ? device_id.c_str()
  275. : device_name.c_str(),
  276. error.str, error.hr);
  277. } catch (const char *error) {
  278. if (previouslyFailed)
  279. return active;
  280. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  281. device_name.empty() ? device_id.c_str()
  282. : device_name.c_str(),
  283. error);
  284. }
  285. previouslyFailed = !active;
  286. return active;
  287. }
  288. void WASAPISource::Reconnect()
  289. {
  290. reconnecting = true;
  291. reconnectThread = CreateThread(
  292. nullptr, 0, WASAPISource::ReconnectThread, this, 0, nullptr);
  293. if (!reconnectThread.Valid())
  294. blog(LOG_WARNING,
  295. "[WASAPISource::Reconnect] "
  296. "Failed to initialize reconnect thread: %lu",
  297. GetLastError());
  298. }
  299. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  300. {
  301. return WaitForSingleObject(handle, time) != WAIT_TIMEOUT;
  302. }
  303. #define RECONNECT_INTERVAL 3000
  304. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  305. {
  306. WASAPISource *source = (WASAPISource *)param;
  307. os_set_thread_name("win-wasapi: reconnect thread");
  308. const HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  309. const bool com_initialized = SUCCEEDED(hr);
  310. if (!com_initialized) {
  311. blog(LOG_ERROR,
  312. "[WASAPISource::ReconnectThread]"
  313. " CoInitializeEx failed: 0x%08X",
  314. hr);
  315. }
  316. obs_monitoring_type type =
  317. obs_source_get_monitoring_type(source->source);
  318. obs_source_set_monitoring_type(source->source,
  319. OBS_MONITORING_TYPE_NONE);
  320. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  321. if (source->TryInitialize())
  322. break;
  323. }
  324. obs_source_set_monitoring_type(source->source, type);
  325. if (com_initialized)
  326. CoUninitialize();
  327. source->reconnectThread = nullptr;
  328. source->reconnecting = false;
  329. return 0;
  330. }
  331. bool WASAPISource::ProcessCaptureData()
  332. {
  333. HRESULT res;
  334. LPBYTE buffer;
  335. UINT32 frames;
  336. DWORD flags;
  337. UINT64 pos, ts;
  338. UINT captureSize = 0;
  339. while (true) {
  340. res = capture->GetNextPacketSize(&captureSize);
  341. if (FAILED(res)) {
  342. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  343. blog(LOG_WARNING,
  344. "[WASAPISource::GetCaptureData]"
  345. " capture->GetNextPacketSize"
  346. " failed: %lX",
  347. res);
  348. return false;
  349. }
  350. if (!captureSize)
  351. break;
  352. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  353. if (FAILED(res)) {
  354. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  355. blog(LOG_WARNING,
  356. "[WASAPISource::GetCaptureData]"
  357. " capture->GetBuffer"
  358. " failed: %lX",
  359. res);
  360. return false;
  361. }
  362. obs_source_audio data = {};
  363. data.data[0] = (const uint8_t *)buffer;
  364. data.frames = (uint32_t)frames;
  365. data.speakers = speakers;
  366. data.samples_per_sec = sampleRate;
  367. data.format = format;
  368. data.timestamp = useDeviceTiming ? ts * 100 : os_gettime_ns();
  369. if (!useDeviceTiming)
  370. data.timestamp -= util_mul_div64(frames, 1000000000ULL,
  371. sampleRate);
  372. obs_source_output_audio(source, &data);
  373. capture->ReleaseBuffer(frames);
  374. }
  375. return true;
  376. }
  377. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  378. DWORD duration)
  379. {
  380. DWORD ret;
  381. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  382. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  383. }
  384. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  385. {
  386. WASAPISource *source = (WASAPISource *)param;
  387. bool reconnect = false;
  388. /* Output devices don't signal, so just make it check every 10 ms */
  389. DWORD dur = source->isInputDevice ? RECONNECT_INTERVAL : 10;
  390. HANDLE sigs[2] = {source->receiveSignal, source->stopSignal};
  391. os_set_thread_name("win-wasapi: capture thread");
  392. while (WaitForCaptureSignal(2, sigs, dur)) {
  393. if (!source->ProcessCaptureData()) {
  394. reconnect = true;
  395. break;
  396. }
  397. }
  398. source->client->Stop();
  399. source->captureThread = nullptr;
  400. source->active = false;
  401. if (reconnect) {
  402. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  403. source->device_name.c_str());
  404. source->Reconnect();
  405. }
  406. return 0;
  407. }
  408. /* ------------------------------------------------------------------------- */
  409. static const char *GetWASAPIInputName(void *)
  410. {
  411. return obs_module_text("AudioInput");
  412. }
  413. static const char *GetWASAPIOutputName(void *)
  414. {
  415. return obs_module_text("AudioOutput");
  416. }
  417. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  418. {
  419. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  420. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  421. }
  422. static void GetWASAPIDefaultsOutput(obs_data_t *settings)
  423. {
  424. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  425. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  426. }
  427. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  428. bool input)
  429. {
  430. try {
  431. return new WASAPISource(settings, source, input);
  432. } catch (const char *error) {
  433. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  434. }
  435. return nullptr;
  436. }
  437. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  438. {
  439. return CreateWASAPISource(settings, source, true);
  440. }
  441. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  442. {
  443. return CreateWASAPISource(settings, source, false);
  444. }
  445. static void DestroyWASAPISource(void *obj)
  446. {
  447. delete static_cast<WASAPISource *>(obj);
  448. }
  449. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  450. {
  451. static_cast<WASAPISource *>(obj)->Update(settings);
  452. }
  453. static obs_properties_t *GetWASAPIProperties(bool input)
  454. {
  455. obs_properties_t *props = obs_properties_create();
  456. vector<AudioDeviceInfo> devices;
  457. obs_property_t *device_prop = obs_properties_add_list(
  458. props, OPT_DEVICE_ID, obs_module_text("Device"),
  459. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  460. GetWASAPIAudioDevices(devices, input);
  461. if (devices.size())
  462. obs_property_list_add_string(
  463. device_prop, obs_module_text("Default"), "default");
  464. for (size_t i = 0; i < devices.size(); i++) {
  465. AudioDeviceInfo &device = devices[i];
  466. obs_property_list_add_string(device_prop, device.name.c_str(),
  467. device.id.c_str());
  468. }
  469. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  470. obs_module_text("UseDeviceTiming"));
  471. return props;
  472. }
  473. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  474. {
  475. return GetWASAPIProperties(true);
  476. }
  477. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  478. {
  479. return GetWASAPIProperties(false);
  480. }
  481. void RegisterWASAPIInput()
  482. {
  483. obs_source_info info = {};
  484. info.id = "wasapi_input_capture";
  485. info.type = OBS_SOURCE_TYPE_INPUT;
  486. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  487. info.get_name = GetWASAPIInputName;
  488. info.create = CreateWASAPIInput;
  489. info.destroy = DestroyWASAPISource;
  490. info.update = UpdateWASAPISource;
  491. info.get_defaults = GetWASAPIDefaultsInput;
  492. info.get_properties = GetWASAPIPropertiesInput;
  493. info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
  494. obs_register_source(&info);
  495. }
  496. void RegisterWASAPIOutput()
  497. {
  498. obs_source_info info = {};
  499. info.id = "wasapi_output_capture";
  500. info.type = OBS_SOURCE_TYPE_INPUT;
  501. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  502. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  503. info.get_name = GetWASAPIOutputName;
  504. info.create = CreateWASAPIOutput;
  505. info.destroy = DestroyWASAPISource;
  506. info.update = UpdateWASAPISource;
  507. info.get_defaults = GetWASAPIDefaultsOutput;
  508. info.get_properties = GetWASAPIPropertiesOutput;
  509. info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
  510. obs_register_source(&info);
  511. }