win-wasapi.cpp 12 KB

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