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

fix: preserve temporal NR masks and reuse GPU neighborhood work

Veyra Goal Agentab7979c743c1
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 36a425a4..d306d5d5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -728,6 +728,9 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_features(veyra_motion_validation_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_motion_validation_tests PRIVATE veyra_pipeline)
add_executable(veyra_repair_shader_tests tests/integration/RepairShaderTests.cpp)
+ add_executable(veyra_nr_temporal_gpu_tests tests/integration/NrTemporalGpuTests.cpp)
+ target_compile_features(veyra_nr_temporal_gpu_tests PRIVATE cxx_std_20)
+ target_link_libraries(veyra_nr_temporal_gpu_tests PRIVATE veyra_pipeline)
add_executable(veyra_gpu_timing_tests tests/integration/GpuTimingTests.cpp)
target_compile_features(veyra_gpu_timing_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_gpu_timing_tests PRIVATE veyra_pipeline)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 57788641..f08b8257 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -55,7 +55,12 @@ SAOG0721/Magpie, commit
`src/Magpie.Core/DLSSNRTemporalShader.h` (GPL-3.0). The Veyra version keeps
the existing D3D12 graph, uses its source motion extent and signed HDR working
space, and adds its own resource/reset plumbing; it is not a binary or runtime
-copy. The switch is default-off until affected RTX hardware and motion-scene
+copy. The 2026-09-21 adaptation distinguishes explicit protection masks from
+valid zero residual observations, excludes protected/feathered history, and
+rejects invalid source time intervals. A Veyra groupshared tile reuses the
+upstream-derived neighborhood observations without changing their tap order.
+Product D3D12 regression coverage is in
+`tests/integration/NrTemporalGpuTests.cpp`. The switch is default-off until affected RTX hardware and motion-scene
quality tests reject ghosting and flicker regressions.
## AMD FidelityFX Optical Flow
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index c364d22f..7a8414ff 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -1256,6 +1256,12 @@ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<a
if(positionalArgv)LocalFree(positionalArgv);
}
if(workerMapping){const int code=veyra::engine::runExportWorker(workerMapping);CoUninitialize();return code;}
+if(smokeSeconds>0){
+ int temporalArgc=0;auto temporalArgv=CommandLineToArgvW(GetCommandLineW(),&temporalArgc);
+ for(int i=1;i<temporalArgc;++i)if(!_wcsicmp(temporalArgv[i],L"--nr-temporal"))initialOptions.settings.nrTemporal=true;
+ if(temporalArgv)LocalFree(temporalArgv);
+ veyra::log::info("app",std::format("smoke NR temporal={}",initialOptions.settings.nrTemporal));
+}
if(smokeSeconds<=0&&exportOutput.empty()){uiPreferences=preferences.load();initialOptions=veyra::engine::PlayerOptions::from(preferences.startup(initialOptions.snapshot()));engine.setVolume(uiPreferences.volume,uiPreferences.muted);uiState.subtitles=uiPreferences.subtitles;subtitlePixels=uiPreferences.subtitleSize;uiState.subtitleOutline=uiPreferences.subtitleOutline;uiState.subtitleBackground=uiPreferences.subtitleBackground;uiState.subtitleSecondLanguage=uiPreferences.subtitleSecondLanguage;uiState.subtitleMargin=uiPreferences.subtitleMargin;uiState.subtitleFont=uiPreferences.subtitleFont;}
engine.requestPresentation(uiPreferences.presentation);
engine.requestSettings(initialOptions.snapshot());
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index ed4b9143..ec18c921 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -1,5 +1,12 @@
# 当前项目状态 / Current Status
+2026-09-21 local bounded NR/performance review: temporal protection/time fixes
+and shared-neighborhood GPU optimization tested on RTX 5070. Default remains
+off; natural-video visual acceptance and independent VFX denoise are not
+delivered. No general 1.4.3 performance regression established. See
+[evidence and limits](NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md).
+No new release or main merge.
+
**2026-09-20:1.4.3 已正式发布为 [GitHub Latest](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.3)。** 发布源码/标签对应 `3b4570e`,正确修复已整合至 main;正式便携包七项检查、120 个载荷校验、对应源码 856 个文件校验及四项远端资产哈希核对通过。用户最新测试包与正式 EXE 完全相同。固定 6X 均匀呈现及未定因设备反馈仍按下方边界处理。发布记录见 [RELEASE_1.4.3_EXECUTION.md](RELEASE_1.4.3_EXECUTION.md)。
2026-09-20:用户验收最新 1.4.3 测试包并授权正式发布。当前发布工作包含截至 `139db25` 的产品修复及远端中文 README 精简,分支审计与正式构建/发布结果统一记录在 [1.4.3 发布执行记录](RELEASE_1.4.3_EXECUTION.md)。下方“仅本地/未发布”语句均为历史阶段记录;固定 6X 均匀呈现仍未解决,不随正式版发布改为通过。
diff --git a/docs/NR_PERFORMANCE_POWER_REVIEW_2026-09-21.md b/docs/NR_PERFORMANCE_POWER_REVIEW_2026-09-21.md
index bc1beab6..642ad310 100644
--- a/docs/NR_PERFORMANCE_POWER_REVIEW_2026-09-21.md
+++ b/docs/NR_PERFORMANCE_POWER_REVIEW_2026-09-21.md
@@ -74,3 +74,10 @@ same enabled setting, then perform one bounded optimization or withdraw the
regressing change. On/off alone does not establish which new edit caused
the cost: the previous version already had a temporal pass. Natural-image
visual acceptance is still outstanding.
+
+The accepted continuation optimization is the groupshared 10x10 halo in
+`shaders/NrTemporal.hlsl`. It removes duplicate nine-tap work without changing
+output fingerprints. Product D3D12 regression and a 30-second p001.mp4
+temporal-on smoke passed; the execution plan records the measured cadence and
+the limit that this is not a subjective natural-video or physical-display
+latency acceptance. No power claim is made from this short run.
diff --git a/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md b/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md
new file mode 100644
index 00000000..c4a50c35
--- /dev/null
+++ b/docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md
@@ -0,0 +1,86 @@
+# NR / XeSS bounded review result
+
+Branch: codex/playback-nr-20260920. Starting checkpoint:
+checkpoint/pre-nr-quality-perf-20260921 (bcdbfbf).
+This closes the bounded local investigation, not universal picture-quality
+or hardware acceptance. No publication or release package was requested here.
+
+## Decisions for items 1 / 2 / 3 / 4 / 6
+
+1. Temporal NR: fix valid-zero residual decay, protection/feather exclusion and
+ invalid source intervals. Keep default off and the existing 80 ms history
+ constant. A groupshared halo eliminates repeated neighborhood observations;
+ no added presentation wait, reduced resolution or changed FG multiplier.
+2. Independent denoise: not implemented. Magpie uses NvVFX VideoSuperRes,
+ NvCV and CUDA, not direct NGX's VSR quality enum. Required runtime/model
+ identity and GPU-only interop are not available in the configured Veyra
+ dependency set. Upstream per-frame synchronization/HDR CPU readback cannot
+ be copied into the real-time graph. Do not advertise the NR rename or the
+ temporal filter as delivery of this separate denoiser.
+3. Product shader tests: D3D12 17x13 FP16 tests cover reset, zero residual,
+ invalid time, motion rejection, protected/feathered history and signed HDR.
+ Added patterned frames with fractional motion and full-frame fingerprints.
+4. Guidance audit: no demonstrated frame-identity/lifetime defect requiring a
+ patch. Existing leases, epochs, fences and current-to-previous direction
+ remain. Synthetic motion tests do not prove all NVOF fast-motion quality.
+6. XeSS: keep 1.4.3-equivalent provider pacing. Previously speculative timing
+ feedback is already withdrawn (dd69e1f). Do not add a nine-sample source-time
+ estimator until the caller carries that source timestamp contract. No
+ synchronous duplicate detector or default AMD flow was added.
+
+## Temporal experiment
+
+RTX 5070, p001.mp4, NR on, SR off, XeSS 4X, 30 seconds each. Same diagnostic
+app, only NrTemporal.dxil changed for the shader comparison. Previous shader
+comparison uses the current host constants: this isolates shader cost, not a
+complete historical app comparison. All five enabled runs exit 0.
+
+| Shader / run | Source frames | Generated | Final source FPS | Late P95 ms | Residual GPU P95 ms | Skips* |
+| --- | ---: | ---: | ---: | ---: | ---: | ---: |
+| Original shader | 1555 | 4476 | 58 | 45.96 | 2.056 | 62 |
+| Corrected, before optimization | 1578 | 4503 | 58 | 46.48 | 2.014 | 67 |
+| Tiled | 1619 | 4848 | 60 | 41.71 | 1.369 | 1 |
+| Tiled confirmation | 1642 | 4887 | 60 | 43.35 | 1.042 | 1 |
+| Before optimization confirmation | 1576 | 4485 | 57 | 46.00 | 2.023 | 71 |
+
+*Skips and GPU P95 use the final player-timing window; source/generated use
+the shutdown smoke summary. They have different boundaries. Final FPS is not
+the whole-run average. None is physical scanout or screen-to-eye latency.
+
+The tiled shader matches the corrected non-tiled shader's full-frame FP16
+fingerprints on all 41 test frames. Both test runs pass and report zero D3D12
+debug errors. This proves equality on this corpus only. Natural-video
+flicker/detail/ghosting has NOT passed subjective acceptance. Temporal-on is
+still substantially later than off (off smoke P95 1.65 ms); do not claim
+the feature is free or that its remaining delay is fixed. No further tuning.
+
+## Release comparison and limits
+
+See NR_PERFORMANCE_POWER_REVIEW_2026-09-21.md and
+MAGPIE_NR_XESS_COMPARISON_2026-09-21.md. Short ABBA runs do not demonstrate a
+blanket 1.4.3 regression: XeSS power +2.1%, DLSS -3.4% in trimmed samples.
+Thermal state/content positions are not controlled and SR was off. DLSS 1.4.3
+had far fewer expired generated frames/slot waits. Do not revert that fix
+because of power alone. Existing fixed-6X uniform-presentation limits remain.
+
+## Reproduction / artifacts
+
+E:/项目/Veyra/tests/nr-quality-perf-20260921:
+- compare-temporal.ps1 (baseline,current then tiled then tiled,current confirm)
+- temporal-isolate-*.log and temporal-gpu-{current,tiled,accepted}.log
+- NrTemporal-{baseline,current,tiled}.dxil and baseline HLSL evidence
+- Existing release comparison script, application logs and power CSVs
+
+Build: E:/项目/Veyra/build/playback-nr-20260920, MSVC vcvars64 + CMake
+--build <build> --target veyra_nr_temporal_gpu_tests veyra -j 4.
+DXC: -T cs_6_0 -E main -O3 -Qstrip_debug -Qstrip_reflect.
+During A/B a baseline shader was copied over the build output; the last
+incremental build therefore correctly reported no work by timestamp. The
+final shader was explicitly recompiled from source, hash verified and tested.
+Final SHA256: DE74C9611D2032AD07C28E4F98F84E14D6521BEF297414F163F07DBF13C84A4C.
+
+app/Veyra.exe is diagnostic staging, with the final shader restored. Its
+inherited package manifest is stale: NOT a redistributable release package.
+No DLL/model added to Git; runtimes unchanged. No main merge or push.
+User acceptance still needs real viewing (especially moving fine detail),
+NR+SR combinations, real capture, and GPUs other than the tested RTX 5070.
diff --git a/docs/NR_QUALITY_PERFORMANCE_PLAN_2026-09-21.md b/docs/NR_QUALITY_PERFORMANCE_PLAN_2026-09-21.md
index b1f4da77..8bce0e26 100644
--- a/docs/NR_QUALITY_PERFORMANCE_PLAN_2026-09-21.md
+++ b/docs/NR_QUALITY_PERFORMANCE_PLAN_2026-09-21.md
@@ -60,3 +60,21 @@ Video: E:/项目/Likely7 个人账号/Deepseek Grok/p001.mp4; PS5 is off.
regressed (58 versus 60 source FPS, lateness P95 46.54 versus 1.65 ms).
Not accepted. Compare against the previous enabled implementation before
attributing this to the new correction; retain evidence and bound tuning.
+
+## Accepted bounded optimization
+
+The original nine-tap temporal shader recomputed the same one-pixel-halo
+observations for neighboring threads. A groupshared 10x10 tile now computes
+each observation once and reuses it, preserving the original tap order,
+thresholds, signed residuals and reset/protection behavior. This is a scheduling
+optimization only; it adds no holdback or frame-rate cap.
+
+Evidence: `tests/nr-quality-perf-20260921/temporal-gpu-accepted.log` passed the
+product D3D12 pass with debug layer clean. The tiled shader and the prior shader
+produced identical full-frame fingerprints for 41 regression frames, including
+odd extents, fractional motion, resets, protection and signed HDR cases.
+With the same staged application, video temporal-on improved from 58 source FPS,
+46.48 ms lateness P95 and 2.014 ms residual GPU P95 to 60 FPS, 41.71 ms and
+1.369 ms respectively; preview skips fell from 67 to 1. These are software
+timings, not physical display latency. The run remains a bounded smoke test,
+not a natural-video subjective quality acceptance.
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index ca316af1..1f996b94 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-09-21 Bounded NR quality/performance result
+
+See docs/NR_QUALITY_PERFORMANCE_ACCEPTANCE_2026-09-21.md for final decisions,
+commands, artifacts and limitations. Tiled confirmation: 60 final source FPS,
+1 preview skip, residual GPU P95 1.042 ms versus non-tiled confirmation
+57 FPS / 71 skips / 2.023 ms. Both exit 0. The 41-frame fingerprint comparison
+is exact on the test corpus, D3D12 debug errors zero. Corrected protection/time
+handling is retained with the optional feature default off. Visual acceptance
+is still pending; no independent denoiser or universal 6X/power fix claimed.
+Final compiled shader restored in build and diagnostic staging, hash in report.
+All smoke sessions completed. No package, push or main merge.
+
## 2026-09-21 NR quality and performance goal started
Baseline bcdbfbf saved as checkpoint/pre-nr-quality-perf-20260921.
@@ -5594,3 +5606,16 @@ E:/项目/Veyra/logs/color-mixer-hue-20260920/{cpu,gpu,gpu-runtime}.*.log;
build and process-local tmp are under the matching E:/项目/Veyra directories.
git diff --check passed. No PS/LR visual equivalence or user-image acceptance
claimed; no packaging, publication, runtime changes or additional GPU pass.
+
+2026-09-21 continuation: compared the pre-existing temporal shader with the
+current correction under identical p001.mp4 settings. The correction itself
+was not promoted because temporal-on remained cadence-limited. Implemented one
+bounded groupshared 10x10 halo optimization in `shaders/NrTemporal.hlsl`.
+`temporal-gpu-accepted.log` passed the product D3D12 regression (debug clean),
+and 41 full-frame fingerprints matched the prior shader. The staged 30-second
+temporal-on smoke improved residual GPU P95 2.014 to 1.369 ms, source 58 to
+60 FPS, lateness P95 46.48 to 41.71 ms, and preview skips 67 to 1; exit 0.
+This is software timing only, not display latency or subjective quality proof.
+No independent denoiser was added because required VFX/NvCV/CUDA GPU-only
+prerequisites and distribution identity remain unavailable. No guidance or
+XeSS rollback was justified by the existing evidence. No release or shutdown.
diff --git a/include/veyra/pipeline/NrTemporalPass.h b/include/veyra/pipeline/NrTemporalPass.h
index b7333958..434116ef 100644
--- a/include/veyra/pipeline/NrTemporalPass.h
+++ b/include/veyra/pipeline/NrTemporalPass.h
@@ -1,5 +1,6 @@
#pragma once
#include "veyra/pipeline/GpuPassUtils.h"
+#include "veyra/engine/EnhancementSettings.h"
#include <array>
namespace veyra::pipeline {
@@ -9,7 +10,8 @@ class NrTemporalPass {
public:
bool initialize(ID3D12Device*,ID3D12Resource* base,ID3D12Resource* motion,ID3D12Resource* output);
ID3D12Resource* raw()const{return raw_.Get();}
- void run(ID3D12GraphicsCommandList*,StateTracker&,bool reset,bool haveMotion,double frameMs);
+ void run(ID3D12GraphicsCommandList*,StateTracker&,bool reset,bool haveMotion,double frameMs,
+ float total,const engine::ProtectionSettings& protection);
void reset(){valid_=false;}
void close();
private:
diff --git a/shaders/NrProtection.hlsli b/shaders/NrProtection.hlsli
new file mode 100644
index 00000000..7859d679
--- /dev/null
+++ b/shaders/NrProtection.hlsli
@@ -0,0 +1,15 @@
+#ifndef VEYRA_NR_PROTECTION
+#define VEYRA_NR_PROTECTION
+float NrProtection(float2 pixel, uint2 size, float enabled, float feather, float4 regions[4]) {
+ float protection=0;
+ if(enabled>0) {
+ for(uint i=0;i<4;++i) {
+ float4 r=regions[i]*float4(size,size);
+ if(r.z<=r.x||r.w<=r.y)continue;
+ float edge=min(min(pixel.x-r.x,r.z-pixel.x),min(pixel.y-r.y,r.w-pixel.y));
+ protection=max(protection,feather>0?smoothstep(0,feather,edge):(edge>=0?1:0));
+ }
+ }
+ return protection;
+}
+#endif
diff --git a/shaders/NrResidualComposite.hlsl b/shaders/NrResidualComposite.hlsl
index ac477911..68d7ca08 100644
--- a/shaders/NrResidualComposite.hlsl
+++ b/shaders/NrResidualComposite.hlsl
@@ -1,3 +1,4 @@
+#include "NrProtection.hlsli"
Texture2D<float4> baseTex:register(t0);
Texture2D<float4> nrInput:register(t1);
Texture2D<float4> nrFinal:register(t2);
@@ -21,15 +22,7 @@ float shadowSafe(float base,float rawDelta,float requestedDelta){
uint w,h,nw,nh;baseTex.GetDimensions(w,h);nrInput.GetDimensions(nw,nh);
if(id.x>=w||id.y>=h)return;
float4 base=baseTex[id.xy];
- float protection=0;
- if(protectionEnabled>0){
- float2 p=float2(id.xy)+0.5;
- for(uint i=0;i<4;++i){float4 r=regions[i]*float4(w,h,w,h);
- if(r.z<=r.x||r.w<=r.y)continue;
- float edge=min(min(p.x-r.x,r.z-p.x),min(p.y-r.y,r.w-p.y));
- protection=max(protection,featherPixels>0?smoothstep(0,featherPixels,edge):(edge>=0?1:0));
- }
- }
+ float protection=NrProtection(float2(id.xy)+0.5,uint2(w,h),protectionEnabled,featherPixels,regions);
if(total==0||protection>=1){outputTex[id.xy]=base;return;}
float2 pos=(float2(id.xy)+0.5)*float2(nw,nh)/float2(w,h)-0.5;
int2 origin=(int2)floor(pos);float2 f=frac(pos);float3 delta=0;float weights=0;
diff --git a/shaders/NrTemporal.hlsl b/shaders/NrTemporal.hlsl
index 59d70f9d..82db1a4d 100644
--- a/shaders/NrTemporal.hlsl
+++ b/shaders/NrTemporal.hlsl
@@ -3,6 +3,7 @@
// src/Magpie.Core/DLSSNRTemporalShader.h (motion route 2).
// Veyra: D3D12 Load-based bilinear sampling, source-flow extent conversion,
// linear signed HDR guide, reset via zero weight, post-protection residual.
+#include "NrProtection.hlsli"
Texture2D<float4> Base:register(t0);
Texture2D<float4> Raw:register(t1);
Texture2D<float4> History:register(t2);
@@ -11,7 +12,7 @@ Texture2D<float2> Motion:register(t4);
RWTexture2D<float4> Output:register(u0);
RWTexture2D<float4> NextHistory:register(u1);
RWTexture2D<float4> NextGuide:register(u2);
-cbuffer Settings:register(b0){uint2 Size;float HistoryWeight;float pad;float4 reserved;}
+cbuffer Settings:register(b0){uint2 Size;float HistoryWeight;float Total;float ProtectionEnabled;float Feather;float2 reserved;float4 Regions[4];}
float3 Guide(float3 c){return c/(1+abs(c));}
bool Inside(int2 p){return all(p>=0)&&all(p<int2(Size));}
float4 Bilinear(Texture2D<float4> tex,float2 p){
@@ -27,23 +28,50 @@ bool PreviousPosition(int2 p,out float2 previous){
if(!all(isfinite(mv)))return false;previous+=mv;
return all(previous>=0)&&all(previous<=float2(Size)-1);
}
-[numthreads(8,8,1)]void main(uint3 id:SV_DispatchThreadID){
+groupshared float4 TileResidual[100];
+groupshared float4 TilePosition[100];
+groupshared float TileError[100];
+[numthreads(8,8,1)]void main(uint3 id:SV_DispatchThreadID,uint3 local:SV_GroupThreadID,uint lane:SV_GroupIndex){
+ // The 8x8 output tile shares a one-pixel halo. Each observation is computed
+ // once instead of nine times; thresholds and accumulation order stay intact.
+ if(HistoryWeight>0){
+ for(uint tap=lane;tap<100;tap+=64){
+ int2 n=int2(id.xy)-int2(local.xy)+int2(tap%10,tap/10)-1;
+ float2 oldPosition;float4 residual=0,position=0;float error=0;
+ if(PreviousPosition(n,oldPosition)){
+ float4 inputN=Base[n],old=Bilinear(PreviousGuide,oldPosition);
+ float3 residualN=Raw[n].rgb-inputN.rgb;
+ bool valid=all(isfinite(inputN))&&all(isfinite(old))&&old.a>=.999&&all(isfinite(residualN));
+ float3 delta=abs(Guide(inputN.rgb)-old.rgb);
+ error=max(delta.r,max(delta.g,delta.b));
+ residual=float4(residualN,valid?1:0);
+ position=float4(oldPosition,1,0);
+ }
+ TileResidual[tap]=residual;TilePosition[tap]=position;TileError[tap]=error;
+ }
+ }
+ GroupMemoryBarrierWithGroupSync();
int2 p=id.xy;if(any(id.xy>=Size))return;
float4 base=Base[p],raw=Raw[p];bool finite=all(isfinite(base))&&all(isfinite(raw));
NextGuide[p]=all(isfinite(base))?float4(Guide(base.rgb),1):0;
if(!finite){NextHistory[p]=0;Output[p]=all(isfinite(base))?base:float4(0,0,0,1);return;}
float3 current=raw.rgb-base.rgb,result=current;float2 previous;
- // Preserve exact bypass/protection pixels; never revive a masked residual.
- if(HistoryWeight>0&&any(abs(current)>1e-7)&&PreviousPosition(p,previous)){
+ // A zero correction is a valid observation, not a protection mask. Keep
+ // protected/feathered pixels exact and exclude them from future history.
+ bool protectedPixel=Total==0||NrProtection(float2(p)+.5,Size,ProtectionEnabled,Feather,Regions)>0;
+ if(protectedPixel){NextHistory[p]=0;Output[p]=raw;return;}
+ uint center=(local.y+1)*10+local.x+1;
+ if(HistoryWeight>0&&TilePosition[center].z>0){
+ previous=TilePosition[center].xy;
float error=0,maximumError=0;bool valid=true;float3 lo=current,hi=current;
[unroll]for(int y=-1;y<=1;++y)[unroll]for(int x=-1;x<=1;++x){
- int2 n=p+int2(x,y);float2 previousN;
- if(!PreviousPosition(n,previousN)){valid=false;continue;}
+ int2 n=p+int2(x,y);uint tap=center+y*10+x;
+ float2 previousN=TilePosition[tap].xy;
+ if(TilePosition[tap].z==0){valid=false;continue;}
if(any(abs((previousN-n)-(previous-p))>2)){valid=false;continue;}
- float4 inputN=Base[n],old=Bilinear(PreviousGuide,previousN);
- float3 residualN=Raw[n].rgb-inputN.rgb;
- if(!all(isfinite(inputN))||!all(isfinite(old))||old.a<.999||!all(isfinite(residualN))){valid=false;continue;}
- float3 delta=abs(Guide(inputN.rgb)-old.rgb);float e=max(delta.r,max(delta.g,delta.b));error+=e/9;maximumError=max(maximumError,e);lo=min(lo,residualN);hi=max(hi,residualN);
+ float3 residualN=TileResidual[tap].rgb;
+ if(TileResidual[tap].a==0){valid=false;continue;}
+ float e=TileError[tap];error+=e/9;maximumError=max(maximumError,e);lo=min(lo,residualN);hi=max(hi,residualN);
}
float q=(1-smoothstep(.008,.04,error))*(1-smoothstep(.025,.10,maximumError));
if(valid&&q>0){float4 old=Bilinear(History,previous);if(all(isfinite(old))&&old.a>=.999){float3 margin=.02+q*abs(old.rgb);result=lerp(current,clamp(old.rgb,lo-margin,hi+margin),HistoryWeight*q);}}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 72eaa66e..27010bcb 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1845,7 +1845,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
for(size_t i=0;i<4;++i){const auto q=desc_.protection.regions[i];c[8+i*4]=q.left;c[9+i*4]=q.top;c[10+i*4]=q.right;c[11+i*4]=q.bottom;}
residualPass_.bind(list,c,gpuHandleOf(residualPass_,0).ptr,gpuHandleOf(residualPass_,3).ptr);
list->Dispatch(((desc_.nrBeforeSr?srcW_:workW_)+15)/16,((desc_.nrBeforeSr?srcH_:workH_)+15)/16,1);tracker_.uavBarrier(list,raw);tracker_.transition(list,raw,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
- if(desc_.nrTemporal)nrTemporal_.run(list,tracker_,reset,haveFlow,ptsMs-prevPtsMs_);
+ if(desc_.nrTemporal)nrTemporal_.run(list,tracker_,reset,haveFlow,ptsMs-prevPtsMs_,r.total,desc_.protection);
gpuTimer_.mark(list,GpuStage::Residual,true);
}
diff --git a/src/pipeline/NrTemporalPass.cpp b/src/pipeline/NrTemporalPass.cpp
index d49ee671..68a2e04c 100644
--- a/src/pipeline/NrTemporalPass.cpp
+++ b/src/pipeline/NrTemporalPass.cpp
@@ -9,7 +9,7 @@ bool NrTemporalPass::initialize(ID3D12Device* device,ID3D12Resource* base,ID3D12
auto desc=base->GetDesc();width_=unsigned(desc.Width);height_=desc.Height;
raw_=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
for(unsigned i=0;i<2;++i){history_[i]=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);guide_[i]=makeTexture(device,width_,height_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);if(!history_[i]||!guide_[i])return false;}
- std::vector<uint8_t> shader;if(!raw_||!pass_.loadShader("NrTemporal.dxil",shader)||!pass_.create(device,shader,16,5,3,8))return false;
+ std::vector<uint8_t> shader;if(!raw_||!pass_.loadShader("NrTemporal.dxil",shader)||!pass_.create(device,shader,16,5,3,24))return false;
DescriptorStager staging;if(!staging.initialize(device,10))return false;
for(unsigned i=0;i<2;++i){
ID3D12Resource* sources[]={base,raw_.Get(),history_[1-i].Get(),guide_[1-i].Get(),motion};
@@ -19,8 +19,10 @@ bool NrTemporalPass::initialize(ID3D12Device* device,ID3D12Resource* base,ID3D12
makeUav(device,guide_[i].Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpuHandleOf(pass_,i*8+7));
}return true;
}
-void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,bool reset,bool haveMotion,double frameMs){
- const auto i=index_;const bool useHistory=valid_&&!reset&&haveMotion;
+void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,bool reset,bool haveMotion,double frameMs,
+ float total,const engine::ProtectionSettings& protection){
+ const auto i=index_;
+ const bool useHistory=valid_&&!reset&&haveMotion&&std::isfinite(frameMs)&&frameMs>0&&frameMs<=250;
tracker.transition(list,raw_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker.transition(list,base_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker.transition(list,motion_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
@@ -28,8 +30,9 @@ void NrTemporalPass::run(ID3D12GraphicsCommandList* list,StateTracker& tracker,b
tracker.transition(list,guide_[1-i].Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
for(auto* r:{output_,history_[i].Get(),guide_[i].Get()})tracker.transition(list,r,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
// 80 ms past-history EMA; no future frames or presentation holdback.
- const float weight=useHistory?float(std::exp(-std::clamp(frameMs,1.0,250.0)/80.0)):0.f;
- const float c[8]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),weight,0,0,0,0,0};
+ const float weight=useHistory?float(std::exp(-frameMs/80.0)):0.f;
+ float c[24]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),weight,total,protection.enabled?1.f:0.f,protection.featherPixels,0,0};
+ for(unsigned n=0;n<4;++n){const auto r=protection.regions[n];c[8+n*4]=r.left;c[9+n*4]=r.top;c[10+n*4]=r.right;c[11+n*4]=r.bottom;}
pass_.bind(list,c,gpuHandleOf(pass_,i*8).ptr,gpuHandleOf(pass_,i*8+5).ptr);
list->Dispatch((width_+7)/8,(height_+7)/8,1);
for(auto* r:{output_,history_[i].Get(),guide_[i].Get()}){tracker.uavBarrier(list,r);tracker.transition(list,r,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}
diff --git a/tests/integration/NrTemporalGpuTests.cpp b/tests/integration/NrTemporalGpuTests.cpp
new file mode 100644
index 00000000..cd27fcbb
--- /dev/null
+++ b/tests/integration/NrTemporalGpuTests.cpp
@@ -0,0 +1,109 @@
+#include "veyra/pipeline/NrTemporalPass.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include <DirectXPackedVector.h>
+#include <cmath>
+#include <iostream>
+#include <limits>
+#include <d3d12sdklayers.h>
+
+int main() {
+ using namespace veyra;
+ using namespace pipeline;
+ using namespace DirectX::PackedVector;
+ gfx::D3D12DeviceContext ctx;
+ gfx::CommandSlotRing ring;
+ Status status=Status::Ok;
+ gfx::DeviceContextDesc desc;
+ desc.enableDebugLayer=true;
+ if(!ctx.initialize(desc,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
+ constexpr unsigned width=17,height=13,pitch=256;
+ auto base=makeTexture(ctx.device(),width,height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
+ auto motion=makeTexture(ctx.device(),width,height,DXGI_FORMAT_R16G16_FLOAT,true);
+ auto output=makeTexture(ctx.device(),width,height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
+ auto upload=makeUploadBuffer(ctx.device(),pitch*height);
+ NrTemporalPass pass;
+ if(!upload||!pass.initialize(ctx.device(),base.Get(),motion.Get(),output.Get()))return 2;
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=pitch*height;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ ComPtr<ID3D12Resource> readback;
+ if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback))))return 2;
+ StateTracker states;
+ bool patterned=false;
+ auto fill=[&](ID3D12Resource* texture,float value,bool flow=false){
+ void* data=nullptr;if(FAILED(upload->Map(0,nullptr,&data)))return false;
+ auto* pixels=static_cast<HALF*>(data);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x)for(unsigned c=0;c<(flow?2u:4u);++c)
+ pixels[y*pitch/2+x*(flow?2:4)+c]=XMConvertFloatToHalf(c==3?1.f:value+(patterned&&!flow?float((x*13+y*7+c*3)%19)*.013f:0.f));
+ upload->Unmap(0,nullptr);
+ unsigned slot;auto* list=ring.acquireNext(slot,status);if(!list)return false;
+ states.transition(list,texture,D3D12_RESOURCE_STATE_COPY_DEST);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=texture;dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource=upload.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ src.PlacedFootprint.Footprint={flow?DXGI_FORMAT_R16G16_FLOAT:DXGI_FORMAT_R16G16B16A16_FLOAT,width,height,1,pitch};
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ return ring.submitAndSignal(slot)&&ring.waitIdle();
+ };
+ engine::ProtectionSettings protection;
+ auto run=[&](float raw,bool reset,double ms=16.6667,bool haveMotion=true,float total=1.f){
+ if(!fill(pass.raw(),raw))return std::numeric_limits<float>::quiet_NaN();
+ unsigned slot;auto* list=ring.acquireNext(slot,status);
+ pass.run(list,states,reset,haveMotion,ms,total,protection);
+ states.transition(list,output.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);
+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};src.pResource=output.Get();src.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;dst.pResource=readback.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;dst.PlacedFootprint.Footprint={DXGI_FORMAT_R16G16B16A16_FLOAT,width,height,1,pitch};
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return std::numeric_limits<float>::quiet_NaN();
+ void* data=nullptr;D3D12_RANGE range{0,pitch*height};readback->Map(0,&range,&data);
+ float result=XMConvertHalfToFloat(static_cast<HALF*>(data)[6*pitch/2+8*4]);
+ uint64_t fingerprint=14695981039346656037ull;
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width*4;++x){
+ fingerprint^=static_cast<HALF*>(data)[y*pitch/2+x];fingerprint*=1099511628211ull;
+ }
+ std::cout<<"frame fingerprint="<<fingerprint<<std::endl;
+ D3D12_RANGE empty{0,0};readback->Unmap(0,&empty);return result;
+ };
+ bool ok=fill(base.Get(),.5f)&&fill(motion.Get(),0,true);
+ auto check=[&](const char* name,bool success){std::cout<<name<<"="<<success<<std::endl;ok&=success;};
+ check("reset identity",run(.75f,true)==.75f);
+ check("constant residual",run(.75f,false)==.75f);
+ const float decay=run(.5f,false);
+ check("zero residual decays",decay>.5f&&decay<.75f);
+ check("no motion bypass",run(.5f,false,16,false)==.5f);
+ for(double ms:{0.,-1.,251.,std::numeric_limits<double>::quiet_NaN()}){
+ run(.75f,true);check("invalid interval bypass",run(.5f,false,ms)==.5f);
+ }
+ run(.75f,true);check("zero total bypass",run(.5f,false,16,true,0)==.5f);
+ protection.enabled=true;protection.regions[0]={.3f,.3f,.7f,.7f};
+ run(.75f,true);check("protected identity",run(.5f,false)==.5f);
+ protection.enabled=false;
+ check("protected history excluded",run(.5f,false)==.5f);
+ protection.enabled=true;protection.regions[0]={.45f,.3f,.8f,.7f};protection.featherPixels=4;
+ run(.75f,true);check("feather identity",run(.5f,false)==.5f);
+ protection.enabled=false;
+ run(.75f,true);fill(base.Get(),.1f);
+ check("changed guide rejects",std::abs(run(.1f,false)-.1f)<.001f);
+ fill(base.Get(),.5f);
+ run(.75f,true);fill(motion.Get(),100,true);
+ check("out of bounds motion bypass",run(.5f,false)==.5f);
+ fill(motion.Get(),0,true);fill(base.Get(),-.5f);
+ check("signed HDR identity",run(-1.f,true)==-1.f);
+ fill(base.Get(),2.f);check("HDR highlight identity",run(3.f,true)==3.f);
+ // Full-frame fingerprints include odd-size tile boundaries, fractional flow,
+ // changing signed corrections and a mid-sequence reset for shader A/B runs.
+ patterned=true;fill(base.Get(),.25f);fill(motion.Get(),.125f,true);
+ for(unsigned frame=0;frame<16;++frame){
+ const float value=.25f+float(int(frame%5)-2)*.04f;
+ check("patterned finite",std::isfinite(run(value,frame==0||frame==9)));
+ }
+ ring.drainQueue();
+ ComPtr<ID3D12InfoQueue> info;
+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info))))return 2;
+ unsigned errors=0;
+ for(UINT64 i=0;i<info->GetNumStoredMessages();++i){
+ SIZE_T size=0;if(FAILED(info->GetMessage(i,nullptr,&size)))return 2;
+ std::vector<uint8_t> bytes(size);auto* message=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());
+ if(FAILED(info->GetMessage(i,message,&size)))return 2;
+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<message->pDescription<<std::endl;}
+ }
+ check("debug layer clean",errors==0);
+ return ok?0:1;
+}