Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
perf: prototype bounded recent single-NR graph cache with reset and pressure eviction
Veyra Goal Agent4c97dad60786
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e2dd9b78..b4aa36dd 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1034,6 +1034,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionTtarget_compile_features(veyra_nr_gpu_competition_load PRIVATE cxx_std_20)target_compile_options(veyra_nr_gpu_competition_load PRIVATE /utf-8)target_link_libraries(veyra_nr_gpu_competition_load PRIVATE veyra_engine)+ add_executable(veyra_nr_recent_cache_experiment tests/perf/NrRecentCacheExperiment.cpp)+ 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)add_executable(veyra_nr_core_cache_contract_tests tests/perf/NrCoreCacheContractTests.cpp)target_compile_features(veyra_nr_core_cache_contract_tests PRIVATE cxx_std_20)target_compile_options(veyra_nr_core_cache_contract_tests PRIVATE /utf-8)diff --git a/docs/PERF_2C_RECENT_CACHE_2026-10-04.md b/docs/PERF_2C_RECENT_CACHE_2026-10-04.mdnew file mode 100644index 00000000..0742b559--- /dev/null+++ b/docs/PERF_2C_RECENT_CACHE_2026-10-04.md@@ -0,0 +1,7 @@+# 2c:最近单NR配置缓存候选++前存档cc8db0f / checkpoint/perf-nr-2c-revised-before-20261004。候选仅常规文件、本机未补丁NVIDIA/Lecram单NR、无SR/FG/HDR/抗闪烁/稳定器/颜色,NR→效果全关→严格同配置;最多一份非活动Graph。持有完整Graph可以保持NR adapter/IAT/Core所有权一致,效果全关新图不给CoreCache,不执行第二次NGX初始化。其他增强图必须先释放缓存,绝不同时创建第二个adapter。默认无需开关,TEST_DISABLE_RECENT_GRAPH_CACHE提供同EXE回退。++key包含完整EnhancementSettings(仅revision归零)、节点顺序、源/work/NR尺寸、格式/位深、runtime路径及NR DLL大小/mtime;这不是运行库哈希加载锁,变化只让缓存失效。实际QueryVideoMemoryInfo构建前后差作为保守占用估计;未知/0不保留。WDDM余量必须>占用1.5倍,并限制自身usage<budget/3,比原案更保守。内存检查500ms包括暂停;压力/失败/源resize/rollback/退出都先释放缓存。命中先清暂停残差seed,第一次完整process(reset=true)重置NR/flow等全部历史。++原生50次开关,前20与此前已封存B2a-v2-nr三轮相同自然源前三帧/Realtime1080参数;之后每轮改自然源时间段验证历史恢复。保存每轮所有完整RGBA8 SHA及8张关键图,CPU创建计时不含readback,D3D12 debug及最终Core关闭/显存记录。真实Qt与压力测试随后执行。压力注入增加独立测试limit,实际资源/累计MiB/HRESULT入日志,不改变默认产品设置。此文件当前是候选说明,未构建/未验收,不能称保留。diff --git a/docs/PERF_EXECUTION_NR_2026-10-04.md b/docs/PERF_EXECUTION_NR_2026-10-04.mdindex fde189f1..f2e783f2 100644--- a/docs/PERF_EXECUTION_NR_2026-10-04.md+++ b/docs/PERF_EXECUTION_NR_2026-10-04.md@@ -32,7 +32,7 @@| 5a | 黑边检测与有效区域处理 | pending | 防暗场误裁,先测准确性与重建收益 || 3a | 进程GPU调度优先级 | in-progress | 九组交错Normal/High/Realtime,本轮三NR竞争Graph,Set/Get/P95/P99及对方吞吐;PERF_3A_GPU_PRIORITY || 2a | 跨重建保留NGX核心 | retained-pending-R0 | v2三轮A/B/B-off完整输出0差异;暖创建减少75.83/71.23/64.58/72.04%;真实UI及SDK拒绝路径通过;导出待R0 |-| 2c | 最近配置实例缓存 | pending | 有界预算/复用reset/压力回退 |+| 2c | 最近配置实例缓存 | in-progress | 单NR↔全关严格key候选,有界显存/唯一adapter/历史reset,native50次与Qt压力待验;PERF_2C_RECENT_CACHE || 2d | 空闲预热 | pending | 首帧收益与开关关闭时显存 || 2b | 后台建图与帧边界切换 | pending | 取决于E2,不移除必要同步 || 3b | NR自动内部尺寸 | pending | 取决于E1、真实预算/画质证据 |diff --git a/include/veyra/engine/RecentGraphCache.h b/include/veyra/engine/RecentGraphCache.hnew file mode 100644index 00000000..dd0ecef6--- /dev/null+++ b/include/veyra/engine/RecentGraphCache.h@@ -0,0 +1,99 @@+#pragma once+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/Log.h"+#include "veyra/ngx/FgCompatibilitySession.h"+#include <filesystem>+#include <format>+#include <algorithm>+#include <cstdint>+#include <memory>+#include <optional>++namespace veyra::engine {+// One inactive single-NR graph. Only an effects-off graph may coexist, so+// there is never a second NR adapter/IAT owner or a second NGX Init.+class RecentGraphCache {+public:+ struct Key {+ EnhancementSettings settings;+ std::optional<ChainRuntimeOrder> order;+ unsigned sourceWidth=0,sourceHeight=0,workWidth=0,workHeight=0,nrWidth=0,nrHeight=0;+ bool hdrInput=false,hdrOutput=false,rgbInput=false;+ unsigned captureBitDepth=8,packedInput=0;bool yuy2Input=false;+ std::wstring runtime;+ uint64_t nrFileBytes=0;int64_t nrFileTimestamp=0;+ bool operator==(const Key&)const=default;+ };+ explicit RecentGraphCache(gfx::D3D12DeviceContext& context):context_(context){}+ ~RecentGraphCache(){evict("source-close");}+ static Key key(EnhancementSettings settings,std::optional<ChainRuntimeOrder> order,const pipeline::EnhanceGraphDesc& desc){+ settings.revision=0;+ Key result{std::move(settings),std::move(order),desc.sourceWidth,desc.sourceHeight,desc.workWidth,desc.workHeight,+ desc.nrWidth,desc.nrHeight,desc.hdrInput,desc.hdrOutput,desc.rgbInput,desc.captureBitDepth,desc.packedInput,desc.yuy2Input,desc.runtimeAbsPath};+ std::error_code error;const auto module=std::filesystem::path(desc.runtimeAbsPath)/L"nvngx_dlssnr.dll";+ result.nrFileBytes=std::filesystem::file_size(module,error);+ if(error)result.nrFileBytes=0;+ const auto time=std::filesystem::last_write_time(module,error);+ if(error)result.nrFileBytes=0;else result.nrFileTimestamp=time.time_since_epoch().count();+ return result;+ }+ static bool eligible(const pipeline::EnhanceGraphDesc& desc){+ return desc.enableNr&&!desc.enableSr&&!desc.enableFg&&!desc.hdrInput&&!desc.hdrOutput&&!desc.videoHdr.enabled&&!desc.color.enabled&&desc.additionalColorCount==0&&+ desc.nrHoldStrength==0&&!desc.noFeatures&&!desc.noNgx&&!desc.stillImage&&+ desc.nrRuntime==NrRuntime::Original&&!desc.nrTemporal&&desc.nrLayersModel.size()<=1&&+ std::none_of(desc.nrLayersTemporal.begin(),desc.nrLayersTemporal.end(),[](bool value){return value;})&&+ (!desc.fixedExecutionPlan||(desc.fixedExecutionPlan->mode==ChainMode::List&&+ desc.fixedExecutionPlan->stepCount==1&&desc.fixedExecutionPlan->steps[0].type==EffectType::NrEnhance));+ }+ static bool effectsOff(const pipeline::EnhanceGraphDesc& desc){+ return !desc.enableNr&&!desc.enableSr&&!desc.enableFg&&!desc.videoHdr.enabled&&!desc.color.enabled&&desc.additionalColorCount==0;+ }+ static std::string label(const Key& key){+ return std::format("{}x{}:{}x{}:{}x{}:runtime{}:file{}:mtime{}",key.sourceWidth,key.sourceHeight,+ key.workWidth,key.workHeight,key.nrWidth,key.nrHeight,int(key.settings.nrRuntime),key.nrFileBytes,key.nrFileTimestamp);+ }+ bool retain(std::unique_ptr<pipeline::EnhanceGraph>& graph,Key key,uint64_t bytes){+ evict("replace");uint64_t budget=0,usage=0;+ if(!graph||graph->failedBackend()!=FailedBackend::None||!bytes||!key.nrFileBytes||+ ngx::FgCompatibilitySession::requested(context_.adapter().vendorId,context_.adapter().deviceId)||FAILED(context_.device()->GetDeviceRemovedReason())||+ !context_.videoMemoryInfo(budget,usage)||!fits(budget,usage,bytes)){+ log::info("feature-cache",std::format("event=miss reason=budget-or-session key={} bytes={} usage={} budget={}",label(key),bytes,usage,budget));return false;}+ graph_=std::move(graph);key_=std::move(key);bytes_=bytes;+ log::info("feature-cache",std::format("event=retain key={} bytes={} usage={} budget={}",label(*key_),bytes_,usage,budget));return true;+ }+ std::unique_ptr<pipeline::EnhanceGraph> take(const Key& key){+ if(!graph_)return {};+ if(!key_||!(*key_==key)){evict("key-changed");return {};}+ if(!checkBudget())return {};+ graph_->invalidatePausedResidualCache();+ log::info("feature-cache",std::format("event=hit key={} bytes={} reset-required=true",label(*key_),bytes_));+ key_.reset();bytes_=0;return std::move(graph_);+ }+ bool checkBudget(){+ if(!graph_)return true;uint64_t budget=0,usage=0;+ if(FAILED(context_.device()->GetDeviceRemovedReason())||!context_.videoMemoryInfo(budget,usage)||!fits(budget,usage,bytes_)){+ evict("budget-pressure-or-device");return false;}+ return true;+ }+ void evict(const char* reason){+ if(!graph_)return;+ log::info("feature-cache",std::format("event=evict reason={} bytes={}",reason,bytes_));+ graph_->shutdown();graph_.reset();key_.reset();bytes_=0;+ }+ uint64_t bytes()const{return bytes_;}+ bool hasCachedGraph()const{return bool(graph_);}+ static bool fits(uint64_t budget,uint64_t usage,uint64_t bytes){+ // Inactive graphs are expendable: preserve only while this process+ // uses less than one third of its dynamic WDDM budget, as well as the+ // required 1.5x spare footprint. Avoid reserving headroom near pressure.+ return bytes&&budget>usage&&usage<budget/3&&bytes<=UINT64_MAX/3&&(budget-usage)>bytes+bytes/2;+ }+private:+ gfx::D3D12DeviceContext& context_;+ std::unique_ptr<pipeline::EnhanceGraph> graph_;+ std::optional<Key> key_;+ uint64_t bytes_=0;+};+}diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 9fb1169c..9e25cb59 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -408,6 +408,11 @@ public:// LUT the ingest shader samples. Without a LUT the strength stays 0.bool setColorLut(const float* rgb,unsigned size,unsigned instance=0);bool createViews();+ // Re-activating an inactive graph must seed a new full paused evaluation;+ // caller still passes reset=true to reset all temporal histories.+ void invalidatePausedResidualCache() noexcept {+ pausedNrCacheValid_=pausedNrResidualOnly_=false;pausedNrFrame_=nullptr;pausedNrSettings_.reset();+ }struct FrameOutputs {FrameBatch batch;diff --git a/scripts/perf/nr-feature-cache.py b/scripts/perf/nr-feature-cache.pynew file mode 100644index 00000000..e57c6aee--- /dev/null+++ b/scripts/perf/nr-feature-cache.py@@ -0,0 +1,55 @@+"""Bounded real feature-cache native experiment, hashes and raw memory curves."""+from pathlib import Path+import csv+import importlib.util+import json+import os+import re+import shutil+import statistics+import subprocess+import sys+import time++ROOT=Path(__file__).resolve().parents[2];BASE=Path('E:/项目/Veyra');TASK='perf-nr-20261004'+spec=importlib.util.spec_from_file_location('matrix',ROOT/'scripts/perf/nr-matrix.py')+matrix=importlib.util.module_from_spec(spec);spec.loader.exec_module(matrix)+variant,label=sys.argv[1:3];app=BASE/'tests'/TASK/(label+'-app')+assert not app.exists();matrix.assert_gpu_tests_idle()+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_recent_cache_experiment.exe'+shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)+results=[]+for repeat in range(1,4):+ for disabled in (True,False):+ matrix.assert_gpu_tests_idle();name=f'{label}-'+('off' if disabled else 'on')+f'-r{repeat}'+ out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name+ for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)+ env=os.environ.copy()+ for key in tuple(env):+ if key.upper().startswith('VEYRA_'):env.pop(key)+ env.update(TEMP=str(tmp),TMP=str(tmp))+ if disabled:env['VEYRA_TEST_DISABLE_RECENT_GRAPH_CACHE']='1'+ command=[str(exe),str(matrix.SOURCES['M1']),str(out)];before=matrix.gpu_query();start=time.monotonic()+ print('START',name,flush=True)+ with (out/'console.log').open('xb') as f:+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=f,stderr=subprocess.STDOUT,timeout=280).returncode+ except subprocess.TimeoutExpired:rc=124+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace')+ rows=list(csv.DictReader((out/'cache.csv').open())) if (out/'cache.csv').exists() else []+ hits=sum(int(r['hit']) for r in rows)+ creates=[float(r['createMs']) for r in rows if int(r['nr']) and int(r['cycle'])>0]+ result={'variant':variant,'label':label,'disabled':disabled,'repeat':repeat,'exeSha256':matrix.digest(exe),+ 'runtimeSha256':matrix.digest(app/'runtime/experimental/nvngx_dlssnr.dll'),+ 'sourceSha256':matrix.digest(matrix.SOURCES['M1']),'beforeGpu':before,'afterGpu':matrix.gpu_query(),+ 'command':command,'exitCode':rc,'wallSeconds':time.monotonic()-start,'frameCount':len(rows),+ 'hits':hits,'warmCreateMedianMs':statistics.median(creates) if creates else None,+ 'sha256Sequence':[r['sha256'] for r in rows],+ 'finalVram':int(re.search(r'afterFinalClose=(\d+)',text).group(1)) if 'afterFinalClose=' in text else None,+ 'passed':rc==0 and len(rows)==50 and 'CACHE_RESULT pass=1' in text and+ 'debugErrors=0 deviceRemoved=0' in text and hits==(0 if disabled else 24),+ 'measurement':'Actual graph creation/reactivation CPU with GPU completion, full output SHA; no display scanout'}+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')+ results.append(result);print('RESULT',name,result['passed'],hits,result['warmCreateMedianMs'],flush=True)+ if not result['passed']:print(text[-6500:],flush=True);raise SystemExit(1)+with (BASE/'logs'/TASK/(label+'-summary.json')).open('x',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 74929836..eb525038 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -40,6 +40,7 @@#include "veyra/gfx/PresentationHooks.h"#include "veyra/RuntimePaths.h"#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/RecentGraphCache.h"#include "veyra/engine/EffectChain.h"#include "veyra/engine/PosterFrame.h"#include <avrt.h>@@ -293,7 +294,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sgfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;ngx::NgxCoreCache coreCache;- pipeline::EnhanceGraph graph(ctx,ring,&coreCache);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;+ RecentGraphCache recentGraphCache(ctx);+ auto graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);+ uint64_t graphBytes=0;auto cacheBudgetPolledAt=Clock::now();+ const bool recentCacheAllowed=!GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_RECENT_GRAPH_CACHE",nullptr,0);+ AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;source::CaptureCardSource captureSource;const bool physicalCapture=path.starts_with(L"capture:")||path.starts_with(L"capture2:");source::ScreenCaptureSource screenSource;const bool isScreen=path.starts_with(L"screen:");// Set when a live parameter change arrives while paused (or on a still@@ -371,7 +376,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,ssnapshot_.sourceRotationDegrees=0;}}else{source::SourceOpenDesc od;od.path=path;- // Files use the same shared D3D12 device as the graph. Capture+ // Files use the same shared D3D12 device as the graph-> Capture// uses it for the compressed-payload decoder (H.264/HEVC/AV1/// VP9 through D3D12VA; MJPEG stays on the software path inside// CaptureCompressedDecoder). Each source performs its own@@ -534,19 +539,30 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sfor(unsigned attempt=0;attempt<6;++attempt){desc.videoHdr=selected.settings.videoHdr;desc.hdrOutput=selected.settings.useHdrPreview(desc.hdrInput,displayHdrActive());- bool opened=graph.initialize(desc);- auto failure=graph.failedBackend();+ // The only graph allowed beside an inactive NR adapter is+ // effects-off. Evict before any other NGX initialization.+ if(recentGraphCache.hasCachedGraph()&&!RecentGraphCache::effectsOff(desc)){+ recentGraphCache.evict("enhancement-build");+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);+ }+ uint64_t buildBudget=0,buildUsage=0;const bool measuredBefore=ctx.videoMemoryInfo(buildBudget,buildUsage);+ bool opened=graph->initialize(desc);+ auto failure=graph->failedBackend();if(opened){- opened=presenter.open(ctx,window,graph,selected.settings.captureCompatible,!isCapture&&!isImage)&&graph.createViews();+ opened=presenter.open(ctx,window,*graph,selected.settings.captureCompatible,!isCapture&&!isImage)&&graph->createViews();failure=FailedBackend::Infrastructure;- if(opened&&graph.xessEnabled()&&!presenter.xessActive()){opened=false;failure=FailedBackend::Fg;}- if(opened&&graph.fsrEnabled()&&!graph.fsrActive()){opened=false;failure=FailedBackend::Fg;}+ if(opened&&graph->xessEnabled()&&!presenter.xessActive()){opened=false;failure=FailedBackend::Fg;}+ if(opened&&graph->fsrEnabled()&&!graph->fsrActive()){opened=false;failure=FailedBackend::Fg;}// Requested AMD FSR upscaling that could not be created// (missing local runtime, unsupported layout) degrades// to the plain scale path with a visible warning.- if(opened&&graph.fsrSrRequested()&&!graph.fsrSrEnabled()){opened=false;failure=FailedBackend::Sr;}+ if(opened&&graph->fsrSrRequested()&&!graph->fsrSrEnabled()){opened=false;failure=FailedBackend::Sr;}}- if(opened)return true;+ if(opened){+ uint64_t afterBudget=0,afterUsage=0;+ graphBytes=measuredBefore&&ctx.videoMemoryInfo(afterBudget,afterUsage)&&afterUsage>buildUsage?afterUsage-buildUsage:0;+ return true;+ }// A live backend/multiplier switch must not turn a working FG// session into effects-off playback when the new provider fails.if(preserveWorkingFg&&failure==FailedBackend::Fg)return false;@@ -559,13 +575,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sbool clampedOverCapability=false;int capabilityGeneratedFrames=-1;if(failure==FailedBackend::Fg&&reduced.multiplier>1){- if(reduced.frameGenerationBackend==FrameGenerationBackend::Dlss)capabilityGeneratedFrames=graph.fgMultiFrameCountMax();+ if(reduced.frameGenerationBackend==FrameGenerationBackend::Dlss)capabilityGeneratedFrames=graph->fgMultiFrameCountMax();else if(reduced.frameGenerationBackend==FrameGenerationBackend::XeSS){const auto xessState=gfx::XessMfgUnlock::snapshot();if(xessState.applied)capabilityGeneratedFrames=int(xessState.maxInterpolations);}else if(fsrFrameGeneration(reduced.frameGenerationBackend)){- capabilityGeneratedFrames=int((graph.fsrActive()?1u:0u));+ capabilityGeneratedFrames=int((graph->fsrActive()?1u:0u));}}if(capabilityGeneratedFrames>0&&int(reduced.multiplier)-1>capabilityGeneratedFrames){@@ -580,7 +596,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!clampedOverCapability&&!disableFailedBackend(reduced,failure))return false;veyra::log::warn("backend-recovery",std::format("initialization failed component={} attempt={} revision={} -> nr={} sr={} multiplier={}; original SDK error above",unsigned(failure),attempt+1,reduced.revision,reduced.nr,reduced.sr,reduced.multiplier));if(!backendRecoveryWarning.empty())backendRecoveryWarning+=L";";- const uint32_t ngxResult=uint32_t(graph.failedNgxResult());+ const uint32_t ngxResult=uint32_t(graph->failedNgxResult());if(selected.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&failure==FailedBackend::Fg)backendRecoveryWarning+=L"NVIDIA VFG 未能启用(需要 Ada / Blackwell 显卡、VFG 运行组件和支持的输出格式),已关闭补帧;原因见日志";else if(selected.settings.frameGenerationBackend==FrameGenerationBackend::Fsr4&&failure==FailedBackend::Fg)@@ -589,11 +605,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sbackendRecoveryWarning+=std::wstring(backendFailureName(failure))+L":"+ngxFailureHint(ngxResult)+std::format(L"(NGX 0x{:08X},驱动 {}),已关闭依赖效果",ngxResult,ctx.adapter().driverVersion);else if(!clampedOverCapability)backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L" 初始化失败,已关闭依赖效果;原因见诊断日志";- if(!graph.driverRequirementNotice().empty())backendRecoveryWarning+=L";"+graph.driverRequirementNotice();+ if(!graph->driverRequirementNotice().empty())backendRecoveryWarning+=L";"+graph->driverRequirementNotice();if(failure==FailedBackend::Fg&&(ngx::AmpereMfgUnlock::applied()||(ngx::DlssgTransfusion::applied()&&ngx::DlssgTransfusion::snapshot().target==ngx::DlssgTransfusion::Target::Ampere)))backendRecoveryWarning+=L";RTX 30 系补帧解锁已应用,但当前驱动/运行库组合下运行时不开放补帧,可改用 AMD FSR 补帧";if(!ring.drainQueue()||!ring.discardRecording())return false;- presenter.close();graph.shutdown();selected=PlayerOptions::from(reduced,selected.nodeOrder);+ presenter.close();graph->shutdown();selected=PlayerOptions::from(reduced,selected.nodeOrder);describeStages(stageRequest(selected),selected.snapshot(),desc);}return false;@@ -602,7 +618,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// Read the active provider after every rebuild or rollback;// an initial effects-off graph has no DLSS capability yet.std::lock_guard lock(mutex_);- fgMultiFrameMaxCap_=graph.fgMultiFrameCountMax();+ fgMultiFrameMaxCap_=graph->fgMultiFrameCountMax();snapshot_.fgMultiFrameMax=fgMultiFrameMaxCap_;snapshot_.fgCapabilityKnown=fgMultiFrameMaxCap_>0;const auto xessState=gfx::XessMfgUnlock::snapshot();@@ -612,9 +628,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,ssnapshot_.xessMaxInterpolatedFrames=xessMaxInterpolatedFramesCap_;// AMD FSR ceiling comes from the active graph provider; 0 keeps the// settings UI on its static 2X fallback until a session ran.- fsrMaxGeneratedFramesCap_=graph.fsrEnabled()&&graph.fsrActive()?int((graph.fsrActive()?1u:0u)):0;+ fsrMaxGeneratedFramesCap_=graph->fsrEnabled()&&graph->fsrActive()?int((graph->fsrActive()?1u:0u)):0;snapshot_.fsrMaxGeneratedFrames=fsrMaxGeneratedFramesCap_;- snapshot_.fsrProviderVersion=graph.fsrProviderVersion();+ snapshot_.fsrProviderVersion=graph->fsrProviderVersion();if(fgMultiFrameMaxCap_>0)veyra::log::info("settings",std::format("frame-generation capability: maxGeneratedFrames={} maxMultiplier={}",fgMultiFrameMaxCap_,fgMultiFrameMaxCap_+1));veyra::log::info("settings",std::format("xess capability: active={} maxInterpolatedFrames={} unlockApplied={} (active context only)",presenter.xessActive(),xessMaxInterpolatedFramesCap_,xessState.applied));if(fsrMaxGeneratedFramesCap_>0)veyra::log::info("settings",std::format("fsr capability: generatedPerPresent={} => maxMultiplier={}",fsrMaxGeneratedFramesCap_,fsrMaxGeneratedFramesCap_+1));@@ -631,11 +647,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstatus(L"当前非 NVIDIA 适配器:NR、NVIDIA 超分与 DLSS 已禁用;可使用 XeSS 预览和 AMD 光流",false);}if(gd.hdrInput)status(gd.hdrOutput?L"HDR输入 · HDR保留增强/显示":L"HDR输入 · SDR色调映射后增强/显示(1000nit参考峰值)",false);- if(graph.xessEnabled()&&!presenter.xessActive())status(L"XeSS 未启用:运行时或设备不兼容;当前为普通呈现",false);+ if(graph->xessEnabled()&&!presenter.xessActive())status(L"XeSS 未启用:运行时或设备不兼容;当前为普通呈现",false);{std::lock_guard lock(mutex_);if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg)))snapshot_.backendWarning=L"当前 GPU 不支持所选 NVIDIA 增强";- if(graph.xessEnabled()&&!presenter.xessActive())snapshot_.backendWarning=L"XeSS 初始化失败;当前为普通呈现";+ if(graph->xessEnabled()&&!presenter.xessActive())snapshot_.backendWarning=L"XeSS 初始化失败;当前为普通呈现";}captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);captureSource.setAudioIngress(unsigned(options.settings.captureAudio));@@ -677,17 +693,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// VEYRA_TEST_VRAM_LEAK_RELEASE=1 lets the swapchain rebuild free it (as a leak tied// to the swapchain would), otherwise nothing frees it.const uint64_t testLeakMiB=[]{wchar_t v[16]{};return GetEnvironmentVariableW(L"VEYRA_TEST_VRAM_LEAK_MIB",v,16)?uint64_t(_wtoi(v)):0ull;}();+ const uint64_t testLeakLimitMiB=[]{wchar_t v[16]{};return GetEnvironmentVariableW(L"VEYRA_TEST_VRAM_LEAK_LIMIT_MIB",v,16)?uint64_t(std::max(0,_wtoi(v))):0ull;}();const bool testLeakReleases=GetEnvironmentVariableW(L"VEYRA_TEST_VRAM_LEAK_RELEASE",nullptr,0)>0;const bool testLeakFullscreenOnly=GetEnvironmentVariableW(L"VEYRA_TEST_VRAM_LEAK_FULLSCREEN_ONLY",nullptr,0)>0;std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> testLeak;auto watchVram=[&](uint64_t usage,uint64_t budget){+ (void)recentGraphCache.checkBudget();bool fullscreen=false;{std::lock_guard lock(mutex_);fullscreen=presentation_.fullscreen;}- if(testLeakMiB&&(!testLeakFullscreenOnly||fullscreen)){+ if(testLeakMiB&&(!testLeakLimitMiB||uint64_t(testLeak.size()+1)*testLeakMiB<=testLeakLimitMiB)&&(!testLeakFullscreenOnly||fullscreen)){const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};D3D12_RESOURCE_DESC desc{};desc.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;desc.Width=testLeakMiB<<20;desc.Height=1;desc.DepthOrArraySize=1;desc.MipLevels=1;desc.SampleDesc.Count=1;desc.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;Microsoft::WRL::ComPtr<ID3D12Resource> r;- if(SUCCEEDED(ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&r))))testLeak.push_back(r);+ const auto hr=ctx.device()->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&r));+ if(SUCCEEDED(hr))testLeak.push_back(r);+ log::info("vram-test",std::format("allocationMiB={} heldMiB={} limitMiB={} hr=0x{:X}",testLeakMiB,uint64_t(testLeak.size())*testLeakMiB,testLeakLimitMiB,unsigned(hr)));}const bool protection=fullscreenMemoryProtection_.load();if(protection!=vramProtectionEnabled){@@ -793,7 +813,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// Live ingress stays latest-frame; file preview keeps the audio clock// and may skip expired enhancement opportunities, never PCM.// Graph, query collection and presentation remain on this owner.- graph.recordGpuTimings();presenter.recordGpuTimings();+ graph->recordGpuTimings();presenter.recordGpuTimings();struct LiveStats {uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};LiveStats liveStats;std::deque<int64_t> liveSubmissions;TimingWindow liveAges,liveWaits,liveReady;@@ -877,7 +897,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}}};- for(const auto& sample:graph.takeGpuTimings())record(sample);+ for(const auto& sample:graph->takeGpuTimings())record(sample);for(const auto& sample:presenter.takeGpuTimings(ctx.fence()))record(sample);};const bool traceSubframes=GetEnvironmentVariableW(L"VEYRA_TEST_TRACE_SUBFRAMES",nullptr,0)>0;@@ -894,7 +914,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(traceSubframes)traceFrame(diagnostics::TraceKind::FrameReady,item.identity,batch.batch.batchId,item.lease->readyFence,item.pts100ns,item.subframe,1,elapsedMs(watch.processStart));}}- if(!graph.resolveGeneration(batch)){++it;continue;}+ if(!graph->resolveGeneration(batch)){++it;continue;}// The GPU may finish between the first poll and resolve.// Collect its timestamps before removing this watch.if(!watch.gpuExecutionMs)collectTimings();@@ -1017,6 +1037,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// the lambdas reference below this line.OnExit stopPresentation{[&]{liveScheduler.reset();finishReset(stop_?diagnostics::ResetOutcome::Cancelled:diagnostics::ResetOutcome::Failed);std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId){if(frameFlow)snapshot_.metrics.flow=frameFlow->snapshot(host100ns());activeFlow_.reset();}}};while(!stop_){+ if(Clock::now()-cacheBudgetPolledAt>=std::chrono::milliseconds(500)){+ (void)recentGraphCache.checkBudget();cacheBudgetPolledAt=Clock::now();+ }diagnostics::CpuStallTrace loopTrace("engine-stall",frames,45.0);collectTimings();loopTrace.mark("collect");@@ -1083,7 +1106,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s{std::lock_guard lock(mutex_);requested=desired_;requestedOrder=desiredNodeOrder_;if(hasOutput)save.swap(savePath_);}if(!save.empty()){try{sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();drainLivePresentation();- if(graph.hdrOutput()){auto hdrPath=std::filesystem::path(save);hdrPath.replace_extension(L".jxr");if(sink::saveHdrScreenshot(hdrPath.wstring(),ctx,ring,graph.videoFrameResource(out.videoSlot)))status(L"HDR截图已保存:"+hdrPath.wstring());else status(L"HDR截图保存失败,请查看日志",false);}else if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}+ if(graph->hdrOutput()){auto hdrPath=std::filesystem::path(save);hdrPath.replace_extension(L".jxr");if(sink::saveHdrScreenshot(hdrPath.wstring(),ctx,ring,graph->videoFrameResource(out.videoSlot)))status(L"HDR截图已保存:"+hdrPath.wstring());else status(L"HDR截图保存失败,请查看日志",false);}else if(!sink::readRgba8(ctx,ring,graph->videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining session: {}",e.what()));status(L"保存异常,播放已保留;可再次保存",false);}}if(isImage)requested.multiplier=1;if(requested.revision==options.settings.revision&&requested!=options.settings){@@ -1179,10 +1202,34 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool preserveWorkingFg=previous.multiplier>1&&requested.multiplier>1&&(previous.frameGenerationBackend!=requested.frameGenerationBackend||previous.multiplier!=requested.multiplier||previous.vfgQuality!=requested.vfgQuality);const bool preserveWorkingNr=previous.nr&&requested.nr&&previous.nrRuntime!=requested.nrRuntime;- if(accepted&&rebuild){presenter.close();graph.shutdown();markResetStage(diagnostics::ResetStage::Destroy);accepted=initializePreview(nextDesc,next,preserveWorkingFg,preserveWorkingNr);+ if(accepted&&rebuild){+ presenter.close();bool reused=false;+ const bool mayRetain=recentCacheAllowed&&!isCapture&&!isImage&&+ RecentGraphCache::eligible(gd)&&RecentGraphCache::effectsOff(nextDesc);+ if(mayRetain&&recentGraphCache.retain(graph,RecentGraphCache::key(previous,previousOrder,gd),graphBytes)){+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,nullptr);+ graphBytes=0;+ }else{+ graph->shutdown();+ const auto cachedBytes=recentGraphCache.bytes();+ auto cached=RecentGraphCache::effectsOff(nextDesc)?std::unique_ptr<pipeline::EnhanceGraph>{}:+ recentGraphCache.take(RecentGraphCache::key(requested,requestedOrder,nextDesc));+ if(cached){graph=std::move(cached);graphBytes=cachedBytes;reused=true;}+ else{+ if(!RecentGraphCache::effectsOff(nextDesc))recentGraphCache.evict("new-enhancement-key");+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,recentGraphCache.hasCachedGraph()?nullptr:&coreCache);+ }+ }+ markResetStage(diagnostics::ResetStage::Destroy);+ accepted=reused?(graph->applySettings(requested)&&presenter.open(ctx,window,*graph,next.settings.captureCompatible,!isCapture&&!isImage)&&graph->createViews()):+ initializePreview(nextDesc,next,preserveWorkingFg,preserveWorkingNr);markResetStage(diagnostics::ResetStage::Create);- if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible,!isCapture&&!isImage)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}- }else if(accepted)accepted=graph.applySettings(requested);+ if(!accepted){+ presenter.close();graph->shutdown();recentGraphCache.evict("build-rollback");+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);graphBytes=0;+ if(!graph->initialize(gd)||!presenter.open(ctx,window,*graph,options.settings.captureCompatible,!isCapture&&!isImage)||!graph->createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}+ }+ }else if(accepted)accepted=graph->applySettings(requested);if(rebuild)publishFrameGenerationCapabilities();if(accepted){if(xessPresentationRecovery){backendRecoveryWarning=L"XeSS 呈现失败,已关闭补帧并恢复播放;错误码见日志";xessPresentationRecovery=false;}@@ -1204,7 +1251,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// reset. Without this the panel only took effect after an// unrelated rebuild (toggling NR): the "sliders do nothing" report.if(requested.revision==previous.revision&&!(requested==previous)){- if(graph.applySettings(requested)){+ if(graph->applySettings(requested)){options=PlayerOptions::from(requested,requestedOrder);{std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;}veyra::log::info("settings",std::format("live parameter update revision={} colourEnabled={} exposure={:.2f} contrast={:.2f} temperature={:.2f}",requested.revision,requested.color.enabled?1:0,requested.color.exposure,requested.color.contrast,requested.color.temperature));@@ -1256,7 +1303,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(cachedFrame){pipeline::EnhanceGraph::FrameOutputs refreshed;const double refreshPtsMs=cachedPacket.pts.toDouble()*1000.0;- if(graph.process(cachedFrame,refreshPtsMs,true,refreshed,cachedPacket.sequence,&cachedPacket.colorInfo,&cachedPacket.hardwareSurface,false,{},0,true)){+ if(graph->process(cachedFrame,refreshPtsMs,true,refreshed,cachedPacket.sequence,&cachedPacket.colorInfo,&cachedPacket.hardwareSurface,false,{},0,true)){out=refreshed;hasOutput=true;{std::lock_guard lock(mutex_);++snapshot_.pausedFrameRefreshes;}@@ -1280,8 +1327,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}if(audioStarted)audioPipe.setPaused(true);wasPaused=true;const bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;- if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView(),-1,true)){if(recoverXessPresentation())continue;status(L"画面呈现失败",true);break;}- if(hasOutput&&graph.resolveGeneration(out))completeReset(out.batch.identity);+ if(hasOutput&&!presenter.present(ctx,ring,*graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView(),-1,true)){if(recoverXessPresentation())continue;status(L"画面呈现失败",true);break;}+ if(hasOutput&&graph->resolveGeneration(out))completeReset(out.batch.identity);// Poll live view/size changes at 50 ms; unchanged flip// buffers are retained without commands or another Present.std::this_thread::sleep_for(std::chrono::milliseconds(refreshPausedFrame_?1:50));continue;@@ -1301,13 +1348,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sreturn isCapture&&!(options.fg&&presentSinkFrameGeneration(options.settings.frameGenerationBackend))&&!pendingCompletions.empty();};const auto leaseWaitStart=Clock::now();- while((liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){+ while((liveScheduler->occupancy()>=2||!graph->nextFrameSlotAvailable()||enhancementPending())&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){advanceLive();if(seekSeconds_>=0)break;- if(liveScheduler->occupancy()==0&&!graph.nextFrameSlotAvailable()&&elapsedMs(leaseWaitStart)>2000){status(L"等待输出纹理释放超时",true);stop_=true;break;}- if(liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())waitLive();+ if(liveScheduler->occupancy()==0&&!graph->nextFrameSlotAvailable()&&elapsedMs(leaseWaitStart)>2000){status(L"等待输出纹理释放超时",true);stop_=true;break;}+ if(liveScheduler->occupancy()>=2||!graph->nextFrameSlotAvailable()||enhancementPending())waitLive();std::lock_guard lock(mutex_);if(desired_.revision!=options.settings.revision)break;}- if(stop_||seekSeconds_>=0||(paused_&&!seekPreviewPending)||liveScheduler->failed()||liveScheduler->occupancy()>=2||!graph.nextFrameSlotAvailable()||enhancementPending())continue;+ if(stop_||seekSeconds_>=0||(paused_&&!seekPreviewPending)||liveScheduler->failed()||liveScheduler->occupancy()>=2||!graph->nextFrameSlotAvailable()||enhancementPending())continue;}// Wait before selecting the latest sample, not after enhancement.if(!presenter.beginSourceInput()){status(L"XeSS input timing failed",true);break;}@@ -1397,20 +1444,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,swidth=uint32_t(frame->width);height=uint32_t(frame->height);describeStages(stageRequest(options),options.snapshot(),gd);gd.hdrInput=!isImage&&activeSource->info().color.isHdrPath();gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,displayHdrActive());- presenter.close();graph.shutdown();out={};hasOutput=false;- if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible,!isCapture&&!isImage)||!graph.createViews()){status(L"串流尺寸切换失败",true);break;}+ presenter.close();graph->shutdown();recentGraphCache.evict("source-resize");+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);graphBytes=0;out={};hasOutput=false;+ if(!graph->initialize(gd)||!presenter.open(ctx,window,*graph,options.settings.captureCompatible,!isCapture&&!isImage)||!graph->createViews()){status(L"串流尺寸切换失败",true);break;}reset=true;pendingResetCause=pipeline::ResetReason::Resize;}if(vramRecoverStep){// Video memory watchdog (see watchVram): rebuild between frames, measure later.const int step=vramRecoverStep;vramRecoverStep=0;drainLivePresentation();if(!ring.drainQueue()){status(L"显存回收时排空失败",true);break;}+ recentGraphCache.evict("memory-recovery");uint64_t budget=0;ctx.videoMemoryInfo(budget,vramRecoverBefore);veyra::log::warn("vram-watch",std::format("rebuilding the {} to release video memory (usage {} MiB)",step==1?"presentation swapchain":"processing graph and swapchain",vramRecoverBefore>>20));presenter.close();- if(step==2){graph.shutdown();out={};hasOutput=false;}+ if(step==2){graph->shutdown();graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);graphBytes=0;out={};hasOutput=false;}if(step==1&&testLeakReleases)testLeak.clear();- if((step==2&&!graph.initialize(gd))||!presenter.open(ctx,window,graph,options.settings.captureCompatible,!isCapture&&!isImage)||(step==2&&!graph.createViews())){status(L"显存回收后重建失败,请重新打开片源",true);break;}+ if((step==2&&!graph->initialize(gd))||!presenter.open(ctx,window,*graph,options.settings.captureCompatible,!isCapture&&!isImage)||(step==2&&!graph->createViews())){status(L"显存回收后重建失败,请重新打开片源",true);break;}reset=true;pendingResetCause=pipeline::ResetReason::Resize;vramRecoverDone=step;vramRecoverCheckAt=Clock::now()+std::chrono::seconds(3);}@@ -1678,21 +1727,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!presenter.beginSourceProcessing()){status(L"XeSS processing timing failed",true);break;}bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();- processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg,previewFgMultiplier,(paused_||isImage)&&transaction);+ processed=!injectedReject&&graph->process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0,admitFg,previewFgMultiplier,(paused_||isImage)&&transaction);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}loopTrace.mark("graphSubmit");previewSkipSinceProcess=false;if(processed)lastProcessedPtsMs=pts;if(!processed){- const auto failedComponent=graph.failedBackend();+ const auto failedComponent=graph->failedBackend();if(!transaction){auto reduced=options.snapshot();if(SUCCEEDED(ctx.device()->GetDeviceRemovedReason())&&disableFailedBackend(reduced,failedComponent)){const auto attempted=options.snapshot();drainLivePresentation();if(!ring.drainQueue()||!ring.discardRecording()){status(L"增强故障恢复排空失败",true);break;}- out={};hasOutput=false;presenter.close();graph.shutdown();+ out={};hasOutput=false;presenter.close();graph->shutdown();{std::lock_guard lock(mutex_);reduced.revision=++nextRevision_;}options=PlayerOptions::from(reduced,options.nodeOrder);describeStages(stageRequest(options),options.snapshot(),gd);@@ -1707,9 +1756,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}}if(transaction){- ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous,previousOrder);+ ring.drainQueue();out={};presenter.close();graph->shutdown();recentGraphCache.evict("process-rollback");+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);graphBytes=0;options=PlayerOptions::from(previous,previousOrder);gd=previousDesc;- if(graph.initialize(gd)&&presenter.open(ctx,window,graph,options.settings.captureCompatible,!isCapture&&!isImage)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0)){+ if(graph->initialize(gd)&&presenter.open(ctx,window,*graph,options.settings.captureCompatible,!isCapture&&!isImage)&&graph->createViews()&&graph->process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,&pkt.hardwareSurface,comparisonMode_!=0)){publishFrameGenerationCapabilities();finishReset(diagnostics::ResetOutcome::RolledBack);std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desiredNodeOrder_=previousOrder;desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;@@ -1848,13 +1898,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst double itemPtsMs=double(item.pts100ns)/10000;const auto decisionTime=host100ns();const bool generationExpired=generated&&(isCapture?timeline.expired(item.pts100ns,decisionTime,100000):!fileAwaitingVideo&&previewGeneratedExpired(nowMs(),itemPtsMs));- const auto readiness=previewFrameReadiness(item,comparisonMode_!=0||!generatedPresentationCurrent(jobGeneration,presentationGeneration.load()),generationExpired,[&]{return graph.resolveFrame(batch,s.next);});+ const auto readiness=previewFrameReadiness(item,comparisonMode_!=0||!generatedPresentationCurrent(jobGeneration,presentationGeneration.load()),generationExpired,[&]{return graph->resolveFrame(batch,s.next);});if(traceSubframes&&generated&&(readiness==PreviewFrameReadiness::Expired||readiness==PreviewFrameReadiness::Suppressed))traceFrame(diagnostics::TraceKind::Discarded,item.identity,batch.batch.batchId,item.lease->readyFence,item.pts100ns,item.subframe,unsigned(readiness),isCapture?double(decisionTime-timeline.deadline(item.pts100ns))/10000:nowMs()-itemPtsMs);if(readiness==PreviewFrameReadiness::Pending){if(elapsedMs(s.readyStart)>2000){ctx.reportDeviceFailure("GPU-frame-ready-timeout",item.lease?item.lease->readyFence:0);- veyra::log::error("capture-present",std::format("GPU frame ready timeout nr={} nrRuntime={} source={} epoch={} revision={} subframe={} dimensions={}x{} nrDimensions={}x{} flowBackend={}",graph.nrEnabled(),nrRuntimeName(options.settings.nrRuntime),item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,item.subframe,graph.workWidth(),graph.workHeight(),graph.nrWidth(),graph.nrHeight(),opticalFlowBackendName(options.settings.opticalFlowBackend)));+ veyra::log::error("capture-present",std::format("GPU frame ready timeout nr={} nrRuntime={} source={} epoch={} revision={} subframe={} dimensions={}x{} nrDimensions={}x{} flowBackend={}",graph->nrEnabled(),nrRuntimeName(options.settings.nrRuntime),item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,item.subframe,graph->workWidth(),graph->workHeight(),graph->nrWidth(),graph->nrHeight(),opticalFlowBackendName(options.settings.opticalFlowBackend)));return {State::Failed};}return {State::Pending,host100ns()+2000};@@ -1908,7 +1958,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto presentBeginHost=host100ns();const auto begin=Clock::now();const auto before=presenter.submittedCount();presenter.reflexFrame(watch->reflexFrame);- if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView(),item.pts100ns))return {State::Failed};+ if(!presenter.present(ctx,ring,*graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView(),item.pts100ns))return {State::Failed};const auto presentEndHost=host100ns();const double returnDeviation=deviationValid?nowMs()-itemPtsMs:0;item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());@@ -2013,7 +2063,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}else{// Images have no media clock, audio or temporal batches.const auto readyStart=Clock::now();- while(!stop_&&!graph.resolveGeneration(out)){+ while(!stop_&&!graph->resolveGeneration(out)){if(elapsedMs(readyStart)>2000){status(L"图片 GPU 就绪超时",true);stop_=true;break;}deadlineWait.slice(.2);}@@ -2025,7 +2075,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sfor(auto& item:out.batch.frames){if(!item.lease)continue;const auto begin=Clock::now();const auto before=presenter.submittedCount();- if(!presenter.present(ctx,ring,graph,item.lease->slot,false,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView(),item.pts100ns)){presentFailed=true;break;}+ if(!presenter.present(ctx,ring,*graph,item.lease->slot,false,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView(),item.pts100ns)){presentFailed=true;break;}item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());framePresentMs+=elapsedMs(begin);frameFlow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());if(presenter.submittedCount()>before){++submitted;frameFlow->presented(false,item.lease->consumerFence,host100ns());}@@ -2056,18 +2106,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#endifloopTrace.mark("captureStats");diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;uint32_t slotsInFlight=0;- {measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);+ {measured=graph->gpuMetrics();graphStats=graph->metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);// Present-sink FG backends record their application-side work on// the presenter's list; surface that sample instead of leaving// the stage unmeasured. The in-graph DLSS FG keeps its own.- if(graph.xessEnabled())measured.gpu[size_t(diagnostics::GpuStage::FgBatch)]=presenter.fgTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);+ if(graph->xessEnabled())measured.gpu[size_t(diagnostics::GpuStage::FgBatch)]=presenter.fgTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;slotsInFlight=ring.inFlightCount();loopTrace.mark("gpuStats");collectTimings();loopTrace.mark("tailCollectTimings");}if(measured.identity.settingsRevision!=options.settings.revision||measured.identity.epoch!=out.batch.identity.epoch){measured={};measured.identity=out.batch.identity;for(auto& sample:measured.gpu)sample.state=diagnostics::SampleState::Pending;}- if(graph.xessEnabled()){+ if(graph->xessEnabled()){graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();}@@ -2084,9 +2134,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sloopTrace.mark("flowSnapshot");measured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();- ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=graph.videoHdrActive()?L"SDR → RTX Video HDR":options.settings.videoHdr.enabled&&!gd.hdrInput?L"SDR → SDR(HDR显示未启用)":gd.hdrOutput?(graph.hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=presentReturnDeviation.p95();- snapshot_.videoHdrActive=graph.videoHdrActive();- snapshot_.videoHdrStatus=graph.videoHdrActive()?L"预览:SDR 转 HDR 已运行":+ ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=graph->videoHdrActive()?L"SDR → RTX Video HDR":options.settings.videoHdr.enabled&&!gd.hdrInput?L"SDR → SDR(HDR显示未启用)":gd.hdrOutput?(graph->hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=presentReturnDeviation.p95();+ snapshot_.videoHdrActive=graph->videoHdrActive();+ snapshot_.videoHdrStatus=graph->videoHdrActive()?L"预览:SDR 转 HDR 已运行":!options.settings.videoHdr.enabled?L"RTX Video HDR 已关闭":gd.hdrInput?L"原生 HDR 输入,无需 SDR 转 HDR":L"当前为 SDR 预览,HDR 转换未运行";@@ -2094,7 +2144,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// over ~1s windows (1.0 = normal speed), resampled on seek.// A rejected LUT input space must be visible, not only logged// (plan v5.2: never apply a mismatched LUT silently).- if(!graph.colorLutNotice().empty())snapshot_.colorStatus+=L";"+graph.colorLutNotice();+ if(!graph->colorLutNotice().empty())snapshot_.colorStatus+=L";"+graph->colorLutNotice();const auto speedNow=Clock::now();if(playbackSpeedLastWall==Clock::time_point()||pts+0.5<playbackSpeedLastPts){playbackSpeedLastPts=pts;playbackSpeedLastWall=speedNow;}else if(std::chrono::duration<double>(speedNow-playbackSpeedLastWall).count()>=0.9){@@ -2105,14 +2155,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}snapshot_.previewSkipped=measured.flow.counters.previewSkippedBeforeGraph;snapshot_.fgBudgetLimited=measured.flow.lastFgRejected100ns>0&&host100ns()-measured.flow.lastFgRejected100ns<10000000;- snapshot_.xessGenerationSuppressed=graph.xessEnabled()&&presenter.xessGenerationSuppressed();- snapshot_.nrActive=graph.nrEnabled()&&graphStats.nrEvaluateCount>0;+ snapshot_.xessGenerationSuppressed=graph->xessEnabled()&&presenter.xessGenerationSuppressed();+ snapshot_.nrActive=graph->nrEnabled()&&graphStats.nrEvaluateCount>0;snapshot_.audioRebuffering=audioRebuffering;snapshot_.audioVideoWaits=audioPipe.videoWaitCount();snapshot_.srActive=gd.enableSr&&graphStats.srEvaluateCount>0;- snapshot_.fgActive=options.fg&&(graph.xessEnabled()?presenter.xessActive()&&graphStats.fgGeneratedFrames>0:graph.fgEnabled()&&measured.flow.counters.fgReadyValid>0);- if(transaction&&backendRecoveryWarning.empty()&&nvidiaAdapter&&(!graph.xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();- snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;+ snapshot_.fgActive=options.fg&&(graph->xessEnabled()?presenter.xessActive()&&graphStats.fgGeneratedFrames>0:graph->fgEnabled()&&measured.flow.counters.fgReadyValid>0);+ if(transaction&&backendRecoveryWarning.empty()&&nvidiaAdapter&&(!graph->xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();+ snapshot_.flowPerf=graph->actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;snapshot_.nrEvaluated=graphStats.nrEvaluateCount;snapshot_.nvofExecuted=graphStats.nvofExecuteCount;snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveScheduler?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;snapshot_.schedulingWaitP95Ms=waitP95;snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentP95;@@ -2163,7 +2213,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// Each step is logged: a session that stopped responding after a remote// play failure left "graph shutdown complete" as its last line.audioPipe.stopThread();audio.shutdown();veyra::log::info("engine","teardown: audio stopped");- ring.drainQueue();presenter.close();graph.shutdown();+ ring.drainQueue();presenter.close();graph->shutdown();recentGraphCache.evict("session-close");(void)coreCache.close();veyra::log::info("engine","teardown: closing sources");captureSource.close();screenSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);diff --git a/tests/perf/NrRecentCacheExperiment.cpp b/tests/perf/NrRecentCacheExperiment.cppnew file mode 100644index 00000000..cb1ccbec--- /dev/null+++ b/tests/perf/NrRecentCacheExperiment.cpp@@ -0,0 +1,97 @@+#include "veyra/engine/RecentGraphCache.h"+#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/ngx/NgxCoreCache.h"+#include "veyra/source/MediaFileSource.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/RuntimePaths.h"+#include <d3d12sdklayers.h>+#include <bcrypt.h>+#include <array>+#include <chrono>+#include <fstream>+#include <iostream>++// Real cached product graphs, natural changing frames, full-image readbacks+// outside the create timing. Same executable opt-out is the fresh-graph control.+namespace {+std::string sha(const std::vector<uint8_t>& pixels){BCRYPT_ALG_HANDLE alg=nullptr;BCRYPT_HASH_HANDLE hash=nullptr;std::array<unsigned char,32> digest{};+ if(BCryptOpenAlgorithmProvider(&alg,BCRYPT_SHA256_ALGORITHM,nullptr,0)<0)return {};+ const bool ok=BCryptCreateHash(alg,&hash,nullptr,0,nullptr,0,0)>=0&&BCryptHashData(hash,const_cast<PUCHAR>(pixels.data()),ULONG(pixels.size()),0)>=0&&BCryptFinishHash(hash,digest.data(),32,0)>=0;+ if(hash)BCryptDestroyHash(hash);BCryptCloseAlgorithmProvider(alg,0);if(!ok)return {};std::string s;const char* hex="0123456789abcdef";for(auto c:digest){s+=hex[c>>4];s+=hex[c&15];}return s;}+}+int wmain(int argc,wchar_t** argv){+ using namespace veyra;using Clock=std::chrono::steady_clock;+ if(argc!=3)return 2;const std::filesystem::path out=argv[2];std::filesystem::create_directories(out);+ Logger::instance().openFile((out/L"engine.log").wstring());+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;+ gfx::DeviceContextDesc device;device.enableDebugLayer=true;+ if(!ctx.initialize(device,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,status))return 2;+ source::MediaFileSource media;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;+ if(!media.open(open)||media.info().width!=1920||media.info().height!=1080)return 2;+ ngx::NgxCoreCache core;engine::RecentGraphCache cache(ctx);+ std::unique_ptr<pipeline::EnhanceGraph> graph;+ const bool enabled=!GetEnvironmentVariableW(L"VEYRA_TEST_DISABLE_RECENT_GRAPH_CACHE",nullptr,0);+ engine::EnhancementSettings prior;pipeline::EnhanceGraphDesc priorDesc;uint64_t graphBytes=0;+ auto memory=[&](){uint64_t budget=0,usage=0;return ctx.videoMemoryInfo(budget,usage)?usage:UINT64_MAX;};+ std::ofstream csv(out/L"cache.csv");csv<<"cycle,nr,hit,createMs,vramBefore,vramLive,graphBytes,nrEvaluations,sourceFrame,sha256\n";+ bool pass=true;unsigned hits=0;+ for(unsigned cycle=0;cycle<50&&pass;++cycle){+ const bool nr=cycle%2==0;engine::EffectChain chain;chain.nodeCount=1;+ chain.nodes[0].type=engine::EffectType::NrEnhance;chain.nodes[0].enabled=nr;+ chain.nodes[0].nr.temporal=false;chain.nodes[0].nr.sizePolicy=pipeline::NrSizePolicy::Realtime;+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.revision=cycle+1;settings.multiplier=1;+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=nr;+ pipeline::EnhanceGraphDesc desc;engine::describeStages(request,settings,desc);+ desc.enableNvofStandalone=nr;desc.enableFg=false;desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ if(!ring.drainQueue())return 2;+ if(graph){+ if(enabled&&engine::RecentGraphCache::eligible(priorDesc)&&engine::RecentGraphCache::effectsOff(desc)&&+ cache.retain(graph,engine::RecentGraphCache::key(prior,{},priorDesc),graphBytes)){}+ else{graph->shutdown();graph.reset();}+ }+ const auto cachedBytes=cache.bytes();bool hit=false;+ const auto before=memory();const auto start=Clock::now();+ if(enabled&&nr)graph=cache.take(engine::RecentGraphCache::key(settings,{},desc));+ if(graph){hit=true;graphBytes=cachedBytes;pass=graph->applySettings(settings);++hits;}+ else{+ if(nr)cache.evict("new-enhancement-key");+ graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,cache.hasCachedGraph()?nullptr:&core);+ pass=graph->initialize(desc);const auto after=memory();graphBytes=after>before?after-before:0;+ }+ pass=pass&&graph->createViews()&&ring.waitIdle();+ const auto createMs=std::chrono::duration<double,std::milli>(Clock::now()-start).count();const auto live=memory();+ // Every on/off pair uses a different natural interval. Reset remains+ // mandatory even when the feature and its textures are retained.+ if(pass&&!media.seek({int64_t(cycle<20?0:cycle/2-10)*200,1000}))pass=false;+ const auto priorMetrics=graph->metrics();sink::RgbaImage image;uint64_t sequence=0;+ for(unsigned frame=0;frame<3&&pass;++frame){+ pipeline::FramePacket packet;const AVFrame* input=nullptr;pipeline::EnhanceGraph::FrameOutputs output;+ pass=media.read(packet,&input)==source::SourceReadStatus::Frame&&+ graph->process(input,packet.pts.toDouble()*1000,frame==0,output,packet.sequence,&packet.colorInfo)&&ring.waitIdle();+ sequence=packet.sequence;+ if(pass&&frame==2)pass=sink::readRgba8(ctx,ring,graph->videoFrameResource(output.videoSlot),image);+ }+ const auto nrDelta=graph->metrics().nrEvaluateCount-priorMetrics.nrEvaluateCount;+ pass=pass&&nrDelta==unsigned(nr?3:0);+ const auto hash=sha(image.pixels);pass=pass&&!hash.empty();+ if(pass&&(cycle==0||cycle==1||cycle==2||cycle==18||cycle==20||cycle==30||cycle==48||cycle==49)){std::ofstream f(out/(L"frame-"+std::to_wstring(cycle)+L".rgba"),std::ios::binary);+ f.write(reinterpret_cast<const char*>(image.pixels.data()),std::streamsize(image.pixels.size()));}+ csv<<cycle<<','<<nr<<','<<hit<<','<<createMs<<','<<before<<','<<live<<','<<graphBytes<<','<<nrDelta<<','<<sequence<<','<<hash<<'\n';csv.flush();+ std::cout<<"CACHE_CYCLE i="<<cycle<<" hit="<<hit<<" createMs="<<createMs<<" pass="<<pass<<std::endl;+ prior=settings;priorDesc=desc;+ }+ ring.drainQueue();if(graph){graph->shutdown();graph.reset();}cache.evict("test-close");+ pass=core.close("test-close")&&pass;media.close();+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;unsigned errors=0;+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&debug))))return 2;+ for(UINT64 i=0;i<debug->GetNumStoredMessages();++i){SIZE_T size=0;debug->GetMessage(i,nullptr,&size);+ std::vector<unsigned char> data(size);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());+ if(FAILED(debug->GetMessage(i,m,&size)))return 2;+ if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<m->pDescription<<std::endl;}}+ const auto removed=ctx.device()->GetDeviceRemovedReason();pass=pass&&errors==0&&SUCCEEDED(removed);+ std::cout<<"CACHE_RESULT pass="<<pass<<" hits="<<hits<<" debugErrors="<<errors+ <<" deviceRemoved="<<unsigned(removed)<<" afterFinalClose="<<memory()<<std::endl;+ return pass?0:1;+}