win-wasapi.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. #include "enum-wasapi.hpp"
  2. #include <obs.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. static void GetWASAPIDefaults(obs_data_t settings);
  10. #define KSAUDIO_SPEAKER_4POINT1 (KSAUDIO_SPEAKER_QUAD|SPEAKER_LOW_FREQUENCY)
  11. #define KSAUDIO_SPEAKER_2POINT1 (KSAUDIO_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY)
  12. class WASAPISource {
  13. ComPtr<IMMDevice> device;
  14. ComPtr<IAudioClient> client;
  15. ComPtr<IAudioCaptureClient> capture;
  16. obs_source_t source;
  17. string device_id;
  18. string device_name;
  19. bool isInputDevice;
  20. bool useDeviceTiming;
  21. bool isDefaultDevice;
  22. bool reconnecting;
  23. WinHandle reconnectThread;
  24. bool active;
  25. WinHandle captureThread;
  26. WinHandle stopSignal;
  27. WinHandle receiveSignal;
  28. speaker_layout speakers;
  29. audio_format format;
  30. uint32_t sampleRate;
  31. static DWORD WINAPI ReconnectThread(LPVOID param);
  32. static DWORD WINAPI CaptureThread(LPVOID param);
  33. bool ProcessCaptureData();
  34. inline void Start();
  35. inline void Stop();
  36. void Reconnect();
  37. bool InitDevice(IMMDeviceEnumerator *enumerator);
  38. void InitName();
  39. void InitClient();
  40. void InitFormat(WAVEFORMATEX *wfex);
  41. void InitCapture();
  42. void Initialize();
  43. bool TryInitialize();
  44. void UpdateSettings(obs_data_t settings);
  45. public:
  46. WASAPISource(obs_data_t settings, obs_source_t source_, bool input);
  47. inline ~WASAPISource();
  48. void Update(obs_data_t settings);
  49. };
  50. WASAPISource::WASAPISource(obs_data_t settings, obs_source_t source_,
  51. bool input)
  52. : reconnecting (false),
  53. active (false),
  54. reconnectThread (nullptr),
  55. captureThread (nullptr),
  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_getstring(settings, "device_id");
  96. useDeviceTiming = obs_data_getbool(settings, "useDeviceTiming");
  97. isDefaultDevice = _strcmpi(device_id.c_str(), "default") == 0;
  98. }
  99. void WASAPISource::Update(obs_data_t settings)
  100. {
  101. string newDevice = obs_data_getstring(settings, "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. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  213. device_name.empty() ?
  214. device_id.c_str() : device_name.c_str(),
  215. error.str, error.hr);
  216. } catch (const char *error) {
  217. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  218. device_name.empty() ?
  219. device_id.c_str() : device_name.c_str(),
  220. error);
  221. }
  222. return active;
  223. }
  224. void WASAPISource::Reconnect()
  225. {
  226. reconnecting = true;
  227. reconnectThread = CreateThread(nullptr, 0,
  228. WASAPISource::ReconnectThread, this,
  229. 0, nullptr);
  230. if (!reconnectThread.Valid())
  231. blog(LOG_WARNING, "[WASAPISource::Reconnect] "
  232. "Failed to intiialize reconnect thread: %d",
  233. GetLastError());
  234. }
  235. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  236. {
  237. return WaitForSingleObject(handle, time) == WAIT_TIMEOUT;
  238. }
  239. #define RECONNECT_INTERVAL 3000
  240. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  241. {
  242. WASAPISource *source = (WASAPISource*)param;
  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. 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. while (WaitForCaptureSignal(2, sigs, dur)) {
  311. if (!source->ProcessCaptureData()) {
  312. reconnect = true;
  313. break;
  314. }
  315. }
  316. source->client->Stop();
  317. source->captureThread = nullptr;
  318. source->active = false;
  319. if (reconnect) {
  320. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  321. source->device_name.c_str());
  322. source->Reconnect();
  323. }
  324. return 0;
  325. }
  326. /* ------------------------------------------------------------------------- */
  327. static const char *GetWASAPIInputName(void)
  328. {
  329. /* TODO: translate */
  330. return "Audio Input Capture (WASAPI)";
  331. }
  332. static const char *GetWASAPIOutputName(void)
  333. {
  334. /* TODO: translate */
  335. return "Audio Output Capture (WASAPI)";
  336. }
  337. static void GetWASAPIDefaults(obs_data_t settings)
  338. {
  339. obs_data_set_default_string(settings, "device_id", "default");
  340. obs_data_set_default_bool(settings, "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. "device_id", "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, "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_property_t prop;
  385. prop = obs_properties_add_bool(props, "use_device_timing",
  386. "Use Device Timing");
  387. return props;
  388. }
  389. static obs_properties_t GetWASAPIPropertiesInput(void)
  390. {
  391. return GetWASAPIProperties(true);
  392. }
  393. static obs_properties_t GetWASAPIPropertiesOutput(void)
  394. {
  395. return GetWASAPIProperties(false);
  396. }
  397. void RegisterWASAPIInput()
  398. {
  399. obs_source_info info = {};
  400. info.id = "wasapi_input_capture";
  401. info.type = OBS_SOURCE_TYPE_INPUT;
  402. info.output_flags = OBS_SOURCE_AUDIO;
  403. info.getname = GetWASAPIInputName;
  404. info.create = CreateWASAPIInput;
  405. info.destroy = DestroyWASAPISource;
  406. info.update = UpdateWASAPISource;
  407. info.defaults = GetWASAPIDefaults;
  408. info.properties = GetWASAPIPropertiesInput;
  409. obs_register_source(&info);
  410. }
  411. void RegisterWASAPIOutput()
  412. {
  413. obs_source_info info = {};
  414. info.id = "wasapi_output_capture";
  415. info.type = OBS_SOURCE_TYPE_INPUT;
  416. info.output_flags = OBS_SOURCE_AUDIO;
  417. info.getname = GetWASAPIOutputName;
  418. info.create = CreateWASAPIOutput;
  419. info.destroy = DestroyWASAPISource;
  420. info.update = UpdateWASAPISource;
  421. info.defaults = GetWASAPIDefaults;
  422. info.properties = GetWASAPIPropertiesOutput;
  423. obs_register_source(&info);
  424. }