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 frame generation admission costs and live presentation phase

Veyra Goal Agent80f7dc48d930
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 2becd108..54eb1676 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -2,6 +2,8 @@
更新:2026-09-19。发布状态与开发状态分别记录,历史计划不代表当前验收。
+最新本地修复:`codex/fg-scheduling-repair-20260919` 从存档 `5a1931b` 修复 DLSS 暖机预算污染、CPU Present 重复计费、窗口采集期限抖动,以及 XeSS 实时呈现前的额外相位等待。构建和本机持续生成/拥堵恢复测试结果见 [补帧调度验收](FG_SCHEDULING_ACCEPTANCE_2026-09-19.md)。GC573 53fps 只新增定位诊断,尚无实卡根因与修复证明;5080 功耗、30/40 系和物理显示验收未覆盖。本轮未打包、合并 main、推送或发布。
+
**1.4.2 已正式发布并设为最新版**:[GitHub Release](https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.4.2),标签提交274d826。正式包、对应源码和SHA256共四资产已核对远端digest;软件短测、HDR组合与便携包七组检查通过。具体边界与发布后证据见WORKLOG。以下为历史开发记录。
当前任务:用户已授权正式发布 **1.4.2**,整合 RTX Video HDR、帧同步及后续采集/字幕/UI 修复,并修复全屏操作提示残留。新群二维码与用户 HDR 对比照片纳入 README/Release,赞助图保留。正式发布进度、验收与资产以 [1.4.2 发布记录](RELEASE_1.4.2_EXECUTION.md) 为准,下方“仅本地”“未合并”等均是先前阶段记录。
diff --git a/docs/FG_SCHEDULING_ACCEPTANCE_2026-09-19.md b/docs/FG_SCHEDULING_ACCEPTANCE_2026-09-19.md
new file mode 100644
index 00000000..4718eec9
--- /dev/null
+++ b/docs/FG_SCHEDULING_ACCEPTANCE_2026-09-19.md
@@ -0,0 +1,48 @@
+# DLSS / XeSS scheduling repair, 2026-09-19
+
+## Scope and evidence
+
+User requested both DLSS and XeSS investigation, including sustained 4X/6X admission failures, irregular work, and GC573 RGB input cadence. Checkpoint: `5a1931b`; branch: `codex/fg-scheduling-repair-20260919`. No publication or runtime replacement.
+
+Local hardware: RTX 5070, SDR 2560x1440 at 100 Hz. Window capture tests use an independently animated child process through the real Windows capture and engine paths, configured at 30 fps. They are not GC573, PS5, 4K NR, or physical scanout measurements.
+
+## Implemented fixes
+
+- `FgRecoveryBudget.h` / `EngineController.cpp`: warmup FG timestamps now follow the matching completion identity and stay out of steady-state admission cost. Previously warmup graph cost was excluded but its FG stage still entered the steady budget. Repeated resets could repeatedly poison recovery.
+- Admission now charges measured GPU blit cost instead of CPU Present duration. DXGI/driver blocking remains real backpressure in the existing bounded scheduler; it is no longer charged again as predicted GPU work. Genuine expensive steady GPU work still fails admission.
+- Live present-sink generation receives the current real frame without the graph-FG source-interval delay. XeSS retains ownership of its subframe pacing. Graph DLSS A/B lookahead, file/replay timing, resource leases, reset rules and queue bounds remain in place.
+- Window capture uses its configured frame interval for presentation phase, preserving actual A/B timestamps. Alternating compositor packet durations previously moved consecutive batches' deadlines across one another. Physical capture continues to honor sample duration.
+- Bounded admission diagnostics now distinguish GPU blit and CPU Present and retain rejection samples separately from periodic successful admissions.
+- Capture callback diagnostics now include arrival interval, driver PTS interval and sample duration next to lock/copy time. This is diagnosis support, not a claimed GC573 throughput fix.
+
+## Verification
+
+Artifacts: `E:/项目/Veyra/logs/xess-gc573-20260919/` and `E:/项目/Veyra/tests/xess-gc573-20260919/`. Build: `E:/项目/Veyra/build/slider-reset-20260919/`. Process TEMP/TMP: `E:/项目/Veyra/tmp/xess-gc573-20260919/`.
+
+Build command: `scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/slider-reset-20260919 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/xess-gc573-20260919 -Targets veyra,veyra_presentation_pacing_tests,veyra_experimental_backend_tests,veyra_live_timing_tests,veyra_presentation_worker_tests,veyra_capture_color_tests` (PowerShell array used for Targets). `build5.log`: exit 0.
+
+- `veyra_live_timing_tests`: exit 0; alternating compositor duration deadline ordering for 2X/4X/6X, sample-duration precedence, existing timing contracts.
+- `veyra_presentation_worker_tests`: exit 0; warmup contamination with and without graph timestamps, repeated recovery at 2X/4X/6X, real GPU overload still rejected, existing bounded scheduler tests.
+- `screen-dlss6-final`: 120.003 seconds, media speed 0.999152, 3033 processed frames. Three 80 ms injected owner-work episodes followed by valid-generation recovery all passed; clean stop passed. Stable epoch: zero skipped-before-evaluation, 15190 ready-valid generated frames, 14456 generated submissions, 734 expired, queue high-water 2, zero allocator waits. These counters are not scanout FPS.
+- Before the compositor-phase fix, `screen-dlss6-quiet` had 441 expired / 1925 valid (22.9%); the final longer stable epoch had 734 / 15190 (4.8%). Different durations and ambient compositor load prevent treating this as a controlled performance claim. Expiration and source mailbox overwrites remain; this is not a zero-drop claim.
+- `dlss6` file lifecycle regression passed before the final compositor-only change: pause, seek, resume, three sync-mode changes, resize, disable, clean stop.
+
+- `screen-xess4-final`: 120.044 seconds, media speed 0.999484, 3050 processed frames, generation remains active; three injected-stall recovery cycles and clean stop passed. Steady capture-timing samples show schedulingWaitP95Ms=0; provider Present still takes time and is not counted as zero-cost generation.
+- `screen-dlss4-vsync`: despite its directory name, mode=-1 completely disabled synchronization; this is an off-mode test. 120.012 seconds, speed 0.999586, 3025 processed; three recovery cycles passed. Final Present flags verified sync=0.
+- `screen-dlss4-vsync-enabled`: mode=0/display=1, final Present sync=1/flags=0. 120.050 seconds, speed 0.999264, 3023 processed; three recovery cycles passed. Stable epoch: 9075 valid generated, 8203 submitted, 872 expired, zero skipped-before-evaluation, queue high-water 2. A 100 Hz screen cannot physically display all frames of 30x4 output.
+- `xess-pan4`, `xess-recovery2`, `xess-recovery4`, `xess-resize4`: exit 0 with D3D12 debug layer, zero debug errors. Checks actual provider submissions through pan, reset/recovery and resize; not visual-quality or scanout certification.
+- `veyra_capture_color_tests`: exit 0. First invocation omitted FFmpeg runtime PATH and failed to start (0xC0000135); rerun with the same dependency PATH as integration tests passed.
+- `dlss2-lifecycle-final`: final build, 6-second file playback followed by pause/seek/resume, three mode changes and resize/disable; exit 0, speed 0.987080, 142 processed frames in measurement.
+- `screen-xess4-vsync`: 15.047 seconds plus three stall/recovery cycles, exit 0, speed 0.994925, 374 processed. Verified backend=XeSS/sync=1/flags=0; provider remains pacing owner.
+
+Integration command pattern: `scripts/run-short-test.ps1 -Exe <build>/veyra_presentation_pacing_tests.exe -Arguments @('unused','<tests>/<case>','-1','0','6','120','screen-dlss') -TimeoutSeconds 220 -LogPrefix <logs>/<case>`. XeSS uses factor 4 / `screen-xess`; enabled VSync uses mode 0 / display 1. File lifecycle uses the existing `E:/项目/Veyra/tests/1.4.2beta/visible-scene.mp4`, 6 seconds and `lifecycle`. Backend regression command: `veyra_experimental_backend_tests.exe <case> <tests>/<case>`; each took only a few seconds. GPU tests ran sequentially.
+
+## Failures and limits
+
+The first screen test attempted to capture its own process and failed with 0x80070057, as designed. The harness was corrected to use an owned child process; the product's self-capture protection was retained. Both verbose and quiet DLSS tests showed expired generated frames before the compositor-phase fix, ruling out per-frame logging as the sole explanation.
+
+GC573 logs show real input around 53.49 fps with effects off. The packed RGB path already uses a bounded copy and GPU unpack; the earlier suspicion of mandatory CPU RGB expansion is not supported for that log. Without the card and matched OBS format/driver timing, no confirmed throughput fix can be claimed. The new diagnostics allow the next user run to distinguish driver cadence, lock contention and copy cost.
+
+No 5080 power trace, GC551/GC573 hardware, PS5 session, HDR/VRR display, RTX 30/40 regression or external display-latency measurement was obtained. GPU utilization alone does not establish scheduling failure; DLSS 4X/6X executes three/five evaluations and is not inherently free. Present CPU duration is not a measurement of GPU idle time. No external reviewer was used.
+
+The broad legacy delivery suite was not rerun; this turn built the application and ran the targeted scheduling, capture-layout and backend regressions listed above. No new export/color/NR algorithm behavior is claimed. Source review confirmed no additional presentation thread, unbounded queue, removal of discontinuity resets or mutation of runtime binaries. `git diff --check` passed.
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 586cde08..3ac7c246 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-09-19 DLSS / XeSS 调度修复施工
+
+开工存档 `5a1931b`,分支 `codex/fg-scheduling-repair-20260919`。用户明确要求同时处理 DLSS。完成暖机 FG 成本与稳态预算分离、以 GPU blit 替代 CPU Present 预算项、XeSS 实时路径取消额外源间隔相位、窗口采集固定配置帧率相位,以及 GC573 回调分项诊断。保留有界队列、真实时间戳、资源租约及必要历史 reset。
+
+实现文件:`FgRecoveryBudget.h`、`LivePresentationTiming.h`、`EngineController.cpp`、`CaptureCardSource.cpp`;回归:`LiveGpuSchedulerTests.cpp`、`LivePresentationTimingTests.cpp`、`PresentationPacingTests.cpp`。详细命令、构建结果、连续生成/恢复测试、失败与未验收项目见 `docs/FG_SCHEDULING_ACCEPTANCE_2026-09-19.md`。
+
+构建复用 `E:/项目/Veyra/build/slider-reset-20260919`,依赖缓存 `E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt`。日志 `E:/项目/Veyra/logs/xess-gc573-20260919`;测试 `E:/项目/Veyra/tests/xess-gc573-20260919`;进程 TEMP/TMP `E:/项目/Veyra/tmp/xess-gc573-20260919`。`build5.log` 构建退出 0;最终 timing/worker 单测退出 0;DLSS6 和 XeSS4 各 120 秒实时窗口采集及三轮 80ms 拥堵恢复退出 0。所有单项均少于 300 秒,GPU 测试串行。
+
+初始窗口测试被产品自身捕获保护正确拒绝,后改独立子进程输入;未取消保护。DLSS4 初次名为 vsync 的测试实际 mode=-1,最终标志 sync=0,因此只计为完全关闭回归,不能算 VSync 通过。未改运行库;无 SDK、模型、DLL 或用户日志入 Git;本轮未打包、推送、发布。无 GC573 实卡,不宣称 53fps 已根治;无 5080 功耗测量,不宣称功率波动消除。
+
+后续最终构建验证:DLSS4 完全关闭与低排队+VSync 各120秒及三轮拥堵恢复通过;VSync 已核对最终 sync=1/flags=0。XeSS4 VSync 15秒及三轮恢复通过,提供方仍独占节奏。DLSS2 文件生命周期通过。XeSS pan4/recovery2/recovery4/resize4 均退出0、debugErrors=0。采集颜色单测首次缺运行路径而未启动(0xC0000135),设置测试进程 PATH 后退出0。`git diff --check` 通过。没有重跑完整旧 delivery 套件,未将本轮针对性回归扩大为导出或全部设备验收。
+
## 2026-09-19 XeSS 游玩转身卡顿深度审计(方案,未施工)
用户要求排查与修复方案。保留当前 `codex/cross-monitor-20260919` 上已有跨屏、V 原图等未提交修改,新增 `docs/XESS_GAMEPLAY_STUTTER_REPAIR_PLAN_2026-09-19.md`。审计确认 XeLL 标记未覆盖 graph 工作、暂时 motion 无效触发 SetEnabled 造成额外历史预热、多倍 pacing 省略上游 fallback、统计遗漏批次边界,以及重复 install 嵌套 mutex 的条件死锁。快速转身误切、mailbox Drop 反馈、双重排期、motion 空间域为待实证假说,不称作已复现根因。采集不走文件 XessGenerationGate,明确排除该误判。
diff --git a/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md b/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md
index 227d09cf..15ec8de8 100644
--- a/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md
+++ b/docs/XESS_GC573_LOG_REPAIR_PLAN_2026-09-19.md
@@ -156,4 +156,4 @@ A的11:35:30.863至11:35:34.929,`fgSkippedBeforeEval`始终为9,是累计值
- 功率须另采带时间戳的硬件遥测,判断是否跟随工作断续;不能从利用率单独归因。屏幕端到端延迟须外部测量,软件日志只报告进程内指标。
- 构建、相关单元/集成测试、GPU debug layer 和真实来源回归后再写验收结论;无实卡或显示设备的场景列为待用户验证。不得用本机 RTX5070 替代 5070 Ti/5080/5090/GC573 全型号验收。
-未来本方案产物统一写入 `E:/项目/Veyra/{build,tests,logs,tmp}/xess-gc573-20260919/`。本轮仅读取原日志与代码,新增本文并更新 WORKLOG;未运行性能测试,也未声称修复完成。
+初次方案阶段仅读取原日志与代码。后续用户授权施工,存档 `5a1931b`,隔离分支 `codex/fg-scheduling-repair-20260919`;实现及实际验收见 [补帧调度验收](FG_SCHEDULING_ACCEPTANCE_2026-09-19.md)。日志、测试、临时产物在 `E:/项目/Veyra/{tests,logs,tmp}/xess-gc573-20260919/`,构建复用 `E:/项目/Veyra/build/slider-reset-20260919/`。GC573 日志所用 packed RGB 已走 GPU 解包,不能继续将 CPU 逐像素扩展写成已确认根因;实卡 53fps 和 5080 功耗仍待验证。
diff --git a/include/veyra/engine/FgRecoveryBudget.h b/include/veyra/engine/FgRecoveryBudget.h
index b390a94d..0dfb52f0 100644
--- a/include/veyra/engine/FgRecoveryBudget.h
+++ b/include/veyra/engine/FgRecoveryBudget.h
@@ -32,9 +32,10 @@ public:
void complete(std::optional<double> measuredMs,bool evaluated,bool warmup,int64_t now,std::optional<double> measuredFg={}){
// Missing GPU timestamps are unknown, not CPU polling delay. Let old
// samples expire; admission still checks each batch's real deadline.
+ if(warmup){if(measuredMs)add(warmup_,now,*measuredMs);return;}
+ if(evaluated&&measuredFg)fgCost(*measuredFg,now);
if(!measuredMs)return;
const double ms=*measuredMs;
- if(warmup){add(warmup_,now,ms);return;}
const auto extra=evaluated?(measuredFg?measuredFg:p95(fg_,now,20000000)):std::optional<double>(0);
// If a generated batch lacks a GPU timing, retain its whole measured
// completion as conservative base cost; never assume free FG.
diff --git a/include/veyra/engine/LivePresentationTiming.h b/include/veyra/engine/LivePresentationTiming.h
index 67b26786..ff378269 100644
--- a/include/veyra/engine/LivePresentationTiming.h
+++ b/include/veyra/engine/LivePresentationTiming.h
@@ -9,6 +9,12 @@ inline int64_t liveSourceInterval100ns(pipeline::Rational duration,double nomina
if(std::isfinite(nominalFps)&&nominalFps>=10&&nominalFps<=1000)return int64_t(std::llround(10000000.0/nominalFps));
return 200000; // documented last-resort 50 Hz estimate, never a measured duration
}
+// Compositor frames have jittery PTS intervals even at a fixed capture limit.
+// Use that limit for the pair's presentation phase, not for its actual A/B PTS.
+// Otherwise alternating 40/20 ms packets move the next pair before the last B.
+inline int64_t livePhaseInterval100ns(pipeline::Rational duration,double nominalFps,bool compositor){
+ return liveSourceInterval100ns(compositor?pipeline::Rational{}:duration,nominalFps);
+}
// Live capture never waits on an absolute source PTS. Once B is available,
// display generated(A,B), then B up to half an input interval later. Anchor
// each pair to current host time, not to the first (possibly stale) sample.
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index d55a8e3e..1b242d42 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -476,11 +476,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
LiveStats liveStats;std::deque<int64_t> liveSubmissions;
TimingWindow liveAges,liveWaits,liveReady;
TimingWindow livePresent{std::chrono::seconds(1)};
- TimingWindow livePresentService{std::chrono::seconds(1)};
+ TimingWindow livePresentGpu{std::chrono::seconds(1)};
FgRecoveryBudget fgBudget;uint64_t fgBudgetRevision=options.settings.revision;
LivePairLatency pairLatency;
const bool adaptiveCapturePhase=physicalCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_CAPTURE_PHASE",nullptr,0)==0;
- int64_t nextFgAdmissionLog=0;
+ int64_t nextFgAdmissionLog=0,nextFgRejectionLog=0;
+ uint64_t fgAdmittedPairs=0,fgRejectedPairs=0;
std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;
std::atomic<uint64_t> presentationGeneration{0};
std::unique_ptr<LiveGpuScheduler> liveScheduler;
@@ -542,7 +543,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(fgCost.state==diagnostics::SampleState::Measured)watch->fgExecutionMs=fgCost.milliseconds;
}
}
- if(sample.identity.settingsRevision==fgBudgetRevision&&fgCost.state==diagnostics::SampleState::Measured&&fgCost.milliseconds)fgBudget.fgCost(*fgCost.milliseconds,host100ns());
+ const auto& blit=sample.gpu[size_t(diagnostics::GpuStage::Blit)];
+ if(sample.identity.settingsRevision==fgBudgetRevision&&blit.state==diagnostics::SampleState::Measured&&blit.milliseconds)livePresentGpu.add(*blit.milliseconds);
if(frameFlow)frameFlow->gpuFrame(sample,host100ns());
for(size_t i=0;i<sample.gpu.size();++i){const auto& gpu=sample.gpu[i];
if(gpu.state==diagnostics::SampleState::Measured&&gpu.milliseconds){
@@ -1041,17 +1043,27 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;
if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
pipeline::EnhanceGraph::FgAdmission admitFg;
+ const auto logAdmission=[&](const pipeline::FrameBatch& batch,int64_t now,int64_t deadline,double elapsed,double blit,bool admitted,const char* timeline){
+ if(admitted)++fgAdmittedPairs;else ++fgRejectedPairs;
+ // Keep the first rejection even if the periodic sample just
+ // logged a success. Both channels remain rate bounded.
+ if(now<nextFgAdmissionLog&&(admitted||now<nextFgRejectionLog))return;
+ nextFgAdmissionLog=now+10000000;if(!admitted)nextFgRejectionLog=now+10000000;
+ veyra::log::info("live-fg-admission",std::format("timeline={} revision={} source={} multiplier={} admitted={} admittedPairs={} rejectedPairs={} remainingDeadlineMs={:.3f} predictedMs={:.3f} elapsedMs={:.3f} blitGpuP95Ms={:.3f} presentCpuP95Ms={:.3f} (CPU Present is backpressure, not added GPU cost)",timeline,batch.identity.settingsRevision,batch.identity.sourceFrameId,options.fgMultiplier,admitted,fgAdmittedPairs,fgRejectedPairs,double(deadline-now)/10000,fgBudget.predicted(now).value_or(-1),elapsed,blit,livePresent.p95()));
+ };
if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();pairLatency.reset();fgBudgetRevision=options.settings.revision;}
- const auto liveInterval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
+ const auto liveInterval=livePhaseInterval100ns(pkt.duration,activeSource->info().averageFps/(isScreen&&halfRate?2:1),isScreen);
const auto processingAllowance=isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)?
fgBudget.processingAllowance(host100ns(),liveInterval):0;
- const auto legacyPairDelay=liveInterval+processingAllowance;
+ // Present-sink providers own subframe pacing after receiving B.
+ // Graph FG needs the A/B presentation phase; provider FG does not.
+ const auto legacyPairDelay=presentSinkFrameGeneration(options.settings.frameGenerationBackend)?0:liveInterval+processingAllowance;
const auto pairDelay=adaptiveCapturePhase&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)?
pairLatency.select(host100ns(),legacyPairDelay,liveInterval,options.fgMultiplier):legacyPairDelay;
// DLSS can reseed after a skipped pair. XeSS
// owns generation inside its presenter and has no graph admission.
if(isCapture&&!rereadCached&&useLiveFgAdmission&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)){
- const auto presentP95=livePresentService.p95();
+ const auto presentP95=livePresentGpu.p95();
admitFg=[&,presentP95](const pipeline::FrameBatch& batch){
// Physical capture and PS5 delivery clocks are not
// guaranteed to match the host clock. Anchor each new
@@ -1066,7 +1078,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto now=host100ns(),deadline=liveTimeline.deadline(lastGenerated);
const double elapsed=elapsedMs(processStart);
const bool admitted=fgBudget.admit(now,deadline,elapsed,presentP95);
- if(now>=nextFgAdmissionLog){nextFgAdmissionLog=now+10000000;veyra::log::info("live-fg-admission",std::format("timeline={} admitted={} remainingDeadlineMs={:.3f} predictedMs={:.3f} elapsedMs={:.3f} decodedAgeMs={:.3f} callbackAgeMs={:.3f} presentP95Ms={:.3f} processingAllowanceMs={:.3f}",pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):"continuous",admitted,double(deadline-now)/10000,fgBudget.predicted(now).value_or(-1),elapsed,double(now-liveInputReady)/10000,double(now-captureArrival)/10000,presentP95,double(processingAllowance)/10000));}
+ logAdmission(batch,now,deadline,elapsed,presentP95,admitted,pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):"continuous");
return admitted;
};
}
@@ -1081,7 +1093,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto a=(historyReset||batch.b100ns<=batch.a100ns||batch.b100ns-batch.a100ns>10000000)?batch.b100ns-interval:batch.a100ns;
const auto lastGenerated=pipeline::FrameBatch::interpolate(a,batch.b100ns,options.fgMultiplier-1,options.fgMultiplier);
const auto now=host100ns();
- return fgBudget.admit(now,now+lastGenerated-int64_t(nowMs()*10000.0),elapsedMs(processStart),livePresentService.p95());
+ const auto deadline=now+lastGenerated-int64_t(nowMs()*10000.0);
+ const auto elapsed=elapsedMs(processStart),blit=livePresentGpu.p95();
+ const auto admitted=fgBudget.admit(now,deadline,elapsed,blit);
+ logAdmission(batch,now,deadline,elapsed,blit,admitted,"file-audio");
+ return admitted;
};
}
uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0,processSlotWaitMs=0;
@@ -1159,7 +1175,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// soft preview-skip history breaks do NOT reopen them.
if(settingsChanged){xessGenerationGate.reset();presenter.setXessGenerationSuppressed(false);fedXessPresented=fedXessGenerated=fedFsrPresented=fedFsrGenerated=0;}
playbackSpeedLastWall={};
- if(liveScheduler){liveStats={};liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();livePresentService.clear();liveReady.clear();}
+ if(liveScheduler){liveStats={};liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();livePresentGpu.clear();liveReady.clear();}
if(settingsChanged||!completionRates)completionRates=std::make_shared<FrameCompletionRates>(host100ns());
frameFlow=std::shared_ptr<FrameFlowWindow>(new FrameFlowWindow(runSessionId,out.batch.identity,host100ns(),completionRates),[](FrameFlowWindow* window){logFrameFlow(window->snapshot(monotonic100ns()),"closed");delete window;});
if(resetRecord)frameFlow->resetLifecycle(*resetRecord);else if(lastResetRecord)frameFlow->resetLifecycle(*lastResetRecord);
@@ -1275,7 +1291,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
const auto waited=elapsedMs(*s.deadlineStart);s.deadlineStart.reset();s.waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());
const auto begin=Clock::now();const auto before=presenter.submittedCount();
- const auto presentSlotWaitBefore=presenter.cpuWaitMilliseconds(ring);
presenter.reflexFrame(watch->reflexFrame);
if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return {State::Failed};
item.lease->consumerFence=presenter.consumerFenceValue(ring.lastSignaledValue());const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());
@@ -1284,9 +1299,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// session/revision windows must not update its admission cost.
if(flow==frameFlow){
livePresent.add(elapsed);
- // Allocator reuse waits on graph work already charged
- // by GPU timestamps; it is not additional blit service.
- livePresentService.add(std::max(0.0,elapsed-(presenter.cpuWaitMilliseconds(ring)-presentSlotWaitBefore)));
+ // DXGI/driver blocking is backpressure, not GPU blit
+ // work. The bounded scheduler retains that pressure.
}
if(didPresent){
cadence.submitted(optionalNow);
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index d289e3c8..2cb55142 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -361,7 +361,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
const bool sampleTime=sample&&sample->GetTime(&sampleStart,&sampleEnd)==S_OK;
const bool valid=sample&&std::isfinite(time)&&SUCCEEDED(sample->GetPointer(&data))&&data&&
(compressedPath?sample->GetActualDataLength()>0:sample->GetActualDataLength()>=LONG(layout.sampleBytes));
- bool enqueued=false;uint64_t timingSequence=0;int64_t copied100ns=0;double lockWaitMs=0;
+ bool enqueued=false;uint64_t timingSequence=0;int64_t copied100ns=0;double lockWaitMs=0,arrivalDeltaMs=0,ptsDeltaMs=0;
{
std::lock_guard lock(mutex);
lockWaitMs=std::chrono::duration<double,std::milli>(Clock::now()-arrival).count();
@@ -371,6 +371,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
if(!valid||(!compressedPath&&!pendingFrame)){callbackError=true;}
else {
const double previous=compressedPath?lastCallbackTime:pendingTime;
+ if(received){arrivalDeltaMs=std::chrono::duration<double,std::milli>(arrival-latestArrival).count();ptsDeltaMs=(time-previous)*1000;}
const bool driverBreak=sample->IsDiscontinuity()==S_OK;
const bool clockBreak=received&&(time<=previous||time-previous>(info.averageFps>0?2.5/info.averageFps:.1));
if(driverBreak||clockBreak){
@@ -411,7 +412,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
}
}
if(enqueued)decodeWake.notify_one();
- if(timingSequence&&(timingSequence%120==0||lockWaitMs>5))log::info("capture-callback",std::format("source={} entryToLockMs={:.3f} entryToCopiedMs={:.3f} bytes={} compressed={} (callback cost, not display latency)",timingSequence,lockWaitMs,(copied100ns-std::chrono::duration_cast<std::chrono::nanoseconds>(arrival.time_since_epoch()).count()/100)/10000.0,sample->GetActualDataLength(),compressedPath));
+ if(timingSequence&&(timingSequence%120==0||lockWaitMs>5))log::info("capture-callback",std::format("source={} entryToLockMs={:.3f} entryToCopiedMs={:.3f} bytes={} compressed={} arrivalDeltaMs={:.3f} ptsDeltaMs={:.3f} sampleDurationMs={:.3f} (callback cost, not display latency)",timingSequence,lockWaitMs,(copied100ns-std::chrono::duration_cast<std::chrono::nanoseconds>(arrival.time_since_epoch()).count()/100)/10000.0,sample->GetActualDataLength(),compressedPath,arrivalDeltaMs,ptsDeltaMs,sampleTime?double(sampleEnd-sampleStart)/10000:-1));
if(log::verboseFrameLogs()&&timingSequence)log::info("capture-ingress-sample",std::format("source={} arrival={} copied={} compressed={}",timingSequence,std::chrono::duration_cast<std::chrono::nanoseconds>(arrival.time_since_epoch()).count()/100,copied100ns,compressedPath));
wake.notify_one();return S_OK;
}
diff --git a/tests/integration/PresentationPacingTests.cpp b/tests/integration/PresentationPacingTests.cpp
index 2588b231..dde510be 100644
--- a/tests/integration/PresentationPacingTests.cpp
+++ b/tests/integration/PresentationPacingTests.cpp
@@ -1,21 +1,41 @@
#include "veyra/engine/EngineController.h"
#include "veyra/Log.h"
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/ScreenCaptureSource.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <chrono>
#include <thread>
+static HWND movingInput(){
+ WNDCLASSW wc{};wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraPacingInput";
+ wc.lpfnWndProc=[](HWND w,UINT m,WPARAM a,LPARAM b)->LRESULT{
+ if(m==WM_TIMER){InvalidateRect(w,nullptr,FALSE);return 0;}
+ if(m==WM_PAINT){PAINTSTRUCT ps;auto dc=BeginPaint(w,&ps);RECT r;GetClientRect(w,&r);FillRect(dc,&r,(HBRUSH)GetStockObject(BLACK_BRUSH));const LONG x=LONG(GetTickCount64()/4%600);RECT bar{x,0,x+40,r.bottom};FillRect(dc,&bar,(HBRUSH)GetStockObject(WHITE_BRUSH));EndPaint(w,&ps);return 0;}
+ return DefWindowProcW(w,m,a,b);
+ };
+ RegisterClassW(&wc);
+ auto w=CreateWindowW(wc.lpszClassName,L"Moving capture input",WS_OVERLAPPEDWINDOW|WS_VISIBLE,1400,50,660,420,nullptr,nullptr,wc.hInstance,nullptr);
+ if(w)SetTimer(w,1,16,nullptr);
+ return w;
+}
int wmain(int argc,wchar_t** argv){
using namespace veyra::engine;using Clock=std::chrono::steady_clock;
+ if(argc==2&&std::wstring(argv[1])==L"--capture-input"){
+ auto w=movingInput();const auto end=Clock::now()+std::chrono::seconds(240);
+ while(IsWindow(w)&&Clock::now()<end){MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}std::this_thread::sleep_for(std::chrono::milliseconds(2));}
+ if(IsWindow(w))DestroyWindow(w);return w?0:2;
+ }
// media, evidence directory, mode(-1=off), display(0..2), multiplier, seconds, lifecycle/replay/xess
if(argc<7)return 2;
const int mode=_wtoi(argv[3]),display=_wtoi(argv[4]),multiplier=_wtoi(argv[5]),seconds=std::clamp(_wtoi(argv[6]),3,120);
if(mode< -1||mode>2||display<0||display>2)return 2;
const std::wstring scenario=argc>7?argv[7]:L"";
+ const bool screen=scenario==L"screen-xess"||scenario==L"screen-dlss";
+ const bool xess=scenario==L"xess"||scenario==L"screen-xess";
if(scenario==L"legacy"){if(mode!=-1)return 2;SetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",L"1");}
std::filesystem::path dir=argv[2];std::filesystem::create_directories(dir);
- SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
+ SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",screen?L"0":L"1");
veyra::Logger::instance().openFile((dir/L"engine.log").wstring());veyra::Logger::instance().setConsoleEnabled(false);
if(FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;
const bool physical=scenario==L"capture-nr"||scenario==L"capture-nr-recovery";
@@ -36,6 +56,22 @@ int wmain(int argc,wchar_t** argv){
}
HWND window=CreateWindowExW(0,L"STATIC",L"Veyra pacing acceptance",WS_OVERLAPPEDWINDOW|WS_VISIBLE,40,40,1280,760,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
if(!window)return 2;
+ HWND inputWindow=nullptr;
+ PROCESS_INFORMATION inputProcess{};
+ if(screen){
+ std::wstring command=L"\""+std::filesystem::absolute(argv[0]).wstring()+L"\" --capture-input";
+ STARTUPINFOW startup{};startup.cb=sizeof(startup);
+ if(!CreateProcessW(nullptr,command.data(),nullptr,nullptr,FALSE,CREATE_NO_WINDOW,nullptr,nullptr,&startup,&inputProcess))return 2;
+ CloseHandle(inputProcess.hThread);
+ for(unsigned attempt=0;attempt<500&&!inputWindow;++attempt){
+ for(const auto& target:veyra::source::ScreenCaptureSource::targets(veyra::source::ScreenTargetKind::Window))
+ if(target.processId==inputProcess.dwProcessId)inputWindow=reinterpret_cast<HWND>(target.handle);
+ if(!inputWindow)std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ if(!inputWindow){TerminateProcess(inputProcess.hProcess,2);WaitForSingleObject(inputProcess.hProcess,1000);CloseHandle(inputProcess.hProcess);return 2;}
+ veyra::source::ScreenCaptureOptions input;input.target=reinterpret_cast<uint64_t>(inputWindow);input.fps=30;input.cursor=false;
+ sourcePath=input.uri();
+ }
MONITORINFOEXW monitor{};monitor.cbSize=sizeof(monitor);GetMonitorInfoW(MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST),&monitor);
DEVMODEW dm{};dm.dmSize=sizeof(dm);EnumDisplaySettingsW(monitor.szDevice,ENUM_CURRENT_SETTINGS,&dm);
std::cout<<"display="<<dm.dmPelsWidth<<"x"<<dm.dmPelsHeight<<" refreshHz="<<dm.dmDisplayFrequency<<std::endl;
@@ -43,7 +79,7 @@ int wmain(int argc,wchar_t** argv){
{
EngineController engine;engine.setVolume(0,true);
PresentationSettings p{mode>=0,PacingMode(std::max(0,mode)),DisplaySync(display)};engine.requestPresentation(p);
- EnhancementSettings effects;effects.multiplier=unsigned(multiplier);if(scenario==L"xess")effects.frameGenerationBackend=FrameGenerationBackend::XeSS;
+ EnhancementSettings effects;effects.multiplier=unsigned(multiplier);if(xess)effects.frameGenerationBackend=FrameGenerationBackend::XeSS;
if(scenario==L"effects"){effects.nr=true;effects.sr=true;effects.srTarget=veyra::pipeline::SrTarget::Qhd;}
if(physical){effects.nr=true;effects.sr=false;}
auto options=PlayerOptions::from(effects);options.captureReplayForTest=scenario==L"replay";
@@ -68,12 +104,22 @@ int wmain(int argc,wchar_t** argv){
if(physical){check(last.nrActive&&last.fgActive&&last.nrEvaluated>first.nrEvaluated,"real capture NR and DLSS remain active");std::cout<<"captureReceivedDelta="<<last.captureReceived-first.captureReceived<<" captureDroppedDelta="<<last.captureDropped-first.captureDropped<<" generatedDelta="<<last.generated-first.generated<<" requested="<<mode<<" effective="<<(last.presentationEffective.enabled?int(last.presentationEffective.mode):-1)<<std::endl;}
std::cout<<"mediaSpeed="<<speed<<" processedDelta="<<last.frames-first.frames<<std::endl;
check(!last.failed&&last.frames>first.frames+10&&speed>.8&&speed<1.2,"sustained playback at media speed");
- if(multiplier>1)check(last.fgActive&&last.generated>0,"real provider generated frames");
+ if(multiplier>1)check(last.fgActive&&last.generated>first.generated,"real provider generated frames during measurement");
if(scenario==L"effects")check(last.nrActive&&last.srActive&&last.nrEvaluated>first.nrEvaluated,"NR and SR remain active with pacing");
- if(mode>=0&&scenario!=L"xess")check(last.presentationEffective.enabled,"optional pacing active");
+ if(mode>=0&&!xess)check(last.presentationEffective.enabled,"optional pacing active");
if(mode==2&&multiplier==1)check(last.presentationEffective.mode==PacingMode::Reflex,"native Reflex active");
- if(mode==2&&multiplier>1&&scenario!=L"xess")check(last.presentationEffective.mode==PacingMode::LowQueue,"Reflex with FG explicitly falls back to low queue");
- if(mode>=0&&scenario==L"xess")check(!last.presentationEffective.enabled&&last.fgActive,"provider remains pacing owner");
+ if(mode==2&&multiplier>1&&!xess)check(last.presentationEffective.mode==PacingMode::LowQueue,"Reflex with FG explicitly falls back to low queue");
+ if(mode>=0&&xess)check(!last.presentationEffective.enabled&&last.fgActive,"provider remains pacing owner");
+ if(screen){
+ for(unsigned cycle=0;cycle<3;++cycle){
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"80");
+ auto before=engine.snapshot();
+ check(wait([&](auto& s){return s.frames>before.frames+15;}),"live input progresses during 80ms stall");
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
+ before=engine.snapshot();const auto recovered=Clock::now();
+ check(wait([&](auto& s){return Clock::now()-recovered>std::chrono::seconds(3)&&s.generated>before.generated+30&&!s.fgBudgetLimited;}),"valid generation recovers after repeated stalls");
+ }
+ }
if(scenario==L"lifecycle"){
engine.pause(true);check(wait([](auto& s){return s.transport==TransportState::Paused;}),"pause");
p.enabled=false;engine.requestPresentation(p);check(wait([](auto& s){return !s.presentationEffective.enabled;}),"disable while paused");
@@ -115,5 +161,6 @@ int wmain(int argc,wchar_t** argv){
}
engine.stop();check(wait([&](auto&){return engine.idle();}),"clean stop");
}
+ if(inputWindow){PostMessageW(inputWindow,WM_CLOSE,0,0);if(WaitForSingleObject(inputProcess.hProcess,3000)!=WAIT_OBJECT_0){TerminateProcess(inputProcess.hProcess,2);WaitForSingleObject(inputProcess.hProcess,1000);}CloseHandle(inputProcess.hProcess);}
DestroyWindow(window);CoUninitialize();return failures?1:0;
}
diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cpp
index 1e78ebf7..e0954d05 100644
--- a/tests/unit/LiveGpuSchedulerTests.cpp
+++ b/tests/unit/LiveGpuSchedulerTests.cpp
@@ -65,8 +65,8 @@ int main(){
const Window::Clock::time_point start{};
Window present{std::chrono::seconds(1)};
present.add(80,start);
- check(present.p95(start)==80,"temporary Present stall is visible to admission");
- check(!budget.admit(10000000,10200000,0,present.p95(start)),"stall limits FG admission");
+ check(present.p95(start)==80,"temporary GPU blit stall is visible to admission");
+ check(!budget.admit(10000000,10200000,0,present.p95(start)),"GPU blit stall limits FG admission");
check(present.p95(start+std::chrono::seconds(1))==0,"Present stall expires without successful FG or new samples");
present.add(2,start+std::chrono::seconds(1));
check(budget.admit(20000000,20200000,0,present.p95(start+std::chrono::seconds(1))),"admission recovers after expired Present stall");
@@ -79,8 +79,10 @@ int main(){
check(!budget.admit(10000000,10100000,0,0),"insufficient pair deadline enters limited state");
check(budget.admit(10100000,10600000,0,0)&&budget.recovering(),"fresh deadline admits warmup without a fixed cooldown");
check(budget.admit(10266667,10766667,0,0)&&!budget.recovering(),"second consecutive source pair exits recovery");
- budget.complete(200,true,true,13000000);
+ budget.complete(200,true,true,13000000,180);
check(*budget.predicted(13000000)<32,"expensive reset warmup does not poison steady cost");
+ budget.complete(std::nullopt,true,true,13000001,190);
+ check(*budget.predicted(13000001)<32,"warmup FG timestamp without graph timestamp cannot poison steady cost");
budget.complete(10,false,false,24000000);
check(budget.processingAllowance(24000000,166667)==100000,"live deadline includes measured enhancement before interpolation cadence");
check(*budget.predicted(24000000)<14,"old slow completion expires even when no FG succeeds");
@@ -93,6 +95,18 @@ int main(){
budget.complete(std::nullopt,true,false,36000000);
check(!budget.predicted(36000000),"missing GPU timing cannot retain a stale CPU polling cost");
check(!budget.admit(36000000,35800000,0,0),"unknown cost still rejects expired presentation deadlines");
+ for(unsigned multiplier:{2u,4u,6u}){
+ budget.reset();const double fg=double(multiplier-1)*1.5;
+ budget.complete(5+fg,true,false,40000000,fg);
+ check(budget.predicted(40000000)==5+fg,"completion samples steady FG with its matching graph identity");
+ for(int64_t t=40100000;t<42100000;t+=166667){
+ budget.complete(200,true,true,t,190);
+ check(budget.admit(t,t+166667,0,1),"repeated reset cost cannot trap healthy 2X/4X/6X pairs in rejection");
+ budget.complete(5+fg,true,false,t+1,fg);
+ }
+ budget.complete(100,true,false,42200000,90);
+ check(!budget.admit(42200000,42366667,0,1),"real steady GPU overload remains limited");
+ }
veyra::engine::LivePairLatency phase;
check(phase.select(10000000,420000,333333,4)==420000,"unknown live readiness keeps legacy phase");
for(int i=0;i<8;++i)phase.observe(10000000+i,370000);
diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cpp
index 867e809d..6b50f691 100644
--- a/tests/unit/LivePresentationTimingTests.cpp
+++ b/tests/unit/LivePresentationTimingTests.cpp
@@ -3,6 +3,7 @@
#include "veyra/source/CaptureTiming.h"
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/engine/FrameRateWindow.h"
+#include "veyra/engine/PresentationScheduler.h"
#include <cmath>
#include <limits>
#include <cstdio>
@@ -53,6 +54,19 @@ int main(){
check(liveSourceInterval100ns({0,1},60)==166667,"known zero cannot turn60fps into120fps");
check(liveSourceInterval100ns(captureDuration(0,0,false,333333),60)==333333,"30fps packet retained by scheduler");
check(liveSourceInterval100ns({INT64_MAX,1},60)==1000000,"huge duration clamps before integer conversion");
+ for(unsigned factor:{2u,4u,6u}){
+ veyra::engine::PresentationScheduler scheduler;
+ int64_t pts=0,previousDeadline=0;bool ordered=true;
+ for(unsigned i=0;i<100;++i){
+ const int64_t dt=i%2?200000:400000;pts+=dt;
+ const auto phase=veyra::engine::livePhaseInterval100ns({dt,10000000},30,true);
+ scheduler.resetPair(1,pts,pts,phase);
+ if(i)ordered&=scheduler.deadline(pts-dt+dt/factor)>previousDeadline;
+ previousDeadline=scheduler.deadline(pts);
+ }
+ check(ordered,"jittery compositor input cannot schedule a new pair before the preceding real frame");
+ }
+ check(veyra::engine::livePhaseInterval100ns({1,30},60,false)==333333,"device sample duration still overrides nominal capture rate");
check(livePairHoldMs(false,1822.09,22.64)==0,"no-FG never waits on stale source PTS");
check(livePairHoldMs(false,1e12,0)==0,"no-FG absolute PTS cannot add latency");
check(livePairHoldMs(true,100,90)==10,"50fps FG pair half interval");