win-wasapi.cpp 12 KB

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