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: retain XeSS buffers and skip obsolete preview waits

Veyra Goal Agent88ed81cf25f7
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 428efdeb..bf268816 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -577,6 +577,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
add_executable(veyra_capture_color_tests tests/unit/CaptureColorContractTests.cpp)
add_executable(veyra_presentation_worker_tests tests/unit/LiveGpuSchedulerTests.cpp)
target_compile_features(veyra_presentation_worker_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_presentation_worker_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_include_directories(veyra_presentation_worker_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(veyra_realtime_preview_tests tests/unit/RealtimePreviewSchedulingTests.cpp)
target_compile_features(veyra_realtime_preview_tests PRIVATE cxx_std_20)
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index c90acca8..2211913a 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -20,7 +20,7 @@
采集呈现相位优化及原始 1.4.2beta 引擎同参数对照见[延迟优化与历史对比](CAPTURE_LATENCY_REDUCTION_2026-09-18.md)。保持 4K30 NV12、NR、DLSS4X,不使用换格式或降低倍率解释收益。
-DLSS / XeSS 双侧长帧排查见[分段诊断与实卡证据](FRAME_STALL_INVESTIGATION_2026-09-18.md)。本机已重现 XeSS 窗口重建阻塞;粉丝正常播放的约 1.4 秒呈现阻塞、历史 DLSS 尖峰尚未归因。本轮添加分段和逐长帧日志,不宣称性能修复,不更新既有 beta 包。
+DLSS / XeSS 双侧长帧调查及后续修复见[调查](FRAME_STALL_INVESTIGATION_2026-09-18.md)与[修复实测](FRAME_STALL_REPAIR_2026-09-18.md)。XeSS 改为保留呈现缓冲,三次缩放从丢 9 帧降到 0,代价是小窗口原生 NR 测得约多 2–4ms;另修复过期生成帧先等 GPU、阻挡就绪原帧的问题。DLSS4X 与 XeSS2X 后续各 120 秒均零采集丢帧,DLSS 注入阻塞恢复及 2X/6X/4X 切换通过。不代表全部卡顿已修好:两后端均抓到第 304 帧 NR Evaluate 约 49ms;另一次 DLSS CPU 尾部约 388ms、粉丝 HDR 正常播放约 1.4 秒呈现阻塞仍未根治。保留细分诊断,不更新既有 beta 包。
RTX Video HDR 独立改动保留。用户已明确终止 NVIDIA FSR 4.1 实验并要求回退,不再执行此前 FSR4 施工和画质修复计划。
diff --git a/docs/FRAME_STALL_REPAIR_2026-09-18.md b/docs/FRAME_STALL_REPAIR_2026-09-18.md
new file mode 100644
index 00000000..2c337c31
--- /dev/null
+++ b/docs/FRAME_STALL_REPAIR_2026-09-18.md
@@ -0,0 +1,167 @@
+# Frame stall repair, 2026-09-18
+
+Status: two scoped fixes implemented and validated. The NR runtime spike,
+sporadic CPU-tail stall and fan's steady HDR stall remain open; not a full cure.
+Baseline: c7464bb; checkpoint/pre-stall-repair-20260918.
+Branch: codex/frame-pacing-20260918. No merge, publication or package.
+
+## Scope and acceptance
+
+1. Reduce the reproduced XeSS ResizeBuffers stall without changing capture
+ format, source resolution, NR quality or requested FG multiplier. Preserve
+ GPU lifetime waits and final window geometry.
+2. Inspect expired generated-frame waits that can hold a ready original behind
+ an obsolete output. Only preview scheduling may skip expired generated frames;
+ preserve fences, leases, counters and chronological surviving output.
+3. Verify with VC-007PRO 3840x2160 NV12 29.97fps, NR + XeSS2X/native and
+ DLSS4X/realtime, using the existing repeatable resize probe and steady runs.
+ SDK success is not proof of physical scanout or elimination of all stutters.
+4. Record rejected experiments and remaining uncertainty. The supplied fan's
+ 1.4-second steady HDR stall is not reproduced locally and has no proven cause.
+
+Outputs: E:/项目/Veyra/{tests,logs,tmp}/frame-stall-repair-20260918;
+build: E:/项目/Veyra/build/frame-pacing-20260918.
+
+## Implemented changes
+
+- `VideoPresenter` retains XeSS buffers at least as large as the current monitor.
+ Ordinary window resize does not shrink/rebuild provider resources. A larger
+ client or monitor can still grow them with the existing GPU drains. This is
+ intentionally XeSS-only. It consumes more output work/memory in small windows.
+- `PresentationGeometry.h` maps the client's fit/zoom/pan rectangle into retained
+ buffer coordinates, matching PresentBlit. Empty/offscreen regions cannot tag an
+ out-of-bounds rectangle. Client geometry changes reset interpolation history.
+- `PreviewFrameReadiness.h` rejects obsolete/suppressed/invalid generated preview
+ output before waiting on its producer fence. Original frames still require
+ their fence. Completion watchers retain GPU leases and resolve generation even
+ when a presentation job has skipped its output; export is unchanged.
+- Engine long-frame diagnostics separate capture metrics, GPU metrics, timestamp
+ collection, flow aggregation, snapshot publication and periodic logging. The
+ engine threshold is 45ms; other traces retain 80ms. Wall time includes OS
+ descheduling. Capture age logs also report deadline, lateness, wait and Present.
+- `EnhanceGraph` records CPU stages only for calls over30ms, separating upload,
+ NVOF Execute, NR command acquisition/parameter setup/Evaluate and FG Evaluate.
+ This is CPU call duration; GPU timestamps remain separate.
+
+## Evidence so far
+
+Same VC-007PRO 3840x2160 NV12 29.97Hz input, RTX5070 / driver616.56,
+SDR2560x1440@100Hz, window1280x760, muted WASAPI, SR/sync off. Each run has
+10s warmup. XeSS2X uses native4K NR; DLSS4X uses the same realtime NR policy as
+the baseline. Different NR policies/backends are not an equal-cost comparison.
+
+| Run directory | Formal seconds | Sample P50/P95 ms | Capture drops |
+| --- | ---: | ---: | ---: |
+| baseline `frame-stall-20260918/xess2-native-resize40` | 40 | 45.624 / 50.448 | 9 |
+| `xess2-drain-experiment40` (rejected) | 40 | 46.261 / 50.740 | 9 |
+| `xess2-retained40` | 40 | 48.372 / 54.984 | 0 |
+| `xess2-final-resize40` | 40 | 49.907 / 57.260 | 0 |
+| `dlss4-final120` | 120 | 40.223 / 40.653 | 10 |
+| `dlss4-tail120` | 120 | 40.206 / 40.572 | 0 |
+| `xess2-tail120` | 120 | 48.736 / 55.666 | 0 |
+| `xess2-graph40` (resize) | 40 | 48.148 / 53.089 | 0 |
+| `xess4-final-resize40` (realtime NR) | 40 | 35.097 / 35.544 | 0 |
+
+The three resizes occur at formal10/20/30s. Baseline XeSS ResizeBuffers took
+115.439/103.269/102.315ms while queue drain was only about0.04ms. A rejected
+250ms debounce plus three disabled-generation frames still lost9 frames. That
+experiment is removed from source. Retained-buffer runs had no ordinary
+ResizeBuffers calls and no capture drops. Median latency increased2.748/4.283ms
+against the resize baseline, so this is a stutter/resize fix, not a claim that
+all XeSS latency decreased. Startup GPU/readiness spikes remain in the logs.
+
+The first final DLSS run contained a separate390.077ms engine iteration at
+source3087:387.874ms was in the previously unsplit CPU tail; GPU readiness was
+observed at10.120ms, GPU span14.326ms, Present0.368ms, callback-to-return424.911ms.
+It lost10 capture frames and expired3 generated outputs. The50ms snapshot max
+was only42.961ms: it missed the transient. Never use that sampled maximum as the
+all-frame maximum. Added diagnostics do not themselves fix this unknown stall.
+The subsequent `dlss4-tail120` run completed120.049s,3597 received,zero dropped,
+NR/FG continuously active, no45ms engine or80ms capture-age event. Non-recurrence
+does not establish the cause or prove a fix.
+
+XeSS native4K NR `xess2-tail120` completed120.047s,3597 received/processed,
+zero capture drops,NR/FG continuously active. The startup spike was narrowed
+with `xess2-graph40`, then `xess2-nr-trace10`: frame304 graph CPU50.215ms,
+NR Evaluate49.060ms,NR acquisition0.030ms,parameters0.012ms,upload0.560ms,
+NVOF Execute0.180ms. Graph GPU span66.868ms versus about26ms normally. This
+identifies the synchronous NR runtime call, not its internal reason (which may
+include driver work or OS preemption). Do not label it an XeSS pacing defect or
+claim it is fixed. No matching304-frame/10s periodic work was found in the
+investigated caller.
+The short diagnostic run also completed cleanly with299 formal inputs/no drops.
+
+The final XeSS4X resize run completed40.0165s,1198 inputs,no capture drops and
+continuous NR/FG. It also recorded NR Evaluate49.802ms at frame304 in startup.
+The final DLSS recovery run recorded48.491ms in the same NR call at frame304.
+Thus this approximately49ms event occurs with both providers and both NR sizes;
+it is not specific to native4K XeSS. No change to that runtime is claimed.
+
+## Verification commands
+
+Run from this worktree unless indicated otherwise. Each hardware run is serial,
+with a200s process timeout (below the300s single-test limit).
+
+```powershell
+./scripts/build-isolated.ps1 -Root . -BuildDirectory 'E:/项目/Veyra/build/frame-pacing-20260918' -DependencyCache 'E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt' -TempDirectory 'E:/项目/Veyra/tmp/frame-stall-repair-20260918' -DisplayVersion 1.4.2beta -Targets veyra_capture_latency_tests,veyra,veyra_preview_geometry_tests,veyra_presentation_worker_tests,veyra_presentation_pacing_tests
+./scripts/test-capture-version-comparison.ps1 -Build 'E:/项目/Veyra/build/frame-pacing-20260918' -Name xess2-final-resize40 -Backend xess -Multiplier 2 -Nr native -Resize -Seconds 40 -Output 'E:/项目/Veyra/tests/frame-stall-repair-20260918' -TempDirectory 'E:/项目/Veyra/tmp/frame-stall-repair-20260918'
+./scripts/test-capture-version-comparison.ps1 -Build 'E:/项目/Veyra/build/frame-pacing-20260918' -Name dlss4-tail120 -Output 'E:/项目/Veyra/tests/frame-stall-repair-20260918' -TempDirectory 'E:/项目/Veyra/tmp/frame-stall-repair-20260918'
+```
+
+Build logs: `build-final.log` initially failed on Windows min/max macros in the
+expanded unit-test includes; target-local NOMINMAX/WIN32_LEAN_AND_MEAN fixed it.
+`build-final-retry.log` and `build-tail.log` passed. Unit suite56 checks passed;
+GPU geometry readback passed fit/zoom/pan/reference/reset and retained-buffer
+square-client/zoom cases. Geometry readback verifies blit coordinates, not XeSS
+interpolated image quality. Test logs: `unit.log`, `geometry.log` under the task
+logs directory; images under the task tests directory `geometry`.
+
+Subsequent diagnostic builds `build-graph-trace.log` and `build-nr-trace.log`
+passed. All listed completed hardware runs returned0. NR CreateFeature18 and
+DLSSG Create returned0x1,non-null handles,seh0; XeSS Create/Init/XeLL returned0.
+Successful Evaluate is evidenced by growing NR/FG counters and no execution
+failure/degradation; SDK success does not imply stutter-free rendering.
+
+Final `build-verified.log` passed (exit0) after increasing CPU trace capacity to32
+marks so6X subframe diagnostics retain the final stages. This last change only
+affects trace storage; the hardware results above precede that capacity increase.
+Final inspection found no running Veyra test processes and an empty task tmp
+directory. Main's working tree is clean; fixes remain on the isolated branch.
+
+Final recovery command from the build directory, per-process TEMP/TMP set to
+the task tmp directory, via hidden Start-Process with a180s timeout:
+
+```powershell
+./veyra_presentation_pacing_tests.exe ignored 'E:/项目/Veyra/tests/frame-stall-repair-20260918/dlss4-recovery' -1 2 4 3 capture-nr-recovery
+```
+
+Exit0: baseline89 capture frames/no drops; injected80ms owner-thread work for3s
+produced reported mailbox drops;12s recovery restored NR/FG without sustained
+budget limiting or accumulated latency (P95 below80ms);pause/resume and2X/6X/4X
+reconfiguration passed,clean stop. This tests actual DLSS GPU resource lifecycle
+and recovery in addition to the unit decision tests. Full release/export gate
+was not run; this is scoped preview acceptance, not a release certification.
+
+Analysis:
+
+```powershell
+python scripts/acceptance/analyze-capture-version-comparison.py 'E:/项目/Veyra/tests/frame-stall-repair-20260918' xess2-drain-experiment40 xess2-retained40 xess2-final-resize40 dlss4-final120 dlss4-tail120 xess2-tail120 xess2-graph40 xess2-nr-trace10 xess4-final-resize40
+```
+
+`comparison.json` holds sampled statistics plus whole-run slow events separately.
+The original logs are preserved, including failed experiments and the390ms
+stall. Each run's `run.json` records arguments and test executable hash.
+
+## Limits and next evidence
+
+The fan's RTX5080 / ASUS4KPRO / P010 HLG-to-PQ native4K XeSS2X steady1.4s
+present-wrapper stall has not been reproduced or fixed. That original wrapper
+combines SDK markers, DXGI Present, buffer-index and SDK status calls; low GPU
+utilization alone cannot identify its cause. The current build has split those
+calls. Need a log from the original HDR setup to attribute the long call.
+
+Local measurements are capture callback to original Present return, not HDMI
+input to physical scanout. XeSS can present asynchronously after return. HDR,
+multi-monitor, actual RTX30/40, FSR rendering, scanout cadence and visual XeSS
+interpolation quality were not validated in this repair. No runtime changed,
+no main merge, push, release, or beta package replacement.
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 63bd2c2a..e1034591 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-09-18 长帧修复与追加实测
+
+用户要求实际修复,继续 `codex/frame-pacing-20260918`,基线 `c7464bb`,存档 `checkpoint/pre-stall-repair-20260918`。两项实现:XeSS 保留至少显示器尺寸的缓冲,普通缩放不再触发提供方重建,颜色区域按 client/buffer 几何映射并重置插值历史;实时预览先跳过过期/被抑制生成帧,再检查 GPU 就绪,原帧 fence 和 completion watcher 的资源持有保留。没有更改采集格式、NR 档位、请求倍率、运行库或导出行为。源文件、全部命令、日志、拒绝的实验与边界见 [修复报告](FRAME_STALL_REPAIR_2026-09-18.md)。
+
+VC-007PRO 4K30 NV12 / RTX5070 / 616.56:XeSS2X 原生 NR 三次缩放从基线丢 9 帧变为连续三轮零丢帧;100ms 级 ResizeBuffers 路径不再调用。保留较大缓冲有成本,中位回调到原帧 Present 返回相对缩放基线多约 2–4ms,不能称为全面降低延迟。XeSS4X 实时 NR 三次缩放亦零丢帧。DLSS4X 与 XeSS2X 后续各 120 秒,3597 输入、零采集丢帧,中位 40.206/48.736ms;这是软件返回时间,不是物理扫描延迟。DLSS 人为 80ms 阻塞恢复、暂停/恢复、2X→6X→4X 均通过。
+
+未隐瞒的残留:第一轮 DLSS 正式窗丢 10 帧,单次 CPU 尾部 387.874ms、原帧回调到返回 424.911ms,随后 120 秒未重现,新增细分统计/状态/日志计时但未声称修好。启动第 304 帧约 49ms 尖峰在 XeSS2X/4X、DLSS4X 均重现,已定位 NR Evaluate 调用本身(49.060/49.802/48.491ms),不是命令槽等待,内部原因未确定。粉丝原 HDR/ASUS 卡约 1.4 秒呈现阻塞未重现,不能将缩放修复冒充该问题根治。
+
+构建五目标成功,最终 `build-verified.log` exit0;末次仅将 CPU 诊断容量增至32,避免6X子帧标记截断,实卡结果在这一纯诊断容量调整之前取得。早期 min/max 宏编译失败已通过测试目标 NOMINMAX 修正。56 项单测、实际 GPU 几何读回通过;所有本轮完成的真机测试 exit0,NR/DLSSG Create0x1 seh0,XeSS Create/Init/XeLL0,计数持续增长且无运行错误。通过只表示各自检查,不等于没有长帧。未跑全发布/导出门禁,HDR、多屏、30/40 实卡、扫描与 XeSS 插值画质未执行。收尾无 Veyra 测试进程,任务临时目录为空,main 工作区干净。
+
+构建 `E:/项目/Veyra/build/frame-pacing-20260918`;实测/CSV/原始日志 `E:/项目/Veyra/tests/frame-stall-repair-20260918`;构建和分析 `E:/项目/Veyra/logs/frame-stall-repair-20260918`;临时 `E:/项目/Veyra/tmp/frame-stall-repair-20260918`。保留失败实验作为必要证据,没有新包或解压副本。未合并 main、推送或发布,SDK/运行库未入 Git。下一项:用当前分段诊断构建在反馈者原 HDR 配置抓长停顿,结合已定位 NR 调用继续处理未解决的长帧。
+
## 2026-09-18 DLSS / XeSS 两侧偶发长帧排查
用户要求两边排查。沿用隔离分支 `codex/frame-pacing-20260918`,基线 `23cc720`,存档 `checkpoint/pre-stall-investigation-20260918`。本轮只加诊断与实测入口,未改调度策略或输入格式。逐项证据、修改文件、命令、真实返回码及限制见 [长帧调查](FRAME_STALL_INVESTIGATION_2026-09-18.md)。
diff --git a/include/veyra/diagnostics/CpuStallTrace.h b/include/veyra/diagnostics/CpuStallTrace.h
index 1886a502..087a6786 100644
--- a/include/veyra/diagnostics/CpuStallTrace.h
+++ b/include/veyra/diagnostics/CpuStallTrace.h
@@ -11,8 +11,8 @@ namespace veyra::diagnostics {
class CpuStallTrace {
using Clock = std::chrono::steady_clock;
public:
- explicit CpuStallTrace(const char* component, uint64_t frame = 0)
- : component_(component), frame_(frame) {}
+ explicit CpuStallTrace(const char* component, uint64_t frame = 0, double thresholdMs = 80.0)
+ : component_(component), frame_(frame), thresholdMs_(thresholdMs) {}
void mark(const char* stage) {
const auto now = Clock::now();
if (count_ < samples_.size()) samples_[count_++] = {stage, ms(now - last_)};
@@ -20,7 +20,7 @@ public:
}
~CpuStallTrace() {
const auto total = ms(Clock::now() - start_);
- if (total < 80.0) return;
+ if (total < thresholdMs_) return;
mark("tail");
std::string detail;
for (size_t i = 0; i < count_; ++i)
@@ -32,8 +32,9 @@ private:
struct Sample { const char* name; double ms; };
const char* component_;
uint64_t frame_;
+ double thresholdMs_;
Clock::time_point start_ = Clock::now(), last_ = start_;
- std::array<Sample, 12> samples_{};
+ std::array<Sample, 32> samples_{};
size_t count_ = 0;
};
}
diff --git a/include/veyra/engine/PresentationGeometry.h b/include/veyra/engine/PresentationGeometry.h
new file mode 100644
index 00000000..6d8e5d89
--- /dev/null
+++ b/include/veyra/engine/PresentationGeometry.h
@@ -0,0 +1,22 @@
+#pragma once
+#include "veyra/engine/PreviewView.h"
+#include <windows.h>
+#include <algorithm>
+#include <cmath>
+
+namespace veyra::engine {
+// PresentBlit fits in client coordinates; DXGI stretches the buffer to that
+// client. Provider color rectangles must use the inverse of the same mapping.
+inline RECT presentationRegion(unsigned imageWidth,unsigned imageHeight,
+ unsigned clientWidth,unsigned clientHeight,unsigned bufferWidth,unsigned bufferHeight,PreviewView view){
+ if(!imageWidth||!imageHeight||!clientWidth||!clientHeight||bufferWidth<2||bufferHeight<2)return {};
+ const float zoom=std::isfinite(view.zoom)&&view.zoom>0?view.zoom:1.0f;
+ const float fit=std::min(float(clientWidth)/imageWidth,float(clientHeight)/imageHeight)*zoom;
+ const float sx=float(bufferWidth)/clientWidth,sy=float(bufferHeight)/clientHeight;
+ const float left=(clientWidth*.5f-view.centerX*imageWidth*fit)*sx;
+ const float top=(clientHeight*.5f-view.centerY*imageHeight*fit)*sy;
+ const auto edge=[](float value,unsigned bound){return LONG(std::clamp(value,0.0f,float(bound)))&~1L;};
+ return {edge(left,bufferWidth),edge(top,bufferHeight),
+ edge(left+imageWidth*fit*sx+.5f,bufferWidth),edge(top+imageHeight*fit*sy+.5f,bufferHeight)};
+}
+}
diff --git a/include/veyra/engine/PreviewFrameReadiness.h b/include/veyra/engine/PreviewFrameReadiness.h
new file mode 100644
index 00000000..9a57be48
--- /dev/null
+++ b/include/veyra/engine/PreviewFrameReadiness.h
@@ -0,0 +1,21 @@
+#pragma once
+#include "veyra/pipeline/FrameBatch.h"
+
+namespace veyra::engine {
+enum class PreviewFrameReadiness { Ready, Pending, Invalid, Suppressed, Expired };
+
+// Obsolete preview outputs must not hold a ready original behind their fences.
+// This only decides presentation; the completion watcher still owns every GPU
+// lease and resolves generation status before resources can be recycled.
+template<class Resolve>
+PreviewFrameReadiness previewFrameReadiness(pipeline::BatchFrame& frame,bool suppressed,bool expired,Resolve&& resolve){
+ const bool generated=frame.kind==pipeline::FrameKind::Generated;
+ if(generated){
+ if(frame.validity!=pipeline::GenerationValidity::Pending&&frame.validity!=pipeline::GenerationValidity::Valid)return PreviewFrameReadiness::Invalid;
+ if(suppressed)return PreviewFrameReadiness::Suppressed;
+ if(expired)return PreviewFrameReadiness::Expired;
+ }
+ if(!resolve())return PreviewFrameReadiness::Pending;
+ return generated&&frame.validity!=pipeline::GenerationValidity::Valid?PreviewFrameReadiness::Invalid:PreviewFrameReadiness::Ready;
+}
+}
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 726013fd..6bd73a16 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -71,6 +71,9 @@ private:
unsigned lastBuffer_=0;bool hasPresented_=false;
HWND window_=nullptr;
std::chrono::steady_clock::time_point lastResize_{};
+ unsigned viewWidth_=0,viewHeight_=0;
+ HMONITOR bufferMonitor_=nullptr;
+ unsigned monitorWidth_=0,monitorHeight_=0;
std::chrono::steady_clock::time_point nextCostLog_{};
std::chrono::steady_clock::time_point lastXessFrame_{};
pipeline::FrameIdentity lastXessIdentity_{};
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 93ecc8e0..7e145008 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1,4 +1,5 @@
#include "veyra/engine/EngineController.h"
+#include "veyra/engine/PreviewFrameReadiness.h"
#include "veyra/engine/FgCompatibilityProbe.h"
#include "veyra/engine/VideoPresenter.h"
#include "veyra/engine/VideoExportJob.h"
@@ -678,7 +679,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
return true;
};
while(!stop_){
- diagnostics::CpuStallTrace loopTrace("engine-stall",frames);
+ diagnostics::CpuStallTrace loopTrace("engine-stall",frames,45.0);
collectTimings();
loopTrace.mark("collect");
if(captureRecovering){
@@ -1232,22 +1233,23 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
while(s.next<batch.batch.count){auto& item=batch.batch.frames[s.next];const bool generated=item.kind==pipeline::FrameKind::Generated;
if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0)return {State::Complete};
- if(isCapture&&!graph.resolveFrame(batch,s.next)){
- if(elapsedMs(s.readyStart)>2000){veyra::log::error("capture-present","GPU frame ready timeout");return {State::Failed};}
- return {State::Pending,host100ns()+2000};
- }
- if(isCapture&&!s.readyReported){s.readyMs=elapsedMs(s.readyStart);s.readyReported=true;flow->cpu(diagnostics::CpuStage::ReadyWait,s.readyMs,host100ns());}
- if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++s.handled;++s.next;continue;}
- if(generated&&(comparisonMode_!=0||!generatedPresentationCurrent(jobGeneration,presentationGeneration.load()))){++presentationSkippedGenerated;++s.next;continue;}
const 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 !isCapture||graph.resolveFrame(batch,s.next);});
+ if(readiness==PreviewFrameReadiness::Pending){
+ if(elapsedMs(s.readyStart)>2000){veyra::log::error("capture-present","GPU frame ready timeout");return {State::Failed};}
+ return {State::Pending,host100ns()+2000};
+ }
+ if(readiness==PreviewFrameReadiness::Invalid){++s.handled;++s.next;s.deadlineStart.reset();continue;}
+ if(readiness==PreviewFrameReadiness::Suppressed){++presentationSkippedGenerated;++s.next;s.deadlineStart.reset();continue;}
+ if(isCapture&&readiness==PreviewFrameReadiness::Ready&&!s.readyReported){s.readyMs=elapsedMs(s.readyStart);s.readyReported=true;flow->cpu(diagnostics::CpuStage::ReadyWait,s.readyMs,host100ns());}
if(generated&&isCapture&&decisionTime>=nextFgDeadlineLog){
nextFgDeadlineLog=decisionTime+10000000;
const auto ready=watch->frameReadyObserved[s.next];
veyra::log::info("fg-deadline",std::format("revision={} batch={} subframe={} expired={} readyObservedLateMs={:.3f} decisionLateMs={:.3f} observedReadyToDecisionMs={:.3f} batchReady={} (CPU fence observations, not scanout)",item.identity.settingsRevision,batch.batch.batchId,item.subframe,generationExpired,double(ready-timeline.deadline(item.pts100ns))/10000,double(decisionTime-timeline.deadline(item.pts100ns))/10000,ready?double(decisionTime-ready)/10000:-1,watch->ready.load()));
}
- if(generationExpired){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}
+ if(readiness==PreviewFrameReadiness::Expired){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}
if(!s.deadlineStart)s.deadlineStart=Clock::now();
if(isCapture){if(host100ns()<timeline.deadline(item.pts100ns))return {State::Pending,timeline.deadline(item.pts100ns)};}
else if(!fileAwaitingVideo){
@@ -1329,7 +1331,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto returned=host100ns();
flow->latency(captureArrival,returned);
const double age=double(returned-captureArrival)/10000;
- if(physicalCapture&&age>=80.0)veyra::log::info("capture-age-stall",std::format("source={} epoch={} revision={} callbackToReturnMs={:.3f} readyObservedAgeMs={:.3f} gpuSpanMs={:.3f} (CPU observation includes scheduling; not scanout)",item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,age,watch->frameReadyObserved[s.next]?double(watch->frameReadyObserved[s.next]-captureArrival)/10000:-1.0,watch->gpuExecutionMs.value_or(-1.0)));
+ if(physicalCapture&&age>=80.0)veyra::log::info("capture-age-stall",std::format("source={} epoch={} revision={} callbackToReturnMs={:.3f} readyObservedAgeMs={:.3f} gpuSpanMs={:.3f} deadlineAgeMs={:.3f} decisionLateMs={:.3f} deadlineWaitMs={:.3f} presentMs={:.3f} (CPU observation includes scheduling; not scanout)",item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,age,watch->frameReadyObserved[s.next]?double(watch->frameReadyObserved[s.next]-captureArrival)/10000:-1.0,watch->gpuExecutionMs.value_or(-1.0),double(timeline.deadline(item.pts100ns)-captureArrival)/10000,double(optionalNow-timeline.deadline(item.pts100ns))/10000,waited,elapsed));
}
if(didPresent&&!generated&&!rereadCached&&!paused_){
const auto stamp=host100ns();const auto stats=flow->snapshot(stamp);
@@ -1398,6 +1400,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;
}
#endif
+ loopTrace.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);
// Present-sink FG backends record their application-side work on
@@ -1405,7 +1408,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// the stage unmeasured. The in-graph DLSS FG keeps its own.
if(graph.xessEnabled()||graph.fsrEnabled())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()){
@@ -1427,7 +1432,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
frameFlow->update([&](auto& m){m.counters.captureReceived=captureStats.received-captureFlowBase.received;m.counters.mailboxOverwritten=captureStats.dropped-captureFlowBase.dropped;m.counters.sourceSkippedBeforeGraph=skipped;m.slotReuseWaitCount=slotWaitCount;m.slotReuseWaitMs=slotWaitMilliseconds;m.counters.commandSlotsInFlight=slotsInFlight;m.counters.commandSlotHighWater=std::max(m.counters.commandSlotHighWater,slotsInFlight);});
frameFlow->update([&](auto& m){m.slotWaitPerFrameMs=processSlotWaitMs;});
captureFlowLast=captureStats;
+ loopTrace.mark("flowUpdate");
measured.flow=frameFlow->snapshot(host100ns());
+ loopTrace.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=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];
@@ -1462,6 +1469,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
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;
}
+ loopTrace.mark("publishSnapshot");
const auto gpuP95=[&](diagnostics::GpuStage stage){return gpuStageTimes[size_t(stage)].p95();};
if(Clock::now()>=nextTimingLog){const auto [retained,overwritten]=Logger::instance().frameTraceSize();
veyra::log::info("frame-trace",std::format("retained={} capacity=8192 overwritten={} (records available in diagnostic preview)",retained,overwritten));}
@@ -1475,6 +1483,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} singleGpuOwner=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveScheduler?completed.readyP95:gpuReadyTimes.p95(),waitP95,presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));
nextTimingLog=Clock::now()+std::chrono::seconds(1);
}
+ loopTrace.mark("periodicLogs");
}
}while(false);
}catch(const std::exception& e){veyra::log::error("engine",e.what());status(L"引擎异常,请查看诊断",true);failed=true;}
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 8082cde9..429beafa 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -1,4 +1,5 @@
#include "veyra/engine/VideoPresenter.h"
+#include "veyra/engine/PresentationGeometry.h"
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/gfx/D3D12DeviceContext.h"
#include "veyra/gfx/CommandSlotRing.h"
@@ -6,6 +7,7 @@
namespace veyra::engine {
bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible) {
close();
+ viewWidth_=viewHeight_=0;bufferMonitor_=nullptr;monitorWidth_=monitorHeight_=0;
++generation_;
Status st=Status::Ok;
if(graph.fgEnabled()&&!graph.xessEnabled()&&!graph.fsrEnabled()){
@@ -22,6 +24,15 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh
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.waitable=!GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",nullptr,0);
d.hdr=graph.hdrOutput();d.hdr10=graph.hdr10Output();d.xess=graph.xessEnabled();d.fsr=graph.fsrEnabled();d.renderWidth=graph.workWidth();d.renderHeight=graph.workHeight();d.captureCompatible=captureCompatible;d.fgMultiplier=graph.fgMultiplier();lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;lastFsrFrame_={};lastFsrIdentity_={};fsrWasEnabled_=false;
+ if(d.xess){
+ bufferMonitor_=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);
+ MONITORINFO monitor{sizeof(monitor)};
+ if(GetMonitorInfoW(bufferMonitor_,&monitor)){
+ monitorWidth_=monitor.rcMonitor.right-monitor.rcMonitor.left;monitorHeight_=monitor.rcMonitor.bottom-monitor.rcMonitor.top;
+ d.width=std::max(d.width,monitorWidth_);d.height=std::max(d.height,monitorHeight_);
+ }
+ veyra::log::info("present",std::format("XeSS retained buffers {}x{} client={}x{}; window scaling avoids provider rebuild",d.width,d.height,rc.right,rc.bottom));
+ }
if(!sink_.initialize(ctx.device(),queue,d,st))return false;
std::vector<uint8_t> vs,ps;
// SRV layout: 0..1 video frames, 2..11 generated frames (2 parities x 5
@@ -45,9 +56,24 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
const auto now=std::chrono::steady_clock::now();
bool resized=false;
const auto deferUntil=uint64_t(uintptr_t(GetPropW(window_,L"Veyra.ResizeDeferUntil")));
- if((unsigned(rc.right)!=sink_.width()||unsigned(rc.bottom)!=sink_.height())&&GetTickCount64()>=deferUntil&&now-lastResize_>=std::chrono::milliseconds(100)) {
+ if(viewWidth_!=unsigned(rc.right)||viewHeight_!=unsigned(rc.bottom)){
+ viewWidth_=rc.right;viewHeight_=rc.bottom;xessWasEnabled_=fsrWasEnabled_=false;
+ }
+ unsigned targetWidth=rc.right,targetHeight=rc.bottom;
+ if(sink_.xess()){
+ const auto monitor=MonitorFromWindow(window_,MONITOR_DEFAULTTONEAREST);
+ if(monitor!=bufferMonitor_){
+ bufferMonitor_=monitor;MONITORINFO info{sizeof(info)};
+ if(GetMonitorInfoW(monitor,&info)){monitorWidth_=info.rcMonitor.right-info.rcMonitor.left;monitorHeight_=info.rcMonitor.bottom-info.rcMonitor.top;}
+ }
+ // Never shrink the provider's working set on ordinary window changes.
+ // Grow only when the client or a new display needs more output pixels.
+ targetWidth=std::max({targetWidth,sink_.width(),monitorWidth_});
+ targetHeight=std::max({targetHeight,sink_.height(),monitorHeight_});
+ }
+ if((targetWidth!=sink_.width()||targetHeight!=sink_.height())&&GetTickCount64()>=deferUntil&&now-lastResize_>=std::chrono::milliseconds(100)) {
resized=true;
- if(!ring.drainQueue())return false;sink_.resize(rc.right,rc.bottom);
+ if(!ring.drainQueue())return false;sink_.resize(targetWidth,targetHeight);
// A capture hook may temporarily retain a DXGI buffer. Keep the old
// valid buffers and let DXGI scale them until a later resize succeeds.
if(!sink_.currentBackBuffer()||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;
@@ -96,23 +122,13 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
// exact `view == PreviewView{}` guard disabled generation forever after
// any wheel zoom or drag, even when the user zoomed back out. The rect is
// clipped to the window and aligned to even coordinates for the providers.
- const float winW=float(sink_.bufferWidth()),winH=float(sink_.bufferHeight());
- const float imgW=float(graph.workWidth()),imgH=float(graph.workHeight());
- const float viewZoom=view.zoom>0.0f?view.zoom:1.0f;
- const float viewFit=std::min(winW/imgW,winH/imgH)*viewZoom;
- const float imageLeft=winW*0.5f-view.centerX*imgW*viewFit;
- const float imageTop=winH*0.5f-view.centerY*imgH*viewFit;
- LONG fgLeft=std::max(0L,LONG(imageLeft))&~1L;
- LONG fgTop=std::max(0L,LONG(imageTop))&~1L;
- LONG fgRight=std::min(LONG(winW+0.5f),LONG(imageLeft+imgW*viewFit+0.5f))&~1L;
- LONG fgBottom=std::min(LONG(winH+0.5f),LONG(imageTop+imgH*viewFit+0.5f))&~1L;
- fgRight=std::max(fgLeft+2L,fgRight);fgBottom=std::max(fgTop+2L,fgBottom);
- const RECT fgRect{fgLeft,fgTop,fgRight,fgBottom};
+ const RECT fgRect=presentationRegion(graph.workWidth(),graph.workHeight(),rc.right,rc.bottom,sink_.bufferWidth(),sink_.bufferHeight(),view);
+ const bool regionVisible=fgRect.right>fgRect.left&&fgRect.bottom>fgRect.top;
if(auto* xess=sink_.xess()){
if(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_FAILURE",nullptr,0)>0){
veyra::log::warn("backend-test","Injected XeSS tagging failure with recorded commands");xessFailed_=true;return false;
}
- const bool enabled=!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId&&!xessGenerationSuppressed_;
+ const bool enabled=regionVisible&&!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId&&!xessGenerationSuppressed_;
const bool reset=!xessWasEnabled_||identity.epoch!=lastXessIdentity_.epoch||identity.settingsRevision!=lastXessIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastXessIdentity_.sourceFrameId;
const float elapsed=lastXessFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastXessFrame_).count());
auto* motion=graph.presentMotion(slot);
@@ -143,7 +159,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
lastXessFrame_=now;lastXessIdentity_=identity;xessWasEnabled_=enabled;
}
if(auto* fsr=sink_.fsr()){
- const bool enabled=!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastFsrIdentity_.sourceFrameId;
+ const bool enabled=regionVisible&&!generated&&!comparison&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastFsrIdentity_.sourceFrameId;
const bool reset=!fsrWasEnabled_||identity.epoch!=lastFsrIdentity_.epoch||identity.settingsRevision!=lastFsrIdentity_.settingsRevision||graph.motionPreviousSource(slot)!=lastFsrIdentity_.sourceFrameId;
const float elapsed=lastFsrFrame_==std::chrono::steady_clock::time_point{}?0.0f:float(std::chrono::duration<double,std::milli>(now-lastFsrFrame_).count());
// The AMD presenter degrades inside the provider (generation off, plain
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 109b312b..9112d5a4 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -8,6 +8,7 @@
// ring (NR evaluates on a fresh list - snippet constraint).
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/engine/ColorLut.h"
+#include "veyra/diagnostics/CpuStallTrace.h"
#include <algorithm>
#include <bit>
@@ -1256,6 +1257,7 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
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)
{
+ diagnostics::CpuStallTrace cpuTrace("graph-cpu-stall",sourceFrameId,30.0);
failedBackend_=engine::FailedBackend::Infrastructure;
out = FrameOutputs{};
out.ptsMs = ptsMs;
@@ -1317,6 +1319,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
return true;
}
uint32_t slot = 0;
+ cpuTrace.mark("validate");
if (uploadFences_[parity] && !context_.waitForFenceValue(uploadFences_[parity])) return false;
// Presentation returns the shared output to COMMON before this parity
// can be written again. Direct graph callers also need the GPU dependency.
@@ -1336,6 +1339,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
ID3D12Resource* nv12Texture = nullptr;
ID3D12GraphicsCommandList* list = ring_.acquireNext(slot, st);
if (list == nullptr) { veyra::log::error("graph", "ring acquire"); return false; }
+ cpuTrace.mark("acquire");
gpuTimer_.frame({epoch_,desc_.settingsRevision,realFrameIndex_+1},context_.fence());gpuTimer_.mark(list,GpuStage::Color);
// Both CPU source layouts feed the same bounded scene/cadence history.
@@ -1512,6 +1516,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.transition(list, chromaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
}
if (desc_.stageMark) desc_.stageMark("upload");
+ cpuTrace.mark("upload");
// 2. YUV -> RGBA16F.
if(colorActive_&&colorDirty_)uploadColorTables(list);
@@ -1539,6 +1544,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
gpuTimer_.mark(list,GpuStage::Color,true);
if (desc_.stageMark) desc_.stageMark("yuv");
+ cpuTrace.mark("color");
// Guidance from original source-space color before SR/NR. Queue waits are GPU-side.
bool haveFlow = false;
@@ -1581,7 +1587,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(!amdOf_){
gpuTimer_.mark(list,GpuStage::Flow);
if(!ring_.submitAndSignal(slot))return false;
+ cpuTrace.mark("flowPrepare");
haveFlow=nvof_->execute(ring_.lastSignaledValue(),st);
+ cpuTrace.mark("nvofExecute");
if(!haveFlow) { ++metrics_.nvofFrameFailures; mvecSource_="zero-motion-fallback (NVOF execute failed)"; }
else {
++metrics_.nvofExecuteCount;
@@ -1615,6 +1623,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
// 3. SR into workRgba (or 1:1 blit bypass).
+ cpuTrace.mark("flowFinish");
if(haveFlow){
auto adapt=[&](ID3D12Resource* output,uint32_t w,uint32_t h,uint32_t descriptor){
tracker_.transition(list,output,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
@@ -1692,6 +1701,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
}
if (desc_.stageMark) desc_.stageMark("sr");
+ cpuTrace.mark("sr");
return true;};
if(!desc_.nrBeforeSr&&!runSr())return false;
if(desc_.nrBeforeSr&&retainReferences){
@@ -1724,11 +1734,13 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.uavBarrier(list, proxyTex_.Get());
tracker_.transition(list, proxyTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
if (desc_.stageMark) desc_.stageMark("encode");
+ cpuTrace.mark("nrPrepare");
// 4b. NR evaluate on a FRESH list (snippet constraint).
if (!ring_.submitAndSignal(slot)) { veyra::log::error("graph", "submit before nr"); return false; }
ID3D12GraphicsCommandList* nlist = ring_.acquireNext(slot, st);
if (nlist == nullptr) { veyra::log::error("graph", "acquire nr list"); return false; }
+ cpuTrace.mark("nrAcquire");
{
namespace p = ngx::dlssnr;
ngx::ParameterBlock pb(ngxParams_);
@@ -1764,12 +1776,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
gpuTimer_.mark(nlist,GpuStage::Nr);
uint64_t er = 0; uint32_t es = 0;
+ cpuTrace.mark("nrParameters");
if (!nrAdapter_->snippetEvaluateFeature(nlist, nrHandle_, ngxParams_, er, es) ||
er != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {
diagnostic.stage="NR Evaluate";diagnostic.ngx=er;diagnostic.seh=es;Logger::diagnosticContext(diagnostic);veyra::log::error("graph", std::format("NR evaluate failed 0x{:X} seh={}", er, es));
failedBackend_=engine::FailedBackend::Nr;
return false;
}
+ cpuTrace.mark("nrEvaluate");
gpuTimer_.mark(nlist,GpuStage::Nr,true);
++metrics_.nrEvaluateCount;
if(haveFlow)++metrics_.nrMotionFrames;
@@ -1795,6 +1809,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
list = nlist; // continue recording on the NR list
}
if (desc_.stageMark) desc_.stageMark("nr");
+ cpuTrace.mark("nr");
if(nrEnabled_&&nrHandle_){
gpuTimer_.mark(list,GpuStage::Residual);
@@ -1887,7 +1902,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
fe.mvecScaleY=(haveFlow||desc_.fgMotionProbe)?-1.0f/static_cast<float>(workH_):1.0f;
if(sub==1)gpuTimer_.mark(flist,GpuStage::FgBatch);
const auto timingStage=static_cast<GpuStage>(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage);
+ cpuTrace.mark("fgPrepare");
if(!fgBackend_->evaluate(flist,ngxParams_,fe,st)){failedBackend_=engine::FailedBackend::Fg;return false;}
+ cpuTrace.mark("fgEvaluate");
++out.fgEvaluated;
gpuTimer_.mark(flist,timingStage,true);if(sub==desc_.fgMultiplier-1)gpuTimer_.mark(flist,GpuStage::FgBatch,true);
tracker_.uavBarrier(flist,genFrame_[generatedSlot].Get());
diff --git a/tests/integration/PreviewGeometryTests.cpp b/tests/integration/PreviewGeometryTests.cpp
index afd400ba..6e9808b9 100644
--- a/tests/integration/PreviewGeometryTests.cpp
+++ b/tests/integration/PreviewGeometryTests.cpp
@@ -38,6 +38,14 @@ int wmain(int argc,wchar_t** argv){
if(ok)ok=test("pan",{2,.25f,.5f},0,{{280,60,255,0,0},{280,200,255,0,255}});
if(ok)ok=test("reference",{2,.5f,.5f},1,{{40,10,255,0,0},{280,10,0,255,0}});
if(ok)ok=test("reset",{},0,{{160,10,0,0,0},{280,80,0,255,0}});
+ if(ok){
+ SetPropW(window,L"Veyra.ResizeDeferUntil",reinterpret_cast<HANDLE>(uintptr_t(GetTickCount64()+60000)));
+ SetWindowPos(window,nullptr,0,0,400,400,SWP_NOMOVE|SWP_NOZORDER);
+ ok=test("retained-square-client",{},0,{{160,40,0,0,0},{40,80,255,0,0},{280,80,0,255,0},{40,160,255,0,255},{160,200,0,0,0}});
+ if(ok)ok=test("retained-zoom",{2,.5f,.5f},0,{{40,10,255,0,0},{280,10,0,255,0},{40,230,255,0,255}});
+ SetWindowPos(window,nullptr,0,0,320,240,SWP_NOMOVE|SWP_NOZORDER);
+ RemovePropW(window,L"Veyra.ResizeDeferUntil");
+ }
if(ok){
for(int y=0;y<32;++y)for(int x=0;x<64;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;p[0]=0;p[1]=0;p[2]=255;p[3]=255;}
pipeline::EnhanceGraph::FrameOutputs current;ok=graph.process(f,33.333,false,current,2,nullptr,nullptr,false);
diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cpp
index ddddfdaa..1e78ebf7 100644
--- a/tests/unit/LiveGpuSchedulerTests.cpp
+++ b/tests/unit/LiveGpuSchedulerTests.cpp
@@ -2,12 +2,33 @@
#include "veyra/engine/TimingWindow.h"
#include "veyra/engine/FgRecoveryBudget.h"
#include "veyra/engine/LivePairLatency.h"
+#include "veyra/engine/PreviewFrameReadiness.h"
+#include "veyra/engine/PresentationGeometry.h"
#include <iostream>
#include <memory>
#include <atomic>
int main(){
using Scheduler=veyra::engine::LiveGpuScheduler;using State=Scheduler::State;
int failures=0;auto check=[&](bool pass,const char* text){std::cout<<(pass?"PASS ":"FAIL ")<<text<<'\n';failures+=!pass;};
+ {
+ using namespace veyra;
+ using R=engine::PreviewFrameReadiness;
+ pipeline::BatchFrame generated;generated.kind=pipeline::FrameKind::Generated;generated.validity=pipeline::GenerationValidity::Pending;
+ unsigned polls=0;auto pending=[&]{++polls;return false;};
+ check(engine::previewFrameReadiness(generated,false,true,pending)==R::Expired&&polls==0,"expired pending generation never waits on GPU readiness");
+ check(engine::previewFrameReadiness(generated,true,false,pending)==R::Suppressed&&polls==0,"old history generation never waits on GPU readiness");
+ check(engine::previewFrameReadiness(generated,false,false,pending)==R::Pending&&polls==1,"current unexpired generation keeps its producer fence");
+ check(engine::previewFrameReadiness(generated,false,false,[&]{generated.validity=pipeline::GenerationValidity::Disabled;return true;})==R::Invalid,"provider-disabled output is never presented");
+ pipeline::BatchFrame real;
+ check(engine::previewFrameReadiness(real,true,true,pending)==R::Pending&&polls==2,"original never bypasses its producer fence or expires with generated output");
+ check(engine::previewFrameReadiness(real,true,true,[]{return true;})==R::Ready,"ready original survives expiration and history suppression");
+ const auto fit=engine::presentationRegion(1920,1080,1000,1000,2560,1440,{});
+ check(fit.left==0&&fit.right==2560&&fit.top==314&&fit.bottom==1124,"retained wide buffer uses square client letterbox mapping");
+ const auto zoom=engine::presentationRegion(1920,1080,1000,1000,2560,1440,{2,.5f,.5f});
+ check(zoom.left==0&&zoom.right==2560&&zoom.top==0&&zoom.bottom==1440,"zoom region clips to retained buffer");
+ const auto outside=engine::presentationRegion(1920,1080,1000,1000,2560,1440,{1,3,.5f});
+ check(outside.left==outside.right,"offscreen image cannot invent an out-of-bounds provider rectangle");
+ }
Scheduler scheduler;unsigned finished=0,secondRan=0,firstSteps=0;bool gpuReady=false;
const auto owner=std::this_thread::get_id();bool sameOwner=true;
auto lease=std::make_shared<int>(1);std::weak_ptr<int> weak=lease;