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

test: measure VC-007PRO NR DLSS 4X capture latency

Veyra Goal Agent410061ad8203
diff --git a/docs/CAPTURE_LATENCY_DLSS4X_2026-09-18.md b/docs/CAPTURE_LATENCY_DLSS4X_2026-09-18.md
new file mode 100644
index 00000000..564a1f6d
--- /dev/null
+++ b/docs/CAPTURE_LATENCY_DLSS4X_2026-09-18.md
@@ -0,0 +1,132 @@
+# VC-007PRO / NR / DLSS 4X 实卡延迟对比
+
+## 测量合同
+
+用户将原请求中的 XeSS 4X 改为 DLSS 4X。本轮在 `codex/frame-pacing-20260918`、基准提交 `a471474a972ef4618002925255cf999123bc0e6f` 上增加诊断与实卡测试入口,不修改同步算法。
+
+- 实卡:VC-007PRO,DirectShow 格式索引 12,3840x2160、请求 30fps、NV12。实际回调接近 29.97fps。
+- 效果:NR 实时档,NR/光流内部 1920x1080;源图、DLSS FG、图输出均为 3840x2160;SR 关闭。不是原生 4K NR。
+- 本机:RTX 5070、驱动 616.56;2560x1440 / 100Hz SDR 显示器;测试窗口外框 1280x760,最后 blit 缩放到窗口。
+- 四轮分别低排队、均匀呈现(用户称前端同步)、Reflex 请求、完全关闭。显示同步统一允许撕裂;均匀呈现是 Veyra 自身实现,不是集成 RTSS。
+- 每轮启动后预热 10 秒,再正式采样 120 秒。真实 HDMI WASAPI 音频入口打开,输出静音;没有停掉音频链路来降低视频延迟。
+- 当前 Reflex 与 FG 同开显式回退低排队。因此这次可以测 Reflex 选项的实际行为,不能宣称测到了原生 Reflex + DLSS 4X 的延迟。
+
+## 计时边界
+
+起点是采集驱动调用 `SampleCB` 的软件时刻;终点是呈现函数返回后的软件时刻。HDMI 扫描/采集卡内部处理/USB/驱动在回调前的延迟、DWM/显示扫描/像素响应在 Present 后的延迟均没有外部参考测量。这里的总耗时不能称为 HDMI 到屏幕的物理端到端延迟。
+
+NV12 是未压缩图像,本路径没有 H.264/HEVC/MJPEG 解码器,不能捏造一个“采集卡解码耗时”。入站包含采集校验、锁和 CPU 拷贝,随后 mailbox 读取、GPU 上传/颜色变换、光流、NR、残差合成、三张 DLSS 插值帧、呈现等待、blit 和 Present。
+
+CPU 与 GPU 并行,不能把 GPU 阶段再加到 CPU 总耗时里;各阶段 P95 也不能直接相加。GPU FG batch 已含 FG1/2/3。GPU 全图区间以同帧首尾 timestamp 求包络,包含依赖间隙,排除另列的 blit。CPU ready 是轮询观察到 fence 完成的时刻,并非精确 GPU 完成时刻。
+
+按 source/arrival 关联入站与读帧,按 source/epoch/revision 关联处理与 GPU 阶段。CPU 使用同一 steady_clock;GPU 仅在 GPU 时间域求差,不跨时钟直接减。呈现延迟按正式时间窗内 Present 返回的事件统计;GPU/处理耗时按正式时间窗内到达的源帧统计。快照计数因 50ms 采样边界可能比完整事件窗少一两帧。
+
+逐帧日志全部开启、控制台日志关闭、文件沿用 64KiB/250ms 缓冲。日志本身有测量开销,四种模式配置一致;没有加入 GPU 像素回读或额外逐 pass fence wait。只有一轮/模式,细小差异不能宣称普适收益。
+
+驱动拒绝了请求 3 个缓冲的协商,实际分配 10 个缓冲,每个 12441600 bytes。分配容量不等于积压十帧,不能由此推算 333ms 延迟;应用 mailbox 实际积压另看测量。
+
+## 执行与证据
+
+所有产物位于 `E:/项目/Veyra/`:
+
+- 构建:`build/frame-pacing-20260918`。
+- 构建日志:`logs/capture-latency-20260918/build.log`。
+- 原始日志、结果、快照、关联 CSV、汇总:`tests/capture-latency-20260918`。
+- 子进程临时目录:`tmp/frame-pacing-20260918`。
+
+工作目录 `E:/项目/Veyra/worktrees/frame-pacing-20260918`,构建命令:
+
+```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_presentation_pacing_tests,veyra_capture_tests
+```
+
+构建 exit0,仅更新诊断测试程序及其产品库;GUI 可执行程序没有在本轮重新链接。实卡枚举使用 `veyra_capture_tests.exe --list`,结果见 `devices.txt`。正式测试使用:
+
+```powershell
+./scripts/test-frame-pacing.ps1 -Output E:/项目/Veyra/tests/capture-latency-20260918 -Name low -Mode 0 -Sync 0 -Multiplier 4 -Seconds 120 -Scenario capture-nr
+./scripts/test-frame-pacing.ps1 -Output E:/项目/Veyra/tests/capture-latency-20260918 -Name even -Mode 1 -Sync 0 -Multiplier 4 -Seconds 120 -Scenario capture-nr
+./scripts/test-frame-pacing.ps1 -Output E:/项目/Veyra/tests/capture-latency-20260918 -Name reflex -Mode 2 -Sync 0 -Multiplier 4 -Seconds 120 -Scenario capture-nr
+./scripts/test-frame-pacing.ps1 -Output E:/项目/Veyra/tests/capture-latency-20260918 -Name off -Mode -1 -Sync 0 -Multiplier 4 -Seconds 120 -Scenario capture-nr
+python scripts/acceptance/analyze-capture-latency.py E:/项目/Veyra/tests/capture-latency-20260918
+```
+
+## 实测结果
+
+四轮退出码均为 0,实际测量分别 120.010、120.042、120.020、120.047 秒。P95 表示 95% 样本不超过该值,不是最坏情况。单位均为毫秒。
+
+| 模式 | 原帧回调到 Present 返回 P50 | P95 | 最大 | 提交 FPS | 实际模式 |
+| --- | ---: | ---: | ---: | ---: | --- |
+| 低排队 | 42.211 | 42.553 | 43.223 | 119.873 | 低排队 |
+| 均匀呈现(前端同步) | 42.290 | 44.784 | 48.074 | 119.883 | 均匀呈现 |
+| Reflex 请求 | 42.188 | 42.518 | 43.408 | 119.880 | 回退低排队 |
+| 完全关闭 | 42.184 | 42.507 | 43.105 | 119.886 | 关闭 |
+
+这台机器、这组配置没有测出低排队或 Reflex 选项相对关闭的显著降延迟收益。均匀呈现的尾部等待更高,提交间隔 P95 也从关闭的 8.750ms 增到 9.670ms,不能宣称它在本场景更平滑。显示器只有 100Hz,表中约 119.88 是 Present 提交率,不是屏幕完整显示率。
+
+### CPU / 调度分段
+
+每格为 P50 / P95。原帧就绪后仍在等同一对 A/B 的生成帧依次呈现,因此原帧就绪早于整批 FG 完成。
+
+| 阶段 | 低排队 | 均匀呈现 | Reflex 请求 | 关闭 |
+| --- | ---: | ---: | ---: | ---: |
+| 回调校验、锁与 CPU 拷贝 | 1.013 / 1.165 | 0.998 / 1.163 | 1.008 / 1.173 | 0.993 / 1.149 |
+| 拷贝完成到 mailbox 读取 | 0.007 / 0.012 | 0.007 / 0.017 | 0.007 / 0.011 | 0.007 / 0.012 |
+| 读取到处理图开始 | 0.014 / 0.018 | 0.014 / 0.018 | 0.013 / 0.018 | 0.013 / 0.018 |
+| CPU 处理图提交(与 GPU 重叠) | 2.035 / 2.412 | 2.076 / 2.484 | 2.010 / 2.379 | 2.062 / 2.464 |
+| 其中 command slot 等待 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 |
+| 提交结束到原帧 ready 观察 | 7.027 / 7.509 | 7.077 / 7.764 | 7.058 / 7.535 | 7.014 / 7.493 |
+| 原帧 ready 到 Present 开始 | 31.825 / 32.319 | 31.924 / 34.261 | 31.816 / 32.282 | 31.798 / 32.269 |
+| 原帧呈现函数调用及紧邻 bookkeeping | 0.213 / 0.344 | 0.213 / 0.340 | 0.211 / 0.342 | 0.214 / 0.344 |
+| 回调到原帧 ready(累计) | 10.145 / 10.614 | 10.235 / 10.936 | 10.151 / 10.610 | 10.143 / 10.608 |
+
+NV12 压缩解码:不适用。GPU 上传/颜色转换见下一表。CPU 提交中还包含写上传缓冲、驱动调用等,本次没有把它进一步硬拆成未经测量的数值。
+
+### GPU 阶段
+
+| 阶段 | 低排队 | 均匀呈现 | Reflex 请求 | 关闭 |
+| --- | ---: | ---: | ---: | ---: |
+| NV12 GPU 上传/颜色转换 | 0.190 / 0.198 | 0.192 / 0.200 | 0.191 / 0.198 | 0.188 / 0.197 |
+| 光流及其准备 | 1.029 / 1.170 | 1.028 / 1.160 | 1.031 / 1.162 | 1.030 / 1.164 |
+| NR | 6.130 / 6.501 | 6.126 / 6.524 | 6.126 / 6.494 | 6.126 / 6.462 |
+| 残差合成 | 0.232 / 0.418 | 0.233 / 0.414 | 0.232 / 0.419 | 0.233 / 0.419 |
+| DLSS 插值第 1 张 | 2.609 / 2.835 | 2.638 / 2.868 | 2.635 / 2.863 | 2.607 / 2.827 |
+| DLSS 插值第 2 张 | 1.485 / 1.708 | 1.505 / 1.739 | 1.508 / 1.734 | 1.483 / 1.705 |
+| DLSS 插值第 3 张 | 1.482 / 1.700 | 1.503 / 1.722 | 1.507 / 1.723 | 1.482 / 1.698 |
+| DLSS 三张总批次(含上三行) | 5.647 / 6.009 | 5.830 / 6.156 | 5.724 / 6.089 | 5.638 / 5.999 |
+| 图 GPU 首尾区间(排除 blit) | 13.717 / 14.169 | 13.822 / 14.308 | 13.792 / 14.252 | 13.708 / 14.124 |
+| 最后 blit 到窗口(每次呈现) | 0.027 / 0.029 | 0.028 / 0.029 | 0.027 / 0.029 | 0.027 / 0.029 |
+
+SR 与 Video HDR 关闭,没有对应 GPU 样本。以上是既有阶段 timestamp 覆盖的完整区段,NR/光流阶段包含相关准备步骤,不等于只量供应商单个内核。
+
+### 生成帧、稳定性和计数
+
+| 指标 | 低排队 | 均匀呈现 | Reflex 请求 | 关闭 |
+| --- | ---: | ---: | ---: | ---: |
+| B 回调到生成帧 Present P50 / P95 | 25.538 / 34.227 | 25.607 / 36.672 | 25.518 / 34.181 | 25.502 / 34.181 |
+| A 回调到生成帧 Present P50 / P95 | 58.904 / 67.598 | 58.981 / 70.040 | 58.883 / 67.554 | 58.869 / 67.558 |
+| 全部提交间隔 P50 / P95 | 8.364 / 8.774 | 8.310 / 9.670 | 8.367 / 8.762 | 8.372 / 8.750 |
+| 原帧延迟首 30s / 尾 30s 的 P50 | 42.250 / 42.216 | 42.327 / 42.223 | 42.208 / 42.177 | 42.196 / 42.166 |
+| 原帧呈现事件样本数 | 3597 | 3598 | 3597 | 3598 |
+| 生成帧呈现事件样本数 | 10789 | 10793 | 10791 | 10794 |
+
+生成帧包含 A 与 B 的信息,约 25ms 的 B 年龄不能当成整张画面的输入响应延迟。A/B 实测到达间隔中位数约 33.37ms;4X 不会把输入采样从 30Hz 变成真实 120Hz。
+
+四轮正式采样段:NR/FG 始终激活,采集 dropped 增量 0,补帧执行前跳过增量 0,执行后过期增量 0;command slot wait 为 0;未见随运行时间积累的排队。预热期间各有 3 个跳过机会及 provider warmup,正式窗最初约 0.85 秒仍采到最近一次跳过的受限状态,limited 样本约占 0.72%,不能将整次运行描述为从未出现受限标记。正式段没有新增跳过。
+
+少量生成帧缺少 CPU ready 观察值:低排队 18、均匀 7、Reflex 7、关闭 12。相关 ready 分段跳过这些样本;有完整 callback/Present 的总耗时仍保留。没有把缺失值填 0,全部原帧 ready 样本完整。
+
+## 根因范围与建议
+
+主要可见延迟是原帧 ready 后约 32ms 的呈现等待,并不是 GPU 运算花了 42ms。`EngineController.cpp` 使用 `liveInterval + processingAllowance` 为实卡 DLSS 成对调度:本机源间隔约 33.33ms,原帧增强预算约 8.3ms,因此原帧目标约在 B 回调之后 41.6ms,再叠加实际调度和 Present。`FgRecoveryBudget.h` 的预算来自近期 GPU 基础处理成本,`PresentationScheduler.h` 再按子帧 PTS 排布三张插值与 B。
+
+四种可选模式共用这个基础时序。关闭撤销新增同步行为,但保留补帧基础排序;低排队也不能凭名字省掉这段。30fps 插值必须等后帧到达,这是因果约束;但是当前具体的整帧延后量是实现策略,不能直接宣称所有约 32ms 都是物理上不可减少的。要降低它,需要验证整套 A/B/原帧时序,而不是删一个 sleep 导致帧成串、倒序或丢弃。
+
+本场景优先保持关闭或低排队;没有证据支持推荐均匀呈现来降延迟。下一项唯一任务是用同一动态输入配合外部高帧率拍摄,测 HDMI 源画面与采集预览的差值,再评估基础补帧时序的可减少部分。本轮只测量,未更改调度来制造收益。
+
+## 真实性与交付检查
+
+真实运行日志四轮均有 NR `CreateFeature id=18 result=0x1 seh=0`、DLSSG `Create ... result=0x1 seh=0`、DLSSG `Evaluate ... generatedCount=3 ... result=0x1 seh=0`,NVOF Create/execute 成功;四轮没有 `[ERROR]`,正常释放并 clean stop。未在 RTX 30/40 上执行,不把 RTX 5070 结果扩展到这些卡。
+
+补充 20 秒 `signal-check`(同配置、关闭模式)exit0,截图独立于四轮数据:`scripts/acceptance/capture-test-window.py` 第一次因窗口遮挡拒绝截图,之后仅将测试窗口置前重试成功。`signal-check.png` 已目视核对为 PS5 PlayStation Plus 主界面,非黑帧、非设备测试图;RGB 均值约 39.45/38.35/35.15,范围 0..255。没有自动操作用户主机进入游戏,场景以静态主界面为主,动态游戏最坏耗时和插值画质未验收。截图仅留本地,没有上传。
+
+修改文件:`CaptureCardSource.cpp`、`EngineController.cpp`(仅增加详细日志)、`PresentationPacingTests.cpp`(实卡入口与采样)、`scripts/acceptance/analyze-capture-latency.py`、`scripts/acceptance/capture-test-window.py`、本报告和 WORKLOG。分析生成 `comparison.json`、`comparison.csv`、`stages.md` 与各组 `joined-presents.csv`,包含各阶段样本数、均值、P50/P95/P99/最大值。保留约 110MB 原始正式测试日志作为证据,无中间包或解压副本。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index f1096cf0..3d0de87e 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# Veyra 工作记录
+## 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 测试。
+
+构建命令、方法、结果、边界与每段耗时统一记录在 [CAPTURE_LATENCY_DLSS4X_2026-09-18.md](CAPTURE_LATENCY_DLSS4X_2026-09-18.md)。本轮构建 `veyra_presentation_pacing_tests,veyra_capture_tests` exit0;产物 `E:/项目/Veyra/build/frame-pacing-20260918`,日志 `E:/项目/Veyra/logs/capture-latency-20260918/build.log`,实卡证据与分析 `E:/项目/Veyra/tests/capture-latency-20260918`,临时目录 `E:/项目/Veyra/tmp/frame-pacing-20260918`。没有新增运行库/SDK 入 Git,没有打包、合并 main、推送或发布。
+
+四轮各 120 秒 exit0,原帧回调到 Present 返回中位数:低排队 42.211ms、均匀呈现 42.290ms、Reflex 请求(实际低排队)42.188ms、关闭 42.184ms;P95 分别 42.553/44.784/42.518/42.507ms。正式窗内采集丢帧、补帧新增跳过/过期、command slot wait 均为 0,NR/FG 始终激活,没有测出新增同步的明显降延迟收益。主要等待为原帧 GPU 就绪后约 32ms 的基础补帧排布,GPU 全图区间约 13.8ms,CPU 与 GPU 重叠不能累加。完整阶段与统计脚本已交付。
+
+NV12 没有压缩解码阶段;总耗时不包含采集卡内部与屏幕扫描。20 秒独立 signal-check exit0,截图目视确认为 PS5 主界面,不能推广为动态游戏最坏情形。第一次截图因遮挡主动失败,仅将测试窗口置前后重试成功。NR/DLSS Create/Evaluate 真实返回 `0x1 seh=0`,四轮无 ERROR。保留原始日志、JSON/CSV 和截图;无新增包、解压副本和临时残留。下一步:同动态输入的外部高帧率拍摄对照,并验证基础补帧时序可减少的等待。
+
+收尾:`git diff --check` exit0,全部测试进程已退出、tmp 为空,桌面 main 工作区干净。仅将上述诊断源码/脚本与文档保存到本地隔离分支,不包含本地证据或二进制。
+
## 2026-09-18 帧同步隔离实现与本机验收交付
在 `codex/frame-pacing-20260918` 完成默认关闭的低排队/均匀呈现/Reflex 实验、允许撕裂/VSync/自动、UI v6 独立持久化、请求与实际状态,以及相关回归。当前构建 `E:/项目/Veyra/build/frame-pacing-20260918/veyra.exe`。存档仍为 `6e69eeb` / `checkpoint/pre-frame-pacing-20260918`;没有合并 main、推送、发布或改动此前 beta 包。
diff --git a/scripts/acceptance/analyze-capture-latency.py b/scripts/acceptance/analyze-capture-latency.py
new file mode 100644
index 00000000..c0f71451
--- /dev/null
+++ b/scripts/acceptance/analyze-capture-latency.py
@@ -0,0 +1,160 @@
+"""Join physical capture traces without mixing CPU and GPU clocks."""
+import argparse
+import csv
+import json
+import re
+from collections import defaultdict
+from pathlib import Path
+
+
+def stats(values):
+ values = sorted(values)
+ if not values:
+ return {"n": 0}
+ def percentile(p):
+ 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),
+ "p50": percentile(.5), "p95": percentile(.95),
+ "p99": percentile(.99), "max": values[-1]}
+
+
+def analyze(directory):
+ result = (directory / "result.txt").read_text(encoding="utf-8-sig")
+ start = int(re.search(r"measurementStart=(\d+)", result)[1])
+ end = int(re.search(r"measurementEnd=(\d+)", result)[1])
+ seconds = (end - start) / 10_000_000
+ events = defaultdict(list)
+ pattern = re.compile(r"\[(capture-(?:ingress|read|graph|present)-sample|gpu-timestamp)\] (.*)")
+ for line in (directory / "engine.log").open(encoding="utf-8-sig", errors="replace"):
+ match = pattern.search(line)
+ if not match:
+ continue
+ fields = {}
+ for key, value in re.findall(r"(\w+)=([^\s]+)", match[2]):
+ if value in ("true", "false"):
+ fields[key] = value == "true"
+ else:
+ fields[key] = float(value) if "." in value else int(value)
+ events[match[1]].append(fields)
+ ingress = {(x["source"], x["arrival"]): x for x in events["capture-ingress-sample"]}
+ reads = {(x["source"], x["arrival"]): x for x in events["capture-read-sample"]}
+ graphs = {(x["source"], x["epoch"], x["revision"]): x for x in events["capture-graph-sample"]}
+ measured_graphs = {k: x for k, x in graphs.items() if start <= x["arrival"] < end}
+ values = defaultdict(list)
+ unmatched = defaultdict(int)
+ def ms(name, a, b):
+ if b < a:
+ raise ValueError(f"negative duration: {name}: {a}, {b}")
+ values[name].append((b - a) / 10_000)
+ arrivals = sorted(x["arrival"] for x in ingress.values() if start <= x["arrival"] < end)
+ for a, b in zip(arrivals, arrivals[1:]):
+ ms("callback_interval", a, b)
+ for x in ingress.values():
+ if start <= x["arrival"] < end:
+ ms("callback_copy_lock", x["arrival"], x["copied"])
+ for x in measured_graphs.values():
+ key = (x["source"], x["arrival"])
+ r, i = reads.get(key), ingress.get(key)
+ if r and i:
+ ms("mailbox_until_read", i["copied"], r["read"])
+ ms("read_to_graph_start", r["read"], x["start"])
+ else:
+ unmatched["graph_ingress_read"] += 1
+ ms("graph_cpu_submission", x["start"], x["submitted"])
+ values["graph_slot_wait"].append(x["slotWaitMs"])
+ presented = [x for x in events["capture-present-sample"] if start <= x["end"] < end]
+ rows = []
+ for x in presented:
+ kind = "generated" if x["generated"] else "real"
+ ms(kind + "_callback_to_present_return", x["arrival"], x["end"])
+ ms(kind + "_present_call", x["begin"], x["end"])
+ if x["ready"]:
+ ms(kind + "_callback_to_ready_observed", x["arrival"], x["ready"])
+ ms(kind + "_ready_to_present_begin", x["ready"], x["begin"])
+ 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"])
+ g = graphs.get((x["source"], x["epoch"], x["revision"]))
+ if g and g["arrival"] == x["arrival"] and x["ready"]:
+ ms(kind + "_submit_to_ready_observed", g["submitted"], x["ready"])
+ else:
+ unmatched["missing_ready" if not x["ready"] else "present_graph"] += 1
+ if not x["generated"]:
+ for name, lo, hi in [("real_first_30s", start, start + 300_000_000),
+ ("real_last_30s", end - 300_000_000, end)]:
+ if lo <= x["end"] < hi:
+ ms(name, x["arrival"], x["end"])
+ 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"])
+ 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",
+ 10: "fg_batch", 11: "blit", 12: "hdr"}
+ for x in events["gpu-timestamp"]:
+ key = (x["frame"], x["epoch"], x["revision"])
+ if key in measured_graphs:
+ duration = (x["end"] - x["begin"]) / x["frequency"] * 1000
+ values["gpu_" + stages[x["stage"]]].append(duration)
+ if x["stage"] != 11:
+ gpu_groups[key].append(x)
+ for group in gpu_groups.values():
+ frequencies = {x["frequency"] for x in group}
+ if len(frequencies) != 1:
+ raise ValueError("GPU clock frequency mismatch")
+ values["gpu_graph_envelope"].append(
+ (max(x["end"] for x in group) - min(x["begin"] for x in group)) / group[0]["frequency"] * 1000)
+ snapshots = list(csv.DictReader((directory / "capture-snapshots.csv").open()))
+ snapshots = [x for x in snapshots if start <= int(x["host"]) < end]
+ first, last = snapshots[0], snapshots[-1]
+ 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),
+ 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}),
+ callbackEvents=len(arrivals), presentEvents=len(presented),
+ callbackFps=len(arrivals) / seconds, presentSubmitFps=len(presented) / seconds)
+ formats = sorted({(x["width"], x["height"], x["format"]) for x in reads.values()
+ if start <= x["arrival"] < end})
+ assert formats == [(3840, 2160, 23)], f"Unexpected input formats: {formats}"
+ counters["observedInputFormats"] = formats
+ with (directory / "joined-presents.csv").open("w", newline="", encoding="utf-8") as file:
+ writer = csv.DictWriter(file, fieldnames=rows[0].keys())
+ writer.writeheader()
+ writer.writerows(rows)
+ return {"name": directory.name, "seconds": seconds, "result": result,
+ "counters": counters, "unmatched": dict(unmatched),
+ "milliseconds": {k: stats(v) for k, v in values.items()}}
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("root", type=Path)
+ parser.add_argument("--names", nargs="+", default=["low", "even", "reflex", "off"])
+ args = parser.parse_args()
+ results = [analyze(args.root / name) for name in args.names]
+ (args.root / "comparison.json").write_text(json.dumps(results, indent=2), encoding="utf-8")
+ lines = ["| Metric (ms, P50 / P95) | " + " | ".join(x["name"] for x in results) + " |",
+ "| --- | " + " | ".join("---:" for x in results) + " |"]
+ for key in results[0]["milliseconds"]:
+ cells = []
+ for result in results:
+ s = result["milliseconds"].get(key)
+ cells.append(f"{s['p50']:.3f} / {s['p95']:.3f}" if s else "unmeasured")
+ lines.append("| " + key + " | " + " | ".join(cells) + " |")
+ (args.root / "stages.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
+ with (args.root / "comparison.csv").open("w", newline="", encoding="utf-8") as file:
+ writer = csv.writer(file)
+ writer.writerow(["mode", "metric", "n", "mean_ms", "p50_ms", "p95_ms", "p99_ms", "max_ms"])
+ for result in results:
+ for key, s in result["milliseconds"].items():
+ writer.writerow([result["name"], key, *[s[x] for x in ["n", "mean", "p50", "p95", "p99", "max"]]])
+ print(result["name"], json.dumps(result["counters"]))
+ print("real latency:", result["milliseconds"]["real_callback_to_present_return"])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/acceptance/capture-test-window.py b/scripts/acceptance/capture-test-window.py
new file mode 100644
index 00000000..59fbb884
--- /dev/null
+++ b/scripts/acceptance/capture-test-window.py
@@ -0,0 +1,39 @@
+"""Capture only the visible latency harness window, outside timed measurements."""
+import ctypes as c
+import ctypes.wintypes as w
+import json
+import sys
+import time
+from pathlib import Path
+from PIL import ImageGrab, ImageStat
+
+u = c.WinDLL("user32", use_last_error=True)
+u.SetProcessDpiAwarenessContext.argtypes = [w.HANDLE]
+u.SetProcessDpiAwarenessContext(c.c_void_p(-4))
+u.FindWindowW.argtypes = [w.LPCWSTR, w.LPCWSTR]
+u.FindWindowW.restype = w.HWND
+u.GetWindowRect.argtypes = [w.HWND, c.POINTER(w.RECT)]
+u.GetAncestor.argtypes = [w.HWND, w.UINT]
+u.GetAncestor.restype = w.HWND
+u.WindowFromPoint.argtypes = [w.POINT]
+u.WindowFromPoint.restype = w.HWND
+window = u.FindWindowW("STATIC", "Veyra pacing acceptance")
+assert window, "Capture harness window missing"
+u.SetWindowPos.argtypes = [w.HWND, w.HWND, c.c_int, c.c_int, c.c_int, c.c_int, w.UINT]
+u.SetForegroundWindow.argtypes = [w.HWND]
+u.SetWindowPos(window, c.c_void_p(-1), 0, 0, 0, 0, 0x43)
+u.SetForegroundWindow(window)
+time.sleep(.3)
+rect = w.RECT()
+assert u.GetWindowRect(window, c.byref(rect))
+points = [(rect.left + 15, rect.top + 40), (rect.right - 15, rect.bottom - 15),
+ ((rect.left + rect.right) // 2, (rect.top + rect.bottom) // 2)]
+assert all(u.GetAncestor(u.WindowFromPoint(w.POINT(x, y)), 2) == window for x, y in points), "Harness is occluded"
+image = ImageGrab.grab(bbox=(rect.left, rect.top, rect.right, rect.bottom), all_screens=True).convert("RGB")
+out = Path(sys.argv[1])
+image.save(out)
+sample = image.crop((20, 60, image.width - 20, image.height - 20))
+result = {"image": str(out), "mean": ImageStat.Stat(sample).mean,
+ "extrema": sample.getextrema(), "bounds": [rect.left, rect.top, rect.right, rect.bottom]}
+out.with_suffix(".json").write_text(json.dumps(result, indent=2), encoding="utf-8")
+print(json.dumps(result))
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index f7f5fbde..bc08c4b8 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1095,6 +1095,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
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(physicalCapture&&veyra::log::verboseFrameLogs())veyra::log::info("capture-graph-sample",std::format("source={} epoch={} revision={} arrival={} start={} submitted={} slotWaitMs={:.6f}",pkt.sequence,out.batch.identity.epoch,out.batch.identity.settingsRevision,captureArrival,std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100,std::chrono::duration_cast<std::chrono::nanoseconds>(processDone.time_since_epoch()).count()/100,processSlotWaitMs));
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));
@@ -1246,6 +1247,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
if(didPresent){
cadence.submitted(optionalNow);
+ if(physicalCapture&&veyra::log::verboseFrameLogs())veyra::log::info("capture-present-sample",std::format("source={} epoch={} revision={} batch={} subframe={} generated={} arrival={} arrivalA={} ready={} begin={} end={}",item.identity.sourceFrameId,item.identity.epoch,item.identity.settingsRevision,batch.batch.batchId,item.subframe,generated,captureArrival,lineage?lineage->a.host100ns:0,watch->frameReadyObserved[s.next],optionalNow,host100ns()));
if(veyra::log::verboseFrameLogs())veyra::log::info("pacing-sample",std::format("mode={} enabled={} sync={} pts={} begin={} end={} ready={} process={} generated={} queue={} lateMs={:.3f}",unsigned(presentationEffective.mode),presentationEffective.enabled,unsigned(presentationEffective.display),item.pts100ns,optionalNow,host100ns(),watch->frameReadyObserved[s.next],std::chrono::duration_cast<std::chrono::nanoseconds>(watch->processStart.time_since_epoch()).count()/100,generated,liveScheduler->occupancy(),isCapture?double(optionalNow-timeline.deadline(item.pts100ns))/10000:fileAwaitingVideo?0:nowMs()-itemPtsMs));
traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);
if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",batch.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index a0fc2cfe..6b2aaba3 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -346,7 +346,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
const bool sampleTime=sample&&sample->GetTime(&sampleStart,&sampleEnd)==S_OK;
const bool valid=sample&&std::isfinite(time)&&SUCCEEDED(sample->GetPointer(&data))&&data&&
(compressedPath?sample->GetActualDataLength()>0:sample->GetActualDataLength()>=LONG(layout.sampleBytes));
- bool enqueued=false;
+ bool enqueued=false;uint64_t timingSequence=0;int64_t copied100ns=0;
{
std::lock_guard lock(mutex);
// The compressed path decodes in its own worker and keeps its own
@@ -381,9 +381,11 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
}
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
+ timingSequence=received;copied100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;
}
}
if(enqueued)decodeWake.notify_one();
+ if(log::verboseFrameLogs()&&timingSequence)log::info("capture-ingress-sample",std::format("source={} arrival={} copied={} compressed={}",timingSequence,std::chrono::duration_cast<std::chrono::nanoseconds>(arrival.time_since_epoch()).count()/100,copied100ns,compressedPath));
wake.notify_one();return S_OK;
}
HRESULT STDMETHODCALLTYPE BufferCB(double,BYTE*,long)override{return E_NOTIMPL;}
@@ -1102,6 +1104,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
delivered->pts=static_cast<int64_t>(time*10000000);delivered->duration=duration.isUnknown()?0:duration.to100ns();delivered->time_base={1,10000000};packet={};packet.pts={delivered->pts,10000000};packet.duration=duration;packet.colorInfo=colorInfo;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;
packet.sequence+=receivedOffset_;packet.sourceEpoch=epoch_;
packet.arrivalHost100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(p.readArrival.time_since_epoch()).count()/100;
+ if(log::verboseFrameLogs())log::info("capture-read-sample",std::format("source={} arrival={} read={} width={} height={} format={}",packet.sequence,packet.arrivalHost100ns,std::chrono::duration_cast<std::chrono::nanoseconds>(Impl::Clock::now().time_since_epoch()).count()/100,delivered->width,delivered->height,delivered->format));
*frame=delivered;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;
}
void CaptureCardSource::close()noexcept{
diff --git a/tests/integration/PresentationPacingTests.cpp b/tests/integration/PresentationPacingTests.cpp
index d84cd3dd..1022cc82 100644
--- a/tests/integration/PresentationPacingTests.cpp
+++ b/tests/integration/PresentationPacingTests.cpp
@@ -1,5 +1,6 @@
#include "veyra/engine/EngineController.h"
#include "veyra/Log.h"
+#include "veyra/source/CaptureCardSource.h"
#include <filesystem>
#include <fstream>
#include <iostream>
@@ -17,6 +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";
+ 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;});
+ 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;
+ }
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;
MONITORINFOEXW monitor{};monitor.cbSize=sizeof(monitor);GetMonitorInfoW(MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST),&monitor);
@@ -28,18 +44,27 @@ 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;}
auto options=PlayerOptions::from(effects);options.captureReplayForTest=scenario==L"replay";
- engine.open(window,argv[1],options);
+ engine.open(window,sourcePath,options);
auto pump=[] {MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}};
auto wait=[&](auto predicate,int ms=15000){auto end=Clock::now()+std::chrono::milliseconds(ms);while(Clock::now()<end){pump();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;};
check(wait([](auto& s){return s.frames>10;}),"first frames");
+ if(physical){const auto warm=Clock::now();check(wait([&](auto& s){return Clock::now()-warm>=std::chrono::seconds(10)&&s.nrActive&&s.fgActive;},20000),"ten second warmup with NR and DLSS active");}
std::ofstream samples(dir/L"snapshots.csv");samples<<"wall,position,frames,generated,lateMs,queueReadyMs,presentMs,skipped,effective,mode,sync,revision\n";
const auto start=Clock::now();auto last=engine.snapshot();const auto first=last;
+ const auto host=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};
+ std::cout<<"measurementStart="<<host()<<" requestedMode="<<mode<<std::endl;
+ std::ofstream capture;
+ if(physical){capture.open(dir/L"capture-snapshots.csv");capture<<"host,received,dropped,processed,generated,nr,fg,limited,callbackFps,submitFps,ageMs,ageP95,requested,effective,realPresented,generatedPresented,fgSkipped,fgExpired\n";}
while(Clock::now()-start<std::chrono::seconds(seconds)&&!last.failed){
pump();last=engine.snapshot();samples<<std::chrono::duration<double>(Clock::now()-start).count()<<','<<last.position<<','<<last.frames<<','<<last.generated<<','<<last.lateMs<<','<<last.schedulingWaitP95Ms<<','<<last.presentCpuP95Ms<<','<<last.previewSkipped<<','<<last.presentationEffective.enabled<<','<<unsigned(last.presentationEffective.mode)<<','<<unsigned(last.presentationEffective.display)<<','<<last.presentationRevision<<'\n';
+ if(physical){const auto& c=last.metrics.flow.counters;capture<<host()<<','<<last.captureReceived<<','<<last.captureDropped<<','<<last.frames<<','<<last.generated<<','<<last.nrActive<<','<<last.fgActive<<','<<last.fgBudgetLimited<<','<<last.captureFps<<','<<last.submissionFps.value_or(0)<<','<<last.captureAgeMs<<','<<last.captureAgeP95Ms<<','<<mode<<','<<(last.presentationEffective.enabled?int(last.presentationEffective.mode):-1)<<','<<c.realPresented<<','<<c.generatedPresented<<','<<c.fgSkippedBeforeEval<<','<<c.generatedExpiredAfterEval<<'\n';}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
const auto speed=(last.position-first.position)/std::chrono::duration<double>(Clock::now()-start).count();
+ std::cout<<"measurementEnd="<<host()<<" elapsedSeconds="<<std::chrono::duration<double>(Clock::now()-start).count()<<std::endl;
+ if(physical){check(last.nrActive&&last.fgActive&&last.nrEvaluated>first.nrEvaluated,"real capture NR and DLSS remain active");std::cout<<"captureReceivedDelta="<<last.captureReceived-first.captureReceived<<" captureDroppedDelta="<<last.captureDropped-first.captureDropped<<" generatedDelta="<<last.generated-first.generated<<" requested="<<mode<<" effective="<<(last.presentationEffective.enabled?int(last.presentationEffective.mode):-1)<<std::endl;}
std::cout<<"mediaSpeed="<<speed<<" processedDelta="<<last.frames-first.frames<<std::endl;
check(!last.failed&&last.frames>first.frames+10&&speed>.8&&speed<1.2,"sustained playback at media speed");
if(multiplier>1)check(last.fgActive&&last.generated>0,"real provider generated frames");