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

feat(cadence): drop repeated pictures before GPU work and give kept frames content timestamps

Veyra Goal Agent85cbd5a4ce72
diff --git a/AGENTS.md b/AGENTS.md
index 09440477..c7f240b0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-11 补帧内容节奏重设计(Claude)**:用户要求重新设计补帧内容节奏里的去除重复帧(30/40 帧游戏 60 帧采集、非整数倍率,不误删真实帧、不加明显耗时),用 GTA6 30→60/58 渲染测试,完成后汇报并关机。存档 `checkpoint/pre-claude-dedup-20261011`(main 5ba186a)与 E 盘 `archives/claude-dedup-20261011`;分支 `claude/dedup-cadence-20261011` 只改直播来源的重复画面判断、留帧和内容时间戳(ContentDedup.h、EngineController 读帧处、EnhanceGraph::lumaSignature、回放测试与单测)及“内容节奏”提示文案。默认模式、NR/SR/FG、运行库、驱动、用户配置不变;硬解串流没有 CPU 画面,只保留 60→30 按时间戳减半。无 merge/push/Release。详见 docs/CONTENT_CADENCE_2026-10-11.md。
+
> **2026-10-10 已验修复合入本地main**:用户在完整测试包交付后明确“合并到main吧”。已将codex/sr-visual-quality-20261010的48d8f34及其11个未合入提交通过--no-ff整合,功能merge为ff80a49,Git树与实测分支完全相同;随后仅更新合并记录/当前状态。本地main包含PGS字幕、播放列表/PR31、BMD原生开关、设置恢复/输入焦点/布局/关闭项编辑等已验修复,SR画质实验保持撤回。范围与验收见docs/MERGE_MAIN_2026-10-10.md;46工作树/495脏文件存档到E盘archives/merge-fixes-20261010/start.json,除本轮main外均保持。新构建明确配置DeckLink SDK,打包使用已验zlib/PS5 slices256版FFmpeg,不无意退回旧依赖。此次只本地合并和文档收尾,不push/Release/换版本/重打包/关机,不改运行库原件/用户配置,不删旧分支或工作树;历史“尚未合并”仅代表当时。
> **2026-10-10 超分实验撤回与本地测试包**:用户要求停止超分继续优化、去掉负优化并汇报,随后明确“弄好了打个测试包给我”。本轮所有SR生产实验(局部/整帧静态运动校验、额外纹理/pass、DLSS档位及FSR曝光实验)全部撤回到c664a67,保留此前已验功能修复和共同参考测试工具。本地制作2.0.6-fixes-20261010完整NVIDIA测试包与对应源码,逐文件核对既有批准runtime、patched FFmpeg的zlib/PS5 slices256、许可证、私有配置冷启动与ZIP;覆盖下条“不打测试包”。不新发正式版、不merge/push/Release/关机,不派Agent,不动45既有工作树/495脏文件/main或真实配置。不得把重复帧误差改善说成一般视频画质提升。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ea9fe18b..4835af22 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -740,6 +740,8 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_definitions(veyra_realtime_preview_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
target_include_directories(veyra_realtime_preview_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(veyra_live_presentation_tests tests/integration/LivePresentationTests.cpp)
+ # wmain holds many PlayerSnapshot locals; the default 1 MiB stack overflowed at entry.
+ target_link_options(veyra_live_presentation_tests PRIVATE /STACK:8388608)
add_executable(veyra_hdr_display_state_tests tests/unit/HdrDisplayStateTests.cpp)
target_compile_features(veyra_hdr_display_state_tests PRIVATE cxx_std_20)
target_compile_options(veyra_hdr_display_state_tests PRIVATE /utf-8)
diff --git a/docs/CONTENT_CADENCE_2026-10-11.md b/docs/CONTENT_CADENCE_2026-10-11.md
new file mode 100644
index 00000000..f73cef8d
--- /dev/null
+++ b/docs/CONTENT_CADENCE_2026-10-11.md
@@ -0,0 +1,89 @@
+# 补帧内容节奏:去除重复帧重新设计(2026-10-11)
+
+## 授权与范围
+
+- 用户:现在的去除重复帧还是软件初期设计;PS5 等游戏锁 30/40 帧、采集卡采 60 帧(延迟比采 30 帧低)时,希望在补帧的“内容节奏”里重新设计去重复帧,兼容各类帧率;原来的 60→30 容易把真实帧也剔除,导致补帧鬼影;不要增加大量计算耗时;用 GTA6 30 帧视频渲染成 60 帧、58 帧来测试。完成后汇报并关机。
+- 沿用规则:先存档、开分支,负优化就退回。
+- 只改直播类来源(采集卡及其测试回放)的内容节奏处理:重复画面判断、留帧、内容时间戳。不改 NR/SR/FG 模型、呈现策略、默认设置、运行库和驱动。不 merge/push/Release。
+
+## 存档与分支
+
+- 检查点标签 `checkpoint/pre-claude-dedup-20261011` 指向 main `5ba186a`;`archives/claude-dedup-20261011/`(bundle 已 verify,start.json 记录 49 个工作树、495 个未提交文件)。
+- 分支 `claude/dedup-cadence-20261011`,工作树 `worktrees/dedup-cadence-20261011`。
+- 构建:`py -3.11 -I tmp/claude-dedup-20261011/build.py dedup`。
+
+## 原来的做法和问题
+
+- “采集 60→30”(`CaptureHalfRate`):按时间戳每两帧留一帧,代码注释自己写明不识别画面是否重复、不处理不规则节奏。游戏帧没有正好落在这个网格上(卡顿、锁 40 帧、58/59.94 Hz 传输)时,会丢真实帧、留重复帧,补帧就在“跨两步的画面”之间插值(鬼影)或在两张相同画面之间插值(停顿)。
+- “自动识别 / 识别 xx fps 内容”:只统计 30/50/60 三种帧率用于显示,并把与上一帧完全相同的帧对应的插帧标为无效;重复帧仍按原时间送显,补帧节奏不均匀。
+
+## 新做法(`include/veyra/engine/ContentDedup.h`)
+
+1. **判断重复**:用采集回调复制每帧时已经取好的 64×36 个亮度点(不读 GPU、不读写合并内存),与“上一张留下的画面”比较。
+ - 任一点明显变化(超过噪声门限,干净采集下 1 个点即可)或多数点整体变化(淡入淡出、平移)→ 新画面;
+ - 否则是重复画面,在任何 GPU 工作之前丢掉(NR/SR/补帧都不再处理重复帧)。
+ - 与“上一张留下的画面”比较,缓慢淡变会累积到门限而不会被一直丢掉;同一画面最长保持 150–250 ms(静止画面偶尔留一帧)。
+ - 压缩采集卡的噪声会被学习,门限随之提高;判断不确定时偏向保留。
+2. **内容时间戳**:新画面一定出现在“上一个采样之后、这个采样之前”。用最近 48 张新画面的采样时刻做线性回归估计内容周期,预测时间夹在这个时间窗内:
+ - 规则内容(30 帧放进 58 Hz、40 帧放进 60 Hz)得到均匀的 33.3/25 ms 间隔,且绝不晚于实际采到的时刻;
+ - 连续两次对不上(卡顿、帧率变化)就重新学习,期间使用采样时刻。
+3. **各模式**:
+ - 采用源时间戳:不变;
+ - 自动识别 / 识别 30·50·60 fps:去重 + 内容时间戳(指定帧率在 ±3% 内时直接采用该周期);
+ - 采集 60→30:去重 + 上限 30 帧(同一个两时隙窗口里有新画面就不会留重复帧,跟随游戏的相位)。
+- 测试开关 `VEYRA_TEST_CONTENT_DEDUP_LEGACY=1` 恢复旧行为,用于同 EXE A/B。
+- 只对能拿到 CPU 画面的来源生效(采集卡、测试回放);硬件解码的串流/文件仍保持原样。
+
+## 测试
+
+### 单元测试(`veyra_live_timing_tests`,合成 64×36 画面)
+
+16 项内容节奏用例全部通过(全程序 94 项 PASS):30 帧放 60 Hz、30 帧放 58 Hz、40 帧放 60 Hz、真 60 帧、±2 噪声的重复帧、静止画面中只有小物体移动、每次 +1 级的缓慢淡入、卡顿(同一画面 4 个采样)后恢复、60→30 上限(30/60 帧内容、相位滑移)、长时间静止(150–250 ms 留一帧)、无 CPU 画面(全部保留;60→30 仍按时间戳隔帧)。
+
+### GTA6 渲染素材回放(同一 EXE,旧行为用 `VEYRA_TEST_CONTENT_DEDUP_LEGACY=1`)
+
+- 素材:`tests/field-issues-20260930/media/gta6-1080p30-45s.mp4`(1080p30)用 ffmpeg 渲染:`fps=60`(30→60)、`fps=58`(30→58)、`setpts=0.75,fps=60`(40 帧内容放 60 Hz)、`fps=60,tblend`(真 60 帧对照)、30→60 加噪声。真值由 `harness/gt.py` 逐帧比较解码画面得到。
+- 回放:`veyra_live_presentation_tests <素材> <输出> --dedup-<模式>`,测试回放走与采集卡相同的直播路径、CPU 解码、DLSS 补帧 2X,每组 20 秒,去掉开头 2 秒。
+- 指标:留下的帧、窗口内真实画面数、丢失的真实画面、留下的重复帧、相邻留帧的内容间隔与期望周期之差在 ±1 ms 内的比例、每帧判定耗时。
+
+| 组 | 留帧 | 真实画面 | 丢失 | 留下重复 | 间隔 ±1ms | 判定耗时 P50/P99 |
+| --- | --- | --- | --- | --- | --- | --- |
+| 30→60,旧 60→30 | 571 | 570 | 0 | 1 | 100% | — |
+| 30→60,**新 60→30** | 571 | 571 | 0 | 0 | 99.8% | 13.7 / 25.9 µs |
+| 30→60,**新自动** | 570 | 570 | 0 | 0 | 99.8% | 13.3 / 59.7 µs |
+| 30→60,旧自动 | 1059 | 530 | 0 | **529** | 0%(16.7 ms 交替) | — |
+| 30→58,旧 60→30 | 1076 | 556 | 0 | **520** | 0%(旧版只在 59–61 Hz 生效,58 Hz 下不起作用) | — |
+| 30→58,**新 60→30** | 570 | 570 | 0 | 0 | 99.65%(P5/P50/P95 33.29/33.33/33.39 ms) | 13.5 / 22.9 µs |
+| 30→58,**新自动** | 571 | 571 | 0 | 0 | 99.65% | 13.7 / 21.2 µs |
+| 30→60 轻噪声,**新自动** | 571 | 571 | 0 | 0 | 99.8% | 13.4 / 21.4 µs |
+| 40 帧放 60 Hz,旧 60→30 | 572 | 761 | **189** | 0 | 0%(固定 33.3 ms,内容是 25 ms) | — |
+| 40 帧放 60 Hz,**新自动** | 753 | 752 | 0 | 1 | 100%(25.0 ms,标准差 0.01 ms) | 14.0 / 21.4 µs |
+| 真 60 帧对照,**新自动** | 1104 | 1047 | 1 | 58* | 97.3% | 14.0 / 25.1 µs |
+| 30→60 强噪声(强度 15),**新自动** | 1201(全部) | — | 0(未跳过任何帧) | 全部保留 | — | — |
+
+\* 真 60 帧素材由相邻帧混合生成,真值阈值把 57 张极小变化的帧算作重复,新版保留了它们(不确定时偏向保留);丢失的 1 张在缩略图上平均差 0.12 级、64×36 采样点上没有任何变化。
+
+日志:`logs/claude-dedup-20261011/replay-20261011-032828/summary.json`(11 组)与 `replay-20261011-0335*`(强噪声);逐帧决策在各组 `engine.log` 的 `[content-dedup-frame]`/`[cadence-input]`。
+
+### 结论
+
+- 30/40 帧内容的 6 组新版回放:约 2,300 张真实画面**没有丢失**,**没有留下重复帧**;58 Hz 下 34.5/17.2 ms 交替的采样被还原成均匀的 33.3 ms,40 帧内容在 60 Hz 下被还原成均匀的 25 ms。
+- 旧 60→30 只在内容正好是 59–61 Hz 的一半时正确;58 Hz 时完全不起作用(留下 520 张重复帧),40 帧内容丢了 25% 的真实画面——补帧会在跨两张画面的大步长上插值,就是群里说的鬼影。旧“自动”留下全部重复帧,补帧节奏 16.7 ms 交替。
+- 开销:每帧 CPU 判定约 14 µs(P99 ≤ 60 µs),没有 GPU 工作;重复帧在任何 GPU 处理前被丢掉,30 帧内容放 60 Hz 时 NR/SR/补帧的处理量减半。
+- 强噪声(重复帧之间每点差异中位数 3 级、最大 26 级,和慢镜头里真实新画面的差异一样大)时无法区分,按设计全部保留,行为等同“采用源时间戳”,不会丢真实帧。
+
+## 回归
+
+- `py -3.11 -I tests/claude-dedup-20261011/harness/regress.py dedup …`:chain、contracts、hdr、presenter、lifecycle、video、rollback、inactive、inactive-node、sr、slider、menu、components、timing,以及新增的 half-rate(原有 `--half-rate` 测试,用真 60 帧素材、硬件解码,覆盖“无 CPU 画面时 60→30 仍按时间戳隔帧”)。
+- 第一轮 half-rate 失败:无 CPU 画面的 60→30 兜底分支没有处理边界,设置切换后的第一帧可能被当作“不满两个时隙”丢掉,热切换事务一直等不到这帧(同一 EXE 用旧行为开关则全部通过)。已改为边界帧立即保留并重新锚定,增加对应单测。
+- 修正后 half-rate 一次出现“禁用后的版本不应保留之前的插帧计数”单项失败;新旧行为各再跑两次全部通过(新行为 3 次中 1 次,旧行为 3 次中 0 次),判断为该检查的时序偶发,与去重逻辑无关,如实记录。
+- 最终版本完整回归结果见下方追加记录。
+
+## 未验证与边界
+
+- 只用渲染素材回放验证;没有用真实采集卡 + 锁 30/40 帧的游戏实测,也没有 NS2/PS5 现场确认。群里提到的“不开补帧 60→30 也卡”以及 59.94/60 设置问题属于呈现时钟,另作处理,本次没有改。
+- 硬件解码的来源(PS5 Remote Play、Moonlight、Xbox 串流、硬解文件)没有 CPU 画面,不做去重;60→30 对它们仍按时间戳隔帧,与旧版一致。
+- 强噪声的压缩/模拟采集无法去重(安全退化为保留)。
+- 新会话或设置变化后,前约 0.7 秒在学习内容周期,期间使用采样时刻。
+- 64×36 采样点碰不到的极小变化(例如画面中只有几个像素的光标闪动)会被当成重复,最长 150–250 ms 后一定留一帧。
+- 测试程序 `veyra_live_presentation_tests` 的 `wmain` 原本就贴着 1 MB 栈上限,本次给它加了 `/STACK:8388608`(只影响测试程序)。测试回放现在可以按 `softwareDecode` 走 CPU 解码(只在测试开关 `captureReplayForTest` 下,UI 不会开启)。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index ba29ad24..a8c8bbc3 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,12 @@
# WORKLOG
+## 2026-10-11 补帧内容节奏:去除重复帧重新设计(Claude)
+
+- 用户要求在补帧“内容节奏”里重新设计去重复帧,兼容 30/40 帧游戏用 60 帧采集及非整数倍率,避免原 60→30 误删真实帧导致鬼影,不增加明显耗时;用 GTA6 30 帧视频渲染 60/58 帧测试,做完汇报后关机。存档 checkpoint/pre-claude-dedup-20261011(main 5ba186a)与 archives/claude-dedup-20261011;分支 claude/dedup-cadence-20261011。
+- 新增 include/veyra/engine/ContentDedup.h:用采集回调已有的 64×36 亮度点与“上一张留下的画面”比较,重复画面在 GPU 工作前丢弃;留下的帧用回归周期预测、夹在采样时间窗内的内容时间戳。自动/识别 xx fps 模式去重,60→30 改为去重 + 30 帧上限(无 CPU 画面的硬解串流仍按时间戳减半)。VEYRA_TEST_CONTENT_DEDUP_LEGACY=1 恢复旧行为。
+- 测试见 docs/CONTENT_CADENCE_2026-10-11.md。
+- 不 merge/push/Release,不改默认内容节奏、NR/SR/FG 模型、运行库、驱动、用户配置。
+
## 2026-10-10 关闭效果器编辑卡顿
- 用户反馈关闭效果器时仅调整内部设置也顿一下;从30c6f60隔离codex/inactive-effects-20261010,start保护44既有工作树/495脏文件和main0e7018ad,未派Agent。根因是完整视频设置比较导致无效GPU revision/排空/重建,同revision的applySettings还会重置NR。新增仅比较开启参数的视图,完整保存值不丢;关闭项更新跳过GPU/暂停帧处理,开启后应用新值。多NR/共享光流/HDR元数据依赖及混合事务保留有效更新。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index d0a43788..1d1676c7 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -9208,11 +9208,11 @@
"ja": "消去"
},
{
- "zh": "游戏 30 帧、采集卡输出 60 帧时选“采集 60→30”",
+ "zh": "游戏锁 30/40 帧、采集卡输出 60 帧时选“自动识别内容节奏”:只去掉重复画面,补帧时间均匀;“采集 60→30”另外把上限固定为 30 帧",
"src": "qml/ProPage.qml",
- "zh-TW": "遊戲 30 幀、擷取卡輸出 60 幀時選“擷取 60→30”",
- "en": "Choose \"Capture 60→30\" when the game runs at 30 fps and the capture card outputs 60",
- "ja": "ゲームが 30 fps でキャプチャーカードが 60 fps を出力する場合は「キャプチャー 60→30」を選択"
+ "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 repeated pictures are dropped and generated frames stay evenly timed; \"Capture 60→30\" also caps the rate at 30",
+ "ja": "ゲームが 30/40 fps 固定でキャプチャーカードが 60 fps を出力する場合は「コンテンツのペーシングを自動判別」を選択:重複した映像だけを除き、補間フレームの間隔を均一にします。「キャプチャー 60→30」はさらに上限を 30 fps にします"
},
{
"zh": "游戏与程序 · ",
diff --git a/include/veyra/engine/ContentDedup.h b/include/veyra/engine/ContentDedup.h
new file mode 100644
index 00000000..2a1bc048
--- /dev/null
+++ b/include/veyra/engine/ContentDedup.h
@@ -0,0 +1,180 @@
+#pragma once
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+
+namespace veyra::engine {
+// Repeated-picture removal and content cadence for live sources (2026-10-11).
+//
+// A game locked to 30 or 40 fps behind a 60 Hz capture repeats pictures. The
+// old "60->30" setting kept every second sample by timestamp, blind to the
+// picture: whenever the game's frames did not land on that grid (a hitch, a
+// 40 fps cap, a 58/59.94 Hz transport) it dropped real frames and kept
+// repeats, and frame generation then interpolated across a doubled step
+// (ghosting) or a still pair; "auto" only reported a rate.
+//
+// A sample is dropped here only when its picture repeats the last kept one,
+// judged on the 64x36 luma points the capture callback already takes (~2.3k
+// compares per frame, no GPU work). Kept frames get a content timestamp from a
+// clamped phase-locked cadence: the picture changed after the previous sample
+// and no later than this one, so the predicted time is clamped into that
+// window. Regular content (30 in 58 Hz, 40 in 60 Hz) gets evenly spaced
+// timestamps that are never later than the sample; hitches and variable rates
+// keep their sample times.
+class ContentDedup {
+public:
+ static constexpr unsigned kPoints = 64 * 36;
+ struct Decision {
+ bool keep = true;
+ int64_t contentPts = 0; // 100 ns, kept frames
+ int64_t interval = 0; // 100 ns from the previous kept frame (0 = unknown)
+ double median = 0; // median |luma difference| to the last kept frame (levels)
+ unsigned changed = 0; // points beyond the change gate
+ const char* reason = "first";
+ };
+ struct Stats {
+ uint64_t observed = 0, kept = 0, repeats = 0, capped = 0, held = 0, blind = 0;
+ uint64_t regular = 0, irregular = 0;
+ double maxShiftMs = 0; // largest sample-to-content correction
+ };
+
+ void reset() {
+ haveKept_ = haveContent_ = skipSpan_ = false; prevSample_ = 0; lastKeptSample_ = 0; lastContent_ = 0;
+ timeCount_ = 0; timeHead_ = 0; period_ = 0; misses_ = 0;
+ }
+ // luma: kPoints 8-bit samples or nullptr (no CPU picture: keep everything).
+ // capPeriod: minimum spacing of kept frames (the 60->30 setting), 0 = none.
+ // hintPeriod: expected content period of the selected content rate, 0 = unknown.
+ Decision observe(const uint8_t* luma, int64_t pts, int64_t transport, bool boundary,
+ int64_t capPeriod = 0, int64_t hintPeriod = 0) {
+ Decision d;
+ ++stats_.observed;
+ if (transport <= 0) transport = 166667;
+ const int64_t previous = prevSample_;
+ const bool continuous = haveKept_ && !boundary && pts > previous && pts - previous <= transport * 6;
+ prevSample_ = pts;
+ if (!luma) {
+ // No CPU picture (hardware-decoded streams): keep everything, except
+ // that 60->30 still samples every second slot by timestamp as before.
+ // A boundary (open, seek, settings change) keeps its first frame and
+ // re-anchors, like the old sampler: transactions wait for that frame.
+ ++stats_.blind; haveKept_ = false;
+ if (boundary) { reset(); prevSample_ = pts; }
+ else if (capPeriod > 0 && haveContent_ && pts > lastKeptSample_ && pts - lastKeptSample_ + transport / 4 < capPeriod && pts - lastKeptSample_ <= transport * 6) {
+ ++stats_.capped; d.keep = false; d.reason = "rate-cap"; return d;
+ }
+ return keep(d, pts, previous, transport, nullptr, Timing::Sample, "no-picture");
+ }
+ if (!continuous) {
+ reset(); prevSample_ = pts;
+ return keep(d, pts, previous, transport, luma, Timing::Sample, boundary ? "boundary" : "first");
+ }
+ // Compare with the last KEPT picture: a slow fade accumulates until it
+ // counts instead of being dropped one sub-threshold step at a time.
+ std::array<uint16_t, 256> histogram{};
+ const int gate = int(std::max(8.0, 3.0 * noise_ + 6.0));
+ unsigned changed = 0;
+ for (unsigned i = 0; i < kPoints; ++i) {
+ const int diff = std::abs(int(luma[i]) - int(kept_[i]));
+ ++histogram[diff];
+ changed += diff > gate;
+ }
+ unsigned median = 0;
+ for (unsigned seen = 0; median < 255; ++median) if ((seen += histogram[median]) * 2 >= kPoints) break;
+ d.median = median; d.changed = changed;
+ // New picture: a point moved clearly (a small object or the HUD in a still
+ // scene counts; a clean capture repeats bit-exactly, so one point is enough
+ // until noise has been seen) or most of the picture shifted (fades, pans).
+ const double medianGate = std::max(1.5, 1.5 * noise_ + 0.75);
+ const bool repeat = changed < (noise_ < 0.5 ? 1u : 3u) && median <= medianGate;
+ const int64_t sinceKept = pts - lastKeptSample_;
+ if (repeat) {
+ // Never hold one picture for long: a still screen keeps a frame now
+ // and then, and a change too slow to pass the gates still advances.
+ const int64_t hold = std::clamp<int64_t>(period_ ? period_ * 4 : transport * 8, 1500000, 2500000);
+ if (sinceKept < hold) {
+ noise_ = noise_ * 0.9 + 0.1 * median;
+ ++stats_.repeats; d.keep = false; d.reason = "repeat"; return d;
+ }
+ ++stats_.held;
+ return keep(d, pts, previous, transport, luma, Timing::Sample, "hold-limit");
+ }
+ if (capPeriod > 0 && sinceKept + transport / 4 < capPeriod) {
+ // 60->30: a new picture one slot after the last kept one (60 fps
+ // content) is over the cap. Repeats never take its place.
+ ++stats_.capped; d.keep = false; d.reason = "rate-cap"; return d;
+ }
+ return keep(d, pts, previous, transport, luma, Timing::Cadence, "new", hintPeriod);
+ }
+ // Estimated content rate of the kept frames (0 until established).
+ double contentFps() const { return period_ > 0 ? 1e7 / double(period_) : 0.0; }
+ double noiseLevel() const { return noise_; }
+ const Stats& stats() const { return stats_; }
+
+private:
+ enum class Timing { Sample, Cadence };
+ static constexpr unsigned kTimes = 48;
+ Decision& keep(Decision& d, int64_t pts, int64_t previous, int64_t transport, const uint8_t* luma, Timing timing,
+ const char* reason, int64_t hint = 0) {
+ d.keep = true; d.reason = reason; ++stats_.kept;
+ int64_t content = pts;
+ if (timing == Timing::Cadence) {
+ // A span that started at a held (still-screen) frame is not a content period.
+ if (skipSpan_) { timeCount_ = 0; timeHead_ = 0; }
+ if (timeCount_ == 0) push(lastKeptSample_);
+ push(pts);
+ if (timeCount_ >= 8) {
+ // Least-squares slope of sample time over kept-frame index: the
+ // sample grid quantizes each time by up to one slot, and the
+ // slope over n frames is off by about slot/n^1.5 (0.05 ms at 58 Hz).
+ const unsigned n = timeCount_, first = (timeHead_ + kTimes - n) % kTimes;
+ const double origin = double(times_[first]), mean = (n - 1) / 2.0;
+ double sxx = 0, sxt = 0, st = 0;
+ for (unsigned i = 0; i < n; ++i) st += double(times_[(first + i) % kTimes]) - origin;
+ for (unsigned i = 0; i < n; ++i) {
+ const double x = i - mean, t = double(times_[(first + i) % kTimes]) - origin - st / n;
+ sxx += x * x; sxt += x * t;
+ }
+ period_ = std::max<int64_t>(int64_t(std::llround(sxt / sxx)), transport - transport / 8);
+ if (hint > 0 && std::llabs(period_ - hint) * 100 < hint * 3) period_ = hint;
+ }
+ // The picture changed after the previous sample and by this one.
+ const int64_t lo = std::max(lastKeptSample_, previous), hi = pts;
+ if (period_ > 0) {
+ const int64_t predicted = lastContent_ + period_, tolerance = transport / 2;
+ if (predicted >= lo - tolerance && predicted <= hi + tolerance) {
+ content = std::clamp(predicted, lo + 1, hi); misses_ = 0; ++stats_.regular;
+ } else {
+ ++stats_.irregular;
+ // Two misses in a row: the rate changed; relearn it from here.
+ if (++misses_ >= 2) { timeCount_ = 0; timeHead_ = 0; period_ = 0; misses_ = 0; push(pts); }
+ }
+ }
+ }
+ if (haveContent_) {
+ content = std::max(content, lastContent_ + 10000);
+ d.interval = content - lastContent_;
+ }
+ skipSpan_ = timing == Timing::Sample && haveContent_;
+ haveContent_ = true;
+ stats_.maxShiftMs = std::max(stats_.maxShiftMs, double(pts - content) / 1e4);
+ d.contentPts = content;
+ if (luma) { std::memcpy(kept_.data(), luma, kPoints); haveKept_ = true; }
+ lastKeptSample_ = pts; lastContent_ = content;
+ return d;
+ }
+
+ void push(int64_t time) { times_[timeHead_] = time; timeHead_ = (timeHead_ + 1) % kTimes; timeCount_ = std::min(timeCount_ + 1, kTimes); }
+
+ std::array<uint8_t, kPoints> kept_{};
+ std::array<int64_t, kTimes> times_{};
+ unsigned timeCount_ = 0, timeHead_ = 0, misses_ = 0;
+ bool haveKept_ = false, haveContent_ = false, skipSpan_ = false;
+ int64_t prevSample_ = 0, lastKeptSample_ = 0, lastContent_ = 0, period_ = 0;
+ double noise_ = 0;
+ Stats stats_;
+};
+}
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index d1dcbf1a..39daa403 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -463,6 +463,10 @@ public:
// `hardwareSurface` carries the decoded texture for paths whose surface
// does not travel inside the AVFrame (D3D11VA). It must be provided exactly
// when frame->format == AV_PIX_FMT_D3D11 and is unused otherwise.
+ // 64x36 luma points of a CPU frame (a capture upload's callback proxy or the
+ // frame's own luma plane), the points scene/cadence analysis samples; no GPU
+ // work. False for hardware surfaces and layouts it does not know.
+ bool lumaSignature(const AVFrame* frame, uint8_t* out) const;
bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, const HardwareSurfaceInput* hardwareSurface = nullptr, bool retainReferences = true, const FgAdmission& admitFg = {}, unsigned previewMultiplier = 0, bool pausedResidualRefresh = false);
bool nextFrameSlotAvailable()const {
const unsigned slot=unsigned(realFrameIndex_%2);
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index 8eaf1008..2080ff24 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -1716,7 +1716,7 @@ VPage {
}
VRow {
label: qsTr("内容节奏")
- hint: qsTr("游戏 30 帧、采集卡输出 60 帧时选“采集 60→30”")
+ hint: qsTr("游戏锁 30/40 帧、采集卡输出 60 帧时选“自动识别内容节奏”:只去掉重复画面,补帧时间均匀;“采集 60→30”另外把上限固定为 30 帧")
VSelect {
objectName: "list-content-rate"
implicitWidth: 170
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 113a9732..491d18a9 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -21,6 +21,7 @@
#include "veyra/engine/LivePairLatency.h"
#include "veyra/engine/RealtimePreviewScheduling.h"
#include "veyra/engine/CaptureHalfRate.h"
+#include "veyra/engine/ContentDedup.h"
#include "veyra/source/MediaFileSource.h"
#include "veyra/source/CaptureCardSource.h"
#include "veyra/source/DeckLinkCapture.h"
@@ -418,7 +419,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// VP9 through D3D12VA; MJPEG stays on the software path inside
// CaptureCompressedDecoder). Each source performs its own
// capability check and records its fallback.
- od.preferHardwareDecode=!(options.softwareDecode&&!isCapture);
+ // Capture replay may decode on the CPU like a physical capture card (content-cadence tests).
+ od.preferHardwareDecode=!(options.softwareDecode&&(!isCapture||options.captureReplayForTest));
od.requireHardwareDecode=options.hardwareDecodeOnly&&!options.softwareDecode&&!isCapture&&!isImage; // stills have no hardware decoder
od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();
od.d3d12AdapterLuid=ctx.adapter().luid;
@@ -898,6 +900,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
uint64_t fedXessPresented=0,fedXessGenerated=0;
double playbackSpeedLastPts=0;Clock::time_point playbackSpeedLastWall{};
CaptureHalfRate captureSampler;
+ // Content cadence for live sources (ContentDedup.h): repeated pictures are
+ // dropped before any GPU work and kept frames get content timestamps.
+ // VEYRA_TEST_CONTENT_DEDUP_LEGACY=1 restores the blind 60->30 sampler and
+ // the report-only content modes for A/B runs.
+ ContentDedup contentDedup;uint64_t dedupRevision=0;
+ ContentDedup::Stats dedupLogged{};
+ static const bool legacyCadence=GetEnvironmentVariableW(L"VEYRA_TEST_CONTENT_DEDUP_LEGACY",nullptr,0)>0;
FrameLineageTracker lineageTracker;
auto completedProcessing=[&](pipeline::FrameIdentity id){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==id.settingsRevision)++snapshot_.processedCompleted;};
auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};
@@ -1632,15 +1641,36 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(!isImage&&!isCapture&&seekSeconds_>=0)continue;
const bool halfRate=isCapture&&options.settings.content==ContentRate::Capture60To30&&
CaptureHalfRate::supported(activeSource->info().averageFps);
+ const bool dedupActive=isCapture&&!isImage&&!legacyCadence&&options.settings.content!=ContentRate::Transport;
if(reset||pipeline::breaksHistory(pkt.flags))captureSampler.reset();
- if(halfRate&&!rereadCached){
+ const int64_t samplePts100ns=pkt.pts.isUnknown()?0:pkt.pts.to100ns();
+ if(dedupActive&&!rereadCached&&!pkt.pts.isUnknown()&&graph){
+ const auto interval=liveSourceInterval100ns(pipeline::Rational::unknown(),activeSource->info().averageFps);
+ std::array<uint8_t,ContentDedup::kPoints> signature;
+ const auto signatureStart=Clock::now();
+ const bool pictured=graph->lumaSignature(frame,signature.data());
+ const bool boundary=reset||pipeline::breaksHistory(pkt.flags)||dedupRevision!=options.settings.revision;
+ dedupRevision=options.settings.revision;
+ const auto content=options.settings.content;
+ const int64_t cap=halfRate?interval*2:0;
+ const int64_t hint=content==ContentRate::Fps30?333333:content==ContentRate::Fps50?200000:content==ContentRate::Fps60?166667:halfRate?interval*2:0;
+ const auto decision=contentDedup.observe(pictured?signature.data():nullptr,pkt.pts.to100ns(),interval,boundary,cap,hint);
+ const double dedupUs=elapsedMs(signatureStart)*1000;
+ if(veyra::log::verboseFrameLogs())veyra::log::info("content-dedup-frame",std::format("source={} pts100ns={} keep={} reason={} median={} changed={} contentPts100ns={} intervalMs={:.3f} cpuUs={:.1f}",
+ pkt.sequence,pkt.pts.to100ns(),decision.keep,decision.reason,decision.median,decision.changed,decision.contentPts,decision.interval/1e4,dedupUs));
+ if(!decision.keep){std::lock_guard lock(mutex_);++snapshot_.captureRateSkipped;continue;}
+ pkt.pts={decision.contentPts,10000000};
+ if(decision.interval>0)pkt.duration={decision.interval,10000000};
+ }else if(halfRate&&legacyCadence&&!rereadCached){
const auto interval=liveSourceInterval100ns(pipeline::Rational::unknown(),activeSource->info().averageFps);
if(!pkt.pts.isUnknown()&&!captureSampler.accept(pkt.pts.to100ns(),interval,false)){
std::lock_guard lock(mutex_);++snapshot_.captureRateSkipped;continue;
}
pkt.duration={interval*2,10000000};
}
- if(!halfRate)captureSampler.reset();
+ if(!halfRate||!legacyCadence)captureSampler.reset();
+ if(isCapture&&!rereadCached&&veyra::log::verboseFrameLogs())
+ veyra::log::info("cadence-input",std::format("source={} samplePts100ns={} pts100ns={} dedup={} legacyHalf={}",pkt.sequence,samplePts100ns,pkt.pts.isUnknown()?0:pkt.pts.to100ns(),dedupActive,halfRate&&legacyCadence));
if(isImage)pkt.sequence=1;
#ifdef VEYRA_ENABLE_XBOX
if(xb&&!rereadCached)xboxReconnectBudget.decoded(monotonic100ns());
@@ -2368,7 +2398,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
snapshot_.srActive=gd.enableSr&&graphStats.srEvaluateCount>0;
snapshot_.fgActive=options.fg&&(graph->xessEnabled()?presenter.xessActive()&&graphStats.fgGeneratedFrames>0:graph->fgEnabled()&&measured.flow.counters.fgReadyValid>0);
if(transaction&&backendRecoveryWarning.empty()&&nvidiaAdapter&&(!graph->xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();
- snapshot_.flowPerf=graph->actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;
+ snapshot_.flowPerf=graph->actualFlowPerf();snapshot_.contentFps=isCapture&&!legacyCadence&&options.settings.content!=ContentRate::Transport&&contentDedup.contentFps()>0?int(std::lround(contentDedup.contentFps())):out.measuredContentRate;
snapshot_.nrEvaluated=graphStats.nrEvaluateCount;snapshot_.nvofExecuted=graphStats.nvofExecuteCount;
snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveScheduler?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;
snapshot_.captureSampledBlack=captureStats.sampledBlack;
@@ -2397,6 +2427,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// memory gets slower in every pass at once (field log 2026-10-01).
uint64_t vramBudget=0,vramUsage=0;ctx.videoMemoryInfo(vramBudget,vramUsage);watchVram(vramUsage,vramBudget);
veyra::log::info("frame-rate",std::format("revision={} gpuCompletedFps={:.2f} completedReal={} capture60To30={} rateSkipped={} presentSubmitFps={:.2f} windowMs=1000 vramMiB={} budgetMiB={} (not scanout FPS)",options.settings.revision,rates.fps,rates.processedCompleted,rates.captureHalfRate,rates.captureRateSkipped,rates.submissionFps.value_or(0),vramUsage>>20,vramBudget>>20));
+ if(options.settings.content!=ContentRate::Transport&&!legacyCadence){
+ const auto& st=contentDedup.stats();
+ veyra::log::info("content-dedup",std::format("revision={} mode={} observed={} kept={} repeats={} rateCap={} held={} blind={} regular={} irregular={} contentFps={:.2f} noise={:.2f} maxShiftMs={:.2f} (per second; repeats are dropped before GPU work, kept frames carry content timestamps)",
+ options.settings.revision,int(options.settings.content),st.observed-dedupLogged.observed,st.kept-dedupLogged.kept,st.repeats-dedupLogged.repeats,st.capped-dedupLogged.capped,st.held-dedupLogged.held,st.blind-dedupLogged.blind,
+ st.regular-dedupLogged.regular,st.irregular-dedupLogged.irregular,contentDedup.contentFps(),contentDedup.noiseLevel(),st.maxShiftMs));
+ dedupLogged=st;
+ }
veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} singleGpuOwner=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveScheduler?completed.readyP95:gpuReadyTimes.p95(),waitP95,presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));
nextTimingLog=Clock::now()+std::chrono::seconds(1);
}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 29fe057f..aeb659cf 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -3416,4 +3416,42 @@ void EnhanceGraph::shutdown()
(void)st;
}
+bool EnhanceGraph::lumaSignature(const AVFrame* frame,uint8_t* out)const{
+ if(!frame||!out||!frame->data[0]||desc_.stillImage)return false;
+ const auto format=AVPixelFormat(frame->format);
+ if(format==AV_PIX_FMT_D3D12||format==AV_PIX_FMT_D3D11)return false;
+ const bool bgr=format==AV_PIX_FMT_BGRA||format==AV_PIX_FMT_BGR0;
+ const auto rgb=[&](const uint8_t* p){return uint8_t((54*unsigned(p[bgr?2:0])+183*unsigned(p[1])+19*unsigned(p[bgr?0:2])+128)>>8);};
+ // Upload-backed capture frames: the callback's proxy, never the write-combined buffer.
+ if(const auto* upload=captureUploadFrame(frame);upload&&upload->proxyValid&&upload->pixelBytes>=1&&upload->pixelBytes<=CaptureUploadFrame::kMaxPixelBytes){
+ const unsigned bytes=upload->pixelBytes;const int pitch=upload->proxyPitch();
+ for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){
+ const uint8_t* p=upload->proxy+ptrdiff_t(y)*pitch+x*bytes;
+ out[y*64+x]=upload->planes==2?p[bytes-1]:desc_.packedInput?packedIngressLuma(upload->proxy,pitch,desc_.packedInput,x,y):
+ desc_.yuy2Input?p[0]:bytes>=4?rgb(p):p[bytes-1];
+ }
+ return true;
+ }
+ if(frame->width<64||frame->height<36)return false;
+ const auto* data=frame->data[0];const ptrdiff_t pitch=frame->linesize[0];
+ for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){
+ const unsigned sx=x*unsigned(frame->width)/64,sy=y*unsigned(frame->height)/36;
+ const uint8_t* row=data+ptrdiff_t(sy)*pitch;uint8_t v=0;
+ switch(format){
+ case AV_PIX_FMT_NV12:case AV_PIX_FMT_NV21:case AV_PIX_FMT_YUV420P:case AV_PIX_FMT_YUVJ420P:case AV_PIX_FMT_YUV422P:
+ case AV_PIX_FMT_YUVJ422P:case AV_PIX_FMT_YUV444P:case AV_PIX_FMT_YUVJ444P:case AV_PIX_FMT_GRAY8:v=row[sx];break;
+ case AV_PIX_FMT_P010LE:case AV_PIX_FMT_P016LE:v=row[sx*2+1];break;
+ case AV_PIX_FMT_YUV420P10LE:case AV_PIX_FMT_YUV422P10LE:case AV_PIX_FMT_YUV444P10LE:
+ v=uint8_t(std::min(1023u,unsigned(row[sx*2])|(unsigned(row[sx*2+1])<<8))>>2);break;
+ case AV_PIX_FMT_YUYV422:case AV_PIX_FMT_YVYU422:v=row[sx*2];break;
+ case AV_PIX_FMT_UYVY422:v=row[sx*2+1];break;
+ case AV_PIX_FMT_RGBA:case AV_PIX_FMT_BGRA:case AV_PIX_FMT_RGB0:case AV_PIX_FMT_BGR0:v=rgb(row+sx*4);break;
+ default:
+ if(desc_.packedInput&&format==packedIngressFormat(desc_.packedInput)){v=packedIngressLuma(data,pitch,desc_.packedInput,sx,sy);break;}
+ return false;
+ }
+ out[y*64+x]=v;
+ }
+ return true;
+}
} // namespace veyra::pipeline
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index 8d1b5848..431fee9d 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -105,6 +105,35 @@ int inactiveEffectsTest(const wchar_t* input,const wchar_t* output,bool nodeMode
return failures?1:0;
}
}
+// --dedup-* replay (ContentDedup.h). Not inlined, snapshots built on the heap:
+// wmain already holds many PlayerSnapshot locals, and two more overflowed its
+// 1 MiB stack before the first line ran.
+__declspec(noinline) static int runContentCadenceReplay(engine::EngineController& engine,const std::wstring& mode){
+ using namespace std::chrono_literals;
+ auto pumpUntil=[&](auto predicate,std::chrono::seconds limit){
+ const auto deadline=std::chrono::steady_clock::now()+limit;
+ while(std::chrono::steady_clock::now()<deadline){
+ MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}
+ if(predicate())return true;std::this_thread::sleep_for(20ms);
+ }
+ return false;
+ };
+ std::unique_ptr<engine::PlayerSnapshot> start,end;
+ const bool started=pumpUntil([&]{start.reset(new engine::PlayerSnapshot(engine.snapshot()));return start->frames>30&&start->fgActive;},25s);
+ std::cout<<(started?"PASS ":"FAIL ")<<"replay starts with DLSS 2X"<<std::endl;
+ const auto begin=std::chrono::steady_clock::now();
+ pumpUntil([&]{end.reset(new engine::PlayerSnapshot(engine.snapshot()));return end->failed||std::chrono::steady_clock::now()-begin>=20s;},25s);
+ std::wcout<<L"DEDUP_RESULT mode="<<mode;
+ std::cout<<" frames="<<end->frames-start->frames<<" skipped="<<end->captureRateSkipped-start->captureRateSkipped<<" generated="<<end->generated-start->generated
+ <<" contentFps="<<end->contentFps<<" realPresented="<<end->metrics.flow.counters.realPresented-start->metrics.flow.counters.realPresented
+ <<" generatedPresented="<<end->metrics.flow.counters.generatedPresented-start->metrics.flow.counters.generatedPresented
+ <<" fgInvalid="<<end->metrics.flow.counters.fgInvalid-start->metrics.flow.counters.fgInvalid<<std::endl;
+ const bool ran=started&&!end->failed&&end->frames>start->frames+300;
+ std::cout<<(ran?"PASS ":"FAIL ")<<"content-cadence replay runs"<<std::endl;
+ engine.stop();const bool drained=pumpUntil([&]{return engine.idle();},8s);
+ std::cout<<(drained?"PASS ":"FAIL ")<<"content-cadence replay drains"<<std::endl;
+ return started&&ran&&drained?0:1;
+}
int wmain(int argc,wchar_t**argv){
if(argc==4&&(wcscmp(argv[3],L"--inactive-effects")==0||wcscmp(argv[3],L"--inactive-effects-node")==0))return inactiveEffectsTest(argv[1],argv[2],wcscmp(argv[3],L"--inactive-effects-node")==0);
#ifdef VEYRA_ENABLE_REMOTEPLAY
@@ -192,7 +221,7 @@ int wmain(int argc,wchar_t**argv){
#endif
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
const bool settingsRebuild=argc==4&&wcscmp(argv[3],L"--settings-rebuild")==0;
- if(!settingsRebuild&&argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--backend-recovery")==0||wcscmp(argv[3],L"--nr-first")==0||wcscmp(argv[3],L"--seek-stress")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--file-continuity")==0||wcscmp(argv[3],L"--file-fg-recovery")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(!settingsRebuild&&argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--backend-recovery")==0||wcscmp(argv[3],L"--nr-first")==0||wcscmp(argv[3],L"--seek-stress")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--file-continuity")==0||wcscmp(argv[3],L"--file-fg-recovery")==0||wcscmp(argv[3],L"--reset-rollback")==0||std::wstring(argv[3]).rfind(L"--dedup-",0)==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);
HWND window=CreateWindowExW(0,L"STATIC",L"Live scheduler replay",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
if(!window)return 3;engine::EngineController engine;engine::PlayerOptions options;options.nr=false;options.fg=false;options.captureReplayForTest=true;
@@ -222,10 +251,22 @@ int wmain(int argc,wchar_t**argv){
if(fileEndpoint){options.captureReplayForTest=false;SetEnvironmentVariableW(L"VEYRA_TEST_FILE_ENDPOINT_LOSS",L"1");engine.setVolume(0,true);}
if(overload){options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",nullptr);}
if(halfRate)options.settings.content=engine::ContentRate::Capture60To30;
+ // --dedup-transport|auto|half|fps30: file replay through the live capture path
+ // with CPU decode and DLSS 2X, for content-cadence A/B runs (ContentDedup.h).
+ const bool dedupRun=argc==4&&std::wstring(argv[3]).rfind(L"--dedup-",0)==0;
+ const std::wstring dedupMode=dedupRun?std::wstring(argv[3]).substr(8):L"";
+ if(dedupRun){
+ options.softwareDecode=true;options.fg=true;options.fgMultiplier=2;
+ options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Dlss;
+ options.settings.content=dedupMode==L"auto"?engine::ContentRate::Auto:dedupMode==L"half"?engine::ContentRate::Capture60To30:
+ dedupMode==L"fps30"?engine::ContentRate::Fps30:engine::ContentRate::Transport;
+ engine.setVolume(0,true);ShowWindow(window,SW_SHOWNOACTIVATE);
+ }
if(fileOverload){options.captureReplayForTest=false;options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;}
int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<std::endl;if(!pass)++failures;};
auto until=[&](auto predicate,int seconds=8){auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(seconds);while(std::chrono::steady_clock::now()<deadline){MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}auto s=engine.snapshot();if(s.failed){std::wcerr<<s.status<<'\n';return false;}if(predicate(s))return true;std::this_thread::sleep_for(5ms);}return false;};
engine.open(window,argv[1],options);
+ if(dedupRun){const int result=runContentCadenceReplay(engine,dedupMode);DestroyWindow(window);CoUninitialize();return result;}
if(settingsRebuild){
check(until([](const auto& s){return s.frames>20&&s.nrActive&&s.fgActive;},30),"original NR 1080p and DLSS 2X start on the actual video");
for(unsigned round=0;round<8&&!failures;++round){
diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cpp
index 8d228c14..3cca55c5 100644
--- a/tests/unit/LivePresentationTimingTests.cpp
+++ b/tests/unit/LivePresentationTimingTests.cpp
@@ -3,6 +3,9 @@
#include "veyra/engine/LivePresentationResetPolicy.h"
#include "veyra/source/CaptureTiming.h"
#include "veyra/engine/CaptureHalfRate.h"
+#include "veyra/engine/ContentDedup.h"
+#include <array>
+#include <vector>
#include "veyra/engine/FrameRateWindow.h"
#include "veyra/engine/PresentationScheduler.h"
#include "veyra/engine/PresentationSettings.h"
@@ -144,5 +147,81 @@ int main(){
check(livePairHoldMs(true,1e12,0)<=1000./30,"timestamp jump has bounded hold");
check(livePairHoldMs(true,10,20)==0,"backwards PTS cannot sleep negatively");
check(livePairHoldMs(true,std::numeric_limits<double>::infinity(),0)==0,"nonfinite PTS rejected");
+ {
+ // ContentDedup: synthetic 64x36 luma pictures sampled at a capture rate.
+ using veyra::engine::ContentDedup;
+ auto picture=[](uint64_t id,int noise,uint64_t sample,std::array<uint8_t,ContentDedup::kPoints>& out){
+ for(unsigned i=0;i<ContentDedup::kPoints;++i){
+ uint64_t h=(id+1)*0x9E3779B97F4A7C15ull+i*0xBF58476D1CE4E5B9ull;h^=h>>31;h*=0x94D049BB133111EBull;h^=h>>29;
+ int v=int(h&0xFF);
+ if(noise){uint64_t n=(sample+7)*0xD6E8FEB86659FD93ull+i*0x2545F4914F6CDD1Dull;n^=n>>32;v+=int(n%unsigned(2*noise+1))-noise;}
+ out[i]=uint8_t(std::clamp(v,0,255));
+ }
+ };
+ struct Run{int kept=0,keptRepeats=0,droppedReal=0,regularSpans=0,spans=0;bool monotonic=true,neverLate=true;std::vector<int64_t> intervals;};
+ // contentOf(sample) gives the picture shown by sample i (ground truth).
+ auto run=[&](double captureFps,auto contentOf,int count,int noise,int64_t cap,int64_t hint,int64_t expectedPeriod){
+ ContentDedup dedup;Run r;std::array<uint8_t,ContentDedup::kPoints> luma{};
+ const int64_t dt=int64_t(std::llround(1e7/captureFps));int64_t lastContent=-1;int64_t lastPicture=-1;int64_t pendingPicture=-1;
+ for(int i=0;i<count;++i){
+ const int64_t pts=int64_t(i)*dt+1000;const int64_t id=contentOf(i);picture(uint64_t(id),noise,uint64_t(i),luma);
+ const auto d=dedup.observe(luma.data(),pts,dt,i==0,cap,hint);
+ if(d.keep){
+ ++r.kept;if(id==lastPicture)++r.keptRepeats;
+ if(pendingPicture>=0&&pendingPicture!=id&&cap==0)++r.droppedReal; // a newer picture superseded an unkept one
+ pendingPicture=-1;lastPicture=id;
+ r.monotonic&=d.contentPts>lastContent;r.neverLate&=d.contentPts<=pts;lastContent=d.contentPts;
+ if(i>60&&d.interval){++r.spans;r.intervals.push_back(d.interval);if(expectedPeriod&&std::llabs(d.interval-expectedPeriod)<=5000)++r.regularSpans;}
+ }else if(id!=lastPicture)pendingPicture=id;
+ }
+ return r;
+ };
+ const int n=1200;
+ {const auto r=run(60.0,[](int i){return int64_t(i/2);},n,0,0,0,333333);
+ check(r.kept==n/2&&r.keptRepeats==0&&r.droppedReal==0,"dedup 30-in-60: every real picture kept once, every repeat dropped");
+ check(r.monotonic&&r.neverLate&&r.regularSpans==r.spans,"dedup 30-in-60: content spans exactly 33.3 ms, never later than the sample");}
+ {const auto r=run(58.0,[](int i){return int64_t(std::floor(i*30.0/58.0+1e-9));},n,0,0,0,333333);
+ check(r.keptRepeats==0&&r.droppedReal==0&&std::abs(r.kept-int(std::floor((n-1)*30.0/58.0))-1)<=1,"dedup 30-in-58: all real pictures kept, no repeats");
+ check(r.monotonic&&r.neverLate&&r.regularSpans*100>=r.spans*95,"dedup 30-in-58: uneven 34.5/17.2 ms samples become even 33.3 ms content spans");}
+ {const auto r=run(60.0,[](int i){return int64_t(std::floor(i*40.0/60.0+1e-9));},n,0,0,0,250000);
+ check(r.keptRepeats==0&&r.droppedReal==0&&std::abs(r.kept-n*2/3)<=1,"dedup 40-in-60: all real pictures kept, no repeats");
+ check(r.monotonic&&r.neverLate&&r.regularSpans*100>=r.spans*95,"dedup 40-in-60: alternating 33/17 ms samples become even 25 ms content spans");}
+ {const auto r=run(60.0,[](int i){return int64_t(i);},n,0,0,0,166667);
+ check(r.kept==n&&r.regularSpans==r.spans,"dedup true 60: nothing dropped, timing unchanged");}
+ {const auto r=run(60.0,[](int i){return int64_t(i/2);},n,2,0,0,333333);
+ check(r.droppedReal==0&&r.keptRepeats*100<=n/2*5,"dedup 30-in-60 with capture noise: real pictures kept, repeats dropped");}
+ {const auto r=run(60.0,[](int i){return int64_t(i/2);},n,0,333334,333333,333333);
+ check(r.kept==n/2&&r.keptRepeats==0,"60->30 cap on 30 fps content keeps every real picture");}
+ {const auto r=run(60.0,[](int i){return int64_t(i);},n,0,333334,333333,0);
+ check(std::abs(r.kept-n/2)<=1&&r.keptRepeats==0,"60->30 cap on 60 fps content keeps every second picture");}
+ {// Hitch: one picture shown for three samples, then the 30 fps cadence resumes one slot later.
+ const auto r=run(60.0,[](int i){return int64_t(i<301?i/2:(i<304?150:(i-1)/2));},n,0,0,0,333333);
+ check(r.keptRepeats==0&&r.droppedReal==0&&r.monotonic&&r.neverLate,"dedup hitch: no real picture lost, timestamps stay ordered and never late");}
+ {// 60->30 with a phase slip: the blind sampler would keep repeats from here on.
+ const auto r=run(60.0,[](int i){return int64_t(i<301?i/2:(i+1)/2);},n,0,333334,333333,333333);
+ check(r.keptRepeats==0,"60->30 cap follows a phase slip instead of keeping repeats");}
+ {// A still scene where only a small object moves (4 points change).
+ ContentDedup dedup;std::array<uint8_t,ContentDedup::kPoints> luma{};picture(1,0,0,luma);int kept=0;
+ for(int i=0;i<120;++i){luma[100]=uint8_t(i*40);luma[101]=uint8_t(i*40+9);luma[600]=uint8_t(i*40+3);luma[2000]=uint8_t(i*40+5);kept+=dedup.observe(luma.data(),i*166667+1000,166667,i==0).keep;}
+ check(kept==120,"dedup keeps a frame where only a small object moved");}
+ {// Slow fade: +1 level per sample never freezes.
+ ContentDedup dedup;std::array<uint8_t,ContentDedup::kPoints> luma{};int kept=0;
+ for(int i=0;i<120;++i){for(auto& v:luma)v=uint8_t(40+i);kept+=dedup.observe(luma.data(),i*166667+1000,166667,i==0).keep;}
+ check(kept>=40,"dedup lets a slow fade advance");}
+ {// Still screen: a held picture is re-kept within 250 ms.
+ ContentDedup dedup;std::array<uint8_t,ContentDedup::kPoints> luma{};picture(3,0,0,luma);int kept=0;
+ for(int i=0;i<240;++i)kept+=dedup.observe(luma.data(),i*166667+1000,166667,i==0).keep;
+ check(kept>=16&&kept<=28&&dedup.stats().held>=15,"dedup still screen keeps one frame every 150-250 ms");}
+ {// No CPU picture: everything is kept.
+ ContentDedup dedup;int kept=0;for(int i=0;i<60;++i)kept+=dedup.observe(nullptr,i*166667+1000,166667,i==0).keep;
+ check(kept==60,"dedup without a picture keeps every sample");}
+ {// No CPU picture with 60->30 (hardware-decoded streams): every second slot, as before.
+ ContentDedup dedup;int kept=0;for(int i=0;i<120;++i)kept+=dedup.observe(nullptr,i*166667+1000+(i%3-1)*5000,166667,i==0,333334,333333).keep;
+ check(kept==60,"60->30 without a picture still samples every second slot by timestamp");}
+ {// A boundary one slot after a kept frame is kept at once (settings transactions wait for it).
+ ContentDedup dedup;bool first=dedup.observe(nullptr,1000,166667,true,333334,0).keep;
+ const bool next=dedup.observe(nullptr,166667+1000,166667,true,333334,0).keep;
+ check(first&&next,"60->30 without a picture keeps a boundary frame immediately");}
+ }
return failed?1:0;
}