win-wasapi.cpp 13 KB

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