Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

fix(presentation): restore Automatic display sync to Present(0,0)

Veyra Goal Agentc1dd0a2d66f7
diff --git a/AGENTS.md b/AGENTS.md
index f8ef8611..0ebeabad 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,6 +4,8 @@
> **2026-10-12 用户确认 Claude 内容节奏修复实机通过并授权合并重打 2.0.7**:从 main05bc4b5 隔离合入 claude/cadence-exact-20261012(60a93f3、8d11cad),按 docs/TEST_2.0.7_REFRESH_2026-10-12.md 重新构建、定向回归、本地 main 合并与 NVIDIA/AMD 完整测试包;显示2.0.7-test-r2。保护68旧树/509脏文件及已交付原包,全部研发产物在E盘新任务目录。不改用户正在运行的播放器/配置、UI频率/默认GPU优先级/运行库/模型,无新push/Release/关机或子Agent授权。
+> **2026-10-13 极限低延迟(Claude)**:用户读完 112ms 排查后明确要求“已经有垂直同步按钮了还把自动弄得和垂直同步一样,弄回原来的那种,和游戏同款的,我们软件首要要求就是延迟压到最低,现在重新写修复方案,延迟必须要做到极限的低!但不要允许撕裂”。存档 `checkpoint/pre-claude-latency-min-20261013`(main 7571919),分支 `claude/latency-min-20261013`,产物统一 `{用途}/claude-latency-min-20261013`。A1 已实施:显示同步“自动”恢复 2.0.4 语义 `Present(0,0)`(新帧替换未显示的旧帧、不等待垂直同步、不传撕裂标志,原生与 XeSS 路径都生效),状态栏/设置提示改写并追加翻译;“垂直同步”“允许撕裂”不变。A2 诊断:display-stats 增加 presentsAhead,自动模式也统计送显→上屏。后续 B1–C3 按 docs/LATENCY_MIN_PLAN_2026-10-13.md,逐步提交、可 A/B、负优化退回。不改运行库/模型/驱动/用户配置;无 merge/push/Release/子 Agent;测试≤300秒、构建≤900秒。
+
> **2026-10-12 内容节奏修正(Claude)**:用户实测 2.0.7:“采集 60→30”被植入内容节奏判断、原始帧率跳动,要求还原为最简单的 60 帧 AABBCCDD→ABCD 稳定隔帧;新“自动识别内容节奏”去重不稳定(VFG 耗时、GPU 占用忽高忽低),游戏运行中出现 6fps,怀疑不是百分百相同的帧也被去掉。追加授权关闭用户正在运行的 Veyra、直接用 T911 实卡(2K60 NV12、游戏 30 帧)测试。存档 `checkpoint/pre-claude-cadence-exact-20261012`(main 05bc4b5)与 `archives/claude-cadence-exact-20261012`,分支 `claude/cadence-exact-20261012`。60→30 恢复 `CaptureHalfRate`(与 85cbd5a 之前相同、不经去重);内容模式整画面逐像素与上一张新画面比较,每个分量都在 ±3 级(8 位刻度)以内才算重复(`PictureCompare.h`,采集回调只在去重开启时比较驱动样本并给帧编画面号);逐字节相同在实卡上从不成立(T911 重复帧 ±1–2 级噪声),该版本已被实卡数据否决。见 docs/CONTENT_CADENCE_EXACT_2026-10-12.md。不改默认设置、NR/SR/FG 模型、运行库;用户设置只读取并复制进测试包;无 merge/push/Release/子 Agent。
> **2026-10-12 构建前采集格式追加授权**:用户要求分辨率先行、MJPEG 标红(不建议使用)、无效组合明确弹错且不自动路由其他格式。允许最小 UI/桥接/采集协商修复和有关回归,保留有效上次配置;与本轮整合一起本地合入 main 和 2.0.7 测试包。
diff --git a/docs/LATENCY_MIN_PLAN_2026-10-13.md b/docs/LATENCY_MIN_PLAN_2026-10-13.md
new file mode 100644
index 00000000..533adde5
--- /dev/null
+++ b/docs/LATENCY_MIN_PLAN_2026-10-13.md
@@ -0,0 +1,47 @@
+# 极限低延迟(不撕裂)修复方案(Claude,2026-10-13)
+
+用户要求:“已经有垂直同步按钮了还把自动弄得和垂直同步一样,弄回原来的那种,和游戏同款的,我们软件首要要求就是延迟压到最低,现在重新写修复方案,延迟必须要做到极限的低!但不要允许撕裂”。
+
+分支 `claude/latency-min-20261013`(从 main 7571919 开出),存档标签 `checkpoint/pre-claude-latency-min-20261013`。产物统一在 `E:/项目/Veyra/{build,tests,logs,tmp,reports}/claude-latency-min-20261013`。不合并 main、不推送、不发布,除非用户另行授权;不改运行库/模型/驱动/用户配置;每个测试 ≤300 秒,构建 ≤900 秒。
+
+## 1. 现状问题(证据见 reports/claude-latency-20261013)
+
+1. 2.0.6(ef2069f)把“自动”从 `Present(0,0)`(新帧替换未显示的旧帧)改成 `Present(1,0)`(垂直同步)。输出帧率超过刷新率时帧会排队:60Hz PBP 下 4K NR+XeSS 2X 光学延迟 112ms(关效果 33ms)。
+2. 原生路径“垂直同步时队列 1 帧”实际没生效:设置了最大延迟 1,但默认模式没人等待可等待对象。小程序实测排 7 帧;320Hz 实卡 DLSS 6X(360fps)送显→上屏 P50 从 4X 的 5.6ms 涨到 11.8ms。现有“低延迟队列”和“跟随显示器上限”都压不住。
+3. XeSS 路径:N 卡上 XeLL 不做“补帧时限到半刷新并对齐 VSync”(Intel 文档写明仅 Intel 显卡);XeSS 与 NR 共用 GPU 队列;“GPU 未完成不叠第二帧”的门对 XeSS 关闭;XeLL 周期错位(上一帧送显前就开始下一帧的 XeLL 睡眠)。
+4. 输出超过刷新率时,补帧的帧要么排队加延迟,要么在显示端被替换掉白算。
+
+## 2. 设计原则
+
+1. **永不排队**:显示器显示不过来的帧,要么不生成,要么在显示前被更新的帧替换;交换链、Intel 送显层、GPU 队列、调度器任何一级都不积压。
+2. **不撕裂**:只有用户显式选择“允许撕裂”才传 `DXGI_PRESENT_ALLOW_TEARING`。
+3. **节流只在读帧之前**:需要等待时只在读采集帧之前等;读入之后处理和送显全程不再等待(GPU 按队列顺序执行)。
+4. **补帧只付原理成本**:真帧只等 (倍数−1)/倍数 个源间隔加补帧计算,不再有其他等待。
+5. **不受限时不变**:输出低于刷新率时(例如 320Hz 下 2X/4X)画面和节奏与现在一致。
+
+## 3. 阶段
+
+| 阶段 | 内容 | 预期 | 验证 |
+|---|---|---|---|
+| **A1 “自动”恢复**(本次授权,已实施) | `presentationVsync()` 只对“垂直同步”返回 true;“自动”=`Present(0,0)`,原生和 XeSS 两条路径都生效;状态栏与设置提示改写;“垂直同步”“允许撕裂”不变 | 输出超过刷新率时不再排队(原生实测 7 帧→约 1 帧);不受限时延迟不变 | 320Hz DLSS 6X 场景送显→上屏回到约 2–5ms;2X/4X、XeSS 2X、仅 NR 不变;Present 参数日志 sync=0 flags=0;60Hz PBP 由用户光学复测 |
+| **A2 诊断**(随 A1) | 每秒记录 presentsAhead(GetLastPresentCount−已显示 PresentCount);“自动”模式也统计送显→上屏(只按确认上屏的那一帧) | 以后的日志能直接看出是否排队 | 日志字段存在且数值合理 |
+| **B1 XeSS“提交即送显”** | XeSS 时读帧→处理→立即打标签并 Present,不再由调度器等 GPU 完成后才送;一个 XeLL 周期内完成 睡眠→读输入→提交→送显,修正周期错位 | 去掉 CPU 等 GPU 的约 7ms 和轮询抖动;XeLL 的队列控制按设计生效 | 320Hz/60Hz 下 XeSS 回调→送显、真帧率、XeLL 睡眠时长;画面校验无错帧 |
+| **B2 补帧输出预算** | 内容帧率×倍数 > 0.97×刷新率时:DLSS/FSR/VFG 自动降到能放下的合法倍数;连 2X 都放不下(如 60Hz 屏 + 60fps 源)就旁路补帧,真帧直接显示、不等插帧;XeSS 用 SetEnabled(false) 旁路;带迟滞防抖,状态栏说明原因 | 不浪费 GPU、动作均匀;60Hz+60fps 时延迟等于仅 NR | DLSS 6X@320Hz 自动降到 4X;60Hz 下 2X 旁路;30fps 游戏 + 2X@60Hz 不被误判 |
+| **B3 “垂直同步”也不排队** | 用户显式选垂直同步时,在读采集帧之前等待可等待对象(≤1 个刷新),不在送显前等;XeSS 代理最大延迟设 1;“低延迟队列”改成这个语义 | 垂直同步模式下的排队上限 1 帧 | DLSS 6X@320Hz 垂直同步模式送显→上屏≈1 个刷新;回调→送显不升 |
+| **C1 VRR 研究** | 用户在驱动开启 G-SYNC/FreeSync 后,实测“自动”是否触发可变刷新;若不触发,评估“垂直同步 + B2 输出预算(输出始终低于最高刷新)”的 VRR 模式(不会撕裂) | 少等 0–1 个刷新(60Hz 平均约 8ms) | 需用户开启 VRR;对比送显→上屏 |
+| **C2 独立翻转确认** | 用 PresentMon(需管理员)确认全屏/窗口的呈现模式;窗口合成会多 1 个刷新 | 明确“全屏更低”的条件或修掉窗口合成 | PresentMon PresentMode 列 |
+| **C3 采集拷贝** | 4K NV12 回调拷贝约 1.5ms,研究直接以驱动缓冲上传 | ≤1.5ms | 回调耗时日志 |
+
+实施顺序:A1+A2 → B1 → B2 → B3 → C*。每步独立提交,测试开关可退回旧行为做 A/B;负优化直接退回并记录。
+
+## 4. 理论延迟与验收目标(4K60 NV12 源,RTX 5070,相对 HDMI 直连)
+
+组成:采集卡约 15ms(硬件/USB,软件无法改变)+ Veyra 基础约 3ms + NR 约 7ms + 补帧计算 2–3ms(VFG 约 15ms)+ 补帧原理等待 (倍数−1)/倍数×源间隔(60fps 2X 8.3ms)+ 等刷新 0–1 个刷新(VRR 下约 0)。
+
+| 场景 | 关效果 | 仅 NR | NR+2X |
+|---|---|---|---|
+| 320Hz 日常 | ≈20ms | ≈27ms | ≈37–42ms |
+| 60Hz PBP,60fps 源 | 33ms(实测,相位决定) | ≈33–50ms | A1 后≈45–55ms;B2 后=仅 NR |
+| 60Hz PBP,30fps 源 | ≈33ms | ≈33–50ms | ≈50–60ms |
+
+60Hz 下处理时间会被刷新量化(同一处理可能落在原本要等的空档里,也可能错过一个刷新)。320Hz 行为推算,最终以用户光学测量为准。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 4abca2f6..d53815e8 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -9345,3 +9345,15 @@ ZIP/EXE原字节晋级,仅外部下载名去test-r2;包内显示原标识在
v2.0.7 ID 410800361,published_at 2026-10-12T16:24:59Z,latest/非草稿/非预发布通过;两个运行资产服务器SHA/size等于原test-r2。v2.0.7-sources ID 410800322,两源资产、非latest,未变依赖源保留v2.0.6。main/tag6ede5a7普通atomic推送成功,产品与67ab696相同,后续只补回执文档。remote.py draft/upload/verify-draft/publish/verify-public均通过;public-check.py final全部公开文档/双QR/Ko-fi/Release/下载200,六群原图SHA吻合,飞书带Cookie匿名GET200。最初无Cookie404/循环证据保留,不把它写成知识库本身失效。
旧v2.0.6Release完整稳定字段不变,68其它树/509脏文件/全部原包保护通过。详细docs/RELEASE_2.0.7_REPORT_2026-10-13.md;外部reports/logs回执固定远端正文/资产digest。只读发布辅助检查曾因utf8-sig别名和依赖回执尚未完成失败,原错误说明保留,改编码/顺序后原检查通过,未重发或改资产。原扩展NR+DLSS热切换失败和NV显存/BMD/HDR/AMD实卡限制保留,没有新性能或全硬件通过声明。群公告632字符仅保存给用户,无代发/关机。
+
+## 2026-10-13 极限低延迟 A1/A2(Claude)
+
+用户要求把显示同步“自动”恢复成 2.0.4 前的游戏同款(不撕裂、不等垂直同步),延迟压到极限。排查依据见 E:/项目/Veyra/reports/claude-latency-20261013(112ms 根因、DXGI 小程序、320Hz 实卡)。方案 docs/LATENCY_MIN_PLAN_2026-10-13.md。
+
+改动:`presentationVsync()` 只对 Vsync 返回 true,“自动”= `Present(0,0)`;VideoPresenter 状态文字、ProPage 提示与 catalog 追加条目;PresentSink 每秒记录 presentsAhead,自动模式送显→上屏只按确认上屏的帧统计;RepairContract/UiContract 测试期望按新语义更新。
+
+构建:`py -3.11 -I E:/项目/Veyra/tmp/claude-latency-min-20261013/build.py`(只读复用 build/test-2.0.7-refresh-20261012,main 7571919 与 r2 产品源码一致;重编 19 个对象,未重编的包含者只属于本次不构建的测试程序),回执 logs/claude-latency-min-20261013/build-20261013-205844/receipt.json。
+
+测试(私有程序副本 tests/claude-latency-min-20261013/app):veyra_repair_contract_tests 259 项 0 失败;veyra_ui_contract_tests 通过;新验收 `scripts/acceptance/latency-min-tests.py` display-sync 12/12(窗口/全屏×低延迟队列×三种模式,实际 Present 参数:自动 sync=0 flags=0,垂直同步 sync=1,允许撕裂 0x200;像素校验通过,D3D12 错误 0),lifecycle 通过。历史 2.0.6 验收脚本仍写死“自动=sync1”,按规则不改旧脚本。
+
+实卡(T911 2K60 NV12 → NR,320Hz,内容不去重):DLSS 6X(360fps 超刷新率)送显→上屏 P50/P95 由垂直同步语义的 11.8/18.3ms 降到 6.2/8.0ms,插帧过期 44→0.6/s,邮箱等待 11.2→0.3ms;同一 EXE 显式垂直同步仍为 12.2/18.4ms(B3 待做);DLSS 4X 5.4/7.0ms 与改前一致;XeSS 2X 自动 sync=0 flags=0,补帧正常 120fps,回调→送显 P95 10.0ms;仅 NR 8.9ms、送显→上屏 4.5ms。60Hz PBP 下 XeSS 超刷新率场景本机无法复现,需用户光学复测。日志 logs/claude-latency-min-20261013/<场景>/。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 4a7a569f..11eaf599 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -15716,6 +15716,20 @@
"zh-TW": "{} {}X 補幀初始化失敗,未替換後端或降低倍率;請查看工作診斷日誌",
"en": "{} {}X frame generation could not initialize. The backend and multiplier were retained; see the task diagnostic log.",
"ja": "{} {}X フレーム生成を初期化できませんでした。バックエンドと倍率は維持されています。タスク診断ログを確認してください。"
+ },
+ {
+ "zh": "显示同步:自动 · 不撕裂,也不等待垂直同步(延迟最低)",
+ "src": "src/engine/VideoPresenter.cpp",
+ "zh-TW": "顯示同步:自動 · 不撕裂,也不等待垂直同步(延遲最低)",
+ "en": "Display sync: auto · no tearing and no VSync wait (lowest latency)",
+ "ja": "表示の同期:自動 · ティアリングなし、垂直同期を待たない(最小遅延)"
+ },
+ {
+ "zh": "自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低 · 垂直同步:每帧都等刷新,输出帧率超过刷新率时会排队、延迟变大 · 允许撕裂:可能出现撕裂线",
+ "src": "qml/ProPage.qml",
+ "zh-TW": "自動(推薦):不撕裂,也不等待垂直同步,每次更新顯示最新一幀,延遲最低 · 垂直同步:每幀都等更新,輸出幀率超過更新率時會排隊、延遲變大 · 允許撕裂:可能出現撕裂線",
+ "en": "Auto (recommended): no tearing and no VSync wait; each refresh shows the newest frame for the lowest latency · VSync: every frame waits for a refresh and queues up, adding latency, when output exceeds the refresh rate · Allow tearing: tear lines may appear",
+ "ja": "自動(推奨):ティアリングなし、垂直同期を待たず、毎回のリフレッシュで最新フレームを表示し遅延が最小 · 垂直同期:全フレームがリフレッシュを待ち、出力がリフレッシュレートを超えるとキューが溜まり遅延が増加 · ティアリングを許可:ティアリングが発生する場合あり"
}
]
}
diff --git a/include/veyra/engine/PresentationSettings.h b/include/veyra/engine/PresentationSettings.h
index 2faa3c7d..95187ca5 100644
--- a/include/veyra/engine/PresentationSettings.h
+++ b/include/veyra/engine/PresentationSettings.h
@@ -25,12 +25,19 @@ struct PresentationSettings {
bool operator==(const PresentationSettings&) const = default;
bool valid()const{return unsigned(mode)<=2&&unsigned(display)<=2&&unsigned(outputRate)<=2&&std::isfinite(customFps)&&customFps>=1.0&&customFps<=1000.0;}
};
-// Automatic explicitly synchronizes the final swapchain to the display in
-// both windowed and fullscreen playback. Present(0,0) relies on the negotiated
-// compositor/provider path; it must not be sold as a universal tear-free mode.
-// The explicit Tearing choice keeps the unsynchronized path available.
+// Automatic never waits for vertical sync and never requests tearing: a
+// flip-model Present(0, 0) replaces a frame that has not been shown yet at the
+// next refresh, so the newest finished frame is the one shown and nothing
+// queues behind the display (games running uncapped in a borderless window).
+// Measured 2026-10-13 (claude-latency-20261013, 320 Hz, producer faster than
+// the display): the frame on screen was 1.0 refresh old with Present(0,0) and
+// 6.9 refreshes old with Present(1,0), whose queue the unwaited latency object
+// does not limit. 2.0.6 (ef2069f) had made Automatic identical to Vsync; the
+// 4K NR+XeSS capture measured 112 ms on a 60 Hz panel with it.
+// Explicit Vsync makes every frame wait for a refresh; only explicit Tearing
+// passes DXGI_PRESENT_ALLOW_TEARING.
constexpr bool presentationVsync(const PresentationSettings& s) {
- return s.display!=DisplaySync::Tearing;
+ return s.display==DisplaySync::Vsync;
}
constexpr bool presentationTearing(const PresentationSettings& s) {
return s.display==DisplaySync::Tearing;
diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.h
index ac8b957a..a48c31f6 100644
--- a/include/veyra/gfx/PresentSink.h
+++ b/include/veyra/gfx/PresentSink.h
@@ -110,6 +110,10 @@ public:
struct FrameStatisticsDelta {
bool supported=false;
uint64_t presents=0,displayed=0,refreshes=0,displayedRefresh=0;
+ // GetLastPresentCount - last shown PresentCount at the sample, -1 if
+ // either query failed. Under Vsync this is the display queue depth;
+ // with Present(0,0) it also counts frames a newer one will replace.
+ int64_t ahead=-1;
HRESULT result=S_OK;
};
FrameStatisticsDelta sampleFrameStatistics();
@@ -202,7 +206,9 @@ private:
uint64_t frameStatisticsBasePresents_=0;
UINT frameStatisticsBasePresentRefresh_=0,frameStatisticsBaseSyncRefresh_=0,frameStatisticsBaseDisplayed_=0;
void sampleDisplayLatency();
- struct PendingPresent { UINT id=0; int64_t qpc=0; };
+ // replaceable: Present(0,0); only the frame a later sample names as shown
+ // is dated, a newer present may have replaced the ones in between.
+ struct PendingPresent { UINT id=0; int64_t qpc=0; bool replaceable=false; };
std::array<PendingPresent,16> pendingPresents_{};
unsigned pendingPresentNext_=0;
UINT lastDisplayedPresent_=0,lastSyncRefresh_=0;
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index 084df410..a6b5046d 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -123,7 +123,7 @@ VPage {
spacing: 0
VRow {
label: qsTr("显示同步")
- hint: qsTr("自动:与屏幕同步防撕裂 · 提交帧率受屏幕刷新率限制 · 想再降延迟可选“允许撕裂”(可能撕裂)或在显卡驱动开启 G-SYNC/FreeSync,最多少等一次刷新(60Hz 约 8 ms)")
+ hint: qsTr("自动(推荐):不撕裂,也不等待垂直同步,每次刷新显示最新一帧,延迟最低 · 垂直同步:每帧都等刷新,输出帧率超过刷新率时会排队、延迟变大 · 允许撕裂:可能出现撕裂线")
VSeg {
objectName: "presentation-display-sync"
options: [{ id: "0", label: qsTr("允许撕裂") }, { id: "1", label: qsTr("垂直同步") }, { id: "2", label: qsTr("自动") }]
diff --git a/scripts/acceptance/latency-min-tests.py b/scripts/acceptance/latency-min-tests.py
new file mode 100644
index 00000000..fbd691e4
--- /dev/null
+++ b/scripts/acceptance/latency-min-tests.py
@@ -0,0 +1,46 @@
+"""claude/latency-min-20261013 acceptance: real windowed and borderless-fullscreen swapchains
+for each display-sync mode x low-queue setting, checking the actual Present arguments.
+
+Expected after restoring Automatic (2.0.4 semantics):
+ Tearing (0) -> Present(0, DXGI_PRESENT_ALLOW_TEARING)
+ Vsync (1) -> Present(1, 0)
+ Automatic (2) -> Present(0, 0) (newest frame replaces an unshown one; never tears)
+
+usage: python -X utf8 -B -I scripts/acceptance/latency-min-tests.py <app dir> <log dir> [display-sync|lifecycle]
+"""
+import re, subprocess, sys, time, json, os
+from pathlib import Path
+
+app, logs = Path(sys.argv[1]), Path(sys.argv[2]); case = sys.argv[3] if len(sys.argv) > 3 else 'display-sync'
+logs.mkdir(parents=True, exist_ok=True)
+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}
+tmp = logs / ('tmp-' + case); tmp.mkdir(exist_ok=True); env.update(TEMP=str(tmp), TMP=str(tmp))
+running = [l for l in subprocess.check_output(['tasklist', '/fo', 'csv', '/nh'], text=True, encoding='mbcs', errors='replace').splitlines() if l.lower().startswith('"veyra')]
+assert not running, 'another Veyra process is running: ' + repr(running)
+if case == 'display-sync':
+ command = [str(app / 'veyra_fg_presentation_tests.exe'), str(tmp / 'pixels'), str(app / 'runtime/experimental'), 'display-sync']
+elif case == 'lifecycle':
+ command = [str(app / 'veyra_present_sink_lifecycle_tests.exe'), str(tmp / 'lifecycle')]
+else:
+ raise SystemExit('unknown case ' + case)
+log = logs / (case + '-' + time.strftime('%H%M%S') + '.log'); begin = time.monotonic()
+with log.open('xb') as console:
+ try: rc = subprocess.run(command, cwd=app, env=env, stdout=console, stderr=subprocess.STDOUT, timeout=290).returncode
+ except subprocess.TimeoutExpired: rc = 124
+body = log.read_text(encoding='utf8', errors='replace')
+errors = [l for l in body.splitlines() if 'D3D12 ERROR' in l or 'D3D12 CORRUPTION' in l]
+result = dict(case=case, exit=rc, seconds=round(time.monotonic() - begin, 1), log=str(log), gpuErrors=errors)
+passed = rc == 0 and not errors
+if case == 'display-sync':
+ expected = {'0': (0, 0x200), '1': (1, 0), '2': (0, 0)}
+ sections = re.findall(r'DISPLAY_SYNC_BEGIN full=(\d) lowQueue=(\d) mode=(\d)(.*?)DISPLAY_SYNC_END full=\d lowQueue=\d mode=\d pass=(\d)', body, re.S)
+ rows = []
+ for full, low, mode, section, ok in sections:
+ calls = re.findall(r'\[present-contract\] backend=DXGI sync=(\d) flags=0x([0-9A-F]+) hr=0x([0-9A-F]+)', section)
+ good = ok == '1' and bool(calls) and all((int(s), int(f, 16)) == expected[mode] and int(h, 16) == 0 for s, f, h in calls)
+ rows.append(dict(full=full, lowQueue=low, mode=mode, calls=sorted(set(calls)), passed=good)); passed = passed and good
+ passed = passed and len(sections) == 12
+ result['sections'] = rows
+result['passed'] = passed
+(logs / (case + '.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf8')
+print(json.dumps(result, ensure_ascii=False, indent=1)[:3000]); raise SystemExit(0 if passed else 1)
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index dc3c8f3e..821af503 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -391,10 +391,10 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
// display actually scanned out. This is still not a photon measurement.
static const bool displayStats=GetEnvironmentVariableW(L"VEYRA_TEST_NO_DISPLAY_STATS",nullptr,0)==0;
const auto stats=displayStats?sink_.sampleFrameStatistics():gfx::PresentSink::FrameStatisticsDelta{};
- if(stats.supported)veyra::log::info("display-stats",std::format("refreshHz={:.3f} presentCalls={} dxgiPresentCount={} refreshes={} presentRefreshDelta={} backend={} (DXGI GetFrameStatistics delta over ~1s. These counters CANNOT tell how many frames the panel actually showed: with vsync off and tearing allowed, dxgiPresentCount tracks completed Present calls, and both refresh counters just advance with the monitor. Measuring scanout needs PresentMon. XeSS generated presents are provider-internal.)",sink_.displayRefreshHz(),stats.presents,stats.displayed,stats.refreshes,stats.displayedRefresh,sink_.xess()?"XeSS":"DXGI"));
+ if(stats.supported)veyra::log::info("display-stats",std::format("refreshHz={:.3f} presentCalls={} dxgiPresentCount={} refreshes={} presentRefreshDelta={} presentsAhead={} backend={} (DXGI GetFrameStatistics delta over ~1s. These counters CANNOT tell how many frames the panel actually showed: with vsync off and tearing allowed, dxgiPresentCount tracks completed Present calls, and both refresh counters just advance with the monitor. presentsAhead = submitted presents after the last shown one at the sample: the display queue under VSync; with Automatic Present(0,0) it includes frames a newer one replaces; -1 unavailable. Measuring scanout needs PresentMon. XeSS generated presents are provider-internal.)",sink_.displayRefreshHz(),stats.presents,stats.displayed,stats.refreshes,stats.displayedRefresh,stats.ahead,sink_.xess()?"XeSS":"DXGI"));
else if(FAILED(stats.result))veyra::log::info("display-stats",std::format("unavailable hr=0x{:X} backend={}",unsigned(stats.result),sink_.xess()?"XeSS":"DXGI"));
const auto scanout=displayStats?sink_.takeDisplayLatency():gfx::PresentSink::DisplayLatencySummary{};
- if(scanout.samples||scanout.compositionMode>=0)veyra::log::info("display-latency",std::format("presentToScanoutP50Ms={:.3f} presentToScanoutP95Ms={:.3f} presentToScanoutMaxMs={:.3f} samples={} compositionMode={} refreshHz={:.3f} (DXGI frame statistics: Present call to the vblank that showed it, VSync DXGI presents only; compositionMode 0 composed 1 overlay 2 none 3 failure -1 unknown; not a photon measurement)",scanout.p50Ms,scanout.p95Ms,scanout.maxMs,scanout.samples,scanout.compositionMode,sink_.displayRefreshHz()));
+ if(scanout.samples||scanout.compositionMode>=0)veyra::log::info("display-latency",std::format("presentToScanoutP50Ms={:.3f} presentToScanoutP95Ms={:.3f} presentToScanoutMaxMs={:.3f} samples={} compositionMode={} refreshHz={:.3f} (DXGI frame statistics: Present call to the vblank that showed it, VSync and Automatic DXGI presents; Automatic dates only frames named as shown; compositionMode 0 composed 1 overlay 2 none 3 failure -1 unknown; not a photon measurement)",scanout.p50Ms,scanout.p95Ms,scanout.maxMs,scanout.samples,scanout.compositionMode,sink_.displayRefreshHz()));
const auto& timing=sink_.lastPresentTiming();
veyra::log::info("present-cost",std::format("generated={} totalMs={:.3f} recordSubmitMs={:.3f} slotWaitMs={:.3f} dxgiMs={:.3f} slow={} source={} epoch={} backend={} resized={} resizeMs={:.3f} beginMs={:.3f} commandsMs={:.3f} beforeMs={:.3f} presentCallMs={:.3f} bufferMs={:.3f} afterMs={:.3f} hr=0x{:X}",generated,
std::chrono::duration<double,std::milli>(presentEnd-presentStart).count(),
@@ -464,7 +464,7 @@ PresentationSettings VideoPresenter::configurePresentation(gfx::D3D12DeviceConte
}
const bool vsync=presentationVsync(requested),tearing=presentationTearing(requested);
providerOwnedPresentation_=xessActive();
- const std::wstring sync=requested.display==DisplaySync::Automatic?L"显示同步:自动 · 与屏幕同步防撕裂":vsync?L"显示同步:垂直同步":L"显示同步:允许撕裂";
+ const std::wstring sync=requested.display==DisplaySync::Automatic?L"显示同步:自动 · 不撕裂,也不等待垂直同步(延迟最低)":vsync?L"显示同步:垂直同步":L"显示同步:允许撕裂";
if(!reflexDisabled){effective.enabled=false;sink_.configurePacing(false,vsync,tearing);status=L"Reflex 驱动状态撤销失败;低延迟队列已停用 · "+sync;return effective;}
if(xessActive()){
// The provider owns Present for its generated frames, so neither the
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index 97dabaf8..a49aa973 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -401,14 +401,16 @@ bool PresentSink::present(Status& status)
const bool beforeOk=!xess_||xess_->beforePresent();
presentTiming_.beforeMs=split();
if(!beforeOk){xessFailed_=true;status=Status::WindowFailure;return false;}
- const bool trackScanout=displayLatencyEnabled_&&!xess_&&syncInterval==1;
+ // Vsync and Automatic Present(0,0) frames are shown at a vblank; a torn
+ // frame has no single vblank to date it by.
+ const bool trackScanout=displayLatencyEnabled_&&!xess_&&!(flags&DXGI_PRESENT_ALLOW_TEARING);
if(trackScanout)sampleDisplayLatency();
LARGE_INTEGER presentQpc{};QueryPerformanceCounter(&presentQpc);
const HRESULT hr = swapChain_->Present(syncInterval, flags);
presentTiming_.callMs=split();presentTiming_.result=hr;
UINT presentId=0;
if(SUCCEEDED(hr)&&trackScanout&&SUCCEEDED(swapChain_->GetLastPresentCount(&presentId)))
- pendingPresents_[pendingPresentNext_++%pendingPresents_.size()]={presentId,presentQpc.QuadPart};
+ pendingPresents_[pendingPresentNext_++%pendingPresents_.size()]={presentId,presentQpc.QuadPart,syncInterval==0};
if(presentContractDirty_||attemptedPresentCount_<=3||attemptedPresentCount_%120==0){
log::info("present-contract",std::format("backend={} sync={} flags=0x{:X} hr=0x{:X}",xess_?"XeSS":"DXGI",syncInterval,flags,unsigned(hr)));
presentContractDirty_=false;
@@ -484,6 +486,8 @@ PresentSink::FrameStatisticsDelta PresentSink::sampleFrameStatistics(){
delta.displayedRefresh=uint64_t(stats.PresentRefreshCount-frameStatisticsBasePresentRefresh_);
delta.refreshes=uint64_t(stats.SyncRefreshCount-frameStatisticsBaseSyncRefresh_);
}
+ UINT lastPresent=0;
+ if(SUCCEEDED(swapChain_->GetLastPresentCount(&lastPresent)))delta.ahead=int64_t(lastPresent)-int64_t(stats.PresentCount);
frameStatisticsBaseValid_=true;
frameStatisticsBasePresents_=presentCount_;
frameStatisticsBaseDisplayed_=stats.PresentCount;
@@ -513,6 +517,7 @@ void PresentSink::sampleDisplayLatency(){
// keeping only the newest (and least delayed) one of each burst.
for(const auto& pending:pendingPresents_){
if(!pending.qpc||pending.id>stats.PresentCount||(previous&&pending.id<=previous)||stats.PresentCount-pending.id>=pendingPresents_.size())continue;
+ if(pending.replaceable&&pending.id!=stats.PresentCount)continue;
const double ms=(scanout-double(stats.PresentCount-pending.id)*period-double(pending.qpc))*1000.0/frequency;
if(ms>=0&&ms<1000&&displayLatencyMs_.size()<4096)displayLatencyMs_.push_back(ms);
}
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index f9e088ed..cd01981c 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -62,7 +62,7 @@ int main(){
check(std::wstring_view(engine::ngxFailureHint(0xBAD00001)).find(L"不支持")!=std::wstring_view::npos,"NGX FeatureNotSupported has a distinct visible reason");
for(bool lowQueue:{false,true})for(bool fullscreen:{false,true})for(auto sync:{engine::DisplaySync::Tearing,engine::DisplaySync::Vsync,engine::DisplaySync::Automatic}) {
engine::PresentationSettings s;s.enabled=lowQueue;s.fullscreen=fullscreen;s.display=sync;
- check(engine::presentationVsync(s)==(sync!=engine::DisplaySync::Tearing)&&engine::presentationTearing(s)==(sync==engine::DisplaySync::Tearing),"Automatic synchronizes windowed/fullscreen independently of low queue; only explicit Tearing is unsynchronized");
+ check(engine::presentationVsync(s)==(sync==engine::DisplaySync::Vsync)&&engine::presentationTearing(s)==(sync==engine::DisplaySync::Tearing),"Automatic neither waits for VSync nor tears (Present(0,0) replaces unshown frames), independently of low queue/fullscreen; only explicit Vsync waits and only explicit Tearing tears");
}
{
source::AudioInputRecovery retry;retry.reset(1000);
diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cpp
index e088eac3..a4b7e759 100644
--- a/tests/unit/UiContractTests.cpp
+++ b/tests/unit/UiContractTests.cpp
@@ -58,7 +58,7 @@ void outputRateContracts(){
require(h.overloaded&&std::wstring(h.rateStatus(s))!=L"正常","VSync cannot hide output below its effective target");
h={};s=live();s.applied.multiplier=4;s.presentationEffective.display=engine::DisplaySync::Automatic;
s.metrics.flow.presentSubmitFps=60;settle(h,s,0,{60});
- require(!h.overloaded&&h.output.displayLimited,"Automatic display sync also uses the refresh limit");
+ require(h.overloaded&&h.output.targetFps==240&&!h.output.displayLimited,"Automatic replaces unshown frames instead of waiting, so the refresh rate is not its submission target");
s.presentationEffective.display=engine::DisplaySync::Tearing;++s.presentationRevision;settle(h,s,0,{60});
require(h.overloaded&&h.output.targetFps==240&&!h.output.displayLimited,"Tearing does not inherit a display cap");
h={};s=live();s.applied.multiplier=4;s.presentationEffective.display=engine::DisplaySync::Vsync;