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

Beauty tracking: detect every frame, One Euro smoothing (no lag, no overshoot)

Veyra Goal Agent91eeae761d65
diff --git a/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md b/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md
index 0f316d7d..30c6e72f 100644
--- a/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md
+++ b/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md
@@ -16,7 +16,7 @@
另有整体强度、磨皮程度、半径(1080p 像素,随画面缩放,0…12)、细节保护、纹理保留、提亮,范围仅人脸 / 全部肤色,
高级项为肤色范围(色相中心/范围、饱和度与亮度上下限、边界柔和)。两项共用人脸置信度门限和遮罩显示(导出时自动关闭)。
-人脸识别由同一条链上的所有美颜节点共用(档位 性能 320 px·10 Hz / 均衡 512 px·15 Hz / 精细 640 px·30 Hz、最多人脸 1…8、
+人脸识别由同一条链上的所有美颜节点共用(每帧识别;档位 性能 320 px / 均衡 512 px / 精细 640 px、最多人脸 1…8、
跟踪平滑 0…1),随链保存、导出时冻结。只有节点开关和实例数会重建处理图,其余全部是实时 uniform。
列表模式:画质页“美颜”卡(NR 组与保护之后、RTX Video HDR 之前),最多 6 层,层卡可复制、上下移动、恢复默认、删除,
@@ -99,3 +99,19 @@ Codex 预算为 1080p 平均 ≤1 ms / P95 ≤2 ms、4K 平均 ≤2.5 ms / P95
2 / 6 节点下的耗时;CPU 渲染线程增量(预算 P95 ≤0.3 ms,未单独测);融合调色时额外转换的耗时。
- 打包脚本尚未把模型放到 `runtime/models`(运行时也查找 `runtime_local/models` 和程序目录下的 `models`),发布前要补。
- 撤销 / 重做对美颜参数的覆盖未单独测试。
+
+## 7. 实测反馈后的跟踪改动(2026-10-18)
+
+用户试用 r1:人物先移出去、区域才跟上,而且一弹一弹。原因是识别只有 15 Hz,每次识别只向新位置走 60%(α = 0.6),
+两次识别之间靠速度外推,速度从 0 慢慢建立(起步拖后)、停下时还按原速度冲过去再被拉回(回弹)。按同样参数模拟
+60 fps、最快 10 个脸宽/秒的运动:最大落后 0.61 脸宽、停下时冲过 0.64 脸宽。
+
+改动:每个新帧都识别(识别与节点在同一帧的命令列表里,人脸就是这一帧的);平滑改为 One Euro 滤波
+(截止频率随速度升高,速度按脸宽/秒计算,与分辨率无关;跟踪平滑 0…1 对应静止截止 3 → 0.3 Hz、速度系数 20 → 6),
+不再预测,停下不会冲过头;漏检的人脸按测得的速度继续走 120 ms 再淡出,新出现的人脸 80 ms 淡入(seek 与图片除外);
+已跟踪的人脸分数可比新起跟踪低 0.15(不在阈值附近闪烁)。模拟同一运动:最大落后约 0.04 脸宽、过冲在噪声水平。
+
+实测(RTX 5070):`tracking`(每帧 3 px)48/48 帧识别,最大中心误差 3.4 px / 脸宽 146 px(原 9.8 px);
+新增 `tracking-motion`(每帧 16 px,约 6.6 脸宽/秒,停下)落后 1.5% 脸宽、过冲 0.25%、停下当帧即稳定。
+每帧识别的成本即原先“识别帧”的成本:1080p 约 0.43 ms、4K 约 0.52 ms(节点 + 识别,一张脸,来自之前的计时;
+本轮用户的测试程序在运行,没有重新计时)。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 568323d0..b50b414b 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -9750,3 +9750,4 @@ Branch claude/aa-53-20261017 from main 26c0d61. Archive E:/项目/Veyra/archives
- 测试(RTX 5070,一次运行):检测器与 OpenCV 5.0.0 在 8 图 × 3 尺寸 × 2 模型上一致;`veyra_beauty_gpu_tests` 11 例(关闭即逐位相同、保护逐位回到原画、HDR、两节点、跟踪、无模型、四张图的磨皮);耗时 1080p 0.093 + 检测 0.13 ms、4K 0.321 + 0.16 ms;GUI 验收 `scripts/acceptance/beauty-gui.py` 59 项(实播放识别到人脸,实时参数不重建,日志无人脸坐标);`ExportWorkflowTests beauty`;QML 编辑器 10 项。
- 最终汇总(`logs/claude-beauty-20261017/final-sweep-20261018-210951`,同一构建、新临时目录):29 项中 28 项通过(含调色逐字节回归 12/12、抗锯齿 GPU 17/17、抗锯齿 GUI 39 项、QML 99 项);image-dimension 的尺寸 / 分块用例全部通过,只有 NR 分块用例因源码路径含非 ASCII 找不到 `ngx-local.json`(与 #53 汇总相同,需 ASCII 路径构建)。
- 没有验证:AMD / Intel、真实采集卡与游戏画面的肉眼评价、长时间运行、CPU 渲染线程增量;打包尚未把模型放进 `runtime/models`。没有合并 main、推送、发布或打包。
+- 用户试用 r1 反馈跟踪落后、回弹:改为每帧识别 + One Euro 平滑(无预测、无过冲)、漏检外推 120 ms、新脸淡入、分数滞回;`tracking` 误差 9.8 → 3.4 px,新增 `tracking-motion`(每帧 16 px)落后 1.5% 脸宽、过冲 0.25%。详见实施文档第 7 节。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 4d912b06..5d0fbf68 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -637,13 +637,6 @@
"en": "2X is the native path; 3X / 4X are experimental unlocks. See diagnostics for failures",
"ja": "2X はネイティブ動作、3X / 4X は実験的なアンロックです。失敗の理由は診断を参照してください"
},
- {
- "zh": "320 像素,每秒 10 次,最省",
- "src": "qml/BeautyEditor.qml",
- "zh-TW": "320 像素,每秒 10 次,最省",
- "en": "320 px, 10 times a second, lightest",
- "ja": "320 px、毎秒 10 回、最も軽い"
- },
{
"zh": "4 项",
"src": "qml/ProPage.qml",
@@ -658,13 +651,6 @@
"en": "5 items",
"ja": "5 項目"
},
- {
- "zh": "512 像素,每秒 15 次",
- "src": "qml/BeautyEditor.qml",
- "zh-TW": "512 像素,每秒 15 次",
- "en": "512 px, 15 times a second",
- "ja": "512 px、毎秒 15 回"
- },
{
"zh": "6 项",
"src": "qml/ProPage.qml",
@@ -672,13 +658,6 @@
"en": "6 items",
"ja": "6 項目"
},
- {
- "zh": "640 像素,每秒 30 次,小脸也能识别",
- "src": "qml/BeautyEditor.qml",
- "zh-TW": "640 像素,每秒 30 次,小臉也能識別",
- "en": "640 px, 30 times a second, finds small faces too",
- "ja": "640 px、毎秒 30 回、小さな顔も検出"
- },
{
"zh": "8 位配对码",
"src": "qml/DialogHost.qml",
@@ -11251,6 +11230,27 @@
"en": "Low mastering peak (older or converted title)",
"ja": "マスタリングのピークが低い作品(旧作・変換版)"
},
+ {
+ "zh": "每帧识别 · 320 像素,最省;远处的小脸可能识别不到",
+ "src": "qml/BeautyEditor.qml",
+ "zh-TW": "每幀識別 · 320 像素,最省;遠處的小臉可能識別不到",
+ "en": "Every frame · 320 px, lightest; small distant faces may be missed",
+ "ja": "毎フレーム検出 · 320 px、最も軽量。遠くの小さな顔は検出されないことがあります"
+ },
+ {
+ "zh": "每帧识别 · 512 像素",
+ "src": "qml/BeautyEditor.qml",
+ "zh-TW": "每幀識別 · 512 像素",
+ "en": "Every frame · 512 px",
+ "ja": "毎フレーム検出 · 512 px"
+ },
+ {
+ "zh": "每帧识别 · 640 像素,小脸也能识别",
+ "src": "qml/BeautyEditor.qml",
+ "zh-TW": "每幀識別 · 640 像素,小臉也能識別",
+ "en": "Every frame · 640 px, finds small faces too",
+ "ja": "毎フレーム検出 · 640 px、小さな顔も検出"
+ },
{
"zh": "比较源画面与上一帧:没有明显变化的像素沿用上一帧输出,明显变化的位置直接用新结果。",
"src": "qml/ProPage.qml",
@@ -14744,13 +14744,6 @@
"en": "Smaller is more sensitive; larger holds more steady",
"ja": "小さいほど敏感、大きいほど安定させる範囲が広がります"
},
- {
- "zh": "越高人脸区域越稳,快速移动时跟得越慢",
- "src": "qml/BeautyEditor.qml",
- "zh-TW": "越高人臉區域越穩,快速移動時跟得越慢",
- "en": "Higher keeps the face area steadier but follows fast movement more slowly",
- "ja": "高いほど顔の範囲が安定しますが、速い動きへの追従は遅くなります"
- },
{
"zh": "越高越保留五官和发丝",
"src": "qml/BeautyEditor.qml",
@@ -14772,6 +14765,13 @@
"en": "Higher is steadier; too high looks dull",
"ja": "高いほど安定しますが、高すぎるとこもった印象になります"
},
+ {
+ "zh": "越高静止时越稳;人物移动时都会紧跟",
+ "src": "qml/BeautyEditor.qml",
+ "zh-TW": "越高靜止時越穩;人物移動時都會緊跟",
+ "en": "Higher is steadier at rest; moving faces are followed closely either way",
+ "ja": "高いほど静止時に安定します。動く顔はどの設定でもしっかり追従します"
+ },
{
"zh": "跟踪平滑",
"src": "qml/BeautyEditor.qml",
diff --git a/include/veyra/beauty/FaceTracker.h b/include/veyra/beauty/FaceTracker.h
index 2effb20e..11ed27d8 100644
--- a/include/veyra/beauty/FaceTracker.h
+++ b/include/veyra/beauty/FaceTracker.h
@@ -13,10 +13,10 @@ namespace veyra::beauty {
// staged tests next to the executable in models/. Empty when none is present.
std::filesystem::path locateFaceModel();
-// Faces for every beauty node of one graph: the YuNet detector on the frame
-// before any effect, at a bounded rate, followed by the GPU tracking pass
-// (shaders/BeautyTrack.hlsl). All of it is recorded into the frame's own command
-// list; the node passes read the faces buffer later in the same frame. Only a
+// Faces for every beauty node of one graph: the YuNet detector on every new frame,
+// before any effect, followed by the GPU tracking pass (shaders/BeautyTrack.hlsl).
+// All of it is recorded into the frame's own command list; the node passes read the
+// faces buffer later in the same frame, so the faces belong to that frame. Only a
// 64-byte status header is read back, a few frames late, for the UI.
class FaceTracker {
public:
@@ -28,14 +28,13 @@ public:
uint64_t frameId = 0; // the same source frame is never detected twice
double ptsMs = 0.0;
bool reset = false; // seek, scene cut, timeline break, new source
- bool still = false; // a picture: fresh faces, no smoothing or prediction
- bool everyFrame = false; // detect on every frame (export)
+ bool still = false; // a picture: fresh faces, no smoothing
};
bool initialize(ID3D12Device* device, const std::filesystem::path& model, uint32_t ringSlots, std::string& error);
void shutdown();
bool ready() const { return ready_; }
- // Live: input size, rate, face count and smoothing, and the lowest confidence any node accepts.
+ // Live: input size, face count and smoothing, and the lowest confidence any node accepts.
void configure(const engine::BeautyDetection& detection, float minConfidence);
// Detection when due, then tracking. Leaves the faces buffer in the non-pixel SRV state.
bool record(ID3D12GraphicsCommandList* list, pipeline::StateTracker& tracker, const Frame& frame);
@@ -57,11 +56,12 @@ private:
std::vector<pipeline::ComPtr<ID3D12Resource>> readbacks_;
std::vector<bool> pending_;
engine::BeautyDetection detection_{};
- float threshold_ = 0.6f;
+ float threshold_ = 0.6f; // a new face needs this score
+ float keepThreshold_ = 0.45f; // a tracked face continues down to this one (the detector's own threshold)
uint32_t slots_ = 0;
- bool ready_ = false, haveFrame_ = false, detectedOnce_ = false, detectedNow_ = false;
+ bool ready_ = false, haveFrame_ = false, detectedNow_ = false;
uint64_t lastFrameId_ = 0, detections_ = 0;
- double lastPts_ = 0.0, lastDetectPts_ = 0.0;
+ double lastPts_ = 0.0;
uint32_t faceCount_ = 0, candidates_ = 0;
};
} // namespace veyra::beauty
diff --git a/include/veyra/engine/BeautySettings.h b/include/veyra/engine/BeautySettings.h
index a81e0cdc..7699974b 100644
--- a/include/veyra/engine/BeautySettings.h
+++ b/include/veyra/engine/BeautySettings.h
@@ -85,13 +85,13 @@ struct BeautySettings {
// One face detector serves every beauty node of a chain: these values are the
// chain's (list and node mode keep their own), saved with it and frozen for export.
+// The detector runs on every new frame at any quality.
struct BeautyDetection {
- uint8_t quality = 1; // 0 performance (320 px, 10 Hz), 1 balanced (512 px, 15 Hz), 2 fine (640 px, 30 Hz)
+ uint8_t quality = 1; // detector input: 0 performance (320 px), 1 balanced (512 px), 2 fine (640 px)
uint8_t maxFaces = 4; // 1 .. 8
- float stability = 0.5f; // 0 .. 1: smoothing of the tracked faces (0 follows every detection)
+ float stability = 0.5f; // 0 .. 1: smoothing of a face at rest (a moving face is followed closely at any value)
bool operator==(const BeautyDetection&) const = default;
uint32_t inputLongSide() const { return quality == 0 ? 320u : quality == 2 ? 640u : 512u; }
- float rateHz() const { return quality == 0 ? 10.0f : quality == 2 ? 30.0f : 15.0f; }
std::string validate() const {
if (quality > 2) return "invalid beauty detection quality";
if (maxFaces < 1 || maxFaces > 8) return "beauty face count out of range";
diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.h
index bb69d254..dba8b46d 100644
--- a/include/veyra/engine/GraphDescription.h
+++ b/include/veyra/engine/GraphDescription.h
@@ -140,7 +140,6 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
describeBeauty(settings,desc);
// A still picture or an export frame is judged on its own faces, never on a
// detection that is a few frames old.
- desc.beautyDetectEveryFrame=request.stillImage||request.exportJob;
// An export never writes a file that silently lacks a selected effect.
desc.beautyRequireDetector=request.exportJob;
desc.videoHdr=settings.videoHdr;
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 1c460d27..27440001 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -180,7 +180,6 @@ struct EnhanceGraphDesc {
// Beauty nodes by parameter ordinal, plus the chain's shared face detection.
std::array<engine::BeautySettings,engine::kMaxBeautyInstances> beauty{};
engine::BeautyDetection beautyDetection{};
- bool beautyDetectEveryFrame=false; // still pictures / export: detect on every frame
bool beautyRequireDetector=false; // export: a missing face detector fails the job before it starts
std::wstring beautyModelPath; // empty: the shipped YuNet file (beauty::locateFaceModel)
static constexpr bool beautyExecutor=true;
diff --git a/qml/Veyra/BeautyEditor.qml b/qml/Veyra/BeautyEditor.qml
index 64acc3b1..f896e83e 100644
--- a/qml/Veyra/BeautyEditor.qml
+++ b/qml/Veyra/BeautyEditor.qml
@@ -193,9 +193,9 @@ ColumnLayout {
label: qsTr("人脸识别 · 全部美颜节点共用"); count: 3
VRow {
label: qsTr("识别档位")
- hint: editor.detection.quality === 0 ? qsTr("320 像素,每秒 10 次,最省")
- : editor.detection.quality === 2 ? qsTr("640 像素,每秒 30 次,小脸也能识别")
- : qsTr("512 像素,每秒 15 次")
+ hint: editor.detection.quality === 0 ? qsTr("每帧识别 · 320 像素,最省;远处的小脸可能识别不到")
+ : editor.detection.quality === 2 ? qsTr("每帧识别 · 640 像素,小脸也能识别")
+ : qsTr("每帧识别 · 512 像素")
VSeg {
objectName: editor.namePrefix + "-quality"
options: [{id: "0", label: qsTr("性能")}, {id: "1", label: qsTr("均衡")}, {id: "2", label: qsTr("精细")}]
@@ -218,7 +218,7 @@ ColumnLayout {
}
VRow {
label: qsTr("跟踪平滑")
- hint: qsTr("越高人脸区域越稳,快速移动时跟得越慢")
+ hint: qsTr("越高静止时越稳;人物移动时都会紧跟")
value: Math.round(Number(editor.detection.stability ?? 0.5) * 100) + "%"
VSlider {
objectName: editor.namePrefix + "-stability"
diff --git a/shaders/BeautyFaces.hlsli b/shaders/BeautyFaces.hlsli
index 89d399a5..8d28feb5 100644
--- a/shaders/BeautyFaces.hlsli
+++ b/shaders/BeautyFaces.hlsli
@@ -4,9 +4,10 @@
#define VEYRA_BEAUTY_FACES_HLSLI
struct BeautyFace {
float4 box; // centre x, centre y, half width, half height: fractions of the source frame
- float4 shape; // cos roll, sin roll (eye line), detector score, presence 0..1
- float4 motion; // velocity x, y (fractions per ms), ms since the last detection match, reserved
- uint4 meta; // header: count, next id, frame counter, raw candidates; face: id, hits, 0, 0
+ float4 shape; // cos roll, sin roll (eye line), recent peak detector score, presence 0..1
+ float4 motion; // filtered speed x, y (fractions per ms), ms since the last detection match, half-width speed
+ uint4 meta; // header: count, next id, frame counter, raw candidates;
+ // face: id, hits, filtered centre x, y at the last match (float bits)
};
static const uint kBeautyMaxFaces = 8u;
#endif
diff --git a/shaders/BeautyTrack.hlsl b/shaders/BeautyTrack.hlsl
index 265bcc9b..0ef6043b 100644
--- a/shaders/BeautyTrack.hlsl
+++ b/shaders/BeautyTrack.hlsl
@@ -1,35 +1,44 @@
// Beauty node: shared face tracking, entirely on the GPU, once per source frame.
//
-// On a detection frame the YuNet candidates (BeautyYuNetDecode.hlsl) go through
-// the same non-maximum suppression as OpenCV's FaceDetectorYN (whole-pixel boxes,
-// highest score first, ties in anchor order, IoU above tNms drops a box), keeping
-// at most tMaxFaces faces. Those faces update up to eight tracks: stable ids, an
-// alpha-beta filter (position weight tAlpha, velocity weight kBeta) so a face
-// does not jitter between detections or lag behind on steady motion, and a
-// grace period followed by a fade when a face is lost. Every other frame only
-// advances the tracks by their velocity. Nothing is read back for the picture.
+// The detector runs on every new frame. Its candidates (BeautyYuNetDecode.hlsl) go
+// through the same non-maximum suppression as OpenCV's FaceDetectorYN (whole-pixel
+// boxes, highest score first, ties in anchor order, IoU above tNms drops a box),
+// keeping at most tMaxFaces faces. Those faces update up to eight tracks with stable
+// ids. Each track is smoothed by a One Euro filter (Casiez, Roussel and Vogel 2012):
+// a low-pass whose cutoff rises with the face's speed, so a face at rest does not
+// jitter and a moving face is followed within about a frame, without the overshoot
+// a predicting filter has where the motion stops. Speeds are in face widths per
+// second, so the behaviour does not depend on the picture size. A face the detector
+// misses keeps moving at its measured speed for the grace period, then fades out
+// where it stopped; a new face fades in, except after a reset or in a picture. A
+// track continues at a lower score than a new one needs (tKeepThreshold against
+// tStartThreshold), so a face near the threshold does not flicker. Nothing is read
+// back for the picture.
#include "BeautyFaces.hlsli"
cbuffer TrackParams : register(b0) {
uint tDetWidth; uint tDetHeight; // detector content size, pixels
uint tCapacity; // candidate list capacity
- uint tFlags; // bit 0 detected this frame, bit 1 reset, bit 2 still picture, bit 3 no prediction
+ uint tFlags; // bit 0 detected this frame, bit 1 reset, bit 2 still picture
float tDtMs; // time since the previous frame (source timestamps)
- float tAlpha; // weight of a new detection, 1 = follow it exactly
+ float tMinCutoff; // One Euro cutoff of a face at rest, Hz
float tNms; // suppression IoU
- float tGraceMs; // a lost face stays this long
+ float tGraceMs; // a missed face keeps moving this long
float tFadeMs; // then fades out over this long
uint tMaxFaces; // 1 .. 8
- float tScoreThreshold;
- uint tReserved0; uint tReserved1; uint tReserved2; uint tReserved3; uint tReserved4;
+ float tKeepThreshold; // score that keeps a track (the candidate list's own threshold)
+ float tBeta; // cutoff increase per face width per second of speed
+ float tDerivativeCutoff; // Hz: smoothing of the measured speed
+ float tFadeInMs; // a new face fades in over this long
+ float tStartThreshold; // score a new track needs
+ uint tReserved0;
};
RWStructuredBuffer<BeautyFace> Faces : register(u0);
RWByteAddressBuffer Candidates : register(u1);
static const uint kGroup = 1024u;
-static const float kBeta = 0.25; // velocity correction per detection
-static const float kMaxSpeed = 0.004; // frame fractions per ms
-static const float kMatchIou = 0.15;
+static const float kMatchIou = 0.2; // against the track moved on to this frame
+static const float kScoreDecay = 0.97; // per matched frame: the track's confidence is its recent peak
// 24 KB of the 32 KB limit: boxes are whole pixels as 16-bit pairs, a removed
// candidate has a negative score.
@@ -60,6 +69,12 @@ float overlap(float4 a, float4 b) {
const float uni = 4.0 * (a.z * a.w + b.z * b.w) - inter;
return uni > 0.0 ? inter / uni : 0.0;
}
+// Exponential smoothing factor of a first-order low-pass with this cutoff over dtMs.
+float lowpass(float cutoffHz, float dtMs) {
+ const float tauMs = 1000.0 / (6.2831853 * max(cutoffHz, 1e-3));
+ return 1.0 / (1.0 + tauMs / max(dtMs, 1e-3));
+}
+float2 lastCentre(BeautyFace f) { return float2(asfloat(f.meta.z), asfloat(f.meta.w)); }
[numthreads(1024, 1, 1)]
void main(uint t : SV_GroupIndex) {
@@ -73,7 +88,7 @@ void main(uint t : SV_GroupIndex) {
const float4 box = asfloat(Candidates.Load4(o));
const uint4 tail = Candidates.Load4(o + 48u);
const float score = asfloat(tail.z);
- const bool valid = score >= tScoreThreshold && box.z > 0.0 && box.w > 0.0 && !any(isnan(box)) && !any(isinf(box)) &&
+ const bool valid = score >= tKeepThreshold && box.z > 0.0 && box.w > 0.0 && !any(isnan(box)) && !any(isinf(box)) &&
all(abs(box) < 16384.0);
const int4 b = int4(box); // truncation toward zero, like OpenCV's Rect2i
gScore[t] = valid ? score : -1.0;
@@ -105,20 +120,26 @@ void main(uint t : SV_GroupIndex) {
}
if (t != 0) return;
- const bool reset = (tFlags & 2u) != 0, still = (tFlags & 4u) != 0, predict = (tFlags & 8u) == 0 && !still;
+ const bool reset = (tFlags & 2u) != 0, still = (tFlags & 4u) != 0;
+ const float dt = still ? 0.0 : max(tDtMs, 0.0);
+ // A frame without a step on the timeline (reset, picture) shows its faces at once.
+ const bool instant = reset || still || dt <= 0.0;
BeautyFace header = Faces[0];
uint count = (reset || still) ? 0u : min(header.meta.x, kBeautyMaxFaces);
uint nextId = reset ? 1u : max(header.meta.y, 1u);
BeautyFace tracks[kBeautyMaxFaces];
+ float4 predicted[kBeautyMaxFaces];
bool matched[kBeautyMaxFaces];
- for (uint i = 0; i < kBeautyMaxFaces; ++i) { tracks[i] = Faces[1 + i]; matched[i] = false; }
-
- // 1. Advance every track to this frame.
- for (uint a = 0; a < count; ++a) {
- tracks[a].motion.z += tDtMs;
- if (predict && tracks[a].motion.z <= tGraceMs) tracks[a].box.xy += tracks[a].motion.xy * tDtMs;
+ for (uint i = 0; i < kBeautyMaxFaces; ++i) {
+ tracks[i] = Faces[1 + i];
+ matched[i] = false;
+ if (i < count) tracks[i].motion.z += dt;
+ // Where the face is now if it kept its speed since its last detection (for the grace period at most).
+ predicted[i] = tracks[i].box;
+ predicted[i].xy = lastCentre(tracks[i]) + tracks[i].motion.xy * min(tracks[i].motion.z, tGraceMs);
}
- // 2. Detections, best first, update the closest unmatched track or start one.
+
+ // 1. Detections, best first, update the best-overlapping unmatched track or start one.
const float2 det = float2(max(tDetWidth, 1u), max(tDetHeight, 1u));
for (uint d = 0; d < gKeptCount; ++d) {
const uint o = 16u + gKept[d] * 64u;
@@ -132,47 +153,60 @@ void main(uint t : SV_GroupIndex) {
int best = -1; float bestOverlap = kMatchIou;
for (uint j = 0; j < count; ++j) {
if (matched[j]) continue;
- const float v = overlap(tracks[j].box, box);
+ const float v = overlap(predicted[j], box);
if (v > bestOverlap) { bestOverlap = v; best = int(j); }
}
if (best >= 0) {
BeautyFace f = tracks[best];
- const float2 innovation = box.xy - f.box.xy;
- // A jump of more than half a face is a new position, not noise.
- const bool jump = length(innovation / max(f.box.zw, 1e-4)) > 1.0;
- const float alpha = (still || jump) ? 1.0 : tAlpha;
- if (predict && f.motion.z > 0.0) {
- const float2 v = f.motion.xy + kBeta * innovation / max(f.motion.z, 1.0);
- f.motion.xy = clamp(v, -kMaxSpeed, kMaxSpeed);
+ const float since = max(f.motion.z, 1e-3); // ms since this track's last detection
+ const float width = max(2.0 * f.box.z, 1e-4);
+ const float2 from = lastCentre(f); // filtered centre at that detection: speeds
+ const float2 shown = f.box.xy; // where it is drawn now (moved on after a miss): blends
+ if (instant || length(box.xy - shown) > width) {
+ // A cut or a jump of more than a face width: the filter restarts there.
+ f.box = box;
+ f.shape.xy = roll;
+ f.motion = float4(0.0, 0.0, 0.0, 0.0);
+ } else {
+ // One Euro: the measured speed (centre and half width, per ms), low-passed,
+ // sets the cutoff for the position, size and roll.
+ const float3 measured = float3(box.xy - from, box.z - f.box.z) / since;
+ const float3 speed = lerp(float3(f.motion.xy, f.motion.w), measured, lowpass(tDerivativeCutoff, since));
+ const float facesPerSecond = (length(speed.xy) / width + abs(speed.z) / max(f.box.z, 1e-4)) * 1000.0;
+ const float a = lowpass(tMinCutoff + tBeta * facesPerSecond, since);
+ f.box.xy = lerp(shown, box.xy, a);
+ f.box.zw = lerp(f.box.zw, box.zw, a);
+ const float2 r = lerp(f.shape.xy, roll, a);
+ f.shape.xy = dot(r, r) > 1e-6 ? normalize(r) : roll;
+ f.motion = float4(speed.xy, 0.0, speed.z);
}
- if (jump) f.motion.xy = 0.0;
- f.box = lerp(f.box, box, alpha);
- const float2 r = lerp(f.shape.xy, roll, alpha);
- f.shape.xy = dot(r, r) > 1e-6 ? normalize(r) : roll;
- f.shape.z = score;
- f.shape.w = 1.0;
+ f.shape.z = max(score, f.shape.z * kScoreDecay);
+ f.shape.w = instant ? 1.0 : saturate(f.shape.w + dt / max(tFadeInMs, 1.0));
f.motion.z = 0.0;
f.meta.y += 1u;
+ f.meta.zw = asuint(f.box.xy);
tracks[best] = f;
matched[best] = true;
- } else if (count < min(tMaxFaces, kBeautyMaxFaces)) {
+ } else if (score >= tStartThreshold && count < min(tMaxFaces, kBeautyMaxFaces)) {
BeautyFace f;
f.box = box;
- f.shape = float4(roll, score, 1.0);
+ f.shape = float4(roll, score, instant ? 1.0 : saturate(dt / max(tFadeInMs, 1.0)));
f.motion = 0.0;
- f.meta = uint4(nextId++, 1u, 0u, 0u);
+ f.meta = uint4(nextId++, 1u, asuint(box.x), asuint(box.y));
tracks[count] = f;
matched[count] = true;
++count;
}
}
- // 3. Presence: full during the grace period after the last match, then a fade.
+ // 2. Missed faces: they keep their speed during the grace period, then fade out where they stopped.
uint kept = 0;
for (uint m = 0; m < count; ++m) {
BeautyFace f = tracks[m];
- f.shape.w = saturate(1.0 - max(f.motion.z - tGraceMs, 0.0) / max(tFadeMs, 1.0));
- if (f.motion.z > tGraceMs) f.motion.xy = 0.0;
- if (f.shape.w <= 0.0) continue;
+ if (!matched[m]) {
+ f.box.xy = predicted[m].xy;
+ if (f.motion.z > tGraceMs) f.shape.w = saturate(f.shape.w - dt / max(tFadeMs, 1.0));
+ if (f.shape.w <= 0.0) continue;
+ }
tracks[kept++] = f;
}
header.meta = uint4(kept, nextId, header.meta.z + 1u, n);
diff --git a/src/beauty/FaceTracker.cpp b/src/beauty/FaceTracker.cpp
index d6b6d6f4..bcfd5118 100644
--- a/src/beauty/FaceTracker.cpp
+++ b/src/beauty/FaceTracker.cpp
@@ -52,7 +52,7 @@ bool FaceTracker::initialize(ID3D12Device* device, const std::filesystem::path&
YuNetConfig config;
config.ringSlots = ringSlots;
config.readback = false; // the tracking pass consumes the candidates on the GPU
- config.scoreThreshold = threshold_;
+ config.scoreThreshold = keepThreshold_;
if (!detector_.initialize(device, model, config, error)) { shutdown(); return false; }
std::vector<uint8_t> cs;
if (!pipeline::loadShaderBytes("BeautyTrack.dxil", cs) ||
@@ -109,9 +109,9 @@ void FaceTracker::shutdown()
readbacks_.clear();
pending_.clear();
slots_ = 0;
- ready_ = haveFrame_ = detectedOnce_ = detectedNow_ = false;
+ ready_ = haveFrame_ = detectedNow_ = false;
lastFrameId_ = detections_ = 0;
- lastPts_ = lastDetectPts_ = 0.0;
+ lastPts_ = 0.0;
faceCount_ = candidates_ = 0;
}
@@ -119,7 +119,9 @@ void FaceTracker::configure(const engine::BeautyDetection& detection, float minC
{
detection_ = detection;
threshold_ = std::clamp(minConfidence, 0.3f, 0.95f);
- detector_.setScoreThreshold(threshold_);
+ // Hysteresis: a tracked face may dip a little below the score that starts one.
+ keepThreshold_ = std::max(0.3f, threshold_ - 0.15f);
+ detector_.setScoreThreshold(keepThreshold_);
}
bool FaceTracker::record(ID3D12GraphicsCommandList* list, pipeline::StateTracker& tracker, const Frame& f)
@@ -130,10 +132,9 @@ bool FaceTracker::record(ID3D12GraphicsCommandList* list, pipeline::StateTracker
const bool sameFrame = haveFrame_ && !f.reset && f.frameId == lastFrameId_;
double dt = 0.0;
if (haveFrame_ && !f.reset && !sameFrame) dt = std::clamp(f.ptsMs - lastPts_, 0.0, 250.0);
- const double interval = 1000.0 / std::max(detection_.rateHz(), 1.0f);
- const bool due = f.everyFrame || f.still || f.reset || !detectedOnce_ || f.ptsMs < lastDetectPts_ ||
- f.ptsMs - lastDetectPts_ >= interval - 0.5;
- const bool detect = !sameFrame && due;
+ // Every new frame is detected (about 0.3 ms at the balanced size on an RTX 5070):
+ // the faces are this frame's, so the region never trails the picture.
+ const bool detect = !sameFrame;
const double scale = double(detection_.inputLongSide()) / double(std::max(f.width, f.height));
const uint32_t width = std::clamp(uint32_t(std::lround(f.width * scale)), 32u, 640u);
const uint32_t height = std::clamp(uint32_t(std::lround(f.height * scale)), 32u, 640u);
@@ -142,20 +143,26 @@ bool FaceTracker::record(ID3D12GraphicsCommandList* list, pipeline::StateTracker
source.texture = f.source; source.width = f.width; source.height = f.height; source.hdr = f.hdr;
if (!detector_.record(list, f.slot, source, width, height)) return false;
++detections_;
- lastDetectPts_ = f.ptsMs;
- detectedOnce_ = detectedNow_ = true;
+ detectedNow_ = true;
}
uint32_t c[kTrackConstants]{};
c[0] = width; c[1] = height; c[2] = detector_.candidateCapacity();
c[3] = (detect ? 1u : 0u) | (f.reset ? 2u : 0u) | (f.still ? 4u : 0u);
c[4] = bitsOf(float(dt));
- c[5] = bitsOf(1.0f - 0.8f * detection_.stability);
+ // One Euro smoothing (shaders/BeautyTrack.hlsl): the stability sets the cutoff of a
+ // face at rest (3 -> 0.3 Hz) and how fast it rises with speed (20 -> 6 Hz per face
+ // width per second); tuned in docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md.
+ const float stability = std::clamp(detection_.stability, 0.0f, 1.0f);
+ c[5] = bitsOf(3.0f + (0.3f - 3.0f) * stability);
c[6] = bitsOf(0.3f);
- // Between detections a face is kept a little longer than one detection interval.
- c[7] = bitsOf(float(std::max(50.0, (f.everyFrame || f.still ? 1000.0 / 60.0 : interval) * 1.5)));
- c[8] = bitsOf(150.0f);
+ c[7] = bitsOf(120.0f); // a missed face keeps moving this long
+ c[8] = bitsOf(120.0f); // then fades out over this long
c[9] = detection_.maxFaces;
- c[10] = bitsOf(threshold_);
+ c[10] = bitsOf(keepThreshold_);
+ c[11] = bitsOf(20.0f + (6.0f - 20.0f) * stability);
+ c[12] = bitsOf(4.0f); // speed estimate cutoff, Hz
+ c[13] = bitsOf(80.0f); // a new face fades in over this long
+ c[14] = bitsOf(threshold_);
tracker.transition(list, faces_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const auto gpu = [&](UINT index) { return track_.heap->GetGPUDescriptorHandleForHeapStart().ptr + UINT64(index) * track_.increment; };
track_.bind(list, reinterpret_cast<const float*>(c), gpu(f.slot * kDescriptorsPerSlot), gpu(f.slot * kDescriptorsPerSlot + 1));
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 2e894fc6..847a9bf7 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -2474,7 +2474,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
beauty::FaceTracker::Frame frameFaces;
frameFaces.source=faces;frameFaces.width=srcW_;frameFaces.height=srcH_;frameFaces.hdr=desc_.hdrWorking();
frameFaces.slot=slot;frameFaces.frameId=sourceFrameId;frameFaces.ptsMs=ptsMs;frameFaces.reset=reset;
- frameFaces.still=desc_.stillImage;frameFaces.everyFrame=desc_.beautyDetectEveryFrame;
+ frameFaces.still=desc_.stillImage;
if(!faceTracker_->record(list,tracker_,frameFaces)){
if(!beautyDetectFailureLogged_)veyra::log::error("beauty-detect","face tracking could not be recorded; beauty nodes keep the last faces");
beautyDetectFailureLogged_=true;
diff --git a/tests/integration/BeautyGpuTests.cpp b/tests/integration/BeautyGpuTests.cpp
index 2c03c43c..224fb77b 100644
--- a/tests/integration/BeautyGpuTests.cpp
+++ b/tests/integration/BeautyGpuTests.cpp
@@ -604,8 +604,8 @@ int trackingCase() {
std::printf("METRIC case=tracking frames=%d detections=%llu worstCentreErrorPx=%.2f faceWidthPx=%.1f\n", frames,
(unsigned long long)detections, worst, p.faces.empty() ? 0.0 : p.faces[0].w);
check(ok, "tracking: the face is tracked on every frame");
- check(detections >= 10 && detections <= 16, "tracking: balanced detection runs at about 15 Hz of a 60 fps video");
- check(ok && worst < 0.08 * p.faces[0].w, "tracking: the tracked centre stays within 8% of the face width of the moving face");
+ check(detections == uint64_t(frames), "tracking: every frame of the video is detected");
+ check(ok && worst < 0.03 * p.faces[0].w, "tracking: the tracked centre stays within 3% of the face width of the moving face");
// A reset (seek) detects on the very next frame.
AVFrame* frame = rgbaFrame(p.image);
sink::RgbaImage out;
@@ -616,6 +616,61 @@ int trackingCase() {
return finish(*gpu, "tracking");
}
+// A face that rests, crosses the picture fast (16 px a frame at 60 fps, about six face
+// widths a second) and stops. The tracked centre has to follow within a few percent of
+// the face width and must not overshoot where the face stops: the 15 Hz predicting
+// filter this replaces trailed by more than half a face and overshot by as much.
+int trackingMotionCase() {
+ Picture p;
+ check(loadPicture("lena", p), "tracking-motion: picture and reference faces");
+ const unsigned width = 1280, height = 640, x0 = 64, y0 = 64;
+ sink::RgbaImage canvas; canvas.width = width; canvas.height = height; canvas.pixels.assign(size_t(width) * height * 4, 96);
+ for (size_t i = 3; i < canvas.pixels.size(); i += 4) canvas.pixels[i] = 255;
+ for (unsigned y = 0; y < p.image.height && y0 + y < height; ++y)
+ std::memcpy(canvas.pixels.data() + (size_t(y0 + y) * width + x0) * 4, p.image.pixels.data() + size_t(y) * p.image.width * 4,
+ size_t(p.image.width) * 4);
+ auto gpu = std::make_unique<Gpu>();
+ auto settings = withBeauty(restoreNode(1.0f));
+ settings.beautyDetection.quality = 2;
+ settings.beautyDetection.stability = 0.5f;
+ bool ok = gpu->start(settings, width, height, false, false);
+ check(ok, "tracking-motion: video-timed graph runs");
+ const int rest = 12, move = 30, after = 30, speed = 16;
+ std::vector<double> error; // tracked centre minus the true one, pixels
+ std::vector<float> faces;
+ const double reference = p.faces[0].x + p.faces[0].w / 2 + x0;
+ for (int i = 0; ok && i < rest + move + after; ++i) {
+ const int dx = std::clamp(i - rest, 0, move) * speed;
+ AVFrame* frame = rgbaFrame(shifted(canvas, dx, 0));
+ sink::RgbaImage out;
+ ok = frame && gpu->render(frame, i == 0, out) && gpu->readFaces(faces) && trackedCount(faces) >= 1;
+ av_frame_free(&frame);
+ if (ok) error.push_back(double(faces[16]) * width - (reference + dx));
+ }
+ check(ok, "tracking-motion: the face is tracked on every frame");
+ if (!ok) return finish(*gpu, "tracking-motion");
+ // The detector's own offset at this size, measured at rest, is not tracking error.
+ double bias = 0;
+ for (int i = 4; i < rest; ++i) bias += error[i];
+ bias /= double(rest - 4);
+ double lag = 0, overshoot = 0, settled = -1;
+ for (int i = rest + 4; i < rest + move; ++i) lag = std::max(lag, -(error[i] - bias));
+ for (int i = rest + move; i < rest + move + after; ++i) overshoot = std::max(overshoot, error[i] - bias);
+ for (int i = rest + move; i < rest + move + after; ++i) {
+ bool calm = true;
+ for (int k = i; k < rest + move + after; ++k) calm = calm && std::abs(error[k] - bias) < 0.015 * p.faces[0].w;
+ if (calm) { settled = i - (rest + move); break; }
+ }
+ const double w = p.faces[0].w;
+ std::printf("METRIC case=tracking-motion faceWidthPx=%.1f speedPxPerFrame=%d detections=%llu lagFaceWidths=%.4f overshootFaceWidths=%.4f "
+ "settleFrames=%.0f\n", w, speed, (unsigned long long)gpu->graph->beautyDetections(), lag / w, overshoot / w, settled);
+ check(gpu->graph->beautyDetections() == uint64_t(rest + move + after), "tracking-motion: every frame is detected");
+ check(lag < 0.06 * w, "tracking-motion: a fast face is followed within 6% of its width");
+ check(overshoot < 0.025 * w, "tracking-motion: the region does not overshoot where the face stops");
+ check(settled >= 0 && settled <= 8, "tracking-motion: the region settles within 8 frames of the stop");
+ return finish(*gpu, "tracking-motion");
+}
+
int noModelCase() {
Picture p;
check(loadPicture("lena", p), "no-model: picture");
@@ -741,6 +796,7 @@ std::vector<Case> cases() {
c.push_back({"two-nodes", [] { return twoNodeCase(); }});
c.push_back({"hdr", [] { return hdrCase(); }});
c.push_back({"tracking", [] { return trackingCase(); }});
+ c.push_back({"tracking-motion", [] { return trackingMotionCase(); }});
c.push_back({"no-model", [] { return noModelCase(); }});
c.push_back({"tune", [] { return tuneCase(); }});
c.push_back({"timing-1080p", [] { return timingCase("timing-1080p", 1920, 1080); }});
diff --git a/tests/unit/EffectChainTests.cpp b/tests/unit/EffectChainTests.cpp
index 4c0caab9..78a97b25 100644
--- a/tests/unit/EffectChainTests.cpp
+++ b/tests/unit/EffectChainTests.cpp
@@ -1222,7 +1222,7 @@ __declspec(noinline) void testBeautySettingsChain() {
refused([](BeautySettings& v) { v.restoreStrength = std::nanf(""); }),
"beauty: out-of-range values are refused");
BeautyDetection d;
- check(d.validate().empty() && d.inputLongSide() == 512 && d.rateHz() == 15.0f, "beauty: balanced detection by default");
+ check(d.validate().empty() && d.inputLongSide() == 512, "beauty: balanced detection by default");
d.maxFaces = 0; check(!d.validate().empty(), "beauty: a detector needs at least one face");
// Sub-functions are independent: strength 0 skips only the smoothing.
b.enabled = true; b.restore = true; b.smooth = true; b.strength = 0.0f;
@@ -1268,12 +1268,12 @@ __declspec(noinline) void testBeautySettingsChain() {
"beauty: NR-first preview runs the group between NR and SR");
StageRequest still = request; still.stillImage = true; still.sr = false;
describeStages(still, *s, *desc);
- check(desc->beautyDetectEveryFrame && !desc->beautyRequireDetector, "beauty: a picture is detected on its own frame");
+ check(!desc->beautyRequireDetector, "beauty: a picture runs without requiring the detector");
StageRequest exportJob = request; exportJob.exportJob = true;
auto masked = std::make_unique<EnhancementSettings>(*s); masked->beauty.showMask = true;
describeStages(exportJob, *masked, *desc);
- check(desc->beautyRequireDetector && desc->beautyDetectEveryFrame && !desc->beauty[0].showMask,
- "beauty: export needs the detector, detects every frame and never writes the mask view");
+ check(desc->beautyRequireDetector && !desc->beauty[0].showMask,
+ "beauty: export needs the detector and never writes the mask view");
// Only the master switch (and the instance count) rebuilds; every value is live.
auto live = std::make_unique<EnhancementSettings>(*s);