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++
feat(nr): add strength five and optional automatic manual picture control
Veyra Goal Agent9eb3b1cf4431
diff --git a/AGENTS.md b/AGENTS.mdindex f5f32db2..f30fed46 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-05 NR 强度与画面调控授权**:用户明确要求“自动调控做为开关,在NR里,也可以选择手动调节,然后保留原版的强度5,开始吧搞定他”。仅在 `E:/项目/Veyra/worktrees/nr-strength-protection-20261005` / `codex/nr-strength-protection-20261005` 从本地 main `de18fc4` 隔离实施。按 `docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md` 修改共享 NR settings/预设/会话、graph/时域接点、残差 shader、QML bridge/逐层面板、翻译、来源 notice、必要 CMake/定向测试与本地打包;此明确范围覆盖历史 UI-only 冻结。默认调控关闭,保留原有路径及总变化量 0–5;自动和手动设置分别保存,不更换、修改或下载 NR DLL,不改采集/解码/音频/补帧/旧 Win32。允许本轮必要 commit/tag/源码 bundle 存档和完整本地候选交付,不包含新 merge/push/Release/关机,不派 Agent。所有产物 E 盘,测试每进程≤300秒、构建≤900秒,不制造 GPU 压力。每轮先运行 `py -3.11 -B scripts/acceptance/nr-protection-control.py guard`;旧 guard/baseline 保留,当前不可变基线独立保存。+> **2026-10-05 本地 main 合并授权**:用户在 Codex 接管 Claude 最新验收和现场修复后明确要求“先合并到main,然后有其他修复等你做”。本次允许提交继承的未提交修复、存档、打标签和本地合并;已将 NR 性能分支及 `claude/field-fixes-20261005` 修复提交 `6e9d827` 合入本地 `main`,合并提交 `f7ced91`。此条覆盖这批工作的历史“不 merge”限制;不包含新的 push/Release、旧 UI 删除或剩余修复实施授权。合并记录见 `docs/MERGE_MAIN_2026-10-05.md`,后续新修复按用户下一条具体要求处理。来源分支和其他工作树保留,桌面旧工作区与用户配置不改,运行库/SDK/模型不得进入源码 Git。> **2026-10-05 性能优化续推约束**:用户明确“继续做吧,我睡了,不要做什么压力测试了”。继续当前NR优化分支与逐节点存档;后续只做正常负载的匹配A/B/B-off和必要功能/画质回归,不启动额外GPU竞争程序、不人为满载或制造显存压力,不改用户其他应用/驱动/配置。该约束覆盖原方案3a/3b等的压力测试要求;动态档以真实播放负载与可控正常素材验证,未测压力边界如实记录。原压力数据仅保留作历史证据,不再执行其驱动。没有新增merge/push/Release/关机授权。diff --git a/CMakeLists.txt b/CMakeLists.txtindex 2c99f73f..dcda029b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1007,6 +1007,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_link_libraries(veyra_motion_validation_tests PRIVATE veyra_pipeline)add_executable(veyra_repair_shader_tests tests/integration/RepairShaderTests.cpp)add_executable(veyra_nr_temporal_gpu_tests tests/integration/NrTemporalGpuTests.cpp)+ add_executable(veyra_nr_correction_gpu_tests tests/integration/NrCorrectionGpuTests.cpp)+ target_compile_features(veyra_nr_correction_gpu_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_nr_correction_gpu_tests PRIVATE /utf-8)+ target_link_libraries(veyra_nr_correction_gpu_tests PRIVATE veyra_pipeline)# Stage-4 defect-audit assertions: GPU-free checks on the architecture-spoof# scope and the Ampere re-label policy (see docs/NR_FG_OPTIMIZATION_PLAN_2026-09-29.md).# Stage-6 anti-flicker tier assertions (GPU-free: enum narrowing, flat/listdiff --git a/README.md b/README.mdindex 5296cc1a..74c3264b 100644--- a/README.md+++ b/README.md@@ -22,6 +22,8 @@ A Windows enhancement player for videos, images, capture cards and streaming. Su## Highlights+**Local NR controls, 2026-10-05:** each NR layer's **Enhancement delta → Total strength** now reaches 5. **Picture control** defaults off; enable it and select Automatic or Manual. Manual controls cover hue, chroma, highlights, local compression and temporal stability. Automatic control preserves the source's colour direction and limits unsafe local changes; switching modes keeps the manual values. Turning control off preserves the original residual algorithm and strength. Five extrapolates one inference's residual; protection reduces gain in risky pixels, so it cannot promise full gain five with no artifacts on every video. Presets, List/Node sessions, PNGs and video exports share the settings. [Local validation and known limits](docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md); public 2.0.3 assets do not include this feature.+- **Rebuilt interface:** Home, Cinema, Professional List, Nodes, Colour, Export and Settings; Simplified/Traditional Chinese, English and Japanese.- **Node editing and layered NR:** executable connections, independent NR/colour parameters, separate List/Node configurations, sessions and presets.- **PC / Xbox streaming:** Moonlight/Sunshine-compatible PC streaming and unofficial experimental Xbox support, alongside PS5, capture cards and screen capture.diff --git a/README_CN.md b/README_CN.mdindex a4ed6de1..e0423e69 100644--- a/README_CN.md+++ b/README_CN.md@@ -20,6 +20,8 @@ Windows 视频、图片、采集卡与串流增强工具。在同一处理链组## 2.0.0 重点+**本地 NR 调控,2026-10-05:** 每层 NR 的“增强变化量 → 总变化强度”现在最高为 5。“画面调控”默认关闭,开启后可选自动/手动;手动可调色相保护、色度保护、高光保护、局部压缩和时域稳定。自动按原图约束色偏及过强变化,切换方式保留手动数值;关闭后保留原始残差算法与强度。5 是一次推理结果的残差外推,保护会降低危险像素的局部增益,不能保证所有素材在完整局部增益 5 下无失真。预设、列表/节点会话、PNG 与视频导出共用这些设置。验收与已知限制见[本轮记录](docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md),公开 2.0.3 包尚未包含此功能。+- **全新界面**:首页、极简、专业列表、节点、调色、导出和设置重新组织;支持简中、繁中、English、日本語。- **节点编辑与多层 NR**:连线编排处理顺序,NR/调色独立参数;列表与节点各自保存配置、会话和预设。- **PC / Xbox 串流**:Moonlight/Sunshine 协议 PC 串流、非官方实验 Xbox 接入,与 PS5、采集卡、屏幕捕获共用增强。diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 9136d8f1..e01c79e2 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -726,3 +726,22 @@ library can be relinked), HarfBuzz 14.4.0 (MIT), libpng (libpng license), zlib`share/<port>/copyright` files of that vcpkg install and must accompany everypackage that contains this build. No source of these libraries is committed toVeyra's Git. Builds without `VEYRA_LIBASS_ROOT` keep the built-in styled renderer.++## Optional NR image correction (2026-10-05)++`shaders/NrCorrection.hlsli` ports the Oklab transforms, gray-axis-continuous+hue projection, residual soft knee and fixed-lightness/hue gamut-ray mapping+from [SAOG0721/Magpie](https://github.com/SAOG0721/Magpie), commit+`27c5df91177a29b33be612e98274169f3d2fca49` (GPL-3.0),+`src/Magpie.Core/DLSSNRColorShader.h` and `DLSSNRDetailShader.h`.+The Oklab matrices by Bjorn Ottosson are public domain:+<https://bottosson.github.io/posts/oklab/> (2021-01-25 matrices).++Veyra changes: operate directly on linear FP16 instead of stored SDR/sRGB;+retain the existing residual controls and opt-out path; extend total gain to 5;+add a chroma-delta budget, a source-anchored highlight shoulder, a 16-iteration+FP16-oriented gamut search, signed scRGB/BT.2020 HDR bounds and final temporal+safety. `NrResidualComposite.hlsl` and `NrTemporal.hlsl` call that shared helper.+Automatic/manual UI, settings persistence and graph controls are Veyra code.+Temporal filtering reuses Veyra's already attributed Magpie motion route;+no additional neural model or proprietary runtime is copied or modified here.diff --git a/docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md b/docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.mdnew file mode 100644index 00000000..7add5bc1--- /dev/null+++ b/docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md@@ -0,0 +1,48 @@+# NR 强度与画面调控执行记录++## 2026-10-05 开工++起点 `de18fc4`;隔离工作树/授权/合同见 `NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md`。+`git status --short` 干净,tag 与 `git bundle verify` 通过。归档 SHA256 已记录在方案。+产物统一使用 `E:/项目/Veyra/{build,tests,logs,tmp,test-packages,archives}/nr-strength-protection-20261005/`。++## 实现及审查++- 总残差强度 0–5;每层调控默认关。自动和手动都保留强度 5,手动五项 0–1,自动启用源图约束。模型强度仍为原来的 0–1,不额外调用模型。关闭调控与起点 shader 在 0/1/2/5 下逐位一致。+- 来源为 Magpie `27c5df91177a29b33be612e98274169f3d2fca49`,Oklab 色相投影、灰轴连续保护、软膝残差压缩。Veyra 改为直接线性 FP16,追加色度变化预算、高光肩部和固定色相色域搜索;HDR 使用 signed scRGB / BT.2020 物理边界,保留负 BT.709 分量与源高光。没有逐帧曝光、CPU 像素回读或未来帧。来源及修改见 `THIRD_PARTY_NOTICES.md`。+- 时域使用现有 80 ms 光流重投影历史,按原图补丁一致性拒绝不可信历史;切镜、无光流、间隔断点、参数变更、零当前残差不保留旧修正。开启调控接管旧防闪,关闭后恢复旧设置;手动稳定性 0 不启用历史。+- 列表/节点共用 `NrLayerEditor`、桥接与处理图;单层/多层、全栈保护、暂停、图片保存和视频导出使用同一组参数。旧预设默认关;新参数或强度 >2 使用 preset schema 29 / library schema 8,会话保留其嵌套配置。复制、重置、保存与重启恢复均已检查。+- 对抗式源码审查发现多层最终保护 pass 仍使用旧 24 常量布局,已统一为 32(补充块清零,避免重复调控)。实际两层分别自动/手动、强度均为 5、带全栈保护的播放器短测通过。+- 构建配置最初继承旧发布缓存,遗漏 Claude 的 libass。候选未交付;已改为最新 `build/field-fixes-20261005/B/CMakeCache.txt` 的全部依赖配置,静态 libass 路径与已验收版一致。最终实际播放器日志有 `fonts configured container=1`、`track ready events=5 styles=3`,保留 ASS 与 MKV 内嵌字体能力。++## 已执行验证++| 验证 | 结果及证据(均在 E:/项目/Veyra 下) |+| --- | --- |+| 生产 C++ / HLSL 构建 | `py -3.11 -B scripts/acceptance/nr-protection-build.py stack-root-build veyra_qml_ui veyra_nr_correction_gpu_tests veyra_nr_temporal_gpu_tests`,退出 0;`logs/nr-strength-protection-20261005/stack-root-build.log`。后续仅改测试/文档,生产 EXE SHA256 `599fd89057a645540cf51e1afa3f93534297ee2de5a95ec1073f346b50149174`,19702272 bytes。 |+| 参数、旧预设、会话、处理链、旧防闪、残差回归 | `py -3.11 -B scripts/acceptance/nr-protection-tests.py final-cpu preset-library preset-legacy effect-chain nr-tiers legacy-shader` 全部退出 0;`logs/nr-strength-protection-20261005/final-cpu/results.json`。包括强度 5 关闭/自动/手动、隐藏手动值、flat/多层与列表/节点保存、严格输入验证、旧文件保护。 |+| 实际 GPU 色彩 shader | `py -3.11 -B scripts/acceptance/nr-protection-tests.py final-gpu temporal correction correction-fp16` 全部退出 0。FP32 和生产 FP16 各 2048 像素、34 检查;关闭时对冻结起点 DXIL 的 0/1/2/5 逐位一致,maxError=0;自动色域/肤色/灰轴/高光/阴影、有限值、手动各项、零保护/零残差、signed HDR。两组 D3D12 debug errors=0、warnings=0;`tests/nr-strength-protection-20261005/final-gpu/shader[-fp16]/shader-result.json`。 |+| 实际 GPU 时域 | 同一 `final-gpu/temporal.log`:48 帧交替亮度残差输出范围 <0.02(输入 0.06),交替色度范围 0.12→0.03125;运动越界、源图变更、断点、无光流、reset、零当前残差与手动稳定性 0 均正确旁路/清历史;debug error=0。 |+| 鼠标/键盘组件 | `py -3.11 -B scripts/acceptance/nr-protection-quick.py mouse4`:40 passed、0 failed;真实 Qt 鼠标点击、滑块、最高值键盘钳位、开关、自动/手动、五个参数、隐藏值保留、多层独立;使用软件 Qt 界面和显式测试快照,不冒充真实引擎桥接。`logs/nr-strength-protection-20261005/qml-mouse4/quick.log`。 |+| 真实单层播放/PNG/预设/导出 | `nr-protection-ui.py first final1` 通过真实播放器桥接控制,四张暂停同帧 PNG、预设保存/应用、复制/重置、两种编辑模式切换。NVENC D3D12 HEVC 3840×2160 导出 source=60、encoded=60、generated=0、hold=0;ffprobe 验证 60 帧,`logs/nr-strength-protection-20261005/production-final1/export-probe.json`。随后 `restore finalrestore1` 第二进程成功恢复两模式强度 5 与手动值。 |+| 真实多层及保护 | `nr-protection-ui.py multi multilayer1` 两层强度 5,第一层自动、第二层手动,真实 NR 创建/播放/全栈保护及 PNG 成功;`logs/nr-strength-protection-20261005/production-multilayer1/`。 |+| 真实游戏素材静帧对照 | `nr-protection-ui.py visual realvideo1 E:/项目/Veyra/tests/hotfix-2.0.0-20261002/media/gta6-1080p30-12s-audio.mp4` 通过;`tests/nr-strength-protection-20261005/production-realvideo1/screenshots/`。人工查看原始 5/自动/手动,观察到自动抑制原始 5 的明显色偏;这只是该帧检查,不是所有素材主观画质或拖影验收。 |+| 继承字幕功能 | `nr-protection-smoke.py inherited2` 实际原 MKV ASS/字体夹具通过,退出 0,无产品错误;`logs/nr-strength-protection-20261005/smoke-inherited2/result.json`。 |+| 翻译与范围 | `py -3.11 -B scripts/i18n/extract.py --check`:1979 entries,繁中/英文/日文 missing=0,placeholder problems=0。每阶段 `nr-protection-control.py guard` 确认独立分支、固定开工归档、其他 18 个工作树 HEAD/status 不变,禁止 SDK/DLL/模型入本轮源码。 |++本机为 RTX 5070,沿用已核验的 Lecram(F95FEB…)、SFv2(6EB209…)与 NVIDIA 原件(E16BCF…),未采用 Swapper 新 DLL。只做正常有界短测,没有竞争负载、压力测试或停止用户进程。构建 ≤900s、每项测试进程 ≤300s,TEMP/TMP 只对本任务子进程设在 E 盘。++## 失败、修复和边界++- 开发期间两次编译失败分别为 `ChainNrParams` 没有 `usesTemporal()` 和测试类型缺少命名空间,均已修复并重新构建。最初 GPU HDR 测试错误地要求两个 BT.709 分量都保持负值,改为验证实际的 signed 色域与源色相/物理峰值合同,未通过放宽 SDR 高光或非有限值检查制造通过。+- 旧预设测试必须传有父目录的目标文件;首次未传参数/无父目录均属夹具错误,已修正。实际 UI 夹具先遇截图目录未建,再遇“预设 UI 行号”与“预设 id”偏移,改用真实 `id` 后保存/应用通过。QuickTest 首次缺 Qt QML 模块,后补完整打包模块;随后修复测试布局等待、总强度新范围及布尔快照转换。libass 首次 smoke 错误要求日志输出版本号;库本身已正常渲染,已改为检查真实字体和 track ready 证据。失败日志保留,不记成产品通过。+- MPEG4 人工短片首次硬解 `send_packet -22` 后使用原有软件回退,NR 播放及导出正常。另用真实 H.264 游戏素材核对原路径;不能把此 MPEG4 回退隐去或称为本轮已修复解码问题。+- `veyra_hdr_color_tests` 的 8 项 native HDR_COLOR 失败在起点 main `de18fc4` 独立构建/执行后,失败名称、数值完全一致:HLG=0 error=12.4882,HLG=1 error=2.53929,各四种组合。证据 `logs/nr-strength-protection-20261005/hdr-baseline-comparison.json`;对应 NR 关闭,属于已存在的 HDR 边界,未修改/合并暂缓的 HDR PR。全局 HDR suite 不是通过。+- 保护会牺牲危险区域的局部变化,不能保证“完整局部增益 5 + 所有素材正常”;有些 NR 新造纹理/几何错误无法从色彩后处理中恢复。仅确认本机软件执行与上述数值/素材,RTX 20/30/40、AMD、真实 HDR 显示、真实采集、长时运动拖影及用户主观质量仍需对应设备/素材。+- 自动 NR 尺寸(按负载)原有合同不接受时域 NR;开启调控稳定时继续显示该限制,不借本功能扩大 Auto 尺寸准入。本次不修原后台掉帧/GPU UI 采集问题。++## 本地交付++目录:`E:/项目/Veyra/test-packages/nr-strength-protection-20261005/Veyra-2.0.3-nr-controls-NVIDIA-win64-portable/`。+同级便携 ZIP、对应源码 ZIP、最终逐文件 manifest 及 `DELIVERY.json` 由 `nr-protection-package.py finalize` 在本地源码提交后生成和核验;最终包摘要以 `DELIVERY.json` 为准(不自引用包 hash)。开工与最终源码 Git bundle 保留在 `archives/nr-strength-protection-20261005/`。+运行库/许可证继承已验收的 field-20261005b NVIDIA 包;本轮 export-worker 诊断移到任务 logs,不随包提供。主线、桌面旧工作树、其他工作区和用户配置保留;本功能没有合并、推送或发布。diff --git a/docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md b/docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.mdnew file mode 100644index 00000000..f39eeab6--- /dev/null+++ b/docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md@@ -0,0 +1,31 @@+# NR 强度 5 与可选画面调控++2026-10-05,用户授权实施;起点本地 main `de18fc4f71843049dc7fd691898598c17af308f0`。+工作树 `E:/项目/Veyra/worktrees/nr-strength-protection-20261005`,分支 `codex/nr-strength-protection-20261005`。+开工 tag `checkpoint/pre-nr-strength-protection-20261005`,源码存档 `E:/项目/Veyra/archives/nr-strength-protection-20261005/source-before.bundle`,SHA256 `AFE2A7A4DC39A7BF7D230E65C0107F99D3F7F290FB00890B281F1D3443D1E286`。++## 行为合同++- 逐层 NR 总变化量范围 0–5;模型参数和其余残差分量范围不变。5 是一次 NR 输出与输入的残差外推,不是五次模型推理,也不保证等同多层 NR。+- 每层“画面调控”开关默认关闭;关闭时沿用现有残差算法,不暗中降低总变化量。开启可选择自动或手动;手动提供色相保护、色度保护、高光保护、局部压缩、时域稳定 0–1,切换模式不抹掉保存值。+- 自动保护按原图及当前像素的失控风险决定抑制程度,不使用逐帧自动曝光或额外 NR Evaluate。安全细节保留高强度,接近色域/高光边界的变化会受限制。不能承诺所有内容在完整局部增益 5 下都无失真。+- 借用 Magpie `27c5df91177a29b33be612e98274169f3d2fca49` 的 Oklab 色相投影、灰轴连续保护、局部软膝压缩与固定色相色域映射,记录 GPLv3 来源。Veyra 输入已是线性 FP16,不重复 sRGB 解码;HDR 使用 scRGB(1=80 nit)与 BT.2020 边界,不能套 SDR 0–1 裁切。+- 时域稳定复用现有有界历史、光流、原图补丁置信度及 reset;不增加未来帧或呈现等待。调控稳定和旧实验防闪独立保存,有效时域配置由共享描述生成;参数变化/reset 拒绝旧历史。无可信运动/切镜/间隔断点时立即旁路历史。+- 三入口与列表/节点共享实现;设置、预设、复制、重置、会话恢复、图片/视频导出均保留参数。旧预设默认调控关闭,只有新功能/强度>2 才升级文件 schema。++## 允许文件边界++`AGENTS.md`、本方案/执行记录/WORKLOG、README 与来源 notice;`include/veyra/engine/EnhancementSettings.h`、`GraphDescription.h`、新增调控 codec;`src/engine/PresetStore.cpp`、`PresetLibrary.cpp`;`include/veyra/pipeline/NrTemporalPass.h`、`src/pipeline/NrTemporalPass.cpp`、`EnhanceGraph.cpp`;`shaders/NrResidualComposite.hlsl`、`NrTemporal.hlsl`、新增 `NrCorrection.hlsli`;`src/ui/QmlPlayerBridge.cpp`、`qml/Veyra/NrLayerEditor.qml`、`i18n/catalog.json`;`CMakeLists.txt`、`cmake/VeyraShaders.cmake`;本功能定向测试及 `scripts/acceptance/nr-protection-*`。如发现必要新接点,先记录证据再扩充本方案/guard;不修改历史 baseline。++## 验收与交付++1. 构建生产程序、实际 HLSL 与相关预设/链/颜色/时域/QML 测试。每进程测试≤300s、构建≤900s,正常负载;日志/临时目录都在本轮 E 盘。+2. 实际 GPU shader:调控关闭与起点 shader 等价;0/1/2/5、零残差、保护区;灰轴/肤色/饱和彩色、近黑/高光、越界候选、signed HDR、有限值;自动与手动边界和零保护;运动/切镜/seek/reset、交替亮度与色度稳定,不以减闪掩盖拖影。+3. 真实 NR 本机短测,核对 Evaluate 次数、设置/预设/会话、列表/节点 UI、暂停刷新、图片/视频导出、继承修复。RTX 本机证据不代替 20/30/40/AMD 实卡或用户主观画质验收;不以像素数值检查宣称所有视频正常。+4. 本地完整 NVIDIA 候选、组件 hash/manifest、源码存档与日志。运行库沿用已审计本地候选,不修改原件、不进源码 Git。无新的合并/推送/Release。++## 当前进度++- 已建隔离工作树、tag 与已验证源码 bundle。+- README 范围包含中英文入口 `README.md`、`README_CN.md`、`README_EN.md`;仅补充本地功能状态及使用方法,已同步本轮 guard 白名单,不改历史基线。+- 实施与验收记录:`docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md`。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 4e4604ea..f5b14390 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,17 @@# Veyra 工作记录+## 2026-10-05 NR 强度 5 与自动/手动调控开工++用户明确授权本功能实施。已从本地 main `de18fc4` 建 `codex/nr-strength-protection-20261005`,工作树 `E:/项目/Veyra/worktrees/nr-strength-protection-20261005`;开工 tag 和已验证 `source-before.bundle` 在 `E:/项目/Veyra/archives/nr-strength-protection-20261005`。方案 `docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md`;独立不可变 `start.json` SHA256 `909bdde5eb460e4b69c5548cc5e504c90d8dbd7e8001e2e47dfe9260d60fd46e`。`py -3.11 -B scripts/acceptance/nr-protection-control.py guard` 通过,其他工作树 HEAD/status 不变。全部新产物按用途写入 E 盘同任务目录;禁止压力测试、不换运行库、不合并/推送/发布。此条仅记录开工,验收结果待实际执行。++### 本轮实施与验收++总变化强度 0–5,逐层默认关闭的自动/手动画面调控,五个手动保护项;线性 Oklab 色相/灰轴、局部压缩/色度预算/高光/signed HDR 色域保护,复用原光流和有界历史,无额外 NR 推理、未来帧或 CPU 像素回读。预设/会话 schema 29/8、列表/节点、复制/重置和导出一致。对抗审查补齐多层全栈保护的 32 常量,修正构建依赖以保留 Claude 的静态 libass。来源、全部命令/失败与边界见 `docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md`。++生产构建 `stack-root-build.log` 退出 0,EXE `599fd89057a645540cf51e1afa3f93534297ee2de5a95ec1073f346b50149174`。`nr-protection-tests.py final-cpu ...` 五项通过;`final-gpu temporal correction correction-fp16` 三项通过,FP32/FP16 各 34 检查、2048 像素,0/1/2/5 关闭时逐位匹配起点 shader,D3D12 error/warning=0;48 帧交替色度范围 0.12→0.03125。QuickTest `mouse4` 40/0;翻译 `extract.py --check` missing=0。实际 UI `first final1` 通过原始/自动/手动与 PNG、预设/复制,NVENC D3D12 HEVC 4K 60 源帧/60 编码帧无 hold;`restore finalrestore1` 重启恢复、`multi multilayer1` 两层带保护、`visual realvideo1` 游戏静帧对照、`smoke inherited2` MKV 特效字幕/字体均通过。++全局 native HDR 8 项旧失败在原 main 单独复现且数值相同(`hdr-baseline-comparison.json`),不能说 HDR suite 全过;20/30/40/AMD、真实 HDR/采集/长时质量未验。初始编译、预设路径、UI 夹具与 QuickTest 布局/依赖问题均已修复,MPEG4 人工素材使用既有软件解码回退,失败证据保留。实际输出均在 `E:/项目/Veyra/{build,tests,logs,tmp,test-packages,archives}/nr-strength-protection-20261005/`,最终包/源码/manifest 以同级 `DELIVERY.json` 为准;测试进程均有上限,无压力测试。保留当前构建、最终候选与必要失败/基线证据;主线和其他工作树不变,本功能未 merge/push/Release。+## 2026-10-05 继续剩余节点,禁止追加压力测试用户睡前要求继续且不要压力测试。Goal已恢复active,当前c4ea7d8/干净分支,nr-control guard通过(112路径);保持原主线/桌面/运行组件与用户配置。先存档3c-graph-normal-before,再准备正常播放DIRECT/COMPUTE及普通/HIGH呈现对照,不启动旧competition驱动。所有新证据仍在E:/项目/Veyra/{logs,tests,tmp,archives}/perf-nr-20261004。随后多NR/跨帧/黑边/自动尺寸逐节点尝试;无收益或画面不满足保留门槛的实现回退,不能将API通过冒充性能收益,画质需人工确认的部分默认不启用。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex b3ad2925..3dc01241 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -2864,6 +2864,13 @@"en": "When off, the host keeps its own resolution and scales the picture itself","ja": "オフのとき、ホストは自身の解像度のままで映像をスケーリングします"},+ {+ "zh": "关闭时保留原始变化量,最高 5",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "關閉時保留原始變化量,最高 5",+ "en": "Off preserves the original residual gain up to 5",+ "ja": "オフでは元の変化量を保持(最大 5)"+ },{"zh": "关闭时这条链路不存在,零开销","src": "qml/ColourPanel.qml",@@ -5237,6 +5244,13 @@"en": "LAN streaming","ja": "LAN ストリーミング"},+ {+ "zh": "局部压缩",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "局部壓縮",+ "en": "Local compression",+ "ja": "局所圧縮"+ },{"zh": "局部明暗","src": "qml/NrLayerEditor.qml",@@ -5874,6 +5888,13 @@"en": "Switches, progress, selected state","ja": "スイッチ、進行状況、選択状態"},+ {+ "zh": "开启调控",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "開啟調控",+ "en": "Enable correction",+ "ja": "調整を有効化"+ },{"zh": "开始","src": "qml/HomePage.qml",@@ -6693,6 +6714,13 @@"en": "Hold for original","ja": "押してオリジナル"},+ {+ "zh": "按原图约束色偏、高光和过强变化;风险区域会降低局部变化量。时域稳定复用光流,快速运动或切镜时拒绝历史。切换自动/手动保留手动数值。",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "按原圖約束色偏、高光和過強變化;風險區域會降低局部變化量。時域穩定重用光流,快速運動或切鏡時拒絕歷史。切換自動/手動保留手動數值。",+ "en": "Uses the original image to constrain hue shifts, highlights and excessive changes. Risky regions receive less gain. Temporal stability reuses optical flow and rejects history during fast motion or cuts. Switching Auto/Manual retains manual values.",+ "ja": "元画像を基準に色相ずれ、ハイライト、過剰な変化を抑えます。問題のある領域では局所的に強度を下げます。時間方向の安定化は光学フローを再利用し、速い動きやカットでは履歴を破棄します。自動/手動の切り替え後も手動値を保持します。"+ },{"zh": "按键可在 设置 → 快捷键 里改","src": "qml/ProPage.qml",@@ -7296,6 +7324,13 @@"en": "NR protected areas from the old node preset were removed; other settings are kept and saved to a .p3-node file from now on; the original file is not overwritten","ja": "旧ノードプリセットの NR 保護領域を削除しました。その他の設定は保持し、今後は .p3-node ファイルに保存します。元のファイルは上書きしません"},+ {+ "zh": "时域稳定",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "時域穩定",+ "en": "Temporal stability",+ "ja": "時間方向の安定化"+ },{"zh": "时间","src": "qml/DialogHost.qml",@@ -9074,6 +9109,20 @@"en": "Aspect ratio","ja": "アスペクト比"},+ {+ "zh": "画面调控",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "畫面調控",+ "en": "Image correction",+ "ja": "画質調整"+ },+ {+ "zh": "画面调控已接管时域稳定;关闭调控后恢复此设置",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "畫面調控已接管時域穩定;關閉調控後恢復此設定",+ "en": "Image correction controls temporal stability; this setting returns when correction is off",+ "ja": "画質調整が時間方向の安定化を制御中。オフにするとこの設定に戻ります。"+ },{"zh": "界面始终用显卡绘制;为避免冲突,小飞机 OSD 不在 Veyra 里显示","src": "qml/SettingsPage.qml",@@ -10068,6 +10117,13 @@"en": "Choose at least one item","ja": "少なくとも 1 項目を選んでください"},+ {+ "zh": "色度保护",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "色度保護",+ "en": "Chroma protection",+ "ja": "彩度保護"+ },{"zh": "色彩","src": "qml/ProPage.qml",@@ -10173,6 +10229,13 @@"en": "Hue","ja": "色相"},+ {+ "zh": "色相保护",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "色相保護",+ "en": "Hue protection",+ "ja": "色相保護"+ },{"zh": "色调","src": "src/ui/QmlPlayerBridge.cpp",@@ -11132,6 +11195,13 @@"en": "Scheduling stepped down","ja": "スケジュールを段階的に下げました"},+ {+ "zh": "调控方式",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "調控方式",+ "en": "Correction mode",+ "ja": "調整モード"+ },{"zh": "调整中","src": "src/ui/QmlPlayerBridge.cpp",@@ -13078,6 +13148,13 @@"en": "Preset library: invalid NR resolution","ja": "プリセットライブラリの NR 解像度が不正です"},+ {+ "zh": "预设库 NR 调控参数损坏",+ "src": "src/engine/PresetLibrary.cpp",+ "zh-TW": "預設庫 NR 調控參數損壞",+ "en": "Preset library NR correction parameters are invalid",+ "ja": "プリセットの NR 調整パラメーターが無効です"+ },{"zh": "预设库 VFG 质量字段损坏","src": "src/engine/PresetLibrary.cpp",@@ -13484,6 +13561,13 @@"en": "Highlights","ja": "ハイライト"},+ {+ "zh": "高光保护",+ "src": "qml/Veyra/NrLayerEditor.qml",+ "zh-TW": "高光保護",+ "en": "Highlight protection",+ "ja": "ハイライト保護"+ },{"zh": "高延迟·需 CPU 拆包","src": "include/veyra/source/CaptureFormatRank.h",diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex d4a7a94e..1ecfa8ad 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -124,9 +124,28 @@ struct NrSettings {int32_t style=0,autoMask=0,uiCorrection=0;bool operator==(const NrSettings&) const = default;};+struct NrCorrectionSettings {+ bool enabled=false,automatic=true;+ // Manual values survive switching automatic control on and off.+ float hue=1,chroma=.75f,highlight=1,compression=.75f,stability=.8f;+ bool operator==(const NrCorrectionSettings&) const = default;+ bool valid() const {+ for(float v:{hue,chroma,highlight,compression,stability})+ if(!std::isfinite(v)||v<0||v>1)return false;+ return true;+ }+ bool usesHistory() const {return enabled&&(automatic||stability>0);}+ std::array<float,8> constants(bool hdr=false) const {+ return {enabled?1.f:0.f,automatic?1.f:hue,automatic?1.f:chroma,+ automatic?1.f:highlight,automatic?1.f:compression,automatic?1.f:stability,+ automatic?1.f:0.f,hdr?1.f:0.f};+ }+};struct ResidualSettings {float total=1,darken=1,brighten=1,color=1,luminance=1;+ NrCorrectionSettings correction{};bool operator==(const ResidualSettings&) const = default;+ bool extendedSchema() const {return total>2||correction!=NrCorrectionSettings{};}};// Fixed storage: settings also cross the export worker's shared-memory POD.// Runtime and NR/SR order are shared by active instances, not separate adapters.@@ -141,6 +160,7 @@ struct NrLayerSettings {NrAntiFlicker antiFlicker=NrAntiFlicker::Flow;pipeline::NrSizePolicy sizePolicy=pipeline::NrSizePolicy::Realtime;bool operator==(const NrLayerSettings&) const = default;+ bool usesTemporal() const {return residual.correction.enabled?residual.correction.usesHistory():temporal;}};struct ProtectionRect {float left=0,top=0,right=0,bottom=0;@@ -189,6 +209,12 @@ struct EnhancementSettings {// enabled layer (or the first node when every layer is bypassed).std::array<NrLayerSettings,kMaxNrInstances> nrLayers{};uint32_t nrLayerCount=0;+ bool usesNrTemporal() const {+ if(!nrLayerCount)return residual.correction.enabled?residual.correction.usesHistory():nrTemporal;+ for(uint32_t i=0;i<nrLayerCount&&i<nrLayers.size();++i)+ if(nrLayers[i].enabled&&nrLayers[i].usesTemporal())return true;+ return false;+ }NrLayerSettings nrLayer(uint32_t index) const {if(nrLayerCount&&index<nrLayers.size())return nrLayers[index];return {model,residual,nrRuntime,nrTemporal,lowLatency,nr,nrAntiFlicker,nrPolicy};@@ -210,9 +236,11 @@ struct EnhancementSettings {}bool sameNrTopology(const EnhancementSettings& other) const {if(nrLayerCount!=other.nrLayerCount)return false;+ if(residual.correction.enabled!=other.residual.correction.enabled||usesNrTemporal()!=other.usesNrTemporal())return false;for(uint32_t i=0;i<nrLayerCount&&i<nrLayers.size();++i){const auto& a=nrLayers[i]; const auto& b=other.nrLayers[i];- if(a.enabled!=b.enabled||a.temporal!=b.temporal||a.runtime!=b.runtime||+ if(a.enabled!=b.enabled||a.temporal!=b.temporal||a.usesTemporal()!=b.usesTemporal()||+ a.residual.correction.enabled!=b.residual.correction.enabled||a.runtime!=b.runtime||a.lowLatencyPairing!=b.lowLatencyPairing||a.sizePolicy!=b.sizePolicy)return false;}return true;@@ -333,7 +361,8 @@ struct EnhancementSettings {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";- for(float v:{residual.total,residual.darken,residual.brighten,residual.color,residual.luminance})if(!range(v,2))return "residual parameter out of range";+ if(!range(residual.total,5)||!residual.correction.valid())return "NR residual/correction parameter out of range";+ for(float v:{residual.darken,residual.brighten,residual.color,residual.luminance})if(!range(v,2))return "residual parameter out of range";if(nrLayerCount>nrLayers.size())return "too many NR instances";for(uint32_t i=0;i<nrLayerCount;++i){const auto& n=nrLayers[i];@@ -342,7 +371,8 @@ struct EnhancementSettings {(n.model.skin!=-1&&!range(n.model.skin,2)))return "NR layer model parameter out of range";if(n.model.style<0||n.model.style>2||n.model.autoMask<0||n.model.autoMask>1||n.model.uiCorrection<0||n.model.uiCorrection>1)return "invalid NR layer experimental parameter";- for(float v:{n.residual.total,n.residual.darken,n.residual.brighten,n.residual.color,n.residual.luminance})+ if(!range(n.residual.total,5)||!n.residual.correction.valid())return "NR layer residual/correction parameter out of range";+ for(float v:{n.residual.darken,n.residual.brighten,n.residual.color,n.residual.luminance})if(!range(v,2))return "NR layer residual parameter out of range";if(!validNrRuntime(n.runtime))return "invalid NR layer runtime";diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.hindex 05ca7cd3..21205f0a 100644--- a/include/veyra/engine/GraphDescription.h+++ b/include/veyra/engine/GraphDescription.h@@ -7,19 +7,26 @@ namespace veyra::engine {// Shared by graph creation and drained live-parameter updates. Disabled list// nodes stay in settings, but never allocate or evaluate an NR feature.inline void describeNrLayers(const EnhancementSettings& settings,pipeline::EnhanceGraphDesc& desc){- desc.nrRuntime=settings.nrRuntime;desc.nrTemporal=settings.nrTemporal;desc.nrAntiFlicker=settings.nrAntiFlicker;+ desc.nrRuntime=settings.nrRuntime;+ desc.nrTemporal=settings.residual.correction.enabled?settings.residual.correction.usesHistory():settings.nrTemporal;+ desc.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.nrLayersModel.clear();desc.nrLayersResidual.clear();- desc.nrLayersTemporal.clear();desc.nrLayersProtection.clear();+ desc.nrLayersTemporal.clear();desc.nrLayersAntiFlicker.clear();desc.nrLayersProtection.clear();desc.nrLayersSizePolicy={settings.nrPolicy};if(!settings.nrLayerCount||!settings.nr)return;+ const bool corrected=std::any_of(settings.nrLayers.begin(),settings.nrLayers.begin()+settings.nrLayerCount,+ [](const auto& n){return n.enabled&&n.residual.correction.enabled;});desc.nrLayersSizePolicy.clear();for(uint32_t i=0;i<settings.nrLayerCount&&i<kMaxNrInstances;++i){const auto& n=settings.nrLayers[i];if(!n.enabled)continue;desc.nrLayersModel.push_back(n.model);desc.nrLayersResidual.push_back(n.residual);- desc.nrLayersTemporal.push_back(n.temporal);+ desc.nrLayersTemporal.push_back(n.usesTemporal());+ // Untouched stacks retain the previous global-tier contract exactly.+ // Controlled layers use Flow independently of the saved legacy tier.+ if(corrected)desc.nrLayersAntiFlicker.push_back(n.residual.correction.enabled?NrAntiFlicker::Flow:n.antiFlicker);desc.nrLayersSizePolicy.push_back(n.sizePolicy);desc.nrLayersProtection.push_back(ProtectionSettings{});}@@ -84,7 +91,7 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,constdesc.enableNr=request.nr&&(request.nvidiaAdapter||request.amdNr)&&(!settings.nrLayerCount||settings.activeNrLayerCount()>0);desc.nrBeforeSr=!request.stillImage&&!request.exportJob&&lowLatency&&desc.enableNr&&desc.enableSr;desc.enableNvofStandalone=desc.enableNr;- const bool temporalMotion=settings.nrTemporal||std::any_of(settings.nrLayers.begin(),settings.nrLayers.begin()+settings.nrLayerCount,[](const auto& n){return n.enabled&&n.temporal;});+ const bool temporalMotion=settings.usesNrTemporal();desc.enableNvofStandalone=desc.enableNr&&(motionUsesFlow(settings.nrMotion)||temporalMotion);desc.enableFg=request.fg&&(request.nvidiaAdapter||(!request.exportJob&&crossVendorFrameGeneration(settings.frameGenerationBackend)));desc.fgMultiplier=request.fgMultiplier;diff --git a/include/veyra/engine/NrCorrectionCodec.h b/include/veyra/engine/NrCorrectionCodec.hnew file mode 100644index 00000000..e77db096--- /dev/null+++ b/include/veyra/engine/NrCorrectionCodec.h@@ -0,0 +1,18 @@+#pragma once+#include "veyra/engine/EnhancementSettings.h"+#include <istream>+#include <ostream>++namespace veyra::engine {+// Appended only in the new preset schema; legacy files retain default/off.+inline void writeNrCorrection(std::ostream& out,const NrCorrectionSettings& c){+ out<<int(c.enabled)<<' '<<int(c.automatic)<<' '<<c.hue<<' '<<c.chroma<<' '+ <<c.highlight<<' '<<c.compression<<' '<<c.stability;+}+inline bool readNrCorrection(std::istream& in,NrCorrectionSettings& c){+ int enabled,automatic;+ if(!(in>>enabled>>automatic>>c.hue>>c.chroma>>c.highlight>>c.compression>>c.stability)||+ enabled<0||enabled>1||automatic<0||automatic>1||!c.valid())return false;+ c.enabled=enabled!=0;c.automatic=automatic!=0;return true;+}+}diff --git a/include/veyra/pipeline/NrTemporalPass.h b/include/veyra/pipeline/NrTemporalPass.hindex 8aacc126..ee87eb71 100644--- a/include/veyra/pipeline/NrTemporalPass.h+++ b/include/veyra/pipeline/NrTemporalPass.h@@ -18,7 +18,8 @@ public:engine::NrAntiFlicker tier=engine::NrAntiFlicker::Flow);ID3D12Resource* raw()const{return raw_.Get();}void run(ID3D12GraphicsCommandList*,StateTracker&,bool reset,bool haveMotion,double frameMs,- float total,const engine::ProtectionSettings& protection);+ float total,const engine::ProtectionSettings& protection,+ const engine::NrCorrectionSettings& correction={},bool hdr=false);void reset(){valid_=false;}void close();private:diff --git a/qml/Veyra/NrLayerEditor.qml b/qml/Veyra/NrLayerEditor.qmlindex da22253d..9ac2a6ca 100644--- a/qml/Veyra/NrLayerEditor.qml+++ b/qml/Veyra/NrLayerEditor.qml@@ -47,7 +47,7 @@ ColumnLayout {VSlider {objectName: "nr-" + valueRow.spec.keyvalueFromModel: true- resettable: true; defaultValue: valueRow.spec.key === "skin" ? -1 : 1+ resettable: true; defaultValue: valueRow.spec.defaultValue ?? (valueRow.spec.key === "skin" ? -1 : 1)implicitWidth: 110from: valueRow.spec.min; to: valueRow.spec.maxvalue: valueRow.amount@@ -206,7 +206,7 @@ ColumnLayout {Layout.fillWidth: truelabel: qsTr("增强变化量"); count: 5Repeater {- model: [{key:"total",label:qsTr("总变化强度"),min:0,max:2},+ model: [{key:"total",label:qsTr("总变化强度"),min:0,max:5},{key:"darken",label:qsTr("暗化变化"),min:0,max:2},{key:"brighten",label:qsTr("亮化变化"),min:0,max:2},{key:"color",label:qsTr("色彩变化"),min:0,max:2},@@ -218,16 +218,60 @@ ColumnLayout {}}}+ VSubGroup {+ objectName: "nr-correction-group"+ Layout.fillWidth: true+ label: qsTr("画面调控"); count: editor.layerData.correctionEnabled ? (editor.layerData.correctionAuto ? 2 : 7) : 1+ VRow {+ label: qsTr("开启调控")+ hint: qsTr("关闭时保留原始变化量,最高 5")+ VSwitch {+ objectName: "nr-correctionEnabled"+ checked: editor.layerData.correctionEnabled ?? false+ onToggled: checked => editor.edited(editor.layerData.index,"correctionEnabled",checked?1:0)+ }+ }+ VRow {+ visible: editor.layerData.correctionEnabled ?? false+ label: qsTr("调控方式")+ VSeg {+ objectName: "nr-correctionAuto"+ options: [{id:"1",label:qsTr("自动")},{id:"0",label:qsTr("手动")}]+ current: (editor.layerData.correctionAuto ?? true) ? "1" : "0"+ onPicked: id => editor.edited(editor.layerData.index,"correctionAuto",Number(id))+ }+ }+ Repeater {+ model: [{key:"hueProtection",label:qsTr("色相保护"),min:0,max:1,defaultValue:1},+ {key:"chromaProtection",label:qsTr("色度保护"),min:0,max:1,defaultValue:0.75},+ {key:"highlightProtection",label:qsTr("高光保护"),min:0,max:1,defaultValue:1},+ {key:"localCompression",label:qsTr("局部压缩"),min:0,max:1,defaultValue:0.75},+ {key:"temporalStability",label:qsTr("时域稳定"),min:0,max:1,defaultValue:0.8}]+ delegate: NrValueRow {+ required property var modelData+ visible: (editor.layerData.correctionEnabled ?? false) && !(editor.layerData.correctionAuto ?? true)+ spec: modelData; amount: editor.layerData[modelData.key] ?? modelData.defaultValue+ onEdited: amount => editor.edited(editor.layerData.index,modelData.key,amount)+ }+ }+ Text {+ Layout.fillWidth: true+ visible: editor.layerData.correctionEnabled ?? false+ text: qsTr("按原图约束色偏、高光和过强变化;风险区域会降低局部变化量。时域稳定复用光流,快速运动或切镜时拒绝历史。切换自动/手动保留手动数值。")+ color: Theme.t3; font.pixelSize: 11; wrapMode: Text.WordWrap+ }+ }VSubGroup {objectName: "nr-experimental-group"Layout.fillWidth: truelabel: qsTr("实验"); count: editor.layerData.temporal ? 3 : 2VRow {label: qsTr("时间域防闪烁")- hint: qsTr("需要光流;关掉则不做时域累积")+ hint: editor.layerData.correctionEnabled ? qsTr("画面调控已接管时域稳定;关闭调控后恢复此设置") : qsTr("需要光流;关掉则不做时域累积")VSwitch {objectName: "nr-temporal"checked: editor.layerData.temporal+ enabled: !(editor.layerData.correctionEnabled ?? false)onToggled: checked => editor.edited(editor.layerData.index,"temporal",checked?1:0)}}@@ -240,6 +284,7 @@ ColumnLayout {hint: qsTr("静态最稳、光流为默认、低频保留高频细节")VSelect {objectName: "nr-antiflicker"+ enabled: !(editor.layerData.correctionEnabled ?? false)options: [{id:"1",label:qsTr("静态累积")},{id:"2",label:qsTr("光流累积 · 默认")},diff --git a/scripts/acceptance/nr-protection-build.py b/scripts/acceptance/nr-protection-build.pynew file mode 100644index 00000000..50af6330--- /dev/null+++ b/scripts/acceptance/nr-protection-build.py@@ -0,0 +1,54 @@+"""Production build using the already audited 2.0.3 dependency cache."""+from pathlib import Path+import os+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[2]+BASE = Path('E:/项目/Veyra')+TASK = 'nr-strength-protection-20261005'+label = sys.argv[1]+assert label.replace('-', '').isalnum()+BUILD = BASE / 'build' / TASK+TMP = BASE / 'tmp' / TASK / 'build'+SOURCE=ROOT+if '--baseline' in sys.argv:+ sys.argv.remove('--baseline')+ SOURCE=BASE/'worktrees/main-merge-20261002'+ assert subprocess.check_output(['git','-C',str(SOURCE),'rev-parse','HEAD'],text=True).strip()=='de18fc4f71843049dc7fd691898598c17af308f0'+ BUILD=BUILD/'baseline';TMP=TMP/'baseline'+LOG = BASE / 'logs' / TASK / (label + '.log')+for p in (BUILD, TMP, LOG.parent): p.mkdir(parents=True, exist_ok=True)+guard = [sys.executable, '-B', str(ROOT / 'scripts/acceptance/nr-protection-control.py'), 'guard']+subprocess.run(guard, check=True)+settings = []+cache = BASE / 'build/field-fixes-20261005/B/CMakeCache.txt'+assert cache.is_file(), 'Latest accepted field-fix dependency cache is required'+assert 'VEYRA_LIBASS_ROOT:PATH=' in cache.read_text(encoding='utf-8'), 'Preserve the accepted libass subtitle renderer'+for line in cache.read_text(encoding='utf-8').splitlines():+ if ':' not in line or '=' not in line or line.startswith(('#', '//')): continue+ keytype, value = line.split('=', 1)+ key, kind = keytype.split(':', 1)+ if kind in ('INTERNAL', 'STATIC') or key == 'VEYRA_DISPLAY_VERSION': continue+ if key.startswith('VEYRA_') or key in ('CMAKE_PREFIX_PATH', 'CMAKE_MAKE_PROGRAM', 'PROTOC', 'PKG_CONFIG_EXECUTABLE'):+ if key == 'VEYRA_LIBASS_ROOT':+ assert (Path(value) / 'include/ass/ass.h').is_file(), 'Accepted libass SDK is unavailable'+ settings.append(f'set({key} [[{value}]] CACHE {kind} "Audited field-fix dependency" FORCE)')+settings.append('set(VEYRA_DISPLAY_VERSION [[2.0.3-nr-controls]] CACHE STRING "Local NR controls candidate" FORCE)')+(TMP / 'dependencies.cmake').write_text('\n'.join(settings), encoding='utf-8')+targets = sys.argv[2:] or ['veyra_qml_ui']+assert all(t.replace('_', '').isalnum() for t in targets)+cmd = TMP / 'build.cmd'+cmd.write_text('@echo off\nchcp 65001 >nul\ncall "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat" >nul 2>&1\nif errorlevel 1 exit /b 4\n"%TASK_CMAKE%" --preset x64-release -S "%TASK_ROOT%" -B "%TASK_BUILD%" -C "%TASK_TMP%\\dependencies.cmake"\nif errorlevel 1 exit /b 5\n"%TASK_CMAKE%" --build "%TASK_BUILD%" --parallel 6 --target ' + ' '.join(targets) + '\nexit /b %errorlevel%\n', encoding='ascii')+env = os.environ.copy()+env.update(TEMP=str(TMP), TMP=str(TMP), VSLANG='1033', TASK_ROOT=str(SOURCE), TASK_BUILD=str(BUILD), TASK_TMP=str(TMP),+ TASK_CMAKE='C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe')+with LOG.open('x', encoding='utf-8') as out:+ try:+ rc = subprocess.run(['cmd.exe', '/d', '/c', str(cmd)], cwd=ROOT, env=env,+ stdout=out, stderr=subprocess.STDOUT, timeout=890).returncode+ except subprocess.TimeoutExpired: rc = 124+print('BUILD', rc, LOG)+print('\n'.join(LOG.read_text(encoding='utf-8', errors='replace').splitlines()[-24:]))+subprocess.run(guard, check=True)+raise SystemExit(rc)diff --git a/scripts/acceptance/nr-protection-control.py b/scripts/acceptance/nr-protection-control.pynew file mode 100644index 00000000..0b5ad38e--- /dev/null+++ b/scripts/acceptance/nr-protection-control.py@@ -0,0 +1,80 @@+"""Task-specific immutable baseline and source-only scope guard."""+from pathlib import Path+import hashlib+import json+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[2]+BASE = Path('E:/项目/Veyra')+TASK = 'nr-strength-protection-20261005'+START = 'de18fc4f71843049dc7fd691898598c17af308f0'+BRANCH = 'codex/' + TASK+ARCHIVE = BASE / 'archives' / TASK+RECORD = ARCHIVE / 'start.json'+ALLOWED = {+ 'AGENTS.md', 'README.md', 'README_CN.md', 'README_EN.md', 'THIRD_PARTY_NOTICES.md',+ 'docs/WORKLOG.md', 'docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md',+ 'docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md',+ 'include/veyra/engine/EnhancementSettings.h', 'include/veyra/engine/GraphDescription.h',+ 'include/veyra/engine/NrCorrectionCodec.h',+ 'include/veyra/pipeline/NrTemporalPass.h', 'src/pipeline/NrTemporalPass.cpp',+ 'src/pipeline/EnhanceGraph.cpp', 'src/engine/PresetStore.cpp', 'src/engine/PresetLibrary.cpp',+ 'shaders/NrResidualComposite.hlsl', 'shaders/NrTemporal.hlsl', 'shaders/NrCorrection.hlsli',+ 'src/ui/QmlPlayerBridge.cpp', 'qml/Veyra/NrLayerEditor.qml', 'i18n/catalog.json',+ 'CMakeLists.txt', 'cmake/VeyraShaders.cmake',+ 'tests/unit/PresetLibraryTests.cpp', 'tests/unit/RepairPresetTests.cpp',+ 'tests/unit/EffectChainTests.cpp', 'tests/unit/GraphDescriptionTests.cpp',+ 'tests/integration/RepairShaderTests.cpp', 'tests/integration/NrVideoQualityProbe.cpp',+ 'tests/integration/NrCorrectionGpuTests.cpp', 'tests/integration/NrTemporalGpuTests.cpp',+ 'tests/qml/quick/tst_components.qml',+}++def git(*args, root=ROOT):+ result=subprocess.run(['git', '-C', str(root), *args], encoding='utf-8',stdout=subprocess.PIPE,stderr=subprocess.PIPE)+ if result.returncode:raise RuntimeError(result.stderr)+ return result.stdout.strip()++def sha(path):+ h = hashlib.sha256()+ with path.open('rb') as f:+ for b in iter(lambda: f.read(1024 * 1024), b''): h.update(b)+ return h.hexdigest()++def worktrees():+ result = []+ for block in git('worktree', 'list', '--porcelain').split('\n\n'):+ lines = block.splitlines()+ if not lines: continue+ path = Path(lines[0].removeprefix('worktree '))+ if path.resolve() == ROOT.resolve(): continue+ result.append({'path': str(path), 'head': git('rev-parse', 'HEAD', root=path),+ 'status': git('status', '--porcelain', '--untracked-files=all', root=path)})+ return result++def guard():+ data = json.loads(RECORD.read_text(encoding='utf-8'))+ assert ROOT.resolve() == Path(data['root']).resolve()+ assert git('branch', '--show-current') == BRANCH+ subprocess.run(['git', '-C', str(ROOT), 'merge-base', '--is-ancestor', START, 'HEAD'], check=True)+ assert sha(ARCHIVE / 'source-before.bundle') == data['bundleSha256']+ assert worktrees() == data['otherWorktrees'], 'Other worktree HEAD/status changed: investigate; never reset it.'+ changed = set(git('diff', '--name-only', START).splitlines())+ changed.update(git('ls-files', '--others', '--exclude-standard').splitlines())+ assert all(f in ALLOWED or f.startswith('scripts/acceptance/nr-protection-') for f in changed), sorted(changed - ALLOWED)+ # SDK/runtime/media/build bytes may not enter the source checkout or Git.+ suffixes = {'.dll', '.lib', '.pdb', '.dxil', '.exe', '.zip', '.7z', '.onnx', '.safetensors', '.mp4'}+ assert not any(Path(f).suffix.lower() in suffixes for f in changed)+ print('NR protection guard PASS', len(changed), 'scoped source files; protected worktrees unchanged')++if __name__ == '__main__':+ if sys.argv[1:] == ['start']:+ assert git('branch', '--show-current') == BRANCH and git('rev-parse', 'HEAD') == START+ ARCHIVE.mkdir(parents=True, exist_ok=True)+ record = {'root': str(ROOT), 'branch': BRANCH, 'head': START,+ 'bundleSha256': sha(ARCHIVE / 'source-before.bundle'), 'otherWorktrees': worktrees()}+ with RECORD.open('x', encoding='utf-8') as f: json.dump(record, f, ensure_ascii=False, indent=2)+ print('Immutable baseline created', RECORD, sha(RECORD))+ else:+ assert sys.argv[1:] == ['guard']+ guard()diff --git a/scripts/acceptance/nr-protection-package.py b/scripts/acceptance/nr-protection-package.pynew file mode 100644index 00000000..64df319b--- /dev/null+++ b/scripts/acceptance/nr-protection-package.py@@ -0,0 +1,115 @@+"""Stage/finalize the local NVIDIA package with source and independent receipts."""+from pathlib import Path+import hashlib,json,shutil,subprocess,sys,zipfile+ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra');TASK='nr-strength-protection-20261005'+SOURCE=BASE/'test-packages/field-fixes-20261005/Veyra-2.0.3-field-20261005b-NVIDIA-win64-portable'+PARENT=BASE/'test-packages'/TASK+APP=PARENT/'Veyra-2.0.3-nr-controls-NVIDIA-win64-portable'+BUILD=BASE/'build'/TASK;LOG=BASE/'logs'/TASK;ARCHIVE=BASE/'archives'/TASK+mode=sys.argv[1] if len(sys.argv)>1 else 'stage';assert mode in ('stage','finalize')+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/nr-protection-control.py'),'guard'],check=True)+def sha(p):+ h=hashlib.sha256()+ with p.open('rb') as f:+ for b in iter(lambda:f.read(1024*1024),b''):h.update(b)+ return h.hexdigest()+def save(p,value):p.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n',encoding='utf8')+def git(*args):return subprocess.check_output(['git','-C',str(ROOT),*args],text=True,encoding='utf8').strip()+expected={'runtime/experimental/nvngx_dlssnr.dll':'F95FEB54137EA11979F9B4EC4F00AFD84B5C98A5624D3388FBF6A87714A39FCC',+ 'runtime/experimental/nr-ampere/nvngx_dlssnr.dll':'6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927',+ 'runtime/experimental/nr-original/nvngx_dlssnr.dll':'E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E'}+for rel,digest in expected.items():assert sha(SOURCE/rel).upper()==digest,rel+if mode=='stage':+ assert not APP.exists();shutil.copytree(SOURCE,APP)+else:+ assert APP.is_dir() and not git('status','--porcelain'),'Commit the validated source before finalizing'+ assert sha(APP/'veyra_qml_ui.exe')==sha(BUILD/'veyra_qml_ui.exe')+ assert sha(APP/'qml/Veyra/Main.qml')==sha(ROOT/'qml/Veyra/Main.qml'),'Remove test injection before delivery'+ for suite in ('final-cpu','final-gpu'):+ checks=json.loads((LOG/suite/'results.json').read_text(encoding='utf8'))+ assert checks and all(c['exit']==0 for c in checks),suite+ assert json.loads((LOG/'qml-mouse4/result.json').read_text(encoding='utf8'))['exit']==0+ ass=json.loads((LOG/'smoke-inherited2/result.json').read_text(encoding='utf8'))+ assert ass['passed'] and ass['exeSha256']==sha(APP/'veyra_qml_ui.exe')+ for label,marker in [('final1','UI'),('finalrestore1','RESTORE'),('multilayer1','MULTI'),('realvideo1','VISUAL')]:+ console=(LOG/('production-'+label)/'console.log').read_text(encoding='utf8',errors='replace')+ assert 'NR_CONTROLS_'+marker+'_PASS' in console and 'NR_CONTROLS_UI_FAIL' not in console,label+ # Move only this task's named diagnostic files; never recursively delete a tree.+ workerLogs=LOG/'export-workers';workerLogs.mkdir(exist_ok=True)+ for p in (APP/'logs').glob('export-worker-*.log'):+ assert p.resolve().is_relative_to(APP.resolve())+ destination=workerLogs/p.name+ assert destination.resolve().is_relative_to(LOG.resolve()) and not destination.exists()+ shutil.move(str(p),str(destination))+shutil.copy2(BUILD/'veyra_qml_ui.exe',APP/'veyra_qml_ui.exe')+shutil.copytree(ROOT/'qml',APP/'qml',dirs_exist_ok=True)+shutil.copytree(BUILD/'shaders',APP/'shaders',dirs_exist_ok=True)+for name in ('THIRD_PARTY_NOTICES.md','README.md','README_CN.md','README_EN.md'):shutil.copy2(ROOT/name,APP/name)+for name in ('NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md','NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md'):+ shutil.copy2(ROOT/'docs'/name,APP/'docs'/name)+(APP/'NR_CONTROLS_LOCAL.md').write_text('本地 NR 画面调控版(未发布)\n\nNR → 增强变化量 → 总变化强度:0–5。NR → 画面调控 → 开启调控:默认关闭,开启后选自动/手动。关闭保留原始变化量;手动可调色相、色度、高光、局部压缩、时域稳定,切换自动仍保留手动值。开启调控接管时间域防闪,关闭恢复原设置。\n\n沿用已核验 Lecram / SFv2 / NVIDIA 原版 NR,未替换 Swapper DLL;保留 Claude 的 libass 字幕及其他主线修复。5 是残差外推,保护会降低危险区域的局部增益,不能保证所有视频无失真。RTX 20/30/40/AMD、真实 HDR 显示及长时主观质量还需验收;全局 native HDR 有八项起点已存在的测试失败,不能宣称 HDR 全过。详见 docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md。\n',encoding='utf8')+for rel,digest in expected.items():assert sha(APP/rel).upper()==digest,rel+receipt={'sourcePackage':str(SOURCE),'candidate':str(APP),'runtimeHashes':expected,'executableSha256':sha(APP/'veyra_qml_ui.exe'),+ 'mainQmlSha256':sha(APP/'qml/Veyra/Main.qml'),'status':mode}+save(LOG/'package-stage.json',receipt)+if mode=='stage':print('CANDIDATE staged',APP);raise SystemExit(0)+head=git('rev-parse','HEAD');assert git('branch','--show-current')=='codex/'+TASK+# Audit every inherited component, including codecs, VFG/CUDA, models and manifests.+immutable={}+for p in SOURCE.rglob('*'):+ if not p.is_file():continue+ rel=p.relative_to(SOURCE).as_posix()+ if rel.startswith(('runtime/','runtime_local/','models/','licenses/')) or p.suffix.lower()=='.dll' or rel in ('release-runtime-manifest.json','vfg-runtime-manifest.json'):+ immutable[rel]=sha(p);assert sha(APP/rel)==immutable[rel],rel+for p in APP.rglob('*'):+ if p.is_file():+ rel=p.relative_to(APP).as_posix()+ assert not rel.startswith(('logs/','tmp/','outputs/','screenshots/','profile/')),rel+ assert p.suffix.lower() not in ('.lib','.pdb','.addon64','.pyc','.whl'),rel+sourceZip=PARENT/'Veyra-2.0.3-nr-controls-veyra-source.zip';assert not sourceZip.exists()+tracked=subprocess.check_output(['git','-C',str(ROOT),'ls-files','-z']).decode('utf8').split('\0')+with zipfile.ZipFile(sourceZip,'x',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:+ for rel in sorted(filter(None,tracked)):z.write(ROOT/rel,arcname='Veyra-2.0.3-nr-controls-source/'+rel)+with zipfile.ZipFile(sourceZip) as z:+ assert z.testzip() is None+ for rel in filter(None,tracked):assert hashlib.sha256(z.read('Veyra-2.0.3-nr-controls-source/'+rel)).hexdigest()==sha(ROOT/rel),rel+bundle=ARCHIVE/'source-final.bundle';assert not bundle.exists()+subprocess.run(['git','-C',str(ROOT),'bundle','create',str(bundle),'HEAD'],check=True)+with (LOG/'final-bundle-verify.log').open('w',encoding='utf8') as out:+ subprocess.run(['git','-C',str(ROOT),'bundle','verify',str(bundle)],stdout=out,stderr=subprocess.STDOUT,check=True)+manifest=json.loads((SOURCE/'package-manifest.json').read_text(encoding='utf8'))+manifest.update(candidate='2.0.3-nr-controls-20261005',baseCommit='de18fc4f71843049dc7fd691898598c17af308f0',+ sourceCommit=head,sourceArchiveCommit=head,worktreeDirty=False,releaseReady=False,localOnly=True,displayVersion='2.0.3-nr-controls',+ executableSha256=receipt['executableSha256'],validationRecord='docs/NR_STRENGTH_PROTECTION_EXECUTION_2026-10-05.md',+ softwareValidation='NR targeted checks passed; eight pre-existing native HDR test failures reproduced on starting main',+ hardwareValidation='RTX 5070 local short tests only; RTX 20/30/40, AMD, real HDR/capture and long subjective quality unverified')+manifest['correspondingSource'].update(application='../'+sourceZip.name,applicationSha256=sha(sourceZip),+ displayVersionOverride='-DVEYRA_DISPLAY_VERSION=2.0.3-nr-controls')+excluded={'package-manifest.json','local-package-manifest.json'}+records=[{'path':p.relative_to(APP).as_posix(),'size':p.stat().st_size,'sha256':sha(p)}+ for p in sorted(APP.rglob('*')) if p.is_file() and p.name not in excluded]+manifest['files']=records;save(APP/'package-manifest.json',manifest)+local={'purpose':'NR strength five with optional automatic/manual picture control; local only','sourceCommit':head,+ 'baseCommit':manifest['baseCommit'],'displayVersion':manifest['displayVersion'],+ 'exeSha256':receipt['executableSha256'],'worktreeDirty':False,'releaseReady':False,+ 'unchangedInheritedComponents':immutable,'files':records,'packageManifestSha256':sha(APP/'package-manifest.json')}+save(APP/'local-package-manifest.json',local)+for row in records:assert sha(APP/row['path'])==row['sha256'],row['path']+archive=PARENT/(APP.name+'.zip');assert not archive.exists()+print('SOURCE verified; packaging',len(records),'files,',len(immutable),'unchanged components',flush=True)+with zipfile.ZipFile(archive,'x',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:+ for p in sorted(APP.rglob('*')):+ if p.is_file():z.write(p,arcname=p.relative_to(PARENT).as_posix())+with zipfile.ZipFile(archive) as z:+ assert z.testzip() is None+ for row in records:assert hashlib.sha256(z.read(APP.name+'/'+row['path'])).hexdigest()==row['sha256'],row['path']+ for name in excluded:assert hashlib.sha256(z.read(APP.name+'/'+name)).hexdigest()==sha(APP/name)+receipt.update(status='local delivery; targeted NR tests passed, hardware/quality limits documented',+ sourceCommit=head,sourceZip=str(sourceZip),sourceZipSha256=sha(sourceZip),sourceBundle=str(bundle),sourceBundleSha256=sha(bundle),+ archive=str(archive),archiveBytes=archive.stat().st_size,archiveSha256=sha(archive),+ fileCount=len(records)+len(excluded),unchangedComponentCount=len(immutable),+ packageManifestSha256=sha(APP/'package-manifest.json'),scopePassed=True,zipCrcAndAllPayloadHashesPassed=True)+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/nr-protection-control.py'),'guard'],check=True)+save(PARENT/'DELIVERY.json',receipt);save(LOG/'delivery.json',receipt)+print(json.dumps(receipt,ensure_ascii=False,indent=2),flush=True)diff --git a/scripts/acceptance/nr-protection-quick.py b/scripts/acceptance/nr-protection-quick.pynew file mode 100644index 00000000..0737c5bc--- /dev/null+++ b/scripts/acceptance/nr-protection-quick.py@@ -0,0 +1,30 @@+"""Stage and exercise shared QML controls through real Qt mouse events."""+from pathlib import Path+import json,os,shutil,subprocess,sys+ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra');TASK='nr-strength-protection-20261005'+label=sys.argv[1];assert label.replace('-','').isalnum()+OUT=BASE/'tests'/TASK/('qml-'+label);TMP=BASE/'tmp'/TASK/('qml-'+label)+LOG=BASE/'logs'/TASK/('qml-'+label)+for p in (OUT,TMP,LOG):p.mkdir(parents=True,exist_ok=False)+QT=Path('C:/veyra-deps/qt-veyra/6.8.3/msvc2022_64')+APP=BASE/'test-packages'/TASK/'Veyra-2.0.3-nr-controls-NVIDIA-win64-portable'+shutil.copy2(BASE/'build'/TASK/'veyra_qml_quick_tests.exe',OUT/'veyra_qml_quick_tests.exe')+for p in APP.glob('Qt6*.dll'):shutil.copy2(p,OUT/p.name)+for name in ('Qt6Test.dll','Qt6QuickTest.dll'):shutil.copy2(QT/'bin'/name,OUT/name)+shutil.copytree(APP/'qml',OUT/'qml')+shutil.copytree(ROOT/'qml',OUT/'qml',dirs_exist_ok=True)+shutil.copytree(QT/'qml/QtTest',OUT/'qml/QtTest')+shutil.copytree(ROOT/'tests/qml/quick',OUT/'qml-tests')+env=os.environ.copy();env.update(TEMP=str(TMP),TMP=str(TMP),QML_DISABLE_DISK_CACHE='1',+ QT_FORCE_STDERR_LOGGING='1',QT_QPA_PLATFORM='offscreen',QT_QUICK_BACKEND='software',+ QT_QUICK_CONTROLS_STYLE='Basic',QT_QPA_PLATFORM_PLUGIN_PATH=str(QT/'plugins/platforms'),+ VEYRA_EXPORT_TEST_ARTIFACTS=str(OUT/'artifacts'),PATH=str(QT/'bin')+os.pathsep+env.get('PATH',''))+(OUT/'artifacts').mkdir()+with (LOG/'quick.log').open('xb') as log:+ try:rc=subprocess.run([str(OUT/'veyra_qml_quick_tests.exe'),'-input',str(OUT/'qml-tests')],cwd=OUT,env=env,+ stdout=log,stderr=subprocess.STDOUT,timeout=290).returncode+ except subprocess.TimeoutExpired:rc=124+(LOG/'result.json').write_text(json.dumps({'exit':rc,'staged':str(OUT),'log':str(LOG/'quick.log')},indent=2),encoding='utf8')+print((LOG/'quick.log').read_text(encoding='utf8',errors='replace')[-3500:])+raise SystemExit(rc)diff --git a/scripts/acceptance/nr-protection-smoke.py b/scripts/acceptance/nr-protection-smoke.pynew file mode 100644index 00000000..3d1354e1--- /dev/null+++ b/scripts/acceptance/nr-protection-smoke.py@@ -0,0 +1,22 @@+"""Verify inherited libass remains active in the actual local executable."""+from pathlib import Path+import hashlib,json,os,subprocess,sys+BASE=Path('E:/项目/Veyra');TASK='nr-strength-protection-20261005'+label=sys.argv[1];assert label.replace('-','').isalnum()+APP=Path(sys.argv[2]) if len(sys.argv)>2 else BASE/'test-packages'/TASK/'Veyra-2.0.3-nr-controls-NVIDIA-win64-portable'+assert APP.resolve().is_relative_to(BASE.resolve())+OUT=BASE/'tests'/TASK/('smoke-'+label);LOG=BASE/'logs'/TASK/('smoke-'+label);TMP=BASE/'tmp'/TASK/('smoke-'+label)+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=False)+media=BASE/'tests/field-fixes-20261005/media/fx-embedded.mkv';assert media.is_file()+env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_QUICK_BACKEND','QSG_RHI_BACKEND'))}+env.update(TEMP=str(TMP),TMP=str(TMP),VEYRA_LOG_FILE=str(LOG/'player.log'),QML_DISABLE_DISK_CACHE='1',QT_FORCE_STDERR_LOGGING='1')+args=[str(APP/'veyra_qml_ui.exe'),'--data-dir',str(OUT/'profile'),'--page','pro','--size','1280x800','--obs-game-capture','--exit-after','8000',str(media)]+with (LOG/'console.log').open('xb') as log:+ rc=subprocess.run(args,cwd=APP,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=60).returncode+text=(LOG/'player.log').read_text(encoding='utf8',errors='replace')+bad=[l for l in text.splitlines() if any(x in l for x in ('[ERROR]','[FATAL]','ReferenceError:','TypeError:','no root object'))]+ass=[l for l in text.splitlines() if '[libass]' in l]+assert rc==0 and not bad and any('track ready events=5' in l for l in ass) and any('fonts configured container=1' in l for l in ass),text[-4000:]+result={'exit':rc,'passed':True,'exeSha256':hashlib.sha256((APP/'veyra_qml_ui.exe').read_bytes()).hexdigest(),'libass':ass[:8]}+(LOG/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')+print('INHERITED LIBASS PASS',LOG)diff --git a/scripts/acceptance/nr-protection-tests.py b/scripts/acceptance/nr-protection-tests.pynew file mode 100644index 00000000..c03950e1--- /dev/null+++ b/scripts/acceptance/nr-protection-tests.py@@ -0,0 +1,41 @@+"""Bounded CPU/GPU regression; no competing load or pressure driver."""+from pathlib import Path+import json+import os+import subprocess+import sys++ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra');TASK='nr-strength-protection-20261005'+BUILD=BASE/'build'/TASK+label=sys.argv[1];assert label.replace('-', '').isalnum()+LOG=BASE/'logs'/TASK/label;OUT=BASE/'tests'/TASK/label;TMP=BASE/'tmp'/TASK/label+for p in (LOG,OUT,TMP):p.mkdir(parents=True,exist_ok=False)+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/nr-protection-control.py'),'guard'],check=True)+candidate=BASE/'test-packages/field-fixes-20261005/Veyra-2.0.3-field-20261005b-NVIDIA-win64-portable'+env=os.environ.copy();env.update(TEMP=str(TMP),TMP=str(TMP),PATH=str(candidate)+os.pathsep+env.get('PATH',''),+ VEYRA_LOG_FILE=str(LOG/'device.log'),QML_DISABLE_DISK_CACHE='1')+tests=[('preset-library', 'veyra_preset_library_tests', []),+ ('preset-legacy','veyra_repair_preset_tests',['presets/legacy-presets.v1']),+ ('effect-chain','veyra_effect_chain_tests',[]),+ ('nr-tiers','veyra_nr_antiflicker_tests',[]),+ ('hdr-contract','veyra_hdr_color_tests',[]),+ ('legacy-shader','veyra_repair_shader_tests',[]),+ ('temporal','veyra_nr_temporal_gpu_tests',[]),+ ('correction','veyra_nr_correction_gpu_tests',[+ str(BASE/'tests'/TASK/'baseline/NrResidualComposite.dxil'),str(OUT/'shader')]),+ ('correction-fp16','veyra_nr_correction_gpu_tests',[+ str(BASE/'tests'/TASK/'baseline/NrResidualComposite.dxil'),str(OUT/'shader-fp16'),'--fp16'])]+if len(sys.argv)>2:tests=[t for t in tests if t[0] in sys.argv[2:]]+results=[]+for name,exe,args in tests:+ destination=LOG/(name+'.log')+ with destination.open('xb') as log:+ try:rc=subprocess.run([str(BUILD/(exe+'.exe')),*args],cwd=OUT,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=290).returncode+ except subprocess.TimeoutExpired:rc=124+ output=destination.read_text(encoding='utf-8',errors='replace')+ results.append({'name':name,'exit':rc,'log':str(destination)})+ print(name,rc,'\n'+'\n'.join(output.splitlines()[-5:]),flush=True)+(LOG/'results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8')+subprocess.run([sys.executable,'-B',str(ROOT/'scripts/acceptance/nr-protection-control.py'),'guard'],check=True)+raise SystemExit(0 if all(r['exit']==0 for r in results) else 1)diff --git a/scripts/acceptance/nr-protection-ui.py b/scripts/acceptance/nr-protection-ui.pynew file mode 100644index 00000000..f072cb98--- /dev/null+++ b/scripts/acceptance/nr-protection-ui.py@@ -0,0 +1,53 @@+"""Real Qt bridge, preview, PNG, preset/session and NVENC validation, <300s/run."""+from pathlib import Path+import hashlib,json,os,subprocess,sys+ROOT=Path(__file__).resolve().parents[2]+BASE=Path('E:/项目/Veyra');TASK='nr-strength-protection-20261005'+APP=BASE/'test-packages'/TASK/'Veyra-2.0.3-nr-controls-NVIDIA-win64-portable'+mode=sys.argv[1];assert mode in ('first','restore','multi','visual')+label=sys.argv[2] if len(sys.argv)>2 else mode+assert label.replace('-','').isalnum()+OUT=BASE/'tests'/TASK/('production-'+label);LOG=BASE/'logs'/TASK/('production-'+label);TMP=BASE/'tmp'/TASK/('production-'+label)+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=False)+(OUT/'screenshots').mkdir();(OUT/'outputs').mkdir()+media=BASE/'tests'/TASK/'nr-fixture.avi'+if mode=='visual':+ media=Path(sys.argv[3]);assert media.is_file() and media.resolve().is_relative_to(BASE.resolve())+env=os.environ.copy();env.update(TEMP=str(TMP),TMP=str(TMP),VEYRA_LOG_FILE=str(LOG/'veyra.log'),QT_FORCE_STDERR_LOGGING='1',QML_DISABLE_DISK_CACHE='1')+for key in ('QT_QPA_PLATFORM','QT_QUICK_BACKEND','VEYRA_UI_RHI','VEYRA_TEST_IGNORE_RTSS'):env.pop(key,None)+if mode=='first' and not media.exists():+ with (LOG/'fixture.log').open('xb') as log:+ subprocess.run(['ffmpeg','-v','warning','-n','-f','lavfi','-i','testsrc2=size=1280x720:rate=30','-t','2','-c:v','mpeg4','-q:v','3','-threads','2',str(media)],env=env,stdout=log,stderr=subprocess.STDOUT,timeout=60,check=True)+receipt=BASE/'logs'/TASK/'production-profile.json'+if mode=='first':+ profile=OUT/'profile'+ receipt.write_text(json.dumps({'profile':str(profile)}),encoding='utf8')+elif mode=='restore':profile=Path(json.loads(receipt.read_text(encoding='utf8'))['profile'])+else:profile=OUT/'profile'+main=APP/'qml/Veyra/Main.qml';original=main.read_bytes();source=original.decode('utf8')+loader='\nLoader { anchors.fill: parent; source: '+json.dumps((ROOT/'scripts/acceptance/nr-protection-ui.qml').as_uri())+'; onLoaded: { item.media='+json.dumps(str(media))+'; item.evidence='+json.dumps(str(OUT))+'; item.resume='+str(mode=='restore').lower()+'; item.multi='+str(mode=='multi').lower()+'; item.visual='+str(mode=='visual').lower()+' } }\n'+args=[str(APP/'veyra_qml_ui.exe'),'--page','pro','--size','1280x900','--reduced-motion','--obs-game-capture','--export-out',str(OUT/'outputs'),'--data-dir',str(profile),'--exit-after','250000']+try:+ at=source.rfind('}');main.write_text(source[:at]+loader+source[at:],encoding='utf8')+ with (LOG/'console.log').open('xb') as log:+ rc=subprocess.run(args,cwd=APP,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=270).returncode+finally:main.write_bytes(original)+assert hashlib.sha256(main.read_bytes()).digest()==hashlib.sha256(original).digest()+console=(LOG/'console.log').read_text(encoding='utf8',errors='replace')+expected={'first':'NR_CONTROLS_UI_PASS','restore':'NR_CONTROLS_RESTORE_PASS','multi':'NR_CONTROLS_MULTI_PASS','visual':'NR_CONTROLS_VISUAL_PASS'}[mode]+assert rc==0 and expected in console and 'NR_CONTROLS_UI_FAIL' not in console,console[-6000:]+if mode=='first':+ parent=(LOG/'veyra.log').read_text(encoding='utf8',errors='replace')+ assert 'mode=auto' in parent and 'mode=manual' in parent and 'gain=5' in parent+ assert len(list((OUT/'screenshots').glob('*.png')))>=4+ outputs=list((OUT/'outputs').glob('*.mp4'));assert len(outputs)==1,outputs+ probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-count_frames','-show_streams','-of','json',str(outputs[0])],env=env,timeout=30))+ stream=next(s for s in probe['streams'] if s['codec_type']=='video')+ assert stream['codec_name']=='hevc' and int(stream['nb_read_frames'])==60+ assert (int(stream['width']),int(stream['height']))==(3840,2160)+ (LOG/'export-probe.json').write_text(json.dumps(probe,indent=2),encoding='utf8')+elif mode=='multi':+ parent=(LOG/'veyra.log').read_text(encoding='utf8',errors='replace')+ assert 'build layer=1 gain=5 mode=auto' in parent and 'build layer=2 gain=5 mode=manual' in parent+ assert len(list((OUT/'screenshots').glob('*.png')))==1+print('NR production',mode,'PASS',OUT)diff --git a/scripts/acceptance/nr-protection-ui.qml b/scripts/acceptance/nr-protection-ui.qmlnew file mode 100644index 00000000..96217f12--- /dev/null+++ b/scripts/acceptance/nr-protection-ui.qml@@ -0,0 +1,174 @@+// Loaded only into the task's candidate copy while exercising the real bridge.+import QtQuick+import Veyra+Item {+ id: test+ property string media: ""+ property string evidence: ""+ property bool resume: false+ property bool multi: false+ property bool visual: false+ property var appWindow: Window.window+ property int step: 0+ property int ticks: 0+ property int entered: 0+ property int savedIndex: -1+ width: appWindow ? appWindow.width : 1280+ height: appWindow ? appWindow.height : 720+ function find(item,name){+ if(item.objectName===name)return item+ for(const child of item.children||[]){const hit=find(child,name);if(hit)return hit}+ return null+ }+ function require(ok,why){+ if(!ok){console.error("NR_CONTROLS_UI_FAIL",step,why);timer.stop();Qt.quit();throw new Error(why)}+ }+ function next(n){step=n;entered=ticks}+ function elapsed(n){return ticks-entered>=n}+ function edit(key,value){require(veyra.setNrLayerParameter(veyra.nrLayers[0].index,key,value),"edit rejected: "+key)}+ function capture(label){+ console.log("NR_CONTROLS_STATE",label,JSON.stringify(veyra.nrLayers),JSON.stringify(veyra.stageTimings),veyra.statusText)+ veyra.logUi("nr-controls-test",label+" "+JSON.stringify(veyra.nrLayers))+ veyra.takeScreenshot()+ }+ NrLayerEditor {+ id: controls+ anchors.right: parent.right;anchors.top: parent.top;anchors.margins: 10+ width: 360;listControls: false+ layerData: veyra.nrLayers.length ? veyra.nrLayers[0] : ({index:0,runtime:0,intensity:1,tone:1,structure:1,skin:-1,style:0,autoMask:0,uiCorrection:0,total:1,darken:1,brighten:1,color:1,luminance:1,temporal:false,antiFlicker:2,sizePolicy:0})+ layerCount: veyra.nrLayers.length+ onEdited: (index,key,amount) => test.require(veyra.setNrLayerParameter(index,key,amount),"control rejected: "+key)+ }+ Connections {+ target: veyra+ function onNotice(message,error){console.log("NR_CONTROLS_NOTICE",message,error)}+ }+ Timer {+ id: timer;interval: 100;repeat: true;running: true+ onTriggered: {+ if(++test.ticks>2400){test.require(false,"240s deadline");return}+ if(!test.media.length||test.ticks<12)return+ if(test.multi){+ if(test.step===0){+ veyra.nodeMode=0;veyra.nrEnabled=true;veyra.srEnabled=false;veyra.fgEnabled=false+ test.edit("total",5);test.edit("correctionEnabled",1)+ test.require(veyra.duplicateNrLayer(veyra.nrLayers[0].index)>=0,"two-layer creation failed")+ const second=veyra.nrLayers[1].index+ test.require(veyra.setNrLayerParameter(second,"correctionAuto",0),"second manual mode rejected")+ test.require(veyra.setNrLayerParameter(second,"temporalStability",.5),"second stability rejected")+ test.require(veyra.setProtectionRegion(.1,.1,.3,.3,0),"stack protection region rejected")+ veyra.protectionEnabled=true+ test.require(veyra.setPreference("screenshotDir",test.evidence+"/screenshots"),"multi screenshot directory rejected")+ veyra.openPath(test.media);test.next(1)+ }else if(test.step===1){+ test.require(!veyra.failed,"two-layer preview failed: "+veyra.statusText)+ if(!veyra.nrActive||veyra.position<.8)return+ if(!veyra.paused)veyra.togglePlayPause()+ test.next(2)+ }else if(test.step===2){+ if(!test.elapsed(20))return+ test.require(veyra.nrLayers.length===2&&veyra.nrActive&&!veyra.failed,"two-layer graph not active")+ test.capture("two-controlled-layers-with-protection")+ console.log("NR_CONTROLS_MULTI_PASS")+ timer.stop();Qt.quit()+ }+ return+ }+ if(test.resume){+ if(test.step===0){+ test.require(veyra.nodeMode===0&&veyra.nrLayers.length===1,"list session not restored")+ const n=veyra.nrLayers[0]+ test.require(n.total===5&&n.correctionEnabled&&!n.correctionAuto&&Math.abs(n.hueProtection-.4)<1e-5&&Math.abs(n.chromaProtection-.3)<1e-5,"manual session values not restored")+ veyra.nodeMode=1;test.next(1)+ }else if(test.step===1){+ if(!test.elapsed(8))return+ const n=veyra.nrLayers[0]+ test.require(n&&n.total===5&&n.correctionEnabled&&!n.correctionAuto&&Math.abs(n.hueProtection-.42)<1e-5,"node session values not restored")+ veyra.nodeMode=0+ console.log("NR_CONTROLS_RESTORE_PASS")+ timer.stop();Qt.quit()+ }+ return+ }+ if(test.step===0){+ veyra.nodeMode=0;veyra.nrEnabled=true;veyra.srEnabled=false;veyra.fgEnabled=false+ if(!veyra.nrLayers.length)veyra.addEffect("nr")+ test.require(veyra.nrLayers.length===1,"expected isolated default NR layer")+ test.require(!veyra.nrLayers[0].correctionEnabled,"new profile correction must default off")+ test.require(veyra.setPreference("screenshotDir",test.evidence+"/screenshots"),"task screenshot directory rejected")+ const residual=test.find(controls,"nr-residual-group"),group=test.find(controls,"nr-correction-group")+ test.require(residual&&group,"new shared NR groups missing")+ residual.expanded=true;group.expanded=true+ test.require(test.find(controls,"nr-total").to===5,"strength slider ceiling is not five")+ test.find(controls,"nr-total").moved(5)+ test.require(veyra.nrLayers[0].total===5,"slider five did not reach settings")+ veyra.openPath(test.media);test.next(1)+ }else if(test.step===1){+ test.require(!veyra.failed,"real preview failed: "+veyra.statusText)+ if(!veyra.nrActive||veyra.position<.8)return+ if(!veyra.paused)veyra.togglePlayPause()+ test.next(2)+ }else if(test.step===2){+ if(!test.elapsed(20)||!veyra.paused)return+ test.capture("raw-five")+ test.find(controls,"nr-correctionEnabled").toggled(true)+ test.require(veyra.nrLayers[0].correctionEnabled&&veyra.nrLayers[0].correctionAuto,"auto switch not applied")+ test.next(3)+ }else if(test.step===3){+ if(!test.elapsed(45))return+ test.require(!veyra.failed&&veyra.nrActive,"controlled paused preview failed")+ test.capture("auto-five")+ test.find(controls,"nr-correctionAuto").picked("0")+ test.find(controls,"nr-hueProtection").moved(.4)+ test.find(controls,"nr-chromaProtection").moved(.3)+ test.find(controls,"nr-highlightProtection").moved(.9)+ test.find(controls,"nr-localCompression").moved(.7)+ test.find(controls,"nr-temporalStability").moved(.8)+ test.next(4)+ }else if(test.step===4){+ if(!test.elapsed(30))return+ const n=veyra.nrLayers[0]+ test.require(!n.correctionAuto&&n.total===5&&Math.abs(n.hueProtection-.4)<1e-5,"manual slider values not applied")+ test.capture("manual-five")+ test.require(veyra.savePresetAs("NR correction manual five",1,false),"production preset save failed")+ const saved=veyra.presetChoices.find(p=>p.label==="NR correction manual five")+ test.savedIndex=saved ? Number(saved.id) : -1+ test.require(test.savedIndex>=0,"saved preset missing from choices")+ test.find(controls,"nr-correctionEnabled").toggled(false)+ test.require(veyra.nrLayers[0].total===5&&!veyra.nrLayers[0].correctionEnabled&&Math.abs(veyra.nrLayers[0].hueProtection-.4)<1e-5,"off must preserve gain/manual values")+ test.next(5)+ }else if(test.step===5){+ if(!test.elapsed(30))return+ test.capture("raw-five-restored")+ if(test.visual){console.log("NR_CONTROLS_VISUAL_PASS");timer.stop();Qt.quit();return}+ const index=veyra.nrLayers[0].index+ test.require(veyra.resetNrLayer(index),"NR reset failed")+ test.require(veyra.nrLayers[0].total===1&&!veyra.nrLayers[0].correctionEnabled,"NR reset defaults wrong")+ test.require(veyra.applyPresetIndex(test.savedIndex),"NR preset apply failed")+ test.require(veyra.nrLayers[0].total===5&&veyra.nrLayers[0].correctionEnabled&&!veyra.nrLayers[0].correctionAuto,"preset did not restore mode and gain")+ const duplicate=veyra.duplicateNrLayer(veyra.nrLayers[0].index)+ test.require(duplicate>=0&&veyra.nrLayers.length===2&&Math.abs(veyra.nrLayers[1].hueProtection-.4)<1e-5&&veyra.nrLayers[1].total===5,"duplicate lost correction values")+ test.require(veyra.removeEffect(duplicate),"duplicate cleanup failed")+ veyra.nodeMode=1+ if(!veyra.nrLayers.length)veyra.addEffect("nr")+ test.edit("total",5);test.edit("correctionEnabled",1);test.edit("correctionAuto",0);test.edit("hueProtection",.42)+ test.require(veyra.nrLayers[0].total===5&&Math.abs(veyra.nrLayers[0].hueProtection-.42)<1e-5,"node parameter editing failed")+ veyra.nodeMode=0;test.next(6)+ }else if(test.step===6){+ if(!test.elapsed(25))return+ veyra.exportCompletionSound=false;veyra.exportSrTargetIndex=2;veyra.exportHevc=true+ veyra.exportRateControl=1;veyra.exportBitrateMbps=12+ veyra.addExportFiles([test.media]);test.next(7)+ }else if(test.step===7){+ if(veyra.exportReadyCount!==1)return+ veyra.startExport();test.require(veyra.exportRunning,"real NR export not started");test.next(8)+ }else if(test.step===8){+ if(veyra.exportRunning)return+ test.require(veyra.exportItems.some(i=>i.state==="done"),"real NR export failed")+ veyra.stopPlayback()+ console.log("NR_CONTROLS_UI_PASS",JSON.stringify(veyra.nrLayers),JSON.stringify(veyra.exportItems))+ timer.stop();Qt.quit()+ }+ }+ }+}diff --git a/shaders/NrCorrection.hlsli b/shaders/NrCorrection.hlslinew file mode 100644index 00000000..213ab5be--- /dev/null+++ b/shaders/NrCorrection.hlsli@@ -0,0 +1,110 @@+// Adapted from SAOG0721/Magpie, GPL-3.0, commit+// 27c5df91177a29b33be612e98274169f3d2fca49:+// src/Magpie.Core/DLSSNRColorShader.h and DLSSNRDetailShader.h.+// Oklab matrices: Bjorn Ottosson, public domain (2021-01-25),+// https://bottosson.github.io/posts/oklab/ .+// Veyra: already-linear FP16 input (no SDR decode/encode), optional controls,+// chroma-delta budget, soft highlight shoulder, 16-step gamut ray search,+// signed scRGB/BT.2020 HDR boundary, and post-temporal safety without a second+// application of residual compression. No per-frame exposure adaptation.+#ifndef VEYRA_NR_CORRECTION+#define VEYRA_NR_CORRECTION+float3 NrLinearToLab(float3 c){+ float3 lms=float3(dot(c,float3(.4122214708,.5363325363,.0514459929)),+ dot(c,float3(.2119034982,.6806995451,.1073969566)),+ dot(c,float3(.0883024619,.2817188376,.6299787005)));+ lms=sign(lms)*pow(abs(lms),1.0/3.0);+ return float3(dot(lms,float3(.2104542553,.7936177850,-.0040720468)),+ dot(lms,float3(1.9779984951,-2.4285922050,.4505937099)),+ dot(lms,float3(.0259040371,.7827717662,-.8086757660)));+}+float3 NrLabToLinear(float3 c){+ float3 v=float3(c.x+.3963377774*c.y+.2158037573*c.z,+ c.x-.1055613458*c.y-.0638541728*c.z,+ c.x-.0894841775*c.y-1.2914855480*c.z);+ v=v*v*v;+ return float3(dot(v,float3(4.0767416621,-3.3077115913,.2309699292)),+ dot(v,float3(-1.2684380046,2.6097574011,-.3413193965)),+ dot(v,float3(-.0041960863,-.7034186147,1.7076147010)));+}+float3 NrTo2020(float3 c){+ return mul(float3x3(.627404,.329283,.043313,.069097,.919540,.011362,.016391,.088013,.895595),c);+}+float3 NrTo709(float3 c){+ return mul(float3x3(1.660491,-.587641,-.072850,-.124550,1.132900,-.008349,-.018151,-.100579,1.118730),c);+}+float NrMaximum(float3 c){return max(c.r,max(c.g,c.b));}+float NrUnit(bool hdr){return hdr?203.0/80.0:1.0;}+float NrCeiling(float3 base,bool hdr){+ // Preserve source HDR peaks; enhancement does not invent a higher peak.+ // The 203-nit floor allows useful midtone detail while 125 scRGB units+ // remain the explicit 10,000-nit PQ boundary. Signed BT.709 is retained.+ return hdr?min(125.0,max(203.0/80.0,NrMaximum(NrTo2020(base))))/(203.0/80.0):1.0;+}+bool NrInGamut(float3 rgb,float ceiling,bool hdr){+ float3 c=hdr?NrTo2020(rgb):rgb;+ float tolerance=1e-6*max(1,ceiling);+ return all(c>=-tolerance)&&all(c<=ceiling+tolerance);+}+float3 NrMapLab(float3 lab,float ceiling,bool hdr){+ lab.x=clamp(lab.x,0,pow(ceiling,1.0/3.0));+ float3 rgb=NrLabToLinear(lab);+ if(!NrInGamut(rgb,ceiling,hdr)){+ float lo=0,hi=1;+ [loop]for(int k=0;k<16;++k){+ float mid=(lo+hi)*.5;+ if(NrInGamut(NrLabToLinear(float3(lab.x,lab.yz*mid)),ceiling,hdr))lo=mid;else hi=mid;+ }+ rgb=NrLabToLinear(float3(lab.x,lab.yz*lo));+ }+ // Only roundoff remains here; clipping before the ray search would rotate hue.+ return hdr?NrTo709(clamp(NrTo2020(rgb),0,ceiling)):clamp(rgb,0,ceiling);+}+float NrSoftScale(float magnitude,float knee,float span){+ if(magnitude<=knee)return 1;+ float excess=magnitude-knee;+ return (knee+excess/(1+excess/span))/max(magnitude,1e-12);+}+float NrHighlightShoulder(float target,float original,float limit){+ float start=clamp(original,0,limit);+ float room=max(limit-start,0);+ float knee=start+room*.5;+ if(target<=knee)return target;+ float span=room*.5;+ return span>1e-7?knee+span*(1-exp(-(target-knee)/span)):start;+}+float3 NrApplyCorrection(float3 original,float3 candidate,bool hdr,+ float hue,float chroma,float highlight,float compression){+ if(hue+chroma+highlight+compression==0||all(original==candidate))return candidate;+ if(!all(isfinite(candidate)))return original;+ float unit=NrUnit(hdr),ceiling=NrCeiling(original,hdr);+ float3 o=NrLinearToLab(original/unit),d=NrLinearToLab(candidate/unit)-o;+ float c=length(o.yz);+ if(hue>0){+ // Original hue has no definition on the gray axis. Smoothly fade out+ // there; projection cannot overshoot through gray into the opposite hue.+ float weight=hue*smoothstep(0,.02,c);+ float2 n=o.yz/max(c,1e-12),target=o.yz+d.yz;+ d.yz=lerp(target,n*max(dot(target,n),0),weight)-o.yz;+ }+ if(chroma>0){+ float magnitude=length(d.yz);+ d.yz*=lerp(1,NrSoftScale(magnitude,.008+.12*c,.02+.15*c),chroma);+ }+ if(compression>0)d*=lerp(1,NrSoftScale(length(d),.04,.12),compression);+ if(highlight>0){+ float target=o.x+d.x;+ // Darkening can recover highlight detail: only outward lightness+ // gets the shoulder. Classification always uses the original base.+ if(d.x>0)d.x=lerp(target,NrHighlightShoulder(target,o.x,pow(ceiling,1.0/3.0)),highlight)-o.x;+ }+ return NrMapLab(o+d,ceiling,hdr)*unit;+}+float3 NrTemporalSafety(float3 base,float3 candidate,bool hdr,bool spatial){+ if(!spatial||all(candidate==base))return candidate;+ if(!all(isfinite(candidate)))return base;+ float unit=NrUnit(hdr),ceiling=NrCeiling(base,hdr);+ if(NrInGamut(candidate/unit,ceiling,hdr))return candidate;+ return NrMapLab(NrLinearToLab(candidate/unit),ceiling,hdr)*unit;+}+#endifdiff --git a/shaders/NrResidualComposite.hlsl b/shaders/NrResidualComposite.hlslindex 68d7ca08..97dc4f3c 100644--- a/shaders/NrResidualComposite.hlsl+++ b/shaders/NrResidualComposite.hlsl@@ -1,9 +1,14 @@#include "NrProtection.hlsli"+#include "NrCorrection.hlsli"Texture2D<float4> baseTex:register(t0);Texture2D<float4> nrInput:register(t1);Texture2D<float4> nrFinal:register(t2);RWTexture2D<float4> outputTex:register(u0);-cbuffer Params:register(b0){float total;float darken;float brighten;float color;float luminance;float protectionEnabled;float featherPixels;float unused;float4 regions[4];}+cbuffer Params:register(b0){+ float total;float darken;float brighten;float color;float luminance;float protectionEnabled;float featherPixels;float unused;float4 regions[4];+ float correctionEnabled;float hueProtection;float chromaProtection;float highlightProtection;+ float localCompression;float temporalStability;float correctionAutomatic;float correctionPad;+}// Extrapolating a negative linear-light residual can cross zero even when// both input images contain shadow detail. Continue below the unboosted// endpoint with a positive, tangent-matched curve instead of hard clipping.@@ -41,5 +46,7 @@ float shadowSafe(float base,float rawDelta,float requestedDelta){float3 result=float3(shadowSafe(base.r,rawDelta.r,delta.r),shadowSafe(base.g,rawDelta.g,delta.g),shadowSafe(base.b,rawDelta.b,delta.b));+ if(correctionEnabled>0.5)+ result=NrApplyCorrection(base.rgb,result,unused>0.5,hueProtection,chromaProtection,highlightProtection,localCompression);outputTex[id.xy]=float4(unused>0.5?result:max(0,result),base.a);}diff --git a/shaders/NrTemporal.hlsl b/shaders/NrTemporal.hlslindex af88f179..c2397923 100644--- a/shaders/NrTemporal.hlsl+++ b/shaders/NrTemporal.hlsl@@ -16,6 +16,7 @@// Route 2 is byte-for-byte the behaviour that existed before the tiers, so a// preset that only ever knew "temporal on" keeps producing what it produced.#include "NrProtection.hlsli"+#include "NrCorrection.hlsli"Texture2D<float4> Base:register(t0);Texture2D<float4> Raw:register(t1);Texture2D<float4> History:register(t2);@@ -29,6 +30,8 @@ RWTexture2D<float4> NextGuide:register(u2);cbuffer Settings:register(b0){uint2 Size;float HistoryWeight;float Total;float ProtectionEnabled;float Feather;float2 reserved;float4 Regions[4];uint Route;float2 LowSize;float RoutePad;+ float CorrectionEnabled;float HueProtection;float ChromaProtection;float HighlightProtection;+ float LocalCompression;float TemporalStability;float CorrectionAutomatic;float CorrectionHdr;}float GuideChannel(float c){// The matching tolerance must distinguish visible changes in shadows,@@ -142,6 +145,9 @@ groupshared float TileError[100];float4 base=Base[p],raw=Raw[p];bool finite=all(isfinite(base))&&all(isfinite(raw));NextGuide[p]=all(isfinite(base))?float4(Guide(base.rgb),1):0;if(!finite){NextHistory[p]=0;Output[p]=all(isfinite(base))?base:float4(0,0,0,1);return;}+ // Optional control must not keep an old correction after the current NR+ // produces an exact identity. The original temporal path stays unchanged.+ if(CorrectionEnabled>0.5&&all(raw.rgb==base.rgb)){NextHistory[p]=0;Output[p]=raw;return;}// Route 4 splits the observation: the accumulated signal is the// low-frequency component and `detail` carries this frame's exact// high-frequency complement through untouched.@@ -230,9 +236,14 @@ groupshared float TileError[100];// correction; otherwise the next frame reuses the same invalid shadow.// Route 3 stores 1+support in alpha: the support channel rides along with// the observation rather than in a separate texture.- NextHistory[p]=float4(clamp(resolved-base.rgb,-65504,65504),Route==3?1+support:1);// Route 4 restores this frame's high frequency after the temporal filter.float3 composited=resolved+detail;+ if(CorrectionEnabled>0.5){+ composited=NrTemporalSafety(base.rgb,composited,CorrectionHdr>0.5,+ HueProtection+ChromaProtection+HighlightProtection+LocalCompression>0);+ resolved=composited-detail;+ }+ NextHistory[p]=float4(clamp(resolved-base.rgb,-65504,65504),Route==3?1+support:1);// Preserve signed wide-gamut/HDR working components (no SDR saturate).Output[p]=float4(clamp(composited,-65504,65504),raw.a);}diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cppindex 1fef637f..5f4e19b0 100644--- a/src/engine/PresetLibrary.cpp+++ b/src/engine/PresetLibrary.cpp@@ -1,4 +1,5 @@#include "veyra/engine/PresetLibrary.h"+#include "veyra/engine/NrCorrectionCodec.h"#include <windows.h>@@ -582,7 +583,10 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entriesreturn c.fgBackend==FrameGenerationBackend::Vfg||c.vfgQuality!=1||(c.editor&&c.editor->globals&&(c.editor->globals->fgBackend==FrameGenerationBackend::Vfg||c.editor->globals->vfgQuality!=1));});- const int version=std::max(minimumVersion, vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);+ const bool correction=std::any_of(entries_.begin(),entries_.end(),[](const auto& e){+ for(unsigned i=0;i<e.chain.nodeCount;++i)if(e.chain.nodes[i].nr.residual.extendedSchema())return true;+ return false;});+ const int version=std::max(minimumVersion, correction?8:vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);o << "VEYRA_PRESET_LIBRARY " << version << '\n' << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';for (const auto& e : entries_) {o << std::quoted(utf8(e.name)) << ' ' << std::quoted(utf8(e.note)) << ' '@@ -607,6 +611,7 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entrieso << ' ' << (n.videoHdr.enabled ? 1 : 0) << ' ' << n.videoHdr.contrast << ' ' << n.videoHdr.saturation << ' '<< n.videoHdr.middleGray << ' ' << n.videoHdr.peakNits << ' ';if(version>=3)o<<int(n.nr.sizePolicy)<<' ';+ if(version>=8){writeNrCorrection(o,n.nr.residual.correction);o<<' ';}if (version>=2 && n.type == EffectType::Color) {writeColorSettings(o, n.color, utf8(n.color.lutNameString()));o << ' ';@@ -641,7 +646,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& outstd::string magic, quoted;int version = 0;size_t count = 0;- if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > 7) { error = L"预设库格式或版本不支持"; return false; }+ if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > 8) { error = L"预设库格式或版本不支持"; return false; }if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }def = wide(quoted);for (size_t i = 0; i < count; ++i) {@@ -697,6 +702,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& outif(!(in>>size)||!pipeline::validNrSizePolicy(static_cast<pipeline::NrSizePolicy>(size))){error=L"预设库 NR 分辨率非法";return false;}node.nr.sizePolicy=static_cast<pipeline::NrSizePolicy>(size);}+ if(version>=8&&!readNrCorrection(in,node.nr.residual.correction)){error=L"预设库 NR 调控参数损坏";return false;}if (version >= 2 && node.type == EffectType::Color) {std::string lut;if (!readColorSettings(in, node.color, lut, 19) ||diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cppindex 145e47d5..9e8b364e 100644--- a/src/engine/PresetStore.cpp+++ b/src/engine/PresetStore.cpp@@ -1,4 +1,5 @@#include "veyra/engine/PresetStore.h"+#include "veyra/engine/NrCorrectionCodec.h"#include <windows.h>#include <fstream>#include <sstream>@@ -35,9 +36,13 @@ std::string PresetStore::serialize()const{const bool higher=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.srTarget>pipeline::SrTarget::Uhd8K;});const bool rendering=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){const auto& s=p.settings;return s.hdrOutputMode!=HdrOutputMode::Hdr10||s.fgMotion!=MotionSource::Automatic||s.srMotion!=MotionSource::OpticalFlow||s.nrMotion!=MotionSource::OpticalFlow;});const bool vfg=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){return p.settings.frameGenerationBackend==FrameGenerationBackend::Vfg||p.settings.vfgQuality!=1;});- const bool fullSchema=fsr4||higher||rendering||vfg;+ const bool correction=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){+ if(p.settings.residual.extendedSchema())return true;+ for(unsigned i=0;i<p.settings.nrLayerCount;++i)if(p.settings.nrLayers[i].residual.extendedSchema())return true;+ return false;});+ const bool fullSchema=fsr4||higher||rendering||vfg||correction;// v26 introduces appended resolution IDs; old readers reject this schema.- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS "<<(vfg?28:rendering?27:higher?26:fsr4?25:hold?24:stack?23:multi?22:21)<<'\n'<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS "<<(correction?29:vfg?28:rendering?27:higher?26:fsr4?25:hold?24:stack?23:multi?22:21)<<'\n'<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<' '<<int(s.captureAudio)<<' '<<s.exportBitrateMbps<<' '<<s.captureFlipVertical<<' '<<int(s.captureBuffer)<<' ';writeColorSettings(o,s.color,utf8(s.color.lutNameString()));o<<' '<<s.videoHdr.enabled<<' '<<s.videoHdr.contrast<<' '<<s.videoHdr.saturation<<' '<<s.videoHdr.middleGray<<' '<<s.videoHdr.peakNits<<' '<<s.nrTemporal;if(multi||fullSchema){o<<' '<<s.additionalColorCount;for(unsigned i=0;i<s.additionalColorCount;++i){o<<' ';writeColorSettings(o,s.additionalColors[i],utf8(s.additionalColors[i].lutNameString()));}}if(stack||fullSchema){@@ -56,14 +61,18 @@ std::string PresetStore::serialize()const{// any entry needs it. Otherwise entries in the same file would parse// differently.if(hold||fullSchema)o<<' '<<s.nrHoldStrength<<' '<<s.nrHoldTolerance;- if(rendering||vfg)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);- if(vfg)o<<' '<<s.vfgQuality;+ if(rendering||vfg||correction)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);+ if(vfg||correction)o<<' '<<s.vfgQuality;+ if(correction){+ o<<' ';writeNrCorrection(o,s.residual.correction);+ for(unsigned i=0;i<s.nrLayerCount;++i){o<<' ';writeNrCorrection(o,s.nrLayers[i].residual.correction);}+ }o<<'\n';}return o.str();}bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){if(data.size()>kMaxPresetBytes)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>28)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>29)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;@@ -125,6 +134,10 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std}if(version>=27){int hdr,fg,sr,nr;if(!(in>>hdr>>fg>>sr>>nr))return false;s.hdrOutputMode=HdrOutputMode(hdr);s.fgMotion=MotionSource(fg);s.srMotion=MotionSource(sr);s.nrMotion=MotionSource(nr);}if(version>=28&&!(in>>s.vfgQuality))return false;+ if(version>=29){+ if(!readNrCorrection(in,s.residual.correction))return false;+ for(unsigned j=0;j<s.nrLayerCount;++j)if(!readNrCorrection(in,s.nrLayers[j].residual.correction))return false;+ }p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);if(!s.validate().empty())return false;out.push_back(std::move(p));diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex ee517c1d..7fe87aca 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -1258,6 +1258,10 @@ bool EnhanceGraph::initNgxFeatures()instance->residualSettings = index < desc_.nrLayersResidual.size() ? desc_.nrLayersResidual[index] : desc_.residual;instance->protection = index < desc_.nrLayersProtection.size() ? desc_.nrLayersProtection[index] : desc_.protection;instance->temporalEnabled = index < desc_.nrLayersTemporal.size() ? desc_.nrLayersTemporal[index] : desc_.nrTemporal;+ const auto& correction=instance->residualSettings.correction;+ veyra::log::info("nr-correction",std::format("build layer={} gain={} mode={} temporal={} hdr={} manual={}/{}/{}/{}/{}",+ index+1,instance->residualSettings.total,correction.enabled?(correction.automatic?"auto":"manual"):"off",+ instance->temporalEnabled,desc_.hdrWorking(),correction.hue,correction.chroma,correction.highlight,correction.compression,correction.stability));if(lmxxfNr_){failedBackend_=engine::FailedBackend::Nr;// The upstream ABI owns encode/network/decode; feed the stable@@ -1492,10 +1496,10 @@ bool EnhanceGraph::createComputePasses(){const UINT residualLayers=UINT(std::max<size_t>(1,nrInstances_.size()));if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||- !residualPass_.create(context_.device(),cs,4*residualLayers,3*residualLayers,residualLayers,24))return false;+ !residualPass_.create(context_.device(),cs,4*residualLayers,3*residualLayers,residualLayers,32))return false;// The existing residual shader can mask the complete stack against its// original base. No extra texture: the final layer owns outputFull().- if(nrInstances_.size()>1&&!stackProtectionPass_.create(context_.device(),cs,4,3,1,24))return false;+ if(nrInstances_.size()>1&&!stackProtectionPass_.create(context_.device(),cs,4,3,1,32))return false;}if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3+UINT(nrInstances_.size()),1,1))return false;// Stage-5 output stabiliser. Only allocated when the setting is non-zero:@@ -2474,15 +2478,17 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// last layer's delta. Keep unmasked per-layer histories in a stack.const auto protection=nrInstances_.size()>1?engine::ProtectionSettings{}:layer->protection;tracker_.transition(list,destination,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- float c[24]={r.total,r.darken,r.brighten,r.color,r.luminance,protection.enabled?1.0f:0.0f,protection.featherPixels,desc_.hdrWorking()?1.0f:0.0f};+ float c[32]={r.total,r.darken,r.brighten,r.color,r.luminance,protection.enabled?1.0f:0.0f,protection.featherPixels,desc_.hdrWorking()?1.0f:0.0f};for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}+ const auto controls=r.correction.constants(desc_.hdrWorking());+ std::copy(controls.begin(),controls.end(),c+24);const UINT residualLayers=UINT(std::max<size_t>(1,nrInstances_.size()));residualPass_.bind(list,c,gpuHandleOf(residualPass_,3u*UINT(layerIndex)).ptr,gpuHandleOf(residualPass_,3u*residualLayers+UINT(layerIndex)).ptr);list->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);+ if(temporallyStabilised)layer->temporal().run(list,tracker_,reset,haveFlow,ptsMs-prevPtsMs_,r.total,protection,r.correction,desc_.hdrWorking());};// 4. NR layers, in order. Each layer encodes its input to the 8-bit parity@@ -2514,7 +2520,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list,output,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);// The original and upstream stack share this boundary's// extent. Later NR layers consume the masked result.- float c[24]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};+ float c[32]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(desc_.protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}stackProtectionPass_.bind(list,c,gpuHandleOf(stackProtectionPass_,0).ptr,gpuHandleOf(stackProtectionPass_,3).ptr);list->Dispatch((extent.width+15)/16,(extent.height+15)/16,1);@@ -2704,7 +2710,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// Each layer already applies its own SDR/HDR residual policy.// This final exclusion mask must preserve the stack's signed// temporal output, including pixels outside protected regions.- float c[24]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};+ float c[32]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(desc_.protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}stackProtectionPass_.bind(list,c,gpuHandleOf(stackProtectionPass_,0).ptr,gpuHandleOf(stackProtectionPass_,3).ptr);list->Dispatch(((desc_.nrBeforeSr?srcW_:workW_)+15)/16,((desc_.nrBeforeSr?srcH_:workH_)+15)/16,1);@@ -3026,12 +3032,15 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){(s.protection.enabled&&!desc_.protectionBeforeSr()&&!interNrProtectionRgba_)))return false;auto nextNr=desc_;engine::describeNrLayers(s,nextNr);if(!desc_.nrLayersSizePolicy.empty()&&nextNr.nrLayersSizePolicy!=desc_.nrLayersSizePolicy)return false;- if(s.nrTemporal!=desc_.nrTemporal)return false;+ if(nextNr.nrTemporal!=desc_.nrTemporal||nextNr.nrAntiFlicker!=desc_.nrAntiFlicker)return false;if(s.nr&&desc_.enableNr){if(s.activeNrLayerCount()!=nrInstances_.size())return false;for(size_t i=0;i<nrInstances_.size();++i){- const bool temporal=i<nextNr.nrLayersTemporal.size()?nextNr.nrLayersTemporal[i]:s.nrTemporal;+ const bool temporal=i<nextNr.nrLayersTemporal.size()?nextNr.nrLayersTemporal[i]:nextNr.nrTemporal;if(temporal!=nrInstances_[i]->temporalEnabled)return false;+ const auto tier=i<nextNr.nrLayersAntiFlicker.size()?nextNr.nrLayersAntiFlicker[i]:nextNr.nrAntiFlicker;+ const auto previousTier=i<desc_.nrLayersAntiFlicker.size()?desc_.nrLayersAntiFlicker[i]:desc_.nrAntiFlicker;+ if(tier!=previousTier)return false;}}// A non-NVIDIA adapter keeps the user's requested NR setting in the UI@@ -3089,12 +3098,17 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){desc_.nrLayersModel=std::move(nextNr.nrLayersModel);desc_.nrLayersResidual=std::move(nextNr.nrLayersResidual);desc_.nrLayersTemporal=std::move(nextNr.nrLayersTemporal);+ desc_.nrLayersAntiFlicker=std::move(nextNr.nrLayersAntiFlicker);desc_.nrLayersProtection=std::move(nextNr.nrLayersProtection);for(size_t i=0;i<nrInstances_.size();++i){auto& layer=*nrInstances_[i];if(s.nr){layer.model=i<desc_.nrLayersModel.size()?desc_.nrLayersModel[i]:s.model;layer.residualSettings=i<desc_.nrLayersResidual.size()?desc_.nrLayersResidual[i]:s.residual;+ const auto& correction=layer.residualSettings.correction;+ veyra::log::info("nr-correction",std::format("live revision={} layer={} gain={} mode={} temporal={} manual={}/{}/{}/{}/{}",+ s.revision,i+1,layer.residualSettings.total,correction.enabled?(correction.automatic?"auto":"manual"):"off",+ layer.temporalEnabled,correction.hue,correction.chroma,correction.highlight,correction.compression,correction.stability));layer.protection=i<desc_.nrLayersProtection.size()?desc_.nrLayersProtection[i]:s.protection;}layer.temporal().reset();@@ -3104,7 +3118,7 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){++layer.inputRevision;}desc_.fgMultiplier=std::max(2u,s.multiplier);- const bool temporalMotion=s.nrTemporal||std::any_of(s.nrLayers.begin(),s.nrLayers.begin()+s.nrLayerCount,[](const auto& n){return n.enabled&&n.temporal;});+ const bool temporalMotion=s.usesNrTemporal();desc_.enableNvofStandalone=s.nr&&!desc_.stillImage&&(desc_.nrUsesFlow()||temporalMotion);nvofStandalone_=desc_.enableNvofStandalone;setNrEnabled(s.nr);setFgEnabled(s.multiplier>1&&!engine::presentSinkFrameGeneration(s.frameGenerationBackend));veyra::log::info("settings",std::format("requested revision={} intensity={} tone={} structure={} skin={} style={} autoMask={} UI={} residual={}/{}/{}/{}/{} multiplier={}",s.revision,s.model.intensity,s.model.tone,s.model.structure,s.model.skin,s.model.style,s.model.autoMask,s.model.uiCorrection,s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance,s.multiplier));diff --git a/src/pipeline/NrTemporalPass.cpp b/src/pipeline/NrTemporalPass.cppindex 8258db44..aede227c 100644--- a/src/pipeline/NrTemporalPass.cpp+++ b/src/pipeline/NrTemporalPass.cpp@@ -35,8 +35,8 @@ bool NrTemporalPass::initialize(ID3D12Device* device,ID3D12Resource* base,ID3D12for(unsigned i=0;i<2;++i){history_[i]=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);guide_[i]=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);if(!history_[i]||!guide_[i])return false;}std::vector<uint8_t> shader;// 7 SRVs (base, raw, history, guide, motion, low residual, low guide), 3 UAVs,- // 28 constants: the original 24 plus Route, LowSize and a pad.- if(!raw_||!pass_.loadShader("NrTemporal.dxil",shader)||!pass_.create(device,shader,20,7,3,28))return false;+ // 36 constants: original 24, Route/LowSize/pad, optional correction block.+ if(!raw_||!pass_.loadShader("NrTemporal.dxil",shader)||!pass_.create(device,shader,20,7,3,36))return false;if(lowFrequency){std::vector<uint8_t> reduce;// 3 SRVs + 2 UAVs = 5 slots per phase, two phases.@@ -64,7 +64,8 @@ bool NrTemporalPass::initialize(ID3D12Device* device,ID3D12Resource* base,ID3D12return true;}void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,bool reset,bool haveMotion,double frameMs,- float total,const engine::ProtectionSettings& protection){+ float total,const engine::ProtectionSettings& protection,+ const engine::NrCorrectionSettings& correction,bool hdr){const auto i=index_;// An interval outside the window is not a normal step: the history chain was// built on a different cadence, so it must not be blended across. Judging it@@ -75,7 +76,8 @@ void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,bif(!intervalSane&&valid_)valid_=false;const bool useHistory=valid_&&!reset&&haveMotion&&intervalSane;// 80 ms past-history EMA; no future frames or presentation holdback.- const float weight=useHistory?float(std::exp(-frameMs/80.0)):0.f;+ const float stability=correction.enabled?(correction.automatic?1.f:correction.stability):1.f;+ const float weight=useHistory?float(std::exp(-frameMs/80.0))*stability:0.f;const unsigned route=routeOf(tier_);if(route==4){// The reduce pass writes the *other* phase's half-resolution pair, which@@ -96,7 +98,7 @@ void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,btracker.transition(list,history_[1-i].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker.transition(list,guide_[1-i].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);for(auto* r:{output_,history_[i].Get(),guide_[i].Get()})tracker.transition(list,r,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- float c[28]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),weight,total,protection.enabled?1.f:0.f,protection.featherPixels,0,0};+ float c[36]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),weight,total,protection.enabled?1.f:0.f,protection.featherPixels,0,0};for(unsigned n=0;n<4;++n){const auto r=engine::protectionConstants(protection.regions[n]);c[8+n*4]=r[0];c[9+n*4]=r[1];c[10+n*4]=r[2];c[11+n*4]=r[3];}// Route and the low-frequency extent follow the region block. The shader// reads LowSize only on route 4 and the pad is never read: they exist to@@ -105,6 +107,8 @@ void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,bc[25]=std::bit_cast<float>(lowWidth_);c[26]=std::bit_cast<float>(lowHeight_);c[27]=0.f;+ const auto controls=correction.constants(hdr);+ std::copy(controls.begin(),controls.end(),c+28);pass_.bind(list,c,gpuHandleOf(pass_,i*10).ptr,gpuHandleOf(pass_,i*10+7).ptr);list->Dispatch((width_+7)/8,(height_+7)/8,1);for(auto* r:{output_,history_[i].Get(),guide_[i].Get()}){tracker.uavBarrier(list,r);tracker.transition(list,r,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 2476fa0e..221b18c7 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -4113,7 +4113,11 @@ QVariantList QmlPlayerBridge::nrLayers() const {{"uiCorrection",bool(n.model.uiCorrection)},{"total",n.residual.total},{"darken",n.residual.darken},{"brighten",n.residual.brighten},{"color",n.residual.color},{"luminance",n.residual.luminance},{"temporal",n.temporal},- {"antiFlicker",int(n.antiFlicker)}};+ {"antiFlicker",int(n.antiFlicker)},+ {"correctionEnabled",n.residual.correction.enabled},{"correctionAuto",n.residual.correction.automatic},+ {"hueProtection",n.residual.correction.hue},{"chromaProtection",n.residual.correction.chroma},+ {"highlightProtection",n.residual.correction.highlight},{"localCompression",n.residual.correction.compression},+ {"temporalStability",n.residual.correction.stability}};}return out;}@@ -4126,7 +4130,8 @@ QString QmlPlayerBridge::nrAutoSelectionReason(int index) const {for(uint32_t i=0;i<impl_->chain.nodeCount;++i){const auto& node=impl_->chain.nodes[i];if(node.type!=engine::EffectType::NrEnhance)continue;if(first<0)first=int(i);- ++count;temporal|=node.enabled&&node.nr.temporal;+ ++count;temporal|=node.enabled&&(node.nr.residual.correction.enabled?+ node.nr.residual.correction.usesHistory():node.nr.temporal);otherAuto|=int(i)!=index&&node.enabled&&node.nr.sizePolicy==pipeline::NrSizePolicy::Auto;}if(first!=index||count>2||otherAuto)return tr("自动 NR 仅支持一至两层列表的第一层");@@ -4163,6 +4168,11 @@ bool QmlPlayerBridge::setNrLayerParameter(int index,const QString& key,double vaelse if(key=="brighten")n.residual.brighten=float(value);else if(key=="color")n.residual.color=float(value);else if(key=="luminance")n.residual.luminance=float(value);+ else if(key=="hueProtection")n.residual.correction.hue=float(value);+ else if(key=="chromaProtection")n.residual.correction.chroma=float(value);+ else if(key=="highlightProtection")n.residual.correction.highlight=float(value);+ else if(key=="localCompression")n.residual.correction.compression=float(value);+ else if(key=="temporalStability")n.residual.correction.stability=float(value);else {if(value!=std::floor(value)||value<0||value>6)return false;if(key=="sizePolicy"){@@ -4173,6 +4183,8 @@ bool QmlPlayerBridge::setNrLayerParameter(int index,const QString& key,double vaelse if(key=="autoMask"&&value<=1)n.model.autoMask=int(value);else if(key=="uiCorrection"&&value<=1)n.model.uiCorrection=int(value);else if(key=="temporal"&&value<=1)n.temporal=value!=0;+ else if(key=="correctionEnabled"&&value<=1)n.residual.correction.enabled=value!=0;+ else if(key=="correctionAuto"&&value<=1)n.residual.correction.automatic=value!=0;else if(key=="antiFlicker"&&validNrAntiFlicker(engine::NrAntiFlicker(int(value))))n.antiFlicker=static_cast<engine::NrAntiFlicker>(int(value));else return false;}diff --git a/tests/integration/NrCorrectionGpuTests.cpp b/tests/integration/NrCorrectionGpuTests.cppnew file mode 100644index 00000000..8b3602fc--- /dev/null+++ b/tests/integration/NrCorrectionGpuTests.cpp@@ -0,0 +1,217 @@+// Production shader on the real D3D12 device, with an archived pre-change+// shader as the off-path oracle. Readback is confined to this diagnostic.+#include "veyra/pipeline/GpuPassUtils.h"+#include "veyra/engine/EnhancementSettings.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include <d3d12sdklayers.h>+#include <DirectXPackedVector.h>+#include <algorithm>+#include <array>+#include <cmath>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <limits>+#include <random>++using namespace veyra;+using namespace veyra::pipeline;+struct Pixel{float r,g,b,a;};+constexpr unsigned Width=128,Height=16,Pitch=Width*sizeof(Pixel),Count=Width*Height;+std::array<double,3> lab(Pixel c){+ // Independent double-precision Oklab coordinates, used to measure hue+ // rotation rather than reproducing the correction implementation.+ const double l=std::cbrt(.4122214708*c.r+.5363325363*c.g+.0514459929*c.b);+ const double m=std::cbrt(.2119034982*c.r+.6806995451*c.g+.1073969566*c.b);+ const double s=std::cbrt(.0883024619*c.r+.2817188376*c.g+.6299787005*c.b);+ return {.2104542553*l+.7936177850*m-.0040720468*s,+ 1.9779984951*l-2.4285922050*m+.4505937099*s,+ .0259040371*l+.7827717662*m-.8086757660*s};+}+Pixel to709(Pixel c){return {float(1.660491*c.r-.587641*c.g-.072850*c.b),+ float(-.124550*c.r+1.132900*c.g-.008349*c.b),+ float(-.018151*c.r-.100579*c.g+1.118730*c.b),c.a};}+Pixel to2020(Pixel c){return {float(.627404*c.r+.329283*c.g+.043313*c.b),+ float(.069097*c.r+.919540*c.g+.011362*c.b),+ float(.016391*c.r+.088013*c.g+.895595*c.b),c.a};}+float distance(Pixel a,Pixel b){return std::max({std::abs(a.r-b.r),std::abs(a.g-b.g),std::abs(a.b-b.b),std::abs(a.a-b.a)});}+bool finite(Pixel p){return std::isfinite(p.r)&&std::isfinite(p.g)&&std::isfinite(p.b)&&std::isfinite(p.a);}+void quantize(std::vector<Pixel>& pixels){using namespace DirectX::PackedVector;+ for(auto& p:pixels)for(auto* c:{&p.r,&p.g,&p.b,&p.a})*c=XMConvertHalfToFloat(XMConvertFloatToHalf(*c));}++struct Fixture{+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status=Status::Ok;+ StateTracker states;ComPtr<ID3D12Resource> base,neural,output,upload,readback;+ ComputePass pass,legacy;+ bool half=false;DXGI_FORMAT format=DXGI_FORMAT_R32G32B32A32_FLOAT;+ bool initialize(const std::filesystem::path& archived,bool fp16){+ half=fp16;format=half?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R32G32B32A32_FLOAT;+ gfx::DeviceContextDesc desc;desc.enableDebugLayer=true;+ if(!ctx.initialize(desc,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return false;+ base=makeTexture(ctx.device(),Width,Height,format,true);+ neural=makeTexture(ctx.device(),Width,Height,format,true);+ output=makeTexture(ctx.device(),Width,Height,format,true);+ upload=makeUploadBuffer(ctx.device(),Pitch*Height);+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=Pitch*Height;+ bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return false;+ std::vector<uint8_t> shader;+ if(!pass.loadShader("NrResidualComposite.dxil",shader)||!pass.create(ctx.device(),shader,4,3,1,32))return false;+ std::ifstream f(archived,std::ios::binary);std::vector<uint8_t> old((std::istreambuf_iterator<char>(f)),{});+ if(!f||old.empty()||!legacy.create(ctx.device(),old,4,3,1,32))return false;+ for(auto* p:{&pass,&legacy}){+ makeSrv(ctx.device(),base.Get(),format,cpuHandleOf(*p,0));+ makeSrv(ctx.device(),base.Get(),format,cpuHandleOf(*p,1));+ makeSrv(ctx.device(),neural.Get(),format,cpuHandleOf(*p,2));+ makeUav(ctx.device(),output.Get(),format,cpuHandleOf(*p,3));+ }+ return base&&neural&&output&&upload;+ }+ bool fill(ID3D12Resource* tex,const std::vector<Pixel>& pixels){+ void* data=nullptr;if(FAILED(upload->Map(0,nullptr,&data)))return false;+ if(half){using namespace DirectX::PackedVector;auto* d=static_cast<HALF*>(data);+ for(unsigned y=0;y<Height;++y)for(unsigned x=0;x<Width;++x){const auto p=pixels[y*Width+x];unsigned at=y*Pitch/2+x*4;+ d[at]=XMConvertFloatToHalf(p.r);d[at+1]=XMConvertFloatToHalf(p.g);d[at+2]=XMConvertFloatToHalf(p.b);d[at+3]=XMConvertFloatToHalf(p.a);}+ }else std::copy(pixels.begin(),pixels.end(),static_cast<Pixel*>(data));+ upload->Unmap(0,nullptr);+ unsigned slot;auto* list=ring.acquireNext(slot,status);if(!list)return false;+ states.transition(list,tex,D3D12_RESOURCE_STATE_COPY_DEST);+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=tex;dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Footprint={format,Width,Height,1,Pitch};+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);+ return ring.submitAndSignal(slot)&&ring.waitIdle();+ }+ std::vector<Pixel> render(const std::array<float,32>& c,bool old=false){+ unsigned slot;auto* list=ring.acquireNext(slot,status);if(!list)return {};+ for(auto* tex:{base.Get(),neural.Get()})states.transition(list,tex,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ states.transition(list,output.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ auto& p=old?legacy:pass;p.bind(list,c.data(),gpuHandleOf(p,0).ptr,gpuHandleOf(p,3).ptr);+ list->Dispatch((Width+15)/16,(Height+15)/16,1);+ states.uavBarrier(list,output.Get());states.transition(list,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};src.pResource=output.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ dst.PlacedFootprint.Footprint={format,Width,Height,1,Pitch};+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return {};+ void* data=nullptr;D3D12_RANGE range{0,Pitch*Height};if(FAILED(readback->Map(0,&range,&data)))return {};+ std::vector<Pixel> result(Count);+ if(half){using namespace DirectX::PackedVector;auto* d=static_cast<HALF*>(data);+ for(unsigned y=0;y<Height;++y)for(unsigned x=0;x<Width;++x){unsigned at=y*Pitch/2+x*4;+ result[y*Width+x]={XMConvertHalfToFloat(d[at]),XMConvertHalfToFloat(d[at+1]),XMConvertHalfToFloat(d[at+2]),XMConvertHalfToFloat(d[at+3])};}+ }else std::copy_n(static_cast<Pixel*>(data),Count,result.begin());+ D3D12_RANGE empty{0,0};readback->Unmap(0,&empty);return result;+ }+};+int wmain(int argc,wchar_t** argv){+ if(argc!=3&&argc!=4)return 2;+ const bool fp16=argc==4&&std::wstring_view(argv[3])==L"--fp16";+ std::filesystem::create_directories(argv[2]);std::ofstream csv(std::filesystem::path(argv[2])/L"shader-observations.csv");+ csv<<"mode,index,baseR,baseG,baseB,neuralR,neuralG,neuralB,resultR,resultG,resultB\n";+ Fixture f;if(!f.initialize(argv[1],fp16))return 2;+ bool ok=true;unsigned checks=0;+ auto check=[&](const char* label,bool success){++checks;std::cout<<(success?"PASS ":"FAIL ")<<label<<std::endl;ok&=success;};+ std::vector<Pixel> base(Count),nr(Count);std::mt19937 random(37181);std::uniform_real_distribution<float> unit(0,1);+ for(unsigned i=0;i<Count;++i){base[i]={unit(random),unit(random),unit(random),.15f+.8f*unit(random)};nr[i]={unit(random),unit(random),unit(random),1};}+ base[0]={.2f,.3f,.4f,.7f};nr[0]={.2002f,.3003f,.4004f,1}; // safe detail at full 5+ base[1]={.985f,.985f,.985f,.8f};nr[1]={.992f,.992f,.992f,1};+ base[2]={.9f,.05f,.02f,.9f};nr[2]={.98f,.12f,.6f,1};+ base[3]={.002f,.004f,.006f,.6f};nr[3]={.001f,.002f,.003f,1};+ for(unsigned i=32;i<128;++i){const float e=(float(i)-80)*1e-7f;base[i]={.2f+e,.2f,.2f-e,.7f};nr[i]={.9f,.05f,.3f,1};}+ if(fp16){quantize(base);quantize(nr);}+ if(!f.fill(f.base.Get(),base)||!f.fill(f.neural.Get(),nr))return 2;+ std::array<float,32> c{};c[0]=c[1]=c[2]=c[3]=c[4]=1;+ for(float gain:{0.f,1.f,2.f,5.f}){+ c[0]=gain;auto old=f.render(c,true),now=f.render(c);+ if(old.size()!=Count||now.size()!=Count)return 2;+ float maxError=0;bool same=true;+ for(unsigned i=0;i<Count;++i){maxError=std::max(maxError,distance(old[i],now[i]));same&=distance(old[i],now[i])==0;}+ std::cout<<"legacy comparison gain="<<gain<<" maxError="<<maxError<<std::endl;+ check("control off agrees with archived shader",same);+ }+ engine::NrCorrectionSettings control;control.enabled=true;+ auto controls=control.constants();std::copy(controls.begin(),controls.end(),c.begin()+24);+ for(float gain:{0.f,1.f,2.f,5.f}){+ c[0]=gain;auto result=f.render(c);if(result.size()!=Count)return 2;+ bool gamut=true,alpha=true;double maxHue=0;+ for(unsigned i=0;i<Count;++i){const auto p=result[i];+ gamut&=finite(p)&&std::min({p.r,p.g,p.b})>=-1e-6f&&std::max({p.r,p.g,p.b})<=1.000001f;+ alpha&=p.a==base[i].a;+ const auto a=lab(base[i]),b=lab(p);const double ca=std::hypot(a[1],a[2]),cb=std::hypot(b[1],b[2]);+ if(ca>.02001&&cb>.001){const double sine=std::abs(a[1]*b[2]-a[2]*b[1])/(ca*cb);maxHue=std::max(maxHue,sine);}+ if(gain==5)csv<<"auto,"<<i<<','<<base[i].r<<','<<base[i].g<<','<<base[i].b<<','<<nr[i].r<<','<<nr[i].g<<','<<nr[i].b<<','<<p.r<<','<<p.g<<','<<p.b<<'\n';+ }+ check("auto output finite and within SDR gamut",gamut);check("source alpha preserved",alpha);+ std::cout<<"hue sine error gain="<<gain<<" maximum="<<maxHue<<std::endl;+ check("full hue protection retains source hue",maxHue<(fp16?.015:.003));+ if(gain==5){+ const auto raw=f.render(c,true);+ check("safe proportional detail keeps requested gain five",distance(result[0],raw[0])<(fp16?.0005f:5e-6f));+ check("white highlight shoulder avoids flat clipping",result[1].r>.985f&&result[1].r<1&&std::abs(result[1].r-result[1].g)<1e-5f);+ check("dark extrapolation retains positive shadow detail",std::min({result[3].r,result[3].g,result[3].b})>0);+ float jump=0;for(unsigned i=33;i<128;++i)jump=std::max(jump,distance(result[i-1],result[i]));+ std::cout<<"gray-axis maximum step="<<jump<<std::endl;check("gray-axis continuity",jump<(fp16?.0005f:1e-4f));+ }+ }+ c[0]=5;auto autoFive=f.render(c);c[0]=4.99999f;auto nearby=f.render(c);float jump=0;+ for(unsigned i=0;i<Count;++i)jump=std::max(jump,distance(autoFive[i],nearby[i]));+ check("gain five boundary is continuous",jump<(fp16?.001f:1e-4f));+ // Each manual spatial control must have an observable effect through the+ // actual cbuffer while keeping a valid output; zero controls are checked+ // separately against the archived raw path below.+ c[0]=5;+ for(unsigned field=25;field<=28;++field){auto start=c;start[field]=0;auto finish=c;finish[field]=1;+ auto a=f.render(start),b=f.render(finish);float response=0;bool valid=true;+ for(unsigned i=0;i<Count;++i){response=std::max(response,distance(a[i],b[i]));valid&=finite(a[i])&&finite(b[i]);}+ std::cout<<"manual field="<<field<<" response="<<response<<std::endl;+ check("manual spatial control is wired and responsive",response>.0001f&&valid);+ }+ c[0]=5;std::fill(c.begin()+24,c.end(),0);c[24]=1;auto zero=f.render(c),off=f.render(c,true);+ bool identical=true;for(unsigned i=0;i<Count;++i)identical&=distance(zero[i],off[i])==0;+ check("all manual protections zero retains raw gain five",identical);+ // A full user exclusion bypasses every colour control.+ std::copy(controls.begin(),controls.end(),c.begin()+24);c[5]=1;c[6]=0;c[8]=0;c[9]=0;c[10]=1;c[11]=1;+ auto protectedFrame=f.render(c);identical=true;+ for(unsigned i=0;i<Count;++i)identical&=distance(protectedFrame[i],base[i])==0;+ check("protection rectangle returns exact source",identical);c[5]=0;+ f.fill(f.neural.Get(),base);auto identity=f.render(c);identical=true;+ for(unsigned i=0;i<Count;++i)identical&=distance(identity[i],base[i])==0;+ check("zero NR residual is exact identity",identical);+ nr[100].r=std::numeric_limits<float>::quiet_NaN();f.fill(f.neural.Get(),nr);+ auto repaired=f.render(c);check("nonfinite NR falls back to finite original",distance(repaired[100],base[100])==0);+ // HDR palette: valid wide-gamut BT.2020 maps to signed BT.709, with peaks+ // above SDR white. No comparison against a display or an HDR-trained model.+ for(unsigned i=0;i<Count;++i){+ Pixel wide={.01f+40*unit(random),.01f+40*unit(random),.01f+40*unit(random),base[i].a};+ base[i]=to709(wide);wide.r*=.96f;wide.g*=1.02f;wide.b*=1.03f;nr[i]=to709(wide);+ }+ base[0]=to709({8,.02f,.02f,.7f});nr[0]=to709({8.2f,.025f,.025f,.7f});+ if(fp16){quantize(base);quantize(nr);}+ f.fill(f.base.Get(),base);f.fill(f.neural.Get(),nr);c[7]=1;auto hdr=f.render(c);+ bool legal=true,alpha=true;+ for(unsigned i=0;i<Count;++i){Pixel p=to2020(hdr[i]),o=to2020(base[i]);float peak=std::min(125.f,std::max(203.f/80.f,std::max({o.r,o.g,o.b})));+ const float tolerance=fp16?.002f*std::max(1.f,peak):.001f;+ legal&=finite(p)&&std::min({p.r,p.g,p.b})>=-tolerance&&std::max({p.r,p.g,p.b})<=peak+tolerance;alpha&=hdr[i].a==base[i].a;+ csv<<"hdr,"<<i<<','<<base[i].r<<','<<base[i].g<<','<<base[i].b<<','<<nr[i].r<<','<<nr[i].g<<','<<nr[i].b<<','<<hdr[i].r<<','<<hdr[i].g<<','<<hdr[i].b<<'\n';+ }+ check("HDR BT2020 gamut and source peak envelope",legal);check("HDR alpha preserved",alpha);+ check("HDR retains signed wide gamut and above-white values",hdr[0].r>1&&std::min(hdr[0].g,hdr[0].b)<0);+ f.fill(f.neural.Get(),base);identity=f.render(c);identical=true;+ for(unsigned i=0;i<Count;++i)identical&=distance(identity[i],base[i])==0;+ check("HDR zero residual retains exact signed source",identical);+ f.ring.drainQueue();ComPtr<ID3D12InfoQueue> info;+ if(FAILED(f.ctx.device()->QueryInterface(IID_PPV_ARGS(&info))))return 2;+ unsigned errors=0,warnings=0;+ for(UINT64 i=0;i<info->GetNumStoredMessages();++i){+ SIZE_T size=0;info->GetMessage(i,nullptr,&size);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;}+ if(message->Severity==D3D12_MESSAGE_SEVERITY_WARNING){++warnings;std::cerr<<message->pDescription<<std::endl;}+ }+ check("D3D12 debug layer has no errors or warnings",errors==0&&warnings==0);+ std::ofstream report(std::filesystem::path(argv[2])/L"shader-result.json");+ report<<"{\"passed\":"<<(ok?"true":"false")<<",\"fp16\":"<<(fp16?"true":"false")<<",\"checks\":"<<checks<<",\"palettePixels\":"<<Count<<",\"debugErrors\":"<<errors<<",\"debugWarnings\":"<<warnings<<"}\n";+ return ok?0:1;+}diff --git a/tests/integration/NrTemporalGpuTests.cpp b/tests/integration/NrTemporalGpuTests.cppindex 3e01c658..3a4f2cf8 100644--- a/tests/integration/NrTemporalGpuTests.cpp+++ b/tests/integration/NrTemporalGpuTests.cpp@@ -33,11 +33,13 @@ int main() {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;bool patterned=false;+ std::array<float,3> rawOffset{};auto fill=[&](ID3D12Resource* texture,float value,bool flow=false){void* data=nullptr;if(FAILED(upload->Map(0,nullptr,&data)))return false;auto* pixels=static_cast<HALF*>(data);for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x)for(unsigned c=0;c<(flow?2u:4u);++c)- pixels[y*pitch/2+x*(flow?2:4)+c]=XMConvertFloatToHalf(c==3?1.f:value+(patterned&&!flow?float((x*13+y*7+c*3)%19)*.013f:0.f));+ pixels[y*pitch/2+x*(flow?2:4)+c]=XMConvertFloatToHalf(c==3?1.f:value++ (texture==pass.raw()?rawOffset[c]:0.f)+(patterned&&!flow?float((x*13+y*7+c*3)%19)*.013f:0.f));upload->Unmap(0,nullptr);unsigned slot;auto* list=ring.acquireNext(slot,status);if(!list)return false;states.transition(list,texture,D3D12_RESOURCE_STATE_COPY_DEST);@@ -47,17 +49,20 @@ int main() {return ring.submitAndSignal(slot)&&ring.waitIdle();};engine::ProtectionSettings protection;+ engine::NrCorrectionSettings correction;float outputMinimum=0.f;+ float outputChroma=0.f;auto run=[&](float raw,bool reset,double ms=16.6667,bool haveMotion=true,float total=1.f){if(!fill(pass.raw(),raw))return std::numeric_limits<float>::quiet_NaN();unsigned slot;auto* list=ring.acquireNext(slot,status);- pass.run(list,states,reset,haveMotion,ms,total,protection);+ pass.run(list,states,reset,haveMotion,ms,total,protection,correction);states.transition(list,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);D3D12_TEXTURE_COPY_LOCATION dst{},src{};src.pResource=output.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;dst.pResource=readback.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);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return std::numeric_limits<float>::quiet_NaN();void* data=nullptr;D3D12_RANGE range{0,pitch*height};readback->Map(0,&range,&data);float result=XMConvertHalfToFloat(static_cast<HALF*>(data)[6*pitch/2+8*4]);+ outputChroma=result-XMConvertHalfToFloat(static_cast<HALF*>(data)[6*pitch/2+8*4+1]);uint64_t fingerprint=14695981039346656037ull;outputMinimum=std::numeric_limits<float>::infinity();for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width*4;++x){@@ -211,6 +216,27 @@ int main() {const float value=.25f+float(int(frame%5)-2)*.04f;check("patterned finite",std::isfinite(run(value,frame==0||frame==9)));}+ patterned=false;correction.enabled=true;fill(base.Get(),.5f);fill(motion.Get(),0,true);+ float lo=1,hi=0;+ for(unsigned i=0;i<48;++i){const float value=run(i%2?.53f:.47f,i==0);+ if(i>12){lo=std::min(lo,value);hi=std::max(hi,value);}}+ check("controlled alternating luma flicker reduced",hi-lo<.02f);+ float chromaLo=1,chromaHi=-1;+ for(unsigned i=0;i<48;++i){+ const float delta=i%2?.03f:-.03f;+ rawOffset={0,-2*delta,-delta};run(.5f+delta,i==0);+ if(i>12){chromaLo=std::min(chromaLo,outputChroma);chromaHi=std::max(chromaHi,outputChroma);}+ }+ std::cout<<"alternating chroma rawRange=0.12 filteredRange="<<chromaHi-chromaLo<<std::endl;+ check("controlled alternating chroma flicker reduced",chromaHi-chromaLo<.04f);+ rawOffset={};+ check("controlled zero correction immediately clears history",run(.5f,false)==.5f);+ check("controlled next observation after identity is fresh",run(.53f,false)==XMConvertHalfToFloat(XMConvertFloatToHalf(.53f)));+ fill(base.Get(),.8f);+ check("controlled scene/source change rejects history",run(.83f,false)==XMConvertHalfToFloat(XMConvertFloatToHalf(.83f)));+ check("controlled missing flow rejects history",run(.77f,false,16.6667,false)==XMConvertHalfToFloat(XMConvertFloatToHalf(.77f)));+ correction.automatic=false;correction.stability=0;+ check("manual temporal zero publishes current observation",run(.74f,false)==XMConvertHalfToFloat(XMConvertFloatToHalf(.74f)));ring.drainQueue();ComPtr<ID3D12InfoQueue> info;if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info))))return 2;diff --git a/tests/integration/NrVideoQualityProbe.cpp b/tests/integration/NrVideoQualityProbe.cppindex 301d493c..e3740fb9 100644--- a/tests/integration/NrVideoQualityProbe.cpp+++ b/tests/integration/NrVideoQualityProbe.cpp@@ -233,7 +233,7 @@ int wmain(int argc,wchar_t** argv){if(featherStack){std::vector<uint8_t> shader;protectionExpected=pipeline::makeTexture(ctx.device(),info.width,info.height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);- if(!protectionExpected||!protectionOracle.loadShader("NrResidualComposite.dxil",shader)||!protectionOracle.create(ctx.device(),shader,4,3,1,24))return 2;+ if(!protectionExpected||!protectionOracle.loadShader("NrResidualComposite.dxil",shader)||!protectionOracle.create(ctx.device(),shader,4,3,1,32))return 2;pipeline::DescriptorStager staging;if(!staging.initialize(ctx.device(),3))return 2;staging.stageSrv(graph.diagnosticNrBase(),nullptr,protectionOracle.heap.Get(),0);staging.stageSrv(graph.diagnosticNrBase(),nullptr,protectionOracle.heap.Get(),1);@@ -282,7 +282,7 @@ int wmain(int argc,wchar_t** argv){unsigned slot=0;auto* list=ring.acquireNext(slot,status);if(!list)return 2;expectedStates.transition(list,protectionExpected.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);// Protect the complete stack, preserving signed residuals outside it.- float constants[24]={1,1,1,1,1,1,32,1};+ float constants[32]={1,1,1,1,1,1,32,1};constants[8]=.45f;constants[9]=.3f;constants[10]=.8f;constants[11]=.7f;protectionOracle.bind(list,constants,pipeline::gpuHandleOf(protectionOracle,0).ptr,pipeline::gpuHandleOf(protectionOracle,3).ptr);list->Dispatch((info.width+15)/16,(info.height+15)/16,1);diff --git a/tests/integration/RepairShaderTests.cpp b/tests/integration/RepairShaderTests.cppindex 92629557..c950e279 100644--- a/tests/integration/RepairShaderTests.cpp+++ b/tests/integration/RepairShaderTests.cpp@@ -15,7 +15,7 @@ int main(){D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=16*256;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;ComputePass down,residual;std::vector<uint8_t> cs;- if(!down.loadShader("NrDownsample.dxil",cs)||!down.create(ctx.device(),cs,2,1,1)||!residual.loadShader("NrResidualComposite.dxil",cs)||!residual.create(ctx.device(),cs,4,3,1,24))return 2;+ if(!down.loadShader("NrDownsample.dxil",cs)||!down.create(ctx.device(),cs,2,1,1)||!residual.loadShader("NrResidualComposite.dxil",cs)||!residual.create(ctx.device(),cs,4,3,1,32))return 2;makeSrv(ctx.device(),base.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(down,0));makeUav(ctx.device(),low.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(down,1));makeSrv(ctx.device(),base.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,0));makeSrv(ctx.device(),low.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,1));makeSrv(ctx.device(),low.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,2));makeUav(ctx.device(),result.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,3));StateTracker states;uint32_t slot;auto* list=ring.acquireNext(slot,status);states.transition(list,base.Get(),D3D12_RESOURCE_STATE_COPY_DEST);@@ -27,7 +27,7 @@ int main(){std::cout<<"area downsample checkerboard mean="<<ok<<std::endl;for(float strength:{0.0f,1.0f,2.0f}){list=ring.acquireNext(slot,status);states.transition(list,low.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);states.transition(list,result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- float c[24]={strength,0.5f,1.5f,2,0,0,0,0};residual.bind(list,c,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;+ float c[32]={strength,0.5f,1.5f,2,0,0,0,0};residual.bind(list,c,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;readback->Map(0,&range,&data);values=static_cast<float*>(data);bool identity=true;for(int y=0;y<16;++y)for(int x=0;x<16;++x)identity=identity&&values[y*64+x*4]==(((x+y)%2)?0.75f:0.25f);readback->Unmap(0,&written);ok=ok&&identity;std::cout<<"zero residual strength="<<strength<<" base identity="<<identity<<std::endl;}auto neural=makeTexture(ctx.device(),8,8,DXGI_FORMAT_R32G32B32A32_FLOAT,true);@@ -45,7 +45,7 @@ int main(){// .10 + 2*(.04-.10) negative, destroying all of this patch's detail.ok=ok&&fill(base.Get(),16,16,.10f,.10f,.10f)&&fill(low.Get(),8,8,.10f,.10f,.10f)&&fill(neural.Get(),8,8,.04f,.04f,.04f);for(unsigned control=0;control<5;++control)for(float strength:{0.f,.5f,1.f,2.f}){- float c[24]={1,1,1,1,1,0,0,0};c[control]=strength;+ float c[32]={1,1,1,1,1,0,0,0};c[control]=strength;list=ring.acquireNext(slot,status);states.transition(list,result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);residual.bind(list,c,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);@@ -64,7 +64,7 @@ int main(){// highlights. Default residual settings must not clamp either boundary.ok=ok&&fill(base.Get(),16,16,-.1f,2.f,.5f)&&fill(low.Get(),8,8,-.1f,2.f,.5f)&&fill(neural.Get(),8,8,-.2f,3.f,.75f);list=ring.acquireNext(slot,status);states.transition(list,result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- float hdr[24]={1,1,1,1,1,0,0,1};residual.bind(list,hdr,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);+ float hdr[32]={1,1,1,1,1,0,0,1};residual.bind(list,hdr,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;readback->Map(0,&range,&data);values=static_cast<float*>(data);diff --git a/tests/qml/quick/tst_components.qml b/tests/qml/quick/tst_components.qmlindex c00ca5a8..1bd30e6a 100644--- a/tests/qml/quick/tst_components.qml+++ b/tests/qml/quick/tst_components.qml@@ -74,11 +74,15 @@ Item {index: 2*i+1, enabled: true, runtime: 0, sizePolicy: 0, intensity: 1,tone: 1, structure: 1, skin: -1, style: 0, autoMask: false,uiCorrection: false, total: 1, darken: 1, brighten: 1,- color: 1, luminance: 1, temporal: false+ color: 1, luminance: 1, temporal: false, antiFlicker: 2,+ correctionEnabled: false, correctionAuto: true,+ hueProtection: 1, chromaProtection: 0.75, highlightProtection: 1,+ localCompression: 0.75, temporalStability: 0.8}))function edit(nodeIndex,key,amount) {lastIndex=nodeIndex; lastKey=keyconst next=rows.map(r => Object.assign({},r))+ if(key==="correctionEnabled"||key==="correctionAuto")amount=Boolean(amount)next.find(r => r.index===nodeIndex)[key]=amountrows=next}@@ -424,6 +428,50 @@ Item {}}+ function test_nr_correction_mouse_controls() {+ const fixture=createTemporaryObject(nrFixture,root)+ verify(waitForPolish(root.Window.window))+ const card=findChild(fixture,"nr-card-1")+ mouseClick(card,40,24);tryCompare(card,"open",true)+ const residual=findChild(card,"nr-residual-group")+ mouseClick(residual,40,15);tryCompare(residual,"expanded",true)+ verify(waitForPolish(root.Window.window));wait(550)+ const strength=findChild(card,"nr-total")+ compare(strength.to,5)+ mouseClick(strength,strength.trackWidth-1,strength.height/2)+ verify(fixture.rows[0].total>4.9)+ keyClick(Qt.Key_Right)+ compare(fixture.rows[0].total,5)+ mouseClick(residual,40,15);tryCompare(residual,"expanded",false)+ const group=findChild(card,"nr-correction-group")+ mouseClick(group,40,15);tryCompare(group,"expanded",true)+ verify(waitForPolish(root.Window.window));wait(550)+ const enabled=findChild(card,"nr-correctionEnabled")+ compare(enabled.checked,false);mouseClick(enabled)+ compare(fixture.rows[0].correctionEnabled,true)+ const mode=findChild(card,"nr-correctionAuto")+ compare(mode.current,"1")+ verify(!findChild(card,"nr-temporal").enabled)+ mouseClick(mode,mode.width-15,mode.height/2)+ compare(fixture.rows[0].correctionAuto,false)+ verify(waitForPolish(root.Window.window));wait(550)+ for(const key of ["hueProtection","chromaProtection","highlightProtection","localCompression","temporalStability"]){+ const control=findChild(card,"nr-"+key)+ verify(control.visible)+ mouseClick(control,control.trackWidth*0.35,control.height/2)+ fuzzyCompare(fixture.rows[0][key],0.35,0.015)+ }+ mouseClick(mode,15,mode.height/2)+ compare(fixture.rows[0].correctionAuto,true)+ compare(findChild(card,"nr-hueProtection").visible,false)+ fuzzyCompare(fixture.rows[0].hueProtection,0.35,0.015)+ mouseClick(enabled)+ compare(fixture.rows[0].correctionEnabled,false)+ verify(findChild(card,"nr-temporal").enabled)+ fuzzyCompare(fixture.rows[0].total,5,0.03)+ compare(fixture.rows[1].correctionEnabled,false)+ }+function test_nr_complete_parameters_and_skin_range() {const fixture=createTemporaryObject(nrFixture,root)verify(waitForPolish(root.Window.window))@@ -451,6 +499,7 @@ Item {compare(fixture.rows[1].skin,-1)pickOption(findChild(card,"nr-skin-mode"),1)compare(fixture.rows[1].skin,0)+ wait(100);verify(waitForPolish(root.Window.window))const skin=findChild(card,"nr-skin")compare(skin.from,0); compare(skin.to,2)mouseClick(skin,skin.trackWidth/4,skin.height/2)@@ -472,11 +521,12 @@ Item {mouseClick(residual,40,15)tryCompare(residual,"expanded",true)verify(waitForPolish(root.Window.window))+ wait(550)for(const key of ["total","darken","brighten","color","luminance"]) {const control=findChild(card,"nr-"+key)verify(control.width>50)mouseClick(control,control.trackWidth/4,control.height/2)- fuzzyCompare(fixture.rows[1][key],0.5,0.02)+ fuzzyCompare(fixture.rows[1][key],key==="total"?1.25:0.5,0.035)const reset=findChild(control,"vslider-reset")mouseClick(reset,reset.width/2,reset.height/2)compare(fixture.rows[1][key],1)diff --git a/tests/unit/EffectChainTests.cpp b/tests/unit/EffectChainTests.cppindex 6c4ec525..7370c34c 100644--- a/tests/unit/EffectChainTests.cpp+++ b/tests/unit/EffectChainTests.cpp@@ -925,7 +925,33 @@ static void testNodeInterNrProtectionDescription(){"unmigrated cross-SR Protection cannot enter production or inherit a list mask");}+void testNrCorrectionDescription(){+ EnhancementSettings s;s.nr=true;s.nrMotion=MotionSource::Zero;+ veyra::pipeline::EnhanceGraphDesc d;StageRequest request;request.nr=true;request.width=1280;request.height=720;+ describeStages(request,s,d);+ check(!d.nrTemporal&&!d.enableNvofStandalone,"NR correction off retains zero-motion/no-history topology");+ auto corrected=s;corrected.residual.correction.enabled=true;+ check(requiresGraphRebuild(s,corrected),"NR correction switch rebuilds history topology");+ describeStages(request,corrected,d);+ check(d.nrTemporal&&d.enableNvofStandalone,"NR auto requests real flow even with zero model motion");+ auto manual=corrected;manual.residual.correction.automatic=false;manual.residual.correction.stability=.5f;+ check(!requiresGraphRebuild(corrected,manual),"NR manual/auto with history is a live parameter update");+ manual.residual.correction.stability=0;+ check(requiresGraphRebuild(corrected,manual),"NR stability zero releases history via rebuild");+ describeStages(request,manual,d);+ check(!d.nrTemporal&&!d.enableNvofStandalone,"NR manual stability zero needs no history or flow");+ manual.nrTemporal=true;describeStages(request,manual,d);+ check(!d.nrTemporal,"manual correction owns temporal setting while enabled");+ manual.residual.correction.enabled=false;describeStages(request,manual,d);+ check(d.nrTemporal,"switch off restores saved legacy temporal option");+ manual.nrLayerCount=2;manual.nrLayers[0].enabled=true;manual.nrLayers[1].enabled=true;+ manual.nrLayers[1].residual.correction.enabled=true;+ describeStages(request,manual,d);+ check(d.nrLayersTemporal.size()==2&&!d.nrLayersTemporal[0]&&d.nrLayersTemporal[1],+ "controlled history is allocated per active layer");+}int main() {+ testNrCorrectionDescription();std::setvbuf(stdout,nullptr,_IONBF,0);testNodeEditorGraph();testExistingChainContracts();diff --git a/tests/unit/PresetLibraryTests.cpp b/tests/unit/PresetLibraryTests.cppindex 9b43fe11..abccf380 100644--- a/tests/unit/PresetLibraryTests.cpp+++ b/tests/unit/PresetLibraryTests.cpp@@ -902,7 +902,44 @@ void testNrVariants() {"NR variant: list and node sessions retain exact DLL selection");}}+void testNrCorrectionStorage() {+ // Exercise the public store/session/chain paths, including hidden manual+ // values while the switch is off. Never rely on serialising a test struct.+ for(unsigned mode=0;mode<3;++mode){+ EnhancementSettings s;s.nr=true;s.nrLayerCount=2;+ for(unsigned i=0;i<s.nrLayerCount;++i){auto& n=s.nrLayers[i];+ n.enabled=true;n.residual.total=5-float(i);+ n.residual.correction={mode!=0,mode!=2,.35f+float(i)*.1f,.2f,.7f,.5f,.65f};+ }+ s.residual=s.nrLayers[0].residual;+ const auto path=scratch((L"nr-correction-"+std::to_wstring(mode)+L".v1").c_str());+ PresetLibrary writer(path);writer.setIncludeBuiltins(false);+ PresetEntry entry;entry.name=L"strength five";entry.chain=toChain(s);+ check(writer.load()&&writer.put(entry),"NR correction: preset save");+ check(readBytes(path).starts_with("VEYRA_PRESET_LIBRARY 8\n"),"NR correction: explicit new schema");+ PresetLibrary reader(path);reader.setIncludeBuiltins(false);+ check(reader.load()&&reader.entries().size()==1&&reader.entries()[0]==entry,+ "NR correction: enabled/mode/manual values survive reload");+ auto session=std::make_unique<ChainSession>(ChainSession::initial(s));+ check(session->select(ChainMode::Node),"NR correction: node session initializes");+ ChainSessionStore store(scratch((L"nr-correction-session-"+std::to_wstring(mode)+L".v1").c_str()));+ auto restored=std::make_unique<ChainSession>(ChainSession::initial({}));+ check(store.save(*session)&&store.load(*restored)&&*restored==*session,+ "NR correction: list/node and editor session roundtrip");+ auto actual=std::make_unique<EnhancementSettings>();+ fromChain(entry.chain,*actual);+ check(actual->validate().empty()&&actual->nrLayers[0].residual==s.nrLayers[0].residual&&+ actual->nrLayers[1].residual==s.nrLayers[1].residual,"NR correction: shared settings carry both layers");+ }+ EnhancementSettings invalid;invalid.residual.total=5.001f;+ check(!invalid.validate().empty(),"NR correction: above five rejected");+ invalid.residual.total=5;invalid.residual.color=2.001f;+ check(!invalid.validate().empty(),"NR correction: component gain retains old limit");+ invalid.residual.color=1;invalid.residual.correction.highlight=1.01f;+ check(!invalid.validate().empty(),"NR correction: invalid protection rejected even while disabled");+}int main() {+ testNrCorrectionStorage();testNrVariants();testRenderingChoices();std::setvbuf(stdout, nullptr, _IONBF, 0);diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex 4a5d4f8d..3613a265 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -303,4 +303,16 @@ ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;ok=ok&&!corruptLoaded&&!corruptPut&&corruptPreserved;f.close();ok=legacyBackends(p)&&ok;ok=retiredSrMode(p)&&ok;ok=schemaVersions(p)&&ok;+ for(unsigned mode=0;mode<3;++mode){+ EnhancementSettings corrected;corrected.nr=true;corrected.residual.total=5;+ corrected.residual.correction={mode!=0,mode!=2,.35f,.25f,.8f,.7f,.5f};+ corrected.nrLayerCount=2;+ for(unsigned i=0;i<2;++i){auto& n=corrected.nrLayers[i];n.enabled=true;n.residual=corrected.residual;n.residual.correction.hue+=float(i)*.1f;}+ auto path=p;path+=L"-nr-correction-"+std::to_wstring(mode);+ std::error_code ec;std::filesystem::remove(path,ec);+ PresetStore writer(path);bool roundtrip=writer.load()&&writer.put(L"strength five",corrected);+ PresetStore reload(path);roundtrip=roundtrip&&reload.load()&&reload.entries().size()==1&&reload.entries()[0].settings==corrected;+ std::ifstream header(path);std::string magic;unsigned version=0;roundtrip=roundtrip&&bool(header>>magic>>version)&&version==29;+ ok&=roundtrip;std::cout<<"strength five correction mode "<<mode<<" schema29 roundtrip="<<roundtrip<<'\n';+ }std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}