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(cadence): restore the plain 60->30 sampler; drop only bit-identical repeats

Veyra Goal Agent60a93f30569d
diff --git a/AGENTS.md b/AGENTS.md
index d17e8a37..e4fc7ddd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-12 内容节奏修正(Claude)**:用户实测 2.0.7:“采集 60→30”被植入内容节奏判断、原始帧率跳动,要求还原为最简单的 60 帧 AABBCCDD→ABCD 稳定隔帧;新“自动识别内容节奏”去重不稳定(VFG 耗时、GPU 占用忽高忽低),游戏运行中出现 6fps,怀疑不是百分百相同的帧也被去掉。存档 `checkpoint/pre-claude-cadence-exact-20261012`(main 05bc4b5)与 `archives/claude-cadence-exact-20261012`,分支 `claude/cadence-exact-20261012`。60→30 恢复 `CaptureHalfRate`(与 85cbd5a 之前相同、不经去重);内容模式只去掉与上一张保留画面逐字节完全相同的帧(`PictureFingerprint.h` 整画面指纹,采集回调仅在内容去重开启时对驱动样本计算,CPU 帧在引擎端计算),静止画面按内容节奏保留。见 docs/CONTENT_CADENCE_EXACT_2026-10-12.md。用户 2.0.7 会话运行期间只做 CPU/轻 GPU 测试;不改默认设置、NR/SR/FG 模型、运行库、用户配置;无 merge/push/Release/子 Agent。
+
> **2026-10-12 构建前采集格式追加授权**:用户要求分辨率先行、MJPEG 标红(不建议使用)、无效组合明确弹错且不自动路由其他格式。允许最小 UI/桥接/采集协商修复和有关回归,保留有效上次配置;与本轮整合一起本地合入 main 和 2.0.7 测试包。
> **2026-10-12 各分支整合与 2.0.7 测试包授权**:用户明确要求将 Claude 最新已验 XeSS 和各分支已完成修复合入 main 并构建 2.0.7 测试包。按 docs/TEST_2.0.7_PLAN_2026-10-12.md 从 main a167831 隔离整合 Claude e46bbdf 与 Codex d883216(含34f479e),必要冲突适配后构建、组合回归、本地 main 合并及 NVIDIA/AMD 完整便携测试包。66旧树/509脏文件及来源 tip 存档保护,不派 Agent,不改驱动/运行库/模型/真实配置;UI33ms/250ms、GPU默认优先级与已撤回负优化保持。产物全E盘,测试每进程≤300秒、构建≤900秒。此范围覆盖历史 no-merge/no-package;没有新 push/Release/上传/关机授权。
diff --git a/docs/CONTENT_CADENCE_2026-10-11.md b/docs/CONTENT_CADENCE_2026-10-11.md
index 3dc44413..80172f18 100644
--- a/docs/CONTENT_CADENCE_2026-10-11.md
+++ b/docs/CONTENT_CADENCE_2026-10-11.md
@@ -1,5 +1,7 @@
# 补帧内容节奏:去除重复帧重新设计(2026-10-11)
+> 2026-10-12 修正(docs/CONTENT_CADENCE_EXACT_2026-10-12.md):“采集 60→30”已恢复为按时间戳隔帧(CaptureHalfRate),不再去重;内容模式不再用 64×36 采样点与变化门限,只去掉与上一张保留画面逐字节完全相同的帧,静止画面按内容节奏保留。下文是 10-11 版本的记录。
+
## 授权与范围
- 用户:现在的去除重复帧还是软件初期设计;PS5 等游戏锁 30/40 帧、采集卡采 60 帧(延迟比采 30 帧低)时,希望在补帧的“内容节奏”里重新设计去重复帧,兼容各类帧率;原来的 60→30 容易把真实帧也剔除,导致补帧鬼影;不要增加大量计算耗时;用 GTA6 30 帧视频渲染成 60 帧、58 帧来测试。完成后汇报并关机。
diff --git a/docs/CONTENT_CADENCE_EXACT_2026-10-12.md b/docs/CONTENT_CADENCE_EXACT_2026-10-12.md
new file mode 100644
index 00000000..2595cda0
--- /dev/null
+++ b/docs/CONTENT_CADENCE_EXACT_2026-10-12.md
@@ -0,0 +1,57 @@
+# 内容节奏修正:60→30 还原,去重只认完全相同的画面(2026-10-12)
+
+## 授权与问题
+
+- 用户(2.0.7 测试包实测,MCS T911 2560×1440@60 P010 HDR):“采集 60→30”被植入了内容节奏判断,原始帧率也在跳,要求还原为最简单的 60 帧 AABBCCDD → ABCD 并且稳定;新的“自动识别内容节奏”去除重复帧的频率变化太快、不稳定,导致 VFG 耗时乱跳、GPU 占用忽高忽低;游戏一直在运行却出现 6fps,怀疑不是百分百相同的帧也被去掉了。
+- 沿用规则:先存档、开分支,负优化就退回;每种测试一个;不 merge/push/Release;不打扰 Codex。
+- 存档:标签 `checkpoint/pre-claude-cadence-exact-20261012`(main 05bc4b5);`archives/claude-cadence-exact-20261012/`(start.json、source-before.bundle 已 verify)。分支 `claude/cadence-exact-20261012`,工作树 `worktrees/cadence-exact-20261012`。
+
+## 原因(用户日志 test-2.0.7 包 logs/veyra-qml.log)
+
+- 60→30(mode=5):`[content-dedup] observed=70 kept=7 repeats=63 held=7`,每秒只留 6–16 帧。85cbd5a 把 60→30 改成“去重 + 30 上限”,所以它跟着去重一起出错。
+- 自动(mode=1)同样出现 `kept=6~7 held=6~7`:所有帧都被判成重复,只靠 150–250 ms 的保持上限偶尔放行一帧。
+- 判重方法:只比较 64×36 个单像素采样点(2560×1440 下每 40×40 取 1 个,P010 只取高 8 位),变化超过 8 级才算新画面。站在原地时游戏里的小动作(角色待机、植被、粒子、HDR 暗部的细微变化)碰不到采样点或不到 8 级,被当成重复去掉。旧文档的“未验证与边界”已写到“采样点碰不到的极小变化会被当成重复”,实机上这种情况是常态。
+
+## 修正
+
+1. **采集 60→30**:回到 `CaptureHalfRate`(与 85cbd5a 之前的代码相同):按时间戳每两帧取一帧、保留原始时间戳、稳定 30 帧;不再经过任何画面判断。
+2. **自动识别 / 识别 30·50·60fps 内容**:一帧只有与上一张保留的画面**逐字节完全相同**(整张画面、所有像素、所有平面)才算重复。
+ - `include/veyra/pipeline/PictureFingerprint.h`:8 路 128 位 AES 状态、每 16 字节两轮,每一步都是状态的双射,任何一个字节不同都会让指纹不同;128 字节状态整体比较,没有任何阈值。
+ - 采集回调在内容去重开启时(`CaptureCardSource::setPictureFingerprints`)对驱动样本计算(不读写合并的上传缓冲),1440p P010 约 0.2 ms、4K P010 约 0.5 ms(本机 9700X),关闭去重时为 0;MJPEG 解码画面同样在解码线程计算;其他 CPU 帧(转换后的帧、测试回放)在引擎端计算(`captureFrameFingerprint`);硬件解码的帧没有 CPU 画面,不去重(与以前相同)。
+ - 卡顿:同一画面持续不到 2.5 个内容周期时仍去掉重复帧(下一张新画面覆盖整个等待时间)。超过后视为静止画面(暂停、菜单),按内容节奏的时间网格保留(30/40/60 帧内容静止时仍是 30/40/60),不再每秒只留 4–7 帧,NR/补帧的 GPU 工作量保持稳定。
+ - 内容时间戳(回归周期、夹在采样窗口内)不变。
+3. 删除不再使用的 `EnhanceGraph::lumaSignature`;内容节奏提示文字(四语)改为“只去掉与上一张完全相同的画面;采集 60→30 固定每两帧取一帧,稳定 30 帧”。
+4. 测试开关 `VEYRA_TEST_CONTENT_DEDUP_LEGACY=1` 仍恢复只统计不去重的旧内容模式;60→30 不再受它影响。
+
+## 测试(每种一个)
+
+| 类型 | 内容 | 结果 |
+| --- | --- | --- |
+| 单元 | `veyra_live_timing_tests`:30-in-60/58、40-in-60、真 60、带噪声重复帧、卡顿、1440p P010 尺寸画面只改 1 字节、静止画面(30/40 帧内容之后、无周期时)、无 CPU 画面;CaptureHalfRate 原有用例 | 92 项全部通过 |
+| 离线同帧 A/B(只用 CPU) | 同一批解码帧同时送旧版(64×36 点)和新版(整画面指纹),`reports/claude-cadence-exact-20261012/offline-ab.json` | 见下表 |
+| 引擎回放(不开补帧,轻 GPU) | `veyra_live_presentation_tests --dedup-auto-nofg / --dedup-half-nofg`,静止画面 + 小物体素材 | 自动:540/540 真实画面、0 丢失、0 重复、每秒恒 30、内容间隔恒 33.333 ms;60→30:每秒恒 30、0 丢失、0 重复 |
+| 回归 | 原有 `--half-rate`(60→30 采样 + 热切换 NR/2X/关闭/切回原节奏) | 34 项全部通过,30 fps→切回 60 fps |
+| 界面 | `veyra_ui_contract_tests`;新 EXE 私有 profile 冷启动 15 秒 | 通过;无 QML 错误 |
+
+离线 A/B(20 秒,60 Hz 采样,1920×1080):
+
+| 素材 | 旧版保留 / 丢失真实画面 / 每秒 | 新版保留 / 丢失 / 每秒 |
+| --- | --- | --- |
+| 静止画面 + 20×20 低对比度移动方块,30→60 无损 | 134 / **465** / 6–7 | **600 / 0 / 恒 30** |
+| GTA6 30→60 无损 | 598 / 0 / 30 | 598 / 0 / 30 |
+| GTA6 30→60 有损 x264(重复帧不逐字节相同) | 598 / 0 / 30(留 4 张重复) | 1196 / 0 / 60(不去重) |
+
+指纹耗时(1080p CPU 帧)P50 约 0.06 ms,引擎内 P50 0.21 ms / P99 0.47 ms(软件解码帧,含缓存未命中)。
+
+日志:`logs/claude-cadence-exact-20261012/replay-20261012-204924`(自动/60→30/单元/界面)、`replay-20261012-205028`(half-rate)、`gui-smoke-*`;构建 `build-20261012-204834/receipt.json`。素材 `tests/claude-cadence-exact-20261012/media`(ffmpeg 无损生成,framemd5 确认每张画面恰好两帧)。
+
+## 测试包
+
+`tests/claude-cadence-exact-20261012/Veyra-2.0.7-test-cadence-NVIDIA`:2.0.7 NVIDIA 测试包全量复制(1639 个文件),只换 `veyra_qml_ui.exe`(显示版本 2.0.7-test-cadence)与 `qml/Veyra/ProPage.qml`;设置与 2.0.7 测试包共用(`%LOCALAPPDATA%` 下 user-data-2.0.0)。
+
+## 未验证与边界
+
+- 没有用实卡验证:用户的 2.0.7 会话一直占用 T911;采集回调里的指纹路径只经代码审查与同算法离线/回放验证。
+- 采集卡对同一画面输出的数据如果不是逐字节相同(压缩/带噪声,例如 MJPEG 或有损串流),自动识别不会去掉任何帧(等同“采用源时间戳”,日志 `repeats=0`)——这是“只去百分百相同的帧”的代价,不会丢真实画面。
+- 静止画面按内容节奏保留意味着暂停/菜单时 GPU 仍按 30/40/60 帧工作(为了稳定);旧版此时只有 4–7 帧。
+- 硬件解码的串流(PS5 Remote Play、Moonlight、Xbox)不去重,60→30 对它们按时间戳隔帧,与以前相同。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index b464d085..c1f59894 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -9295,3 +9295,11 @@ audit.py核对测试/GUI/所有app原件、两份旧final、旧JSON和源码bund
- XeSS实际GUI开关/重启、seek/暂停/倍率/光流/关闭再开通过;GTA4K30+原版NR1080+XeSS2X、GPU普通class2,20独立样本软件提交60FPS,应用GPU图8.54ms、NR采样5.85ms、光流2.39ms。这不是完整XeSS驱动开销、屏幕刷新/延迟或新A/B提速证明;默认优先级仍原有实时class5。几何52状态D3D12/软件×100%/150%无播放条遮挡。
- 66旧树/509脏文件及分支tip核验原样,完成来源均为整合祖先。旧RTSS仅剩计划文档,其余旧归档/撤回实验不混入。没有新增生产Timer、统计频率或采集逐帧缓冲变更,没有运行库/SDK/模型/私有素材入Git。
- 本验收tip按用户授权本地main --no-ff合并,完整Git树必须相同;随后脚本test-2.0.7-package.py seal/cold制作NVIDIA/AMD完整包及本版源码,审计逐文件/运行组件/厂商/PE/ZIP并用解压最终ZIP私有目录冷启动。合并hash/保护快照见archives/test-2.0.7-20261012,最终包证据见test-packages/test-2.0.7-20261012/DELIVERY.json、cold-start.json;完成前不交付。当前两份staging内容审计已通过,最终封包/冷启动另记外部回执,避免源码自引用改包。NV长期显存增长和AMD/BMD现场未宣称根治;未push/Release/上传/关机。
+
+## 2026-10-12 内容节奏修正:60→30 还原,去重只认完全相同画面(Claude)
+
+- 用户实测 2.0.7(MCS T911 2560×1440@60 P010 HDR):60→30 原始帧率跳动,要求还原为 AABBCCDD→ABCD 稳定隔帧;自动识别去重不稳定、游戏运行中出现 6fps。存档 checkpoint/pre-claude-cadence-exact-20261012(main 05bc4b5)、archives/claude-cadence-exact-20261012,分支 claude/cadence-exact-20261012。
+- 原因:85cbd5a 让 60→30 走“去重+30 上限”;去重只比 64×36 个单像素采样点(P010 取高 8 位)、变化超过 8 级才算新画面,原地站立时的小动作碰不到采样点,被当成重复(日志 mode=5/1 每秒只留 6–16 帧、held=6–7)。
+- 修正:60→30 回到 CaptureHalfRate;内容模式用 PictureFingerprint(整画面所有平面逐字节,8 路 AES),完全相同才去掉;采集回调只在去重开启时计算(1440p P010 约 0.2 ms),MJPEG 解码帧同样,其他 CPU 帧引擎端算;静止画面超过 2.5 个内容周期后按内容节奏网格保留。删除 EnhanceGraph::lumaSignature,提示文字四语更新。
+- 结果:离线同帧 A/B 静止画面+小低对比移动物体(无损 30→60)旧版 600 张真实画面只留 134(每秒 6–7),新版 600/600 每秒恒 30;GTA6 无损 30→60 两者 598/598;有损 x264 重复帧不逐字节相同,新版全部保留。引擎回放(不开补帧)自动 540/540、0 丢失 0 重复、每秒恒 30、间隔恒 33.333 ms;60→30 每秒恒 30。单测 92、--half-rate 34、ui-contracts、新 EXE 冷启动通过。构建 py -3.11 -I tmp/claude-cadence-exact-20261012/build.py(复用 build/test-2.0.7-20261012 对象,只读)。
+- 测试包 tests/claude-cadence-exact-20261012/Veyra-2.0.7-test-cadence-NVIDIA(2.0.7 NVIDIA 包全量复制,只换 EXE 与 ProPage.qml,共用用户设置)。实卡未验(用户会话占用 T911);采集卡重复帧若非逐字节相同则自动模式不去重(repeats=0)。无 merge/push/Release。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 008ce997..4a7a569f 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -9271,11 +9271,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 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-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": "游戏与程序 · ",
diff --git a/include/veyra/engine/ContentDedup.h b/include/veyra/engine/ContentDedup.h
index 2a1bc048..84f6e24d 100644
--- a/include/veyra/engine/ContentDedup.h
+++ b/include/veyra/engine/ContentDedup.h
@@ -1,123 +1,101 @@
#pragma once
+#include "veyra/pipeline/PictureFingerprint.h"
#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).
+// Repeated-picture removal and content cadence for live sources (2026-10-11,
+// exact pictures 2026-10-12).
//
-// 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 game locked to 30 or 40 fps behind a 60 Hz capture repeats pictures; frame
+// generation then interpolates across a still pair, or across a doubled step
+// where a blind sampler dropped a real picture. The content modes (auto /
+// 30 / 50 / 60 fps) drop a sample here when its picture repeats the last kept
+// one; "60->30" is the plain every-second-sample CaptureHalfRate, not this.
//
-// 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.
+// A repeat is a picture whose every byte of every plane equals the last kept
+// picture (PictureFingerprint.h). The first version judged 64x36 sampled points
+// with an 8-level gate: a running HDR game seen from a still position lost most
+// real pictures (6-16 kept of 60 per second, field log 2026-10-12). Anything
+// that is not bit-identical is a new picture now, so a noisy or re-encoded
+// source simply keeps every sample.
+//
+// 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.
+//
+// A picture that stays identical past a hitch (paused game, menu) is held at
+// the content cadence instead of one frame per 150-250 ms: the kept rate, and
+// with it the GPU work of NR and frame generation, stays steady.
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 observed = 0, kept = 0, repeats = 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;
+ haveKept_ = haveContent_ = skipSpan_ = holding_ = 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.
+ // picture: exact identity of the sample, or nullptr (no CPU picture: keep everything).
// 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 observe(const pipeline::PictureFingerprint* picture, int64_t pts, int64_t transport, bool boundary, 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.
+ if (!picture) {
+ // No CPU picture (hardware-decoded streams): keep everything. A
+ // boundary (open, seek, settings change) re-anchors the cadence.
++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");
+ return keep(d, pts, previous, transport, picture, 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;
+ if (*picture == kept_) {
+ const int64_t cadence = std::min<int64_t>(period_ > 0 ? period_ : hintPeriod > 0 ? hintPeriod : transport * 2, 666667);
+ if (!holding_) {
+ // A hitch repeats one picture for a few samples: drop those, so
+ // the next picture spans the whole wait.
+ if (pts - lastKeptSample_ < std::max(cadence * 5 / 2, transport * 3)) { ++stats_.repeats; d.keep = false; d.reason = "repeat"; return d; }
+ holding_ = true; holdDue_ = pts;
}
+ // Past that the picture is still: hold it on the content cadence's
+ // grid (40 fps in 60 Hz keeps 33/17 ms), never slower than 15 fps.
+ if (pts + transport / 4 < holdDue_) { ++stats_.repeats; d.keep = false; d.reason = "repeat"; return d; }
+ holdDue_ = std::max(holdDue_ + cadence, pts + cadence / 2);
++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, picture, Timing::Sample, "hold");
}
- return keep(d, pts, previous, transport, luma, Timing::Cadence, "new", hintPeriod);
+ holding_ = false;
+ return keep(d, pts, previous, transport, picture, 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,
+ Decision& keep(Decision& d, int64_t pts, int64_t previous, int64_t transport, const pipeline::PictureFingerprint* picture, Timing timing,
const char* reason, int64_t hint = 0) {
d.keep = true; d.reason = reason; ++stats_.kept;
int64_t content = pts;
@@ -162,19 +140,18 @@ private:
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; }
+ if (picture) { kept_ = *picture; 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_{};
+ pipeline::PictureFingerprint 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;
+ bool haveKept_ = false, haveContent_ = false, skipSpan_ = false, holding_ = false;
+ int64_t prevSample_ = 0, lastKeptSample_ = 0, lastContent_ = 0, period_ = 0, holdDue_ = 0;
Stats stats_;
};
}
diff --git a/include/veyra/pipeline/CaptureUploadFrame.h b/include/veyra/pipeline/CaptureUploadFrame.h
index 7bc7c3c9..5279e9da 100644
--- a/include/veyra/pipeline/CaptureUploadFrame.h
+++ b/include/veyra/pipeline/CaptureUploadFrame.h
@@ -24,6 +24,10 @@
// - The 64x36 points the graph analyses are sampled in the callback from the
// driver sample (raw pixel bytes, same packing as the frame), never read
// back from the upload buffer.
+// - While content dedup runs (ContentDedup.h) the callback also fingerprints
+// the whole driver sample, every payload byte of every plane, for the same
+// reason: the engine decides on repeats without touching the upload buffer.
+#include "veyra/pipeline/PictureFingerprint.h"
#include <d3d12.h>
#include <wrl/client.h>
#include <cstdint>
@@ -33,7 +37,9 @@
extern "C" {
#include <libavutil/buffer.h>
#include <libavutil/frame.h>
+#include <libavutil/imgutils.h>
#include <libavutil/mem.h>
+#include <libavutil/pixdesc.h>
}
namespace veyra::pipeline {
@@ -56,6 +62,9 @@ struct CaptureUploadFrame {
// proxyPitch(): a tiny frame with the same packing as the real one.
uint8_t proxy[kProxyWidth * kProxyHeight * kMaxPixelBytes] = {};
int proxyPitch() const { return int(kProxyWidth * pixelBytes); }
+ // Exact identity of the picture (content dedup only; see the rules above).
+ bool fingerprintValid = false;
+ PictureFingerprint fingerprint;
uint64_t fallbacks = 0;
// Last GPU list that reads the upload buffer (set by the graph).
@@ -134,7 +143,7 @@ inline void selectCaptureUploadTarget(AVFrame& frame) {
auto* info = captureUploadFrame(&frame);
if (!info) return;
uint8_t* base = info->mapped;
- info->direct = true; info->proxyValid = false;
+ info->direct = true; info->proxyValid = false; info->fingerprintValid = false;
if (info->gpuBusy()) {
if (!info->cpu) { info->cpu = static_cast<uint8_t*>(av_malloc(size_t(info->bytes))); if (info->cpu) std::memset(info->cpu, 0, size_t(info->bytes)); }
if (info->cpu) { base = info->cpu; info->direct = false; ++info->fallbacks; }
@@ -150,7 +159,7 @@ inline void useCaptureUploadCpuPlanes(AVFrame& frame) {
if (!info) return;
if (!info->cpu) { info->cpu = static_cast<uint8_t*>(av_malloc(size_t(info->bytes))); if (info->cpu) std::memset(info->cpu, 0, size_t(info->bytes)); }
if (!info->cpu) return;
- info->direct = false; info->proxyValid = false;
+ info->direct = false; info->proxyValid = false; info->fingerprintValid = false;
frame.data[0] = info->cpu;
if (info->planes == 2) frame.data[1] = info->cpu + info->chromaOffset;
}
@@ -174,6 +183,32 @@ inline void sampleCaptureUploadProxy(AVFrame& frame, const uint8_t* source, size
info->proxyValid = true;
}
+// Content dedup (ContentDedup.h): exact identity of the whole picture. An
+// upload-backed frame carries the capture callback's fingerprint of the driver
+// sample and is never read back; any other CPU frame (CPU planes, decoded or
+// converted frames, test replay) is hashed here, every payload byte of every
+// plane. Hardware frames, and upload buffers written without a fingerprint,
+// have none: the caller keeps the sample.
+inline bool captureFrameFingerprint(const AVFrame* frame, PictureFingerprint& out) {
+ if (!frame || !frame->data[0] || frame->width <= 0 || frame->height <= 0) return false;
+ if (const auto* info = captureUploadFrame(frame)) {
+ if (info->fingerprintValid) { out = info->fingerprint; return true; }
+ if (info->direct) return false;
+ }
+ const auto format = AVPixelFormat(frame->format);
+ const auto* desc = av_pix_fmt_desc_get(format);
+ if (!desc || (desc->flags & (AV_PIX_FMT_FLAG_HWACCEL | AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_PAL))) return false;
+ PictureHasher hasher;
+ for (int plane = 0, planes = av_pix_fmt_count_planes(format); plane < planes; ++plane) {
+ const int bytes = av_image_get_linesize(format, frame->width, plane);
+ const int rows = plane == 1 || plane == 2 ? -((-frame->height) >> desc->log2_chroma_h) : frame->height;
+ if (bytes <= 0 || !frame->data[plane] || frame->linesize[plane] < bytes) return false;
+ hasher.rows(frame->data[plane], size_t(frame->linesize[plane]), size_t(bytes), unsigned(rows));
+ }
+ out = hasher.finish();
+ return true;
+}
+
// v210 stores six pixels in four words, not one four-byte word per pixel.
// Copy complete groups from the driver sample; never read width*4 bytes from
// its shorter packed row. Analysis remains a bounded coarse source sample.
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index e2c50ee0..8cd0e00f 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -467,10 +467,6 @@ 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/include/veyra/pipeline/PictureFingerprint.h b/include/veyra/pipeline/PictureFingerprint.h
new file mode 100644
index 00000000..52e8ee15
--- /dev/null
+++ b/include/veyra/pipeline/PictureFingerprint.h
@@ -0,0 +1,86 @@
+#pragma once
+// Exact picture identity for repeated-frame removal (2026-10-12).
+//
+// ContentDedup judged a repeat on 64x36 sampled points with a change gate of 8
+// levels, so a still scene with small real motion lost real pictures (field log
+// 2026-10-12: a running 1440p P010 HDR game kept 6-16 of 60 frames). A picture
+// now repeats only when every byte of every plane is identical: rows are
+// absorbed into eight 128-bit lanes, two AES rounds per 16 bytes. Each step is a
+// bijection of the lane state, so a changed byte changes its lane and the lanes
+// re-converge only if a later difference cancels a pseudo-random 128-bit state
+// difference exactly. The 128-byte state is compared whole; nothing is
+// thresholded. ~0.2 ms for a 1440p P010 picture on one core (bench 2026-10-12).
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <emmintrin.h>
+#include <intrin.h>
+#include <wmmintrin.h>
+
+namespace veyra::pipeline {
+
+struct PictureFingerprint {
+ std::array<uint64_t, 16> words{};
+ bool operator==(const PictureFingerprint&) const = default;
+};
+
+class PictureHasher {
+public:
+ static constexpr unsigned kLanes = 8;
+ PictureHasher() {
+ for (unsigned i = 0; i < kLanes; ++i) {
+ lanes_[i] = _mm_set_epi64x(int64_t(0x9E3779B97F4A7C15ull * (i + 1)), int64_t(0xC2B2AE3D27D4EB4Full ^ (i * 0x165667B19E3779F9ull)));
+ scalar_[2 * i] = 0x9E3779B97F4A7C15ull * (2 * i + 1); scalar_[2 * i + 1] = 0xC2B2AE3D27D4EB4Full * (2 * i + 2);
+ }
+ }
+ // One row (or any byte run); call in the same order for every picture.
+ void absorb(const uint8_t* data, size_t bytes) {
+ total_ += bytes;
+ if (!aes()) { absorbScalar(data, bytes); return; }
+ const __m128i k1 = _mm_set_epi64x(0x243F6A8885A308D3ll, 0x13198A2E03707344ll), k2 = _mm_set_epi64x(int64_t(0xA4093822299F31D0ull), 0x082EFA98EC4E6C89ll);
+ size_t offset = 0;
+ // Lanes stay in registers across the row (a member array is reloaded every block).
+ __m128i a = lanes_[0], b = lanes_[1], c = lanes_[2], d = lanes_[3], e = lanes_[4], f = lanes_[5], g = lanes_[6], h = lanes_[7];
+ const auto mix = [&](__m128i s, size_t at) { return _mm_aesenc_si128(_mm_aesenc_si128(_mm_xor_si128(s, _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + at))), k1), k2); };
+ for (; offset + 16 * kLanes <= bytes; offset += 16 * kLanes) {
+ a = mix(a, offset); b = mix(b, offset + 16); c = mix(c, offset + 32); d = mix(d, offset + 48);
+ e = mix(e, offset + 64); f = mix(f, offset + 80); g = mix(g, offset + 96); h = mix(h, offset + 112);
+ }
+ lanes_[0] = a; lanes_[1] = b; lanes_[2] = c; lanes_[3] = d; lanes_[4] = e; lanes_[5] = f; lanes_[6] = g; lanes_[7] = h;
+ for (unsigned i = 0; offset < bytes; ++i, offset += 16) {
+ alignas(16) uint8_t tail[16] = {};
+ std::memcpy(tail, data + offset, bytes - offset < 16 ? bytes - offset : 16);
+ lanes_[i] = _mm_aesenc_si128(_mm_aesenc_si128(_mm_xor_si128(lanes_[i], _mm_load_si128(reinterpret_cast<const __m128i*>(tail))), k1), k2);
+ }
+ }
+ void rows(const uint8_t* base, size_t pitch, size_t rowBytes, unsigned count) {
+ for (unsigned y = 0; y < count; ++y) absorb(base + size_t(y) * pitch, rowBytes);
+ }
+ PictureFingerprint finish() const {
+ PictureFingerprint out;
+ if (aes()) for (unsigned i = 0; i < kLanes; ++i) _mm_storeu_si128(reinterpret_cast<__m128i*>(out.words.data() + 2 * i), lanes_[i]);
+ else out.words = scalar_;
+ out.words[0] ^= total_;
+ return out;
+ }
+ static bool aes() {
+ static const bool available = [] { int info[4] = {}; __cpuid(info, 1); return (info[2] & (1 << 25)) != 0; }();
+ return available;
+ }
+
+private:
+ // CPUs without AES-NI: sixteen 64-bit lanes, xor-multiply-rotate-multiply per word (each a bijection).
+ void absorbScalar(const uint8_t* data, size_t bytes) {
+ for (size_t offset = 0; offset < bytes; offset += 8) {
+ uint64_t word = 0; std::memcpy(&word, data + offset, bytes - offset < 8 ? bytes - offset : 8);
+ uint64_t& lane = scalar_[(offset / 8) % scalar_.size()];
+ lane = _rotl64((lane ^ word) * 0x9FB21C651E98DF25ull, 29) * 0xD6E8FEB86659FD93ull;
+ }
+ }
+ __m128i lanes_[kLanes];
+ std::array<uint64_t, 16> scalar_{};
+ uint64_t total_ = 0;
+};
+
+} // namespace veyra::pipeline
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 5208ef0a..732f23e0 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -56,6 +56,9 @@ public:
// match the samples (RGB24 upside-down reports). Applies to the next
// sample; works for RGB and YUV without touching the device.
void setVerticalFlip(bool enabled);
+ // Content dedup: fingerprint every sample's whole picture (CaptureUploadFrame.h).
+ // Any thread; applies to the next sample.
+ void setPictureFingerprints(bool enabled);
// N1 diagnostic: keep the legacy per-pixel CPU unpack (BGR0/YUY2 targets)
// instead of the GPU unpack path. Applied on the next connect.
void setCpuUnpack(bool enabled);
diff --git a/include/veyra/source/CaptureCompressedDecoder.h b/include/veyra/source/CaptureCompressedDecoder.h
index 7c97295d..76373ad5 100644
--- a/include/veyra/source/CaptureCompressedDecoder.h
+++ b/include/veyra/source/CaptureCompressedDecoder.h
@@ -69,6 +69,9 @@ public:
bool hardwareActive() const;
bool waitingForInput() const;
void recoverAtKeyframe();
+ // Content dedup: fingerprint each software-decoded MJPEG picture written to an
+ // upload-backed target (CaptureUploadFrame.h). Call on the decoding thread.
+ void setPictureFingerprints(bool enabled);
const char* backendName() const;
const std::string& lastError() const;
uint64_t framesDecoded() const;
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index b3038132..084df410 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -1803,7 +1803,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: 170
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 3afe6618..b016002f 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -30,6 +30,7 @@
#ifdef VEYRA_ENABLE_REMOTEPLAY
#include "veyra/source/RemotePlaySessionSource.h"
#endif
+#include "veyra/pipeline/CaptureUploadFrame.h"
#include "veyra/pipeline/EnhanceGraph.h"
#include "veyra/pipeline/ResetCoordinator.h"
#include "veyra/gfx/XessMfgUnlock.h"
@@ -932,13 +933,16 @@ 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.
+ // Content cadence for live sources (ContentDedup.h): in the auto / 30 / 50 /
+ // 60 fps content modes, bit-identical repeated pictures are dropped before
+ // any GPU work and kept frames get content timestamps. "60->30" is the
+ // plain every-second-sample CaptureHalfRate again (user 2026-10-12).
+ // VEYRA_TEST_CONTENT_DEDUP_LEGACY=1 restores 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;
+ const auto dedupContent=[](ContentRate content){return content!=ContentRate::Transport&&content!=ContentRate::Capture60To30;};
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;};
@@ -1698,36 +1702,38 @@ 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;
+ const bool dedupActive=isCapture&&!isImage&&!legacyCadence&&dedupContent(options.settings.content);
+ // The callback fingerprints whole pictures only while dedup needs them.
+ if(physicalCapture)captureSource.setPictureFingerprints(dedupActive);
if(reset||pipeline::breaksHistory(pkt.flags))captureSampler.reset();
const int64_t samplePts100ns=pkt.pts.isUnknown()?0:pkt.pts.to100ns();
- if(dedupActive&&!rereadCached&&!pkt.pts.isUnknown()&&graph){
+ if(dedupActive&&!rereadCached&&!pkt.pts.isUnknown()){
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());
+ pipeline::PictureFingerprint picture;
+ const auto fingerprintStart=Clock::now();
+ const bool pictured=pipeline::captureFrameFingerprint(frame,picture);
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));
+ const int64_t hint=content==ContentRate::Fps30?333333:content==ContentRate::Fps50?200000:content==ContentRate::Fps60?166667:0;
+ const auto decision=contentDedup.observe(pictured?&picture:nullptr,pkt.pts.to100ns(),interval,boundary,hint);
+ const double dedupUs=elapsedMs(fingerprintStart)*1000;
+ if(veyra::log::verboseFrameLogs())veyra::log::info("content-dedup-frame",std::format("source={} pts100ns={} keep={} reason={} picture={:016x} contentPts100ns={} intervalMs={:.3f} cpuUs={:.1f}",
+ pkt.sequence,pkt.pts.to100ns(),decision.keep,decision.reason,pictured?picture.words[1]:0,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){
+ }else if(halfRate&&!rereadCached){
+ // 60->30: every second sample by timestamp, original PTS, a steady 30.
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||!legacyCadence)captureSampler.reset();
+ if(!halfRate)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));
+ veyra::log::info("cadence-input",std::format("source={} samplePts100ns={} pts100ns={} dedup={} halfRate={}",pkt.sequence,samplePts100ns,pkt.pts.isUnknown()?0:pkt.pts.to100ns(),dedupActive,halfRate));
if(isImage)pkt.sequence=1;
#ifdef VEYRA_ENABLE_XBOX
if(xb&&!rereadCached)xboxReconnectBudget.decoded(monotonic100ns());
@@ -2455,7 +2461,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=isCapture&&!legacyCadence&&options.settings.content!=ContentRate::Transport&&contentDedup.contentFps()>0?int(std::lround(contentDedup.contentFps())):out.measuredContentRate;
+ snapshot_.flowPerf=graph->actualFlowPerf();snapshot_.contentFps=isCapture&&!legacyCadence&&dedupContent(options.settings.content)&&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;
@@ -2484,11 +2490,11 @@ 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){
+ if(isCapture&&dedupContent(options.settings.content)&&!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));
+ veyra::log::info("content-dedup",std::format("revision={} mode={} observed={} kept={} repeats={} held={} blind={} regular={} irregular={} contentFps={:.2f} maxShiftMs={:.2f} (per second; only bit-identical 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.held-dedupLogged.held,st.blind-dedupLogged.blind,
+ st.regular-dedupLogged.regular,st.irregular-dedupLogged.irregular,contentDedup.contentFps(),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()));
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index ca110148..ffbb9040 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -3552,42 +3552,4 @@ 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/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 76610410..4919c094 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -260,11 +260,22 @@ bool parseCapturePath(std::wstring_view path,CaptureSelection& selection){
selection.videoIndex=videoIndex;selection.format=format;selection.audio=audio;selection.colorOverride=fields>=4?colorOverride:0;return true;
}
}
+// Content dedup (ContentDedup.h): exact identity of the driver sample, every
+// payload byte of every plane in source order, never the write-combined copy.
+// About 0.2 ms for 1440p P010 and 0.5 ms for 4K P010 (bench 2026-10-12), so
+// only while a content mode asks for it.
+static void fingerprintCaptureSample(const CaptureMediaLayout& layout,const uint8_t* data,AVFrame& frame){
+ auto* info=pipeline::captureUploadFrame(&frame);if(!info)return;
+ pipeline::PictureHasher hasher;
+ hasher.rows(data,layout.stride,layout.rowBytes,layout.height);
+ for(unsigned p=1;p<layout.planes;++p)hasher.rows(data+(p==1?layout.chromaOffset:layout.secondChromaOffset),layout.chromaStride,layout.chromaRowBytes,layout.height/2);
+ info->fingerprint=hasher.finish();info->fingerprintValid=true;
+}
// One native sample into a mailbox frame. Upload-backed frames
// (CaptureUploadFrame.h) are written once, straight into GPU upload memory, or
// into their CPU planes while the GPU still reads the buffer; planar I420/YV12
// is interleaved into the frame's NV12 layout here instead of in the graph.
-static bool writeCaptureFrame(const CaptureMediaLayout& layout,const uint8_t* data,size_t bytes,AVFrame& frame,bool flipRows){
+static bool writeCaptureFrame(const CaptureMediaLayout& layout,const uint8_t* data,size_t bytes,AVFrame& frame,bool flipRows,bool fingerprint){
pipeline::selectCaptureUploadTarget(frame);
const bool flip=layout.bottomUp!=flipRows;
if(layout.planes==3&&frame.format==AV_PIX_FMT_NV12&&pipeline::captureUploadFrame(&frame)){
@@ -273,6 +284,7 @@ static bool writeCaptureFrame(const CaptureMediaLayout& layout,const uint8_t* da
}else if(!copyCaptureSample(layout,data,bytes,frame,flipRows))return false;
if(layout.packing==CapturePacking::V210)pipeline::sampleCaptureV210Proxy(frame,data,layout.stride,flip);
else pipeline::sampleCaptureUploadProxy(frame,data,layout.stride,flip);
+ if(fingerprint)fingerprintCaptureSample(layout,data,frame);
return true;
}
struct CaptureCardSource::Impl:ISampleGrabberCB {
@@ -373,6 +385,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
std::vector<AVFrame*> compressedFree;
// Manual capture flip; read by the DirectShow callback thread.
std::atomic<bool> verticalFlip{false};
+ // Content dedup wants picture fingerprints; read by the callback and MJPEG workers.
+ std::atomic<bool> pictureFingerprints{false};
std::unique_ptr<WasapiAudioInput> wasapi;
std::unique_ptr<decklink::Capture> decklink;
std::wstring audioError;
@@ -417,7 +431,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
externalFrames.fetch_add(1,std::memory_order_relaxed);
AVFrame* staged=nullptr;bool written=false;
{std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}}
- if(staged)written=writeCaptureFrame(layout,data,bytes,*staged,verticalFlip.load());
+ if(staged)written=writeCaptureFrame(layout,data,bytes,*staged,verticalFlip.load(),pictureFingerprints.load(std::memory_order_relaxed));
{
std::lock_guard lock(mutex);
if(staged)stagingBusy=false;
@@ -492,6 +506,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
}
// Upload-backed target: written once, straight into GPU upload memory.
pipeline::selectCaptureUploadTarget(*target);
+ decoder.setPictureFingerprints(pictureFingerprints.load(std::memory_order_relaxed));
AVFrame* decodedFrame=nullptr;bool hardware=false;
const bool produced=decoder.decode(sample.payload.data(),sample.payload.size(),int64_t(sample.time*1e7),target,&decodedFrame,hardware)&&!hardware;
{
@@ -613,7 +628,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
{std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}
if(signalProbeEnabled&&arrival>=nextSignalProbe){nextSignalProbe=arrival+std::chrono::seconds(1);probeNow=true;}}
if(probeNow)signalSample=sampleCaptureSignal(layout,data,size_t(sample->GetActualDataLength()));
- if(staged)stagedOk=writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*staged,verticalFlip.load());
+ if(staged)stagedOk=writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*staged,verticalFlip.load(),pictureFingerprints.load(std::memory_order_relaxed));
}
{
std::lock_guard lock(mutex);
@@ -688,7 +703,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
}else{
// Staging frame unavailable (should not happen once
// configured); keep the locked copy as a safe fallback.
- if(!writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load())){callbackError=true;wake.notify_one();return S_OK;}
+ if(!writeCaptureFrame(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame,verticalFlip.load(),pictureFingerprints.load(std::memory_order_relaxed))){callbackError=true;wake.notify_one();return S_OK;}
}
if(pending)++dropped;
// Inspect consecutive callbacks, not consecutive mailbox reads.
@@ -857,6 +872,9 @@ void CaptureCardSource::setVerticalFlip(bool enabled){
if(p.verticalFlip.exchange(enabled)==enabled)return;
log::info("capture-flip",std::format("manual vertical flip={} (applies to the next sample; ingest only)",enabled?1:0));
}
+void CaptureCardSource::setPictureFingerprints(bool enabled){
+ if(p_->pictureFingerprints.exchange(enabled)!=enabled)log::info("capture-dedup",std::format("picture fingerprints={} (whole driver sample, content dedup)",enabled?1:0));
+}
void CaptureCardSource::setCpuUnpack(bool enabled){
auto& p=*p_;
if(p.cpuUnpack==enabled)return;
diff --git a/src/source/CaptureCompressedDecoder.cpp b/src/source/CaptureCompressedDecoder.cpp
index 38ae9430..c2728235 100644
--- a/src/source/CaptureCompressedDecoder.cpp
+++ b/src/source/CaptureCompressedDecoder.cpp
@@ -67,6 +67,7 @@ struct CaptureCompressedDecoder::Impl {
bool hardwareChecked = false;
bool waiting = false;
bool depthWarningLogged = false;
+ bool fingerprints = false; // content dedup: fingerprint each decoded picture
std::string error;
uint64_t frames = 0, failures = 0, fallbacks = 0;
double decodeMs = 0, convertMs = 0;
@@ -108,6 +109,16 @@ struct CaptureCompressedDecoder::Impl {
}
}
pipeline::sampleCaptureUploadProxy(*target, frame.data[0], size_t(frame.linesize[0]), false);
+ // Content dedup (ContentDedup.h): the decoded picture, every byte of every
+ // plane; the upload buffer written above is never read back.
+ if (auto* info = fingerprints ? pipeline::captureUploadFrame(target) : nullptr) {
+ pipeline::PictureHasher hasher;
+ const unsigned chromaRows = is422 ? height : height / 2;
+ hasher.rows(frame.data[0], size_t(frame.linesize[0]), width, height);
+ hasher.rows(frame.data[1], size_t(frame.linesize[1]), width / 2, chromaRows);
+ hasher.rows(frame.data[2], size_t(frame.linesize[2]), width / 2, chromaRows);
+ info->fingerprint = hasher.finish(); info->fingerprintValid = true;
+ }
return true;
}
@@ -382,6 +393,7 @@ bool CaptureCompressedDecoder::opened() const { return p_->decoder.opened(); }
bool CaptureCompressedDecoder::hardwareActive() const { return p_->hardware; }
bool CaptureCompressedDecoder::waitingForInput() const { return p_->waiting; }
void CaptureCompressedDecoder::recoverAtKeyframe() { p_->decoder.recoverAtKeyframe(); }
+void CaptureCompressedDecoder::setPictureFingerprints(bool enabled) { p_->fingerprints = enabled; }
const char* CaptureCompressedDecoder::backendName() const
{
if (p_->hardware) return p_->stream && p_->codec == CaptureCodec::Hevc ? "d3d11va" : "d3d12va";
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index 05c18e41..91f58239 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -108,7 +108,7 @@ int inactiveEffectsTest(const wchar_t* input,const wchar_t* output,bool nodeMode
// --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){
+__declspec(noinline) static int runContentCadenceReplay(engine::EngineController& engine,const std::wstring& mode,bool fg){
using namespace std::chrono_literals;
auto pumpUntil=[&](auto predicate,std::chrono::seconds limit){
const auto deadline=std::chrono::steady_clock::now()+limit;
@@ -119,8 +119,8 @@ __declspec(noinline) static int runContentCadenceReplay(engine::EngineController
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 bool started=pumpUntil([&]{start.reset(new engine::PlayerSnapshot(engine.snapshot()));return start->frames>30&&(!fg||start->fgActive);},25s);
+ std::cout<<(started?"PASS ":"FAIL ")<<(fg?"replay starts with DLSS 2X":"replay starts without frame generation")<<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;
@@ -253,10 +253,12 @@ int wmain(int argc,wchar_t**argv){
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).
+ // A "-nofg" suffix runs it without frame generation (light GPU load).
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"";
+ std::wstring dedupMode=dedupRun?std::wstring(argv[3]).substr(8):L"";
+ const bool dedupNoFg=dedupMode.ends_with(L"-nofg");if(dedupNoFg)dedupMode.resize(dedupMode.size()-5);
if(dedupRun){
- options.softwareDecode=true;options.fg=true;options.fgMultiplier=2;
+ options.softwareDecode=true;options.fg=!dedupNoFg;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;
@@ -266,7 +268,7 @@ int wmain(int argc,wchar_t**argv){
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(dedupRun){const int result=runContentCadenceReplay(engine,dedupMode,!dedupNoFg);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 3cca55c5..ecc0ee40 100644
--- a/tests/unit/LivePresentationTimingTests.cpp
+++ b/tests/unit/LivePresentationTimingTests.cpp
@@ -4,6 +4,8 @@
#include "veyra/source/CaptureTiming.h"
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/engine/ContentDedup.h"
+#include "veyra/pipeline/PictureFingerprint.h"
+#include <algorithm>
#include <array>
#include <vector>
#include "veyra/engine/FrameRateWindow.h"
@@ -148,27 +150,32 @@ 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");
{
- // 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){
+ // ContentDedup: synthetic pictures sampled at a capture rate, identified by
+ // their exact fingerprint (PictureFingerprint.h). "60->30" is CaptureHalfRate
+ // (tested above), not this.
+ using veyra::engine::ContentDedup;using veyra::pipeline::PictureFingerprint;using veyra::pipeline::PictureHasher;
+ // A 64x36 picture per id; noise makes every sample differ a little, so no two are bit-identical.
+ auto picture=[](uint64_t id,int noise,uint64_t sample){
+ std::array<uint8_t,64*36> pixels{};
+ for(unsigned i=0;i<pixels.size();++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));
+ pixels[i]=uint8_t(std::clamp(v,0,255));
}
+ PictureHasher hasher;hasher.rows(pixels.data(),64,64,36);return hasher.finish();
};
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{};
+ auto run=[&](double captureFps,auto contentOf,int count,int noise,int64_t hint,int64_t expectedPeriod){
+ ContentDedup dedup;Run r;
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);
+ const int64_t pts=int64_t(i)*dt+1000;const int64_t id=contentOf(i);const auto fingerprint=picture(uint64_t(id),noise,uint64_t(i));
+ const auto d=dedup.observe(&fingerprint,pts,dt,i==0,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
+ ++r.kept;if(id==lastPicture&&!noise)++r.keptRepeats;
+ if(pendingPicture>=0&&pendingPicture!=id)++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;}
@@ -177,51 +184,46 @@ int main(){
return r;
};
const int n=1200;
- {const auto r=run(60.0,[](int i){return int64_t(i/2);},n,0,0,0,333333);
+ {const auto r=run(60.0,[](int i){return int64_t(i/2);},n,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);
+ {const auto r=run(58.0,[](int i){return int64_t(std::floor(i*30.0/58.0+1e-9));},n,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);
+ {const auto r=run(60.0,[](int i){return int64_t(std::floor(i*40.0/60.0+1e-9));},n,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);
+ {const auto r=run(60.0,[](int i){return int64_t(i);},n,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");}
+ {const auto r=run(60.0,[](int i){return int64_t(i/2);},n,1,0,333333);
+ check(r.kept==n&&r.droppedReal==0,"dedup 30-in-60 with capture noise: repeats that are not bit-identical are all kept");}
{// 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);
+ const auto r=run(60.0,[](int i){return int64_t(i<301?i/2:(i<304?150:(i-1)/2));},n,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");}
+ {// A still 1440p P010-sized scene where one byte changes per new picture: the
+ // 64x36 points of the first version lost such pictures (field log 2026-10-12).
+ std::vector<uint8_t> frame(size_t(5120)*1440,90);ContentDedup dedup;int kept=0;
+ for(int i=0;i<120;++i){
+ if(i%2==0)frame[size_t(i)*7919%frame.size()]^=1;
+ PictureHasher hasher;hasher.rows(frame.data(),5120,5120,1440);const auto fingerprint=hasher.finish();
+ kept+=dedup.observe(&fingerprint,i*166667+1000,166667,i==0).keep;
+ }
+ check(kept==60,"dedup: a picture that differs in one byte is new, its exact repeat is dropped");}
+ {// Still picture after 30 fps content: held on the 33.3 ms cadence (steady GPU work), not once per 150-250 ms.
+ ContentDedup dedup;int kept=0;
+ for(int i=0;i<600;++i){const auto fingerprint=picture(i<240?uint64_t(i/2):1000u,0,0);const bool keep=dedup.observe(&fingerprint,i*166667+1000,166667,i==0).keep;if(i>=300)kept+=keep;}
+ check(kept>=148&&kept<=152&&dedup.stats().held>=140,"dedup still picture after 30 fps content is held at a steady 30 fps");}
+ {// Still picture after 40 fps content in 60 Hz: held on the 25 ms grid (33/17 ms samples).
+ ContentDedup dedup;int kept=0;
+ for(int i=0;i<600;++i){const auto fingerprint=picture(i<240?uint64_t(std::floor(i*40.0/60.0+1e-9)):1000u,0,0);const bool keep=dedup.observe(&fingerprint,i*166667+1000,166667,i==0).keep;if(i>=300)kept+=keep;}
+ check(kept>=196&&kept<=204,"dedup still picture after 40 fps content is held at 40 fps");}
+ {// Still picture from the start, no learned rate: half the 60 Hz transport.
+ ContentDedup dedup;const auto fingerprint=picture(3,0,0);int kept=0;
+ for(int i=0;i<240;++i)kept+=dedup.observe(&fingerprint,i*166667+1000,166667,i==0).keep;
+ check(kept>=116&&kept<=122,"dedup still picture with no learned rate keeps 30 of a 60 Hz capture");}
{// 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;
}