win-wasapi.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. if (prop.vt != VT_EMPTY && prop.blob.pBlobData) {
  252. deviceFormatProperties =
  253. (PWAVEFORMATEX)prop.blob.pBlobData;
  254. device_sample = std::to_string(
  255. deviceFormatProperties->nSamplesPerSec);
  256. }
  257. }
  258. store->Release();
  259. }
  260. InitClient();
  261. if (!isInputDevice)
  262. InitRender();
  263. InitCapture();
  264. }
  265. bool WASAPISource::TryInitialize()
  266. {
  267. try {
  268. Initialize();
  269. } catch (HRError &error) {
  270. if (previouslyFailed)
  271. return active;
  272. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  273. device_name.empty() ? device_id.c_str()
  274. : device_name.c_str(),
  275. error.str, error.hr);
  276. } catch (const char *error) {
  277. if (previouslyFailed)
  278. return active;
  279. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  280. device_name.empty() ? device_id.c_str()
  281. : device_name.c_str(),
  282. error);
  283. }
  284. previouslyFailed = !active;
  285. return active;
  286. }
  287. void WASAPISource::Reconnect()
  288. {
  289. reconnecting = true;
  290. reconnectThread = CreateThread(
  291. nullptr, 0, WASAPISource::ReconnectThread, this, 0, nullptr);
  292. if (!reconnectThread.Valid())
  293. blog(LOG_WARNING,
  294. "[WASAPISource::Reconnect] "
  295. "Failed to initialize reconnect thread: %lu",
  296. GetLastError());
  297. }
  298. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  299. {
  300. return WaitForSingleObject(handle, time) != WAIT_TIMEOUT;
  301. }
  302. #define RECONNECT_INTERVAL 3000
  303. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  304. {
  305. WASAPISource *source = (WASAPISource *)param;
  306. os_set_thread_name("win-wasapi: reconnect thread");
  307. const HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  308. const bool com_initialized = SUCCEEDED(hr);
  309. if (!com_initialized) {
  310. blog(LOG_ERROR,
  311. "[WASAPISource::ReconnectThread]"
  312. " CoInitializeEx failed: 0x%08X",
  313. hr);
  314. }
  315. obs_monitoring_type type =
  316. obs_source_get_monitoring_type(source->source);
  317. obs_source_set_monitoring_type(source->source,
  318. OBS_MONITORING_TYPE_NONE);
  319. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  320. if (source->TryInitialize())
  321. break;
  322. }
  323. obs_source_set_monitoring_type(source->source, type);
  324. if (com_initialized)
  325. CoUninitialize();
  326. source->reconnectThread = nullptr;
  327. source->reconnecting = false;
  328. return 0;
  329. }
  330. bool WASAPISource::ProcessCaptureData()
  331. {
  332. HRESULT res;
  333. LPBYTE buffer;
  334. UINT32 frames;
  335. DWORD flags;
  336. UINT64 pos, ts;
  337. UINT captureSize = 0;
  338. while (true) {
  339. res = capture->GetNextPacketSize(&captureSize);
  340. if (FAILED(res)) {
  341. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  342. blog(LOG_WARNING,
  343. "[WASAPISource::GetCaptureData]"
  344. " capture->GetNextPacketSize"
  345. " failed: %lX",
  346. res);
  347. return false;
  348. }
  349. if (!captureSize)
  350. break;
  351. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  352. if (FAILED(res)) {
  353. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  354. blog(LOG_WARNING,
  355. "[WASAPISource::GetCaptureData]"
  356. " capture->GetBuffer"
  357. " failed: %lX",
  358. res);
  359. return false;
  360. }
  361. obs_source_audio data = {};
  362. data.data[0] = (const uint8_t *)buffer;
  363. data.frames = (uint32_t)frames;
  364. data.speakers = speakers;
  365. data.samples_per_sec = sampleRate;
  366. data.format = format;
  367. data.timestamp = useDeviceTiming ? ts * 100 : os_gettime_ns();
  368. if (!useDeviceTiming)
  369. data.timestamp -= (uint64_t)frames * 1000000000ULL /
  370. (uint64_t)sampleRate;
  371. obs_source_output_audio(source, &data);
  372. capture->ReleaseBuffer(frames);
  373. }
  374. return true;
  375. }
  376. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  377. DWORD duration)
  378. {
  379. DWORD ret;
  380. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  381. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  382. }
  383. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  384. {
  385. WASAPISource *source = (WASAPISource *)param;
  386. bool reconnect = false;
  387. /* Output devices don't signal, so just make it check every 10 ms */
  388. DWORD dur = source->isInputDevice ? RECONNECT_INTERVAL : 10;
  389. HANDLE sigs[2] = {source->receiveSignal, source->stopSignal};
  390. os_set_thread_name("win-wasapi: capture thread");
  391. while (WaitForCaptureSignal(2, sigs, dur)) {
  392. if (!source->ProcessCaptureData()) {
  393. reconnect = true;
  394. break;
  395. }
  396. }
  397. source->client->Stop();
  398. source->captureThread = nullptr;
  399. source->active = false;
  400. if (reconnect) {
  401. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  402. source->device_name.c_str());
  403. source->Reconnect();
  404. }
  405. return 0;
  406. }
  407. /* ------------------------------------------------------------------------- */
  408. static const char *GetWASAPIInputName(void *)
  409. {
  410. return obs_module_text("AudioInput");
  411. }
  412. static const char *GetWASAPIOutputName(void *)
  413. {
  414. return obs_module_text("AudioOutput");
  415. }
  416. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  417. {
  418. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  419. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  420. }
  421. static void GetWASAPIDefaultsOutput(obs_data_t *settings)
  422. {
  423. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  424. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  425. }
  426. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  427. bool input)
  428. {
  429. try {
  430. return new WASAPISource(settings, source, input);
  431. } catch (const char *error) {
  432. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  433. }
  434. return nullptr;
  435. }
  436. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  437. {
  438. return CreateWASAPISource(settings, source, true);
  439. }
  440. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  441. {
  442. return CreateWASAPISource(settings, source, false);
  443. }
  444. static void DestroyWASAPISource(void *obj)
  445. {
  446. delete static_cast<WASAPISource *>(obj);
  447. }
  448. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  449. {
  450. static_cast<WASAPISource *>(obj)->Update(settings);
  451. }
  452. static obs_properties_t *GetWASAPIProperties(bool input)
  453. {
  454. obs_properties_t *props = obs_properties_create();
  455. vector<AudioDeviceInfo> devices;
  456. obs_property_t *device_prop = obs_properties_add_list(
  457. props, OPT_DEVICE_ID, obs_module_text("Device"),
  458. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  459. GetWASAPIAudioDevices(devices, input);
  460. if (devices.size())
  461. obs_property_list_add_string(
  462. device_prop, obs_module_text("Default"), "default");
  463. for (size_t i = 0; i < devices.size(); i++) {
  464. AudioDeviceInfo &device = devices[i];
  465. obs_property_list_add_string(device_prop, device.name.c_str(),
  466. device.id.c_str());
  467. }
  468. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  469. obs_module_text("UseDeviceTiming"));
  470. return props;
  471. }
  472. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  473. {
  474. return GetWASAPIProperties(true);
  475. }
  476. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  477. {
  478. return GetWASAPIProperties(false);
  479. }
  480. void RegisterWASAPIInput()
  481. {
  482. obs_source_info info = {};
  483. info.id = "wasapi_input_capture";
  484. info.type = OBS_SOURCE_TYPE_INPUT;
  485. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  486. info.get_name = GetWASAPIInputName;
  487. info.create = CreateWASAPIInput;
  488. info.destroy = DestroyWASAPISource;
  489. info.update = UpdateWASAPISource;
  490. info.get_defaults = GetWASAPIDefaultsInput;
  491. info.get_properties = GetWASAPIPropertiesInput;
  492. info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
  493. obs_register_source(&info);
  494. }
  495. void RegisterWASAPIOutput()
  496. {
  497. obs_source_info info = {};
  498. info.id = "wasapi_output_capture";
  499. info.type = OBS_SOURCE_TYPE_INPUT;
  500. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  501. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  502. info.get_name = GetWASAPIOutputName;
  503. info.create = CreateWASAPIOutput;
  504. info.destroy = DestroyWASAPISource;
  505. info.update = UpdateWASAPISource;
  506. info.get_defaults = GetWASAPIDefaultsOutput;
  507. info.get_properties = GetWASAPIPropertiesOutput;
  508. info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
  509. obs_register_source(&info);
  510. }