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 node engine: face restore + skin smoothing, GPU face tracking, formats

Veyra Goal Agent7e86637bd494
diff --git a/cmake/VeyraBeauty.cmake b/cmake/VeyraBeauty.cmake
index 7813506a..4f7e37e3 100644
--- a/cmake/VeyraBeauty.cmake
+++ b/cmake/VeyraBeauty.cmake
@@ -8,12 +8,20 @@
# per file: THIRD_PARTY_NOTICES.md.
target_sources(veyra_pipeline PRIVATE
src/beauty/OnnxLite.cpp
- src/beauty/YuNetGpu.cpp)
+ src/beauty/YuNetGpu.cpp
+ src/beauty/FaceTracker.cpp
+ src/pipeline/BeautyPass.cpp)
foreach(kernel Prep Stem Pointwise Depthwise Pool UpAdd Decode)
string(TOLOWER "${kernel}" lower)
veyra_add_compute_shader(veyra_shader_beauty_yunet_${lower} BeautyYuNet${kernel})
add_dependencies(veyra_pipeline veyra_shader_beauty_yunet_${lower})
endforeach()
+# Face tracking and the node passes (region, statistics, blur, apply).
+foreach(stage Track Roi Stats Blur Apply)
+ string(TOLOWER "${stage}" lower)
+ veyra_add_compute_shader(veyra_shader_beauty_${lower} Beauty${stage})
+ add_dependencies(veyra_pipeline veyra_shader_beauty_${lower})
+endforeach()
# Detector against OpenCV's reference outputs (scripts/beauty/yunet-reference.py).
add_executable(veyra_beauty_detector_tests tests/integration/BeautyDetectorTests.cpp)
@@ -21,3 +29,10 @@ target_compile_features(veyra_beauty_detector_tests PRIVATE cxx_std_20)
target_compile_options(veyra_beauty_detector_tests PRIVATE /utf-8)
target_compile_definitions(veyra_beauty_detector_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_beauty_detector_tests PRIVATE veyra_pipeline veyra_sinks)
+
+# The beauty node in the real graph: restore / smoothing / HDR / tracking / timing.
+add_executable(veyra_beauty_gpu_tests tests/integration/BeautyGpuTests.cpp)
+target_compile_features(veyra_beauty_gpu_tests PRIVATE cxx_std_20)
+target_compile_options(veyra_beauty_gpu_tests PRIVATE /utf-8)
+target_compile_definitions(veyra_beauty_gpu_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+target_link_libraries(veyra_beauty_gpu_tests PRIVATE veyra_engine)
diff --git a/include/veyra/beauty/FaceTracker.h b/include/veyra/beauty/FaceTracker.h
new file mode 100644
index 00000000..2effb20e
--- /dev/null
+++ b/include/veyra/beauty/FaceTracker.h
@@ -0,0 +1,67 @@
+#pragma once
+#include "veyra/beauty/YuNetGpu.h"
+#include "veyra/engine/BeautySettings.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+
+#include <filesystem>
+#include <string>
+#include <vector>
+
+namespace veyra::beauty {
+// The shipped YuNet model (OpenCV Zoo 47534e27, MIT). It is never part of the source
+// tree: packages carry it in runtime/models, development trees in runtime_local/models,
+// staged tests next to the executable in models/. Empty when none is present.
+std::filesystem::path locateFaceModel();
+
+// Faces for every beauty node of one graph: the YuNet detector on the frame
+// before any effect, at a bounded rate, followed by the GPU tracking pass
+// (shaders/BeautyTrack.hlsl). All of it is recorded into the frame's own command
+// list; the node passes read the faces buffer later in the same frame. Only a
+// 64-byte status header is read back, a few frames late, for the UI.
+class FaceTracker {
+public:
+ struct Frame {
+ ID3D12Resource* source = nullptr; // linear RGBA16F / RGBA32F picture before every effect node
+ uint32_t width = 0, height = 0;
+ bool hdr = false; // scRGB working space
+ uint32_t slot = 0; // command ring slot of `list`
+ uint64_t frameId = 0; // the same source frame is never detected twice
+ double ptsMs = 0.0;
+ bool reset = false; // seek, scene cut, timeline break, new source
+ bool still = false; // a picture: fresh faces, no smoothing or prediction
+ bool everyFrame = false; // detect on every frame (export)
+ };
+
+ bool initialize(ID3D12Device* device, const std::filesystem::path& model, uint32_t ringSlots, std::string& error);
+ void shutdown();
+ bool ready() const { return ready_; }
+ // Live: input size, rate, face count and smoothing, and the lowest confidence any node accepts.
+ void configure(const engine::BeautyDetection& detection, float minConfidence);
+ // Detection when due, then tracking. Leaves the faces buffer in the non-pixel SRV state.
+ bool record(ID3D12GraphicsCommandList* list, pipeline::StateTracker& tracker, const Frame& frame);
+ ID3D12Resource* faces() const { return faces_.Get(); }
+ // 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_; }
+ uint32_t rawCandidates() const { return candidates_; }
+ uint64_t detections() const { return detections_; }
+ bool detectedThisFrame() const { return detectedNow_; }
+ const std::string& description() const { return detector_.modelDescription(); }
+ static constexpr uint32_t kFaceEntries = 9; // header + eight faces, 64 bytes each
+
+private:
+ YuNetGpu detector_;
+ pipeline::ComputePass track_;
+ pipeline::ComPtr<ID3D12DescriptorHeap> staging_;
+ pipeline::ComPtr<ID3D12Resource> faces_;
+ std::vector<pipeline::ComPtr<ID3D12Resource>> readbacks_;
+ std::vector<bool> pending_;
+ engine::BeautyDetection detection_{};
+ float threshold_ = 0.6f;
+ uint32_t slots_ = 0;
+ bool ready_ = false, haveFrame_ = false, detectedOnce_ = false, detectedNow_ = false;
+ uint64_t lastFrameId_ = 0, detections_ = 0;
+ double lastPts_ = 0.0, lastDetectPts_ = 0.0;
+ uint32_t faceCount_ = 0, candidates_ = 0;
+};
+} // namespace veyra::beauty
diff --git a/include/veyra/beauty/YuNetGpu.h b/include/veyra/beauty/YuNetGpu.h
index 0c91dea1..e703d989 100644
--- a/include/veyra/beauty/YuNetGpu.h
+++ b/include/veyra/beauty/YuNetGpu.h
@@ -28,6 +28,7 @@ struct YuNetConfig {
uint32_t candidateCapacity = 1024;
float scoreThreshold = 0.6f;
float nmsThreshold = 0.3f;
+ bool readback = true; // copy each slot's candidates to a CPU-readable buffer (collect)
};
// YuNet (OpenCV Zoo / libfacedetection, MIT) face detector as D3D12 compute
@@ -39,7 +40,7 @@ struct YuNetConfig {
class YuNetGpu {
public:
struct Source {
- ID3D12Resource* texture = nullptr; // RGBA16F, readable as a non-pixel SRV
+ ID3D12Resource* texture = nullptr; // RGBA16F / RGBA32F float texture, readable as a non-pixel SRV
uint32_t width = 0, height = 0; // full texture size
bool hdr = false; // scRGB (1.0 = 80 nits) instead of linear SDR
uint32_t originX = 0, originY = 0; // optional crop; 0 size = whole texture
@@ -70,6 +71,14 @@ public:
bool collect(uint32_t slot, std::vector<FaceBox>& faces, uint32_t* rawCandidates = nullptr);
static void nonMaxSuppression(std::vector<FaceBox>& boxes, float iouThreshold);
+ // GPU consumers (the beauty tracking pass): this slot's candidate list as a raw
+ // buffer (count, then 64-byte records), in the UAV state between records.
+ ID3D12Resource* candidateBuffer(uint32_t slot) const;
+ uint64_t candidateBufferBytes() const;
+ uint32_t candidateCapacity() const;
+ // Live: the decode keeps candidates at or above this score.
+ void setScoreThreshold(float threshold);
+
// Test and tooling hooks.
ID3D12Resource* inputBuffer() const; // padded BGR0 float4 grid, UAV state
ID3D12Resource* headBuffer(uint32_t scale) const; // merged 16-channel head, UAV state
diff --git a/include/veyra/engine/BeautySettings.h b/include/veyra/engine/BeautySettings.h
new file mode 100644
index 00000000..a81e0cdc
--- /dev/null
+++ b/include/veyra/engine/BeautySettings.h
@@ -0,0 +1,133 @@
+#pragma once
+#include <cmath>
+#include <cstdint>
+#include <istream>
+#include <ostream>
+#include <string>
+
+namespace veyra::engine {
+// Beauty node: two independent sub-functions on the picture at the node's position.
+//
+// Face restore ("人脸原画保护"): inside the detected faces the node blends the
+// same frame's original back in (the picture before every effect
+// node: colour grades, SR, every NR layer, earlier beauty nodes):
+// P = lerp(C, O, strength * faceMask).
+// Skin smoothing ("美颜"): SkinSoft's skin selection, detail protection and
+// texture restore around an edge-preserving local mean (GPUPixel's
+// variance-adaptive blend, run as a fast guided filter) on P.
+//
+// Only `enabled` changes the graph (the node exists or not); every other value is
+// a uniform, so tuning never rebuilds NGX / NR / FG. Faces come from one detector
+// shared by every beauty node of the chain (BeautyDetection).
+inline constexpr uint32_t kMaxBeautyInstances = 6;
+
+enum class BeautyRestoreScope : uint8_t { Face = 0, Skin = 1 }; // whole face estimate / its skin only
+enum class BeautyScope : uint8_t { Faces = 0, AllSkin = 1 }; // smoothing inside faces / every skin-coloured pixel
+
+struct BeautySettings {
+ bool enabled = false;
+ // Face restore.
+ bool restore = false;
+ float restoreStrength = 1.0f; // 0 .. 1
+ BeautyRestoreScope restoreScope = BeautyRestoreScope::Face;
+ float regionExpand = 0.05f; // -0.10 .. 0.30 of the face size
+ float feather = 0.08f; // 0 .. 0.20 of the face width
+ // Skin smoothing.
+ bool smooth = false;
+ float strength = 1.0f; // 0 .. 1, the whole smoothing sub-function
+ // Defaults tuned on lit photos and dark game footage (docs/BEAUTY_IMPLEMENTATION_PLAN):
+ // visible on skin texture, eyes / lashes / lips kept.
+ float smoothAmount = 0.50f; // 0 .. 1
+ float radius = 4.0f; // 0 .. 12: Gaussian sigma in 1080p pixels, scaled with the node's size
+ float detail = 0.65f; // 0 .. 1 detail protection
+ float texture = 0.30f; // 0 .. 1 texture restore (back to P, never to the effects restore removed)
+ float brighten = 0.0f; // 0 .. 1 skin brightening
+ BeautyScope scope = BeautyScope::Faces;
+ // Skin range on the display-referred picture (SkinSoft's HSV / luma selection).
+ float hueCenter = 0.08f; // 0 .. 1 (hue turns)
+ float hueRange = 0.10f; // 0.01 .. 0.50
+ // SkinSoft's 0.12 / 0.18 floors drop dim or dark skin (night game scenes measured
+ // 0.03-0.17 luma); inside a detected face the lower floors are safe.
+ float satMin = 0.08f, satMax = 0.80f; // 0 .. 1
+ float lumaMin = 0.04f, lumaMax = 0.95f;
+ float softness = 0.35f; // 0 .. 1
+ float minConfidence = 0.6f; // 0.3 .. 0.95: faces below it do not count for this node
+ bool showMask = false; // tint the restore (blue) and smoothing (magenta) areas
+ bool operator==(const BeautySettings&) const = default;
+
+ // Untouched defaults add no node, so presets saved without beauty keep their format.
+ bool configured() const { return *this != BeautySettings{}; }
+ bool restoreActive() const { return enabled && restore && restoreStrength > 0.0f; }
+ bool smoothActive() const { return enabled && smooth && strength > 0.0f && (smoothAmount > 0.0f || brighten > 0.0f); }
+ // Anything to do this frame (the node itself exists whenever it is enabled).
+ bool effective() const { return restoreActive() || smoothActive() || (enabled && showMask); }
+ // The values that matter to the running effect: a disabled node compares equal
+ // to the defaults, so editing it never counts as a change.
+ BeautySettings active() const { return enabled ? *this : BeautySettings{}; }
+ bool sameStructure(const BeautySettings& other) const { return enabled == other.enabled; }
+ std::string validate() const {
+ const auto in = [](float v, float lo, float hi) { return std::isfinite(v) && v >= lo && v <= hi; };
+ if (!in(restoreStrength, 0, 1)) return "beauty restore strength out of range";
+ if (restoreScope != BeautyRestoreScope::Face && restoreScope != BeautyRestoreScope::Skin) return "invalid beauty restore scope";
+ if (!in(regionExpand, -0.10f, 0.30f)) return "beauty region expansion out of range";
+ if (!in(feather, 0, 0.20f)) return "beauty feather out of range";
+ if (!in(strength, 0, 1) || !in(smoothAmount, 0, 1) || !in(detail, 0, 1) || !in(texture, 0, 1) || !in(brighten, 0, 1))
+ return "beauty smoothing value out of range";
+ if (!in(radius, 0, 12)) return "beauty radius out of range";
+ if (scope != BeautyScope::Faces && scope != BeautyScope::AllSkin) return "invalid beauty scope";
+ if (!in(hueCenter, 0, 1) || !in(hueRange, 0.01f, 0.5f) || !in(softness, 0, 1)) return "beauty skin hue out of range";
+ if (!in(satMin, 0, 1) || !in(satMax, 0, 1) || satMin >= satMax) return "beauty skin saturation range invalid";
+ if (!in(lumaMin, 0, 1) || !in(lumaMax, 0, 1) || lumaMin >= lumaMax) return "beauty skin brightness range invalid";
+ if (!in(minConfidence, 0.3f, 0.95f)) return "beauty face confidence out of range";
+ return {};
+ }
+};
+
+// One face detector serves every beauty node of a chain: these values are the
+// chain's (list and node mode keep their own), saved with it and frozen for export.
+struct BeautyDetection {
+ uint8_t quality = 1; // 0 performance (320 px, 10 Hz), 1 balanced (512 px, 15 Hz), 2 fine (640 px, 30 Hz)
+ uint8_t maxFaces = 4; // 1 .. 8
+ float stability = 0.5f; // 0 .. 1: smoothing of the tracked faces (0 follows every detection)
+ bool operator==(const BeautyDetection&) const = default;
+ uint32_t inputLongSide() const { return quality == 0 ? 320u : quality == 2 ? 640u : 512u; }
+ float rateHz() const { return quality == 0 ? 10.0f : quality == 2 ? 30.0f : 15.0f; }
+ std::string validate() const {
+ if (quality > 2) return "invalid beauty detection quality";
+ if (maxFaces < 1 || maxFaces > 8) return "beauty face count out of range";
+ if (!std::isfinite(stability) || stability < 0.0f || stability > 1.0f) return "beauty tracking stability out of range";
+ return {};
+ }
+};
+
+// Preset library v15 / chain session v10: one block per beauty node, one per chain.
+inline void writeBeauty(std::ostream& out, const BeautySettings& b) {
+ out << (b.enabled ? 1 : 0) << ' ' << (b.restore ? 1 : 0) << ' ' << b.restoreStrength << ' ' << int(b.restoreScope) << ' '
+ << b.regionExpand << ' ' << b.feather << ' ' << (b.smooth ? 1 : 0) << ' ' << b.strength << ' ' << b.smoothAmount << ' '
+ << b.radius << ' ' << b.detail << ' ' << b.texture << ' ' << b.brighten << ' ' << int(b.scope) << ' '
+ << b.hueCenter << ' ' << b.hueRange << ' ' << b.satMin << ' ' << b.satMax << ' ' << b.lumaMin << ' ' << b.lumaMax << ' '
+ << b.softness << ' ' << b.minConfidence << ' ' << (b.showMask ? 1 : 0);
+}
+inline bool readBeauty(std::istream& in, BeautySettings& b) {
+ int enabled = 0, restore = 0, restoreScope = 0, smooth = 0, scope = 0, mask = 0;
+ if (!(in >> enabled >> restore >> b.restoreStrength >> restoreScope >> b.regionExpand >> b.feather >> smooth >> b.strength >>
+ b.smoothAmount >> b.radius >> b.detail >> b.texture >> b.brighten >> scope >> b.hueCenter >> b.hueRange >> b.satMin >>
+ b.satMax >> b.lumaMin >> b.lumaMax >> b.softness >> b.minConfidence >> mask)) return false;
+ const auto flag = [](int v) { return v == 0 || v == 1; };
+ if (!flag(enabled) || !flag(restore) || !flag(smooth) || !flag(mask) || restoreScope < 0 || restoreScope > 1 || scope < 0 || scope > 1)
+ return false;
+ b.enabled = enabled != 0; b.restore = restore != 0; b.smooth = smooth != 0; b.showMask = mask != 0;
+ b.restoreScope = static_cast<BeautyRestoreScope>(restoreScope);
+ b.scope = static_cast<BeautyScope>(scope);
+ return b.validate().empty();
+}
+inline void writeBeautyDetection(std::ostream& out, const BeautyDetection& d) {
+ out << int(d.quality) << ' ' << int(d.maxFaces) << ' ' << d.stability;
+}
+inline bool readBeautyDetection(std::istream& in, BeautyDetection& d) {
+ int quality = 0, faces = 0;
+ if (!(in >> quality >> faces >> d.stability) || quality < 0 || quality > 2 || faces < 1 || faces > 8) return false;
+ d.quality = uint8_t(quality); d.maxFaces = uint8_t(faces);
+ return d.validate().empty();
+}
+} // namespace veyra::engine
diff --git a/include/veyra/engine/EffectChain.h b/include/veyra/engine/EffectChain.h
index 1c24640a..0083cd62 100644
--- a/include/veyra/engine/EffectChain.h
+++ b/include/veyra/engine/EffectChain.h
@@ -31,7 +31,7 @@ enum class EffectType : uint8_t {
VideoHdr, // SDR -> HDR conversion
FrameGeneration, // must be the last node
AntiAliasing, // spatial anti-aliasing (#53): same size, repeatable, before RTX Video HDR
- Beauty, // face restore + skin smoothing: same size, repeatable (reserved, hidden)
+ Beauty, // face restore + skin smoothing: same size, repeatable, before RTX Video HDR
Count
};
constexpr uint32_t effectTypeCount = uint32_t(EffectType::Count);
@@ -78,6 +78,7 @@ struct ChainNode {
ColorSettings color{};
VideoHdrSettings videoHdr{};
AntiAliasSettings aa{};
+ BeautySettings beauty{};
bool operator==(const ChainNode&) const = default;
};
@@ -98,6 +99,8 @@ struct EffectChain {
// toChain() ran out of nodes: validateChain() refuses the chain instead of a
// stage being dropped silently.
bool overflow = false;
+ // One face detector serves every beauty node of this chain.
+ BeautyDetection beautyDetection{};
bool operator==(const EffectChain&) const = default;
// Counts nodes of one type, regardless of enabled state.
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index 0458470b..23fc491a 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -10,12 +10,10 @@
#include "veyra/source/CaptureBuffer.h"
#include "veyra/engine/ColorSettings.h"
#include "veyra/engine/AntiAliasSettings.h"
+#include "veyra/engine/BeautySettings.h"
namespace veyra::engine {
inline constexpr uint32_t kMaxColorInstances = 6;
inline constexpr uint32_t kMaxNrInstances = 4;
-// Beauty nodes (face restore + skin smoothing). Reserved by the effect-chain
-// extension; the effect itself is not available yet (hidden in the catalog).
-inline constexpr uint32_t kMaxBeautyInstances = 6;
// Anti-flicker route for the NR temporal pass. The tiers come from Magpie's
// DLSSNRTemporal (GPL-3.0, commit 3841698): see shaders/NrTemporal.hlsl.
// Off - no temporal accumulation at all.
@@ -352,6 +350,17 @@ struct EnhancementSettings {
AntiAliasSettings antiAlias;
std::array<AntiAliasSettings,kMaxAntiAliasInstances-1> additionalAntiAlias{};
uint32_t additionalAntiAliasCount=0;
+ // Beauty nodes: instance zero is the first list layer, the rest follow in
+ // group order. The detection values are shared by every instance of the chain.
+ BeautySettings beauty;
+ std::array<BeautySettings,kMaxBeautyInstances-1> additionalBeauty{};
+ uint32_t additionalBeautyCount=0;
+ BeautyDetection beautyDetection;
+ bool beautyEnabled() const {
+ if(beauty.enabled)return true;
+ for(uint32_t i=0;i<additionalBeautyCount&&i<additionalBeauty.size();++i)if(additionalBeauty[i].enabled)return true;
+ return false;
+ }
// Stage-5 output stabiliser (anti-flicker). Holds the previous output where
// the source has not visibly changed. 0 is off, and off is the default: the
// graph then skips the dispatch entirely, so a build with this feature
@@ -413,6 +422,10 @@ struct EnhancementSettings {
active.antiAlias=antiAlias.active();
for(size_t i=0;i<active.additionalAntiAlias.size();++i)
active.additionalAntiAlias[i]=i<additionalAntiAliasCount?additionalAntiAlias[i].active():AntiAliasSettings{};
+ active.beauty=beauty.active();
+ for(size_t i=0;i<active.additionalBeauty.size();++i)
+ active.additionalBeauty[i]=i<additionalBeautyCount?additionalBeauty[i].active():BeautySettings{};
+ if(!beautyEnabled())active.beautyDetection=defaults.beautyDetection;
if(nrHoldStrength==0)active.nrHoldTolerance=defaults.nrHoldTolerance;
if(!hdrCurve.enabled){
active.hdrCurve=defaults.hdrCurve;
@@ -471,6 +484,11 @@ struct EnhancementSettings {
if(video.antiAlias.sameStructure(target.antiAlias))video.antiAlias=target.antiAlias;
for(size_t i=0;i<additionalAntiAlias.size();++i)
if(video.additionalAntiAlias[i].sameStructure(target.additionalAntiAlias[i]))video.additionalAntiAlias[i]=target.additionalAntiAlias[i];
+ // Beauty: only a node's master switch (and the node count) shapes the graph.
+ if(video.beauty.sameStructure(target.beauty))video.beauty=target.beauty;
+ for(size_t i=0;i<additionalBeauty.size();++i)
+ if(video.additionalBeauty[i].sameStructure(target.additionalBeauty[i]))video.additionalBeauty[i]=target.additionalBeauty[i];
+ video.beautyDetection=target.beautyDetection;
return video==target;
}
void rejectVideoRequest(const EnhancementSettings& attempted,const EnhancementSettings& previous) {
@@ -545,6 +563,11 @@ struct EnhancementSettings {
if(additionalAntiAliasCount>additionalAntiAlias.size())return "too many anti-aliasing instances";
for(uint32_t i=0;i<additionalAntiAliasCount;++i)
if(auto error=additionalAntiAlias[i].validate();!error.empty())return error;
+ if(auto error=beauty.validate();!error.empty())return error;
+ if(additionalBeautyCount>additionalBeauty.size())return "too many beauty instances";
+ for(uint32_t i=0;i<additionalBeautyCount;++i)
+ if(auto error=additionalBeauty[i].validate();!error.empty())return error;
+ if(auto error=beautyDetection.validate();!error.empty())return error;
if(!pipeline::validNrSizePolicy(nrPolicy))return "invalid NR size policy";
if(flow<FlowQuality::Performance||flow>FlowQuality::Quality||content<ContentRate::Transport||content>ContentRate::Capture60To30)return "invalid flow/content mode";
return {};
diff --git a/include/veyra/engine/ExportFeaturePolicy.h b/include/veyra/engine/ExportFeaturePolicy.h
index 21434b8d..0ad93d0c 100644
--- a/include/veyra/engine/ExportFeaturePolicy.h
+++ b/include/veyra/engine/ExportFeaturePolicy.h
@@ -13,10 +13,14 @@ inline EnhancementSettings freezeExportSettings(EnhancementSettings settings) {
// Preserve invalid counts for the caller's validation; normalization must
// not turn a corrupt settings transaction into an apparently valid one.
if(settings.nrLayerCount>settings.nrLayers.size()||settings.additionalColorCount>settings.additionalColors.size()||
- settings.additionalAntiAliasCount>settings.additionalAntiAlias.size())return settings;
+ settings.additionalAntiAliasCount>settings.additionalAntiAlias.size()||
+ settings.additionalBeautyCount>settings.additionalBeauty.size())return settings;
settings.nrPolicy=exportNrSizePolicy(settings.nrRuntime);
for(uint32_t i=0;i<settings.nrLayerCount&&i<settings.nrLayers.size();++i)
settings.nrLayers[i].sizePolicy=exportNrSizePolicy(settings.nrLayers[i].runtime);
+ // The beauty mask view is a diagnostic overlay of the preview, never part of a file.
+ settings.beauty.showMask=false;
+ for(auto& beauty:settings.additionalBeauty)beauty.showMask=false;
const auto chain=toChain(settings);fromChain(chain,settings);
return settings;
}
diff --git a/include/veyra/engine/GraphDescription.h b/include/veyra/engine/GraphDescription.h
index 27d0dcce..bb69d254 100644
--- a/include/veyra/engine/GraphDescription.h
+++ b/include/veyra/engine/GraphDescription.h
@@ -44,6 +44,13 @@ inline void describeAntiAlias(const EnhancementSettings& settings,pipeline::Enha
for(uint32_t i=1;i<kMaxAntiAliasInstances;++i)
desc.antiAlias[i]=i-1<settings.additionalAntiAliasCount?settings.additionalAntiAlias[i-1]:AntiAliasSettings{};
}
+// Beauty by parameter ordinal, like anti-aliasing; the detection values are the chain's.
+inline void describeBeauty(const EnhancementSettings& settings,pipeline::EnhanceGraphDesc& desc){
+ desc.beauty[0]=settings.beauty;
+ for(uint32_t i=1;i<kMaxBeautyInstances;++i)
+ desc.beauty[i]=i-1<settings.additionalBeautyCount?settings.additionalBeauty[i-1]:BeautySettings{};
+ desc.beautyDetection=settings.beautyDetection;
+}
struct StageRequest {
bool nr=false,sr=false,fg=false;
@@ -66,7 +73,8 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
desc.fixedExecutionPlan.reset();desc.fixedExecutionPlanError.clear();
desc.runtimeNodeOrder=request.nodeOrder!=nullptr;
if(savedSettings.nrLayerCount>savedSettings.nrLayers.size()||savedSettings.additionalColorCount>savedSettings.additionalColors.size()||
- savedSettings.additionalAntiAliasCount>savedSettings.additionalAntiAlias.size()){
+ savedSettings.additionalAntiAliasCount>savedSettings.additionalAntiAlias.size()||
+ savedSettings.additionalBeautyCount>savedSettings.additionalBeauty.size()){
desc.fixedExecutionPlanError="too many runtime chain instances";return {};
}
std::optional<EnhancementSettings> exportSettings;
@@ -129,6 +137,12 @@ inline pipeline::ResolutionPlan describeStages(const StageRequest& request,const
desc.additionalColors=settings.additionalColors;
desc.additionalColorCount=settings.additionalColorCount;
describeAntiAlias(settings,desc);
+ describeBeauty(settings,desc);
+ // A still picture or an export frame is judged on its own faces, never on a
+ // detection that is a few frames old.
+ desc.beautyDetectEveryFrame=request.stillImage||request.exportJob;
+ // An export never writes a file that silently lacks a selected effect.
+ desc.beautyRequireDetector=request.exportJob;
desc.videoHdr=settings.videoHdr;
// Custom: static HDR output tuning (present blit curve + display metadata).
desc.hdrCurve=settings.hdrCurve;
diff --git a/include/veyra/engine/RecentGraphCache.h b/include/veyra/engine/RecentGraphCache.h
index 7a4d7703..d57efbc3 100644
--- a/include/veyra/engine/RecentGraphCache.h
+++ b/include/veyra/engine/RecentGraphCache.h
@@ -44,7 +44,7 @@ public:
}
static bool eligible(const pipeline::EnhanceGraphDesc& desc){
return desc.enableNr&&!desc.enableSr&&!desc.enableFg&&!desc.hdrInput&&!desc.hdrOutput&&!desc.videoHdr.enabled&&!desc.color.enabled&&desc.additionalColorCount==0&&
- !desc.antiAliasActive()&&desc.nrHoldStrength==0&&!desc.noFeatures&&!desc.noNgx&&!desc.stillImage&&!desc.nrAutoPoolLayer&&
+ !desc.antiAliasActive()&&!desc.beautyActive()&&desc.nrHoldStrength==0&&!desc.noFeatures&&!desc.noNgx&&!desc.stillImage&&!desc.nrAutoPoolLayer&&
currentNrRuntime(desc.nrRuntime)==NrRuntime::Ampere&&!desc.nrTemporal&&desc.nrLayersModel.size()<=1&&
std::none_of(desc.nrLayersTemporal.begin(),desc.nrLayersTemporal.end(),[](bool value){return value;})&&
!desc.runtimeNodeOrder&&(!desc.fixedExecutionPlan||(
@@ -52,7 +52,7 @@ public:
}
static bool effectsOff(const pipeline::EnhanceGraphDesc& desc){
return !desc.enableNr&&!desc.enableSr&&!desc.enableFg&&!desc.videoHdr.enabled&&!desc.color.enabled&&desc.additionalColorCount==0&&
- !desc.antiAliasActive();
+ !desc.antiAliasActive()&&!desc.beautyActive();
}
static std::string label(const Key& key){
return std::format("{}x{}:{}x{}:{}x{}:runtime{}:file{}:mtime{}",key.sourceWidth,key.sourceHeight,
diff --git a/include/veyra/pipeline/BeautyPass.h b/include/veyra/pipeline/BeautyPass.h
new file mode 100644
index 00000000..81fc2409
--- /dev/null
+++ b/include/veyra/pipeline/BeautyPass.h
@@ -0,0 +1,46 @@
+#pragma once
+#include "veyra/engine/BeautySettings.h"
+#include "veyra/pipeline/GpuPassUtils.h"
+#include <string>
+
+namespace veyra::pipeline {
+// One beauty node on linear float textures of one size (the node's place in the
+// chain). The graph owns the input, the output, the frame's original (the
+// picture before every effect node) and the faces buffer of the shared tracker;
+// the pass owns a 64-byte region buffer, two statistics-grid textures (about
+// 960x540 whatever the node size) and the indirect-dispatch signature.
+//
+// Each frame the output starts as a copy of the input, so every pixel outside
+// this frame's face region is bit-identical; shaders/BeautyRoi.hlsl then sizes
+// the remaining dispatches to that region (none without faces). Every setting is
+// live (refresh): only the node's existence changes the graph.
+class BeautyPass {
+public:
+ static constexpr UINT kConstantCount = 32;
+ bool initialize(ID3D12Device* device, const engine::BeautySettings& settings, uint32_t width, uint32_t height,
+ 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);
+ // `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_; }
+ std::string describe() const;
+ uint32_t statisticsScale() const { return scale_; }
+ // Node pixels of the smoothing sigma for a radius setting (1080p equivalent).
+ float sigmaPixels() const;
+private:
+ struct Stage { ComputePass pass; };
+ bool createStage(ID3D12Device* device, Stage& stage, const char* shader, UINT sets);
+ void constants(uint32_t* c, bool hdrWorking, bool originalValid) const;
+ engine::BeautySettings settings_{};
+ uint32_t width_ = 0, height_ = 0, sourceWidth_ = 0, sourceHeight_ = 0, lowWidth_ = 0, lowHeight_ = 0, scale_ = 1;
+ Stage roi_, stats_, blur_, apply_;
+ ComPtr<ID3D12Resource> region_, lowA_, lowB_;
+ ComPtr<ID3D12CommandSignature> signature_;
+ ID3D12Resource* input_ = nullptr;
+ ID3D12Resource* output_ = nullptr;
+ ID3D12Resource* original_ = nullptr;
+ ID3D12Resource* faces_ = nullptr;
+};
+}
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 6f00dce9..1c460d27 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -5,6 +5,8 @@
#include "veyra/pipeline/ColorGradeTables.h"
#include "veyra/pipeline/ColorGradeInstance.h"
#include "veyra/pipeline/AntiAliasPass.h"
+#include "veyra/pipeline/BeautyPass.h"
+#include "veyra/beauty/FaceTracker.h"
#include "veyra/pipeline/NrInstance.h"
#include "veyra/pipeline/ResolutionPlan.h"
#include "veyra/pipeline/NrTemporalPass.h"
@@ -175,6 +177,17 @@ struct EnhanceGraphDesc {
for(const auto& a:antiAlias)if(a.enabled)return true;
return false;
}
+ // Beauty nodes by parameter ordinal, plus the chain's shared face detection.
+ std::array<engine::BeautySettings,engine::kMaxBeautyInstances> beauty{};
+ engine::BeautyDetection beautyDetection{};
+ bool beautyDetectEveryFrame=false; // still pictures / export: detect on every frame
+ bool beautyRequireDetector=false; // export: a missing face detector fails the job before it starts
+ std::wstring beautyModelPath; // empty: the shipped YuNet file (beauty::locateFaceModel)
+ static constexpr bool beautyExecutor=true;
+ bool beautyActive() const {
+ for(const auto& b:beauty)if(b.enabled)return true;
+ return false;
+ }
// Production builders compile once and use this plan for NR resource
// sizes and node tail Color routing after the fixed base block. This is
// NOT an arbitrary-order GPU dispatcher. Direct
@@ -416,18 +429,26 @@ struct EnhanceGraphDesc {
return "anti-aliasing parameter index/enabled mismatch";
if(!antiAliasExecutor)return "anti-aliasing is not available in this build";
}
- if(step.type==EffectType::Beauty)return "beauty nodes are not available in this build";
+ if(step.type==EffectType::Beauty){
+ if(step.parameterIndex>=beauty.size()||!beauty[step.parameterIndex].enabled)
+ return "beauty parameter index/enabled mismatch";
+ if(!beautyExecutor)return "beauty nodes are not available in this build";
+ }
// Same-size passes take the rank of the slot they run in.
PassSlot passSlot=PassSlot::None;
if(samePass(step.type)){
passSlot=slotOfStep(i);
if(passSlot==PassSlot::None)return "same-size node position is not supported by the fixed dispatcher";
- if(step.type!=EffectType::Color)rank=0; // list mode / source-size slot; node slots below
+ // List mode: anti-aliasing runs at source size first; the beauty group
+ // follows the whole NR group (with its protection). Node slots below.
+ if(step.type==EffectType::AntiAliasing)rank=0;
+ if(step.type==EffectType::Beauty)rank=passSlot==PassSlot::SourcePost?0:int(EffectType::Protection);
}
if(nrBeforeSr){
if(step.type==EffectType::NrEnhance)rank=1;
if(step.type==EffectType::Protection)rank=2;
if(step.type==EffectType::SuperResolution)rank=3;
+ if(step.type==EffectType::Beauty&&!runtimeNodeOrder)rank=2; // right after the NR group
}
if(runtimeNodeOrder){
if(step.type==EffectType::Protection&&interProtection)rank=nrBeforeSr?1:2;
@@ -702,6 +723,16 @@ public:
// does not match the content domain). The engine surfaces this in the
// status panel so the refusal is visible, not only logged.
const std::wstring& colorLutNotice() const { return colorLutNotice_; }
+ // Beauty nodes: a problem that disables them (shown, never only logged), and the
+ // faces the shared tracker found a few frames ago (status only; the picture
+ // uses this frame's GPU result).
+ const std::wstring& beautyNotice() const { return beautyNotice_; }
+ bool beautyNodesActive() const { return beautyNodesActive_; }
+ bool beautyDetectorReady() const { return faceTracker_&&faceTracker_->ready(); }
+ uint32_t beautyFaceCount() const { return faceTracker_?faceTracker_->faceCount():0; }
+ 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; }
// 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; }
@@ -904,6 +935,33 @@ private:
std::array<std::unique_ptr<AntiAliasPass>,engine::kMaxAntiAliasInstances> antiAliasPasses_{};
std::array<ComPtr<ID3D12Resource>,engine::kMaxAntiAliasInstances> antiAliasOutputs_{};
bool createAntiAlias(uint32_t parameter,uint32_t width,uint32_t height);
+ // Beauty nodes by parameter ordinal, plus what they share: the face tracker,
+ // the faces buffer (a zero buffer when the detector is unavailable) and this
+ // frame's original - the picture before every effect node. Without a fused
+ // grade the converted input already is that picture (srcRgba_ / preGradeRgba_
+ // are never written again in the frame); with one, beautyOriginal_ receives an
+ // ungraded conversion on the frames where a node restores faces.
+ std::array<std::unique_ptr<BeautyPass>,engine::kMaxBeautyInstances> beautyPasses_{};
+ std::array<ComPtr<ID3D12Resource>,engine::kMaxBeautyInstances> beautyOutputs_{};
+ bool createBeauty(uint32_t parameter,uint32_t width,uint32_t height);
+ bool createBeautyShared();
+ ID3D12Resource* beautyFaces() const { return faceTracker_&&faceTracker_->ready()?faceTracker_->faces():beautyFacesFallback_.Get(); }
+ bool beautyRestoreRequested() const {
+ for(const auto& b:desc_.beauty)if(b.restoreActive())return true;
+ return false;
+ }
+ float beautyMinConfidence() const {
+ float value=0.95f;
+ for(const auto& b:desc_.beauty)if(b.enabled)value=std::min(value,b.minConfidence);
+ return value;
+ }
+ // 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_;
+ ID3D12Resource* beautyOriginalSource_=nullptr;
+ bool beautyNodesActive_=false,beautyOriginalValid_=false,beautyDetectFailureLogged_=false;
+ std::wstring beautyNotice_;
bool tailColorExecutionLogged_=false,preNrColorExecutionLogged_=false;
bool preSrColorExecutionLogged_=false;
bool interNrColorExecutionLogged_=false;
diff --git a/shaders/Beauty.hlsli b/shaders/Beauty.hlsli
new file mode 100644
index 00000000..b664806e
--- /dev/null
+++ b/shaders/Beauty.hlsli
@@ -0,0 +1,142 @@
+// Beauty node: constants, colour domain, skin selection and face masks shared by
+// the node passes (BeautyRoi / BeautyStats / BeautyBlur / BeautyApply).
+//
+// Working textures are linear FP16: SDR BT.709 with white = 1.0, or HDR scRGB
+// (1 = 80 cd/m2) whose 203-nit reference white bWorkingToWhite maps to 1.0. The
+// smoothing runs on a perceptual copy (the sRGB transfer below white, continued
+// logarithmically above it with the same slope, sign kept for out-of-709
+// components); every blend back into the picture uses linear values, so HDR
+// highlights and negative wide-gamut components survive wherever a mask is 0.
+//
+// Skin selection follows SkinSoft (yasunari01/obs-filters fd5690f,
+// skinsoft-filter/data/effects/skinsoft.effect, GPL-2.0-or-later): HSV hue
+// distance plus saturation / luma windows with a shared softness, evaluated on
+// the display-referred picture.
+#ifndef VEYRA_BEAUTY_HLSLI
+#define VEYRA_BEAUTY_HLSLI
+
+cbuffer BeautyParams : register(b0) {
+ uint bWidth; uint bHeight; // node extent
+ uint bSrcWidth; uint bSrcHeight; // original (source) extent
+ uint bLowWidth; uint bLowHeight; // statistics grid
+ uint bScale; // node pixels per statistics cell (each axis)
+ uint bFlags;
+ float bWorkingToWhite;
+ float bRestoreStrength; float bRegionExpand; float bFeather;
+ float bStrength; float bSmoothAmount; float bDetail; float bTexture;
+ float bBrighten; float bSigma; float bEpsilon; float bMinConfidence;
+ float bHueCenter; float bHueRange; float bSatMin; float bSatMax;
+ float bLumaMin; float bLumaMax; float bSoftness; uint bPass;
+ uint bMaxFaces; uint bReserved0; uint bReserved1; uint bReserved2;
+};
+static const uint kBeautyRestore = 1u; // face restore active
+static const uint kBeautySmooth = 2u; // skin smoothing active
+static const uint kBeautyRestoreSkin = 4u; // restore only the skin of the face
+static const uint kBeautyAllSkin = 8u; // smooth every skin-coloured pixel, not only faces
+static const uint kBeautyShowMask = 16u;
+static const uint kBeautyOriginal = 32u; // the original texture holds this frame
+
+SamplerState bPointSampler : register(s0); // point, clamp
+SamplerState bLinearSampler : register(s1); // bilinear, clamp
+
+#include "BeautyFaces.hlsli"
+
+// 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;
+static const float kSmoothExpand = 0.10, kSmoothFeather = 0.12;
+
+float BeautyEncode(float relative) {
+ const float y = abs(relative);
+ const float e = y > 1.0 ? 1.0 + 0.30469 * log2(y) : (y <= 0.0031308 ? 12.92 * y : 1.055 * pow(y, 1.0 / 2.4) - 0.055);
+ return relative < 0.0 ? -e : e;
+}
+float BeautyDecode(float encoded) {
+ const float e = abs(encoded);
+ const float y = e > 1.0 ? exp2((e - 1.0) / 0.30469) : (e <= 0.04045 ? e / 12.92 : pow((e + 0.055) / 1.055, 2.4));
+ return encoded < 0.0 ? -y : y;
+}
+float3 BeautyPerceptual(float3 linearRgb) {
+ const float3 c = linearRgb * bWorkingToWhite;
+ return float3(BeautyEncode(c.r), BeautyEncode(c.g), BeautyEncode(c.b));
+}
+float3 BeautyLinear(float3 perceptual) {
+ return float3(BeautyDecode(perceptual.r), BeautyDecode(perceptual.g), BeautyDecode(perceptual.b)) / bWorkingToWhite;
+}
+float BeautyLuma(float3 rgb) { return dot(rgb, float3(0.2126, 0.7152, 0.0722)); }
+
+// --- SkinSoft skin selection -------------------------------------------------
+float3 BeautyRgbToHsv(float3 c) {
+ const float4 k = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
+ const float4 p = lerp(float4(c.bg, k.wz), float4(c.gb, k.xy), step(c.b, c.g));
+ const float4 q = lerp(float4(p.xyw, c.r), float4(c.r, p.yzx), step(p.x, c.r));
+ const float d = q.x - min(q.w, q.y);
+ const float e = 0.00001;
+ return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
+}
+float BeautyRange(float value, float lo, float hi, float softness) {
+ const float soft = max(softness, 0.001);
+ return smoothstep(lo - soft, lo + soft, value) * (1.0 - smoothstep(hi - soft, hi + soft, value));
+}
+// `display`: perceptual (display-referred) RGB; values above white count as white.
+float BeautySkin(float3 display) {
+ const float3 c = saturate(display);
+ const float3 hsv = BeautyRgbToHsv(c);
+ const float luma = BeautyLuma(c);
+ const float soft = bSoftness * 0.18;
+ const float d = abs(hsv.x - bHueCenter);
+ const float hue = 1.0 - smoothstep(max(bHueRange - soft, 0.001), bHueRange + soft, min(d, 1.0 - d));
+ return saturate(hue * BeautyRange(hsv.y, bSatMin, bSatMax, soft) * BeautyRange(luma, bLumaMin, bLumaMax, soft));
+}
+
+// --- Face masks ----------------------------------------------------------------
+// Soft oval of one face in node pixels: `expand` grows the axes, `feather` is the
+// soft edge as a fraction of the face width.
+float BeautyFaceOval(BeautyFace f, float2 p, float expand, float feather) {
+ const float2 size = float2(bWidth, bHeight);
+ // Eyes run along (cos, sin); the face's up direction is perpendicular to them.
+ const float2 up = float2(f.shape.y, -f.shape.x);
+ const float2 centre = f.box.xy * size + up * (kBeautyOvalLift * f.box.w * 2.0 * bHeight);
+ const float2 axes = max(f.box.zw * size * float2(kBeautyOvalX, kBeautyOvalY) * (1.0 + expand), 1.0);
+ const float2 d = p - centre;
+ const float2 local = float2(dot(d, f.shape.xy), dot(d, float2(-f.shape.y, f.shape.x)));
+ const float rho = length(local / axes);
+ const float width = feather * 2.0 * f.box.z * bWidth / min(axes.x, axes.y);
+ 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.
+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));
+ }
+ return mask;
+}
+
+// --- Region (BeautyRoi.hlsl writes it, every other pass reads it) -------------
+// Bytes: 0 full-size dispatch (x, y, 1), 12 statistics-grid dispatch (x, y, 1),
+// 24 full origin, 32 full size, 40 grid origin, 48 grid size, 56 faces, flags.
+static const uint kRoiFullArgs = 0u, kRoiLowArgs = 12u, kRoiOrigin = 24u, kRoiSize = 32u;
+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) {
+ 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;
+ if (mask <= 0.0) return c;
+ // Same size as the source: the original texel itself; otherwise bilinear.
+ const float3 o = (bWidth == bSrcWidth && bHeight == bSrcHeight)
+ ? original.Load(int3(p, 0)).rgb
+ : original.SampleLevel(bLinearSampler, (float2(p) + 0.5) / float2(bWidth, bHeight), 0).rgb;
+ if (bFlags & kBeautyRestoreSkin) mask *= BeautySkin(BeautyPerceptual(o));
+ return mask >= 1.0 ? o : lerp(c, o, mask); // a full restore is the original texel itself
+}
+#endif
diff --git a/shaders/BeautyApply.hlsl b/shaders/BeautyApply.hlsl
new file mode 100644
index 00000000..12312ff5
--- /dev/null
+++ b/shaders/BeautyApply.hlsl
@@ -0,0 +1,58 @@
+// Beauty node, final step: one pass over this frame's region.
+//
+// P = the node input with the original restored inside the faces
+// 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
+// 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
+// smoothing strength; outside the masks the input passes through unchanged.
+// The mask view tints the restore area blue and the smoothing area magenta.
+#include "Beauty.hlsli"
+
+Texture2D<float4> Input : register(t0);
+Texture2D<float4> Original : register(t1);
+StructuredBuffer<BeautyFace> Faces : register(t2);
+ByteAddressBuffer Roi : register(t3);
+Texture2D<float4> Coefficients : register(t4);
+RWTexture2D<float4> Output : register(u0);
+
+[numthreads(8, 8, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint2 extent = Roi.Load2(kRoiSize);
+ if (any(id.xy >= extent)) return;
+ const int2 p = int2(Roi.Load2(kRoiOrigin) + id.xy);
+ const float4 c = Input.Load(int3(p, 0));
+ float restoreMask;
+ const float3 restored = BeautyRestored(Input, Original, Faces, p, restoreMask);
+ float3 result = restored;
+ float smoothMask = 0.0;
+ if (bFlags & (kBeautySmooth | kBeautyShowMask)) {
+ 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;
+ 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));
+ const float2 grid = clamp((float2(p) + 0.5) / float(bScale), lowOrigin + 0.5, lowOrigin + lowExtent - 0.5);
+ const float4 k = Coefficients.SampleLevel(bLinearSampler, grid / float2(bLowWidth, bLowHeight), 0);
+ const float3 blurred = k.a * i + k.rgb;
+ const float protection = 1.0 - smoothstep(0.02, 0.22, length(i - blurred) * bDetail * 3.0);
+ const float3 smoothed = lerp(i, blurred, smoothMask * bSmoothAmount * protection);
+ float3 retouched = lerp(smoothed, i, smoothMask * bTexture);
+ if (bBrighten > 0.0) {
+ const float y = BeautyLuma(retouched);
+ if (y > 1e-4 && y < 1.0) retouched *= pow(y, 1.0 / (1.0 + 0.6 * bBrighten * smoothMask)) / y;
+ }
+ result = lerp(restored, BeautyLinear(retouched), bStrength);
+ }
+ }
+ if (bFlags & kBeautyShowMask) {
+ const float white = 1.0 / bWorkingToWhite;
+ result = lerp(result, float3(0.10, 0.35, 1.0) * white, 0.45 * saturate(restoreMask));
+ result = lerp(result, float3(1.0, 0.15, 0.85) * white, 0.45 * saturate(smoothMask));
+ }
+ Output[p] = float4(result, c.a);
+}
diff --git a/shaders/BeautyBlur.hlsl b/shaders/BeautyBlur.hlsl
new file mode 100644
index 00000000..18220bd0
--- /dev/null
+++ b/shaders/BeautyBlur.hlsl
@@ -0,0 +1,38 @@
+// Beauty node, smoothing steps 2-5: separable Gaussian on the statistics grid,
+// restricted to this frame's region (taps clamp to it, so cells outside it are
+// never read). bPass 0 / 1: horizontal / vertical blur of the statistics; pass 1
+// also turns the local mean and variance into the guided-filter coefficients
+// (a from the luma variance against bEpsilon, b = (1 - a) * mean per channel).
+// bPass 2 / 3: horizontal / vertical blur of those coefficients.
+#include "Beauty.hlsli"
+
+Texture2D<float4> Source : register(t0);
+ByteAddressBuffer Roi : register(t3);
+RWTexture2D<float4> Target : register(u0);
+
+[numthreads(8, 8, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint2 lowExtent = Roi.Load2(kRoiLowSize);
+ if (any(id.xy >= lowExtent)) return;
+ const int2 origin = int2(Roi.Load2(kRoiLowOrigin));
+ const int2 cell = origin + int2(id.xy);
+ const int2 axis = (bPass & 1u) ? int2(0, 1) : int2(1, 0);
+ const int2 lo = origin, hi = origin + int2(lowExtent) - 1;
+ const float sigma = max(bSigma, 0.35);
+ const int radius = int(min(ceil(3.0 * sigma), 12.0));
+ float4 sum = 0.0;
+ float weights = 0.0;
+ for (int k = -radius; k <= radius; ++k) {
+ const float w = exp(-0.5 * float(k * k) / (sigma * sigma));
+ sum += w * Source.Load(int3(clamp(cell + axis * k, lo, hi), 0));
+ weights += w;
+ }
+ float4 value = sum / weights;
+ if (bPass == 1u) {
+ const float meanY = BeautyLuma(value.rgb);
+ const float variance = max(value.a - meanY * meanY, 0.0);
+ const float a = variance / (variance + bEpsilon);
+ value = float4(value.rgb * (1.0 - a), a);
+ }
+ Target[cell] = value;
+}
diff --git a/shaders/BeautyFaces.hlsli b/shaders/BeautyFaces.hlsli
new file mode 100644
index 00000000..89d399a5
--- /dev/null
+++ b/shaders/BeautyFaces.hlsli
@@ -0,0 +1,12 @@
+// Tracked faces shared by every beauty node of one graph. BeautyTrack.hlsl owns the
+// buffer; the node passes read it. Entry 0 is the header, entries 1..8 the faces.
+#ifndef VEYRA_BEAUTY_FACES_HLSLI
+#define VEYRA_BEAUTY_FACES_HLSLI
+struct BeautyFace {
+ float4 box; // centre x, centre y, half width, half height: fractions of the source frame
+ float4 shape; // cos roll, sin roll (eye line), detector score, presence 0..1
+ float4 motion; // velocity x, y (fractions per ms), ms since the last detection match, reserved
+ uint4 meta; // header: count, next id, frame counter, raw candidates; face: id, hits, 0, 0
+};
+static const uint kBeautyMaxFaces = 8u;
+#endif
diff --git a/shaders/BeautyRoi.hlsl b/shaders/BeautyRoi.hlsl
new file mode 100644
index 00000000..4de90a53
--- /dev/null
+++ b/shaders/BeautyRoi.hlsl
@@ -0,0 +1,57 @@
+// 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
+// after this one only run on that region; the rest of the output is the input copy.
+#include "Beauty.hlsli"
+
+StructuredBuffer<BeautyFace> Faces : register(t2);
+RWByteAddressBuffer Roi : register(u0);
+
+[numthreads(1, 1, 1)]
+void main() {
+ const float2 size = float2(bWidth, bHeight);
+ const bool smooth = (bFlags & kBeautySmooth) != 0;
+ const bool restore = (bFlags & kBeautyRestore) != 0 && (bFlags & kBeautyOriginal) != 0;
+ // The statistics grid around a pixel reaches 3 sigma (capped at 12 cells) plus the bilinear neighbour.
+ const float filter = smooth ? (min(ceil(3.0 * bSigma), 12.0) * 2.0 + 2.0) * float(bScale) : 0.0;
+ float2 lo = size, hi = 0.0;
+ uint faces = 0;
+ if (smooth && (bFlags & kBeautyAllSkin)) { lo = 0.0; hi = size; faces = 1; }
+ else {
+ const uint count = min(Faces[0].meta.x, kBeautyMaxFaces);
+ for (uint i = 0; i < count; ++i) {
+ const BeautyFace f = Faces[1 + i];
+ if (f.shape.z < bMinConfidence || f.shape.w <= 0.0) continue;
+ float reach = 0.0;
+ 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;
+ // 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;
+ const float2 centre = f.box.xy * size;
+ lo = min(lo, centre - radius);
+ hi = max(hi, centre + radius);
+ ++faces;
+ }
+ }
+ uint2 origin = 0, extent = 0;
+ if (faces) {
+ origin = uint2(clamp(floor(lo), 0.0, size));
+ const uint2 end = uint2(clamp(ceil(hi), 0.0, size));
+ extent = select(end > origin, end - origin, uint2(0, 0));
+ }
+ if (any(extent == 0)) { origin = 0; extent = 0; }
+ // Statistics cells covering the region (bScale node pixels each).
+ const uint2 lowOrigin = origin / bScale;
+ const uint2 lowEnd = min((origin + extent + bScale - 1) / bScale, uint2(bLowWidth, bLowHeight));
+ const uint2 lowExtent = any(extent == 0) ? uint2(0, 0) : lowEnd - lowOrigin;
+ Roi.Store3(kRoiFullArgs, uint3((extent + 7) / 8, any(extent == 0) ? 0u : 1u));
+ Roi.Store3(kRoiLowArgs, uint3((lowExtent + 7) / 8, any(lowExtent == 0) ? 0u : 1u));
+ Roi.Store2(kRoiOrigin, origin);
+ Roi.Store2(kRoiSize, extent);
+ Roi.Store2(kRoiLowOrigin, lowOrigin);
+ Roi.Store2(kRoiLowSize, lowExtent);
+ Roi.Store2(kRoiFaces, uint2(faces, bFlags));
+}
diff --git a/shaders/BeautyStats.hlsl b/shaders/BeautyStats.hlsl
new file mode 100644
index 00000000..4ae76a88
--- /dev/null
+++ b/shaders/BeautyStats.hlsl
@@ -0,0 +1,34 @@
+// Beauty node, smoothing step 1: statistics of the face-restored picture P on a
+// coarse grid (bScale x bScale node pixels per cell): the mean perceptual colour
+// and the mean squared perceptual luma. With the blur passes they become the
+// local mean / variance of a fast guided filter (He & Sun 2015) - the
+// variance-adaptive skin blend of GPUPixel's BeautyFaceUnitFilter (pixpark/gpupixel
+// ef552bf, Apache-2.0) at a fraction of the cost, and without SkinSoft's sparse
+// 9-tap blur, which ghosts at large radii.
+#include "Beauty.hlsli"
+
+Texture2D<float4> Input : register(t0);
+Texture2D<float4> Original : register(t1);
+StructuredBuffer<BeautyFace> Faces : register(t2);
+ByteAddressBuffer Roi : register(t3);
+RWTexture2D<float4> Stats : register(u0);
+
+[numthreads(8, 8, 1)]
+void main(uint3 id : SV_DispatchThreadID) {
+ const uint2 lowExtent = Roi.Load2(kRoiLowSize);
+ if (any(id.xy >= lowExtent)) return;
+ const uint2 cell = Roi.Load2(kRoiLowOrigin) + id.xy;
+ const uint2 first = cell * bScale;
+ const uint2 last = min(first + bScale, uint2(bWidth, bHeight));
+ float3 sum = 0.0;
+ float sumYY = 0.0, n = 0.0;
+ for (uint y = first.y; y < last.y; ++y) {
+ for (uint x = first.x; x < last.x; ++x) {
+ float mask;
+ const float3 i = BeautyPerceptual(BeautyRestored(Input, Original, Faces, int2(x, y), mask));
+ const float l = BeautyLuma(i);
+ sum += i; sumYY += l * l; n += 1.0;
+ }
+ }
+ Stats[cell] = n > 0.0 ? float4(sum / n, sumYY / n) : 0.0;
+}
diff --git a/shaders/BeautyTrack.hlsl b/shaders/BeautyTrack.hlsl
new file mode 100644
index 00000000..265bcc9b
--- /dev/null
+++ b/shaders/BeautyTrack.hlsl
@@ -0,0 +1,185 @@
+// Beauty node: shared face tracking, entirely on the GPU, once per source frame.
+//
+// On a detection frame the YuNet candidates (BeautyYuNetDecode.hlsl) go through
+// the same non-maximum suppression as OpenCV's FaceDetectorYN (whole-pixel boxes,
+// highest score first, ties in anchor order, IoU above tNms drops a box), keeping
+// at most tMaxFaces faces. Those faces update up to eight tracks: stable ids, an
+// alpha-beta filter (position weight tAlpha, velocity weight kBeta) so a face
+// does not jitter between detections or lag behind on steady motion, and a
+// grace period followed by a fade when a face is lost. Every other frame only
+// advances the tracks by their velocity. Nothing is read back for the picture.
+#include "BeautyFaces.hlsli"
+
+cbuffer TrackParams : register(b0) {
+ uint tDetWidth; uint tDetHeight; // detector content size, pixels
+ uint tCapacity; // candidate list capacity
+ uint tFlags; // bit 0 detected this frame, bit 1 reset, bit 2 still picture, bit 3 no prediction
+ float tDtMs; // time since the previous frame (source timestamps)
+ float tAlpha; // weight of a new detection, 1 = follow it exactly
+ float tNms; // suppression IoU
+ float tGraceMs; // a lost face stays this long
+ float tFadeMs; // then fades out over this long
+ uint tMaxFaces; // 1 .. 8
+ float tScoreThreshold;
+ uint tReserved0; uint tReserved1; uint tReserved2; uint tReserved3; uint tReserved4;
+};
+RWStructuredBuffer<BeautyFace> Faces : register(u0);
+RWByteAddressBuffer Candidates : register(u1);
+
+static const uint kGroup = 1024u;
+static const float kBeta = 0.25; // velocity correction per detection
+static const float kMaxSpeed = 0.004; // frame fractions per ms
+static const float kMatchIou = 0.15;
+
+// 24 KB of the 32 KB limit: boxes are whole pixels as 16-bit pairs, a removed
+// candidate has a negative score.
+groupshared float gScore[kGroup];
+groupshared uint gId[kGroup];
+groupshared uint2 gBox[kGroup];
+groupshared float gBestScore[kGroup];
+groupshared uint gBestIndex[kGroup];
+groupshared uint gKept[kBeautyMaxFaces];
+groupshared uint gKeptCount;
+
+uint pack16(int a, int b) { return (uint(a) & 0xffffu) | (uint(b) << 16); }
+int4 unpackBox(uint2 p) {
+ return int4((int(p.x << 16)) >> 16, int(p.x) >> 16, (int(p.y << 16)) >> 16, int(p.y) >> 16);
+}
+float overlapInt(int4 a, int4 b) {
+ const int x1 = max(a.x, b.x), y1 = max(a.y, b.y);
+ const int x2 = min(a.x + a.z, b.x + b.z), y2 = min(a.y + a.w, b.y + b.w);
+ const int inter = (x2 > x1 && y2 > y1) ? (x2 - x1) * (y2 - y1) : 0;
+ const int uni = a.z * a.w + b.z * b.w - inter;
+ return uni > 0 ? float(inter) / float(uni) : 0.0;
+}
+// Normalised centre / half-size boxes.
+float overlap(float4 a, float4 b) {
+ const float2 lo = max(a.xy - a.zw, b.xy - b.zw), hi = min(a.xy + a.zw, b.xy + b.zw);
+ const float2 extent = max(hi - lo, 0.0);
+ const float inter = extent.x * extent.y;
+ const float uni = 4.0 * (a.z * a.w + b.z * b.w) - inter;
+ return uni > 0.0 ? inter / uni : 0.0;
+}
+
+[numthreads(1024, 1, 1)]
+void main(uint t : SV_GroupIndex) {
+ const bool detected = (tFlags & 1u) != 0;
+ const uint n = detected ? min(Candidates.Load(0), min(tCapacity, kGroup)) : 0u;
+ gScore[t] = -1.0;
+ gId[t] = 0xffffffffu;
+ gBox[t] = uint2(0u, 0u);
+ if (t < n) {
+ const uint o = 16u + t * 64u;
+ const float4 box = asfloat(Candidates.Load4(o));
+ const uint4 tail = Candidates.Load4(o + 48u);
+ const float score = asfloat(tail.z);
+ const bool valid = score >= tScoreThreshold && box.z > 0.0 && box.w > 0.0 && !any(isnan(box)) && !any(isinf(box)) &&
+ all(abs(box) < 16384.0);
+ const int4 b = int4(box); // truncation toward zero, like OpenCV's Rect2i
+ gScore[t] = valid ? score : -1.0;
+ gId[t] = tail.w;
+ gBox[t] = uint2(pack16(b.x, b.y), pack16(b.z, b.w));
+ }
+ if (t == 0) gKeptCount = 0u;
+ GroupMemoryBarrierWithGroupSync();
+
+ // Greedy suppression, tMaxFaces rounds of "best remaining box, drop what overlaps it".
+ for (uint k = 0; k < min(tMaxFaces, kBeautyMaxFaces); ++k) {
+ gBestScore[t] = gScore[t];
+ gBestIndex[t] = t;
+ GroupMemoryBarrierWithGroupSync();
+ for (uint stride = kGroup / 2; stride > 0; stride >>= 1) {
+ if (t < stride) {
+ const float a = gBestScore[t], b = gBestScore[t + stride];
+ const uint ia = gBestIndex[t], ib = gBestIndex[t + stride];
+ if (b > a || (b == a && b >= 0.0 && gId[ib] < gId[ia])) { gBestScore[t] = b; gBestIndex[t] = ib; }
+ }
+ GroupMemoryBarrierWithGroupSync();
+ }
+ const bool found = gBestScore[0] >= 0.0;
+ const uint winner = gBestIndex[0];
+ if (found && t == 0) { gKept[k] = winner; gKeptCount = k + 1u; }
+ if (found && t < n && gScore[t] >= 0.0 && (t == winner || overlapInt(unpackBox(gBox[t]), unpackBox(gBox[winner])) > tNms))
+ gScore[t] = -1.0;
+ GroupMemoryBarrierWithGroupSync();
+ }
+ if (t != 0) return;
+
+ const bool reset = (tFlags & 2u) != 0, still = (tFlags & 4u) != 0, predict = (tFlags & 8u) == 0 && !still;
+ BeautyFace header = Faces[0];
+ uint count = (reset || still) ? 0u : min(header.meta.x, kBeautyMaxFaces);
+ uint nextId = reset ? 1u : max(header.meta.y, 1u);
+ BeautyFace tracks[kBeautyMaxFaces];
+ bool matched[kBeautyMaxFaces];
+ for (uint i = 0; i < kBeautyMaxFaces; ++i) { tracks[i] = Faces[1 + i]; matched[i] = false; }
+
+ // 1. Advance every track to this frame.
+ for (uint a = 0; a < count; ++a) {
+ tracks[a].motion.z += tDtMs;
+ if (predict && tracks[a].motion.z <= tGraceMs) tracks[a].box.xy += tracks[a].motion.xy * tDtMs;
+ }
+ // 2. Detections, best first, update the closest unmatched track or start one.
+ const float2 det = float2(max(tDetWidth, 1u), max(tDetHeight, 1u));
+ for (uint d = 0; d < gKeptCount; ++d) {
+ const uint o = 16u + gKept[d] * 64u;
+ const float4 raw = asfloat(Candidates.Load4(o));
+ const float4 eyes = asfloat(Candidates.Load4(o + 16u)); // right eye x, y, left eye x, y
+ const float score = asfloat(Candidates.Load(o + 56u));
+ const float4 box = float4((raw.xy + raw.zw * 0.5) / det, raw.zw * 0.5 / det);
+ float2 roll = eyes.zw - eyes.xy;
+ if (roll.x < 0.0) roll = -roll;
+ roll = dot(roll, roll) > 1e-6 ? normalize(roll) : float2(1.0, 0.0);
+ int best = -1; float bestOverlap = kMatchIou;
+ for (uint j = 0; j < count; ++j) {
+ if (matched[j]) continue;
+ const float v = overlap(tracks[j].box, box);
+ if (v > bestOverlap) { bestOverlap = v; best = int(j); }
+ }
+ if (best >= 0) {
+ BeautyFace f = tracks[best];
+ const float2 innovation = box.xy - f.box.xy;
+ // A jump of more than half a face is a new position, not noise.
+ const bool jump = length(innovation / max(f.box.zw, 1e-4)) > 1.0;
+ const float alpha = (still || jump) ? 1.0 : tAlpha;
+ if (predict && f.motion.z > 0.0) {
+ const float2 v = f.motion.xy + kBeta * innovation / max(f.motion.z, 1.0);
+ f.motion.xy = clamp(v, -kMaxSpeed, kMaxSpeed);
+ }
+ if (jump) f.motion.xy = 0.0;
+ f.box = lerp(f.box, box, alpha);
+ const float2 r = lerp(f.shape.xy, roll, alpha);
+ f.shape.xy = dot(r, r) > 1e-6 ? normalize(r) : roll;
+ f.shape.z = score;
+ f.shape.w = 1.0;
+ f.motion.z = 0.0;
+ f.meta.y += 1u;
+ tracks[best] = f;
+ matched[best] = true;
+ } else if (count < min(tMaxFaces, kBeautyMaxFaces)) {
+ BeautyFace f;
+ f.box = box;
+ f.shape = float4(roll, score, 1.0);
+ f.motion = 0.0;
+ f.meta = uint4(nextId++, 1u, 0u, 0u);
+ tracks[count] = f;
+ matched[count] = true;
+ ++count;
+ }
+ }
+ // 3. Presence: full during the grace period after the last match, then a fade.
+ uint kept = 0;
+ for (uint m = 0; m < count; ++m) {
+ BeautyFace f = tracks[m];
+ f.shape.w = saturate(1.0 - max(f.motion.z - tGraceMs, 0.0) / max(tFadeMs, 1.0));
+ if (f.motion.z > tGraceMs) f.motion.xy = 0.0;
+ if (f.shape.w <= 0.0) continue;
+ tracks[kept++] = f;
+ }
+ header.meta = uint4(kept, nextId, header.meta.z + 1u, n);
+ Faces[0] = header;
+ for (uint w = 0; w < kBeautyMaxFaces; ++w) {
+ BeautyFace f = tracks[w];
+ if (w >= kept) { f.box = 0.0; f.shape = float4(1.0, 0.0, 0.0, 0.0); f.motion = 0.0; f.meta = 0u; }
+ Faces[1 + w] = f;
+ }
+}
diff --git a/src/beauty/FaceTracker.cpp b/src/beauty/FaceTracker.cpp
new file mode 100644
index 00000000..d6b6d6f4
--- /dev/null
+++ b/src/beauty/FaceTracker.cpp
@@ -0,0 +1,188 @@
+#include "veyra/beauty/FaceTracker.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <format>
+
+#include "veyra/Log.h"
+#include "veyra/RuntimePaths.h"
+
+namespace veyra::beauty {
+namespace {
+constexpr const wchar_t* kModelNames[] = {L"face_detection_yunet_2023mar.onnx", L"face_detection_yunet_2026may.onnx"};
+constexpr UINT kTrackConstants = 16;
+constexpr UINT kDescriptorsPerSlot = 3; // t0 (unused), u0 faces, u1 candidates
+constexpr UINT64 kFaceBytes = 64;
+
+pipeline::ComPtr<ID3D12Resource> makeBuffer(ID3D12Device* device, UINT64 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 = bytes; d.Height = 1; d.DepthOrArraySize = 1; d.MipLevels = 1;
+ d.SampleDesc.Count = 1; d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Flags = flags;
+ pipeline::ComPtr<ID3D12Resource> r;
+ if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, IID_PPV_ARGS(&r)))) return nullptr;
+ return r;
+}
+uint32_t bitsOf(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }
+} // namespace
+
+std::filesystem::path locateFaceModel()
+{
+ 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)
+ for (const auto* name : kModelNames)
+ if (std::filesystem::is_regular_file(folder / name, ec)) return folder / name;
+ return {};
+}
+
+bool FaceTracker::initialize(ID3D12Device* device, const std::filesystem::path& model, uint32_t ringSlots, std::string& error)
+{
+ shutdown();
+ if (!device || !ringSlots || model.empty()) { error = model.empty() ? "face model file not found" : "invalid face tracker configuration"; return false; }
+ YuNetConfig config;
+ config.ringSlots = ringSlots;
+ config.readback = false; // the tracking pass consumes the candidates on the GPU
+ config.scoreThreshold = threshold_;
+ if (!detector_.initialize(device, model, config, error)) { shutdown(); return false; }
+ std::vector<uint8_t> cs;
+ if (!pipeline::loadShaderBytes("BeautyTrack.dxil", cs) ||
+ !track_.create(device, cs, ringSlots * kDescriptorsPerSlot, 1, 2, kTrackConstants)) {
+ error = "face tracking pass creation failed"; shutdown(); return false;
+ }
+ 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; }
+ 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; }
+ // SRVs go through a non-visible heap (DescriptorStager's driver workaround); UAVs are written directly.
+ D3D12_SHADER_RESOURCE_VIEW_DESC none{};
+ none.Format = DXGI_FORMAT_R32_TYPELESS;
+ none.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ none.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ none.Buffer.NumElements = 1;
+ none.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
+ device->CreateShaderResourceView(nullptr, &none, staging_->GetCPUDescriptorHandleForHeapStart());
+ const auto at = [&](UINT index) { auto h = track_.heap->GetCPUDescriptorHandleForHeapStart(); h.ptr += SIZE_T(index) * track_.increment; return h; };
+ for (uint32_t s = 0; s < ringSlots; ++s) {
+ device->CopyDescriptorsSimple(1, at(s * kDescriptorsPerSlot), staging_->GetCPUDescriptorHandleForHeapStart(),
+ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ D3D12_UNORDERED_ACCESS_VIEW_DESC faces{};
+ faces.Format = DXGI_FORMAT_UNKNOWN;
+ faces.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ faces.Buffer.NumElements = kFaceEntries;
+ faces.Buffer.StructureByteStride = UINT(kFaceBytes);
+ device->CreateUnorderedAccessView(faces_.Get(), nullptr, &faces, at(s * kDescriptorsPerSlot + 1));
+ D3D12_UNORDERED_ACCESS_VIEW_DESC raw{};
+ raw.Format = DXGI_FORMAT_R32_TYPELESS;
+ raw.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ raw.Buffer.NumElements = UINT(detector_.candidateBufferBytes() / 4);
+ raw.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
+ device->CreateUnorderedAccessView(detector_.candidateBuffer(s), nullptr, &raw, at(s * kDescriptorsPerSlot + 2));
+ readbacks_.push_back(makeBuffer(device, kFaceBytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST));
+ if (!readbacks_.back()) { error = "face status readback allocation failed"; shutdown(); return false; }
+ }
+ pending_.assign(ringSlots, false);
+ slots_ = ringSlots;
+ ready_ = true;
+ log::info("beauty-detect", std::format("face tracker ready: {}; model {}; slots {}", detector_.modelDescription(),
+ model.filename().string(), ringSlots));
+ return true;
+}
+
+void FaceTracker::shutdown()
+{
+ detector_.shutdown();
+ track_ = {};
+ staging_.Reset();
+ faces_.Reset();
+ readbacks_.clear();
+ pending_.clear();
+ slots_ = 0;
+ ready_ = haveFrame_ = detectedOnce_ = detectedNow_ = false;
+ lastFrameId_ = detections_ = 0;
+ lastPts_ = lastDetectPts_ = 0.0;
+ faceCount_ = candidates_ = 0;
+}
+
+void FaceTracker::configure(const engine::BeautyDetection& detection, float minConfidence)
+{
+ detection_ = detection;
+ threshold_ = std::clamp(minConfidence, 0.3f, 0.95f);
+ detector_.setScoreThreshold(threshold_);
+}
+
+bool FaceTracker::record(ID3D12GraphicsCommandList* list, pipeline::StateTracker& tracker, const Frame& f)
+{
+ detectedNow_ = false;
+ if (!ready_ || !list || f.slot >= slots_ || !f.source || !f.width || !f.height) return false;
+ // A repeated frame (paused tuning, a redraw) keeps its faces: no detection, no time.
+ const bool sameFrame = haveFrame_ && !f.reset && f.frameId == lastFrameId_;
+ double dt = 0.0;
+ if (haveFrame_ && !f.reset && !sameFrame) dt = std::clamp(f.ptsMs - lastPts_, 0.0, 250.0);
+ const double interval = 1000.0 / std::max(detection_.rateHz(), 1.0f);
+ const bool due = f.everyFrame || f.still || f.reset || !detectedOnce_ || f.ptsMs < lastDetectPts_ ||
+ f.ptsMs - lastDetectPts_ >= interval - 0.5;
+ const bool detect = !sameFrame && due;
+ const double scale = double(detection_.inputLongSide()) / double(std::max(f.width, f.height));
+ const uint32_t width = std::clamp(uint32_t(std::lround(f.width * scale)), 32u, 640u);
+ const uint32_t height = std::clamp(uint32_t(std::lround(f.height * scale)), 32u, 640u);
+ if (detect) {
+ YuNetGpu::Source source;
+ source.texture = f.source; source.width = f.width; source.height = f.height; source.hdr = f.hdr;
+ if (!detector_.record(list, f.slot, source, width, height)) return false;
+ ++detections_;
+ lastDetectPts_ = f.ptsMs;
+ detectedOnce_ = detectedNow_ = true;
+ }
+ uint32_t c[kTrackConstants]{};
+ c[0] = width; c[1] = height; c[2] = detector_.candidateCapacity();
+ c[3] = (detect ? 1u : 0u) | (f.reset ? 2u : 0u) | (f.still ? 4u : 0u);
+ c[4] = bitsOf(float(dt));
+ c[5] = bitsOf(1.0f - 0.8f * detection_.stability);
+ c[6] = bitsOf(0.3f);
+ // Between detections a face is kept a little longer than one detection interval.
+ c[7] = bitsOf(float(std::max(50.0, (f.everyFrame || f.still ? 1000.0 / 60.0 : interval) * 1.5)));
+ c[8] = bitsOf(150.0f);
+ c[9] = detection_.maxFaces;
+ c[10] = bitsOf(threshold_);
+ tracker.transition(list, faces_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ const auto gpu = [&](UINT index) { return track_.heap->GetGPUDescriptorHandleForHeapStart().ptr + UINT64(index) * track_.increment; };
+ track_.bind(list, reinterpret_cast<const float*>(c), gpu(f.slot * kDescriptorsPerSlot), gpu(f.slot * kDescriptorsPerSlot + 1));
+ list->Dispatch(1, 1, 1);
+ tracker.uavBarrier(list, faces_.Get());
+ tracker.transition(list, faces_.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);
+ 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;
+ if (!sameFrame) { lastPts_ = f.ptsMs; lastFrameId_ = f.frameId; }
+ haveFrame_ = true;
+ return true;
+}
+
+void FaceTracker::collect(uint32_t slot)
+{
+ if (!ready_ || slot >= slots_ || !pending_[slot]) return;
+ void* mapped = nullptr;
+ D3D12_RANGE range{0, SIZE_T(kFaceBytes)};
+ if (SUCCEEDED(readbacks_[slot]->Map(0, &range, &mapped)) && mapped) {
+ uint32_t meta[4];
+ std::memcpy(meta, static_cast<const uint8_t*>(mapped) + 48, sizeof(meta));
+ faceCount_ = std::min(meta[0], 8u);
+ candidates_ = meta[3];
+ D3D12_RANGE none{0, 0};
+ readbacks_[slot]->Unmap(0, &none);
+ }
+ pending_[slot] = false;
+}
+} // namespace veyra::beauty
diff --git a/src/beauty/YuNetGpu.cpp b/src/beauty/YuNetGpu.cpp
index 78df1149..2969a76b 100644
--- a/src/beauty/YuNetGpu.cpp
+++ b/src/beauty/YuNetGpu.cpp
@@ -603,7 +603,7 @@ struct YuNetGpu::Impl {
list->SetComputeRootSignature(rootSignature.Get());
if (source) {
D3D12_SHADER_RESOURCE_VIEW_DESC sd{};
- sd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
+ sd.Format = source->texture->GetDesc().Format; // RGBA16F or RGBA32F, both read as float4
sd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
sd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
sd.Texture2D.MipLevels = 1;
@@ -663,9 +663,13 @@ struct YuNetGpu::Impl {
uavBarrier(list);
if (profileHeap) list->EndQuery(profileHeap, D3D12_QUERY_TYPE_TIMESTAMP, profileBase + 1 + uint32_t(i));
}
- transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
- list->CopyBufferRegion(readbacks[slot].Get(), 0, candidates[slot].Get(), 0, candidateBytes);
- transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ if (cfg.readback) {
+ transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
+ list->CopyBufferRegion(readbacks[slot].Get(), 0, candidates[slot].Get(), 0, candidateBytes);
+ transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ } else {
+ uavBarrier(list);
+ }
return true;
}
@@ -697,6 +701,13 @@ void YuNetGpu::setProfiler(ID3D12QueryHeap* heap, uint32_t baseIndex) { impl_->p
uint64_t YuNetGpu::weightBytes() const { return uint64_t(impl_->weights.size()) * 4; }
uint64_t YuNetGpu::workingSetBytes() const { return impl_->workingSet; }
uint64_t YuNetGpu::multiplyAccumulates(uint32_t w, uint32_t h) const { return impl_->macs(w, h); }
+ID3D12Resource* YuNetGpu::candidateBuffer(uint32_t slot) const
+{
+ return impl_->ready && slot < impl_->candidates.size() ? impl_->candidates[slot].Get() : nullptr;
+}
+uint64_t YuNetGpu::candidateBufferBytes() const { return impl_->candidateBytes; }
+uint32_t YuNetGpu::candidateCapacity() const { return impl_->cfg.candidateCapacity; }
+void YuNetGpu::setScoreThreshold(float threshold) { impl_->cfg.scoreThreshold = threshold; }
ID3D12Resource* YuNetGpu::inputBuffer() const
{
return impl_->ready ? impl_->buffers[size_t(impl_->tensors[size_t(impl_->inputTensor)].buffer)].Get() : nullptr;
diff --git a/src/engine/EffectChain.cpp b/src/engine/EffectChain.cpp
index d4b52568..aa64bf35 100644
--- a/src/engine/EffectChain.cpp
+++ b/src/engine/EffectChain.cpp
@@ -14,9 +14,8 @@ constexpr std::array<EffectInfo, effectTypeCount> kCatalog{{
{EffectType::Protection, effectTypeName(EffectType::Protection), "NR 保护区域", 1, false, false, false, false, false},
{EffectType::VideoHdr, effectTypeName(EffectType::VideoHdr), "RTX Video HDR", 1, false, false, true, false, false},
{EffectType::FrameGeneration, effectTypeName(EffectType::FrameGeneration), "补帧", 1, false, true, false, false, false},
- // Beauty stays hidden until its executor ships; the engine and file formats already know it.
{EffectType::AntiAliasing, effectTypeName(EffectType::AntiAliasing), "抗锯齿", kMaxAntiAliasInstances, true, false, false, false, false, false},
- {EffectType::Beauty, effectTypeName(EffectType::Beauty), "美颜", kMaxBeautyInstances, true, false, false, false, false, true},
+ {EffectType::Beauty, effectTypeName(EffectType::Beauty), "美颜", kMaxBeautyInstances, true, false, false, false, false, false},
}};
} // namespace
@@ -242,6 +241,8 @@ ChainValidation validateChain(const EffectChain& chain) {
return {false, "节点模式已取消 NR 保护区域,请迁移旧节点配置"};
if(node.type==EffectType::NrEnhance&&!pipeline::validNrSizePolicy(node.nr.sizePolicy))
return {false, "NR 内部处理分辨率非法"};
+ if(node.type==EffectType::Beauty&&!node.beauty.validate().empty())
+ return {false, "美颜参数超出范围"};
++seen[index];
if (node.enabled) lastEnabled = i;
}
@@ -249,6 +250,7 @@ ChainValidation validateChain(const EffectChain& chain) {
const auto& info = kCatalog[t];
if (seen[t] > info.maxInstances) return {false, "该效果数量超出上限"};
}
+ if (!chain.beautyDetection.validate().empty()) return {false, "美颜人脸识别设置超出范围"};
// Frame generation always runs on the chain's final output: the present
// sink owns the swapchain and the OSD/subtitles are composited after it.
// The UI refuses to move it, and this is the engine-side guard.
@@ -293,6 +295,7 @@ EffectChain toChain(const EnhancementSettings& settings) {
chain.mode = ChainMode::List;
chain.fgStrictAdmission = settings.fgStrictAdmission;
chain.fgMultiplier = std::max(2u, settings.multiplier);
+ chain.beautyDetection = settings.beautyDetection;
// A full chain never overwrites its last node: it is flagged, and validateChain()
// refuses it, instead of a stage disappearing (the old 16-node chain did that).
ChainNode spill;
@@ -305,7 +308,8 @@ EffectChain toChain(const EnhancementSettings& settings) {
return node;
};
// List order is the product order: colour (fused into the ingest shader),
- // anti-aliasing (source size), SR, NR layers, protection, Video HDR, frame generation.
+ // anti-aliasing (source size), SR, NR layers, protection, the beauty group,
+ // Video HDR, frame generation.
append(EffectType::Color, settings.color.enabled).color = settings.color;
for(uint32_t i=0;i<std::min(settings.additionalColorCount,kMaxColorInstances-1);++i)
append(EffectType::Color,settings.additionalColors[i].enabled).color=settings.additionalColors[i];
@@ -332,6 +336,11 @@ EffectChain toChain(const EnhancementSettings& settings) {
nr.nr.sizePolicy = layer.sizePolicy;
}
append(EffectType::Protection, settings.protection.enabled).protection = settings.protection;
+ // Untouched beauty adds no node either.
+ if(settings.beauty.configured()||settings.additionalBeautyCount)
+ append(EffectType::Beauty,settings.beauty.enabled).beauty=settings.beauty;
+ for(uint32_t i=0;i<std::min(settings.additionalBeautyCount,kMaxBeautyInstances-1);++i)
+ append(EffectType::Beauty,settings.additionalBeauty[i].enabled).beauty=settings.additionalBeauty[i];
append(EffectType::VideoHdr, settings.videoHdr.enabled).videoHdr = settings.videoHdr;
append(EffectType::FrameGeneration, settings.multiplier > 1);
return chain;
@@ -349,7 +358,8 @@ std::optional<ChainRuntimeOrder> runtimeOrder(const EffectChain& chain) {
ChainValidation restoreRuntimeOrder(const EnhancementSettings& settings, const ChainRuntimeOrder& order,
EffectChain& output) {
if (order.nodeCount > kMaxChainNodes || settings.nrLayerCount > kMaxNrInstances ||
- settings.additionalColorCount >= kMaxColorInstances || settings.additionalAntiAliasCount >= kMaxAntiAliasInstances)
+ settings.additionalColorCount >= kMaxColorInstances || settings.additionalAntiAliasCount >= kMaxAntiAliasInstances ||
+ settings.additionalBeautyCount >= kMaxBeautyInstances)
return {false, "运行节点顺序或实例数量无效"};
const auto source = toChain(settings);
EffectChain restored;
@@ -357,6 +367,7 @@ ChainValidation restoreRuntimeOrder(const EnhancementSettings& settings, const C
restored.nodeCount = order.nodeCount;
restored.fgMultiplier = source.fgMultiplier;
restored.fgStrictAdmission = source.fgStrictAdmission;
+ restored.beautyDetection = source.beautyDetection;
std::array<bool, kMaxChainNodes> used{};
for (uint32_t i = 0; i < order.nodeCount; ++i) {
if (uint32_t(order.types[i]) >= effectTypeCount) return {false, "运行节点类型无效"};
@@ -371,7 +382,8 @@ ChainValidation restoreRuntimeOrder(const EnhancementSettings& settings, const C
const auto& node = source.nodes[i];
if (node.enabled || (node.type == EffectType::NrEnhance && settings.nrLayerCount) ||
(node.type == EffectType::Color && settings.additionalColorCount) ||
- (node.type == EffectType::AntiAliasing && settings.additionalAntiAliasCount))
+ (node.type == EffectType::AntiAliasing && settings.additionalAntiAliasCount) ||
+ (node.type == EffectType::Beauty && settings.additionalBeautyCount))
return {false, "运行节点顺序遗漏实例参数"};
}
const auto valid = validateChain(restored);
@@ -391,6 +403,11 @@ void fromChain(const EffectChain& chain, EnhancementSettings& settings) {
settings.additionalAntiAlias = {};
settings.additionalAntiAliasCount = 0;
bool firstAntiAlias = true;
+ settings.beauty = {};
+ settings.additionalBeauty = {};
+ settings.additionalBeautyCount = 0;
+ settings.beautyDetection = chain.beautyDetection;
+ bool firstBeauty = true;
settings.sr = false;
settings.nr = false;
settings.nrLayers = {};
@@ -463,7 +480,16 @@ void fromChain(const EffectChain& chain, EnhancementSettings& settings) {
aa.enabled=node.enabled;
}
break;
- case EffectType::Beauty: // reserved: no executor or settings yet
+ case EffectType::Beauty:
+ if(firstBeauty){
+ settings.beauty=node.beauty;
+ settings.beauty.enabled=node.enabled;
+ firstBeauty=false;
+ }else if(settings.additionalBeautyCount<settings.additionalBeauty.size()){
+ auto& beauty=settings.additionalBeauty[settings.additionalBeautyCount++];
+ beauty=node.beauty;
+ beauty.enabled=node.enabled;
+ }
break;
case EffectType::Count:
break;
@@ -693,6 +719,11 @@ bool requiresGraphRebuild(const EnhancementSettings& savedPrevious, const Enhanc
if(!previous.antiAlias.sameStructure(next.antiAlias))return true;
for(uint32_t i=0;i<std::min(next.additionalAntiAliasCount,kMaxAntiAliasInstances-1);++i)
if(!previous.additionalAntiAlias[i].sameStructure(next.additionalAntiAlias[i]))return true;
+ // Beauty: a node exists while it is enabled; every value inside it is live.
+ if(previous.additionalBeautyCount!=next.additionalBeautyCount)return true;
+ if(!previous.beauty.sameStructure(next.beauty))return true;
+ for(uint32_t i=0;i<std::min(next.additionalBeautyCount,kMaxBeautyInstances-1);++i)
+ if(!previous.additionalBeauty[i].sameStructure(next.additionalBeauty[i]))return true;
if(previous.additionalColorCount!=next.additionalColorCount)return true;
for(uint32_t i=0;i<std::min(next.additionalColorCount,kMaxColorInstances-1);++i){
const auto& a=previous.additionalColors[i];
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index b70d7680..5e1e0e66 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -758,7 +758,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool admitted=(tested||(autoRequested&&automatic==desc.nrLayersSizePolicy.begin()&&selected.settings.activeAutoNrLayerCount()==1))&&
!nrAutoPoolUnavailable&&selected.settings.activeNrLayerCount()<=2&&
!isCapture&&!isImage&&desc.enableNr&&!desc.enableSr&&!desc.enableFg&&
- !desc.hdrWorking()&&!desc.videoHdr.enabled&&!desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.runtimeNodeOrder&&desc.nrHoldStrength==0&&
+ !desc.hdrWorking()&&!desc.videoHdr.enabled&&!desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.beautyActive()&&!desc.runtimeNodeOrder&&desc.nrHoldStrength==0&&
currentNrRuntime(desc.nrRuntime)==NrRuntime::Ampere&&desc.opticalFlowBackend==OpticalFlowBackend::Nvidia&&
desc.nrMotion==MotionSource::OpticalFlow&&
nvidiaAdapter&&ctx.adapter().deviceId==0x2f04&&desc.workWidth==1920&&desc.workHeight==1080&&
diff --git a/src/engine/EngineControllerImage.cpp b/src/engine/EngineControllerImage.cpp
index cc8ba40c..ca5d40ca 100644
--- a/src/engine/EngineControllerImage.cpp
+++ b/src/engine/EngineControllerImage.cpp
@@ -72,6 +72,11 @@ void EngineController::runLargeImage(HWND window,const sink::RgbaImage& original
desc.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
sink::RgbaImage candidate;TiledImageProcessor::Stats stats;
status(L"正在分块增强大图,保留完整输出尺寸…");
+ // Faces cannot be found tile by tile; the beauty nodes are not applied here.
+ if(requested.beautyEnabled()){
+ veyra::log::warn("image-tiles","beauty nodes are not applied to tiled large images");
+ std::lock_guard lock(mutex_);snapshot_.backendWarning=L"大图分块处理不支持美颜,本图未应用美颜";
+ }
bool processed=false;
try{processed=TiledImageProcessor::process(ctx,ring,original,candidate,desc,stop_,stats,[this](uint32_t n,uint32_t total){status(std::format(L"大图分块增强 {}/{} · 每块独立上下文",n,total));});}
catch(const std::exception& e){veyra::log::warn("image-tiles",std::format("settings exception; retaining previous result: {}",e.what()));}
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index 03e3cf67..eaae4570 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -30,7 +30,7 @@ struct Shared {
// chain is fixed-capacity and trivially copyable, so it can cross the
// process boundary; a worker that sees another version refuses the job
// instead of reading a mismatched layout.
- DWORD signature=magic,version=10,bytes=sizeof(Shared); // 10: 32-node chain with anti-aliasing / beauty payloads
+ DWORD signature=magic,version=11,bytes=sizeof(Shared); // 10: 32-node chain with anti-aliasing; 11: beauty payloads and face detection
EnhancementSettings settings;
EffectChain chain;
wchar_t input[32768]{},output[32768]{},temporary[32768]{};
diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cpp
index 740a6014..ad3c8a38 100644
--- a/src/engine/PresetLibrary.cpp
+++ b/src/engine/PresetLibrary.cpp
@@ -93,6 +93,7 @@ void PresetLibrary::addBuiltins() {
bool PresetLibrary::load() {
error_.clear();
addBuiltins();
+ const auto directBeauty=std::filesystem::path(path_).concat(L".beauty");
const auto directEffects=std::filesystem::path(path_).concat(L".effects");
const auto directNr=std::filesystem::path(path_).concat(L".nr-model");
const auto directDlss=std::filesystem::path(path_).concat(L".dlss-sr");
@@ -128,6 +129,9 @@ bool PresetLibrary::load() {
const auto effectsPath=std::filesystem::path(path_).concat(L".effects");
if(std::filesystem::exists(directEffects))path_=directEffects;
else if(std::filesystem::exists(effectsPath))path_=effectsPath;
+ const auto beautyPath=std::filesystem::path(path_).concat(L".beauty");
+ if(std::filesystem::exists(directBeauty))path_=directBeauty;
+ else if(std::filesystem::exists(beautyPath))path_=beautyPath;
if (!std::filesystem::exists(path_)) return true;
std::error_code ec;
const auto size = std::filesystem::file_size(path_, ec);
@@ -222,7 +226,9 @@ bool PresetLibrary::save() {
// Match PresetStore: never replace a valid file with one our reader rejects.
if (!parse(data, checked, checkedDefault, error_)) return false;
// Opting into a new model must leave the older build's library intact.
- // v14 (anti-aliasing / beauty nodes, chains past 16 nodes) gets its own file too.
+ // v14 (anti-aliasing nodes, chains past 16 nodes) and v15 (beauty nodes) get their own files too.
+ if(data.starts_with("VEYRA_PRESET_LIBRARY 15")&&!path_.wstring().ends_with(L".beauty"))path_=std::filesystem::path(path_).concat(L".beauty");
+ if(!path_.wstring().ends_with(L".beauty")){
if(data.starts_with("VEYRA_PRESET_LIBRARY 14")&&!path_.wstring().ends_with(L".effects"))path_=std::filesystem::path(path_).concat(L".effects");
if(!path_.wstring().ends_with(L".effects")){
if(data.starts_with("VEYRA_PRESET_LIBRARY 13")&&!path_.wstring().ends_with(L".nr-model"))path_=std::filesystem::path(path_).concat(L".nr-model");
@@ -247,6 +253,7 @@ bool PresetLibrary::save() {
}
}
}
+ }
std::error_code ec;
std::filesystem::create_directories(path_.parent_path(), ec);
const auto temporary = std::filesystem::path(path_).concat(L".tmp");
@@ -687,7 +694,14 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
const bool effects=std::any_of(entries_.begin(),entries_.end(),[&](const auto& e){
return effectNodes(e.chain)||(e.nodeConfiguration&&(effectNodes(e.nodeConfiguration->chain)||
(e.nodeConfiguration->editor&&effectNodes(e.nodeConfiguration->editor->nodes))));});
- const int version=std::max(minimumVersion, effects?14:nrModel?13:dlss?12:tuning?11:flow?10:correctionExtended?9:correction?8:vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);
+ // v15: beauty nodes, or the chain's shared face detection values.
+ const auto beautyChain=[](const EffectChain& chain){
+ return chain.beautyDetection!=BeautyDetection{}||std::any_of(chain.nodes.begin(),chain.nodes.begin()+chain.nodeCount,[](const auto& n){
+ return n.type==EffectType::Beauty;});};
+ const bool beauty=std::any_of(entries_.begin(),entries_.end(),[&](const auto& e){
+ return beautyChain(e.chain)||(e.nodeConfiguration&&(beautyChain(e.nodeConfiguration->chain)||
+ (e.nodeConfiguration->editor&&beautyChain(e.nodeConfiguration->editor->nodes))));});
+ const int version=std::max(minimumVersion, beauty?15:effects?14:nrModel?13:dlss?12:tuning?11:flow?10:correctionExtended?9:correction?8:vfg?7:rendering?6:globals?5:editor?4:layerSizes?3:multi?2:1);
o << "VEYRA_PRESET_LIBRARY " << version << '\n' << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';
for (const auto& e : entries_) {
o << std::quoted(utf8(e.name)) << ' ' << std::quoted(utf8(e.note)) << ' '
@@ -722,7 +736,12 @@ std::string PresetLibrary::encodeEntries(const std::vector<PresetEntry>& entries
writeAntiAlias(o, n.aa);
o << ' ';
}
+ if (version>=15 && n.type == EffectType::Beauty) {
+ writeBeauty(o, n.beauty);
+ o << ' ';
+ }
}
+ if (version >= 15) { writeBeautyDetection(o, e.chain.beautyDetection); o << ' '; }
o << ' ';
writeColorSettings(o, e.color, utf8(e.color.lutNameString()));
if (version >= 4) {
@@ -756,7 +775,7 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
std::string magic, quoted;
int version = 0;
size_t count = 0;
- const int allowedVersion=maxVersion>0?std::min(maxVersion,14):14;
+ const int allowedVersion=maxVersion>0?std::min(maxVersion,15):15;
if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > allowedVersion) { error = L"预设库格式或版本不支持"; return false; }
if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }
def = wide(quoted);
@@ -829,7 +848,11 @@ bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out
if (version >= 14 && node.type == EffectType::AntiAliasing && !readAntiAlias(in, node.aa)) {
error = L"预设库节点抗锯齿参数损坏"; return false;
}
+ if (version >= 15 && node.type == EffectType::Beauty && !readBeauty(in, node.beauty)) {
+ error = L"预设库节点美颜参数损坏"; return false;
+ }
}
+ if (version >= 15 && !readBeautyDetection(in, e.chain.beautyDetection)) { error = L"预设库美颜人脸识别字段损坏"; return false; }
in >> std::ws;
std::string lut;
// 19 is the current colour-block schema: it includes the per-section
@@ -912,7 +935,12 @@ std::string ChainSessionStore::encode(const ChainSession& session) {
return n.type==EffectType::AntiAliasing||n.type==EffectType::Beauty;});};
const bool effects=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){
return effectNodes(c.chain)||(c.editor&&effectNodes(c.editor->nodes));});
- const int version = effects?9:nrModel?8:dlss?7:tuning?6:vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;
+ const auto beautyChain=[](const EffectChain& chain){
+ return chain.beautyDetection!=BeautyDetection{}||std::any_of(chain.nodes.begin(),chain.nodes.begin()+chain.nodeCount,[](const auto& n){
+ return n.type==EffectType::Beauty;});};
+ const bool beauty=std::any_of(session.configurations.begin(),session.configurations.end(),[&](const auto& c){
+ return beautyChain(c.chain)||(c.editor&&beautyChain(c.editor->nodes));});
+ const int version = beauty?10:effects?9:nrModel?8:dlss?7:tuning?6:vfg?5:rendering?4:editor ? (editor->globals ? 3 : 2) : 1;
out << "VEYRA_CHAIN_SESSION " << version << '\n' << int(session.active) << ' ' << session.initialized[0] << ' ' << session.initialized[1];
if(version>=4)out<<' '<<bool(editor);out<<'\n';
std::vector<PresetEntry> entries;
@@ -966,7 +994,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
std::istringstream in(data); in.imbue(std::locale::classic());
std::string magic, body; int version = 0, active = 0, list = 0, node = 0;
if (!(in >> magic >> version >> active >> list >> node) || magic != "VEYRA_CHAIN_SESSION" ||
- (version < 1 || version > 9) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;
+ (version < 1 || version > 10) || active < 0 || active > 1 || list != 1 || node < 0 || node > 1) return false;
int hasEditor=version>=2?1:0;
if(version>=4&&(!(in>>hasEditor)||hasEditor<0||hasEditor>1))return false;
ChainSession parsed; parsed.active = ChainMode(active); parsed.initialized = {true, node != 0};
@@ -981,7 +1009,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
}
if (!(in >> std::quoted(body))) return false;
std::vector<PresetEntry> entries; std::wstring def, error;
- if (!PresetLibrary::parse(body, entries, def, error, nullptr, true, version>=9?14:version>=8?13:11) || entries.size() != 2 || !def.empty()) return false;
+ if (!PresetLibrary::parse(body, entries, def, error, nullptr, true, version>=10?15:version>=9?14:version>=8?13:11) || entries.size() != 2 || !def.empty()) return false;
for (size_t i = 0; i < entries.size(); ++i) {
if (entries[i].kind != ChainMode(i)) return false;
parsed.configurations[i].chain = entries[i].chain;
@@ -1015,7 +1043,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
}
if (!(in >> std::quoted(body))) return false;
entries.clear(); def.clear(); error.clear();
- if (!PresetLibrary::parse(body, entries, def, error, nullptr, true, version>=9?14:version>=8?13:11) || entries.size() != 1 ||
+ if (!PresetLibrary::parse(body, entries, def, error, nullptr, true, version>=10?15:version>=9?14:version>=8?13:11) || entries.size() != 1 ||
!def.empty() || entries[0].kind != ChainMode::Node || entries[0].chain.nodeCount != count) return false;
editor->nodes = std::move(entries[0].chain);
for (uint32_t i = 0; i < count; ++i) {
@@ -1032,6 +1060,7 @@ bool ChainSessionStore::decode(const std::string& data, ChainSession& session, b
}
bool ChainSessionStore::load(ChainSession& session) {
+ const auto directBeauty=std::filesystem::path(path_).concat(L".beauty");
const auto directEffects=std::filesystem::path(path_).concat(L".effects");
const auto directNr=std::filesystem::path(path_).concat(L".nr-model");
const auto directDlss=std::filesystem::path(path_).concat(L".dlss-sr");
@@ -1065,6 +1094,9 @@ bool ChainSessionStore::load(ChainSession& session) {
const auto effectsPath=std::filesystem::path(path_).concat(L".effects");
if(std::filesystem::exists(directEffects,ec))path_=directEffects;
else if(std::filesystem::exists(effectsPath,ec))path_=effectsPath;
+ const auto beautyPath=std::filesystem::path(path_).concat(L".beauty");
+ if(std::filesystem::exists(directBeauty,ec))path_=directBeauty;
+ else if(std::filesystem::exists(beautyPath,ec))path_=beautyPath;
const bool exists = std::filesystem::exists(path_, ec);
if (!exists && !ec) return true;
const auto size = std::filesystem::file_size(path_, ec);
@@ -1094,6 +1126,8 @@ bool ChainSessionStore::save(const ChainSession& session) {
const auto data = encode(session);
ChainSession checked;
if (!decode(data, checked)) { error_ = L"模式会话编码校验失败,未保存"; return false; }
+ if(data.starts_with("VEYRA_CHAIN_SESSION 10")&&!path_.wstring().ends_with(L".beauty"))path_=std::filesystem::path(path_).concat(L".beauty");
+ if(!path_.wstring().ends_with(L".beauty")){
if(data.starts_with("VEYRA_CHAIN_SESSION 9")&&!path_.wstring().ends_with(L".effects"))path_=std::filesystem::path(path_).concat(L".effects");
if(!path_.wstring().ends_with(L".effects")){
if(data.starts_with("VEYRA_CHAIN_SESSION 8")&&!path_.wstring().ends_with(L".nr-model"))path_=std::filesystem::path(path_).concat(L".nr-model");
@@ -1118,6 +1152,7 @@ bool ChainSessionStore::save(const ChainSession& session) {
}
}
}
+ }
std::error_code ec;
if (!path_.parent_path().empty()) std::filesystem::create_directories(path_.parent_path(), ec);
if (ec) { error_ = L"模式会话目录无法创建"; return false; }
diff --git a/src/engine/PreviewGpuSession.cpp b/src/engine/PreviewGpuSession.cpp
index cfdcc038..7529ba9a 100644
--- a/src/engine/PreviewGpuSession.cpp
+++ b/src/engine/PreviewGpuSession.cpp
@@ -25,7 +25,7 @@ bool PreviewGpuSession::requestAllowed(const EnhancementSettings& settings){
return settings.validate().empty()&&(settings.nr||settings.sr)&&settings.multiplier==1&&
currentNrRuntime(settings.nrRuntime)==NrRuntime::Ampere&&settings.activeNrLayerCount()<=1&&!settings.activeAutoNrLayerCount()&&
!settings.videoHdr.enabled&&!settings.color.enabled&&settings.additionalColorCount==0&&
- !settings.antiAlias.enabled&&settings.additionalAntiAliasCount==0&&
+ !settings.antiAlias.enabled&&settings.additionalAntiAliasCount==0&&!settings.beautyEnabled()&&
(settings.videoSrQuality==0||settings.videoSrQuality==4);
}
bool PreviewGpuSession::computeAllowed(const gfx::AdapterInfo& adapter,const pipeline::EnhanceGraphDesc& desc){
@@ -38,7 +38,7 @@ bool PreviewGpuSession::computeAllowed(const gfx::AdapterInfo& adapter,const pip
desc.nrRuntime==NrRuntime::Original&&desc.nrLayersExtent.size()==2&&
desc.nrLayersExtent[0]==pipeline::Extent{1920,1080}&&desc.nrLayersExtent[1]==pipeline::Extent{1920,1080}&&
!desc.nrBeforeSr&&!desc.runtimeNodeOrder&&!desc.hdrInput&&!desc.hdrOutput&&!desc.videoHdr.enabled&&
- !desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.nrHoldStrength&&
+ !desc.color.enabled&&!desc.additionalColorCount&&!desc.antiAliasActive()&&!desc.beautyActive()&&!desc.nrHoldStrength&&
!desc.nrTemporal&&std::none_of(desc.nrLayersTemporal.begin(),desc.nrLayersTemporal.end(),[](bool enabled){return enabled;})&&
desc.opticalFlowBackend==OpticalFlowBackend::Nvidia&&desc.enableFg&&
desc.frameGenerationBackend==FrameGenerationBackend::Dlss&&(desc.fgMultiplier==2||desc.fgMultiplier==3);
diff --git a/src/pipeline/BeautyPass.cpp b/src/pipeline/BeautyPass.cpp
new file mode 100644
index 00000000..8dbc1119
--- /dev/null
+++ b/src/pipeline/BeautyPass.cpp
@@ -0,0 +1,202 @@
+#include "veyra/pipeline/BeautyPass.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <format>
+
+namespace veyra::pipeline {
+namespace {
+constexpr UINT kSrvs = 5, kSet = kSrvs + 1; // t0..t4, u0
+constexpr DXGI_FORMAT kColorFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
+constexpr UINT kRegionBytes = 64; // shaders/Beauty.hlsli kRoiBytes
+constexpr UINT kFullArgs = 0, kLowArgs = 12;
+constexpr uint32_t kRestore = 1, kSmooth = 2, kRestoreSkin = 4, kAllSkin = 8, kShowMask = 16, kOriginal = 32;
+uint32_t bitsOf(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }
+}
+
+bool BeautyPass::createStage(ID3D12Device* device, Stage& stage, const char* shader, UINT sets)
+{
+ std::vector<uint8_t> cs;
+ return stage.pass.loadShader(shader, cs) && stage.pass.create(device, cs, sets * kSet, kSrvs, 1, kConstantCount, 0, true);
+}
+
+bool BeautyPass::initialize(ID3D12Device* device, const engine::BeautySettings& settings, uint32_t width, uint32_t height,
+ uint32_t sourceWidth, uint32_t sourceHeight)
+{
+ if (!device || !settings.enabled || !settings.validate().empty() || !width || !height || !sourceWidth || !sourceHeight) return false;
+ settings_ = settings;
+ width_ = width; height_ = height; sourceWidth_ = sourceWidth; sourceHeight_ = sourceHeight;
+ // About 540 statistics rows whatever the node size: 1080p uses 2x2 cells, 4K 4x4.
+ scale_ = std::clamp(uint32_t(std::lround(double(height) / 540.0)), 1u, 8u);
+ lowWidth_ = (width + scale_ - 1) / scale_;
+ lowHeight_ = (height + scale_ - 1) / scale_;
+ D3D12_HEAP_PROPERTIES hp{};
+ hp.Type = D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_RESOURCE_DESC bd{};
+ bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bd.Width = kRegionBytes; bd.Height = 1; bd.DepthOrArraySize = 1; bd.MipLevels = 1; bd.SampleDesc.Count = 1;
+ bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; bd.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &bd, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&region_))))
+ return false;
+ lowA_ = makeTexture(device, lowWidth_, lowHeight_, kColorFormat, true);
+ lowB_ = makeTexture(device, lowWidth_, lowHeight_, kColorFormat, true);
+ D3D12_INDIRECT_ARGUMENT_DESC argument{};
+ argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
+ D3D12_COMMAND_SIGNATURE_DESC sd{};
+ sd.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS);
+ sd.NumArgumentDescs = 1;
+ sd.pArgumentDescs = &argument;
+ if (!lowA_ || !lowB_ || FAILED(device->CreateCommandSignature(&sd, nullptr, IID_PPV_ARGS(&signature_)))) return false;
+ return createStage(device, roi_, "BeautyRoi.dxil", 1) && createStage(device, stats_, "BeautyStats.dxil", 1) &&
+ createStage(device, blur_, "BeautyBlur.dxil", 2) && createStage(device, apply_, "BeautyApply.dxil", 1);
+}
+
+void BeautyPass::createViews(ID3D12Device* device, DescriptorStager& stager, ID3D12Resource* input, ID3D12Resource* output,
+ ID3D12Resource* original, ID3D12Resource* faces)
+{
+ input_ = input; output_ = output; original_ = original; faces_ = faces;
+ D3D12_SHADER_RESOURCE_VIEW_DESC texture{};
+ texture.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
+ texture.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ texture.Texture2D.MipLevels = 1;
+ const auto tex = [&](Stage& stage, UINT set, UINT slot, ID3D12Resource* resource) {
+ auto d = texture;
+ d.Format = resource ? resource->GetDesc().Format : kColorFormat; // the original may be RGBA32F
+ stager.stageSrv(resource, &d, stage.pass.heap.Get(), set * kSet + slot);
+ };
+ D3D12_SHADER_RESOURCE_VIEW_DESC structured{};
+ structured.Format = DXGI_FORMAT_UNKNOWN;
+ structured.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ structured.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ structured.Buffer.NumElements = 9; // FaceTracker::kFaceEntries
+ structured.Buffer.StructureByteStride = 64;
+ D3D12_SHADER_RESOURCE_VIEW_DESC raw{};
+ raw.Format = DXGI_FORMAT_R32_TYPELESS;
+ raw.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ raw.Buffer.NumElements = kRegionBytes / 4;
+ raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
+ 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);
+ };
+ const auto uav = [&](Stage& stage, UINT set, ID3D12Resource* resource) {
+ makeUav(device, resource, kColorFormat, cpuHandleOf(stage.pass, set * kSet + kSrvs));
+ };
+ // Region: faces in, region buffer out.
+ tex(roi_, 0, 0, nullptr); tex(roi_, 0, 1, nullptr); common(roi_, 0); tex(roi_, 0, 4, nullptr);
+ D3D12_UNORDERED_ACCESS_VIEW_DESC regionUav{};
+ regionUav.Format = DXGI_FORMAT_R32_TYPELESS;
+ regionUav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ regionUav.Buffer.NumElements = kRegionBytes / 4;
+ regionUav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
+ device->CreateUnorderedAccessView(region_.Get(), nullptr, &regionUav, cpuHandleOf(roi_.pass, kSrvs));
+ // Statistics of the restored picture.
+ tex(stats_, 0, 0, input); tex(stats_, 0, 1, original); common(stats_, 0); tex(stats_, 0, 4, nullptr); uav(stats_, 0, lowA_.Get());
+ // Blur sets: 0 reads A writes B, 1 reads B writes A.
+ tex(blur_, 0, 0, lowA_.Get()); tex(blur_, 0, 1, nullptr); common(blur_, 0); tex(blur_, 0, 4, nullptr); uav(blur_, 0, lowB_.Get());
+ tex(blur_, 1, 0, lowB_.Get()); tex(blur_, 1, 1, nullptr); common(blur_, 1); tex(blur_, 1, 4, nullptr); uav(blur_, 1, lowA_.Get());
+ // Final pass: the coefficients end in A.
+ tex(apply_, 0, 0, input); tex(apply_, 0, 1, original); common(apply_, 0); tex(apply_, 0, 4, lowA_.Get()); uav(apply_, 0, output);
+}
+
+float BeautyPass::sigmaPixels() const
+{
+ // The radius is the Gaussian sigma in 1080p pixels, scaled with the node's height.
+ return std::max(settings_.radius * float(height_) / 1080.0f, 0.25f);
+}
+
+void BeautyPass::constants(uint32_t* c, bool hdrWorking, bool originalValid) const
+{
+ const auto& s = settings_;
+ uint32_t flags = 0;
+ if (s.restoreActive()) flags |= kRestore;
+ if (s.smoothActive()) flags |= kSmooth;
+ if (s.restoreScope == engine::BeautyRestoreScope::Skin) flags |= kRestoreSkin;
+ if (s.scope == engine::BeautyScope::AllSkin) flags |= kAllSkin;
+ if (s.enabled && s.showMask) flags |= kShowMask;
+ if (originalValid && original_) flags |= kOriginal;
+ c[0] = width_; c[1] = height_; c[2] = sourceWidth_; c[3] = sourceHeight_;
+ c[4] = lowWidth_; c[5] = lowHeight_; c[6] = scale_; c[7] = flags;
+ // "1.0 = white": SDR white, or the 203-nit reference white of scRGB HDR working.
+ c[8] = bitsOf(hdrWorking ? 80.0f / 203.0f : 1.0f);
+ c[9] = bitsOf(s.restoreStrength); c[10] = bitsOf(s.regionExpand); c[11] = bitsOf(s.feather);
+ c[12] = bitsOf(s.strength); c[13] = bitsOf(s.smoothAmount); c[14] = bitsOf(s.detail); c[15] = bitsOf(s.texture);
+ c[16] = bitsOf(s.brighten);
+ c[17] = bitsOf(sigmaPixels() / float(scale_));
+ // Guided-filter regulariser on the perceptual luma variance: what counts as an edge
+ // to keep. Measured on lit faces (scripts/beauty notes): skin 0.002-0.009, eyes
+ // 0.016-0.04 at a 1.5-3% face-height sigma. Detail 0 -> 0.012, 1 -> 0.002.
+ c[18] = bitsOf(0.012f - 0.010f * s.detail);
+ c[19] = bitsOf(s.minConfidence);
+ c[20] = bitsOf(s.hueCenter); c[21] = bitsOf(s.hueRange); c[22] = bitsOf(s.satMin); c[23] = bitsOf(s.satMax);
+ c[24] = bitsOf(s.lumaMin); c[25] = bitsOf(s.lumaMax); c[26] = bitsOf(s.softness); c[27] = 0;
+ c[28] = 8; c[29] = c[30] = c[31] = 0;
+}
+
+bool BeautyPass::dispatch(ID3D12GraphicsCommandList* list, StateTracker& tracker, bool hdrWorking, bool originalValid)
+{
+ if (!list || !input_ || !output_ || input_ == output_ || !faces_) 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);
+ list->CopyResource(output_, input_);
+ const bool restore = settings_.restoreActive() && originalValid && original_;
+ const bool smooth = settings_.smoothActive();
+ const bool mask = settings_.enabled && settings_.showMask;
+ if (!restore && !smooth && !mask) {
+ tracker.transition(list, output_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ return true;
+ }
+ uint32_t c[kConstantCount]{};
+ constants(c, hdrWorking, originalValid);
+ const auto* constants = reinterpret_cast<const float*>(c);
+ const auto bind = [&](Stage& stage, UINT set) {
+ stage.pass.bind(list, constants, gpuHandleOf(stage.pass, set * kSet).ptr, gpuHandleOf(stage.pass, set * kSet + kSrvs).ptr);
+ };
+ 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);
+ // Region of this frame, as dispatch arguments.
+ tracker.transition(list, region_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ bind(roi_, 0);
+ list->Dispatch(1, 1, 1);
+ tracker.uavBarrier(list, region_.Get());
+ tracker.transition(list, region_.Get(), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ if (smooth) {
+ tracker.transition(list, lowA_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ bind(stats_, 0);
+ list->ExecuteIndirect(signature_.Get(), 1, region_.Get(), kLowArgs, nullptr, 0);
+ tracker.uavBarrier(list, lowA_.Get());
+ for (uint32_t pass = 0; pass < 4; ++pass) {
+ ID3D12Resource* source = (pass & 1) ? lowB_.Get() : lowA_.Get();
+ ID3D12Resource* target = (pass & 1) ? lowA_.Get() : lowB_.Get();
+ tracker.transition(list, source, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ tracker.transition(list, target, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ c[27] = pass;
+ bind(blur_, pass & 1);
+ list->ExecuteIndirect(signature_.Get(), 1, region_.Get(), kLowArgs, nullptr, 0);
+ tracker.uavBarrier(list, target);
+ }
+ c[27] = 0;
+ tracker.transition(list, lowA_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ }
+ tracker.transition(list, output_, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ bind(apply_, 0);
+ list->ExecuteIndirect(signature_.Get(), 1, region_.Get(), kFullArgs, nullptr, 0);
+ tracker.uavBarrier(list, output_);
+ tracker.transition(list, output_, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ return true;
+}
+
+std::string BeautyPass::describe() const
+{
+ const auto& s = settings_;
+ std::string text = std::format("restore={} {:.0f}%{} smoothing={} {:.0f}% radius={:.1f} detail={:.0f}% texture={:.0f}% scope={}",
+ s.restore, s.restoreStrength * 100.0f, s.restoreScope == engine::BeautyRestoreScope::Skin ? " skin" : "",
+ s.smooth, s.smoothAmount * 100.0f, s.radius, s.detail * 100.0f, s.texture * 100.0f,
+ s.scope == engine::BeautyScope::AllSkin ? "all-skin" : "faces");
+ return text + std::format(" grid={}x{} cell={}", lowWidth_, lowHeight_, scale_);
+}
+}
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index dbb83d4d..2e894fc6 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -56,8 +56,8 @@ extern "C" {
namespace veyra::pipeline {
using diagnostics::GpuStage;
static_assert(diagnostics::kTimedNrLayers==engine::kMaxNrInstances&&diagnostics::kTimedColorNodes==engine::kMaxColorInstances&&
- diagnostics::kTimedAaNodes==engine::kMaxAntiAliasInstances,
- "every NR layer / Color / anti-aliasing instance needs its own node timing slot");
+ diagnostics::kTimedAaNodes==engine::kMaxAntiAliasInstances&&diagnostics::kTimedBeautyNodes==engine::kMaxBeautyInstances,
+ "every NR layer / Color / anti-aliasing / beauty instance needs its own node timing slot");
namespace {
@@ -393,6 +393,9 @@ bool EnhanceGraph::createNodeColorResources(){
}else if(step.type==engine::EffectType::AntiAliasing&&parameter<antiAliasPasses_.size()){
if(!createAntiAlias(parameter,step.output.width,step.output.height))return false;
pass.output=antiAliasOutputs_[parameter].Get();
+ }else if(step.type==engine::EffectType::Beauty&&parameter<beautyPasses_.size()){
+ if(!createBeauty(parameter,step.output.width,step.output.height))return false;
+ pass.output=beautyOutputs_[parameter].Get();
}else{
veyra::log::error("graph",std::format("no executor for same-size {} step={}",engine::effectTypeName(step.type),i));
return false;
@@ -421,11 +424,61 @@ bool EnhanceGraph::createAntiAlias(uint32_t parameter,uint32_t width,uint32_t he
return created;
}
+bool EnhanceGraph::createBeauty(uint32_t parameter,uint32_t width,uint32_t height){
+ auto& pass=beautyPasses_[parameter];
+ pass=std::make_unique<BeautyPass>();
+ beautyOutputs_[parameter]=makeTexture(context_.device(),width,height,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
+ const bool created=beautyOutputs_[parameter]&&pass->initialize(context_.device(),desc_.beauty[parameter],width,height,srcW_,srcH_);
+ if(created){
+ beautyNodesActive_=true;
+ veyra::log::info("beauty",std::format("instance={} {} extent={}x{} hdr={}",parameter,pass->describe(),width,height,desc_.hdrWorking()));
+ }else veyra::log::error("beauty",std::format("instance={} extent={}x{}: creation failed",parameter,width,height));
+ return created;
+}
+
+// Shared by every beauty node: the tracker (the detector loads once per graph and
+// costs a few milliseconds), the faces buffer and the original's texture.
+bool EnhanceGraph::createBeautyShared(){
+ beautyNotice_.clear();beautyOriginalSource_=nullptr;
+ if(!beautyNodesActive_)return true;
+ if(colorActive_){
+ beautyOriginal_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);
+ if(!beautyOriginal_)return false;
+ beautyOriginalSource_=beautyOriginal_.Get();
+ }else beautyOriginalSource_=preGradeRgba_?preGradeRgba_.Get():srcRgba_.Get();
+ const auto model=desc_.beautyModelPath.empty()?beauty::locateFaceModel():std::filesystem::path(desc_.beautyModelPath);
+ faceTracker_=std::make_unique<beauty::FaceTracker>();
+ std::string error;
+ if(!faceTracker_->initialize(context_.device(),model,ring_.slotCount(),error)){
+ veyra::log::error("beauty-detect",std::format("face detector unavailable ({}); beauty nodes see no faces",error));
+ faceTracker_.reset();
+ if(desc_.beautyRequireDetector)return false;
+ beautyNotice_=model.empty()?L"美颜:人脸模型文件缺失,人脸原画保护与人脸区域美颜暂不生效"
+ :L"美颜:人脸识别初始化失败,人脸原画保护与人脸区域美颜暂不生效";
+ }else faceTracker_->configure(desc_.beautyDetection,beautyMinConfidence());
+ if(!faceTracker_){
+ 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;
+ }
+ veyra::log::info("beauty",std::format("shared: original={} detector={} quality={} faces<={} stability={:.2f}",
+ colorActive_?"ungraded copy":preGradeRgba_?"pre-grade input":"converted input",faceTracker_?"ready":"unavailable",
+ int(desc_.beautyDetection.quality),int(desc_.beautyDetection.maxFaces),desc_.beautyDetection.stability));
+ return true;
+}
+
+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());
+}
+
// Binds one slot's passes in plan order: each reads the previous output.
ID3D12Resource* EnhanceGraph::chainSlotViews(const std::vector<SlotPass>& passes,ID3D12Resource* input,const char* where){
for(const auto& pass:passes){
- 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);
+ bindSlotPassInput(pass,input);
input=pass.output;
veyra::log::info("node-dispatch",std::format("{} {} step={} parameter={} resource={} input={}x{} output={}x{}",
where,engine::effectTypeName(pass.type),pass.step,pass.parameter,pass.resource,pass.width,pass.height,pass.width,pass.height));
@@ -443,6 +496,10 @@ bool EnhanceGraph::dispatchSlotPasses(ID3D12GraphicsCommandList* list,const std:
gpuTimer_.mark(list,diagnostics::aaNodeStage(pass.parameter));
if(!antiAliasPasses_[pass.parameter]->dispatch(list,tracker_,desc_.hdrWorking(),reset))return false;
gpuTimer_.mark(list,diagnostics::aaNodeStage(pass.parameter),true);
+ }else if(pass.type==engine::EffectType::Beauty){
+ gpuTimer_.mark(list,diagnostics::beautyNodeStage(pass.parameter));
+ if(!beautyPasses_[pass.parameter]->dispatch(list,tracker_,desc_.hdrWorking(),beautyOriginalValid_))return false;
+ gpuTimer_.mark(list,diagnostics::beautyNodeStage(pass.parameter),true);
}
if(log)veyra::log::info("node-dispatch",std::format("recorded {} {} step={} parameter={} resource={}",where,engine::effectTypeName(pass.type),pass.step,pass.parameter,pass.resource));
}
@@ -750,6 +807,7 @@ bool EnhanceGraph::createResources()
}
if(!createAdditionalColorResources())return false;
if(!createNodeColorResources())return false;
+ if(!createBeautyShared())return false;
videoFrame_[0] = makeTexture(context_.device(), workW_, workH_, outputFormat(), true);
videoFrame_[1] = makeTexture(context_.device(), workW_, workH_, outputFormat(), true);
confTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R8_UNORM, true);
@@ -2095,6 +2153,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
ID3D12Resource* nv12Texture = nullptr;
ID3D12GraphicsCommandList* list = ring_.acquireNext(slot, st);
if (list == nullptr) { veyra::log::error("graph", "ring acquire"); return false; }
+ // The ring handed this slot out after its fence: the face status it carried is ready.
+ if(faceTracker_)faceTracker_->collect(slot);
cpuTrace.mark("acquire");
gpuTimer_.frame({epoch_,desc_.settingsRevision,realFrameIndex_+1},context_.fence());gpuTimer_.mark(list,GpuStage::Color);
@@ -2360,12 +2420,22 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
};
// Grading is fused into input conversion. Retain a genuinely ungraded
// reference only when comparison requests it, then run the normal input.
- if(colorGradeActive()&&retainReferences){
+ // A beauty node restoring faces needs the same ungraded picture this frame.
+ const bool beautyRestore=beautyNodesActive_&&beautyRestoreRequested();
+ const bool beautyCopy=beautyOriginal_&&beautyRestore;
+ if(colorGradeActive()&&(retainReferences||beautyCopy)){
convertInput(false,srcRgba_.Get(),0);
tracker_.transition(list,srcRgba_.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);
- tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);
- list->CopyResource(sourceReferences_[parity].Get(),srcRgba_.Get());
- tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
+ if(retainReferences){
+ tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ list->CopyResource(sourceReferences_[parity].Get(),srcRgba_.Get());
+ tracker_.transition(list,sourceReferences_[parity].Get(),D3D12_RESOURCE_STATE_COMMON);
+ }
+ if(beautyCopy){
+ tracker_.transition(list,beautyOriginal_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
+ list->CopyResource(beautyOriginal_.Get(),srcRgba_.Get());
+ tracker_.transition(list,beautyOriginal_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ }
}
if(preGradeRgba_&&!colorActive_)convertInput(false,preGradeRgba_.Get(),1);
else convertInput(colorActive_,srcRgba_.Get(),0);
@@ -2392,6 +2462,27 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
gpuTimer_.mark(list,GpuStage::Color,true);
if (desc_.stageMark) desc_.stageMark("yuv");
cpuTrace.mark("color");
+ // Beauty: this frame's original, then faces for every beauty node, before any
+ // effect node runs. Detection reads the original when it holds this frame.
+ beautyOriginalValid_=false;
+ if(beautyNodesActive_){
+ beautyOriginalValid_=beautyOriginal_?beautyCopy:beautyOriginalSource_!=nullptr;
+ if(faceTracker_&&faceTracker_->ready()){
+ ID3D12Resource* faces=beautyOriginal_&&!beautyCopy?srcRgba_.Get():beautyOriginalSource_;
+ tracker_.transition(list,faces,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ gpuTimer_.mark(list,GpuStage::BeautyDetect);
+ beauty::FaceTracker::Frame frameFaces;
+ frameFaces.source=faces;frameFaces.width=srcW_;frameFaces.height=srcH_;frameFaces.hdr=desc_.hdrWorking();
+ frameFaces.slot=slot;frameFaces.frameId=sourceFrameId;frameFaces.ptsMs=ptsMs;frameFaces.reset=reset;
+ frameFaces.still=desc_.stillImage;frameFaces.everyFrame=desc_.beautyDetectEveryFrame;
+ if(!faceTracker_->record(list,tracker_,frameFaces)){
+ if(!beautyDetectFailureLogged_)veyra::log::error("beauty-detect","face tracking could not be recorded; beauty nodes keep the last faces");
+ beautyDetectFailureLogged_=true;
+ }
+ gpuTimer_.mark(list,GpuStage::BeautyDetect,true);
+ if (desc_.stageMark) desc_.stageMark("beauty-faces");
+ }
+ }
if(!sourcePostPasses_.empty()){
if(!dispatchSlotPasses(list,sourcePostPasses_,slot,"source-size",!sourcePostExecutionLogged_,reset))return false;
tracker_.transition(list,sourcePostOutput_,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
@@ -3280,6 +3371,9 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
// textures (rebuild); the MLAA threshold / strength and history weights are uniforms.
engine::describeAntiAlias(s,nextNr);
for(unsigned i=0;i<engine::kMaxAntiAliasInstances;++i)if(!nextNr.antiAlias[i].sameStructure(desc_.antiAlias[i]))return false;
+ // Beauty: a node exists while it is enabled; everything inside it is a uniform.
+ engine::describeBeauty(s,nextNr);
+ for(unsigned i=0;i<engine::kMaxBeautyInstances;++i)if(!nextNr.beauty[i].sameStructure(desc_.beauty[i]))return false;
if(s.videoHdr.enabled!=desc_.videoHdr.enabled)return false;
// Output stabiliser: its pass is allocated at build time, so on/off rebuilds; strength and
// tolerance are uniforms. Neither used to reach a running graph (field report
@@ -3323,6 +3417,9 @@ bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){
}
desc_.antiAlias=nextNr.antiAlias;
for(size_t i=0;i<antiAliasPasses_.size();++i)if(antiAliasPasses_[i])antiAliasPasses_[i]->refresh(desc_.antiAlias[i]);
+ desc_.beauty=nextNr.beauty;desc_.beautyDetection=nextNr.beautyDetection;
+ for(size_t i=0;i<beautyPasses_.size();++i)if(beautyPasses_[i])beautyPasses_[i]->refresh(desc_.beauty[i]);
+ if(faceTracker_)faceTracker_->configure(desc_.beautyDetection,beautyMinConfidence());
desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;
desc_.nrHoldStrength=s.nrHoldStrength;desc_.nrHoldTolerance=s.nrHoldTolerance;
desc_.nrLayersModel=std::move(nextNr.nrLayersModel);
@@ -3367,8 +3464,7 @@ void EnhanceGraph::setNrEnabled(bool on)
if(wasEnabled!=nrEnabled_&&!tailPasses_.empty()){
const auto& first=tailPasses_.front();
auto* input=nrEnabled_&&desc_.finalNrAfterSr()?residualRgba_.Get():(preNrColorOutput_?preNrColorOutput_:workRgba_.Get());
- if(first.type==engine::EffectType::Color)
- nodeColorInstances_[first.parameter]->createViews(context_.device(),stager_,input,first.output);
+ bindSlotPassInput(first,input);
}
return;
}
@@ -3551,6 +3647,11 @@ void EnhanceGraph::shutdown()
for(auto& passes:interNrPasses_)passes.clear();
for(auto& pass:antiAliasPasses_)pass.reset();
antiAliasOutputs_={};
+ for(auto& pass:beautyPasses_)pass.reset();
+ beautyOutputs_={};
+ if(faceTracker_)faceTracker_->shutdown();
+ faceTracker_.reset();beautyOriginal_.Reset();beautyFacesFallback_.Reset();beautyOriginalSource_=nullptr;
+ beautyNodesActive_=beautyOriginalValid_=beautyDetectFailureLogged_=false;beautyNotice_.clear();
sourcePostOutput_=nullptr;
preSrColorOutput_=nullptr;preSrColorExecutionLogged_=false;
interNrColorOutputs_={};interNrColorExecutionLogged_=false;
diff --git a/tests/integration/BeautyGpuTests.cpp b/tests/integration/BeautyGpuTests.cpp
new file mode 100644
index 00000000..2c03c43c
--- /dev/null
+++ b/tests/integration/BeautyGpuTests.cpp
@@ -0,0 +1,775 @@
+// GPU checks for the beauty node (face restore + skin smoothing), one case per process
+// (like veyra_anti_alias_gpu_tests):
+//
+// veyra_beauty_gpu_tests.exe --list
+// veyra_beauty_gpu_tests.exe --case <name> <reference-dir> <output-dir>
+//
+// <reference-dir> is the YuNet reference folder (scripts/beauty/yunet-reference.py):
+// public test pictures in originals/ and OpenCV's faces per detector size, used here
+// to know where the faces are. The real graph runs on those pictures; masks are
+// judged in the face core (well inside every oval) and far outside every face.
+// off-identity enabled node with both sub-functions off == no node, bit for bit
+// restore-grade a fused colour grade, face restore 100%: core == ungraded picture,
+// far outside == graded picture
+// restore-half 50%: core == the midpoint of graded and ungraded
+// smooth-* skin texture drops in the face, eyes keep theirs, outside unchanged;
+// before / after / mask pictures are written for a look
+// two-nodes smoothing node then a restore node: the second returns to the original
+// hdr P010 PQ input, scRGB output: finite, a 1000-nit patch and an out-of-709
+// patch outside the faces bit-identical, the face changed
+// tracking a moving face (video timing): faces follow it, detections at the rate
+// no-model a missing model: preview runs (notice, no faces), export refuses
+// timing-* GPU milliseconds of the node and of the shared detection
+// VEYRA_BEAUTY_GPU_DEBUG=1 enables the D3D12 debug layer and fails on its errors.
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/engine/GraphDescription.h"
+#include "veyra/engine/EffectChain.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <d3d12sdklayers.h>
+#include <DirectXPackedVector.h>
+#include <objbase.h>
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <functional>
+#include <iostream>
+#include <memory>
+#include <optional>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <vector>
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/pixfmt.h>
+}
+
+namespace {
+using namespace veyra;
+using engine::BeautySettings;
+using engine::EffectType;
+namespace fs = std::filesystem;
+
+fs::path gRefs, gOut;
+int failures = 0;
+void check(bool ok, const std::string& label) {
+ std::printf("%s %s\n", ok ? "PASS" : "FAIL", label.c_str());
+ if (!ok) ++failures;
+}
+double srgbToLinear(double c) { return c <= 0.04045 ? c / 12.92 : std::pow((c + 0.055) / 1.055, 2.4); }
+double linearToSrgb(double l) {
+ l = std::clamp(l, 0.0, 1.0);
+ return l <= 0.0031308 ? 12.92 * l : 1.055 * std::pow(l, 1.0 / 2.4) - 0.055;
+}
+
+// ---- pictures and faces -------------------------------------------------------------
+struct Face { double x = 0, y = 0, w = 0, h = 0; double lm[10]{}; double score = 0; };
+struct Picture { sink::RgbaImage image; std::vector<Face> faces; };
+
+bool loadPicture(const std::string& stem, Picture& p) {
+ fs::path file;
+ for (const auto& f : fs::directory_iterator(gRefs / "originals"))
+ if (f.path().stem().string() == stem) file = f.path();
+ if (file.empty() || !sink::loadImage(file.wstring(), p.image)) return false;
+ // OpenCV's faces at the balanced detector size (512 on the long side), scaled to the picture.
+ for (const auto& f : fs::directory_iterator(gRefs)) {
+ const auto name = f.path().filename().string();
+ if (!f.is_directory() || name.rfind(stem + "-", 0) != 0) continue;
+ uint32_t w = 0, h = 0, pw = 0, ph = 0;
+ std::ifstream meta(f.path() / "meta.txt");
+ if (!(meta >> w >> h >> pw >> ph) || std::max(w, h) != 512) continue;
+ const double sx = double(p.image.width) / w, sy = double(p.image.height) / h;
+ std::ifstream faces(f.path() / "faces.txt");
+ std::string line;
+ while (std::getline(faces, line)) {
+ std::istringstream row(line);
+ std::vector<double> v; double x;
+ while (row >> x) v.push_back(x);
+ if (v.size() != 15) continue;
+ Face face;
+ face.x = v[0] * sx; face.y = v[1] * sy; face.w = v[2] * sx; face.h = v[3] * sy;
+ for (int k = 0; k < 10; ++k) face.lm[k] = v[4 + size_t(k)] * (k % 2 ? sy : sx);
+ face.score = v[14];
+ p.faces.push_back(face);
+ }
+ }
+ return !p.faces.empty();
+}
+sink::RgbaImage resized(const sink::RgbaImage& in, unsigned w, unsigned h);
+// The picture (and its faces) enlarged so the frame is `rows` tall: the sizes video has.
+Picture enlarged(const Picture& p, unsigned rows) {
+ Picture out;
+ const double k = double(rows) / p.image.height;
+ out.image = resized(p.image, unsigned(std::lround(p.image.width * k)), rows);
+ out.faces = p.faces;
+ for (auto& f : out.faces) {
+ f.x *= k; f.y *= k; f.w *= k; f.h *= k;
+ for (auto& v : f.lm) v *= k;
+ }
+ return out;
+}
+// Normalised distance from a face centre (1 = the box half size).
+double faceDistance(const Face& f, double x, double y) {
+ const double cx = f.x + f.w / 2, cy = f.y + f.h / 2;
+ return std::hypot((x + 0.5 - cx) / (f.w / 2), (y + 0.5 - cy) / (f.h / 2));
+}
+bool inCore(const Picture& p, unsigned x, unsigned y) {
+ for (const auto& f : p.faces) if (faceDistance(f, x, y) < 0.55) return true;
+ return false;
+}
+bool farOutside(const Picture& p, unsigned x, unsigned y) {
+ for (const auto& f : p.faces) if (faceDistance(f, x, y) < 2.6) return false;
+ return true;
+}
+sink::RgbaImage resized(const sink::RgbaImage& in, unsigned w, unsigned h) {
+ sink::RgbaImage out; out.width = w; out.height = h; out.pixels.resize(size_t(w) * h * 4);
+ for (unsigned y = 0; y < h; ++y)
+ for (unsigned x = 0; x < w; ++x) {
+ const double sx = (x + 0.5) * in.width / w - 0.5, sy = (y + 0.5) * in.height / h - 0.5;
+ const int x0 = std::clamp(int(std::floor(sx)), 0, int(in.width) - 1), y0 = std::clamp(int(std::floor(sy)), 0, int(in.height) - 1);
+ const int x1 = std::min(x0 + 1, int(in.width) - 1), y1 = std::min(y0 + 1, int(in.height) - 1);
+ const double fx = std::clamp(sx - x0, 0.0, 1.0), fy = std::clamp(sy - y0, 0.0, 1.0);
+ for (int c = 0; c < 4; ++c) {
+ const auto at = [&](int xx, int yy) { return double(in.pixels[(size_t(yy) * in.width + xx) * 4 + c]); };
+ const double v = (at(x0, y0) * (1 - fx) + at(x1, y0) * fx) * (1 - fy) + (at(x0, y1) * (1 - fx) + at(x1, y1) * fx) * fy;
+ out.pixels[(size_t(y) * w + x) * 4 + c] = uint8_t(std::clamp(std::lround(v), 0l, 255l));
+ }
+ }
+ return out;
+}
+// The picture shifted by (dx, dy) inside a canvas of its own size, grey around it.
+sink::RgbaImage shifted(const sink::RgbaImage& in, int dx, int dy) {
+ sink::RgbaImage out = in;
+ for (unsigned y = 0; y < in.height; ++y)
+ for (unsigned x = 0; x < in.width; ++x) {
+ const int sx = int(x) - dx, sy = int(y) - dy;
+ uint8_t* d = out.pixels.data() + (size_t(y) * in.width + x) * 4;
+ if (sx < 0 || sy < 0 || sx >= int(in.width) || sy >= int(in.height)) { d[0] = d[1] = d[2] = 96; d[3] = 255; continue; }
+ std::memcpy(d, in.pixels.data() + (size_t(sy) * in.width + sx) * 4, 4);
+ }
+ return out;
+}
+
+AVFrame* rgbaFrame(const sink::RgbaImage& image) {
+ AVFrame* f = av_frame_alloc();
+ if (!f) return nullptr;
+ f->format = AV_PIX_FMT_RGBA; f->width = int(image.width); f->height = int(image.height);
+ f->color_range = AVCOL_RANGE_JPEG; f->color_trc = AVCOL_TRC_IEC61966_2_1; f->colorspace = AVCOL_SPC_RGB;
+ if (av_frame_get_buffer(f, 32) < 0) { av_frame_free(&f); return nullptr; }
+ for (unsigned y = 0; y < image.height; ++y)
+ std::memcpy(f->data[0] + size_t(y) * f->linesize[0], image.pixels.data() + size_t(y) * image.width * 4, size_t(image.width) * 4);
+ return f;
+}
+
+double pq(double nits) {
+ const double y = std::pow(std::clamp(nits / 10000.0, 0.0, 1.0), 2610.0 / 16384.0);
+ return std::pow((3424.0 / 4096.0 + 2413.0 / 128.0 * y) / (1 + 2392.0 / 128.0 * y), 2523.0 / 32.0);
+}
+struct Code10 { uint16_t y, cb, cr; };
+Code10 encode2020(double r, double g, double b) {
+ const double R = pq(r), G = pq(g), B = pq(b), Y = 0.2627 * R + 0.6780 * G + 0.0593 * B;
+ const auto q = [](double v) { return uint16_t(std::clamp(std::lround(v), 0l, 1023l)); };
+ return {q(64 + 876 * Y), q(512 + 896 * (B - Y) / 1.8814), q(512 + 896 * (R - Y) / 1.4746)};
+}
+// The picture as P010 PQ BT.2020 (SDR white at 203 nits), plus two 32x32 patches in
+// the top-left corner: 1000-nit white and an out-of-709 green.
+constexpr unsigned kPatch = 32;
+bool hdrPatch(unsigned x, unsigned y, int& which) {
+ which = -1;
+ if (y >= 8 && y < 8 + kPatch && x >= 8 && x < 8 + kPatch) which = 0;
+ if (y >= 8 && y < 8 + kPatch && x >= 48 && x < 48 + kPatch) which = 1;
+ return which >= 0;
+}
+AVFrame* hdrFrame(const sink::RgbaImage& image) {
+ AVFrame* f = av_frame_alloc();
+ if (!f) return nullptr;
+ f->format = AV_PIX_FMT_P010; f->width = int(image.width); f->height = int(image.height);
+ f->color_range = AVCOL_RANGE_MPEG; f->colorspace = AVCOL_SPC_BT2020_NCL; f->color_primaries = AVCOL_PRI_BT2020;
+ f->color_trc = AVCOL_TRC_SMPTE2084;
+ if (av_frame_get_buffer(f, 32) < 0) { av_frame_free(&f); return nullptr; }
+ std::vector<Code10> codes(size_t(image.width) * image.height);
+ for (unsigned y = 0; y < image.height; ++y)
+ for (unsigned x = 0; x < image.width; ++x) {
+ int which = -1;
+ Code10 c;
+ if (hdrPatch(x, y, which)) c = which == 0 ? encode2020(1000, 1000, 1000) : encode2020(8, 120, 8);
+ else {
+ const uint8_t* p = image.pixels.data() + (size_t(y) * image.width + x) * 4;
+ const double r = srgbToLinear(p[0] / 255.0), g = srgbToLinear(p[1] / 255.0), b = srgbToLinear(p[2] / 255.0);
+ const double r2 = 0.6274 * r + 0.3293 * g + 0.0433 * b, g2 = 0.0691 * r + 0.9195 * g + 0.0114 * b, b2 = 0.0164 * r + 0.0880 * g + 0.8956 * b;
+ c = encode2020(r2 * 203.0, g2 * 203.0, b2 * 203.0);
+ }
+ codes[size_t(y) * image.width + x] = c;
+ reinterpret_cast<uint16_t*>(f->data[0] + size_t(y) * f->linesize[0])[x] = uint16_t(c.y << 6);
+ }
+ for (unsigned y = 0; y < image.height / 2; ++y)
+ for (unsigned x = 0; x < image.width / 2; ++x) {
+ uint32_t cb = 0, cr = 0;
+ for (unsigned j = 0; j < 2; ++j) for (unsigned i = 0; i < 2; ++i) {
+ const auto& c = codes[size_t(y * 2 + j) * image.width + x * 2 + i]; cb += c.cb; cr += c.cr;
+ }
+ auto* row = reinterpret_cast<uint16_t*>(f->data[1] + size_t(y) * f->linesize[1]);
+ row[x * 2] = uint16_t(((cb + 2) / 4) << 6); row[x * 2 + 1] = uint16_t(((cr + 2) / 4) << 6);
+ }
+ return f;
+}
+
+// ---- graph without NGX ----------------------------------------------------------------
+struct Gpu {
+ gfx::D3D12DeviceContext ctx; gfx::CommandSlotRing ring;
+ std::unique_ptr<pipeline::EnhanceGraph> graph = std::make_unique<pipeline::EnhanceGraph>(ctx, ring);
+ pipeline::EnhanceGraphDesc desc;
+ bool up = false, debug = std::getenv("VEYRA_BEAUTY_GPU_DEBUG") != nullptr;
+ uint64_t frameId = 0;
+ std::string error;
+ bool start(const engine::EnhancementSettings& settings, unsigned w, unsigned h, bool hdr, bool still = true,
+ const engine::ChainRuntimeOrder* order = nullptr, const std::wstring& model = {}, bool exportJob = false) {
+ if (!up) {
+ gfx::DeviceContextDesc device; Status st;
+ device.enableDebugLayer = debug;
+ if (!ctx.initialize(device, st) || !ring.initialize(ctx.device(), ctx.directQueue(), ctx.fence(), ctx.fenceEvent(), 4, st)) return false;
+ up = true;
+ } else { ring.drainQueue(); graph->shutdown(); }
+ desc = {};
+ desc.sourceWidth = desc.workWidth = w; desc.sourceHeight = desc.workHeight = h;
+ desc.rgbInput = !hdr; desc.hdrInput = hdr; desc.hdrOutput = hdr;
+ desc.stillImage = still; desc.noFeatures = true; desc.noNgx = true;
+ desc.enableNr = desc.enableSr = desc.enableFg = false; desc.outputDitherStep = 0;
+ engine::StageRequest request; request.width = w; request.height = h; request.stillImage = still;
+ request.nodeOrder = order; request.exportJob = exportJob;
+ engine::describeStages(request, settings, desc);
+ desc.stillImage = still;
+ if (!model.empty()) desc.beautyModelPath = model;
+ if (!desc.fixedExecutionPlanError.empty()) { error = desc.fixedExecutionPlanError; std::cout << "plan error: " << error << std::endl; return false; }
+ frameId = 0;
+ return graph->initialize(desc) && graph->createViews();
+ }
+ bool render(AVFrame* frame, bool reset, sink::RgbaImage& out) {
+ pipeline::EnhanceGraph::FrameOutputs outputs;
+ if (!graph->process(frame, double(frameId) * 1000.0 / 60.0, reset, outputs, frameId + 1)) return false;
+ ++frameId;
+ auto* texture = graph->videoFrameResource(outputs.videoSlot);
+ if (!texture) return false;
+ if (texture->GetDesc().Format == DXGI_FORMAT_R8G8B8A8_UNORM) return sink::readRgba8(ctx, ring, texture, out);
+ return readHalf(texture, out);
+ }
+ Microsoft::WRL::ComPtr<ID3D12Resource> readbackBuffer(UINT64 bytes) {
+ D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_READBACK;
+ D3D12_RESOURCE_DESC buffer{}; buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; buffer.Width = bytes;
+ buffer.Height = 1; buffer.DepthOrArraySize = 1; buffer.MipLevels = 1; buffer.SampleDesc.Count = 1;
+ buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ Microsoft::WRL::ComPtr<ID3D12Resource> readback;
+ if (FAILED(ctx.device()->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) return nullptr;
+ return readback;
+ }
+ // FP16 readback of the scRGB output (8 bytes per pixel in `out.pixels`).
+ bool readHalf(ID3D12Resource* texture, sink::RgbaImage& out) {
+ const auto d = texture->GetDesc();
+ if (d.Format != DXGI_FORMAT_R16G16B16A16_FLOAT) return false;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; UINT64 bytes = 0;
+ ctx.device()->GetCopyableFootprints(&d, 0, 1, 0, &fp, nullptr, nullptr, &bytes);
+ auto readback = readbackBuffer(bytes);
+ 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 = {texture, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE};
+ list->ResourceBarrier(1, &b);
+ D3D12_TEXTURE_COPY_LOCATION src{}, dst{};
+ src.pResource = texture; src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dst.pResource = readback.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; dst.PlacedFootprint = fp;
+ list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
+ std::swap(b.Transition.StateBefore, b.Transition.StateAfter); list->ResourceBarrier(1, &b);
+ if (!ring.submitAndSignal(slot) || !ring.waitIdle()) return false;
+ uint8_t* data = nullptr; D3D12_RANGE range{0, SIZE_T(bytes)};
+ if (FAILED(readback->Map(0, &range, reinterpret_cast<void**>(&data)))) return false;
+ out.width = uint32_t(d.Width); out.height = d.Height; out.pixels.resize(size_t(out.width) * out.height * 8);
+ for (UINT y = 0; y < out.height; ++y)
+ std::memcpy(out.pixels.data() + size_t(y) * out.width * 8, data + fp.Offset + size_t(y) * fp.Footprint.RowPitch, size_t(out.width) * 8);
+ D3D12_RANGE empty{}; readback->Unmap(0, &empty);
+ return true;
+ }
+ // The tracked faces after the last frame: header + eight faces, 16 floats each.
+ bool readFaces(std::vector<float>& faces) {
+ auto* buffer = graph->beautyFacesBuffer();
+ auto readback = buffer ? readbackBuffer(9 * 64) : 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, 9 * 64);
+ 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, 9 * 64};
+ if (FAILED(readback->Map(0, &range, &data))) return false;
+ faces.resize(9 * 16);
+ std::memcpy(faces.data(), data, 9 * 64);
+ 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)];
+ if (s.state != diagnostics::SampleState::Measured) return std::nullopt;
+ return s.milliseconds;
+ }
+ unsigned debugErrors() {
+ if (!debug || !up) return 0;
+ Microsoft::WRL::ComPtr<ID3D12InfoQueue> info;
+ if (FAILED(ctx.device()->QueryInterface(IID_PPV_ARGS(&info)))) { std::printf("D3D12 debug info queue unavailable\n"); return 1; }
+ unsigned errors = 0;
+ for (UINT64 i = 0; i < info->GetNumStoredMessagesAllowedByRetrievalFilter(); ++i) {
+ SIZE_T size = 0; info->GetMessage(i, nullptr, &size); std::vector<uint8_t> storage(size);
+ auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data());
+ if (SUCCEEDED(info->GetMessage(i, message, &size)) && message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) {
+ std::printf("D3D12_ERROR id=%u %s\n", unsigned(message->ID), message->pDescription); ++errors;
+ }
+ }
+ return errors;
+ }
+ ~Gpu() { if (up) { ring.drainQueue(); graph->shutdown(); ring.shutdown(); } }
+};
+
+// Header entry: meta.x (float index 12) is the face count as an integer.
+uint32_t trackedCount(const std::vector<float>& faces) {
+ uint32_t n = 0;
+ if (faces.size() > 12) std::memcpy(&n, &faces[12], 4);
+ return n;
+}
+BeautySettings restoreNode(float strength = 1.0f) { BeautySettings b; b.enabled = true; b.restore = true; b.restoreStrength = strength; return b; }
+BeautySettings smoothNode(float amount = 0.6f, float radius = 4.0f) {
+ BeautySettings b; b.enabled = true; b.smooth = true; b.smoothAmount = amount; b.radius = radius; b.detail = 0.5f; b.texture = 0.2f;
+ return b;
+}
+// The strong end of the tuned range (amount 0.85, sigma 7, detail 0.4, texture 0.15).
+BeautySettings strongNode() { auto b = smoothNode(0.85f, 7.0f); b.detail = 0.4f; b.texture = 0.15f; return b; }
+engine::EnhancementSettings withBeauty(const BeautySettings& b) { engine::EnhancementSettings s; s.beauty = b; return s; }
+// Mild enough that the face stays below white: the midpoint check needs unclipped values.
+engine::EnhancementSettings graded(engine::EnhancementSettings s) {
+ s.color.enabled = true; s.color.exposure = 0.3f; s.color.saturation = 25.0f; s.color.temperature = 25.0f;
+ return s;
+}
+void save(const std::string& name, const sink::RgbaImage& image) {
+ if (image.pixels.size() == size_t(image.width) * image.height * 4) (void)sink::saveImage((gOut / (name + ".png")).wstring(), image);
+}
+
+// 8-bit picture statistics.
+struct Diff { size_t pixels = 0, differing = 0; int maxDiff = 0; };
+template <typename Pred> Diff compare(const sink::RgbaImage& a, const sink::RgbaImage& b, Pred where) {
+ Diff d;
+ for (unsigned y = 0; y < a.height; ++y)
+ for (unsigned x = 0; x < a.width; ++x) {
+ if (!where(x, y)) continue;
+ ++d.pixels;
+ int m = 0;
+ for (int c = 0; c < 3; ++c) m = std::max(m, std::abs(int(a.pixels[(size_t(y) * a.width + x) * 4 + c]) - int(b.pixels[(size_t(y) * a.width + x) * 4 + c])));
+ d.differing += m > 0; d.maxDiff = std::max(d.maxDiff, m);
+ }
+ return d;
+}
+// Mean absolute difference of the luma from its 3x3 mean: the fine texture.
+template <typename Pred> double texture(const sink::RgbaImage& a, Pred where) {
+ const auto luma = [&](int x, int y) {
+ x = std::clamp(x, 0, int(a.width) - 1); y = std::clamp(y, 0, int(a.height) - 1);
+ const uint8_t* p = a.pixels.data() + (size_t(y) * a.width + x) * 4;
+ return 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2];
+ };
+ double sum = 0; size_t n = 0;
+ for (unsigned y = 0; y < a.height; ++y)
+ for (unsigned x = 0; x < a.width; ++x) {
+ if (!where(x, y)) continue;
+ double mean = 0;
+ for (int j = -1; j <= 1; ++j) for (int i = -1; i <= 1; ++i) mean += luma(int(x) + i, int(y) + j);
+ sum += std::abs(luma(int(x), int(y)) - mean / 9.0); ++n;
+ }
+ return n ? sum / double(n) : 0.0;
+}
+
+int finish(Gpu& gpu, const std::string& name) {
+ const auto errors = gpu.debugErrors();
+ check(errors == 0, name + ": no D3D12 debug-layer errors");
+ return failures ? 1 : 0;
+}
+
+int offIdentityCase() {
+ Picture p;
+ check(loadPicture("lena", p), "off-identity: picture and reference faces");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage plain, idle;
+ BeautySettings idleNode; idleNode.enabled = true;
+ bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, plain) &&
+ gpu->start(withBeauty(idleNode), p.image.width, p.image.height, false) && gpu->render(frame, true, idle);
+ check(ok && gpu->graph->beautyNodesActive(), "off-identity: a graph with an idle beauty node runs");
+ const auto d = compare(plain, idle, [](unsigned, unsigned) { return true; });
+ std::printf("METRIC case=off-identity pixels=%zu differing=%zu\n", d.pixels, d.differing);
+ check(ok && d.pixels > 0 && d.differing == 0, "off-identity: both sub-functions off is bit-identical to no node");
+ av_frame_free(&frame);
+ return finish(*gpu, "off-identity");
+}
+
+int restoreCase(const std::string& name, float strength) {
+ Picture p;
+ check(loadPicture("lena", p), name + ": picture and reference faces");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage original, grade, restored;
+ 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(restoreNode(strength))), p.image.width, p.image.height, false) && gpu->render(frame, true, restored);
+ check(ok, name + ": ungraded, graded and graded + restore graphs run");
+ if (ok) {
+ std::vector<float> faces;
+ ok = gpu->readFaces(faces);
+ std::printf("METRIC case=%s trackedFaces=%u score=%.3f\n", name.c_str(), ok ? trackedCount(faces) : 0u, ok ? faces[16 + 6] : 0.0f);
+ check(ok && trackedCount(faces) >= 1, name + ": the tracker found the face on the picture's own frame");
+ const auto outside = compare(restored, grade, [&](unsigned x, unsigned y) { return farOutside(p, x, y); });
+ std::printf("METRIC case=%s outsidePixels=%zu outsideDiffering=%zu\n", name.c_str(), outside.pixels, outside.differing);
+ check(outside.pixels > 1000 && outside.differing == 0, name + ": far from the face the graded picture is bit-identical");
+ if (strength >= 1.0f) {
+ const auto core = compare(restored, original, [&](unsigned x, unsigned y) { return inCore(p, x, y); });
+ std::printf("METRIC case=%s corePixels=%zu coreDiffering=%zu coreMax=%d\n", name.c_str(), core.pixels, core.differing, core.maxDiff);
+ check(core.pixels > 2000 && core.differing == 0, name + ": the face core is the ungraded picture, bit for bit");
+ } else {
+ // Expected: the linear midpoint of the graded and ungraded pictures (8-bit inputs, +-2 levels).
+ size_t n = 0, bad = 0, clipped = 0; int worst = 0;
+ for (unsigned y = 0; y < p.image.height; ++y)
+ for (unsigned x = 0; x < p.image.width; ++x) {
+ if (!inCore(p, x, y)) continue;
+ bool edge = false;
+ for (int c = 0; c < 3; ++c) {
+ const size_t i = (size_t(y) * p.image.width + x) * 4 + c;
+ edge |= grade.pixels[i] >= 254 || grade.pixels[i] <= 1 || original.pixels[i] >= 254 || original.pixels[i] <= 1;
+ }
+ if (edge) { ++clipped; continue; }
+ ++n;
+ for (int c = 0; c < 3; ++c) {
+ const size_t i = (size_t(y) * p.image.width + x) * 4 + c;
+ const double mid = linearToSrgb((srgbToLinear(original.pixels[i] / 255.0) + srgbToLinear(grade.pixels[i] / 255.0)) * 0.5) * 255.0;
+ const int e = int(std::abs(std::lround(mid) - long(restored.pixels[i])));
+ worst = std::max(worst, e); bad += e > 2;
+ }
+ }
+ std::printf("METRIC case=%s corePixels=%zu clippedSkipped=%zu coreWorst=%d coreOver2=%zu\n", name.c_str(), n, clipped, worst, bad);
+ check(n > 2000 && bad == 0, name + ": the face core is the linear midpoint (within 2 levels)");
+ }
+ save(name + "-graded", grade); save(name + "-restored", restored);
+ }
+ av_frame_free(&frame);
+ return finish(*gpu, name);
+}
+
+int smoothCase(const std::string& name, const std::string& stem, BeautySettings setting) {
+ // Native size: an enlarged picture has lost the skin texture the check measures.
+ Picture p;
+ check(loadPicture(stem, p), name + ": picture and reference faces");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage off, on, mask;
+ BeautySettings masked = setting; masked.showMask = true;
+ bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, off) &&
+ gpu->start(withBeauty(setting), p.image.width, p.image.height, false) && gpu->render(frame, true, on) &&
+ gpu->start(withBeauty(masked), p.image.width, p.image.height, false) && gpu->render(frame, true, mask);
+ check(ok, name + ": graphs without and with smoothing run");
+ if (ok) {
+ save(name + "-off", off); save(name + "-on", on); save(name + "-mask", mask);
+ const auto outside = compare(on, off, [&](unsigned x, unsigned y) { return farOutside(p, x, y); });
+ // Skin texture: the face core minus the eyes; the eyes on their own.
+ const auto nearEye = [&](unsigned x, unsigned y) {
+ for (const auto& f : p.faces)
+ for (int e = 0; e < 2; ++e)
+ if (std::hypot(x + 0.5 - f.lm[e * 2], y + 0.5 - f.lm[e * 2 + 1]) < f.w * 0.09) return true;
+ return false;
+ };
+ const auto skin = [&](unsigned x, unsigned y) { return inCore(p, x, y) && !nearEye(x, y); };
+ const double skinBefore = texture(off, skin), skinAfter = texture(on, skin);
+ const double eyeBefore = texture(off, nearEye), eyeAfter = texture(on, nearEye);
+ const auto changed = compare(on, off, [&](unsigned x, unsigned y) { return inCore(p, x, y); });
+ std::printf("METRIC case=%s faces=%zu outsidePixels=%zu outsideDiffering=%zu coreChanged=%zu/%zu skinTexture=%.3f->%.3f (%.1f%%) eyeTexture=%.3f->%.3f (%.1f%%)\n",
+ name.c_str(), p.faces.size(), outside.pixels, outside.differing, changed.differing, changed.pixels, skinBefore, skinAfter,
+ 100.0 * (skinAfter / skinBefore - 1.0), eyeBefore, eyeAfter, 100.0 * (eyeAfter / std::max(eyeBefore, 1e-9) - 1.0));
+ check(outside.pixels > 1000 && outside.differing == 0, name + ": far from every face nothing changes");
+ check(changed.differing * 4 > changed.pixels, name + ": the face is processed");
+ const double skinDrop = 1.0 - skinAfter / skinBefore, eyeDrop = 1.0 - eyeAfter / std::max(eyeBefore, 1e-9);
+ check(skinDrop > 0.08, name + ": fine skin texture in the face drops by more than 8%");
+ check(eyeDrop < skinDrop, name + ": the eyes lose less of their detail than the skin (detail protection)");
+ }
+ av_frame_free(&frame);
+ return finish(*gpu, name);
+}
+
+int twoNodeCase() {
+ Picture p;
+ check(loadPicture("lena", p), "two-nodes: picture and reference faces");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ // Node mode: smoothing, then a full restore.
+ engine::EffectChain chain; chain.mode = engine::ChainMode::Node;
+ auto& a = chain.nodes[chain.nodeCount++]; a.type = EffectType::Beauty; a.enabled = true; a.beauty = smoothNode(1.0f, 6.0f);
+ auto& b = chain.nodes[chain.nodeCount++]; b.type = EffectType::Beauty; b.enabled = true; b.beauty = restoreNode(1.0f);
+ engine::EnhancementSettings settings; engine::fromChain(chain, settings);
+ const auto order = engine::runtimeOrder(chain);
+ engine::EffectChain smoothOnly = chain; smoothOnly.nodeCount = 1;
+ engine::EnhancementSettings first; engine::fromChain(smoothOnly, first);
+ const auto firstOrder = engine::runtimeOrder(smoothOnly);
+ sink::RgbaImage original, smoothed, both;
+ bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, original) &&
+ gpu->start(first, p.image.width, p.image.height, false, true, &*firstOrder) && gpu->render(frame, true, smoothed) &&
+ gpu->start(settings, p.image.width, p.image.height, false, true, &*order) && gpu->render(frame, true, both);
+ check(ok, "two-nodes: node chains run");
+ if (ok) {
+ const auto changed = compare(smoothed, original, [&](unsigned x, unsigned y) { return inCore(p, x, y); });
+ const auto core = compare(both, original, [&](unsigned x, unsigned y) { return inCore(p, x, y); });
+ std::printf("METRIC case=two-nodes smoothedCoreChanged=%zu/%zu restoredCoreDiffering=%zu\n", changed.differing, changed.pixels, core.differing);
+ check(changed.differing * 4 > changed.pixels, "two-nodes: the first node changes the face");
+ check(core.pixels > 2000 && core.differing == 0, "two-nodes: the second node's restore undoes the first in the face core");
+ }
+ av_frame_free(&frame);
+ return finish(*gpu, "two-nodes");
+}
+
+int hdrCase() {
+ Picture p;
+ check(loadPicture("lena", p), "hdr: picture and reference faces");
+ AVFrame* frame = hdrFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ auto on = withBeauty(smoothNode(0.8f, 4.0f)); on.beauty.restore = true; on.beauty.restoreStrength = 0.5f;
+ on.hdrOutputMode = engine::HdrOutputMode::ScRgb;
+ engine::EnhancementSettings offSettings; offSettings.hdrOutputMode = engine::HdrOutputMode::ScRgb;
+ sink::RgbaImage off, out;
+ bool ok = frame && gpu->start(offSettings, p.image.width, p.image.height, true) && gpu->render(frame, true, off) &&
+ gpu->start(on, p.image.width, p.image.height, true) && gpu->render(frame, true, out) &&
+ out.pixels.size() == size_t(p.image.width) * p.image.height * 8 && off.pixels.size() == out.pixels.size();
+ check(ok, "hdr: HDR graphs run (scRGB FP16 output)");
+ if (ok) {
+ const auto* a = reinterpret_cast<const uint16_t*>(out.pixels.data());
+ const auto* b = reinterpret_cast<const uint16_t*>(off.pixels.data());
+ bool finite = true; size_t patch = 0, patchDiffering = 0, negative = 0, core = 0, coreChanged = 0; float peak = 0;
+ for (unsigned y = 0; y < p.image.height; ++y)
+ for (unsigned x = 0; x < p.image.width; ++x) {
+ const size_t i = size_t(y) * p.image.width + x;
+ bool differs = false;
+ for (int c = 0; c < 3; ++c) {
+ const float v = DirectX::PackedVector::XMConvertHalfToFloat(a[i * 4 + c]);
+ finite = finite && std::isfinite(v);
+ differs |= a[i * 4 + c] != b[i * 4 + c];
+ }
+ int which = -1;
+ if (hdrPatch(x, y, which) && x % kPatch > 1 && y % kPatch > 1) {
+ ++patch; patchDiffering += differs;
+ if (which == 0) peak = std::max(peak, DirectX::PackedVector::XMConvertHalfToFloat(a[i * 4]));
+ if (which == 1) negative += DirectX::PackedVector::XMConvertHalfToFloat(a[i * 4]) < 0.0f;
+ }
+ if (inCore(p, x, y)) { ++core; coreChanged += differs; }
+ }
+ std::printf("METRIC case=hdr finite=%d patchPixels=%zu patchDiffering=%zu peak=%.3f negativeGreen=%zu coreChanged=%zu/%zu\n",
+ finite, patch, patchDiffering, peak, negative, coreChanged, core);
+ check(finite, "hdr: no NaN or infinity");
+ check(patch > 1000 && patchDiffering == 0, "hdr: the 1000-nit and out-of-709 patches outside the face are bit-identical");
+ check(peak > 10.0f && negative > 400, "hdr: the highlight keeps its level and the green keeps its negative components");
+ check(coreChanged * 4 > core, "hdr: the face is processed");
+ }
+ av_frame_free(&frame);
+ return finish(*gpu, "hdr");
+}
+
+int trackingCase() {
+ Picture p;
+ check(loadPicture("lena", p), "tracking: picture and reference faces");
+ auto gpu = std::make_unique<Gpu>();
+ auto settings = withBeauty(restoreNode(1.0f));
+ settings.beautyDetection.stability = 0.5f;
+ bool ok = gpu->start(settings, p.image.width, p.image.height, false, false);
+ check(ok, "tracking: video-timed graph runs");
+ const int frames = 48, step = 3; // 3 px per frame at 60 fps
+ std::vector<float> faces;
+ double worst = 0;
+ for (int i = 0; ok && i < frames; ++i) {
+ const auto moved = shifted(p.image, i * step - frames * step / 2, 0);
+ AVFrame* frame = rgbaFrame(moved);
+ sink::RgbaImage out;
+ ok = frame && gpu->render(frame, i == 0, out) && gpu->readFaces(faces);
+ av_frame_free(&frame);
+ if (!ok || trackedCount(faces) < 1) { ok = false; break; }
+ const double expected = (p.faces[0].x + p.faces[0].w / 2 + (i * step - frames * step / 2)) / p.image.width;
+ if (i >= 8) worst = std::max(worst, std::abs(double(faces[16]) - expected) * p.image.width);
+ }
+ const uint64_t detections = gpu->graph->beautyDetections();
+ std::printf("METRIC case=tracking frames=%d detections=%llu worstCentreErrorPx=%.2f faceWidthPx=%.1f\n", frames,
+ (unsigned long long)detections, worst, p.faces.empty() ? 0.0 : p.faces[0].w);
+ check(ok, "tracking: the face is tracked on every frame");
+ check(detections >= 10 && detections <= 16, "tracking: balanced detection runs at about 15 Hz of a 60 fps video");
+ check(ok && worst < 0.08 * p.faces[0].w, "tracking: the tracked centre stays within 8% of the face width of the moving face");
+ // A reset (seek) detects on the very next frame.
+ AVFrame* frame = rgbaFrame(p.image);
+ sink::RgbaImage out;
+ const auto before = gpu->graph->beautyDetections();
+ ok = frame && gpu->render(frame, true, out);
+ check(ok && gpu->graph->beautyDetections() == before + 1, "tracking: a reset frame detects immediately");
+ av_frame_free(&frame);
+ return finish(*gpu, "tracking");
+}
+
+int noModelCase() {
+ Picture p;
+ check(loadPicture("lena", p), "no-model: picture");
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage plain, out;
+ const std::wstring missing = (gOut / L"no-such-model.onnx").wstring();
+ bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, plain) &&
+ gpu->start(withBeauty(restoreNode()), p.image.width, p.image.height, false, true, nullptr, missing) && gpu->render(frame, true, out);
+ check(ok && !gpu->graph->beautyDetectorReady() && !gpu->graph->beautyNotice().empty(), "no-model: preview runs and says why beauty is off");
+ const auto d = compare(plain, out, [](unsigned, unsigned) { return true; });
+ check(ok && d.differing == 0, "no-model: without faces the picture is unchanged");
+ const bool exported = gpu->start(withBeauty(restoreNode()), p.image.width, p.image.height, false, false, nullptr, missing, true);
+ check(!exported, "no-model: an export with beauty refuses to start without the detector");
+ av_frame_free(&frame);
+ return finish(*gpu, "no-model");
+}
+
+int timingCase(const std::string& name, unsigned width, unsigned height) {
+ Picture crowd, portrait;
+ check(loadPicture("largest_selfie", crowd) && loadPicture("lena", portrait), name + ": pictures");
+ // A crowd (many small faces) and a close-up (one face across half the frame height).
+ const auto crowdImage = resized(crowd.image, width, height);
+ sink::RgbaImage close; close.width = width; close.height = height; close.pixels.assign(size_t(width) * height * 4, 96);
+ const unsigned side = height; // lena 512 -> the full height
+ const auto big = resized(portrait.image, side, side);
+ for (unsigned y = 0; y < side; ++y)
+ std::memcpy(close.pixels.data() + (size_t(y) * width + (width - side) / 2) * 4, big.pixels.data() + size_t(y) * side * 4, size_t(side) * 4);
+ sink::RgbaImage empty; empty.width = width; empty.height = height; empty.pixels.assign(size_t(width) * height * 4, 96);
+ for (size_t i = 3; i < empty.pixels.size(); i += 4) { empty.pixels[i] = 255; close.pixels[i] = 255; }
+ struct Run { const char* label; const sink::RgbaImage* image; BeautySettings node; };
+ BeautySettings both = smoothNode(0.6f, 4.0f); both.restore = true;
+ const Run runs[] = {{"close-restore", &close, restoreNode()}, {"close-smooth", &close, smoothNode()}, {"close-both", &close, both},
+ {"crowd-both", &crowdImage, both}, {"no-face-both", &empty, both}};
+ for (const auto& run : runs) {
+ auto gpu = std::make_unique<Gpu>();
+ AVFrame* frame = rgbaFrame(*run.image);
+ bool ok = frame && gpu->start(withBeauty(run.node), width, height, false, false);
+ std::vector<double> node, detect, detectAll;
+ sink::RgbaImage out;
+ for (int i = 0; ok && i < 64; ++i) {
+ ok = gpu->render(frame, i == 0, out);
+ if (i < 8) continue;
+ if (const auto ms = gpu->stageMs(diagnostics::beautyNodeStage(0))) node.push_back(*ms);
+ if (const auto ms = gpu->stageMs(diagnostics::GpuStage::BeautyDetect)) {
+ detectAll.push_back(*ms);
+ if (*ms > 0.05) detect.push_back(*ms);
+ }
+ }
+ av_frame_free(&frame);
+ const auto median = [](std::vector<double> v) { if (v.empty()) return 0.0; std::sort(v.begin(), v.end()); return v[v.size() / 2]; };
+ const auto p95 = [](std::vector<double> v) { if (v.empty()) return 0.0; std::sort(v.begin(), v.end()); return v[std::min(v.size() - 1, v.size() * 95 / 100)]; };
+ const auto mean = [](const std::vector<double>& v) { double s = 0; for (double x : v) s += x; return v.empty() ? 0.0 : s / double(v.size()); };
+ std::printf("TIMING extent=%ux%u content=%s nodeMedianMs=%.3f nodeP95Ms=%.3f detectMeanMs=%.3f detectFrameMedianMs=%.3f detectFrameP95Ms=%.3f samples=%zu detectFrames=%zu faces=%u\n",
+ width, height, run.label, median(node), p95(node), mean(detectAll), median(detect), p95(detect), node.size(), detect.size(),
+ gpu->graph->beautyFaceCount());
+ check(ok && node.size() > 40, name + " " + run.label + ": measured");
+ }
+ return failures ? 1 : 0;
+}
+
+// Tuning aid, not a check: VEYRA_BEAUTY_TUNE="tag;stems;amount;radius;detail;texture;rows" runs
+// the smoothing on each picture (rows 0 = native size) and writes the largest face
+// before | after as <tag>-<stem>.png, with the skin / eye texture change.
+int tuneCase() {
+ const char* spec = std::getenv("VEYRA_BEAUTY_TUNE");
+ if (!spec) { std::printf("VEYRA_BEAUTY_TUNE not set\n"); return 2; }
+ std::vector<std::string> f;
+ { std::stringstream s(spec); std::string item; while (std::getline(s, item, ';')) f.push_back(item); }
+ if (f.size() != 7) { std::printf("bad VEYRA_BEAUTY_TUNE\n"); return 2; }
+ BeautySettings b = smoothNode(std::stof(f[2]), std::stof(f[3]));
+ b.detail = std::stof(f[4]); b.texture = std::stof(f[5]);
+ const unsigned rows = unsigned(std::stoul(f[6]));
+ std::stringstream stems(f[1]); std::string stem;
+ while (std::getline(stems, stem, ',')) {
+ Picture loaded;
+ if (!loadPicture(stem, loaded)) { check(false, "tune: picture " + stem); continue; }
+ const Picture p = rows ? enlarged(loaded, rows) : loaded;
+ AVFrame* frame = rgbaFrame(p.image);
+ auto gpu = std::make_unique<Gpu>();
+ sink::RgbaImage off, on;
+ const bool ok = frame && gpu->start(engine::EnhancementSettings{}, p.image.width, p.image.height, false) && gpu->render(frame, true, off) &&
+ gpu->start(withBeauty(b), p.image.width, p.image.height, false) && gpu->render(frame, true, on);
+ av_frame_free(&frame);
+ if (!ok) { check(false, "tune: graph " + stem); continue; }
+ const auto nearEye = [&](unsigned x, unsigned y) {
+ for (const auto& face : p.faces)
+ for (int e = 0; e < 2; ++e)
+ if (std::hypot(x + 0.5 - face.lm[e * 2], y + 0.5 - face.lm[e * 2 + 1]) < face.w * 0.09) return true;
+ return false;
+ };
+ const auto skin = [&](unsigned x, unsigned y) { return inCore(p, x, y) && !nearEye(x, y); };
+ const double s0 = texture(off, skin), s1 = texture(on, skin), e0 = texture(off, nearEye), e1 = texture(on, nearEye);
+ const auto changed = compare(on, off, [&](unsigned x, unsigned y) { return inCore(p, x, y); });
+ std::printf("TUNE tag=%s stem=%s size=%ux%u skin=%.3f->%.3f (%.1f%%) eyes=%.3f->%.3f (%.1f%%) coreMaxDiff=%d\n", f[0].c_str(), stem.c_str(),
+ p.image.width, p.image.height, s0, s1, 100.0 * (s1 / std::max(s0, 1e-9) - 1.0), e0, e1, 100.0 * (e1 / std::max(e0, 1e-9) - 1.0), changed.maxDiff);
+ // Largest face, 1.4x its box, before | after.
+ const auto& face = *std::max_element(p.faces.begin(), p.faces.end(), [](const Face& a, const Face& c) { return a.h < c.h; });
+ const int side = int(std::max(face.w, face.h) * 1.4);
+ const int x0 = std::clamp(int(face.x + face.w / 2) - side / 2, 0, std::max(0, int(p.image.width) - side));
+ const int y0 = std::clamp(int(face.y + face.h / 2) - side / 2, 0, std::max(0, int(p.image.height) - side));
+ const int w = std::min(side, int(p.image.width)), h = std::min(side, int(p.image.height));
+ sink::RgbaImage pair; pair.width = uint32_t(w * 2 + 4); pair.height = uint32_t(h); pair.pixels.assign(size_t(pair.width) * pair.height * 4, 255);
+ for (int y = 0; y < h; ++y) {
+ std::memcpy(pair.pixels.data() + (size_t(y) * pair.width) * 4, off.pixels.data() + (size_t(y0 + y) * off.width + x0) * 4, size_t(w) * 4);
+ std::memcpy(pair.pixels.data() + (size_t(y) * pair.width + w + 4) * 4, on.pixels.data() + (size_t(y0 + y) * on.width + x0) * 4, size_t(w) * 4);
+ }
+ save(f[0] + "-" + stem, pair);
+ }
+ return failures ? 1 : 0;
+}
+
+struct Case { std::string name; std::function<int()> run; };
+std::vector<Case> cases() {
+ std::vector<Case> c;
+ c.push_back({"off-identity", [] { return offIdentityCase(); }});
+ c.push_back({"restore-grade", [] { return restoreCase("restore-grade", 1.0f); }});
+ c.push_back({"restore-half", [] { return restoreCase("restore-half", 0.5f); }});
+ c.push_back({"smooth-lena", [] { return smoothCase("smooth-lena", "lena", strongNode()); }});
+ c.push_back({"smooth-astronaut", [] { return smoothCase("smooth-astronaut", "astronaut", strongNode()); }});
+ c.push_back({"smooth-messi", [] { return smoothCase("smooth-messi", "messi5", strongNode()); }});
+ c.push_back({"smooth-game-night", [] { return smoothCase("smooth-game-night", "gta-f040", strongNode()); }});
+ c.push_back({"two-nodes", [] { return twoNodeCase(); }});
+ c.push_back({"hdr", [] { return hdrCase(); }});
+ c.push_back({"tracking", [] { return trackingCase(); }});
+ c.push_back({"no-model", [] { return noModelCase(); }});
+ c.push_back({"tune", [] { return tuneCase(); }});
+ c.push_back({"timing-1080p", [] { return timingCase("timing-1080p", 1920, 1080); }});
+ c.push_back({"timing-2160p", [] { return timingCase("timing-2160p", 3840, 2160); }});
+ return c;
+}
+} // namespace
+
+int wmain(int argc, wchar_t** argv) {
+ std::setvbuf(stdout, nullptr, _IONBF, 0);
+ const auto all = cases();
+ if (argc == 2 && std::wstring_view(argv[1]) == L"--list") {
+ for (const auto& c : all) std::cout << c.name << '\n';
+ return 0;
+ }
+ if (argc == 5 && std::wstring_view(argv[1]) == L"--case") {
+ gRefs = argv[3]; gOut = argv[4];
+ std::error_code ec; fs::create_directories(gOut, ec);
+ if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return 2; // WIC picture loading
+ const std::wstring wanted = argv[2];
+ for (const auto& c : all)
+ if (std::wstring(c.name.begin(), c.name.end()) == wanted) {
+ const int result = c.run();
+ std::printf(result ? "beauty gpu: %s FAILED\n" : "beauty gpu: %s passed\n", c.name.c_str());
+ return result;
+ }
+ std::cout << "unknown case" << std::endl;
+ return 2;
+ }
+ std::cout << "usage: veyra_beauty_gpu_tests --list | --case <name> <reference-dir> <output-dir>" << std::endl;
+ return 2;
+}
diff --git a/tests/unit/EffectChainTests.cpp b/tests/unit/EffectChainTests.cpp
index 0dd37115..faf787d7 100644
--- a/tests/unit/EffectChainTests.cpp
+++ b/tests/unit/EffectChainTests.cpp
@@ -1065,7 +1065,8 @@ __declspec(noinline) void testAntiAliasSettingsChain() {
check(chain->countOf(EffectType::AntiAliasing) == 0 && chain->countOf(EffectType::Beauty) == 0 && !chain->overflow,
"E0: untouched settings add no anti-aliasing or beauty node");
check(effectInfo(EffectType::AntiAliasing).hidden != pipeline::EnhanceGraphDesc::antiAliasExecutor &&
- effectInfo(EffectType::Beauty).hidden, "E0: the catalog hides effects whose executor is not built");
+ effectInfo(EffectType::Beauty).hidden != pipeline::EnhanceGraphDesc::beautyExecutor,
+ "E0: the catalog shows exactly the effects whose executor is built");
chain->overflow = true;
check(!validateChain(*chain).accepted, "E0: an overflowing chain is refused instead of losing its last node");
@@ -1148,6 +1149,7 @@ __declspec(noinline) void testSameSizeSlots() {
auto& node = chain->nodes[chain->nodeCount++]; node.type = type; node.enabled = true;
if (type == EffectType::Color) node.color.enabled = true;
if (type == EffectType::AntiAliasing) { node.aa.enabled = true; node.aa.method = AntiAliasMethod::Smaa; node.aa.quality = 1; }
+ if (type == EffectType::Beauty) { node.beauty.enabled = true; node.beauty.smooth = true; }
}
auto settings = std::make_unique<EnhancementSettings>(); fromChain(*chain, *settings);
const auto order = runtimeOrder(*chain);
@@ -1191,13 +1193,120 @@ __declspec(noinline) void testSameSizeSlots() {
desc->slotOfStep(step(*desc, EffectType::AntiAliasing, 1)) == Slot::Tail && desc->antiAlias[1].enabled,
"E0 slots: mixed same-size passes after SR share the tail slot in order");
describe({EffectType::SuperResolution, EffectType::NrEnhance, EffectType::Beauty}, true, *desc);
- check(!desc->fixedExecutionPlanError.empty(), "E0: beauty nodes do not reach the graph in this build");
+ check(desc->fixedExecutionPlanError.empty() && desc->slotOfStep(step(*desc, EffectType::Beauty, 0)) == Slot::Tail &&
+ desc->validateFixedExecutionPlan().empty() && desc->beautyActive(), "beauty: SR -> NR -> beauty runs in the tail slot");
+ describe({EffectType::Beauty, EffectType::SuperResolution, EffectType::NrEnhance}, true, *desc);
+ check(desc->slotOfStep(step(*desc, EffectType::Beauty, 0)) == Slot::SourcePost && desc->validateFixedExecutionPlan().empty(),
+ "beauty: a leading beauty node runs at source size");
+ describe({EffectType::SuperResolution, EffectType::Beauty, EffectType::NrEnhance}, true, *desc);
+ check(desc->slotOfStep(step(*desc, EffectType::Beauty, 0)) == Slot::PreNr && desc->validateFixedExecutionPlan().empty(),
+ "beauty: SR -> beauty -> NR uses the pre-NR slot");
+ describe({EffectType::NrEnhance, EffectType::Beauty, EffectType::SuperResolution}, true, *desc);
+ check(desc->nrBeforeSr && desc->slotOfStep(step(*desc, EffectType::Beauty, 0)) == Slot::PreSr && desc->validateFixedExecutionPlan().empty(),
+ "beauty: NR -> beauty -> SR uses the pre-SR slot");
// Color-only chains keep their existing slots (also covered byte-for-byte by the slot regression).
describe({EffectType::NrEnhance, EffectType::Color, EffectType::SuperResolution, EffectType::Color}, true, *desc);
check(desc->validateFixedExecutionPlan().empty() && desc->preSrColor(0) && desc->tailColor(1) && !desc->sourcePostActive(),
"E0 slots: Color-only node chains keep the pre-SR and tail grades");
}
+__declspec(noinline) void testBeautySettingsChain() {
+ using namespace veyra;
+ using namespace veyra::engine;
+ using Slot = pipeline::EnhanceGraphDesc::PassSlot;
+ BeautySettings b;
+ check(b.validate().empty() && !b.configured() && !b.effective(), "beauty: defaults validate and do nothing");
+ const auto refused = [](auto edit) { BeautySettings v; v.enabled = true; edit(v); return !v.validate().empty(); };
+ check(refused([](BeautySettings& v) { v.radius = 13.0f; }) && refused([](BeautySettings& v) { v.satMin = 0.9f; }) &&
+ refused([](BeautySettings& v) { v.minConfidence = 0.2f; }) && refused([](BeautySettings& v) { v.regionExpand = 0.5f; }) &&
+ refused([](BeautySettings& v) { v.restoreStrength = std::nanf(""); }),
+ "beauty: out-of-range values are refused");
+ BeautyDetection d;
+ check(d.validate().empty() && d.inputLongSide() == 512 && d.rateHz() == 15.0f, "beauty: balanced detection by default");
+ d.maxFaces = 0; check(!d.validate().empty(), "beauty: a detector needs at least one face");
+ // Sub-functions are independent: strength 0 skips only the smoothing.
+ b.enabled = true; b.restore = true; b.smooth = true; b.strength = 0.0f;
+ check(b.restoreActive() && !b.smoothActive() && b.effective(), "beauty: smoothing strength 0 keeps the face restore");
+ b.strength = 1.0f; b.restoreStrength = 0.0f;
+ check(!b.restoreActive() && b.smoothActive(), "beauty: restore strength 0 keeps the smoothing");
+
+ // Two list layers and shared detection survive the chain round trip, after protection.
+ auto s = std::make_unique<EnhancementSettings>();
+ s->nr = true; s->sr = true; s->protection.enabled = true;
+ s->beauty.enabled = true; s->beauty.restore = true; s->beauty.restoreStrength = 0.75f; s->beauty.feather = 0.12f;
+ s->additionalBeautyCount = 1;
+ auto& second = s->additionalBeauty[0];
+ second.enabled = false; second.smooth = true; second.smoothAmount = 0.5f; second.radius = 3.5f; second.scope = BeautyScope::AllSkin;
+ s->beautyDetection.quality = 2; s->beautyDetection.maxFaces = 2; s->beautyDetection.stability = 0.8f;
+ check(s->validate().empty(), "beauty: two list layers validate");
+ auto chain = std::make_unique<EffectChain>(toChain(*s));
+ uint32_t protection = chain->nodeCount, first = chain->nodeCount, hdr = chain->nodeCount;
+ for (uint32_t i = 0; i < chain->nodeCount; ++i) {
+ if (chain->nodes[i].type == EffectType::Protection) protection = i;
+ if (chain->nodes[i].type == EffectType::Beauty && first == chain->nodeCount) first = i;
+ if (chain->nodes[i].type == EffectType::VideoHdr) hdr = i;
+ }
+ check(chain->countOf(EffectType::Beauty) == 2 && protection < first && first < hdr && chain->beautyDetection == s->beautyDetection,
+ "beauty: the list group follows NR protection and precedes RTX Video HDR");
+ auto back = std::make_unique<EnhancementSettings>();
+ fromChain(*chain, *back);
+ check(back->beauty == s->beauty && back->additionalBeautyCount == 1 && back->additionalBeauty[0] == second &&
+ back->beautyDetection == s->beautyDetection, "beauty: fromChain restores both layers and the detection values");
+
+ // Plan: default order puts the group in the tail; NR-first preview right after NR.
+ StageRequest request; request.width = 1280; request.height = 720; request.nr = true; request.sr = true;
+ auto desc = std::make_unique<pipeline::EnhanceGraphDesc>();
+ describeStages(request, *s, *desc);
+ const auto beautyStep = desc->planStepOf(EffectType::Beauty, 0);
+ check(desc->fixedExecutionPlanError.empty() && desc->slotOfStep(beautyStep) == Slot::Tail && desc->beauty[0] == s->beauty &&
+ desc->beautyDetection == s->beautyDetection && desc->validateFixedExecutionPlan().empty(),
+ "beauty: list mode runs the group in the tail slot");
+ auto nrFirst = std::make_unique<EnhancementSettings>(*s); nrFirst->lowLatency = true;
+ for (auto& layer : nrFirst->nrLayers) layer.lowLatencyPairing = true;
+ describeStages(request, *nrFirst, *desc);
+ check(desc->nrBeforeSr && desc->slotOfStep(desc->planStepOf(EffectType::Beauty, 0)) == Slot::PreSr && desc->validateFixedExecutionPlan().empty(),
+ "beauty: NR-first preview runs the group between NR and SR");
+ StageRequest still = request; still.stillImage = true; still.sr = false;
+ describeStages(still, *s, *desc);
+ check(desc->beautyDetectEveryFrame && !desc->beautyRequireDetector, "beauty: a picture is detected on its own frame");
+ StageRequest exportJob = request; exportJob.exportJob = true;
+ auto masked = std::make_unique<EnhancementSettings>(*s); masked->beauty.showMask = true;
+ describeStages(exportJob, *masked, *desc);
+ check(desc->beautyRequireDetector && desc->beautyDetectEveryFrame && !desc->beauty[0].showMask,
+ "beauty: export needs the detector, detects every frame and never writes the mask view");
+
+ // Only the master switch (and the instance count) rebuilds; every value is live.
+ auto live = std::make_unique<EnhancementSettings>(*s);
+ live->beauty.restoreStrength = 0.3f; live->beauty.smooth = true; live->beauty.radius = 6.0f; live->beautyDetection.quality = 0;
+ check(s->sameVideoConfiguration(*live) && !requiresGraphRebuild(*s, *live), "beauty: tuning an enabled node is live");
+ auto toggled = std::make_unique<EnhancementSettings>(*s); toggled->beauty.enabled = false;
+ check(!s->sameVideoConfiguration(*toggled) && requiresGraphRebuild(*s, *toggled), "beauty: switching a node rebuilds");
+ auto counted = std::make_unique<EnhancementSettings>(*s); counted->additionalBeautyCount = 0;
+ check(requiresGraphRebuild(*s, *counted), "beauty: removing a layer rebuilds");
+ auto disabled = std::make_unique<EnhancementSettings>(*toggled); disabled->beauty.radius = 7.0f;
+ check(toggled->sameVideoConfiguration(*disabled), "beauty: editing a disabled node changes nothing");
+
+ // Node mode: two beauty nodes keep their order and parameters.
+ auto node = std::make_unique<EffectChain>(); node->mode = ChainMode::Node;
+ const auto add = [&](EffectType type) -> ChainNode& { auto& n = node->nodes[node->nodeCount++]; n = ChainNode{}; n.type = type; n.enabled = true; return n; };
+ add(EffectType::Beauty).beauty.smooth = true;
+ add(EffectType::SuperResolution);
+ auto& tail = add(EffectType::Beauty); tail.beauty.restore = true; tail.beauty.minConfidence = 0.8f;
+ auto nodeSettings = std::make_unique<EnhancementSettings>(); fromChain(*node, *nodeSettings);
+ const auto order = runtimeOrder(*node);
+ auto restored = std::make_unique<EffectChain>();
+ const auto verdict = restoreRuntimeOrder(*nodeSettings, *order, *restored);
+ check(verdict.accepted && restored->nodes[2].beauty.minConfidence == 0.8f && restored->nodes[0].beauty.smooth,
+ "beauty: node order restores both instances");
+ StageRequest nodeRequest; nodeRequest.width = 640; nodeRequest.height = 360; nodeRequest.sr = true; nodeRequest.nodeOrder = &*order;
+ describeStages(nodeRequest, *nodeSettings, *desc);
+ check(desc->slotOfStep(desc->planStepOf(EffectType::Beauty, 0)) == Slot::SourcePost &&
+ desc->slotOfStep(desc->planStepOf(EffectType::Beauty, 1)) == Slot::Tail && desc->validateFixedExecutionPlan().empty(),
+ "beauty: node mode runs one instance at source size and one in the tail");
+ for (int i = 0; i < 6; ++i) add(EffectType::Beauty);
+ check(!validateChain(*node).accepted, "beauty: more than six beauty nodes are refused");
+}
+
__declspec(noinline) void testWideChains() {
using namespace veyra::engine;
auto chain = std::make_unique<EffectChain>(); chain->mode = ChainMode::Node;
@@ -1293,6 +1402,7 @@ int main() {
testNativeVideoSrPolicy();
testAntiAliasSettingsChain();
testSameSizeSlots();
+ testBeautySettingsChain();
testWideChains();
std::printf(failures ? "effect chain: %d FAILURES\n" : "effect chain: all checks passed\n", failures);
return failures ? 1 : 0;
diff --git a/tests/unit/PresetLibraryTests.cpp b/tests/unit/PresetLibraryTests.cpp
index ce46c0c7..3120aa06 100644
--- a/tests/unit/PresetLibraryTests.cpp
+++ b/tests/unit/PresetLibraryTests.cpp
@@ -1102,6 +1102,63 @@ __declspec(noinline) void testDlssSrModels() {
}
// E0 (2026-10-18): library v14 / session v9 carry anti-aliasing nodes and chains
// past 16 nodes in their own files; older readers keep their bytes.
+__declspec(noinline) void testBeautyNodeStorage() {
+ const auto path = scratch(L"beauty-library.v1");
+ const auto sidecar = std::filesystem::path(path).concat(L".beauty");
+ for (const auto* suffix : {L".beauty", L".effects", L".effects.beauty"}) std::filesystem::remove(std::filesystem::path(path).concat(suffix));
+ PresetLibrary writer(path); writer.setIncludeBuiltins(false);
+ auto old = std::make_unique<PresetEntry>(); old->name = L"before beauty"; old->chain = toChain(sample());
+ check(writer.load() && writer.put(*old), "beauty storage: seed a library without beauty");
+ const auto original = readBytes(path);
+ check(!original.starts_with("VEYRA_PRESET_LIBRARY 15") && !std::filesystem::exists(sidecar),
+ "beauty storage: untouched beauty keeps the older format");
+ auto settings = sample();
+ settings.beauty.enabled = true; settings.beauty.restore = true; settings.beauty.restoreStrength = 0.8f; settings.beauty.feather = 0.12f;
+ settings.beauty.smooth = true; settings.beauty.smoothAmount = 0.55f; settings.beauty.radius = 6.5f; settings.beauty.scope = BeautyScope::AllSkin;
+ settings.beauty.minConfidence = 0.7f; settings.beauty.lumaMin = 0.06f;
+ settings.additionalBeautyCount = 1;
+ settings.additionalBeauty[0].enabled = false; settings.additionalBeauty[0].restore = true; settings.additionalBeauty[0].restoreScope = BeautyRestoreScope::Skin;
+ settings.beautyDetection.quality = 2; settings.beautyDetection.maxFaces = 3; settings.beautyDetection.stability = 0.25f;
+ check(settings.validate().empty(), "beauty storage: two beauty layers validate");
+ auto entry = std::make_unique<PresetEntry>(); entry->name = L"beauty"; entry->chain = toChain(settings);
+ check(writer.put(*entry), "beauty storage: save a chain with beauty");
+ check(readBytes(path) == original && readBytes(sidecar).starts_with("VEYRA_PRESET_LIBRARY 15\n"),
+ "beauty storage: v15 goes to its own file and keeps the older library intact");
+ {
+ PresetLibrary reader(path); reader.setIncludeBuiltins(false);
+ check(reader.load() && reader.entries().size() == 2 && reader.entries()[1].chain == entry->chain,
+ "beauty storage: both layers and the shared detection reload exactly");
+ auto applied = sample(); PresetLibrary::apply(reader.entries()[1], applied);
+ check(applied.beauty == settings.beauty && applied.additionalBeautyCount == 1 && applied.additionalBeauty[0] == settings.additionalBeauty[0] &&
+ applied.beautyDetection == settings.beautyDetection, "beauty storage: applying the chain restores beauty");
+ auto plain = sample(); PresetLibrary::apply(reader.entries()[0], plain);
+ check(plain.beauty == BeautySettings{} && plain.additionalBeautyCount == 0, "beauty storage: an older chain applies without beauty");
+ }
+ // A v14 reader (anti-aliasing build) cannot take the beauty payload; it refuses the file.
+ auto downgraded = readBytes(sidecar);
+ downgraded.replace(0, std::string("VEYRA_PRESET_LIBRARY 15").size(), "VEYRA_PRESET_LIBRARY 14");
+ const auto downgradedPath = scratch(L"beauty-downgraded.v1");
+ { std::ofstream f(downgradedPath, std::ios::binary); f << downgraded; }
+ {
+ PresetLibrary reader(downgradedPath); reader.setIncludeBuiltins(false);
+ check(!reader.load() || reader.entries().empty(), "beauty storage: beauty payloads under a v14 header are refused");
+ }
+ const auto sessionPath = scratch(L"beauty-session.v1");
+ for (const auto* suffix : {L".beauty", L".effects"}) std::filesystem::remove(std::filesystem::path(sessionPath).concat(suffix));
+ auto session = std::make_unique<ChainSession>(ChainSession::initial(sample()));
+ ChainSessionStore sessions(sessionPath);
+ check(sessions.save(*session), "beauty session: save the older format first");
+ const auto rollback = readBytes(sessionPath);
+ session->configurations[0].chain = toChain(settings);
+ check(sessions.save(*session) && readBytes(sessionPath) == rollback &&
+ readBytes(std::filesystem::path(sessionPath).concat(L".beauty")).starts_with("VEYRA_CHAIN_SESSION 10"),
+ "beauty session: v10 goes to its own file");
+ auto restored = std::make_unique<ChainSession>();
+ ChainSessionStore reload(sessionPath);
+ check(reload.load(*restored) && restored->configurations[0].chain == session->configurations[0].chain,
+ "beauty session: the list chain with beauty reloads exactly");
+}
+
__declspec(noinline) void testEffectNodeStorage() {
const auto path = scratch(L"effects-library.v1");
const auto sidecar = std::filesystem::path(path).concat(L".effects");
@@ -1138,7 +1195,7 @@ __declspec(noinline) void testEffectNodeStorage() {
check(!reader.load() || reader.entries().empty(), "effects storage: anti-aliasing nodes under a v13 header are refused");
}
auto future = readBytes(sidecar);
- future.replace(0, std::string("VEYRA_PRESET_LIBRARY 14").size(), "VEYRA_PRESET_LIBRARY 15");
+ future.replace(0, std::string("VEYRA_PRESET_LIBRARY 14").size(), "VEYRA_PRESET_LIBRARY 16");
const auto futurePath = scratch(L"effects-future.v1");
{ std::ofstream f(futurePath, std::ios::binary); f << future; }
{
@@ -1182,6 +1239,7 @@ __declspec(noinline) void testEffectNodeStorage() {
}
int main() {
testEffectNodeStorage();
+ testBeautyNodeStorage();
testDlssSrModels();
testFlowStorage();
testFlowApplication();