win-wasapi.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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;
  24. bool isDefaultDevice;
  25. bool reconnecting;
  26. WinHandle reconnectThread;
  27. bool active;
  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. : reconnecting (false),
  56. active (false),
  57. reconnectThread (nullptr),
  58. captureThread (nullptr),
  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. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  151. {
  152. switch (layout) {
  153. case KSAUDIO_SPEAKER_QUAD: return SPEAKERS_QUAD;
  154. case KSAUDIO_SPEAKER_2POINT1: return SPEAKERS_2POINT1;
  155. case KSAUDIO_SPEAKER_4POINT1: return SPEAKERS_4POINT1;
  156. case KSAUDIO_SPEAKER_SURROUND: return SPEAKERS_SURROUND;
  157. case KSAUDIO_SPEAKER_5POINT1: return SPEAKERS_5POINT1;
  158. case KSAUDIO_SPEAKER_5POINT1_SURROUND: return SPEAKERS_5POINT1_SURROUND;
  159. case KSAUDIO_SPEAKER_7POINT1: return SPEAKERS_7POINT1;
  160. case KSAUDIO_SPEAKER_7POINT1_SURROUND: return SPEAKERS_7POINT1_SURROUND;
  161. }
  162. return (speaker_layout)channels;
  163. }
  164. void WASAPISource::InitFormat(WAVEFORMATEX *wfex)
  165. {
  166. DWORD layout = 0;
  167. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  168. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)wfex;
  169. layout = ext->dwChannelMask;
  170. }
  171. /* WASAPI is always float */
  172. sampleRate = wfex->nSamplesPerSec;
  173. format = AUDIO_FORMAT_FLOAT;
  174. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  175. }
  176. void WASAPISource::InitCapture()
  177. {
  178. HRESULT res = client->GetService(__uuidof(IAudioCaptureClient),
  179. (void**)capture.Assign());
  180. if (FAILED(res))
  181. throw HRError("Failed to create capture context", res);
  182. res = client->SetEventHandle(receiveSignal);
  183. if (FAILED(res))
  184. throw HRError("Failed to set event handle", res);
  185. captureThread = CreateThread(nullptr, 0,
  186. WASAPISource::CaptureThread, this,
  187. 0, nullptr);
  188. if (!captureThread.Valid())
  189. throw "Failed to create capture thread";
  190. client->Start();
  191. active = true;
  192. blog(LOG_INFO, "WASAPI: Device '%s' initialized", device_name.c_str());
  193. }
  194. void WASAPISource::Initialize()
  195. {
  196. ComPtr<IMMDeviceEnumerator> enumerator;
  197. HRESULT res;
  198. res = CoCreateInstance(__uuidof(MMDeviceEnumerator),
  199. nullptr, CLSCTX_ALL,
  200. __uuidof(IMMDeviceEnumerator),
  201. (void**)enumerator.Assign());
  202. if (FAILED(res))
  203. throw HRError("Failed to create enumerator", res);
  204. if (!InitDevice(enumerator))
  205. return;
  206. device_name = GetDeviceName(device);
  207. InitClient();
  208. InitCapture();
  209. }
  210. bool WASAPISource::TryInitialize()
  211. {
  212. try {
  213. Initialize();
  214. } catch (HRError error) {
  215. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  216. device_name.empty() ?
  217. device_id.c_str() : device_name.c_str(),
  218. error.str, error.hr);
  219. } catch (const char *error) {
  220. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  221. device_name.empty() ?
  222. device_id.c_str() : device_name.c_str(),
  223. error);
  224. }
  225. return active;
  226. }
  227. void WASAPISource::Reconnect()
  228. {
  229. reconnecting = true;
  230. reconnectThread = CreateThread(nullptr, 0,
  231. WASAPISource::ReconnectThread, this,
  232. 0, nullptr);
  233. if (!reconnectThread.Valid())
  234. blog(LOG_WARNING, "[WASAPISource::Reconnect] "
  235. "Failed to intiialize reconnect thread: %d",
  236. GetLastError());
  237. }
  238. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  239. {
  240. return WaitForSingleObject(handle, time) == WAIT_TIMEOUT;
  241. }
  242. #define RECONNECT_INTERVAL 3000
  243. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  244. {
  245. WASAPISource *source = (WASAPISource*)param;
  246. os_set_thread_name("win-wasapi: reconnect thread");
  247. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  248. if (source->TryInitialize())
  249. break;
  250. }
  251. source->reconnectThread = nullptr;
  252. source->reconnecting = false;
  253. return 0;
  254. }
  255. bool WASAPISource::ProcessCaptureData()
  256. {
  257. HRESULT res;
  258. LPBYTE buffer;
  259. UINT32 frames;
  260. DWORD flags;
  261. UINT64 pos, ts;
  262. UINT captureSize = 0;
  263. while (true) {
  264. res = capture->GetNextPacketSize(&captureSize);
  265. if (FAILED(res)) {
  266. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  267. blog(LOG_WARNING,
  268. "[WASAPISource::GetCaptureData]"
  269. " capture->GetNextPacketSize"
  270. " failed: %lX", res);
  271. return false;
  272. }
  273. if (!captureSize)
  274. break;
  275. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  276. if (FAILED(res)) {
  277. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  278. blog(LOG_WARNING,
  279. "[WASAPISource::GetCaptureData]"
  280. " capture->GetBuffer"
  281. " failed: %lX", res);
  282. return false;
  283. }
  284. obs_source_audio data = {};
  285. data.data[0] = (const uint8_t*)buffer;
  286. data.frames = (uint32_t)frames;
  287. data.speakers = speakers;
  288. data.samples_per_sec = sampleRate;
  289. data.format = format;
  290. data.timestamp = useDeviceTiming ?
  291. ts*100 : os_gettime_ns();
  292. obs_source_output_audio(source, &data);
  293. capture->ReleaseBuffer(frames);
  294. }
  295. return true;
  296. }
  297. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  298. DWORD duration)
  299. {
  300. DWORD ret;
  301. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  302. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  303. }
  304. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  305. {
  306. WASAPISource *source = (WASAPISource*)param;
  307. bool reconnect = false;
  308. /* Output devices don't signal, so just make it check every 10 ms */
  309. DWORD dur = source->isInputDevice ? INFINITE : 10;
  310. HANDLE sigs[2] = {
  311. source->receiveSignal,
  312. source->stopSignal
  313. };
  314. os_set_thread_name("win-wasapi: capture thread");
  315. while (WaitForCaptureSignal(2, sigs, dur)) {
  316. if (!source->ProcessCaptureData()) {
  317. reconnect = true;
  318. break;
  319. }
  320. }
  321. source->client->Stop();
  322. source->captureThread = nullptr;
  323. source->active = false;
  324. if (reconnect) {
  325. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  326. source->device_name.c_str());
  327. source->Reconnect();
  328. }
  329. return 0;
  330. }
  331. /* ------------------------------------------------------------------------- */
  332. static const char *GetWASAPIInputName(void)
  333. {
  334. return obs_module_text("AudioInput");
  335. }
  336. static const char *GetWASAPIOutputName(void)
  337. {
  338. return obs_module_text("AudioOutput");
  339. }
  340. static void GetWASAPIDefaults(obs_data_t *settings)
  341. {
  342. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  343. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  344. }
  345. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  346. bool input)
  347. {
  348. try {
  349. return new WASAPISource(settings, source, input);
  350. } catch (const char *error) {
  351. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  352. }
  353. return nullptr;
  354. }
  355. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  356. {
  357. return CreateWASAPISource(settings, source, true);
  358. }
  359. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  360. {
  361. return CreateWASAPISource(settings, source, false);
  362. }
  363. static void DestroyWASAPISource(void *obj)
  364. {
  365. delete static_cast<WASAPISource*>(obj);
  366. }
  367. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  368. {
  369. static_cast<WASAPISource*>(obj)->Update(settings);
  370. }
  371. static obs_properties_t *GetWASAPIProperties(bool input)
  372. {
  373. obs_properties_t *props = obs_properties_create();
  374. vector<AudioDeviceInfo> devices;
  375. /* TODO: translate */
  376. obs_property_t *device_prop = obs_properties_add_list(props,
  377. OPT_DEVICE_ID, obs_module_text("Device"),
  378. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  379. GetWASAPIAudioDevices(devices, input);
  380. if (devices.size())
  381. obs_property_list_add_string(device_prop,
  382. obs_module_text("Default"), "default");
  383. for (size_t i = 0; i < devices.size(); i++) {
  384. AudioDeviceInfo &device = devices[i];
  385. obs_property_list_add_string(device_prop,
  386. device.name.c_str(), device.id.c_str());
  387. }
  388. obs_property_t *prop;
  389. prop = obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  390. obs_module_text("UseDeviceTiming"));
  391. return props;
  392. }
  393. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  394. {
  395. return GetWASAPIProperties(true);
  396. }
  397. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  398. {
  399. return GetWASAPIProperties(false);
  400. }
  401. void RegisterWASAPIInput()
  402. {
  403. obs_source_info info = {};
  404. info.id = "wasapi_input_capture";
  405. info.type = OBS_SOURCE_TYPE_INPUT;
  406. info.output_flags = OBS_SOURCE_AUDIO;
  407. info.get_name = GetWASAPIInputName;
  408. info.create = CreateWASAPIInput;
  409. info.destroy = DestroyWASAPISource;
  410. info.update = UpdateWASAPISource;
  411. info.get_defaults = GetWASAPIDefaults;
  412. info.get_properties = GetWASAPIPropertiesInput;
  413. obs_register_source(&info);
  414. }
  415. void RegisterWASAPIOutput()
  416. {
  417. obs_source_info info = {};
  418. info.id = "wasapi_output_capture";
  419. info.type = OBS_SOURCE_TYPE_INPUT;
  420. info.output_flags = OBS_SOURCE_AUDIO;
  421. info.get_name = GetWASAPIOutputName;
  422. info.create = CreateWASAPIOutput;
  423. info.destroy = DestroyWASAPISource;
  424. info.update = UpdateWASAPISource;
  425. info.get_defaults = GetWASAPIDefaults;
  426. info.get_properties = GetWASAPIPropertiesOutput;
  427. obs_register_source(&info);
  428. }