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: trial one-downsample NR chains with independent residual controls

Veyra Goal Agentbd4c2efd0274
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9579d362..47526bd9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1052,6 +1052,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_features(veyra_nr_queue_migration_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_queue_migration_experiment PRIVATE /utf-8)
target_link_libraries(veyra_nr_queue_migration_experiment PRIVATE veyra_engine)
+ add_executable(veyra_nr_low_chain_experiment tests/perf/NrLowChainExperiment.cpp)
+ target_compile_features(veyra_nr_low_chain_experiment PRIVATE cxx_std_20)
+ target_compile_options(veyra_nr_low_chain_experiment PRIVATE /utf-8)
+ target_link_libraries(veyra_nr_low_chain_experiment PRIVATE veyra_engine)
target_compile_features(veyra_nr_recent_cache_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_recent_cache_experiment PRIVATE /utf-8)
target_link_libraries(veyra_nr_recent_cache_experiment PRIVATE veyra_engine bcrypt)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 708ed2e6..42b80579 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -711,3 +711,20 @@ Hardware inference, image quality and stability remain unverified on RX 9000.
# Performance experiments (2026-10-04)
`tests/perf/DuplicateFrameCS.hlsl` adapts `src/Magpie.Core/shaders/DuplicateFrameCS.hlsl` from [SAOG0721/Magpie](https://github.com/SAOG0721/Magpie/tree/27c5df91177a29b33be612e98274169f3d2fca49), fixed commit `27c5df91177a29b33be612e98274169f3d2fca49` / `v0.6.9-experimental`, GPL-3.0. Original shader SHA256 `39fe0acfcf499083c1380aa4a5dc0ad8e0b6632537efda61342e068d9eac2275` matches the local research copy byte-for-byte. Adaptations retain group reduction and atomic publication, replace sampler Gather with four bounded texture loads for D3D12/odd extents, add typed textures and provenance. This is an isolated measurement fixture; no production duplicate-skip behavior is implied.
+### NR low-resolution chain candidate (2026-10-05)
+
+The chain topology in `src/pipeline/EnhanceGraph.cpp` adapts
+`DLSSNRFilter::InitializeChain` in `src/Magpie.Core/DLSSNRFilter.cpp` and
+`src/Magpie.Core/DLSSNRMultiPass.h` from
+[SAOG0721/Magpie](https://github.com/SAOG0721/Magpie/tree/27c5df91177a29b33be612e98274169f3d2fca49),
+fixed commit `27c5df91177a29b33be612e98274169f3d2fca49`, GPL-3.0.
+The exact upstream files have SHA256 `46c75e125e172c1c0bffc811a7bb9e9cbb8ebeb6627dd80cafaa7ca374937712`
+and `98df10cc69fc0224ea5383aac343f7ab227577eb3e1907da09c1d5a8e5133982`;
+the repository license is GPL-3.0, compatible with Veyra's GPL-3.0 license.
+Adaptations use the existing D3D12 ring/state tracker/parity encode/Feature-18
+instances, downsample once, borrow each previous low-resolution result, preserve
+Veyra's five independent residual controls per layer, and lift the final residual
+once with the existing bilateral composite and full-resolution protection mask.
+Upstream's D3D11 interop, one shared residual group and single-list Evaluate
+batching are not copied. Initially test-only and off by default; this attribution
+does not imply identical image quality or completion of product acceptance.
diff --git a/docs/PERF_4A_LOW_CHAIN_2026-10-05.md b/docs/PERF_4A_LOW_CHAIN_2026-10-05.md
new file mode 100644
index 00000000..c8136531
--- /dev/null
+++ b/docs/PERF_4A_LOW_CHAIN_2026-10-05.md
@@ -0,0 +1,9 @@
+# 4a 多层NR低分辨率整链候选
+
+before cefbaec / checkpoint/perf-nr-4a-low-chain-before-20261004。固定上游SAOG0721/Magpie 27c5df91177a29b33be612e98274169f3d2fca49 / v0.6.9-experimental,GPL-3.0;确切cpp/header/license及URL/SHA收据E:/项目/Veyra/deps/saog-magpie-research-20261003/4a-27c5df91177a29b33be612e98274169f3d2fca49-receipt.json。源码注释与THIRD_PARTY_NOTICES逐项标注。
+
+按本次授权选择“保留每层独立残差参数”:仅2/3层同内部尺寸、非时域SDR列表图,第一层从原图降到L0;每层在低尺寸应用自身total/darken/brighten/color/luminance,下一层借用该低尺寸结果;出口一次LN-L0双边升采样叠回原全尺寸底图,完整全尺寸保护区域保留。现有单层、异尺寸、节点/交错、NR前于SR、时域/HDR/AMD保持原路径,不移除已支持参数。
+
+初始入口仅隔离测试ENV VEYRA_TEST_NR_LOW_CHAIN,默认不启用,尚无生产UI。不会以需要不同画面的多层链替换单层路径。特性创建/历史依旧每层独立,保留fresh-list约束,不照搬上游一次list批量Evaluate。内存预算检查保持保守,不做显存压力。
+
+先构建,再测:单层与不兼容组合逐帧SHA相同、真实多层debug/PTS/层次数及效果不隐失,独立残差改动可达;正常Qt2/3层A/B/B-off交错测总增强与Residual,不仅最后NR字段。多层完整图片PSNR/差异与可审查对照图保留,未经人工画质确认不默认打开。没有收益、正确性失败或不可接受画面时回退并保留失败证据。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 4e924de2..ed2166ee 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -8277,3 +8277,6 @@ before 6bc2a33 / checkpoint/perf-nr-3c-queue-admission-before-20261004。Preview
# 2026-10-05 3c限定准入保留
native nr-queue-migration.py B2d B3c-migration-v1九组通过,1278完整输出/PTS一致,自动每进程四次往返、fence递增,debug/移除0,创建失败注入返回DIRECT保持效果。Qt真实FSR3.1、XeSS、VFG、调色、时域NR往返/停止均通过:E:/项目/Veyra/logs/perf-nr-20261004/B3c-queue-ui-v3-fsr3/phase-review.json、v4-xess/result.json、v5-vfg/result.json。脚本枚举、过早断言及固定队列次数误判均保留原失败收据并按实际稳定阶段修正;v1退出后脚本继续改设置触发退出崩溃列R0,不能宣称已修复。详PERF_3C_GRAPH_NORMAL_2026-10-05。限定本机已测文件组合保留自动COMPUTE约8%收益,HIGH不默认,R0及其他组合验证待;无压力/用户配置/主线修改。
+# 2026-10-05 4a低分辨率链候选构建
+
+before cefbaec / checkpoint/perf-nr-4a-low-chain-before-20261004。按固定SAOG27c5df9/GPL3拓扑移植,明确保留每层五项残差控制,仅2/3层同尺寸非时域SDR列表图,L0一次降采样、LN-L0一次全尺寸叠回/保护;fresh-list、NVOF单位、单层及其他拓扑保持。默认关闭且只测试ENV入口,源码/THIRD_PARTY_NOTICES注明来源及改动,方案PERF_4A_LOW_CHAIN_2026-10-05。build-low-chain-v1/v2通过(UI+native),E:/项目/Veyra/logs/perf-nr-20261004;将执行10组合各off/on共800全图及独立控制/回退验证,再普通Qt计时。没有创建竞争/显存压力,未标画质或性能通过。
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 4183e85a..70fcd743 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -563,6 +563,7 @@ public:
ID3D12Resource* diagnosticVideoSrOutput() const { return videoSrOutput_.Get(); }
ID3D12Resource* diagnosticNrLayerInput(size_t index) const { return index < nrInstances_.size() ? nrInstances_[index]->input() : nullptr; }
ID3D12Resource* diagnosticNrLayerOutput(size_t index) const { return index < nrInstances_.size() ? nrInstances_[index]->fullTarget() : nullptr; }
+ bool diagnosticLowResolutionNrChain()const{return lowResolutionNrChain_;}
engine::NrLayerSettings diagnosticNrLayerSettings(size_t index) const {
if(index>=nrInstances_.size())return {};
const auto& n=*nrInstances_[index];
@@ -663,6 +664,7 @@ private:
// tools/nr_probe verified several handles coexist on one snippet session.
std::vector<std::unique_ptr<NrInstance>> nrInstances_;
bool lmxxfNr_ = false;
+ bool lowResolutionNrChain_=false; // isolated 4a candidate; single-layer path unchanged
bool submitGraph(uint32_t slot);
// The layer count the current graph was built with, so a settings change
// that adds or removes a layer is detected as a rebuild.
diff --git a/scripts/perf/nr-low-chain.py b/scripts/perf/nr-low-chain.py
new file mode 100644
index 00000000..b8d5d3f4
--- /dev/null
+++ b/scripts/perf/nr-low-chain.py
@@ -0,0 +1,37 @@
+"""Ordinary source, full-output pixels/control/fallback proof; timing is separate."""
+from pathlib import Path
+import csv,importlib.util,json,os,re,shutil,subprocess,sys,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];groups=sys.argv[3:] or ['single','single-sr','2','3','2-sr','3-sr','mixed','temporal','protected','edits']
+matrix.assert_gpu_tests_idle();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_nr_low_chain_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe);results=[]
+for group in groups:
+ for mode in ('off','on'):
+ matrix.assert_gpu_tests_idle();name=f'{label}-{group}-{mode}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
+ for path in (out,tmp):path.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 mode=='on':env['VEYRA_TEST_NR_LOW_CHAIN']='1'
+ command=[str(exe),str(matrix.SOURCES['M1']),str(out),group];print('START',name,flush=True);start=time.monotonic()
+ with (out/'console.log').open('xb') as stream:
+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=250).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace');line=next((s for s in text.splitlines() if s.startswith('LOW_CHAIN_RESULT ')),'')
+ metrics={k:int(v) for k,v in re.findall(r'(\w+)=(-?\d+)',line)};rows=list(csv.DictReader((out/'frames.csv').open())) if (out/'frames.csv').exists() else []
+ result={'name':name,'group':group,'mode':mode,'command':command,'exitCode':rc,'metrics':metrics,'frames':rows,'wallSeconds':time.monotonic()-start,
+ 'exeSha256':matrix.digest(exe),'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),'sourceSha256':matrix.digest(matrix.SOURCES['M1']),
+ 'passed':rc==0 and metrics.get('pass')==1 and metrics.get('debugErrors')==0,'measurement':'40 full frames with PNG/readback; image/control correctness only; no timing claim or GPU competition'}
+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');results.append(result);print('RESULT',name,result['passed'],metrics,flush=True)
+ (BASE/'logs'/TASK/(label+'-completed.json')).write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8')
+ if not result['passed']:print(text[-6500:],flush=True);raise SystemExit(1)
+comparisons=[]
+for group in groups:
+ off,on=[r for r in results if r['group']==group];row={'group':group,'equalCount':len(off['frames'])==len(on['frames']),'differentRows':sum(a!=b for a,b in zip(off['frames'],on['frames'])),'active':on['metrics']['active']}
+ if not row['active']:assert row['equalCount'] and row['differentRows']==0,row
+ comparisons.append(row)
+(BASE/'logs'/TASK/(label+'-summary.json')).write_text(json.dumps({'results':results,'comparisons':comparisons},ensure_ascii=False,indent=2),encoding='utf-8')
+print('LOW_CHAIN_COMPLETE',comparisons,flush=True)
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index fb180056..c279ef51 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -443,6 +443,20 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
if(context_.adapter().vendorId==0x1002 && desc_.opticalFlowBackend==engine::OpticalFlowBackend::Nvidia)
desc_.opticalFlowBackend=engine::OpticalFlowBackend::AmdFidelityFx;
nrEnabled_ = desc.enableNr && !desc.noFeatures && (!desc.noNgx || lmxxfNr_);
+ // Adapted chain topology from SAOG0721/Magpie, GPL-3.0,
+ // 27c5df91177a29b33be612e98274169f3d2fca49 / DLSSNRFilter::InitializeChain.
+ // Veyra keeps independent residual controls at EACH low-resolution layer,
+ // then lifts LN-L0 once. Upstream applies one shared residual group instead.
+ // Mixed sizes, temporal/Node/HDR/AMD and single NR retain the existing path.
+ lowResolutionNrChain_=GetEnvironmentVariableW(L"VEYRA_TEST_NR_LOW_CHAIN",nullptr,0)&&nrEnabled_&&!lmxxfNr_&&
+ (nrLayerCount_==2||nrLayerCount_==3)&&!desc_.runtimeNodeOrder&&!desc_.nrBeforeSr&&!desc_.hdrInput&&!desc_.hdrOutput&&
+ !desc_.videoHdr.enabled&&!desc_.color.enabled&&!desc_.additionalColorCount&&!desc_.nrTemporal&&!desc_.nrHoldStrength&&
+ std::none_of(desc_.nrLayersTemporal.begin(),desc_.nrLayersTemporal.end(),[](bool enabled){return enabled;})&&
+ std::all_of(desc_.nrLayersExtent.begin(),desc_.nrLayersExtent.end(),[&](Extent extent){return extent==desc_.nrLayersExtent.front();})&&
+ desc_.nrLayersExtent.front().width>=64&&desc_.nrLayersExtent.front().height>=64&&
+ desc_.nrLayersExtent.front()!=desc_.nrFullExtent(0);
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_NR_LOW_CHAIN",nullptr,0))
+ log::info("nr-chain",std::format("lowResolution={} layers={} internal={}x{} output={}x{} perLayerResidual=true",lowResolutionNrChain_,nrLayerCount_,nrW_,nrH_,workW_,workH_));
fgEnabled_ = desc.enableFg && !desc.noFeatures && !desc.stillImage &&
desc.frameGenerationBackend != engine::FrameGenerationBackend::XeSS &&
(!desc.noNgx || engine::fsrFrameGeneration(desc.frameGenerationBackend)||desc.frameGenerationBackend==engine::FrameGenerationBackend::Vfg);
@@ -1234,13 +1248,14 @@ bool EnhanceGraph::initNgxFeatures()
for (size_t index = 0; index < layers; ++index) {
auto instance = std::make_unique<NrInstance>();
const auto extent=desc_.nrLayersExtent[index];
- const auto full=desc_.nrFullExtent(index);
+ const auto full=lowResolutionNrChain_?extent:desc_.nrFullExtent(index);
const uint32_t fullW=full.width,fullH=full.height;
// Only a single layer may alias the graph's stage input, and only
// when the extents already match: that is what the original graph
// did, and the path has to stay byte-identical. Extra layers read
// the previous layer's output, which the downsample produces.
ID3D12Resource* borrowed = nullptr;
+ if(lowResolutionNrChain_&&index)borrowed=nrInstances_.back()->outputFull();
if (layers == 1) {
const bool sameExtent = extent.width==fullW&&extent.height==fullH;
if (sameExtent) borrowed = nrBaseInput();
@@ -1586,7 +1601,7 @@ bool EnhanceGraph::createViews()
const UINT k=UINT(layerIndex);
// The shader reads base (t0), the NR-extent input (t1) and the neural
// result (t2); the heap keeps those three per layer, in order.
- ID3D12Resource* base=nrLayerBase(layerIndex);
+ ID3D12Resource* base=lowResolutionNrChain_&&layerIndex==0?nrInstances_[0]->input():nrLayerBase(layerIndex);
stagedSrv(base,DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,3*k+0);
stagedSrv(nrInstances_[layerIndex]->input(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,3*k+1);
stagedSrv(nrInstances_[layerIndex]->finalRgba(),DXGI_FORMAT_R16G16B16A16_FLOAT,residualPass_,3*k+2);
@@ -1625,7 +1640,7 @@ bool EnhanceGraph::createViews()
if(nrInstances_.size()>1){
auto* original=nrBaseInput();
stagedSrv(original,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,0);
- stagedSrv(original,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,1);
+ stagedSrv(lowResolutionNrChain_?nrInstances_[0]->input():original,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,1);
auto* protectedInput=interNrProtectionRgba_?nrInstances_[desc_.interNrProtectionTarget()-1]->fullTarget():
(preSrProtectionRgba_?nrInstances_[desc_.nrBeforeSrLayerCount()-1]->fullTarget():nrInstances_.back()->fullTarget());
stagedSrv(protectedInput,DXGI_FORMAT_R16G16B16A16_FLOAT,stackProtectionPass_,2);
@@ -2464,7 +2479,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(!runBoundaryColor(true)||!runSr()||!runBoundaryColor(false))return false;
}
auto* layer = nrInstances_[layerIndex].get();
- const uint32_t sourceW=layer->fullWidth(),sourceH=layer->fullHeight();
+ const auto sourceExtent=lowResolutionNrChain_&&layerIndex==0?desc_.nrFullExtent(0):Extent{layer->fullWidth(),layer->fullHeight()};
+ const uint32_t sourceW=sourceExtent.width,sourceH=sourceExtent.height;
if ((layer->handle() == nullptr && !layer->amd) || !layer->enabled) continue;
if(interNrColorActiveCount_){
const auto& plan=*desc_.fixedExecutionPlan;
@@ -2634,7 +2650,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(!nrInstances_.empty())compositeNrLayer(nrInstances_.size()-1);
if(nrInstances_.size()>1){
auto* final=nrInstances_.back()->fullTarget();
- if(desc_.protection.enabled&&!preSrProtectionRgba_&&!interNrProtectionRgba_){
+ if(lowResolutionNrChain_||(desc_.protection.enabled&&!preSrProtectionRgba_&&!interNrProtectionRgba_)){
auto* original=nrBaseInput();
tracker_.transition(list,original,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list,final,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
@@ -2642,7 +2658,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// Each layer already applies its own SDR/HDR residual policy.
// This final exclusion mask must preserve the stack's signed
// temporal output, including pixels outside protected regions.
- float c[24]={1,1,1,1,1,1,desc_.protection.featherPixels,1.f};
+ float c[24]={1,1,1,1,1,desc_.protection.enabled?1.f:0.f,desc_.protection.featherPixels,1.f};
for(size_t i=0;i<4;++i){const auto q=engine::protectionConstants(desc_.protection.regions[i]);c[8+i*4]=q[0];c[9+i*4]=q[1];c[10+i*4]=q[2];c[11+i*4]=q[3];}
stackProtectionPass_.bind(list,c,gpuHandleOf(stackProtectionPass_,0).ptr,gpuHandleOf(stackProtectionPass_,3).ptr);
list->Dispatch(((desc_.nrBeforeSr?srcW_:workW_)+15)/16,((desc_.nrBeforeSr?srcH_:workH_)+15)/16,1);
@@ -3117,6 +3133,7 @@ ID3D12Resource* EnhanceGraph::generatedFrameResource(uint32_t slot) const
// ---------------------------------------------------------------------------
void EnhanceGraph::shutdown()
{
+ lowResolutionNrChain_=false;
pausedNrCacheValid_=pausedNrResidualOnly_=false;pausedNrFrame_=nullptr;
lastAppliedSettings_.reset();pausedNrSettings_.reset();
if (!initialized_ && !coreHost_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
diff --git a/tests/perf/NrLowChainExperiment.cpp b/tests/perf/NrLowChainExperiment.cpp
new file mode 100644
index 00000000..7314833a
--- /dev/null
+++ b/tests/perf/NrLowChainExperiment.cpp
@@ -0,0 +1,53 @@
+#include "veyra/engine/PreviewGpuSession.h"
+#include "veyra/engine/GraphDescription.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/FileIdentity.h"
+#include <d3d12sdklayers.h>
+#include <fstream>
+#include <iostream>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;if(argc!=4)return 2;const std::wstring group=argv[3];
+ const bool sr=group==L"2-sr"||group==L"3-sr"||group==L"single-sr";
+ const bool single=group==L"single"||group==L"single-sr",triple=group==L"3"||group==L"3-sr";
+ const bool mixed=group==L"mixed",temporal=group==L"temporal",protectedGroup=group==L"protected",edits=group==L"edits";
+ if(group!=L"2"&&!sr&&!single&&!triple&&!mixed&&!temporal&&!protectedGroup&&!edits)return 2;
+ const unsigned layers=single?1:triple?3:2;
+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);Logger::instance().openFile((out/L"engine.log").wstring());
+ Microsoft::WRL::ComPtr<ID3D12Debug> layer;if(FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&layer))))return 2;layer->EnableDebugLayer();
+ engine::EffectChain chain;chain.nodeCount=layers;
+ for(unsigned i=0;i<layers;++i){chain.nodes[i].type=engine::EffectType::NrEnhance;chain.nodes[i].enabled=true;
+ chain.nodes[i].nr.temporal=temporal;chain.nodes[i].nr.sizePolicy=sr?pipeline::NrSizePolicy::Realtime:
+ mixed&&i==0?pipeline::NrSizePolicy::P480:pipeline::NrSizePolicy::P720;}
+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.sr=sr;settings.videoSrQuality=0;
+ settings.srTarget=pipeline::SrTarget::Uhd4K;settings.multiplier=1;
+ if(protectedGroup){settings.protection.enabled=true;settings.protection.featherPixels=4;settings.protection.regions[0]={.2f,.2f,.8f,.8f,false};}
+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=true;request.sr=sr;
+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ engine::PreviewGpuSession session;if(!session.initialize()||!session.graph->initialize(desc)||!session.graph->createViews())return 2;
+ const bool requested=GetEnvironmentVariableW(L"VEYRA_TEST_NR_LOW_CHAIN",nullptr,0)>0,active=session.graph->diagnosticLowResolutionNrChain();
+ bool pass=active==(requested&&!single&&!mixed&&!temporal)&&session.graph->nrLayerCount()==layers;
+ for(unsigned i=0;i<layers&&pass;++i){const auto shape=session.graph->diagnosticNrLayerOutput(i)->GetDesc();const auto expected=active?desc.nrLayersExtent[i]:desc.nrFullExtent(i);pass=shape.Width==expected.width&&shape.Height==expected.height;}
+ source::MediaFileSource media;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;if(!media.open(open))return 2;
+ std::ofstream frames(out/L"frames.csv");frames<<"frame,pts100ns,width,height,sha256,nrDelta\n";unsigned completed=0;
+ for(unsigned i=0;i<40&&pass;++i){
+ if(edits&&(i==10||i==20||i==30)){
+ const unsigned edited=i==20?1:0;auto& r=settings.nrLayers[edited].residual;r.total=i==30?1.f:.4f;r.color=i==30?1.f:.3f;r.darken=i==30?1.f:1.3f;
+ pass=session.graph->applySettings(settings)&&session.graph->diagnosticNrLayerSettings(edited).residual==r;
+ }
+ pipeline::FramePacket packet;const AVFrame* input=nullptr;pipeline::EnhanceGraph::FrameOutputs output;const auto before=session.graph->metrics().nrEvaluateCount;
+ pass=pass&&media.read(packet,&input)==source::SourceReadStatus::Frame&&session.graph->process(input,packet.pts.toDouble()*1000,i==0,output,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle();
+ sink::RgbaImage image;if(pass)pass=sink::readRgba8(session.context,session.ring,session.graph->videoFrameResource(output.videoSlot),image);
+ const auto delta=session.graph->metrics().nrEvaluateCount-before;pass=pass&&delta==layers;
+ if(pass){frames<<i<<','<<int64_t(packet.pts.toDouble()*10000000)<<','<<image.width<<','<<image.height<<','<<sha256Hex(image.pixels.data(),image.pixels.size())<<','<<delta<<'\n';frames.flush();
+ pass=sink::saveImage((out/(L"frame-"+std::to_wstring(i)+L".png")).wstring(),image);if(pass)++completed;}
+ }
+ media.close();session.ring.drainQueue();session.graph->shutdown();pass=session.core.close("low-chain-test")&&pass;
+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;if(FAILED(session.context.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;
+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T n=0;debug->GetMessage(i,nullptr,&n);std::vector<unsigned char> bytes(n);auto* m=reinterpret_cast<D3D12_MESSAGE*>(bytes.data());
+ if(FAILED(debug->GetMessage(i,m,&n)))return 2;if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<"DEBUG_ERROR "<<m->pDescription<<std::endl;}}
+ const auto removed=session.context.device()->GetDeviceRemovedReason();pass=pass&&completed==40&&errors==0&&SUCCEEDED(removed);debug.Reset();session.shutdown();
+ std::cout<<"LOW_CHAIN_RESULT pass="<<pass<<" frames="<<completed<<" layers="<<layers<<" requested="<<requested<<" active="<<active<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;return pass?0:1;
+}