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(experiment): prebuild actual NR sizes on one bounded snippet session
Veyra Goal Agent81ad31e1098a
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e6743fed..7c49d1e0 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1052,6 +1052,13 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_compile_features(veyra_nr_mixed_resolution_experiment PRIVATE cxx_std_20)target_compile_options(veyra_nr_mixed_resolution_experiment PRIVATE /utf-8)target_link_libraries(veyra_nr_mixed_resolution_experiment PRIVATE veyra_engine)+ add_executable(veyra_nr_auto_controller_tests tests/perf/AutoNrControllerTests.cpp)+ target_compile_features(veyra_nr_auto_controller_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_nr_auto_controller_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ add_executable(veyra_nr_auto_pool_experiment tests/perf/NrAutoPoolExperiment.cpp)+ target_compile_features(veyra_nr_auto_pool_experiment PRIVATE cxx_std_20)+ target_compile_options(veyra_nr_auto_pool_experiment PRIVATE /utf-8)+ target_link_libraries(veyra_nr_auto_pool_experiment PRIVATE veyra_engine)add_executable(veyra_nr_queue_migration_experiment tests/perf/NrQueueMigrationExperiment.cpp)target_compile_features(veyra_nr_queue_migration_experiment PRIVATE cxx_std_20)target_compile_options(veyra_nr_queue_migration_experiment PRIVATE /utf-8)diff --git a/include/veyra/engine/AutoNrController.h b/include/veyra/engine/AutoNrController.hnew file mode 100644index 00000000..2ed42e5a--- /dev/null+++ b/include/veyra/engine/AutoNrController.h@@ -0,0 +1,37 @@+#pragma once+#include <cmath>+#include <cstdint>+#include <deque>+#include <optional>++namespace veyra::engine {+// Transport-frame budget, completed enhancement P95. No content-rate guesses.+// History resets discard observations, while a one-minute switch cap persists+// until the source/settings session itself changes.+class AutoNrController {+public:+ void reset(int64_t now100ns) {level_=0;switches_.clear();lowSince_.reset();next_=now100ns+5000000;lastSwitch_=now100ns-30000000;}+ std::optional<unsigned> observe(int64_t now100ns,std::optional<double> p95Ms,uint64_t samples,double budgetMs) {+ if(now100ns<next_)return {};+ next_=now100ns+5000000;+ while(!switches_.empty()&&now100ns-switches_.front()>=600000000)switches_.pop_front();+ if(!p95Ms||!std::isfinite(*p95Ms)||*p95Ms<=0||samples<8||!std::isfinite(budgetMs)||budgetMs<=0){lowSince_.reset();return {};}+ const bool over=*p95Ms>budgetMs,low=*p95Ms<budgetMs*.7;+ if(low){if(!lowSince_)lowSince_=now100ns;}else lowSince_.reset();+ if(switches_.size()>=4||now100ns-lastSwitch_<30000000)return {};+ if(over&&level_<4)++level_;+ else if(low&&level_>0&&lowSince_&&now100ns-*lowSince_>=30000000)--level_;+ else return {};+ switches_.push_back(now100ns);lastSwitch_=now100ns;lowSince_.reset();+ return level_;+ }+ void discardObservations(int64_t now100ns) {lowSince_.reset();next_=now100ns+10000000;}+ unsigned level()const{return level_;}+ static constexpr unsigned percent(unsigned level) {return level==0?100:level==1?85:level==2?70:level==3?55:40;}+private:+ unsigned level_=0;+ int64_t next_=0,lastSwitch_=0;+ std::optional<int64_t> lowSince_;+ std::deque<int64_t> switches_;+};+}diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 4183e85a..9b1a59ab 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -389,6 +389,9 @@ struct EnhanceGraphDesc {ID3D12Resource* srMotionProbe = nullptr;// Same borrowed diagnostic contract as srMotionProbe, for FG only.ID3D12Resource* fgMotionProbe = nullptr;+ // Isolated 3b experiment: one layer owns a bounded pool on this same+ // snippet session. Not set by any product entry point until proven.+ std::optional<uint32_t> nrAutoPoolLayer;};class EnhanceGraph {@@ -474,6 +477,9 @@ public:// Full-batch consumers (export/file accounting) still use resolveGeneration.bool resolveFrame(FrameOutputs& out,uint32_t index);bool applySettings(const engine::EnhancementSettings&);+ bool selectAutoNrLevel(unsigned level);+ bool autoNrPoolReady()const{return nrAutoPoolReady_;}+ unsigned autoNrLevel()const{return nrAutoLevel_;}// s10 ownership-order teardown: NVOF fence drain must happen BEFORE this// call (it needs the ring and out-fence alive). Releases features, NVOF@@ -662,6 +668,11 @@ private:// NR layers. One entry means the single-layer product path; the probe in// tools/nr_probe verified several handles coexist on one snippet session.std::vector<std::unique_ptr<NrInstance>> nrInstances_;+ std::array<std::unique_ptr<NrInstance>,5> nrAutoPool_;+ unsigned nrAutoLevel_=0;+ bool nrAutoPoolReady_=false,nrAutoResetPending_=false;+ bool createNrFeature(NrInstance& layer);+ bool createAutoNrPool();bool lmxxfNr_ = false;bool submitGraph(uint32_t slot);// The layer count the current graph was built with, so a settings changediff --git a/scripts/perf/nr-auto-pool-native.py b/scripts/perf/nr-auto-pool-native.pynew file mode 100644index 00000000..44a5dc45--- /dev/null+++ b/scripts/perf/nr-auto-pool-native.py@@ -0,0 +1,44 @@+"""Same-session actual-size NR pools versus fresh features, no extra load."""+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];repeats=int(sys.argv[3]) if len(sys.argv)>3 else 2;assert 1<=repeats<=3+matrix.assert_gpu_tests_idle();folder=BASE/'logs'/TASK/(label+'-summary');folder.mkdir(parents=True,exist_ok=False)+app=matrix.stage(variant,label);exe=app/'veyra_nr_auto_pool_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)+identity={p.relative_to(app).as_posix():matrix.digest(p) for p in app.rglob('*') if p.is_file() and p.suffix.lower() in ('.exe','.dll','.qml')}+(folder/'artifacts.json').write_text(json.dumps(identity,ensure_ascii=False,indent=2),encoding='utf-8')+results=[];tables={}+for count in (1,2):+ for repeat in range(1,repeats+1):+ for mode in ('reference','pool'):+ name=f'{label}-{count}-{mode}-r{repeat}';out=BASE/'tests'/TASK/name;out.mkdir(parents=True,exist_ok=False)+ tmp=BASE/'tmp'/TASK/name;tmp.mkdir(parents=True,exist_ok=False)+ env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_QUICK_BACKEND','QSG_RHI_BACKEND'))};env.update(TEMP=str(tmp),TMP=str(tmp),VEYRA_VERBOSE_FRAME_LOGS='1')+ matrix.assert_gpu_tests_idle();print('START',name,flush=True);start=time.monotonic()+ with (out/'console.log').open('x',encoding='utf-8') as stream:+ proc=subprocess.run([str(exe),str(matrix.SOURCES['M1']),str(out),mode,str(count)],cwd=app,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=250)+ console=(out/'console.log').read_text(encoding='utf-8',errors='replace');log=(out/'engine.log').read_text(encoding='utf-8',errors='replace')+ nativePass=proc.returncode==0 and f'NR_AUTO_POOL_RESULT pass=1 frames=90 layers={count} debugErrors=0 deviceRemoved=0' in console and '[ERROR]' not in log+ row={'name':name,'mode':mode,'layers':count,'repeat':repeat,'nativePassed':nativePass,'exitCode':proc.returncode,'wallSeconds':time.monotonic()-start,+ 'sourceSha256':matrix.digest(matrix.SOURCES['M1']),'exeSha256':matrix.digest(exe),'runtimeSha256':identity['runtime/experimental/nvngx_dlssnr.dll'],+ 'sourceCommit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD']).decode().strip(),+ 'poolEvents':[line for line in log.splitlines() if '[nr-auto-pool]' in line],+ 'explicitParameterDestruction':[line for line in log.splitlines() if 'NR parameter blocks explicitly destroyed=' in line]}+ (out/'receipt.json').write_text(json.dumps(row,ensure_ascii=False,indent=2),encoding='utf-8');results.append(row)+ (folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8');assert nativePass,row+ with (out/'frames.csv').open(encoding='utf-8') as stream:frames=list(csv.DictReader(stream))+ assert len(frames)==90 and [int(frames[i*15]['level']) for i in range(6)]==[0,1,2,3,4,0]+ assert all(int(frames[i*15]['historyReset'])==1 for i in range(6))+ # Save differences before asserting. A failed comparison remains evidence.+ key=(count,'reference',1)+ if mode=='reference' and repeat==1:tables[key]=frames+ different=[i for i,(a,b) in enumerate(zip(tables[key],frames)) if a!=b]+ row.update(referenceDifferentFrames=different,allFullFramePixelsCompared=True)+ (out/'receipt.json').write_text(json.dumps(row,ensure_ascii=False,indent=2),encoding='utf-8')+ (folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8')+ print('AUTO_POOL_NATIVE_RESULT',json.dumps(row,ensure_ascii=False),flush=True)+ assert not different,'Actual-size pool differs from independently-created same-size reference'+assert all(matrix.digest(app/name)==sha for name,sha in identity.items());matrix.assert_gpu_tests_idle()+(folder/'summary.json').write_text(json.dumps({'runs':results,'fullFrameCount':len(results)*90,'referenceDifferentFrames':0,'payloadUnchanged':True,'extraGpuLoad':False},ensure_ascii=False,indent=2),encoding='utf-8')+print('AUTO_POOL_NATIVE_COMPLETE',len(results),flush=True)diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex fb180056..1f0b9c95 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -1277,38 +1277,9 @@ bool EnhanceGraph::initNgxFeatures()// NR feature create (8.5 create parameter contract), one handle per layer.for (size_t layerIndex = 0; nrEnabled_ && !lmxxfNr_ && layerIndex < nrInstances_.size(); ++layerIndex) {auto* layer = nrInstances_[layerIndex].get();- const uint32_t nrW=layer->width(),nrH=layer->height();- namespace p = ngx::dlssnr;- ngx::ParameterBlock pb(ngxParams_);- pb.setU32(p::kWidth, nrW); pb.setU32(p::kHeight, nrH);- pb.setU32(p::kInputWidth, nrW); pb.setU32(p::kInputHeight, nrH);- pb.setU32(p::kOutputWidth, nrW); pb.setU32(p::kOutputHeight, nrH);- pb.setU32(p::kOutputDotWidth, nrW); pb.setU32(p::kOutputDotHeight, nrH);- pb.setU32(p::kUpscaling, 0);- pb.setF32(p::kScale, 1.0f); pb.setF32(p::kScalingRatio, 1.0f);- pb.setVoid(p::kComputeScalingRatioCallback,- reinterpret_cast<void*>(&ngx::DlssNrRuntimeAdapter::scalingRatioCallback));- pb.setI32(p::kHintRenderPreset, 0);- pb.setU32(p::kStdWidth, nrW); pb.setU32(p::kStdHeight, nrH);- pb.setI32(p::kPerfQualityValue, 1);- pb.setU32(p::kCreationNodeMask, 1); pb.setU32(p::kVisibilityNodeMask, 1);- ID3D12GraphicsCommandList* list = ring_.acquire(0, st);- if (list == nullptr) { failedBackend_=engine::FailedBackend::Infrastructure; return false; }- failedBackend_=engine::FailedBackend::Nr;- // One parameter block per layer: the block carries the feature's create- // contract, and Magpie's evidence is that each pass needs its own.- layer->setParameters(coreHost_->allocateParameters(st));- if (layer->parameters() == nullptr) return false;- NVSDK_NGX_Handle* created = nullptr;- if (!nrAdapter_->snippetCreateFeature(list, ngxParams_, &created, nrResult_, nrSeh_) ||- nrResult_ != static_cast<uint64_t>(NVSDK_NGX_Result_Success) || created == nullptr) {- veyra::log::error("graph", std::format("NR layer {} create failed 0x{:X}", layerIndex + 1, nrResult_));- return false;- }- layer->setHandle(created);- failedBackend_=engine::FailedBackend::Infrastructure;- if(!ring_.submitAndSignal(0)||!ring_.waitIdle())return false;+ if(!createNrFeature(*layer))return false;}+ if(desc_.nrAutoPoolLayer&&!createAutoNrPool())return false;if (srEnabled_ && !desc_.noFeatures && desc_.videoSrQuality!=engine::kVideoSrFsr) {ngx::DlssSrBackend::CreateDesc sd{};@@ -1397,6 +1368,89 @@ bool EnhanceGraph::initNgxFeatures()// into residualRgba_. Copying back is deliberate: every downstream reader// (SR, FG, tail colour, diagnostic views) keeps binding the same texture, so// enabling the stabiliser cannot silently mis-bind a consumer.+bool EnhanceGraph::createNrFeature(NrInstance& layer) {+ Status st=Status::Ok;const uint32_t nrW=layer.width(),nrH=layer.height();+ namespace p=ngx::dlssnr;ngx::ParameterBlock pb(ngxParams_);+ pb.setU32(p::kWidth,nrW);pb.setU32(p::kHeight,nrH);+ pb.setU32(p::kInputWidth,nrW);pb.setU32(p::kInputHeight,nrH);+ pb.setU32(p::kOutputWidth,nrW);pb.setU32(p::kOutputHeight,nrH);+ pb.setU32(p::kOutputDotWidth,nrW);pb.setU32(p::kOutputDotHeight,nrH);+ pb.setU32(p::kUpscaling,0);pb.setF32(p::kScale,1.0f);pb.setF32(p::kScalingRatio,1.0f);+ pb.setVoid(p::kComputeScalingRatioCallback,reinterpret_cast<void*>(&ngx::DlssNrRuntimeAdapter::scalingRatioCallback));+ pb.setI32(p::kHintRenderPreset,0);pb.setU32(p::kStdWidth,nrW);pb.setU32(p::kStdHeight,nrH);+ pb.setI32(p::kPerfQualityValue,1);pb.setU32(p::kCreationNodeMask,1);pb.setU32(p::kVisibilityNodeMask,1);+ auto* list=ring_.acquire(0,st);+ if(!list){failedBackend_=engine::FailedBackend::Infrastructure;return false;}+ failedBackend_=engine::FailedBackend::Nr;+ layer.setParameters(coreHost_->allocateParameters(st));if(!layer.parameters())return false;+ NVSDK_NGX_Handle* created=nullptr;+ if(!nrAdapter_->snippetCreateFeature(list,ngxParams_,&created,nrResult_,nrSeh_)||+ nrResult_!=uint64_t(NVSDK_NGX_Result_Success)||!created){+ log::error("graph",std::format("NR {}x{} create failed 0x{:X} seh={}",nrW,nrH,nrResult_,nrSeh_));return false;+ }+ layer.setHandle(created);failedBackend_=engine::FailedBackend::Infrastructure;+ return ring_.submitAndSignal(0)&&ring_.waitIdle();+}++bool EnhanceGraph::createAutoNrPool() {+ const auto index=*desc_.nrAutoPoolLayer;+ const bool admitted=nrEnabled_&&!srEnabled_&&!fgEnabled_&&!lmxxfNr_&&!desc_.hdrWorking()&&!desc_.stillImage&&+ !desc_.noFeatures&&!desc_.noNgx&&!desc_.runtimeNodeOrder&&!desc_.nrTemporal&&desc_.nrHoldStrength==0&&+ desc_.nrRuntime==engine::NrRuntime::Original&&desc_.opticalFlowBackend==engine::OpticalFlowBackend::Nvidia&&+ context_.adapter().deviceId==0x2f04&&context_.adapter().isNvidia&&index<nrInstances_.size()&&nrInstances_.size()+4<=8&&+ workW_==1920&&workH_==1080&&desc_.nrLayersExtent[index]==Extent{1920,1080}&&+ std::none_of(nrInstances_.begin(),nrInstances_.end(),[](const auto& layer){return layer->temporalEnabled;});+ if(!admitted){failedBackend_=engine::FailedBackend::Nr;log::error("nr-auto-pool","experimental admission refused; product entry points do not request this pool");return false;}+ uint64_t budget=0,usage=0;const auto start=std::chrono::steady_clock::now();+ const auto& initial=*nrInstances_[index];+ constexpr unsigned percents[5]={100,85,70,55,40};+ uint64_t extraTextureBytes=0;+ for(unsigned level=1;level<5;++level){const uint32_t w=(1920*percents[level]/100)&~1u,h=(1080*percents[level]/100)&~1u;+ extraTextureBytes+=uint64_t(w)*h*36+uint64_t(workW_)*workH_*8;}+ if(!context_.videoMemoryInfo(budget,usage)||budget<=usage||extraTextureBytes>(budget-usage)/2||usage+extraTextureBytes>=budget/3){+ failedBackend_=engine::FailedBackend::Nr;log::error("nr-auto-pool","insufficient measured headroom; refusing extra pool");return false;}+ const auto beforeUsage=usage;+ for(unsigned level=1;level<5;++level) {+ const uint32_t w=(1920*percents[level]/100)&~1u,h=(1080*percents[level]/100)&~1u;+ auto layer=std::make_unique<NrInstance>();+ if(!layer->create(context_.device(),w,h,workW_,workH_,nrZeroMotion_.Get(),nrZeroDepth_.Get()))return false;+ layer->model=initial.model;layer->residualSettings=initial.residualSettings;layer->protection=initial.protection;+ nrAutoPool_[level]=std::move(layer);if(!createNrFeature(*nrAutoPool_[level]))return false;+ if(!context_.videoMemoryInfo(budget,usage)||budget<=usage||usage>=budget/3){+ failedBackend_=engine::FailedBackend::Nr;log::error("nr-auto-pool","SDK pool exceeds conservative measured headroom; refusing activation");return false;}+ log::info("nr-auto-pool",std::format("event=created level={} internal={}x{} usageMiB={}",level,w,h,usage>>20));+ }+ nrAutoLevel_=0;nrAutoPoolReady_=true;+ log::info("nr-auto-pool",std::format("event=ready layer={} handles={} createMs={:.3f} extraMiB={}",index,nrInstances_.size()+4,+ std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count(),(usage-beforeUsage)>>20));+ return true;+}++bool EnhanceGraph::selectAutoNrLevel(unsigned level) {+ if(!nrAutoPoolReady_||!desc_.nrAutoPoolLayer||level>=nrAutoPool_.size())return false;+ if(level==nrAutoLevel_)return true;+ // The host must retire every presentation/CPU lease at this boundary.+ if(!realLeases_[0].expired()||!realLeases_[1].expired()||!nrAutoPool_[level])return false;+ const auto start=std::chrono::steady_clock::now();+ if(!ring_.drainQueue()||!ring_.discardRecording())return false;+ const auto index=*desc_.nrAutoPoolLayer,prior=nrAutoLevel_;const auto previousDesc=desc_;+ auto& old=*nrInstances_[index];auto& next=*nrAutoPool_[level];+ next.model=old.model;next.residualSettings=old.residualSettings;next.protection=old.protection;next.enabled=old.enabled;+ nrAutoPool_[prior]=std::move(nrInstances_[index]);nrInstances_[index]=std::move(nrAutoPool_[level]);+ const Extent extent{next.width(),next.height()};desc_.nrLayersExtent[index]=extent;+ if(desc_.fixedExecutionPlan)for(unsigned i=0;i<desc_.fixedExecutionPlan->stepCount;++i){auto& step=desc_.fixedExecutionPlan->steps[i];+ if(step.type==engine::EffectType::NrEnhance&&step.resourceIndex==index)step.processing=extent;}+ if(!createViews()){+ nrAutoPool_[level]=std::move(nrInstances_[index]);nrInstances_[index]=std::move(nrAutoPool_[prior]);desc_=previousDesc;+ const bool restored=createViews();log::error("nr-auto-pool",std::format("descriptor switch failed restored={}",restored));return false;+ }+ nrAutoLevel_=level;nrAutoResetPending_=true;invalidatePausedResidualCache();+ for(auto& layer:nrInstances_){layer->historyValid=false;layer->inputRevision=1;}+ log::info("nr-auto-pool",std::format("event=switch from={} to={} internal={}x{} switchMs={:.3f} reset=true",prior,level,extent.width,extent.height,+ std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()));+ return true;+}+bool EnhanceGraph::createNrHoldPass(){nrHoldPass_.reset();@@ -1791,6 +1845,7 @@ bool EnhanceGraph::createViews()// ---------------------------------------------------------------------------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){+ reset=reset||nrAutoResetPending_;nrAutoResetPending_=false;// 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.@@ -3142,6 +3197,10 @@ void EnhanceGraph::shutdown()featuresReleased=featuresReleased&&safe&&layerResult==uint64_t(NVSDK_NGX_Result_Success)&&layerSeh==0;layer->setHandle(nullptr);}+ for(auto& layer:nrAutoPool_)if(layer&&layer->handle()){+ uint64_t result=0;uint32_t seh=0;const bool safe=nrAdapter_->snippetReleaseFeature(layer->handle(),result,seh);+ featuresReleased=featuresReleased&&safe&&result==uint64_t(NVSDK_NGX_Result_Success)&&seh==0;layer->setHandle(nullptr);+ }gpuDis_.reset();amdOf_.reset();for(auto& motion:presentMotion_)motion.Reset();@@ -3179,6 +3238,9 @@ void EnhanceGraph::shutdown()// core is still alive, rather than relying on its shutdown leak fallback.if (coreHost_ && coreHost_->initialized()) {unsigned releasedNrParameters = 0;+ for(auto layer=nrAutoPool_.rbegin();layer!=nrAutoPool_.rend();++layer)if(*layer&&(*layer)->parameters()){+ coreHost_->destroyParameters((*layer)->parameters());(*layer)->setParameters(nullptr);++releasedNrParameters;+ }for (auto layer = nrInstances_.rbegin(); layer != nrInstances_.rend(); ++layer) {if ((*layer)->parameters() == nullptr) continue;coreHost_->destroyParameters((*layer)->parameters());@@ -3225,6 +3287,7 @@ void EnhanceGraph::shutdown()downsamplePass_={};residualPass_={};stackProtectionPass_={};flowAdaptPass_={};for(auto& layer:nrInstances_)layer->close();nrInstances_.clear();+ for(auto& layer:nrAutoPool_)layer.reset();nrAutoLevel_=0;nrAutoPoolReady_=nrAutoResetPending_=false;residualRgba_.Reset();preSrProtectionRgba_.Reset();interNrProtectionRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();for(unsigned i=0;i<kGeneratedPoolSlots;++i){if(fgDisableMapped_[i]&&fgDisableReadback_[i]){D3D12_RANGE written{0,0};fgDisableReadback_[i]->Unmap(0,&written);}fgDisableMapped_[i]=nullptr;fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();encPass_ = ComputePass{};diff --git a/tests/perf/AutoNrControllerTests.cpp b/tests/perf/AutoNrControllerTests.cppnew file mode 100644index 00000000..baa8b1be--- /dev/null+++ b/tests/perf/AutoNrControllerTests.cpp@@ -0,0 +1,26 @@+#include "veyra/engine/AutoNrController.h"+#include <iostream>+#include <limits>+int main() {+ using veyra::engine::AutoNrController;AutoNrController c;c.reset(0);+ if(c.observe(4999999,20,30,10))return 1;+ if(c.observe(5000000,20,30,10)!=1)return 1;+ if(c.observe(10000000,20,30,10))return 1; // dwell protects visible switching+ if(c.observe(35000000,20,30,10)!=2)return 1;+ if(c.observe(65000000,20,30,10)!=3)return 1;+ if(c.observe(95000000,20,30,10)!=4)return 1;+ if(c.observe(125000000,20,30,10))return 1; // floor remains honestly over budget+ if(c.observe(130000000,4,30,10)||c.observe(160000000,4,30,10))return 1; // four/minute cap+ if(c.observe(605000000,4,30,10)!=3)return 1;+ c.discardObservations(605000000);+ if(c.observe(610000000,4,30,10))return 1;+ if(c.observe(615000000,4,30,10))return 1;+ if(c.observe(645000000,4,30,10)!=2)return 1;+ c.reset(700000000);+ if(c.level()!=0||c.observe(705000000,20,7,10)||c.observe(710000000,std::nullopt,30,10)||+ c.observe(715000000,std::numeric_limits<double>::quiet_NaN(),30,10)||c.observe(720000000,20,30,0))return 1;+ if(c.observe(725000000,11,30,10)!=1)return 1;+ if(c.observe(755000000,7.5,30,10)||c.observe(785000000,7.5,30,10))return 1; // hysteresis band+ std::cout<<"AUTO_NR_CONTROLLER_PASS transportBudget=1 dwell=1 hysteresis=1 cap=1 floor=1 invalidTiming=1 reset=1"<<std::endl;+ return 0;+}diff --git a/tests/perf/NrAutoPoolExperiment.cpp b/tests/perf/NrAutoPoolExperiment.cppnew file mode 100644index 00000000..62668f29--- /dev/null+++ b/tests/perf/NrAutoPoolExperiment.cpp@@ -0,0 +1,60 @@+#include "veyra/engine/PreviewGpuSession.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/AutoNrController.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/RuntimePaths.h"+#include "veyra/FileIdentity.h"+#include <d3d12sdklayers.h>+#include <chrono>+#include <fstream>+#include <iostream>++int wmain(int argc,wchar_t** argv) {+ using namespace veyra;if(argc!=5)return 2;+ const bool pooled=std::wstring(argv[3])==L"pool";if(!pooled&&std::wstring(argv[3])!=L"reference")return 2;+ const unsigned count=_wtoi(argv[4]);if(count<1||count>2)return 2;+ const HRESULT com=CoInitializeEx(nullptr,COINIT_MULTITHREADED);if(FAILED(com))return 2;+ struct ComLifetime{~ComLifetime(){CoUninitialize();}} comLifetime;+ const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);Logger::instance().openFile((out/L"engine.log").wstring());+ Microsoft::WRL::ComPtr<ID3D12Debug> debugLayer;if(FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugLayer))))return 2;debugLayer->EnableDebugLayer();+ engine::EffectChain chain;chain.nodeCount=count;+ for(unsigned i=0;i<count;++i){auto& node=chain.nodes[i];node.type=engine::EffectType::NrEnhance;node.enabled=true;node.nr.temporal=false;node.nr.sizePolicy=pipeline::NrSizePolicy::Realtime;}+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.multiplier=1;+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=true;+ pipeline::EnhanceGraphDesc initial;engine::describeStages(request,settings,initial);initial.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ engine::PreviewGpuSession session;if(!session.initialize())return 2;+ auto makeDesc=[&](unsigned level){auto desc=initial;const auto percent=engine::AutoNrController::percent(level);+ const pipeline::Extent size{(1920*percent/100)&~1u,(1080*percent/100)&~1u};desc.nrLayersExtent[0]=size;+ for(unsigned i=0;i<desc.fixedExecutionPlan->stepCount;++i){auto& step=desc.fixedExecutionPlan->steps[i];if(step.type==engine::EffectType::NrEnhance&&step.resourceIndex==0)step.processing=size;}+ return desc;};+ if(pooled){initial.nrAutoPoolLayer=0;if(!session.graph->initialize(initial)||!session.graph->createViews()||!session.graph->autoNrPoolReady())return 2;}+ source::MediaFileSource source;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;if(!source.open(open))return 2;+ constexpr unsigned levels[6]={0,1,2,3,4,0};+ std::ofstream frames(out/L"frames.csv");frames<<"frame,level,pts100ns,width,height,historyReset,sha256\n";+ bool pass=true;unsigned completed=0;+ for(unsigned segment=0;segment<6&&pass;++segment){const auto level=levels[segment];+ if(pooled)pass=session.graph->selectAutoNrLevel(level);+ else{session.graph->shutdown();pass=session.graph->initialize(makeDesc(level))&&session.graph->createViews();}+ for(unsigned j=0;j<15&&pass;++j){const unsigned frame=segment*15+j;+ pipeline::FramePacket packet;const AVFrame* input=nullptr;pipeline::EnhanceGraph::FrameOutputs output;+ // For the pool, switches must request reset themselves. Only the+ // first frame has an explicit caller reset.+ pass=source.read(packet,&input)==source::SourceReadStatus::Frame&&+ session.graph->process(input,packet.pts.toDouble()*1000,pooled?frame==0:j==0,output,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle();+ if(pass&&j==0)pass=output.historyReset;+ sink::RgbaImage image;if(pass)pass=sink::readRgba8(session.context,session.ring,session.graph->videoFrameResource(output.videoSlot),image);+ if(pass){frames<<frame<<','<<level<<','<<int64_t(packet.pts.toDouble()*10000000)<<','<<image.width<<','<<image.height<<','<<output.historyReset<<','+ <<sha256Hex(image.pixels.data(),image.pixels.size())<<'\n';frames.flush();+ if(j==0||j==14)pass=sink::saveImage((out/(L"frame-"+std::to_wstring(frame)+L".png")).wstring(),image);+ if(pass)++completed;}+ }+ }+ source.close();session.ring.drainQueue();session.graph->shutdown();pass=session.core.close("nr-auto-pool-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==90&&errors==0&&SUCCEEDED(removed);debug.Reset();session.shutdown();+ std::cout<<"NR_AUTO_POOL_RESULT pass="<<pass<<" frames="<<completed<<" layers="<<count<<" debugErrors="<<errors<<" deviceRemoved="<<unsigned(removed)<<std::endl;+ return pass?0:1;+}