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(fg): keep generated frames when live output is near the refresh rate
Veyra Goal Agent8544c0cb8d1f
diff --git a/AGENTS.md b/AGENTS.mdindex c69164c3..53f51fa8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra Agent 工作规则+> **2026-10-31 补帧接近刷新率修复**:用户确认“开始修”。分支`claude/fg-60hz-pacing-20261031`(基于c6c28b9)按docs/FG_60HZ_PACING_2026-10-31.md改实时图内补帧:输出在刷新率0.65–1.02倍时自动模式走一帧队列,输出不超过刷新率时生成帧等到下一帧到期,VFG跳帧后前2次不计入成本。`VEYRA_TEST_LEGACY_NEAR_REFRESH=1`恢复旧规则。本机只验证320 Hz,未在真实60 Hz屏/采集卡/5060 Ti验证,不得当作现场已修好。不合并main、不push/Release。+> **2026-10-29 RX7000 NR接入**:用户授权在codex/amd-rdna3-nr-20261029(基线e7a9ae1)加入7000系NR与Small性能模型。按docs/AMD_RDNA3_NR_PLAN_2026-10-29.md隔离RedDuke网络worker,保留9000 lmxxf及现有NVIDIA路径;不接旧帧异步残差,不回读GPU图像,不改真实配置/驱动/现有SDK与运行组件。不合并main、不push/Release。本机无RX7000,合同测试不冒充实卡通过。> **2026-10-28/29英伟达低延迟任务**:当前隔离分支`codex/nvidia-low-latency-20261028`,基线main4351bbd;用户授权完善Reflex并改为“英伟达低延迟:关/开/开+增强”。直接NVAPI,源帧Sleep与生成帧带外队列标记分开;当前本机DLSS/VFG/FSR原生路径验证,XeSS保持提供方调度并显示不生效。真实证据、失败修正和硬件边界见`docs/NVIDIA_LOW_LATENCY_2026-10-28.md`与`reports/nvidia-low-latency-20261028/FINAL.json`。2026-10-29 Claude复查修正(非英伟达显卡低排队归属、状态逐段翻译、摘要、未补帧通知降级)与屏幕采集延迟对比已提交到本分支(未合并main),见执行记录末节及`reports/claude-nvidia-ll-review-20261029/FINAL.json`。不合并main、不push/Release,不改真实配置、驱动、SDK/模型/DLL;使用私有测试配置。diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.mdindex 70ba9bbe..136ccfb0 100644--- a/docs/CURRENT_STATUS.md+++ b/docs/CURRENT_STATUS.md@@ -1,6 +1,8 @@# 当前项目状态-更新:2026-10-30。这里只描述现在;历史过程见[历史索引](history/INDEX.md)。+更新:2026-10-31。这里只描述现在;历史过程见[历史索引](history/INDEX.md)。++2026-10-31当前任务:分支 `claude/fg-60hz-pacing-20261031`(基于 `c6c28b9`)修现场 60 Hz 屏 4K30 补帧每 16.5 秒一串掉帧和 VFG 卡在 30 fps:接近刷新率时自动模式走一帧队列、垂直同步下生成帧等到下一帧到期、VFG 跳帧后前两次不计入成本。本机 320 Hz A/B 与回归通过,**未在真实 60 Hz 屏或 RTX 5060 Ti 验证**,需现场确认。见[执行记录](FG_60HZ_PACING_2026-10-31.md);未合并 main、未 push/Release。当前施工分支 `codex/amd-rdna3-nr-20261029`,从下述英伟达低延迟及Claude复查后的 `e7a9ae1` 接入 RX 7000 NR(RedDuke 独立网络 worker,Small / Original,兼容手动百分比)。保留 RX 9000 lmxxf 与 NVIDIA;本地构建、GPU 协议及设置/UI回归已通过,尚未在 RX 7000 实卡推理验收。测试入口和证据见 [接入记录](AMD_RDNA3_NR_PLAN_2026-10-29.md)。未合并main、未push/发布,正式版仍2.1.1。diff --git a/docs/FG_60HZ_PACING_2026-10-31.md b/docs/FG_60HZ_PACING_2026-10-31.mdnew file mode 100644index 00000000..18264b94--- /dev/null+++ b/docs/FG_60HZ_PACING_2026-10-31.md@@ -0,0 +1,83 @@+# 补帧在接近刷新率时的间歇掉帧(2026-10-31)++用户提供现场日志 `veyra-qml(69).log`(RTX 5060 Ti、4K30 USB 采集、60 Hz HDR 屏、2.1.1),诊断见 `E:/项目/Veyra/reports/claude-fg-intermittent-20261031/README.md`。用户确认“开始修”。分支 `claude/fg-60hz-pacing-20261031`,基于 `c6c28b9`;未合并 main、未 push/Release。回执 `E:/项目/Veyra/reports/claude-fg-60hz-pacing-20261031/FINAL.json`。++## 诊断结论++- 采集实际 29.972 fps,2X 输出 59.944 fps,屏幕 60.005 Hz,两者每 16.5 秒差一帧。每对帧按 USB 回调到达时刻锚定(标准差约 2.6 ms),周期末 3–4 秒帧贴着刷新边界来回落。+- v2.0.8 两条在 320 Hz 上调出来的规则把它变成丢帧:垂直同步下生成帧最多等 2 ms;自动模式 `Present(0,0)` 下,同一刷新内的新帧替换未显示的旧帧,计数器仍显示 60。+- 另一个独立问题:VFG 高档连续运行 23.1–23.6 ms,跳帧后单次要 28.5 ms(窗口)或 39.6 ms(全屏),而预算只允许约 25.9 ms。这次探测超预算后又拒绝 2 秒,日志里连续 30 fps 最长 76 秒,只有改设置才恢复。++## 改动++| 项 | 规则 | 适用范围 |+|---|---|---|+| 垂直同步等待 | 生成帧等到下一帧到期前 0.5 ms 才放弃(`liveGeneratedCapacityExpired`) | 实时、图内补帧、输出 ≤ 刷新率×1.02。超过时仍是最多 2 ms,DLSS 6X 高刷不变 |+| 自动模式 | 输出在刷新率的 0.65–1.02 倍时改走一帧深度垂直同步队列(`automaticQueueWanted`),状态显示“显示同步:自动(补帧接近刷新率)”。决定需保持 1.5 秒才切换(首次立即) | 同上;可变刷新已是该路径。XeSS 自行呈现,不变 |+| 迟到容忍 | 接近刷新率时生成帧可晚到下一帧到期前 0.5 ms(60 Hz 2X:16.2 ms,原 10 ms),准入预算用同一数字 | 只在输出间隔大于 10.5 ms 时有差别,即约 95 Hz 以下屏幕 |+| VFG 成本 | 跳帧后前 2 次补帧不计入成本估计(`FgCostSettling`) | 只限实时 VFG。DLSS 重新播种本来就不计入,文件播放不变 |+| 诊断 | `[fg-near-refresh]`、`[fg-drops]`(截止/容量/上限三类丢帧累计)、`[display-latency] replacedAtLeast`(被替换帧的下限)、`[pacing] automaticQueue` | 只写日志 |++`VEYRA_TEST_LEGACY_NEAR_REFRESH=1` 恢复全部旧规则供 A/B。++方案第 4 项(用设备时间戳平滑到达时刻)未做。++## 代价++- 自动模式在接近刷新率时不再“永不等待”。320 Hz 实测捕获到呈现 P50 差 ≤0.3 ms,P95 为 0 至 +1.8 ms。60 Hz 模型里真实帧最多多等 8–13 ms,P99 为 2–6.7 ms。+- 60 Hz 2X 的 VFG 成本上限约从 25.9 ms 放宽到 32.1 ms。成本落在这段时以前退回 30 fps,现在保持 60 fps,真实帧最多晚一次刷新。+- 真的跑不动的模式,每 2 秒探测从 1–2 组变为 3 组(回放:600 对中评估 30 对,2 秒内最多 3 对)。++## 验证++本机 RTX 5070、320 Hz 窗口模式、DLSS 6X,每组 12 秒 ×2,新旧规则交替,无其他占用。旧版实际显示数只能给范围:下限是 `samples`(自动模式只记轮询时刚好看到的帧),上限是呈现数减 `replacedAtLeast`。++| 自动模式 | 比值 | 旧:呈现/秒 | 旧:实际显示/秒 | 新:呈现/秒 | 新:被替换/秒 | 容量丢帧(12 秒) | 捕获→呈现 P50/P95 ms(旧→新) |+|---|---|---|---|---|---|---|---|+| 回放 53.2×6 | 0.9975 | 319.2 | 284–308 | 318.2–319.0 | 0 | 4–13 | 不适用 |+| 窗口 52.2×6 | 0.97 | 311 | 264–293 | 306.6–308 | 0 | 51–61 | 19.2→19.4–19.5 / 20.3–20.4→20.3–20.4 |+| 窗口 39.6×6 | 0.74 | 237.7 | 205–231 | 236.6–236.8 | 0 | 15–16 | 25.4–25.5→25.6 / 26.3–26.4→26.2–26.3 |++同一窗口场景较早一轮的 P95 是 20.7–20.8→22.5–22.6(P50 19.8→19.7),所以代价写成 0 至 +1.8 ms。++| 垂直同步 | 比值 | 容量丢帧(12 秒,旧→新) | 呈现/秒(旧→新) | 捕获→呈现 P95(旧→新) |+|---|---|---|---|---|+| 回放 53.2×6 | 0.9975 | 78–101→18–22 | 311–314→318 | 不适用 |+| 窗口 52.4×6 | 0.98 | 95–105→69–76 | 305–306→307–308 | 21.4–22.3→22.5 |+| 窗口 53.7×6(输出略高于刷新) | 1.006 | 72–103→75–80 | 315–316→316 | 20.4–20.8→22.3 |++- 高于刷新率(回放 60×6=360/s)规则不生效:自动 360/s、实际显示下限 304–306 两边相同;垂直同步容量丢帧 505–533→491–501,属波动。+- 旧自动模式实测丢帧随比值变化:0.38/0.51 无,0.56/0.65 最多约 2%(只有 `samples`,可能偏高),0.74–1.0 至少 3–6%。0.65 以下未处理。+- 模拟 60 Hz(`VEYRA_TEST_DISPLAY_HZ=60`,实际屏幕仍 320 Hz,只验证状态切换):VFG 30×2 进入队列模式、容忍 16.2 ms、状态文字正确,60/s 无丢帧。+- 60 Hz 模型 `sim_near.py`(29.972×2 对 60.005 Hz,占所有帧):自动 3.19%→0,垂直同步 1.09%→0;生成帧迟到时 19.07%/0.55%→0。+- 单元回放:垂直同步 6000 对丢 153→0,真实帧最大等待 2.17→8.17 ms;VFG 陷阱 600 对评估 10→600(窗口与全屏探测成本都恢复)。+- 卡顿恢复:真实 GPU `screen-vfg` 新旧规则、`screen-dlss` 新规则,3 轮 80 ms 卡顿后都恢复。+- 回归:repair contract、live timing、scheduler、realtime、i18n 全部 0 失败;QtQuick 123/0/1 跳过;9 个原生 GPU 场景(含 DLSS 6X、VFG、FSR、XeSS、生命周期)通过;翻译 2714 条无缺失;UI 启动无 QML 错误。++## 未验证++- **没有在真实 60 Hz 屏幕、采集卡或 RTX 5060 Ti 上跑过。** 320 Hz 结果证明机制,60 Hz 的数字只来自模型,需要现场确认。+- VFG 陷阱本机无法复现(本机显卡常驻 P0,跳帧后成本不升高),只有日志数字回放。跳帧后高成本的原因(疑似显卡降频)未证实;日志证据只显示窗口下第二次已接近稳态,全屏没有直接证据。若全屏下第三次仍超预算,这部分仍可能退回 30 fps。+- 第 4 项和 XeSS 未动,日志里 XeSS 段太短。0.65 以下、无补帧、文件播放都未改。++## 现场怎么看++用新版复现同样设置(4K30、2X、60 Hz),日志应出现:++- `[fg-near-refresh] near=true outputFps=60.000 refreshHz=60.000`,`[pacing] ... automaticQueue=true`(选自动时)。+- `[display-latency] replacedAtLeast=0`,`[fg-drops]` 的 capacity 基本不再增长,不再每 16.5 秒一串。+- `[live-fg-admission]` 不再长时间 `admitted=false`;全屏切换后约 2 秒内恢复。++对照:同机设 `VEYRA_TEST_LEGACY_NEAR_REFRESH=1` 再跑一次。++## 重跑++脚本在 `E:/项目/Veyra/reports/claude-fg-60hz-pacing-20261031/tools`。回放素材已清理,可重新生成:++`ffmpeg -f lavfi -i "testsrc2=size=1920x1080:rate=53.2:duration=40" -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p near-53p2.mp4`(60 fps 素材把 rate 改为 60)++手动入口 `E:/项目/Veyra/tests/claude-fg-60hz-pacing-20261031/启动补帧刷新率测试.cmd`,私有配置,运行目录仍 `tests/claude-sr-stage-20261028/app`。++## 与其他工作的关系++屏幕采集固定延迟修复在 `claude/screen-capture-hold-20261029` 工作树未提交,也改 `LivePresentationTiming.h`、`EngineController.cpp`、`PresentationPacingTests.cpp`,合并时可能冲突。两边未合并、未联合测试。diff --git a/docs/README.md b/docs/README.mdindex a01f1c4e..771e7494 100644--- a/docs/README.md+++ b/docs/README.md@@ -2,7 +2,7 @@日常只从这些入口开始:-当前任务:[英伟达低延迟三档](NVIDIA_LOW_LATENCY_2026-10-28.md)(独立分支,未发布)。+当前任务:[补帧接近刷新率的间歇掉帧](FG_60HZ_PACING_2026-10-31.md)(独立分支,未发布);此前:[英伟达低延迟三档](NVIDIA_LOW_LATENCY_2026-10-28.md)。1. [当前项目状态](CURRENT_STATUS.md):正式版、活动工作、暂停项、现场问题及验收边界。2. [开发与验证](DEVELOPMENT.md):唯一施工树、构建、回归、运行供体和路径规则。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex b31e8de1..f3d72bf2 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -196,4 +196,20 @@ RTX5060Ti、4K30 NV12→VFG2X/60Hz,主要稳定段NR/SR关闭。中档84.016不得将此前高档VFG预算拒绝当作全局结论。报告reports/fg-intermittent-20261031/MULTI_PROVIDER.md;原日志还含DLSS和XeSS。XeSS行9884(10:30:19.447)Present调用80.881ms、总81.097ms,前置记录提交0.207ms;生成和节奏在代理内部,不能将0.207ms冒充GPU推理耗时。SDK各短阶段有效样本大多58–62fps、cycleMismatches=0,关闭尾窗低FPS不代表播放持续掉帧;普通frame-flow原帧30也不是XeSS最终帧率。-源码明确XeSS生成帧不经Veyra生成子帧预算/10ms期限/2ms容量分支,每帧显示统计trackScanout也排除XeSS(每秒统计仍调用);上述机制均不能被当作全提供方同症状的唯一原因。调查范围应扩至共用采集、owner调度、呈现入口、Windows/驱动/合成及窗口状态,但现有证据不能确定同一根因。无产品修改/新构建/现场测试/发布。后续需要同设置分提供方的丢弃原因计数及API耗时分解,不能继续把单段关联提升为定论。\ No newline at end of file+源码明确XeSS生成帧不经Veyra生成子帧预算/10ms期限/2ms容量分支,每帧显示统计trackScanout也排除XeSS(每秒统计仍调用);上述机制均不能被当作全提供方同症状的唯一原因。调查范围应扩至共用采集、owner调度、呈现入口、Windows/驱动/合成及窗口状态,但现有证据不能确定同一根因。无产品修改/新构建/现场测试/发布。后续需要同设置分提供方的丢弃原因计数及API耗时分解,不能继续把单段关联提升为定论。++## 2026-10-31 补帧接近刷新率修复++用户确认“开始修”。分支claude/fg-60hz-pacing-20261031,基于c6c28b9;未合并main、未push/Release,未提交。记录docs/FG_60HZ_PACING_2026-10-31.md,回执reports/claude-fg-60hz-pacing-20261031/FINAL.json。++改动:输出不超过刷新率×1.02时生成帧等到下一帧到期前0.5 ms;输出在0.65–1.02倍时自动模式走一帧队列,迟到容忍与准入预算同步放宽(60 Hz 2X为16.2 ms);实时VFG跳帧后前2次不计入成本;新增fg-near-refresh、fg-drops、replacedAtLeast日志。第4项到达时刻平滑未做。++命令:tmp/claude-fg-60hz-pacing-20261031/build/build.py(并发2);check.py unit/ab/near/gpu-regress/qml/stage,sweep.py,func.py,ui_smoke.py,脚本已复制到报告tools。++失败与修正:timing测试目标不带/utf-8,包含DisplayFgBudget.h编译失败,比值断言改放realtime测试;pacing日志漏传参数编译失败;测试脚本写入NUL字符常量编译失败;首轮从构建目录运行缺DLSS运行库,FG未生效,改在共享运行目录运行。窗口输入16 ms定时器加GetTickCount只能产出约28 fps,改高精度重绘后才达到目标速率。++05:50–05:53与06:06后用户自行打开E:/App下2.1.1,首轮上限/低比值A/B被污染(GPU约48%),已移到contaminated目录并重跑;未停止用户进程,之后脚本记录userVeyraRunning。首轮用samples比较时发现自动模式samples只是下限、与垂直同步口径不同,会高估旧版丢帧,新增replacedAtLeast后重测,结果按范围报告。++结果:320 Hz自动模式比值0.74–1.0,旧版实际显示少3–15%(范围),新版被替换0、容量丢帧不超过生成帧的2%;捕获→呈现P50差≤0.3 ms,P95 0至+1.8 ms。垂直同步回放容量丢帧78–101→18–22。高于刷新率规则不生效,结果在波动内。单元回放:6000对丢153→0;VFG陷阱600对评估10→600。repair/timing/scheduler/realtime/i18n 0失败,QtQuick 123/0/1跳过,9个原生GPU场景通过,运行目录97个运行组件哈希一致。++未验:真实60 Hz屏、采集卡、RTX 5060 Ti;VFG陷阱本机不能复现,只有日志数字回放;跳帧后高成本的原因未证实。屏幕采集固定延迟修复分支也改同几个文件,未合并、未联合测试。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 0f41cd6a..3b393c12 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -7155,6 +7155,13 @@"en": "Screen capture error 0x{:08X}: {}","ja": "画面キャプチャーのエラー 0x{:08X}:{}"},+ {+ "zh": "屏幕队列 1 帧,避免丢帧",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": "螢幕佇列 1 幀,避免掉幀",+ "en": "1-frame display queue to avoid dropped frames",+ "ja": "画面キュー 1 フレーム、フレーム落ちを防止"+ },{"zh": "展开本卡片并播放 HDR 输出时测量,每秒最多 4 次","src": "qml/ProDisplayPanel.qml",@@ -10397,6 +10404,13 @@"en": "Display sync: auto + variable refresh","ja": "表示の同期:自動 + 可変リフレッシュ"},+ {+ "zh": "显示同步:自动(补帧接近刷新率)",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": "顯示同步:自動(補幀接近更新率)",+ "en": "Display sync: auto (frame generation near refresh rate)",+ "ja": "表示の同期:自動(フレーム生成がリフレッシュレートに近い)"+ },{"zh": "显示器","src": "qml/ScreenSourceDialog.qml",@@ -14066,11 +14080,11 @@"ja": "自動(負荷に応じて)"},{- "zh": "自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低 · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线",+ "zh": "自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低(实时补帧输出接近刷新率时改排 1 帧,避免丢帧) · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线","src": "qml/ProPresentationRows.qml",- "zh-TW": "自動(推薦):不撕裂,也不等待垂直同步,每次更新顯示最新一幀,延遲最低 · 垂直同步:每幀都等到更新才顯示,比自動多等最多一次更新 · 允許撕裂:可能出現撕裂線",- "en": "Auto (recommended): no tearing and no VSync wait; each refresh shows the newest frame for the lowest latency · VSync: every frame waits for a refresh, at most one refresh longer than Auto · Allow tearing: tear lines may appear",- "ja": "自動(推奨):ティアリングなし、垂直同期を待たず、毎回のリフレッシュで最新フレームを表示し遅延が最小 · 垂直同期:全フレームがリフレッシュを待って表示され、自動より最大 1 リフレッシュ分長く待つ · ティアリングを許可:ティアリングが発生する場合あり"+ "zh-TW": "自動(推薦):不撕裂,也不等待垂直同步,每次更新顯示最新一幀,延遲最低(即時補幀輸出接近更新率時改排 1 幀,避免掉幀) · 垂直同步:每幀都等到更新才顯示,比自動多等最多一次更新 · 允許撕裂:可能出現撕裂線",+ "en": "Auto (recommended): no tearing and no VSync wait; each refresh shows the newest frame for the lowest latency (live frame generation near the refresh rate queues 1 frame to avoid drops) · VSync: every frame waits for a refresh, at most one refresh longer than Auto · Allow tearing: tear lines may appear",+ "ja": "自動(推奨):ティアリングなし、垂直同期を待たず、毎回のリフレッシュで最新フレームを表示し遅延が最小(ライブのフレーム生成がリフレッシュレートに近いときは 1 フレームをキューしてフレーム落ちを防止) · 垂直同期:全フレームがリフレッシュを待って表示され、自動より最大 1 リフレッシュ分長く待つ · ティアリングを許可:ティアリングが発生する場合あり"},{"zh": "自动(独立显卡)",diff --git a/include/veyra/engine/DisplayFgBudget.h b/include/veyra/engine/DisplayFgBudget.hindex 05adf1c9..f34cc158 100644--- a/include/veyra/engine/DisplayFgBudget.h+++ b/include/veyra/engine/DisplayFgBudget.h@@ -24,6 +24,23 @@ namespace veyra::engine {// surplus waits or is dropped, so suggest turning generation off.inline constexpr double kDisplayFgFitTolerance=1.02;inline constexpr double kDisplayFgFillRatio=0.97;+// The same rates decide how a live frame reaches the panel. Near the refresh+// (about one new picture per refresh) capture arrival jitter puts two frames+// inside one refresh, and each one lost leaves a refresh repeating the last.+// Field log 2026-10-31 (4K30 2X, 60 Hz, 29.97 x 2 against 60.005 Hz): the two+// rates beat every 16.5 s and 3-4% of the generated frames went. Model of that+// display (reports/claude-fg-60hz-pacing-20261031): Present(0,0) loses 3.2% of+// all frames at ratio 1.0, 11% at 0.8 with a late generated frame, 3.7% at+// 0.67, nothing at 0.6. Measured on 320 Hz: at least 3-6% from 0.74 to 1.0,+// at most about 2% at 0.56-0.65 (left as it is), nothing at 0.5.+inline constexpr double kDisplayFgNearRatio=0.65;++inline bool displayFgOutputFits(double outputFps,double refreshHz){+ return std::isfinite(outputFps)&&std::isfinite(refreshHz)&&outputFps>0&&refreshHz>0&&outputFps<=refreshHz*kDisplayFgFitTolerance;+}+inline bool displayFgOutputNear(double outputFps,double refreshHz){+ return displayFgOutputFits(outputFps,refreshHz)&&outputFps>=refreshHz*kDisplayFgNearRatio;+}// Multipliers the user can pick for the backend (fgMultiplierChoices: XeSS// stops at 4X, FSR offers 2X only). Lower values than an accepted requestdiff --git a/include/veyra/engine/FgRecoveryBudget.h b/include/veyra/engine/FgRecoveryBudget.hindex f10a60e8..aa05b799 100644--- a/include/veyra/engine/FgRecoveryBudget.h+++ b/include/veyra/engine/FgRecoveryBudget.h@@ -69,17 +69,19 @@ public:int64_t processingAllowance(int64_t now,int64_t interval)const{return int64_t(std::min(double(std::max<int64_t>(0,interval)),baseCost(now).value_or(0)*10000));}- bool canAdmit(int64_t now,int64_t deadline,double elapsed,double present,bool warmingHistory=false,double queuedMs=0)const{+ // graceMs: how late the generated frame may still be shown; the caller+ // passes the bound presentation uses (liveGeneratedGrace100ns).+ bool canAdmit(int64_t now,int64_t deadline,double elapsed,double present,bool warmingHistory=false,double queuedMs=0,double graceMs=10)const{const auto cost=predicted(now,warmingHistory);// FG has not been submitted at admission. CPU time can at most cover// the base work; it must never erase the cost of future FG calls.const double queued=std::isfinite(queuedMs)?std::max(0.0,queuedMs):0.0;const double progress=std::clamp(elapsed,0.0,queued+baseCost(now).value_or(0));- const bool fits=double(deadline-now)/10000+10>=std::max(0.0,queued+cost.value_or(0)-progress)+std::max(0.0,present);+ const bool fits=double(deadline-now)/10000+graceMs>=std::max(0.0,queued+cost.value_or(0)-progress)+std::max(0.0,present);return fits;}- bool admit(int64_t now,int64_t deadline,double elapsed,double present,bool warmingHistory=false,double queuedMs=0){- return recordAdmission(canAdmit(now,deadline,elapsed,present,warmingHistory,queuedMs));+ bool admit(int64_t now,int64_t deadline,double elapsed,double present,bool warmingHistory=false,double queuedMs=0,double graceMs=10){+ return recordAdmission(canAdmit(now,deadline,elapsed,present,warmingHistory,queuedMs,graceMs));}// strictFirstOutput=false reproduces the 1.4.0 rule: only the whole group// against its last deadline. true additionally requires the first output to@@ -113,4 +115,25 @@ public:}bool recovering()const{return limited_&&recoveryPairs_>0;}};+// Live VFG keeps its A/B history across a skipped pair, so the next evaluation+// is not a warmup sample like a DLSS reseed, and it is not a steady sample+// either. Field log 2026-10-31 (RTX 5060 Ti, 4K30 VFG High): 23.1-23.6 ms when+// running continuously, 28.5 ms windowed and 39.6 ms fullscreen after skips,+// while the budget allowed about 25.9 ms. Each lone probe then measured over+// budget and rejected the next pair for 2 s: 30 fps for up to 76 s, until a+// settings change. The first evaluations after a skip therefore do not enter+// the FG estimate. A mode that really is too slow is still rejected by the+// first group after them, so a failed probe costs three groups per 2 s, not one.+class FgCostSettling {+ unsigned left_=0;+public:+ static constexpr unsigned kEvaluations=2;+ void reset(){left_=0;}+ // Call for each completed group in order; true when its FG time may be used.+ bool observe(bool skipped,bool evaluated){+ if(skipped){left_=kEvaluations;return false;}+ if(!evaluated||!left_)return true;+ --left_;return false;+ }+};}diff --git a/include/veyra/engine/LivePresentationTiming.h b/include/veyra/engine/LivePresentationTiming.hindex 0783bbb6..25245c81 100644--- a/include/veyra/engine/LivePresentationTiming.h+++ b/include/veyra/engine/LivePresentationTiming.h@@ -31,4 +31,24 @@ inline double livePairHoldMs(bool hasGenerated,double realPtsMs,double generatedif(!hasGenerated||!std::isfinite(realPtsMs)||!std::isfinite(generatedPtsMs))return 0;return std::clamp(realPtsMs-generatedPtsMs,0.0,1000.0/30.0);}+// How late a live generated frame is still worth showing: 10 ms, the bound the+// FG budget admits against. Near the refresh a dropped frame leaves a refresh+// repeating the last picture, so it stays useful until the next frame is due+// (60 Hz 2X: 16.2 ms). Never later: the real frame must not wait behind it.+inline constexpr int64_t kLiveGeneratedGrace100ns=100000,kLiveNextFrameMargin100ns=5000;+inline int64_t liveGeneratedGrace100ns(bool outputNearRefresh,int64_t outputInterval100ns){+ return outputNearRefresh?std::max(kLiveGeneratedGrace100ns,outputInterval100ns-kLiveNextFrameMargin100ns):kLiveGeneratedGrace100ns;+}+// One present of display capacity (explicit VSync): when a generated frame+// stops waiting for it. Above the refresh the queue is always full, so waiting+// only moves it into the scheduler and holds the real frame behind (DLSS 6X+// replay on 320 Hz: callback->present P95 18.4 -> 34.2 ms): half the interval,+// at most 2 ms. When the output fits, capacity comes back within a refresh and+// no backlog can build; giving up after 2 ms there dropped 3-4% of the generated+// frames of a 60 Hz 2X stream in bursts every 16.5 s (field log 2026-10-31), so+// it waits until the next frame is due.+inline bool liveGeneratedCapacityExpired(bool outputFitsRefresh,double waitedMs,double outputIntervalMs,int64_t now,int64_t nextDue){+ if(waitedMs<=std::min(2.0,outputIntervalMs/2))return false;+ return !outputFitsRefresh||now>=nextDue-kLiveNextFrameMargin100ns;+}}diff --git a/include/veyra/engine/PresentationSettings.h b/include/veyra/engine/PresentationSettings.hindex d85187db..fc66dfb1 100644--- a/include/veyra/engine/PresentationSettings.h+++ b/include/veyra/engine/PresentationSettings.h@@ -56,7 +56,9 @@ constexpr bool syncNvidiaLowLatencyQueue(PresentationSettings& p,bool nvidiaAdap// effective settings: inside the VRR range the panel starts a refresh when// the frame arrives, so the wait is about zero and nothing tears; above the// range the one-deep VSync queue holds (Microsoft documents VRR through the-// tearing flag, which only explicit Tearing may use).+// tearing flag, which only explicit Tearing may use). Automatic is reported as+// Vsync the same way while live frame generation runs near the refresh, where+// replacing is what loses frames (VideoPresenter::automaticQueueWanted).constexpr bool presentationVsync(const PresentationSettings& s) {return s.display==DisplaySync::Vsync;}diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 08123c08..b840925e 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -44,7 +44,7 @@ public:bool beginSourceInput();bool beginSourceProcessing();void sourceProcessed(pipeline::FrameIdentity);- PresentationSettings configurePresentation(gfx::D3D12DeviceContext&,PresentationSettings,bool fg,std::wstring& status);+ PresentationSettings configurePresentation(gfx::D3D12DeviceContext&,PresentationSettings,bool fg,std::wstring& status,bool outputNearRefresh=false);bool presentationReady(){return sink_.presentationReady();}bool waitPresentationReady(unsigned ms){return sink_.waitPresentationReady(ms);}uint64_t beginReflex(){const auto id=reflexInputFrame_;reflexInputFrame_=0;reflex_.renderStart(id);return id;}@@ -95,6 +95,15 @@ public:return requested.variableRefresh&&requested.display==DisplaySync::Automatic&&gfx::vrrLevel(vrr)>=3;}bool vrrSync()const{return vrrSync_;}+ // Live frame generation near the refresh (displayFgOutputNear): Automatic+ // presents through the one-deep VSync queue, because Present(0,0) would+ // replace a frame whose neighbour landed in the same refresh. With room for+ // each frame the wait is about zero: the frame still shows at the next+ // refresh. Output above the refresh keeps Present(0,0) and its low latency.+ static bool automaticQueueWanted(const PresentationSettings& requested,const gfx::VrrState& vrr,bool outputNearRefresh){+ return outputNearRefresh&&requested.display==DisplaySync::Automatic&&!vrrSyncWanted(requested,vrr);+ }+ bool automaticQueue()const{return automaticQueue_;}diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0,uint64_t epoch=0){gpuTimer_.collect(presentationFence_?presentationFence_.Get():f);if((revision&&gpuTimer_.last().identity.settingsRevision!=revision)||(epoch&&gpuTimer_.last().identity.epoch!=epoch)){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}// Application-side frame-generation timing for present-sink backends// (XeSS): the copies, barriers and provider prepare work recorded on@@ -176,7 +185,7 @@ private:bool xessWasEnabled_=false;bool xessFailed_=false;bool xessGenerationSuppressed_=false;- HMONITOR refreshMonitor_=nullptr;double refreshHz_=0;gfx::VrrState vrr_{};bool refreshQueried_=false,vrrSync_=false;+ HMONITOR refreshMonitor_=nullptr;double refreshHz_=0;gfx::VrrState vrr_{};bool refreshQueried_=false,vrrSync_=false,automaticQueue_=false;DisplayStateService* displayStates_=nullptr;uint64_t displayStateSerial_=0,displayGeneration_=0;// VRR presentation may start or stop after it is requested or when thediff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex 03e87288..68b5055f 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -125,7 +125,7 @@ public:// compositionMode: DXGI_FRAME_PRESENTATION_MODE (0 composed, 1 overlay,// 2 none, 3 composition failure), -1 when the query is unavailable.struct DisplayLatencySummary {- uint64_t samples=0;+ uint64_t samples=0,replacedAtLeast=0;double p50Ms=-1,p95Ms=-1,maxMs=-1;int compositionMode=-1;};@@ -217,7 +217,8 @@ private:struct PendingPresent { UINT id=0; int64_t qpc=0; bool replaceable=false; };std::array<PendingPresent,16> pendingPresents_{};unsigned pendingPresentNext_=0;- UINT lastDisplayedPresent_=0,lastSyncRefresh_=0;+ UINT lastDisplayedPresent_=0,lastSyncRefresh_=0,lastPresentRefresh_=0;+ uint64_t replacedPresents_=0;int64_t lastSyncQpc_=0;double refreshQpc_=0;bool displayLatencyEnabled_=true;diff --git a/qml/Veyra/ProPresentationRows.qml b/qml/Veyra/ProPresentationRows.qmlindex be1527e7..52bd8029 100644--- a/qml/Veyra/ProPresentationRows.qml+++ b/qml/Veyra/ProPresentationRows.qml@@ -10,7 +10,7 @@ ColumnLayout {spacing: 0VRow {label: qsTr("显示同步")- hint: qsTr("自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低 · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线")+ hint: qsTr("自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低(实时补帧输出接近刷新率时改排 1 帧,避免丢帧) · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线")VSeg {objectName: "presentation-display-sync"options: [{ id: "0", label: qsTr("允许撕裂") }, { id: "1", label: qsTr("垂直同步") }, { id: "2", label: qsTr("自动") }]diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex accc0150..9d03e75a 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -1137,6 +1137,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// VEYRA_TEST_DISPLAY_HZ=<hz> replaces the measured refresh for it.DisplayFgBudgetGate displayFgGate;static const double displayFgTestHz=[]{wchar_t v[16]{};return GetEnvironmentVariableW(L"VEYRA_TEST_DISPLAY_HZ",v,16)?std::clamp(_wtof(v),0.0,1000.0):0.0;}();+ // Live graph FG against the panel (DisplayFgBudget.h, LivePresentationTiming.h).+ // The near decision holds like the hint, so a wobbling rate cannot+ // reconfigure the presentation queue. VEYRA_TEST_LEGACY_NEAR_REFRESH=1+ // restores the earlier rules, including FgCostSettling, for A/B runs.+ DisplayFgBudgetGate nearRefreshGate;bool liveOutputFits=false,liveNearRefresh=false;+ static const bool legacyNearRefresh=GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_NEAR_REFRESH",nullptr,0)>0;+ FgCostSettling vfgCostSettling;+ uint64_t generatedDropDeadline=0,generatedDropCapacity=0,generatedDropCap=0;LivePairLatency pairLatency;const bool adaptiveCapturePhase=physicalCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_CAPTURE_PHASE",nullptr,0)==0;int64_t nextFgAdmissionLog=0,nextFgRejectionLog=0;@@ -1260,8 +1268,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// A reduced (2X) group must not lower the full-group FG// cost estimate, but its base cost is a normal sample -// see FgRecoveryBudget::complete. Only a history reset or- // an FG recovery is a warmup sample.- if(batch.batch.identity.settingsRevision==fgBudgetRevision)fgBudget.complete(watch.gpuExecutionMs,batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery,host100ns(),watch.fgExecutionMs,!batch.fgReduced);+ // an FG recovery is a warmup sample. See FgCostSettling for+ // the evaluations that follow a skipped live VFG pair.+ if(batch.batch.identity.settingsRevision==fgBudgetRevision){+ const bool settled=!isCapture||legacyNearRefresh||options.settings.frameGenerationBackend!=FrameGenerationBackend::Vfg||vfgCostSettling.observe(batch.fgCandidates>0&&batch.fgEvaluated==0,batch.fgEvaluated>0);+ fgBudget.complete(watch.gpuExecutionMs,batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery,host100ns(),watch.fgExecutionMs,!batch.fgReduced&&settled);+ }if(options.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&batch.batch.identity.settingsRevision==fgBudgetRevision){if(batch.historyReset)vfgOverload.reset();if(!batch.historyReset&&!batch.fgRecovery&&!batch.fgReduced&&batch.fgEvaluated+1==options.fgMultiplier)@@ -1334,7 +1346,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// (another monitor, a display change, 重新检测, the VRR// confirmation); a change re-applies.const bool vrrChanged=presenter.vrrSync()!=VideoPresenter::vrrSyncWanted(requested,presenter.displayVrr());- if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged&&!capRefreshChanged){+ const bool automaticQueueChanged=presenter.automaticQueue()!=VideoPresenter::automaticQueueWanted(requested,presenter.displayVrr(),liveNearRefresh);+ if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged&&!capRefreshChanged&&!automaticQueueChanged){// Reflex dropped out at runtime: the queue-depth part of the// low-latency setting stays, so only the status line changes.if(presentationEffective.nvidiaLowLatency!=NvidiaLowLatency::Off&&!presenter.reflexActive()&&presenter.reflexFailed()){@@ -1350,11 +1363,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}if(isImage){requested.enabled=false;requested.nvidiaLowLatency=NvidiaLowLatency::Off;}std::wstring message;- presentationEffective=presenter.configurePresentation(ctx,requested,options.fg,message);+ presentationEffective=presenter.configurePresentation(ctx,requested,options.fg,message,liveNearRefresh);presentationPaced=presenter.pacingActive()&&!legacyVsyncQueue;pacingRevision=revision;presenterGeneration=presenter.generation();pacingRefreshHz=refreshHz;cadence.reset();{std::lock_guard lock(mutex_);snapshot_.presentationEffective=presentationEffective;snapshot_.presentationRevision=revision;snapshot_.presentationStatus=message;snapshot_.presentationProviderOwned=presenter.providerOwnedPresentation();}- veyra::log::info("pacing",std::format("revision={} requested={}/{}/{} effective={}/{}/{} displayQueuePaced={} variableRefresh={} vrrLevel={} vrrSync={}",revision,requested.enabled,unsigned(requested.mode),unsigned(requested.display),presentationEffective.enabled,unsigned(presentationEffective.mode),unsigned(presentationEffective.display),presentationPaced,requested.variableRefresh,gfx::vrrLevel(presenter.displayVrr()),presenter.vrrSync()));+ veyra::log::info("pacing",std::format("revision={} requested={}/{}/{} effective={}/{}/{} displayQueuePaced={} variableRefresh={} vrrLevel={} vrrSync={} automaticQueue={}",revision,requested.enabled,unsigned(requested.mode),unsigned(requested.display),presentationEffective.enabled,unsigned(presentationEffective.mode),unsigned(presentationEffective.display),presentationPaced,requested.variableRefresh,gfx::vrrLevel(presenter.displayVrr()),presenter.vrrSync(),presenter.automaticQueue()));};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());}};@@ -2166,7 +2179,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,snextFgAdmissionLog=now+10000000;if(!admitted)nextFgRejectionLog=now+10000000;veyra::log::info("live-fg-admission",std::format("timeline={} revision={} source={} multiplier={} requestedMultiplier={} admitted={} admittedPairs={} rejectedPairs={} remainingDeadlineMs={:.3f} firstDeadlineMs={:.3f} queuedGpuMs={:.3f} predictedMs={:.3f} elapsedMs={:.3f} blitGpuP95Ms={:.3f} presentCpuP95Ms={:.3f} warmingHistory={} (CPU Present is backpressure, not added GPU cost; firstDeadlineMs=-1 when unused)",timeline,batch.identity.settingsRevision,batch.identity.sourceFrameId,previewFgMultiplier,options.fgMultiplier,admitted,fgAdmittedPairs,fgRejectedPairs,double(deadline-now)/10000,firstDeadline?double(firstDeadline-now)/10000:-1,queuedMs,fgBudget.predicted(now,warmingHistory).value_or(-1),elapsed,blit,livePresent.p95(),warmingHistory));};- if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();vfgOverload.reset();pairLatency.reset();fgBudgetRevision=options.settings.revision;displayFgGate.reset();}+ if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();vfgOverload.reset();vfgCostSettling.reset();pairLatency.reset();fgBudgetRevision=options.settings.revision;displayFgGate.reset();nearRefreshGate.reset();}previewFgMultiplier=options.fgMultiplier;// An output cap used to only drop candidates at present time, so// the GPU still generated frames that were thrown away: at 6X on@@ -2204,6 +2217,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,soptions.settings.revision,frameGenerationBackendName(options.settings.frameGenerationBackend),options.fgMultiplier,hint==0?std::string("none"):hint==1?std::string("off"):std::format("{}X",hint),contentFps*options.fgMultiplier,contentFps,refreshHz,displayFgTestHz>0?" (test override)":"",dedupActive,halfRate,unsigned(presentationEffective.display)));}}else displayFgGate.reset();+ // XeSS paces its own generated frames behind Present.+ const bool graphOutput=hinted&&!legacyNearRefresh&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend);+ const double outputFps=contentFps*previewFgMultiplier;+ liveOutputFits=graphOutput&&displayFgOutputFits(outputFps,refreshHz);+ if(!graphOutput)nearRefreshGate.reset();+ else if(contentFps>0&&refreshHz>0&&nearRefreshGate.update(displayFgOutputNear(outputFps,refreshHz)?1u:0u,host100ns()))+ veyra::log::info("fg-near-refresh",std::format("revision={} near={} outputFps={:.3f} refreshHz={:.3f}{} (near: Automatic uses the one-frame VSync queue, a generated frame stays valid until the next one is due)",options.settings.revision,nearRefreshGate.applied()==1,outputFps,refreshHz,displayFgTestHz>0?" (test override)":""));+ liveNearRefresh=graphOutput&&nearRefreshGate.valid()&&nearRefreshGate.applied()==1;std::lock_guard lock(mutex_);snapshot_.displayFgSuggestion=hinted&&displayFgGate.valid()?displayFgGate.applied():0u;snapshot_.displayFgRefreshHz=refreshHz;snapshot_.displayFgContentFps=contentFps;@@ -2223,6 +2244,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto legacyPairDelay=presentSinkFrameGeneration(options.settings.frameGenerationBackend)?0:liveInterval+processingAllowance;const auto pairDelay=adaptiveCapturePhase&&options.fg&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)?pairLatency.select(host100ns(),legacyPairDelay,liveInterval,previewFgMultiplier):legacyPairDelay;+ const auto generatedGrace=liveGeneratedGrace100ns(liveNearRefresh,liveInterval/std::max(1u,previewFgMultiplier));// DLSS can reseed after a skipped pair. XeSS// owns generation inside its presenter and has no graph admission.if(isCapture&&!rereadCached&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend)){@@ -2240,7 +2262,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto lastGenerated=pipeline::FrameBatch::interpolate(a,batch.b100ns,previewFgMultiplier-1,previewFgMultiplier);const auto now=host100ns(),deadline=liveTimeline.deadline(lastGenerated);const double elapsed=elapsedMs(processStart);- const bool admitted=fgBudget.admit(now,deadline,elapsed,presentP95,warmingHistory);+ const bool admitted=fgBudget.admit(now,deadline,elapsed,presentP95,warmingHistory,0,double(generatedGrace)/10000);logAdmission(batch,now,deadline,elapsed,presentP95,admitted,warmingHistory,pairAnchoredLive?(isStream?"decoded-pair":"capture-pair"):"continuous");return admitted?pipeline::EnhanceGraph::FgDecision::Evaluate:pipeline::EnhanceGraph::FgDecision::Skip;};@@ -2513,7 +2535,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#ifdef VEYRA_ENABLE_XBOX&xb,#endif- &seekDecoded,&seekStarted,&audio,&audioPipe,&audioStarted,&cadence,&ctx,&fileAudioAlignPending,&fileAwaitingVideo,&fileInputEnded,&playbackRate,&frameFlow,&graph,&host100ns,&isCapture,&isImage,&livePresent,&liveScheduler,&nextFgDeadlineLog,&nowMs,&options,&pendingCompletions,&physicalCapture,&presentEntryDeviation,&presentReturnDeviation,&presentationEffective,&presentationGeneration,&presentationSkippedGenerated,&presenter,&ring,&runSessionId,&seekPreviewPending,&traceFrame,&traceSubframes,watch,step,timeline,captureArrival,baselineReady,delayEnhanced,activeSeekId,lineage,jobGeneration,rereadCached,sourceIntervalMs,submitThenPresent,flow=frameFlow](int64_t now)->LiveGpuScheduler::Step{+ &seekDecoded,&seekStarted,&audio,&audioPipe,&audioStarted,&cadence,&ctx,&fileAudioAlignPending,&fileAwaitingVideo,&fileInputEnded,&generatedDropCap,&generatedDropCapacity,&generatedDropDeadline,&playbackRate,&frameFlow,&graph,&host100ns,&isCapture,&isImage,&livePresent,&liveScheduler,&nextFgDeadlineLog,&nowMs,&options,&pendingCompletions,&physicalCapture,&presentEntryDeviation,&presentReturnDeviation,&presentationEffective,&presentationGeneration,&presentationSkippedGenerated,&presenter,&ring,&runSessionId,&seekPreviewPending,&traceFrame,&traceSubframes,watch,step,timeline,captureArrival,baselineReady,delayEnhanced,activeSeekId,lineage,jobGeneration,rereadCached,sourceIntervalMs,submitThenPresent,generatedGrace,outputFitsRefresh=liveOutputFits,flow=frameFlow](int64_t now)->LiveGpuScheduler::Step{using State=LiveGpuScheduler::State;auto& batch=watch->output;auto& s=*step;auto updatePending=[&](LiveStepState*){unsigned left=0;for(unsigned i=s.next;i<batch.batch.count;++i)if(batch.batch.frames[i].kind!=pipeline::FrameKind::Generated||batch.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++left;@@ -2532,7 +2554,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0)return {State::Complete};const double itemPtsMs=double(item.pts100ns)/10000;const auto decisionTime=host100ns();- const bool generationExpired=generated&&(isCapture?timeline.expired(item.pts100ns,decisionTime,100000):!fileAwaitingVideo&&previewGeneratedExpired(nowMs(),itemPtsMs));+ const bool generationExpired=generated&&(isCapture?timeline.expired(item.pts100ns,decisionTime,generatedGrace):!fileAwaitingVideo&&previewGeneratedExpired(nowMs(),itemPtsMs));// B1: an XeSS real frame needs no CPU fence; the queue orders it.const bool early=submitThenPresent&&!generated&&!watch->ready;const auto readiness=previewFrameReadiness(item,comparisonMode_!=0||!generatedPresentationCurrent(jobGeneration,presentationGeneration.load()),generationExpired,[&]{return early||graph->resolveFrame(batch,s.next);});@@ -2554,8 +2576,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,snextFgDeadlineLog=decisionTime+10000000;const auto ready=watch->frameReadyObserved[s.next];veyra::log::info("fg-deadline",std::format("revision={} batch={} subframe={} expired={} readyObservedLateMs={:.3f} decisionLateMs={:.3f} observedReadyToDecisionMs={:.3f} batchReady={} (CPU fence observations, not scanout; -1 means readiness unknown)",item.identity.settingsRevision,batch.batch.batchId,item.subframe,generationExpired,ready?double(ready-timeline.deadline(item.pts100ns))/10000:-1,double(decisionTime-timeline.deadline(item.pts100ns))/10000,ready?double(decisionTime-ready)/10000:-1,watch->ready.load()));+ veyra::log::info("fg-drops",std::format("revision={} deadline={} capacity={} cap={} outputFitsRefresh={} graceMs={:.1f} (session totals of frames dropped before Present, by reason)",item.identity.settingsRevision,generatedDropDeadline,generatedDropCapacity,generatedDropCap,outputFitsRefresh,double(generatedGrace)/10000));}- if(readiness==PreviewFrameReadiness::Expired){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}+ if(readiness==PreviewFrameReadiness::Expired){++generatedDropDeadline;++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();s.capacityStart.reset();continue;}if(!s.deadlineStart)s.deadlineStart=Clock::now();if(isCapture){if(host100ns()<timeline.deadline(item.pts100ns))return {State::Pending,timeline.deadline(item.pts100ns)};}else if(!fileAwaitingVideo){@@ -2586,19 +2609,18 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// If the next candidate is due before this// slot, discard this stale display opportunity// instead of accumulating latency.- if(capInterval>0&&cadence.rateSkipsCandidate(optionalNow,mediaDeadline,interval,capInterval)){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}+ if(capInterval>0&&cadence.rateSkipsCandidate(optionalNow,mediaDeadline,interval,capInterval)){++generatedDropCap;++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}if(optionalNow<due)return {State::Pending,due};}// Explicit VSync: one present of display capacity per present, so a// frame never waits in DXGI's queue (true when not paced). A generated- // frame waits at most half its interval (<= 2 ms) and is otherwise- // replaced by the next one: waiting longer only moved the queue into- // this scheduler and held the real frame behind it (DLSS 6X replay- // on 320 Hz: callback->present P95 18.4 -> 34.2 ms). The real frame waits.+ // frame gives up as liveGeneratedCapacityExpired says and is replaced+ // by the next one. The real frame waits.if((!legacyVsyncQueue||presentationEffective.enabled||presentationEffective.outputRate==OutputRateMode::Custom)&&!presenter.presentationReady()){if(generated&&!legacyVsyncQueue){if(!s.capacityStart)s.capacityStart=Clock::now();- if(elapsedMs(*s.capacityStart)>std::min(2.0,sourceIntervalMs/std::max(1u,batch.batch.count)/2)){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();s.capacityStart.reset();continue;}+ const auto nextDue=outputFitsRefresh&&s.next+1<batch.batch.count?timeline.deadline(batch.batch.frames[s.next+1].pts100ns):optionalNow;+ if(liveGeneratedCapacityExpired(outputFitsRefresh,elapsedMs(*s.capacityStart),sourceIntervalMs/std::max(1u,batch.batch.count),optionalNow,nextDue)){++generatedDropCapacity;++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();s.capacityStart.reset();continue;}}return {State::Pending,optionalNow+2000};}diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex b666c39d..2bb7d387 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -451,7 +451,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&if(stats.supported)veyra::log::info("display-stats",std::format("refreshHz={:.3f} presentCalls={} dxgiPresentCount={} refreshes={} presentRefreshDelta={} presentsAhead={} backend={} (DXGI GetFrameStatistics delta over ~1s. These counters CANNOT tell how many frames the panel actually showed: with vsync off and tearing allowed, dxgiPresentCount tracks completed Present calls, and both refresh counters just advance with the monitor. presentsAhead = submitted presents after the last shown one at the sample: the display queue under VSync; with Automatic Present(0,0) it includes frames a newer one replaces; -1 unavailable. Measuring scanout needs PresentMon. XeSS generated presents are provider-internal.)",sink_.displayRefreshHz(),stats.presents,stats.displayed,stats.refreshes,stats.displayedRefresh,stats.ahead,sink_.xess()?"XeSS":"DXGI"));else if(FAILED(stats.result))veyra::log::info("display-stats",std::format("unavailable hr=0x{:X} backend={}",unsigned(stats.result),sink_.xess()?"XeSS":"DXGI"));const auto scanout=displayStats?sink_.takeDisplayLatency():gfx::PresentSink::DisplayLatencySummary{};- if(scanout.samples||scanout.compositionMode>=0)veyra::log::info("display-latency",std::format("presentToScanoutP50Ms={:.3f} presentToScanoutP95Ms={:.3f} presentToScanoutMaxMs={:.3f} samples={} compositionMode={} refreshHz={:.3f} (DXGI frame statistics: Present call to the vblank that showed it, VSync and Automatic DXGI presents; Automatic dates only frames named as shown; compositionMode 0 composed 1 overlay 2 none 3 failure -1 unknown; not a photon measurement)",scanout.p50Ms,scanout.p95Ms,scanout.maxMs,scanout.samples,scanout.compositionMode,sink_.displayRefreshHz()));+ if(scanout.samples||scanout.compositionMode>=0)veyra::log::info("display-latency",std::format("presentToScanoutP50Ms={:.3f} presentToScanoutP95Ms={:.3f} presentToScanoutMaxMs={:.3f} samples={} replacedAtLeast={} compositionMode={} refreshHz={:.3f} (DXGI frame statistics: Present call to the vblank that showed it, VSync and Automatic DXGI presents; Automatic dates only frames named as shown; compositionMode 0 composed 1 overlay 2 none 3 failure -1 unknown; not a photon measurement)",scanout.p50Ms,scanout.p95Ms,scanout.maxMs,scanout.samples,scanout.replacedAtLeast,scanout.compositionMode,sink_.displayRefreshHz()));const auto& timing=sink_.lastPresentTiming();veyra::log::info("present-cost",std::format("generated={} totalMs={:.3f} recordSubmitMs={:.3f} slotWaitMs={:.3f} dxgiMs={:.3f} slow={} source={} epoch={} backend={} resized={} resizeMs={:.3f} beginMs={:.3f} commandsMs={:.3f} beforeMs={:.3f} presentCallMs={:.3f} bufferMs={:.3f} afterMs={:.3f} hr=0x{:X}",generated,std::chrono::duration<double,std::milli>(presentEnd-presentStart).count(),@@ -501,7 +501,7 @@ void VideoPresenter::publishLiveCoverage(const HdrCurveSettings& curve,pipeline:void VideoPresenter::close(){metadataSent_=false;metadataDirty_=false;lastMetadata_={};sourceMetadata_={};metadataAttempt_={};hdrPeakInfo_={};- refreshMonitor_=nullptr;refreshHz_=0;vrr_={};refreshQueried_=false;vrrSync_=false;displayStateSerial_=0;vrrConfirmAt_.reset();+ refreshMonitor_=nullptr;refreshHz_=0;vrr_={};refreshQueried_=false;vrrSync_=false;automaticQueue_=false;displayStateSerial_=0;vrrConfirmAt_.reset();retainedFrame_.reset();xessInputId_=0;xessWork_={};xessWorkPosition_=0;reflex_.close();reflexFrame_=reflexInputFrame_=0;@@ -554,7 +554,7 @@ double VideoPresenter::displayRefreshHz(){if(const auto state=displayStates_->state(monitor);state&&state->serial!=displayStateSerial_)applyDisplayState(*state);return refreshHz_;}-PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContext& ctx,PresentationSettings requested,bool fg,std::wstring& status){+PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContext& ctx,PresentationSettings requested,bool fg,std::wstring& status,bool outputNearRefresh){// The NVIDIA choice only runs on an NVIDIA adapter, where it implies the// low queue. Another adapter keeps the plain switch's value; the UI retains// the choice for the next NVIDIA session (syncNvidiaLowLatencyQueue).@@ -608,9 +608,10 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContedisplayRefreshHz();const bool wasVrrSync=vrrSync_;vrrSync_=vrrSyncWanted(requested,vrr_);+ automaticQueue_=automaticQueueWanted(requested,vrr_,outputNearRefresh);// VRR presentation just started: ask the driver once more whether it runs.if(vrrSync_&&!wasVrrSync)vrrConfirmAt_=std::chrono::steady_clock::now()+std::chrono::seconds(3);- if(vrrSync_){requested.display=DisplaySync::Vsync;effective.display=DisplaySync::Vsync;}+ if(vrrSync_||automaticQueue_){requested.display=DisplaySync::Vsync;effective.display=DisplaySync::Vsync;}const bool vsync=presentationVsync(requested),tearing=presentationTearing(requested);providerOwnedPresentation_=xessActive();// The interface translates this line piece by piece at " · " and ";"@@ -620,8 +621,8 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContefor(const auto& piece:pieces)if(!piece.empty())line+=(line.empty()?L"":L" · ")+piece;return line;};- const std::wstring syncMode=vrrSync_?L"显示同步:自动 + 可变刷新":requested.display==DisplaySync::Automatic?L"显示同步:自动":vsync?L"显示同步:垂直同步":L"显示同步:允许撕裂";- const std::wstring syncDetail=vrrSync_?(gfx::vrrLevel(vrr_)>=4?L"屏幕跟着画面刷新,不撕裂":L"已请求,等待驱动确认"):requested.display==DisplaySync::Automatic?L"不撕裂,也不等待垂直同步(延迟最低)":L"";+ const std::wstring syncMode=vrrSync_?L"显示同步:自动 + 可变刷新":automaticQueue_?L"显示同步:自动(补帧接近刷新率)":requested.display==DisplaySync::Automatic?L"显示同步:自动":vsync?L"显示同步:垂直同步":L"显示同步:允许撕裂";+ const std::wstring syncDetail=vrrSync_?(gfx::vrrLevel(vrr_)>=4?L"屏幕跟着画面刷新,不撕裂":L"已请求,等待驱动确认"):automaticQueue_?L"屏幕队列 1 帧,避免丢帧":requested.display==DisplaySync::Automatic?L"不撕裂,也不等待垂直同步(延迟最低)":L"";if(!reflexDisabled){effective.enabled=false;effective.nvidiaLowLatency=NvidiaLowLatency::Off;sink_.configurePacing(false,vsync,tearing);status=join({L"英伟达低延迟撤销失败,请关闭视频后重试",syncMode,syncDetail});return effective;}if(xessActive()){// The provider owns Present for its generated frames, so neither the@@ -647,7 +648,7 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConte// there would throttle presents to the refresh, the wait they avoid.const bool paced=vsync&&sink_.configurePacing(true,vsync,tearing);const bool restored=paced||sink_.configurePacing(false,vsync,tearing);- const std::wstring queue=paced?(vrrSync_?L"可变刷新:超过屏幕最高刷新时只排 1 帧":L"垂直同步:屏幕队列 1 帧,读帧前等待刷新"):vsync?L"垂直同步:屏幕队列控制不可用":restored?L"":L"显示队列恢复失败";+ const std::wstring queue=paced?(vrrSync_?L"可变刷新:超过屏幕最高刷新时只排 1 帧":automaticQueue_?L"":L"垂直同步:屏幕队列 1 帧,读帧前等待刷新"):vsync?L"垂直同步:屏幕队列控制不可用":restored?L"":L"显示队列恢复失败";std::wstring cap;if(followDisplay)cap=std::format(L"输出上限:跟随显示器 {:.0f} Hz",requested.customFps);else if(requested.outputRate==OutputRateMode::Custom)cap=std::format(L"输出上限:{:.3f} FPS",requested.customFps);diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex 16fc5d8b..061dd1ad 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -300,7 +300,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,frameStatisticsBaseValid_=false;// New swap chain: present ids restart; VEYRA_TEST_NO_DISPLAY_STATS=1 disables the samples.displayLatencyEnabled_=GetEnvironmentVariableW(L"VEYRA_TEST_NO_DISPLAY_STATS",nullptr,0)==0;- pendingPresents_={};lastDisplayedPresent_=0;lastSyncRefresh_=0;lastSyncQpc_=0;refreshQpc_=0;displayLatencyMs_.clear();+ pendingPresents_={};lastDisplayedPresent_=0;lastSyncRefresh_=0;lastPresentRefresh_=0;replacedPresents_=0;lastSyncQpc_=0;refreshQpc_=0;displayLatencyMs_.clear();log::info("display-refresh",std::format("monitor refresh={:.3f} Hz at swapchain creation (0 = unknown); submissions above this rate cannot all be scanned out",displayRefreshHz_));log::info("present", std::format("present-sink: window {}x{} swapEffect={} buffers=3 vsync={} tearing={} captureCompatible={} (capture not verified)",width_, height_, actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL?"flip-sequential":"flip-discard", desc_.vsync ? 1 : 0, (desc_.tearing && tearingSupported_) ? 1 : 0, desc.captureCompatible));@@ -480,6 +480,14 @@ void PresentSink::sampleDisplayLatency(){if(stats.PresentCount==lastDisplayedPresent_)return;const UINT previous=lastDisplayedPresent_;lastDisplayedPresent_=stats.PresentCount;+ // One refresh shows one new present, so presents beyond the refreshes+ // between two shown frames were replaced unseen: Present(0,0) loses them+ // with every other counter still reading full rate (field log 2026-10-31).+ if(previous&&stats.PresentCount>previous&&stats.PresentRefreshCount>=lastPresentRefresh_){+ const UINT presents=stats.PresentCount-previous,refreshes=stats.PresentRefreshCount-lastPresentRefresh_;+ if(presents>refreshes)replacedPresents_+=presents-refreshes;+ }+ lastPresentRefresh_=stats.PresentRefreshCount;const double period=refreshQpc_>0?refreshQpc_:displayRefreshHz_>=1?frequency/displayRefreshHz_:0;if(period<=0||stats.SyncRefreshCount<stats.PresentRefreshCount||stats.SyncRefreshCount-stats.PresentRefreshCount>16)return;const double scanout=double(stats.SyncQPCTime.QuadPart)-double(stats.SyncRefreshCount-stats.PresentRefreshCount)*period;@@ -505,6 +513,7 @@ void PresentSink::sampleDisplayLatency(){}PresentSink::DisplayLatencySummary PresentSink::takeDisplayLatency(){DisplayLatencySummary summary;+ summary.replacedAtLeast=replacedPresents_;replacedPresents_=0;auto& values=displayLatencyMs_;if(!values.empty()){std::sort(values.begin(),values.end());diff --git a/tests/integration/PresentationPacingTests.cpp b/tests/integration/PresentationPacingTests.cppindex b93729ee..854da71f 100644--- a/tests/integration/PresentationPacingTests.cpp+++ b/tests/integration/PresentationPacingTests.cpp@@ -11,7 +11,7 @@ static HWND movingInput(){WNDCLASSW wc{};wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraPacingInput";wc.lpfnWndProc=[](HWND w,UINT m,WPARAM a,LPARAM b)->LRESULT{if(m==WM_TIMER){InvalidateRect(w,nullptr,FALSE);return 0;}- if(m==WM_PAINT){PAINTSTRUCT ps;auto dc=BeginPaint(w,&ps);RECT r;GetClientRect(w,&r);FillRect(dc,&r,(HBRUSH)GetStockObject(BLACK_BRUSH));const LONG x=LONG(GetTickCount64()/4%600);RECT bar{x,0,x+40,r.bottom};FillRect(dc,&bar,(HBRUSH)GetStockObject(WHITE_BRUSH));EndPaint(w,&ps);return 0;}+ if(m==WM_PAINT){PAINTSTRUCT ps;auto dc=BeginPaint(w,&ps);RECT r;GetClientRect(w,&r);FillRect(dc,&r,(HBRUSH)GetStockObject(BLACK_BRUSH));const LONG x=LONG(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/1000%2400/4);RECT bar{x,0,x+40,r.bottom};FillRect(dc,&bar,(HBRUSH)GetStockObject(WHITE_BRUSH));EndPaint(w,&ps);return 0;}return DefWindowProcW(w,m,a,b);};RegisterClassW(&wc);@@ -23,7 +23,18 @@ int wmain(int argc,wchar_t** argv){using namespace veyra::engine;using Clock=std::chrono::steady_clock;if(argc==2&&std::wstring(argv[1])==L"--capture-input"){auto w=movingInput();const auto end=Clock::now()+std::chrono::seconds(240);- while(IsWindow(w)&&Clock::now()<end){MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}std::this_thread::sleep_for(std::chrono::milliseconds(2));}+ // A chosen capture rate needs a window that changes faster than the+ // limit: the 16 ms message timer alone delivers about 30 fps under it.+ const bool repaint=GetEnvironmentVariableW(L"VEYRA_TEST_SCREEN_FPS",nullptr,0)>0;+ HANDLE timer=CreateWaitableTimerExW(nullptr,nullptr,CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,TIMER_ALL_ACCESS);+ while(IsWindow(w)&&Clock::now()<end){+ MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}+ if(repaint&&IsWindow(w)){InvalidateRect(w,nullptr,FALSE);UpdateWindow(w);}+ LARGE_INTEGER due;due.QuadPart=-20000;+ if(timer&&SetWaitableTimer(timer,&due,0,nullptr,nullptr,FALSE))WaitForSingleObject(timer,10);+ else std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ if(timer)CloseHandle(timer);if(IsWindow(w))DestroyWindow(w);return w?0:2;}// media, evidence directory, mode(-1=off), display(0..2), multiplier, seconds, lifecycle/replay/xess@@ -31,10 +42,12 @@ int wmain(int argc,wchar_t** argv){const int mode=_wtoi(argv[3]),display=_wtoi(argv[4]),multiplier=_wtoi(argv[5]),seconds=std::clamp(_wtoi(argv[6]),3,120);if(mode< -1||mode>2||display<0||display>2)return 2;const std::wstring scenario=argc>7?argv[7]:L"";- // latency-screen[-sr]: a live 60 fps window capture for capture-to-present- // A/B runs. mode -1 off, 0 low queue only, 1 NVIDIA 开, 2 NVIDIA 开+增强.+ // latency-screen[-sr|-vfg]: a live window capture, 60 fps unless+ // VEYRA_TEST_SCREEN_FPS says otherwise (near-refresh A/B: 53 fps x 6 = 318+ // on 320 Hz), for capture-to-present A/B runs. mode -1 off, 0 low queue+ // only, 1 NVIDIA 开, 2 NVIDIA 开+增强.const bool latency=scenario.starts_with(L"latency-");- const bool screen=scenario==L"screen-xess"||scenario==L"screen-dlss"||latency;+ const bool screen=scenario==L"screen-xess"||scenario==L"screen-dlss"||scenario==L"screen-vfg"||latency;const bool xess=scenario==L"xess"||scenario==L"screen-xess"||scenario==L"native-xess";if(scenario==L"legacy"){if(mode!=-1)return 2;SetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_SWAPCHAIN",L"1");}std::filesystem::path dir=argv[2];std::filesystem::create_directories(dir);@@ -72,7 +85,7 @@ int wmain(int argc,wchar_t** argv){if(!inputWindow)std::this_thread::sleep_for(std::chrono::milliseconds(10));}if(!inputWindow){TerminateProcess(inputProcess.hProcess,2);WaitForSingleObject(inputProcess.hProcess,1000);CloseHandle(inputProcess.hProcess);return 2;}- veyra::source::ScreenCaptureOptions input;input.target=reinterpret_cast<uint64_t>(inputWindow);input.fps=latency?60:30;input.cursor=false;+ veyra::source::ScreenCaptureOptions input;input.target=reinterpret_cast<uint64_t>(inputWindow);input.fps=30;if(latency){wchar_t fps[16]{};input.fps=GetEnvironmentVariableW(L"VEYRA_TEST_SCREEN_FPS",fps,16)?std::clamp(_wtoi(fps),10,240):60;}input.cursor=false;sourcePath=input.uri();}MONITORINFOEXW monitor{};monitor.cbSize=sizeof(monitor);GetMonitorInfoW(MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST),&monitor);@@ -86,7 +99,7 @@ int wmain(int argc,wchar_t** argv){if(native){p.nvidiaLowLatency=mode<0?NvidiaLowLatency::Off:mode==2?NvidiaLowLatency::Boost:NvidiaLowLatency::On;engine.requestPresentation(p);}if(latency){p.nvidiaLowLatency=mode==1?NvidiaLowLatency::On:mode==2?NvidiaLowLatency::Boost:NvidiaLowLatency::Off;engine.requestPresentation(p);}EnhancementSettings effects;effects.multiplier=unsigned(multiplier);if(xess)effects.frameGenerationBackend=FrameGenerationBackend::XeSS;- if(scenario==L"native-vfg")effects.frameGenerationBackend=FrameGenerationBackend::Vfg;+ if(scenario==L"native-vfg"||scenario==L"latency-screen-vfg"||scenario==L"screen-vfg")effects.frameGenerationBackend=FrameGenerationBackend::Vfg;if(scenario==L"native-fsr")effects.frameGenerationBackend=FrameGenerationBackend::Fsr;if(scenario==L"effects"||scenario==L"native-effects"){effects.nr=true;effects.sr=true;effects.srTarget=veyra::pipeline::SrTarget::Qhd;}if(scenario==L"latency-screen-sr"){effects.sr=true;effects.srTarget=veyra::pipeline::SrTarget::Uhd4K;}@@ -112,6 +125,7 @@ int wmain(int argc,wchar_t** argv){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;+ {std::string status(4096,char(0));status.resize(std::max(0,WideCharToMultiByte(CP_UTF8,0,last.presentationStatus.c_str(),-1,status.data(),int(status.size()),nullptr,nullptr)-1));std::cout<<"presentationStatus="<<status<<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>first.generated,"real provider generated frames during measurement");if(scenario==L"effects"||scenario==L"native-effects")check(last.nrActive&&last.srActive&&last.nrEvaluated>first.nrEvaluated,"NR and SR remain active with pacing");diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cppindex 460a9223..3de64fd8 100644--- a/tests/unit/LiveGpuSchedulerTests.cpp+++ b/tests/unit/LiveGpuSchedulerTests.cpp@@ -154,6 +154,48 @@ int main(){check(budget.predicted(50000003,true)==7,"rejected reset without FG cannot become a warmup timing sample");check(!budget.admit(50000002,49800002,1.217,.047,true),"cheap recovery cannot bypass an expired deadline");check(budget.predicted(60000002,true)==budget.predicted(60000002),"expired recovery measurement falls back to steady estimate");+ {+ veyra::engine::FgCostSettling settling;+ check(settling.observe(false,true),"continuous evaluations enter the FG estimate");+ check(!settling.observe(true,false)&&!settling.observe(false,true)&&!settling.observe(false,true)&&settling.observe(false,true),"the first two evaluations after a skip stay out of it");+ settling.observe(true,false);+ check(settling.observe(false,false)&&!settling.observe(false,true),"a group without FG does not use up the settling evaluations");+ settling.reset();check(settling.observe(false,true),"settings revision reset clears settling");+ // Field log 2026-10-31, 4K30 VFG High on an RTX 5060 Ti: base 3.4 ms with FG and+ // 1.45 ms without, 23.1 ms running continuously, 39.6 ms (fullscreen) or 28.5 ms+ // (window) after skips. One second of FG at 33 ms starts it, as a hiccup did.+ // Returns the evaluated pairs of the last 20 s out of 60 s (600 pairs at most).+ const auto replay=[](double continuous,double isolated,bool settle,double graceMs,unsigned& maxPer2s){+ veyra::engine::FgRecoveryBudget replayBudget;veyra::engine::FgCostSettling cost;+ const int64_t interval=333667;+ bool previous=true;unsigned evaluated=0,window=0;maxPer2s=0;+ for(unsigned n=0;n<1800;++n){+ const int64_t now=100000000+n*interval;+ const auto allowance=replayBudget.processingAllowance(now,interval);+ const bool admitted=replayBudget.admit(now,now+interval/2+allowance-5000,.2,.45,false,0,graceMs);+ const bool comparable=!settle||cost.observe(!admitted,admitted);+ if(admitted){const double fg=n<30?33:previous?continuous:isolated;replayBudget.complete(3.4+fg,true,false,now+int64_t(fg*10000),fg,comparable);}+ else replayBudget.complete(1.45,false,false,now+14500);+ previous=admitted;+ if(n>=1200){evaluated+=admitted;window+=admitted;if(n%60==59){maxPer2s=std::max(maxPer2s,window);window=0;}}+ }+ return evaluated;+ };+ unsigned per2s=0;+ const auto trapped=replay(23.1,39.6,false,10,per2s);+ printf("VFG trap replay: earlier rule %u of 600 pairs evaluated, most in 2 s %u\n",trapped,per2s);+ check(trapped<=20,"replay: counting the lone probe keeps VFG at 30 fps");+ const auto recoveredFull=replay(23.1,39.6,true,10,per2s);+ printf("VFG trap replay: fullscreen %u of 600\n",recoveredFull);+ check(recoveredFull==600,"replay: fullscreen probes at 39.6 ms recover full FG");+ check(replay(23.1,28.5,true,10,per2s)==600,"replay: windowed probes at 28.5 ms recover full FG");+ const auto overload=replay(46,46,true,10,per2s);+ printf("VFG trap replay: really too slow %u of 600, most in 2 s %u\n",overload,per2s);+ check(overload<=40&&per2s<=4,"replay: a mode that really is too slow stays rejected with a bounded probe");+ check(replay(29,29,false,10,per2s)<=20,"replay: 29 ms misses the 10 ms bound");+ check(replay(29,29,true,16.18,per2s)==600,"replay: near a 60 Hz refresh 29 ms still reaches the next frame's due time");+ check(replay(34,34,true,16.18,per2s)<=40,"replay: near the refresh a group longer than the input interval stays rejected");+ }veyra::engine::LivePairLatency phase;check(phase.select(10000000,420000,333333,4)==420000,"unknown live readiness keeps legacy phase");for(int i=0;i<8;++i)phase.observe(10000000+i,370000);diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cppindex a0775f4e..989c77b3 100644--- a/tests/unit/LivePresentationTimingTests.cpp+++ b/tests/unit/LivePresentationTimingTests.cpp@@ -149,6 +149,47 @@ int main(){check(livePairHoldMs(true,1e12,0)<=1000./30,"timestamp jump has bounded hold");check(livePairHoldMs(true,10,20)==0,"backwards PTS cannot sleep negatively");check(livePairHoldMs(true,std::numeric_limits<double>::infinity(),0)==0,"nonfinite PTS rejected");+ {+ using veyra::engine::liveGeneratedGrace100ns;+ check(liveGeneratedGrace100ns(false,166667)==100000,"away from the refresh a generated frame keeps 10 ms");+ check(liveGeneratedGrace100ns(true,166667)==161667,"60 Hz 2X stays useful until 0.5 ms before the next frame is due");+ check(liveGeneratedGrace100ns(true,31447)==100000,"a short output interval never shortens the 10 ms bound");+ using veyra::engine::liveGeneratedCapacityExpired;+ check(!liveGeneratedCapacityExpired(false,1.3,2.78,0,0)&&liveGeneratedCapacityExpired(false,1.5,2.78,0,0),"above the refresh 6X waits half its interval");+ check(!liveGeneratedCapacityExpired(false,1.9,16.7,0,0)&&liveGeneratedCapacityExpired(false,2.1,16.7,0,0),"above the refresh the wait stays at most 2 ms");+ check(!liveGeneratedCapacityExpired(true,5,16.7,1000000,1100000),"output that fits keeps waiting 10 ms before the next frame is due");+ check(liveGeneratedCapacityExpired(true,5,16.7,1095000,1100000),"output that fits gives up 0.5 ms before the next frame is due");+ check(!liveGeneratedCapacityExpired(true,1,16.7,2000000,1100000),"a frame that only just started waiting keeps the earlier floor");+ // A one-deep queue on 60.005 Hz fed with the field log's pairs (29.972 fps,+ // arrival sd about 1.9 ms). A present flips at the next refresh, which is+ // when capacity returns. Polls every 0.2 ms as the scheduler does. 100 ns units.+ struct Replay{unsigned pairs=0,drops=0;double maxRealWait=0;};+ const auto replay=[](bool fits,double hz,double fps,double sd){+ const double refresh=1e7/hz,interval=1e7/fps;+ Replay r;uint32_t seed=7;+ const auto gauss=[&]{double sum=0;for(int i=0;i<12;++i){seed=seed*1664525u+1013904223u;sum+=double(seed>>8)/double(1u<<24);}return (sum-6)*sd;};+ double free=-1e18,last=0;+ for(unsigned n=0;n<6000;++n){+ const double real=n*interval+gauss()+interval+34000,generated=real-interval/2;+ ++r.pairs;+ double start=std::max(generated,last);bool dropped=false;+ for(double t=start;t<free;t+=2000)+ if(liveGeneratedCapacityExpired(fits,(t-start)/10000,interval/2/10000,int64_t(t),int64_t(real))){dropped=true;break;}+ if(dropped)++r.drops;+ else{start=std::max(start,free);last=start;free=(std::floor(start/refresh)+1)*refresh;}+ start=std::max(real,last);+ const double presented=std::max(start,free);+ r.maxRealWait=std::max(r.maxRealWait,(presented-real)/10000);+ last=presented;free=(std::floor(presented/refresh)+1)*refresh;+ }+ return r;+ };+ const auto before=replay(false,60.0049,29.9722,18700),after=replay(true,60.0049,29.9722,18700);+ printf("near-refresh replay: drops %u -> %u of %u pairs, max real wait %.2f -> %.2f ms\n",before.drops,after.drops,after.pairs,before.maxRealWait,after.maxRealWait);+ check(before.drops*100>=before.pairs,"field-rate replay: the 2 ms rule drops at least 1% of the pairs");+ check(after.drops==0,"field-rate replay: no generated frame is dropped when it may wait for the next due time");+ check(after.maxRealWait<=1000/60.0049,"field-rate replay: the real frame waits at most one refresh");+ }{// PictureCompare.h: a sample repeats the last new picture only when every// component of the whole picture is within the capture-noise band.diff --git a/tests/unit/RealtimePreviewSchedulingTests.cpp b/tests/unit/RealtimePreviewSchedulingTests.cppindex ae1781fe..ace1ff44 100644--- a/tests/unit/RealtimePreviewSchedulingTests.cpp+++ b/tests/unit/RealtimePreviewSchedulingTests.cpp@@ -159,6 +159,12 @@ int main() {check(displayFgSuggestion(B::Dlss, 6, 0, 60) == 0 && displayFgSuggestion(B::Dlss, 6, 60, 0) == 0, "unknown rates suggest nothing");check(displayFgSuggestion(B::Dlss, 1, 60, 60) == 0, "no generation requested: no hint");check(displayFgSuggestion(B::Dlss, 6, 60, 100, true) == 1, "under VSync 60 fps on 100 Hz suggests off: the surplus would wait");+ check(displayFgOutputNear(60, 60) && displayFgOutputNear(59.9444, 60.0049) && displayFgOutputNear(61, 60), "30 fps 2X is near a 60 Hz panel, within the hint's 2% tolerance");+ check(!displayFgOutputFits(360, 320) && !displayFgOutputNear(360, 320), "DLSS 6X above 320 Hz keeps the rules tuned for it");+ check(displayFgOutputNear(318, 320) && displayFgOutputNear(240, 320), "MFG close to a 320 Hz panel is near");+ check(displayFgOutputFits(120, 320) && !displayFgOutputNear(120, 320), "60 fps 2X on 320 Hz fits but is far from the refresh");+ check(displayFgOutputFits(60, 120) && !displayFgOutputNear(60, 120), "30 fps 2X on 120 Hz is not near: the model loses nothing there");+ check(!displayFgOutputFits(0, 60) && !displayFgOutputFits(60, 0) && !displayFgOutputNear(std::nan(""), 60), "unknown rates select no rule");check(displayFgSuggestion(B::Dlss, 2, 60, 100, true) == 1, "under VSync 2X at 60 fps on 100 Hz suggests off");check(displayFgSuggestion(B::Dlss, 6, 60, 320, true) == 4, "under VSync a fitting lower multiplier is suggested");check(displayFgSuggestion(B::Dlss, 2, 30, 60, true) == 0, "under VSync a fitting request: no hint");diff --git a/tests/unit/UiLanguageTests.cpp b/tests/unit/UiLanguageTests.cppindex f8404d46..1ae312fa 100644--- a/tests/unit/UiLanguageTests.cpp+++ b/tests/unit/UiLanguageTests.cpp@@ -40,6 +40,9 @@ int main(int argc, char** argv) {expect(i18n::text(QStringLiteral("英伟达低延迟不可用,当前使用低排队(详见日志) · 输出上限:关闭 · 垂直同步:屏幕队列 1 帧,读帧前等待刷新 · 显示同步:垂直同步")),QStringLiteral("NVIDIA Low Latency unavailable; using low queue depth (see the log) · Output cap: off · VSync: 1-frame display queue, waits for refresh before reading a frame · Display sync: VSync"),"presentation fallback status pieces");+ expect(i18n::text(QStringLiteral("英伟达低延迟:关 · 显示同步:自动(补帧接近刷新率) · 屏幕队列 1 帧,避免丢帧")),+ QStringLiteral("NVIDIA Low Latency: Off · Display sync: auto (frame generation near refresh rate) · 1-frame display queue to avoid dropped frames"),+ "near-refresh status pieces");// Unknown text and paths come back unchanged.expect(i18n::text(QStringLiteral("D:/视频/我的片子.mkv")), QStringLiteral("D:/视频/我的片子.mkv"), "path untouched");