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 BMD raw input to upstream allocator negotiation
Veyra Goal Agent886b461bb0ae
diff --git a/AGENTS.md b/AGENTS.mdindex 814c228e..6f333010 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-09 BMD 黑屏跟进**:用户提供 veyra-qml(43).log,要求继续修复 2.0.6 未解决的 BMD 黑屏,确认 OBS 两种来源都可出画。按 docs/BLACKMAGIC_FOLLOWUP_PLAN_2026-10-09.md 从 main dbfceab 在 E 盘 codex/blackmagic-followup-20261009 隔离修复必要 DirectShow 接收协商及定向测试/本地候选;这些具体接点覆盖旧冻结。独立 start/bundle 保护38原工作树和495脏文件;旧 guard/start 不改。普通采集、音频、NR/补帧/显示算法、运行库/模型原字节保持;不派 Agent、不改驱动/用户配置/其它工作树。测试≤300秒、构建≤900秒,产物全E盘。无新合并/push/Release/关机授权;BMD 实卡未验不得声称已修好。+> **2026-10-08 桌面项目清理追加授权**:用户要求“桌面这个也清一清”,仅处理桌面 Veyra 项目的忽略产物。按 docs/DESKTOP_STORAGE_CLEANUP_2026-10-08.md,历史 logs lossless 去重归档 E 盘后移除桌面副本,8 套旧 CMake 构建保留 EXE/配置/源码片段后清缓存,旧 1.2.0 解压副本与原 ZIP/额外日志归档核对后移除;35 工作树、495 脏文件及 66,680 个保留文件哈希通过。保留 out/remoteplay 当前依赖、out 内工作树、SDK/runtime/素材及 .git,不涉及桌面其它文件。不改历史 guard/start,不改产品、不 push/Release/关机;C 回收与 E 归档成本分别报告。> **2026-10-08 本地合并与项目清理授权**:用户要求把当前修复合入 main,然后排查并清理项目磁盘占用。已验 VFG 71723e0 从 main 96a7c8de 快进合并;按 docs/PROJECT_STORAGE_CLEANUP_PLAN_2026-10-08.md 盘点并删除经清单核实的过时可重建构建、私有测试 app/缓存、冗余解压副本。此授权覆盖这些产物的历史保留限制,不改历史 guard/start 基线,不删除工作树、源码、未提交修改、依赖/SDK/运行库原件、用户素材或正式发布 ZIP/对应源码。独立 start/495 份脏文件备份在 E:/项目/Veyra/archives/project-cleanup-20261008;按硬链接身份及实际磁盘空间分别报告。保留当前可用构建、2.0.6 两显卡包与最新 VFG 候选、必要日志/验收记录。不派 Agent、不改产品实现或用户配置、不 push/Release/关机。diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex c2bb7c51..12d577b4 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -54,6 +54,16 @@ also follows the format contract in that commit's `source/dshow-formats.cpp`;Veyra reuses its existing UYVY GPU ingress and retains explicit color metadata.These adaptations do not constitute Blackmagic hardware certification.+The Blackmagic-specific allocator negotiation and terminal renderer flag in+`src/source/NativeCaptureSink.cpp`, and output-selected direct connection in+`src/source/CaptureCardSource.cpp`, additionally adapt `CapturePin::GetAllocator`,+`GetAllocatorRequirements`, `MiscFlagsHandler::GetMiscFlags` and+`HDevice::ConnectPins` from that same commit (`source/capture-filter.cpp`,+`source/device.cpp`, Copyright (C) 2023 Lain Bailey, LGPL-2.1-or-later).+Veyra limits this compatibility policy to Blackmagic/DeckLink video, retains+the upstream-selected allocator for diagnostics, and preserves its own+blocking, stop/flush, sample-size and negotiated media-contract checks.+The AVerMedia hardware HDR-to-SDR property request in`src/source/CaptureCardSource.cpp` is adapted from `source/device-vendor.cpp`(`SetTonemapperAvermedia`) in [obsproject/libdshowcapture](https://github.com/obsproject/libdshowcapture/tree/c13d4b7b0c66979396ba0a9060c9aafc15bb7b22),diff --git a/docs/BLACKMAGIC_FOLLOWUP_PLAN_2026-10-09.md b/docs/BLACKMAGIC_FOLLOWUP_PLAN_2026-10-09.mdnew file mode 100644index 00000000..a5d98fbd--- /dev/null+++ b/docs/BLACKMAGIC_FOLLOWUP_PLAN_2026-10-09.md@@ -0,0 +1,26 @@+# BMD 黑屏跟进:驱动交帧兼容候选++用户在 2.0.6 后继续报告 BMD 黑屏,提供 `veyra-qml(43).log`,并确认 OBS 的视频采集设备与 Blackmagic 来源都可显示。当前任务只修这项采集兼容,不沿用上一轮关机请求,不合并 main、不推送或发布。++## 已确认和未知++- 日志七次连接均能持续出帧,增强关闭仍黑;HDYC 已原生直连,旧 crossbar 修复在两入口都没有找到上游。38 次 YUV/RGB 黑采样、6 次 ARGB 全白采样,不能把后者当真实画面恢复。+- 上轮报告只验了合成接口、本机 USB 和 GPU 颜色,没有 BMD 真卡验收。本轮不重复宣称实卡已修好。+- 对照 OBS libdshowcapture 固定提交 `c13d4b7b0c66979396ba0a9060c9aafc15bb7b22`:其接收 pin 不提供分配器/缓冲要求,ConnectDirect 不强塞 media type,终端暴露 renderer 标记。Veyra 原生接收器主动提供通用 MemoryAllocator、3 个缓冲的要求及 N4 上游建议。此为真实接口差异,尚不是已证实现场根因。+- 卡型号、物理输入、实际信号制式仍未知;驱动 GetFormat 是配置,不能当信号检测。禁止盲切 HDMI/SDI、盲遍历制式、隐藏黑帧或将黑场认定失去信号。++## 本轮实现与验证++1. 仅识别为 Blackmagic/DeckLink 的原生视频接收使用 OBS 式驱动分配器协商:无接收端 allocator 提案、无硬编码缓冲要求/上游建议,保留驱动 NotifyAllocator 的实际分配器供日志读取;标记真正的终端 renderer。普通采集与音频策略保持。+2. BMD 保留驱动声明的 DIB 方向,不再额外尝试负高度 SetFormat;SetFormat 后让输出 pin 提供连接类型,并严格核对实际 subtype/尺寸/stride/方向/颜色/帧时长,变化则明确失败。不能以兼容为名偷偷换格式。+3. 仅本轮 BMD 候选提供进程级 `VEYRA_BMD_DSHOW_LEGACY=1` 对照开关,使用相同 EXE、运行库、媒体模式和私有配置比较。无自动重连或黑场触发切换。ReceiveCanBlock 保持真实 S_OK,Stop/flush/动态模式检查继续生效。+4. 真实 COM allocator/sample 测试覆盖驱动提供 buffer、只读样本、不改原字节、短帧/动态变更/停止/flush/重连和 COM 身份;现有普通 video/audio 分配器、格式/颜色、GPU ingress 与本机 USB 1080p60 回归。每测试 ≤300 秒,不做压力或并发 GPU 测试。+5. 从当前 main `dbfceab` 隔离施工,复用产品相同的已验 `71723e0` 缓存构建输入,重新编译两个产品 source 及相关测试,链接同一组产品 object;构建输入先后 SHA 核对。所有新产物在 `E:/项目/Veyra/{reports,archives,build,tests,logs,tmp,test-packages}/blackmagic-followup-20261009`。+6. 本地候选、对应源码、真实命令/日志/失败记录、简明实卡步骤交付。38 原工作树和 495 未提交文件按不可变 start 保护;旧 guard/start 不改。运行库、SDK、模型不进 Git,不改驱动、用户配置或其他算法。没有子 Agent。++## 参考++- [OBS CapturePin / terminal filter](https://github.com/obsproject/libdshowcapture/blob/c13d4b7b0c66979396ba0a9060c9aafc15bb7b22/source/capture-filter.cpp),LGPL-2.1-or-later,Copyright (C) 2023 Lain Bailey;复用协商逻辑,保留 Veyra 的 RAII、状态/布局检查与分配器诊断。+- [OBS direct connection](https://github.com/obsproject/libdshowcapture/blob/c13d4b7b0c66979396ba0a9060c9aafc15bb7b22/source/device.cpp)。+- [Microsoft GetAllocator](https://learn.microsoft.com/en-us/windows/win32/api/strmif/nf-strmif-imeminputpin-getallocator):输出 pin 决定实际 allocator;NotifyAllocator 后 GetAllocator 返回已选择 allocator。+- [Microsoft IAMFilterMiscFlags](https://learn.microsoft.com/en-us/windows/win32/api/strmif/nn-strmif-iamfiltermiscflags):source/renderer 应提供类型标记;此标记不是像素正确证明。diff --git a/docs/BLACKMAGIC_FOLLOWUP_REPORT_2026-10-09.md b/docs/BLACKMAGIC_FOLLOWUP_REPORT_2026-10-09.mdnew file mode 100644index 00000000..69583104--- /dev/null+++ b/docs/BLACKMAGIC_FOLLOWUP_REPORT_2026-10-09.md@@ -0,0 +1,52 @@+# BMD 黑屏跟进:本地候选++用户提供 `veyra-qml(43).log`,确认 OBS 通用视频采集和 Blackmagic 来源都可显示。本轮完成 BMD 原生视频的驱动交帧兼容候选;没有 BMD 实卡,不能宣称现场根因已证实或黑屏已经修好。++## 事实++日志七次连接都持续收帧/送显,增强关闭仍黑;HDYC 已原生直连,说明上次格式修复确实存在,但两入口均 `inputMediums=0 crossbar=false`,crossbar 路径没帮助该卡。44 次 CPU 原始样本统计中 38 次是黑场值、6 次 ARGB 全白,没有证据显示真实内容恢复。GetFormat 是配置读回,不能当信号检测。卡型号、实际信号制式、HDMI/SDI 仍未知。++上轮报告仅验过合成接口、本机 USB 和 GPU 颜色,BMD 真卡始终未通过。黑场内容、驱动占位帧、制式/输入错误、缓冲兼容不能只凭这份日志区分。++## 改动及来源++对照 OBS libdshowcapture `c13d4b7b0c66979396ba0a9060c9aafc15bb7b22`(LGPL-2.1-or-later,Copyright (C) 2023 Lain Bailey),复用 CapturePin allocator 方法、terminal renderer 标记和 HDevice::ConnectPins 的输出选择类型逻辑;源码与 THIRD_PARTY_NOTICES 已标注。++- BMD 原生接收器不再主动提供通用 MemoryAllocator、缓冲要求或 N4 建议,让输出 pin 选择实际 allocator;NotifyAllocator 后保留实际对象/只读状态及 alignment/prefix/数量诊断。+- 该兼容接收器暴露 renderer 标记,保留 canonical IUnknown、真实 ReceiveCanBlock=S_OK 与原 Stop/flush/短帧检查。+- BMD 保留驱动 DIB 方向;SetFormat/GetFormat 后由输出 pin 提供 ConnectDirect 类型,严格核对 subtype、尺寸、stride、颜色、帧时长和 VideoInfo2 隔行标志,动态扫描变更要求重开。+- 普通 USB/音频使用原工厂和缓冲策略;v210 仍走原系统 RGB 转换,本轮没有原生10-bit v210。没有黑场触发的换档、重连、丢帧或物理输入路由修改。+- `VEYRA_BMD_DSHOW_LEGACY=1` 供同 EXE 旧协商对照,默认 BMD 走新兼容方式。++提供 allocator 本身是合法 DirectShow 行为。旧版测试失败说明它不满足本轮 OBS 式兼容策略,**不是复现 BMD 黑屏,也不代表九个现场根因**。++## 验证++基线 main `dbfceabee804cd81bac4a4781f0b7b4cf272902e`,隔离分支 `codex/blackmagic-followup-20261009`。缓存产品 `71723e0` 与 main 之间只有已核对的清理/管理文档差异。重新编译两个 capture source 及 fixture,GUI/测试链接相同新产品 objects;缓存输入前后 SHA 不变。最终构建 receipt 由 `E:/项目/Veyra/reports/blackmagic-followup-20261009/build-current.json` 指向,含命令、源码、objects、缓存和 EXE SHA。++| 项目 | 结果 |+|---|---|+| 旧实现 + 新兼容约定 | 9 项预期失败,exit1;其余检查通过 |+| 当前采集/音频/格式/COM 样本 | 261 项通过、0 失败;真实 COM allocator、HDYC 字节交付/只读样本/Stop/flush/短帧/隔行变更/重连 |+| GPU 像素 | 124 项通过,HDYC 两方向逐像素等同 UYVY BT709 |+| KUHAIMI 27P YUY2 1080p60 | 初次 60.101426 FPS、重连 59.950521 FPS,PTS 单调;软件回调率 |+| 实际 GUI | 11.954秒 exit0,连接/关闭增强/截图/断开/属性入口状态通过,Main.qml loader 完整恢复 |+| 随包脚本 | PowerShell 解析通过;15秒私有配置启动/正常退出/生成 ZIP,源配置 SHA 未改 |++最终原日志在 `E:/项目/Veyra/logs/blackmagic-followup-20261009/delivery-tests`、`gui` 和 `launcher-smoke`。GUI 截图已查看,是 USB 卡产生的“无信号”图样:证明非黑像素进入/显示/截图,不证明实际 HDMI 内容或 BMD 通过。未验 BMD 两入口、AMD/BMD 联合使用、长稳或屏幕端到端延迟。无竞争 GPU/子 Agent,单测试均小于300秒。++## 失败记录++1. 构建脚本先因缓存缺采集测试 object 中止,改为从源码编译。随后错误组合 Ninja -t commands 的43条依赖命令,因 command line too long 未执行;改为只选/验证目标 cl.exe 行。最终缓存输入逐项 SHA 未变。+2. GPU 首次缺 EXE 相对路径 shaders 而 exit3;硬链接已核验原 shader 后重跑通过124项。失败保留在 contracts/gpu-pixels.log。+3. USB fixture 的 pass=0 是轮次,被包装脚本误当布尔失败;原产品 exit0/两轮 PASS 保留,修正解析并重新取得两轮证据。+4. 隔行旧版对照曾因回调计数级联导致13项失败;改为各自前后计数,最终9项旧版预期失败、当前261项通过。不把级联断言当独立故障。+5. 首个 overlay 包含 qml 下原 Qt plugin DLL,被后置白名单拒绝。失败 SHA/大小/原因在 package-failed-attempt.json;仅删除本任务该失败 ZIP,限定 qml/Veyra 后重新打包通过。最终不含 DLL/模型/PDB/LIB/SDK。++## 交付++`E:/项目/Veyra/test-packages/blackmagic-followup-20261009/Veyra-2.0.6-BMD-compat-test.zip`:9,069,313字节,SHA256 `5da4a452e2612a81fd5b0d63605809723547d63be631b241415cab7aff470a40`,108项,CRC和每项 payload SHA 通过。EXE SHA256 `f1597d657037fe5174fd8d25dbd72902dc3f5b142b8b2d260121844bf9d462ee`;manifest列明基线、源码 SHA、实际显示构建串2.0.6-vfg-next、BMD未验。对应完整源码 `Veyra-2.0.6-BMD-compat-source.zip` 的最终提交/CRC/SHA 见同任务 closure.json。++保留原包,将补丁覆盖到完整2.0.6便携副本,AMD/NVIDIA沿用各自运行库。先用 OBS 成功时的同设备/同精确制式/同像素格式测试基础画面,再开增强和断开重连。脚本默认新协商,-Variant Legacy 使用同EXE旧协商;3分钟输出 ZIP、私有配置。仍黑时必须补齐 OBS 有效模式/卡/物理口,或下一轮用原生 SDK 查询实际信号,不能继续将收帧成功当画面成功。++1614个 donor 文件前后核验;保留当前构建、一个共享依赖私有app和必要证据。38原工作树、495未提交文件及用户日志按独立 start 保护,旧 guard/start 不改。不改运行库/模型/驱动/用户配置,不合并 main、不 push/正式发布或关机;自查不冒称独立 Reviewer。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex f6372f25..ba50ae4d 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,17 @@# WORKLOG+## 2026-10-09 BMD 2.0.6 黑屏跟进候选++用户提供veyra-qml(43).log,确认OBS两种来源可显示,要求继续排查2.0.6未解决的BMD黑屏。从main dbfceab隔离codex/blackmagic-followup-20261009,独立state.py/start/bundle保护38原工作树、495脏文件。七次连接持续出帧,HDYC原生连接已生效但两入口没有crossbar;44次原样本38黑场/6全白,不能证明真实图像或区分制式/路由/缓冲根因。对照原2.0.6文档纠正“本机USB通过”与“BMD未验”边界。++按BLACKMAGIC_FOLLOWUP_PLAN_2026-10-09.md复用OBS固定c13d4b7 LGPL allocator/terminal/direct-connect约定,仅BMD原生视频采用驱动分配器、无接收端/N4缓冲要求、输出选择media type、保留DIB方向;严格核对实际subtype/布局/颜色/帧时长/隔行标志,保留阻塞/停止/flush/短帧检查。普通采集/音频原策略、v210原转换继续保留;同EXE进程级Legacy开关和私有配置日志启动脚本。源码及THIRD_PARTY_NOTICES记来源。此为兼容候选,不宣称allocator差异已经证实为现场黑屏根因。++命令python -B scripts/acceptance/bmd-followup-build.py,最终receipt见reports/blackmagic-followup-20261009/build-current.json:新编译两产品source、相关fixture并链接相同objects;原71723缓存产品与dbfceab仅文档差异,缓存输入前后SHA相同。python -B scripts/acceptance/bmd-followup-test.py delivery-tests --usb:旧实现9项预期失败(策略对照,不是黑屏复现),当前261项0失败,GPU124项,实卡KUHAIMI27P YUY2连接60.101426/重连59.950521回调FPS、PTS单调。package.py prepare核对1614 donor后建立唯一硬链接依赖私有app;test.py gui --gui,生产GUI11.954秒exit0、截图/断开/属性状态通过、Main.qml恢复;截图是USB无信号图样,不是BMD/有效HDMI信号证明。Start-BMD-Capture-Test.ps1解析和15秒私有profile启动/正常退出/日志ZIP通过,原profileSHA不变。日志全在E:/项目/Veyra/logs/blackmagic-followup-20261009。++失败保留:缺旧缓存测试object、Ninja依赖命令误组合而命令行过长未执行、GPU首次shader目录缺失、USB轮次pass=0被误判、旧对照回调计数级联,均修正并重新取证;第一次含Qt plugin的overlay被白名单拒绝,记录SHA/大小后仅删除自有失败ZIP并限定应用QML。详见BLACKMAGIC_FOLLOWUP_REPORT_2026-10-09.md。package.py package最终9,069,313字节/108项,SHA5da4a452e2612a81fd5b0d63605809723547d63be631b241415cab7aff470a40,CRC/每payloadSHA通过,无DLL/模型/SDK;EXE f1597d657037fe5174fd8d25dbd72902dc3f5b142b8b2d260121844bf9d462ee。对应源码与最终保全收据在同任务test-packages和reports/closure.json。++当前可用构建/单份共享依赖app/必要日志截图/源码保留,所有新研发产物E盘。BMD/AMD-BMD实卡、长稳、屏幕延迟仍未验。没有子Agent/竞争GPU/驱动或用户配置改动,没有main合并/push/Release/关机;旧guard/start不改,反向测试和自查不冒称独立Reviewer。+## 2026-10-07 VFG本地候选交付完成- 最终归档源码e18942096bb65789a1701f0468acdc64f1be415e,candidate-final构建20.312秒exit0,EXE仍c007c7fc9072a6114eb2479b1880b65f5386a5fd445e6c58513faf3c1328a2b2;仅整理文档/验收脚本,产品与全部已测编译输入一致。diff --git a/include/veyra/source/NativeCaptureSink.h b/include/veyra/source/NativeCaptureSink.hindex 75c3e6a2..53900beb 100644--- a/include/veyra/source/NativeCaptureSink.h+++ b/include/veyra/source/NativeCaptureSink.h@@ -5,9 +5,15 @@#include <wrl/client.h>#include <functional>namespace veyra::source {+enum class CaptureAllocatorMode { SinkDefault, Upstream };+// Exact raw connection contract, including subtype and VideoInfo2 field flags.+bool nativeCaptureContractsMatch(const AM_MEDIA_TYPE&,const AM_MEDIA_TYPE&);// Native terminal filter: no legacy SampleGrabber orientation/VideoInfo2// restriction, conversion filter or extra queue. Callback borrows the sample.HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&);+// Blackmagic compatibility: let the output pin choose its own allocator and+// requirements. The selected allocator is still retained after NotifyAllocator.+HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&,CaptureAllocatorMode);HRESULT createNativeAudioSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&);HRESULT createBitstreamAudioSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&);// Compressed (MJPEG/H.264/HEVC/...) variant: carries the driver payload withoutdiff --git a/scripts/acceptance/bmd-followup-build.py b/scripts/acceptance/bmd-followup-build.pynew file mode 100644index 00000000..44413a45--- /dev/null+++ b/scripts/acceptance/bmd-followup-build.py@@ -0,0 +1,85 @@+"""Build only the two capture sources and related tests; preserve cached inputs."""+from pathlib import Path+import ctypes,hashlib,json,os,re,subprocess,time,sys+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-followup-20261009'+CACHE=BASE/'build/vfg-next-20261007';OUT=BASE/'build'/TASK;LOG=BASE/'logs'/TASK/('build-'+time.strftime('%Y%m%d-%H%M%S'));TMP=BASE/'tmp'/TASK/'build'+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=True)+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/bmd-followup-control.py')],check=True)+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+shell=ctypes.WinDLL('shell32');shell.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)];shell.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p);ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]+def args(s):+ n=ctypes.c_int();p=shell.CommandLineToArgvW(s,ctypes.byref(n));a=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return a+def unescape(s):return s.replace('$ ', ' ').replace('$:', ':').replace('$$','$')+ninja=(CACHE/'build.ninja').read_text(encoding='utf8');settings=(CACHE/'CMakeCache.txt').read_text(encoding='utf8')+tool=re.search(r'^CMAKE_MAKE_PROGRAM:FILEPATH=(.*)$',settings,re.M).group(1)+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP))+setup=subprocess.run(['cmd.exe','/u','/d','/c',r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],capture_output=True,text=True,encoding='utf-16-le',env=env,check=True)+for line in setup.stdout.splitlines():+ if '=' in line:+ k,v=line.split('=',1)+ if k and not k.startswith('='):env[k]=v+env.update(TEMP=str(TMP),TMP=str(TMP))+inputs={};commands=[];started=time.monotonic()+def protect(p):+ p=Path(p);p=p if p.is_absolute() else CACHE/p+ assert p.is_file(),p+ if str(p) not in inputs:inputs[str(p)]=sha(p)+ return p+def rule(name,protectObjects=True):+ lines=re.search(r'^build '+re.escape(name)+r': .*?(?=\n\n)',ninja,re.M|re.S).group().splitlines()+ variables=dict(re.match(r' ([A-Z_]+) = (.*)',line).groups() for line in lines[1:] if re.match(r' ([A-Z_]+) = (.*)',line))+ objects=[(protect(unescape(n)) if protectObjects else CACHE/unescape(n)) for n in lines[0].split('Release ',1)[1].split(' | ',1)[0].split(' ')]+ for a in args(unescape(variables['LINK_LIBRARIES'])):+ if a.lower().endswith('.lib') and (Path(a).is_file() or (CACHE/a).is_file()):protect(a)+ return objects,variables+gui=rule('veyra_qml_ui.exe');color=rule('veyra_capture_color_tests.exe',False);capture=rule('veyra_capture_tests.exe',False);gpu=rule('veyra_hdr_color_tests.exe',False)+for p in (CACHE/'veyra_qml_ui.exe',CACHE/'veyra-qml.manifest',CACHE/'build.ninja',CACHE/'CMakeCache.txt'):protect(p)+(LOG/'inputs-before.json').write_text(json.dumps(inputs,indent=2),encoding='utf8')+def run(cmd,name):+ assert time.monotonic()-started<880+ commands.append(cmd);t=time.monotonic()+ with (LOG/(name+'.log')).open('w',encoding='utf8') as f:r=subprocess.run(cmd,cwd=CACHE,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=min(300,890-(time.monotonic()-started)))+ print(name,'exit',r.returncode,'seconds',round(time.monotonic()-t,2),flush=True)+ if r.returncode:print((LOG/(name+'.log')).read_text(encoding='utf8',errors='replace')[-2500:]);raise SystemExit(r.returncode)+def compile(source,name,objectRule,extra=()):+ # -t commands also prints order-only dependency generators. Select only the+ # requested object's compiler line; never execute those cached-tree writers.+ command=subprocess.check_output([tool,'-t','commands',objectRule],cwd=CACHE,encoding='utf8').splitlines()[-1];a=args(command)+ assert a[0].lower().endswith('cl.exe') and '/Fo'+objectRule.replace('/','\\') in a,(a[0],objectRule)+ # The old source path is the final argument, all outputs are redirected to E task storage.+ a=a[:-1];a=[v for v in a if not v.startswith(('/Fo','/Fd')) and v!='/showIncludes']+ target=OUT/(name+'.obj');a=a[:1]+['/I'+str(ROOT/'include'),'/I'+str(ROOT/'tests/unit')]+a[1:]+list(extra)+['/Fo'+str(target),'/Fd'+str(OUT/(name+'.pdb')),str(source)]+ run(a,'compile-'+name);return target+sinkRule=r'CMakeFiles/veyra_sources.dir/src/source/NativeCaptureSink.cpp.obj'+sourceRule=r'CMakeFiles/veyra_sources.dir/src/source/CaptureCardSource.cpp.obj'+testRule=r'CMakeFiles/veyra_capture_color_tests.dir/tests/unit/CaptureColorContractTests.cpp.obj'+sink=compile(ROOT/'src/source/NativeCaptureSink.cpp','NativeCaptureSink',sinkRule)+source=compile(ROOT/'src/source/CaptureCardSource.cpp','CaptureCardSource',sourceRule)+test=compile(ROOT/'tests/unit/CaptureColorContractTests.cpp','capture-contract',testRule)+field=compile(ROOT/'tests/integration/CaptureSourceTests.cpp','capture-source-fixture',r'CMakeFiles/veyra_capture_tests.dir/tests/integration/CaptureSourceTests.cpp.obj')+gpuObject=gpu[0][0];gpuSource=str(gpuObject.relative_to(CACHE)).replace('\\','/').split('.dir/',1)[1][:-4]+gpuFixture=compile(ROOT/gpuSource,'capture-gpu-fixture',str(gpuObject.relative_to(CACHE)).replace('\\','/'))+old=TMP/'NativeCaptureSink-original.cpp';old.write_bytes(subprocess.check_output(['git','show','dbfceab:src/source/NativeCaptureSink.cpp'],cwd=ROOT))+oldSink=compile(old,'NativeCaptureSink-original',sinkRule)+oldTest=compile(ROOT/'tests/unit/CaptureColorContractTests.cpp','capture-contract-red',testRule,['/DVEYRA_TEST_BMD_LEGACY_FACTORY=1'])+link=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Tools\MSVC\1444~1.352\bin\Hostx64\x64\link.exe'+cmake=r'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'+def linkexe(name,entry,overrides,replaceObjects=None):+ objects,var=entry;objects=objects if replaceObjects is None else replaceObjects+ response=OUT/(name+'.rsp');response.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in overrides+objects)+'\n'+unescape(var.get('LINK_PATH',''))+'\n'+unescape(var['LINK_LIBRARIES']),encoding='utf8')+ exe=OUT/(name+'.exe');manifest=OUT/('manifest-'+name);manifest.mkdir(exist_ok=True)+ flags=[('/MANIFESTINPUT:'+str(CACHE/'veyra-qml.manifest')) if a.startswith('/MANIFESTINPUT:') else a for a in args(unescape(var.get('LINK_FLAGS','')))]+ run([cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(manifest),r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(response),'/out:'+str(exe),'/implib:'+str(OUT/(name+'.lib')),'/pdb:'+str(OUT/(name+'.pdb')),'/version:0.0']+flags,'link-'+name)+ return exe+red=linkexe('capture-contract-red',color,[oldSink],[oldTest])+green=linkexe('capture-contract',color,[sink,source],[test])+physical=linkexe('capture-source',capture,[sink,source],[field])+app=linkexe('veyra-bmd-followup',gui,[sink,source])+gpuExe=linkexe('capture-gpu',gpu,[sink,source],[gpuFixture])+for p,d in inputs.items():assert sha(Path(p))==d,p+sources={str(p.relative_to(ROOT)).replace('\\','/'):sha(p) for p in [ROOT/'src/source/NativeCaptureSink.cpp',ROOT/'src/source/CaptureCardSource.cpp',ROOT/'include/veyra/source/NativeCaptureSink.h',ROOT/'tests/unit/CaptureColorContractTests.cpp',ROOT/'tests/unit/BmdAllocatorCases.h']}+receipt={'baseMain':'dbfceabee804cd81bac4a4781f0b7b4cf272902e','cachedProduct':'71723e0249a17764696796fd204a6eb69d6da276','commands':commands,'inputsUnchanged':inputs,'sources':sources,'objects':{str(p):sha(p) for p in (sink,source,test,oldSink,oldTest,field,gpuFixture)},'originalSinkSha256':sha(old),'executables':{str(p):{'sha256':sha(p),'bytes':p.stat().st_size} for p in (red,green,physical,app,gpuExe)},'seconds':time.monotonic()-started}+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')+(BASE/'reports'/TASK/'build-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/bmd-followup-control.py')],check=True)+print('BMD build and original input preservation passed',flush=True)diff --git a/scripts/acceptance/bmd-followup-control.py b/scripts/acceptance/bmd-followup-control.pynew file mode 100644index 00000000..b558145b--- /dev/null+++ b/scripts/acceptance/bmd-followup-control.py@@ -0,0 +1,17 @@+"""Read-only scope and preservation gate for the BMD follow-up."""+from pathlib import Path+import hashlib,json,subprocess,sys+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-followup-20261009'+subprocess.run([sys.executable,'-B',str(BASE/'reports'/TASK/'state.py'),'verify'],check=True)+allowed={'AGENTS.md','THIRD_PARTY_NOTICES.md','docs/WORKLOG.md','docs/BLACKMAGIC_FOLLOWUP_PLAN_2026-10-09.md','docs/BLACKMAGIC_FOLLOWUP_REPORT_2026-10-09.md',+ 'include/veyra/source/NativeCaptureSink.h','src/source/NativeCaptureSink.cpp','src/source/CaptureCardSource.cpp',+ 'tests/unit/CaptureColorContractTests.cpp','tests/unit/BmdAllocatorCases.h',+ 'scripts/acceptance/bmd-followup-control.py','scripts/acceptance/bmd-followup-build.py','scripts/acceptance/bmd-followup-test.py','scripts/acceptance/bmd-followup-package.py','scripts/diagnostics/Start-BMD-Capture-Test.ps1'}+def git(*args):return subprocess.check_output(['git',*args],cwd=ROOT).decode('utf8')+changed=set(git('diff','dbfceabee804cd81bac4a4781f0b7b4cf272902e','--name-only').splitlines())+changed.update(git('ls-files','--others','--exclude-standard').splitlines())+assert changed<=allowed,sorted(changed-allowed)+for n in changed:assert Path(n).suffix.lower() not in ('.exe','.dll','.pdb','.lib','.onnx','.zip','.hipfb','.cubin'),n+subprocess.run(['git','diff','--check'],cwd=ROOT,check=True,capture_output=True)+(BASE/'reports'/TASK/'control.json').write_text(json.dumps({'passed':True,'scope':sorted(changed),'baseMain':'dbfceabee804cd81bac4a4781f0b7b4cf272902e'},ensure_ascii=False,indent=2),encoding='utf8')+print('BMD preservation/scope passed:',len(changed),'files')diff --git a/scripts/acceptance/bmd-followup-package.py b/scripts/acceptance/bmd-followup-package.pynew file mode 100644index 00000000..65192a5b--- /dev/null+++ b/scripts/acceptance/bmd-followup-package.py@@ -0,0 +1,60 @@+"""One shared private app and a small overlay; keep runtimes unchanged."""+from pathlib import Path+import hashlib,json,os,shutil,subprocess,sys,zipfile+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-followup-20261009'+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'+OUT=BASE/'test-packages'/TASK;APP=BASE/'tests'/TASK/'app';BUILD=BASE/'build'/TASK+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+def build():return json.loads(Path(json.loads((BASE/'reports'/TASK/'build-current.json').read_text(encoding='utf8'))['receipt']).read_text(encoding='utf8'))+def auditDonor():+ manifest=json.loads((DONOR/'package-manifest.json').read_text(encoding='utf-8-sig'))+ for row in manifest['files']:assert sha(DONOR/row['path'])==row['sha256'].lower(),row['path']+ return manifest+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/bmd-followup-control.py')],check=True)+receipt=build()+for n,d in receipt['sources'].items():assert sha(ROOT/n)==d,n+for n,d in receipt['executables'].items():assert sha(Path(n))==d['sha256'],n+manifest=auditDonor();OUT.mkdir(parents=True,exist_ok=True)+if sys.argv[1]=='prepare':+ assert not APP.exists();APP.parent.mkdir(parents=True,exist_ok=True)+ def linked(a,b):+ if Path(a).relative_to(DONOR).as_posix() in ('veyra_qml_ui.exe','qml/Veyra/Main.qml','THIRD_PARTY_NOTICES.md','package-manifest.json'):return shutil.copy2(a,b)+ os.link(a,b);return b+ shutil.copytree(DONOR,APP,copy_function=linked)+ shutil.copy2(BUILD/'veyra-bmd-followup.exe',APP/'veyra_qml_ui.exe');shutil.copy2(ROOT/'THIRD_PARTY_NOTICES.md',APP/'THIRD_PARTY_NOTICES.md')+ (BASE/'reports'/TASK/'app.json').write_text(json.dumps({'path':str(APP),'exeSha256':sha(APP/'veyra_qml_ui.exe'),'donorFilesVerified':len(manifest['files']),'sharedDependenciesUnmodified':True},ensure_ascii=False,indent=2),encoding='utf8')+ print('Prepared one private app; verified donor files',len(manifest['files']));raise SystemExit(0)+assert sys.argv[1]=='package'+assert sha(APP/'veyra_qml_ui.exe')==sha(BUILD/'veyra-bmd-followup.exe')+payload={'veyra_qml_ui.exe':BUILD/'veyra-bmd-followup.exe','THIRD_PARTY_NOTICES.md':ROOT/'THIRD_PARTY_NOTICES.md','Start-BMD-Capture-Test.ps1':ROOT/'scripts/diagnostics/Start-BMD-Capture-Test.ps1','licenses/capture/LIBDSHOWCAPTURE_LGPL.txt':ROOT/'licenses/capture/LIBDSHOWCAPTURE_LGPL.txt'}+# Use the complete matching QML/shader set; no new DLL/model/SDK is distributed.+for folder in ('qml/Veyra','shaders'):+ for p in (DONOR/folder).rglob('*'):+ if p.is_file():payload[p.relative_to(DONOR).as_posix()]=p+readme='''BMD / Blackmagic / DeckLink 2.0.6 兼容测试补丁(非正式发布)++1. 保留原包,另复制/解压一份完整 Veyra 2.0.6 便携包;把本补丁解压覆盖到副本根目录。AMD/NVIDIA 继续用各自原包的运行库。+2. 关闭 OBS 和其它采集程序,运行 veyra_qml_ui.exe。选原来的 BMD 入口,使用 OBS 能出画时的完全相同分辨率、帧率、像素格式;59.94 与 60、1080p30 与 1080i60 不互换。先关闭增强确认基础画面,再开平时的增强。两个名称不证明物理上有两张卡。+3. 新兼容模式默认自动应用于 BMD。请测试两个入口、断开后重连。不要用任意模式代替实际输入制式;软件没有声称自动检测 BMD 信号。+4. 如需收集对照日志,在本目录打开 PowerShell,运行:+ powershell -NoProfile -ExecutionPolicy Bypass -File .\\Start-BMD-Capture-Test.ps1+ 选择设备/格式,3分钟后自动退出并在 logs 中生成 zip。脚本使用私有配置,不改原设置。+ 旧协商对照:同一命令末尾加 -Variant Legacy。两次请选完全相同的设备/模式/增强设置;不要同时开。+5. 如仍黑屏,把两次 zip 与 OBS 来源的属性(实际输入制式、卡型号、HDMI/SDI)一起交给开发者。日志中的黑像素统计不是“无信号”判定,正常黑场不会触发切换/丢帧。++本轮修复的是接收端与驱动的分配器/连接格式协商,保留驱动 DIB 方向;同时拒绝静默 subtype/隔行合同变更。已做本机 COM、GPU 像素、普通 USB 采集与 GUI 验证;没有本机 BMD 卡,实卡是否恢复出画仍待反馈。运行库/模型均沿用原包,本补丁不更换驱动。+基于当前 main dbfceab(包含已合入的 VFG 优化),此包仅为 BMD 本地候选,不是新版本发布。软件内构建字符串沿用缓存构建的 2.0.6-vfg-next,以 bmd-compat-manifest.json 中 EXE SHA 为本候选身份。+'''+files={n:{'sha256':sha(p),'bytes':p.stat().st_size} for n,p in payload.items()}+meta={'schema':1,'version':'2.0.6','candidate':'bmd-followup-20261009','localOnly':True,'releaseReady':False,'baseMain':receipt['baseMain'],'displayVersion':'2.0.6-vfg-next','realBmdHardwareValidated':False,'runtimeChanges':False,'appliesTo':'Blackmagic/DeckLink native raw video; v210 keeps the existing system conversion path','correspondingSource':'Veyra-2.0.6-BMD-compat-source.zip','compiledSources':receipt['sources'],'files':files}+target=OUT/'Veyra-2.0.6-BMD-compat-test.zip';assert not target.exists()+with zipfile.ZipFile(target,'x',zipfile.ZIP_DEFLATED,compresslevel=6) as z:+ for name,p in sorted(payload.items()):z.write(p,name)+ z.writestr('使用说明.txt',readme.encode('utf-8-sig'));z.writestr('bmd-compat-manifest.json',json.dumps(meta,ensure_ascii=False,indent=2).encode('utf8'))+with zipfile.ZipFile(target) as z:+ assert z.testzip() is None+ for name,row in files.items():assert hashlib.sha256(z.read(name)).hexdigest()==row['sha256'],name+ assert not any(Path(n).suffix.lower() in ('.dll','.onnx','.pdb','.lib','.hipfb') for n in z.namelist())+auditDonor()+result={'path':str(target),'bytes':target.stat().st_size,'sha256':sha(target),'files':len(files)+2,'crcAndEveryPayloadShaVerified':True,'exeSha256':sha(BUILD/'veyra-bmd-followup.exe'),'donorFilesVerified':len(manifest['files'])}+(BASE/'reports'/TASK/'package.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8');print(json.dumps(result,ensure_ascii=False))diff --git a/scripts/acceptance/bmd-followup-test.py b/scripts/acceptance/bmd-followup-test.pynew file mode 100644index 00000000..9c23ec08--- /dev/null+++ b/scripts/acceptance/bmd-followup-test.py@@ -0,0 +1,74 @@+"""Bounded serial contract, GPU and real USB tests; BMD hardware is not local."""+from pathlib import Path+import hashlib,json,os,re,subprocess,sys,time,psutil+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-followup-20261009';BUILD=BASE/'build'/TASK+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'+label=sys.argv[1];assert label.replace('-','').isalnum()+OUT=BASE/'tests'/TASK/label;TMP=BASE/'tmp'/TASK/label;LOG=BASE/'logs'/TASK/label+for p in (OUT,TMP,LOG):p.mkdir(parents=True,exist_ok=False)+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/bmd-followup-control.py')],check=True)+build=json.loads(Path(json.loads((BASE/'reports'/TASK/'build-current.json').read_text(encoding='utf8'))['receipt']).read_text(encoding='utf8'))+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()+for n,d in build['sources'].items():assert sha(ROOT/n)==d,n+for n,d in build['executables'].items():assert sha(Path(n))==d['sha256'],n+# GPU fixtures locate shader binaries relative to their own EXE, not PATH.+for p in (DONOR/'shaders').rglob('*'):+ if p.is_file():+ target=BUILD/'shaders'/p.relative_to(DONOR/'shaders');target.parent.mkdir(parents=True,exist_ok=True)+ if not target.exists():os.link(p,target)+ assert sha(target)==sha(p),target+busy=[p.info for p in psutil.process_iter(['pid','name']) if p.info['name'] and p.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra-bmd-followup.exe','capture-gpu.exe')]+assert not busy,busy+env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_','QSG_'))}+env.update(TEMP=str(TMP),TMP=str(TMP),CUDA_CACHE_PATH=str(TMP/'cuda-cache'))+win=Path(env['WINDIR']);env['PATH']=os.pathsep.join(map(str,(BUILD,DONOR,win/'System32',win,win/'System32/Wbem')))+cases=[('pre-fix-contract','capture-contract-red.exe',[],True),('candidate-contract','capture-contract.exe',[],False),('gpu-pixels','capture-gpu.exe',[],False),('devices','capture-source.exe',['--list'],False)]+if '--usb' in sys.argv:cases+=[('usb-1080p60','capture-source.exe',['--rate-test','capture:0:1:-1','0'],False)]+if '--cases' in sys.argv:+ selected=set(sys.argv[sys.argv.index('--cases')+1].split(','))+ assert selected<=set(c[0] for c in cases),selected+ cases=[c for c in cases if c[0] in selected]+if '--gui' in sys.argv:cases=[]+results=[]+for name,exe,a,red in cases:+ log=LOG/(name+'.log');child=env.copy();child['VEYRA_LOG_FILE']=str(LOG/(name+'-engine.log'));cmd=[str(BUILD/exe),*a];start=time.monotonic()+ with log.open('xb') as f:+ try:rc=subprocess.run(cmd,cwd=OUT,env=child,stdout=f,stderr=subprocess.STDOUT,timeout=290).returncode+ except subprocess.TimeoutExpired:rc=124+ text=log.read_text(encoding='utf8',errors='replace');failures=re.findall(r'^FAIL .+$',text,re.M)+ if red:+ passed=rc==1 and len(failures)>=7 and all('BMD ' in f for f in failures) and 'failures=' in text+ else:passed=rc==0 and not failures and not re.search(r'\bpass=0\b',text)+ if name=='candidate-contract':passed=passed and text.count('PASS BMD source pixels delivered exactly')==2 and 'failures=0' in text+ if name=='gpu-pixels':passed=passed and len(re.findall(r'BLACKMAGIC_HDYC_GPU flip=[01] identical709=1.*pass=1',text))==2 and len(re.findall(r'CAPTURE_GPU subtype=43594448.*pass=1',text))==2+ # pass=0 is the first measurement index in this fixture, not a failed boolean.+ if name=='usb-1080p60':passed=rc==0 and not failures and len(re.findall(r'PASS RATE pass=[01]',text))==2 and not re.search(r'\[capture-bmd-compat\]',text)+ result={'case':name,'command':cmd,'exit':rc,'seconds':time.monotonic()-start,'passed':bool(passed),'expectedOldFailure':red,'failedChecks':failures,'checksPrinted':len(re.findall(r'^PASS\b|\bpass=1\b',text,re.M)),'exeSha256':sha(BUILD/exe),'log':str(log)}+ results.append(result);(LOG/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')+ print(json.dumps(result,ensure_ascii=False),flush=True);print('\n'.join(text.splitlines()[-4:]),flush=True)+ if not passed:raise SystemExit(1)+if '--gui' in sys.argv:+ app=BASE/'tests'/TASK/'app';main=app/'qml/Veyra/Main.qml';original=main.read_bytes()+ assert sha(app/'veyra_qml_ui.exe')==sha(BUILD/'veyra-bmd-followup.exe')+ assert os.stat(main).st_ino!=os.stat(DONOR/'qml/Veyra/Main.qml').st_ino,'Main.qml must be a private copy before loader injection'+ profile=OUT/'profile';images=OUT/'screenshots';profile.mkdir();images.mkdir()+ (profile/'qml-preferences.v1.json').write_text(json.dumps({'overlayCompat':'off','gpuPriority':'normal','obsGameCapture':False,'screenshotDir':str(images)},ensure_ascii=False),encoding='utf8')+ source=original.decode('utf8');at=source.rfind('}')+ loader='\nLoader { source: '+json.dumps((ROOT/'scripts/acceptance/blackmagic-ui.qml').as_uri())+'; onLoaded: { item.dialogHost=dialogs;item.evidence='+json.dumps(str(images))+';item.phase="capture"; } }\n'+ child=env.copy();child.update(VEYRA_LOG_FILE=str(LOG/'gui-engine.log'),CUDA_CACHE_PATH=str(TMP/'cuda-cache'),QML_DISK_CACHE_PATH=str(TMP/'qml-cache'))+ child['PATH']=os.pathsep.join(map(str,(app,win/'System32',win,win/'System32/Wbem')))+ command=[str(app/'veyra_qml_ui.exe'),'--page','pro','--size','1280x900','--data-dir',str(profile),'--exit-after','110000']+ start=time.monotonic();log=LOG/'gui.log'+ try:+ main.write_text(source[:at]+loader+source[at:],encoding='utf8')+ with log.open('xb') as f:+ try:rc=subprocess.run(command,cwd=app,env=child,stdout=f,stderr=subprocess.STDOUT,timeout=125).returncode+ except subprocess.TimeoutExpired:rc=124+ finally:main.write_bytes(original)+ text=log.read_text(encoding='utf8',errors='replace')+ passed=rc==0 and 'BLACKMAGIC_UI_PASS' in text and not re.search(r'BLACKMAGIC_UI_FAIL|ReferenceError:|TypeError:|no root object',text)+ imageFiles=list(images.glob('veyra-*.png'));passed=passed and len(imageFiles)==1+ result={'case':'production-gui-usb','command':command,'exit':rc,'seconds':time.monotonic()-start,'passed':bool(passed),'exeSha256':sha(app/'veyra_qml_ui.exe'),'mainRestored':sha(main)==hashlib.sha256(original).hexdigest(),'screenshotFiles':[str(p) for p in images.glob('*.png')],'fixtureSha256':sha(ROOT/'scripts/acceptance/blackmagic-ui.qml'),'log':str(log)}+ (LOG/'summary.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8');print(json.dumps(result,ensure_ascii=False),flush=True)+ print('\n'.join(text.splitlines()[-6:]),flush=True);assert passed+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/bmd-followup-control.py')],check=True)diff --git a/scripts/diagnostics/Start-BMD-Capture-Test.ps1 b/scripts/diagnostics/Start-BMD-Capture-Test.ps1new file mode 100644index 00000000..4504c075--- /dev/null+++ b/scripts/diagnostics/Start-BMD-Capture-Test.ps1@@ -0,0 +1,63 @@+param(+ [string]$AppDirectory = $PSScriptRoot,+ [ValidateSet('Compatible','Legacy')][string]$Variant = 'Compatible',+ [string]$ProfileSource = '',+ [string]$OutputDirectory = '',+ [ValidateRange(15,280)][int]$DurationSeconds = 180+)+$ErrorActionPreference='Stop'+function File-Sha256([string]$Path) {+ $stream=[IO.File]::OpenRead($Path);$hasher=[Security.Cryptography.SHA256]::Create()+ try { return [BitConverter]::ToString($hasher.ComputeHash($stream)).Replace('-','') }+ finally { $hasher.Dispose();$stream.Dispose() }+}+$app=[IO.Path]::GetFullPath($AppDirectory);$player=Join-Path $app 'veyra_qml_ui.exe'+if (-not (Test-Path -LiteralPath $player -PathType Leaf)) { throw 'Extract the patch into a Veyra 2.0.6 portable copy first.' }+if (@(Get-Process -Name 'veyra_qml_ui','Veyra' -ErrorAction SilentlyContinue).Count -gt 0) { throw 'Close Veyra first. Close OBS before testing the same capture card.' }+if ([string]::IsNullOrWhiteSpace($OutputDirectory)) { $OutputDirectory=Join-Path $app ('logs/bmd-'+$Variant+'-'+(Get-Date -Format 'yyyyMMdd-HHmmss-fff')) }+$output=[IO.Path]::GetFullPath($OutputDirectory)+if (Test-Path -LiteralPath $output) { throw 'Output already exists; evidence will not be overwritten.' }+$profile=Join-Path $output 'private-profile';$tmp=Join-Path $output 'tmp'+$null=New-Item -ItemType Directory -Path $profile,$tmp -Force+$copied=@()+if (-not [string]::IsNullOrWhiteSpace($ProfileSource)) {+ $fromProfile=[IO.Path]::GetFullPath($ProfileSource)+ # Only preferences, never PSN/Xbox credentials or whole user directories.+ foreach ($name in @('capture-preferences.v1','chain-session.v1','chain-session.v1.vfg','qml-preferences.v1.json','ui-session.v1')) {+ $from=Join-Path $fromProfile $name+ if (Test-Path -LiteralPath $from -PathType Leaf) {+ $digest=File-Sha256 $from;Copy-Item -LiteralPath $from -Destination (Join-Path $profile $name)+ $copied += [pscustomobject]@{path=$from;sha256=$digest}+ }+ }+}+$names=@('TEMP','TMP','CUDA_CACHE_PATH','QML_DISK_CACHE_PATH','VEYRA_LOG_FILE','VEYRA_BMD_DSHOW_LEGACY')+$saved=@{};foreach ($name in $names) { $saved[$name]=[Environment]::GetEnvironmentVariable($name,'Process') }+$arguments=@('--page','pro','--data-dir',$profile,'--exit-after',($DurationSeconds*1000).ToString())+if (@($arguments | Where-Object { $_.Contains('"') -or $_.EndsWith('\') }).Count -gt 0) { throw 'Unsupported argument quoting.' }+$quoted=@($arguments | ForEach-Object { '"'+$_+'"' })+$result=125;$forcedStop=$false+try {+ $env:TEMP=$tmp;$env:TMP=$tmp;$env:CUDA_CACHE_PATH=Join-Path $tmp 'cuda-cache';$env:QML_DISK_CACHE_PATH=Join-Path $tmp 'qml-cache'+ $env:VEYRA_LOG_FILE=Join-Path $output 'engine.log'+ if ($Variant -eq 'Legacy') { $env:VEYRA_BMD_DSHOW_LEGACY='1' }+ else { [Environment]::SetEnvironmentVariable('VEYRA_BMD_DSHOW_LEGACY',$null,'Process') }+ Write-Host ('BMD '+$Variant+': select the same device and exact input resolution/FPS/pixel format as OBS. Disable enhancements for the first check; then test your usual settings.')+ # Visible player is intentional: this launcher is an interactive field test.+ $process=Start-Process -FilePath $player -ArgumentList $quoted -WorkingDirectory $app -PassThru -WindowStyle Normal `+ -RedirectStandardOutput (Join-Path $output 'console.log') -RedirectStandardError (Join-Path $output 'stderr.log')+ $null=$process.Handle+ if (-not $process.WaitForExit(($DurationSeconds+20)*1000)) { $forcedStop=$true;Stop-Process -Id $process.Id -Force;$process.WaitForExit() }+ $process.WaitForExit();$process.Refresh();$result=$process.ExitCode+ if ($forcedStop) { $result=124 } elseif ($null -eq $result) { $result=125 }+} finally { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name,$saved[$name],'Process') } }+$unchanged=$true;foreach ($item in $copied) { if (-not (Test-Path -LiteralPath $item.path -PathType Leaf) -or (File-Sha256 $item.path) -ne $item.sha256) { $unchanged=$false } }+$receipt=[pscustomobject]@{exit=$result;forcedStop=$forcedStop;variant=$Variant;executableSha256=(File-Sha256 $player);privateProfile=$profile;sourceProfileUnchanged=$unchanged;durationLimitSeconds=$DurationSeconds;realBmdHardwareValidated=$false}+$receipt | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $output 'test-receipt.json') -Encoding UTF8+Add-Type -AssemblyName System.IO.Compression;Add-Type -AssemblyName System.IO.Compression.FileSystem+$stream=[IO.File]::Open(($output+'.zip'),[IO.FileMode]::CreateNew);$zip=[IO.Compression.ZipArchive]::new($stream,[IO.Compression.ZipArchiveMode]::Create)+try { foreach ($file in @(Get-ChildItem -LiteralPath $output -File | Where-Object { $_.Extension -in '.log','.json' })) { $null=[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$file.FullName,$file.Name,[IO.Compression.CompressionLevel]::Optimal) } }+finally { $zip.Dispose();$stream.Dispose() }+Write-Host ('Send this evidence: '+$output+'.zip')+if (-not $unchanged) { throw 'Original preferences changed during comparison.' }+exit $resultdiff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 732d7a5a..8e6121e5 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -833,6 +833,10 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.clestd::wstring devicePath=selection.videoPath;if(devicePath.empty()){const auto devices=monikers(false);if(index<devices.size())devicePath=monikerPath(devices[index].Get());}const auto deviceName=captureDeviceName(devicePath);p.signalProbeEnabled=isBlackmagicCaptureDevice(deviceName,devicePath);+ wchar_t legacyFlag[2]{};+ const bool bmdLegacy=GetEnvironmentVariableW(L"VEYRA_BMD_DSHOW_LEGACY",legacyFlag,2)==1&&legacyFlag[0]==L'1';+ const bool bmdCompat=p.signalProbeEnabled&&!bmdLegacy;+ if(p.signalProbeEnabled)log::info("capture-bmd-compat",std::format("enabled={} legacyOverride={} allocator={} bufferRequirements={} connectType={} dibOrientation={} notSignalDetection=1",bmdCompat,bmdLegacy,bmdCompat?"upstream":"sink-default",bmdCompat?"driver":"N4",bmdCompat?"output-selected":"explicit",bmdCompat?"driver":"request-top-down"));const auto upstream=dshow::connectCaptureCrossbar(p.graph.Get(),p.builder.Get(),p.device.Get());log::info("capture-upstream",std::format("name={} inputMediums={} crossbar={} existing={} hr=0x{:08X} routeChanged=0",narrowForLog(deviceName),upstream.inputMediums,bool(upstream.filter),upstream.existing,uint32_t(upstream.hr)));if(FAILED(upstream.hr)){error_=std::format(L"采集卡上游输入连接失败(0x{:08X}),请检查驱动与输入选择。",uint32_t(upstream.hr));freeType(native);return false;}@@ -852,7 +856,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle// normalizes the mismatch (connected type is then negative and no flip is// applied), a refusal keeps the driver-declared sign and the existing flip.// Truthful bottom-up devices stay correct in both cases.- if(nativeSupported&&captureIsRgbDib(nativeLayout.packing)){+ if(nativeSupported&&!bmdCompat&&captureIsRgbDib(nativeLayout.packing)){if(auto* header=captureBitmapHeader(*native);header&&header->biHeight>0){const LONG advertised=header->biHeight;header->biHeight=-advertised;const HRESULT topDownHr=p.config->SetFormat(native);@@ -914,14 +918,22 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle// suggestion is advisory; a refusal keeps the driver's defaults and is// reported after the connect instead of failing the device.const auto bufferPolicy=static_cast<CaptureBufferMode>(p.bufferMode);- const long suggestedBuffers=captureDesiredVideoBuffers(bufferPolicy,long(nativeLayout.width),long(nativeLayout.height));+ const long suggestedBuffers=bmdCompat?0:captureDesiredVideoBuffers(bufferPolicy,long(nativeLayout.width),long(nativeLayout.height));ComPtr<IPin> input,output;- hr=createNativeCaptureSink(*native,[&p](IMediaSample* sample){REFERENCE_TIME a=0,b=0;const auto timeHr=sample->GetTime(&a,&b);if(FAILED(timeHr))return timeHr;return p.SampleCB(double(a)/1e7,sample);},p.grabFilter,input);+ hr=createNativeCaptureSink(*native,[&p](IMediaSample* sample){REFERENCE_TIME a=0,b=0;const auto timeHr=sample->GetTime(&a,&b);if(FAILED(timeHr))return timeHr;return p.SampleCB(double(a)/1e7,sample);},p.grabFilter,input,bmdCompat?CaptureAllocatorMode::Upstream:CaptureAllocatorMode::SinkDefault);if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.grabFilter.Get(),L"Native frame mailbox");if(SUCCEEDED(hr))hr=p.builder->FindPin(p.device.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&output);if(SUCCEEDED(hr)&&suggestedBuffers>0)suggestCaptureVideoBuffering(output.Get(),suggestedBuffers,LONG(nativeLayout.sampleBytes));- if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(output.Get(),input.Get(),native);+ // OBS HDevice::ConnectPins (fixed commit/license in NativeCaptureSink.cpp)+ // lets the output pin supply its configured media type. Check the actual+ // layout after connection so this cannot silently pick another mode.+ if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(output.Get(),input.Get(),bmdCompat?nullptr:native);if(SUCCEEDED(hr))hr=input->ConnectionMediaType(&connected);+ if(SUCCEEDED(hr)&&bmdCompat){+ const bool same=nativeCaptureContractsMatch(*native,connected);+ log::info("capture-bmd-compat",std::format("connectedContractMatches={} subtype=0x{:08X} converters=0",same,connected.subtype.Data1));+ if(!same){error_=L"BMD 驱动返回的连接格式与所选模式不同,请按实际信号重新选择格式。";hr=VFW_E_INVALIDMEDIATYPE;}+ }if(SUCCEEDED(hr)){ALLOCATOR_PROPERTIES actual{};const auto allocatorHr=queryCaptureAllocatorProperties(input.Get(),actual);diff --git a/src/source/NativeCaptureSink.cpp b/src/source/NativeCaptureSink.cppindex e45219b4..7ebbed3e 100644--- a/src/source/NativeCaptureSink.cpp+++ b/src/source/NativeCaptureSink.cpp@@ -11,6 +11,11 @@namespace veyra::source {using Microsoft::WRL::ComPtr;+bool nativeCaptureContractsMatch(const AM_MEDIA_TYPE& a,const AM_MEDIA_TYPE& b){+ if(a.subtype!=b.subtype||!equivalentCaptureTypes(a,b))return false;+ const auto fields=[](const AM_MEDIA_TYPE& t){return t.formattype==FORMAT_VideoInfo2&&t.pbFormat&&t.cbFormat>=sizeof(VIDEOINFOHEADER2)?reinterpret_cast<const VIDEOINFOHEADER2*>(t.pbFormat)->dwInterlaceFlags:DWORD(0);};+ return fields(a)==fields(b);+}namespace {LONG audioBlockBytes(const WAVEFORMATEX& f){// Round up to whole sample frames, including uncommon rates such as 11025.@@ -57,7 +62,7 @@ public:HRESULT STDMETHODCALLTYPE Reset()override{used_=false;return S_OK;}HRESULT STDMETHODCALLTYPE Clone(IEnumMediaTypes** p)override{if(!p)return E_POINTER;try{*p=new TypeEnum(type_,used_);return S_OK;}catch(...){*p=nullptr;return E_OUTOFMEMORY;}}};-class NativeSink final:public IBaseFilter,public IPin,public IMemInputPin {+class NativeSink final:public IBaseFilter,public IPin,public IMemInputPin,public IAMFilterMiscFlags {std::atomic<ULONG> refs_{1};std::recursive_mutex mutex_;FILTER_STATE state_=State_Stopped;bool flushing_=false;AM_MEDIA_TYPE desired_{},connected_{};CaptureMediaLayout layout_;@@ -66,8 +71,9 @@ class NativeSink final:public IBaseFilter,public IPin,public IMemInputPin {std::function<HRESULT(IMediaSample*)> callback_;bool audio_=false;bool compressed_=false;+ CaptureAllocatorMode allocatorMode_=CaptureAllocatorMode::SinkDefault;public:- NativeSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> cb,bool compressed=false):callback_(std::move(cb)){+ NativeSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> cb,bool compressed=false,CaptureAllocatorMode allocatorMode=CaptureAllocatorMode::SinkDefault):callback_(std::move(cb)),allocatorMode_(allocatorMode){compressed_=compressed;audio_=!compressed&&audioType(type);if(compressed_){if(FAILED(copyType(desired_,type)))throw std::bad_alloc();@@ -80,7 +86,8 @@ public:HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id==IID_IUnknown||id==IID_IPersist||id==IID_IMediaFilter||id==IID_IBaseFilter)*p=static_cast<IBaseFilter*>(this);- else if(id==IID_IPin)*p=static_cast<IPin*>(this);else if(id==IID_IMemInputPin)*p=static_cast<IMemInputPin*>(this);else return E_NOINTERFACE;+ else if(id==IID_IPin)*p=static_cast<IPin*>(this);else if(id==IID_IMemInputPin)*p=static_cast<IMemInputPin*>(this);+ else if(id==IID_IAMFilterMiscFlags&&allocatorMode_==CaptureAllocatorMode::Upstream)*p=static_cast<IAMFilterMiscFlags*>(this);else return E_NOINTERFACE;AddRef();return S_OK;}ULONG STDMETHODCALLTYPE AddRef()override{return ++refs_;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs_;if(!n)delete this;return n;}@@ -110,7 +117,7 @@ public:HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* p)override{if(!p)return E_POINTER;*p=PINDIR_INPUT;return S_OK;}HRESULT STDMETHODCALLTYPE QueryId(LPWSTR* p)override{if(!p)return E_POINTER;*p=static_cast<LPWSTR>(CoTaskMemAlloc(sizeof(L"Input")));if(!*p)return E_OUTOFMEMORY;memcpy(*p,L"Input",sizeof(L"Input"));return S_OK;}HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE* p)override{- if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(compressed_)return sameCompressed(*p,peer_?connected_:desired_)?S_OK:S_FALSE;if(audio_)return sameAudio(*p,peer_?connected_:desired_)?S_OK:S_FALSE;if(peer_)return equivalentCaptureTypes(*p,connected_)?S_OK:S_FALSE;CaptureMediaLayout candidate;+ if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(compressed_)return sameCompressed(*p,peer_?connected_:desired_)?S_OK:S_FALSE;if(audio_)return sameAudio(*p,peer_?connected_:desired_)?S_OK:S_FALSE;if(peer_)return (allocatorMode_==CaptureAllocatorMode::Upstream?nativeCaptureContractsMatch(*p,connected_):equivalentCaptureTypes(*p,connected_))?S_OK:S_FALSE;CaptureMediaLayout candidate;return captureMediaLayout(*p,candidate)&&p->subtype==desired_.subtype&&candidate.width==layout_.width&&candidate.height==layout_.height?S_OK:S_FALSE;}HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes** p)override{if(!p)return E_POINTER;try{*p=new TypeEnum(desired_);return S_OK;}catch(...){*p=nullptr;return E_OUTOFMEMORY;}}@@ -119,9 +126,24 @@ public:HRESULT STDMETHODCALLTYPE BeginFlush()override{std::lock_guard lock(mutex_);flushing_=true;return S_OK;}HRESULT STDMETHODCALLTYPE EndFlush()override{std::lock_guard lock(mutex_);flushing_=false;return S_OK;}HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME,REFERENCE_TIME,double)override{return S_OK;}- HRESULT STDMETHODCALLTYPE GetAllocator(IMemAllocator** p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(!allocator_){const auto hr=CoCreateInstance(CLSID_MemoryAllocator,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&allocator_));if(FAILED(hr))return hr;}return allocator_.CopyTo(p);}- HRESULT STDMETHODCALLTYPE NotifyAllocator(IMemAllocator* p,BOOL)override{+ // Adapted from OBS libdshowcapture c13d4b7b0c66979396ba0a9060c9aafc15bb7b22,+ // CapturePin allocator methods (Lain Bailey, LGPL-2.1-or-later).+ // Unlike OBS, retain the selected allocator for truthful post-connect+ // diagnostics. Never replace a driver pool with the generic allocator.+ HRESULT STDMETHODCALLTYPE GetAllocator(IMemAllocator** p)override{+ if(!p)return E_POINTER;*p=nullptr;std::lock_guard lock(mutex_);+ if(!allocator_){+ if(allocatorMode_==CaptureAllocatorMode::Upstream)return VFW_E_NO_ALLOCATOR;+ const auto hr=CoCreateInstance(CLSID_MemoryAllocator,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&allocator_));if(FAILED(hr))return hr;+ }+ return allocator_.CopyTo(p);+ }+ HRESULT STDMETHODCALLTYPE NotifyAllocator(IMemAllocator* p,BOOL readOnly)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);allocator_=p;+ if(allocatorMode_==CaptureAllocatorMode::Upstream){+ ALLOCATOR_PROPERTIES actual{};const auto hr=p->GetProperties(&actual);+ log::info("capture-bmd-allocator",std::format("upstreamSelected=1 readOnly={} buffers={} bytes={} align={} prefix={} hr=0x{:08X}",bool(readOnly),actual.cBuffers,actual.cbBuffer,actual.cbAlign,actual.cbPrefix,uint32_t(hr)));+ }if(audio_){ALLOCATOR_PROPERTIES actual{};const auto hr=p->GetProperties(&actual);const auto& f=*reinterpret_cast<const WAVEFORMATEX*>(desired_.pbFormat);@@ -131,6 +153,7 @@ public:}HRESULT STDMETHODCALLTYPE GetAllocatorRequirements(ALLOCATOR_PROPERTIES* p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);+ if(allocatorMode_==CaptureAllocatorMode::Upstream){*p={};return E_NOTIMPL;}*p={compressed_?4:3,compressed_?LONG(512*1024):audio_?audioBlockBytes(*reinterpret_cast<const WAVEFORMATEX*>(desired_.pbFormat)):LONG(layout_.sampleBytes),1,0};return S_OK;}// Receive holds the pin mutex across the callback (DirectShow requires@@ -144,7 +167,7 @@ public:AM_MEDIA_TYPE* changed=nullptr;const auto typeHr=sample->GetMediaType(&changed);if(FAILED(typeHr)){if(changed){clearType(*changed);CoTaskMemFree(changed);}log::error("capture",std::format("sample GetMediaType hr=0x{:08X}",uint32_t(typeHr)));return typeHr;}if(typeHr==S_OK&&changed){- const bool same=audio_?sameAudio(*changed,connected_):compressed_?sameCompressed(*changed,connected_):equivalentCaptureTypes(*changed,connected_);+ const bool same=audio_?sameAudio(*changed,connected_):compressed_?sameCompressed(*changed,connected_):allocatorMode_==CaptureAllocatorMode::Upstream?nativeCaptureContractsMatch(*changed,connected_):equivalentCaptureTypes(*changed,connected_);clearType(*changed);CoTaskMemFree(changed);if(!same){log::error("capture",std::format("dynamic capture contract changed; reopen required hr=0x{:08X}",uint32_t(VFW_E_INVALIDMEDIATYPE)));return VFW_E_INVALIDMEDIATYPE;}}if(compressed_){if(sample->GetActualDataLength()<=0)return VFW_E_BUFFER_UNDERFLOW;}@@ -154,6 +177,9 @@ public:}HRESULT STDMETHODCALLTYPE ReceiveMultiple(IMediaSample** p,long n,long* done)override{if(!p||!done||n<0)return E_INVALIDARG;*done=0;while(*done<n){const auto hr=Receive(p[*done]);if(hr!=S_OK)return hr;++*done;}return S_OK;}HRESULT STDMETHODCALLTYPE ReceiveCanBlock()override{return S_OK;}+ // OBS MiscFlagsHandler::GetMiscFlags, same source/license as above.+ // Use this object's canonical IUnknown; do not create a separate COM identity.+ ULONG STDMETHODCALLTYPE GetMiscFlags()override{return AM_FILTER_MISC_FLAGS_IS_RENDERER;}};}HRESULT suggestCaptureAudioBuffering(IPin* pin,const WAVEFORMATEX& format){@@ -203,8 +229,11 @@ HRESULT createCompressedCaptureSink(const AM_MEDIA_TYPE& type,std::function<HREStry{filter.Attach(new NativeSink(type,std::move(callback),true));return filter.As(&pin);}catch(...){return E_OUTOFMEMORY;}}HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> callback,ComPtr<IBaseFilter>& filter,ComPtr<IPin>& pin){+ return createNativeCaptureSink(type,std::move(callback),filter,pin,CaptureAllocatorMode::SinkDefault);+}+HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> callback,ComPtr<IBaseFilter>& filter,ComPtr<IPin>& pin,CaptureAllocatorMode allocatorMode){filter.Reset();pin.Reset();CaptureMediaLayout layout;if(!captureMediaLayout(type,layout))return VFW_E_INVALIDMEDIATYPE;- try{filter.Attach(new NativeSink(type,std::move(callback)));return filter.As(&pin);}catch(...){return E_OUTOFMEMORY;}+ try{filter.Attach(new NativeSink(type,std::move(callback),false,allocatorMode));return filter.As(&pin);}catch(...){return E_OUTOFMEMORY;}}HRESULT createNativeAudioSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> callback,ComPtr<IBaseFilter>& filter,ComPtr<IPin>& pin){filter.Reset();pin.Reset();if(!audioType(type))return VFW_E_INVALIDMEDIATYPE;diff --git a/tests/unit/BmdAllocatorCases.h b/tests/unit/BmdAllocatorCases.hnew file mode 100644index 00000000..654300c2--- /dev/null+++ b/tests/unit/BmdAllocatorCases.h@@ -0,0 +1,95 @@+#pragma once+#include <array>++// Uses real DirectShow allocators and samples, not fake success callbacks.+// OutputPin is the upstream direction fixture from CaptureColorContractTests.+template<class Check> void bmdAllocatorCases(Check check){+ using namespace veyra::source;+ VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);+ vi.bmiHeader.biWidth=8;vi.bmiHeader.biHeight=4;vi.bmiHeader.biBitCount=16;+ vi.bmiHeader.biSizeImage=64;vi.AvgTimePerFrame=333333;+ AM_MEDIA_TYPE type{};type.majortype=MEDIATYPE_Video;type.subtype=MEDIASUBTYPE_UYVY;+ type.subtype.Data1=MAKEFOURCC('H','D','Y','C');type.formattype=FORMAT_VideoInfo2;+ type.cbFormat=sizeof(vi);type.pbFormat=reinterpret_cast<BYTE*>(&vi);+#ifndef VEYRA_TEST_BMD_LEGACY_FACTORY+ auto other=type;VIDEOINFOHEADER2 otherInfo=vi;other.pbFormat=reinterpret_cast<BYTE*>(&otherInfo);+ check(nativeCaptureContractsMatch(type,other),"BMD exact raw contract matches equivalent declaration");+ otherInfo.dwInterlaceFlags=AMINTERLACE_IsInterlaced|AMINTERLACE_Field1First;+ check(!nativeCaptureContractsMatch(type,other),"BMD connection rejects same-size/fps interlace mismatch");otherInfo=vi;+ other.subtype=MEDIASUBTYPE_UYVY;+ check(!nativeCaptureContractsMatch(type,other),"BMD connection rejects unrequested alias subtype");+#endif+ ComPtr<IBaseFilter> filter;ComPtr<IPin> input,output;ComPtr<IMemInputPin> memory;+ output.Attach(new OutputPin);unsigned delivered=0;std::array<BYTE,64> observed{};+ const auto callback=[&](IMediaSample* sample){+ BYTE* bytes=nullptr;if(FAILED(sample->GetPointer(&bytes))||!bytes)return E_FAIL;+ std::copy_n(bytes,observed.size(),observed.begin());++delivered;return S_OK;+ };+#ifdef VEYRA_TEST_BMD_LEGACY_FACTORY+ const auto create=createNativeCaptureSink(type,callback,filter,input);+#else+ const auto create=createNativeCaptureSink(type,callback,filter,input,CaptureAllocatorMode::Upstream);+#endif+ check(create==S_OK&&SUCCEEDED(filter.As(&memory)),"BMD real terminal created");+ if(!memory)return;+ ComPtr<IAMFilterMiscFlags> flags;const auto flagsHr=filter.As(&flags);+ check(flagsHr==S_OK&&flags->GetMiscFlags()==AM_FILTER_MISC_FLAGS_IS_RENDERER,"BMD terminal advertises renderer to graph manager");+ if(flags){+ ComPtr<IUnknown> a,b,c;filter.As(&a);flags.As(&b);input.As(&c);+ check(a.Get()==b.Get()&&b.Get()==c.Get(),"BMD filter/pin/renderer share canonical COM identity");+ }+ check(memory->ReceiveCanBlock()==S_OK,"BMD callback truthfully declares possible blocking");+ for(unsigned cycle=0;cycle<2;++cycle){+ check(input->ReceiveConnection(output.Get(),&type)==S_OK,"BMD HDYC connects/reconnects with unchanged contract");+ ComPtr<IMemAllocator> offered;+ const auto offeredHr=memory->GetAllocator(&offered);+ check(offeredHr==VFW_E_NO_ALLOCATOR&&!offered,"BMD sink does not offer generic allocator to producer");+ ALLOCATOR_PROPERTIES requirements{99,99,99,99};+ check(memory->GetAllocatorRequirements(&requirements)==E_NOTIMPL,"BMD sink leaves buffer requirements to driver");+ check(memory->GetAllocator(nullptr)==E_POINTER&&memory->NotifyAllocator(nullptr,TRUE)==E_POINTER,"BMD allocator null arguments rejected");+ ComPtr<IMemAllocator> driver;+ ALLOCATOR_PROPERTIES wanted{4,64,16,32},actual{};+ const bool ready=SUCCEEDED(CoCreateInstance(CLSID_MemoryAllocator,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&driver)))&&+ SUCCEEDED(driver->SetProperties(&wanted,&actual))&&SUCCEEDED(driver->Commit());+ check(ready,"BMD fixture upstream owns real aligned allocator with prefix");+ if(ready){+ check(memory->NotifyAllocator(driver.Get(),TRUE)==S_OK,"BMD accepts producer read-only pool");+ offered.Reset();check(memory->GetAllocator(&offered)==S_OK&&offered.Get()==driver.Get(),"BMD selected allocator remains driver object for diagnostics");+ ALLOCATOR_PROPERTIES queried{};+ check(queryCaptureAllocatorProperties(input.Get(),queried)==S_OK&&queried.cBuffers==actual.cBuffers&&queried.cbBuffer==actual.cbBuffer&&queried.cbAlign==actual.cbAlign&&queried.cbPrefix==actual.cbPrefix,"BMD diagnostic properties preserve producer pool/alignment/prefix");+ ComPtr<IMediaSample> sample;const auto sampleHr=driver->GetBuffer(&sample,nullptr,nullptr,0);+ check(sampleHr==S_OK&&sample,"BMD producer sample acquired");+ if(sample){+ BYTE* bytes=nullptr;sample->GetPointer(&bytes);std::array<BYTE,64> original{};+ for(unsigned i=0;i<original.size();++i)original[i]=BYTE((i*37+cycle*19)%251);+ std::copy(original.begin(),original.end(),bytes);sample->SetActualDataLength(64);+ const auto before=delivered;+ check(memory->Receive(sample.Get())==VFW_E_WRONG_STATE&&delivered==before,"BMD stopped terminal rejects delivery");+ filter->Run(0);+ check(memory->Receive(sample.Get())==S_OK&&delivered==before+1&&observed==original&&std::equal(original.begin(),original.end(),bytes),"BMD source pixels delivered exactly and read-only sample untouched");+ input->BeginFlush();check(memory->Receive(sample.Get())==S_FALSE&&delivered==before+1,"BMD flush suppresses callback");input->EndFlush();+ sample->SetActualDataLength(63);check(memory->Receive(sample.Get())==VFW_E_BUFFER_UNDERFLOW&&delivered==before+1,"BMD short frame rejected before callback");sample->SetActualDataLength(64);+ vi.bmiHeader.biHeight=8;sample->SetMediaType(&type);+ check(memory->Receive(sample.Get())==VFW_E_INVALIDMEDIATYPE&&delivered==before+1,"BMD mode change requires reopen rather than reinterpretation");+ vi.bmiHeader.biHeight=4;sample->SetMediaType(nullptr);+ vi.dwInterlaceFlags=AMINTERLACE_IsInterlaced;sample->SetMediaType(&type);+ check(memory->Receive(sample.Get())==VFW_E_INVALIDMEDIATYPE&&delivered==before+1,"BMD dynamic interlace change cannot keep stale temporal contract");+ vi.dwInterlaceFlags=0;sample->SetMediaType(nullptr);+ const unsigned beforeResume=delivered;+ check(memory->Receive(sample.Get())==S_OK&&observed==original&&delivered==beforeResume+1,"BMD unchanged frame resumes after rejected mode");+ filter->Stop();+ check(memory->Receive(sample.Get())==VFW_E_WRONG_STATE&&delivered==beforeResume+1,"BMD Stop quiesces callback");+ }+ sample.Reset();driver->Decommit();+ }+ offered.Reset();+ check(input->Disconnect()==S_OK,"BMD disconnect drops upstream peer and allocator");+ check(memory->GetAllocator(&offered)==VFW_E_NO_ALLOCATOR&&!offered,"BMD reconnect cannot reuse previous producer allocator");+ }+ // Default factory keeps the existing UVC/audio allocator contract.+ filter.Reset();input.Reset();memory.Reset();+ check(createNativeCaptureSink(type,callback,filter,input)==S_OK&&SUCCEEDED(filter.As(&memory)),"ordinary capture factory remains available");+ ComPtr<IMemAllocator> ordinary;ALLOCATOR_PROPERTIES requirements{};+ check(memory->GetAllocator(&ordinary)==S_OK&&ordinary&&memory->GetAllocatorRequirements(&requirements)==S_OK&&requirements.cBuffers==3&&requirements.cbBuffer==64,"ordinary capture retains sink allocator and bounded requirements");+ flags.Reset();check(filter.As(&flags)==E_NOINTERFACE,"ordinary graph renderer discovery unchanged");+}diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cppindex 7d76dfd5..ab0efadc 100644--- a/tests/unit/CaptureColorContractTests.cpp+++ b/tests/unit/CaptureColorContractTests.cpp@@ -33,12 +33,14 @@ struct OutputPin final:IPin,IAMBufferNegotiation {HRESULT STDMETHODCALLTYPE EndFlush()override{return S_OK;}HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME,REFERENCE_TIME,double)override{return S_OK;}};+#include "BmdAllocatorCases.h"int main(){CoInitializeEx(nullptr,COINIT_MULTITHREADED);int failures=0;auto check=[&](bool pass,const char* name){std::cout<<(pass?"PASS ":"FAIL ")<<name<<'\n';if(!pass)++failures;};captureFormatCases(check);blackmagicTest::run(check);elgatoHdrCases(check);+ bmdAllocatorCases(check);VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=4;vi.bmiHeader.biHeight=2;vi.bmiHeader.biBitCount=16;vi.bmiHeader.biSizeImage=24;vi.AvgTimePerFrame=166667;AM_MEDIA_TYPE type{};type.majortype=MEDIATYPE_Video;type.subtype=MEDIASUBTYPE_YUY2;type.formattype=FORMAT_VideoInfo2;type.pbFormat=reinterpret_cast<BYTE*>(&vi);type.cbFormat=sizeof(vi);source::CaptureMediaLayout layout;check(source::captureMediaLayout(type,layout)&&layout.stride==12&&layout.rowBytes==8&&!layout.bottomUp,"VideoInfo2 YUY2 padded row contract");