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

perf: prototype paused single-NR residual reuse after reset-output baseline

Veyra Goal Agent0ef0227cf230
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e54cd46d..e6d8270f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -170,7 +170,7 @@ add_library(veyra_ngx STATIC
target_link_libraries(veyra_ngx PRIVATE
"$<IF:$<CONFIG:Debug>,${VEYRA_DLSS_SDK_ROOT}/lib/Windows_x86_64/x64/nvsdk_ngx_s_dbg.lib,${VEYRA_DLSS_SDK_ROOT}/lib/Windows_x86_64/x64/nvsdk_ngx_s.lib>")
target_compile_definitions(veyra_ngx PUBLIC
- VEYRA_EXPERIMENTAL_LOCAL_DLSSNR=1 VEYRA_HAS_NGX_CORE_CACHE=1)
+ VEYRA_EXPERIMENTAL_LOCAL_DLSSNR=1 VEYRA_HAS_NGX_CORE_CACHE=1 VEYRA_HAS_PAUSED_NR_RESIDUAL_REUSE=1)
# Diagnostic: exercises the Ada multi-frame unlock against the local DLSS-G
# runtime image without involving NGX (works on any NVIDIA adapter).
@@ -1018,6 +1018,14 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_features(veyra_nr_static_input_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_static_input_experiment PRIVATE /utf-8)
target_link_libraries(veyra_nr_static_input_experiment PRIVATE veyra_engine bcrypt)
+ add_executable(veyra_duplicate_gpu_experiment tests/perf/DuplicateGpuExperiment.cpp)
+ target_compile_features(veyra_duplicate_gpu_experiment PRIVATE cxx_std_20)
+ target_compile_options(veyra_duplicate_gpu_experiment PRIVATE /utf-8)
+ target_link_libraries(veyra_duplicate_gpu_experiment PRIVATE veyra_engine d3dcompiler)
+ add_executable(veyra_nr_paused_residual_experiment tests/perf/NrPausedResidualExperiment.cpp)
+ target_compile_features(veyra_nr_paused_residual_experiment PRIVATE cxx_std_20)
+ target_compile_options(veyra_nr_paused_residual_experiment PRIVATE /utf-8)
+ target_link_libraries(veyra_nr_paused_residual_experiment PRIVATE veyra_engine bcrypt)
add_executable(veyra_nr_core_cache_contract_tests tests/perf/NrCoreCacheContractTests.cpp)
target_compile_features(veyra_nr_core_cache_contract_tests PRIVATE cxx_std_20)
target_compile_options(veyra_nr_core_cache_contract_tests PRIVATE /utf-8)
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 606477be..8036280c 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -4,7 +4,7 @@
公开版本:2.0.3(main `354b1c6`,产品源码 `f82f649`);AMD/NVIDIA分包、AMD NR宿主、VFG全档、Xbox/导出码率/背景/极简缺口修复已发布。当前优化从本地修复tip `8cdc612` 开出 `codex/perf-nr-20261004`,工作树 `E:/项目/Veyra/worktrees/perf-nr-20261004`;继承已验RTSS误提示/重启循环、自定义倍速/字幕/UI热路径/专业布局和全屏恢复。它们尚未进入远端2.0.3,不能将本地候选称为公开版本。
-本轮按 `PERF_PLAN_NR_2026-10-03.md` / `PERF_EXECUTION_NR_2026-10-04.md`:先对齐文档/归档,再全新构建当前基线、逐节点A/B/B-off复测和存档,负优化回退。原方案中RTSS/启动优化“未合并”和2.0.1基线为历史状态,不再执行重复合并。产品性能改动及本轮基线尚未开始,下面早期阶段条目均按各自日期理解。
+本轮按 `PERF_PLAN_NR_2026-10-03.md` / `PERF_EXECUTION_NR_2026-10-04.md`:先对齐文档/归档,再全新构建当前基线、逐节点A/B/B-off复测和存档,负优化回退。原方案中RTSS/启动优化“未合并”和2.0.1基线为历史状态,不再执行重复合并。M1五设置各三轮优化前基线已封存;2a核心复用暖创建减少约65–76%,三轮画面完全一致,保留待R0。重复帧整链复用/节奏盲预测均有画面反例,未加入产品;E1/E2/E3实验分别记录边界。5c窄范围候选及其余节点继续,不能称全方案完成。下面早期阶段条目均按各自日期理解。
仍未解决/未验:严重后台掉帧根因;真实Xbox有声/长期稳定;AMD RX9000推理/画质;RTX30/40实际NR/FG;用户616.92;物理显示节奏/端到端延迟。HDR/Dolby PR13/14用户暂缓,不纳入此次优化。不merge/push/Release/关机,不改用户驱动、配置或原桌面工作树。
diff --git a/docs/PERF_5C_PAUSED_NR_2026-10-04.md b/docs/PERF_5C_PAUSED_NR_2026-10-04.md
new file mode 100644
index 00000000..f37f85fb
--- /dev/null
+++ b/docs/PERF_5C_PAUSED_NR_2026-10-04.md
@@ -0,0 +1,11 @@
+# 5c:暂停GPU与残差编辑候选
+
+现有Engine暂停循环不重复调用EnhanceGraph,仅每50ms重新呈现保留帧;普通暂停不跑NR已实现。仍需实际30秒计数/GPU测量与设置刷新回归,不能仅从代码推断整卡GPU占用为零。
+
+前置实测 `pause-reset-M1-v1`:M1第一张自然图像、300次相同输入,每次明确reset,单层NR三轮输出均逐字节相同;NR+DLSS SR三轮各262张不同。各轮native安全通过、debug0、设备正常,原始数据 `E:/项目/Veyra/logs/perf-nr-20261004/pause-reset-M1-v1-*`。因此不能将暂停复用推广到超分链路。
+
+候选只在NVIDIA单层、无抗闪烁/稳定器、无SR/FG/HDR/颜色节点、相同不可变暂停AVFrame/源序号/PTS情况下,复用一次成功“暂停刷新且reset”的NR结果;首个暂停编辑完整处理,不复用此前连续播放的历史。只改残差参数(其余完整EnhancementSettings逐项相同)才复用;模型/颜色/源/seek/普通播放/失败/重建全部失效。保留原残差着色器和输出/租约/fence路径,无GPU像素回读。
+
+`VEYRA_TEST_DISABLE_PAUSED_NR_RESIDUAL_REUSE=1` 在同EXE回退;`paused-nr-cache event=reuse` 与真实NR Evaluate计数分别记录。原生实验每组300次暂停残差编辑,150次时改变NR模型以验证失效;保存完整输出SHA和关键帧。优化前EXE已封存 `E:/项目/Veyra/tests/perf-nr-20261004/A5c-paused-v1-app/`,SHA066ac43c6df06819b181e564fb2a42ed2b1d82441f3fc31837bdbf0d07986045。
+
+当前为待构建/待A-B-B-off候选;没有实际收益或保留决定。SR、抗闪烁、多层组合必须保持完整处理并验证输出。真实Qt暂停30秒、连续编辑、模型/源切换和恢复播放仍待回归。不设置灰色空壳开关。
diff --git a/docs/PERF_E3_DUPLICATE_SOURCE_2026-10-04.md b/docs/PERF_E3_DUPLICATE_SOURCE_2026-10-04.md
new file mode 100644
index 00000000..cc0e33a2
--- /dev/null
+++ b/docs/PERF_E3_DUPLICATE_SOURCE_2026-10-04.md
@@ -0,0 +1,36 @@
+# E3:真实WGC重复比例与精确GPU比较成本
+
+本机RTX5070 / 616.56,Windows显示器处于HDR;只捕获隔离测试的GDI子进程窗口,不读取用户桌面或其他应用。原生程序使用产品ScreenCaptureSource、真实生产者fence与有界AVFrame租约,再调用精确GPU比较器;FP16源比较RGBA。不运行任何NR/SR跳帧候选。
+
+## 真实屏幕来源
+
+`E3-own-window-v3-capture-r1` 连续三阶段,各60秒,native exit0、D3D12 debug error0、设备正常、生产者丢帧0。
+
+| 实际来源阶段 | 收到帧数 | 精确重复帧 | 重复比例(含第一帧作分母) |
+|---|---:|---:|---:|
+| 静止条纹,每16ms请求重绘 | 1476 | 1475 | 99.932% |
+| 条纹中的白框持续移动 | 1481 | 8 | 0.540% |
+| 拖动本测试窗口位置,内部条纹不动 | 1589 | 1588 | 99.937% |
+
+请求60fps不等于实际60fps:本次实际交付24.60、24.68、26.48fps。等待轮询不是重复帧,不纳入分母。移动窗口位置不会必然改变“捕获该窗口内部”的像素;此阶段不是全桌面窗口拖动的统计,更不是主机游戏统计。WGC日志的compositorToReadMs含时钟/CPU观察误差,出现少量负值,未用于物理延迟结论。
+
+原始日志、逐帧sequence/PTS/精确结果/GPU timestamp/等待时间位于 `E:/项目/Veyra/logs/perf-nr-20261004/E3-own-window-v3-capture-r1/`;运行与文件身份见result.json及 `E3-own-window-v3-summary.json`。
+
+## GPU比较正确性和成本
+
+从GPL-3.0来源SAOG0721/Magpie固定提交27c5df91177a29b33be612e98274169f3d2fca49移植8×8组归并及每组单次原子;四次有界Load替换Gather,适配现有无sampler根签名。来源、修改和原件SHA见THIRD_PARTY_NOTICES及shader头;只用于测试。19×17奇数尺寸末像素单LSB、SDR忽略alpha/FP16比较alpha、历史更新、epoch失效均通过;每尺寸300重复+300变化帧、三轮共3600次check调用,其中12次建立历史。第一帧不当作重复。
+
+下表排除每段前11帧,取各轮中位,再取三轮中位。readback等待与history拷贝均是真实完成后才读取;未将未就绪结果作为相同。
+
+| 尺寸/内容 | GPU dispatch ms | CPU fence等待 us | 总比较路径 us(含变化时保存历史) |
+|---|---:|---:|---:|
+| 1080p重复 | 0.0091 | 52.3 | 113.6 |
+| 1080p变化 | 0.0091 | 49.0 | 195.9 |
+| 4K重复 | 0.0279 | 75.0 | 166.6 |
+| 4K变化 | 0.0304 | 78.0 | 306.7 |
+
+变化组1080p总成本三轮195.5–246.8us、4K297.9–348.1us,超过方案无重复时≤0.1ms门槛。此测试每次空闲queue等待,不能冒充整合到实际播放后的CPU关键路径收益;全卡频率快照附result.json。还存在完整EnhanceGraph输出不等价反例,见PERF_1A_DUPLICATE_REUSE,因此不将比较器加入默认产品。
+
+失败证据保留:v1运行包D3DCompile不支持cs_5_1,修订为不需要5.1特性的cs_5_0;v2同进程测试窗口被产品ScreenCaptureSource正常拒绝(防自身采集),改为拥有的子进程,未放宽产品限制。v2三轮纯比较有效,但v2捕获失败;只用v3完整结果。
+
+E3屏幕部分完成;KUHAIMI27P实卡虽可枚举,主机信号、30/40/60帧模式尚未经用户确认,未采卡、不用合成素材代替。1a拒绝不依赖这项外部缺口;其余优化继续。
diff --git a/docs/PERF_EXECUTION_NR_2026-10-04.md b/docs/PERF_EXECUTION_NR_2026-10-04.md
index 6d2fc40a..a5cb8a79 100644
--- a/docs/PERF_EXECUTION_NR_2026-10-04.md
+++ b/docs/PERF_EXECUTION_NR_2026-10-04.md
@@ -27,7 +27,7 @@
| A0 | 当前版本基线及矩阵驱动 | in-progress | A完整包封存;M1五组各三轮15/15通过,PERF_BASELINE_NR;其余素材/切换基线在各节点前补齐 |
| E1 | Feature18动态输入尺寸 | completed-conditional | 两运行库8组合API/区域/恢复正常,但缩小后与独立小实例不同;PERF_E1_DYNAMIC_SIZE,3b优先实际尺寸实例 |
| E2 | 并行Evaluate/CreateFeature | completed-conditional | 单Core/adapter,三次240s累计12min及150次创建安全通过;间隔110–116ms,不能据此宣称2b无缝 |
-| E3 | 真实来源精确重复比例 | pending | 屏幕/实卡可用性与合成节奏分开 |
+| E3 | 真实来源精确重复比例 | completed-screen-awaiting-card | 真实WGC三阶段各60秒通过,静止99.932%/移动内容0.540%/窗口位置99.937%;PERF_E3_DUPLICATE_SOURCE;实卡待来源确认 |
| 1a | 精确重复帧整链复用 | rejected-unchanged-output | 自然同像素300帧×五组×三轮,A-A噪声0;NR/SR复用299帧不同;PERF_1A_DUPLICATE_REUSE;无生产改动 |
| 5a | 黑边检测与有效区域处理 | pending | 防暗场误裁,先测准确性与重建收益 |
| 3a | 进程GPU调度优先级 | pending | 只改本进程,有竞争负载的实际A/B |
@@ -42,7 +42,7 @@
| 5b | 文件/导出跨帧并行 | pending | 保留源帧/PTS/flow依赖,不扩大实时延迟 |
| 4a | 多NR整链低分辨率调度 | pending | 保留每层残差参数;先测同尺寸与一致性 |
| 4b | 先粗后细组合 | pending | 核对现有逐层尺寸;不新增强制预设 |
-| 5c | 暂停不重跑/残差重合成 | pending | 计数器/真实GPU占用与暂停编辑 |
+| 5c | 暂停不重跑/残差重合成 | in-progress | 暂停不Evaluate已有;显式reset单NR300帧一致、SR组合不一致;只限单层NR候选,A/B/B-off及真实UI待测 |
| UI | 性能设置及状态 | pending | 只暴露保留实现,统一持久化/能力/翻译 |
| R0 | 全产品回归与最终候选 | pending | 合同/Xbox/Qt/字幕/导出/兼容及源码存档 |
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 4ba4542f..a1961af6 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -8174,3 +8174,9 @@ release. 5090 live acceptance, 15-second hitch and user flicker remain unresolve
- `nr-rebuild-series.py B2a B2a-rebuild-v2`、`nr-rebuild-report.py A-rebuild-v1 B2a-rebuild-v2 B2a-rebuild-v2-off` exit0;B与同EXE关闭组各12/12,240张完整输出分别对A零差异。四组暖创建1569.510→379.349、1409.580→405.504、1456.600→515.900、1348.730→377.124ms;原始日志 `E:/项目/Veyra/logs/perf-nr-20261004/B2a-rebuild-v2*`。
- v3真实Qt界面六组20次请求通过;层数多个属性导致26次实际重建,FG/运行库仍完整重开。v2倍率属性自动启用FG,额外2X实验保留,纠正v3后才计非FG路径。
- SDK核心容量/活跃借用/初始化失败注入exit0,64个真实参数最终清零;不是实测TDR。SR内部缓存关闭后本进程DXGI使用量141803520 bytes。所有核心复用收益仅暖重建,不冒充持续FPS或首启优化。2a保留,R0导出/全产品回归仍待做;详情PERF_2A_CORE_REUSE。
+# 2026-10-04 NR性能优化:E3真实屏幕与5c前置/候选
+
+- E3 `nr-duplicate.py B2a E3-own-window-v3` 4/4 exit0;三轮比较/真实WGC三阶段各60秒,静止1475/1476重复、移动内容8/1481、移动自有窗口位置1588/1589,无捕获丢帧/debug错误/设备移除。原始数据 `E:/项目/Veyra/logs/perf-nr-20261004/E3-own-window-v3-*`。
+- 精确GPU比较仅测试:1080p变化CPU总路径三轮中位195.9us、4K306.7us,超过0.1ms门槛;shader自身9.1/30.4us。v1编译器cs5.1不支持、v2同进程窗口被产品保护拒绝,失败证据保留;cs5.0及拥有的子进程修订通过,未放宽产品限制。实卡信号未确认、未采卡。
+- 5c `nr-static.py B2a pause-reset-M1-v1 nr-reset srnr-reset` 六组通过:NR reset后300帧三轮0差异,SR组合各262差异。只对单NR暂停刷新制作窄范围候选,普通暂停不Evaluate已有。
+- 暂停编辑基线EXE SHA066ac43c…86045在 `tests/perf-nr-20261004/A5c-paused-v1-app/` 独立封存。`nr-paused.py B2a A5c-paused-v1` 四组各三轮12/12,通过300次编辑及第150次模型失效检查;A NR数300/300/300/600(每轮),无debug/设备错误。`build-paused-baseline-v1` 缺AVFrame/iostream头失败,补头后 `build-paused-duplicates-v3` 成功。5c产品候选尚待构建和对照,不记录未取得收益。
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 92b25fec..9fb1169c 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -446,7 +446,7 @@ public:
// `hardwareSurface` carries the decoded texture for paths whose surface
// does not travel inside the AVFrame (D3D11VA). It must be provided exactly
// when frame->format == AV_PIX_FMT_D3D11 and is unused otherwise.
- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {}, unsigned previewMultiplier = 0);
+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {}, unsigned previewMultiplier = 0, bool pausedResidualRefresh = false);
bool nextFrameSlotAvailable()const {
const unsigned slot=unsigned(realFrameIndex_%2);
if(presentationFences_[slot]&&presentationFences_[slot]->GetCompletedValue()<presentationValues_[slot])return false;
@@ -478,6 +478,7 @@ public:
struct Metrics {
uint64_t nrEvaluateCount = 0;
+ uint64_t pausedNrResidualReuses = 0;
uint64_t srEvaluateCount = 0;
uint64_t nvofExecuteCount = 0;
uint64_t amdOfExecuteCount = 0;
@@ -779,6 +780,14 @@ private:
// Per-run state.
uint64_t realFrameIndex_ = 0;
+ // Only a successful explicit paused/still-frame reset may seed this.
+ // Ordinary playback, source changes, failures and non-residual edits
+ // invalidate it. No cross-frame/duplicate-source reuse is performed.
+ bool pausedNrCacheValid_=false,pausedNrResidualOnly_=false;
+ const AVFrame* pausedNrFrame_=nullptr;
+ uint64_t pausedNrSourceId_=0;
+ double pausedNrPts_=0;
+ std::optional<engine::EnhancementSettings> lastAppliedSettings_,pausedNrSettings_;
uint64_t epoch_ = 0;
std::weak_ptr<FrameLease> realLeases_[2],generatedLeases_[kGeneratedPoolSlots];
uint32_t nextListSlot_ = 0;
diff --git a/scripts/perf/nr-duplicate.py b/scripts/perf/nr-duplicate.py
new file mode 100644
index 00000000..c1007c3e
--- /dev/null
+++ b/scripts/perf/nr-duplicate.py
@@ -0,0 +1,39 @@
+"""Isolated exact GPU comparison and actual WGC of an owned pattern window."""
+from pathlib import Path
+import importlib.util
+import json
+import os
+import shutil
+import subprocess
+import sys
+import time
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'
+spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py')
+matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)
+variant,label=sys.argv[1:3]
+app=BASE/'tests'/TASK/(label+'-app');assert not app.exists()
+shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable',app,copy_function=matrix.copy_dependency)
+exe=app/'veyra_duplicate_gpu_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
+shader=app/'DuplicateFrameCS.hlsl';shutil.copy2(ROOT/'tests/perf/DuplicateFrameCS.hlsl',shader)
+results=[]
+for mode,repeat in [('compare',1),('compare',2),('compare',3),('capture',1)]:
+ name=f'{label}-{mode}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
+ for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
+ env=os.environ.copy()
+ for key in tuple(env):
+ if key.upper().startswith('VEYRA_'):env.pop(key)
+ env.update(TEMP=str(tmp),TMP=str(tmp))
+ command=[str(exe),str(shader),str(out),mode];before=matrix.gpu_query();start=time.monotonic()
+ print('START',name,flush=True)
+ with (out/'console.log').open('xb') as log:
+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=280).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace')
+ result={'variant':variant,'mode':mode,'repeat':repeat,'exeSha256':matrix.digest(exe),'shaderSha256':matrix.digest(shader),
+ 'beforeGpu':before,'afterGpu':matrix.gpu_query(),'command':command,'exitCode':rc,'wallSeconds':time.monotonic()-start,
+ 'passed':rc==0 and 'RESULT failures=0 debugErrors=0 deviceRemoved=0' in text,
+ 'capturePrivacy':'Only the owned GDI pattern window; never a user desktop/application or capture card'}
+ results.append(result);(out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
+ print('RESULT',name,rc,result['passed'],flush=True)
+ if not result['passed']:print(text[-6000:],flush=True);raise SystemExit(1)
+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
diff --git a/scripts/perf/nr-paused.py b/scripts/perf/nr-paused.py
new file mode 100644
index 00000000..d56db567
--- /dev/null
+++ b/scripts/perf/nr-paused.py
@@ -0,0 +1,46 @@
+"""Actual graph paused residual edits; bounded processes and full-frame hashes."""
+from pathlib import Path
+import csv
+import importlib.util
+import json
+import os
+import shutil
+import subprocess
+import sys
+import time
+ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'
+spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py');matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)
+variant,label=sys.argv[1:3];modes=sys.argv[3:] or ['nr','srnr','temporal','layers']
+app=BASE/'tests'/TASK/(label+'-app');exe=app/'veyra_nr_paused_residual_experiment.exe'
+if not app.exists():
+ shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-win64-portable',app,copy_function=matrix.copy_dependency)
+ shutil.copy2(BASE/'build'/TASK/variant.removesuffix('-off')/exe.name,exe)
+ (app/'paused-test-stage.json').write_text(json.dumps({'exeSha256':matrix.digest(exe),'sourceCommit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD']).decode().strip()}),encoding='utf-8')
+else:
+ assert matrix.digest(exe)==json.loads((app/'paused-test-stage.json').read_text())['exeSha256']
+if modes==['--stage-only']:
+ print('SEALED',app,matrix.digest(exe));raise SystemExit(0)
+results=[]
+for mode in modes:
+ assert mode in ('nr','srnr','temporal','layers')
+ for repeat in range(1,4):
+ name=f'{label}-{mode}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
+ for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
+ env=os.environ.copy()
+ for key in tuple(env):
+ if key.upper().startswith('VEYRA_'):env.pop(key)
+ env.update(TEMP=str(tmp),TMP=str(tmp))
+ if variant.endswith('-off'):env['VEYRA_TEST_DISABLE_PAUSED_NR_RESIDUAL_REUSE']='1'
+ command=[str(exe),str(matrix.SOURCES['M1']),str(out),mode];before=matrix.gpu_query();start=time.monotonic();print('START',name,flush=True)
+ with (out/'console.log').open('xb') as log:
+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=log,stderr=subprocess.STDOUT,timeout=280).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace');rows=list(csv.DictReader((out/'edits.csv').open())) if (out/'edits.csv').exists() else []
+ result={'variant':variant,'label':label,'mode':mode,'repeat':repeat,'exeSha256':matrix.digest(exe),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),
+ 'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'beforeGpu':before,'afterGpu':matrix.gpu_query(),'command':command,
+ 'exitCode':rc,'wallSeconds':time.monotonic()-start,'frameCount':len(rows),'nrEvaluations':sum(int(r['nrDelta']) for r in rows),'srEvaluations':sum(int(r['srDelta']) for r in rows),
+ 'passed':rc==0 and len(rows)==300 and 'RESULT safetyPass=1' in text and 'debugErrors=0 deviceRemoved=0' in text,
+ 'sha256Sequence':[r['sha256'] for r in rows],'measurement':'Diagnostic readback excluded from process timing; explicit reset on each paused edit'}
+ results.append(result);(out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');print('RESULT',name,rc,result['passed'],result['nrEvaluations'],flush=True)
+ if not result['passed']:print(text[-5000:],flush=True);raise SystemExit(1)
+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
diff --git a/scripts/perf/nr-static.py b/scripts/perf/nr-static.py
index 2bc852b4..203bd647 100644
--- a/scripts/perf/nr-static.py
+++ b/scripts/perf/nr-static.py
@@ -19,7 +19,7 @@ shutil.copytree(BASE/'test-packages'/TASK/'Veyra-2.0.3-perf-baseline-A-NVIDIA-wi
exe=app/'veyra_nr_static_input_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
results=[]
for mode in modes:
- assert mode in ('nr','nr-temporal','srnr','sr','off')
+ assert mode in ('nr','nr-temporal','srnr','sr','off','nr-reset','srnr-reset')
for repeat in range(1,4):
name=f'{label}-{mode}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 23fc468a..c4ee6854 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1256,7 +1256,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(cachedFrame){
pipeline::EnhanceGraph::FrameOutputs refreshed;
const double refreshPtsMs=cachedPacket.pts.toDouble()*1000.0;
- if(graph.process(cachedFrame,refreshPtsMs,true,refreshed,cachedPacket.sequence,&cachedPacket.colorInfo,&cachedPacket.hardwareSurface,false)){
+ if(graph.process(cachedFrame,refreshPtsMs,true,refreshed,cachedPacket.sequence,&cachedPacket.colorInfo,&cachedPacket.hardwareSurface,false,{},0,true)){
out=refreshed;
hasOutput=true;
{std::lock_guard lock(mutex_);++snapshot_.pausedFrameRefreshes;}
@@ -1679,7 +1679,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!presenter.beginSourceProcessing()){status(L"XeSS processing timing failed",true);break;}
bool processed=false;{
processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();
- processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg,previewFgMultiplier);
+ processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg,previewFgMultiplier,(paused_||isImage)&&transaction);
processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;
}
loopTrace.mark("graphSubmit");
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 59f9fc12..754eeea0 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1789,8 +1789,21 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
// process: the per-frame chain (verbatim from the probe lambda).
// ---------------------------------------------------------------------------
-bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, const HardwareSurfaceInput* hardwareSurface, bool retainReferences, const FgAdmission& admitFg, unsigned previewMultiplier)
+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, const HardwareSurfaceInput* hardwareSurface, bool retainReferences, const FgAdmission& admitFg, unsigned previewMultiplier, bool pausedResidualRefresh)
{
+ // Whole-chain duplicate reuse failed the unchanged-output experiment.
+ // This narrower path only handles repeated edits of the SAME paused
+ // frame, after one complete reset evaluation under this configuration.
+ const bool pausedEligible=pausedResidualRefresh&&reset&&context_.adapter().isNvidia&&nrEnabled_&&nrInstances_.size()==1&&
+ !nrInstances_[0]->temporalEnabled&&!nrInstances_[0]->stabilised&&!lmxxfNr_&&
+ !srEnabled_&&!fgEnabled_&&!desc_.videoHdr.enabled&&!desc_.hdrWorking()&&
+ !colorGradeActive()&&!tailColorActiveCount_&&!preNrColorActiveCount_&&
+ !preSrColorActiveCount_&&!interNrColorActiveCount_&&desc_.nrHoldStrength==0&&
+ (!hardwareSurface||!hardwareSurface->present())&&
+ !GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_PAUSED_NR_RESIDUAL_REUSE",nullptr,0);
+ const bool reusePausedNr=pausedEligible&&pausedNrCacheValid_&&pausedNrResidualOnly_&&
+ frame==pausedNrFrame_&&sourceFrameId==pausedNrSourceId_&&ptsMs==pausedNrPts_;
+ pausedNrCacheValid_=false; // Every failure path remains an invalid cache.
diagnostics::CpuStallTrace cpuTrace("graph-cpu-stall",sourceFrameId,30.0);
failedBackend_=engine::FailedBackend::Infrastructure;
out = FrameOutputs{};
@@ -2418,7 +2431,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// layer costs two lists: one for encode+decode prep, one for the evaluate
// (the original single-layer code did exactly the same, hence the identical
// output). The ring is drained by submission, never by a CPU wait.
- if (nrEnabled_ && nrCreated()) {
+ if(reusePausedNr){
+ nrInstances_[0]->inputRevision=1;
+ ++metrics_.pausedNrResidualReuses;
+ log::info("paused-nr-cache",std::format("event=reuse source={} revision={} count={}",sourceFrameId,desc_.settingsRevision,metrics_.pausedNrResidualReuses));
+ }
+ if (nrEnabled_ && nrCreated()&&!reusePausedNr) {
for (size_t layerIndex = 0; layerIndex < nrInstances_.size(); ++layerIndex) {
const bool preSrProtection=preSrProtectionRgba_&&layerIndex==desc_.nrBeforeSrLayerCount();
const bool interNrProtection=interNrProtectionRgba_&&layerIndex==desc_.interNrProtectionTarget();
@@ -2873,6 +2891,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
out.videoSlot = parity;
BatchFrame real;real.identity=out.batch.identity;real.pts100ns=out.batch.b100ns;real.lease=std::make_shared<FrameLease>();real.lease->texture=videoFrame_[parity];real.lease->sourceReference=sourceReferences_[parity];real.lease->baseReference=baseReferences_[parity];real.lease->slot=parity;real.lease->readyFence=out.videoFenceValue;real.lease->readyFenceObject=out.videoFenceObject;real.lease->referencesValid=retainReferences;realLeases_[parity]=real.lease;out.batch.append(std::move(real));
if(veyra::log::verboseFrameLogs())veyra::log::info("frame-batch",std::format("batch={} epoch={} revision={} source={} a={} b={} count={} realSlot={} realFence={} genSlot={} genFence={}",out.batch.batchId,epoch_,out.batch.identity.settingsRevision,out.batch.identity.sourceFrameId,out.batch.a100ns,out.batch.b100ns,out.batch.count,parity,out.videoFenceValue,out.genSlot,out.genFenceValue));
+ if(pausedEligible&&lastAppliedSettings_){
+ pausedNrCacheValid_=true;pausedNrFrame_=frame;pausedNrSourceId_=sourceFrameId;pausedNrPts_=ptsMs;
+ pausedNrSettings_=lastAppliedSettings_;
+ }
return true;
}
@@ -2975,6 +2997,15 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
// Switching the referenced .cube re-stages a descriptor, which needs the
// queue drained: treat it as a rebuild (parameters stay live).
if(s.color.lutNameString()!=desc_.color.lutNameString()||s.color.lutInputSpace!=desc_.color.lutInputSpace)return false;
+ pausedNrResidualOnly_=false;
+ if(pausedNrSettings_){
+ auto residualEdit=*pausedNrSettings_;residualEdit.revision=s.revision;
+ residualEdit.residual=s.residual;
+ for(unsigned i=0;i<residualEdit.nrLayerCount;++i)residualEdit.nrLayers[i].residual=s.nrLayers[i].residual;
+ pausedNrResidualOnly_=residualEdit==s;
+ }
+ if(!pausedNrResidualOnly_)pausedNrCacheValid_=false;
+ lastAppliedSettings_=s;
desc_.videoHdr=s.videoHdr;
if(!(s.color==desc_.color)){
desc_.color=s.color;
@@ -3079,6 +3110,8 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
// ---------------------------------------------------------------------------
void EnhanceGraph::shutdown()
{
+ pausedNrCacheValid_=pausedNrResidualOnly_=false;pausedNrFrame_=nullptr;
+ lastAppliedSettings_.reset();pausedNrSettings_.reset();
if (!initialized_ && !coreHost_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
for(unsigned i=0;i<2;++i)if(presentationFences_[i]){
const HRESULT hr=context_.directQueue()->Wait(presentationFences_[i].Get(),presentationValues_[i]);
diff --git a/tests/perf/DuplicateGpuExperiment.cpp b/tests/perf/DuplicateGpuExperiment.cpp
new file mode 100644
index 00000000..50417341
--- /dev/null
+++ b/tests/perf/DuplicateGpuExperiment.cpp
@@ -0,0 +1,127 @@
+#include "DuplicateGpuFixture.h"
+#include "veyra/source/ScreenCaptureSource.h"
+#include "veyra/Log.h"
+#include <d3d12sdklayers.h>
+#include <fstream>
+#include <thread>
+#include <algorithm>
+
+// Isolated measurement, never a product source-frame skip. WGC captures only
+// this test's own pattern window; no user desktop/application pixels are read.
+namespace {
+using namespace veyra;
+unsigned failures=0;
+void check(bool ok,const char* name){std::cout<<"CHECK "<<name<<" pass="<<ok<<std::endl;failures+=!ok;}
+pipeline::ComPtr<ID3D12Resource> upload(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,
+ unsigned w,unsigned h,bool half,unsigned mutation){
+ const unsigned bytes=half?8:4;
+ const auto fmt=half?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM;
+ auto texture=pipeline::makeTexture(ctx.device(),w,h,fmt,false);if(!texture)return {};
+ auto desc=texture->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};UINT64 total=0;
+ ctx.device()->GetCopyableFootprints(&desc,0,1,0,&footprint,nullptr,nullptr,&total);
+ auto staging=pipeline::makeUploadBuffer(ctx.device(),total);if(!staging)return {};
+ void* p=nullptr;D3D12_RANGE empty{};if(FAILED(staging->Map(0,&empty,&p)))return {};
+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){auto* dst=static_cast<unsigned char*>(p)+footprint.Offset+y*footprint.Footprint.RowPitch+x*bytes;
+ if(half){const uint16_t v[]={0x3800,0x3400,0x3000,0x3c00};std::memcpy(dst,v,8);}
+ else {const unsigned char v[]={123,37,71,255};std::memcpy(dst,v,4);}
+ // All four corners and odd-size edges are deliberately exercisable.
+ if(mutation&&x==w-1&&y==h-1){if(half){uint16_t v;const unsigned off=mutation==2?6:0;std::memcpy(&v,dst+off,2);++v;std::memcpy(dst+off,&v,2);}else ++dst[mutation==2?3:0];}
+ }
+ staging->Unmap(0,nullptr);Status status;uint32_t slot;auto* list=ring.acquireNext(slot,status);if(!list)return {};
+ pipeline::StateTracker states;states.transition(list,texture.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION from{};from.pResource=staging.Get();from.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;from.PlacedFootprint=footprint;
+ D3D12_TEXTURE_COPY_LOCATION to{};to.pResource=texture.Get();to.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ list->CopyTextureRegion(&to,0,0,0,&from,nullptr);states.transition(list,texture.Get(),D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return {};return texture;
+}
+bool animated=false;
+LRESULT CALLBACK pattern(HWND window,UINT message,WPARAM wp,LPARAM lp){
+ if(message==WM_APP+1){animated=wp!=0;InvalidateRect(window,nullptr,FALSE);return 0;}
+ if(message==WM_CLOSE){DestroyWindow(window);return 0;}
+ if(message==WM_DESTROY){PostQuitMessage(0);return 0;}
+ if(message==WM_TIMER){InvalidateRect(window,nullptr,FALSE);return 0;}
+ if(message==WM_PAINT){PAINTSTRUCT ps;auto dc=BeginPaint(window,&ps);RECT rect;GetClientRect(window,&rect);
+ const COLORREF colors[]={RGB(220,30,45),RGB(20,210,70),RGB(25,60,225)};
+ for(unsigned i=0;i<3;++i){RECT band{LONG(rect.right*i/3),0,LONG(rect.right*(i+1)/3),rect.bottom};auto brush=CreateSolidBrush(colors[i]);FillRect(dc,&band,brush);DeleteObject(brush);}
+ if(animated){RECT box{LONG(GetTickCount64()/8%std::max(1L,rect.right-40)),20,0,60};box.right=box.left+40;FillRect(dc,&box,HBRUSH(GetStockObject(WHITE_BRUSH)));}
+ EndPaint(window,&ps);return 0;
+ }
+ return DefWindowProcW(window,message,wp,lp);
+}
+void pump(){MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}}
+bool capture(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,dupperf::ExactChecker& checker,const std::filesystem::path& out){
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ wchar_t exe[32768]{};GetModuleFileNameW(nullptr,exe,32768);std::wstring command=L"\""+std::wstring(exe)+L"\" --target";
+ STARTUPINFOW startup{sizeof(startup)};PROCESS_INFORMATION child{};if(!CreateProcessW(exe,command.data(),nullptr,nullptr,FALSE,0,nullptr,nullptr,&startup,&child))return false;
+ struct OwnedChild {PROCESS_INFORMATION process;HWND window=nullptr;~OwnedChild(){if(window)PostMessageW(window,WM_CLOSE,0,0);if(WaitForSingleObject(process.hProcess,3000)==WAIT_TIMEOUT)TerminateProcess(process.hProcess,1);CloseHandle(process.hThread);CloseHandle(process.hProcess);}} owned{child};
+ struct Find {DWORD pid;HWND window=nullptr;} find{child.dwProcessId};
+ for(unsigned tries=0;tries<100&&!find.window;++tries){EnumWindows([](HWND w,LPARAM arg)->BOOL{auto& f=*reinterpret_cast<Find*>(arg);DWORD pid=0;GetWindowThreadProcessId(w,&pid);if(pid==f.pid&&IsWindowVisible(w)){f.window=w;return FALSE;}return TRUE;},LPARAM(&find));Sleep(20);}
+ const auto window=find.window;owned.window=window;if(!window)return false;
+ source::ScreenCaptureOptions options;options.target=uint64_t(window);options.fps=60;options.cursor=false;
+ source::SourceOpenDesc desc;desc.path=options.uri();desc.d3d12Device=ctx.device();desc.d3d12Queue=ctx.directQueue();
+ source::ScreenCaptureSource source;bool pass=source.open(desc);if(!pass)std::wcerr<<source.status()<<std::endl;
+ for(unsigned phase=0;phase<3&&pass;++phase){
+ PostMessageW(window,WM_APP+1,phase==1,0);checker.invalidate();const auto before=source.metrics();unsigned frames=0,duplicates=0,waiting=0;int64_t lastPts=-1;
+ std::ofstream csv(out/(L"capture-"+std::to_wstring(phase)+L".csv"));csv<<"sequence,pts100ns,first,duplicate,gpuCompareMs,cpuFenceWaitUs,totalCpuUs\n";
+ const auto started=GetTickCount64();uint64_t moved=0;
+ while(GetTickCount64()-started<60000&&pass){
+ pump();const auto elapsed=GetTickCount64()-started;
+ if(phase==2&&elapsed/100!=moved){moved=elapsed/100;SetWindowPos(window,nullptr,40+int(moved%15)*4,40+int(moved%9)*3,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);}
+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto read=source.read(packet,&frame);
+ if(read==source::SourceReadStatus::Waiting){++waiting;Sleep(1);continue;}
+ if(read!=source::SourceReadStatus::Frame){std::wcerr<<source.status()<<std::endl;pass=false;break;}
+ if(!packet.hardwareSurface.present()||packet.pts.to100ns()<=lastPts){pass=false;break;}lastPts=packet.pts.to100ns();
+ if(pipeline::breaksHistory(packet.flags))checker.invalidate();
+ if(packet.hardwareSurface.waitFence&&FAILED(ctx.directQueue()->Wait(packet.hardwareSurface.waitFence,packet.hardwareSurface.waitValue))){pass=false;break;}
+ dupperf::ExactChecker::Result result;
+ pass=checker.check(packet.hardwareSurface.texture,D3D12_RESOURCE_STATE_COMMON,packet.colorInfo.isHdrPath(),result);if(!pass)break;
+ ++frames;duplicates+=result.duplicate;csv<<packet.sequence<<','<<lastPts<<','<<result.first<<','<<result.duplicate<<','<<result.gpuCompareMs<<','<<result.cpuFenceWaitUs<<','<<result.totalCpuUs<<'\n';
+ }
+ const auto metrics=source.metrics();std::cout<<"CAPTURE phase="<<phase<<" durationMs="<<GetTickCount64()-started<<" frames="<<frames<<" duplicates="<<duplicates<<" waitingPolls="<<waiting<<" received="<<metrics.received-before.received<<" dropped="<<metrics.dropped-before.dropped<<" pass="<<pass<<std::endl;
+ pass=pass&&frames>0;csv.flush();
+ }
+ ring.drainQueue();source.close();CoUninitialize();return pass;
+}
+}
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;
+ if(argc==2&&std::wstring(argv[1])==L"--target"){
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ WNDCLASSW wc{};wc.lpfnWndProc=pattern;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraDupPerfOwnedPattern";if(!RegisterClassW(&wc))return 2;
+ auto window=CreateWindowExW(WS_EX_NOACTIVATE,wc.lpszClassName,L"Veyra own-pattern duplicate measurement",WS_OVERLAPPEDWINDOW,40,40,660,420,nullptr,nullptr,wc.hInstance,nullptr);
+ if(!window)return 2;ShowWindow(window,SW_SHOWNOACTIVATE);SetTimer(window,1,16,nullptr);const auto started=GetTickCount64();
+ while(GetTickCount64()-started<240000&&IsWindow(window)){pump();Sleep(1);}if(IsWindow(window))DestroyWindow(window);return 0;
+ }
+ if(argc!=4)return 2;const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);
+ Logger::instance().openFile((out/L"engine.log").wstring());gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
+ gfx::DeviceContextDesc dd;dd.enableDebugLayer=true;if(!ctx.initialize(dd,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ dupperf::ExactChecker checker(ctx,ring);if(!checker.initialize(argv[1]))return 2;
+ if(std::wstring(argv[3])==L"capture")check(capture(ctx,ring,checker,out),"actual WGC own-window 3x60 seconds");
+ else {
+ for(bool half:{false,true}){
+ auto a=upload(ctx,ring,19,17,half,0),rgb=upload(ctx,ring,19,17,half,1),alpha=upload(ctx,ring,19,17,half,2);
+ dupperf::ExactChecker::Result r;checker.invalidate();check(checker.check(a.Get(),D3D12_RESOURCE_STATE_COMMON,half,r)&&r.first&&!r.duplicate,"first accepted");
+ check(checker.check(a.Get(),D3D12_RESOURCE_STATE_COMMON,half,r)&&!r.first&&r.duplicate,"exact same pixels");
+ check(checker.check(alpha.Get(),D3D12_RESOURCE_STATE_COMMON,half,r)&&r.duplicate!=half,"SDR RGB versus FP16 RGBA alpha semantics");
+ check(checker.check(rgb.Get(),D3D12_RESOURCE_STATE_COMMON,half,r)&&!r.duplicate,"last odd-size pixel single LSB");
+ check(checker.check(rgb.Get(),D3D12_RESOURCE_STATE_COMMON,half,r)&&r.duplicate,"accepted source history");
+ checker.invalidate();check(checker.check(rgb.Get(),D3D12_RESOURCE_STATE_COMMON,half,r)&&r.first,"epoch invalidation");
+ }
+ std::ofstream csv(out/L"compare.csv");csv<<"width,height,changing,frame,gpuCompareMs,cpuFenceWaitUs,totalCpuUs,historyCopyCpuUs,duplicate\n";
+ for(unsigned w:{1920u,3840u}){
+ const unsigned h=w*9/16;auto a=upload(ctx,ring,w,h,false,0),b=upload(ctx,ring,w,h,false,1);
+ for(bool changing:{false,true}){checker.invalidate();for(unsigned i=0;i<300;++i){
+ dupperf::ExactChecker::Result r;const bool ok=checker.check(changing&&i%2?b.Get():a.Get(),D3D12_RESOURCE_STATE_COMMON,false,r);
+ if(!ok||(i>0&&r.duplicate==changing)){check(false,"300-frame compare sequence");break;}
+ csv<<w<<','<<h<<','<<changing<<','<<i<<','<<r.gpuCompareMs<<','<<r.cpuFenceWaitUs<<','<<r.totalCpuUs<<','<<r.historyCopyCpuUs<<','<<r.duplicate<<'\n';
+ }}
+ std::cout<<"TIMING width="<<w<<" pass="<<(failures==0)<<std::endl;
+ }
+ }
+ ring.drainQueue();Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;
+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;
+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T size=0;debug->GetMessage(i,nullptr,&size);std::vector<unsigned char> data(size);auto* message=reinterpret_cast<D3D12_MESSAGE*>(data.data());
+ if(FAILED(debug->GetMessage(i,message,&size)))return 2;if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<std::endl;}}
+ const auto removed=ctx.device()->GetDeviceRemovedReason();std::cout<<"RESULT failures="<<failures<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ return failures==0&&errors==0&&SUCCEEDED(removed)?0:1;
+}
diff --git a/tests/perf/DuplicateGpuFixture.h b/tests/perf/DuplicateGpuFixture.h
index 2a36dda3..6cb3ce6b 100644
--- a/tests/perf/DuplicateGpuFixture.h
+++ b/tests/perf/DuplicateGpuFixture.h
@@ -29,7 +29,7 @@ public:
void invalidate(){valid_=false;}
bool initialize(const std::filesystem::path& shader){
pipeline::ComPtr<ID3DBlob> code,errors;
- const auto hr=D3DCompileFromFile(shader.c_str(),nullptr,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","cs_5_1",D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&code,&errors);
+ const auto hr=D3DCompileFromFile(shader.c_str(),nullptr,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","cs_5_0",D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&code,&errors);
if(FAILED(hr)){std::cerr<<"compile HRESULT="<<unsigned(hr)<<' '<<(errors?static_cast<const char*>(errors->GetBufferPointer()):"")<<std::endl;return false;}
std::vector<uint8_t> bytes(static_cast<const uint8_t*>(code->GetBufferPointer()),static_cast<const uint8_t*>(code->GetBufferPointer())+code->GetBufferSize());
if(!pass_.create(ctx_.device(),bytes,3,2,1,1)||!stager_.initialize(ctx_.device(),2))return false;
diff --git a/tests/perf/NrPausedResidualExperiment.cpp b/tests/perf/NrPausedResidualExperiment.cpp
new file mode 100644
index 00000000..c621c5cf
--- /dev/null
+++ b/tests/perf/NrPausedResidualExperiment.cpp
@@ -0,0 +1,64 @@
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/engine/GraphDescription.h"
+#include "veyra/engine/EffectChain.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/Log.h"
+#include <bcrypt.h>
+#include <d3d12sdklayers.h>
+#include <fstream>
+#include <iostream>
+#include <array>
+#include <chrono>
+#include <algorithm>
+extern "C" {
+#include <libavutil/frame.h>
+}
+namespace {
+std::string sha(const std::vector<uint8_t>& pixels){BCRYPT_ALG_HANDLE alg=nullptr;BCRYPT_HASH_HANDLE hash=nullptr;std::array<unsigned char,32> digest{};
+ if(BCryptOpenAlgorithmProvider(&alg,BCRYPT_SHA256_ALGORITHM,nullptr,0)<0)return {};
+ const bool ok=BCryptCreateHash(alg,&hash,nullptr,0,nullptr,0,0)>=0&&BCryptHashData(hash,const_cast<PUCHAR>(pixels.data()),ULONG(pixels.size()),0)>=0&&BCryptFinishHash(hash,digest.data(),32,0)>=0;
+ if(hash)BCryptDestroyHash(hash);BCryptCloseAlgorithmProvider(alg,0);if(!ok)return {};std::string s;const char* hex="0123456789abcdef";for(auto c:digest){s+=hex[c>>4];s+=hex[c&15];}return s;}
+}
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;if(argc!=4)return 2;const std::wstring mode=argv[3];const bool sr=mode==L"srnr",temporal=mode==L"temporal",multiple=mode==L"layers";
+ if(mode!=L"nr"&&!sr&&!temporal&&!multiple)return 2;
+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);Logger::instance().openFile((out/L"engine.log").wstring());
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc dd;dd.enableDebugLayer=true;
+ if(!ctx.initialize(dd,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status))return 2;
+ source::MediaFileSource media;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;if(!media.open(open))return 2;
+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;if(media.read(packet,&frame)!=source::SourceReadStatus::Frame)return 2;
+ engine::EffectChain chain;chain.nodeCount=multiple?2:1;
+ for(unsigned i=0;i<chain.nodeCount;++i){chain.nodes[i].type=engine::EffectType::NrEnhance;chain.nodes[i].enabled=true;chain.nodes[i].nr.temporal=temporal;}
+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.sr=sr;settings.srTarget=pipeline::SrTarget::Uhd4K;settings.videoSrQuality=0;settings.multiplier=1;
+ engine::StageRequest request;request.width=frame->width;request.height=frame->height;request.nr=true;request.sr=sr;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);desc.enableNvofStandalone=true;desc.enableFg=false;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ pipeline::EnhanceGraph graph(ctx,ring);if(!graph.initialize(desc)||!graph.createViews())return 2;
+ std::ofstream csv(out/L"edits.csv");csv<<"edit,modelChanged,total,processCpuWithWaitMs,nrDelta,srDelta,sha256\n";bool pass=true;
+ for(unsigned i=0;i<300&&pass;++i){
+ settings.nrLayers[0].residual.total=settings.residual.total=float(i%10)*.2f;
+ // A model edit in the middle must invalidate the resident NR result.
+ if(i==150)settings.nrLayers[0].model.intensity=settings.model.intensity=.7f;
+ pass=graph.applySettings(settings);if(!pass)break;const auto before=graph.metrics();pipeline::EnhanceGraph::FrameOutputs output;
+ const auto started=std::chrono::steady_clock::now();
+#ifdef VEYRA_HAS_PAUSED_NR_RESIDUAL_REUSE
+ pass=graph.process(frame,0,true,output,1,&packet.colorInfo,nullptr,false,{},0,true)&&ring.waitIdle();
+#else
+ pass=graph.process(frame,0,true,output,1,&packet.colorInfo,nullptr,false)&&ring.waitIdle();
+#endif
+ const auto ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-started).count();const auto after=graph.metrics();sink::RgbaImage image;
+ if(pass)pass=sink::readRgba8(ctx,ring,graph.videoFrameResource(output.videoSlot),image);if(!pass)break;
+ const auto hash=sha(image.pixels);if(hash.empty()){pass=false;break;}
+ csv<<i<<','<<(i==150)<<','<<settings.residual.total<<','<<ms<<','<<after.nrEvaluateCount-before.nrEvaluateCount<<','<<after.srEvaluateCount-before.srEvaluateCount<<','<<hash<<'\n';csv.flush();
+ if(i==0||i==1||i==10||i==149||i==150||i==151||i==299){std::ofstream f(out/(L"frame-"+std::to_wstring(i)+L".rgba"),std::ios::binary);f.write(reinterpret_cast<const char*>(image.pixels.data()),image.pixels.size());}
+ output={};if(i%60==0)std::cout<<"EDIT "<<i<<" ms="<<ms<<" nrDelta="<<after.nrEvaluateCount-before.nrEvaluateCount<<std::endl;
+ }
+ const auto metrics=graph.metrics();ring.drainQueue();graph.shutdown();media.close();Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;
+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;
+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T size=0;debug->GetMessage(i,nullptr,&size);std::vector<unsigned char> data(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());if(FAILED(debug->GetMessage(i,m,&size)))return 2;if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<m->pDescription<<std::endl;}}
+ const auto removed=ctx.device()->GetDeviceRemovedReason();std::cout<<"RESULT safetyPass="<<(pass&&errors==0&&SUCCEEDED(removed))<<" nrEvaluations="<<metrics.nrEvaluateCount<<" srEvaluations="<<metrics.srEvaluateCount<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;
+ return pass&&errors==0&&SUCCEEDED(removed)?0:1;
+}
diff --git a/tests/perf/NrStaticInputExperiment.cpp b/tests/perf/NrStaticInputExperiment.cpp
index 6dd249c7..73abca12 100644
--- a/tests/perf/NrStaticInputExperiment.cpp
+++ b/tests/perf/NrStaticInputExperiment.cpp
@@ -36,8 +36,9 @@ int wmain(int argc,wchar_t** argv){
using namespace veyra;
if(argc!=4)return 2;
const std::wstring mode=argv[3];
- if(mode!=L"nr"&&mode!=L"nr-temporal"&&mode!=L"srnr"&&mode!=L"sr"&&mode!=L"off")return 2;
- const bool nr=mode!=L"off"&&mode!=L"sr",sr=mode==L"srnr"||mode==L"sr";
+ if(mode!=L"nr"&&mode!=L"nr-temporal"&&mode!=L"srnr"&&mode!=L"sr"&&mode!=L"off"&&mode!=L"nr-reset"&&mode!=L"srnr-reset")return 2;
+ const bool nr=mode!=L"off"&&mode!=L"sr",sr=mode==L"srnr"||mode==L"sr"||mode==L"srnr-reset";
+ const bool resetEveryFrame=mode==L"nr-reset"||mode==L"srnr-reset";
const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);
Logger::instance().openFile((out/L"engine.log").wstring());
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
@@ -65,7 +66,7 @@ int wmain(int argc,wchar_t** argv){
const unsigned snapshots[]={0,1,2,4,8,16,32,64,127,255,299};
for(unsigned i=0;i<300&&pass;++i){
pipeline::EnhanceGraph::FrameOutputs output;const auto start=std::chrono::steady_clock::now();
- pass=graph.process(input,(i+1)*1000.0/60,i==0,output,i+1,&packet.colorInfo)&&ring.waitIdle();
+ pass=graph.process(input,(i+1)*1000.0/60,i==0||resetEveryFrame,output,i+1,&packet.colorInfo)&&ring.waitIdle();
const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
sink::RgbaImage image;if(pass)pass=sink::readRgba8(ctx,ring,graph.videoFrameResource(output.videoSlot),image);
if(!pass)break;