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

test: compare 4K SR reconstruction and motion-aligned error

Veyra Goal Agent8fc00d4c4915
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d0a0be00..c772fb7b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -439,6 +439,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_include_directories(veyra_srfg_depth_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_compile_definitions(veyra_srfg_depth_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(veyra_srfg_depth_tests PRIVATE veyra_engine)
+ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTests.cpp)
+ target_compile_features(veyra_sr_reconstruction_tests PRIVATE cxx_std_20)
+ target_include_directories(veyra_sr_reconstruction_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_compile_definitions(veyra_sr_reconstruction_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
+ target_link_libraries(veyra_sr_reconstruction_tests PRIVATE veyra_engine)
target_compile_features(veyra_depth_response_tests PRIVATE cxx_std_20)
target_include_directories(veyra_depth_response_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_compile_definitions(veyra_depth_response_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
diff --git a/docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md b/docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md
new file mode 100644
index 00000000..0e385da5
--- /dev/null
+++ b/docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md
@@ -0,0 +1,12 @@
+# Independent 4K reconstruction diagnostic review
+
+Fresh-context read-only reviewer `review_sr_reconstruction`, scoped base `3aa9c77`. Final **PASS**, no unresolved introduced P0/P1/P2. Full Goal remains open.
+
+- Independent preflight71/phase7 75 PASS; `logs/delivery/268ee4b316bf4604bedafcd9b747b09c/result.json`,41.718s.
+- Two independent scene invocations exit0,17.861s/22.122s. Evidence root `logs/optimization-goal-20260908/review-sr-reconstruction-af3b9187db1e408889edef8ab204ea0e/`.
+- Real shared graph1920×1080→3840×2160, scored SR24/NVOF23/reset1/debugErrors0. SR repeats match every frame hash. All reported spatial/temporal metrics reproduced exactly; Create/Evaluate0x1Success/SEH0. Structured nonblack reference and SR PNGs viewed.
+- Linear-light2×2 downsample, full24frame scores, known-motion correspondence and identity-based occlusion exclusion audited. Default product behavior and export integrity checks unchanged.
+- Initial documentationP2 clarified: NR/FG are disabled for24 scored source frames, while initialization still creates NR/FG and performs one frameId0 FG warm-up Evaluate excluded from scoring. Reviewer reread the correction and closed P2; no code change or redundant GPU rerun required.
+- Tracked fingerprint before/after full review `c75729b6fad01daa710480e28a34f935b1b79d26`. Untracked source/doc and executable hashes unchanged during full review, recorded in ignored evidence root. Reviewer did not rebuild; checked Maker build log and executed the resulting executable independently.
+
+Limits: two constructed scenes include startup; they establish neither natural footage/steady-state/perceptual benefit nor SR/NR joint improvement.20 GPU SR-stage samples do not prove playback FPS or end-to-end latency. PASS does not cover the full Goal, physical capture, long stability or distribution.
diff --git a/docs/SR_RECONSTRUCTION_2026-09-08.md b/docs/SR_RECONSTRUCTION_2026-09-08.md
new file mode 100644
index 00000000..9520127c
--- /dev/null
+++ b/docs/SR_RECONSTRUCTION_2026-09-08.md
@@ -0,0 +1,49 @@
+# 已知 4K 画面的超分重建对照
+
+Cycle77,基线 `3aa9c77`。本轮只新增独立诊断与 CMake target,不改变产品默认配置或导出完整性检查。**当前 DLSS SR 在两个构造样本里降低了空间误差,但提高了运动对齐后的误差变化和最大局部误差,不能据此声称全面改善画质。**
+
+## 输入与比较合同
+
+`tests/integration/SrReconstructionTests.cpp` 生成逐帧精确的 3840×2160 RGB8 参考;先解码 sRGB 到线性光,2×2 box 平均,再编码为 1920×1080 RGB8 输入。相同输入依次走共享 EnhanceGraph 的普通线性双线性缩放、DLSS SR、重新创建的 DLSS SR 重复组。所有组输出均为真实 3840×2160 资源。24 个被评分源帧不运行 NR/FG,NVOF 实际执行;共享图初始化仍创建 NR/FG,并有一次 frameId=0 的 FG 预热 Evaluate,它不参与本次评分。
+
+每组 24 帧、60fps PTS,仅首帧 reset。保存每组最后输出、最后源输入及 4K 参考 PNG;所有 24 帧都计算误差,不是以末帧替代序列。SR 重复组逐帧完整像素 hash 必须相同。每场景独立进程设 275 秒 watchdog。
+
+- 场景0:四个频率的棋盘纹理(方格边长 4/8/16/32 输出像素),整体每帧左移 4px。
+- 场景1:平滑周期背景每帧左移 4px,带细纹理前景每帧右移 8px,产生覆盖与显露。
+- 重建 MAE / PSNR / 最大误差均为 RGB8 编码值度量,包含起始帧;不含 alpha。
+- temporalErrorMae8:计算当前输出误差与前一帧对应场景点的输出误差之差的绝对均值。对应关系来自构造运动,不使用被测 NVOF 来评价自己。排除出界与前后景身份发生变化的点。它是本样本的时间误差指标,不是经过主观校准的“闪烁评分”。
+- 两个场景的运动均为整输入像素平移,尤其有利于普通空间缩放的时间稳定性;不代表自然片源、亚像素运动、压缩或所有遮挡。
+
+## 实测结果
+
+| 场景 / 路径 | RGB8 MAE ↓ | PSNR dB ↑ | 最大误差 ↓ | 时间误差 MAE8 ↓ |
+|---|---:|---:|---:|---:|
+| 多频棋盘 / 普通缩放 | 15.9795 | 19.0963 | 84 | 0.007202 |
+| 多频棋盘 / DLSS SR | 13.8156 | 20.3638 | 140 | 8.36538 |
+| 移动前景 / 普通缩放 | 1.92695 | 30.5818 | 64 | 0.006848 |
+| 移动前景 / DLSS SR | 1.76538 | 30.8184 | 111 | 0.309143 |
+
+SR 重复组像素逐帧精确重现。每组 SR Evaluate 24(空间组0)、NVOF23、reset1、NVOF failures0、D3D12 ERROR/CORRUPTION0。实际运行在本机 RTX,所有组 exit0。查看了非黑且有结构的移动前景 SR PNG。
+
+- 场景0:`logs/optimization-goal-20260908/sr-recon-final-0-b240e19c658c43d2bc06b06c4f4442ea/`,17.030秒。
+- 场景1:`logs/optimization-goal-20260908/sr-recon-final-1-42eb27fb292f4be0814b1e6d2c42de08/`,19.956秒。
+- 每目录 `stdout.log` 包含实际 Create/Evaluate 与 `SR_RECON` 汇总;`result.json` 记录退出码与耗时。
+
+SR stage 使用现有 GPU timestamp,跳过前4帧后各20样本:场景0首轮 mean3.007ms/P95 3.285ms,重复轮3.036/3.425ms;场景1首轮2.981/3.387ms,重复轮3.005/3.253ms。这只是 SR stage,排除 NVOF/解码/显示等;诊断有逐帧回读与等待,不能换算成正常播放器 FPS 或端到端延迟,20样本也不是长期性能结论。
+
+## 决策与未完成事项
+
+保持当前可选 SR,不强制替换用户设置,不把 4K 输出标签当作画质保证。不加默认深度模型或叠加另一个超分器。这个实验没有分离光流误差与 SR 自身历史处理的影响;下一步应检查已知运动指导的对照及自然素材,再决定具体改法,不能直接归罪于单个参数。
+
+RTX Video SDK 在本地项目和定向 Downloads 文件名搜索中未找到,尚未接入或测得收益。未完成自然压缩素材、主观画质及 SR/NR 联合质量验收。Phase7 / Goal 仍进行中。
+
+实际命令:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root "$PWD" -Preset x64-release
+out/build/x64-release/veyra_sr_reconstruction_tests.exe <唯一忽略日志目录> 0
+out/build/x64-release/veyra_sr_reconstruction_tests.exe <另一个唯一忽略日志目录> 1
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7
+```
+
+构建 `logs/optimization-goal-20260908/build-cycle77-final.log` exit0。[独立只读复核](REVIEW_SR_RECONSTRUCTION_2026-09-08.md)与门禁已通过,仅覆盖本专项。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 75d316da..ef3fc2ca 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1237,3 +1237,9 @@ review_nr_depth_response nointroducedP0/P1/P2. Independentpreflight71/phase7e67d
## Cycle76 independent final PASS
Initial P2 incomplete-FG-sample assertion repaired; independent18cases review-srfg-final-e1efc4f1b8124f8f9bea0aa7423b8345 exit0/32.210s, actual Create/Evaluate0x1 SEH0/debug0. Finalpreflight71 and phase7 bf527e55e4914c8aa93451ec78121f18 41.408s/75PASS. docs/REVIEW_SR_FG_DEPTH_RESPONSE_2026-09-08.md. Defaultdepthmodel remains absent; no verified cost/quality case for adding it. Next: known4K reconstruction against spatial baseline, then natural/changing-frame quality. RTX Video SDK absent from project and filename-targeted Downloads search. Export integrity unchanged; fullGoal open.
+
+## Cycle77 reconstruction candidate
+Actual1080->4K sharedgraph two24frame scenes: final0-b240e19c658c43d2bc06b06c4f4442ea17.030s andfinal1-42eb27fb292f4be0814b1e6d2c42de0819.956s exit0, NR/FGoff SR24/NVOF23/reset1/debug0, SRrepeat exact. SR lowers spatialMAE but increases temporalerrorandmaxerror; docs/SR_RECONSTRUCTION_2026-09-08.md. No naturalquality or defaultreplacement claim. Buildcycle77finalexit0; frozen gate/reviewpending.
+
+## Cycle77 independent final PASS
+review_sr_reconstruction: full24frameSR/spatial metrics reproduced, SRrepeat exact; twoactualRTXinvocations17.861/22.122s, debug0; docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md. Independentpreflight71/phase7 268ee4b316bf4604bedafcd9b747b09c41.718s75PASS. DocumentationP2 initializationFGwarmup distinction fixedandreadonlyrereadclosed. No default/product/export change. Next isolate exactmotion vsestimated SR guidance, and natural material; recent-app source exists (ffprobe H2641920x1080,30000/1001,limitedBT709,56.689s), not native4K reference. FullGoalopen.
diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.md
index c54aea47..8a2b36bb 100644
--- a/loop/EVIDENCE.md
+++ b/loop/EVIDENCE.md
@@ -540,3 +540,9 @@ review_nr_depth_response nointroducedP0/P1/P2. Independentpreflight71/phase7e67d
## Cycle76 independent final PASS
Initial P2 incomplete-FG-sample assertion repaired; independent18cases review-srfg-final-e1efc4f1b8124f8f9bea0aa7423b8345 exit0/32.210s, actual Create/Evaluate0x1 SEH0/debug0. Finalpreflight71 and phase7 bf527e55e4914c8aa93451ec78121f18 41.408s/75PASS. docs/REVIEW_SR_FG_DEPTH_RESPONSE_2026-09-08.md. Defaultdepthmodel remains absent; no verified cost/quality case for adding it. Next: known4K reconstruction against spatial baseline, then natural/changing-frame quality. RTX Video SDK absent from project and filename-targeted Downloads search. Export integrity unchanged; fullGoal open.
+
+## Cycle77 reconstruction candidate
+Actual1080->4K sharedgraph two24frame scenes: final0-b240e19c658c43d2bc06b06c4f4442ea17.030s andfinal1-42eb27fb292f4be0814b1e6d2c42de0819.956s exit0, NR/FGoff SR24/NVOF23/reset1/debug0, SRrepeat exact. SR lowers spatialMAE but increases temporalerrorandmaxerror; docs/SR_RECONSTRUCTION_2026-09-08.md. No naturalquality or defaultreplacement claim. Buildcycle77finalexit0; frozen gate/reviewpending.
+
+## Cycle77 independent final PASS
+review_sr_reconstruction: full24frameSR/spatial metrics reproduced, SRrepeat exact; twoactualRTXinvocations17.861/22.122s, debug0; docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md. Independentpreflight71/phase7 268ee4b316bf4604bedafcd9b747b09c41.718s75PASS. DocumentationP2 initializationFGwarmup distinction fixedandreadonlyrereadclosed. No default/product/export change. Next isolate exactmotion vsestimated SR guidance, and natural material; recent-app source exists (ffprobe H2641920x1080,30000/1001,limitedBT709,56.689s), not native4K reference. FullGoalopen.
diff --git a/loop/JOURNAL.md b/loop/JOURNAL.md
index 5e8971e0..9c1e1e18 100644
--- a/loop/JOURNAL.md
+++ b/loop/JOURNAL.md
@@ -1572,3 +1572,14 @@ Cycle76 reviewer P2: partial FG depth groups could pass with incomplete generate
## Cycle76 independent final PASS
Initial P2 incomplete-FG-sample assertion repaired; independent18cases review-srfg-final-e1efc4f1b8124f8f9bea0aa7423b8345 exit0/32.210s, actual Create/Evaluate0x1 SEH0/debug0. Finalpreflight71 and phase7 bf527e55e4914c8aa93451ec78121f18 41.408s/75PASS. docs/REVIEW_SR_FG_DEPTH_RESPONSE_2026-09-08.md. Defaultdepthmodel remains absent; no verified cost/quality case for adding it. Next: known4K reconstruction against spatial baseline, then natural/changing-frame quality. RTX Video SDK absent from project and filename-targeted Downloads search. Export integrity unchanged; fullGoal open.
+
+## Cycle77 - known4K reconstruction benchmark
+Previous Goal turn progress:3aa9c77 independently verified SR/FG depth response and fixed incomplete-GT assertion. Clean tree/noSTOP. Add isolated shared-graph1920x1080->3840x2160 comparison: linear-light2x2downsample from exact procedural4K, spatialbilinear vsSR andSRrepeat, allframes fullRGB error and known-motion temporal error. NR/FGoff, actualNVOF. No product defaults/export/check changes. Separate scene invocations each275s watchdog; never interpret mere4K dimensions or syntheticMAE as naturalquality.
+
+## Cycle77 reconstruction candidate
+Actual1080->4K sharedgraph two24frame scenes: final0-b240e19c658c43d2bc06b06c4f4442ea17.030s andfinal1-42eb27fb292f4be0814b1e6d2c42de0819.956s exit0, NR/FGoff SR24/NVOF23/reset1/debug0, SRrepeat exact. SR lowers spatialMAE but increases temporalerrorandmaxerror; docs/SR_RECONSTRUCTION_2026-09-08.md. No naturalquality or defaultreplacement claim. Buildcycle77finalexit0; frozen gate/reviewpending.
+
+Cycle77 independent initial review: two scenes reproduced17.861/22.122s, phase7 268ee4b316bf4604bedafcd9b747b09c41.718s75PASS. DocumentationP2 fixed: NR/FG are off for24scoredframes, not initialization; sharedgraphstillcreatesNR/FG andFGwarmupEvaluateframe0. No code/test change; reviewer reread requested.
+
+## Cycle77 independent final PASS
+review_sr_reconstruction: full24frameSR/spatial metrics reproduced, SRrepeat exact; twoactualRTXinvocations17.861/22.122s, debug0; docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md. Independentpreflight71/phase7 268ee4b316bf4604bedafcd9b747b09c41.718s75PASS. DocumentationP2 initializationFGwarmup distinction fixedandreadonlyrereadclosed. No default/product/export change. Next isolate exactmotion vsestimated SR guidance, and natural material; recent-app source exists (ffprobe H2641920x1080,30000/1001,limitedBT709,56.689s), not native4K reference. FullGoalopen.
diff --git a/loop/STATE.json b/loop/STATE.json
index 9fffc74c..3490ed97 100644
--- a/loop/STATE.json
+++ b/loop/STATE.json
@@ -76,19 +76,19 @@
}
],
"cycle": {
- "completed": 76,
+ "completed": 77,
"maximum": 120,
"sameFailureAttempts": 0,
"maximumSameFailureAttempts": 3,
"noProgressCycles": 0,
"maximumNoProgressCycles": 5
},
- "currentTask": "Cycle76 SR/FG depth response independently passed after FG sample-completeness assertion repair",
+ "currentTask": "Cycle77 known4K reconstruction independently passed; spatial/temporal tradeoff measured",
"lastGate": {
"name": "phase7",
"status": "passed",
"exitCode": 0,
- "evidence": "logs/delivery/bf527e55e4914c8aa93451ec78121f18/result.json;41.408s;75checks"
+ "evidence": "logs/delivery/268ee4b316bf4604bedafcd9b747b09c/result.json;41.718s;75checks"
},
"lastFailureFingerprint": "",
"failureLedger": [
@@ -107,8 +107,8 @@
"Current USB2 1080p50 physical throughput passed; user perceived latency/audio/actual FG display cadence still need confirmation.",
"Public proprietary runtime distribution rights unresolved; local delivery only."
],
- "nextAction": "Known4K downsample/reconstruction comparison against spatial baseline, then natural/changing-frame quality; RTX Video SDK unavailable",
- "updatedAt": "2026-09-08T12:28:19.1665042Z",
+ "nextAction": "Isolate accurate motion versus estimated SR guidance and supplement natural material; no default SR/depth replacement without benefit",
+ "updatedAt": "2026-09-08T12:41:17.8709040Z",
"deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md",
"captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending",
"testInvocationLimitSeconds": 300,
@@ -133,7 +133,8 @@
"Cycles71-73 independent scopedPASS: scene14/motionverticalcostboundary; NR600NVOF594; actualFG600source594generated6hold1200output independentlydecoded, docs/REVIEW_SCENE_BOUNDARIES_2026-09-08.md",
"Cycle74 independent scopedPASS, docs/REVIEW_BIDIRECTIONAL_FLOW_2026-09-08.md:360/1080/4K controlledbidirectional plus640x129alignmentfix; no defaultintegration",
"Cycle75 independent NRdepth24casesPASS:docs/REVIEW_NR_DEPTH_RESPONSE_2026-09-08.md; no depthresponse, strongMV/intensityresponse; no newmodels/defaults",
- "Cycle76 independent scopedPASS: docs/REVIEW_SR_FG_DEPTH_RESPONSE_2026-09-08.md; SR8bit negative depth response, FG tiny constructed benefit, no defaultmodel"
+ "Cycle76 independent scopedPASS: docs/REVIEW_SR_FG_DEPTH_RESPONSE_2026-09-08.md; SR8bit negative depth response, FG tiny constructed benefit, no defaultmodel",
+ "Cycle77 independent scopedPASS: docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md; real4K SR spatialMAE lower, temporalerror/max higher; no natural/steady-state claim"
],
"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb",
"localDelivery": "capture_fix_candidate_needs_review",
@@ -271,8 +272,8 @@
"testInvocationLimitSeconds": 300,
"productModified": true,
"consecutiveBlockedGoalTurns": 0,
- "previousGoalTurnClassification": "progress: controlledNRdepthnegative withresidenttextureupdate, MV/intensitypositive, actualRTXandindependentreview; avoidedunsupporteddefaultmodelcost",
- "currentGoalTurnClassification": "progress: SR/FG depth response and exact half-frame GT measured; incomplete-sample P2 fixed, independent18cases andgate PASS; default model not justified",
+ "previousGoalTurnClassification": "progress: SR/FG depth response and exact half-frame GT measured; incomplete-sample P2 fixed, independent18cases andgate PASS; default model not justified",
+ "currentGoalTurnClassification": "progress: known4K downsample reconstruction and temporal errors measured, independentRTXreproduction andgatePASS; next isolate motion cause",
"controlSynchronizationAuthorization": "2026-09-08 user: 确认,给你全部权限; applies to previously proposed exact two-hash synchronization",
"diagnosticFindings": [
"Q7 read-only dependency check: RTXVideoSDK not present in third_party_local; official1.1download redirects NVIDIA login. Localdepthfile vitl is Large, not permitted Small; no verified Small ONNX/provider. No dependency integrated or performance claimed."
diff --git a/tests/integration/SrReconstructionTests.cpp b/tests/integration/SrReconstructionTests.cpp
new file mode 100644
index 00000000..59d111f0
--- /dev/null
+++ b/tests/integration/SrReconstructionTests.cpp
@@ -0,0 +1,67 @@
+// Isolated exact-source reconstruction diagnostic; never a product readback path.
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <d3d12sdklayers.h>
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <filesystem>
+#include <iostream>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+using namespace veyra;
+namespace {
+constexpr unsigned W=3840,H=2160,N=24;
+bool foreground(int x,int y,unsigned frame){return x>=900+int(frame)*8&&x<1800+int(frame)*8&&y>=500&&y<1600;}
+uint64_t hash(const sink::RgbaImage& image){uint64_t v=14695981039346656037ull;for(auto b:image.pixels){v^=b;v*=1099511628211ull;}return v;}
+int experiment(const std::filesystem::path& dir,unsigned scene){
+ std::array<float,256> linear{};for(unsigned i=0;i<256;++i){float s=i/255.f;linear[i]=s<=.04045f?s/12.92f:std::pow((s+.055f)/1.055f,2.4f);}
+ auto encoded=[](float s){return uint8_t(std::clamp(std::lround((s<=.0031308f?s*12.92f:1.055f*std::pow(s,1/2.4f)-.055f)*255),0l,255l));};
+ std::vector<uint64_t> srHashes;std::vector<uint8_t> gt(size_t(W)*H*4);
+ for(unsigned mode=0;mode<3;++mode){
+ 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;
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=W/2;gd.sourceHeight=H/2;gd.workWidth=W;gd.workHeight=H;gd.rgbInput=true;gd.enableNr=false;gd.enableFg=false;gd.enableSr=mode!=0;gd.enableNvofStandalone=true;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();
+ if(!graph.initialize(gd)||!graph.createViews())return 2;
+ AVFrame* f=av_frame_alloc();if(!f)return 2;f->width=W/2;f->height=H/2;f->format=AV_PIX_FMT_RGBA;f->color_range=AVCOL_RANGE_JPEG;f->color_trc=AVCOL_TRC_IEC61966_2_1;f->colorspace=AVCOL_SPC_RGB;if(av_frame_get_buffer(f,32)<0){av_frame_free(&f);return 2;}
+ std::vector<int16_t> previousError(size_t(W)*H*3),currentError(previousError.size());std::vector<double> srTimes;
+ uint64_t absolute=0,squared=0,samples=0,temporal=0,temporalSamples=0;unsigned maximum=0;bool ok=true;
+ for(unsigned frame=0;frame<N&&ok;++frame){
+ // Every sample derives from the same exact high-resolution scene.
+ for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){
+ const int q=int(x)+int(frame)*4;const bool object=scene==1&&foreground(x,y,frame);
+ unsigned value;
+ if(object)value=((int(x)-int(frame)*8)/7+int(y)/11)%2?185:95;
+ else if(scene==0){const unsigned band=y/(H/4);const unsigned period=4u<<band;value=((q/int(period)+int(y)/int(period))%2)?190:55;}
+ else value=unsigned(110+35*std::sin(q*.037)+25*std::cos(y*.051));
+ auto* p=&gt[(size_t(y)*W+x)*4];p[0]=uint8_t(value);p[1]=uint8_t(std::min(255u,value+20));p[2]=uint8_t(std::max(0,int(value)-20));p[3]=255;
+ }
+ for(unsigned y=0;y<H/2;++y)for(unsigned x=0;x<W/2;++x){auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;
+ for(unsigned c=0;c<3;++c){float sum=0;for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx)sum+=linear[gt[(size_t(y*2+dy)*W+x*2+dx)*4+c]];p[c]=encoded(sum*.25f);}p[3]=255;}
+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage image;ok=graph.process(f,frame*(1000.0/60),frame==0,out,frame+1)&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);
+ if(!ok)break;ok=image.width==W&&image.height==H&&image.pixels.size()==gt.size();if(!ok)break;
+ const auto h=hash(image);if(mode==1)srHashes.push_back(h);if(mode==2)ok=h==srHashes[frame];
+ for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){const bool object=scene==1&&foreground(x,y,frame);const int px=int(x)+(object?-8:4);const bool temporalValid=frame>0&&px>=0&&px<int(W)&&(scene==0||foreground(px,y,frame-1)==object);
+ for(unsigned c=0;c<3;++c){const size_t i=(size_t(y)*W+x)*3+c;const int error=int(image.pixels[(size_t(y)*W+x)*4+c])-int(gt[(size_t(y)*W+x)*4+c]);currentError[i]=int16_t(error);const unsigned a=unsigned(std::abs(error));absolute+=a;squared+=uint64_t(a)*a;++samples;maximum=std::max(maximum,a);
+ if(temporalValid){temporal+=std::abs(error-previousError[(size_t(y)*W+px)*3+c]);++temporalSamples;}}
+ }
+ previousError.swap(currentError);const auto metrics=graph.gpuMetrics();const auto& timing=metrics.gpu[size_t(diagnostics::GpuStage::Sr)];
+ if(frame>=4&&metrics.identity.sourceFrameId==frame+1&&timing.state==diagnostics::SampleState::Measured&&timing.milliseconds)srTimes.push_back(*timing.milliseconds);
+ if(frame+1==N)ok=ok&&sink::saveImage((dir/("scene"+std::to_string(scene)+"-mode"+std::to_string(mode)+".png")).wstring(),image);
+ if(frame+1==N&&mode==0){sink::RgbaImage reference{W,H,gt},input{W/2,H/2,{}};input.pixels.resize(size_t(W/2)*(H/2)*4);for(unsigned y=0;y<H/2;++y)std::copy_n(f->data[0]+size_t(y)*f->linesize[0],W/2*4,input.pixels.data()+size_t(y)*(W/2)*4);ok=ok&&sink::saveImage((dir/L"reference.png").wstring(),reference)&&sink::saveImage((dir/L"input.png").wstring(),input);}
+ }
+ av_frame_free(&f);auto m=graph.metrics();ok=ok&&m.nrEvaluateCount==0&&m.srEvaluateCount==(mode?N:0)&&m.nvofExecuteCount==N-1&&m.nvofFrameFailures==0&&m.resetCount==1&&samples==uint64_t(N)*W*H*3&&temporalSamples>0;
+ ok=ring.drainQueue()&&ok;graph.shutdown();pipeline::ComPtr<ID3D12InfoQueue> iq;unsigned errors=0;if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&iq))))return 2;
+ for(UINT64 i=0;i<iq->GetNumStoredMessages();++i){SIZE_T size=0;if(FAILED(iq->GetMessage(i,nullptr,&size)))return 2;std::vector<uint8_t> bytes(size);auto* msg=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());if(FAILED(iq->GetMessage(i,msg,&size)))return 2;if(msg->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<msg->pDescription<<std::endl;}}
+ std::sort(srTimes.begin(),srTimes.end());double mean=0;for(auto v:srTimes)mean+=v;mean=srTimes.empty()?-1:mean/srTimes.size();
+ std::cout<<"SR_RECON scene="<<scene<<" mode="<<mode<<" source=1920x1080 output=3840x2160 frames="<<N<<" sr="<<m.srEvaluateCount<<" nvof="<<m.nvofExecuteCount<<" reset="<<m.resetCount<<" mae8="<<double(absolute)/samples<<" psnr="<<(squared?10*std::log10(255.*255.*samples/squared):999)<<" max="<<maximum<<" temporalErrorMae8="<<double(temporal)/temporalSamples<<" gpuSrSamples="<<srTimes.size()<<" gpuSrMeanMs="<<mean<<" gpuSrP95Ms="<<(srTimes.empty()?-1:srTimes[size_t(std::ceil(srTimes.size()*.95))-1])<<" errors="<<errors<<" pass="<<(ok&&!errors)<<std::endl;
+ if(!ok||errors)return 1;
+ }
+ return 0;
+}
+}
+int wmain(int argc,wchar_t** argv){if(argc!=3)return 2;unsigned scene=unsigned(std::wcstoul(argv[2],nullptr,10));if(scene>1)return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::path dir=argv[1];std::filesystem::create_directories(dir);int result=experiment(dir,scene);CoUninitialize();return result;}