win-wasapi.cpp 14 KB

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