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++
fix(capture): adapt PR63 audio identity, carrier transitions and bounded vendor recovery
Veyra Goal Agent1f96e8f8e9e5
diff --git a/AGENTS.md b/AGENTS.mdindex 32213dda..f5a741b4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-18 PR63接入授权**:用户明确要求合并适配PR63(圆刚厂商音频图)。按docs/PR63_AVERMEDIA_AUDIO_PLAN_2026-10-18.md在codex/pr63-avermedia-audio-20261018实施,允许音频源/位流解码/会话/状态及必要CMake/测试/文档适配,覆盖这些接点的旧冻结。先存档90工作树/103分支及旧脏文件;保留PR57和其他未合分支,不碰Claude施工。通过本机Windows定向验收后允许合并本PR和适配到main、普通GitHub同步,不发布/代发评论/关机。厂商DLL只可读本机已安装原件、无实卡不虚报;专有文件不改不进Git,产物全E盘,构建≤900秒/测试≤300秒、限-j2、无Agent/UI频率变更。+> **2026-10-17 PR57本机接入授权**:用户要求合入其云端Agent的PR57并做好测试。按docs/PR57_INTEGRATION_PLAN_2026-10-17.md,从main d68d6be在codex/pr57-capture-window-20261017保留原head09ac54b/1295d6b整合;允许窗口捕获游戏输入/缩放/resize及采集能力/精确格式/旧版选择入口的必要适配、源/引擎快照/bridge/QML/CMake/翻译/回归接点,覆盖这些范围历史冻结。本机Windows构建/实测通过后允许本地main正常合并与普通GitHub同步以完成PR57;不发布新版本、不改已发2.0.9资产/标签、不代发评论/关闭无关issue/派Agent/关机。84旧树/96旧分支/509脏文件与PR/源码bundle先存档;全E盘,测试≤300秒/构建≤900秒,UI33ms/250ms、既有低延迟/运行组件/模型/驱动/真实配置保持。云端测试待办不扩展当前授权,实卡未覆盖项须明示。> **2026-10-17 2.0.9 正式发布授权**:用户明确“发布吧,老样子发好给我群公告”。按docs/RELEASE_2.0.9_PLAN_2026-10-17.md从已验bfce70b建立codex/release-2.0.9-20261017,允许已验代码main正常快进/普通push nrvideo/main、新v2.0.9与v2.0.9-sources标签、正式Release及对应源码上传。NVIDIA/AMD沿用已交付2.0.9-test ZIP,外部正式命名,包内字节/test标识保持,不重编译重封包。中英README和完整更新报告覆盖全部2.0.8后改动,保留六群/赞助width220、Discord/Ko-fi/知识库;主仅两包,源归档上传应用源与新增去隔行源,旧FFmpeg/依赖源保留固定链接。83旧树/95旧分支/509脏文件/六原归档与旧Release保护,全E盘,无子Agent/代发/关闭issue/关机。最新授权覆盖此前本轮no-main/no-push/no-Release,不扩展为修改专有二进制、驱动或用户配置。diff --git a/CMakeLists.txt b/CMakeLists.txtindex 0a1c807f..94b5eaf4 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -582,6 +582,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/source/ScreenCaptureSource.cppsrc/source/AverMediaAudioSwitch.cppsrc/source/AverMediaVendorAudio.cpp+ src/source/AverMediaAudioCarrier.cppsrc/source/CaptureCompressedDecoder.cppsrc/source/WasapiAudioInput.cppsrc/source/MagewellCapture.cpp@@ -790,6 +791,23 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_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)+ add_executable(veyra_avermedia_carrier_tests tests/unit/AverMediaCarrierTests.cpp)+ target_compile_features(veyra_avermedia_carrier_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_avermedia_carrier_tests PRIVATE /utf-8)+ target_compile_definitions(veyra_avermedia_carrier_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_include_directories(veyra_avermedia_carrier_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_link_libraries(veyra_avermedia_carrier_tests PRIVATE veyra_sources ${FFMPEG_LIBRARIES})+ add_library(veyra_avermedia_fake_vendor SHARED tests/fixtures/FakeAverMediaVendor.cpp tests/fixtures/FakeAverMediaVendor.def)+ target_compile_features(veyra_avermedia_fake_vendor PRIVATE cxx_std_20)+ target_compile_options(veyra_avermedia_fake_vendor PRIVATE /utf-8)+ target_compile_definitions(veyra_avermedia_fake_vendor PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_include_directories(veyra_avermedia_fake_vendor PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ target_link_libraries(veyra_avermedia_fake_vendor PRIVATE ole32)+ add_executable(veyra_avermedia_vendor_tests tests/unit/AverMediaVendorAudioTests.cpp)+ target_compile_features(veyra_avermedia_vendor_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_avermedia_vendor_tests PRIVATE /utf-8)+ target_compile_definitions(veyra_avermedia_vendor_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_link_libraries(veyra_avermedia_vendor_tests PRIVATE veyra_sources)add_executable(veyra_iec61937_probe_tests tests/unit/Iec61937ProbeTests.cpp)target_compile_features(veyra_iec61937_probe_tests PRIVATE cxx_std_20)target_compile_definitions(veyra_iec61937_probe_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 799e2846..4c781cd6 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -938,3 +938,10 @@ Source: https://github.com/FFmpeg/FFmpeg/tree/bf1b838f2ab88b4f8fd83443325c782ea0Changes to `libavfilter/vf_deinterlace_d3d12.c` are supplied as `scripts/ffmpeg/deinterlace-d3d12-async.patch`: eight submission slots retain reference frames until their GPU fence completes, retain/signal the output pool's own fence, respect visible dimensions instead of padded decode allocation sizes, use declared stream frame rate, correct short-stream/field timestamps and drain final output before EOF. Slots only wait when reused while occupied; normal execution does not wait on every pass. `scripts/ffmpeg/build-deinterlace-module.py` also accommodates the localized MSVC banner during configure without changing its ABI. The caller wraps existing D3D11/D3D12 GPU surfaces, preserves source time/field order, and resets filter history on seek/close/fallback. It does not copy GPU pixels back to the CPU during playback.Redistribution of this module must include `COPYING.LGPLv2.1`, the FFmpeg license notice, the actual configuration/hash/patch manifest and the complete corresponding-source archive generated by that script. Build/use boundaries and rebuild instructions: `docs/BUILD_DEINTERLACE_2026-10-16.md`. MediaMTX v1.21.2 (MIT, https://github.com/bluenviron/mediamtx/releases/tag/v1.21.2) is used only as a loopback RTSP regression server and is not shipped in the player.+## AVerMedia vendor audio graph (PR63)++- Integration source: [Se7eNHea7eN/Veyra-NRVideo PR63](https://github.com/Likely7/Veyra-NRVideo/pull/63), fixed commit `4db24dada13748364d7e613bc4160224b330a7d2`, Veyra GPL-3.0 repository. The original graph adapter is credited to that contribution.+- Adapted files: `include/veyra/source/AverMediaVendorAudio.h`, `src/source/AverMediaVendorAudio.cpp`, `src/source/CaptureCardSource.cpp`, and CMake. Veyra additions split bounded carrier handling into `AverMediaAudioCarrier`, add strict identity/public-ABI declarations in `AverMediaVendorProtocol`, format-aware decoding in `BitstreamAudio`, and source-only test doubles/codec tests.+- ABI reference only: AVerMedia's [obs-MultichannelAudio public headers](https://github.com/AVerMedia-Technologies-Inc/obs-MultichannelAudio/tree/7d1250b42e42f964b4fa3a6bcb7269cc09a1e798/avt_dshow_core/include), fixed commit `7d1250b42e42f964b4fa3a6bcb7269cc09a1e798`. Its repository contains a GPL-2.0 license. No OBS implementation source or proprietary vendor implementation is copied into Veyra; local declarations describe the public x64 call contract (`AudioDevice`, `AudioDealer`, `AUDIO_SAMPLE_INFO`, `DeviceInfo`, and `LogHelper`).+- Changes include STA ownership, bounded asynchronous startup/recovery, exact device matching, callback lifetime protection, guarded external calls/log formatting, continuously detected IEC 61937, and actual decoded channel-layout changes. The separately installed `avt_dshow_core.dll` and its dependencies are loaded in place by absolute path; they are never modified or included in source or test fixtures. Users must install the official AVerMedia Multichannel Audio component themselves. This does not grant redistribution rights or certify untested card/driver versions.+diff --git a/docs/PR63_AVERMEDIA_AUDIO_PLAN_2026-10-18.md b/docs/PR63_AVERMEDIA_AUDIO_PLAN_2026-10-18.mdnew file mode 100644index 00000000..91e6a78a--- /dev/null+++ b/docs/PR63_AVERMEDIA_AUDIO_PLAN_2026-10-18.md@@ -0,0 +1,21 @@+# PR63 圆刚厂商音频图接入与适配++用户要求合并适配PR63。开工main26c0d61,远端main f0cbbbf(仅星图更新);PR head4db24dada13748364d7e613bc4160224b330a7d2。90工作树/103分支/509旧脏文件、已验证source-before.bundle和原PR归档在E:/项目/Veyra/archives/pr63-avermedia-audio-20261018。独立codex/pr63-avermedia-audio-20261018完成三方合并8147496,保留PR57格式枚举/精确连接代码。AMD0.44、全屏输入和Claude未合分支保持独立。++## 发现的真实缺口++- 单独音频路径仅检查组件存在,就可能选中其他圆刚卡;有identity时仍回退任意音频,违反用户选择。+- 厂商公开7d1250b4头文件回调为BOOL(AUDIO_SAMPLE_INFO按值,BYTE*,LONG),原PR忽略元数据且多一个参数,另读取私有core+0x18布局。+- 日志extra实际是va_list,却当C字符串解引用;外部调用没有已有开关模块的SEH保护。早期失败漏RemoveDllDirectory,启动持锁睡眠,异步失败不回退。+- 6ch→2ch/采样率变化不重配CaptureAudioSession,原模型声道mask猜测;手动PCM/接收器位流偏好被绕过。+- 回调无数据或无新AC3时在监测前return,6秒恢复失效;PCM模式不再检测新位流,可能播放压缩噪声;初始缓存4秒PCM重放造成延迟/队列拒绝。++## 适配范围++1. 严格选择本次所选设备,其他设备、PCM-only、接收器透传偏好沿用原路径;不共享厂商图到错误设备。+2. 按公开API ABI镜像,去私有偏移,受限绝对路径加载/释放、外部故障保护、STA消息泵、无锁睡眠和明确启动/失败状态。回调退出后再释放会话。+3. 提取有界载波处理供真实解码测试:分片头/负载、有效突发计数、Pc/长度/字序、连续检测及格式切换;压缩载波不作为PCM直出,不积压数秒PCM。+4. 使用实际解码布局/采样率,格式变化重启原CaptureAudioSession并reset时钟/历史;保留音量/同步/录制及诊断。必要修补共享BitstreamDecoder的格式切换与输入padding/无进展边界。+5. 真实音频编码夹具、fake厂商ABI/故障/线程/恢复测试、既有音频与采集回归;独立完整Windows应用构建。若本机无圆刚实卡,明确未验,不使用作者截图替代本机证明。++所有产物在E盘pr63-avermedia-audio-20261018目录,构建-j2/≤900秒,每次测试≤300秒。新源码/测试/说明可入Git;不下载/分发厂商二进制,不修改驱动/组件/用户配置,不派Agent,不提高33ms/250ms/UI重绘频率。验收后按用户授权合并PR63及适配到main并普通同步GitHub,不发布新版本/改Release、不代发评论/关机。合并前重新核对远端head和本地main,禁止force。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 721410bd..67cf6103 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,9 @@# WORKLOG+## 2026-10-18 PR63 圆刚5.1厂商图接入开工++已存档90旧工作树/103分支/509旧脏文件,source-before.bundle verify通过;原PR4db24da及patch在archives/pr63-avermedia-audio-20261018。nrvideo/main f0cbbbf仅星图更新,隔离合并8147496保留PR57新枚举/精确连接接口。公开厂商头7d1250b4固定归档至deps/.../reference,ABI为12字节AUDIO_SAMPLE_INFO按值回调;原PR签名/日志varargs/私有offset/设备误路由/格式切换/断流监测存在缺口,按PR63_AVERMEDIA_AUDIO_PLAN_2026-10-18.md补齐。全E盘、无子Agent、不碰Claude/旧树/真实配置,验收后只合并同步PR63不发布。+## 2026-10-17 采集格式与旧版入口(Linux 源码候选)按用户“全部修复掉,再添加老版本采集格式选择入口”,在窗口修复 1295d6b 之上隔离实施 `codex/capture-format-fixes-20261017`。修复 DirectShow 能力回退、尺寸/帧率范围候选、±1 tick 显示分组漏掉像素项、精确媒体类型恢复与连接校验;增加可搜索虚拟化旧版组合列表、自定义尺寸检查和查询错误诊断。原低延迟回调/队列、BMD 原生、增强/音频/渲染/运行库与配置保持。详见 docs/CAPTURE_FORMAT_FIXES_2026-10-17.md。diff --git a/include/veyra/sink/BitstreamAudio.h b/include/veyra/sink/BitstreamAudio.hindex 3816faa8..d7a092e8 100644--- a/include/veyra/sink/BitstreamAudio.h+++ b/include/veyra/sink/BitstreamAudio.h@@ -95,6 +95,8 @@ public:bool opened() const;unsigned channels() const;unsigned sampleRate() const;+ uint32_t channelMask() const;+ uint64_t formatRevision() const;uint64_t decodedFrames() const;uint64_t decodedBytesIn() const;const std::string& lastError() const;diff --git a/include/veyra/source/AverMediaAudioCarrier.h b/include/veyra/source/AverMediaAudioCarrier.hnew file mode 100644index 00000000..0bb8ced7--- /dev/null+++ b/include/veyra/source/AverMediaAudioCarrier.h@@ -0,0 +1,51 @@+#pragma once+#include "veyra/source/AverMediaVendorProtocol.h"+#include "veyra/sink/BitstreamAudio.h"+#include <functional>+#include <memory>+#include <span>+#include <vector>++namespace veyra::source {+struct VendorPcmBlock {+ const float* samples=nullptr;+ size_t frames=0;+ unsigned channels=0;+ uint32_t rate=0,mask=0;+ bool discontinuity=false;+ std::string_view codec;+};+struct VendorCarrierState {+ bool bitstream=false;+ unsigned channels=0;+ uint32_t rate=0;+ uint64_t bursts=0,decodedFrames=0,pcmFrames=0,droppedBytes=0;+ size_t retainedBytes=0;+ std::string codec,error;+};+// Thread-affine, bounded, continuously detecting carrier. The explicit clock+// permits deterministic transition tests without waiting for hardware timers.+class AverMediaAudioCarrier {+public:+ using Callback=std::function<bool(const VendorPcmBlock&)>;+ static constexpr size_t kMaxBytes=131072;+ explicit AverMediaAudioCarrier(Callback callback);+ bool feed(std::span<const uint8_t>,avermedia::SampleInfo,double now);+ void reset();+ const VendorCarrierState& state()const{return state_;}+private:+ bool emitPcm(std::span<const uint8_t>,avermedia::SampleInfo);+ bool emitBurst(std::span<const uint8_t>,sink::BitstreamKind);+ Callback callback_;+ VendorCarrierState state_;+ std::vector<uint8_t> buffer_,packet_;+ std::vector<float> pcm_;+ std::unique_ptr<sink::BitstreamDecoder> decoder_;+ sink::BitstreamKind kind_=sink::BitstreamKind::None,candidate_=sink::BitstreamKind::None;+ unsigned confirmations_=0;+ bool compressed_=false,discontinuity_=true;+ double lastIec_=0;+ uint64_t revision_=0;+ avermedia::SampleInfo input_{};+};+} // namespace veyra::sourcediff --git a/include/veyra/source/AverMediaVendorAudio.h b/include/veyra/source/AverMediaVendorAudio.hindex ff992ca4..1702e9a1 100644--- a/include/veyra/source/AverMediaVendorAudio.h+++ b/include/veyra/source/AverMediaVendorAudio.h@@ -10,8 +10,8 @@// IEC 61937 carrier into interleaved float PCM for the existing capture audio// session.//-// The call sequence and the AudioDealer ABI were measured on 2026-10-18 and are-// documented in docs/AVERMEDIA_5P1_DRIVE_HANDOFF_2026-10-18.md. Everything here+// The AudioDealer ABI is checked against the fixed public headers referenced+// in THIRD_PARTY_NOTICES.md. Everything here// is read-only with respect to the vendor binaries: they are loaded by absolute// path from the user's own installation, never copied, patched or signed.//@@ -19,17 +19,16 @@// * The carrier arrives as 16-bit stereo at 48 kHz. When IEC 61937 bursts are// present the payload is unwrapped, byte-swapped per 16-bit word and sent to// the FFmpeg AC-3 decoder already used by the bitstream capture path.-// * When no burst appears within the probe window the carrier is treated as-// ordinary linear PCM and passed through unchanged, so a console that is-// set to Linear PCM still produces sound on this path.-// * After the graph has delivered a stream, a burst silence longer than the-// loss window rebuilds the vendor graph. This is what recovers the capture-// after the console changes its audio output format.+// * PCM uses its actual callback metadata. Carrier detection continues while+// PCM plays; compressed-to-PCM changes reconfigure the existing session.+// * A bounded watchdog rebuilds the graph when callbacks stop or decoding+// fails, then exposes terminal failure for the owner's DirectShow fallback.#include <cstdint>#include <functional>#include <memory>#include <string>+#include "veyra/source/AverMediaAudioCarrier.h"namespace veyra::source {@@ -37,6 +36,8 @@ struct AverMediaVendorAudioState {bool started = false;bool running = false;bool bitstream = false;+ bool starting = false;+ bool failed = false;std::wstring device;std::string carrier; // "AC-3" / "linear PCM 2ch" once decidedunsigned channels = 0;@@ -58,18 +59,18 @@ public:struct Impl;// Called on the vendor streaming thread with interleaved float PCM.- // `frames` counts sample frames, not floats.- using PcmCallback =- std::function<void(const float* interleaved, size_t frames, unsigned channels, uint32_t sampleRate)>;+ // Block frames count sample frames, not floats. False requests recovery.+ using PcmCallback = AverMediaAudioCarrier::Callback;- AverMediaVendorAudio();+ explicit AverMediaVendorAudio(unsigned stallMs=6000,unsigned maxRestarts=3);~AverMediaVendorAudio();AverMediaVendorAudio(const AverMediaVendorAudio&) = delete;AverMediaVendorAudio& operator=(const AverMediaVendorAudio&) = delete;// Resolves the installed component, starts the vendor graph on a dedicated- // STA thread and begins delivering PCM. Returns false (and fills state())- // when the component is missing or the graph refuses to bind.+ // STA thread. Waits at most 150ms for an initial result; a true return may+ // mean pending startup. state().starting/failed distinguishes that from+ // actual samples. Missing components and immediate failures return false.// `preferName` is the capture card's own name ("Live Gamer Ultra 2.1") and// `preferPath` its DirectShow device path. The vendor device list is matched// on the USB instance first (the audio function of the same card shares it),diff --git a/include/veyra/source/AverMediaVendorProtocol.h b/include/veyra/source/AverMediaVendorProtocol.hnew file mode 100644index 00000000..d75d193d--- /dev/null+++ b/include/veyra/source/AverMediaVendorProtocol.h@@ -0,0 +1,81 @@+#pragma once++// ABI/identity contract referenced from AVerMedia's public OBS headers at+// obs-MultichannelAudio 7d1250b42e42f964b4fa3a6bcb7269cc09a1e798.+// This is a local interface mirror, not the proprietary runtime or SDK.+#include <algorithm>+#include <cstdint>+#include <cwctype>+#include <cwchar>+#include <optional>+#include <span>+#include <string>+#include <string_view>++namespace veyra::source::avermedia {+struct SampleInfo { uint32_t channels=0,bits=0,rate=0; };+static_assert(sizeof(SampleInfo)==12);+struct DeviceInfo { std::wstring friendlyName,devicePath; };+class AudioDealer {+public:+ virtual ~AudioDealer() = default;+ virtual int onAudioData(SampleInfo, unsigned char*, long) = 0;+};+inline std::wstring lower(std::wstring_view value) {+ std::wstring out(value); for(auto& c:out)c=wchar_t(towlower(c)); return out;+}+inline bool vendorPath(std::wstring_view path) {+ return lower(path).find(L"vid_07ca")!=std::wstring::npos;+}+inline std::wstring usbIdentity(std::wstring_view path) {+ auto p=lower(path); std::replace(p.begin(),p.end(),L'\\',L'#');+ const auto vid=p.find(L"vid_07ca&pid_"); if(vid==p.npos)return {};+ const auto first=p.find(L'#',vid),last=first==p.npos?p.npos:p.find(L'#',first+1);+ if(first==p.npos)return {};+ auto product=p.substr(vid,first-vid),instance=p.substr(first+1,last==p.npos?p.npos:last-first-1);+ const auto mi=product.find(L"&mi_");+ if(mi!=product.npos){+ product.erase(mi);const auto tail=instance.rfind(L'&');+ if(tail!=instance.npos&&instance.size()-tail==5+ &&std::all_of(instance.begin()+tail+1,instance.end(),[](wchar_t c){return iswxdigit(c)!=0;}))instance.erase(tail);+ }+ return instance.empty()?std::wstring():product+L"#"+instance;+}+inline std::wstring deviceName(std::wstring_view text) {+ auto n=lower(text);+ // Windows wraps the actual device name, e.g. HDMI/Line In (...-Audio).+ const auto left=n.find(L'('),right=n.rfind(L')');+ if(left!=n.npos&&right>left)n=n.substr(left+1,right-left-1);+ for(auto suffix:{L"-audio",L"-video",L" (audio)",L" (video)"}){+ const auto at=n.find(suffix);if(at!=n.npos)n.erase(at,wcslen(suffix));+ }+ while(!n.empty()&&iswspace(n.back()))n.pop_back();+ return n;+}+inline bool vendorName(std::wstring_view name) {+ const auto n=lower(name);return n.find(L"avermedia")!=n.npos||n.find(L"live gamer")!=n.npos;+}+inline bool eligible(std::wstring_view name,std::wstring_view path,unsigned ingress) {+ // PCM-only never arms the non-PCM graph. A component installed for another+ // card is not evidence that the explicitly selected microphone is ours.+ const auto p=lower(path);+ if(p.find(L"vid_")!=p.npos&&!vendorPath(p))return false;+ return ingress!=1&&(vendorPath(path)||vendorName(name));+}+inline std::optional<size_t> selectDevice(std::span<const DeviceInfo> devices,+ std::wstring_view name,std::wstring_view path) {+ const auto exact=lower(path),identity=usbIdentity(path),wanted=deviceName(name);+ std::optional<size_t> match;+ for(size_t i=0;i<devices.size();++i){+ const auto& d=devices[i];if(d.devicePath.empty())continue;+ if(!exact.empty()&&lower(d.devicePath)==exact)return i;+ if(!identity.empty()){+ if(usbIdentity(d.devicePath)!=identity)continue;+ }else if(wanted.empty()||deviceName(d.friendlyName)!=wanted)continue;+ if(!vendorPath(d.devicePath)&&!vendorName(d.friendlyName))continue;+ if(match)return {}; // Ambiguous identical cards: never donate audio.+ match=i;+ }+ return match;+}+} // namespace veyra::source::avermediadiff --git a/src/sink/BitstreamAudio.cpp b/src/sink/BitstreamAudio.cppindex 2b6c9edb..3cc18979 100644--- a/src/sink/BitstreamAudio.cpp+++ b/src/sink/BitstreamAudio.cpp@@ -158,6 +158,9 @@ struct BitstreamDecoder::Impl {bool outLayoutValid = false;std::vector<uint8_t> iecPending;std::vector<uint8_t> parserScratch;+ std::vector<uint8_t> inputScratch;+ uint64_t formatRevision=0;+ int outputRate=0,outputSampleFormat=-1;std::string lastError;uint64_t frames = 0;uint64_t bytesIn = 0;@@ -170,6 +173,7 @@ struct BitstreamDecoder::Impl {if (packet != nullptr) av_packet_free(&packet);if (parser != nullptr) av_parser_close(parser);if (context != nullptr) avcodec_free_context(&context);+ av_channel_layout_uninit(&outLayout);outLayoutValid = false;}@@ -222,6 +226,12 @@ struct BitstreamDecoder::Impl {}bool handleFrame(std::vector<float>& out) {+ if(outLayoutValid&&(av_channel_layout_compare(&outLayout,&frame->ch_layout)!=0+ ||outputRate!=frame->sample_rate||outputSampleFormat!=frame->format)){+ // A console can switch channel layout without changing codec.+ // Do not concatenate samples from two formats into one callback.+ out.clear();swr_free(&resampler);av_channel_layout_uninit(&outLayout);outLayoutValid=false;+ }if (!outLayoutValid) {if (av_channel_layout_copy(&outLayout, &frame->ch_layout) < 0) {lastError = "decoded frame has no usable channel layout";@@ -231,6 +241,7 @@ struct BitstreamDecoder::Impl {av_channel_layout_default(&outLayout, outLayout.nb_channels > 0 ? outLayout.nb_channels : 2);}outLayoutValid = true;+ outputRate=frame->sample_rate;outputSampleFormat=frame->format;++formatRevision;}if (!ensureResampler()) return false;const unsigned channels = unsigned(outLayout.nb_channels);@@ -339,6 +350,11 @@ bool BitstreamDecoder::push(const uint8_t* data, size_t bytes, std::vector<floatreturn p.decodePacket(out);}+ // FFmpeg parsers require zero padding even when the caller supplies a+ // complete IEC payload. A vector's spare capacity is not readable padding.+ p.inputScratch.assign(stream,stream+streamBytes);+ p.inputScratch.resize(streamBytes+AV_INPUT_BUFFER_PADDING_SIZE,0);+ stream=p.inputScratch.data();size_t offset = 0;while (offset < streamBytes) {uint8_t* packetData = nullptr;@@ -350,6 +366,7 @@ bool BitstreamDecoder::push(const uint8_t* data, size_t bytes, std::vector<floatreturn false;}offset += size_t(consumed);+ if(consumed==0&&packetSize<=0){p.lastError="codec parser made no progress";return false;}if (packetSize <= 0) continue;av_packet_unref(p.packet);if (av_new_packet(p.packet, packetSize) < 0) {@@ -366,6 +383,7 @@ void BitstreamDecoder::reset() {auto& p = *p_;p.iecPending.clear();p.parserScratch.clear();+ swr_free(&p.resampler);av_channel_layout_uninit(&p.outLayout);p.outLayoutValid=false;if (p.context != nullptr) avcodec_flush_buffers(p.context);if (p.parser != nullptr) av_parser_close(p.parser);if (p.context != nullptr) p.parser = av_parser_init(p.context->codec_id);@@ -379,6 +397,10 @@ unsigned BitstreamDecoder::sampleRate() const {return p_->context != nullptr ? unsigned(p_->context->sample_rate) : 0;}uint64_t BitstreamDecoder::decodedFrames() const { return p_->frames; }+uint32_t BitstreamDecoder::channelMask() const {+ return p_->outLayoutValid&&p_->outLayout.order==AV_CHANNEL_ORDER_NATIVE?uint32_t(p_->outLayout.u.mask):0;+}+uint64_t BitstreamDecoder::formatRevision() const { return p_->formatRevision; }uint64_t BitstreamDecoder::decodedBytesIn() const { return p_->bytesIn; }const std::string& BitstreamDecoder::lastError() const { return p_->lastError; }diff --git a/src/source/AverMediaAudioCarrier.cpp b/src/source/AverMediaAudioCarrier.cppnew file mode 100644index 00000000..c74d31fa--- /dev/null+++ b/src/source/AverMediaAudioCarrier.cpp@@ -0,0 +1,127 @@+#include "veyra/source/AverMediaAudioCarrier.h"+#include <algorithm>+#include <cmath>+#include <cstring>++namespace veyra::source {+namespace {+constexpr uint8_t syncBytes[]{0x72,0xF8,0x1F,0x4E};+uint16_t word(const uint8_t* p){return uint16_t(p[0])|uint16_t(p[1])<<8;}+bool sync(const uint8_t* p){return std::memcmp(p,syncBytes,4)==0;}+bool supported(sink::BitstreamKind k){return k==sink::BitstreamKind::Ac3||k==sink::BitstreamKind::Eac3||k==sink::BitstreamKind::Dts;}+}+AverMediaAudioCarrier::AverMediaAudioCarrier(Callback callback):callback_(std::move(callback)){}+void AverMediaAudioCarrier::reset(){+ buffer_.clear();packet_.clear();pcm_.clear();decoder_.reset();state_={};+ kind_=candidate_=sink::BitstreamKind::None;confirmations_=0;compressed_=false;discontinuity_=true;lastIec_=0;revision_=0;input_={};+}+bool AverMediaAudioCarrier::emitPcm(std::span<const uint8_t> bytes,avermedia::SampleInfo info){+ // The public callback describes the samples. Never guess 16-bit/48k from+ // the size of a driver delivery (24-bit PCM is not a compressed carrier).+ if(info.channels<1||info.channels>8||info.rate<8000||info.rate>192000+ ||(info.bits!=16&&info.bits!=24&&info.bits!=32)){state_.error="unsupported vendor PCM format";return false;}+ const size_t sampleBytes=info.bits/8,align=sampleBytes*info.channels,frames=bytes.size()/align;+ // Limit each session push to 20 ms; never replay a four-second probe queue.+ const size_t blockFrames=std::max<size_t>(1,info.rate/50);+ for(size_t frame=0;frame<frames;frame+=blockFrames){+ const size_t count=std::min(blockFrames,frames-frame);pcm_.resize(count*info.channels);+ for(size_t i=0;i<pcm_.size();++i){+ const auto* p=bytes.data()+(frame*info.channels+i)*sampleBytes;+ uint32_t v=0;for(size_t j=0;j<sampleBytes;++j)v|=uint32_t(p[j])<<(8*j);+ const int32_t value=info.bits==16?int32_t(int16_t(v)):info.bits==24?int32_t(v<<8)>>8:int32_t(v);+ pcm_[i]=float(double(value)/std::ldexp(1.0,int(info.bits)-1));+ }+ const uint32_t mask=info.channels==1?4:info.channels==2?3:info.channels==6?0x3f:info.channels==8?0x63f:0;+ if(!mask){state_.error="vendor PCM has no declared speaker layout";return false;}+ VendorPcmBlock block{pcm_.data(),count,info.channels,info.rate,mask,discontinuity_,{}};+ if(callback_&&!callback_(block)){state_.error="capture audio session rejected PCM";return false;}+ discontinuity_=false;state_.pcmFrames+=count;+ }+ state_.channels=info.channels;state_.rate=info.rate;state_.codec="linear PCM";state_.bitstream=false;state_.error.clear();+ return true;+}+bool AverMediaAudioCarrier::emitBurst(std::span<const uint8_t> words,sink::BitstreamKind kind){+ if(kind!=candidate_){candidate_=kind;confirmations_=0;}+ if(confirmations_<2)++confirmations_;+ if(confirmations_<2)return true; // Count distinct complete payloads, not sync inside a payload.+ if(!supported(kind)){state_.error="unsupported IEC 61937 vendor carrier";return true;}+ if(!decoder_||kind!=kind_){+ decoder_=std::make_unique<sink::BitstreamDecoder>();+ if(!decoder_->open(kind,false)){state_.error=decoder_->lastError();return false;}+ kind_=kind;revision_=0;discontinuity_=true;+ }+ packet_.resize(words.size());+ for(size_t i=0;i+1<words.size();i+=2){packet_[i]=words[i+1];packet_[i+1]=words[i];}+ if(words.size()%2)packet_.back()=words.back();+ pcm_.clear();+ if(!decoder_->push(packet_.data(),packet_.size(),pcm_)){state_.error=decoder_->lastError();return false;}+ state_.codec=sink::bitstreamKindName(kind);state_.bitstream=true;+ const auto channels=decoder_->channels(),rate=decoder_->sampleRate();+ if(!pcm_.empty()&&channels&&rate){+ discontinuity_=discontinuity_||revision_!=decoder_->formatRevision();revision_=decoder_->formatRevision();+ VendorPcmBlock block{pcm_.data(),pcm_.size()/channels,channels,rate,decoder_->channelMask(),discontinuity_,state_.codec};+ if(callback_&&!callback_(block)){state_.error="capture audio session rejected decoded carrier";return false;}+ discontinuity_=false;state_.decodedFrames+=block.frames;state_.channels=channels;state_.rate=rate;+ }+ state_.error.clear();return true;+}+bool AverMediaAudioCarrier::feed(std::span<const uint8_t> bytes,avermedia::SampleInfo info,double now){+ if(bytes.empty())return true;+ if(input_.channels!=info.channels||input_.bits!=info.bits||input_.rate!=info.rate){reset();input_=info;}+ const size_t align=size_t(info.channels)*(info.bits/8);+ if(!align||align>32||bytes.size()>kMaxBytes){state_.error="invalid or oversized vendor callback";return false;}+ // Only 16-bit stereo is an IEC carrier. Other declared PCM is converted+ // using its actual metadata and still goes through the shared session.+ if(info.bits!=16||info.channels!=2){+ if(compressed_){decoder_.reset();compressed_=false;discontinuity_=true;}+ buffer_.insert(buffer_.end(),bytes.begin(),bytes.end());+ const size_t complete=buffer_.size()/align*align;+ const bool ok=emitPcm(std::span(buffer_).first(complete),info);+ buffer_.erase(buffer_.begin(),buffer_.begin()+complete);state_.retainedBytes=buffer_.size();return ok;+ }+ if(buffer_.size()+bytes.size()>kMaxBytes){state_.droppedBytes+=buffer_.size();buffer_.clear();discontinuity_=true;}+ buffer_.insert(buffer_.end(),bytes.begin(),bytes.end());+ size_t cursor=0;bool sawIec=false;+ while(cursor+8<=buffer_.size()){+ if(cursor%4||!sync(buffer_.data()+cursor)){++cursor;continue;}+ sawIec=true;+ const uint16_t pc=word(buffer_.data()+cursor+4),pd=word(buffer_.data()+cursor+6);+ const auto type=pc&0x1f;+ const auto kind=sink::classifyIec61937DataType(uint16_t(type));+ // E-AC3 and HD data lengths use bytes, AC3 and DTS-core use bits.+ const size_t payload=(type==0x15||type==0x11||type==0x16)?pd:(size_t(pd)+7)/8;+ if(!compressed_){+ // No compressed payload (including an unsupported one) is audible+ // as PCM. Discard a short raw prefix at the format boundary.+ compressed_=true;discontinuity_=true;decoder_.reset();candidate_=sink::BitstreamKind::None;confirmations_=0;+ }+ lastIec_=now;+ if(!pd||(pc&0x80)){cursor+=8;continue;} // pause/error: do not pin the parser at a zero length header.+ if(payload>kMaxBytes-8){++cursor;continue;}+ const size_t stored=(payload+1)&~size_t(1);+ if(cursor+8+stored>buffer_.size())break;+ ++state_.bursts;+ const bool ok=emitBurst(std::span(buffer_).subspan(cursor+8,payload),kind);+ cursor+=8+stored;+ if(!ok){buffer_.erase(buffer_.begin(),buffer_.begin()+cursor);state_.retainedBytes=buffer_.size();return false;}+ }+ if(sawIec||compressed_){+ if(!sawIec&&now-lastIec_>=4.0){+ // The source changed to real PCM. Retain only its newest 20 ms,+ // reset codec history and reconfigure the same playback session.+ const size_t tail=std::min(buffer_.size()/align*align,size_t(info.rate/50)*align);+ decoder_.reset();kind_=candidate_=sink::BitstreamKind::None;confirmations_=0;compressed_=false;discontinuity_=true;+ const bool ok=emitPcm(std::span(buffer_).last(tail),info);buffer_.clear();state_.retainedBytes=0;return ok;+ }+ // Preserve only a partial payload, or at most seven sync/header bytes.+ cursor=cursor/align*align;+ if(cursor)buffer_.erase(buffer_.begin(),buffer_.begin()+cursor);+ }else{+ // Keep two sample frames so a split sync cannot leak a header/payload+ // prefix to the speakers. This adds <0.1ms, not a multi-second backlog.+ const size_t complete=buffer_.size()>8?(buffer_.size()-8)/align*align:0;+ if(complete){const bool ok=emitPcm(std::span(buffer_).first(complete),info);if(!ok)return false;buffer_.erase(buffer_.begin(),buffer_.begin()+complete);}+ }+ state_.retainedBytes=buffer_.size();return true;+}+} // namespace veyra::sourcediff --git a/src/source/AverMediaVendorAudio.cpp b/src/source/AverMediaVendorAudio.cppindex ec0fd17e..518cbb94 100644--- a/src/source/AverMediaVendorAudio.cpp+++ b/src/source/AverMediaVendorAudio.cpp@@ -1,628 +1,209 @@#include "veyra/source/AverMediaVendorAudio.h"-#include "veyra/source/AverMediaAudioSwitch.h"-#include "veyra/sink/BitstreamAudio.h"#include "veyra/Log.h"-#include <windows.h>#include <objbase.h>--#include <algorithm>+#include <array>#include <atomic>#include <chrono>-#include <cstdlib>+#include <condition_variable>+#include <cstdio>#include <cstring>-#include <cwctype>#include <format>#include <mutex>-#include <string>-#include <string_view>#include <thread>#include <vector>namespace veyra::source {namespace {--// IEC 61937 sync as it appears on the carrier: the words 0xF872 0x4E1F are-// stored little-endian, so the byte order is 72 F8 1F 4E.-constexpr uint8_t kIecSync[4] = {0x72, 0xF8, 0x1F, 0x4E};-constexpr size_t kIecHeaderBytes = 8;--// How long the carrier is watched before it is declared linear PCM.-constexpr double kProbeSeconds = 4.0;-// Burst silence after a working bitstream before the vendor graph is rebuilt.-constexpr double kLossSeconds = 6.0;-constexpr int kMaxRestarts = 3;-// Bound on the retained carrier tail; bursts are 6144 bytes at most for AC-3.-constexpr size_t kCarrierKeep = 1u << 20;--double nowSeconds() {- using namespace std::chrono;- return duration<double>(steady_clock::now().time_since_epoch()).count();-}--std::string narrow(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;-}--// ABI of AVerMedia::AudioDevice as measured on 2026-10-18-// (docs/AVERMEDIA_5P1_DRIVE_HANDOFF_2026-10-18.md section 2/3).-struct VendorDeviceInfo {- std::wstring friendlyName;- std::wstring devicePath;-};--// "\\?\usb#vid_07ca&pid_2553&mi_00#9&183620d5&0&0000#{...}\global" ->-// "9&183620d5&0". A composite USB device gives every interface its own instance-// id that differs only in the trailing "&NNNN" (measured: video mi_00 ends in-// &0000, audio mi_02 in &0002), so the shared port prefix is what pins the-// component's device list to this physical capture card.-std::wstring usbInstanceId(std::wstring_view path) {- std::wstring lower(path);- std::transform(lower.begin(), lower.end(), lower.begin(), [](wchar_t c) { return wchar_t(towlower(c)); });- const auto mi = lower.find(L"&mi_");- if (mi == std::wstring::npos) return {};- const auto first = lower.find(L'#', mi);- if (first == std::wstring::npos) return {};- const auto second = lower.find(L'#', first + 1);- if (second == std::wstring::npos || second - first < 2) return {};- std::wstring instance = lower.substr(first + 1, second - first - 1);- // Drop the per-interface tail: "9&183620d5&0&0002" -> "9&183620d5&0".- const auto tail = instance.rfind(L'&');- if (tail != std::wstring::npos && instance.size() - tail == 5) instance.erase(tail);- return instance;-}--struct AverMediaVendorAudio::Impl;--class VendorAudioDealer {-public:- virtual ~VendorAudioDealer() = default;- virtual int onAudioData(void* header, const void* data, int length, unsigned extra) = 0;+double nowSeconds(){return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();}+std::string narrow(const std::wstring& text){+ const int size=WideCharToMultiByte(CP_UTF8,0,text.data(),int(text.size()),nullptr,0,nullptr,nullptr);+ std::string out(size>0?size_t(size):0,'\0');+ if(size>0)WideCharToMultiByte(CP_UTF8,0,text.data(),int(text.size()),out.data(),size,nullptr,nullptr);return out;+}+// Local x64 mirror of the fixed public headers in THIRD_PARTY_NOTICES. The+// wrapper owns one opaque pointer; never inspect its private implementation.+using ForeignFn=uintptr_t(*)(void*,void*,void*);+struct ForeignCall {ForeignFn fn=nullptr;void* self=nullptr;void* a=nullptr;void* b=nullptr;uintptr_t result=0;DWORD fault=0;};+void invoke(ForeignCall* call){+ __try {call->result=call->fn(call->self,call->a,call->b);}+ __except(GetExceptionCode()==0xE06D7363?EXCEPTION_CONTINUE_SEARCH:(call->fault=GetExceptionCode(),EXCEPTION_EXECUTE_HANDLER)){}+}+void formatLog(char* out,size_t size,const char* format,char* args) noexcept {+ __try {if(args)std::vsnprintf(out,size,format,args);else std::snprintf(out,size,"%s",format);}+ __except(EXCEPTION_EXECUTE_HANDLER){std::snprintf(out,size,"vendor log formatting fault");}+}+void vendorLog(const char* format,char* args) noexcept {+ if(!format)return;char text[1024]{};formatLog(text,sizeof(text),format,args);+ try{log::info("capture-audio-vendor",text);}catch(...){}+}+constexpr const char* exports[]={+ "??0AudioDevice@AVerMedia@@QEAA@XZ",+ "??1AudioDevice@AVerMedia@@QEAA@XZ",+ "?ConnectFilters@AudioDevice@AVerMedia@@QEAA_NXZ",+ "?GetDeviceList@AudioDevice@AVerMedia@@SAXAEAV?$vector@UDeviceInfo@AVerMedia@@V?$allocator@UDeviceInfo@AVerMedia@@@std@@@std@@@Z",+ "?ResetGraph@AudioDevice@AVerMedia@@QEAA_NXZ",+ "?SetCallback@AudioDevice@AVerMedia@@QEAA_NPEAVAudioDealer@2@@Z",+ "?Start@AudioDevice@AVerMedia@@QEAA_NXZ",+ "?Stop@AudioDevice@AVerMedia@@QEAA_NXZ",+ "?UpdateDevice@AudioDevice@AVerMedia@@QEAA_NAEBV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@0@Z"};--// The vendor stub expects the two-slot vtable: slot 0 the deleting destructor,-// slot 1 the data callback. Any extra virtual above these two would shift it.-class Dealer final : public VendorAudioDealer {-public:- explicit Dealer(class AverMediaVendorAudio::Impl* owner) : owner_(owner) {}- int onAudioData(void* header, const void* data, int length, unsigned extra) override;--private:- AverMediaVendorAudio::Impl* owner_ = nullptr;-};--using CtorFn = void* (*)(void*);-using DtorFn = void (*)(void*);-using ConnectFn = bool (*)(void*);-using GetDeviceListFn = void (*)(std::vector<VendorDeviceInfo>&);-using ResetGraphFn = bool (*)(void*);-using SetCallbackFn = bool (*)(void*, VendorAudioDealer*);-using StartFn = bool (*)(void*);-using StopFn = bool (*)(void*);-using UpdateDeviceFn = bool (*)(void*, const std::wstring&, const std::wstring&);-using LogSinkFn = void (*)(void (*)(const char*, char*));--constexpr const char* kExportCtor = "??0AudioDevice@AVerMedia@@QEAA@XZ";-constexpr const char* kExportDtor = "??1AudioDevice@AVerMedia@@QEAA@XZ";-constexpr const char* kExportConnect = "?ConnectFilters@AudioDevice@AVerMedia@@QEAA_NXZ";-constexpr const char* kExportDeviceList =- "?GetDeviceList@AudioDevice@AVerMedia@@SAXAEAV?$vector@UDeviceInfo@AVerMedia@@V?$allocator@UDeviceInfo@AVerMedia@@@std@@@std@@@Z";-constexpr const char* kExportReset = "?ResetGraph@AudioDevice@AVerMedia@@QEAA_NXZ";-constexpr const char* kExportSetCallback = "?SetCallback@AudioDevice@AVerMedia@@QEAA_NPEAVAudioDealer@2@@Z";-constexpr const char* kExportStart = "?Start@AudioDevice@AVerMedia@@QEAA_NXZ";-constexpr const char* kExportStop = "?Stop@AudioDevice@AVerMedia@@QEAA_NXZ";-constexpr const char* kExportUpdate =- "?UpdateDevice@AudioDevice@AVerMedia@@QEAA_NAEBV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@0@Z";-constexpr const char* kExportLogInfo = "?setInfoHandler@LogHelper@@YAXP6AXPEBDPEAD@Z@Z";-constexpr const char* kExportLogWarn = "?setWarningHandler@LogHelper@@YAXP6AXPEBDPEAD@Z@Z";-constexpr const char* kExportLogError = "?setErrorHandler@LogHelper@@YAXP6AXPEBDPEAD@Z@Z";-constexpr const char* kExportLogDebug = "?setDebugHandler@LogHelper@@YAXP6AXPEBDPEAD@Z@Z";--// The vendor component writes its own diagnostics through these callbacks. The-// format string is not filled in by the component, so the text is passed-// through verbatim (see the handoff: "%d"/"%ls" stay unexpanded).-void vendorLog(const char* level, const char* message, char* extra) {- std::string line = message != nullptr ? message : "";- if (extra != nullptr) {- bool printable = true;- for (int i = 0; i < 180 && extra[i] != 0; ++i) {- const unsigned char c = static_cast<unsigned char>(extra[i]);- if (c < 32 || c > 126) { printable = false; break; }- }- if (printable && extra[0] != 0) line += " | " + std::string(extra);- }- const std::string tag = std::string("capture-audio-vendor/") + (level != nullptr ? level : "info");- if (std::strstr(line.c_str(), "fail") != nullptr || std::strstr(line.c_str(), "null") != nullptr)- log::warn(tag.c_str(), line);- else- log::info(tag.c_str(), line);+enum Entry {Ctor,Dtor,Connect,DeviceList,Reset,SetCallback,Start,Stop,Update,EntryCount};}-void vendorInfo(const char* message, char* extra) { vendorLog("info", message, extra); }-void vendorWarn(const char* message, char* extra) { vendorLog("warn", message, extra); }-void vendorError(const char* message, char* extra) { vendorLog("error", message, extra); }-void vendorDebug(const char* message, char* extra) { vendorLog("dbg", message, extra); }--} // namespacestruct AverMediaVendorAudio::Impl {mutable std::mutex mutex;+ std::condition_variable changed;AverMediaVendorAudioState state;- PcmCallback onPcm;std::thread worker;- std::atomic<bool> stopRequested{false};- std::atomic<bool> restartRequested{false};- std::wstring preferName;- std::wstring preferPath;-- // Graph objects; only touched on the worker thread.- HMODULE module = nullptr;- std::vector<PVOID> dllDirectories;- CtorFn ctor = nullptr;- DtorFn dtor = nullptr;- ConnectFn connect = nullptr;- GetDeviceListFn deviceList = nullptr;- ResetGraphFn reset = nullptr;- SetCallbackFn setCallback = nullptr;- StartFn startGraph = nullptr;- StopFn stopGraph = nullptr;- UpdateDeviceFn updateDevice = nullptr;- void* device = nullptr;- Dealer dealer{this};-- // Decode state; touched by the streaming callback and reset by the worker.+ std::atomic<bool> stopRequested=false,restartRequested=false;+ std::atomic<double> lastCallbackAt=0;+ HANDLE stopEvent=CreateEventW(nullptr,TRUE,FALSE,nullptr);+ unsigned stallMs=6000,maxRestarts=3;+ std::wstring preferName,preferPath;+ std::array<ForeignFn,EntryCount> api{};+ alignas(16) std::array<unsigned char,64> storage{};+ bool constructed=false;+ HMODULE module=nullptr;+ std::vector<DLL_DIRECTORY_COOKIE> directories;std::mutex decodeMutex;- bool tearingDown = false;- enum class Mode { Undecided, Bitstream, LinearPcm } mode = Mode::Undecided;- std::vector<uint8_t> carrier;- std::vector<uint8_t> ac3;- std::vector<float> pcm;- std::unique_ptr<sink::BitstreamDecoder> decoder;- double openedAt = 0;- double lastBurstAt = 0;- uint16_t dataType = 0;-- bool loadLibrary();- bool resolve();- bool setupGraph();- void teardownGraph();- void run();- void onCarrier(const uint8_t* data, size_t bytes);- void decodeCarrier();- void emitBitstream();- void emitLinearPcm();- void noteError(const std::string& text);-};--int Dealer::onAudioData(void* header, const void* data, int length, unsigned extra) {- (void)header;- (void)extra;- if (owner_ == nullptr) return 1;- if (data == nullptr || length <= 0) return 1;- owner_->onCarrier(static_cast<const uint8_t*>(data), size_t(length));- return 1;-}--bool AverMediaVendorAudio::Impl::loadLibrary() {- const std::wstring root = AverMediaAudioSwitch::locateComponentRoot();- if (root.empty()) {- noteError("AVerMedia Multichannel Audio component not found");- return false;- }- const std::wstring coreDir = root + L"\\obs-plugins\\64bit";- const std::wstring dataDir = root + L"\\data\\obs-plugins\\AVerMediaMultichannelAudio";- // The core DLL needs both directories: avt_device_opener.dll lives next to- // it, the Realtek SDK / MSVC 2012 runtime sit in the plugin's data folder.- for (const std::wstring& dir : {coreDir, dataDir}) {- if (GetFileAttributesW(dir.c_str()) == INVALID_FILE_ATTRIBUTES) continue;- if (PVOID cookie = AddDllDirectory(dir.c_str()); cookie != nullptr) dllDirectories.push_back(cookie);- }- const std::wstring corePath = coreDir + L"\\avt_dshow_core.dll";- module = LoadLibraryExW(corePath.c_str(), nullptr,- LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS |- LOAD_LIBRARY_SEARCH_USER_DIRS);- if (module == nullptr) {- noteError(std::format("LoadLibraryExW(avt_dshow_core.dll) failed error={}", GetLastError()));- return false;- }- log::info("capture-audio-vendor", std::format("vendor graph component root=\"{}\"", narrow(root)));- return true;-}--bool AverMediaVendorAudio::Impl::resolve() {- auto get = [this](const char* name) -> void* {- void* address = reinterpret_cast<void*>(GetProcAddress(module, name));- if (address == nullptr) log::warn("capture-audio-vendor", std::string("missing export ") + name);- return address;- };- ctor = reinterpret_cast<CtorFn>(get(kExportCtor));- dtor = reinterpret_cast<DtorFn>(get(kExportDtor));- connect = reinterpret_cast<ConnectFn>(get(kExportConnect));- deviceList = reinterpret_cast<GetDeviceListFn>(get(kExportDeviceList));- reset = reinterpret_cast<ResetGraphFn>(get(kExportReset));- setCallback = reinterpret_cast<SetCallbackFn>(get(kExportSetCallback));- startGraph = reinterpret_cast<StartFn>(get(kExportStart));- stopGraph = reinterpret_cast<StopFn>(get(kExportStop));- updateDevice = reinterpret_cast<UpdateDeviceFn>(get(kExportUpdate));- if (auto set = reinterpret_cast<LogSinkFn>(get(kExportLogInfo))) set(vendorInfo);- if (auto set = reinterpret_cast<LogSinkFn>(get(kExportLogWarn))) set(vendorWarn);- if (auto set = reinterpret_cast<LogSinkFn>(get(kExportLogError))) set(vendorError);- if (auto set = reinterpret_cast<LogSinkFn>(get(kExportLogDebug))) set(vendorDebug);- const bool complete = ctor != nullptr && dtor != nullptr && connect != nullptr && reset != nullptr &&- setCallback != nullptr && startGraph != nullptr && stopGraph != nullptr &&- updateDevice != nullptr && deviceList != nullptr;- if (!complete) noteError("avt_dshow_core.dll is missing required AudioDevice exports");- return complete;-}--bool AverMediaVendorAudio::Impl::setupGraph() {- {- std::lock_guard lock(decodeMutex);- tearingDown = false;- mode = Mode::Undecided;- carrier.clear();- ac3.clear();- pcm.clear();- decoder.reset();- dataType = 0;- openedAt = nowSeconds();- lastBurstAt = 0;- }- // 16 bytes: the wrapper itself only needs 8, the ctor stores a pointer.- device = ctor(std::calloc(1, 16));- if (device == nullptr) {- noteError("AudioDevice ctor returned null");- return false;- }- // ResetGraph is the real Initialize: it creates the filter graph and marks- // the core as initialised (core+0x30).- if (!reset(device)) {- noteError("ResetGraph (Initialize) failed");- return false;- }- std::vector<VendorDeviceInfo> devices;- deviceList(devices);- log::info("capture-audio-vendor", std::format("vendor device list count={}", devices.size()));- auto lowerOf = [](std::wstring text) {- std::transform(text.begin(), text.end(), text.begin(), [](wchar_t c) { return wchar_t(towlower(c)); });- return text;- };- const VendorDeviceInfo* chosen = nullptr;- const VendorDeviceInfo* audioFunction = nullptr;- const VendorDeviceInfo* preferred = nullptr;- const VendorDeviceInfo* instanceMatch = nullptr;- const std::wstring wanted = lowerOf(preferName);- // The video and audio functions of one card share the USB instance id, the- // segment after "&mi_XX#" in the device path. That is the only identity the- // component's device list carries that a second card cannot forge.- const std::wstring videoInstance = usbInstanceId(preferPath);- for (const auto& info : devices) {- log::info("capture-audio-vendor", std::format("vendor device name=\"{}\" path=\"{}\"",- narrow(info.friendlyName), narrow(info.devicePath)));- if (info.devicePath.empty()) continue;- if (audioFunction == nullptr && lowerOf(info.devicePath).find(L"mi_02") != std::wstring::npos)- audioFunction = &info;- if (preferred == nullptr && !wanted.empty() && lowerOf(info.friendlyName).rfind(wanted, 0) == 0)- preferred = &info;- if (instanceMatch == nullptr && !videoInstance.empty() &&- lowerOf(info.devicePath).find(videoInstance) != std::wstring::npos)- instanceMatch = &info;- }- if (!videoInstance.empty() && instanceMatch == nullptr)- log::info("capture-audio-vendor", std::format("no vendor device shares instance=\"{}\"", narrow(videoInstance)));- // Prefer the audio function of this very card, then the card named after the- // video device, then any audio function the component lists.- chosen = instanceMatch != nullptr ? instanceMatch : preferred != nullptr ? preferred : audioFunction;- if (chosen == nullptr) {- noteError("vendor device list has no audio function (is the interactive desktop active?)");- return false;- }- if (!updateDevice(device, chosen->friendlyName, chosen->devicePath)) {- noteError("UpdateDevice failed");- return false;- }- if (!connect(device)) {- noteError("ConnectFilters failed");- return false;- }- // core+0x18 holds the interface the callback is installed on; with a null- // device pointer SetCallback would crash inside the vendor code.- void* core = *reinterpret_cast<void**>(device);- void* callbackInterface =- core != nullptr ? *reinterpret_cast<void**>(reinterpret_cast<unsigned char*>(core) + 0x18) : nullptr;- if (callbackInterface == nullptr) {- noteError("SetCallback skipped: the graph exposes no callback interface");- return false;- }- if (!setCallback(device, &dealer)) {- noteError("SetCallback failed");- return false;- }- if (!startGraph(device)) {- noteError("Start failed");- return false;- }- {- std::lock_guard lock(mutex);- state.device = chosen->friendlyName;- state.started = true;- state.running = true;- state.error.clear();- }- log::info("capture-audio-vendor", std::format("vendor graph started device=\"{}\"", narrow(chosen->friendlyName)));- return true;-}--void AverMediaVendorAudio::Impl::teardownGraph() {- {- std::lock_guard lock(decodeMutex);- tearingDown = true;- decoder.reset();- carrier.clear();- ac3.clear();- }- if (device != nullptr) {- if (stopGraph != nullptr) stopGraph(device);- if (dtor != nullptr) dtor(device);- std::free(device);- device = nullptr;- }-}--void AverMediaVendorAudio::Impl::noteError(const std::string& text) {- std::lock_guard lock(mutex);- state.error = std::wstring(text.begin(), text.end());- state.running = false;- log::warn("capture-audio-vendor", text);-}--void AverMediaVendorAudio::Impl::onCarrier(const uint8_t* data, size_t bytes) {- std::lock_guard lock(decodeMutex);- if (tearingDown) return;- {- std::lock_guard guard(mutex);- ++state.callbacks;- state.carrierBytes += bytes;- }- carrier.insert(carrier.end(), data, data + bytes);- decodeCarrier();-}--void AverMediaVendorAudio::Impl::decodeCarrier() {- if (mode == Mode::Undecided) {- // Look for two bursts of the same data type: one may be a stray sync- // word inside payload, two matching ones are decisive.- size_t cursor = 0;- size_t found = 0;- uint16_t foundType = 0;- while (cursor + kIecHeaderBytes <= carrier.size()) {- if (std::memcmp(carrier.data() + cursor, kIecSync, 4) != 0) {- ++cursor;- continue;- }- const uint16_t type = uint16_t(carrier[cursor + 4]) | uint16_t(carrier[cursor + 5] << 8);- if (sink::classifyIec61937DataType(type) == sink::BitstreamKind::None) {- ++cursor;- continue;- }- if (found == 0 || type == foundType) {- ++found;- foundType = type;- if (found >= 2) break;- } else {- found = 1;- foundType = type;- }- cursor += kIecHeaderBytes;+ bool tearingDown=true;+ std::unique_ptr<AverMediaAudioCarrier> carrier;+ PcmCallback onPcm;+ struct Dealer final:avermedia::AudioDealer {+ Impl* owner=nullptr;+ int onAudioData(avermedia::SampleInfo info,unsigned char* data,long length) override {+ if(!owner||!data||length<=0)return TRUE;+ try{return owner->onCarrier(info,data,size_t(length))?TRUE:FALSE;}+ catch(...){owner->recordError("vendor callback exception");owner->restartRequested=true;return FALSE;}}- if (found >= 2) {- const auto kind = sink::classifyIec61937DataType(foundType);- decoder = std::make_unique<sink::BitstreamDecoder>();- if (decoder->open(kind, false)) {- mode = Mode::Bitstream;- dataType = foundType;- lastBurstAt = nowSeconds();- log::info("capture-audio-vendor", std::format(- "carrier is IEC 61937 dataType=0x{:02X} ({}); decoding to PCM",- unsigned(foundType), sink::bitstreamKindName(kind)));- {- std::lock_guard lock(mutex);- state.bitstream = true;- state.carrier = sink::bitstreamKindName(kind);- }- } else {- const std::string why = decoder->lastError();- decoder.reset();- noteError(std::string("bitstream decoder refused the stream: ") + why);- }- } else if (nowSeconds() - openedAt > kProbeSeconds || carrier.size() > kCarrierKeep) {- mode = Mode::LinearPcm;- log::info("capture-audio-vendor", std::format(- "no IEC 61937 burst in {:.1f}s of carrier; treating it as linear PCM", nowSeconds() - openedAt));- std::lock_guard lock(mutex);- state.carrier = "linear PCM 2ch";+ } dealer;+ Impl(){dealer.owner=this;}+ ~Impl(){if(stopEvent)CloseHandle(stopEvent);}+ void recordError(const std::string& why){+ {std::lock_guard lock(mutex);state.error.assign(why.begin(),why.end());}+ changed.notify_all();log::warn("capture-audio-vendor",why);+ }+ bool call(Entry entry,void* a=nullptr,void* b=nullptr,bool boolean=true){+ if(!api[entry])return false;+ ForeignCall c{api[entry],entry==DeviceList?a:storage.data(),entry==DeviceList?nullptr:a,b};+ try{invoke(&c);}catch(...){recordError(std::string("C++ exception calling ")+exports[entry]);return false;}+ if(c.fault){recordError(std::format("vendor call fault entry={} seh=0x{:08X}",exports[entry],c.fault));return false;}+ if(entry==Ctor)return c.result==reinterpret_cast<uintptr_t>(storage.data());+ return !boolean||(c.result&0xff)!=0;+ }+ bool load(){+ auto root=AverMediaAudioSwitch::locateComponentRoot();+ if(root.empty()){recordError("AVerMedia Multichannel Audio component not installed");return false;}+ wchar_t absolute[32768]{};const DWORD size=GetFullPathNameW(root.c_str(),32768,absolute,nullptr);+ if(!size||size>=32768){recordError("invalid vendor component path");return false;}root=absolute;+ const auto coreDir=root+L"\\obs-plugins\\64bit",dataDir=root+L"\\data\\obs-plugins\\AVerMediaMultichannelAudio";+ for(const auto& dir:{coreDir,dataDir})if(GetFileAttributesW(dir.c_str())!=INVALID_FILE_ATTRIBUTES){+ auto cookie=AddDllDirectory(dir.c_str());if(cookie)directories.push_back(cookie);}- }- if (mode == Mode::Bitstream) emitBitstream();- else if (mode == Mode::LinearPcm) emitLinearPcm();- else if (carrier.size() > kCarrierKeep) carrier.erase(carrier.begin(), carrier.end() - kCarrierKeep / 2);-}--void AverMediaVendorAudio::Impl::emitBitstream() {- size_t cursor = 0;- while (cursor + kIecHeaderBytes <= carrier.size()) {- if (std::memcmp(carrier.data() + cursor, kIecSync, 4) != 0) { ++cursor; continue; }- const size_t payloadBits = size_t(carrier[cursor + 6]) | size_t(carrier[cursor + 7] << 8);- const size_t payload = payloadBits / 8;- if (payload == 0 || cursor + kIecHeaderBytes + payload > carrier.size()) break;- {- std::lock_guard guard(mutex);- ++state.bursts;+ module=LoadLibraryExW((coreDir+L"\\avt_dshow_core.dll").c_str(),nullptr,+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_DEFAULT_DIRS|LOAD_LIBRARY_SEARCH_USER_DIRS);+ if(!module){recordError(std::format("LoadLibraryExW vendor audio failed error={}",GetLastError()));return false;}+ for(size_t i=0;i<api.size();++i){+ api[i]=reinterpret_cast<ForeignFn>(GetProcAddress(module,exports[i]));+ if(!api[i]){recordError(std::string("missing vendor export ")+exports[i]);return false;}}- const uint8_t* words = carrier.data() + cursor + kIecHeaderBytes;- // The carrier stores the bitstream as 16-bit words in little-endian- // order; the codec wants them in wire order, so swap each pair.- for (size_t i = 0; i + 1 < payload; i += 2) {- ac3.push_back(words[i + 1]);- ac3.push_back(words[i]);+ // LogHelper supplies a va_list, not an extra printable string.+ for(auto level:{"Debug","Info","Warning","Error"}){+ const auto name=std::format("?set{}Handler@LogHelper@@YAXP6AXPEBDPEAD@Z@Z",level);+ auto fn=reinterpret_cast<ForeignFn>(GetProcAddress(module,name.c_str()));+ if(fn){ForeignCall c{fn,reinterpret_cast<void*>(vendorLog)};invoke(&c);if(c.fault){recordError("vendor log handler installation fault");return false;}}}- lastBurstAt = nowSeconds();- cursor += kIecHeaderBytes + payload;- }- if (cursor > 0) carrier.erase(carrier.begin(), carrier.begin() + std::ptrdiff_t(cursor));- if (ac3.empty()) return;- pcm.clear();- if (decoder != nullptr && decoder->push(ac3.data(), ac3.size(), pcm)) {- ac3.clear();- const unsigned channels = decoder->channels();- const uint32_t rate = decoder->sampleRate();- if (!pcm.empty() && onPcm && channels > 0 && rate > 0) {- const size_t frames = pcm.size() / channels;- {- std::lock_guard lock(mutex);- state.channels = channels;- state.sampleRate = rate;- state.decodedFrames += frames;- }- onPcm(pcm.data(), frames, channels, rate);+ log::info("capture-audio-vendor",std::format("component root=\"{}\" required exports={}",narrow(root),api.size()));return true;+ }+ bool setup(){+ {std::lock_guard lock(mutex);state.starting=true;state.error.clear();}+ {std::lock_guard lock(decodeMutex);tearingDown=false;carrier=std::make_unique<AverMediaAudioCarrier>(onPcm);}+ storage.fill(0);constructed=call(Ctor,nullptr,nullptr,false);+ if(!constructed){recordError("vendor AudioDevice constructor failed");return false;}+ if(!call(Reset)){recordError("vendor ResetGraph failed");return false;}+ std::vector<avermedia::DeviceInfo> devices;if(!call(DeviceList,&devices,nullptr,false))return false;+ const auto selected=avermedia::selectDevice(devices,preferName,preferPath);+ if(!selected){recordError("selected AVerMedia audio device not found or ambiguous; refusing another card");return false;}+ const auto& chosen=devices[*selected];+ if(!call(Update,const_cast<std::wstring*>(&chosen.friendlyName),const_cast<std::wstring*>(&chosen.devicePath))+ ||!call(Connect)||!call(SetCallback,&dealer)||!call(Start)){+ recordError("vendor audio graph setup/start failed");return false;}- } else if (ac3.size() > kCarrierKeep) {- ac3.clear();- }- // A stream that stopped producing bursts is rebuilt from scratch.- if (lastBurstAt > 0 && nowSeconds() - lastBurstAt > kLossSeconds && !restartRequested.exchange(true)) {- std::lock_guard lock(mutex);- ++state.losses;- log::warn("capture-audio-vendor", std::format("no IEC 61937 burst for {:.1f}s; rebuilding the vendor graph",- nowSeconds() - lastBurstAt));- }-}--void AverMediaVendorAudio::Impl::emitLinearPcm() {- // 16-bit stereo carrier: pass it through so a console set to Linear PCM- // still plays on this path.- const size_t frames = carrier.size() / 4;- if (frames == 0) return;- pcm.resize(frames * 2);- for (size_t i = 0; i < frames * 2; ++i) {- const int16_t sample = int16_t(uint16_t(carrier[i * 2]) | uint16_t(carrier[i * 2 + 1] << 8));- pcm[i] = float(sample) / 32768.0f;- }- carrier.erase(carrier.begin(), carrier.begin() + std::ptrdiff_t(frames * 4));- if (onPcm) {- {- std::lock_guard lock(mutex);- state.channels = 2;- state.sampleRate = 48000;- state.pcmFrames += frames;+ // The watchdog begins after Start, not during its 5-13 second preroll.+ lastCallbackAt=nowSeconds();+ {std::lock_guard lock(mutex);state.device=chosen.friendlyName;state.starting=false;state.started=state.running=true;}+ changed.notify_all();log::info("capture-audio-vendor",std::format("vendor graph started device=\"{}\"",narrow(chosen.friendlyName)));return true;+ }+ void teardown(){+ // Stop joins the vendor callback; never hold decodeMutex across it.+ {std::lock_guard lock(decodeMutex);tearingDown=true;carrier.reset();}+ if(constructed){call(Stop);call(SetCallback,nullptr);call(Dtor,nullptr,nullptr,false);constructed=false;}+ {std::lock_guard lock(mutex);state.started=state.running=false;}+ }+ bool onCarrier(avermedia::SampleInfo info,const uint8_t* data,size_t bytes){+ std::lock_guard lock(decodeMutex);if(tearingDown||stopRequested)return true;+ const double now=nowSeconds();lastCallbackAt=now;+ const bool ok=carrier->feed({data,bytes},info,now);const auto& decoded=carrier->state();+ {std::lock_guard guard(mutex);++state.callbacks;state.carrierBytes+=bytes;+ state.bitstream=decoded.bitstream;state.channels=decoded.channels;state.sampleRate=decoded.rate;+ state.carrier=decoded.codec;state.bursts=decoded.bursts;state.decodedFrames=decoded.decodedFrames;state.pcmFrames=decoded.pcmFrames;+ if(!decoded.error.empty())state.error.assign(decoded.error.begin(),decoded.error.end());else state.error.clear();}- onPcm(pcm.data(), frames, 2, 48000);- }-}--void AverMediaVendorAudio::Impl::run() {- const HRESULT com = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);- if (FAILED(com) && com != RPC_E_CHANGED_MODE) {- noteError(std::format("CoInitializeEx failed hr=0x{:08X}", unsigned(com)));- return;- }- if (!loadLibrary() || !resolve()) {- if (module != nullptr) FreeLibrary(module);- module = nullptr;- if (SUCCEEDED(com)) CoUninitialize();- return;- }- if (!setupGraph()) {- teardownGraph();- FreeLibrary(module);- module = nullptr;- if (SUCCEEDED(com)) CoUninitialize();- return;- }- int restarts = 0;- while (!stopRequested.load()) {- std::this_thread::sleep_for(std::chrono::milliseconds(20));- if (restartRequested.exchange(false) && restarts < kMaxRestarts) {- ++restarts;- log::info("capture-audio-vendor", std::format("rebuilding the vendor graph ({} of {})", restarts, kMaxRestarts));- teardownGraph();- openedAt = nowSeconds();- if (!setupGraph()) {- log::warn("capture-audio-vendor", "vendor graph rebuild failed; audio stops here");- break;+ if(!ok)restartRequested=true;return ok;+ }+ void run(){+ const HRESULT co=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);bool ok=false;+ try{+ if(FAILED(co))recordError(std::format("vendor STA init failed hr=0x{:08X}",unsigned(co)));+ else if(load()&&setup()){+ ok=true;unsigned attempts=0;+ while(!stopRequested){+ if(stopEvent)MsgWaitForMultipleObjects(1,&stopEvent,FALSE,20,QS_ALLINPUT);+ else std::this_thread::sleep_for(std::chrono::milliseconds(20));+ MSG msg{};while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}+ if(stopRequested)break;+ const bool stalled=(nowSeconds()-lastCallbackAt.load())*1000.0>stallMs;+ if(stalled||restartRequested.exchange(false)){+ if(attempts>=maxRestarts){recordError("vendor audio recovery limit reached; falling back to DirectShow");ok=false;break;}+ ++attempts;{std::lock_guard lock(mutex);++state.losses;state.starting=true;}+ teardown();if(stopRequested)break;if(!setup()){ok=false;break;}+ {std::lock_guard lock(mutex);++state.restarts;}+ }+ }}- std::lock_guard lock(mutex);- ++state.restarts;- }- }- teardownGraph();- FreeLibrary(module);- module = nullptr;- for (PVOID cookie : dllDirectories) RemoveDllDirectory(cookie);- dllDirectories.clear();- {- std::lock_guard lock(mutex);- state.running = false;- state.started = false;+ }catch(...){recordError("vendor audio worker exception");ok=false;}+ try{teardown();}catch(...){ok=false;}+ if(module){FreeLibrary(module);module=nullptr;}+ for(auto cookie:directories)RemoveDllDirectory(cookie);directories.clear();api.fill(nullptr);+ {std::lock_guard lock(mutex);state.starting=state.started=state.running=false;state.failed=!ok&&!stopRequested;+ if(state.failed&&state.error.empty())state.error=L"vendor audio graph unavailable";}+ changed.notify_all();if(SUCCEEDED(co))CoUninitialize();}- if (SUCCEEDED(com)) CoUninitialize();-}--AverMediaVendorAudio::AverMediaVendorAudio() : p_(std::make_unique<Impl>()) {}--AverMediaVendorAudio::~AverMediaVendorAudio() {- stop();- if (p_ && p_->module != nullptr) FreeLibrary(p_->module);-}--bool AverMediaVendorAudio::start(PcmCallback onPcm, const std::wstring& preferName,- const std::wstring& preferPath) {- if (p_->worker.joinable()) return p_->state.running;- p_->onPcm = std::move(onPcm);- p_->preferName = preferName;- p_->preferPath = preferPath;- p_->stopRequested = false;- p_->restartRequested = false;- p_->worker = std::thread([this] { p_->run(); });- // The worker loads the component and starts streaming. Failures (missing- // exports, a refusing component, a rejected session) surface within a second- // or two and must fall back at once. A healthy graph, on the other hand,- // prerolls inside the vendor's Start() for 5 to 13 seconds (measured- // 2026-10-18: 5.2 s with a burst carrier, 13.0 s on linear PCM), so a timeout- // there is not a failure - the callbacks arrive on the worker thread and the- // caller keeps this object either way.- for (int i = 0; i < 300; ++i) {- {- std::lock_guard lock(p_->mutex);- if (p_->state.error.empty() && !p_->state.running)- std::this_thread::sleep_for(std::chrono::milliseconds(10));- else- break;- }- }- std::lock_guard lock(p_->mutex);- return p_->state.error.empty();-}--void AverMediaVendorAudio::stop() {- if (!p_ || !p_->worker.joinable()) return;- p_->stopRequested = true;- p_->worker.join();-}--bool AverMediaVendorAudio::running() const {- std::lock_guard lock(p_->mutex);- return p_->state.running;-}--AverMediaVendorAudioState AverMediaVendorAudio::state() const {- std::lock_guard lock(p_->mutex);- return p_->state;-}+};+AverMediaVendorAudio::AverMediaVendorAudio(unsigned stallMs,unsigned maxRestarts):p_(std::make_unique<Impl>()){+ p_->stallMs=std::max(50u,stallMs);p_->maxRestarts=maxRestarts;+}+AverMediaVendorAudio::~AverMediaVendorAudio(){stop();}+bool AverMediaVendorAudio::start(PcmCallback callback,const std::wstring& name,const std::wstring& path){+ if(p_->worker.joinable()){const auto s=state();return !s.failed&&(s.starting||s.running);}+ if(!avermedia::eligible(name,path,0)){p_->recordError("selected input is not an AVerMedia capture device");return false;}+ if(AverMediaAudioSwitch::locateComponentRoot().empty()){p_->recordError("AVerMedia Multichannel Audio component not installed");return false;}+ p_->onPcm=std::move(callback);p_->preferName=name;p_->preferPath=path;p_->stopRequested=false;p_->restartRequested=false;+ if(p_->stopEvent)ResetEvent(p_->stopEvent);+ {std::lock_guard lock(p_->mutex);p_->state={};p_->state.starting=true;}+ try{p_->worker=std::thread([this]{p_->run();});}+ catch(...){p_->recordError("cannot start vendor audio worker");std::lock_guard lock(p_->mutex);p_->state.starting=false;p_->state.failed=true;return false;}+ std::unique_lock lock(p_->mutex);+ p_->changed.wait_for(lock,std::chrono::milliseconds(150),[this]{return !p_->state.starting;});+ // Pending Start is asynchronous startup, not proof that PCM exists.+ return !p_->state.failed&&(p_->state.starting||p_->state.running);+}+void AverMediaVendorAudio::stop(){+ if(!p_||!p_->worker.joinable())return;p_->stopRequested=true;if(p_->stopEvent)SetEvent(p_->stopEvent);p_->worker.join();+}+bool AverMediaVendorAudio::running()const{std::lock_guard lock(p_->mutex);return p_->state.running;}+AverMediaVendorAudioState AverMediaVendorAudio::state()const{std::lock_guard lock(p_->mutex);return p_->state;}} // namespace veyra::sourcediff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 89365e8a..809f4134 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -210,16 +210,7 @@ bool bind(unsigned index,bool audio,ComPtr<IBaseFilter>& filter){auto list=monikbool bindPath(std::wstring_view wanted,bool audio,ComPtr<IBaseFilter>& filter){if(wanted.empty())return false;for(auto& moniker:monikers(audio))if(monikerPath(moniker.Get())==wanted)return SUCCEEDED(moniker->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&filter)));return false;}-// AVerMedia's USB vendor id as it appears in every DirectShow device path-// ("\\?\usb#vid_07ca&pid_2553&mi_00#..."). The capture filter Veyra adds is-// registered as "Capture card", so the filter name cannot identify the card;-// the moniker path can.-bool isAverMediaUsbPath(std::wstring_view path){- if(path.empty())return false;- std::wstring lower(path.begin(),path.end());- std::transform(lower.begin(),lower.end(),lower.begin(),[](wchar_t c){return wchar_t(towlower(c));});- return lower.find(L"vid_07ca")!=std::wstring::npos;-}+std::wstring captureDeviceName(std::wstring_view path){for(auto& moniker:monikers(false))if(monikerPath(moniker.Get())==path)return propertyString(moniker.Get(),L"FriendlyName");return {};@@ -362,6 +353,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {// compressed multichannel stream only leaves the vendor's own audio graph,// which this object drives in-process while it is bound to the source.std::unique_ptr<AverMediaVendorAudio> vendorAudio;+ std::shared_ptr<std::atomic<bool>> vendorDelivering;// Dolby/DTS passthrough: when the device offers only compressed media types// the raw bursts are decoded here and the session is configured with the// decoded layout on the first frame (that is why its start is deferred).@@ -970,7 +962,14 @@ void CaptureCardSource::videoPresented(double pts,int64_t time,int64_t arrival){}void CaptureCardSource::videoReset(bool resetAudio){if(p_->wasapi)p_->wasapi->videoReset(resetAudio);else if(p_->audioSession)p_->audioSession->videoReset(resetAudio);}void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->wasapi)p_->wasapi->setSync(mode,offset);else if(p_->audioSession)p_->audioSession->setSync(mode,offset);}-sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->wasapi?p_->wasapi->snapshot():p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};if(!p_->audioError.empty())state.error=p_->audioError;return state;}+sink::CaptureAudioState CaptureCardSource::audioState()const{+ auto state=p_->wasapi?p_->wasapi->snapshot():p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};+ if(p_->vendorAudio){const auto vendor=p_->vendorAudio->state();+ if(!vendor.error.empty())state.error=vendor.error;+ else if(vendor.starting&&!state.inputBlocks)state.error=L"AVerMedia audio graph is initializing; waiting for actual audio samples";+ }+ if(!p_->audioError.empty())state.error=p_->audioError;return state;+}bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}bool CaptureCardSource::compressedVideo()const{return p_->compressedPath;}bool CaptureCardSource::configureDeckLink(const SourceOpenDesc& desc){@@ -1280,43 +1279,33 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleif(!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){- bool vendorConnected=false;+ std::wstring wantedName,wantedPath;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;auto list=monikers(true);for(size_t i=0;i<list.size();++i){- const std::wstring path=monikerPath(list[i].Get());- const bool wanted=selection.stable?(path==selection.audioPath):(i==size_t(audio));- if(!wanted)continue;- audioName=propertyString(list[i].Get(),L"FriendlyName");audioPath=path;break;+ const auto path=monikerPath(list[i].Get());+ if(!(selection.stable?path==selection.audioPath:i==size_t(audio)))continue;+ wantedName=propertyString(list[i].Get(),L"FriendlyName");wantedPath=path;break;}- p.pendingAudioName=audioName;- if(!audioPath.empty())applyVendorAudioSwitch(audioName,audioPath);- // The vendor graph is tried first: it is the only path that can- // deliver the console's compressed stream, and it falls back to- // plain PCM on its own when the console sends Linear PCM.- if(!AverMediaAudioSwitch::locateComponentRoot().empty())- vendorConnected=connectVendorAudio(audioName,audioName,audioPath);+ p.pendingAudioName=wantedName;}else if(audio==kCaptureAudioFromVideoDevice){- // Audio from the card's own function. An AVerMedia card only hands- // the compressed stream to the process that runs the component's- // audio graph; its pin alone stays linear PCM.- std::wstring videoPath=selection.videoPath;- if(!selection.stable){- auto list=monikers(false);- if(selection.videoIndex<list.size())videoPath=monikerPath(list[selection.videoIndex].Get());- }- const std::wstring videoName=captureDeviceName(videoPath);- const bool avermedia=isAverMediaUsbPath(videoPath);- log::info("capture-audio-vendor",std::format("embedded audio: device=\"{}\" avermediaPath={} component={}",- narrowForLog(videoName),avermedia?1:0,AverMediaAudioSwitch::locateComponentRoot().empty()?0:1));- if(avermedia&&!AverMediaAudioSwitch::locateComponentRoot().empty())- vendorConnected=connectVendorAudio(videoName,videoName,videoPath);+ wantedPath=selection.videoPath;+ if(!selection.stable){auto list=monikers(false);if(selection.videoIndex<list.size())wantedPath=monikerPath(list[selection.videoIndex].Get());}+ wantedName=captureDeviceName(wantedPath);+ }+ const bool useVendor=avermedia::eligible(wantedName,wantedPath,p.audioIngressMode)+ &&!AverMediaAudioSwitch::locateComponentRoot().empty();+ // Preserve the explicit receiver passthrough preference. Automatic mode+ // uses the vendor graph, PCM-only never arms the non-PCM component.+ bool audioReady=false;+ if(p.audioIngressMode==2){+ if(useVendor)applyVendorAudioSwitch(wantedName,wantedPath);+ audioReady=connectDirectShowAudio(desc);+ if(!audioReady&&useVendor){p.averMediaSwitch.stop();audioReady=connectVendorAudio(wantedName,wantedName,wantedPath);}+ }else{+ if(useVendor)audioReady=connectVendorAudio(wantedName,wantedName,wantedPath);+ if(!audioReady)audioReady=connectDirectShowAudio(desc);}- const bool audioReady=vendorConnected||connectDirectShowAudio(desc);if(!audioReady){p.audioError=L"采集音频设备或 PCM 格式不可用;视频继续运行";log::warn("capture-audio","audio connection unavailable; retaining video capture");@@ -1428,7 +1417,15 @@ bool CaptureCardSource::applyVendorAudioSwitch(const std::wstring& audioName,con// ("@device:cm:{...}\wave:{...}") and contains no vid_/pid_ - exactly// the tokens the vendor component parses. Ask the device tree instead:// the USB functions are still there.- const auto functions=AverMediaAudioSwitch::findUsbFunctions(L"vid_07ca");+ if(!avermedia::eligible(name,path,p.audioIngressMode))return false;+ auto functions=AverMediaAudioSwitch::findUsbFunctions(L"vid_07ca");+ // A class-manager audio moniker has no USB serial. Require one unique+ // matching audio function, rather than arming every installed card.+ std::vector<avermedia::DeviceInfo> identities;+ for(const auto& f:functions)identities.push_back({f.friendlyName,f.interfacePath.empty()?f.instanceId:f.interfacePath});+ const auto selected=avermedia::selectDevice(identities,name,path);+ if(!selected){log::warn("capture-audio-vendor","non-PCM switch device identity absent/ambiguous; skipped");return false;}+ const auto chosenFunction=functions[*selected];functions={chosenFunction};for(const auto& function:functions)log::info("capture-audio-vendor",std::format("device tree: instance=\"{}\" friendly=\"{}\" interfacePath={}",narrowForLog(function.instanceId),narrowForLog(function.friendlyName),@@ -1486,41 +1483,36 @@ bool CaptureCardSource::connectVendorAudio(const std::wstring& deviceName,constauto session=std::make_unique<sink::CaptureAudioSession>();auto vendor=std::make_unique<AverMediaVendorAudio>();auto* target=session.get();- auto clock=std::make_shared<CaptureAudioClock>();- auto began=std::make_shared<bool>(false);- auto failed=std::make_shared<bool>(false);- const bool started=vendor->start([target,clock,began,failed](const float* interleaved,size_t frames,unsigned channels,uint32_t rate){- if(*failed||interleaved==nullptr||frames==0||channels==0||rate==0)return;- if(!*began){+ struct FormatState {unsigned channels=0;uint32_t rate=0,mask=0;CaptureAudioClock clock;};+ auto format=std::make_shared<FormatState>();+ auto delivering=std::make_shared<std::atomic<bool>>(false);+ const bool started=vendor->start([target,format,delivering](const VendorPcmBlock& block){+ // Vendor Start may preroll during configure(). Owner gain/sync and video+ // Run must be committed before any sample reaches the output session.+ if(!delivering->load())return true;+ if(!block.samples||!block.frames||!block.channels||!block.rate||!block.mask)return false;+ const bool changed=format->channels!=block.channels||format->rate!=block.rate||format->mask!=block.mask;+ if(changed){+ target->stop();WAVEFORMATEXTENSIBLE wfx{};- wfx.Format.wFormatTag=WAVE_FORMAT_EXTENSIBLE;- wfx.Format.nChannels=WORD(channels);- wfx.Format.nSamplesPerSec=rate;- wfx.Format.wBitsPerSample=32;- wfx.Format.nBlockAlign=WORD(channels*4);- wfx.Format.nAvgBytesPerSec=rate*channels*4;- wfx.Format.cbSize=sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);- wfx.Samples.wValidBitsPerSample=32;- // 5.1 side layout as the component reports it.- wfx.dwChannelMask=channels==6?0x60Fu:channels==8?0x63Fu:channels==2?0x3u:0x60Fu;- wfx.SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;- if(!target->configure(wfx.Format,sizeof(wfx))||!target->start()){- *failed=true;- log::warn("capture-audio-vendor",std::format("audio session refused {}ch at {} Hz",channels,rate));- return;- }- *began=true;- log::info("capture-audio-vendor",std::format("decoded carrier started channels={} mask=0x{:X} rate={} float=1",channels,unsigned(wfx.dwChannelMask),rate));+ wfx.Format.wFormatTag=WAVE_FORMAT_EXTENSIBLE;wfx.Format.nChannels=WORD(block.channels);+ wfx.Format.nSamplesPerSec=block.rate;wfx.Format.wBitsPerSample=32;+ wfx.Format.nBlockAlign=WORD(block.channels*sizeof(float));+ wfx.Format.nAvgBytesPerSec=block.rate*wfx.Format.nBlockAlign;+ wfx.Format.cbSize=sizeof(wfx)-sizeof(WAVEFORMATEX);wfx.Samples.wValidBitsPerSample=32;+ wfx.dwChannelMask=block.mask;wfx.SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;+ if(!target->configure(wfx.Format,sizeof(wfx))||!target->start())return false;+ format->channels=block.channels;format->rate=block.rate;format->mask=block.mask;+ log::info("capture-audio-vendor",std::format("session format channels={} mask=0x{:X} rate={} float=1",block.channels,block.mask,block.rate));}+ target->setInputBitstream(std::wstring(block.codec.begin(),block.codec.end()));+ const bool discontinuity=changed||block.discontinuity;const double arrival=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();- const double pts=clock->observe(std::nullopt,arrival,1000.0*double(frames)/double(rate),false);- if(!target->push(interleaved,frames*channels*sizeof(float),pts,false)){- *failed=true;- log::warn("capture-audio-vendor","audio session stopped accepting decoded PCM");- }+ const double pts=format->clock.observe(std::nullopt,arrival,1000.0*double(block.frames)/block.rate,discontinuity);+ return target->push(block.samples,block.frames*block.channels*sizeof(float),pts,discontinuity);},preferName,preferPath);const auto state=vendor->state();- if(!started||*failed){+ if(!started){log::warn("capture-audio-vendor",std::format("vendor graph unavailable device=\"{}\" error=\"{}\" callbacks={}",narrowForLog(deviceName),std::string(state.error.begin(),state.error.end()),state.callbacks));return false;@@ -1528,6 +1520,7 @@ bool CaptureCardSource::connectVendorAudio(const std::wstring& deviceName,constlog::info("capture-audio-vendor",std::format("binding=vendor-graph device=\"{}\" carrier=\"{}\" bitstream={} channels={} rate={}",narrowForLog(deviceName),state.carrier,state.bitstream?1:0,state.channels,state.sampleRate));p.audioSession=std::move(session);+ p.vendorDelivering=std::move(delivering);p.vendorAudio=std::move(vendor);return true;}@@ -1796,6 +1789,7 @@ bool CaptureCardSource::start(){if(!p.referenceClock)fg->SetDefaultSyncSource();if(SUCCEEDED(mf->GetSyncSource(&p.ageClock))&&p.ageClock&&FAILED(p.ageClock->GetTime(&p.runReference)))p.runReference=0;}}p.lastFrame=Impl::Clock::now();const auto hr=p.control->Run();p.info.opened=SUCCEEDED(hr);+ if(p.vendorDelivering)p.vendorDelivering->store(p.info.opened);if(p.info.opened&&p.wasapi&&!p.wasapi->start())p.audioError=L"WASAPI 音频启动失败;视频继续运行";if(p.info.opened&&p.magewellWanted){p.externalTimeAnchored=false;@@ -1817,12 +1811,14 @@ bool CaptureCardSource::start(){}void CaptureCardSource::recoverAudio(float gain,unsigned syncMode,int offsetMs){auto& p=*p_;if(!p.info.opened||!p.control||p.wasapi)return;- // The vendor graph notices a silent carrier by itself and rebuilds; the- // DirectShow recovery would only fight it.+ bool vendorFailed=false;if(p.vendorAudio){- static bool reported=false;- if(!reported){reported=true;log::info("capture-audio-vendor","DirectShow audio recovery skipped: the vendor graph rebuilds itself");}- return;+ const auto vendor=p.vendorAudio->state();+ if(!vendor.failed)return; // Its bounded watchdog owns this graph.+ if(p.vendorDelivering)p.vendorDelivering->store(false);+ p.vendorAudio->stop();p.vendorAudio.reset();p.vendorDelivering.reset();+ vendorFailed=true;+ log::warn("capture-audio-vendor","vendor recovery exhausted; reconnecting the original DirectShow audio input");}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@@ -1833,7 +1829,7 @@ void CaptureCardSource::recoverAudio(float gain,unsigned syncMode,int offsetMs){return;}const auto state=p.audioSession?p.audioSession->snapshot():sink::CaptureAudioState{};- if(!p.audioRecovery.due(state.inputBlocks,GetTickCount64()))return;+ if(!vendorFailed&&!p.audioRecovery.due(state.inputBlocks,GetTickCount64()))return;// DirectShow audio/video pins share one graph. Briefly stop it to mutate// only the audio branch; do not renegotiate or replace the video device.const HRESULT stopped=p.control->Stop();@@ -1845,8 +1841,10 @@ void CaptureCardSource::recoverAudio(float gain,unsigned syncMode,int offsetMs){p.audioSession.reset();if(p.audioFilter){const HRESULT hr=p.graph->RemoveFilter(p.audioFilter.Get());log::info("capture-audio-reconnect",std::format("Remove audio device hr=0x{:08X}",uint32_t(hr)));if(FAILED(hr))return false;p.audioFilter.Reset();}if(!connectDirectShowAudio(reconnectDesc_))return false;+ if(p.audioPassthrough)return true;+ if(!p.audioSession)return false;p.audioSession->setGain(gain);p.audioSession->setSync(syncMode,offsetMs);- return p.audioSession->start();+ return p.audioSessionDeferred||p.audioSession->start();}();{std::lock_guard lock(p.mutex);p.pending=false;p.forceDiscontinuity=true;}++epoch_;p.lastFrame=Impl::Clock::now();@@ -1974,7 +1972,8 @@ void CaptureCardSource::close()noexcept{if(p.magewell){p.magewell->stop();p.magewell.reset();}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.elgatoHdr.reset();- if(p.vendorAudio){p.vendorAudio->stop();p.vendorAudio.reset();}+ if(p.vendorDelivering)p.vendorDelivering->store(false);+ if(p.vendorAudio){p.vendorAudio->stop();p.vendorAudio.reset();}p.vendorDelivering.reset();p.averMediaSwitch.stop();p.embeddedAudioUnavailable=false;if(p.audioSession)p.audioSession->stop();p.audioError.clear();if(p.audioPassthrough)p.audioPassthrough->close();diff --git a/tests/fixtures/FakeAverMediaVendor.cpp b/tests/fixtures/FakeAverMediaVendor.cppnew file mode 100644index 00000000..f8f1b972--- /dev/null+++ b/tests/fixtures/FakeAverMediaVendor.cpp@@ -0,0 +1,47 @@+// Test double for the fixed public x64 ABI; no vendor implementation/binary.+#include "veyra/source/AverMediaVendorProtocol.h"+#include <windows.h>+#include <objbase.h>+#include <atomic>+#include <chrono>+#include <cstdarg>+#include <stdexcept>+#include <thread>+#include <vector>+using namespace veyra::source::avermedia;+namespace {+std::wstring mode;std::atomic<unsigned> starts=0,stops=0,callbacks=0,live=0;std::atomic<bool> sta=true;+using Logger=void(*)(const char*,char*);Logger logger=nullptr;+struct Graph {AudioDealer* dealer=nullptr;std::atomic<bool> stop=false;std::thread thread;};+Graph*& graph(void* self){return *reinterpret_cast<Graph**>(self);}+void trace(const char* format,...){va_list args;va_start(args,format);if(logger)logger(format,args);va_end(args);}+void apartment(){APTTYPE type;APTTYPEQUALIFIER qualifier;sta=sta&&SUCCEEDED(CoGetApartmentType(&type,&qualifier))&&type==APTTYPE_STA;}+}+extern "C" {+__declspec(dllexport) void FakeMode(const wchar_t* value){mode=value;starts=stops=callbacks=live=0;sta=true;}+__declspec(dllexport) unsigned FakeCount(unsigned which){return which==0?starts.load():which==1?stops.load():which==2?callbacks.load():which==3?live.load():sta?1:0;}+void* FakeCtor(void* self){apartment();graph(self)=new Graph;++live;return self;}+void FakeStop(void* self){++stops;auto* g=graph(self);if(!g)return;g->stop=true;if(g->thread.joinable())g->thread.join();}+void FakeDtor(void* self){FakeStop(self);delete graph(self);graph(self)=nullptr;--live;}+bool FakeReset(void*){apartment();if(mode==L"seh")RaiseException(0xC0000005,0,0,nullptr);if(mode==L"exception")throw std::runtime_error("test vendor exception");return mode!=L"reset-fail";}+void FakeDevices(std::vector<DeviceInfo>& out){+ out={{L"Live Gamer Ultra 2.1-Audio",L"\\\\?\\usb#vid_07ca&pid_2553&mi_02#5&first&0&0002#{guid}"},+ {L"Live Gamer Ultra 2.1-Audio",L"\\\\?\\usb#vid_07ca&pid_2553&mi_02#5&second&0&0002#{guid}"}};+}+bool FakeUpdate(void*,const std::wstring&,const std::wstring& path){return path.find(L"first")!=path.npos;}+bool FakeConnect(void*){return mode!=L"connect-fail";}+bool FakeCallback(void* self,AudioDealer* dealer){graph(self)->dealer=dealer;return true;}+bool FakeStart(void* self){+ ++starts;apartment();trace("fake public log channel=%d rate=%s",2,"48000");+ if(mode==L"delayed"||mode==L"late-fail")std::this_thread::sleep_for(std::chrono::milliseconds(500));+ if(mode==L"start-fail"||mode==L"late-fail")return false;+ if(mode==L"stall")return true;+ auto* g=graph(self);g->stop=false;+ g->thread=std::thread([g]{+ std::vector<unsigned char> pcm(1920,0);+ for(size_t i=0;i<pcm.size();i+=2){pcm[i]=0;pcm[i+1]=0x20;}+ while(!g->stop){++callbacks;if(g->dealer){const SampleInfo info=mode==L"bad-format"?SampleInfo{2,12,48000}:SampleInfo{2,16,48000};g->dealer->onAudioData(info,pcm.data(),long(pcm.size()));}std::this_thread::sleep_for(std::chrono::milliseconds(10));}+ });return true;+}+void FakeLogger(Logger log){logger=log;}+}diff --git a/tests/fixtures/FakeAverMediaVendor.def b/tests/fixtures/FakeAverMediaVendor.defnew file mode 100644index 00000000..da9117cf--- /dev/null+++ b/tests/fixtures/FakeAverMediaVendor.def@@ -0,0 +1,11 @@+EXPORTS+ "??0AudioDevice@AVerMedia@@QEAA@XZ"=FakeCtor+ "??1AudioDevice@AVerMedia@@QEAA@XZ"=FakeDtor+ "?ConnectFilters@AudioDevice@AVerMedia@@QEAA_NXZ"=FakeConnect+ "?GetDeviceList@AudioDevice@AVerMedia@@SAXAEAV?$vector@UDeviceInfo@AVerMedia@@V?$allocator@UDeviceInfo@AVerMedia@@@std@@@std@@@Z"=FakeDevices+ "?ResetGraph@AudioDevice@AVerMedia@@QEAA_NXZ"=FakeReset+ "?SetCallback@AudioDevice@AVerMedia@@QEAA_NPEAVAudioDealer@2@@Z"=FakeCallback+ "?Start@AudioDevice@AVerMedia@@QEAA_NXZ"=FakeStart+ "?Stop@AudioDevice@AVerMedia@@QEAA_NXZ"=FakeStop+ "?UpdateDevice@AudioDevice@AVerMedia@@QEAA_NAEBV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@0@Z"=FakeUpdate+ "?setInfoHandler@LogHelper@@YAXP6AXPEBDPEAD@Z@Z"=FakeLoggerdiff --git a/tests/unit/AverMediaCarrierTests.cpp b/tests/unit/AverMediaCarrierTests.cppnew file mode 100644index 00000000..98fa4b17--- /dev/null+++ b/tests/unit/AverMediaCarrierTests.cpp@@ -0,0 +1,98 @@+#include "veyra/source/AverMediaAudioCarrier.h"+#include <algorithm>+#include <bit>+#include <cmath>+#include <iostream>+#include <stdexcept>+extern "C" {+#include <libavcodec/avcodec.h>+#include <libavutil/channel_layout.h>+}+using namespace veyra;+namespace {+unsigned checks=0;+void require(bool value,const char* text){++checks;if(!value)throw std::runtime_error(text);}+struct Output {unsigned channels;uint32_t rate,mask;bool discontinuity;std::string codec;std::vector<float> pcm;};+std::vector<std::vector<uint8_t>> encode(AVCodecID id,uint64_t mask,int rate){+ const auto* codec=avcodec_find_encoder(id);require(codec!=nullptr,"encoder available");+ auto* c=avcodec_alloc_context3(codec);require(c!=nullptr,"encoder context");+ c->sample_rate=rate;c->sample_fmt=AV_SAMPLE_FMT_FLTP;c->bit_rate=mask==3?192000:448000;+ av_channel_layout_from_mask(&c->ch_layout,mask);+ require(avcodec_open2(c,codec,nullptr)>=0,"open real encoder");+ AVFrame* f=av_frame_alloc();AVPacket* packet=av_packet_alloc();+ f->nb_samples=c->frame_size;f->format=c->sample_fmt;f->sample_rate=rate;+ av_channel_layout_copy(&f->ch_layout,&c->ch_layout);require(av_frame_get_buffer(f,0)>=0,"encoder buffer");+ std::vector<std::vector<uint8_t>> packets;+ auto drain=[&]{while(avcodec_receive_packet(c,packet)>=0){packets.emplace_back(packet->data,packet->data+packet->size);av_packet_unref(packet);}};+ for(int n=0;n<12;++n){+ av_frame_make_writable(f);f->pts=int64_t(n)*f->nb_samples;+ for(int ch=0;ch<c->ch_layout.nb_channels;++ch){auto* values=reinterpret_cast<float*>(f->extended_data[ch]);+ for(int i=0;i<f->nb_samples;++i)values[i]=float(0.05*std::sin((i+f->pts)*6.28318530718*(180+ch*70)/rate));}+ require(avcodec_send_frame(c,f)>=0,"encode frame");drain();+ }+ avcodec_send_frame(c,nullptr);drain();av_packet_free(&packet);av_frame_free(&f);avcodec_free_context(&c);+ require(packets.size()>=10,"real encoded packets");return packets;+}+std::vector<uint8_t> burst(const std::vector<uint8_t>& packet,unsigned type){+ std::vector<uint8_t> out(std::max<size_t>(6144,8+((packet.size()+1)&~size_t(1))),0);+ out[0]=0x72;out[1]=0xf8;out[2]=0x1f;out[3]=0x4e;out[4]=uint8_t(type);+ const size_t pd=type==0x15?packet.size():packet.size()*8;out[6]=uint8_t(pd);out[7]=uint8_t(pd>>8);+ for(size_t i=0;i<packet.size();i+=2){out[8+i]=i+1<packet.size()?packet[i+1]:0;out[9+i]=packet[i];}return out;+}+}+int main(){try{+ using source::avermedia::DeviceInfo;+ const std::wstring video=L"\\\\?\\usb#vid_07ca&pid_2553&mi_00#5&abc&0&0000#{guid}";+ const std::wstring audio=L"\\\\?\\usb#vid_07ca&pid_2553&mi_02#5&abc&0&0002#{guid}";+ std::vector<DeviceInfo> devices{{L"Live Gamer Ultra 2.1-Audio",audio},{L"Live Gamer Ultra 2.1-Audio",L"\\\\?\\usb#vid_07ca&pid_2553&mi_02#5&other&0&0002#{guid}"}};+ require(source::avermedia::selectDevice(devices,L"Live Gamer Ultra 2.1-Video",video)==0,"USB sibling matches exact card");+ require(!source::avermedia::selectDevice(devices,L"Live Gamer Ultra 2.1-Audio",L"opaque"),"identical card names ambiguous");+ require(!source::avermedia::selectDevice(devices,L"Live Gamer Ultra 2.1-Audio",L"\\\\?\\usb#vid_07ca&pid_2553&mi_00#5&absent&0&0000#{guid}"),"no wrong-card name fallback");+ require(!source::avermedia::eligible(L"Microphone",L"opaque",0),"unrelated microphone unchanged");+ require(!source::avermedia::eligible(L"Live Gamer",L"vid_1234",0),"explicit other vendor rejected");+ require(!source::avermedia::eligible(L"Live Gamer",video,1),"PCM-only does not arm component");+ std::vector<Output> outputs;+ source::AverMediaAudioCarrier carrier([&](const source::VendorPcmBlock& b){+ require(b.frames<=1536,"bounded output block");require(b.mask!=0,"actual speaker mask");+ outputs.push_back({b.channels,b.rate,b.mask,b.discontinuity,std::string(b.codec),{b.samples,b.samples+b.frames*b.channels}});return true;+ });+ const source::avermedia::SampleInfo stereo{2,16,48000};+ std::vector<uint8_t> pcm(1920*4,0);for(size_t i=0;i<pcm.size();i+=2){pcm[i]=0x00;pcm[i+1]=0x20;}+ require(carrier.feed(pcm,stereo,0),"initial PCM");require(!outputs.empty(),"PCM delivered without four-second preroll");+ require(outputs.front().discontinuity&&outputs.front().pcm.front()==0.25f,"PCM value and initial discontinuity");+ auto feedCodec=[&](AVCodecID codec,uint64_t mask,int rate,unsigned type,double start){+ const auto encoded=encode(codec,mask,rate);size_t before=outputs.size();size_t total=0;+ for(const auto& packet:encoded){const auto wire=burst(packet,type);size_t pos=0;+ for(size_t n:{size_t(1),size_t(3),size_t(1919),size_t(7),size_t(8192)}){+ const size_t bytes=std::min(n,wire.size()-pos);if(!bytes)break;+ require(carrier.feed(std::span(wire).subspan(pos,bytes),stereo,start+double(total)/192000),"split IEC feed");pos+=bytes;total+=bytes;+ }+ if(pos<wire.size()){require(carrier.feed(std::span(wire).subspan(pos),stereo,start+double(total)/192000),"IEC remainder");total+=wire.size()-pos;}+ }+ require(outputs.size()>before+2,"real decoded audio exists");+ const auto& last=outputs.back();require(last.channels==unsigned(std::popcount(mask))&&last.rate==unsigned(rate)&&last.mask==mask,"decoded channel layout/rate matches real codec");+ require(!last.codec.empty(),"diagnostics name compressed input");+ for(float v:last.pcm)require(std::isfinite(v)&&std::abs(v)<1,"decoded PCM finite and bounded");+ for(unsigned ch=0;ch<last.channels;++ch){double energy=0;for(size_t i=ch;i<last.pcm.size();i+=last.channels)energy+=last.pcm[i]*last.pcm[i];require(energy>0.001,"every decoded channel contains signal");}+ require(std::any_of(outputs.begin()+before,outputs.end(),[](auto& o){return o.discontinuity;}),"format boundary resets history");+ };+ feedCodec(AV_CODEC_ID_AC3,0x3f,48000,1,1);+ feedCodec(AV_CODEC_ID_AC3,3,44100,1,2);+ feedCodec(AV_CODEC_ID_AC3,0x60f,48000,1,3);+ auto before=outputs.size();require(carrier.feed(pcm,stereo,8),"compressed to PCM");+ require(outputs.size()==before+1&&outputs.back().codec.empty()&&outputs.back().channels==2,"switch to PCM session");+ require(outputs.back().pcm.size()<=960*2&&outputs.back().discontinuity,"only newest 20ms after compressed loss");+ feedCodec(AV_CODEC_ID_EAC3,0x3f,48000,0x15,9);+ carrier.reset();outputs.clear();+ std::vector<uint8_t> unsupported(6144,0);unsupported[0]=0x72;unsupported[1]=0xf8;unsupported[2]=0x1f;unsupported[3]=0x4e;unsupported[4]=0x16;unsupported[6]=0x10;+ require(carrier.feed(unsupported,stereo,0)&&carrier.feed(unsupported,stereo,0.1),"unknown HD carrier detected");+ require(outputs.empty()&&!carrier.state().error.empty(),"unsupported compressed bytes never played as noise");+ carrier.reset();outputs.clear();std::vector<uint8_t> raw24{0,0,0x40,0,0,0xc0};+ require(carrier.feed(raw24,{2,24,96000},0),"24-bit metadata");+ require(outputs.back().rate==96000&&outputs.back().pcm[0]==0.5f&&outputs.back().pcm[1]==-0.5f,"actual 24-bit sample conversion");+ std::vector<uint8_t> tooLarge(source::AverMediaAudioCarrier::kMaxBytes+1);require(!carrier.feed(tooLarge,stereo,0),"oversized callback rejected");+ source::AverMediaAudioCarrier rejected([](const source::VendorPcmBlock&){return false;});require(!rejected.feed(pcm,stereo,0),"session error requests recovery");+ carrier.reset();outputs.clear();+ for(unsigned n=0;n<2000;++n){std::vector<uint8_t> noise(511,0);require(carrier.feed(noise,stereo,n*.01),"continuous quiet PCM");require(carrier.state().retainedBytes<=12,"bounded persistent PCM buffer");}+ std::cout<<"PASS "<<checks<<" checks: identity, real AC3/EAC3, fragmented carriers, 6/2ch and rate changes, PCM transitions, malformed input\n";return 0;+}catch(const std::exception& e){std::cerr<<"FAIL "<<e.what()<<" after "<<checks<<" checks\n";return 1;}}diff --git a/tests/unit/AverMediaVendorAudioTests.cpp b/tests/unit/AverMediaVendorAudioTests.cppnew file mode 100644index 00000000..045eb9d4--- /dev/null+++ b/tests/unit/AverMediaVendorAudioTests.cpp@@ -0,0 +1,69 @@+#include "veyra/source/AverMediaVendorAudio.h"+#include <windows.h>+#include <atomic>+#include <chrono>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <stdexcept>+#include <thread>+using namespace veyra::source;+namespace {+unsigned checks=0;+void require(bool value,const char* text){++checks;if(!value)throw std::runtime_error(text);}+template<class F> bool wait(F f,unsigned ms=2000){for(unsigned n=0;n<ms/10;++n){if(f())return true;std::this_thread::sleep_for(std::chrono::milliseconds(10));}return f();}+}+int wmain(int argc,wchar_t** argv){try{+ require(argc==3,"usage: vendor tests fake.dll owned-test-root");+ const auto root=std::filesystem::absolute(argv[2]);std::filesystem::create_directories(root/L"obs-plugins/64bit");+ std::filesystem::create_directories(root/L"data/obs-plugins/AVerMediaMultichannelAudio");+ const auto dll=root/L"obs-plugins/64bit/avt_dshow_core.dll";+ std::filesystem::copy_file(argv[1],dll,std::filesystem::copy_options::overwrite_existing);+ // Component discovery checks these paths; these inert test placeholders+ // are never loaded. Product staging never contains this fake component.+ for(const auto& name:{L"obs-plugins/64bit/avt_device_opener.dll",L"data/obs-plugins/AVerMediaMultichannelAudio/RTICE_SDK_x64.dll",L"data/obs-plugins/AVerMediaMultichannelAudio/RTK_IO_x64.dll"})std::ofstream(root/name).put('\0');+ SetEnvironmentVariableW(L"VEYRA_AVERMEDIA_COMPONENT",root.c_str());+ const auto module=LoadLibraryExW(dll.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);+ require(module!=nullptr,"load own ABI fixture");+ auto mode=reinterpret_cast<void(*)(const wchar_t*)>(GetProcAddress(module,"FakeMode"));+ auto count=reinterpret_cast<unsigned(*)(unsigned)>(GetProcAddress(module,"FakeCount"));require(mode&&count,"fixture exports");+ const std::wstring name=L"Live Gamer Ultra 2.1-Video",path=L"\\\\?\\usb#vid_07ca&pid_2553&mi_00#5&first&0&0000#{guid}";+ std::atomic<unsigned> received=0;std::atomic<bool> valid=true;+ auto callback=[&](const VendorPcmBlock& block){valid=valid&&block.channels==2&&block.rate==48000&&block.mask==3&&block.samples[0]==0.25f;++received;return true;};+ {+ mode(L"normal");AverMediaVendorAudio audio(100,2);+ require(!audio.start(callback,L"Microphone",L"opaque"),"never open unrelated microphone");require(count(0)==0,"no vendor calls for unrelated input");+ require(audio.start(callback,name,path),"start selected card");require(wait([&]{return received>3;}),"public callback delivers PCM");+ require(valid,"sample metadata and callback ABI");std::this_thread::sleep_for(std::chrono::milliseconds(180));+ require(audio.state().restarts==0,"continuous PCM is healthy without IEC bursts");require(count(4)==1,"all graph control on STA");+ audio.stop();const auto callbacks=count(2);std::this_thread::sleep_for(std::chrono::milliseconds(50));+ require(count(2)==callbacks&&count(3)==0,"stop joins callbacks and destroys graph");audio.stop();+ }+ {+ mode(L"delayed");AverMediaVendorAudio audio;+ const auto start=std::chrono::steady_clock::now();require(audio.start(callback,name,path),"delayed start accepted as pending");+ require(std::chrono::steady_clock::now()-start<std::chrono::milliseconds(350),"capture startup does not wait for vendor preroll");+ require(audio.state().starting&&!audio.state().running,"pending startup not reported running");require(wait([&]{return audio.running();}),"delayed completion visible");audio.stop();+ }+ for(const auto* scenario:{L"reset-fail",L"connect-fail",L"start-fail",L"late-fail",L"seh",L"exception"}){+ mode(scenario);AverMediaVendorAudio audio;audio.start(callback,name,path);+ require(wait([&]{return audio.state().failed;}),"vendor failure surfaced without crashing");+ require(!audio.state().error.empty()&&!audio.running(),"terminal diagnostic available");audio.stop();require(count(3)==0,"failure cleanup destroys graph");+ }+ {+ mode(L"normal");AverMediaVendorAudio audio;+ audio.start(callback,name,L"\\\\?\\usb#vid_07ca&pid_2553&mi_00#5&absent&0&0000#{guid}");+ require(wait([&]{return audio.state().failed;}),"absent selected serial refused");require(count(0)==0,"same-name other card never started");audio.stop();+ }+ for(const auto* scenario:{L"stall",L"bad-format"}){+ mode(scenario);AverMediaVendorAudio audio(80,2);audio.start(callback,name,path);+ require(wait([&]{return audio.state().failed;},3000),"no callbacks / invalid data exhaust bounded recovery");+ require(audio.state().restarts==2&&count(0)==3,"only configured number of rebuilds");audio.stop();require(count(3)==0,"rebuild cleanup");+ }+ {+ mode(L"normal");AverMediaVendorAudio audio;+ for(unsigned i=0;i<10;++i){require(audio.start(callback,name,path),"repeat startup");audio.stop();require(count(3)==0,"repeat teardown");}+ }+ FreeLibrary(module);SetEnvironmentVariableW(L"VEYRA_AVERMEDIA_COMPONENT",nullptr);+ std::cout<<"PASS "<<checks<<" checks: public ABI, STA, delayed startup, device identity, callback shutdown, SEH/C++ faults, bounded watchdog\n";return 0;+}catch(const std::exception& e){std::cerr<<"FAIL "<<e.what()<<" after "<<checks<<" checks\n";return 1;}}