win-wasapi.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. CoInitializeEx(0, COINIT_MULTITHREADED);
  286. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  287. if (source->TryInitialize())
  288. break;
  289. }
  290. source->reconnectThread = nullptr;
  291. source->reconnecting = false;
  292. return 0;
  293. }
  294. bool WASAPISource::ProcessCaptureData()
  295. {
  296. HRESULT res;
  297. LPBYTE buffer;
  298. UINT32 frames;
  299. DWORD flags;
  300. UINT64 pos, ts;
  301. UINT captureSize = 0;
  302. while (true) {
  303. res = capture->GetNextPacketSize(&captureSize);
  304. if (FAILED(res)) {
  305. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  306. blog(LOG_WARNING,
  307. "[WASAPISource::GetCaptureData]"
  308. " capture->GetNextPacketSize"
  309. " failed: %lX", res);
  310. return false;
  311. }
  312. if (!captureSize)
  313. break;
  314. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  315. if (FAILED(res)) {
  316. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  317. blog(LOG_WARNING,
  318. "[WASAPISource::GetCaptureData]"
  319. " capture->GetBuffer"
  320. " failed: %lX", res);
  321. return false;
  322. }
  323. obs_source_audio data = {};
  324. data.data[0] = (const uint8_t*)buffer;
  325. data.frames = (uint32_t)frames;
  326. data.speakers = speakers;
  327. data.samples_per_sec = sampleRate;
  328. data.format = format;
  329. data.timestamp = useDeviceTiming ?
  330. ts*100 : os_gettime_ns();
  331. if (!useDeviceTiming)
  332. data.timestamp -= (uint64_t)frames * 1000000000ULL /
  333. (uint64_t)sampleRate;
  334. obs_source_output_audio(source, &data);
  335. capture->ReleaseBuffer(frames);
  336. }
  337. return true;
  338. }
  339. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  340. DWORD duration)
  341. {
  342. DWORD ret;
  343. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  344. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  345. }
  346. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  347. {
  348. WASAPISource *source = (WASAPISource*)param;
  349. bool reconnect = false;
  350. /* Output devices don't signal, so just make it check every 10 ms */
  351. DWORD dur = source->isInputDevice ? INFINITE : 10;
  352. HANDLE sigs[2] = {
  353. source->receiveSignal,
  354. source->stopSignal
  355. };
  356. os_set_thread_name("win-wasapi: capture thread");
  357. while (WaitForCaptureSignal(2, sigs, dur)) {
  358. if (!source->ProcessCaptureData()) {
  359. reconnect = true;
  360. break;
  361. }
  362. }
  363. source->client->Stop();
  364. source->captureThread = nullptr;
  365. source->active = false;
  366. if (reconnect) {
  367. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  368. source->device_name.c_str());
  369. source->Reconnect();
  370. }
  371. return 0;
  372. }
  373. /* ------------------------------------------------------------------------- */
  374. static const char *GetWASAPIInputName(void*)
  375. {
  376. return obs_module_text("AudioInput");
  377. }
  378. static const char *GetWASAPIOutputName(void*)
  379. {
  380. return obs_module_text("AudioOutput");
  381. }
  382. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  383. {
  384. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  385. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  386. }
  387. static void GetWASAPIDefaultsOutput(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, true);
  391. }
  392. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  393. bool input)
  394. {
  395. try {
  396. return new WASAPISource(settings, source, input);
  397. } catch (const char *error) {
  398. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  399. }
  400. return nullptr;
  401. }
  402. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  403. {
  404. return CreateWASAPISource(settings, source, true);
  405. }
  406. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  407. {
  408. return CreateWASAPISource(settings, source, false);
  409. }
  410. static void DestroyWASAPISource(void *obj)
  411. {
  412. delete static_cast<WASAPISource*>(obj);
  413. }
  414. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  415. {
  416. static_cast<WASAPISource*>(obj)->Update(settings);
  417. }
  418. static obs_properties_t *GetWASAPIProperties(bool input)
  419. {
  420. obs_properties_t *props = obs_properties_create();
  421. vector<AudioDeviceInfo> devices;
  422. obs_property_t *device_prop = obs_properties_add_list(props,
  423. OPT_DEVICE_ID, obs_module_text("Device"),
  424. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  425. GetWASAPIAudioDevices(devices, input);
  426. if (devices.size())
  427. obs_property_list_add_string(device_prop,
  428. obs_module_text("Default"), "default");
  429. for (size_t i = 0; i < devices.size(); i++) {
  430. AudioDeviceInfo &device = devices[i];
  431. obs_property_list_add_string(device_prop,
  432. device.name.c_str(), device.id.c_str());
  433. }
  434. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  435. obs_module_text("UseDeviceTiming"));
  436. return props;
  437. }
  438. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  439. {
  440. return GetWASAPIProperties(true);
  441. }
  442. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  443. {
  444. return GetWASAPIProperties(false);
  445. }
  446. void RegisterWASAPIInput()
  447. {
  448. obs_source_info info = {};
  449. info.id = "wasapi_input_capture";
  450. info.type = OBS_SOURCE_TYPE_INPUT;
  451. info.output_flags = OBS_SOURCE_AUDIO |
  452. OBS_SOURCE_DO_NOT_DUPLICATE;
  453. info.get_name = GetWASAPIInputName;
  454. info.create = CreateWASAPIInput;
  455. info.destroy = DestroyWASAPISource;
  456. info.update = UpdateWASAPISource;
  457. info.get_defaults = GetWASAPIDefaultsInput;
  458. info.get_properties = GetWASAPIPropertiesInput;
  459. obs_register_source(&info);
  460. }
  461. void RegisterWASAPIOutput()
  462. {
  463. obs_source_info info = {};
  464. info.id = "wasapi_output_capture";
  465. info.type = OBS_SOURCE_TYPE_INPUT;
  466. info.output_flags = OBS_SOURCE_AUDIO |
  467. OBS_SOURCE_DO_NOT_DUPLICATE |
  468. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  469. info.get_name = GetWASAPIOutputName;
  470. info.create = CreateWASAPIOutput;
  471. info.destroy = DestroyWASAPISource;
  472. info.update = UpdateWASAPISource;
  473. info.get_defaults = GetWASAPIDefaultsOutput;
  474. info.get_properties = GetWASAPIPropertiesOutput;
  475. obs_register_source(&info);
  476. }