1
0

win-wasapi.cpp 15 KB

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