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(experiment): prepare bounded NVOF snapshots on a shared-device queue

Veyra Goal Agent5edbf795c9ca
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 69b78ae7..45e189db 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -473,7 +473,7 @@ endif()
# EnhanceGraph (the real GPU chain) needs the NGX + NVOF backends; wire it
# into veyra_pipeline only when both exist so bare contract builds still work.
if(TARGET veyra_ngx AND TARGET veyra_nvof AND VEYRA_FFMPEG_ROOT)
- target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/pipeline/NrTemporalPass.cpp src/pipeline/NrHoldPass.cpp src/core/SceneCadenceAnalyzer.cpp)
+ target_sources(veyra_pipeline PRIVATE src/pipeline/EnhanceGraph.cpp src/pipeline/FlowPrefetch.cpp src/pipeline/NrTemporalPass.cpp src/pipeline/NrHoldPass.cpp src/core/SceneCadenceAnalyzer.cpp)
target_include_directories(veyra_pipeline PRIVATE ${FFMPEG_INCLUDE_DIRS})
target_link_libraries(veyra_pipeline PRIVATE veyra_ngx veyra_nvof ${FFMPEG_LIBRARIES})
add_dependencies(veyra_pipeline
diff --git a/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md b/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md
index becbcf23..62726a21 100644
--- a/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md
+++ b/docs/PERF_5B_NVOF_PREFETCH_2026-10-05.md
@@ -9,3 +9,5 @@
先用真实生产exportVideo测单NR与NR+SR4K,三个交错回合,B-off与已验证默认导出路径比较整次/处理区间;完整输出文件/decoded PTS不一致则不进入产品。核对debug层、reset/取消及有限资源重用,不做设备移除或真实资源压力。单进程≤250秒。该复用图会额外复制flow/conf且占显存,若成本大于隐去的NVOF等待,明确拒绝此实现;不能为微小收益重写整条source/color链或宣传达到原估计10%。
初始源码检查:独立辅助图需要独立queue/fence但共享ID3D12Device,现D3D12DeviceContext只有新建device入口;新增仅供此候选的共享设备队列创建,事务式资源创建失败不破坏原context。原图NVOF input A/B仍正常更新,故关闭候选后可回原路径,生产默认图无附加GPU资源。
+
+候选按上述结构实现,`VEYRA_TEST_EXPORT_NVOF_PREFETCH=1`才创建辅助图;主图消费导入快照时维持GPU侧fence依赖,生产默认无快照/额外队列。准备过程复用实际EnhanceGraph,不复制颜色/光流算法。主图计数另记prefetchedFlowCount,辅助图实际NVOF execute仍有日志,不冒充主图常规execute。关闭辅助图先等各快照consumer,再drain/注销,原Graph reset仍按自己的真实luma/PTS分析并与快照描述匹配。下一步编译和真实输出/正常耗时证据;尚未声明通过。
diff --git a/include/veyra/gfx/D3D12DeviceContext.h b/include/veyra/gfx/D3D12DeviceContext.h
index aebfdff9..c2001aff 100644
--- a/include/veyra/gfx/D3D12DeviceContext.h
+++ b/include/veyra/gfx/D3D12DeviceContext.h
@@ -50,6 +50,10 @@ public:
// (vendor 0x10DE, non-software) -> device at >= 12_0 -> direct queue ->
// fence/event -> command slot ring. Every step logs its real result.
bool initialize(const DeviceContextDesc& desc, Status& status);
+ // Independent bounded producer queue on the same device. Its own fence
+ // timeline must have exactly one CommandSlotRing signaler.
+ bool initializeSharedQueue(const D3D12DeviceContext& owner,
+ D3D12_COMMAND_LIST_TYPE type,uint32_t slots,Status& status);
void shutdown(); // reverse-order teardown
bool initialized() const { return initialized_; }
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 4183e85a..b9b4d1e6 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -448,10 +448,16 @@ public:
// number of outputs changes, and it is reported as previewFgMultiplier.
enum class FgDecision { Skip, Evaluate, Seed, Reduced };
using FgAdmission=std::function<FgDecision(const FrameBatch&,bool warmingHistory)>;
+ struct PreparedFlow {
+ ComPtr<ID3D12Resource> flow,confidence;
+ ComPtr<ID3D12Fence> readyFence;
+ uint64_t readyValue=0,source=0,previous=0,settingsRevision=0;
+ double ptsMs=0;bool historyReset=false,valid=false;
+ };
// `hardwareSurface` carries the decoded texture for paths whose surface
// does not travel inside the AVFrame (D3D11VA). It must be provided exactly
// when frame->format == AV_PIX_FMT_D3D11 and is unused otherwise.
- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {}, unsigned previewMultiplier = 0, bool pausedResidualRefresh = false);
+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {}, unsigned previewMultiplier = 0, bool pausedResidualRefresh = false, const PreparedFlow* preparedFlow = nullptr);
bool nextFrameSlotAvailable()const {
const unsigned slot=unsigned(realFrameIndex_%2);
if(presentationFences_[slot]&&presentationFences_[slot]->GetCompletedValue()<presentationValues_[slot])return false;
@@ -486,6 +492,7 @@ public:
uint64_t pausedNrResidualReuses = 0;
uint64_t srEvaluateCount = 0;
uint64_t nvofExecuteCount = 0;
+ uint64_t prefetchedFlowCount = 0;
uint64_t amdOfExecuteCount = 0;
uint64_t gpuDisExecuteCount = 0;
uint64_t nvofFrameFailures = 0;
diff --git a/include/veyra/pipeline/FlowPrefetch.h b/include/veyra/pipeline/FlowPrefetch.h
new file mode 100644
index 00000000..3d478031
--- /dev/null
+++ b/include/veyra/pipeline/FlowPrefetch.h
@@ -0,0 +1,24 @@
+#pragma once
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include <array>
+
+namespace veyra::pipeline {
+// Experimental file/export producer. Reuses product colour/NVOF/densify,
+// bounded to two snapshots. No capture lookahead or pixel CPU readback.
+class FlowPrefetch {
+public:
+ ~FlowPrefetch(){shutdown();}
+ bool initialize(gfx::D3D12DeviceContext& owner,const EnhanceGraphDesc& desc);
+ bool prepare(const AVFrame* frame,double pts,bool reset,uint64_t source,
+ const ColorDescription* color,EnhanceGraph::PreparedFlow& output);
+ void consumed(ID3D12Fence* fence,uint64_t value);
+ void shutdown();
+private:
+ struct Slot {ComPtr<ID3D12Resource> flow,confidence;ComPtr<ID3D12Fence> consumer;uint64_t consumerValue=0;};
+ 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;
+};
+}
diff --git a/scripts/perf/nr-export-pipeline.py b/scripts/perf/nr-export-pipeline.py
index 6a5d0f1c..8fc9a018 100644
--- a/scripts/perf/nr-export-pipeline.py
+++ b/scripts/perf/nr-export-pipeline.py
@@ -4,7 +4,7 @@ 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,mode=sys.argv[1:4];groups=sys.argv[4:] or ['none4k','nr','nr2','nrsr4k','sr8k']
-assert mode in ('default','serial','events','async','async-events','interleaved','default-interleaved','all')
+assert mode in ('default','serial','events','async','async-events','prefetch','interleaved','default-interleaved','prefetch-interleaved','all')
assert all(g in ('none4k','nr','nr2','sr4k','nrsr4k','sr8k','fg2') for g in groups)
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)
@@ -17,7 +17,7 @@ for group in groups:
source=BASE/'tests/perf-matrix/media/M2.mkv' if group in ('none4k','sr8k') else matrix.SOURCES['M1']
config='none' if group=='none4k' else group;frames=60 if group=='sr8k' else 120
for repeat in range(1,4):
- modes=(('serial','default') if repeat%2 else ('default','serial')) if mode=='default-interleaved' else (('serial','async') if repeat%2 else ('async','serial')) if mode=='interleaved' else (('serial','events','async','async-events') if repeat%2 else ('async-events','async','events','serial')) if mode=='all' else (mode,)
+ modes=(('default','prefetch') if repeat%2 else ('prefetch','default')) if mode=='prefetch-interleaved' else (('serial','default') if repeat%2 else ('default','serial')) if mode=='default-interleaved' else (('serial','async') if repeat%2 else ('async','serial')) if mode=='interleaved' else (('serial','events','async','async-events') if repeat%2 else ('async-events','async','events','serial')) if mode=='all' else (mode,)
for current in modes:
matrix.assert_gpu_tests_idle();name=f'{label}-{group}-{current}-r{repeat}';out=BASE/'logs'/TASK/name;tmp=BASE/'tmp'/TASK/name
for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
@@ -28,6 +28,7 @@ for group in groups:
if current=='serial':env['VEYRA_TEST_EXPORT_SERIAL']='1'
if current=='events':env['VEYRA_TEST_EXPORT_ASYNC']='0'
if current=='async':env['VEYRA_TEST_EXPORT_FENCE_EVENTS']='0'
+ if current=='prefetch':env['VEYRA_TEST_EXPORT_NVOF_PREFETCH']='1'
if current in ('async','async-events'):env['VEYRA_TEST_EXPORT_ASYNC']='1'
if current in ('events','async-events'):env['VEYRA_TEST_EXPORT_FENCE_EVENTS']='1'
command=[str(exe),str(source),str(dest),config,str(frames),str(out)]
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index c75c9e79..865d0846 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -2,6 +2,7 @@
#include "veyra/engine/ExportStreams.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/pipeline/FlowPrefetch.h"
#include "veyra/pipeline/ResolutionPlan.h"
#include "veyra/sink/VideoEncoder.h"
#include "veyra/gfx/D3D12DeviceContext.h"
@@ -46,6 +47,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);
struct CompletionEvent {HANDLE value=nullptr;~CompletionEvent(){if(value)CloseHandle(value);}} completionEvent;
std::unique_ptr<sink::VideoEncoder> encoder;
+ std::unique_ptr<pipeline::FlowPrefetch> flowPrefetch;
AVFormatContext* mux=nullptr;AVStream* videoStream=nullptr;ExportStreams streams;
bool ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;
uint64_t repairedTimestamps=0;
@@ -231,6 +233,13 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
const bool eligibleNvenc=!options.fg&&encoder->backend()==sink::EncoderBackend::Nvenc&&slowFrameIndex<0;
const bool asyncNvenc=!serialOverride&&eligibleNvenc&&testFlag(L"VEYRA_TEST_EXPORT_ASYNC",eligibleNvenc);
bool fenceEvents=!serialOverride&&testFlag(L"VEYRA_TEST_EXPORT_FENCE_EVENTS",eligibleNvenc);
+ if(testFlag(L"VEYRA_TEST_EXPORT_NVOF_PREFETCH",false)){
+ const bool allowed=asyncNvenc&&graph.nvofSessionInitialized()&&!gd.hdrInput&&!gd.hdrOutput&&
+ !gd.color.enabled&&!gd.additionalColorCount&&!gd.videoHdr.enabled&&gd.opticalFlowBackend==OpticalFlowBackend::Nvidia;
+ if(!allowed){failureReason=L"NVOF预取实验配置不受支持";veyra::log::error("flow-prefetch","experimental export admission refused");break;}
+ flowPrefetch=std::make_unique<pipeline::FlowPrefetch>();
+ if(!flowPrefetch->initialize(ctx,gd)){failureReason=L"NVOF预取实验初始化失败";break;}
+ }
if(fenceEvents){
const bool injected=GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_EVENT_CREATE_FAIL",nullptr,0)>0;
if(!injected)completionEvent.value=CreateEventW(nullptr,FALSE,FALSE,nullptr);
@@ -313,7 +322,12 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
Microsoft::WRL::ComPtr<ID3D12Device5> device5;
if(SUCCEEDED(ctx.device()->QueryInterface(IID_PPV_ARGS(&device5)))){device5->RemoveDevice();veyra::log::warn("export","test hook: D3D12 device removed at this frame");}
}
- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,(pts+videoOriginSeconds)*1000,sourceCount==0||repairPts||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false)){error=true;break;}
+ const double framePtsMs=(pts+videoOriginSeconds)*1000;
+ const bool frameReset=sourceCount==0||repairPts||pipeline::breaksHistory(packet.flags);
+ pipeline::EnhanceGraph::PreparedFlow preparedFlow;
+ if(flowPrefetch&&!flowPrefetch->prepare(frame,framePtsMs,frameReset,packet.sequence,&packet.colorInfo,preparedFlow)){error=true;break;}
+ pipeline::EnhanceGraph::FrameOutputs out;
+ if(!graph.process(frame,framePtsMs,frameReset,out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false,{},0,false,flowPrefetch?&preparedFlow:nullptr)){error=true;break;}
const auto readyStart=std::chrono::steady_clock::now();
if(!asyncNvenc&&!waitCompleted(out,readyStart,sourceCount))break;
if(sourceCount>0&&options.fg){
@@ -329,6 +343,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
auto& real=out.batch.frames[out.batch.count-1];
if(!encodeAt(real.lease->slot,false,pts)){error=true;break;}
real.lease->consumerFence=ring.lastSignaledValue();lastReal=real.lease;
+ if(flowPrefetch)flowPrefetch->consumed(ctx.fence(),real.lease->consumerFence);
if(asyncNvenc){
const uint64_t consumerFence=real.lease->consumerFence;
pendingFrames.push_back({std::move(out),consumerFence,sourceCount,readyStart});
@@ -367,6 +382,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}
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));
const int64_t estimatedEnd=lastOutputUs+std::max<int64_t>(1,int64_t(std::llround(sourceInterval*1000000/multiplier)));
const int64_t finalEnd=requestedEnd>0?std::min(estimatedEnd,int64_t(std::llround((requestedEnd-videoOriginSeconds)*1000000))):estimatedEnd;
if(!flushVideo(finalEnd))break;
@@ -377,7 +393,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
ok=written>0;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});
}while(false); }catch(const std::exception& e){veyra::log::error("export",std::format("exception: {}",e.what()));failureReason=L"导出异常,请查看诊断";ok=false;}
encoder.reset();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}avformat_free_context(mux);}
- ring.drainQueue();graph.shutdown();source.close();ring.shutdown();
+ flowPrefetch.reset();ring.drainQueue();graph.shutdown();source.close();ring.shutdown();
if(GetEnvironmentVariableW(L"VEYRA_TEST_EXPORT_DEBUG",nullptr,0)>0&&ctx.device()){
Microsoft::WRL::ComPtr<ID3D12InfoQueue> debug;const HRESULT hr=ctx.device()->QueryInterface(IID_PPV_ARGS(&debug));unsigned errors=0;
if(FAILED(hr)){ok=false;veyra::log::error("export-debug",std::format("InfoQueue query failed hr=0x{:X}",unsigned(hr)));}
diff --git a/src/gfx/D3D12DeviceContext.cpp b/src/gfx/D3D12DeviceContext.cpp
index 887a0fb7..0c6451d5 100644
--- a/src/gfx/D3D12DeviceContext.cpp
+++ b/src/gfx/D3D12DeviceContext.cpp
@@ -264,6 +264,28 @@ bool D3D12DeviceContext::initialize(const DeviceContextDesc& desc, Status& statu
return true;
}
+bool D3D12DeviceContext::initializeSharedQueue(const D3D12DeviceContext& owner,
+ D3D12_COMMAND_LIST_TYPE type,uint32_t slots,Status& status)
+{
+ if(this==&owner||!owner.initialized_||type!=D3D12_COMMAND_LIST_TYPE_COMPUTE||slots<2||slots>6){
+ status=Status::InvalidArgument;return false;
+ }
+ ComPtr<ID3D12CommandQueue> queue;ComPtr<ID3D12Fence> fence;
+ D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=type;desc.Priority=D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
+ HRESULT hr=owner.device_->CreateCommandQueue(&desc,IID_PPV_ARGS(&queue));
+ if(FAILED(hr)){status=Status::DeviceFailure;veyra::log::error("gfx-shared-queue",std::format("CreateCommandQueue hr=0x{:X}",unsigned(hr)));return false;}
+ hr=owner.device_->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence));
+ if(FAILED(hr)){status=Status::DeviceFailure;veyra::log::error("gfx-shared-queue",std::format("CreateFence hr=0x{:X}",unsigned(hr)));return false;}
+ HANDLE event=CreateEventW(nullptr,FALSE,FALSE,nullptr);
+ if(!event){status=Status::DeviceFailure;veyra::log::error("gfx-shared-queue",std::format("CreateEvent error={}",GetLastError()));return false;}
+ // Creation failures above leave any live context intact.
+ shutdown();factory_=owner.factory_;adapter_=owner.adapter_;device_=owner.device_;
+ adapterInfo_=owner.adapterInfo_;featureLevel_=owner.featureLevel_;debugLayerEnabled_=owner.debugLayerEnabled_;
+ queue_=std::move(queue);fence_=std::move(fence);fenceEvent_=event;commandSlotCount_=slots;initialized_=true;
+ queue_->SetName(L"Veyra independent flow preparation queue");status=Status::Ok;
+ veyra::log::info("gfx-shared-queue",std::format("sameDevice=true type=COMPUTE slots={} independentFence=true",slots));return true;
+}
+
void D3D12DeviceContext::shutdown()
{
if (!initialized_) {
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index fb180056..4a10744e 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -1789,7 +1789,7 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
// process: the per-frame chain (verbatim from the probe lambda).
// ---------------------------------------------------------------------------
-bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, const HardwareSurfaceInput* hardwareSurface, bool retainReferences, const FgAdmission& admitFg, unsigned previewMultiplier, bool pausedResidualRefresh)
+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, const HardwareSurfaceInput* hardwareSurface, bool retainReferences, const FgAdmission& admitFg, unsigned previewMultiplier, bool pausedResidualRefresh, const PreparedFlow* preparedFlow)
{
// Whole-chain duplicate reuse failed the unchanged-output experiment.
// This narrower path only handles repeated edits of the SAME paused
@@ -2212,6 +2212,20 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
// Guidance from original source-space color before SR/NR. Queue waits are GPU-side.
bool haveFlow = false;
const bool runMotion = nvofStandalone_ || (presentSinkFg()&&desc_.fgUsesFlow()) || (fgEnabled_&&desc_.fgUsesFlow()) || (srEnabled_&&desc_.srUsesFlow()&&(desc_.videoSrQuality==0||desc_.videoSrQuality==engine::kVideoSrFsr));
+ if(preparedFlow){
+ auto matches=[&](ID3D12Resource* resource,DXGI_FORMAT format){
+ if(!resource)return false;const auto d=resource->GetDesc();ComPtr<ID3D12Device> device;
+ return SUCCEEDED(resource->GetDevice(IID_PPV_ARGS(&device)))&&device.Get()==context_.device()&&
+ d.Width==nvofW_&&d.Height==nvofH_&&d.Format==format&&d.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ };
+ if(!runMotion||!nvof_||gpuDis_||amdOf_||!preparedFlow->readyFence||!preparedFlow->readyValue||
+ preparedFlow->source!=sourceFrameId||preparedFlow->previous!=previousSource_||
+ preparedFlow->ptsMs!=ptsMs||preparedFlow->settingsRevision!=desc_.settingsRevision||
+ preparedFlow->historyReset!=reset||preparedFlow->valid!=prevValid_||
+ !matches(preparedFlow->flow.Get(),DXGI_FORMAT_R16G16_FLOAT)||!matches(preparedFlow->confidence.Get(),DXGI_FORMAT_R8_UNORM)){
+ veyra::log::error("flow-prefetch","prepared guidance contract mismatch; refusing stale motion");return false;
+ }
+ }
if (runMotion && (gpuDis_ || amdOf_ || (nvof_ && nvof_->initialized()))) {
const float dims[8] = {uintBits(nvofW_),uintBits(nvofH_),uintBits(nvofW_),uintBits(nvofH_),0,0,0,0};
if (prevValid_) {
@@ -2246,7 +2260,21 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
++metrics_.gpuDisExecuteCount;haveFlow=true;
gpuTimer_.mark(list,GpuStage::Flow,true);
}
- if (prevValid_ && !gpuDis_) {
+ if(preparedFlow&&prevValid_){
+ gpuTimer_.mark(list,GpuStage::Flow);
+ if(!submitGraph(slot))return false;
+ const HRESULT hr=ring_.queue()->Wait(preparedFlow->readyFence.Get(),preparedFlow->readyValue);
+ if(FAILED(hr)){veyra::log::error("flow-prefetch",std::format("consumer queue Wait hr=0x{:X}",unsigned(hr)));return false;}
+ list=ring_.acquireNext(slot,st);if(!list)return false;
+ auto copy=[&](ID3D12Resource* from,ID3D12Resource* to){
+ tracker_.transition(list,from,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,to,D3D12_RESOURCE_STATE_COPY_DEST);
+ list->CopyResource(to,from);tracker_.transition(list,from,D3D12_RESOURCE_STATE_COMMON);
+ tracker_.transition(list,to,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ };
+ copy(preparedFlow->flow.Get(),flowTex_.Get());copy(preparedFlow->confidence.Get(),confTex_.Get());
+ haveFlow=true;++metrics_.prefetchedFlowCount;gpuTimer_.mark(list,GpuStage::Flow,true);
+ }
+ if (prevValid_ && !gpuDis_ && !preparedFlow) {
if(!amdOf_){
gpuTimer_.mark(list,GpuStage::Flow);
if(!submitGraph(slot))return false;
diff --git a/src/pipeline/FlowPrefetch.cpp b/src/pipeline/FlowPrefetch.cpp
new file mode 100644
index 00000000..3f8c1928
--- /dev/null
+++ b/src/pipeline/FlowPrefetch.cpp
@@ -0,0 +1,61 @@
+#include "veyra/pipeline/FlowPrefetch.h"
+#include "veyra/Log.h"
+#include <format>
+namespace veyra::pipeline {
+bool FlowPrefetch::initialize(gfx::D3D12DeviceContext& owner,const EnhanceGraphDesc& input){
+ shutdown();Status status;
+ if(!context_.initializeSharedQueue(owner,D3D12_COMMAND_LIST_TYPE_COMPUTE,4,status)||
+ !ring_.initialize(context_.device(),context_.directQueue(),context_.fence(),context_.fenceEvent(),4,status))return false;
+ auto desc=input;desc.noFeatures=false;desc.noNgx=true;desc.enableSr=desc.enableNr=desc.enableFg=false;desc.enableNvofStandalone=true;
+ desc.nrBeforeSr=false;desc.workWidth=desc.nrWidth=desc.sourceWidth;desc.workHeight=desc.nrHeight=desc.sourceHeight;
+ desc.nrLayers.clear();desc.nrLayersExtent.clear();desc.nrLayersModel.clear();desc.nrLayersSizePolicy.clear();
+ desc.nrLayersResidual.clear();desc.nrLayersTemporal.clear();desc.nrLayersAntiFlicker.clear();desc.nrLayersProtection.clear();
+ 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;
+ 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);
+ if(!slot.flow||!slot.confidence)return false;
+ }
+ revision_=input.settingsRevision;
+ veyra::log::info("flow-prefetch",std::format("initialized slots=2 sameDevice=true flow={}x{} default=false",graph_->flowWidth(),graph_->flowHeight()));return true;
+}
+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(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;}
+ }
+ EnhanceGraph::FrameOutputs result;
+ if(!graph_->process(frame,pts,reset,result,source,color,nullptr,false))return false;
+ Status status;uint32_t slot;auto* list=ring_.acquireNext(slot,status);if(!list)return false;
+ StateTracker states;
+ auto copy=[&](ID3D12Resource* from,ID3D12Resource* to){
+ const auto original=graph_->diagnosticResourceState(from);states.set(from,original);
+ states.transition(list,from,D3D12_RESOURCE_STATE_COPY_SOURCE);states.transition(list,to,D3D12_RESOURCE_STATE_COPY_DEST);
+ list->CopyResource(to,from);states.transition(list,from,original);states.transition(list,to,D3D12_RESOURCE_STATE_COMMON);
+ };
+ copy(graph_->flowResource(),snapshot.flow.Get());copy(graph_->confidenceResource(),snapshot.confidence.Get());
+ if(!ring_.submitAndSignal(slot))return false;
+ output.flow=snapshot.flow;output.confidence=snapshot.confidence;output.readyFence=context_.fence();output.readyValue=ring_.lastSignaledValue();
+ output.source=result.batch.identity.sourceFrameId;output.previous=previous_;output.settingsRevision=revision_;
+ output.ptsMs=pts;output.historyReset=result.historyReset;output.valid=sequence_>0&&!result.historyReset;
+ previous_=output.source;++sequence_;return true;
+}
+void FlowPrefetch::consumed(ID3D12Fence* fence,uint64_t value){
+ auto& slot=slots_[activeSlot_];slot.consumer=fence;slot.consumerValue=value;
+}
+void FlowPrefetch::shutdown(){
+ if(ring_.initialized()){
+ for(auto& slot:slots_)if(slot.consumer&&slot.consumerValue){
+ const HRESULT hr=ring_.queue()->Wait(slot.consumer.Get(),slot.consumerValue);
+ if(FAILED(hr))veyra::log::error("flow-prefetch",std::format("teardown Wait hr=0x{:X}",unsigned(hr)));
+ }
+ ring_.drainQueue();
+ }
+ if(graph_)graph_->shutdown();graph_.reset();slots_={};ring_.shutdown();context_.shutdown();
+ sequence_=previous_=revision_=0;activeSlot_=0;
+}
+}