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++
Finish Claude's low-latency frame pacing and VFG auto regulation
Veyra Goal Agent6e79a5e01c5c
diff --git a/AGENTS.md b/AGENTS.mdindex 679b8035..c04b1d01 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,8 @@# Veyra Agent 工作规则-> **2026-10-31 本地main整合(最新)**:用户要求把各分支修复合入main并处理兼容。main现含英伟达低延迟三档、RX7000 NR、补帧接近刷新率修复、屏幕采集无补帧扣留修复、屏幕捕获帧率、采集载波Dolby/DTS、F7/F8、60→30取第一份。Lecram两线和AverMedia诊断存档未并入。活动树在main,下面各段“不合并main”到此结束;未push/Release,正式版仍2.1.1。回执E:/项目/Veyra/reports/claude-main-integration-20261031/FINAL.json。RX7000实卡、真实60 Hz屏/采集卡/5060 Ti、PS5载波音频未验证。+> **2026-11-01 补帧延迟不增长返工(最新)**:用户不接受10-31修复的延迟增长。分支`claude/fg-no-latency-growth-20261101`(基于main 13016a8,未合并、未push/Release)撤掉自动模式队列、长等待和放宽的VFG预算,改平滑呈现锚点,VFG 2X赶不上刷新时这一对改用下一档模型。真实60 Hz实测见docs/FG_NO_LATENCY_GROWTH_2026-11-01.md,回执E:/项目/Veyra/reports/claude-fg-sidefx-20261101/FINAL.json。`VEYRA_TEST_LEGACY_LIVE_PACING=1`恢复旧规则。真实采集卡和5060 Ti未验证,5060 Ti速度是人为加延迟模拟的。++> **2026-10-31 本地main整合**:用户要求把各分支修复合入main并处理兼容。main现含英伟达低延迟三档、RX7000 NR、补帧接近刷新率修复、屏幕采集无补帧扣留修复、屏幕捕获帧率、采集载波Dolby/DTS、F7/F8、60→30取第一份。Lecram两线和AverMedia诊断存档未并入。活动树在main,下面各段“不合并main”到此结束;未push/Release,正式版仍2.1.1。回执E:/项目/Veyra/reports/claude-main-integration-20261031/FINAL.json。RX7000实卡、真实60 Hz屏/采集卡/5060 Ti、PS5载波音频未验证。> **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。diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex f5835fab..e29843d1 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -1340,7 +1340,7 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.add(L"BUTTON",L"AMD 性能档 · 光流宽高各减半",215,BS_AUTOCHECKBOX|WS_TABSTOP,1,12,306,-1,36);combo(204,1,350,{L"NR / DLSS光流 · 性能",L"NR / DLSS光流 · 平衡",L"NR / DLSS光流 · 质量"});add(L"STATIC",L"内容节奏",1114,0,1,12,394,-1,24);- combo(205,1,422,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});+ combo(205,1,422,{L"采用源时间戳",L"自动剔除重复帧",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});add(L"STATIC",L"AMD FidelityFX 为运动估算;不是 AMD NR。XeSS 为实验预览 2X,不支持导出。",1110,0,1,12,426,-1,72);add(L"STATIC",L"采集音频同步",1115,0,1,12,608,-1,26);combo(216,1,644,{L"自动同步 · 软件估算",L"手动声音偏移",L"关闭补偿"});diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.mdindex 8db15ae9..bc49a751 100644--- a/docs/CURRENT_STATUS.md+++ b/docs/CURRENT_STATUS.md@@ -1,6 +1,8 @@# 当前项目状态-更新:2026-10-31。这里只描述现在;历史过程见[历史索引](history/INDEX.md)。+更新:2026-11-01。这里只描述现在;历史过程见[历史索引](history/INDEX.md)。++**2026-11-01 补帧延迟不增长返工(分支,未合并)**:用户不接受 10-31 修复的延迟增长,分支 `claude/fg-no-latency-growth-20261101` 撤掉了自动模式队列、长等待和放宽的 VFG 预算,改用平滑呈现锚点。VFG 2X 在生成帧赶不上刷新时,这一对改用下一档模型。真实 60 Hz 实测:模拟 5060 Ti 速度的高档,自动模式显示 43→59.2 帧/秒,垂直同步 58.2→60.0;从采集时钟线算的呈现延迟不升反降。代价是显存多约 1.9 GB,慢显卡上高档约三分之二的对用中档。main 仍是下面的队列版本。见[执行记录](FG_NO_LATENCY_GROWTH_2026-11-01.md)。未在真实采集卡和 5060 Ti 上验证。**2026-10-31 本地 main 整合**:用户要求把各分支修复合入 main 并处理兼容,活动树现在 main,未 push/Release,正式版仍 2.1.1。本次并入:英伟达低延迟三档、RX 7000 NR、补帧接近刷新率修复、屏幕采集无补帧扣留修复、屏幕捕获帧率、采集载波 Dolby/DTS、F7/F8、60→30 取第一份。未并入:Lecram 两条暂停线和 AverMedia 诊断存档。冲突、兼容修正和回归结果见 [WORKLOG](WORKLOG.md) 最后一节,回执 `E:/项目/Veyra/reports/claude-main-integration-20261031/FINAL.json`。diff --git a/docs/FG_60HZ_PACING_2026-10-31.md b/docs/FG_60HZ_PACING_2026-10-31.mdindex 43be14d8..a0864e5a 100644--- a/docs/FG_60HZ_PACING_2026-10-31.md+++ b/docs/FG_60HZ_PACING_2026-10-31.md@@ -1,5 +1,7 @@# 补帧在接近刷新率时的间歇掉帧(2026-10-31)+> **2026-11-01:本文的队列、长等待和放宽预算已被撤销**,用户不接受延迟增长。现行规则和真实 60 Hz 实测见 [FG_NO_LATENCY_GROWTH_2026-11-01.md](FG_NO_LATENCY_GROWTH_2026-11-01.md)。下面保留当时的诊断和记录,标“更正”的数字是原文算错的。+用户提供现场日志 `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`。## 诊断结论@@ -24,7 +26,7 @@## 代价-- 自动模式在接近刷新率时不再“永不等待”。320 Hz 实测捕获到呈现 P50 差 ≤0.3 ms,P95 为 0 至 +1.8 ms。60 Hz 模型里真实帧最多多等 8–13 ms,P99 为 2–6.7 ms。+- 自动模式在接近刷新率时不再“永不等待”。320 Hz 实测捕获到呈现 P50 差 ≤0.3 ms,P95 为 0 至 +1.8 ms。60 Hz 模型里真实帧最多多等 8–13 ms,P99 为 2–6.7 ms。(更正:模型把刚好落在刷新边界的呈现算早了一个刷新,数字偏低。修正后比值 0.999 时 P95 3.5、P99 5.7、最多 10.2 ms;比值 1.001 时 P50 4.4、P95 12.6、P99 14.5、最多 16.2 ms。)- 60 Hz 2X 的 VFG 成本上限约从 25.9 ms 放宽到 32.1 ms。成本落在这段时以前退回 30 fps,现在保持 60 fps,真实帧最多晚一次刷新。- 真的跑不动的模式,每 2 秒探测从 1–2 组变为 3 组(回放:600 对中评估 30 对,2 秒内最多 3 对)。@@ -49,8 +51,8 @@- 高于刷新率(回放 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(窗口与全屏探测成本都恢复)。+- 60 Hz 模型 `sim_near.py`(29.972×2 对 60.005 Hz,占所有帧):自动 3.19%→0,垂直同步 1.09%→0;生成帧迟到时 19.07%/0.55%→0。(更正:旧垂直同步应为 1.50%,生成帧迟到时 1.49%。)+- 单元回放:垂直同步 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 错误。diff --git a/docs/FG_NO_LATENCY_GROWTH_2026-11-01.md b/docs/FG_NO_LATENCY_GROWTH_2026-11-01.mdnew file mode 100644index 00000000..0f7ad04e--- /dev/null+++ b/docs/FG_NO_LATENCY_GROWTH_2026-11-01.md@@ -0,0 +1,99 @@+# 补帧 60 Hz 修复返工:延迟不增长(2026-11-01)++用户看完 10-31 修复的连带问题后要求:“全部都修复,并且保持好低延迟,延迟增长是我不能接受的”。之后又要求“VFG 的问题也要解决”,并把本机显示器调到 60 Hz 让我重测。++分支 `claude/fg-no-latency-growth-20261101`,基于 main `13016a8`。未 merge、未 push、未 Release。证据在 `E:/项目/Veyra/reports/claude-fg-sidefx-20261101`,表格是其中的 `hz60-summary.txt`。++## 撤掉的++10-31 版(`docs/FG_60HZ_PACING_2026-10-31.md`)靠等待换不丢帧,这些全部撤销:++- 自动模式接近刷新率时改走一帧队列(`automaticQueueWanted`、状态文字和提示里的说明)。这条同时带走了等待对象回退的 bug。+- 垂直同步下生成帧等到下一帧到期(`liveGeneratedCapacityExpired`)。+- 迟到容忍和 VFG 预算放宽到 16.2 ms(`liveGeneratedGrace100ns`、`graceMs`),这是 29–32 ms 翻转区的来源。+- `displayFgOutputFits/Near`、`kDisplayFgNearRatio`、`[fg-near-refresh]`。++## 现在的规则++| 项 | 规则 | 范围 |+|---|---|---|+| 呈现锚点 | 源 PTS 加跟踪的偏移(`LiveArrivalSmoother`),二阶,时钟差无滞后,再提前 0.5 ms。单个离群回调不动基线,同侧连续两个才跟过去 | 物理和屏幕采集、图内补帧。串流、内容去重、XeSS 不变 |+| 准入与到期 | 预算和 `LivePairLatency` 仍按回调;生成帧到期按“平滑到期和回调到期中较晚者 + 10 ms” | 同上 |+| 垂直同步容量等待 | `min(间隔/2, clamp(2-(间隔-5)/12, 1, 2))`:60 Hz 2X 约 1 ms,高刷 MFG 仍是原来的 2 ms 规则 | 同上;其他来源仍是 `min(2, 间隔/2)` |+| VFG 自动调控(界面开关,默认开) | 这一对帧的生成帧会赶不上刷新(`liveFramesShareRefresh`)或预算不够时,改用下一档模型:高→中,中→低 | 实时 2X、物理和屏幕采集、显存预算余量 ≥4.3 GB。可变刷新和允许撕裂只保留预算这条。低档和 3X 以上开关置灰 |+| VFG 成本 | 连续 1 秒没跑过选定模型后,前 2 次按预热样本记。探测失败后隔 2、4、8 秒重试 | 实时 VFG |++`VEYRA_TEST_LEGACY_LIVE_PACING=1` 恢复 10-31 之前的规则。++用户要求:“这个功能的话,放到VFG的参数里面吧,叫做VFG自动调控”。列表页和节点页的“VFG 质量”下面各有一个开关(`EnhancementSettings::vfgAutoRegulate`),和“DLSS 性能模式”一样存在界面偏好里,不进预设。关闭后不加载第二个模型,不占那约 1.9 GB。切换会重建补帧图,帧率短暂下降几秒,和改 VFG 质量一样。测试程序用 `VEYRA_TEST_VFG_NO_AUTO_REGULATE=1` 关它。++同时按用户要求把“内容节奏”里的“自动识别内容节奏”改名为“自动剔除重复帧”(en: Remove duplicate frames automatically),只改文字,行为和存档值不变。“内容节奏”这一行的标题没动。++新日志:`[live-anchor]`、`[vfg-fast]`(两种模型各跑了多少对、各自耗时)、`[vfg-probe]`、`[display-latency] replacedAtLeast`、`[fg-drops]`。++## 为什么 VFG 高档会丢 20–30%++生成帧要等 B 到达后再算,真实帧的呈现时刻上限是一个输入间隔加基础处理。所以模型耗时超过半个输入间隔(30 fps 时 16.7 ms)时,生成帧和真实帧的间隔就短于一次刷新。5060 Ti 跑高档约 23 ms,两帧只隔约 7–10 ms。相位落在两帧之间没有刷新的区间时,真实帧替换生成帧,画面掉到 30 fps,持续几秒,随 16.5 秒拍频循环。++丢帧比例约等于 `(刷新间隔 - 两帧间隔) / 刷新间隔 / 2`,和实测对得上。等下一次刷新能保住它,但真实帧要多等最多一次刷新,这就是被否掉的延迟增长。所以改成换模型:中档快约 4–5 倍,在这些相位来得及。++## 真实 60 Hz 实测++条件:本机 RTX 5070、2560×1440 屏调到 60.000 Hz(用户自己调的)。4K 片源按采集卡节奏送入:自身时钟偏 800 ppm、回调抖动 1.9 ms、自适应相位。输出 59.7/s,每轮 14 秒。“5060 Ti 速度”是在 VFG 工作线程上给高档加 9.4 ms、中档加 2.8 ms,生成帧就绪 26 ms,与现场日志一致。++自动模式:++| 档位 | 规则 | 显示帧/秒 | 最差一秒 | 真实帧呈现 平均/P95(距采集时钟线)ms | 回调→呈现 P95 ms |+|---|---|---|---|---|---|+| 高档,5060 Ti 速度 | 旧 | 43.0 | 31 | 34.04 / 37.65 | 34.43 |+| | 新,不带快模型 | 41.3 | 30 | 33.54 / 34.30 | 36.33 |+| | 新 | **59.2** | 57 | 33.53 / 34.30 | 36.32 |+| 高档,本机速度 | 旧 | 56.7 | 49 | 34.05 / 37.62 | 34.43 |+| | 新 | **58.5** | 55 | 33.53 / 34.36 | 36.31 |+| 中档 | 旧 | 57.6 | 53 | 22.27 / 25.59 | 22.52 |+| | 新 | **58.8** | 52 | 21.73 / 22.33 | 24.51 |++垂直同步:++| 档位 | 规则 | 显示帧/秒 | 最差一秒 | 真实帧呈现 平均/P95 ms | 呈现→扫描 P50 ms |+|---|---|---|---|---|---|+| 高档,5060 Ti 速度 | 旧 | 58.2 | 55 | 37.12 / 44.01 | 14.61 |+| | 新 | **60.0** | 60 | 33.54 / 34.34 | 8.38 |+| 中档 | 旧 | 59.0 | 57 | 22.31 / 25.64 | 9.22 |+| | 新 | **59.8** | 59 | 21.75 / 22.52 | 7.62 |++- 高档 5060 Ti 速度一轮里,选定模型跑了 118–128 对,快模型 235–246 对,启动时预算又用了 60 对。本机速度只有 24 对(另加启动 60 对)。+- 真实 VFG 超预算(4K 超分 + 高档 + 8X,320 Hz):失败探测按 2、4、8、8… 秒重试;60 fps 下 40 秒内评估 37→20 组,呈现 P50/P95 17.37/18.32→16.84/17.23 ms。这个结果来自加快模型之前的版本;8X 不加载快模型。++自动模式的“显示帧/秒”来自 `[display-latency] samples`,是下限。`replacedAtLeast` 抓不到“真实帧替换迟到生成帧”这种情况,不能再当丢帧数看。++## 代价++- **高档不再总是高档。** 慢显卡上约三分之二的对用中档,随拍频成段切换。快显卡基本不受影响。切换是否肉眼可见没有验证。+- **显存多约 1.9 GB**(本机 3973→5834 MB),预算余量不足 4.3 GB 时不加载,退回只跑选定模型。加载多 0.2–0.5 秒。+- **软件自己的“回调→呈现”P95 高约 2 ms。** 回调时刻本身抖,提前到的帧要等基线。从采集时钟线算 P95 低约 3 ms,平均低 0.5 ms。这是口径差异,但界面上的数字确实变大。+- 自动模式的中档还会丢约 1.5%(58.8/59.7),回调迟到超过低档省下的时间时救不回来。++## 其他 320 Hz 结果(修复抖动钩子前的一轮)++- 无注入抖动的窗口采集,22 组 ×3 次:捕获→呈现 P50 低 0–0.6 ms,P95 持平或更低(最差高 0.04 ms)。+- 第一轮带抖动的两组数据作废:钩子在引擎线程上空转,挡住了调度器。P99 的差异也不算数,每轮开头约 13 帧慢 10 ms,新旧规则都有。修好后的整轮没有跑完,只完成 1 组:捕获→呈现 P50/P95 24.39/28.09→23.70/25.31,回调 P95 20.97→22.08。++## 回归++60 Hz 屏上:cpu2 12/0,QtQuick 123/0/1 跳过,启动无 QML 错误,lifecycle 2/0,gpu 20/0(VFG、DLSS 6X、FSR、XeSS、过载)。live 5/1:`--source-gap` 的 EOF 快照失败,同一项在未改动的 main 上 3 次也只过 1 次。翻译 2715 条无缺失。RX 7000 / lmxxf 合同未重跑,没动 NR 代码。++开关与改名:真实程序两次启动(私有配置)。默认开;高档 2X 可用,低档和 4X 置灰;关闭后重启仍是关;中文和英文都显示新名称;无 QML 错误,截图 `reports/claude-fg-sidefx-20261101/ui-edit.png`。运行中开→关→开各成功一次,日志里加载了 2 次快模型、建了 3 次图。开关这轮屏幕已被用户调回 320 Hz:开时加载快模型,关时不加载。节点页的开关只验证到页面能加载,没有点过。之后重跑 cpu、cpu2、qml、smoke、lifecycle 全部通过;gpu 和 live 没有重跑,这次只加了设置字段和判断条件。++## 未验证++- **没有真实采集卡和 RTX 5060 Ti。** “5060 Ti 速度”是人为加延迟,基础处理没有变慢,两帧间隔比现场短(7 ms 对 10 ms)。+- 现场日志里全屏时单次高档 39.6 ms 的现象本机不能复现。若快模型跑着时显卡仍降频,高档的恢复可能更慢,结果是更多对用中档,不会丢帧。+- 选定模型与快模型切换时的画质跳变。+- 没有在可变刷新屏和 144/240 Hz 上跑快模型。++## 重跑++`E:/项目/Veyra/reports/claude-fg-sidefx-20261101/tools/verify.py`:`hz60 slow 9.4`(旧/新无快模型)、`hz60 fast 9.4`、`hz60 plainfast`、`ab plain|field|vfg|vfgfield|vfgover [次数]`。片源用 ffmpeg 从 `nr-1080p30.mp4` 转到 29.87 fps 4K(命令见 WORKLOG)。环境变量:`VEYRA_TEST_REPLAY_AS_CARD`、`VEYRA_TEST_ARRIVAL_JITTER_MS`、`VEYRA_TEST_ADAPTIVE_SCREEN_PHASE`、`VEYRA_TEST_VFG_DELAY_MS`。++现场看 `[vfg-fast]` 和 `[display-latency] samples`,别看提交 FPS。diff --git a/docs/README.md b/docs/README.mdindex 0265131f..f4bfdca0 100644--- a/docs/README.md+++ b/docs/README.md@@ -2,6 +2,8 @@日常只从这些入口开始:+进行中(分支,未合并):[补帧延迟不增长返工](FG_NO_LATENCY_GROWTH_2026-11-01.md)。+最近并入本地 main(未发布):[补帧接近刷新率的间歇掉帧](FG_60HZ_PACING_2026-10-31.md)、[英伟达低延迟三档](NVIDIA_LOW_LATENCY_2026-10-28.md)、[RX 7000 NR](AMD_RDNA3_NR_PLAN_2026-10-29.md)、[屏幕捕获与采集音频](CAPTURE_FPS_AUDIO_REPORT_2026-10-27.md)。1. [当前项目状态](CURRENT_STATUS.md):正式版、活动工作、暂停项、现场问题及验收边界。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 726c562f..b579c7d5 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -284,3 +284,38 @@ RTX5060Ti、4K30 NV12→VFG2X/60Hz,主要稳定段NR/SR关闭。中档84.016未解决:屏幕捕获真实程序60上限接收59.8–60.0、处理57.0–57.4(3次),120上限60.0/60.0。10-27分支测得60.0/60.0,限速器代码与该分支逐字相同;此后驱动从32.0.16.1656变为32.0.16.2101,2.1.1正式版今天也从53.55/53.72变为56.27/55.27。推断来自环境(合成时间戳抖动),但没有在今天的环境单独构建分支对比,原因未证实。未验:RX7000实卡推理/画质/性能;真实60 Hz屏、采集卡、RTX 5060 Ti;PS5加采集卡的载波音频;串流;打包。未重跑8K最终输出+NR+VFG危险组合。++## 2026-11-01 补帧延迟不增长返工与 VFG 快模型++用户:“全部都修复,并且保持好低延迟,延迟增长是我不能接受的”;后来“我现在把我显示器调整到60hz了,你重新短测一下,而且VFG高档为什么会掉百分之20?VFG的问题也要解决”。分支claude/fg-no-latency-growth-20261101,基于main 13016a8;未提交、未合并、未push/Release。记录docs/FG_NO_LATENCY_GROWTH_2026-11-01.md,回执reports/claude-fg-sidefx-20261101/FINAL.json。++改动:撤掉自动模式队列、长等待、放宽的VFG预算;LiveArrivalSmoother平滑呈现锚点(提前0.5 ms);垂直同步容量等待随输出间隔变化;VFG 2X赶不上刷新或预算不够时这一对改用下一档模型(显存预算余量≥4.3 GB才加载);FgCostSettling改为空转1秒后才记预热、失败探测2/4/8秒重试。更正10-31记录里算错的三组数字(模型把落在刷新边界的呈现算早了一个刷新)。++命令:tmp/claude-fg-sidefx-20261101/build/build.py(并发2);verify.py stage/cpu/cpu2/qml/smoke/lifecycle/gpu/live/hz60/ab,脚本已复制到报告tools。片源:`ffmpeg -i tests/nr-manual-scale-20261024/media/nr-1080p30.mp4 -t 26 -vf fps=29.87,scale=3840:2160:flags=bilinear -an -c:v h264_nvenc -preset p1 -b:v 40M -pix_fmt yuv420p card-4k.mp4`;4.6K用hevc_nvenc。++失败与修正:+- 第一个抖动钩子在引擎线程空转,挡住调度器,VFG 30×2回调P50假增1.9 ms;两组数据作废,改为等待时继续advanceLive。+- 单个离群回调会把基线带偏十几帧;改为同侧连续两个才跟随。+- P99“增长”来自每轮开头约13帧慢10 ms,新旧规则都有;统计改为跳过开头。+- 垂直同步容量等待固定1 ms在320 Hz实测丢3–6%呈现且P99无收益;改为随间隔变化。+- 快模型第一版几乎全程跑中档:高档耗时估计卡在启动时的39 ms,且新探测全被当预热不计;改为取低包络,4秒没跑过就按七折试一次,结果高档/快模型128/235对。+- 第一版4K高档在本机只要约16 ms,复现不出丢帧;在VFG工作线程加9.4 ms模拟5060 Ti。+- 用户中途叫停一轮约26分钟的320 Hz全量A/B:“为什么跑那么久?我没时间和你耗”。最终代码的320 Hz全量A/B未跑完(1/22组)。++真实60 Hz结果(每项1轮14秒,自动模式显示帧/秒是下限):模拟5060 Ti速度高档,自动43.0→59.2,垂直同步58.2→60.0;本机速度高档自动56.7→58.5;中档自动57.6→58.8,垂直同步59.0→59.8。真实帧呈现距采集时钟线的P95:34.30对37.65,34.34对44.01,22.33对25.59,22.52对25.64。回调→呈现P95高约2 ms。显存3973→5834 MB。++回归(60 Hz屏):cpu2 12/0;qml 123/0/1跳过;smoke无QML错误;lifecycle 2/0;gpu 20/0;live 5/1,--source-gap的EOF快照失败,同一项在未改动的main上3次也只过1次。cpu里7项无参数报用法错误,由cpu2带参数跑。翻译2715条无缺失。全量构建只有veyra_fsr_probe/veyra_fsr_upscale_probe因缺本地SDK失败(原有)。++空间:tests/claude-fg-sidefx-20261101 868 MB(含片源295 MB),tmp 98 MB,日志1.7 MB,报告0.75 MB。++未验:真实采集卡、真实5060 Ti、全屏下高档单次39.6 ms现象、模型切换的可见程度、可变刷新和144/240 Hz上的快模型。++## 2026-11-01 VFG 自动调控开关与“自动剔除重复帧”改名++用户:“这个功能的话,放到VFG的参数里面吧,叫做VFG自动调控,然后还有一个自动识别内容节奏这个东西,很多人搞不懂是啥意思,你给改成自动剔除重复帧”。同一分支,未提交。++改动:EnhancementSettings::vfgAutoRegulate(默认开,存界面偏好,不进预设,切换重建图);列表页和节点页加开关,低档和3X以上置灰;“自动识别内容节奏”改名(QML、Status、Chain、旧版SettingsWindow、四语翻译),只改文字。翻译2718条无缺失。++验证:tmp/claude-fg-sidefx-20261101/regulate_ui.py 真实程序两次启动,默认开、置灰条件、重启保持、中英文新名称都通过,截图 reports/claude-fg-sidefx-20261101/ui-edit.png。hz60 toggle 运行中开→关→开通过。cpu2 12/0,qml 123/0/1跳过,smoke、lifecycle通过。gpu、live未重跑。全量构建340秒,只有两个fsr探针因缺SDK失败(原有)。++注意:用户中途把屏幕调回320 Hz,所以开关这轮是320 Hz,hz60-on/off/toggle.json 的文件名不代表60 Hz,看里面的refreshHz。60 Hz丢帧数据仍是上一节那轮。节点页开关没有点过。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 2b044123..4e064f13 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -2065,6 +2065,13 @@"en": "VFG takes about %1 ms per frame; about %2X holds at the current load","ja": "VFG は 1 枚あたり約 %1 ms、現在の負荷で安定するのは約 %2X"},+ {+ "zh": "VFG 自动调控",+ "src": "qml/NodePage.qml",+ "zh-TW": "VFG 自動調控",+ "en": "VFG auto regulation",+ "ja": "VFG 自動調整"+ },{"zh": "VFG 质量","src": "qml/NodePage.qml",@@ -6546,6 +6553,13 @@"en": "Live capture","ja": "ライブキャプチャー"},+ {+ "zh": "实时采集 2X 时,当前档来不及赶上屏幕刷新,这一对帧就改用下一档,不丢帧也不加延迟。多占约 2 GB 显存,显存不够时不生效",+ "src": "qml/NodePage.qml",+ "zh-TW": "即時擷取 2X 時,目前檔位來不及趕上螢幕更新,這一對幀就改用下一檔,不掉幀也不增加延遲。多占約 2 GB 顯示記憶體,不足時不生效",+ "en": "During live capture at 2X, when the current level cannot make the screen refresh, that frame pair uses the next faster level: no dropped frame and no added latency. Uses about 2 GB more VRAM; does nothing when VRAM is short",+ "ja": "ライブキャプチャーの 2X で現在の品質が画面のリフレッシュに間に合わないとき、そのフレーム対だけ一段速い品質を使います。フレーム落ちも遅延の増加もありません。VRAM を約 2 GB 多く使い、足りないときは無効です"+ },{"zh": "实时预览,设置对所有文件生效","src": "qml/SubtitleSettingsDialog.qml",@@ -7155,13 +7169,6 @@"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",@@ -8072,6 +8079,13 @@"en": "The engine did not accept the DLSS performance mode; the previous setting is kept","ja": "エンジンが DLSS パフォーマンスモードを受け付けませんでした。元の設定を維持します"},+ {+ "zh": "引擎未接受 VFG 自动调控,原设置保留",+ "src": "src/ui/bridge/FrameGeneration.cpp",+ "zh-TW": "引擎未接受 VFG 自動調控,原設定保留",+ "en": "The engine did not accept VFG auto regulation; the previous setting is kept",+ "ja": "エンジンが VFG 自動調整を受け付けませんでした。元の設定を維持します"+ },{"zh": "引擎未接受光流配置,原设置保留","src": "src/ui/bridge/Status.cpp",@@ -10411,13 +10425,6 @@"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",@@ -12330,11 +12337,11 @@"ja": "ゲームモード:マウス透過を解除"},{- "zh": "游戏锁 30/40 帧、采集卡输出 60 帧时选“自动识别内容节奏”:只去掉与上一张完全相同的画面,补帧时间均匀;“采集 60→30”固定每两帧取一帧,稳定 30 帧",+ "zh": "游戏锁 30/40 帧、采集卡输出 60 帧时选“自动剔除重复帧”:只去掉与上一张完全相同的画面,补帧时间均匀;“采集 60→30”固定每两帧取一帧,稳定 30 帧","src": "qml/ProPage.qml",- "zh-TW": "遊戲鎖 30/40 幀、擷取卡輸出 60 幀時選“自動識別內容節奏”:只去掉與上一張完全相同的畫面,補幀時間均勻;“擷取 60→30”固定每兩幀取一幀,穩定 30 幀",- "en": "For a game locked to 30/40 fps behind a 60 fps capture card, choose \"Detect content pacing automatically\": only pictures identical to the previous one are dropped and generated frames stay evenly timed; \"Capture 60→30\" always keeps every second frame for a steady 30",- "ja": "ゲームが 30/40 fps 固定でキャプチャーカードが 60 fps を出力する場合は「コンテンツのペーシングを自動判別」を選択:直前とまったく同じ映像だけを除き、補間フレームの間隔を均一にします。「キャプチャー 60→30」は常に 2 フレームごとに 1 フレームを取り、30 fps で安定させます"+ "zh-TW": "遊戲鎖 30/40 幀、擷取卡輸出 60 幀時選“自動剔除重複幀”:只去掉與上一張完全相同的畫面,補幀時間均勻;“擷取 60→30”固定每兩幀取一幀,穩定 30 幀",+ "en": "For a game locked to 30/40 fps behind a 60 fps capture card, choose \"Remove duplicate frames automatically\": only pictures identical to the previous one are dropped and generated frames stay evenly timed; \"Capture 60→30\" always keeps every second frame for a steady 30",+ "ja": "ゲームが 30/40 fps 固定でキャプチャーカードが 60 fps を出力する場合は「重複フレームを自動で除去」を選択:直前とまったく同じ映像だけを除き、補間フレームの間隔を均一にします。「キャプチャー 60→30」は常に 2 フレームごとに 1 フレームを取り、安定した 30 fps にします"},{"zh": "源 %1 fps",@@ -13974,6 +13981,13 @@"en": "Auto estimate: applies to live capture card / PS5 input","ja": "自動推定:キャプチャーカード / PS5 のライブ入力時に有効"},+ {+ "zh": "自动剔除重复帧",+ "src": "qml/NodePage.qml",+ "zh-TW": "自動剔除重複幀",+ "en": "Remove duplicate frames automatically",+ "ja": "重複フレームを自動で除去"+ },{"zh": "自动去隔行","src": "qml/SettingsPage.qml",@@ -14044,13 +14058,6 @@"en": "Detect input automatically · Native BMD","ja": "入力信号を自動検出 · BMD ネイティブ"},- {- "zh": "自动识别内容节奏",- "src": "qml/NodePage.qml",- "zh-TW": "自動識別內容節奏",- "en": "Detect content pacing automatically",- "ja": "コンテンツのペーシングを自動判別"- },{"zh": "自动调控力度","src": "qml/NrLayerEditor.qml",@@ -14101,11 +14108,11 @@"ja": "自動(負荷に応じて)"},{- "zh": "自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低(实时补帧输出接近刷新率时改排 1 帧,避免丢帧) · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线",+ "zh": "自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低 · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线","src": "qml/ProPresentationRows.qml",- "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-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": "自动(独立显卡)",diff --git a/include/veyra/engine/DisplayFgBudget.h b/include/veyra/engine/DisplayFgBudget.hindex f34cc158..05adf1c9 100644--- a/include/veyra/engine/DisplayFgBudget.h+++ b/include/veyra/engine/DisplayFgBudget.h@@ -24,23 +24,6 @@ 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/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex c1a65cd9..28587f43 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -399,6 +399,10 @@ struct EnhancementSettings {// UI "DLSS 性能模式": NVIDIA's DLSS-G performance mode (ngx/DlssgLite.h),// DLSS frame generation only. A global control kept in shell preferences.bool dlssgLite=false;+ // UI "VFG 自动调控": live 2X VFG runs a pair with the next faster model when the+ // chosen one would miss its refresh or the budget (LivePresentationTiming.h).+ // A global control kept in shell preferences.+ bool vfgAutoRegulate=true;ContentRate content=ContentRate::Transport;AudioSyncMode audioSync=AudioSyncMode::Automatic;int32_t audioOffsetMs=0;@@ -471,6 +475,7 @@ struct EnhancementSettings {if(!(multiplier>1&&frameGenerationBackend==FrameGenerationBackend::XeSS&&motionUsesFlow(fgMotion,frameGenerationBackend)))active.fgMotionRefine=defaults.fgMotionRefine;if(!(multiplier>1&&frameGenerationBackend==FrameGenerationBackend::Dlss))active.dlssgLite=defaults.dlssgLite;+ if(!(multiplier>1&&frameGenerationBackend==FrameGenerationBackend::Vfg))active.vfgAutoRegulate=defaults.vfgAutoRegulate;return active;}bool sameActiveVideoParameters(const EnhancementSettings& other) const {diff --git a/include/veyra/engine/FgRecoveryBudget.h b/include/veyra/engine/FgRecoveryBudget.hindex aa05b799..0933ae94 100644--- a/include/veyra/engine/FgRecoveryBudget.h+++ b/include/veyra/engine/FgRecoveryBudget.h@@ -69,19 +69,17 @@ 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));}- // 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{+ bool canAdmit(int64_t now,int64_t deadline,double elapsed,double present,bool warmingHistory=false,double queuedMs=0)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+graceMs>=std::max(0.0,queued+cost.value_or(0)-progress)+std::max(0.0,present);+ const bool fits=double(deadline-now)/10000+10>=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,double graceMs=10){- return recordAdmission(canAdmit(now,deadline,elapsed,present,warmingHistory,queuedMs,graceMs));+ 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));}// strictFirstOutput=false reproduces the 1.4.0 rule: only the whole group// against its last deadline. true additionally requires the first output to@@ -115,25 +113,40 @@ 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+// Live VFG keeps its A/B history across skipped pairs, so the evaluation that+// ends a long skip is no DLSS-style warmup, and it is not a steady sample either.+// Field log 2026-10-31 (RTX 5060 Ti, 4K30 VFG High): 23.1-23.6 ms running+// continuously, 28.5 ms windowed and 39.6 ms fullscreen after 2 s or more of+// skipping, while the budget allowed about 25.9 ms. Each lone probe 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.+// settings change. After a second without an evaluation the next two are warmup+// samples, so they raise neither the FG nor the base estimate. One skipped pair+// changes nothing. A mode that really is too slow is rejected by the group after+// them, so a probe costs three groups where it cost one: failed probes retry+// after 2, 4, then every 8 s, where the budget alone would retry every 2 s.class FgCostSettling {- unsigned left_=0;+ int64_t lastEvaluated_=0,holdUntil_=0;+ unsigned left_=0,recorded_=0,failures_=0;+ bool probing_=false;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;+ static constexpr int64_t kIdle100ns=10000000,kRetry100ns=20000000;+ static constexpr unsigned kEvaluations=2,kProbeGroups=4,kMaxDoublings=2;+ void reset(){*this=FgCostSettling{};}+ // Call for each completed group in order; true marks a warmup sample.+ bool observe(bool skipped,bool evaluated,int64_t now){+ if(skipped){+ if(probing_){probing_=false;left_=0;holdUntil_=now+(kRetry100ns<<failures_);failures_=std::min(failures_+1,kMaxDoublings);}+ return false;+ }+ if(!evaluated)return false;+ const bool idle=lastEvaluated_&&now-lastEvaluated_>=kIdle100ns;+ lastEvaluated_=now;+ if(idle){left_=kEvaluations;recorded_=0;probing_=true;}+ if(left_){--left_;return true;}+ if(probing_&&++recorded_>=kProbeGroups){probing_=false;failures_=0;}+ return false;}+ bool holding(int64_t now)const{return now<holdUntil_;}+ int64_t holdUntil()const{return holdUntil_;}};}diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.hindex 39ac5045..71fdfb40 100644--- a/include/veyra/engine/GraphDescription.h+++ b/include/veyra/engine/GraphDescription.h@@ -177,7 +177,7 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,constdesc.flowQuality=settings.flow;desc.contentRate=settings.content;desc.opticalFlowBackend=settings.opticalFlowBackend;- desc.amdFlowHalfResolution=settings.amdFlowHalfResolution;desc.fgMotionRefine=settings.fgMotionRefine;desc.dlssgLite=settings.dlssgLite;+ desc.amdFlowHalfResolution=settings.amdFlowHalfResolution;desc.fgMotionRefine=settings.fgMotionRefine;desc.dlssgLite=settings.dlssgLite;desc.vfgAutoRegulate=settings.vfgAutoRegulate;desc.nrLayersExtent.clear();for(uint32_t i=0;i<chain.nodeCount;++i){auto& node=chain.nodes[i];diff --git a/include/veyra/engine/LivePresentationTiming.h b/include/veyra/engine/LivePresentationTiming.hindex 94817c3b..80352166 100644--- a/include/veyra/engine/LivePresentationTiming.h+++ b/include/veyra/engine/LivePresentationTiming.h@@ -36,24 +36,73 @@ 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);}+// Presentation anchor of a live FG pair. A capture callback jitters where the+// picture does not: field log 2026-10-31 (4K30 on USB) has callbacks with sd+// 1.9-2.6 ms against device PTS steady to the microsecond, 800 ppm off the host+// clock. Anchored to its own callback each pair carries that jitter to the panel,+// where a real frame and the next generated frame then share a refresh and one+// of them is replaced: at 59.94 fps on 60.005 Hz 3.5% of all frames, nearly all+// of them real. The anchor is PTS plus a tracked offset to the callback, second+// order so that a clock difference in either direction leaves no lag: its mean+// stays on the mean callback, so it moves single frames and never adds delay.+// Capture-to-panel latency then keeps its mean and loses tail. The latency this+// application reports starts at the callback and would read 0.6 ms higher at P95+// only because its start point jitters; kLead100ns keeps it where it was, for+// 0.5% more late generated frames (reports/claude-fg-sidefx-20261101/sim_final).+// One callback beyond min(interval/3, 8 ms) does not move the line; a second on+// the same side moves it there at once. The FG budget, generated-frame expiry+// and LivePairLatency stay on the callback itself.+class LiveArrivalSmoother {+ double offset_=0,drift_=0,jitter_=0,outside_=0;+ unsigned samples_=0;+ uint64_t snaps_=0;+public:+ static constexpr double kGain=.1,kDriftGain=kGain*kGain/4;+ static constexpr int64_t kLead100ns=5000;+ void reset(){offset_=drift_=outside_=0;samples_=0;}+ int64_t anchor(int64_t source,int64_t callback,int64_t interval){+ const double measured=double(callback-source),error=measured-offset_;+ const bool outside=samples_&&std::abs(error)>double(std::min<int64_t>(interval/3,80000));+ if(outside&&error*outside_<=0)outside_=error;+ else if(outside||!samples_){+ snaps_+=samples_>0;offset_=measured;outside_=0;samples_=1;+ }else{+ outside_=0;+ // A running mean until it has as many samples as the gain averages.+ samples_=std::min(samples_+1,10u);+ if(samples_<10)offset_+=error/samples_;+ else{offset_+=kGain*error+drift_;drift_+=kDriftGain*error;}+ jitter_+=.02*(std::abs(error)-jitter_);+ }+ return source+std::llround(offset_)-kLead100ns;+ }+ // Diagnostics: mean distance of a callback from the line, the clock difference, jumps.+ double jitterMs()const{return jitter_/10000;}+ double driftPpm(int64_t interval)const{return interval>0?drift_/double(interval)*1e6:0;}+ uint64_t snaps()const{return snaps_;}+};// 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;+// FG budget admits against, from the later of its smoothed due time and the one+// its own callback gives. A late callback must not expire more frames than it did.+inline constexpr int64_t kLiveGeneratedGrace100ns=100000;+inline int64_t liveGeneratedGrace100ns(int64_t callback,int64_t anchor){return kLiveGeneratedGrace100ns+std::max<int64_t>(0,callback-anchor);}+// Live VFG 2X: a generated frame is ready base + model time after the callback,+// its real frame is due an interval + base after it, and the panel shows one of+// them per refresh. With model time above half the interval they are closer than+// a refresh at some phases of the 16.5 s beat, the real frame replaces the generated+// one and the picture falls to 30 fps for seconds (60 Hz, model 23 ms: 28-31% of all+// frames on a real panel, 2026-11-01). Waiting for the next refresh would cost the+// real frame up to a refresh. Instead such a pair runs the next faster model.+inline bool liveFramesShareRefresh(int64_t generated,int64_t real,int64_t lastVblank,double period,double latch){+ if(period<=0)return false;+ const auto refresh=[&](int64_t present){return std::ceil((double(present-lastVblank)+latch)/period);};+ return refresh(generated)>=refresh(real);}+// Explicit VSync: how long a generated frame waits for display capacity with a+// smoothed anchor, half its interval being the other limit. The flip it takes can+// cost the real frame a whole refresh, so the wait falls with the interval. 60 Hz+// 2X model: 2 ms keeps 0.6% more frames but holds real frames 0.7 ms longer on+// average than 1 ms. 320 Hz A/B: 1 ms loses 3-6% of the presents for nothing at+// P99, and 2 ms shows no growth against the callback anchor.+inline double liveSmoothedCapacityWaitMs(double outputIntervalMs){return std::clamp(2-(outputIntervalMs-5)/12,1.0,2.0);}}diff --git a/include/veyra/engine/PresentationSettings.h b/include/veyra/engine/PresentationSettings.hindex fc66dfb1..d85187db 100644--- a/include/veyra/engine/PresentationSettings.h+++ b/include/veyra/engine/PresentationSettings.h@@ -56,9 +56,7 @@ 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). Automatic is reported as-// Vsync the same way while live frame generation runs near the refresh, where-// replacing is what loses frames (VideoPresenter::automaticQueueWanted).+// tearing flag, which only explicit Tearing may use).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 b840925e..b77415e0 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -44,8 +44,9 @@ public:bool beginSourceInput();bool beginSourceProcessing();void sourceProcessed(pipeline::FrameIdentity);- PresentationSettings configurePresentation(gfx::D3D12DeviceContext&,PresentationSettings,bool fg,std::wstring& status,bool outputNearRefresh=false);+ PresentationSettings configurePresentation(gfx::D3D12DeviceContext&,PresentationSettings,bool fg,std::wstring& status);bool presentationReady(){return sink_.presentationReady();}+ gfx::PresentSink::RefreshGrid refreshGrid()const{return sink_.refreshGrid();}bool waitPresentationReady(unsigned ms){return sink_.waitPresentationReady(ms);}uint64_t beginReflex(){const auto id=reflexInputFrame_;reflexInputFrame_=0;reflex_.renderStart(id);return id;}void endReflex(uint64_t id){reflex_.renderEnd(id);}@@ -95,15 +96,6 @@ 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@@ -185,7 +177,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,automaticQueue_=false;+ HMONITOR refreshMonitor_=nullptr;double refreshHz_=0;gfx::VrrState vrr_{};bool refreshQueried_=false,vrrSync_=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 68b5055f..14c033d9 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -130,6 +130,11 @@ public:int compositionMode=-1;};DisplayLatencySummary takeDisplayLatency();+ // Host 100 ns (steady_clock). The last vblank in the frame statistics and the+ // measured period; latch is how long before a vblank a Present still makes it:+ // the shortest Present to scanout seen lately. Empty before any statistics.+ struct RefreshGrid { int64_t lastVblank100ns=0; double period100ns=0,latch100ns=0; };+ RefreshGrid refreshGrid()const;double displayRefreshHz()const{return displayRefreshHz_;}// The owner re-reads the monitor after a move or mode change.void setDisplayRefreshHz(double hz){if(hz>=1.0)displayRefreshHz_=hz;}@@ -220,7 +225,7 @@ private:UINT lastDisplayedPresent_=0,lastSyncRefresh_=0,lastPresentRefresh_=0;uint64_t replacedPresents_=0;int64_t lastSyncQpc_=0;- double refreshQpc_=0;+ double refreshQpc_=0,latchMs_=2;bool displayLatencyEnabled_=true;std::vector<double> displayLatencyMs_;};diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 3aa0757d..0310af3e 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -135,6 +135,8 @@ struct EnhanceGraphDesc {engine::FrameGenerationBackend frameGenerationBackend=engine::FrameGenerationBackend::Dlss;uint32_t vfgQuality=1;bool vfgAsyncSubmission=false; // preview-only; export retains synchronous SDK verdicts+ bool vfgAutoRegulate=true;+ bool vfgFastFallback=false; // live 2X with vfgAutoRegulate: also load the next faster VFG modeluint64_t settingsRevision=1;engine::FlowQuality flowQuality=engine::FlowQuality::Balanced;engine::OpticalFlowBackend opticalFlowBackend=engine::OpticalFlowBackend::Nvidia;@@ -566,7 +568,7 @@ public:struct FrameOutputs {FrameBatch batch;uint32_t fgCandidates=0,fgEvaluated=0,fgSkippedBeforeEval=0,fgSkippedForReset=0;- bool historyReset=false,fgRecovery=false,fgBudgetSeed=false,fgReduced=false;+ bool historyReset=false,fgRecovery=false,fgBudgetSeed=false,fgReduced=false,fgFast=false,fgFastForBudget=false;ResetReason detectedReset=ResetReason::None;bool contentDuplicate=false;int measuredContentRate=0;double ptsMs = 0.0;@@ -595,7 +597,9 @@ public:// (fg_harness --fg-planar-alt verified 5/1/5 alternation keeps correct// interpolation positions). The pair keeps its true A/B PTS; only the// number of outputs changes, and it is reported as previewFgMultiplier.- enum class FgDecision { Skip, Evaluate, Seed, Reduced };+ // Fast: the faster VFG model for this pair, its frame would miss the refresh.+ // FastForBudget: the same because the budget rejected the chosen model.+ enum class FgDecision { Skip, Evaluate, Seed, Reduced, Fast, FastForBudget };using FgAdmission=std::function<FgDecision(const FrameBatch&,bool warmingHistory)>;// `hardwareSurface` carries the decoded texture for paths whose surface// does not travel inside the AVFrame (D3D11VA). It must be provided exactly@@ -786,6 +790,7 @@ public:void setNrEnabled(bool on);void setFgEnabled(bool on) { fgEnabled_ = on && !desc_.stillImage; }bool fgCreated() const;+ bool vfgFastReady() const;engine::FailedBackend failedBackend() const { return failedBackend_; }private:diff --git a/include/veyra/pipeline/VfgBackend.h b/include/veyra/pipeline/VfgBackend.hindex c363c0c7..f8c2bb50 100644--- a/include/veyra/pipeline/VfgBackend.h+++ b/include/veyra/pipeline/VfgBackend.h@@ -21,7 +21,7 @@ public:// loads a second effect with the second model on the same CUDA stream.bool initialize(gfx::D3D12DeviceContext&,const std::wstring& runtimeRoot,unsigned width,unsigned height,DXGI_FORMAT,unsigned multiplier,unsigned quality,- bool asynchronousSubmission=false);+ bool asynchronousSubmission=false,bool fastFallback=false);bool created() const;// Caller transitions encoded texture to COPY_SOURCE and back to COMMON.// Submit this list before generate(). Normal frames never CPU-wait here;@@ -34,7 +34,11 @@ public:// Signals an OWNED producer fence and queues a GPU wait before copyOutput.// Preview offloads the serial CUDA wait/run/signal to a bounded worker;// synchronous/export callers retain the immediate SDK rejection verdict.- bool generate(unsigned parity,unsigned subframe,unsigned multiplier,bool reset);+ // fast: this pair uses the second effect, see fastReady().+ bool generate(unsigned parity,unsigned subframe,unsigned multiplier,bool reset,bool fast=false);+ // A second effect is loaded: a mixed tier's second model, or with fastFallback+ // the next faster model, for pairs the chosen one would finish too late for.+ bool fastReady() const;// Poll after the corresponding consumer fence. A submitted copy is not// proof that the SDK accepted the generated frame.SubmissionState submissionState(unsigned slot) const;diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex ebb02723..db6e1497 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -433,6 +433,8 @@ class QmlPlayerBridge : public QObject {// DLSS 性能模式: NVIDIA's DLSS-G performance mode (EnhancementSettings::dlssgLite);// available when the package carries its runtime (runtime/experimental/dlssg-lite).Q_PROPERTY(bool dlssgLite READ dlssgLite WRITE setDlssgLite NOTIFY settingsChanged)+ // VFG 自动调控: EnhancementSettings::vfgAutoRegulate.+ Q_PROPERTY(bool vfgAutoRegulate READ vfgAutoRegulate WRITE setVfgAutoRegulate NOTIFY settingsChanged)Q_PROPERTY(bool dlssgLiteAvailable READ dlssgLiteAvailable CONSTANT)Q_PROPERTY(QString dlssgLiteHint READ dlssgLiteHint NOTIFY snapshotChanged)Q_PROPERTY(int contentRate READ contentRate WRITE setContentRate NOTIFY settingsChanged)@@ -1092,6 +1094,8 @@ public:void setEdgeAegis(bool value);bool dlssgLite() const;void setDlssgLite(bool value);+ bool vfgAutoRegulate() const;+ void setVfgAutoRegulate(bool value);bool dlssgLiteAvailable() const;QString dlssgLiteHint() const;int contentRate() const;diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qmlindex d5d52c0c..e5604797 100644--- a/qml/Veyra/NodePage.qml+++ b/qml/Veyra/NodePage.qml@@ -1172,7 +1172,7 @@ VPage {}// engine::ContentRate order (same list as the professional page).readonly property var contentRates: [- { id: "0", label: qsTr("采用源时间戳") }, { id: "1", label: qsTr("自动识别内容节奏") },+ { id: "0", label: qsTr("采用源时间戳") }, { id: "1", label: qsTr("自动剔除重复帧") },{ id: "2", label: qsTr("识别 30fps 内容") }, { id: "3", label: qsTr("识别 50fps 内容") },{ id: "4", label: qsTr("识别 60fps 内容") }, { id: "5", label: qsTr("采集 60→30(PS5 30 帧)") }]@@ -1648,6 +1648,14 @@ VPage {onPicked: id => veyra.vfgQuality = Number(id)}}+ VRow {+ label: qsTr("VFG 自动调控")+ visible: veyra.fgBackendName === "vfg"+ enabled: veyra.vfgQuality !== 0 && veyra.fgMultiplier === 2+ opacity: enabled ? 1 : 0.5+ hint: qsTr("实时采集 2X 时,当前档来不及赶上屏幕刷新,这一对帧就改用下一档,不丢帧也不加延迟。多占约 2 GB 显存,显存不够时不生效")+ VSwitch { objectName: "node-vfg-auto-regulate"; checked: veyra.vfgAutoRegulate; onToggled: checked => veyra.vfgAutoRegulate = checked }+ }VRow {label: qsTr("补帧运动来源")visible: veyra.fgBackendName !== "vfg"diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qmlindex 6e702c4a..6296b20f 100644--- a/qml/Veyra/ProPage.qml+++ b/qml/Veyra/ProPage.qml@@ -77,7 +77,7 @@ VPage {property int selectedEffect: -1// engine::ContentRate order.readonly property var contentRates: [- { id: "0", label: qsTr("采用源时间戳") }, { id: "1", label: qsTr("自动识别内容节奏") },+ { id: "0", label: qsTr("采用源时间戳") }, { id: "1", label: qsTr("自动剔除重复帧") },{ id: "2", label: qsTr("识别 30fps 内容") }, { id: "3", label: qsTr("识别 50fps 内容") },{ id: "4", label: qsTr("识别 60fps 内容") }, { id: "5", label: qsTr("采集 60→30(PS5 30 帧)") }]@@ -1741,6 +1741,18 @@ VPage {onPicked: id => veyra.vfgQuality = Number(id)}}+ VRow {+ label: qsTr("VFG 自动调控")+ visible: veyra.fgBackendName === "vfg"+ enabled: veyra.vfgQuality !== 0 && veyra.fgMultiplier === 2+ opacity: enabled ? 1 : 0.5+ hint: qsTr("实时采集 2X 时,当前档来不及赶上屏幕刷新,这一对帧就改用下一档,不丢帧也不加延迟。多占约 2 GB 显存,显存不够时不生效")+ VSwitch {+ objectName: "list-vfg-auto-regulate"+ checked: veyra.vfgAutoRegulate+ onToggled: checked => veyra.vfgAutoRegulate = checked+ }+ }VRow {label: qsTr("严格补帧节奏")hint: qsTr("帧同步 · 默认关闭")@@ -1796,7 +1808,7 @@ VPage {}VRow {label: qsTr("内容节奏")- hint: qsTr("游戏锁 30/40 帧、采集卡输出 60 帧时选“自动识别内容节奏”:只去掉与上一张完全相同的画面,补帧时间均匀;“采集 60→30”固定每两帧取一帧,稳定 30 帧")+ hint: qsTr("游戏锁 30/40 帧、采集卡输出 60 帧时选“自动剔除重复帧”:只去掉与上一张完全相同的画面,补帧时间均匀;“采集 60→30”固定每两帧取一帧,稳定 30 帧")VSelect {objectName: "list-content-rate"implicitWidth: 170diff --git a/qml/Veyra/ProPresentationRows.qml b/qml/Veyra/ProPresentationRows.qmlindex 52bd8029..be1527e7 100644--- a/qml/Veyra/ProPresentationRows.qml+++ b/qml/Veyra/ProPresentationRows.qml@@ -10,7 +10,7 @@ ColumnLayout {spacing: 0VRow {label: qsTr("显示同步")- hint: qsTr("自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低(实时补帧输出接近刷新率时改排 1 帧,避免丢帧) · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线")+ hint: qsTr("自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低 · 垂直同步:每帧都等到刷新才显示,比自动多等最多一个刷新 · 允许撕裂:可能出现撕裂线")VSeg {objectName: "presentation-display-sync"options: [{ id: "0", label: qsTr("允许撕裂") }, { id: "1", label: qsTr("垂直同步") }, { id: "2", label: qsTr("自动") }]diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cppindex 2a79cea1..ecc0b8c2 100644--- a/src/engine/EffectChain.cpp+++ b/src/engine/EffectChain.cpp@@ -743,6 +743,7 @@ bool requiresGraphRebuild(const EnhancementSettings& savedPrevious, const Enhancif (previous.amdFlowHalfResolution != next.amdFlowHalfResolution) return true;if (previous.fgMotionRefine != next.fgMotionRefine) return true;if (previous.dlssgLite != next.dlssgLite) return true;+ if (previous.vfgAutoRegulate != next.vfgAutoRegulate) return true;if (previous.flow != next.flow) return true;if (previous.captureCompatible != next.captureCompatible) return true;if (previous.forceSdrPreview != next.forceSdrPreview) return true;diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 56b16485..a689b948 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -518,7 +518,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool isStream=isRemote||isMoonlight||isXbox;const bool isCapture=physicalCapture||options.captureReplayForTest||isStream||isScreen;// File replay has no hardware arrival clock; retain its continuous PTS anchor.- const bool pairAnchoredLive=physicalCapture||isStream||isScreen;+ // VEYRA_TEST_REPLAY_AS_CARD=1 delivers it like a capture card instead (see below).+ const bool testReplayAsCard=options.captureReplayForTest&&GetEnvironmentVariableW(L"VEYRA_TEST_REPLAY_AS_CARD",nullptr,0)>0;+ const bool pairAnchoredLive=physicalCapture||isStream||isScreen||testReplayAsCard;source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;if(isScreen)activeSource=&screenSource;#ifdef VEYRA_ENABLE_REMOTEPLAY@@ -789,6 +791,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(stop_)return false;desc.vfgAsyncSubmission=!isImage&&selected.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&GetEnvironmentVariableW(L"VEYRA_TEST_VFG_SYNC_SUBMIT",nullptr,0)==0;+ desc.vfgFastFallback=desc.vfgAsyncSubmission&&selected.settings.vfgAutoRegulate&&(physicalCapture||isScreen||testReplayAsCard)&&selected.settings.multiplier==2&&+ GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_LIVE_PACING",nullptr,0)==0;desc.videoHdr=selected.settings.videoHdr;desc.hdrOutput=selected.settings.useHdrPreview(desc.hdrInput,displayHdrActive());// Auto is optional and preview-only; fixed/export policies@@ -1139,16 +1143,20 @@ 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;+ // Live graph FG presents on a smoothed anchor (LiveArrivalSmoother).+ // VEYRA_TEST_LEGACY_LIVE_PACING=1 restores the callback anchor, the+ // 2 ms capacity wait and the lone VFG probe for A/B runs.+ static const bool legacyLivePacing=GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_LIVE_PACING",nullptr,0)>0;+ LiveArrivalSmoother liveArrival;int64_t liveGeneratedGrace=kLiveGeneratedGrace100ns,nextLiveAnchorLog=0;FgCostSettling vfgCostSettling;+ double vfgChosenFgMs=0,vfgFastFgMs=0;uint64_t vfgFastPairs=0,vfgFastBudgetPairs=0,vfgChosenPairs=0;int64_t vfgChosenAt=0,nextVfgFastLog=0;uint64_t generatedDropDeadline=0,generatedDropCapacity=0,generatedDropCap=0;LivePairLatency pairLatency;- const bool adaptiveCapturePhase=physicalCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_CAPTURE_PHASE",nullptr,0)==0;+ // VEYRA_TEST_ADAPTIVE_SCREEN_PHASE=1 and VEYRA_TEST_ARRIVAL_JITTER_MS=<sd> give+ // window capture what a USB card has: this phase and a late callback.+ const bool adaptiveCapturePhase=(physicalCapture||testReplayAsCard||(isScreen&&GetEnvironmentVariableW(L"VEYRA_TEST_ADAPTIVE_SCREEN_PHASE",nullptr,0)>0))&&GetEnvironmentVariableW(L"VEYRA_TEST_LEGACY_CAPTURE_PHASE",nullptr,0)==0;+ static const double testArrivalJitterMs=[]{wchar_t v[16]{};return GetEnvironmentVariableW(L"VEYRA_TEST_ARRIVAL_JITTER_MS",v,16)?std::clamp(_wtof(v),0.0,10.0):0.0;}();+ uint32_t testArrivalSeed=7;int64_t testCardStart=0;double testCardFirstPtsMs=0;int64_t nextFgAdmissionLog=0,nextFgRejectionLog=0;uint64_t fgAdmittedPairs=0,fgRejectedPairs=0,fgReducedPairs=0;int64_t nextFgReducedLog=0;std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;@@ -1269,13 +1277,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(watch.real)completedProcessing(batch.batch.identity);// 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. 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);+ // see FgRecoveryBudget::complete. A history reset, an FG+ // recovery and a live VFG pair settling after a long skip+ // (FgCostSettling) are warmup samples.+ const auto vfgHeldUntil=vfgCostSettling.holdUntil();+ const bool costSettling=batch.batch.identity.settingsRevision==fgBudgetRevision&&isCapture&&!legacyLivePacing&&options.settings.frameGenerationBackend==FrameGenerationBackend::Vfg&&+ vfgCostSettling.observe((batch.fgCandidates>0&&batch.fgEvaluated==0)||batch.fgFastForBudget,batch.fgEvaluated>0&&!batch.fgFast,host100ns());+ // Each model's own time. The steady time is the low envelope: an+ // evaluation after skips can cost 1.7x (see FgCostSettling).+ if(batch.batch.identity.settingsRevision==fgBudgetRevision&&watch.fgExecutionMs&&batch.fgEvaluated>0&&!batch.fgReduced&&!batch.historyReset&&!batch.fgRecovery){+ auto& cost=batch.fgFast?vfgFastFgMs:vfgChosenFgMs;const double ms=*watch.fgExecutionMs;+ cost=cost>0&&ms>=cost?cost+.1*(ms-cost):ms;+ if(!batch.fgFast){vfgChosenAt=host100ns();++vfgChosenPairs;}}+ if(vfgCostSettling.holdUntil()!=vfgHeldUntil)veyra::log::info("vfg-probe",std::format("revision={} retryInMs={} (a VFG probe after a long skip stayed over budget; failed probes retry after 2, 4, then every 8 s)",options.settings.revision,(vfgCostSettling.holdUntil()-host100ns())/10000));+ if(batch.batch.identity.settingsRevision==fgBudgetRevision)fgBudget.complete(watch.gpuExecutionMs,batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery||costSettling,host100ns(),watch.fgExecutionMs,!batch.fgReduced&&!batch.fgFast);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)@@ -1293,7 +1309,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool phaseSample=phaseValidOnly?valid==batch.fgCandidates&&batch.hasGenerated:batch.fgCandidates>0&&valid+invalid==batch.fgCandidates&&!failed;if(adaptiveCapturePhase&&watch.captureArrival>0&&phaseSample&&- !batch.historyReset&&!batch.fgRecovery&&+ !batch.historyReset&&!batch.fgRecovery&&!costSettling&&!batch.fgFast&&batch.batch.identity.settingsRevision==fgBudgetRevision&&watch.presentationGeneration==presentationGeneration.load()){int64_t requiredDelay=0;const auto observed=host100ns();@@ -1348,8 +1364,7 @@ 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());- const bool automaticQueueChanged=presenter.automaticQueue()!=VideoPresenter::automaticQueueWanted(requested,presenter.displayVrr(),liveNearRefresh);- if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged&&!capRefreshChanged&&!automaticQueueChanged){+ if(revision==pacingRevision&&presenterGeneration==presenter.generation()&&!vrrChanged&&!capRefreshChanged){// 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()){@@ -1365,11 +1380,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,liveNearRefresh);+ presentationEffective=presenter.configurePresentation(ctx,requested,options.fg,message);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={} 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()));+ 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()));};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());}};@@ -1683,7 +1698,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!accepted){finishReset(diagnostics::ResetOutcome::Failed);status(L"设置切换排空失败,已停止",true);break;}backendRecoveryWarning.clear();const bool preserveWorkingFg=previous.multiplier>1&&requested.multiplier>1&&- (previous.frameGenerationBackend!=requested.frameGenerationBackend||previous.multiplier!=requested.multiplier||previous.vfgQuality!=requested.vfgQuality);+ (previous.frameGenerationBackend!=requested.frameGenerationBackend||previous.multiplier!=requested.multiplier||previous.vfgQuality!=requested.vfgQuality||previous.vfgAutoRegulate!=requested.vfgAutoRegulate);const bool preserveWorkingNr=previous.nr&&requested.nr&&previous.nrRuntime!=requested.nrRuntime;if(accepted&&rebuild){if(!presenter.prepareGraphChange()){finishReset(diagnostics::ResetOutcome::Failed);status(L"设置切换呈现排空失败,已停止",true);break;}@@ -2107,6 +2122,15 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(previewSourceFailed){status(source.errorMessage().empty()?L"视频读取或候选帧保存失败":source.errorMessage(),true);break;}}if(!retainCandidate()){status(L"无法保存解码帧,已停止播放",true);break;}+ if(testReplayAsCard||(testArrivalJitterMs>0&&isScreen)){+ double sum=0;for(int i=0;i<12;++i){testArrivalSeed=testArrivalSeed*1664525u+1013904223u;sum+=double(testArrivalSeed>>8)/double(1u<<24);}+ // A card's clock: 800 ppm slow against the host, as in the field log.+ if(testReplayAsCard&&!testCardStart){testCardStart=host100ns();testCardFirstPtsMs=pkt.pts.toDouble()*1000;}+ const auto line=testReplayAsCard?testCardStart+int64_t((pkt.pts.toDouble()*1000-testCardFirstPtsMs)*10000*1.0008):pkt.arrivalHost100ns;+ const auto until=line+int64_t(std::max(0.0,sum-3)*testArrivalJitterMs*10000);+ while(host100ns()<until){advanceLive();std::this_thread::yield();}+ pkt.arrivalHost100ns=host100ns();+ }const auto processStart=Clock::now();const auto captureArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:host100ns();// A PS5 callback is a compressed AU, not a decoded video frame.@@ -2173,7 +2197,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool previewOnlyReset=!hardFrameReset&&temporalBreak;if(hardFrameReset)++metricsWindowEpoch;const bool historyReset=hardFrameReset||temporalBreak;- if(historyReset)++historyResets;+ if(historyReset){++historyResets;liveArrival.reset();}if(presentationGenerationResetRequired(reset,pkt.flags))++presentationGeneration;// A mailbox Drop must reset SR/NR/flow/FG history, but draining// the two-batch presenter here discarded completed real frames.@@ -2189,7 +2213,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();vfgCostSettling.reset();pairLatency.reset();fgBudgetRevision=options.settings.revision;displayFgGate.reset();nearRefreshGate.reset();}+ if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();vfgOverload.reset();vfgCostSettling.reset();vfgChosenFgMs=vfgFastFgMs=0;liveArrival.reset();pairLatency.reset();fgBudgetRevision=options.settings.revision;displayFgGate.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@@ -2227,14 +2251,6 @@ 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;@@ -2254,7 +2270,12 @@ 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));+ const bool smoothAnchor=pairAnchoredLive&&options.fg&&!isStream&&!dedupActive&&!legacyLivePacing&&!presentSinkFrameGeneration(options.settings.frameGenerationBackend);+ std::optional<int64_t> pairPresentAnchor;+ const auto presentAnchorFor=[&](int64_t source){+ if(!pairPresentAnchor)pairPresentAnchor=smoothAnchor?liveArrival.anchor(source,liveInputReady,liveInterval):liveInputReady;+ return *pairPresentAnchor;+ };// 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)){@@ -2265,6 +2286,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// input pair before enhancement, so a 59.94-vs-60Hz// mismatch cannot accumulate into a stale deadline.// Never extend it based on processing/ready completion.+ // Admission asks whether this pair's own frames can make+ // it, so it keeps the callback; LiveArrivalSmoother moves+ // only the presentation anchor set below.if(pairAnchoredLive)liveTimeline.resetPair(batch.identity.epoch,batch.b100ns,liveInputReady,pairDelay);else if(!liveTimeline.anchored(batch.identity.epoch))liveTimeline.reset(batch.identity.epoch,batch.b100ns,liveInputReady,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));const auto interval=liveInterval;@@ -2272,9 +2296,30 @@ 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,0,double(generatedGrace)/10000);+ const bool admitted=!vfgCostSettling.holding(now)&&fgBudget.admit(now,deadline,elapsed,presentP95,warmingHistory);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;+ auto decision=admitted?pipeline::EnhanceGraph::FgDecision::Evaluate:pipeline::EnhanceGraph::FgDecision::Skip;+ if(smoothAnchor&&options.settings.vfgAutoRegulate&&previewFgMultiplier==2&&!warmingHistory&&graph->vfgFastReady()){+ const double base=fgBudget.baseCost(now).value_or(0),progress=std::clamp(elapsed,0.0,base),blit=std::max(0.0,presentP95);+ if(!admitted){+ if(double(deadline-now)/10000+10>=std::max(0.0,base+vfgFastFgMs-progress)+blit)decision=pipeline::EnhanceGraph::FgDecision::FastForBudget;+ }else if(vfgChosenFgMs>0&&presentationEffective.display!=DisplaySync::Tearing&&!presenter.vrrSync()){+ const auto grid=presenter.refreshGrid();+ // A time too high would never be corrected without running the+ // model: after 4 s without it, try where 30% less would make it.+ // 1 ms keeps clear of the refresh edge: the faster model costs nothing there.+ const double chosen=now-vfgChosenAt>=40000000?vfgChosenFgMs*.7:vfgChosenFgMs;+ const auto ready=now+int64_t((std::max(0.0,base+chosen-progress)+blit+1)*10000);+ if(now-grid.lastVblank100ns<10000000&&liveFramesShareRefresh(ready,presentAnchorFor(batch.b100ns)+pairDelay,grid.lastVblank100ns,grid.period100ns,grid.latch100ns))decision=pipeline::EnhanceGraph::FgDecision::Fast;+ }+ if(decision==pipeline::EnhanceGraph::FgDecision::Fast)++vfgFastPairs;+ else if(decision==pipeline::EnhanceGraph::FgDecision::FastForBudget)++vfgFastBudgetPairs;+ if(now>=nextVfgFastLog&&(vfgFastPairs||vfgFastBudgetPairs)){+ nextVfgFastLog=now+10000000;+ veyra::log::info("vfg-fast",std::format("revision={} refreshPairs={} budgetPairs={} chosenPairs={} chosenFgMs={:.2f} fastFgMs={:.2f} latchMs={:.2f} (session totals: pairs run with the next faster model because the chosen one would miss the refresh or the budget, and pairs run with the chosen one)",options.settings.revision,vfgFastPairs,vfgFastBudgetPairs,vfgChosenPairs,vfgChosenFgMs,vfgFastFgMs,presenter.refreshGrid().latch100ns/10000));+ }+ }+ return decision;};}// File playback checks both the first output and whole-group@@ -2497,7 +2542,15 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(isCapture&&!rereadCached&&(isStream||pairPacing||!liveTimeline.anchored(out.batch.identity.epoch,paceSourcePts))){const auto duration100ns=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);if(!liveTimeline.anchored(out.batch.identity.epoch,paceSourcePts)||(pairPacing&&frames==0))veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,pairPacing?(isRemote?"decoded-pair":"capture-pair"):paceSourcePts?"source-pts":"capture-ready"));- if(pairPacing||isStream)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?pairDelay:0,paceSourcePts);+ if(pairPacing||isStream){+ const auto presentAnchor=presentAnchorFor(out.batch.b100ns);+ liveGeneratedGrace=liveGeneratedGrace100ns(liveInputReady,presentAnchor);+ liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,presentAnchor,options.fg?pairDelay:0,paceSourcePts);+ if(smoothAnchor&&host100ns()>=nextLiveAnchorLog){+ nextLiveAnchorLog=host100ns()+10000000;+ veyra::log::info("live-anchor",std::format("revision={} callbackJitterMs={:.3f} clockDriftPpm={:.0f} snaps={} callbackMinusAnchorMs={:.3f} (presentation anchor: source PTS plus a tracked offset to the capture callback, less a 0.5 ms lead)",options.settings.revision,liveArrival.jitterMs(),liveArrival.driftPpm(liveInterval),liveArrival.snaps(),double(liveInputReady-presentAnchor)/10000));+ }+ }else if(!liveTimeline.anchored(out.batch.identity.epoch,paceSourcePts))liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns:0,paceSourcePts);}if(!isImage&&!isCapture&&frames==0){anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}@@ -2545,7 +2598,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,&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{+ &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=liveGeneratedGrace,smoothAnchor,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;@@ -2586,7 +2639,7 @@ 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));+ veyra::log::info("fg-drops",std::format("revision={} deadline={} capacity={} cap={} graceMs={:.1f} (session totals of frames dropped before Present, by reason)",item.identity.settingsRevision,generatedDropDeadline,generatedDropCapacity,generatedDropCap,double(generatedGrace)/10000));}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();@@ -2624,13 +2677,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}// 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 gives up as liveGeneratedCapacityExpired says and is replaced- // by the next one. The real frame waits.+ // frame waits at most half its interval (<= 2 ms, and see+ // liveSmoothedCapacityWaitMs) 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.if((!legacyVsyncQueue||presentationEffective.enabled||presentationEffective.outputRate==OutputRateMode::Custom)&&!presenter.presentationReady()){if(generated&&!legacyVsyncQueue){if(!s.capacityStart)s.capacityStart=Clock::now();- 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;}+ const double outputIntervalMs=sourceIntervalMs/std::max(1u,batch.batch.count);+ if(elapsedMs(*s.capacityStart)>std::min(smoothAnchor?liveSmoothedCapacityWaitMs(outputIntervalMs):2.0,outputIntervalMs/2)){++generatedDropCapacity;++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();s.capacityStart.reset();continue;}}return {State::Pending,optionalNow+2000};}@@ -2658,7 +2714,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,scadence.submitted(optionalNow);cadence.rateSubmitted(optionalNow,capInterval);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));+ if(veyra::log::verboseFrameLogs())veyra::log::info("pacing-sample",std::format("mode={} enabled={} sync={} pts={} begin={} end={} ready={} process={} generated={} queue={} lateMs={:.3f} arrival={}",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,captureArrival));diagnostics::FrameTraceEvent event{presentEndHost,runSessionId,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,diagnostics::TraceKind::Present,item.subframe,1,elapsed};event.decodedHost=baselineReady;event.processHost=std::chrono::duration_cast<std::chrono::nanoseconds>(watch->processStart.time_since_epoch()).count()/100;event.readyHost=watch->frameReadyObserved[s.next];event.presentBeginHost=presentBeginHost;event.presentEndHost=presentEndHost;diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 2bb7d387..e337f356 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -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;automaticQueue_=false;displayStateSerial_=0;vrrConfirmAt_.reset();+ refreshMonitor_=nullptr;refreshHz_=0;vrr_={};refreshQueried_=false;vrrSync_=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,bool outputNearRefresh){+PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceContext& ctx,PresentationSettings requested,bool fg,std::wstring& status){// 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,10 +608,9 @@ 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_||automaticQueue_){requested.display=DisplaySync::Vsync;effective.display=DisplaySync::Vsync;}+ if(vrrSync_){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 ";"@@ -621,8 +620,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"显示同步:自动 + 可变刷新":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"";+ 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"";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@@ -648,7 +647,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 帧":automaticQueue_?L"":L"垂直同步:屏幕队列 1 帧,读帧前等待刷新"):vsync?L"垂直同步:屏幕队列控制不可用":restored?L"":L"显示队列恢复失败";+ const std::wstring queue=paced?(vrrSync_?L"可变刷新:超过屏幕最高刷新时只排 1 帧":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 061dd1ad..22c03f23 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -508,9 +508,18 @@ void PresentSink::sampleDisplayLatency(){if(pending.replaceable&&pending.id!=stats.PresentCount)continue;if(pending.id!=stats.PresentCount&&(!newestQpc||newestQpc-double(pending.qpc)>double(stats.PresentCount-pending.id)*period*1.25))continue;const double ms=(scanout-double(stats.PresentCount-pending.id)*period-double(pending.qpc))*1000.0/frequency;+ if(pending.id==stats.PresentCount&&ms>=0&&ms<1000)latchMs_=std::min(latchMs_+.001,ms);if(ms>=0&&ms<1000&&displayLatencyMs_.size()<4096)displayLatencyMs_.push_back(ms);}}+PresentSink::RefreshGrid PresentSink::refreshGrid()const{+ static const double frequency=[]{LARGE_INTEGER f{};QueryPerformanceFrequency(&f);return double(f.QuadPart);}();+ RefreshGrid grid;+ const double period=refreshQpc_>0?refreshQpc_:displayRefreshHz_>=1?frequency/displayRefreshHz_:0;+ if(!lastSyncQpc_||period<=0)return grid;+ grid.lastVblank100ns=int64_t(double(lastSyncQpc_)*1e7/frequency);grid.period100ns=period*1e7/frequency;grid.latch100ns=latchMs_*10000;+ return grid;+}PresentSink::DisplayLatencySummary PresentSink::takeDisplayLatency(){DisplayLatencySummary summary;summary.replacedAtLeast=replacedPresents_;replacedPresents_=0;diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex e541fe6a..2d5458e5 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -1276,7 +1276,7 @@ bool EnhanceGraph::initVfg()if(!fgEnabled_||desc_.frameGenerationBackend!=engine::FrameGenerationBackend::Vfg)return true;failedBackend_=engine::FailedBackend::Fg;vfgBackend_=std::make_unique<VfgBackend>();- if(!vfgBackend_->initialize(context_,desc_.runtimeAbsPath,workW_,workH_,outputFormat(),desc_.fgMultiplier,desc_.vfgQuality,desc_.vfgAsyncSubmission))return false;+ if(!vfgBackend_->initialize(context_,desc_.runtimeAbsPath,workW_,workH_,outputFormat(),desc_.fgMultiplier,desc_.vfgQuality,desc_.vfgAsyncSubmission,desc_.vfgFastFallback))return false;fgCapsAvailable_=true;fgMultiFrameMax_=int(FrameBatch::Capacity)-1;return true;}@@ -3283,6 +3283,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// seed path already runs a single evaluation.const bool reduced=decision==FgDecision::Reduced&&!resetFg;out.fgReduced=reduced;+ out.fgFast=vfgBackend_&&!resetFg&&(decision==FgDecision::Fast||decision==FgDecision::FastForBudget);+ out.fgFastForBudget=out.fgFast&&decision==FgDecision::FastForBudget;// A reset has no usable A/B pair. Seed one complete 2X evaluation group;// all later subframes would repeat reset work and cannot be presented.const uint32_t fgCalls=(resetFg||reduced)?1:fgMultiplier-1;@@ -3322,7 +3324,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(vfgBackend_){// GPU producer -> CUDA interpolation -> GPU consumer. No per-frame// CPU fence waits/readback; the bounded command ring owns reuse.- if(!vfgBackend_->generate(parity,sub,resetFg?2u:outputMultiplier,resetFg)){failedBackend_=engine::FailedBackend::Fg;return false;}+ if(!vfgBackend_->generate(parity,sub,resetFg?2u:outputMultiplier,resetFg,out.fgFast)){failedBackend_=engine::FailedBackend::Fg;return false;}auto* flist=ring_.acquireNext(slot,st);if(!flist)return false;tracker_.transition(flist,genFrame_[generatedSlot].Get(),D3D12_RESOURCE_STATE_COPY_DEST);if(!vfgBackend_->copyOutput(flist,genFrame_[generatedSlot].Get(),generatedSlot)){failedBackend_=engine::FailedBackend::Fg;return false;}@@ -3542,7 +3544,7 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){// rebuild instead of accepting a change that cannot take effect in place.if((desc_.enableNr&&s.nrRuntime!=desc_.nrRuntime)||(desc_.enableFg&&(std::max(2u,s.multiplier)!=desc_.fgMultiplier||s.frameGenerationBackend!=desc_.frameGenerationBackend||- (desc_.frameGenerationBackend==engine::FrameGenerationBackend::Vfg&&s.vfgQuality!=desc_.vfgQuality)))||+ (desc_.frameGenerationBackend==engine::FrameGenerationBackend::Vfg&&(s.vfgQuality!=desc_.vfgQuality||s.vfgAutoRegulate!=desc_.vfgAutoRegulate))))||(desc_.enableSr&&(s.videoSrQuality!=desc_.videoSrQuality||(desc_.videoSrQuality==0&&s.dlssSrModel!=desc_.dlssSrModel)))||(s.multiplier>1&&s.frameGenerationBackend==engine::FrameGenerationBackend::Dlss&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;// The colour master switch changes the graph shape (tables + shader branch)@@ -3663,6 +3665,7 @@ void EnhanceGraph::setNrEnabled(bool on)ID3D12Fence* EnhanceGraph::contextFence()const{return context_.fence();}uint32_t EnhanceGraph::actualFlowPerf()const{return nvof_?nvof_->caps().actualPerfLevel:0;}+bool EnhanceGraph::vfgFastReady() const { return vfgBackend_&&vfgBackend_->fastReady(); }bool EnhanceGraph::fgCreated() const{return (vfgBackend_&&vfgBackend_->created()) || fsrActive() || (fgBackend_ && fgBackend_->created());diff --git a/src/pipeline/VfgBackend.cpp b/src/pipeline/VfgBackend.cppindex d14c9380..ac78c83b 100644--- a/src/pipeline/VfgBackend.cpp+++ b/src/pipeline/VfgBackend.cpp@@ -140,7 +140,7 @@ struct VfgBackend::Impl {Microsoft::WRL::ComPtr<ID3D12PipelineState> cutPso;Microsoft::WRL::ComPtr<ID3D12Resource> cutResults;D3D12_RESOURCE_STATES cutState=D3D12_RESOURCE_STATE_COMMON;- struct Job {unsigned parity,sub,multiplier;bool reset;uint64_t revision,value;};+ struct Job {unsigned parity,sub,multiplier;bool reset;uint64_t revision,value;bool fast;};std::array<std::atomic<SubmissionState>,kOutputs> states{};std::atomic<bool> failed=false;std::mutex jobsMutex,profileMutex;@@ -150,6 +150,7 @@ struct VfgBackend::Impl {bool asynchronous=false,stopping=false;unsigned outstanding=0;unsigned rejectRun=0,runCount=0; // process-local deterministic failure test+ double testRunDelayMs=0; // VEYRA_TEST_VFG_DELAY_MS: a slower GPU, on this worker onlybool profileCpu=false;std::array<double,13> cpuSum{},cpuMax{};std::array<unsigned,13> cpuSamples{};@@ -315,7 +316,7 @@ struct VfgBackend::Impl {buffer.resource.Reset();}bool cudaJob(const Job& job){- const auto [parity,sub,multiplier,reset,revision,value]=job;+ const auto [parity,sub,multiplier,reset,revision,value,fast]=job;Current current(*this);if(!current.active)return false;CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS wait{};wait.params.fence.value=value;bool ok=cu(cpuCall(2,[&]{return cuWaitExternalSemaphoresAsyncFn(&inputSemaphore,&wait,1,stream);}),"cuWaitExternalSemaphoresAsync")&&!failed.load();@@ -334,7 +335,7 @@ struct VfgBackend::Impl {if(sub==1||revision!=lastRevision||parity!=lastParity||reset!=lastReset){++pairSerial;lastRevision=revision;lastParity=parity;lastReset=reset;}- const bool second=mixed&&sub!=engine::vfgPrimarySubframe(multiplier);+ const bool second=(mixed&&sub!=engine::vfgPrimarySubframe(multiplier))||(fast&&effects[1].handle);auto& e=effects[second?1:0];if(ok&&e.boundPair!=pairSerial){ok=cv(cpuCall(3,[&]{return setImage(e.handle,"SrcImage0",inputs[reset?parity:1-parity].image);}),"SetImage previous")&&@@ -348,6 +349,10 @@ struct VfgBackend::Impl {}ok=ok&&cv(cpuCall(5,[&]{return setImage(e.handle,"DstImage0",outputs[parity+2*(sub-1)].image);}),"SetImage output")&&cv(cpuCall(8,[&]{return setU32(e.handle,"FrameIndex",sub);}),"SetU32 FrameIndex");+ if(ok&&testRunDelayMs>0){+ const auto until=std::chrono::steady_clock::now()+std::chrono::duration<double,std::milli>(testRunDelayMs*(second?.3:1));+ while(std::chrono::steady_clock::now()<until)std::this_thread::yield();+ }if(ok){if(rejectRun&&++runCount==rejectRun){log::warn("vfg","injected VFG Run rejection (test hook)");ok=false;}else ok=cv(cpuCall(9,[&]{return run(e.handle,1);}),"NvVFX_Run async");@@ -392,12 +397,12 @@ struct VfgBackend::Impl {{std::lock_guard lock(jobsMutex);--outstanding;}}}- bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset){+ bool handoff(unsigned parity,unsigned sub,unsigned multiplier,bool reset,bool fast){const unsigned slot=parity+2*(sub-1);if(!asynchronous){const uint64_t value=++signalValue;if(!hr(cpuCall(1,[&]{return context->directQueue()->Signal(producer.Get(),value);}),"signal VFG producer"))return false;- const bool ok=cudaJob({parity,sub,multiplier,reset,inputRevision,value});+ const bool ok=cudaJob({parity,sub,multiplier,reset,inputRevision,value,fast});if(!ok){failed.store(true);Current current(*this);if(current.active&&stream)cu(cuStreamSynchronizeFn(stream),"rejected synchronous job drain");@@ -415,7 +420,7 @@ struct VfgBackend::Impl {if(!hr(cpuCall(1,[&]{return context->directQueue()->Signal(producer.Get(),value);}),"signal VFG producer"))return false;// Allocate the queue entry before adding a GPU dependency. Even a host// allocation exception cannot leave a wait with no job to signal it.- jobs.push_back({parity,sub,multiplier,reset,inputRevision,value});+ jobs.push_back({parity,sub,multiplier,reset,inputRevision,value,fast});if(!hr(cpuCall(11,[&]{return context->directQueue()->Wait(completion.Get(),value);}),"queue wait VFG completion")){jobs.pop_back();return false;}@@ -430,7 +435,7 @@ struct VfgBackend::Impl {VfgBackend::VfgBackend():impl_(std::make_unique<Impl>()){}VfgBackend::~VfgBackend(){shutdown();}-bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring& root,unsigned width,unsigned height,DXGI_FORMAT format,unsigned multiplier,unsigned quality,bool asynchronousSubmission){+bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring& root,unsigned width,unsigned height,DXGI_FORMAT format,unsigned multiplier,unsigned quality,bool asynchronousSubmission,bool fastFallback){shutdown();#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERSauto& p=*impl_;@@ -443,6 +448,7 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&p.effects[0].mode=engine::vfgPrimaryMode(quality);p.effects[1].mode=engine::vfgSecondaryMode(quality);p.gpuShotChange=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_AUTO_SHOT_CHANGE",nullptr,0)==0;p.profileCpu=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_CPU_PROFILE",nullptr,0)>0;+ {wchar_t delay[16]{};if(GetEnvironmentVariableW(L"VEYRA_TEST_VFG_DELAY_MS",delay,16))p.testRunDelayMs=std::clamp(_wtof(delay),0.0,40.0);}wchar_t reject[16]{};const auto rejectLength=GetEnvironmentVariableW(L"VEYRA_TEST_VFG_REJECT_RUN",reject,16);if(rejectLength&&rejectLength<16)p.rejectRun=unsigned(std::clamp(_wtoi(reject),0,1000000));@@ -523,17 +529,32 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&// NvVFX_Run wait on the GPU (measured 2026-10-11: host 3.5 ms -> 0.13 ms per// 4K Run) and repeated per subframe (+0.2 ms GPU each).const unsigned automaticShotChange=p.gpuShotChange?0u:1u;- const unsigned effectCount=p.mixed?2u:1u;- for(unsigned i=0;i<effectCount;++i){- auto& e=p.effects[i];+ const auto createEffect=[&](Impl::Effect& e,const char* loadName){if(!p.cv(p.create("VideoFrameGeneration",&e.handle),"NvVFX_CreateEffect")||!p.cv(p.setStream(e.handle,"CudaStream",p.stream),"SetCudaStream")||!p.cv(p.setU32(e.handle,"InputWidth",width),"InputWidth")||!p.cv(p.setU32(e.handle,"InputHeight",height),"InputHeight")||!p.cv(p.setU32(e.handle,"Mode",e.mode),"Mode")||!p.cv(p.setU32(e.handle,"AutomaticShotChangeDetectionEnabled",automaticShotChange),"AutomaticShotChangeDetectionEnabled")||!p.cv(p.setImage(e.handle,"SrcImage0",p.inputs[0].image),"initial previous")||!p.cv(p.setImage(e.handle,"SrcImage1",p.inputs[1].image),"initial current")||- !p.cv(p.loadEffect(e.handle),i?"NvVFX_Load second model":"NvVFX_Load")||!p.cv(p.setImage(e.handle,"DstImage0",p.outputs[0].image),"initial output")||+ !p.cv(p.loadEffect(e.handle),loadName)||!p.cv(p.setImage(e.handle,"DstImage0",p.outputs[0].image),"initial output")||!p.cv(p.setU32(e.handle,"FrameMultiplier",multiplier),"initial multiplier"))return false;- e.boundMultiplier=multiplier;+ e.boundMultiplier=multiplier;return true;+ };+ for(unsigned i=0;i<(p.mixed?2u:1u);++i)if(!createEffect(p.effects[i],i?"NvVFX_Load second model":"NvVFX_Load"))return false;+ // Live 2X: the next faster model, for the pairs the engine picks (LivePresentationTiming.h).+ // Without it the chosen model runs every pair, so a failure here costs nothing else.+ // It takes about 1.9 GB at 4K, as much again as the chosen model, which D3D's usage+ // may not count (RTX 5070, 2026-11-01), so 4.3 GB of the budget must be free.+ uint64_t memoryBudget=0,memoryUsage=0;+ const bool fastFits=context.videoMemoryInfo(memoryBudget,memoryUsage)&&memoryBudget>memoryUsage+(uint64_t(4300)<<20);+ if(fastFallback&&!p.mixed&&quality>0&&!fastFits)log::info("vfg",std::format("fast model not loaded: budgetMB={} usageMB={}",memoryBudget>>20,memoryUsage>>20));+ if(fastFallback&&!p.mixed&&quality>0&&fastFits){+ auto& e=p.effects[1];e.mode=quality-1;+ const auto start=std::chrono::steady_clock::now();+ if(createEffect(e,"NvVFX_Load fast model"))log::info("vfg",std::format("fast model mode={} loadMs={:.0f}",e.mode,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()));+ else{+ if(e.handle){p.destroy(e.handle);e.handle=nullptr;}+ log::warn("vfg","fast model unavailable; the chosen model runs every pair");+ }}if(p.gpuShotChange&&!p.createShotChangeTest())return false;p.asynchronous=asynchronousSubmission;@@ -544,7 +565,7 @@ bool VfgBackend::initialize(gfx::D3D12DeviceContext& context,const std::wstring&log::info("vfg",std::format("SDK submission={} capacity={} (CUDA work remains serial)",p.asynchronous?"bounded worker":"graph owner",kOutputs));p.ready=true;log::info("vfg","native VFG initialized; GPU-only D3D12 buffer/fence bridge");return true;#else- (void)context;(void)root;(void)width;(void)height;(void)format;(void)multiplier;(void)quality;(void)asynchronousSubmission;+ (void)context;(void)root;(void)width;(void)height;(void)format;(void)multiplier;(void)quality;(void)asynchronousSubmission;(void)fastFallback;log::error("vfg","VFG unavailable: configure VEYRA_CUDA_DRIVER_INCLUDE_DIR");return false;#endif}@@ -572,12 +593,19 @@ bool VfgBackend::capture(ID3D12GraphicsCommandList* list,ID3D12Resource* texture(void)list;(void)texture;(void)parity;(void)comparePrevious;return false;#endif}-bool VfgBackend::generate(unsigned parity,unsigned sub,unsigned multiplier,bool reset){+bool VfgBackend::fastReady()const{+#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERS+ return impl_->ready&&impl_->effects[1].handle;+#else+ return false;+#endif+}+bool VfgBackend::generate(unsigned parity,unsigned sub,unsigned multiplier,bool reset,bool fast){#ifdef VEYRA_HAVE_CUDA_DRIVER_HEADERSauto& p=*impl_;if(!p.ready||p.failed.load()||parity>1||multiplier<2||multiplier>p.maxMultiplier||sub<1||sub>=multiplier)return false;- return p.handoff(parity,sub,multiplier,reset);+ return p.handoff(parity,sub,multiplier,reset,fast);#else- (void)parity;(void)sub;(void)multiplier;(void)reset;return false;+ (void)parity;(void)sub;(void)multiplier;(void)reset;(void)fast;return false;#endif}VfgBackend::SubmissionState VfgBackend::submissionState(unsigned slot)const{diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 0ee14d66..5a811d21 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -261,6 +261,10 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystconst bool on = p.value(QStringLiteral("dlssgPerformance")).toBool();if (s.dlssgLite != on) { s.dlssgLite = on; changed = true; }}+ if (p.contains(QStringLiteral("vfgAutoRegulate"))) {+ const bool on = p.value(QStringLiteral("vfgAutoRegulate")).toBool();+ if (s.vfgAutoRegulate != on) { s.vfgAutoRegulate = on; changed = true; }+ }if (!defaultFlowApplied && p.contains(QStringLiteral("contentRate"))) {const int rate = p.value(QStringLiteral("contentRate")).toInt();if (rate >= 0 && rate <= int(engine::ContentRate::Capture60To30) && int(s.content) != rate) { s.content = static_cast<engine::ContentRate>(rate); changed = true; }diff --git a/src/ui/bridge/Chain.cpp b/src/ui/bridge/Chain.cppindex ec76f7f6..88fe2edc 100644--- a/src/ui/bridge/Chain.cpp+++ b/src/ui/bridge/Chain.cpp@@ -988,7 +988,7 @@ QVariantList QmlPlayerBridge::presetSaveParts() const {s.audioOffsetMs != 0);const QStringList flowNames{QStringLiteral("NVIDIA NVOF"), tr("AMD 光流"), QStringLiteral("GPU DIS")};const QStringList qualityNames{tr("性能"), tr("平衡"), tr("质量")};- const QStringList cadenceNames{tr("采用源时间戳"), tr("自动识别内容节奏"), tr("识别 30fps 内容"),+ const QStringList cadenceNames{tr("采用源时间戳"), tr("自动剔除重复帧"), tr("识别 30fps 内容"),tr("识别 50fps 内容"), tr("识别 60fps 内容"), tr("采集 60→30(PS5 30 帧)")};QString flowSummary = flowNames.value(int(s.opticalFlowBackend)) + QStringLiteral(" · ") +qualityNames.value(int(s.flow)) + QStringLiteral(" · ") + cadenceNames.value(int(s.content));diff --git a/src/ui/bridge/FrameGeneration.cpp b/src/ui/bridge/FrameGeneration.cppindex 88098cf9..74c4bbfa 100644--- a/src/ui/bridge/FrameGeneration.cpp+++ b/src/ui/bridge/FrameGeneration.cpp@@ -224,6 +224,16 @@ void QmlPlayerBridge::setDlssgLite(bool value) {if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "DLSS performance mode not saved");emit settingsChanged();}+bool QmlPlayerBridge::vfgAutoRegulate() const { return settings().vfgAutoRegulate; }+void QmlPlayerBridge::setVfgAutoRegulate(bool value) {+ auto s = settings();+ if (s.vfgAutoRegulate == value) return;+ s.vfgAutoRegulate = value;+ if (!impl_->commit(std::move(s))) { emit notice(tr("引擎未接受 VFG 自动调控,原设置保留"), true); return; }+ impl_->prefs[QStringLiteral("vfgAutoRegulate")] = value;+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "VFG auto regulation not saved");+ emit settingsChanged();+}bool QmlPlayerBridge::dlssgLiteAvailable() const {static const bool present = ngx::dlssgLiteRuntimePresent(runtime::localRuntimeDirectory());return present;diff --git a/src/ui/bridge/Status.cpp b/src/ui/bridge/Status.cppindex 156b4abe..54d40810 100644--- a/src/ui/bridge/Status.cpp+++ b/src/ui/bridge/Status.cpp@@ -362,7 +362,7 @@ void QmlPlayerBridge::updateRunStatus() {if(chosen.content!=engine::ContentRate::Transport){QString cadence;switch(chosen.content){- case engine::ContentRate::Auto:cadence=tr("自动识别内容节奏");break;+ case engine::ContentRate::Auto:cadence=tr("自动剔除重复帧");break;case engine::ContentRate::Fps30:cadence=tr("识别 %1 fps 内容").arg(30);break;case engine::ContentRate::Fps50:cadence=tr("识别 %1 fps 内容").arg(50);break;case engine::ContentRate::Fps60:cadence=tr("识别 %1 fps 内容").arg(60);break;diff --git a/tests/integration/PresentationPacingTests.cpp b/tests/integration/PresentationPacingTests.cppindex 5d8d4eb6..9446599e 100644--- a/tests/integration/PresentationPacingTests.cpp+++ b/tests/integration/PresentationPacingTests.cpp@@ -99,16 +99,23 @@ 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"||scenario==L"latency-screen-vfg"||scenario==L"screen-vfg")effects.frameGenerationBackend=FrameGenerationBackend::Vfg;+ // latency-screen-sr-vfg: a mode the budget really rejects, for the failed probe path of live VFG.+ const bool overBudgetVfg=scenario==L"latency-screen-sr-vfg";+ if(scenario==L"native-vfg"||scenario==L"latency-screen-vfg"||scenario==L"screen-vfg"||overBudgetVfg)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;}+ if(scenario==L"latency-screen-sr"||overBudgetVfg){effects.sr=true;effects.srTarget=veyra::pipeline::SrTarget::Uhd4K;}+ if(overBudgetVfg)effects.vfgQuality=2;+ // replay-vfg-low|medium|high: a clip through the live scheduler (with VEYRA_TEST_REPLAY_AS_CARD, paced like a capture card).+ const bool replayVfg=scenario.starts_with(L"replay-vfg-");+ if(replayVfg){effects.frameGenerationBackend=FrameGenerationBackend::Vfg;effects.vfgQuality=scenario==L"replay-vfg-high"||scenario==L"replay-vfg-toggle"?2:scenario==L"replay-vfg-medium"?1:0;}+ if(GetEnvironmentVariableW(L"VEYRA_TEST_VFG_NO_AUTO_REGULATE",nullptr,0)>0)effects.vfgAutoRegulate=false;if(physical){effects.nr=true;effects.sr=false;}- auto options=PlayerOptions::from(effects);options.captureReplayForTest=scenario==L"replay";+ auto options=PlayerOptions::from(effects);options.captureReplayForTest=scenario==L"replay"||replayVfg;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;},scenario==L"native-effects"||scenario==L"latency-screen-sr"?30000:15000),"first frames");+ check(wait([](auto& s){return s.frames>10;},scenario==L"native-effects"||scenario==L"latency-screen-sr"||overBudgetVfg?30000:15000),"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;@@ -129,7 +136,12 @@ int wmain(int argc,wchar_t** argv){check(!last.failed&&last.frames>first.frames+10&&speed>.8&&speed<1.2,"sustained playback at media speed");// Without FG the ready->Present wait is display capacity only, never a first-frame PTS anchor.if(latency&&multiplier==1){std::cout<<"schedulingWaitP95Ms="<<last.schedulingWaitP95Ms<<std::endl;check(last.schedulingWaitP95Ms<1000.0/std::max<DWORD>(dm.dmDisplayFrequency,30)+2,"screen capture without FG is held at most one display refresh");}- if(multiplier>1)check(last.fgActive&&last.generated>first.generated,"real provider generated frames during measurement");+ if(scenario==L"replay-vfg-toggle")for(const bool on:{false,true}){+ effects.vfgAutoRegulate=on;check(engine.requestSettings(effects),"VFG auto regulation change accepted");+ const auto changed=Clock::now();+ check(wait([&](auto& s){return Clock::now()-changed>std::chrono::seconds(3)&&s.applied.vfgAutoRegulate==on&&s.fgActive;},20000),"VFG auto regulation change applied with VFG still running");+ }+ if(multiplier>1&&!overBudgetVfg)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");if(mode>=0&&!xess)check(last.presentationEffective.enabled,"optional pacing active");if((native||latency)&&mode>=0&&!xess)check(last.presentationEffective.nvidiaLowLatency==p.nvidiaLowLatency,"requested native NVIDIA low latency mode actually active with or without FG");diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cppindex 3de64fd8..dcaf458a 100644--- a/tests/unit/LiveGpuSchedulerTests.cpp+++ b/tests/unit/LiveGpuSchedulerTests.cpp@@ -155,46 +155,74 @@ int main(){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");+ using veyra::engine::FgCostSettling;+ FgCostSettling settling;const int64_t pair=333667;int64_t t=100000000;+ check(!settling.observe(false,true,t),"the first evaluation is a steady sample");+ check(!settling.observe(false,true,t+=pair),"continuous evaluations are steady samples");+ check(!settling.observe(true,false,t+=pair)&&!settling.observe(false,true,t+=pair),"one skipped pair hides nothing");+ check(!settling.observe(false,false,t+=pair),"a group without FG is no sample of FG");+ t+=FgCostSettling::kIdle100ns;+ check(settling.observe(false,true,t)&&settling.observe(false,true,t+=pair)&&!settling.observe(false,true,t+=pair),"after a second without an evaluation the next two are warmup");+ check(!settling.holding(t),"a probe holds nothing until it fails");+ const auto failProbe=[&]{+ for(int i=0;i<60&&settling.holding(t);++i)t+=pair;+ t+=FgCostSettling::kIdle100ns;+ settling.observe(false,true,t);settling.observe(false,true,t+=pair);settling.observe(false,true,t+=pair);+ settling.observe(true,false,t+=pair);+ return settling.holdUntil()-t;+ };+ check(settling.observe(true,false,t+=pair)==false&&settling.holdUntil()-t==20000000,"a probe rejected right after settling retries after 2 s");+ check(failProbe()==40000000&&failProbe()==80000000&&failProbe()==80000000,"further failed probes retry after 4 s, then every 8 s");+ check(settling.holding(t)&&!settling.holding(t+80000000),"the hold ends on time");+ t+=80000000+FgCostSettling::kIdle100ns;+ settling.observe(false,true,t);settling.observe(false,true,t+=pair);+ for(unsigned i=0;i<FgCostSettling::kProbeGroups;++i)check(!settling.observe(false,true,t+=pair),"evaluations after settling are steady samples");+ settling.observe(true,false,t+=pair);+ check(!settling.holding(t),"a probe that ran on clears the failures: a later skip holds nothing");+ t+=FgCostSettling::kIdle100ns;+ settling.observe(false,true,t);settling.observe(false,true,t+=pair);settling.observe(false,true,t+=pair);settling.observe(true,false,t+=pair);+ check(settling.holdUntil()-t==20000000,"the next failed probe starts over at 2 s");+ settling.reset();check(!settling.holding(t)&&!settling.observe(false,true,t+FgCostSettling::kIdle100ns),"settings revision reset clears everything");// 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;+ // (window) after 2 s of skipping. One second of FG at 33 ms starts it, as a+ // hiccup did. afterSkip is the cost after one skipped pair; the log has no such+ // sample, so it is varied. Returns evaluated pairs of the last 20 s of 60 s.+ const auto replay=[](double continuous,double isolated,double afterSkip,bool settle,unsigned& maxPer2s){+ veyra::engine::FgRecoveryBudget replayBudget;FgCostSettling cost;const int64_t interval=333667;- bool previous=true;unsigned evaluated=0,window=0;maxPer2s=0;+ bool previous=true;int64_t lastEvaluated=100000000;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);+ const bool admitted=(!settle||!cost.holding(now))&&replayBudget.admit(now,now+interval/2+allowance-5000,.2,.45);+ const double fg=n<30?33:now-lastEvaluated>=10000000?isolated:previous?continuous:afterSkip;+ const int64_t done=now+int64_t((admitted?3.4+fg:1.45)*10000);+ const bool warmup=settle&&cost.observe(!admitted,admitted,done);+ if(admitted){replayBudget.complete(3.4+fg,true,warmup,done,fg);lastEvaluated=done;}+ else replayBudget.complete(1.45,false,false,done);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);+ const auto trapped=replay(23.1,39.6,23.1,false,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);+ const auto recoveredFull=replay(23.1,39.6,23.1,true,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);+ check(replay(23.1,28.5,23.1,true,per2s)==600,"replay: windowed probes at 28.5 ms recover full FG");+ check(replay(23.1,39.6,39.6,true,per2s)==600,"replay: also if one skipped pair cost as much as a long skip");+ const auto overload=replay(46,46,46,true,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");+ check(overload<=9&&per2s<=3,"replay: a mode that really is too slow settles at three groups per 8 s");+ unsigned before2s=0;+ check(replay(46,46,46,true,per2s)<=replay(46,46,46,false,before2s),"replay: a mode too slow evaluates no more often than the lone probe did");+ check(replay(29,29,29,true,per2s)<=9,"replay: 29 ms misses the 10 ms bound and stays rejected");+ check(replay(29,46,46,true,per2s)<=9,"replay: so does 29 ms with a slower first evaluation");+ check(replay(25.5,25.5,25.5,true,per2s)==600,"replay: 25.5 ms fits the 10 ms bound and runs on");}veyra::engine::LivePairLatency phase;check(phase.select(10000000,420000,333333,4)==420000,"unknown live readiness keeps legacy phase");diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cppindex 7b74e785..8b6c8ac0 100644--- a/tests/unit/LivePresentationTimingTests.cpp+++ b/tests/unit/LivePresentationTimingTests.cpp@@ -177,45 +177,96 @@ int main(){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;+ using veyra::engine::LiveArrivalSmoother;+ const int64_t interval=333667,lead=LiveArrivalSmoother::kLead100ns;+ LiveArrivalSmoother clean;bool exact=true;+ for(int i=0;i<300;++i)exact&=clean.anchor(i*interval,i*interval+5000000,interval)==i*interval+5000000-lead;+ check(exact,"callbacks without jitter anchor where they arrive, less the lead");+ clean.reset();check(clean.anchor(0,7000000,interval)==7000000-lead,"after a reset the first callback is the anchor");+ // Field log 2026-10-31: 29.972 fps, callback sd 1.87 ms, PTS 800 ppm off the+ // host clock (either way here). 100 ns units.+ const auto gaussian=[](uint32_t& seed,double sd){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;};+ for(double ppm:{800.0,-800.0,0.0}){+ LiveArrivalSmoother smoother;uint32_t seed=7;double shift=0,spread=0,raw=0;unsigned count=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;+ const double line=n*333643.0+40000,callback=line+gaussian(seed,18700);+ const auto anchor=smoother.anchor(int64_t(n*333643.0*(1-ppm*1e-6)),int64_t(callback),interval);+ if(n<300)continue;+ shift+=double(anchor+lead)-line;spread+=std::abs(double(anchor+lead)-line);raw+=std::abs(callback-line);++count;+ }+ printf("anchor at %.0f ppm: mean %.3f ms from the callback line, mean distance %.3f ms, callback %.3f ms\n",ppm,shift/count/10000,spread/count/10000,raw/count/10000);+ check(std::abs(shift/count)<=1000,"the anchor keeps the mean callback whichever clock is faster: no added delay");+ check(spread*2<raw,"the anchor carries less than half of the callback jitter");+ }+ LiveArrivalSmoother jumps;+ for(int i=0;i<100;++i)jumps.anchor(i*interval,i*interval+50000,interval);+ check(jumps.anchor(100*interval,100*interval+140000,interval)==100*interval+50000-lead,"one callback 9 ms off the line does not move it");+ check(jumps.anchor(101*interval,101*interval+50000,interval)==101*interval+50000-lead&&jumps.snaps()==0,"and the next one is back on the line");+ check(jumps.anchor(102*interval,102*interval+140000,interval)==102*interval+50000-lead&&jumps.anchor(103*interval,103*interval-40000,interval)==103*interval+50000-lead,"callbacks off the line on opposite sides do not move it");+ check(jumps.anchor(104*interval,104*interval-40000,interval)==104*interval-40000-lead&&jumps.snaps()==1,"a second one on the same side moves it at once");+ for(int i=105;i<115;++i)jumps.anchor(i*interval,i*interval+10000,interval);+ int64_t settled=0;+ for(int i=115;i<195;++i)settled=jumps.anchor(i*interval,i*interval+10000,interval)-i*interval;+ check(std::abs(settled-(10000-lead))<=1000,"a 5 ms step within the limit is tracked within 90 pairs");+ LiveArrivalSmoother fast;+ for(int i=0;i<20;++i)fast.anchor(i*83333,i*83333+50000,83333);+ check(fast.anchor(20*83333,20*83333+85000,83333)==20*83333+50000-lead&&fast.anchor(21*83333,21*83333+85000,83333)==21*83333+85000-lead,"the limit follows a shorter interval");+ using veyra::engine::liveGeneratedGrace100ns;+ check(liveGeneratedGrace100ns(1000000,1000000)==100000&&liveGeneratedGrace100ns(1000000,1010000)==100000,"on time or early callback: a generated frame keeps 10 ms from its due time");+ check(liveGeneratedGrace100ns(1030000,1000000)==130000,"late callback: its frame expires when it did on the callback anchor");+ using veyra::engine::liveFramesShareRefresh;+ const double refresh=166667;+ check(liveFramesShareRefresh(1020000,1100000,1000000,refresh,10000),"no vblank between the two presents: one refresh shows them");+ check(!liveFramesShareRefresh(1120000,1300000,1000000,refresh,10000),"a vblank between them: both are shown");+ check(liveFramesShareRefresh(1160000,1300000,1000000,refresh,10000),"a present inside the latch misses that vblank");+ check(!liveFramesShareRefresh(1020000,1100000,1000000,0,10000),"no refresh grid selects nothing");+ check(liveFramesShareRefresh(1300000,1250000,1000000,refresh,10000),"a generated frame ready after its real frame cannot be shown");+ using veyra::engine::liveSmoothedCapacityWaitMs;+ check(liveSmoothedCapacityWaitMs(3.125)==2&&liveSmoothedCapacityWaitMs(4.17)==2,"high refresh MFG keeps the 2 ms capacity wait");+ check(std::abs(liveSmoothedCapacityWaitMs(16.68)-1.03)<.01&&liveSmoothedCapacityWaitMs(33.4)==1,"60 Hz 2X waits about 1 ms, and never less");+ check(liveSmoothedCapacityWaitMs(8.33)>1.5&&liveSmoothedCapacityWaitMs(8.33)<2,"120 Hz 2X lies between");+ // Present(0,0) on 60.005 Hz fed with those pairs on the adaptive phase. VFG+ // medium: generated ready 8.5 ms after the callback, 0.3 ms of wake-up jitter.+ // The panel shows the last present before each refresh. A real frame replaced+ // there still reached it inside the next generated frame, so it counts too.+ struct Shown{unsigned lost=0,lostReal=0,count=0;double mean=0,callbackP95=0;};+ const auto display=[&](bool smooth,double ppm){+ const double refresh=1e7/60.0049,source=1e7/29.9722,ready=85000,delay=ready+source/2+5000,latch=3000;+ struct Item{double time;bool real;double capture,callback;};+ std::vector<Item> items;items.reserve(36000);uint32_t seed=11;LiveArrivalSmoother smoother;+ for(unsigned n=0;n<18000;++n){+ const double capture=n*source,callback=capture+40000+gaussian(seed,18700);+ const double anchor=smooth?double(smoother.anchor(int64_t(capture*(1-ppm*1e-6)),int64_t(callback),int64_t(source))):callback;+ const double real=anchor+delay;+ items.push_back({std::max(real-source/2,callback+ready)+std::abs(gaussian(seed,3000)),false,capture,callback});+ items.push_back({real+std::abs(gaussian(seed,3000)),true,capture,callback});+ }+ std::stable_sort(items.begin(),items.end(),[](const Item& a,const Item& b){return a.time<b.time;});+ Shown r;std::vector<double> fromCallback;std::vector<const Item*> replaced;const Item* pending=nullptr;double sum=0;+ double scan=(std::floor((items[0].time+latch)/refresh+1e-9)+1)*refresh;+ for(const auto& item:items){+ while(scan<=item.time+latch){+ if(pending){+ if(pending->real)replaced.push_back(pending);+ for(const auto* shown:replaced){sum+=scan-shown->capture;fromCallback.push_back(scan-shown->callback);}+ }+ pending=nullptr;replaced.clear();scan+=refresh;+ }+ if(pending){++r.lost;if(pending->real){++r.lostReal;replaced.push_back(pending);}}+ pending=&item;}+ std::sort(fromCallback.begin(),fromCallback.end());+ r.count=unsigned(items.size());r.mean=sum/fromCallback.size();r.callbackP95=fromCallback[(fromCallback.size()-1)*95/100];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");+ for(double ppm:{800.0,-800.0}){+ const auto before=display(false,ppm),after=display(true,ppm);+ printf("60 Hz display at %.0f ppm: lost %.2f%% -> %.2f%%, real %.2f%% -> %.2f%%, capture-to-panel mean %.2f -> %.2f ms, callback P95 %.2f -> %.2f ms\n",ppm,100.0*before.lost/before.count,100.0*after.lost/after.count,100.0*before.lostReal/before.count,100.0*after.lostReal/after.count,before.mean/10000,after.mean/10000,before.callbackP95/10000,after.callbackP95/10000);+ check(after.lost*10<=before.lost*8,"60 Hz replay: at least a fifth fewer frames are lost");+ check(after.lostReal*5<=before.lostReal,"60 Hz replay: real frames are hardly lost any more");+ check(after.mean<=before.mean,"60 Hz replay: capture-to-panel latency does not grow");+ check(after.callbackP95<=before.callbackP95+2000,"60 Hz replay: the latency this application reports does not grow at P95");+ }}{// 60 fps window capture without FG (2026-10-29): the first frame was readdiff --git a/tests/unit/RealtimePreviewSchedulingTests.cpp b/tests/unit/RealtimePreviewSchedulingTests.cppindex ace1ff44..ae1781fe 100644--- a/tests/unit/RealtimePreviewSchedulingTests.cpp+++ b/tests/unit/RealtimePreviewSchedulingTests.cpp@@ -159,12 +159,6 @@ 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 1ae312fa..f8404d46 100644--- a/tests/unit/UiLanguageTests.cpp+++ b/tests/unit/UiLanguageTests.cpp@@ -40,9 +40,6 @@ 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");