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 PS5 frame-generation deadlines, clock drift and overload metrics
Veyra Goal Agentb5cb1b53afa4
diff --git a/apps/veyra/ui/LiveStatusDashboard.h b/apps/veyra/ui/LiveStatusDashboard.hindex 0bf10848..b5592a76 100644--- a/apps/veyra/ui/LiveStatusDashboard.h+++ b/apps/veyra/ui/LiveStatusDashboard.h@@ -35,7 +35,7 @@ inline void paintDashboard(HWND h,HDC dc,int w,int height,const engine::PlayerSnconst wchar_t* names[]={L"光流耗时",L"NR耗时",L"超分耗时",L"帧生成耗时"};for(int i=0;i<4;++i){int x=left+i*(cw+gap);card(x,top,cw,58);text(names[i],x+6,top+7,cw-10,17,9,secondary);const auto& a=f.gpuTiming[size_t(stages[i])];std::wstring value=L"—";- if(active){if(s.metrics.gpu[size_t(stages[i])].state==diagnostics::SampleState::NotExecuted)value=L"未开启";else if(a.mean)value=std::format(L"{:.1f}",*a.mean);}+ if(active){if(a.mean)value=std::format(L"{:.1f}",*a.mean);else if(s.metrics.gpu[size_t(stages[i])].state==diagnostics::SampleState::NotExecuted)value=(i==3&&s.applied.multiplier>1)?L"等待补帧":L"未开启";}if(i==3&&s.applied.multiplier>1&&s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS)value=L"不可测";text(value,x+6,top+27,cw-10,24,14,textColor);}diff --git a/docs/PS5_FG_CLOCK_METRICS_REPAIR_2026-09-13.md b/docs/PS5_FG_CLOCK_METRICS_REPAIR_2026-09-13.mdnew file mode 100644index 00000000..d078abb1--- /dev/null+++ b/docs/PS5_FG_CLOCK_METRICS_REPAIR_2026-09-13.md@@ -0,0 +1,44 @@+# PS5 补帧、过载耗时与声音补偿修复++基线 `c68b4b0`,分支 `codex/ps5-fg-overload-audio`。用户报告 DLSS 2X 无有效补帧、过载后耗时消失、声音补偿持续上涨。本次只修本机版本,不发布。++## 证据与口径++- 原始日志副本:`logs/ps5-fg-overload-audio-before.log`(含本机信息,不入 Git)。revision 7:485 个补帧候选全部在 Evaluate 前被拒绝;revision 8:1694 个候选中只执行 3 次且全部预热。不是仅 UI 显示错误,也不是 DLL 初始化失败。+- 19:09:20 至 19:17:23 的串流回调计数、扣除 receiveAge 后,平均约 59.9314 fps。旧 RemotePlayClock 直接用 frameIndex / 60;约八分钟产生约 0.55 秒时间轴偏差,与用户约 575 ms 音频等待现象量级一致。日志不足以测量 PS5 扫描输出时间,不能把 59.9314 宣称为协议原生帧率。+- 声音补偿公式:`当前呈现 host - 视频 PTS - 音频到达 host/PTS 映射`,裁剪到自动模式上限。它是音视频对齐等待,不是 NR/SR/FG GPU 耗时。PCM 队列是实际尚未送入声音设备的样本量,不能与补偿直接相加。+- 解码后 latest mailbox 旧实现把覆盖标成 Discontinuity,导致每次过载丢帧重开统计窗口;GPU 计时异步返回时又被 epoch 检查拒绝。需要保留 GPU 历史 reset,但不清空同配置下的耗时统计。+- PS5 的 arrival 是压缩 AU 到达,不能直接当成解码后画面可用的时间。在补帧调度锚点使用 decodedHost,完整输入到呈现的测量仍从原 AU arrival 起算,不隐藏解码耗时。+- 实机第三轮表明:仅修正首次锚点仍不足,PS5 硬解交付耗时约 2–15 ms 摆动,会耗尽固定旧锚点的余量。最终 PS5 专用准入/呈现使用每对新解码输入的 decodedHost + 一个输入间隔预算;在增强前确定,增强耗时或 GPU 完成不能延长它。A/B 内仍按 PTS 间距显示,源 PTS 不改写为完成时间;网络/解码抖动仍可能体现在输出节奏,不能保证锁定 120 fps。文件与物理采集的现有时间线不变。++## 实施++1. RemotePlayClock 采用最近一秒到达时间的低抖动相位估计,最大 0.5% 渐进修正。保持单调 PTS、原帧序号和 nominal duration;真实大间断继续显式 reset。不是硬编码 59.94,不改变文件原始 PTS。+2. 音频 ingress 映射改为最近两秒的最小值,移除永不老化的启动最小值,避免设备钟差被算成永久增加的补偿。保留原 PCM 连续性、重采样和有限队列策略,不靠丢声音压低显示值。+3. decoded mailbox 使用 Drop,并传递先前真实的 Open/Discontinuity 等事件。Engine 的 Drop / preview skip 只重置处理历史;明确 seek/配置/尺寸/设备/时间轴中断仍创建新统计窗口。FrameFlowWindow 只接受本统计窗口注册的 epoch 范围及同配置 GPU 结果。+4. 最近一秒有实际 FG 测量则显示该均值;配置已开启但当前没有执行时显示“等待补帧”,不再写“未开启”。XeSS 内部计时仍标不可测。+5. 新增每秒补帧准入原因、每两秒音频对齐和周期串流时钟日志,供后续用户长时验收。++## 验证与未完成边界++- 构建命令:`cmd /c out/remoteplay/build-extra-delay.cmd`。最初链接因运行中的 veyra.exe 被锁失败;将旧 EXE 重命名为同目录忽略文件 `veyra-before-clock-fix.exe`,保持旧进程运行,再链接成功。不是关闭用户的软件。+- `cmd /c out/remoteplay/build-clock-tests.cmd`:离线核心 68/68;新增模拟十分钟 30/60 profile、正负 1400 ppm 漂移、2 ms 抖动及真实准入类检查。初版用 5 ms 抖动却要求 98% 准入,因预算确实可能不足而失败;改为具有明确余量的 2 ms 固定输入,未放宽产品准入阈值。+- `veyra_repair_contract_tests.exe`:最终 103 checks / 0 failures;覆盖连续 78 次历史切换的异步计时保留、新窗口拒绝旧计时、十分钟音频 ingress 漂移老化、PS5 解码抖动不占预算而增强超时仍拒绝。+- `veyra_presentation_worker_tests.exe`:通过现有调度预算和恢复检查。+- `veyra_capture_audio_tests.exe`:真实 WASAPI 基础、模式切换、长延迟、间断恢复和有界 PCM 测试通过,`logs/ps5-clock-audio.log`。+- `veyra_capture_audio_tests.exe --drift-slow`:120 秒设备钟差,P95 音画偏差 4.254 ms、missing=0、resets=1(启动)、overflows=0,队列峰值 89.646 ms,`logs/ps5-clock-audio-drift.log`。+- `veyra_live_presentation_tests.exe --last-paired-ps5 <日志目录>` 是明确 opt-in 的真实串流测试:复用本机已加密的最后主机、硬解、4K 视频 SR、NR、DLSS 2X、真实声音设备静音输出,30–38 秒注入 35 ms CPU 工作模拟过载。不会写配对或执行开关机。+- 实机第一轮失败,暴露 decoded mailbox 的 Discontinuity 与压缩 AU 锚点问题;第二轮过载耗时 164/164 采样保留,但补帧恢复/长时测试未通过。第三轮跑完 120 秒,音频等待早期 64.761 / 末期 57.389 ms,过载计时 163/163,仍因末期有效补帧只有 4 fps 失败,因此继续修正解码输入对的固定预算。后续结果见下方追加;不得把前三轮算通过。++## 后续实测结果++最终第四轮 120 秒实机测试通过:`logs/ps5-clock-live4-result.log`、`logs/ps5-clock-live4/engine.log`。++- RTX 5070、PS5 H.264 硬解、视频 SR 到 3840×2160、实时内部 NR、DLSS 2X;NR Feature18 Create=0x1 / SEH=0,DLSSG Create 3840×2160=0x1 / SEH=0,预热 Evaluate=0x1。+- 115 秒时有效生成累计 5251 帧,最终一秒有效生成 53 fps。呈现提交达到过 120 fps,稳态仍有约 84–118 fps 波动,不能宣传固定 120 fps,也未测显示器 scanout。+- 注入 CPU 过载后,163/163 次采样保留 NR 实测耗时;恢复后持续生成有效补帧。不是取消过载保护或给假计时。+- 音频等待早期 64.587 ms,末期 57.892 ms;启动与强制过载恢复合计 4 次 reset,恢复后未继续增长。两分钟实机加离线十分钟仿真,不等于小时级游戏验收。+- `veyra_remoteplay_boundary_tests.exe` 通过,新增 Drop / Discontinuity 分类断言;边界测试不冒充实机证据。+- 最终产品构建:`cmd /c out/remoteplay/build-clock-product.cmd`,`logs/ps5-clock-product-final.log`;最终合同构建及运行:`cmd /c out/remoteplay/build-clock-contract.cmd`、`veyra_repair_contract_tests.exe`,`logs/ps5-clock-contract-final.log`。`git diff --check` 通过。++交付 EXE:`out/remoteplay/product-repair/veyra.exe`,桌面原 PS5 测试版快捷方式仍指向该位置。当前旧进程须退出后重新打开才会运行新代码。本轮未改 NVIDIA/FFmpeg DLL,未提交 SDK、二进制、配对资料或日志,没有 push / Release。下一步唯一验收:用户重开测试版,按实际游戏配置长时游玩,核对补帧、过载计时和声音连续性;若仍异常,带新增 `live-fg-admission` / `remoteplay-clock` / `live-audio-sync` 日志继续定位。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 97bd264f..36704c8e 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1759,3 +1759,8 @@ apps/veyra/SettingsWindow.cpp调整布局;apps/veyra/ui/AppShell.cpp新增音基线83f90ba,分支codex/ps5-decoded-frame-strip。用户软件解码正常;同真实PS5 AU软/硬解比较定位到FFmpeg n9.0.1 H.264 MAX_SLICES=32,而PS5输入68 slices,硬解在进入增强前已经损坏。外置开源源码容量改256并按原LGPL功能配置重编译;同码流全图误差由167.459变为0,已查看完整装备页,日志ps5-live-decode/ps5-live-patched。另用两张黑白图并发GPU排队复现并修复共享硬解SRV槽覆盖,按已有两槽fence轮转并使用staging,修复后4组错误通道归零。产品构建cmd /c out/remoteplay/build-extra-delay.cmd成功(最后ps5-strip-final-build.log);普通视频软硬解全图、8组HDR颜色/呈现、6组Main10软硬解NR/SR/FG组合、40秒主程序硬解NR(1135次NR,1134次NVOF,failed=false)、UI合同回归通过。NR CreateFeature18=0x1,SEH=0。未将共享Source/Graph实机同AU验证冒充主UI长时PS5/HDR/手柄/音频验收。新FFmpeg五DLL更新本机测试目录与默认开发前缀,原件忽略目录备份;新增源码补丁、重编译脚本、双层provenance打包校验及真实全图诊断。对应源码ZIP本地验证通过,未发布;SDK/NVIDIA运行时/依赖DLL/媒体/凭据均未入Git。失败记录包括:诊断缺include、MSYS link遮蔽MSVC、零上下文补丁apply失败,均已修正;最初GPU回读一致但画面仍坏的检查不作通过证明。详情、命令、哈希、日志与后续验收见docs/PS5_HARDWARE_STRIP_REPAIR_2026-09-13.md。用户下一步重开桌面PS5测试版,选自动优先硬解或D3D12VA重连体验。++## 2026-09-13 PS5 DLSS 补帧、过载计时与声音补偿修复+基线 c68b4b0,分支 codex/ps5-fg-overload-audio。日志证实 DLSS 候选大量被截止时间判定跳过、实际串流约 59.9314 fps 而视频时钟固定除以60、decoded mailbox 覆盖误标 Discontinuity 导致统计窗口不断重开。修正本地估计时钟渐进校准、音频 ingress 映射有限老化、Drop 分类与同配置软历史重置的异步计时保留;PS5 每对新解码输入在增强前确定补帧预算,不用增强完成延后截止时间。UI 不再把已开启但等待执行的 FG 写成未开启。+构建 cmd /c out/remoteplay/build-clock-product.cmd 成功;离线核心68/68,合同103/103,调度与RemotePlay边界通过。真实WASAPI基础回归及120秒慢钟差通过,P95音画偏差4.254ms、仅启动reset1次、无溢出。前三轮实机回归失败均保留:逐步定位覆盖事件分类、压缩AU锚点和硬解交付抖动。第四轮120秒PS5 H264硬解+4K视频SR+实时NR+DLSS2X通过;115秒有效生成累计5251,末期有效补帧53fps,过载163/163保留计时,音频等待早期64.587/末期57.892ms。NR/DLSSG Create与预热Evaluate=0x1,SEH=0。不能宣称固定120fps或小时级验收。+证据 logs/ps5-clock-live4-result.log、logs/ps5-clock-live4/engine.log、logs/ps5-clock-audio-drift.log;其余命令、失败边界和修改文件见 docs/PS5_FG_CLOCK_METRICS_REPAIR_2026-09-13.md。运行中的旧EXE重命名保留,最新主程序已构建到原快捷方式路径,用户重开才生效。未改运行DLL,未提交SDK/二进制/凭据/日志,未推送发布。下一步由用户长时游戏体验验收。diff --git a/include/veyra/engine/FrameFlowWindow.h b/include/veyra/engine/FrameFlowWindow.hindex d8e119aa..f853dcf9 100644--- a/include/veyra/engine/FrameFlowWindow.h+++ b/include/veyra/engine/FrameFlowWindow.h@@ -35,11 +35,13 @@ public:}};// Each asynchronous job retains its own window. Replacing the current window-// never lets an old job increment the new revision/epoch's counters.+// never lets an old job increment a new settings/hard-reset window's counters.+// Soft preview/mailbox drops retain that window and its measured throughput.class FrameFlowWindow {mutable std::mutex mutex_;diagnostics::FrameFlowMetrics metrics_;std::shared_ptr<FrameCompletionRates> rates_;+ uint64_t firstTimingEpoch_=0,lastTimingEpoch_=0;std::array<uint64_t,8192> readyBatches_{};struct Latency {int64_t time;double ms;};std::deque<Latency> latency_;@@ -61,6 +63,15 @@ class FrameFlowWindow {public:FrameFlowWindow(uint64_t session,pipeline::FrameIdentity id,int64_t now,std::shared_ptr<FrameCompletionRates> rates={}):rates_(rates?std::move(rates):std::make_shared<FrameCompletionRates>(now)){metrics_.latest.sessionId=session;metrics_.latest.frame=id;+ firstTimingEpoch_=lastTimingEpoch_=id.epoch;+ }+ // A mailbox/preview drop invalidates temporal inputs, not GPU measurements+ // from the same settings. Explicit open/seek/settings resets create a new+ // window; asynchronous results outside its registered epoch range reject.+ void advanceHistory(pipeline::FrameIdentity id){+ std::lock_guard lock(mutex_);+ if(id.settingsRevision==metrics_.latest.frame.settingsRevision&&id.epoch>=lastTimingEpoch_)+ lastTimingEpoch_=id.epoch;}template<class F> void update(F action){std::lock_guard lock(mutex_);action(metrics_);}// CPU-observed reset/rebuild lifecycle; GPU execution remains in GPU timing.@@ -92,7 +103,8 @@ public:}void gpuFrame(const diagnostics::GpuFrameTiming& frame,int64_t now){std::lock_guard lock(mutex_);- if(!metrics_.latest.sameWindow(metrics_.latest.sessionId,frame.identity))return;+ if(frame.identity.settingsRevision!=metrics_.latest.frame.settingsRevision||+ frame.identity.epoch<firstTimingEpoch_||frame.identity.epoch>lastTimingEpoch_)return;// Every dequeued record is delivered once. Different frames may have// equal timestamp endpoints, especially empty diagnostic passes.for(unsigned i=0;i<gpuCount;++i){const auto& s=frame.gpu[i];if(s.state==diagnostics::SampleState::Measured&&s.milliseconds)stage(i,*s.milliseconds,now);}diff --git a/include/veyra/engine/PresentationScheduler.h b/include/veyra/engine/PresentationScheduler.hindex fce044a7..f084655c 100644--- a/include/veyra/engine/PresentationScheduler.h+++ b/include/veyra/engine/PresentationScheduler.h@@ -2,7 +2,9 @@#include <cstdint>namespace veyra::engine {// Maps a continuous source epoch to one monotonic host timeline. Processing-// completion must never re-anchor individual pairs. Units are 100 ns.+// completion must never re-anchor individual pairs. PS5 may explicitly reset+// per newly decoded input pair (before enhancement) because its PTS is locally+// estimated and decoder delivery jitter is not playback lateness. Units: 100 ns.class PresentationScheduler {public:void reset(uint64_t epoch,int64_t source,int64_t host,int64_t lookahead,bool paceSourcePts=true) {diff --git a/include/veyra/remoteplay/Timeline.h b/include/veyra/remoteplay/Timeline.hindex 1086ecd5..56eaa45f 100644--- a/include/veyra/remoteplay/Timeline.h+++ b/include/veyra/remoteplay/Timeline.h@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-3.0-only#pragma once#include "Types.h"+#include <deque>namespace veyra::remoteplay {class Sequence16Extender {public:@@ -25,6 +26,12 @@ public:std::optional<std::int64_t> audioPts(std::uint64_t firstSample,std::uint32_t rate,HostTime audioStart) const noexcept;private:HostTime origin_=0,videoAnchor_=0,lastArrival_=0;+ // Bounded lower-envelope PLL: nominal profile FPS is not a source clock+ // (a 60 profile can deliver ~59.94). Filter network jitter, slew only the+ // locally estimated timestamps, and never accumulate nominal-rate error.+ struct PhaseSample {HostTime arrival;std::int64_t error;};+ std::deque<PhaseSample> phaseWindow_;+ std::int64_t phase_=0,lastPts_=0;std::uint64_t firstIndex_=0,lastIndex_=0;std::uint32_t fps_=0;bool anchored_=false;};diff --git a/include/veyra/sink/ArrivalClockMapping.h b/include/veyra/sink/ArrivalClockMapping.hnew file mode 100644index 00000000..c66fc29a--- /dev/null+++ b/include/veyra/sink/ArrivalClockMapping.h@@ -0,0 +1,19 @@+#pragma once+#include <deque>+#include <algorithm>+namespace veyra::sink {+// Recent low-jitter mapping, not an all-time minimum. Device oscillator drift+// must not be reported as ever-growing software audio compensation.+class ArrivalClockMapping {+ struct Sample {double host,offset;};+ std::deque<Sample> minimum_;+public:+ void reset(){minimum_.clear();}+ double observe(double hostMs,double ptsMs){+ const double offset=hostMs-ptsMs;+ while(!minimum_.empty()&&(minimum_.front().host<=hostMs-2000||minimum_.size()>=4096))minimum_.pop_front();+ while(!minimum_.empty()&&minimum_.back().offset>=offset)minimum_.pop_back();+ minimum_.push_back({hostMs,offset});return minimum_.front().offset;+ }+};+}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex c7915cdb..3f31658f 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -258,6 +258,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sLiveStats liveStats;std::deque<int64_t> liveSubmissions;TimingWindow liveAges,liveWaits,livePresent,liveReady;FgRecoveryBudget fgBudget;uint64_t fgBudgetRevision=options.settings.revision;+ int64_t nextFgAdmissionLog=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;@@ -561,6 +562,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(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();+ // A PS5 callback is a compressed AU, not a decoded video frame.+ // Its decode baseline must not consume the entire FG lookahead+ // budget. Still measure full ingress latency from captureArrival.+ const auto liveInputReady=isRemote&&pkt.decodedHost100ns>0?pkt.decodedHost100ns:captureArrival;const auto sourceArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100;// A skipped preview candidate breaks the temporal span the// motion/NR/FG history was built on: the next processed frame@@ -568,10 +573,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// 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;+ const bool hardFrameReset=reset||pipeline::breaksHistory(pkt.flags&~static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Drop));+ const bool temporalBreak=pipeline::breaksHistory(pkt.flags)||previewSkipSinceProcess;+ const bool previewOnlyReset=!hardFrameReset&&temporalBreak;if(hardFrameReset)++metricsWindowEpoch;- const bool historyReset=hardFrameReset||previewSkipSinceProcess;+ const bool historyReset=hardFrameReset||temporalBreak;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.@@ -585,11 +591,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(isCapture&&!rereadCached&&useLiveFgAdmission&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){const auto presentP95=livePresent.p95();admitFg=[&,presentP95](const pipeline::FrameBatch& batch){- if(!liveTimeline.anchored(batch.identity.epoch))liveTimeline.reset(batch.identity.epoch,batch.b100ns,captureArrival,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));+ // PS5 decode/network delivery jitters independently of+ // its estimated PTS. Give each newly decoded pair its+ // one-input-interval budget, anchored BEFORE enhancement.+ // Never extend it based on processing/ready completion.+ if(isRemote||!liveTimeline.anchored(batch.identity.epoch))liveTimeline.reset(batch.identity.epoch,batch.b100ns,liveInputReady,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));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 fgBudget.admit(host100ns(),liveTimeline.deadline(lastGenerated),elapsedMs(processStart),presentP95);+ 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("admitted={} remainingDeadlineMs={:.3f} predictedMs={:.3f} elapsedMs={:.3f} decodedAgeMs={:.3f} callbackAgeMs={:.3f} presentP95Ms={:.3f}",admitted,double(deadline-now)/10000,fgBudget.predicted(now).value_or(-1),elapsed,double(now-liveInputReady)/10000,double(now-captureArrival)/10000,presentP95));}+ return admitted;};}// File playback: same pair admission, but deadlines are PTS@@ -655,12 +669,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(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);- frameFlow->update([&](auto& m){m.counters.historyResets+=uint64_t(out.historyReset);m.counters.settingsResets+=uint64_t(settingsChanged);m.counters.captureDropResets+=uint64_t(pipeline::hasFrameFlag(pkt.flags,pipeline::FrameFlagBits::Drop));});+ frameFlow->update([&](auto& m){m.counters.settingsResets+=uint64_t(settingsChanged);});captureFlowBase=captureFlowLast;{std::lock_guard lock(mutex_);rateSkippedBase=snapshot_.captureRateSkipped;activeFlow_=frameFlow;}veyra::log::info("metrics",std::format("reset session={} appliedRevision={} epoch={} sourceBase={}",runSessionId,metricsRevision,metricsEpoch,statsSourceBase));}const double processMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();+ frameFlow->advanceHistory(out.batch.identity);+ frameFlow->update([&](auto& m){m.counters.historyResets+=uint64_t(out.historyReset);m.counters.captureDropResets+=uint64_t(pipeline::hasFrameFlag(pkt.flags,pipeline::FrameFlagBits::Drop));});const auto lineage=lineageTracker.observe(out.batch,sourceArrival,pkt.arrivalHost100ns>0,rereadCached||isImage);if(lineage&&out.hasGenerated){frameFlow->pairArrived(*lineage);@@ -679,13 +695,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sstd::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));}- if(isCapture&&!rereadCached&&!liveTimeline.anchored(out.batch.identity.epoch)){+ if(isCapture&&!rereadCached&&(isRemote||!liveTimeline.anchored(out.batch.identity.epoch))){const auto duration100ns=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);// File replay has no device pacing and still needs its PTS// clock. Physical capture without FG presents as soon as ready.const bool paceSourcePts=options.fg||!physicalCapture;- veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,paceSourcePts?"source-pts":"capture-ready"));- liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,captureArrival,options.fg?duration100ns:0,paceSourcePts);+ if(!liveTimeline.anchored(out.batch.identity.epoch))veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,isRemote?"decoded-pair":paceSourcePts?"source-pts":"capture-ready"));+ liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns:0,paceSourcePts);}if(!isImage&&!isCapture&&frames==0){anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}double frameWaitMs=0,framePresentMs=0;diff --git a/src/remoteplay/Timeline.cpp b/src/remoteplay/Timeline.cppindex 97fca307..80ed627a 100644--- a/src/remoteplay/Timeline.cpp+++ b/src/remoteplay/Timeline.cpp@@ -2,6 +2,7 @@#include "veyra/remoteplay/Timeline.h"#include <limits>#include <stdexcept>+#include <algorithm>namespace veyra::remoteplay {Sequence16Extender::Result Sequence16Extender::observe(std::uint16_t n) noexcept {if(!initialized_){initialized_=true;previous_=n;extended_=n;return {extended_,true,true,0};}@@ -32,11 +33,25 @@ std::optional<EstimatedStamp> RemotePlayClock::video(std::uint64_t index,HostTimif(!anchored_){videoAnchor_=arrival-origin_;firstIndex_=index;anchored_=true;}else if(arrival-lastArrival_>2000000 || index-lastIndex_>fps_/2u){videoAnchor_=arrival-origin_;firstIndex_=index;gap=true;+ phaseWindow_.clear();phase_=0;}const auto delta=rescale(index-firstIndex_,fps_);if(!delta || videoAnchor_>std::numeric_limits<std::int64_t>::max()-*delta)return {};- lastArrival_=arrival;lastIndex_=index;- return EstimatedStamp{videoAnchor_+*delta,10000000/static_cast<std::int64_t>(fps_),gap};+ const auto nominal=videoAnchor_+*delta;+ const auto error=(arrival-origin_)-nominal;+ while(!phaseWindow_.empty()&&phaseWindow_.front().arrival<=arrival-10000000)phaseWindow_.pop_front();+ while(!phaseWindow_.empty()&&phaseWindow_.back().error>=error)phaseWindow_.pop_back();+ phaseWindow_.push_back({arrival,error});+ // At most 0.5% slew; even after a jitter burst successive PTS cannot+ // reverse or abruptly jump. A real network gap still resets above.+ const auto step=10000000/static_cast<std::int64_t>(fps_);+ const auto maxSlew=step/200;+ phase_+=std::clamp(phaseWindow_.front().error-phase_,-maxSlew,maxSlew);+ if(phase_>0&&nominal>std::numeric_limits<std::int64_t>::max()-phase_)return {};+ auto pts=nominal+phase_;+ if(index!=firstIndex_&&!gap)pts=std::max(pts,lastPts_+1);+ lastArrival_=arrival;lastIndex_=index;lastPts_=pts;+ return EstimatedStamp{pts,step,gap};}std::optional<std::int64_t> RemotePlayClock::audioPts(std::uint64_t first,std::uint32_t rate,HostTime start) const noexcept {if(!fps_ || start<origin_ || rate<8000 || rate>192000)return {};diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cppindex 11e2b0e5..ecaaab1e 100644--- a/src/sink/CaptureAudioSession.cpp+++ b/src/sink/CaptureAudioSession.cpp@@ -1,5 +1,6 @@#include "veyra/sink/CaptureAudioSession.h"#include "veyra/sink/WasapiAudioSink.h"+#include "veyra/sink/ArrivalClockMapping.h"#include <algorithm>#include <cmath>#include <cstring>@@ -29,6 +30,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {std::atomic<unsigned> mode{0};std::atomic<int> offset{0};double videoPts=0,videoHost=0;bool haveVideo=false;double ingressMapping=0;bool haveIngress=false;+ ArrivalClockMapping ingressClock;int64_t lastArrival=0;CaptureAudioState state;std::thread thread;@@ -69,6 +71,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {double filteredError=0,correctionPpm=0;int64_t nextCorrection=0;int64_t lastReset=0;+ int64_t nextSyncLog=0;unsigned appliedMode=mode.load();int appliedOffset=offset.load();uint64_t lastUnderruns=0;bool endpointEventReady=false;@@ -220,6 +223,10 @@ struct CaptureAudioSession::Impl : AudioPcmSource {const auto audioPts=renderer.mediaTimeMs();const double observedNow=double(hostTime())/10000;state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(vPts+observedNow-vHost)):std::nullopt;+ if(hostTime()>=nextSyncLog){+ nextSyncLog=hostTime()+20000000;+ log::info("live-audio-sync",std::format("videoPtsMs={:.3f} videoHostMs={:.3f} audioIngressMapMs={:.3f} compensationMs={:.3f} pcmMs={:.3f} endpointMs={:.3f} skewMs={:.3f} correctionPpm={:.1f} resets={} (local clock alignment, not GPU execution time)",vPts,vHost,ingress,target,state.bufferedMs,state.endpointBufferedMs,state.skewMs.value_or(-999),state.driftCorrectionPpm,state.resets));+ }}}renderer.shutdown();std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();state.endpointBufferedMs=0;@@ -248,10 +255,9 @@ bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool disstd::lock_guard lock(p.mutex);if(p.stop||!p.state.error.empty())return true;if(discontinuity){p.input.clear();p.inputBytes=0;p.pendingReset=true;p.haveVideo=false;}- const double mapping=double(hostTime())/10000-pts;p.lastArrival=hostTime();- if(!p.haveIngress||discontinuity){p.ingressMapping=mapping;p.haveIngress=true;}- else p.ingressMapping=std::min(p.ingressMapping,mapping);+ if(!p.haveIngress||discontinuity){p.ingressClock.reset();p.haveIngress=true;}+ p.ingressMapping=p.ingressClock.observe(double(p.lastArrival)/10000,pts);const double blockMs=1000.0*bytes/p.format.nAvgBytesPerSec;if(p.queuedMs()+blockMs>Impl::maxQueuedMs){p.input.clear();p.inputBytes=0;p.pendingReset=true;++p.state.overflows;p.queueChanged();diff --git a/src/source/RemotePlaySessionSource.cpp b/src/source/RemotePlaySessionSource.cppindex dd1c0708..7d4d2b57 100644--- a/src/source/RemotePlaySessionSource.cpp+++ b/src/source/RemotePlaySessionSource.cpp@@ -121,7 +121,7 @@ void RemotePlaySessionSource::publishDecoded(const AVFrame* frame,pipeline::Framstd::lock_guard lock(mutex_);++rates_.decoded;if(latest_){++skipped_;item.packet.flags|=latest_->packet.flags;- item.packet.flags|=static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);}+ item.packet.flags|=static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Drop);}latest_=std::move(item);}SourceReadStatus RemotePlaySessionSource::read(pipeline::FramePacket& packet,const AVFrame** frame) {diff --git a/src/source/RemotePlaySource.cpp b/src/source/RemotePlaySource.cppindex 99956f8a..7762f037 100644--- a/src/source/RemotePlaySource.cpp+++ b/src/source/RemotePlaySource.cpp@@ -245,10 +245,12 @@ pipeline::FramePacket RemotePlaySource::makePacket(const remoteplay::VideoSamplepacket.arrivalHost100ns = sample.arrival100ns;const auto stamp = clock_.video(sourceIndex, sample.arrival100ns);if (stamp) {+ if(sourceIndex%600==0)veyra::log::info("remoteplay-clock",std::format("wireIndex={} ptsMs={:.3f} arrivalMinusPtsMs={:.3f} nominalFps={} (arrival-disciplined local estimate, not PS5 native PTS)",sourceIndex,double(stamp->pts100ns)/10000,double(sample.arrival100ns-static_cast<int64_t>(origin100ns_)-stamp->pts100ns)/10000,info_.averageFps));packet.pts = pipeline::Rational{stamp->pts100ns, 10000000};packet.duration = pipeline::Rational{stamp->duration100ns, 10000000};if (stamp->discontinuity) packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);} else {+ veyra::log::error("remoteplay-clock",std::format("invalid local timestamp wireIndex={} arrival100ns={} origin100ns={}",sourceIndex,sample.arrival100ns,origin100ns_));packet.pts = pipeline::Rational::unknown();packet.duration = pipeline::Rational::unknown();}diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cppindex a27d53a2..bd8c6cbd 100644--- a/tests/integration/LivePresentationTests.cpp+++ b/tests/integration/LivePresentationTests.cpp@@ -7,9 +7,49 @@#include <regex>#include <string>#include <vector>+#ifdef VEYRA_ENABLE_REMOTEPLAY+#include "veyra/remoteplay/ProfileStore.h"+#include "veyra/source/RemotePlaySource.h"+#endifusing namespace veyra;using namespace std::chrono_literals;int wmain(int argc,wchar_t**argv){+#ifdef VEYRA_ENABLE_REMOTEPLAY+ // Explicit opt-in; uses existing local pairing without changing it. Runs+ // the actual shared engine, audio endpoint, GPU admission and presenter.+ if(argc==3&&std::wstring_view(argv[1])==L"--last-paired-ps5"){+ const auto dir=remoteplay::profileDirectory();wchar_t name[80]{};+ GetPrivateProfileStringW(L"RemotePlay",L"LastProfile",L"",name,80,(dir/L"settings.ini").c_str());+ const std::wstring profile=name;if(profile.empty()||profile.find_first_of(L"/\\:")!=profile.npos)return 3;+ auto saved=remoteplay::loadProfile(dir/profile);if(!saved)return 4;+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);+ HWND window=CreateWindowExW(0,L"STATIC",L"PS5 timing regression",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);if(!window)return 5;+ engine::EngineController engine;engine.setVolume(0,true);+ engine::PlayerOptions options;options.nr=options.sr=options.fg=true;options.fgMultiplier=2;options.settings.videoSrQuality=2;+ source::RemotePlayConnectDesc request;request.request=std::move(*saved);request.request.video={1920,1080,60,80000,remoteplay::Codec::H264};request.decodeMode=source::RemotePlayConnectDesc::DecodeMode::Hardware;+ engine.openRemotePlay(window,std::move(request),options);+ const auto start=std::chrono::steady_clock::now();unsigned overloadSamples=0,overloadTimings=0;double early=-1,late=-1;uint64_t maxGenerated=0;bool failed=false;int lastSecond=-1;+ while(std::chrono::steady_clock::now()-start<120s){+ const int second=int(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now()-start).count());+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",second>=30&&second<38?L"35":nullptr);+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}+ const auto s=engine.snapshot();if(s.failed){failed=true;char message[1024]{};WideCharToMultiByte(CP_UTF8,0,s.status.c_str(),-1,message,sizeof(message),nullptr,nullptr);std::cout<<"ENGINE_FAILED "<<message<<std::endl;break;}+ maxGenerated=std::max(maxGenerated,s.generated);+ if(second>=33&&second<38){++overloadSamples;overloadTimings+=s.metrics.flow.gpuTiming[size_t(diagnostics::GpuStage::Nr)].mean.has_value();}+ if(second==25)early=s.captureAudio.compensationMs;+ if(second>=110)late=s.captureAudio.compensationMs;+ if(second!=lastSecond&&second%5==0){lastSecond=second;std::cout<<"PS5 t="<<second<<" presented="<<s.metrics.flow.presentSubmitFps<<" generated="<<s.generated<<" nrMs="<<s.metrics.flow.gpuTiming[size_t(diagnostics::GpuStage::Nr)].mean.value_or(-1)<<" audioDelay="<<s.captureAudio.compensationMs<<" pcm="<<s.captureAudio.bufferedMs<<" resets="<<s.captureAudio.resets<<std::endl;}+ std::this_thread::sleep_for(20ms);+ }+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);+ const auto final=engine.snapshot();engine.stop();+ const auto stopDeadline=std::chrono::steady_clock::now()+10s;while(!engine.idle()&&std::chrono::steady_clock::now()<stopDeadline)std::this_thread::sleep_for(10ms);+ const bool ok=!failed&&engine.idle()&&maxGenerated>100&&final.metrics.flow.validGeneratedFps>10&&overloadSamples>0&&overloadTimings*100>=overloadSamples*95&&early>=0&&late>=0&&late<150&&std::abs(late-early)<40;+ std::cout<<(ok?"PASS ":"FAIL ")<<"PS5 actual NR/SR/DLSS 2X, overload timings="<<overloadTimings<<'/'<<overloadSamples<<" earlyAudio="<<early<<" lateAudio="<<late<<" finalValidFgFps="<<final.metrics.flow.validGeneratedFps<<std::endl;+ DestroyWindow(window);CoUninitialize();return ok?0:1;+ }+#endifSetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--nr-first")==0||wcscmp(argv[3],L"--seek-stress")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--file-continuity")==0||wcscmp(argv[3],L"--file-fg-recovery")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);diff --git a/tests/remoteplay/CoreTests.cpp b/tests/remoteplay/CoreTests.cppindex 27efd270..756e742c 100644--- a/tests/remoteplay/CoreTests.cpp+++ b/tests/remoteplay/CoreTests.cpp@@ -6,6 +6,8 @@#include "veyra/remoteplay/PacketPump.h"#include "veyra/remoteplay/InputGate.h"#include "veyra/remoteplay/SessionInbox.h"+#include "veyra/engine/PresentationScheduler.h"+#include "veyra/engine/FgRecoveryBudget.h"#include <atomic>#include <chrono>#include <functional>@@ -62,6 +64,27 @@ TEST(sequence_multiple_wraps){Sequence16Extender x;for(std::uint64_t i=0;i<20000TEST(clock_common_origin){RemotePlayClock c;c.reset(1000000,60);auto v=c.video(123,1300000);CHECK(v&&v->pts100ns==300000);CHECK(c.audioPts(480,48000,1100000)==200000);CHECK(v->provenance==TimestampProvenance::LocalEstimated);}TEST(clock_cadence_no_cumulative_rounding){RemotePlayClock c;c.reset(0,60);for(std::uint64_t i=0;i<60000;++i){const auto time=static_cast<std::int64_t>(i*10000000/60);auto s=c.video(i,time);CHECK(s&&s->pts100ns==time);}}TEST(clock_gap_reanchors){RemotePlayClock c;c.reset(0,60);CHECK(c.video(0,0));auto s=c.video(60,10000000);CHECK(s&&s->discontinuity&&s->pts100ns==10000000);}+TEST(clock_long_session_drift_and_fg){+ for(unsigned fps:{30u,60u})for(int ppm:{-1400,1400}){+ RemotePlayClock c;c.reset(0,fps);+ veyra::engine::PresentationScheduler schedule;+ veyra::engine::FgRecoveryBudget budget;+ const int64_t interval=10000000/fps;+ schedule.reset(1,0,0,interval);+ int64_t previous=-1;unsigned admitted=0,measured=0;+ for(uint64_t i=0;i<fps*600u;++i){+ const auto base=int64_t(i*uint64_t(1000000+ppm)*10/fps);+ const auto jitter=i%97==11?20000:int64_t(i%7)*1000;+ const auto arrival=base+jitter;+ const auto stamp=c.video(i,arrival);+ CHECK(stamp&&!stamp->discontinuity&&stamp->pts100ns>previous);previous=stamp->pts100ns;+ budget.fgCost(2,arrival);budget.complete(12,true,false,arrival);+ const bool admittedNow=budget.admit(arrival+20000,schedule.deadline(stamp->pts100ns-interval/2),2,.5);+ if(i>fps*10u){CHECK(std::abs(stamp->pts100ns-base)<150000);++measured;admitted+=admittedNow;}+ }+ CHECK(admitted>measured*98/100);+ }+}TEST(clock_reject_invalid){RemotePlayClock c;CHECK(!c.video(0,0));THROWS(c.reset(0,120));THROWS(c.reset(-1,60));c.reset(10,60);CHECK(!c.video(0,9));CHECK(c.video(1,20));CHECK(!c.video(1,20));CHECK(!c.video(2,19));CHECK(!c.audioPts(0,0,10));CHECK(!c.audioPts(std::numeric_limits<std::uint64_t>::max(),8000,10));}TEST(queue_limits_validation){QueueLimits l;l.maxFrames=0;THROWS(VideoIngress{l});l={};l.maxConfigBytes=l.maxBytes+1;THROWS(VideoIngress{l});l={};l.maxAge100ns=0;THROWS(VideoIngress{l});}TEST(config_not_counted_as_picture){VideoIngress q;q.begin(1);CHECK(q.push(config(),0)==PushStatus::ConfigStored);CHECK(q.stats().accessUnits==0);CHECK(q.stats().depth==0);CHECK(!q.tryPop(0));}diff --git a/tests/remoteplay/ProductBoundaryTests.cpp b/tests/remoteplay/ProductBoundaryTests.cppindex 55142fd7..e42e84ec 100644--- a/tests/remoteplay/ProductBoundaryTests.cpp+++ b/tests/remoteplay/ProductBoundaryTests.cpp@@ -37,6 +37,7 @@ static void mailbox(){packet.sequence=2;packet.flags=0;s.publishDecoded(raw,packet,info);av_frame_free(&raw);const AVFrame* frame=nullptr;pipeline::FramePacket out;if(s.read(out,&frame)!=SourceReadStatus::Frame||!frame||out.sequence!=2||s.skipped()!=1||!pipeline::breaksHistory(out.flags))throw std::runtime_error("latest decoded mailbox");+ if(!pipeline::hasFrameFlag(out.flags,pipeline::FrameFlagBits::Drop)||pipeline::hasFrameFlag(out.flags,pipeline::FrameFlagBits::Discontinuity))throw std::runtime_error("decoded overwrite must be a soft Drop, not a clock discontinuity");if(s.read(out,&frame)!=SourceReadStatus::Waiting)throw std::runtime_error("mailbox replay");}};diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex bcae55e0..705e5ff7 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -14,9 +14,15 @@#include "veyra/engine/CfrTimeline.h"#include "veyra/Log.h"#include "veyra/sink/AudioFrameTimeline.h"+#include "veyra/sink/ArrivalClockMapping.h"int main(){using namespace veyra;int failures=0,checks=0;auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};+ sink::ArrivalClockMapping ingressClock;+ double mapping=0;+ for(int i=0;i<60000;++i)mapping=ingressClock.observe(1000+i*10.01+(i%13==5?4:0),i*10.0);+ check(std::abs(mapping-(1000+59999*.01))<2.1,"ten-minute audio ingress mapping ages oscillator drift instead of retaining startup minimum");+ ingressClock.reset();check(ingressClock.observe(100,0)==100,"audio discontinuity replaces prior ingress mapping");sink::AudioFrameTimeline pcmTime;check(pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Native,false,1,pipeline::SrTarget::Uhd4K,true).nr==pipeline::Extent{1920,1080},"NR-first preview uses source resolution");check(pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Native,true,1,pipeline::SrTarget::Uhd4K,true).nr==pipeline::Extent{3840,2160},"export ignores low latency preview order");@@ -97,6 +103,15 @@ int main(){check(captureTimeline.deadline(6000600000LL)<=6001030000LL,"unbuffered capture cannot accumulate source-clock drift");captureTimeline.reset(2,0,2000000,166667,true);check(captureTimeline.deadline(166667)==2333334,"switch to FG restores continuous source-PTS pacing and lookahead");+ engine::PresentationScheduler ps5Timeline;bool decodedPairFits=true;+ for(int64_t i=1;i<120;++i){+ const int64_t b=i*166667,decoded=1000000+b+(i%2?150000:20000);+ ps5Timeline.reset(1,b,decoded,166667);+ const auto deadline=ps5Timeline.deadline(b-83333);+ decodedPairFits&=engine::admitLiveFg(decoded+10000,deadline,1,12,.3);+ decodedPairFits&=!engine::admitLiveFg(decoded+400000,deadline,40,12,.3);+ }+ check(decodedPairFits,"PS5 decoder jitter does not spend FG budget; delayed enhancement still expires against the original decoded input deadline");check(!engine::admitLiveFg(1200000,1000000,0,std::nullopt,0),"warmup rejects already-expired FG before evaluate");check(engine::admitLiveFg(900000,1000000,0,std::nullopt,0),"warmup does not invent a measured completion estimate");check(!engine::admitLiveFg(900000,1000000,2,30.0,1),"predicted completion beyond deadline skips optional pair");@@ -144,6 +159,14 @@ int main(){delivered.identity.settingsRevision=2;deliveredTiming.gpuFrame(delivered,1000000);delivered.identity.settingsRevision=1;delivered.identity.epoch=2;deliveredTiming.gpuFrame(delivered,1000000);check(deliveredTiming.snapshot(2000000).gpuTiming[0].samples==2,"dequeued GPU frames each count once even with equal timestamps; old epoch and revision rejected");+ for(uint64_t epoch=2;epoch<80;++epoch){+ deliveredTiming.advanceHistory({epoch,1,epoch});+ delivered.identity={epoch-1,1,epoch};deliveredTiming.gpuFrame(delivered,2000000+int64_t(epoch)*1000);+ }+ check(deliveredTiming.snapshot(5000000).gpuTiming[0].samples==80,"overload history changes retain delayed GPU samples across consecutive mailbox drops");+ engine::FrameFlowWindow afterSeek(1,{80,1,80},6000000);+ afterSeek.gpuFrame(delivered,6000000);+ check(!afterSeek.snapshot(7000000).gpuTiming[0].mean,"hard reset rejects GPU samples from previous measurement window");diagnostics::GpuFrameTiming work{{1,1,1},{}};auto stamp=[&](diagnostics::GpuStage stage,uint64_t begin,uint64_t end){work.gpu[size_t(stage)]={diagnostics::SampleState::Measured,double(end-begin),begin,end,1000};};stamp(diagnostics::GpuStage::Color,0,2);