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: admit measured compute graph and migrate queues at drained rebuilds

Veyra Goal Agent98a717bbb5fa
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 210849f6..9579d362 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1048,6 +1048,10 @@ add_executable(veyra_sr_reconstruction_tests tests/integration/SrReconstructionT
target_compile_features(veyra_nr_graph_queue_experiment PRIVATE cxx_std_20)
target_compile_options(veyra_nr_graph_queue_experiment PRIVATE /utf-8)
target_link_libraries(veyra_nr_graph_queue_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)
+ target_link_libraries(veyra_nr_queue_migration_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/docs/PERF_3C_GRAPH_NORMAL_2026-10-05.md b/docs/PERF_3C_GRAPH_NORMAL_2026-10-05.md
index 968a8b5a..13f476bc 100644
--- a/docs/PERF_3C_GRAPH_NORMAL_2026-10-05.md
+++ b/docs/PERF_3C_GRAPH_NORMAL_2026-10-05.md
@@ -16,3 +16,11 @@ COMPUTE普通增强区间中位降低8.93%(2X)/7.66%(3X)。这不是纯
全部源帧跳过计数0。2X各轮生成过期2;3X DIRECT各轮3,COMPUTE普通4/4/5,HIGH各轮4;不隐藏这一差异。UI Timer最大片段83ms,不能冒充渲染帧率或证明全程无卡顿。多数轮在源帧303/304处仍有约98–109ms engine循环,graphSubmit约66–77ms;DIRECT/COMPUTE都有,R0根因继续排查。
命令:`py -3.11 -B scripts/perf/nr-graph-normal.py B2d B3c-graph-normal-v1`。原始18轮:`E:/项目/Veyra/logs/perf-nr-20261004/B3c-graph-normal-v1-*`;汇总`B3c-graph-normal-v1-summary/comparison.json`、`per-run.csv`、`artifacts.json`。当前计算队列仍是测试环境变量候选,尚未自动扩大到AMD/VFG/FSR/XeSS/HDR/节点模式;需补队列迁移/后端回退/预热/最近实例缓存验收后才能保留生产入口。
+
+## 生产准入候选与验收边界
+
+自动COMPUTE仅准入本机已测PCI 10DE:2F04、文件1920×1080、双层非时域1080p NR、Lecram选择、DLSS SR 4K、DLSS2X/3X、NVOF、SDR列表图。其他设备、采集、图片、HDR、VFG/FSR/XeSS、节点图、时域NR和其他尺寸保留DIRECT,不以5070证据扩大支持承诺。没有新增HIGH默认或篡改运行库/驱动。未来拓宽准入需补该组合证据。
+
+队列只在排空后的图重建切换:先创建替代allocator/list/timestamp资源,成功后排空旧队列再交换,保留同一fence递增值。失败保留旧DIRECT,不能降为无效果伪装成功;回到DIRECT失败则旧配置恢复或停止报告。队列变化驱逐最近图,单NR缓存/预热仍走原DIRECT,不破坏已保留优化。修正discardRecording失败重建列表时固定DIRECT的类型错误。定向native逐帧全图/PTS测试包含4次往返、十项不兼容准入及队列创建失败回退,真实Qt再检查后端切换;尚未执行结果不标通过。
+
+构建v1/v3通过。v2新增fixture误写不存在的Fsr3枚举导致编译失败,改为既有Fsr;日志build-queue-admission-v2.log保留。新增测试只在E盘隔离profile和产物运行,无压力或用户应用修改。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index decc0df4..1c680e82 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -8271,3 +8271,6 @@ build-priority-load-v1 2步exit0。本轮三NR竞争fixture SHA a46c2923ab4b7a20
# 2026-10-05 3c完整图普通负载18组结束
执行`py -3.11 -B scripts/perf/nr-graph-normal.py B2d B3c-graph-normal-v1`,18/18正常产品检查通过,无额外竞争/人工显存压力,测试前后全部产品payload SHA一致。2X DIRECT普通→COMPUTE普通增强21.386→19.477ms;3X23.330→21.542ms,三轮中位,约8.93%/7.66%。源跳过全0,3X生成过期DIRECT3→COMPUTE4/4/5;软件Present P99无明显改善,约70ms尾部与frame303/304图提交仍存在,不宣称卡顿根治。HIGH继续拒绝默认。数据/设置/身份/完整异常E:/项目/Veyra/logs/perf-nr-20261004/B3c-graph-normal-v1-summary和各18轮,详docs/PERF_3C_GRAPH_NORMAL_2026-10-05.md。guard 113路径通过;下一步生产队列迁移/回退与缓存兼容。
+# 2026-10-05 3c生产队列准入候选
+
+before 6bc2a33 / checkpoint/perf-nr-3c-queue-admission-before-20261004。PreviewGpuSession增加限定本机已验双NR+SR4K+DLSS2/3X文件图的自动COMPUTE,其余保留DIRECT;CommandSlotRing事务换队列保留递增fence、错误保留旧资源,最近缓存只在实际换队列时驱逐;所有呈现仍普通DIRECT。Engine重建/旧配置恢复接入,采集/图片禁自动。修正discardRecording错误恢复的list类型。build-queue-admission-v1/v3通过;v2测试枚举Fsr3笔误编译失败、改既有Fsr,失败证据保留E:/项目/Veyra/logs/perf-nr-20261004。将执行native9组往返/全图/PTS/错误回退和真实Qt后端切换,未执行不标验收通过。
diff --git a/include/veyra/engine/PreviewGpuSession.h b/include/veyra/engine/PreviewGpuSession.h
index 5054da80..e6b95a1a 100644
--- a/include/veyra/engine/PreviewGpuSession.h
+++ b/include/veyra/engine/PreviewGpuSession.h
@@ -8,7 +8,7 @@ namespace veyra::engine {
// moves from idle prewarm to playback; no second device or snippet Init owner.
struct PreviewGpuSession {
gfx::D3D12DeviceContext context;
- Microsoft::WRL::ComPtr<ID3D12CommandQueue> executionQueue; // optional experimental compute producer
+ Microsoft::WRL::ComPtr<ID3D12CommandQueue> executionQueue;
gfx::CommandSlotRing ring;
ngx::NgxCoreCache core;
RecentGraphCache recent{context};
@@ -17,6 +17,8 @@ struct PreviewGpuSession {
std::optional<RecentGraphCache::Key> prepared;
~PreviewGpuSession();
bool initialize(unsigned slots=16);
+ static bool computeAllowed(const gfx::AdapterInfo&,const pipeline::EnhanceGraphDesc&);
+ bool configureQueue(const pipeline::EnhanceGraphDesc&,bool allowAutomatic=true); // drained graph rebuild only
static bool requestAllowed(const EnhancementSettings&);
bool prepare(EnhancementSettings,unsigned width,unsigned height);
bool adopt(const EnhancementSettings&,const pipeline::EnhanceGraphDesc&);
diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.h
index 2c4a67b2..3b779448 100644
--- a/include/veyra/gfx/CommandSlotRing.h
+++ b/include/veyra/gfx/CommandSlotRing.h
@@ -39,6 +39,9 @@ public:
uint32_t slotCount,
Status& status);
void shutdown();
+ // Graph rebuild only: create replacements first, drain the old queue, then
+ // swap lists without restarting this fence's strictly monotonic timeline.
+ bool rebindQueue(ID3D12CommandQueue* queue,Status& status);
uint32_t slotCount() const { return slotCount_; }
bool initialized() const { return initialized_; }
diff --git a/scripts/perf/nr-queue-migration.py b/scripts/perf/nr-queue-migration.py
new file mode 100644
index 00000000..b814f2d7
--- /dev/null
+++ b/scripts/perf/nr-queue-migration.py
@@ -0,0 +1,35 @@
+"""Full graph pixels/fence monotonicity across ordinary compute/direct migrations."""
+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];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_queue_migration_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe);results=[]
+for repeat in range(1,4):
+ for mode in ('direct','auto','creation-fallback'):
+ matrix.assert_gpu_tests_idle();name=f'{label}-{mode}-r{repeat}';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=='direct':env['VEYRA_TEST_GRAPH_DIRECT']='1'
+ if mode=='creation-fallback':env['VEYRA_TEST_GRAPH_CREATE_FAIL']='1'
+ command=[str(exe),str(matrix.SOURCES['M1']),str(out)];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=150).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('QUEUE_MIGRATION_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,'mode':mode,'repeat':repeat,'command':command,'testEnv':{k:v for k,v in env.items() if k.startswith('VEYRA_TEST_')},'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 and metrics.get('migrations')==(4 if mode=='auto' else 0),
+ 'measurement':'Full pixels/PTS across queue rebuilds with diagnostic waits/readback; not throughput; no extra competing process'}
+ (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)
+ if not result['passed']:print(text[-4500:],flush=True);raise SystemExit(1)
+reference=results[0]['frames'];comparisons=[{'name':r['name'],'rowCount':len(r['frames']),'differentRows':sum(a!=b for a,b in zip(reference,r['frames'])),'equalCount':len(reference)==len(r['frames'])} for r in results]
+passed=all(r['equalCount'] and r['differentRows']==0 for r in comparisons)
+(BASE/'logs'/TASK/(label+'-summary.json')).write_text(json.dumps({'results':results,'comparisons':comparisons,'passed':passed},ensure_ascii=False,indent=2),encoding='utf-8')
+print('QUEUE_MIGRATION_COMPLETE',passed,comparisons,flush=True);raise SystemExit(0 if passed else 1)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index b72cdd2e..5ca998a3 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -580,6 +580,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
uint64_t buildBudget=0,buildUsage=0;const bool measuredBefore=ctx.videoMemoryInfo(buildBudget,buildUsage);
const bool adopted=gpu->adopt(selected.snapshot(),desc);
+ if(!adopted&&!gpu->configureQueue(desc,!isCapture&&!isImage))return false;
bool opened=adopted||graph->initialize(desc);
auto failure=graph->failedBackend();
if(opened){
@@ -1262,7 +1263,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
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;}
+ if(!gpu->configureQueue(gd,!isCapture&&!isImage)||!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();
diff --git a/src/engine/PreviewGpuSession.cpp b/src/engine/PreviewGpuSession.cpp
index bc66ce04..851cd510 100644
--- a/src/engine/PreviewGpuSession.cpp
+++ b/src/engine/PreviewGpuSession.cpp
@@ -3,6 +3,7 @@
#include "veyra/engine/EngineController.h"
#include "veyra/gfx/GpuSchedulingPriority.h"
#include "veyra/RuntimePaths.h"
+#include <algorithm>
#include <chrono>
namespace veyra::engine {
@@ -26,6 +27,43 @@ bool PreviewGpuSession::requestAllowed(const EnhancementSettings& settings){
!settings.videoHdr.enabled&&!settings.color.enabled&&settings.additionalColorCount==0&&
(settings.videoSrQuality==0||settings.videoSrQuality==4);
}
+bool PreviewGpuSession::computeAllowed(const gfx::AdapterInfo& adapter,const pipeline::EnhanceGraphDesc& desc){
+ // Initial automatic admission is deliberately the ordinary-load configuration
+ // actually measured (18 Qt runs + 2502 full outputs). Other devices/providers
+ // keep DIRECT until their own evidence supports widening this set.
+ return adapter.isNvidia&&adapter.deviceId==0x2f04&&desc.sourceWidth==1920&&desc.sourceHeight==1080&&
+ desc.workWidth==3840&&desc.workHeight==2160&&desc.enableNr&&desc.enableSr&&desc.videoSrQuality==0&&
+ !desc.noFeatures&&!desc.noNgx&&!desc.stillImage&&
+ desc.nrRuntime==NrRuntime::Original&&desc.nrLayersExtent.size()==2&&
+ desc.nrLayersExtent[0]==pipeline::Extent{1920,1080}&&desc.nrLayersExtent[1]==pipeline::Extent{1920,1080}&&
+ !desc.nrBeforeSr&&!desc.runtimeNodeOrder&&!desc.hdrInput&&!desc.hdrOutput&&!desc.videoHdr.enabled&&
+ !desc.color.enabled&&!desc.additionalColorCount&&!desc.nrHoldStrength&&
+ !desc.nrTemporal&&std::none_of(desc.nrLayersTemporal.begin(),desc.nrLayersTemporal.end(),[](bool enabled){return enabled;})&&
+ desc.opticalFlowBackend==OpticalFlowBackend::Nvidia&&desc.enableFg&&
+ desc.frameGenerationBackend==FrameGenerationBackend::Dlss&&(desc.fgMultiplier==2||desc.fgMultiplier==3);
+}
+bool PreviewGpuSession::configureQueue(const pipeline::EnhanceGraphDesc& desc,bool allowAutomatic){
+ if(!ring.initialized())return false;
+ const bool compute=GetEnvironmentVariableW(L"VEYRA_TEST_GRAPH_COMPUTE",nullptr,0)||
+ (allowAutomatic&&!GetEnvironmentVariableW(L"VEYRA_TEST_GRAPH_DIRECT",nullptr,0)&&computeAllowed(context.adapter(),desc));
+ if((ring.queue()->GetDesc().Type==D3D12_COMMAND_LIST_TYPE_COMPUTE)==compute)return true;
+ Microsoft::WRL::ComPtr<ID3D12CommandQueue> candidate;
+ if(compute){
+ D3D12_COMMAND_QUEUE_DESC queueDesc{};queueDesc.Type=D3D12_COMMAND_LIST_TYPE_COMPUTE;
+ const HRESULT hr=GetEnvironmentVariableW(L"VEYRA_TEST_GRAPH_CREATE_FAIL",nullptr,0)?E_OUTOFMEMORY:
+ context.device()->CreateCommandQueue(&queueDesc,IID_PPV_ARGS(&candidate));
+ log::info("graph-queue",std::format("requested=COMPUTE createHr=0x{:X} automatic={}",unsigned(hr),!GetEnvironmentVariableW(L"VEYRA_TEST_GRAPH_COMPUTE",nullptr,0)));
+ if(FAILED(hr)){log::warn("graph-queue","COMPUTE unavailable; retaining DIRECT");return true;}
+ candidate->SetName(L"Veyra compute producer");
+ }
+ Status status=Status::Ok;
+ if(!ring.rebindQueue(compute?candidate.Get():context.directQueue(),status)){
+ log::warn("graph-queue",std::format("queue migration failed requestedCompute={} status={}",compute,unsigned(status)));
+ return compute&&SUCCEEDED(context.device()->GetDeviceRemovedReason());
+ }
+ recent.evict("queue-migration");prepared.reset();executionQueue=std::move(candidate);
+ log::info("graph-queue",std::format("selected={} fence={} cacheEvicted=true",compute?"COMPUTE":"DIRECT",ring.lastSignaledValue()));return true;
+}
bool PreviewGpuSession::prepare(EnhancementSettings settings,unsigned width,unsigned height){
if(!requestAllowed(settings)||width<64||height<64||width>3840||height>2160)return false;
const auto start=std::chrono::steady_clock::now();settings=PlayerOptions::from(settings).snapshot();
diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cpp
index 88c8410e..8e4a2e15 100644
--- a/src/gfx/CommandSlotRing.cpp
+++ b/src/gfx/CommandSlotRing.cpp
@@ -106,6 +106,38 @@ void CommandSlotRing::shutdown()
veyra::log::info("gfx", "slot-ring: shutdown complete");
}
+bool CommandSlotRing::rebindQueue(ID3D12CommandQueue* queue,Status& status){
+ if(!initialized_||!queue){status=Status::InvalidArgument;return false;}
+ if(queue==queue_)return true;
+ const auto type=queue->GetDesc().Type;
+ if(type!=D3D12_COMMAND_LIST_TYPE_DIRECT&&type!=D3D12_COMMAND_LIST_TYPE_COMPUTE){status=Status::InvalidArgument;return false;}
+ for(const auto& slot:slots_)if(slot.recording){status=Status::InvalidArgument;log::error("gfx","queue-rebind rejected: command list still recording");return false;}
+ // Local replacements leave the currently working ring intact on failure.
+ std::vector<Slot> replacement(slotCount_);
+ for(uint32_t i=0;i<slotCount_;++i){
+ HRESULT hr=device_->CreateCommandAllocator(type,IID_PPV_ARGS(&replacement[i].allocator));
+ if(SUCCEEDED(hr))hr=device_->CreateCommandList(0,type,replacement[i].allocator.Get(),nullptr,IID_PPV_ARGS(&replacement[i].list));
+ if(SUCCEEDED(hr))hr=replacement[i].list->Close();
+ if(FAILED(hr)){status=Status::DeviceFailure;log::error("gfx",std::format("queue-rebind lists slot={} hr=0x{:X}",i,unsigned(hr)));return false;}
+ replacement[i].list->SetName(std::format(L"Veyra rebound slot {}",i).c_str());
+ }
+ ComPtr<ID3D12QueryHeap> heap;ComPtr<ID3D12Resource> readback;
+ D3D12_QUERY_HEAP_DESC query{};query.Type=D3D12_QUERY_HEAP_TYPE_TIMESTAMP;query.Count=slotCount_*2;
+ UINT64 frequency=0;HRESULT hr=queue->GetTimestampFrequency(&frequency);
+ if(SUCCEEDED(hr)&&frequency)hr=device_->CreateQueryHeap(&query,IID_PPV_ARGS(&heap));
+ else if(SUCCEEDED(hr))hr=E_FAIL;
+ D3D12_HEAP_PROPERTIES props{};props.Type=D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC desc{};desc.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;desc.Width=slotCount_*2*sizeof(uint64_t);
+ desc.Height=1;desc.DepthOrArraySize=1;desc.MipLevels=1;desc.SampleDesc.Count=1;desc.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ if(SUCCEEDED(hr))hr=device_->CreateCommittedResource(&props,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback));
+ if(FAILED(hr)){status=Status::DeviceFailure;log::error("gfx",std::format("queue-rebind timestamps hr=0x{:X}",unsigned(hr)));return false;}
+ if(!drainQueue()){status=Status::DeviceFailure;return false;}
+ queue_=queue;slots_.swap(replacement);timestampHeap_=std::move(heap);timingReadback_=std::move(readback);
+ timestampFrequency_=frequency;nextSlot_=0;gpuCommandTimesMs_.clear();gpuCommandTimesCursor_=0;
+ status=Status::Ok;log::info("gfx",std::format("queue-rebind type={} frequencyHz={} nextFence={} slots={}",unsigned(type),frequency,nextFenceValue_,slotCount_));
+ return true;
+}
+
ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& status)
{
if (!initialized_ || slot >= slotCount_) {
@@ -208,7 +240,7 @@ uint32_t CommandSlotRing::inFlightCount() const
}
bool CommandSlotRing::discardRecording(){
- bool ok=true;for(uint32_t i=0;i<slots_.size();++i){auto& s=slots_[i];if(s.recording){const HRESULT hr=s.list->Close();s.recording=false;s.timed=false;s.label.clear();veyra::log::info("gfx",std::format("discard unsubmitted command list slot={} hr=0x{:X}",i,unsigned(hr)));if(FAILED(hr)){s.list.Reset();const HRESULT created=device_->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,s.allocator.Get(),nullptr,IID_PPV_ARGS(&s.list));if(FAILED(created)||FAILED(s.list->Close()))ok=false;}}}return ok;
+ bool ok=true;for(uint32_t i=0;i<slots_.size();++i){auto& s=slots_[i];if(s.recording){const HRESULT hr=s.list->Close();s.recording=false;s.timed=false;s.label.clear();veyra::log::info("gfx",std::format("discard unsubmitted command list slot={} hr=0x{:X}",i,unsigned(hr)));if(FAILED(hr)){s.list.Reset();const HRESULT created=device_->CreateCommandList(0,queue_->GetDesc().Type,s.allocator.Get(),nullptr,IID_PPV_ARGS(&s.list));if(FAILED(created)||FAILED(s.list->Close()))ok=false;}}}return ok;
}
bool CommandSlotRing::drainQueue()
{
diff --git a/tests/perf/NrQueueMigrationExperiment.cpp b/tests/perf/NrQueueMigrationExperiment.cpp
new file mode 100644
index 00000000..53b3b116
--- /dev/null
+++ b/tests/perf/NrQueueMigrationExperiment.cpp
@@ -0,0 +1,58 @@
+#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!=3)return 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=2;
+ for(unsigned i=0;i<2;++i){chain.nodes[i].type=engine::EffectType::NrEnhance;chain.nodes[i].enabled=true;chain.nodes[i].nr.temporal=false;chain.nodes[i].nr.sizePolicy=pipeline::NrSizePolicy::Realtime;}
+ engine::EnhancementSettings settings;engine::fromChain(chain,settings);settings.sr=true;settings.videoSrQuality=0;settings.srTarget=pipeline::SrTarget::Uhd4K;settings.multiplier=2;
+ engine::StageRequest request;request.width=1920;request.height=1080;request.nr=true;request.sr=true;request.fg=true;request.fgMultiplier=2;
+ pipeline::EnhanceGraphDesc base;engine::describeStages(request,settings,base);base.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ engine::PreviewGpuSession session;if(!session.initialize())return 2;
+ const auto adapter=session.context.adapter();bool pass=engine::PreviewGpuSession::computeAllowed(adapter,base);unsigned exclusions=0;
+ auto excluded=[&](pipeline::EnhanceGraphDesc desc){++exclusions;pass=!engine::PreviewGpuSession::computeAllowed(adapter,desc)&&pass;};
+ auto incompatible=base;incompatible.nrRuntime=engine::NrRuntime::LmxxfAmd;excluded(incompatible);
+ for(auto backend:{engine::FrameGenerationBackend::Vfg,engine::FrameGenerationBackend::XeSS,engine::FrameGenerationBackend::Fsr}){incompatible=base;incompatible.frameGenerationBackend=backend;excluded(incompatible);}
+ incompatible=base;incompatible.hdrInput=true;excluded(incompatible);incompatible=base;incompatible.color.enabled=true;excluded(incompatible);
+ incompatible=base;incompatible.nrLayersTemporal[0]=true;excluded(incompatible);incompatible=base;incompatible.runtimeNodeOrder=true;excluded(incompatible);
+ incompatible=base;incompatible.opticalFlowBackend=engine::OpticalFlowBackend::AmdFidelityFx;excluded(incompatible);
+ auto other=adapter;other.deviceId=0x2684;pass=!engine::PreviewGpuSession::computeAllowed(other,base)&&pass;++exclusions;
+ std::ofstream frames(out/L"frames.csv");frames<<"phase,frame,subframe,pts100ns,width,height,sha256\n";unsigned real=0,generated=0,migrations=0;uint64_t lastFence=0;
+ for(unsigned phase=0;phase<4&&pass;++phase){
+ auto desc=base;if(phase%2){desc.enableNr=desc.enableSr=desc.enableFg=false;desc.noFeatures=true;desc.fixedExecutionPlan.reset();}
+ pass=session.ring.drainQueue()&&session.ring.discardRecording();session.graph->shutdown();
+ session.graph=std::make_unique<pipeline::EnhanceGraph>(session.context,session.ring,&session.core);
+ const auto previousType=session.ring.queue()->GetDesc().Type;
+ pass=pass&&session.configureQueue(desc)&&session.graph->initialize(desc)&&session.graph->createViews();
+ const bool expectedCompute=phase%2==0&&!GetEnvironmentVariableW(L"VEYRA_TEST_GRAPH_DIRECT",nullptr,0)&&!GetEnvironmentVariableW(L"VEYRA_TEST_GRAPH_CREATE_FAIL",nullptr,0);
+ pass=pass&&((session.ring.queue()->GetDesc().Type==D3D12_COMMAND_LIST_TYPE_COMPUTE)==expectedCompute);
+ if(previousType!=session.ring.queue()->GetDesc().Type)++migrations;
+ source::MediaFileSource source;source::SourceOpenDesc open;open.path=argv[1];open.preferHardwareDecode=false;pass=pass&&source.open(open);
+ for(unsigned i=0;i<24&&pass;++i){
+ pipeline::FramePacket packet;const AVFrame* input=nullptr;pipeline::EnhanceGraph::FrameOutputs output;
+ pass=source.read(packet,&input)==source::SourceReadStatus::Frame&&session.graph->process(input,packet.pts.toDouble()*1000,i==0,output,packet.sequence,&packet.colorInfo)&&session.ring.waitIdle();
+ if(pass&&desc.enableFg){for(unsigned spin=0;spin<1000&&!session.graph->resolveGeneration(output);++spin)Sleep(1);pass=output.gpuComplete();}
+ auto record=[&](ID3D12Resource* texture,unsigned subframe,int64_t pts){sink::RgbaImage image;const bool ok=sink::readRgba8(session.context,session.ring,texture,image);
+ if(ok){frames<<phase<<','<<i<<','<<subframe<<','<<pts<<','<<image.width<<','<<image.height<<','<<sha256Hex(image.pixels.data(),image.pixels.size())<<'\n';frames.flush();}return ok;};
+ if(pass){pass=record(session.graph->videoFrameResource(output.videoSlot),0,int64_t(packet.pts.toDouble()*10000000));++real;}
+ for(unsigned f=0;f<output.batch.count&&pass;++f){const auto& item=output.batch.frames[f];if(item.kind!=pipeline::FrameKind::Generated)continue;pass=item.validity==pipeline::GenerationValidity::Valid&&item.lease&&record(item.lease->texture.Get(),item.subframe,item.pts100ns);if(pass)++generated;}
+ pass=pass&&session.ring.lastSignaledValue()>lastFence;lastFence=session.ring.lastSignaledValue();
+ }
+ source.close();
+ }
+ session.ring.drainQueue();session.graph->shutdown();pass=session.core.close("migration-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 bytes=0;debug->GetMessage(i,nullptr,&bytes);std::vector<unsigned char> data(bytes);auto* m=reinterpret_cast<D3D12_MESSAGE*>(data.data());
+ if(FAILED(debug->GetMessage(i,m,&bytes)))return 2;if(m->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){++errors;std::cerr<<"DEBUG_ERROR "<<m->pDescription<<std::endl;}}
+ const HRESULT removed=session.context.device()->GetDeviceRemovedReason();pass=pass&&real==96&&generated==46&&errors==0&&SUCCEEDED(removed);
+ debug.Reset();session.shutdown();std::cout<<"QUEUE_MIGRATION_RESULT pass="<<pass<<" real="<<real<<" generated="<<generated<<" migrations="<<migrations<<" exclusions="<<exclusions<<" fence="<<lastFence<<" debugErrors="<<errors<<" removed="<<unsigned(removed)<<std::endl;return pass?0:1;
+}