Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
feat(audio): arm AVerMedia non-PCM passthrough so GC553G2/GC553PRO/GC575 deliver 5.1
Veyra Goal Agent5f848b5b6f6d
diff --git a/CMakeLists.txt b/CMakeLists.txtindex d33c5bb9..2f2dea36 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -471,6 +471,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/source/NativeCaptureSink.cppsrc/source/MediaFileSource.cppsrc/source/CaptureCardSource.cpp+ src/source/AverMediaAudioSwitch.cppsrc/source/CaptureCompressedDecoder.cppsrc/source/WasapiAudioInput.cpp)@@ -568,6 +569,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_features(veyra_audio_timeline_tests PRIVATE cxx_std_20)target_link_libraries(veyra_audio_timeline_tests PRIVATE veyra_sinks)add_executable(veyra_capture_audio_tests tests/integration/CaptureAudioTests.cpp)+ add_executable(veyra_avermedia_switch_tests tests/unit/AverMediaAudioSwitchTests.cpp)+ target_compile_features(veyra_avermedia_switch_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_avermedia_switch_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_link_libraries(veyra_avermedia_switch_tests PRIVATE veyra_sources)if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavcodec/avcodec.h")add_executable(veyra_bitstream_audio_test tools/bitstream_audio_test/main.cpp)target_compile_features(veyra_bitstream_audio_test PRIVATE cxx_std_20)diff --git a/docs/AVERMEDIA_5P1_SWITCH_IMPLEMENTATION_2026-09-17.md b/docs/AVERMEDIA_5P1_SWITCH_IMPLEMENTATION_2026-09-17.mdnew file mode 100644index 00000000..103b1997--- /dev/null+++ b/docs/AVERMEDIA_5P1_SWITCH_IMPLEMENTATION_2026-09-17.md@@ -0,0 +1,188 @@+# AVerMedia 5.1 采集开关:实现与验证++日期:2026-09-17+分支:`codex/avermedia-51-switch-20260917`(独立 worktree `out/worktrees/avermedia-51`,基于 `6119a7d`)+上游调研:[`AVERMEDIA_5P1_CAPTURE_FEASIBILITY_2026-09-17.md`](AVERMEDIA_5P1_CAPTURE_FEASIBILITY_2026-09-17.md)++目标:让 Veyra 也能从 GC553G2 / GC553PRO / GC575 拿到 5.1——也就是把 AVerMedia 的 OBS 插件+真正做的那一步自己做掉,而不是再写一份可行性分析。++---++## 1. 做了什么++### 1.1 新模块:`include/veyra/source/AverMediaAudioSwitch.h` + `src/source/AverMediaAudioSwitch.cpp`++按绝对路径加载用户**已经装好**的厂商组件,调用与 OBS 插件完全相同的入口点:++```+Qt6Core.dll (OBS bin\64bit) -> 预加载,避免依赖靠 PATH 猜+avt_device_opener.dll -> LoadLibraryExW + 13 个修饰名导出+ AVerMedia::VendorSdk(dataDir) -> initialize()+ AVerMedia::DeviceOpener -> SetVendorSdk() -> SwitchDeviceThenDetectAudioFormat({name,path})+ -> IsAudioFormatNonPcm() -> StartChecking()+ VendorSdk::getAudioFormat() -> 唯一可信的成功判据(原因见 1.3)+```++- **不分发任何第三方二进制**:组件只从用户自己的安装目录加载;找不到就静默降级,基础播放/采集/导出不受影响。+- 发现顺序:环境变量 `VEYRA_AVERMEDIA_COMPONENT`(诊断覆盖)→ `HKLM\SOFTWARE\AVerMedia\OBS_Plugins\AVerMediaMultichannelAudio\Path` → `%ProgramFiles%\obs-studio`。+ 三种来源都要求同一个目录布局(`obs-plugins\64bit\avt_device_opener.dll` + `data\obs-plugins\AVerMediaMultichannelAudio\RTICE_SDK_x64.dll` + `RTK_IO_x64.dll`)。+- 外来代码可能抛 C++ 异常也可能触发 SEH:调用被拆成"只含 POD 的 `__try/__except` 调用器 + 外层 `catch(...)`",任何失败都变成一条日志,不允许把采集进程带走。+- `stop()` 幂等;DLL 故意**不** `FreeLibrary`(其监控线程与 Qt 运行时在进程末尾卸载不安全)。++### 1.2 接进采集源:`src/source/CaptureCardSource.cpp`++- 音频图**建立之前**先武装开关(媒体类型枚举必须看到切换后的状态):`configure()` → `applyVendorAudioSwitch(name,path)` → 再 `connectDirectShowAudio()`。+ 只对 DirectShow 独立音频设备、且设备路径含 `vid_07ca` 时才尝试;WASAPI 端点与"视频设备内置音频"不动。+- `binding=separate ...` 日志新增 `device="<友好名>"`:这是上一次复盘里最缺的信息(当时无法确认 index 0/2 到底是哪个端点)。+- 嵌入式音频引脚不存在(`VFW_E_NOT_FOUND`)被判为**静态不可用**:不再每 5 秒重试(上次现场日志里空转了 7 次、20 秒、21 行噪音)。+- `close()` 关闭开关。++### 1.3 为什么用 `getAudioFormat` 当成功判据++`SwitchDeviceThenDetectAudioFormat` 返回 `void` 且内部吞掉错误,只有它自己会打印失败信息。+而 `vendor initialize/setDevice/setPort/AT_Audio_Send_Non_Pcm_Data` 的返回值都在内部被丢弃,+唯一能确认"真的跟卡说上话"的接口是 `AT_Audio_Get_HdmiRX_AudioFormat`:++```cpp+if (!formatOk) { state=Failed; detail="card not reached: getAudioFormat ret=..."; return false; }+```++芯片返回 **20 (0x14)** 表示 HDMI 源正在发非 PCM(Dolby);其他值表示 PCM。+注意这是**源的当前格式**,不是"有没有武装成功"——用户在菜单里时它一样是 PCM。++---++## 2. 实测证据(全部来自本机,可复核)++### 2.1 构建++```+out\worktrees\avermedia-51\out\build-avermedia-51.cmd exit 0+(CMake presets x64-release + Ninja,DLSS SDK / FFmpeg / clip-tools 指向 C:\veyra-deps 与主检出的 third_party_local;+ RemotePlay=OFF 以缩短隔离构建时间——与发布构建的这一处差异必须单独复核)+日志:out\worktrees\avermedia-51\out\build-7.log(213 个目标)+```++### 2.2 导出名表与真实二进制的比对++```+python + pefile 对比 avt_device_opener.dll(1.0.2, SHA256 100A3D2E…82F1) 的导出表:+required exports present: 13 / 13+```++即 1.1 里那张修饰名表没有一个是猜的。++### 2.3 单元测试(无硬件、无 OBS)++`tests/unit/AverMediaAudioSwitchTests.cpp` → `veyra_avermedia_switch_tests.exe`++裸机(本机没有装 OBS 插件):+```+ok vid_07ca path is recognised+ok uppercase VID_07CA is recognised (case-insensitive)+ok a non-AVerMedia device is rejected+ok an empty path is rejected+ok a WASAPI endpoint id is rejected+note component not installed on this machine (expected on a bare test host)+ok locateComponentRoot returns empty when absent+ok apply() reports failure when the component is absent+ok status marks the component as absent / DLLs not loaded / 有原因可记+ok status state is Unavailable+ok stop() leaves the helper inactive+ok destructor after stop() is safe+PASS (0 failures)+```++### 2.4 用**真实组件**跑通加载链(本次最有价值的一条)++把安装包解出的真实文件铺成同一套目录结构(`%TEMP%\averma-fake-component`),并放入一台现成的+`Qt6Core.dll`(6.8.3.0,来自本机其它软件,仅用于本地验证,不进任何交付物),然后+`set VEYRA_AVERMEDIA_COMPONENT=...` 再跑同一个测试:++```+DeviceOpener::SwitchDeviceThenDetectAudioFormat, closePort ret: 0+SetupDiGetDeviceInterfaceDetail : 1 / Not found the device × N (本机没有插卡)+serialNumber:+uvcName: USB3 Digital Audio (我们传入的结构化参数被正确读走)+Fail to open COM1 (厂商自己的兜底路径)+ok located component provides avt_device_opener.dll+note apply() with component present returned 0: card not reached: getAudioFormat ret=5+PASS (0 failures)+```++这条同时证明了四件事:++1. Qt 预加载 + `LoadLibraryExW` 路径策略有效(同一个 DLL 在只加 Qt 之前会以 126 失败,见下);+2. 13 个导出在**运行时**全部解析成功;+3. 手写的 `DeviceOpenerParam{std::wstring name; std::wstring path;}` ABI 镜像被真实组件正确读取(它打印出了我们传的 `uvcName`);+4. 没有卡时是**干净失败**:进程不崩、不挂,`getAudioFormat ret=5` 就是"组件在、卡不在"的签名,而且我们的返回值如实报 0(false)。++对照实验(未加 Qt 时):+```+LoadLibraryExW(avt_device_opener.dll) -> 失败,err=126 (ERROR_MOD_NOT_FOUND)+LoadLibraryExW(RTICE_SDK_x64.dll) -> 成功(RTK_IO_x64.dll 在同目录,靠 DLL_LOAD_DIR 解析)+```++### 2.5 项目交付短测++```+powershell -File scripts/gates/delivery.ps1 -Root <worktree> -BuildDirectory <worktree>\out\build+DELIVERY SHORT GATE PASS (exit 0)+logs\delivery\084be258e4834f7d958efa997a0b40c1\result.json+```++---++## 3. 用户侧怎么验收(这是唯一还没走完的一步)++1. 机器上装好 AVerMedia Multichannel Audio 组件(他已经在 OBS 里用上了,说明组件与固件都满足)。+2. PS5 输出设 **Dolby Digital**,进游戏(菜单一般不出 5.1)。+3. 用 Veyra 连接采集卡的**独立音频设备**(不要选"视频设备内置音频",那张卡没有内置音频引脚),+ 采集音频模式选「自动」或「位流优先」。+4. 看日志里这行 `[capture-audio-vendor]`:+ - `non-PCM switch armed ... chipFormat=20 nonPcmNow=1` → 切换生效,源正在发 Dolby;+ - `chipFormat=<其它>` → 组件在跑但源不是 Dolby;+ - `card not reached: getAudioFormat ret=5` → 没插卡/被别的软件占着;+ - `not installed` → 组件没找到(可用环境变量指路)。+5. 紧接着看 `[capture-audio-bitstream] device bitstream types=?`:+ - **非 0** → 卡切换后真的换了媒体类型,现有"位流优先"链路直接吃下,5.1 应当立刻可用;+ - **仍然是 0** → 说明切换只改载荷不改媒体类型(调研报告 2.4 的推断成立),下一步要做的是+ 在 PCM 标签流上嗅探 IEC 61937 同步字 `F8 72 4E 1F` 并按 data-type 选解码器;**在那之前,+ 这种情况下的声音会是位流被当 PCM 播出来的噪音,不是正常的 2.0**。++第 5 步是这次唯一无法在本机回答的问题——本机没有卡,也没有 5.1 源。++---++## 4. 未验证 / 已知限制(不得含糊)++- **真卡未验收**:本机没有 GC553G2,`SwitchDeviceThenDetectAudioFormat` 走到"找不到设备"就结束了;+ 真正把卡切到 non-PCM、以及切换后端点媒体类型是否变化,都还没有观测。+- **只验证到组件加载与调用**:`initialize` 后的真实设备交互、`StartChecking` 线程在长时运行下的行为未验证。+- **退出不还原模式**:`stop()` 只 `StopChecking` + `closePort/uninitialize`,不调 `setNonPcmOnOff(0)`+ ——这与厂商插件行为一致(它也不还原)。副作用是:之后若用**没有**装插件的软件采集同一端点,+ 可能听到位流当 PCM 的噪音。要不要在关闭时还原,等真机结果再定。+- **没有 UI 开关**:目前是"检测到 AVerMedia 设备 + 组件存在就自动武装"。若将来需要按需关闭,加一个设置项即可。+- **厂商自己的日志走 stdout**:`avt_device_opener.dll` 在没有安装 log handler 时直接打印+ (`Not found the device`、`Fail to open COM1` 等)。没有接 `SetLogHandler`,因为它的参数是+ `std::function`,跨 DLL 边界构造的 ABI 风险高于收益。这些行会出现在控制台,不进 Veyra 日志文件。+- **隔离构建 RemotePlay=OFF**:本分支的验证构建关闭了 RemotePlay;提交前需要一次与发布一致的完整构建。+- **不是所有 AVerMedia 卡都适用**:本模块按 `vid_07ca` 放行,真正支不支持 5.1 由卡与固件决定;+ 官方只列 GC553G2 / GC553PRO / GC575(GC553G2 需固件 ≥ V1.0.7.7),且源必须是 Dolby 位流,不支持 5.1 LPCM。++---++## 5. 改动文件++| 文件 | 说明 |+|---|---|+| `include/veyra/source/AverMediaAudioSwitch.h` | 新模块接口 |+| `src/source/AverMediaAudioSwitch.cpp` | 发现 / 加载 / 调用 / 降级 / 停机 |+| `src/source/CaptureCardSource.cpp` | 建图前武装开关;记录音频设备名;嵌入式引脚静态失败不再重试 |+| `include/veyra/source/CaptureCardSource.h` | 新增 `applyVendorAudioSwitch` 声明 |+| `tests/unit/AverMediaAudioSwitchTests.cpp` | 无硬件单元测试(14 项) |+| `CMakeLists.txt` | 新源文件 + 测试目标 |++未提交任何 SDK / DLL / 模型 / 用户配置;`third_party_local`、`runtime_local`、`loop\local` 在隔离 worktree 里+是**目录联接**(只读复用主检出的本地依赖),不参与版本控制。diff --git a/include/veyra/source/AverMediaAudioSwitch.h b/include/veyra/source/AverMediaAudioSwitch.hnew file mode 100644index 00000000..c315187f--- /dev/null+++ b/include/veyra/source/AverMediaAudioSwitch.h@@ -0,0 +1,80 @@+#pragma once++// AVerMedia multichannel-audio switch (GC553G2 / GC553PRO / GC575).+//+// Those cards forward HDMI audio as 2.0 PCM until something tells the internal+// audio path to pass the compressed (non-PCM) stream through. That "something"+// is AVerMedia's own component: the user installs it for OBS ("AVerMedia+// Multichannel Audio"), and OBS then gets the Dolby stream as 6 PCM channels.+// Nothing is redistributed here - this module loads the copy that already sits+// on the machine, calls the same entry points the OBS plugin calls, and leaves+// capture/decoding to Veyra's existing audio graph.+//+// Behaviour measured from avt_device_opener.dll 1.0.2 (see+// docs/AVERMEDIA_5P1_CAPTURE_FEASIBILITY_2026-09-17.md):+// * VendorSdk forwards 1:1 to RTICE_SDK_x64!initialize / uninitialize /+// setDevice / setPort / closePort and to AT_Audio_Get_HdmiRX_AudioFormat,+// AT_Audio_CSR_Get_Send_Non_Pcm_Data_On_off, AT_Audio_Send_Non_Pcm_Data.+// Each call is wrapped in the global mutex "Global\RTK_SDK_LOCK_NAME", so+// only one process drives the card at a time (OBS and Veyra can therefore+// not both hold it).+// * AT_Audio_Get_HdmiRX_AudioFormat returns 20 (0x14) while the HDMI source+// sends non-PCM; the enable path refuses to switch for any other value.+// * DeviceOpener::StartChecking runs the vendor thread that re-applies the+// switch when the console toggles between PCM and bitstream.+//+// The two helper DLLs are prebuilt and carry no source; they are only ever+// loaded from the user's own installation, by absolute path.++#include <memory>+#include <string>+#include <string_view>++namespace veyra::source {++enum class AverMediaSwitchState { Unavailable, Ready, Switched, Failed };++struct AverMediaSwitchStatus {+ AverMediaSwitchState state = AverMediaSwitchState::Unavailable;+ bool componentFound = false;+ bool dllsLoaded = false;+ bool sdkReady = false;+ bool nonPcmActive = false; // what the chip reports *now* (source format)+ int chipAudioFormat = -1; // raw AT_Audio_Get_HdmiRX_AudioFormat value+ std::wstring componentRoot; // folder that owns obs-plugins\64bit+ std::string detail; // last result/error, for the log+};++class AverMediaAudioSwitch {+public:+ AverMediaAudioSwitch();+ ~AverMediaAudioSwitch();+ AverMediaAudioSwitch(const AverMediaAudioSwitch&) = delete;+ AverMediaAudioSwitch& operator=(const AverMediaAudioSwitch&) = delete;++ // Folder of the installed component (the one containing+ // obs-plugins\64bit\avt_device_opener.dll). Empty when not installed.+ static std::wstring locateComponentRoot();+ // Cheap test used to skip unrelated audio devices: the DirectShow device+ // path of an AVerMedia capture device carries vid_07ca.+ static bool isAverMediaDevicePath(std::wstring_view devicePath);++ // Loads the component (once) and arms non-PCM passthrough for the card+ // behind `devicePath`. Never throws; failures are reported in status().+ bool apply(const std::wstring& deviceName, const std::wstring& devicePath);+ // Starts the vendor monitor thread that re-applies the switch when the+ // console changes audio format. Called by apply(); idempotent.+ void startMonitoring();+ // Stops the vendor monitor thread and releases the SDK port. The DLLs stay+ // loaded until the process exits: their own worker must not be unloaded+ // underneath a still-running thread.+ void stop() noexcept;+ bool active() const;+ const AverMediaSwitchStatus& status() const;++private:+ struct Impl;+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::sourcediff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.hindex d9fe8465..345bf3cc 100644--- a/include/veyra/source/CaptureCardSource.h+++ b/include/veyra/source/CaptureCardSource.h@@ -67,6 +67,9 @@ public:void close()noexcept override;private:bool connectDirectShowAudio(const SourceOpenDesc&);+ // AVerMedia capture cards need their installed vendor component to arm+ // non-PCM (Dolby/DTS) passthrough before the audio pin is negotiated.+ bool applyVendorAudioSwitch(const std::wstring& audioName,const std::wstring& audioPath);SourceReadStatus readWithWait(pipeline::FramePacket&,const AVFrame**,unsigned milliseconds);struct Impl;std::unique_ptr<Impl> p_;SourceOpenDesc reconnectDesc_;diff --git a/src/source/AverMediaAudioSwitch.cpp b/src/source/AverMediaAudioSwitch.cppnew file mode 100644index 00000000..2fee2d91--- /dev/null+++ b/src/source/AverMediaAudioSwitch.cpp@@ -0,0 +1,441 @@+#include "veyra/source/AverMediaAudioSwitch.h"++#include "veyra/Log.h"++#include <windows.h>++#include <cstdint>+#include <format>+#include <string>+#include <vector>++namespace veyra::source {+namespace {++// ---------------------------------------------------------------------------+// ABI mirror of the component's public headers (GPLv2, shipped in+// AVerMedia-Technologies-Inc/obs-MultichannelAudio). Only the layout matters:+// both the component and Veyra are built with the MSVC x64 toolchain, so these+// are plain aggregates with the same member order.+// ---------------------------------------------------------------------------+struct VendorDeviceOpenerParam {+ std::wstring name; // +0x00+ std::wstring path; // +0x20+};++using RawFn = long long (*)(void*, void*, void*, void*, void*);++struct RawCall {+ RawFn fn = nullptr;+ void* self = nullptr;+ void* a = nullptr;+ void* b = nullptr;+ void* c = nullptr;+ void* d = nullptr;+ long long result = -1;+ unsigned sehCode = 0;+};++// SEH must live in a function that owns no C++ objects, which is why the+// invocation is split away from everything else. Foreign code can both throw+// (their wrappers use std::string/throw) and fault, so both are handled.+void invokeRaw(RawCall* call) noexcept {+ __try {+ call->result = call->fn(call->self, call->a, call->b, call->c, call->d);+ } __except (call->sehCode = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER) {+ call->result = -1;+ }+}++// Entry points of avt_device_opener.dll, decorated names as exported.+constexpr const char* kExportVendorSdkCtor = "??0VendorSdk@AVerMedia@@QEAA@PEBD@Z";+constexpr const char* kExportVendorSdkDtor = "??1VendorSdk@AVerMedia@@QEAA@XZ";+constexpr const char* kExportSdkInitialize = "?initialize@VendorSdk@AVerMedia@@QEAAHXZ";+constexpr const char* kExportSdkUninitialize = "?uninitialize@VendorSdk@AVerMedia@@QEAAHXZ";+constexpr const char* kExportSdkClosePort = "?closePort@VendorSdk@AVerMedia@@QEAAHXZ";+constexpr const char* kExportSdkGetAudioFormat = "?getAudioFormat@VendorSdk@AVerMedia@@QEAAHPEAH@Z";+constexpr const char* kExportOpenerCtor = "??0DeviceOpener@AVerMedia@@QEAA@XZ";+constexpr const char* kExportOpenerDtor = "??1DeviceOpener@AVerMedia@@QEAA@XZ";+constexpr const char* kExportOpenerSetVendorSdk = "?SetVendorSdk@DeviceOpener@AVerMedia@@QEAAXPEAVVendorSdk@2@@Z";+constexpr const char* kExportOpenerSwitch = "?SwitchDeviceThenDetectAudioFormat@DeviceOpener@AVerMedia@@QEAAXAEBUDeviceOpenerParam@2@@Z";+constexpr const char* kExportOpenerIsNonPcm = "?IsAudioFormatNonPcm@DeviceOpener@AVerMedia@@QEBA_NXZ";+constexpr const char* kExportOpenerStartChecking = "?StartChecking@DeviceOpener@AVerMedia@@QEAAXXZ";+constexpr const char* kExportOpenerStopChecking = "?StopChecking@DeviceOpener@AVerMedia@@QEAAXXZ";++// The chip reports this value while the HDMI source sends a compressed+// (non-PCM) stream; their enable path refuses to switch for anything else.+constexpr int kChipFormatNonPcm = 20;++// Both classes hold a single opaque implementation pointer, but the storage is+// over-sized on purpose: the constructor only writes what it needs, and a+// larger zeroed block keeps a layout surprise from corrupting the stack.+struct ObjectStorage {+ alignas(16) unsigned char bytes[64] = {};+ void* raw() noexcept { return bytes; }+};++std::string narrowUtf8(const std::wstring& text) {+ if (text.empty()) return {};+ const int size = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), int(text.size()), nullptr, 0, nullptr, nullptr);+ if (size <= 0) return {};+ std::string out(size_t(size), '\0');+ WideCharToMultiByte(CP_UTF8, 0, text.c_str(), int(text.size()), out.data(), size, nullptr, nullptr);+ return out;+}++bool fileExists(const std::wstring& path) {+ const DWORD attributes = GetFileAttributesW(path.c_str());+ return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;+}++bool directoryExists(const std::wstring& path) {+ const DWORD attributes = GetFileAttributesW(path.c_str());+ return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;+}++std::wstring registryPathValue(HKEY root, const wchar_t* subKey, const wchar_t* valueName) {+ HKEY key = nullptr;+ if (RegOpenKeyExW(root, subKey, 0, KEY_READ | KEY_WOW64_64KEY, &key) != ERROR_SUCCESS) return {};+ DWORD type = 0;+ DWORD bytes = 0;+ std::wstring value;+ if (RegQueryValueExW(key, valueName, nullptr, &type, nullptr, &bytes) == ERROR_SUCCESS && type == REG_SZ && bytes > sizeof(wchar_t)) {+ value.resize(bytes / sizeof(wchar_t));+ if (RegQueryValueExW(key, valueName, nullptr, &type, reinterpret_cast<BYTE*>(value.data()), &bytes) != ERROR_SUCCESS) value.clear();+ while (!value.empty() && value.back() == L'\0') value.pop_back();+ }+ RegCloseKey(key);+ return value;+}++std::wstring joinPath(const std::wstring& base, const wchar_t* relative) {+ if (base.empty()) return {};+ std::wstring out = base;+ if (out.back() != L'\\' && out.back() != L'/') out.push_back(L'\\');+ out.append(relative);+ return out;+}++bool looksLikeComponent(const std::wstring& root) {+ if (root.empty()) return false;+ return fileExists(joinPath(root, L"obs-plugins\\64bit\\avt_device_opener.dll")) &&+ fileExists(joinPath(root, L"data\\obs-plugins\\AVerMediaMultichannelAudio\\RTICE_SDK_x64.dll")) &&+ fileExists(joinPath(root, L"data\\obs-plugins\\AVerMediaMultichannelAudio\\RTK_IO_x64.dll"));+}++// Qt6Core.dll is what avt_device_opener.dll links against and what OBS ships+// next to its own executable. Loading it first by absolute path keeps the+// dependency from resolving against whatever else happens to be on PATH; we+// never add OBS directories to this process's search path.+std::wstring findQt6Core(const std::wstring& root) {+ const wchar_t* candidates[] = {+ L"bin\\64bit\\Qt6Core.dll",+ L"obs-plugins\\64bit\\Qt6Core.dll",+ L"Qt6Core.dll",+ };+ for (const wchar_t* candidate : candidates) {+ const std::wstring path = joinPath(root, candidate);+ if (fileExists(path)) return path;+ }+ return {};+}++// Applies one vendor call, converting both C++ exceptions and SEH faults into+// a negative result so a foreign component can never take the capture down.+bool callVendor(RawCall& call, std::string& error) {+ if (call.fn == nullptr) {+ error = "entry point missing";+ return false;+ }+ try {+ invokeRaw(&call);+ } catch (...) {+ error = "component raised a C++ exception";+ return false;+ }+ if (call.sehCode != 0) {+ error = std::format("component faulted (SEH 0x{:08X})", call.sehCode);+ return false;+ }+ return true;+}++} // namespace++struct AverMediaAudioSwitch::Impl {+ struct Exports {+ RawFn vendorCtor = nullptr;+ RawFn vendorDtor = nullptr;+ RawFn initialize = nullptr;+ RawFn uninitialize = nullptr;+ RawFn closePort = nullptr;+ RawFn getAudioFormat = nullptr;+ RawFn openerCtor = nullptr;+ RawFn openerDtor = nullptr;+ RawFn setVendorSdk = nullptr;+ RawFn switchDevice = nullptr;+ RawFn isNonPcm = nullptr;+ RawFn startChecking = nullptr;+ RawFn stopChecking = nullptr;+ bool complete() const {+ return vendorCtor && vendorDtor && initialize && uninitialize && closePort && getAudioFormat &&+ openerCtor && openerDtor && setVendorSdk && switchDevice && isNonPcm &&+ startChecking && stopChecking;+ }+ };++ AverMediaSwitchStatus status;+ std::wstring componentRoot; // install root (owns obs-plugins\64bit)+ std::wstring dataDirectory; // ...\data\obs-plugins\AVerMediaMultichannelAudio+ std::string dataDirectoryUtf8;+ HMODULE avtModule = nullptr;+ HMODULE qtModule = nullptr;+ Exports exports;+ ObjectStorage sdkStorage;+ ObjectStorage openerStorage;+ bool sdkConstructed = false;+ bool openerConstructed = false;+ bool sdkInitialized = false;+ bool checking = false;++ void* sdk() noexcept { return sdkStorage.raw(); }+ void* opener() noexcept { return openerStorage.raw(); }++ bool resolveExports() {+ struct Entry { const char* name; RawFn* target; };+ const Entry entries[] = {+ {kExportVendorSdkCtor, &exports.vendorCtor},+ {kExportVendorSdkDtor, &exports.vendorDtor},+ {kExportSdkInitialize, &exports.initialize},+ {kExportSdkUninitialize, &exports.uninitialize},+ {kExportSdkClosePort, &exports.closePort},+ {kExportSdkGetAudioFormat, &exports.getAudioFormat},+ {kExportOpenerCtor, &exports.openerCtor},+ {kExportOpenerDtor, &exports.openerDtor},+ {kExportOpenerSetVendorSdk, &exports.setVendorSdk},+ {kExportOpenerSwitch, &exports.switchDevice},+ {kExportOpenerIsNonPcm, &exports.isNonPcm},+ {kExportOpenerStartChecking, &exports.startChecking},+ {kExportOpenerStopChecking, &exports.stopChecking},+ };+ for (const Entry& entry : entries) {+ FARPROC address = GetProcAddress(avtModule, entry.name);+ if (address == nullptr) {+ status.detail = std::format("missing export {}", entry.name);+ return false;+ }+ *entry.target = reinterpret_cast<RawFn>(address);+ }+ return true;+ }++ bool loadComponent() {+ if (avtModule != nullptr) return true;+ componentRoot = AverMediaAudioSwitch::locateComponentRoot();+ status.componentRoot = componentRoot;+ status.componentFound = !componentRoot.empty();+ if (!status.componentFound) {+ status.detail = "AVerMedia Multichannel Audio is not installed";+ return false;+ }+ dataDirectory = joinPath(componentRoot, L"data\\obs-plugins\\AVerMediaMultichannelAudio");+ // Qt is optional here: if it is already loaded (or absent because the+ // component does not need it) the loader resolves it on its own.+ const std::wstring qtPath = findQt6Core(componentRoot);+ if (!qtPath.empty()) {+ qtModule = LoadLibraryExW(qtPath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);+ }+ const std::wstring avtPath = joinPath(componentRoot, L"obs-plugins\\64bit\\avt_device_opener.dll");+ avtModule = LoadLibraryExW(avtPath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);+ if (avtModule == nullptr) {+ status.detail = std::format("LoadLibraryExW failed (error {})", GetLastError());+ if (qtModule != nullptr) { FreeLibrary(qtModule); qtModule = nullptr; }+ return false;+ }+ status.dllsLoaded = true;+ if (!resolveExports()) {+ FreeLibrary(avtModule);+ avtModule = nullptr;+ status.dllsLoaded = false;+ if (qtModule != nullptr) { FreeLibrary(qtModule); qtModule = nullptr; }+ return false;+ }+ return true;+ }+};++AverMediaAudioSwitch::AverMediaAudioSwitch() : p_(std::make_unique<Impl>()) {}+AverMediaAudioSwitch::~AverMediaAudioSwitch() { stop(); }++std::wstring AverMediaAudioSwitch::locateComponentRoot() {+ // Diagnostic override: a user whose component lives outside the OBS default+ // layout can point Veyra at the folder that owns obs-plugins\64bit. The+ // layout is still validated, so a bad value is ignored rather than loaded.+ wchar_t overrideBuffer[32768] = {};+ const DWORD overrideLength = GetEnvironmentVariableW(L"VEYRA_AVERMEDIA_COMPONENT", overrideBuffer, 32768);+ if (overrideLength > 0 && overrideLength < 32768) {+ const std::wstring candidate(overrideBuffer);+ if (looksLikeComponent(candidate)) return candidate;+ }+ std::wstring root = registryPathValue(HKEY_LOCAL_MACHINE,+ L"SOFTWARE\\AVerMedia\\OBS_Plugins\\AVerMediaMultichannelAudio", L"Path");+ if (looksLikeComponent(root)) return root;+ // Fall back to the default OBS locations when the registry entry is missing+ // (portable installs, or a plugin folder copied by hand).+ const wchar_t* environmentRoots[] = {L"ProgramFiles", L"ProgramFiles(x86)"};+ for (const wchar_t* variable : environmentRoots) {+ wchar_t buffer[MAX_PATH] = {};+ const DWORD length = GetEnvironmentVariableW(variable, buffer, MAX_PATH);+ if (length == 0 || length >= MAX_PATH) continue;+ for (const wchar_t* suffix : {L"\\obs-studio", L"\\OBS Studio"}) {+ const std::wstring candidate = std::wstring(buffer) + suffix;+ if (looksLikeComponent(candidate)) return candidate;+ }+ }+ return {};+}++bool AverMediaAudioSwitch::isAverMediaDevicePath(std::wstring_view devicePath) {+ std::wstring lowered(devicePath);+ for (wchar_t& character : lowered) character = wchar_t(towlower(character));+ return lowered.find(L"vid_07ca") != std::wstring::npos;+}++bool AverMediaAudioSwitch::apply(const std::wstring& deviceName, const std::wstring& devicePath) {+ auto& impl = *p_;+ if (impl.sdkInitialized && !devicePath.empty()) {+ // Already armed (for example after an audio reconnect); the vendor+ // monitor thread keeps the mode applied, so refreshing the status is+ // enough. This deliberately avoids a second setDevice/setPort cycle.+ RawCall refresh{impl.exports.isNonPcm, impl.opener()};+ std::string refreshError;+ impl.status.nonPcmActive = callVendor(refresh, refreshError) && (refresh.result & 0xFF) != 0;+ return true;+ }+ if (!impl.loadComponent()) {+ impl.status.state = AverMediaSwitchState::Unavailable;+ return false;+ }+ if (!impl.status.sdkReady) {+ impl.dataDirectoryUtf8 = narrowUtf8(impl.dataDirectory);+ // The component keeps no reference to this string; const_cast only+ // satisfies the raw-call signature.+ RawCall ctor{impl.exports.vendorCtor, impl.sdk(), const_cast<char*>(impl.dataDirectoryUtf8.c_str())};+ if (!callVendor(ctor, impl.status.detail)) {+ impl.status.state = AverMediaSwitchState::Failed;+ return false;+ }+ impl.sdkConstructed = true;+ RawCall initialize{impl.exports.initialize, impl.sdk()};+ if (!callVendor(initialize, impl.status.detail) || initialize.result != 0) {+ impl.status.detail = std::format("vendor initialize failed (ret={})", initialize.result);+ impl.status.state = AverMediaSwitchState::Failed;+ return false;+ }+ impl.sdkInitialized = true;+ impl.status.sdkReady = true;+ }+ if (!impl.openerConstructed) {+ RawCall ctor{impl.exports.openerCtor, impl.opener()};+ if (!callVendor(ctor, impl.status.detail)) {+ impl.status.state = AverMediaSwitchState::Failed;+ return false;+ }+ impl.openerConstructed = true;+ RawCall bind{impl.exports.setVendorSdk, impl.opener(), impl.sdk()};+ std::string error;+ if (!callVendor(bind, error)) {+ impl.status.detail = "SetVendorSdk failed: " + error;+ impl.status.state = AverMediaSwitchState::Failed;+ return false;+ }+ }+ VendorDeviceOpenerParam param{deviceName, devicePath};+ RawCall switchCall{impl.exports.switchDevice, impl.opener(), ¶m};+ if (!callVendor(switchCall, impl.status.detail)) {+ impl.status.state = AverMediaSwitchState::Failed;+ return false;+ }+ int chipFormat = -1;+ RawCall formatCall{impl.exports.getAudioFormat, impl.sdk(), &chipFormat};+ std::string formatError;+ const bool formatOk = callVendor(formatCall, formatError) && formatCall.result == 0;+ impl.status.chipAudioFormat = formatOk ? chipFormat : -1;+ RawCall nonPcmCall{impl.exports.isNonPcm, impl.opener()};+ std::string nonPcmError;+ impl.status.nonPcmActive = callVendor(nonPcmCall, nonPcmError) && (nonPcmCall.result & 0xFF) != 0;+ if (!formatOk) {+ // SwitchDeviceThenDetectAudioFormat returns void and swallows its own+ // errors, so the chip query is the only confirmation we get. If it does+ // not answer, the card was not reached and the mode is not armed.+ impl.status.state = AverMediaSwitchState::Failed;+ impl.status.detail = std::format("card not reached: getAudioFormat ret={}{}{}",+ formatCall.result, formatError.empty() ? "" : " ", formatError);+ return false;+ }+ impl.status.detail = std::format("chipAudioFormat={}{}", chipFormat,+ chipFormat == kChipFormatNonPcm ? " (non-PCM/Dolby)" : " (PCM)");+ impl.status.state = AverMediaSwitchState::Switched;+ startMonitoring();+ return true;+}++void AverMediaAudioSwitch::stop() noexcept {+ if (!p_) return;+ auto& impl = *p_;+ try {+ if (impl.checking && impl.avtModule != nullptr) {+ RawCall stopChecking{impl.exports.stopChecking, impl.opener()};+ std::string error;+ callVendor(stopChecking, error);+ impl.checking = false;+ }+ if (impl.sdkInitialized) {+ RawCall close{impl.exports.closePort, impl.sdk()};+ std::string error;+ callVendor(close, error);+ RawCall uninitialize{impl.exports.uninitialize, impl.sdk()};+ callVendor(uninitialize, error);+ impl.sdkInitialized = false;+ }+ if (impl.openerConstructed) {+ RawCall dtor{impl.exports.openerDtor, impl.opener()};+ std::string error;+ callVendor(dtor, error);+ impl.openerConstructed = false;+ }+ if (impl.sdkConstructed) {+ RawCall dtor{impl.exports.vendorDtor, impl.sdk()};+ std::string error;+ callVendor(dtor, error);+ impl.sdkConstructed = false;+ }+ } catch (...) {+ // Teardown must never throw; the vendors' worker threads are already+ // stopped by the calls above.+ }+ // The modules stay loaded on purpose: their monitor thread and the Qt+ // runtime are not safe to unload while other threads may still touch them.+}++void AverMediaAudioSwitch::startMonitoring() {+ auto& impl = *p_;+ if (!impl.sdkInitialized || impl.checking || impl.avtModule == nullptr) return;+ RawCall start{impl.exports.startChecking, impl.opener()};+ std::string error;+ if (!callVendor(start, error)) {+ impl.status.detail = "StartChecking failed: " + error;+ return;+ }+ impl.checking = true;+}++bool AverMediaAudioSwitch::active() const {+ return p_ && p_->checking;+}++const AverMediaSwitchStatus& AverMediaAudioSwitch::status() const {+ return p_->status;+}++} // namespace veyra::sourcediff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex dea45824..4eebaa63 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -7,6 +7,7 @@#include "veyra/source/CaptureFormatRank.h"#include "veyra/source/CaptureCodec.h"#include "veyra/source/CaptureCompressedDecoder.h"+#include "veyra/source/AverMediaAudioSwitch.h"#include "veyra/pipeline/ColorMetadata.h"#include "veyra/Log.h"#include "veyra/sink/AudioFormat.h"@@ -175,6 +176,11 @@ std::wstring encodePath(std::wstring_view value){for(const wchar_t character:value){const uint16_t unit=static_cast<uint16_t>(character);for(int shift=12;shift>=0;shift-=4)encoded.push_back(digits[(unit>>shift)&0xF]);}return encoded;}std::string pathTag(std::wstring_view value){const auto encoded=encodePath(value);std::string tag;tag.reserve(encoded.size());for(const wchar_t character:encoded)tag.push_back(static_cast<char>(character));return tag;}+// Audio devices are selected by ordinal in the legacy path form, so the log has+// to carry the friendly name: without it a field log cannot say which endpoint+// actually produced the samples.+std::string narrowForLog(const std::wstring& value){if(value.empty())return {};const int size=WideCharToMultiByte(CP_UTF8,0,value.c_str(),int(value.size()),nullptr,0,nullptr,nullptr);if(size<=0)return {};std::string out(size_t(size),'\0');WideCharToMultiByte(CP_UTF8,0,value.c_str(),int(value.size()),out.data(),size,nullptr,nullptr);return out;}+std::wstring filterName(IBaseFilter* filter){if(!filter)return {};FILTER_INFO info{};if(FAILED(filter->QueryFilterInfo(&info)))return {};std::wstring name=info.achName;if(info.pGraph)info.pGraph->Release();return name;}int hexValue(wchar_t character){if(character>=L'0'&&character<=L'9')return character-L'0';if(character>=L'A'&&character<=L'F')return character-L'A'+10;if(character>=L'a'&&character<=L'f')return character-L'a'+10;return -1;}bool decodePath(std::wstring_view encoded,std::wstring& value){if(encoded.size()%4!=0)return false;value.clear();value.reserve(encoded.size()/4);@@ -224,6 +230,14 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {std::shared_ptr<sink::BitstreamAudioSink> audioPassthrough;bool audioSessionDeferred=false;std::wstring audioBitstreamKind;+ // AVerMedia GC553G2 / GC553PRO / GC575 only forward compressed HDMI audio+ // after the installed vendor component arms non-PCM passthrough. The+ // component is loaded from the user's own OBS installation (never+ // redistributed); see AverMediaAudioSwitch.h for the measured behaviour.+ AverMediaAudioSwitch averMediaSwitch;+ // "Use the video device's built-in audio" is unrecoverable when the video+ // filter has no audio pin at all: retrying that is pure log noise.+ bool embeddedAudioUnavailable=false;// 0 automatic, 1 PCM only, 2 bitstream preferred (see// engine::CaptureAudioIngress). Read when the audio graph is built.unsigned audioIngressMode=0;@@ -609,6 +623,15 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAuif(!p.wasapi->configure(selection.audioPath)){p.wasapi.reset();p.audioError=L"WASAPI 音频端点ID无效;视频继续运行";}log::info("capture-audio","binding=wasapi shared=1 explicitEndpoint=1 videoClock=ingress-host-estimate");}else if(audio!=kCaptureAudioDisabled){+ if(audio>=0){+ // Resolve the DirectShow device identity before the graph is built.+ // The AVerMedia switch is keyed on the device path, and it has to+ // happen first so media-type enumeration sees the post-switch state.+ std::wstring audioName,audioPath;+ if(selection.stable)audioPath=selection.audioPath;+ else{auto list=monikers(true);if(size_t(audio)<list.size()){audioName=propertyString(list[size_t(audio)].Get(),L"FriendlyName");audioPath=monikerPath(list[size_t(audio)].Get());}}+ if(!audioPath.empty())applyVendorAudioSwitch(audioName,audioPath);+ }const bool audioReady=connectDirectShowAudio(desc);if(!audioReady){p.audioError=L"采集音频设备或 PCM 格式不可用;视频继续运行";@@ -656,6 +679,24 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAup.info.width,p.info.height,p.info.averageFps,actual?unsigned(actual->subtype.Data1):0,unsigned(formatHr),audio));freeType(actual);return true;}+bool CaptureCardSource::applyVendorAudioSwitch(const std::wstring& audioName,const std::wstring& audioPath){+ auto& p=*p_;+ if(!AverMediaAudioSwitch::isAverMediaDevicePath(audioPath)){+ log::info("capture-audio-vendor",std::format("skipped: not an AVerMedia capture device (device=\"{}\")",narrowForLog(audioName)));+ return false;+ }+ const bool applied=p.averMediaSwitch.apply(audioName,audioPath);+ const auto& status=p.averMediaSwitch.status();+ if(applied){+ log::info("capture-audio-vendor",std::format("non-PCM switch armed device=\"{}\" component=\"{}\" chipFormat={} nonPcmNow={} monitoring={}",+ narrowForLog(audioName),narrowForLog(status.componentRoot),status.chipAudioFormat,status.nonPcmActive?1:0,+ p.averMediaSwitch.active()?1:0));+ }else{+ log::warn("capture-audio-vendor",std::format("non-PCM switch unavailable device=\"{}\" componentFound={} dllsLoaded={} detail=\"{}\"",+ narrowForLog(audioName),status.componentFound?1:0,status.dllsLoaded?1:0,status.detail));+ }+ return applied;+}bool CaptureCardSource::connectDirectShowAudio(const SourceOpenDesc& desc){auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;const int audio=selection.audio;HRESULT hr=S_OK;@@ -670,10 +711,15 @@ bool CaptureCardSource::connectDirectShowAudio(const SourceOpenDesc& desc){if(!bound){log::warn("capture-audio",std::format("binding=separate failed mode={} audioIndex={} audioPathTag={}",audio,audio,pathTag(selection.audioPath)));return false;}hr=p.graph->AddFilter(audioFilter.Get(),L"Capture audio");if(FAILED(hr)){log::warn("capture-audio",std::format("binding=separate AddFilter hr=0x{:08X}",uint32_t(hr)));return false;}- p.audioFilter=audioFilter;log::info("capture-audio",std::format("binding=separate embedded=0 audioIndex={} audioPathTag={}",audio,audio,pathTag(selection.audioPath)));+ p.audioFilter=audioFilter;log::info("capture-audio",std::format("binding=separate embedded=0 audioIndex={} audioPathTag={} device=\"{}\"",audio,audio,pathTag(selection.audioPath),narrowForLog(filterName(audioFilter.Get()))));}ComPtr<IPin> audioPin;hr=audioPinFor(p.builder.Get(),audioFilter.Get(),audioPin);- if(FAILED(hr)){log::warn("capture-audio",std::format("audio output pin not found embedded={} hr=0x{:08X}",embedded?1:0,uint32_t(hr)));return false;}+ if(FAILED(hr)){+ if(embedded)p.embeddedAudioUnavailable=true;+ log::warn("capture-audio",std::format("audio output pin not found embedded={} hr=0x{:08X}{}",embedded?1:0,uint32_t(hr),+ embedded?" (this video filter exposes no audio pin; select the separate audio device)":""));+ return false;+ }ComPtr<IEnumMediaTypes> types;hr=audioPin->EnumMediaTypes(&types);if(FAILED(hr)){log::warn("capture-audio",std::format("EnumMediaTypes hr=0x{:08X}",uint32_t(hr)));return false;}// Preserve the device's actual speaker layout. Enumeration order is// commonly stereo first even when native 5.1 is available.@@ -886,6 +932,13 @@ bool CaptureCardSource::start(){void CaptureCardSource::recoverAudio(float gain,unsigned syncMode,int offsetMs){auto& p=*p_;if(!p.info.opened||!p.control||p.wasapi)return;CaptureSelection selection;if(!parseCapturePath(reconnectDesc_.path,selection)||!selection.stable||selection.audio==kCaptureAudioDisabled||selection.audio==kCaptureAudioWasapi)return;+ // A video filter without an audio pin can never recover: in the field log+ // this retried seven times over twenty seconds with an identical failure.+ if(selection.audio==kCaptureAudioFromVideoDevice&&p.embeddedAudioUnavailable){+ static bool reported=false;+ if(!reported){reported=true;log::warn("capture-audio-reconnect","embedded audio pin is absent on this device; recovery disabled, select a separate audio device");}+ return;+ }const auto state=p.audioSession?p.audioSession->snapshot():sink::CaptureAudioState{};if(!p.audioRecovery.due(state.inputBlocks,GetTickCount64()))return;// DirectShow audio/video pins share one graph. Briefly stop it to mutate@@ -994,6 +1047,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,cvoid CaptureCardSource::close()noexcept{auto& p=*p_;if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}if(p.wasapi)p.wasapi->stop();p.wasapi.reset();+ p.averMediaSwitch.stop();p.embeddedAudioUnavailable=false;if(p.audioSession)p.audioSession->stop();p.audioError.clear();if(p.audioPassthrough)p.audioPassthrough->close();p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();p.audioPassthrough.reset();diff --git a/tests/unit/AverMediaAudioSwitchTests.cpp b/tests/unit/AverMediaAudioSwitchTests.cppnew file mode 100644index 00000000..f8b39548--- /dev/null+++ b/tests/unit/AverMediaAudioSwitchTests.cpp@@ -0,0 +1,94 @@+// Unit checks for the AVerMedia multichannel-audio switch wrapper.+//+// The component it drives is optional: it only exists on machines where the+// user installed AVerMedia's OBS plugin. These checks therefore have to hold on+// both kinds of machine - with and without the component - and they must hold+// without any capture hardware attached.++#include "veyra/source/AverMediaAudioSwitch.h"++#include <windows.h>++#include <cstdio>+#include <string>++namespace {++int failures = 0;++void check(bool condition, const char* what) {+ if (condition) {+ std::printf("ok %s\n", what);+ } else {+ std::printf("FAIL %s\n", what);+ ++failures;+ }+}++} // namespace++int wmain() {+ using veyra::source::AverMediaAudioSwitch;++ // Device-path classification. AVerMedia's VID is 0x07CA; the GC553G2 is+ // PID 0x2553, which is what the shipped component also matches on.+ check(AverMediaAudioSwitch::isAverMediaDevicePath(+ L"\\\\?\\usb#vid_07ca&pid_2553#a0000000000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global"),+ "vid_07ca path is recognised");+ check(AverMediaAudioSwitch::isAverMediaDevicePath(+ L"\\\\?\\USB#VID_07CA&PID_2553#serial#{guid}"),+ "uppercase VID_07CA is recognised (case-insensitive)");+ check(!AverMediaAudioSwitch::isAverMediaDevicePath(+ L"\\\\?\\usb#vid_046d&pid_0825#6&2f0a1c4&0&1#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global"),+ "a non-AVerMedia device is rejected");+ check(!AverMediaAudioSwitch::isAverMediaDevicePath(L""), "an empty path is rejected");+ check(!AverMediaAudioSwitch::isAverMediaDevicePath(L"{0.0.1.00000000}.{1234}"),+ "a WASAPI endpoint id is rejected");++ // Component discovery must either find a usable folder or report nothing at+ // all; a half-matched folder would hand garbage to LoadLibrary later.+ const std::wstring root = AverMediaAudioSwitch::locateComponentRoot();+ if (root.empty()) {+ std::printf("note component not installed on this machine (expected on a bare test host)\n");+ check(true, "locateComponentRoot returns empty when absent");+ } else {+ const std::wstring dll = root + L"\\obs-plugins\\64bit\\avt_device_opener.dll";+ check(GetFileAttributesW(dll.c_str()) != INVALID_FILE_ATTRIBUTES,+ "located component provides avt_device_opener.dll");+ std::wprintf(L"note component root: %ls\n", root.c_str());+ }++ // Without the component, apply() must fail soft: no crash, no throw, a+ // state a caller can log, and a usable object afterwards.+ AverMediaAudioSwitch first;+ const bool applied = first.apply(L"USB3 Digital Audio",+ L"\\\\?\\usb#vid_07ca&pid_2553#serial#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global");+ const auto& status = first.status();+ if (root.empty()) {+ check(!applied, "apply() reports failure when the component is absent");+ check(!status.componentFound, "status marks the component as absent");+ check(!status.dllsLoaded, "status marks the DLLs as not loaded");+ check(!status.detail.empty(), "status carries a reason for the log");+ check(status.state == veyra::source::AverMediaSwitchState::Unavailable,+ "status state is Unavailable");+ } else {+ // With a component present the call is allowed to succeed or fail (no+ // card is attached here), but it must never fault the process.+ std::printf("note apply() with component present returned %d: %s\n", applied ? 1 : 0, status.detail.c_str());+ check(true, "apply() completed without faulting");+ }++ // Teardown must be idempotent: close() calls stop() and then the destructor+ // runs it again.+ first.stop();+ first.stop();+ check(!first.active(), "stop() leaves the helper inactive");+ {+ AverMediaAudioSwitch second;+ second.stop();+ }+ check(true, "destructor after stop() is safe");++ std::printf("%s (%d failure%s)\n", failures == 0 ? "PASS" : "FAIL", failures, failures == 1 ? "" : "s");+ return failures == 0 ? 0 : 1;+}