win-wasapi.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. #define KSAUDIO_SPEAKER_4POINT1 (KSAUDIO_SPEAKER_QUAD|SPEAKER_LOW_FREQUENCY)
  14. #define KSAUDIO_SPEAKER_2POINT1 (KSAUDIO_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY)
  15. class WASAPISource {
  16. ComPtr<IMMDevice> device;
  17. ComPtr<IAudioClient> client;
  18. ComPtr<IAudioCaptureClient> capture;
  19. ComPtr<IAudioRenderClient> render;
  20. obs_source_t *source;
  21. string device_id;
  22. string device_name;
  23. bool isInputDevice;
  24. bool useDeviceTiming = false;
  25. bool isDefaultDevice = false;
  26. bool reconnecting = false;
  27. bool previouslyFailed = false;
  28. WinHandle reconnectThread;
  29. bool active = false;
  30. WinHandle captureThread;
  31. WinHandle stopSignal;
  32. WinHandle receiveSignal;
  33. speaker_layout speakers;
  34. audio_format format;
  35. uint32_t sampleRate;
  36. static DWORD WINAPI ReconnectThread(LPVOID param);
  37. static DWORD WINAPI CaptureThread(LPVOID param);
  38. bool ProcessCaptureData();
  39. inline void Start();
  40. inline void Stop();
  41. void Reconnect();
  42. bool InitDevice(IMMDeviceEnumerator *enumerator);
  43. void InitName();
  44. void InitClient();
  45. void InitRender();
  46. void InitFormat(WAVEFORMATEX *wfex);
  47. void InitCapture();
  48. void Initialize();
  49. bool TryInitialize();
  50. void UpdateSettings(obs_data_t *settings);
  51. public:
  52. WASAPISource(obs_data_t *settings, obs_source_t *source_, bool input);
  53. inline ~WASAPISource();
  54. void Update(obs_data_t *settings);
  55. };
  56. WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
  57. bool input)
  58. : source (source_),
  59. 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, "[WASAPISource::WASAPISource] "
  74. "Device '%s' not found. Waiting for device",
  75. device_id.c_str());
  76. Reconnect();
  77. }
  78. }
  79. inline void WASAPISource::Stop()
  80. {
  81. SetEvent(stopSignal);
  82. if (active) {
  83. blog(LOG_INFO, "WASAPI: Device '%s' Terminated",
  84. device_name.c_str());
  85. WaitForSingleObject(captureThread, INFINITE);
  86. }
  87. if (reconnecting)
  88. WaitForSingleObject(reconnectThread, INFINITE);
  89. ResetEvent(stopSignal);
  90. }
  91. inline WASAPISource::~WASAPISource()
  92. {
  93. Stop();
  94. }
  95. void WASAPISource::UpdateSettings(obs_data_t *settings)
  96. {
  97. device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
  98. useDeviceTiming = obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
  99. isDefaultDevice = _strcmpi(device_id.c_str(), "default") == 0;
  100. }
  101. void WASAPISource::Update(obs_data_t *settings)
  102. {
  103. string newDevice = obs_data_get_string(settings, OPT_DEVICE_ID);
  104. bool restart = newDevice.compare(device_id) != 0;
  105. if (restart)
  106. Stop();
  107. UpdateSettings(settings);
  108. if (restart)
  109. Start();
  110. }
  111. bool WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator)
  112. {
  113. HRESULT res;
  114. if (isDefaultDevice) {
  115. res = enumerator->GetDefaultAudioEndpoint(
  116. isInputDevice ? eCapture : eRender,
  117. isInputDevice ? eCommunications : eConsole,
  118. device.Assign());
  119. } else {
  120. wchar_t *w_id;
  121. os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
  122. res = enumerator->GetDevice(w_id, device.Assign());
  123. bfree(w_id);
  124. }
  125. return SUCCEEDED(res);
  126. }
  127. #define BUFFER_TIME_100NS (5*10000000)
  128. void WASAPISource::InitClient()
  129. {
  130. CoTaskMemPtr<WAVEFORMATEX> wfex;
  131. HRESULT res;
  132. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  133. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
  134. nullptr, (void**)client.Assign());
  135. if (FAILED(res))
  136. throw HRError("Failed to activate client context", res);
  137. res = client->GetMixFormat(&wfex);
  138. if (FAILED(res))
  139. throw HRError("Failed to get mix format", res);
  140. InitFormat(wfex);
  141. if (!isInputDevice)
  142. flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
  143. res = client->Initialize(
  144. 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,
  157. nullptr, (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(
  164. AUDCLNT_SHAREMODE_SHARED, 0,
  165. BUFFER_TIME_100NS, 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_QUAD: return SPEAKERS_QUAD;
  188. case KSAUDIO_SPEAKER_2POINT1: return SPEAKERS_2POINT1;
  189. case KSAUDIO_SPEAKER_4POINT1: return SPEAKERS_4POINT1;
  190. case KSAUDIO_SPEAKER_SURROUND: return SPEAKERS_SURROUND;
  191. case KSAUDIO_SPEAKER_5POINT1: return SPEAKERS_5POINT1;
  192. case KSAUDIO_SPEAKER_5POINT1_SURROUND: return SPEAKERS_5POINT1_SURROUND;
  193. case KSAUDIO_SPEAKER_7POINT1: return SPEAKERS_7POINT1;
  194. case KSAUDIO_SPEAKER_7POINT1_SURROUND: return SPEAKERS_7POINT1_SURROUND;
  195. }
  196. return (speaker_layout)channels;
  197. }
  198. void WASAPISource::InitFormat(WAVEFORMATEX *wfex)
  199. {
  200. DWORD layout = 0;
  201. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  202. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)wfex;
  203. layout = ext->dwChannelMask;
  204. }
  205. /* WASAPI is always float */
  206. sampleRate = wfex->nSamplesPerSec;
  207. format = AUDIO_FORMAT_FLOAT;
  208. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  209. }
  210. void WASAPISource::InitCapture()
  211. {
  212. HRESULT res = client->GetService(__uuidof(IAudioCaptureClient),
  213. (void**)capture.Assign());
  214. if (FAILED(res))
  215. throw HRError("Failed to create capture context", res);
  216. res = client->SetEventHandle(receiveSignal);
  217. if (FAILED(res))
  218. throw HRError("Failed to set event handle", res);
  219. captureThread = CreateThread(nullptr, 0,
  220. WASAPISource::CaptureThread, this,
  221. 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),
  233. nullptr, CLSCTX_ALL,
  234. __uuidof(IMMDeviceEnumerator),
  235. (void**)enumerator.Assign());
  236. if (FAILED(res))
  237. throw HRError("Failed to create enumerator", res);
  238. if (!InitDevice(enumerator))
  239. return;
  240. device_name = GetDeviceName(device);
  241. InitClient();
  242. if (!isInputDevice) 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() ?
  254. device_id.c_str() : 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() ?
  261. device_id.c_str() : 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(nullptr, 0,
  271. WASAPISource::ReconnectThread, this,
  272. 0, nullptr);
  273. if (!reconnectThread.Valid())
  274. blog(LOG_WARNING, "[WASAPISource::Reconnect] "
  275. "Failed to intiialize 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. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  288. if (source->TryInitialize())
  289. break;
  290. }
  291. source->reconnectThread = nullptr;
  292. source->reconnecting = false;
  293. return 0;
  294. }
  295. bool WASAPISource::ProcessCaptureData()
  296. {
  297. HRESULT res;
  298. LPBYTE buffer;
  299. UINT32 frames;
  300. DWORD flags;
  301. UINT64 pos, ts;
  302. UINT captureSize = 0;
  303. while (true) {
  304. res = capture->GetNextPacketSize(&captureSize);
  305. if (FAILED(res)) {
  306. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  307. blog(LOG_WARNING,
  308. "[WASAPISource::GetCaptureData]"
  309. " capture->GetNextPacketSize"
  310. " failed: %lX", res);
  311. return false;
  312. }
  313. if (!captureSize)
  314. break;
  315. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  316. if (FAILED(res)) {
  317. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  318. blog(LOG_WARNING,
  319. "[WASAPISource::GetCaptureData]"
  320. " capture->GetBuffer"
  321. " failed: %lX", res);
  322. return false;
  323. }
  324. obs_source_audio data = {};
  325. data.data[0] = (const uint8_t*)buffer;
  326. data.frames = (uint32_t)frames;
  327. data.speakers = speakers;
  328. data.samples_per_sec = sampleRate;
  329. data.format = format;
  330. data.timestamp = useDeviceTiming ?
  331. ts*100 : os_gettime_ns();
  332. obs_source_output_audio(source, &data);
  333. capture->ReleaseBuffer(frames);
  334. }
  335. return true;
  336. }
  337. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  338. DWORD duration)
  339. {
  340. DWORD ret;
  341. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  342. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  343. }
  344. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  345. {
  346. WASAPISource *source = (WASAPISource*)param;
  347. bool reconnect = false;
  348. /* Output devices don't signal, so just make it check every 10 ms */
  349. DWORD dur = source->isInputDevice ? INFINITE : 10;
  350. HANDLE sigs[2] = {
  351. source->receiveSignal,
  352. source->stopSignal
  353. };
  354. os_set_thread_name("win-wasapi: capture thread");
  355. while (WaitForCaptureSignal(2, sigs, dur)) {
  356. if (!source->ProcessCaptureData()) {
  357. reconnect = true;
  358. break;
  359. }
  360. }
  361. source->client->Stop();
  362. source->captureThread = nullptr;
  363. source->active = false;
  364. if (reconnect) {
  365. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  366. source->device_name.c_str());
  367. source->Reconnect();
  368. }
  369. return 0;
  370. }
  371. /* ------------------------------------------------------------------------- */
  372. static const char *GetWASAPIInputName(void*)
  373. {
  374. return obs_module_text("AudioInput");
  375. }
  376. static const char *GetWASAPIOutputName(void*)
  377. {
  378. return obs_module_text("AudioOutput");
  379. }
  380. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  381. {
  382. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  383. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  384. }
  385. static void GetWASAPIDefaultsOutput(obs_data_t *settings)
  386. {
  387. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  388. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  389. }
  390. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  391. bool input)
  392. {
  393. try {
  394. return new WASAPISource(settings, source, input);
  395. } catch (const char *error) {
  396. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  397. }
  398. return nullptr;
  399. }
  400. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  401. {
  402. return CreateWASAPISource(settings, source, true);
  403. }
  404. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  405. {
  406. return CreateWASAPISource(settings, source, false);
  407. }
  408. static void DestroyWASAPISource(void *obj)
  409. {
  410. delete static_cast<WASAPISource*>(obj);
  411. }
  412. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  413. {
  414. static_cast<WASAPISource*>(obj)->Update(settings);
  415. }
  416. static obs_properties_t *GetWASAPIProperties(bool input)
  417. {
  418. obs_properties_t *props = obs_properties_create();
  419. vector<AudioDeviceInfo> devices;
  420. obs_property_t *device_prop = obs_properties_add_list(props,
  421. OPT_DEVICE_ID, obs_module_text("Device"),
  422. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  423. GetWASAPIAudioDevices(devices, input);
  424. if (devices.size())
  425. obs_property_list_add_string(device_prop,
  426. obs_module_text("Default"), "default");
  427. for (size_t i = 0; i < devices.size(); i++) {
  428. AudioDeviceInfo &device = devices[i];
  429. obs_property_list_add_string(device_prop,
  430. device.name.c_str(), device.id.c_str());
  431. }
  432. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  433. obs_module_text("UseDeviceTiming"));
  434. return props;
  435. }
  436. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  437. {
  438. return GetWASAPIProperties(true);
  439. }
  440. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  441. {
  442. return GetWASAPIProperties(false);
  443. }
  444. void RegisterWASAPIInput()
  445. {
  446. obs_source_info info = {};
  447. info.id = "wasapi_input_capture";
  448. info.type = OBS_SOURCE_TYPE_INPUT;
  449. info.output_flags = OBS_SOURCE_AUDIO |
  450. OBS_SOURCE_DO_NOT_DUPLICATE;
  451. info.get_name = GetWASAPIInputName;
  452. info.create = CreateWASAPIInput;
  453. info.destroy = DestroyWASAPISource;
  454. info.update = UpdateWASAPISource;
  455. info.get_defaults = GetWASAPIDefaultsInput;
  456. info.get_properties = GetWASAPIPropertiesInput;
  457. obs_register_source(&info);
  458. }
  459. void RegisterWASAPIOutput()
  460. {
  461. obs_source_info info = {};
  462. info.id = "wasapi_output_capture";
  463. info.type = OBS_SOURCE_TYPE_INPUT;
  464. info.output_flags = OBS_SOURCE_AUDIO |
  465. OBS_SOURCE_DO_NOT_DUPLICATE |
  466. OBS_SOURCE_DO_NOT_MONITOR;
  467. info.get_name = GetWASAPIOutputName;
  468. info.create = CreateWASAPIOutput;
  469. info.destroy = DestroyWASAPISource;
  470. info.update = UpdateWASAPISource;
  471. info.get_defaults = GetWASAPIDefaultsOutput;
  472. info.get_properties = GetWASAPIPropertiesOutput;
  473. obs_register_source(&info);
  474. }