Skip to content

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 Blackmagic DirectShow setup and HDYC capture compatibility

Veyra Goal Agent42943410d5e3
diff --git a/AGENTS.md b/AGENTS.md
index fed709c4..4f5aae10 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-07 Blackmagic采集兼容授权**:用户要求兼容日志中的 Blackmagic WDM Capture / Decklink Video Capture,并说明不能确认物理卡数。从已验VFG候选cc22e88在E盘codex/blackmagic-capture-20261007按docs/BLACKMAGIC_CAPTURE_PLAN_2026-10-07.md隔离修复必要DirectShow上游连接/HDYC格式/驱动属性页/源黑帧诊断与QML及针对性构建验收。本次具体接点覆盖历史冻结;不改其它补帧/NR算法、不碰驱动/用户配置/其他工作树。独立start和Git bundle在archives/blackmagic-capture-20261007,先执行blackmagic-control.py,不改旧guard/baseline。无子Agent、压力/竞争负载;单测试≤300秒、构建≤900秒,产物统一E盘。运行库/模型原字节且不进Git;没有新merge/push/Release/关机授权。实卡未验不能宣称已解决。
+
> **2026-10-07 VFG专项优化授权**:用户明确“尝试优化VFG,其他的补帧暂时不动”。从已封存排查aec800e在E盘codex/vfg-optimization-20261007按docs/VFG_OPTIMIZATION_PLAN_2026-10-07.md实施VFG必要提交/互操作/专属调度及定向构建验收、本地候选;这些具体接点覆盖旧冻结。DLSS/XeSS/FSR实现与策略保持,不改NR算法、用户配置、驱动或其它工作树。独立不可变start及source-before.bundle在archives/vfg-optimization-20261007,先运行vfg-opt-control.py,不改旧guard/baseline。不派Agent、无压力/竞争负载,测试≤300秒、构建≤900秒,产物全在E盘;没有新merge/push/Release/关机授权,运行库/模型原字节保留且不进源码Git。
> **2026-10-07 2.0.5 正式发布授权**:用户明确“发布吧,2.0.5 老样子发完给我弄个群公告”。按docs/PUBLISH_2.0.5_PLAN_2026-10-07.md,仅将已测2.0.5做发布文档/元数据整理,允许本轮main合并、普通推送、v2.0.5标签、正式GitHub Release与5项资产上传;本条覆盖此前本地交付的no-push/no-Release限制。产品EXE/QML/shader/运行库/模型保持;NVIDIA显存持续增长未修复,留待下一版,不实施假说。群公告只交用户、不代发,不关机。独立start基线保护28既有工作树/495修改文件/53历史证据,先运行本轮publish-2.0.5-control.py,旧guard不修改。不派Agent、无压力/竞争负载、不改用户配置/驱动,所有产物E盘,保留双二维码width220、Discord和Ko-fi。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index db27d251..c2bb7c51 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -41,6 +41,19 @@ color accuracy or official NVIDIA certification. Provenance and measurements:
## AVerMedia capture HDR-to-SDR control
+The WDM upstream crossbar helpers in `include/veyra/source/DirectShowCaptureSetup.h`
+are adapted from OBS `libdshowcapture` at the same fixed commit
+`c13d4b7b0c66979396ba0a9060c9aafc15bb7b22`: `source/device.cpp`
+(`FindCrossbar`, `ConnectPins`) and `source/dshow-base.cpp` (`GetPinMedium`,
+`GetFilterByMedium`, `DirectConnectFilters`). Copyright (C) 2023 Lain Bailey,
+LGPL-2.1-or-later; see `licenses/capture/LIBDSHOWCAPTURE_LGPL.txt`.
+Veyra adds medium bounds and direction validation, multiple-medium matching,
+existing-connection protection and HRESULT reporting. It connects the upstream
+graph edge without changing the user's physical input routing. HDYC recognition
+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 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_CAPTURE_PLAN_2026-10-07.md b/docs/BLACKMAGIC_CAPTURE_PLAN_2026-10-07.md
new file mode 100644
index 00000000..42e6d7c3
--- /dev/null
+++ b/docs/BLACKMAGIC_CAPTURE_PLAN_2026-10-07.md
@@ -0,0 +1,36 @@
+# Blackmagic / DeckLink DirectShow 黑屏兼容
+
+2026-10-07,用户要求兼容日志中的两个采集条目,并补充截图名称为 `Blackmagic WDM Capture`、`Decklink Video Capture`;用户无法确认物理卡数。两个名称是两条驱动入口,不据名称合并设备、不宣称两张卡。
+
+从已验 VFG 候选 cc22e88 在 `E:/项目/Veyra/worktrees/blackmagic-capture-20261007` 隔离施工,保留其 VFG 优化。Desktop 脏工作区及其它 31 工作树不改。独立不可变 start.json、完整 Git bundle、原始日志/截图副本分别存放 `E:/项目/Veyra/archives/blackmagic-capture-20261007`、`logs/blackmagic-capture-20261007/input`。先执行本轮 blackmagic-control.py,不修改旧 guard/baseline。构建、测试、临时、候选包统一 E 盘同任务目录。无 Agent、竞争压力、驱动/用户配置修改、merge/push/Release/关机授权。
+
+## 事实和未证实项
+
+- 用户日志来自 2.0.4 / RTX5070Ti / 驱动576.88,五次连接均有连续原始帧、增强和送显记录。ARGB32 720p50、UYVY 720×486/29.97、HDYC1080p30、v2101080p30均被尝试。
+- HDYC 被识别为未知格式,绕到系统 RGB32 转换。原生直连只连接视频输出与 Veyra sink,没有按 OBS 为 WDM 设备寻找/连接上游 crossbar。UI 无驱动属性入口,默认格式只按性能排序取第一项,不能代表实际信号制式。
+- 五次连接社区 NR 均发生 BAD00002 / SEH C0000005,现有回退继续播放;此为独立故障记录,不以更换用户运行库掩盖采集问题。
+- 收到帧/Present 返回成功不能证明像素非黑。日志没有像素统计,也没有 Blackmagic SDK 的信号状态。实际型号、HDMI/SDI、输入制式未知;不能直接断言 root cause。
+
+## 最小闭环
+
+1. 从既已登记的 obsproject/libdshowcapture 固定提交 c13d4b7b0c66979396ba0a9060c9aafc15bb7b22(LGPL2.1+)移植 WDM medium 查找与上游 crossbar 连接。对已连接 pin 不重复连接;没有 crossbar 的普通 UVC 保持直通;找到但连不上显式报错。保留硬件已设路由,绝不随意切 HDMI/SDI。
+2. HDYC 复用已有 UYVY GPU 解包并按 subtype 提供 BT709 缺省,明确元数据与用户覆盖仍优先。保留尺寸/stride/方向/颜色防错及 CPU 诊断回退。v210 保持既有系统转换,不伪称原生10bit支持。
+3. 提供设备/输入选择器的系统属性页入口,用户主动打开;采集使用中禁止争抢同一设备,提示先断开。关页后重新查询能力;优先显示驱动当前格式(仅 Blackmagic),仍保留已记住的用户选择。注明59.94与60、逐行与隔行必须匹配;不自动遍历打开所有模式。
+
+补充已发现的格式身份缺口:旧 VideoInfo2 key 没有 dwInterlaceFlags,p30/i60 和不同场序可能碰撞。新 key 保存扫描标志;旧 key 仅唯一匹配时迁移,歧义必须重选。驱动属性页的实例内 SetFormat 变更须携带精确 key,避免关页释放 filter 后丢弃用户所选模式。驱动 GetFormat 仅是配置默认,不能冒充实时信号检测。
+4. Blackmagic 输入端只对已在 CPU 的原始样本做低频有界网格统计,不能新增 GPU 回读。持续黑采样仅提示检查输入/制式,不将黑场内容等同无信号;日志区分源像素与后续呈现。
+
+## 验收和交付
+
+- 构建本轮 EXE 与既有采集颜色/格式/GPU目标;单进程测试≤300秒、构建≤900秒。
+- 检查 HDYC VideoInfo/2、padding、短样本、矩阵缺省与明确覆盖、上下翻转、native sink 交付;真实 GPU 色卡输出非黑且等同 UYVY BT709,不能只检查 exit0。
+- crossbar 合成接口覆盖 medium 匹配/方向/已有连接/失败回传和属性页缺失;原生 USB 卡回归若本机可用,真实卡与合成证据分开记录。
+- 检查 QML/驱动对话入口、黑采样提示及恢复、保存格式优先、普通卡无额外开卡/制式变更。保留其它算法/运行库原字节。
+- 交付独立本地测试候选、对应源码和简明实卡步骤。Blackmagic 真卡不在本机,不把 mock/USB/RTX 通过外推该卡已解决。
+
+## 参考
+
+- https://github.com/obsproject/libdshowcapture/tree/c13d4b7b0c66979396ba0a9060c9aafc15bb7b22/source :device.cpp FindCrossbar/ConnectPins;dshow-base.cpp medium 和直连帮助函数。
+- https://sdk-doc.blackmagicdesign.com/decklink-sdk/section1.html :Desktop Video 的 DirectShow/WDM 两类过滤器与设备配置工具。
+- https://documents.blackmagicdesign.com/UserManuals/DesktopVideoManual.pdf :物理输入/信号制式设置。
+- https://learn.microsoft.com/en-us/windows/win32/directshow/displaying-a-filters-property-pages :标准 ISpecifyPropertyPages/OleCreatePropertyFrame。
diff --git a/docs/BLACKMAGIC_CAPTURE_REPORT_2026-10-07.md b/docs/BLACKMAGIC_CAPTURE_REPORT_2026-10-07.md
new file mode 100644
index 00000000..f7bd59b2
--- /dev/null
+++ b/docs/BLACKMAGIC_CAPTURE_REPORT_2026-10-07.md
@@ -0,0 +1,53 @@
+# Blackmagic / DeckLink 采集兼容测试说明
+
+状态:本机接口、像素和普通 USB 卡回归通过;Blackmagic 实卡待测试。此包是本地候选 `2.0.5-capture-test`,保留此前已经验收的 VFG 优化。
+
+## 两个设备名称
+
+截图中的 `Blackmagic WDM Capture` 与 `Decklink Video Capture` 是两个驱动入口。它们可能来自同一张物理卡,现有日志和截图不足以确认数量,程序继续分别列出,不合并设备身份。
+
+用户原日志为 2.0.4 / RTX5070Ti / 驱动576.88,五次连接均收到连续帧并送显。收到帧不等于画面非黑,旧日志没有源像素统计。日志还包含社区 NR 初始化异常 `BAD00002 / SEH C0000005`,这是另一项故障,实卡验收应先关闭全部增强。
+
+## 本次改动
+
+- 按 OBS libdshowcapture 的成熟实现,补齐 WDM 上游输入选择器的发现与连接。使用设备 medium 的 GUID 和实例 ID 精确匹配,保留已有连接;不自动修改 HDMI/SDI 路由。找到但连接失败时显示错误并记录 HRESULT。
+- HDYC 直接进入现有 UYVY GPU 解包路径,按其格式提供 BT.709 缺省,明确颜色元数据和手动覆盖仍优先。v210 仍使用既有系统转换,此次没有增加原生 10bit v210 解包。
+- 采集面板增加“设备属性”;Blackmagic 增加“输入选择”。连接、采集中及断开尚未完成时,接口拒绝争抢设备;断开后可以配置。没有属性页的驱动给出明确提示,可用 Desktop Video Setup 配置。
+- Blackmagic 优先列出驱动当前配置,明确这不是实时信号检测;保存的用户选择仍优先。格式标明逐行/隔行,保存键包含扫描及场序标志,避免 p30/i60 碰撞。旧键仅唯一匹配时迁移,歧义要求重选。
+- Blackmagic 原始 CPU 样本每秒最多检查 32×18 个点,不增加 GPU 回读。连续三次黑采样后提示检查输入制式,像素恢复后清除提示。黑场内容也会触发此观察,不能据此断言物理无信号,也不会丢弃或改动该帧。
+
+## 实际验证
+
+最终构建 `capture-build-v4` 成功,EXE SHA256:
+`0e95e46d0419fd2dbb04e33a55e6c47ecdc6ff93dad14c51a286552f30848214`。
+
+| 检查 | 结果与边界 |
+| --- | --- |
+| 采集颜色、原生 sink、WDM medium/方向/重复连接/失败回传、黑采样 | 213 项通过,0 失败;上游接口为合成 COM 测试,不是真卡 |
+| 格式身份和旧键迁移 | 0 失败,覆盖 p/i 歧义拒绝及唯一匹配迁移 |
+| 真实 GPU 像素 | 124 个输出检查通过;HDYC 全/限范围灰阶误差为 0;带 padding 彩色图正/反向输出均与 UYVY+明确 BT.709 逐像素一致,colorSpread=1 |
+| 普通 USB 采集 | 本机 KUHAIMI 27P、1080p60 YUY2,连接和重连两段回调为 60.084 / 59.961fps,PTS 递增;无上游 crossbar、无路由修改 |
+| 产品 GUI | 连接、收帧、驱动设置在连接中/采集中被拒绝、断开后按钮恢复、旧 VideoInfo2 键重启恢复均通过 |
+| 驱动属性缺失 | 普通 USB 实际创建 COM 图,GetFormat 成功,无输入属性页时返回 E_NOINTERFACE,按钮及所选格式保持可用 |
+| 可见像素 | 产品截图完整显示采集卡内置“无信号”提示图;证明该卡的非黑像素能走到输出,不代表外部 HDMI 视频已验收 |
+
+没有 Blackmagic 实卡,没有验证其 HDMI/SDI 输入切换、特定型号的属性页、隔行画面质量或社区 NR 异常恢复。此次没有增加去隔行算法,也没有把 USB/合成测试外推为 Blackmagic 已解决。其它补帧实现、NR 模型、SDK、运行库和着色器保持原字节。
+
+首轮构建 `capture-build-v1` 失败:Windows SDK 将 IKsPin 声明置于 `__STREAMS__` 条件下,且初版引用了不存在的 HRESULT 名称。改为局部暴露 SDK 声明及真实错误常量后 v2 通过;v3 修正单场/双场样本的场率标签;最终 v4 补齐连接/断开期间的驱动争用保护。原失败日志保留,没有伪报通过。
+
+验收日志统一位于 `E:/项目/Veyra/logs/blackmagic-capture-20261007/`:`capture-build-v4.log/json`、`contracts-v4/`、`usb-rate-v4/`、`gui-v4/`、`driver-page-v4/`。实图位于 `E:/项目/Veyra/tests/blackmagic-capture-20261007/gui-v4/screenshots/`。源码与 EXE 的逐文件对应关系、完整包清单和 CRC 核对结果见同任务 `verify/` 及包内 `package-manifest.json`。
+
+## 请对方这样测试
+
+1. 解压到新目录,先关闭 madVR、OBS 等正在占用此卡的软件。启动后关闭 NR、超分、补帧和其它增强。
+2. 用 Blackmagic Desktop Video Setup 或采集面板的驱动设置,确认实际接的是 HDMI 还是 SDI。某个入口没有设置页并不等于设备不支持,可从官方配置工具设置。
+3. 选择与真实信号一致的分辨率、59.94/60、逐行/隔行。设备 FPS 先保持 0;“驱动默认”仅是配置值。驱动列出的 HDYC/UYVY 可以直接试,避免同时改动多个变量。
+4. 两个入口分别连接测试,先确认基础画面。如果没有出画,断开后再换入口或制式。不要同时打开两条接口争抢可能相同的硬件。
+5. 基础画面正常后再逐项打开增强。若仍黑屏,发本次日志及所选格式;新的 `capture-upstream` 和 `capture-source-pixels` 会区分上游连接失败、驱动原始黑采样和后续处理问题。若社区 NR 继续初始化失败,再单独排查 NR。
+
+## 来源
+
+- OBS libdshowcapture 固定提交 [c13d4b7b0c66979396ba0a9060c9aafc15bb7b22](https://github.com/obsproject/libdshowcapture/tree/c13d4b7b0c66979396ba0a9060c9aafc15bb7b22/source),LGPL-2.1-or-later;文件、函数、修改说明及许可证见 THIRD_PARTY_NOTICES.md 和新头文件。
+- [Blackmagic DeckLink SDK 概览](https://sdk-doc.blackmagicdesign.com/decklink-sdk/section1.html)、[Desktop Video 使用手册](https://documents.blackmagicdesign.com/UserManuals/DesktopVideoManual.pdf)。本次沿用 DirectShow,不宣称接入 DeckLink 原生 SDK。
+
+构建、日志、临时、测试、归档和候选包都在 E:/项目/Veyra 对应任务目录。隔离分支 `codex/blackmagic-capture-20261007`,其它工作树和正式包保留。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index aa3e5e76..0ebb4985 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-10-07 Blackmagic / DeckLink 采集黑屏兼容
+
+用户要求兼容截图中 Blackmagic WDM Capture、Decklink Video Capture 两个入口,随后确认无法判断物理卡数。按 docs/BLACKMAGIC_CAPTURE_PLAN_2026-10-07.md,从已验 VFG 候选 cc22e88 隔离到 codex/blackmagic-capture-20261007,保留 VFG 优化。开工 tag checkpoint/pre-blackmagic-capture-20261007;E:/项目/Veyra/archives/blackmagic-capture-20261007 保存完整 source-before.bundle、不可变 start.json,原日志/截图只读副本在 logs/blackmagic-capture-20261007/input。新 guard 逐文件保护其它 31 个工作树及 1346 个原始文件,不改旧 baseline/guard、桌面脏区、main、发布包、运行库、驱动或用户配置。无子 Agent、竞争 GPU 压力、merge/push/Release/关机操作。
+
+原日志为 2.0.4 / RTX5070Ti / 驱动576.88:两入口五次连接均有回调和 Present,不能据此证明非黑;社区 NR 每次 BAD00002 / SEH C0000005。代码发现 HDYC 未识别、原生直连未接 WDM 上游输入选择器、默认格式不代表输入制式、旧 VideoInfo2 格式键缺扫描/场序。按已登记 OBS libdshowcapture c13d4b7b0c66979396ba0a9060c9aafc15bb7b22 LGPL2.1+ 移植 medium/上游连接,保留路由与已连接 pin,失败显式回传。HDYC 复用现有 GPU UYVY+BT709,明确元数据/覆盖优先;增加用户主动打开的设备/输入属性页及 Blackmagic 每秒有界 CPU 黑采样诊断。v210 保持系统转换,不新增去隔行。采集连接中、运行中和断开未完成时拒绝驱动争用。只加单个 snapshot 观察字段,没有改算法/处理图/着色器。
+
+命令 python -B scripts/acceptance/blackmagic-build.py capture-build-v1 首次失败:SDK 的 IKsPin 条件声明、错误常量不存在;失败日志保留。局部声明可见性及真实错误常量修复后 capture-build-v2 exit0。capture-build-v3 修正单场样本场率标签,最终 capture-build-v4 补齐连接/断开驱动争用边界,均 exit0。最终 EXE SHA256 0e95e46d0419fd2dbb04e33a55e6c47ecdc6ff93dad14c51a286552f30848214,显示版本2.0.5-capture-test。构建目录 E:/项目/Veyra/build/blackmagic-capture-20261007,使用已接受2.0.5依赖和 patched FFmpeg,临时目录 E:/项目/Veyra/tmp/blackmagic-capture-20261007/build;日志同任务 logs/ 下 build-v1至v4,不覆盖失败。
+
+python -B scripts/acceptance/blackmagic-tests.py contracts-v4:采集颜色/native sink/合成 COM 213项0失败,格式选择0失败,真实 GPU 124输出检查通过;HDYC 正/反向带 padding 彩图与明确 BT709 UYVY逐像素相同,灰阶全/限范围error=0;设备只读枚举通过。此前 contracts-v2 也通过,最终交付按 v4证据。python -B scripts/acceptance/blackmagic-field-tests.py prepare prepare-v4 验证正式包全部哈希后独立复制候选,无可写硬链接。rate usb-rate-v4 实卡 KUHAIMI27P/1080p60 YUY2 连接及重连14.281秒,通过60.084/59.961fps回调与单调PTS,inputMediums=0/crossbar=false/routeChanged=0。ui gui-v4 两进程11.766/4.172秒通过产品连接/断开、连接中和采集中禁开驱动设置、收帧状态、重启旧键迁移;显式截图显示采集卡内置无信号提示图,不能算外部HDMI信号验收。properties driver-page-v4 4.172秒通过真实 COM 图创建/GetFormat及无属性页E_NOINTERFACE回退,查询状态不悬挂。所有 GPU 测试串行,每进程≤300秒;使用私有E盘profile,候选 Main.qml 注入后恢复原字节。
+
+详细报告 docs/BLACKMAGIC_CAPTURE_REPORT_2026-10-07.md。本机无 Blackmagic 实卡,不宣称其已出画或型号认证,不宣称社区 NR 异常解决。源像素采样是黑场观察,不是物理信号检测;基本画面验证后才逐项开增强。legacy-only scripts/gates/delivery.ps1 不适用于当前 QML 入口,本轮执行针对性产品GUI、像素和采集回归。对应源码、便携候选、逐文件清单及最终保护核验由 blackmagic-finalize.py 生成在 E:/项目/Veyra/test-packages/blackmagic-capture-20261007 和 verify/blackmagic-capture-20261007;不更新正式版本或 README 发布内容。
+
## 2026-10-07 VFG 专项优化
用户授权“尝试优化VFG,其他的补帧暂时不动”。排查分支封存aec800e,优化隔离codex/vfg-optimization-20261007;开工tag checkpoint/pre-vfg-optimization-20261007,完整Git bundle与不可变start.json在E:/项目/Veyra/archives/vfg-optimization-20261007。当前任务计划docs/VFG_OPTIMIZATION_PLAN_2026-10-07.md;新guard逐文件保护其它全部工作树、正式2.0.5 EXE/Main/VFG运行库及非VFG实现,未改旧guard/start。所有构建、测试、日志、临时目录使用E:/项目/Veyra对应vfg-optimization-20261007目录;无子Agent、竞争GPU压力、驱动/用户配置变更、merge/push/Release/关机。
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index df742b37..69eea557 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -100,6 +100,7 @@ struct PlayerSnapshot {
uint64_t captureReceived=0,captureDropped=0,nrEvaluated=0,nvofExecuted=0;
uint64_t captureRateSkipped=0,processedCompleted=0;
bool captureHalfRate=false;
+ bool captureSampledBlack=false; // Sparse CPU-source samples, not no-signal detection.
bool captureRecovering=false;unsigned captureReconnectAttempts=0;
double captureFps=0,captureReadAgeMs=0,captureAgeMs=0,captureAgeP95Ms=0;
double schedulingWaitP95Ms=0,processCpuP95Ms=0,presentCpuP95Ms=0;
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 74ff6856..3ec07b32 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -24,6 +24,7 @@ constexpr int kCaptureAudioWasapi=-3; // capture2 only; requires explicit endpoi
struct CaptureMetrics {
uint64_t received=0, delivered=0, dropped=0;
double callbackFps=0, readAgeMs=0, frameAgeMs=0;
+ bool sampledBlack=false; // Sparse source pixels, not input signal detection.
};
class CaptureCardSource final:public IFrameSource {
public:
@@ -34,6 +35,8 @@ public:
int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride=0,double requestedFps=0,std::wstring_view formatKey={});
static std::vector<CaptureFormat> formats(unsigned device);
static std::vector<CaptureFormat> formatsByPath(std::wstring_view devicePath);
+ // Explicit user action on the UI COM apartment; no Run or auto-routing.
+ static bool showDeviceProperties(std::wstring_view devicePath,uintptr_t owner,bool inputSelector,std::wstring& error,std::wstring* changedFormatKey=nullptr);
bool open(const SourceOpenDesc&)override;
// Negotiate/allocate before GPU initialization, but do not queue frames
// or start audio until the presenter and enhancement graph are ready.
diff --git a/include/veyra/source/CaptureFormatSelection.h b/include/veyra/source/CaptureFormatSelection.h
index 5ef4cc43..3b7ccf70 100644
--- a/include/veyra/source/CaptureFormatSelection.h
+++ b/include/veyra/source/CaptureFormatSelection.h
@@ -4,11 +4,21 @@
#include <span>
namespace veyra::source {
-struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;std::wstring key;int rank=0;int tier=0;};
+struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;std::wstring key;int rank=0;int tier=0;bool driverCurrent=false;};
inline const CaptureFormat* selectCaptureFormat(std::span<const CaptureFormat> formats,int legacyIndex,std::wstring_view key){
for(const auto& format:formats)
if(key.empty()?format.index==legacyIndex:format.key==key)return &format;
+ // Old VideoInfo2 keys omitted interlace/field-order flags. A single match
+ // is safe to migrate; p30/i60 or top/bottom-field ambiguity requires the
+ // user to choose explicitly. Never guess a mode from driver list order.
+ if(!key.empty()&&key.find(L":scan=")==key.npos){
+ const CaptureFormat* match=nullptr;const std::wstring prefix=std::wstring(key)+L":scan=";
+ for(const auto& format:formats)if(format.key.starts_with(prefix)){
+ if(match)return nullptr;match=&format;
+ }
+ return match;
+ }
return nullptr;
}
diff --git a/include/veyra/source/CaptureMediaType.h b/include/veyra/source/CaptureMediaType.h
index c6ceb421..18b30389 100644
--- a/include/veyra/source/CaptureMediaType.h
+++ b/include/veyra/source/CaptureMediaType.h
@@ -31,6 +31,23 @@ inline BITMAPINFOHEADER* captureBitmapHeader(AM_MEDIA_TYPE& type){
if(type.formattype==FORMAT_VideoInfo2&&type.cbFormat>=sizeof(VIDEOINFOHEADER2))return &reinterpret_cast<VIDEOINFOHEADER2*>(type.pbFormat)->bmiHeader;
return nullptr;
}
+inline std::wstring captureFormatIdentity(const AM_MEDIA_TYPE& type){
+ if(!type.pbFormat)return {};
+ const BITMAPINFOHEADER* bitmap=nullptr;REFERENCE_TIME duration=0;
+ if(type.formattype==FORMAT_VideoInfo&&type.cbFormat>=sizeof(VIDEOINFOHEADER)){
+ const auto& v=*reinterpret_cast<const VIDEOINFOHEADER*>(type.pbFormat);bitmap=&v.bmiHeader;duration=v.AvgTimePerFrame;
+ }else if(type.formattype==FORMAT_VideoInfo2&&type.cbFormat>=sizeof(VIDEOINFOHEADER2)){
+ const auto& v=*reinterpret_cast<const VIDEOINFOHEADER2*>(type.pbFormat);bitmap=&v.bmiHeader;duration=v.AvgTimePerFrame;
+ }
+ if(!bitmap)return {};
+ wchar_t subtype[40]{},formatType[40]{};StringFromGUID2(type.subtype,subtype,40);StringFromGUID2(type.formattype,formatType,40);
+ auto key=std::format(L"{}:{}:{}:{}:{}:{}:{}",bitmap->biWidth,bitmap->biHeight,duration,subtype,formatType,bitmap->biBitCount,bitmap->biCompression);
+ // 1080p30 and 1080i60 can otherwise have identical identities. Retain all
+ // interlace flags, including field order, rather than silently selecting
+ // the first same-size/rate entry. Legacy keys migrate only if unambiguous.
+ if(type.formattype==FORMAT_VideoInfo2)key+=std::format(L":scan={}",reinterpret_cast<const VIDEOINFOHEADER2*>(type.pbFormat)->dwInterlaceFlags);
+ return key;
+}
// RGB DIB packings are the only ones whose biHeight sign describes storage
// order; YUV formats are always top-down (see captureMediaLayout).
constexpr bool captureIsRgbDib(CapturePacking packing){
@@ -93,6 +110,12 @@ inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out
if(out.sampleBytes>size_t(std::numeric_limits<LONG>::max()))return false;
AVFrame frame{};frame.format=out.format;frame.width=int(out.width);frame.height=int(out.height);
out.color=pipeline::resolveFrameColor(frame);
+ // HDYC is UYVY with BT.709, even at SD sizes. Explicit VideoInfo2 tags
+ // below, and the user's color override, retain precedence.
+ if(captureIsFourcc(type.subtype,captureFourcc('H','D','Y','C'))){
+ out.color.matrix=pipeline::YuvMatrix::BT709;out.color.matrixAssumed=false;
+ out.color.primaries=pipeline::ColorPrimaries::BT709;out.color.primariesAssumed=false;
+ }
// SDR capture is already display-referred R'G'B' after the YUV matrix.
// Preserve those code values through the sRGB working round trip, like
// the old RGB ingress, instead of applying a camera OETF a second time.
diff --git a/include/veyra/source/CapturePixelFormat.h b/include/veyra/source/CapturePixelFormat.h
index 793bbaa6..e0f300ca 100644
--- a/include/veyra/source/CapturePixelFormat.h
+++ b/include/veyra/source/CapturePixelFormat.h
@@ -20,6 +20,7 @@ inline CapturePacking capturePacking(const GUID& id){
struct Entry{DWORD code;CapturePacking packing;};
static constexpr Entry entries[]={
{captureFourcc('Y','U','Y','2'),CapturePacking::Yuy2},{captureFourcc('U','Y','V','Y'),CapturePacking::Uyvy},
+ {captureFourcc('H','D','Y','C'),CapturePacking::Uyvy},
{captureFourcc('Y','V','Y','U'),CapturePacking::Yvyu},{captureFourcc('N','V','1','2'),CapturePacking::Nv12},
{captureFourcc('N','V','2','1'),CapturePacking::Nv21},{captureFourcc('I','4','2','0'),CapturePacking::I420},
{captureFourcc('I','Y','U','V'),CapturePacking::I420},{captureFourcc('Y','V','1','2'),CapturePacking::Yv12},
diff --git a/include/veyra/source/CaptureSignalProbe.h b/include/veyra/source/CaptureSignalProbe.h
new file mode 100644
index 00000000..bb6bc233
--- /dev/null
+++ b/include/veyra/source/CaptureSignalProbe.h
@@ -0,0 +1,43 @@
+#pragma once
+#include "veyra/source/CaptureMediaType.h"
+#include <string_view>
+#include <cwctype>
+#include <algorithm>
+
+namespace veyra::source {
+inline bool isBlackmagicCaptureDevice(std::wstring_view name,std::wstring_view path={}){
+ const auto contains=[](std::wstring_view value,std::wstring_view needle){
+ return std::search(value.begin(),value.end(),needle.begin(),needle.end(),[](wchar_t a,wchar_t b){return towlower(a)==b;})!=value.end();
+ };
+ return contains(name,L"blackmagic")||contains(name,L"decklink")||contains(path,L"decklink#");
+}
+struct CaptureSignalSample {bool known=false,blackLike=false;unsigned points=0,minimum=255,maximum=0,chromaDeviation=0;double mean=0;};
+// Diagnostic only: <=32x18 points from the existing CPU sample, no readback.
+// Black content is NOT evidence of absent input; never alter/reject it.
+inline CaptureSignalSample sampleCaptureSignal(const CaptureMediaLayout& l,const uint8_t* data,size_t bytes){
+ CaptureSignalSample s;if(!data||bytes<l.sampleBytes||!l.width||!l.height)return s;
+ const bool rgb=l.packing==CapturePacking::Bgr32||l.packing==CapturePacking::Bgra32;
+ const bool uy=l.packing==CapturePacking::Uyvy,yuy=l.packing==CapturePacking::Yuy2,yvy=l.packing==CapturePacking::Yvyu;
+ if(!rgb&&!uy&&!yuy&&!yvy)return s;
+ const unsigned nx=std::min(32u,l.width),ny=std::min(18u,l.height);uint64_t sum=0;
+ for(unsigned gy=0;gy<ny;++gy){
+ const unsigned y=ny==1?0:gy*(l.height-1)/(ny-1);const auto* row=data+size_t(y)*l.stride;
+ for(unsigned gx=0;gx<nx;++gx){
+ const unsigned x=nx==1?0:gx*(l.width-1)/(nx-1);unsigned value;
+ if(rgb){const auto* p=row+x*4;value=std::max({unsigned(p[0]),unsigned(p[1]),unsigned(p[2])});}
+ else{const auto* p=row+(x&~1u)*2;value=p[uy?(x%2?3:1):(x%2?2:0)];
+ const unsigned u=uy?0:yvy?3:1,v=uy?2:yvy?1:3;
+ s.chromaDeviation=std::max({s.chromaDeviation,unsigned(std::abs(int(p[u])-128)),unsigned(std::abs(int(p[v])-128))});}
+ s.minimum=std::min(s.minimum,value);s.maximum=std::max(s.maximum,value);sum+=value;++s.points;
+ }
+ }
+ s.known=s.points>0;s.mean=s.points?double(sum)/s.points:0;
+ const unsigned black=rgb||l.color.range==pipeline::ColorRange::Full?0:16;
+ s.blackLike=s.known&&s.maximum<=black+2&&(rgb||s.chromaDeviation<=2);return s;
+}
+struct CaptureSignalProbeState {
+ uint64_t samples=0;unsigned blackStreak=0;CaptureSignalSample latest;
+ void observe(const CaptureSignalSample& sample){latest=sample;++samples;if(!sample.known){blackStreak=0;return;}blackStreak=sample.blackLike?std::min(blackStreak+1,3600u):0;}
+ bool persistentBlack()const{return latest.known&&blackStreak>=3;}
+};
+}
diff --git a/include/veyra/source/DirectShowCaptureSetup.h b/include/veyra/source/DirectShowCaptureSetup.h
new file mode 100644
index 00000000..ab51adc5
--- /dev/null
+++ b/include/veyra/source/DirectShowCaptureSetup.h
@@ -0,0 +1,141 @@
+#pragma once
+// WDM crossbar discovery/connection adapted from OBS libdshowcapture:
+// c13d4b7b0c66979396ba0a9060c9aafc15bb7b22, source/device.cpp
+// (FindCrossbar, ConnectPins), source/dshow-base.cpp (GetPinMedium,
+// GetFilterByMedium, DirectConnectFilters). Copyright (C) 2023 Lain Bailey.
+// LGPL-2.1-or-later; licenses/capture/LIBDSHOWCAPTURE_LGPL.txt.
+// Veyra: all valid mediums, bounds/direction checks, exact matching pins,
+// no duplicate/self connections, HRESULT propagation; never Route.
+#include <windows.h>
+#include <dshow.h>
+#include <ks.h>
+#include <ksmedia.h>
+// Windows gates IKsPin's public COM declaration behind the DirectShow
+// base-class marker. Only expose the declarations; no base-class SDK/library.
+#ifndef __STREAMS__
+#define __STREAMS__
+#define VEYRA_CAPTURE_UNDEF_STREAMS
+#endif
+#include <ksproxy.h>
+#ifdef VEYRA_CAPTURE_UNDEF_STREAMS
+#undef __STREAMS__
+#undef VEYRA_CAPTURE_UNDEF_STREAMS
+#endif
+#include <ocidl.h>
+#include <olectl.h>
+#include <wrl/client.h>
+#include <vector>
+#include <algorithm>
+
+namespace veyra::source::dshow {
+using Microsoft::WRL::ComPtr;
+inline bool sameMedium(const REGPINMEDIUM& a,const REGPINMEDIUM& b){
+ return a.clsMedium==b.clsMedium&&a.dw1==b.dw1&&a.dw2==b.dw2;
+}
+inline std::vector<REGPINMEDIUM> captureMediums(const KSMULTIPLE_ITEM* items){
+ std::vector<REGPINMEDIUM> out;
+ if(!items||items->Size<sizeof(KSMULTIPLE_ITEM)||items->Count>256||
+ items->Count>(items->Size-sizeof(KSMULTIPLE_ITEM))/sizeof(REGPINMEDIUM))return out;
+ const auto* media=reinterpret_cast<const REGPINMEDIUM*>(items+1);
+ for(ULONG i=0;i<items->Count;++i)if(media[i].clsMedium!=GUID_NULL&&media[i].clsMedium!=KSMEDIUMSETID_Standard)
+ out.push_back(media[i]);
+ return out;
+}
+inline std::vector<REGPINMEDIUM> pinMediums(IPin* pin){
+ ComPtr<IKsPin> ks;KSMULTIPLE_ITEM* items=nullptr;
+ if(!pin||FAILED(pin->QueryInterface(IID_PPV_ARGS(&ks))))return {};
+ const HRESULT hr=ks->KsQueryMediums(&items);
+ auto out=SUCCEEDED(hr)?captureMediums(items):std::vector<REGPINMEDIUM>{};
+ CoTaskMemFree(items);return out;
+}
+inline std::vector<ComPtr<IPin>> pins(IBaseFilter* filter,PIN_DIRECTION wanted){
+ std::vector<ComPtr<IPin>> out;ComPtr<IEnumPins> en;
+ if(!filter||FAILED(filter->EnumPins(&en)))return out;
+ for(;;){ComPtr<IPin> pin;PIN_DIRECTION direction{};
+ if(en->Next(1,&pin,nullptr)!=S_OK)break;
+ if(SUCCEEDED(pin->QueryDirection(&direction))&&direction==wanted)out.push_back(pin);
+ }return out;
+}
+inline bool connected(IPin* pin){ComPtr<IPin> peer;return pin&&SUCCEEDED(pin->ConnectedTo(&peer))&&peer;}
+inline bool sameObject(IUnknown* a,IUnknown* b){
+ ComPtr<IUnknown> x,y;return a&&b&&SUCCEEDED(a->QueryInterface(IID_PPV_ARGS(&x)))&&
+ SUCCEEDED(b->QueryInterface(IID_PPV_ARGS(&y)))&&x.Get()==y.Get();
+}
+// Connect the graph edge, not IAMCrossbar::Route: the user's physical input
+// selection belongs to the driver and is retained.
+inline HRESULT connectUpstream(IFilterGraph* graph,IBaseFilter* upstream,IBaseFilter* device){
+ if(!graph||!upstream||!device)return E_POINTER;
+ if(sameObject(upstream,device))return S_FALSE;
+ HRESULT last=S_FALSE;
+ for(auto& input:pins(device,PINDIR_INPUT)){
+ if(connected(input.Get()))continue;
+ last=VFW_E_CANNOT_CONNECT;
+ const auto wanted=pinMediums(input.Get());
+ for(auto& output:pins(upstream,PINDIR_OUTPUT)){
+ if(connected(output.Get()))continue;
+ const auto offered=pinMediums(output.Get());
+ if(!wanted.empty()&&!offered.empty()&&!std::any_of(wanted.begin(),wanted.end(),[&](const auto& a){
+ return std::any_of(offered.begin(),offered.end(),[&](const auto& b){return sameMedium(a,b);});}))continue;
+ last=graph->ConnectDirect(output.Get(),input.Get(),nullptr);
+ if(SUCCEEDED(last))return S_OK;
+ }
+ }return last;
+}
+struct CrossbarSetup {HRESULT hr=S_FALSE;ComPtr<IBaseFilter> filter;unsigned inputMediums=0;bool existing=false;};
+inline CrossbarSetup connectCaptureCrossbar(IGraphBuilder* graph,ICaptureGraphBuilder2* builder,IBaseFilter* device){
+ CrossbarSetup result;if(!graph||!builder||!device){result.hr=E_POINTER;return result;}
+ std::vector<REGPINMEDIUM> wanted;
+ for(auto& input:pins(device,PINDIR_INPUT)){
+ ComPtr<IPin> peer;
+ if(SUCCEEDED(input->ConnectedTo(&peer))&&peer){
+ PIN_INFO info{};
+ if(SUCCEEDED(peer->QueryPinInfo(&info))&&info.pFilter){
+ ComPtr<IBaseFilter> filter;filter.Attach(info.pFilter);ComPtr<IAMCrossbar> crossbar;
+ if(SUCCEEDED(filter.As(&crossbar))){result.filter=filter;result.existing=true;result.hr=S_OK;return result;}
+ }continue;
+ }
+ auto media=pinMediums(input.Get());wanted.insert(wanted.end(),media.begin(),media.end());
+ }
+ result.inputMediums=unsigned(wanted.size());
+ // No input medium means an ordinary source such as UVC. Avoid opening
+ // unrelated hardware just to search for a crossbar.
+ if(wanted.empty())return result;
+ ComPtr<IAMCrossbar> crossbar;ComPtr<IBaseFilter> upstream;
+ if(SUCCEEDED(builder->FindInterface(nullptr,nullptr,device,IID_PPV_ARGS(&crossbar)))&&
+ SUCCEEDED(crossbar.As(&upstream))){
+ result.filter=upstream;
+ if(!sameObject(upstream.Get(),device)){
+ FILTER_INFO info{};result.hr=upstream->QueryFilterInfo(&info);
+ if(FAILED(result.hr))return result;
+ ComPtr<IFilterGraph> owner;owner.Attach(info.pGraph);
+ if(owner&&!sameObject(owner.Get(),graph)){result.hr=VFW_E_NOT_IN_GRAPH;return result;}
+ if(!owner){result.hr=graph->AddFilter(upstream.Get(),L"Capture input selector");if(FAILED(result.hr))return result;}
+ }
+ result.hr=connectUpstream(graph,upstream.Get(),device);return result;
+ }
+ ComPtr<ICreateDevEnum> devices;ComPtr<IEnumMoniker> en;
+ result.hr=CoCreateInstance(CLSID_SystemDeviceEnum,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&devices));
+ if(FAILED(result.hr))return result;
+ const HRESULT enumHr=devices->CreateClassEnumerator(AM_KSCATEGORY_CROSSBAR,&en,0);
+ if(enumHr!=S_OK){result.hr=FAILED(enumHr)?enumHr:S_FALSE;return result;}
+ for(;;){ComPtr<IMoniker> moniker;if(en->Next(1,&moniker,nullptr)!=S_OK)break;
+ ComPtr<IBaseFilter> candidate;if(FAILED(moniker->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&candidate))))continue;
+ bool match=false;
+ for(auto& pin:pins(candidate.Get(),PINDIR_OUTPUT))for(const auto& medium:pinMediums(pin.Get()))
+ match|=std::any_of(wanted.begin(),wanted.end(),[&](const auto& m){return sameMedium(m,medium);});
+ if(!match)continue;
+ result.filter=candidate;result.hr=graph->AddFilter(candidate.Get(),L"Capture input selector");
+ if(SUCCEEDED(result.hr))result.hr=connectUpstream(graph,candidate.Get(),device);
+ return result;
+ }
+ result.hr=S_FALSE;return result;
+}
+inline HRESULT showPropertyPages(IUnknown* object,HWND owner,const wchar_t* title){
+ if(!object)return E_POINTER;
+ ComPtr<ISpecifyPropertyPages> pages;HRESULT hr=object->QueryInterface(IID_PPV_ARGS(&pages));
+ if(FAILED(hr))return hr;
+ CAUUID ids{};hr=pages->GetPages(&ids);
+ if(SUCCEEDED(hr))hr=ids.cElems&&ids.pElems?OleCreatePropertyFrame(owner,0,0,title,1,&object,ids.cElems,ids.pElems,0,0,nullptr):E_NOINTERFACE;
+ CoTaskMemFree(ids.pElems);return hr;
+}
+}
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 6c7324db..0f029e3f 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -109,6 +109,7 @@ class QmlPlayerBridge : public QObject {
Q_PROPERTY(QVariantList captureDevices READ captureDevices NOTIFY captureChanged)
Q_PROPERTY(QString captureDeviceId READ captureDeviceId WRITE setCaptureDeviceId NOTIFY captureChanged)
Q_PROPERTY(QString captureDeviceLabel READ captureDeviceLabel NOTIFY captureChanged)
+ Q_PROPERTY(bool captureBlackmagicDevice READ captureBlackmagicDevice NOTIFY captureChanged)
Q_PROPERTY(bool captureForceSdr READ captureForceSdr WRITE setCaptureForceSdr NOTIFY settingsChanged)
Q_PROPERTY(bool amdNrGpu READ amdNrGpu CONSTANT)
Q_PROPERTY(QVariantMap effectCapabilities READ effectCapabilities NOTIFY effectCapabilitiesChanged)
@@ -544,6 +545,7 @@ public:
QString captureDeviceId() const;
void setCaptureDeviceId(const QString& value);
QString captureDeviceLabel() const;
+ bool captureBlackmagicDevice() const;
bool captureForceSdr() const;
bool captureMagewellDevice() const;
QString captureMagewellStatus() const;
@@ -573,6 +575,7 @@ public:
// private to QML ("is not a function").
Q_INVOKABLE void refreshCaptureTargets();
Q_INVOKABLE void refreshCaptureDevices();
+ Q_INVOKABLE bool openCaptureDriverSettings(bool inputSelector = false);
Q_INVOKABLE bool startCaptureSession();
Q_INVOKABLE bool setScreenOption(const QString& key, const QVariant& value);
Q_INVOKABLE bool startScreenCapture();
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index da73f6e3..1cc8ee6c 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -224,10 +224,11 @@ Item {
dialogWidth: 660
foot: qsTr("关闭其他占用同一采集卡的软件")
actions: [
- { label: qsTr("取消") },
+ { label: captureDialog.live ? qsTr("断开") : qsTr("取消") },
{ label: qsTr("连接并开始"), primary: true, icon: "play" }
]
onActionTriggered: label => {
+ if (label === qsTr("断开")) { veyra.stopPlayback(); return }
if (label !== qsTr("连接并开始")) { host.close(); return }
if (veyra.startCaptureSession()) { host.close(); host.startCapture() }
}
@@ -338,6 +339,31 @@ Item {
onPicked: id => veyra.captureFormatKey = id
}
}
+ VRow {
+ objectName: "capture-driver-settings-row"
+ visible: veyra.captureDeviceId.length > 0
+ label: qsTr("驱动设置")
+ hint: captureDialog.live ? qsTr("先断开采集,再配置驱动")
+ : veyra.captureBlackmagicDevice
+ ? qsTr("Blackmagic 两个条目可能属于同一张卡。确认 HDMI/SDI 输入口,格式须匹配信号的分辨率、59.94/60 和逐行/隔行;驱动默认格式不是自动检测。")
+ : qsTr("配置驱动公开的输入与视频属性;其他采集应用占用设备时请先关闭")
+ RowLayout {
+ spacing: 6
+ VButton {
+ objectName: "capture-driver-properties"
+ text: qsTr("设备属性"); ghost: true
+ enabled: !veyra.captureQueryBusy && !captureDialog.live && !veyra.liveOpeningText.length
+ onClicked: veyra.openCaptureDriverSettings(false)
+ }
+ VButton {
+ objectName: "capture-driver-input"
+ visible: veyra.captureBlackmagicDevice
+ text: qsTr("输入选择"); ghost: true
+ enabled: !veyra.captureQueryBusy && !captureDialog.live && !veyra.liveOpeningText.length
+ onClicked: veyra.openCaptureDriverSettings(true)
+ }
+ }
+ }
VRow {
objectName: "capture-magewell-row"
label: qsTr("美乐威低延迟模式")
diff --git a/scripts/acceptance/blackmagic-build.py b/scripts/acceptance/blackmagic-build.py
new file mode 100644
index 00000000..3a9317ab
--- /dev/null
+++ b/scripts/acceptance/blackmagic-build.py
@@ -0,0 +1,28 @@
+"""Isolated capture build, using unchanged accepted 2.0.5 dependencies."""
+from pathlib import Path
+import hashlib,json,os,subprocess,sys,time
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-capture-20261007'
+label=sys.argv[1];assert label.replace('-','').isalnum()
+BUILD=BASE/'build'/TASK;TMP=BASE/'tmp'/TASK/'build';LOG=BASE/'logs'/TASK/(label+'.log')
+for p in (BUILD,TMP,LOG.parent):p.mkdir(parents=True,exist_ok=True)
+guard=[sys.executable,'-B',str(ROOT/'scripts/acceptance/blackmagic-control.py')];subprocess.run(guard,check=True)
+cache=BASE/'build/release-2.0.5-20261007/standard/CMakeCache.txt';settings=[]
+for line in cache.read_text(encoding='utf8').splitlines():
+ if ':' not in line or '=' not in line or line.startswith(('#','//')):continue
+ keytype,value=line.split('=',1);key,kind=keytype.split(':',1)
+ if kind in ('INTERNAL','STATIC') or key in ('VEYRA_DISPLAY_VERSION','VEYRA_AMD_NR_TEST_GRAPH_SOURCE'):continue
+ if key.startswith('VEYRA_') or key in ('CMAKE_PREFIX_PATH','CMAKE_MAKE_PROGRAM','PROTOC','PKG_CONFIG_EXECUTABLE'):
+ settings.append(f'set({key} [[{value}]] CACHE {kind} "Accepted dependencies" FORCE)')
+settings.append('set(VEYRA_DISPLAY_VERSION [[2.0.5-capture-test]] CACHE STRING "Local capture compatibility" FORCE)')
+(TMP/'dependencies.cmake').write_text('\n'.join(settings),encoding='utf8')
+targets=sys.argv[2:] or ['veyra_qml_ui','veyra_capture_color_tests','veyra_capture_format_selection_tests','veyra_capture_tests','veyra_hdr_color_tests']
+assert all(t.replace('_','').isalnum() for t in targets)
+cmd=TMP/'build.cmd';cmd.write_text('@echo off\nchcp 65001 >nul\ncall "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat" >nul 2>&1\nif errorlevel 1 exit /b 4\n"%TASK_CMAKE%" --preset x64-release -S "%TASK_ROOT%" -B "%TASK_BUILD%" -C "%TASK_TMP%\\dependencies.cmake"\nif errorlevel 1 exit /b 5\n"%TASK_CMAKE%" --build "%TASK_BUILD%" --parallel 6 --target '+' '.join(targets)+'\nexit /b %errorlevel%\n',encoding='ascii')
+env=os.environ.copy();env.update(TEMP=str(TMP),TMP=str(TMP),VSLANG='1033',TASK_ROOT=str(ROOT),TASK_BUILD=str(BUILD),TASK_TMP=str(TMP),TASK_CMAKE='C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe')
+source={str(p.relative_to(ROOT)).replace('\\','/'):hashlib.sha256(p.read_bytes()).hexdigest() for folder in ('src','include','shaders','qml','tests') for p in (ROOT/folder).rglob('*') if p.is_file()}
+start=time.monotonic()
+with LOG.open('x',encoding='utf8') as stream:
+ try:rc=subprocess.run(['cmd.exe','/d','/c',str(cmd)],cwd=ROOT,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=890).returncode
+ except subprocess.TimeoutExpired:rc=124
+LOG.with_suffix('.json').write_text(json.dumps({'exit':rc,'seconds':time.monotonic()-start,'targets':targets,'sourceHead':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,encoding='ascii').strip(),'sourceFiles':source,'dependencyCacheSha256':hashlib.sha256(cache.read_bytes()).hexdigest()},indent=2),encoding='utf8')
+print('BUILD',rc,LOG);print('\n'.join(LOG.read_text(encoding='utf8',errors='replace').splitlines()[-14:]));subprocess.run(guard,check=True);raise SystemExit(rc)
diff --git a/scripts/acceptance/blackmagic-control.py b/scripts/acceptance/blackmagic-control.py
new file mode 100644
index 00000000..dd18914f
--- /dev/null
+++ b/scripts/acceptance/blackmagic-control.py
@@ -0,0 +1,36 @@
+"""Preserve all other worktrees and existing packages during capture compatibility work."""
+from pathlib import Path
+import hashlib,json,subprocess
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-capture-20261007'
+START=BASE/'archives'/TASK/'start.json'
+ALLOWED={'AGENTS.md','docs/WORKLOG.md','THIRD_PARTY_NOTICES.md',
+ 'src/source/CaptureCardSource.cpp','include/veyra/source/CaptureCardSource.h',
+ 'include/veyra/source/CapturePixelFormat.h','include/veyra/source/CaptureMediaType.h',
+ 'include/veyra/source/CaptureFormatSelection.h','src/ui/QmlPlayerBridge.cpp','include/veyra/ui/QmlPlayerBridge.h',
+ 'qml/Veyra/DialogHost.qml','src/engine/EngineController.cpp','include/veyra/engine/EngineController.h',
+ 'tests/unit/CaptureColorContractTests.cpp','tests/unit/CaptureFormatCases.h','tests/unit/CaptureFormatSelectionTests.cpp',
+ 'tests/integration/CaptureFormatGpuCases.h'}
+def sha(p):
+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
+def git(*args,cwd=ROOT):return subprocess.check_output(['git',*args],cwd=cwd)
+def others():
+ out=[]
+ for line in git('worktree','list','--porcelain').decode('utf8').splitlines():
+ if not line.startswith('worktree '):continue
+ p=Path(line[9:])
+ if p.resolve()==ROOT.resolve():continue
+ names=set(git('ls-files','-m','-o','--exclude-standard','-z',cwd=p).decode('utf8').split('\0'))-{''}
+ out.append({'path':str(p),'head':git('rev-parse','HEAD',cwd=p).decode().strip(),
+ 'statusHex':git('status','--porcelain=v1','-z','--untracked-files=all',cwd=p).hex(),
+ 'changed':{n:sha(p/n) if (p/n).is_file() else None for n in sorted(names)}})
+ return out
+def allowed(n):return n in ALLOWED or n.startswith(('docs/BLACKMAGIC_CAPTURE_','scripts/acceptance/blackmagic-','include/veyra/source/DirectShowCaptureSetup','include/veyra/source/CaptureSignalProbe','tests/unit/BlackmagicCaptureCases'))
+start=json.loads(START.read_text(encoding='utf8'))
+assert sha(START)=='6303b4856c05cf6765dfb6ccc8a5f41e02f263c0062e72cb6a34e6394ae40596','Immutable baseline changed'
+changed=[n for n,d in start['files'].items() if not (ROOT/n).is_file() or sha(ROOT/n)!=d]
+current=set(git('ls-files','-c','-o','--exclude-standard','-z').decode('utf8').split('\0'))-{''}
+changed+=sorted(current-set(start['files']))
+assert all(allowed(n) for n in changed),[n for n in changed if not allowed(n)]
+assert others()==start['otherWorktrees'],'Another worktree changed; preserve and investigate'
+for n,d in start['immutable'].items():assert sha(Path(n))==d,n
+print('Capture guard passed:',len(set(changed)),'scope files;',len(start['otherWorktrees']),'other worktrees preserved;',len(start['immutable']),'immutable files intact')
diff --git a/scripts/acceptance/blackmagic-field-tests.py b/scripts/acceptance/blackmagic-field-tests.py
new file mode 100644
index 00000000..ad21b64a
--- /dev/null
+++ b/scripts/acceptance/blackmagic-field-tests.py
@@ -0,0 +1,67 @@
+"""Local USB and production GUI regressions; this does not validate Blackmagic hardware."""
+from pathlib import Path
+import hashlib,json,os,re,shutil,subprocess,sys,time,psutil
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-capture-20261007'
+APP=BASE/'test-packages'/TASK/'Veyra-2.0.5-capture-test-NVIDIA-win64-portable'
+PACKAGE=BASE/'releases/publish-2.0.5-20261007/packages/Veyra-2.0.5-NVIDIA-win64-portable'
+BUILD=BASE/'build'/TASK
+mode,label=sys.argv[1:3];assert mode in ('prepare','rate','ui','properties') and label.replace('-','').isalnum()
+def sha(p):
+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/blackmagic-control.py')],cwd=ROOT,check=True)
+assert not any(p.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_capture_tests.exe','veyra_hdr_color_tests.exe') for p in psutil.process_iter(['name']))
+logs=BASE/'logs'/TASK/label;logs.mkdir(parents=True,exist_ok=False)
+if mode=='prepare':
+ build=json.loads((BASE/'logs'/TASK/'capture-build-v4.json').read_text(encoding='utf8'));assert build['exit']==0
+ for n,d in build['sourceFiles'].items():assert sha(ROOT/n)==d,n
+ old=json.loads((PACKAGE/'package-manifest.json').read_text(encoding='utf-8-sig'))
+ for row in old['files']:assert sha(PACKAGE/row['path'])==row['sha256'].lower(),row['path']
+ assert not APP.exists();APP.parent.mkdir(parents=True,exist_ok=True)
+ shutil.copytree(PACKAGE,APP,copy_function=shutil.copy2)
+ shutil.copy2(BUILD/'veyra_qml_ui.exe',APP/'veyra_qml_ui.exe')
+ for name in ('qml/Veyra/DialogHost.qml','THIRD_PARTY_NOTICES.md'):shutil.copy2(ROOT/name,APP/name)
+ result={'candidate':str(APP),'exeSha256':sha(APP/'veyra_qml_ui.exe'),'build':'capture-build-v4','independentCopies':True}
+ (logs/'summary.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8');print(result,flush=True);sys.exit(0)
+out,tmp=(BASE/k/TASK/label for k in ('tests','tmp'))
+for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
+env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_','QSG_'))}
+windows=Path(env['WINDIR']);env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),QML_DISABLE_DISK_CACHE='1',QT_FORCE_STDERR_LOGGING='1')
+env['PATH']=os.pathsep.join(map(str,([BUILD,PACKAGE] if mode=='rate' else [])+[windows/'System32',windows,windows/'System32/Wbem']))
+results=[]
+def run(name,cmd,cwd,marker):
+ log=logs/(name+'.log');child=env.copy();child['VEYRA_LOG_FILE']=str(logs/(name+'-engine.log'));start=time.monotonic()
+ with log.open('xb') as f:
+ try:rc=subprocess.run(cmd,cwd=cwd,env=child,stdout=f,stderr=subprocess.STDOUT,timeout=150).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=log.read_text(encoding='utf8',errors='replace')
+ passed=rc==0 and marker in text and not re.search(r'^FAIL\b|BLACKMAGIC_UI_FAIL|ReferenceError:|TypeError:|no root object',text,re.M)
+ result={'case':name,'command':cmd,'exit':rc,'seconds':time.monotonic()-start,'exeSha256':sha(Path(cmd[0])),'passed':bool(passed),'log':str(log)}
+ results.append(result);(logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8');print(result,flush=True)
+ assert passed,text[-5000:]
+ return text
+if mode=='rate':
+ # Enumerated KUHAIMI 27P device 0, YUY2 VideoInfo2 1080p60 native index 1.
+ text=run('usb-1080p60',[str(BUILD/'veyra_capture_tests.exe'),'--rate-test','capture:0:1:-1','0'],out,'PASS RATE pass=1')
+ assert len(re.findall(r'PASS RATE pass=[01]',text))==2 and re.search(r'\[capture-upstream\].*inputMediums=0 crossbar=false existing=false hr=0x00000001 routeChanged=0',text)
+else:
+ assert sha(APP/'veyra_qml_ui.exe')==sha(BUILD/'veyra_qml_ui.exe')
+ profile=out/'profile';profile.mkdir();images=out/'screenshots';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')
+ main=APP/'qml/Veyra/Main.qml';original=main.read_bytes();source=original.decode('utf8');at=source.rfind('}')
+ try:
+ remembered=''
+ for phase in (('properties',) if mode=='properties' else ('capture','restore')):
+ if phase=='restore':
+ prefs=profile/'capture-preferences.v1';data=prefs.read_text(encoding='utf-16-le');quoted=re.findall(r'"((?:\\.|[^"\\])*)"',data)
+ assert len(quoted)>=2;remembered=quoted[1];assert remembered.endswith(':scan=0'),remembered
+ shutil.copy2(prefs,out/'capture-preferences-before-legacy.v1')
+ prefs.write_text(data.replace(remembered,remembered.rsplit(':scan=',1)[0],1),encoding='utf-16-le')
+ setting='item.dialogHost=dialogs;item.evidence='+json.dumps(str(images))+';item.phase='+json.dumps(phase)+';item.rememberedKey='+json.dumps(remembered)+';'
+ loader='\nLoader { source: '+json.dumps((ROOT/'scripts/acceptance/blackmagic-ui.qml').as_uri())+'; onLoaded: {'+setting+'} }\n'
+ main.write_text(source[:at]+loader+source[at:],encoding='utf8')
+ text=run(phase,[str(APP/'veyra_qml_ui.exe'),'--page','pro','--size','1280x900','--data-dir',str(profile),'--exit-after','110000'],APP,{'capture':'BLACKMAGIC_UI_PASS','restore':'BLACKMAGIC_UI_RESTORE_PASS','properties':'BLACKMAGIC_UI_PROPERTIES_PASS'}[phase])
+ if phase=='properties':assert re.search(r'\[capture-driver-settings\].*crossbarHr=0x00000001 beforeGetFormatHr=0x00000000 afterGetFormatHr=0x00000000 pageHr=0x80004002',text),'Real COM graph/property fallback was not exercised'
+ finally:main.write_bytes(original)
+ assert sha(main)==sha(PACKAGE/'qml/Veyra/Main.qml')
+ if mode=='ui':assert len(list(images.glob('veyra-*.png')))==1,'Explicit captured-frame screenshot missing'
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/blackmagic-control.py')],cwd=ROOT,check=True)
diff --git a/scripts/acceptance/blackmagic-finalize.py b/scripts/acceptance/blackmagic-finalize.py
new file mode 100644
index 00000000..2f0d0bf2
--- /dev/null
+++ b/scripts/acceptance/blackmagic-finalize.py
@@ -0,0 +1,90 @@
+"""Audit source/test correspondence and assemble a local portable test handoff."""
+from pathlib import Path
+import ast,hashlib,json,os,re,shutil,subprocess,sys,time,zipfile,psutil
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='blackmagic-capture-20261007'
+LOGS=BASE/'logs'/TASK;OUT=BASE/'test-packages'/TASK;VERIFY=BASE/'verify'/TASK
+APP=OUT/'Veyra-2.0.5-capture-test-NVIDIA-win64-portable'
+PACKAGE=BASE/'releases/publish-2.0.5-20261007/packages/Veyra-2.0.5-NVIDIA-win64-portable'
+BUILD=BASE/'build'/TASK
+def read(p):return json.loads(p.read_text(encoding='utf-8-sig'))
+def sha(p):
+ with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
+def git(*args):return subprocess.check_output(['git',*args],cwd=ROOT).decode('utf8').strip()
+guard=[sys.executable,'-B',str(ROOT/'scripts/acceptance/blackmagic-control.py')]
+subprocess.run(guard,cwd=ROOT,check=True)
+assert not any(p.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_capture_tests.exe','veyra_hdr_color_tests.exe') for p in psutil.process_iter(['name']))
+assert not git('status','--porcelain=v1'),'Commit reviewed source before packaging'
+subprocess.run(['git','diff','--check'],cwd=ROOT,check=True)
+head=git('rev-parse','HEAD');build=read(LOGS/'capture-build-v4.json');assert build['exit']==0
+for n,d in build['sourceFiles'].items():assert sha(ROOT/n)==d,'Build input changed: '+n
+for p in (ROOT/'scripts/acceptance').glob('blackmagic-*.py'):ast.parse(p.read_text(encoding='utf8'),filename=str(p))
+contracts=read(LOGS/'contracts-v4/summary.json');assert len(contracts)==4 and all(x['passed'] and x['exit']==0 for x in contracts)
+for x in contracts:assert sha(Path(x['command'][0]))==x['exeSha256'],x['case']
+rate=read(LOGS/'usb-rate-v4/summary.json');gui=read(LOGS/'gui-v4/summary.json');props=read(LOGS/'driver-page-v4/summary.json')
+assert len(rate)==1 and len(gui)==2 and len(props)==1 and all(x['passed'] and x['exit']==0 for x in rate+gui+props)
+exe=sha(BUILD/'veyra_qml_ui.exe');assert sha(APP/'veyra_qml_ui.exe')==exe
+assert all(x['exeSha256']==exe for x in gui+props)
+assert rate[0]['exeSha256']==sha(BUILD/'veyra_capture_tests.exe')
+note=ROOT/'docs/BLACKMAGIC_CAPTURE_REPORT_2026-10-07.md';assert exe in note.read_text(encoding='utf8')
+shutil.copy2(note,APP/'CAPTURE-TEST-NOTES.zh-CN.md')
+old=read(PACKAGE/'package-manifest.json')
+changed={'veyra_qml_ui.exe','qml/Veyra/DialogHost.qml','THIRD_PARTY_NOTICES.md'}
+oldPaths={x['path'] for x in old['files']}
+for row in old['files']:
+ rel=row['path'];assert sha(PACKAGE/rel)==row['sha256'].lower(),rel
+ assert not os.path.samefile(APP/rel,PACKAGE/rel),'Writable hardlink: '+rel
+ if rel not in changed:assert sha(APP/rel)==row['sha256'].lower(),'Unapproved payload difference: '+rel
+for rel in changed-{'veyra_qml_ui.exe'}:assert sha(APP/rel)==sha(ROOT/rel),rel
+assert {p.relative_to(APP).as_posix() for p in APP.rglob('*') if p.is_file()}==oldPaths|{'package-manifest.json','CAPTURE-TEST-NOTES.zh-CN.md'}
+source=OUT/'Veyra-2.0.5-capture-test-source.zip';assert not source.exists()
+subprocess.run(['git','archive','--format=zip','--prefix=Veyra-capture-test/','--output='+str(source),head],cwd=ROOT,check=True,timeout=90)
+with zipfile.ZipFile(source) as z:
+ assert z.testzip() is None
+ for item in z.infolist():assert not re.search(r'\.(dll|lib|exe|pdb|onnx|f16|hsaco|cubin)$',item.filename,re.I),item.filename
+ for n in build['sourceFiles']:
+ # Archive/check-out EOLs can differ; both must represent the exact compiled text.
+ assert z.read('Veyra-capture-test/'+n).replace(b'\r\n',b'\n')==(ROOT/n).read_bytes().replace(b'\r\n',b'\n'),n
+manifest={'schema':3,'version':'2.0.5','candidate':'2.0.5-capture-test','displayVersion':'2.0.5-capture-test',
+ 'releaseReady':False,'localOnly':True,'gpuPackage':'NVIDIA','baseCommit':build['sourceHead'],'sourceArchiveCommit':head,
+ 'buildInputReceipt':'capture-build-v4.json','compiledSourceFilesVerified':len(build['sourceFiles']),
+ 'publishedBaseVersion':'2.0.5','publishedBaseExeSha256':sha(PACKAGE/'veyra_qml_ui.exe'),
+ 'correspondingSource':{'application':'../'+source.name,'applicationSha256':sha(source),
+ 'dependencies':old['correspondingSource']['dependencies'],'dependencySha256':old['correspondingSource']['dependencySha256'],
+ 'instructions':'docs/BUILD_2.0.5.md','displayVersionOverride':'-DVEYRA_DISPLAY_VERSION=2.0.5-capture-test'},
+ 'validation':'Local RTX5070 GPU pixels + KUHAIMI27P USB/GUI only; Blackmagic physical hardware awaiting field test',
+ 'knownIssues':['Physical Blackmagic HDMI/SDI routing and model-specific property pages not validated',
+ 'No new deinterlacing or native v210 conversion','Community NR initialization exception in supplied log is separate and unresolved',
+ 'NVIDIA VRAM growth remains unresolved; higher VFG multipliers retain prior test-candidate limits'],
+ 'files':[]}
+for p in sorted(APP.rglob('*')):
+ if p.is_file() and p.name!='package-manifest.json':manifest['files'].append({'path':p.relative_to(APP).as_posix(),'size':p.stat().st_size,'sha256':sha(p)})
+(APP/'package-manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf8')
+portable=OUT/(APP.name+'.zip');assert not portable.exists();start=time.monotonic()
+with zipfile.ZipFile(portable,'x',compression=zipfile.ZIP_DEFLATED,compresslevel=3,allowZip64=True) as z:
+ for p in sorted(APP.rglob('*')):
+ if p.is_file():z.write(p,APP.name+'/'+p.relative_to(APP).as_posix())
+expected={APP.name+'/'+x['path']:x['sha256'] for x in manifest['files']}
+expected[APP.name+'/package-manifest.json']=sha(APP/'package-manifest.json')
+with zipfile.ZipFile(portable) as z:
+ assert len(z.namelist())==len(expected) and set(z.namelist())==set(expected)
+ for name,d in expected.items():
+ with z.open(name) as f:assert hashlib.file_digest(f,'sha256').hexdigest()==d,name
+ assert z.testzip() is None
+print('Portable ZIP payload verified',len(expected),'files',round(time.monotonic()-start,3),'seconds',flush=True)
+# Only task-owned generated CUDA caches are disposable. Preserve profiles,
+# screenshots, logs, current build and final deliverables.
+removed=[];taskTmp=(BASE/'tmp'/TASK).resolve()
+for cache in sorted(taskTmp.rglob('cuda-cache')):
+ resolved=cache.resolve();assert resolved.is_relative_to(taskTmp) and resolved!=taskTmp and cache.is_dir() and not cache.is_symlink()
+ size=sum(p.stat().st_size for p in cache.rglob('*') if p.is_file())
+ shutil.rmtree(resolved);removed.append({'path':str(resolved),'bytes':size})
+subprocess.run(guard,cwd=ROOT,check=True)
+assert not git('status','--porcelain=v1')
+result={'passed':True,'head':head,'branch':git('branch','--show-current'),'candidate':str(APP),
+ 'exeSha256':exe,'source':str(source),'sourceSha256':sha(source),'portable':str(portable),'portableSha256':sha(portable),
+ 'packageManifestSha256':sha(APP/'package-manifest.json'),'compiledSourceFilesVerified':len(build['sourceFiles']),
+ 'payloadFiles':len(expected),'contracts':contracts,'rate':rate,'gui':gui,'properties':props,
+ 'otherWorktreesAndPublishedPackagesPreserved':True,'runtimeModelShaderBytesUnchanged':True,'noProprietaryBinariesInSource':True,
+ 'blackmagicPhysicalValidation':False,'sourceAndPortableCrcAndPayloadVerified':True,'removedTaskCaches':removed}
+VERIFY.mkdir(parents=True,exist_ok=True);(VERIFY/'final-check.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
+print(json.dumps({k:result[k] for k in ('passed','head','candidate','exeSha256','portable','portableSha256','source','payloadFiles','compiledSourceFilesVerified')},ensure_ascii=False),flush=True)
diff --git a/scripts/acceptance/blackmagic-tests.py b/scripts/acceptance/blackmagic-tests.py
new file mode 100644
index 00000000..ba91d2ce
--- /dev/null
+++ b/scripts/acceptance/blackmagic-tests.py
@@ -0,0 +1,31 @@
+"""Bounded serial source contracts and real GPU pixel checks; no signal claims."""
+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-capture-20261007'
+label=sys.argv[1];assert label.replace('-','').isalnum()
+BUILD=BASE/'build'/TASK;PACKAGE=BASE/'releases/publish-2.0.5-20261007/packages/Veyra-2.0.5-NVIDIA-win64-portable'
+out=BASE/'tests'/TASK/label;tmp=BASE/'tmp'/TASK/label;logs=BASE/'logs'/TASK/label
+for p in (out,tmp,logs):p.mkdir(parents=True,exist_ok=False)
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/blackmagic-control.py')],cwd=ROOT,check=True)
+assert not any(p.info['name'].lower() in ('veyra.exe','veyra_qml_ui.exe','veyra_hdr_color_tests.exe') for p in psutil.process_iter(['name']))
+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'))
+env['PATH']=os.pathsep.join(map(str,(BUILD,PACKAGE,Path(env['WINDIR'])/'System32',Path(env['WINDIR']),Path(env['WINDIR'])/'System32/Wbem')))
+cases=[('color','veyra_capture_color_tests.exe',[]),('selection','veyra_capture_format_selection_tests.exe',[]),('gpu','veyra_hdr_color_tests.exe',[]),('devices','veyra_capture_tests.exe',['--list'])]
+results=[]
+for name,exe,args in cases:
+ log=logs/(name+'.log');child=env.copy();child['VEYRA_LOG_FILE']=str(logs/(name+'-engine.log'))
+ cmd=[str(BUILD/exe),*args];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');passed=rc==0 and not re.search(r'^FAIL\b|\bpass=0\b',text,re.M)
+ if name=='color':passed=passed and 'WDM connects matching output' in text and 'HDYC SD dimensions keep BT709' in text
+ if name=='selection':passed=passed and 'capture format selection failures=0' in text
+ if name=='gpu':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
+ if name=='devices':passed=rc in (0,1) and not re.search(r'^FAIL\b',text,re.M)
+ item={'case':name,'command':cmd,'exit':rc,'seconds':time.monotonic()-start,'passed':bool(passed),'checksPrinted':len(re.findall(r'^PASS\b|\bpass=1\b',text,re.M)),'exeSha256':hashlib.sha256((BUILD/exe).read_bytes()).hexdigest(),'log':str(log)}
+ results.append(item);(logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8');print(json.dumps(item,ensure_ascii=False),flush=True)
+ print('\n'.join(text.splitlines()[-5:]),flush=True)
+ if not passed:raise SystemExit(1)
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/blackmagic-control.py')],cwd=ROOT,check=True)
diff --git a/scripts/acceptance/blackmagic-ui.qml b/scripts/acceptance/blackmagic-ui.qml
new file mode 100644
index 00000000..cf696861
--- /dev/null
+++ b/scripts/acceptance/blackmagic-ui.qml
@@ -0,0 +1,99 @@
+import QtQuick
+Item {
+ id: test
+ property var dialogHost: null
+ property var appWindow: Window.window
+ property string evidence: ""
+ property string phase: "capture"
+ property string rememberedKey: ""
+ property int step: 0
+ property int ticks: 0
+ property int began: 0
+ property bool grabbed: false
+ property string selected: ""
+ function require(ok,why) { if(!ok) throw new Error(why) }
+ function find(item,name) {
+ if(item.objectName===name)return item
+ for(const child of item.children||[]){const hit=find(child,name);if(hit)return hit}
+ return null
+ }
+ function grab(name) {
+ grabbed=false
+ appWindow.contentItem.grabToImage(result=>{
+ if(!result.saveToFile(test.evidence+"/"+name+".png"))console.log("BLACKMAGIC_UI_FAIL screenshot save")
+ test.grabbed=true
+ })
+ }
+ Timer {
+ interval:250;running:true;repeat:true
+ onTriggered: { try {
+ ++test.ticks
+ test.require(test.ticks<400,"100s deadline step="+test.step)
+ test.require(!veyra.failed,"source failed: "+veyra.statusText)
+ if(test.step===0) {
+ if(test.ticks<8)return
+ test.require(test.dialogHost!==null,"production DialogHost missing")
+ veyra.nrEnabled=false;veyra.srEnabled=false;veyra.fgEnabled=false;veyra.muted=true
+ test.dialogHost.open("capture");test.step=1
+ } else if(test.step===1) {
+ if(veyra.captureQueryBusy||!veyra.captureFormats.length)return
+ const device=veyra.captureDevices.find(x=>x.label==="KUHAIMI 27P")
+ test.require(device!==undefined,"explicit local USB fixture unavailable")
+ if(veyra.captureDeviceId!==device.id){veyra.captureDeviceId=device.id;return}
+ test.require(!veyra.captureBlackmagicDevice,"ordinary USB card misidentified as Blackmagic")
+ const props=test.find(test.appWindow.contentItem,"capture-driver-properties")
+ const input=test.find(test.appWindow.contentItem,"capture-driver-input")
+ test.require(props!==null&&props.enabled,"driver properties unavailable while idle")
+ test.require(input!==null&&!input.visible,"Blackmagic-only input control shown on ordinary USB")
+ if(test.phase==="properties") {
+ // This fixture has no input crossbar/property page. Exercise
+ // real COM graph creation without displaying a modal window.
+ const before=veyra.captureFormatKey
+ test.require(!veyra.openCaptureDriverSettings(true),"ordinary USB unexpectedly exposed an input crossbar")
+ test.require(!veyra.captureQueryBusy&&props.enabled&&veyra.captureFormatKey===before,"failed property page left query busy or changed format")
+ console.log("BLACKMAGIC_UI_PROPERTIES_PASS",veyra.captureStatus)
+ Qt.quit();return
+ }
+ if(test.phase==="restore") {
+ test.require(veyra.captureFormatKey===test.rememberedKey,"legacy VideoInfo2 format did not migrate: "+veyra.captureFormatKey)
+ console.log("BLACKMAGIC_UI_RESTORE_PASS",veyra.captureFormatKey)
+ Qt.quit();return
+ }
+ const format=veyra.captureFormats.find(x=>x.id.includes(":scan=")&&x.label.startsWith("1920 x 1080 @ 60.00")&&x.label.includes("YUY2"))
+ test.require(format!==undefined,"explicit 1080p60 YUY2 VideoInfo2 unavailable")
+ veyra.captureFormatKey=format.id;test.selected=format.id
+ veyra.captureAudioChoice=-1;veyra.captureRequestedFps=0
+ test.grab("capture-idle");test.step=2
+ } else if(test.step===2) {
+ if(!test.grabbed||veyra.applying)return
+ test.require(veyra.startCaptureSession(),"GUI source connect rejected")
+ // Opening must not create a competing driver filter either.
+ test.require(!veyra.openCaptureDriverSettings(false),"driver settings opened during source opening")
+ test.step=3
+ } else if(test.step===3) {
+ if(!veyra.running||veyra.captureFps<20)return
+ test.require(veyra.captureSignalLevel==="ok"&&veyra.captureSignalText==="正在收帧","callback status makes incorrect signal claim")
+ test.require(!test.find(test.appWindow.contentItem,"capture-driver-properties").enabled,"driver properties enabled during capture")
+ test.require(!veyra.openCaptureDriverSettings(false),"driver settings opened during live capture")
+ test.require(!veyra.nrEnabled&&!veyra.srEnabled&&!veyra.fgEnabled,"basic capture silently enabled enhancement")
+ test.began=test.ticks;test.step=4
+ } else if(test.step===4) {
+ if(test.ticks-test.began<24)return
+ test.require(veyra.captureFps>50&&veyra.captureFps<70,"local 60fps capture callback out of range: "+veyra.captureFps)
+ console.log("BLACKMAGIC_UI_LIVE",veyra.captureFps,veyra.sourceSummary,test.selected)
+ test.grab("capture-live")
+ veyra.takeScreenshot();test.step=5
+ } else if(test.step===5) {
+ if(!test.grabbed||!veyra.lastScreenshot.length)return
+ test.find(test.appWindow.contentItem,"capture-dialog").actionTriggered("断开")
+ test.step=6
+ } else if(test.step===6) {
+ if(veyra.running||veyra.captureSignalLevel!=="idle")return
+ test.require(test.find(test.appWindow.contentItem,"capture-driver-properties").enabled,"driver properties did not recover after disconnect")
+ test.require(veyra.captureFormatKey===test.selected,"disconnect lost selected format")
+ console.log("BLACKMAGIC_UI_PASS",test.selected,veyra.lastScreenshot)
+ Qt.quit()
+ }
+ } catch(e) {console.log("BLACKMAGIC_UI_FAIL",String(e));Qt.quit()} }
+ }
+}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 1c50ab42..b39d7760 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -2304,6 +2304,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
snapshot_.flowPerf=graph->actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;
snapshot_.nrEvaluated=graphStats.nrEvaluateCount;snapshot_.nvofExecuted=graphStats.nvofExecuteCount;
snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveScheduler?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;
+ snapshot_.captureSampledBlack=captureStats.sampledBlack;
snapshot_.schedulingWaitP95Ms=waitP95;snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentP95;
}
loopTrace.mark("publishSnapshot");
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 144044bf..732d7a5a 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -3,6 +3,8 @@
#include "veyra/source/WasapiAudioInput.h"
#include "veyra/source/CaptureTiming.h"
#include "veyra/source/CaptureMediaType.h"
+#include "veyra/source/DirectShowCaptureSetup.h"
+#include "veyra/source/CaptureSignalProbe.h"
#include "veyra/pipeline/CaptureUploadFrame.h"
#include "veyra/source/NativeCaptureSink.h"
#include <avrt.h>
@@ -203,6 +205,10 @@ bool bind(unsigned index,bool audio,ComPtr<IBaseFilter>& filter){auto list=monik
bool 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;
}
+std::wstring captureDeviceName(std::wstring_view path){
+ for(auto& moniker:monikers(false))if(monikerPath(moniker.Get())==path)return propertyString(moniker.Get(),L"FriendlyName");
+ return {};
+}
bool createConfiguration(ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b){return SUCCEEDED(CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g)))&&SUCCEEDED(CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&b)))&&SUCCEEDED(b->SetFiltergraph(g.Get()));}
bool configuration(unsigned device,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return createConfiguration(g,b)&&bind(device,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
bool configuration(std::wstring_view path,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return createConfiguration(g,b)&&bindPath(path,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
@@ -368,6 +374,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
std::wstring audioError;
AudioInputRecovery audioRecovery;
SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;
+ bool signalProbeEnabled=false;Clock::time_point nextSignalProbe{};CaptureSignalProbeState signalProbe;
// Magewell Pro Capture low-latency video (MagewellCapture.h). While it runs, the DirectShow
// video samples are ignored and its frames enter the same native mailbox below; if it stops
// on its own, DirectShow delivery resumes by itself.
@@ -563,13 +570,21 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
(compressedPath?sample->GetActualDataLength()>0:sample->GetActualDataLength()>=LONG(layout.sampleBytes));
bool enqueued=false;uint64_t timingSequence=0;int64_t copied100ns=0;double lockWaitMs=0,arrivalDeltaMs=0,ptsDeltaMs=0;
// Native path: claim the staging frame, copy outside the lock.
- AVFrame* staged=nullptr;bool stagedOk=false;
+ AVFrame* staged=nullptr;bool stagedOk=false,probeNow=false;CaptureSignalSample signalSample;
if(valid&&!compressedPath){
- {std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}}
+ {std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}
+ if(signalProbeEnabled&&arrival>=nextSignalProbe){nextSignalProbe=arrival+std::chrono::seconds(1);probeNow=true;}}
+ if(probeNow)signalSample=sampleCaptureSignal(layout,data,size_t(sample->GetActualDataLength()));
if(staged)stagedOk=writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*staged,verticalFlip.load());
}
{
std::lock_guard lock(mutex);
+ if(probeNow){
+ const bool wasBlack=signalProbe.persistentBlack();signalProbe.observe(signalSample);
+ if(signalProbe.samples<=6||wasBlack!=signalProbe.persistentBlack()||signalProbe.samples%30==0)
+ log::info("capture-source-pixels",std::format("samples={} known={} points={} min={} max={} mean={:.2f} chromaDeviation={} blackLike={} blackStreak={} persistentBlack={} sourceCpuSample=1 notSignalDetection=1",
+ signalProbe.samples,signalSample.known,signalSample.points,signalSample.minimum,signalSample.maximum,signalSample.mean,signalSample.chromaDeviation,signalSample.blackLike,signalProbe.blackStreak,signalProbe.persistentBlack()));
+ }
lockWaitMs=std::chrono::duration<double,std::milli>(Clock::now()-arrival).count();
// The compressed path decodes in its own worker and keeps its own
// frame pool, so the preallocated NV12 mailbox is legitimately
@@ -688,13 +703,17 @@ std::wstring CaptureCardSource::makeCapturePath(unsigned videoIndex,const Captur
if(video.path.empty()||(audioMode>=0&&(!audio||audio->path.empty())))return std::format(L"capture:{}:{}:{}:{}{}",videoIndex,format,audioMode,colorOverride,suffix);
return std::format(L"capture2:{}:{}:{}:{}:{}{}",encodePath(video.path),format,audioMode,audioMode>=0?encodePath(audio->path):L"",colorOverride,suffix);
}
-std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config){
+std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config,bool preferDriverCurrent=false){
std::vector<CaptureFormat> out;if(!config)return out;int count=0,size=0;
+ std::wstring currentKey;
+ if(preferDriverCurrent){AM_MEDIA_TYPE* current=nullptr;const HRESULT hr=config->GetFormat(&current);
+ if(SUCCEEDED(hr)&&current)currentKey=captureFormatIdentity(*current);
+ log::info("capture-default-format",std::format("GetFormat hr=0x{:08X} key={} configurationOnly=1 notSignalDetection=1",uint32_t(hr),narrowForLog(currentKey)));freeType(current);}
if(FAILED(config->GetNumberOfCapabilities(&count,&size))||size<1||size>65536)return out;
std::vector<BYTE> caps(size);
for(int i=0;i<count;++i){AM_MEDIA_TYPE* type=nullptr;if(FAILED(config->GetStreamCaps(i,&type,caps.data())))continue;BITMAPINFOHEADER* bitmap=nullptr;REFERENCE_TIME duration=0;
- if(type->formattype==FORMAT_VideoInfo&&type->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* info=reinterpret_cast<VIDEOINFOHEADER*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}
- else if(type->formattype==FORMAT_VideoInfo2&&type->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* info=reinterpret_cast<VIDEOINFOHEADER2*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}
+ if(type&&type->pbFormat&&type->formattype==FORMAT_VideoInfo&&type->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* info=reinterpret_cast<VIDEOINFOHEADER*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}
+ else if(type&&type->pbFormat&&type->formattype==FORMAT_VideoInfo2&&type->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* info=reinterpret_cast<VIDEOINFOHEADER2*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}
// Device capabilities, not a 1080p/2160p 30/60 preset list. Keep native
// indices so the selected row opens the exact driver media type.
if(bitmap&&bitmap->biWidth>0&&bitmap->biWidth<=3840&&std::abs(int64_t(bitmap->biHeight))>0&&std::abs(int64_t(bitmap->biHeight))<=2160&&duration>0){unsigned width=bitmap->biWidth,height=unsigned(std::abs(int64_t(bitmap->biHeight)));double fps=1e7/duration;
@@ -703,18 +722,50 @@ std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config){
// N3: latency tier + recommended rank; compressed/unknown sorts last.
const auto tier=valid?captureFormatTier(layout.packing):CaptureFormatTier::Decoded;
const int rank=valid?captureFormatRank(layout.packing):captureFormatRank(CapturePacking::Unknown);
- wchar_t subtype[40]{},formatType[40]{};StringFromGUID2(type->subtype,subtype,40);StringFromGUID2(type->formattype,formatType,40);
- const auto key=std::format(L"{}:{}:{}:{}:{}:{}:{}",width,bitmap->biHeight,duration,subtype,formatType,bitmap->biBitCount,bitmap->biCompression);
- out.push_back({i,width,height,fps,std::format(L"{} x {} @ {:.2f} fps · {} · {} · {} [format {}]",width,height,fps,pixel,support,captureFormatTierLabel(tier),i),key,rank,int(tier)});
+ const auto key=captureFormatIdentity(*type);const bool current=!currentKey.empty()&&key==currentKey;
+ std::wstring scan;
+ if(type->formattype==FORMAT_VideoInfo2){const auto flags=reinterpret_cast<const VIDEOINFOHEADER2*>(type->pbFormat)->dwInterlaceFlags;
+ scan=(flags&AMINTERLACE_IsInterlaced)?std::format(L" · 隔行({:.2f} 场/秒)",fps*((flags&AMINTERLACE_1FieldPerSample)?1:2)):L" · 逐行";}
+ out.push_back({i,width,height,fps,std::format(L"{} x {} @ {:.2f} fps{} · {} · {} · {}{} [format {}]",width,height,fps,scan,pixel,support,captureFormatTierLabel(tier),current?L" · 驱动默认":L"",i),key,rank,int(tier),current});
}
freeType(type);
}
// Recommended order first; equal ranks keep the driver's enumeration order.
- std::stable_sort(out.begin(),out.end(),[](const CaptureFormat& a,const CaptureFormat& b){return a.rank<b.rank;});
+ std::stable_sort(out.begin(),out.end(),[](const CaptureFormat& a,const CaptureFormat& b){return a.driverCurrent!=b.driverCurrent?a.driverCurrent:a.rank<b.rank;});
return out;
}
-std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(device,g,b,f,c))return {};return enumerateFormats(c.Get());}
-std::vector<CaptureFormat> CaptureCardSource::formatsByPath(std::wstring_view devicePath){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(devicePath,g,b,f,c))return {};return enumerateFormats(c.Get());}
+std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){
+ ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(device,g,b,f,c))return {};
+ const auto list=monikers(false);const auto name=device<list.size()?propertyString(list[device].Get(),L"FriendlyName"):L"";
+ return enumerateFormats(c.Get(),isBlackmagicCaptureDevice(name));
+}
+std::vector<CaptureFormat> CaptureCardSource::formatsByPath(std::wstring_view devicePath){
+ ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(devicePath,g,b,f,c))return {};
+ return enumerateFormats(c.Get(),isBlackmagicCaptureDevice(captureDeviceName(devicePath),devicePath));
+}
+bool CaptureCardSource::showDeviceProperties(std::wstring_view devicePath,uintptr_t owner,bool inputSelector,std::wstring& error,std::wstring* changedFormatKey){
+ error.clear();if(changedFormatKey)changedFormatKey->clear();
+ ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device;ComPtr<IAMStreamConfig> config;
+ if(!configuration(devicePath,graph,builder,device,config)){error=L"无法打开驱动设置;请先断开采集并关闭占用设备的应用。";return false;}
+ AM_MEDIA_TYPE* before=nullptr;const HRESULT beforeHr=config->GetFormat(&before);
+ const std::wstring beforeKey=SUCCEEDED(beforeHr)&&before?captureFormatIdentity(*before):L"";freeType(before);
+ const auto setup=dshow::connectCaptureCrossbar(graph.Get(),builder.Get(),device.Get());
+ HRESULT hr=setup.hr;
+ if(SUCCEEDED(hr)){
+ if(inputSelector)hr=setup.filter?dshow::showPropertyPages(setup.filter.Get(),reinterpret_cast<HWND>(owner),L"采集输入选择"):E_NOINTERFACE;
+ else{
+ hr=dshow::showPropertyPages(device.Get(),reinterpret_cast<HWND>(owner),L"采集设备驱动设置");
+ if(hr==E_NOINTERFACE){ComPtr<IPin> pin;
+ if(SUCCEEDED(builder->FindPin(device.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&pin)))
+ hr=dshow::showPropertyPages(pin.Get(),reinterpret_cast<HWND>(owner),L"采集视频格式");}
+ }
+ }
+ AM_MEDIA_TYPE* after=nullptr;const HRESULT afterHr=config->GetFormat(&after);
+ if(changedFormatKey&&SUCCEEDED(hr)&&SUCCEEDED(afterHr)&&after){const auto key=captureFormatIdentity(*after);if(key!=beforeKey)*changedFormatKey=key;}freeType(after);
+ log::info("capture-driver-settings",std::format("inputSelector={} crossbarHr=0x{:08X} beforeGetFormatHr=0x{:08X} afterGetFormatHr=0x{:08X} pageHr=0x{:08X} changedFormat={}",inputSelector,uint32_t(setup.hr),uint32_t(beforeHr),uint32_t(afterHr),uint32_t(hr),changedFormatKey&&!changedFormatKey->empty()));
+ if(FAILED(hr))error=hr==E_NOINTERFACE?L"驱动没有公开此设置页。Blackmagic 请用 Desktop Video Setup 选择 HDMI/SDI,并在采集面板匹配分辨率、帧率和逐行/隔行制式。":std::format(L"驱动设置无法打开(0x{:08X})。",uint32_t(hr));
+ return SUCCEEDED(hr);
+}
const SourceInfo& CaptureCardSource::info()const{return p_->info;}
void CaptureCardSource::setAudioIngress(unsigned mode){
auto& p=*p_;
@@ -781,6 +832,10 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle
}
std::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);
+ 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;}
configureAverToneMap(p.device.Get(),devicePath,native->subtype.Data1==MAKEFOURCC('P','0','1','0')||native->subtype.Data1==MAKEFOURCC('P','0','1','6'));
log::info("capture-device",std::format("path={} selectedFormat={} requestedFps={} nativeSubtype=0x{:X}",narrowForLog(devicePath),format,expectedFps,native->subtype.Data1));
HRESULT hr=p.config->SetFormat(native);const GUID requestedSubtype=native->subtype;
@@ -1487,6 +1542,7 @@ bool CaptureCardSource::reconnect(float gain,unsigned syncMode,int offsetMs){
CaptureMetrics CaptureCardSource::metrics()const{
auto& p=*p_;std::lock_guard lock(p.mutex);CaptureMetrics m;
m.received=receivedOffset_+p.received;m.delivered=deliveredOffset_+p.sequence;m.dropped=droppedOffset_+p.dropped;m.readAgeMs=p.readAgeMs;
+ m.sampledBlack=p.signalProbe.persistentBlack();
if(p.recentArrivals.size()>1&&Impl::Clock::now()-p.latestArrival<std::chrono::seconds(1)){const double elapsed=std::chrono::duration<double>(p.recentArrivals.back()-p.recentArrivals.front()).count();if(elapsed>0)m.callbackFps=(p.recentArrivals.size()-1)/elapsed;}
if(p.sequence)m.frameAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();return m;
}
@@ -1580,6 +1636,7 @@ void CaptureCardSource::close()noexcept{
p.info={};
p.sequence=p.received=p.dropped=p.lastDrop=0;p.pending=p.callbackError=p.configured=p.forceDiscontinuity=false;p.lastPts=p.readAgeMs=0;
p.recentArrivals.clear();
+ p.signalProbeEnabled=false;p.signalProbe={};p.nextSignalProbe={};
p.driverDiscontinuity.reset();p.suppressedDriverDiscontinuities=p.discontinuitySamples=0;
}
}
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index 27e2ae2f..fe84522b 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -111,6 +111,7 @@ namespace Gdiplus { using std::min; using std::max; }
#include "veyra/ngx/NrArchitecturePolicy.h"
#include "veyra/ngx/FgCompatibilitySession.h"
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/CaptureSignalProbe.h"
#include "veyra/source/ScreenCaptureSource.h"
namespace veyra::ui {
@@ -328,6 +329,8 @@ struct QmlPlayerBridge::Impl {
struct CaptureQuery { int kind = 0; std::wstring device; std::vector<source::CaptureDevice> video, audio; std::vector<source::CaptureFormat> formats; };
std::future<CaptureQuery> captureQuery;
bool captureBusy = false, captureListed = false, captureResumePending = false;
+ bool captureDriverSettingsOpen = false;
+ std::wstring captureDriverFormatKey;
int captureQueryKind = 0; // 0 device list, 1 formats, 2 formats then connect (continue)
std::vector<source::CaptureDevice> captureVideo, captureAudio;
std::vector<source::CaptureFormat> captureFormatList;
@@ -1952,9 +1955,11 @@ QVariantList QmlPlayerBridge::captureDevices() const {
}
QString QmlPlayerBridge::captureDeviceId() const { return utf8Of(impl_->captureDevice); }
void QmlPlayerBridge::setCaptureDeviceId(const QString& value) {
+ if (impl_->captureDriverSettingsOpen) return;
if (impl_->captureDevice == wideOf(value)) return;
impl_->captureDevice = wideOf(value);
impl_->captureFormatList.clear(); impl_->captureFormatKey.clear();
+ impl_->captureDriverFormatKey.clear();
// Colour follows the device, as in 1.4.4; audio returns to "none" unless it
// is the remembered device.
impl_->captureColor = impl_->capturePrefs.colorForDevice(impl_->captureDevice);
@@ -1970,7 +1975,7 @@ QVariantList QmlPlayerBridge::captureFormats() const {
QVariantList out;
for (const auto& f : impl_->captureFormatList)
out << QVariantMap{{"id", utf8Of(f.key)}, {"label", uiText(f.label)}, {"tier", f.tier},
- {"costHint", source::captureFormatNeedsCostHint(static_cast<source::CaptureFormatTier>(f.tier))}};
+ {"costHint", source::captureFormatNeedsCostHint(static_cast<source::CaptureFormatTier>(f.tier))}, {"driverCurrent", f.driverCurrent}};
return out;
}
QString QmlPlayerBridge::captureFormatKey() const { return utf8Of(impl_->captureFormatKey); }
@@ -2042,8 +2047,28 @@ void QmlPlayerBridge::setCaptureBufferMode(int value) {
auto s = settings(); s.captureBuffer = static_cast<source::CaptureBufferMode>(value);
impl_->commit(std::move(s)); emit settingsChanged();
}
-bool QmlPlayerBridge::captureQueryBusy() const { return impl_->captureBusy; }
+bool QmlPlayerBridge::captureQueryBusy() const { return impl_->captureBusy || impl_->captureDriverSettingsOpen; }
QString QmlPlayerBridge::captureStatus() const { return impl_->captureStatus; }
+bool QmlPlayerBridge::captureBlackmagicDevice() const {
+ for (const auto& d : impl_->captureVideo) if (d.path == impl_->captureDevice) return source::isBlackmagicCaptureDevice(d.name, d.path);
+ return false;
+}
+bool QmlPlayerBridge::openCaptureDriverSettings(bool inputSelector) {
+ auto& i = *impl_;
+ if (captureQueryBusy() || i.captureDevice.empty()) { emit notice(tr("请先选择设备并等待查询完成"), true); return false; }
+ if (i.openingSource || (i.snapshot.capture && !i.engine.idle())) { emit notice(tr("请等待连接结束并断开采集,再打开驱动设置"), true); return false; }
+ HWND owner = i.videoWindow ? GetAncestor(i.videoWindow, GA_ROOT) : nullptr;
+ if (!owner) if (auto* window = QGuiApplication::focusWindow()) owner = reinterpret_cast<HWND>(window->winId());
+ i.captureDriverSettingsOpen = true; emit captureChanged();
+ std::wstring error;
+ const bool ok = source::CaptureCardSource::showDeviceProperties(i.captureDevice, reinterpret_cast<uintptr_t>(owner), inputSelector, error, &i.captureDriverFormatKey);
+ i.captureDriverSettingsOpen = false;
+ if (!ok) { i.captureStatus = uiText(error); emit notice(i.captureStatus, true); emit captureChanged(); return false; }
+ // Some property pages change only this filter instance's IAMStreamConfig.
+ // Carry its exact identity to the new graph instead of discarding it.
+ queryCapture(3, i.captureDevice);
+ return true;
+}
bool QmlPlayerBridge::captureMagewellDevice() const { return source::magewell::isProCaptureDevicePath(impl_->captureDevice); }
QString QmlPlayerBridge::captureMagewellStatus() const {
std::wstring runtime;
@@ -2052,12 +2077,13 @@ QString QmlPlayerBridge::captureMagewellStatus() const {
return veyra::ui::i18n::text(source::magewell::statusText());
}
void QmlPlayerBridge::refreshCaptureDevices() {
+ if (impl_->captureDriverSettingsOpen) return;
impl_->capturePrefs = ui::CapturePreferenceStore(impl_->dataDir).load();
queryCapture(0, {});
}
void QmlPlayerBridge::queryCapture(int kind, std::wstring device) {
auto& i = *impl_;
- if (i.captureBusy) { if (kind == 0) i.captureStatus = tr("正在查询设备…"); return; }
+ if (captureQueryBusy()) { if (kind == 0) i.captureStatus = tr("正在查询设备…"); return; }
i.captureBusy = true; i.captureQueryKind = kind;
i.captureStatus = kind == 0 ? tr("正在查询采集设备…当前播放继续") : tr("正在读取设备支持的格式…");
i.captureQuery = std::async(std::launch::async, [kind, device] {
@@ -2115,12 +2141,18 @@ void QmlPlayerBridge::tickCapture() {
if (q.device != i.captureDevice) { emit captureChanged(); return; } // stale answer
i.captureFormatList = std::move(q.formats);
const bool remembered = i.captureDevice == i.capturePrefs.videoPath;
+ const std::wstring driverSelection = i.captureDriverFormatKey.empty() ? i.captureFormatKey : i.captureDriverFormatKey;
+ if (q.kind == 3) i.captureDriverFormatKey.clear();
i.captureFormatKey.clear();
- if (remembered && !i.capturePrefs.formatKey.empty()) {
- for (const auto& f : i.captureFormatList) if (f.key == i.capturePrefs.formatKey) i.captureFormatKey = f.key;
+ if (q.kind == 3 && !driverSelection.empty()) {
+ if (const auto* f = source::selectCaptureFormat(i.captureFormatList, -1, driverSelection)) i.captureFormatKey = f->key;
+ } else if (remembered && !i.capturePrefs.formatKey.empty()) {
+ if (const auto* f = source::selectCaptureFormat(i.captureFormatList, -1, i.capturePrefs.formatKey)) i.captureFormatKey = f->key;
} else if (!i.captureFormatList.empty()) i.captureFormatKey = i.captureFormatList.front().key;
i.captureStatus = i.captureFormatList.empty() ? tr("未读到有效的 4K 以内采集格式,或设备正被其他应用占用。")
: i.captureFormatKey.empty() ? tr("上次格式已不可用,请重新选择格式。")
+ : q.kind == 3 ? tr("驱动设置已关闭。请核对所选格式与设备帧率,再连接。")
+ : captureBlackmagicDevice() ? tr("请选择与输入信号一致的格式。驱动默认格式不代表检测到的信号。")
: tr("连接后使用当前增强设置。格式与音频变更需要重新连接。");
veyra::log::info("capture-ui", std::format("formats={} selected={}", i.captureFormatList.size(), !i.captureFormatKey.empty()));
emit captureChanged();
@@ -2131,7 +2163,7 @@ void QmlPlayerBridge::tickCapture() {
}
bool QmlPlayerBridge::startCaptureSession() {
auto& i = *impl_;
- if (i.captureBusy) { emit notice(tr("设备查询还没有完成"), true); return false; }
+ if (captureQueryBusy()) { emit notice(tr("设备查询或驱动设置尚未完成"), true); return false; }
int device = -1;
for (size_t k = 0; k < i.captureVideo.size(); ++k) if (i.captureVideo[k].path == i.captureDevice) device = int(k);
const auto* format = source::selectCaptureFormat(i.captureFormatList, -1, i.captureFormatKey);
@@ -6800,13 +6832,15 @@ QString QmlPlayerBridge::captureSignalLevel() const {
const auto& s = impl_->snapshot;
if (!s.running || !s.capture) return QStringLiteral("idle");
if (s.captureRecovering) return QStringLiteral("warn");
+ if (s.captureSampledBlack) return QStringLiteral("warn");
return s.captureFps > 0.5 ? QStringLiteral("ok") : QStringLiteral("warn");
}
QString QmlPlayerBridge::captureSignalText() const {
const auto& s = impl_->snapshot;
if (captureSignalLevel() == QLatin1String("idle")) return tr("未连接");
if (s.captureRecovering) return tr("正在恢复");
- return s.captureFps > 0.5 ? tr("信号正常") : tr("等待信号");
+ if (s.captureFps > 0.5 && s.captureSampledBlack) return tr("收到黑帧 · 检查输入制式");
+ return s.captureFps > 0.5 ? tr("正在收帧") : tr("等待信号");
}
void QmlPlayerBridge::importPresetDialog() {
diff --git a/tests/integration/CaptureFormatGpuCases.h b/tests/integration/CaptureFormatGpuCases.h
index 1c9862af..b198b4db 100644
--- a/tests/integration/CaptureFormatGpuCases.h
+++ b/tests/integration/CaptureFormatGpuCases.h
@@ -21,7 +21,7 @@ inline bool captureReadFp16(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::Comm
inline int captureGpuCases(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring){
using namespace veyra;using namespace veyra::source;int failures=0;
auto fourcc=[](const char* n){return GUID{captureFourcc(n[0],n[1],n[2],n[3]),0,0x10,{0x80,0,0,0xaa,0,0x38,0x9b,0x71}};};
- const GUID ids[]={MEDIASUBTYPE_RGB24,MEDIASUBTYPE_RGB32,MEDIASUBTYPE_ARGB32,MEDIASUBTYPE_RGB555,MEDIASUBTYPE_RGB565,fourcc("YUY2"),fourcc("UYVY"),fourcc("YVYU"),fourcc("NV12"),fourcc("NV21"),fourcc("I420"),fourcc("IYUV"),fourcc("YV12"),fourcc("P010"),fourcc("P016")};
+ const GUID ids[]={MEDIASUBTYPE_RGB24,MEDIASUBTYPE_RGB32,MEDIASUBTYPE_ARGB32,MEDIASUBTYPE_RGB555,MEDIASUBTYPE_RGB565,fourcc("YUY2"),fourcc("UYVY"),fourcc("HDYC"),fourcc("YVYU"),fourcc("NV12"),fourcc("NV21"),fourcc("I420"),fourcc("IYUV"),fourcc("YV12"),fourcc("P010"),fourcc("P016")};
for(const auto& id:ids)for(bool full:{false,true}){
VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=64;vi.bmiHeader.biHeight=32;vi.AvgTimePerFrame=166667;
DXVA2_ExtendedFormat ext{};ext.NominalRange=full?DXVA2_NominalRange_0_255:DXVA2_NominalRange_16_235;ext.VideoTransferMatrix=DXVA2_VideoTransferMatrix_BT709;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;
@@ -34,7 +34,7 @@ inline int captureGpuCases(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::Comma
for(unsigned y=0;y<32;++y){auto* row=raw.data()+y*l.stride;
for(unsigned x=0;x<64;++x){
const unsigned code=x<16?black:x>=48?white:(wide?max/4+(x-16):black+(white-black)/2);
- if(l.format==AV_PIX_FMT_BGR0){for(unsigned b=0;b<3;++b)row[x*4+b]=x<32?0:255;row[x*4+3]=255;}
+ if(l.format==AV_PIX_FMT_BGR0){for(unsigned b=0;b<3;++b)row[x*4+b]=x<32?0:255;row[x*4+3]=0;}
else if(l.format==AV_PIX_FMT_BGR24){row[x*3]=row[x*3+1]=row[x*3+2]=x<32?0:255;}
else if(l.format==AV_PIX_FMT_RGB555LE){const uint16_t v=x<32?0:0x7FFF;memcpy(row+x*2,&v,2);}
else if(l.format==AV_PIX_FMT_RGB565LE){const uint16_t v=x<32?0:0xFFFF;memcpy(row+x*2,&v,2);}
@@ -60,5 +60,30 @@ inline int captureGpuCases(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::Comma
std::cout<<"CAPTURE_GPU subtype="<<std::hex<<id.Data1<<std::dec<<" bits="<<bits<<" full="<<full<<" error="<<error<<" precision="<<precision<<" pass="<<ok<<std::endl;
if(!ok)++failures;out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);
}
+ // Blackmagic HDYC: colored padded samples at an SD-sized extent must
+ // match UYVY with explicit BT.709, including the manual row flip. Gray
+ // ramps alone cannot expose an accidental BT.601 matrix fallback.
+ for(bool flip:{false,true}){
+ std::vector<float> reference;bool pass=true;double colorSpread=0;
+ for(bool hdyc:{false,true}){
+ VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=64;vi.bmiHeader.biHeight=32;vi.bmiHeader.biSizeImage=(128+16)*32;vi.AvgTimePerFrame=333667;
+ if(!hdyc){DXVA2_ExtendedFormat ext{};ext.NominalRange=DXVA2_NominalRange_16_235;ext.VideoTransferMatrix=DXVA2_VideoTransferMatrix_BT709;ext.VideoPrimaries=DXVA2_VideoPrimaries_BT709;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;}
+ AM_MEDIA_TYPE type{};type.majortype=MEDIATYPE_Video;type.subtype=fourcc(hdyc?"HDYC":"UYVY");type.formattype=FORMAT_VideoInfo2;type.cbFormat=sizeof(vi);type.pbFormat=reinterpret_cast<BYTE*>(&vi);
+ CaptureMediaLayout l;bool ok=captureMediaLayout(type,l);std::vector<uint8_t> raw(l.sampleBytes,0xee);
+ for(unsigned y=0;y<32&&ok;++y)for(unsigned x=0;x<64;x+=2){auto* p=raw.data()+size_t(y)*l.stride+x*2;p[0]=y<16?90:150;p[1]=x<32?40:200;p[2]=y<16?240:34;p[3]=x<32?80:160;}
+ AVFrame* f=av_frame_alloc();f->width=64;f->height=32;f->format=l.format;
+ ok=ok&&av_frame_get_buffer(f,32)>=0&&copyCaptureSample(l,raw.data(),raw.size(),*f,flip);
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=64;gd.sourceHeight=gd.workHeight=32;gd.enableNr=gd.enableFg=gd.enableSr=false;gd.noFeatures=true;gd.packedInput=pipeline::packedInputCode(l.color.pixelFormat);
+ pipeline::EnhanceGraph::FrameOutputs out;std::vector<float> pixels;
+ ok=ok&&graph.initialize(gd)&&graph.createViews()&&graph.process(f,0,true,out,1,&l.color)&&captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),pixels);
+ if(ok){
+ for(size_t p=0;p<pixels.size();p+=4)colorSpread=std::max(colorSpread,std::abs(double(pixels[p])-pixels[p+2]));
+ if(!hdyc)reference=pixels;else ok=pixels==reference&&colorSpread>.2;
+ }
+ pass&=ok;out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);
+ }
+ std::cout<<"BLACKMAGIC_HDYC_GPU flip="<<flip<<" identical709="<<pass<<" colorSpread="<<colorSpread<<" pass="<<pass<<std::endl;
+ if(!pass)++failures;
+ }
return failures;
}
diff --git a/tests/unit/BlackmagicCaptureCases.h b/tests/unit/BlackmagicCaptureCases.h
new file mode 100644
index 00000000..45fec431
--- /dev/null
+++ b/tests/unit/BlackmagicCaptureCases.h
@@ -0,0 +1,125 @@
+#pragma once
+#include "veyra/source/DirectShowCaptureSetup.h"
+#include "veyra/source/CaptureSignalProbe.h"
+#include <atomic>
+
+namespace blackmagicTest {
+using Microsoft::WRL::ComPtr;
+// No physical devices or windows: these peers exercise production topology,
+// direction/medium matching and failed connection propagation.
+struct Pin final:IPin,IKsPin {
+ std::atomic<ULONG> refs{1};PIN_DIRECTION direction;Pin* peer=nullptr;std::vector<REGPINMEDIUM> media;
+ explicit Pin(PIN_DIRECTION d,std::vector<REGPINMEDIUM> m={}):direction(d),media(std::move(m)){}
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id==IID_IUnknown||id==IID_IPin)*p=static_cast<IPin*>(this);else if(id==__uuidof(IKsPin))*p=static_cast<IKsPin*>(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;}
+ HRESULT STDMETHODCALLTYPE Connect(IPin*,const AM_MEDIA_TYPE*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE ReceiveConnection(IPin*,const AM_MEDIA_TYPE*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE Disconnect()override{peer=nullptr;return S_OK;}
+ HRESULT STDMETHODCALLTYPE ConnectedTo(IPin** p)override{if(!p)return E_POINTER;*p=peer;if(peer){peer->AddRef();return S_OK;}return VFW_E_NOT_CONNECTED;}
+ HRESULT STDMETHODCALLTYPE ConnectionMediaType(AM_MEDIA_TYPE*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE QueryPinInfo(PIN_INFO*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* p)override{if(!p)return E_POINTER;*p=direction;return S_OK;}
+ HRESULT STDMETHODCALLTYPE QueryId(LPWSTR*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE*)override{return S_OK;}
+ HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes**)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE QueryInternalConnections(IPin**,ULONG*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE EndOfStream()override{return S_OK;}HRESULT STDMETHODCALLTYPE BeginFlush()override{return S_OK;}HRESULT STDMETHODCALLTYPE EndFlush()override{return S_OK;}
+ HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME,REFERENCE_TIME,double)override{return S_OK;}
+ HRESULT STDMETHODCALLTYPE KsQueryMediums(KSMULTIPLE_ITEM** p)override{
+ if(!p)return E_POINTER;const size_t size=sizeof(KSMULTIPLE_ITEM)+media.size()*sizeof(REGPINMEDIUM);
+ auto* block=static_cast<KSMULTIPLE_ITEM*>(CoTaskMemAlloc(size));if(!block)return E_OUTOFMEMORY;
+ block->Size=ULONG(size);block->Count=ULONG(media.size());if(!media.empty())memcpy(block+1,media.data(),media.size()*sizeof(REGPINMEDIUM));*p=block;return S_OK;
+ }
+ HRESULT STDMETHODCALLTYPE KsQueryInterfaces(KSMULTIPLE_ITEM**)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE KsCreateSinkPinHandle(KSPIN_INTERFACE&,KSPIN_MEDIUM&)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE KsGetCurrentCommunication(KSPIN_COMMUNICATION*,KSPIN_INTERFACE*,KSPIN_MEDIUM*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE KsPropagateAcquire()override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE KsDeliver(IMediaSample*,ULONG)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE KsMediaSamplesCompleted(PKSSTREAM_SEGMENT)override{return E_NOTIMPL;}
+ IMemAllocator* STDMETHODCALLTYPE KsPeekAllocator(KSPEEKOPERATION)override{return nullptr;}
+ HRESULT STDMETHODCALLTYPE KsReceiveAllocator(IMemAllocator*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE KsRenegotiateAllocator()override{return E_NOTIMPL;}
+ LONG STDMETHODCALLTYPE KsIncrementPendingIoCount()override{return 0;}LONG STDMETHODCALLTYPE KsDecrementPendingIoCount()override{return 0;}
+ HRESULT STDMETHODCALLTYPE KsQualityNotify(ULONG,REFERENCE_TIME)override{return E_NOTIMPL;}
+};
+struct PinEnum final:IEnumPins {
+ ULONG refs=1;size_t at=0;std::vector<ComPtr<IPin>> values;
+ explicit PinEnum(std::vector<ComPtr<IPin>> p):values(std::move(p)){}
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id!=IID_IUnknown&&id!=IID_IEnumPins)return E_NOINTERFACE;*p=this;AddRef();return S_OK;}
+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs;if(!n)delete this;return n;}
+ HRESULT STDMETHODCALLTYPE Next(ULONG n,IPin** p,ULONG* fetched)override{if(!p||(!fetched&&n!=1))return E_POINTER;ULONG count=0;while(count<n&&at<values.size()){p[count]=values[at++].Get();p[count++]->AddRef();}if(fetched)*fetched=count;return count==n?S_OK:S_FALSE;}
+ HRESULT STDMETHODCALLTYPE Skip(ULONG n)override{at=std::min(at+size_t(n),values.size());return S_OK;}
+ HRESULT STDMETHODCALLTYPE Reset()override{at=0;return S_OK;}
+ HRESULT STDMETHODCALLTYPE Clone(IEnumPins** p)override{if(!p)return E_POINTER;auto* clone=new PinEnum(values);clone->at=at;*p=clone;return S_OK;}
+};
+struct Filter final:IBaseFilter {
+ ULONG refs=1;std::vector<ComPtr<IPin>> pinList;
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id!=IID_IUnknown&&id!=IID_IBaseFilter&&id!=IID_IMediaFilter&&id!=IID_IPersist)return E_NOINTERFACE;*p=this;AddRef();return S_OK;}
+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs;if(!n)delete this;return n;}
+ HRESULT STDMETHODCALLTYPE GetClassID(CLSID*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE Stop()override{return S_OK;}HRESULT STDMETHODCALLTYPE Pause()override{return S_OK;}HRESULT STDMETHODCALLTYPE Run(REFERENCE_TIME)override{return S_OK;}
+ HRESULT STDMETHODCALLTYPE GetState(DWORD,FILTER_STATE* s)override{if(!s)return E_POINTER;*s=State_Stopped;return S_OK;}
+ HRESULT STDMETHODCALLTYPE SetSyncSource(IReferenceClock*)override{return S_OK;}HRESULT STDMETHODCALLTYPE GetSyncSource(IReferenceClock**)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE EnumPins(IEnumPins** p)override{if(!p)return E_POINTER;*p=new PinEnum(pinList);return S_OK;}
+ HRESULT STDMETHODCALLTYPE FindPin(LPCWSTR,IPin**)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE QueryFilterInfo(FILTER_INFO* p)override{if(!p)return E_POINTER;*p={};return S_OK;}
+ HRESULT STDMETHODCALLTYPE JoinFilterGraph(IFilterGraph*,LPCWSTR)override{return S_OK;}
+ HRESULT STDMETHODCALLTYPE QueryVendorInfo(LPWSTR*)override{return E_NOTIMPL;}
+};
+struct Graph final:IFilterGraph {
+ ULONG refs=1;unsigned connections=0;HRESULT connectResult=S_OK;IPin* connectedOutput=nullptr;
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id!=IID_IUnknown&&id!=IID_IFilterGraph)return E_NOINTERFACE;*p=this;AddRef();return S_OK;}
+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs;if(!n)delete this;return n;}
+ HRESULT STDMETHODCALLTYPE AddFilter(IBaseFilter*,LPCWSTR)override{return S_OK;}HRESULT STDMETHODCALLTYPE RemoveFilter(IBaseFilter*)override{return S_OK;}
+ HRESULT STDMETHODCALLTYPE EnumFilters(IEnumFilters**)override{return E_NOTIMPL;}HRESULT STDMETHODCALLTYPE FindFilterByName(LPCWSTR,IBaseFilter**)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE ConnectDirect(IPin* output,IPin* input,const AM_MEDIA_TYPE*)override{++connections;connectedOutput=output;if(SUCCEEDED(connectResult)){static_cast<Pin*>(input)->peer=static_cast<Pin*>(output);static_cast<Pin*>(output)->peer=static_cast<Pin*>(input);}return connectResult;}
+ HRESULT STDMETHODCALLTYPE Reconnect(IPin*)override{return E_NOTIMPL;}HRESULT STDMETHODCALLTYPE Disconnect(IPin*)override{return E_NOTIMPL;}
+ HRESULT STDMETHODCALLTYPE SetDefaultSyncSource()override{return S_OK;}
+};
+template<class Check>void run(Check check){
+ using namespace veyra;using namespace veyra::source;
+ const REGPINMEDIUM a{{0xc0ffee,1,2,{3,4,5,6,7,8,9,10}},7,2};auto b=a;b.dw1=8;
+ REGPINMEDIUM standard{};standard.clsMedium=KSMEDIUMSETID_Standard;
+ check(dshow::sameMedium(a,a)&&!dshow::sameMedium(a,b),"WDM medium includes hardware instance IDs");
+ struct {KSMULTIPLE_ITEM header;REGPINMEDIUM m[3];} block{{sizeof(block),3},{standard,b,a}};
+ check(dshow::captureMediums(&block.header).size()==2,"WDM skips standard medium and retains all device mediums");
+ block.header.Size=sizeof(KSMULTIPLE_ITEM);check(dshow::captureMediums(&block.header).empty(),"WDM rejects truncated medium arrays");
+ block.header.Size=sizeof(block);block.header.Count=100000;check(dshow::captureMediums(&block.header).empty(),"WDM rejects oversized medium count");
+ ComPtr<Pin> input,wrong,output;input.Attach(new Pin(PINDIR_INPUT,{a}));wrong.Attach(new Pin(PINDIR_OUTPUT,{b}));output.Attach(new Pin(PINDIR_OUTPUT,{standard,b,a}));
+ ComPtr<Filter> source,upstream;source.Attach(new Filter);upstream.Attach(new Filter);
+ source->pinList={input.Get()};upstream->pinList={input.Get(),wrong.Get(),output.Get()};
+ ComPtr<Graph> graph;graph.Attach(new Graph);
+ check(dshow::connectUpstream(graph.Get(),upstream.Get(),source.Get())==S_OK&&graph->connections==1&&graph->connectedOutput==output.Get(),"WDM connects matching output, skips wrong direction/card, checks later mediums");
+ check(dshow::connectUpstream(graph.Get(),upstream.Get(),source.Get())==S_FALSE&&graph->connections==1,"WDM retains existing upstream connection");
+ check(dshow::connectUpstream(graph.Get(),source.Get(),source.Get())==S_FALSE&&graph->connections==1,"WDM never connects a filter to itself");
+ input->peer=output->peer=nullptr;graph->connectResult=E_ACCESSDENIED;
+ check(dshow::connectUpstream(graph.Get(),upstream.Get(),source.Get())==E_ACCESSDENIED,"WDM connection refusal is propagated, not success");
+ upstream->pinList={wrong.Get()};const unsigned calls=graph->connections;
+ check(FAILED(dshow::connectUpstream(graph.Get(),upstream.Get(),source.Get()))&&graph->connections==calls,"WDM does not attempt another card's medium");
+ ComPtr<IGraphBuilder> realGraph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<Filter> uvc;uvc.Attach(new Filter);uvc->pinList={output.Get()};
+ const bool ready=SUCCEEDED(CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&realGraph)))&&SUCCEEDED(CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&builder)));
+ const auto setup=ready?dshow::connectCaptureCrossbar(realGraph.Get(),builder.Get(),uvc.Get()):dshow::CrossbarSetup{E_FAIL};
+ check(ready&&setup.hr==S_FALSE&&!setup.filter&&setup.inputMediums==0,"ordinary UVC with no upstream input remains untouched");
+ check(dshow::showPropertyPages(nullptr,nullptr,L"test")==E_POINTER&&dshow::showPropertyPages(source.Get(),nullptr,L"test")==E_NOINTERFACE,"missing driver property pages are explicit (no modal window)");
+ check(isBlackmagicCaptureDevice(L"Blackmagic WDM Capture")&&isBlackmagicCaptureDevice(L"Decklink Video Capture")&&!isBlackmagicCaptureDevice(L"USB Video"),"two Blackmagic interface names recognized without merging device IDs");
+ VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=4;vi.bmiHeader.biHeight=4;vi.bmiHeader.biSizeImage=48;vi.AvgTimePerFrame=333667;
+ AM_MEDIA_TYPE t{};t.majortype=MEDIATYPE_Video;t.formattype=FORMAT_VideoInfo2;t.cbFormat=sizeof(vi);t.pbFormat=reinterpret_cast<BYTE*>(&vi);t.subtype={captureFourcc('H','D','Y','C'),0,0x10,{0x80,0,0,0xaa,0,0x38,0x9b,0x71}};
+ CaptureMediaLayout l;check(captureMediaLayout(t,l)&&l.packing==CapturePacking::Uyvy&&l.stride==12&&!l.bottomUp&&l.color.matrix==pipeline::YuvMatrix::BT709&&!l.color.matrixAssumed,"HDYC SD dimensions keep BT709 and native padded UYVY");
+ const auto pKey=captureFormatIdentity(t);vi.dwInterlaceFlags=AMINTERLACE_IsInterlaced|AMINTERLACE_Field1First;
+ const auto iKey=captureFormatIdentity(t);vi.dwInterlaceFlags=AMINTERLACE_IsInterlaced;
+ check(pKey!=iKey&&iKey!=captureFormatIdentity(t),"1080p/i and field order have distinct stable identities");
+ DXVA2_ExtendedFormat ext{};ext.VideoTransferMatrix=DXVA2_VideoTransferMatrix_BT601;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;
+ check(captureMediaLayout(t,l)&&l.color.matrix==pipeline::YuvMatrix::BT601,"explicit HDYC color metadata overrides subtype default");vi.dwControlFlags=0;captureMediaLayout(t,l);
+ std::vector<uint8_t> bytes(l.sampleBytes,255);for(unsigned y=0;y<4;++y)for(unsigned x=0;x<4;x+=2){auto* px=bytes.data()+y*l.stride+x*2;px[0]=px[2]=128;px[1]=px[3]=16;}
+ const auto black=sampleCaptureSignal(l,bytes.data(),bytes.size());
+ check(black.known&&black.blackLike&&black.maximum==16&&black.points==16,"source probe sees limited-range black and ignores padded bytes");
+ CaptureSignalProbeState state;state.observe(black);state.observe(black);check(!state.persistentBlack(),"startup black samples do not immediately warn");state.observe(black);check(state.persistentBlack(),"three low-frequency black samples produce an observation");
+ bytes[1]=180;const auto bright=sampleCaptureSignal(l,bytes.data(),bytes.size());state.observe(bright);
+ check(bright.known&&!bright.blackLike&&!state.persistentBlack(),"source color immediately clears black observation");
+ check(!sampleCaptureSignal(l,bytes.data(),bytes.size()-1).known,"source probe refuses incomplete samples");
+ bytes[1]=16;bytes[0]=220;check(!sampleCaptureSignal(l,bytes.data(),bytes.size()).blackLike,"low luma with chroma is not misreported as black");
+ t.subtype=MEDIASUBTYPE_ARGB32;vi.bmiHeader.biSizeImage=64;captureMediaLayout(t,l);bytes.assign(l.sampleBytes,0);bytes[2]=200;
+ check(!sampleCaptureSignal(l,bytes.data(),bytes.size()).blackLike,"ARGB capture diagnostic ignores unused zero alpha");
+ bytes.assign(l.sampleBytes,0);check(sampleCaptureSignal(l,bytes.data(),bytes.size()).blackLike,"RGB zero-alpha black sample remains measurable");
+}
+}
diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cpp
index 998be866..7d76dfd5 100644
--- a/tests/unit/CaptureColorContractTests.cpp
+++ b/tests/unit/CaptureColorContractTests.cpp
@@ -2,6 +2,7 @@
#include "veyra/source/NativeCaptureSink.h"
#include "CaptureFormatCases.h"
#include "ElgatoHdrCases.h"
+#include "BlackmagicCaptureCases.h"
#include "veyra/sink/AudioFormat.h"
#include <iostream>
#include <vector>
@@ -36,6 +37,7 @@ 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);
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);
diff --git a/tests/unit/CaptureFormatCases.h b/tests/unit/CaptureFormatCases.h
index 585a7750..06c5a4ee 100644
--- a/tests/unit/CaptureFormatCases.h
+++ b/tests/unit/CaptureFormatCases.h
@@ -10,7 +10,7 @@ template<class Check> void captureFormatCases(Check check){
struct Case{GUID id;int bytes;};
const Case cases[]={
{MEDIASUBTYPE_RGB24,48},{MEDIASUBTYPE_RGB32,64},{MEDIASUBTYPE_ARGB32,64},{MEDIASUBTYPE_RGB555,32},{MEDIASUBTYPE_RGB565,32},
- {fourcc("YUY2"),32},{fourcc("UYVY"),32},{fourcc("YVYU"),32},
+ {fourcc("YUY2"),32},{fourcc("UYVY"),32},{fourcc("HDYC"),32},{fourcc("YVYU"),32},
{fourcc("NV12"),24},{fourcc("NV21"),24},{fourcc("I420"),24},{fourcc("IYUV"),24},{fourcc("YV12"),24},
{fourcc("P010"),48},{fourcc("P016"),48}};
for(const auto& item:cases){
diff --git a/tests/unit/CaptureFormatSelectionTests.cpp b/tests/unit/CaptureFormatSelectionTests.cpp
index 0b63b198..3c7d9e74 100644
--- a/tests/unit/CaptureFormatSelectionTests.cpp
+++ b/tests/unit/CaptureFormatSelectionTests.cpp
@@ -11,6 +11,10 @@ int main(){
check(!selectCaptureFormat(formats,2,L"missing"),"missing key never falls back to another format");
check(selectCaptureFormat(formats,2,L"")==&formats[1],"legacy request retains index semantics");
check(!selectCaptureFormat(formats,9,L""),"invalid legacy index rejected");
+ std::array<CaptureFormat,2> scan{{{4,1920,1080,30,L"",L"1080-30:scan=0"},{9,1920,1080,30,L"",L"1080-30:scan=3"}}};
+ check(!selectCaptureFormat(scan,4,L"1080-30"),"ambiguous legacy p30/i60 key must be reselected");
+ check(selectCaptureFormat(scan,4,L"1080-30:scan=3")==&scan[1],"interlace identity overrides stale index");
+ check(selectCaptureFormat(std::span<const CaptureFormat>(scan.data(),1),9,L"1080-30")==&scan[0],"unique legacy scan key migrates safely");
double fps=0;std::wstring key;
for(double requested:{0.,29.97,40.,60.}){
const auto query=capturePathOptions(requested,L"0034004B");