win-wasapi.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. obs_source_t *source;
  20. string device_id;
  21. string device_name;
  22. bool isInputDevice;
  23. bool useDeviceTiming = false;
  24. bool isDefaultDevice = false;
  25. bool reconnecting = false;
  26. bool previouslyFailed = false;
  27. WinHandle reconnectThread;
  28. bool active = false;
  29. WinHandle captureThread;
  30. WinHandle stopSignal;
  31. WinHandle receiveSignal;
  32. speaker_layout speakers;
  33. audio_format format;
  34. uint32_t sampleRate;
  35. static DWORD WINAPI ReconnectThread(LPVOID param);
  36. static DWORD WINAPI CaptureThread(LPVOID param);
  37. bool ProcessCaptureData();
  38. inline void Start();
  39. inline void Stop();
  40. void Reconnect();
  41. bool InitDevice(IMMDeviceEnumerator *enumerator);
  42. void InitName();
  43. void InitClient();
  44. void InitFormat(WAVEFORMATEX *wfex);
  45. void InitCapture();
  46. void Initialize();
  47. bool TryInitialize();
  48. void UpdateSettings(obs_data_t *settings);
  49. public:
  50. WASAPISource(obs_data_t *settings, obs_source_t *source_, bool input);
  51. inline ~WASAPISource();
  52. void Update(obs_data_t *settings);
  53. };
  54. WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
  55. bool input)
  56. : source (source_),
  57. isInputDevice (input)
  58. {
  59. UpdateSettings(settings);
  60. stopSignal = CreateEvent(nullptr, true, false, nullptr);
  61. if (!stopSignal.Valid())
  62. throw "Could not create stop signal";
  63. receiveSignal = CreateEvent(nullptr, false, false, nullptr);
  64. if (!receiveSignal.Valid())
  65. throw "Could not create receive signal";
  66. Start();
  67. }
  68. inline void WASAPISource::Start()
  69. {
  70. if (!TryInitialize()) {
  71. blog(LOG_INFO, "[WASAPISource::WASAPISource] "
  72. "Device '%s' not found. Waiting for device",
  73. device_id.c_str());
  74. Reconnect();
  75. }
  76. }
  77. inline void WASAPISource::Stop()
  78. {
  79. SetEvent(stopSignal);
  80. if (active) {
  81. blog(LOG_INFO, "WASAPI: Device '%s' Terminated",
  82. device_name.c_str());
  83. WaitForSingleObject(captureThread, INFINITE);
  84. }
  85. if (reconnecting)
  86. WaitForSingleObject(reconnectThread, INFINITE);
  87. ResetEvent(stopSignal);
  88. }
  89. inline WASAPISource::~WASAPISource()
  90. {
  91. Stop();
  92. }
  93. void WASAPISource::UpdateSettings(obs_data_t *settings)
  94. {
  95. device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
  96. useDeviceTiming = obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
  97. isDefaultDevice = _strcmpi(device_id.c_str(), "default") == 0;
  98. }
  99. void WASAPISource::Update(obs_data_t *settings)
  100. {
  101. string newDevice = obs_data_get_string(settings, OPT_DEVICE_ID);
  102. bool restart = newDevice.compare(device_id) != 0;
  103. if (restart)
  104. Stop();
  105. UpdateSettings(settings);
  106. if (restart)
  107. Start();
  108. }
  109. bool WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator)
  110. {
  111. HRESULT res;
  112. if (isDefaultDevice) {
  113. res = enumerator->GetDefaultAudioEndpoint(
  114. isInputDevice ? eCapture : eRender,
  115. isInputDevice ? eCommunications : eConsole,
  116. device.Assign());
  117. } else {
  118. wchar_t *w_id;
  119. os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
  120. res = enumerator->GetDevice(w_id, device.Assign());
  121. bfree(w_id);
  122. }
  123. return SUCCEEDED(res);
  124. }
  125. #define BUFFER_TIME_100NS (5*10000000)
  126. void WASAPISource::InitClient()
  127. {
  128. CoTaskMemPtr<WAVEFORMATEX> wfex;
  129. HRESULT res;
  130. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  131. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
  132. nullptr, (void**)client.Assign());
  133. if (FAILED(res))
  134. throw HRError("Failed to activate client context", res);
  135. res = client->GetMixFormat(&wfex);
  136. if (FAILED(res))
  137. throw HRError("Failed to get mix format", res);
  138. InitFormat(wfex);
  139. if (!isInputDevice)
  140. flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
  141. res = client->Initialize(
  142. AUDCLNT_SHAREMODE_SHARED, flags,
  143. BUFFER_TIME_100NS, 0, wfex, nullptr);
  144. if (FAILED(res))
  145. throw HRError("Failed to get initialize audio client", res);
  146. }
  147. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  148. {
  149. switch (layout) {
  150. case KSAUDIO_SPEAKER_QUAD: return SPEAKERS_QUAD;
  151. case KSAUDIO_SPEAKER_2POINT1: return SPEAKERS_2POINT1;
  152. case KSAUDIO_SPEAKER_4POINT1: return SPEAKERS_4POINT1;
  153. case KSAUDIO_SPEAKER_SURROUND: return SPEAKERS_SURROUND;
  154. case KSAUDIO_SPEAKER_5POINT1: return SPEAKERS_5POINT1;
  155. case KSAUDIO_SPEAKER_5POINT1_SURROUND: return SPEAKERS_5POINT1_SURROUND;
  156. case KSAUDIO_SPEAKER_7POINT1: return SPEAKERS_7POINT1;
  157. case KSAUDIO_SPEAKER_7POINT1_SURROUND: return SPEAKERS_7POINT1_SURROUND;
  158. }
  159. return (speaker_layout)channels;
  160. }
  161. void WASAPISource::InitFormat(WAVEFORMATEX *wfex)
  162. {
  163. DWORD layout = 0;
  164. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  165. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)wfex;
  166. layout = ext->dwChannelMask;
  167. }
  168. /* WASAPI is always float */
  169. sampleRate = wfex->nSamplesPerSec;
  170. format = AUDIO_FORMAT_FLOAT;
  171. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  172. }
  173. void WASAPISource::InitCapture()
  174. {
  175. HRESULT res = client->GetService(__uuidof(IAudioCaptureClient),
  176. (void**)capture.Assign());
  177. if (FAILED(res))
  178. throw HRError("Failed to create capture context", res);
  179. res = client->SetEventHandle(receiveSignal);
  180. if (FAILED(res))
  181. throw HRError("Failed to set event handle", res);
  182. captureThread = CreateThread(nullptr, 0,
  183. WASAPISource::CaptureThread, this,
  184. 0, nullptr);
  185. if (!captureThread.Valid())
  186. throw "Failed to create capture thread";
  187. client->Start();
  188. active = true;
  189. blog(LOG_INFO, "WASAPI: Device '%s' initialized", device_name.c_str());
  190. }
  191. void WASAPISource::Initialize()
  192. {
  193. ComPtr<IMMDeviceEnumerator> enumerator;
  194. HRESULT res;
  195. res = CoCreateInstance(__uuidof(MMDeviceEnumerator),
  196. nullptr, CLSCTX_ALL,
  197. __uuidof(IMMDeviceEnumerator),
  198. (void**)enumerator.Assign());
  199. if (FAILED(res))
  200. throw HRError("Failed to create enumerator", res);
  201. if (!InitDevice(enumerator))
  202. return;
  203. device_name = GetDeviceName(device);
  204. InitClient();
  205. InitCapture();
  206. }
  207. bool WASAPISource::TryInitialize()
  208. {
  209. try {
  210. Initialize();
  211. } catch (HRError error) {
  212. if (previouslyFailed)
  213. return active;
  214. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  215. device_name.empty() ?
  216. device_id.c_str() : device_name.c_str(),
  217. error.str, error.hr);
  218. } catch (const char *error) {
  219. if (previouslyFailed)
  220. return active;
  221. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  222. device_name.empty() ?
  223. device_id.c_str() : device_name.c_str(),
  224. error);
  225. }
  226. previouslyFailed = !active;
  227. return active;
  228. }
  229. void WASAPISource::Reconnect()
  230. {
  231. reconnecting = true;
  232. reconnectThread = CreateThread(nullptr, 0,
  233. WASAPISource::ReconnectThread, this,
  234. 0, nullptr);
  235. if (!reconnectThread.Valid())
  236. blog(LOG_WARNING, "[WASAPISource::Reconnect] "
  237. "Failed to intiialize reconnect thread: %lu",
  238. GetLastError());
  239. }
  240. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  241. {
  242. return WaitForSingleObject(handle, time) == WAIT_TIMEOUT;
  243. }
  244. #define RECONNECT_INTERVAL 3000
  245. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  246. {
  247. WASAPISource *source = (WASAPISource*)param;
  248. os_set_thread_name("win-wasapi: reconnect thread");
  249. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  250. if (source->TryInitialize())
  251. break;
  252. }
  253. source->reconnectThread = nullptr;
  254. source->reconnecting = false;
  255. return 0;
  256. }
  257. bool WASAPISource::ProcessCaptureData()
  258. {
  259. HRESULT res;
  260. LPBYTE buffer;
  261. UINT32 frames;
  262. DWORD flags;
  263. UINT64 pos, ts;
  264. UINT captureSize = 0;
  265. while (true) {
  266. res = capture->GetNextPacketSize(&captureSize);
  267. if (FAILED(res)) {
  268. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  269. blog(LOG_WARNING,
  270. "[WASAPISource::GetCaptureData]"
  271. " capture->GetNextPacketSize"
  272. " failed: %lX", res);
  273. return false;
  274. }
  275. if (!captureSize)
  276. break;
  277. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  278. if (FAILED(res)) {
  279. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  280. blog(LOG_WARNING,
  281. "[WASAPISource::GetCaptureData]"
  282. " capture->GetBuffer"
  283. " failed: %lX", res);
  284. return false;
  285. }
  286. obs_source_audio data = {};
  287. data.data[0] = (const uint8_t*)buffer;
  288. data.frames = (uint32_t)frames;
  289. data.speakers = speakers;
  290. data.samples_per_sec = sampleRate;
  291. data.format = format;
  292. data.timestamp = useDeviceTiming ?
  293. ts*100 : os_gettime_ns();
  294. obs_source_output_audio(source, &data);
  295. capture->ReleaseBuffer(frames);
  296. }
  297. return true;
  298. }
  299. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  300. DWORD duration)
  301. {
  302. DWORD ret;
  303. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  304. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  305. }
  306. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  307. {
  308. WASAPISource *source = (WASAPISource*)param;
  309. bool reconnect = false;
  310. /* Output devices don't signal, so just make it check every 10 ms */
  311. DWORD dur = source->isInputDevice ? INFINITE : 10;
  312. HANDLE sigs[2] = {
  313. source->receiveSignal,
  314. source->stopSignal
  315. };
  316. os_set_thread_name("win-wasapi: capture thread");
  317. while (WaitForCaptureSignal(2, sigs, dur)) {
  318. if (!source->ProcessCaptureData()) {
  319. reconnect = true;
  320. break;
  321. }
  322. }
  323. source->client->Stop();
  324. source->captureThread = nullptr;
  325. source->active = false;
  326. if (reconnect) {
  327. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  328. source->device_name.c_str());
  329. source->Reconnect();
  330. }
  331. return 0;
  332. }
  333. /* ------------------------------------------------------------------------- */
  334. static const char *GetWASAPIInputName(void)
  335. {
  336. return obs_module_text("AudioInput");
  337. }
  338. static const char *GetWASAPIOutputName(void)
  339. {
  340. return obs_module_text("AudioOutput");
  341. }
  342. static void GetWASAPIDefaults(obs_data_t *settings)
  343. {
  344. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  345. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  346. }
  347. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  348. bool input)
  349. {
  350. try {
  351. return new WASAPISource(settings, source, input);
  352. } catch (const char *error) {
  353. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  354. }
  355. return nullptr;
  356. }
  357. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  358. {
  359. return CreateWASAPISource(settings, source, true);
  360. }
  361. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  362. {
  363. return CreateWASAPISource(settings, source, false);
  364. }
  365. static void DestroyWASAPISource(void *obj)
  366. {
  367. delete static_cast<WASAPISource*>(obj);
  368. }
  369. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  370. {
  371. static_cast<WASAPISource*>(obj)->Update(settings);
  372. }
  373. static obs_properties_t *GetWASAPIProperties(bool input)
  374. {
  375. obs_properties_t *props = obs_properties_create();
  376. vector<AudioDeviceInfo> devices;
  377. /* TODO: translate */
  378. obs_property_t *device_prop = obs_properties_add_list(props,
  379. OPT_DEVICE_ID, obs_module_text("Device"),
  380. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  381. GetWASAPIAudioDevices(devices, input);
  382. if (devices.size())
  383. obs_property_list_add_string(device_prop,
  384. obs_module_text("Default"), "default");
  385. for (size_t i = 0; i < devices.size(); i++) {
  386. AudioDeviceInfo &device = devices[i];
  387. obs_property_list_add_string(device_prop,
  388. device.name.c_str(), device.id.c_str());
  389. }
  390. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  391. obs_module_text("UseDeviceTiming"));
  392. return props;
  393. }
  394. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  395. {
  396. return GetWASAPIProperties(true);
  397. }
  398. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  399. {
  400. return GetWASAPIProperties(false);
  401. }
  402. void RegisterWASAPIInput()
  403. {
  404. obs_source_info info = {};
  405. info.id = "wasapi_input_capture";
  406. info.type = OBS_SOURCE_TYPE_INPUT;
  407. info.output_flags = OBS_SOURCE_AUDIO;
  408. info.get_name = GetWASAPIInputName;
  409. info.create = CreateWASAPIInput;
  410. info.destroy = DestroyWASAPISource;
  411. info.update = UpdateWASAPISource;
  412. info.get_defaults = GetWASAPIDefaults;
  413. info.get_properties = GetWASAPIPropertiesInput;
  414. obs_register_source(&info);
  415. }
  416. void RegisterWASAPIOutput()
  417. {
  418. obs_source_info info = {};
  419. info.id = "wasapi_output_capture";
  420. info.type = OBS_SOURCE_TYPE_INPUT;
  421. info.output_flags = OBS_SOURCE_AUDIO;
  422. info.get_name = GetWASAPIOutputName;
  423. info.create = CreateWASAPIOutput;
  424. info.destroy = DestroyWASAPISource;
  425. info.update = UpdateWASAPISource;
  426. info.get_defaults = GetWASAPIDefaults;
  427. info.get_properties = GetWASAPIPropertiesOutput;
  428. obs_register_source(&info);
  429. }