win-wasapi.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #include "enum-wasapi.hpp"
  2. #include <obs-module.h>
  3. #include <util/platform.h>
  4. #include <util/windows/HRError.hpp>
  5. #include <util/windows/ComPtr.hpp>
  6. #include <util/windows/WinHandle.hpp>
  7. #include <util/windows/CoTaskMemPtr.hpp>
  8. #include <util/threading.h>
  9. using namespace std;
  10. #define OPT_DEVICE_ID "device_id"
  11. #define OPT_USE_DEVICE_TIMING "use_device_timing"
  12. static void GetWASAPIDefaults(obs_data_t *settings);
  13. // Fix inconsistent defs of speaker_surround between avutil & wasapi
  14. #define KSAUDIO_SPEAKER_2POINT1 (KSAUDIO_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY)
  15. #define KSAUDIO_SPEAKER_SURROUND_AVUTIL \
  16. (KSAUDIO_SPEAKER_STEREO|SPEAKER_FRONT_CENTER)
  17. #define KSAUDIO_SPEAKER_4POINT1 (KSAUDIO_SPEAKER_QUAD|SPEAKER_LOW_FREQUENCY)
  18. class WASAPISource {
  19. ComPtr<IMMDevice> device;
  20. ComPtr<IAudioClient> client;
  21. ComPtr<IAudioCaptureClient> capture;
  22. ComPtr<IAudioRenderClient> render;
  23. obs_source_t *source;
  24. string device_id;
  25. string device_name;
  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_),
  62. isInputDevice (input)
  63. {
  64. UpdateSettings(settings);
  65. stopSignal = CreateEvent(nullptr, true, false, nullptr);
  66. if (!stopSignal.Valid())
  67. throw "Could not create stop signal";
  68. receiveSignal = CreateEvent(nullptr, false, false, nullptr);
  69. if (!receiveSignal.Valid())
  70. throw "Could not create receive signal";
  71. Start();
  72. }
  73. inline void WASAPISource::Start()
  74. {
  75. if (!TryInitialize()) {
  76. blog(LOG_INFO, "[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,
  137. nullptr, (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(
  147. AUDCLNT_SHAREMODE_SHARED, flags,
  148. BUFFER_TIME_100NS, 0, wfex, nullptr);
  149. if (FAILED(res))
  150. throw HRError("Failed to get initialize audio client", res);
  151. }
  152. void WASAPISource::InitRender()
  153. {
  154. CoTaskMemPtr<WAVEFORMATEX> wfex;
  155. HRESULT res;
  156. LPBYTE buffer;
  157. UINT32 frames;
  158. ComPtr<IAudioClient> client;
  159. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
  160. nullptr, (void**)client.Assign());
  161. if (FAILED(res))
  162. throw HRError("Failed to activate client context", res);
  163. res = client->GetMixFormat(&wfex);
  164. if (FAILED(res))
  165. throw HRError("Failed to get mix format", res);
  166. res = client->Initialize(
  167. AUDCLNT_SHAREMODE_SHARED, 0,
  168. BUFFER_TIME_100NS, 0, wfex, nullptr);
  169. if (FAILED(res))
  170. throw HRError("Failed to get initialize audio client", res);
  171. /* Silent loopback fix. Prevents audio stream from stopping and */
  172. /* messing up timestamps and other weird glitches during silence */
  173. /* by playing a silent sample all over again. */
  174. res = client->GetBufferSize(&frames);
  175. if (FAILED(res))
  176. throw HRError("Failed to get buffer size", res);
  177. res = client->GetService(__uuidof(IAudioRenderClient),
  178. (void**)render.Assign());
  179. if (FAILED(res))
  180. throw HRError("Failed to get render client", res);
  181. res = render->GetBuffer(frames, &buffer);
  182. if (FAILED(res))
  183. throw HRError("Failed to get buffer", res);
  184. memset(buffer, 0, frames*wfex->nBlockAlign);
  185. render->ReleaseBuffer(frames, 0);
  186. }
  187. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  188. {
  189. switch (layout) {
  190. case KSAUDIO_SPEAKER_QUAD: return SPEAKERS_QUAD;
  191. case KSAUDIO_SPEAKER_2POINT1: return SPEAKERS_2POINT1;
  192. case KSAUDIO_SPEAKER_4POINT1: return SPEAKERS_4POINT1;
  193. case KSAUDIO_SPEAKER_SURROUND_AVUTIL: return SPEAKERS_SURROUND;
  194. case KSAUDIO_SPEAKER_5POINT1: return SPEAKERS_5POINT1_SURROUND;
  195. case KSAUDIO_SPEAKER_5POINT1_SURROUND: return SPEAKERS_5POINT1;
  196. case KSAUDIO_SPEAKER_7POINT1: return SPEAKERS_7POINT1_SURROUND;
  197. case KSAUDIO_SPEAKER_7POINT1_SURROUND: 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,
  223. WASAPISource::CaptureThread, this,
  224. 0, nullptr);
  225. if (!captureThread.Valid())
  226. throw "Failed to create capture thread";
  227. client->Start();
  228. active = true;
  229. blog(LOG_INFO, "WASAPI: Device '%s' initialized", device_name.c_str());
  230. }
  231. void WASAPISource::Initialize()
  232. {
  233. ComPtr<IMMDeviceEnumerator> enumerator;
  234. HRESULT res;
  235. res = CoCreateInstance(__uuidof(MMDeviceEnumerator),
  236. nullptr, CLSCTX_ALL,
  237. __uuidof(IMMDeviceEnumerator),
  238. (void**)enumerator.Assign());
  239. if (FAILED(res))
  240. throw HRError("Failed to create enumerator", res);
  241. if (!InitDevice(enumerator))
  242. return;
  243. device_name = GetDeviceName(device);
  244. InitClient();
  245. if (!isInputDevice) InitRender();
  246. InitCapture();
  247. }
  248. bool WASAPISource::TryInitialize()
  249. {
  250. try {
  251. Initialize();
  252. } catch (HRError error) {
  253. if (previouslyFailed)
  254. return active;
  255. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  256. device_name.empty() ?
  257. device_id.c_str() : device_name.c_str(),
  258. error.str, error.hr);
  259. } catch (const char *error) {
  260. if (previouslyFailed)
  261. return active;
  262. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  263. device_name.empty() ?
  264. device_id.c_str() : device_name.c_str(),
  265. error);
  266. }
  267. previouslyFailed = !active;
  268. return active;
  269. }
  270. void WASAPISource::Reconnect()
  271. {
  272. reconnecting = true;
  273. reconnectThread = CreateThread(nullptr, 0,
  274. WASAPISource::ReconnectThread, this,
  275. 0, nullptr);
  276. if (!reconnectThread.Valid())
  277. blog(LOG_WARNING, "[WASAPISource::Reconnect] "
  278. "Failed to initialize reconnect thread: %lu",
  279. GetLastError());
  280. }
  281. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  282. {
  283. return WaitForSingleObject(handle, time) != WAIT_TIMEOUT;
  284. }
  285. #define RECONNECT_INTERVAL 3000
  286. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  287. {
  288. WASAPISource *source = (WASAPISource*)param;
  289. os_set_thread_name("win-wasapi: reconnect thread");
  290. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  291. if (source->TryInitialize())
  292. break;
  293. }
  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 ? INFINITE : 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. }