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(capture): add opt-in Blackmagic native input

Veyra Goal Agentaf2edf405285
diff --git a/AGENTS.md b/AGENTS.md
index 2914412c..a37c9891 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-09 BMD 原生修复授权**:用户在原生信号核查后明确“修”,随后要求“做成和美乐威一样的开关”。按 docs/DECKLINK_NATIVE_PLAN_2026-10-09.md,在codex/decklink-native-20261009实现DeckLink COM输入、共享采集/模式恢复、必要10位GPU解包/颜色合同及采集设置开关(美乐威旁、默认关闭、保存选择、重连生效),覆盖这些必要接点的旧冻结。42旧工作树/495脏文件及main0e7018ad按独立start保护。SDK原件/生成头文件留E盘,正式构建须明确传VEYRA_DECKLINK_SDK_DIR,不进Git,不改驱动/运行库/模型/用户配置;无子Agent/测试包/合并/push/Release/关机。没有BMD实卡不得宣称现场已经恢复或延迟收益。实施证据见同轮REPORT。
+
> **2026-10-09 BMD 信号核查**:用户提供 veyra-qml(45).log,要求具体核对 madVR/Blackmagic 官方软件并解释持续黑屏。本轮按 docs/BLACKMAGIC_SIGNAL_RESEARCH_PLAN_2026-10-09.md,在 codex/blackmagic-signal-research-20261009 基于973fc9b隔离记录,只读核对日志、产品源码、固定上游与官方文档;没有新的产品修复/实卡通过声明。独立start保护41既有工作树/495脏文件,产物全E盘;保留“不用打测试包”,不改用户配置/驱动/运行库,不派Agent,不合并/推送/发布/关机。原生DeckLink能力缺口与本例尚未确认的物理原因必须分开。结论见同轮REPORT。
> **2026-10-09 PR31 与播放列表授权**:用户要求处理 PR31 / issue21,播放列表采用文件夹导入、极简底栏按钮、可移动缩放浮窗、拖动排序/单项移除/名称排序/追加拖入/正在播放标记。按 docs/PR31_PLAYLIST_PLAN_2026-10-09.md 在 codex/pr31-playlist-20261009 隔离接入 PR31 的采集音频输出切换修复及必要 UI 模型/bridge/QML/构建/翻译/定向验收;这些具体接点覆盖旧冻结。基于已验字幕分支27cf4b4;独立 start/bundle 保护40既有工作树/495脏文件。产物全E盘、不制作测试包、不派Agent、不改驱动/用户配置/运行库原件。只做本次局部修改,不推进其它增强算法;本轮不发布、关机。每项测试≤300秒,构建≤900秒,当前主线及其它工作树不动。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8122092d..00ef3aca 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -559,6 +559,8 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
src/source/NativeCaptureSink.cpp
src/source/MediaFileSource.cpp
src/source/CaptureCardSource.cpp
+ src/source/DeckLinkCapture.cpp
+ src/source/DeckLinkDriver.cpp
src/source/ElgatoHdrControl.cpp
src/source/ScreenCaptureSource.cpp
src/source/AverMediaAudioSwitch.cpp
@@ -567,6 +569,32 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
src/source/MagewellCapture.cpp
)
veyra_apply_warnings(veyra_sources)
+ # Optional external DeckLink SDK. Generate the official COM ABI outside the
+ # source tree; Desktop Video supplies the installed COM server at run time.
+ set(VEYRA_DECKLINK_SDK_DIR "" CACHE PATH "External DeckLink SDK Win IDL directory")
+ if(VEYRA_DECKLINK_SDK_DIR AND NOT EXISTS "${VEYRA_DECKLINK_SDK_DIR}/DeckLinkAPI.idl")
+ message(FATAL_ERROR "VEYRA_DECKLINK_SDK_DIR must contain the external Win DeckLinkAPI.idl")
+ endif()
+ if(VEYRA_DECKLINK_SDK_DIR AND EXISTS "${VEYRA_DECKLINK_SDK_DIR}/DeckLinkAPI.idl")
+ find_program(VEYRA_MIDL_EXECUTABLE midl REQUIRED)
+ set(VEYRA_DECKLINK_GENERATED "${CMAKE_CURRENT_BINARY_DIR}/decklink-generated")
+ file(MAKE_DIRECTORY "${VEYRA_DECKLINK_GENERATED}")
+ file(GLOB VEYRA_DECKLINK_IDL_DEPENDS "${VEYRA_DECKLINK_SDK_DIR}/*.idl")
+ add_custom_command(OUTPUT "${VEYRA_DECKLINK_GENERATED}/DeckLinkAPI_h.h"
+ COMMAND "${VEYRA_MIDL_EXECUTABLE}" /nologo /env x64 /I "${VEYRA_DECKLINK_SDK_DIR}"
+ /out "${VEYRA_DECKLINK_GENERATED}" /h DeckLinkAPI_h.h
+ /iid DeckLinkAPI_i.c /tlb DeckLinkAPI.tlb /client none /server none
+ "${VEYRA_DECKLINK_SDK_DIR}/DeckLinkAPI.idl"
+ DEPENDS ${VEYRA_DECKLINK_IDL_DEPENDS} VERBATIM)
+ add_custom_target(veyra_decklink_abi DEPENDS "${VEYRA_DECKLINK_GENERATED}/DeckLinkAPI_h.h")
+ add_dependencies(veyra_sources veyra_decklink_abi)
+ set_source_files_properties(src/source/DeckLinkDriver.cpp PROPERTIES
+ COMPILE_DEFINITIONS VEYRA_HAS_DECKLINK=1 INCLUDE_DIRECTORIES "${VEYRA_DECKLINK_GENERATED}")
+ message(STATUS "DeckLink native capture ABI: ${VEYRA_DECKLINK_SDK_DIR}")
+ else()
+ set_source_files_properties(src/source/DeckLinkDriver.cpp PROPERTIES COMPILE_DEFINITIONS VEYRA_HAS_DECKLINK=0)
+ message(STATUS "DeckLink native capture: no SDK configured (DirectShow remains available)")
+ endif()
# Magewell Pro Capture low-latency video: compiled against the vendor SDK headers when
# VEYRA_MAGEWELL_SDK_DIR points at them (kept outside the source tree); LibMWCapture.dll is
# loaded at run time. Without the headers the feature reports itself unavailable.
@@ -623,6 +651,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_source_tests PRIVATE veyra_sources)
add_executable(veyra_capture_tests tests/integration/CaptureSourceTests.cpp)
+ add_executable(veyra_decklink_tests tests/unit/DeckLinkCaptureTests.cpp)
+ target_compile_features(veyra_decklink_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_decklink_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_decklink_tests PRIVATE veyra_sources)
add_executable(veyra_screen_capture_tests tests/integration/ScreenCaptureTests.cpp)
target_compile_features(veyra_screen_capture_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_screen_capture_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 2f54c38c..b9b1d6b3 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -786,3 +786,28 @@ quantization-aware neutral-tint guard, source-color gamut-ray lightness bound,
independent lightness/shadow controls, style-specific automatic coefficients
and an automatic amount slider. These additions are Veyra code; the upstream
port and public-domain matrix attribution above remain unchanged.
+
+## Blackmagic native capture (2026-10-09)
+
+The DeckLink capture lifecycle in `src/source/DeckLinkDriver.cpp` and
+`src/source/DeckLinkCapture.cpp` follows OBS Studio's
+`plugins/decklink/decklink-device-instance.cpp`,
+`decklink-device.cpp` and `win/platform.cpp`, pinned to
+[e7f0b0d43c538f5d108aa4cbea473d57b3012a1a](https://github.com/obsproject/obs-studio/tree/e7f0b0d43c538f5d108aa4cbea473d57b3012a1a/plugins/decklink)
+(OBS Project contributors, GPL-2.0-or-later; Veyra uses GPLv3).
+Veyra moves Pause/Enable/Flush/Start to the owner thread, validates the first
+real frame, distinguishes no-input frames from valid black pixels, preserves
+source timestamps and HDR metadata, and reuses its bounded upload mailbox and
+audio session. Device selection uses persistent/topological IDs plus subdevice
+identity. No OBS binary, driver, EDID writes or VideoProcessor code is included.
+
+Build-time COM declarations come from the unmodified Blackmagic DeckLink SDK
+12.0 Win IDL files supplied by OBS 31.0.3, pinned to
+[fcd1910bf5116b69404a6ecdda6efedd1d00ebdf](https://github.com/obsproject/obs-studio/tree/fcd1910bf5116b69404a6ecdda6efedd1d00ebdf/plugins/decklink/win/decklink-sdk).
+Copyright (c) 2021 Blackmagic Design; the permissive license is retained in
+those external SDK files. They and generated headers remain outside the source
+repository. Build with `VEYRA_DECKLINK_SDK_DIR` pointing at the Win IDL directory;
+without it, the native backend is unavailable and DirectShow remains usable.
+The runtime uses the user's installed Desktop Video COM server; no driver DLL
+or SDK is bundled. `PackedCaptureToLinear.hlsl` implements the documented v210
+and R10l layouts using Veyra's existing HDR color functions and GPU ingress.
diff --git a/docs/DECKLINK_NATIVE_PLAN_2026-10-09.md b/docs/DECKLINK_NATIVE_PLAN_2026-10-09.md
new file mode 100644
index 00000000..4c2fb851
--- /dev/null
+++ b/docs/DECKLINK_NATIVE_PLAN_2026-10-09.md
@@ -0,0 +1,16 @@
+# BMD 原生采集修复
+
+用户在本轮信号排查后明确要求“修”。本轮从 `1d7cd55` 在 `codex/decklink-native-20261009` 隔离实现必要 DeckLink 输入、共享采集接点、模式变化恢复、GPU 10位输入解包及 UI 提示;不推进其它补帧/NR算法。当前授权覆盖这些必要 source/engine/pipeline/shader/CMake 接点的历史冻结。
+
+开工保全 `E:/项目/Veyra/archives/decklink-native-20261009/start.json`:42个既有工作树、495脏文件、main `0e7018ad` 不动。增量源码bundle以 `973fc9b` 为前提,对应完整基包仍在上一轮 archives/blackmagic-signal-research-20261009/source-before.bundle,不重复制作整工程副本。
+
+## 实现合同
+
+1. 对照已固定 OBS DeckLink 实现,使用官方稳定12.0 COM ABI(SDK由OBS31.0.3固定提交fcd1910bf5116b69404a6ecdda6efedd1d00ebdf提供原件,E盘生成头文件;SDK/驱动不入Git)。Windows使用已安装Desktop Video COM服务,不捆绑或修改驱动。
+2. 用户追加“做成和美乐威一样的开关”:采集设置增加“Blackmagic 原生采集”,默认关闭;开启显示带型号/当前输入口的原生设备,关闭恢复DirectShow入口,切换需重连。保存用户明确选过的两种接口设备身份;多原生设备不猜映射,唯一原生设备可明确选中。原生优先自动检测,老卡保留手动制式。使用persistent/topological ID(含子设备),不以ordinal猜设备;HDMI/SDI跟随Desktop Video Setup,不写驱动配置/EDID。
+3. 配置期有界识别真实模式与有效帧,所有HRESULT、实际制式/位深/像素格式/扫描/信号标记进日志。回调不调用停止重配、不持源锁调用驱动;控制在所有者线程执行。有效黑画面正常交付,no-input帧不当作有效画面。模式/颜色合同变化走既有恢复及共享图重建/reset。
+4. 复用现有三帧存储、容量1mailbox/上传帧/真实PTS;不增加固定排队、逐帧CPU fence wait或GPU像素回读。内置PCM音频复用CaptureAudioSession;独立WASAPI沿现有路径,端点恢复保留。
+5. 对常见v210/10-bit RGBXLE只在明确新格式合同下GPU解包,保留PQ/HLG/色域/峰值元数据;不全局放开旧8位packed HDR限制,不把10/12位输入静默当8位SDR。不能支持的驱动模式明确失败/手动回退。
+6. 驱动抽象允许真实产品状态机注入假驱动验证无卡/自动模式/无信号/格式重配/错误/超时/停止/有界资源等;GPU独立验证10位打包、范围、颜色、HDR和旧格式,原普通USB/音频定向回归。不得把这些测试冒充受影响BMD卡验收。
+
+所有新构建/测试/日志/临时/依赖位于 `E:/项目/Veyra/{build,tests,logs,tmp,reports,deps,downloads,archives,worktrees}/decklink-native-20261009` 或已列的 `deps/decklink-sdk-obs31-20261009`。每测试≤300秒、构建≤900秒。不派Agent,不改用户配置/运行库/模型,不打测试包、不merge/push/Release/关机。完成后记录实际命令、失败修复、哈希及实卡限制。
diff --git a/docs/DECKLINK_NATIVE_REPORT_2026-10-09.md b/docs/DECKLINK_NATIVE_REPORT_2026-10-09.md
new file mode 100644
index 00000000..5a8c7931
--- /dev/null
+++ b/docs/DECKLINK_NATIVE_REPORT_2026-10-09.md
@@ -0,0 +1,74 @@
+# Blackmagic 原生采集开关与本机验证
+
+用户要求修复持续黑屏,并追加“做成和美乐威一样的开关”。已在 `codex/decklink-native-20261009` 实现并构建;原生接口、GPU 解包、界面及普通 USB 回归通过。**本机没有 BMD 卡,尚不能宣称反馈者的黑屏已恢复或实测延迟降低。** 未打测试包、合并 main、推送或发布。
+
+## 使用行为
+
+- 采集设置中,“Blackmagic 原生采集”位于“美乐威低延迟模式”旁,默认关闭,保存选择。选中 BMD 时可启用;普通 USB 卡不会被当成 BMD。
+- 关闭使用原来的 DirectShow;开启后重新选择原生设备、格式并连接。设置不会立即中断正在播放的来源。两种接口分别记住明确使用过的设备身份,多张原生卡不猜映射。
+- 支持的卡可选自动检测;不支持自动的卡保留手动制式。HDMI/SDI 沿用 Desktop Video Setup,本功能不改驱动永久配置、端口或 EDID。
+- 原生路径先确认真实有效帧。无输入标志、模式/颜色变化和驱动错误有明确日志;有效黑画面仍正常交付。输入改变时沿已有恢复/处理图重建流程重置历史。
+
+## 对原故障的判断
+
+上一轮核对 `veyra-qml(45).log`:10-09 的 9 次配置全部启用了前次兼容接收器,已记录的 41 次原始 CPU 样本抽样均为黑场值,位置在上传/GPU 处理前。这个证据排除了“只是 NR 或后续渲染把正常输入变黑”的解释,也说明前次 allocator 修改在现场未解决问题。
+
+配置成功和持续回调不能证明 HDMI/SDI 信号有效。新增原生路径补上此前缺少的实际模式、RGB/YUV/位深回调及 no-input/lock 诊断,避免继续只凭枚举模式猜输入。本例具体是输入口、制式/颜色错配还是 DirectShow 驱动兼容,仍需实卡日志确认;用户反馈 OBS 通用来源也可出画,不能据此宣称 DirectShow 天然不可用。研究证据详见 `BLACKMAGIC_SIGNAL_RESEARCH_REPORT_2026-10-09.md`。
+
+## 实现与延迟边界
+
+使用已安装 Desktop Video 的 COM 服务;稳定 persistent/topological ID 包含子设备身份,重复身份拒绝使用。配置/重配在所有者线程,回调只提交状态或交付样本;停止先分离并等回调退出,再释放采集/音频存储。
+
+自动检测沿 OBS 的 Pause → Enable → Flush → Start 顺序重配;有效帧等待默认 2.5 秒,上限 5 秒,属于连接阶段等待,不是逐帧缓存,也不包含驱动自身 COM 调用耗时。回归另覆盖驱动在 EnableVideoInput 中就报告新制式的情况。
+
+复用现有三个帧存储和容量 1 mailbox;原生回调一次完整 CPU ingest copy,可直接写入现有 D3D12 upload buffer,未新增常驻 FIFO、逐帧 CPU fence wait 或 GPU 像素回读。10 位 v210/RGBXLE 走共享 GPU 解包,正确处理行距、范围、PQ/HLG 和 BT.2020;旧 8 位 packed HDR 防错保持。仅 SDR 可回退 8 位,不支持的 HDR 元数据/EOTF 明确失败。GPU→CPU 读回仅用于颜色测试。
+
+原生内置音频当前协商 48kHz/16-bit/stereo,复用 CaptureAudioSession;用户指定的独立 WASAPI/DirectShow 音频沿原路径。不宣称原生多声道、专门去隔行、BMD 全型号或真实输入到屏幕延迟已验收。
+
+## 构建与验证证据
+
+工作树 `E:/项目/Veyra/worktrees/decklink-native-20261009`,基线 `1d7cd55`。全部新产物在 `E:/项目/Veyra/{build,tests,logs,tmp,reports,archives}/decklink-native-20261009`;SDK 位于 `E:/项目/Veyra/deps/decklink-sdk-obs31-20261009`。
+
+| 检查 | 结果与证据(logs/decklink-native-20261009 下) |
+|---|---|
+| 完整产品与定向测试构建 | `build-20261009-203938/receipt.json`;保留此前全部已验 HDR/字幕/PR31/播放列表对象,按当前头文件依赖闭包重新编译/校验,旧缓存只读 |
+| 最终 UI/翻译增量构建 | `build-20261009-205406/receipt.json`;18.953 秒,非 UI 测试 EXE 哈希前后不变 |
+| CMake 集成 | `build-20261009-204033/receipt.json`;原生 SDK 与不配 SDK 两种全工程配置成功,分别经 CMake 实际编译适配器对象,SDK 头文件经 MIDL 生成 |
+| 原生产品状态机 | `tests-20261009-204033/receipt.json`;SDK/no-SDK 两个变体各 25 项通过,含真实回调线程、早期检测、无信号、有效黑场、精确时间、格式/HDR变化、错误/超时/停止释放及无驱动显式失败 |
+| 旧采集颜色/格式 | 同上;261 项颜色合同通过,格式身份/排序测试 exit 0 |
+| 实际 GPU 颜色 | 同上;148 条通过记录,包含 24 组新增 10 位测试:v210/RGBXLE × full/limited × SDR/PQ/HLG × CPU/upload 帧,对照独立双精度参考;日志无 pass=0 / D3D12 ERROR / CORRUPTION |
+| 普通 USB 源帧率/重连 | `tests-20261009-204508/receipt.json`;KUHAIMI 27P 1080p60,重连前后回调 59.926940 / 59.997117 FPS,361 / 362 次读取,PTS 均递增 |
+| 既有音频恢复 | 同上;真实静音 WASAPI A→B→A→默认/重复选择、端点丢失、慢启动、瞬态、Xbox float/RTP 五项通过;Windows 默认端点未改 |
+| 实际界面开关 | `gui-switch-20261009-205501/receipt.json`;新配置默认关闭、保存开启后重启恢复、经生产开关关闭、列表过滤、无驱动提示、普通卡隔离和英文三阶段通过,无 QML 错误 |
+| 最终 GUI 普通 USB 实采 | `gui-usb-20261009-205516/receipt.json`;11.953 秒,连接/播放/截图/断开通过,回调 59.938308 FPS |
+| 翻译 | `reports/decklink-native-20261009/translations.json`;新增 41 键均有繁中/英文/日文,2106 个原条目未变,占位符错误 0;仍有 29 个遗留缺译,不冒称全项目翻译完成 |
+
+命令均在本工作树执行:
+
+```text
+python -B scripts/acceptance/decklink-native-build.py
+python -B scripts/acceptance/decklink-native-build.py cmake-check
+python -B scripts/acceptance/decklink-native-build.py ui-only
+python -B scripts/acceptance/decklink-native-test.py native no-sdk legacy-color selection gpu usb-rate endpoint-switch endpoint-loss slow-start transient xbox-float-rtp
+python -B scripts/acceptance/decklink-native-test.py usb-rate endpoint-switch endpoint-loss slow-start transient xbox-float-rtp
+python -B scripts/acceptance/decklink-native-gui-test.py switch
+python -B scripts/acceptance/decklink-native-gui-test.py usb
+python -B scripts/i18n/extract.py --check
+python -B scripts/acceptance/decklink-native-control.py final
+```
+
+最终 GUI SHA256:`30B0898A97E101E7C9E5A46AACCD9BD16E56AE6F539D35B4917E41227D710D7D`。两个最终 GUI 回执使用同一 EXE,并各自核对原便携包 1614 文件哈希不变;全部用户配置在 E 盘私有 profile。截图和证据在对应 logs 目录。
+
+## 构建接入与来源
+
+后续正常构建必须显式配置 `-DVEYRA_DECKLINK_SDK_DIR=<外部 Win IDL 目录>`。未指定则编译不可用的原生 stub,DirectShow 仍可用;指定无效目录则 CMake 明确失败。不能只带 UI 就声称原生后端已随包构建。MIDL 生成头文件只在 binary dir,不进入源码 Git。
+
+生命周期改造来源为 [OBS e7f0b0d 的 DeckLink 插件](https://github.com/obsproject/obs-studio/tree/e7f0b0d43c538f5d108aa4cbea473d57b3012a1a/plugins/decklink),GPL-2.0-or-later;SDK 12.0 Win IDL 原件来自 [OBS 31.0.3 固定提交 fcd1910b](https://github.com/obsproject/obs-studio/tree/fcd1910bf5116b69404a6ecdda6efedd1d00ebdf/plugins/decklink/win/decklink-sdk),许可/来源见 THIRD_PARTY_NOTICES。未搬入带非商业限制的 VideoProcessor 代码,无驱动或 SDK 分发、运行库修改。
+
+## 失败记录与收尾
+
+首轮局部构建暴露旧静态库依赖闭包遗漏、SDK 枚举名不符、链接工作目录相对库路径、音频测试误引入无关编码对象,均修正后重新编译/链接,失败 build 日志保留。不将首轮失败当作通过。CMake 检查首次错误指向仅有 DLL/DEF 的 patched FFmpeg runtime prefix,改用已验 MSVC import-library prefix 后两种配置通过,运行仍用已验含 zlib/PS5 slice 补丁的同版本 FFmpeg。
+
+帧率测试首次进程 exit 0、两段 PASS,审计脚本却把 `PASS RATE pass=0` 的阶段编号当 GPU 布尔失败;现仅对 GPU 记录解释 pass=0,原日志保留,真实 USB 重测通过后继续音频回归。首次复用旧 GUI 脚本将单张测试截图写到 Pictures,已按精确路径/哈希移入本轮 E 盘 evidence;之后私有 profile 显式设置 screenshotDir,新截图全在 E 盘,未移动用户文件。
+
+范围守卫保护的 42 个既有工作树、495 个脏文件和 main `0e7018ad` 保持原样。最终回执/源码提交/bundle 信息见 `E:/项目/Veyra/reports/decklink-native-20261009/final.json`。实卡仍需验证实际输入锁定、自动/手动出画、拔插/制式切换和输入到屏幕延迟。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index f4eac640..897f1674 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -8948,3 +8948,16 @@ media, SDK files or runtime binaries.
判断:已确定上游抽样就黑、上次allocator候选现场未解决;确定Veyra缺原生检测状态/模式回调。没有实际input-lock/检测制式/no-input标志,不能断言仅为制式或输入口错误。用户反馈OBS通用也可出画,是反对“DirectShow天然不可用”的证据;具体图/模式/输入差异仍需同源对照。本机PnP无Blackmagic/DeckLink记录,只有Blackmagic RAW安装目录,不冒称BMD实卡验收。报告与后续原生输入适配验收合同见docs/BLACKMAGIC_SIGNAL_RESEARCH_REPORT_2026-10-09.md和同轮PLAN;拟沿共享图/容量1mailbox/显式reset、保留手动和DSHOW回退,不盲切端口/写EDID,不能承诺原生接口自动根治或延迟收益。
产物统一E:/项目/Veyra/{tmp,reports,downloads,archives,worktrees}/blackmagic-signal-research-20261009;audit.py核对日志统计、源码原件SHA、原始像素采样位置、范围/41工作树/495脏文件和main,回执reports/.../final-audit.json。audit首轮错误匹配了接口前置声明而非Impl方法,位置断言失败,改为匹配完整实现签名后重验,未修改产品来迁就审计。产品源码、驱动、用户配置、运行库未修改,无产品改动不重复构建/GPU测试;无测试包、合并、push/Release或关机。
+
+## 2026-10-09 BMD 原生采集与美乐威旁的可保存开关
+
+用户在研究后要求“修”,追加“做成和美乐威一样的开关”。从1d7cd55隔离到codex/decklink-native-20261009,计划/报告为docs/DECKLINK_NATIVE_PLAN_2026-10-09.md和docs/DECKLINK_NATIVE_REPORT_2026-10-09.md。E盘archives/decklink-native-20261009/start.json保全42旧工作树/495脏文件/main0e7018ad;无子Agent、测试包、main合并、push/Release或关机。
+
+- 新增DeckLink COM后端和可注入产品状态机,使用Desktop Video已安装驱动;真实自动/手动制式、稳定设备/子设备身份、重复ID拒绝、no-input/有效黑场区别、实际时间/行距/HDR元数据、所有者线程重配及回调退出后释放。复用共享CaptureCardSource、三帧存储和容量1mailbox,不新增固定排队/逐帧fence wait/GPU回读。内置PCM及独立音频复用原音频层。
+- 共享GPU支持明确的新v210/RGBXLE10合同,保留PQ/HLG/色域与旧8位HDR防错;模式/颜色变更走现有恢复和图重建/reset。采集设置中新增Blackmagic原生开关,美乐威旁、默认关、保存选择、重连生效;关闭回DirectShow,两接口独立记住设备,多设备不猜映射,不写端口/EDID/驱动配置。新41个显示键均补繁中/英文/日文,原2106条目未变,placeholder0;遗留缺译29未扩改。
+- `python -B scripts/acceptance/decklink-native-build.py`最终全产品/测试构建成功,回执logs/decklink-native-20261009/build-20261009-203938/receipt.json;`...build.py ui-only`更新最终UI/翻译,18.953秒,回执build-20261009-205406/receipt.json,非UI EXE哈希不变。GUI SHA256 30B0898A97E101E7C9E5A46AACCD9BD16E56AE6F539D35B4917E41227D710D7D。保留已验字幕/HDR/PR31/播放列表对象,依赖头文件闭包重新编译/校验,旧缓存只读。`...build.py cmake-check`原生/no-SDK两种完整配置及适配器对象实际编译成功,回执build-20261009-204033/receipt.json。正常构建须明确传VEYRA_DECKLINK_SDK_DIR;SDK12.0原件与MIDL生成头文件均在E盘,来源/改造/许可证已记THIRD_PARTY_NOTICES。
+- `python -B scripts/acceptance/decklink-native-test.py native no-sdk legacy-color selection gpu usb-rate endpoint-switch endpoint-loss slow-start transient xbox-float-rtp`前五项通过:两个变体各25项、旧颜色261项、格式exit0、GPU148条通过记录含24组新增10位CPU/upload×SDR/PQ/HLG×range测试,回执tests-20261009-204033/receipt.json。帧率阶段进程PASS却被脚本将pass=0编号误认布尔失败;修正审计正则后执行`...test.py usb-rate endpoint-switch endpoint-loss slow-start transient xbox-float-rtp`全部通过,回执tests-20261009-204508/receipt.json。实际KUHAIMI 27P重连前后59.926940/59.997117回调FPS,PTS递增;真实静音WASAPI端点切换/丢失/慢启/瞬态/Xbox float-RTP回归通过,未改Windows默认端点。
+- `python -B scripts/acceptance/decklink-native-gui-test.py switch`三阶段通过,默认关/保存重启/生产开关关闭/普通卡隔离/无驱动状态/英文,无QML错误;回执gui-switch-20261009-205501/receipt.json。`...gui-test.py usb`最终GUI1080p60连接/播放/截图/断开通过,59.938308回调FPS,回执gui-usb-20261009-205516/receipt.json。每次前后原便携包1614文件SHA不变,配置为E盘私有profile。初次旧GUI脚本截图落Pictures,已核验精确路径/哈希后移到E盘本轮evidence,新私有profile明确指定E盘screenshotDir。
+- 初次构建依赖闭包/SDK枚举名/相对链接库路径/音频无关对象问题与CMake误用DLL-only FFmpeg前缀均修复后重验,失败日志仍在logs任务目录;不是产品通过证明。最终审查另修正EnableVideoInput早期制式回调丢失、10位RGB极白粗亮度样本溢出、未知HDR EOTF误作SDR、原生重连后名义帧率刷新等边界,均在上述最终构建/相应回归中。产物全在E:/项目/Veyra/{build,tests,logs,tmp,reports,archives}/decklink-native-20261009,SDK另在deps/decklink-sdk-obs31-20261009;无运行库/模型修改或SDK/二进制入Git。
+
+本机无BMD卡。以上证明本机产品状态机/GPU/UI及旧USB/音频回归,不是反馈者出画、BMD全型号/多声道/去隔行或实测延迟证明。原日志已定位到上游样本抽样黑,具体信号/驱动原因仍需新原生日志,不能以原生接入自动宣称根治。最终范围守卫、源码提交/checkpoint和增量bundle见reports/decklink-native-20261009/final.json。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 4e47e8f9..9c630449 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -14743,6 +14743,293 @@
"zh-TW": "關閉視窗",
"en": "Close window",
"ja": "ウィンドウを閉じる"
+ },
+ {
+ "zh": "Blackmagic 原生采集",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "Blackmagic 原生擷取",
+ "en": "Blackmagic native capture",
+ "ja": "Blackmagic ネイティブキャプチャ"
+ },
+ {
+ "zh": "默认关闭。开启使用 DeckLink 原生接口,关闭使用 DirectShow。需安装 Desktop Video 驱动;切换后重新选择设备和格式并连接,不写入驱动永久配置。",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "預設關閉。開啟使用 DeckLink 原生介面,關閉使用 DirectShow。需要 Desktop Video 驅動;切換後重新選擇裝置及格式並連線,不寫入驅動永久設定。",
+ "en": "Off by default. On uses DeckLink; off uses DirectShow. Requires Desktop Video. Reselect the device and format, then reconnect. Driver preferences are not changed.",
+ "ja": "既定はオフです。オンで DeckLink、オフで DirectShow を使用します。Desktop Video が必要です。切り替え後にデバイスと形式を選び直して接続してください。ドライバーの永続設定は変更しません。"
+ },
+ {
+ "zh": "原生采集跟随 Desktop Video Setup 的 HDMI/SDI 输入。支持自动检测的卡建议选择自动;信号未锁定时会明确提示。",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "原生擷取沿用 Desktop Video Setup 的 HDMI/SDI 輸入。支援自動偵測的卡建議選擇自動;訊號未鎖定時會明確提示。",
+ "en": "Native capture follows the HDMI/SDI input selected in Desktop Video Setup. Choose automatic detection when supported. An unlocked signal is reported explicitly.",
+ "ja": "Desktop Video Setup で選んだ HDMI/SDI 入力を使用します。対応カードは自動検出を推奨します。信号がロックされていない場合は明示します。"
+ },
+ {
+ "zh": "Blackmagic 两个条目可能属于同一张卡。DirectShow 黑屏可尝试下方原生采集开关;手动格式须匹配实际信号。",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "Blackmagic 兩個項目可能屬於同一張卡。DirectShow 黑畫面可嘗試下方原生擷取開關;手動格式須符合實際訊號。",
+ "en": "Both Blackmagic entries may refer to one card. If DirectShow is black, try native capture below. Manual formats must match the input signal.",
+ "ja": "Blackmagic の二つの項目が同じカードを指す場合があります。DirectShow が黒画面になる場合は下のネイティブキャプチャを試してください。手動形式は実際の信号に合わせます。"
+ },
+ {
+ "zh": "请等待采集设备查询完成后再切换接口",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "請等待擷取裝置查詢完成後再切換介面",
+ "en": "Wait for device discovery to finish before switching interfaces.",
+ "ja": "デバイスの検索が完了してから切り替えてください。"
+ },
+ {
+ "zh": "请选择 BMD 原生设备;若列表中没有,请安装 Desktop Video 驱动。多个设备不会自动猜选。",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "請選擇 BMD 原生裝置;若清單中沒有,請安裝 Desktop Video 驅動。多個裝置不會自動猜選。",
+ "en": "Select a native BMD device. If none is listed, install Desktop Video. Multiple devices are never selected by guesswork.",
+ "ja": "BMD ネイティブデバイスを選んでください。表示されない場合は Desktop Video をインストールしてください。複数のデバイスは自動で推測選択しません。"
+ },
+ {
+ "zh": "原生采集先确认有效信号;支持自动检测的卡建议选择自动。HDMI/SDI 跟随 Desktop Video Setup。",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "原生擷取先確認有效訊號;支援自動偵測的卡建議選擇自動。HDMI/SDI 沿用 Desktop Video Setup。",
+ "en": "Native capture first verifies a valid signal. Use automatic detection when supported. HDMI/SDI follows Desktop Video Setup.",
+ "ja": "有効な信号を確認してからキャプチャします。対応カードは自動検出を使用してください。HDMI/SDI は Desktop Video Setup に従います。"
+ },
+ {
+ "zh": "采集接口已切换,请刷新并重新选择设备和格式",
+ "src": "qml/Veyra/DialogHost.qml;src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "擷取介面已切換,請重新整理並選擇裝置及格式",
+ "en": "Capture interface changed. Refresh and reselect the device and format.",
+ "ja": "キャプチャのインターフェイスが変更されました。更新してデバイスと形式を選び直してください。"
+ },
+ {
+ "zh": "BMD HDR 帧的 EOTF 不受支持;仅接受 SDR、PQ 或 HLG,拒绝猜测颜色传递",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD HDR 影格的 EOTF 不受支援;僅接受 SDR、PQ 或 HLG,不猜測色彩傳遞",
+ "en": "Unsupported BMD EOTF. Only SDR, PQ and HLG are supported; the transfer function will not be guessed.",
+ "ja": "BMD の EOTF は未対応です。SDR、PQ、HLG のみ対応し、伝達関数の推測は行いません。"
+ },
+ {
+ "zh": "BMD HDR 需要 10 位原生输入格式",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "BMD HDR 需要 10 位元原生輸入格式",
+ "en": "BMD HDR requires a native 10-bit input format.",
+ "ja": "BMD HDR にはネイティブ 10 ビット入力形式が必要です。"
+ },
+ {
+ "zh": "BMD PCM 音频配置失败;视频继续运行",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "BMD PCM 音訊設定失敗;視訊繼續執行",
+ "en": "BMD PCM audio configuration failed; video continues.",
+ "ja": "BMD PCM 音声の設定に失敗しました。映像は継続します。"
+ },
+ {
+ "zh": "BMD 制式回调异常",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 制式回呼異常",
+ "en": "BMD format callback failed.",
+ "ja": "BMD 形式コールバックでエラーが発生しました。"
+ },
+ {
+ "zh": "BMD 原生入口跟随 Desktop Video Setup 的 HDMI/SDI 输入设置;请在该程序选择输入口,再使用自动检测或手动制式。",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "BMD 原生入口沿用 Desktop Video Setup 的 HDMI/SDI 輸入設定;請在該程式選擇輸入埠,再使用自動偵測或手動制式。",
+ "en": "Native BMD capture uses the HDMI/SDI input selected in Desktop Video Setup. Select the input there, then use automatic detection or a manual format.",
+ "ja": "BMD ネイティブ入力は Desktop Video Setup の HDMI/SDI 設定に従います。同アプリで入力を選び、自動検出または手動形式を使用してください。"
+ },
+ {
+ "zh": "BMD 原生接口 {} 失败(0x{:08X}),请检查驱动、输入制式和设备占用",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 原生介面 {} 失敗(0x{:08X}),請檢查驅動、輸入制式與裝置占用",
+ "en": "BMD native API {} failed (0x{:08X}). Check the driver, input format and device access.",
+ "ja": "BMD ネイティブ API {} が失敗しました(0x{:08X})。ドライバー、入力形式、デバイスの使用状況を確認してください。"
+ },
+ {
+ "zh": "BMD 原生接口不可用,请安装 Desktop Video 驱动或使用 DirectShow 入口",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 原生介面無法使用,請安裝 Desktop Video 驅動或使用 DirectShow 入口",
+ "en": "Native BMD capture is unavailable. Install Desktop Video or use DirectShow.",
+ "ja": "BMD ネイティブ入力を使用できません。Desktop Video をインストールするか DirectShow を使用してください。"
+ },
+ {
+ "zh": "BMD 实际信号为 {:.3f} FPS,与请求的 {:.3f} FPS 不一致;设为 0 可跟随实际信号",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "BMD 實際訊號為 {:.3f} FPS,與要求的 {:.3f} FPS 不一致;設為 0 可沿用實際訊號",
+ "en": "BMD signal is {:.3f} FPS, but {:.3f} FPS was requested. Set 0 to follow the signal.",
+ "ja": "BMD の実信号は {:.3f} FPS ですが、要求値は {:.3f} FPS です。0 に設定すると実信号に従います。"
+ },
+ {
+ "zh": "BMD 帧回调异常",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 影格回呼異常",
+ "en": "BMD frame callback failed.",
+ "ja": "BMD フレームコールバックでエラーが発生しました。"
+ },
+ {
+ "zh": "BMD 帧布局已改变,正在重新协商采集",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 影格配置已變更,正在重新協商擷取",
+ "en": "BMD frame layout changed; renegotiating capture.",
+ "ja": "BMD フレーム配置が変わりました。キャプチャを再設定しています。"
+ },
+ {
+ "zh": "BMD 无法读取有效画面或源时间戳",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 無法讀取有效畫面或來源時間戳記",
+ "en": "BMD could not read valid video or source timestamps.",
+ "ja": "BMD の有効な映像またはソースのタイムスタンプを取得できません。"
+ },
+ {
+ "zh": "BMD 未检测到有效输入。请关闭占用采集卡的应用,并在 Desktop Video Setup 核对 HDMI/SDI 和制式;也可选择手动制式",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 未偵測到有效輸入。請關閉占用擷取卡的應用程式,並在 Desktop Video Setup 核對 HDMI/SDI 與制式;也可選擇手動制式",
+ "en": "BMD found no valid input. Close other capture apps and check HDMI/SDI and format in Desktop Video Setup. A matching manual format can also be selected.",
+ "ja": "BMD の有効な入力が見つかりません。他のキャプチャアプリを終了し、Desktop Video Setup の HDMI/SDI と形式を確認してください。対応する手動形式も選択できます。"
+ },
+ {
+ "zh": "BMD 标记 HDR,但驱动未提供 HDR 元数据接口",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 標記 HDR,但驅動未提供 HDR 中繼資料介面",
+ "en": "BMD reports HDR, but the driver provides no HDR metadata interface.",
+ "ja": "BMD は HDR を報告していますが、ドライバーに HDR メタデータのインターフェイスがありません。"
+ },
+ {
+ "zh": "BMD 输入不支持所选制式/像素格式",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 輸入不支援所選制式/像素格式",
+ "en": "BMD input does not support the selected video/pixel format.",
+ "ja": "BMD 入力は選択した映像/ピクセル形式に対応していません。"
+ },
+ {
+ "zh": "BMD 输入信号丢失,正在等待 HDMI/SDI 信号锁定",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 輸入訊號遺失,正在等待 HDMI/SDI 訊號鎖定",
+ "en": "BMD input signal lost; waiting for HDMI/SDI signal lock.",
+ "ja": "BMD 入力信号が失われました。HDMI/SDI の信号ロックを待っています。"
+ },
+ {
+ "zh": "BMD 输入制式/颜色格式已变化,正在重新检测信号",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 輸入制式/色彩格式已變更,正在重新偵測訊號",
+ "en": "BMD input mode/color format changed; detecting the signal again.",
+ "ja": "BMD 入力モード/色形式が変わりました。信号を再検出しています。"
+ },
+ {
+ "zh": "BMD 输入颜色/行距合同已变化,正在重建处理链",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 輸入色彩/列距契約已變更,正在重建處理鏈",
+ "en": "BMD input color/stride changed; rebuilding the processing chain.",
+ "ja": "BMD 入力の色/行ストライドが変わりました。処理パイプラインを再構築しています。"
+ },
+ {
+ "zh": "BMD 返回无效帧布局、时间戳或不受支持的 HDR 位深",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "BMD 傳回無效影格配置、時間戳記或不受支援的 HDR 位元深度",
+ "en": "BMD returned an invalid frame layout, timestamp or unsupported HDR bit depth.",
+ "ja": "BMD が無効なフレーム配置、タイムスタンプ、または未対応の HDR ビット深度を返しました。"
+ },
+ {
+ "zh": "BMD 返回未支持的像素格式",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 傳回未支援的像素格式",
+ "en": "BMD returned an unsupported pixel format.",
+ "ja": "BMD が未対応のピクセル形式を返しました。"
+ },
+ {
+ "zh": "BMD 返回未知颜色空间",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "BMD 傳回未知色彩空間",
+ "en": "BMD returned an unknown color space.",
+ "ja": "BMD が不明な色空間を返しました。"
+ },
+ {
+ "zh": "BMD 采集帧缓冲分配失败",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "BMD 擷取影格緩衝配置失敗",
+ "en": "BMD capture frame allocation failed.",
+ "ja": "BMD キャプチャフレームのメモリ確保に失敗しました。"
+ },
+ {
+ "zh": "WASAPI 音频端点无效;视频继续运行",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "WASAPI 音訊端點無效;視訊繼續執行",
+ "en": "WASAPI audio endpoint is unavailable; video continues.",
+ "ja": "WASAPI 音声エンドポイントを使用できません。映像は継続します。"
+ },
+ {
+ "zh": "[原生] {} · {}",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "[原生] {} · {}",
+ "en": "[Native] {} · {}",
+ "ja": "[ネイティブ] {} · {}"
+ },
+ {
+ "zh": "{} · {} x {} @ {:.3f} fps · {} · BMD 原生",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "{} · {} x {} @ {:.3f} fps · {} · BMD 原生",
+ "en": "{} · {} x {} @ {:.3f} fps · {} · Native BMD",
+ "ja": "{} · {} x {} @ {:.3f} fps · {} · BMD ネイティブ"
+ },
+ {
+ "zh": "保存的 BMD 制式不可用,请重新选择",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "儲存的 BMD 制式無法使用,請重新選擇",
+ "en": "Saved BMD format is unavailable. Select a format again.",
+ "ja": "保存された BMD 形式を使用できません。形式を選び直してください。"
+ },
+ {
+ "zh": "保存的 BMD 制式已不可用,请刷新并重新选择",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "儲存的 BMD 制式已無法使用,請重新整理並選擇",
+ "en": "Saved BMD format is no longer available. Refresh and select a format again.",
+ "ja": "保存された BMD 形式は利用できなくなりました。更新して選び直してください。"
+ },
+ {
+ "zh": "未找到该 BMD 原生设备,请安装 Desktop Video 驱动并刷新设备列表",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "找不到該 BMD 原生裝置,請安裝 Desktop Video 驅動並重新整理裝置清單",
+ "en": "Native BMD device not found. Install Desktop Video and refresh the device list.",
+ "ja": "BMD ネイティブデバイスが見つかりません。Desktop Video をインストールし、デバイス一覧を更新してください。"
+ },
+ {
+ "zh": "独立采集音频配置失败;BMD 原生视频继续运行",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "獨立擷取音訊設定失敗;BMD 原生視訊繼續執行",
+ "en": "Separate capture audio configuration failed; native BMD video continues.",
+ "ja": "独立したキャプチャ音声の設定に失敗しました。BMD ネイティブ映像は継続します。"
+ },
+ {
+ "zh": "自动检测实际信号 · BMD 原生",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "自動偵測實際訊號 · BMD 原生",
+ "en": "Detect input automatically · Native BMD",
+ "ja": "入力信号を自動検出 · BMD ネイティブ"
+ },
+ {
+ "zh": "跟随驱动输入",
+ "src": "src/source/DeckLinkDriver.cpp",
+ "zh-TW": "沿用驅動輸入",
+ "en": "Driver input",
+ "ja": "ドライバーの入力設定"
+ },
+ {
+ "zh": "这张 BMD 卡不支持自动检测,请选择与信号一致的手动制式",
+ "src": "src/source/DeckLinkCapture.cpp",
+ "zh-TW": "這張 BMD 卡不支援自動偵測,請選擇與訊號一致的手動制式",
+ "en": "This BMD card does not support automatic detection. Select the manual format matching the signal.",
+ "ja": "この BMD カードは自動検出に対応していません。信号に一致する手動形式を選んでください。"
+ },
+ {
+ "zh": "逐行",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "循序",
+ "en": "Progressive",
+ "ja": "プログレッシブ"
+ },
+ {
+ "zh": "隔行",
+ "src": "src/source/CaptureCardSource.cpp",
+ "zh-TW": "交錯",
+ "en": "Interlaced",
+ "ja": "インターレース"
}
]
}
diff --git a/include/veyra/pipeline/CaptureUploadFrame.h b/include/veyra/pipeline/CaptureUploadFrame.h
index 3c314346..7bc7c3c9 100644
--- a/include/veyra/pipeline/CaptureUploadFrame.h
+++ b/include/veyra/pipeline/CaptureUploadFrame.h
@@ -90,8 +90,10 @@ inline uint32_t captureUploadPixelBytes(AVPixelFormat format) {
// Returns nullptr when the format is not supported or the buffer cannot be
// created; the caller then allocates an ordinary frame.
-inline AVFrame* allocCaptureUploadFrame(ID3D12Device* device, AVPixelFormat format, unsigned width, unsigned height) {
- const uint32_t pixelBytes = captureUploadPixelBytes(format);
+inline AVFrame* allocCaptureUploadFrame(ID3D12Device* device, AVPixelFormat format, unsigned width, unsigned height, bool packed10Carrier=false) {
+ // BGRA is only a four-byte storage carrier for explicitly identified
+ // DeckLink packing. It is never interpreted as BGRA pixels by the graph.
+ const uint32_t pixelBytes = packed10Carrier&&format==AV_PIX_FMT_BGRA?4:captureUploadPixelBytes(format);
if (!device || !width || !height || !pixelBytes) return nullptr;
const bool semiplanar = format == AV_PIX_FMT_NV12 || format == AV_PIX_FMT_P010 || format == AV_PIX_FMT_P016;
// Packed rows are uploaded as RGBA8 texels, so a row is a whole number of texels.
@@ -172,6 +174,23 @@ inline void sampleCaptureUploadProxy(AVFrame& frame, const uint8_t* source, size
info->proxyValid = true;
}
+// v210 stores six pixels in four words, not one four-byte word per pixel.
+// Copy complete groups from the driver sample; never read width*4 bytes from
+// its shorter packed row. Analysis remains a bounded coarse source sample.
+inline void sampleCaptureV210Proxy(AVFrame& frame,const uint8_t* source,size_t pitch,bool flip){
+ auto* info=captureUploadFrame(&frame);if(!info||!source)return;
+ for(unsigned y=0;y<CaptureUploadFrame::kProxyHeight;++y){
+ const unsigned row=y*info->height/CaptureUploadFrame::kProxyHeight;
+ const auto* line=source+size_t(flip?info->height-1-row:row)*pitch;
+ auto* out=info->proxy+size_t(y)*info->proxyPitch();
+ for(unsigned x=0;x<CaptureUploadFrame::kProxyWidth;x+=6){
+ const unsigned group=(x*info->width/CaptureUploadFrame::kProxyWidth)/6;
+ std::memcpy(out+(x/6)*16,line+size_t(group)*16,16);
+ }
+ }
+ info->proxyValid=true;
+}
+
// Planar 4:2:0 (I420 / YV12) driver sample -> NV12 frame. u/v point at the
// first source row of each chroma plane; flip reverses the rows of every plane.
inline void interleaveCaptureI420(AVFrame& dst, const uint8_t* luma, size_t lumaPitch, const uint8_t* u, const uint8_t* v, size_t chromaPitch,
diff --git a/include/veyra/pipeline/ColorMetadata.h b/include/veyra/pipeline/ColorMetadata.h
index 19fc488a..c33c35d0 100644
--- a/include/veyra/pipeline/ColorMetadata.h
+++ b/include/veyra/pipeline/ColorMetadata.h
@@ -31,7 +31,9 @@ inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription
case AV_PIX_FMT_YUV420P10LE:case AV_PIX_FMT_P010:c.pixelFormat=SourcePixelFormat::P010;break;
case AV_PIX_FMT_YUV420P:case AV_PIX_FMT_YUVJ420P:c.pixelFormat=SourcePixelFormat::Yuv420P;break;
case AV_PIX_FMT_YUYV422:c.pixelFormat=SourcePixelFormat::Yuy2;break;
- case AV_PIX_FMT_BGRA:case AV_PIX_FMT_BGR0:c.pixelFormat=SourcePixelFormat::Bgra8;break;
+ case AV_PIX_FMT_BGRA:case AV_PIX_FMT_BGR0:
+ if(c.pixelFormat!=SourcePixelFormat::V210&&c.pixelFormat!=SourcePixelFormat::Rgb10xLE)c.pixelFormat=SourcePixelFormat::Bgra8;
+ break;
case AV_PIX_FMT_BGR24:c.pixelFormat=SourcePixelFormat::Bgr24;break;
case AV_PIX_FMT_RGB555LE:c.pixelFormat=SourcePixelFormat::Rgb555;break;
case AV_PIX_FMT_RGB565LE:c.pixelFormat=SourcePixelFormat::Rgb565;break;
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index dbf01a07..68985257 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -78,6 +78,8 @@ enum class SourcePixelFormat : uint8_t {
Rgb565, // 16-bit 5:6:5 DIB
Uyvy, // UYVY 4:2:2
Yvyu, // YVYU 4:2:2
+ V210, // DeckLink 10-bit 4:2:2, four LE words per six pixels
+ Rgb10xLE, // DeckLink R10l: R bits 31..22, G 21..12, B 11..2
};
// Value carried in EnhanceGraphDesc::packedInput; 0 means "not a packed input".
constexpr uint32_t packedInputCode(SourcePixelFormat format) {
@@ -87,6 +89,8 @@ constexpr uint32_t packedInputCode(SourcePixelFormat format) {
case SourcePixelFormat::Rgb565: return 3;
case SourcePixelFormat::Uyvy: return 4;
case SourcePixelFormat::Yvyu: return 5;
+ case SourcePixelFormat::V210: return 6;
+ case SourcePixelFormat::Rgb10xLE: return 7;
default: break;
}
return 0;
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 3ec07b32..5208ef0a 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -76,6 +76,7 @@ public:
void close()noexcept override;
private:
std::wstring error_;
+ bool configureDeckLink(const SourceOpenDesc&);
bool connectDirectShowAudio(const SourceOpenDesc&);
// AVerMedia capture cards need their installed vendor component to arm
// non-PCM (Dolby/DTS) passthrough before the audio pin is negotiated.
diff --git a/include/veyra/source/CapturePixelFormat.h b/include/veyra/source/CapturePixelFormat.h
index e0f300ca..68078348 100644
--- a/include/veyra/source/CapturePixelFormat.h
+++ b/include/veyra/source/CapturePixelFormat.h
@@ -6,7 +6,7 @@
#include <format>
namespace veyra::source {
-enum class CapturePacking { Unknown, Yuy2, Uyvy, Yvyu, Nv12, Nv21, I420, Yv12, P010, P016, Bgr32, Bgra32, Bgr24, Rgb555, Rgb565 };
+enum class CapturePacking { Unknown, Yuy2, Uyvy, Yvyu, Nv12, Nv21, I420, Yv12, P010, P016, Bgr32, Bgra32, Bgr24, Rgb555, Rgb565, V210, Rgb10xLE };
constexpr DWORD captureFourcc(char a,char b,char c,char d){return DWORD(uint8_t(a))|(DWORD(uint8_t(b))<<8)|(DWORD(uint8_t(c))<<16)|(DWORD(uint8_t(d))<<24);}
inline bool captureIsFourcc(const GUID& id,DWORD code){
const GUID expected{code,0,0x10,{0x80,0,0,0xaa,0,0x38,0x9b,0x71}};return id==expected;
diff --git a/include/veyra/source/DeckLinkCapture.h b/include/veyra/source/DeckLinkCapture.h
new file mode 100644
index 00000000..b3a61620
--- /dev/null
+++ b/include/veyra/source/DeckLinkCapture.h
@@ -0,0 +1,83 @@
+#pragma once
+#include "veyra/pipeline/FramePacket.h"
+#include <cstddef>
+#include <functional>
+#include <memory>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace veyra::source::decklink {
+// Public ingress contract contains no SDK declarations. The SDK adapter and
+// the injected test driver both exercise Capture's actual state machine.
+enum class Pixel { Uyvy8, Bgra8, V210, Rgb10xLE };
+struct Mode {
+ uint32_t id=0, width=0, height=0;
+ int64_t duration=0, scale=0;
+ bool interlaced=false;
+ std::wstring name;
+ pipeline::ColorDescription color;
+};
+struct Device { std::wstring name,path; bool autoDetection=false; };
+struct Frame {
+ const uint8_t* data=nullptr; size_t bytes=0;
+ uint32_t width=0,height=0,stride=0;
+ Pixel pixel=Pixel::Uyvy8;
+ int64_t pts100ns=0,duration100ns=0;
+ bool noInput=false,bottomUp=false;
+ pipeline::ColorDescription color;
+};
+struct Signal { Mode mode; bool rgb=false; unsigned bits=0; };
+size_t rowBytes(Pixel,uint32_t width);
+bool sameColor(const pipeline::ColorDescription&,const pipeline::ColorDescription&);
+bool isPath(std::wstring_view);
+std::wstring modeKey(uint32_t);
+std::vector<Device> devices();
+std::vector<Mode> modes(std::wstring_view);
+
+class DriverSink {
+public:
+ virtual ~DriverSink()=default;
+ virtual void formatChanged(const Signal&)=0;
+ virtual void video(const Frame&)=0;
+ virtual void audio(const void*,size_t,int64_t pts100ns)=0;
+ virtual void failure(std::wstring)=0;
+};
+class Driver {
+public:
+ virtual ~Driver()=default;
+ virtual bool open(std::wstring_view,DriverSink&,std::wstring&)=0;
+ virtual std::vector<Mode> modes()=0;
+ virtual bool autoDetection()const=0;
+ // No control method may run from a driver callback. stop() detaches the
+ // callback and waits for all in-flight callbacks before returning.
+ virtual bool enable(const Mode&,Pixel,bool automatic,bool audio,std::wstring&)=0;
+ virtual bool start(std::wstring&)=0;
+ virtual bool pause(std::wstring&)=0;
+ virtual bool flush(std::wstring&)=0;
+ virtual void stop()noexcept=0;
+};
+std::unique_ptr<Driver> makeDriver();
+
+class Capture final:private DriverSink {
+public:
+ explicit Capture(std::unique_ptr<Driver> driver=makeDriver());
+ ~Capture();
+ // Probe only: bounded wait for an actual frame, no pixels/audio retained.
+ bool configure(std::wstring_view path,std::wstring_view key,bool audio,
+ unsigned timeoutMs=2500);
+ bool start(std::function<void(const Frame&)> video,
+ std::function<void(const void*,size_t,int64_t)> audio={});
+ void stop()noexcept;
+ bool needsReopen()const;
+ std::wstring error()const;
+ Frame contract()const; // data is always null; metadata from valid probe frame
+ Mode mode()const;
+private:
+ void formatChanged(const Signal&)override;
+ void video(const Frame&)override;
+ void audio(const void*,size_t,int64_t)override;
+ void failure(std::wstring)override;
+ struct Impl;std::unique_ptr<Impl> p_;
+};
+}
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index 844fb861..ff26263b 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -345,7 +345,9 @@ Item {
label: qsTr("驱动设置")
hint: captureDialog.live ? qsTr("先断开采集,再配置驱动")
: veyra.captureBlackmagicDevice
- ? qsTr("Blackmagic 两个条目可能属于同一张卡。确认 HDMI/SDI 输入口,格式须匹配信号的分辨率、59.94/60 和逐行/隔行;驱动默认格式不是自动检测。")
+ ? (veyra.preferences.blackmagicNativeCapture === true
+ ? qsTr("原生采集跟随 Desktop Video Setup 的 HDMI/SDI 输入。支持自动检测的卡建议选择自动;信号未锁定时会明确提示。")
+ : qsTr("Blackmagic 两个条目可能属于同一张卡。DirectShow 黑屏可尝试下方原生采集开关;手动格式须匹配实际信号。"))
: qsTr("配置驱动公开的输入与视频属性;其他采集应用占用设备时请先关闭")
RowLayout {
spacing: 6
@@ -364,6 +366,18 @@ Item {
}
}
}
+ VRow {
+ objectName: "capture-blackmagic-native-row"
+ label: qsTr("Blackmagic 原生采集")
+ hint: qsTr("默认关闭。开启使用 DeckLink 原生接口,关闭使用 DirectShow。需安装 Desktop Video 驱动;切换后重新选择设备和格式并连接,不写入驱动永久配置。")
+ VSwitch {
+ objectName: "capture-blackmagic-native"
+ enabled: !veyra.captureQueryBusy && (veyra.captureBlackmagicDevice || veyra.preferences.blackmagicNativeCapture === true)
+ opacity: enabled ? 1 : 0.35
+ checked: veyra.preferences.blackmagicNativeCapture === true
+ onToggled: checked => veyra.setPreference("blackmagicNativeCapture", checked)
+ }
+ }
VRow {
objectName: "capture-magewell-row"
label: qsTr("美乐威低延迟模式")
diff --git a/scripts/acceptance/decklink-native-build.py b/scripts/acceptance/decklink-native-build.py
new file mode 100644
index 00000000..55c740e5
--- /dev/null
+++ b/scripts/acceptance/decklink-native-build.py
@@ -0,0 +1,170 @@
+"""Scoped native capture build; immutable accepted cache, current dependency closure."""
+from pathlib import Path
+import ctypes, hashlib, json, os, re, subprocess, sys, time
+from concurrent.futures import ThreadPoolExecutor
+
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='decklink-native-20261009'
+CACHE=BASE/'build/vfg-next-20261007';OUT=BASE/'build'/TASK
+SDK=BASE/'deps/decklink-sdk-obs31-20261009'
+LOG=BASE/'logs'/TASK/('build-'+time.strftime('%Y%m%d-%H%M%S'));TMP=BASE/'tmp'/TASK/'build'
+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=True)
+def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
+shell=ctypes.WinDLL('shell32');shell.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)];shell.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p);ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]
+def args(s):
+ n=ctypes.c_int();p=shell.CommandLineToArgvW(s,ctypes.byref(n));a=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return a
+def unescape(s):return s.replace('$ ',' ').replace('$:',':').replace('$$','$')
+tool=re.search(r'^CMAKE_MAKE_PROGRAM:FILEPATH=(.*)$',(CACHE/'CMakeCache.txt').read_text(encoding='utf8'),re.M).group(1)
+ninja=(CACHE/'build.ninja').read_text(encoding='utf8');inputs={};sources={};commands=[];start=time.monotonic()
+def protect(p):
+ p=Path(p);p=p if p.is_absolute() else CACHE/p;assert p.is_file(),p
+ if str(p) not in inputs:inputs[str(p)]=sha(p)
+ return p
+def rule(name):
+ lines=re.search(r'^build '+re.escape(name)+r': .*?(?=\n\n)',ninja,re.M|re.S).group().splitlines()
+ var=dict(re.match(r' ([A-Z_]+) = (.*)',l).groups() for l in lines[1:] if re.match(r' ([A-Z_]+) = (.*)',l))
+ objects=[unescape(n).replace('\\','/') for n in lines[0].split('Release ',1)[1].split(' | ',1)[0].split(' || ',1)[0].split(' ')]
+ for value in args(unescape(var.get('LINK_LIBRARIES',''))):
+ if value.lower().endswith('.lib') and (Path(value).is_file() or (CACHE/value).is_file()):protect(value)
+ return objects,var
+def compiler(name):return args(subprocess.check_output([tool,'-t','commands',name],cwd=CACHE,text=True,encoding='utf8').splitlines()[-1])
+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP),VSLANG='1033')
+setup=subprocess.run(['cmd.exe','/u','/d','/c',r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],capture_output=True,text=True,encoding='utf-16-le',env=env,check=True)
+for line in setup.stdout.splitlines():
+ if '=' in line:
+ k,v=line.split('=',1)
+ if k and not k.startswith('='):env[k]=v
+env.update(TEMP=str(TMP),TMP=str(TMP))
+def run(command,name,cwd=TMP):
+ commands.append(command);remaining=890-(time.monotonic()-start);assert remaining>0
+ with (LOG/(name+'.log')).open('wb') as stream:r=subprocess.run(command,cwd=cwd,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=min(300,remaining))
+ print(name,'exit',r.returncode,flush=True)
+ if r.returncode:print((LOG/(name+'.log')).read_text(encoding='utf8',errors='replace')[-6000:]);raise RuntimeError(name)
+
+if sys.argv[1:]==['cmake-check']:
+ cache=dict(re.findall(r'^([^#/:=]+):[^=]+=(.*)$',(CACHE/'CMakeCache.txt').read_text(encoding='utf8'),re.M))
+ cmake=r'C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe'
+ names=('VEYRA_DLSS_SDK_ROOT','VEYRA_NVOF_SDK_ROOT','VEYRA_NVENC_HEADERS_ROOT','VEYRA_XESS_ROOT',
+ 'VEYRA_FIDELITYFX_ROOT','VEYRA_FIDELITYFX2_ROOT','VEYRA_MAGEWELL_SDK_DIR','VEYRA_LIBASS_ROOT','CMAKE_PREFIX_PATH')
+ for native in (True,False):
+ name='cmake-sdk' if native else 'cmake-no-sdk';directory=OUT/name
+ flags=['-D'+key+'='+cache[key] for key in names]
+ # The accepted vcpkg prefix supplies MSVC import libraries. The patched
+ # runtime prefix used in tests contains DLLs/DEFs, not MSVC libraries.
+ flags+=['-DVEYRA_FFMPEG_ROOT='+cache['VEYRA_FFMPEG_ROOT'],
+ '-DVEYRA_ENABLE_EXPERIMENTAL_DLSSNR=ON','-DVEYRA_ENABLE_D3D12_DEBUG=OFF','-DVEYRA_BUILD_QML_UI=ON',
+ '-DVEYRA_ENABLE_REMOTEPLAY=OFF','-DVEYRA_ENABLE_MOONLIGHT=OFF','-DVEYRA_ENABLE_XBOX=OFF',
+ '-DVEYRA_DECKLINK_SDK_DIR='+(str(SDK) if native else ''),'-DCMAKE_BUILD_TYPE=Release','-DCMAKE_MAKE_PROGRAM='+tool]
+ run([cmake,'-S',str(ROOT),'-B',str(directory),'-G','Ninja',*flags],name+'-configure')
+ run([cmake,'--build',str(directory),'--target','CMakeFiles/veyra_sources.dir/src/source/DeckLinkDriver.cpp.obj','-j','2'],name+'-compile')
+ (LOG/'receipt.json').write_text(json.dumps({'commands':commands,'passed':True,'seconds':time.monotonic()-start},ensure_ascii=False,indent=2),encoding='utf8')
+ (BASE/'reports'/TASK/'cmake-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')
+ print('CMake native and no-SDK configurations/driver objects passed;',LOG,flush=True)
+ raise SystemExit(0)
+headerKey=hashlib.sha256(''.join(str(p)+sha(p) for folder in ('include','tests') for p in sorted((ROOT/folder).rglob('*.h'))).encode()).hexdigest()
+def compile(source,name,a,extra=(),dependencyKey=''):
+ sources[str(source)]=sha(source);target=OUT/(name+'.obj')
+ command=a[:1]+['/utf-8','/I'+str(ROOT/'include'),'/I'+str(ROOT/'src')]+[v.replace(str(CACHE).replace('\\','/'),str(OUT).replace('\\','/')) if v.startswith(('/DVEYRA_SHADER_DIR','-DVEYRA_SHADER_DIR')) else v for v in a[1:-1] if not v.startswith(('/Fo','/Fd')) and v!='/showIncludes']
+ command+=list(extra)+['/Fo'+str(target),'/Fd'+str(OUT/(name+'.pdb')),str(source)]
+ key=hashlib.sha256((json.dumps(command)+sources[str(source)]+headerKey+dependencyKey).encode()).hexdigest();stamp=target.with_suffix('.build.json')
+ if target.is_file() and stamp.is_file():
+ old=json.loads(stamp.read_text());
+ if old['key']==key and old['object']==sha(target):print('reuse',name,flush=True);return target
+ run(command,'compile-'+name);stamp.write_text(json.dumps({'key':key,'object':sha(target)}),encoding='utf8');return target
+previous=json.loads((BASE/'logs/pr31-playlist-20261009/build-20261009-144612/receipt.json').read_text(encoding='utf8'))
+overrides={name:protect(row['path']) for name,row in previous['overrides'].items()}
+for name,row in previous['overrides'].items():assert sha(row['path'])==row['sha256'],name
+targets={n:rule(n+'.exe') for n in ('veyra_qml_ui','veyra_capture_tests','veyra_capture_color_tests','veyra_capture_format_selection_tests','veyra_hdr_color_tests','veyra_capture_audio_tests')}
+objects=set(p for obj,var in targets.values() for p in obj)
+def libraries(var):return {Path(v).stem for v in args(unescape(var.get('LINK_LIBRARIES',''))) if v.endswith('.lib') and Path(v).stem.startswith('veyra_')}
+groups=set().union(*(libraries(var) for objs,var in targets.values()))
+for group in groups:
+ if re.search(r'^build '+re.escape(group+'.lib')+r': (?:CXX|C)_STATIC_',ninja,re.M):objects.update(rule(group+'.lib')[0])
+changed_headers=[p.replace('\\','/') for p in subprocess.check_output(['git','diff','--name-only','HEAD'],cwd=ROOT,text=True,encoding='utf8').splitlines() if p.startswith('include/')]
+dependencies={};current=None
+for line in subprocess.check_output([tool,'-t','deps'],cwd=CACHE,text=True,encoding='utf8').splitlines():
+ if line and not line[0].isspace():current=line.split(': #deps ',1)[0].replace('\\','/');dependencies[current]=[]
+ elif current and line.strip():dependencies[current].append(line.strip().replace('\\','/'))
+rebuild=[]
+for obj in objects:
+ relative=obj.split('.dir/',1)[-1][:-4]
+ if not relative.startswith(('src/','apps/','tests/')) or not (ROOT/relative).is_file():continue
+ original=next((p for p in previous['sources'] if p.replace('\\','/').endswith('/'+relative)),None)
+ source_changed=original is not None and Path(original).read_bytes().replace(b'\r\n',b'\n')!=(ROOT/relative).read_bytes().replace(b'\r\n',b'\n')
+ directly=relative in ('src/source/CaptureCardSource.cpp','src/engine/EngineController.cpp','src/pipeline/EnhanceGraph.cpp','src/ui/QmlPlayerBridge.cpp','tests/integration/HdrColorTests.cpp')
+ dep_changed=any(any(d.endswith('/'+h) for d in dependencies.get(obj,())) for h in changed_headers)
+ if source_changed or directly or dep_changed or not (CACHE/obj).is_file():rebuild.append((obj,ROOT/relative,compiler(obj)))
+def job(row):
+ obj,source,a=row;return obj,compile(source,obj.replace('/','-').replace('.','-'),a)
+with ThreadPoolExecutor(max_workers=4) as pool:
+ for obj,p in pool.map(job,rebuild):overrides[obj]=p
+for obj in objects:
+ if obj not in overrides:protect(obj)
+# Unchanged objects added by PR31, not present in the older cached CMake graph.
+playlist=[protect(BASE/'build/pr31-playlist-20261009'/n) for n in ('PlaylistModel.obj','playlist-moc.obj')]
+for relative in ('include/veyra/ui/QmlPlayerBridge.h','include/veyra/ui/PlaylistModel.h','src/ui/PlaylistModel.cpp'):
+ original=next(p for p in previous['sources'] if p.replace('\\','/').endswith('/'+relative));assert sha(original)==previous['sources'][original]
+ assert Path(original).read_bytes().replace(b'\r\n',b'\n')==(ROOT/relative).read_bytes().replace(b'\r\n',b'\n');sources[str(ROOT/relative)]=sha(ROOT/relative)
+sourceCompiler=compiler('CMakeFiles/veyra_sources.dir/src/source/CaptureCardSource.cpp.obj')
+generatedSdk=OUT/'decklink-generated';generatedSdk.mkdir(exist_ok=True)
+for file in SDK.rglob('*'):
+ if file.is_file():protect(file)
+midl=protect(Path(r'C:/Program Files (x86)/Windows Kits/10/bin/10.0.26100.0/x64/midl.exe'))
+run([str(midl),'/nologo','/env','x64','/I',str(SDK),'/out',str(generatedSdk),'/h','DeckLinkAPI_h.h',
+ '/iid','DeckLinkAPI_i.c','/tlb','DeckLinkAPI.tlb','/client','none','/server','none',str(SDK/'DeckLinkAPI.idl')],'generate-decklink-abi')
+nativeCore=compile(ROOT/'src/source/DeckLinkCapture.cpp','DeckLinkCapture',sourceCompiler)
+nativeDriver=compile(ROOT/'src/source/DeckLinkDriver.cpp','DeckLinkDriver',sourceCompiler,['/DVEYRA_HAS_DECKLINK=1','/I'+str(generatedSdk)],sha(generatedSdk/'DeckLinkAPI_h.h'))
+stubDriver=compile(ROOT/'src/source/DeckLinkDriver.cpp','DeckLinkDriver-stub',sourceCompiler,['/DVEYRA_HAS_DECKLINK=0'])
+native=[nativeCore,nativeDriver]
+uiOnly=sys.argv[1:]==['ui-only']
+if uiOnly:
+ for name in ('veyra_capture_tests','veyra_capture_color_tests','veyra_capture_format_selection_tests',
+ 'veyra_hdr_color_tests','veyra_capture_audio_tests','decklink-tests','decklink-stub-tests'):
+ protect(OUT/(name+'.exe'))
+for file in SDK.rglob('*'):
+ if file.is_file():protect(file)
+
+shaderOut=OUT/'shaders';shaderOut.mkdir(exist_ok=True)
+for source in (CACHE/'shaders').rglob('*'):
+ if not source.is_file() or source.name=='PackedCaptureToLinear.dxil':continue
+ protect(source);target=shaderOut/source.relative_to(CACHE/'shaders');target.parent.mkdir(parents=True,exist_ok=True)
+ if not target.exists():os.link(source,target)
+dxc=protect(Path(r'C:/Program Files (x86)/Windows Kits/10/bin/10.0.26100.0/x64/dxc.exe'))
+run([str(dxc),'-T','cs_6_0','-E','main','-O3','-Qstrip_debug','-Qstrip_reflect','-Fo',str(shaderOut/'PackedCaptureToLinear.dxil'),str(ROOT/'shaders/PackedCaptureToLinear.hlsl')],'shader-packed')
+resource='CMakeFiles/veyra_qml_ui.dir/.qt/rcc/qrc_veyra_i18n.cpp.obj'
+rcc=protect(Path('C:/veyra-deps/qt-veyra/6.8.3/msvc2022_64/bin/rcc.exe'))
+qrc=OUT/'i18n.qrc';qrc.write_text('<RCC><qresource prefix="/i18n"><file alias="catalog.json">'+(ROOT/'i18n/catalog.json').as_posix()+'</file></qresource></RCC>',encoding='utf8')
+generated=OUT/'qrc_veyra_i18n.cpp';run([str(rcc),'--name','veyra_i18n','--no-zstd','-o',str(generated),str(qrc)],'generate-i18n')
+overrides[resource]=compile(generated,'qrc_veyra_i18n',compiler(resource));sources[str(ROOT/'i18n/catalog.json')]=sha(ROOT/'i18n/catalog.json')
+
+cmake=r'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
+link=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Tools\MSVC\1444~1.352\bin\Hostx64\x64\link.exe';executables=[]
+def linkTarget(name,objs,var):
+ rsp=OUT/(name+'.rsp');rsp.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in objs)+'\n'+unescape(var.get('LINK_PATH',''))+'\n'+unescape(var['LINK_LIBRARIES']),encoding='utf8')
+ directory=OUT/('manifest-'+name);directory.mkdir(exist_ok=True)
+ flags=[('/MANIFESTINPUT:'+str(CACHE/'veyra-qml.manifest')) if a.startswith('/MANIFESTINPUT:') else a for a in args(unescape(var.get('LINK_FLAGS','')))]
+ command=[cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(directory),r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(rsp),'/out:'+str(OUT/(name+'.exe')),'/implib:'+str(OUT/(name+'.lib')),'/pdb:'+str(OUT/(name+'.pdb')),'/version:0.0']+flags
+ run(command,'link-'+name,CACHE);executables.append(OUT/(name+'.exe'))
+for name,(objs,var) in targets.items():
+ if uiOnly and name!='veyra_qml_ui':continue
+ selected=[overrides.get(obj,CACHE/obj) for obj in objs]
+ linked=libraries(var)
+ selected+=[p for obj,p in overrides.items() if obj not in objs and any(obj.startswith('CMakeFiles/'+group+'.dir/') for group in linked) and
+ (name!='veyra_capture_audio_tests' or obj.endswith('/src/sink/CaptureAudioSession.cpp.obj'))]
+ if name=='veyra_qml_ui':selected+=playlist
+ # Static-library closure flattened by CMake into the immutable GUI graph.
+ if 'veyra_sources' in linked:selected+=native
+ linkTarget(name,selected,var)
+if not uiOnly:
+ test=compile(ROOT/'tests/unit/DeckLinkCaptureTests.cpp','DeckLinkCaptureTests',sourceCompiler)
+ var=targets['veyra_capture_tests'][1]
+ baseObj=protect(CACHE/'CMakeFiles/veyra_base.dir/src/base/Log.cpp.obj')
+ linkTarget('decklink-tests',[test,nativeCore,nativeDriver,baseObj],var)
+ linkTarget('decklink-stub-tests',[test,nativeCore,stubDriver,baseObj],var)
+for p,d in inputs.items():assert sha(p)==d,p
+for folder in ('include','src','shaders','qml','tests'):
+ for file in (ROOT/folder).rglob('*'):
+ if file.is_file() and file.suffix in ('.h','.hlsl','.hlsli','.qml','.cpp'):sources[str(file)]=sha(file)
+receipt={'commands':commands,'sources':sources,'overrides':{n:{'path':str(p),'sha256':sha(p)} for n,p in overrides.items()},'inputsUnchanged':inputs,'seconds':time.monotonic()-start,'executables':{p.name:sha(p) for p in executables},'recompiledDependencyClosure':len(rebuild)}
+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')
+(BASE/'reports'/TASK/'build-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')
+print('Built current product and native/legacy tests; immutable inputs unchanged;',LOG,flush=True)
diff --git a/scripts/acceptance/decklink-native-control.py b/scripts/acceptance/decklink-native-control.py
new file mode 100644
index 00000000..d98c4191
--- /dev/null
+++ b/scripts/acceptance/decklink-native-control.py
@@ -0,0 +1,42 @@
+"""Audit immutable pre-task worktrees and this task's narrow source scope."""
+from pathlib import Path
+import hashlib
+import json
+import re
+import subprocess
+import sys
+
+ROOT = Path(__file__).resolve().parents[2]
+BASE = Path('E:/项目/Veyra')
+TASK = 'decklink-native-20261009'
+start = json.loads((BASE/'archives'/TASK/'start.json').read_text(encoding='utf8'))
+
+def git(*args, cwd=ROOT):
+ return subprocess.check_output(['git', *args], cwd=cwd)
+
+def sha(path):
+ with path.open('rb') as stream:
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
+
+for name, row in start['worktrees'].items():
+ path = Path(name)
+ assert git('rev-parse', 'HEAD', cwd=path).decode().strip() == row['head'], name
+ assert hashlib.sha256(git('status', '--porcelain=v1', '-z', cwd=path)).hexdigest() == row['statusSha256'], name
+ for relative, digest in row['dirtyFiles'].items():
+ file = path/relative
+ assert (sha(file) if file.is_file() else None) == digest, str(file)
+assert git('rev-parse', 'main').decode().strip() == start['main']
+assert git('branch', '--show-current').decode().strip() == 'codex/'+TASK
+allowed = {'THIRD_PARTY_NOTICES.md', 'src/pipeline/EnhanceGraph.cpp', 'src/source/DeckLinkDriver.cpp', 'scripts/acceptance/decklink-native-ui.qml', 'qml/Veyra/DialogHost.qml', 'scripts/acceptance/decklink-native-control.py', 'src/engine/EngineController.cpp', 'include/veyra/source/DeckLinkCapture.h', 'scripts/acceptance/decklink-native-test.py', 'tests/unit/DeckLinkCaptureTests.cpp', 'AGENTS.md', 'shaders/PackedCaptureToLinear.hlsl', 'include/veyra/pipeline/EnhanceGraph.h', 'i18n/catalog.json', 'src/source/DeckLinkCapture.cpp', 'docs/DECKLINK_NATIVE_REPORT_2026-10-09.md', 'include/veyra/source/CaptureCardSource.h', 'include/veyra/pipeline/ColorMetadata.h', 'tests/integration/HdrColorTests.cpp', 'include/veyra/source/CapturePixelFormat.h', 'docs/DECKLINK_NATIVE_PLAN_2026-10-09.md', 'include/veyra/pipeline/FramePacket.h', 'src/ui/QmlPlayerBridge.cpp', 'scripts/acceptance/decklink-native-build.py', 'docs/WORKLOG.md', 'scripts/acceptance/decklink-native-gui-test.py', 'CMakeLists.txt', 'include/veyra/pipeline/CaptureUploadFrame.h', 'src/source/CaptureCardSource.cpp', 'tests/integration/DeckLinkGpuCases.h'}
+dirty = {p.decode('utf8') for p in git('ls-files', '-m', '-d', '--others', '--exclude-standard', '-z').split(b'\0') if p}
+changed = {p.decode('utf8') for p in git('diff', '--name-only', start['base']).splitlines() if p}
+assert (changed | dirty) <= allowed, (changed | dirty) - allowed
+git('diff', '--check')
+git('diff', '--cached', '--check')
+label = sys.argv[1] if len(sys.argv) > 1 else 'audit'
+assert re.fullmatch('[a-z0-9-]+', label)
+report = {'baselineWorktreesUnchanged': len(start['worktrees']),
+ 'dirtyFilesUnchanged': sum(len(v['dirtyFiles']) for v in start['worktrees'].values()),
+ 'scopePass': True, 'changed': sorted(changed | dirty), 'mainHead': start['main'], 'base': start['base']}
+(BASE/'reports'/TASK/(label+'.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
+print(json.dumps(report, ensure_ascii=False), flush=True)
diff --git a/scripts/acceptance/decklink-native-gui-test.py b/scripts/acceptance/decklink-native-gui-test.py
new file mode 100644
index 00000000..a12db233
--- /dev/null
+++ b/scripts/acceptance/decklink-native-gui-test.py
@@ -0,0 +1,77 @@
+"""Real capture settings, saved switch and ordinary USB; isolated app/profile."""
+from pathlib import Path
+import hashlib, json, os, re, shutil, subprocess, sys, time
+import psutil
+
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='decklink-native-20261009'
+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'
+BUILD=BASE/'build'/TASK;APP=BASE/'tests'/TASK/'app'
+FFMPEG=BASE/'deps/ffmpeg-subtitle-formats-20261009/installed/bin'
+case=sys.argv[1] if len(sys.argv)>1 else 'switch'
+assert case in ('switch','usb')
+LOG=BASE/'logs'/TASK/('gui-'+case+'-'+time.strftime('%Y%m%d-%H%M%S'))
+TMP=BASE/'tmp'/TASK/LOG.name
+for p in (LOG,TMP):p.mkdir(parents=True,exist_ok=False)
+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
+manifest=json.loads((DONOR/'package-manifest.json').read_text(encoding='utf8'))
+def verify():
+ for row in manifest['files']:assert sha(DONOR/row['path'])==row['sha256'],row['path']
+verify()
+for proc in psutil.process_iter(['name']):
+ assert not (proc.info['name'] or '').lower().startswith(('veyra','fg-presentation','flash-pixel')),proc.info
+if not APP.exists():
+ APP.mkdir(parents=True)
+ for row in manifest['files']:
+ rel=Path(row['path'])
+ if rel.parts[0] in ('runtime_local','logs') or rel.name=='veyra_qml_ui.exe':continue
+ target=APP/rel;target.parent.mkdir(parents=True,exist_ok=True);os.link(DONOR/rel,target)
+ (APP/'runtime_local').mkdir(exist_ok=True)
+def replace(source,target):
+ target.parent.mkdir(parents=True,exist_ok=True)
+ swap=target.with_name(target.name+'.swap');shutil.copy2(source,swap);os.replace(swap,target)
+def write(target,content):
+ swap=target.with_name(target.name+'.swap');swap.write_bytes(content);os.replace(swap,target)
+replace(BUILD/'veyra_qml_ui.exe',APP/'veyra_qml_ui.exe')
+for source in (ROOT/'qml').rglob('*'):
+ if source.is_file() and (source.suffix in ('.qml','.js') or source.name=='qmldir'):
+ replace(source,APP/'qml'/source.relative_to(ROOT/'qml'))
+for source in (BUILD/'shaders').rglob('*.dxil'):replace(source,APP/'shaders'/source.relative_to(BUILD/'shaders'))
+for source in FFMPEG.glob('*.dll'):replace(source,APP/source.name)
+profile=BASE/'tests'/TASK/'profiles'/LOG.name;profile.mkdir(parents=True,exist_ok=False)
+preferences=profile/'qml-preferences.v1.json'
+preferences.write_text(json.dumps({'language':'zh-CN','autoResume':False,'rememberPosition':False,
+ 'prewarmEnhancement':False,'gpuPriority':'normal','subtitleEnabled':False,
+ 'screenshotDir':str(LOG/'screenshots'),'sentinel':'preserved'}),encoding='utf8')
+env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_','QSG_'))}
+env.update(PATH=str(APP)+os.pathsep+env['PATH'],TEMP=str(TMP),TMP=str(TMP),CUDA_CACHE_PATH=str(TMP/'cuda'),
+ QML_DISK_CACHE_PATH=str(TMP/'qml-cache'),QT_FORCE_STDERR_LOGGING='1')
+main=APP/'qml/Veyra/Main.qml';saved=main.read_bytes();results=[]
+try:
+ for phase in (('fresh','restore','english') if case=='switch' else ('capture',)):
+ evidence=LOG/phase;evidence.mkdir()
+ if phase=='english':
+ prefs=json.loads(preferences.read_text(encoding='utf8'));prefs['language']='en';preferences.write_text(json.dumps(prefs),encoding='utf8')
+ test=ROOT/'scripts/acceptance'/('decklink-native-ui.qml' if case=='switch' else 'blackmagic-ui.qml')
+ loader='\nLoader { source: '+json.dumps(test.as_uri())+'; onLoaded: { item.dialogHost=dialogs; item.phase='+json.dumps(phase)+'; item.evidence='+json.dumps(evidence.as_posix(),ensure_ascii=False)+' } }\n'
+ text=saved.decode('utf8');at=text.rfind('}');assert at>0
+ write(main,(text[:at]+loader+text[at:]).encode('utf8'))
+ env['VEYRA_LOG_FILE']=str(evidence/'engine.log')
+ command=[str(APP/'veyra_qml_ui.exe'),'--data-dir',str(profile),'--page','home','--size','1280x900','--exit-after','29000' if case=='switch' else '100000']
+ began=time.monotonic()
+ with (evidence/'console.log').open('wb') as stream:
+ run=subprocess.run(command,cwd=APP,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=45 if case=='switch' else 115)
+ console=(evidence/'console.log').read_text(encoding='utf8',errors='replace')
+ errors=[line for line in console.splitlines() if re.search(r'NATIVE_UI_FAIL|BLACKMAGIC_UI_FAIL|ReferenceError:|TypeError:|\[ERROR\s*\]|\[FATAL\s*\]|D3D12 ERROR|D3D12 CORRUPTION|Cannot assign|Binding loop',line)]
+ prefs=json.loads(preferences.read_text(encoding='utf8'));assert prefs.get('sentinel')=='preserved'
+ if case=='switch':assert bool(prefs.get('blackmagicNativeCapture',False))==(phase!='restore')
+ passed=run.returncode==0 and not errors and ('NATIVE_UI_PASS' if case=='switch' else 'BLACKMAGIC_UI_PASS') in console
+ row={'phase':phase,'command':command,'exit':run.returncode,'seconds':time.monotonic()-began,'passed':passed,
+ 'errors':errors,'events':[l for l in console.splitlines() if 'NATIVE_UI_' in l or 'BLACKMAGIC_UI_' in l],'profile':str(profile)}
+ results.append(row);print(json.dumps(row,ensure_ascii=False),flush=True)
+ if not passed:break
+finally:write(main,saved)
+verify()
+receipt={'results':results,'passed':all(r['passed'] for r in results),'exeSha256':sha(APP/'veyra_qml_ui.exe'),'donorUnchanged':len(manifest['files'])}
+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')
+(BASE/'reports'/TASK/('gui-'+case+'-current.json')).write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')
+raise SystemExit(not receipt['passed'])
diff --git a/scripts/acceptance/decklink-native-test.py b/scripts/acceptance/decklink-native-test.py
new file mode 100644
index 00000000..06dc8705
--- /dev/null
+++ b/scripts/acceptance/decklink-native-test.py
@@ -0,0 +1,39 @@
+"""Bounded serial native protocol, actual GPU pixels, legacy USB/audio checks."""
+from pathlib import Path
+import hashlib,json,os,re,subprocess,sys,time
+BASE=Path('E:/项目/Veyra');TASK='decklink-native-20261009';BUILD=BASE/'build'/TASK
+DONOR=BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'
+FFMPEG=BASE/'deps/ffmpeg-subtitle-formats-20261009/installed/bin';QT=Path('C:/veyra-deps/qt-veyra/6.8.3/msvc2022_64')
+LOG=BASE/'logs'/TASK/('tests-'+time.strftime('%Y%m%d-%H%M%S'));TMP=BASE/'tmp'/TASK/LOG.name
+for p in (LOG,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_'))}
+env.update(PATH=os.pathsep.join(map(str,(FFMPEG,QT/'bin',DONOR)))+os.pathsep+env['PATH'],TEMP=str(TMP),TMP=str(TMP),CUDA_CACHE_PATH=str(TMP/'cuda'))
+cases=[('native','decklink-tests',[]),('no-sdk','decklink-stub-tests',[]),('legacy-color','veyra_capture_color_tests',[]),('selection','veyra_capture_format_selection_tests',[]),('gpu','veyra_hdr_color_tests',[]),('devices','veyra_capture_tests',['--list']),('usb-rate','veyra_capture_tests',['--rate-test','capture:0:1:-1','0'])]
+cases +=[(name,'veyra_capture_audio_tests',['--'+name]) for name in ('endpoint-switch','endpoint-loss','slow-start','transient','xbox-float-rtp')]
+selected=sys.argv[1:]
+if selected:assert set(selected)<={n for n,_,_ in cases};cases=[row for row in cases if row[0] in selected]
+results=[]
+for name,exe,extra in cases:
+ if name=='usb-rate':
+ # Verify this run's physical fixture before the existing rate test
+ # converts its ordinal to the actual device + saved format identity.
+ listing=subprocess.check_output([str(BUILD/'veyra_capture_tests.exe'),'--list'],cwd=BUILD,env=env,timeout=20)
+ (LOG/'usb-rate-devices.log').write_bytes(listing)
+ first=listing.splitlines()[0]
+ assert first.startswith(b'VIDEO 0 KUHAIMI 27P ') and b'vid_048d&pid_c027' in first,first
+ cmd=[str(BUILD/(exe+'.exe')),*extra];env['VEYRA_LOG_FILE']=str(LOG/(name+'-engine.log'));began=time.monotonic()
+ with (LOG/(name+'.log')).open('wb') as stream:
+ try:rc=subprocess.run(cmd,cwd=BUILD,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=290).returncode
+ except subprocess.TimeoutExpired:rc=124
+ output=(LOG/(name+'.log')).read_text(encoding='utf8',errors='replace');skipped=name=='endpoint-switch' and rc==77
+ # RATE uses pass=0/1 as a phase index; only GPU records use it as a result.
+ failed=bool(re.search(r'^FAIL\b|D3D12 ERROR|D3D12 CORRUPTION',output,re.M)) or (name=='gpu' and bool(re.search(r'\bpass=0\b',output)))
+ ok=(rc==0 or skipped or name=='devices' and rc==1) and not failed
+ if name=='gpu':ok=ok and len(re.findall(r'^DECKLINK_GPU .*pass=1',output,re.M))==24
+ checks=sum(line.startswith('PASS ') or name=='gpu' and bool(re.search(r'\bpass=1\b',line)) for line in output.splitlines())
+ row={'name':name,'command':cmd,'exit':rc,'seconds':time.monotonic()-began,'passed':bool(ok),'skipped':skipped,'checks':checks,'exeSha256':hashlib.sha256(Path(cmd[0]).read_bytes()).hexdigest(),'log':str(LOG/(name+'.log'))}
+ results.append(row);(LOG/'receipt.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
+ print(json.dumps(row,ensure_ascii=False),flush=True)
+ if not ok:print(output[-6500:],flush=True);break
+(BASE/'reports'/TASK/('tests-'+('-'.join(selected) if selected else 'all')+'-current.json')).write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')
+raise SystemExit(any(not r['passed'] for r in results))
diff --git a/scripts/acceptance/decklink-native-ui.qml b/scripts/acceptance/decklink-native-ui.qml
new file mode 100644
index 00000000..2e3d33d7
--- /dev/null
+++ b/scripts/acceptance/decklink-native-ui.qml
@@ -0,0 +1,96 @@
+import QtQuick
+Item {
+ id: test
+ property var dialogHost: null
+ property var appWindow: Window.window
+ property string evidence: ""
+ property string phase: "fresh"
+ property int step: 0
+ property int ticks: 0
+ property bool grabbed: false
+ property var before: []
+ function require(ok, why) {
+ if (!ok) throw new Error(why)
+ console.log("NATIVE_UI_CHECK", 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 reveal(row) {
+ let parent = row.parent
+ while (parent) {
+ if (parent.contentItem !== undefined && parent.contentY !== undefined && parent.contentHeight > parent.height) {
+ const y = row.mapToItem(parent.contentItem, 0, 0).y
+ parent.contentY = Math.min(parent.contentHeight - parent.height, Math.max(0, y - 140))
+ return
+ }
+ parent = parent.parent
+ }
+ }
+ Timer {
+ interval: 250; running: true; repeat: true
+ onTriggered: { try {
+ ++test.ticks
+ if (test.ticks > 110) throw new Error("deadline step=" + test.step)
+ if (test.step === 0) {
+ if (test.ticks < 6 || !test.dialogHost) return
+ test.require(!veyra.running && !veyra.nrEnabled && !veyra.fgEnabled, "no source or enhancement started")
+ test.dialogHost.open("capture"); test.step = 1; return
+ }
+ if (veyra.captureQueryBusy) return
+ const row = test.find(test.appWindow.contentItem, "capture-blackmagic-native-row")
+ const toggle = test.find(test.appWindow.contentItem, "capture-blackmagic-native")
+ const magewell = test.find(test.appWindow.contentItem, "capture-magewell-row")
+ if (!row || !toggle || !magewell) throw new Error("production switches missing")
+ if (test.step === 1) {
+ test.require(row.parent === magewell.parent && row.y < magewell.y, "native switch is beside Magewell in the capture panel")
+ if (test.phase === "restore") {
+ test.require(veyra.preferences.blackmagicNativeCapture === true && toggle.checked && toggle.enabled, "enabled preference restored and can be switched off without a BMD driver")
+ toggle.toggled(false); test.step = 3; return
+ }
+ test.require(veyra.preferences.blackmagicNativeCapture !== true && !toggle.checked, "fresh profile defaults off")
+ test.require(!veyra.captureDevices.some(x => x.id.startsWith("decklink-native:")), "default-off list contains only DirectShow endpoints")
+ const usb = veyra.captureDevices.find(x => x.label === "KUHAIMI 27P")
+ test.require(usb !== undefined, "real local USB regression fixture is present")
+ if (veyra.captureDeviceId !== usb.id) { veyra.captureDeviceId = usb.id; return }
+ test.require(!veyra.captureBlackmagicDevice && !toggle.enabled, "ordinary USB cannot enable the BMD-only switch")
+ test.require(row.label === (test.phase === "english" ? "Blackmagic native capture" : "Blackmagic 原生采集"), "switch label uses the selected language")
+ test.before = veyra.captureDevices.map(x => x.id)
+ // Exercise the actual saved-preference API; this PC has no BMD
+ // endpoint on which a user could enable the disabled switch.
+ veyra.setPreference("blackmagicNativeCapture", true)
+ test.step = 2; return
+ }
+ if (test.step === 2) {
+ test.require(toggle.checked && toggle.enabled, "saved setting updates the production switch")
+ const ids = veyra.captureDevices.map(x => x.id)
+ test.require(test.before.every(x => ids.includes(x)), "enabling native mode retains ordinary USB and virtual devices")
+ test.require(!veyra.captureDeviceId.length && veyra.captureStatus.length > 0, "missing native driver/device produces an explicit status without guessing another card")
+ test.require(!veyra.running, "switching the setting does not start a capture")
+ test.reveal(row); test.step = 4; return
+ }
+ if (test.step === 3) {
+ test.require(veyra.preferences.blackmagicNativeCapture === false && !toggle.checked, "production toggle handler saves off")
+ test.require(!veyra.captureDevices.some(x => x.id.startsWith("decklink-native:")), "off restores the DirectShow device list")
+ test.require(!veyra.running, "switching off leaves idle playback idle")
+ test.reveal(row); test.step = 4; return
+ }
+ if (test.step === 4) {
+ test.grabbed = false
+ test.appWindow.contentItem.grabToImage(result => {
+ test.grabbed = result.saveToFile(test.evidence + "/capture-switch.png")
+ })
+ test.step = 5; return
+ }
+ if (test.step === 5 && test.grabbed) {
+ console.log("NATIVE_UI_PASS", test.phase)
+ Qt.quit()
+ }
+ } catch(e) { console.log("NATIVE_UI_FAIL", String(e)); Qt.quit() } }
+ }
+}
diff --git a/shaders/PackedCaptureToLinear.hlsl b/shaders/PackedCaptureToLinear.hlsl
index 79d4b283..c94c0d47 100644
--- a/shaders/PackedCaptureToLinear.hlsl
+++ b/shaders/PackedCaptureToLinear.hlsl
@@ -3,10 +3,12 @@
// UYVY / YVYU with the same color contract as RgbToLinear / Yuy2ToLinear.
// packing: 1 BGR24, 2 RGB555, 3 RGB565, 4 UYVY, 5 YVYU.
#include "HdrColor.hlsli"
+#include "HdrToSdr.hlsli"
#include "ColorGrade.hlsli"
cbuffer Params : register(b0) {
uint width; uint height; uint transfer; uint limitedU;
float limited; float matrix709; float primaries2020; uint packing;
+ float hdrWorking; float sourcePeak; float targetPeak; float reserved;
float4 colorRow0; float4 colorRow1; float4 colorRow2; float4 colorControls; float4 colorFlags;
};
Texture2D<float4> packedBytes : register(t0);
@@ -21,11 +23,30 @@ uint byteAt(uint y, uint index) {
const float4 t = packedBytes[uint2(index >> 2, y)];
return uint(round(saturate(t[index & 3]) * 255.0));
}
+uint wordAt(uint y,uint index){
+ const uint base=index*4;
+ return byteAt(y,base)|(byteAt(y,base+1)<<8)|(byteAt(y,base+2)<<16)|(byteAt(y,base+3)<<24);
+}
[numthreads(16,16,1)]
void main(uint3 p : SV_DispatchThreadID) {
if (p.x >= width || p.y >= height) return;
float3 rgb;
- if (packing == 4 || packing == 5) {
+ if (packing == 6) {
+ const uint base=(p.x/6)*4,i=p.x%6;
+ const uint a=wordAt(p.y,base),b=wordAt(p.y,base+1),c=wordAt(p.y,base+2),d=wordAt(p.y,base+3);
+ const uint ys[6]={(a>>10)&1023,b&1023,(b>>20)&1023,(c>>10)&1023,d&1023,(d>>20)&1023};
+ const uint us[3]={a&1023,(b>>10)&1023,(c>>20)&1023},vs[3]={(a>>20)&1023,c&1023,(d>>10)&1023};
+ float y=float(ys[i])/1023.0;float2 uv=(float2(us[i/2],vs[i/2])-512.0)/1023.0;
+ if(limited>0.5){y=(float(ys[i])-64.0)/876.0;uv=(float2(us[i/2],vs[i/2])-512.0)/896.0;}
+ rgb=matrix709>1.5?float3(y+1.4746*uv.y,y-.164553*uv.x-.571353*uv.y,y+1.8814*uv.x)
+ :matrix709>.5?float3(y+1.5748*uv.y,y-.187324*uv.x-.468124*uv.y,y+1.8556*uv.x)
+ :float3(y+1.402*uv.y,y-.344136*uv.x-.714136*uv.y,y+1.772*uv.x);
+ rgb=saturate(rgb);
+ } else if(packing==7){
+ const uint v=wordAt(p.y,p.x);
+ rgb=float3((v>>22)&1023,(v>>12)&1023,(v>>2)&1023)/1023.0;
+ if(limitedU!=0)rgb=saturate((rgb-64.0/1023.0)*(1023.0/876.0));
+ } else if (packing == 4 || packing == 5) {
const float4 pair = packedBytes[uint2(p.x / 2, p.y)];
const bool second = (p.x & 1) != 0;
float y, cb, cr;
@@ -47,8 +68,23 @@ void main(uint3 p : SV_DispatchThreadID) {
else rgb = float3(((v >> 11) & 31) / 31.0, ((v >> 5) & 63) / 63.0, (v & 31) / 31.0);
}
if (limitedU != 0 && packing <= 3) rgb = saturate((rgb - 16.0 / 255.0) * (255.0 / 219.0));
- float3 decoded = float3(decode(rgb.r), decode(rgb.g), decode(rgb.b));
- if (primaries2020 > 0.5) decoded = HdrTo709(decoded);
- if (colorFlags.x > 0.5) { ColorGradeParams grade = { colorRow0, colorRow1, colorRow2, colorControls, colorFlags }; decoded = ColorGradeApplyWithFlags(decoded, grade); }
+ float3 decoded;
+ if(transfer>=4){
+ float3 nits;
+ if(transfer==4){
+ const float3 q=pow(saturate(rgb),32.0/2523.0);
+ nits=10000.0*pow(max(q-3424.0/4096.0,0)/max(2413.0/128.0-2392.0/128.0*q,1e-6),16384.0/2610.0);
+ }else{
+ const float3 scene=select(rgb<=.5,rgb*rgb/3.0,(exp((rgb-.55991073)/.17883277)+.28466892)/12.0);
+ nits=1000.0*scene*pow(max(dot(scene,float3(.2627,.6780,.0593)),0),.2);
+ }
+ float3 linear709=primaries2020>.5?HdrTo709(nits):nits;
+ if(colorFlags.x>.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};linear709=ColorGradeApplyWithFlags(linear709/203.0,grade)*203.0;}
+ decoded=hdrWorking>.5?linear709/80.0:HdrToSdr(linear709,sourcePeak,targetPeak);
+ }else{
+ decoded=float3(decode(rgb.r),decode(rgb.g),decode(rgb.b));
+ if(primaries2020>.5)decoded=HdrTo709(decoded);
+ if(colorFlags.x>.5){ColorGradeParams grade={colorRow0,colorRow1,colorRow2,colorControls,colorFlags};decoded=ColorGradeApplyWithFlags(decoded,grade);}
+ }
linearRgb[p.xy] = float4(decoded, 1);
}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index f0dc8670..c98d6e8a 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -23,6 +23,7 @@
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/DeckLinkCapture.h"
#include "veyra/source/ScreenCaptureSource.h"
#include "veyra/xbox/DisconnectPolicy.h"
#ifdef VEYRA_ENABLE_REMOTEPLAY
@@ -545,9 +546,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
{std::lock_guard lock(mutex_);snapshot_.sourceHdr=gd.hdrInput;}
gd.highQualityPresentation=isRemote&&activeSource->info().color.reconstructChroma;
gd.rgbInput=isImage||isScreen||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);
- gd.captureBitDepth=activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::P010?10:activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;
+ auto ingressBitDepth=[](pipeline::SourcePixelFormat format){return format==pipeline::SourcePixelFormat::P010||format==pipeline::SourcePixelFormat::V210||format==pipeline::SourcePixelFormat::Rgb10xLE?10u:format==pipeline::SourcePixelFormat::P016?16u:8u;};
+ gd.captureBitDepth=ingressBitDepth(activeSource->info().color.pixelFormat);
gd.yuy2Input=isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Yuy2;gd.stillImage=isImage;
gd.packedInput=isCapture?pipeline::packedInputCode(activeSource->info().color.pixelFormat):0;
+ auto captureGraphColor=activeSource->info().color;
const bool nvidiaAdapter=ctx.adapter().isNvidia;
// AMD adapters run NR on the lmxxf runtime. Both the normalization
// and the stage description used to drop NR on every non-NVIDIA
@@ -1159,7 +1162,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
captureSource.setBufferMode(unsigned(options.settings.captureBuffer));
if(captureSource.reconnect(muted_?0.0f:volume_.load(),unsigned(options.settings.audioSync),options.settings.audioOffsetMs)){
captureRecovering=false;reset=true;pendingResetCause=pipeline::ResetReason::DeviceLost;captureSampler.reset();
- {std::lock_guard lock(mutex_);snapshot_.captureRecovering=false;}
+ {std::lock_guard lock(mutex_);snapshot_.captureRecovering=false;
+ if(captureSource.info().videoDecodePath=="decklink")snapshot_.nominalSourceFps=captureSource.info().averageFps;}
status(L"采集设备已重新连接,等待新画面");
}else{
captureRetryAt=Clock::now()+std::chrono::seconds(std::min(5u,captureRetries));
@@ -1535,7 +1539,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
captureSource.videoReset();av_frame_free(&cachedFrame);hasOutput=false;out={};
captureRecovering=true;captureRetries=0;captureRetryAt=Clock::now()+std::chrono::milliseconds(500);
{std::lock_guard lock(mutex_);snapshot_.captureRecovering=true;snapshot_.captureFps=0;}
- status(L"采集信号中断,等待原设备恢复");continue;
+ status(captureSource.errorMessage().empty()?L"采集信号中断,等待原设备恢复":captureSource.errorMessage());continue;
}
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){const auto recovery=remote->recoveryStatus();status(recovery.message.empty()?L"PS5 串流异常,请检查主机状态后重新连接。":recovery.message,true);break;}
@@ -1584,11 +1588,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
status(isScreen?screenSource.status():isCapture?L"采集信号中断,请检查设备连接或格式":source.errorMessage().empty()?L"视频解码或时间戳错误":source.errorMessage(),true);break;}
}
if(isScreen){std::lock_guard lock(mutex_);snapshot_.sourceNotice=screenSource.status();}
- if((isStream||isScreen)&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height||(isScreen&&gd.hdrInput!=activeSource->info().color.isHdrPath()))){
+ const bool nativeCapture=physicalCapture&&activeSource->info().videoDecodePath=="decklink";
+ if((isStream||isScreen||nativeCapture)&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height||(isScreen&&gd.hdrInput!=activeSource->info().color.isHdrPath())||
+ (nativeCapture&&!source::decklink::sameColor(captureGraphColor,activeSource->info().color)))){
drainLivePresentation();if(!ring.drainQueue()){status(L"串流尺寸切换排空失败",true);break;}
width=uint32_t(frame->width);height=uint32_t(frame->height);
describeStages(stageRequest(options),options.snapshot(),gd);
gd.hdrInput=!isImage&&activeSource->info().color.isHdrPath();gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,displayHdrActive());
+ if(nativeCapture){
+ captureGraphColor=activeSource->info().color;gd.rgbInput=captureGraphColor.pixelFormat==pipeline::SourcePixelFormat::Bgra8;
+ gd.yuy2Input=false;gd.packedInput=pipeline::packedInputCode(captureGraphColor.pixelFormat);gd.captureBitDepth=ingressBitDepth(captureGraphColor.pixelFormat);
+ std::lock_guard lock(mutex_);snapshot_.sourceWidth=width;snapshot_.sourceHeight=height;snapshot_.sourceHdr=gd.hdrInput;snapshot_.sourceDisplayAspect=activeSource->info().displayAspect;
+ }
presenter.close();graph->shutdown();recentGraphCache.evict("source-resize");
graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);graphBytes=0;out={};hasOutput=false;
if(!graph->initialize(gd)||!openPreparedPresenter(options)){if(!stop_)status(L"串流尺寸切换失败",true);break;}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 4d9f4b6f..4597de1d 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -63,8 +63,10 @@ constexpr int64_t usPerSecond = 1000000;
float uintBits(uint32_t v) { return std::bit_cast<float>(v); }
// N1 packed capture ingress helpers. Codes match pipeline::packedInputCode:
-// 1 BGR24, 2 RGB555, 3 RGB565, 4 UYVY, 5 YVYU.
+// 1 BGR24, 2 RGB555, 3 RGB565, 4 UYVY, 5 YVYU, 6 v210, 7 RGBXLE10.
unsigned packedIngressRowBytes(uint32_t code,unsigned width){
+ if(code==6)return ((width+5)/6)*16;
+ if(code==7)return width*4;
return code==1?width*3:width*2;
}
unsigned packedIngressTexels(uint32_t code,unsigned width){
@@ -77,6 +79,7 @@ AVPixelFormat packedIngressFormat(uint32_t code){
case 3:return AV_PIX_FMT_RGB565LE;
case 4:return AV_PIX_FMT_UYVY422;
case 5:return AV_PIX_FMT_YVYU422;
+ case 6:case 7:return AV_PIX_FMT_BGRA; // raw storage carrier, explicitly unpacked
default:break;
}
return AV_PIX_FMT_NONE;
@@ -92,6 +95,9 @@ uint8_t packedIngressLuma(const uint8_t* data,ptrdiff_t linesize,uint32_t code,u
const unsigned r=(w>>11)&31,g=(w>>5)&63,b=w&31;return uint8_t((54*(r<<3|r>>2)+183*(g<<2|g>>4)+19*(b<<3|b>>2)+128)>>8);}
case 4:return p[x*2+1]; // UYVY: Y0 follows U
case 5:return p[x*2]; // YVYU: Y0 leads
+ case 6:{const auto* q=p+(x/6)*16;uint32_t words[4];std::memcpy(words,q,16);
+ constexpr unsigned word[]={0,1,1,2,3,3},shift[]={10,0,20,10,0,20};return uint8_t(((words[word[x%6]]>>shift[x%6])&1023)>>2);}
+ case 7:{uint32_t word;std::memcpy(&word,p+x*4,4);const auto r=(word>>22)&1023,g=(word>>12)&1023,b=(word>>2)&1023;return uint8_t(std::min(255u,(54*r+183*g+19*b+512)>>10));}
default:break;
}
return 0;
@@ -1517,7 +1523,7 @@ bool EnhanceGraph::createComputePasses()
const UINT ingressUavCount = preGradeRgba_ ? 2u : 1u;
if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 12, 2, ingressUavCount, 12+kColorGradeConstantCount, 4)) return false;
const char* rgbShader=desc_.packedInput?"PackedCaptureToLinear.dxil":desc_.yuy2Input?"Yuy2ToLinear.dxil":"RgbToLinear.dxil";
- if((desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)&&(!rgbPass_.loadShader(rgbShader,cs)||!rgbPass_.create(context_.device(),cs,12,1,ingressUavCount,8+kColorGradeConstantCount,4)))return false;
+ if((desc_.rgbInput||desc_.yuy2Input||desc_.packedInput)&&(!rgbPass_.loadShader(rgbShader,cs)||!rgbPass_.create(context_.device(),cs,12,1,ingressUavCount,(desc_.packedInput?12:8)+kColorGradeConstantCount,4)))return false;
// Descriptor budget grows with the NR stack: encode needs one SRV+UAV pair
// per layer, decode needs three SRVs and one UAV per layer. The base 8
// slots the single-layer graph always used are kept as the floor.
@@ -1919,7 +1925,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
const bool gpuRgb=desc_.rgbInput&&frame->format==AV_PIX_FMT_D3D11&&hardwareSurface&&hardwareSurface->present();
if(resolved.scRgb&&(!gpuRgb||resolved.transfer!=TransferFunction::Linear||resolved.primaries!=ColorPrimaries::BT709||hardwareSurface->texture->GetDesc().Format!=DXGI_FORMAT_R16G16B16A16_FLOAT))return false;
- if (resolved.isHdrPath()&&(!desc_.hdrInput||(!resolved.scRgb&&desc_.rgbInput)||desc_.yuy2Input||desc_.packedInput)) {
+ const bool packedHdr=desc_.packedInput==6||desc_.packedInput==7;
+ if (resolved.isHdrPath()&&(!desc_.hdrInput||(!resolved.scRgb&&desc_.rgbInput)||desc_.yuy2Input||(desc_.packedInput&&!packedHdr))) {
veyra::log::error("graph", "HDR input requires an explicit YUV HDR contract; RGB/YUY2 HDR ingress is unsupported"); return false;
}
if(std::abs(ptsMs)>9e13){veyra::log::error("timeline","PTS outside representable range");return false;}
@@ -2013,7 +2020,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// (CaptureUploadFrame.h): the GPU copies from the frame's own buffer.
if(auto* upload=(packed||desc_.yuy2Input)?captureUploadFrame(frame):nullptr;upload&&upload->direct&&upload->proxyValid&&upload->planes==1&&
upload->device.Get()==context_.device()&&frame->data[0]==upload->mapped&&upload->width==srcW_&&upload->height==srcH_&&
- upload->pitch>=ingressTexels*4&&upload->pixelBytes==(packed&&desc_.packedInput==1?3u:2u))gpuDirectFrame=upload;
+ upload->pitch>=ingressTexels*4&&upload->pixelBytes==(packed&&desc_.packedInput>=6?4u:packed&&desc_.packedInput==1?3u:2u))gpuDirectFrame=upload;
if(!gpuDirectFrame)for(uint32_t y=0;y<srcH_;++y){
auto* dst=mappedRgb_[parity]+y*rgbPitch_;const auto* src=frame->data[0]+ptrdiff_t(y)*frame->linesize[0];
if(packed||desc_.yuy2Input||frame->format==AV_PIX_FMT_RGBA)std::memcpy(dst,src,size_t(ingressRowBytes));
@@ -2210,9 +2217,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
auto convertInput=[&](bool grade, ID3D12Resource* target, UINT uavSlot){
tracker_.transition(list, target, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){
- float c[8+kColorGradeConstantCount]={uintBits(srcW_),uintBits(srcH_),uintBits(workingTransferCode(resolved)),uintBits(resolved.range==ColorRange::Limited?1u:0u),
+ float c[12+kColorGradeConstantCount]={uintBits(srcW_),uintBits(srcH_),uintBits(resolved.transfer==TransferFunction::PQ?4u:resolved.transfer==TransferFunction::HLG?5u:workingTransferCode(resolved)),uintBits(resolved.range==ColorRange::Limited?1u:0u),
resolved.range==ColorRange::Full?0.0f:1.0f,resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,resolved.primaries==ColorPrimaries::BT2020?1.0f:0.0f,uintBits(desc_.packedInput)};
- if(grade)packColorGradeConstants(colorTables_,c+8);
+ if(desc_.packedInput){c[8]=desc_.hdrWorking()?1.f:0.f;c[9]=toneMapPeakNits_;c[10]=203.f;}
+ if(grade)packColorGradeConstants(colorTables_,c+(desc_.packedInput?12:8));
if(resolved.scRgb){c[4]=desc_.hdrWorking()?1.f:2.f;c[5]=toneMapPeakNits_;}
rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,gpuRgb?3+parity:0).ptr,gpuHandleOf(rgbPass_,1+uavSlot).ptr,gpuHandleOf(rgbPass_,8).ptr);
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 8e6121e5..d4033430 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -1,4 +1,5 @@
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/DeckLinkCapture.h"
#include "veyra/source/CaptureFrameRate.h"
#include "veyra/source/WasapiAudioInput.h"
#include "veyra/source/CaptureTiming.h"
@@ -269,7 +270,8 @@ static bool writeCaptureFrame(const CaptureMediaLayout& layout,const uint8_t* da
if(!data||bytes<layout.sampleBytes)return false;
pipeline::interleaveCaptureI420(frame,data,layout.stride,data+layout.chromaOffset,data+layout.secondChromaOffset,layout.chromaStride,layout.width,layout.height,flip);
}else if(!copyCaptureSample(layout,data,bytes,frame,flipRows))return false;
- pipeline::sampleCaptureUploadProxy(frame,data,layout.stride,flip);
+ if(layout.packing==CapturePacking::V210)pipeline::sampleCaptureV210Proxy(frame,data,layout.stride,flip);
+ else pipeline::sampleCaptureUploadProxy(frame,data,layout.stride,flip);
return true;
}
struct CaptureCardSource::Impl:ISampleGrabberCB {
@@ -371,6 +373,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
// Manual capture flip; read by the DirectShow callback thread.
std::atomic<bool> verticalFlip{false};
std::unique_ptr<WasapiAudioInput> wasapi;
+ std::unique_ptr<decklink::Capture> decklink;
std::wstring audioError;
AudioInputRecovery audioRecovery;
SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;
@@ -407,7 +410,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
}
long driverBuffers=0;
bool externalTimeAnchored=false;double externalTimeOffset=0;
- void deliverExternal(const uint8_t* data,size_t bytes,double deviceSeconds,bool discontinuity){
+ int64_t pendingNativePts100ns=0;
+ void deliverExternal(const uint8_t* data,size_t bytes,double deviceSeconds,bool discontinuity,int64_t duration100ns=0,int64_t nativePts100ns=0){
const auto arrival=Clock::now();
externalFrames.fetch_add(1,std::memory_order_relaxed);
AVFrame* staged=nullptr;bool written=false;
@@ -428,7 +432,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
if(pending)++dropped;
pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,discontinuity,received>0,pendingTime,time,info.averageFps);
pending=true;pendingTime=time;pendingArrival=arrival;
- pendingDuration=captureDuration(0,0,false,nominalDuration100ns);
+ pendingNativePts100ns=nativePts100ns;
+ pendingDuration=captureDuration(0,duration100ns,duration100ns>0,nominalDuration100ns);
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
recentArrivals.push_back(arrival);
@@ -437,6 +442,38 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
wake.notify_one();
if(frameEvent)SetEvent(frameEvent);
}
+ bool allocateFrames(const SourceOpenDesc& desc){auto& p=*this;
+ // Native capture with the graph's device: the three mailbox frames are
+ // D3D12 upload buffers, so the callback's copy is the only CPU copy of a
+ // frame (CaptureUploadFrame.h). Semiplanar and packed layouts keep their
+ // format; planar I420/YV12 becomes NV12. Layouts that are converted per
+ // pixel on the CPU (NV21, legacy rollback, 32-bit RGB) keep ordinary frames,
+ // as does VEYRA_TEST_CAPTURE_CPU_FRAMES=1 for A/B runs.
+ const bool packed10=p.layout.packing==CapturePacking::V210||p.layout.packing==CapturePacking::Rgb10xLE;
+ AVPixelFormat uploadFormat=AV_PIX_FMT_NONE;
+ if(desc.d3d12Device&&!p.compressedPath&&GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_CPU_FRAMES",nullptr,0)==0){
+ const bool legacyYuy2=p.layout.format==AV_PIX_FMT_YUYV422&&(p.layout.packing==CapturePacking::Uyvy||p.layout.packing==CapturePacking::Yvyu);
+ if(packed10)uploadFormat=AV_PIX_FMT_BGRA;
+ else if(p.layout.planes==3&&p.layout.format==AV_PIX_FMT_YUV420P&&p.info.width%2==0&&p.info.height%2==0)uploadFormat=AV_PIX_FMT_NV12;
+ else if(p.layout.planes==(pipeline::captureUploadPixelBytes(p.layout.format)&&(p.layout.format==AV_PIX_FMT_NV12||p.layout.format==AV_PIX_FMT_P010||p.layout.format==AV_PIX_FMT_P016)?2u:1u)&&
+ p.layout.packing!=CapturePacking::Nv21&&!legacyYuy2)uploadFormat=p.layout.format;
+ }
+ const bool uploadFrames=uploadFormat!=AV_PIX_FMT_NONE;
+ unsigned uploadBacked=0;
+ for(auto** f:{&p.frame,&p.pendingFrame,&p.stagingFrame}){
+ *f=uploadFrames?pipeline::allocCaptureUploadFrame(static_cast<ID3D12Device*>(desc.d3d12Device),uploadFormat,unsigned(p.info.width),unsigned(p.info.height),packed10):nullptr;
+ if(*f){++uploadBacked;continue;}
+ *f=av_frame_alloc();if(!*f)return false;
+ (*f)->format=p.layout.format;(*f)->width=p.info.width;(*f)->height=p.info.height;
+ // 256-byte row alignment matches the graph's D3D12 upload pitch, so
+ // the ingest copy is one memcpy per plane instead of one per row.
+ if(av_frame_get_buffer(*f,256)<0)return false;
+ }
+ log::info("capture",std::format("mailbox frames uploadBacked={} of 3 layoutFormat={} frameFormat={} (single CPU copy when 3)",uploadBacked,int(p.layout.format),int(uploadFrames&&uploadBacked==3?uploadFormat:p.layout.format)));
+ p.stagingBusy=false;
+ if(!p.frameEvent)p.frameEvent=CreateEventW(nullptr,FALSE,FALSE,nullptr);
+ return p.frameEvent!=nullptr;
+ }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}
ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}
// Decode worker loop: pop a compressed payload, decode it with our own
@@ -689,6 +726,7 @@ std::vector<CaptureDevice> CaptureCardSource::deviceDetails(bool audio){
}
result.push_back(std::move(device));
}
+ if(!audio)for(auto& device:decklink::devices())result.push_back({std::move(device.name),std::move(device.path),true,false});
if(audio)for(auto& endpoint:WasapiAudioInput::devices())result.push_back({std::move(endpoint.name),std::move(endpoint.id),false,true});
return result;
}
@@ -735,16 +773,26 @@ std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config,bool preferD
return out;
}
std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){
+ const auto details=deviceDetails();if(device<details.size()&&decklink::isPath(details[device].path))return formatsByPath(details[device].path);
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){
+ if(decklink::isPath(devicePath)){
+ std::vector<CaptureFormat> out;
+ for(const auto& device:decklink::devices())if(device.path==devicePath&&device.autoDetection)
+ out.push_back({0,0,0,0,L"自动检测实际信号 · BMD 原生",decklink::modeKey(0),0,0,true});
+ int index=1;for(const auto& mode:decklink::modes(devicePath))out.push_back({index++,mode.width,mode.height,double(mode.scale)/mode.duration,
+ std::format(L"{} · {} x {} @ {:.3f} fps · {} · BMD 原生",mode.name,mode.width,mode.height,double(mode.scale)/mode.duration,mode.interlaced?L"隔行":L"逐行"),decklink::modeKey(mode.id),1,0,false});
+ return out;
+ }
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();
+ if(decklink::isPath(devicePath)){error=L"BMD 原生入口跟随 Desktop Video Setup 的 HDMI/SDI 输入设置;请在该程序选择输入口,再使用自动检测或手动制式。";return false;}
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);
@@ -810,7 +858,60 @@ void CaptureCardSource::videoReset(bool resetAudio){if(p_->wasapi)p_->wasapi->vi
void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->wasapi)p_->wasapi->setSync(mode,offset);else if(p_->audioSession)p_->audioSession->setSync(mode,offset);}
sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->wasapi?p_->wasapi->snapshot():p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};if(!p_->audioError.empty())state.error=p_->audioError;return state;}
bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}
+bool CaptureCardSource::configureDeckLink(const SourceOpenDesc& desc){
+ auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;
+ const auto formats=formatsByPath(selection.videoPath);
+ const auto* selected=selectCaptureFormat(formats,selection.format,selection.formatKey);
+ if(!selected){error_=L"保存的 BMD 制式已不可用,请刷新并重新选择";return false;}
+ p.decklink=std::make_unique<decklink::Capture>();
+ if(!p.decklink->configure(selection.videoPath,selected->key,selection.audio==kCaptureAudioFromVideoDevice)){
+ error_=p.decklink->error();p.decklink.reset();return false;
+ }
+ const auto input=p.decklink->contract();const auto mode=p.decklink->mode();
+ p.layout={};auto& layout=p.layout;layout.width=input.width;layout.height=input.height;layout.stride=input.stride;
+ layout.rowBytes=unsigned(decklink::rowBytes(input.pixel,input.width));layout.sampleBytes=size_t(input.stride)*input.height;
+ layout.bottomUp=input.bottomUp;layout.duration=input.duration100ns;layout.color=input.color;
+ applyCaptureColorOverride(layout.color,selection.colorOverride);
+ switch(input.pixel){
+ case decklink::Pixel::Uyvy8:layout.packing=CapturePacking::Uyvy;layout.format=AV_PIX_FMT_UYVY422;break;
+ case decklink::Pixel::Bgra8:layout.packing=CapturePacking::Bgra32;layout.format=AV_PIX_FMT_BGR0;break; // capture is opaque, ignore undefined alpha
+ case decklink::Pixel::V210:layout.packing=CapturePacking::V210;layout.format=AV_PIX_FMT_BGRA;break;
+ case decklink::Pixel::Rgb10xLE:layout.packing=CapturePacking::Rgb10xLE;layout.format=AV_PIX_FMT_BGRA;break;
+ }
+ if(layout.color.isHdrPath()&&input.pixel!=decklink::Pixel::V210&&input.pixel!=decklink::Pixel::Rgb10xLE){error_=L"BMD HDR 需要 10 位原生输入格式";p.decklink.reset();return false;}
+ p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=input.width;p.info.height=input.height;
+ p.info.displayAspect=double(input.width)/input.height;p.info.duration=pipeline::Rational::unknown();p.info.color=layout.color;
+ p.info.averageFps=double(mode.scale)/mode.duration;p.info.nominalRateNum=int(mode.scale);p.info.nominalRateDen=int(mode.duration);
+ p.info.timestampQuantum=1e-7;p.info.videoDecodePath="decklink";
+ p.info.videoPixelFormatName=input.pixel==decklink::Pixel::V210?"v210":input.pixel==decklink::Pixel::Rgb10xLE?"R10l":input.pixel==decklink::Pixel::Uyvy8?"UYVY":"BGRA";
+ if(selection.requestedFps>0&&!captureFrameRateMatches(selection.requestedFps,layout.duration)){
+ error_=std::format(L"BMD 实际信号为 {:.3f} FPS,与请求的 {:.3f} FPS 不一致;设为 0 可跟随实际信号",p.info.averageFps,selection.requestedFps);p.decklink.reset();return false;
+ }
+ p.nominalDuration100ns=layout.duration;p.externalTimeAnchored=true;p.externalTimeOffset=0;
+ if(!p.allocateFrames(desc)){error_=L"BMD 采集帧缓冲分配失败";return false;}
+ if(selection.audio==kCaptureAudioFromVideoDevice){
+ WAVEFORMATEX wave{};wave.wFormatTag=WAVE_FORMAT_PCM;wave.nChannels=2;wave.nSamplesPerSec=48000;wave.wBitsPerSample=16;wave.nBlockAlign=4;wave.nAvgBytesPerSec=192000;
+ p.audioSession=std::make_unique<sink::CaptureAudioSession>();
+ if(!p.audioSession->configure(wave,sizeof(wave))){p.audioSession.reset();p.audioError=L"BMD PCM 音频配置失败;视频继续运行";}
+ }else if(selection.audio==kCaptureAudioWasapi){
+ p.wasapi=std::make_unique<WasapiAudioInput>();
+ if(!p.wasapi->configure(selection.audioPath)){p.wasapi.reset();p.audioError=L"WASAPI 音频端点无效;视频继续运行";}
+ }else if(selection.audio>=0){
+ // Optional independent DirectShow audio, retaining the user's explicit
+ // endpoint. Native video never opens a second DirectShow video stream.
+ HRESULT hr=CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.graph));
+ if(SUCCEEDED(hr))hr=CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.builder));
+ if(SUCCEEDED(hr))hr=p.builder->SetFiltergraph(p.graph.Get());
+ if(SUCCEEDED(hr)&&connectDirectShowAudio(desc))hr=p.graph.As(&p.control);
+ else if(SUCCEEDED(hr))hr=E_FAIL;
+ log::info("decklink-audio",std::format("separate DirectShow audio hr=0x{:08X}",uint32_t(hr)));
+ if(FAILED(hr))p.audioError=L"独立采集音频配置失败;BMD 原生视频继续运行";
+ }
+ p.configured=true;reconnectDesc_=desc;reconnectFormat_=selected->key;reconnectInfo_=p.info;
+ return true;
+}
bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.clear();p_->lastAudioGain=-1;auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;const unsigned index=selection.videoIndex;int format=selection.format;const int audio=selection.audio;
+ if(selection.stable&&decklink::isPath(selection.videoPath))return configureDeckLink(desc);
if(selection.stable?!configuration(selection.videoPath,p.graph,p.builder,p.device,p.config):!configuration(index,p.graph,p.builder,p.device,p.config))return false;
const auto available=enumerateFormats(p.config.Get());
const auto* chosen=selectCaptureFormat(available,format,selection.formatKey);
@@ -1055,33 +1156,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle
}
if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events)))return false;
if(p.grab&&(FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0))))return false;
- // Native capture with the graph's device: the three mailbox frames are
- // D3D12 upload buffers, so the callback's copy is the only CPU copy of a
- // frame (CaptureUploadFrame.h). Semiplanar and packed layouts keep their
- // format; planar I420/YV12 becomes NV12. Layouts that are converted per
- // pixel on the CPU (NV21, legacy rollback, 32-bit RGB) keep ordinary frames,
- // as does VEYRA_TEST_CAPTURE_CPU_FRAMES=1 for A/B runs.
- AVPixelFormat uploadFormat=AV_PIX_FMT_NONE;
- if(desc.d3d12Device&&!p.compressedPath&&GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_CPU_FRAMES",nullptr,0)==0){
- const bool legacyYuy2=p.layout.format==AV_PIX_FMT_YUYV422&&(p.layout.packing==CapturePacking::Uyvy||p.layout.packing==CapturePacking::Yvyu);
- if(p.layout.planes==3&&p.layout.format==AV_PIX_FMT_YUV420P&&p.info.width%2==0&&p.info.height%2==0)uploadFormat=AV_PIX_FMT_NV12;
- else if(p.layout.planes==(pipeline::captureUploadPixelBytes(p.layout.format)&&(p.layout.format==AV_PIX_FMT_NV12||p.layout.format==AV_PIX_FMT_P010||p.layout.format==AV_PIX_FMT_P016)?2u:1u)&&
- p.layout.packing!=CapturePacking::Nv21&&!legacyYuy2)uploadFormat=p.layout.format;
- }
- const bool uploadFrames=uploadFormat!=AV_PIX_FMT_NONE;
- unsigned uploadBacked=0;
- for(auto** f:{&p.frame,&p.pendingFrame,&p.stagingFrame}){
- *f=uploadFrames?pipeline::allocCaptureUploadFrame(static_cast<ID3D12Device*>(desc.d3d12Device),uploadFormat,unsigned(p.info.width),unsigned(p.info.height)):nullptr;
- if(*f){++uploadBacked;continue;}
- *f=av_frame_alloc();if(!*f)return false;
- (*f)->format=p.layout.format;(*f)->width=p.info.width;(*f)->height=p.info.height;
- // 256-byte row alignment matches the graph's D3D12 upload pitch, so
- // the ingest copy is one memcpy per plane instead of one per row.
- if(av_frame_get_buffer(*f,256)<0)return false;
- }
- log::info("capture",std::format("mailbox frames uploadBacked={} of 3 layoutFormat={} frameFormat={} (single CPU copy when 3)",uploadBacked,int(p.layout.format),int(uploadFrames&&uploadBacked==3?uploadFormat:p.layout.format)));
- p.stagingBusy=false;
- if(!p.frameEvent)p.frameEvent=CreateEventW(nullptr,FALSE,FALSE,nullptr);
+ if(!p.allocateFrames(desc))return false;
if(compressedPath){
// Write targets: the frame the worker is filling plus one spare handed
// out by read(). Frames are never reused while the caller still owns
@@ -1462,10 +1537,19 @@ if(audioTypes.empty()&&(!allowBitstream||bitstreamTypes.empty())){log::warn("cap
return connectedAudio;
}
bool CaptureCardSource::start(){
- auto& p=*p_;if(p.info.opened)return true;if(!p.configured||!p.control)return false;
+ auto& p=*p_;if(p.info.opened)return true;if(!p.configured||(!p.control&&!p.decklink))return false;
if(p.audioSession&&p.audioSessionDeferred)log::info("capture-audio-bitstream","audio session starts with the first decoded bitstream frame");
else if(p.audioSession&&!p.audioSession->start())log::warn("capture-audio","audio start failed; retaining video capture");
p.audioRecovery.reset(GetTickCount64());
+ if(p.decklink){
+ if(p.control){const HRESULT hr=p.control->Run();log::info("decklink-audio",std::format("Run separate audio hr=0x{:08X}",uint32_t(hr)));}
+ p.lastFrame=Impl::Clock::now();
+ p.info.opened=p.decklink->start([&p](const decklink::Frame& frame){p.deliverExternal(frame.data,frame.bytes,double(frame.pts100ns)/1e7,false,frame.duration100ns,frame.pts100ns);},
+ [&p](const void* data,size_t bytes,int64_t pts){if(p.audioSession)p.audioSession->push(data,bytes,double(pts)/10000,false);});
+ if(!p.info.opened){error_=p.decklink->error();return false;}
+ if(p.wasapi&&!p.wasapi->start())p.audioError=L"WASAPI 音频启动失败;视频继续运行";
+ return true;
+ }
// Driver frame age (observeDriverAge): fix the graph clock now and note its time at Run.
p.ageClock.Reset();p.runReference=0;p.driverAges.clear();
{ComPtr<IFilterGraph> fg;ComPtr<IMediaFilter> mf;
@@ -1532,6 +1616,7 @@ bool CaptureCardSource::reconnect(float gain,unsigned syncMode,int offsetMs){
const auto desc=reconnectDesc_;const auto key=reconnectFormat_;const auto expected=reconnectInfo_;
// Stop callbacks before carrying counters into the next device session.
// Never hold the mailbox lock while DirectShow Stop waits for a callback.
+ if(p_->decklink)p_->decklink->stop();
if(p_->control){const HRESULT hr=p_->control->Stop();log::info("capture-reconnect",std::format("Stop hr=0x{:08X}",uint32_t(hr)));if(FAILED(hr))return false;}
{std::lock_guard lock(p_->mutex);
receivedOffset_+=p_->received;deliveredOffset_+=p_->sequence;droppedOffset_+=p_->dropped;}
@@ -1541,7 +1626,7 @@ bool CaptureCardSource::reconnect(float gain,unsigned syncMode,int offsetMs){
auto reopen=desc;reopen.path=std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(selection.videoPath),format,selection.audio,encodePath(selection.audioPath),selection.colorOverride);
reopen.path+=capturePathOptions(selection.requestedFps,encodePath(key));
bool ok=configure(reopen);
- if(ok){const auto& current=p_->info;
+ if(ok&&!decklink::isPath(selection.videoPath)){const auto& current=p_->info;
ok=current.width==expected.width&&current.height==expected.height&&captureFrameRateMatches(expected.averageFps,p_->layout.duration)&&current.color.pixelFormat==expected.color.pixelFormat&&
current.color.transfer==expected.color.transfer&&current.color.matrix==expected.color.matrix&&current.color.primaries==expected.color.primaries&&
current.color.range==expected.color.range&&current.color.displayReferred709==expected.color.displayReferred709&&current.color.preserveSdrCodeValues==expected.color.preserveSdrCodeValues;
@@ -1561,6 +1646,7 @@ CaptureMetrics CaptureCardSource::metrics()const{
SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,30);}
SourceReadStatus CaptureCardSource::tryRead(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,0);}
SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,const AVFrame** frame,unsigned milliseconds){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;
+ if(p.decklink&&p.decklink->needsReopen()){error_=p.decklink->error();log::warn("decklink-reconnect",narrowForLog(error_));return SourceReadStatus::Error;}
// Magewell: stop DirectShow video once the SDK has proved itself (30 frames), and run
// it again if the SDK thread ends, so video never stops altogether.
if(p.magewellDelivering.load()&&p.control){
@@ -1575,7 +1661,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
}
}
long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)log::warn("capture-reconnect",std::format("DirectShow event={} detail=0x{:X}",code,uint64_t(a)));p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}
- double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;AVFrame* delivered=nullptr;AVFrame* expiredHardware=nullptr;bool feedDecode=false;
+ double time=0;int64_t nativeTime100ns=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;AVFrame* delivered=nullptr;AVFrame* expiredHardware=nullptr;bool feedDecode=false;
{
std::unique_lock lock(p.mutex);if(milliseconds)p.wake.wait_for(lock,std::chrono::milliseconds(milliseconds),[&]{return p.pending||p.callbackError;});
if(p.callbackError)return SourceReadStatus::Error;
@@ -1598,7 +1684,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
// must never be null here (SampleCB rejects that as an error).
std::swap(p.frame,p.pendingFrame);delivered=p.frame;
}
- p.pending=false;time=p.pendingTime;p.readArrival=p.pendingArrival;
+ p.pending=false;time=p.pendingTime;nativeTime100ns=p.pendingNativePts100ns;p.readArrival=p.pendingArrival;
duration=p.pendingDuration;
p.readAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();
if(!p.sequence)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Open);
@@ -1618,7 +1704,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
colorInfo=pipeline::resolveFrameColor(*delivered,p.layout.color);
if(delivered->format==AV_PIX_FMT_D3D12&&colorInfo.pixelFormat==pipeline::SourcePixelFormat::Unknown)colorInfo.pixelFormat=pipeline::SourcePixelFormat::NV12;
}
- delivered->pts=static_cast<int64_t>(time*10000000);delivered->duration=duration.isUnknown()?0:duration.to100ns();delivered->time_base={1,10000000};packet={};packet.pts={delivered->pts,10000000};packet.duration=duration;packet.colorInfo=colorInfo;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;
+ delivered->pts=p.decklink?nativeTime100ns:static_cast<int64_t>(time*10000000);delivered->duration=duration.isUnknown()?0:duration.to100ns();delivered->time_base={1,10000000};packet={};packet.pts={delivered->pts,10000000};packet.duration=duration;packet.colorInfo=colorInfo;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;
packet.sequence+=receivedOffset_;packet.sourceEpoch=epoch_;
packet.arrivalHost100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(p.readArrival.time_since_epoch()).count()/100;
if(log::verboseFrameLogs())log::info("capture-read-sample",std::format("source={} arrival={} read={} width={} height={} format={}",packet.sequence,packet.arrivalHost100ns,std::chrono::duration_cast<std::chrono::nanoseconds>(Impl::Clock::now().time_since_epoch()).count()/100,delivered->width,delivered->height,delivered->format));
@@ -1626,6 +1712,8 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
}
void CaptureCardSource::close()noexcept{
auto& p=*p_;
+ // Native stop detaches and joins callbacks before freeing mailbox/audio.
+ if(p.decklink){p.decklink->stop();p.decklink.reset();}
p.magewellDelivering=false;
if(p.magewell){p.magewell->stop();p.magewell.reset();}if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}
if(p.wasapi)p.wasapi->stop();p.wasapi.reset();
diff --git a/src/source/DeckLinkCapture.cpp b/src/source/DeckLinkCapture.cpp
new file mode 100644
index 00000000..8015426d
--- /dev/null
+++ b/src/source/DeckLinkCapture.cpp
@@ -0,0 +1,158 @@
+#include "veyra/source/DeckLinkCapture.h"
+#include "veyra/Log.h"
+#include <algorithm>
+#include <chrono>
+#include <condition_variable>
+#include <format>
+#include <mutex>
+#include <optional>
+
+namespace veyra::source::decklink {
+size_t rowBytes(Pixel p,uint32_t width){
+ if(p==Pixel::V210)return ((size_t(width)+5)/6)*16;
+ return size_t(width)*(p==Pixel::Uyvy8?2:4);
+}
+bool sameColor(const pipeline::ColorDescription& a,const pipeline::ColorDescription& b){
+ return a.pixelFormat==b.pixelFormat&&a.range==b.range&&a.matrix==b.matrix&&a.transfer==b.transfer&&
+ a.primaries==b.primaries&&a.displayReferred709==b.displayReferred709&&a.preserveSdrCodeValues==b.preserveSdrCodeValues&&
+ a.hdrMaxCllNits==b.hdrMaxCllNits&&a.hdrMaxFallNits==b.hdrMaxFallNits&&a.hdrMasteringPeakNits==b.hdrMasteringPeakNits;
+}
+bool isPath(std::wstring_view path){return path.starts_with(L"decklink-native:");}
+std::wstring modeKey(uint32_t id){return id?std::format(L"decklink:{:08x}",id):L"decklink:auto";}
+struct Capture::Impl {
+ std::unique_ptr<Driver> driver;
+ mutable std::mutex mutex;std::condition_variable changed;
+ std::optional<Signal> pending;
+ Frame contract;Mode mode;
+ bool automatic=false,embeddedAudio=false,probing=false,valid=false,running=false,reopen=false;
+ Pixel pixel=Pixel::V210;
+ std::wstring error;
+ std::function<void(const Frame&)> onVideo;
+ std::function<void(const void*,size_t,int64_t)> onAudio;
+};
+Capture::Capture(std::unique_ptr<Driver> driver):p_(std::make_unique<Impl>()){p_->driver=std::move(driver);}
+Capture::~Capture(){stop();}
+void Capture::failure(std::wstring error){
+ {std::lock_guard lock(p_->mutex);p_->error=std::move(error);p_->reopen=true;}
+ p_->changed.notify_all();
+}
+void Capture::formatChanged(const Signal& signal){
+ {std::lock_guard lock(p_->mutex);
+ const bool rgb=p_->pixel==Pixel::Bgra8||p_->pixel==Pixel::Rgb10xLE;
+ if(signal.mode.id==p_->mode.id&&signal.rgb==rgb)return; // StartStreams may repeat the current detection.
+ if(p_->running){p_->reopen=true;p_->error=L"BMD 输入制式/颜色格式已变化,正在重新检测信号";}
+ else if(p_->probing&&p_->automatic){p_->pending=signal;p_->valid=false;}
+ }
+ p_->changed.notify_all();
+}
+void Capture::video(const Frame& frame){
+ std::function<void(const Frame&)> callback;
+ {
+ std::lock_guard lock(p_->mutex);
+ if(!p_->running&&!p_->probing)return;
+ if(frame.noInput){
+ if(p_->running){p_->error=L"BMD 输入信号丢失,正在等待 HDMI/SDI 信号锁定";p_->reopen=true;}
+ p_->changed.notify_all();return;
+ }
+ if(p_->reopen||p_->pending)return;
+ if(frame.width!=p_->mode.width||frame.height!=p_->mode.height||frame.pixel!=p_->pixel){
+ if(p_->running){p_->error=L"BMD 帧布局已改变,正在重新协商采集";p_->reopen=true;}
+ return; // Frames queued before Pause/Flush are never published.
+ }
+ const bool ten=frame.pixel==Pixel::V210||frame.pixel==Pixel::Rgb10xLE;
+ if(!frame.data||frame.width<2||frame.width>3840||!frame.height||frame.height>2160||
+ frame.stride<rowBytes(frame.pixel,frame.width)||frame.stride>frame.width*8+16384||frame.bytes<size_t(frame.stride)*frame.height||frame.duration100ns<=0||
+ (frame.color.isHdrPath()&&!ten)){
+ p_->error=L"BMD 返回无效帧布局、时间戳或不受支持的 HDR 位深";p_->reopen=true;p_->changed.notify_all();return;
+ }
+ if(p_->probing){
+ p_->contract=frame;p_->contract.data=nullptr;p_->contract.bytes=0;p_->valid=true;p_->changed.notify_all();return;
+ }
+ if(frame.stride!=p_->contract.stride||frame.bottomUp!=p_->contract.bottomUp||!sameColor(frame.color,p_->contract.color)){
+ p_->error=L"BMD 输入颜色/行距合同已变化,正在重建处理链";p_->reopen=true;return;
+ }
+ callback=p_->onVideo;
+ }
+ // No source/control lock is held during the one ingest copy. The adapter
+ // retains the SDK frame for this call only; there is no extra frame queue.
+ if(callback)callback(frame);
+}
+void Capture::audio(const void* bytes,size_t size,int64_t pts){
+ std::function<void(const void*,size_t,int64_t)> callback;
+ {std::lock_guard lock(p_->mutex);if(p_->running&&!p_->reopen)callback=p_->onAudio;}
+ if(callback)callback(bytes,size,pts);
+}
+bool Capture::configure(std::wstring_view path,std::wstring_view key,bool audio,unsigned timeoutMs){
+ stop();auto& p=*p_;std::wstring why;
+ {std::lock_guard lock(p.mutex);p.error.clear();p.reopen=false;p.valid=false;p.contract={};p.pending.reset();p.embeddedAudio=audio;}
+ auto failed=[&](std::wstring message){p.driver->stop();std::lock_guard lock(p.mutex);p.probing=false;if(!message.empty())p.error=std::move(message);return false;};
+ if(!isPath(path)||!p.driver){failure(L"BMD 原生接口不可用,请安装 Desktop Video 驱动或使用 DirectShow 入口");return false;}
+ if(!p.driver->open(path,*this,why))return failed(why);
+ const auto available=p.driver->modes();
+ const bool automatic=key==L"decklink:auto"||key.empty();
+ {std::lock_guard lock(p.mutex);p.automatic=automatic;}
+ if(automatic&&!p.driver->autoDetection())return failed(L"这张 BMD 卡不支持自动检测,请选择与信号一致的手动制式");
+ const auto chosen=std::find_if(available.begin(),available.end(),[&](const Mode& m){return automatic||modeKey(m.id)==key;});
+ if(chosen==available.end())return failed(L"保存的 BMD 制式不可用,请重新选择");
+ auto enable=[&](const Mode& mode,Pixel pixel){
+ {std::lock_guard lock(p.mutex);p.mode=mode;p.pixel=pixel;p.valid=false;}
+ const bool ok=p.driver->enable(mode,pixel,automatic,audio,why);if(ok)why.clear();return ok;
+ };
+ // Prefer ten-bit output even for eight-bit signals: this avoids throwing
+ // away HDR precision before the first metadata-bearing frame arrives.
+ // Some drivers announce the detected mode during EnableVideoInput,
+ // before StartStreams. Do not lose that callback at the probe boundary.
+ {std::lock_guard lock(p.mutex);p.probing=true;}
+ if(!enable(*chosen,Pixel::V210)&&!enable(*chosen,Pixel::Uyvy8))return failed(why);
+ why.clear();
+ if(!p.driver->start(why))return failed(why);
+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::milliseconds(std::clamp(timeoutMs,1u,5000u));
+ bool ok=false;
+ for(;;){
+ std::optional<Signal> signal;
+ {std::unique_lock lock(p.mutex);
+ if(p.reopen)break;
+ if(p.pending){signal=p.pending;p.pending.reset();p.valid=false;}
+ else if(p.valid){ok=true;break;}
+ else if(p.changed.wait_until(lock,deadline)==std::cv_status::timeout)break;
+ }
+ if(signal){
+ // OBS's Pause -> EnableVideoInput -> Flush -> Start sequence,
+ // moved to the owner thread. Format callbacks never call control.
+ if(!p.driver->pause(why))break;
+ const Pixel preferred=signal->rgb?Pixel::Rgb10xLE:Pixel::V210;
+ bool enabled=enable(signal->mode,preferred);
+ if(!enabled&&signal->bits<=8)enabled=enable(signal->mode,signal->rgb?Pixel::Bgra8:Pixel::Uyvy8);
+ if(!enabled||!p.driver->flush(why)||!p.driver->start(why))break;
+ }
+ if(std::chrono::steady_clock::now()>=deadline)break;
+ }
+ std::wstring pauseError;
+ if(!p.driver->pause(pauseError)){if(why.empty())why=pauseError;ok=false;}
+ {std::lock_guard lock(p.mutex);p.probing=false;if(p.reopen||p.pending)ok=false;}
+ if(!ok){
+ {std::lock_guard lock(p.mutex);if(why.empty())why=p.error;}
+ if(why.empty())why=L"BMD 未检测到有效输入。请关闭占用采集卡的应用,并在 Desktop Video Setup 核对 HDMI/SDI 和制式;也可选择手动制式";
+ return failed(why);
+ }
+ if(!p.driver->flush(why))return failed(why);
+ log::info("decklink-signal",std::format("valid=1 mode=0x{:08X} extent={}x{} rate={}/{} interlaced={} pixel={} stride={} transfer={} primaries={} mailbox=1 probeFramesRetained=0",
+ p.mode.id,p.contract.width,p.contract.height,p.mode.scale,p.mode.duration,p.mode.interlaced,int(p.pixel),p.contract.stride,int(p.contract.color.transfer),int(p.contract.color.primaries)));
+ return true;
+}
+bool Capture::start(std::function<void(const Frame&)> video,std::function<void(const void*,size_t,int64_t)> audio){
+ {std::lock_guard lock(p_->mutex);if(!p_->valid||p_->reopen)return false;p_->onVideo=std::move(video);p_->onAudio=std::move(audio);p_->running=true;}
+ std::wstring why;if(p_->driver->start(why))return true;
+ {std::lock_guard lock(p_->mutex);p_->running=false;p_->error=std::move(why);}
+ return false;
+}
+void Capture::stop()noexcept{
+ {std::lock_guard lock(p_->mutex);p_->running=false;p_->probing=false;}
+ if(p_->driver)p_->driver->stop();
+ {std::lock_guard lock(p_->mutex);p_->onVideo={};p_->onAudio={};}
+}
+bool Capture::needsReopen()const{std::lock_guard lock(p_->mutex);return p_->reopen;}
+std::wstring Capture::error()const{std::lock_guard lock(p_->mutex);return p_->error;}
+Frame Capture::contract()const{std::lock_guard lock(p_->mutex);return p_->contract;}
+Mode Capture::mode()const{std::lock_guard lock(p_->mutex);return p_->mode;}
+}
diff --git a/src/source/DeckLinkDriver.cpp b/src/source/DeckLinkDriver.cpp
new file mode 100644
index 00000000..6d4c1986
--- /dev/null
+++ b/src/source/DeckLinkDriver.cpp
@@ -0,0 +1,221 @@
+// Capture lifecycle adapted from OBS Studio plugins/decklink,
+// e7f0b0d43c538f5d108aa4cbea473d57b3012a1a (GPL-2.0-or-later).
+// Veyra uses owner-thread negotiation, stable IDs, explicit metadata and its
+// existing upload mailbox. SDK headers are generated externally, never vendored.
+#include "veyra/source/DeckLinkCapture.h"
+#include "veyra/Log.h"
+#include <algorithm>
+#include <format>
+#include <optional>
+
+#if VEYRA_HAS_DECKLINK
+#include <windows.h>
+#include <wrl/client.h>
+#include <DeckLinkAPI_h.h>
+#include <atomic>
+#include <cmath>
+#include <condition_variable>
+#include <mutex>
+
+namespace veyra::source::decklink {
+using Microsoft::WRL::ComPtr;
+namespace {
+bool checked(HRESULT hr,const char* operation,std::wstring* error=nullptr){
+ log::info("decklink-api",std::format("{} hr=0x{:08X}",operation,uint32_t(hr)));
+ if(FAILED(hr)&&error)*error=std::format(L"BMD 原生接口 {} 失败(0x{:08X}),请检查驱动、输入制式和设备占用",std::wstring(operation,operation+strlen(operation)),uint32_t(hr));
+ return SUCCEEDED(hr);
+}
+std::wstring take(BSTR value){std::wstring s=value?std::wstring(value,SysStringLen(value)):L"";SysFreeString(value);return s;}
+struct Row {ComPtr<IDeckLink> device;ComPtr<IDeckLinkInput> input;Device details;};
+std::vector<Row> enumerate(){
+ std::vector<Row> out;ComPtr<IDeckLinkIterator> iterator;
+ const HRESULT hr=CoCreateInstance(__uuidof(CDeckLinkIterator),nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&iterator));
+ // A missing Desktop Video driver is normal on ordinary UVC systems.
+ if(FAILED(hr)){if(hr!=REGDB_E_CLASSNOTREG)checked(hr,"CreateIterator");return out;}
+ ComPtr<IDeckLink> device;
+ while(iterator->Next(&device)==S_OK){
+ Row row;row.device=device;
+ ComPtr<IDeckLinkProfileAttributes> attributes;
+ if(FAILED(device.As(&row.input))||FAILED(device.As(&attributes))){device.Reset();continue;}
+ LONGLONG id=0,sub=0;bool persistent=SUCCEEDED(attributes->GetInt(BMDDeckLinkPersistentID,&id));
+ if(!persistent&&FAILED(attributes->GetInt(BMDDeckLinkTopologicalID,&id))){log::warn("decklink-device","No stable ID; refusing ordinal mapping");device.Reset();continue;}
+ const auto subHr=attributes->GetInt(BMDDeckLinkSubDeviceIndex,&sub);
+ BSTR name=nullptr;const auto nameHr=device->GetDisplayName(&name);
+ row.details.name=take(name);if(FAILED(nameHr)||row.details.name.empty())row.details.name=L"Blackmagic DeckLink";
+ row.details.path=std::format(L"decklink-native:{}:{:016x}:{:x}",persistent?L"p":L"t",uint64_t(id),uint64_t(sub));
+ BOOL automatic=FALSE;const auto detectHr=attributes->GetFlag(BMDDeckLinkSupportsInputFormatDetection,&automatic);
+ row.details.autoDetection=SUCCEEDED(detectHr)&&automatic;
+ ComPtr<IDeckLinkConfiguration> config;LONGLONG port=0;
+ if(SUCCEEDED(device.As(&config)))checked(config->GetInt(bmdDeckLinkConfigVideoInputConnection,&port),"GetInputConnection");
+ row.details.name=std::format(L"[原生] {} · {}",row.details.name,port==bmdVideoConnectionHDMI?L"HDMI":port==bmdVideoConnectionSDI?L"SDI":L"跟随驱动输入");
+ log::info("decklink-device",std::format("stableKind={} id=0x{:016X} sub={} subHr=0x{:08X} autoDetect={} detectHr=0x{:08X} connection=0x{:X}",persistent?"persistent":"topological",uint64_t(id),sub,uint32_t(subHr),row.details.autoDetection,uint32_t(detectHr),uint64_t(port)));
+ out.push_back(std::move(row));device.Reset();
+ }
+ // A driver without unique sub-device IDs must never make two physical
+ // inputs share a saved identity. Leave those endpoints unselectable.
+ std::vector<std::wstring> ambiguous;
+ for(const auto& row:out)if(std::count_if(out.begin(),out.end(),[&](const Row& other){return other.details.path==row.details.path;})>1)ambiguous.push_back(row.details.path);
+ if(!ambiguous.empty())log::warn("decklink-device","Duplicate stable input IDs; refusing ambiguous endpoints");
+ std::erase_if(out,[&](const Row& row){return std::find(ambiguous.begin(),ambiguous.end(),row.details.path)!=ambiguous.end();});
+ return out;
+}
+Mode describe(IDeckLinkDisplayMode* mode){
+ Mode out;out.id=mode->GetDisplayMode();out.width=mode->GetWidth();out.height=mode->GetHeight();
+ BMDTimeValue duration=0;BMDTimeScale scale=0;
+ if(FAILED(mode->GetFrameRate(&duration,&scale)))return {};
+ out.duration=duration;out.scale=scale;
+ const auto field=mode->GetFieldDominance();out.interlaced=field==bmdUpperFieldFirst||field==bmdLowerFieldFirst;
+ BSTR name=nullptr;const HRESULT nameHr=mode->GetName(&name);out.name=take(name);if(FAILED(nameHr))out.name=L"BMD";
+ using namespace pipeline;
+ auto& c=out.color;c.range=ColorRange::Limited;c.transfer=TransferFunction::BT709;
+ c.transferAssumed=true;c.preserveSdrCodeValues=true;
+ const auto flags=mode->GetFlags();
+ if(flags&bmdDisplayModeColorspaceRec2020){c.matrix=YuvMatrix::BT2020NCL;c.primaries=ColorPrimaries::BT2020;}
+ else if(flags&bmdDisplayModeColorspaceRec709){c.matrix=YuvMatrix::BT709;c.primaries=ColorPrimaries::BT709;}
+ else{c.matrix=out.height>576?YuvMatrix::BT709:YuvMatrix::BT601;c.primaries=out.height>576?ColorPrimaries::BT709:out.height==576?ColorPrimaries::BT601_625:ColorPrimaries::BT601_525;c.matrixAssumed=c.primariesAssumed=(flags&bmdDisplayModeColorspaceRec601)==0;}
+ return out;
+}
+std::vector<Mode> readModes(IDeckLinkInput* input){
+ std::vector<Mode> out;ComPtr<IDeckLinkDisplayModeIterator> iterator;
+ if(!checked(input->GetDisplayModeIterator(&iterator),"GetDisplayModeIterator"))return out;
+ ComPtr<IDeckLinkDisplayMode> mode;
+ while(iterator->Next(&mode)==S_OK){auto m=describe(mode.Get());
+ if(m.width>=2&&m.width<=3840&&m.height&&m.height<=2160&&m.duration>0&&m.scale>0)out.push_back(std::move(m));mode.Reset();}
+ // A conservative seed only. The format-change callback, not this order,
+ // selects the real automatic mode before any frame can be published.
+ std::stable_sort(out.begin(),out.end(),[](const Mode& a,const Mode& b){const auto seed=[](const Mode& m){return m.width==1920&&m.height==1080&&!m.interlaced&&m.scale==m.duration*60;};return seed(a)&&!seed(b);});
+ return out;
+}
+BMDPixelFormat sdkPixel(Pixel p){switch(p){case Pixel::V210:return bmdFormat10BitYUV;case Pixel::Rgb10xLE:return bmdFormat10BitRGBXLE;case Pixel::Bgra8:return bmdFormat8BitBGRA;default:return bmdFormat8BitYUV;}}
+std::optional<Pixel> pixel(BMDPixelFormat p){switch(p){case bmdFormat10BitYUV:return Pixel::V210;case bmdFormat10BitRGBXLE:return Pixel::Rgb10xLE;case bmdFormat8BitBGRA:return Pixel::Bgra8;case bmdFormat8BitYUV:return Pixel::Uyvy8;default:return {};}}
+class Callback final:public IDeckLinkInputCallback {
+ std::atomic<ULONG> refs_{1};std::mutex mutex_;std::condition_variable idle_;
+ DriverSink* sink_;unsigned active_=0;bool accepting_=true;
+ pipeline::ColorDescription color_;std::atomic<bool> loggedFrame_{false},loggedMetadata_{false};std::atomic<int> noInput_{-1};
+ struct Entry {
+ Callback& owner;DriverSink* sink=nullptr;pipeline::ColorDescription color;
+ explicit Entry(Callback& o):owner(o){std::lock_guard lock(o.mutex_);if(o.accepting_){++o.active_;sink=o.sink_;color=o.color_;}}
+ ~Entry(){if(sink){std::lock_guard lock(owner.mutex_);if(--owner.active_==0)owner.idle_.notify_all();}}
+ };
+public:
+ explicit Callback(DriverSink& sink):sink_(&sink){}
+ void color(const pipeline::ColorDescription& c){std::lock_guard lock(mutex_);color_=c;loggedFrame_=loggedMetadata_=false;noInput_=-1;}
+ void detach(){std::lock_guard lock(mutex_);accepting_=false;}
+ void wait(){std::unique_lock lock(mutex_);idle_.wait(lock,[&]{return active_==0;});sink_=nullptr;}
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** out)override{if(!out)return E_POINTER;*out=nullptr;if(id!=IID_IUnknown&&id!=__uuidof(IDeckLinkInputCallback))return E_NOINTERFACE;*out=static_cast<IDeckLinkInputCallback*>(this);AddRef();return S_OK;}
+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs_;}
+ ULONG STDMETHODCALLTYPE Release()override{const auto n=--refs_;if(!n)delete this;return n;}
+ HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events,IDeckLinkDisplayMode* display,BMDDetectedVideoInputFormatFlags flags)override{
+ Entry entry(*this);if(!entry.sink)return S_OK;
+ try{
+ if(!display)return E_POINTER;
+ Signal signal;signal.mode=describe(display);signal.rgb=(flags&bmdDetectedVideoInputRGB444)!=0;
+ signal.bits=flags&bmdDetectedVideoInput12BitDepth?12:flags&bmdDetectedVideoInput10BitDepth?10:flags&bmdDetectedVideoInput8BitDepth?8:0;
+ log::info("decklink-format",std::format("events=0x{:X} mode=0x{:08X} extent={}x{} duration={}/{} interlaced={} detectedFlags=0x{:X} rgb={} bits={}",events,signal.mode.id,signal.mode.width,signal.mode.height,signal.mode.duration,signal.mode.scale,signal.mode.interlaced,flags,signal.rgb,signal.bits));
+ entry.sink->formatChanged(signal);return S_OK;
+ }catch(...){entry.sink->failure(L"BMD 制式回调异常");return E_FAIL;}
+ }
+ HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video,IDeckLinkAudioInputPacket* audio)override{
+ Entry entry(*this);if(!entry.sink)return S_OK;
+ try{
+ if(video){
+ Frame frame;const auto flags=video->GetFlags();frame.noInput=(flags&bmdFrameHasNoInputSource)!=0;
+ if(noInput_.exchange(frame.noInput?1:0)!=(frame.noInput?1:0))log::info("decklink-input",std::format("noInput={} frameFlags=0x{:X}",frame.noInput,flags));
+ if(frame.noInput){entry.sink->video(frame);return S_OK;}
+ const auto format=pixel(video->GetPixelFormat());
+ if(!format){entry.sink->failure(L"BMD 返回未支持的像素格式");return E_FAIL;}
+ frame.pixel=*format;frame.width=video->GetWidth();frame.height=video->GetHeight();frame.stride=video->GetRowBytes();frame.bottomUp=(flags&bmdFrameFlagFlipVertical)!=0;
+ void* data=nullptr;const HRESULT bytesHr=video->GetBytes(&data);
+ const HRESULT timeHr=video->GetStreamTime(&frame.pts100ns,&frame.duration100ns,10000000);
+ if(FAILED(bytesHr)||FAILED(timeHr)){checked(bytesHr,"VideoGetBytes");checked(timeHr,"VideoGetStreamTime");entry.sink->failure(L"BMD 无法读取有效画面或源时间戳");return E_FAIL;}
+ frame.data=static_cast<const uint8_t*>(data);frame.bytes=size_t(frame.stride)*frame.height;frame.color=entry.color;
+ using namespace pipeline;
+ frame.color.pixelFormat=frame.pixel==Pixel::V210?SourcePixelFormat::V210:frame.pixel==Pixel::Rgb10xLE?SourcePixelFormat::Rgb10xLE:frame.pixel==Pixel::Uyvy8?SourcePixelFormat::Uyvy:SourcePixelFormat::Bgra8;
+ frame.color.range=frame.pixel==Pixel::Bgra8?ColorRange::Full:ColorRange::Limited;
+ ComPtr<IDeckLinkVideoFrameMetadataExtensions> metadata;const HRESULT metaHr=video->QueryInterface(IID_PPV_ARGS(&metadata));
+ LONGLONG colorspace=0,eotf=0;HRESULT colorHr=E_NOINTERFACE,eotfHr=E_NOINTERFACE;
+ if(metadata){
+ colorHr=metadata->GetInt(bmdDeckLinkFrameMetadataColorspace,&colorspace);
+ if(SUCCEEDED(colorHr)){
+ if(colorspace==bmdColorspaceRec2020){frame.color.matrix=YuvMatrix::BT2020NCL;frame.color.primaries=ColorPrimaries::BT2020;}
+ else if(colorspace==bmdColorspaceRec709){frame.color.matrix=YuvMatrix::BT709;frame.color.primaries=ColorPrimaries::BT709;}
+ else if(colorspace==bmdColorspaceRec601){frame.color.matrix=YuvMatrix::BT601;frame.color.primaries=frame.height==576?ColorPrimaries::BT601_625:ColorPrimaries::BT601_525;}
+ else {entry.sink->failure(L"BMD 返回未知颜色空间");return E_FAIL;}
+ frame.color.matrixAssumed=frame.color.primariesAssumed=false;
+ }
+ if(flags&bmdFrameContainsHDRMetadata){
+ eotfHr=metadata->GetInt(bmdDeckLinkFrameMetadataHDRElectroOpticalTransferFunc,&eotf);
+ if(FAILED(eotfHr)||(eotf!=0&&eotf!=2&&eotf!=3)){checked(eotfHr,"GetHDRTransfer");entry.sink->failure(L"BMD HDR 帧的 EOTF 不受支持;仅接受 SDR、PQ 或 HLG,拒绝猜测颜色传递");return E_FAIL;}
+ frame.color.transfer=eotf==2?TransferFunction::PQ:eotf==3?TransferFunction::HLG:TransferFunction::BT709;
+ frame.color.transferAssumed=false;frame.color.preserveSdrCodeValues=!frame.color.isHdrPath();
+ auto light=[&](BMDDeckLinkFrameMetadataID id){double value=0;const HRESULT h=metadata->GetFloat(id,&value);return SUCCEEDED(h)&&std::isfinite(value)&&value>0&&value<=65535?float(value):0.f;};
+ frame.color.hdrMaxCllNits=light(bmdDeckLinkFrameMetadataHDRMaximumContentLightLevel);
+ frame.color.hdrMaxFallNits=light(bmdDeckLinkFrameMetadataHDRMaximumFrameAverageLightLevel);
+ frame.color.hdrMasteringPeakNits=light(bmdDeckLinkFrameMetadataHDRMaxDisplayMasteringLuminance);
+ }
+ }else if(flags&bmdFrameContainsHDRMetadata){entry.sink->failure(L"BMD 标记 HDR,但驱动未提供 HDR 元数据接口");return E_FAIL;}
+ if(!loggedMetadata_.exchange(true)){log::info("decklink-metadata",std::format("QueryInterfaceHr=0x{:08X} colorspaceHr=0x{:08X} colorspace=0x{:X} hdr={} eotfHr=0x{:08X} eotf={}",uint32_t(metaHr),uint32_t(colorHr),uint64_t(colorspace),(flags&bmdFrameContainsHDRMetadata)!=0,uint32_t(eotfHr),eotf));}
+ if(!loggedFrame_.exchange(true)){log::info("decklink-frame",std::format("flags=0x{:X} extent={}x{} rowBytes={} pixel=0x{:X} bytesHr=0x{:08X} timeHr=0x{:08X} pts={} duration={}",flags,frame.width,frame.height,frame.stride,unsigned(video->GetPixelFormat()),uint32_t(bytesHr),uint32_t(timeHr),frame.pts100ns,frame.duration100ns));}
+ entry.sink->video(frame);
+ }
+ if(audio){void* data=nullptr;BMDTimeValue pts=0;const auto bytesHr=audio->GetBytes(&data);const auto timeHr=audio->GetPacketTime(&pts,10000000);const auto samples=audio->GetSampleFrameCount();
+ if(SUCCEEDED(bytesHr)&&SUCCEEDED(timeHr)&&data&&samples>0)entry.sink->audio(data,size_t(samples)*4,pts); // negotiated 16-bit stereo
+ else{checked(bytesHr,"AudioGetBytes");checked(timeHr,"AudioGetPacketTime");}
+ }
+ return S_OK;
+ }catch(...){entry.sink->failure(L"BMD 帧回调异常");return E_FAIL;}
+ }
+};
+class ComDriver final:public Driver {
+ ComPtr<IDeckLink> device_;ComPtr<IDeckLinkInput> input_;ComPtr<Callback> callback_;
+ bool auto_=false,videoEnabled_=false,audioEnabled_=false;
+ void logStatus(){ComPtr<IDeckLinkStatus> status;if(FAILED(device_.As(&status)))return;
+ BOOL locked=FALSE;LONGLONG detected=0,flags=0,current=0;
+ const auto a=status->GetFlag(bmdDeckLinkStatusVideoInputSignalLocked,&locked),b=status->GetInt(bmdDeckLinkStatusDetectedVideoInputMode,&detected),c=status->GetInt(bmdDeckLinkStatusDetectedVideoInputFormatFlags,&flags),d=status->GetInt(bmdDeckLinkStatusCurrentVideoInputMode,&current);
+ log::info("decklink-status",std::format("lockHr=0x{:08X} locked={} detectedHr=0x{:08X} detected=0x{:08X} flagsHr=0x{:08X} detectedFlags=0x{:X} currentHr=0x{:08X} current=0x{:08X}",uint32_t(a),locked,uint32_t(b),uint32_t(detected),uint32_t(c),uint64_t(flags),uint32_t(d),uint32_t(current)));}
+public:
+ ~ComDriver(){stop();}
+ bool open(std::wstring_view path,DriverSink& sink,std::wstring& error)override{
+ stop();for(auto& row:enumerate())if(row.details.path==path){device_=row.device;input_=row.input;auto_=row.details.autoDetection;break;}
+ if(!input_){error=L"未找到该 BMD 原生设备,请安装 Desktop Video 驱动并刷新设备列表";return false;}
+ callback_.Attach(new Callback(sink));
+ if(!checked(input_->SetCallback(callback_.Get()),"SetCallback",&error)){stop();return false;}
+ logStatus();return true;
+ }
+ std::vector<Mode> modes()override{return input_?readModes(input_.Get()):std::vector<Mode>{};}
+ bool autoDetection()const override{return auto_;}
+ bool enable(const Mode& mode,Pixel p,bool automatic,bool audio,std::wstring& error)override{
+ if(!input_)return false;BOOL supported=FALSE;BMDDisplayMode actual=bmdModeUnknown;
+ const auto hr=input_->DoesSupportVideoMode(bmdVideoConnectionUnspecified,BMDDisplayMode(mode.id),sdkPixel(p),bmdNoVideoInputConversion,bmdSupportedVideoModeDefault,&actual,&supported);
+ checked(hr,"DoesSupportVideoMode",&error);
+ log::info("decklink-negotiate",std::format("mode=0x{:08X} actual=0x{:08X} pixel=0x{:08X} supported={} automatic={}",mode.id,unsigned(actual),unsigned(sdkPixel(p)),supported,automatic));
+ if(FAILED(hr)||!supported||uint32_t(actual)!=mode.id){if(error.empty())error=L"BMD 输入不支持所选制式/像素格式";return false;}
+ if(!checked(input_->EnableVideoInput(BMDDisplayMode(mode.id),sdkPixel(p),automatic?bmdVideoInputEnableFormatDetection:bmdVideoInputFlagDefault),"EnableVideoInput",&error))return false;
+ videoEnabled_=true;callback_->color(mode.color);
+ if(audio&&!audioEnabled_){if(!checked(input_->EnableAudioInput(bmdAudioSampleRate48kHz,bmdAudioSampleType16bitInteger,2),"EnableAudioInput",&error))return false;audioEnabled_=true;}
+ logStatus();return true;
+ }
+ bool start(std::wstring& error)override{return input_&&checked(input_->StartStreams(),"StartStreams",&error);}
+ bool pause(std::wstring& error)override{return input_&&checked(input_->PauseStreams(),"PauseStreams",&error);}
+ bool flush(std::wstring& error)override{return input_&&checked(input_->FlushStreams(),"FlushStreams",&error);}
+ void stop()noexcept override{
+ if(callback_)callback_->detach();
+ if(input_){checked(input_->StopStreams(),"StopStreams");checked(input_->SetCallback(nullptr),"DetachCallback");}
+ if(callback_)callback_->wait();
+ if(input_&&audioEnabled_)checked(input_->DisableAudioInput(),"DisableAudioInput");
+ if(input_&&videoEnabled_)checked(input_->DisableVideoInput(),"DisableVideoInput");
+ callback_.Reset();input_.Reset();device_.Reset();videoEnabled_=audioEnabled_=false;
+ }
+};
+}
+std::vector<Device> devices(){std::vector<Device> out;for(auto& row:enumerate())out.push_back(std::move(row.details));return out;}
+std::vector<Mode> modes(std::wstring_view path){for(auto& row:enumerate())if(row.details.path==path)return readModes(row.input.Get());return {};}
+std::unique_ptr<Driver> makeDriver(){return std::make_unique<ComDriver>();}
+}
+#else
+namespace veyra::source::decklink {
+std::vector<Device> devices(){return {};}
+std::vector<Mode> modes(std::wstring_view){return {};}
+std::unique_ptr<Driver> makeDriver(){return {};}
+}
+#endif
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index f6ede25e..45c30d53 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -112,6 +112,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/DeckLinkCapture.h"
#include "veyra/source/CaptureSignalProbe.h"
#include "veyra/source/ScreenCaptureSource.h"
@@ -1964,12 +1965,21 @@ void QmlPlayerBridge::copyDiagnostics() {
// --- capture dialog ----------------------------------------------------------
+static QString captureDeviceUiLabel(const source::CaptureDevice& device) {
+ return source::decklink::isPath(device.path)
+ ? uiText(device.name).replace(QStringLiteral("跟随驱动输入"), uiText(L"跟随驱动输入")) : utf8Of(device.name);
+}
QVariantList QmlPlayerBridge::captureDevices() const {
// The source's own enumeration (asynchronous, see refreshCaptureDevices). An
// empty list means the machine reports no capture devices.
QVariantList out;
- for (const auto& d : impl_->captureVideo)
- out << QVariantMap{{"id", utf8Of(d.path)}, {"label", utf8Of(d.name)}, {"embeddedAudio", d.hasEmbeddedAudio}};
+ for (const auto& d : impl_->captureVideo) {
+ const bool native=source::decklink::isPath(d.path);
+ const bool enabled=impl_->prefBool("blackmagicNativeCapture",false);
+ if(native&&!enabled)continue;
+ if(!native&&enabled&&source::isBlackmagicCaptureDevice(d.name,d.path))continue;
+ out << QVariantMap{{"id", utf8Of(d.path)}, {"label", captureDeviceUiLabel(d)}, {"embeddedAudio", d.hasEmbeddedAudio}};
+ }
return out;
}
QString QmlPlayerBridge::captureDeviceId() const { return utf8Of(impl_->captureDevice); }
@@ -1987,14 +1997,17 @@ void QmlPlayerBridge::setCaptureDeviceId(const QString& value) {
emit captureChanged();
}
QString QmlPlayerBridge::captureDeviceLabel() const {
- for (const auto& d : impl_->captureVideo) if (d.path == impl_->captureDevice) return utf8Of(d.name);
+ for (const auto& d : impl_->captureVideo) if (d.path == impl_->captureDevice) return captureDeviceUiLabel(d);
return impl_->captureDevice.empty() ? tr("未选择设备") : tr("设备未连接");
}
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},
+ for (const auto& f : impl_->captureFormatList) {
+ auto label=uiText(f.label);
+ if(source::decklink::isPath(impl_->captureDevice))label=label.replace(QStringLiteral("逐行"),tr("逐行")).replace(QStringLiteral("隔行"),tr("隔行"));
+ out << QVariantMap{{"id", utf8Of(f.key)}, {"label", label}, {"tier", f.tier},
{"costHint", source::captureFormatNeedsCostHint(static_cast<source::CaptureFormatTier>(f.tier))}, {"driverCurrent", f.driverCurrent}};
+ }
return out;
}
QString QmlPlayerBridge::captureFormatKey() const { return utf8Of(impl_->captureFormatKey); }
@@ -2069,7 +2082,7 @@ void QmlPlayerBridge::setCaptureBufferMode(int value) {
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);
+ for (const auto& d : impl_->captureVideo) if (d.path == impl_->captureDevice) return source::decklink::isPath(d.path)||source::isBlackmagicCaptureDevice(d.name, d.path);
return false;
}
bool QmlPlayerBridge::openCaptureDriverSettings(bool inputSelector) {
@@ -2145,15 +2158,23 @@ void QmlPlayerBridge::tickCapture() {
veyra::log::info("capture-ui", std::format("devices video={} audio={}", i.captureVideo.size(), i.captureAudio.size()));
// Restore the remembered device; otherwise the first one. Never guess audio.
std::wstring pick;
- for (const auto& d : i.captureVideo) if (d.path == i.capturePrefs.videoPath) pick = d.path;
- if (pick.empty() && !i.captureVideo.empty() && i.capturePrefs.videoPath.empty()) pick = i.captureVideo.front().path;
+ const auto choices=captureDevices();
+ auto allowed=[&](std::wstring_view path){for(const auto& value:choices)if(wideOf(value.toMap().value("id").toString())==path)return true;return false;};
+ if(allowed(i.capturePrefs.videoPath))pick=i.capturePrefs.videoPath;
+ // The two APIs are separate identities. Restore an explicitly used
+ // endpoint, or select a unique native endpoint; never map by ordinal.
+ const bool native=i.prefBool("blackmagicNativeCapture",false);
+ const auto remembered=wideOf(i.prefs.value(native?"blackmagicNativeLastDevice":"blackmagicDirectShowLastDevice").toString());
+ if(pick.empty()&&allowed(remembered))pick=remembered;
+ if(pick.empty()&&native){std::vector<std::wstring> candidates;for(const auto& d:i.captureVideo)if(source::decklink::isPath(d.path))candidates.push_back(d.path);if(candidates.size()==1)pick=candidates.front();}
+ if (pick.empty() && !choices.empty() && i.capturePrefs.videoPath.empty()&&!native) pick=wideOf(choices.front().toMap().value("id").toString());
i.captureStatus = i.captureVideo.empty() ? tr("未找到采集设备。连接后点击刷新。")
: pick.empty() ? tr("上次采集设备未连接。插回后刷新,或手动选择其他设备。") : QString();
if (!pick.empty()) {
i.captureDevice.clear();
setCaptureDeviceId(utf8Of(pick));
if (pick == i.capturePrefs.videoPath) restoreRememberedAudio();
- }
+ }else{setCaptureDeviceId({});if(native)i.captureStatus=tr("请选择 BMD 原生设备;若列表中没有,请安装 Desktop Video 驱动。多个设备不会自动猜选。");}
emit captureChanged();
return;
}
@@ -2171,6 +2192,7 @@ void QmlPlayerBridge::tickCapture() {
i.captureStatus = i.captureFormatList.empty() ? tr("未读到有效的 4K 以内采集格式,或设备正被其他应用占用。")
: i.captureFormatKey.empty() ? tr("上次格式已不可用,请重新选择格式。")
: q.kind == 3 ? tr("驱动设置已关闭。请核对所选格式与设备帧率,再连接。")
+ : source::decklink::isPath(i.captureDevice) ? tr("原生采集先确认有效信号;支持自动检测的卡建议选择自动。HDMI/SDI 跟随 Desktop Video Setup。")
: captureBlackmagicDevice() ? tr("请选择与输入信号一致的格式。驱动默认格式不代表检测到的信号。")
: tr("连接后使用当前增强设置。格式与音频变更需要重新连接。");
veyra::log::info("capture-ui", std::format("formats={} selected={}", i.captureFormatList.size(), !i.captureFormatKey.empty()));
@@ -2186,6 +2208,9 @@ bool QmlPlayerBridge::startCaptureSession() {
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);
+ if(source::decklink::isPath(i.captureDevice)!=i.prefBool("blackmagicNativeCapture",false)&&captureBlackmagicDevice()){
+ emit notice(tr("采集接口已切换,请刷新并重新选择设备和格式"),true);return false;
+ }
if (device < 0 || !format) { emit notice(tr("请先选择采集设备和格式"), true); return false; }
const int audio = i.captureAudioChoice;
const source::CaptureDevice* audioDevice = audio >= 0 && size_t(audio) < i.captureAudio.size() ? &i.captureAudio[size_t(audio)] : nullptr;
@@ -2201,6 +2226,7 @@ bool QmlPlayerBridge::startCaptureSession() {
i.captureFps > 0 ? i.captureFps : format->fps, true});
veyra::log::info("capture-ui", std::format("connect format={} audio={} color={} fps={}", QString::fromStdWString(format->label).toStdString(), audio, i.captureColor, i.captureFps));
i.prefs["captureDeviceName"] = utf8Of(i.captureVideo[size_t(device)].name);
+ if(captureBlackmagicDevice())i.prefs[source::decklink::isPath(i.captureDevice)?"blackmagicNativeLastDevice":"blackmagicDirectShowLastDevice"]=utf8Of(i.captureDevice);
rememberSource(QStringLiteral("capture"), utf8Of(i.captureVideo[size_t(device)].name));
i.prefs["captureFormatLabel"] = utf8Of(format->label);
i.savePrefs();
@@ -5070,6 +5096,10 @@ QRect QmlPlayerBridge::launchScreenAvailable() const {
}
bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {
+ if(key==QLatin1String("blackmagicNativeCapture")){
+ if(captureQueryBusy()){emit notice(tr("请等待采集设备查询完成后再切换接口"),true);return false;}
+ if(captureBlackmagicDevice())impl_->prefs[source::decklink::isPath(impl_->captureDevice)?"blackmagicNativeLastDevice":"blackmagicDirectShowLastDevice"]=utf8Of(impl_->captureDevice);
+ }
static const QHash<QString, std::pair<int, int>> ranges{
{"subtitleSize", {16, 56}}, {"subtitleFont", {0, 5}}, {"subtitleOutline", {0, 3}},
{"subtitleMargin", {0, 240}}, {"subtitleLines", {0, 8}},
@@ -5077,7 +5107,7 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {
{"listInspectorWidth", {376, 4000}}};
static const QStringList flags{"subtitleEnabled", "subtitleBackground", "subtitleFit",
"subtitleSecondLanguage", "audioForceStereo", "holdCompare",
- "magewellLowLatency", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement", "hdrFgCompatibility"};
+ "magewellLowLatency", "blackmagicNativeCapture", "cinePillHidden", "exportStopsPlayback", "obsGameCapture", "autoResume", "fullscreenMemoryProtection", "prewarmEnhancement", "hdrFgCompatibility"};
QVariant stored;
if (ranges.contains(key)) {
bool ok = false; const int n = value.toInt(&ok);
@@ -5174,6 +5204,7 @@ void QmlPlayerBridge::applyPreference(const QString& key) {
if (key == QLatin1String("audioDevice")) sink::setPreferredRenderEndpoint(impl_->prefString("audioDevice").toStdWString());
else if (key == QLatin1String("audioForceStereo")) sink::setForceStereoDownmix(impl_->prefBool("audioForceStereo", false));
else if (key == QLatin1String("magewellLowLatency")) source::magewell::setLowLatencyPreference(impl_->prefBool("magewellLowLatency", false));
+ else if (key == QLatin1String("blackmagicNativeCapture")) { if(impl_->captureListed)refreshCaptureDevices();emit captureChanged(); }
else if (key == QLatin1String("language")) {
const QString code = i18n::resolve(impl_->prefString("language"));
if (!i18n::apply(code)) emit notice(tr("这个语言的翻译没有找到,界面保持简体中文"), true);
diff --git a/tests/integration/DeckLinkGpuCases.h b/tests/integration/DeckLinkGpuCases.h
new file mode 100644
index 00000000..f476e282
--- /dev/null
+++ b/tests/integration/DeckLinkGpuCases.h
@@ -0,0 +1,63 @@
+#pragma once
+#include "CaptureFormatGpuCases.h"
+#include "veyra/pipeline/CaptureUploadFrame.h"
+#include <array>
+#include <cmath>
+
+// Independent double-precision color reference and test-only GPU readback.
+// 64-pixel v210 rows end inside a six-pixel group; padding must stay invisible.
+inline int decklinkGpuCases(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring){
+ using namespace veyra;using namespace pipeline;using namespace source;
+ int failures=0;
+ for(unsigned code:{6u,7u})for(bool full:{false,true})for(unsigned curve:{1u,4u,5u})for(bool upload:{false,true}){
+ constexpr unsigned w=64,h=32;const unsigned rowBytes=code==6?((w+5)/6)*16:w*4,stride=rowBytes+128;
+ std::vector<uint8_t> raw(size_t(stride)*h,0xab);std::vector<std::array<double,3>> expected(w*h);
+ ColorDescription color;color.pixelFormat=code==6?SourcePixelFormat::V210:SourcePixelFormat::Rgb10xLE;
+ color.range=full?ColorRange::Full:ColorRange::Limited;color.matrix=curve==1?YuvMatrix::BT709:YuvMatrix::BT2020NCL;
+ color.primaries=curve==1?ColorPrimaries::BT709:ColorPrimaries::BT2020;color.transfer=curve==1?TransferFunction::SRGB:curve==4?TransferFunction::PQ:TransferFunction::HLG;
+ auto component=[&](unsigned x,unsigned y,unsigned channel){
+ if(channel==0)return unsigned((full?0:64)+((x*11+y*17)%(full?1024:877)));
+ return unsigned(channel==1?384+(x/2%4)*64:416+(y%4)*48);
+ };
+ auto decode=[&](double v){
+ if(curve==1)return v<=.04045?v/12.92:std::pow((v+.055)/1.055,2.4);
+ if(curve==4){const auto p=std::pow(v,32.0/2523);return 10000*std::pow(std::max(p-3424.0/4096,0.0)/(2413.0/128-2392.0/128*p),16384.0/2610);}
+ return v<=.5?v*v/3:(std::exp((v-.55991073)/.17883277)+.28466892)/12;
+ };
+ for(unsigned y=0;y<h;++y){
+ auto* row=raw.data()+size_t(y)*stride;
+ if(code==6)for(unsigned x=0;x<w;x+=6){
+ unsigned yy[6],u[3],v[3];for(unsigned i=0;i<6;++i)yy[i]=component(x+i,y,0);
+ for(unsigned i=0;i<3;++i){u[i]=component(x+2*i,y,1);v[i]=component(x+2*i,y,2);}
+ const uint32_t words[]={u[0]|yy[0]<<10|v[0]<<20,yy[1]|u[1]<<10|yy[2]<<20,v[1]|yy[3]<<10|u[2]<<20,yy[4]|v[2]<<10|yy[5]<<20};
+ memcpy(row+(x/6)*16,words,16);
+ }else for(unsigned x=0;x<w;++x){
+ const uint32_t r=component(x,y,0),g=component((x+19)%w,y,0),b=component((x+37)%w,y,0);
+ const uint32_t word=r<<22|g<<12|b<<2|3u;memcpy(row+x*4,&word,4); // X bits deliberately nonzero
+ }
+ for(unsigned x=0;x<w;++x){
+ std::array<double,3> c;
+ if(code==6){const double yy=(double(component(x,y,0))-(full?0:64))/(full?1023:876),u=(double(component(x,y,1))-512)/(full?1023:896),v=(double(component(x,y,2))-512)/(full?1023:896);
+ c=curve==1?std::array{yy+1.5748*v,yy-.187324*u-.468124*v,yy+1.8556*u}:std::array{yy+1.4746*v,yy-.164553*u-.571353*v,yy+1.8814*u};
+ }else{for(unsigned i=0;i<3;++i)c[i]=(double(component((x+(i==1?19:i==2?37:0))%w,y,0))-(full?0:64))/(full?1023:876);}
+ for(auto& v:c)v=decode(std::clamp(v,0.0,1.0));
+ if(curve==5){const auto light=.2627*c[0]+.6780*c[1]+.0593*c[2];for(auto& v:c)v*=1000*std::pow(light,.2);}
+ if(curve!=1){const auto old=c;c={1.660491*old[0]-.587641*old[1]-.072850*old[2],-.124550*old[0]+1.132900*old[1]-.008349*old[2],-.018151*old[0]-.100579*old[1]+1.118730*old[2]};for(auto& v:c)v/=80;}
+ expected[y*w+x]=c;
+ }
+ }
+ CaptureMediaLayout layout;layout.width=w;layout.height=h;layout.stride=stride;layout.rowBytes=rowBytes;layout.sampleBytes=raw.size();layout.format=AV_PIX_FMT_BGRA;layout.packing=code==6?CapturePacking::V210:CapturePacking::Rgb10xLE;layout.color=color;
+ AVFrame* frame=upload?allocCaptureUploadFrame(ctx.device(),AV_PIX_FMT_BGRA,w,h,true):av_frame_alloc();
+ bool ok=frame!=nullptr;if(ok&&!upload){frame->width=w;frame->height=h;frame->format=AV_PIX_FMT_BGRA;ok=av_frame_get_buffer(frame,256)>=0;}
+ if(ok){selectCaptureUploadTarget(*frame);ok=copyCaptureSample(layout,raw.data(),raw.size(),*frame);if(code==6)sampleCaptureV210Proxy(*frame,raw.data(),stride,false);else sampleCaptureUploadProxy(*frame,raw.data(),stride,false);}
+ EnhanceGraph graph(ctx,ring);EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=w;gd.sourceHeight=gd.workHeight=h;gd.enableNr=gd.enableFg=gd.enableSr=false;gd.noFeatures=true;gd.packedInput=code;gd.captureBitDepth=10;gd.hdrInput=curve!=1;gd.hdrOutput=curve!=1;
+ EnhanceGraph::FrameOutputs out;std::vector<float> actual;
+ ok=ok&&graph.initialize(gd)&&graph.createViews()&&graph.process(frame,0,true,out,1,&color)&&captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),actual);
+ double maxError=0;if(ok)for(unsigned i=0;i<w*h;++i)for(unsigned c=0;c<3;++c){const double error=std::abs(actual[i*4+c]-expected[i][c])/std::max(1.0,std::abs(expected[i][c]));if(!std::isfinite(error))ok=false;maxError=std::max(maxError,error);}
+ ok=ok&&maxError<.004;
+ if(upload)ok=ok&&captureUploadFrame(frame)&&captureUploadFrame(frame)->direct&&captureUploadFrame(frame)->proxyValid;
+ std::cout<<"DECKLINK_GPU packing="<<code<<" full="<<full<<" transfer="<<curve<<" upload="<<upload<<" normalizedError="<<maxError<<" pass="<<ok<<std::endl;
+ if(!ok)++failures;out={};ring.drainQueue();graph.shutdown();av_frame_free(&frame);
+ }
+ return failures;
+}
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
index a3715d13..264f40fe 100644
--- a/tests/integration/HdrColorTests.cpp
+++ b/tests/integration/HdrColorTests.cpp
@@ -8,6 +8,7 @@
#include "veyra/source/MediaFileSource.h"
#include "veyra/RuntimePaths.h"
#include "CaptureFormatGpuCases.h"
+#include "DeckLinkGpuCases.h"
#include "SdrColorGpuCases.h"
#include "HdrNativeRoundTripCases.h"
#include "HdrToneMapGpuCases.h"
@@ -22,7 +23,7 @@ int wmain(int argc,wchar_t** argv){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;
if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 2;
- int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring)+hdrRoundTrip::run(ctx,ring)+hdrToneTests::run(ctx,ring)+screenScRgbCases(ctx,ring);
+ int failures=captureGpuCases(ctx,ring)+decklinkGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring)+hdrRoundTrip::run(ctx,ring)+hdrToneTests::run(ctx,ring)+screenScRgbCases(ctx,ring);
if(argc>1){
std::vector<uint8_t> software;const float expectedPeak=argc>2?float(_wtof(argv[2])):0;
for(bool hardware:{false,true}){
diff --git a/tests/unit/DeckLinkCaptureTests.cpp b/tests/unit/DeckLinkCaptureTests.cpp
new file mode 100644
index 00000000..8f85cce5
--- /dev/null
+++ b/tests/unit/DeckLinkCaptureTests.cpp
@@ -0,0 +1,101 @@
+#include "veyra/source/DeckLinkCapture.h"
+#include <windows.h>
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <thread>
+#include <vector>
+using namespace veyra::source::decklink;
+using namespace veyra::pipeline;
+namespace {
+Mode makeMode(uint32_t id=1,unsigned width=1920){
+ Mode m;m.id=id;m.width=width;m.height=1080;m.duration=1001;m.scale=60000;m.name=L"fixture";
+ m.color.range=ColorRange::Limited;m.color.matrix=YuvMatrix::BT709;m.color.primaries=ColorPrimaries::BT709;m.color.transfer=TransferFunction::BT709;m.color.preserveSdrCodeValues=true;return m;
+}
+struct FakeDriver:Driver {
+ DriverSink* sink=nullptr;Mode mode=makeMode();Pixel pixel=Pixel::V210;
+ bool automatic=true,noSignal=false,occupied=false,rejectTen=false,failFlush=false,failStart=false,sendRgbChange=false,detectDuringEnable=false;
+ unsigned enabled=0,started=0,paused=0,flushed=0,stopped=0;
+ std::vector<uint8_t> pixels;
+ std::thread::id owner=std::this_thread::get_id();bool allControlsOnOwner=true;
+ void control(){allControlsOnOwner&=std::this_thread::get_id()==owner;}
+ bool open(std::wstring_view,DriverSink& target,std::wstring& error)override{control();sink=&target;if(occupied){error=L"busy";return false;}return true;}
+ std::vector<Mode> modes()override{return {makeMode(),makeMode(2,1280)};}
+ bool autoDetection()const override{return automatic;}
+ bool enable(const Mode& m,Pixel p,bool,bool,std::wstring& error)override{control();++enabled;if(rejectTen&&(p==Pixel::V210||p==Pixel::Rgb10xLE)){error=L"unsupported";return false;}mode=m;pixel=p;
+ if(detectDuringEnable&&enabled==1){std::thread callback([&]{sink->formatChanged({makeMode(2,1280),true,10});});callback.join();}
+ return true;}
+ Frame frame(){
+ Frame f;f.width=mode.width;f.height=mode.height;f.stride=unsigned(rowBytes(pixel,mode.width))+128;f.pixel=pixel;
+ pixels.resize(size_t(f.stride)*f.height,0);f.data=pixels.data();f.bytes=pixels.size();f.pts100ns=123456789;f.duration100ns=166833;f.noInput=noSignal;
+ f.color=mode.color;f.color.pixelFormat=pixel==Pixel::V210?SourcePixelFormat::V210:pixel==Pixel::Rgb10xLE?SourcePixelFormat::Rgb10xLE:SourcePixelFormat::Uyvy;return f;
+ }
+ bool start(std::wstring& error)override{
+ control();++started;if(failStart){error=L"start failed";return false;}
+ // A real driver callback thread: synchronous join intentionally makes
+ // any callback re-entry into owner control observable, without sleeps.
+ std::thread callback([&]{if(sendRgbChange&&started==1)sink->formatChanged({makeMode(2,1280),true,10});else if(!noSignal)sink->video(frame());else{Frame f;f.noInput=true;sink->video(f);}});callback.join();return true;
+ }
+ bool pause(std::wstring&)override{control();++paused;return true;}
+ bool flush(std::wstring& error)override{control();++flushed;if(failFlush){error=L"flush failed";return false;}return true;}
+ void stop()noexcept override{control();++stopped;sink=nullptr;}
+};
+}
+int main(){
+ int failures=0;auto check=[&](bool value,const char* name){printf("%s %s\n",value?"PASS":"FAIL",name);if(!value)++failures;};
+ auto fixture=[](){auto driver=std::make_unique<FakeDriver>();auto* raw=driver.get();return std::pair{std::move(driver),raw};};
+ constexpr auto path=L"decklink-native:p:0000000000000123:0";
+ {
+ auto [driver,fake]=fixture();Capture capture(std::move(driver));unsigned video=0,audio=0;
+ check(capture.configure(path,L"decklink:auto",true,50),"valid signal probes without retaining a frame");
+ check(capture.contract().data==nullptr&&capture.contract().stride==unsigned(rowBytes(Pixel::V210,1920))+128,"probe preserves real stride, releases SDK pixels");
+ check(capture.start([&](const Frame& f){++video;check(f.pts100ns==123456789&&f.duration100ns==166833,"SDK timestamps preserved including fractional rate");},[&](const void*,size_t,int64_t){++audio;}),"deferred start publishes into consumer");
+ check(video==1,"valid black pixels are delivered (not classified as missing signal)");
+ fake->sink->formatChanged({makeMode(),false,10});check(!capture.needsReopen(),"duplicate detection after start does not reconnect forever");
+ uint8_t pcm[4]{};fake->sink->audio(pcm,sizeof(pcm),123456789);check(audio==1,"audio begins only after consumer start");
+ Frame invalid;invalid.noInput=true;fake->sink->video(invalid);fake->sink->video(fake->frame());fake->sink->audio(pcm,sizeof(pcm),0);
+ check(capture.needsReopen()&&video==1&&audio==1&&!capture.error().empty(),"no-input flag gates stale video/audio and requests recovery");
+ capture.stop();check(fake->sink==nullptr&&fake->allControlsOnOwner,"stop detaches sink, all controls stay off callback thread");
+ }
+ {
+ auto [driver,fake]=fixture();fake->sendRgbChange=true;Capture capture(std::move(driver));
+ check(capture.configure(path,L"decklink:auto",false,100)&&capture.mode().id==2&&capture.contract().pixel==Pixel::Rgb10xLE,"automatic RGB mode change reconfigures mode and ten-bit packing");
+ check(fake->enabled==2&&fake->paused>=2&&fake->flushed==2&&fake->allControlsOnOwner,"owner Pause/Enable/Flush/Start, bounded renegotiation");
+ unsigned frames=0;capture.start([&](const Frame&){++frames;});auto changed=fake->frame();changed.color.transfer=TransferFunction::PQ;changed.color.primaries=ColorPrimaries::BT2020;fake->sink->video(changed);
+ check(capture.needsReopen()&&frames==1,"same-size SDR to HDR change requires new graph contract");
+ }
+ {
+ auto [driver,fake]=fixture();fake->detectDuringEnable=true;Capture capture(std::move(driver));
+ check(capture.configure(path,L"decklink:auto",false,100)&&capture.mode().id==2&&capture.contract().pixel==Pixel::Rgb10xLE&&fake->allControlsOnOwner,
+ "detection during EnableVideoInput is retained before StartStreams");
+ }
+ {
+ auto [driver,fake]=fixture();fake->noSignal=true;Capture capture(std::move(driver));const auto before=std::chrono::steady_clock::now();
+ check(!capture.configure(path,L"decklink:auto",false,30)&&!capture.error().empty()&&std::chrono::steady_clock::now()-before<std::chrono::seconds(1),"no-signal timeout is bounded and descriptive");
+ check(fake->sink==nullptr,"timeout stops and releases callback before return");
+ }
+ {
+ auto [driver,fake]=fixture();fake->automatic=false;Capture capture(std::move(driver));
+ check(!capture.configure(path,L"decklink:auto",false,30),"old card without automatic detection rejects auto explicitly");
+ check(capture.configure(path,modeKey(2),false,30)&&capture.mode().id==2,"manual exact mode remains available on old card");
+ check(!capture.configure(path,modeKey(999),false,30),"removed saved mode never falls back to ordinal");
+ }
+ for(unsigned scenario=0;scenario<3;++scenario){
+ auto [driver,fake]=fixture();fake->occupied=scenario==0;fake->failFlush=scenario==1;fake->failStart=scenario==2;Capture capture(std::move(driver));
+ check(!capture.configure(path,L"decklink:auto",false,30)&&!capture.error().empty()&&fake->sink==nullptr,"driver busy/start/flush failure closes resources");
+ }
+ {
+ auto [driver,fake]=fixture();fake->rejectTen=true;Capture capture(std::move(driver));
+ check(capture.configure(path,L"decklink:auto",false,30)&&capture.contract().pixel==Pixel::Uyvy8,"8-bit-only SDR card has explicit fallback");
+ unsigned frames=0;capture.start([&](const Frame&){++frames;});auto bad=fake->frame();bad.color.transfer=TransferFunction::PQ;fake->sink->video(bad);
+ check(capture.needsReopen()&&frames==1,"eight-bit output cannot silently carry HDR");
+ }
+ {
+ auto [driver,fake]=fixture();Capture capture(std::move(driver));capture.configure(path,L"decklink:auto",false,30);capture.start([](const Frame&){});
+ auto bad=fake->frame();bad.stride=1;fake->sink->video(bad);check(capture.needsReopen(),"invalid driver stride rejected before any ingest copy");
+ }
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);const auto actual=devices();printf("INFO installed native devices=%zu (not hardware acceptance)\n",actual.size());
+ {Capture missing;check(!missing.configure(L"decklink-native:missing-test-device",L"decklink:auto",false,30)&&!missing.error().empty(),"missing native driver/device fails explicitly without capture or null dereference");}
+ CoUninitialize();
+ return failures?1:0;
+}