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