win-wasapi.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. // Fix inconsistent defs of speaker_surround between avutil & wasapi
  15. #define KSAUDIO_SPEAKER_2POINT1 (KSAUDIO_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY)
  16. #define KSAUDIO_SPEAKER_4POINT1 (KSAUDIO_SPEAKER_QUAD|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. 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_),
  61. 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, "[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,
  136. nullptr, (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(
  146. 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,
  159. nullptr, (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(
  166. AUDCLNT_SHAREMODE_SHARED, 0,
  167. BUFFER_TIME_100NS, 0, wfex, nullptr);
  168. if (FAILED(res))
  169. throw HRError("Failed to get initialize audio client", res);
  170. /* Silent loopback fix. Prevents audio stream from stopping and */
  171. /* messing up timestamps and other weird glitches during silence */
  172. /* by playing a silent sample all over again. */
  173. res = client->GetBufferSize(&frames);
  174. if (FAILED(res))
  175. throw HRError("Failed to get buffer size", res);
  176. res = client->GetService(__uuidof(IAudioRenderClient),
  177. (void**)render.Assign());
  178. if (FAILED(res))
  179. throw HRError("Failed to get render client", res);
  180. res = render->GetBuffer(frames, &buffer);
  181. if (FAILED(res))
  182. throw HRError("Failed to get buffer", res);
  183. memset(buffer, 0, frames*wfex->nBlockAlign);
  184. render->ReleaseBuffer(frames, 0);
  185. }
  186. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  187. {
  188. switch (layout) {
  189. case KSAUDIO_SPEAKER_2POINT1: return SPEAKERS_2POINT1;
  190. case KSAUDIO_SPEAKER_SURROUND: return SPEAKERS_4POINT0;
  191. case KSAUDIO_SPEAKER_4POINT1: return SPEAKERS_4POINT1;
  192. case KSAUDIO_SPEAKER_5POINT1_SURROUND: return SPEAKERS_5POINT1;
  193. case KSAUDIO_SPEAKER_7POINT1_SURROUND: return SPEAKERS_7POINT1;
  194. }
  195. return (speaker_layout)channels;
  196. }
  197. void WASAPISource::InitFormat(WAVEFORMATEX *wfex)
  198. {
  199. DWORD layout = 0;
  200. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  201. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)wfex;
  202. layout = ext->dwChannelMask;
  203. }
  204. /* WASAPI is always float */
  205. sampleRate = wfex->nSamplesPerSec;
  206. format = AUDIO_FORMAT_FLOAT;
  207. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  208. }
  209. void WASAPISource::InitCapture()
  210. {
  211. HRESULT res = client->GetService(__uuidof(IAudioCaptureClient),
  212. (void**)capture.Assign());
  213. if (FAILED(res))
  214. throw HRError("Failed to create capture context", res);
  215. res = client->SetEventHandle(receiveSignal);
  216. if (FAILED(res))
  217. throw HRError("Failed to set event handle", res);
  218. captureThread = CreateThread(nullptr, 0,
  219. WASAPISource::CaptureThread, this,
  220. 0, nullptr);
  221. if (!captureThread.Valid())
  222. throw "Failed to create capture thread";
  223. client->Start();
  224. active = true;
  225. blog(LOG_INFO, "WASAPI: Device '%s' initialized", device_name.c_str());
  226. }
  227. void WASAPISource::Initialize()
  228. {
  229. ComPtr<IMMDeviceEnumerator> enumerator;
  230. HRESULT res;
  231. res = CoCreateInstance(__uuidof(MMDeviceEnumerator),
  232. nullptr, CLSCTX_ALL,
  233. __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) InitRender();
  242. InitCapture();
  243. }
  244. bool WASAPISource::TryInitialize()
  245. {
  246. try {
  247. Initialize();
  248. } catch (HRError error) {
  249. if (previouslyFailed)
  250. return active;
  251. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  252. device_name.empty() ?
  253. device_id.c_str() : device_name.c_str(),
  254. error.str, error.hr);
  255. } catch (const char *error) {
  256. if (previouslyFailed)
  257. return active;
  258. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  259. device_name.empty() ?
  260. device_id.c_str() : device_name.c_str(),
  261. error);
  262. }
  263. previouslyFailed = !active;
  264. return active;
  265. }
  266. void WASAPISource::Reconnect()
  267. {
  268. reconnecting = true;
  269. reconnectThread = CreateThread(nullptr, 0,
  270. WASAPISource::ReconnectThread, this,
  271. 0, nullptr);
  272. if (!reconnectThread.Valid())
  273. blog(LOG_WARNING, "[WASAPISource::Reconnect] "
  274. "Failed to initialize reconnect thread: %lu",
  275. GetLastError());
  276. }
  277. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  278. {
  279. return WaitForSingleObject(handle, time) != WAIT_TIMEOUT;
  280. }
  281. #define RECONNECT_INTERVAL 3000
  282. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  283. {
  284. WASAPISource *source = (WASAPISource*)param;
  285. os_set_thread_name("win-wasapi: reconnect thread");
  286. CoInitializeEx(0, COINIT_MULTITHREADED);
  287. obs_monitoring_type type = obs_source_get_monitoring_type(source->source);
  288. obs_source_set_monitoring_type(source->source, OBS_MONITORING_TYPE_NONE);
  289. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  290. if (source->TryInitialize())
  291. break;
  292. }
  293. obs_source_set_monitoring_type(source->source, type);
  294. source->reconnectThread = nullptr;
  295. source->reconnecting = false;
  296. return 0;
  297. }
  298. bool WASAPISource::ProcessCaptureData()
  299. {
  300. HRESULT res;
  301. LPBYTE buffer;
  302. UINT32 frames;
  303. DWORD flags;
  304. UINT64 pos, ts;
  305. UINT captureSize = 0;
  306. while (true) {
  307. res = capture->GetNextPacketSize(&captureSize);
  308. if (FAILED(res)) {
  309. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  310. blog(LOG_WARNING,
  311. "[WASAPISource::GetCaptureData]"
  312. " capture->GetNextPacketSize"
  313. " failed: %lX", res);
  314. return false;
  315. }
  316. if (!captureSize)
  317. break;
  318. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  319. if (FAILED(res)) {
  320. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  321. blog(LOG_WARNING,
  322. "[WASAPISource::GetCaptureData]"
  323. " capture->GetBuffer"
  324. " failed: %lX", res);
  325. return false;
  326. }
  327. obs_source_audio data = {};
  328. data.data[0] = (const uint8_t*)buffer;
  329. data.frames = (uint32_t)frames;
  330. data.speakers = speakers;
  331. data.samples_per_sec = sampleRate;
  332. data.format = format;
  333. data.timestamp = useDeviceTiming ?
  334. ts*100 : os_gettime_ns();
  335. if (!useDeviceTiming)
  336. data.timestamp -= (uint64_t)frames * 1000000000ULL /
  337. (uint64_t)sampleRate;
  338. obs_source_output_audio(source, &data);
  339. capture->ReleaseBuffer(frames);
  340. }
  341. return true;
  342. }
  343. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  344. DWORD duration)
  345. {
  346. DWORD ret;
  347. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  348. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  349. }
  350. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  351. {
  352. WASAPISource *source = (WASAPISource*)param;
  353. bool reconnect = false;
  354. /* Output devices don't signal, so just make it check every 10 ms */
  355. DWORD dur = source->isInputDevice ? RECONNECT_INTERVAL : 10;
  356. HANDLE sigs[2] = {
  357. source->receiveSignal,
  358. source->stopSignal
  359. };
  360. os_set_thread_name("win-wasapi: capture thread");
  361. while (WaitForCaptureSignal(2, sigs, dur)) {
  362. if (!source->ProcessCaptureData()) {
  363. reconnect = true;
  364. break;
  365. }
  366. }
  367. source->client->Stop();
  368. source->captureThread = nullptr;
  369. source->active = false;
  370. if (reconnect) {
  371. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  372. source->device_name.c_str());
  373. source->Reconnect();
  374. }
  375. return 0;
  376. }
  377. /* ------------------------------------------------------------------------- */
  378. static const char *GetWASAPIInputName(void*)
  379. {
  380. return obs_module_text("AudioInput");
  381. }
  382. static const char *GetWASAPIOutputName(void*)
  383. {
  384. return obs_module_text("AudioOutput");
  385. }
  386. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  387. {
  388. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  389. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  390. }
  391. static void GetWASAPIDefaultsOutput(obs_data_t *settings)
  392. {
  393. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  394. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  395. }
  396. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  397. bool input)
  398. {
  399. try {
  400. return new WASAPISource(settings, source, input);
  401. } catch (const char *error) {
  402. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  403. }
  404. return nullptr;
  405. }
  406. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  407. {
  408. return CreateWASAPISource(settings, source, true);
  409. }
  410. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  411. {
  412. return CreateWASAPISource(settings, source, false);
  413. }
  414. static void DestroyWASAPISource(void *obj)
  415. {
  416. delete static_cast<WASAPISource*>(obj);
  417. }
  418. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  419. {
  420. static_cast<WASAPISource*>(obj)->Update(settings);
  421. }
  422. static obs_properties_t *GetWASAPIProperties(bool input)
  423. {
  424. obs_properties_t *props = obs_properties_create();
  425. vector<AudioDeviceInfo> devices;
  426. obs_property_t *device_prop = obs_properties_add_list(props,
  427. OPT_DEVICE_ID, obs_module_text("Device"),
  428. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  429. GetWASAPIAudioDevices(devices, input);
  430. if (devices.size())
  431. obs_property_list_add_string(device_prop,
  432. obs_module_text("Default"), "default");
  433. for (size_t i = 0; i < devices.size(); i++) {
  434. AudioDeviceInfo &device = devices[i];
  435. obs_property_list_add_string(device_prop,
  436. device.name.c_str(), device.id.c_str());
  437. }
  438. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  439. obs_module_text("UseDeviceTiming"));
  440. return props;
  441. }
  442. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  443. {
  444. return GetWASAPIProperties(true);
  445. }
  446. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  447. {
  448. return GetWASAPIProperties(false);
  449. }
  450. void RegisterWASAPIInput()
  451. {
  452. obs_source_info info = {};
  453. info.id = "wasapi_input_capture";
  454. info.type = OBS_SOURCE_TYPE_INPUT;
  455. info.output_flags = OBS_SOURCE_AUDIO |
  456. 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 |
  471. OBS_SOURCE_DO_NOT_DUPLICATE |
  472. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  473. info.get_name = GetWASAPIOutputName;
  474. info.create = CreateWASAPIOutput;
  475. info.destroy = DestroyWASAPISource;
  476. info.update = UpdateWASAPISource;
  477. info.get_defaults = GetWASAPIDefaultsOutput;
  478. info.get_properties = GetWASAPIPropertiesOutput;
  479. obs_register_source(&info);
  480. }