win-wasapi.cpp 15 KB

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