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

fix(player): cancel window rebuild on exit and clear borrowed presentation queue

Veyra Goal Agent04a0fc3e86f0
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7aac312d..0b36528d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -770,6 +770,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_definitions(veyra_image_dimension_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(veyra_image_dimension_tests PRIVATE veyra_engine)
add_executable(veyra_preview_geometry_tests tests/integration/PreviewGeometryTests.cpp)
+ add_executable(veyra_present_sink_lifecycle_tests tests/perf/PresentSinkLifecycleTests.cpp)
+ target_compile_features(veyra_present_sink_lifecycle_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_present_sink_lifecycle_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_present_sink_lifecycle_tests PRIVATE veyra_gfx user32)
add_executable(veyra_experimental_backend_tests tests/integration/ExperimentalBackendTests.cpp)
target_compile_features(veyra_experimental_backend_tests PRIVATE cxx_std_20)
target_include_directories(veyra_experimental_backend_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index bd5b479e..c517f86c 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -8342,3 +8342,5 @@ R0合同14项+Qt Quick39项通过;真实Qt GPU/软件功能布局4/4、严格8
`nr-r0-normal.py B2d R0-normal-v1`33/33正常负载交错通过:M1各五配置A/B三轮、S4同B DIRECT三轮,sourceSkipped全0。S4增强19.481→18.795ms(3.52%),同B DIRECT19.299→18.795(2.61%);其余配置无稳定收益,单NR原生约6.1ms,软件Present P99几乎未变。最长成功Present110.209ms,CPU图提交长尾仍在;不宣称后台掉帧根治或NR内核提速。全部payload SHA原样。原日志/JSON/CSV在E:/项目/Veyra/logs/perf-nr-20261004/R0-normal-v1-summary及33原始目录。
`nr-r0-close.py B2d R0-close-rebuild-v1`请求FSR后200ms退出实际C0000005;封存A的`R0-close-baseline-v1 fsr3`同样失败。初始化在Qt HWND销毁后继续,CreateSwapChainForHwnd 80070005后清理崩溃。源码确认PresentSink非拥有旧队列未清空,交换链失败前未赋新队列,随后VideoPresenter释放旧队列;重建缺取消检查/停止后仍回滚。先存档本候选和完整失败证据,再最小修复queue生命周期/长初始化取消。没有压力/GPU竞争/设备移除;OBS真实采集仍待,候选尚不可交付。
+
+R0-candidate eb8b1a2已存档,bundle da0440b9229a8bcbc4c6a918d1cdeac38b3372ae4c8eff3af358744424dc3e61。退出修复候选只改PresentSink提前绑定当前queue/拒绝失效HWND/清空借用句柄与指针、VideoPresenter验证目标窗口、EngineController NGX返回后的stop和退出不回滚。其他呈现重建统一经过同一取消检查,保留仅交换链恢复不重建views的旧语义。新增实际D3D12 debug生命周期测试:合法打开→释放旧队列→已关闭窗口初始化失败→重复关闭→新窗口重开,三轮;不造GPU负载/设备故障。待构建及真实退出回归,不提前标通过。
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index d521e9d0..df2eea55 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -562,6 +562,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
std::wstring backendRecoveryWarning;
bool nrAutoPoolUnavailable=false;
std::wstring nrAutoStatus;
+ auto openPreparedPresenter=[&](const PlayerOptions& selected,bool createViews=true){
+ // NGX creation cannot be interrupted. Observe exit when it
+ // returns, before touching a UI-owned HWND or creating views.
+ return !stop_&&presenter.open(ctx,window,*graph,selected.settings.captureCompatible,!isCapture&&!isImage)&&
+ !stop_&&(!createViews||graph->createViews());
+ };
auto initializePreview=[&](pipeline::EnhanceGraphDesc& desc,PlayerOptions& selected,bool preserveWorkingFg=false,bool preserveWorkingNr=false){
backendRecoveryWarning.clear();
auto supported=selected.snapshot();
@@ -574,6 +580,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
veyra::log::warn("capability","normalized requested NVIDIA effects before graph creation; applied settings reflect actual disabled stages");
}
for(unsigned attempt=0;attempt<6;++attempt){
+ if(stop_)return false;
desc.videoHdr=selected.settings.videoHdr;
desc.hdrOutput=selected.settings.useHdrPreview(desc.hdrInput,displayHdrActive());
// Auto is optional and preview-only; fixed/export policies
@@ -606,9 +613,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool adopted=gpu->adopt(selected.snapshot(),desc);
if(!adopted&&!gpu->configureQueue(desc,!isCapture&&!isImage))return false;
bool opened=adopted||graph->initialize(desc);
+ if(stop_){veyra::log::info("engine","preview initialization cancelled after graph creation");return false;}
auto failure=graph->failedBackend();
if(opened){
- opened=presenter.open(ctx,window,*graph,selected.settings.captureCompatible,!isCapture&&!isImage)&&graph->createViews();
+ opened=openPreparedPresenter(selected);
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;}
@@ -617,6 +625,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// to the plain scale path with a visible warning.
if(opened&&graph->fsrSrRequested()&&!graph->fsrSrEnabled()){opened=false;failure=FailedBackend::Sr;}
}
+ if(stop_)return false;
if(opened){
uint64_t afterBudget=0,afterUsage=0;
const auto newBytes=measuredBefore&&ctx.videoMemoryInfo(afterBudget,afterUsage)&&afterUsage>buildUsage?afterUsage-buildUsage:0;
@@ -704,6 +713,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
};
const auto initialRequested=options.snapshot();
const bool previewInitialized=initializePreview(gd,options);
+ if(stop_)break;
publishFrameGenerationCapabilities();
if(!previewInitialized){status(L"视频初始化失败,请查看对应组件的诊断日志",true);break;}
if(!backendRecoveryWarning.empty()){
@@ -1266,6 +1276,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
bool accepted=ring.drainQueue();out={};hasOutput=false;
resetRecord->rebuilt=rebuild;
markResetStage(diagnostics::ResetStage::Drain);
+ if(stop_)break;
if(!accepted){finishReset(diagnostics::ResetOutcome::Failed);status(L"设置切换排空失败,已停止",true);break;}
backendRecoveryWarning.clear();
const bool preserveWorkingFg=previous.multiplier>1&&requested.multiplier>1&&
@@ -1290,13 +1301,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
}
markResetStage(diagnostics::ResetStage::Destroy);
- accepted=reused?(graph->applySettings(requested)&&presenter.open(ctx,window,*graph,next.settings.captureCompatible,!isCapture&&!isImage)&&graph->createViews()):
+ accepted=reused?(graph->applySettings(requested)&&openPreparedPresenter(next)):
initializePreview(nextDesc,next,preserveWorkingFg,preserveWorkingNr);
markResetStage(diagnostics::ResetStage::Create);
+ if(stop_){veyra::log::info("engine","settings rebuild cancelled; skipping rollback on exit");break;}
if(!accepted){
presenter.close();graph->shutdown();recentGraphCache.evict("build-rollback");
graph=std::make_unique<pipeline::EnhanceGraph>(ctx,ring,&coreCache);graphBytes=0;
- 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;}
+ if(!gpu->configureQueue(gd,!isCapture&&!isImage)||!graph->initialize(gd)||!openPreparedPresenter(options)){if(!stop_)status(L"设置失败且旧资源恢复失败,已停止",true);break;}
}
}else if(accepted)accepted=graph->applySettings(requested);
if(rebuild)publishFrameGenerationCapabilities();
@@ -1552,7 +1564,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.hdrInput=!isImage&&activeSource->info().color.isHdrPath();gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,displayHdrActive());
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;}
+ if(!graph->initialize(gd)||!openPreparedPresenter(options)){if(!stop_)status(L"串流尺寸切换失败",true);break;}
reset=true;pendingResetCause=pipeline::ResetReason::Resize;
}
if(vramRecoverStep){
@@ -1565,7 +1577,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
presenter.close();
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))||!openPreparedPresenter(options,step==2)){if(!stop_)status(L"显存回收后重建失败,请重新打开片源",true);break;}
reset=true;pendingResetCause=pipeline::ResetReason::Resize;
vramRecoverDone=step;vramRecoverCheckAt=Clock::now()+std::chrono::seconds(3);
}
@@ -1851,7 +1863,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
{std::lock_guard lock(mutex_);reduced.revision=++nextRevision_;}
options=PlayerOptions::from(reduced,options.nodeOrder);
describeStages(stageRequest(options),options.snapshot(),gd);
- if(!initializePreview(gd,options)){status(L"增强故障后的基础图重建失败",true);break;}
+ if(!initializePreview(gd,options)){if(!stop_)status(L"增强故障后的基础图重建失败",true);break;}
publishFrameGenerationCapabilities();
backendRecoveryWarning=std::wstring(backendFailureName(failedComponent))+L"运行失败,已关闭对应效果;错误码见日志"+(backendRecoveryWarning.empty()?L"":L";"+backendRecoveryWarning);
{std::lock_guard lock(mutex_);desired_.rejectVideoRequest(attempted,options.snapshot());snapshot_.desired=desired_;snapshot_.applied=options.snapshot();snapshot_.rejectedRevision=attempted.revision;snapshot_.applying=desired_!=snapshot_.applied;snapshot_.backendWarning=backendRecoveryWarning;}
@@ -1865,11 +1877,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
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)&&openPreparedPresenter(options)&&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;
- }else{status(L"参数回滚失败,已停止",true);break;}
+ }else{if(!stop_)status(L"参数回滚失败,已停止",true);break;}
}else{status(std::wstring(backendFailureName(failedComponent))+L"执行失败;请查看日志",true);break;}
}
if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} fgBackend={} flowBackend={} multiplier={} (source kept open)",options.settings.revision,pts,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend),options.snapshot().multiplier));}
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 1171d03f..bd38b54f 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -22,6 +22,11 @@ void VideoPresenter::sourceProcessed(pipeline::FrameIdentity identity){
}
bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible,bool mediaClockPaced) {
close();
+ RECT rc{};
+ if(!IsWindow(window)||!GetClientRect(window,&rc)){
+ veyra::log::warn("present","presentation creation cancelled: target window is no longer available");
+ return false;
+ }
viewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;
++generation_;
Status st=Status::Ok;
@@ -45,7 +50,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh
veyra::log::info("present","application frame-generation presentation uses independent queue/fence, 3 command slots; shared textures use producer/consumer GPU fences");
}
auto* queue=presentationQueue_?presentationQueue_.Get():ctx.directQueue();
- gpuTimer_.initialize(ctx.device(),queue);window_=window;RECT rc{};GetClientRect(window,&rc);
+ gpuTimer_.initialize(ctx.device(),queue);window_=window;
gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;d.tearing=false;
d.waitable=!GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",nullptr,0);
d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index c57a385a..23ef5880 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -112,10 +112,18 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
const Desc& desc, Status& status)
{
device_ = device;
+ // These are borrowed until shutdown. Bind the current queue before any
+ // fallible creation: a failed reopen must never signal the previous queue.
+ queue_ = queue;
shutdownCalled_ = false;
desc_ = desc;
width_ = desc.width;
height_ = desc.height;
+ if (!device_ || !queue_ || (desc.targetWindow && !IsWindow(desc.targetWindow))) {
+ log::warn("present", "sink initialization refused invalid device, queue or target window");
+ status = Status::WindowFailure;
+ return false;
+ }
// Register a window class once per process.
HINSTANCE instance = GetModuleHandleW(nullptr);
@@ -247,8 +255,6 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
log::info("present",desc.hdr10?"output=HDR10 RGB10 PQ/BT2020":desc.hdr?"output=scRGB FP16 (1=80 nits)":"output=SDR RGB G22");
// Block ALT+ENTER; the engine owns mode changes.
(void)factory_->MakeWindowAssociation(hwnd_, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);
- queue_ = queue;
-
if (!refetchBackBuffers()) {
status = Status::WindowFailure;
return false;
@@ -551,6 +557,8 @@ void PresentSink::shutdown()
log::info("present", "sink-shutdown: sub-step factory-release");
factory_.Reset();
+ hwnd_ = nullptr; // borrowed HWNDs are cleared too, never destroyed here
+ queue_ = nullptr; // owner may release its queue immediately after shutdown
device_ = nullptr;
log::info("present", "sink-shutdown: complete");
}
diff --git a/tests/perf/PresentSinkLifecycleTests.cpp b/tests/perf/PresentSinkLifecycleTests.cpp
new file mode 100644
index 00000000..229dedc4
--- /dev/null
+++ b/tests/perf/PresentSinkLifecycleTests.cpp
@@ -0,0 +1,61 @@
+#include "veyra/gfx/PresentSink.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/Log.h"
+#include <d3d12sdklayers.h>
+#include <filesystem>
+#include <iostream>
+#include <vector>
+
+// Real window close / failed reopen / second close / valid reopen. No NGX,
+// allocation pressure, device fault injection or artificial GPU workload.
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra;
+ if(argc!=2)return 2;
+ const std::filesystem::path output=argv[1];std::filesystem::create_directories(output);
+ Logger::instance().openFile((output/L"engine.log").wstring());
+ WNDCLASSW wc{};wc.hInstance=GetModuleHandleW(nullptr);wc.lpfnWndProc=DefWindowProcW;
+ wc.lpszClassName=L"VeyraPresentSinkLifecycleFixture";
+ if(!RegisterClassW(&wc))return 2;
+ gfx::D3D12DeviceContext ctx;gfx::DeviceContextDesc device;device.enableDebugLayer=true;
+ Status status=Status::Ok;if(!ctx.initialize(device,status))return 2;
+ gfx::ComPtr<ID3D12InfoQueue> info;
+ if(FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info))))return 2;
+ info->ClearStoredMessages();
+ auto makeWindow=[&]{return CreateWindowExW(WS_EX_NOACTIVATE,wc.lpszClassName,L"Veyra lifecycle",
+ WS_POPUP,40,40,320,180,nullptr,nullptr,wc.hInstance,nullptr);};
+ auto makeQueue=[&](gfx::ComPtr<ID3D12CommandQueue>& queue){
+ D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;
+ return SUCCEEDED(ctx.device()->CreateCommandQueue(&desc,IID_PPV_ARGS(&queue)));
+ };
+ bool pass=true;
+ for(unsigned round=0;round<3&&pass;++round){
+ gfx::PresentSink sink;gfx::ComPtr<ID3D12CommandQueue> first,second;
+ HWND window=makeWindow();if(!window||!makeQueue(first))return 2;
+ gfx::PresentSink::Desc desc;desc.targetWindow=window;desc.width=320;desc.height=180;
+ pass=sink.initialize(ctx.device(),first.Get(),desc,status);
+ sink.shutdown();pass=pass&&sink.hwnd()==nullptr;
+ first.Reset();const HWND closed=window;DestroyWindow(window);
+ if(!makeQueue(second))return 2;
+ desc.targetWindow=closed;
+ pass=pass&&!sink.initialize(ctx.device(),second.Get(),desc,status)&&status==Status::WindowFailure;
+ sink.shutdown();sink.shutdown();pass=pass&&sink.hwnd()==nullptr;
+ window=makeWindow();if(!window)return 2;desc.targetWindow=window;
+ pass=pass&&sink.initialize(ctx.device(),second.Get(),desc,status);
+ sink.shutdown();sink.shutdown();pass=pass&&sink.hwnd()==nullptr;
+ second.Reset();DestroyWindow(window);
+ std::cout<<"LIFECYCLE round="<<round<<" passed="<<pass<<std::endl;
+ }
+ unsigned errors=0;
+ for(UINT64 i=0;i<info->GetNumStoredMessagesAllowedByRetrievalFilter();++i){
+ SIZE_T size=0;if(FAILED(info->GetMessage(i,nullptr,&size)))return 2;
+ std::vector<char> storage(size);auto* message=reinterpret_cast<D3D12_MESSAGE*>(storage.data());
+ if(FAILED(info->GetMessage(i,message,&size)))return 2;
+ if(message->Severity<=D3D12_MESSAGE_SEVERITY_ERROR){
+ ++errors;std::cerr<<"DEBUG_ERROR "<<message->pDescription<<std::endl;
+ }
+ }
+ pass=pass&&errors==0&&SUCCEEDED(ctx.device()->GetDeviceRemovedReason());
+ info.Reset();ctx.shutdown();UnregisterClassW(wc.lpszClassName,wc.hInstance);
+ std::cout<<"LIFECYCLE_RESULT passed="<<pass<<" debugErrors="<<errors<<std::endl;
+ return pass?0:1;
+}