Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

feat(sr): finish single-layer RTX Video SR prescale and output fit

Veyra Goal Agentcf84762cedea
diff --git a/AGENTS.md b/AGENTS.md
index aec0bcc2..7ead6061 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra Agent 工作规则
+> 2026-10-28当前任务:用户授权接手Claude的单层RTX视频超分功能,继续使用`claude/sr-stage-20261028`与现有施工树。范围是先降/超分/再缩的单层链,按`docs/SR_STAGE_HANDOFF_2026-10-28.md`续接;不自动扩展多层,不合并main、不push、不Release。接手前未提交改动已归档,原生NR先行/较小输出边界与导出协议需以本轮回执为准。
+
## 现在从哪里开始
- 当前正式版 **2.1.1**,发行标签 `v2.1.1` / 源码标签 `v2.1.1-sources`,发行提交 `2fecacf`,已完整进入main。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 52134ed9..f258ece6 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -225,6 +225,7 @@ target_link_libraries(veyra_runtime_probe PRIVATE veyra_gfx)
veyra_add_compute_shader(veyra_shader_parity_encode ParityEncode)
veyra_add_compute_shader(veyra_shader_parity_decode ParityDecode)
veyra_add_compute_shader(veyra_shader_hdr_video_sr HdrVideoSrRestore)
+veyra_add_compute_shader(veyra_shader_sr_resolve SrResolve)
veyra_add_compute_shader(veyra_shader_hdr_amd_nr_encode HdrAmdNrEncode)
veyra_add_compute_shader(veyra_shader_hdr_amd_nr_restore HdrAmdNrRestore)
if(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR)
@@ -614,7 +615,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
# veyra_sources: product input sources (Playbook R3/R7). MediaFileSource
# composes veyra_media; no second decode implementation exists.
- add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_flow_adapt veyra_shader_flow_refine veyra_shader_flow_fill veyra_shader_flow_claim veyra_shader_vfg_shot_change)
+ add_dependencies(veyra_pipeline veyra_shader_sr_resolve veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_nr_temporal veyra_shader_nr_hold veyra_shader_flow_adapt veyra_shader_flow_refine veyra_shader_flow_fill veyra_shader_flow_claim veyra_shader_vfg_shot_change)
add_library(veyra_sources STATIC
src/source/NativeCaptureSink.cpp
src/source/MediaFileSource.cpp
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 79ef0d82..914cf4dc 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -1,6 +1,6 @@
# 当前项目状态
-更新:2026-10-27。这里只描述现在;历史过程见[历史索引](history/INDEX.md)。
+更新:2026-10-28。这里只描述现在;历史过程见[历史索引](history/INDEX.md)。
## 正式版与开发基线
@@ -10,6 +10,8 @@
## 本轮整理结果与开发入口
+**2026-10-28新增开发分支:**当前施工树在`claude/sr-stage-20261028`,用户要求接手Claude完成单层RTX视频超分的“先降到→超分到→再缩到”。已补NR先行/较小输出的尺寸校验及导出协议,定向验收与收尾见[接手记录](SR_STAGE_HANDOFF_2026-10-28.md)。尚未合入main或发布;正式版本仍2.1.1,不把本分支内容计入现有发布包。独立的`claude/capture-fps-audio-20261027`不属于本轮,未顺带合并。
+
- 项目整理1–4由用户明确授权执行,起点main `7bf02d4`;结构整理提交`d4b1034`,构建与相关回归已通过。本轮以main作为后续开发入口,准确整合HEAD见执行任务FINAL回执。
- 已清43退休产物目录、移除89干净旧工作树、归档122分支引用;工作树101→12,收尾施工分支移除后本地分支132→10。保留的旧分支是6脏树、2条Lecram暂停线和1条带独有忽略内容的旧诊断线,另加main。
- 历史规则/计划/报告已分类,611份文档进入history;原9千行桥接改为启动接线与领域模块,对话框和专业页复用组件已拆分。E盘空闲空间相对开工前净增约28.14GiB,包含本轮保全归档/测试目录成本。
diff --git a/docs/SR_STAGE_HANDOFF_2026-10-28.md b/docs/SR_STAGE_HANDOFF_2026-10-28.md
new file mode 100644
index 00000000..9ae69a65
--- /dev/null
+++ b/docs/SR_STAGE_HANDOFF_2026-10-28.md
@@ -0,0 +1,58 @@
+# 单层三段式超分接手记录(2026-10-28)
+
+用户要求接手 Claude 未完成的超分功能。已阅读其对话与现场改动,按最后确认的范围完成:**单层、RTX 视频超分,先降到 → 超分到 → 再缩到**。没有把本轮扩成多层、多次 AI 推理、DLSS/FSR 三段式或细节混合。分支 `claude/sr-stage-20261028`,基线 `7b0b64b`;本轮不合并 main、不推送、不发布。
+
+## 功能与使用
+
+- 专业列表的超分卡片、节点模式的超分节点共用 `SrStageEditor.qml`。
+- 先降:关闭、720p、900p、1080p、1440p,或手动50–90%(滑条5%步进,松开提交);按片源比例处理。
+- 超分:保留2K、4K、5K、6K、7K、8K目标。再缩:不缩、片源尺寸、2K至7K;无效尺寸组合给出原因。
+- 两个例子:糊4K → 先降1080p → RTX视频超分4K;原生2K → RTX视频超分8K → 再缩4K。
+- 界面显示实际已应用的尺寸;预设、模式会话、独立导出传递这两个新参数。非RTX视频超分后端禁用两行,并保留保存值供切回。
+- 默认关闭先降、再缩,保持原单步规则。新功能会丢掉先降阶段被过滤的原生细节;HUD、字幕或清晰4K素材不保证改善。
+
+## Claude 已完成的部分
+
+设置与尺寸规划、处理图资源和GPU pass、预设格式、桥接/QML、翻译、图片A/B及首轮测试已写好,但尚未提交和收尾。原方案与原测试报告保留于 [方案](SR_STAGE_PLAN_2026-10-28.md)、[Claude实施报告](SR_STAGE_REPORT_2026-10-28.md)。原报告的GPU耗时、PSNR/SSIM是Claude当时的数据,不能当成本轮独立性能测量。
+
+接手前33个改动文件及binary patch按SHA保全至 `E:/项目/Veyra/archives/codex-sr-stage-handoff-20261028/claude-uncommitted.zip`,已逐项复核。起点标签 `checkpoint/pre-codex-sr-stage-handoff-20261028`。其他分支及用户数据未改。
+
+## 接手修复
+
+1. **NR先行与缩小后输出的衔接**:旧全局校验要求NR尺寸不超过最终工作尺寸。新流程能把4K片源最终输出为2K,但先行NR仍在4K处理;因此合法组合被拒绝。新增真实GPU边界测试先复现 `invalid NR extent`,修为按 `desc.nrFullExtent(0)` 校验,不降低NR分辨率、不绕过每层尺寸校验。修复后同一组合6帧实际处理通过。
+2. **导出进程协议**:`EnhancementSettings`追加字段改变共享内存布局,独立导出协议由11升级为12,防止旧worker按旧布局解释新参数。真实D3D12 NVENC导出验证冻结值、实际SR尺寸和完整帧数。
+3. 补充24个RTX视频超分尺寸/质量组合、NR先行、最终尺寸小于源、非整数面积缩回的GPU测试;真实界面验收覆盖节点模式。
+
+界面测试首次扩展误以为进入节点模式会带入列表的SR;产品合同实际是首次进入空图。已保留失败回执,修正测试夹具先通过 `addEffect("sr")` 添加节点后复验,不修改产品的空图行为。第一次只终止本轮明确识别的测试进程,没有停止用户软件。
+
+## 本轮验证
+
+复用 `E:/项目/Veyra/build/claude-screen-recording-20261022`,MSVC/Ninja并发2,每次构建≤900秒;测试每进程≤300秒。主要命令:
+
+```text
+python E:/项目/Veyra/tmp/claude-sr-stage-20261028/build/build.py veyra_qml_ui veyra_sr_quality_tests veyra_export_workflow_tests
+python scripts/acceptance/sr-stage-ui.py --task codex-sr-stage-handoff-20261028
+python scripts/i18n/extract.py --check
+```
+
+其余定向测试由 `reports/codex-sr-stage-handoff-20261028/run.py` 启动;准确参数、退出码、耗时在同目录JSON,日志在 `logs/codex-sr-stage-handoff-20261028`。
+
+| 检查 | 本轮结果 |
+|---|---|
+| EffectChain、RepairPreset、PresetLibrary、RepairContract、UI i18n、QtQuick | 六组退出0;契约272项0失败,翻译缺失0 |
+| `stage-boundaries` | 修复前失败、修复后退出0;源4K先行原生NR/最终2K,及非整数缩回实际处理通过 |
+| `stage` | SDR先降面积参考、SDR/HDR再缩、HDR底图/亮度检查退出0 |
+| `stage-capabilities` | 24个组合通过:质量1–4,每档5K/6K/7K/8K后缩4K、720p→4K、21:9 |
+| 原有单步SR集成测试 | 退出0,覆盖原尺寸视频修复、质量差异、前置调色、DLSS与FSR路径 |
+| 独立导出 | 两个真实NVENC任务各4源帧/4编码帧;输出分别2560×1440、3840×2160,ffprobe独立检查 |
+| 实际界面 | 列表/节点操作、手动比例、无效项提示、后端切换、关闭恢复;最终回执见FINAL.json |
+
+GPU四组首次runner使用同一stdout日志名,前几组stdout被后组覆盖;各组退出码/末尾标记保留在 `gpu.json`,各组独立GPU事件日志仍在对应tests目录。runner已改用用例序号,不重复运行测试来填补旧输出。
+
+## 交付与边界
+
+共享测试运行目录:`E:/项目/Veyra/tests/claude-sr-stage-20261028/app`,可运行其中 `veyra_qml_ui.exe`;本轮替换EXE/QML时先创建新文件,避免写穿正式供体硬链接。最终确认运行目录组件与供体manifest一致、测试注入的Main.qml已恢复。
+
+本轮未占用采集卡或连接真实主机,未重做显存峰值、长时动态画质、端到端延迟、main二进制逐像素对照,也未扩展为全显卡支持。Claude图片A/B表明有些2K→8K→4K裁切过锐较轻;这是有限样本,不能承诺所有老游戏/电影变清晰。先降导致的原生HUD细节损失保留明确提示。
+
+最终机器回执:`E:/项目/Veyra/reports/codex-sr-stage-handoff-20261028/FINAL.json`。当前正式2.1.1包和GitHub Release保持不变。
diff --git a/docs/SR_STAGE_PLAN_2026-10-28.md b/docs/SR_STAGE_PLAN_2026-10-28.md
new file mode 100644
index 00000000..9ae1ae8a
--- /dev/null
+++ b/docs/SR_STAGE_PLAN_2026-10-28.md
@@ -0,0 +1,144 @@
+# 三段式超分(单层)方案 2026-10-28
+
+状态:**已在分支`claude/sr-stage-20261028`实施,未合并**,结果与偏差见[实施报告](SR_STAGE_REPORT_2026-10-28.md)。用户2026-10-28要求“先实现单层的,并且使用RTX视频超分测试,SR效果非常一般,先写方案”。
+
+## 1. 目标与范围
+
+把现有“一步超分”扩成单层三段:**先降到 → 超分到 → 再缩到**。
+
+| 场景 | 片源 | 设置 | 实际尺寸 |
+|---|---|---|---|
+| 糊的4K(老游戏/老电影放大母版、PS5低内部分辨率输出) | 3840×2160 | 先降1080p · 超分到4K | 3840×2160 → 1920×1080 → VSR 3840×2160 |
+| 同上,保留更多原细节 | 3840×2160 | 先降1440p · 超分到4K | → 2560×1440 → VSR 3840×2160(1.5x) |
+| 原生2K仍不够清楚(超采样) | 2560×1440 | 超分到8K · 再缩到4K | → VSR 7680×4320(3x)→ 面积缩到3840×2160 |
+| 原生2K,先降后超分 | 2560×1440 | 先降1080p · 超分到4K | → 1920×1080 → VSR 3840×2160 |
+| 糊的4K + 超采样 | 3840×2160 | 先降1080p · 超分到8K · 再缩到4K | → 1920×1080 → VSR 7680×4320(4x)→ 3840×2160 |
+| 21:9 | 3840×1600 | 先降1080p · 超分到4K | → 1920×800 → VSR 3840×1600 |
+
+- **本阶段后端只做RTX视频超分(质量1–4)**,作为用户指定的测试后端。DLSS SR/FSR需要把光流运动矢量换算到先降后的尺寸,放到后续阶段;选这两个后端时两项新设置禁用并写明原因,不静默生效。
+- 默认“先降:关闭 / 再缩:不缩”必须与现有main(2.1.1)**逐像素同行为**(含压缩视频原尺寸修复、采集卡原尺寸跳过)。
+- 数据按“第0层”设计,以后加2–3层不改已保存格式的含义(见第8节)。
+- 本阶段不做:细节保留混合、自动识别有效分辨率、descale、多层、DLSS/FSR三段式。
+
+## 2. 现状(代码事实)
+
+- `ResolutionPlan::make`(`include/veyra/pipeline/ResolutionPlan.h`):仅当目标框大于片源才放大,`base`=超分输出=工作尺寸;`srApplied=sr&&base!=source`。4K片源+4K目标不放大。
+- `GraphDescription.h:121-127`:RTX视频超分在原尺寸对**压缩视频**仍运行(`nativeVideoRestore`);无压缩采集源原尺寸跳过(5090日志57:4K→4K VSR约8.7ms/帧)。
+- `EffectChain.cpp:537-550`:链路编译时SR步骤`processing=output=srExtent`,片源已等于目标则不生成SR步骤;SR目录`maxInstances=1`。
+- SR参数是全局项:`EnhancementSettings::srTarget/videoSrQuality/dlssSrModel`(`EnhancementSettings.h:339-341`),节点只带开关;`ChainGlobalSettings`(`EffectChain.h`)随列表/节点文档保存;非活动项在`EnhancementSettings.h:421-422`归一化(DLSS模型先例)。
+- VSR执行(`EnhanceGraph.cpp:2519-2534`):`ScaleBlit`把SR输入编码进`videoSrInput_`(R8G8B8A8,SDR模式1/HDR代理模式3)→ `VideoSrBackend::evaluate`(Rect/OutRect取自纹理尺寸)→ 解码回`workRgba_`:SDR用`ScaleBlit`模式-1,HDR用`HdrVideoSrRestore`(双线性取HDR底图与代理输入,`HdrRestore(base,Decode(proxy),Decode(proxyOut))`)。资源在`EnhanceGraph.cpp:723`按`srcW_×srcH_`/`workW_×workH_`创建。
+- `shaders/NrDownsample.hlsl`:精确面积(box)缩小,支持非整数比例,可直接复用。
+- 持久化:PresetStore当前最高v32;PresetLibrary v15;ChainSession v10。新版本只在用到新字段时写,并换文件后缀让旧版继续读自己的文件(现有规则)。
+- 界面:列表模式`ProPage.qml:1313-1372`(超分算法/DLSS模型/目标尺寸/运动来源/质量),节点模式`NodePage.qml`约1539行的SR目标。
+- VSR尺寸能力:SDK 1.1头文件只有输入/输出矩形,无能力表;2026-09-10方案已记录“没有足以承诺任意8K输出的能力表”。**5K–8K输出与3x以上倍率必须实测。**
+
+## 3. 设计
+
+### 3.1 设置(第0层)
+
+```cpp
+// ResolutionPlan.h —— 追加,不改现有ID
+enum class SrPrescale : uint32_t { Off, P720, P900, P1080, P1440, Manual=200 }; // 手动=100+百分比,50..90
+enum class SrOutput : uint32_t { Target, Source, Qhd, Uhd4K, Uhd5K, Uhd6K, Uhd7K }; // Target=2.1.1行为
+```
+
+- `EnhancementSettings`、`ChainGlobalSettings`各加`srPrescale=Off`、`srOutput=Target`,紧跟`srTarget`。两者仍为平凡可复制,导出worker共享内存照常(`ExportJobManager.cpp:54`静态断言)。
+- 校验:非法枚举拒绝(“invalid SR prescale/output”)。归一化:`!sr`或后端不是RTX视频超分(质量1–4)时两项按默认值进入活动设置,保存值保留——与`dlssSrModel`同一做法,界面同时禁用并写原因。
+
+### 3.2 尺寸规划
+
+`ResolutionPlan`新增`srInput`(先降后)、`srOutput`(VSR实际输出),`base`仍是SR之后整条链的工作尺寸:
+
+1. `srInput=source`;先降生效时按16:9高度框(720/900/1080/1440,与NR尺寸档同一等比算法)或手动百分比缩小,偶数对齐;结果不小于片源则**先降未生效**。
+2. `srOutput`=把`srInput`等比放进超分目标框(只放大)。先降关闭时等于现在的`base`,保证回归。
+3. `base=srOutput`;“再缩到”框小于`srOutput`时把它等比缩进框内,“片源尺寸”直接取`source`。框不小于`srOutput`则**再缩未生效**。
+4. `srApplied=sr&&srOutput!=srInput`。先降后已不小于目标框(如手动90%的4K配2K目标)时,先降视为未生效,整段按现有规则处理(与“已达目标不超分”同义),状态写明原因,不报错打断播放。界面对固定高度的无效组合直接置灰。
+5. `nr/flow/fg/output`沿用现有公式,以新`base`为准;NR先行(低延迟)路径不变:NR仍在片源尺寸,先降属于SR步骤内部。
+
+链路编译`compileChainExecutionPlan`改用同一函数:SR步骤`input=cursor`、`processing=srOutput`、`output=base`;只有“先降未生效且无放大且无再缩”才省略SR步骤。`ChainExecutionRequest`加两项。`GraphDescription`把`srInput/srOutput`写入`EnhanceGraphDesc`;`nativeVideoRestore`只在先降未生效时适用,先降生效时采集卡源也执行(用户显式选择)。
+
+### 3.3 GPU流程(只改VSR分支)
+
+```text
+SR输入(片源尺寸, 线性FP16)
+ └─[先降] NrDownsample面积缩小 → srPrescaled_ (srInput, FP16)
+ └─ ScaleBlit编码(SDR=1 / HDR代理=3) → videoSrInput_ (srInput, RGBA8)
+ └─ VSR evaluate → videoSrOutput_ (srOutput, RGBA8)
+ ├─ srOutput==base:现有解码 / HdrVideoSrRestore(底图改用srPrescaled_)
+ └─ srOutput>base :SrResolve —— 逐SR像素解码/HDR还原后按面积权重平均 → workRgba_ (base)
+```
+
+- 新资源:`srPrescaled_`(仅先降时),`videoSrInput_`改为`srInput`尺寸,`videoSrOutput_`改为`srOutput`尺寸;新ComputePass:`srPrescalePass_`(复用`NrDownsample.dxil`,独立描述符)、`srResolvePass_`(新`SrResolve.hlsl`)。
+- `SrResolve.hlsl`:面积权重沿用`NrDownsample`的精确算法;SDR解码与HDR还原放进共享`VideoSrRestore.hlsli`,`HdrVideoSrRestore.hlsl`改为include它且数学不变(GPU测试比对改前改后输出一致)。融合解码+缩小,免掉8K FP16中间纹理(253.1MiB)。
+- HDR:还原所用底图与代理输入必须同为`srInput`尺寸(先降后的线性底图+`videoSrInput_`),否则高光还原错位。
+- 全部在现有命令列表内:无像素回读、无逐pass CPU等待;`GpuStage::Sr`计时覆盖先降+编码+VSR+解码/再缩。
+- `nrBeforeSr`/`sourcePostOutput_`选输入的现有分支(描述符18/4)保持,先降读的就是`srStageInput()`。
+- 日志:`[video-sr] selected quality=Q source=… prescale=… evaluate=… output=…`;Create/Evaluate失败沿用NGX错误码和`FailedBackend::Sr`,实时重配失败保留旧图与参数(现有applied/回滚)。
+
+### 3.4 显存(RGBA8=4B/像素,FP16=8B/像素)
+
+| 组合 | 新增/变化 |
+|---|---|
+| 4K→先降1080p→4K | `srPrescaled_` 15.8MiB;`videoSrInput_` 31.6→7.9MiB;其余不变 |
+| 2K→VSR 8K→再缩4K | `videoSrOutput_` 126.6MiB;NR/FG/输出纹理全部按4K,而现有“目标8K”整条链都是8K |
+| 先降+再缩都关 | 与2.1.1相同 |
+
+### 3.5 界面与状态
+
+列表“超分辨率”卡片和节点SR检查器各加两行,顺序即处理顺序:
+
+- **先降到**:关闭 / 720p / 900p / 1080p / 1440p / 自定义(50–90%)。提示:“片源本身糊时,先缩小再超分,VSR更容易重建;会损失原有的真实细节(如原生4K的HUD、字幕)。”
+- **超分到**:现有“目标尺寸”改名,选项不变;提示补充“开启先降到后,片源已达目标也会执行”。
+- **再缩到**:不缩 / 片源尺寸 / 2K / 4K / 5K / 6K / 7K,只开放小于“超分到”的选项。提示:“超分到更高再缩回,相当于超采样;8K超分耗时显著增加。”
+- 后端不是RTX视频超分时两行禁用,写“目前仅RTX视频超分支持”。
+- 卡片摘要示例:“RTX 视频超分 · 1080p→4K · 质量 3”。“实际尺寸”一行取引擎已应用的计划,例:`3840×2160 → 1920×1080 → 3840×2160`,未生效时写原因。不新增刷新定时器,不改33ms/250ms刷新。
+- `i18n/catalog.json`补zh-TW/en/ja。导出对话框、录制、`PlayerUiFacade`设置日志里的输出尺寸改用新计划(现有`srTarget`触点:bridge `Export.cpp`/`Recording.cpp`/`Chain.cpp`、`QmlPlayerBridge_p.h`、`SettingsWindow.cpp`),保证显示尺寸=实际文件尺寸。
+
+### 3.6 持久化
+
+- PresetStore v33、PresetLibrary v16(globals)、ChainSession v11各在行尾追加两项;只有非默认值才写新版本并换新后缀(如`.sr-stage`),2.1.1继续读自己的旧文件;读取超出版本/非法值拒绝并保留原文件。
+- 实时重配:重建条件加入两项(吸取2026-09-09“后端切换未触发重建”的教训),以已应用revision+实际`[video-sr]`尺寸日志双重确认。
+
+## 4. 实施步骤(每步可单独审查、构建、回归)
+
+1. 设置/尺寸规划/链路编译/校验与归一化 + 单元测试。
+2. 三种存储格式 + 往返、旧版本、非法值测试。
+3. GPU:资源、先降、`SrResolve`/共享hlsli、VSR分支、日志 + GPU测试。
+4. 引擎重配、bridge、QML两种编辑器、i18n、导出/录制尺寸显示 + 界面验收脚本。
+5. 画质A/B、性能/显存实测,写报告、WORKLOG与FINAL回执。
+
+分支:自main `7b0b64b`新建`claude/sr-stage-20261028`,与未合并的`claude/capture-fps-audio-20261027`分开审查;需要一起出测试包时在本地合并,不push、不Release。产物进`build/claude-screen-recording-20261022`和`tests|logs|tmp|reports/claude-sr-stage-20261028`。单Agent、构建并发2/≤900秒、单测试≤300秒、私有data-dir/TEMP。
+
+## 5. 验证
+
+| 层次 | 内容 | 通过标准 |
+|---|---|---|
+| 尺寸单测 | 第1节全部例子;先降/再缩关闭时对全部片源×6个目标与现有计划相等;21:9/4:3/奇数尺寸;未生效判定;NR先行;导出 | 全部相等/符合 |
+| 设置/存储 | DLSS/FSR下归一化;非法值;v33/v16/v11往返;默认值仍写旧版本 | 通过且原文件保留 |
+| GPU正确性(扩展`SrQualityTests`) | 实际Create/Evaluate、纹理尺寸、非黑无NaN;先降/再缩与CPU面积参考对比;HDR代理路径;`HdrVideoSrRestore`改include前后输出一致 | 误差在FP16/8bit量化范围内;改include前后逐像素一致 |
+| 默认回归 | 功能关闭时同帧输出与main构建逐像素一致(SDR、HDR、压缩视频原尺寸修复、采集源跳过) | 一致 |
+| VSR能力 | 1080p→4K、1440p→4K、1440p→8K、1080p→8K、720p→4K、21:9各质量1–4 | 记录实际成功/失败;不支持的组合界面禁用并写原因,不偷换成普通缩放 |
+| 实时切换 | 播放中先降关→1080p→关、再缩不缩→4K | 每次都有新applied与对应尺寸日志,失败回滚 |
+| 画质A/B | 见下 | 用户目视判断为准,数值只作参考 |
+| 性能/显存 | 4K60文件播放30秒:每组合`GpuStage::Sr`中位/P95、整帧GPU、显存峰值;含/不含实时NR | 记录;超出60fps预算的组合在提示里说明 |
+
+**画质A/B**:
+- 本机现有`tests/nr-manual-scale-20261024/media/nr-4k30.mp4`是`testsrc2`合成画面,只能验尺寸和正确性,**不能判断画质**。需要用户提供自然素材:一段“糊的4K”(老游戏/老电影)和一段原生2K;或经用户同意用采集卡录PS5画面。另用系统已装FFmpeg从清晰4K母版生成“4K→1080p→4K+压缩”的退化版,以母版作参考算PSNR/SSIM。
+- 对照组(VSR质量4与2):关闭;现有单步(4K原尺寸修复/2K→4K);先降1440p→4K;先降1080p→4K;2K→8K→4K;先降1080p→8K→4K。
+- 输出:同一暂停帧无损PNG(静态细节、文字/HUD、运动三类场景)+ 10秒片段看时域闪烁;并排100%/200%裁切交给用户看。PSNR可能下降而观感更清楚,数值不当结论。
+
+## 6. 风险与未验证边界
+
+- VSR是为压缩视频放大训练的;“先降再超”是否优于现有4K原尺寸修复取决于片源。若A/B看不出提升,如实报告,不硬上多层。
+- 先降会丢掉片源里真实存在的高分辨率细节(原生4K HUD/字幕/UI),第一阶段无法避免,提示里写明;第二阶段用细节保留混合解决。
+- 线性光面积平均与NR一致;若A/B出现细亮线变粗或亮度偏移,再评估编码域平均,不预先加开关。
+- 8K输出与4x以上倍率能否运行、耗时多少均未知;5070上8K VSR可能超出60fps预算,只适合30fps或导出。
+- 1080p→4K的VSR可能比现在4K→4K原尺寸修复更省(输入少4倍),待实测,不预先宣称。
+- 采集卡实测需用户同意后才占用设备;未测前不声称采集场景可用。
+
+## 7. 后续阶段(不在本次范围)
+
+1. 细节保留混合:按局部高频能量把原片真实细节(HUD/文字)混回;自动识别有效分辨率并推荐“先降到”。
+2. Descale:已知放大核与原生分辨率的片源(动画/部分老片)做逆放大,复用成熟开源实现前核对许可证并记入THIRD_PARTY_NOTICES。
+3. DLSS SR/FSR三段式(运动矢量按`srInput`换算)。
+4. 多层:`srLayers[]`(每层先降/超分到/再缩/后端/质量),第0层就是本次的平铺字段,SR目录`maxInstances`放开;每加一层先实测耗时与伪影累积再决定上限。
diff --git a/docs/SR_STAGE_REPORT_2026-10-28.md b/docs/SR_STAGE_REPORT_2026-10-28.md
new file mode 100644
index 00000000..2f7d6aab
--- /dev/null
+++ b/docs/SR_STAGE_REPORT_2026-10-28.md
@@ -0,0 +1,99 @@
+# 三段式超分(单层)实施报告 2026-10-28
+
+> 本文保留Claude阶段的实施与测试记录。Codex接手后的边界修复、独立导出与最终验收见[接手记录](SR_STAGE_HANDOFF_2026-10-28.md),以该记录和对应FINAL回执为当前交付依据。
+
+依据[方案](SR_STAGE_PLAN_2026-10-28.md)。用户回复“图片测试就行,这张是原生 4K”,视为同意按方案实施并用图片测试。分支`claude/sr-stage-20261028`,基线main `7b0b64b`;未合并、未push、未Release。
+
+## 1. 做了什么
+
+超分卡片(列表模式)和超分节点(节点模式)共用新组件`SrStageEditor.qml`:**先降到 → 超分到 → 再缩到**,另有“实际尺寸”一行显示引擎正在使用的尺寸。
+
+| 设置 | 选项 | 存储 |
+|---|---|---|
+| 先降到 | 关闭 / 720p / 900p / 1080p / 1440p / 手动 50–90% | `SrPrescale`,手动=100+百分比 |
+| 超分到 | 原“目标尺寸”,2K–8K 不变 | `SrTarget` |
+| 再缩到 | 不缩 / 片源尺寸 / 2K / 4K / 5K / 6K / 7K | `SrOutput` |
+
+- 尺寸:`srStageExtents`(`ResolutionPlan.h`)统一给出“先降后 / SR 结果 / 步骤输出”。先降后已无法再放大、或再缩框不小于 SR 结果时,该步“未生效”并在界面写明原因,不报错。`ResolutionPlan`新增`srInput/srOutput`;链路编译的 SR 步骤`processing`=SR 结果、`output`=再缩后尺寸。
+- 只在 RTX 视频超分(质量 1–4、NVIDIA)运行:`runningSrPrescale/Output`对其他后端/显卡给出关闭值;`activeVideoSettings`同样归一化,所以 DLSS/FSR 下改这两项不重建图;界面两行禁用并写“目前仅 RTX 视频超分支持”,桥接也拒绝写入。
+- GPU(`EnhanceGraph.cpp` VSR 分支):先降复用`NrDownsample.dxil`精确面积缩小(线性光)到`srPrescaled_`;`videoSrInput_/videoSrOutput_`按先降尺寸/SR 结果尺寸分配;再缩用新`SrResolve.hlsl`,逐 SR 像素先解码(SDR)或 HDR 还原,再按面积权重平均写入工作纹理,不分配 8K FP16 中间纹理。HDR 还原所用底图与代理输入同为先降尺寸。全部在原命令列表内,无回读、无 CPU 等待;`GpuStage::Sr`计时包含先降和再缩。
+- 采集卡原尺寸跳过、压缩视频原尺寸修复等原规则在“先降关闭/不缩”时不变;开启先降后,采集源与静态图片也执行(用户显式选择)。
+- 重建:`requiresGraphRebuild`与引擎尺寸比较都加入新项;日志`[video-sr] selected ... three-step prescale=WxH evaluate=WxH`。
+- 存储:PresetStore v33、预设库 v16、模式会话 v11,只有用到新项才写新版本;库/会话写入新的`.sr-stage`旁路文件,旧文件保留供 2.1.1 回退。
+- i18n:15 条新文案补齐繁中/英/日,`extract.py --check`缺失 0。
+
+与方案的差异:`HdrVideoSrRestore.hlsl`未改动,`SrResolve.hlsl`直接用`HdrColor.hlsli`的`HdrRestore`并自带同样的双线性采样,避免改动现有 HDR 路径;HDR 正确性改由下文第 3 节的比对证明。
+
+## 2. 构建
+
+`tmp/claude-sr-stage-20261028/build/build.py`(vcvars64,`--parallel 2`,≤900 秒):单元测试目标 35.9 秒;`veyra_qml_ui`+SR/契约/i18n 测试 216.4 秒;其余增量均通过。运行目录`tests/claude-sr-stage-20261028/app`由`stage_app.py`硬链接 2.1.1 测试供体,再写入本次构建的 EXE、测试 EXE 和`SrResolve.dxil`(其余 shader 与供体逐 SHA 相同),DLL/模型逐 SHA 核对。
+
+## 3. 测试结果(全部通过)
+
+| 测试 | 结果 |
+|---|---|
+| `veyra_effect_chain_tests` | 全部通过,含新增三段式 40 项:关闭时 7 种片源×6 目标与原公式一致;14 个尺寸例子;链路步骤;描述在 DLSS/FSR/非 NVIDIA 下保持单步;导出/静图/采集;校验、归一化、重建、全局项往返 |
+| `veyra_repair_preset_tests` | v21(默认仍旧版本)/v33 往返;v33 非法先降值整文件拒绝且原文件保留 |
+| `veyra_preset_library_tests` | 新增 13 项:库 v16、会话 v11 旁路文件,原文件字节不变,导入导出、非法值原子拒绝 |
+| `veyra_repair_contract_tests` | 272 项 0 失败 |
+| `veyra_ui_i18n_tests` | 0 失败 |
+| `veyra_qml_quick_tests` | 117 通过 / 0 失败 / 1 跳过 |
+| `veyra_sr_quality_tests stage`(真实 RTX 视频超分) | 见下 |
+| `veyra_sr_quality_tests`(原有单步回归) | 原尺寸修复、质量档、前置调色、DLSS/FSR 全部通过 |
+| `veyra_live_presentation_tests --settings-rebuild` / `--inactive-effects` | 21 项 PASS / 9 次编辑 0 失败(GTA VI 原生 4K 视频) |
+| `veyra_effect_slot_regression_tests` | 12 个用例全部 exit 0 |
+| `scripts/acceptance/sr-stage-ui.py`(真实程序) | 15 项通过,无 QML 错误 |
+
+GPU 测试(合成画面,读回只在测试中):
+
+- 不开超分时输入输出转换无损(最大差 0),A/B 基线可信。
+- 先降:4K→1080p 后的 VSR 输入与 CPU 线性光面积平均一致,q1/q4 最大差 1 LSB、超过 1 的 0 个。
+- SDR 再缩:2K→8K→4K 输出与“同图 8K 结果的 CPU 面积平均”一致,最大差 1 LSB。
+- HDR 再缩(P010 PQ 输入,scRGB 输出):与 8K 还原结果的面积平均一致,超出容差 0 个。
+- HDR 先降:`HdrRestore`的结果只会在底图 ±1.27 范围内;单步相对全尺寸底图最大 1.199,先降相对“先降底图双线性采样”最大 1.276(容差 1.319),平均亮度比 0.998。若误用全尺寸底图,细高光线处会超出该范围。
+
+界面验收(4K30 合成视频,VSR 质量 3):通过控件本身切换先降 1080p、超分到 8K、再缩到 4K、手动 75%,实际尺寸依次为`3840x2160 → 1920x1080 → 3840x2160`、`… → 7680x4320 → 3840x2160`、`3840x2160 → 2880x1620 → 7680x4320 → 3840x2160`。每次都有新的`[video-sr] selected`(真实重建)。2K 目标时 1440p 选项置灰,手动设置后显示“先降到未生效”。切到 FSR 两行禁用、桥接拒绝写入。关闭后恢复单步。会话按 v11 写入`.sr-stage`,原文件保留。
+
+## 4. 图片 A/B(RTX 视频超分质量 4,RTX 5070)
+
+素材:用户附件实际是 2000×1125、69KB 的 webp(聊天传输压缩过,不是原生 4K 原图);有参照的对比改用项目以前用过的本地原生 4K 自然视频`GTAVI_An_Extended_Look_4K_Native.mp4`,抽取 t=780 秒(城市+HUD 小地图)和 t=95 秒(人物/金属/纹理)两帧无损 PNG 作参照。退化:糊的 4K = 面积缩到 1080p→JPEG q70→双三次放回 4K;原生 2K = Lanczos 缩到 2560×1440。PSNR/SSIM 按亮度对参照计算;“锐度”是梯度均值(参照 t780 为 0.00736、t95 为 0.00601),超过参照多半是过锐/光晕。
+
+| 场景 / 方式 | t780 PSNR / SSIM / 锐度 | t95 PSNR / SSIM / 锐度 | SR 耗时 |
+|---|---|---|---|
+| 糊 4K:不超分 | 41.65 / 0.9780 / 0.0062 | 43.85 / 0.9744 / 0.0031 | – |
+| 糊 4K:现有单步(4K 原尺寸修复) | 40.91 / 0.9706 / 0.0090 | 42.77 / 0.9664 / 0.0063 | 23.1 ms |
+| 糊 4K:先降 1440p→4K | 40.49 / 0.9668 / 0.0093 | 42.24 / 0.9626 / 0.0066 | 10.5 ms |
+| 糊 4K:先降 1080p→4K | 40.96 / 0.9659 / 0.0094 | 42.56 / 0.9638 / 0.0069 | 6.0 ms |
+| 糊 4K:先降 1080p→8K→4K | 40.98 / 0.9695 / 0.0083 | 42.53 / 0.9646 / 0.0057 | 7.2 ms |
+| 原生 2K:双三次放大 | 48.63 / 0.9957 / 0.0068 | 51.86 / 0.9941 / 0.0048 | – |
+| 原生 2K:现有单步 2K→4K | 44.76 / 0.9805 / 0.0095 | 45.74 / 0.9781 / 0.0071 | 10.5 ms |
+| 原生 2K:2K→8K→4K | **45.40 / 0.9835** / 0.0085 | **46.52 / 0.9812** / 0.0062 | 11.5 ms |
+| 原生 2K:先降 1080p→4K | 42.57 / 0.9757 / 0.0093 | 44.54 / 0.9731 / 0.0068 | 6.0 ms |
+
+结论(两帧,结果可复现):
+
+- **原生 2K 想更清楚:2K→8K→4K 在两帧上 PSNR、SSIM 都高于现有单步,锐度更接近原图**,1:1 观感也更自然;单步明显偏过锐。
+- **糊的 4K:三段式在客观分上与现有单步基本持平**(1080p→8K→4K 的 PSNR 略高、SSIM 略低),主要收益是开销降到 1/3–1/4(23 ms→6–7 ms)。观感差别需要用户自己看裁切图判断。
+- 所有 AI 超分的 PSNR 都低于双三次/不超分,这是重建细节类方法的常态,数值不当最终结论。
+- **已知限制得到量化**:把原图清晰的小地图贴回糊画面(模拟 PS5“画面糊、HUD 原生 4K”),HUD 区域 PSNR 单步 44.19 dB,先降后 35.0–36.6 dB;文字仍可读但边缘改变。这正是第二阶段“细节保留混合”要解决的。
+- 用户附件(2000×1125 放大成糊 4K,无参照):先降 1080p→4K 6.7 ms,现有单步 26.4 ms;压缩块明显减少、边缘更干净,但这张图压缩太重,看不出真实细节差异。
+
+图片与数据:`reports/claude-sr-stage-20261028/ab/{gta-t780,gta-t95,attachment-soft4k}/`(`ab.json`、`hud-case.json`、各组 100% 裁切和`zoom-*.png` 1:1 对比);输入/输出 PNG 在`tests/claude-sr-stage-20261028/ab/`。
+
+## 5. 性能(RTX 5070,`GpuStage::Sr`中位数,含编码/先降/再缩)
+
+| 情况 | 现有单步 | 三段式 |
+|---|---|---|
+| 4K 合成画面 q1 | 6.2 ms(4K→4K) | 1.64 ms(1080p→4K) |
+| 4K 合成画面 q4 | 25.1 ms | 6.8 ms |
+| 2K→8K q2:整条链 8K / 再缩 4K | 4.85 ms | 4.60 ms(后续 NR/补帧按 4K) |
+
+4K 片源用质量 4 做原尺寸修复每帧约 23–26 ms,已超过 60fps 预算;先降 1080p 后 6–7 ms。
+
+## 6. 未验证与边界
+
+- 未用户本人的原生 4K 原图跑参照对比(附件被压成 2000×1125);拿到原图路径后可用`scripts/acceptance/sr-stage-ab.py --mode native`直接跑。
+- 未实测显存峰值,第 3.4 节方案中的数字是纹理尺寸计算值。
+- 未与 main 构建做逐像素对比;关闭时代码路径只多了描述符槽位,由原有单步回归测试覆盖。
+- 未上采集卡实测(会占用设备,需要用户同意);未测 5K–7K 目标、1080p→8K 以外的 4x 以上倍率(6x 等)。本机 VSR 在 3x/4x 输出 8K 均正常。
+- DLSS SR/FSR 三段式、多层、细节保留混合、descale 均未做(第二阶段起)。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 05f5a6c1..4f8719d6 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -31,3 +31,17 @@
远端main原9520946,二维码提交a983c18;连接器上传后逐SHA/PNG解码发现图片损坏,改用原文件字节通过Git修复提交26480b2,最终远端原图77616字节、SHA256 AEDA3DF086F9C0983055A4F73EB2BD9F422C03E5C1910AF603A6ED0E79F2BDF9,与用户截图完全一致。两次远端提交均基于远端main,只含二维码范围,未推送本地项目整理提交。
GitHub连接器用于文件树/提交/引用更新,缺少Release编辑接口时用gh release edit --notes-file;随后合并远端二维码改动回本地main。verify.py核对远端三文档、原图字节与PNG解码、赞助图访问、两图宽度、Release正文仅群码/日期变化,全部通过;不涉及产品代码,无需重建。证据、原正文与最终回执:E:/项目/Veyra/reports/github-group-qr-20261027/。真实配置、依赖和正式包未改。
+
+## 2026-10-28 单层RTX三段式超分接手完成
+
+用户要求接手Claude额度用尽前未完成的功能。阅读原会话确认最后范围为单层RTX视频超分“先降到→超分到→再缩到”,沿用claude/sr-stage-20261028,基线7b0b64b;不合并main、不push、不Release,不把独立capture-fps-audio分支混入。保全33个改动文件/patch至archives/codex-sr-stage-handoff-20261028并逐SHA验证,起点标签checkpoint/pre-codex-sr-stage-handoff-20261028。
+
+复查新增真实GPU边界测试,先复现4K原生NR先行→1080p先降→2K输出被旧NR≤work边界错误拒绝;修为按NR实际所在阶段nrFullExtent校验,保留逐层校验,修复后6帧处理通过。独立导出共享参数布局改变,协议11→12,补两个实际worker/NVENC任务验证新字段、执行尺寸与完整帧数。
+
+构建:复用tmp/claude-sr-stage-20261028/build/build.py,MSVC/Ninja并发2,产品/相关测试目标均构建通过;主要增量26.8秒、后续6.9秒/3.1秒。运行目录复用tests/claude-sr-stage-20261028/app,通过新文件替换EXE/QML,不写穿供体链接。
+
+本轮run.py记录:六组unit/contract/QML退出0(RepairContract272项0失败);GPU stage-boundaries、stage、stage-capabilities、原单步SR四组退出0,新增24个实际VSR组合全部成功。GUI验收覆盖列表15项与节点4项,退出0、无QML错误;首次节点夹具未向空图添加SR而等待,停止本轮测试进程、保留失败记录,修正夹具后通过。两个实际导出各4源帧/4编码帧,ffprobe核对H.264、2560×1440及3840×2160。i18n extract --check缺失0、占位符0,git diff --check通过。
+
+GPU首次runner的stdout路径重名,前组stdout被覆盖;各组exit/末尾标记仍在gpu.json,各组独立engine事件日志保留;runner已改用序号。未借机重复整轮测试。未做main二进制逐像素对照、长时动态画质/显存峰值或实卡采集;Claude原图片A/B与本轮定向验收分开陈述。
+
+详细范围、命令、失败与验证见docs/SR_STAGE_HANDOFF_2026-10-28.md;本轮JSON/日志:reports与logs/codex-sr-stage-handoff-20261028。正式2.1.1包/SDK/模型/用户配置不改,Lecram继续暂停。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index ef72e9e4..13bc9f3e 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -2744,6 +2744,13 @@
"en": "Don't wait",
"ja": "待たない"
},
+ {
+ "zh": "不缩",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "不縮",
+ "en": "No downscale",
+ "ja": "縮小しない"
+ },
{
"zh": "不补偿",
"src": "qml/ProDisplayPanel.qml",
@@ -3794,6 +3801,34 @@
"en": "Choose a resolution first, then a frame rate and pixel format supported at that resolution.",
"ja": "先に解像度を選択し、その解像度で対応するフレームレートとピクセル形式を選択してください。"
},
+ {
+ "zh": "先降到",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "先降到",
+ "en": "Shrink first to",
+ "ja": "先に縮小"
+ },
+ {
+ "zh": "先降到 / 再缩到目前仅 RTX 视频超分支持",
+ "src": "src/ui/bridge/Enhancement.cpp",
+ "zh-TW": "先降到 / 再縮到目前僅 RTX 影片超解析支援",
+ "en": "Shrink first / Fit after are available with RTX Video Super Resolution only for now",
+ "ja": "先に縮小 / 後で縮小は現在 RTX ビデオ超解像のみ対応しています"
+ },
+ {
+ "zh": "先降到未生效:片源不大于所选尺寸,或先降后已不能再放大",
+ "src": "src/ui/bridge/Status.cpp",
+ "zh-TW": "先降到未生效:片源不大於所選尺寸,或先降後已不能再放大",
+ "en": "Shrink first not applied: the source is not larger than the chosen size, or nothing would be left to enlarge after shrinking",
+ "ja": "先に縮小は適用されていません:ソースが選択サイズ以下か、縮小後に拡大する余地がありません"
+ },
+ {
+ "zh": "先降比例",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "先降比例",
+ "en": "Shrink scale",
+ "ja": "縮小率"
+ },
{
"zh": "光流",
"src": "qml/NodePage.qml",
@@ -4194,6 +4229,20 @@
"en": "Recommended when re-streaming: input keeps going while Veyra is not in front. While on, the controller also drives the PS5 when you use other programs on this PC",
"ja": "再ストリーミングするときはオン推奨:Veyra が前面になくても転送を続けます。オンの間は、この PC で他のソフトを使っていてもコントローラーが PS5 を操作します"
},
+ {
+ "zh": "再缩到",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "再縮到",
+ "en": "Fit after to",
+ "ja": "後で縮小"
+ },
+ {
+ "zh": "再缩到未生效:只在超分放大后、且小于超分结果时执行",
+ "src": "src/ui/bridge/Status.cpp",
+ "zh-TW": "再縮到未生效:只在超解析放大後、且小於超解析結果時執行",
+ "en": "Fit after not applied: it runs only after an enlarging upscale, and only to a size smaller than the upscaled result",
+ "ja": "後で縮小は適用されていません:超解像で拡大した後、その結果より小さいサイズにのみ実行します"
+ },
{
"zh": "写入封装文件头",
"src": "src/engine/VideoExportJob.cpp",
@@ -6504,6 +6553,13 @@
"en": "Live preview; settings apply to every file",
"ja": "リアルタイムプレビュー。設定はすべてのファイルに適用"
},
+ {
+ "zh": "实际尺寸",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "實際尺寸",
+ "en": "Actual sizes",
+ "ja": "実際のサイズ"
+ },
{
"zh": "实际运行:FSR %1 · 2X",
"src": "src/ui/bridge/FrameGeneration.cpp",
@@ -9460,11 +9516,11 @@
"ja": "名前の変更に失敗しました:空、48 文字超、または既存のプリセットと同じ名前にはできません"
},
{
- "zh": "放大时重建细节;原尺寸时修复视频文件和串流的压缩伪影,无压缩的采集卡格式在原尺寸不运行。效果取决于片源。",
- "src": "qml/NodePage.qml",
- "zh-TW": "放大時重建細節;原尺寸時修復影片檔案和串流的壓縮瑕疵,無壓縮的擷取卡格式在原尺寸不執行。效果取決於片源。",
- "en": "Reconstructs detail when upscaling; at native size it reduces compression artifacts in video files and streams, and does not run for uncompressed capture-card formats. Results depend on the source.",
- "ja": "拡大時は細部を再構成し、元の解像度では動画ファイルとストリームの圧縮ノイズを軽減します。非圧縮のキャプチャーカード形式では元の解像度で実行しません。効果はソースにより異なります。"
+ "zh": "放大时重建细节;原尺寸时修复视频文件和串流的压缩伪影,无压缩的采集卡格式在原尺寸不运行;开启先降到后,片源已达目标也会执行。效果取决于片源。",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "放大時重建細節;原尺寸時修復影片檔案和串流的壓縮偽影,無壓縮的擷取卡格式在原尺寸不執行;開啟先降到後,片源已達目標也會執行。效果取決於片源。",
+ "en": "Reconstructs detail when upscaling; at native size it reduces compression artifacts in video files and streams, and does not run for uncompressed capture-card formats. With Shrink first on, it also runs when the source already meets the target. Results depend on the source.",
+ "ja": "拡大時は細部を再構成し、元の解像度では動画ファイルとストリームの圧縮ノイズを軽減します。非圧縮のキャプチャーカード形式では元の解像度で実行しません。「先に縮小」がオンの場合は、ソースが目標に達していても実行します。効果はソースにより異なります。"
},
{
"zh": "效果",
@@ -12357,6 +12413,13 @@
"en": "Source",
"ja": "ソース"
},
+ {
+ "zh": "片源尺寸",
+ "src": "qml/ProPage.qml",
+ "zh-TW": "片源尺寸",
+ "en": "Source size",
+ "ja": "ソースのサイズ"
+ },
{
"zh": "片源最亮 %1 nit,曲线硬上限 %2 nit:%3",
"src": "qml/ProDisplayPanel.qml",
@@ -12364,6 +12427,13 @@
"en": "Declared source peak %1 nit, curve cap %2 nit: %3",
"ja": "ソースの公称ピーク %1 nit、カーブ上限 %2 nit:%3"
},
+ {
+ "zh": "片源本身糊时,先缩小再超分,RTX 视频超分更容易重建细节;会损失片源中真实的高分辨率细节(如原生 4K 的 HUD、字幕)。",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "片源本身糊時,先縮小再超解析,RTX 影片超解析更容易重建細節;會損失片源中真實的高解析度細節(如原生 4K 的 HUD、字幕)。",
+ "en": "When the source itself is soft, shrinking before upscaling lets RTX Video Super Resolution rebuild detail more easily; real high-resolution detail in the source (such as native 4K HUD or subtitles) is lost.",
+ "ja": "ソース自体がぼやけている場合、先に縮小してから超解像すると RTX ビデオ超解像が細部を再構成しやすくなります。ソース本来の高解像度の細部(ネイティブ 4K の HUD や字幕など)は失われます。"
+ },
{
"zh": "片源没有携带亮度信息",
"src": "qml/ProDisplayPanel.qml",
@@ -12798,6 +12868,13 @@
"en": "Monitoring overlay compatibility",
"ja": "モニタリングソフト互換"
},
+ {
+ "zh": "目前仅 RTX 视频超分支持",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "目前僅 RTX 影片超解析支援",
+ "en": "RTX Video Super Resolution only for now",
+ "ja": "現在は RTX ビデオ超解像のみ対応"
+ },
{
"zh": "目前只支持 RTX 50 系列:40/30 系的多帧解锁只适用于原版运行库",
"src": "src/ui/bridge/FrameGeneration.cpp",
@@ -12812,13 +12889,6 @@
"en": "Target",
"ja": "対象"
},
- {
- "zh": "目标尺寸",
- "src": "qml/NodePage.qml",
- "zh-TW": "目標尺寸",
- "en": "Target size",
- "ja": "目標サイズ"
- },
{
"zh": "目标已失效",
"src": "src/ui/bridge/Capture.cpp",
@@ -12856,7 +12926,7 @@
},
{
"zh": "目标须大于片源尺寸;已达到目标时不执行超分。",
- "src": "qml/NodePage.qml",
+ "src": "qml/SrStageEditor.qml",
"zh-TW": "目標須大於片源尺寸;已達到目標時不執行超解析度。",
"en": "The target must exceed the source size. Upscaling is skipped when the source already meets the target.",
"ja": "入力より大きい目標解像度が必要です。入力が目標以上の場合は超解像処理を行いません。"
@@ -15556,6 +15626,20 @@
"en": "SR 4K · NR 1 layer · FG 2X",
"ja": "超解像 4K · NR 1 層 · フレーム生成 2X"
},
+ {
+ "zh": "超分到",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "超解析到",
+ "en": "Upscale to",
+ "ja": "超解像の目標"
+ },
+ {
+ "zh": "超分到更大尺寸后按面积缩回,相当于超采样;只在超分放大后执行。8K 超分耗时显著增加。",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "超解析到更大尺寸後按面積縮回,相當於超取樣;只在超解析放大後執行。8K 超解析耗時顯著增加。",
+ "en": "Upscales to a larger size, then area-averages back down, like supersampling; runs only after an enlarging upscale. 8K upscaling takes much more GPU time.",
+ "ja": "より大きなサイズへ超解像してから面積平均で縮小します(スーパーサンプリング相当)。超解像で拡大した場合のみ実行します。8K の超解像は処理時間が大きく増えます。"
+ },
{
"zh": "超分算法",
"src": "qml/NodePage.qml",
@@ -17642,6 +17726,13 @@
"en": "Must stay below the maximum",
"ja": "上限より低くしてください"
},
+ {
+ "zh": "须小于超分目标",
+ "src": "qml/SrStageEditor.qml",
+ "zh-TW": "須小於超解析目標",
+ "en": "Must be smaller than the upscale target",
+ "ja": "超解像の目標より小さい必要があります"
+ },
{
"zh": "预算 ",
"src": "qml/ProPage.qml",
diff --git a/include/veyra/engine/EffectChain.h b/include/veyra/engine/EffectChain.h
index 5151486a..c237a148 100644
--- a/include/veyra/engine/EffectChain.h
+++ b/include/veyra/engine/EffectChain.h
@@ -178,6 +178,9 @@ struct ChainExecutionRequest {
bool stillImage = false;
bool exportJob = false;
bool amdNrExport = false; // bounded internal model input, full-size output
+ // Three-step SR as it runs (callers pass Off/Target where it does not apply).
+ pipeline::SrPrescale srPrescale = pipeline::SrPrescale::Off;
+ pipeline::SrOutput srOutput = pipeline::SrOutput::Target;
};
struct ChainExecutionStep {
EffectType type = EffectType::NrEnhance;
@@ -207,6 +210,8 @@ struct ChainGlobalSettings {
pipeline::SrTarget srTarget = pipeline::SrTarget::Uhd4K;
uint32_t videoSrQuality = kDefaultVideoSrQuality;
uint32_t dlssSrModel = 0; // EnhancementSettings::dlssSrModel
+ pipeline::SrPrescale srPrescale = pipeline::SrPrescale::Off; // EnhancementSettings::srPrescale
+ pipeline::SrOutput srOutput = pipeline::SrOutput::Target; // EnhancementSettings::srOutput
FrameGenerationBackend fgBackend = FrameGenerationBackend::Dlss;
uint32_t vfgQuality=1;
FlowQuality flow = FlowQuality::Balanced;
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index 7b4de0d5..f2450964 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -75,6 +75,8 @@ inline constexpr uint32_t kVideoSrFsr=5;
// Fresh SR selections use RTX Video SR high; explicit saved selections retain
// their numeric IDs. The UI seeds FSR separately on AMD/Intel adapters.
inline constexpr uint32_t kDefaultVideoSrQuality=4;
+// Three-step SR (prescale / SR / output fit) runs on RTX Video SR only so far.
+constexpr bool srStageBackend(uint32_t videoSrQuality){return videoSrQuality>=1&&videoSrQuality<=4;}
// DLSS SR model (videoSrQuality 0 only): 0 = DLSS 4 transformer (preset K,
// what DLSS SR always used here), 1 = DLSS 4.5 second-generation transformer
// (preset M), 2 = DLSS 4.5 Ultra Performance model (preset L). Both 4.5
@@ -339,6 +341,10 @@ struct EnhancementSettings {
pipeline::SrTarget srTarget=pipeline::SrTarget::Uhd4K;
uint32_t videoSrQuality=kDefaultVideoSrQuality; // 0 DLSS SR; 1–4 RTX Video SR
uint32_t dlssSrModel=0; // DLSS SR only; see kDlssSrModelCount
+ // Three-step SR (user 2026-10-28): shrink to srPrescale, SR to srTarget,
+ // then fit into srOutput. Off/Target keep the single step.
+ pipeline::SrPrescale srPrescale=pipeline::SrPrescale::Off;
+ pipeline::SrOutput srOutput=pipeline::SrOutput::Target;
uint32_t multiplier=1;
FrameGenerationBackend frameGenerationBackend=FrameGenerationBackend::Dlss;
// NvVFX Mode: Low=0, Medium=1 (default), High=2; mixed tiers 3-5, see vfgPrimaryMode().
@@ -420,6 +426,7 @@ struct EnhancementSettings {
if(!nr||!protection.enabled)active.protection=defaults.protection;
if(!sr){active.srTarget=defaults.srTarget;active.videoSrQuality=defaults.videoSrQuality;active.srMotion=defaults.srMotion;}
if(!sr||videoSrQuality!=0)active.dlssSrModel=defaults.dlssSrModel;
+ if(!sr||!srStageBackend(videoSrQuality)){active.srPrescale=defaults.srPrescale;active.srOutput=defaults.srOutput;}
if(multiplier<=1){
active.frameGenerationBackend=defaults.frameGenerationBackend;active.vfgQuality=defaults.vfgQuality;
active.fgMotion=defaults.fgMotion;active.fgStrictAdmission=defaults.fgStrictAdmission;
@@ -559,6 +566,8 @@ struct EnhancementSettings {
if(videoSrQuality>kVideoSrFsr)return "invalid video SR quality";
if(dlssSrModel>=kDlssSrModelCount)return "invalid DLSS SR model";
if(!pipeline::validSrTarget(srTarget))return "invalid SR target";
+ if(!pipeline::validSrPrescale(srPrescale))return "invalid SR prescale";
+ if(!pipeline::validSrOutput(srOutput))return "invalid SR output";
if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx&&opticalFlowBackend!=OpticalFlowBackend::GpuDis)return "invalid optical flow backend";
if(multiplier<1||multiplier>(frameGenerationBackend==FrameGenerationBackend::Vfg?8u:6u))return "unsupported multiplier";
// 0 = auto quality; explicit values are capped at 300 Mbps so a typo
diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.h
index 0bce655d..e70fe1bd 100644
--- a/include/veyra/engine/GraphDescription.h
+++ b/include/veyra/engine/GraphDescription.h
@@ -65,6 +65,15 @@ struct StageRequest {
const ChainRuntimeOrder* nodeOrder=nullptr; // paired with this settings transaction
};
+// Three-step SR runs on RTX Video SR (NVIDIA) only; every other backend keeps
+// the single step whatever the saved fields say.
+inline pipeline::SrPrescale runningSrPrescale(const EnhancementSettings& s,bool nvidiaAdapter){
+ return nvidiaAdapter&&srStageBackend(s.videoSrQuality)?s.srPrescale:pipeline::SrPrescale::Off;
+}
+inline pipeline::SrOutput runningSrOutput(const EnhancementSettings& s,bool nvidiaAdapter){
+ return nvidiaAdapter&&srStageBackend(s.videoSrQuality)?s.srOutput:pipeline::SrOutput::Target;
+}
+
// Fills the stage, size and parameter fields of `desc` from `settings`.
// Source-format fields (hdrInput, rgbInput, packedInput, ...), hdrOutput and
// host hooks are left untouched: the caller owns those.
@@ -99,8 +108,10 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
const bool boundedAmd=request.exportJob&&!request.stillImage&&request.amdNr&&
currentNrRuntime(settings.nrRuntime)==NrRuntime::LmxxfAmd;
const auto policy=request.exportJob?exportNrSizePolicy(settings.nrRuntime,settings.nrPolicy):settings.nrPolicy;
+ const auto srPrescale=runningSrPrescale(settings,request.nvidiaAdapter);
+ const auto srOutput=runningSrOutput(settings,request.nvidiaAdapter);
if(!pipeline::Extent{request.width,request.height}.valid()||!pipeline::validSrTarget(settings.srTarget)||
- !pipeline::validNrSizePolicy(policy)){
+ !pipeline::validNrSizePolicy(policy)||!pipeline::validSrPrescale(srPrescale)||!pipeline::validSrOutput(srOutput)){
// ResolutionPlan::make throws for these inputs. Report the same
// invalid contract before any graph allocation, including on reuse.
desc.fixedExecutionPlanError="invalid fixed-plan source extent, SR target or NR size policy";
@@ -111,11 +122,13 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
auto plan=pipeline::ResolutionPlan::make({request.width,request.height},request.sr,
boundedAmd?pipeline::NrSizePolicy::Realtime:policy,
(request.stillImage||request.exportJob)&&!boundedAmd,settings.revision,settings.srTarget,lowLatency,
- request.amdNr&&currentNrRuntime(settings.nrRuntime)==NrRuntime::LmxxfAmd?1080u:0u);
+ request.amdNr&&currentNrRuntime(settings.nrRuntime)==NrRuntime::LmxxfAmd?1080u:0u,srPrescale,srOutput);
if(request.exportJob&&!request.stillImage)
plan.nr=exportNrProcessingExtent(plan.base,settings.nrRuntime,policy);
desc.sourceWidth=request.width;desc.sourceHeight=request.height;
desc.workWidth=plan.base.width;desc.workHeight=plan.base.height;
+ desc.srInputWidth=plan.srInput.width;desc.srInputHeight=plan.srInput.height;
+ desc.srOutputWidth=plan.srOutput.width;desc.srOutputHeight=plan.srOutput.height;
desc.nrWidth=plan.nr.width;desc.nrHeight=plan.nr.height;
desc.flowWidth=plan.flow.width;desc.flowHeight=plan.flow.height;
// RTX Video SR can restore compressed video at its original resolution.
@@ -173,7 +186,7 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
}
ChainExecutionPlan execution;
const auto validation=compileChainExecutionPlan(chain,{{request.width,request.height},settings.srTarget,
- request.stillImage,request.exportJob,boundedAmd},execution);
+ request.stillImage,request.exportJob,boundedAmd,srPrescale,srOutput},execution);
if(!validation.accepted){desc.fixedExecutionPlanError=validation.message;return plan;}
if(request.nodeOrder){
// Node order owns the first NR stage, even for an ordinary resize or
@@ -194,7 +207,7 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
exportNrProcessingExtent(plan.base,settings.nrRuntime,size):
pipeline::ResolutionPlan::make({request.width,request.height},request.sr,size,request.stillImage,
settings.revision,settings.srTarget,lowLatency,
- request.amdNr&&currentNrRuntime(settings.nrRuntime)==NrRuntime::LmxxfAmd?1080u:0u).nr);
+ request.amdNr&&currentNrRuntime(settings.nrRuntime)==NrRuntime::LmxxfAmd?1080u:0u,srPrescale,srOutput).nr);
}
desc.fixedExecutionPlan=execution;
return plan;
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index d3b2fa2d..c261ef20 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -126,6 +126,9 @@ struct EnhanceGraphDesc {
bool stillImage = false; // no temporal motion/FG history for a single image
uint32_t nrWidth=0,nrHeight=0; // zero preserves legacy native working extent
uint32_t flowWidth=0,flowHeight=0; // zero preserves legacy source-space NVOF extent
+ // Three-step SR (RTX Video SR): what SR reads after the prescale and what it
+ // writes before the output fit. Zero: SR reads the source and writes the work extent.
+ uint32_t srInputWidth=0,srInputHeight=0,srOutputWidth=0,srOutputHeight=0;
uint32_t fgMultiplier=2;
engine::FrameGenerationBackend frameGenerationBackend=engine::FrameGenerationBackend::Dlss;
uint32_t vfgQuality=1;
@@ -810,6 +813,9 @@ private:
bool initialized_ = false;
uint32_t srcW_ = 0, srcH_ = 0, workW_ = 3840, workH_ = 2160;
+ uint32_t srInW_ = 0, srInH_ = 0, srOutW_ = 0, srOutH_ = 0; // RTX Video SR input/result
+ bool srPrescaleActive()const{return srInW_!=srcW_||srInH_!=srcH_;}
+ bool srResolveActive()const{return srOutW_!=workW_||srOutH_!=workH_;}
uint32_t nrW_=0,nrH_=0;
uint32_t nvofW_ = 0, nvofH_ = 0, rawW_ = 0, rawH_ = 0, nvofGrid_ = 4, selectedGrid_ = 4;
bool srEnabled_ = false, nrEnabled_ = false, fgEnabled_ = false, nvofStandalone_ = false;
@@ -832,6 +838,7 @@ private:
size_t rgbPitch_=0;
ComPtr<ID3D12Resource> workRgba_;
ComPtr<ID3D12Resource> videoSrInput_,videoSrOutput_;
+ ComPtr<ID3D12Resource> srPrescaled_; // linear SR input after the three-step prescale
ComPtr<ID3D12Resource> videoHdrInput_,videoHdrOutput_;
ComPtr<ID3D12Resource> residualRgba_,nrFlow_,baseFlow_;
ComPtr<ID3D12Resource> preSrProtectionRgba_;
@@ -891,6 +898,7 @@ private:
ComputePass amdHdrEncodePass_, amdHdrRestorePass_;
float toneMapPeakNits_=0; // latched per graph/source; never varies with frame brightness
ComputePass rgbPass_,hdrVideoSrPass_;
+ ComputePass srPrescalePass_,srResolvePass_; // three-step SR area shrink before / after RTX Video SR
ComputePass downsamplePass_,residualPass_,stackProtectionPass_,flowAdaptPass_;
ComputePass flowRefinePass_,flowFillPass_,fgFlowAdaptPass_,flowClaimPass_;
// Stage-5 output stabiliser (anti-flicker). Constructed only when the
diff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.h
index e765ed3e..9264b4da 100644
--- a/include/veyra/pipeline/ResolutionPlan.h
+++ b/include/veyra/pipeline/ResolutionPlan.h
@@ -37,17 +37,93 @@ constexpr Extent srTargetExtent(SrTarget target) {
}
return {};
}
+// Three-step SR (user 2026-10-28): shrink the picture before SR, then fit the
+// SR result into a smaller output. Off/Target keep the single-step SR. A fixed
+// height fits a 16:9 box like NrSizePolicy; a manual value is 100+percent of
+// the SR input (50..90), stored the way NR stores its percent.
+enum class SrPrescale : uint32_t { Off, P720, P900, P1080, P1440 };
+inline constexpr unsigned kSrPrescaleMinimumPercent=50,kSrPrescaleMaximumPercent=90;
+constexpr bool manualSrPrescale(SrPrescale prescale){
+ return uint32_t(prescale)>=100+kSrPrescaleMinimumPercent&&uint32_t(prescale)<=100+kSrPrescaleMaximumPercent;
+}
+constexpr SrPrescale srPrescaleForPercent(unsigned percent){
+ return percent>=kSrPrescaleMinimumPercent&&percent<=kSrPrescaleMaximumPercent?SrPrescale(100+percent):SrPrescale(~0u);
+}
+constexpr unsigned srPrescalePercent(SrPrescale prescale){return manualSrPrescale(prescale)?uint32_t(prescale)-100:100;}
+constexpr bool validSrPrescale(SrPrescale prescale){return prescale<=SrPrescale::P1440||manualSrPrescale(prescale);}
+constexpr unsigned srPrescaleHeight(SrPrescale prescale){
+ switch(prescale){case SrPrescale::P720:return 720;case SrPrescale::P900:return 900;case SrPrescale::P1080:return 1080;case SrPrescale::P1440:return 1440;default:return 0;}
+}
+// Target keeps the SR result; Source returns to the source extent.
+enum class SrOutput : uint32_t { Target, Source, Qhd, Uhd4K, Uhd5K, Uhd6K, Uhd7K };
+constexpr bool validSrOutput(SrOutput output){return output<=SrOutput::Uhd7K;}
+constexpr Extent srOutputExtent(SrOutput output,Extent source){
+ switch(output){
+ case SrOutput::Source:return source;
+ case SrOutput::Qhd:return srTargetExtent(SrTarget::Qhd);
+ case SrOutput::Uhd4K:return srTargetExtent(SrTarget::Uhd4K);
+ case SrOutput::Uhd5K:return srTargetExtent(SrTarget::Uhd5K);
+ case SrOutput::Uhd6K:return srTargetExtent(SrTarget::Uhd6K);
+ case SrOutput::Uhd7K:return srTargetExtent(SrTarget::Uhd7K);
+ default:return {};
+ }
+}
+// Sizes of one SR step: input after the prescale, the SR result, the step
+// output. A prescale that leaves nothing for SR to enlarge, and an output that
+// would not shrink an enlarged result, are not applied and are reported.
+struct SrStageExtents {
+ Extent input,evaluated,output;
+ bool prescaleIneffective=false,outputIneffective=false;
+ bool enlarges()const{return evaluated!=input;}
+};
+inline SrStageExtents srStageExtents(Extent source,SrTarget target,SrPrescale prescale=SrPrescale::Off,SrOutput output=SrOutput::Target){
+ // Fit into the box, enlarging only: the single-step SR size rule.
+ const auto enlarge=[](Extent from,Extent box){
+ const double scale=std::min(double(box.width)/from.width,double(box.height)/from.height);
+ return scale>1.0?Extent{std::max(2u,uint32_t(from.width*scale+1e-6)&~1u),std::max(2u,uint32_t(from.height*scale+1e-6)&~1u)}:from;
+ };
+ const auto shrink=[](Extent from,double scale){
+ return Extent{std::max(2u,uint32_t(from.width*scale+1e-6)&~1u),std::max(2u,uint32_t(from.height*scale+1e-6)&~1u)};
+ };
+ SrStageExtents s;s.input=source;s.evaluated=enlarge(source,srTargetExtent(target));
+ if(prescale!=SrPrescale::Off){
+ const double height=srPrescaleHeight(prescale);
+ const double scale=manualSrPrescale(prescale)?srPrescalePercent(prescale)/100.0:
+ std::min({1.0,(height*16.0/9.0)/source.width,height/source.height});
+ const auto input=shrink(source,scale);
+ const auto evaluated=enlarge(input,srTargetExtent(target));
+ if(scale<1.0&&input.width<source.width&&input.height<source.height&&evaluated!=input){s.input=input;s.evaluated=evaluated;}
+ else s.prescaleIneffective=true;
+ }
+ s.output=s.evaluated;
+ if(output!=SrOutput::Target){
+ const auto box=srOutputExtent(output,source);
+ const double scale=std::min(double(box.width)/s.evaluated.width,double(box.height)/s.evaluated.height);
+ if(s.enlarges()&&scale<1.0)s.output=output==SrOutput::Source?source:shrink(s.evaluated,scale);
+ else if(s.evaluated!=box)s.outputIneffective=true;
+ }
+ return s;
+}
struct ResolutionPlan {
Extent source,base,nr,flow,fg,output;
+ // What SR reads and writes. Single-step SR: srInput==source, srOutput==base.
+ Extent srInput,srOutput;
bool srApplied=false;
+ bool srPrescaleIneffective=false,srOutputIneffective=false;
uint64_t settingsRevision=0;
- static ResolutionPlan make(Extent source,bool sr,NrSizePolicy policy,bool exporting,uint64_t revision=0,SrTarget target=SrTarget::Uhd4K,bool nrBeforeSr=false,unsigned manualHeightBudget=0) {
+ static ResolutionPlan make(Extent source,bool sr,NrSizePolicy policy,bool exporting,uint64_t revision=0,SrTarget target=SrTarget::Uhd4K,bool nrBeforeSr=false,unsigned manualHeightBudget=0,
+ SrPrescale prescale=SrPrescale::Off,SrOutput output=SrOutput::Target) {
if(!source.valid())throw std::invalid_argument("invalid SDR source extent");
if(!validSrTarget(target))throw std::invalid_argument("invalid SR target");
if(!validNrSizePolicy(policy))throw std::invalid_argument("invalid NR size policy");
- ResolutionPlan p; p.source=source;p.base=source;
- if(sr){const auto limit=srTargetExtent(target);const double scale=std::min(double(limit.width)/source.width,double(limit.height)/source.height);if(scale>1.0)p.base={std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)};}
- p.srApplied=sr&&p.base!=source;p.nr=p.base;
+ if(!validSrPrescale(prescale)||!validSrOutput(output))throw std::invalid_argument("invalid SR prescale or output");
+ ResolutionPlan p; p.source=source;p.base=p.srInput=p.srOutput=source;
+ if(sr){
+ const auto stage=srStageExtents(source,target,prescale,output);
+ p.srInput=stage.input;p.srOutput=stage.evaluated;p.base=stage.output;
+ p.srPrescaleIneffective=stage.prescaleIneffective;p.srOutputIneffective=stage.outputIneffective;
+ }
+ p.srApplied=sr&&p.srOutput!=p.srInput;p.nr=p.base;
if(nrBeforeSr&&!exporting)p.nr=source;
if(!exporting&&policy!=NrSizePolicy::Native) {
// A bounded backend supplies its existing maximum budget. Manual
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 9d027c7c..c12b4106 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -49,6 +49,8 @@ class QmlPlayerBridge : public QObject {
// a display rate is only real if the system display event can be read - the
// design requires exactly this distinction rather than reusing submit FPS).
Q_PROPERTY(QString outputSummary READ outputSummary NOTIFY snapshotChanged)
+ Q_PROPERTY(QString srStageSummary READ srStageSummary NOTIFY snapshotChanged)
+ Q_PROPERTY(QString srStageNote READ srStageNote NOTIFY snapshotChanged)
Q_PROPERTY(bool fullscreenMemorySafe READ fullscreenMemorySafe NOTIFY snapshotChanged)
Q_PROPERTY(double displayFps READ displayFps NOTIFY snapshotChanged)
Q_PROPERTY(bool displayFpsKnown READ displayFpsKnown NOTIFY snapshotChanged)
@@ -390,6 +392,10 @@ class QmlPlayerBridge : public QObject {
Q_PROPERTY(int videoSrQuality READ videoSrQuality WRITE setVideoSrQuality NOTIFY settingsChanged)
Q_PROPERTY(int dlssSrModel READ dlssSrModel WRITE setDlssSrModel NOTIFY settingsChanged)
Q_PROPERTY(QVariantList dlssSrModelChoices READ dlssSrModelChoices CONSTANT)
+ // Three-step SR (RTX Video SR). srPrescale: 0 off, 1..4 720p/900p/1080p/1440p,
+ // 150..190 a manual 50..90 %. srOutput: 0 keep the SR result, 1 source size, 2..6 2K/4K/5K/6K/7K.
+ Q_PROPERTY(int srPrescale READ srPrescale WRITE setSrPrescale NOTIFY settingsChanged)
+ Q_PROPERTY(int srOutput READ srOutput WRITE setSrOutput NOTIFY settingsChanged)
Q_PROPERTY(bool protectionEnabled READ protectionEnabled WRITE setProtectionEnabled NOTIFY settingsChanged)
Q_PROPERTY(QVariantMap protectionState READ protectionState NOTIFY protectionChanged)
Q_PROPERTY(bool colorEnabled READ colorEnabled WRITE setColorEnabled NOTIFY settingsChanged)
@@ -621,6 +627,8 @@ public:
~QmlPlayerBridge() override;
QString outputSummary() const;
+ QString srStageSummary() const;
+ QString srStageNote() const;
double displayFps() const;
bool displayFpsKnown() const;
double queuedFrames() const;
@@ -1029,6 +1037,10 @@ public:
int dlssSrModel() const;
void setDlssSrModel(int value);
QVariantList dlssSrModelChoices() const;
+ int srPrescale() const;
+ void setSrPrescale(int value);
+ int srOutput() const;
+ void setSrOutput(int value);
bool protectionEnabled() const;
void setProtectionEnabled(bool value);
QVariantMap protectionState() const;
diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qml
index 2dfb21cb..df1d56d3 100644
--- a/qml/Veyra/NodePage.qml
+++ b/qml/Veyra/NodePage.qml
@@ -1529,17 +1529,7 @@ VPage {
onPicked: id => veyra.dlssSrModel = Number(id)
}
}
- VRow {
- label: qsTr("目标尺寸")
- hint: veyra.videoSrQuality >= 1 && veyra.videoSrQuality <= 4
- ? qsTr("放大时重建细节;原尺寸时修复视频文件和串流的压缩伪影,无压缩的采集卡格式在原尺寸不运行。效果取决于片源。")
- : qsTr("目标须大于片源尺寸;已达到目标时不执行超分。")
- VSeg {
- options: [{ id: "1", label: "2K" }, { id: "2", label: "4K" }, { id: "4", label: "5K" }, { id: "5", label: "6K" }, { id: "6", label: "7K" }, { id: "3", label: "8K" }]
- current: String(veyra.srTargetIndex)
- onPicked: id => veyra.srTargetIndex = parseInt(id)
- }
- }
+ SrStageEditor { Layout.fillWidth: true; namePrefix: "node" }
VRow {
label: qsTr("超分运动来源")
hint: qsTr("零运动会限制时序重建;RTX 视频超分不使用此输入")
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index a5a84ab4..9bd4763a 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -1318,8 +1318,12 @@ VPage {
title: qsTr("超分辨率")
switchAvailable: Support.available(veyra, "sr")
summary: !switchAvailable ? Support.reason(veyra, "sr") : (veyra.srEnabled ? (veyra.srBackendChoices?.find(o => o.id === String(veyra.videoSrQuality === 0 || veyra.videoSrQuality === 5 ? veyra.videoSrQuality : 4))?.label || qsTr("RTX 视频超分")) : qsTr("已关闭"))
- + " · " + veyra.srTargetLabel
+ + " · " + (srStageShown && veyra.srPrescale > 0 ? (veyra.srPrescale >= 150 ? (veyra.srPrescale - 100) + "%" : ["", "720p", "900p", "1080p", "1440p"][veyra.srPrescale]) + "→" : "")
+ + veyra.srTargetLabel
+ + (srStageShown && veyra.srOutput > 0 ? "→" + (veyra.srOutput === 1 ? qsTr("片源尺寸") : ["", "", "2K", "4K", "5K", "6K", "7K"][veyra.srOutput]) : "")
+ (veyra.videoSrQuality > 0 ? qsTr(" · 质量 ") + veyra.videoSrQuality : "")
+ // Three-step SR shows in the summary only where it runs (RTX Video SR).
+ readonly property bool srStageShown: veyra.videoSrQuality >= 1 && veyra.videoSrQuality <= 4
on: veyra.srEnabled
open: true
onToggled: on => veyra.srEnabled = on
@@ -1345,24 +1349,7 @@ VPage {
onPicked: id => veyra.dlssSrModel = Number(id)
}
}
- VRow {
- label: qsTr("目标尺寸")
- hint: veyra.videoSrQuality >= 1 && veyra.videoSrQuality <= 4
- ? qsTr("放大时重建细节;原尺寸时修复视频文件和串流的压缩伪影,无压缩的采集卡格式在原尺寸不运行。效果取决于片源。")
- : qsTr("目标须大于片源尺寸;已达到目标时不执行超分。")
- VSeg {
- options: [
- { id: "1", label: "2K" },
- { id: "2", label: "4K" },
- { id: "4", label: "5K" },
- { id: "5", label: "6K" },
- { id: "6", label: "7K" },
- { id: "3", label: "8K" }
- ]
- current: String(veyra.srTargetIndex)
- onPicked: id => veyra.srTargetIndex = parseInt(id)
- }
- }
+ SrStageEditor { Layout.fillWidth: true; namePrefix: "list" }
VRow {
label: qsTr("超分运动来源")
hint: qsTr("零运动会限制时序重建;RTX 视频超分不使用此输入")
diff --git a/qml/Veyra/SrStageEditor.qml b/qml/Veyra/SrStageEditor.qml
new file mode 100644
index 00000000..5d2650ee
--- /dev/null
+++ b/qml/Veyra/SrStageEditor.qml
@@ -0,0 +1,109 @@
+// Three-step SR (user 2026-10-28): 先降到 -> 超分到 -> 再缩到, shared by the list
+// page's SR card and the node page's SR node. The prescale and the output fit
+// run on RTX Video SR only; with another backend those rows stay visible and
+// disabled, with the reason.
+import QtQuick
+import QtQuick.Layouts
+import "EffectSupport.js" as Support
+
+ColumnLayout {
+ id: editor
+ property string namePrefix: "list"
+ spacing: 6
+ readonly property bool stageBackend: veyra.videoSrQuality >= 1 && veyra.videoSrQuality <= 4
+ readonly property bool stageEnabled: stageBackend && Support.available(veyra, "sr")
+ // SR target box height by the UI target IDs (1 2K, 2 4K, 3 8K, 4 5K, 5 6K, 6 7K).
+ readonly property int targetHeight: ({1: 1440, 2: 2160, 3: 4320, 4: 2880, 5: 3456, 6: 4032})[veyra.srTargetIndex] || 2160
+ // A manual prescale is stored as 100 + percent (50..90).
+ readonly property bool manualPrescale: veyra.srPrescale >= 150 && veyra.srPrescale <= 190
+ property int lastManualPercent: 75
+ Connections {
+ target: veyra
+ function onSettingsChanged() { if (editor.manualPrescale) editor.lastManualPercent = veyra.srPrescale - 100 }
+ }
+ function sized(id, label, height) {
+ const tooLarge = height >= targetHeight
+ return {id: id, label: label, disabled: tooLarge, note: tooLarge ? qsTr("须小于超分目标") : ""}
+ }
+ readonly property var prescaleChoices: [
+ {id: "0", label: qsTr("关闭", "off")}, sized("1", "720p", 720), sized("2", "900p", 900),
+ sized("3", "1080p", 1080), sized("4", "1440p", 1440), {id: "manual", label: qsTr("手动")}
+ ]
+ readonly property var outputChoices: [
+ {id: "0", label: qsTr("不缩")}, {id: "1", label: qsTr("片源尺寸")}, sized("2", "2K", 1440),
+ sized("3", "4K", 2160), sized("4", "5K", 2880), sized("5", "6K", 3456), sized("6", "7K", 4032)
+ ]
+
+ VRow {
+ label: qsTr("先降到")
+ hint: editor.stageBackend
+ ? qsTr("片源本身糊时,先缩小再超分,RTX 视频超分更容易重建细节;会损失片源中真实的高分辨率细节(如原生 4K 的 HUD、字幕)。")
+ : qsTr("目前仅 RTX 视频超分支持")
+ enabled: editor.stageEnabled
+ opacity: enabled ? 1 : 0.4
+ VSelect {
+ objectName: editor.namePrefix + "-sr-prescale"
+ options: editor.prescaleChoices
+ value: editor.manualPrescale ? qsTr("手动") : (options.find(o => o.id === String(veyra.srPrescale))?.label || "")
+ onPicked: id => veyra.srPrescale = id === "manual" ? 100 + editor.lastManualPercent : Number(id)
+ }
+ }
+ VRow {
+ objectName: editor.namePrefix + "-sr-prescale-percent-row"
+ visible: editor.manualPrescale
+ enabled: editor.stageEnabled
+ opacity: enabled ? 1 : 0.4
+ label: qsTr("先降比例")
+ hint: qsTr("松开后应用 · 宽高同比例")
+ value: Math.round(prescaleSlider.displayedValue) + "%"
+ VSlider {
+ id: prescaleSlider
+ objectName: editor.namePrefix + "-sr-prescale-percent"
+ valueFromModel: true
+ resettable: true; defaultValue: 75
+ implicitWidth: 110
+ from: 50; to: 90; stepSize: 5
+ live: false // SR sizes rebuild the graph: commit once on release.
+ value: editor.manualPrescale ? veyra.srPrescale - 100 : editor.lastManualPercent
+ onMoved: value => veyra.srPrescale = 100 + Math.round(value)
+ }
+ }
+ VRow {
+ label: qsTr("超分到")
+ hint: editor.stageBackend
+ ? qsTr("放大时重建细节;原尺寸时修复视频文件和串流的压缩伪影,无压缩的采集卡格式在原尺寸不运行;开启先降到后,片源已达目标也会执行。效果取决于片源。")
+ : qsTr("目标须大于片源尺寸;已达到目标时不执行超分。")
+ VSeg {
+ objectName: editor.namePrefix + "-sr-target"
+ options: [{ id: "1", label: "2K" }, { id: "2", label: "4K" }, { id: "4", label: "5K" }, { id: "5", label: "6K" }, { id: "6", label: "7K" }, { id: "3", label: "8K" }]
+ current: String(veyra.srTargetIndex)
+ onPicked: id => veyra.srTargetIndex = parseInt(id)
+ }
+ }
+ VRow {
+ label: qsTr("再缩到")
+ hint: editor.stageBackend
+ ? qsTr("超分到更大尺寸后按面积缩回,相当于超采样;只在超分放大后执行。8K 超分耗时显著增加。")
+ : qsTr("目前仅 RTX 视频超分支持")
+ enabled: editor.stageEnabled
+ opacity: enabled ? 1 : 0.4
+ VSelect {
+ objectName: editor.namePrefix + "-sr-output"
+ options: editor.outputChoices
+ value: options.find(o => o.id === String(veyra.srOutput))?.label || ""
+ onPicked: id => veyra.srOutput = Number(id)
+ }
+ }
+ VRow {
+ objectName: editor.namePrefix + "-sr-stage-actual"
+ visible: veyra.srStageSummary.length > 0 || veyra.srStageNote.length > 0
+ label: qsTr("实际尺寸")
+ hint: veyra.srStageNote
+ Text {
+ text: veyra.srStageSummary
+ color: Theme.t2; font.family: Theme.fontUi; font.pixelSize: 11
+ wrapMode: Text.WordWrap
+ Layout.maximumWidth: 240
+ }
+ }
+}
diff --git a/qml/Veyra/qmldir b/qml/Veyra/qmldir
index 05a7c200..8874f928 100644
--- a/qml/Veyra/qmldir
+++ b/qml/Veyra/qmldir
@@ -40,6 +40,7 @@ ColourPanel 1.0 ColourPanel.qml
VScrollBar 1.0 VScrollBar.qml
VConfirm 1.0 VConfirm.qml
NrLayerEditor 1.0 NrLayerEditor.qml
+SrStageEditor 1.0 SrStageEditor.qml
AntiAliasEditor 1.0 AntiAliasEditor.qml
BeautyEditor 1.0 BeautyEditor.qml
VSpinner 1.0 VSpinner.qml
diff --git a/scripts/acceptance/sr-stage-ab.py b/scripts/acceptance/sr-stage-ab.py
new file mode 100644
index 00000000..0e7bb2e7
--- /dev/null
+++ b/scripts/acceptance/sr-stage-ab.py
@@ -0,0 +1,131 @@
+"""Three-step SR picture A/B with RTX Video SR (claude-sr-stage-20261028).
+
+Every picture goes through the real graph (veyra_sr_quality_tests stage-image in the
+task's staged copy, video-file semantics: a 4K source at a 4K target gets the existing
+native-size restore). Lossless PNG in and out.
+
+ --mode blurry --image X no reference: X is scaled to 3840x2160 (bicubic) as a soft
+ 4K, then single step vs three-step. Sharpness proxy only.
+ --mode native --image X X is a native 3840x2160 reference. Two degraded sources are
+ made from it (soft 4K: area 1920x1080, JPEG q70, bicubic back
+ to 4K; native 2K: Lanczos 2560x1440) and every result is
+ compared with the reference (PSNR / SSIM on luma).
+Crops (100 %) of the busiest regions go side by side into one PNG per region.
+usage: py -3.11 -X utf8 -B -I scripts/acceptance/sr-stage-ab.py --mode blurry|native --image PATH [--tag NAME]
+"""
+from pathlib import Path
+import argparse, io, json, os, re, subprocess
+import numpy as np
+from PIL import Image, ImageDraw
+
+B = Path('E:/项目/Veyra'); T = 'claude-sr-stage-20261028'
+A = B/'tests'/T/'app'; TMP = B/'tmp'/T/'ab'
+ap = argparse.ArgumentParser(); ap.add_argument('--mode', choices=['blurry', 'native'], required=True)
+ap.add_argument('--image', required=True); ap.add_argument('--tag', default='')
+args = ap.parse_args()
+tag = args.tag or args.mode
+OUT = B/'reports'/T/'ab'/tag; WORK = B/'tests'/T/'ab'/tag
+for p in (OUT, WORK, TMP): p.mkdir(parents=True, exist_ok=True)
+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}
+env.update(TEMP=str(TMP), TMP=str(TMP))
+
+
+def render(src, name, quality, prescale='off', target='4k', output='target'):
+ """One picture through the graph; returns (array, gpu ms of the SR stage, sizes)."""
+ run = subprocess.run([str(A/'veyra_sr_quality_tests.exe'), str(WORK/'gpu'), 'stage-image', str(src), name, str(quality), prescale, target, output, 'video'],
+ cwd=A, env=env, capture_output=True, text=True, timeout=120)
+ line = next((l for l in run.stdout.splitlines() if l.startswith('STAGE_IMAGE')), '')
+ assert run.returncode == 0 and 'passed=1' in line, (name, run.returncode, line, run.stdout[-500:])
+ fields = dict(kv.split('=', 1) for kv in line.split()[1:])
+ return np.asarray(Image.open(WORK/'gpu'/(name + '.png')).convert('RGB')), float(fields['srMs']), fields
+
+
+def luma(a):
+ a = a.astype(np.float64) / 255.0
+ return 0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]
+
+
+def psnr(a, b):
+ mse = np.mean((luma(a) - luma(b)) ** 2)
+ return float('inf') if mse == 0 else 10 * np.log10(1.0 / mse)
+
+
+def box(x, r=4):
+ # Mean over (2r+1)^2 windows via an integral image (SSIM's local statistics).
+ c = np.pad(x, r + 1, mode='edge').cumsum(0).cumsum(1); n = 2 * r + 1
+ return (c[n:, n:] - c[:-n, n:] - c[n:, :-n] + c[:-n, :-n])[:x.shape[0], :x.shape[1]] / (n * n)
+
+
+def ssim(a, b):
+ x, y = luma(a), luma(b); c1, c2 = 0.01 ** 2, 0.03 ** 2
+ mx, my = box(x), box(y); vx, vy, cxy = box(x * x) - mx * mx, box(y * y) - my * my, box(x * y) - mx * my
+ return float(np.mean(((2 * mx * my + c1) * (2 * cxy + c2)) / ((mx * mx + my * my + c1) * (vx + vy + c2))))
+
+
+def sharpness(a):
+ # Mean luma gradient magnitude (no-reference detail proxy; noise and halos raise it too).
+ y = luma(a); return float(np.mean(np.hypot(np.diff(y, axis=1)[:-1], np.diff(y, axis=0)[:, :-1])))
+
+
+def crops(images, labels, reference=None, size=480, count=3, prefix='crop'):
+ """The `count` busiest non-overlapping windows of the first image, all images side by side."""
+ base = luma(images[0]); g = np.hypot(*np.gradient(base)); h, w = base.shape; picks = []
+ energy = box(g, size // 2)
+ for _ in range(count):
+ y, x = np.unravel_index(np.argmax(energy), energy.shape)
+ y0, x0 = int(np.clip(y - size // 2, 0, h - size)), int(np.clip(x - size // 2, 0, w - size))
+ picks.append((x0, y0)); energy[max(0, y0 - size):y0 + 2 * size, max(0, x0 - size):x0 + 2 * size] = -1
+ out = []
+ for i, (x0, y0) in enumerate(picks):
+ tiles = [(reference, 'reference')] if reference is not None else []
+ tiles += list(zip(images, labels))
+ sheet = Image.new('RGB', (size * len(tiles), size + 24), (24, 24, 24)); draw = ImageDraw.Draw(sheet)
+ for k, (img, label) in enumerate(tiles):
+ sheet.paste(Image.fromarray(img[y0:y0 + size, x0:x0 + size]), (k * size, 24)); draw.text((k * size + 6, 5), label, fill=(240, 240, 240))
+ path = OUT/f'{prefix}-{i + 1}-x{x0}-y{y0}.png'; sheet.save(path); out.append(str(path))
+ return out
+
+
+source = Image.open(args.image).convert('RGB')
+report = dict(mode=args.mode, image=str(args.image), imageSize=list(source.size), cases={})
+if args.mode == 'blurry':
+ soft = source.resize((3840, 2160), Image.BICUBIC) if source.size != (3840, 2160) else source
+ soft_path = WORK/'soft-4k.png'; soft.save(soft_path)
+ cases = [('input', 0, 'off', '4k', 'target'), ('vsr4-native', 4, 'off', '4k', 'target'),
+ ('vsr4-1440-4k', 4, '1440', '4k', 'target'), ('vsr4-1080-4k', 4, '1080', '4k', 'target'),
+ ('vsr4-1080-8k-4k', 4, '1080', '8k', '4k'), ('vsr2-1080-4k', 2, '1080', '4k', 'target')]
+ images, labels = [], []
+ for name, q, pre, tgt, outp in cases:
+ img, ms, fields = render(soft_path, name, q, pre, tgt, outp)
+ report['cases'][name] = dict(srMs=ms, srInput=fields['srInput'], srOutput=fields['srOutput'], output=fields['output'], sharpness=sharpness(img))
+ images.append(img); labels.append(f'{name} {ms:.1f} ms' if ms > 0 else name)
+ report['crops'] = crops(images, labels)
+else:
+ assert source.size == (3840, 2160), 'native mode needs a 3840x2160 reference'
+ ref = np.asarray(source)
+ buf = io.BytesIO(); source.resize((1920, 1080), Image.BOX).save(buf, 'JPEG', quality=70)
+ soft = Image.open(io.BytesIO(buf.getvalue())).convert('RGB').resize((3840, 2160), Image.BICUBIC)
+ soft_path = WORK/'soft-4k.png'; soft.save(soft_path)
+ qhd_path = WORK/'native-2k.png'; source.resize((2560, 1440), Image.LANCZOS).save(qhd_path)
+ groups = {'soft-4k': (soft_path, [('input', 0, 'off', '4k', 'target'), ('vsr4-native', 4, 'off', '4k', 'target'),
+ ('vsr4-1440-4k', 4, '1440', '4k', 'target'), ('vsr4-1080-4k', 4, '1080', '4k', 'target'),
+ ('vsr4-1080-8k-4k', 4, '1080', '8k', '4k')]),
+ 'native-2k': (qhd_path, [('vsr4-2k-4k', 4, 'off', '4k', 'target'), ('vsr4-2k-8k-4k', 4, 'off', '8k', '4k'),
+ ('vsr4-1080-4k', 4, '1080', '4k', 'target')])}
+ report['crops'] = {}
+ for group, (src, cases) in groups.items():
+ images, labels = [], []
+ if group == 'native-2k':
+ up = np.asarray(Image.open(src).resize((3840, 2160), Image.BICUBIC))
+ report['cases'][group + '/bicubic'] = dict(psnr=psnr(up, ref), ssim=ssim(up, ref), sharpness=sharpness(up))
+ images.append(up); labels.append('bicubic')
+ for name, q, pre, tgt, outp in cases:
+ img, ms, fields = render(src, f'{group}-{name}', q, pre, tgt, outp)
+ assert img.shape == ref.shape, (name, img.shape)
+ report['cases'][group + '/' + name] = dict(srMs=ms, srInput=fields['srInput'], srOutput=fields['srOutput'], output=fields['output'],
+ psnr=psnr(img, ref), ssim=ssim(img, ref), sharpness=sharpness(img))
+ images.append(img); labels.append(f'{name} {ms:.1f} ms' if ms > 0 else name)
+ report['crops'][group] = crops(images, labels, reference=ref, prefix=group)
+ report['referenceSharpness'] = sharpness(ref)
+(OUT/'ab.json').write_text(json.dumps(report, ensure_ascii=False, indent=1), 'utf8')
+print(json.dumps(report, ensure_ascii=False, indent=1))
diff --git a/scripts/acceptance/sr-stage-ui.py b/scripts/acceptance/sr-stage-ui.py
new file mode 100644
index 00000000..1e1a18e5
--- /dev/null
+++ b/scripts/acceptance/sr-stage-ui.py
@@ -0,0 +1,59 @@
+"""Three-step SR rows in the real app (claude-sr-stage-20261028).
+
+Runs this tree's build in the task's staged copy (tmp stage_app.py: hard links to the
+2.1.1 portable donor, this build's EXE / shaders / QML), on a private profile, playing a
+4K file with RTX Video SR while sr-stage-ui.qml drives the list SR card. Main.qml gets the
+test Loader only inside that copy.
+usage: py -3.11 -X utf8 -B -I scripts/acceptance/sr-stage-ui.py [media]
+"""
+from pathlib import Path
+import argparse, json, os, shutil, subprocess, sys
+
+parser=argparse.ArgumentParser()
+parser.add_argument('media',nargs='?',default='E:/项目/Veyra/tests/nr-manual-scale-20261024/media/nr-4k30.mp4')
+parser.add_argument('--task',default='claude-sr-stage-20261028')
+args=parser.parse_args()
+assert args.task.startswith(('codex-','claude-')) and '/' not in args.task and '\\' not in args.task and '..' not in args.task
+B = Path('E:/项目/Veyra'); T = args.task; R = Path(__file__).resolve().parents[2]
+A = B/'tests/claude-sr-stage-20261028/app'; P = B/'tests'/T/'profile-ui'; L = B/'logs'/T/'ui'; TMP = B/'tmp'/T/'ui'; OUT = B/'reports'/T
+MEDIA = Path(args.media)
+assert (A/'veyra_qml_ui.exe').exists(), 'run the task stage_app.py first'
+for p in [L, TMP, OUT]: p.mkdir(parents=True, exist_ok=True)
+
+
+def replace(p, data):
+ p.parent.mkdir(parents=True, exist_ok=True)
+ if p.exists(): p.unlink() # never write through a hard link
+ p.write_bytes(data)
+
+
+if P.exists(): shutil.rmtree(P)
+P.mkdir(parents=True)
+(P/'qml-preferences.v1.json').write_text(json.dumps(dict(language='zh-CN', autoResume=False, prewarmEnhancement=False)), 'utf8')
+main_src = R/'qml/Veyra/Main.qml'; main = main_src.read_text('utf8'); pos = main.rfind('}')
+loader = ('\nLoader { anchors.fill: parent; source: ' + json.dumps((R/'scripts/acceptance/sr-stage-ui.qml').as_uri()) +
+ '; onLoaded: item.media=' + json.dumps(MEDIA.as_posix()) + ' }\n')
+replace(A/'qml/Veyra/Main.qml', (main[:pos] + loader + main[pos:]).encode('utf8'))
+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}
+log_file = L/'engine.log'; console = L/'console.log'
+for f in (log_file, console):
+ if f.exists(): f.unlink()
+env.update(TEMP=str(TMP), TMP=str(TMP), APPDATA=str(P/'AppData'), LOCALAPPDATA=str(P/'LocalAppData'), CUDA_CACHE_PATH=str(TMP/'cuda'),
+ QML_DISABLE_DISK_CACHE='1', QT_FORCE_STDERR_LOGGING='1', VEYRA_LOG_FILE=str(log_file))
+try:
+ with console.open('wb') as f:
+ run = subprocess.run([str(A/'veyra_qml_ui.exe'), '--page', 'pro', '--size', '1600x900', '--data-dir', str(P), '--exit-after', '200000'],
+ cwd=A, env=env, stdout=f, stderr=subprocess.STDOUT, timeout=240)
+finally:
+ replace(A/'qml/Veyra/Main.qml', main_src.read_bytes())
+text = console.read_text('utf8', errors='replace')
+lines = log_file.read_text('utf8', errors='replace').splitlines() if log_file.exists() else []
+grab = lambda tag: [l.split('] ', 2)[-1] for l in lines if tag in l]
+result = dict(exit=run.returncode, media=str(MEDIA), passed='SR_STAGE_UI_PASS' in text and 'SR_STAGE_UI_FAIL' not in text,
+ steps=grab('[sr-stage-test]'), videoSr=grab('[video-sr] selected'), resolution=grab('[resolution] source=')[:12],
+ accepted=grab('accepted srTarget=')[:12],
+ qmlErrors=[l for l in text.splitlines() if any(s in l for s in ['ReferenceError:', 'TypeError:', 'Binding loop detected', 'is not a type', 'ambiguous'])][:8],
+ log=str(log_file))
+(OUT/'sr-stage-ui.json').write_text(json.dumps(result, ensure_ascii=False, indent=1), 'utf8')
+print(json.dumps(result, ensure_ascii=False, indent=1))
+sys.exit(0 if result['passed'] and not result['qmlErrors'] else 1)
diff --git a/scripts/acceptance/sr-stage-ui.qml b/scripts/acceptance/sr-stage-ui.qml
new file mode 100644
index 00000000..855e2476
--- /dev/null
+++ b/scripts/acceptance/sr-stage-ui.qml
@@ -0,0 +1,101 @@
+// Loaded only into a private staging copy, never the user's running package.
+// claude-sr-stage-20261028: the three-step SR rows of the list SR card, driven
+// through the controls themselves while a 4K file plays with RTX Video SR.
+import QtQuick
+Item {
+ id: test
+ property string media: ""
+ function find(name) {
+ let hit = null
+ const walk = item => { if (hit) return; if (item.objectName === name) { hit = item; return } for (const c of item.children) walk(c) }
+ walk(test.parent.parent) // the Loader's parent: the window's content item
+ return hit
+ }
+ Timer {
+ interval: 500; running: test.media.length > 0; repeat: true
+ property int step: 0
+ property int ticks: 0
+ property int total: 0
+ function check(ok, label) { if (!ok) throw new Error(label); veyra.logUi("sr-stage-test", "PASS " + label) }
+ function next(n) { step = n; ticks = 0 }
+ function settled() { return ticks >= 6 && !veyra.applying && veyra.running }
+ onTriggered: { try {
+ ++ticks; ++total; if (total > 400) throw new Error("bounded step=" + step)
+ if (step === 0) {
+ if (ticks < 4) return
+ veyra.muted = true; veyra.fgEnabled = false; veyra.nrEnabled = false
+ veyra.srEnabled = true; veyra.videoSrQuality = 3; veyra.srTargetIndex = 2
+ veyra.openPath(test.media); next(1); return
+ }
+ if (step === 1) {
+ if (!settled()) return
+ check(veyra.srActive, "RTX Video SR restores the 4K file at its size: " + veyra.statusText)
+ check(veyra.srStageSummary === "", "single step shows no three-step sizes")
+ const prescale = find("list-sr-prescale"), output = find("list-sr-output")
+ check(prescale && output && prescale.enabled && output.enabled, "the list SR card has both rows, enabled for RTX Video SR")
+ prescale.picked("3"); next(2); return // 1080p, through the control
+ }
+ if (step === 2) {
+ if (!settled()) return
+ check(veyra.srPrescale === 3, "the prescale control sets 1080p")
+ check(veyra.srActive && veyra.srStageSummary === "3840x2160 → 1920x1080 → 3840x2160", "running sizes " + veyra.srStageSummary)
+ find("list-sr-target").picked("3"); next(3); return // 8K
+ }
+ if (step === 3) {
+ if (!settled()) return
+ find("list-sr-output").picked("3"); next(4); return // fit 4K
+ }
+ if (step === 4) {
+ if (!settled()) return
+ check(veyra.srOutput === 3, "the output control sets 4K")
+ check(veyra.srStageSummary === "3840x2160 → 1920x1080 → 7680x4320 → 3840x2160", "running sizes " + veyra.srStageSummary)
+ check(veyra.outputSummary === "3840x2160", "the chain output stays 4K: " + veyra.outputSummary)
+ find("list-sr-prescale").picked("manual"); next(5); return
+ }
+ if (step === 5) {
+ if (!settled()) return
+ check(veyra.srPrescale === 175 && find("list-sr-prescale-percent-row").visible, "manual prescale starts at 75 %")
+ check(veyra.srStageSummary === "3840x2160 → 2880x1620 → 7680x4320 → 3840x2160", "running sizes " + veyra.srStageSummary)
+ // A 2K target after a 1440p prescale cannot enlarge: reported, not applied.
+ find("list-sr-output").picked("0"); veyra.srTargetIndex = 1; veyra.srPrescale = 4; next(6); return
+ }
+ if (step === 6) {
+ if (!settled()) return
+ check(veyra.srStageNote.indexOf("先降到未生效") === 0, "an ineffective prescale is reported: " + veyra.srStageNote)
+ check(find("list-sr-prescale").options.find(o => o.id === "4").disabled === true, "1440p is marked unavailable for a 2K target")
+ veyra.videoSrQuality = 5; next(7); return // AMD FSR
+ }
+ if (step === 7) {
+ if (!settled()) return
+ check(!find("list-sr-prescale").enabled && !find("list-sr-output").enabled, "another SR backend disables both rows")
+ const before = veyra.srPrescale; veyra.srPrescale = 3
+ check(veyra.srPrescale === before, "the bridge refuses a prescale edit for another backend")
+ veyra.videoSrQuality = 3; veyra.srTargetIndex = 2; veyra.srPrescale = 0; next(8); return
+ }
+ if (step === 8) {
+ if (!settled()) return
+ check(veyra.srStageSummary === "" && veyra.srStageNote === "", "prescale off restores the single step")
+ veyra.nodeMode = 1
+ check(veyra.addEffect("sr") >= 0, "add an SR node to the initially empty node graph")
+ veyra.navigate("node"); next(9); return
+ }
+ if (step === 9) {
+ if (!settled()) return
+ veyra.nrEnabled = false; veyra.srEnabled = true
+ veyra.videoSrQuality = 3; veyra.srTargetIndex = 2
+ const prescale = find("node-sr-prescale"), output = find("node-sr-output")
+ if (!prescale || !output) return
+ check(prescale.enabled && output.enabled, "node SR editor exposes both enabled rows")
+ prescale.picked("3"); output.picked("0"); next(10); return
+ }
+ if (step === 10) {
+ if (!settled()) return
+ check(veyra.nodeMode === 1 && veyra.srActive && veyra.srPrescale === 3,
+ "node editor applies the prescale through its control")
+ check(veyra.srStageSummary === "3840x2160 → 1920x1080 → 3840x2160",
+ "node editor running sizes " + veyra.srStageSummary)
+ veyra.logUi("sr-stage-test", "SR_STAGE_UI_PASS"); console.log("SR_STAGE_UI_PASS"); Qt.quit(); return
+ }
+ } catch (e) { veyra.logUi("sr-stage-test", "SR_STAGE_UI_FAIL " + e.message); console.log("SR_STAGE_UI_FAIL " + e.message); Qt.quit() } }
+ }
+}
diff --git a/shaders/SrResolve.hlsl b/shaders/SrResolve.hlsl
new file mode 100644
index 00000000..e5400dc2
--- /dev/null
+++ b/shaders/SrResolve.hlsl
@@ -0,0 +1,38 @@
+// Three-step SR (2026-10-28): fits the RTX Video SR result into the smaller
+// work extent. Each SR texel is first decoded (SDR, as ScaleBlit's decode) or
+// HDR-restored (as HdrVideoSrRestore, base and proxy sampled at the texel's
+// centre), then the linear values are averaged with NrDownsample's exact area
+// weights. No full-size linear intermediate is written.
+#include "HdrColor.hlsli"
+Texture2D<float4> hdrBase:register(t0);
+Texture2D<float4> proxyInput:register(t1);
+Texture2D<float4> proxyOutput:register(t2);
+RWTexture2D<float4> outputTex:register(u0);
+cbuffer Dims:register(b0){uint sourceW;uint sourceH;uint outW;uint outH;float hdr;float3 unused;}
+float3 Decode(float3 c){return select(c<=.04045,c/12.92,pow((c+.055)/1.055,2.4));}
+float4 Texel(uint2 p){
+ const float4 c=proxyOutput[p];
+ if(hdr<.5)return float4(Decode(max(c.rgb,0.0)),c.a);
+ uint bw,bh;hdrBase.GetDimensions(bw,bh);
+ float2 pos=(float2(p)+.5)*float2(bw,bh)/float2(sourceW,sourceH)-.5;
+ int2 q=int2(floor(pos)),last=int2(bw,bh)-1;float2 f=frac(pos);
+ float3 base=0,proxy=0;
+ for(int y=0;y<2;++y)for(int x=0;x<2;++x){
+ int2 s=clamp(q+int2(x,y),int2(0,0),last);
+ float weight=(x?f.x:1-f.x)*(y?f.y:1-f.y);
+ base+=hdrBase[s].rgb*weight;
+ proxy+=proxyInput[s].rgb*weight;
+ }
+ return float4(HdrRestore(base,Decode(proxy),Decode(c.rgb)),1);
+}
+[numthreads(16,16,1)]void main(uint3 id:SV_DispatchThreadID){
+ if(id.x>=outW||id.y>=outH)return;
+ float2 low=float2(id.xy)*float2(sourceW,sourceH)/float2(outW,outH);
+ float2 high=float2(id.xy+1)*float2(sourceW,sourceH)/float2(outW,outH);
+ float4 sum=0;float weights=0;
+ for(uint y=(uint)floor(low.y);y<(uint)ceil(high.y);++y)for(uint x=(uint)floor(low.x);x<(uint)ceil(high.x);++x){
+ float weight=max(0,min(high.x,x+1.0)-max(low.x,(float)x))*max(0,min(high.y,y+1.0)-max(low.y,(float)y));
+ sum+=Texel(uint2(min(x,sourceW-1),min(y,sourceH-1)))*weight;weights+=weight;
+ }
+ outputTex[id.xy]=sum/max(weights,1e-6);
+}
diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cpp
index f5d38491..ea40b2d3 100644
--- a/src/engine/EffectChain.cpp
+++ b/src/engine/EffectChain.cpp
@@ -518,7 +518,8 @@ ChainValidation compileChainExecutionPlan(const EffectChain& chain, const ChainE
if (chain.mode != ChainMode::List && chain.mode != ChainMode::Node) return {false, "未知链路模式"};
const auto validation = validateChain(chain);
if (!validation.accepted) return validation;
- if (!request.source.valid() || !pipeline::validSrTarget(request.srTarget))
+ if (!request.source.valid() || !pipeline::validSrTarget(request.srTarget) ||
+ !pipeline::validSrPrescale(request.srPrescale) || !pipeline::validSrOutput(request.srOutput))
return {false, "执行计划尺寸或超分目标非法"};
// Retain storage ordinals even when an earlier instance is disabled. This
@@ -534,20 +535,21 @@ ChainValidation compileChainExecutionPlan(const EffectChain& chain, const ChainE
if (node.enabled && node.type == EffectType::NrEnhance) nrFirst = node.nr.lowLatencyPairing;
}
nrFirst = nrFirst && !request.stillImage && !request.exportJob;
- const auto srExtent = pipeline::ResolutionPlan::make(request.source, true,
- pipeline::NrSizePolicy::Native, true, 0, request.srTarget).base;
+ // SR processing is its evaluated size; a three-step output fit can make
+ // the step output smaller than that.
+ const auto srStage = pipeline::srStageExtents(request.source, request.srTarget, request.srPrescale, request.srOutput);
ChainExecutionPlan plan;
auto cursor = request.source;
const auto append = [&](uint32_t index) {
const auto& node = chain.nodes[index];
if (!node.enabled) return;
- if (node.type == EffectType::SuperResolution && cursor == srExtent) return;
+ if (node.type == EffectType::SuperResolution && !srStage.enlarges() && cursor == srStage.output) return;
ChainExecutionStep step;
step.type = node.type; step.nodeIndex = index;
step.parameterIndex = parameterIndices[index];
step.resourceIndex = plan.resourceCounts[size_t(node.type)]++;
step.input = step.processing = step.output = cursor;
- if (node.type == EffectType::SuperResolution) step.processing = step.output = srExtent;
+ if (node.type == EffectType::SuperResolution) { step.processing = srStage.evaluated; step.output = srStage.output; }
if (node.type == EffectType::NrEnhance) {
step.processing = request.exportJob&&!request.stillImage?
exportNrProcessingExtent(cursor,node.nr.runtime,node.nr.sizePolicy):
@@ -589,6 +591,7 @@ ChainValidation compileChainExecutionPlan(const EffectChain& chain, const ChainE
ChainGlobalSettings ChainGlobalSettings::capture(const EnhancementSettings& s) {
ChainGlobalSettings c;
c.srTarget = s.srTarget; c.videoSrQuality = s.videoSrQuality; c.dlssSrModel = s.dlssSrModel;
+ c.srPrescale = s.srPrescale; c.srOutput = s.srOutput;
c.fgBackend = s.frameGenerationBackend; c.flow = s.flow;
c.vfgQuality=s.vfgQuality;
c.opticalFlowBackend = s.opticalFlowBackend; c.amdFlowHalfResolution = s.amdFlowHalfResolution;
@@ -603,6 +606,7 @@ void ChainGlobalSettings::apply(EnhancementSettings& s) const {
s.hdrOutputMode=hdrOutputMode;s.fgMotion=fgMotion;s.srMotion=srMotion;s.nrMotion=nrMotion;
s.hdrCurve=hdrCurve;s.hdrMetadata=hdrMetadata;
s.srTarget = srTarget; s.videoSrQuality = videoSrQuality; s.dlssSrModel = dlssSrModel;
+ s.srPrescale = srPrescale; s.srOutput = srOutput;
s.frameGenerationBackend = fgBackend; s.flow = flow;
s.vfgQuality=vfgQuality;
s.opticalFlowBackend = opticalFlowBackend; s.amdFlowHalfResolution = amdFlowHalfResolution;
@@ -623,6 +627,7 @@ void ChainConfiguration::apply(EnhancementSettings& s) const {
bool ChainConfiguration::operator==(const ChainConfiguration& other) const {
return chain == other.chain && srTarget == other.srTarget && videoSrQuality == other.videoSrQuality && dlssSrModel == other.dlssSrModel &&
+ srPrescale == other.srPrescale && srOutput == other.srOutput &&
fgBackend == other.fgBackend && vfgQuality == other.vfgQuality && flow == other.flow && opticalFlowBackend == other.opticalFlowBackend &&
amdFlowHalfResolution == other.amdFlowHalfResolution && nrPolicy == other.nrPolicy &&
// The author's own rendering globals had the same blind spot: a change to
@@ -721,6 +726,8 @@ bool requiresGraphRebuild(const EnhancementSettings& savedPrevious, const Enhanc
if ((previous.nrHoldStrength > 0.0f) != (next.nrHoldStrength > 0.0f)) return true;
if (previous.nrPolicy != next.nrPolicy) return true;
if (previous.srTarget != next.srTarget) return true;
+ // Three-step SR changes what SR reads and writes.
+ if (previous.srPrescale != next.srPrescale || previous.srOutput != next.srOutput) return true;
// A different DLSS SR model (render preset) needs a new SR feature.
if (previous.dlssSrModel != next.dlssSrModel) return true;
if (previous.frameGenerationBackend != next.frameGenerationBackend) return true;
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 5e598e22..4ed83c74 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1656,7 +1656,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.nrBeforeSr!=nextDesc.nrBeforeSr||
gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||
gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||
- gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight)rebuild=true;
+ gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight||
+ gd.srInputWidth!=nextDesc.srInputWidth||gd.srInputHeight!=nextDesc.srInputHeight||
+ gd.srOutputWidth!=nextDesc.srOutputWidth||gd.srOutputHeight!=nextDesc.srOutputHeight)rebuild=true;
bool accepted=ring.drainQueue();out={};hasOutput=false;
resetRecord->rebuilt=rebuild;
markResetStage(diagnostics::ResetStage::Drain);
@@ -2771,7 +2773,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
for(size_t stage=0;stage<measured.gpu.size();++stage){const auto& sample=measured.gpu[stage];if(sample.state==diagnostics::SampleState::Measured&&sample.milliseconds&&sample.end&&sample.end!=lastGpuSampleEnd[stage]){gpuStageTimes[stage].add(*sample.milliseconds);lastGpuSampleEnd[stage]=sample.end;}}
- measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;
+ measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr,0,runningSrPrescale(options.settings,ctx.adapter().isNvidia),runningSrOutput(options.settings,ctx.adapter().isNvidia));measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;
LiveStats completed;if(liveScheduler)completed=liveStats;
uint64_t skipped=0;{std::lock_guard lock(mutex_);skipped=snapshot_.captureRateSkipped-rateSkippedBase;}
frameFlow->update([&](auto& m){m.counters.captureReceived=captureStats.received-captureFlowBase.received;m.counters.mailboxOverwritten=captureStats.dropped-captureFlowBase.dropped;m.counters.sourceSkippedBeforeGraph=skipped;m.slotReuseWaitCount=slotWaitCount;m.slotReuseWaitMs=slotWaitMilliseconds;m.counters.commandSlotsInFlight=slotsInFlight;m.counters.commandSlotHighWater=std::max(m.counters.commandSlotHighWater,slotsInFlight);});
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index 9b348263..c040985e 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -31,7 +31,8 @@ struct Shared {
// process boundary; a worker that sees another version refuses the job
// instead of reading a mismatched layout.
// 10: 32-node chain with anti-aliasing; 11: beauty payloads and face detection.
- static constexpr DWORD kVersion=11;
+ // 12: SR prescale/output fields change the shared settings layout.
+ static constexpr DWORD kVersion=12;
DWORD signature=magic,version=kVersion,bytes=sizeof(Shared);
EnhancementSettings settings;
EffectChain chain;
diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cpp
index ad3c8a38..fbcfe354 100644
--- a/src/engine/PresetLibrary.cpp
+++ b/src/engine/PresetLibrary.cpp
@@ -14,7 +14,7 @@ namespace {
// Six full grades per entry (plus the legacy first-grade field), up to 64
// entries. Never remove the file-size guard as LUT names are external input.
constexpr size_t kMaxPresetBytes = 2u * 1024u * 1024u;
-void writeRendering(std::ostream& out,const ChainGlobalSettings& g,bool vfg=false,bool tuning=false,bool dlss=false){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);if(vfg)out<<' '<<g.vfgQuality;
+void writeRendering(std::ostream& out,const ChainGlobalSettings& g,bool vfg=false,bool tuning=false,bool dlss=false,bool srStage=false){out<<' '<<int(g.hdrOutputMode)<<' '<<int(g.fgMotion)<<' '<<int(g.srMotion)<<' '<<int(g.nrMotion);if(vfg)out<<' '<<g.vfgQuality;
// Static HDR output tuning: library v11 / session v6.
// Older mainline versions keep their original NR/Flow layout.
if(tuning)out<<' '<<g.hdrCurve.shadowLiftEv100<<' '<<g.hdrCurve.shadowRangeNits<<' '<<g.hdrCurve.midGrayNits<<' '
@@ -22,8 +22,10 @@ void writeRendering(std::ostream& out,const ChainGlobalSettings& g,bool vfg=fals
<<g.hdrCurve.enabled<<' '<<(g.hdrMetadata.enabled?1:0)<<' '<<g.hdrMetadata.masteringPeakNits<<' '
<<g.hdrMetadata.maxCllNits<<' '<<g.hdrMetadata.maxFallNits<<' '<<g.hdrMetadata.masteringMinNitsX10000
<<' '<<g.hdrCurve.strengthPercent<<' '<<g.hdrCurve.displayPeakNits;
- if(dlss)out<<' '<<g.dlssSrModel;}
-bool readRendering(std::istream& in,ChainGlobalSettings& g,bool vfg=false,bool tuning=false,bool dlss=false){
+ if(dlss)out<<' '<<g.dlssSrModel;
+ // Three-step SR prescale / output: library v16, session v11.
+ if(srStage)out<<' '<<uint32_t(g.srPrescale)<<' '<<uint32_t(g.srOutput);}
+bool readRendering(std::istream& in,ChainGlobalSettings& g,bool vfg=false,bool tuning=false,bool dlss=false,bool srStage=false){
int hdr,fg,sr,nr;
if(!(in>>hdr>>fg>>sr>>nr))return false;
g.hdrOutputMode=HdrOutputMode(hdr);g.fgMotion=MotionSource(fg);g.srMotion=MotionSource(sr);g.nrMotion=MotionSource(nr);
@@ -38,6 +40,7 @@ bool readRendering(std::istream& in,ChainGlobalSettings& g,bool vfg=false,bool t
if(!g.hdrCurve.valid()||!g.hdrMetadata.valid())return false;
}
if(dlss&&(!(in>>g.dlssSrModel)||g.dlssSrModel>=kDlssSrModelCount))return false;
+ if(srStage){uint32_t prescale=0,output=0;if(!(in>>prescale>>output))return false;g.srPrescale=pipeline::SrPrescale(prescale);g.srOutput=pipeline::SrOutput(output);}
EnhancementSettings s;g.apply(s);return s.validate().empty();
}
void applyRenderingPreset(const PresetEntry& e,EnhancementSettings& s){
@@ -93,6 +96,7 @@ void PresetLibrary::addBuiltins() {
bool PresetLibrary::load() {
error_.clear();
addBuiltins();
+ const auto directSrStage=std::filesystem::path(path_).concat(L".sr-stage");
const auto directBeauty=std::filesystem::path(path_).concat(L".beauty");
const auto directEffects=std::filesystem::path(path_).concat(L".effects");
const auto directNr=std::filesystem::path(path_).concat(L".nr-model");
@@ -132,6 +136,9 @@ bool PresetLibrary::load() {
const auto beautyPath=std::filesystem::path(path_).concat(L".beauty");
if(std::filesystem::exists(directBeauty))path_=directBeauty;
else if(std::filesystem::exists(beautyPath))path_=beautyPath;
+ const auto srStagePath=std::filesystem::path(path_).concat(L".sr-stage");
+ if(std::filesystem::exists(directSrStage))path_=directSrStage;
+ else if(std::filesystem::exists(srStagePath))path_=srStagePath;
if (!std::filesystem::exists(path_)) return true;
std::error_code ec;
const auto size = std::filesystem::file_size(path_, ec);
@@ -227,6 +234,9 @@ bool PresetLibrary::save() {
if (!parse(data, checked, checkedDefault, error_)) return false;
// Opting into a new model must leave the older build's library intact.
// v14 (anti-aliasing nodes, chains past 16 nodes) and v15 (beauty nodes) get their own files too.
+ // v16 (three-step SR) as well.
+ if(data.starts_with("VEYRA_PRESET_LIBRARY 16")&&!path_.wstring().ends_with(L".sr-stage"))path_=std::filesystem::path(path_).concat(L".sr-stage");
+ if(!path_.wstring().ends_with(L".sr-stage")){
if(data.starts_with("VEYRA_PRESET_LIBRARY 15")&&!path_.wstring().ends_with(L".beauty"))path_=std::filesystem::path(path_).concat(L".beauty");
if(!path_.wstring().ends_with(L".beauty")){
if(data.starts_with("VEYRA_PRESET_LIBRARY 14")&&!path_.wstring().ends_with(L".effects"))path_=std::filesystem::path(path_).concat(L".effects");
@@ -254,6 +264,7 @@ bool PresetLibrary::save() {
}
}
}
+ }
std::error_code ec;
std::filesystem::create_directories(path_.parent_path(), ec);
const auto temporary = std::filesystem::path(path_).concat(L".tmp");
@@ -701,7 +712,15 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
const bool beauty=std::any_of(entries_.begin(),entries_.end(),[&](const auto& e){
return beautyChain(e.chain)||(e.nodeConfiguration&&(beautyChain(e.nodeConfiguration->chain)||
(e.nodeConfiguration->editor&&beautyChain(e.nodeConfiguration->editor->nodes))));});
- const int version=std::max(minimumVersion, beauty?15:effects?14:nrModel?13:dlss?12:tuning?11:flow?10:correctionExtended?9:correction?8:vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);
+ // v16: three-step SR prescale / output in any stored globals.
+ const auto srStageOf=[](const ChainGlobalSettings& g){return g.srPrescale!=pipeline::SrPrescale::Off||g.srOutput!=pipeline::SrOutput::Target;};
+ const bool srStage=std::any_of(entries_.begin(),entries_.end(),[&](const auto& e){
+ if(e.globals&&srStageOf(*e.globals))return true;
+ if(!e.nodeConfiguration)return false;
+ const auto& c=*e.nodeConfiguration;
+ return srStageOf(c)||(c.editor&&c.editor->globals&&srStageOf(*c.editor->globals));
+ });
+ const int version=std::max(minimumVersion, srStage?16:beauty?15:effects?14:nrModel?13:dlss?12:tuning?11:flow?10:correctionExtended?9: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)) << ' '
@@ -755,7 +774,7 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
}
if(version>=6){
o<<' '<<e.globals.has_value();
- if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g,version>=7,version>=11,version>=12);}
+ if(e.globals){const auto& g=*e.globals;o<<' '<<int(g.srTarget)<<' '<<g.videoSrQuality<<' '<<int(g.fgBackend)<<' '<<int(g.flow)<<' '<<int(g.opticalFlowBackend)<<' '<<g.amdFlowHalfResolution<<' '<<int(g.nrPolicy);writeRendering(o,g,version>=7,version>=11,version>=12,version>=16);}
}
if(version>=10){
o<<' '<<e.flow.has_value();
@@ -775,7 +794,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
std::string magic, quoted;
int version = 0;
size_t count = 0;
- const int allowedVersion=maxVersion>0?std::min(maxVersion,15):15;
+ const int allowedVersion=maxVersion>0?std::min(maxVersion,16):16;
if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > allowedVersion) { error = L"预设库格式或版本不支持"; return false; }
if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }
def = wide(quoted);
@@ -887,7 +906,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
if(present){ChainGlobalSettings g;int target,backend,flow,optical,half,policy;
if(!(in>>target>>g.videoSrQuality>>backend>>flow>>optical>>half>>policy)||half<0||half>1)return false;
g.srTarget=pipeline::SrTarget(target);g.fgBackend=FrameGenerationBackend(backend);g.flow=FlowQuality(flow);g.opticalFlowBackend=OpticalFlowBackend(optical);g.amdFlowHalfResolution=half!=0;g.nrPolicy=pipeline::NrSizePolicy(policy);
- if(!readRendering(in,g,version>=7,version>=11,version>=12))return false;e.globals=g;
+ if(!readRendering(in,g,version>=7,version>=11,version>=12,version>=16))return false;e.globals=g;
}
}
if(version>=10){
@@ -940,7 +959,10 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
return n.type==EffectType::Beauty;});};
const bool beauty=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){
return beautyChain(c.chain)||(c.editor&&beautyChain(c.editor->nodes));});
- const int version = beauty?10:effects?9:nrModel?8:dlss?7:tuning?6:vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;
+ const auto srStageOf=[](const ChainGlobalSettings& g){return g.srPrescale!=pipeline::SrPrescale::Off||g.srOutput!=pipeline::SrOutput::Target;};
+ const bool srStage=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){
+ return srStageOf(c)||(c.editor&&c.editor->globals&&srStageOf(*c.editor->globals));});
+ const int version = srStage?11:beauty?10:effects?9:nrModel?8:dlss?7:tuning?6:vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;
out << "VEYRA_CHAIN_SESSION " << version << '\n' << int(session.active) << ' ' << session.initialized[0] << ' ' << session.initialized[1];
if(version>=4)out<<' '<<bool(editor);out<<'\n';
std::vector<PresetEntry> entries;
@@ -949,7 +971,7 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
out << int(c.srTarget) << ' ' << c.videoSrQuality << ' ' << int(c.fgBackend) << ' '
<< int(c.flow) << ' ' << int(c.opticalFlowBackend) << ' ' << c.amdFlowHalfResolution << ' '
<< int(c.nrPolicy) << ' ' << c.selectedNr << ' ' << c.selectedColour;
- if(version>=4)writeRendering(out,c,version>=5,version>=6,version>=7);out<<'\n';
+ if(version>=4)writeRendering(out,c,version>=5,version>=6,version>=7,version>=11);out<<'\n';
PresetEntry entry;
entry.name = i == 0 ? L"list" : L"node";
entry.kind = ChainMode(i); entry.chain = c.chain;
@@ -967,7 +989,7 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
const auto& g = *document.globals;
out << int(g.srTarget) << ' ' << g.videoSrQuality << ' ' << int(g.fgBackend) << ' '
<< int(g.flow) << ' ' << int(g.opticalFlowBackend) << ' ' << g.amdFlowHalfResolution << ' '
- << int(g.nrPolicy);if(version>=4)writeRendering(out,g,version>=5,version>=6,version>=7);out<<'\n';
+ << int(g.nrPolicy);if(version>=4)writeRendering(out,g,version>=5,version>=6,version>=7,version>=11);out<<'\n';
}
out << graph.nextId << ' ' << graph.inputNext << ' ' << document.nodes.nodeCount << '\n';
// The ordinary preset codec validates a linear runtime chain. Use a
@@ -994,7 +1016,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
std::istringstream in(data); in.imbue(std::locale::classic());
std::string magic, body; int version = 0, active = 0, list = 0, node = 0;
if (!(in >> magic >> version >> active >> list >> node) || magic != "VEYRA_CHAIN_SESSION" ||
- (version < 1 || version > 10) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;
+ (version < 1 || version > 11) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;
int hasEditor=version>=2?1:0;
if(version>=4&&(!(in>>hasEditor)||hasEditor<0||hasEditor>1))return false;
ChainSession parsed; parsed.active = ChainMode(active); parsed.initialized = {true, node != 0};
@@ -1005,7 +1027,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
c.srTarget = pipeline::SrTarget(target); c.fgBackend = FrameGenerationBackend(backend);
c.flow = FlowQuality(flow); c.opticalFlowBackend = OpticalFlowBackend(optical);
c.amdFlowHalfResolution = half != 0; c.nrPolicy = pipeline::NrSizePolicy(policy);
- if(version>=4&&!readRendering(in,c,version>=5,version>=6,version>=7))return false;
+ if(version>=4&&!readRendering(in,c,version>=5,version>=6,version>=7,version>=11))return false;
}
if (!(in >> std::quoted(body))) return false;
std::vector<PresetEntry> entries; std::wstring def, error;
@@ -1030,7 +1052,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
g.srTarget = pipeline::SrTarget(target); g.fgBackend = FrameGenerationBackend(backend);
g.flow = FlowQuality(flow); g.opticalFlowBackend = OpticalFlowBackend(optical);
g.amdFlowHalfResolution = half != 0; g.nrPolicy = pipeline::NrSizePolicy(policy);
- if(version>=4&&!readRendering(in,g,version>=5,version>=6,version>=7))return false;
+ if(version>=4&&!readRendering(in,g,version>=5,version>=6,version>=7,version>=11))return false;
editor->globals = g;
}
uint32_t count = 0;
@@ -1060,6 +1082,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
}
bool ChainSessionStore::load(ChainSession& session) {
+ const auto directSrStage=std::filesystem::path(path_).concat(L".sr-stage");
const auto directBeauty=std::filesystem::path(path_).concat(L".beauty");
const auto directEffects=std::filesystem::path(path_).concat(L".effects");
const auto directNr=std::filesystem::path(path_).concat(L".nr-model");
@@ -1097,6 +1120,9 @@ bool ChainSessionStore::load(ChainSession& session) {
const auto beautyPath=std::filesystem::path(path_).concat(L".beauty");
if(std::filesystem::exists(directBeauty,ec))path_=directBeauty;
else if(std::filesystem::exists(beautyPath,ec))path_=beautyPath;
+ const auto srStagePath=std::filesystem::path(path_).concat(L".sr-stage");
+ if(std::filesystem::exists(directSrStage,ec))path_=directSrStage;
+ else if(std::filesystem::exists(srStagePath,ec))path_=srStagePath;
const bool exists = std::filesystem::exists(path_, ec);
if (!exists && !ec) return true;
const auto size = std::filesystem::file_size(path_, ec);
@@ -1126,6 +1152,8 @@ bool ChainSessionStore::save(const ChainSession& session) {
const auto data = encode(session);
ChainSession checked;
if (!decode(data, checked)) { error_ = L"模式会话编码校验失败,未保存"; return false; }
+ if(data.starts_with("VEYRA_CHAIN_SESSION 11")&&!path_.wstring().ends_with(L".sr-stage"))path_=std::filesystem::path(path_).concat(L".sr-stage");
+ if(!path_.wstring().ends_with(L".sr-stage")){
if(data.starts_with("VEYRA_CHAIN_SESSION 10")&&!path_.wstring().ends_with(L".beauty"))path_=std::filesystem::path(path_).concat(L".beauty");
if(!path_.wstring().ends_with(L".beauty")){
if(data.starts_with("VEYRA_CHAIN_SESSION 9")&&!path_.wstring().ends_with(L".effects"))path_=std::filesystem::path(path_).concat(L".effects");
@@ -1153,6 +1181,7 @@ bool ChainSessionStore::save(const ChainSession& session) {
}
}
}
+ }
std::error_code ec;
if (!path_.parent_path().empty()) std::filesystem::create_directories(path_.parent_path(), ec);
if (ec) { error_ = L"模式会话目录无法创建"; return false; }
diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cpp
index 6e683457..71b62001 100644
--- a/src/engine/PresetStore.cpp
+++ b/src/engine/PresetStore.cpp
@@ -47,13 +47,16 @@ std::string PresetStore::serialize()const{
if(!p.settings.model.performance)return true;
for(unsigned i=0;i<p.settings.nrLayerCount;++i)if(!p.settings.nrLayers[i].model.performance)return true;
return false;});
- const bool fullSchema=fsr4||higher||rendering||vfg||correction||dlss||nrModel;
- const bool correctionExtended=nrModel||dlss||std::any_of(entries_.begin(),entries_.end(),[](const auto& p){
+ // v33 appends the three-step SR prescale and output (2026-10-28).
+ const bool srStage=std::any_of(entries_.begin(),entries_.end(),[](const auto& p){
+ return p.settings.srPrescale!=pipeline::SrPrescale::Off||p.settings.srOutput!=pipeline::SrOutput::Target;});
+ const bool fullSchema=fsr4||higher||rendering||vfg||correction||dlss||nrModel||srStage;
+ const bool correctionExtended=srStage||nrModel||dlss||std::any_of(entries_.begin(),entries_.end(),[](const auto& p){
if(p.settings.residual.correction.extendedControls())return true;
for(unsigned i=0;i<p.settings.nrLayerCount;++i)if(p.settings.nrLayers[i].residual.correction.extendedControls())return true;
return false;});
// 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 "<<(nrModel?32:dlss?31:correctionExtended?30: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';
+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS "<<(srStage?33:nrModel?32:dlss?31:correctionExtended?30: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){
@@ -72,21 +75,22 @@ 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||correction||dlss||nrModel)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);
- if(vfg||correction||dlss||nrModel)o<<' '<<s.vfgQuality;
- if(correction||dlss||nrModel){
+ if(rendering||vfg||correction||dlss||nrModel||srStage)o<<' '<<int(s.hdrOutputMode)<<' '<<int(s.fgMotion)<<' '<<int(s.srMotion)<<' '<<int(s.nrMotion);
+ if(vfg||correction||dlss||nrModel||srStage)o<<' '<<s.vfgQuality;
+ if(correction||dlss||nrModel||srStage){
o<<' ';writeNrCorrection(o,s.residual.correction,correctionExtended);
for(unsigned i=0;i<s.nrLayerCount;++i){o<<' ';writeNrCorrection(o,s.nrLayers[i].residual.correction,correctionExtended);}
}
- if(dlss||nrModel)o<<' '<<s.dlssSrModel;
- if(nrModel){o<<' '<<s.model.performance;
+ if(dlss||nrModel||srStage)o<<' '<<s.dlssSrModel;
+ if(nrModel||srStage){o<<' '<<s.model.performance;
for(unsigned i=0;i<s.nrLayerCount;++i)o<<' '<<s.nrLayers[i].model.performance;}
+ if(srStage)o<<' '<<uint32_t(s.srPrescale)<<' '<<uint32_t(s.srOutput);
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>32)||!(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>33)||!(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;
@@ -156,6 +160,7 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std
if(version>=32){int performance=0;
if(!(in>>performance)||performance<0||performance>1)return false;s.model.performance=performance!=0;
for(unsigned j=0;j<s.nrLayerCount;++j){if(!(in>>performance)||performance<0||performance>1)return false;s.nrLayers[j].model.performance=performance!=0;}}
+ if(version>=33){uint32_t prescale=0,output=0;if(!(in>>prescale>>output))return false;s.srPrescale=pipeline::SrPrescale(prescale);s.srOutput=pipeline::SrOutput(output);}
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.cpp
index 4a477d52..bfb3c844 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -580,14 +580,28 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
if(!Extent{srcW_,srcH_}.valid()||!Extent{workW_,workH_}.valid()){
veyra::log::error("resolution","source/output exceeds D3D12 texture dimensions or is empty");return false;
}
- if(!Extent{nrW_,nrH_}.valid()||nrW_>workW_||nrH_>workH_){veyra::log::error("resolution","invalid NR extent");return false;}
+ // NR before SR still reads the source. Three-step SR can now produce a
+ // smaller work texture, so its output is not the bound for that NR input.
+ const auto nrFull=desc_.nrFullExtent(0);
+ if(!Extent{nrW_,nrH_}.valid()||nrW_>nrFull.width||nrH_>nrFull.height){
+ veyra::log::error("resolution",std::format("invalid NR extent {}x{} for stage input {}x{}",nrW_,nrH_,nrFull.width,nrFull.height));return false;
+ }
if(!Extent{nvofW_,nvofH_}.valid()||nvofW_>srcW_||nvofH_>srcH_){veyra::log::error("resolution","invalid source-space flow extent");return false;}
+ if((desc.srInputWidth==0)!=(desc.srInputHeight==0)||(desc.srOutputWidth==0)!=(desc.srOutputHeight==0)){veyra::log::error("resolution","partial SR extent is invalid");return false;}
+ srInW_=desc.srInputWidth?desc.srInputWidth:srcW_;srInH_=desc.srInputHeight?desc.srInputHeight:srcH_;
+ srOutW_=desc.srOutputWidth?desc.srOutputWidth:workW_;srOutH_=desc.srOutputHeight?desc.srOutputHeight:workH_;
+ if(srPrescaleActive()||srResolveActive()){
+ // Three-step SR: shrink, enlarge with RTX Video SR, fit into the work extent.
+ if(!Extent{srInW_,srInH_}.valid()||!Extent{srOutW_,srOutH_}.valid()||srInW_>srcW_||srInH_>srcH_||
+ srOutW_<workW_||srOutH_<workH_||srOutW_<=srInW_||srOutH_<=srInH_){veyra::log::error("resolution","invalid three-step SR extent");return false;}
+ if(!desc.enableSr||!engine::srStageBackend(desc.videoSrQuality)){veyra::log::error("resolution","three-step SR runs on RTX Video SR only");return false;}
+ }
diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={srcW_,srcH_};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={workW_,workH_};initDiagnostic.resolution.nr={nrW_,nrH_};initDiagnostic.resolution.flow={nvofW_,nvofH_};initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="unverified-user-replaceable";Logger::diagnosticContext(initDiagnostic);
veyra::log::info("resolution",std::format("source={}x{} base={}x{} nr={}x{} flow={}x{} fg={}x{} output={}x{}",srcW_,srcH_,workW_,workH_,nrW_,nrH_,nvofW_,nvofH_,workW_,workH_,workW_,workH_));
veyra::log::info("pipeline-order",desc.splitNrAcrossSr()?"NR(source) -> SR -> NR(work) -> FG (node preview)":desc.nrBeforeSr?"NR -> residual(source) -> SR -> FG (experimental preview)":"SR -> NR -> residual -> FG");
if(!desc.videoHdr.valid()||(desc.hdrOutput&&!desc.hdrInput&&!desc.convertVideoHdr())){veyra::log::error("hdr","HDR output requires native HDR input or explicit Video HDR conversion");return false;}
const bool videoRestore=!desc.stillImage&&desc.videoSrQuality>=1&&desc.videoSrQuality<=4;
- srEnabled_ = desc.enableSr && (srcW_ != workW_ || srcH_ != workH_ || videoRestore);
+ srEnabled_ = desc.enableSr && (srcW_ != workW_ || srcH_ != workH_ || videoRestore || srPrescaleActive() || srResolveActive());
lmxxfNr_ = context_.adapter().vendorId == 0x1002 || desc.nrRuntime == engine::NrRuntime::LmxxfAmd;
if(context_.adapter().vendorId==0x1002 && desc_.opticalFlowBackend==engine::OpticalFlowBackend::Nvidia)
desc_.opticalFlowBackend=engine::OpticalFlowBackend::AmdFidelityFx;
@@ -720,7 +734,9 @@ bool EnhanceGraph::createResources()
videoHdrOutput_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
if(!videoHdrInput_||!videoHdrOutput_)return false;
}
- if(srEnabled_&&desc_.videoSrQuality&&desc_.videoSrQuality!=engine::kVideoSrFsr){videoSrInput_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);videoSrOutput_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);if(!videoSrInput_||!videoSrOutput_)return false;}
+ if(srEnabled_&&desc_.videoSrQuality&&desc_.videoSrQuality!=engine::kVideoSrFsr){videoSrInput_=makeTexture(context_.device(),srInW_,srInH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);videoSrOutput_=makeTexture(context_.device(),srOutW_,srOutH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);if(!videoSrInput_||!videoSrOutput_)return false;
+ // Three-step SR: the linear SR input after the exact area shrink.
+ if(srPrescaleActive()&&!(srPrescaled_=makeTexture(context_.device(),srInW_,srInH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true)))return false;}
// FSR upscaling needs a render-extent depth; Veyra has no source-resolution
// depth source, so this is the same explicit constant far depth the
// frame-generation path uses. It limits disocclusion quality and must not
@@ -1495,7 +1511,8 @@ bool EnhanceGraph::initNgxFeatures()
ID3D12GraphicsCommandList* list = ring_.acquire(0, st);
if (list == nullptr) { failedBackend_=engine::FailedBackend::Infrastructure; return false; }
failedBackend_=engine::FailedBackend::Sr;
- if(desc_.videoSrQuality){videoSrBackend_=std::make_unique<ngx::VideoSrBackend>();if(!videoSrBackend_->create(*coreHost_,list))return false;veyra::log::info("video-sr",std::format("selected quality={} input={}x{} output={}x{}",desc_.videoSrQuality,srcW_,srcH_,workW_,workH_));}
+ if(desc_.videoSrQuality){videoSrBackend_=std::make_unique<ngx::VideoSrBackend>();if(!videoSrBackend_->create(*coreHost_,list))return false;veyra::log::info("video-sr",std::format("selected quality={} input={}x{} output={}x{}{}",desc_.videoSrQuality,srcW_,srcH_,workW_,workH_,
+ srPrescaleActive()||srResolveActive()?std::format(" three-step prescale={}x{} evaluate={}x{}",srInW_,srInH_,srOutW_,srOutH_):std::string()));}
else if (!srBackend_->create(*coreHost_, list, ngxParams_, sd, st) || !srBackend_->created()) {
veyra::log::error("graph", "SR create failed");
return false;
@@ -1739,14 +1756,17 @@ bool EnhanceGraph::createComputePasses()
if(!amdHdrEncodePass_.loadShader("HdrAmdNrEncode.dxil",cs)||!amdHdrEncodePass_.create(context_.device(),cs,2*nrLayerSlots,1,1))return false;
if(!amdHdrRestorePass_.loadShader("HdrAmdNrRestore.dxil",cs)||!amdHdrRestorePass_.create(context_.device(),cs,4*nrLayerSlots,3,1))return false;
}
- if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 21, 1, 1)) return false;
+ if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 22, 1, 1)) return false;
// Nv12Upload stays: frame-time CopyTextureRegion is poisoned by the
// injected layer (SEH in NGX evaluate, r33-final3 evidence); the compute
// upload is the proven frame-path ingestion on this system.
if (!uploadPass_.loadShader("Nv12Upload.dxil", cs) || !uploadPass_.create(context_.device(), cs, 4, 1, 2)) return false;
if (!densifyPass_.loadShader("NvofDensify.dxil", cs) ||
!densifyPass_.create(context_.device(), cs, 7, 5, 2)) return false;
- if(desc_.hdrWorking()&&videoSrInput_&&(!hdrVideoSrPass_.loadShader("HdrVideoSrRestore.dxil",cs)||!hdrVideoSrPass_.create(context_.device(),cs,7,3,1)))return false;
+ if(desc_.hdrWorking()&&videoSrInput_&&(!hdrVideoSrPass_.loadShader("HdrVideoSrRestore.dxil",cs)||!hdrVideoSrPass_.create(context_.device(),cs,10,3,1)))return false;
+ // Three-step SR: NrDownsample's exact area shrink before RTX Video SR, SrResolve after it.
+ if(srPrescaled_&&(!srPrescalePass_.loadShader("NrDownsample.dxil",cs)||!srPrescalePass_.create(context_.device(),cs,2,1,1)))return false;
+ if(videoSrOutput_&&srResolveActive()&&(!srResolvePass_.loadShader("SrResolve.dxil",cs)||!srResolvePass_.create(context_.device(),cs,10,3,1)))return false;
if (!stager_.initialize(context_.device(), 80)) {
veyra::log::error("graph", "descriptor stager init failed");
return false;
@@ -1916,6 +1936,30 @@ bool EnhanceGraph::createViews()
stagedSrv(srStageInput(),DXGI_FORMAT_R16G16B16A16_FLOAT,hdrVideoSrPass_,4);
stagedSrv(videoSrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,5);
stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,6);
+ if(srPrescaled_){
+ stagedSrv(srPrescaled_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,hdrVideoSrPass_,7);
+ stagedSrv(videoSrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,8);
+ stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,hdrVideoSrPass_,9);
+ }
+ }
+ // Three-step SR. Prescale: 0 resolved SR input, 1 shrunk input (UAV); ScaleBlit
+ // encodes the shrunk input from blit slot 21. Resolve uses hdrVideoSrPass_'s
+ // layout: (base, encoded input, SR result) at 0 source / 4 resolved SR input /
+ // 7 shrunk input, 3 the work texture (UAV).
+ if(srPrescaled_){
+ stagedSrv(srStageInput(),DXGI_FORMAT_R16G16B16A16_FLOAT,srPrescalePass_,0);
+ makeUav(context_.device(),srPrescaled_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(srPrescalePass_,1));
+ stagedSrv(srPrescaled_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,blitPass_,21);
+ }
+ if(videoSrOutput_&&srResolveActive()){
+ ID3D12Resource* bases[3]={srcRgba_.Get(),srStageInput(),srPrescaled_?srPrescaled_.Get():srcRgba_.Get()};
+ const UINT sets[3]={0,4,7};
+ for(size_t i=0;i<3;++i){
+ stagedSrv(bases[i],DXGI_FORMAT_R16G16B16A16_FLOAT,srResolvePass_,sets[i]);
+ stagedSrv(videoSrInput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,srResolvePass_,sets[i]+1);
+ stagedSrv(videoSrOutput_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,srResolvePass_,sets[i]+2);
+ }
+ makeUav(context_.device(),workRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(srResolvePass_,3));
}
// Immutable per-resource views.
if(desc_.rgbInput||desc_.yuy2Input||desc_.packedInput){
@@ -2518,17 +2562,36 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
auto runVideoSr=[&]()->bool{
gpuTimer_.mark(list,GpuStage::Sr);
+ // Three-step SR shrinks the resolved SR input first (exact area, linear light).
+ const bool prescaled=srPrescaled_!=nullptr;
+ if(prescaled){
+ tracker_.transition(list,srStageInput(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker_.transition(list,srPrescaled_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const float down[8]={uintBits(srcW_),uintBits(srcH_),uintBits(srInW_),uintBits(srInH_),0,0,0,0};
+ srPrescalePass_.bind(list,down,gpuHandleOf(srPrescalePass_,0).ptr,gpuHandleOf(srPrescalePass_,1).ptr);
+ list->Dispatch((srInW_+15)/16,(srInH_+15)/16,1);tracker_.uavBarrier(list,srPrescaled_.Get());
+ tracker_.transition(list,srPrescaled_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ }
tracker_.transition(list,videoSrInput_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float enc[8]={uintBits(srcW_),uintBits(srcH_),uintBits(srcW_),uintBits(srcH_),desc_.hdrWorking()?3.0f:1.0f,0,0,0};
- blitPass_.bind(list,enc,gpuHandleOf(blitPass_,desc_.nrBeforeSr||sourcePostOutput_?18:0).ptr,gpuHandleOf(blitPass_,16).ptr);list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);tracker_.uavBarrier(list,videoSrInput_.Get());
+ const float enc[8]={uintBits(srInW_),uintBits(srInH_),uintBits(srInW_),uintBits(srInH_),desc_.hdrWorking()?3.0f:1.0f,0,0,0};
+ blitPass_.bind(list,enc,gpuHandleOf(blitPass_,prescaled?21:desc_.nrBeforeSr||sourcePostOutput_?18:0).ptr,gpuHandleOf(blitPass_,16).ptr);list->Dispatch((srInW_+15)/16,(srInH_+15)/16,1);tracker_.uavBarrier(list,videoSrInput_.Get());
tracker_.transition(list,videoSrInput_.Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,videoSrOutput_.Get(),D3D12_RESOURCE_STATE_COMMON);
if(!videoSrBackend_->evaluate(list,videoSrInput_.Get(),videoSrOutput_.Get(),desc_.videoSrQuality)){failedBackend_=engine::FailedBackend::Sr;return false;}
tracker_.uavBarrier(list,videoSrOutput_.Get());tracker_.transition(list,videoSrOutput_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,workRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float dec[8]={uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),-1,0,0,0};
- if(desc_.hdrWorking()){
+ // HDR restore and the resolve take the base that was encoded.
+ const UINT restoreSet=prescaled?7:desc_.nrBeforeSr||sourcePostOutput_?4:0;
+ if(srResolveActive()){
tracker_.transition(list,videoSrInput_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- hdrVideoSrPass_.bind(list,dec,gpuHandleOf(hdrVideoSrPass_,desc_.nrBeforeSr||sourcePostOutput_?4:0).ptr,gpuHandleOf(hdrVideoSrPass_,3).ptr);
- }else blitPass_.bind(list,dec,gpuHandleOf(blitPass_,17).ptr,gpuHandleOf(blitPass_,1).ptr);list->Dispatch((workW_+15)/16,(workH_+15)/16,1);tracker_.uavBarrier(list,workRgba_.Get());tracker_.transition(list,workRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ const float fit[8]={uintBits(srOutW_),uintBits(srOutH_),uintBits(workW_),uintBits(workH_),desc_.hdrWorking()?1.0f:0.0f,0,0,0};
+ srResolvePass_.bind(list,fit,gpuHandleOf(srResolvePass_,restoreSet).ptr,gpuHandleOf(srResolvePass_,3).ptr);
+ }else{
+ const float dec[8]={uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),-1,0,0,0};
+ if(desc_.hdrWorking()){
+ tracker_.transition(list,videoSrInput_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ hdrVideoSrPass_.bind(list,dec,gpuHandleOf(hdrVideoSrPass_,restoreSet).ptr,gpuHandleOf(hdrVideoSrPass_,3).ptr);
+ }else blitPass_.bind(list,dec,gpuHandleOf(blitPass_,17).ptr,gpuHandleOf(blitPass_,1).ptr);
+ }
+ list->Dispatch((workW_+15)/16,(workH_+15)/16,1);tracker_.uavBarrier(list,workRgba_.Get());tracker_.transition(list,workRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
++metrics_.srEvaluateCount;gpuTimer_.mark(list,GpuStage::Sr,true);
return true;
};
@@ -3685,7 +3748,7 @@ void EnhanceGraph::shutdown()
fgFlowClaims_.Reset();fgFlowAgreement_.Reset();flowClaimPass_={};flowClaims_=false;
for(unsigned i=0;i<kGeneratedPoolSlots;++i){if(fgDisableMapped_[i]&&fgDisableReadback_[i]){D3D12_RANGE written{0,0};fgDisableReadback_[i]->Unmap(0,&written);}fgDisableMapped_[i]=nullptr;fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();
encPass_ = ComputePass{};
- blitPass_ = ComputePass{};hdrVideoSrPass_={};
+ blitPass_ = ComputePass{};hdrVideoSrPass_={};srPrescalePass_={};srResolvePass_={};
yuvPass_ = ComputePass{};
for(auto i=additionalColorInstances_.rbegin();i!=additionalColorInstances_.rend();++i)i->reset();
for(auto i=nodeColorInstances_.rbegin();i!=nodeColorInstances_.rend();++i)i->reset();
@@ -3724,7 +3787,7 @@ void EnhanceGraph::shutdown()
neuralTex_.Reset();
proxyTex_.Reset();
for(auto& r:sourceReferences_)r.Reset();for(auto& r:baseReferences_)r.Reset();workRgba_.Reset();
- preGradeRgba_.Reset();srcRgba_.Reset();videoSrInput_.Reset();videoSrOutput_.Reset();
+ preGradeRgba_.Reset();srcRgba_.Reset();videoSrInput_.Reset();videoSrOutput_.Reset();srPrescaled_.Reset();
nrHoldPass_.reset();
colorDetail_.close();
chromaTex_.Reset();
diff --git a/src/ui/PlayerUiFacade.cpp b/src/ui/PlayerUiFacade.cpp
index b85dc0b7..0ac7bb31 100644
--- a/src/ui/PlayerUiFacade.cpp
+++ b/src/ui/PlayerUiFacade.cpp
@@ -63,7 +63,11 @@ bool sameSnapshot(const veyra::engine::PlayerSnapshot& a, const veyra::engine::P
a.metrics.resolution.nr.width == b.metrics.resolution.nr.width &&
a.metrics.resolution.nr.height == b.metrics.resolution.nr.height &&
a.metrics.resolution.output.width == b.metrics.resolution.output.width &&
- a.metrics.resolution.output.height == b.metrics.resolution.output.height;
+ a.metrics.resolution.output.height == b.metrics.resolution.output.height &&
+ a.metrics.resolution.srInput == b.metrics.resolution.srInput &&
+ a.metrics.resolution.srOutput == b.metrics.resolution.srOutput &&
+ a.metrics.resolution.srPrescaleIneffective == b.metrics.resolution.srPrescaleIneffective &&
+ a.metrics.resolution.srOutputIneffective == b.metrics.resolution.srOutputIneffective;
}
} // namespace
@@ -132,8 +136,9 @@ bool PlayerUiFacade::applySettings(const veyra::engine::EnhancementSettings& set
uint64_t acceptedRevision=0;
if (!engine_.requestSettings(settings, order,&acceptedRevision)) return false;
veyra::log::info("ui-settings-request", std::format(
- "accepted srTarget={} quality={} fgBackend={} flowBackend={}",
- int(settings.srTarget), settings.videoSrQuality, int(settings.frameGenerationBackend), int(settings.opticalFlowBackend)));
+ "accepted srTarget={} quality={} fgBackend={} flowBackend={} srPrescale={} srOutput={}",
+ int(settings.srTarget), settings.videoSrQuality, int(settings.frameGenerationBackend), int(settings.opticalFlowBackend),
+ uint32_t(settings.srPrescale), uint32_t(settings.srOutput)));
pending_ = settings;
pendingFgRevision_=acceptedRevision;
pendingNrRevision_=acceptedRevision;requestedNrRuntime_=settings.nrRuntime;
diff --git a/src/ui/QmlPlayerBridge_p.h b/src/ui/QmlPlayerBridge_p.h
index a1c008da..00164ece 100644
--- a/src/ui/QmlPlayerBridge_p.h
+++ b/src/ui/QmlPlayerBridge_p.h
@@ -901,6 +901,7 @@ struct QmlPlayerBridge::Impl {
if (!projected->firstOf(engine::EffectType::SuperResolution)) {
s.srTarget = previous.srTarget; s.videoSrQuality = previous.videoSrQuality;
s.dlssSrModel = previous.dlssSrModel;
+ s.srPrescale = previous.srPrescale; s.srOutput = previous.srOutput;
}
if (!projected->firstOf(engine::EffectType::FrameGeneration)){
s.frameGenerationBackend = previous.frameGenerationBackend;
diff --git a/src/ui/bridge/Chain.cpp b/src/ui/bridge/Chain.cpp
index 4598a6fa..f3b953ad 100644
--- a/src/ui/bridge/Chain.cpp
+++ b/src/ui/bridge/Chain.cpp
@@ -571,6 +571,8 @@ bool QmlPlayerBridge::resetNode(uint id) {
impl_->draftGlobals.srTarget = defaults.srTarget;
impl_->draftGlobals.videoSrQuality = defaults.videoSrQuality;
impl_->draftGlobals.dlssSrModel = defaults.dlssSrModel;
+ impl_->draftGlobals.srPrescale = defaults.srPrescale;
+ impl_->draftGlobals.srOutput = defaults.srOutput;
}
if (!impl_->revalidate(true, &previous)) {
const auto error = impl_->validation.message; node = before;
diff --git a/src/ui/bridge/Enhancement.cpp b/src/ui/bridge/Enhancement.cpp
index f2ddd123..8abd3ca7 100644
--- a/src/ui/bridge/Enhancement.cpp
+++ b/src/ui/bridge/Enhancement.cpp
@@ -39,6 +39,27 @@ void QmlPlayerBridge::setDlssSrModel(int value) {
s.dlssSrModel = unsigned(value);
if (impl_->commit(s)) emit settingsChanged();
}
+int QmlPlayerBridge::srPrescale() const { return int(settings().srPrescale); }
+int QmlPlayerBridge::srOutput() const { return int(settings().srOutput); }
+// Three-step SR runs on RTX Video SR only; other backends keep the single step.
+void QmlPlayerBridge::setSrPrescale(int value) {
+ const auto want = pipeline::SrPrescale(uint32_t(value));
+ if (value < 0 || !pipeline::validSrPrescale(want)) return;
+ auto s = settings();
+ if (s.srPrescale == want) return;
+ if (!engine::srStageBackend(s.videoSrQuality)) { emit notice(tr("先降到 / 再缩到目前仅 RTX 视频超分支持"), true); return; }
+ s.srPrescale = want;
+ if (impl_->commit(s)) emit settingsChanged();
+}
+void QmlPlayerBridge::setSrOutput(int value) {
+ const auto want = pipeline::SrOutput(uint32_t(value));
+ if (value < 0 || !pipeline::validSrOutput(want)) return;
+ auto s = settings();
+ if (s.srOutput == want) return;
+ if (!engine::srStageBackend(s.videoSrQuality)) { emit notice(tr("先降到 / 再缩到目前仅 RTX 视频超分支持"), true); return; }
+ s.srOutput = want;
+ if (impl_->commit(s)) emit settingsChanged();
+}
void QmlPlayerBridge::setVideoSrQuality(int value) {
if (value < 0 || value > 5) return;
const auto cap = effectCapabilities().value("sr" + QString::number(value)).toMap();
diff --git a/src/ui/bridge/Recording.cpp b/src/ui/bridge/Recording.cpp
index f5dffc3b..23c60088 100644
--- a/src/ui/bridge/Recording.cpp
+++ b/src/ui/bridge/Recording.cpp
@@ -88,8 +88,8 @@ void QmlPlayerBridge::startExport() {
if(!impl_->exportQueue.queue().start(wideOf(folder),*settings,impl_->exportHevc,impl_->exportRateControl,reason)){
emit notice(uiText(reason),true);emit exportChanged();return;
}
- veyra::log::info("qml-export",std::format("export frozen bitrateMbps={} rateControl={} hevc={} srTarget={}",
- settings->exportBitrateMbps,int(impl_->exportRateControl),impl_->exportHevc,int(settings->srTarget)));
+ veyra::log::info("qml-export",std::format("export frozen bitrateMbps={} rateControl={} hevc={} srTarget={} srPrescale={} srOutput={}",
+ settings->exportBitrateMbps,int(impl_->exportRateControl),impl_->exportHevc,int(settings->srTarget),uint32_t(settings->srPrescale),uint32_t(settings->srOutput)));
impl_->exportQueue.refresh();pollExport();emit navigate(QStringLiteral("exp"));
// Leave the GPU to the export (field request 2026-10-02): whatever plays is closed,
// unless 导出页 → 导出时关闭正在播放的内容 is off.
diff --git a/src/ui/bridge/Status.cpp b/src/ui/bridge/Status.cpp
index f8f1c426..ef27cf9f 100644
--- a/src/ui/bridge/Status.cpp
+++ b/src/ui/bridge/Status.cpp
@@ -12,6 +12,29 @@ QString QmlPlayerBridge::outputSummary() const {
if (!s.running || !plan.output.valid() || plan.settingsRevision != s.applied.revision) return {};
return QStringLiteral("%1x%2").arg(plan.output.width).arg(plan.output.height);
}
+// Three-step SR as the running plan has it: source -> shrunk input -> SR
+// result -> output. Empty for single-step SR.
+QString QmlPlayerBridge::srStageSummary() const {
+ const auto& s = impl_->snapshot;
+ const auto& plan = s.metrics.resolution;
+ if (!s.running || !plan.output.valid() || plan.settingsRevision != s.applied.revision || !plan.srApplied) return {};
+ if (plan.srInput == plan.source && plan.srOutput == plan.base) return {};
+ const auto size = [](pipeline::Extent e) { return QStringLiteral("%1x%2").arg(e.width).arg(e.height); };
+ QStringList parts{size(plan.source)};
+ if (plan.srInput != plan.source) parts << size(plan.srInput);
+ parts << size(plan.srOutput);
+ if (plan.base != plan.srOutput) parts << size(plan.base);
+ return parts.join(QStringLiteral(" → "));
+}
+QString QmlPlayerBridge::srStageNote() const {
+ const auto& s = impl_->snapshot;
+ const auto& plan = s.metrics.resolution;
+ if (!s.running || !plan.output.valid() || plan.settingsRevision != s.applied.revision) return {};
+ QStringList notes;
+ if (plan.srPrescaleIneffective) notes << tr("先降到未生效:片源不大于所选尺寸,或先降后已不能再放大");
+ if (plan.srOutputIneffective) notes << tr("再缩到未生效:只在超分放大后、且小于超分结果时执行");
+ return notes.join(QStringLiteral(";"));
+}
// A display rate is only real when the system's display event can be read. No
// counter is wired in this build, so it reports unknown and the UI shows "未测" -
diff --git a/tests/integration/ExportWorkflowTests.cpp b/tests/integration/ExportWorkflowTests.cpp
index 3ddcdd54..760edc2c 100644
--- a/tests/integration/ExportWorkflowTests.cpp
+++ b/tests/integration/ExportWorkflowTests.cpp
@@ -37,6 +37,14 @@ int wmain(int argc,wchar_t** argv){
const bool hevc=mode.find(L"hevc")!=std::wstring::npos;
const bool fsr=mode.find(L"fsr-")==0;
const bool rejectXess=mode==L"reject-xess";
+ const bool srStage=mode==L"sr-stage-fit"||mode==L"sr-stage-prescale";
+ if(srStage){
+ settings.sr=true;settings.videoSrQuality=1;settings.srMotion=MotionSource::Zero;
+ settings.srPrescale=veyra::pipeline::SrPrescale::P1080;
+ settings.srTarget=mode==L"sr-stage-fit"?veyra::pipeline::SrTarget::Uhd8K:veyra::pipeline::SrTarget::Uhd4K;
+ settings.srOutput=mode==L"sr-stage-fit"?veyra::pipeline::SrOutput::Uhd4K:veyra::pipeline::SrOutput::Qhd;
+ media.audio.policy=media.subtitles.policy=ExportTrackPolicy::None;
+ }
if(fsr||rejectXess){
settings.frameGenerationBackend=rejectXess?FrameGenerationBackend::XeSS:FrameGenerationBackend::Fsr;
settings.multiplier=2;
@@ -166,11 +174,20 @@ int wmain(int argc,wchar_t** argv){
for(const auto& t:info.tracks)if(t.subtitle&&media.subtitles.count<media.subtitles.indices.size())media.subtitles.indices[media.subtitles.count++]=t.index;
require(media.subtitles.count>0,"reject source has no subtitle track");
}
- require(manager.start(input,output,settings,hevc,0,-1,from,to,veyra::sink::ExportRateControl::Cq,media),"start refused");
+ require(manager.start(input,output,settings,hevc,srStage?4:0,-1,from,to,veyra::sink::ExportRateControl::Cq,media),"start refused");
auto s=finish(manager);collected(s);
std::wcout<<L"state="<<int(s.state)<<L" encoded="<<s.encoded<<L" message="<<s.message<<L"\n";
if(mode.find(L"reject")!=std::wstring::npos){require(s.state==ExportState::Failed,"incompatible source was not rejected");require(!std::filesystem::exists(output),"rejection produced final file");require(!s.message.empty(),"failure reason missing");}
else require(s.state==ExportState::Succeeded,"export failed");
+ if(srStage){
+ require(s.encoded==4&&s.sourceFrames==4,"SR stage export lost source frames");
+ require(s.frozen.srPrescale==settings.srPrescale&&s.frozen.srOutput==settings.srOutput&&s.frozen.srTarget==settings.srTarget,
+ "SR stage fields lost crossing the worker protocol");
+ std::ifstream log(s.workerLog);const std::string text((std::istreambuf_iterator<char>(log)),{});
+ const auto evaluated=mode==L"sr-stage-fit"?"evaluate=7680x4320":"evaluate=3840x2160";
+ require(text.find(evaluated)!=std::string::npos,"SR stage was not evaluated at the requested dimensions");
+ std::wcout<<L"SR_STAGE_EXPORT encoded="<<s.encoded<<L" frozenAndEvaluated=1\n";
+ }
if(rejectXess){
require(s.message.find(L"XeSS")!=std::wstring::npos&&s.message.find(L"FSR")!=std::wstring::npos,"XeSS rejection lost its backend-specific reason");
require(s.encoded==0,"unsupported XeSS wrote frames");
diff --git a/tests/integration/SrQualityTests.cpp b/tests/integration/SrQualityTests.cpp
index cfcec8f4..3fda7f74 100644
--- a/tests/integration/SrQualityTests.cpp
+++ b/tests/integration/SrQualityTests.cpp
@@ -6,11 +6,15 @@
#include "veyra/source/MediaFileSource.h"
#include "veyra/RuntimePaths.h"
#include "veyra/Log.h"
+#include <DirectXPackedVector.h>
+#include <algorithm>
+#include <cmath>
#include <filesystem>
#include <iostream>
#include <fstream>
#include <memory>
#include <array>
+#include <string>
#include <vector>
extern "C" {
#include <libavutil/frame.h>
@@ -88,11 +92,303 @@ static int referenceTest(const std::filesystem::path& directory,const std::wstri
}
+// ---- three-step SR (2026-10-28) ----------------------------------------------
+// Real RTX Video SR with the prescale and the output fit: sizes and SDK
+// evaluations, the shrink against a CPU area average of the graph's own encoded
+// input, and the fit against a CPU area average of the same graph run at the SR
+// size (SDR and HDR). Readbacks are restricted to this test.
+namespace stage {
+using namespace veyra;
+// Copy a texture in a known state to the CPU and restore that state.
+bool read(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* tex,D3D12_RESOURCE_STATES state,unsigned bytesPerPixel,sink::RgbaImage& img){
+ if(!tex)return false;
+ const auto d=tex->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT64 total=0;
+ ctx.device()->GetCopyableFootprints(&d,0,1,0,&fp,nullptr,nullptr,&total);
+ D3D12_HEAP_PROPERTIES heap{};heap.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC buffer{};buffer.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;buffer.Width=total;buffer.Height=1;
+ buffer.DepthOrArraySize=1;buffer.MipLevels=1;buffer.SampleDesc.Count=1;buffer.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;
+ if(FAILED(ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&buffer,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return false;
+ Status st=Status::Ok;const auto slot=ring.slotCount()-1;auto* list=ring.acquire(slot,st);if(!list)return false;
+ D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ b.Transition={tex,D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,state,D3D12_RESOURCE_STATE_COPY_SOURCE};list->ResourceBarrier(1,&b);
+ D3D12_TEXTURE_COPY_LOCATION src{},dst{};src.pResource=tex;src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint=fp;
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;
+ uint8_t* data=nullptr;D3D12_RANGE range{0,SIZE_T(total)};
+ if(FAILED(readback->Map(0,&range,reinterpret_cast<void**>(&data))))return false;
+ img.width=uint32_t(d.Width);img.height=d.Height;img.pixels.resize(size_t(img.width)*img.height*bytesPerPixel);
+ for(UINT y=0;y<img.height;++y)std::memcpy(img.pixels.data()+size_t(y)*img.width*bytesPerPixel,data+fp.Offset+size_t(y)*fp.Footprint.RowPitch,size_t(img.width)*bytesPerPixel);
+ D3D12_RANGE none{0,0};readback->Unmap(0,&none);return true;
+}
+double decode(uint8_t v){const double c=v/255.0;return c<=0.04045?c/12.92:std::pow((c+0.055)/1.055,2.4);}
+double encode(double c){c=std::clamp(c,0.0,1.0);return 255.0*(c<=0.0031308?c*12.92:1.055*std::pow(c,1.0/2.4)-0.055);}
+float half(const sink::RgbaImage& img,size_t i){uint16_t h;std::memcpy(&h,img.pixels.data()+i*2,2);return DirectX::PackedVector::XMConvertHalfToFloat(h);}
+// Natural-ish detail at every frequency: zone plate, hard blocks, thin lines and noise.
+sink::RgbaImage pattern(unsigned w,unsigned h){
+ sink::RgbaImage img;img.width=w;img.height=h;img.pixels.resize(size_t(w)*h*4);uint32_t seed=12345;
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){
+ const double u=double(x)/w,v=double(y)/h;seed=seed*1664525u+1013904223u;const double noise=((seed>>24)&255)/255.0-0.5;
+ const double zone=0.5+0.5*std::sin((u*u+v*v)*w*0.35),block=((x/37+y/53)%2)?0.85:0.15;
+ double r=0.15+0.55*u+0.2*zone*(v<0.5)+0.06*noise,g=0.2+0.5*v+0.25*block*(u>0.5)+0.06*noise,b=0.3+0.3*zone*(u<0.5)+0.3*block*(v>0.5)+0.06*noise;
+ if((x+y)%61<2||(x>w/2&&(x+2*y)%47==0))r=g=b=0.95;
+ auto* p=&img.pixels[(size_t(y)*w+x)*4];
+ p[0]=uint8_t(std::clamp(r,0.0,1.0)*255+0.5);p[1]=uint8_t(std::clamp(g,0.0,1.0)*255+0.5);p[2]=uint8_t(std::clamp(b,0.0,1.0)*255+0.5);p[3]=255;
+ }
+ return img;
+}
+struct FreeFrame{void operator()(AVFrame* f)const{av_frame_free(&f);}};
+using Frame=std::unique_ptr<AVFrame,FreeFrame>;
+Frame sdrFrame(const sink::RgbaImage& img){
+ Frame f(av_frame_alloc());if(!f)return {};
+ f->format=AV_PIX_FMT_RGBA;f->width=int(img.width);f->height=int(img.height);
+ if(av_frame_get_buffer(f.get(),32)<0)return {};
+ for(unsigned y=0;y<img.height;++y)std::memcpy(f->data[0]+size_t(y)*f->linesize[0],img.pixels.data()+size_t(y)*img.width*4,size_t(img.width)*4);
+ f->color_range=AVCOL_RANGE_JPEG;f->colorspace=AVCOL_SPC_RGB;f->color_trc=AVCOL_TRC_IEC61966_2_1;f->color_primaries=AVCOL_PRI_BT709;
+ return f;
+}
+// The same picture as P010 PQ BT.2020: 0..200 nits with 1000-nit lines.
+Frame hdrFrame(const sink::RgbaImage& img){
+ Frame f(av_frame_alloc());if(!f)return {};
+ f->format=AV_PIX_FMT_P010;f->width=int(img.width);f->height=int(img.height);
+ f->color_range=AVCOL_RANGE_MPEG;f->colorspace=AVCOL_SPC_BT2020_NCL;f->color_primaries=AVCOL_PRI_BT2020;f->color_trc=AVCOL_TRC_SMPTE2084;
+ if(av_frame_get_buffer(f.get(),32)<0)return {};
+ const auto pq=[](double nits){const double y=std::pow(std::clamp(nits/10000.0,0.0,1.0),2610.0/16384.0);
+ return std::pow((3424.0/4096.0+2413.0/128.0*y)/(1+2392.0/128.0*y),2523.0/32.0);};
+ std::vector<double> yv(size_t(img.width)*img.height),cbv(yv.size()),crv(yv.size());
+ for(size_t i=0;i<yv.size();++i){
+ const auto* p=&img.pixels[i*4];const bool bright=p[0]==242&&p[1]==242&&p[2]==242;
+ const double R=pq(bright?1000:decode(p[0])*200),G=pq(bright?1000:decode(p[1])*200),B=pq(bright?1000:decode(p[2])*200);
+ const double Y=0.2627*R+0.6780*G+0.0593*B;yv[i]=Y;cbv[i]=(B-Y)/1.8814;crv[i]=(R-Y)/1.4746;
+ }
+ const auto q=[](double v){return uint16_t(std::clamp(std::lround(v),0l,1023l)<<6);};
+ for(unsigned y=0;y<img.height;++y)for(unsigned x=0;x<img.width;++x)
+ reinterpret_cast<uint16_t*>(f->data[0]+size_t(y)*f->linesize[0])[x]=q(64+876*yv[size_t(y)*img.width+x]);
+ for(unsigned y=0;y<img.height/2;++y)for(unsigned x=0;x<img.width/2;++x){
+ double cb=0,cr=0;for(unsigned k=0;k<4;++k){const size_t i=size_t(y*2+k/2)*img.width+x*2+k%2;cb+=cbv[i]/4;cr+=crv[i]/4;}
+ auto* row=reinterpret_cast<uint16_t*>(f->data[1]+size_t(y)*f->linesize[1]);row[x*2]=q(512+896*cb);row[x*2+1]=q(512+896*cr);
+ }
+ return f;
+}
+struct Run{bool ok=false;sink::RgbaImage output,srInput;double srMs=-1;uint64_t evaluations=0;pipeline::Extent srIn{},srOut{},work{};bool enabled=false;};
+Run run(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,const AVFrame* frame,bool hdr,const engine::EnhancementSettings& settings,
+ bool readSrInput,bool still=false,bool uncompressed=false,unsigned frames=6){
+ engine::StageRequest request;request.width=unsigned(frame->width);request.height=unsigned(frame->height);request.sr=settings.sr;
+ request.stillImage=still;request.uncompressedSource=uncompressed;request.nr=settings.nr;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);
+ desc.rgbInput=!hdr;desc.hdrInput=hdr;desc.hdrOutput=hdr;desc.outputDitherStep=0;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ Run r;r.srIn={desc.srInputWidth,desc.srInputHeight};r.srOut={desc.srOutputWidth,desc.srOutputHeight};r.work={desc.workWidth,desc.workHeight};
+ if(!desc.fixedExecutionPlanError.empty()){std::cout<<"plan error: "<<desc.fixedExecutionPlanError<<std::endl;return r;}
+ pipeline::EnhanceGraph graph(ctx,ring);
+ if(!graph.initialize(desc)||!graph.createViews()){graph.shutdown();return r;}
+ graph.recordGpuTimings();std::vector<double> ms;pipeline::EnhanceGraph::FrameOutputs out;bool ok=true;
+ for(unsigned i=0;i<frames&&ok;++i){
+ out={};ok=graph.process(frame,i*33.333333,i==0,out,i+1)&&ring.waitIdle();
+ for(const auto& t:graph.takeGpuTimings()){const auto& v=t.gpu[size_t(diagnostics::GpuStage::Sr)];if(v.milliseconds&&t.identity.sourceFrameId>2)ms.push_back(*v.milliseconds);}
+ }
+ if(ok){auto* tex=graph.videoFrameResource(out.videoSlot);
+ ok=tex&&read(ctx,ring,tex,D3D12_RESOURCE_STATE_COMMON,tex->GetDesc().Format==DXGI_FORMAT_R16G16B16A16_FLOAT?8:4,r.output);}
+ // The single-step and prescale SDR paths leave the encoded SR input in COMMON.
+ if(ok&&readSrInput)ok=read(ctx,ring,graph.diagnosticVideoSrInput(),D3D12_RESOURCE_STATE_COMMON,4,r.srInput);
+ r.evaluations=graph.metrics().srEvaluateCount;r.enabled=graph.srEnabled();
+ if(!ms.empty()){std::sort(ms.begin(),ms.end());r.srMs=ms[ms.size()/2];}
+ r.ok=ok;out={};ring.drainQueue();graph.shutdown();return r;
+}
+engine::EnhancementSettings vsr(unsigned quality,pipeline::SrTarget target,pipeline::SrPrescale prescale=pipeline::SrPrescale::Off,pipeline::SrOutput output=pipeline::SrOutput::Target){
+ engine::EnhancementSettings s;s.nr=false;s.sr=quality!=0;s.multiplier=1;s.videoSrQuality=quality?quality:engine::kDefaultVideoSrQuality;
+ s.srTarget=target;s.srPrescale=prescale;s.srOutput=output;s.srMotion=engine::MotionSource::Zero;s.hdrOutputMode=engine::HdrOutputMode::ScRgb;
+ return s;
+}
+// CPU area average of an image by an integer factor, SDR (sRGB) or scRGB FP16.
+std::vector<double> shrink(const sink::RgbaImage& img,unsigned factor,bool hdr){
+ const unsigned w=img.width/factor,h=img.height/factor;std::vector<double> out(size_t(w)*h*3);
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x)for(unsigned c=0;c<3;++c){
+ double sum=0;for(unsigned j=0;j<factor;++j)for(unsigned i=0;i<factor;++i){
+ const size_t p=(size_t(y*factor+j)*img.width+x*factor+i)*4+c;sum+=hdr?half(img,p):decode(img.pixels[p]);}
+ out[(size_t(y)*w+x)*3+c]=sum/(factor*factor);
+ }
+ return out;
+}
+int test(const std::filesystem::path& directory){
+ std::filesystem::create_directories(directory);Logger::instance().openFile((directory/L"engine.log").wstring());
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ if(!ctx.initialize({},status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ bool ok=true;
+ const auto check=[&](bool pass,const std::string& label){std::cout<<(pass?"PASS ":"FAIL ")<<label<<std::endl;ok=ok&&pass;};
+ using pipeline::SrTarget;using pipeline::SrPrescale;using pipeline::SrOutput;using pipeline::Extent;
+ const auto uhd=pattern(3840,2160),qhd=pattern(2560,1440);
+ const auto uhdSdr=sdrFrame(uhd),qhdSdr=sdrFrame(qhd),uhdHdr=hdrFrame(uhd),qhdHdr=hdrFrame(qhd);
+ if(!uhdSdr||!qhdSdr||!uhdHdr||!qhdHdr)return 2;
+ // 1. Without SR the input/output conversion is transparent (the A/B baseline).
+ {
+ const auto off=run(ctx,ring,uhdSdr.get(),false,vsr(0,SrTarget::Uhd4K),false);
+ int worst=0;for(size_t i=0;off.ok&&i<uhd.pixels.size();++i)if(i%4!=3)worst=std::max(worst,std::abs(int(off.output.pixels[i])-int(uhd.pixels[i])));
+ check(off.ok&&off.output.width==3840&&worst<=1,"SDR input/output conversion is transparent (max "+std::to_string(worst)+")");
+ }
+ // 2. SDR prescale: 4K -> 1080p -> RTX Video SR 4K.
+ for(const unsigned quality:{1u,4u}){
+ const auto native=run(ctx,ring,uhdSdr.get(),false,vsr(quality,SrTarget::Uhd4K),true);
+ const auto shrunk=run(ctx,ring,uhdSdr.get(),false,vsr(quality,SrTarget::Uhd4K,SrPrescale::P1080),true);
+ check(native.ok&&native.enabled&&native.srInput.width==3840&&native.evaluations==6,"SDR q"+std::to_string(quality)+" single step: 4K native restore runs RTX Video SR");
+ check(shrunk.ok&&shrunk.enabled&&shrunk.srIn==Extent{1920,1080}&&shrunk.srOut==Extent{3840,2160}&&shrunk.srInput.width==1920&&
+ shrunk.srInput.height==1080&&shrunk.output.width==3840&&shrunk.output.height==2160&&shrunk.evaluations==6,
+ "SDR q"+std::to_string(quality)+" prescale: SR reads 1920x1080 and writes 3840x2160");
+ if(native.ok&&shrunk.ok&&native.srInput.width==3840&&shrunk.srInput.width==1920){
+ const auto reference=shrink(native.srInput,2,false);int worst=0;size_t over=0,count=0;
+ for(size_t p=0;p<size_t(1920)*1080;++p)for(unsigned c=0;c<3;++c){
+ const int d=std::abs(int(shrunk.srInput.pixels[p*4+c])-int(std::lround(encode(reference[p*3+c]))));worst=std::max(worst,d);over+=d>1;++count;}
+ check(worst<=2&&over*1000<count,"SDR q"+std::to_string(quality)+" prescale equals the area average in linear light (max "+std::to_string(worst)+", >1: "+std::to_string(over)+")");
+ }
+ std::cout<<"STAGE_TIMING case=sdr-4k q="<<quality<<" nativeSrMs="<<native.srMs<<" prescale1080SrMs="<<shrunk.srMs<<std::endl;
+ }
+ // 3. SDR fit: 2K -> RTX Video SR 8K -> 4K equals the area average of the 8K run.
+ {
+ const auto full=run(ctx,ring,qhdSdr.get(),false,vsr(2,SrTarget::Uhd8K),false);
+ const auto fit=run(ctx,ring,qhdSdr.get(),false,vsr(2,SrTarget::Uhd8K,SrPrescale::Off,SrOutput::Uhd4K),false);
+ check(full.ok&&full.output.width==7680&&fit.ok&&fit.enabled&&fit.srOut==Extent{7680,4320}&&fit.work==Extent{3840,2160}&&
+ fit.output.width==3840&&fit.output.height==2160&&fit.evaluations==6,"SDR fit: SR writes 7680x4320, the chain runs at 3840x2160");
+ if(full.ok&&fit.ok&&full.output.width==7680&&fit.output.width==3840){
+ const auto reference=shrink(full.output,2,false);int worst=0;size_t over=0,count=0;
+ for(size_t p=0;p<size_t(3840)*2160;++p)for(unsigned c=0;c<3;++c){
+ const int d=std::abs(int(fit.output.pixels[p*4+c])-int(std::lround(encode(reference[p*3+c]))));worst=std::max(worst,d);over+=d>1;++count;}
+ check(worst<=2&&over*200<count,"SDR fit equals the area average of the 8K result (max "+std::to_string(worst)+", >1: "+std::to_string(over)+")");
+ }
+ std::cout<<"STAGE_TIMING case=sdr-2k-8k q=2 fullSrMs="<<full.srMs<<" fitSrMs="<<fit.srMs<<std::endl;
+ }
+ // 4. HDR fit (proxy + restore per SR texel, then the average), scRGB output.
+ {
+ const auto full=run(ctx,ring,qhdHdr.get(),true,vsr(2,SrTarget::Uhd8K),false);
+ const auto fit=run(ctx,ring,qhdHdr.get(),true,vsr(2,SrTarget::Uhd8K,SrPrescale::Off,SrOutput::Uhd4K),false);
+ check(full.ok&&fit.ok&&fit.enabled&&fit.output.width==3840&&full.output.width==7680,"HDR fit: 8K SR result fitted to 3840x2160");
+ if(full.ok&&fit.ok&&full.output.width==7680&&fit.output.width==3840){
+ const auto reference=shrink(full.output,2,true);size_t over=0,count=0,bad=0;double worst=0,peak=0;
+ for(size_t p=0;p<size_t(3840)*2160;++p)for(unsigned c=0;c<3;++c){
+ const double v=half(fit.output,p*4+c),r=reference[p*3+c];if(!std::isfinite(v)){++bad;continue;}
+ const double d=std::abs(v-r);worst=std::max(worst,d);peak=std::max(peak,v);over+=d>0.003+0.003*std::abs(r);++count;}
+ check(!bad&&over*1000<count,"HDR fit equals the area average of the 8K restore (worst "+std::to_string(worst)+", over "+std::to_string(over)+", peak "+std::to_string(peak)+")");
+ }
+ }
+ // 5. HDR prescale. HdrRestore returns base + a delta clamped to +-0.5*203/80, so
+ // every output channel lies within that bound of the base it sampled. The
+ // single step must stay near the full linear input; the prescale near the
+ // bilinear-sampled area average of it (a full-size base would fail on the
+ // thin 1000-nit lines).
+ {
+ const auto linear=run(ctx,ring,uhdHdr.get(),true,vsr(0,SrTarget::Uhd4K),false);
+ const auto native=run(ctx,ring,uhdHdr.get(),true,vsr(2,SrTarget::Uhd4K),false);
+ const auto shrunk=run(ctx,ring,uhdHdr.get(),true,vsr(2,SrTarget::Uhd4K,SrPrescale::P1080),false);
+ check(linear.ok&&native.ok&&shrunk.ok&&shrunk.enabled&&shrunk.srIn==Extent{1920,1080}&&shrunk.output.width==3840,"HDR prescale: SR reads 1920x1080");
+ if(linear.ok&&native.ok&&shrunk.ok&&linear.output.width==3840&&native.output.width==3840&&shrunk.output.width==3840){
+ const auto base=shrink(linear.output,2,true);
+ const auto sample=[&](unsigned x,unsigned y,unsigned c){
+ const double px=(x+0.5)*0.5-0.5,py=(y+0.5)*0.5-0.5;const int qx=int(std::floor(px)),qy=int(std::floor(py));
+ const double fx=px-qx,fy=py-qy;double v=0;
+ for(int j=0;j<2;++j)for(int i=0;i<2;++i){const int sx=std::clamp(qx+i,0,1919),sy=std::clamp(qy+j,0,1079);
+ v+=base[(size_t(sy)*1920+sx)*3+c]*(i?fx:1-fx)*(j?fy:1-fy);}
+ return v;};
+ const double bound=0.5*203.0/80.0+0.05;double worstNative=0,worstShrunk=0,a=0,b=0;size_t bad=0;
+ for(unsigned y=0;y<2160;++y)for(unsigned x=0;x<3840;++x)for(unsigned c=0;c<3;++c){
+ const size_t i=(size_t(y)*3840+x)*4+c;const double n=half(native.output,i),s=half(shrunk.output,i);
+ if(!std::isfinite(n)||!std::isfinite(s)){++bad;continue;}
+ worstNative=std::max(worstNative,std::abs(n-half(linear.output,i)));worstShrunk=std::max(worstShrunk,std::abs(s-sample(x,y,c)));a+=n;b+=s;}
+ check(!bad&&worstNative<=bound,"HDR single step stays within the restore clamp of the full base ("+std::to_string(worstNative)+")");
+ check(!bad&&worstShrunk<=bound,"HDR prescale restores from the shrunk base ("+std::to_string(worstShrunk)+")");
+ check(std::abs(b/a-1)<0.03,"HDR prescale keeps the mean brightness (ratio "+std::to_string(b/a)+")");
+ }
+ }
+ ring.shutdown();ctx.shutdown();std::cout<<"STAGE_RESULT passed="<<ok<<std::endl;return ok?0:1;
+}
+int boundaries(const std::filesystem::path& directory){
+ std::filesystem::create_directories(directory);Logger::instance().openFile((directory/L"engine.log").wstring());
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ if(!ctx.initialize({},status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ bool ok=true;
+ const auto check=[&](bool pass,const char* label){std::cout<<(pass?"PASS ":"FAIL ")<<label<<std::endl;ok=ok&&pass;};
+ using pipeline::SrTarget;using pipeline::SrPrescale;using pipeline::SrOutput;using pipeline::Extent;
+ const auto frame=sdrFrame(pattern(3840,2160));if(!frame)return 2;
+ auto settings=vsr(1,SrTarget::Qhd,SrPrescale::P1080);
+ const auto down=run(ctx,ring,frame.get(),false,settings,false);
+ check(down.ok&&down.enabled&&down.work==Extent{2560,1440}&&down.evaluations==6,
+ "4K -> 1080p -> 2K runs with a chain output smaller than the source");
+ settings.nr=true;settings.lowLatency=true;settings.nrPolicy=pipeline::NrSizePolicy::Native;
+ settings.nrTemporal=false;settings.nrMotion=engine::MotionSource::Zero;
+ const auto nrFirst=run(ctx,ring,frame.get(),false,settings,false);
+ check(nrFirst.ok&&nrFirst.enabled&&nrFirst.work==Extent{2560,1440}&&nrFirst.evaluations==6,
+ "native NR at source 4K -> prescale 1080p -> VSR 2K retains the source NR extent");
+ settings.nr=false;settings.lowLatency=false;settings.srPrescale=SrPrescale::P720;
+ settings.srTarget=SrTarget::Uhd4K;settings.srOutput=SrOutput::Qhd;
+ const auto fit=run(ctx,ring,frame.get(),false,settings,false);
+ check(fit.ok&&fit.enabled&&fit.srIn==Extent{1280,720}&&fit.srOut==Extent{3840,2160}&&fit.work==Extent{2560,1440},
+ "4K -> 720p -> VSR 4K -> 2K supports a non-integer area resolve");
+ ring.shutdown();ctx.shutdown();std::cout<<"STAGE_BOUNDARIES passed="<<ok<<std::endl;return ok?0:1;
+}
+int capabilities(const std::filesystem::path& directory){
+ std::filesystem::create_directories(directory);Logger::instance().openFile((directory/L"engine.log").wstring());
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ if(!ctx.initialize({},status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ using pipeline::SrTarget;using pipeline::SrPrescale;using pipeline::SrOutput;using pipeline::Extent;
+ const auto frame=sdrFrame(pattern(3840,2160)),wide=sdrFrame(pattern(3840,1600));if(!frame||!wide)return 2;
+ bool ok=true;unsigned cases=0;
+ for(unsigned quality=1;quality<=4;++quality){
+ for(auto target:{SrTarget::Uhd5K,SrTarget::Uhd6K,SrTarget::Uhd7K,SrTarget::Uhd8K}){
+ const auto result=run(ctx,ring,frame.get(),false,vsr(quality,target,SrPrescale::P1080,SrOutput::Uhd4K),false,false,false,2);
+ const bool passed=result.ok&&result.srIn==Extent{1920,1080}&&result.srOut==pipeline::srTargetExtent(target)&&
+ result.work==Extent{3840,2160}&&result.evaluations==2;
+ std::cout<<"STAGE_CAPABILITY q="<<quality<<" target="<<uint32_t(target)<<" passed="<<passed<<std::endl;ok=ok&&passed;++cases;
+ }
+ for(bool isWide:{false,true}){
+ const auto result=run(ctx,ring,isWide?wide.get():frame.get(),false,vsr(quality,SrTarget::Uhd4K,isWide?SrPrescale::P1080:SrPrescale::P720),false,false,false,2);
+ const bool passed=result.ok&&result.evaluations==2&&result.work==(isWide?Extent{3840,1600}:Extent{3840,2160});
+ std::cout<<"STAGE_CAPABILITY q="<<quality<<" wide="<<isWide<<" scale="<<(isWide?2:3)<<" passed="<<passed<<std::endl;ok=ok&&passed;++cases;
+ }
+ }
+ ring.shutdown();ctx.shutdown();std::cout<<"STAGE_CAPABILITIES cases="<<cases<<" passed="<<ok<<std::endl;return ok?0:1;
+}
+pipeline::SrPrescale prescaleArg(std::wstring_view v){
+ if(v==L"720")return pipeline::SrPrescale::P720;if(v==L"900")return pipeline::SrPrescale::P900;
+ if(v==L"1080")return pipeline::SrPrescale::P1080;if(v==L"1440")return pipeline::SrPrescale::P1440;
+ if(v.ends_with(L"%"))return pipeline::srPrescaleForPercent(unsigned(std::stoi(std::wstring(v.substr(0,v.size()-1)))));
+ return pipeline::SrPrescale::Off;
+}
+pipeline::SrTarget targetArg(std::wstring_view v){
+ if(v==L"2k")return pipeline::SrTarget::Qhd;if(v==L"5k")return pipeline::SrTarget::Uhd5K;if(v==L"6k")return pipeline::SrTarget::Uhd6K;
+ if(v==L"7k")return pipeline::SrTarget::Uhd7K;if(v==L"8k")return pipeline::SrTarget::Uhd8K;return pipeline::SrTarget::Uhd4K;
+}
+pipeline::SrOutput outputArg(std::wstring_view v){
+ if(v==L"source")return pipeline::SrOutput::Source;if(v==L"2k")return pipeline::SrOutput::Qhd;if(v==L"4k")return pipeline::SrOutput::Uhd4K;
+ if(v==L"5k")return pipeline::SrOutput::Uhd5K;if(v==L"6k")return pipeline::SrOutput::Uhd6K;if(v==L"7k")return pipeline::SrOutput::Uhd7K;return pipeline::SrOutput::Target;
+}
+// One A/B picture: <dir> stage-image <input.png> <name> <quality 0..4> <prescale> <target> <output> [video|still|capture]
+int image(const std::filesystem::path& directory,const std::wstring& input,const std::wstring& name,unsigned quality,
+ std::wstring_view prescale,std::wstring_view target,std::wstring_view output,std::wstring_view mode){
+ std::filesystem::create_directories(directory);Logger::instance().openFile((directory/(name+L".log")).wstring());
+ sink::RgbaImage source;if(!sink::loadImage(input,source))return 2;
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ if(!ctx.initialize({},status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ const auto frame=sdrFrame(source);if(!frame)return 2;
+ const auto r=run(ctx,ring,frame.get(),false,vsr(quality,targetArg(target),prescaleArg(prescale),outputArg(output)),false,mode==L"still",mode==L"capture");
+ std::error_code ec;std::filesystem::remove(directory/(name+L".png"),ec); // saveImage never replaces a file
+ const bool saved=r.ok&&sink::saveImage((directory/(name+L".png")).wstring(),r.output,false);
+ std::cout<<"STAGE_IMAGE name="<<std::string(name.begin(),name.end())<<" source="<<source.width<<'x'<<source.height<<" srInput="<<r.srIn.width<<'x'<<r.srIn.height<<" srOutput="<<r.srOut.width<<'x'<<r.srOut.height
+ <<" output="<<r.output.width<<'x'<<r.output.height<<" srActive="<<r.enabled<<" evaluations="<<r.evaluations<<" srMs="<<r.srMs<<" passed="<<saved<<std::endl;
+ ring.shutdown();ctx.shutdown();return saved?0:1;
+}
+}
+
int wmain(int argc,wchar_t** argv){
using namespace veyra;
if(argc<2)return 2;
const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if(FAILED(com))return 2;
+ if(argc==3&&std::wstring_view(argv[2])==L"stage"){const int result=stage::test(argv[1]);CoUninitialize();return result;}
+ if(argc==3&&std::wstring_view(argv[2])==L"stage-boundaries"){const int result=stage::boundaries(argv[1]);CoUninitialize();return result;}
+ if(argc==3&&std::wstring_view(argv[2])==L"stage-capabilities"){const int result=stage::capabilities(argv[1]);CoUninitialize();return result;}
+ if(argc>=9&&std::wstring_view(argv[2])==L"stage-image"){
+ const int result=stage::image(argv[1],argv[3],argv[4],unsigned(std::stoi(argv[5])),argv[6],argv[7],argv[8],argc>9?argv[9]:L"video");
+ CoUninitialize();return result;
+ }
if(argc>5&&(std::wstring_view(argv[2])==L"reference"||std::wstring_view(argv[2])==L"models")){
const std::wstring_view mode=argv[5];
if(mode.starts_with(L"legacy-"))return 2; // withdrawn experiment; no production toggle remains
diff --git a/tests/unit/EffectChainTests.cpp b/tests/unit/EffectChainTests.cpp
index da79d1dd..085031e1 100644
--- a/tests/unit/EffectChainTests.cpp
+++ b/tests/unit/EffectChainTests.cpp
@@ -1403,6 +1403,120 @@ __declspec(noinline) void testWideChains() {
"E0: the runtime order transports every node of a wide chain");
}
+// Three-step SR (2026-10-28): shrink, RTX Video SR, fit. Off/Target must stay the
+// single-step sizes; the plan, the chain step and the graph description agree.
+static void testThreeStepSr(){
+ using namespace veyra;using pipeline::Extent;using pipeline::SrPrescale;using pipeline::SrOutput;using pipeline::SrTarget;
+ bool same=true;unsigned cases=0;
+ const std::array<Extent,7> sources{{{640,360},{1280,720},{1920,1080},{2560,1440},{3840,2160},{3840,1600},{1080,1920}}};
+ for(const auto source:sources)for(uint32_t target=0;target<=uint32_t(SrTarget::Uhd7K);++target){
+ const auto box=pipeline::srTargetExtent(SrTarget(target));
+ const double scale=std::min(double(box.width)/source.width,double(box.height)/source.height);
+ const Extent expected=scale>1.0?Extent{std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)}:source;
+ const auto stage=pipeline::srStageExtents(source,SrTarget(target));
+ const auto plan=pipeline::ResolutionPlan::make(source,true,pipeline::NrSizePolicy::Native,false,0,SrTarget(target));
+ same=same&&stage.input==source&&stage.evaluated==expected&&stage.output==expected&&!stage.prescaleIneffective&&!stage.outputIneffective&&
+ plan.base==expected&&plan.srInput==source&&plan.srOutput==expected&&plan.srApplied==(expected!=source);
+ ++cases;
+ }
+ check(same&&cases==42,"three-step SR: off/target keeps the single-step sizes for every source and target");
+ struct Case{Extent source;SrPrescale prescale;SrTarget target;SrOutput fit;Extent input,evaluated,output;bool prescaleOff,outputOff;const char* label;};
+ const Case table[]={
+ {{3840,2160},SrPrescale::P1080,SrTarget::Uhd4K,SrOutput::Target,{1920,1080},{3840,2160},{3840,2160},false,false,"three-step SR: blurry 4K -> 1080p -> 4K"},
+ {{3840,2160},SrPrescale::P1440,SrTarget::Uhd4K,SrOutput::Target,{2560,1440},{3840,2160},{3840,2160},false,false,"three-step SR: 4K -> 1440p -> 4K"},
+ {{2560,1440},SrPrescale::Off,SrTarget::Uhd8K,SrOutput::Uhd4K,{2560,1440},{7680,4320},{3840,2160},false,false,"three-step SR: native 2K -> 8K -> fit 4K"},
+ {{2560,1440},SrPrescale::P1080,SrTarget::Uhd4K,SrOutput::Target,{1920,1080},{3840,2160},{3840,2160},false,false,"three-step SR: native 2K -> 1080p -> 4K"},
+ {{3840,2160},SrPrescale::P1080,SrTarget::Uhd8K,SrOutput::Uhd4K,{1920,1080},{7680,4320},{3840,2160},false,false,"three-step SR: 4K -> 1080p -> 8K -> fit 4K"},
+ {{3840,1600},SrPrescale::P1080,SrTarget::Uhd4K,SrOutput::Target,{1920,800},{3840,1600},{3840,1600},false,false,"three-step SR: 21:9 keeps its aspect"},
+ {{3840,2160},pipeline::srPrescaleForPercent(75),SrTarget::Uhd4K,SrOutput::Target,{2880,1620},{3840,2160},{3840,2160},false,false,"three-step SR: manual 75 %"},
+ {{2560,1440},SrPrescale::Off,SrTarget::Uhd8K,SrOutput::Source,{2560,1440},{7680,4320},{2560,1440},false,false,"three-step SR: fit back to the exact source size"},
+ {{1920,1080},SrPrescale::Off,SrTarget::Uhd4K,SrOutput::Qhd,{1920,1080},{3840,2160},{2560,1440},false,false,"three-step SR: 1080p -> 4K -> fit 2K"},
+ {{1920,1080},SrPrescale::P1080,SrTarget::Uhd4K,SrOutput::Target,{1920,1080},{3840,2160},{3840,2160},true,false,"three-step SR: a source already at the prescale size is reported, not shrunk"},
+ {{3840,2160},SrPrescale::P1440,SrTarget::Qhd,SrOutput::Target,{3840,2160},{3840,2160},{3840,2160},true,false,"three-step SR: a prescale nothing can enlarge again is not applied"},
+ {{3840,2160},pipeline::srPrescaleForPercent(90),SrTarget::Qhd,SrOutput::Target,{3840,2160},{3840,2160},{3840,2160},true,false,"three-step SR: manual 90 % of 4K with a 2K target is not applied"},
+ {{3840,2160},SrPrescale::Off,SrTarget::Uhd4K,SrOutput::Qhd,{3840,2160},{3840,2160},{3840,2160},false,true,"three-step SR: the output fit needs an enlarging SR"},
+ {{1920,1080},SrPrescale::Off,SrTarget::Uhd4K,SrOutput::Uhd5K,{1920,1080},{3840,2160},{3840,2160},false,true,"three-step SR: an output box larger than the SR result is reported"},
+ };
+ for(const auto& c:table){
+ const auto s=pipeline::srStageExtents(c.source,c.target,c.prescale,c.fit);
+ const bool ok=s.input==c.input&&s.evaluated==c.evaluated&&s.output==c.output&&s.prescaleIneffective==c.prescaleOff&&s.outputIneffective==c.outputOff;
+ if(!ok)std::printf(" got %ux%u -> %ux%u -> %ux%u flags %d %d\n",s.input.width,s.input.height,s.evaluated.width,s.evaluated.height,
+ s.output.width,s.output.height,int(s.prescaleIneffective),int(s.outputIneffective));
+ check(ok,c.label);
+ }
+ {
+ const auto plan=pipeline::ResolutionPlan::make({3840,2160},true,pipeline::NrSizePolicy::Realtime,false,0,SrTarget::Uhd4K,false,0,SrPrescale::P1080);
+ const auto single=pipeline::ResolutionPlan::make({3840,2160},true,pipeline::NrSizePolicy::Realtime,false,0,SrTarget::Uhd4K);
+ check(plan.srApplied&&!single.srApplied&&plan.srInput==Extent{1920,1080}&&plan.srOutput==Extent{3840,2160}&&
+ plan.base==single.base&&plan.nr==single.nr&&plan.flow==single.flow&&plan.output==single.output,
+ "three-step SR: a 4K prescale changes only what SR reads; NR, flow and output sizes stay");
+ }
+ // The chain step: present even when the source already has the target size.
+ EnhancementSettings s;s.nr=false;s.sr=true;s.videoSrQuality=3;s.srPrescale=SrPrescale::P1080;
+ {
+ const auto chain=toChain(s);
+ ChainExecutionPlan plan;ChainExecutionRequest request{{3840,2160},SrTarget::Uhd4K,false,false,false,SrPrescale::P1080,SrOutput::Target};
+ bool ok=compileChainExecutionPlan(chain,request,plan).accepted&&plan.resourceCounts[size_t(EffectType::SuperResolution)]==1;
+ for(uint32_t i=0;i<plan.stepCount;++i)if(plan.steps[i].type==EffectType::SuperResolution)
+ ok=ok&&plan.steps[i].input==Extent{3840,2160}&&plan.steps[i].processing==Extent{3840,2160}&&plan.steps[i].output==Extent{3840,2160};
+ check(ok,"three-step SR: 4K -> 1080p -> 4K keeps an SR step");
+ request.srPrescale=SrPrescale::Off;
+ check(compileChainExecutionPlan(chain,request,plan).accepted&&plan.resourceCounts[size_t(EffectType::SuperResolution)]==0,
+ "three-step SR: without it a 4K source at a 4K target still has no SR step");
+ ChainExecutionRequest fit{{2560,1440},SrTarget::Uhd8K,false,false,false,SrPrescale::Off,SrOutput::Uhd4K};
+ ok=compileChainExecutionPlan(chain,fit,plan).accepted&&plan.output==Extent{3840,2160};
+ for(uint32_t i=0;i<plan.stepCount;++i)if(plan.steps[i].type==EffectType::SuperResolution)
+ ok=ok&&plan.steps[i].processing==Extent{7680,4320}&&plan.steps[i].output==Extent{3840,2160};
+ check(ok,"three-step SR: the SR step evaluates 8K and outputs the 4K fit");
+ fit.srPrescale=SrPrescale(5);
+ check(!compileChainExecutionPlan(chain,fit,plan).accepted,"three-step SR: an invalid prescale fails the plan");
+ }
+ // The graph description: RTX Video SR on NVIDIA only.
+ {
+ StageRequest request;request.width=3840;request.height=2160;request.sr=true;request.nvidiaAdapter=true;
+ pipeline::EnhanceGraphDesc desc;describeStages(request,s,desc);
+ check(desc.enableSr&&desc.srInputWidth==1920&&desc.srInputHeight==1080&&desc.srOutputWidth==3840&&desc.srOutputHeight==2160&&
+ desc.workWidth==3840&&desc.workHeight==2160&&desc.validateFixedExecutionPlan().empty(),
+ "three-step SR: the graph description carries the shrunk SR input");
+ request.uncompressedSource=true;describeStages(request,s,desc);
+ check(desc.enableSr&&desc.srInputWidth==1920,"three-step SR: an explicit prescale also runs on raw capture");
+ request.uncompressedSource=false;request.exportJob=true;describeStages(request,s,desc);
+ check(desc.enableSr&&desc.srInputWidth==1920&&desc.validateFixedExecutionPlan().empty(),"three-step SR: exports use the same sizes");
+ request.exportJob=false;request.stillImage=true;describeStages(request,s,desc);
+ check(desc.enableSr&&desc.srInputWidth==1920&&desc.validateFixedExecutionPlan().empty(),"three-step SR: still images run it too");
+ request.stillImage=false;
+ for(const unsigned backend:{0u,kVideoSrFsr}){
+ auto other=s;other.videoSrQuality=backend;describeStages(request,other,desc);
+ check(desc.srInputWidth==3840&&desc.srOutputWidth==3840&&!desc.enableSr,"three-step SR: DLSS SR and FSR keep the single step");
+ }
+ request.nvidiaAdapter=false;describeStages(request,s,desc);
+ check(desc.srInputWidth==3840&&desc.srOutputWidth==desc.workWidth,"three-step SR: other adapters keep the single step");
+ request.nvidiaAdapter=true;request.width=2560;request.height=1440;
+ auto fit=s;fit.srPrescale=SrPrescale::Off;fit.srTarget=SrTarget::Uhd8K;fit.srOutput=SrOutput::Uhd4K;describeStages(request,fit,desc);
+ check(desc.enableSr&&desc.srInputWidth==2560&&desc.srOutputWidth==7680&&desc.srOutputHeight==4320&&desc.workWidth==3840&&
+ desc.workHeight==2160&&desc.validateFixedExecutionPlan().empty(),"three-step SR: 2K -> 8K -> 4K works at 4K after SR");
+ }
+ // Settings: validation, inactive normalization, rebuilds and chain globals.
+ {
+ auto bad=s;
+ for(const uint32_t value:{5u,149u,191u}){bad.srPrescale=SrPrescale(value);check(!bad.validate().empty(),"three-step SR: an invalid prescale is rejected");}
+ for(const uint32_t value:{150u,190u}){bad.srPrescale=SrPrescale(value);check(bad.validate().empty(),"three-step SR: manual 50 % and 90 % are valid");}
+ bad=s;bad.srOutput=SrOutput(7);check(!bad.validate().empty(),"three-step SR: an invalid output is rejected");
+ check(s.activeVideoSettings().srPrescale==SrPrescale::P1080,"three-step SR: RTX Video SR keeps the prescale");
+ auto off=s;off.sr=false;auto dlss=s;dlss.videoSrQuality=0;
+ check(off.activeVideoSettings().srPrescale==SrPrescale::Off&&dlss.activeVideoSettings().srPrescale==SrPrescale::Off,
+ "three-step SR: SR off and other backends normalize the fields");
+ auto before=s;before.srPrescale=SrPrescale::Off;auto output=s;output.srOutput=SrOutput::Qhd;
+ check(requiresGraphRebuild(before,s)&&requiresGraphRebuild(s,output),"three-step SR: prescale and output changes rebuild the graph");
+ auto dlssBefore=before;dlssBefore.videoSrQuality=0;
+ check(!requiresGraphRebuild(dlssBefore,dlss),"three-step SR: inactive edits do not rebuild the graph");
+ EnhancementSettings restored;ChainGlobalSettings::capture(output).apply(restored);
+ check(restored.srPrescale==SrPrescale::P1080&&restored.srOutput==SrOutput::Qhd,"three-step SR: chain globals carry both fields");
+ auto a=ChainConfiguration::capture(toChain(s),s,-1,-1);auto b=a;b.srOutput=SrOutput::Qhd;
+ check(!(a==b),"three-step SR: configuration equality sees the output fit");
+ }
+}
+
int main() {
{
using namespace veyra;using namespace veyra::engine;
@@ -1476,6 +1590,7 @@ int main() {
testSameSizeSlots();
testBeautySettingsChain();
testWideChains();
+ testThreeStepSr();
std::printf(failures ? "effect chain: %d FAILURES\n" : "effect chain: all checks passed\n", failures);
return failures ? 1 : 0;
}
diff --git a/tests/unit/PresetLibraryTests.cpp b/tests/unit/PresetLibraryTests.cpp
index 3120aa06..9667b322 100644
--- a/tests/unit/PresetLibraryTests.cpp
+++ b/tests/unit/PresetLibraryTests.cpp
@@ -1100,6 +1100,48 @@ __declspec(noinline) void testDlssSrModels() {
ChainSessionStore finalReader(sessionPath);
check(finalReader.load(*restored)&&*restored==*session,"DLSS session: saved K wins over old M/L choices");
}
+// Three-step SR (2026-10-28): library v16 / session v11 in .sr-stage files; the
+// older files keep their bytes for a 2.1.1 rollback.
+__declspec(noinline) void testSrStageStorage() {
+ EnhancementSettings source;source.nr=false;source.sr=true;source.videoSrQuality=3;
+ const auto libraryPath=scratch(L"sr-stage-library.v1");
+ const auto legacyLibrary=std::filesystem::path(libraryPath).concat(L".field-render");
+ for(const auto* suffix:{L".field-render",L".field-render.sr-stage",L".sr-stage"})std::filesystem::remove(std::filesystem::path(libraryPath).concat(suffix));
+ PresetLibrary writer(libraryPath);writer.setIncludeBuiltins(false);
+ PresetEntry entry;entry.name=L"SR stage";entry.kind=ChainMode::List;
+ entry.contents=presetContentMask(PresetContent::Chain);entry.chain=toChain(source);
+ entry.globals=ChainGlobalSettings::capture(source);
+ check(writer.load()&&writer.put(entry),"SR stage presets: save a single-step library");
+ const auto rollback=readBytes(legacyLibrary);
+ check(!rollback.empty()&&rollback.starts_with("VEYRA_PRESET_LIBRARY 6"),"SR stage presets: single step keeps the old format");
+ entry.globals->srPrescale=veyra::pipeline::SrPrescale::P1080;entry.globals->srOutput=veyra::pipeline::SrOutput::Uhd4K;
+ check(writer.put(entry,true),"SR stage presets: save prescale and output");
+ check(readBytes(legacyLibrary)==rollback,"SR stage presets: original library is retained for rollback");
+ PresetLibrary reader(libraryPath);reader.setIncludeBuiltins(false);
+ check(reader.load()&&reader.entries().size()==1&&reader.entries()[0].globals->srPrescale==veyra::pipeline::SrPrescale::P1080&&
+ reader.entries()[0].globals->srOutput==veyra::pipeline::SrOutput::Uhd4K,"SR stage presets: fresh reader finds the sidecar");
+ auto applied=source;PresetLibrary::apply(reader.entries()[0],applied);
+ check(applied.srPrescale==veyra::pipeline::SrPrescale::P1080&&applied.srOutput==veyra::pipeline::SrOutput::Uhd4K,"SR stage presets: applying the chain restores both");
+ const auto exported=scratch(L"sr-stage-export.v16");
+ check(writer.exportEntry(0,exported)&&readBytes(exported).starts_with("VEYRA_PRESET_LIBRARY 16"),"SR stage presets: export declares v16");
+ entry.name=L"invalid stage";entry.globals->srPrescale=veyra::pipeline::SrPrescale(5);
+ check(!writer.put(entry),"SR stage presets: an invalid prescale is rejected atomically");
+
+ const auto sessionPath=scratch(L"sr-stage-session.v1");
+ for(const auto* suffix:{L".sr-stage",L".p3-editor",L".p3-editor.p3-globals",L".p3-editor.sr-stage"})std::filesystem::remove(std::filesystem::path(sessionPath).concat(suffix));
+ std::filesystem::remove(sessionPath);
+ auto session=std::make_unique<ChainSession>(ChainSession::initial(source));
+ check(session->select(ChainMode::Node),"SR stage session: initialize independent node configuration");
+ ChainSessionStore sessions(sessionPath);
+ check(sessions.save(*session),"SR stage session: save single-step rollback file");
+ const auto sessionRollback=readBytes(sessionPath);
+ session->configurations[0].srPrescale=veyra::pipeline::srPrescaleForPercent(75);
+ session->configurations[1].srOutput=veyra::pipeline::SrOutput::Source;
+ check(sessions.save(*session)&&readBytes(sessionPath)==sessionRollback,"SR stage session: save the new format beside the original");
+ check(readBytes(std::filesystem::path(sessionPath).concat(L".sr-stage")).starts_with("VEYRA_CHAIN_SESSION 11"),"SR stage session: the sidecar declares v11");
+ auto restored=std::make_unique<ChainSession>();ChainSessionStore reopened(sessionPath);
+ check(reopened.load(*restored)&&*restored==*session,"SR stage session: List and Node values round-trip independently");
+}
// E0 (2026-10-18): library v14 / session v9 carry anti-aliasing nodes and chains
// past 16 nodes in their own files; older readers keep their bytes.
__declspec(noinline) void testBeautyNodeStorage() {
@@ -1241,6 +1283,7 @@ int main() {
testEffectNodeStorage();
testBeautyNodeStorage();
testDlssSrModels();
+ testSrStageStorage();
testFlowStorage();
testFlowApplication();
testNrCorrectionStorage();
diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cpp
index 740fa7f9..4d9db2b3 100644
--- a/tests/unit/RepairPresetTests.cpp
+++ b/tests/unit/RepairPresetTests.cpp
@@ -3,6 +3,7 @@
#include <iostream>
#include <fstream>
#include <sstream>
+#include <iterator>
namespace {
bool retiredSrMode(const std::filesystem::path& path) {
using namespace veyra::engine;
@@ -326,4 +327,26 @@ ok=ok&&b.entries().size()==1&&b.defaultSettings()==s;
std::ifstream header(path);std::string magic;unsigned version=0;roundtrip=roundtrip&&bool(header>>magic>>version)&&version==(model?31:21);
ok&=roundtrip;std::cout<<"DLSS model="<<model<<" schema="<<version<<" roundtrip="<<roundtrip<<'\n';
}
+ // Three-step SR (v33): the schema changes only when a preset uses it; a bad
+ // value in a v33 row fails the whole file, which is then kept.
+ for(unsigned mode=0;mode<3;++mode){
+ EnhancementSettings stage;stage.nr=false;stage.sr=true;
+ if(mode==1)stage.srPrescale=veyra::pipeline::SrPrescale::P1080;
+ if(mode==2){stage.srPrescale=veyra::pipeline::srPrescaleForPercent(75);stage.srOutput=veyra::pipeline::SrOutput::Uhd4K;}
+ auto path=p;path+=L"-sr-stage-"+std::to_wstring(mode);
+ std::error_code ec;std::filesystem::remove(path,ec);
+ PresetStore writer(path);bool roundtrip=writer.load()&&writer.put(L"SR stage",stage);
+ PresetStore reader(path);roundtrip=roundtrip&&reader.load()&&reader.entries().size()==1&&reader.entries()[0].settings==stage;
+ std::ifstream header(path);std::string magic;unsigned version=0;roundtrip=roundtrip&&bool(header>>magic>>version)&&version==(mode?33:21);
+ header.close();
+ if(mode==1){
+ std::ifstream in(path,std::ios::binary);std::string text((std::istreambuf_iterator<char>(in)),{});in.close();
+ const auto end=text.find_last_not_of("\r\n"),last=text.rfind(' ',end),before=text.rfind(' ',last-1);
+ text.replace(before+1,last-before-1,"5");
+ auto broken=p;broken+=L"-sr-stage-invalid";std::ofstream(broken,std::ios::binary)<<text;
+ PresetStore bad(broken);roundtrip=roundtrip&&!bad.load();
+ std::ifstream kept(broken,std::ios::binary);roundtrip=roundtrip&&std::string((std::istreambuf_iterator<char>(kept)),{})==text;
+ }
+ ok&=roundtrip;std::cout<<"SR stage mode="<<mode<<" schema="<<version<<" roundtrip="<<roundtrip<<'\n';
+ }
std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}