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

av-scheduling P0-P3: audio master clock, preview PTS skip policy, file FG admission, XeSS gate

Veyra Goal Agent9885759bbfa2
diff --git a/AGENTS.md b/AGENTS.md
index 9b16f50f..079e0c38 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> 2026-09-11 用户授权执行实时调度修复(方案见 `docs/REALTIME_AV_SCHEDULING_REPAIR_PLAN_2026-09-11.md`,开工前存档点 `checkpoint/av-scheduling-2026-09-11`,隔离分支施工):实时文件/采集**预览**在持续欠速时允许按真实 PTS 跳过已解码源帧的增强/呈现机会(先省补帧工作,再省原帧增强),稳态音频不停机、媒体时间保持一倍速、跳帧均匀覆盖时间线;源 PTS/序号/duration 保持真实,历史按断点 reset。该例外只限实时预览:视频导出、图片处理、暂停单帧查看仍必须完整处理,不得把丢帧扩大到导出,也不得把预览跳帧伪装成未丢帧。不得以停音频/丢 PCM/偷偷放慢声音制造同步。
+
> 2026-09-11 用户授权发布 0.0.4:当前音画同步与音频连续性修复推送到 `Likely7/Veyra-NRVideo`,更新中英文 README 并发布完整便携包。运行组件沿用 0.0.3 的七文件白名单及双 NR 原件身份,不新增或替换运行时;社区版继续记录 `HashMismatch`。源码 Git 禁止 SDK/DLL/模型,软件允许用户替换 DLL 的决定不变。
> 2026-09-11 用户授权发布当前0.0.3:源码推送到`Likely7/Veyra-NRVideo`,完整便携Release包含当前双NR运行版本和直播实验选项。此前用户指定的RTX40/50社区DLL可原样进入本次Release的`runtime/experimental/nr-community/`,身份沿用下条SHA256、310.8.0.0、165840496字节、`HashMismatch`,必须逐文件列入manifest并明确社区修改版;这是本次发布范围的扩展,不允许自动加入其他版本或修改文件。源码Git仍绝不包含SDK/DLL/模型。软件不恢复运行时哈希锁。OBS捕获说明按用户要求仅补README,不继续改软件提示。
@@ -96,7 +98,7 @@ renodx-dlss5-1.addon64
- 任何 NGX/NVOF 返回值、HRESULT、SEH、资源尺寸/格式和 GPU timestamp 都必须进入日志。
- 所有历史型模块在 open/seek/resize/pause-resume/scene-cut/device-lost 时显式 reset。
- 正常播放、采集和最终视频导出路径禁止 GPU→CPU 像素回读、每 pass CPU fence wait、无界帧队列和多份隐式颜色转换。视频导出必须用 Video Codec SDK 的 D3D12 NVENC input/fence;raw pipe 只准作诊断 fallback,不能通过首发 gate。
-- 采集 ingress 使用 latest-frame mailbox(容量 1)并丢弃过期帧;图内部另有严格上限的 A/B/C history window。低延迟 FG 需要 A/B 的一帧 lookahead window;这不是可伪造为固定 `1/f` 的实测显示延迟。高质量实时模式最多再保留 C 做验证。播放器/导出不得丢源帧。
+- 采集 ingress 使用 latest-frame mailbox(容量 1)并丢弃过期帧;图内部另有严格上限的 A/B/C history window。低延迟 FG 需要 A/B 的一帧 lookahead window;这不是可伪造为固定 `1/f` 的实测显示延迟。高质量实时模式最多再保留 C 做验证。实时文件/采集**预览**在持续欠速时可按真实 PTS 跳过已解码源帧的增强/呈现机会(2026-09-11 修订,仅限预览;跳帧须均匀覆盖时间线且计入诊断);视频导出与图片/暂停单帧仍不得丢源帧。
- 所有来源先显式解析 range/matrix/transfer,进入统一 linear working texture;所有 sink 只做一次明确的输出转换。
- Guidance motion 固定为 current→previous、单位为 post-SR `workingExtent` 像素;depth 为 R32F 相对深度;confidence 为 R8_UNORM。低置信度区域必须衰减/清零 motion,不能把坏向量硬塞给 NGX。
- seek、scene cut、PTS discontinuity、capture drop、resize、source switch、pause/resume 和 device lost 必须原子 reset SR/NR/FG/depth/flow 的全部历史。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9f7c78e0..4c4fa90f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -458,6 +458,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
add_executable(veyra_presentation_worker_tests tests/unit/LiveGpuSchedulerTests.cpp)
target_compile_features(veyra_presentation_worker_tests PRIVATE cxx_std_20)
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)
+ target_compile_definitions(veyra_realtime_preview_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_include_directories(veyra_realtime_preview_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(veyra_live_presentation_tests tests/integration/LivePresentationTests.cpp)
add_executable(veyra_audio_timeline_tests tests/integration/AudioTimelineTests.cpp)
target_compile_features(veyra_audio_timeline_tests PRIVATE cxx_std_20)
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index 4bf91283..4e0ec107 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -34,6 +34,11 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"呈现提交",fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps));
rows.emplace_back(L"源帧处理",fps(f.sourceCompletedFps));
rows.emplace_back(xess?L"补帧完成":L"有效补帧",xess?L"SDK内部不可测":fps(f.validGeneratedFps));
+ rows.emplace_back(L"正常播放速度",playing?std::format(L"{:.2f} x",s.playbackSpeed):L"未测");
+ if(!s.capture&&!s.image){
+ rows.emplace_back(L"预览状态",!playing?L"未运行":s.previewSkipped?std::format(L"已跳帧 {}",s.previewSkipped):s.fgBudgetLimited?L"补帧预算不足":L"正常");
+ if(s.xessGenerationSuppressed)rows.emplace_back(L"XeSS补帧",L"欠速暂停生成 · 实验");
+ }
rows.emplace_back(L"输入",s.capture?std::format(L"{:.1f} fps",s.captureFps):L"文件 / 图片");
rows.emplace_back(L"总延迟 P95",playing?ms(f.softwareLatencyP95Ms):L"未测");
rows.emplace_back(L"采集覆盖 / 补帧过期",std::format(L"{} / {}",f.counters.mailboxOverwritten,f.counters.generatedExpiredAfterEval));
@@ -66,7 +71,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"NR内部尺寸",s.applied.nr?std::format(L"{} x {}",s.metrics.resolution.nr.width,s.metrics.resolution.nr.height):L"关闭");
rows.emplace_back(L"NR运行版本",s.nrActive?(s.applied.nrRuntime==engine::NrRuntime::Community?L"社区兼容 · 实验":L"NVIDIA原版"):L"未运行");
rows.emplace_back(L"显示模式",s.running?(s.applied.captureCompatible?L"直播兼容 · 实验":L"标准显示"):L"未运行");
- rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioEndpointRecovering?L"音频设备恢复中 · 时间线保持":s.audioRebuffering?L"视频过载 · 同步缓冲":L"音频主时钟")):L"无音频");
+ rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioEndpointRecovering?L"音频设备恢复中 · 时间线保持":s.audioRebuffering?L"重新同步 · 等待视频锚点":L"音频主时钟")):L"无音频");
if(!s.capture&&s.audioAvailable){
rows.emplace_back(L"音频设备恢复次数",std::to_wstring(s.audioEndpointRecoveries));
if(FAILED(s.audioEndpointError))rows.emplace_back(L"最近音频设备错误",std::format(L"0x{:08X}",unsigned(s.audioEndpointError)));
diff --git a/docs/REALTIME_AV_SCHEDULING_REPAIR_PLAN_2026-09-11.md b/docs/REALTIME_AV_SCHEDULING_REPAIR_PLAN_2026-09-11.md
index 5a6dfa58..ac90a74c 100644
--- a/docs/REALTIME_AV_SCHEDULING_REPAIR_PLAN_2026-09-11.md
+++ b/docs/REALTIME_AV_SCHEDULING_REPAIR_PLAN_2026-09-11.md
@@ -1,6 +1,6 @@
# 连续音频与实时视频调度修复方案
-日期:2026-09-11。状态:方案,尚未实施。基线:0.0.4,产品提交 `cecf34e`,当前源码含发布记录与用户 README 修改。保留上一轮4060诊断及 WORKLOG 未提交内容。
+日期:2026-09-11。状态:**施工中(隔离分支 `agent/av-scheduling-repair`)**。基线:0.0.4,产品提交 `cecf34e`;开工存档点 tag `checkpoint/av-scheduling-2026-09-11`(提交 `21ce5d3`,与 0.0.4 产品无 C++ 源码差异),实施与证据见 `docs/WORKLOG.md` 对应条目。本轮施工:P0 契约同步与 A/B 回归、P1 时钟解耦、P2 视频实时闭环、P3 XeSS 准入迟滞(文件路径;采集生产算法按 §3.2 仅验证不改动)、P4 状态与回归。
目标:播放或采集增强处理达不到请求帧率时,保持声音连续、媒体时间正常推进、视频延迟有界;短暂耗时波动不反复停声音。用明确的预览帧取舍处理算力不足,不以音频暂停掩盖欠速,不声称提高 NR 本身的算力。
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
index a9738cd6..2a1b278a 100644
--- a/include/veyra/diagnostics/FrameMetrics.h
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -27,6 +27,9 @@ struct FrameFlowIdentity {
struct FrameFlowCounters {
uint64_t captureReceived=0,mailboxOverwritten=0;
uint64_t sourceAccepted=0,sourceSkippedBeforeGraph=0,realSubmitted=0;
+ // Realtime file preview only: decoded source frames whose enhancement
+ // opportunity was dropped (PTS window fully passed) before the graph.
+ uint64_t previewSkippedBeforeGraph=0;
uint64_t fgCandidate=0,fgEvaluated=0,fgSkippedBeforeEval=0,fgReadyValid=0,fgInvalid=0,fgWarmup=0;
uint64_t xessSdkGenerated=0,xessSdkPresented=0,realReady=0;
uint64_t realPresented=0,generatedPresented=0,generatedExpiredAfterEval=0,cancelledBeforePresent=0;
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index fc0b0b61..dd2ed3e9 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -42,6 +42,12 @@ struct PlayerSnapshot {
bool captureHalfRate=false;
double captureFps=0,captureReadAgeMs=0,captureAgeMs=0,captureAgeP95Ms=0;
double schedulingWaitP95Ms=0,processCpuP95Ms=0,presentCpuP95Ms=0;
+ // Realtime file preview: dropped enhancement opportunities this metrics
+ // window, and measured media-advance / wall-clock playback speed (1.0 =
+ // normal speed). Zero previewSkipped means every decoded frame was enhanced.
+ uint64_t previewSkipped=0;
+ double playbackSpeed=0;
+ bool fgBudgetLimited=false,xessGenerationSuppressed=false;
bool running=false,failed=false,image=false,capture=false;
};
class EngineController {
diff --git a/include/veyra/engine/RealtimePreviewScheduling.h b/include/veyra/engine/RealtimePreviewScheduling.h
new file mode 100644
index 00000000..e3549126
--- /dev/null
+++ b/include/veyra/engine/RealtimePreviewScheduling.h
@@ -0,0 +1,82 @@
+#pragma once
+#include <cmath>
+#include <cstdint>
+
+namespace veyra::engine {
+// Realtime preview scheduling policies (REALTIME_AV_SCHEDULING_REPAIR P2/P3).
+// The audio-master clock never pauses for slow enhancement; decoded source
+// frames instead lose their enhancement/display opportunity when their real
+// PTS window has passed. Export, images and paused single frames never use
+// these policies and keep full source integrity.
+inline constexpr double kPreviewExpiryEpsilonMs = 0.01;
+
+// A decoded candidate may be dropped before upload/color/SR/NR once its whole
+// display window [pts, pts+interval) is behind the master media clock and a
+// newer decoded candidate is available. PTS stays truthful; only the preview
+// opportunity is dropped.
+inline bool previewCandidateExpired(double clockMs, double ptsMs, double intervalMs) {
+ if (!std::isfinite(clockMs) || !std::isfinite(ptsMs) || !std::isfinite(intervalMs) || intervalMs <= 0)
+ return false; // unknown cadence never drops frames
+ return clockMs > ptsMs + intervalMs + kPreviewExpiryEpsilonMs;
+}
+
+// A completed generated frame is presented only while it can still be the
+// freshest displayable image: once the master clock passed its own PTS by the
+// same 10 ms grace the capture path uses, presenting it replays stale media
+// between already-shown endpoints. Completed REAL frames are always presented:
+// with one in-flight batch they are by construction the newest ready result
+// (plan rule 3: never drop the only ready picture).
+inline bool previewGeneratedExpired(double clockMs, double ptsMs) {
+ if (!std::isfinite(clockMs) || !std::isfinite(ptsMs))
+ return false;
+ return clockMs > ptsMs + 10.0 + kPreviewExpiryEpsilonMs;
+}
+
+// XeSS-FG generation happens inside the SDK swapchain, so pair admission
+// cannot gate an Evaluate. Suppress generation over stable intervals instead:
+// sustained lateness disables it, sustained health re-enables it, and single
+// fluctuations never toggle it. Re-enabling goes through the presenter's
+// history reset (xefg resetHistory), not a per-frame switch.
+class XessGenerationGate {
+public:
+ explicit XessGenerationGate(unsigned suppressAfter = 12, unsigned resumeAfter = 60)
+ : suppressAfter_(suppressAfter), resumeAfter_(resumeAfter) {}
+
+ // Observe the media-clock lateness (clock - pts) of one presented real
+ // frame. Returns true when the suppression state changed.
+ bool observe(double latenessMs, double intervalMs) {
+ if (!std::isfinite(latenessMs) || !std::isfinite(intervalMs) || intervalMs <= 0)
+ return false;
+ if (suppressed_) {
+ if (latenessMs < intervalMs * 0.5) {
+ if (++healthy_ >= resumeAfter_) {
+ suppressed_ = false;
+ streak_ = healthy_ = 0;
+ return true;
+ }
+ } else {
+ healthy_ = 0;
+ }
+ return false;
+ }
+ if (latenessMs > intervalMs * 1.5) {
+ if (++streak_ >= suppressAfter_) {
+ suppressed_ = true;
+ streak_ = healthy_ = 0;
+ return true;
+ }
+ } else {
+ streak_ = 0;
+ }
+ return false;
+ }
+
+ bool suppressed() const { return suppressed_; }
+ void reset() { suppressed_ = false; streak_ = healthy_ = 0; }
+
+private:
+ unsigned suppressAfter_, resumeAfter_;
+ unsigned streak_ = 0, healthy_ = 0;
+ bool suppressed_ = false;
+};
+}
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 67e400f3..29732424 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -19,6 +19,11 @@ public:
uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}
uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}
bool xessActive() const {return sink_.xess()!=nullptr;}
+ // Sustained under-rate may suppress SDK-owned XeSS-FG generation over a
+ // stable interval (xefgSwapChainSetEnabled); re-enabling goes through the
+ // per-frame history reset, never a per-frame toggle.
+ void setXessGenerationSuppressed(bool v){xessGenerationSuppressed_=v;}
+ bool xessGenerationSuppressed() const {return xessGenerationSuppressed_;}
diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}
std::vector<diagnostics::GpuFrameTiming> takeGpuTimings(ID3D12Fence* fence){gpuTimer_.collect(fence);return gpuTimer_.takeCompleted();}
void recordGpuTimings(){gpuTimer_.recordCompleted();}
@@ -34,6 +39,7 @@ private:
std::chrono::steady_clock::time_point lastXessFrame_{};
pipeline::FrameIdentity lastXessIdentity_{};
bool xessWasEnabled_=false;
+ bool xessGenerationSuppressed_=false;
void refresh(ID3D12Device*);
};
}
diff --git a/include/veyra/sink/AudioVideoContinuity.h b/include/veyra/sink/AudioVideoContinuity.h
deleted file mode 100644
index f81a42dc..00000000
--- a/include/veyra/sink/AudioVideoContinuity.h
+++ /dev/null
@@ -1,31 +0,0 @@
-#pragma once
-#include <chrono>
-#include <cmath>
-#include <optional>
-
-namespace veyra::sink {
-// Audio-owner policy. A presentation deadline is not a hard PCM stop boundary:
-// short GPU jitter must leave a continuous endpoint running. Explicit transport
-// resets still hold immediately; persistent lag and a hard lead bound rebuffer.
-class AudioVideoContinuity {
-public:
- using Clock=std::chrono::steady_clock;
- bool blocked(bool explicitHold,double audioPts,double coverage,Clock::time_point now) {
- if(explicitHold){lateSince_.reset();buffering_=false;return true;}
- if(!std::isfinite(audioPts)||!std::isfinite(coverage)){reset();return false;}
- const double lead=audioPts-coverage;
- if(buffering_){
- if(lead<=0)reset();
- return buffering_;
- }
- if(lead<=20){lateSince_.reset();return false;}
- if(!lateSince_)lateSince_=now;
- buffering_=lead>=80||now-*lateSince_>=std::chrono::milliseconds(100);
- return buffering_;
- }
- void reset(){lateSince_.reset();buffering_=false;}
-private:
- bool buffering_=false;
- std::optional<Clock::time_point> lateSince_;
-};
-}
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index f692b903..ca9c0b01 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -69,9 +69,11 @@ public:
void stopThread();
void setPaused(bool value) { paused_.store(value); }
- // File playback: prefill while held, then let the device clock advance
- // with a bounded jitter allowance beyond video coverage. Enforced on the audio owner even
- // while the GPU owner is blocked in feature creation/evaluation.
+ // File playback: audio is the master clock. Prefill while explicitly held
+ // (open/seek/settings rebuild/pause); once released the device clock runs
+ // at one-times speed regardless of video lag — slow enhancement drops
+ // preview frames instead of pausing sound. Coverage is published for
+ // diagnostics only.
void holdForVideo();
void videoReady(double ptsMs);
void videoPresented(double nextPtsMs);
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index e2f40e9f..61c2a074 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -9,6 +9,7 @@
#include "veyra/engine/TimingWindow.h"
#include "veyra/engine/FrameFlowWindow.h"
#include "veyra/engine/LiveFgAdmission.h"
+#include "veyra/engine/RealtimePreviewScheduling.h"
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/source/CaptureCardSource.h"
@@ -174,6 +175,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
};
PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;
DeadlineWait deadlineWait;
+ // Realtime file preview scheduling (P2/P3): expired decoded
+ // candidates lose their enhancement opportunity against the audio
+ // master clock; FG admission predicts pair completion; XeSS-FG
+ // generation is suppressed over stable intervals when sustained
+ // late. Export/images/paused frames never enter these paths.
+ uint64_t previewSkippedTotal=0,previewSkippedSinceSubmit=0;
+ bool previewSkipSinceProcess=false;
+ TimingWindow fileCompletion;uint64_t fileCompletionRevision=0;
+ XessGenerationGate xessGenerationGate;
+ double playbackSpeedLastPts=0;Clock::time_point playbackSpeedLastWall{};
CaptureHalfRate captureSampler;
FrameLineageTracker lineageTracker;
auto completedProcessing=[&](pipeline::FrameIdentity id){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==id.settingsRevision)++snapshot_.processedCompleted;};
@@ -267,7 +278,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
auto drainLivePresentation=[&]{if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}};
auto advanceLive=[&]{if(liveScheduler){pollCompletions();if(stop_||paused_)liveScheduler->cancel();else liveScheduler->advance(host100ns());}};
auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0);};
- uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,statsSourceBase=0;
+ uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,metricsWindowEpoch=0,statsSourceBase=0;
uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();
std::shared_ptr<FrameCompletionRates> completionRates;
source::CaptureMetrics captureFlowBase{},captureFlowLast{};
@@ -276,6 +287,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
OnExit stopPresentation{[&]{liveScheduler.reset();finishReset(stop_?diagnostics::ResetOutcome::Cancelled:diagnostics::ResetOutcome::Failed);std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId){if(frameFlow)snapshot_.metrics.flow=frameFlow->snapshot(host100ns());activeFlow_.reset();}}};
const bool injectSourceGap=options.captureReplayForTest&&GetEnvironmentVariableW(L"VEYRA_TEST_REPLAY_SOURCE_GAP",nullptr,0)>0;
std::optional<Clock::time_point> sourceGapUntil;
+ // Master media clock for file playback: the audio device clock when
+ // mapped, a monotonic anchor without audio, and its frozen value
+ // while an endpoint recovers. Steady-state video scheduling reads
+ // this clock; it never waits on audio coverage.
+ auto nowMs=[&](){
+ if(!audioStarted)return anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();
+ publishAudioStatus();const double a=audio.mediaTimeMs();
+ if(std::isfinite(a)){lastAudioClockMs=a;audioClockExhausted=false;return a;}
+ // A disconnected endpoint freezes the shared media clock. Only a
+ // fully exhausted audio stream may hand its tail to the wall clock.
+ if(audioPipe.clockExhausted()){
+ if(!audioClockExhausted){audioClockExhausted=true;audioTailAnchor=Clock::now();}
+ return lastAudioClockMs+std::chrono::duration<double,std::milli>(Clock::now()-audioTailAnchor).count();
+ }
+ return lastAudioClockMs;
+ };
while(!stop_){
if(audioStarted)publishAudioStatus();
if(audioStarted&&injectFileEndpointLoss&&!fileEndpointLossInjected&&frames>=20){audioPipe.requestEndpointLossForTest();fileEndpointLossInjected=true;}
@@ -411,14 +438,43 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(isImage)pkt.sequence=1;
if(!rereadCached)++sourceFrames;
const double decodeMs=elapsedMs(decodeStart);decodeTimes.add(decodeMs);
- const double pts=isImage?0:pkt.pts.toDouble()*1000;
+ double pts=isImage?0:pkt.pts.toDouble()*1000;
if(isCapture&&frames==0){anchor=Clock::now();anchorMs=pts;}
if(pts+0.1<discardBefore)continue;
+ // Realtime preview candidates: decode stays ordered and
+ // reference-lossless; an expired candidate loses only its
+ // enhancement/display opportunity (plan §4.3). The open/seek
+ // anchor, paused seek preview and settings replay never drop.
+ if(!isCapture&&!isImage&&!transaction&&!fileAwaitingVideo&&!seekPreviewPending){
+ const double previewIntervalMs=double(liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps))/10000.0;
+ bool previewSourceFailed=false;
+ while(!stop_&&previewCandidateExpired(nowMs(),pts,previewIntervalMs)){
+ pipeline::FramePacket next;const AVFrame* raw=nullptr;
+ const auto rs=activeSource->read(next,&raw);
+ if(rs==source::SourceReadStatus::Eos)break; // final decoded candidate is kept
+ if(rs!=source::SourceReadStatus::Frame||next.pts.isUnknown()){previewSourceFailed=true;break;}
+ const double nextPts=next.pts.toDouble()*1000;
+ if(nextPts+0.1<discardBefore)continue; // post-seek decode residue keeps dropping
+ pkt=next;frame=raw;
+ pts=nextPts;
+ ++previewSkippedTotal;++previewSkippedSinceSubmit;previewSkipSinceProcess=true;
+ }
+ if(previewSourceFailed){status(L"视频解码或时间戳错误",true);break;}
+ }
if(frame!=cachedFrame){av_frame_free(&cachedFrame);cachedFrame=av_frame_clone(frame);cachedPacket=pkt;}
const auto processStart=Clock::now();
const auto captureArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:host100ns();
const auto sourceArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100;
- const bool historyReset=reset||pipeline::breaksHistory(pkt.flags);
+ // A skipped preview candidate breaks the temporal span the
+ // motion/NR/FG history was built on: the next processed frame
+ // is an explicit history reset (plan §4.4). It is a SOFT
+ // break: metrics windows, completion predictions and reset
+ // lifecycle records continue (only hard resets — open/seek/
+ // pause/discontinuity/settings — reopen them).
+ const bool hardFrameReset=reset||pipeline::breaksHistory(pkt.flags);
+ const bool previewOnlyReset=!hardFrameReset&&previewSkipSinceProcess;
+ if(hardFrameReset)++metricsWindowEpoch;
+ const bool historyReset=hardFrameReset||previewSkipSinceProcess;
if(historyReset){++historyResets;++presentationGeneration;}
// A mailbox Drop must reset SR/NR/flow/FG history, but draining
// the two-batch presenter here discarded completed real frames.
@@ -439,9 +495,25 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
return admitLiveFg(host100ns(),liveTimeline.deadline(lastGenerated),elapsedMs(processStart),predictionEpoch==batch.identity.epoch?completionP95:std::nullopt,presentP95);
};
}
+ // File playback: same pair admission, but deadlines are PTS
+ // deadlines on the audio master clock. A pair whose last
+ // generated timestamp can no longer be reached spends no FG
+ // Evaluate; the real frame keeps its normal cadence (plan §4.1).
+ if(!isCapture&&!isImage&&!rereadCached&&!transaction&&options.fg&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){
+ const bool predictionValid=fileCompletionRevision==options.settings.revision&&fileCompletion.size()>=8;
+ const std::optional<double> completionP95=predictionValid?std::optional<double>(fileCompletion.p95()):std::nullopt;
+ const double presentP95=predictionValid?presentTimes.p95():0.0;
+ admitFg=[&,historyReset,completionP95,presentP95](const pipeline::FrameBatch& batch){
+ const auto interval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
+ 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);
+ return admitLiveFg(int64_t(nowMs()*10000.0),lastGenerated,elapsedMs(processStart),completionP95,presentP95);
+ };
+ }
uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0,processSlotWaitMs=0;
if(resetRecord&&resetRecord->epoch==0)resetStageStart=Clock::now();
bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0,admitFg);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}
+ previewSkipSinceProcess=false;
if(!processed){
if(transaction){
ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
@@ -456,7 +528,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(veyra::log::verboseFrameLogs())veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));
reset=false;hasOutput=true;
const auto processDone=Clock::now();
- if(!resetRecord&&out.historyReset){
+ if(!resetRecord&&out.historyReset&&!previewOnlyReset){
resetStart=processStart;resetStageStart=processStart;
resetRecord=diagnostics::FrameFlowMetrics::ResetRecord{};resetRecord->sessionId=runSessionId;resetRecord->settingsRevision=out.batch.identity.settingsRevision;resetRecord->epoch=out.batch.identity.epoch;resetRecord->sourceFrameId=out.batch.identity.sourceFrameId;resetRecord->reason=static_cast<uint8_t>(diagnostics::resetCause(pkt.flags,pendingResetCause,out.detectedReset));
resetRecord->stageMs[size_t(diagnostics::ResetStage::Drain)]=0.0;resetRecord->stageMs[size_t(diagnostics::ResetStage::Destroy)]=0.0;resetRecord->stageMs[size_t(diagnostics::ResetStage::Create)]=0.0;
@@ -468,11 +540,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
markResetStage(diagnostics::ResetStage::Warmup);
}
pendingResetCause=pipeline::ResetReason::None;
- if(!frameFlow||metricsRevision!=options.settings.revision||metricsEpoch!=out.batch.identity.epoch){
+ if(!frameFlow||metricsRevision!=options.settings.revision||metricsEpoch!=metricsWindowEpoch){
const bool settingsChanged=metricsRevision!=options.settings.revision;
- metricsRevision=options.settings.revision;metricsEpoch=out.batch.identity.epoch;statsStart=Clock::now();statsSourceBase=sourceFrames-uint64_t(!rereadCached);
+ metricsRevision=options.settings.revision;metricsEpoch=metricsWindowEpoch;statsStart=Clock::now();statsSourceBase=sourceFrames-uint64_t(!rereadCached);
slotWaitBase=processWaitBase;slotWaitMsBase=processWaitMsBase;submitBase=processSubmitBase;
captureAges.clear();scheduleWaits.clear();processTimes.clear();presentTimes.clear();decodeTimes.clear();gpuReadyTimes.clear();for(auto& window:gpuStageTimes)window.clear();lastGpuSampleEnd={};latenessSamples.clear();submissionTimes.clear();submitted=expired=0;
+ // Admission predictions and the XeSS gate must not carry
+ // samples across a settings revision (new backend/dimensions);
+ // soft preview-skip history breaks do NOT reopen them.
+ if(settingsChanged){xessGenerationGate.reset();presenter.setXessGenerationSuppressed(false);}
+ playbackSpeedLastWall={};
if(liveScheduler){liveStats={};liveStats.identity=out.batch.identity;liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();liveCompletion.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;});
@@ -493,7 +570,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
frameFlow->cpu(diagnostics::CpuStage::Decode,decodeMs,host100ns());
frameFlow->cpu(diagnostics::CpuStage::Submit,processMs,host100ns());
frameFlow->cpu(diagnostics::CpuStage::SlotWait,processSlotWaitMs,host100ns());
- frameFlow->update([&](auto& m){m.latest.frame=out.batch.identity;m.latest.batchId=out.batch.batchId;m.latest.readyFence=std::max(out.videoFenceValue,out.genFenceValue);m.counters.sourceAccepted+=!rereadCached;++m.counters.realSubmitted;m.counters.fgCandidate+=out.fgCandidates;m.counters.fgEvaluated+=out.fgEvaluated;m.counters.fgSkippedBeforeEval+=out.fgSkippedBeforeEval;if(!out.hasGenerated)m.counters.fgWarmup+=out.fgEvaluated;});
+ frameFlow->update([&](auto& m){m.latest.frame=out.batch.identity;m.latest.batchId=out.batch.batchId;m.latest.readyFence=std::max(out.videoFenceValue,out.genFenceValue);m.counters.sourceAccepted+=!rereadCached;++m.counters.realSubmitted;m.counters.previewSkippedBeforeGraph+=previewSkippedSinceSubmit;m.counters.fgCandidate+=out.fgCandidates;m.counters.fgEvaluated+=out.fgEvaluated;m.counters.fgSkippedBeforeEval+=out.fgSkippedBeforeEval;if(!out.hasGenerated)m.counters.fgWarmup+=out.fgEvaluated;});
+ previewSkippedSinceSubmit=0;
if(transaction||frames==0){
std::lock_guard lock(mutex_);snapshot_.captureHalfRate=halfRate;
veyra::log::info("capture-rate",std::format("revision={} requested60To30={} active={} transportFps={} originalPtsPreserved=true",options.settings.revision,options.settings.content==ContentRate::Capture60To30,halfRate,isCapture?activeSource->info().averageFps:0));
@@ -507,18 +585,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,captureArrival,options.fg?duration100ns:0,paceSourcePts);
}
if(!isImage&&!isCapture&&frames==0){anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}
- auto nowMs=[&](){
- if(!audioStarted)return anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();
- publishAudioStatus();const double a=audio.mediaTimeMs();
- if(std::isfinite(a)){lastAudioClockMs=a;audioClockExhausted=false;return a;}
- // A disconnected endpoint freezes the shared media clock. Only a
- // fully exhausted audio stream may hand its tail to the wall clock.
- if(audioPipe.clockExhausted()){
- if(!audioClockExhausted){audioClockExhausted=true;audioTailAnchor=Clock::now();}
- return lastAudioClockMs+std::chrono::duration<double,std::milli>(Clock::now()-audioTailAnchor).count();
- }
- return lastAudioClockMs;
- };
double frameWaitMs=0,framePresentMs=0;
double gpuWaitMs=0;
if(liveScheduler){
@@ -596,6 +662,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(!rereadCached&&!isImage)completedProcessing(out.batch.identity);
gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);
frameFlow->cpu(diagnostics::CpuStage::ReadyWait,gpuWaitMs,host100ns());
+ // Completion-time prediction for the NEXT pair's admission:
+ // samples span submit -> GPU-ready. Cost depends on backend and
+ // dimensions, so the window is keyed to the settings revision
+ // only — not to seek/preview-skip temporal epochs.
+ if(!isImage&&fileCompletionRevision!=options.settings.revision){
+ fileCompletion.clear();fileCompletionRevision=options.settings.revision;
+ }
+ if(!isImage)fileCompletion.add(elapsedMs(processStart));
// WASAPI prefill is allowed before video; device-clock playback
// is not. Align only open/seek, never discard audio to catch up
// with a slow graph during ordinary playback or settings edits.
@@ -614,6 +688,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++handled;continue;}
if(generated&&comparisonMode_!=0)continue;
if(isCapture&&generated&&liveTimeline.expired(item.pts100ns,host100ns(),100000)){++expired;++handled;frameFlow->update([](auto& m){++m.counters.generatedExpiredAfterEval;});continue;}
+ // File preview: a generated result whose PTS the master
+ // clock already passed by the shared 10ms grace replays
+ // stale media; skip its present but still count it as
+ // computed-but-not-shown GPU work (plan §4.1).
+ if(!isCapture&&generated&&comparisonMode_==0&&previewGeneratedExpired(nowMs(),item.pts100ns/10000.0)){++expired;++handled;frameFlow->update([](auto& m){++m.counters.generatedExpiredAfterEval;});continue;}
const double itemPtsMs=item.pts100ns/10000.0;
if(audioStarted&&!fileAwaitingVideo)audioPipe.videoReady(itemPtsMs);
const auto waitStart=Clock::now();
@@ -634,13 +713,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
// XeSS owns generated frames inside its swapchain. The
// engine sees only real B frames, so its audio coverage
// must last a SOURCE interval, never a hidden subframe.
- const bool callerPresentsGenerated=options.fg&&!graph.xessEnabled()&&comparisonMode_==0;
+ // A pair whose FG was not evaluated/generated covers
+ // the whole source interval to the next real frame.
+ const bool callerPresentsGenerated=options.fg&&!graph.xessEnabled()&&comparisonMode_==0&&out.hasGenerated;
double nextPtsMs=itemPtsMs+intervalMs/(callerPresentsGenerated?options.fgMultiplier:1);
for(uint32_t next=i+1;next<out.batch.count;++next){const auto& candidate=out.batch.frames[next];
if(candidate.kind!=pipeline::FrameKind::Generated||(candidate.validity==pipeline::GenerationValidity::Valid&&comparisonMode_==0)){nextPtsMs=candidate.pts100ns/10000.0;break;}}
if(audioStarted){audioPipe.videoPresented(nextPtsMs);audioPipe.setPaused(paused_);}
if(fileAwaitingVideo)veyra::log::info("audio-sync",std::format("video anchor presented ptsMs={:.3f} audioPtsMs={:.3f} nextPtsMs={:.3f} paused={} (Present return, scanout unmeasured)",itemPtsMs,audio.mediaTimeMs(),nextPtsMs,paused_.load()));
fileAwaitingVideo=false;anchor=Clock::now();anchorMs=itemPtsMs;
+ // Sustained lateness suppresses SDK-owned XeSS-FG
+ // generation over a stable interval; the presenter's
+ // history reset covers the later re-enable.
+ if(graph.xessEnabled()&&presenter.xessActive()&&xessGenerationGate.observe(nowMs()-itemPtsMs,intervalMs)){
+ presenter.setXessGenerationSuppressed(xessGenerationGate.suppressed());
+ veyra::log::info("xess-fg-gate",std::format("event={} revision={} lateMs={:.3f} intervalMs={:.3f}",xessGenerationGate.suppressed()?"suppress":"resume",options.settings.revision,nowMs()-itemPtsMs,intervalMs));
+ }
}
if(presenter.submittedCount()>before&&!generated&&!rereadCached)frameFlow->latency(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100,host100ns());
if(presenter.submittedCount()>before&&generated&&lineage)frameFlow->generatedLatency(*lineage,host100ns());
@@ -675,6 +763,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];
+ // Measured playback speed: media-PTS advance per wall time
+ // over ~1s windows (1.0 = normal speed), resampled on seek.
+ const auto speedNow=Clock::now();
+ if(playbackSpeedLastWall==Clock::time_point()||pts+0.5<playbackSpeedLastPts){playbackSpeedLastPts=pts;playbackSpeedLastWall=speedNow;}
+ else if(std::chrono::duration<double>(speedNow-playbackSpeedLastWall).count()>=0.9){
+ const double wallS=std::chrono::duration<double>(speedNow-playbackSpeedLastWall).count();
+ const double mediaS=(pts-playbackSpeedLastPts)/1000.0;
+ if(mediaS>=0)snapshot_.playbackSpeed=mediaS/wallS;
+ playbackSpeedLastPts=pts;playbackSpeedLastWall=speedNow;
+ }
+ snapshot_.previewSkipped=measured.flow.counters.previewSkippedBeforeGraph;
+ snapshot_.fgBudgetLimited=measured.flow.counters.fgSkippedBeforeEval>0;
+ snapshot_.xessGenerationSuppressed=graph.xessEnabled()&&presenter.xessGenerationSuppressed();
snapshot_.nrActive=graph.nrEnabled()&&graphStats.nrEvaluateCount>0;
snapshot_.audioRebuffering=audioRebuffering;
snapshot_.audioVideoWaits=audioPipe.videoWaitCount();
@@ -689,7 +790,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
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));}
- if(!isCapture&&Clock::now()>=nextTimingLog){veyra::log::info("player-timing",std::format("revision={} decodeP95Ms={:.3f} graphSubmitP95Ms={:.3f} gpuReadyP95Ms={:.3f} presentP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} processed={}",options.settings.revision,decodeTimes.p95(),processTimes.p95(),gpuReadyTimes.p95(),presentTimes.p95(),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,sourceFrames-statsSourceBase));nextTimingLog=Clock::now()+std::chrono::seconds(1);}
+ if(!isCapture&&Clock::now()>=nextTimingLog){const double playbackSpeedNow=[&]{std::lock_guard lock(mutex_);return snapshot_.playbackSpeed;}();
+ veyra::log::info("player-timing",std::format("revision={} decodeP95Ms={:.3f} graphSubmitP95Ms={:.3f} gpuReadyP95Ms={:.3f} presentP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} previewSkipped={} playbackSpeed={:.3f} processed={}",options.settings.revision,decodeTimes.p95(),processTimes.p95(),gpuReadyTimes.p95(),presentTimes.p95(),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,measured.flow.counters.previewSkippedBeforeGraph,playbackSpeedNow,sourceFrames-statsSourceBase));nextTimingLog=Clock::now()+std::chrono::seconds(1);}
if(isCapture&&Clock::now()>=nextTimingLog){
logFrameFlow(measured.flow,"active");
const auto rates=snapshot();
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index e1932f1b..3bc3740d 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -61,7 +61,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
const float fit=std::min(float(sink_.bufferWidth())/graph.workWidth(),float(sink_.bufferHeight())/graph.workHeight());
const LONG w=std::max(1L,LONG(std::lround(graph.workWidth()*fit))),h=std::max(1L,LONG(std::lround(graph.workHeight()*fit)));
const LONG left=(LONG(sink_.bufferWidth())-w)/2,top=(LONG(sink_.bufferHeight())-h)/2;
- const bool enabled=!generated&&!comparison&&view==PreviewView{}&&graph.presentMotionValid(slot)&&identity.sourceFrameId!=lastXessIdentity_.sourceFrameId;
+ const bool enabled=!generated&&!comparison&&view==PreviewView{}&&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);
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index e0fa032f..3ee40114 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -1,5 +1,4 @@
#include "veyra/sink/AudioGain.h"
-#include "veyra/sink/AudioVideoContinuity.h"
#include "veyra/sink/WasapiAudioSink.h"
#include <algorithm>
@@ -163,7 +162,8 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
void AudioPipeline::holdForVideo()
{
- videoHold_=true;videoSync_=true;wake_.notify_all();
+ if(!videoHold_.exchange(true))log::info("audio-continuity",std::format("event=hold coverageMs={:.3f}",std::isfinite(videoLimitMs_.load())?videoLimitMs_.load():-1.0));
+ videoSync_=true;wake_.notify_all();
}
void AudioPipeline::videoReady(double ptsMs)
@@ -177,7 +177,10 @@ void AudioPipeline::videoReady(double ptsMs)
void AudioPipeline::videoPresented(double nextPtsMs)
{
if(!videoSync_||!std::isfinite(nextPtsMs))return;
- videoLimitMs_=nextPtsMs;videoHold_=false;wake_.notify_all();
+ const bool released=videoHold_.exchange(false);
+ videoLimitMs_=nextPtsMs;
+ if(released)log::info("audio-continuity",std::format("event=release coverageMs={:.3f}",nextPtsMs));
+ wake_.notify_all();
}
void AudioPipeline::pushConverted(int frames)
@@ -507,14 +510,14 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
bool endpointReady = renderer && (!ownEndpoint || renderer->start());
double lastClockMs = 0, recoveryTargetMs = 0;
auto retryAt = t0;
- AudioVideoContinuity continuity;
- auto videoBlocked=[&]{
- const double observed=endpointReady?renderer->mediaTimeMs():lastClockMs;
- const double current=std::isfinite(observed)?observed:lastClockMs;
- return videoSync_&&continuity.blocked(videoHold_,current,videoLimitMs_,std::chrono::steady_clock::now());
- };
+ // Steady-state under-rate must never stop sound: the audio device clock is
+ // the master timeline and slow video enhancement drops preview frames
+ // instead (engine-side, plan P1). Only explicit transport holds — open,
+ // seek, settings rebuild, pause — gate the endpoint here.
+ auto videoBlocked=[&]{return videoSync_&&videoHold_.load();};
auto shouldPause=[&]{return paused_.load()||videoBlocked();};
auto publishVideoWait=[&](bool paused){const bool waiting=paused&&videoBlocked();if(videoWaiting_.exchange(waiting)!=waiting&&waiting)++videoWaitCount_;};
+ auto nextContinuitySummary=t0+std::chrono::milliseconds(1000);
auto recovering = [&](HRESULT error) {
endpointError_ = FAILED(error) ? error : E_FAIL;
endpointRecovering_ = true;
@@ -581,6 +584,16 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
if (pauseNow != pauseApplied && endpointReady) renderer->setPaused(pauseNow);
pauseApplied = pauseNow;
publishVideoWait(pauseApplied);
+ // Bounded per-second audio state: master clock, video coverage and
+ // lead make steady under-rate observable without per-frame logging.
+ if (videoSync_ && !pauseNow && std::chrono::steady_clock::now() >= nextContinuitySummary) {
+ nextContinuitySummary = std::chrono::steady_clock::now() + std::chrono::milliseconds(1000);
+ const double coverage = videoLimitMs_.load();
+ log::info("audio-continuity", std::format("event=summary clockMs={:.3f} coverageMs={:.3f} leadMs={:.3f} hold={} recovering={}",
+ lastClockMs, std::isfinite(coverage) ? coverage : -1.0,
+ std::isfinite(coverage) ? lastClockMs - coverage : -1.0,
+ videoHold_.load(), endpointRecovering_.load()));
+ }
// Seek request? Atomic re-sequence.
{
std::unique_lock<std::mutex> lock(mutex_);
diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cpp
index 037c62a1..2e443dd9 100644
--- a/tests/integration/AudioTimelineTests.cpp
+++ b/tests/integration/AudioTimelineTests.cpp
@@ -80,10 +80,41 @@ int jitter(const std::filesystem::path& dir) {
}
return failures?1:0;
}
+int underrate(const std::filesystem::path& dir) {
+ // Deterministic sustained under-rate: a 60fps source whose enhancement
+ // completes at only ~51fps — the RTX4060 revision11 log signature.
+ // Presented coverage advances slower than media time while real PCM plays.
+ // The audio master clock must keep one-times continuous playback with no
+ // rebuffer; video must drop preview work instead of pausing sound.
+ const auto file=dir/"video-underrate.wav";fixture(file,48000,8000);
+ AudioPipeline pipe;AudioRenderer renderer;renderer.setGain(0);
+ check(pipe.open(file.wstring()),"open sustained under-rate fixture");
+ pipe.holdForVideo();pipe.startThread(&renderer,true);
+ check(until([&]{return renderer.started()&&!pipe.endpointRecovering()&&pipe.waitingForVideo();}),"prefill held before under-rate replay");
+ const auto waits=pipe.videoWaitCount();
+ const auto begin=std::chrono::steady_clock::now();
+ const double frameCostMs=1000.0/51.0,intervalMs=1000.0/60.0;
+ pipe.videoPresented(intervalMs);
+ for(int n=1;n<=204;++n){
+ std::this_thread::sleep_until(begin+std::chrono::microseconds(int64_t(n*frameCostMs*1000)));
+ const double presentedPts=n*intervalMs;
+ pipe.videoReady(presentedPts);
+ pipe.videoPresented(presentedPts+intervalMs);
+ }
+ const double wall=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-begin).count();
+ const double media=renderer.mediaTimeMs();const auto stops=pipe.videoWaitCount()-waits;
+ std::cout<<"UNDERRATE60 wallMs="<<wall<<" audioMs="<<media<<" additionalVideoPauses="<<stops<<" underruns="<<renderer.underruns()<<'\n';
+ check(stops==0,"51/60 sustained under-rate never stops audio");
+ check(std::abs(media-wall)<35,"audio keeps one-times speed while enhancement under-rates");
+ check(renderer.underruns()==0&&pipe.overruns()==0,"under-rate loses no PCM and inserts no silence");
+ pipe.stopThread();
+ return failures?1:0;
+}
}
int wmain(int argc, wchar_t** argv) {
- if (argc!=2&&!(argc==3&&wcscmp(argv[2],L"--jitter")==0)) return 2;
+ if (argc!=2&&!(argc==3&&(wcscmp(argv[2],L"--jitter")==0||wcscmp(argv[2],L"--underrate")==0))) return 2;
const std::filesystem::path dir=argv[1]; std::filesystem::create_directories(dir);
+ if(argc==3&&wcscmp(argv[2],L"--underrate")==0)return underrate(dir);
if(argc==3)return jitter(dir);
for(uint32_t rate:{48000u,44100u}) { const auto file=dir/(std::to_string(rate)+".wav"); fixture(file,rate); decode(file); }
AudioRenderer renderer;
@@ -193,14 +224,19 @@ int wmain(int argc, wchar_t** argv) {
gated.videoReady(0);std::this_thread::sleep_for(350ms);
check(std::abs(gatedRenderer.mediaTimeMs()-initial)<.1,"350ms NR startup and GPU-ready alone cannot advance sound");
gated.videoPresented(100);
- check(until([&]{return gated.waitingForVideo()&&gatedRenderer.mediaTimeMs()>=100;}),"audio owner stops at video coverage while GPU owner is blocked");
- const double stalled=gatedRenderer.mediaTimeMs();std::this_thread::sleep_for(350ms);
- std::cout<<"VIDEO_GATE stallStartMs="<<stalled<<" stallEndMs="<<gatedRenderer.mediaTimeMs()<<'\n';
- check(stalled<=210&&std::abs(gatedRenderer.mediaTimeMs()-stalled)<.1,"long GPU stall stays bounded after jitter grace and clock stops accumulating lead");
- gated.videoReady(260);
- check(until([&]{return gatedRenderer.mediaTimeMs()>=260;}),"ready later frame can reach its deadline after missing FG candidates");
- gated.videoPresented(310);
- check(until([&]{return gatedRenderer.mediaTimeMs()>=290;}),"actual next video releases audio clock");
+ // Sustained under-rate: the video owner presents nothing for 600ms while
+ // coverage stays at 100ms. The audio master clock keeps playing real PCM
+ // at one-times speed — steady-state video lag never pauses sound (P1).
+ const auto underrateBegin=std::chrono::steady_clock::now();
+ std::this_thread::sleep_for(600ms);
+ const double underrateWall=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-underrateBegin).count();
+ const double underrateMedia=gatedRenderer.mediaTimeMs();
+ std::cout<<"VIDEO_GATE underrateWallMs="<<underrateWall<<" underrateMediaMs="<<underrateMedia<<" coverageMs=100 waits="<<gated.videoWaitCount()<<'\n';
+ check(!gated.waitingForVideo(),"sustained video under-rate never marks audio rebuffering");
+ check(std::abs(underrateMedia-underrateWall)<35,"600ms video stall keeps one-times continuous audio");
+ check(gatedRenderer.underruns()==0,"under-rate does not starve the endpoint or insert silence");
+ gated.videoPresented(1200);
+ check(until([&]{return gatedRenderer.mediaTimeMs()>underrateMedia+50;}),"audio keeps advancing after video coverage catches up");
gated.holdForVideo();std::this_thread::sleep_for(70ms);
const double rebuilding=gatedRenderer.mediaTimeMs();std::this_thread::sleep_for(250ms);
check(std::abs(gatedRenderer.mediaTimeMs()-rebuilding)<.1,"settings rebuild freezes PCM position without skipping samples");
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index 69336aaf..5d8a5039 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -5,6 +5,8 @@
#include <filesystem>
#include <fstream>
#include <regex>
+#include <string>
+#include <vector>
using namespace veyra;
using namespace std::chrono_literals;
int wmain(int argc,wchar_t**argv){
@@ -72,16 +74,26 @@ int wmain(int argc,wchar_t**argv){
DestroyWindow(window);CoUninitialize();return failures?1:0;
}
if(fileOverload){
- engine.setVolume(0,true);bool held=false,resumed=false;double maxLead=0;
- check(until([&](const auto& s){held|=s.audioVideoWaits>1;resumed|=held&&!s.audioRebuffering&&s.frames>10;maxLead=std::max(maxLead,s.lateMs);return s.frames>=100;},90),"overloaded file keeps advancing without dropping source frames or deadlocking");
- check(held&&resumed,"actual GPU overload holds audio and resumes after video catches up");
- check(maxLead<120,"sustained GPU overload stays within hard audio lead bound plus source/endpoint interval");
+ engine.setVolume(0,true);bool audioAnchorReleased=false;double maxLag=0;
+ check(until([&](const auto& s){audioAnchorReleased|=s.frames>2&&!s.audioRebuffering;maxLag=std::max(maxLag,s.lateMs);return s.frames>=100;},90),"overloaded file keeps advancing without deadlocking");
+ check(audioAnchorReleased,"startup audio anchor releases despite overload");
+ // Sustained-overload steady window: steady-state audio never pauses —
+ // the realtime preview drops enhancement opportunities instead (P1/P2).
+ const auto steadyStart=engine.snapshot();
+ std::this_thread::sleep_for(std::chrono::seconds(2));
+ const auto steady=engine.snapshot();const auto& c=steady.metrics.flow.counters;
+ std::cout<<"FILE_OVERLOAD steadyFrames="<<steadyStart.frames<<"->"<<steady.frames<<" addedWaits="<<steady.audioVideoWaits-steadyStart.audioVideoWaits<<" lateMs="<<steady.lateMs<<" startLateMs="<<steadyStart.lateMs<<" previewSkipped="<<c.previewSkippedBeforeGraph<<" fgSkipped="<<c.fgSkippedBeforeEval<<" fgEvaluated="<<c.fgEvaluated<<'\n';
+ check(steady.audioVideoWaits==steadyStart.audioVideoWaits,"sustained overload adds no steady-state audio stops");
+ check(steady.frames>steadyStart.frames+10,"overloaded preview keeps submitting frames");
+ check(steady.lateMs<500&&std::abs(steady.lateMs-steadyStart.lateMs)<250,"overload display lag stays bounded instead of compounding");
+ check(c.previewSkippedBeforeGraph>0||c.fgSkippedBeforeEval>0,"overload reduces work before evaluation (preview skips or FG admission)");
+ std::cout<<"FILE_OVERLOAD maxObservedLagMs="<<maxLag<<'\n';
check(engine.snapshot().nrEvaluated>50&&engine.snapshot().srActive&&engine.snapshot().generated>0,"sync test actually executes NR, SR and generated frames");
auto settings=engine.snapshot().desired;settings.multiplier=2;engine.requestSettings(settings);
check(until([](const auto& s){return !s.applying&&s.applied.multiplier==2&&s.metrics.flow.counters.realPresented>4;},30),"file audio resumes after FG backend rebuild");
- check(std::abs(engine.snapshot().lateMs)<120,"rebuilt overloaded graph retains the bounded continuity allowance");
+ check(std::abs(engine.snapshot().lateMs)<500,"rebuilt overloaded graph retains bounded continuity lag");
engine.seek(.3);
- check(until([](const auto& s){return s.position>=.3&&s.position<.6&&std::abs(s.lateMs)<35;}),"playing seek warms video before releasing audio");
+ check(until([](const auto& s){return s.position>=.3&&s.position<.6&&std::abs(s.lateMs)<60;}),"playing seek warms video before releasing audio");
const auto before=engine.snapshot();engine.pause(true);engine.seek(.5);
check(until([](const auto& s){return s.transport==engine::TransportState::Paused&&s.position>=.49&&s.position<.6;}),"paused seek survives an audio overload hold");
engine.pause(false);check(until([&](const auto& s){return s.frames>before.frames+8;}),"file resumes after overload and seek");
@@ -89,7 +101,19 @@ int wmain(int argc,wchar_t**argv){
check(until([](const auto& s){return !s.applying&&!s.applied.nr&&!s.applied.sr&&s.applied.multiplier==1&&s.metrics.flow.counters.realPresented>=30;}),"leave overload and restore a sustainable video graph");
check(std::abs(engine.snapshot().lateMs)<35,"recovered graph has no retained overload offset");
engine.stop();check(until([&](const auto&){return engine.idle();},5),"file overload shutdown");
- std::cout<<"FILE_OVERLOAD held="<<held<<" resumed="<<resumed<<" maxObservedLeadMs="<<maxLead<<'\n';
+ // Presented real PTS must cover the played span uniformly: under-rate
+ // drops preview frames spread over time, never a long black stretch.
+ Logger::instance().flush();std::ifstream log(std::filesystem::path(argv[2])/"engine.log");std::string line;
+ std::vector<double> realPts;const std::regex ptsPattern("subframe=0 pts100ns=([0-9]+)");
+ while(std::getline(log,line))if(line.find("[submit]")!=std::string::npos){std::smatch m;if(std::regex_search(line,m,ptsPattern))realPts.push_back(std::stod(m[1])/10000.0);}
+ double maxPresentGap=0;unsigned resyncGaps=0;for(size_t i=1;i<realPts.size();++i){
+ const double gap=realPts[i]-realPts[i-1];
+ if(gap>400){++resyncGaps;continue;} // explicit seek/rebuild resync windows
+ maxPresentGap=std::max(maxPresentGap,gap);
+ }
+ std::cout<<"FILE_OVERLOAD realPresents="<<realPts.size()<<" maxSteadyGapMs="<<maxPresentGap<<" resyncGaps="<<resyncGaps<<'\n';
+ check(realPts.size()>=60,"overload presents a real frame sequence");
+ check(maxPresentGap<200&&resyncGaps<=5,"steady presents cover the timeline without long gaps; only bounded explicit resyncs interrupt");
DestroyWindow(window);CoUninitialize();return failures?1:0;
}
if(overload){
diff --git a/tests/unit/RealtimePreviewSchedulingTests.cpp b/tests/unit/RealtimePreviewSchedulingTests.cpp
new file mode 100644
index 00000000..2b576846
--- /dev/null
+++ b/tests/unit/RealtimePreviewSchedulingTests.cpp
@@ -0,0 +1,137 @@
+// Realtime preview scheduling policy tests (REALTIME_AV_SCHEDULING_REPAIR P2/P3).
+// Pure PTS/clock mathematics: no GPU, no WASAPI. The simulations mirror the
+// engine's streaming candidate drop — decode is ordered and instantaneous
+// relative to enhancement cost; only the enhancement opportunity of an
+// expired candidate is dropped.
+#include "veyra/engine/RealtimePreviewScheduling.h"
+#include <algorithm>
+#include <cstdint>
+#include <iostream>
+#include <vector>
+
+using namespace veyra::engine;
+
+namespace {
+int failures = 0;
+void check(bool ok, const char* text) {
+ std::cout << (ok ? "PASS " : "FAIL ") << text << '\n';
+ failures += !ok;
+}
+
+struct Simulation {
+ std::vector<double> submittedPts;
+ uint64_t skipped = 0;
+ std::vector<double> completionLatenessMs;
+};
+
+// Mirrors the engine loop: the source is ready at its PTS, enhancement of one
+// submitted frame costs costMs, and the next selection happens when the GPU
+// batch completed. Expired candidates are dropped while a newer decoded frame
+// exists; the final candidate before EOF is always kept.
+Simulation simulateFilePreview(double intervalMs, double costMs, double durationMs) {
+ Simulation sim;
+ double readyAt = 0; // wall/media clock when the engine can select
+ double nextPts = 0; // next decoded candidate PTS
+ while (nextPts < durationMs) {
+ double pts = nextPts;
+ while (previewCandidateExpired(readyAt, pts, intervalMs) && pts + intervalMs < durationMs) {
+ ++sim.skipped;
+ pts += intervalMs;
+ }
+ sim.submittedPts.push_back(pts);
+ sim.completionLatenessMs.push_back(readyAt + costMs - pts);
+ readyAt += costMs;
+ nextPts = pts + intervalMs;
+ }
+ return sim;
+}
+}
+
+int main() {
+ // --- candidate expiry boundaries
+ check(!previewCandidateExpired(0, 0, 16.7), "window start is not expired");
+ check(!previewCandidateExpired(16.0, 0, 16.7), "inside window is not expired");
+ check(!previewCandidateExpired(16.71, 0, 16.7), "grace epsilon keeps the boundary frame");
+ check(previewCandidateExpired(16.72, 0, 16.7), "just past the window is expired");
+ check(!previewCandidateExpired(1000, 500, 0), "unknown cadence never drops a candidate");
+ check(!previewGeneratedExpired(105, 100), "generated result within 10ms grace is presentable");
+ check(previewGeneratedExpired(110.2, 100), "generated result past the grace is expired");
+
+ // --- 30fps source, 15fps capacity: uniform every-other coverage
+ {
+ const auto sim = simulateFilePreview(1000.0 / 30, 67.0, 3000.0);
+ std::cout << "30to15 submitted=" << sim.submittedPts.size() << " skipped=" << sim.skipped << '\n';
+ check(sim.submittedPts.size() >= 42 && sim.submittedPts.size() <= 48,
+ "30fps at half capacity submits about half the frames");
+ // Exclude the EOF tail (final candidates are always kept regardless
+ // of expiry) and the warmup pair.
+ bool uniform = sim.submittedPts.size() > 2;
+ double maxGap = 0;
+ for (size_t i = 2; i < sim.submittedPts.size(); ++i) {
+ if (sim.submittedPts[i] > 3000.0 - 2 * (1000.0 / 30)) break;
+ const double gap = sim.submittedPts[i] - sim.submittedPts[i - 1];
+ maxGap = std::max(maxGap, gap);
+ uniform &= gap > 1.5 * (1000.0 / 30) && gap < 2.5 * (1000.0 / 30);
+ }
+ check(uniform && maxGap > 0 && maxGap < 2.5 * (1000.0 / 30),
+ "30->15 sampling spreads across the whole second, not front-loaded");
+ check(sim.submittedPts.back() >= 3000.0 - 3 * (1000.0 / 30),
+ "sampling reaches the media tail instead of stalling");
+ double maxLate = 0;
+ for (double late : sim.completionLatenessMs) maxLate = std::max(maxLate, late);
+ check(maxLate < 70.0 + 2 * (1000.0 / 30) + 0.5,
+ "steady-state display lateness stays bounded by one completion plus window");
+ }
+
+ // --- 60fps source, 51/60 capacity: skips distributed, lateness bounded
+ {
+ const auto sim = simulateFilePreview(1000.0 / 60, 1000.0 / 51, 4000.0);
+ std::cout << "60underrate submitted=" << sim.submittedPts.size() << " skipped=" << sim.skipped << '\n';
+ check(sim.skipped > 0 && sim.skipped < sim.submittedPts.size() / 3,
+ "51/60 under-rate skips a bounded fraction, not most frames");
+ double maxGap = 0;
+ for (size_t i = 1; i < sim.submittedPts.size(); ++i)
+ maxGap = std::max(maxGap, sim.submittedPts[i] - sim.submittedPts[i - 1]);
+ check(maxGap <= 3 * (1000.0 / 60) + 0.01, "60fps under-rate never leaves a long display gap");
+ double maxLate = 0;
+ for (double late : sim.completionLatenessMs) maxLate = std::max(maxLate, late);
+ check(maxLate < 100.0, "under-rate display lateness stays bounded (no runaway backlog)");
+ }
+
+ // --- extreme overload: still submits the freshest candidate (no black)
+ {
+ const auto sim = simulateFilePreview(1000.0 / 60, 200.0, 2000.0);
+ std::cout << "extreme submitted=" << sim.submittedPts.size() << '\n';
+ check(!sim.submittedPts.empty(), "extreme overload still presents candidates");
+ bool spaced = true;
+ for (size_t i = 1; i < sim.submittedPts.size(); ++i)
+ spaced &= sim.submittedPts[i] - sim.submittedPts[i - 1] > 0;
+ check(spaced, "submissions stay PTS-ordered and strictly increasing");
+ check(sim.submittedPts.back() >= 2000.0 - 3 * (1000.0 / 60), "even extreme overload keeps covering the timeline");
+ }
+
+ // --- XeSS generation gate hysteresis
+ {
+ XessGenerationGate gate;
+ const double interval = 1000.0 / 60;
+ bool changed = false;
+ for (int i = 0; i < 11; ++i) changed |= gate.observe(50.0, interval);
+ check(!changed && !gate.suppressed(), "eleven late frames do not yet suppress XeSS generation");
+ check(gate.observe(50.0, interval) && gate.suppressed(), "twelfth sustained late frame suppresses");
+ bool flapped = false;
+ for (int i = 0; i < 200 && !flapped; ++i)
+ flapped = i % 2 ? gate.observe(5.0, interval) : gate.observe(50.0, interval);
+ check(gate.suppressed() && !flapped, "flapping lateness while suppressed never re-enables");
+ gate.observe(50.0, interval); // clear the healthy streak left by the flap tail
+ bool resumed = false;
+ for (int i = 0; i < 59; ++i) resumed |= gate.observe(5.0, interval);
+ check(!resumed && gate.suppressed(), "fifty-nine healthy frames keep generation suppressed");
+ check(gate.observe(5.0, interval) && !gate.suppressed(), "sixtieth healthy frame re-enables generation");
+ gate.observe(50.0, interval);
+ gate.reset();
+ check(!gate.suppressed(), "reset clears suppression state");
+ }
+
+ std::cout << "failures=" << failures << '\n';
+ return failures ? 1 : 0;
+}