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: MediaPipe 468-point face mesh for real face contours and feature exclusion

Veyra Goal Agent2019128b8052
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 4be62244..503f4572 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -5,12 +5,13 @@
| Source | License | Veyra use |
|---|---|---|
| YuNet face detector, OpenCV Zoo `models/face_detection_yunet` at `47534e27`: `face_detection_yunet_2023mar.onnx` (232,589 bytes, SHA256 `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4`) and `face_detection_yunet_2026may.onnx` (229,738 bytes, SHA256 `ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0`); hashes match the Git LFS pointer oids | MIT, Copyright (c) 2020 Shiqi Yu | Weights only, loaded at run time from `runtime/models`, `runtime_local/models` or `models` next to the program; never in source Git. The network runs as Veyra's own D3D12 compute shaders (`shaders/BeautyYuNet*.hlsl`, `src/beauty/YuNetGpu.cpp`); `src/beauty/OnnxLite.cpp` reads the ONNX file. |
+| MediaPipe face landmark model, google-ai-edge/mediapipe tag `v0.8.9`, `mediapipe/modules/face_landmark/face_landmark.tflite` (1,241,896 bytes, SHA256 `c603fa6149219a3e9487dc9abd7a0c24474c77263273d24868378cdf40aa26d1`, committed in the repository at that tag), and the outline index lists of `mediapipe/python/solutions/face_mesh_connections.py` | Apache-2.0 (the repository's license, LICENSE SHA256 `c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4`) | 468 face points per tracked face: weights only, loaded at run time from the same model folders as YuNet, never in source Git; read by `src/beauty/TfliteLite.cpp` and run as Veyra's own D3D12 compute shaders (`shaders/BeautyMesh*.hlsl`, `src/beauty/FaceMeshGpu.cpp`). The contour, eye, brow and lip index lists are copied into `shaders/BeautyMeshDecode.hlsl` and the tests |
| SkinSoft, yasunari01/obs-filters `fd5690f`, `skinsoft-filter/data/effects/skinsoft.effect` | GPL-2.0-or-later | Skin selection (HSV hue distance, saturation / luma windows, shared softness), detail protection and texture restore, ported to `shaders/Beauty.hlsli` and `shaders/BeautyApply.hlsl` |
| GPUPixel, pixpark/gpupixel `ef552bf`, `BeautyFaceUnitFilter` | Apache-2.0 | The variance-adaptive skin blend, re-implemented as a fast guided filter (He & Sun 2015) in `shaders/BeautyStats.hlsl` / `BeautyBlur.hlsl`; no GPUPixel source or binary is included |
-| OpenCV 5.0.0 `FaceDetectorYN` | Apache-2.0 | Test references only (`scripts/beauty/yunet-reference.py` writes the expected detector outputs); `shaders/BeautyTrack.hlsl` follows its non-maximum suppression rules (whole-pixel boxes, score order, IoU). OpenCV is neither linked nor shipped |
+| OpenCV 5.0.0 `FaceDetectorYN`, `dnn.readNetFromTFLite` | Apache-2.0 | Test references only (`scripts/beauty/yunet-reference.py` and `facemesh-reference.py` write the expected detector and face mesh outputs); `shaders/BeautyTrack.hlsl` follows its non-maximum suppression rules (whole-pixel boxes, score order, IoU). OpenCV is neither linked nor shipped |
-Veyra changes: the detector, the GPU face tracking (stable ids, alpha-beta
-filter, grace and fade), the same-frame original restore, the region pass with
+Veyra changes: the detector, the face mesh crop / network / outlines, the GPU face
+tracking (stable ids, One Euro smoothing, grace and fade), the same-frame original restore, the region pass with
indirect dispatch and every UI / preset / export connection are Veyra's own.
Smoothing works on a perceptual copy relative to the SDR or 203-nit HDR white
and blends back in linear light; SkinSoft's sparse 9-tap blur is replaced by the
diff --git a/cmake/VeyraBeauty.cmake b/cmake/VeyraBeauty.cmake
index 4f7e37e3..938608c4 100644
--- a/cmake/VeyraBeauty.cmake
+++ b/cmake/VeyraBeauty.cmake
@@ -2,13 +2,16 @@
# Included from the FFmpeg-gated block of CMakeLists.txt, after veyra_pipeline /
# veyra_sinks / veyra_engine exist.
#
-# Sources: YuNet (OpenCV Zoo 47534e27, MIT; the weights load from a file at run
-# time and never enter the tree), SkinSoft (yasunari01/obs-filters fd5690f,
+# Sources: YuNet (OpenCV Zoo 47534e27, MIT) and the MediaPipe face landmark model
+# (v0.8.9, Apache-2.0) - both load from files at run time and never enter the tree -,
+# SkinSoft (yasunari01/obs-filters fd5690f,
# GPL-2.0-or-later) and GPUPixel (pixpark/gpupixel ef552bf, Apache-2.0). Details
# per file: THIRD_PARTY_NOTICES.md.
target_sources(veyra_pipeline PRIVATE
src/beauty/OnnxLite.cpp
+ src/beauty/TfliteLite.cpp
src/beauty/YuNetGpu.cpp
+ src/beauty/FaceMeshGpu.cpp
src/beauty/FaceTracker.cpp
src/pipeline/BeautyPass.cpp)
foreach(kernel Prep Stem Pointwise Depthwise Pool UpAdd Decode)
@@ -16,6 +19,12 @@ foreach(kernel Prep Stem Pointwise Depthwise Pool UpAdd Decode)
veyra_add_compute_shader(veyra_shader_beauty_yunet_${lower} BeautyYuNet${kernel})
add_dependencies(veyra_pipeline veyra_shader_beauty_yunet_${lower})
endforeach()
+# Face mesh: crop, network layers, outlines.
+foreach(kernel Crop Conv Depthwise Pointwise Decode)
+ string(TOLOWER "${kernel}" lower)
+ veyra_add_compute_shader(veyra_shader_beauty_mesh_${lower} BeautyMesh${kernel})
+ add_dependencies(veyra_pipeline veyra_shader_beauty_mesh_${lower})
+endforeach()
# Face tracking and the node passes (region, statistics, blur, apply).
foreach(stage Track Roi Stats Blur Apply)
string(TOLOWER "${stage}" lower)
diff --git a/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md b/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md
index 30c6e72f..0d924a73 100644
--- a/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md
+++ b/docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md
@@ -30,6 +30,7 @@
| 设置、校验、预设编码 | `include/veyra/engine/BeautySettings.h`;`EnhancementSettings`、`EffectChain`(`toChain`/`fromChain`/节点顺序)、`GraphDescription`、`ExportFeaturePolicy` |
| 存储 | 预设库 v15、链会话 v10,写入独立的 `.beauty` 文件,旧文件逐字节不变;导出协议 11 |
| 人脸检测 | `src/beauty/OnnxLite.cpp`(只读解析 ONNX 权重)、`src/beauty/YuNetGpu.cpp` + `shaders/BeautyYuNet*.hlsl`(YuNet 全网络手写 D3D12 compute) |
+| 人脸网格 | `src/beauty/TfliteLite.cpp`(只读解析 TFLite)、`src/beauty/FaceMeshGpu.cpp` + `shaders/BeautyMesh*.hlsl`(MediaPipe 468 点网络、裁剪、轮廓输出),见第 8 节 |
| 跟踪 | `src/beauty/FaceTracker.cpp` + `shaders/BeautyTrack.hlsl`:GPU 上 NMS(与 OpenCV FaceDetectorYN 相同的整像素框规则)、α-β 滤波、稳定 id、丢失后宽限再淡出;画面路径不回读,只每槽读回 64 字节计数头给界面 |
| 节点 | `src/pipeline/BeautyPass.cpp` + `shaders/Beauty{Roi,Stats,Blur,Apply}.hlsl`、`Beauty.hlsli`、`BeautyFaces.hlsli` |
| 图 | `EnhanceGraph`:E0 插入槽(源尺寸 SourcePost、PreSr、PreNr、链尾 Tail),`bindSlotPassInput` 同时修正 NR 旁路时只重绑调色的问题 |
@@ -115,3 +116,34 @@ Codex 预算为 1080p 平均 ≤1 ms / P95 ≤2 ms、4K 平均 ≤2.5 ms / P95
新增 `tracking-motion`(每帧 16 px,约 6.6 脸宽/秒,停下)落后 1.5% 脸宽、过冲 0.25%、停下当帧即稳定。
每帧识别的成本即原先“识别帧”的成本:1080p 约 0.43 ms、4K 约 0.52 ms(节点 + 识别,一张脸,来自之前的计时;
本轮用户的测试程序在运行,没有重新计时)。
+
+## 8. 人脸网格:真实脸型轮廓与五官排除(2026-10-19)
+
+用户试用后指出遮罩只是一个椭圆。原因:YuNet 只给人脸框和 5 个点,遮罩只能由框推一个椭圆,原画保护会把头发、帽檐、背景一起
+恢复,磨皮也只能靠肤色和细节保护避开五官(嘴唇颜色接近肤色,常被磨到)。按用户同意改用 MediaPipe 468 点人脸网格:
+
+- 模型:`face_landmark.tflite`(MediaPipe v0.8.9 仓库内文件,Apache-2.0,SHA256 `c603fa61…26d1`),与 YuNet 一样运行时从
+ 模型目录加载、不进源码库;`TfliteLite` 读取(fp16 权重展开、DEQUANTIZE 折叠,不认识的一律拒绝)。
+- 网络:97 个算子融合成 45 个 GPU 层(逐点卷积带残差 / 最大池化 + 通道补零 / PReLU 融合),全部人脸一次批处理;裁剪按
+ MediaPipe:以跟踪框为中心、眼线放平、边长为框长边的 1.44 倍(MediaPipe 对其检测框用 1.5 倍;48 张参考脸上 YuNet 框
+ 换算出的裁剪是 MediaPipe 跟踪裁剪的 1/0.96,取中位数校准),192×192、显示编码 0…1、双线性复制边缘。
+- 输出:468 点映射回画面,按轨迹 id 做 One Euro 平滑(与人脸跟踪同参数),取出轮廓 36 点、外唇 20 点、双眼各 16 点、
+ 双眉各 10 点。网格分数 logit > −4(保持 > −5.5)且轮廓与检测框一致(中心偏差 < 0.35 脸宽、宽度 0.6…1.8 倍)才使用,
+ 否则该脸回退到椭圆。
+- 遮罩:原画保护 = 轮廓按“区域扩展”外扩、按“边缘羽化”柔化;磨皮 = 轮廓外扩 10% × 肤色 ×(1 − 五官),五官 = 双眼、
+ 双眉、嘴唇外扩 2% 脸宽、4% 柔边;全部肤色模式同样排除检测到的五官。每像素每张脸只算一次轮廓距离。
+- 成本控制:跟踪状态连续报告无人脸时不跑网格(轮廓清空一次),新出现的人脸在淡入的头几帧用椭圆。
+
+实测(RTX 5070):
+- 网络与参考(OpenCV TFLite + 按 TensorFlow 规则的 numpy 实现,两者互差 1e-4)在 62 张脸上一致:坐标最大差 0.00014 裁剪像素、
+ 分数最大差 0.00002;D3D12 调试层无错误。
+- 图中实测(`mesh-landmarks`):lena / astronaut / 两张 GTA 帧的轮廓点与参考平均差 0.4–0.8% 脸宽,最大 2.3%。
+- `mesh-contour`:调色下全强度保护,轮廓内 20071 像素逐位等于原画,轮廓外 227172 像素逐位保持调色;原椭圆会覆盖、轮廓外的
+ 2787 像素(头发、帽檐)不再被恢复。
+- `mesh-features`:强档磨皮下双眼、双眉、嘴唇内部 608 像素逐位不变,皮肤细纹理仍降 21.4%。
+- 原有 15 个用例全部通过。耗时(节点中位数 + 识别/跟踪/网格均值):1080p 一张脸 0.148 + 0.783 ≈ 0.93 ms,四张脸
+ 0.139 + 0.913 ms,无脸 0.033 + 0.427 ms;4K 一张脸 0.556 + 0.868 ≈ 1.42 ms。均在预算内(1080p 平均 ≤1 ms 已接近上限)。
+
+限制:侧脸、低头、远处小脸常被网格分数否决,回退到椭圆(人群图 62 张脸中 48 张可用);网格本身约 0.3 ms 固定开销来自约 45 次
+小调度,后续可把 6×6 以下各层合并成一次调度;没有虹膜点;新出现的人脸头几帧是椭圆。
+
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index b50b414b..7d8bd36e 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -9751,3 +9751,4 @@ Branch claude/aa-53-20261017 from main 26c0d61. Archive E:/项目/Veyra/archives
- 最终汇总(`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 节。
+- 10-19 用户反馈遮罩只是椭圆:按同意接入 MediaPipe 468 点人脸网格(v0.8.9,Apache-2.0,自写 TFLite 读取 + 45 个 GPU 层),原画保护按真实轮廓、磨皮排除双眼双眉嘴唇;网络与参考 62 张脸一致(最大差 0.00014 裁剪像素),新增 `mesh-landmarks` / `mesh-contour` / `mesh-features`;1080p 一张脸约 0.93 ms、4K 约 1.42 ms。详见实施文档第 8 节。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 5d0fbf68..b75c509b 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -3207,11 +3207,11 @@
"ja": "顔のオリジナル保護"
},
{
- "zh": "人脸原画保护:在识别到的人脸里混回本帧原画(没有经过任何效果)。磨皮:柔化皮肤,保留眼睛、睫毛和嘴唇的细节。两项可分别开关。",
+ "zh": "人脸原画保护:按人脸轮廓混回本帧原画(没有经过任何效果)。磨皮:柔化皮肤,眼睛、眉毛和嘴唇不参与。两项可分别开关。",
"src": "qml/BeautyEditor.qml",
- "zh-TW": "人臉原畫保護:在識別到的人臉裡混回本幀原畫(沒有經過任何效果)。磨皮:柔化皮膚,保留眼睛、睫毛和嘴唇的細節。兩項可分別開關。",
- "en": "Original face restore: blends this frame's original (before any effect) back into the detected faces. Skin smoothing: softens skin and keeps the detail of eyes, lashes and lips. Each can be switched on its own.",
- "ja": "顔のオリジナル保護:検出した顔の中に、このフレームの元の画像(どの効果も通す前)を戻して合成します。美肌:目・まつ毛・唇のディテールを残したまま肌をなめらかにします。それぞれ個別にオン/オフできます。"
+ "zh-TW": "人臉原畫保護:按人臉輪廓混回本幀原畫(沒有經過任何效果)。磨皮:柔化皮膚,眼睛、眉毛和嘴唇不參與。兩項可分別開關。",
+ "en": "Original face restore: blends this frame's original (before any effect) back in along the face outline. Skin smoothing: softens skin and leaves the eyes, brows and lips out. Each can be switched on its own.",
+ "ja": "顔のオリジナル保護:顔の輪郭に沿って、このフレームの元の画像(どの効果も通す前)を戻して合成します。美肌:肌をなめらかにし、目・眉・唇は対象外です。それぞれ個別にオン/オフできます。"
},
{
"zh": "人脸置信度",
@@ -12889,6 +12889,13 @@
"en": "Beauty: the face model file is missing; original face restore and face-area beauty are not applied",
"ja": "美顔:顔モデルファイルがないため、顔のオリジナル保護と顔の範囲の美顔は適用されません"
},
+ {
+ "zh": "美颜:人脸网格模型缺失,人脸区域按椭圆近似,五官不单独排除",
+ "src": "src/pipeline/EnhanceGraph.cpp",
+ "zh-TW": "美顏:人臉網格模型缺失,人臉區域按橢圓近似,五官不單獨排除",
+ "en": "Beauty: the face mesh model is missing; face areas are approximated by ovals and the eyes, brows and lips are not left out",
+ "ja": "美顔:顔メッシュモデルがないため、顔の範囲は楕円で近似され、目・眉・唇は除外されません"
+ },
{
"zh": "美颜:人脸识别初始化失败,人脸原画保护与人脸区域美颜暂不生效",
"src": "src/pipeline/EnhanceGraph.cpp",
diff --git a/include/veyra/beauty/FaceMeshGpu.h b/include/veyra/beauty/FaceMeshGpu.h
new file mode 100644
index 00000000..f65f3f12
--- /dev/null
+++ b/include/veyra/beauty/FaceMeshGpu.h
@@ -0,0 +1,72 @@
+#pragma once
+#include <d3d12.h>
+
+#include <cstdint>
+#include <filesystem>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace veyra::pipeline { class StateTracker; }
+
+namespace veyra::beauty {
+
+// The shipped face mesh model: MediaPipe face_landmark (468 points, v0.8.9, Apache-2.0).
+// Like the detector model it never enters the source tree; the same folders are searched
+// (runtime/models, runtime_local/models, models next to the executable). Empty when absent.
+std::filesystem::path locateFaceMeshModel();
+
+// MediaPipe's face landmark network as D3D12 compute kernels. For every face the
+// tracker keeps (shaders/BeautyTrack.hlsl) it crops the frame around the face, runs
+// the network for all faces at once and turns the 468 points into the outlines the
+// node passes mask with: the face contour, the eyes, the brows and the lips
+// (shaders/BeautyFaces.hlsli kShape*). The network is read from the TFLite file at
+// run time and fused into about fifty layers (stem, depthwise 3x3, 1x1 with the
+// block's residual and PReLU, heads). Everything is recorded into the caller's
+// command list; nothing is read back.
+class FaceMeshGpu {
+public:
+ struct Frame {
+ ID3D12Resource* source = nullptr; // linear RGBA16F / RGBA32F picture, non-pixel SRV
+ uint32_t width = 0, height = 0;
+ bool hdr = false; // scRGB working space
+ uint32_t slot = 0; // command ring slot of the list
+ uint32_t maxFaces = 8; // tracks to process (the max faces setting)
+ float dtMs = 0.0f; // time since the previous recorded frame
+ bool reset = false, still = false; // the points start without history
+ float restCutoff = 1.65f, speedFactor = 13.0f, speedCutoff = 4.0f; // One Euro, as the tracks
+ };
+
+ FaceMeshGpu();
+ ~FaceMeshGpu();
+ FaceMeshGpu(const FaceMeshGpu&) = delete;
+ FaceMeshGpu& operator=(const FaceMeshGpu&) = delete;
+
+ // `faces`: the tracker's faces buffer (structured, 64-byte entries, read as SRV);
+ // `shapes`: the outline buffer this writes (kShapeEntries float2 per face slot).
+ bool initialize(ID3D12Device* device, const std::filesystem::path& model, ID3D12Resource* faces, ID3D12Resource* shapes,
+ uint32_t ringSlots, std::string& error);
+ void shutdown();
+ bool ready() const;
+ const std::string& description() const;
+ // Crop, network and outlines for this frame's tracks; the faces buffer must be in the
+ // non-pixel SRV state. Leaves the outlines in the non-pixel SRV state.
+ bool record(ID3D12GraphicsCommandList* list, pipeline::StateTracker& tracker, const Frame& frame);
+ // Test hook, synchronous on `queue`: the network alone on `count` crops (192 x 192 x 3
+ // RGB 0..1, NHWC, one after the other); `output` gets count x (1404 landmark values,
+ // then the face flag logit).
+ bool runNetwork(ID3D12CommandQueue* queue, const std::vector<float>& input, uint32_t count, std::vector<float>& output, std::string& error);
+
+ static constexpr uint32_t kInputSize = 192, kLandmarks = 468, kShapeEntries = 128, kMaxFaces = 8;
+ static constexpr uint64_t kShapeBytes = uint64_t(kMaxFaces) * kShapeEntries * 8;
+ // Crop side over the face box's long side: MediaPipe crops 1.5x its detector's box;
+ // YuNet's box is a little larger (the crop MediaPipe's tracking would take from the
+ // points is 0.96 of ours, median of 48 reference faces).
+ static constexpr float kCropScale = 1.44f;
+
+private:
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+};
+
+} // namespace veyra::beauty
diff --git a/include/veyra/beauty/FaceTracker.h b/include/veyra/beauty/FaceTracker.h
index 11ed27d8..26425b5e 100644
--- a/include/veyra/beauty/FaceTracker.h
+++ b/include/veyra/beauty/FaceTracker.h
@@ -1,4 +1,5 @@
#pragma once
+#include "veyra/beauty/FaceMeshGpu.h"
#include "veyra/beauty/YuNetGpu.h"
#include "veyra/engine/BeautySettings.h"
#include "veyra/pipeline/GpuPassUtils.h"
@@ -14,7 +15,8 @@ namespace veyra::beauty {
std::filesystem::path locateFaceModel();
// 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).
+// before any effect, followed by the GPU tracking pass (shaders/BeautyTrack.hlsl)
+// and the face mesh of every track (FaceMeshGpu: contour, eyes, brows, lips).
// 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.
@@ -39,6 +41,10 @@ public:
// 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);
ID3D12Resource* faces() const { return faces_.Get(); }
+ // Face outlines (FaceMeshGpu layout); all "no mesh" when the mesh model is missing.
+ ID3D12Resource* shapes() const { return shapes_.Get(); }
+ bool meshReady() const { return meshReady_; }
+ const std::string& meshDescription() const { return mesh_.description(); }
// Reads the status this slot carried last time (its fence has completed when the ring hands the slot out).
void collect(uint32_t slot);
uint32_t faceCount() const { return faceCount_; }
@@ -50,6 +56,9 @@ public:
private:
YuNetGpu detector_;
+ FaceMeshGpu mesh_;
+ pipeline::ComPtr<ID3D12Resource> shapes_, shapesClear_;
+ bool meshReady_ = false, meshCleared_ = false;
pipeline::ComputePass track_;
pipeline::ComPtr<ID3D12DescriptorHeap> staging_;
pipeline::ComPtr<ID3D12Resource> faces_;
diff --git a/include/veyra/beauty/TfliteLite.h b/include/veyra/beauty/TfliteLite.h
new file mode 100644
index 00000000..1cd635b8
--- /dev/null
+++ b/include/veyra/beauty/TfliteLite.h
@@ -0,0 +1,53 @@
+#pragma once
+#include <cstdint>
+#include <filesystem>
+#include <string>
+#include <vector>
+
+namespace veyra::beauty {
+
+// A deliberately small TFLite reader: just enough of the flatbuffer schema to read
+// a compact float CNN (tensors with their constant data, the builtin operators of
+// such a network with their convolution / pooling options, graph inputs and
+// outputs). Float16 constants are widened to float32 and DEQUANTIZE operators on
+// constants are folded away. Anything it does not understand is rejected with a
+// message, never guessed. Used by the face mesh to read the model file that ships
+// next to the program (the model is never part of the source tree).
+struct TfliteTensor {
+ std::string name;
+ std::vector<int32_t> shape;
+ int32_t type = 0; // TensorType: 0 float32, 1 float16, 2 int32
+ std::vector<float> floats; // float constants (widened); empty for activations
+ std::vector<int32_t> ints; // int32 constants (paddings)
+ bool constant() const { return !floats.empty() || !ints.empty(); }
+ size_t elementCount() const
+ {
+ size_t n = 1;
+ for (const auto d : shape) n *= size_t(d < 0 ? 0 : d);
+ return n;
+ }
+};
+
+enum class TfliteOp : int32_t { Add = 0, Conv2D = 3, DepthwiseConv2D = 4, Dequantize = 6, MaxPool2D = 17, Pad = 34, Prelu = 54 };
+
+struct TfliteOperator {
+ TfliteOp op = TfliteOp::Add;
+ std::vector<int32_t> inputs, outputs; // tensor indices, -1 = optional input left out
+ bool samePadding = true;
+ int32_t strideW = 1, strideH = 1;
+ int32_t filterW = 0, filterH = 0; // pooling
+ int32_t depthMultiplier = 1;
+ int32_t dilationW = 1, dilationH = 1;
+ int32_t activation = 0; // fused activation: 0 none
+};
+
+struct TfliteModel {
+ uint32_t version = 0;
+ std::vector<TfliteTensor> tensors;
+ std::vector<TfliteOperator> operators; // constant DEQUANTIZE operators are folded away
+ std::vector<int32_t> inputs, outputs;
+};
+
+bool loadTflite(const std::filesystem::path& path, TfliteModel& model, std::string& error);
+
+} // namespace veyra::beauty
diff --git a/include/veyra/pipeline/BeautyPass.h b/include/veyra/pipeline/BeautyPass.h
index 81fc2409..756a8e1a 100644
--- a/include/veyra/pipeline/BeautyPass.h
+++ b/include/veyra/pipeline/BeautyPass.h
@@ -21,7 +21,7 @@ public:
uint32_t sourceWidth, uint32_t sourceHeight);
void refresh(const engine::BeautySettings& settings) { settings_ = settings; }
void createViews(ID3D12Device* device, DescriptorStager& stager, ID3D12Resource* input, ID3D12Resource* output,
- ID3D12Resource* original, ID3D12Resource* faces);
+ ID3D12Resource* original, ID3D12Resource* faces, ID3D12Resource* shapes);
// `originalValid`: the original texture holds this frame (face restore needs it).
bool dispatch(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool hdrWorking, bool originalValid);
const engine::BeautySettings& settings() const { return settings_; }
@@ -42,5 +42,6 @@ private:
ID3D12Resource* output_ = nullptr;
ID3D12Resource* original_ = nullptr;
ID3D12Resource* faces_ = nullptr;
+ ID3D12Resource* shapes_ = nullptr;
};
}
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 27440001..d84e8c18 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -732,6 +732,8 @@ public:
uint64_t beautyDetections() const { return faceTracker_?faceTracker_->detections():0; }
// Tests: the tracked faces (non-pixel SRV state between frames).
ID3D12Resource* beautyFacesBuffer() const { return beautyNodesActive_?beautyFaces():nullptr; }
+ ID3D12Resource* beautyShapesBuffer() const { return beautyNodesActive_?beautyShapes():nullptr; }
+ bool beautyMeshReady() const { return faceTracker_&&faceTracker_->meshReady(); }
// True when the colour stage exists in this graph (master switch on and not
// neutral). The encoder uses it to dither its 8/10-bit conversion output.
bool colorGradeActive() const { return colorActive_||additionalColorActiveCount_!=0||tailColorActiveCount_!=0||preNrColorActiveCount_!=0||preSrColorActiveCount_!=0||interNrColorActiveCount_!=0||sourcePostColorActiveCount_!=0; }
@@ -945,6 +947,7 @@ private:
bool createBeauty(uint32_t parameter,uint32_t width,uint32_t height);
bool createBeautyShared();
ID3D12Resource* beautyFaces() const { return faceTracker_&&faceTracker_->ready()?faceTracker_->faces():beautyFacesFallback_.Get(); }
+ ID3D12Resource* beautyShapes() const { return faceTracker_&&faceTracker_->ready()?faceTracker_->shapes():beautyShapesFallback_.Get(); }
bool beautyRestoreRequested() const {
for(const auto& b:desc_.beauty)if(b.restoreActive())return true;
return false;
@@ -957,7 +960,7 @@ private:
// Re-points one slot pass at a new input (chainSlotViews, NR bypass).
void bindSlotPassInput(const SlotPass& pass,ID3D12Resource* input);
std::unique_ptr<beauty::FaceTracker> faceTracker_;
- ComPtr<ID3D12Resource> beautyOriginal_,beautyFacesFallback_;
+ ComPtr<ID3D12Resource> beautyOriginal_,beautyFacesFallback_,beautyShapesFallback_;
ID3D12Resource* beautyOriginalSource_=nullptr;
bool beautyNodesActive_=false,beautyOriginalValid_=false,beautyDetectFailureLogged_=false;
std::wstring beautyNotice_;
diff --git a/qml/Veyra/BeautyEditor.qml b/qml/Veyra/BeautyEditor.qml
index f896e83e..69a31aeb 100644
--- a/qml/Veyra/BeautyEditor.qml
+++ b/qml/Veyra/BeautyEditor.qml
@@ -57,7 +57,7 @@ ColumnLayout {
spacing: 6
Text {
Layout.fillWidth: true
- text: qsTr("人脸原画保护:在识别到的人脸里混回本帧原画(没有经过任何效果)。磨皮:柔化皮肤,保留眼睛、睫毛和嘴唇的细节。两项可分别开关。")
+ text: qsTr("人脸原画保护:按人脸轮廓混回本帧原画(没有经过任何效果)。磨皮:柔化皮肤,眼睛、眉毛和嘴唇不参与。两项可分别开关。")
color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11; wrapMode: Text.WordWrap
}
VRow {
diff --git a/scripts/acceptance/beauty-gui.py b/scripts/acceptance/beauty-gui.py
index 1f86a68f..5ae15f32 100644
--- a/scripts/acceptance/beauty-gui.py
+++ b/scripts/acceptance/beauty-gui.py
@@ -5,8 +5,8 @@ usage: py -3.11 -I scripts/acceptance/beauty-gui.py <staged-app-name>
Runs a private copy of the staged app (tests/claude-beauty-20261017/<name>, with the
face model in its models/ folder) with an isolated profile, injects beauty-gui.qml
into that copy's Main.qml (restored afterwards), plays a clip with a face, and
-checks the console and engine log: the node and the shared face tracker are created,
-live values never rebuild them, and the log carries no face positions. Other Veyra
+checks the console and engine log: the node, the shared face tracker and the face
+mesh are created, live values never rebuild them, and the log carries no face positions. Other Veyra
processes are left alone; nothing outside the task folders is written.
"""
from pathlib import Path
@@ -55,9 +55,10 @@ tracker = re.findall(r'face tracker ready[^\r\n]*', edits)
rebuiltLive = re.findall(r'\[beauty\] instance=\d+ [^\r\n]*', live)
detectErrors = [l for l in engine.splitlines() if 'beauty-detect' in l and re.search(r'unavailable|failed|could not', l)]
# AGENTS.md: the log never records face crops, landmark tracks or pixels.
-positions = [l for l in engine.splitlines() if 'beauty' in l and re.search(r'landmark|\bbox\b|\bcx=|\bcy=|score=', l)]
+positions = [l for l in engine.splitlines() if 'beauty' in l and re.search(r'landmarks?\s*[=:]|\bbox\s*[=:]|\bcx=|\bcy=|score=|points?\s*[=:]', l)]
if not created: errors.append('the live player never created a beauty node')
if not tracker: errors.append('the shared face tracker never started')
+if 'mesh=ready' not in edits: errors.append('the face mesh (contour, eyes, brows, lips) was not active')
if rebuiltLive: errors.append('live beauty values rebuilt the node: ' + rebuiltLive[0])
if detectErrors: errors.append('face detection reported a problem: ' + detectErrors[0])
if positions: errors.append('the log records face positions: ' + positions[0])
diff --git a/scripts/beauty/facemesh-reference.py b/scripts/beauty/facemesh-reference.py
new file mode 100644
index 00000000..1e08d192
--- /dev/null
+++ b/scripts/beauty/facemesh-reference.py
@@ -0,0 +1,260 @@
+"""Reference outputs of the MediaPipe face landmark model (468 points) for the GPU port.
+
+For every face of the YuNet references (scripts/beauty/yunet-reference.py) this crops
+the original picture the way FaceMeshGpu does (centre of the face box, a square
+`--scale` times the box's long side, rotated so the eye line is level), runs the
+model and writes, under <out>/<case>-<face>/:
+ input.bin the 192 x 192 x 3 network input, float32 NHWC, RGB 0..1 (sRGB values)
+ output.bin the 1404 raw landmark values (x, y, z in crop pixels) and the face flag logit, float32
+ crop.txt centre x y, side, cos sin of the crop in original-picture pixels
+ landmarks.txt the 468 points mapped back to the picture, x y per line
+ overlay.png the picture with the face contour, eyes, brows and lips drawn (for a look)
+The network runs twice: OpenCV's TFLite importer (NCHW) and a small numpy executor
+that follows TensorFlow's padding rules exactly; the script stops if they disagree.
+Only public test pictures are used; nothing leaves the output folder.
+
+usage: facemesh-reference.py <face_landmark.tflite> <yunet-ref-dir> <out-dir> [--scale 1.44] [stem ...]
+(1.44 = FaceMeshGpu::kCropScale; the C++ tests read <yunet-ref-dir>/mesh)
+"""
+from pathlib import Path
+import hashlib, json, math, struct, sys
+import cv2
+import numpy as np
+
+SIZE = 192
+# MediaPipe face_mesh_connections.py (v0.8.9, Apache-2.0): closed outlines, in order.
+FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149,
+ 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109]
+LIPS = [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 409, 270, 269, 267, 0, 37, 39, 40, 185]
+LEFT_EYE = [263, 249, 390, 373, 374, 380, 381, 382, 362, 398, 384, 385, 386, 387, 388, 466]
+RIGHT_EYE = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246]
+LEFT_BROW = [276, 283, 282, 295, 285, 336, 296, 334, 293, 300]
+RIGHT_BROW = [46, 53, 52, 65, 55, 107, 66, 105, 63, 70]
+
+
+class Tflite:
+ """Just enough of the TFLite flatbuffer to run this model."""
+ OPS = {0: 'ADD', 3: 'CONV_2D', 4: 'DEPTHWISE_CONV_2D', 6: 'DEQUANTIZE', 17: 'MAX_POOL_2D', 34: 'PAD', 54: 'PRELU'}
+
+ def __init__(self, data):
+ self.d = data
+ root = self.table(self.ref(0))
+ codes = []
+ v, n = self.vec(root(1))
+ for k in range(n):
+ oc = self.table(self.ref(v + 4 * k))
+ dep = self.d[oc(0)] if oc(0) else 0
+ codes.append(self.i32(oc(3)) if oc(3) else dep)
+ bv, _ = self.vec(root(4))
+ sg = self.table(self.ref(self.vec(root(2))[0]))
+ tv, tn = self.vec(sg(0))
+ self.tensors = []
+ for k in range(tn):
+ t = self.table(self.ref(tv + 4 * k))
+ shape = self.ints(t(0))
+ kind = self.d[t(1)] if t(1) else 0
+ buf = self.u32(t(2)) if t(2) else 0
+ b = self.table(self.ref(bv + 4 * buf))
+ raw = b''
+ if b(0):
+ s, ln = self.vec(b(0)); raw = self.d[s:s + ln]
+ name = self.string(t(3)) if t(3) else ''
+ self.tensors.append(dict(shape=shape, kind=kind, raw=raw, name=name))
+ self.inputs, self.outputs = self.ints(sg(1)), self.ints(sg(2))
+ self.ops = []
+ ov, on = self.vec(sg(3))
+ for k in range(on):
+ op = self.table(self.ref(ov + 4 * k))
+ name = self.OPS.get(codes[self.u32(op(0)) if op(0) else 0])
+ if name is None:
+ raise SystemExit('unsupported operator')
+ opts = {}
+ if op(4):
+ bo = self.table(self.ref(op(4)))
+ b8 = lambda i: self.d[bo(i)] if bo(i) else 0
+ b32 = lambda i: self.i32(bo(i)) if bo(i) else 0
+ if name == 'CONV_2D': opts = dict(same=b8(0) == 0, sw=b32(1), sh=b32(2), act=b8(3))
+ elif name == 'DEPTHWISE_CONV_2D': opts = dict(same=b8(0) == 0, sw=b32(1), sh=b32(2), mult=b32(3), act=b8(4))
+ elif name == 'MAX_POOL_2D': opts = dict(same=b8(0) == 0, sw=b32(1), sh=b32(2), fw=b32(3), fh=b32(4), act=b8(5))
+ elif name == 'ADD': opts = dict(act=b8(0))
+ self.ops.append(dict(op=name, inputs=self.ints(op(1)), outputs=self.ints(op(2)), **opts))
+
+ def u32(self, o): return struct.unpack_from('<I', self.d, o)[0]
+ def i32(self, o): return struct.unpack_from('<i', self.d, o)[0]
+ def ref(self, o): return o + self.u32(o)
+ def vec(self, o):
+ v = self.ref(o); return v + 4, self.u32(v)
+ def ints(self, o):
+ if not o: return []
+ s, n = self.vec(o); return [self.i32(s + 4 * j) for j in range(n)]
+ def string(self, o):
+ s, n = self.vec(o); return self.d[s:s + n].decode()
+ def table(self, o):
+ vt = o - self.i32(o)
+ vlen = struct.unpack_from('<H', self.d, vt)[0]
+ def field(i):
+ off = 4 + 2 * i
+ if off >= vlen: return None
+ f = struct.unpack_from('<H', self.d, vt + off)[0]
+ return o + f if f else None
+ return field
+
+ def constant(self, i):
+ t = self.tensors[i]
+ dtype = {0: '<f4', 1: '<f2', 2: '<i4'}[t['kind']]
+ return np.frombuffer(t['raw'], dtype).astype(np.float32 if t['kind'] != 2 else np.int32).reshape(t['shape'])
+
+ def run(self, x):
+ values = {self.inputs[0]: x.astype(np.float32)}
+ for i, t in enumerate(self.tensors):
+ if t['raw']: values[i] = self.constant(i)
+ for op in self.ops:
+ a = [values[i] for i in op['inputs']]
+ kind = op['op']
+ if kind == 'DEQUANTIZE': y = a[0].astype(np.float32)
+ elif kind == 'CONV_2D': y = conv(a[0], a[1], a[2], op['sh'], op['sw'], op['same'])
+ elif kind == 'DEPTHWISE_CONV_2D': y = depthwise(a[0], a[1], a[2], op['sh'], op['sw'], op['same'])
+ elif kind == 'PRELU': y = np.where(a[0] >= 0, a[0], a[0] * a[1].reshape(1, 1, 1, -1))
+ elif kind == 'ADD': y = a[0] + a[1]
+ elif kind == 'MAX_POOL_2D':
+ n, h, w, c = a[0].shape
+ y = a[0][:, :h // 2 * 2, :w // 2 * 2].reshape(n, h // 2, 2, w // 2, 2, c).max(axis=(2, 4))
+ elif kind == 'PAD': y = np.pad(a[0], [tuple(p) for p in a[1]])
+ if op.get('act'):
+ raise SystemExit('fused activation not supported')
+ values[op['outputs'][0]] = y.astype(np.float32)
+ return [values[i] for i in self.outputs]
+
+
+def same_pads(size, k, s):
+ out = (size + s - 1) // s
+ total = max((out - 1) * s + k - size, 0)
+ return out, total // 2, total - total // 2
+
+
+def conv(x, w, b, sh, sw, same):
+ n, h, wd, c = x.shape
+ o, kh, kw, _ = w.shape
+ if same:
+ oh, pt, pb = same_pads(h, kh, sh); ow, pl, pr = same_pads(wd, kw, sw)
+ else:
+ oh, ow, pt, pb, pl, pr = (h - kh) // sh + 1, (wd - kw) // sw + 1, 0, 0, 0, 0
+ xp = np.pad(x, ((0, 0), (pt, pb), (pl, pr), (0, 0)))
+ y = np.zeros((n, oh, ow, o), np.float64)
+ for i in range(kh):
+ for j in range(kw):
+ patch = xp[:, i:i + sh * (oh - 1) + 1:sh, j:j + sw * (ow - 1) + 1:sw, :]
+ y += np.tensordot(patch, w[:, i, j, :].astype(np.float64), axes=([3], [1]))
+ return (y + b).astype(np.float32)
+
+
+def depthwise(x, w, b, sh, sw, same):
+ n, h, wd, c = x.shape
+ _, kh, kw, _ = w.shape
+ if same:
+ oh, pt, pb = same_pads(h, kh, sh); ow, pl, pr = same_pads(wd, kw, sw)
+ else:
+ oh, ow, pt, pb, pl, pr = (h - kh) // sh + 1, (wd - kw) // sw + 1, 0, 0, 0, 0
+ xp = np.pad(x, ((0, 0), (pt, pb), (pl, pr), (0, 0)))
+ y = np.zeros((n, oh, ow, c), np.float64)
+ for i in range(kh):
+ for j in range(kw):
+ y += xp[:, i:i + sh * (oh - 1) + 1:sh, j:j + sw * (ow - 1) + 1:sw, :] * w[0, i, j, :]
+ return (y + b).astype(np.float32)
+
+
+def read_image(path):
+ data = np.fromfile(str(path), dtype=np.uint8) # cv2.imread does not take non-ASCII paths on Windows
+ image = cv2.imdecode(data, cv2.IMREAD_COLOR)
+ if image is None:
+ raise SystemExit(f'cannot decode {path}')
+ return image
+
+
+def crop_of(face, scale):
+ """Crop centre, side and eye-line direction from a YuNet face (x y w h, right eye, left eye, ...)."""
+ x, y, w, h = face[:4]
+ ex, ey = face[6] - face[4], face[7] - face[5]
+ if ex < 0: ex, ey = -ex, -ey
+ length = math.hypot(ex, ey) or 1.0
+ return x + w / 2, y + h / 2, scale * max(w, h), ex / length, ey / length
+
+
+def crop_matrix(cx, cy, side, c, s):
+ """Maps crop pixel indices (u, v) to picture pixel indices (OpenCV: pixel centres at integers)."""
+ k = side / SIZE
+ # continuous crop (u + 0.5) -> centred (u + 0.5 - 96) * k -> rotate -> + centre; minus 0.5 back to indices
+ a, b = c * k, -s * k
+ d, e = s * k, c * k
+ tx = cx + a * (0.5 - SIZE / 2) + b * (0.5 - SIZE / 2) - 0.5
+ ty = cy + d * (0.5 - SIZE / 2) + e * (0.5 - SIZE / 2) - 0.5
+ return np.array([[a, b, tx], [d, e, ty]], np.float64)
+
+
+def main():
+ args = sys.argv[1:]
+ scale = 1.44
+ if '--scale' in args:
+ at = args.index('--scale'); scale = float(args[at + 1]); del args[at:at + 2]
+ model_path, refs, out = Path(args[0]), Path(args[1]), Path(args[2])
+ stems = args[3:] or ['lena', 'astronaut', 'messi5', 'largest_selfie', 'gta-f028', 'gta-f040', 'gta-f044', 'gta-f052']
+ model = model_path.read_bytes()
+ net = Tflite(model)
+ cvnet = cv2.dnn.readNetFromTFLite(np.frombuffer(model, np.uint8))
+ out.mkdir(parents=True, exist_ok=True)
+ summary = []
+ for stem in stems:
+ original_path = next((p for p in (refs / 'originals').glob(stem + '.*')), None)
+ if original_path is None:
+ raise SystemExit(f'no original for {stem}')
+ picture = read_image(original_path)
+ h0, w0 = picture.shape[:2]
+ # The 640-long-side detection, scaled back to the original picture.
+ case = next(p for p in refs.iterdir() if p.is_dir() and p.name.startswith(stem + '-') and max(map(int, p.name.rsplit('-', 1)[1].split('x'))) == 640)
+ dw, dh = map(int, case.name.rsplit('-', 1)[1].split('x'))
+ faces = json.loads((case / 'faces.json').read_text(encoding='utf8'))
+ rgb = cv2.cvtColor(picture, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
+ overlay = picture.copy()
+ for index, face in enumerate(faces):
+ f = [v * (w0 / dw if k % 2 == 0 else h0 / dh) for k, v in enumerate(face[:14])] + [face[14]]
+ cx, cy, side, c, s = crop_of(f, scale)
+ m = crop_matrix(cx, cy, side, c, s)
+ tensor = cv2.warpAffine(rgb, m, (SIZE, SIZE), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_REPLICATE)
+ tensor = np.ascontiguousarray(tensor, np.float32)
+ landmarks, flag = net.run(tensor[None])
+ cvnet.setInput(np.ascontiguousarray(tensor[None].transpose(0, 3, 1, 2)))
+ cv_landmarks = cvnet.forward('conv2d_21').reshape(-1)
+ cvnet.setInput(np.ascontiguousarray(tensor[None].transpose(0, 3, 1, 2)))
+ cv_flag = float(cvnet.forward('conv2d_31').reshape(-1)[0])
+ landmarks = landmarks.reshape(-1); flag = float(flag.reshape(-1)[0])
+ agree = float(np.abs(landmarks - cv_landmarks).max())
+ if agree > 1e-2 or abs(flag - cv_flag) > 1e-2:
+ raise SystemExit(f'{stem} face {index}: numpy and OpenCV disagree ({agree}, {flag} vs {cv_flag})')
+ folder = out / f'{stem}-{index}'
+ folder.mkdir(exist_ok=True)
+ tensor.astype('<f4').tofile(str(folder / 'input.bin'))
+ np.concatenate([landmarks, [flag]]).astype('<f4').tofile(str(folder / 'output.bin'))
+ (folder / 'crop.txt').write_text(f'{cx:.6f} {cy:.6f} {side:.6f} {c:.8f} {s:.8f}\n', encoding='utf8')
+ points = landmarks.reshape(468, 3)[:, :2]
+ k = side / SIZE
+ centred = (points - SIZE / 2) * k
+ image_points = np.stack([cx + c * centred[:, 0] - s * centred[:, 1], cy + s * centred[:, 0] + c * centred[:, 1]], 1)
+ (folder / 'landmarks.txt').write_text(''.join(f'{x:.4f} {y:.4f}\n' for x, y in image_points), encoding='utf8')
+ for loop, colour in ((FACE_OVAL, (0, 255, 0)), (LIPS, (0, 0, 255)), (LEFT_EYE, (255, 0, 0)), (RIGHT_EYE, (255, 0, 0)),
+ (LEFT_BROW, (255, 255, 0)), (RIGHT_BROW, (255, 255, 0))):
+ cv2.polylines(overlay, [np.round(image_points[loop] * 4).astype(np.int32)], True, colour, 1, cv2.LINE_AA, shift=2)
+ # Where MediaPipe's tracking would put the next crop: the landmarks' box, 1.5x, square.
+ lo, hi = image_points.min(0), image_points.max(0)
+ tracked = 1.5 * max(hi - lo)
+ summary.append(dict(case=f'{stem}-{index}', flag=flag, presence=1 / (1 + math.exp(-flag)), side=float(side),
+ landmarkSide=float(tracked), ratio=float(tracked / side), numpyVsOpencv=agree,
+ yunetBox=[float(f[2]), float(f[3])]))
+ print(f'{stem}-{index}: flag {flag:+.2f} side {side:.1f} landmark-roi {tracked:.1f} ratio {tracked / side:.3f} agree {agree:.2e}', flush=True)
+ ok, encoded = cv2.imencode('.png', overlay)
+ encoded.tofile(str(out / f'{stem}-overlay.png'))
+ meta = dict(model=model_path.name, modelSha256=hashlib.sha256(model).hexdigest(), opencv=cv2.__version__, scale=scale, faces=summary)
+ (out / 'cases.json').write_text(json.dumps(meta, indent=1), encoding='utf8')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/shaders/Beauty.hlsli b/shaders/Beauty.hlsli
index b664806e..8b966e40 100644
--- a/shaders/Beauty.hlsli
+++ b/shaders/Beauty.hlsli
@@ -41,6 +41,9 @@ SamplerState bLinearSampler : register(s1); // bilinear, clamp
#include "BeautyFaces.hlsli"
+// Face outlines from the face mesh (kShape* layout), one block per face slot.
+StructuredBuffer<float2> Shapes : register(t5);
+
// Restore uses the estimated face oval; smoothing reaches a little further
// (forehead, chin, neck) and relies on the skin selection for its edge.
static const float kBeautyOvalX = 1.0, kBeautyOvalY = 1.12, kBeautyOvalLift = 0.06;
@@ -105,14 +108,107 @@ float BeautyFaceOval(BeautyFace f, float2 p, float expand, float feather) {
const float edge = max(width * 0.5, 0.002);
return 1.0 - smoothstep(1.0 - edge, 1.0 + edge, rho);
}
-// Largest mask over the faces this node accepts.
+// Signed distance in node pixels from p to a closed outline of the face mesh
+// (negative inside, even-odd rule).
+float BeautyOutlineDistance(uint first, uint count, float2 p) {
+ const float2 size = float2(bWidth, bHeight);
+ float2 previous = Shapes[first + count - 1] * size;
+ float nearest = 1e30;
+ bool inside = false;
+ for (uint i = 0; i < count; ++i) {
+ const float2 v = Shapes[first + i] * size;
+ const float2 edge = previous - v, w = p - v;
+ const float2 b = w - edge * saturate(dot(w, edge) / max(dot(edge, edge), 1e-12));
+ nearest = min(nearest, dot(b, b));
+ if ((v.y > p.y) != (previous.y > p.y) && p.x < edge.x * (p.y - v.y) / (previous.y - v.y) + v.x) inside = !inside;
+ previous = v;
+ }
+ return inside ? -sqrt(nearest) : sqrt(nearest);
+}
+// Face width in node pixels (the detector's box), the unit of every margin below.
+float BeautyFaceWidth(BeautyFace f) { return max(2.0 * f.box.z * bWidth, 1.0); }
+// Soft region of face slot `slot` in node pixels: the mesh contour when the face has a
+// usable mesh, grown by `expand` and softened over `feather` (fractions of the face
+// width, the edge centred on the grown contour); otherwise the oval from its box.
+float BeautyFaceRegion(uint slot, BeautyFace f, float2 p, float expand, float feather) {
+ const uint base = slot * kShapeEntries;
+ if (Shapes[base].x < 0.5) return BeautyFaceOval(f, p, expand, feather);
+ const float2 size = float2(bWidth, bHeight);
+ const float width = BeautyFaceWidth(f);
+ const float grow = expand * width, soft = max(feather * width, 1.5);
+ const float reach = max(grow, 0.0) + soft;
+ if (any(p < Shapes[base + 2] * size - reach) || any(p > Shapes[base + 3] * size + reach)) return 0.0;
+ const float d = BeautyOutlineDistance(base + kShapeContour, kShapeContourCount, p) - grow;
+ return 1.0 - smoothstep(-0.5 * soft, 0.5 * soft, d);
+}
+// Eyes, brows and lips of face slot `slot` (grown a little, soft edge): 1 where the
+// smoothing must not reach. Faces without a usable mesh have none.
+float BeautyFeatures(uint slot, BeautyFace f, float2 p) {
+ const uint base = slot * kShapeEntries;
+ if (Shapes[base].x < 0.5) return 0.0;
+ const float2 size = float2(bWidth, bHeight);
+ const float width = BeautyFaceWidth(f);
+ const float margin = 0.02 * width, soft = max(0.04 * width, 1.5);
+ const float reach = margin + soft;
+ if (any(p < Shapes[base + 4] * size - reach) || any(p > Shapes[base + 5] * size + reach)) return 0.0;
+ float d = BeautyOutlineDistance(base + kShapeLips, kShapeLipsCount, p);
+ d = min(d, BeautyOutlineDistance(base + kShapeLeftEye, kShapeEyeCount, p));
+ d = min(d, BeautyOutlineDistance(base + kShapeRightEye, kShapeEyeCount, p));
+ d = min(d, BeautyOutlineDistance(base + kShapeLeftBrow, kShapeBrowCount, p));
+ d = min(d, BeautyOutlineDistance(base + kShapeRightBrow, kShapeBrowCount, p));
+ return 1.0 - smoothstep(-0.5 * soft, 0.5 * soft, d - margin);
+}
+// Largest region over the faces this node accepts.
float BeautyFaces(StructuredBuffer<BeautyFace> faces, float2 p, float expand, float feather) {
const uint count = min(faces[0].meta.x, kBeautyMaxFaces);
float mask = 0.0;
for (uint i = 0; i < count; ++i) {
const BeautyFace f = faces[1 + i];
if (f.shape.z < bMinConfidence || f.shape.w <= 0.0) continue;
- mask = max(mask, f.shape.w * BeautyFaceOval(f, p, expand, feather));
+ mask = max(mask, f.shape.w * BeautyFaceRegion(i, f, p, expand, feather));
+ }
+ return mask;
+}
+// Restore region, smoothing region and the eyes / brows / lips over the faces this
+// node accepts, with one contour distance per face (the regions differ only in how
+// far they grow and how soft their edge is).
+struct BeautyMaskSet { float restore; float smooth; float features; };
+BeautyMaskSet BeautyFaceMasks(StructuredBuffer<BeautyFace> faces, float2 p, bool smoothing) {
+ BeautyMaskSet m;
+ m.restore = 0.0; m.smooth = 0.0; m.features = 0.0;
+ const uint count = min(faces[0].meta.x, kBeautyMaxFaces);
+ const float2 size = float2(bWidth, bHeight);
+ for (uint i = 0; i < count; ++i) {
+ const BeautyFace f = faces[1 + i];
+ if (f.shape.z < bMinConfidence || f.shape.w <= 0.0) continue;
+ const uint base = i * kShapeEntries;
+ if (Shapes[base].x < 0.5) {
+ m.restore = max(m.restore, f.shape.w * BeautyFaceOval(f, p, bRegionExpand, bFeather));
+ if (smoothing) m.smooth = max(m.smooth, f.shape.w * BeautyFaceOval(f, p, kSmoothExpand + bRegionExpand, kSmoothFeather));
+ continue;
+ }
+ const float width = BeautyFaceWidth(f);
+ const float restoreGrow = bRegionExpand * width, restoreSoft = max(bFeather * width, 1.5);
+ const float smoothGrow = (kSmoothExpand + bRegionExpand) * width, smoothSoft = max(kSmoothFeather * width, 1.5);
+ const float reach = max(max(restoreGrow, 0.0) + restoreSoft, smoothing ? max(smoothGrow, 0.0) + smoothSoft : 0.0);
+ if (any(p < Shapes[base + 2] * size - reach) || any(p > Shapes[base + 3] * size + reach)) continue;
+ const float d = BeautyOutlineDistance(base + kShapeContour, kShapeContourCount, p);
+ m.restore = max(m.restore, f.shape.w * (1.0 - smoothstep(-0.5 * restoreSoft, 0.5 * restoreSoft, d - restoreGrow)));
+ if (smoothing) {
+ m.smooth = max(m.smooth, f.shape.w * (1.0 - smoothstep(-0.5 * smoothSoft, 0.5 * smoothSoft, d - smoothGrow)));
+ m.features = max(m.features, f.shape.w * BeautyFeatures(i, f, p));
+ }
+ }
+ return m;
+}
+// The eyes, brows and lips of the faces this node accepts.
+float BeautyFeatureMask(StructuredBuffer<BeautyFace> faces, float2 p) {
+ const uint count = min(faces[0].meta.x, kBeautyMaxFaces);
+ float mask = 0.0;
+ for (uint i = 0; i < count; ++i) {
+ const BeautyFace f = faces[1 + i];
+ if (f.shape.z < bMinConfidence || f.shape.w <= 0.0) continue;
+ mask = max(mask, f.shape.w * BeautyFeatures(i, f, p));
}
return mask;
}
@@ -124,13 +220,14 @@ static const uint kRoiFullArgs = 0u, kRoiLowArgs = 12u, kRoiOrigin = 24u, kRoiSi
static const uint kRoiLowOrigin = 40u, kRoiLowSize = 48u, kRoiFaces = 56u, kRoiBytes = 64u;
// The face-restored picture P at node pixel p: the node input C with the same
-// frame's original blended in. Restore masks use the estimated oval; the skin
-// scope keeps only the original's skin inside it.
-float3 BeautyRestored(Texture2D<float4> input, Texture2D<float4> original, StructuredBuffer<BeautyFace> faces, int2 p, out float mask) {
+// frame's original blended in. Restore masks follow the face contour (the oval
+// without a mesh); the skin scope keeps only the original's skin inside it.
+// `region`: the restore region at p (BeautyFaceMasks), before the strength.
+float3 BeautyRestoredIn(Texture2D<float4> input, Texture2D<float4> original, int2 p, float region, out float mask) {
const float3 c = input.Load(int3(p, 0)).rgb;
mask = 0.0;
if ((bFlags & kBeautyRestore) == 0 || (bFlags & kBeautyOriginal) == 0) return c;
- mask = BeautyFaces(faces, float2(p) + 0.5, bRegionExpand, bFeather) * bRestoreStrength;
+ mask = region * bRestoreStrength;
if (mask <= 0.0) return c;
// Same size as the source: the original texel itself; otherwise bilinear.
const float3 o = (bWidth == bSrcWidth && bHeight == bSrcHeight)
@@ -139,4 +236,9 @@ float3 BeautyRestored(Texture2D<float4> input, Texture2D<float4> original, Struc
if (bFlags & kBeautyRestoreSkin) mask *= BeautySkin(BeautyPerceptual(o));
return mask >= 1.0 ? o : lerp(c, o, mask); // a full restore is the original texel itself
}
+float3 BeautyRestored(Texture2D<float4> input, Texture2D<float4> original, StructuredBuffer<BeautyFace> faces, int2 p, out float mask) {
+ const bool restoring = (bFlags & kBeautyRestore) != 0 && (bFlags & kBeautyOriginal) != 0;
+ const float region = restoring ? BeautyFaceMasks(faces, float2(p) + 0.5, false).restore : 0.0;
+ return BeautyRestoredIn(input, original, p, region, mask);
+}
#endif
diff --git a/shaders/BeautyApply.hlsl b/shaders/BeautyApply.hlsl
index 12312ff5..b3c09446 100644
--- a/shaders/BeautyApply.hlsl
+++ b/shaders/BeautyApply.hlsl
@@ -4,7 +4,8 @@
// B = a * I + b, the guided-filter result of P's perceptual copy I (coefficients
// from the statistics grid, bilinear)
// SkinSoft (yasunari01/obs-filters fd5690f, GPL-2.0-or-later) then decides how
-// much of B to take: skin selection x face region, detail protection
+// much of B to take: skin selection x face region (minus the eyes, brows and lips
+// of the face mesh), detail protection
// 1 - smoothstep(0.02, 0.22, |I - B| * detail * 3), texture restore back to I.
// Brightening lifts the skin's perceptual luma (gamma 1 / (1 + 0.6 k), only
// below white). The result goes back to linear and mixes with P by the
@@ -25,14 +26,18 @@ void main(uint3 id : SV_DispatchThreadID) {
if (any(id.xy >= extent)) return;
const int2 p = int2(Roi.Load2(kRoiOrigin) + id.xy);
const float4 c = Input.Load(int3(p, 0));
+ const bool smoothing = (bFlags & (kBeautySmooth | kBeautyShowMask)) != 0;
+ const BeautyMaskSet masks = BeautyFaceMasks(Faces, float2(p) + 0.5, smoothing);
float restoreMask;
- const float3 restored = BeautyRestored(Input, Original, Faces, p, restoreMask);
+ const float3 restored = BeautyRestoredIn(Input, Original, p, masks.restore, restoreMask);
float3 result = restored;
float smoothMask = 0.0;
- if (bFlags & (kBeautySmooth | kBeautyShowMask)) {
+ if (smoothing) {
const float3 i = BeautyPerceptual(restored);
- const float region = (bFlags & kBeautyAllSkin) ? 1.0 : BeautyFaces(Faces, float2(p) + 0.5, kSmoothExpand + bRegionExpand, kSmoothFeather);
- smoothMask = region > 0.0 ? region * BeautySkin(i) : 0.0;
+ // Every skin pixel, or the faces' regions; the eyes, brows and lips of the faces stay out.
+ const float region = (bFlags & kBeautyAllSkin) ? 1.0 : masks.smooth;
+ const float features = (bFlags & kBeautyAllSkin) ? BeautyFeatureMask(Faces, float2(p) + 0.5) : masks.features;
+ smoothMask = region > 0.0 ? region * BeautySkin(i) * (1.0 - features) : 0.0;
if ((bFlags & kBeautySmooth) && smoothMask > 0.0) {
// Statistics cell centres sit at (cell + 0.5) * bScale; stay inside this frame's cells.
const float2 lowOrigin = float2(Roi.Load2(kRoiLowOrigin)), lowExtent = float2(Roi.Load2(kRoiLowSize));
diff --git a/shaders/BeautyFaces.hlsli b/shaders/BeautyFaces.hlsli
index 8d28feb5..78344f05 100644
--- a/shaders/BeautyFaces.hlsli
+++ b/shaders/BeautyFaces.hlsli
@@ -10,4 +10,16 @@ struct BeautyFace {
// face: id, hits, filtered centre x, y at the last match (float bits)
};
static const uint kBeautyMaxFaces = 8u;
+
+// Face outlines from the face mesh (FaceMeshGpu, BeautyMeshDecode.hlsl): one block of
+// kShapeEntries float2 per face slot, in source-frame fractions, read by the node passes.
+// 0: (1 when the face has a usable mesh, the mesh's face score); 2-3: contour box
+// min / max; 4-5: box of the eyes, brows and lips; kShapeContour..: the closed outlines.
+// A face without a usable mesh keeps the oval from its box.
+static const uint kShapeEntries = 128u;
+static const uint kShapeContour = 8u, kShapeContourCount = 36u;
+static const uint kShapeLips = 44u, kShapeLipsCount = 20u;
+static const uint kShapeLeftEye = 64u, kShapeRightEye = 80u, kShapeEyeCount = 16u;
+static const uint kShapeLeftBrow = 96u, kShapeRightBrow = 106u, kShapeBrowCount = 10u;
+static const uint kShapeOutlinePoints = 108u;
#endif
diff --git a/shaders/BeautyMesh.hlsli b/shaders/BeautyMesh.hlsli
new file mode 100644
index 00000000..cc0af631
--- /dev/null
+++ b/shaders/BeautyMesh.hlsli
@@ -0,0 +1,43 @@
+// Shared declarations for the face mesh kernels (src/beauty/FaceMeshGpu.cpp): the
+// MediaPipe face landmark network (468 points) on a 192 x 192 crop of every tracked face.
+//
+// Tensors live in one float4 scratch buffer, channel-last with the face slot outermost:
+// element = offset + ((face * height + y) * width + x) * quads + quad, quad k holding
+// channels 4k..4k+3. Weights, biases and PReLU slopes of every layer live in one float4
+// buffer (offsets in float4 units); the host packs them as
+// convolution k x k: W[wOff + ((q * k + ky) * k + kx) * inQ * 4 + c] = (w[4q+0][ky][kx][c], .., w[4q+3][ky][kx][c])
+// depthwise 3 x 3 : W[wOff + q * 9 + ky * 3 + kx] = (w[ky][kx][4q+0], .., w[ky][kx][4q+3])
+// bias, slope : W[bOff + q], W[aOff + q]
+#ifndef VEYRA_BEAUTY_MESH_HLSLI
+#define VEYRA_BEAUTY_MESH_HLSLI
+#include "BeautyFaces.hlsli"
+
+cbuffer MeshParams : register(b0) {
+ uint inW; uint inH; uint inQ;
+ uint outW; uint outH; uint outQ;
+ uint wOff; uint bOff; uint aOff; // aOff: PReLU slopes, kMeshNone without
+ uint inOff; uint outOff; uint resOff; // tensor offsets, float4 units
+ uint resInfo; // residual quads | mode << 16: 0 none, 1 the same-size tensor, 2 its 2x2 max-pool (channel padded)
+ uint convInfo; // kernel | stride << 8 | pad top << 16 | pad left << 24
+ uint capacity; // face slots to process (the max faces setting)
+ uint forcedCount; // 0: the tracked face count (Faces header); else this many slots (tests)
+};
+StructuredBuffer<float4> Weights : register(t0);
+StructuredBuffer<BeautyFace> Faces : register(t1);
+RWStructuredBuffer<float4> Scratch : register(u0);
+
+static const uint kMeshNone = 0xffffffffu;
+
+uint meshFaces() {
+ const uint tracked = min(Faces[0].meta.x, kBeautyMaxFaces);
+ return min(forcedCount != 0u ? forcedCount : tracked, capacity);
+}
+uint tensorAt(uint offset, uint face, uint x, uint y, uint w, uint h, uint quads) {
+ return offset + ((face * h + y) * w + x) * quads;
+}
+float4 meshActivation(float4 v, uint q) {
+ if (aOff == kMeshNone) return v;
+ const float4 slope = Weights[aOff + q];
+ return select(v >= 0.0, v, v * slope);
+}
+#endif
diff --git a/shaders/BeautyMeshConv.hlsl b/shaders/BeautyMeshConv.hlsl
new file mode 100644
index 00000000..e4896ffb
--- /dev/null
+++ b/shaders/BeautyMeshConv.hlsl
@@ -0,0 +1,29 @@
+// Face mesh: k x k convolution (the 3 x 3 stride-2 stem, the 3 x 3 heads) with bias and
+// an optional PReLU. TensorFlow SAME padding arrives as the top / left pad.
+#include "BeautyMesh.hlsli"
+
+[numthreads(64, 1, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint face = id.z;
+ if (face >= meshFaces() || id.x >= outW * outH * outQ) return;
+ const uint q = id.x % outQ, pixel = id.x / outQ, x = pixel % outW, y = pixel / outW;
+ const uint k = convInfo & 0xffu, stride = (convInfo >> 8) & 0xffu;
+ const int padTop = int((convInfo >> 16) & 0xffu), padLeft = int(convInfo >> 24);
+ float4 acc = Weights[bOff + q];
+ for (uint ky = 0; ky < k; ++ky) {
+ const int sy = int(y * stride + ky) - padTop;
+ if (sy < 0 || sy >= int(inH)) continue;
+ for (uint kx = 0; kx < k; ++kx) {
+ const int sx = int(x * stride + kx) - padLeft;
+ if (sx < 0 || sx >= int(inW)) continue;
+ const uint input = tensorAt(inOff, face, uint(sx), uint(sy), inW, inH, inQ);
+ const uint w = wOff + ((q * k + ky) * k + kx) * inQ * 4;
+ for (uint c = 0; c < inQ; ++c) {
+ const float4 v = Scratch[input + c];
+ const uint b = w + c * 4;
+ acc += Weights[b] * v.x + Weights[b + 1] * v.y + Weights[b + 2] * v.z + Weights[b + 3] * v.w;
+ }
+ }
+ }
+ Scratch[tensorAt(outOff, face, x, y, outW, outH, outQ) + q] = meshActivation(acc, q);
+}
diff --git a/shaders/BeautyMeshCrop.hlsl b/shaders/BeautyMeshCrop.hlsl
new file mode 100644
index 00000000..b4006957
--- /dev/null
+++ b/shaders/BeautyMeshCrop.hlsl
@@ -0,0 +1,43 @@
+// Face mesh input: for every tracked face the 192 x 192 crop the landmark model expects
+// (MediaPipe face_landmark: centred on the face, a square `scale` times the face box's
+// long side, rotated so the eye line is level) as RGB 0..1 display-referred values,
+// what the model saw in its 8-bit training pictures. Bilinear on the encoded values
+// with replicated edges, as MediaPipe's ImageToTensor (and the reference script's
+// OpenCV warpAffine with BORDER_REPLICATE) do. The crop's centre, side and axis go to
+// the scratch buffer for the decode.
+// inW / inH: source size; inQ: HDR source; wOff: crop scale (float bits);
+// outOff: the input tensor; resOff: crop parameters (two float4 per face)
+#include "BeautyMesh.hlsli"
+#include "HdrColor.hlsli"
+
+Texture2D<float4> Source : register(t2);
+
+float3 meshDisplay(int2 p) {
+ const float3 c = Source.Load(int3(clamp(p, int2(0, 0), int2(inW, inH) - 1), 0)).rgb;
+ const float3 v = saturate(inQ != 0u ? HdrProxy(c) : c);
+ return select(v <= 0.0031308, v * 12.92, 1.055 * pow(v, 1.0 / 2.4) - 0.055);
+}
+
+[numthreads(64, 1, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint face = id.z;
+ if (face >= meshFaces() || id.x >= outW * outH) return;
+ const uint u = id.x % outW, v = id.x / outW;
+ const BeautyFace f = Faces[1 + face];
+ const float2 size = float2(inW, inH);
+ const float2 centre = f.box.xy * size;
+ const float side = asfloat(wOff) * max(2.0 * f.box.z * size.x, 2.0 * f.box.w * size.y);
+ const float2 axis = f.shape.xy;
+ const float2 c = (float2(u, v) + 0.5 - 0.5 * float2(outW, outH)) * (side / float(outW));
+ // Continuous picture position of this crop pixel's centre, then the texel grid (centres at +0.5).
+ const float2 p = centre + float2(axis.x * c.x - axis.y * c.y, axis.y * c.x + axis.x * c.y) - 0.5;
+ const int2 i0 = int2(floor(p));
+ const float2 t = p - float2(i0);
+ const float3 rgb = lerp(lerp(meshDisplay(i0), meshDisplay(i0 + int2(1, 0)), t.x),
+ lerp(meshDisplay(i0 + int2(0, 1)), meshDisplay(i0 + int2(1, 1)), t.x), t.y);
+ Scratch[tensorAt(outOff, face, u, v, outW, outH, 1u)] = float4(rgb, 0.0);
+ if (u == 0u && v == 0u) {
+ Scratch[resOff + face * 2u] = float4(centre, side, 0.0);
+ Scratch[resOff + face * 2u + 1u] = float4(axis, 0.0, 0.0);
+ }
+}
diff --git a/shaders/BeautyMeshDecode.hlsl b/shaders/BeautyMeshDecode.hlsl
new file mode 100644
index 00000000..9002169c
--- /dev/null
+++ b/shaders/BeautyMeshDecode.hlsl
@@ -0,0 +1,113 @@
+// Face mesh output: the 468 points of every tracked face back in the frame (source
+// fractions), smoothed over time, and the outlines the node passes mask with
+// (BeautyFaces.hlsli kShape*). One group per face slot; every slot is written, an
+// empty one as "no mesh".
+//
+// Smoothing: a One Euro filter per point (speed in face widths per second, the same
+// settings as the face tracks), kept per track id so a face keeps its history when
+// the track list is compacted; reset frames and pictures start fresh. A face uses its
+// mesh when the model's face flag passes (with hysteresis) and the contour agrees with
+// the detector's face box; otherwise it keeps the oval from its box.
+// inW / inH: source size; inOff: landmark tensor (1 x 1 x 1404); outOff: flag tensor;
+// resOff: crop parameters; wOff / bOff / aOff: rest cutoff, speed factor, speed
+// cutoff (float bits); resInfo: dt in ms (float bits); convInfo: bit 0 reset,
+// bit 1 still picture, bit 2 state parity
+#include "BeautyMesh.hlsli"
+
+RWStructuredBuffer<float2> Shapes : register(u1);
+RWStructuredBuffer<float4> State : register(u2);
+
+static const uint kPoints = 468u, kLandmarkQuads = 351u;
+static const uint kStateFace = 1u + kPoints, kStateHalf = kBeautyMaxFaces * kStateFace;
+static const float kStartLogit = -4.0, kKeepLogit = -5.5;
+// MediaPipe face_mesh_connections.py (v0.8.9, Apache-2.0) as closed outlines, in the
+// order of BeautyFaces.hlsli: contour, outer lips, left eye, right eye, left brow, right brow.
+static const uint kOutline[kShapeOutlinePoints] = {
+ 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149,
+ 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,
+ 61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 409, 270, 269, 267, 0, 37, 39, 40, 185,
+ 263, 249, 390, 373, 374, 380, 381, 382, 362, 398, 384, 385, 386, 387, 388, 466,
+ 33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246,
+ 276, 283, 282, 295, 285, 336, 296, 334, 293, 300,
+ 46, 53, 52, 65, 55, 107, 66, 105, 63, 70};
+
+groupshared float2 gPoint[kPoints];
+groupshared uint gPrevious;
+
+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));
+}
+float component(float4 v, uint i) { return i == 0u ? v.x : i == 1u ? v.y : i == 2u ? v.z : v.w; }
+
+[numthreads(512, 1, 1)]
+void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) {
+ const uint face = group.z;
+ const uint parity = (convInfo >> 2) & 1u;
+ const uint previousHalf = parity != 0u ? kStateHalf : 0u, nextHalf = parity != 0u ? 0u : kStateHalf;
+ const uint shape = face * kShapeEntries;
+ if (face >= meshFaces()) {
+ if (t == 0u) {
+ Shapes[shape] = float2(0.0, 0.0);
+ State[nextHalf + face * kStateFace] = float4(0.0, 0.0, 0.0, 0.0);
+ }
+ return;
+ }
+ const BeautyFace f = Faces[1 + face];
+ const bool fresh = (convInfo & 3u) != 0u;
+ const float dt = asfloat(resInfo);
+ if (t == 0u) {
+ uint found = kMeshNone;
+ if (!fresh && f.meta.x != 0u)
+ for (uint s = 0; s < kBeautyMaxFaces; ++s)
+ if (asuint(State[previousHalf + s * kStateFace].x) == f.meta.x) found = s;
+ gPrevious = found;
+ }
+ GroupMemoryBarrierWithGroupSync();
+ const uint previous = gPrevious;
+ const float2 size = float2(inW, inH);
+ const float faceWidth = max(2.0 * f.box.z * size.x, 1.0);
+ if (t < kPoints) {
+ const float4 crop0 = Scratch[resOff + face * 2u], crop1 = Scratch[resOff + face * 2u + 1u];
+ const uint base = inOff + face * kLandmarkQuads;
+ const float x = component(Scratch[base + (3u * t) / 4u], (3u * t) % 4u);
+ const float y = component(Scratch[base + (3u * t + 1u) / 4u], (3u * t + 1u) % 4u);
+ // Crop pixels (0..192 across) -> centred -> rotated back -> picture -> fractions.
+ const float2 c = (float2(x, y) - 96.0) * (crop0.z / 192.0);
+ const float2 p = (crop0.xy + float2(crop1.x * c.x - crop1.y * c.y, crop1.y * c.x + crop1.x * c.y)) / size;
+ float4 s = float4(p, 0.0, 0.0);
+ if (previous != kMeshNone) {
+ const float4 last = State[previousHalf + previous * kStateFace + 1u + t];
+ if (dt > 0.0) {
+ const float2 speed = lerp(last.zw, (p - last.xy) / dt, lowpass(asfloat(aOff), dt));
+ const float facesPerSecond = length(speed * size) / faceWidth * 1000.0;
+ s = float4(lerp(last.xy, p, lowpass(asfloat(wOff) + asfloat(bOff) * facesPerSecond, dt)), speed);
+ } else s = last;
+ }
+ State[nextHalf + face * kStateFace + 1u + t] = s;
+ gPoint[t] = s.xy;
+ }
+ GroupMemoryBarrierWithGroupSync();
+ if (t < kShapeOutlinePoints) Shapes[shape + kShapeContour + t] = gPoint[kOutline[t]];
+ if (t == 0u) {
+ float2 lo = 1e9, hi = -1e9, featureLo = 1e9, featureHi = -1e9;
+ for (uint i = 0; i < kShapeContourCount; ++i) { lo = min(lo, gPoint[kOutline[i]]); hi = max(hi, gPoint[kOutline[i]]); }
+ for (uint j = kShapeContourCount; j < kShapeOutlinePoints; ++j) {
+ featureLo = min(featureLo, gPoint[kOutline[j]]);
+ featureHi = max(featureHi, gPoint[kOutline[j]]);
+ }
+ const float logit = Scratch[outOff + face].x;
+ const bool wasValid = previous != kMeshNone && State[previousHalf + previous * kStateFace].y > 0.5;
+ const float2 contourCentre = (lo + hi) * 0.5 * size;
+ const float contourWidth = (hi.x - lo.x) * size.x;
+ const bool agrees = all(isfinite(lo)) && all(isfinite(hi)) && length(contourCentre - f.box.xy * size) < 0.35 * faceWidth &&
+ contourWidth > 0.6 * faceWidth && contourWidth < 1.8 * faceWidth;
+ const bool valid = isfinite(logit) && logit > (wasValid ? kKeepLogit : kStartLogit) && agrees;
+ Shapes[shape] = float2(valid ? 1.0 : 0.0, 1.0 / (1.0 + exp(-clamp(logit, -40.0, 40.0))));
+ Shapes[shape + 2u] = lo;
+ Shapes[shape + 3u] = hi;
+ Shapes[shape + 4u] = featureLo;
+ Shapes[shape + 5u] = featureHi;
+ State[nextHalf + face * kStateFace] = float4(asfloat(f.meta.x), valid ? 1.0 : 0.0, logit, 0.0);
+ }
+}
diff --git a/shaders/BeautyMeshDepthwise.hlsl b/shaders/BeautyMeshDepthwise.hlsl
new file mode 100644
index 00000000..65579d4e
--- /dev/null
+++ b/shaders/BeautyMeshDepthwise.hlsl
@@ -0,0 +1,21 @@
+// Face mesh: depthwise 3 x 3 convolution (stride 1 or 2, TensorFlow SAME padding) with bias.
+#include "BeautyMesh.hlsli"
+
+[numthreads(64, 1, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint face = id.z;
+ if (face >= meshFaces() || id.x >= outW * outH * outQ) return;
+ const uint q = id.x % outQ, pixel = id.x / outQ, x = pixel % outW, y = pixel / outW;
+ const uint stride = (convInfo >> 8) & 0xffu;
+ const int padTop = int((convInfo >> 16) & 0xffu), padLeft = int(convInfo >> 24);
+ float4 acc = Weights[bOff + q];
+ [unroll] for (uint ky = 0; ky < 3; ++ky) {
+ const int sy = int(y * stride + ky) - padTop;
+ [unroll] for (uint kx = 0; kx < 3; ++kx) {
+ const int sx = int(x * stride + kx) - padLeft;
+ if (sx >= 0 && sy >= 0 && sx < int(inW) && sy < int(inH))
+ acc += Weights[wOff + q * 9 + ky * 3 + kx] * Scratch[tensorAt(inOff, face, uint(sx), uint(sy), inW, inH, inQ) + q];
+ }
+ }
+ Scratch[tensorAt(outOff, face, x, y, outW, outH, outQ) + q] = meshActivation(acc, q);
+}
diff --git a/shaders/BeautyMeshPointwise.hlsl b/shaders/BeautyMeshPointwise.hlsl
new file mode 100644
index 00000000..24a2c944
--- /dev/null
+++ b/shaders/BeautyMeshPointwise.hlsl
@@ -0,0 +1,29 @@
+// Face mesh: 1 x 1 convolution with bias, then the block's residual and PReLU, fused:
+// mode 1: + the block input (same size and channels)
+// mode 2: + the block input max-pooled 2 x 2 (it has twice the size); channels beyond
+// its own are zero (the TFLite PAD that widens the shortcut)
+#include "BeautyMesh.hlsli"
+
+[numthreads(64, 1, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint face = id.z;
+ if (face >= meshFaces() || id.x >= outW * outH * outQ) return;
+ const uint q = id.x % outQ, pixel = id.x / outQ, x = pixel % outW, y = pixel / outW;
+ float4 acc = Weights[bOff + q];
+ const uint input = tensorAt(inOff, face, x, y, inW, inH, inQ);
+ const uint w = wOff + q * inQ * 4;
+ for (uint c = 0; c < inQ; ++c) {
+ const float4 v = Scratch[input + c];
+ const uint b = w + c * 4;
+ acc += Weights[b] * v.x + Weights[b + 1] * v.y + Weights[b + 2] * v.z + Weights[b + 3] * v.w;
+ }
+ const uint mode = resInfo >> 16, resQ = resInfo & 0xffffu;
+ if (mode == 1u) {
+ acc += Scratch[tensorAt(resOff, face, x, y, outW, outH, resQ) + q];
+ } else if (mode == 2u && q < resQ) {
+ const uint rw = outW * 2, rh = outH * 2;
+ const uint r = tensorAt(resOff, face, x * 2, y * 2, rw, rh, resQ) + q;
+ acc += max(max(Scratch[r], Scratch[r + resQ]), max(Scratch[r + rw * resQ], Scratch[r + (rw + 1) * resQ]));
+ }
+ Scratch[tensorAt(outOff, face, x, y, outW, outH, outQ) + q] = meshActivation(acc, q);
+}
diff --git a/shaders/BeautyRoi.hlsl b/shaders/BeautyRoi.hlsl
index 4de90a53..a553f4b6 100644
--- a/shaders/BeautyRoi.hlsl
+++ b/shaders/BeautyRoi.hlsl
@@ -1,7 +1,8 @@
// Beauty node: the region this node touches this frame, as indirect dispatch
-// arguments. The union of the accepted faces' ovals (restore and smoothing reach,
-// plus the smoothing filter's footprint) clamped to the node; the whole frame
-// when smoothing every skin pixel; nothing at all without faces. The passes
+// arguments. The union of the accepted faces' regions (their contour box, or the
+// oval without a mesh, grown by the restore and smoothing reach and the smoothing
+// filter's footprint) clamped to the node; the whole frame when smoothing every
+// skin pixel; nothing at all without faces. The passes
// after this one only run on that region; the rest of the output is the input copy.
#include "Beauty.hlsli"
@@ -27,6 +28,18 @@ void main() {
if (restore) reach = max(reach, (1.0 + bRegionExpand) * (1.0 + bFeather * 2.0));
if (smooth || (bFlags & kBeautyShowMask)) reach = max(reach, (1.0 + kSmoothExpand + bRegionExpand) * (1.0 + kSmoothFeather * 2.0));
if (reach <= 0.0) continue;
+ if (Shapes[i * kShapeEntries].x >= 0.5) {
+ // The mesh contour's box, grown like BeautyFaceRegion.
+ const float width = max(2.0 * f.box.z * bWidth, 1.0);
+ float grow = 0.0;
+ if (restore) grow = max(grow, max(bRegionExpand, 0.0) + bFeather);
+ if (smooth || (bFlags & kBeautyShowMask)) grow = max(grow, max(kSmoothExpand + bRegionExpand, 0.0) + kSmoothFeather);
+ const float margin = grow * width + 2.0 + filter;
+ lo = min(lo, Shapes[i * kShapeEntries + 2] * size - margin);
+ hi = max(hi, Shapes[i * kShapeEntries + 3] * size + margin);
+ ++faces;
+ continue;
+ }
// Bounding circle of the (rotated, lifted) oval.
const float2 axes = f.box.zw * size * float2(kBeautyOvalX, kBeautyOvalY) * reach;
const float radius = max(axes.x, axes.y) * 1.05 + kBeautyOvalLift * f.box.w * 2.0 * bHeight + filter + 2.0;
diff --git a/src/beauty/FaceMeshGpu.cpp b/src/beauty/FaceMeshGpu.cpp
new file mode 100644
index 00000000..510c0e9f
--- /dev/null
+++ b/src/beauty/FaceMeshGpu.cpp
@@ -0,0 +1,662 @@
+#include "veyra/beauty/FaceMeshGpu.h"
+
+#include "veyra/Log.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/beauty/TfliteLite.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+
+#include <wrl/client.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <format>
+
+namespace veyra::beauty {
+namespace {
+template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>;
+
+constexpr const wchar_t* kModelName = L"face_landmark.tflite";
+constexpr uint32_t kConstantDwords = 16;
+constexpr uint32_t kSrvs = 3, kUavs = 3, kPerSlot = kSrvs + kUavs; // t0 weights, t1 faces, t2 source | u0 scratch, u1 shapes, u2 state
+constexpr uint32_t kNone = 0xffffffffu;
+constexpr uint32_t kSide = FaceMeshGpu::kInputSize;
+constexpr uint32_t kLandmarkValues = FaceMeshGpu::kLandmarks * 3, kLandmarkQuads = kLandmarkValues / 4;
+constexpr uint64_t kStateFloat4s = 2ull * FaceMeshGpu::kMaxFaces * (1 + FaceMeshGpu::kLandmarks); // two halves, header + points per face
+constexpr uint64_t kCropFloat4s = 2ull * FaceMeshGpu::kMaxFaces;
+
+enum class Kind : uint32_t { Crop, Conv, Depthwise, Pointwise, Decode, Count };
+constexpr const char* kShaderFile[] = {"BeautyMeshCrop.dxil", "BeautyMeshConv.dxil", "BeautyMeshDepthwise.dxil",
+ "BeautyMeshPointwise.dxil", "BeautyMeshDecode.dxil"};
+
+uint32_t bitsOf(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }
+
+ComPtr<ID3D12Resource> makeBuffer(ID3D12Device* device, uint64_t bytes, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_FLAGS flags,
+ D3D12_RESOURCE_STATES state)
+{
+ D3D12_HEAP_PROPERTIES hp{};
+ hp.Type = heap;
+ D3D12_RESOURCE_DESC d{};
+ d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ d.Width = std::max<uint64_t>(bytes, 16); d.Height = 1; d.DepthOrArraySize = 1; d.MipLevels = 1;
+ d.SampleDesc.Count = 1; d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Flags = flags;
+ ComPtr<ID3D12Resource> r;
+ if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(&r)))) return nullptr;
+ return r;
+}
+
+struct Tensor {
+ uint32_t w = 0, h = 0, q = 0; // quads = channels / 4, rounded up
+ uint64_t offset = 0; // float4 units in the scratch buffer
+ int lastRead = -1; // layer index
+ bool pinned = false; // kept to the end (the outputs)
+ uint64_t float4s() const { return uint64_t(w) * h * q * FaceMeshGpu::kMaxFaces; }
+};
+struct Layer {
+ Kind kind = Kind::Conv;
+ int in = -1, res = -1, out = -1; // tensors
+ uint32_t wOff = 0, bOff = 0, aOff = kNone;
+ uint32_t kernel = 1, stride = 1, padTop = 0, padLeft = 0;
+ uint32_t residual = 0; // 0 none, 1 the same-size tensor, 2 its 2x2 max-pool
+};
+
+// One-shot work on a private queue (weight upload, the test hook).
+struct Submit {
+ ComPtr<ID3D12CommandAllocator> allocator;
+ ComPtr<ID3D12GraphicsCommandList> list;
+ ComPtr<ID3D12Fence> fence;
+ bool open(ID3D12Device* device)
+ {
+ return SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) &&
+ SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) &&
+ SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)));
+ }
+ bool run(ID3D12CommandQueue* queue)
+ {
+ if (FAILED(list->Close())) return false;
+ ID3D12CommandList* lists[] = {list.Get()};
+ queue->ExecuteCommandLists(1, lists);
+ HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
+ queue->Signal(fence.Get(), 1);
+ fence->SetEventOnCompletion(1, event);
+ WaitForSingleObject(event, 20000);
+ CloseHandle(event);
+ return fence->GetCompletedValue() >= 1;
+ }
+};
+
+void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to)
+{
+ D3D12_RESOURCE_BARRIER b{};
+ b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ b.Transition.pResource = r;
+ b.Transition.StateBefore = from;
+ b.Transition.StateAfter = to;
+ b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+ list->ResourceBarrier(1, &b);
+}
+void uavBarrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r)
+{
+ D3D12_RESOURCE_BARRIER b{};
+ b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
+ b.UAV.pResource = r;
+ list->ResourceBarrier(1, &b);
+}
+} // namespace
+
+std::filesystem::path locateFaceMeshModel()
+{
+ wchar_t exe[32768]{};
+ const DWORD length = GetModuleFileNameW(nullptr, exe, DWORD(std::size(exe)));
+ const auto exeDirectory = length && length < std::size(exe) ? std::filesystem::path(exe).parent_path() : std::filesystem::current_path();
+ const auto root = runtime::applicationRoot();
+ const std::filesystem::path folders[] = {root / "runtime" / "models", root / "runtime_local" / "models", exeDirectory / "models"};
+ std::error_code ec;
+ for (const auto& folder : folders)
+ if (std::filesystem::is_regular_file(folder / kModelName, ec)) return folder / kModelName;
+ return {};
+}
+
+struct FaceMeshGpu::Impl {
+ ID3D12Device* device = nullptr;
+ std::string description;
+ std::vector<Tensor> tensors;
+ std::vector<Layer> layers;
+ std::vector<float> weights; // float4 aligned
+ int inputTensor = -1, landmarkTensor = -1, flagTensor = -1;
+ uint64_t scratchFloat4s = 0;
+ ComPtr<ID3D12Resource> weightBuffer, scratch, state;
+ ID3D12Resource* faces = nullptr;
+ ID3D12Resource* shapes = nullptr;
+ ComPtr<ID3D12RootSignature> root;
+ ComPtr<ID3D12PipelineState> pipelines[size_t(Kind::Count)];
+ ComPtr<ID3D12DescriptorHeap> heap, staging;
+ UINT increment = 0;
+ uint32_t slots = 0, parity = 0;
+ bool ready = false;
+
+ // ------------------------------------------------------------------ plan
+ uint32_t allocate(size_t float4s)
+ {
+ const size_t at = weights.size() / 4;
+ weights.resize(weights.size() + float4s * 4, 0.0f);
+ return uint32_t(at);
+ }
+ float& weight(uint32_t float4Index, uint32_t component) { return weights[size_t(float4Index) * 4 + component]; }
+
+ // Convolution [O, k, k, I] (TFLite OHWI) and its bias.
+ void packConv(const TfliteTensor& w, const TfliteTensor& b, Layer& l)
+ {
+ const uint32_t o = uint32_t(w.shape[0]), k = uint32_t(w.shape[1]), in = uint32_t(w.shape[3]);
+ const uint32_t oq = (o + 3) / 4, iq = (in + 3) / 4;
+ l.wOff = allocate(size_t(oq) * k * k * iq * 4);
+ for (uint32_t q = 0; q < oq; ++q)
+ for (uint32_t ky = 0; ky < k; ++ky)
+ for (uint32_t kx = 0; kx < k; ++kx)
+ for (uint32_t c = 0; c < in; ++c)
+ for (uint32_t j = 0; j < 4 && 4 * q + j < o; ++j)
+ weight(l.wOff + ((q * k + ky) * k + kx) * iq * 4 + c, j) = w.floats[((size_t(4 * q + j) * k + ky) * k + kx) * in + c];
+ l.bOff = allocate(oq);
+ for (uint32_t c = 0; c < o; ++c) weight(l.bOff + c / 4, c % 4) = b.floats[c];
+ }
+ // Depthwise [1, 3, 3, C] and its bias.
+ void packDepthwise(const TfliteTensor& w, const TfliteTensor& b, Layer& l)
+ {
+ const uint32_t channels = uint32_t(w.shape[3]), cq = (channels + 3) / 4;
+ l.wOff = allocate(size_t(cq) * 9);
+ for (uint32_t tap = 0; tap < 9; ++tap)
+ for (uint32_t c = 0; c < channels; ++c) weight(l.wOff + (c / 4) * 9 + tap, c % 4) = w.floats[size_t(tap) * channels + c];
+ l.bOff = allocate(cq);
+ for (uint32_t c = 0; c < channels; ++c) weight(l.bOff + c / 4, c % 4) = b.floats[c];
+ }
+
+ int newTensor(uint32_t w, uint32_t h, uint32_t channels)
+ {
+ Tensor t;
+ t.w = w; t.h = h; t.q = (channels + 3) / 4;
+ tensors.push_back(t);
+ return int(tensors.size()) - 1;
+ }
+
+ // The network as fused layers: every convolution, with the residual add (of the
+ // block input itself, or of its 2x2 max-pool, channel padded) and the PReLU that
+ // follow it folded into the 1x1 convolution. MAX_POOL / PAD / ADD / PRELU appear
+ // only inside those patterns; anything else is refused.
+ bool buildPlan(const TfliteModel& m, std::string& error)
+ {
+ const size_t tensorCount = m.tensors.size();
+ std::vector<std::vector<int>> consumers(tensorCount);
+ std::vector<int> producer(tensorCount, -1);
+ for (size_t i = 0; i < m.operators.size(); ++i) {
+ for (const auto t : m.operators[i].inputs) if (t >= 0) consumers[size_t(t)].push_back(int(i));
+ for (const auto t : m.operators[i].outputs) producer[size_t(t)] = int(i);
+ }
+ const auto single = [&](int t) { return consumers[size_t(t)].size() == 1 ? consumers[size_t(t)][0] : -1; };
+ const auto shapeOf = [&](int t, uint32_t& w, uint32_t& h, uint32_t& c) {
+ const auto& s = m.tensors[size_t(t)].shape;
+ if (s.size() != 4 || s[0] != 1 || s[1] <= 0 || s[2] <= 0 || s[3] <= 0) return false;
+ h = uint32_t(s[1]); w = uint32_t(s[2]); c = uint32_t(s[3]);
+ return true;
+ };
+ if (m.tensors[size_t(m.inputs[0])].shape != std::vector<int32_t>{1, int32_t(kSide), int32_t(kSide), 3}) {
+ error = "model input is not 1 x 192 x 192 x 3"; return false;
+ }
+ std::vector<int> gpu(tensorCount, -1);
+ inputTensor = newTensor(kSide, kSide, 3);
+ gpu[size_t(m.inputs[0])] = inputTensor;
+ std::vector<bool> done(m.operators.size(), false);
+ for (size_t i = 0; i < m.operators.size(); ++i) {
+ if (done[i]) continue;
+ const TfliteOperator& op = m.operators[i];
+ // A shortcut's max-pool / padding may come before the 1x1 convolution that
+ // takes them in; every operator must have been taken in by the end.
+ if (op.op == TfliteOp::MaxPool2D || op.op == TfliteOp::Pad) continue;
+ if (op.op != TfliteOp::Conv2D && op.op != TfliteOp::DepthwiseConv2D) {
+ error = std::format("operator {} is outside a supported block", i); return false;
+ }
+ if (op.inputs.size() < 3 || op.inputs[0] < 0 || gpu[size_t(op.inputs[0])] < 0 || op.inputs[1] < 0 || op.inputs[2] < 0 ||
+ op.outputs.size() != 1) {
+ error = std::format("convolution {} input is not available", i); return false;
+ }
+ const TfliteTensor& w = m.tensors[size_t(op.inputs[1])];
+ const TfliteTensor& b = m.tensors[size_t(op.inputs[2])];
+ uint32_t inW, inH, inC, outW, outH, outC;
+ if (w.floats.empty() || b.floats.empty() || op.activation != 0 || op.dilationW != 1 || op.dilationH != 1 ||
+ op.strideW != op.strideH || op.strideW < 1 || op.strideW > 3 ||
+ !shapeOf(op.inputs[0], inW, inH, inC) || !shapeOf(op.outputs[0], outW, outH, outC) || b.floats.size() != outC) {
+ error = std::format("convolution {} has an unsupported configuration", i); return false;
+ }
+ Layer layer;
+ layer.in = gpu[size_t(op.inputs[0])];
+ layer.stride = uint32_t(op.strideW);
+ if (op.op == TfliteOp::Conv2D) {
+ if (w.shape.size() != 4 || uint32_t(w.shape[0]) != outC || uint32_t(w.shape[3]) != inC || w.shape[1] != w.shape[2] ||
+ w.shape[1] < 1 || w.shape[1] > 3) {
+ error = std::format("convolution {} weights", i); return false;
+ }
+ layer.kernel = uint32_t(w.shape[1]);
+ layer.kind = layer.kernel == 1 && layer.stride == 1 ? Kind::Pointwise : Kind::Conv;
+ packConv(w, b, layer);
+ } else {
+ if (w.shape != std::vector<int32_t>{1, 3, 3, int32_t(inC)} || op.depthMultiplier != 1 || inC != outC) {
+ error = std::format("depthwise convolution {} weights", i); return false;
+ }
+ layer.kernel = 3;
+ layer.kind = Kind::Depthwise;
+ packDepthwise(w, b, layer);
+ }
+ // TensorFlow SAME: the odd pixel of the padding goes to the bottom / right.
+ const auto expected = [&](uint32_t size) {
+ return op.samePadding ? (size + layer.stride - 1) / layer.stride : (size - layer.kernel) / layer.stride + 1;
+ };
+ if (outW != expected(inW) || outH != expected(inH)) { error = std::format("convolution {} output size", i); return false; }
+ if (op.samePadding) {
+ const auto pad = [&](uint32_t size, uint32_t out) {
+ const int64_t total = std::max<int64_t>(int64_t(out - 1) * layer.stride + layer.kernel - size, 0);
+ return uint32_t(total / 2);
+ };
+ layer.padTop = pad(inH, outH);
+ layer.padLeft = pad(inW, outW);
+ }
+ int finalOut = op.outputs[0];
+ int next = single(finalOut);
+ if (layer.kind == Kind::Pointwise && next >= 0 && m.operators[size_t(next)].op == TfliteOp::Add) {
+ const TfliteOperator& add = m.operators[size_t(next)];
+ if (add.inputs.size() != 2 || add.activation != 0) { error = std::format("residual add {}", next); return false; }
+ const int other = add.inputs[0] == finalOut ? add.inputs[1] : add.inputs[0];
+ if (other >= 0 && gpu[size_t(other)] >= 0) {
+ const Tensor& r = tensors[size_t(gpu[size_t(other)])];
+ if (r.w != outW || r.h != outH || r.q != (outC + 3) / 4) { error = std::format("residual add {} shapes", next); return false; }
+ layer.res = gpu[size_t(other)];
+ layer.residual = 1;
+ } else {
+ int pool = other >= 0 ? producer[size_t(other)] : -1, padOp = -1;
+ if (pool >= 0 && m.operators[size_t(pool)].op == TfliteOp::Pad) {
+ padOp = pool;
+ const TfliteOperator& pad = m.operators[size_t(padOp)];
+ const auto& pads = pad.inputs.size() == 2 && pad.inputs[1] >= 0 ? m.tensors[size_t(pad.inputs[1])].ints : std::vector<int32_t>{};
+ if (pads.size() != 8 || pads[0] || pads[1] || pads[2] || pads[3] || pads[4] || pads[5] || pads[6] || pads[7] < 0 ||
+ single(pad.inputs[0]) != padOp) {
+ error = std::format("shortcut padding {}", padOp); return false;
+ }
+ pool = producer[size_t(pad.inputs[0])];
+ }
+ if (pool < 0 || m.operators[size_t(pool)].op != TfliteOp::MaxPool2D) { error = std::format("residual add {} input", next); return false; }
+ const TfliteOperator& mp = m.operators[size_t(pool)];
+ if (mp.filterW != 2 || mp.filterH != 2 || mp.strideW != 2 || mp.strideH != 2 || mp.samePadding || mp.activation ||
+ mp.inputs.empty() || mp.inputs[0] < 0 || gpu[size_t(mp.inputs[0])] < 0 || single(mp.outputs[0]) != (padOp >= 0 ? padOp : next)) {
+ error = std::format("shortcut pooling {}", pool); return false;
+ }
+ const int source = gpu[size_t(mp.inputs[0])];
+ const Tensor& r = tensors[size_t(source)];
+ if (r.w != outW * 2 || r.h != outH * 2 || r.q > (outC + 3) / 4) { error = std::format("shortcut pooling {} shapes", pool); return false; }
+ layer.res = source;
+ layer.residual = 2;
+ done[size_t(pool)] = true;
+ if (padOp >= 0) done[size_t(padOp)] = true;
+ }
+ done[size_t(next)] = true;
+ finalOut = add.outputs[0];
+ next = single(finalOut);
+ }
+ if (next >= 0 && m.operators[size_t(next)].op == TfliteOp::Prelu) {
+ const TfliteOperator& prelu = m.operators[size_t(next)];
+ if (prelu.inputs.size() != 2 || prelu.inputs[1] < 0 || m.tensors[size_t(prelu.inputs[1])].floats.size() != outC) {
+ error = std::format("PReLU {} slopes", next); return false;
+ }
+ const auto& slopes = m.tensors[size_t(prelu.inputs[1])].floats;
+ layer.aOff = allocate((outC + 3) / 4);
+ for (uint32_t c = 0; c < outC; ++c) weight(layer.aOff + c / 4, c % 4) = slopes[c];
+ done[size_t(next)] = true;
+ finalOut = prelu.outputs[0];
+ }
+ layer.out = newTensor(outW, outH, outC);
+ gpu[size_t(finalOut)] = layer.out;
+ layers.push_back(layer);
+ done[i] = true;
+ }
+ for (size_t i = 0; i < m.operators.size(); ++i)
+ if (!done[i]) { error = std::format("operator {} is not part of a supported block", i); return false; }
+ for (const auto output : m.outputs) {
+ uint32_t w, h, c;
+ if (output < 0 || gpu[size_t(output)] < 0 || !shapeOf(output, w, h, c) || w != 1 || h != 1) { error = "model outputs"; return false; }
+ if (c == kLandmarkValues) landmarkTensor = gpu[size_t(output)];
+ else if (c == 1) flagTensor = gpu[size_t(output)];
+ }
+ if (landmarkTensor < 0 || flagTensor < 0) { error = "expected a 1404-value landmark output and a face flag"; return false; }
+ tensors[size_t(landmarkTensor)].pinned = tensors[size_t(flagTensor)].pinned = true;
+ for (size_t i = 0; i < layers.size(); ++i) {
+ tensors[size_t(layers[i].in)].lastRead = int(i);
+ if (layers[i].res >= 0) tensors[size_t(layers[i].res)].lastRead = int(i);
+ }
+ return true;
+ }
+
+ // Tensor placement in the scratch buffer (after the crop parameters): first fit,
+ // reusing the space of tensors no later layer reads.
+ void placeTensors()
+ {
+ struct Block { uint64_t offset, size; int tensor; };
+ std::vector<Block> live;
+ uint64_t end = kCropFloat4s;
+ const auto place = [&](int t) {
+ const uint64_t size = tensors[size_t(t)].float4s();
+ std::sort(live.begin(), live.end(), [](const Block& a, const Block& b) { return a.offset < b.offset; });
+ uint64_t at = kCropFloat4s;
+ for (const auto& b : live) {
+ if (at + size <= b.offset) break;
+ at = std::max(at, b.offset + b.size);
+ }
+ tensors[size_t(t)].offset = at;
+ live.push_back({at, size, t});
+ end = std::max(end, at + size);
+ };
+ place(inputTensor);
+ for (size_t i = 0; i < layers.size(); ++i) {
+ std::erase_if(live, [&](const Block& b) { const Tensor& t = tensors[size_t(b.tensor)]; return !t.pinned && t.lastRead < int(i); });
+ place(layers[i].out);
+ }
+ scratchFloat4s = end;
+ }
+
+ // ------------------------------------------------------------- resources
+ bool upload(ID3D12CommandQueue* queue, std::string& error)
+ {
+ const uint64_t bytes = uint64_t(weights.size()) * 4;
+ weightBuffer = makeBuffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);
+ auto staged = makeBuffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ);
+ if (!weightBuffer || !staged) { error = "weight buffer allocation failed"; return false; }
+ void* mapped = nullptr;
+ if (FAILED(staged->Map(0, nullptr, &mapped))) { error = "weight upload map failed"; return false; }
+ std::memcpy(mapped, weights.data(), size_t(bytes));
+ staged->Unmap(0, nullptr);
+ Submit s;
+ if (!s.open(device)) { error = "weight upload list creation failed"; return false; }
+ s.list->CopyBufferRegion(weightBuffer.Get(), 0, staged.Get(), 0, bytes);
+ barrier(s.list.Get(), weightBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ if (!s.run(queue)) { error = "weight upload timed out"; return false; }
+ return true;
+ }
+
+ bool createPipelines(std::string& error)
+ {
+ D3D12_DESCRIPTOR_RANGE1 srv{};
+ srv.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ srv.NumDescriptors = kSrvs;
+ srv.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE;
+ D3D12_DESCRIPTOR_RANGE1 uav{};
+ uav.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
+ uav.NumDescriptors = kUavs;
+ uav.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE;
+ D3D12_ROOT_PARAMETER1 rp[3]{};
+ rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
+ rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rp[0].Constants.Num32BitValues = kConstantDwords;
+ rp[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rp[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rp[1].DescriptorTable.NumDescriptorRanges = 1;
+ rp[1].DescriptorTable.pDescriptorRanges = &srv;
+ rp[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rp[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rp[2].DescriptorTable.NumDescriptorRanges = 1;
+ rp[2].DescriptorTable.pDescriptorRanges = &uav;
+ D3D12_VERSIONED_ROOT_SIGNATURE_DESC rd{};
+ rd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
+ rd.Desc_1_1.NumParameters = 3;
+ rd.Desc_1_1.pParameters = rp;
+ ComPtr<ID3DBlob> blob, message;
+ if (FAILED(D3D12SerializeVersionedRootSignature(&rd, &blob, &message)) ||
+ FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)))) {
+ error = "face mesh root signature creation failed"; return false;
+ }
+ for (size_t k = 0; k < size_t(Kind::Count); ++k) {
+ std::vector<uint8_t> code;
+ if (!pipeline::loadShaderBytes(kShaderFile[k], code)) { error = std::string("shader missing: ") + kShaderFile[k]; return false; }
+ D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
+ pd.pRootSignature = root.Get();
+ pd.CS = {code.data(), code.size()};
+ if (FAILED(device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pipelines[k])))) {
+ error = std::string("face mesh pipeline failed: ") + kShaderFile[k]; return false;
+ }
+ }
+ return true;
+ }
+
+ D3D12_CPU_DESCRIPTOR_HANDLE cpuAt(UINT index) const
+ {
+ auto h = heap->GetCPUDescriptorHandleForHeapStart();
+ h.ptr += SIZE_T(index) * increment;
+ return h;
+ }
+ D3D12_GPU_DESCRIPTOR_HANDLE gpuAt(UINT index) const
+ {
+ auto h = heap->GetGPUDescriptorHandleForHeapStart();
+ h.ptr += UINT64(index) * increment;
+ return h;
+ }
+
+ bool createDescriptors(std::string& error)
+ {
+ D3D12_DESCRIPTOR_HEAP_DESC hd{};
+ hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ hd.NumDescriptors = slots * kPerSlot;
+ hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
+ D3D12_DESCRIPTOR_HEAP_DESC sd = hd;
+ sd.NumDescriptors = slots;
+ sd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
+ if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap))) || FAILED(device->CreateDescriptorHeap(&sd, IID_PPV_ARGS(&staging)))) {
+ error = "face mesh descriptor heap creation failed"; return false;
+ }
+ increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ const auto structuredSrv = [&](ID3D12Resource* r, UINT elements, UINT stride, UINT at) {
+ D3D12_SHADER_RESOURCE_VIEW_DESC d{};
+ d.Format = DXGI_FORMAT_UNKNOWN;
+ d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ d.Buffer.NumElements = elements;
+ d.Buffer.StructureByteStride = stride;
+ device->CreateShaderResourceView(r, &d, cpuAt(at));
+ };
+ const auto structuredUav = [&](ID3D12Resource* r, UINT elements, UINT stride, UINT at) {
+ D3D12_UNORDERED_ACCESS_VIEW_DESC d{};
+ d.Format = DXGI_FORMAT_UNKNOWN;
+ d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ d.Buffer.NumElements = elements;
+ d.Buffer.StructureByteStride = stride;
+ device->CreateUnorderedAccessView(r, nullptr, &d, cpuAt(at));
+ };
+ for (uint32_t s = 0; s < slots; ++s) {
+ const UINT base = s * kPerSlot;
+ structuredSrv(weightBuffer.Get(), UINT(weights.size() / 4), 16, base);
+ structuredSrv(faces, 1 + kMaxFaces, 64, base + 1);
+ // t2 (the source picture) is written for every recorded frame; a null view until then.
+ D3D12_SHADER_RESOURCE_VIEW_DESC nd{};
+ nd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
+ nd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
+ nd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ nd.Texture2D.MipLevels = 1;
+ device->CreateShaderResourceView(nullptr, &nd, cpuAt(base + 2));
+ structuredUav(scratch.Get(), UINT(scratchFloat4s), 16, base + 3);
+ structuredUav(shapes, kMaxFaces * kShapeEntries, 8, base + 4);
+ structuredUav(state.Get(), UINT(kStateFloat4s), 16, base + 5);
+ }
+ return true;
+ }
+
+ // ----------------------------------------------------------------- record
+ void dispatch(ID3D12GraphicsCommandList* list, uint32_t slot, Kind kind, const uint32_t* constants, uint32_t groupsX, uint32_t groupsZ)
+ {
+ list->SetPipelineState(pipelines[size_t(kind)].Get());
+ list->SetComputeRoot32BitConstants(0, kConstantDwords, constants, 0);
+ list->SetComputeRootDescriptorTable(1, gpuAt(slot * kPerSlot));
+ list->SetComputeRootDescriptorTable(2, gpuAt(slot * kPerSlot + kSrvs));
+ list->Dispatch(groupsX, 1, groupsZ);
+ }
+
+ void recordLayers(ID3D12GraphicsCommandList* list, uint32_t slot, uint32_t capacity, uint32_t forced)
+ {
+ for (const auto& l : layers) {
+ const Tensor& in = tensors[size_t(l.in)];
+ const Tensor& out = tensors[size_t(l.out)];
+ uint32_t c[kConstantDwords]{};
+ c[0] = in.w; c[1] = in.h; c[2] = in.q;
+ c[3] = out.w; c[4] = out.h; c[5] = out.q;
+ c[6] = l.wOff; c[7] = l.bOff; c[8] = l.aOff;
+ c[9] = uint32_t(in.offset); c[10] = uint32_t(out.offset);
+ c[11] = l.res >= 0 ? uint32_t(tensors[size_t(l.res)].offset) : 0u;
+ c[12] = (l.res >= 0 ? tensors[size_t(l.res)].q : 0u) | (l.residual << 16);
+ c[13] = l.kernel | (l.stride << 8) | (l.padTop << 16) | (l.padLeft << 24);
+ c[14] = capacity; c[15] = forced;
+ dispatch(list, slot, l.kind, c, (out.w * out.h * out.q + 63) / 64, capacity);
+ uavBarrier(list, scratch.Get());
+ }
+ }
+};
+
+FaceMeshGpu::FaceMeshGpu() : impl_(std::make_unique<Impl>()) {}
+FaceMeshGpu::~FaceMeshGpu() = default;
+bool FaceMeshGpu::ready() const { return impl_ && impl_->ready; }
+const std::string& FaceMeshGpu::description() const { return impl_->description; }
+
+bool FaceMeshGpu::initialize(ID3D12Device* device, const std::filesystem::path& model, ID3D12Resource* faces, ID3D12Resource* shapes,
+ uint32_t ringSlots, std::string& error)
+{
+ shutdown();
+ if (!device || !faces || !shapes || !ringSlots) { error = "invalid face mesh configuration"; return false; }
+ if (model.empty()) { error = "face mesh model file not found"; return false; }
+ TfliteModel m;
+ if (!loadTflite(model, m, error)) return false;
+ Impl& d = *impl_;
+ d.device = device;
+ d.faces = faces;
+ d.shapes = shapes;
+ d.slots = ringSlots;
+ if (!d.buildPlan(m, error)) { shutdown(); return false; }
+ d.placeTensors();
+ d.scratch = makeBuffer(device, d.scratchFloat4s * 16, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+ D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ d.state = makeBuffer(device, kStateFloat4s * 16, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+ D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ if (!d.scratch || !d.state) { error = "face mesh buffer allocation failed"; shutdown(); return false; }
+ ComPtr<ID3D12CommandQueue> queue;
+ D3D12_COMMAND_QUEUE_DESC qd{};
+ qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
+ if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue))) || !d.upload(queue.Get(), error) || !d.createPipelines(error) ||
+ !d.createDescriptors(error)) {
+ if (error.empty()) error = "face mesh upload queue creation failed";
+ shutdown();
+ return false;
+ }
+ d.description = std::format("MediaPipe face mesh: {} operators, {} GPU layers, {} weights, scratch {:.1f} MiB for {} faces",
+ m.operators.size(), d.layers.size(), d.weights.size(), double(d.scratchFloat4s) * 16.0 / 1048576.0, kMaxFaces);
+ d.ready = true;
+ log::info("beauty-mesh", d.description + "; model " + model.filename().string());
+ return true;
+}
+
+void FaceMeshGpu::shutdown()
+{
+ *impl_ = Impl{};
+}
+
+bool FaceMeshGpu::record(ID3D12GraphicsCommandList* list, pipeline::StateTracker& tracker, const Frame& f)
+{
+ Impl& d = *impl_;
+ if (!d.ready || !list || f.slot >= d.slots || !f.source || !f.width || !f.height) return false;
+ // The source picture of this frame into the slot's t2.
+ D3D12_SHADER_RESOURCE_VIEW_DESC sd{};
+ sd.Format = f.source->GetDesc().Format;
+ sd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
+ sd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ sd.Texture2D.MipLevels = 1;
+ auto staged = d.staging->GetCPUDescriptorHandleForHeapStart();
+ staged.ptr += SIZE_T(f.slot) * d.increment;
+ d.device->CreateShaderResourceView(f.source, &sd, staged);
+ d.device->CopyDescriptorsSimple(1, d.cpuAt(f.slot * kPerSlot + 2), staged, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+
+ ID3D12DescriptorHeap* heaps[] = {d.heap.Get()};
+ list->SetDescriptorHeaps(1, heaps);
+ list->SetComputeRootSignature(d.root.Get());
+ tracker.transition(list, d.faces, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker.transition(list, f.source, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker.transition(list, d.shapes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const uint32_t capacity = std::clamp(f.maxFaces, 1u, kMaxFaces);
+ uint32_t c[kConstantDwords]{};
+ c[0] = f.width; c[1] = f.height; c[2] = f.hdr ? 1u : 0u;
+ c[3] = kSide; c[4] = kSide; c[5] = 1;
+ c[6] = bitsOf(kCropScale);
+ c[10] = uint32_t(d.tensors[size_t(d.inputTensor)].offset);
+ c[11] = 0; // crop parameters at the start of the scratch buffer
+ c[14] = capacity;
+ d.dispatch(list, f.slot, Kind::Crop, c, (kSide * kSide + 63) / 64, capacity);
+ uavBarrier(list, d.scratch.Get());
+ d.recordLayers(list, f.slot, capacity, 0);
+ uint32_t k[kConstantDwords]{};
+ k[0] = f.width; k[1] = f.height;
+ k[6] = bitsOf(f.restCutoff); k[7] = bitsOf(f.speedFactor); k[8] = bitsOf(f.speedCutoff);
+ k[9] = uint32_t(d.tensors[size_t(d.landmarkTensor)].offset);
+ k[10] = uint32_t(d.tensors[size_t(d.flagTensor)].offset);
+ k[11] = 0;
+ k[12] = bitsOf(f.dtMs);
+ k[13] = (f.reset ? 1u : 0u) | (f.still ? 2u : 0u) | (d.parity << 2);
+ k[14] = capacity;
+ d.dispatch(list, f.slot, Kind::Decode, k, 1, kMaxFaces); // every slot: empty ones are marked "no mesh"
+ uavBarrier(list, d.state.Get());
+ tracker.uavBarrier(list, d.shapes);
+ tracker.transition(list, d.shapes, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ d.parity ^= 1u;
+ return true;
+}
+
+bool FaceMeshGpu::runNetwork(ID3D12CommandQueue* queue, const std::vector<float>& input, uint32_t count, std::vector<float>& output,
+ std::string& error)
+{
+ Impl& d = *impl_;
+ const size_t perFace = size_t(kSide) * kSide * 3;
+ if (!d.ready || !queue || !count || count > kMaxFaces || input.size() != perFace * count) { error = "invalid network test input"; return false; }
+ const Tensor& in = d.tensors[size_t(d.inputTensor)];
+ const Tensor& landmarks = d.tensors[size_t(d.landmarkTensor)];
+ const Tensor& flag = d.tensors[size_t(d.flagTensor)];
+ // Input: channel-last RGB -> one float4 per pixel, faces one after the other.
+ const uint64_t inputBytes = uint64_t(count) * kSide * kSide * 16;
+ auto upload = makeBuffer(d.device, inputBytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ);
+ const uint64_t landmarkBytes = uint64_t(count) * landmarks.q * 16, flagBytes = uint64_t(count) * flag.q * 16;
+ auto readback = makeBuffer(d.device, landmarkBytes + flagBytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);
+ if (!upload || !readback) { error = "network test buffers"; return false; }
+ float* mapped = nullptr;
+ if (FAILED(upload->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) { error = "network test map"; return false; }
+ for (size_t p = 0; p < size_t(count) * kSide * kSide; ++p) {
+ mapped[p * 4] = input[p * 3]; mapped[p * 4 + 1] = input[p * 3 + 1]; mapped[p * 4 + 2] = input[p * 3 + 2]; mapped[p * 4 + 3] = 0.0f;
+ }
+ upload->Unmap(0, nullptr);
+ Submit s;
+ if (!s.open(d.device)) { error = "network test list"; return false; }
+ ID3D12GraphicsCommandList* list = s.list.Get();
+ barrier(list, d.scratch.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST);
+ list->CopyBufferRegion(d.scratch.Get(), in.offset * 16, upload.Get(), 0, inputBytes);
+ barrier(list, d.scratch.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ ID3D12DescriptorHeap* heaps[] = {d.heap.Get()};
+ list->SetDescriptorHeaps(1, heaps);
+ list->SetComputeRootSignature(d.root.Get());
+ barrier(list, d.faces, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ d.recordLayers(list, 0, count, count);
+ barrier(list, d.faces, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON);
+ barrier(list, d.scratch.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
+ list->CopyBufferRegion(readback.Get(), 0, d.scratch.Get(), landmarks.offset * 16, landmarkBytes);
+ list->CopyBufferRegion(readback.Get(), landmarkBytes, d.scratch.Get(), flag.offset * 16, flagBytes);
+ barrier(list, d.scratch.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ if (!s.run(queue)) { error = "network test timed out"; return false; }
+ const float* result = nullptr;
+ D3D12_RANGE range{0, SIZE_T(landmarkBytes + flagBytes)};
+ if (FAILED(readback->Map(0, &range, reinterpret_cast<void**>(const_cast<float**>(&result))))) { error = "network test readback"; return false; }
+ output.assign(size_t(count) * (kLandmarkValues + 1), 0.0f);
+ for (uint32_t face = 0; face < count; ++face) {
+ std::memcpy(output.data() + size_t(face) * (kLandmarkValues + 1), result + size_t(face) * landmarks.q * 4, kLandmarkValues * 4);
+ output[size_t(face) * (kLandmarkValues + 1) + kLandmarkValues] = result[landmarkBytes / 4 + size_t(face) * flag.q * 4];
+ }
+ D3D12_RANGE none{0, 0};
+ readback->Unmap(0, &none);
+ return true;
+}
+
+} // namespace veyra::beauty
diff --git a/src/beauty/FaceTracker.cpp b/src/beauty/FaceTracker.cpp
index bcfd5118..d589bb7d 100644
--- a/src/beauty/FaceTracker.cpp
+++ b/src/beauty/FaceTracker.cpp
@@ -61,7 +61,9 @@ bool FaceTracker::initialize(ID3D12Device* device, const std::filesystem::path&
}
faces_ = makeBuffer(device, kFaceEntries * kFaceBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COMMON);
- if (!faces_) { error = "face buffer allocation failed"; shutdown(); return false; }
+ shapes_ = makeBuffer(device, FaceMeshGpu::kShapeBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+ D3D12_RESOURCE_STATE_COMMON);
+ if (!faces_ || !shapes_) { error = "face buffer allocation failed"; shutdown(); return false; }
D3D12_DESCRIPTOR_HEAP_DESC sd{};
sd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; sd.NumDescriptors = 1; sd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
if (FAILED(device->CreateDescriptorHeap(&sd, IID_PPV_ARGS(&staging_)))) { error = "face tracker descriptor heap failed"; shutdown(); return false; }
@@ -95,6 +97,12 @@ bool FaceTracker::initialize(ID3D12Device* device, const std::filesystem::path&
pending_.assign(ringSlots, false);
slots_ = ringSlots;
ready_ = true;
+ // The face mesh is optional: without it every face keeps the oval from its box.
+ std::string meshError;
+ meshReady_ = mesh_.initialize(device, locateFaceMeshModel(), faces_.Get(), shapes_.Get(), ringSlots, meshError);
+ shapesClear_ = makeBuffer(device, FaceMeshGpu::kShapeBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON);
+ meshReady_ = meshReady_ && shapesClear_;
+ if (!meshReady_) log::warn("beauty-mesh", "face mesh unavailable (" + meshError + "); faces keep the oval from their box");
log::info("beauty-detect", std::format("face tracker ready: {}; model {}; slots {}", detector_.modelDescription(),
model.filename().string(), ringSlots));
return true;
@@ -102,6 +110,10 @@ bool FaceTracker::initialize(ID3D12Device* device, const std::filesystem::path&
void FaceTracker::shutdown()
{
+ mesh_.shutdown();
+ shapes_.Reset();
+ shapesClear_.Reset();
+ meshReady_ = meshCleared_ = false;
detector_.shutdown();
track_ = {};
staging_.Reset();
@@ -172,6 +184,29 @@ bool FaceTracker::record(ID3D12GraphicsCommandList* list, pipeline::StateTracker
list->CopyBufferRegion(readbacks_[f.slot].Get(), 0, faces_.Get(), 0, kFaceBytes);
tracker.transition(list, faces_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
pending_[f.slot] = true;
+ // The outlines of this frame's tracks, smoothed like the tracks themselves. While the
+ // status of the last frames reports no face, the mesh's ~45 dispatches would find
+ // only empty slots: its outlines are cleared once instead, and a face that appears
+ // meanwhile keeps the oval from its box until the mesh runs again (a few frames,
+ // during its fade-in). Resets and pictures always run it.
+ const bool meshWanted = f.reset || f.still || faceCount_ > 0 || detections_ <= slots_;
+ if (meshReady_ && detect && !meshWanted && !meshCleared_) {
+ tracker.transition(list, shapes_.Get(), D3D12_RESOURCE_STATE_COPY_DEST);
+ tracker.transition(list, shapesClear_.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);
+ list->CopyBufferRegion(shapes_.Get(), 0, shapesClear_.Get(), 0, FaceMeshGpu::kShapeBytes);
+ tracker.transition(list, shapes_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ meshCleared_ = true;
+ }
+ if (meshReady_ && detect && meshWanted) {
+ meshCleared_ = false;
+ FaceMeshGpu::Frame m;
+ m.source = f.source; m.width = f.width; m.height = f.height; m.hdr = f.hdr; m.slot = f.slot;
+ m.maxFaces = detection_.maxFaces; m.dtMs = float(dt); m.reset = f.reset; m.still = f.still;
+ m.restCutoff = 3.0f + (0.3f - 3.0f) * stability;
+ m.speedFactor = 20.0f + (6.0f - 20.0f) * stability;
+ m.speedCutoff = 4.0f;
+ if (!mesh_.record(list, tracker, m)) log::warn("beauty-mesh", "face mesh could not be recorded for this frame");
+ }
if (!sameFrame) { lastPts_ = f.ptsMs; lastFrameId_ = f.frameId; }
haveFrame_ = true;
return true;
diff --git a/src/beauty/TfliteLite.cpp b/src/beauty/TfliteLite.cpp
new file mode 100644
index 00000000..2fd89e9a
--- /dev/null
+++ b/src/beauty/TfliteLite.cpp
@@ -0,0 +1,242 @@
+#include "veyra/beauty/TfliteLite.h"
+
+#include <algorithm>
+#include <cstring>
+#include <format>
+#include <fstream>
+#include <limits>
+
+namespace veyra::beauty {
+namespace {
+// Flatbuffer cursor over the whole file. Every read is bounds checked; a malformed
+// or truncated file turns into a clean error instead of an out-of-range access.
+struct Buffer {
+ const std::vector<uint8_t>& bytes;
+ bool bad = false;
+
+ bool fits(size_t offset, size_t size) const { return offset <= bytes.size() && size <= bytes.size() - offset; }
+ template <typename T> T read(size_t offset)
+ {
+ T value{};
+ if (!fits(offset, sizeof(T))) { bad = true; return value; }
+ std::memcpy(&value, bytes.data() + offset, sizeof(T));
+ return value;
+ }
+ // uoffset at `offset` -> absolute position of what it points to.
+ size_t follow(size_t offset)
+ {
+ const uint32_t delta = read<uint32_t>(offset);
+ if (bad || !fits(offset, size_t(delta))) { bad = true; return 0; }
+ return offset + delta;
+ }
+};
+
+// One flatbuffer table: field accessors by field id.
+struct Table {
+ Buffer* b = nullptr;
+ size_t at = 0, vtable = 0;
+ uint16_t vtableSize = 0;
+
+ static Table open(Buffer& b, size_t at)
+ {
+ Table t;
+ t.b = &b;
+ t.at = at;
+ const int32_t back = b.read<int32_t>(at);
+ const int64_t vt = int64_t(at) - int64_t(back);
+ if (b.bad || vt < 0 || !b.fits(size_t(vt), 4)) { b.bad = true; return t; }
+ t.vtable = size_t(vt);
+ t.vtableSize = b.read<uint16_t>(t.vtable);
+ return t;
+ }
+ // Absolute position of a field, 0 when it is absent.
+ size_t field(int id) const
+ {
+ if (!b || b->bad) return 0;
+ const size_t slot = 4 + 2 * size_t(id);
+ if (slot + 2 > vtableSize) return 0;
+ const uint16_t offset = b->read<uint16_t>(vtable + slot);
+ return offset ? at + offset : 0;
+ }
+ template <typename T> T scalar(int id, T fallback) const
+ {
+ const size_t f = field(id);
+ return f ? b->read<T>(f) : fallback;
+ }
+ Table table(int id) const
+ {
+ const size_t f = field(id);
+ if (!f) return {};
+ return open(*b, b->follow(f));
+ }
+ // Vector of `id`: element count and the position of the first element.
+ bool vector(int id, size_t& first, uint32_t& count, size_t elementSize) const
+ {
+ first = 0; count = 0;
+ const size_t f = field(id);
+ if (!f) return false;
+ const size_t v = b->follow(f);
+ count = b->read<uint32_t>(v);
+ first = v + 4;
+ if (b->bad || !b->fits(first, size_t(count) * elementSize)) { b->bad = true; count = 0; return false; }
+ return true;
+ }
+ std::vector<int32_t> ints(int id) const
+ {
+ size_t first; uint32_t count;
+ std::vector<int32_t> out;
+ if (!vector(id, first, count, 4)) return out;
+ out.resize(count);
+ for (uint32_t i = 0; i < count; ++i) out[i] = b->read<int32_t>(first + 4 * size_t(i));
+ return out;
+ }
+ std::string string(int id) const
+ {
+ size_t first; uint32_t count;
+ if (!vector(id, first, count, 1)) return {};
+ return std::string(reinterpret_cast<const char*>(b->bytes.data() + first), count);
+ }
+ Table element(int id, uint32_t index) const
+ {
+ size_t first; uint32_t count;
+ if (!vector(id, first, count, 4) || index >= count) return {};
+ return open(*b, b->follow(first + 4 * size_t(index)));
+ }
+ uint32_t count(int id) const
+ {
+ size_t first; uint32_t n;
+ vector(id, first, n, 4);
+ return n;
+ }
+ bool valid() const { return b && !b->bad; }
+};
+
+float halfToFloat(uint16_t h)
+{
+ const uint32_t sign = uint32_t(h >> 15) << 31;
+ uint32_t exponent = (h >> 10) & 0x1f, mantissa = h & 0x3ff, bits;
+ if (exponent == 0) {
+ if (mantissa == 0) bits = sign;
+ else { // subnormal: renormalise
+ exponent = 113;
+ while (!(mantissa & 0x400)) { mantissa <<= 1; --exponent; }
+ bits = sign | (exponent << 23) | ((mantissa & 0x3ff) << 13);
+ }
+ } else if (exponent == 31) bits = sign | 0x7f800000u | (mantissa << 13);
+ else bits = sign | ((exponent + 112) << 23) | (mantissa << 13);
+ float f;
+ std::memcpy(&f, &bits, 4);
+ return f;
+}
+} // namespace
+
+bool loadTflite(const std::filesystem::path& path, TfliteModel& model, std::string& error)
+{
+ model = {};
+ std::ifstream file(path, std::ios::binary);
+ if (!file) { error = "cannot open " + path.filename().string(); return false; }
+ std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(file)), {});
+ if (bytes.size() < 16 || bytes.size() > (size_t(1) << 30)) { error = "unexpected model file size"; return false; }
+ if (std::memcmp(bytes.data() + 4, "TFL3", 4) != 0) { error = "not a TFLite model (identifier)"; return false; }
+ Buffer b{bytes};
+ const Table root = Table::open(b, b.follow(0));
+ model.version = root.scalar<uint32_t>(0, 0);
+ if (!root.valid() || model.version != 3) { error = std::format("unsupported TFLite schema version {}", model.version); return false; }
+
+ // Operator codes: TFLite takes the larger of the builtin code (field 3) and the
+ // deprecated byte (field 0) that older files fill instead.
+ std::vector<int32_t> codes;
+ for (uint32_t i = 0; i < root.count(1); ++i) {
+ const Table oc = root.element(1, i);
+ codes.push_back(std::max(oc.scalar<int32_t>(3, 0), int32_t(oc.scalar<int8_t>(0, 0))));
+ }
+ if (root.count(2) != 1) { error = "expected exactly one subgraph"; return false; }
+ const Table graph = root.element(2, 0);
+ const uint32_t bufferCount = root.count(4);
+ const uint32_t tensorCount = graph.count(0);
+ model.tensors.resize(tensorCount);
+ for (uint32_t i = 0; i < tensorCount; ++i) {
+ const Table t = graph.element(0, i);
+ TfliteTensor& out = model.tensors[i];
+ out.shape = t.ints(0);
+ out.type = t.scalar<int8_t>(1, 0);
+ out.name = t.string(3);
+ const uint32_t buffer = t.scalar<uint32_t>(2, 0);
+ if (buffer >= bufferCount) { error = "tensor buffer index out of range"; return false; }
+ if (t.field(4)) {
+ const Table q = t.table(4);
+ if (q.count(0) || q.count(1) || q.count(2) || q.count(3)) { error = "quantized tensor " + out.name + " is not supported"; return false; }
+ }
+ const Table data = root.element(4, buffer);
+ size_t first = 0; uint32_t size = 0;
+ if (data.valid() && data.vector(0, first, size, 1) && size) {
+ const size_t n = out.elementCount();
+ if (out.type == 0 && size_t(size) == n * 4) {
+ out.floats.resize(n);
+ std::memcpy(out.floats.data(), bytes.data() + first, n * 4);
+ } else if (out.type == 1 && size_t(size) == n * 2) {
+ out.floats.resize(n);
+ for (size_t k = 0; k < n; ++k) out.floats[k] = halfToFloat(b.read<uint16_t>(first + 2 * k));
+ } else if (out.type == 2 && size_t(size) == n * 4) {
+ out.ints.resize(n);
+ std::memcpy(out.ints.data(), bytes.data() + first, n * 4);
+ } else { error = "constant " + out.name + " has an unsupported type or size"; return false; }
+ }
+ }
+ model.inputs = graph.ints(1);
+ model.outputs = graph.ints(2);
+ const auto inRange = [&](int32_t index) { return index >= -1 && index < int32_t(tensorCount); };
+ for (uint32_t i = 0; i < graph.count(3); ++i) {
+ const Table op = graph.element(3, i);
+ const uint32_t code = op.scalar<uint32_t>(0, 0);
+ if (code >= codes.size()) { error = "operator code index out of range"; return false; }
+ TfliteOperator o;
+ o.inputs = op.ints(1);
+ o.outputs = op.ints(2);
+ for (const auto t : o.inputs) if (!inRange(t)) { error = "operator input out of range"; return false; }
+ for (const auto t : o.outputs) if (t < 0 || t >= int32_t(tensorCount)) { error = "operator output out of range"; return false; }
+ const int32_t builtin = codes[code];
+ switch (builtin) {
+ case 0: case 3: case 4: case 6: case 17: case 34: case 54: o.op = TfliteOp(builtin); break;
+ default: error = std::format("unsupported operator (builtin code {})", builtin); return false;
+ }
+ const Table options = op.field(4) ? op.table(4) : Table{};
+ if (options.valid()) {
+ if (o.op == TfliteOp::Conv2D) {
+ o.samePadding = options.scalar<int8_t>(0, 0) == 0;
+ o.strideW = options.scalar<int32_t>(1, 1); o.strideH = options.scalar<int32_t>(2, 1);
+ o.activation = options.scalar<int8_t>(3, 0);
+ o.dilationW = options.scalar<int32_t>(4, 1); o.dilationH = options.scalar<int32_t>(5, 1);
+ } else if (o.op == TfliteOp::DepthwiseConv2D) {
+ o.samePadding = options.scalar<int8_t>(0, 0) == 0;
+ o.strideW = options.scalar<int32_t>(1, 1); o.strideH = options.scalar<int32_t>(2, 1);
+ o.depthMultiplier = options.scalar<int32_t>(3, 1);
+ o.activation = options.scalar<int8_t>(4, 0);
+ o.dilationW = options.scalar<int32_t>(5, 1); o.dilationH = options.scalar<int32_t>(6, 1);
+ } else if (o.op == TfliteOp::MaxPool2D) {
+ o.samePadding = options.scalar<int8_t>(0, 0) == 0;
+ o.strideW = options.scalar<int32_t>(1, 1); o.strideH = options.scalar<int32_t>(2, 1);
+ o.filterW = options.scalar<int32_t>(3, 1); o.filterH = options.scalar<int32_t>(4, 1);
+ o.activation = options.scalar<int8_t>(5, 0);
+ } else if (o.op == TfliteOp::Add) {
+ o.activation = options.scalar<int8_t>(0, 0);
+ }
+ }
+ if (o.op == TfliteOp::Dequantize) {
+ // A constant float16 tensor widened at load time: fold it.
+ if (o.inputs.size() != 1 || o.outputs.size() != 1 || o.inputs[0] < 0 || model.tensors[size_t(o.inputs[0])].floats.empty()) {
+ error = "DEQUANTIZE of a non-constant tensor is not supported"; return false;
+ }
+ auto& target = model.tensors[size_t(o.outputs[0])];
+ target.floats = model.tensors[size_t(o.inputs[0])].floats;
+ target.type = 0;
+ continue;
+ }
+ model.operators.push_back(std::move(o));
+ }
+ if (b.bad) { error = "truncated or malformed TFLite file"; return false; }
+ if (model.inputs.size() != 1 || model.outputs.empty()) { error = "unexpected graph inputs / outputs"; return false; }
+ return true;
+}
+
+} // namespace veyra::beauty
diff --git a/src/pipeline/BeautyPass.cpp b/src/pipeline/BeautyPass.cpp
index 8dbc1119..ad603216 100644
--- a/src/pipeline/BeautyPass.cpp
+++ b/src/pipeline/BeautyPass.cpp
@@ -7,7 +7,7 @@
namespace veyra::pipeline {
namespace {
-constexpr UINT kSrvs = 5, kSet = kSrvs + 1; // t0..t4, u0
+constexpr UINT kSrvs = 6, kSet = kSrvs + 1; // t0..t5, u0
constexpr DXGI_FORMAT kColorFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
constexpr UINT kRegionBytes = 64; // shaders/Beauty.hlsli kRoiBytes
constexpr UINT kFullArgs = 0, kLowArgs = 12;
@@ -53,9 +53,9 @@ bool BeautyPass::initialize(ID3D12Device* device, const engine::BeautySettings&
}
void BeautyPass::createViews(ID3D12Device* device, DescriptorStager& stager, ID3D12Resource* input, ID3D12Resource* output,
- ID3D12Resource* original, ID3D12Resource* faces)
+ ID3D12Resource* original, ID3D12Resource* faces, ID3D12Resource* shapes)
{
- input_ = input; output_ = output; original_ = original; faces_ = faces;
+ input_ = input; output_ = output; original_ = original; faces_ = faces; shapes_ = shapes;
D3D12_SHADER_RESOURCE_VIEW_DESC texture{};
texture.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
texture.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
@@ -77,9 +77,13 @@ void BeautyPass::createViews(ID3D12Device* device, DescriptorStager& stager, ID3
raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
raw.Buffer.NumElements = kRegionBytes / 4;
raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
+ D3D12_SHADER_RESOURCE_VIEW_DESC outlines = structured;
+ outlines.Buffer.NumElements = 8 * 128; // FaceMeshGpu::kMaxFaces x kShapeEntries
+ outlines.Buffer.StructureByteStride = 8;
const auto common = [&](Stage& stage, UINT set) {
stager.stageSrv(faces_, &structured, stage.pass.heap.Get(), set * kSet + 2);
stager.stageSrv(region_.Get(), &raw, stage.pass.heap.Get(), set * kSet + 3);
+ stager.stageSrv(shapes_, &outlines, stage.pass.heap.Get(), set * kSet + 5);
};
const auto uav = [&](Stage& stage, UINT set, ID3D12Resource* resource) {
makeUav(device, resource, kColorFormat, cpuHandleOf(stage.pass, set * kSet + kSrvs));
@@ -137,7 +141,7 @@ void BeautyPass::constants(uint32_t* c, bool hdrWorking, bool originalValid) con
bool BeautyPass::dispatch(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool hdrWorking, bool originalValid)
{
- if (!list || !input_ || !output_ || input_ == output_ || !faces_) return false;
+ if (!list || !input_ || !output_ || input_ == output_ || !faces_ || !shapes_) return false;
// The output starts as the input: outside this frame's region nothing changes.
tracker.transition(list, input_, D3D12_RESOURCE_STATE_COPY_SOURCE);
tracker.transition(list, output_, D3D12_RESOURCE_STATE_COPY_DEST);
@@ -158,6 +162,7 @@ bool BeautyPass::dispatch(ID3D12GraphicsCommandList* list, StateTracker& tracker
tracker.transition(list, input_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
if (original_) tracker.transition(list, original_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker.transition(list, faces_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker.transition(list, shapes_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
// Region of this frame, as dispatch arguments.
tracker.transition(list, region_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
bind(roi_, 0);
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 847a9bf7..1f231b8e 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -455,15 +455,22 @@ bool EnhanceGraph::createBeautyShared(){
if(desc_.beautyRequireDetector)return false;
beautyNotice_=model.empty()?L"美颜:人脸模型文件缺失,人脸原画保护与人脸区域美颜暂不生效"
:L"美颜:人脸识别初始化失败,人脸原画保护与人脸区域美颜暂不生效";
- }else faceTracker_->configure(desc_.beautyDetection,beautyMinConfidence());
+ }else{
+ faceTracker_->configure(desc_.beautyDetection,beautyMinConfidence());
+ if(!faceTracker_->meshReady())beautyNotice_=L"美颜:人脸网格模型缺失,人脸区域按椭圆近似,五官不单独排除";
+ }
if(!faceTracker_){
+ // Zeroed stand-ins: no faces, no outlines.
D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_DEFAULT;
D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=beauty::FaceTracker::kFaceEntries*64;
bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
if(FAILED(context_.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&beautyFacesFallback_))))return false;
+ bd.Width=beauty::FaceMeshGpu::kShapeBytes;
+ if(FAILED(context_.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&beautyShapesFallback_))))return false;
}
- veyra::log::info("beauty",std::format("shared: original={} detector={} quality={} faces<={} stability={:.2f}",
+ veyra::log::info("beauty",std::format("shared: original={} detector={} mesh={} quality={} faces<={} stability={:.2f}",
colorActive_?"ungraded copy":preGradeRgba_?"pre-grade input":"converted input",faceTracker_?"ready":"unavailable",
+ faceTracker_&&faceTracker_->meshReady()?"ready":"unavailable",
int(desc_.beautyDetection.quality),int(desc_.beautyDetection.maxFaces),desc_.beautyDetection.stability));
return true;
}
@@ -472,7 +479,7 @@ void EnhanceGraph::bindSlotPassInput(const SlotPass& pass,ID3D12Resource* input)
if(pass.type==engine::EffectType::Color)nodeColorInstances_[pass.parameter]->createViews(context_.device(),stager_,input,pass.output);
else if(pass.type==engine::EffectType::AntiAliasing)antiAliasPasses_[pass.parameter]->createViews(context_.device(),stager_,input,pass.output);
else if(pass.type==engine::EffectType::Beauty)
- beautyPasses_[pass.parameter]->createViews(context_.device(),stager_,input,pass.output,beautyOriginalSource_,beautyFaces());
+ beautyPasses_[pass.parameter]->createViews(context_.device(),stager_,input,pass.output,beautyOriginalSource_,beautyFaces(),beautyShapes());
}
// Binds one slot's passes in plan order: each reads the previous output.
@@ -3650,7 +3657,7 @@ void EnhanceGraph::shutdown()
for(auto& pass:beautyPasses_)pass.reset();
beautyOutputs_={};
if(faceTracker_)faceTracker_->shutdown();
- faceTracker_.reset();beautyOriginal_.Reset();beautyFacesFallback_.Reset();beautyOriginalSource_=nullptr;
+ faceTracker_.reset();beautyOriginal_.Reset();beautyFacesFallback_.Reset();beautyShapesFallback_.Reset();beautyOriginalSource_=nullptr;
beautyNodesActive_=beautyOriginalValid_=beautyDetectFailureLogged_=false;beautyNotice_.clear();
sourcePostOutput_=nullptr;
preSrColorOutput_=nullptr;preSrColorExecutionLogged_=false;
diff --git a/tests/integration/BeautyDetectorTests.cpp b/tests/integration/BeautyDetectorTests.cpp
index 50322c81..d5f48d04 100644
--- a/tests/integration/BeautyDetectorTests.cpp
+++ b/tests/integration/BeautyDetectorTests.cpp
@@ -13,6 +13,7 @@
// detector size: faces must overlap the reference.
// timing : (--timing) GPU milliseconds per layer kind at 320 / 512 / 640 wide.
// VEYRA_BEAUTY_GPU_DEBUG=1 enables the D3D12 debug layer and fails on its errors.
+#include "veyra/beauty/FaceMeshGpu.h"
#include "veyra/beauty/YuNetGpu.h"
#include "veyra/gfx/CommandSlotRing.h"
#include "veyra/gfx/D3D12DeviceContext.h"
@@ -362,6 +363,59 @@ void timing(Gpu& gpu, beauty::YuNetGpu& det, const fs::path& originals) {
}
} // namespace
+// Face mesh network against scripts/beauty/facemesh-reference.py: the same 192 x 192
+// crops in, the 1404 landmark values and the face flag out, for every reference face.
+void meshCases(Gpu& gpu, const fs::path& dir) {
+ const auto modelPath = beauty::locateFaceMeshModel();
+ check(!modelPath.empty(), "mesh: model next to the test (models/face_landmark.tflite)");
+ if (modelPath.empty()) return;
+ // The buffers the mesh binds; the network test reads neither.
+ auto faces = gpu.buffer(64 * 9, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON);
+ ComPtr<ID3D12Resource> shapes; // written by the mesh: unordered access
+ {
+ D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_RESOURCE_DESC d{}; d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; d.Width = beauty::FaceMeshGpu::kShapeBytes; d.Height = 1;
+ d.DepthOrArraySize = 1; d.MipLevels = 1; d.SampleDesc.Count = 1; d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ if (FAILED(gpu.ctx.device()->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&shapes))))
+ shapes.Reset();
+ }
+ beauty::FaceMeshGpu mesh;
+ std::string error;
+ const bool ready = faces && shapes && mesh.initialize(gpu.ctx.device(), modelPath, faces.Get(), shapes.Get(), 1, error);
+ check(ready, "mesh: initialise " + error);
+ if (!ready) return;
+ std::printf("MESH %s\n", mesh.description().c_str());
+ std::vector<fs::path> cases;
+ for (const auto& f : fs::directory_iterator(dir))
+ if (f.is_directory() && fs::exists(f.path() / "input.bin")) cases.push_back(f.path());
+ std::sort(cases.begin(), cases.end());
+ constexpr size_t kInput = 192 * 192 * 3, kOutput = 1404 + 1;
+ double worstPoint = 0, worstFlag = 0;
+ size_t compared = 0;
+ for (size_t first = 0; first < cases.size(); first += beauty::FaceMeshGpu::kMaxFaces) {
+ const size_t n = std::min<size_t>(beauty::FaceMeshGpu::kMaxFaces, cases.size() - first);
+ std::vector<float> input, expected, output;
+ for (size_t k = 0; k < n; ++k) {
+ const auto in = readFloats(cases[first + k] / "input.bin"), out = readFloats(cases[first + k] / "output.bin");
+ if (in.size() != kInput || out.size() != kOutput) { check(false, "mesh: reference " + cases[first + k].filename().string()); return; }
+ input.insert(input.end(), in.begin(), in.end());
+ expected.insert(expected.end(), out.begin(), out.end());
+ }
+ if (!mesh.runNetwork(gpu.ctx.directQueue(), input, uint32_t(n), output, error)) { check(false, "mesh: run " + error); return; }
+ for (size_t k = 0; k < n; ++k) {
+ for (size_t v = 0; v < 1404; ++v)
+ worstPoint = std::max(worstPoint, double(std::abs(output[k * kOutput + v] - expected[k * kOutput + v])));
+ worstFlag = std::max(worstFlag, double(std::abs(output[k * kOutput + 1404] - expected[k * kOutput + 1404])));
+ }
+ compared += n;
+ }
+ std::printf("METRIC mesh faces=%zu worstLandmarkErrorCropPx=%.5f worstFlagLogitError=%.5f\n", compared, worstPoint, worstFlag);
+ check(compared >= 8, "mesh: reference faces found");
+ check(worstPoint < 0.02, "mesh: every landmark within 0.02 crop pixels of the reference");
+ check(worstFlag < 0.02, "mesh: face flag within 0.02 of the reference logit");
+}
+
int wmain(int argc, wchar_t** argv) {
if (argc < 3) { std::printf("usage: veyra_beauty_detector_tests <model.onnx> <reference-dir> [--timing]\n"); return 2; }
const fs::path model = argv[1], refs = argv[2];
@@ -388,6 +442,7 @@ int wmain(int argc, wchar_t** argv) {
if (!loadReference(dir, r)) { check(false, "reference " + dir.filename().string()); continue; }
runCase(gpu, det, r, refs / "originals");
}
+ if (fs::exists(refs / "mesh")) meshCases(gpu, refs / "mesh");
if (withTiming) timing(gpu, det, refs / "originals");
const unsigned debugErrors = gpu.debugErrors();
check(debugErrors == 0, "D3D12 debug layer");
diff --git a/tests/integration/BeautyGpuTests.cpp b/tests/integration/BeautyGpuTests.cpp
index 224fb77b..e7a6980f 100644
--- a/tests/integration/BeautyGpuTests.cpp
+++ b/tests/integration/BeautyGpuTests.cpp
@@ -313,6 +313,26 @@ struct Gpu {
D3D12_RANGE empty{}; readback->Unmap(0, &empty);
return true;
}
+ // The face outlines after the last frame: 8 slots x 128 float2 (BeautyFaces.hlsli kShape*).
+ bool readShapes(std::vector<float>& shapes) {
+ auto* buffer = graph->beautyShapesBuffer();
+ constexpr UINT64 bytes = 8 * 128 * 8;
+ auto readback = buffer ? readbackBuffer(bytes) : nullptr;
+ Status st = Status::Ok; const auto slot = ring.slotCount() - 1; auto* list = readback ? ring.acquire(slot, st) : nullptr;
+ if (!list) return false;
+ D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ b.Transition = {buffer, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_SOURCE};
+ list->ResourceBarrier(1, &b);
+ list->CopyBufferRegion(readback.Get(), 0, buffer, 0, bytes);
+ std::swap(b.Transition.StateBefore, b.Transition.StateAfter); list->ResourceBarrier(1, &b);
+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) return false;
+ void* data = nullptr; D3D12_RANGE range{0, SIZE_T(bytes)};
+ if (FAILED(readback->Map(0, &range, &data))) return false;
+ shapes.resize(bytes / 4);
+ std::memcpy(shapes.data(), data, size_t(bytes));
+ D3D12_RANGE empty{}; readback->Unmap(0, &empty);
+ return true;
+ }
std::optional<double> stageMs(diagnostics::GpuStage stage) {
const auto m = graph->gpuMetrics();
const auto& s = m.gpu[size_t(stage)];
@@ -671,6 +691,176 @@ int trackingMotionCase() {
return finish(*gpu, "tracking-motion");
}
+// --- face mesh -------------------------------------------------------------------
+// MediaPipe face_mesh_connections (v0.8.9) as closed outlines, as BeautyMeshDecode.hlsl:
+// contour 36, lips 20, left eye 16, right eye 16, left brow 10, right brow 10.
+constexpr int kOutline[108] = {
+ 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149,
+ 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,
+ 61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291, 409, 270, 269, 267, 0, 37, 39, 40, 185,
+ 263, 249, 390, 373, 374, 380, 381, 382, 362, 398, 384, 385, 386, 387, 388, 466,
+ 33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246,
+ 276, 283, 282, 295, 285, 336, 296, 334, 293, 300,
+ 46, 53, 52, 65, 55, 107, 66, 105, 63, 70};
+constexpr int kOutlineFirst[6] = {0, 36, 56, 72, 88, 98}, kOutlineCount[6] = {36, 20, 16, 16, 10, 10};
+using Point = std::array<double, 2>;
+// The reference points of one face (scripts/beauty/facemesh-reference.py), picture pixels.
+bool loadMesh(const std::string& stem, int index, std::vector<Point>& points) {
+ std::ifstream in(gRefs / "mesh" / (stem + "-" + std::to_string(index)) / "landmarks.txt");
+ points.clear();
+ Point p;
+ while (in >> p[0] >> p[1]) points.push_back(p);
+ return points.size() == 468;
+}
+std::vector<Point> outline(const std::vector<Point>& points, int part) {
+ std::vector<Point> out;
+ for (int k = 0; k < kOutlineCount[part]; ++k) out.push_back(points[size_t(kOutline[kOutlineFirst[part] + k])]);
+ return out;
+}
+// Signed distance (negative inside) from a pixel centre to a closed outline.
+double outlineDistance(const std::vector<Point>& poly, double px, double py) {
+ double best = 1e30; bool inside = false;
+ for (size_t i = 0, j = poly.size() - 1; i < poly.size(); j = i++) {
+ const auto& a = poly[i]; const auto& b = poly[j];
+ const double ex = b[0] - a[0], ey = b[1] - a[1], wx = px - a[0], wy = py - a[1];
+ const double s = std::clamp((wx * ex + wy * ey) / std::max(ex * ex + ey * ey, 1e-12), 0.0, 1.0);
+ best = std::min(best, std::hypot(wx - ex * s, wy - ey * s));
+ if ((a[1] > py) != (b[1] > py) && px < ex * (py - a[1]) / (b[1] - a[1]) + a[0]) inside = !inside;
+ }
+ return inside ? -best : best;
+}
+double outlineWidth(const std::vector<Point>& poly) {
+ double lo = 1e30, hi = -1e30;
+ for (const auto& p : poly) { lo = std::min(lo, p[0]); hi = std::max(hi, p[0]); }
+ return hi - lo;
+}
+
+// The graph's outlines against the reference points: the network in the real
+// pipeline (crop from the tracked box, decode, outline gathering).
+int meshLandmarksCase() {
+ double worstMean = 0, worstMax = 0;
+ int pictures = 0;
+ for (const char* stem : {"lena", "astronaut", "gta-f040", "gta-f052"}) {
+ Picture p;
+ std::vector<Point> reference;
+ if (!loadPicture(stem, p) || !loadMesh(stem, 0, reference)) { check(false, std::string("mesh-landmarks: references for ") + stem); continue; }
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage out;
+ std::vector<float> shapes;
+ const bool ok = frame && gpu->start(withBeauty(restoreNode()), p.image.width, p.image.height, false) && gpu->render(frame, true, out) &&
+ gpu->readShapes(shapes);
+ av_frame_free(&frame);
+ check(ok && shapes[0] > 0.5f, std::string("mesh-landmarks: ") + stem + " has a usable mesh");
+ if (!ok || shapes[0] <= 0.5f) continue;
+ const double width = outlineWidth(outline(reference, 0));
+ double sum = 0, worst = 0;
+ for (int k = 0; k < 108; ++k) {
+ const double x = shapes[size_t(8 + k) * 2] * p.image.width, y = shapes[size_t(8 + k) * 2 + 1] * p.image.height;
+ const auto& r = reference[size_t(kOutline[k])];
+ const double e = std::hypot(x - r[0], y - r[1]) / width;
+ sum += e; worst = std::max(worst, e);
+ }
+ std::printf("METRIC case=mesh-landmarks picture=%s faceWidthPx=%.1f meshScore=%.3f meanError=%.4f maxError=%.4f (face widths)\n", stem,
+ width, shapes[1], sum / 108, worst);
+ worstMean = std::max(worstMean, sum / 108); worstMax = std::max(worstMax, worst);
+ ++pictures;
+ if (!gpu->debug) continue;
+ check(gpu->debugErrors() == 0, std::string("mesh-landmarks: D3D12 debug layer for ") + stem);
+ }
+ check(pictures == 4, "mesh-landmarks: every picture ran");
+ check(worstMean < 0.025, "mesh-landmarks: outline points within 2.5% of the face width on average");
+ check(worstMax < 0.08, "mesh-landmarks: every outline point within 8% of the face width");
+ return failures ? 1 : 0;
+}
+
+// Full face restore under a grade follows the face contour: the original inside it,
+// the graded picture outside it - also where the old oval reached (hair, hat brim).
+int meshContourCase() {
+ Picture p;
+ std::vector<Point> reference;
+ check(loadPicture("lena", p) && loadMesh("lena", 0, reference), "mesh-contour: picture and reference points");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage original, grade, restored;
+ const BeautySettings node = restoreNode(1.0f);
+ bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, original) &&
+ gpu->start(graded({}), p.image.width, p.image.height, false) && gpu->render(frame, true, grade) &&
+ gpu->start(graded(withBeauty(node)), p.image.width, p.image.height, false) && gpu->render(frame, true, restored);
+ av_frame_free(&frame);
+ check(ok, "mesh-contour: ungraded, graded and graded + restore graphs run");
+ if (!ok) return finish(*gpu, "mesh-contour");
+ const auto contour = outline(reference, 0);
+ const Face& f = p.faces[0];
+ const double width = f.w; // the node's unit: the detector's box width
+ const double grow = node.regionExpand * width, soft = std::max(node.feather * width, 1.5);
+ const double tolerance = 0.03 * width + 2.0; // the graph's points against the reference ones
+ const auto inside = compare(restored, original, [&](unsigned x, unsigned y) {
+ return outlineDistance(contour, x + 0.5, y + 0.5) < grow - soft / 2 - tolerance;
+ });
+ const auto outside = compare(restored, grade, [&](unsigned x, unsigned y) {
+ return outlineDistance(contour, x + 0.5, y + 0.5) > grow + soft / 2 + tolerance;
+ });
+ // Where the oval from the box (Beauty.hlsli BeautyFaceOval, the mask before the mesh) restored
+ // at least half way, but the contour does not reach.
+ const double ex = f.lm[2] - f.lm[0], ey = f.lm[3] - f.lm[1], el = std::max(std::hypot(ex, ey), 1e-9);
+ const double rc = (ex < 0 ? -ex : ex) / el, rs = (ex < 0 ? -ey : ey) / el;
+ const double ocx = f.x + f.w / 2 + rs * 0.06 * f.h, ocy = f.y + f.h / 2 - rc * 0.06 * f.h;
+ const double ax = f.w / 2 * (1.0 + node.regionExpand), ay = f.h / 2 * 1.12 * (1.0 + node.regionExpand);
+ const auto oldOval = [&](unsigned x, unsigned y) {
+ const double dx = x + 0.5 - ocx, dy = y + 0.5 - ocy;
+ const double u = dx * rc + dy * rs, v = -dx * rs + dy * rc;
+ return std::hypot(u / ax, v / ay) < 1.0;
+ };
+ const auto between = compare(restored, grade, [&](unsigned x, unsigned y) {
+ return oldOval(x, y) && outlineDistance(contour, x + 0.5, y + 0.5) > grow + soft / 2 + tolerance;
+ });
+ std::printf("METRIC case=mesh-contour insidePixels=%zu insideDiffering=%zu outsidePixels=%zu outsideDiffering=%zu ovalOnlyPixels=%zu ovalOnlyDiffering=%zu\n",
+ inside.pixels, inside.differing, outside.pixels, outside.differing, between.pixels, between.differing);
+ check(inside.pixels > 5000 && inside.differing == 0, "mesh-contour: inside the face contour the picture is the ungraded original");
+ check(outside.pixels > 5000 && outside.differing == 0, "mesh-contour: outside the contour the graded picture is untouched");
+ check(between.pixels > 500 && between.differing == 0, "mesh-contour: hair and background the old oval covered keep the grade");
+ save("mesh-contour-restored", restored);
+ return finish(*gpu, "mesh-contour");
+}
+
+// Smoothing leaves the eyes, brows and lips exactly as they were and still smooths the skin.
+int meshFeaturesCase() {
+ Picture p;
+ std::vector<Point> reference;
+ check(loadPicture("lena", p) && loadMesh("lena", 0, reference), "mesh-features: picture and reference points");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage plain, smoothed;
+ bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, plain) &&
+ gpu->start(withBeauty(strongNode()), p.image.width, p.image.height, false) && gpu->render(frame, true, smoothed);
+ av_frame_free(&frame);
+ check(ok, "mesh-features: plain and smoothing graphs run");
+ if (!ok) return finish(*gpu, "mesh-features");
+ // The graph's points are within 1% of the face width of the reference ones (mesh-landmarks).
+ const double width = p.faces[0].w, tolerance = 0.012 * width + 1.0;
+ std::vector<std::vector<Point>> features;
+ for (int part = 1; part < 6; ++part) features.push_back(outline(reference, part));
+ const auto inFeature = [&](unsigned x, unsigned y) {
+ for (const auto& poly : features) if (outlineDistance(poly, x + 0.5, y + 0.5) < -tolerance) return true;
+ return false;
+ };
+ const auto kept = compare(smoothed, plain, inFeature);
+ const auto contour = outline(reference, 0);
+ const auto skin = [&](unsigned x, unsigned y) {
+ if (outlineDistance(contour, x + 0.5, y + 0.5) > -0.08 * width) return false;
+ for (const auto& poly : features) if (outlineDistance(poly, x + 0.5, y + 0.5) < 0.06 * width) return false;
+ return true;
+ };
+ const double before = texture(plain, skin), after = texture(smoothed, skin);
+ std::printf("METRIC case=mesh-features featurePixels=%zu featureDiffering=%zu skinTexture=%.3f->%.3f (%.1f%%)\n", kept.pixels, kept.differing,
+ before, after, 100.0 * (after / std::max(before, 1e-9) - 1.0));
+ check(kept.pixels > 400 && kept.differing == 0, "mesh-features: eyes, brows and lips are not smoothed at all");
+ check(after < before * 0.92, "mesh-features: the skin between them is still smoothed");
+ save("mesh-features-smoothed", smoothed);
+ return finish(*gpu, "mesh-features");
+}
+
int noModelCase() {
Picture p;
check(loadPicture("lena", p), "no-model: picture");
@@ -797,6 +987,9 @@ std::vector<Case> cases() {
c.push_back({"hdr", [] { return hdrCase(); }});
c.push_back({"tracking", [] { return trackingCase(); }});
c.push_back({"tracking-motion", [] { return trackingMotionCase(); }});
+ c.push_back({"mesh-landmarks", [] { return meshLandmarksCase(); }});
+ c.push_back({"mesh-contour", [] { return meshContourCase(); }});
+ c.push_back({"mesh-features", [] { return meshFeaturesCase(); }});
c.push_back({"no-model", [] { return noModelCase(); }});
c.push_back({"tune", [] { return tuneCase(); }});
c.push_back({"timing-1080p", [] { return timingCase("timing-1080p", 1920, 1080); }});