win-wasapi.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. #include "enum-wasapi.hpp"
  2. #include <obs-module.h>
  3. #include <obs.h>
  4. #include <util/platform.h>
  5. #include <util/windows/HRError.hpp>
  6. #include <util/windows/ComPtr.hpp>
  7. #include <util/windows/WinHandle.hpp>
  8. #include <util/windows/CoTaskMemPtr.hpp>
  9. #include <util/threading.h>
  10. #include <util/util_uint64.h>
  11. #include <cinttypes>
  12. #include <thread>
  13. using namespace std;
  14. #define OPT_DEVICE_ID "device_id"
  15. #define OPT_USE_DEVICE_TIMING "use_device_timing"
  16. static void GetWASAPIDefaults(obs_data_t *settings);
  17. #define OBS_KSAUDIO_SPEAKER_4POINT1 \
  18. (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY)
  19. class WASAPISource {
  20. ComPtr<IMMNotificationClient> notify;
  21. ComPtr<IMMDeviceEnumerator> enumerator;
  22. ComPtr<IAudioClient> client;
  23. ComPtr<IAudioCaptureClient> capture;
  24. obs_source_t *source;
  25. wstring default_id;
  26. string device_id;
  27. string device_name;
  28. uint64_t lastNotifyTime = 0;
  29. bool isInputDevice;
  30. bool useDeviceTiming = false;
  31. bool isDefaultDevice = false;
  32. bool reconnecting = false;
  33. bool previouslyFailed = false;
  34. WinHandle reconnectThread;
  35. bool active = false;
  36. WinHandle captureThread;
  37. WinHandle stopSignal;
  38. WinHandle receiveSignal;
  39. speaker_layout speakers;
  40. audio_format format;
  41. uint32_t sampleRate;
  42. static DWORD WINAPI ReconnectThread(LPVOID param);
  43. static DWORD WINAPI CaptureThread(LPVOID param);
  44. bool ProcessCaptureData();
  45. void Start();
  46. void Stop();
  47. void Reconnect();
  48. static ComPtr<IMMDevice> InitDevice(IMMDeviceEnumerator *enumerator,
  49. bool isDefaultDevice,
  50. bool isInputDevice,
  51. const string device_id,
  52. wstring &default_id);
  53. static ComPtr<IAudioClient> InitClient(IMMDevice *device,
  54. bool isInputDevice,
  55. enum speaker_layout &speakers,
  56. enum audio_format &format,
  57. uint32_t &sampleRate);
  58. static void InitFormat(const WAVEFORMATEX *wfex,
  59. enum speaker_layout &speakers,
  60. enum audio_format &format, uint32_t &sampleRate);
  61. static void ClearBuffer(IMMDevice *device);
  62. static ComPtr<IAudioCaptureClient> InitCapture(IAudioClient *client,
  63. HANDLE receiveSignal);
  64. void Initialize();
  65. bool TryInitialize();
  66. void UpdateSettings(obs_data_t *settings);
  67. public:
  68. WASAPISource(obs_data_t *settings, obs_source_t *source_, bool input);
  69. ~WASAPISource();
  70. void Update(obs_data_t *settings);
  71. void SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id);
  72. };
  73. class WASAPINotify : public IMMNotificationClient {
  74. long refs = 0; /* auto-incremented to 1 by ComPtr */
  75. WASAPISource *source;
  76. public:
  77. WASAPINotify(WASAPISource *source_) : source(source_) {}
  78. STDMETHODIMP_(ULONG) AddRef()
  79. {
  80. return (ULONG)os_atomic_inc_long(&refs);
  81. }
  82. STDMETHODIMP_(ULONG) STDMETHODCALLTYPE Release()
  83. {
  84. long val = os_atomic_dec_long(&refs);
  85. if (val == 0)
  86. delete this;
  87. return (ULONG)val;
  88. }
  89. STDMETHODIMP QueryInterface(REFIID riid, void **ptr)
  90. {
  91. if (riid == IID_IUnknown) {
  92. *ptr = (IUnknown *)this;
  93. } else if (riid == __uuidof(IMMNotificationClient)) {
  94. *ptr = (IMMNotificationClient *)this;
  95. } else {
  96. *ptr = nullptr;
  97. return E_NOINTERFACE;
  98. }
  99. os_atomic_inc_long(&refs);
  100. return S_OK;
  101. }
  102. STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role,
  103. LPCWSTR id)
  104. {
  105. source->SetDefaultDevice(flow, role, id);
  106. return S_OK;
  107. }
  108. STDMETHODIMP OnDeviceAdded(LPCWSTR) { return S_OK; }
  109. STDMETHODIMP OnDeviceRemoved(LPCWSTR) { return S_OK; }
  110. STDMETHODIMP OnDeviceStateChanged(LPCWSTR, DWORD) { return S_OK; }
  111. STDMETHODIMP OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY)
  112. {
  113. return S_OK;
  114. }
  115. };
  116. WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
  117. bool input)
  118. : source(source_), isInputDevice(input)
  119. {
  120. UpdateSettings(settings);
  121. stopSignal = CreateEvent(nullptr, true, false, nullptr);
  122. if (!stopSignal.Valid())
  123. throw "Could not create stop signal";
  124. receiveSignal = CreateEvent(nullptr, false, false, nullptr);
  125. if (!receiveSignal.Valid())
  126. throw "Could not create receive signal";
  127. notify = new WASAPINotify(this);
  128. if (!notify)
  129. throw "Could not create WASAPINotify";
  130. HRESULT res = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
  131. CLSCTX_ALL,
  132. IID_PPV_ARGS(enumerator.Assign()));
  133. if (FAILED(res))
  134. throw HRError("Failed to create enumerator", res);
  135. res = enumerator->RegisterEndpointNotificationCallback(notify);
  136. if (FAILED(res))
  137. throw HRError("Failed to register endpoint callback", res);
  138. Start();
  139. }
  140. void WASAPISource::Start()
  141. {
  142. if (!TryInitialize()) {
  143. blog(LOG_INFO, "WASAPI: Device '%s' failed to start",
  144. device_id.c_str());
  145. Reconnect();
  146. }
  147. }
  148. void WASAPISource::Stop()
  149. {
  150. SetEvent(stopSignal);
  151. if (active) {
  152. blog(LOG_INFO, "WASAPI: Device '%s' Terminated",
  153. device_name.c_str());
  154. WaitForSingleObject(captureThread, INFINITE);
  155. }
  156. if (reconnecting)
  157. WaitForSingleObject(reconnectThread, INFINITE);
  158. ResetEvent(stopSignal);
  159. capture.Clear();
  160. client.Clear();
  161. }
  162. WASAPISource::~WASAPISource()
  163. {
  164. enumerator->UnregisterEndpointNotificationCallback(notify);
  165. Stop();
  166. }
  167. void WASAPISource::UpdateSettings(obs_data_t *settings)
  168. {
  169. device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
  170. useDeviceTiming = obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
  171. isDefaultDevice = _strcmpi(device_id.c_str(), "default") == 0;
  172. }
  173. void WASAPISource::Update(obs_data_t *settings)
  174. {
  175. string newDevice = obs_data_get_string(settings, OPT_DEVICE_ID);
  176. bool restart = newDevice.compare(device_id) != 0;
  177. if (restart)
  178. Stop();
  179. UpdateSettings(settings);
  180. if (restart)
  181. Start();
  182. }
  183. ComPtr<IMMDevice> WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator,
  184. bool isDefaultDevice,
  185. bool isInputDevice,
  186. const string device_id,
  187. wstring &default_id)
  188. {
  189. ComPtr<IMMDevice> device;
  190. if (isDefaultDevice) {
  191. HRESULT res = enumerator->GetDefaultAudioEndpoint(
  192. isInputDevice ? eCapture : eRender,
  193. isInputDevice ? eCommunications : eConsole,
  194. device.Assign());
  195. if (FAILED(res))
  196. throw HRError("Failed GetDefaultAudioEndpoint", res);
  197. CoTaskMemPtr<wchar_t> id;
  198. res = device->GetId(&id);
  199. if (FAILED(res))
  200. throw HRError("Failed to get default id", res);
  201. default_id = id;
  202. } else {
  203. wchar_t *w_id;
  204. os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
  205. if (!w_id)
  206. throw "Failed to widen device id string";
  207. const HRESULT res =
  208. enumerator->GetDevice(w_id, device.Assign());
  209. bfree(w_id);
  210. if (FAILED(res))
  211. throw HRError("Failed to enumerate device", res);
  212. }
  213. return device;
  214. }
  215. #define BUFFER_TIME_100NS (5 * 10000000)
  216. ComPtr<IAudioClient> WASAPISource::InitClient(IMMDevice *device,
  217. bool isInputDevice,
  218. enum speaker_layout &speakers,
  219. enum audio_format &format,
  220. uint32_t &sampleRate)
  221. {
  222. ComPtr<IAudioClient> client;
  223. HRESULT res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
  224. nullptr, (void **)client.Assign());
  225. if (FAILED(res))
  226. throw HRError("Failed to activate client context", res);
  227. CoTaskMemPtr<WAVEFORMATEX> wfex;
  228. res = client->GetMixFormat(&wfex);
  229. if (FAILED(res))
  230. throw HRError("Failed to get mix format", res);
  231. InitFormat(wfex, speakers, format, sampleRate);
  232. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  233. if (!isInputDevice)
  234. flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
  235. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags,
  236. BUFFER_TIME_100NS, 0, wfex, nullptr);
  237. if (FAILED(res))
  238. throw HRError("Failed to initialize audio client", res);
  239. return client;
  240. }
  241. void WASAPISource::ClearBuffer(IMMDevice *device)
  242. {
  243. CoTaskMemPtr<WAVEFORMATEX> wfex;
  244. HRESULT res;
  245. LPBYTE buffer;
  246. UINT32 frames;
  247. ComPtr<IAudioClient> client;
  248. res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
  249. (void **)client.Assign());
  250. if (FAILED(res))
  251. throw HRError("Failed to activate client context", res);
  252. res = client->GetMixFormat(&wfex);
  253. if (FAILED(res))
  254. throw HRError("Failed to get mix format", res);
  255. res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS,
  256. 0, wfex, nullptr);
  257. if (FAILED(res))
  258. throw HRError("Failed to initialize audio client", res);
  259. /* Silent loopback fix. Prevents audio stream from stopping and */
  260. /* messing up timestamps and other weird glitches during silence */
  261. /* by playing a silent sample all over again. */
  262. res = client->GetBufferSize(&frames);
  263. if (FAILED(res))
  264. throw HRError("Failed to get buffer size", res);
  265. ComPtr<IAudioRenderClient> render;
  266. res = client->GetService(IID_PPV_ARGS(render.Assign()));
  267. if (FAILED(res))
  268. throw HRError("Failed to get render client", res);
  269. res = render->GetBuffer(frames, &buffer);
  270. if (FAILED(res))
  271. throw HRError("Failed to get buffer", res);
  272. memset(buffer, 0, (size_t)frames * (size_t)wfex->nBlockAlign);
  273. render->ReleaseBuffer(frames, 0);
  274. }
  275. static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
  276. {
  277. switch (layout) {
  278. case KSAUDIO_SPEAKER_2POINT1:
  279. return SPEAKERS_2POINT1;
  280. case KSAUDIO_SPEAKER_SURROUND:
  281. return SPEAKERS_4POINT0;
  282. case OBS_KSAUDIO_SPEAKER_4POINT1:
  283. return SPEAKERS_4POINT1;
  284. case KSAUDIO_SPEAKER_5POINT1_SURROUND:
  285. return SPEAKERS_5POINT1;
  286. case KSAUDIO_SPEAKER_7POINT1_SURROUND:
  287. return SPEAKERS_7POINT1;
  288. }
  289. return (speaker_layout)channels;
  290. }
  291. void WASAPISource::InitFormat(const WAVEFORMATEX *wfex,
  292. enum speaker_layout &speakers,
  293. enum audio_format &format, uint32_t &sampleRate)
  294. {
  295. DWORD layout = 0;
  296. if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  297. WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex;
  298. layout = ext->dwChannelMask;
  299. }
  300. /* WASAPI is always float */
  301. speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
  302. format = AUDIO_FORMAT_FLOAT;
  303. sampleRate = wfex->nSamplesPerSec;
  304. }
  305. ComPtr<IAudioCaptureClient> WASAPISource::InitCapture(IAudioClient *client,
  306. HANDLE receiveSignal)
  307. {
  308. ComPtr<IAudioCaptureClient> capture;
  309. HRESULT res = client->GetService(IID_PPV_ARGS(capture.Assign()));
  310. if (FAILED(res))
  311. throw HRError("Failed to create capture context", res);
  312. res = client->SetEventHandle(receiveSignal);
  313. if (FAILED(res))
  314. throw HRError("Failed to set event handle", res);
  315. res = client->Start();
  316. if (FAILED(res))
  317. throw HRError("Failed to start capture client", res);
  318. return capture;
  319. }
  320. void WASAPISource::Initialize()
  321. {
  322. ComPtr<IMMDevice> device = InitDevice(enumerator, isDefaultDevice,
  323. isInputDevice, device_id,
  324. default_id);
  325. device_name = GetDeviceName(device);
  326. ComPtr<IAudioClient> temp_client =
  327. InitClient(device, isInputDevice, speakers, format, sampleRate);
  328. if (!isInputDevice)
  329. ClearBuffer(device);
  330. ComPtr<IAudioCaptureClient> temp_capture =
  331. InitCapture(temp_client, receiveSignal);
  332. client = std::move(temp_client);
  333. capture = std::move(temp_capture);
  334. captureThread = CreateThread(nullptr, 0, WASAPISource::CaptureThread,
  335. this, 0, nullptr);
  336. if (!captureThread.Valid()) {
  337. capture.Clear();
  338. client.Clear();
  339. throw "Failed to create capture thread";
  340. }
  341. active = true;
  342. blog(LOG_INFO, "WASAPI: Device '%s' [%" PRIu32 " Hz] initialized",
  343. device_name.c_str(), sampleRate);
  344. }
  345. bool WASAPISource::TryInitialize()
  346. {
  347. try {
  348. Initialize();
  349. } catch (HRError &error) {
  350. if (previouslyFailed)
  351. return active;
  352. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX",
  353. device_name.empty() ? device_id.c_str()
  354. : device_name.c_str(),
  355. error.str, error.hr);
  356. } catch (const char *error) {
  357. if (previouslyFailed)
  358. return active;
  359. blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s",
  360. device_name.empty() ? device_id.c_str()
  361. : device_name.c_str(),
  362. error);
  363. }
  364. previouslyFailed = !active;
  365. return active;
  366. }
  367. void WASAPISource::Reconnect()
  368. {
  369. reconnecting = true;
  370. reconnectThread = CreateThread(
  371. nullptr, 0, WASAPISource::ReconnectThread, this, 0, nullptr);
  372. if (!reconnectThread.Valid())
  373. blog(LOG_WARNING,
  374. "[WASAPISource::Reconnect] "
  375. "Failed to initialize reconnect thread: %lu",
  376. GetLastError());
  377. }
  378. static inline bool WaitForSignal(HANDLE handle, DWORD time)
  379. {
  380. return WaitForSingleObject(handle, time) != WAIT_TIMEOUT;
  381. }
  382. #define RECONNECT_INTERVAL 3000
  383. DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
  384. {
  385. WASAPISource *source = (WASAPISource *)param;
  386. os_set_thread_name("win-wasapi: reconnect thread");
  387. const HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
  388. const bool com_initialized = SUCCEEDED(hr);
  389. if (!com_initialized) {
  390. blog(LOG_ERROR,
  391. "[WASAPISource::ReconnectThread]"
  392. " CoInitializeEx failed: 0x%08X",
  393. hr);
  394. }
  395. while (!WaitForSignal(source->stopSignal, RECONNECT_INTERVAL)) {
  396. if (source->TryInitialize())
  397. break;
  398. }
  399. if (com_initialized)
  400. CoUninitialize();
  401. source->reconnectThread = nullptr;
  402. source->reconnecting = false;
  403. return 0;
  404. }
  405. bool WASAPISource::ProcessCaptureData()
  406. {
  407. HRESULT res;
  408. LPBYTE buffer;
  409. UINT32 frames;
  410. DWORD flags;
  411. UINT64 pos, ts;
  412. UINT captureSize = 0;
  413. while (true) {
  414. res = capture->GetNextPacketSize(&captureSize);
  415. if (FAILED(res)) {
  416. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  417. blog(LOG_WARNING,
  418. "[WASAPISource::ProcessCaptureData]"
  419. " capture->GetNextPacketSize"
  420. " failed: %lX",
  421. res);
  422. return false;
  423. }
  424. if (!captureSize)
  425. break;
  426. res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
  427. if (FAILED(res)) {
  428. if (res != AUDCLNT_E_DEVICE_INVALIDATED)
  429. blog(LOG_WARNING,
  430. "[WASAPISource::ProcessCaptureData]"
  431. " capture->GetBuffer"
  432. " failed: %lX",
  433. res);
  434. return false;
  435. }
  436. obs_source_audio data = {};
  437. data.data[0] = (const uint8_t *)buffer;
  438. data.frames = (uint32_t)frames;
  439. data.speakers = speakers;
  440. data.samples_per_sec = sampleRate;
  441. data.format = format;
  442. data.timestamp = useDeviceTiming ? ts * 100 : os_gettime_ns();
  443. if (!useDeviceTiming)
  444. data.timestamp -= util_mul_div64(frames, 1000000000ULL,
  445. sampleRate);
  446. obs_source_output_audio(source, &data);
  447. capture->ReleaseBuffer(frames);
  448. }
  449. return true;
  450. }
  451. static inline bool WaitForCaptureSignal(DWORD numSignals, const HANDLE *signals,
  452. DWORD duration)
  453. {
  454. DWORD ret;
  455. ret = WaitForMultipleObjects(numSignals, signals, false, duration);
  456. return ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT;
  457. }
  458. DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
  459. {
  460. WASAPISource *source = (WASAPISource *)param;
  461. bool reconnect = false;
  462. /* Output devices don't signal, so just make it check every 10 ms */
  463. DWORD dur = source->isInputDevice ? RECONNECT_INTERVAL : 10;
  464. HANDLE sigs[2] = {source->receiveSignal, source->stopSignal};
  465. os_set_thread_name("win-wasapi: capture thread");
  466. while (WaitForCaptureSignal(2, sigs, dur)) {
  467. if (!source->ProcessCaptureData()) {
  468. reconnect = true;
  469. break;
  470. }
  471. }
  472. source->client->Stop();
  473. source->captureThread = nullptr;
  474. source->active = false;
  475. if (reconnect) {
  476. blog(LOG_INFO, "Device '%s' invalidated. Retrying",
  477. source->device_name.c_str());
  478. source->Reconnect();
  479. }
  480. return 0;
  481. }
  482. void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id)
  483. {
  484. if (!isDefaultDevice)
  485. return;
  486. EDataFlow expectedFlow = isInputDevice ? eCapture : eRender;
  487. ERole expectedRole = isInputDevice ? eCommunications : eConsole;
  488. if (flow != expectedFlow || role != expectedRole)
  489. return;
  490. if (id && default_id.compare(id) == 0)
  491. return;
  492. blog(LOG_INFO, "WASAPI: Default %s device changed",
  493. isInputDevice ? "input" : "output");
  494. /* reset device only once every 300ms */
  495. uint64_t t = os_gettime_ns();
  496. if (t - lastNotifyTime < 300000000)
  497. return;
  498. std::thread([this]() {
  499. Stop();
  500. Start();
  501. }).detach();
  502. lastNotifyTime = t;
  503. }
  504. /* ------------------------------------------------------------------------- */
  505. static const char *GetWASAPIInputName(void *)
  506. {
  507. return obs_module_text("AudioInput");
  508. }
  509. static const char *GetWASAPIOutputName(void *)
  510. {
  511. return obs_module_text("AudioOutput");
  512. }
  513. static void GetWASAPIDefaultsInput(obs_data_t *settings)
  514. {
  515. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  516. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
  517. }
  518. static void GetWASAPIDefaultsOutput(obs_data_t *settings)
  519. {
  520. obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
  521. obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
  522. }
  523. static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
  524. bool input)
  525. {
  526. try {
  527. return new WASAPISource(settings, source, input);
  528. } catch (const char *error) {
  529. blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
  530. }
  531. return nullptr;
  532. }
  533. static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
  534. {
  535. return CreateWASAPISource(settings, source, true);
  536. }
  537. static void *CreateWASAPIOutput(obs_data_t *settings, obs_source_t *source)
  538. {
  539. return CreateWASAPISource(settings, source, false);
  540. }
  541. static void DestroyWASAPISource(void *obj)
  542. {
  543. delete static_cast<WASAPISource *>(obj);
  544. }
  545. static void UpdateWASAPISource(void *obj, obs_data_t *settings)
  546. {
  547. static_cast<WASAPISource *>(obj)->Update(settings);
  548. }
  549. static obs_properties_t *GetWASAPIProperties(bool input)
  550. {
  551. obs_properties_t *props = obs_properties_create();
  552. vector<AudioDeviceInfo> devices;
  553. obs_property_t *device_prop = obs_properties_add_list(
  554. props, OPT_DEVICE_ID, obs_module_text("Device"),
  555. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  556. GetWASAPIAudioDevices(devices, input);
  557. if (devices.size())
  558. obs_property_list_add_string(
  559. device_prop, obs_module_text("Default"), "default");
  560. for (size_t i = 0; i < devices.size(); i++) {
  561. AudioDeviceInfo &device = devices[i];
  562. obs_property_list_add_string(device_prop, device.name.c_str(),
  563. device.id.c_str());
  564. }
  565. obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
  566. obs_module_text("UseDeviceTiming"));
  567. return props;
  568. }
  569. static obs_properties_t *GetWASAPIPropertiesInput(void *)
  570. {
  571. return GetWASAPIProperties(true);
  572. }
  573. static obs_properties_t *GetWASAPIPropertiesOutput(void *)
  574. {
  575. return GetWASAPIProperties(false);
  576. }
  577. void RegisterWASAPIInput()
  578. {
  579. obs_source_info info = {};
  580. info.id = "wasapi_input_capture";
  581. info.type = OBS_SOURCE_TYPE_INPUT;
  582. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  583. info.get_name = GetWASAPIInputName;
  584. info.create = CreateWASAPIInput;
  585. info.destroy = DestroyWASAPISource;
  586. info.update = UpdateWASAPISource;
  587. info.get_defaults = GetWASAPIDefaultsInput;
  588. info.get_properties = GetWASAPIPropertiesInput;
  589. info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
  590. obs_register_source(&info);
  591. }
  592. void RegisterWASAPIOutput()
  593. {
  594. obs_source_info info = {};
  595. info.id = "wasapi_output_capture";
  596. info.type = OBS_SOURCE_TYPE_INPUT;
  597. info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  598. OBS_SOURCE_DO_NOT_SELF_MONITOR;
  599. info.get_name = GetWASAPIOutputName;
  600. info.create = CreateWASAPIOutput;
  601. info.destroy = DestroyWASAPISource;
  602. info.update = UpdateWASAPISource;
  603. info.get_defaults = GetWASAPIDefaultsOutput;
  604. info.get_properties = GetWASAPIPropertiesOutput;
  605. info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
  606. obs_register_source(&info);
  607. }