win-wasapi.cpp 12 KB

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