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++

Integrate native NVIDIA VFG 2X–8X across preview, export and saved chains

Veyra Goal Agent0d891731ba65
diff --git a/AGENTS.md b/AGENTS.md
index 418ad16b..9406baa8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-03 VFG 接入授权**:用户“接入看看,8x也支持上”“所有档位都加上”。在当前 E 盘隔离工作树的 `codex/vfg-integration-20261003`,以 `1802f43565e07f3c3040d3fe745ca2e939aab00f` 为基线,按 `docs/VFG_INTEGRATION_EXECUTION_2026-10-03.md` 接入 NVIDIA VFG、全部 2X–8X 与 Low/Medium/High。必要的 native backend、D3D12/CUDA bridge、共享 graph/pools/leases、settings/preset/session/worker、preview/export、QML/bridge、shader/CMake 与针对性验收获本轮授权,覆盖对应历史冻结;不扩改无关链路,不派子 Agent,不 merge/push/Release。存档 `checkpoint/pre-vfg-integration-20261003` 与 `E:/项目/Veyra/archives/vfg-integration-20261003-start/source-before.bundle`;原五项修复、main、桌面、用户配置与已有候选保持。新 SDK/运行库/模型仍在 E 盘独立 deps,不进源码 Git;默认 Medium,高倍率实验标识、实测与未验边界如实报告。测试≤300s、构建≤900s。
+
> **2026-10-03 当前真人现场修复与升级授权**:用户明确要求 Xbox 无声/断开修复、lmxxf AMD RX 9000 NR 接入、导出码率回跳/设置无效修复、RTSS 兼容背景透明修复、取消 NVIDIA App 插件检测;先存档、写方案、创建分支再动手。仅在 `E:/项目/Veyra/worktrees/field-upgrade-20261003` / `codex/field-upgrade-20261003`(main `66cd3e5`)按 `docs/FIELD_UPGRADE_PLAN_2026-10-03.md` 实施。这五项必要 backend/NR/graph/source/QML/bridge/CMake/定向验收接点获本轮授权,覆盖对应历史冻结;无关链路不扩改。开工存档及标签见方案;旧桌面 guard/baseline、main、其他工作区、用户设置和已发布包保持。所有产物在 E 盘,不派子 Agent,不 merge/push/Release/删除旧 UI。单测试≤300秒、单构建≤900秒;现有运行库身份、patched FFmpeg 与源码/模型隔离不变,AMD/Xbox 实机未验如实记录。
> **2026-10-02 导出优化目标授权(用户:“开启目标模式搞定他”)**:按 `docs/EXPORT_PAGE_OPTIMIZATION_PLAN_2026-10-02.md` 在 `E:/项目/Veyra/worktrees/export-page-20261002` / `codex/export-page-20261002` 实现导出页布局、可编辑顺序队列、MKV/多音轨/内嵌字幕、取消重试及完成提示音,并做真实验收。本条仅解除该方案列出的导出后端、QML/bridge、必要 CMake 与定向测试接点的历史冻结;其他链路不改。每轮先执行本分支 `python -B scripts/acceptance/export-page-control.py`,不可变基线在 `E:/项目/Veyra/archives/export-page-20261002-start/scope-baseline.json`,不得修改旧桌面 guard/baseline。Claude 的其他工作区、主分支、已有候选与用户配置保持原样;专用 E 盘构建/测试/TEMP,不派子 Agent,不 commit/tag/merge/push/Release。单测试≤300秒,构建≤900秒;已有 runtime/patched FFmpeg 身份和源码隔离约束保持。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f5fe4e96..1756892a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -361,6 +361,7 @@ add_library(veyra_pipeline STATIC
src/pipeline/ColorDetailPass.cpp
src/pipeline/NrInstance.cpp
src/pipeline/LmxxfNrBackend.cpp
+ src/pipeline/VfgBackend.cpp
)
veyra_apply_warnings(veyra_pipeline)
# FFmpeg/NVOF headers are third-party: /WX stays off for this target.
@@ -370,6 +371,11 @@ target_compile_definitions(veyra_pipeline PUBLIC
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX
VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
target_include_directories(veyra_pipeline PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
+set(VEYRA_CUDA_DRIVER_INCLUDE_DIR "" CACHE PATH "External CUDA driver headers for native VFG (never vendored)")
+if(EXISTS "${VEYRA_CUDA_DRIVER_INCLUDE_DIR}/cuda.h")
+ target_include_directories(veyra_pipeline PRIVATE "${VEYRA_CUDA_DRIVER_INCLUDE_DIR}")
+ target_compile_definitions(veyra_pipeline PRIVATE VEYRA_HAVE_CUDA_DRIVER_HEADERS=1)
+endif()
target_link_libraries(veyra_pipeline PUBLIC veyra_base veyra_gfx d3d12 dxgi dxguid d3dcompiler)
add_library(veyra_lmxxf_fake_runtime SHARED tests/unit/LmxxfNrFakeRuntime.cpp)
target_compile_features(veyra_lmxxf_fake_runtime PRIVATE cxx_std_20)
@@ -391,6 +397,9 @@ target_compile_definitions(veyra_pipeline_tests PRIVATE
UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
target_include_directories(veyra_pipeline_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(veyra_pipeline_tests PRIVATE veyra_pipeline)
+add_executable(veyra_vfg_gpu_tests tests/integration/VfgGpuTests.cpp)
+target_compile_features(veyra_vfg_gpu_tests PRIVATE cxx_std_20)
+target_link_libraries(veyra_vfg_gpu_tests PRIVATE veyra_pipeline)
add_executable(veyra_scene_tests
tests/unit/SceneCadenceTests.cpp
@@ -1020,10 +1029,20 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_options(veyra_engine PRIVATE /utf-8)
target_compile_definitions(veyra_engine PUBLIC VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}" VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")
target_link_libraries(veyra_engine PUBLIC veyra_pipeline veyra_sources veyra_sinks veyra_ngx veyra_nvof)
+ add_executable(veyra_vfg_export_probe tests/integration/VfgExportProbe.cpp)
+ target_compile_features(veyra_vfg_export_probe PRIVATE cxx_std_20)
+ target_compile_options(veyra_vfg_export_probe PRIVATE /utf-8)
+ target_link_libraries(veyra_vfg_export_probe PRIVATE veyra_engine)
add_executable(veyra_preset_library_tests tests/unit/PresetLibraryTests.cpp src/engine/PresetLibrary.cpp src/engine/EffectChain.cpp)
target_compile_features(veyra_preset_library_tests PRIVATE cxx_std_20)
target_include_directories(veyra_preset_library_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(veyra_preset_library_tests PRIVATE veyra_base)
+ add_executable(veyra_vfg_settings_tests tests/unit/VfgSettingsTests.cpp src/engine/PresetLibrary.cpp src/engine/PresetStore.cpp src/engine/EffectChain.cpp)
+ target_compile_features(veyra_vfg_settings_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_vfg_settings_tests PRIVATE /utf-8)
+ target_compile_definitions(veyra_vfg_settings_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_vfg_settings_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ target_link_libraries(veyra_vfg_settings_tests PRIVATE veyra_base)
add_executable(veyra_effect_chain_tests tests/unit/EffectChainTests.cpp src/engine/EffectChain.cpp)
target_compile_features(veyra_effect_chain_tests PRIVATE cxx_std_20)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 0d9143d4..14a9742c 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -2,6 +2,42 @@
NVIDIA SDKs and runtimes are excluded from source control. The publisher-authorized experimental Release package contains only selected runtime DLLs and applicable notices, as documented in `docs/RUNTIME_COMPONENTS_0.0.2.md`. This is not vendor endorsement or a general redistribution grant. ReShade/RenoDX add-ons are not loaded or distributed by the product.
+## NVIDIA Video Frame Generation (local integration, 2026-10-03)
+
+`src/pipeline/VfgBackend.cpp` and `include/veyra/pipeline/VfgBackend.h` implement
+the public native Video Effects SDK 1.3.0 and NvCVImage C APIs. Effect setup,
+`VideoFrameGeneration` selectors, multiplier/frame-index sequencing and quality
+modes were cross-checked against [NVIDIA-Maxine/VFX-SDK-Samples](https://github.com/NVIDIA-Maxine/VFX-SDK-Samples/tree/52011f89c1741d06b40ea312af1f20be8be9ec62),
+fixed commit `52011f89c1741d06b40ea312af1f20be8be9ec62`,
+`apps/VideoFrameGenerationEffectApp/VideoFrameGenerationEffectApp.cpp` and its README (MIT,
+Copyright NVIDIA Corporation). The sample remains in external dependencies;
+its CLI, OpenCV/CPU image transfer and implementation are not vendored.
+Veyra adds its own D3D12/CUDA external-buffer/fence bridge, opaque descriptors
+allocated by NvCVImage, exact adapter-LUID selection, asynchronous native calls,
+bounded output leases, shared preview/export integration, reset and diagnostics.
+The public NvCVImage documentation is authoritative for void destruction and
+borrowed pixel ownership; no proprietary SDK struct or header is copied into Git.
+
+The local runtime is the unmodified official `nvidia-vfx` 0.2.0.0 Windows wheel,
+`nvidia_vfx-0.2.0.0-cp311-cp311-win_amd64.whl`, 435809365 bytes, SHA-256
+`5aaf6a42bc6b6dbbf52fcb714194c994a6893cbbf7ada38bc2165a1f83e4a6fc`.
+Only the fourteen native VFG dependencies are used; Python and its extension
+are not a product dependency. This proprietary runtime is **not MIT**.
+The local candidate carries its NVIDIA software/AI/model terms and third-party
+notices with a separate `vfg-runtime-manifest.json`; public redistribution has
+not been authorized or established by this integration. CUDA driver headers
+are an external build dependency only; the system `nvcuda.dll` is never bundled.
+DLLs remain unmodified, separately identified and outside source control;
+manifest identity does not lock user replacements. Hardware/format support and
+initialization failures are reported by the native backend.
+
+Shared graph/pool, presenter, worker, settings/preset/session and QML modifications
+are Veyra code. The SDK provides frame inference; the local RTX 5070 tests do
+not establish RTX 40 hardware results, physical display latency, universal HDR
+color accuracy or official NVIDIA certification. Provenance and measurements:
+`docs/VFG_RESEARCH_AND_INTEGRATION_PLAN_2026-10-03.md` and
+`docs/VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md`.
+
## AVerMedia capture HDR-to-SDR control
The AVerMedia hardware HDR-to-SDR property request in
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 7456c14f..fc60ff1a 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -1,5 +1,14 @@
# 当前项目状态 / Current Status
+## 2026-10-03 VFG 全档位:独立本地接入
+
+`codex/vfg-integration-20261003` 已接原生 NVIDIA VFG 2X–8X、Low/Medium/High,
+共享图、实际预览/NVENC导出、列表/节点、预设/会话和worker冻结均接入。720p/4K
+8/10-bit全部21组合、21种真实导出、2K30AVI+最高SR4K+原生NR+VFG8、24/60fps、
+取消/缺失SDK、GUI热切换/重启和旧格式回归通过;缺失组件UI仍显示8X的错误已修复。
+RTX5070/616.56短测,不代表40系/616.92/HDR色度/物理显示/长稳通过。高档8X实时会降档。
+最终本地包在制作和验证中,公开2.0.2保持原状;详情 `VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md`。
+
## 2026-10-03 五项问题修复:独立本地候选
分支 codex/field-upgrade-20261003,已先存档写方案。修复 Xbox 音频输出线程未
diff --git a/docs/VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md b/docs/VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md
new file mode 100644
index 00000000..7ec7a4b6
--- /dev/null
+++ b/docs/VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md
@@ -0,0 +1,84 @@
+# VFG 全档位接入验收(2026-10-03,本地候选)
+
+## 已实现与实际验证
+
+`codex/vfg-integration-20261003` 接入 NVIDIA Video Effects SDK 1.3.0 原生 VFG,
+包含 2X/3X/4X/5X/6X/7X/8X、Low/Medium/High(默认 Medium)。列表与节点模式、
+预设、重启会话、实际预览和进程隔离的视频导出全部接入。VFG 不借用 DLSS 生成结果。
+保留此前五项现场修复和 AMD NR 0.39 资源;这些功能的实机边界仍见原验收报告。
+
+产品代码使用 C++ 原生 API、D3D12/CUDA shared buffer/fence;NVENC 接收 GPU texture,
+没有新增生产路径像素回读、逐 pass CPU fence wait、Python/Streamline/ReShade 依赖。
+FrameBatch=8,生成池14,输出池16,present/encoder 描述符按池尺寸推导;
+DLSS 兼容原十张全尺寸纹理仍保留。FG 位于增强之后、OSD/字幕之前,源 PTS/epoch
+和租约保持真实;每个子帧独立保存,不把最后一张输出重复七次。
+
+本机:Windows x64 / RTX 5070 / 驱动 **616.56**,不是反馈者的 616.92。
+所有证据在 `E:/项目/Veyra/logs/vfg-integration-20261003`;媒体/画像/会话在同任务 tests。
+
+| 检查 | 结果与证据 |
+| --- | --- |
+| 最终产品编译 | `build-product-v4.log`,MSVC/Ninja 51 步 exit0,含 QML、engine、native/导出探针和回归 |
+| 原生 720p | `native-720-v2.log/json`,463 checks/0 failures,RGBA8、RGB10A2 各21种组合 |
+| 原生 4K | `native-4k-v1.log/json`,463 checks/0 failures,同样全部倍率/质量;D3D12 debug errors=0 |
+| 真输出与切镜 | 8X 每组七张不同哈希,移动图块中间位置有序;manual cut 与当前输入 byte error=0;无效 slot/9X 拒绝 |
+| 设置与旧格式 | `unit-v4/summary.json`,VFG 331 checks、旧 PresetLibrary/RepairPreset/RepairContract/EffectChain、Qt Quick 39 项均 exit0 |
+| 21 种真实导出 | `export-all-v2/summary.json`,720p30、2..8 × 三质量,NVENC HEVC;每8张源帧输出16..64,60..240 fps,视频时长/音轨保持 |
+| 2K AVI + NR + 4K SR + 8X | `combinations-v4/2k30-avi-nr-highest-sr4k-vfg8.log`,2560×1440/30fps AVI,最高 SR 档、原生3840×2160 NR、4K VFG Medium8,24源 + 161生成 + 7尾 hold = 192输出,3840×2160/240fps/0.8s |
+| 24/60fps、取消与失败 | `combinations-v4/summary.json`,24→192fps、60→480fps;取消不提升最终文件;缺失 SDK 导出明确失败,未冒充成功 |
+| 实际 GUI | `ui-v4/summary.json`,全部倍率热切换、8X 三质量、暂停/seek/resize/resume、节点/列表独立质量、两预设保存与重启通过 |
+| worker 冻结 | 同 GUI 测试:启动8X Medium后父进程改2X Low,worker仍输出64帧/240fps;不读运行中的新设置 |
+| 缺失运行库预览 | `ui-v4/missing.log`,fgActive=false、fgEnabled=false、multiplier=1,9.1667s进度继续,警告明确点名 VFG |
+
+21种导出的首尾填充是现有 CFR 策略:N张源、(N−1)(M−1)张生成、M−1张尾 hold。
+日志分别计数;尾 hold 不计作算法生成帧。输出倍率不等于每张视频图像都应互不相同。
+
+## 性能与使用边界
+
+原生测试的 `groupWallMs` 包含 CPU 提交、GPU copy、最终诊断同步/读回准备,
+不能称纯模型时间或屏幕延迟。720p Medium8 约22.0–23.3ms/组,High8约105.8–107.2ms;
+4K Medium8约37.0–38.5ms,High8约123.8–131.0ms。测试是合成移动图块短测。
+
+真实 GUI 的短窗口提交读数(ui-v4):2/3/4X Medium=60/90/120次每秒;
+8X Low约241、Medium约118、High约60且明确显示“调度降档”。窗口短读数有抖动,
+不是物理屏幕 FPS、稳定性能保证或端到端延迟。高档8X离线可完整生成;实时播放仍执行
+现有一倍速音频/PTS预算,允许跳过预览增强机会或降低生成工作,日志不会掩盖。
+
+Windows 官方硬件范围为 Ada/Blackwell(RTX40/50);本轮只验证5070。6X–8X 明示实验。
+3X/5X/7X 来自公共倍率 API,实际逐项验证过,不称官方游戏生产档。
+RGBA8/RGB10A2 bridge 支持不等于 HDR 色度专项验收;scRGB half-float 不在 VFG
+原生编码范围,初始化拒绝时预览关闭该效果并提示。影片画质 AB、RTX40、616.92、
+采集卡/主机 VFG、长稳、VRR/物理显示节奏与屏幕/手柄端到端延迟均未实测。
+
+## 保存、回退与对抗自查
+
+稳定 backend ID4、独立 vfgQuality 0..2;旧 ID/默认和后端倍率上限保留。PresetStore28、
+PresetLibrary7、ChainSession5、worker ABI8,旧数据默认 Medium;新 library/session
+采用 `.vfg` 旁文件,旧数据保留。只应用颜色的预设不覆盖补帧质量。任务冻结包括 VFG 质量。
+
+缺失 SDK 曾暴露实际 bug:engine multiplier 已降到1,UI仍enabled/8X。`ui-missing-diagnostic`
+记录 active=false/enabled=true/position=9.2;已发布拒绝 revision,并在 facade 按最新请求
+同步后端/倍率/质量,旧 rejection 不覆盖更晚选择;ui-v4 验证 UI 与 engine 一致。
+VFG 不使用外部 motion,即使从显式 OpticalFlow 的 DLSS 预设切换也不额外启动无用光流;
+NR/SR 的外部 guidance 仍保留。不可访问 runtime 路径以 error_code 判断,组件页不会抛 filesystem 异常。
+
+自查覆盖:最高 subframe/pool/SRV offset、GPU handoff/故障后 signal、借用 CUDA memory
+所有权、销毁顺序、非重复输出、PTS/尾 hold、旧 schema、较新 UI 请求与失败回退。
+这是本 Agent 自查与真实自动测试,不宣称独立 Reviewer 或未发生的硬件验收。
+
+早期失败保留:native-v1 的 void ABI/packed enum、product-v1 的 private 测试 API、
+unit-v1 的缺失 argv、unit-v2 的旧非法枚举值、export-v1 的过严微秒 fps断言和错误日志路径。
+GUI ui-v1 与 Qt Quick 并行时出现暂停;GPU正常排空,无卡死证据。焦点/按键干扰是推断,
+串行 ui-v2/v4 正常。不能把上述首次失败记录当最终通过。
+
+## 来源与本地交付状态
+
+NVIDIA 官方 wheel0.2.0.0/SDK1.3.0,435809365 bytes,SHA256
+`5aaf6a42bc6b6dbbf52fcb714194c994a6893cbbf7ada38bc2165a1f83e4a6fc`。
+MIT样例固定 `52011f89c1741d06b40ea312af1f20be8be9ec62`,改造/来源见 THIRD_PARTY_NOTICES。
+闭源 runtime 与样例许可证不同;十四个必需 DLL 原样保存在本地候选 `runtime/nvidia/vfg`,
+独立 `vfg-runtime-manifest.json`/许可证,不进入源码 Git,不增加用户运行库哈希锁。
+
+预定本地候选 `E:/项目/Veyra/test-packages/vfg-integration-20261003/`
+`Veyra-2.0.2-vfg-20261003-win64-portable.zip`;最终组包、清洁环境实跑与哈希将在完成后记录。
+源码已达到上述本机检查,最终包目前尚未验收。未 merge main、push 或公开发布。
diff --git a/docs/VFG_INTEGRATION_EXECUTION_2026-10-03.md b/docs/VFG_INTEGRATION_EXECUTION_2026-10-03.md
new file mode 100644
index 00000000..ae96309f
--- /dev/null
+++ b/docs/VFG_INTEGRATION_EXECUTION_2026-10-03.md
@@ -0,0 +1,28 @@
+# VFG 全档位接入施工(2026-10-03)
+
+## 授权与开工存档
+
+用户明确要求接入 VFG,支持 8X,并追加“所有档位都加上”。范围为原生 C++ NVIDIA VFG 后端、预览及视频导出、2X/3X/4X/5X/6X/7X/8X、Low/Medium/High(默认 Medium)、列表/节点/会话/预设/导出任务保存,以及完成这些功能所必需的共享图、GPU 互操作和资源池。保留原后端的合法倍率,不将 VFG 的 8X 放开成 DLSS 8X。
+
+源码起点 `1802f43565e07f3c3040d3fe745ca2e939aab00f`,工作树 `E:/项目/Veyra/worktrees/field-upgrade-20261003`,新分支 `codex/vfg-integration-20261003`。产品编辑前完成 `git bundle create ... HEAD`、`git bundle verify`、干净状态记录与 tag `checkpoint/pre-vfg-integration-20261003`。存档 `E:/项目/Veyra/archives/vfg-integration-20261003-start/source-before.bundle`,SHA256 `1F3154049591C069B6CD63D266FC4447A153480D41608086BEB1422092E8D6F0`。原修复和研究分支、main、桌面原工作树不改。
+
+SDK 来源/固定版本/哈希/许可/研究证据见 [研究方案](VFG_RESEARCH_AND_INTEGRATION_PLAN_2026-10-03.md)。研究方案中的首期仅 2X/4X 被本次全部倍率授权覆盖。官方 2X/4X 生产档和 6X/8X 实验档的区别保留;3X/5X/7X 为公共倍率 API 可选项,不凭整数范围宣称已验,逐档实际测试。
+
+## 实施与约束
+
+1. P1 原生 API 和 GPU bridge:固定 SDK ABI,C++ 动态加载绝对路径和受限搜索;CUDA device LUID 与 D3D12 adapter 相同。共享 D3D12 buffer/fence 在创建时导入,GPU texture/buffer 拷贝,CUDA 流等待 producer、运行/保存每个结果、signal consumer;D3D12 queue 等待后使用拥有租约的生成纹理。无 Python 产品依赖、无逐帧 CPU fence wait、无生产像素 readback。初始化/退出可排空。
+2. P2 共享图:稳定 backend ID 4,FG 最后、OSD/字幕之前;无需外部 guidance,其他 NR/SR 的 flow 保留。FrameBatch 8、生成池 14(2 parity × 7)、GPU 计时/状态数组/描述符/回收一致扩容。A/B 真实 PTS,首帧/seek/切镜/掉帧/resize/暂停恢复/源切换/device lost 原子 reset,避免旧帧跨 epoch。输出缓冲被重写之前保存,不以重复帧当生成帧。
+3. P3 设置/UI:全部倍率及质量档后端专用;旧 ID/预设/默认不破坏。会话、预设、任务快照、worker serialization 相同;热切换失败明确回退并显示实际后端。6X–8X 明示实验;3X/5X 使用公共 API,在验收报告独立列证据。
+4. P4 导出:保持 D3D12 NVENC 与冻结 settings,VFG 不进入 XeSS/FSR 替换 DLSS 分支。每个间隔 M−1 张真实生成帧与每张源帧进入 CFR 时间线;首尾 hold、切镜 bypass、失败/取消必须准确计数和记录,导出不丢源帧。
+5. P5 验收:GPU bridge identity、2..8 全倍率输出/非重复/PTS/租约、三质量、reset/关闭/resize/失败,SDR RGBA8/10-bit 边界单测;真实产品预览/热切换/保存恢复及 NVENC 文件 frame count/rate/duration/audio。NR+SR 组合、1080p/4K、24/30/60fps 性能/显存分开记录;未接 RTX40/采集/主机、物理显示节奏/端到端延迟和 HDR 色度专项不得冒称通过。
+
+仅必要范围,不重写 source/audio clocks/NR/SR。不依赖 Streamline/ReShade,不复制 proprietary SDK headers/models/runtime 到 Git,不改磁盘运行库或哈希锁。SDK 默认本机研发,公开分发需另做许可与组件审计;本轮无上传/发布授权。故障若只能传输或 UI 测试通过,不将其升级成 VFG 推理成功。
+
+## 产物与续接状态
+
+本任务 `E:/项目/Veyra/{build,tests,logs,tmp,test-packages}/vfg-integration-20261003`;已有 SDK 保持 `deps/vfg-python-20261003` 与 `deps/vfg-samples-20261003`。TEMP/TMP 仅设置子进程。
+
+- P0 研究已完成;完整结果在研究方案。
+- P1–P4 已实现,P5 原生720p/4K全组合、21种真实导出、GUI热切换/会话/worker/缺失组件回退、本机 NR+最高 SR4K+VFG8 已通过,详见 `VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md`。
+- 最终产品编译 `build-product-v4.log` exit0;设置/旧格式/QML回归 `unit-v4`、GUI `ui-v4`、组合 `combinations-v4` 通过。核心与早期失败证据均保留,不把短测当长稳或物理显示验收。
+- 本地便携候选组包和脱离开发目录的最终验证尚在进行;没有 merge/push/Release。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 17ad9c3f..32738b52 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,25 @@
# Veyra 工作记录
+## 2026-10-03 VFG 全倍率产品闭环(最终组包前)
+
+- 产品 native/graph/pool/presenter/NVENC、backend ID4与三质量、旧格式迁移、列表/节点预设/会话、worker ABI8、QML全部倍率控件完成。原生463 checks各720p/4K与实际21种导出通过;详情 `docs/VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md`,此前“产品仍在进行”条目是早期状态。
+- 命令统一 Python311 `-B scripts/acceptance/...`:`vfg-build.py build-product-v4.log veyra_qml_ui veyra_vfg_export_probe veyra_vfg_gpu_tests veyra_vfg_settings_tests veyra_preset_library_tests veyra_repair_preset_tests veyra_repair_contract_tests veyra_effect_chain_tests veyra_qml_quick_tests` exit0,51步;`vfg-product-tests.py unit-v4 unit` exit0,331 settings/旧预设/合同/EffectChain/QML39;`vfg-ui.py ui-v4` exit0,run/restore/missing全部通过。输出统一 E:/项目/Veyra/logs/vfg-integration-20261003,与tests/tmp对应子目录。
+- `vfg-product-tests.py export-all-v2 export` exit0,30fps720p全部21组合,HEVC/NVENC,16..64帧和60..240fps/时长/音轨核验。首轮 runner 因 fps 微秒舍入和CLI日志读取失败,产品导出本身成功;修正断言及读实际stdout,不掩盖首轮失败。
+- `vfg-combination-tests.py combinations-v4` exit0:真实2560x1440/30fps AVI+SR最高档至4K+3840x2160原生NR+VFG8 Medium,24源/161生成/7尾hold/192输出;24→192与60→480fps;取消无最终文件;缺失SDK导出exit1是预期失败而非成功导出。
+- 缺失组件实际 UI bug 留证 ui-missing-diagnostic:active=false、enabled=true、position9.2、multiplier8;修复 EngineController recovery rejection revision 与 facade后端/倍率/质量对账,较新请求受保护,ui-v4验为enabled=false/multiplier1、9.1667s基础播放。外部光流策略对VFG完全关闭,NR/SR仍保留;runtime路径探测改error_code。
+- ui-v1 与QtQuick并行时进入Paused而GPU正常排空,不能称GPU卡死;干扰原因是推断。此后串行ui-v2/v4热切换正常,最终使用v4完整结果。8X Low约241次/秒提交,High约60且调度降档,不称240fps稳定显示或物理延迟下降。
+- 来源/固定MIT样例/原生API改造已写 THIRD_PARTY_NOTICES。源码Git没有新DLL/SDK/模型;最终包尚待组包/干净运行。无merge/push/Release,main/桌面状态待最后再次核对。
+
+## 2026-10-03 VFG 原生接入施工
+
+- 用户追加授权 VFG 2X–8X 全倍率及 Low/Medium/High 全质量;新分支 codex/vfg-integration-20261003,起点 1802f43565e07f3c3040d3fe745ca2e939aab00f,tag checkpoint/pre-vfg-integration-20261003。E:/项目/Veyra/archives/vfg-integration-20261003-start/source-before.bundle 验证通过,SHA256 1F3154049591C069B6CD63D266FC4447A153480D41608086BEB1422092E8D6F0。先存档/写 docs/VFG_INTEGRATION_EXECUTION_2026-10-03.md 后施工,桌面工作区/main 保留。
+- 原生 C++ 直接动态调用官方 Video Effects 1.3.0,外部 CUDA driver headers 仅编译依赖。NVCV 自行分配 opaque descriptor,D3D12 shared buffer + producer/completion fence 与 CUDA stream 互操作;逐帧无 CPU 像素读回/CPU fence wait,不引入 Python、Streamline、ReShade 产品依赖。shader/output 编码保持现有边界。
+- `python -B scripts/acceptance/vfg-build.py build-native-tests-v3.log veyra_vfg_gpu_tests` exit0;前次缺失 readback helper 编译失败已修复。`python -B scripts/acceptance/vfg-native-tests.py native-720-v2` exit0,463 checks/0 failures,RTX5070 616.56,RGBA8 与 RGB10A2,全部 2X–8X/三质量,8X 七张独立哈希/中间位置、manual cut 与当前帧一致、D3D12 debug errors 0。CPU readback 仅诊断测试。
+- native-720-v1 全测失败:SDK FromD3DFormat 不接受 RGB10A2,且参考声明误写 DestroyEffect 返回值。根据官方 void API 修复销毁,SDK packed format capability 实测确定 RGB10A2=13/P32=11,留证 packed-format-capabilities.json;v2 验证 10-bit 顺序/切镜精确拷贝通过。不能把首轮 SDR 部分通过当全测通过。
+- 高质量 720p 8X 约104–107ms/组(包含测试 CPU 提交、GPU copy 和同步),不证明实时 30fps;三质量/高倍允许离线完整生成,实时仍按现有预算/PTS调度记录实际跳帧。本轮物理屏幕节奏、RTX40、HDR 色度及组合性能尚待测。
+- 已扩 FrameBatch=8 / 生成池14 / 输出池16,present descriptor 改由池尺寸推导,保留 DLSS compatibility 原十张全尺寸绑定;新增 FG6/FG7 计时、专用 ID4 与 vfgQuality,预设/会话迁移和 worker ABI8。产品图/GUI/NVENC 完整构建与真实验证仍在进行,不宣称已交付。
+- 产物统一 E:/项目/Veyra/{build,tests,logs,tmp,test-packages}/vfg-integration-20261003,运行时 E:/项目/Veyra/deps/vfg-python-20261003,源码 Git 未新增 DLL/SDK/model。无 merge/push/Release。
+
## 2026-10-03 五项修复:代码与本机验收
- 最终本地包 E:/项目/Veyra/test-packages/field-upgrade-20261003/Veyra-2.0.2-field-20261003-win64-portable.zip,766558374 bytes,SHA256 099751e596b4a7de814ddc2af9cdaa527817d1a422861cdcee5a6be77877c679,2054 payload 文件;审计 E:/项目/Veyra/logs/field-upgrade-20261003/candidate-package-audit.json。应用 SHA256 2d708d65aff3f61950243d4743397d1869aca2ec2e4b56311fcd63aa3abfbcd3;source ZIP 单独提供,代码存档 c80662f344032ca3adac42277b1ab6726609cde6 / checkpoint/field-upgrade-code-20261003,runtime/模型与源码分离。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index f64d6ffb..17d3f710 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -1043,6 +1043,13 @@
"en": "NVIDIA RTX frame generation; the multiplier depends on what the runtime supports",
"ja": "NVIDIA RTX のフレーム生成。倍率はランタイムの実際の対応範囲によります"
},
+ {
+ "zh": "NVIDIA VFG 未能启用(需要 Ada / Blackwell 显卡、VFG 运行组件和支持的输出格式),已关闭补帧;原因见日志",
+ "src": "src/engine/EngineController.cpp",
+ "zh-TW": "NVIDIA VFG 未能啟用(需要 Ada / Blackwell 顯示卡、VFG 執行組件和支援的輸出格式),已關閉補幀;原因見日誌",
+ "en": "NVIDIA VFG could not start (requires an Ada / Blackwell GPU, VFG runtime and a supported output format). Frame generation is off; see the log.",
+ "ja": "NVIDIA VFG を有効にできませんでした(Ada / Blackwell GPU、VFG ランタイム、対応する出力形式が必要)。フレーム生成はオフです。ログをご確認ください。"
+ },
{
"zh": "NVIDIA 驱动级 AI 插帧,与软件内补帧二选一",
"src": "qml/SettingsPage.qml",
@@ -1255,7 +1262,7 @@
},
{
"zh": "RTX 50 · NVIDIA 原版",
- "src": "qml/Veyra/NrLayerEditor.qml",
+ "src": "qml/NrLayerEditor.qml",
"zh-TW": "RTX 50 · NVIDIA 原版",
"en": "RTX 50 · NVIDIA original",
"ja": "RTX 50 · NVIDIA オリジナル"
@@ -1379,6 +1386,34 @@
"en": "UI correction · unverified",
"ja": "UI 補正 · 未検証"
},
+ {
+ "zh": "VFG 支持 2X~8X 和低 / 中 / 高质量;6X~8X 为实验档,高倍高质量会增加处理时间",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "VFG 支援 2X~8X 和低 / 中 / 高品質;6X~8X 為實驗檔,高倍高品質會增加處理時間",
+ "en": "VFG supports 2X–8X and Low / Medium / High quality. 6X–8X are experimental; higher multipliers and quality take more processing time.",
+ "ja": "VFG は 2X~8X と低 / 中 / 高品質に対応します。6X~8X は実験設定です。倍率や品質を上げると処理時間が増えます。"
+ },
+ {
+ "zh": "VFG 质量",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "VFG 品質",
+ "en": "VFG quality",
+ "ja": "VFG 品質"
+ },
+ {
+ "zh": "VFG 质量设置未被接受,原设置保留",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "VFG 品質設定未被接受,原設定保留",
+ "en": "VFG quality was not accepted; the previous setting was kept.",
+ "ja": "VFG 品質設定が拒否されたため、前の設定を保持しました。"
+ },
+ {
+ "zh": "VFG 需要 NVIDIA Ada / Blackwell 显卡(RTX 40 / 50)",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "VFG 需要 NVIDIA Ada / Blackwell 顯示卡(RTX 40 / 50)",
+ "en": "VFG requires an NVIDIA Ada / Blackwell GPU (RTX 40 / 50).",
+ "ja": "VFG には NVIDIA Ada / Blackwell GPU(RTX 40 / 50)が必要です。"
+ },
{
"zh": "Veyra 本地诊断(复制前脱敏预览;不会上传)\n",
"src": "src/base/Log.cpp",
@@ -1484,6 +1519,13 @@
"en": "Xbox streaming…",
"ja": "Xbox ストリーミング…"
},
+ {
+ "zh": "Xbox 串流中断({}),正在重连 {}/3…",
+ "src": "src/engine/EngineController.cpp",
+ "zh-TW": "Xbox 串流中斷({}),正在重連 {}/3…",
+ "en": "Xbox stream interrupted ({}); reconnecting {}/3…",
+ "ja": "Xbox ストリームが中断されました({})。再接続中 {}/3…"
+ },
{
"zh": "Xbox 串流中断,请重新连接。",
"src": "src/engine/EngineController.cpp",
@@ -1505,6 +1547,20 @@
"en": "Xbox streaming connection failed; see diagnostics",
"ja": "Xbox ストリーミングの接続に失敗しました。診断を確認してください"
},
+ {
+ "zh": "Xbox 已重新连接",
+ "src": "src/engine/EngineController.cpp",
+ "zh-TW": "Xbox 已重新連接",
+ "en": "Xbox reconnected",
+ "ja": "Xbox に再接続しました"
+ },
+ {
+ "zh": "Xbox 服务结束了串流(",
+ "src": "src/source/XboxSessionSource.cpp",
+ "zh-TW": "Xbox 服務結束了串流(",
+ "en": "The Xbox service ended the stream (",
+ "ja": "Xbox サービスがストリームを終了しました("
+ },
{
"zh": "Xbox 服务返回错误(HTTP %1)。",
"src": "src/ui/XboxModel.cpp",
@@ -1540,6 +1596,20 @@
"en": "Xbox connection failed: ",
"ja": "Xbox 接続に失敗しました:"
},
+ {
+ "zh": "Xbox 重连失败:",
+ "src": "src/engine/EngineController.cpp",
+ "zh-TW": "Xbox 重連失敗:",
+ "en": "Xbox reconnection failed: ",
+ "ja": "Xbox の再接続に失敗:"
+ },
+ {
+ "zh": "Xbox 重连时 GPU 排空失败",
+ "src": "src/engine/EngineController.cpp",
+ "zh-TW": "Xbox 重連時 GPU 排空失敗",
+ "en": "Could not drain the GPU queue during Xbox reconnection.",
+ "ja": "Xbox 再接続時に GPU キューの待機処理に失敗しました。"
+ },
{
"zh": "XeSS 初始化失败;当前为普通呈现",
"src": "src/engine/EngineController.cpp",
@@ -1864,7 +1934,7 @@
},
{
"zh": "中",
- "src": "qml/SettingsPage.qml",
+ "src": "qml/NodePage.qml",
"zh-TW": "中",
"en": "Medium",
"ja": "中"
@@ -2219,13 +2289,6 @@
"en": "The host's certificate does not match the one saved at pairing (the host was reinstalled, or this is not the paired one). Remove this host and pair again.",
"ja": "ホストの証明書がペアリング時に保存したものと一致しません(ホストが再インストールされたか、ペアリングしたホストではありません)。このホストを削除して再ペアリングしてください。"
},
- {
- "zh": "主机结束了串流。",
- "src": "src/source/XboxSessionSource.cpp",
- "zh-TW": "主機結束了串流。",
- "en": "The host ended the stream.",
- "ja": "ホストがストリーミングを終了しました。"
- },
{
"zh": "主机要用同一个账号登录,并在 设置 → 设备和连接 → 远程功能 里启用远程功能",
"src": "qml/DialogHost.qml",
@@ -2331,6 +2394,13 @@
"en": "Bitstream first (Dolby/DTS passthrough decoding)",
"ja": "ビットストリーム優先(Dolby/DTS パススルーデコード)"
},
+ {
+ "zh": "低",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "低",
+ "en": "Low",
+ "ja": "低"
+ },
{
"zh": "低延迟",
"src": "include/veyra/source/CaptureFormatRank.h",
@@ -2648,7 +2718,7 @@
},
{
"zh": "全屏显存增长保护",
- "src": "qml/Veyra/SettingsPage.qml",
+ "src": "qml/SettingsPage.qml",
"zh-TW": "全螢幕顯存增長保護",
"en": "Fullscreen VRAM growth protection",
"ja": "全画面の VRAM 増加保護"
@@ -3720,7 +3790,7 @@
},
{
"zh": "启动后自动继续上次内容",
- "src": "qml/Veyra/SettingsPage.qml",
+ "src": "qml/SettingsPage.qml",
"zh-TW": "啟動後自動繼續上次內容",
"en": "Automatically resume on startup",
"ja": "起動時に前回の再生を再開"
@@ -4950,13 +5020,6 @@
"en": "Other files can still be previewed during export; they compete with it for the GPU.",
"ja": "書き出し中も他のファイルをプレビューできますが、書き出しと GPU を取り合います。"
},
- {
- "zh": "导出设置无效",
- "src": "src/ui/QmlPlayerBridge.cpp",
- "zh-TW": "匯出設定無效",
- "en": "Invalid export settings",
- "ja": "書き出し設定が不正です"
- },
{
"zh": "导出设置无效:%1",
"src": "src/ui/QmlPlayerBridge.cpp",
@@ -6148,11 +6211,11 @@
"ja": "選択したフォーマットは {:.3f} FPS ですが、キャプチャーカードは {:.3f} FPS を返しています。デバイスが対応するフォーマットを選び直してください。"
},
{
- "zh": "所选补帧后端最高 %1X,倍率已调整为 %1X",
+ "zh": "所选补帧后端的倍率已调整为 %1X",
"src": "src/ui/QmlPlayerBridge.cpp",
- "zh-TW": "所選補幀後端最高 %1X,倍率已調整為 %1X",
- "en": "The selected frame generation backend goes up to %1X; the multiplier was set to %1X",
- "ja": "選択したフレーム生成方式は最大 %1X のため、倍率を %1X にしました"
+ "zh-TW": "所選補幀後端的倍率已調整為 %1X",
+ "en": "The selected frame-generation backend adjusted the multiplier to %1X.",
+ "ja": "選択したフレーム生成方式の倍率を %1X に調整しました。"
},
{
"zh": "所选设备不可用,已回落到系统默认:",
@@ -6626,7 +6689,7 @@
},
{
"zh": "播放速度",
- "src": "qml/Veyra/PlaybackRateButton.qml",
+ "src": "qml/PlaybackRateButton.qml",
"zh-TW": "播放速度",
"en": "Playback speed",
"ja": "再生速度"
@@ -7492,6 +7555,13 @@
"en": "Not run",
"ja": "未実行"
},
+ {
+ "zh": "未找到 VFG 运行组件,请在组件页核对路径",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "未找到 VFG 執行組件,請在組件頁核對路徑",
+ "en": "VFG runtime components were not found. Check their paths on the Components page.",
+ "ja": "VFG ランタイムが見つかりません。コンポーネントページでパスをご確認ください。"
+ },
{
"zh": "未找到可捕获的窗口或显示器",
"src": "qml/DialogHost.qml",
@@ -7800,13 +7870,6 @@
"en": "A Dolby Vision RPU was found but the base layer's compatibility signalling is missing, so the colors cannot be confirmed; stopped",
"ja": "Dolby Vision RPU を検出しましたが、ベースレイヤーの互換宣言がなく色を確認できないため停止しました"
},
- {
- "zh": "检测到 NVIDIA App 的画面插件(RTX HDR / 智能平滑运动 / RTX 动态鲜艳度)注入了 Veyra,它已知会在采集开始时让显卡设备丢失或让程序崩溃。请在 NVIDIA App → 图形 → 程序设置里为 Veyra 关闭这几项后再试",
- "src": "src/ui/QmlPlayerBridge.cpp",
- "zh-TW": "偵測到 NVIDIA App 的畫面外掛(RTX HDR / 智慧平滑運動 / RTX 動態鮮豔度)注入了 Veyra,已知它會在擷取開始時造成顯示卡裝置遺失或程式當機。請在 NVIDIA App → 圖形 → 程式設定中為 Veyra 關閉這幾項後再試",
- "en": "NVIDIA App's picture plug-in (RTX HDR / Smooth Motion / RTX Dynamic Vibrance) is injected into Veyra; it is known to lose the GPU device or crash Veyra when a capture starts. Turn these off for Veyra in NVIDIA App → Graphics → Program Settings and try again",
- "ja": "NVIDIA App の画面プラグイン(RTX HDR / Smooth Motion / RTX Dynamic Vibrance)が Veyra に挿入されています。キャプチャ開始時に GPU デバイスの喪失やクラッシュを起こすことが確認されています。NVIDIA App → グラフィックス → プログラム設定で Veyra に対してこれらをオフにしてから再試行してください"
- },
{
"zh": "检测到 OBS 游戏采集和小飞机(RTSS)同时注入 Veyra。两者默认的挂钩方式冲突,OBS 游戏采集可能抓不到画面(任何 D3D12 程序都一样)。在 RTSS 里添加 veyra_qml_ui.exe,并在它的设置中勾选“Use Microsoft Detours API hooking”;或在 OBS 改用窗口采集(Windows 10 1903+)",
"src": "src/ui/QmlPlayerBridge.cpp",
@@ -7830,7 +7893,7 @@
},
{
"zh": "检测异常增长时自动退出全屏;默认关闭",
- "src": "qml/Veyra/SettingsPage.qml",
+ "src": "qml/SettingsPage.qml",
"zh-TW": "偵測異常增長時自動退出全螢幕;預設關閉",
"en": "Exit fullscreen if abnormal growth is detected; off by default",
"ja": "異常な増加を検出すると全画面を解除(初期設定はオフ)"
@@ -9039,13 +9102,6 @@
"en": "Target bitrate: 1–300 Mbps. Actual VBR average bitrate varies with scene complexity.",
"ja": "目標ビットレートは 1~300 Mbps。VBR の実際の平均値は映像の複雑さによって変わります。"
},
- {
- "zh": "目标码率影响画质与文件大小。",
- "src": "qml/ExportPage.qml",
- "zh-TW": "目標位元率影響畫質與檔案大小。",
- "en": "The target bitrate affects picture quality and file size.",
- "ja": "目標ビットレートは画質とファイルサイズに影響します。"
- },
{
"zh": "目标行数",
"src": "qml/DialogHost.qml",
@@ -10266,7 +10322,7 @@
},
{
"zh": "视频恢复上次进度;采集卡沿用上次设备与设置",
- "src": "qml/Veyra/SettingsPage.qml",
+ "src": "qml/SettingsPage.qml",
"zh-TW": "影片恢復上次進度;擷取卡沿用上次裝置與設定",
"en": "Resume the video position or reopen the last capture device and settings",
"ja": "動画の前回の位置、または前回のキャプチャーデバイスと設定を復元"
@@ -12686,6 +12742,13 @@
"en": "Preset library: invalid NR resolution",
"ja": "プリセットライブラリの NR 解像度が不正です"
},
+ {
+ "zh": "预设库 VFG 质量字段损坏",
+ "src": "src/engine/PresetLibrary.cpp",
+ "zh-TW": "預設庫 VFG 品質字段損壞",
+ "en": "The preset library has an invalid VFG quality field.",
+ "ja": "プリセットライブラリの VFG 品質フィールドが破損しています。"
+ },
{
"zh": "预设库保护区域损坏",
"src": "src/engine/PresetLibrary.cpp",
@@ -12805,6 +12868,13 @@
"en": "Preset library: invalid frame generation backend or multiplier",
"ja": "プリセットライブラリのフレーム生成方式または倍率が不正です"
},
+ {
+ "zh": "预设库补帧后端无效",
+ "src": "src/engine/PresetLibrary.cpp",
+ "zh-TW": "預設庫補幀後端無效",
+ "en": "The preset library has an invalid frame-generation backend.",
+ "ja": "プリセットライブラリのフレーム生成方式が無効です。"
+ },
{
"zh": "预设库调色参数超出范围",
"src": "src/engine/PresetLibrary.cpp",
@@ -13064,6 +13134,13 @@
"en": "Driver default (no override)",
"ja": "ドライバーの既定(介入しない)"
},
+ {
+ "zh": "高",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "高",
+ "en": "High",
+ "ja": "高"
+ },
{
"zh": "高光",
"src": "qml/ColourPanel.qml",
@@ -13078,6 +13155,13 @@
"en": "high latency · needs CPU unpacking",
"ja": "高遅延 · CPU での展開が必要"
},
+ {
+ "zh": "高质量需要更多处理时间",
+ "src": "qml/NodePage.qml",
+ "zh-TW": "高品質需要更多處理時間",
+ "en": "High quality takes more processing time.",
+ "ja": "高品質にはより多くの処理時間が必要です。"
+ },
{
"zh": "黄色",
"src": "qml/ColourMixer.qml",
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
index d4eac1a4..753eb404 100644
--- a/include/veyra/diagnostics/FrameMetrics.h
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -7,11 +7,11 @@
namespace veyra::diagnostics {
// NrLayer*/ColorNode* are per-instance node spans nested inside the stage
// spans above; they are never merged into enhancementProcessingMs.
-enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, Fg4, Fg5, FgBatch, Blit, VideoHdr,
+enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, Fg4, Fg5, Fg6, Fg7, FgBatch, Blit, VideoHdr,
NrLayer0, NrLayer1, NrLayer2, NrLayer3,
ColorNode0, ColorNode1, ColorNode2, ColorNode3, ColorNode4, ColorNode5, Count };
static_assert(unsigned(GpuStage::Fg5)-unsigned(GpuStage::Fg1)==4);
-static_assert(unsigned(GpuStage::FgBatch)>unsigned(GpuStage::Fg5));
+static_assert(unsigned(GpuStage::FgBatch)>unsigned(GpuStage::Fg7));
static_assert(unsigned(GpuStage::Count)<=32,"GpuTimer keeps one mask bit per stage");
inline constexpr unsigned kTimedNrLayers=4,kTimedColorNodes=6;
// NR layers are indexed among EXECUTING layers; Color by parameter ordinal.
diff --git a/include/veyra/engine/EffectChain.h b/include/veyra/engine/EffectChain.h
index ab3e574a..77669c0d 100644
--- a/include/veyra/engine/EffectChain.h
+++ b/include/veyra/engine/EffectChain.h
@@ -193,6 +193,7 @@ struct ChainGlobalSettings {
pipeline::SrTarget srTarget = pipeline::SrTarget::Uhd4K;
uint32_t videoSrQuality = 0;
FrameGenerationBackend fgBackend = FrameGenerationBackend::Dlss;
+ uint32_t vfgQuality=1;
FlowQuality flow = FlowQuality::Balanced;
OpticalFlowBackend opticalFlowBackend = OpticalFlowBackend::Nvidia;
bool amdFlowHalfResolution = false;
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index 706b92e3..32ea881e 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -30,7 +30,7 @@ inline bool validNrAntiFlicker(NrAntiFlicker v) {
}
// Preserve persisted values 0/1/2; the old Fsr value now explicitly selects
// the 3.1 provider. Fsr4 requires a real ML provider, never an auto fallback.
-enum class FrameGenerationBackend { Dlss = 0, XeSS = 1, Fsr = 2, Fsr4 = 3 };
+enum class FrameGenerationBackend { Dlss = 0, XeSS = 1, Fsr = 2, Fsr4 = 3, Vfg = 4 };
constexpr bool fsrFrameGeneration(FrameGenerationBackend backend) {
return backend == FrameGenerationBackend::Fsr || backend == FrameGenerationBackend::Fsr4;
}
@@ -45,6 +45,7 @@ constexpr bool presentSinkFrameGeneration(FrameGenerationBackend backend) {
// Multipliers the UI offers. 5X is intentionally absent: the DLSS runtime
// exposes 2/3/4/6 and MFG buyers pick from those; 1 = generation off.
inline constexpr uint32_t kFgMultiplierChoices[]={1,2,3,4,6};
+inline constexpr uint32_t kVfgMultiplierChoices[]={1,2,3,4,5,6,7,8};
inline constexpr size_t kFgMultiplierChoiceCount=sizeof(kFgMultiplierChoices)/sizeof(kFgMultiplierChoices[0]);
// Export bitrate presets in Mbps; index 0 keeps the encoder's constant-quality
// default. Labels are the UI strings for the same order.
@@ -97,7 +98,8 @@ enum class AudioSyncMode { Automatic, Manual, Off };
enum class HdrOutputMode { Hdr10, ScRgb };
enum class MotionSource { Zero, OpticalFlow, Automatic };
constexpr bool motionUsesFlow(MotionSource source,FrameGenerationBackend backend=FrameGenerationBackend::Dlss) {
- return source==MotionSource::OpticalFlow||(source==MotionSource::Automatic&&backend!=FrameGenerationBackend::XeSS);
+ return backend!=FrameGenerationBackend::Vfg&&
+ (source==MotionSource::OpticalFlow||(source==MotionSource::Automatic&&backend!=FrameGenerationBackend::XeSS));
}
constexpr std::string_view frameGenerationBackendName(FrameGenerationBackend backend) {
switch(backend) {
@@ -105,6 +107,7 @@ constexpr std::string_view frameGenerationBackendName(FrameGenerationBackend bac
case FrameGenerationBackend::XeSS: return "XeSS";
case FrameGenerationBackend::Fsr: return "AMD-FSR";
case FrameGenerationBackend::Fsr4: return "AMD-FSR4-ML";
+ case FrameGenerationBackend::Vfg: return "NVIDIA-VFG";
}
return "unknown";
}
@@ -241,6 +244,7 @@ struct EnhancementSettings {
uint32_t videoSrQuality=0; // 0 DLSS SR; 1–4 RTX Video SR
uint32_t multiplier=1;
FrameGenerationBackend frameGenerationBackend=FrameGenerationBackend::Dlss;
+ uint32_t vfgQuality=1; // NvVFX Mode: Low=0, Medium=1 (default), High=2
// Export target bitrate in Mbps; 0 keeps the encoder's constant-quality
// default (NVENC CONSTQP / MFT quality mode). Only the export job consumes
// it: preview never re-encodes.
@@ -338,7 +342,8 @@ struct EnhancementSettings {
return "active NR layers must share runtime and NR/SR order";
}
if(nr&&nrLayerCount&&!activeNrLayerCount())return "enabled NR stack has no active layer";
- if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::Fsr4)return "invalid frame generation backend";
+ if(frameGenerationBackend<FrameGenerationBackend::Dlss||frameGenerationBackend>FrameGenerationBackend::Vfg)return "invalid frame generation backend";
+ if(vfgQuality>2)return "invalid VFG quality";
// The XeSS provider reports its own generated-frame ceiling at session
// start; the engine clamps/rejects above it, so validation only guards
// the absolute API range here.
@@ -349,7 +354,7 @@ struct EnhancementSettings {
if(videoSrQuality>kVideoSrFsr)return "invalid video SR quality";
if(!pipeline::validSrTarget(srTarget))return "invalid SR target";
if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx&&opticalFlowBackend!=OpticalFlowBackend::GpuDis)return "invalid optical flow backend";
- if(multiplier<1||multiplier>6)return "unsupported multiplier";
+ if(multiplier<1||multiplier>(frameGenerationBackend==FrameGenerationBackend::Vfg?8u:6u))return "unsupported multiplier";
// 0 = auto quality; explicit values are capped at 300 Mbps so a typo
// cannot ask a driver for a nonsense rate.
if(exportBitrateMbps>300)return "export bitrate out of range";
diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.h
index d0f8c2fc..06412aac 100644
--- a/include/veyra/engine/GraphDescription.h
+++ b/include/veyra/engine/GraphDescription.h
@@ -90,6 +90,7 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
desc.videoSrQuality=settings.videoSrQuality;
describeNrLayers(settings,desc);
desc.frameGenerationBackend=settings.frameGenerationBackend;
+ desc.vfgQuality=settings.vfgQuality;
desc.color=settings.color;
desc.additionalColors=settings.additionalColors;
desc.additionalColorCount=settings.additionalColorCount;
diff --git a/include/veyra/engine/PresetLibrary.h b/include/veyra/engine/PresetLibrary.h
index c4dee859..6eec23e7 100644
--- a/include/veyra/engine/PresetLibrary.h
+++ b/include/veyra/engine/PresetLibrary.h
@@ -34,6 +34,7 @@ inline constexpr uint32_t kPresetAllContent =
struct PresetFrameGeneration {
uint32_t multiplier = 1;
FrameGenerationBackend backend = FrameGenerationBackend::Dlss;
+ uint32_t vfgQuality = 1;
bool operator==(const PresetFrameGeneration&) const = default;
};
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index a4e8668a..50ed80af 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -45,6 +45,7 @@ struct SwsContext;
struct NVSDK_NGX_Parameter;
struct NVSDK_NGX_Handle;
namespace veyra::guidance { class AmdOpticalFlow; class GpuDisOpticalFlow; }
+namespace veyra::pipeline { class VfgBackend; }
namespace veyra::gfx {
class D3D12DeviceContext;
@@ -69,9 +70,9 @@ struct ColorDescription;
// Decoded-surface view for the D3D11VA ingress (defined in FramePacket.h).
struct HardwareSurfaceInput;
-// One generated-frame texture per (parity, subframe): 2 parities x 5 generated
-// frames = 6X multi-frame generation. Sized once, reused for every FG backend.
-inline constexpr unsigned kGeneratedPoolSlots=10;
+// One generated texture per (parity, subframe), through seven subframes at 8X.
+// Each backend keeps its own supported multiplier and resource requirements.
+inline constexpr unsigned kGeneratedPoolSlots=2*(FrameBatch::Capacity-1);
inline constexpr unsigned kOutputPoolSlots=2+kGeneratedPoolSlots;
struct EnhanceGraphDesc {
@@ -114,6 +115,7 @@ struct EnhanceGraphDesc {
uint32_t flowWidth=0,flowHeight=0; // zero preserves legacy source-space NVOF extent
uint32_t fgMultiplier=2;
engine::FrameGenerationBackend frameGenerationBackend=engine::FrameGenerationBackend::Dlss;
+ uint32_t vfgQuality=1;
uint64_t settingsRevision=1;
engine::FlowQuality flowQuality=engine::FlowQuality::Balanced;
engine::OpticalFlowBackend opticalFlowBackend=engine::OpticalFlowBackend::Nvidia;
@@ -602,6 +604,8 @@ private:
bool initNgxFeatures();
bool initFsrSr();
bool initFsrFg();
+ bool initVfg();
+ std::unique_ptr<VfgBackend> vfgBackend_;
// RTX 40 series: opens the Blackwell-only multi-frame gate in the mapped
// DLSS-G runtime. Never touched on any other architecture.
void applyAdaMfgUnlock();
diff --git a/include/veyra/pipeline/FrameBatch.h b/include/veyra/pipeline/FrameBatch.h
index 0cf8af1e..7e6ded23 100644
--- a/include/veyra/pipeline/FrameBatch.h
+++ b/include/veyra/pipeline/FrameBatch.h
@@ -39,11 +39,11 @@ struct BatchFrame {
std::shared_ptr<FrameLease> lease;
};
struct FrameBatch {
- static constexpr uint32_t Capacity=6;
+ static constexpr uint32_t Capacity=8;
uint64_t batchId=0;
FrameIdentity identity;
int64_t a100ns=0,b100ns=0;
- // 6X multi-frame generation needs one real frame plus up to five generated
+ // 8X multi-frame generation needs one real frame plus up to seven generated
// frames in a single batch.
std::array<BatchFrame,Capacity> frames{};
uint32_t count=0;
diff --git a/include/veyra/pipeline/VfgBackend.h b/include/veyra/pipeline/VfgBackend.h
new file mode 100644
index 00000000..f638d1e1
--- /dev/null
+++ b/include/veyra/pipeline/VfgBackend.h
@@ -0,0 +1,34 @@
+#pragma once
+#include <d3d12.h>
+#include <memory>
+#include <string>
+
+namespace veyra::gfx { class D3D12DeviceContext; }
+namespace veyra::pipeline {
+// Public NvVFX 1.3 API. SDK metadata is allocated by NVCVImage.dll; no SDK
+// headers, models or implementation are vendored into the source repository.
+// Borrowed encoded textures stay in the graph's normal FrameLease pool.
+class VfgBackend {
+public:
+ VfgBackend();
+ ~VfgBackend();
+ VfgBackend(const VfgBackend&)=delete;
+ VfgBackend& operator=(const VfgBackend&)=delete;
+ static std::wstring runtimeDirectory(const std::wstring& runtimeRoot);
+ static bool runtimeAvailable(const std::wstring& runtimeRoot);
+ bool initialize(gfx::D3D12DeviceContext&,const std::wstring& runtimeRoot,
+ unsigned width,unsigned height,DXGI_FORMAT,unsigned multiplier,unsigned quality);
+ bool created() const;
+ // Caller transitions encoded texture to COPY_SOURCE and back to COMMON.
+ // Submit this list before generate(). All CPU waits are confined to teardown.
+ bool capture(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned parity);
+ // Signals an OWNED producer fence, waits/runs/signals on the CUDA stream,
+ // and queues a GPU wait before the caller records copyOutput().
+ bool generate(unsigned parity,unsigned subframe,unsigned multiplier,bool reset);
+ bool copyOutput(ID3D12GraphicsCommandList*,ID3D12Resource*,unsigned slot);
+ void shutdown();
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+};
+}
diff --git a/include/veyra/ui/PlayerUiFacade.h b/include/veyra/ui/PlayerUiFacade.h
index 983f9820..5997b9b3 100644
--- a/include/veyra/ui/PlayerUiFacade.h
+++ b/include/veyra/ui/PlayerUiFacade.h
@@ -122,6 +122,7 @@ private:
veyra::engine::NrRuntime requestedNrRuntime_=veyra::engine::NrRuntime::Original;
veyra::engine::FrameGenerationBackend requestedFgBackend_=veyra::engine::FrameGenerationBackend::Dlss;
uint32_t requestedFgMultiplier_=1;
+ uint32_t requestedVfgQuality_=1;
uint64_t revision_ = 0;
bool haveLast_ = false;
std::vector<RecentEntry> recent_;
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 666524d7..e5020d58 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -68,6 +68,7 @@ class QmlPlayerBridge : public QObject {
// --- frame generation settings ----------------------------------------
Q_PROPERTY(QString fgBackendName READ fgBackendName WRITE setFgBackendName NOTIFY settingsChanged)
+ Q_PROPERTY(int vfgQuality READ vfgQuality WRITE setVfgQuality NOTIFY settingsChanged)
Q_PROPERTY(QVariantList fgBackendChoices READ fgBackendChoices CONSTANT)
Q_PROPERTY(QString fgProviderText READ fgProviderText NOTIFY fgChoicesChanged)
Q_PROPERTY(int fgMaxMultiplier READ fgMaxMultiplier NOTIFY snapshotChanged)
@@ -478,6 +479,8 @@ public:
QVariantList fgBackendChoices() const;
QString fgProviderText() const;
void setFgBackendName(const QString& value);
+ int vfgQuality() const;
+ void setVfgQuality(int value);
int fgMaxMultiplier() const;
bool fgEnabled() const;
void setFgEnabled(bool enabled);
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index a69f2e91..8970f9f8 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -1568,7 +1568,7 @@ Item {
case "video-hdr": return qsTr("峰值 ") + (veyra.videoHdrParams.peakNits || 1000) + " nits"
case "protection": return veyra.protectionRegions.length + qsTr(" / 4 个区域")
case "color": return qsTr("调色参数")
- case "frame-generation": return veyra.fgMultiplier + "X · " + (veyra.fgBackendName === "xess" ? "Intel XeSS" : "DLSS")
+ case "frame-generation": return veyra.fgMultiplier + "X · " + (veyra.fgBackendChoices.find(x => x.id === veyra.fgBackendName) || {label: "FG"}).label
}
return ""
}
diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qml
index ebd98158..3c28446e 100644
--- a/qml/Veyra/NodePage.qml
+++ b/qml/Veyra/NodePage.qml
@@ -68,7 +68,7 @@ VPage {
case "nr": return "#FF8A3D"
case "protection": return "#8A8A96"
case "video-hdr": return "#FFB547"
- case "frame-generation": case "dlss-fg": case "xess-fg": case "fsr3-fg": case "fsr4-fg": return "#3DDC84"
+ case "frame-generation": case "dlss-fg": case "xess-fg": case "fsr3-fg": case "fsr4-fg": case "vfg-fg": return "#3DDC84"
}
return "#55555C"
}
@@ -1436,13 +1436,33 @@ VPage {
hint: veyra.fgMaxMultiplier + qsTr("X 为上限")
VSeg {
objectName: "node-fg-multiplier"
+ visible: veyra.fgBackendName !== "vfg"
options: veyra.fgMultiplierChoices
current: String(veyra.fgMultiplier)
onPicked: id => veyra.fgMultiplier = parseInt(id)
}
+ VSelect {
+ objectName: "node-vfg-multiplier"
+ visible: veyra.fgBackendName === "vfg"
+ options: veyra.fgMultiplierChoices
+ value: String(veyra.fgMultiplier) + "X"
+ onPicked: id => veyra.fgMultiplier = Number(id)
+ }
+ }
+ VRow {
+ label: qsTr("VFG 质量")
+ visible: veyra.fgBackendName === "vfg"
+ hint: qsTr("高质量需要更多处理时间")
+ VSelect {
+ objectName: "node-vfg-quality"
+ options: [{id:"0",label:qsTr("低")},{id:"1",label:qsTr("中")},{id:"2",label:qsTr("高")}]
+ value: options[veyra.vfgQuality].label
+ onPicked: id => veyra.vfgQuality = Number(id)
+ }
}
VRow {
label: qsTr("补帧运动来源")
+ visible: veyra.fgBackendName !== "vfg"
hint: qsTr("XeSS 默认零运动;FSR 仍有自身的光流计算")
VSeg { objectName: "node-fg-motion"; options: [{id:"0",label:qsTr("零运动")},{id:"1",label:qsTr("光流")}]; current: String(veyra.fgMotionSource); onPicked: id => veyra.fgMotionSource = Number(id) }
}
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index 4e55536f..c34d3ec6 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -1484,6 +1484,7 @@ VPage {
}
VRow {
label: qsTr("补帧运动来源")
+ visible: veyra.fgBackendName !== "vfg"
hint: qsTr("XeSS 默认零运动;FSR 仍有自身的光流计算")
VSeg { objectName: "list-fg-motion"; options: [{id:"0",label:qsTr("零运动")},{id:"1",label:qsTr("光流")}]; current: String(veyra.fgMotionSource); onPicked: id => veyra.fgMotionSource = Number(id) }
}
@@ -1491,10 +1492,29 @@ VPage {
label: qsTr("倍率")
hint: veyra.fgMaxMultiplier + qsTr("X 为上限")
VSeg {
+ visible: veyra.fgBackendName !== "vfg"
options: veyra.fgMultiplierChoices
current: String(veyra.fgMultiplier)
onPicked: id => veyra.fgMultiplier = parseInt(id)
}
+ VSelect {
+ objectName: "list-vfg-multiplier"
+ visible: veyra.fgBackendName === "vfg"
+ options: veyra.fgMultiplierChoices
+ value: String(veyra.fgMultiplier) + "X"
+ onPicked: id => veyra.fgMultiplier = Number(id)
+ }
+ }
+ VRow {
+ label: qsTr("VFG 质量")
+ visible: veyra.fgBackendName === "vfg"
+ hint: qsTr("高质量需要更多处理时间")
+ VSelect {
+ objectName: "list-vfg-quality"
+ options: [{id:"0",label:qsTr("低")},{id:"1",label:qsTr("中")},{id:"2",label:qsTr("高")}]
+ value: options[veyra.vfgQuality].label
+ onPicked: id => veyra.vfgQuality = Number(id)
+ }
}
VRow {
label: qsTr("严格补帧节奏")
diff --git a/scripts/acceptance/vfg-build.py b/scripts/acceptance/vfg-build.py
new file mode 100644
index 00000000..00edddba
--- /dev/null
+++ b/scripts/acceptance/vfg-build.py
@@ -0,0 +1,46 @@
+"""Fresh isolated build, using only the existing product dependency paths."""
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+BASE = Path('E:/项目/Veyra')
+TASK = 'vfg-integration-20261003'
+BUILD, TMP, LOGS = (BASE / part / TASK for part in ('build', 'tmp', 'logs'))
+CONTROL = ROOT / 'scripts/acceptance/vfg-control.py'
+subprocess.run([sys.executable, '-B', str(CONTROL)], check=True)
+for p in (BUILD, TMP, LOGS):
+ p.mkdir(parents=True, exist_ok=True)
+settings = []
+for line in (BASE / 'build/release-2.0.2-20261003/CMakeCache.txt').read_text(encoding='utf8').splitlines():
+ if ':' not in line or '=' not in line or line.startswith(('#', '//')):
+ continue
+ keytype, value = line.split('=', 1)
+ key, kind = keytype.split(':', 1)
+ if kind in ('INTERNAL', 'STATIC'):
+ continue
+ if key.startswith('VEYRA_') or key in ('CMAKE_PREFIX_PATH', 'CMAKE_MAKE_PROGRAM', 'PROTOC', 'PKG_CONFIG_EXECUTABLE'):
+ settings.append(f'set({key} [[{value}]] CACHE {kind} "Existing dependency" FORCE)')
+settings.append('set(VEYRA_CUDA_DRIVER_INCLUDE_DIR [[E:/项目/Veyra/deps/nvidia-vfx-audit-20260921/nvidia/cuda_runtime/include]] CACHE PATH "External CUDA driver headers" FORCE)')
+(TMP / 'dependencies.cmake').write_text('\n'.join(settings), encoding='utf8')
+targets = sys.argv[2:] or ['veyra_qml_ui', 'veyra_xbox_tests', 'veyra_capture_audio_tests', 'veyra_qml_quick_tests', 'veyra_export_probe']
+if any(not t.replace('_', '').isalnum() for t in targets):
+ raise SystemExit('Invalid target')
+cmd = TMP / 'build.cmd'
+cmd.write_text('@echo off\nchcp 65001 >nul\ncall "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat" >nul 2>&1\nif errorlevel 1 exit /b 4\n"%TASK_CMAKE%" --preset x64-release -S "%TASK_ROOT%" -B "%TASK_BUILD%" -C "%TASK_TMP%\\dependencies.cmake"\nif errorlevel 1 exit /b 5\n"%TASK_CMAKE%" --build "%TASK_BUILD%" --parallel 6 --target ' + ' '.join(targets) + '\nexit /b %errorlevel%\n', encoding='ascii')
+env = os.environ.copy()
+env.update(VSLANG='1033', TASK_ROOT=str(ROOT), TASK_BUILD=str(BUILD), TASK_TMP=str(TMP),
+ TEMP=str(TMP), TMP=str(TMP),
+ TASK_CMAKE='C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe')
+log = LOGS / sys.argv[1]
+with log.open('x', encoding='utf8') as output:
+ try:
+ code = subprocess.run(['cmd.exe', '/d', '/c', str(cmd)], cwd=ROOT, env=env,
+ stdout=output, stderr=subprocess.STDOUT, timeout=890).returncode
+ except subprocess.TimeoutExpired:
+ code = 124
+print('BUILD', code, log)
+print('\n'.join(log.read_text(encoding='utf8', errors='replace').splitlines()[-25:]))
+subprocess.run([sys.executable, '-B', str(CONTROL)], check=True)
+raise SystemExit(code)
diff --git a/scripts/acceptance/vfg-clean-smoke.py b/scripts/acceptance/vfg-clean-smoke.py
new file mode 100644
index 00000000..69e00cb9
--- /dev/null
+++ b/scripts/acceptance/vfg-clean-smoke.py
@@ -0,0 +1,69 @@
+"""Final ZIP identity, portable native VFG, and six UI pages in both renderers."""
+import hashlib, json, os, subprocess, sys, zipfile
+from pathlib import Path
+from PIL import Image
+BASE=Path('E:/项目/Veyra');TASK='vfg-integration-20261003';LABEL='2.0.2-vfg-20261003';ROOT=Path(__file__).resolve().parents[2]
+archive=BASE/'test-packages'/TASK/('Veyra-'+LABEL+'-win64-portable.zip')
+verify=BASE/'verify'/TASK;verify.mkdir(parents=True,exist_ok=False)
+with zipfile.ZipFile(archive) as z:
+ for name in z.namelist():(verify/name).resolve().relative_to(verify.resolve())
+ z.extractall(verify)
+app=verify/('Veyra-'+LABEL+'-win64-portable');logs=BASE/'logs'/TASK/'clean-smoke';tmp=BASE/'tmp'/TASK/'clean-smoke'
+for p in (logs,tmp):p.mkdir(parents=True,exist_ok=False)
+manifest=json.loads((app/'package-manifest.json').read_text(encoding='utf8'))
+def verifyFiles():
+ for row in manifest['files']:
+ f=app/row['path'];assert f.stat().st_size==row['size'] and hashlib.sha256(f.read_bytes()).hexdigest()==row['sha256'],row['path']
+verifyFiles()
+assert not any(f.suffix in ('.pyd','.addon64','.pdb','.lib','.whl') for f in app.rglob('*') if f.is_file())
+command=[sys.executable,'-B',str(ROOT/'scripts/acceptance/vfg-ui.py'),'ui-package-final','package',str(app)]
+with (logs/'vfg-native-ui.log').open('xb') as log:subprocess.run(command,cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,timeout=290,check=True)
+source='''import QtQuick
+Item {
+ id: test
+ property var appWindow: Window.window
+ property string evidence: ""
+ property bool expectSoftware: false
+ property int step: 0
+ property bool waiting: false
+ property int ticks: 0
+ property var pages: ["home","pro","node","exp","set","min"]
+ Timer { id: timer; interval: 250; repeat: true; running: true
+ onTriggered: {
+ if(++test.ticks>100){console.error("CLEAN_SMOKE_FAIL timeout");Qt.quit();return}
+ if(!test.evidence.length||test.ticks<8||test.waiting)return
+ if(vySoftwareUi!==test.expectSoftware){console.error("CLEAN_SMOKE_FAIL renderer mismatch");Qt.quit();return}
+ if(test.step>=test.pages.length){console.log("CLEAN_SMOKE_PASS",test.expectSoftware);timer.stop();Qt.quit();return}
+ test.appWindow.page=test.pages[test.step];test.waiting=true;shot.restart()
+ }
+ }
+ Timer { id: shot; interval: 350; onTriggered: {
+ test.appWindow.contentItem.grabToImage(result=>{
+ if(!result.saveToFile(test.evidence+"/"+test.pages[test.step]+".png")){console.error("CLEAN_SMOKE_FAIL screenshot");Qt.quit();return}
+ test.step++;test.waiting=false
+ })
+ } }
+}'''
+qml=tmp/'pages.qml';qml.write_text(source,encoding='utf8');main=app/'qml/Veyra/Main.qml';original=main.read_bytes();results=[]
+try:
+ for mode in ('gpu','software'):
+ evidence=verify/(mode+'-evidence');evidence.mkdir();text=original.decode('utf8');at=text.rfind('}')
+ loader='\nLoader { source: '+json.dumps(qml.as_uri())+'; onLoaded: { item.evidence='+json.dumps(str(evidence))+'; item.expectSoftware='+str(mode=='software').lower()+' } }\n'
+ main.write_text(text[:at]+loader+text[at:],encoding='utf8')
+ env=os.environ.copy();env.update(TEMP=str(tmp),TMP=str(tmp),VEYRA_LOG_FILE=str(logs/(mode+'-app.log')),QT_FORCE_STDERR_LOGGING='1',QML_DISABLE_DISK_CACHE='1')
+ for key in ('QT_QPA_PLATFORM','QT_QUICK_BACKEND','VEYRA_UI_RHI','VEYRA_VFG_RUNTIME'):env.pop(key,None)
+ env['PATH']=os.pathsep.join((env['WINDIR']+'/System32',env['WINDIR'],env['WINDIR']+'/System32/Wbem'))
+ if mode=='gpu':env['VEYRA_UI_RHI']='d3d12'
+ args=['.\\veyra_qml_ui.exe','--size','1280x720','--reduced-motion','--data-dir',str(verify/(mode+'-profile')),'--exit-after','27000']
+ if mode=='software':args.append('--obs-game-capture')
+ with (logs/(mode+'-console.log')).open('xb') as log:code=subprocess.run(args,executable=str(app/'veyra_qml_ui.exe'),cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=40).returncode
+ console=(logs/(mode+'-console.log')).read_text(encoding='utf8',errors='replace');assert code==0 and 'CLEAN_SMOKE_PASS' in console and 'CLEAN_SMOKE_FAIL' not in console,console[-3000:]
+ files=sorted(evidence.glob('*.png'));assert len(files)==6;pixels=[]
+ for file in files:
+ im=Image.open(file).convert('RGBA');pixel=im.getpixel((15,80));assert pixel[3]==255 and max(pixel[:3])<160,(file,pixel)
+ pixels.append({'page':file.stem,'pixel':pixel,'size':im.size})
+ results.append({'renderer':mode,'exit':code,'pages':pixels});print('CLEAN SMOKE PASS',mode,flush=True)
+finally:main.write_bytes(original)
+verifyFiles()
+(logs/'summary.json').write_text(json.dumps({'archive':str(archive),'filesVerified':len(manifest['files']),'portableVfgUi':str(BASE/'logs'/TASK/'ui-package-final/summary.json'),'results':results},indent=2),encoding='utf8')
+print('CLEAN VFG PACKAGE PASS',len(manifest['files']),verify,flush=True)
diff --git a/scripts/acceptance/vfg-combination-tests.py b/scripts/acceptance/vfg-combination-tests.py
new file mode 100644
index 00000000..9daef20c
--- /dev/null
+++ b/scripts/acceptance/vfg-combination-tests.py
@@ -0,0 +1,46 @@
+"""Real shared graph/NVENC edge cases. Each product invocation is bounded to 290s."""
+import json, os, re, subprocess, sys
+from pathlib import Path
+BASE=Path('E:/项目/Veyra');TASK='vfg-integration-20261003';APP=BASE/'tests'/TASK/'app'
+label=sys.argv[1];out=BASE/'tests'/TASK/label;logs=BASE/'logs'/TASK/label;tmp=BASE/'tmp'/TASK/label
+for p in (out,logs,tmp):p.mkdir(parents=True,exist_ok=False)
+env=os.environ.copy();env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),VEYRA_VFG_RUNTIME=str(BASE/'deps/vfg-python-20261003/nvvfx/libs'))
+results=[]
+def fixture(rate):
+ file=out/f'720p{rate}.mp4'
+ with (logs/f'fixture-{rate}.log').open('xb') as log:
+ subprocess.run(['ffmpeg','-v','warning','-n','-f','lavfi','-i',f'testsrc2=size=1280x720:rate={rate}','-f','lavfi','-i','sine=frequency=440:sample_rate=48000','-t',str(8/rate),'-c:v','libx264','-preset','fast','-crf','12','-c:a','aac','-shortest',str(file)],env=env,stdout=log,stderr=subprocess.STDOUT,timeout=90,check=True)
+ return file
+def run(name,source,flags=(),missing=False):
+ child=env.copy()
+ if missing:child['VEYRA_VFG_RUNTIME']=str(tmp/'missing-runtime')
+ file=out/(name+'.mp4');logfile=logs/(name+'.log')
+ with logfile.open('xb') as log:
+ code=subprocess.run(['.\\veyra_vfg_export_probe.exe',str(source),str(file),'8','1',*flags],executable=str(APP/'veyra_vfg_export_probe.exe'),cwd=APP,env=child,stdout=log,stderr=subprocess.STDOUT,timeout=290).returncode
+ text=logfile.read_text(encoding='utf8',errors='replace')
+ if missing:
+ assert code==1 and not file.exists() and '[vfg]' in text and 'ok=0' in text,text[-6000:]
+ elif '--cancel' in flags:
+ assert code==0 and not file.exists() and 'cancelled=1' in text,text[-6000:]
+ else:
+ assert code==0 and 'backend=NVIDIA-VFG' in text and 'quality=1' in text and 'substituting' not in text,text[-6000:]
+ assert not re.search(r'\[ERROR\]|device removed|not alive',text),text[-6000:]
+ probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-count_frames','-show_streams','-of','json',str(file)],env=env,timeout=30))
+ v=next(s for s in probe['streams'] if s['codec_type']=='video')
+ sourceprobe=json.loads(subprocess.check_output(['ffprobe','-v','error','-count_frames','-show_streams','-of','json',str(source)],env=env,timeout=30))
+ sv=next(s for s in sourceprobe['streams'] if s['codec_type']=='video');n,d=map(int,sv['r_frame_rate'].split('/'))
+ on,od=map(int,v['r_frame_rate'].split('/'))
+ assert int(v['nb_read_frames'])==int(sv['nb_read_frames'])*8 and on/od==n/d*8,probe
+ assert abs(float(v['duration'])-int(sv['nb_read_frames'])/(n/d))<1/(on/od),probe
+ if '--sr' in flags:assert (v['width'],v['height'])==(3840,2160) and 'nr=1' in text and 'sr=1' in text,text[-6000:]
+ (logs/(name+'-probe.json')).write_text(json.dumps(probe,indent=2),encoding='utf8')
+ result={'test':name,'exit':code,'status':'pass','log':str(logfile)};results.append(result)
+ (logs/'summary.json').write_text(json.dumps(results,indent=2),encoding='utf8');print(result,flush=True)
+source=BASE/'tests/field-upgrade-20261003/production-rtss/2k30.avi'
+assert source.exists(),source
+run('2k30-avi-nr-highest-sr4k-vfg8',source,('--nr','--sr'))
+for rate in (24,60):run(f'720p{rate}-vfg8',fixture(rate))
+short=BASE/'tests'/TASK/'export-basic-v2/input.mp4'
+run('cancel-native8',short,('--cancel',))
+run('missing-runtime-export8',short,missing=True)
+print('VFG COMBINATIONS PASS',out)
diff --git a/scripts/acceptance/vfg-control.py b/scripts/acceptance/vfg-control.py
new file mode 100644
index 00000000..fbed82a0
--- /dev/null
+++ b/scripts/acceptance/vfg-control.py
@@ -0,0 +1,28 @@
+"""Scope and source/runtime isolation for the explicitly authorized VFG integration."""
+import subprocess
+from pathlib import Path
+ROOT = Path(__file__).resolve().parents[2]
+BASE = '1802f43565e07f3c3040d3fe745ca2e939aab00f'
+def git(*args):
+ return subprocess.check_output(['git', *args], cwd=ROOT).decode('utf8').strip()
+if git('branch', '--show-current') != 'codex/vfg-integration-20261003' or git('rev-parse', 'checkpoint/pre-vfg-integration-20261003^{commit}') != BASE:
+ raise SystemExit('VFG SCOPE FAIL: branch/archive')
+allowed = {'AGENTS.md','CMakeLists.txt','THIRD_PARTY_NOTICES.md','i18n/catalog.json',
+ 'src/pipeline/EnhanceGraph.cpp','include/veyra/pipeline/EnhanceGraph.h',
+ 'src/pipeline/VfgBackend.cpp','include/veyra/pipeline/VfgBackend.h',
+ 'include/veyra/pipeline/FrameBatch.h','include/veyra/diagnostics/FrameMetrics.h',
+ 'include/veyra/engine/EnhancementSettings.h','include/veyra/engine/GraphDescription.h',
+ 'src/engine/EngineController.cpp','src/engine/VideoExportJob.cpp','src/engine/VideoPresenter.cpp',
+ 'include/veyra/engine/ExportWorkerProtocol.h','src/engine/SettingsJson.cpp',
+ 'src/engine/PresetStore.cpp','src/engine/PresetLibrary.cpp',
+ 'include/veyra/engine/PresetLibrary.h','include/veyra/engine/EffectChain.h','src/engine/EffectChain.cpp',
+ 'src/engine/ExportJobManager.cpp',
+ 'include/veyra/ui/QmlPlayerBridge.h','src/ui/QmlPlayerBridge.cpp',
+ 'include/veyra/ui/PlayerUiFacade.h','src/ui/PlayerUiFacade.cpp',
+ 'src/ui/QmlSessionStore.cpp','src/ui/EffectGraphModel.cpp'}
+changed = set(git('diff','--name-only',BASE).splitlines()) | set(git('ls-files','--others','--exclude-standard').splitlines())
+extra = {p for p in changed if p not in allowed and not p.startswith(('docs/','scripts/acceptance/vfg-','tests/','qml/Veyra/'))}
+binary = {p for p in changed if Path(p).suffix.lower() in {'.dll','.exe','.lib','.pdb','.zip','.whl','.f16','.f32','.onnx','.hsaco','.cso','.addon64'}}
+if extra or binary:
+ raise SystemExit('VFG SCOPE FAIL:\n' + '\n'.join(sorted(extra|binary)))
+print('VFG SCOPE PASS:',len(changed),'paths; no SDK/runtime/model assets')
diff --git a/scripts/acceptance/vfg-localize.py b/scripts/acceptance/vfg-localize.py
new file mode 100644
index 00000000..323b4d00
--- /dev/null
+++ b/scripts/acceptance/vfg-localize.py
@@ -0,0 +1,28 @@
+"""Translations for the VFG controls/status and newly collected field-repair status."""
+import json, subprocess, sys
+from pathlib import Path
+ROOT=Path(__file__).resolve().parents[2]
+translations={
+'NVIDIA VFG 未能启用(需要 Ada / Blackwell 显卡、VFG 运行组件和支持的输出格式),已关闭补帧;原因见日志':('NVIDIA VFG could not start (requires an Ada / Blackwell GPU, VFG runtime and a supported output format). Frame generation is off; see the log.','NVIDIA VFG を有効にできませんでした(Ada / Blackwell GPU、VFG ランタイム、対応する出力形式が必要)。フレーム生成はオフです。ログをご確認ください。'),
+'VFG 支持 2X~8X 和低 / 中 / 高质量;6X~8X 为实验档,高倍高质量会增加处理时间':('VFG supports 2X–8X and Low / Medium / High quality. 6X–8X are experimental; higher multipliers and quality take more processing time.','VFG は 2X~8X と低 / 中 / 高品質に対応します。6X~8X は実験設定です。倍率や品質を上げると処理時間が増えます。'),
+'VFG 质量':('VFG quality','VFG 品質'),
+'VFG 质量设置未被接受,原设置保留':('VFG quality was not accepted; the previous setting was kept.','VFG 品質設定が拒否されたため、前の設定を保持しました。'),
+'VFG 需要 NVIDIA Ada / Blackwell 显卡(RTX 40 / 50)':('VFG requires an NVIDIA Ada / Blackwell GPU (RTX 40 / 50).','VFG には NVIDIA Ada / Blackwell GPU(RTX 40 / 50)が必要です。'),
+'Xbox 串流中断({}),正在重连 {}/3…':('Xbox stream interrupted ({}); reconnecting {}/3…','Xbox ストリームが中断されました({})。再接続中 {}/3…'),
+'Xbox 已重新连接':('Xbox reconnected','Xbox に再接続しました'),
+'Xbox 服务结束了串流(':('The Xbox service ended the stream (','Xbox サービスがストリームを終了しました('),
+'Xbox 重连失败:':('Xbox reconnection failed: ','Xbox の再接続に失敗:'),
+'Xbox 重连时 GPU 排空失败':('Could not drain the GPU queue during Xbox reconnection.','Xbox 再接続時に GPU キューの待機処理に失敗しました。'),
+'低':('Low','低'),
+'所选补帧后端的倍率已调整为 %1X':('The selected frame-generation backend adjusted the multiplier to %1X.','選択したフレーム生成方式の倍率を %1X に調整しました。'),
+'未找到 VFG 运行组件,请在组件页核对路径':('VFG runtime components were not found. Check their paths on the Components page.','VFG ランタイムが見つかりません。コンポーネントページでパスをご確認ください。'),
+'预设库 VFG 质量字段损坏':('The preset library has an invalid VFG quality field.','プリセットライブラリの VFG 品質フィールドが破損しています。'),
+'预设库补帧后端无效':('The preset library has an invalid frame-generation backend.','プリセットライブラリのフレーム生成方式が無効です。'),
+'高':('High','高'),
+'高质量需要更多处理时间':('High quality takes more processing time.','高品質にはより多くの処理時間が必要です。')}
+path=ROOT/'i18n/catalog.json';data=json.loads(path.read_text(encoding='utf8'))
+for e in data['entries']:
+ if e['zh'] in translations:e['en'],e['ja']=translations[e['zh']]
+path.write_text(json.dumps(data,ensure_ascii=False,indent=1)+'\n',encoding='utf8')
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/i18n/to_traditional.py')],check=True)
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/i18n/extract.py'),'--check'],check=True)
diff --git a/scripts/acceptance/vfg-native-tests.py b/scripts/acceptance/vfg-native-tests.py
new file mode 100644
index 00000000..28bf0467
--- /dev/null
+++ b/scripts/acceptance/vfg-native-tests.py
@@ -0,0 +1,17 @@
+"""Bounded real-GPU native SDK/interop checks, isolated logs/TEMP on E:."""
+import json, os, subprocess, sys
+from pathlib import Path
+BASE=Path('E:/项目/Veyra');TASK='vfg-integration-20261003'
+logs,tests,tmp=(BASE/p/TASK for p in ('logs','tests','tmp'))
+for p in (logs,tests,tmp):p.mkdir(parents=True,exist_ok=True)
+label=sys.argv[1] if len(sys.argv)>1 else 'native-v1'
+if not label.replace('-','').isalnum():raise SystemExit('invalid label')
+env=os.environ.copy();env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'))
+command=[str(BASE/'build'/TASK/'veyra_vfg_gpu_tests.exe'),str(BASE/'deps/vfg-python-20261003/nvvfx/libs'),*(sys.argv[2:] or ['1280','720'])]
+with (logs/(label+'.log')).open('x',encoding='utf8') as out:
+ try:code=subprocess.run(command,cwd=tests,env=env,stdout=out,stderr=subprocess.STDOUT,timeout=290).returncode
+ except subprocess.TimeoutExpired:code=124
+(logs/(label+'.json')).write_text(json.dumps({'command':command,'returncode':code,'timeoutSeconds':290,'log':str(logs/(label+'.log'))},ensure_ascii=False,indent=2),encoding='utf8')
+print('NATIVE GPU TEST',code,logs/(label+'.log'))
+print('\n'.join((logs/(label+'.log')).read_text(encoding='utf8',errors='replace').splitlines()[-18:]))
+raise SystemExit(code)
diff --git a/scripts/acceptance/vfg-package.py b/scripts/acceptance/vfg-package.py
new file mode 100644
index 00000000..356d6251
--- /dev/null
+++ b/scripts/acceptance/vfg-package.py
@@ -0,0 +1,76 @@
+"""Local VFG + field-fix candidate; official runtime separate from Veyra source."""
+import hashlib, importlib.util, json, os, shutil, subprocess, sys, zipfile
+from pathlib import Path
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-integration-20261003';LABEL='2.0.2-vfg-20261003'
+OUTPUT=BASE/'test-packages'/TASK;STAGE=OUTPUT/('Veyra-'+LABEL+'-win64-portable');LOGS=BASE/'logs'/TASK
+SDK=BASE/'deps/vfg-python-20261003';WHEEL=BASE/'downloads/vfg-research-20261003/nvidia_vfx-0.2.0.0-cp311-cp311-win_amd64.whl'
+NAMES=('cudart64_12.dll','nppc64_12.dll','nppial64_12.dll','nppicc64_12.dll','nppidei64_12.dll','nppif64_12.dll','nppig64_12.dll','nppim64_12.dll','nppist64_12.dll','nppitc64_12.dll','NVCVImage.dll','nvngxruntime.dll','NVVideoEffects.dll','nvVFXVideoFrameGeneration.dll')
+spec=importlib.util.spec_from_file_location('qml_package',ROOT/'scripts/package-qml-release.py');pkg=importlib.util.module_from_spec(spec);spec.loader.exec_module(pkg)
+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/vfg-control.py')],check=True)
+mode=sys.argv[1]
+if mode=='stage':
+ assert not subprocess.check_output(['git','status','--porcelain'],cwd=ROOT).strip(),'Commit the validated source before staging'
+ assert pkg.digest(WHEEL)=='5aaf6a42bc6b6dbbf52fcb714194c994a6893cbbf7ada38bc2165a1f83e4a6fc'
+ OUTPUT.mkdir(parents=True,exist_ok=True)
+ command=[sys.executable,'-B',str(ROOT/'scripts/package-qml-release.py'),'--build',str(BASE/'build'/TASK),'--runtime-source',str(BASE/'releases/2.0.2/Veyra-2.0.2-win64-portable'),'--legacy-licenses',str(BASE/'releases/2.0.2/Veyra-2.0.2-win64-portable/licenses'),'--qt','C:/veyra-deps/qt-veyra/6.8.3/msvc2022_64','--qt-licenses',str(BASE/'deps/qt-licenses-6.8.3'),'--output',str(OUTPUT),'--label',LABEL,'--no-archive']
+ with (LOGS/'package-stage.log').open('xb') as log:subprocess.run(command,cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,timeout=290,check=True)
+ shutil.copytree(BASE/'deps/veyra-amd-nr-039-20261003',STAGE/'runtime/amd-nr')
+ target=STAGE/'runtime/nvidia/vfg';target.mkdir(parents=True)
+ records=[]
+ for name in NAMES:
+ source=SDK/'nvvfx/libs'/name;shutil.copy2(source,target/name)
+ records.append({'path':'runtime/nvidia/vfg/'+name,'name':name,'source':str(source),'size':source.stat().st_size,'sha256':pkg.digest(source),'experimental':True,'removable':True,'modified':False})
+ identityFile=BASE/'tmp'/TASK/'vfg-identities.json';identityFile.write_text(json.dumps(records,ensure_ascii=False),encoding='utf8')
+ env=os.environ.copy();env.pop('PSModulePath',None);env['VEYRA_VFG_IDENTITIES']=str(identityFile)
+ script=r'''$ErrorActionPreference='Stop'; @(Get-Content -LiteralPath $env:VEYRA_VFG_IDENTITIES -Encoding UTF8 -Raw | ConvertFrom-Json) | ForEach-Object { $s=Get-AuthenticodeSignature -LiteralPath $_.source; $v=[System.Diagnostics.FileVersionInfo]::GetVersionInfo($_.source); [PSCustomObject]@{name=$_.name;version=$v.FileVersion;signature=[string]$s.Status;signer=$s.SignerCertificate.Subject} } | ConvertTo-Json -Depth 4'''
+ identities=json.loads(subprocess.check_output(['powershell','-NoProfile','-NonInteractive','-Command',script],env=env,timeout=90).decode('utf8-sig'))
+ for r in records:
+ identity=next(x for x in identities if x['name']==r['name']);assert identity['signature']=='Valid' and 'NVIDIA' in identity['signer'],identity
+ r.update(identity);r.pop('source')
+ vfg={'schema':1,'localOnly':True,'runtime':'NVIDIA Video Effects SDK 1.3.0 / nvidia-vfx 0.2.0.0','sourceWheel':WHEEL.name,'sourceWheelBytes':WHEEL.stat().st_size,'sourceWheelSha256':pkg.digest(WHEEL),'license':'licenses/nvidia-vfg','publicDistributionAudited':False,'pythonRequired':False,'files':records}
+ (STAGE/'vfg-runtime-manifest.json').write_text(json.dumps(vfg,ensure_ascii=False,indent=2),encoding='utf8')
+ shutil.copytree(SDK/'nvidia_vfx-0.2.0.0.dist-info/licenses/packaging',STAGE/'licenses/nvidia-vfg')
+ samples=STAGE/'licenses/vfg-samples';samples.mkdir();shutil.copy2(BASE/'deps/vfg-samples-20261003/LICENSE',samples/'MIT.txt')
+ (STAGE/'LOCAL-VFG.md').write_text('''# Veyra VFG 本地候选
+
+双击 veyra_qml_ui.exe。专业页添加补帧,选择 NVIDIA VFG,再选倍率和质量;节点模式同样可用。
+包含 2X / 3X / 4X / 5X / 6X / 7X / 8X 和低 / 中 / 高三档,默认中档。
+预览、视频导出、预设与重启保存均接入原生 VFG。运行组件已放在 runtime/nvidia/vfg,无需 Python。
+RTX 40 / 50 是官方 Windows 支持范围;本机仅 RTX 5070、616.56 已测试。高倍率为实验选项。
+高档 8X 运算成本较高,实时播放可能降档或跳过预览帧;离线导出完整处理,不丢源帧。
+软件显示的是提交帧率。它不等于屏幕实际显示帧率,也不证明端到端延迟降低。
+本包还保留 Xbox 音频/重连、码率编辑、RTSS 背景、NVIDIA App 误检测修复和 AMD NR 0.39。
+Xbox 真机有声/长期稳定、AMD RX9000 推理、RTX40、616.92、HDR色度专项仍未实机验收。
+这是本地实验候选,未合并 main、未推送、未公开发布。第三方组件按独立 manifest 与许可记录。
+详见 docs/VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md 和 docs/FIELD_UPGRADE_ACCEPTANCE_2026-10-03.md。
+''',encoding='utf8')
+ for name in ('VFG_INTEGRATION_EXECUTION_2026-10-03.md','VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md','VFG_RESEARCH_AND_INTEGRATION_PLAN_2026-10-03.md','FIELD_UPGRADE_ACCEPTANCE_2026-10-03.md','AMD_NR_INTEGRATION_2026-10-03.md'):shutil.copy2(ROOT/'docs'/name,STAGE/'docs'/name)
+ print('LOCAL VFG CANDIDATE STAGED',STAGE,flush=True)
+elif mode=='archive':
+ assert STAGE.exists()
+ # Restore source documents before hashing; a smoke test restores its QML loader.
+ for name in ('VFG_INTEGRATION_EXECUTION_2026-10-03.md','VFG_INTEGRATION_ACCEPTANCE_2026-10-03.md'):shutil.copy2(ROOT/'docs'/name,STAGE/'docs'/name)
+ manifest=json.loads((STAGE/'package-manifest.json').read_text(encoding='utf8'));records=[]
+ for file in sorted(STAGE.rglob('*')):
+ if not file.is_file():continue
+ name=file.relative_to(STAGE).as_posix()
+ if name=='package-manifest.json':continue
+ pkg.validate_payload(name)
+ records.append({'path':name,'size':file.stat().st_size,'sha256':pkg.digest(file)})
+ assert not any('fake' in r['path'].lower() or r['path'].endswith(('.pyd','.addon64','.pdb','.lib','.whl')) for r in records)
+ manifest.update(files=records,localOnly=True,vfgProvenance='vfg-runtime-manifest.json',amdProvenance='runtime/amd-nr/amd-nr-local-manifest.json',rtx40HardwareVerified=False,amdInferenceVerified=False,xboxHardwareVerified=False)
+ (STAGE/'package-manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf8')
+ source=OUTPUT/('Veyra-'+LABEL+'-source.zip')
+ # The payload's source commit is the implementation checkpoint; later docs
+ # commits contain acceptance evidence but cannot silently repin its binaries.
+ subprocess.run(['git','archive','--format=zip','--output',str(source),manifest['baseCommit']],cwd=ROOT,timeout=60,check=True)
+ source.with_suffix('.zip.sha256').write_text(pkg.digest(source)+' '+source.name+'\n',encoding='ascii')
+ archive=Path(str(STAGE)+'.zip')
+ with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED,compresslevel=5) as z:
+ for file in sorted(STAGE.rglob('*')):
+ if file.is_file():z.write(file,STAGE.name+'/'+file.relative_to(STAGE).as_posix())
+ audit=pkg.verify_zip(archive);audit.update(bytes=archive.stat().st_size,sourceCommit=manifest['baseCommit'],appSha256=pkg.digest(STAGE/'veyra_qml_ui.exe'),sourceZip=str(source),sourceSha256=pkg.digest(source))
+ archive.with_suffix('.zip.sha256').write_text(audit['sha256']+' '+archive.name+'\n',encoding='ascii')
+ (LOGS/'candidate-package-audit.json').write_text(json.dumps(audit,indent=2),encoding='utf8')
+ print('LOCAL VFG CANDIDATE ARCHIVE PASS',json.dumps(audit),flush=True)
+else:raise SystemExit('stage or archive')
diff --git a/scripts/acceptance/vfg-product-tests.py b/scripts/acceptance/vfg-product-tests.py
new file mode 100644
index 00000000..91ae3482
--- /dev/null
+++ b/scripts/acceptance/vfg-product-tests.py
@@ -0,0 +1,54 @@
+"""Bounded real product regressions; SDK and all test artifacts remain outside Git."""
+import json, os, re, shutil, subprocess, sys
+from pathlib import Path
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-integration-20261003'
+BUILD=BASE/'build'/TASK;APP=BASE/'tests'/TASK/'app';QT=Path('C:/veyra-deps/qt-veyra/6.8.3/msvc2022_64')
+label=sys.argv[1];mode=sys.argv[2] if len(sys.argv)>2 else 'unit'
+if not label.replace('-','').isalnum():raise SystemExit('invalid label')
+out=BASE/'tests'/TASK/label;logs=BASE/'logs'/TASK/label;tmp=BASE/'tmp'/TASK/label
+for p in (out,logs,tmp):p.mkdir(parents=True,exist_ok=False)
+if not APP.exists():shutil.copytree(BASE/'releases/2.0.2/Veyra-2.0.2-win64-portable',APP)
+names=['veyra_qml_ui','veyra_vfg_export_probe','veyra_vfg_settings_tests','veyra_preset_library_tests','veyra_repair_preset_tests','veyra_repair_contract_tests','veyra_effect_chain_tests','veyra_qml_quick_tests']
+for name in names:shutil.copy2(BUILD/(name+'.exe'),APP/(name+'.exe'))
+shutil.copytree(BUILD/'shaders',APP/'shaders',dirs_exist_ok=True)
+shutil.copytree(ROOT/'qml',APP/'qml',dirs_exist_ok=True)
+shutil.copytree(ROOT/'tests/qml/quick',APP/'qml-tests',dirs_exist_ok=True)
+for name in ('Qt6Test.dll','Qt6QuickTest.dll'):shutil.copy2(QT/'bin'/name,APP/name)
+env=os.environ.copy();env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),
+ VEYRA_VFG_RUNTIME=str(BASE/'deps/vfg-python-20261003/nvvfx/libs'),QML_DISABLE_DISK_CACHE='1',QT_FORCE_STDERR_LOGGING='1')
+results=[]
+def run(name,exe,args=(),overrides=None):
+ child=env.copy();child.update(overrides or {});child['VEYRA_LOG_FILE']=str(logs/(name+'-engine.log'))
+ with (logs/(name+'.log')).open('xb') as log:
+ try:code=subprocess.run(['.\\'+exe,*map(str,args)],executable=str(APP/exe),cwd=APP,env=child,stdout=log,stderr=subprocess.STDOUT,timeout=290).returncode
+ except subprocess.TimeoutExpired:code=124
+ result={'test':name,'exit':code,'log':str(logs/(name+'.log'))};results.append(result)
+ (logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
+ print(result,flush=True)
+ if code:raise SystemExit('TEST FAILED '+name+'\n'+(logs/(name+'.log')).read_text(encoding='utf8',errors='replace')[-5000:])
+ return result
+if mode=='unit':
+ for name in names[2:7]:run(name,name+'.exe',[out/'settings'] if name=='veyra_vfg_settings_tests' else [out/'repair-presets.txt'] if name=='veyra_repair_preset_tests' else [])
+ run('qml-quick','veyra_qml_quick_tests.exe',['-input',APP/'qml-tests'],{'QT_QPA_PLATFORM':'offscreen','QT_QUICK_BACKEND':'software','QT_QUICK_CONTROLS_STYLE':'Basic','QT_QPA_PLATFORM_PLUGIN_PATH':str(QT/'plugins/platforms'),'PATH':str(QT/'bin')+os.pathsep+env['PATH']})
+elif mode=='stage':pass
+elif mode=='export':
+ rate=int(sys.argv[3]) if len(sys.argv)>3 else 30;width=int(sys.argv[4]) if len(sys.argv)>4 else 1280;height=width*9//16
+ media=out/'input.mp4'
+ with (logs/'fixture.log').open('xb') as log:subprocess.run(['ffmpeg','-v','warning','-n','-f','lavfi','-i',f'testsrc2=size={width}x{height}:rate={rate}','-f','lavfi','-i','sine=frequency=440:sample_rate=48000','-t',str(8/rate),'-c:v','libx264','-preset','fast','-crf','12','-c:a','aac','-shortest',str(media)],env=env,stdout=log,stderr=subprocess.STDOUT,timeout=90,check=True)
+ cases=[(m,q) for q in range(3) for m in range(2,9)] if len(sys.argv)<6 else [(int(sys.argv[5]),int(sys.argv[6]))]
+ flags=sys.argv[7:]
+ for m,q in cases:
+ name=f'{width}p-{rate}fps-{m}x-q{q}';file=out/(name+'.mp4')
+ result=run(name,'veyra_vfg_export_probe.exe',[media,file,m,q,*flags])
+ probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-count_frames','-show_streams','-show_format','-of','json',str(file)],env=env,timeout=30))
+ video=next(s for s in probe['streams'] if s['codec_type']=='video');audio=next(s for s in probe['streams'] if s['codec_type']=='audio')
+ assert video['codec_name']=='hevc' and int(video['nb_read_frames'])==8*m,probe
+ num,den=map(int,video['avg_frame_rate'].split('/'));assert abs(num/den-rate*m)<rate*m*0.00001,probe
+ num,den=map(int,video['r_frame_rate'].split('/'));assert num/den==rate*m,probe
+ assert abs(float(video['duration'])-8/rate)<1/(rate*m) and abs(float(audio['duration'])-8/rate)<0.06,probe
+ engine=(logs/(name+'.log')).read_text(encoding='utf8',errors='replace')
+ assert 'backend=NVIDIA-VFG' in engine and 'nvenc' in engine.lower() and 'substituting' not in engine
+ assert not re.search(r'\[ERROR\]|device removed|not alive',engine),engine[-5000:]
+ result['probe']=probe;(logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
+else:raise SystemExit('unknown mode')
+print('VFG PRODUCT PASS',mode,APP,flush=True)
diff --git a/scripts/acceptance/vfg-ui.py b/scripts/acceptance/vfg-ui.py
new file mode 100644
index 00000000..f49ba5e0
--- /dev/null
+++ b/scripts/acceptance/vfg-ui.py
@@ -0,0 +1,54 @@
+"""Real GUI hot switches, persistence and process-isolated VFG export; each run <300s."""
+import json, os, shutil, subprocess, sys
+from pathlib import Path
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='vfg-integration-20261003'
+APP=BASE/'tests'/TASK/'app';BUILD=BASE/'build'/TASK
+FFPROBE=shutil.which('ffprobe');assert FFPROBE
+label=sys.argv[1];out=BASE/'tests'/TASK/label;logs=BASE/'logs'/TASK/label;tmp=BASE/'tmp'/TASK/label
+packaged=len(sys.argv)>2 and sys.argv[2]=='package'
+if packaged:
+ APP=Path(sys.argv[3]).resolve();assert APP.is_relative_to(BASE.resolve()) and (APP/'vfg-runtime-manifest.json').is_file()
+for p in (out,logs,tmp):p.mkdir(parents=True,exist_ok=False)
+env=os.environ.copy();env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),VEYRA_VFG_RUNTIME=str(BASE/'deps/vfg-python-20261003/nvvfx/libs'),QT_FORCE_STDERR_LOGGING='1',QML_DISABLE_DISK_CACHE='1')
+for key in ('QT_QPA_PLATFORM','QT_QUICK_BACKEND','VEYRA_UI_RHI'):env.pop(key,None)
+if packaged:
+ env.pop('VEYRA_VFG_RUNTIME',None)
+ windir=Path(env['WINDIR']);env['PATH']=os.pathsep.join(map(str,(windir/'System32',windir,windir/'System32/Wbem')))
+else:
+ for name in ('veyra_qml_ui.exe',):shutil.copy2(BUILD/name,APP/name)
+ shutil.copytree(ROOT/'qml',APP/'qml',dirs_exist_ok=True)
+media=out/'preview-720p30.mp4';short=BASE/'tests'/TASK/'export-basic-v2/input.mp4'
+previous=BASE/'tests'/TASK/'ui-v1/preview-720p30.mp4'
+if previous.exists() and label!='ui-v1':media=previous
+else:
+ with (logs/'fixture.log').open('xb') as log:subprocess.run(['ffmpeg','-v','warning','-n','-f','lavfi','-i','testsrc2=size=1280x720:rate=30','-t','90','-c:v','libx264','-preset','ultrafast','-crf','28','-an',str(media)],env=env,stdout=log,stderr=subprocess.STDOUT,timeout=90,check=True)
+profile=out/'profile';outputs=out/'outputs';outputs.mkdir()
+phases=('run','restore','missing')
+if len(sys.argv)>2 and not packaged:
+ assert sys.argv[2]=='missing-only'
+ phases=('missing',)
+ shutil.copytree(BASE/'tests'/TASK/'ui-v2/profile',profile)
+main=APP/'qml/Veyra/Main.qml';original=main.read_bytes();source=original.decode('utf8');at=source.rfind('}')
+results=[]
+try:
+ for phase in phases:
+ child=env.copy();child['VEYRA_LOG_FILE']=str(logs/(phase+'-engine.log'))
+ data=profile
+ if phase=='missing':
+ data=out/'missing-profile';shutil.copytree(profile,data);child['VEYRA_VFG_RUNTIME']=str(tmp/'missing-runtime')
+ loader='\nLoader { source: '+json.dumps((ROOT/'scripts/acceptance/vfg-ui.qml').as_uri())+'; onLoaded: { item.media='+json.dumps(str(media))+'; item.shortMedia='+json.dumps(str(short))+'; item.evidence='+json.dumps(str(out))+'; item.phase='+json.dumps(phase)+' } }\n'
+ main.write_text(source[:at]+loader+source[at:],encoding='utf8')
+ with (logs/(phase+'.log')).open('xb') as log:
+ code=subprocess.run(['.\\veyra_qml_ui.exe','--page','pro','--size','1280x900','--reduced-motion','--export-out',str(outputs),'--data-dir',str(data),'--exit-after','240000'],executable=str(APP/'veyra_qml_ui.exe'),cwd=APP,env=child,stdout=log,stderr=subprocess.STDOUT,timeout=270).returncode
+ text=(logs/(phase+'.log')).read_text(encoding='utf8',errors='replace')
+ marker={'run':'VFG_UI_PASS','restore':'VFG_UI_RESTORE_PASS','missing':'VFG_UI_MISSING_PASS'}[phase]
+ assert code==0 and marker in text and 'VFG_UI_FAIL' not in text,text[-5000:]
+ results.append({'phase':phase,'returncode':code,'marker':marker});print(results[-1],flush=True)
+finally:main.write_bytes(original)
+if 'run' in phases:
+ files=list(outputs.glob('*.mp4'));assert len(files)==1,files
+ probe=json.loads(subprocess.check_output([FFPROBE,'-v','error','-count_frames','-show_streams','-of','json',str(files[0])],env=env,timeout=30))
+ v=next(s for s in probe['streams'] if s['codec_type']=='video');assert int(v['nb_read_frames'])==64 and v['r_frame_rate']=='240/1',probe
+ results.append({'export':str(files[0]),'probe':probe})
+(logs/'summary.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
+print('VFG UI PRODUCT PASS',out)
diff --git a/scripts/acceptance/vfg-ui.qml b/scripts/acceptance/vfg-ui.qml
new file mode 100644
index 00000000..d78f44f7
--- /dev/null
+++ b/scripts/acceptance/vfg-ui.qml
@@ -0,0 +1,125 @@
+// Disposable staging loader using the actual bridge, engine and export worker.
+import QtQuick
+Item {
+ id: test
+ property var appWindow: Window.window
+ property string media: ""
+ property string shortMedia: ""
+ property string evidence: ""
+ property string phase: "run"
+ property int step: 0
+ property int ticks: 0
+ property int waited: 0
+ property int current: 0
+ property real beforePosition: 0
+ property var cases: [{m:2,q:1},{m:3,q:1},{m:4,q:1},{m:5,q:1},{m:6,q:1},{m:7,q:1},{m:8,q:1},{m:8,q:0},{m:8,q:2}]
+ function check(ok,why){if(!ok){console.error("VFG_UI_FAIL",phase,step,why);timer.stop();Qt.quit();throw new Error(why)}}
+ function next(n){step=n;waited=0}
+ function find(item,name){if(item.objectName===name)return item;for(const child of item.children||[]){const r=find(child,name);if(r)return r}return null}
+ function findNodePage(item){if(typeof item.selectId==="function")return item;for(const child of item.children||[]){const r=findNodePage(child);if(r)return r}return null}
+ function preset(name){return veyra.presets.findIndex(x=>x.name===name)}
+ function startCase(){const c=cases[current];beforePosition=veyra.position;veyra.fgMultiplier=c.m;veyra.vfgQuality=c.q;next(2)}
+ Connections {target: veyra;function onNotice(message,error){console.log("VFG_NOTICE",message,error)}}
+ Timer {id: timer;interval: 200;running: true;repeat: true
+ onTriggered: {try {
+ if(++test.ticks>1150)test.check(false,"230-second deadline");++test.waited
+ if(!test.media.length)return
+ if(test.step===0){
+ if(test.waited<10)return
+ test.check(veyra.fgBackendChoices.some(x=>x.id==="vfg"),"VFG backend menu")
+ if(test.phase==="restore"){
+ test.check(veyra.nodeMode===0&&veyra.fgBackendName==="vfg"&&veyra.fgMultiplier===8&&veyra.vfgQuality===1,"list restart preserves 8X Medium")
+ test.check(test.preset("VFG List 8 Medium")>=0&&test.preset("VFG Node 8 High")>=0,"preset restart")
+ veyra.nodeMode=1;test.check(veyra.fgBackendName==="vfg"&&veyra.fgMultiplier===8&&veyra.vfgQuality===2,"node restart preserves independent 8X High")
+ test.check(veyra.applyPresetIndex(test.preset("VFG Node 8 High")),"node VFG preset applies")
+ veyra.nodeMode=0;test.check(veyra.vfgQuality===1,"switch back restores list Medium")
+ console.log("VFG_UI_RESTORE_PASS");timer.stop();Qt.quit();return
+ }
+ veyra.muted=true;veyra.nrEnabled=false;veyra.srEnabled=false
+ test.appWindow.page="pro"
+ if(test.phase==="missing"){
+ veyra.openPath(test.media);test.next(20);return
+ }
+ test.check(veyra.addEffect("vfg-fg")>=0,"add VFG list stage")
+ const factor=test.find(test.appWindow.contentItem,"list-vfg-multiplier")
+ const quality=test.find(test.appWindow.contentItem,"list-vfg-quality")
+ test.check(factor&&quality,"list controls created")
+ test.check(factor.options.map(x=>x.id).join(",")==="2,3,4,5,6,7,8","all seven multiplier controls")
+ for(let q=0;q<3;++q){quality.picked(String(q));test.check(veyra.vfgQuality===q,"quality control commits "+q)}
+ for(let m=2;m<=8;++m){factor.picked(String(m));test.check(veyra.fgMultiplier===m,"multiplier control commits "+m)}
+ veyra.vfgQuality=1;veyra.fgMultiplier=2;veyra.openPath(test.media);test.next(1)
+ }else if(test.step===1){
+ if(!veyra.running||!veyra.hasSource||veyra.applying)return
+ test.startCase()
+ }else if(test.step===2){
+ if(test.waited<12||veyra.applying)return
+ const c=test.cases[test.current]
+ test.check(veyra.running&&veyra.fgActive&&veyra.fgBackendName==="vfg","VFG inactive "+veyra.statusText)
+ test.check(veyra.fgMultiplier===c.m&&veyra.vfgQuality===c.q,"hot settings rollback")
+ test.check(veyra.position>test.beforePosition+0.3,"playback clock stopped")
+ test.check(veyra.runStatusDetail.indexOf("NVIDIA VFG")>=0,"actual running backend label")
+ console.log("VFG_UI_CASE",c.m,c.q,"submitFps",veyra.submitFps,"detail",veyra.runStatusDetail)
+ if(++test.current<test.cases.length){test.startCase();return}
+ veyra.vfgQuality=1;test.next(3)
+ }else if(test.step===3){
+ if(test.waited<8||veyra.applying)return
+ test.check(veyra.savePresetAs("VFG List 8 Medium",15,false),"save list VFG preset")
+ test.appWindow.contentItem.grabToImage(r=>r.saveToFile(test.evidence+"/vfg-list.png"))
+ veyra.fgBackendName="dlss";veyra.fgMultiplier=6;test.next(15)
+ }else if(test.step===15){
+ if(test.waited<12||veyra.applying)return
+ test.check(veyra.fgActive&&veyra.fgBackendName==="dlss"&&veyra.fgMultiplier===6,"legacy DLSS 6X works after VFG 8X")
+ console.log("VFG_UI_DLSS6_PASS",veyra.runStatusDetail)
+ veyra.fgBackendName="vfg";veyra.fgMultiplier=8;test.next(16)
+ }else if(test.step===16){
+ if(test.waited<12||veyra.applying)return
+ test.check(veyra.fgActive&&veyra.fgBackendName==="vfg"&&veyra.fgMultiplier===8,"VFG 8X restores after DLSS 6X")
+ veyra.togglePlayPause();test.next(4)
+ }else if(test.step===4){
+ if(!veyra.paused)return
+ veyra.seekTo(2);test.appWindow.width=1160;test.appWindow.height=740;test.next(5)
+ }else if(test.step===5){
+ if(test.waited<10)return
+ test.check(veyra.paused&&veyra.position>=1.9,"paused seek")
+ veyra.togglePlayPause();test.next(6)
+ }else if(test.step===6){
+ if(test.waited<10||veyra.applying)return
+ test.check(veyra.running&&!veyra.paused&&veyra.position>2.5,"resume after seek/resize")
+ veyra.nodeMode=1;test.appWindow.page="node";test.check(veyra.addEffect("vfg-fg")>=0,"add VFG node")
+ veyra.fgMultiplier=8;veyra.vfgQuality=2;test.next(7)
+ }else if(test.step===7){
+ if(test.waited<10||veyra.applying)return
+ test.check(veyra.chainValid&&veyra.fgActive&&veyra.vfgQuality===2,"node VFG running")
+ test.check(veyra.effectCatalog.some(x=>x.id==="vfg-fg"),"node add menu includes VFG")
+ const page=test.findNodePage(test.appWindow.contentItem),fg=veyra.chain.find(x=>x.type==="frame-generation")
+ if(page&&fg)page.selectId(fg.id)
+ test.check(veyra.savePresetAs("VFG Node 8 High",15,true),"save node VFG preset")
+ test.appWindow.contentItem.grabToImage(r=>r.saveToFile(test.evidence+"/vfg-node.png"))
+ veyra.stopPlayback();test.next(8)
+ }else if(test.step===8){
+ if(test.waited<8||veyra.hasSource)return
+ veyra.nodeMode=0;test.appWindow.page="pro"
+ test.check(veyra.fgMultiplier===8&&veyra.vfgQuality===1,"list state survives node High")
+ veyra.addExportFiles([test.shortMedia]);veyra.exportCompletionSound=false;veyra.exportHevc=true;veyra.exportSrTargetIndex=-1;veyra.exportRateControl=1;veyra.exportBitrateMbps=18
+ test.next(9)
+ }else if(test.step===9){
+ if(veyra.exportReadyCount!==1)return
+ veyra.startExport();test.check(veyra.exportRunning,"VFG worker started")
+ veyra.vfgQuality=0;veyra.fgMultiplier=2;test.next(10)
+ }else if(test.step===10){
+ if(veyra.exportRunning)return
+ test.check(veyra.exportItems.filter(x=>x.state==="done").length===1,"native VFG worker export")
+ veyra.fgMultiplier=8;veyra.vfgQuality=1;test.next(11)
+ }else if(test.step===11){
+ if(test.waited<10)return
+ console.log("VFG_UI_PASS");timer.stop();Qt.quit()
+ }else if(test.step===20){
+ if(test.waited<20||veyra.applying||!veyra.running)return
+ console.log("VFG_UI_MISSING_STATE",JSON.stringify({active:veyra.fgActive,enabled:veyra.fgEnabled,position:veyra.position,backend:veyra.fgBackendName,multiplier:veyra.fgMultiplier,quality:veyra.vfgQuality,warning:veyra.backendWarning}))
+ test.check(!veyra.fgActive&&!veyra.fgEnabled&&veyra.position>0.4,"missing runtime keeps base playback")
+ test.check(veyra.backendWarning.indexOf("VFG")>=0,"missing runtime reports exact failed backend")
+ console.log("VFG_UI_MISSING_PASS",veyra.backendWarning);timer.stop();Qt.quit()
+ }
+ }catch(e){console.error("VFG_UI_FAIL",e.message);timer.stop();Qt.quit()}}
+ }
+}
diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cpp
index 6591f830..a1d5340a 100644
--- a/src/engine/EffectChain.cpp
+++ b/src/engine/EffectChain.cpp
@@ -505,6 +505,7 @@ ChainGlobalSettings ChainGlobalSettings::capture(const EnhancementSettings& s) {
ChainGlobalSettings c;
c.srTarget = s.srTarget; c.videoSrQuality = s.videoSrQuality;
c.fgBackend = s.frameGenerationBackend; c.flow = s.flow;
+ c.vfgQuality=s.vfgQuality;
c.opticalFlowBackend = s.opticalFlowBackend; c.amdFlowHalfResolution = s.amdFlowHalfResolution;
c.nrPolicy = s.nrPolicy;
c.hdrOutputMode=s.hdrOutputMode;c.fgMotion=s.fgMotion;c.srMotion=s.srMotion;c.nrMotion=s.nrMotion;
@@ -516,6 +517,7 @@ void ChainGlobalSettings::apply(EnhancementSettings& s) const {
s.hdrOutputMode=hdrOutputMode;s.fgMotion=fgMotion;s.srMotion=srMotion;s.nrMotion=nrMotion;
s.srTarget = srTarget; s.videoSrQuality = videoSrQuality;
s.frameGenerationBackend = fgBackend; s.flow = flow;
+ s.vfgQuality=vfgQuality;
s.opticalFlowBackend = opticalFlowBackend; s.amdFlowHalfResolution = amdFlowHalfResolution;
}
@@ -534,7 +536,7 @@ void ChainConfiguration::apply(EnhancementSettings& s) const {
bool ChainConfiguration::operator==(const ChainConfiguration& other) const {
return chain == other.chain && srTarget == other.srTarget && videoSrQuality == other.videoSrQuality &&
- fgBackend == other.fgBackend && flow == other.flow && opticalFlowBackend == other.opticalFlowBackend &&
+ fgBackend == other.fgBackend && vfgQuality == other.vfgQuality && flow == other.flow && opticalFlowBackend == other.opticalFlowBackend &&
amdFlowHalfResolution == other.amdFlowHalfResolution && nrPolicy == other.nrPolicy &&
selectedNr == other.selectedNr && selectedColour == other.selectedColour &&
((!editor && !other.editor) || (editor && other.editor && *editor == *other.editor));
@@ -561,7 +563,7 @@ bool ChainConfiguration::valid() const {
if (!parameters->validate().empty()) return false;
}
}
- if (!validateChain(chain).accepted || chain.fgMultiplier < 2 || chain.fgMultiplier > 6 ||
+ if (!validateChain(chain).accepted || chain.fgMultiplier < 2 || chain.fgMultiplier > (fgBackend==FrameGenerationBackend::Vfg?8u:6u) ||
!pipeline::validNrSizePolicy(nrPolicy)) return false;
const auto& selectable = editor ? editor->nodes : chain;
const auto selectionOk = [&](int index, EffectType type) {
@@ -625,6 +627,7 @@ bool requiresGraphRebuild(const EnhancementSettings& previous, const Enhancement
if (previous.nrPolicy != next.nrPolicy) return true;
if (previous.srTarget != next.srTarget) return true;
if (previous.frameGenerationBackend != next.frameGenerationBackend) return true;
+ if (previous.vfgQuality != next.vfgQuality) return true;
if (previous.opticalFlowBackend != next.opticalFlowBackend) return true;
if (previous.amdFlowHalfResolution != next.amdFlowHalfResolution) return true;
if (previous.flow != next.flow) return true;
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 0a7a5576..240c53aa 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -578,7 +578,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
veyra::log::warn("backend-recovery",std::format("initialization failed component={} attempt={} revision={} -> nr={} sr={} multiplier={}; original SDK error above",unsigned(failure),attempt+1,reduced.revision,reduced.nr,reduced.sr,reduced.multiplier));
if(!backendRecoveryWarning.empty())backendRecoveryWarning+=L";";
const uint32_t ngxResult=uint32_t(graph.failedNgxResult());
- if(selected.settings.frameGenerationBackend==FrameGenerationBackend::Fsr4&&failure==FailedBackend::Fg)
+ if(selected.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&failure==FailedBackend::Fg)
+ backendRecoveryWarning+=L"NVIDIA VFG 未能启用(需要 Ada / Blackwell 显卡、VFG 运行组件和支持的输出格式),已关闭补帧;原因见日志";
+ else if(selected.settings.frameGenerationBackend==FrameGenerationBackend::Fsr4&&failure==FailedBackend::Fg)
backendRecoveryWarning+=L"FSR 4 ML 提供方不可用(需要支持的 RX 9000 和驱动),已关闭补帧;原因见日志";
else if((ngxResult&0xFFF00000u)==0xBAD00000u)
backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L":"+ngxFailureHint(ngxResult)+std::format(L"(NGX 0x{:08X},驱动 {}),已关闭依赖效果",ngxResult,ctx.adapter().driverVersion);
@@ -619,7 +621,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
publishFrameGenerationCapabilities();
if(!previewInitialized){status(L"视频初始化失败,请查看对应组件的诊断日志",true);break;}
if(!backendRecoveryWarning.empty()){
- std::lock_guard lock(mutex_);desired_.rejectVideoRequest(initialRequested,options.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;
+ std::lock_guard lock(mutex_);desired_.rejectVideoRequest(initialRequested,options.snapshot());snapshot_.desired=desired_;snapshot_.rejectedRevision=initialRequested.revision;snapshot_.backendWarning=backendRecoveryWarning;
}
if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg))){
veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested features: nr={} sr={} fgBackend={} flowBackend={}",options.nr,options.sr,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend)));
@@ -1172,7 +1174,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!accepted){finishReset(diagnostics::ResetOutcome::Failed);status(L"设置切换排空失败,已停止",true);break;}
backendRecoveryWarning.clear();
const bool preserveWorkingFg=previous.multiplier>1&&requested.multiplier>1&&
- (previous.frameGenerationBackend!=requested.frameGenerationBackend||previous.multiplier!=requested.multiplier);
+ (previous.frameGenerationBackend!=requested.frameGenerationBackend||previous.multiplier!=requested.multiplier||previous.vfgQuality!=requested.vfgQuality);
const bool preserveWorkingNr=previous.nr&&requested.nr&&previous.nrRuntime!=requested.nrRuntime;
if(accepted&&rebuild){presenter.close();graph.shutdown();markResetStage(diagnostics::ResetStage::Destroy);accepted=initializePreview(nextDesc,next,preserveWorkingFg,preserveWorkingNr);
markResetStage(diagnostics::ResetStage::Create);
@@ -1182,7 +1184,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(accepted){
if(xessPresentationRecovery){backendRecoveryWarning=L"XeSS 呈现失败,已关闭补帧并恢复播放;错误码见日志";xessPresentationRecovery=false;}
if(!backendRecoveryWarning.empty()){
- std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,next.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;
+ std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,next.snapshot());snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.backendWarning=backendRecoveryWarning;
}
options=next;gd=nextDesc;transaction=true;reset=true;
resetRecord->epoch=0;
@@ -1695,7 +1697,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!initializePreview(gd,options)){status(L"增强故障后的基础图重建失败",true);break;}
publishFrameGenerationCapabilities();
backendRecoveryWarning=std::wstring(backendFailureName(failedComponent))+L"运行失败,已关闭对应效果;错误码见日志"+(backendRecoveryWarning.empty()?L"":L";"+backendRecoveryWarning);
- {std::lock_guard lock(mutex_);desired_.rejectVideoRequest(attempted,options.snapshot());snapshot_.desired=desired_;snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;snapshot_.backendWarning=backendRecoveryWarning;}
+ {std::lock_guard lock(mutex_);desired_.rejectVideoRequest(attempted,options.snapshot());snapshot_.desired=desired_;snapshot_.applied=options.snapshot();snapshot_.rejectedRevision=attempted.revision;snapshot_.applying=desired_!=snapshot_.applied;snapshot_.backendWarning=backendRecoveryWarning;}
veyra::log::warn("backend-recovery",std::format("runtime component={} disabled; rebuilt revision={} nr={} sr={} multiplier={}; retry next source frame",unsigned(failedComponent),options.settings.revision,options.nr,options.sr,options.snapshot().multiplier));
finishReset(diagnostics::ResetOutcome::Failed);reset=true;pendingResetCause=pipeline::ResetReason::Settings;
holdFileAudio();fileAudioAlignPending=true;
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index adbac237..dfc44962 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -29,7 +29,7 @@ struct Shared {
// chain is fixed-capacity and trivially copyable, so it can cross the
// process boundary; a worker that sees another version refuses the job
// instead of reading a mismatched layout.
- DWORD signature=magic,version=7,bytes=sizeof(Shared); // 7: resume after a GPU reset
+ DWORD signature=magic,version=8,bytes=sizeof(Shared); // 8: VFG quality in the immutable settings snapshot
EnhancementSettings settings;
EffectChain chain;
wchar_t input[32768]{},output[32768]{},temporary[32768]{};
@@ -245,7 +245,7 @@ ExportJobSnapshot ExportJobManager::poll(){
}
int runExportWorker(HANDLE mapping){
auto s=static_cast<Shared*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!s)return 1;
- if(s->signature!=magic||s->version!=7||s->bytes!=sizeof(Shared)||!s->media.valid()||s->audioStreamIndex< -1||s->rateControl>uint32_t(sink::ExportRateControl::Cq)||!std::isfinite(s->trimStartSeconds)||!std::isfinite(s->trimEndSeconds)||s->trimStartSeconds<0||s->trimEndSeconds<0||(s->trimEndSeconds>0&&s->trimEndSeconds<=s->trimStartSeconds)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]||s->temporary[32767]||!s->temporary[0]||s->priorCount>=kMaxExportParts){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}
+ if(s->signature!=magic||s->version!=8||s->bytes!=sizeof(Shared)||!s->media.valid()||s->audioStreamIndex< -1||s->rateControl>uint32_t(sink::ExportRateControl::Cq)||!std::isfinite(s->trimStartSeconds)||!std::isfinite(s->trimEndSeconds)||s->trimStartSeconds<0||s->trimEndSeconds<0||(s->trimEndSeconds>0&&s->trimEndSeconds<=s->trimStartSeconds)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]||s->temporary[32767]||!s->temporary[0]||s->priorCount>=kMaxExportParts){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}
Logger::instance().openFile((runtime::logsDirectory()/std::format("export-worker-{}.log",GetCurrentProcessId())).wstring());
ExportStreams::enableWorkerLogging(GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_FFMPEG_DEBUG",nullptr,0)>0);
// The chain is the description of record for this job; the settings struct
diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cpp
index b5db55f1..1fef637f 100644
--- a/src/engine/PresetLibrary.cpp
+++ b/src/engine/PresetLibrary.cpp
@@ -13,14 +13,14 @@ namespace {
// Six full grades per entry (plus the legacy first-grade field), up to 64
// entries. Never remove the file-size guard as LUT names are external input.
constexpr size_t kMaxPresetBytes = 2u * 1024u * 1024u;
-void writeRendering(std::ostream& out,const ChainGlobalSettings& g){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);}
-bool readRendering(std::istream& in,ChainGlobalSettings& g){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;g.hdrOutputMode=HdrOutputMode(hdr);g.fgMotion=MotionSource(fg);g.srMotion=MotionSource(sr);g.nrMotion=MotionSource(nr);EnhancementSettings s;g.apply(s);return s.validate().empty();}
+void writeRendering(std::ostream& out,const ChainGlobalSettings& g,bool vfg=false){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);if(vfg)out<<' '<<g.vfgQuality;}
+bool readRendering(std::istream& in,ChainGlobalSettings& g,bool vfg=false){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;g.hdrOutputMode=HdrOutputMode(hdr);g.fgMotion=MotionSource(fg);g.srMotion=MotionSource(sr);g.nrMotion=MotionSource(nr);if(vfg&&!(in>>g.vfgQuality))return false;EnhancementSettings s;g.apply(s);return s.validate().empty();}
void applyRenderingPreset(const PresetEntry& e,EnhancementSettings& s){
if(!e.globals)return;
- const auto fg=s.frameGenerationBackend;const auto fgMotion=s.fgMotion;
+ const auto fg=s.frameGenerationBackend;const auto fgMotion=s.fgMotion;const auto quality=s.vfgQuality;
if(e.contents&presetContentMask(PresetContent::Chain))e.globals->apply(s);
if(e.contents&presetContentMask(PresetContent::FrameGeneration))s.fgMotion=e.globals->fgMotion;
- else{s.frameGenerationBackend=fg;s.fgMotion=fgMotion;}
+ else{s.frameGenerationBackend=fg;s.fgMotion=fgMotion;s.vfgQuality=quality;}
}
std::string utf8(const std::wstring& s) {
if (s.empty()) return {};
@@ -68,6 +68,8 @@ void PresetLibrary::addBuiltins() {
bool PresetLibrary::load() {
error_.clear();
addBuiltins();
+ const auto rootVfg=std::filesystem::path(path_).concat(L".vfg");
+ if(std::filesystem::exists(rootVfg))path_=rootVfg;
const auto rootRendering=std::filesystem::path(path_).concat(L".field-render");
if(std::filesystem::exists(rootRendering))path_=rootRendering;
const auto migratedPath = std::filesystem::path(path_).concat(L".p3-node");
@@ -79,6 +81,8 @@ bool PresetLibrary::load() {
if (std::filesystem::exists(globalsPath)) path_ = globalsPath;
const auto renderingPath=std::filesystem::path(path_).concat(L".field-render");
if(std::filesystem::exists(renderingPath))path_=renderingPath;
+ const auto vfgPath=std::filesystem::path(path_).concat(L".vfg");
+ if(std::filesystem::exists(vfgPath))path_=vfgPath;
if (!std::filesystem::exists(path_)) return true;
std::error_code ec;
const auto size = std::filesystem::file_size(path_, ec);
@@ -172,6 +176,8 @@ bool PresetLibrary::save() {
std::wstring checkedDefault;
// Match PresetStore: never replace a valid file with one our reader rejects.
if (!parse(data, checked, checkedDefault, error_)) return false;
+ if(data.starts_with("VEYRA_PRESET_LIBRARY 7")&&!path_.wstring().ends_with(L".vfg"))path_=std::filesystem::path(path_).concat(L".vfg");
+ if(!path_.wstring().ends_with(L".vfg")){
if(data.starts_with("VEYRA_PRESET_LIBRARY 6")&&!path_.wstring().ends_with(L".field-render"))path_=std::filesystem::path(path_).concat(L".field-render");
if (std::any_of(entries_.begin(), entries_.end(), [](const auto& e) { return e.nodeConfiguration.has_value(); }) &&
!path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-editor") && !path_.wstring().ends_with(L".p3-globals"))
@@ -180,6 +186,7 @@ bool PresetLibrary::save() {
return e.nodeConfiguration && e.nodeConfiguration->editor && e.nodeConfiguration->editor->globals;
}) && !path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-globals"))
path_ = std::filesystem::path(path_).concat(L".p3-globals");
+ }
std::error_code ec;
std::filesystem::create_directories(path_.parent_path(), ec);
const auto temporary = std::filesystem::path(path_).concat(L".tmp");
@@ -283,6 +290,7 @@ void PresetLibrary::apply(const PresetEntry& entry, EnhancementSettings& setting
const auto keepAdditionalColorCount = settings.additionalColorCount;
const auto keepMultiplier = settings.multiplier;
const auto keepBackend = settings.frameGenerationBackend;
+ const auto keepQuality = settings.vfgQuality;
applyRenderingPreset(entry,settings);
const auto keepAudioSync = settings.audioSync;
const auto keepAudioOffset = settings.audioOffsetMs;
@@ -301,9 +309,11 @@ void PresetLibrary::apply(const PresetEntry& entry, EnhancementSettings& setting
if (entry.contents & presetContentMask(PresetContent::FrameGeneration)) {
settings.multiplier = std::max(1u, entry.fg.multiplier);
settings.frameGenerationBackend = entry.fg.backend;
+ settings.vfgQuality = entry.fg.vfgQuality;
} else {
settings.multiplier = keepMultiplier;
settings.frameGenerationBackend = keepBackend;
+ settings.vfgQuality = keepQuality;
}
if (entry.contents & presetContentMask(PresetContent::Audio)) {
settings.audioSync = entry.audioSync;
@@ -426,7 +436,7 @@ ChainValidation PresetLibrary::applyToEditor(const PresetEntry& entry, NodeEdito
PresetEntry keep; keep.kind = ChainMode::Node; keep.chain.mode = ChainMode::Node;
keep.contents = presetContentMask(PresetContent::FrameGeneration);
const auto* old = document.nodes.firstOf(EffectType::FrameGeneration);
- keep.fg = {old && old->enabled ? document.nodes.fgMultiplier : 1, settings.frameGenerationBackend};
+ keep.fg = {old && old->enabled ? document.nodes.fgMultiplier : 1, settings.frameGenerationBackend, settings.vfgQuality};
if (auto v = applyToEditor(keep, *next, values); !v.accepted) return v;
nodes.fgStrictAdmission = document.nodes.fgStrictAdmission;
}
@@ -502,6 +512,7 @@ ChainValidation PresetLibrary::applyToEditor(const PresetEntry& entry, NodeEdito
if (node) node->enabled = entry.fg.multiplier > 1;
if (entry.fg.multiplier > 1) nodes.fgMultiplier = entry.fg.multiplier;
values.frameGenerationBackend = entry.fg.backend;
+ values.vfgQuality = entry.fg.vfgQuality;
}
if (entry.contents & presetContentMask(PresetContent::Audio)) {
values.audioSync = entry.audioSync; values.audioOffsetMs = entry.audioOffsetMs;
@@ -564,7 +575,14 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
return e.nodeConfiguration && e.nodeConfiguration->editor && e.nodeConfiguration->editor->globals;
});
const bool rendering=std::any_of(entries_.begin(),entries_.end(),[](const auto& e){return e.globals.has_value();});
- const int version=std::max(minimumVersion, rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);
+ const bool vfg=std::any_of(entries_.begin(),entries_.end(),[](const auto& e){
+ if(e.fg.backend==FrameGenerationBackend::Vfg||e.fg.vfgQuality!=1||
+ (e.globals&&(e.globals->fgBackend==FrameGenerationBackend::Vfg||e.globals->vfgQuality!=1)))return true;
+ if(!e.nodeConfiguration)return false;const auto& c=*e.nodeConfiguration;
+ return c.fgBackend==FrameGenerationBackend::Vfg||c.vfgQuality!=1||
+ (c.editor&&c.editor->globals&&(c.editor->globals->fgBackend==FrameGenerationBackend::Vfg||c.editor->globals->vfgQuality!=1));
+ });
+ const int version=std::max(minimumVersion, vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);
o << "VEYRA_PRESET_LIBRARY " << version << '\n' << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';
for (const auto& e : entries_) {
o << std::quoted(utf8(e.name)) << ' ' << std::quoted(utf8(e.note)) << ' '
@@ -572,6 +590,7 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
<< e.fg.multiplier << ' ' << int(e.fg.backend) << ' ' << int(e.audioSync) << ' ' << e.audioOffsetMs << ' '
<< e.chain.nodeCount << ' ' << int(e.chain.mode) << ' ' << e.chain.fgMultiplier << ' '
<< (e.chain.fgStrictAdmission ? 1 : 0) << ' ';
+ if(version>=7)o<<e.fg.vfgQuality<<' ';
for (uint32_t i = 0; i < e.chain.nodeCount; ++i) {
const auto& n = e.chain.nodes[i];
o << int(n.type) << ' ' << (n.enabled ? 1 : 0) << ' ' << n.viewX << ' ' << n.viewY << ' '
@@ -606,7 +625,7 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
}
if(version>=6){
o<<' '<<e.globals.has_value();
- if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g);}
+ if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g,version>=7);}
}
o << '\n';
}
@@ -622,7 +641,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
std::string magic, quoted;
int version = 0;
size_t count = 0;
- if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > (preserveLegacy ? 3 : 6)) { error = L"预设库格式或版本不支持"; return false; }
+ if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > 7) { error = L"预设库格式或版本不支持"; return false; }
if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }
def = wide(quoted);
for (size_t i = 0; i < count; ++i) {
@@ -632,14 +651,16 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
uint32_t nodeCount = 0;
if (!(in >> std::quoted(name) >> std::quoted(note) >> kind >> builtin >> e.contents >> e.fg.multiplier >> fgBackend >> audioSync >> e.audioOffsetMs >> nodeCount >> chainMode >> e.chain.fgMultiplier >> strict)) { error = L"预设库头部字段损坏"; return false; }
if (kind < 0 || kind > 1 || chainMode < 0 || chainMode > 1 || strict < 0 || strict > 1 ||
- nodeCount > kMaxChainNodes || e.fg.multiplier < 1 || e.fg.multiplier > 6) { error = L"预设库字段超出范围"; return false; }
+ nodeCount > kMaxChainNodes || e.fg.multiplier < 1 || e.fg.multiplier > (version>=7?8u:6u)) { error = L"预设库字段超出范围"; return false; }
+ if(version>=7&&!(in>>e.fg.vfgQuality)){error=L"预设库 VFG 质量字段损坏";return false;}
+ if(fgBackend<0||fgBackend>(version>=7?4:3)){error=L"预设库补帧后端无效";return false;}
e.name = wide(name);
e.note = wide(note);
e.kind = static_cast<ChainMode>(kind);
e.builtin = builtin != 0;
e.fg.backend = static_cast<FrameGenerationBackend>(fgBackend);
EnhancementSettings fgContract;
- fgContract.multiplier=e.fg.multiplier;fgContract.frameGenerationBackend=e.fg.backend;
+ fgContract.multiplier=e.fg.multiplier;fgContract.frameGenerationBackend=e.fg.backend;fgContract.vfgQuality=e.fg.vfgQuality;
if(!fgContract.validate().empty()){error=L"预设库补帧后端或倍率无效";return false;}
e.audioSync = static_cast<AudioSyncMode>(audioSync);
e.chain.nodeCount = nodeCount;
@@ -718,7 +739,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
if(present){ChainGlobalSettings g;int target,backend,flow,optical,half,policy;
if(!(in>>target>>g.videoSrQuality>>backend>>flow>>optical>>half>>policy)||half<0||half>1)return false;
g.srTarget=pipeline::SrTarget(target);g.fgBackend=FrameGenerationBackend(backend);g.flow=FlowQuality(flow);g.opticalFlowBackend=OpticalFlowBackend(optical);g.amdFlowHalfResolution=half!=0;g.nrPolicy=pipeline::NrSizePolicy(policy);
- if(!readRendering(in,g))return false;e.globals=g;
+ if(!readRendering(in,g,version>=7))return false;e.globals=g;
}
}
out.push_back(std::move(e));
@@ -734,7 +755,9 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
const auto& editor = session.configurations[1].editor;
const auto extended=[](const ChainGlobalSettings& g){return g.srTarget>pipeline::SrTarget::Uhd8K||g.hdrOutputMode!=HdrOutputMode::Hdr10||g.fgMotion!=MotionSource::Automatic||g.srMotion!=MotionSource::OpticalFlow||g.nrMotion!=MotionSource::OpticalFlow;};
const bool rendering=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){return extended(c)||(c.editor&&c.editor->globals&&extended(*c.editor->globals));});
- const int version = rendering?4:editor ? (editor->globals ? 3 : 2) : 1;
+ const auto usesVfg=[](const ChainGlobalSettings& g){return g.fgBackend==FrameGenerationBackend::Vfg||g.vfgQuality!=1;};
+ const bool vfg=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){return usesVfg(c)||(c.editor&&c.editor->globals&&usesVfg(*c.editor->globals));});
+ const int version = vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;
out << "VEYRA_CHAIN_SESSION " << version << '\n' << int(session.active) << ' ' << session.initialized[0] << ' ' << session.initialized[1];
if(version>=4)out<<' '<<bool(editor);out<<'\n';
std::vector<PresetEntry> entries;
@@ -743,11 +766,11 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
out << int(c.srTarget) << ' ' << c.videoSrQuality << ' ' << int(c.fgBackend) << ' '
<< int(c.flow) << ' ' << int(c.opticalFlowBackend) << ' ' << c.amdFlowHalfResolution << ' '
<< int(c.nrPolicy) << ' ' << c.selectedNr << ' ' << c.selectedColour;
- if(version>=4)writeRendering(out,c);out<<'\n';
+ if(version>=4)writeRendering(out,c,version>=5);out<<'\n';
PresetEntry entry;
entry.name = i == 0 ? L"list" : L"node";
entry.kind = ChainMode(i); entry.chain = c.chain;
- entry.fg = {c.chain.fgMultiplier, c.fgBackend};
+ entry.fg = {c.chain.fgMultiplier, c.fgBackend, c.vfgQuality};
if (const auto color = c.chain.firstOf(EffectType::Color)) entry.color = color->color;
entries.push_back(std::move(entry));
}
@@ -761,7 +784,7 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
const auto& g = *document.globals;
out << int(g.srTarget) << ' ' << g.videoSrQuality << ' ' << int(g.fgBackend) << ' '
<< int(g.flow) << ' ' << int(g.opticalFlowBackend) << ' ' << g.amdFlowHalfResolution << ' '
- << int(g.nrPolicy);if(version>=4)writeRendering(out,g);out<<'\n';
+ << int(g.nrPolicy);if(version>=4)writeRendering(out,g,version>=5);out<<'\n';
}
out << graph.nextId << ' ' << graph.inputNext << ' ' << document.nodes.nodeCount << '\n';
// The ordinary preset codec validates a linear runtime chain. Use a
@@ -770,7 +793,8 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
// This does not weaken ordinary preset import or runtime validation.
auto entry = std::make_unique<PresetEntry>();
entry->name = L"editor"; entry->kind = ChainMode::Node; entry->chain = document.nodes;
- entry->fg = {document.nodes.fgMultiplier, session.configurations[1].fgBackend};
+ const auto& editorGlobals=document.globals?*document.globals:static_cast<const ChainGlobalSettings&>(session.configurations[1]);
+ entry->fg = {document.nodes.fgMultiplier, editorGlobals.fgBackend, editorGlobals.vfgQuality};
for (uint32_t i = 0; i < document.nodes.nodeCount; ++i) {
out << graph.ids[i] << ' ' << graph.next[i] << ' ' << document.nodes.nodes[i].enabled << '\n';
entry->chain.nodes[i].enabled = false;
@@ -787,7 +811,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
std::istringstream in(data); in.imbue(std::locale::classic());
std::string magic, body; int version = 0, active = 0, list = 0, node = 0;
if (!(in >> magic >> version >> active >> list >> node) || magic != "VEYRA_CHAIN_SESSION" ||
- (version < 1 || version > 4) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;
+ (version < 1 || version > 5) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;
int hasEditor=version>=2?1:0;
if(version>=4&&(!(in>>hasEditor)||hasEditor<0||hasEditor>1))return false;
ChainSession parsed; parsed.active = ChainMode(active); parsed.initialized = {true, node != 0};
@@ -798,7 +822,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
c.srTarget = pipeline::SrTarget(target); c.fgBackend = FrameGenerationBackend(backend);
c.flow = FlowQuality(flow); c.opticalFlowBackend = OpticalFlowBackend(optical);
c.amdFlowHalfResolution = half != 0; c.nrPolicy = pipeline::NrSizePolicy(policy);
- if(version>=4&&!readRendering(in,c))return false;
+ if(version>=4&&!readRendering(in,c,version>=5))return false;
}
if (!(in >> std::quoted(body))) return false;
std::vector<PresetEntry> entries; std::wstring def, error;
@@ -823,7 +847,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
g.srTarget = pipeline::SrTarget(target); g.fgBackend = FrameGenerationBackend(backend);
g.flow = FlowQuality(flow); g.opticalFlowBackend = OpticalFlowBackend(optical);
g.amdFlowHalfResolution = half != 0; g.nrPolicy = pipeline::NrSizePolicy(policy);
- if(version>=4&&!readRendering(in,g))return false;
+ if(version>=4&&!readRendering(in,g,version>=5))return false;
editor->globals = g;
}
uint32_t count = 0;
@@ -855,6 +879,8 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
bool ChainSessionStore::load(ChainSession& session) {
error_.clear();
std::error_code ec;
+ const auto rootVfg=std::filesystem::path(path_).concat(L".vfg");
+ if(std::filesystem::exists(rootVfg,ec))path_=rootVfg;
const auto rootRendering=std::filesystem::path(path_).concat(L".field-render");
if(std::filesystem::exists(rootRendering,ec))path_=rootRendering;
const auto migratedPath = std::filesystem::path(path_).concat(L".p3-node");
@@ -866,6 +892,8 @@ bool ChainSessionStore::load(ChainSession& session) {
if (std::filesystem::exists(globalsPath, ec)) path_ = globalsPath;
const auto renderingPath=std::filesystem::path(path_).concat(L".field-render");
if(std::filesystem::exists(renderingPath,ec))path_=renderingPath;
+ const auto vfgPath=std::filesystem::path(path_).concat(L".vfg");
+ if(std::filesystem::exists(vfgPath,ec))path_=vfgPath;
const bool exists = std::filesystem::exists(path_, ec);
if (!exists && !ec) return true;
const auto size = std::filesystem::file_size(path_, ec);
@@ -895,6 +923,8 @@ bool ChainSessionStore::save(const ChainSession& session) {
const auto data = encode(session);
ChainSession checked;
if (!decode(data, checked)) { error_ = L"模式会话编码校验失败,未保存"; return false; }
+ if(data.starts_with("VEYRA_CHAIN_SESSION 5")&&!path_.wstring().ends_with(L".vfg"))path_=std::filesystem::path(path_).concat(L".vfg");
+ if(!path_.wstring().ends_with(L".vfg")){
if(data.starts_with("VEYRA_CHAIN_SESSION 4")&&!path_.wstring().ends_with(L".field-render"))path_=std::filesystem::path(path_).concat(L".field-render");
// A v1 reader must never reinterpret or overwrite the new editor graph.
// Preserve the original session as a rollback point during this opt-in.
@@ -904,6 +934,7 @@ bool ChainSessionStore::save(const ChainSession& session) {
if (session.configurations[1].editor && session.configurations[1].editor->globals &&
!path_.wstring().ends_with(L".field-render")&&!path_.wstring().ends_with(L".p3-globals"))
path_ = std::filesystem::path(path_).concat(L".p3-globals");
+ }
std::error_code ec;
if (!path_.parent_path().empty()) std::filesystem::create_directories(path_.parent_path(), ec);
if (ec) { error_ = L"模式会话目录无法创建"; return false; }
diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cpp
index 042582cb..145e47d5 100644
--- a/src/engine/PresetStore.cpp
+++ b/src/engine/PresetStore.cpp
@@ -34,9 +34,10 @@ std::string PresetStore::serialize()const{
const bool fsr4=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.frameGenerationBackend==FrameGenerationBackend::Fsr4;});
const bool higher=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.srTarget>pipeline::SrTarget::Uhd8K;});
const bool rendering=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){const auto& s=p.settings;return s.hdrOutputMode!=HdrOutputMode::Hdr10||s.fgMotion!=MotionSource::Automatic||s.srMotion!=MotionSource::OpticalFlow||s.nrMotion!=MotionSource::OpticalFlow;});
- const bool fullSchema=fsr4||higher||rendering;
+ const bool vfg=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.frameGenerationBackend==FrameGenerationBackend::Vfg||p.settings.vfgQuality!=1;});
+ const bool fullSchema=fsr4||higher||rendering||vfg;
// v26 introduces appended resolution IDs; old readers reject this schema.
- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS "<<(rendering?27:higher?26:fsr4?25:hold?24:stack?23:multi?22:21)<<'\n'<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';
+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS "<<(vfg?28:rendering?27:higher?26:fsr4?25:hold?24:stack?23:multi?22:21)<<'\n'<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';
for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<' '<<int(s.captureAudio)<<' '<<s.exportBitrateMbps<<' '<<s.captureFlipVertical<<' '<<int(s.captureBuffer)<<' ';writeColorSettings(o,s.color,utf8(s.color.lutNameString()));o<<' '<<s.videoHdr.enabled<<' '<<s.videoHdr.contrast<<' '<<s.videoHdr.saturation<<' '<<s.videoHdr.middleGray<<' '<<s.videoHdr.peakNits<<' '<<s.nrTemporal;
if(multi||fullSchema){o<<' '<<s.additionalColorCount;for(unsigned i=0;i<s.additionalColorCount;++i){o<<' ';writeColorSettings(o,s.additionalColors[i],utf8(s.additionalColors[i].lutNameString()));}}
if(stack||fullSchema){
@@ -55,13 +56,14 @@ std::string PresetStore::serialize()const{
// any entry needs it. Otherwise entries in the same file would parse
// differently.
if(hold||fullSchema)o<<' '<<s.nrHoldStrength<<' '<<s.nrHoldTolerance;
- if(rendering)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);
+ if(rendering||vfg)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);
+ if(vfg)o<<' '<<s.vfgQuality;
o<<'\n';
}return o.str();
}
bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){
if(data.size()>kMaxPresetBytes)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;
- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>27)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;
+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>28)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;
for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;
if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;
if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;
@@ -69,7 +71,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std
if(version>=3&&!(in>>s.videoSrQuality))return false;
// Retired local FSR4 mode: keep the preset, use RTX Video SR high.
if(version==20&&s.videoSrQuality==6)s.videoSrQuality=3;
- if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=25?3:version>=13?2:(version>=6&&version<=7?2:1)))return false;
+ if(version>=4){int backend;if(!(in>>backend)||backend<0||backend>(version>=28?4:version>=25?3:version>=13?2:(version>=6&&version<=7?2:1)))return false;
// Before v8, 1 meant removed FRUC and 2 meant XeSS. New writes use v10.
s.frameGenerationBackend=version<8
?(backend==2?FrameGenerationBackend::XeSS:FrameGenerationBackend::Dlss)
@@ -122,6 +124,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std
if(!std::isfinite(s.nrHoldTolerance)||s.nrHoldTolerance<0.0f||s.nrHoldTolerance>1.0f)return false;
}
if(version>=27){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;s.hdrOutputMode=HdrOutputMode(hdr);s.fgMotion=MotionSource(fg);s.srMotion=MotionSource(sr);s.nrMotion=MotionSource(nr);}
+ if(version>=28&&!(in>>s.vfgQuality))return false;
p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;
s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);
if(!s.validate().empty())return false;out.push_back(std::move(p));
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index d5402ec1..90b537c3 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -308,7 +308,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(error||cancel)break;
if(options.fg&&lastReal)for(uint32_t j=1;j<multiplier;++j){if(!encodeAt(lastReal->slot,false,previousPts+sourceInterval*j/multiplier)){error=true;break;}++holdCount;}
if(error)break;
- veyra::log::info("export-counts",std::format("slowFrames={} source={} generated={} hold={} output={} multiplier={} repairedTimestamps={} backend={} encoder={} bitrateMbps={} note={} (holds are not DLSSG)",slowFrames,sourceCount,generatedCount,holdCount,outputIndex,multiplier,repairedTimestamps,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
+ veyra::log::info("export-counts",std::format("slowFrames={} source={} generated={} hold={} output={} multiplier={} repairedTimestamps={} backend={} vfgQuality={} encoder={} bitrateMbps={} note={} (holds are not generated frames)",slowFrames,sourceCount,generatedCount,holdCount,outputIndex,multiplier,repairedTimestamps,frameGenerationBackendName(options.settings.frameGenerationBackend),options.settings.vfgQuality,std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
progress(.99,L"正在收尾:等待编码器输出剩余帧");
if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}
const int64_t estimatedEnd=lastOutputUs+std::max<int64_t>(1,int64_t(std::llround(sourceInterval*1000000/multiplier)));
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 25c90339..f402c527 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -58,9 +58,9 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh
}
if(!sink_.initialize(ctx.device(),queue,d,st))return false;
std::vector<uint8_t> vs,ps;
- // SRV layout: 0..1 video frames, 2..11 generated frames (2 parities x 5
- // subframes, 6X), 12..15 comparison references.
- if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,16,graph.outputFormat()))return false;
+ // The output pool contains both parities of every generated subframe.
+ // Comparison references follow it; derive offsets to cover VFG through 8X.
+ if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,pipeline::kOutputPoolSlots+4,graph.outputFormat()))return false;
if(sink_.xess()){
std::vector<uint8_t> cs;
if(!pipeline::loadShaderBytes("PresentMotion.dxil",cs)||!presentMotionPass_.create(ctx.device(),cs,4,1,1,16))return false;
@@ -76,8 +76,8 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh
D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_RTV;hd.NumDescriptors=3;
if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rtvs_))))return false;
inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);refresh(ctx.device());
- for(unsigned i=0;i<12;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
- for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.sourceReference(i):graph.baseReference(i-2),DXGI_FORMAT_R16G16B16A16_FLOAT,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i+12)*pass_.increment});
+ for(unsigned i=0;i<pipeline::kOutputPoolSlots;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
+ for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.sourceReference(i):graph.baseReference(i-2),DXGI_FORMAT_R16G16B16A16_FLOAT,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i+pipeline::kOutputPoolSlots)*pass_.increment});
return true;
}
void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}
@@ -158,7 +158,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
if(comparison&&!generated&&referencesValid){
auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);
D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);
- dims[2]=samplingFlags+(graph.hdr10Output()?4:graph.hdrOutput()?0:1)+(graph.videoHdrActive()?8:0);list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(12+slot+(baseReference?2:0))*pass_.increment});
+ dims[2]=samplingFlags+(graph.hdr10Output()?4:graph.hdrOutput()?0:1)+(graph.videoHdrActive()?8:0);list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(pipeline::kOutputPoolSlots+slot+(baseReference?2:0))*pass_.increment});
if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*renderW)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);
std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 73e7f394..d05528a4 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -7,6 +7,7 @@
// views are created last. Per-frame execution uses the shared command slot
// ring (NR evaluates on a fresh list - snippet constraint).
#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/pipeline/VfgBackend.h"
#include "veyra/engine/GraphDescription.h"
#include "veyra/engine/ColorLut.h"
#include "veyra/engine/EffectChain.h"
@@ -441,7 +442,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
nrEnabled_ = desc.enableNr && !desc.noFeatures && (!desc.noNgx || lmxxfNr_);
fgEnabled_ = desc.enableFg && !desc.noFeatures && !desc.stillImage &&
desc.frameGenerationBackend != engine::FrameGenerationBackend::XeSS &&
- (!desc.noNgx || engine::fsrFrameGeneration(desc.frameGenerationBackend));
+ (!desc.noNgx || engine::fsrFrameGeneration(desc.frameGenerationBackend)||desc.frameGenerationBackend==engine::FrameGenerationBackend::Vfg);
nvofStandalone_ = desc.enableNvofStandalone && !desc.noFeatures;
if(desc_.opticalFlowBackend==engine::OpticalFlowBackend::AmdFidelityFx&&desc.amdFlowHalfResolution){nvofW_=std::max(1u,nvofW_/2);nvofH_=std::max(1u,nvofH_/2);}
uint64_t budget=0,usage=0;
@@ -464,7 +465,10 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
if(const auto target=desc_.interNrProtectionTarget();target<engine::kMaxNrInstances){
const auto extent=desc_.nrFullExtent(target);interProtectionBytes=uint64_t(extent.width)*extent.height*8;
}
- const uint64_t estimate=uint64_t(workW_)*workH_*(fgEnabled_?100:76)
+ const bool vfg=fgEnabled_&&desc_.frameGenerationBackend==engine::FrameGenerationBackend::Vfg;
+ const uint64_t vfgSharedBytes=vfg?uint64_t((workW_*4u+255u)&~255u)*workH_*(2u+2u*(desc_.fgMultiplier-1u)):0;
+ const unsigned generatedTextures=fgEnabled_?(fsrEnabled()?2u:vfg?2u*(desc_.fgMultiplier-1u):10u):0;
+ const uint64_t estimate=uint64_t(workW_)*workH_*(76u+4u*generatedTextures)+vfgSharedBytes
+nrTextureBytes+fullLayerBytes
+uint64_t(srcW_)*srcH_*(32u+(desc_.protectionBeforeSr()?8u:0u))+temporalBytes+tailColorBytes+interProtectionBytes;
if(context_.videoMemoryInfo(budget,usage)){
@@ -487,6 +491,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
if (!initNvof()) { failedBackend_=engine::FailedBackend::OpticalFlow; return false; }
if (!initFsrSr()) return false;
if (!initFsrFg()) return false;
+ if (!initVfg()) return false;
if(nrEnabled_&&GetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",nullptr,0)){
failedBackend_=engine::FailedBackend::Nr;
veyra::log::error("backend-recovery-test","test-only NR initialization rejection before SDK call; not a hardware failure");return false;
@@ -639,7 +644,10 @@ bool EnhanceGraph::createResources()
// Valid placeholder descriptors keep disabled FG inexpensive. Enabling it
// is a graph rebuild, so no in-flight descriptor is resized in place.
for(size_t i=0;i<kGeneratedPoolSlots;++i){
- const bool used=fgEnabled_&&(!fsrEnabled()||i<2);
+ // DLSS compatibility binds ten full-sized resources even at 2X.
+ // VFG owns only the selected multiplier's outputs; FSR owns one pair.
+ const unsigned usedCount=fsrEnabled()?2u:desc_.frameGenerationBackend==engine::FrameGenerationBackend::Vfg?2u*(desc_.fgMultiplier-1u):10u;
+ const bool used=fgEnabled_&&i<usedCount;
genFrame_[i]=makeTexture(context_.device(),used?workW_:1,used?workH_:1,outputFormat(),true);
if(!genFrame_[i])return false;
}
@@ -1026,6 +1034,16 @@ bool EnhanceGraph::initFsrFg() {
return true;
}
+bool EnhanceGraph::initVfg()
+{
+ if(!fgEnabled_||desc_.frameGenerationBackend!=engine::FrameGenerationBackend::Vfg)return true;
+ failedBackend_=engine::FailedBackend::Fg;
+ vfgBackend_=std::make_unique<VfgBackend>();
+ if(!vfgBackend_->initialize(context_,desc_.runtimeAbsPath,workW_,workH_,outputFormat(),desc_.fgMultiplier,desc_.vfgQuality))return false;
+ fgCapsAvailable_=true;fgMultiFrameMax_=int(FrameBatch::Capacity)-1;
+ return true;
+}
+
bool EnhanceGraph::initNgxFeatures()
{
Status st = Status::Ok;
@@ -1037,7 +1055,7 @@ bool EnhanceGraph::initNgxFeatures()
}
// FSR upscaling is a FidelityFX effect: a session whose only feature is
// FSR SR must not require (or fail on) the NGX core.
- const bool needNgxCore = (nrEnabled_ && !lmxxfNr_) || (fgEnabled_ && !fsrEnabled()) || desc_.convertVideoHdr() ||
+ const bool needNgxCore = (nrEnabled_ && !lmxxfNr_) || (fgEnabled_ && !fsrEnabled() && !vfgBackend_) || desc_.convertVideoHdr() ||
(srEnabled_ && desc_.videoSrQuality!=engine::kVideoSrFsr);
if (!needNgxCore) {
veyra::log::info("graph", "NGX core skipped: lmxxf NR / AMD FSR stages use their own runtimes");
@@ -1086,7 +1104,7 @@ bool EnhanceGraph::initNgxFeatures()
}
if(!fgCompatibility_->prepareDriver(desc_.runtimeAbsPath,projectId.c_str(),engineVersion.c_str()))return false;
std::array<ID3D12Resource*,2> real={videoFrame_[0].Get(),videoFrame_[1].Get()};
- std::array<ID3D12Resource*,kGeneratedPoolSlots> generated{};
+ std::array<ID3D12Resource*,10> generated{};
for(size_t i=0;i<generated.size();++i)generated[i]=genFrame_[i].Get();
if(!fgCompatibility_->bindResources(real,generated))return false;
}
@@ -1102,8 +1120,7 @@ bool EnhanceGraph::initNgxFeatures()
return false;
}
- fgCapsAvailable_ = false;
- fgMultiFrameMax_ = 0;
+ if(!vfgBackend_){fgCapsAvailable_ = false;fgMultiFrameMax_ = 0;}
if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {
failedBackend_=engine::FailedBackend::Fg;
fgBackend_ = std::make_unique<ngx::DlssFgBackend>();
@@ -2709,6 +2726,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(reduced)out.fgSkippedBeforeEval=out.fgCandidates-fgCalls;
out.fgRecovery=runFg&&(fgHistorySkipped_||reseedRejected);
if(fgBackendAvailable&&!runFg){out.fgSkippedBeforeEval=out.fgCandidates;fgHistorySkipped_=true;}
+ if(runFg&&vfgBackend_){
+ // First timestamp precedes the producer signal/CUDA dependency wait;
+ // the matching end follows the consumer copy. The direct-queue span
+ // therefore includes actual cross-queue work, not CPU wall time.
+ gpuTimer_.mark(list,GpuStage::FgBatch);gpuTimer_.mark(list,GpuStage::Fg1);
+ tracker_.transition(list,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);
+ if(!vfgBackend_->capture(list,videoFrame_[parity].Get(),parity)){failedBackend_=engine::FailedBackend::Fg;return false;}
+ tracker_.transition(list,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
+ }
if(!runFg)gpuTimer_.resolve(list);
if (!submitGraph(slot)) return false;
if(!runFg)gpuTimer_.submitted(ring_.lastSignaledValue());
@@ -2719,6 +2745,30 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if (runFg && fgCreated()) {
for(uint32_t sub=1;sub<=fgCalls;++sub){
const uint32_t generatedSlot=parity+(sub-1)*2;
+ if(vfgBackend_){
+ // GPU producer -> CUDA interpolation -> GPU consumer. No per-frame
+ // CPU fence waits/readback; the bounded command ring owns reuse.
+ if(!vfgBackend_->generate(parity,sub,resetFg?2u:outputMultiplier,resetFg)){failedBackend_=engine::FailedBackend::Fg;return false;}
+ auto* flist=ring_.acquireNext(slot,st);if(!flist)return false;
+ tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ if(!vfgBackend_->copyOutput(flist,genFrame_[generatedSlot].Get(),generatedSlot)){failedBackend_=engine::FailedBackend::Fg;return false;}
+ tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_COMMON);
+ const auto timingStage=GpuStage(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage,true);
+ if(sub<fgCalls)gpuTimer_.mark(flist,GpuStage(unsigned(GpuStage::Fg1)+sub));
+ else{gpuTimer_.mark(flist,GpuStage::FgBatch,true);gpuTimer_.resolve(flist);}
+ if(!submitGraph(slot))return false;
+ if(sub==fgCalls)gpuTimer_.submitted(ring_.lastSignaledValue());
+ ++out.fgEvaluated;out.hasGenerated=!resetFg;out.genSlot=parity;
+ out.genFenceValue=ring_.lastSignaledValue();out.genFenceObject=context_.fence();out.generatedPtsMs=(prevPtsMs_+ptsMs)*0.5;
+ if(out.hasGenerated){
+ ++metrics_.fgSubmittedCandidates;
+ BatchFrame f;f.identity=out.batch.identity;f.kind=FrameKind::Generated;f.validity=GenerationValidity::Pending;f.subframe=sub;
+ f.pts100ns=FrameBatch::interpolate(out.batch.a100ns,out.batch.b100ns,sub,outputMultiplier);
+ f.lease=std::make_shared<FrameLease>();f.lease->texture=genFrame_[generatedSlot];f.lease->slot=generatedSlot;
+ f.lease->readyFence=out.genFenceValue;f.lease->readyFenceObject=out.genFenceObject;generatedLeases_[generatedSlot]=f.lease;out.batch.append(std::move(f));
+ }
+ continue;
+ }
auto* flist=ring_.acquireNext(slot,st); if(!flist)return false;
auto* motion=desc_.fgMotionProbe?desc_.fgMotionProbe:(haveFlow&&desc_.fgUsesFlow()?baseFlow_.Get():nrZeroMotion_.Get());
tracker_.transition(flist,videoFrame_[parity].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
@@ -2818,7 +2868,7 @@ bool EnhanceGraph::resolveFrame(FrameOutputs& out,uint32_t index)
auto& frame=out.batch.frames[index];
if(!frame.lease||!frame.lease->ready())return false;
if(frame.kind!=FrameKind::Generated||frame.validity!=GenerationValidity::Pending)return true;
- if(fsrActive()){
+ if(fsrActive()||vfgBackend_){
frame.validity=out.contentDuplicate?GenerationValidity::Disabled:GenerationValidity::Valid;
if(out.contentDuplicate){++metrics_.fgDisabledFrames;++metrics_.fgDuplicateSuppressed;}else ++metrics_.fgGeneratedFrames;
return true;
@@ -2888,7 +2938,7 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
// DLSS allocates multiplier-specific feature/output resources.
// XeSS has a fixed 2X proxy swapchain contract. Settings callers must
// rebuild instead of accepting a change that cannot take effect in place.
- if(s.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend==engine::FrameGenerationBackend::Dlss&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;
+ if(s.nrRuntime!=desc_.nrRuntime||std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||s.vfgQuality!=desc_.vfgQuality||s.videoSrQuality!=desc_.videoSrQuality||!s.validate().empty()||(s.multiplier>1&&s.frameGenerationBackend==engine::FrameGenerationBackend::Dlss&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;
// The colour master switch changes the graph shape (tables + shader branch)
// and must rebuild; every other colour field is a live uniform update.
if(s.color.enabled!=desc_.color.enabled)return false;
@@ -2974,7 +3024,7 @@ ID3D12Fence* EnhanceGraph::contextFence()const{return context_.fence();}
uint32_t EnhanceGraph::actualFlowPerf()const{return nvof_?nvof_->caps().actualPerfLevel:0;}
bool EnhanceGraph::fgCreated() const
{
- return fsrActive() || (fgBackend_ && fgBackend_->created());
+ return (vfgBackend_&&vfgBackend_->created()) || fsrActive() || (fgBackend_ && fgBackend_->created());
}
uint64_t EnhanceGraph::lastNvofSignal() const
@@ -3038,6 +3088,7 @@ void EnhanceGraph::shutdown()
fsrSrZeroMotion_.Reset();upFsrSrZeroMotion_.Reset();
upFsrSrDepth_.Reset();
fsrFgBackend_.reset();
+ vfgBackend_.reset();
if (fgBackend_) fgBackend_->release();
if(videoSrBackend_){videoSrBackend_->release();videoSrBackend_.reset();}
videoHdrBackend_.reset();videoHdrInput_.Reset();videoHdrOutput_.Reset();
diff --git a/src/pipeline/VfgBackend.cpp b/src/pipeline/VfgBackend.cpp
new file mode 100644
index 00000000..2a539c56
--- /dev/null
+++ b/src/pipeline/VfgBackend.cpp
@@ -0,0 +1,331 @@
+#include "veyra/pipeline/VfgBackend.h"
+#include "veyra/pipeline/FrameBatch.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/Log.h"
+#include <Windows.h>
+#include <array>
+#include <filesystem>
+#include <format>
+#include <vector>
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+#include <cuda.h>
+#endif
+
+namespace veyra::pipeline {
+namespace {
+namespace fs=std::filesystem;
+constexpr unsigned kOutputs=2*(FrameBatch::Capacity-1);
+constexpr DWORD kDllFlags=LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32|LOAD_LIBRARY_SEARCH_USER_DIRS;
+bool regularFile(const fs::path& path){std::error_code error;return fs::is_regular_file(path,error);}
+HMODULE load(const fs::path& path){
+ const auto dll=LoadLibraryExW(path.c_str(),nullptr,kDllFlags);
+ if(!dll){const auto error=GetLastError();const auto bytes=path.u8string();
+ log::error("vfg",std::format("LoadLibrary failed path={} win32={}",std::string(reinterpret_cast<const char*>(bytes.data()),bytes.size()),error));}
+ return dll;
+}
+template<class T> bool bind(HMODULE dll,const char* name,T& fn){
+ fn=reinterpret_cast<T>(GetProcAddress(dll,name));
+ if(!fn)log::error("vfg",std::format("missing API {} win32={}",name,GetLastError()));
+ return fn!=nullptr;
+}
+bool hr(HRESULT value,const char* operation){
+ if(SUCCEEDED(value))return true;
+ log::error("vfg",std::format("{} HRESULT=0x{:08X}",operation,unsigned(value)));return false;
+}
+}
+
+std::wstring VfgBackend::runtimeDirectory(const std::wstring& root){
+ std::array<wchar_t,32768> overridePath{};
+ const auto size=GetEnvironmentVariableW(L"VEYRA_VFG_RUNTIME",overridePath.data(),DWORD(overridePath.size()));
+ if(size){
+ if(size>=overridePath.size()||!fs::path(overridePath.data()).is_absolute())return {};
+ return fs::path(overridePath.data()).lexically_normal().wstring();
+ }
+ if(!fs::path(root).is_absolute())return {};
+ const std::array<fs::path,3> choices={fs::path(root)/L"vfg",fs::path(root).parent_path()/L"nvidia-vfg",fs::path(root)};
+ for(const auto& directory:choices)if(regularFile(directory/L"NVVideoEffects.dll"))return directory.lexically_normal().wstring();
+ return choices[0].lexically_normal().wstring();
+}
+bool VfgBackend::runtimeAvailable(const std::wstring& root){
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ const auto directory=runtimeDirectory(root);
+ return !directory.empty()&&regularFile(fs::path(directory)/L"NVVideoEffects.dll")&&
+ regularFile(fs::path(directory)/L"NVCVImage.dll")&&
+ regularFile(fs::path(directory)/L"nvVFXVideoFrameGeneration.dll");
+#else
+ return false;
+#endif
+}
+
+struct VfgBackend::Impl {
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ // Only function signatures from the public C API. NVCV owns its opaque
+ // image descriptors; format conversion and the tested RGB10A2/P32 mapping
+ // do not duplicate proprietary image struct definitions.
+ int (__cdecl* create)(const char*,void**)=nullptr;
+ void (__cdecl* destroy)(void*)=nullptr;
+ int (__cdecl* setU32)(void*,const char*,unsigned)=nullptr;
+ int (__cdecl* setImage)(void*,const char*,void*)=nullptr;
+ int (__cdecl* setStream)(void*,const char*,CUstream)=nullptr;
+ int (__cdecl* loadEffect)(void*)=nullptr;
+ int (__cdecl* run)(void*,int)=nullptr;
+ int (__cdecl* getVersion)(unsigned*)=nullptr;
+ int (__cdecl* imageCreate)(unsigned,unsigned,int,int,unsigned,unsigned,unsigned,void**)=nullptr;
+ void (__cdecl* imageDealloc)(void*)=nullptr;
+ void (__cdecl* imageDestroy)(void*)=nullptr;
+ int (__cdecl* imageInit)(void*,unsigned,unsigned,int,void*,int,int,unsigned,unsigned)=nullptr;
+ int (__cdecl* fromD3D)(DXGI_FORMAT,int*,int*,unsigned char*)=nullptr;
+ const char* (__cdecl* errorString)(int)=nullptr;
+#define CU_FN(name) decltype(&name) name##Fn=nullptr
+ CU_FN(cuInit);CU_FN(cuDeviceGetCount);CU_FN(cuDeviceGet);CU_FN(cuDeviceGetLuid);CU_FN(cuDeviceGetAttribute);
+ CU_FN(cuDevicePrimaryCtxRetain);CU_FN(cuDevicePrimaryCtxRelease);CU_FN(cuCtxPushCurrent);CU_FN(cuCtxPopCurrent);
+ CU_FN(cuStreamCreate);CU_FN(cuStreamDestroy);CU_FN(cuStreamSynchronize);
+ CU_FN(cuImportExternalMemory);CU_FN(cuExternalMemoryGetMappedBuffer);CU_FN(cuDestroyExternalMemory);CU_FN(cuMemFree);
+ CU_FN(cuImportExternalSemaphore);CU_FN(cuDestroyExternalSemaphore);CU_FN(cuWaitExternalSemaphoresAsync);CU_FN(cuSignalExternalSemaphoresAsync);
+ CU_FN(cuGetErrorName);CU_FN(cuGetErrorString);
+#undef CU_FN
+ struct Buffer {
+ Microsoft::WRL::ComPtr<ID3D12Resource> resource;
+ CUexternalMemory memory=nullptr;
+ CUdeviceptr pointer=0;
+ void* image=nullptr;
+ };
+ std::array<Buffer,2> inputs;
+ std::array<Buffer,kOutputs> outputs;
+ gfx::D3D12DeviceContext* context=nullptr;
+ Microsoft::WRL::ComPtr<ID3D12Fence> producer,completion;
+ CUexternalSemaphore inputSemaphore=nullptr,outputSemaphore=nullptr;
+ CUcontext cudaContext=nullptr;CUstream stream=nullptr;CUdevice device=0;
+ bool retained=false;
+ void* effect=nullptr;
+ std::vector<HMODULE> libraries;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
+ uint64_t bytes=0,signalValue=0;
+ unsigned width=0,height=0,maxMultiplier=2;
+ DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN;
+ bool ready=false;
+ bool cv(int code,const char* name){
+ if(code==0)return true;
+ log::error("vfg",std::format("{} status={} detail={}",name,code,errorString?errorString(code):"unavailable"));return false;
+ }
+ bool cu(CUresult code,const char* name){
+ if(code==CUDA_SUCCESS)return true;
+ const char* label=nullptr;const char* detail=nullptr;
+ if(cuGetErrorNameFn)cuGetErrorNameFn(code,&label);
+ if(cuGetErrorStringFn)cuGetErrorStringFn(code,&detail);
+ log::error("vfg-cuda",std::format("{} result={} name={} detail={}",name,unsigned(code),label?label:"?",detail?detail:"?"));return false;
+ }
+ struct Current {
+ Impl& owner;bool active=false;
+ explicit Current(Impl& p):owner(p){active=p.cu(p.cuCtxPushCurrentFn(p.cudaContext),"cuCtxPushCurrent");}
+ ~Current(){if(active){CUcontext previous=nullptr;owner.cu(owner.cuCtxPopCurrentFn(&previous),"cuCtxPopCurrent");}}
+ };
+ bool importFence(ID3D12Fence* fence,CUexternalSemaphore& semaphore){
+ HANDLE handle=nullptr;
+ if(!hr(context->device()->CreateSharedHandle(fence,nullptr,GENERIC_ALL,nullptr,&handle),"CreateSharedHandle fence"))return false;
+ CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC desc{};desc.type=CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE;desc.handle.win32.handle=handle;
+ const auto code=cuImportExternalSemaphoreFn(&semaphore,&desc);CloseHandle(handle);
+ return cu(code,"cuImportExternalSemaphore");
+ }
+ bool makeBuffer(Buffer& buffer,int pixelFormat,int componentType,unsigned layout){
+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_RESOURCE_DESC desc{};desc.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;desc.Width=bytes;desc.Height=1;
+ desc.DepthOrArraySize=1;desc.MipLevels=1;desc.SampleDesc.Count=1;desc.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ if(!hr(context->device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_SHARED,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&buffer.resource)),"Create shared buffer"))return false;
+ HANDLE handle=nullptr;
+ if(!hr(context->device()->CreateSharedHandle(buffer.resource.Get(),nullptr,GENERIC_ALL,nullptr,&handle),"CreateSharedHandle buffer"))return false;
+ CUDA_EXTERNAL_MEMORY_HANDLE_DESC imported{};
+ imported.type=CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE;imported.handle.win32.handle=handle;
+ imported.size=context->device()->GetResourceAllocationInfo(0,1,&desc).SizeInBytes;imported.flags=CUDA_EXTERNAL_MEMORY_DEDICATED;
+ const auto code=cuImportExternalMemoryFn(&buffer.memory,&imported);CloseHandle(handle);
+ if(!cu(code,"cuImportExternalMemory"))return false;
+ CUDA_EXTERNAL_MEMORY_BUFFER_DESC mapped{};mapped.size=bytes;
+ if(!cu(cuExternalMemoryGetMappedBufferFn(&buffer.pointer,buffer.memory,&mapped),"cuExternalMemoryGetMappedBuffer"))return false;
+ // Allocate descriptor storage through the SDK and release its tiny owned
+ // pixel allocation before binding the borrowed CUDA mapping. Init does
+ // not transfer ownership of external pixels to NvCVImage_Destroy.
+ if(!cv(imageCreate(1,1,pixelFormat,componentType,layout,0,1,&buffer.image),"NvCVImage_Create"))return false;
+ imageDealloc(buffer.image);
+ if(!cv(imageInit(buffer.image,width,height,int(footprint.Footprint.RowPitch),reinterpret_cast<void*>(buffer.pointer),pixelFormat,componentType,layout,1),"NvCVImage_Init"))return false;
+ return true;
+ }
+ void releaseBuffer(Buffer& buffer){
+ if(buffer.image){imageDestroy(buffer.image);buffer.image=nullptr;}
+ if(buffer.pointer){cu(cuMemFreeFn(buffer.pointer),"cuMemFree external mapping");buffer.pointer=0;}
+ if(buffer.memory){cu(cuDestroyExternalMemoryFn(buffer.memory),"cuDestroyExternalMemory");buffer.memory=nullptr;}
+ buffer.resource.Reset();
+ }
+ bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
+ Current current(*this);if(!current.active)return false;
+ const uint64_t value=++signalValue;
+ if(!hr(context->directQueue()->Signal(producer.Get(),value),"signal VFG producer"))return false;
+ CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS wait{};wait.params.fence.value=value;
+ if(!cu(cuWaitExternalSemaphoresAsyncFn(&inputSemaphore,&wait,1,stream),"cuWaitExternalSemaphoresAsync"))return false;
+ bool ok=cv(setImage(effect,"SrcImage0",inputs[reset?parity:1-parity].image),"SetImage previous")&&
+ cv(setImage(effect,"SrcImage1",inputs[parity].image),"SetImage current")&&
+ cv(setImage(effect,"DstImage0",outputs[parity+2*(sub-1)].image),"SetImage output")&&
+ cv(setU32(effect,"ShotChange",reset?1u:0u),"SetU32 ShotChange")&&
+ cv(setU32(effect,"FrameMultiplier",multiplier),"SetU32 FrameMultiplier")&&
+ cv(setU32(effect,"FrameIndex",sub),"SetU32 FrameIndex")&&cv(run(effect,1),"NvVFX_Run async");
+ // Complete the ownership handoff even after a synchronous SDK rejection;
+ // never leave the direct queue waiting on a signal we did not enqueue.
+ CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS signal{};signal.params.fence.value=value;
+ if(!cu(cuSignalExternalSemaphoresAsyncFn(&outputSemaphore,&signal,1,stream),"cuSignalExternalSemaphoresAsync"))return false;
+ if(!hr(context->directQueue()->Wait(completion.Get(),value),"queue wait VFG completion"))return false;
+ return ok;
+ }
+#endif
+};
+VfgBackend::VfgBackend():impl_(std::make_unique<Impl>()){}
+VfgBackend::~VfgBackend(){shutdown();}
+
+bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring& root,unsigned width,unsigned height,DXGI_FORMAT format,unsigned multiplier,unsigned quality){
+ shutdown();
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ auto& p=*impl_;
+ if(context.adapter().vendorId!=0x10DE||!runtimeAvailable(root)||!width||!height||multiplier<2||multiplier>FrameBatch::Capacity||quality>2||
+ (format!=DXGI_FORMAT_R8G8B8A8_UNORM&&format!=DXGI_FORMAT_R10G10B10A2_UNORM)){
+ log::error("vfg","unsupported adapter/runtime/dimensions/multiplier/quality/encoding");return false;
+ }
+ p.context=&context;p.width=width;p.height=height;p.format=format;p.maxMultiplier=multiplier;
+ std::array<wchar_t,32768> system{};const auto n=GetSystemDirectoryW(system.data(),UINT(system.size()));if(!n||n>=system.size())return false;
+ HMODULE driver=load(fs::path(system.data())/L"nvcuda.dll");if(!driver)return false;p.libraries.push_back(driver);
+#define BIND_CU(name,exported) if(!bind(driver,exported,p.name##Fn))return false
+ BIND_CU(cuInit,"cuInit");BIND_CU(cuDeviceGetCount,"cuDeviceGetCount");BIND_CU(cuDeviceGet,"cuDeviceGet");BIND_CU(cuDeviceGetLuid,"cuDeviceGetLuid");BIND_CU(cuDeviceGetAttribute,"cuDeviceGetAttribute");
+ BIND_CU(cuDevicePrimaryCtxRetain,"cuDevicePrimaryCtxRetain");BIND_CU(cuDevicePrimaryCtxRelease,"cuDevicePrimaryCtxRelease_v2");
+ BIND_CU(cuCtxPushCurrent,"cuCtxPushCurrent_v2");BIND_CU(cuCtxPopCurrent,"cuCtxPopCurrent_v2");
+ BIND_CU(cuStreamCreate,"cuStreamCreate");BIND_CU(cuStreamDestroy,"cuStreamDestroy_v2");BIND_CU(cuStreamSynchronize,"cuStreamSynchronize");
+ BIND_CU(cuImportExternalMemory,"cuImportExternalMemory");BIND_CU(cuExternalMemoryGetMappedBuffer,"cuExternalMemoryGetMappedBuffer");
+ BIND_CU(cuDestroyExternalMemory,"cuDestroyExternalMemory");BIND_CU(cuMemFree,"cuMemFree_v2");
+ BIND_CU(cuImportExternalSemaphore,"cuImportExternalSemaphore");BIND_CU(cuDestroyExternalSemaphore,"cuDestroyExternalSemaphore");
+ BIND_CU(cuWaitExternalSemaphoresAsync,"cuWaitExternalSemaphoresAsync");BIND_CU(cuSignalExternalSemaphoresAsync,"cuSignalExternalSemaphoresAsync");
+ BIND_CU(cuGetErrorName,"cuGetErrorName");BIND_CU(cuGetErrorString,"cuGetErrorString");
+#undef BIND_CU
+ if(!p.cu(p.cuInitFn(0),"cuInit"))return false;
+ int count=0;if(!p.cu(p.cuDeviceGetCountFn(&count),"cuDeviceGetCount"))return false;
+ bool matched=false;
+ for(int i=0;i<count;++i){CUdevice device=0;uint64_t luid=0;unsigned node=0;
+ if(!p.cu(p.cuDeviceGetFn(&device,i),"cuDeviceGet")||!p.cu(p.cuDeviceGetLuidFn(reinterpret_cast<char*>(&luid),&node,device),"cuDeviceGetLuid"))return false;
+ if(luid==context.adapter().luid&&node){p.device=device;matched=true;break;}
+ }
+ if(!matched){log::error("vfg","CUDA/D3D12 adapter LUID mismatch");return false;}
+ int major=0,minor=0;
+ if(!p.cu(p.cuDeviceGetAttributeFn(&major,CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR,p.device),"compute major")||
+ !p.cu(p.cuDeviceGetAttributeFn(&minor,CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR,p.device),"compute minor"))return false;
+ if(!((major==8&&minor==9)||major==12)){log::error("vfg",std::format("Windows VFG requires Ada/Blackwell; compute={}.{}",major,minor));return false;}
+ if(!p.cu(p.cuDevicePrimaryCtxRetainFn(&p.cudaContext,p.device),"cuDevicePrimaryCtxRetain"))return false;p.retained=true;
+ Impl::Current current(p);if(!current.active)return false;
+ if(!p.cu(p.cuStreamCreateFn(&p.stream,CU_STREAM_NON_BLOCKING),"cuStreamCreate"))return false;
+ const fs::path runtime=runtimeDirectory(root);
+ const std::array<const wchar_t*,15> dependencies={L"cudart64_12.dll",L"nppc64_12.dll",L"nppial64_12.dll",L"nppicc64_12.dll",L"nppidei64_12.dll",L"nppif64_12.dll",L"nppig64_12.dll",L"nppim64_12.dll",L"nppist64_12.dll",L"nppitc64_12.dll",L"NVCVImage.dll",L"nvngxruntime.dll",L"NVVideoEffects.dll",L"nvVFXVideoFrameGeneration.dll",nullptr};
+ HMODULE core=nullptr,image=nullptr;
+ for(auto name:dependencies){if(!name)continue;auto dll=load(runtime/name);if(!dll)return false;p.libraries.push_back(dll);
+ if(std::wstring_view(name)==L"NVVideoEffects.dll")core=dll;if(std::wstring_view(name)==L"NVCVImage.dll")image=dll;}
+#define BIND_VFX(member,name) if(!bind(core,name,p.member))return false
+ BIND_VFX(create,"NvVFX_CreateEffect");BIND_VFX(destroy,"NvVFX_DestroyEffect");BIND_VFX(setU32,"NvVFX_SetU32");BIND_VFX(setImage,"NvVFX_SetImage");
+ BIND_VFX(setStream,"NvVFX_SetCudaStream");BIND_VFX(loadEffect,"NvVFX_Load");BIND_VFX(run,"NvVFX_Run");BIND_VFX(getVersion,"NvVFX_GetVersion");
+#undef BIND_VFX
+#define BIND_IMAGE(member,name) if(!bind(image,name,p.member))return false
+ BIND_IMAGE(imageCreate,"NvCVImage_Create");BIND_IMAGE(imageDealloc,"NvCVImage_Dealloc");BIND_IMAGE(imageDestroy,"NvCVImage_Destroy");
+ BIND_IMAGE(imageInit,"NvCVImage_Init");BIND_IMAGE(fromD3D,"NvCVImage_FromD3DFormat");BIND_IMAGE(errorString,"NvCV_GetErrorStringFromCode");
+#undef BIND_IMAGE
+ unsigned version=0;if(!p.cv(p.getVersion(&version),"NvVFX_GetVersion"))return false;
+ log::info("vfg",std::format("SDK version=0x{:08X} LUID={} compute={}.{} size={}x{} multiplier={} quality={} async=1",version,context.adapter().luidString,major,minor,width,height,multiplier,quality));
+ D3D12_RESOURCE_DESC texture{};texture.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;texture.Width=width;texture.Height=height;texture.DepthOrArraySize=1;texture.MipLevels=1;texture.Format=format;texture.SampleDesc.Count=1;
+ UINT rows=0;uint64_t rowBytes=0,total=0;context.device()->GetCopyableFootprints(&texture,0,1,0,&p.footprint,&rows,&rowBytes,&total);
+ p.bytes=uint64_t(p.footprint.Footprint.RowPitch)*height;
+ int pixelFormat=0,componentType=0;unsigned char layout=0;
+ if(format==DXGI_FORMAT_R10G10B10A2_UNORM){
+ // SDK 1.3's older FromD3DFormat helper rejects this DXGI format. The
+ // packed NvCV API uses the appended RGB10A2=13 and P32=11 (interleaved).
+ // NvCVImage_Create/Init and Load admit this pair; the GPU identity test
+ // additionally verifies the actual R10/G10/B10/A2 bit layout.
+ pixelFormat=13;componentType=11;layout=0;
+ }else if(!p.cv(p.fromD3D(format,&pixelFormat,&componentType,&layout),"NvCVImage_FromD3DFormat"))return false;
+ log::info("vfg",std::format("encoded format={} NvCV pixel={} component={} layout={} pitch={} sharedBytes={}",unsigned(format),pixelFormat,componentType,layout,p.footprint.Footprint.RowPitch,p.bytes*(2+2*(multiplier-1))));
+ for(auto& buffer:p.inputs)if(!p.makeBuffer(buffer,pixelFormat,componentType,layout))return false;
+ for(unsigned i=0;i<2*(multiplier-1);++i)if(!p.makeBuffer(p.outputs[i],pixelFormat,componentType,layout))return false;
+ if(!hr(context.device()->CreateFence(0,D3D12_FENCE_FLAG_SHARED,IID_PPV_ARGS(&p.producer)),"CreateFence producer")||
+ !hr(context.device()->CreateFence(0,D3D12_FENCE_FLAG_SHARED,IID_PPV_ARGS(&p.completion)),"CreateFence completion")||
+ !p.importFence(p.producer.Get(),p.inputSemaphore)||!p.importFence(p.completion.Get(),p.outputSemaphore))return false;
+ if(!p.cv(p.create("VideoFrameGeneration",&p.effect),"NvVFX_CreateEffect")||
+ !p.cv(p.setStream(p.effect,"CudaStream",p.stream),"SetCudaStream")||
+ !p.cv(p.setU32(p.effect,"InputWidth",width),"InputWidth")||!p.cv(p.setU32(p.effect,"InputHeight",height),"InputHeight")||
+ !p.cv(p.setU32(p.effect,"Mode",quality),"Mode")||!p.cv(p.setU32(p.effect,"AutomaticShotChangeDetectionEnabled",1),"AutomaticShotChangeDetectionEnabled")||
+ !p.cv(p.setImage(p.effect,"SrcImage0",p.inputs[0].image),"initial previous")||!p.cv(p.setImage(p.effect,"SrcImage1",p.inputs[1].image),"initial current")||
+ !p.cv(p.loadEffect(p.effect),"NvVFX_Load")||!p.cv(p.setImage(p.effect,"DstImage0",p.outputs[0].image),"initial output")||
+ !p.cv(p.setU32(p.effect,"FrameMultiplier",multiplier),"initial multiplier"))return false;
+ p.ready=true;log::info("vfg","native VFG initialized; GPU-only D3D12 buffer/fence bridge");return true;
+#else
+ (void)context;(void)root;(void)width;(void)height;(void)format;(void)multiplier;(void)quality;
+ log::error("vfg","VFG unavailable: configure VEYRA_CUDA_DRIVER_INCLUDE_DIR");return false;
+#endif
+}
+bool VfgBackend::created()const{
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ return impl_->ready;
+#else
+ return false;
+#endif
+}
+bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture,unsigned parity){
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ auto& p=*impl_;if(!p.ready||!list||!texture||parity>1)return false;
+ const auto desc=texture->GetDesc();if(desc.Width!=p.width||desc.Height!=p.height||desc.Format!=p.format)return false;
+ auto* buffer=p.inputs[parity].resource.Get();
+ D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={buffer,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST};
+ list->ResourceBarrier(1,&barrier);
+ D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=texture;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=buffer;dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=p.footprint;
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);return true;
+#else
+ (void)list;(void)texture;(void)parity;return false;
+#endif
+}
+bool VfgBackend::generate(unsigned parity,unsigned sub,unsigned multiplier,bool reset){
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ auto& p=*impl_;if(!p.ready||parity>1||multiplier<2||multiplier>p.maxMultiplier||sub<1||sub>=multiplier)return false;
+ return p.handoff(parity,sub,multiplier,reset);
+#else
+ (void)parity;(void)sub;(void)multiplier;(void)reset;return false;
+#endif
+}
+bool VfgBackend::copyOutput(ID3D12GraphicsCommandList* list,ID3D12Resource* texture,unsigned slot){
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ auto& p=*impl_;if(!p.ready||!list||!texture||slot>=2*(p.maxMultiplier-1))return false;
+ const auto desc=texture->GetDesc();if(desc.Width!=p.width||desc.Height!=p.height||desc.Format!=p.format)return false;
+ auto* buffer=p.outputs[slot].resource.Get();
+ D3D12_RESOURCE_BARRIER barrier{};barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;barrier.Transition={buffer,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE};
+ list->ResourceBarrier(1,&barrier);
+ D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=buffer;src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint=p.footprint;
+ D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=texture;dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);list->ResourceBarrier(1,&barrier);return true;
+#else
+ (void)list;(void)texture;(void)slot;return false;
+#endif
+}
+void VfgBackend::shutdown(){
+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS
+ auto& p=*impl_;p.ready=false;
+ if(p.cudaContext&&p.cuCtxPushCurrentFn&&p.cuCtxPopCurrentFn){
+ Impl::Current current(p);
+ if(current.active){
+ // This is teardown, not per-frame synchronization. The graph owner
+ // drains its direct queue before destroying shared staging buffers.
+ if(p.stream)p.cu(p.cuStreamSynchronizeFn(p.stream),"teardown cuStreamSynchronize");
+ if(p.effect){p.destroy(p.effect);p.effect=nullptr;log::info("vfg","NvVFX_DestroyEffect completed (void API)");}
+ for(auto& b:p.outputs)p.releaseBuffer(b);for(auto& b:p.inputs)p.releaseBuffer(b);
+ if(p.outputSemaphore)p.cu(p.cuDestroyExternalSemaphoreFn(p.outputSemaphore),"destroy output semaphore");
+ if(p.inputSemaphore)p.cu(p.cuDestroyExternalSemaphoreFn(p.inputSemaphore),"destroy input semaphore");
+ if(p.stream)p.cu(p.cuStreamDestroyFn(p.stream),"cuStreamDestroy");
+ }
+ }
+ if(p.retained)p.cu(p.cuDevicePrimaryCtxReleaseFn(p.device),"cuDevicePrimaryCtxRelease");
+ p.producer.Reset();p.completion.Reset();
+ for(auto i=p.libraries.rbegin();i!=p.libraries.rend();++i)FreeLibrary(*i);
+ impl_=std::make_unique<Impl>();
+#endif
+}
+}
diff --git a/src/ui/PlayerUiFacade.cpp b/src/ui/PlayerUiFacade.cpp
index 64a9383c..eb90875e 100644
--- a/src/ui/PlayerUiFacade.cpp
+++ b/src/ui/PlayerUiFacade.cpp
@@ -82,11 +82,22 @@ PlayerUiFacade::Frame PlayerUiFacade::poll() {
}
// A GPU/provider failure arrives after command admission. Match the exact
// accepted revision so a stale rejection cannot overwrite a newer choice.
- // Reconcile only the FG pair; unrelated editable controls stay untouched.
- if(pendingFgRevision_&&snapshot.rejectedRevision==pendingFgRevision_&&
- pending_.frameGenerationBackend==requestedFgBackend_&&pending_.multiplier==requestedFgMultiplier_){
+ // Opening a source assigns a new revision to the already accepted request.
+ // VFG startup/runtime recovery keeps that revision and disables only FG.
+ // Never reconcile a rejection older than the UI's latest accepted edit.
+ const bool recoveredVfg=snapshot.rejectedRevision>=pendingFgRevision_&&
+ snapshot.desired.revision==snapshot.rejectedRevision&&
+ requestedFgBackend_==veyra::engine::FrameGenerationBackend::Vfg&&
+ snapshot.desired.frameGenerationBackend==requestedFgBackend_&&
+ snapshot.desired.vfgQuality==requestedVfgQuality_&&
+ requestedFgMultiplier_>1&&snapshot.desired.multiplier==1&&
+ !snapshot.backendWarning.empty();
+ if(pendingFgRevision_&&(snapshot.rejectedRevision==pendingFgRevision_||recoveredVfg)&&
+ pending_.frameGenerationBackend==requestedFgBackend_&&pending_.multiplier==requestedFgMultiplier_&&
+ pending_.vfgQuality==requestedVfgQuality_){
pending_.frameGenerationBackend=snapshot.desired.frameGenerationBackend;
- pending_.multiplier=snapshot.desired.multiplier;pendingFgRevision_=0;
+ pending_.multiplier=snapshot.desired.multiplier;
+ pending_.vfgQuality=snapshot.desired.vfgQuality;pendingFgRevision_=0;
veyra::log::info("ui-fg-rollback",std::format("rejectedRevision={} restoredBackend={} restoredMultiplier={}",
snapshot.rejectedRevision,int(pending_.frameGenerationBackend),pending_.multiplier));
}
@@ -113,6 +124,7 @@ bool PlayerUiFacade::applySettings(const veyra::engine::EnhancementSettings& set
pendingFgRevision_=acceptedRevision;
pendingNrRevision_=acceptedRevision;requestedNrRuntime_=settings.nrRuntime;
requestedFgBackend_=settings.frameGenerationBackend;requestedFgMultiplier_=settings.multiplier;
+ requestedVfgQuality_=settings.vfgQuality;
return true;
}
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index 67a40048..2297e3fe 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -36,10 +36,12 @@
#include <cmath>
#include <limits>
#include <optional>
+#include <span>
#include <vector>
#include "veyra/Log.h"
#include "veyra/RuntimePaths.h"
+#include "veyra/pipeline/VfgBackend.h"
#include "veyra/engine/ColorLookStore.h"
#include "veyra/engine/ColorLut.h"
#include "veyra/engine/Subtitles.h"
@@ -567,7 +569,7 @@ struct QmlPlayerBridge::Impl {
const auto before=facade.pendingSettings();
auto frame = facade.poll();
const auto restored=facade.pendingSettings();
- const bool fgRollback=before.frameGenerationBackend!=restored.frameGenerationBackend||before.multiplier!=restored.multiplier;
+ const bool fgRollback=before.frameGenerationBackend!=restored.frameGenerationBackend||before.multiplier!=restored.multiplier||before.vfgQuality!=restored.vfgQuality;
const bool nrRollback=before.nrRuntime!=restored.nrRuntime;
if(nrRollback) {
for(auto* c:{&chain,&acceptedChain})for(uint32_t i=0;i<c->nodeCount;++i)
@@ -581,6 +583,7 @@ struct QmlPlayerBridge::Impl {
};
restoreFg(chain);restoreFg(acceptedChain);
if(draftGlobals.fgBackend==before.frameGenerationBackend)draftGlobals.fgBackend=restored.frameGenerationBackend;
+ if(draftGlobals.vfgQuality==before.vfgQuality)draftGlobals.vfgQuality=restored.vfgQuality;
options=engine::PlayerOptions::from(restored,engine::runtimeOrder(acceptedChain));
}
if (!frame.changed && haveSnapshot) return fgRollback||nrRollback;
@@ -650,8 +653,10 @@ struct QmlPlayerBridge::Impl {
if (!projected->firstOf(engine::EffectType::SuperResolution)) {
s.srTarget = previous.srTarget; s.videoSrQuality = previous.videoSrQuality;
}
- if (!projected->firstOf(engine::EffectType::FrameGeneration))
+ if (!projected->firstOf(engine::EffectType::FrameGeneration)){
s.frameGenerationBackend = previous.frameGenerationBackend;
+ s.vfgQuality = previous.vfgQuality;
+ }
}
engine::fromChain(*projected, s);
if(const auto error=s.validate();!error.empty()){
@@ -757,6 +762,26 @@ static uint32_t primaryGpuVendor() {
// FSR 4 ML frame generation needs an AMD RX 9000; on other GPUs the provider crashed the
// whole program (field report 2026-10-01). Known non-AMD adapters are refused up front.
static bool fsr4Possible() { const auto v = primaryGpuVendor(); return v == 0 || v == 0x1002; }
+// The menu checks the same default DXGI preference as the engine. The native
+// backend then verifies CUDA compute capability and the exact adapter LUID.
+static bool vfgHardwarePossible(){
+ static const bool supported=[] {
+ Microsoft::WRL::ComPtr<IDXGIFactory6> factory;
+ if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))return false;
+ for(UINT i=0;;++i){Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
+ if(factory->EnumAdapterByGpuPreference(i,DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,IID_PPV_ARGS(&adapter))==DXGI_ERROR_NOT_FOUND)break;
+ if(!adapter)break;DXGI_ADAPTER_DESC1 d{};
+ if(FAILED(adapter->GetDesc1(&d))||(d.Flags&DXGI_ADAPTER_FLAG_SOFTWARE)||FAILED(D3D12CreateDevice(adapter.Get(),D3D_FEATURE_LEVEL_12_0,__uuidof(ID3D12Device),nullptr)))continue;
+ const auto name=QString::fromWCharArray(d.Description);
+ return d.VendorId==0x10DE&&(name.contains(QStringLiteral("GeForce RTX 40"),Qt::CaseInsensitive)||
+ name.contains(QStringLiteral("GeForce RTX 50"),Qt::CaseInsensitive)||name.contains(QStringLiteral("Ada"),Qt::CaseInsensitive)||name.contains(QStringLiteral("Blackwell"),Qt::CaseInsensitive));
+ }return false;
+ }();return supported;
+}
+static unsigned normalizeFgMultiplier(unsigned value,engine::FrameGenerationBackend backend,unsigned cap){
+ value=std::clamp(value,2u,cap);
+ return backend==engine::FrameGenerationBackend::Dlss&&value==5?4u:value;
+}
bool QmlPlayerBridge::amdNrGpu() const { return primaryGpuVendor()==0x1002; }
QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystem::path dataDirectory,
@@ -1156,7 +1181,7 @@ QVariantList QmlPlayerBridge::stageTimings() const {
{"光流", Stage::Flow, "#9A85FF"},
{"NR采样", Stage::Nr, "#FF8A3D"},
{"残差", Stage::Residual, "#E7B868"},
- {"DLSS FG", Stage::FgBatch, "#3DDC84"},
+ {"FG", Stage::FgBatch, "#3DDC84"},
{"HDR", Stage::VideoHdr, "#E58BD9"},
{"呈现", Stage::Blit, "#58CAD4"},
};
@@ -1313,6 +1338,7 @@ QString QmlPlayerBridge::fgBackendName() const {
case engine::FrameGenerationBackend::XeSS:return QStringLiteral("xess");
case engine::FrameGenerationBackend::Fsr:return QStringLiteral("fsr3");
case engine::FrameGenerationBackend::Fsr4:return QStringLiteral("fsr4");
+ case engine::FrameGenerationBackend::Vfg:return QStringLiteral("vfg");
}
return {};
}
@@ -1321,11 +1347,17 @@ QVariantList QmlPlayerBridge::fgBackendChoices() const {
QVariantMap{{"id","dlss"},{"label",tr("DLSS 帧生成")}},
QVariantMap{{"id","xess"},{"label",tr("Intel XeSS · 实验")}},
QVariantMap{{"id","fsr3"},{"label",tr("FSR 3.1 · 2X")}},
- QVariantMap{{"id","fsr4"},{"label",tr("FSR 4 ML · RX 9000 · 实验")}}
+ QVariantMap{{"id","fsr4"},{"label",tr("FSR 4 ML · RX 9000 · 实验")}},
+ QVariantMap{{"id","vfg"},{"label",tr("NVIDIA VFG · RTX 40 / 50")}}
};
}
QString QmlPlayerBridge::fgProviderText() const {
const auto& s=impl_->snapshot;
+ if(fgBackendName()==QLatin1String("vfg")){
+ if(!vfgHardwarePossible())return tr("VFG 需要 NVIDIA Ada / Blackwell 显卡(RTX 40 / 50)");
+ if(!pipeline::VfgBackend::runtimeAvailable(runtime::localRuntimeDirectory().wstring()))return tr("未找到 VFG 运行组件,请在组件页核对路径");
+ return tr("VFG 支持 2X~8X 和低 / 中 / 高质量;6X~8X 为实验档,高倍高质量会增加处理时间");
+ }
if(engine::fsrFrameGeneration(s.applied.frameGenerationBackend)&&s.applied.multiplier>1&&!s.fsrProviderVersion.empty())
return tr("实际运行:FSR %1 · 2X").arg(QString::fromStdString(s.fsrProviderVersion));
if(fgBackendName()==QLatin1String("fsr4"))return tr("FSR 4 ML 需要支持的 RX 9000 和驱动;实卡待验");
@@ -1351,13 +1383,17 @@ static int xessCeiling(const engine::PlayerSnapshot& s) {
return std::max(cap, seen);
}
void QmlPlayerBridge::setFgBackendName(const QString& value) {
- if(value!=QLatin1String("dlss")&&value!=QLatin1String("xess")&&value!=QLatin1String("fsr3")&&value!=QLatin1String("fsr4")){emit notice(tr("未知补帧后端"),true);return;}
+ if(value!=QLatin1String("dlss")&&value!=QLatin1String("xess")&&value!=QLatin1String("fsr3")&&value!=QLatin1String("fsr4")&&value!=QLatin1String("vfg")){emit notice(tr("未知补帧后端"),true);return;}
auto s = settings();
const auto want = value == QLatin1String("xess") ? engine::FrameGenerationBackend::XeSS
: value == QLatin1String("fsr3") ? engine::FrameGenerationBackend::Fsr
: value == QLatin1String("fsr4") ? engine::FrameGenerationBackend::Fsr4
+ : value == QLatin1String("vfg") ? engine::FrameGenerationBackend::Vfg
: engine::FrameGenerationBackend::Dlss;
if (s.frameGenerationBackend == want) return;
+ if(want==engine::FrameGenerationBackend::Vfg&&(!vfgHardwarePossible()||!pipeline::VfgBackend::runtimeAvailable(runtime::localRuntimeDirectory().wstring()))){
+ emit notice(!vfgHardwarePossible()?tr("VFG 需要 NVIDIA Ada / Blackwell 显卡(RTX 40 / 50)"):tr("未找到 VFG 运行组件,请在组件页核对路径"),true);emit settingsChanged();return;
+ }
if (want == engine::FrameGenerationBackend::Fsr4 && !fsr4Possible()) {
// Keep the previous choice; the menu snaps back to it.
emit notice(tr("FSR 4 ML 补帧只支持 AMD RX 9000 显卡,当前显卡不能使用,已保持原来的补帧方式"), true);
@@ -1370,14 +1406,14 @@ void QmlPlayerBridge::setFgBackendName(const QString& value) {
auto& chain = impl_->chain;
const auto beforeMultiplier = chain.fgMultiplier;
const int cap = want == engine::FrameGenerationBackend::XeSS ? xessCeiling(impl_->snapshot)
- : engine::fsrFrameGeneration(want) ? 2 : 6;
- const bool clamped = chain.fgMultiplier > uint32_t(cap);
- if (clamped) chain.fgMultiplier = uint32_t(cap);
+ : engine::fsrFrameGeneration(want) ? 2 : want==engine::FrameGenerationBackend::Vfg?8:6;
+ chain.fgMultiplier=normalizeFgMultiplier(chain.fgMultiplier,want,uint32_t(cap));
+ const bool clamped = chain.fgMultiplier != beforeMultiplier;
if(!impl_->commit(s)){
chain.fgMultiplier = beforeMultiplier;
emit notice(tr("补帧后端切换未被接受,原设置保留"),true);return;
}
- if (clamped) emit notice(tr("所选补帧后端最高 %1X,倍率已调整为 %1X").arg(cap), false);
+ if (clamped) emit notice(tr("所选补帧后端的倍率已调整为 %1X").arg(chain.fgMultiplier), false);
emit settingsChanged();
emit chainChanged();
}
@@ -1389,6 +1425,7 @@ int QmlPlayerBridge::fgMaxMultiplier() const {
// new context validates it. XeSS: 4X with the audited unlock provider, else
// 2X, or what a running session already reported above 2X.
const auto& s = impl_->snapshot;
+ if(settings().frameGenerationBackend==engine::FrameGenerationBackend::Vfg)return 8;
if(engine::fsrFrameGeneration(settings().frameGenerationBackend))return 2;
if (settings().frameGenerationBackend == engine::FrameGenerationBackend::XeSS)
return xessCeiling(s);
@@ -1404,8 +1441,9 @@ QVariantList QmlPlayerBridge::fgMultiplierChoices() const {
== engine::FrameGenerationBackend::XeSS;
const int ceiling = xess ? std::min(fgMaxMultiplier(), 4) : fgMaxMultiplier();
QVariantList out;
- // Only the engine's legal multipliers (kFgMultiplierChoices: no 5X).
- for (const auto choice : engine::kFgMultiplierChoices) {
+ const auto choices=settings().frameGenerationBackend==engine::FrameGenerationBackend::Vfg?
+ std::span<const uint32_t>(engine::kVfgMultiplierChoices):std::span<const uint32_t>(engine::kFgMultiplierChoices);
+ for (const auto choice : choices) {
const int m = int(choice);
if (m < 2 || m > ceiling) continue;
QVariantMap item;
@@ -1416,6 +1454,14 @@ QVariantList QmlPlayerBridge::fgMultiplierChoices() const {
return out;
}
+int QmlPlayerBridge::vfgQuality()const{return int(settings().vfgQuality);}
+void QmlPlayerBridge::setVfgQuality(int value){
+ if(value<0||value>2)return;auto s=settings();if(s.vfgQuality==uint32_t(value))return;
+ s.vfgQuality=uint32_t(value);
+ if(!impl_->commit(s)){emit notice(tr("VFG 质量设置未被接受,原设置保留"),true);return;}
+ emit settingsChanged();emit chainChanged();
+}
+
bool QmlPlayerBridge::fgStrict() const { return impl_->chain.fgStrictAdmission; }
void QmlPlayerBridge::setFgStrict(bool value) {
if (impl_->chain.fgStrictAdmission == value) return;
@@ -1550,6 +1596,10 @@ QVariantList QmlPlayerBridge::componentList() const {
// Read from the runtime manifest the build produces rather than a list written
// by hand here, so the page cannot claim a component the package lacks.
QVariantList out;
+ const auto vfgDirectory=pipeline::VfgBackend::runtimeDirectory(runtime::localRuntimeDirectory().wstring());
+ const bool vfgAvailable=pipeline::VfgBackend::runtimeAvailable(runtime::localRuntimeDirectory().wstring());
+ out<<QVariantMap{{"name",QStringLiteral("NVIDIA VFG")},{"detail",QString::fromStdWString(vfgDirectory)},
+ {"loaded",vfgAvailable},{"experimental",true}};
const auto manifest = runtime::localRuntimeDirectory() / L"release-runtime-manifest.json";
QFile file(QString::fromWCharArray(manifest.c_str()));
if (!file.open(QIODevice::ReadOnly)) {
@@ -3587,8 +3637,9 @@ int QmlPlayerBridge::fgMultiplier() const {
return node && node->enabled ? int(impl_->chain.fgMultiplier) : 1;
}
void QmlPlayerBridge::setFgMultiplier(int multiplier) {
- const bool legal = std::find(std::begin(engine::kFgMultiplierChoices), std::end(engine::kFgMultiplierChoices),
- uint32_t(std::max(multiplier, 0))) != std::end(engine::kFgMultiplierChoices);
+ const auto choices=settings().frameGenerationBackend==engine::FrameGenerationBackend::Vfg?
+ std::span<const uint32_t>(engine::kVfgMultiplierChoices):std::span<const uint32_t>(engine::kFgMultiplierChoices);
+ const bool legal = std::find(choices.begin(),choices.end(),uint32_t(std::max(multiplier,0)))!=choices.end();
if (!legal || multiplier > fgMaxMultiplier()) {
emit notice(tr("补帧倍率超出当前后端范围"), true); return;
}
@@ -4707,12 +4758,15 @@ void QmlPlayerBridge::openSubtitleDialog() { emit navigate(QStringLiteral("subti
// not silently dropped.
int QmlPlayerBridge::addEffect(const QString& type) {
const bool fgType=type==QLatin1String("dlss-fg")||type==QLatin1String("xess-fg")||
- type==QLatin1String("fsr3-fg")||type==QLatin1String("fsr4-fg");
- const auto fgBackend=type==QLatin1String("fsr4-fg")?engine::FrameGenerationBackend::Fsr4:
+ type==QLatin1String("fsr3-fg")||type==QLatin1String("fsr4-fg")||type==QLatin1String("vfg-fg");
+ const auto fgBackend=type==QLatin1String("vfg-fg")?engine::FrameGenerationBackend::Vfg:type==QLatin1String("fsr4-fg")?engine::FrameGenerationBackend::Fsr4:
type==QLatin1String("fsr3-fg")?engine::FrameGenerationBackend::Fsr:
type==QLatin1String("xess-fg")?engine::FrameGenerationBackend::XeSS:engine::FrameGenerationBackend::Dlss;
const auto fgCeiling=engine::fsrFrameGeneration(fgBackend)?2u:
- fgBackend==engine::FrameGenerationBackend::XeSS?uint32_t(xessCeiling(impl_->snapshot)):6u;
+ fgBackend==engine::FrameGenerationBackend::XeSS?uint32_t(xessCeiling(impl_->snapshot)):fgBackend==engine::FrameGenerationBackend::Vfg?8u:6u;
+ if(fgType&&fgBackend==engine::FrameGenerationBackend::Vfg&&(!vfgHardwarePossible()||!pipeline::VfgBackend::runtimeAvailable(runtime::localRuntimeDirectory().wstring()))){
+ emit notice(!vfgHardwarePossible()?tr("VFG 需要 NVIDIA Ada / Blackwell 显卡(RTX 40 / 50)"):tr("未找到 VFG 运行组件,请在组件页核对路径"),true);return -1;
+ }
if (impl_->chain.mode == engine::ChainMode::Node) {
const bool fg = fgType;
const engine::EffectInfo* info = nullptr;
@@ -4726,7 +4780,7 @@ int QmlPlayerBridge::addEffect(const QString& type) {
const auto oldLayout = impl_->layout; const auto previous = impl_->facade.pendingSettings();
const auto oldGlobals = impl_->draftGlobals;
auto pending = settings();
- if (fg){pending.frameGenerationBackend=fgBackend;c.fgMultiplier=std::clamp(c.fgMultiplier,2u,fgCeiling);}
+ if (fg){pending.frameGenerationBackend=fgBackend;c.fgMultiplier=normalizeFgMultiplier(c.fgMultiplier,fgBackend,fgCeiling);}
int index = -1;
if (fg) for (uint32_t i = 0; i < c.nodeCount; ++i)
if (c.nodes[i].type == engine::EffectType::FrameGeneration) index = int(i);
@@ -4778,7 +4832,7 @@ int QmlPlayerBridge::addEffect(const QString& type) {
c.nodes[slot].viewX=float(slot%4)*260;c.nodes[slot].viewY=float(slot/4)*300;
}
c.nodes[slot].enabled=true;
- c.fgMultiplier=std::clamp(c.fgMultiplier,2u,fgCeiling);
+ c.fgMultiplier=normalizeFgMultiplier(c.fgMultiplier,fgBackend,fgCeiling);
auto next=previous;engine::fromChain(c,next);
next.frameGenerationBackend=fgBackend;
impl_->validation=engine::validateChain(c);
@@ -5242,6 +5296,7 @@ bool QmlPlayerBridge::savePresetAs(const QString& name, int contentsMask, bool n
entry.color = impl_->facade.pendingSettings().color;
entry.fg.multiplier = impl_->facade.pendingSettings().multiplier;
entry.fg.backend = impl_->facade.pendingSettings().frameGenerationBackend;
+ entry.fg.vfgQuality = impl_->facade.pendingSettings().vfgQuality;
entry.audioSync = impl_->facade.pendingSettings().audioSync;
entry.audioOffsetMs = impl_->facade.pendingSettings().audioOffsetMs;
if (nodeMode) {
@@ -5252,6 +5307,7 @@ bool QmlPlayerBridge::savePresetAs(const QString& name, int contentsMask, bool n
}
entry.fg.multiplier = uint32_t(fgMultiplier());
entry.fg.backend = impl_->draftGlobals.fgBackend;
+ entry.fg.vfgQuality = impl_->draftGlobals.vfgQuality;
entry.globals=impl_->draftGlobals;
}
const bool ok = impl_->facade.savePreset(entry, false);
@@ -5447,6 +5503,7 @@ void QmlPlayerBridge::updateRunStatus() {
case engine::FrameGenerationBackend::XeSS: backend = tr("XeSS"); break;
case engine::FrameGenerationBackend::Fsr: backend = tr("FSR 3.1"); break;
case engine::FrameGenerationBackend::Fsr4: backend = tr("FSR 4 ML"); break;
+ case engine::FrameGenerationBackend::Vfg: backend = QStringLiteral("NVIDIA VFG"); break;
}
detail << tr("补帧 %1X · %2").arg(s.applied.multiplier)
.arg(backend);
diff --git a/tests/integration/VfgExportProbe.cpp b/tests/integration/VfgExportProbe.cpp
new file mode 100644
index 00000000..bc43e8ab
--- /dev/null
+++ b/tests/integration/VfgExportProbe.cpp
@@ -0,0 +1,31 @@
+// Diagnostic entry into the actual graph + D3D12 NVENC + mux/verify path.
+// This file contains no interpolation or encoding implementation.
+#include "veyra/engine/VideoExportJob.h"
+#include <atomic>
+#include <filesystem>
+#include <iostream>
+#include <string>
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ if(argc<5)return 2;const unsigned m=std::stoul(argv[3]),quality=std::stoul(argv[4]);
+ if(m<2||m>8||quality>2)return 2;
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ EnhancementSettings s;s.frameGenerationBackend=FrameGenerationBackend::Vfg;s.multiplier=m;s.vfgQuality=quality;
+ bool cancelTest=false;
+ for(int i=5;i<argc;++i){const std::wstring flag=argv[i];
+ if(flag==L"--nr")s.nr=true;
+ else if(flag==L"--sr"){s.sr=true;s.videoSrQuality=4;s.srTarget=veyra::pipeline::SrTarget::Uhd4K;}
+ else if(flag==L"--cancel")cancelTest=true;
+ else return 2;
+ }
+ s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;s.exportBitrateMbps=18;
+ auto options=PlayerOptions::from(s);options.exportRateControl=veyra::sink::ExportRateControl::Vbr;
+ std::atomic<bool> cancel{false};ExportCounts last;
+ const bool ok=exportVideo(argv[1],argv[2],options,true,cancel,
+ [](double p,const std::wstring& msg){std::wcout<<int(p*100)<<L"% "<<msg<<L'\n';},0,{},
+ [&](const ExportCounts& c){last=c;if(cancelTest&&c.source>=2)cancel=true;});
+ std::cout<<"VFG_PRODUCT source="<<last.source<<" generated="<<last.generated<<" hold="<<last.holds<<" output="<<last.encoded<<" multiplier="<<m<<" quality="<<quality<<" ok="<<ok<<" cancelled="<<cancel.load()<<'\n';
+ CoUninitialize();
+ if(cancelTest)return !ok&&cancel&&!std::filesystem::exists(argv[2])?0:1;
+ return ok&&last.source>1&&last.generated>0&&last.encoded==last.source*m?0:1;
+}
diff --git a/tests/integration/VfgGpuTests.cpp b/tests/integration/VfgGpuTests.cpp
new file mode 100644
index 00000000..c4a9d817
--- /dev/null
+++ b/tests/integration/VfgGpuTests.cpp
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Product-library VFG test. Pixel readback and final CPU waits are diagnostic
+// only; production uses the same GPU handoff and leased textures without them.
+#include "veyra/pipeline/VfgBackend.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/Log.h"
+#include <d3d12sdklayers.h>
+#include <array>
+#include <cmath>
+#include <cstring>
+#include <cstdio>
+#include <set>
+#include <chrono>
+#include <vector>
+#include <algorithm>
+using namespace veyra;
+void transition(ID3D12GraphicsCommandList* l,ID3D12Resource* r,D3D12_RESOURCE_STATES a,D3D12_RESOURCE_STATES b){
+ D3D12_RESOURCE_BARRIER x{};x.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;x.Transition={r,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,a,b};l->ResourceBarrier(1,&x);
+}
+Microsoft::WRL::ComPtr<ID3D12Resource> makeReadback(ID3D12Device* device,uint64_t bytes){
+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC desc{};desc.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;desc.Width=bytes;desc.Height=1;desc.DepthOrArraySize=1;desc.MipLevels=1;desc.SampleDesc.Count=1;desc.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ Microsoft::WRL::ComPtr<ID3D12Resource> buffer;if(FAILED(device->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&buffer))))return {};return buffer;
+}
+int wmain(int argc,wchar_t** argv){
+ if(argc<2){std::puts("usage: veyra_vfg_gpu_tests <runtime dir> [width height]");return 2;}
+ const unsigned w=argc>2?unsigned(_wtoi(argv[2])):1280,h=argc>3?unsigned(_wtoi(argv[3])):720;
+ if(!w||!h||w>3840||h>2160)return 2;
+ unsigned checks=0,failed=0;const auto check=[&](bool b,const char* label){++checks;if(!b){++failed;std::printf("FAIL %s\n",label);}};
+ gfx::D3D12DeviceContext ctx;Status st=Status::Ok;gfx::DeviceContextDesc d{};d.enableDebugLayer=true;d.commandSlotCount=6;
+ if(!ctx.initialize(d,st))return 2;
+ gfx::CommandSlotRing ring;if(!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))return 2;
+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;ctx.device()->QueryInterface(IID_PPV_ARGS(&debug));
+ for(auto format:{DXGI_FORMAT_R8G8B8A8_UNORM,DXGI_FORMAT_R10G10B10A2_UNORM}){
+ std::array<Microsoft::WRL::ComPtr<ID3D12Resource>,2> textures;
+ for(auto& t:textures)t=pipeline::makeTexture(ctx.device(),w,h,format,false);
+ auto output=pipeline::makeTexture(ctx.device(),w,h,format,false);if(!textures[0]||!textures[1]||!output)return 2;
+ const auto desc=textures[0]->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT rows=0;uint64_t rowBytes=0,total=0;
+ ctx.device()->GetCopyableFootprints(&desc,0,1,0,&fp,&rows,&rowBytes,&total);
+ const uint64_t bytes=uint64_t(fp.Footprint.RowPitch)*h;
+ auto upload=pipeline::makeUploadBuffer(ctx.device(),bytes*2);auto readback=makeReadback(ctx.device(),bytes*7);if(!upload||!readback)return 2;
+ void* mapped=nullptr;if(FAILED(upload->Map(0,nullptr,&mapped)))return 2;
+ std::array<double,2> inputCentroid{};
+ for(unsigned p=0;p<2;++p){double sum=0,weighted=0;
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){
+ const unsigned left=w/2+p*32;const bool box=x>=left&&x<left+w/10&&y>=h/3&&y<2*h/3;
+ const unsigned r=box?230:16,g=unsigned(16+(x*29/w)),b=unsigned(24+(y*31/h));
+ if(box){sum+=r-16;weighted+=(r-16)*x;}
+ auto* pixel=static_cast<uint8_t*>(mapped)+p*bytes+y*fp.Footprint.RowPitch+x*4;
+ if(format==DXGI_FORMAT_R8G8B8A8_UNORM){pixel[0]=uint8_t(r);pixel[1]=uint8_t(g);pixel[2]=uint8_t(b);pixel[3]=255;}
+ else{const uint32_t packed=(r*1023/255)|((g*1023/255)<<10)|((b*1023/255)<<20)|(3u<<30);std::memcpy(pixel,&packed,4);}
+ }inputCentroid[p]=weighted/sum;
+ }
+ // Keep mapping for readback comparisons; upload memory is immutable.
+ for(unsigned quality=0;quality<3;++quality){
+ pipeline::VfgBackend vfg;
+ if(!vfg.initialize(ctx,argv[1],w,h,format,8,quality)){std::puts("FAIL native VFG initialization");return 3;}
+ for(unsigned p=0;p<2;++p){uint32_t slot=0;auto* l=ring.acquireNext(slot,st);if(!l)return 2;
+ transition(l,textures[p].Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;src.PlacedFootprint=fp;src.PlacedFootprint.Offset=p*bytes;
+ D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=textures[p].Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ l->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ transition(l,textures[p].Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ check(vfg.capture(l,textures[p].Get(),p),"capture encoded GPU frame");
+ transition(l,textures[p].Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot))return 2;
+ }
+ for(unsigned multiplier=2;multiplier<=8;++multiplier){
+ const auto start=std::chrono::steady_clock::now();
+ for(unsigned sub=1;sub<multiplier;++sub){
+ if(!vfg.generate(1,sub,multiplier,false)){std::puts("FAIL native VFG asynchronous Run");return 4;}
+ uint32_t slot=0;auto* l=ring.acquireNext(slot,st);if(!l)return 2;
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);
+ check(vfg.copyOutput(l,output.Get(),1+2*(sub-1)),"consume native output on GPU");
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=output.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;dst.PlacedFootprint.Offset=(sub-1)*bytes;
+ l->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot))return 2;
+ }
+ check(ring.waitIdle(),"diagnostic final group completion");
+ const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
+ D3D12_RANGE range{0,size_t(bytes*(multiplier-1))};void* pixels=nullptr;if(FAILED(readback->Map(0,&range,&pixels)))return 2;
+ std::set<uint64_t> hashes;double previous=inputCentroid[0];
+ std::printf("VFG format=%u size=%ux%u quality=%u multiplier=%u groupWallMs=%.3f centroids=",unsigned(format),w,h,quality,multiplier,ms);
+ for(unsigned sub=1;sub<multiplier;++sub){uint64_t hash=1469598103934665603ull;double weight=0,sum=0;
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){const auto* pixel=static_cast<uint8_t*>(pixels)+(sub-1)*bytes+y*fp.Footprint.RowPitch+x*4;
+ for(unsigned c=0;c<4;++c){hash^=pixel[c];hash*=1099511628211ull;}
+ unsigned red=0;if(format==DXGI_FORMAT_R8G8B8A8_UNORM)red=pixel[0];else{uint32_t packed=0;std::memcpy(&packed,pixel,4);red=(packed&1023)*255/1023;}
+ const double value=red>40?red-16:0;sum+=value;weight+=value*x;
+ }
+ const auto center=sum?weight/sum:-1;std::printf("%.3f,",center);hashes.insert(hash);
+ check(center>previous-1&&center>inputCentroid[0]-1&&center<inputCentroid[1]+1,"intermediate red block advances between A/B");previous=center;
+ }
+ std::printf(" distinct=%zu\n",hashes.size());check(hashes.size()==multiplier-1,"all generated subframes distinct");
+ D3D12_RANGE written{0,0};readback->Unmap(0,&written);
+ }
+ // Manual cut must not reuse the previous input; clear ShotChange on
+ // the next run, and retain both imported buffers for normal pairs.
+ check(vfg.generate(1,1,2,true),"manual shot change native call");
+ uint32_t slot=0;auto* l=ring.acquireNext(slot,st);if(!l)return 2;
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);check(vfg.copyOutput(l,output.Get(),1),"cut output GPU copy");
+ transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ D3D12_TEXTURE_COPY_LOCATION src{};src.pResource=output.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ D3D12_TEXTURE_COPY_LOCATION dst{};dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;
+ l->CopyTextureRegion(&dst,0,0,0,&src,nullptr);transition(l,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);
+ check(ring.submitAndSignal(slot)&&ring.waitIdle(),"cut output ready");
+ void* pixels=nullptr;D3D12_RANGE range{0,size_t(bytes)};if(FAILED(readback->Map(0,&range,&pixels)))return 2;
+ unsigned maxError=0;for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w*4;++x){
+ const auto a=static_cast<uint8_t*>(pixels)[y*fp.Footprint.RowPitch+x];const auto b=static_cast<uint8_t*>(mapped)[bytes+y*fp.Footprint.RowPitch+x];maxError=std::max(maxError,unsigned(std::abs(int(a)-int(b))));}
+ check(maxError<=2,"manual cut equals current encoded input");std::printf("cutMaxByteError=%u\n",maxError);D3D12_RANGE written{0,0};readback->Unmap(0,&written);
+ check(!vfg.generate(1,8,8,false)&&!vfg.generate(2,1,2,false)&&!vfg.generate(0,1,9,false),"invalid slot/multiplier rejected");
+ vfg.shutdown();
+ }
+ D3D12_RANGE written{0,0};upload->Unmap(0,&written);
+ }
+ uint32_t removed=0;check(ctx.checkDeviceAlive(removed),"device alive after all formats/models/multipliers");
+ if(debug){for(uint64_t i=0;i<debug->GetNumStoredMessages();++i){size_t size=0;debug->GetMessage(i,nullptr,&size);std::vector<uint8_t> bytes(size);auto* message=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());debug->GetMessage(i,message,&size);
+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){check(false,"D3D12 debug error");std::printf("D3D12 ERROR %s\n",message->pDescription);}}}
+ std::printf("Native GPU VFG: %u checks %u failures. Hardware/cadence/film/HDR quality remain separate.\n",checks,failed);return failed?1:0;
+}
diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cpp
index 04d44c5d..5862a742 100644
--- a/tests/unit/RepairPresetTests.cpp
+++ b/tests/unit/RepairPresetTests.cpp
@@ -211,13 +211,13 @@ ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;
ok=ok&&b.put(L"FSR 4 ML 2X",fsr4);PresetStore fsr4Reload(p);
ok=ok&&fsr4Reload.load()&&fsr4Reload.entries().back().settings==fsr4&&b.erase(1);
fsr4.multiplier=4;ok=ok&&!b.put(L"FSR 4 ML 4X rejected",fsr4);
- auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(4);ok=ok&&!b.put(L"invalid backend",badBackend);
+ auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(5);ok=ok&&!b.put(L"invalid backend",badBackend);
auto dis=s;dis.opticalFlowBackend=OpticalFlowBackend::GpuDis;ok=ok&&b.put(L"GPU DIS",dis)&&b.save();PresetStore disReload(p);ok=ok&&disReload.load()&&disReload.entries().back().settings==dis&&b.erase(1);
auto badFlow=s;badFlow.opticalFlowBackend=static_cast<OpticalFlowBackend>(3);ok=ok&&!b.put(L"invalid flow backend",badFlow);
auto ampere=s;ampere.nr=true;ampere.nrRuntime=NrRuntime::Ampere;ok=ok&&b.put(L"RTX30",ampere);PresetStore ampereReload(p);ok=ok&&ampereReload.load()&&ampereReload.entries().back().settings==ampere&&b.erase(1);
auto original=s;original.nr=true;original.nrRuntime=NrRuntime::NvidiaOriginal;ok=ok&&b.put(L"NVIDIA original",original);PresetStore originalReload(p);ok=ok&&originalReload.load()&&originalReload.entries().back().settings==original&&b.erase(1);
- auto badNr=s;badNr.nrRuntime=static_cast<NrRuntime>(4);ok=ok&&!b.put(L"invalid NR runtime",badNr);
+ auto badNr=s;badNr.nrRuntime=static_cast<NrRuntime>(5);ok=ok&&!b.put(L"invalid NR runtime",badNr);
auto half=s;half.content=ContentRate::Capture60To30;ok=ok&&b.put(L"capture half rate",half);PresetStore halfReload(p);ok=ok&&halfReload.load()&&halfReload.entries().back().settings.content==ContentRate::Capture60To30&&b.erase(1);
// 5 is the AMD FSR upscaling slot now, so it must round-trip; 6 stays invalid.
auto fsrSr=s;fsrSr.videoSrQuality=veyra::engine::kVideoSrFsr;ok=ok&&b.put(L"FSR SR",fsrSr);
diff --git a/tests/unit/VfgSettingsTests.cpp b/tests/unit/VfgSettingsTests.cpp
new file mode 100644
index 00000000..cc3b125a
--- /dev/null
+++ b/tests/unit/VfgSettingsTests.cpp
@@ -0,0 +1,56 @@
+#include "veyra/engine/PresetStore.h"
+#include "veyra/engine/PresetLibrary.h"
+#include "veyra/pipeline/FrameBatch.h"
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <memory>
+using namespace veyra::engine;
+namespace {unsigned checks=0,failures=0;void check(bool ok,const char* why){++checks;if(!ok){++failures;std::cout<<"FAIL "<<why<<'\n';}}
+std::string bytes(const std::filesystem::path& p){std::ifstream f(p,std::ios::binary);return {(std::istreambuf_iterator<char>(f)),{}};}}
+int wmain(int argc,wchar_t** argv){
+ if(argc!=2||!std::filesystem::path(argv[1]).is_absolute())return 2;
+ const std::filesystem::path root=argv[1];if(!std::filesystem::create_directories(root))return 2;
+ check(!motionUsesFlow(MotionSource::OpticalFlow,FrameGenerationBackend::Vfg)&&
+ !motionUsesFlow(MotionSource::Automatic,FrameGenerationBackend::Vfg),"VFG uses its own motion even after a DLSS flow preset");
+ check(motionUsesFlow(MotionSource::OpticalFlow)&&motionUsesFlow(MotionSource::Automatic),"SR/NR external motion remains enabled");
+ EnhancementSettings legacy;PresetStore old(root/L"legacy.txt");check(old.load()&&old.put(L"old",legacy),"write legacy default");
+ PresetStore legacyReader(root/L"legacy.txt");check(legacyReader.load()&&legacyReader.entries()[0].settings.vfgQuality==1,"old presets default to Medium");
+ const auto original=bytes(root/L"legacy.txt");
+ PresetStore store(root/L"settings.txt");check(store.load(),"new store");
+ for(unsigned quality=0;quality<3;++quality)for(unsigned m=2;m<=8;++m){
+ EnhancementSettings s;s.frameGenerationBackend=FrameGenerationBackend::Vfg;s.multiplier=m;s.vfgQuality=quality;
+ check(s.validate().empty(),"VFG legal multiplier/quality");
+ const auto name=std::to_wstring(m)+L"x-q"+std::to_wstring(quality);
+ check(store.put(name,s),"legacy settings store writes VFG");
+ const auto path=root/(name+L".preset");PresetLibrary library(path);library.setIncludeBuiltins(false);
+ auto e=std::make_unique<PresetEntry>();e->name=name;e->chain=toChain(s);e->fg={m,FrameGenerationBackend::Vfg,quality};e->globals=ChainGlobalSettings::capture(s);
+ check(library.load()&&library.put(*e),"library saves VFG");
+ PresetLibrary reloaded(path);reloaded.setIncludeBuiltins(false);
+ check(reloaded.load()&&reloaded.entries().size()==1&&reloaded.entries()[0]==*e,"library restores full VFG state");
+ auto applied=legacy;PresetLibrary::apply(*e,applied);
+ check(applied.multiplier==m&&applied.frameGenerationBackend==FrameGenerationBackend::Vfg&&applied.vfgQuality==quality,"preset applies multiplier backend quality");
+ e->contents=presetContentMask(PresetContent::Color);applied=s;applied.vfgQuality=(quality+1)%3;
+ const auto kept=applied.vfgQuality;PresetLibrary::apply(*e,applied);
+ check(applied.frameGenerationBackend==FrameGenerationBackend::Vfg&&applied.multiplier==m&&applied.vfgQuality==kept,"partial color preset preserves VFG");
+ auto session=std::make_unique<ChainSession>(ChainSession::initial(s));check(session->select(ChainMode::Node),"VFG node mode initializes");
+ auto editor=std::make_shared<NodeEditorDocument>();editor->nodes=session->configurations[1].chain;
+ editor->globals=ChainGlobalSettings::capture(s);check(editor->layout.initialize(editor->nodes).accepted,"VFG node draft layout");
+ session->configurations[1].editor=editor;check(session->valid(),"VFG session valid");
+ auto restored=std::make_unique<ChainSession>();
+ const auto sessionPath=root/(name+L".session");ChainSessionStore sessionWriter(sessionPath);
+ check(sessionWriter.save(*session),"session atomic save");ChainSessionStore sessionReader(sessionPath);
+ check(sessionReader.load(*restored)&&*session==*restored,"session restart finds VFG suffix");
+ auto bad=s;bad.multiplier=9;check(!bad.validate().empty(),"reject VFG 9X");bad=s;bad.vfgQuality=3;check(!bad.validate().empty(),"reject unknown quality");
+ bad=s;bad.frameGenerationBackend=FrameGenerationBackend::Dlss;if(m>6)check(!bad.validate().empty(),"DLSS ceiling remains 6X");
+ veyra::pipeline::FrameBatch batch;batch.identity={1,2,3};batch.a100ns=10000000;batch.b100ns=10333333;
+ for(unsigned j=1;j<m;++j){veyra::pipeline::BatchFrame f;f.identity=batch.identity;f.subframe=j;f.pts100ns=batch.interpolate(batch.a100ns,batch.b100ns,j,m);f.kind=veyra::pipeline::FrameKind::Generated;batch.append(f);}
+ veyra::pipeline::BatchFrame real;real.identity=batch.identity;real.pts100ns=batch.b100ns;batch.append(real);
+ check(batch.count==m&&batch.frames[m-1].pts100ns==batch.b100ns,"2..8 ordered PTS with every source frame");
+ if(m==8){bool rejected=false;try{real.pts100ns++;batch.append(real);}catch(const std::invalid_argument&){rejected=true;}check(rejected&&batch.count==8,"8X batch rejects ninth frame");}
+ }
+ PresetStore restoredStore(root/L"settings.txt");check(restoredStore.load()&&restoredStore.entries().size()==21,"all VFG settings restored");
+ for(const auto& e:restoredStore.entries())check(e.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&e.settings.vfgQuality<3&&e.settings.multiplier>=2&&e.settings.multiplier<=8,"stored VFG values legal");
+ check(bytes(root/L"legacy.txt")==original,"legacy file unchanged");
+ std::cout<<"VFG settings "<<checks<<" checks, "<<failures<<" failures\n";return failures?1:0;
+}