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++
Complete NR reuse, colour temperature and presentation statistics
Veyra Goal Agenta375afa55011
diff --git a/CMakeLists.txt b/CMakeLists.txtindex d46f5d7c..d77bc608 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -307,6 +307,9 @@ veyra_add_compute_shader(veyra_shader_nr_residual NrResidualComposite)veyra_add_compute_shader(veyra_shader_nr_temporal NrTemporal)# Stage-5 output stabiliser (anti-flicker, default off).veyra_add_compute_shader(veyra_shader_nr_hold NrHold)+# NR inference reuse (realtime preview only, default off).+veyra_add_compute_shader(veyra_shader_nr_reuse_compose NrReuseCompose)+veyra_add_compute_shader(veyra_shader_nr_reuse_warp NrReuseWarp)veyra_add_compute_shader(veyra_shader_flow_adapt FlowAdapt)veyra_add_compute_shader(veyra_shader_flow_refine FlowRefine)veyra_add_compute_shader(veyra_shader_flow_fill FlowFill)@@ -567,7 +570,7 @@ endif()# EnhanceGraph (the real GPU chain) needs the NGX + NVOF backends; wire it# into veyra_pipeline only when both exist so bare contract builds still work.if(TARGET veyra_ngx AND TARGET veyra_nvof AND VEYRA_FFMPEG_ROOT)- target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/pipeline/NrTemporalPass.cpp src/pipeline/NrHoldPass.cpp src/core/SceneCadenceAnalyzer.cpp)+ target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/pipeline/NrTemporalPass.cpp src/pipeline/NrHoldPass.cpp src/pipeline/NrReusePass.cpp src/core/SceneCadenceAnalyzer.cpp)target_include_directories(veyra_pipeline PRIVATE ${FFMPEG_INCLUDE_DIRS})target_link_libraries(veyra_pipeline PRIVATE veyra_ngx veyra_nvof ${FFMPEG_LIBRARIES})add_dependencies(veyra_pipeline@@ -662,7 +665,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource# composes veyra_media; no second decode implementation exists.- add_dependencies(veyra_pipeline veyra_shader_sr_resolve veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_flow_adapt veyra_shader_flow_refine veyra_shader_flow_fill veyra_shader_flow_claim veyra_shader_vfg_shot_change)+ add_dependencies(veyra_pipeline veyra_shader_sr_resolve veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_nr_reuse_compose veyra_shader_nr_reuse_warp veyra_shader_flow_adapt veyra_shader_flow_refine veyra_shader_flow_fill veyra_shader_flow_claim veyra_shader_vfg_shot_change)add_library(veyra_sources STATICsrc/source/NativeCaptureSink.cppsrc/source/MediaFileSource.cpp@@ -1361,12 +1364,24 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTadd_executable(veyra_nr_hold_gpu_tests tests/integration/NrHoldGpuTests.cpp)target_compile_features(veyra_nr_hold_gpu_tests PRIVATE cxx_std_20)target_link_libraries(veyra_nr_hold_gpu_tests PRIVATE veyra_pipeline)+ # NR inference reuse: frame selection, Auto controller and settings (GPU-free),+ # and the reuse pass on real D3D12 dispatches.+ add_executable(veyra_nr_reuse_tests tests/unit/NrReuseTests.cpp)+ target_compile_features(veyra_nr_reuse_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_nr_reuse_tests PRIVATE veyra_engine)+ add_executable(veyra_nr_reuse_gpu_tests tests/integration/NrReuseGpuTests.cpp)+ target_compile_features(veyra_nr_reuse_gpu_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_nr_reuse_gpu_tests PRIVATE veyra_pipeline)add_executable(veyra_nr_runtime_assertion_tests tests/integration/NrRuntimeAssertionTests.cpp)target_compile_features(veyra_nr_runtime_assertion_tests PRIVATE cxx_std_20)target_link_libraries(veyra_nr_runtime_assertion_tests PRIVATE veyra_pipeline)add_executable(veyra_nr_video_quality_probe tests/integration/NrVideoQualityProbe.cpp)target_compile_features(veyra_nr_video_quality_probe PRIVATE cxx_std_20)target_link_libraries(veyra_nr_video_quality_probe PRIVATE veyra_engine)+ # NR inference reuse against full inference on a real video (offline readbacks).+ add_executable(veyra_nr_reuse_quality_probe tests/integration/NrReuseQualityProbe.cpp)+ target_compile_features(veyra_nr_reuse_quality_probe PRIVATE cxx_std_20)+ target_link_libraries(veyra_nr_reuse_quality_probe PRIVATE veyra_engine)add_executable(veyra_nr_dynamic_size_experiment tests/perf/NrDynamicSizeExperiment.cpp)target_compile_features(veyra_nr_dynamic_size_experiment PRIVATE cxx_std_20)target_compile_options(veyra_nr_dynamic_size_experiment PRIVATE /utf-8)diff --git a/docs/FPS_LOW1_AND_COLOR_TEMPERATURE_2026-11-07.md b/docs/FPS_LOW1_AND_COLOR_TEMPERATURE_2026-11-07.mdnew file mode 100644index 00000000..0605a2ae--- /dev/null+++ b/docs/FPS_LOW1_AND_COLOR_TEMPERATURE_2026-11-07.md@@ -0,0 +1,100 @@+# 帧率卡的 1% low 与色温冷端修正(2026-11-07)++**分支**:`claude/nr-reuse-20261107`,与 NR 推理复用同在一个工作树,提交时分开。++**来源**:用户 11-07 的两条反馈。++## 一、“显示 fps”一直未测 → 改为提交 fps + 1% low++**现象**:帧率卡的“显示 fps”永远显示“未测”。用户发现小飞机(RTSS)注入后能测到帧率和 1% low。++**原因**:++- 代码里 `displayFps()` 一直返回“未知”。注释说明本构建没有接入显示事件计数,真实的面板扫描帧率从来没有测量。+- RTSS、PresentMon 这类叠加工具是挂钩程序的 Present 调用来计时的,它们统计的就是程序“交给屏幕”的速度,与我们的“提交 fps”是同一个量,并不是屏幕实际显示的帧数。+- 它们的 1% low 也是用 Present 间隔算的,我们完全可以自己算。++**改动**:++- 新增 `FramePaceWindow`(`include/veyra/engine/FrameRateWindow.h`):+ - 每次 Present 记录与上一次的间隔,只保留最近 10 秒;+ - 取第 99 百分位间隔折算成帧率,即 1% low,与 RTSS 的百分位算法一致;+ - 不足 100 个间隔时不给数;+ - 超过 0.5 秒的间隔视为暂停或跳转,不计入,并从下一次 Present 重新开始计。+- 数据经 `FrameFlowMetrics::presentLow1Fps` → 引擎快照 `submissionLow1Fps` → 桥接层 `submitLowFps` / `submitLowFpsKnown` 送到界面。+ - XeSS SDK 自行呈现时,我们观察不到那些帧的间隔,所以显示“—”。+- 删除 `displayFps` / `displayFpsKnown` 两个属性。三处界面都改为“提交 fps”加“1% low”:+ - 专业页帧率卡:提交 fps 放大为主数字;+ - 节点页状态条;+ - 显示面板。++**验证**:`veyra_live_timing_tests` 新增 5 项:+- 不足 100 个间隔时为未知;+- 稳定 60 Hz 得 60;+- 每 50 帧一次 50 ms 卡顿得 20;+- 暂停 3 秒不计;+- 只看最近 10 秒。++真实程序结果见下方执行记录。++## 二、色温冷端拉满后画面“爆了”++**现象**:调色面板“色温(相对)”拉到 −100,整个画面爆蓝。++**根因**:`planckianXy` 采用 Kim 等人的普朗克曲线三次近似,其中 2222–4000 K 那段 y 公式的常数项写成了 −0.0316772744,正确值是 −0.16748867。++- 4000 K 以下白点因此偏向黄绿;适配回 D65 时,蓝色在 −100(3250 K)被放大约 23 倍,亮度翻倍。+- 滑杆在约 −70(4000 K)处会突然从蓝色 ×1.8 跳到 ×7。++| 色温 | 旧(错误公式) | 修正公式后 |+|---|---|---|+| −70(4001 K) | R 0.61,G 1.07,B 1.80 | 相同 |+| −71(3974 K) | R 1.02,G 0.74,B 6.99 | R 0.60,G 1.07,B 1.82 |+| −100(3250 K) | R 0.18,G 0.43,B 23.4 | R 0.38,G 1.12,B 2.62 |++表中为白色 (1,1,1) 经白平衡矩阵后的通道值。++**改动**:++1. **修正系数**:y 常数项改为正确值,并补上 1667–2222 K 那段的 y 公式。+2. **冷端与暖端对称**:只修公式时,−100 仍是 3250 K 的钨丝灯校正(蓝 ×2.6),而 +100 只有(红 ×1.19,蓝 ×0.6),两端力度相差一倍。+ - 现在暖端保持原曲线 6500 K × 2^(t/100),+100 = 13000 K,一点不变;+ - 冷端按迈尔德镜像,−100 的白点偏移量与 +100 相同,即 4333 K,白色约(0.68,1.06,1.59);+ - −50 由 4596 K 变为 5027 K。++**影响**:已保存的负色温预设会比以前温和;正色温完全不变。++**验证**:`veyra_color_grade_tests` 新增 3 项:+- 0 到 −100 每档单调增加、相邻差不超过 6%;+- −100 与 +100 偏移力度相当;+- −100 时 18% 灰各通道仍在 2 倍以内。++## 执行记录++本机 RTX 5070,320 Hz。构建在 `build/claude-nr-reuse-20261107`,用 9 个目标,107.4 秒。++**测试**:++| 测试 | 结果 |+|---|---|+| `veyra_live_timing_tests` | 164 项全过,含 1% low 新增 5 项 |+| `veyra_color_grade_tests` | 54 项全过,含色温新增 3 项 |+| `veyra_color_grade_gpu_tests` | 通过 |+| `veyra_effect_slot_regression_tests` | 运行目录内 12/12,含色温 −22 的用例 |+| QtQuick 全套 | 172/0/1 |+| 翻译 | 0 缺失 |++构建目录里直接跑 slot 测试会因缺 `ngx-local.json` 失败,这是环境问题。++**真实程序**(运行目录 `tests/claude-nr-reuse-20261107/app`):++- 帧率卡显示“60.0 提交 fps | 39.5 1% low”,截图 `logs/claude-nr-reuse-20261107/ui/window-half.png`。+ - 1% low 在攒够 100 个间隔后出现;切档后 10 秒窗口里还有之前跟不上的慢帧,随后从 38.8 升到 45.7。+- 真实游戏画面的色温截图(`logs/claude-nr-reuse-20261107/ui/veyra-*.png`):+ - −100:明显偏冷,红叶仍可辨,没有爆;+ - +100:偏暖,力度与冷端相当;+ - −50、0 正常。++**未验证**:+- 与 RTSS 读数逐帧对照:本机没有装 RTSS;+- 其他显卡、HDR 下的色温。diff --git a/docs/NR_INFERENCE_REUSE_2026-11-07.md b/docs/NR_INFERENCE_REUSE_2026-11-07.mdnew file mode 100644index 00000000..7c97425c--- /dev/null+++ b/docs/NR_INFERENCE_REUSE_2026-11-07.md@@ -0,0 +1,205 @@+# NR 推理复用(自动推理复用)2026-11-07++分支 `claude/nr-reuse-20261107`,基于 main `0079ed9`,工作树 `E:/项目/Veyra/worktrees/claude-nr-reuse-20261107`,构建目录 `E:/项目/Veyra/build/claude-nr-reuse-20261107`。++## 来由++- 用户 11-07 决定:不复制、不移植 SAOG0721/Magpie 的代码,要自研更强的 NR 提速方案。+- 提案见 `E:/项目/Veyra/reports/claude-nr-own-optim-20261107/PROPOSAL.md`。用户选了方案 A,要求:+ - 开关叫“自动推理复用”;+ - 同时提供手动模式,可选 1/2、1/3、1/4。+- 本实现从 Veyra 现有模块写起:光流、残差合成、场景/复位规则、自动档控制器思路。没有打开或参考 Magpie 源码。+- “按运动补偿复用之前的计算结果”是通用做法,例如:+ - reverse reprojection caching(Nehab 等,2007);+ - TAA;+ - 视频编码的运动补偿。++## 行为++**只用于实时预览。** 只有预览图会被标记 `nrReusePreview`;导出、暂停单帧、图片的图不会被标记,照常逐帧完整推理。++**复用帧怎么出图**:这一帧不跑 NR 推理,输出为++```+out = 本帧源 + w × (上一推理帧的 NR 输出 − 上一推理帧的源),位置按光流对齐+```++- 搬运的是 NR 带来的“变化”,不是旧画面,所以源画面的细节和位置总是当前帧的。+- 权重 `w` 在下列位置降为 0,这些像素显示未增强的本帧源:+ - 搬过来的关键帧源与本帧源对不上:3×3 盒均亮度,在约 2.2 次方编码下比较,差值 0.03–0.08 之间平滑过渡;+ - 对齐后的位置出了画面;+ - NR 全局保护区域内,在本帧像素上重新计算一次,复用的变化不会伸进保护区。++**变化拆成两部分搬运**:++- 邻域均值(色调、颜色)在 3×3 邻域对得上时照搬;+- 细节部分只在本像素自身的细节也与关键帧对应位置一致时才搬,阈值 0.03–0.09(同一编码下)。+- 这样随帧变化的颗粒、噪点不会被盖上上一帧的细节,只保留它自己的细节加上搬来的色调。++**暂停时补做完整推理**:进入暂停时,若最后处理的一帧是复用帧,引擎沿用“暂停期间改设置”那条重绘路径,带 reset 重新处理缓存帧,这一帧就会完整推理。日志记 `pause began lastFrameReused=...`,产品合同要求暂停单帧完整处理。++**下一帧一定重新推理**:不会连续两帧复用,所以搬运的变化最多是一个源帧之前的,错误的运动矢量最多影响一帧。++**档位**:0 = 每帧推理;1 / 2 / 3 = 每 4 / 3 / 2 帧复用 1 帧。++- 手动 1/2、1/3、1/4 分别固定为 3、2、1 档。+- 用户的“1/2、1/3、1/4”按“每 2/3/4 帧复用 1 帧”实现。若用户本意是“每 2/3/4 帧只推理 1 次”,需要放开“最多连续复用 1 帧”的限制,界面文字也要跟着改。++**自动**:引擎的 `AutoNrReuseController` 选档。++- 输入是 1 秒窗口内的平均增强耗时,以及推理帧上的 NR 耗时(各层 span 之和)。预算沿用自动 NR 尺寸:transport 帧间隔 × 0.8。+- 复用只降低平均耗时,P95 仍是推理帧的耗时,所以按平均值判断。+- 超预算持续 0.5 秒就升一档。换档后等 1.25 秒,让窗口里只剩新档位的帧再判断。+- 降档要满足两点:预测降一档后的平均耗时(当前平均 + 增加的推理份额 × NR 耗时)小于 0.85 倍预算,并且持续 3 秒。+- 换档只是图内调度,不重建、不排空呈现,所以没有切档停顿。+- 自动最多到每 2 帧复用 1 帧。++**NR 自身的时域历史**:复用帧之后的那次推理,NR 的历史停在两帧前。++- 这一帧给 NR 的运动输入(nrFlow_ 及各层 motion)改为串接后的运动 `D(p) = f(p) + D_prev(p + f(p))`。+- 时域稳定器也改读复用 pass 的运动:推理帧之后等于原光流,逐位相同;复用帧之后是串接运动。+- 稳定器的 frameMs 用距上次推理帧的间隔。++**复位**:任何 reset 都会让调度器重来,下一帧推理。reset 包括:++- seek、PTS 断点、场景切换(软件解码有 CPU 场景分析)、尺寸变化、换源、暂停刷新;+- 设置的实时修改。++**生效条件**(不满足时记 `nr-reuse ... inactive reason=`,界面显示“未生效:原因”):++- 预览图;+- 英伟达 NGX NR,不含 AMD 后端;+- SDR 工作空间(!hdrWorking);+- NR 运动来源为光流;+- NR 没有分在超分前后;+- NR 层之间没有保护区域;+- 列表模式(非 runtimeNodeOrder);+- 不与自动 NR 尺寸池同时使用。复用开启时引擎不准入自动尺寸池;预热和最近图缓存也不收复用配置。++**开关的生效方式**:++- 关 ↔ 开会重建图,因为 pass 只在开启时创建;关闭时不创建任何资源,命令流与改动前相同。+- 自动、1/2、1/3、1/4 之间切换实时生效。++**显存**:两张链路分辨率的 RGBA16F 关键帧,加上光流分辨率的位移(2 张 RGBA16F)和运动(RG16F),已计入建图显存预估。++## 11-07 用户反馈后的调整++**本轮验证(真实程序,4K60,4 层 NR)**:++| | 关闭复用 | 1/2 |+|---|---|---|+| NR 第4层 平均 / P95 | 3.50 / 3.79 ms | 1.77 / 3.66 ms |+| 总耗时 | 16.24 ms | 8.36 ms |+| 提交 | 52.8 fps | 60.0 fps |++- 状态只显示“每 2 帧复用 1 帧”。+- 截图:`logs/claude-nr-reuse-20261107/ui/window-half.png`(阶段耗时)、`item-list-nr-stage.png`(三张卡在 NR 画面增强内,与 NR 层并列)。+- “输出稳定器”和“NR 全局保护区域”的 `shield` 图标原本不在图标库里,一直显示空白方块。已在 `prototypes/ui-redesign-2026-09-25/icons.js` 补上 Lucide shield,并用 `tools/qt_probe/make-icons.py` 重新生成 `qml/Veyra/IconData.js`,只多了这一项。+- 新单测 33/0、GPU 7/0、QtQuick 172/0/1。+++- **改名与位置**:卡片改名“NR 自动推理复用”,与“输出稳定器 · 抗闪烁”“NR 全局保护区域”一起挪进“NR 画面增强”。三者是 NR 一级下的全局选项,与 NR 层卡片并列,排在“添加 NR 层”按钮之后;“处理顺序”点击保护区域时会先展开 NR 卡。+- **状态文字**:不再显示“已复用 N 帧”。长时间播放会到几百万帧,没有意义;只保留“自动 · 每 N 帧复用 1 帧”或“每 N 帧复用 1 帧”。+- **底部运算时间随复用实时变化**:+ - 原因:阶段耗时行显示的是“执行过该阶段的帧”的平均。复用帧不跑 NR,不进统计,所以 NR 行一直停在单次推理的耗时,看起来没效果。+ - 改法:复用帧给每层 NR 和 NR 行各记一个零长度的 GPU 计时样本。阶段行的平均值因此变成“平均每个源帧花在 NR 上的时间”,例如 1/2 复用时减半;悬停提示里的 P95 仍是单次推理耗时。+ - 零长度样本落在残差合成区间内,不改变整帧增强耗时的并集计算。自动档估算单次推理成本改用各层 P95。++## 改动文件++| 部分 | 文件 |+|---|---|+| 设置 | `include/veyra/engine/EnhancementSettings.h`:`NrReuseMode`、`nrReuse`、校验、NR 关闭时归一化 |+| 描述 | `include/veyra/engine/GraphDescription.h`;`include/veyra/pipeline/EnhanceGraph.h`(`nrReusePreview`、`nrReuse`、访问函数、计数) |+| 调度 | `include/veyra/pipeline/NrReuse.h`(`NrReuseScheduler`) |+| GPU | `include/veyra/pipeline/NrReusePass.h`、`src/pipeline/NrReusePass.cpp`、`shaders/NrReuseCompose.hlsl`、`shaders/NrReuseWarp.hlsl`,并复用 `FlowAdapt.dxil` |+| 图 | `src/pipeline/EnhanceGraph.cpp`:建 pass、生效条件、逐帧决策、跳过 NR 链、复用合成、存关键帧、串接运动、稳定器运动与间隔、实时改档、显存预估、释放 |+| 引擎 | `include/veyra/engine/AutoNrReuseController.h`;`src/engine/EngineController.cpp`(仅预览标记、自动控制、状态、自动尺寸准入);`src/engine/EffectChain.cpp`(开关重建);`src/engine/PreviewGpuSession.cpp` 与 `include/veyra/engine/RecentGraphCache.h`(预热、COMPUTE、最近图不收复用) |+| 界面 | `include/veyra/ui/QmlPlayerBridge.h`、`src/ui/bridge/Enhancement.cpp`(`nrReuseMode`,存偏好 `nrReuse`)、`src/ui/QmlPlayerBridge.cpp`(启动恢复)、`src/ui/bridge/Playback.cpp`(状态文字)、`qml/Veyra/ProPage.qml`(列表模式“自动推理复用”卡片) |+| 翻译 | `i18n/catalog.json`,新增 27 条 |+| 构建与测试 | `CMakeLists.txt`;`tests/unit/NrReuseTests.cpp`;`tests/integration/NrReuseGpuTests.cpp` |++## 验收++见本任务回执 `E:/项目/Veyra/reports/claude-nr-reuse-20261107/FINAL.json` 与本文件末尾的执行记录。++## 执行记录++本机 RTX 5070,驱动 32.0.16.2101,320 Hz 屏。++**构建**:`python -X utf8 -B scripts/acceptance/build-recording-handoff.py --task claude-nr-reuse-20261107 --root E:/项目/Veyra/worktrees/claude-nr-reuse-20261107 --label 2.1.3-nr-reuse-test --jobs 2 <targets>`++- 首次配置 223.4 秒;+- 之后均为增量构建,逐次日志在 `logs/claude-nr-reuse-20261107/build-*`。++**新测试**:++| 测试 | 结果 |+|---|---|+| `veyra_nr_reuse_tests`(不用显卡) | 33/0。覆盖:<br>• 1/2、1/3、1/4 的复用模式;不会连续复用两帧;<br>• 复位;只在复用前一帧存关键帧;<br>• 自动档升、降与不抖;<br>• 设置校验、NR 关闭时归一化、开关重建、实时切档、仅预览标记 |+| `veyra_nr_reuse_gpu_tests`(D3D12 调试层) | 7/0。覆盖:<br>• 零运动;<br>• 平移跟随:内部 +0.2001,露出区 0;<br>• 内容对不上时原样显示源;<br>• 推理帧后的运动与光流逐位相同;<br>• 链式运动 −2−3=−5,NR 尺度下 −10;<br>• 调试层 0 错误 |++**回归**:++| 测试 | 结果 |+|---|---|+| QtQuick 全套(软件绘制) | 172/0/1,跳过的是需要专门产物目录的像素对比 |+| effect_chain | 通过 |+| preset_library | 通过 |+| repair_preset | 通过 |+| nr_model_settings | 0 失败 |+| nr_antiflicker | 0 失败 |+| repair_contract | 300/0 |+| ui_i18n | 0 失败 |+| nr_hold_gpu | 9/0 |+| settings_transaction(在运行目录内) | passed=1,调试层 0 |+| amd_nr_graph(在运行目录内,假 lmxxf) | 128/0 |++- 翻译 `extract.py --check`:missing 0。+- 构建目录里直接跑时:settings_transaction 缺 `ngx-local.json`,amd_nr_graph 缺 FidelityFX 运行组件,这是环境问题;放进运行目录后通过,失败日志保留。++**真实程序**:运行目录 `tests/claude-nr-reuse-20261107/app`,用正式 2.1.3 NVIDIA 包,换上本分支的 exe、着色器和 QML。++- 每次用独立配置、TEMP、日志和 QML 缓存根目录;+- 探针 QML 负责加 NR 层、设模式、暂停和截卡片图;+- 脚本 `reports/claude-nr-reuse-20261107/nr_reuse_run.py`。++预览的 NR 推理最大 1080p(选的尺寸只用于导出),所以单层 NR 在本机跟得上。为了制造超载,用了 4 层 NR。++| 场景(4K60 HEVC q60.mp4) | 平均增强耗时 | 跳帧 | 说明 |+|---|---:|---|---|+| 1 层,关 | 4.49 ms | 0 | 没有任何 nr-reuse 记录,关闭路径不变 |+| 1 层,手动 1/2 | 3.11 ms(细节拆分后 3.17 ms) | 0 | 状态“每 2 帧复用 1 帧”,每秒约 +30 |+| 4 层,关 | 15.24 ms | 4 秒内 1→3 | 超过 13.33 ms 预算 |+| 4 层,自动 | 15.07 → 11.64 ms | 停在 2 | 约 2 秒升到每 4 帧复用 1 帧后稳定,不再升也不降 |++- **实时切档**:720p30 平移片段,依次自动 → 1/2 → 1/3 → 1/4 → 关。+ - 每秒复用约 15、10、7.5 帧;切档不重建;+ - 关闭时重建图约 0.35 秒,之后状态清空;+ - 0 错误。+- **暂停**:1/2 模式下暂停 6 次。4 次落在复用帧上,都立即完整推理重绘;2 次落在推理帧上,不需要重绘。+- **界面**:卡片三种状态的截图在 `logs/claude-nr-reuse-20261107/ui/`,文字与实际状态一致。+- **启动脚本**:`tests/claude-nr-reuse-20261107/启动推理复用测试.cmd` 冒烟通过:独立配置,6 秒后正常退出,没有残留进程。++**画质**:离线对比工具 `veyra_nr_reuse_quality_probe`。同一组解码帧先按每帧推理跑一遍,再按 1/2 复用跑一遍,逐帧比较 8 位 sRGB 输出;图像在 `logs/claude-nr-reuse-20261107/quality/`。++| 素材 | 复用帧平均差 | PSNR | 差值 >8 的像素 | 复用后推理帧的平均差 | NR 本身的平均改动 |+|---|---:|---:|---:|---:|---:|+| 720p 真实游戏平移 | 0.70 | 45.7 dB | 0.13% | 0.58 | 4.19 |+| 1080p 合成测试卡 | 2.09 | 34.4 dB | 2.17% | 1.73 | 39.4 |+| 4K60 合成测试卡 | 1.98 | 34.2 dB | 1.93% | 1.53 | — |++- 真实画面的差异图几乎全黑,只有人物弓箭边缘有淡轮廓,右侧新露出的一列退回原图。+- 测试卡的差异集中在两处:每帧随机的噪点棋盘(新噪点只有推理才能处理),以及移动细线和方块的边缘。+- 加入细节拆分后,三项平均差都小幅下降,真实画面没有变差;4K 下复用合成的 P95 从 0.52 ms 升到 0.85 ms。+- 推理次数都减半,调试层 0 错误。++**未验证**:++- 其他显卡(尤其 30/40 系、笔记本卡);+- HDR、节点模式、NR 分在超分前后、AMD NR:都按设计拒绝,未测;+- 真实采集卡 4K60;+- 长时间播放;+- 物理显示延迟;+- 用户人工看画面的结论。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 76253766..90b9c1c1 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -798,3 +798,60 @@ Veyra-2.1.3-AMD-win64-portable.zip:717577602 bytes,SHA256 `dc1223f0aff0feb39## 2026-11-06 项目产物安全清理删除122372文件,逻辑53.72 GiB,E盘实测可用净增33.73 GiB;项目路径累计152.89→99.28 GiB。34关键文件/正式与源码ZIP SHA不变,19工作树原HEAD/修改清单不变,依赖/Junction/用户配置/当前build与app保留。只清编译中间文件、旧测试部署与未发布包、私有缓存、旧性能读回;保留修改与用户数据候选315项,首次预检20个Profile命名obj保守排除。单文件1.4.0旧下载ZIP删除被自动审批blocked by policy拒绝,未执行、未绕过,仍保留。详情docs/PROJECT_CLEANUP_2026-11-06.md和reports/codex-project-cleanup-20261106/FINAL.json,命令及逐文件证据在同任务。产品代码/正式包不改,未push/发布。++## 2026-11-07 NR 推理复用(自动推理复用,Claude,未提交)++**来由**:用户不复制、不移植 SAOG0721/Magpie 代码,选了自研方案 A,要求开关名为“自动推理复用”,另提供手动 1/2、1/3、1/4。++- 分支 `claude/nr-reuse-20261107`,基于 main 0079ed9;+- 工作树 `worktrees/claude-nr-reuse-20261107`,构建目录 `build/claude-nr-reuse-20261107`;+- 没有动共用施工树和当前可用构建。++**行为**:++- 只用于实时预览。复用帧不跑 NR,输出“本帧源 + 上一推理帧的 NR 变化”,变化按光流搬运。+- 变化拆成两部分:邻域均值按 3×3 邻域是否匹配决定是否搬;细节只在本像素细节也一致时才搬。对不上、出界或在保护区内时显示原图。+- 复用帧之后一定重新推理。那一帧给 NR 和时域稳定器的运动换成串接后的运动。+- 手动 1/2、1/3、1/4 表示每 2/3/4 帧复用 1 帧。+- 自动由 AutoNrReuseController 选档:平均增强耗时对比 80% 帧间隔,超预算 0.5 秒升档;预测降档仍低于 0.85 倍预算并持续 3 秒才降档;最多每 2 帧复用 1 帧。+- 开关切换会重建图,档位之间实时切换。+- 暂停时若最后一帧是复用帧,补做一次完整推理重绘。+- 导出、图片、预热图、最近图缓存、COMPUTE 准入和自动 NR 尺寸池都不收复用配置。++**验证**:++- 新单测 33/0,新 GPU 测试 7/0(调试层 0);+- QtQuick 172/0/1;+- 设置、预设、合同、翻译、抗闪烁、稳定器 GPU 回归通过;设置事务和 AMD 合成图 128/0 在运行目录内通过。+- 真实程序:+ - 1 层 4K60,1/2 时平均增强耗时 4.49 → 3.11 ms;+ - 4 层超载,自动约 2 秒升到每 4 帧复用 1 帧,15.24 → 11.64 ms,跳帧停止;+ - 实时切档和暂停重绘通过。+- 画质(对比每帧推理):720p 真实平移,复用帧平均差 0.70/255、PSNR 45.7 dB;合成测试卡上差异集中在随机噪点块和移动细线。++**记录**:`docs/NR_INFERENCE_REUSE_2026-11-07.md`,回执 `E:/项目/Veyra/reports/claude-nr-reuse-20261107/FINAL.json`。手动入口 `tests/claude-nr-reuse-20261107/启动推理复用测试.cmd`,独立配置。++**范围**:未打包、未提交、未合 main、未 push。只在本机 RTX 5070 验证,其他显卡、HDR、节点模式、采集卡未验证。++## 2026-11-07 NR 推理复用界面调整、提交 fps 的 1% low、色温冷端修正(Claude,未提交)++同一工作树 `worktrees/claude-nr-reuse-20261107`,按用户截图反馈修改:++- **NR 推理复用**:+ - 去掉“已复用 N 帧”;+ - 卡片改名“NR 自动推理复用”;+ - “输出稳定器 · 抗闪烁”“NR 自动推理复用”“NR 全局保护区域”挪进“NR 画面增强”,与 NR 层并列;+ - 复用帧给 NR 阶段记零长度计时样本,底部阶段耗时的平均随复用实时下降(4 层 4K60:NR 第4层 3.50 → 1.77 ms,总 16.24 → 8.36 ms),P95 仍是单次推理;自动档改用 P95 估算单次推理成本。+- **图标**:两张卡的 `shield` 图标原本不在图标库,一直空白,已补 Lucide shield 并重新生成 IconData。+- **帧率卡**:“显示 fps”从未接入测量、永远未测,已删除。RTSS 也是按 Present 计帧,等同于提交 fps。+ - 现在提交 fps 是主数字,旁边显示 1% low,算法为最近 10 秒 Present 间隔的第 99 百分位;三处界面统一;+ - 实测“60.0 提交 fps | 39.5 1% low”。+- **色温**:普朗克曲线 2222–4000 K 段 y 常数项写错(−0.0317,应为 −0.1675),−100 时蓝通道 ×23、在约 −70 处突跳。已修正,并把冷端按迈尔德与暖端镜像(−100 = 4333 K),暖端不变;真实画面 −100 偏冷但不爆。++**验证**:+- 新单测:NR 复用 33/0、播放计时 164(含 1% low 5 项)、色彩表 54(含色温 3 项);+- 色彩 GPU 通过,slot 回归在运行目录内 12/12,QtQuick 172/0/1,翻译 0 缺失。++**记录**:`docs/NR_INFERENCE_REUSE_2026-11-07.md`、`docs/FPS_LOW1_AND_COLOR_TEMPERATURE_2026-11-07.md`,回执 `E:/项目/Veyra/reports/claude-nr-reuse-20261107/FINAL.json`。++**范围**:未提交、未合 main、未 push;只在本机 RTX 5070 验证,没有与 RTSS 读数逐帧对照。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 0faa4f01..c1709819 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -385,6 +385,13 @@"en": " frames","ja": " フレーム"},+ {+ "zh": " 帧复用 1 帧",+ "src": "qml/ProPage.qml",+ "zh-TW": " 幀復用 1 幀",+ "en": " frames",+ "ja": "フレームごとに 1 回再利用"+ },{"zh": " 次数=","src": "src/base/Log.cpp",@@ -1183,6 +1190,13 @@"en": "HDR metadata","ja": "HDR メタデータ"},+ {+ "zh": "HDR 处理时不复用",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "HDR 處理時不復用",+ "en": "not used for HDR processing",+ "ja": "HDR 処理中は再利用しません"+ },{"zh": "HDR 片源也按 SDR 显示;与采集卡的“转为 SDR 显示”是同一设置","src": "qml/ProDisplayPanel.qml",@@ -1442,6 +1456,13 @@"en": "Invalid NR internal resolution","ja": "NR の内部処理解像度が不正です"},+ {+ "zh": "NR 分在超分前后时不复用",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "NR 分在超解析前後時不復用",+ "en": "not used when NR is split around super resolution",+ "ja": "NR が超解像の前後に分かれているときは再利用しません"+ },{"zh": "NR 层 ","src": "qml/ProPage.qml",@@ -1449,6 +1470,20 @@"en": "NR layer ","ja": "NR 層 "},+ {+ "zh": "NR 层之间有保护区域时不复用",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "NR 層之間有保護區域時不復用",+ "en": "not used with protected areas between NR layers",+ "ja": "NR レイヤー間に保護領域があるときは再利用しません"+ },+ {+ "zh": "NR 未运行",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "NR 未執行",+ "en": "NR is not running",+ "ja": "NR が動作していません"+ },{"zh": "NR 求值 %1 / NVOF %2","src": "src/ui/bridge/Export.cpp",@@ -1512,6 +1547,13 @@"en": "Auto NR %1% · %2×%3","ja": "NR 自動 %1% · %2×%3"},+ {+ "zh": "NR 自动推理复用",+ "src": "qml/ProPage.qml",+ "zh-TW": "NR 自動推理復用",+ "en": "NR automatic inference reuse",+ "ja": "NR 推論の自動再利用"+ },{"zh": "NR 运动来源","src": "qml/NrLayerEditor.qml",@@ -1519,6 +1561,13 @@"en": "NR motion source","ja": "NR のモーション入力"},+ {+ "zh": "NR 运动来源需为光流",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "NR 運動來源需為光流",+ "en": "the NR motion source must be optical flow",+ "ja": "NR のモーション入力をオプティカルフローにしてください"+ },{"zh": "NR运行版本切换失败,已恢复上一套参数","src": "src/engine/EngineController.cpp",@@ -3381,6 +3430,13 @@"en": "Only sizes within driver bounds and granularity are accepted; the actual format is checked on connection","ja": "ドライバーのサイズ範囲と刻みに合う値のみ使用できます。実際の形式は接続時に確認します"},+ {+ "zh": "仅支持英伟达 NR",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "僅支援英偉達 NR",+ "en": "NVIDIA NR only",+ "ja": "NVIDIA NR のみ対応"+ },{"zh": "仅清空列表,不删除硬盘文件","src": "qml/PlaylistWindow.qml",@@ -5216,6 +5272,20 @@"en": "Only matters when Interface drawing is set to GPU; with software drawing the RTSS OSD shows on the video only","ja": "「インターフェース描画」が GPU のときだけ有効です。ソフトウェア描画では RTSS の OSD は映像にだけ表示されます"},+ {+ "zh": "只在实时预览生效",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "只在即時預覽生效",+ "en": "live preview only",+ "ja": "リアルタイムプレビューのみ有効"+ },+ {+ "zh": "只在实时预览生效:被复用的帧不跑 NR 推理,改用上一帧的 NR 变化按光流对齐后叠加,下一帧一定重新推理;对不齐的地方显示原画面。",+ "src": "qml/ProPage.qml",+ "zh-TW": "只在即時預覽生效:被復用的幀不跑 NR 推理,改用上一幀的 NR 變化按光流對齊後疊加,下一幀一定重新推理;對不齊的地方顯示原畫面。",+ "en": "Live preview only: a reused frame skips NR inference and applies the previous frame's NR change, aligned by optical flow; the next frame always runs inference again. Where the alignment does not match, the original picture is shown.",+ "ja": "リアルタイムプレビューのみ有効:再利用するフレームは NR 推論を行わず、前のフレームの NR による変化をオプティカルフローで位置合わせして重ねます。次のフレームでは必ず推論し直します。位置が合わない部分は元の画面を表示します。"+ },{"zh": "只在这个亮度以下的暗部生效","src": "qml/ProDisplayPanel.qml",@@ -6196,6 +6266,13 @@"en": "Copy track parameters","ja": "トラックパラメーターのコピー"},+ {+ "zh": "复用方式",+ "src": "qml/ProPage.qml",+ "zh-TW": "復用方式",+ "en": "Reuse mode",+ "ja": "再利用の方式"+ },{"zh": "外挂","src": "src/ui/bridge/Subtitles.cpp",@@ -6819,6 +6896,13 @@"en": "Export ","ja": "書き出し "},+ {+ "zh": "导出、暂停单帧和图片照常逐帧完整推理。目前支持英伟达 NR、SDR 和列表模式。",+ "src": "qml/ProPage.qml",+ "zh-TW": "匯出、暫停單幀和圖片照常逐幀完整推理。目前支援英偉達 NR、SDR 和列表模式。",+ "en": "Export, paused frames and images still run full inference on every frame. Currently NVIDIA NR, SDR and list mode only.",+ "ja": "書き出し、一時停止中のフレーム、画像はこれまでどおり全フレームで推論します。現在は NVIDIA NR、SDR、リストモードのみ対応です。"+ },{"zh": "导出「","src": "qml/ColourPanel.qml",@@ -7589,6 +7673,20 @@"en": "On · strength ","ja": "オン · 強度 "},+ {+ "zh": "已开启 · 每 ",+ "src": "qml/ProPage.qml",+ "zh-TW": "已開啟 · 每 ",+ "en": "On · 1 reused in every ",+ "ja": "オン · "+ },+ {+ "zh": "已开启 · 自动",+ "src": "qml/ProPage.qml",+ "zh-TW": "已開啟 · 自動",+ "en": "On · automatic",+ "ja": "オン · 自動"+ },{"zh": "已开启,将在播放时请求可变刷新;是否生效以驱动报告为准","src": "src/ui/bridge/FrameGeneration.cpp",@@ -8863,6 +8961,27 @@"en": "Manual","ja": "手動"},+ {+ "zh": "手动 1/2 · 每 2 帧复用 1 帧",+ "src": "qml/ProPage.qml",+ "zh-TW": "手動 1/2 · 每 2 幀復用 1 幀",+ "en": "Manual 1/2 · reuse 1 frame in 2",+ "ja": "手動 1/2 · 2 フレームに 1 回再利用"+ },+ {+ "zh": "手动 1/3 · 每 3 帧复用 1 帧",+ "src": "qml/ProPage.qml",+ "zh-TW": "手動 1/3 · 每 3 幀復用 1 幀",+ "en": "Manual 1/3 · reuse 1 frame in 3",+ "ja": "手動 1/3 · 3 フレームに 1 回再利用"+ },+ {+ "zh": "手动 1/4 · 每 4 帧复用 1 帧",+ "src": "qml/ProPage.qml",+ "zh-TW": "手動 1/4 · 每 4 幀復用 1 幀",+ "en": "Manual 1/4 · reuse 1 frame in 4",+ "ja": "手動 1/4 · 4 フレームに 1 回再利用"+ },{"zh": "手动 HDR 需要 P010/P016 格式;SDR 信号请选择自动或 Rec.709。","src": "src/source/CaptureCardSource.cpp",@@ -10425,13 +10544,6 @@"en": "Display","ja": "表示"},- {- "zh": "显示 fps",- "src": "qml/NodePage.qml",- "zh-TW": "顯示 fps",- "en": "Display fps",- "ja": "表示 fps"- },{"zh": "显示全部可用帧率","src": "qml/CaptureSourceDialog.qml",@@ -10530,13 +10642,6 @@"en": "Display peak","ja": "ディスプレイのピーク"},- {- "zh": "显示帧率",- "src": "qml/ProDisplayPanel.qml",- "zh-TW": "顯示幀率",- "en": "Show frame rate",- "ja": "フレームレートを表示"- },{"zh": "显示播放条","src": "qml/TopDock.qml",@@ -10831,6 +10936,13 @@"en": "Recent","ja": "最近"},+ {+ "zh": "最近 10 秒里最慢的 1% 提交间隔折算的帧率,和 RTSS 等叠加工具的算法相同",+ "src": "qml/ProDisplayPanel.qml",+ "zh-TW": "最近 10 秒裡最慢的 1% 提交間隔折算的幀率,和 RTSS 等疊加工具的算法相同",+ "en": "The frame rate of the slowest 1% of submit intervals in the last 10 s, computed the same way as overlays such as RTSS",+ "ja": "直近 10 秒で最も遅い 1% の提出間隔から求めたフレームレート。RTSS などのオーバーレイと同じ計算方法です"+ },{"zh": "有效目标 %1 fps","src": "src/ui/bridge/Status.cpp",@@ -11027,6 +11139,13 @@"en": "No beauty layer · original face restore and skin smoothing","ja": "美顔層なし · 顔のオリジナル保護と美肌"},+ {+ "zh": "未生效:",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "未生效:",+ "en": "Inactive: ",+ "ja": "無効:"+ },{"zh": "未登录","src": "qml/Ps5SourceDialog.qml",@@ -12028,6 +12147,13 @@"en": "Low mastering peak (older or converted title)","ja": "マスタリングのピークが低い作品(旧作・変換版)"},+ {+ "zh": "每 %1 帧复用 1 帧",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "每 %1 幀復用 1 幀",+ "en": "reusing 1 frame in %1",+ "ja": "%1 フレームに 1 回再利用"+ },{"zh": "每帧识别 · 320 像素,最省;远处的小脸可能识别不到","src": "qml/BeautyEditor.qml",@@ -14030,6 +14156,13 @@"en": "Auto NR instance pool unavailable; keeping the fixed 1080p policy","ja": "自動 NR のインスタンスプールを使用できません。固定 1080p 設定を維持します"},+ {+ "zh": "自动 NR 尺寸开启时不复用",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "自動 NR 尺寸開啟時不復用",+ "en": "not used with automatic NR size",+ "ja": "NR サイズの自動調整中は再利用しません"+ },{"zh": "自动 NR 当前仅验证 RTX 5070","src": "src/ui/bridge/Hardware.cpp",@@ -14037,6 +14170,13 @@"en": "Auto NR is currently verified only on RTX 5070","ja": "自動 NR は現在 RTX 5070 のみで検証済みです"},+ {+ "zh": "自动 · ",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "自動 · ",+ "en": "Automatic · ",+ "ja": "自動 · "+ },{"zh": "自动 · 恒定质量","src": "include/veyra/engine/EnhancementSettings.h",@@ -14240,6 +14380,13 @@"en": "Auto: HEVC first, H.264 when the host does not support it","ja": "自動:HEVC を優先し、ホストが非対応なら H.264"},+ {+ "zh": "自动:只在跟不上时复用,最多每 2 帧复用 1 帧;手动:固定比例",+ "src": "qml/ProPage.qml",+ "zh-TW": "自動:只在跟不上時復用,最多每 2 幀復用 1 幀;手動:固定比例",+ "en": "Automatic: reuses only when the preview cannot keep up, at most 1 frame in 2. Manual: a fixed ratio",+ "ja": "自動:処理が追いつかないときだけ再利用し、最大で 2 フレームに 1 回。手動:固定の割合"+ },{"zh": "自定义","src": "qml/NodePage.qml",@@ -14569,6 +14716,13 @@"en": "Node mode really runs in link order; offline export supports list mode only.","ja": "ノードモードは接続順に実際に処理します。オフラインの書き出しはリストモードのみ対応です。"},+ {+ "zh": "节点模式暂不支持",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "節點模式暫不支援",+ "en": "not available in node mode yet",+ "ja": "ノードモードはまだ非対応です"+ },{"zh": "节点模式请用节点的复制","src": "src/ui/bridge/Enhancement.cpp",@@ -15836,6 +15990,13 @@"en": "Resource unavailable","ja": "リソースを使用できません"},+ {+ "zh": "资源不足",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "資源不足",+ "en": "not enough resources",+ "ja": "リソースが不足しています"+ },{"zh": "赞助作者","src": "qml/SettingsPage.qml",@@ -15997,6 +16158,13 @@"en": "Higher is steadier at rest; moving faces are followed closely either way","ja": "高いほど静止時に安定します。動く顔はどの設定でもしっかり追従します"},+ {+ "zh": "跟得上,每帧都推理",+ "src": "src/ui/bridge/Playback.cpp",+ "zh-TW": "跟得上,每幀都推理",+ "en": "keeping up, inferring every frame",+ "ja": "追いついています。全フレームで推論中"+ },{"zh": "跟踪平滑","src": "qml/BeautyEditor.qml",@@ -17803,13 +17971,6 @@"en": "Use a direct media URL. Ordinary web pages and pages requiring browser sign-in cannot be played directly. Live streams usually do not support seeking.","ja": "メディアの直接 URL が必要です。通常の Web ページやブラウザーでのログインが必要なページは直接再生できません。ライブ配信では通常シークできません。"},- {- "zh": "需要系统显示事件才能测得真实值;取不到时显示未测",- "src": "qml/ProDisplayPanel.qml",- "zh-TW": "需要系統顯示事件才能測得真實值;取不到時顯示未測",- "en": "Real values need system display events; shows Not measured when they are unavailable",- "ja": "実際の値にはシステムの表示イベントが必要です。取得できない場合は「未計測」と表示します"- },{"zh": "需要重启软件","src": "qml/SettingsPage.qml",@@ -18923,6 +19084,13 @@"en": "Off by default · only steadies parts of the picture that do not change; moving parts do not smear","ja": "既定はオフ · 変化していない部分だけを安定させ、動く部分に残像は出ません"},+ {+ "zh": "默认关闭 · 跟不上时让部分帧沿用上一帧的 NR 结果",+ "src": "qml/ProPage.qml",+ "zh-TW": "預設關閉 · 跟不上時讓部分幀沿用上一幀的 NR 結果",+ "en": "Off by default · when the preview cannot keep up, some frames reuse the previous frame's NR result",+ "ja": "既定はオフ · 処理が追いつかないとき、一部のフレームで前のフレームの NR 結果を再利用します"+ },{"zh": "默认关闭。仅 NVIDIA HDR10 补帧时生效;4K 额外约 32 MiB 显存,可能增加 GPU 开销。切换时画面可能短暂停顿。","src": "qml/SettingsPage.qml",diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.hindex 1f0266c5..d27d001d 100644--- a/include/veyra/diagnostics/FrameMetrics.h+++ b/include/veyra/diagnostics/FrameMetrics.h@@ -75,6 +75,8 @@ struct FrameFlowMetrics {double validGeneratedFps=0,presentSubmitFps=0,sourceCompletedFps=0,outputCompletedFps=0,xessSdkSubmitFps=0;double realPresentFps=0,generatedPresentFps=0;bool rateWindowReady=false;+ // 1% low of the present rate (FramePaceWindow); unknown until enough presents.+ std::optional<double> presentLow1Fps;std::optional<double> softwareLatencyMs,softwareLatencyP95Ms,slotWaitPerFrameMs;uint64_t latencySamples=0;uint32_t pendingOutputFrames=0; // valid frame opportunities retained by presenter jobsdiff --git a/include/veyra/engine/AutoNrReuseController.h b/include/veyra/engine/AutoNrReuseController.hnew file mode 100644index 00000000..be109fad--- /dev/null+++ b/include/veyra/engine/AutoNrReuseController.h@@ -0,0 +1,79 @@+#pragma once+#include <cmath>+#include <cstdint>+#include <optional>++namespace veyra::engine {+// Chooses the NR inference reuse level in Auto (pipeline/NrReuse.h): 0 infers+// every frame, 1/2/3 reuse one frame in every 4/3/2.+//+// Unlike the NR size pool a level change costs nothing (no instance rebuild,+// no drained presentation), so this reacts within about a second. It only+// steps down when the lower level is predicted to fit with room to spare,+// using the measured NR inference time, so it does not bounce.+//+// Inputs come from the same one-second FrameFlowWindow:+// meanMs - mean enhancement processing per source frame. Reuse lowers the+// mean; the P95 stays an inferred frame's cost, so it cannot judge.+// nrMs - mean NR inference time of an inferred frame, all layers.+// budget - 80% of the transport frame interval, as for the size pool.+class AutoNrReuseController {+public:+ static constexpr unsigned kMaxLevel = 3;+ static constexpr double reusedShare(unsigned level) {+ return level == 1 ? 0.25 : level == 2 ? 1.0 / 3.0 : level == 3 ? 0.5 : 0.0;+ }+ void reset(int64_t now100ns, unsigned level = 0) {+ level_ = level > kMaxLevel ? 0 : level;+ discardObservations(now100ns);+ }+ void discardObservations(int64_t now100ns) {+ next_ = now100ns + kSettle;+ overSince_.reset();+ lowSince_.reset();+ }+ std::optional<unsigned> observe(int64_t now100ns, std::optional<double> meanMs, uint64_t samples,+ std::optional<double> nrMs, double budgetMs) {+ if (now100ns < next_) return {};+ next_ = now100ns + kStep;+ if (!meanMs || !std::isfinite(*meanMs) || *meanMs <= 0 || samples < 8 ||+ !std::isfinite(budgetMs) || budgetMs <= 0) {+ overSince_.reset();+ lowSince_.reset();+ return {};+ }+ const bool over = *meanMs > budgetMs;+ if (over) { if (!overSince_) overSince_ = now100ns; }+ else overSince_.reset();+ bool fitsLower = false;+ if (level_ > 0 && !over) {+ // The inferences one level down would add back. Without an NR+ // measurement assume the whole mean, which only delays a step down.+ const double perInference = nrMs && std::isfinite(*nrMs) && *nrMs > 0 ? *nrMs : *meanMs;+ const double added = (reusedShare(level_) - reusedShare(level_ - 1)) * perInference;+ fitsLower = *meanMs + added < budgetMs * kLowerFit;+ }+ if (fitsLower) { if (!lowSince_) lowSince_ = now100ns; }+ else lowSince_.reset();+ if (over && level_ < kMaxLevel && now100ns - *overSince_ >= kRaiseAfter) return change(now100ns, level_ + 1);+ if (fitsLower && now100ns - *lowSince_ >= kLowerAfter) return change(now100ns, level_ - 1);+ return {};+ }+ unsigned level() const { return level_; }++private:+ // The flow window spans one second and refreshes every 0.25 s: after a+ // change, wait until it holds only frames measured at the new level.+ static constexpr int64_t kSettle = 12500000, kStep = 2500000;+ static constexpr int64_t kRaiseAfter = 5000000, kLowerAfter = 30000000;+ static constexpr double kLowerFit = 0.85;+ std::optional<unsigned> change(int64_t now100ns, unsigned level) {+ level_ = level;+ discardObservations(now100ns);+ return level_;+ }+ unsigned level_ = 0;+ int64_t next_ = 0;+ std::optional<int64_t> overSince_, lowSince_;+};+}diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex d9fab437..58792872 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -78,6 +78,14 @@ struct PlayerSnapshot {bool nrAutoActive=false;uint32_t nrAutoPercent=0,nrAutoWidth=0,nrAutoHeight=0;std::wstring nrAutoStatus;+ // NR inference reuse: whether the preview graph runs it, whether Auto+ // chooses the level, the level (0 infers every frame, 1/2/3 reuse one+ // frame in every 4/3/2), frames reused so far, and why a requested mode is+ // not running (ASCII reason from EnhanceGraph::nrReuseIneligibility).+ bool nrReuseActive=false,nrReuseAutomatic=false;+ uint32_t nrReuseLevel=0;+ uint64_t nrReuseFrames=0;+ std::string nrReuseUnavailable;bool videoHdrActive=false; // TrueHDR actually running this graph (needs an HDR display path)std::wstring backendWarning;std::wstring sourceNotice;@@ -125,6 +133,7 @@ struct PlayerSnapshot {uint32_t posterWidth=0,posterHeight=0;diagnostics::FrameMetrics metrics;std::optional<double> submissionFps;+ std::optional<double> submissionLow1Fps; // 1% low of the presents, as an overlay reports ituint32_t flowPerf=0;int contentFps=0;uint64_t frames=0,generated=0;uint64_t captureReceived=0,captureDropped=0,nrEvaluated=0,nvofExecuted=0;diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex 94e210f7..2e307f7a 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -31,6 +31,16 @@ enum class NrAntiFlicker : uint8_t { Off, Static, Flow, FlowPlus, LowFrequency }inline bool validNrAntiFlicker(NrAntiFlicker v) {return v>=NrAntiFlicker::Off&&v<=NrAntiFlicker::LowFrequency;}+// NR inference reuse, realtime preview only (docs/NR_INFERENCE_REUSE_2026-11-07.md).+// A reused frame skips NR inference and carries the previous frame's NR change+// along the optical flow; the next frame always infers again. Off infers every+// frame. Auto reuses only while the preview cannot keep up. Half, Third and+// Quarter reuse one frame in every 2, 3 and 4. Export, paused frames and+// images always infer every frame whatever this says.+enum class NrReuseMode : uint8_t { Off, Auto, Half, Third, Quarter };+inline bool validNrReuseMode(NrReuseMode v) {+ return v>=NrReuseMode::Off&&v<=NrReuseMode::Quarter;+}// 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, Vfg = 4 };@@ -412,6 +422,8 @@ struct EnhancementSettings {// tuned against (see shaders/NrHold.hlsl).float nrHoldStrength=0.0f;float nrHoldTolerance=0.02f;+ // Preview only; see NrReuseMode. Off by default.+ NrReuseMode nrReuse=NrReuseMode::Off;pipeline::NrSizePolicy nrPolicy=pipeline::NrSizePolicy::Realtime;FlowQuality flow=FlowQuality::Balanced;OpticalFlowBackend opticalFlowBackend=OpticalFlowBackend::Nvidia;@@ -480,6 +492,7 @@ struct EnhancementSettings {active.additionalBeauty[i]=i<additionalBeautyCount?additionalBeauty[i].active():BeautySettings{};if(!beautyEnabled())active.beautyDetection=defaults.beautyDetection;if(nrHoldStrength==0)active.nrHoldTolerance=defaults.nrHoldTolerance;+ if(!nr)active.nrReuse=defaults.nrReuse;if(!hdrCurve.enabled){active.hdrCurve=defaults.hdrCurve;// Display peak also rescales enabled HDR10 metadata, independently@@ -570,6 +583,7 @@ struct EnhancementSettings {// a relative box-luma delta, so anything above 1 would hold every pixel.if(!range(nrHoldStrength,1))return "output stabiliser strength out of range";if(!range(nrHoldTolerance,1))return "output stabiliser tolerance out of range";+ if(!validNrReuseMode(nrReuse))return "invalid NR inference reuse mode";if(!range(model.intensity,1)||!range(model.tone,1)||!range(model.structure,1))return "model parameter out of range";if(model.skin!=-1&&!range(model.skin,2))return "skin parameter out of range";if(model.style<0||model.style>2||model.autoMask<0||model.autoMask>1||model.uiCorrection<0||model.uiCorrection>1)return "invalid experimental parameter";diff --git a/include/veyra/engine/FrameFlowWindow.h b/include/veyra/engine/FrameFlowWindow.hindex f853dcf9..21061aeb 100644--- a/include/veyra/engine/FrameFlowWindow.h+++ b/include/veyra/engine/FrameFlowWindow.h@@ -15,6 +15,7 @@ class FrameCompletionRates {mutable std::mutex mutex_;FrameRateWindow generated_,presented_,source_,output_,xess_;FrameRateWindow realPresented_,generatedPresented_;+ FramePaceWindow presentPace_;int64_t start_;public:explicit FrameCompletionRates(int64_t now):start_(now){@@ -26,12 +27,13 @@ public:if(real){source_.complete(now);output_.complete(now);}for(unsigned i=0;i<valid;++i){generated_.complete(now);output_.complete(now);}}- void presented(bool generated,int64_t now){std::lock_guard lock(mutex_);presented_.complete(now);(generated?generatedPresented_:realPresented_).complete(now);}+ void presented(bool generated,int64_t now){std::lock_guard lock(mutex_);presented_.complete(now);presentPace_.complete(now);(generated?generatedPresented_:realPresented_).complete(now);}void xess(uint64_t count,int64_t now){std::lock_guard lock(mutex_);for(uint64_t i=0;i<count;++i)xess_.complete(now);}void snapshot(diagnostics::FrameFlowMetrics& m,int64_t now)const{std::lock_guard lock(mutex_);m.validGeneratedFps=generated_.rate(now);m.presentSubmitFps=presented_.rate(now);m.sourceCompletedFps=source_.rate(now);m.outputCompletedFps=output_.rate(now);m.xessSdkSubmitFps=xess_.rate(now);m.rateWindowReady=now-start_>=10000000;m.realPresentFps=realPresented_.rate(now);m.generatedPresentFps=generatedPresented_.rate(now);+ m.presentLow1Fps=presentPace_.lowFps(now);}};// Each asynchronous job retains its own window. Replacing the current windowdiff --git a/include/veyra/engine/FrameRateWindow.h b/include/veyra/engine/FrameRateWindow.hindex 39a6d2d1..ce04c6a2 100644--- a/include/veyra/engine/FrameRateWindow.h+++ b/include/veyra/engine/FrameRateWindow.h@@ -1,7 +1,12 @@#pragma once#include <algorithm>+#include <cmath>+#include <cstddef>#include <cstdint>#include <deque>+#include <optional>+#include <utility>+#include <vector>namespace veyra::engine {// Completion events, not source arrivals or generated-frame multipliers.// Call under the owning controller's mutex. All times use monotonic 100 ns.@@ -23,4 +28,33 @@ private:int64_t start_=0;std::deque<int64_t> times_;};+// The "1% low" a frame-time overlay (RTSS, PresentMon) reports for an+// application: the 99th-percentile interval between consecutive presents over+// the last ten seconds, as a frame rate. Like those tools it measures Present+// calls, the same events as the submit rate, not panel scanout. A gap over half+// a second is a pause or a seek rather than a slow frame: it is not counted and+// the next present starts a new run.+class FramePaceWindow {+public:+ void reset(){last_=0;intervals_.clear();}+ void complete(int64_t now){+ if(last_>0&&now>last_&&now-last_<=kGap)intervals_.push_back({now,now-last_});+ last_=now;+ while(intervals_.size()>16384||(!intervals_.empty()&&intervals_.front().first<=now-kWindow))intervals_.pop_front();+ }+ std::optional<double> lowFps(int64_t now)const{+ std::vector<int64_t> recent;recent.reserve(intervals_.size());+ for(const auto& entry:intervals_)if(entry.first>now-kWindow)recent.push_back(entry.second);+ if(recent.size()<kMinIntervals)return {};+ const size_t at=size_t(std::ceil(0.99*double(recent.size())))-1;+ std::nth_element(recent.begin(),recent.begin()+std::ptrdiff_t(at),recent.end());+ if(recent[at]<=0)return {};+ return 10000000.0/double(recent[at]);+ }+ static constexpr int64_t kWindow=100000000,kGap=5000000;+ static constexpr size_t kMinIntervals=100;+private:+ int64_t last_=0;+ std::deque<std::pair<int64_t,int64_t>> intervals_; // present time, interval since the previous one+};}diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.hindex 031a5c25..39161b9c 100644--- a/include/veyra/engine/GraphDescription.h+++ b/include/veyra/engine/GraphDescription.h@@ -13,6 +13,7 @@ inline void describeNrLayers(const EnhancementSettings& settings,pipeline::Enhandesc.nrAntiFlicker=settings.residual.correction.enabled?NrAntiFlicker::Flow:settings.nrAntiFlicker;desc.model=settings.model;desc.residual=settings.residual;desc.protection=settings.protection;desc.nrHoldStrength=settings.nrHoldStrength;desc.nrHoldTolerance=settings.nrHoldTolerance;+ desc.nrReuse=settings.nr?settings.nrReuse:NrReuseMode::Off;desc.nrLayersModel.clear();desc.nrLayersResidual.clear();desc.nrLayersTemporal.clear();desc.nrLayersAntiFlicker.clear();desc.nrLayersProtection.clear();desc.nrLayersSizePolicy={settings.nrPolicy};diff --git a/include/veyra/engine/RecentGraphCache.h b/include/veyra/engine/RecentGraphCache.hindex d57efbc3..d76f4f8b 100644--- a/include/veyra/engine/RecentGraphCache.h+++ b/include/veyra/engine/RecentGraphCache.h@@ -44,7 +44,7 @@ public:}static bool eligible(const pipeline::EnhanceGraphDesc& desc){return desc.enableNr&&!desc.enableSr&&!desc.enableFg&&!desc.hdrInput&&!desc.hdrOutput&&!desc.videoHdr.enabled&&!desc.color.enabled&&desc.additionalColorCount==0&&- !desc.antiAliasActive()&&!desc.beautyActive()&&desc.nrHoldStrength==0&&!desc.noFeatures&&!desc.noNgx&&!desc.stillImage&&!desc.nrAutoPoolLayer&&+ !desc.antiAliasActive()&&!desc.beautyActive()&&desc.nrHoldStrength==0&&desc.nrReuse==NrReuseMode::Off&&!desc.noFeatures&&!desc.noNgx&&!desc.stillImage&&!desc.nrAutoPoolLayer&¤tNrRuntime(desc.nrRuntime)==NrRuntime::Ampere&&!desc.nrTemporal&&desc.nrLayersModel.size()<=1&&std::none_of(desc.nrLayersTemporal.begin(),desc.nrLayersTemporal.end(),[](bool value){return value;})&&!desc.runtimeNodeOrder&&(!desc.fixedExecutionPlan||(diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 82b6867a..0c2672ea 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -11,6 +11,8 @@#include "veyra/pipeline/ResolutionPlan.h"#include "veyra/pipeline/NrTemporalPass.h"#include "veyra/pipeline/NrHoldPass.h"+#include "veyra/pipeline/NrReuse.h"+#include "veyra/pipeline/NrReusePass.h"#include "veyra/pipeline/FramePacket.h" // ColorDescription, for the HDR display metadata// EnhanceGraph - the real unified processing graph (Playbook R3.2).@@ -167,6 +169,11 @@ struct EnhanceGraphDesc {// without it. See shaders/NrHold.hlsl.float nrHoldStrength=0.0f;float nrHoldTolerance=0.02f;+ // NR inference reuse (NrReuse.h). Only the realtime preview builder sets+ // nrReusePreview; export, image and diagnostic graphs leave it false and+ // infer every frame whatever nrReuse says. Off creates no reuse pass.+ bool nrReusePreview=false;+ engine::NrReuseMode nrReuse=engine::NrReuseMode::Off;// Colour grade (plan v4). When color.enabled is false the stage does not// exist: no tables are allocated, no constants are packed and the ingest// shaders return their linear RGB untouched.@@ -630,6 +637,17 @@ public:bool selectAutoNrLevel(unsigned level);bool autoNrPoolReady()const{return nrAutoPoolReady_;}unsigned autoNrLevel()const{return nrAutoLevel_;}+ // NR inference reuse (NrReuse.h): active only in a preview graph built with+ // a mode other than Off and a supported NR chain. Auto takes its level+ // from the engine; a manual mode pins it. Empty reason: active or not asked.+ bool nrReuseActive()const{return nrReusePass_!=nullptr;}+ bool nrReuseAutomatic()const{return nrReusePass_&&desc_.nrReuse==engine::NrReuseMode::Auto;}+ unsigned nrReuseLevel()const{return nrReuseScheduler_.level();}+ // The last processed frame reused instead of inferring. A paused picture+ // must be fully inferred, so the engine re-renders such a frame on pause.+ bool nrReuseLastFrameReused()const{return nrReusePass_&&nrReuseScheduler_.lastReused();}+ void setNrReuseLevel(unsigned level);+ const std::string& nrReuseUnavailable()const{return nrReuseUnavailable_;}Extent autoNrExtent()const{return nrAutoPoolReady_&&desc_.nrAutoPoolLayer?desc_.nrLayersExtent[*desc_.nrAutoPoolLayer]:Extent{};}// s10 ownership-order teardown: NVOF fence drain must happen BEFORE this@@ -650,6 +668,7 @@ public:uint64_t fgSubmittedCandidates = 0, fgDisabledFrames = 0;uint64_t fgProviderDisabled = 0;uint64_t nrMotionFrames = 0, sceneCutCount = 0, resetCount = 0;+ uint64_t nrReuseFrames = 0, nrReuseChainedMotion = 0;};const Metrics& metrics() const { return metrics_; }const std::string& mvecSource() const { return mvecSource_; }@@ -915,6 +934,15 @@ private:// setting is non-zero; a default (0) session never allocates it and the// dispatch is skipped, so the disabled path is unchanged.std::unique_ptr<NrHoldPass> nrHoldPass_;+ // NR inference reuse: constructed only for a preview graph that asked for+ // it and whose NR chain qualifies (createNrReusePass), so every other+ // graph records exactly the commands it did before.+ std::unique_ptr<NrReusePass> nrReusePass_;+ NrReuseScheduler nrReuseScheduler_;+ bool nrReuseKeyValid_=false; // the previous frame inferred and stored its chain+ double nrReuseInferredPts_=0; // PTS of the last frame that ran NR inference+ std::string nrReuseUnavailable_;+ std::string nrReuseIneligibility() const;// 纹理 / 清晰度 / 去朦胧 of the list grade fused into input conversion (srcRgba_).ColorDetailPass colorDetail_;// The texture the rest of the graph reads as "the NR result". Without the@@ -922,6 +950,7 @@ private:// produces. Set once per frame, read by the SR/FG/tail bindings below.ID3D12Resource* nrOutputView_=nullptr;bool createNrHoldPass();+ bool createNrReusePass();// --- colour grade (v4): CPU-baked tables read by the ingest shaders -----bool colorActive_=false;std::wstring colorLutNotice_;diff --git a/include/veyra/pipeline/NrReuse.h b/include/veyra/pipeline/NrReuse.hnew file mode 100644index 00000000..f04795e1--- /dev/null+++ b/include/veyra/pipeline/NrReuse.h@@ -0,0 +1,61 @@+#pragma once+#include "veyra/engine/EnhancementSettings.h"+#include <cstdint>++namespace veyra::pipeline {+// NR inference reuse, frame selection (docs/NR_INFERENCE_REUSE_2026-11-07.md).+//+// Veyra's own design for the realtime preview: when the GPU cannot keep up, a+// frame may skip NR inference and carry the change made by the frame before+// it along the optical flow. A reused frame is ALWAYS followed by an inferred+// one, so a carried change is never older than one source frame and a wrong+// vector can only show for one frame.+//+// Levels: 0 infers every frame; 1, 2 and 3 reuse one frame in every 4, 3 and+// 2. Manual modes pin a level; Auto lets the engine's controller choose it.+// Export, paused frames and images never construct a scheduler.+class NrReuseScheduler {+public:+ static constexpr unsigned kMaxLevel = 3;+ // Inferred frames between two reused ones; zero never reuses.+ static constexpr unsigned inferredPerReuse(unsigned level) {+ return level == 1 ? 3u : level == 2 ? 2u : level == 3 ? 1u : 0u;+ }+ // One reused frame in every `framesPerReuse`, for logs and the UI.+ static constexpr unsigned framesPerReuse(unsigned level) {+ return level ? inferredPerReuse(level) + 1 : 0u;+ }+ static constexpr unsigned levelFor(engine::NrReuseMode mode) {+ return mode == engine::NrReuseMode::Half ? 3u : mode == engine::NrReuseMode::Third ? 2u :+ mode == engine::NrReuseMode::Quarter ? 1u : 0u;+ }++ void setLevel(unsigned level) { level_ = level > kMaxLevel ? kMaxLevel : level; }+ unsigned level() const { return level_; }+ // Once per frame, before NR. `available`: a stored inference from the+ // previous frame and this frame's motion both exist, and nothing reset.+ // Returns true when this frame reuses instead of inferring.+ bool next(bool available) {+ if (level_ == 0 || !available || lastReused_ || inferred_ < inferredPerReuse(level_)) {+ lastReused_ = false;+ ++inferred_;+ return false;+ }+ lastReused_ = true;+ inferred_ = 0;+ return true;+ }+ bool lastReused() const { return lastReused_; }+ // After an inferred frame: whether the next frame may reuse it, so only+ // that inferred frame needs to keep its chain (1/3 and 1/4 skip the rest).+ bool reuseMayFollow() const { return level_ && !lastReused_ && inferred_ >= inferredPerReuse(level_); }+ // A reset, rebuild or settings change: the next frame infers and the+ // pattern restarts from there.+ void reset() { inferred_ = 0; lastReused_ = false; }++private:+ unsigned level_ = 0;+ unsigned inferred_ = 0;+ bool lastReused_ = false;+};+}diff --git a/include/veyra/pipeline/NrReusePass.h b/include/veyra/pipeline/NrReusePass.hnew file mode 100644index 00000000..980db5b5--- /dev/null+++ b/include/veyra/pipeline/NrReusePass.h@@ -0,0 +1,60 @@+#pragma once+#include "veyra/engine/EnhancementSettings.h"+#include "veyra/pipeline/GpuPassUtils.h"+#include <vector>++namespace veyra::pipeline {+// NR inference reuse, GPU side (docs/NR_INFERENCE_REUSE_2026-11-07.md).+//+// Owns everything a reused frame needs and nothing else: the last inferred+// frame's NR chain output and input, the motion back to that frame, and the+// passes that carry the change. The graph's own textures are borrowed:+// source - the NR chain input (EnhanceGraph::nrBaseInput)+// output - the NR chain output (residualRgba_), written on reused frames+// flow - this frame's current->previous flow at the flow extent+// targets - NR motion inputs; after a reused frame they receive the motion+// back to the last inferred frame, which is what NR's own history+// holds, instead of the one-frame flow+// A graph built without reuse never creates this pass, so its command stream+// is unchanged.+class NrReusePass {+public:+ struct MotionTarget { ID3D12Resource* texture = nullptr; uint32_t width = 0, height = 0; };+ bool initialize(ID3D12Device* device, uint32_t width, uint32_t height,+ uint32_t flowWidth, uint32_t flowHeight,+ ID3D12Resource* source, ID3D12Resource* output, ID3D12Resource* flow,+ const std::vector<MotionTarget>& targets);+ // Every frame with flow: motion back to the last inferred frame. `chain`+ // is true when the previous frame reused.+ void compose(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool chain);+ // Inferred frame after a reused one: overwrite NR's motion inputs.+ void writeMotionTargets(ID3D12GraphicsCommandList* list, StateTracker& tracker);+ // Inferred frame: keep its chain output and input for a following reuse.+ void store(ID3D12GraphicsCommandList* list, StateTracker& tracker);+ // Reused frame: output = source + carried change, outside `protection`.+ void reuse(ID3D12GraphicsCommandList* list, StateTracker& tracker, const engine::ProtectionSettings& protection);+ // Motion for the temporal stabiliser: identical to the flow after an+ // inferred frame, chained after a reused one.+ ID3D12Resource* motion() const { return motion_.Get(); }+ uint64_t bytes() const { return bytes_; }+ void close();++ // Perceptual box-luma mismatch: full weight below kLow, none above kHigh.+ static constexpr float kLow = 0.03f, kHigh = 0.08f;+ // Per-pixel detail mismatch: the fine part of the change is carried fully+ // below kDetailLow and not at all above kDetailHigh.+ static constexpr float kDetailLow = 0.03f, kDetailHigh = 0.09f;+ static constexpr unsigned kWarpConstants = 28;++private:+ ComputePass compose_, warp_, adapt_;+ ComPtr<ID3D12Resource> displacement_[2], motion_, keyOutput_, keySource_;+ std::vector<MotionTarget> targets_;+ ID3D12Resource* source_ = nullptr;+ ID3D12Resource* output_ = nullptr;+ ID3D12Resource* flow_ = nullptr;+ uint32_t width_ = 0, height_ = 0, flowWidth_ = 0, flowHeight_ = 0;+ unsigned latest_ = 0; // displacement_[latest_] holds this frame's result+ uint64_t bytes_ = 0;+};+}diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex b13dc51c..bc616a1a 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -45,15 +45,13 @@ class QmlPlayerBridge : public QObject {Q_OBJECT// --- professional-page readouts ---------------------------------------// Every one of these reports an engine value. Where the engine has no- // measurement the getter says so (e.g. displayFpsKnown stays false, because- // a display rate is only real if the system display event can be read - the- // design requires exactly this distinction rather than reusing submit FPS).+ // measurement the getter says so. There is no "display fps": panel scanout+ // is not measured, and overlays such as RTSS also count Present calls, which+ // is the submit rate below (with its 1% low).Q_PROPERTY(QString outputSummary READ outputSummary NOTIFY snapshotChanged)Q_PROPERTY(QString srStageSummary READ srStageSummary NOTIFY snapshotChanged)Q_PROPERTY(QString srStageNote READ srStageNote NOTIFY snapshotChanged)Q_PROPERTY(bool fullscreenMemorySafe READ fullscreenMemorySafe NOTIFY snapshotChanged)- Q_PROPERTY(double displayFps READ displayFps NOTIFY snapshotChanged)- Q_PROPERTY(bool displayFpsKnown READ displayFpsKnown NOTIFY snapshotChanged)Q_PROPERTY(double queuedFrames READ queuedFrames NOTIFY snapshotChanged)Q_PROPERTY(bool queuedFramesKnown READ queuedFramesKnown NOTIFY snapshotChanged)Q_PROPERTY(int skippedFrames READ skippedFrames NOTIFY snapshotChanged)@@ -298,6 +296,9 @@ class QmlPlayerBridge : public QObject {// number we cannot measure must not be shown as if we measured it).Q_PROPERTY(double submitFps READ submitFps NOTIFY snapshotChanged)Q_PROPERTY(bool submitFpsKnown READ submitFpsKnown NOTIFY snapshotChanged)+ // 1% low of the presents over the last ten seconds (FramePaceWindow).+ Q_PROPERTY(double submitLowFps READ submitLowFps NOTIFY snapshotChanged)+ Q_PROPERTY(bool submitLowFpsKnown READ submitLowFpsKnown NOTIFY snapshotChanged)Q_PROPERTY(double lateMs READ lateMs NOTIFY snapshotChanged)Q_PROPERTY(double lateP95Ms READ lateP95Ms NOTIFY snapshotChanged)Q_PROPERTY(QString metricsSummary READ metricsSummary NOTIFY snapshotChanged)@@ -323,6 +324,9 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(bool lowLatency READ lowLatency WRITE setLowLatency NOTIFY settingsChanged)Q_PROPERTY(bool nrTemporal READ nrTemporal WRITE setNrTemporal NOTIFY settingsChanged)Q_PROPERTY(double nrHoldStrength READ nrHoldStrength WRITE setNrHoldStrength NOTIFY settingsChanged)+ Q_PROPERTY(int nrReuseMode READ nrReuseMode WRITE setNrReuseMode NOTIFY settingsChanged)+ Q_PROPERTY(bool nrReuseActive READ nrReuseActive NOTIFY snapshotChanged)+ Q_PROPERTY(QString nrReuseStatus READ nrReuseStatus NOTIFY snapshotChanged)Q_PROPERTY(double nrHoldTolerance READ nrHoldTolerance WRITE setNrHoldTolerance NOTIFY settingsChanged)Q_PROPERTY(bool videoHdr READ videoHdr WRITE setVideoHdr NOTIFY settingsChanged)Q_PROPERTY(QVariantMap videoHdrParams READ videoHdrParams NOTIFY videoHdrParamsChanged)@@ -642,8 +646,6 @@ public:QString outputSummary() const;QString srStageSummary() const;QString srStageNote() const;- double displayFps() const;- bool displayFpsKnown() const;double queuedFrames() const;bool queuedFramesKnown() const;int skippedFrames() const;@@ -905,6 +907,8 @@ public:double submitFps() const;bool submitFpsKnown() const;+ double submitLowFps() const;+ bool submitLowFpsKnown() const;double lateMs() const;double lateP95Ms() const;QString metricsSummary() const;@@ -945,6 +949,10 @@ public:// Stage-5 output stabiliser (anti-flicker). Global rather than per-node:// it runs once, after the whole NR stack and the residual composite.double nrHoldStrength() const;+ int nrReuseMode() const;+ void setNrReuseMode(int value);+ bool nrReuseActive() const;+ QString nrReuseStatus() const;void setNrHoldStrength(double value);double nrHoldTolerance() const;void setNrHoldTolerance(double value);diff --git a/prototypes/ui-redesign-2026-09-25/icons.js b/prototypes/ui-redesign-2026-09-25/icons.jsindex 63bc7cf1..6c5b538e 100644--- a/prototypes/ui-redesign-2026-09-25/icons.js+++ b/prototypes/ui-redesign-2026-09-25/icons.js@@ -35,6 +35,7 @@ window.VI = (function () {palette: '<circle cx="13.5" cy="6.5" r=".5"/><circle cx="17.5" cy="10.5" r=".5"/><circle cx="8.5" cy="7.5" r=".5"/><circle cx="6.5" cy="12.5" r=".5"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/>',music: '<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',zap: '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',+ shield: '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>',sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2m-7.07-14.07 1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>',info: '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/>',check: '<path d="M20 6 9 17l-5-5"/>',diff --git a/qml/Veyra/IconData.js b/qml/Veyra/IconData.jsindex 27832184..8c3dd6b4 100644--- a/qml/Veyra/IconData.js+++ b/qml/Veyra/IconData.js@@ -38,6 +38,7 @@ var paths = {"palette": "M13 6.5a0.5 0.5 0 1 0 1 0a0.5 0.5 0 1 0 -1 0zM17 10.5a0.5 0.5 0 1 0 1 0a0.5 0.5 0 1 0 -1 0zM8 7.5a0.5 0.5 0 1 0 1 0a0.5 0.5 0 1 0 -1 0zM6 12.5a0.5 0.5 0 1 0 1 0a0.5 0.5 0 1 0 -1 0zM12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z","music": "M9 18V5l12-2v13M3 18a3 3 0 1 0 6 0a3 3 0 1 0 -6 0zM15 16a3 3 0 1 0 6 0a3 3 0 1 0 -6 0z","zap": "M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",+ "shield": "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z","sun": "M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0zM12 2v2M12 20v2m-7.07-14.07 1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41","info": "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0zM12 16v-4M12 8h.01","check": "M20 6 9 17l-5-5",diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qmlindex cb29cfa6..fa6f795a 100644--- a/qml/Veyra/NodePage.qml+++ b/qml/Veyra/NodePage.qml@@ -474,8 +474,8 @@ VPage {model: [{ k: qsTr("输入"), v: veyra.sourceSummary, hi: false },{ k: qsTr("输出"), v: veyra.outputSummary.length > 0 ? veyra.outputSummary : qsTr("未测"), hi: false },- { k: qsTr("显示 fps"), v: veyra.displayFpsKnown ? veyra.displayFps.toFixed(1) : qsTr("未测"), hi: true },- { k: veyra.submitFpsLabel + " fps", v: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : qsTr("未测"), hi: false },+ { k: veyra.submitFpsLabel + " fps", v: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : qsTr("未测"), hi: true },+ { k: qsTr("1% low"), v: veyra.submitLowFpsKnown ? veyra.submitLowFps.toFixed(1) : "—", hi: false },{ k: qsTr("待呈现"), v: veyra.queuedFramesKnown ? veyra.queuedFrames.toFixed(0) + qsTr(" 帧") : qsTr("未测"), hi: false }]delegate: RowLayout {@@ -495,7 +495,7 @@ VPage {}Text {text: modelData.v.length > 0 ? modelData.v : "—"- color: modelData.hi && veyra.displayFpsKnown ? Theme.ok : Theme.t1+ color: modelData.hi && veyra.submitFpsKnown ? Theme.ok : Theme.t1font.family: Theme.fontMonofont.pixelSize: modelData.hi ? 14 : 12font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBolddiff --git a/qml/Veyra/ProDisplayPanel.qml b/qml/Veyra/ProDisplayPanel.qmlindex c4c1b6c2..f5f6523d 100644--- a/qml/Veyra/ProDisplayPanel.qml+++ b/qml/Veyra/ProDisplayPanel.qml@@ -682,9 +682,9 @@ ColumnLayout {value: veyra.submitFpsKnown ? veyra.submitFps.toFixed(2) : qsTr("未测量")}VRow {- label: qsTr("显示帧率")- hint: qsTr("需要系统显示事件才能测得真实值;取不到时显示未测")- value: veyra.displayFpsKnown ? veyra.displayFps.toFixed(2) : qsTr("未测")+ label: qsTr("1% low")+ hint: qsTr("最近 10 秒里最慢的 1% 提交间隔折算的帧率,和 RTSS 等叠加工具的算法相同")+ value: veyra.submitLowFpsKnown ? veyra.submitLowFps.toFixed(2) : "—"}VRow {label: qsTr("晚点 P95")diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 8a6107b9..dabaf159 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -93,7 +93,7 @@ VPage {if (chip.type === "sr") target = "list-sr"else if (chip.type === "aa") target = "list-anti-alias"else if (chip.type === "video-hdr") target = "list-video-hdr"- else if (chip.type === "protection") target = "list-global-protection"+ else if (chip.type === "protection") { nrStage.open = true; target = "list-global-protection" }else if (chip.type === "beauty") {beautyStage.open = truelet ordinal = 0@@ -940,29 +940,31 @@ VPage {spacing: 6VEyebrow { text: qsTr("帧率与节奏") }- // The design puts "显示 fps" first and "提交 fps" after it, and its- // own note is explicit: a display rate is only real if the system- // display event can be read, and when it cannot it must say 未测- // rather than reuse the submit rate.+ // The submit rate is the headline, as an overlay such as RTSS shows+ // it: both count Present calls. Panel scanout is not measured, so+ // there is no separate display rate (it only ever said 未测). The+ // 1% low is the 99th-percentile present interval of the last 10 s.RowLayout {spacing: 6Text {- text: veyra.displayFpsKnown ? veyra.displayFps.toFixed(1) : qsTr("未测")- color: veyra.displayFpsKnown ? Theme.ok : Theme.t3+ objectName: "fps-submit"+ text: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : qsTr("未测")+ color: veyra.submitFpsKnown ? Theme.ok : Theme.t3font.family: Theme.fontMonofont.pixelSize: 22font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold}- Text { text: qsTr("显示 fps"); color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }+ Text { text: veyra.submitFpsLabel + " fps"; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }Rectangle { implicitWidth: 1; implicitHeight: 12; color: Theme.stroke2 }Text {- text: veyra.submitFpsKnown ? veyra.submitFps.toFixed(1) : qsTr("未测")+ objectName: "fps-low1"+ text: veyra.submitLowFpsKnown ? veyra.submitLowFps.toFixed(1) : "—"color: Theme.t1font.family: Theme.fontMonofont.pixelSize: 13font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold}- Text { text: veyra.submitFpsLabel; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }+ Text { text: qsTr("1% low"); color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11 }}// Frame-time line (design .spark): submit interval over the last// 12 s, the dashed line is the source frame budget.@@ -1469,123 +1471,171 @@ VPage {note: full ? qsTr("(最多 4 层)") : qsTr("(加在 NR ") + veyra.nrLayers.length + qsTr(" 之后 · 最多 4 层)")onAdd: { root.markPop(veyra.nrLayers.length + 1); root.selectedEffect = veyra.addEffect("nr") }}- }- // Stage-5 output stabiliser. Global, not per-layer: it- // runs once after the whole NR stack. Default off, and- // off means the pass is never even dispatched.- VAccordion {- objectName: "list-output-stabiliser"- Layout.fillWidth: true- visible: veyra.nodeMode === 0- title: qsTr("输出稳定器 · 抗闪烁")- glyph: "shield"; hue: Theme.accent- summary: veyra.nrHoldStrength > 0- ? qsTr("已开启 · 强度 ") + Math.round(veyra.nrHoldStrength * 100) + "%"- : qsTr("默认关闭 · 只稳住没变化的画面,动的地方不拖影")- on: veyra.nrHoldStrength > 0- onToggled: on => veyra.nrHoldStrength = on ? 0.8 : 0- Text {+ // Global NR options sit inside the NR stage, beside its layers+ // (field request 2026-11-07): each runs once over the whole stack.+ // Stage-5 output stabiliser. Global, not per-layer: it+ // runs once after the whole NR stack. Default off, and+ // off means the pass is never even dispatched.+ VAccordion {+ objectName: "list-output-stabiliser"Layout.fillWidth: true- text: qsTr("比较源画面与上一帧:没有明显变化的像素沿用上一帧输出,明显变化的位置直接用新结果。") +- qsTr("不重投影、不用光流,所以运动区域不会拖影。放在最后一层 NR 之后、超分与补帧之前。")- wrapMode: Text.WordWrap- color: Theme.t3- font.family: Theme.fontUi; font.pixelSize: 11- }- VRow {- label: qsTr("稳定强度")- hint: qsTr("越高越稳,过高会显得发闷")- visible: veyra.nrHoldStrength > 0- value: Math.round(veyra.nrHoldStrength * 100) + "%"- VSlider {- objectName: "list-hold-strength"- implicitWidth: 110- from: 0.1; to: 1.0; inputScale: 100- value: veyra.nrHoldStrength- onMoved: value => veyra.nrHoldStrength = value+ Layout.topMargin: 4+ visible: veyra.nodeMode === 0+ title: qsTr("输出稳定器 · 抗闪烁")+ glyph: "shield"; hue: Theme.accent+ summary: veyra.nrHoldStrength > 0+ ? qsTr("已开启 · 强度 ") + Math.round(veyra.nrHoldStrength * 100) + "%"+ : qsTr("默认关闭 · 只稳住没变化的画面,动的地方不拖影")+ on: veyra.nrHoldStrength > 0+ onToggled: on => veyra.nrHoldStrength = on ? 0.8 : 0+ Text {+ Layout.fillWidth: true+ text: qsTr("比较源画面与上一帧:没有明显变化的像素沿用上一帧输出,明显变化的位置直接用新结果。") ++ qsTr("不重投影、不用光流,所以运动区域不会拖影。放在最后一层 NR 之后、超分与补帧之前。")+ wrapMode: Text.WordWrap+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11}- }- VRow {- label: qsTr("变化容差")- hint: qsTr("越小越敏感,越大稳得越多")- visible: veyra.nrHoldStrength > 0- value: Number(veyra.nrHoldTolerance).toFixed(3)- VSlider {- objectName: "list-hold-tolerance"- implicitWidth: 110- inputDecimals: 3- from: 0.005; to: 0.10- value: veyra.nrHoldTolerance- onMoved: value => veyra.nrHoldTolerance = value+ VRow {+ label: qsTr("稳定强度")+ hint: qsTr("越高越稳,过高会显得发闷")+ visible: veyra.nrHoldStrength > 0+ value: Math.round(veyra.nrHoldStrength * 100) + "%"+ VSlider {+ objectName: "list-hold-strength"+ implicitWidth: 110+ from: 0.1; to: 1.0; inputScale: 100+ value: veyra.nrHoldStrength+ onMoved: value => veyra.nrHoldStrength = value+ }+ }+ VRow {+ label: qsTr("变化容差")+ hint: qsTr("越小越敏感,越大稳得越多")+ visible: veyra.nrHoldStrength > 0+ value: Number(veyra.nrHoldTolerance).toFixed(3)+ VSlider {+ objectName: "list-hold-tolerance"+ implicitWidth: 110+ inputDecimals: 3+ from: 0.005; to: 0.10+ value: veyra.nrHoldTolerance+ onMoved: value => veyra.nrHoldTolerance = value+ }}}- }- VAccordion {- objectName: "list-global-protection"- Layout.fillWidth: true- visible: veyra.nodeMode === 0- title: qsTr("NR 全局保护区域")- glyph: "shield"; hue: Theme.accent- summary: qsTr("区域内排除所有 NR 层 · 仅列表模式")- on: veyra.protectionEnabled- onToggled: on => veyra.protectionEnabled = on- Text {- Layout.fillWidth: true- text: veyra.protectionDrawShape.length > 0- ? qsTr("在画面上按住左键拖出") + (veyra.protectionDrawShape === "ellipse" ? qsTr("圆形 / 椭圆") : qsTr("矩形")) + qsTr("区域 · Esc 取消")- : qsTr("在画面上画出矩形或圆形区域(最多 4 个),区域内的画面不做任何一层 NR 处理。")- wrapMode: Text.WordWrap- color: veyra.protectionDrawShape.length > 0 ? Theme.accent : Theme.t3- font.family: Theme.fontUi; font.pixelSize: 11- }- RowLayout {+ // NR inference reuse (src/pipeline/NrReuse.h). Global like the+ // stabiliser and realtime preview only; default off, and off+ // builds no reuse pass at all.+ VAccordion {+ objectName: "list-nr-reuse"Layout.fillWidth: true- spacing: 6- VButton {- objectName: "list-protection-draw-rect"- text: qsTr("画矩形")- primary: veyra.protectionDrawShape === "rect"- onClicked: veyra.beginProtectionDraw(veyra.protectionDrawShape === "rect" ? "" : "rect")- }- VButton {- objectName: "list-protection-draw-ellipse"- text: qsTr("画圆形")- primary: veyra.protectionDrawShape === "ellipse"- onClicked: veyra.beginProtectionDraw(veyra.protectionDrawShape === "ellipse" ? "" : "ellipse")+ Layout.topMargin: 4+ visible: veyra.nodeMode === 0+ title: qsTr("NR 自动推理复用")+ glyph: "zap"; hue: Theme.accent+ summary: veyra.nrReuseMode === 0+ ? qsTr("默认关闭 · 跟不上时让部分帧沿用上一帧的 NR 结果")+ : veyra.nrReuseStatus.length > 0 ? veyra.nrReuseStatus+ : veyra.nrReuseMode === 1 ? qsTr("已开启 · 自动")+ : qsTr("已开启 · 每 ") + veyra.nrReuseMode + qsTr(" 帧复用 1 帧")+ on: veyra.nrReuseMode !== 0+ onToggled: on => veyra.nrReuseMode = on ? 1 : 0+ Text {+ Layout.fillWidth: true+ text: qsTr("只在实时预览生效:被复用的帧不跑 NR 推理,改用上一帧的 NR 变化按光流对齐后叠加,下一帧一定重新推理;对不齐的地方显示原画面。") ++ qsTr("导出、暂停单帧和图片照常逐帧完整推理。目前支持英伟达 NR、SDR 和列表模式。")+ wrapMode: Text.WordWrap+ color: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11}- Item { Layout.fillWidth: true }- VButton {- text: qsTr("清空"); ghost: true- visible: veyra.protectionRegions.length > 0- onClicked: veyra.clearProtectionRegions()+ VRow {+ label: qsTr("复用方式")+ hint: qsTr("自动:只在跟不上时复用,最多每 2 帧复用 1 帧;手动:固定比例")+ visible: veyra.nrReuseMode !== 0+ VSelect {+ objectName: "list-nr-reuse-mode"+ implicitWidth: 210+ options: [+ { id: "1", label: qsTr("自动") },+ { id: "2", label: qsTr("手动 1/2 · 每 2 帧复用 1 帧") },+ { id: "3", label: qsTr("手动 1/3 · 每 3 帧复用 1 帧") },+ { id: "4", label: qsTr("手动 1/4 · 每 4 帧复用 1 帧") }+ ]+ value: (options.find(o => o.id === String(veyra.nrReuseMode)) || options[0]).label+ onPicked: id => veyra.nrReuseMode = Number(id)+ }}}- Repeater {- model: veyra.protectionRegions- delegate: VRow {- required property var modelData- required property int index- label: (modelData.ellipse ? qsTr("圆形 ") : qsTr("矩形 ")) + (index + 1)- value: Math.round(modelData.left * 100) + "," + Math.round(modelData.top * 100) + " → "- + Math.round(modelData.right * 100) + "," + Math.round(modelData.bottom * 100) + " %"++ VAccordion {+ objectName: "list-global-protection"+ Layout.fillWidth: true+ Layout.topMargin: 4+ visible: veyra.nodeMode === 0+ title: qsTr("NR 全局保护区域")+ glyph: "shield"; hue: Theme.accent+ summary: qsTr("区域内排除所有 NR 层 · 仅列表模式")+ on: veyra.protectionEnabled+ onToggled: on => veyra.protectionEnabled = on+ Text {+ Layout.fillWidth: true+ text: veyra.protectionDrawShape.length > 0+ ? qsTr("在画面上按住左键拖出") + (veyra.protectionDrawShape === "ellipse" ? qsTr("圆形 / 椭圆") : qsTr("矩形")) + qsTr("区域 · Esc 取消")+ : qsTr("在画面上画出矩形或圆形区域(最多 4 个),区域内的画面不做任何一层 NR 处理。")+ wrapMode: Text.WordWrap+ color: veyra.protectionDrawShape.length > 0 ? Theme.accent : Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 11+ }+ RowLayout {+ Layout.fillWidth: true+ spacing: 6VButton {- objectName: "list-protection-remove-" + index- icon: true; ghost: true; iconName: "x"- onClicked: veyra.removeProtectionRegion(modelData.index)+ objectName: "list-protection-draw-rect"+ text: qsTr("画矩形")+ primary: veyra.protectionDrawShape === "rect"+ onClicked: veyra.beginProtectionDraw(veyra.protectionDrawShape === "rect" ? "" : "rect")+ }+ VButton {+ objectName: "list-protection-draw-ellipse"+ text: qsTr("画圆形")+ primary: veyra.protectionDrawShape === "ellipse"+ onClicked: veyra.beginProtectionDraw(veyra.protectionDrawShape === "ellipse" ? "" : "ellipse")+ }+ Item { Layout.fillWidth: true }+ VButton {+ text: qsTr("清空"); ghost: true+ visible: veyra.protectionRegions.length > 0+ onClicked: veyra.clearProtectionRegions()}}- }- VRow {- label: qsTr("羽化像素")- value: Number(veyra.protectionState.feather).toFixed(0) + " px"- VSlider {- objectName: "list-protection-feather"- implicitWidth: 110- from: 0; to: 64- value: veyra.protectionState.feather- onMoved: value => veyra.setProtectionFeather(Math.round(value))+ Repeater {+ model: veyra.protectionRegions+ delegate: VRow {+ required property var modelData+ required property int index+ label: (modelData.ellipse ? qsTr("圆形 ") : qsTr("矩形 ")) + (index + 1)+ value: Math.round(modelData.left * 100) + "," + Math.round(modelData.top * 100) + " → "+ + Math.round(modelData.right * 100) + "," + Math.round(modelData.bottom * 100) + " %"+ VButton {+ objectName: "list-protection-remove-" + index+ icon: true; ghost: true; iconName: "x"+ onClicked: veyra.removeProtectionRegion(modelData.index)+ }+ }+ }+ VRow {+ label: qsTr("羽化像素")+ value: Number(veyra.protectionState.feather).toFixed(0) + " px"+ VSlider {+ objectName: "list-protection-feather"+ implicitWidth: 110+ from: 0; to: 64+ value: veyra.protectionState.feather+ onMoved: value => veyra.setProtectionFeather(Math.round(value))+ }}}}diff --git a/shaders/NrReuseCompose.hlsl b/shaders/NrReuseCompose.hlslnew file mode 100644index 00000000..91dcc4b3--- /dev/null+++ b/shaders/NrReuseCompose.hlsl@@ -0,0 +1,56 @@+// NR inference reuse, motion step (docs/NR_INFERENCE_REUSE_2026-11-07.md).+//+// Veyra's own design: a frame that skips NR inference reuses the change made+// by the last frame that did infer. This pass keeps the motion from the+// current frame back to that inferred frame.+//+// Flow is current->previous in flow-extent pixels (previous = current + flow).+// When the previous frame inferred, the result is just this frame's flow, so+// a stream that never reuses carries exactly the vectors it always had. After+// a reused frame the stored displacement is chained once more:+// D(p) = f(p) + D_prev(p + f(p))+// with D_prev sampled bilinearly. z is a 0..1 validity weight: 0 where the+// chained position leaves the frame or a vector is not finite.+Texture2D<float2> Flow : register(t0);+Texture2D<float4> Previous : register(t1);+RWTexture2D<float4> Displacement : register(u0);+// The same displacement in the flow texture's own format, so NR inputs and+// the temporal stabiliser can read it exactly like the ordinary flow.+RWTexture2D<float2> Motion : register(u1);+cbuffer Settings : register(b0) {+ uint Width; // flow extent+ uint Height;+ uint Chain; // 0: previous frame inferred; 1: chain through Previous+ uint Unused0;+ float4 Unused1;+};+SamplerState PointClamp : register(s0);+SamplerState LinearClamp : register(s1);++[numthreads(16, 16, 1)]+void main(uint3 id : SV_DispatchThreadID) {+ if (id.x >= Width || id.y >= Height) return;+ const float2 f = Flow[id.xy];+ if (!all(isfinite(f))) {+ Displacement[id.xy] = float4(0, 0, 0, 0);+ Motion[id.xy] = float2(0, 0);+ return;+ }+ if (Chain == 0) {+ // Bit-exact passthrough: the vectors an inferring stream always had.+ const float2 at = float2(id.xy) + 0.5 + f;+ const bool inside = all(at >= 0) && all(at <= float2(Width, Height));+ Displacement[id.xy] = float4(f, inside ? 1 : 0, 0);+ Motion[id.xy] = f;+ return;+ }+ const float2 size = float2(Width, Height);+ const float2 at = float2(id.xy) + 0.5 + f;+ float valid = all(at >= 0) && all(at <= size) ? 1 : 0;+ const float4 previous = Previous.SampleLevel(LinearClamp, at / size, 0);+ float2 d = f + previous.xy;+ valid *= saturate(previous.z);+ if (!all(isfinite(d))) { d = f; valid = 0; }+ Displacement[id.xy] = float4(d, valid, 0);+ Motion[id.xy] = d;+}diff --git a/shaders/NrReuseWarp.hlsl b/shaders/NrReuseWarp.hlslnew file mode 100644index 00000000..5e068866--- /dev/null+++ b/shaders/NrReuseWarp.hlsl@@ -0,0 +1,87 @@+// NR inference reuse, picture step (docs/NR_INFERENCE_REUSE_2026-11-07.md).+//+// A frame that skips NR inference shows its own source plus the change the+// last inferred frame made, carried along the displacement to that frame:+// out(x) = S(x) + w(x) * (O_key(q) - S_key(q)), q = x + D(x)+// S is this frame's NR chain input, O_key / S_key the chain output and input+// of the inferred frame. The change, not the old picture, is carried, so the+// frame's own source detail and position are always current.+//+// w falls to 0 where the carried key source does not match this frame's+// source (uncovered background, a wrong vector, a cut) or where q leaves the+// frame. Those pixels show the unenhanced source rather than an enhancement+// placed on the wrong content. The next frame always infers again.+//+// The NR protection regions are applied again at this frame's own pixels, so+// a carried change never reaches into a protected region.+#include "NrProtection.hlsli"+Texture2D<float4> Source : register(t0);+Texture2D<float4> KeyOutput : register(t1);+Texture2D<float4> KeySource : register(t2);+Texture2D<float4> Displacement : register(t3); // flow extent: xy current->key, z validity+RWTexture2D<float4> Output : register(u0);+cbuffer Settings : register(b0) {+ uint Width; // NR chain extent+ uint Height;+ uint FlowWidth; // displacement extent+ uint FlowHeight;+ float Low; // perceptual box-luma mismatch: full weight below Low,+ float High; // none above High+ uint Unused0;+ uint Unused1;+ float ProtectionEnabled;+ float ProtectionFeather;+ float DetailLow; // perceptual detail mismatch: fine change kept below DetailLow,+ float DetailHigh; // only the neighbourhood change above DetailHigh+ float4 Regions[4];+};+SamplerState PointClamp : register(s0);+SamplerState LinearClamp : register(s1);++float Luma(float3 c) { return dot(c, float3(0.2126, 0.7152, 0.0722)); }+// Compare in a display-like encoding so one threshold means the same in+// shadows and highlights; the stored values stay linear.+float Encode(float v) { return pow(max(v, 0), 1.0 / 2.2); }++[numthreads(16, 16, 1)]+void main(uint3 id : SV_DispatchThreadID) {+ if (id.x >= Width || id.y >= Height) return;+ const float4 source = Source[id.xy];+ const float2 size = float2(Width, Height);+ const float2 uv = (float2(id.xy) + 0.5) / size;+ const float4 d = Displacement.SampleLevel(LinearClamp, uv, 0);+ const float2 at = float2(id.xy) + 0.5 + d.xy * size / float2(FlowWidth, FlowHeight);+ float w = saturate(d.z) * (1 - NrProtection(float2(id.xy) + 0.5, uint2(Width, Height), ProtectionEnabled, ProtectionFeather, Regions));+ if (!all(isfinite(at)) || any(at < 0) || any(at > size)) w = 0;+ float3 result = source.rgb;+ if (w > 0) {+ float3 current = 0, keySource = 0, keyOutput = 0;+ const int2 last = int2(Width, Height) - 1;+ [unroll] for (int y = -1; y <= 1; ++y)+ [unroll] for (int x = -1; x <= 1; ++x) {+ const float2 q = (at + float2(x, y)) / size;+ current += Source[clamp(int2(id.xy) + int2(x, y), int2(0, 0), last)].rgb;+ keySource += KeySource.SampleLevel(LinearClamp, q, 0).rgb;+ keyOutput += KeyOutput.SampleLevel(LinearClamp, q, 0).rgb;+ }+ current /= 9; keySource /= 9; keyOutput /= 9;+ // The neighbourhood must match: otherwise the change belongs to other content.+ const float mismatch = abs(Encode(Luma(current)) - Encode(Luma(keySource)));+ w *= 1 - smoothstep(Low, High, mismatch);+ // The change is split. Its neighbourhood mean (tone, colour) is carried+ // wherever the neighbourhood matches. Its fine detail is carried only+ // where this pixel's own detail matches the key's, so detail that does+ // not follow the motion (grain, noise, flicker) is never stamped onto new+ // detail; such pixels keep their own detail with the carried tone.+ const float3 centreSource = KeySource.SampleLevel(LinearClamp, at / size, 0).rgb;+ const float3 centreOutput = KeyOutput.SampleLevel(LinearClamp, at / size, 0).rgb;+ const float detailCurrent = Encode(Luma(source.rgb)) - Encode(Luma(current));+ const float detailKey = Encode(Luma(centreSource)) - Encode(Luma(keySource));+ const float detailWeight = 1 - smoothstep(DetailLow, DetailHigh, abs(detailCurrent - detailKey));+ const float3 coarse = keyOutput - keySource;+ const float3 change = coarse + detailWeight * ((centreOutput - centreSource) - coarse);+ if (all(isfinite(change))) result = source.rgb + w * change;+ }+ // SDR only (the host refuses HDR): same floor as NrResidualComposite.+ Output[id.xy] = float4(max(0, result), source.a);+}diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cppindex ecc0b8c2..7f9f7874 100644--- a/src/engine/EffectChain.cpp+++ b/src/engine/EffectChain.cpp@@ -730,6 +730,9 @@ bool requiresGraphRebuild(const EnhancementSettings& savedPrevious, const Enhancif (previous.lowLatency != next.lowLatency) return true;// The output stabiliser's pass exists only when it is on (EnhanceGraph::createNrHoldPass).if ((previous.nrHoldStrength > 0.0f) != (next.nrHoldStrength > 0.0f)) return true;+ // NR inference reuse allocates its pass only when on (EnhanceGraph::createNrReusePass);+ // Auto and the manual ratios switch live.+ if ((previous.nrReuse != NrReuseMode::Off) != (next.nrReuse != NrReuseMode::Off)) return true;if (previous.nrPolicy != next.nrPolicy) return true;if (previous.srTarget != next.srTarget) return true;// The double SR reduction and the supersample shrink change what SR reads and writes.diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex b764d476..058e7833 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -15,6 +15,7 @@#include "veyra/engine/TimingWindow.h"#include "veyra/engine/FrameFlowWindow.h"#include "veyra/engine/AutoNrController.h"+#include "veyra/engine/AutoNrReuseController.h"#include "veyra/engine/LiveFgAdmission.h"#include "veyra/engine/FgRecoveryBudget.h"#include "veyra/engine/VfgQueueBudget.h"@@ -445,8 +446,8 @@ PlayerSnapshot EngineController::snapshot()const{}#endifauto& flow=copy.metrics.flow;- if(!playing){flow.sourceCompletedFps=flow.outputCompletedFps=flow.validGeneratedFps=flow.presentSubmitFps=flow.xessSdkSubmitFps=0;}- copy.fps=flow.sourceCompletedFps;copy.submissionFps=flow.presentSubmitFps;+ if(!playing){flow.sourceCompletedFps=flow.outputCompletedFps=flow.validGeneratedFps=flow.presentSubmitFps=flow.xessSdkSubmitFps=0;flow.presentLow1Fps.reset();}+ copy.fps=flow.sourceCompletedFps;copy.submissionFps=flow.presentSubmitFps;copy.submissionLow1Fps=flow.presentLow1Fps;return copy;}void EngineController::status(const std::wstring& s,bool failed){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.failed=failed;if(failed)snapshot_.transport=TransportState::Failed;}@@ -793,6 +794,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sGetEnvironmentVariableW(L"VEYRA_TEST_VFG_SYNC_SUBMIT",nullptr,0)==0;desc.vfgFastFallback=desc.vfgAsyncSubmission&&selected.settings.vfgAutoRegulate&&(physicalCapture||isScreen||testReplayAsCard)&&selected.settings.multiplier==2&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_LIVE_PACING",nullptr,0)==0;+ // NR inference reuse belongs to the realtime preview only:+ // export, the image path and the paused frame infer every frame.+ desc.nrReusePreview=!isImage;desc.videoHdr=selected.settings.videoHdr;desc.hdrOutput=selected.settings.useHdrPreview(desc.hdrInput,displayHdrActive());// Auto is optional and preview-only; fixed/export policies@@ -805,6 +809,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s!nrAutoPoolUnavailable&&selected.settings.activeNrLayerCount()<=2&&!isCapture&&!isImage&&desc.enableNr&&!desc.enableSr&&!desc.enableFg&&!desc.hdrWorking()&&!desc.videoHdr.enabled&&!desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.beautyActive()&&!desc.runtimeNodeOrder&&desc.nrHoldStrength==0&&+ desc.nrReuse==NrReuseMode::Off&¤tNrRuntime(desc.nrRuntime)==NrRuntime::Ampere&&desc.opticalFlowBackend==OpticalFlowBackend::Nvidia&&desc.nrMotion==MotionSource::OpticalFlow&&nvidiaAdapter&&ctx.adapter().deviceId==0x2f04&&desc.workWidth==1920&&desc.workHeight==1080&&@@ -1501,6 +1506,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// the lambdas reference below this line.AutoNrController autoNrControl;autoNrControl.reset(host100ns());uint64_t autoNrRevision=options.settings.revision;int64_t autoNrLogAt=0;+ AutoNrReuseController nrReuseControl;nrReuseControl.reset(host100ns());+ uint64_t nrReuseRevision=options.settings.revision;int64_t nrReuseLogAt=0;// A simultaneous seek/speed change may discard the cached frame// after a successful rebuild. Keep its status acknowledgement// until the first successfully processed frame, across loop turns.@@ -1804,6 +1811,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// reaches the picture if the cached source frame is pushed// through the graph again: the grade is fused into the ingest// dispatch, so nothing else would upload the new tables.+ // NR inference reuse is a realtime-preview strategy only: the+ // paused picture must be a fully inferred frame, so a reused+ // last frame is re-rendered once when the pause begins.+ if(!wasPaused&&graph->nrReuseActive()){+ const bool reusedLast=graph->nrReuseLastFrameReused();+ if(reusedLast)refreshPausedFrame_=true;+ veyra::log::info("nr-reuse",std::format("pause began lastFrameReused={}{}",reusedLast,reusedLast?"; re-rendering it with full inference":""));+ }if(refreshPausedFrame_){refreshPausedFrame_=false;if(cachedFrame){@@ -1912,6 +1927,35 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,selapsedMs(started),presentationCancelledJobs.load()));}}+ // NR inference reuse, Auto: a level change is a scheduling choice+ // inside the graph, so nothing drains or rebuilds (AutoNrReuseController).+ if(graph->nrReuseAutomatic()&&frameFlow&&!transaction&&!paused_){+ const auto now=host100ns();+ if(nrReuseRevision!=options.settings.revision||nrReuseControl.level()!=graph->nrReuseLevel()){+ nrReuseControl.reset(now,graph->nrReuseLevel());nrReuseRevision=options.settings.revision;+ }+ if(reset)nrReuseControl.discardObservations(now);+ const auto flow=frameFlow->snapshot(now);+ std::optional<double> nrMs;+ for(auto stage:{diagnostics::GpuStage::NrLayer0,diagnostics::GpuStage::NrLayer1,diagnostics::GpuStage::NrLayer2,diagnostics::GpuStage::NrLayer3}){+ const auto& a=flow.gpuTiming[size_t(stage)];+ // Reused frames add zero-length samples, so the mean is per+ // source frame; the P95 is the cost of one inference.+ if(a.samples&&a.p95&&std::isfinite(*a.p95))nrMs=nrMs.value_or(0)+*a.p95;+ }+ const double transportFps=activeSource->info().averageFps*playbackRate;+ const double budget=std::isfinite(transportFps)&&transportFps>0?800.0/transportFps:0;+ const auto& timing=flow.enhancementProcessing;+ if(const auto next=nrReuseControl.observe(now,timing.mean,timing.samples,nrMs,budget)){+ graph->setNrReuseLevel(*next);+ veyra::log::info("nr-reuse",std::format("auto level={} framesPerReuse={} meanMs={:.3f} nrMs={:.3f} budgetMs={:.3f} samples={}",+ *next,pipeline::NrReuseScheduler::framesPerReuse(*next),timing.mean.value_or(0),nrMs.value_or(0),budget,timing.samples));+ }else if(now>=nrReuseLogAt){+ veyra::log::info("nr-reuse",std::format("auto observe level={} meanMs={:.3f} nrMs={:.3f} budgetMs={:.3f} samples={} reused={}",+ graph->nrReuseLevel(),timing.mean.value_or(0),nrMs.value_or(0),budget,timing.samples,graph->metrics().nrReuseFrames));+ nrReuseLogAt=now+100000000;+ }+ }// Wait before selecting the latest sample, not after enhancement.if(!presenter.beginSourceInput()){status(L"XeSS input timing failed",true);break;}const auto decodeStart=Clock::now();@@ -2919,6 +2963,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,ssnapshot_.nrAutoPercent=graph->autoNrPoolReady()?AutoNrController::percent(graph->autoNrLevel()):0;const auto autoExtent=graph->autoNrExtent();snapshot_.nrAutoWidth=autoExtent.width;snapshot_.nrAutoHeight=autoExtent.height;snapshot_.nrAutoStatus=nrAutoStatus;+ snapshot_.nrReuseActive=graph->nrReuseActive();snapshot_.nrReuseAutomatic=graph->nrReuseAutomatic();+ snapshot_.nrReuseLevel=graph->nrReuseActive()?graph->nrReuseLevel():0;+ snapshot_.nrReuseFrames=graphStats.nrReuseFrames;snapshot_.nrReuseUnavailable=graph->nrReuseUnavailable();snapshot_.audioRebuffering=audioRebuffering;snapshot_.audioVideoWaits=audioPipe.videoWaitCount();snapshot_.srActive=gd.enableSr&&graphStats.srEvaluateCount>0;diff --git a/src/engine/PreviewGpuSession.cpp b/src/engine/PreviewGpuSession.cppindex 7529ba9a..64dcc724 100644--- a/src/engine/PreviewGpuSession.cpp+++ b/src/engine/PreviewGpuSession.cpp@@ -26,6 +26,9 @@ bool PreviewGpuSession::requestAllowed(const EnhancementSettings& settings){currentNrRuntime(settings.nrRuntime)==NrRuntime::Ampere&&settings.activeNrLayerCount()<=1&&!settings.activeAutoNrLayerCount()&&!settings.videoHdr.enabled&&!settings.color.enabled&&settings.additionalColorCount==0&&!settings.antiAlias.enabled&&settings.additionalAntiAliasCount==0&&!settings.beautyEnabled()&&+ // A prewarmed graph is built without the preview-only reuse pass, so it+ // must never be adopted for a session that asked for reuse.+ settings.nrReuse==NrReuseMode::Off&&(settings.videoSrQuality==0||settings.videoSrQuality==4);}bool PreviewGpuSession::computeAllowed(const gfx::AdapterInfo& adapter,const pipeline::EnhanceGraphDesc& desc){@@ -38,7 +41,7 @@ bool PreviewGpuSession::computeAllowed(const gfx::AdapterInfo& adapter,const pipdesc.nrRuntime==NrRuntime::Original&&desc.nrLayersExtent.size()==2&&desc.nrLayersExtent[0]==pipeline::Extent{1920,1080}&&desc.nrLayersExtent[1]==pipeline::Extent{1920,1080}&&!desc.nrBeforeSr&&!desc.runtimeNodeOrder&&!desc.hdrInput&&!desc.hdrOutput&&!desc.videoHdr.enabled&&- !desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.beautyActive()&&!desc.nrHoldStrength&&+ !desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.beautyActive()&&!desc.nrHoldStrength&&desc.nrReuse==NrReuseMode::Off&&!desc.nrTemporal&&std::none_of(desc.nrLayersTemporal.begin(),desc.nrLayersTemporal.end(),[](bool enabled){return enabled;})&&desc.opticalFlowBackend==OpticalFlowBackend::Nvidia&&desc.enableFg&&desc.frameGenerationBackend==FrameGenerationBackend::Dlss&&(desc.fgMultiplier==2||desc.fgMultiplier==3);diff --git a/src/pipeline/ColorGradeTables.cpp b/src/pipeline/ColorGradeTables.cppindex 1bad7150..f4ce0ad7 100644--- a/src/pipeline/ColorGradeTables.cpp+++ b/src/pipeline/ColorGradeTables.cpp@@ -8,12 +8,16 @@ constexpr double kD65x=0.3127,kD65y=0.3290;using Mat3=std::array<double,9>;// Planckian locus, Kim et al. cubic approximation (valid 1667..25000 K):-// x is a cubic in 1/T, y is a cubic in x.+// x is a cubic in 1/T, y is a cubic in x, with three y pieces.+// The 2222..4000 K piece once ended in -0.0316772744 instead of -0.16748867:+// below 4000 K the white point jumped towards yellow-green, and adapting it to+// D65 multiplied blue by about 23 at -100 (field report 2026-11-07).void planckianXy(double kelvin,double& x,double& y){const double t=std::clamp(kelvin,1667.0,25000.0);if(t<=4000.0){x=-0.2661239e9/(t*t*t)-0.2343589e6/(t*t)+0.8776956e3/t+0.179910;- y=-0.9549476*x*x*x-1.37418593*x*x+2.09137015*x-0.0316772744;+ y=t<=2222.0?-1.1063814*x*x*x-1.34811020*x*x+2.18555832*x-0.20219683+ :-0.9549476*x*x*x-1.37418593*x*x+2.09137015*x-0.16748867;}else{x=-3.0258469e9/(t*t*t)+2.1070379e6/(t*t)+0.2226347e3/t+0.240390;y=3.0817580*x*x*x-5.87338670*x*x+3.75112997*x-0.37001483;@@ -175,8 +179,14 @@ ColorGradeTables ColorGradeTables::bake(const engine::ColorSettings& s){double wx=kD65x,wy=kD65y;if(s.temperature!=0||s.tint!=0){// Temperature is relative: +100 assumes a much cooler illuminant, which- // makes the image warmer (Lightroom's slider direction).- planckianXy(6500.0*std::exp2(double(s.temperature)/100.0),wx,wy);+ // makes the image warmer (Lightroom's slider direction). The warm side+ // keeps its curve, 6500 K x 2^(t/100), +100 = 13000 K. The cool side+ // mirrors it in mireds, so -100 moves the white point exactly as far as+ // +100 does (4333 K). 6500 x 2^(t/100) put -100 at 3250 K, twice as far,+ // and the cool end overwhelmed the picture.+ const double t=double(s.temperature)/100.0,neutralMired=1e6/6500.0;+ const double mired=t>=0.0?neutralMired/std::exp2(t):neutralMired*(2.0-std::exp2(t));+ planckianXy(1e6/mired,wx,wy);wy=std::clamp(wy+double(s.tint)*0.00025,0.05,0.95);}// Adaption direction: the slider states which illuminant the image was shotdiff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 27f0e0f1..833101ea 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -677,7 +677,12 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)const bool vfxFirst=srEnabled_&&vfxFirstSrPass(desc_);const uint64_t vfxSrBytes=(vfxFinal?uint64_t(srInW_)*srInH_*4u+uint64_t(srOutW_)*srOutH_*4u:0)+(vfxFirst?uint64_t(srcW_)*srcH_*4u+uint64_t(desc_.firstSrWidth)*desc_.firstSrHeight*4u:0);- const uint64_t estimate=vfxSrBytes+dualBytes+supersampleBytes+uint64_t(workW_)*workH_*(76u+4u*generatedTextures)+vfgSharedBytes+ // NR inference reuse keeps one inferred chain output and input plus motion+ // at the flow extent (createNrReusePass); only a preview graph asks for it.+ const bool reuseRequested=desc_.nrReusePreview&&desc_.enableNr&&desc_.nrReuse!=engine::NrReuseMode::Off;+ const uint64_t reuseBytes=reuseRequested?uint64_t(desc_.finalNrAfterSr()?workW_:srcW_)*(desc_.finalNrAfterSr()?workH_:srcH_)*16u++ uint64_t(nvofW_)*nvofH_*20u:0;+ const uint64_t estimate=reuseBytes+vfxSrBytes+dualBytes+supersampleBytes+uint64_t(workW_)*workH_*(76u+4u*generatedTextures)+vfgSharedBytes+nrTextureBytes+fullLayerBytes+uint64_t(srcW_)*srcH_*(32u+(desc_.protectionBeforeSr()?8u:0u))+temporalBytes+tailColorBytes+interProtectionBytes+(flowRefine_?uint64_t(nvofW_)*nvofH_*(flowConsistency_?13u:flowClaims_?18u:12u)+uint64_t(workW_)*workH_*4u:0);@@ -1799,6 +1804,65 @@ bool EnhanceGraph::createNrHoldPass()return true;}+// The first version carries one finished chain output on the source side of+// SR. Anything that would make that output depend on more than this frame's+// chain input is refused with a reason instead of guessed at.+std::string EnhanceGraph::nrReuseIneligibility() const+{+ if(!desc_.nrReusePreview)return "not a realtime preview graph";+ if(desc_.stillImage)return "still image";+ if(!nrEnabled_||!nrCreated())return "NR not created";+ if(lmxxfNr_||!context_.adapter().isNvidia)return "NVIDIA NGX NR only";+ for(const auto& layer:nrInstances_)if(layer->amd||layer->handle()==nullptr)return "NVIDIA NGX NR only";+ if(desc_.hdrWorking())return "SDR only";+ if(!desc_.nrUsesFlow()||!nvofStandalone_)return "NR motion must use optical flow";+ if(desc_.splitNrAcrossSr())return "NR split across SR";+ if(preSrProtectionRgba_||interNrProtectionRgba_)return "protection between NR stages";+ if(desc_.runtimeNodeOrder)return "node mode";+ if(desc_.nrAutoPoolLayer)return "automatic NR size pool";+ if(!residualRgba_||!flowTex_||!nrFlow_)return "missing graph textures";+ return {};+}++bool EnhanceGraph::createNrReusePass()+{+ nrReusePass_.reset();nrReuseScheduler_.reset();nrReuseKeyValid_=false;nrReuseUnavailable_.clear();+ if(desc_.nrReuse==engine::NrReuseMode::Off||!desc_.nrReusePreview)return true;+ if(auto reason=nrReuseIneligibility();!reason.empty()){+ nrReuseUnavailable_=reason;+ veyra::log::info("nr-reuse",std::format("requested mode={} inactive reason=\"{}\"",int(desc_.nrReuse),reason));+ return true; // the preview keeps inferring every frame+ }+ std::vector<NrReusePass::MotionTarget> targets{{nrFlow_.Get(),nrW_,nrH_}};+ for(const auto& layer:nrInstances_)+ if(layer->motion()!=nrFlow_.Get())targets.push_back({layer->motion(),layer->width(),layer->height()});+ auto* source=nrBaseInput();+ const auto extent=residualRgba_->GetDesc();+ auto pass=std::make_unique<NrReusePass>();+ if(!pass->initialize(context_.device(),uint32_t(extent.Width),extent.Height,nvofW_,nvofH_,+ source,residualRgba_.Get(),flowTex_.Get(),targets)){+ nrReuseUnavailable_="reuse resources unavailable";+ veyra::log::warn("nr-reuse","resources unavailable; the preview keeps inferring every frame");+ return true; // never fail the graph for an optional speed-up+ }+ nrReusePass_=std::move(pass);+ nrReuseScheduler_.setLevel(NrReuseScheduler::levelFor(desc_.nrReuse));+ veyra::log::info("nr-reuse",std::format("active mode={} level={} framesPerReuse={} chain={}x{} flow={}x{} layers={} motionTargets={} bytes={}MiB",+ int(desc_.nrReuse),nrReuseScheduler_.level(),NrReuseScheduler::framesPerReuse(nrReuseScheduler_.level()),+ uint32_t(extent.Width),extent.Height,nvofW_,nvofH_,nrInstances_.size(),targets.size(),nrReusePass_->bytes()>>20));+ return true;+}++void EnhanceGraph::setNrReuseLevel(unsigned level)+{+ if(!nrReuseAutomatic())return;+ const unsigned previous=nrReuseScheduler_.level();+ nrReuseScheduler_.setLevel(level);+ if(nrReuseScheduler_.level()!=previous)+ veyra::log::info("nr-reuse",std::format("automatic level={} framesPerReuse={} previous={}",+ nrReuseScheduler_.level(),NrReuseScheduler::framesPerReuse(nrReuseScheduler_.level()),previous));+}+bool EnhanceGraph::createComputePasses(){std::vector<uint8_t> cs;@@ -1834,6 +1898,9 @@ bool EnhanceGraph::createComputePasses()// previous graph, which otherwise kept copying its last frame over the// live output (picture frozen after turning it off, 2026-10-02).if(!createNrHoldPass())return false;+ // NR inference reuse: like the stabiliser, always called so a rebuild+ // without it releases the previous graph's pass.+ if(!createNrReusePass())return false;// Keep the legacy ingress root signature when no independent colour grade// needs the FP32 side output. The extra UAV is part of the R5.3 contract// only for graphs that actually allocate preGradeRgba_.@@ -1977,7 +2044,10 @@ bool EnhanceGraph::createViews()// descriptor first bound a null resource, so the composite went// nowhere and the final texture was never touched.if (layer->stabilised &&- !layer->temporal().initialize(context_.device(), base, flowTex_.Get(), target,+ // With inference reuse the stabiliser reads the reuse pass's motion: the+ // ordinary flow after an inferred frame, the chained motion after a+ // reused one, so its history is always reprojected from where it was made.+ !layer->temporal().initialize(context_.device(), base, nrReusePass_?nrReusePass_->motion():flowTex_.Get(), target,layerIndex < desc_.nrLayersAntiFlicker.size()? desc_.nrLayersAntiFlicker[layerIndex] : desc_.nrAntiFlicker)) return false;makeUav(context_.device(),@@ -2892,6 +2962,24 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(layer->motion()!=nrFlow_.Get())adapt(layer->motion(),layer->width(),layer->height(),3+UINT(i));}}+ // NR inference reuse (NrReuse.h), decided after this frame's flow and before+ // any NR layer records work: a reused frame skips the whole NR chain. Only a+ // preview graph that asked for it has the pass; every other graph is unchanged.+ bool nrReuseFrame=false,nrAfterReuse=false;+ if(nrReusePass_&&nrEnabled_&&nrCreated()){+ if(reset){nrReuseScheduler_.reset();nrReuseKeyValid_=false;}+ nrAfterReuse=nrReuseScheduler_.lastReused();+ if(haveFlow){+ nrReusePass_->compose(list,tracker_,nrAfterReuse);+ nrReuseFrame=nrReuseScheduler_.next(nrReuseKeyValid_&&!reset&&!pausedResidualRefresh&&!reusePausedNr);+ // The inferred frame after a reused one: NR's own history is the+ // frame before the reused one, so its motion input is the chained+ // motion back to that frame, not this frame's one-step flow.+ if(!nrReuseFrame&&nrAfterReuse&&desc_.nrUsesFlow()){+ nrReusePass_->writeMotionTargets(list,tracker_);++metrics_.nrReuseChainedMotion;+ }+ }else nrReuseScheduler_.next(false);+ }if(reset){++metrics_.resetCount;++epoch_;}out.historyReset=reset;out.batch.batchId=realFrameIndex_+1;out.batch.identity={epoch_,desc_.settingsRevision,sourceFrameId};@@ -3009,7 +3097,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framelist->Dispatch((layer->fullWidth()+15)/16,(layer->fullHeight()+15)/16,1);tracker_.uavBarrier(list,destination);tracker_.transition(list,destination,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);- if(temporallyStabilised)layer->temporal().run(list,tracker_,reset,haveFlow,ptsMs-prevPtsMs_,r.total,protection,r.correction,desc_.hdrWorking());+ // After a reused frame the stabiliser's history is two source frames old.+ const double sinceHistoryMs=nrAfterReuse?ptsMs-nrReuseInferredPts_:ptsMs-prevPtsMs_;+ if(temporallyStabilised)layer->temporal().run(list,tracker_,reset,haveFlow,sinceHistoryMs,r.total,protection,r.correction,desc_.hdrWorking());};// 4. NR layers, in order. Each layer encodes its input to the 8-bit parity@@ -3027,7 +3117,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame++metrics_.pausedNrResidualReuses;log::info("paused-nr-cache",std::format("event=reuse source={} revision={} count={}",sourceFrameId,desc_.settingsRevision,metrics_.pausedNrResidualReuses));}- if (nrEnabled_ && nrCreated()&&!reusePausedNr) {+ if (nrEnabled_ && nrCreated()&&!reusePausedNr&&!nrReuseFrame) {for (size_t layerIndex = 0; layerIndex < nrInstances_.size(); ++layerIndex) {const bool preSrProtection=preSrProtectionRgba_&&layerIndex==desc_.nrBeforeSrLayerCount();const bool interNrProtection=interNrProtectionRgba_&&layerIndex==desc_.interNrProtectionTarget();@@ -3233,8 +3323,21 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// their consumers above. Keep the single-layer command order unchanged.if(nrEnabled_&&nrCreated()){gpuTimer_.mark(list,GpuStage::Residual);- if(!nrInstances_.empty())compositeNrLayer(nrInstances_.size()-1);- if(nrInstances_.size()>1){+ // A reused frame writes the chain output itself: its own source plus+ // the previous frame's NR change carried along the flow.+ if(nrReuseFrame){+ // A zero-length NR sample per layer: the stage means then show the+ // NR time per source frame (what reuse saves), while the P95 keeps+ // the cost of one inference.+ for(size_t i=0;i<nrInstances_.size();++i){+ gpuTimer_.mark(list,diagnostics::nrLayerStage(unsigned(i)));+ gpuTimer_.mark(list,diagnostics::nrLayerStage(unsigned(i)),true);+ }+ gpuTimer_.mark(list,GpuStage::Nr);gpuTimer_.mark(list,GpuStage::Nr,true);+ nrReusePass_->reuse(list,tracker_,desc_.protection);++metrics_.nrReuseFrames;+ }+ if(!nrReuseFrame&&!nrInstances_.empty())compositeNrLayer(nrInstances_.size()-1);+ if(!nrReuseFrame&&nrInstances_.size()>1){auto* final=nrInstances_.back()->fullTarget();if(desc_.protection.enabled&&!preSrProtectionRgba_&&!interNrProtectionRgba_){auto* original=nrBaseInput();@@ -3259,6 +3362,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}+ // Keep an inferred frame's chain output and input, before the+ // stabiliser changes the output, while a following frame may reuse it.+ if(nrReusePass_){+ const bool keep=!nrReuseFrame&&nrReuseScheduler_.reuseMayFollow();+ if(keep)nrReusePass_->store(list,tracker_);+ nrReuseKeyValid_=keep;+ if(!nrReuseFrame)nrReuseInferredPts_=ptsMs;+ }// The stabiliser below closes this span: a second Residual pair would// overwrite the composite's timestamps and drop its time from the load.if(!nrHoldPass_)gpuTimer_.mark(list,GpuStage::Residual,true);@@ -3638,6 +3749,9 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){// tolerance are uniforms. Neither used to reach a running graph (field report// 2026-10-01: switching it on mid-play did nothing until something else rebuilt).if((s.nrHoldStrength>0.0f)!=(desc_.nrHoldStrength>0.0f))return false;+ // NR inference reuse: a preview graph allocates its pass only when built+ // with reuse on, so on/off rebuilds; Auto and the manual ratios are live.+ if(desc_.nrReusePreview&&s.nr&&(s.nrReuse!=engine::NrReuseMode::Off)!=(desc_.nrReuse!=engine::NrReuseMode::Off))return false;// Switching the referenced .cube re-stages a descriptor, which needs the// queue drained: treat it as a rebuild (parameters stay live).if(s.color.enabled&&(s.color.lutNameString()!=desc_.color.lutNameString()||s.color.lutInputSpace!=desc_.color.lutInputSpace))return false;@@ -3681,6 +3795,18 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){if(faceTracker_)faceTracker_->configure(desc_.beautyDetection,beautyMinConfidence());desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;desc_.nrHoldStrength=s.nrHoldStrength;desc_.nrHoldTolerance=s.nrHoldTolerance;+ if(desc_.nrReusePreview&&s.nr){+ const auto previousReuse=desc_.nrReuse;desc_.nrReuse=s.nrReuse;+ if(nrReusePass_&&desc_.nrReuse!=previousReuse){+ // A manual ratio pins the level; Auto starts from inferring every+ // frame and lets the engine's controller raise it.+ nrReuseScheduler_.setLevel(NrReuseScheduler::levelFor(desc_.nrReuse));+ veyra::log::info("nr-reuse",std::format("live mode={} level={}",int(desc_.nrReuse),nrReuseScheduler_.level()));+ }+ }+ // Every live change resets NR's own history below, so the next frame+ // infers instead of carrying a change made with the old parameters.+ nrReuseScheduler_.reset();nrReuseKeyValid_=false;desc_.nrLayersModel=std::move(nextNr.nrLayersModel);desc_.nrLayersResidual=std::move(nextNr.nrLayersResidual);desc_.nrLayersTemporal=std::move(nextNr.nrLayersTemporal);@@ -3945,6 +4071,7 @@ void EnhanceGraph::shutdown()preGradeRgba_.Reset();srcRgba_.Reset();videoSrInput_.Reset();videoSrOutput_.Reset();srPrescaled_.Reset();firstSrInput_.Reset();firstSrOutput_.Reset();firstSrLinear_.Reset();nrHoldPass_.reset();+ nrReusePass_.reset();colorDetail_.close();chromaTex_.Reset();lumaTex_.Reset();diff --git a/src/pipeline/NrReusePass.cpp b/src/pipeline/NrReusePass.cppnew file mode 100644index 00000000..1c6ec157--- /dev/null+++ b/src/pipeline/NrReusePass.cpp@@ -0,0 +1,166 @@+#include "veyra/pipeline/NrReusePass.h"+#include <algorithm>+#include <bit>+#include <format>++namespace veyra::pipeline {+namespace {+// A texture CopyResource can fill from `like`: same extent, format and flags.+ComPtr<ID3D12Resource> makeLike(ID3D12Device* device, ID3D12Resource* like)+{+ D3D12_HEAP_PROPERTIES hp{};+ hp.Type = D3D12_HEAP_TYPE_DEFAULT;+ auto desc = like->GetDesc();+ desc.Flags &= ~(D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER);+ ComPtr<ID3D12Resource> r;+ const HRESULT hr = device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc,+ D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&r));+ if (FAILED(hr)) {+ veyra::log::error("nr-reuse", std::format("key texture alloc failed {}x{} format={} hr=0x{:X}",+ uint64_t(desc.Width), desc.Height, int(desc.Format), unsigned(hr)));+ return nullptr;+ }+ return r;+}+uint64_t textureBytes(ID3D12Device* device, ID3D12Resource* r)+{+ const auto desc = r->GetDesc();+ return device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes;+}+float bits(uint32_t v) { return std::bit_cast<float>(v); }+}++bool NrReusePass::initialize(ID3D12Device* device, uint32_t width, uint32_t height,+ uint32_t flowWidth, uint32_t flowHeight,+ ID3D12Resource* source, ID3D12Resource* output, ID3D12Resource* flow,+ const std::vector<MotionTarget>& targets)+{+ close();+ if (!device || !source || !output || !flow || !width || !height || !flowWidth || !flowHeight) return false;+ const auto sourceDesc = source->GetDesc(), outputDesc = output->GetDesc();+ if (sourceDesc.Width != width || sourceDesc.Height != height ||+ outputDesc.Width != width || outputDesc.Height != height) {+ veyra::log::warn("nr-reuse", std::format("chain extents differ source={}x{} output={}x{} expected={}x{}",+ uint64_t(sourceDesc.Width), sourceDesc.Height, uint64_t(outputDesc.Width), outputDesc.Height, width, height));+ return false;+ }+ source_ = source; output_ = output; flow_ = flow;+ width_ = width; height_ = height; flowWidth_ = flowWidth; flowHeight_ = flowHeight;+ targets_ = targets;+ keyOutput_ = makeLike(device, output);+ keySource_ = makeLike(device, source);+ for (auto& d : displacement_) d = makeTexture(device, flowWidth, flowHeight, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ motion_ = makeTexture(device, flowWidth, flowHeight, DXGI_FORMAT_R16G16_FLOAT, true);+ if (!keyOutput_ || !keySource_ || !displacement_[0] || !displacement_[1] || !motion_) { close(); return false; }+ for (auto* r : {keyOutput_.Get(), keySource_.Get(), displacement_[0].Get(), displacement_[1].Get(), motion_.Get()})+ bytes_ += textureBytes(device, r);++ std::vector<uint8_t> shader;+ if (!compose_.loadShader("NrReuseCompose.dxil", shader) ||+ !compose_.create(device, shader, 8, 2, 2, 8, 0, true)) { close(); return false; }+ if (!warp_.loadShader("NrReuseWarp.dxil", shader) ||+ !warp_.create(device, shader, 16, 4, 1, kWarpConstants, 0, true)) { close(); return false; }+ const UINT adaptSlots = UINT(std::max<size_t>(1, targets_.size()) * 2);+ if (!adapt_.loadShader("FlowAdapt.dxil", shader) ||+ !adapt_.create(device, shader, adaptSlots, 1, 1)) { close(); return false; }++ DescriptorStager staging;+ if (!staging.initialize(device, 32)) { close(); return false; }+ // Ping-pong sets, staged once. Set i writes displacement_[i] and reads the+ // other one, so the slot mapping never changes between frames.+ for (unsigned i = 0; i < 2; ++i) {+ staging.stageSrv(flow, nullptr, compose_.heap.Get(), i * 4 + 0);+ staging.stageSrv(displacement_[1 - i].Get(), nullptr, compose_.heap.Get(), i * 4 + 1);+ makeUav(device, displacement_[i].Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpuHandleOf(compose_, i * 4 + 2));+ makeUav(device, motion_.Get(), DXGI_FORMAT_R16G16_FLOAT, cpuHandleOf(compose_, i * 4 + 3));+ // Warp set i reads the displacement compose set i wrote.+ ID3D12Resource* sources[] = {source, keyOutput_.Get(), keySource_.Get(), displacement_[i].Get()};+ for (unsigned j = 0; j < 4; ++j) staging.stageSrv(sources[j], nullptr, warp_.heap.Get(), i * 8 + j);+ makeUav(device, output, outputDesc.Format, cpuHandleOf(warp_, i * 8 + 4));+ }+ for (size_t t = 0; t < targets_.size(); ++t) {+ staging.stageSrv(motion_.Get(), nullptr, adapt_.heap.Get(), UINT(t * 2));+ makeUav(device, targets_[t].texture, DXGI_FORMAT_R16G16_FLOAT, cpuHandleOf(adapt_, UINT(t * 2 + 1)));+ }+ return true;+}++void NrReusePass::compose(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool chain)+{+ if (!compose_.pso) return;+ const unsigned i = latest_ ^ 1u;+ const float c[8] = {bits(flowWidth_), bits(flowHeight_), bits(chain ? 1u : 0u), 0, 0, 0, 0, 0};+ tracker.transition(list, flow_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, displacement_[latest_].Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, displacement_[i].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ tracker.transition(list, motion_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ compose_.bind(list, c, gpuHandleOf(compose_, i * 4).ptr, gpuHandleOf(compose_, i * 4 + 2).ptr);+ list->Dispatch((flowWidth_ + 15) / 16, (flowHeight_ + 15) / 16, 1);+ tracker.uavBarrier(list, displacement_[i].Get());+ tracker.uavBarrier(list, motion_.Get());+ tracker.transition(list, displacement_[i].Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, motion_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ latest_ = i;+}++void NrReusePass::writeMotionTargets(ID3D12GraphicsCommandList* list, StateTracker& tracker)+{+ if (!adapt_.pso) return;+ tracker.transition(list, motion_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ for (size_t t = 0; t < targets_.size(); ++t) {+ const auto& target = targets_[t];+ tracker.transition(list, target.texture, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ const float c[8] = {bits(flowWidth_), bits(flowHeight_), bits(target.width), bits(target.height), 0, 0, 0, 0};+ adapt_.bind(list, c, gpuHandleOf(adapt_, UINT(t * 2)).ptr, gpuHandleOf(adapt_, UINT(t * 2 + 1)).ptr);+ list->Dispatch((target.width + 15) / 16, (target.height + 15) / 16, 1);+ tracker.uavBarrier(list, target.texture);+ tracker.transition(list, target.texture, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ }+}++void NrReusePass::store(ID3D12GraphicsCommandList* list, StateTracker& tracker)+{+ if (!keyOutput_) return;+ auto copy = [&](ID3D12Resource* from, ID3D12Resource* to) {+ tracker.transition(list, from, D3D12_RESOURCE_STATE_COPY_SOURCE);+ tracker.transition(list, to, D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyResource(to, from);+ tracker.transition(list, to, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, from, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ };+ copy(output_, keyOutput_.Get());+ copy(source_, keySource_.Get());+}++void NrReusePass::reuse(ID3D12GraphicsCommandList* list, StateTracker& tracker, const engine::ProtectionSettings& protection)+{+ if (!warp_.pso) return;+ const unsigned i = latest_;+ float c[kWarpConstants] = {bits(width_), bits(height_), bits(flowWidth_), bits(flowHeight_), kLow, kHigh, 0, 0,+ protection.enabled ? 1.f : 0.f, protection.featherPixels, kDetailLow, kDetailHigh};+ for (size_t r = 0; r < 4; ++r) {+ const auto q = engine::protectionConstants(protection.regions[r]);+ for (size_t k = 0; k < 4; ++k) c[12 + r * 4 + k] = q[k];+ }+ for (auto* r : {source_, keyOutput_.Get(), keySource_.Get(), displacement_[i].Get()})+ tracker.transition(list, r, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ tracker.transition(list, output_, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ warp_.bind(list, c, gpuHandleOf(warp_, i * 8).ptr, gpuHandleOf(warp_, i * 8 + 4).ptr);+ list->Dispatch((width_ + 15) / 16, (height_ + 15) / 16, 1);+ tracker.uavBarrier(list, output_);+ tracker.transition(list, output_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+}++void NrReusePass::close()+{+ compose_ = {}; warp_ = {}; adapt_ = {};+ for (auto& d : displacement_) d.Reset();+ motion_.Reset(); keyOutput_.Reset(); keySource_.Reset();+ targets_.clear();+ source_ = output_ = flow_ = nullptr;+ width_ = height_ = flowWidth_ = flowHeight_ = 0;+ latest_ = 0;+ bytes_ = 0;+}++} // namespace veyra::pipelinediff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 5a811d21..f462325b 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -279,6 +279,11 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst};restoreHold("nrHoldStrength", s.nrHoldStrength);restoreHold("nrHoldTolerance", s.nrHoldTolerance);+ if (p.contains(QStringLiteral("nrReuse"))) {+ const int value = p.value(QStringLiteral("nrReuse")).toInt();+ const auto mode = static_cast<engine::NrReuseMode>(value);+ if (value >= 0 && engine::validNrReuseMode(mode) && s.nrReuse != mode) { s.nrReuse = mode; changed = true; }+ }for(const auto& pair : {std::pair{"captureFlipVertical",&s.captureFlipVertical},std::pair{"captureForceSdr",&s.forceSdrPreview}})if(p.contains(QLatin1String(pair.first))){const bool value=p.value(QLatin1String(pair.first)).toBool();changed|=*pair.second!=value;*pair.second=value;}if(p.contains("captureAudioIngress")){const int value=p.value("captureAudioIngress").toInt();if(value>=0&&value<=2){changed|=int(s.captureAudio)!=value;s.captureAudio=static_cast<engine::CaptureAudioIngress>(value);}}diff --git a/src/ui/bridge/Enhancement.cpp b/src/ui/bridge/Enhancement.cppindex bfdf7e08..f4a10db2 100644--- a/src/ui/bridge/Enhancement.cpp+++ b/src/ui/bridge/Enhancement.cpp@@ -1227,6 +1227,20 @@ void QmlPlayerBridge::setNrHoldStrength(double value) {if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "output stabiliser strength not saved");emit settingsChanged();}+// NR inference reuse (pipeline/NrReuse.h), realtime preview only. 0 off,+// 1 Auto, 2/3/4 reuse one frame in every 2/3/4. Global like the stabiliser.+int QmlPlayerBridge::nrReuseMode() const { return int(settings().nrReuse); }+void QmlPlayerBridge::setNrReuseMode(int value) {+ const auto mode = static_cast<engine::NrReuseMode>(value);+ if (value < 0 || !engine::validNrReuseMode(mode)) return;+ auto s = settings();+ if (s.nrReuse == mode) return;+ s.nrReuse = mode;+ if (!impl_->commit(std::move(s))) return;+ impl_->prefs[QStringLiteral("nrReuse")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "NR inference reuse mode not saved");+ emit settingsChanged();+}double QmlPlayerBridge::nrHoldTolerance() const { return double(settings().nrHoldTolerance); }void QmlPlayerBridge::setNrHoldTolerance(double value) {auto s = settings();diff --git a/src/ui/bridge/Playback.cpp b/src/ui/bridge/Playback.cppindex 4c9bef72..111e5c7a 100644--- a/src/ui/bridge/Playback.cpp+++ b/src/ui/bridge/Playback.cpp@@ -1,5 +1,6 @@// QML bridge: Playback responsibilities.#include "../QmlPlayerBridge_p.h"+#include "veyra/pipeline/NrReuse.h"namespace veyra::ui {// --- playback ---------------------------------------------------------------@@ -69,6 +70,10 @@ double QmlPlayerBridge::submitFps() const {return xessPresenting(s) ? s.metrics.flow.xessSdkSubmitFps : s.submissionFps.value_or(0.0);}bool QmlPlayerBridge::submitFpsKnown() const { return xessPresenting(impl_->snapshot) || impl_->snapshot.submissionFps.has_value(); }+// Our own presents only: while the XeSS SDK presents its frames itself the+// intervals between them are not observed here, so there is no 1% low.+double QmlPlayerBridge::submitLowFps() const { return submitLowFpsKnown() ? *impl_->snapshot.submissionLow1Fps : 0.0; }+bool QmlPlayerBridge::submitLowFpsKnown() const { return !xessPresenting(impl_->snapshot) && impl_->snapshot.submissionLow1Fps.has_value(); }QString QmlPlayerBridge::submitFpsLabel() const { return xessPresenting(impl_->snapshot) ? tr("SDK 提交") : tr("提交"); }double QmlPlayerBridge::lateMs() const { return impl_->snapshot.lateMs; }double QmlPlayerBridge::lateP95Ms() const { return impl_->snapshot.lateP95Ms; }@@ -90,6 +95,34 @@ QString QmlPlayerBridge::nrAutoStatus() const {if(!s.nrAutoStatus.empty())return tr("当前配置未启用自动 NR,保留固定 1080p 档");return {};}+// NR inference reuse: what the running preview graph actually does. Nothing+// while the mode is off or nothing plays; a reason when the mode is on but+// this chain cannot reuse (EnhanceGraph::nrReuseIneligibility, ASCII).+bool QmlPlayerBridge::nrReuseActive() const { return impl_->snapshot.nrReuseActive; }+QString QmlPlayerBridge::nrReuseStatus() const {+ const auto& s=impl_->snapshot;+ if(settings().nrReuse==engine::NrReuseMode::Off)return {};+ if(s.nrReuseActive){+ const unsigned every=pipeline::NrReuseScheduler::framesPerReuse(s.nrReuseLevel);+ const QString state=every==0?tr("跟得上,每帧都推理"):tr("每 %1 帧复用 1 帧").arg(every);+ // No running count: hours of play reach millions of frames.+ return s.nrReuseAutomatic?tr("自动 · ")+state:state;+ }+ const auto& why=s.nrReuseUnavailable;+ if(why.empty())return {};+ QString reason;+ if(why=="not a realtime preview graph"||why=="still image")reason=tr("只在实时预览生效");+ else if(why=="NR not created")reason=tr("NR 未运行");+ else if(why=="NVIDIA NGX NR only")reason=tr("仅支持英伟达 NR");+ else if(why=="SDR only")reason=tr("HDR 处理时不复用");+ else if(why=="NR motion must use optical flow")reason=tr("NR 运动来源需为光流");+ else if(why=="NR split across SR")reason=tr("NR 分在超分前后时不复用");+ else if(why=="protection between NR stages")reason=tr("NR 层之间有保护区域时不复用");+ else if(why=="node mode")reason=tr("节点模式暂不支持");+ else if(why=="automatic NR size pool")reason=tr("自动 NR 尺寸开启时不复用");+ else reason=tr("资源不足");+ return tr("未生效:")+reason;+}bool QmlPlayerBridge::srActive() const { return impl_->snapshot.srActive; }bool QmlPlayerBridge::fgActive() const { return impl_->snapshot.fgActive; }bool QmlPlayerBridge::captureRecovering() const { return impl_->snapshot.captureRecovering; }diff --git a/src/ui/bridge/Status.cpp b/src/ui/bridge/Status.cppindex bd3a0729..2be9f90c 100644--- a/src/ui/bridge/Status.cpp+++ b/src/ui/bridge/Status.cpp@@ -40,13 +40,6 @@ QString QmlPlayerBridge::srStageNote() const {return notes.join(QStringLiteral(";"));}-// A display rate is only real when the system's display event can be read. No-// counter is wired in this build, so it reports unknown and the UI shows "未测" --// which is exactly what the design requires instead of passing the submit rate off-// as a measurement that was never taken.-double QmlPlayerBridge::displayFps() const { return 0.0; }-bool QmlPlayerBridge::displayFpsKnown() const { return false; }-double QmlPlayerBridge::queuedFrames() const {// Valid output opportunities held by presenter jobs, not cumulative skips// and not the OS/display queue. Zero is meaningful only with a live window.diff --git a/tests/integration/NrReuseGpuTests.cpp b/tests/integration/NrReuseGpuTests.cppnew file mode 100644index 00000000..10ca7cd5--- /dev/null+++ b/tests/integration/NrReuseGpuTests.cpp@@ -0,0 +1,228 @@+// NR inference reuse, GPU pass (docs/NR_INFERENCE_REUSE_2026-11-07.md), on+// real D3D12 dispatches with the debug layer:+// * a reused frame with zero motion shows its source plus the stored change;+// * with a known translation the change follows the content;+// * where the carried key source does not match, the source shows unchanged;+// * chained motion is the sum of the steps and reaches NR's motion inputs;+// * after an inferred frame the motion output is the flow, bit for bit.+#include "veyra/pipeline/NrReusePass.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include <DirectXPackedVector.h>+#include <algorithm>+#include <cmath>+#include <d3d12sdklayers.h>+#include <iostream>+#include <vector>++int main()+{+ using namespace veyra;+ using namespace pipeline;+ using DirectX::PackedVector::HALF;+ using DirectX::PackedVector::XMConvertFloatToHalf;+ using DirectX::PackedVector::XMConvertHalfToFloat;+ gfx::D3D12DeviceContext ctx;+ gfx::CommandSlotRing ring;+ Status status = Status::Ok;+ gfx::DeviceContextDesc desc;+ desc.enableDebugLayer = true;+ if (!ctx.initialize(desc, status) ||+ !ring.initialize(ctx.device(), ctx.directQueue(), ctx.fence(), ctx.fenceEvent(), 4, status)) return 2;++ // The chain at 64x48, the flow at half size, NR's motion input at 64x48:+ // the scaling paths are exercised, not only the 1:1 case.+ constexpr unsigned W = 64, H = 48, FW = 32, FH = 24;+ auto source = makeTexture(ctx.device(), W, H, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ auto output = makeTexture(ctx.device(), W, H, DXGI_FORMAT_R16G16B16A16_FLOAT, true);+ auto flow = makeTexture(ctx.device(), FW, FH, DXGI_FORMAT_R16G16_FLOAT, true);+ auto nrMotion = makeTexture(ctx.device(), W, H, DXGI_FORMAT_R16G16_FLOAT, true);+ auto upload = makeUploadBuffer(ctx.device(), W * H * 8);+ if (!source || !output || !flow || !nrMotion || !upload) return 2;+ D3D12_HEAP_PROPERTIES hp{}; hp.Type = D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};+ bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bd.Width = W * H * 8;+ bd.Height = 1; bd.DepthOrArraySize = 1; bd.MipLevels = 1; bd.SampleDesc.Count = 1;+ bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ ComPtr<ID3D12Resource> readback;+ if (FAILED(ctx.device()->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &bd,+ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) return 2;++ StateTracker states;+ auto run = [&](auto&& record) {+ unsigned slot;+ auto* list = ring.acquireNext(slot, status);+ if (!list) return false;+ record(list);+ return ring.submitAndSignal(slot) && ring.waitIdle();+ };+ // Upload `values` (channels per texel) into an FP16 texture.+ // Footprint rows are padded to the 256-byte pitch alignment.+ auto pitchOf = [](unsigned w, unsigned channels) { return (w * channels * 2 + 255u) & ~255u; };+ auto fill = [&](ID3D12Resource* texture, unsigned w, unsigned h, unsigned channels, const std::vector<float>& values) {+ const unsigned pitch = pitchOf(w, channels);+ void* data = nullptr;+ if (FAILED(upload->Map(0, nullptr, &data))) return false;+ for (unsigned y = 0; y < h; ++y) {+ auto* row = reinterpret_cast<HALF*>(static_cast<uint8_t*>(data) + size_t(y) * pitch);+ for (unsigned i = 0; i < w * channels; ++i) row[i] = XMConvertFloatToHalf(values[size_t(y) * w * channels + i]);+ }+ upload->Unmap(0, nullptr);+ return run([&](ID3D12GraphicsCommandList* list) {+ states.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);+ D3D12_TEXTURE_COPY_LOCATION dst{}, src{};+ dst.pResource = texture; dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ src.pResource = upload.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Footprint = {channels == 4 ? DXGI_FORMAT_R16G16B16A16_FLOAT : DXGI_FORMAT_R16G16_FLOAT, w, h, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ });+ };+ auto read = [&](ID3D12Resource* texture, unsigned w, unsigned h, unsigned channels, std::vector<float>& out, std::vector<uint16_t>* raw = nullptr) {+ const unsigned pitch = pitchOf(w, channels);+ if (!run([&](ID3D12GraphicsCommandList* list) {+ states.transition(list, texture, D3D12_RESOURCE_STATE_COPY_SOURCE);+ D3D12_TEXTURE_COPY_LOCATION dst{}, src{};+ src.pResource = texture; src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ dst.pResource = readback.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ dst.PlacedFootprint.Footprint = {channels == 4 ? DXGI_FORMAT_R16G16B16A16_FLOAT : DXGI_FORMAT_R16G16_FLOAT, w, h, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ })) return false;+ void* data = nullptr;+ D3D12_RANGE range{0, size_t(pitch) * h};+ if (FAILED(readback->Map(0, &range, &data))) return false;+ out.resize(size_t(w) * h * channels);+ if (raw) raw->resize(out.size());+ for (unsigned y = 0; y < h; ++y) {+ const auto* row = reinterpret_cast<const HALF*>(static_cast<const uint8_t*>(data) + size_t(y) * pitch);+ for (unsigned i = 0; i < w * channels; ++i) {+ const size_t at = size_t(y) * w * channels + i;+ out[at] = XMConvertHalfToFloat(row[i]);+ if (raw) (*raw)[at] = row[i];+ }+ }+ D3D12_RANGE empty{0, 0};+ readback->Unmap(0, &empty);+ return true;+ };++ bool ok = true;+ auto check = [&](const char* name, bool success) {+ std::cout << (success ? "PASS " : "FAIL ") << name << std::endl;+ ok &= success;+ };++ NrReusePass pass;+ if (!pass.initialize(ctx.device(), W, H, FW, FH, source.Get(), output.Get(), flow.Get(),+ {{nrMotion.Get(), W, H}})) return 2;++ // A textured gray scene; the "NR change" brightens a 10x10 square.+ auto scene = [&](int shift, float lift, std::vector<float>& px) {+ px.assign(size_t(W) * H * 4, 0);+ for (unsigned y = 0; y < H; ++y)+ for (unsigned x = 0; x < W; ++x) {+ const int sx = int(x) - shift;+ const float v = 0.25f + 0.15f * float(((sx & 7) < 4) ^ ((y & 7) < 4));+ const bool square = sx >= 20 && sx < 30 && y >= 18 && y < 28;+ float* p = &px[(size_t(y) * W + x) * 4];+ p[0] = p[1] = p[2] = v + (square ? lift : 0.f);+ p[3] = 1;+ }+ };+ auto constantFlow = [&](float dx, float dy) {+ std::vector<float> v(size_t(FW) * FH * 2);+ for (size_t i = 0; i < v.size(); i += 2) { v[i] = dx; v[i + 1] = dy; }+ return v;+ };+ auto inferred = [&](int shift) {+ // The inferred frame: chain input and the NR chain's output with its change.+ std::vector<float> in, out;+ scene(shift, 0.f, in);+ scene(shift, 0.2f, out);+ return fill(source.Get(), W, H, 4, in) && fill(output.Get(), W, H, 4, out) &&+ run([&](auto* list) { pass.store(list, states); });+ };+ auto at = [&](const std::vector<float>& px, unsigned x, unsigned y) { return px[(size_t(y) * W + x) * 4]; };++ // --- zero motion: source + stored change ---------------------------------+ {+ std::vector<float> in, result, expected;+ bool steps = inferred(0) && fill(flow.Get(), FW, FH, 2, constantFlow(0, 0));+ scene(0, 0.f, in);+ steps = steps && fill(source.Get(), W, H, 4, in) &&+ run([&](auto* list) { pass.compose(list, states, false); pass.reuse(list, states, {}); }) &&+ read(output.Get(), W, H, 4, result);+ scene(0, 0.2f, expected);+ double worst = 0;+ for (size_t i = 0; steps && i < result.size(); ++i) worst = std::max(worst, double(std::abs(result[i] - expected[i])));+ std::cout << "static worstError=" << worst << std::endl;+ check("zero motion reuses the stored change", steps && worst < 2e-3);+ }+ // --- translation: the change follows the content --------------------------+ {+ // Content moved 4 px right: previous = current + flow, so flow is -4+ // chain pixels, -2 at the half-size flow extent.+ std::vector<float> in, result;+ bool steps = inferred(0) && fill(flow.Get(), FW, FH, 2, constantFlow(-2, 0));+ scene(4, 0.f, in);+ steps = steps && fill(source.Get(), W, H, 4, in) &&+ run([&](auto* list) { pass.compose(list, states, false); pass.reuse(list, states, {}); }) &&+ read(output.Get(), W, H, 4, result);+ // The lifted square now covers x 24..33; x 20..23 is uncovered.+ const float inside = steps ? at(result, 28, 22) - at(in, 28, 22) : 0;+ const float behind = steps ? at(result, 21, 22) - at(in, 21, 22) : 1;+ std::cout << "moved inside=" << inside << " behind=" << behind << std::endl;+ check("the change moves with the content", steps && std::abs(inside - 0.2f) < 0.01f && std::abs(behind) < 0.01f);+ }+ // --- mismatch: unenhanced source ------------------------------------------+ {+ std::vector<float> in, result;+ bool steps = inferred(0) && fill(flow.Get(), FW, FH, 2, constantFlow(0, 0));+ in.assign(size_t(W) * H * 4, 0.9f);+ for (size_t i = 3; i < in.size(); i += 4) in[i] = 1;+ steps = steps && fill(source.Get(), W, H, 4, in) &&+ run([&](auto* list) { pass.compose(list, states, false); pass.reuse(list, states, {}); }) &&+ read(output.Get(), W, H, 4, result);+ double worst = 0;+ for (size_t i = 0; steps && i < result.size(); ++i) worst = std::max(worst, double(std::abs(result[i] - in[i])));+ std::cout << "mismatch worstError=" << worst << std::endl;+ check("content that does not match shows the source unchanged", steps && worst < 1e-3);+ }+ // --- motion outputs ---------------------------------------------------------+ {+ std::vector<float> flowValues = constantFlow(-1.5f, 0.75f), motion, target;+ std::vector<uint16_t> flowBits, motionBits;+ bool steps = fill(flow.Get(), FW, FH, 2, flowValues) &&+ run([&](auto* list) { pass.compose(list, states, false); }) &&+ read(pass.motion(), FW, FH, 2, motion, &motionBits) && read(flow.Get(), FW, FH, 2, flowValues, &flowBits);+ check("after an inferred frame the motion is the flow, bit for bit", steps && motionBits == flowBits);+ // Reused frame (above), then the inferred frame after it: -2 then -3+ // flow pixels chain to -5, which NR's 64-wide input sees as -10.+ steps = fill(flow.Get(), FW, FH, 2, constantFlow(-2, 0)) &&+ run([&](auto* list) { pass.compose(list, states, false); }) &&+ fill(flow.Get(), FW, FH, 2, constantFlow(-3, 0)) &&+ run([&](auto* list) { pass.compose(list, states, true); pass.writeMotionTargets(list, states); }) &&+ read(pass.motion(), FW, FH, 2, motion) && read(nrMotion.Get(), W, H, 2, target);+ const size_t mid = (size_t(FH / 2) * FW + FW / 2) * 2, targetMid = (size_t(H / 2) * W + W / 2) * 2;+ std::cout << "chained motion=" << (steps ? motion[mid] : 0) << " nrInput=" << (steps ? target[targetMid] : 0) << std::endl;+ check("chained motion is the sum of the steps", steps && std::abs(motion[mid] + 5.f) < 1e-3f && std::abs(motion[mid + 1]) < 1e-3f);+ check("NR's motion input receives the chained motion at its own scale",+ steps && std::abs(target[targetMid] + 10.f) < 1e-2f && std::abs(target[targetMid + 1]) < 1e-3f);+ }++ ring.drainQueue();+ ComPtr<ID3D12InfoQueue> info;+ if (FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info)))) return 2;+ unsigned errors = 0;+ for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) {+ SIZE_T size = 0;+ if (FAILED(info->GetMessage(i, nullptr, &size))) return 2;+ std::vector<uint8_t> bytes(size);+ auto* message = reinterpret_cast<D3D12_MESSAGE*>(bytes.data());+ if (FAILED(info->GetMessage(i, message, &size))) return 2;+ if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { ++errors; std::cerr << message->pDescription << std::endl; }+ }+ check("debug layer clean", errors == 0);+ pass.close();+ std::cout << (ok ? "ALL PASS" : "FAILED") << std::endl;+ return ok ? 0 : 1;+}diff --git a/tests/integration/NrReuseQualityProbe.cpp b/tests/integration/NrReuseQualityProbe.cppnew file mode 100644index 00000000..d1119437--- /dev/null+++ b/tests/integration/NrReuseQualityProbe.cpp@@ -0,0 +1,216 @@+// NR inference reuse: picture difference against full inference on a real video+// (docs/NR_INFERENCE_REUSE_2026-11-07.md).+//+// Two graphs built through the product path (chain -> settings -> describeStages)+// process the same decoded frames in lockstep. A infers every frame. B is a+// preview graph that reuses one frame in two (Half). After every frame both NR+// chain outputs are read back and compared in 8-bit sRGB units. Reused frames and+// inferred frames are reported separately: B's inferred frames also differ a+// little, because B's NR history skips the reused frames.+//+// Offline only: the readbacks and CPU waits exist in this executable, never in+// playback. usage: <video> <out-dir> <frames> <dump-frame>+#include "veyra/engine/EffectChain.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/Log.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/RuntimePaths.h"+#include "veyra/source/MediaFileSource.h"+#include <DirectXPackedVector.h>+#include <algorithm>+#include <cmath>+#include <d3d12sdklayers.h>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <vector>++namespace {+using namespace veyra;+// Full-frame RGBA16F readback; the texture is returned to NON_PIXEL_SHADER_RESOURCE,+// the state the graph's own tracker expects it in.+bool readback(gfx::D3D12DeviceContext& ctx, gfx::CommandSlotRing& ring, ID3D12Resource* texture,+ std::vector<float>& rgba, unsigned& width, unsigned& height)+{+ if (!texture) return false;+ const auto desc = texture->GetDesc();+ if (desc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT) return false;+ width = unsigned(desc.Width); height = desc.Height;+ const unsigned rowBytes = width * 8, pitch = (rowBytes + 255) & ~255u;+ D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC buffer{}; buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;+ buffer.Width = UINT64(pitch) * height; buffer.Height = 1; buffer.DepthOrArraySize = 1; buffer.MipLevels = 1;+ buffer.SampleDesc.Count = 1; buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ Microsoft::WRL::ComPtr<ID3D12Resource> staging;+ if (FAILED(ctx.device()->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer,+ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&staging)))) return false;+ unsigned slot = 0; Status status = Status::Ok;+ auto* list = ring.acquireNext(slot, status);+ if (!list) return false;+ D3D12_RESOURCE_BARRIER barrier{}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barrier.Transition.pResource = texture; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;+ list->ResourceBarrier(1, &barrier);+ D3D12_TEXTURE_COPY_LOCATION src{}, dst{};+ src.pResource = texture; src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ dst.pResource = staging.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R16G16B16A16_FLOAT, width, height, 1, pitch};+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);+ std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter);+ list->ResourceBarrier(1, &barrier);+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) return false;+ void* data = nullptr; D3D12_RANGE range{0, size_t(pitch) * height};+ if (FAILED(staging->Map(0, &range, &data))) return false;+ rgba.resize(size_t(width) * height * 4);+ for (unsigned y = 0; y < height; ++y) {+ const auto* row = reinterpret_cast<const DirectX::PackedVector::HALF*>(static_cast<const uint8_t*>(data) + size_t(y) * pitch);+ for (unsigned i = 0; i < width * 4; ++i) rgba[size_t(y) * width * 4 + i] = DirectX::PackedVector::XMConvertHalfToFloat(row[i]);+ }+ D3D12_RANGE none{0, 0}; staging->Unmap(0, &none);+ return true;+}+float srgb8(float linear)+{+ const float v = std::clamp(linear, 0.f, 1.f);+ return 255.f * (v <= 0.0031308f ? 12.92f * v : 1.055f * std::pow(v, 1 / 2.4f) - 0.055f);+}+// Binary PPM (P6), viewable and trivially converted; sRGB-encoded.+bool writePpm(const std::filesystem::path& path, const std::vector<float>& rgba, unsigned w, unsigned h, float gain = 1, const std::vector<float>* minus = nullptr)+{+ std::ofstream out(path, std::ios::binary);+ out << "P6\n" << w << ' ' << h << "\n255\n";+ for (size_t i = 0; i < size_t(w) * h; ++i)+ for (unsigned c = 0; c < 3; ++c) {+ float v = srgb8(rgba[i * 4 + c]);+ if (minus) v = std::min(255.f, std::abs(v - srgb8((*minus)[i * 4 + c])) * gain);+ out.put(char(uint8_t(std::lround(std::clamp(v, 0.f, 255.f)))));+ }+ return bool(out);+}+}++int wmain(int argc, wchar_t** argv)+{+ if (argc != 5) return 2;+ const std::filesystem::path directory = argv[2];+ const unsigned frames = unsigned(_wtoi(argv[3])), dumpFrame = unsigned(_wtoi(argv[4]));+ if (frames < 4 || frames > 600) return 2;+ std::filesystem::create_directories(directory);+ Logger::instance().openFile((directory / L"engine.log").wstring());+ Logger::instance().setConsoleEnabled(false);+ gfx::D3D12DeviceContext ctx; gfx::CommandSlotRing ring; Status status;+ gfx::DeviceContextDesc device; device.enableDebugLayer = true;+ if (!ctx.initialize(device, status) || !ring.initialize(ctx.device(), ctx.directQueue(), ctx.fence(), ctx.fenceEvent(), 6, status)) return 2;+ source::MediaFileSource source; source::SourceOpenDesc open;+ open.path = argv[1]; open.preferHardwareDecode = false;+ if (!source.open(open)) return 2;+ const auto info = source.info();++ // Product path: one enabled NR node, default model, as the list card adds it.+ engine::EffectChain chain; chain.nodeCount = 1;+ chain.nodes[0].type = engine::EffectType::NrEnhance; chain.nodes[0].enabled = true;+ engine::EnhancementSettings settings; engine::fromChain(chain, settings);+ if (!engine::validateChain(chain).accepted || !settings.validate().empty()) return 2;+ engine::StageRequest request; request.nr = true; request.width = info.width; request.height = info.height;+ pipeline::EnhanceGraphDesc full;+ engine::describeStages(request, settings, full);+ full.enableNvofStandalone = full.enableNr;+ full.runtimeAbsPath = runtime::localRuntimeDirectory().wstring();+ auto reused = full;+ reused.nrReusePreview = true; reused.nrReuse = engine::NrReuseMode::Half;+ std::cout << "source=" << info.width << 'x' << info.height << " fps=" << info.averageFps << std::endl;++ // One NR graph per process at a time (the NR runtime adapter owns one hook+ // slot), so the passes run one after the other over the same decoded frames.+ struct Pass { std::vector<std::vector<uint8_t>> frames; std::vector<bool> reused; std::vector<float> dump; uint64_t evaluates = 0;+ double nrChange = 0; unsigned nrChangeFrames = 0; };+ unsigned w = 0, h = 0;+ auto run = [&](const pipeline::EnhanceGraphDesc& desc, Pass& pass) -> int {+ if (!source.seek({0, 1000})) return 2;+ pipeline::EnhanceGraph graph(ctx, ring);+ if (!graph.initialize(desc) || !graph.createViews()) return 2;+ if (desc.nrReusePreview) {+ std::cout << "nr=" << graph.nrWidth() << 'x' << graph.nrHeight() << " reuseActive=" << graph.nrReuseActive()+ << " reason=\"" << graph.nrReuseUnavailable() << "\"" << std::endl;+ if (!graph.nrReuseActive()) return 1;+ }+ std::vector<float> out;+ for (unsigned i = 0; i < frames; ++i) {+ pipeline::FramePacket packet; const AVFrame* frame = nullptr;+ if (source.read(packet, &frame) != source::SourceReadStatus::Frame) break;+ pipeline::EnhanceGraph::FrameOutputs result;+ const uint64_t before = graph.metrics().nrReuseFrames;+ if (!graph.process(frame, packet.pts.toDouble() * 1000, i == 0, result, packet.sequence, &packet.colorInfo) ||+ !ring.waitIdle() || !readback(ctx, ring, graph.diagnosticNrLayerOutput(0), out, w, h)) return 3;+ pass.reused.push_back(graph.metrics().nrReuseFrames > before);+ std::vector<uint8_t> encoded(size_t(w) * h * 3);+ for (size_t p = 0; p < size_t(w) * h; ++p)+ for (unsigned c = 0; c < 3; ++c) encoded[p * 3 + c] = uint8_t(std::lround(srgb8(out[p * 4 + c])));+ // How much NR itself changes the picture, as a scale for the reuse difference.+ std::vector<float> input; unsigned iw = 0, ih = 0;+ if (!desc.nrReusePreview && i >= 2 && readback(ctx, ring, graph.diagnosticNrLayerInput(0), input, iw, ih) && iw == w && ih == h) {+ double change = 0;+ for (size_t p = 0; p < size_t(w) * h; ++p)+ for (unsigned c = 0; c < 3; ++c) change += std::abs(double(encoded[p * 3 + c]) - std::lround(srgb8(input[p * 4 + c])));+ pass.nrChange += change / (double(w) * h * 3); ++pass.nrChangeFrames;+ }+ pass.frames.push_back(std::move(encoded));+ if (i == dumpFrame) pass.dump = out;+ }+ pass.evaluates = graph.metrics().nrEvaluateCount;+ ring.drainQueue(); graph.shutdown();+ return 0;+ };+ Pass a, b;+ if (const int rc = run(full, a)) return rc;+ if (const int rc = run(reused, b)) return rc;+ if (a.frames.size() != b.frames.size() || a.frames.empty()) return 3;++ std::ofstream csv(directory / L"frames.csv");+ csv << "frame,reused,maeSrgb8,maxSrgb8,psnrDb,over8Percent\n";+ double reusedMae = 0, reusedPsnr = 0, inferredMae = 0, inferredPsnr = 0, reusedMax = 0, reusedOver8 = 0;+ unsigned reusedCount = 0, inferredCount = 0;+ for (size_t i = 0; i < a.frames.size(); ++i) {+ double sum = 0, sq = 0, worst = 0; size_t over8 = 0;+ for (size_t k = 0; k < a.frames[i].size(); ++k) {+ const double d = std::abs(int(a.frames[i][k]) - int(b.frames[i][k]));+ sum += d; sq += d * d; worst = std::max(worst, d); over8 += d > 8;+ }+ const double n = double(a.frames[i].size()), mae = sum / n, mse = sq / n;+ const double psnr = mse > 0 ? 10 * std::log10(255.0 * 255.0 / mse) : 99.0, over = 100.0 * double(over8) / n;+ csv << i << ',' << b.reused[i] << ',' << mae << ',' << worst << ',' << psnr << ',' << over << '\n';+ if (i < 2) continue;+ if (b.reused[i]) { reusedMae += mae; reusedPsnr += psnr; reusedMax = std::max(reusedMax, worst); reusedOver8 += over; ++reusedCount; }+ else { inferredMae += mae; inferredPsnr += psnr; ++inferredCount; }+ }+ if (!a.dump.empty() && !b.dump.empty()) {+ writePpm(directory / L"full-inference.ppm", a.dump, w, h);+ writePpm(directory / L"reuse.ppm", b.dump, w, h);+ writePpm(directory / L"difference-x8.ppm", b.dump, w, h, 8, &a.dump);+ std::cout << "dumped frame=" << dumpFrame << " reused=" << (dumpFrame < b.reused.size() && b.reused[dumpFrame]) << std::endl;+ }+ source.close();+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug; unsigned errors = 0;+ if (SUCCEEDED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))+ for (UINT64 i = 0; i < debug->GetNumStoredMessages(); ++i) {+ SIZE_T size = 0; debug->GetMessage(i, nullptr, &size);+ std::vector<unsigned char> bytes(size); auto* m = reinterpret_cast<D3D12_MESSAGE*>(bytes.data());+ if (SUCCEEDED(debug->GetMessage(i, m, &size)) && m->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) {+ ++errors; std::cerr << m->pDescription << std::endl;+ }+ }+ std::cout << "frames reused=" << reusedCount << " inferred=" << inferredCount+ << " reusedMaeSrgb8=" << (reusedCount ? reusedMae / reusedCount : 0)+ << " reusedPsnrDb=" << (reusedCount ? reusedPsnr / reusedCount : 0)+ << " reusedMaxSrgb8=" << reusedMax+ << " inferredMaeSrgb8=" << (inferredCount ? inferredMae / inferredCount : 0)+ << " inferredPsnrDb=" << (inferredCount ? inferredPsnr / inferredCount : 0)+ << " reusedOver8Percent=" << (reusedCount ? reusedOver8 / reusedCount : 0)+ << " nrChangeMaeSrgb8=" << (a.nrChangeFrames ? a.nrChange / a.nrChangeFrames : 0)+ << " evaluatesA=" << a.evaluates << " evaluatesB=" << b.evaluates+ << " debugErrors=" << errors << std::endl;+ return errors == 0 && reusedCount > 0 ? 0 : 1;+}diff --git a/tests/unit/ColorGradeTableTests.cpp b/tests/unit/ColorGradeTableTests.cppindex c7fce319..6520a0f4 100644--- a/tests/unit/ColorGradeTableTests.cpp+++ b/tests/unit/ColorGradeTableTests.cpp@@ -73,6 +73,24 @@ int main(){const auto c=applyMatrix(ColorGradeTables::bake(cool),{0.18f,0.18f,0.18f});check(w[0]>w[2]*1.01f,"positive temperature warms the image (red above blue)");check(c[0]<c[2]*0.99f,"negative temperature cools the image (blue above red)");+ // The cool end must be continuous, bounded and as strong as the warm end+ // (field report 2026-11-07: -100 multiplied blue by ~23 and blew the picture out).+ double previous=0;bool smooth=true,monotone=true;+ for(int v=0;v>=-100;--v){+ ColorSettings c;c.enabled=true;c.temperature=float(v);+ const auto m=applyMatrix(ColorGradeTables::bake(c),{0.18f,0.18f,0.18f});+ const double blueOverRed=double(m[2])/double(m[0]);+ if(v<0){smooth=smooth&&blueOverRed<previous*1.06;monotone=monotone&&blueOverRed>previous;}+ previous=blueOverRed;+ }+ check(smooth&&monotone,"cool temperature grows smoothly, one step at a time, from 0 to -100");+ ColorSettings warmest;warmest.enabled=true;warmest.temperature=100;+ ColorSettings coolest;coolest.enabled=true;coolest.temperature=-100;+ const auto hot=applyMatrix(ColorGradeTables::bake(warmest),{0.18f,0.18f,0.18f});+ const auto cold=applyMatrix(ColorGradeTables::bake(coolest),{0.18f,0.18f,0.18f});+ const double warmShift=std::log(double(hot[0])/double(hot[2])),coolShift=std::log(double(cold[2])/double(cold[0]));+ check(std::abs(coolShift/warmShift-1.0)<0.3,"-100 and +100 shift the white balance about equally");+ check(cold[0]>0.18f*0.5f&&cold[2]<0.18f*2.0f&&cold[1]<0.18f*1.2f,"-100 keeps mid grey within a 2x channel range");ColorSettings green;green.enabled=true;green.tint=80;const auto g=applyMatrix(ColorGradeTables::bake(green),{0.18f,0.18f,0.18f});check(g[1]<g[0]&&g[1]<g[2],"positive tint shifts mid grey towards magenta");diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cppindex 22ce9a6b..8d2f63b7 100644--- a/tests/unit/LivePresentationTimingTests.cpp+++ b/tests/unit/LivePresentationTimingTests.cpp@@ -447,5 +447,32 @@ int main(){ContentDedup dedup;int kept=0;for(int i=0;i<60;++i)kept+=dedup.observe(nullptr,i*166667+1000,166667,i==0).keep;check(kept==60,"dedup without a picture keeps every sample");}}+ {// 1% low of the presents (FramePaceWindow), as RTSS/PresentMon compute it.+ using veyra::engine::FramePaceWindow;+ FramePaceWindow pace;int64_t t=1000000;+ for(int i=0;i<60;++i){pace.complete(t);t+=166667;}+ check(!pace.lowFps(t),"1% low stays unknown until 100 present intervals");+ for(int i=0;i<600;++i){pace.complete(t);t+=166667;}+ const auto steady=pace.lowFps(t);+ check(steady&&std::abs(*steady-60.0)<0.1,"steady 60 Hz presents give a 60 fps 1% low");+ // 1 in 50 presents takes 50 ms: 2% of intervals, so the 99th percentile is one of them.+ FramePaceWindow hitch;t=1000000;+ for(int i=0;i<600;++i){hitch.complete(t);t+=(i%50==49)?500000:166667;}+ const auto low=hitch.lowFps(t);+ check(low&&std::abs(*low-20.0)<0.1,"hitches every 50 frames drag the 1% low to 20 fps");+ // A pause is not a slow frame: the gap is dropped and the run restarts.+ FramePaceWindow paused;t=1000000;+ for(int i=0;i<300;++i){paused.complete(t);t+=166667;}+ t+=30000000;+ for(int i=0;i<300;++i){paused.complete(t);t+=166667;}+ const auto resumed=paused.lowFps(t);+ check(resumed&&std::abs(*resumed-60.0)<0.1,"a three-second pause does not count as a slow frame");+ // Only the last ten seconds count.+ FramePaceWindow old;t=1000000;+ for(int i=0;i<300;++i){old.complete(t);t+=333333;}+ for(int i=0;i<700;++i){old.complete(t);t+=166667;}+ const auto recent=old.lowFps(t);+ check(recent&&std::abs(*recent-60.0)<0.1,"intervals older than ten seconds leave the 1% low");+ }return failed?1:0;}diff --git a/tests/unit/NrReuseTests.cpp b/tests/unit/NrReuseTests.cppnew file mode 100644index 00000000..24beb937--- /dev/null+++ b/tests/unit/NrReuseTests.cpp@@ -0,0 +1,184 @@+// NR inference reuse: frame selection, the Auto controller and the settings+// contract (docs/NR_INFERENCE_REUSE_2026-11-07.md). GPU-free.+#include "veyra/engine/AutoNrReuseController.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/pipeline/NrReuse.h"+#include <iostream>+#include <string>++namespace {+int failures = 0;+void check(const std::string& name, bool ok)+{+ std::cout << (ok ? "PASS " : "FAIL ") << name << std::endl;+ if (!ok) ++failures;+}+// 'K' inferred, 'R' reused, for `frames` frames at `level`.+std::string pattern(unsigned level, unsigned frames, bool available = true)+{+ veyra::pipeline::NrReuseScheduler s;+ s.setLevel(level);+ std::string out;+ for (unsigned i = 0; i < frames; ++i) out += s.next(available) ? 'R' : 'K';+ return out;+}+}++int main()+{+ using namespace veyra;+ using pipeline::NrReuseScheduler;+ using engine::NrReuseMode;++ // --- frame selection ----------------------------------------------------+ check("level 0 infers every frame", pattern(0, 12) == "KKKKKKKKKKKK");+ check("1/2 alternates", pattern(3, 8) == "KRKRKRKR");+ check("1/3 reuses one frame in three", pattern(2, 9) == "KKRKKRKKR");+ check("1/4 reuses one frame in four", pattern(1, 12) == "KKKRKKKRKKKR");+ check("no stored inference: never reuses", pattern(3, 6, false) == "KKKKKK");+ check("manual modes pin their levels",+ NrReuseScheduler::levelFor(NrReuseMode::Half) == 3 && NrReuseScheduler::levelFor(NrReuseMode::Third) == 2 &&+ NrReuseScheduler::levelFor(NrReuseMode::Quarter) == 1 && NrReuseScheduler::levelFor(NrReuseMode::Auto) == 0 &&+ NrReuseScheduler::levelFor(NrReuseMode::Off) == 0);+ check("frames per reuse", NrReuseScheduler::framesPerReuse(3) == 2 && NrReuseScheduler::framesPerReuse(2) == 3 &&+ NrReuseScheduler::framesPerReuse(1) == 4 && NrReuseScheduler::framesPerReuse(0) == 0);+ {+ // A reused frame is always followed by an inferred one, at any level+ // and whatever the availability pattern.+ bool never = true;+ for (unsigned level = 0; level <= 3; ++level) {+ NrReuseScheduler s;+ s.setLevel(level);+ bool last = false;+ for (unsigned i = 0; i < 200; ++i) {+ const bool reused = s.next(i % 7 != 3);+ if (reused && last) never = false;+ last = reused;+ }+ }+ check("never two reused frames in a row", never);+ }+ {+ NrReuseScheduler s;+ s.setLevel(3);+ std::string out;+ for (unsigned i = 0; i < 4; ++i) out += s.next(true) ? 'R' : 'K';+ s.reset();+ for (unsigned i = 0; i < 4; ++i) out += s.next(true) ? 'R' : 'K';+ check("a reset makes the next frame infer and restarts the pattern", out == "KRKRKRKR");+ NrReuseScheduler t;+ t.setLevel(3);+ out.clear();+ out += t.next(true) ? 'R' : 'K';+ t.reset();+ out += t.next(true) ? 'R' : 'K';+ out += t.next(true) ? 'R' : 'K';+ check("reset between an inferred frame and its reuse delays the reuse", out == "KKR");+ }+ {+ NrReuseScheduler s;+ s.setLevel(9);+ check("level clamps to the maximum", s.level() == NrReuseScheduler::kMaxLevel);+ }+ {+ // Only the inferred frame right before a possible reuse keeps its chain.+ for (unsigned level = 1; level <= 3; ++level) {+ NrReuseScheduler s;+ s.setLevel(level);+ std::string keeps, frames;+ for (unsigned i = 0; i < 12; ++i) {+ const bool reused = s.next(true);+ frames += reused ? 'R' : 'K';+ keeps += !reused && s.reuseMayFollow() ? 's' : '-';+ }+ // Every reused frame is preceded by a kept inferred frame, and a kept+ // frame is always followed by a reuse when nothing interferes.+ bool consistent = true;+ for (unsigned i = 0; i + 1 < 12; ++i) consistent &= (keeps[i] == 's') == (frames[i + 1] == 'R');+ check(std::string("level ") + char('0' + level) + " keeps exactly the frames a reuse follows (" + frames + " " + keeps + ")", consistent);+ }+ NrReuseScheduler idle;+ idle.next(true);+ check("level 0 never keeps a chain", !idle.reuseMayFollow());+ }++ // --- Auto controller ----------------------------------------------------+ {+ engine::AutoNrReuseController c;+ const int64_t second = 10000000;+ c.reset(0);+ // 60 fps transport: budget 13.333 ms. Enhancement mean 18 ms with NR 10 ms.+ std::optional<unsigned> change;+ int64_t t = 0;+ for (; t <= 3 * second && !change; t += second / 4) change = c.observe(t, 18.0, 60, 10.0, 13.333);+ check("over budget raises the level within ~2 s", change && *change == 1 && t <= 2 * second);+ // At level 1 the mean drops; still over: keeps raising, one step at a time.+ change.reset();+ const int64_t start = t;+ for (; t <= start + 3 * second && !change; t += second / 4) change = c.observe(t, 15.5, 60, 10.0, 13.333);+ check("still over budget raises again after settling", change && *change == 2 && t - start >= second);+ // Comfortably under budget, but one level down would add (1/3-1/4)*10 ms:+ // 9 + 0.83 = 9.83 < 0.85*13.333 = 11.33, so it steps down after 3 s.+ change.reset();+ const int64_t low = t;+ for (; t <= low + 6 * second && !change; t += second / 4) change = c.observe(t, 9.0, 60, 10.0, 13.333);+ check("sustained headroom lowers the level after ~3 s", change && *change == 1 && t - low >= 3 * second);+ // Under budget, but the lower level would not fit with room: hold.+ change.reset();+ const int64_t hold = t;+ for (; t <= hold + 8 * second && !change; t += second / 4) change = c.observe(t, 10.5, 60, 10.0, 13.333);+ check("no step down when the lower level would not fit", !change && c.level() == 1);+ // Too few samples or no budget: no decision.+ engine::AutoNrReuseController d;+ d.reset(0);+ bool none = true;+ for (int64_t u = 0; u <= 5 * second; u += second / 4)+ none &= !d.observe(u, 30.0, 4, 10.0, 13.333) && !d.observe(u, 30.0, 60, 10.0, 0.0);+ check("no decision without samples or budget", none && d.level() == 0);+ // Never beyond 1/2.+ engine::AutoNrReuseController e;+ e.reset(0);+ for (int64_t u = 0; u <= 30 * second; u += second / 4) e.observe(u, 40.0, 60, 30.0, 13.333);+ check("Auto never goes beyond one reused frame in two", e.level() == engine::AutoNrReuseController::kMaxLevel);+ }++ // --- settings contract --------------------------------------------------+ {+ engine::EnhancementSettings s;+ check("default is off", s.nrReuse == NrReuseMode::Off && s.validate().empty());+ s.nrReuse = static_cast<NrReuseMode>(7);+ check("an unknown mode is rejected", !s.validate().empty());+ s.nrReuse = NrReuseMode::Third;+ check("a manual mode validates", s.validate().empty());+ s.nr = false;+ check("NR off normalises reuse away", s.activeVideoSettings().nrReuse == NrReuseMode::Off);+ s.nr = true;+ check("NR on keeps the mode", s.activeVideoSettings().nrReuse == NrReuseMode::Third);++ engine::EnhancementSettings off;+ off.nr = true;+ auto on = off;+ on.nrReuse = NrReuseMode::Auto;+ auto half = off;+ half.nrReuse = NrReuseMode::Half;+ check("turning reuse on rebuilds", engine::requiresGraphRebuild(off, on));+ check("turning reuse off rebuilds", engine::requiresGraphRebuild(half, off));+ check("switching Auto to a manual ratio is live", !engine::requiresGraphRebuild(on, half));+ auto offNoNr = off;+ offNoNr.nr = false;+ auto onNoNr = on;+ onNoNr.nr = false;+ check("changing the mode while NR is off does not rebuild", !engine::requiresGraphRebuild(offNoNr, onNoNr));++ pipeline::EnhanceGraphDesc desc;+ engine::describeNrLayers(half, desc);+ check("the description carries the mode", desc.nrReuse == NrReuseMode::Half);+ check("only the preview builder marks a graph for reuse", !desc.nrReusePreview);+ engine::describeNrLayers(onNoNr, desc);+ check("NR off describes no reuse", desc.nrReuse == NrReuseMode::Off);+ }++ std::cout << (failures ? "FAILED " : "ALL PASS ") << failures << std::endl;+ return failures ? 1 : 0;+}