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

test(perf): verify prefetch output and separate creation from pipeline time

Veyra Goal Agentf07f6c3ad4fd
diff --git a/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md b/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md
index 24e293d1..c91992d4 100644
--- a/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md
+++ b/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md
@@ -13,3 +13,7 @@
候选按上述结构实现,`VEYRA_TEST_EXPORT_NVOF_PREFETCH=1`才创建辅助图;主图消费导入快照时维持GPU侧fence依赖,生产默认无快照/额外队列。准备过程复用实际EnhanceGraph,不复制颜色/光流算法。主图计数另记prefetchedFlowCount,辅助图实际NVOF execute仍有日志,不冒充主图常规execute。关闭辅助图先等各快照consumer,再drain/注销,原Graph reset仍按自己的真实luma/PTS分析并与快照描述匹配。下一步编译和真实输出/正常耗时证据;尚未声明通过。
build-nvof-prefetch-v1失败,FlowPrefetch初始化误写不存在的nrLayers成员(正确并行数组为nrLayersExtent/Model等);删除多余访问后进行有据的第二次构建,原失败日志保留。不将编译失败当成运行时/硬件失败。
+
+v2构建成功;B5b-prefetch-smoke-v1七个真实debug导出通过,单/双NR、NR+SR4K整文件SHA各自同off,取消清理通过,debug0/removed0;每个24帧组实际导入23个flow,原NVOF执行0,辅助图确有23次NVOF执行。raw目录同任务logs。此小样本的处理计时包含辅助图创建,尚不能用于稳态提速结论:下一构建将计时起点放在辅助图创建之后,整次导出仍包含创建。没有改写旧数据。
+
+追加独立trace开关,只在诊断组记录真实GPU Flow/NR/SR timestamp,按每个队列GetClockCalibration映射到QPC并保留调用耗时界限,禁止用裸跨队列计数相同直接证明重叠。依据[微软GetClockCalibration文档](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12commandqueue-getclockcalibration);正常性能三轮trace关闭,以免日志干扰。最终是否保留仍需整次/稳态和额外显存的收益风险比较。
diff --git a/include/veyra/diagnostics/GpuQueueTrace.h b/include/veyra/diagnostics/GpuQueueTrace.h
new file mode 100644
index 00000000..e50f79ef
--- /dev/null
+++ b/include/veyra/diagnostics/GpuQueueTrace.h
@@ -0,0 +1,30 @@
+#pragma once
+#include "veyra/diagnostics/FrameMetrics.h"
+#include "veyra/Log.h"
+#include <format>
+namespace veyra::diagnostics {
+// Test-only timestamp trace. Cross-queue timestamps require each queue's
+// calibration; numerical equality of raw counters alone proves no overlap.
+class GpuQueueTrace {
+ ID3D12CommandQueue* queue_=nullptr;const char* role_="";
+public:
+ bool initialize(ID3D12CommandQueue* queue,const char* role){queue_=queue;role_=role;return calibrate();}
+ bool calibrate(){
+ if(!queue_)return false;UINT64 gpu=0,cpu=0,frequency=0;LARGE_INTEGER before{},after{},qpc{};
+ QueryPerformanceFrequency(&qpc);QueryPerformanceCounter(&before);
+ const HRESULT a=queue_->GetTimestampFrequency(&frequency),b=queue_->GetClockCalibration(&gpu,&cpu);
+ QueryPerformanceCounter(&after);
+ log::info("prefetch-clock",std::format("role={} frequency={} gpu={} cpu={} qpcFrequency={} uncertaintyTicks={} frequencyHr=0x{:X} calibrationHr=0x{:X}",
+ role_,frequency,gpu,cpu,qpc.QuadPart,after.QuadPart-before.QuadPart,unsigned(a),unsigned(b)));
+ return SUCCEEDED(a)&&SUCCEEDED(b)&&frequency&&qpc.QuadPart;
+ }
+ void emit(const GpuFrameTiming& frame){
+ if(!queue_)return;
+ for(const auto stage:{GpuStage::Flow,GpuStage::Sr,GpuStage::NrLayer0,GpuStage::NrLayer1}){
+ const auto& s=frame.gpu[size_t(stage)];if(s.state!=SampleState::Measured||!s.frequency)continue;
+ log::info("prefetch-gpu",std::format("role={} source={} stage={} begin={} end={} frequency={}",
+ role_,frame.identity.sourceFrameId,unsigned(stage),s.begin,s.end,s.frequency));
+ }
+ }
+};
+}
diff --git a/include/veyra/pipeline/FlowPrefetch.h b/include/veyra/pipeline/FlowPrefetch.h
index 3d478031..78e51813 100644
--- a/include/veyra/pipeline/FlowPrefetch.h
+++ b/include/veyra/pipeline/FlowPrefetch.h
@@ -2,6 +2,7 @@
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/diagnostics/GpuQueueTrace.h"
#include <array>
namespace veyra::pipeline {
@@ -20,5 +21,6 @@ private:
gfx::D3D12DeviceContext context_;gfx::CommandSlotRing ring_;
std::unique_ptr<EnhanceGraph> graph_;std::array<Slot,2> slots_;
uint64_t sequence_=0,previous_=0,revision_=0;unsigned activeSlot_=0;
+ diagnostics::GpuQueueTrace trace_;bool traceEnabled_=false;
};
}
diff --git a/scripts/perf/nr-export-prefetch.py b/scripts/perf/nr-export-prefetch.py
new file mode 100644
index 00000000..e7dc4762
--- /dev/null
+++ b/scripts/perf/nr-export-prefetch.py
@@ -0,0 +1,40 @@
+"""Small real-export prefetch/output/debug checks before any timing matrix."""
+from pathlib import Path
+import 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_export_pipeline_experiment.exe';shutil.copy2(BASE/'build'/TASK/variant/exe.name,exe)
+folder=BASE/'logs'/TASK/(label+'-summary');folder.mkdir(parents=True,exist_ok=False)
+payload={str(p.relative_to(app)):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(payload,ensure_ascii=False,indent=2),encoding='utf-8')
+results=[]
+for group,prefetch,cancel in [('nr',False,False),('nr',True,False),('nrsr4k',False,False),('nrsr4k',True,False),('nr2',False,False),('nr2',True,False),('nr',True,True)]:
+ matrix.assert_gpu_tests_idle();name=f'{label}-{group}-{int(prefetch)}'+('-cancel' if cancel else '');out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
+ for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
+ dest=out/'export.mp4';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),VEYRA_TEST_EXPORT_DEBUG='1')
+ if prefetch:env['VEYRA_TEST_EXPORT_NVOF_PREFETCH']='1'
+ command=[str(exe),str(matrix.SOURCES['M1']),str(dest),group,'24',str(out)]+(['--cancel'] if cancel else [])
+ print('START',name,flush=True);start=time.monotonic()
+ with (out/'console.log').open('xb') as stream:
+ try:rc=subprocess.run(command,cwd=app,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=250).returncode
+ except subprocess.TimeoutExpired:rc=124
+ text=(out/'console.log').read_text(encoding='utf-8',errors='replace');log=(out/'engine.log').read_text(encoding='utf-8',errors='replace')
+ line=next((s for s in text.splitlines() if s.startswith('EXPORT_PIPELINE_RESULT ')),'');metrics={k:float(v) for k,v in re.findall(r'(\w+)=(-?[\d.]+)',line)}
+ passed=rc==0 and '[export-debug] errors=0 removedReason=0x0' in log and (metrics.get('cancelled')==1 and metrics.get('ok')==0 and not dest.exists() if cancel else metrics.get('ok')==1 and metrics.get('source')==24)
+ if prefetch and not cancel:passed=passed and '[flow-prefetch] source=24 consumed=' in log
+ result={'name':name,'group':group,'prefetch':prefetch,'cancel':cancel,'command':command,'exitCode':rc,'metrics':metrics,'passed':passed,'extraGpuLoad':False,
+ 'wallSeconds':time.monotonic()-start,'exeSha256':matrix.digest(exe),'outputSha256':matrix.digest(dest) if dest.exists() else None,
+ 'diagnostics':[s for s in log.splitlines() if any(tag in s for tag in ('[export-debug]','[flow-prefetch]','[export-pipeline]','[scene]'))]}
+ (out/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8');results.append(result)
+ (folder/'completed.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8');print('RESULT',json.dumps(result),flush=True)
+ if not passed:print(log[-7000:],flush=True);raise SystemExit(1)
+assert all(matrix.digest(app/name)==sha for name,sha in payload.items()),'Product payload mutated'
+pairs=[{'group':g,'sameWholeFile':len({r['outputSha256'] for r in results if r['group']==g and not r['cancel']})==1} for g in ('nr','nrsr4k','nr2')]
+passed=all(p['sameWholeFile'] for p in pairs)
+(folder/'summary.json').write_text(json.dumps({'runs':results,'pairs':pairs,'passed':passed,'payloadUnchanged':True},ensure_ascii=False,indent=2),encoding='utf-8')
+matrix.assert_gpu_tests_idle();print('PREFETCH_SMOKE_COMPLETE',passed,pairs,flush=True);raise SystemExit(0 if passed else 1)
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 865d0846..86d4802e 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -211,7 +211,6 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
double previousPts=0;int64_t lastOutputUs=-1;
uint64_t slowFrames=0;
// Directed export measurements exclude feature/encoder creation, but include final drain.
- const auto pipelineStart=std::chrono::steady_clock::now();
double completionWaitMs=0;
// Acceptance hook: VEYRA_TEST_EXPORT_SLOW_FRAME=<source index>:<ms> holds that frame's
// completion back, standing in for a GPU that is slow but alive. Unset in normal use.
@@ -245,6 +244,9 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(!injected)completionEvent.value=CreateEventW(nullptr,FALSE,FALSE,nullptr);
if(!completionEvent.value){veyra::log::warn("export-pipeline",std::format("completion event create failed error={} injected={}; keeping polling",injected?ERROR_INVALID_HANDLE:GetLastError(),injected));fenceEvents=false;}
}
+ diagnostics::GpuQueueTrace prefetchTrace;
+ const bool tracePrefetch=flowPrefetch&&testFlag(L"VEYRA_TEST_EXPORT_PREFETCH_TIMESTAMPS",false);
+ if(tracePrefetch){prefetchTrace.initialize(ring.queue(),"consumer");graph.recordGpuTimings();}
struct PendingFrame {pipeline::EnhanceGraph::FrameOutputs output;uint64_t consumerFence=0,source=0;std::chrono::steady_clock::time_point submitted;};
std::deque<PendingFrame> pendingFrames;unsigned maxInFlight=1;
// Preserve the 30s alive-device contract, cancellation and slow-frame hook.
@@ -303,7 +305,9 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
timestamps.emplace_back(outputIndex,timeUs);lastOutputUs=timeUs;
return encoder->encode(slot,generated,outputIndex++);
};
+ const auto pipelineStart=std::chrono::steady_clock::now();
while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;
+ if(tracePrefetch)for(const auto& timing:graph.takeGpuTimings())prefetchTrace.emit(timing);
if(pendingFrames.size()>=2&&!finishOldest())break;
source::SourceReadStatus rs;
if(sourceCount==0){packet=firstPacket;frame=firstFrame;rs=source::SourceReadStatus::Frame;}
@@ -380,6 +384,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
veyra::log::info("export-counts",std::format("slowFrames={} source={} generated={} hold={} output={} multiplier={} repairedTimestamps={} backend={} vfgQuality={} encoder={} bitrateMbps={} note={} (holds are not generated frames)",slowFrames,sourceCount,generatedCount,holdCount,outputIndex,multiplier,repairedTimestamps,frameGenerationBackendName(options.settings.frameGenerationBackend),options.settings.vfgQuality,std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));
progress(.99,L"正在收尾:等待编码器输出剩余帧");
if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}
+ if(tracePrefetch){for(const auto& timing:graph.takeGpuTimings())prefetchTrace.emit(timing);prefetchTrace.calibrate();}
veyra::log::info("export-pipeline",std::format("source={} pipelineMs={:.3f} completionWaitMs={:.3f} mode={} fenceEvents={} maxInFlight={}",
sourceCount,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-pipelineStart).count(),completionWaitMs,asyncNvenc?"async":"serial",fenceEvents,maxInFlight));
if(flowPrefetch)veyra::log::info("flow-prefetch",std::format("source={} consumed={} normalMotionExecutes={}",sourceCount,graph.metrics().prefetchedFlowCount,graph.metrics().nvofExecuteCount));
diff --git a/src/pipeline/FlowPrefetch.cpp b/src/pipeline/FlowPrefetch.cpp
index b233b359..653acfca 100644
--- a/src/pipeline/FlowPrefetch.cpp
+++ b/src/pipeline/FlowPrefetch.cpp
@@ -13,6 +13,8 @@ bool FlowPrefetch::initialize(gfx::D3D12DeviceContext& owner,const EnhanceGraphD
desc.fixedExecutionPlan.reset();desc.fixedExecutionPlanError.clear();desc.runtimeNodeOrder=false;desc.additionalColorCount=0;
graph_=std::make_unique<EnhanceGraph>(context_,ring_);
if(!graph_->initialize(desc)||!graph_->createViews())return false;
+ traceEnabled_=GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_PREFETCH_TIMESTAMPS",nullptr,0)>0;
+ if(traceEnabled_){trace_.initialize(ring_.queue(),"producer");graph_->recordGpuTimings();}
for(auto& slot:slots_){
slot.flow=makeTexture(context_.device(),graph_->flowWidth(),graph_->flowHeight(),DXGI_FORMAT_R16G16_FLOAT,false);
slot.confidence=makeTexture(context_.device(),graph_->flowWidth(),graph_->flowHeight(),DXGI_FORMAT_R8_UNORM,false);
@@ -24,6 +26,7 @@ bool FlowPrefetch::initialize(gfx::D3D12DeviceContext& owner,const EnhanceGraphD
bool FlowPrefetch::prepare(const AVFrame* frame,double pts,bool reset,uint64_t source,
const ColorDescription* color,EnhanceGraph::PreparedFlow& output){
output={};if(!graph_)return false;activeSlot_=unsigned(sequence_%2);auto& snapshot=slots_[activeSlot_];
+ if(traceEnabled_)for(const auto& timing:graph_->takeGpuTimings())trace_.emit(timing);
if(snapshot.consumer&&snapshot.consumerValue){
const HRESULT hr=ring_.queue()->Wait(snapshot.consumer.Get(),snapshot.consumerValue);
if(FAILED(hr)){veyra::log::error("flow-prefetch",std::format("producer reuse Wait hr=0x{:X}",unsigned(hr)));return false;}
@@ -55,7 +58,8 @@ void FlowPrefetch::shutdown(){
}
ring_.drainQueue();
}
- if(graph_)graph_->shutdown();graph_.reset();slots_={};ring_.shutdown();context_.shutdown();
+ if(graph_){if(traceEnabled_){for(const auto& timing:graph_->takeGpuTimings())trace_.emit(timing);trace_.calibrate();}graph_->shutdown();}
+ graph_.reset();slots_={};traceEnabled_=false;ring_.shutdown();context_.shutdown();
sequence_=previous_=revision_=0;activeSlot_=0;
}
}