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

Reduce capture DLSS phase margin and verify against 1.4.2beta

Veyra Goal Agent23cc720675a9
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d8421fdd..428efdeb 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -666,6 +666,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_fg_presentation_tests PRIVATE veyra_engine)
add_executable(veyra_player_tracks_tests tests/integration/PlayerTracksTests.cpp)
add_executable(veyra_scheduling_chain_tests tests/integration/SchedulingChainTests.cpp)
+ add_executable(veyra_capture_latency_tests tests/integration/CaptureLatencyComparisonTests.cpp)
+ target_compile_features(veyra_capture_latency_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_capture_latency_tests PRIVATE /utf-8)
+ target_link_libraries(veyra_capture_latency_tests PRIVATE veyra_engine)
+ add_dependencies(veyra_capture_latency_tests veyra_shader_present_blit)
add_executable(veyra_presentation_pacing_tests tests/integration/PresentationPacingTests.cpp)
target_compile_features(veyra_presentation_pacing_tests PRIVATE cxx_std_20)
target_compile_options(veyra_presentation_pacing_tests PRIVATE /utf-8)
diff --git a/docs/CAPTURE_LATENCY_REDUCTION_2026-09-18.md b/docs/CAPTURE_LATENCY_REDUCTION_2026-09-18.md
new file mode 100644
index 00000000..abb05bdb
--- /dev/null
+++ b/docs/CAPTURE_LATENCY_REDUCTION_2026-09-18.md
@@ -0,0 +1,129 @@
+# 采集 DLSS 成对呈现延迟优化
+
+状态:本机历史版本同参数对照、候选构建与针对性回归完成;仅确认约 2ms 软件延迟收益,偶发长帧未解决,候选不代表全面验收。基准 `410061a`,存档 `checkpoint/pre-capture-latency-reduction-20260918`,沿用隔离分支 `codex/frame-pacing-20260918`,不合并或发布。
+
+## 依据与范围
+
+上一轮 VC-007PRO 4K30 NV12、NR 实时 1080p、DLSS 4X 实测原帧回调到呈现返回约 42.2ms;原帧就绪约 10.1ms,随后等待约 31.8ms。旧策略以源周期加基础 GPU 成本安排 B 的目标时刻。4X 的三张插值必须位于 A/B 之间且顺序呈现,不能将 B 提前插到它们前面冒充降延迟。
+
+本轮只优化物理采集的自有 DLSS 呈现相位。保留倍率、PTS、画质、音频和资源 fence;文件、导出、PS5 与 XeSS 提供方时序不变。
+
+## 实现
+
+从既有 CPU fence 观测取得每个已完成有效批次的 `max(ready_i - arrival_B + pts_B - pts_i)`。它是保持原子帧间隔时所需的 B 延后量;CPU 观测是保守上界,不冒充 GPU 时间戳。
+
+下一批提交前选择最近一秒、最多 64 批的 P95,加 1ms 唤醒余量。至少 8 个有效批次才开始缩短;每批缩短不超过 0.25ms 且不超过一个子帧间隔的 1/16,增加则立即跟随更保守的估计,最多恢复到旧策略。没有当前批次完成后重锚、隐藏降倍率、额外 fence wait 或丢帧抵债。
+
+设置变更与显式排空清除估计,预热/恢复批次不训练;过期样本回到旧策略,旧呈现 generation 不参与新估计。诊断环境变量 `VEYRA_TEST_LEGACY_CAPTURE_PHASE` 仅用于同构建基线对照。
+
+## 验收计划
+
+单测覆盖 2X/4X/6X、缺测、慢帧、样本老化、逐步前移和重置。实际编译产品和测试程序,先短测,再固定实卡配置各 120 秒对照旧/新关闭模式与低排队,检查延迟、实际提交间隔、丢帧、补帧受限和递增延迟。只有收益与节奏证据同时成立才保留。所有运行均不超过 300 秒。
+
+产物:构建沿用 `E:/项目/Veyra/build/frame-pacing-20260918`;本轮测试/日志分别为 `E:/项目/Veyra/tests/capture-latency-reduction-20260918`、`E:/项目/Veyra/logs/capture-latency-reduction-20260918`;临时目录沿用 `E:/项目/Veyra/tmp/frame-pacing-20260918`。不生成便携包。
+
+物理 HDMI/卡内部/USB 和显示扫描未测;场景由当前主机提供,不能把静态主界面当作快速游戏验收。
+
+## 同构建实卡对照
+
+固定 VC-007PRO 3840x2160 30fps NV12、NR 内部 1080p、DLSS 4X 输出 4K、SR 关闭、音频入口开启但输出静音,RTX 5070 / 616.56。每轮预热 10 秒再正式采样 120 秒。窗口 1280x760、显示器 2560x1440 / 100Hz、允许撕裂,与上一轮相同。旧/新使用同一二进制,仅旧组设置进程环境变量绕过相位估计。
+
+| 指标,毫秒 | 旧策略 / 关闭 | 新策略 / 关闭 | 新策略 / 低排队 |
+| --- | ---: | ---: | ---: |
+| 原帧回调到 Present 返回 P50 | 42.439 | 40.233 | 40.057 |
+| P95 | 42.788 | 40.857 | 40.427 |
+| P99 | 42.930 | 41.557 | 40.737 |
+| 最大 | 43.230 | 42.466 | 41.278 |
+
+同模式前后 P50 降低 2.206ms(5.20%);低排队相对新关闭的差别很小,不能解释为普适模式收益。三轮 NR/FG 始终激活,正式窗新增采集 dropped、FG skipped、FG expired、command slot wait 全为 0,实际约 29.97 回调/秒、119.88 次 Present 提交/秒。100Hz 面板不会完整显示每秒 120 张画面。
+
+旧/新关闭组的提交间隔 P01/P50/P95/P99 分别为 5.424/8.375/10.684/11.118ms 和 7.827/8.359/8.716/8.866ms;两组没有小于目标一半或大于目标 1.5 倍的间隔。新组首/末 30 秒延迟 P50 为 40.248/40.217ms,没有延迟积累。本轮观测到间隔波动缩小,不能推广为全部内容或机器都更平滑。
+
+预热阶段仍有 provider warmup/跳过,正式窗开头约 0.85 秒保留既有受限标签(样本约 0.7%),正式窗没有新增跳过。未将启动标签隐藏或统计清零。
+
+### 为什么没有省掉 32ms
+
+原帧就绪后等待约 32ms,其中大部分是 A/B 补帧按 PTS 顺序排布的时间。第一张补帧已经拥有独立的 GPU fence,无须等第二、第三张算完。新关闭组第一张补帧就绪观察 P50 为 13.104ms、呈现为 15.222ms;再排三段约 8.34ms 后才到原帧 B,约 40.23ms。直接提前显示 B 会破坏时序,不能算同质量、同倍率的优化。
+
+用户要求保持采集方案,继续对比加入帧同步前的真实 1.4.2beta。停止 60fps/MJPEG 替代试验,移除相应测试入口。上表的“旧策略”只是在新版本中关闭相位优化,不能当作历史版本对照。
+
+## 历史版本对照方法
+
+从 `checkpoint/pre-frame-pacing-20260918` / `6e69eeb` 创建 `codex/beta-latency-ab-20260918`,工作区 `E:/项目/Veyra/worktrees/beta-latency-ab-20260918`。将其 `src/`、`include/` 与原始 `Veyra-1.4.2beta-source.zip` 对比,220 个源码/头文件一致(仅统一 CRLF/LF)。历史引擎保持原样,只加入共同采样程序及 CMake 测试目标。
+
+两版编译同一 `CaptureLatencyComparisonTests.cpp`,复用相同 NR/FG/SR 原件与 NGX 配置,关闭逐帧详细日志。每轮预热 10 秒,正式 120 秒;固定 VC-007PRO 4K30 NV12、NR 内部 1080p、DLSS 4X、SR 关闭、WASAPI 采集且输出静音、1280x760 窗口、100Hz 显示器,默认同步关闭。通过旧版已存在的 snapshot 读取计时,每 50ms 采样,只保留原帧 Present 计数变化的快照。统计是**抽样快照分布**,不是全帧统计,也不是 HDMI 到屏幕。
+
+三组分别为历史 beta、新版同步关闭且绕过本轮相位优化、新版同步关闭且启用相位优化。最后重复历史 beta 检查顺序/负载漂移。此对照使用历史源码重新编译的产品引擎,不冒充原便携 GUI 二进制的外部端到端测量。
+
+历史构建:`E:/项目/Veyra/build/beta-latency-ab-20260918`;证据:`E:/项目/Veyra/tests/beta-latency-ab-20260918`;临时:`E:/项目/Veyra/tmp/beta-latency-ab-20260918`;构建日志仍在本轮 `logs/capture-latency-reduction-20260918`。第一次启动缺少新测试目标的 PresentBlit shader 依赖和本地 NGX 配置,失败证据保留于 `beta120`;补齐测试目标依赖与配置后重新开始,失败启动不参与正式结果。
+
+### 执行命令
+
+在历史工作区执行:
+
+```powershell
+./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/beta-latency-ab-20260918 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/beta-latency-ab-20260918 -DisplayVersion 1.4.2beta -Targets veyra_capture_latency_tests
+```
+
+在当前工作区执行:
+
+```powershell
+./scripts/build-isolated.ps1 -Root . -BuildDirectory E:/项目/Veyra/build/frame-pacing-20260918 -DependencyCache E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory E:/项目/Veyra/tmp/frame-pacing-20260918 -DisplayVersion 1.4.2beta -Targets veyra_capture_latency_tests,veyra_presentation_pacing_tests
+./scripts/test-capture-version-comparison.ps1 -Build E:/项目/Veyra/build/beta-latency-ab-20260918 -Name beta-a120
+./scripts/test-capture-version-comparison.ps1 -Build E:/项目/Veyra/build/frame-pacing-20260918 -Name current-off120 -LegacyPhase
+./scripts/test-capture-version-comparison.ps1 -Build E:/项目/Veyra/build/frame-pacing-20260918 -Name candidate120
+./scripts/test-capture-version-comparison.ps1 -Build E:/项目/Veyra/build/beta-latency-ab-20260918 -Name beta-b120
+python scripts/acceptance/analyze-capture-version-comparison.py E:/项目/Veyra/tests/beta-latency-ab-20260918 beta-a120 current-off120 candidate120 beta-b120
+```
+
+共同测试源 SHA256:`129F56C6EC5B705BBF95CC6C76D1E6BE3CDB474568A291D22905E56F9BC2B9B1`。源码审计和运行库身份分别保存于 `source-audit.json`、`runtime-identities.json`。旧引擎新增测试 target 包含独立 PresentBlit shader 依赖;NVIDIA/AMD/Intel 目录复用已批准运行库,根目录 FFmpeg DLL 沿用当前已打补丁依赖,本地 `ngx-local.json` 同源复制。没有读取或覆盖用户 UI 偏好。
+
+### 已完成恢复回归
+
+本轮 `recovery/result.txt`:实卡注入 80ms 工作延迟后报告 mailbox 丢帧,撤销后恢复 NR/完整补帧且没有持续积累延迟;暂停/恢复、2X→6X→4X 均恢复真实 NR/FG,正常停止。单测覆盖相位范围/过期/重置,`unit.log` PASS;修复契约 `contracts.log` 205 项 0 失败。RTX 30/40 未在本轮执行,不以 5070 结果代替。
+
+## 历史对照结果
+
+实际顺序为旧 beta A → 新版关闭且禁用相位优化 → 新版关闭且启用相位优化 → 旧 beta B。四轮均预热后正式运行 120 秒并 exit0,NR 与 DLSS4X 全程激活。软件回调约 29.97fps,提交读数中位数 120fps;不代表 100Hz 面板显示 120fps。
+
+| 抽样软件延迟,ms | 旧 beta A | 新版关闭/未优化 | 新版关闭/优化候选 | 旧 beta B |
+| --- | ---: | ---: | ---: | ---: |
+| P50 | 42.578 | 42.631 | 40.496 | 42.683 |
+| P95 | 43.412 | 43.503 | 42.829 | 43.392 |
+| P99 | 45.179 | 44.171 | 43.662 | 44.437 |
+| 最大 | 317.326 | 172.015 | 56.673 | 45.045 |
+| 首 30 秒中位数 | 42.523 | 42.480 | 40.574 | 42.485 |
+| 末 30 秒中位数 | 42.808 | 43.245 | 40.452 | 43.027 |
+| 正式窗新增采集丢帧 | 23 | 5 | 0 | 0 |
+| 正式窗新增 FG 提前跳过 | 3 | 0 | 0 | 0 |
+| 正式窗新增生成帧过期 | 18 | 5 | 8 | 4 |
+| command slot 等待 | 0 | 0 | 0 | 0 |
+
+结论:**新版关闭模式的软件延迟落在两次旧 beta 中位数之间,未测出新增帧同步带来的明显基础延迟回归。** 优化候选比新版未优化下降 2.135ms(5.01%),与本轮前一组逐帧日志对照的约 2.2ms 收益一致。没有改变分辨率、采集格式、倍率或 NR 档位。
+
+尾部不能省略:旧 beta A 正式窗约 87.5/87.8/92.4 秒出现丢帧与 276–317ms 延迟;旧 beta B 没有重现同级尖峰。新版未优化也有 172ms 抽样尖峰。优化候选仍过期 8 张生成帧,不能宣称消除了卡顿,也不能凭单轮更小的最大值断言稳定性修复成功。本机存在其他运行中的应用,未关闭用户进程;缺少系统级调度跟踪,无法把尖峰武断归因于应用、驱动或外部负载。受限状态的快照比例依次为 1.483%/0.719%/0.718%/0.719%,含正式窗开头继承的预热标签;各计数增量如实保留。
+
+### 阶段交叉核对
+
+以下是旧版已有 rolling-mean 指标的快照中位数,不是逐帧阶段总和,也不与前一组完整日志统计混用:
+
+| 阶段,ms | 旧 beta A | 新版关闭/未优化 | 优化候选 | 旧 beta B |
+| --- | ---: | ---: | ---: | ---: |
+| 回调到 read | 1.066 | 1.047 | 1.098 | 1.038 |
+| GPU 颜色/上传 | 0.193 | 0.196 | 0.193 | 0.195 |
+| GPU 光流 | 1.064 | 1.070 | 1.083 | 1.089 |
+| GPU NR | 6.270 | 6.297 | 6.296 | 6.292 |
+| GPU 残差合成 | 0.258 | 0.262 | 0.262 | 0.271 |
+| GPU FG 批次 | 5.836 | 5.904 | 6.137 | 6.138 |
+| 增强阶段区间 | 13.425 | 13.507 | 13.770 | 13.787 |
+| 每次呈现 CPU 服务 | 0.268 | 0.246 | 0.251 | 0.254 |
+
+NV12 为原生像素输入,无 H.264/HEVC/MJPEG 压缩解码。旧版已有 `capture-pair` 时序与 A/B 插帧排布,约 42ms 不由新选项凭空产生;优化来自减少保守呈现余量,GPU 运算没有更快。CPU/GPU 异步重叠、三张生成帧与原帧按 PTS 排布,这些阶段不可简单相加为物理总延迟。
+
+四轮日志均真实创建 NR Feature18 与 DLSSG,Create 返回 `0x1 seh=0`;DLSSG warm-up Evaluate `ok=1 result=0x1`,后续 NR/FG 计数持续增加,正式运行无 ERROR。详细 Evaluate 逐帧输出在本次历史 A/B 统一关闭,不能编造逐帧返回码证据;前述同构建详细日志保留。
+
+## 交付与边界
+
+产品引擎修改为 `LivePairLatency.h` 与 `EngineController.cpp`;单测/恢复场景、共用历史对照探针、CMake 目标、两个分析脚本和对照启动脚本负责验收,文档更新到 WORKLOG/CURRENT_STATUS。本轮产品构建记录 `build.log`,共同探针构建 `build-current-ab.log`、`build-beta-ab.log`、`build-beta-ab-repair.log`,结果 CSV/JSON、失败启动与四轮日志均保留。未新增 SDK/运行库到 Git;未打包、合并、推送或发布,原 beta 包未改。
+
+这里只完成采集 callback→软件 Present 返回比较;卡内部/USB 前半段、Present 后显示队列和扫描均未测,因此不能排除用户体感在未测阶段的差异。下一项唯一任务是对偶发长帧作同源可重复归因,并补齐实际屏幕端对照,不能用改采集格式替代。
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index 31a033c1..05c436e7 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -16,7 +16,9 @@
## 本轮开发
-帧同步已在隔离分支 `codex/frame-pacing-20260918` 实现并完成本机短测,基线存档 `6e69eeb`。入口:专业模式 → 运动 → 帧同步,默认关闭;低排队、均匀呈现、Reflex 实验和独立显示同步偏好可保存。无补帧文件测试减少了一帧提前缓存驻留;6X 提交吞吐保持 144fps,未证明显著降延迟或更平滑。Reflex 无补帧时真实调用 NVAPI,开启补帧时明确回退低排队并保留倍率;XeSS 继续由提供方调度。屏幕端到端延迟、30/40 实卡、真实采集、PS5、VRR 未验证,完整原计划尚未全部验收。详见[验收报告](FRAME_PACING_ACCEPTANCE_2026-09-18.md)。未合并 main、推送、发布或更新现有 1.4.2beta 包。
+帧同步已在隔离分支 `codex/frame-pacing-20260918` 实现并完成本机短测,基线存档 `6e69eeb`。入口:专业模式 → 运动 → 帧同步,默认关闭;低排队、均匀呈现、Reflex 实验和独立显示同步偏好可保存。无补帧文件测试减少了一帧提前缓存驻留;6X 提交吞吐保持 144fps,未证明显著降延迟或更平滑。Reflex 无补帧时真实调用 NVAPI,开启补帧时明确回退低排队并保留倍率;XeSS 继续由提供方调度。VC-007PRO 4K30 NV12、NR+DLSS4X 已完成四模式各 120 秒实卡测试,详见[采集阶段计时](CAPTURE_LATENCY_DLSS4X_2026-09-18.md)。屏幕端到端延迟、30/40 实卡、PS5、VRR 未验证,完整原计划尚未全部验收。其他验收见[帧同步报告](FRAME_PACING_ACCEPTANCE_2026-09-18.md)。未合并 main、推送、发布或更新现有 1.4.2beta 包。
+
+采集呈现相位优化及原始 1.4.2beta 引擎同参数对照见[延迟优化与历史对比](CAPTURE_LATENCY_REDUCTION_2026-09-18.md)。保持 4K30 NV12、NR、DLSS4X,不使用换格式或降低倍率解释收益。
RTX Video HDR 独立改动保留。用户已明确终止 NVIDIA FSR 4.1 实验并要求回退,不再执行此前 FSR4 施工和画质修复计划。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 3d0de87e..79bdd632 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 2026-09-18 原始 1.4.2beta 与帧同步版本同参数延迟对照
+
+用户明确保持 VC-007PRO 4K30 NV12、NR+DLSS4X,不接受换采集方案。停止 60fps/MJPEG 替代试验并移除其测试入口。历史基线为 `6e69eeb`,新建隔离分支/工作区 `codex/beta-latency-ab-20260918` / `E:/项目/Veyra/worktrees/beta-latency-ab-20260918`;其 src/include 共 220 文件与原始 beta 源码包一致,只新增共同采样程序和 CMake 目标,历史引擎不改。
+
+四轮各预热 10 秒、正式 120 秒,全部 exit0:旧 beta 两次中位数 42.578/42.683ms,新版关闭且禁用本轮优化 42.631ms,优化候选 40.496ms。未测出新同步代码在关闭状态下的明显软件延迟回归;相位优化约省 2.135ms(5.01%)。旧 beta 首轮最大 317ms、丢帧 23;新版未优化最大 172ms、丢帧 5;候选最大 56.673ms、无采集丢帧但仍过期 8 张生成帧;旧 beta 复测最大 45.045ms、过期 4 张。未将单轮峰值差冒充根因定位或稳定性根治。
+
+完整参数、执行命令、阶段耗时、返回码与限制见 [历史对照与优化报告](CAPTURE_LATENCY_REDUCTION_2026-09-18.md)。这是同一探针链接原始/当前引擎的重新编译比较,不是原便携 GUI 二进制或 HDMI→屏幕的物理延迟测试;50ms 快照抽样不冒充全帧统计。两版复用相同批准运行库,NR/DLSSG Create `0x1 seh=0`、FG warm-up Evaluate `ok=1 result=0x1`,正式四轮 NR/FG 全程激活、无 ERROR。
+
+本轮还完成先前同构建逐帧 A/B:42.439→40.233ms,低排队 40.057ms;该“旧策略”从未代表原 beta,已在报告明确纠正。相位优化只作用物理采集 DLSS、保留真实 PTS/倍率/fence。产品和测试构建成功,单测通过,契约 205 项 0 失败;真实采集 80ms 人为阻塞后恢复、暂停/恢复、2X→6X→4X 均通过。30/40 本轮未执行,显示扫描未测。
+
+产物:`E:/项目/Veyra/build/frame-pacing-20260918`、`build/beta-latency-ab-20260918`;证据 `tests/capture-latency-reduction-20260918`、`tests/beta-latency-ab-20260918`;日志 `logs/capture-latency-reduction-20260918`;临时 `tmp/frame-pacing-20260918`、`tmp/beta-latency-ab-20260918`。历史探针第一次缺本地 ngx 配置和 PresentBlit shader,修复 CMake 依赖/补齐同源配置后再跑,失败保留于 beta120。当前源码在 frame-pacing 隔离分支;存档点 `checkpoint/pre-capture-latency-reduction-20260918`。无新包或解压副本,无 SDK/运行库入 Git,不合并 main、不推送、不发布。下一项唯一任务:偶发长帧的可重复归因与屏幕端实测。
+
## 2026-09-18 VC-007PRO / NR / DLSS 4X 四模式两分钟实测
用户将本轮采集延迟对比从 XeSS 改为 DLSS 4X。沿用隔离分支 `codex/frame-pacing-20260918`、基准 `a471474`,增加采集 callback/read/graph/present 逐帧关联日志和 `capture-nr` 真机测试入口;产品同步算法未改。固定 VC-007PRO 3840x2160 30fps NV12、NR 实时 1080p、4K DLSS 4X、SR 关闭、允许撕裂,低排队/均匀呈现/Reflex 请求/关闭各 120 秒,预热 10 秒。Reflex+FG 实际回退低排队,不冒充原生 Reflex 测试。
diff --git a/include/veyra/engine/LivePairLatency.h b/include/veyra/engine/LivePairLatency.h
new file mode 100644
index 00000000..363a6dcb
--- /dev/null
+++ b/include/veyra/engine/LivePairLatency.h
@@ -0,0 +1,35 @@
+#pragma once
+#include <algorithm>
+#include <cstdint>
+#include <deque>
+#include <vector>
+
+namespace veyra::engine {
+// Observed readiness of earlier pairs bounds the phase of the next pair.
+// Values are host-clock 100 ns; source PTS differences only supply spacing.
+class LivePairLatency {
+ struct Sample { int64_t time, delay; };
+ std::deque<Sample> samples_;
+ int64_t selected_=0;
+public:
+ void reset(){samples_.clear();selected_=0;}
+ void observe(int64_t now,int64_t requiredDelay){
+ if(requiredDelay<=0||requiredDelay>20000000)return;
+ while(!samples_.empty()&&(samples_.size()>=64||samples_.front().time<now-10000000))samples_.pop_front();
+ samples_.push_back({now,requiredDelay});
+ }
+ int64_t select(int64_t now,int64_t legacyDelay,int64_t interval,unsigned multiplier){
+ std::vector<int64_t> current;
+ for(const auto& sample:samples_)if(sample.time>=now-10000000)current.push_back(sample.delay);
+ if(current.size()<8||interval<=0||multiplier<2){selected_=legacyDelay;return selected_;}
+ const auto index=(current.size()*95+99)/100-1;
+ std::nth_element(current.begin(),current.begin()+index,current.end());
+ // One millisecond covers polling/wakeup jitter. Never add latency above
+ // the existing policy, or compress phase by more than 0.25 ms per pair.
+ const auto target=std::min(legacyDelay,current[index]+10000);
+ const auto step=std::min<int64_t>(2500,interval/multiplier/16);
+ selected_=std::clamp(selected_?selected_-step:legacyDelay,target,legacyDelay);
+ return selected_;
+ }
+};
+}
diff --git a/scripts/acceptance/analyze-capture-latency.py b/scripts/acceptance/analyze-capture-latency.py
index c0f71451..c1a121d9 100644
--- a/scripts/acceptance/analyze-capture-latency.py
+++ b/scripts/acceptance/analyze-capture-latency.py
@@ -15,7 +15,8 @@ def stats(values):
i = (len(values) - 1) * p
lo = int(i)
return values[lo] + (values[min(lo + 1, len(values) - 1)] - values[lo]) * (i - lo)
- return {"n": len(values), "mean": sum(values) / len(values),
+ return {"n": len(values), "mean": sum(values) / len(values), "min": values[0],
+ "p01": percentile(.01), "p05": percentile(.05),
"p50": percentile(.5), "p95": percentile(.95),
"p99": percentile(.99), "max": values[-1]}
@@ -73,6 +74,8 @@ def analyze(directory):
if x["ready"]:
ms(kind + "_callback_to_ready_observed", x["arrival"], x["ready"])
ms(kind + "_ready_to_present_begin", x["ready"], x["begin"])
+ ms(f"subframe_{x['subframe']}_callback_to_ready", x["arrival"], x["ready"])
+ ms(f"subframe_{x['subframe']}_callback_to_present", x["arrival"], x["end"])
if x["generated"] and x["arrivalA"]:
ms("generated_a_callback_to_present_return", x["arrivalA"], x["end"])
ms("generated_ab_arrival_gap", x["arrivalA"], x["arrival"])
@@ -89,6 +92,8 @@ def analyze(directory):
rows.append({**x, "softwareLatencyMs": (x["end"] - x["arrival"]) / 10_000})
for a, b in zip(presented, presented[1:]):
ms("present_interval", a["end"], b["end"])
+ multiplier = int(re.search(r"FG=DLSS(\d+)X", result)[1])
+ nominal_interval = stats(values["callback_interval"])["p50"] / multiplier
gpu_groups = defaultdict(list)
stages = {0: "upload_color", 1: "sr", 2: "flow", 3: "nr", 4: "residual",
5: "fg1", 6: "fg2", 7: "fg3", 8: "fg4", 9: "fg5",
@@ -112,6 +117,9 @@ def analyze(directory):
counters = {key: int(last[key]) - int(first[key]) for key in
["received", "dropped", "processed", "generated", "realPresented", "generatedPresented", "fgSkipped", "fgExpired"]}
counters.update(limitedFraction=sum(int(x["limited"]) for x in snapshots) / len(snapshots),
+ shortIntervals=sum(x < nominal_interval * .5 for x in values["present_interval"]),
+ longIntervals=sum(x > nominal_interval * 1.5 for x in values["present_interval"]),
+ nominalPresentIntervalMs=nominal_interval,
nrAllActive=all(int(x["nr"]) for x in snapshots),
fgAllActive=all(int(x["fg"]) for x in snapshots),
effectiveModes=sorted({int(x["effective"]) for x in snapshots}),
diff --git a/scripts/acceptance/analyze-capture-version-comparison.py b/scripts/acceptance/analyze-capture-version-comparison.py
new file mode 100644
index 00000000..1f8ace4c
--- /dev/null
+++ b/scripts/acceptance/analyze-capture-version-comparison.py
@@ -0,0 +1,58 @@
+"""Compare identical 50 ms snapshot probes; these are not every-frame traces."""
+import argparse
+import csv
+import json
+from pathlib import Path
+from statistics import mean, median
+
+
+def percentile(values, p):
+ values = sorted(values)
+ position = (len(values) - 1) * p
+ lo = int(position)
+ return values[lo] + (values[min(lo + 1, len(values) - 1)] - values[lo]) * (position - lo)
+
+
+def analyze(directory):
+ with (directory / "snapshots.csv").open(encoding="utf-8") as stream:
+ samples = [{key: float(value) for key, value in row.items()} for row in csv.DictReader(stream)]
+ if not samples:
+ raise ValueError(f"No samples: {directory}")
+ # Keep only snapshots with a new real Present counter. This avoids weighting
+ # a stalled/stale snapshot as if the same frame had been presented again.
+ rows = []
+ previous = None
+ for row in samples:
+ if row["realPresented"] != previous:
+ rows.append(row)
+ previous = row["realPresented"]
+ result = {"snapshots": len(samples), "distinctRealPresentSnapshots": len(rows),
+ "secondsBetweenSnapshots": samples[-1]["wall"] - samples[0]["wall"],
+ "continuouslyActive4X": all(r["nr"] == 1 and r["fg"] == 1 and r["multiplier"] == 4 for r in samples),
+ "limitedSnapshotPercent": 100 * mean(r["limited"] for r in samples)}
+ result["deltas"] = {key: samples[-1][key] - samples[0][key] for key in
+ ("received", "dropped", "generated", "realPresented", "generatedPresented", "fgSkipped", "fgExpired", "slotWaits")}
+ values = [r["ageMs"] for r in rows]
+ result["callbackToRealPresentReturnMs"] = {
+ "p50": median(values), "p95": percentile(values, .95), "p99": percentile(values, .99), "max": max(values),
+ "first30sMedian": median(r["ageMs"] for r in rows if r["wall"] < 30),
+ "last30sMedian": median(r["ageMs"] for r in rows if r["wall"] > samples[-1]["wall"] - 30)}
+ result["medianSnapshotMetrics"] = {key: median(r[key] for r in rows) for key in
+ ("callbackFps", "submitFps", "readAgeMs", "readyMeanMs", "deadlineMeanMs", "presentMeanMs",
+ "colorMeanMs", "flowMeanMs", "nrMeanMs", "residualMeanMs", "fgMeanMs", "graphMeanMs")}
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("root", type=Path)
+ parser.add_argument("names", nargs="+")
+ args = parser.parse_args()
+ results = {name: analyze(args.root / name) for name in args.names}
+ text = json.dumps(results, indent=2)
+ (args.root / "comparison.json").write_text(text + "\n", encoding="utf-8")
+ print(text)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-capture-version-comparison.ps1 b/scripts/test-capture-version-comparison.ps1
new file mode 100644
index 00000000..8a529e51
--- /dev/null
+++ b/scripts/test-capture-version-comparison.ps1
@@ -0,0 +1,24 @@
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory)][string]$Build,
+ [Parameter(Mandatory)][string]$Name,
+ [string]$Output='E:/项目/Veyra/tests/beta-latency-ab-20260918',
+ [int]$Seconds=120,
+ [switch]$LegacyPhase
+)
+$ErrorActionPreference='Stop'
+if($Seconds -lt 3 -or $Seconds -gt 120){throw 'Seconds must be 3..120'}
+$dir=Join-Path $Output $Name
+New-Item -ItemType Directory -Force $dir | Out-Null
+$env:TEMP='E:/项目/Veyra/tmp/beta-latency-ab-20260918'
+$env:TMP=$env:TEMP
+New-Item -ItemType Directory -Force $env:TEMP | Out-Null
+$env:VEYRA_TEST_LEGACY_CAPTURE_PHASE=if($LegacyPhase){'1'}else{$null}
+$exe=Join-Path $Build 'veyra_capture_latency_tests.exe'
+[ordered]@{build=$Build;name=$Name;seconds=$Seconds;legacyPhase=[bool]$LegacyPhase;executableSha256=(Get-FileHash -LiteralPath $exe).Hash} |
+ ConvertTo-Json | Set-Content -LiteralPath (Join-Path $dir 'run.json') -Encoding utf8
+$test=Start-Process -FilePath $exe -ArgumentList @(('"' + $dir + '"'),$Seconds) -WorkingDirectory $Build -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $dir 'result.txt') -RedirectStandardError (Join-Path $dir 'stderr.txt')
+$handle=$test.Handle
+if(!$test.WaitForExit(200000)){$test.Kill();throw 'Historical capture comparison exceeded 200 seconds'}
+Get-Content -LiteralPath (Join-Path $dir 'result.txt')
+if($test.ExitCode -ne 0){throw "Comparison failed: $($test.ExitCode)"}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index bc08c4b8..92e316b6 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -12,6 +12,7 @@
#include "veyra/engine/FrameFlowWindow.h"
#include "veyra/engine/LiveFgAdmission.h"
#include "veyra/engine/FgRecoveryBudget.h"
+#include "veyra/engine/LivePairLatency.h"
#include "veyra/engine/RealtimePreviewScheduling.h"
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/source/MediaFileSource.h"
@@ -472,12 +473,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
TimingWindow livePresent{std::chrono::seconds(1)};
TimingWindow livePresentService{std::chrono::seconds(1)};
FgRecoveryBudget fgBudget;uint64_t fgBudgetRevision=options.settings.revision;
+ LivePairLatency pairLatency;
+ const bool adaptiveCapturePhase=physicalCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_CAPTURE_PHASE",nullptr,0)==0;
int64_t nextFgAdmissionLog=0;
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;
struct CompletionWatch {
uint64_t reflexFrame=0;
+ int64_t captureArrival=0;
+ uint64_t presentationGeneration=0;
pipeline::EnhanceGraph::FrameOutputs output;
std::shared_ptr<FrameFlowWindow> flow;
Clock::time_point processStart;
@@ -564,6 +569,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
traceFrame(diagnostics::TraceKind::Ready,batch.batch.identity,batch.batch.batchId,std::max(batch.videoFenceValue,batch.genFenceValue),batch.batch.b100ns,invalid,valid,elapsedMs(watch.processStart));
if(watch.real)completedProcessing(batch.batch.identity);
if(batch.batch.identity.settingsRevision==fgBudgetRevision)fgBudget.complete(watch.gpuExecutionMs,batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery,host100ns(),watch.fgExecutionMs);
+ if(adaptiveCapturePhase&&watch.captureArrival>0&&valid==options.fgMultiplier-1&&
+ batch.hasGenerated&&!batch.historyReset&&!batch.fgRecovery&&
+ batch.batch.identity.settingsRevision==fgBudgetRevision&&watch.presentationGeneration==presentationGeneration.load()){
+ int64_t requiredDelay=0;
+ const auto observed=host100ns();
+ for(unsigned i=0;i<batch.batch.count;++i){const auto& item=batch.batch.frames[i];
+ // resolveGeneration can observe a fence after the
+ // first poll. Its current host time is a safe upper bound.
+ const auto ready=watch.frameReadyObserved[i]?watch.frameReadyObserved[i]:observed;
+ requiredDelay=std::max(requiredDelay,ready-watch.captureArrival+batch.batch.b100ns-item.pts100ns);
+ }
+ pairLatency.observe(observed,requiredDelay);
+ }
completeReset(batch.batch.identity);
watch.readyObserved=Clock::now();watch.ready=true;it=pendingCompletions.erase(it);
}
@@ -597,7 +615,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
{std::lock_guard lock(mutex_);snapshot_.presentationEffective=presentationEffective;snapshot_.presentationRevision=revision;snapshot_.presentationStatus=message;}
veyra::log::info("pacing",std::format("revision={} requested={}/{}/{} effective={}/{}/{}",revision,requested.enabled,unsigned(requested.mode),unsigned(requested.display),presentationEffective.enabled,unsigned(presentationEffective.mode),unsigned(presentationEffective.display)));
};
- auto drainLivePresentation=[&]{cadence.reset();if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}};
+ auto drainLivePresentation=[&]{cadence.reset();if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}pairLatency.reset();};
auto advanceLive=[&]{applyPresentation();if(liveScheduler){pollCompletions();if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){liveScheduler->cancel();cadence.reset();}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,metricsWindowEpoch=0,statsSourceBase=0;
@@ -1007,10 +1025,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;
if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
pipeline::EnhanceGraph::FgAdmission admitFg;
- if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();fgBudgetRevision=options.settings.revision;}
+ if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();pairLatency.reset();fgBudgetRevision=options.settings.revision;}
const auto liveInterval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
const auto processingAllowance=isCapture&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)?
fgBudget.processingAllowance(host100ns(),liveInterval):0;
+ const auto legacyPairDelay=liveInterval+processingAllowance;
+ const auto pairDelay=adaptiveCapturePhase&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)?
+ pairLatency.select(host100ns(),legacyPairDelay,liveInterval,options.fgMultiplier):legacyPairDelay;
// DLSS can reseed after a skipped pair. XeSS
// owns generation inside its presenter and has no graph admission.
if(isCapture&&!rereadCached&&useLiveFgAdmission&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)){
@@ -1021,7 +1042,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// input pair before enhancement, so a 59.94-vs-60Hz
// mismatch cannot accumulate into a stale deadline.
// Never extend it based on processing/ready completion.
- if(pairAnchoredLive)liveTimeline.resetPair(batch.identity.epoch,batch.b100ns,liveInputReady,liveInterval+processingAllowance);
+ if(pairAnchoredLive)liveTimeline.resetPair(batch.identity.epoch,batch.b100ns,liveInputReady,pairDelay);
else if(!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;
@@ -1155,7 +1176,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// clock. Physical capture without FG presents as soon as ready.
const bool paceSourcePts=options.fg||!physicalCapture;
if(!liveTimeline.anchored(out.batch.identity.epoch)||(pairPacing&&frames==0))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,pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):paceSourcePts?"source-pts":"capture-ready"));
- if(pairPacing||isRemote)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns+processingAllowance:0,paceSourcePts);
+ if(pairPacing||isRemote)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?pairDelay:0,paceSourcePts);
else if(!liveTimeline.anchored(out.batch.identity.epoch))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;}
@@ -1165,6 +1186,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto timeline=liveTimeline;
const uint64_t jobGeneration=presentationGeneration.load();
auto watch=std::make_shared<CompletionWatch>();watch->output=out;watch->flow=frameFlow;watch->processStart=processStart;watch->real=!rereadCached;
+ watch->captureArrival=captureArrival;watch->presentationGeneration=jobGeneration;
watch->reflexFrame=currentReflexFrame;
pendingCompletions.push_back(watch);
struct LiveStepState {
diff --git a/tests/integration/CaptureLatencyComparisonTests.cpp b/tests/integration/CaptureLatencyComparisonTests.cpp
new file mode 100644
index 00000000..e9232158
--- /dev/null
+++ b/tests/integration/CaptureLatencyComparisonTests.cpp
@@ -0,0 +1,109 @@
+#include "veyra/engine/EngineController.h"
+#include "veyra/Log.h"
+#include "veyra/source/CaptureCardSource.h"
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <iomanip>
+#include <iostream>
+#include <thread>
+
+int wmain(int argc, wchar_t** argv) {
+ using namespace veyra::engine;
+ using Clock = std::chrono::steady_clock;
+ if (argc != 3) return 2;
+ const int seconds = _wtoi(argv[2]);
+ if (seconds < 3 || seconds > 120) return 2;
+ const std::filesystem::path dir = argv[1];
+ std::filesystem::create_directories(dir);
+ SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS", L"0");
+ veyra::Logger::instance().openFile((dir / L"engine.log").wstring());
+ veyra::Logger::instance().setConsoleEnabled(false);
+ if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return 2;
+ const auto devices = veyra::source::CaptureCardSource::deviceDetails();
+ const auto device = std::find_if(devices.begin(), devices.end(), [](const auto& d) { return d.name == L"VC-007PRO"; });
+ if (device == devices.end()) { std::cout << "FAIL VC-007PRO missing" << std::endl; return 3; }
+ const auto formats = veyra::source::CaptureCardSource::formatsByPath(device->path);
+ const auto format = std::find_if(formats.begin(), formats.end(), [](const auto& f) {
+ return f.width == 3840 && f.height == 2160 && std::abs(f.fps - 30) < .01 && f.label.find(L"NV12") != std::wstring::npos;
+ });
+ if (format == formats.end()) { std::cout << "FAIL 4K30 NV12 missing" << std::endl; return 3; }
+ const auto audios = veyra::source::CaptureCardSource::deviceDetails(true);
+ const auto audio = std::find_if(audios.begin(), audios.end(), [](const auto& a) {
+ return a.wasapi && a.name.find(L"HDMI (VC-007PRO)") != std::wstring::npos;
+ });
+ if (audio == audios.end()) { std::cout << "FAIL identical WASAPI input unavailable" << std::endl; return 3; }
+ const auto path = veyra::source::CaptureCardSource::makeCapturePath(unsigned(device - devices.begin()), *device,
+ format->index, veyra::source::kCaptureAudioWasapi, &*audio);
+ HWND window = CreateWindowExW(0, L"STATIC", L"Veyra historical capture comparison", WS_OVERLAPPEDWINDOW | WS_VISIBLE,
+ 40, 40, 1280, 760, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
+ if (!window) return 2;
+ MONITORINFOEXW monitor{}; monitor.cbSize = sizeof(monitor);
+ GetMonitorInfoW(MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST), &monitor);
+ DEVMODEW dm{}; dm.dmSize = sizeof(dm); EnumDisplaySettingsW(monitor.szDevice, ENUM_CURRENT_SETTINGS, &dm);
+ std::cout << "capture=VC-007PRO input=3840x2160 fps=" << format->fps << " NV12 formatIndex=" << format->index
+ << " audio=WASAPI-muted NR=realtime1080 FG=DLSS4X SR=off sync=default-off window=1280x760 display="
+ << dm.dmPelsWidth << 'x' << dm.dmPelsHeight << '@' << dm.dmDisplayFrequency << std::endl;
+ int failures = 0;
+ auto check = [&](bool ok, const char* label) { std::cout << (ok ? "PASS " : "FAIL ") << label << std::endl; failures += !ok; };
+ auto pump = [] { MSG msg; while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } };
+ {
+ EngineController engine;
+ engine.setVolume(0, true);
+ EnhancementSettings settings; settings.nr = true; settings.sr = false; settings.multiplier = 4;
+ engine.open(window, path, PlayerOptions::from(settings));
+ auto wait = [&](auto predicate, int ms) {
+ const auto until = Clock::now() + std::chrono::milliseconds(ms);
+ while (Clock::now() < until) {
+ pump(); const auto s = engine.snapshot();
+ if (s.failed) return false;
+ if (predicate(s)) return true;
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ }
+ return false;
+ };
+ const bool started = wait([](const auto& s) { return s.frames > 10 && s.nrActive && s.fgActive; }, 25000);
+ check(started, "first frames with NR and DLSS");
+ const auto warm = Clock::now();
+ const bool warmed = started && wait([&](const auto& s) {
+ return Clock::now() - warm >= std::chrono::seconds(10) && s.nrActive && s.fgActive && s.applied.multiplier == 4;
+ }, 20000);
+ check(warmed, "ten second warmup");
+ if (warmed) {
+ std::ofstream csv(dir / L"snapshots.csv");
+ csv << std::setprecision(10);
+ csv << "wall,frames,received,dropped,generated,nr,fg,multiplier,limited,callbackFps,submitFps,ageMs,ageP95,readAgeMs,realPresented,generatedPresented,fgSkipped,fgExpired,slotWaits,readyMeanMs,deadlineMeanMs,presentMeanMs,colorMeanMs,flowMeanMs,nrMeanMs,residualMeanMs,fgMeanMs,graphMeanMs\n";
+ const auto first = engine.snapshot();
+ auto last = first;
+ const auto start = Clock::now();
+ bool active = true;
+ while (Clock::now() - start < std::chrono::seconds(seconds) && !last.failed) {
+ pump(); last = engine.snapshot();
+ const auto& flow = last.metrics.flow; const auto& c = flow.counters;
+ active = active && last.nrActive && last.fgActive && last.applied.multiplier == 4 && !last.srActive;
+ auto cpu = [&](veyra::diagnostics::CpuStage stage) { return flow.cpuTiming[size_t(stage)].mean.value_or(-1); };
+ auto gpu = [&](veyra::diagnostics::GpuStage stage) { return flow.gpuTiming[size_t(stage)].mean.value_or(-1); };
+ using C = veyra::diagnostics::CpuStage; using G = veyra::diagnostics::GpuStage;
+ csv << std::chrono::duration<double>(Clock::now() - start).count() << ',' << last.frames << ',' << last.captureReceived
+ << ',' << last.captureDropped << ',' << last.generated << ',' << last.nrActive << ',' << last.fgActive
+ << ',' << last.applied.multiplier << ',' << last.fgBudgetLimited << ',' << last.captureFps << ',' << last.submissionFps.value_or(0)
+ << ',' << last.captureAgeMs << ',' << last.captureAgeP95Ms << ',' << last.captureReadAgeMs << ',' << c.realPresented
+ << ',' << c.generatedPresented << ',' << c.fgSkippedBeforeEval << ',' << c.generatedExpiredAfterEval << ',' << flow.slotReuseWaitCount
+ << ',' << cpu(C::ReadyWait) << ',' << cpu(C::DeadlineWait) << ',' << cpu(C::Present)
+ << ',' << gpu(G::Color) << ',' << gpu(G::Flow) << ',' << gpu(G::Nr) << ',' << gpu(G::Residual)
+ << ',' << gpu(G::FgBatch) << ',' << flow.enhancementProcessing.mean.value_or(-1) << '\n';
+ std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ }
+ const double elapsed = std::chrono::duration<double>(Clock::now() - start).count();
+ std::cout << "elapsed=" << elapsed << " receivedDelta=" << last.captureReceived - first.captureReceived
+ << " droppedDelta=" << last.captureDropped - first.captureDropped << " nrDelta=" << last.nrEvaluated - first.nrEvaluated
+ << " generatedDelta=" << last.generated - first.generated << " realPresentedDelta="
+ << last.metrics.flow.counters.realPresented - first.metrics.flow.counters.realPresented << std::endl;
+ check(!last.failed && elapsed >= seconds && last.frames > first.frames + 10, "full measurement");
+ check(active && last.nrEvaluated > first.nrEvaluated && last.generated > first.generated, "NR and DLSS4X continuously active");
+ }
+ engine.stop(); check(wait([&](const auto&) { return engine.idle(); }, 15000), "clean stop");
+ }
+ DestroyWindow(window); CoUninitialize();
+ return failures ? 1 : 0;
+}
diff --git a/tests/integration/PresentationPacingTests.cpp b/tests/integration/PresentationPacingTests.cpp
index 1022cc82..2588b231 100644
--- a/tests/integration/PresentationPacingTests.cpp
+++ b/tests/integration/PresentationPacingTests.cpp
@@ -18,20 +18,21 @@ int wmain(int argc,wchar_t** argv){
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
veyra::Logger::instance().openFile((dir/L"engine.log").wstring());veyra::Logger::instance().setConsoleEnabled(false);
if(FAILED(CoInitializeEx(nullptr,COINIT_MULTITHREADED)))return 2;
- const bool physical=scenario==L"capture-nr";
+ const bool physical=scenario==L"capture-nr"||scenario==L"capture-nr-recovery";
+ if(physical&&(multiplier<2||multiplier>6))return 2;
std::wstring sourcePath=argv[1];
if(physical){
const auto devices=veyra::source::CaptureCardSource::deviceDetails();
const auto device=std::find_if(devices.begin(),devices.end(),[](const auto& d){return d.name==L"VC-007PRO";});
if(device==devices.end()){std::cout<<"FAIL VC-007PRO missing"<<std::endl;return 3;}
const auto formats=veyra::source::CaptureCardSource::formatsByPath(device->path);
- const auto format=std::find_if(formats.begin(),formats.end(),[](const auto& f){return f.width==3840&&f.height==2160&&std::abs(f.fps-30)<.01&&f.label.find(L"NV12")!=std::wstring::npos;});
+ const auto format=std::find_if(formats.begin(),formats.end(),[&](const auto& f){return f.width==3840&&f.height==2160&&std::abs(f.fps-30)<.01&&f.label.find(L"NV12")!=std::wstring::npos;});
if(format==formats.end()){std::cout<<"FAIL exact 3840x2160 30fps NV12 format missing"<<std::endl;return 3;}
const auto audios=veyra::source::CaptureCardSource::deviceDetails(true);
const auto audio=std::find_if(audios.begin(),audios.end(),[](const auto& a){return a.wasapi&&a.name.find(L"HDMI (VC-007PRO)")!=std::wstring::npos;});
const int audioMode=audio!=audios.end()?veyra::source::kCaptureAudioWasapi:veyra::source::kCaptureAudioDisabled;
sourcePath=veyra::source::CaptureCardSource::makeCapturePath(unsigned(device-devices.begin()),*device,format->index,audioMode,audio!=audios.end()?&*audio:nullptr);
- std::cout<<"capture=VC-007PRO input=3840x2160 fps="<<format->fps<<" formatIndex="<<format->index<<" audioMode="<<audioMode<<" NR=realtime1080 FG=DLSS4X SR=off"<<std::endl;
+ std::cout<<"capture=VC-007PRO input=3840x2160 fps="<<format->fps<<" inputFormat=NV12 formatIndex="<<format->index<<" audioMode="<<audioMode<<" NR=realtime1080 FG=DLSS"<<multiplier<<"X SR=off"<<std::endl;
}
HWND window=CreateWindowExW(0,L"STATIC",L"Veyra pacing acceptance",WS_OVERLAPPEDWINDOW|WS_VISIBLE,40,40,1280,760,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
if(!window)return 2;
@@ -44,7 +45,7 @@ int wmain(int argc,wchar_t** argv){
PresentationSettings p{mode>=0,PacingMode(std::max(0,mode)),DisplaySync(display)};engine.requestPresentation(p);
EnhancementSettings effects;effects.multiplier=unsigned(multiplier);if(scenario==L"xess")effects.frameGenerationBackend=FrameGenerationBackend::XeSS;
if(scenario==L"effects"){effects.nr=true;effects.sr=true;effects.srTarget=veyra::pipeline::SrTarget::Qhd;}
- if(physical){effects.nr=true;effects.sr=false;effects.multiplier=4;}
+ if(physical){effects.nr=true;effects.sr=false;}
auto options=PlayerOptions::from(effects);options.captureReplayForTest=scenario==L"replay";
engine.open(window,sourcePath,options);
auto pump=[] {MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}};
@@ -94,6 +95,24 @@ int wmain(int argc,wchar_t** argv){
SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
before=engine.snapshot();check(wait([&](auto& s){return s.frames>before.frames+20;}),"recover after overload");
}
+ if(scenario==L"capture-nr-recovery"){
+ auto before=engine.snapshot();
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"80");
+ const auto overloadStart=Clock::now();
+ check(wait([&](auto& s){return Clock::now()-overloadStart>std::chrono::seconds(3)&&s.frames>before.frames+5;}),"capture progresses during injected 80ms work");
+ check(engine.snapshot().captureDropped>before.captureDropped,"capture overload reports mailbox drops");
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
+ const auto recoveryStart=Clock::now();
+ check(wait([&](auto& s){return Clock::now()-recoveryStart>std::chrono::seconds(12)&&s.fgActive&&s.nrActive&&!s.fgBudgetLimited&&s.captureAgeP95Ms<80;},20000),"capture recovers full FG without accumulating latency");
+ engine.pause(true);check(wait([](auto& s){return s.transport==TransportState::Paused;}),"capture pause");
+ engine.pause(false);before=engine.snapshot();
+ check(wait([&](auto& s){return s.frames>before.frames+30&&s.fgActive&&s.nrActive;}),"capture resume restores NR and FG");
+ for(const unsigned factor:{2u,6u,unsigned(multiplier)}){
+ effects.multiplier=factor;check(engine.requestSettings(effects),"capture multiplier request accepted");
+ const auto changed=Clock::now();
+ check(wait([&](auto& s){return Clock::now()-changed>std::chrono::seconds(3)&&s.applied.multiplier==factor&&s.fgActive&&s.nrActive;}),"capture multiplier applied with active NR and FG");
+ }
+ }
engine.stop();check(wait([&](auto&){return engine.idle();}),"clean stop");
}
DestroyWindow(window);CoUninitialize();return failures?1:0;
diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cpp
index cedd4a81..ddddfdaa 100644
--- a/tests/unit/LiveGpuSchedulerTests.cpp
+++ b/tests/unit/LiveGpuSchedulerTests.cpp
@@ -1,6 +1,7 @@
#include "veyra/engine/LiveGpuScheduler.h"
#include "veyra/engine/TimingWindow.h"
#include "veyra/engine/FgRecoveryBudget.h"
+#include "veyra/engine/LivePairLatency.h"
#include <iostream>
#include <memory>
#include <atomic>
@@ -71,5 +72,27 @@ int main(){
budget.complete(std::nullopt,true,false,36000000);
check(!budget.predicted(36000000),"missing GPU timing cannot retain a stale CPU polling cost");
check(!budget.admit(36000000,35800000,0,0),"unknown cost still rejects expired presentation deadlines");
+ veyra::engine::LivePairLatency phase;
+ check(phase.select(10000000,420000,333333,4)==420000,"unknown live readiness keeps legacy phase");
+ for(int i=0;i<8;++i)phase.observe(10000000+i,370000);
+ check(phase.select(10000008,420000,333333,4)==417500,"phase advance is gradual rather than a burst");
+ for(int i=0;i<32;++i)phase.select(10000100+i,420000,333333,4);
+ check(phase.select(10000200,420000,333333,4)==380000,"4X keeps measured readiness plus jitter margin");
+ phase.observe(10000201,410000);
+ check(phase.select(10000202,420000,333333,4)==420000,"slow batch immediately restores conservative phase");
+ check(phase.select(21000000,420000,333333,4)==420000,"stale readiness cannot shorten a new pair");
+ for(unsigned multiplier:{2u,4u,6u}){
+ phase.reset();
+ const int64_t interval=333667,ready=120000;
+ const int64_t needed=ready+interval*(multiplier-1)/multiplier;
+ for(int i=0;i<8;++i)phase.observe(30000000+i,needed);
+ auto last=interval+90000;bool bounded=true;
+ for(int i=0;i<80;++i){const auto delay=phase.select(30000100+i,interval+90000,interval,multiplier);
+ bounded&=delay>=needed&&delay<=interval+90000&&last-delay<=2500;last=delay;}
+ check(bounded,"2X/4X/6X preserves readiness and bounded phase at 29.97 Hz");
+ phase.reset();check(phase.select(30001000,interval+90000,interval,multiplier)==interval+90000,"reset discards earlier readiness");
+ }
+ phase.observe(40000000,-1);phase.observe(40000000,30000000);
+ check(phase.select(40000001,420000,333333,4)==420000,"invalid observations cannot train phase");
return failures?1:0;
}