123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635 |
- #include "enum-wasapi.hpp"
- #include <obs-module.h>
- #include <obs.h>
- #include <util/dstr.h>
- #include <util/platform.h>
- #include <util/windows/HRError.hpp>
- #include <util/windows/ComPtr.hpp>
- #include <util/windows/WinHandle.hpp>
- #include <util/windows/CoTaskMemPtr.hpp>
- #include <util/windows/win-version.h>
- #include <util/windows/window-helpers.h>
- #include <util/threading.h>
- #include <util/util_uint64.h>
- #include <atomic>
- #include <cinttypes>
- #include <audioclientactivationparams.h>
- #include <avrt.h>
- #include <RTWorkQ.h>
- #include <wrl/implements.h>
- using namespace std;
- #define OPT_DEVICE_ID "device_id"
- #define OPT_USE_DEVICE_TIMING "use_device_timing"
- #define OPT_WINDOW "window"
- #define OPT_PRIORITY "priority"
- static void GetWASAPIDefaults(obs_data_t *settings);
- #define OBS_KSAUDIO_SPEAKER_4POINT1 \
- (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY)
- typedef HRESULT(STDAPICALLTYPE *PFN_ActivateAudioInterfaceAsync)(
- LPCWSTR, REFIID, PROPVARIANT *,
- IActivateAudioInterfaceCompletionHandler *,
- IActivateAudioInterfaceAsyncOperation **);
- typedef HRESULT(STDAPICALLTYPE *PFN_RtwqUnlockWorkQueue)(DWORD);
- typedef HRESULT(STDAPICALLTYPE *PFN_RtwqLockSharedWorkQueue)(PCWSTR usageClass,
- LONG basePriority,
- DWORD *taskId,
- DWORD *id);
- typedef HRESULT(STDAPICALLTYPE *PFN_RtwqCreateAsyncResult)(IUnknown *,
- IRtwqAsyncCallback *,
- IUnknown *,
- IRtwqAsyncResult **);
- typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWorkItem)(DWORD, LONG,
- IRtwqAsyncResult *);
- typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWaitingWorkItem)(HANDLE, LONG,
- IRtwqAsyncResult *,
- RTWQWORKITEM_KEY *);
- class WASAPIActivateAudioInterfaceCompletionHandler
- : public Microsoft::WRL::RuntimeClass<
- Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
- Microsoft::WRL::FtmBase,
- IActivateAudioInterfaceCompletionHandler> {
- IUnknown *unknown;
- HRESULT activationResult;
- WinHandle activationSignal;
- public:
- WASAPIActivateAudioInterfaceCompletionHandler();
- HRESULT GetActivateResult(IAudioClient **client);
- private:
- virtual HRESULT STDMETHODCALLTYPE ActivateCompleted(
- IActivateAudioInterfaceAsyncOperation *activateOperation)
- override final;
- };
- WASAPIActivateAudioInterfaceCompletionHandler::
- WASAPIActivateAudioInterfaceCompletionHandler()
- {
- activationSignal = CreateEvent(nullptr, false, false, nullptr);
- if (!activationSignal.Valid())
- throw "Could not create receive signal";
- }
- HRESULT
- WASAPIActivateAudioInterfaceCompletionHandler::GetActivateResult(
- IAudioClient **client)
- {
- WaitForSingleObject(activationSignal, INFINITE);
- *client = static_cast<IAudioClient *>(unknown);
- return activationResult;
- }
- HRESULT
- WASAPIActivateAudioInterfaceCompletionHandler::ActivateCompleted(
- IActivateAudioInterfaceAsyncOperation *activateOperation)
- {
- HRESULT hr, hr_activate;
- hr = activateOperation->GetActivateResult(&hr_activate, &unknown);
- hr = SUCCEEDED(hr) ? hr_activate : hr;
- activationResult = hr;
- SetEvent(activationSignal);
- return hr;
- }
- enum class SourceType {
- Input,
- DeviceOutput,
- ProcessOutput,
- };
- class ARtwqAsyncCallback : public IRtwqAsyncCallback {
- protected:
- ARtwqAsyncCallback(void *source) : source(source) {}
- public:
- STDMETHOD_(ULONG, AddRef)() { return ++refCount; }
- STDMETHOD_(ULONG, Release)() { return --refCount; }
- STDMETHOD(QueryInterface)(REFIID riid, void **ppvObject)
- {
- HRESULT hr = E_NOINTERFACE;
- if (riid == __uuidof(IRtwqAsyncCallback) ||
- riid == __uuidof(IUnknown)) {
- *ppvObject = this;
- AddRef();
- hr = S_OK;
- } else {
- *ppvObject = NULL;
- }
- return hr;
- }
- STDMETHOD(GetParameters)
- (DWORD *pdwFlags, DWORD *pdwQueue)
- {
- *pdwFlags = 0;
- *pdwQueue = queue_id;
- return S_OK;
- }
- STDMETHOD(Invoke)
- (IRtwqAsyncResult *) override = 0;
- DWORD GetQueueId() const { return queue_id; }
- void SetQueueId(DWORD id) { queue_id = id; }
- protected:
- std::atomic<ULONG> refCount = 1;
- void *source;
- DWORD queue_id = 0;
- };
- class WASAPISource {
- ComPtr<IMMNotificationClient> notify;
- ComPtr<IMMDeviceEnumerator> enumerator;
- ComPtr<IAudioClient> client;
- ComPtr<IAudioCaptureClient> capture;
- obs_source_t *source;
- wstring default_id;
- string device_id;
- string device_name;
- WinModule mmdevapi_module;
- PFN_ActivateAudioInterfaceAsync activate_audio_interface_async = NULL;
- PFN_RtwqUnlockWorkQueue rtwq_unlock_work_queue = NULL;
- PFN_RtwqLockSharedWorkQueue rtwq_lock_shared_work_queue = NULL;
- PFN_RtwqCreateAsyncResult rtwq_create_async_result = NULL;
- PFN_RtwqPutWorkItem rtwq_put_work_item = NULL;
- PFN_RtwqPutWaitingWorkItem rtwq_put_waiting_work_item = NULL;
- bool rtwq_supported = false;
- window_priority priority;
- string window_class;
- string title;
- string executable;
- HWND hwnd = NULL;
- DWORD process_id = 0;
- const SourceType sourceType;
- std::atomic<bool> useDeviceTiming = false;
- std::atomic<bool> isDefaultDevice = false;
- bool previouslyFailed = false;
- WinHandle reconnectThread = NULL;
- class CallbackStartCapture : public ARtwqAsyncCallback {
- public:
- CallbackStartCapture(WASAPISource *source)
- : ARtwqAsyncCallback(source)
- {
- }
- STDMETHOD(Invoke)
- (IRtwqAsyncResult *) override
- {
- ((WASAPISource *)source)->OnStartCapture();
- return S_OK;
- }
- } startCapture;
- ComPtr<IRtwqAsyncResult> startCaptureAsyncResult;
- class CallbackSampleReady : public ARtwqAsyncCallback {
- public:
- CallbackSampleReady(WASAPISource *source)
- : ARtwqAsyncCallback(source)
- {
- }
- STDMETHOD(Invoke)
- (IRtwqAsyncResult *) override
- {
- ((WASAPISource *)source)->OnSampleReady();
- return S_OK;
- }
- } sampleReady;
- ComPtr<IRtwqAsyncResult> sampleReadyAsyncResult;
- class CallbackRestart : public ARtwqAsyncCallback {
- public:
- CallbackRestart(WASAPISource *source)
- : ARtwqAsyncCallback(source)
- {
- }
- STDMETHOD(Invoke)
- (IRtwqAsyncResult *) override
- {
- ((WASAPISource *)source)->OnRestart();
- return S_OK;
- }
- } restart;
- ComPtr<IRtwqAsyncResult> restartAsyncResult;
- WinHandle captureThread;
- WinHandle idleSignal;
- WinHandle stopSignal;
- WinHandle receiveSignal;
- WinHandle restartSignal;
- WinHandle reconnectExitSignal;
- WinHandle exitSignal;
- WinHandle initSignal;
- DWORD reconnectDuration = 0;
- WinHandle reconnectSignal;
- speaker_layout speakers;
- audio_format format;
- uint32_t sampleRate;
- uint64_t framesProcessed = 0;
- static DWORD WINAPI ReconnectThread(LPVOID param);
- static DWORD WINAPI CaptureThread(LPVOID param);
- bool ProcessCaptureData();
- void Start();
- void Stop();
- static ComPtr<IMMDevice> InitDevice(IMMDeviceEnumerator *enumerator,
- bool isDefaultDevice,
- SourceType type,
- const string device_id);
- static ComPtr<IAudioClient> InitClient(
- IMMDevice *device, SourceType type, DWORD process_id,
- PFN_ActivateAudioInterfaceAsync activate_audio_interface_async,
- speaker_layout &speakers, audio_format &format,
- uint32_t &sampleRate);
- static void InitFormat(const WAVEFORMATEX *wfex,
- enum speaker_layout &speakers,
- enum audio_format &format, uint32_t &sampleRate);
- static void ClearBuffer(IMMDevice *device);
- static ComPtr<IAudioCaptureClient> InitCapture(IAudioClient *client,
- HANDLE receiveSignal);
- void Initialize();
- bool TryInitialize();
- struct UpdateParams {
- string device_id;
- bool useDeviceTiming;
- bool isDefaultDevice;
- window_priority priority;
- string window_class;
- string title;
- string executable;
- };
- UpdateParams BuildUpdateParams(obs_data_t *settings);
- void UpdateSettings(UpdateParams &¶ms);
- void LogSettings();
- public:
- WASAPISource(obs_data_t *settings, obs_source_t *source_,
- SourceType type);
- ~WASAPISource();
- void Update(obs_data_t *settings);
- void OnWindowChanged(obs_data_t *settings);
- void Activate();
- void Deactivate();
- void SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id);
- void OnStartCapture();
- void OnSampleReady();
- void OnRestart();
- };
- class WASAPINotify : public IMMNotificationClient {
- long refs = 0; /* auto-incremented to 1 by ComPtr */
- WASAPISource *source;
- public:
- WASAPINotify(WASAPISource *source_) : source(source_) {}
- STDMETHODIMP_(ULONG) AddRef()
- {
- return (ULONG)os_atomic_inc_long(&refs);
- }
- STDMETHODIMP_(ULONG) STDMETHODCALLTYPE Release()
- {
- long val = os_atomic_dec_long(&refs);
- if (val == 0)
- delete this;
- return (ULONG)val;
- }
- STDMETHODIMP QueryInterface(REFIID riid, void **ptr)
- {
- if (riid == IID_IUnknown) {
- *ptr = (IUnknown *)this;
- } else if (riid == __uuidof(IMMNotificationClient)) {
- *ptr = (IMMNotificationClient *)this;
- } else {
- *ptr = nullptr;
- return E_NOINTERFACE;
- }
- os_atomic_inc_long(&refs);
- return S_OK;
- }
- STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role,
- LPCWSTR id)
- {
- source->SetDefaultDevice(flow, role, id);
- return S_OK;
- }
- STDMETHODIMP OnDeviceAdded(LPCWSTR) { return S_OK; }
- STDMETHODIMP OnDeviceRemoved(LPCWSTR) { return S_OK; }
- STDMETHODIMP OnDeviceStateChanged(LPCWSTR, DWORD) { return S_OK; }
- STDMETHODIMP OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY)
- {
- return S_OK;
- }
- };
- WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_,
- SourceType type)
- : source(source_),
- sourceType(type),
- startCapture(this),
- sampleReady(this),
- restart(this)
- {
- mmdevapi_module = LoadLibrary(L"Mmdevapi");
- if (mmdevapi_module) {
- activate_audio_interface_async =
- (PFN_ActivateAudioInterfaceAsync)GetProcAddress(
- mmdevapi_module, "ActivateAudioInterfaceAsync");
- }
- UpdateSettings(BuildUpdateParams(settings));
- LogSettings();
- idleSignal = CreateEvent(nullptr, true, false, nullptr);
- if (!idleSignal.Valid())
- throw "Could not create idle signal";
- stopSignal = CreateEvent(nullptr, true, false, nullptr);
- if (!stopSignal.Valid())
- throw "Could not create stop signal";
- receiveSignal = CreateEvent(nullptr, false, false, nullptr);
- if (!receiveSignal.Valid())
- throw "Could not create receive signal";
- restartSignal = CreateEvent(nullptr, true, false, nullptr);
- if (!restartSignal.Valid())
- throw "Could not create restart signal";
- reconnectExitSignal = CreateEvent(nullptr, true, false, nullptr);
- if (!reconnectExitSignal.Valid())
- throw "Could not create reconnect exit signal";
- exitSignal = CreateEvent(nullptr, true, false, nullptr);
- if (!exitSignal.Valid())
- throw "Could not create exit signal";
- initSignal = CreateEvent(nullptr, false, false, nullptr);
- if (!initSignal.Valid())
- throw "Could not create init signal";
- reconnectSignal = CreateEvent(nullptr, false, false, nullptr);
- if (!reconnectSignal.Valid())
- throw "Could not create reconnect signal";
- notify = new WASAPINotify(this);
- if (!notify)
- throw "Could not create WASAPINotify";
- HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
- CLSCTX_ALL,
- IID_PPV_ARGS(enumerator.Assign()));
- if (FAILED(hr))
- throw HRError("Failed to create enumerator", hr);
- hr = enumerator->RegisterEndpointNotificationCallback(notify);
- if (FAILED(hr))
- throw HRError("Failed to register endpoint callback", hr);
- /* OBS will already load DLL on startup if it exists */
- const HMODULE rtwq_module = GetModuleHandle(L"RTWorkQ.dll");
- // while RTWQ was introduced in Win 8.1, it silently fails
- // to capture Desktop Audio for some reason. Disable for now.
- struct win_version_info win1703 = {};
- win1703.major = 10;
- win1703.minor = 0;
- win1703.build = 15063;
- win1703.revis = 0;
- struct win_version_info ver;
- get_win_ver(&ver);
- if (win_version_compare(&ver, &win1703) >= 0)
- rtwq_supported = rtwq_module != NULL;
- if (rtwq_supported) {
- rtwq_unlock_work_queue =
- (PFN_RtwqUnlockWorkQueue)GetProcAddress(
- rtwq_module, "RtwqUnlockWorkQueue");
- rtwq_lock_shared_work_queue =
- (PFN_RtwqLockSharedWorkQueue)GetProcAddress(
- rtwq_module, "RtwqLockSharedWorkQueue");
- rtwq_create_async_result =
- (PFN_RtwqCreateAsyncResult)GetProcAddress(
- rtwq_module, "RtwqCreateAsyncResult");
- rtwq_put_work_item = (PFN_RtwqPutWorkItem)GetProcAddress(
- rtwq_module, "RtwqPutWorkItem");
- rtwq_put_waiting_work_item =
- (PFN_RtwqPutWaitingWorkItem)GetProcAddress(
- rtwq_module, "RtwqPutWaitingWorkItem");
- try {
- hr = rtwq_create_async_result(nullptr, &startCapture,
- nullptr,
- &startCaptureAsyncResult);
- if (FAILED(hr)) {
- throw HRError(
- "Could not create startCaptureAsyncResult",
- hr);
- }
- hr = rtwq_create_async_result(nullptr, &sampleReady,
- nullptr,
- &sampleReadyAsyncResult);
- if (FAILED(hr)) {
- throw HRError(
- "Could not create sampleReadyAsyncResult",
- hr);
- }
- hr = rtwq_create_async_result(nullptr, &restart,
- nullptr,
- &restartAsyncResult);
- if (FAILED(hr)) {
- throw HRError(
- "Could not create restartAsyncResult",
- hr);
- }
- DWORD taskId = 0;
- DWORD id = 0;
- hr = rtwq_lock_shared_work_queue(L"Capture", 0, &taskId,
- &id);
- if (FAILED(hr)) {
- throw HRError("RtwqLockSharedWorkQueue failed",
- hr);
- }
- startCapture.SetQueueId(id);
- sampleReady.SetQueueId(id);
- restart.SetQueueId(id);
- } catch (HRError &err) {
- blog(LOG_ERROR, "RTWQ setup failed: %s (0x%08X)",
- err.str, err.hr);
- rtwq_supported = false;
- }
- }
- if (!rtwq_supported) {
- captureThread = CreateThread(nullptr, 0,
- WASAPISource::CaptureThread, this,
- 0, nullptr);
- if (!captureThread.Valid()) {
- enumerator->UnregisterEndpointNotificationCallback(
- notify);
- throw "Failed to create capture thread";
- }
- }
- Start();
- }
- void WASAPISource::Start()
- {
- if (rtwq_supported) {
- rtwq_put_work_item(startCapture.GetQueueId(), 0,
- startCaptureAsyncResult);
- } else {
- SetEvent(initSignal);
- }
- }
- void WASAPISource::Stop()
- {
- if (!reconnectThread.Valid())
- WaitForSingleObject(reconnectSignal, INFINITE);
- SetEvent(stopSignal);
- blog(LOG_INFO, "WASAPI: Device '%s' Terminated", device_name.c_str());
- if (rtwq_supported)
- SetEvent(receiveSignal);
- if (reconnectThread.Valid())
- WaitForSingleObject(idleSignal, INFINITE);
- SetEvent(exitSignal);
- if (reconnectThread.Valid()) {
- SetEvent(reconnectExitSignal);
- WaitForSingleObject(reconnectThread, INFINITE);
- }
- if (rtwq_supported)
- rtwq_unlock_work_queue(sampleReady.GetQueueId());
- else
- WaitForSingleObject(captureThread, INFINITE);
- }
- WASAPISource::~WASAPISource()
- {
- enumerator->UnregisterEndpointNotificationCallback(notify);
- Stop();
- }
- WASAPISource::UpdateParams WASAPISource::BuildUpdateParams(obs_data_t *settings)
- {
- WASAPISource::UpdateParams params;
- params.device_id = obs_data_get_string(settings, OPT_DEVICE_ID);
- params.useDeviceTiming =
- obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING);
- params.isDefaultDevice =
- _strcmpi(params.device_id.c_str(), "default") == 0;
- params.priority =
- (window_priority)obs_data_get_int(settings, "priority");
- params.window_class.clear();
- params.title.clear();
- params.executable.clear();
- if (sourceType != SourceType::Input) {
- const char *const window =
- obs_data_get_string(settings, OPT_WINDOW);
- char *window_class = nullptr;
- char *title = nullptr;
- char *executable = nullptr;
- ms_build_window_strings(window, &window_class, &title,
- &executable);
- if (window_class) {
- params.window_class = window_class;
- bfree(window_class);
- }
- if (title) {
- params.title = title;
- bfree(title);
- }
- if (executable) {
- params.executable = executable;
- bfree(executable);
- }
- }
- return params;
- }
- void WASAPISource::UpdateSettings(UpdateParams &¶ms)
- {
- device_id = std::move(params.device_id);
- useDeviceTiming = params.useDeviceTiming;
- isDefaultDevice = params.isDefaultDevice;
- priority = params.priority;
- window_class = std::move(params.window_class);
- title = std::move(params.title);
- executable = std::move(params.executable);
- }
- void WASAPISource::LogSettings()
- {
- if (sourceType == SourceType::ProcessOutput) {
- blog(LOG_INFO,
- "[win-wasapi: '%s'] update settings:\n"
- "\texecutable: %s\n"
- "\ttitle: %s\n"
- "\tclass: %s\n"
- "\tpriority: %d",
- obs_source_get_name(source), executable.c_str(),
- title.c_str(), window_class.c_str(), (int)priority);
- } else {
- blog(LOG_INFO,
- "[win-wasapi: '%s'] update settings:\n"
- "\tdevice id: %s\n"
- "\tuse device timing: %d",
- obs_source_get_name(source), device_id.c_str(),
- (int)useDeviceTiming);
- }
- }
- void WASAPISource::Update(obs_data_t *settings)
- {
- UpdateParams params = BuildUpdateParams(settings);
- const bool restart =
- (sourceType == SourceType::ProcessOutput)
- ? ((priority != params.priority) ||
- (window_class != params.window_class) ||
- (title != params.title) ||
- (executable != params.executable))
- : (device_id.compare(params.device_id) != 0);
- UpdateSettings(std::move(params));
- LogSettings();
- if (restart)
- SetEvent(restartSignal);
- }
- void WASAPISource::OnWindowChanged(obs_data_t *settings)
- {
- UpdateParams params = BuildUpdateParams(settings);
- const bool restart =
- (sourceType == SourceType::ProcessOutput)
- ? ((priority != params.priority) ||
- (window_class != params.window_class) ||
- (title != params.title) ||
- (executable != params.executable))
- : (device_id.compare(params.device_id) != 0);
- UpdateSettings(std::move(params));
- if (restart)
- SetEvent(restartSignal);
- }
- void WASAPISource::Activate()
- {
- if (!reconnectThread.Valid()) {
- ResetEvent(reconnectExitSignal);
- reconnectThread = CreateThread(nullptr, 0,
- WASAPISource::ReconnectThread,
- this, 0, nullptr);
- }
- }
- void WASAPISource::Deactivate()
- {
- if (reconnectThread.Valid()) {
- SetEvent(reconnectExitSignal);
- WaitForSingleObject(reconnectThread, INFINITE);
- reconnectThread = NULL;
- }
- }
- ComPtr<IMMDevice> WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator,
- bool isDefaultDevice,
- SourceType type,
- const string device_id)
- {
- ComPtr<IMMDevice> device;
- if (isDefaultDevice) {
- const bool input = type == SourceType::Input;
- HRESULT res = enumerator->GetDefaultAudioEndpoint(
- input ? eCapture : eRender,
- input ? eCommunications : eConsole, device.Assign());
- if (FAILED(res))
- throw HRError("Failed GetDefaultAudioEndpoint", res);
- } else {
- wchar_t *w_id;
- os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id);
- if (!w_id)
- throw "Failed to widen device id string";
- const HRESULT res =
- enumerator->GetDevice(w_id, device.Assign());
- bfree(w_id);
- if (FAILED(res))
- throw HRError("Failed to enumerate device", res);
- }
- return device;
- }
- #define BUFFER_TIME_100NS (5 * 10000000)
- static DWORD GetSpeakerChannelMask(speaker_layout layout)
- {
- switch (layout) {
- case SPEAKERS_STEREO:
- return KSAUDIO_SPEAKER_STEREO;
- case SPEAKERS_2POINT1:
- return KSAUDIO_SPEAKER_2POINT1;
- case SPEAKERS_4POINT0:
- return KSAUDIO_SPEAKER_SURROUND;
- case SPEAKERS_4POINT1:
- return OBS_KSAUDIO_SPEAKER_4POINT1;
- case SPEAKERS_5POINT1:
- return KSAUDIO_SPEAKER_5POINT1_SURROUND;
- case SPEAKERS_7POINT1:
- return KSAUDIO_SPEAKER_7POINT1_SURROUND;
- }
- return (DWORD)layout;
- }
- ComPtr<IAudioClient> WASAPISource::InitClient(
- IMMDevice *device, SourceType type, DWORD process_id,
- PFN_ActivateAudioInterfaceAsync activate_audio_interface_async,
- speaker_layout &speakers, audio_format &format,
- uint32_t &samples_per_sec)
- {
- WAVEFORMATEXTENSIBLE wfextensible;
- CoTaskMemPtr<WAVEFORMATEX> wfex;
- const WAVEFORMATEX *pFormat;
- HRESULT res;
- ComPtr<IAudioClient> client;
- if (type == SourceType::ProcessOutput) {
- if (activate_audio_interface_async == NULL)
- throw "ActivateAudioInterfaceAsync is not available";
- struct obs_audio_info oai;
- obs_get_audio_info(&oai);
- const WORD nChannels = (WORD)get_audio_channels(oai.speakers);
- const DWORD nSamplesPerSec = oai.samples_per_sec;
- constexpr WORD wBitsPerSample = 32;
- const WORD nBlockAlign = nChannels * wBitsPerSample / 8;
- WAVEFORMATEX &wf = wfextensible.Format;
- wf.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
- wf.nChannels = nChannels;
- wf.nSamplesPerSec = nSamplesPerSec;
- wf.nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
- wf.nBlockAlign = nBlockAlign;
- wf.wBitsPerSample = wBitsPerSample;
- wf.cbSize = sizeof(wfextensible) - sizeof(format);
- wfextensible.Samples.wValidBitsPerSample = wBitsPerSample;
- wfextensible.dwChannelMask =
- GetSpeakerChannelMask(oai.speakers);
- wfextensible.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
- AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams;
- audioclientActivationParams.ActivationType =
- AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK;
- audioclientActivationParams.ProcessLoopbackParams
- .TargetProcessId = process_id;
- audioclientActivationParams.ProcessLoopbackParams
- .ProcessLoopbackMode =
- PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE;
- PROPVARIANT activateParams{};
- activateParams.vt = VT_BLOB;
- activateParams.blob.cbSize =
- sizeof(audioclientActivationParams);
- activateParams.blob.pBlobData =
- reinterpret_cast<BYTE *>(&audioclientActivationParams);
- {
- Microsoft::WRL::ComPtr<
- WASAPIActivateAudioInterfaceCompletionHandler>
- handler = Microsoft::WRL::Make<
- WASAPIActivateAudioInterfaceCompletionHandler>();
- ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
- res = activate_audio_interface_async(
- VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
- __uuidof(IAudioClient), &activateParams,
- handler.Get(), &asyncOp);
- if (FAILED(res))
- throw HRError(
- "Failed to get activate audio client",
- res);
- res = handler->GetActivateResult(client.Assign());
- if (FAILED(res))
- throw HRError("Async activation failed", res);
- }
- pFormat = &wf;
- } else {
- res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
- nullptr, (void **)client.Assign());
- if (FAILED(res))
- throw HRError("Failed to activate client context", res);
- res = client->GetMixFormat(&wfex);
- if (FAILED(res))
- throw HRError("Failed to get mix format", res);
- pFormat = wfex.Get();
- }
- InitFormat(pFormat, speakers, format, samples_per_sec);
- DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
- if (type != SourceType::Input)
- flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
- res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags,
- BUFFER_TIME_100NS, 0, pFormat, nullptr);
- if (FAILED(res))
- throw HRError("Failed to initialize audio client", res);
- return client;
- }
- void WASAPISource::ClearBuffer(IMMDevice *device)
- {
- CoTaskMemPtr<WAVEFORMATEX> wfex;
- HRESULT res;
- LPBYTE buffer;
- UINT32 frames;
- ComPtr<IAudioClient> client;
- res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
- (void **)client.Assign());
- if (FAILED(res))
- throw HRError("Failed to activate client context", res);
- res = client->GetMixFormat(&wfex);
- if (FAILED(res))
- throw HRError("Failed to get mix format", res);
- res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS,
- 0, wfex, nullptr);
- if (FAILED(res))
- throw HRError("Failed to initialize audio client", res);
- /* Silent loopback fix. Prevents audio stream from stopping and */
- /* messing up timestamps and other weird glitches during silence */
- /* by playing a silent sample all over again. */
- res = client->GetBufferSize(&frames);
- if (FAILED(res))
- throw HRError("Failed to get buffer size", res);
- ComPtr<IAudioRenderClient> render;
- res = client->GetService(IID_PPV_ARGS(render.Assign()));
- if (FAILED(res))
- throw HRError("Failed to get render client", res);
- res = render->GetBuffer(frames, &buffer);
- if (FAILED(res))
- throw HRError("Failed to get buffer", res);
- memset(buffer, 0, (size_t)frames * (size_t)wfex->nBlockAlign);
- render->ReleaseBuffer(frames, 0);
- }
- static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels)
- {
- switch (layout) {
- case KSAUDIO_SPEAKER_2POINT1:
- return SPEAKERS_2POINT1;
- case KSAUDIO_SPEAKER_SURROUND:
- return SPEAKERS_4POINT0;
- case OBS_KSAUDIO_SPEAKER_4POINT1:
- return SPEAKERS_4POINT1;
- case KSAUDIO_SPEAKER_5POINT1_SURROUND:
- return SPEAKERS_5POINT1;
- case KSAUDIO_SPEAKER_7POINT1_SURROUND:
- return SPEAKERS_7POINT1;
- }
- return (speaker_layout)channels;
- }
- void WASAPISource::InitFormat(const WAVEFORMATEX *wfex,
- enum speaker_layout &speakers,
- enum audio_format &format, uint32_t &sampleRate)
- {
- DWORD layout = 0;
- if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
- WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex;
- layout = ext->dwChannelMask;
- }
- /* WASAPI is always float */
- speakers = ConvertSpeakerLayout(layout, wfex->nChannels);
- format = AUDIO_FORMAT_FLOAT;
- sampleRate = wfex->nSamplesPerSec;
- }
- ComPtr<IAudioCaptureClient> WASAPISource::InitCapture(IAudioClient *client,
- HANDLE receiveSignal)
- {
- ComPtr<IAudioCaptureClient> capture;
- HRESULT res = client->GetService(IID_PPV_ARGS(capture.Assign()));
- if (FAILED(res))
- throw HRError("Failed to create capture context", res);
- res = client->SetEventHandle(receiveSignal);
- if (FAILED(res))
- throw HRError("Failed to set event handle", res);
- res = client->Start();
- if (FAILED(res))
- throw HRError("Failed to start capture client", res);
- return capture;
- }
- void WASAPISource::Initialize()
- {
- ComPtr<IMMDevice> device;
- if (sourceType == SourceType::ProcessOutput) {
- device_name = "[VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK]";
- hwnd = ms_find_window(INCLUDE_MINIMIZED, priority,
- window_class.c_str(), title.c_str(),
- executable.c_str());
- if (!hwnd)
- throw "Failed to find window";
- DWORD dwProcessId = 0;
- if (!GetWindowThreadProcessId(hwnd, &dwProcessId)) {
- hwnd = NULL;
- throw "Failed to get process id of window";
- }
- process_id = dwProcessId;
- } else {
- device = InitDevice(enumerator, isDefaultDevice, sourceType,
- device_id);
- device_name = GetDeviceName(device);
- }
- ResetEvent(receiveSignal);
- ComPtr<IAudioClient> temp_client = InitClient(
- device, sourceType, process_id, activate_audio_interface_async,
- speakers, format, sampleRate);
- if (sourceType == SourceType::DeviceOutput)
- ClearBuffer(device);
- ComPtr<IAudioCaptureClient> temp_capture =
- InitCapture(temp_client, receiveSignal);
- client = std::move(temp_client);
- capture = std::move(temp_capture);
- if (rtwq_supported) {
- HRESULT hr = rtwq_put_waiting_work_item(
- receiveSignal, 0, sampleReadyAsyncResult, nullptr);
- if (FAILED(hr)) {
- capture.Clear();
- client.Clear();
- throw HRError("RtwqPutWaitingWorkItem failed", hr);
- }
- hr = rtwq_put_waiting_work_item(restartSignal, 0,
- restartAsyncResult, nullptr);
- if (FAILED(hr)) {
- capture.Clear();
- client.Clear();
- throw HRError("RtwqPutWaitingWorkItem failed", hr);
- }
- }
- blog(LOG_INFO, "WASAPI: Device '%s' [%" PRIu32 " Hz] initialized",
- device_name.c_str(), sampleRate);
- }
- bool WASAPISource::TryInitialize()
- {
- bool success = false;
- try {
- Initialize();
- success = true;
- } catch (HRError &error) {
- if (!previouslyFailed) {
- blog(LOG_WARNING,
- "[WASAPISource::TryInitialize]:[%s] %s: %lX",
- device_name.empty() ? device_id.c_str()
- : device_name.c_str(),
- error.str, error.hr);
- }
- } catch (const char *error) {
- if (!previouslyFailed) {
- blog(LOG_WARNING,
- "[WASAPISource::TryInitialize]:[%s] %s",
- device_name.empty() ? device_id.c_str()
- : device_name.c_str(),
- error);
- }
- }
- previouslyFailed = !success;
- return success;
- }
- DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param)
- {
- os_set_thread_name("win-wasapi: reconnect thread");
- WASAPISource *source = (WASAPISource *)param;
- const HANDLE sigs[] = {
- source->reconnectExitSignal,
- source->reconnectSignal,
- };
- const HANDLE reconnect_sigs[] = {
- source->reconnectExitSignal,
- source->stopSignal,
- };
- bool exit = false;
- while (!exit) {
- const DWORD ret = WaitForMultipleObjects(_countof(sigs), sigs,
- false, INFINITE);
- switch (ret) {
- case WAIT_OBJECT_0:
- exit = true;
- break;
- default:
- assert(ret == (WAIT_OBJECT_0 + 1));
- if (source->reconnectDuration > 0) {
- WaitForMultipleObjects(
- _countof(reconnect_sigs),
- reconnect_sigs, false,
- source->reconnectDuration);
- }
- source->Start();
- }
- }
- return 0;
- }
- bool WASAPISource::ProcessCaptureData()
- {
- HRESULT res;
- LPBYTE buffer;
- UINT32 frames;
- DWORD flags;
- UINT64 pos, ts;
- UINT captureSize = 0;
- while (true) {
- if ((sourceType == SourceType::ProcessOutput) &&
- !IsWindow(hwnd)) {
- blog(LOG_WARNING,
- "[WASAPISource::ProcessCaptureData] window disappeared");
- return false;
- }
- res = capture->GetNextPacketSize(&captureSize);
- if (FAILED(res)) {
- if (res != AUDCLNT_E_DEVICE_INVALIDATED)
- blog(LOG_WARNING,
- "[WASAPISource::ProcessCaptureData]"
- " capture->GetNextPacketSize"
- " failed: %lX",
- res);
- return false;
- }
- if (!captureSize)
- break;
- res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts);
- if (FAILED(res)) {
- if (res != AUDCLNT_E_DEVICE_INVALIDATED)
- blog(LOG_WARNING,
- "[WASAPISource::ProcessCaptureData]"
- " capture->GetBuffer"
- " failed: %lX",
- res);
- return false;
- }
- obs_source_audio data = {};
- data.data[0] = (const uint8_t *)buffer;
- data.frames = (uint32_t)frames;
- data.speakers = speakers;
- data.samples_per_sec = sampleRate;
- data.format = format;
- if (sourceType == SourceType::ProcessOutput) {
- data.timestamp = util_mul_div64(framesProcessed,
- UINT64_C(1000000000),
- sampleRate);
- framesProcessed += frames;
- } else {
- data.timestamp = useDeviceTiming ? ts * 100
- : os_gettime_ns();
- if (!useDeviceTiming)
- data.timestamp -= util_mul_div64(
- frames, UINT64_C(1000000000),
- sampleRate);
- }
- obs_source_output_audio(source, &data);
- capture->ReleaseBuffer(frames);
- }
- return true;
- }
- #define RECONNECT_INTERVAL 3000
- DWORD WINAPI WASAPISource::CaptureThread(LPVOID param)
- {
- os_set_thread_name("win-wasapi: capture thread");
- const HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
- const bool com_initialized = SUCCEEDED(hr);
- if (!com_initialized) {
- blog(LOG_ERROR,
- "[WASAPISource::CaptureThread]"
- " CoInitializeEx failed: 0x%08X",
- hr);
- }
- DWORD unused = 0;
- const HANDLE handle = AvSetMmThreadCharacteristics(L"Audio", &unused);
- WASAPISource *source = (WASAPISource *)param;
- const HANDLE inactive_sigs[] = {
- source->exitSignal,
- source->stopSignal,
- source->initSignal,
- };
- const HANDLE active_sigs[] = {
- source->exitSignal,
- source->stopSignal,
- source->receiveSignal,
- source->restartSignal,
- };
- DWORD sig_count = _countof(inactive_sigs);
- const HANDLE *sigs = inactive_sigs;
- bool exit = false;
- while (!exit) {
- bool idle = false;
- bool stop = false;
- bool reconnect = false;
- do {
- /* Windows 7 does not seem to wake up for LOOPBACK */
- const DWORD dwMilliseconds =
- ((sigs == active_sigs) &&
- (source->sourceType != SourceType::Input))
- ? 10
- : INFINITE;
- const DWORD ret = WaitForMultipleObjects(
- sig_count, sigs, false, dwMilliseconds);
- switch (ret) {
- case WAIT_OBJECT_0: {
- exit = true;
- stop = true;
- idle = true;
- break;
- }
- case WAIT_OBJECT_0 + 1:
- stop = true;
- idle = true;
- break;
- case WAIT_OBJECT_0 + 2:
- case WAIT_TIMEOUT:
- if (sigs == inactive_sigs) {
- assert(ret != WAIT_TIMEOUT);
- if (source->TryInitialize()) {
- sig_count =
- _countof(active_sigs);
- sigs = active_sigs;
- } else {
- if (source->reconnectDuration ==
- 0) {
- blog(LOG_INFO,
- "WASAPI: Device '%s' failed to start (source: %s)",
- source->device_id
- .c_str(),
- obs_source_get_name(
- source->source));
- }
- stop = true;
- reconnect = true;
- source->reconnectDuration =
- RECONNECT_INTERVAL;
- }
- } else {
- stop = !source->ProcessCaptureData();
- if (stop) {
- blog(LOG_INFO,
- "Device '%s' invalidated. Retrying (source: %s)",
- source->device_name.c_str(),
- obs_source_get_name(
- source->source));
- stop = true;
- reconnect = true;
- source->reconnectDuration =
- RECONNECT_INTERVAL;
- }
- }
- break;
- default:
- assert(sigs == active_sigs);
- assert(ret == WAIT_OBJECT_0 + 3);
- stop = true;
- reconnect = true;
- source->reconnectDuration = 0;
- ResetEvent(source->restartSignal);
- }
- } while (!stop);
- sig_count = _countof(inactive_sigs);
- sigs = inactive_sigs;
- if (source->client) {
- source->client->Stop();
- source->capture.Clear();
- source->client.Clear();
- }
- if (idle) {
- SetEvent(source->idleSignal);
- } else if (reconnect) {
- blog(LOG_INFO,
- "Device '%s' invalidated. Retrying (source: %s)",
- source->device_name.c_str(),
- obs_source_get_name(source->source));
- SetEvent(source->reconnectSignal);
- }
- }
- if (handle)
- AvRevertMmThreadCharacteristics(handle);
- if (com_initialized)
- CoUninitialize();
- return 0;
- }
- void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id)
- {
- if (!isDefaultDevice)
- return;
- const bool input = sourceType == SourceType::Input;
- const EDataFlow expectedFlow = input ? eCapture : eRender;
- const ERole expectedRole = input ? eCommunications : eConsole;
- if (flow != expectedFlow || role != expectedRole)
- return;
- if (id) {
- if (default_id.compare(id) == 0)
- return;
- default_id = id;
- } else {
- if (default_id.empty())
- return;
- default_id.clear();
- }
- blog(LOG_INFO, "WASAPI: Default %s device changed",
- input ? "input" : "output");
- SetEvent(restartSignal);
- }
- void WASAPISource::OnStartCapture()
- {
- const DWORD ret = WaitForSingleObject(stopSignal, 0);
- switch (ret) {
- case WAIT_OBJECT_0:
- SetEvent(idleSignal);
- break;
- default:
- assert(ret == WAIT_TIMEOUT);
- if (!TryInitialize()) {
- if (reconnectDuration == 0) {
- blog(LOG_INFO,
- "WASAPI: Device '%s' failed to start (source: %s)",
- device_id.c_str(),
- obs_source_get_name(source));
- }
- reconnectDuration = RECONNECT_INTERVAL;
- SetEvent(reconnectSignal);
- }
- }
- }
- void WASAPISource::OnSampleReady()
- {
- bool stop = false;
- bool reconnect = false;
- if (!ProcessCaptureData()) {
- stop = true;
- reconnect = true;
- reconnectDuration = RECONNECT_INTERVAL;
- }
- if (WaitForSingleObject(restartSignal, 0) == WAIT_OBJECT_0) {
- stop = true;
- reconnect = true;
- reconnectDuration = 0;
- ResetEvent(restartSignal);
- rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult,
- nullptr);
- }
- if (WaitForSingleObject(stopSignal, 0) == WAIT_OBJECT_0) {
- stop = true;
- reconnect = false;
- }
- if (!stop) {
- if (FAILED(rtwq_put_waiting_work_item(receiveSignal, 0,
- sampleReadyAsyncResult,
- nullptr))) {
- blog(LOG_ERROR,
- "Could not requeue sample receive work");
- stop = true;
- reconnect = true;
- reconnectDuration = RECONNECT_INTERVAL;
- }
- }
- if (stop) {
- client->Stop();
- capture.Clear();
- client.Clear();
- if (reconnect) {
- blog(LOG_INFO,
- "Device '%s' invalidated. Retrying (source: %s)",
- device_name.c_str(), obs_source_get_name(source));
- SetEvent(reconnectSignal);
- } else {
- SetEvent(idleSignal);
- }
- }
- }
- void WASAPISource::OnRestart()
- {
- SetEvent(receiveSignal);
- }
- /* ------------------------------------------------------------------------- */
- static const char *GetWASAPIInputName(void *)
- {
- return obs_module_text("AudioInput");
- }
- static const char *GetWASAPIDeviceOutputName(void *)
- {
- return obs_module_text("AudioOutput");
- }
- static const char *GetWASAPIProcessOutputName(void *)
- {
- return obs_module_text("ApplicationAudioCapture");
- }
- static void GetWASAPIDefaultsInput(obs_data_t *settings)
- {
- obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
- obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, false);
- }
- static void GetWASAPIDefaultsDeviceOutput(obs_data_t *settings)
- {
- obs_data_set_default_string(settings, OPT_DEVICE_ID, "default");
- obs_data_set_default_bool(settings, OPT_USE_DEVICE_TIMING, true);
- }
- static void GetWASAPIDefaultsProcessOutput(obs_data_t *) {}
- static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source,
- SourceType type)
- {
- try {
- return new WASAPISource(settings, source, type);
- } catch (const char *error) {
- blog(LOG_ERROR, "[CreateWASAPISource] %s", error);
- }
- return nullptr;
- }
- static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source)
- {
- return CreateWASAPISource(settings, source, SourceType::Input);
- }
- static void *CreateWASAPIDeviceOutput(obs_data_t *settings,
- obs_source_t *source)
- {
- return CreateWASAPISource(settings, source, SourceType::DeviceOutput);
- }
- static void *CreateWASAPIProcessOutput(obs_data_t *settings,
- obs_source_t *source)
- {
- return CreateWASAPISource(settings, source, SourceType::ProcessOutput);
- }
- static void DestroyWASAPISource(void *obj)
- {
- delete static_cast<WASAPISource *>(obj);
- }
- static void UpdateWASAPISource(void *obj, obs_data_t *settings)
- {
- static_cast<WASAPISource *>(obj)->Update(settings);
- }
- static void ActivateWASAPISource(void *obj)
- {
- static_cast<WASAPISource *>(obj)->Activate();
- }
- static void DeactivateWASAPISource(void *obj)
- {
- static_cast<WASAPISource *>(obj)->Deactivate();
- }
- static bool UpdateWASAPIMethod(obs_properties_t *props, obs_property_t *,
- obs_data_t *settings)
- {
- WASAPISource *source = (WASAPISource *)obs_properties_get_param(props);
- if (!source)
- return false;
- source->Update(settings);
- return true;
- }
- static obs_properties_t *GetWASAPIPropertiesInput(void *)
- {
- obs_properties_t *props = obs_properties_create();
- vector<AudioDeviceInfo> devices;
- obs_property_t *device_prop = obs_properties_add_list(
- props, OPT_DEVICE_ID, obs_module_text("Device"),
- OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
- GetWASAPIAudioDevices(devices, true);
- if (devices.size())
- obs_property_list_add_string(
- device_prop, obs_module_text("Default"), "default");
- for (size_t i = 0; i < devices.size(); i++) {
- AudioDeviceInfo &device = devices[i];
- obs_property_list_add_string(device_prop, device.name.c_str(),
- device.id.c_str());
- }
- obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
- obs_module_text("UseDeviceTiming"));
- return props;
- }
- static obs_properties_t *GetWASAPIPropertiesDeviceOutput(void *)
- {
- obs_properties_t *props = obs_properties_create();
- vector<AudioDeviceInfo> devices;
- obs_property_t *device_prop = obs_properties_add_list(
- props, OPT_DEVICE_ID, obs_module_text("Device"),
- OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
- GetWASAPIAudioDevices(devices, false);
- if (devices.size())
- obs_property_list_add_string(
- device_prop, obs_module_text("Default"), "default");
- for (size_t i = 0; i < devices.size(); i++) {
- AudioDeviceInfo &device = devices[i];
- obs_property_list_add_string(device_prop, device.name.c_str(),
- device.id.c_str());
- }
- obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING,
- obs_module_text("UseDeviceTiming"));
- return props;
- }
- static bool wasapi_window_changed(obs_properties_t *props, obs_property_t *p,
- obs_data_t *settings)
- {
- WASAPISource *source = (WASAPISource *)obs_properties_get_param(props);
- if (!source)
- return false;
- source->OnWindowChanged(settings);
- ms_check_window_property_setting(props, p, settings, "window", 0);
- return true;
- }
- static obs_properties_t *GetWASAPIPropertiesProcessOutput(void *data)
- {
- obs_properties_t *props = obs_properties_create();
- obs_properties_set_param(props, data, NULL);
- obs_property_t *const window_prop = obs_properties_add_list(
- props, OPT_WINDOW, obs_module_text("Window"),
- OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
- ms_fill_window_list(window_prop, INCLUDE_MINIMIZED, nullptr);
- obs_property_set_modified_callback(window_prop, wasapi_window_changed);
- obs_property_t *const priority_prop = obs_properties_add_list(
- props, OPT_PRIORITY, obs_module_text("Priority"),
- OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
- obs_property_list_add_int(priority_prop,
- obs_module_text("Priority.Title"),
- WINDOW_PRIORITY_TITLE);
- obs_property_list_add_int(priority_prop,
- obs_module_text("Priority.Class"),
- WINDOW_PRIORITY_CLASS);
- obs_property_list_add_int(priority_prop,
- obs_module_text("Priority.Exe"),
- WINDOW_PRIORITY_EXE);
- return props;
- }
- void RegisterWASAPIInput()
- {
- obs_source_info info = {};
- info.id = "wasapi_input_capture";
- info.type = OBS_SOURCE_TYPE_INPUT;
- info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
- info.get_name = GetWASAPIInputName;
- info.create = CreateWASAPIInput;
- info.destroy = DestroyWASAPISource;
- info.update = UpdateWASAPISource;
- info.activate = ActivateWASAPISource;
- info.deactivate = DeactivateWASAPISource;
- info.get_defaults = GetWASAPIDefaultsInput;
- info.get_properties = GetWASAPIPropertiesInput;
- info.icon_type = OBS_ICON_TYPE_AUDIO_INPUT;
- obs_register_source(&info);
- }
- void RegisterWASAPIDeviceOutput()
- {
- obs_source_info info = {};
- info.id = "wasapi_output_capture";
- info.type = OBS_SOURCE_TYPE_INPUT;
- info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
- OBS_SOURCE_DO_NOT_SELF_MONITOR;
- info.get_name = GetWASAPIDeviceOutputName;
- info.create = CreateWASAPIDeviceOutput;
- info.destroy = DestroyWASAPISource;
- info.update = UpdateWASAPISource;
- info.activate = ActivateWASAPISource;
- info.deactivate = DeactivateWASAPISource;
- info.get_defaults = GetWASAPIDefaultsDeviceOutput;
- info.get_properties = GetWASAPIPropertiesDeviceOutput;
- info.icon_type = OBS_ICON_TYPE_AUDIO_OUTPUT;
- obs_register_source(&info);
- }
- void RegisterWASAPIProcessOutput()
- {
- obs_source_info info = {};
- info.id = "wasapi_process_output_capture";
- info.type = OBS_SOURCE_TYPE_INPUT;
- info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
- OBS_SOURCE_DO_NOT_SELF_MONITOR;
- info.get_name = GetWASAPIProcessOutputName;
- info.create = CreateWASAPIProcessOutput;
- info.destroy = DestroyWASAPISource;
- info.update = UpdateWASAPISource;
- info.activate = ActivateWASAPISource;
- info.deactivate = DeactivateWASAPISource;
- info.get_defaults = GetWASAPIDefaultsProcessOutput;
- info.get_properties = GetWASAPIPropertiesProcessOutput;
- info.icon_type = OBS_ICON_TYPE_PROCESS_AUDIO_OUTPUT;
- obs_register_source(&info);
- }
|