This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 21:27:42 -04:00
1 parent 5fd47421f9
commit aecd2ebe1d
852 files changed
+4844 -46144

No files matched your search

+93 -155
View File
@@ -1,6 +1,3 @@
// win-fg - runtime config: enable gate, model, multiplier, and the synthesis
// tuning parameters. Sourced from environment variables and an optional
// conf.toml (a config file, when present, wins over the env defaults).
#pragma once
#include <cstdint>
#include <cstdlib>
@@ -12,143 +9,110 @@
namespace winfg {
struct Config {
bool enabled = false; // gate; loader also honours the manifest enable var
// GRANULAR PRESENT-PATH DEBUG TRACE. Default OFF. When ON, winfg_QueuePresentKHR
// emits a per-frame, step-by-step trail (logcat tag "win-fg") so a freeze/
// crash-on-enable leaves an obvious LAST line at the exact stage that hung or
// faulted (acquire-spare, compute-submit, present-generated/real, fence wait,
// fallback). Zero behaviour change and effectively zero cost when off - one
// predicted-not-taken bool test per step, no logcat writes.
// WIN_FG_DEBUG=1|0 / conf.toml debug=on|off.
bool enabled = false;
bool debug = false;
// ── EVEN-CADENCE FRAME PACING ─────────────────────────────────────────────
// Default ON. The 2x insert path presents the GENERATED frame then the REAL
// frame back-to-back in one vkQueuePresentKHR hook call, so on Mailbox/
// Immediate both land in ~one instant followed by a full frame-interval gap
// until the next pair - uneven in time → judder ("slows down to catch up").
// With pacing on, the layer measures the real-frame interval (EMA of a
// monotonic clock) and holds the REAL present to its scheduled beat so the
// generated frame lands near the temporal MIDPOINT between consecutive real
// frames (even gen,real,gen,real cadence). Pure bounded CPU sleep - no GPU
// wait added; if a frame is already behind schedule the wait is SKIPPED
// (present immediately) so worst case is one un-paced pair, never a hitch.
// FIFO self-paces so the waits collapse to ~0 there. Off ⇒ byte-identical
// back-to-back behaviour. WIN_FG_PACING=on|off / conf.toml pacing=on|off.
// ISOLATION BUILD: default flipped to OFF to A/B the AYANEO-750 post-setting-change
// flicker regression against the pacing feature (everything else byte-identical).
bool pacing = false;
int model = 4; // 3 = symmetric flow, 4 = bidir + occlusion gate
int multiplier = 2; // generated presents per real present + 1
// EXTRA SWAPCHAIN IMAGE HEADROOM (device-freeze fix). On top of the +1 spare the
// insert path needs, request this many ADDITIONAL images at swapchain creation:
// requested minImageCount = app_min + 1 (spare) + extra_images,
// clamped to surfaceCaps.maxImageCount (0 = unlimited -> no clamp), never below
// app_min+1. The extra headroom stops the guest's NEXT vkAcquireNextImageKHR from
// starving while win-fg holds a spare + a real frame in flight to the AHB-backed
// host compositor. Some SoCs (Adreno 840 / Turnip) recycle displayed AHBs too
// slowly to tolerate the extra present with only the +1 spare and freeze on the
// first inserted frame; the AYANEO (Adreno 750) recycles fast enough to tolerate
// it. Default 2 (a few MB VRAM), applied on all devices. On a device that already
// works this only grows the pool - no FPS/quality change; the pool-headroom guard
// in QueuePresentKHR stays a no-op when headroom is adequate.
// WIN_FG_EXTRA_IMAGES / conf.toml extra_images.
int model = 4;
int multiplier = 2;
int extraImages = 2;
// ── FLOW-RESOLUTION PERFORMANCE PRESET ────────────────────────────────────
// Trades base-FPS-drop against optical-flow quality by selecting the FINEST
// pyramid level the dense flow is solved at (FrameGen::kFlowFinest):
// 0 = Quality -> kFlowFinest = 1 (~1/2-res flow; best motion, biggest FG cost)
// 1 = Balanced -> kFlowFinest = 2 (~1/4-res; TODAY's behaviour) [DEFAULT]
// 2 = Performance -> kFlowFinest = 3 (~1/8-res; cheapest -> smallest base-FPS drop)
// Out-of-range clamps to Balanced (1), so an unset/older conf.toml is byte-
// identical to today. Changing this LIVE rebuilds the affected per-size flow
// images (like a resize) inside the layer and resets the flow predictor, so a
// preset change is fully hot - no FG toggle needed. See FrameGen::configure /
// FrameGen::flowFinestForPreset. WIN_FG_PERF_PRESET / conf.toml perf_preset.
int perfPreset = 1; // 0 quality, 1 balanced (default), 2 performance
float flowScale = 1.0f; // scales solved flow magnitude
// C1 GLOBAL-MOTION PRE-WARP. Estimate the per-frame camera affine (LK) and
// remove it before the dense SAD flow search so the search only sees coherent
// object-only residual motion (kills fast-pan "melt"). 0 = auto (engage only
// when the LK solve is stable), 1 = on (force-engage once a solve exists),
// 2 = off (never pre-warp; identity affine → pipeline == pre-C1 exactly).
// WIN_FG_GM=auto|on|off / conf.toml global_motion=auto|on|off.
int gmMode = 0; // 0 auto, 1 on, 2 off
// C2 FLOW REGULARIZATION (TV-L1 smoothness prior). After C1 removes the camera
// motion, the dense flow (flowLvl_ at kFlowFinest, 1/4-res) is the OBJECT-only
// residual; it still carries spurious per-block vectors. C2 runs N semi-implicit
// TV-L1 denoising iterations on that field - an L1 data term + edge-aware Total-
// Variation regularizer - to kill incoherent vectors while KEEPING true motion
// discontinuities (object edges) sharp. Solved in-place; expand's median + C1
// add-back consume the cleaned field unchanged. 0 iterations ⇒ byte-identical to
// pre-C2. See shaders/of3_flowreg.comp.
// WIN_FG_FLOWREG=auto|on|off / conf.toml flow_reg=auto|on|off.
int frMode = 0; // 0 auto (engaged), 1 on (engaged), 2 off
int frIters = 4; // TV-L1 iterations at kFlowFinest (0 ⇒ off)
float frLambda = 2.0f; // L1 data-fidelity weight (higher ⇒ trust SAD flow)
float frDt = 0.25f; // semi-implicit smoothing step (higher ⇒ smoother)
float frEdge = 8.0f; // luma-gradient edge sensitivity for the TV weight g
float frEps = 0.05f; // Charbonnier epsilon (px) for the TV diffusivity
// synthesis (wfg_synth) tuning
float beta = 8.0f; // softmax sharpness on importance Z
float lambda = 0.6f; // FB-consistency vs photometric weight
// Tightened 2026-08-17 to prioritise "no ghost" over max sharpness - the
// remaining single-frame ghosts came from pixels that the previous defaults
// still trusted with warp when they should have cross-faded. Raising both
// pushes borderline pixels toward the safe cross-fade path (softer, but no
// smear). Prewarp will lift the ceiling further; this is the "safety net"
// knob change until then.
// Walked back from (0.10, 9.0) tighten after user reported softening. The
// real fix for the residual ghosts is the 3a-fallback path change in
// layer.cpp (present real curr on fallback instead of blitting synth over);
// the gate can stay closer to the original values now.
float epsilon = 0.07f; // disocclusion floor (0.05 -> 0.10 -> 0.07)
float photoScale = 7.5f; // photometric residual scale into Z (6.0 -> 9.0 -> 7.5)
// HUD exclusion rect in pixel coords (x0,y0,x1,y1). Fragments inside are
// passed through as the real current frame (no warp, no synth) so text /
// overlays don't ghost. Disabled when x0 >= x1 or y0 >= y1 (the default).
// Sourced from WIN_FG_HUD_RECT="x0,y0,x1,y1" env var or conf.toml
// (hudRect="x0,y0,x1,y1"). Pattern is Isygold's Vegas DXVK framegen -
// host knows where the HUD is, tell the shader to skip it.
int perfPreset = 1;
float flowScale = 1.0f;
int gmMode = 0;
int frMode = 0;
int frIters = 4;
float frLambda = 2.0f;
float frDt = 0.25f;
float frEdge = 8.0f;
float frEps = 0.05f;
float beta = 8.0f;
float lambda = 0.6f;
float epsilon = 0.07f;
float photoScale = 7.5f;
float hudX0 = 0.0f;
float hudY0 = 0.0f;
float hudX1 = 0.0f;
float hudY1 = 0.0f;
// ── TRAINING-DATA CAPTURE MODE (Route-B VFI dataset collection) ───────────
// A dev-only gate. When OFF (default) the present path is byte-identical to a
// build without this feature - a single bool test and nothing else. When ON,
// every real present is downscaled on the GPU, read back async, and written to
// disk as lossless QOI (motion-rich 256² triplet patches by default, or full
// downscaled frames) plus a JSONL manifest, for offline (i-1,i+1)->i training.
// NEVER captures win-fg's generated frames - capture reads the real swapchain
// image at the TOP of QueuePresentKHR, before any interpolation.
// WIN_FG_CAPTURE=on|off / conf.toml capture=on|off.
bool capture = false;
// Downscale target box (aspect-preserving, never upscales). WIN_FG_CAPTURE_W/H,
// conf capture_width/capture_height.
int captureW = 1280;
int captureH = 720;
// 0 = patch (self-contained aligned triplets, DEFAULT), 1 = frame (full
// downscaled frames in order). WIN_FG_CAPTURE_MODE=patch|frame.
int capMode = 0;
int capPatches = 3; // patches per triplet in patch mode (WIN_FG_CAPTURE_PATCHES)
int capPatchSize = 256; // patch edge in downscaled px (WIN_FG_CAPTURE_PATCH)
// Skip a unit whose inter-frame motion (mean per-pixel luma abs-diff, 0..255)
// is below this. WIN_FG_CAPTURE_MOTION / conf capture_motion.
int capPatches = 3;
int capPatchSize = 256;
float capMotion = 2.0f;
// Output dir; empty => $HOME/.cache/winfg-capture. WIN_FG_CAPTURE_DIR /
// conf capture_dir. A per-run session subdir is created under it.
std::string capDir;
// Rolling-shard size cap (MiB). Output is a small number of large packed
// .wfgcap containers, not thousands of loose files; a new shard opens when the
// current one passes this. WIN_FG_CAPTURE_SHARD_MB / conf capture_shard_mb.
int capShardMB = 1024;
void sanitize() {
if (model < 3) model = 3; if (model > 4) model = 4;
if (multiplier < 2) multiplier = 2; if (multiplier > 4) multiplier = 4;
if (extraImages < 0) extraImages = 0; if (extraImages > 8) extraImages = 8;
if (perfPreset < 0 || perfPreset > 2) perfPreset = 1; // clamp out-of-range -> Balanced
if (perfPreset < 0 || perfPreset > 2) perfPreset = 1;
if (gmMode < 0) gmMode = 0; if (gmMode > 2) gmMode = 2;
if (frMode < 0) frMode = 0; if (frMode > 2) frMode = 2;
if (frIters < 0) frIters = 0; if (frIters > 16) frIters = 16;
@@ -158,7 +122,6 @@ struct Config {
if (frEps < 1e-3f) frEps = 1e-3f;
if (flowScale < 0.05f) flowScale = 0.05f; if (flowScale > 4.0f) flowScale = 4.0f;
if (beta < 0.0f) beta = 0.0f; if (lambda < 0.0f) lambda = 0.0f;
// capture knobs
if (captureW < 16) captureW = 16; if (captureW > 7680) captureW = 7680;
if (captureH < 16) captureH = 16; if (captureH > 4320) captureH = 4320;
if (capMode < 0) capMode = 0; if (capMode > 1) capMode = 1;
@@ -176,7 +139,6 @@ static inline int envi(const char* k, int d) {
const char* v = std::getenv(k); return v ? std::atoi(v) : d;
}
// "auto"/"on"/"off" (also true/false/on/off numerics) -> {0 auto, 1 on, 2 off}.
static inline int parse_tristate(const std::string& v, int dflt) {
if (v.empty()) return dflt;
if (v == "auto") return 0;
@@ -185,19 +147,16 @@ static inline int parse_tristate(const std::string& v, int dflt) {
return dflt;
}
// "on"/"off"/"1"/"true"/... -> bool.
static inline bool parse_bool(const std::string& v, bool dflt) {
int t = parse_tristate(v, dflt ? 1 : 2);
return t == 1;
}
// "patch"|"frame" -> {0 patch, 1 frame}.
static inline int parse_capmode(const std::string& v, int dflt) {
if (v == "patch" || v == "patches" || v == "0") return 0;
if (v == "frame" || v == "frames" || v == "1") return 1;
return dflt;
}
// key=value TOML-lite reader (flat keys, '#' comments) - enough for our knobs.
static inline void apply_toml(Config& c, const std::string& path) {
std::ifstream f(path);
if (!f) return;
@@ -229,7 +188,6 @@ static inline void apply_toml(Config& c, const std::string& path) {
else if (k == "lambda") c.lambda = std::strtof(v.c_str(), nullptr);
else if (k == "epsilon") c.epsilon = std::strtof(v.c_str(), nullptr);
else if (k == "photoScale") c.photoScale = std::strtof(v.c_str(), nullptr);
// ── capture-mode knobs ────────────────────────────────────────────────
else if (k == "capture") c.capture = parse_bool(v, c.capture);
else if (k == "capture_dir") c.capDir = v;
else if (k == "capture_width") c.captureW = std::atoi(v.c_str());
@@ -240,7 +198,6 @@ static inline void apply_toml(Config& c, const std::string& path) {
else if (k == "capture_motion") c.capMotion = std::strtof(v.c_str(), nullptr);
else if (k == "capture_shard_mb") c.capShardMB = std::atoi(v.c_str());
else if (k == "hudRect") {
// "x0,y0,x1,y1" in pixel coords
float r[4] = {0,0,0,0}; int n = 0;
size_t start = 0; std::string s = v;
for (; n < 4; ++n) {
@@ -255,22 +212,18 @@ static inline void apply_toml(Config& c, const std::string& path) {
}
}
// Path of the conf.toml the app writes (used for hot-reload mtime checks).
static inline std::string conf_path() {
if (const char* p = std::getenv("WIN_FG_CONF")) return p;
const char* home = std::getenv("HOME");
return home ? std::string(home) + "/.config/win-fg/conf.toml" : std::string();
}
// Resolve the capture output root: explicit override, else $HOME/.cache/winfg-capture,
// else a /tmp fallback so a HOME-less prefix still writes somewhere pullable.
static inline std::string capture_root(const Config& c) {
if (!c.capDir.empty()) return c.capDir;
if (const char* home = std::getenv("HOME")) return std::string(home) + "/.cache/winfg-capture";
return std::string("/tmp/winfg-capture");
}
// env defaults first, then conf.toml overrides (file wins when present).
static inline Config load_config() {
Config c;
c.enabled = envi("WIN_FG_ENABLE", 0) != 0;
@@ -292,7 +245,6 @@ static inline Config load_config() {
c.lambda = envf("WIN_FG_LAMBDA", c.lambda);
c.epsilon = envf("WIN_FG_EPSILON", c.epsilon);
c.photoScale = envf("WIN_FG_PHOTOSCALE", c.photoScale);
// ── capture-mode env (conf.toml still wins below) ─────────────────────────
if (const char* cc = std::getenv("WIN_FG_CAPTURE")) c.capture = parse_bool(cc, c.capture);
c.captureW = envi("WIN_FG_CAPTURE_W", c.captureW);
c.captureH = envi("WIN_FG_CAPTURE_H", c.captureH);
@@ -303,7 +255,6 @@ static inline Config load_config() {
c.capShardMB = envi("WIN_FG_CAPTURE_SHARD_MB", c.capShardMB);
if (const char* cd = std::getenv("WIN_FG_CAPTURE_DIR")) c.capDir = cd;
if (const char* h = std::getenv("WIN_FG_HUD_RECT")) {
// "x0,y0,x1,y1" - pixel coords; disabled when x0>=x1 or y0>=y1
float r[4] = {0,0,0,0}; int n = 0;
std::string s = h; size_t start = 0;
for (; n < 4; ++n) {
@@ -321,37 +272,24 @@ static inline Config load_config() {
return c;
}
// UBO layout - MUST match wfg_synth.comp binding 0.
// The vec4 hudRect is 16-byte aligned in std140, sits at offset 32 (after the
// 8 leading floats which naturally occupy 32B). Disabled when hudX0>=hudX1.
struct SynthUBO {
float flowScale, alpha, beta, lambda, epsilon, photoScale, pad0, pad1;
float hudX0, hudY0, hudX1, hudY1;
};
// UBO layout - MUST match of3_flow / of3_expand_m4 binding 0 (Model3UBO).
struct FlowUBO { float flowScale; uint32_t level; float occlLo; float occlHi; };
// C1 global-motion UBO - MUST match binding 1 in of3_gm_reduce / of3_gm_prewarp /
// of3_expand(_m4). std140: four vec4 = 64 bytes. The affine is in centered-UV
// space: P = [[p1,p3],[p2,p4]], translation (tx,ty); warp uvSrc = uv + P*(uv-0.5)
// + t maps a prev(template) coord to the curr(image) coord it samples (prev→curr).
// lin[] = running LK estimate (linearization point fed to of3_gm_reduce)
// app[] = APPLIED affine (of3_gm_prewarp + expand add-back); identity when
// disengaged so the pipeline is byte-identical to pre-C1.
struct GMUBO {
float lin[4]; // p1,p2,p3,p4
float linT[4]; // tx,ty, engaged, pad
float app[4]; // p1,p2,p3,p4
float appT[4]; // tx,ty, pad, pad
float lin[4];
float linT[4];
float app[4];
float appT[4];
};
// C2 flow-regularization UBO - MUST match binding 0 (vec4 params) in
// of3_flowreg.comp. std140: one vec4 = 16 bytes. See Config::fr* fields.
struct FlowRegUBO {
float dt; // params.x - semi-implicit smoothing step
float lambda; // params.y - L1 data-fidelity weight (θ = dt·lambda)
float edgeAlpha; // params.z - luma-gradient edge sensitivity for g
float epsTV; // params.w - Charbonnier epsilon (px) for the TV diffusivity
float dt;
float lambda;
float edgeAlpha;
float epsTV;
};
} // namespace winfg
}
@@ -1,5 +1,3 @@
// GENERATED by tools/embed_spv.py - do not edit by hand.
// win-fg embedded SPIR-V: our optical-flow front end + synthesis only.
#pragma once
#include <cstdint>
#include <cstddef>
@@ -41,4 +39,4 @@ static inline Blob blob(Shader s) {
default: return { nullptr, 0 };
}
}
} } // namespace winfg::embedded
} }
+8 -36
View File
@@ -1,4 +1,3 @@
// win-fg - compute frame-generation engine implementation.
#include "framegen.hpp"
#include "embedded_shaders.hpp"
#include "log.hpp"
@@ -49,10 +48,6 @@ void FrameGen::destroyImage(Img& i) {
i = Img{};
}
// C1: allocate the per-slot host-visible SSBOs the LK reduce writes partials into.
// Host-visible + coherent so the CPU can read them back after the owning frame's
// fence signals (no staging copy needed; the buffers are tiny - kGmThreads*kGmStride
// floats each, ~64 KB). Persistently mapped.
bool FrameGen::makeGmBuffers() {
const VkDeviceSize sz = (VkDeviceSize)kGmThreads * kGmStride * sizeof(float);
const VkMemoryPropertyFlags want = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
@@ -75,8 +70,6 @@ bool FrameGen::makeGmBuffers() {
bool FrameGen::makePipe(Pipe& p, int shaderId,
const std::vector<VkDescriptorType>&) {
// binding layout is derived per shader below in init(); here we only build
// the module + a generic layout supplied by caller via setLayout already set.
embedded::Blob b = embedded::blob((embedded::Shader)shaderId);
VkShaderModuleCreateInfo mi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
mi.codeSize = b.words * 4; mi.pCode = b.code;
@@ -101,7 +94,6 @@ void FrameGen::destroyPipe(Pipe& p) {
p = Pipe{};
}
// Build a descriptor-set layout from an explicit (binding, type) list.
static bool buildSetLayout(const DeviceDispatch* dd, VkDevice dev,
const std::vector<std::pair<uint32_t, VkDescriptorType>>& binds,
VkDescriptorSetLayout& out) {
@@ -123,12 +115,11 @@ bool FrameGen::init(const DeviceDispatch* dd, const InstanceDispatch* id,
si.addressModeU = si.addressModeV = si.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
VKOK(dd_->CreateSampler(device_, &si, nullptr, &linear_));
// descriptor pool sized generously for our per-frame sets.
VkDescriptorPoolSize sizes[] = {
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 256},
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 64},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 16}, // C1 LK-reduce SSBOs
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 16},
};
VkDescriptorPoolCreateInfo pci{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
pci.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
@@ -141,19 +132,15 @@ bool FrameGen::init(const DeviceDispatch* dd, const InstanceDispatch* id,
const auto U = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
const auto SB = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
// per-shader binding sets (match the GLSL layout(binding=...) declarations)
if (!buildSetLayout(dd_, dev, {B{32,S},B{48,W}}, pLuma_.setLayout)) return false;
if (!buildSetLayout(dd_, dev, {B{32,S},B{48,W}}, pDown_.setLayout)) return false;
if (!buildSetLayout(dd_, dev, {B{0,U},B{32,S},B{33,S},B{34,S},B{48,W}}, pFlow_.setLayout)) return false;
if (!buildSetLayout(dd_, dev, {B{0,U},B{32,S},B{33,S},B{34,S},B{48,W}}, pFlowM4_.setLayout)) return false;
// C1: expand sets gain a second UBO (binding 1 = GMUBO) for the global-motion add-back.
if (!buildSetLayout(dd_, dev, {B{0,U},B{1,U},B{32,S},B{48,W},B{49,W}}, pExpand_.setLayout)) return false;
if (!buildSetLayout(dd_, dev, {B{0,U},B{1,U},B{32,S},B{48,W},B{49,W}}, pExpandM4_.setLayout)) return false;
if (!buildSetLayout(dd_, dev, {B{0,U},B{32,S},B{33,S},B{34,S},B{35,S},B{48,W}}, pSynth_.setLayout)) return false;
// C1: LK-reduce (UBO, SSBO, prev, curr) and curr-luma stabilization prewarp (UBO, src, dst).
if (!buildSetLayout(dd_, dev, {B{1,U},B{16,SB},B{32,S},B{33,S}}, pGmReduce_.setLayout)) return false;
if (!buildSetLayout(dd_, dev, {B{1,U},B{32,S},B{48,W}}, pGmPrewarp_.setLayout)) return false;
// C2: flow-reg (UBO, u_in, f0_obs, luma, out).
if (!buildSetLayout(dd_, dev, {B{0,U},B{32,S},B{33,S},B{34,S},B{48,W}}, pFlowReg_.setLayout)) return false;
std::vector<VkDescriptorType> unused;
@@ -177,23 +164,19 @@ static VkExtent2D levelExtent(VkExtent2D e, int l) {
return { e.width >> l ? e.width >> l : 1u, e.height >> l ? e.height >> l : 1u };
}
bool FrameGen::onResize(VkExtent2D extent, VkFormat /*colorFormat*/, bool force) {
// force skips the same-extent early-out so a perf_preset change (which alters
// flowFinest_ and therefore the per-size flow-image resolutions) rebuilds them.
bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true;
// tear down previous size
for (auto& i : pyrA_) destroyImage(i); pyrA_.clear();
for (auto& i : pyrB_) destroyImage(i); pyrB_.clear();
for (auto& i : pyrAs_) destroyImage(i); pyrAs_.clear();
for (auto& i : flowLvl_) destroyImage(i); flowLvl_.clear();
destroyImage(flowExpA_); destroyImage(flowExpB_);
destroyImage(flowRegA_); destroyImage(flowRegB_); // C2
destroyImage(flowRegA_); destroyImage(flowRegB_);
extent_ = extent; ready_ = false;
const VkImageUsageFlags lumaUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT;
// flowLvl_ is cleared every frame (per-frame reset) and C2 copies the cleaned
// finest level back into it - both need TRANSFER_DST. The C2 ping-pong images
// are the copy SOURCE (TRANSFER_SRC).
const VkImageUsageFlags flowUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
const VkImageUsageFlags regUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
pyrA_.resize(kLevels); pyrB_.resize(kLevels); flowLvl_.resize(kLevels);
@@ -203,13 +186,11 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat /*colorFormat*/, bool force)
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
}
// C1: stabilized curr luma - only the levels the dense flow reads (finest..coarsest).
pyrAs_.resize(kLevels);
for (int l = flowFinest_; l < kLevels; ++l)
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
if (!makeImage(flowExpA_, extent, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
if (!makeImage(flowExpB_, extent, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
// C2: TV-L1 ping-pong scratch at the finest solved flow level (perf_preset-driven res).
if (!makeImage(flowRegA_, levelExtent(extent, flowFinest_), VK_FORMAT_R16G16B16A16_SFLOAT, regUsage)) return false;
if (!makeImage(flowRegB_, levelExtent(extent, flowFinest_), VK_FORMAT_R16G16B16A16_SFLOAT, regUsage)) return false;
ready_ = true;
@@ -229,13 +210,6 @@ void FrameGen::barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkI
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b);
}
// NOTE: descriptor-set allocation/update per record() and the exact per-level
// flow wiring are implemented in record_impl.inc for readability; the graph is:
// luma(curr)->pyrA[0], luma(prev)->pyrB[0]
// downsample pyrA/pyrB to kLevels
// coarse->fine flow (per level) into flowLvl
// expand flowLvl[0] -> flowExpA/flowExpB
// synth(prev,curr,flowExpA,flowExpB, alpha) -> out
void FrameGen::destroy() {
if (!device_) return;
@@ -245,11 +219,11 @@ void FrameGen::destroy() {
for (auto& i : pyrAs_) destroyImage(i); pyrAs_.clear();
for (auto& i : flowLvl_) destroyImage(i); flowLvl_.clear();
destroyImage(flowExpA_); destroyImage(flowExpB_);
destroyImage(flowRegA_); destroyImage(flowRegB_); // C2
destroyImage(flowRegA_); destroyImage(flowRegB_);
destroyPipe(pLuma_); destroyPipe(pDown_); destroyPipe(pFlow_); destroyPipe(pFlowM4_);
destroyPipe(pExpand_); destroyPipe(pExpandM4_); destroyPipe(pSynth_);
destroyPipe(pGmReduce_); destroyPipe(pGmPrewarp_);
destroyPipe(pFlowReg_); // C2
destroyPipe(pFlowReg_);
for (int s = 0; s < kGmSlots; ++s) {
if (gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]);
if (gmSsbo_[s]) dd_->DestroyBuffer(device_, gmSsbo_[s], nullptr);
@@ -262,8 +236,6 @@ void FrameGen::destroy() {
descPool_ = VK_NULL_HANDLE; linear_ = VK_NULL_HANDLE; device_ = VK_NULL_HANDLE; ready_ = false;
}
} // namespace winfg
}
// record() + its scratch helpers reopen namespace winfg themselves, so include
// this OUTSIDE the namespace block above (keeps FrameGen:: members attached).
#include "record_impl.inc"
+38 -79
View File
@@ -1,8 +1,3 @@
// win-fg - compute frame-generation engine.
// Owns the compute pipelines (our of3_* optical flow + wfg_synth) and the
// per-resolution intermediate images, and records the flow+synth graph that
// turns (prev, curr) into an interpolated frame. Written for win-fg; no code
// from bionic-fg / lsfg / GameScope.
#pragma once
#include "vk_dispatch.hpp"
#include "config.hpp"
@@ -14,70 +9,53 @@ class FrameGen {
public:
bool init(const DeviceDispatch* dd, const InstanceDispatch* id,
VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue);
// Applies a new config. Recomputes the active finest flow level from
// cfg_.perfPreset; if it changed while resources are live, safely rebuilds the
// affected per-size flow images (like a resize) and resets the flow predictor,
// so a perf_preset change is FULLY LIVE - no FG toggle needed. Defined in
// record_impl.inc (needs the scratch-state teardown). See flowFinestForPreset.
void configure(const Config& c);
// (Re)build per-resolution resources for a swapchain of the given size/format.
// force=true rebuilds even when the extent is unchanged (used by configure()
// when a perf_preset change alters the finest solved flow level).
bool onResize(VkExtent2D extent, VkFormat colorFormat, bool force = false);
// Record the whole flow+synth graph into cmd. prevView/currView are SAMPLED
// views of the two real frames; outView is a STORAGE view of the target
// image the generated frame is written into. alpha in (0,1).
// gmSlot selects which C1 global-motion SSBO to reduce into / read back; the
// caller MUST pass the ring-slot index of the FrameCtx it just fence-waited
// (that guarantees this slot's PREVIOUS reduce has completed and is safe to
// read on the host - see the decoupled-LK note in record_impl.inc).
void record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView,
VkImageView outView, float alpha, uint32_t gmSlot = 0);
void destroy();
bool valid() const { return device_ != VK_NULL_HANDLE && ready_; }
const Config& config() const { return cfg_; }
// public so the record_impl.inc free helpers can reference them
struct Img { VkImage image = VK_NULL_HANDLE; VkDeviceMemory mem = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE; VkExtent2D extent{}; VkFormat fmt{}; };
struct Pipe { VkPipeline pipeline = VK_NULL_HANDLE; VkPipelineLayout layout = VK_NULL_HANDLE;
VkDescriptorSetLayout setLayout = VK_NULL_HANDLE; VkShaderModule module = VK_NULL_HANDLE; };
// ── C1 GLOBAL-MOTION PRE-WARP constants (public so record_impl.inc's free
// helpers can size/index the SSBO pool). See of3_gm_reduce/of3_gm_prewarp. ──
static constexpr int kGmSlots = 3; // >= present ring size; one SSBO per in-flight ctx
static constexpr int kGmLevel = 3; // 1/8-res luma pyramid level for the LK estimate
static constexpr int kGmThreads = 512; // fixed reduce threads (8 groups * local_size_x 64)
static constexpr int kGmStride = 32; // floats/thread: 21 H + 6 b + coverage + resid + pad
// Finest pyramid level the dense flow is solved at (0 = full res). This is now
// RUNTIME-SELECTABLE via conf.toml perf_preset (0 Quality=1 / 1 Balanced=2 /
// 2 Performance=3). kFlowFinestDefault is the Balanced value (today's behaviour);
// the ACTIVE level lives in flowFinest_ and is read through flowFinest(). onResize
// sizes the stabilized-curr pyramid + C2 scratch from it, and record_impl.inc
// wires the flow/expand inputs to it - both must agree, so they all read
// flowFinest()/flowFinest_ (never a hard-coded 2). (Was a static constexpr = 2.)
static constexpr int kFlowFinestDefault = 2; // Balanced (perf_preset=1)
// Map perf_preset -> finest solved level. Out-of-range -> Balanced. A higher
// level = coarser (cheaper) flow = smaller base-FPS drop. configure() clamps the
// result against kLevels so at least two solved levels always remain.
static constexpr int kGmSlots = 3;
static constexpr int kGmLevel = 3;
static constexpr int kGmThreads = 512;
static constexpr int kGmStride = 32;
static constexpr int kFlowFinestDefault = 2;
static int flowFinestForPreset(int preset) {
switch (preset) {
case 0: return 1; // Quality ~1/2-res
case 2: return 3; // Performance ~1/8-res
case 1: default: return kFlowFinestDefault; // Balanced ~1/4-res (today)
case 0: return 1;
case 2: return 3;
case 1: default: return kFlowFinestDefault;
}
}
// The ACTIVE finest solved flow level (set by configure() from perf_preset).
int flowFinest() const { return flowFinest_; }
private:
uint32_t findMemType(uint32_t bits, VkMemoryPropertyFlags props) const;
bool makeImage(Img& out, VkExtent2D ext, VkFormat fmt, VkImageUsageFlags usage);
void destroyImage(Img& i);
bool makeGmBuffers(); // allocate the kGmSlots host-visible LK-reduce SSBOs
// Read back one reduce SSBO, solve the 6x6 inverse-compositional LK step, and
// update the running/applied global affine. Returns true if it engaged this
// frame. Implemented in record_impl.inc (has the ScratchState/UBO context).
bool makeGmBuffers();
bool updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent);
bool makePipe(Pipe& p, int shaderId,
const std::vector<VkDescriptorType>& bindings);
@@ -97,55 +75,36 @@ private:
Config cfg_;
VkExtent2D extent_{};
bool ready_ = false;
// ACTIVE finest solved flow level (perf_preset). Default = Balanced (today's 2)
// so an unconfigured engine and an unset conf.toml are byte-identical to before.
int flowFinest_ = kFlowFinestDefault;
// pipelines
Pipe pLuma_, pDown_, pFlow_, pFlowM4_, pExpand_, pExpandM4_, pSynth_;
// C1: LK normal-equation reduce + curr-luma stabilization pre-warp
Pipe pGmReduce_, pGmPrewarp_;
// C2: TV-L1 flow-regularization iteration (one dispatch per iteration)
Pipe pFlowReg_;
// per-resolution resources
// 7 levels (was 5): the coarsest levels set the max motion the solver can track.
// At 5 levels the reach was only ~±84px/frame at 720p, so fast camera motion
// (150-300px/frame at the periphery) saturated the search -> incoherent vectors
// -> oil-paint melt. Two more (tiny) coarse levels push the reach to ~±300px so
// large global motion is captured coherently instead of smeared. Near-zero cost:
// the extra levels are 40x22 and 20x11 images.
static const int kLevels = 7;
std::vector<Img> pyrA_, pyrB_; // luma pyramids for curr / prev
std::vector<Img> pyrAs_; // C1: STABILIZED curr luma (flow levels only)
std::vector<Img> flowLvl_; // per-level flow scratch
Img flowExpA_, flowExpB_; // fwd / bwd expanded flow (+conf)
// C2: TV-L1 ping-pong scratch at kFlowFinest res. flowLvl_[kFlowFinest] holds
// the fixed observation f0 (never written during the iterations); u ping-pongs
// between these two; the final iterate is copied back into flowLvl_[kFlowFinest]
// so of3_expand consumes the cleaned field with no binding change (⇒ skipping
// C2 leaves flowLvl_ byte-identical to pre-C2).
std::vector<Img> pyrA_, pyrB_;
std::vector<Img> pyrAs_;
std::vector<Img> flowLvl_;
Img flowExpA_, flowExpB_;
Img flowRegA_, flowRegB_;
// ── C1 global-motion state ────────────────────────────────────────────────
// Host-visible SSBOs the reduce shader writes per-thread partials into; the
// CPU sums + solves them. One per ring slot so a readback never races a live
// submission (the caller fence-waited its slot before calling record()).
VkBuffer gmSsbo_[kGmSlots] {};
VkDeviceMemory gmSsboMem_[kGmSlots]{};
void* gmSsboPtr_[kGmSlots]{};
bool gmBuffersReady_ = false;
// running affine params p1..p6 in centered-UV space (see GMUBO in config.hpp);
// identity = all zero. gmLinAt_ records the linearization params in effect when
// each slot's reduce was dispatched (the correct IC-update base for that slot).
double gmRun_[6] {};
double gmLinAt_[kGmSlots][6] {};
bool gmSlotValid_[kGmSlots]{};
bool gmHaveEst_ = false; // at least one good solve so far
int gmStableCount_ = 0; // consecutive good solves (auto-engage threshold)
bool gmEngaged_ = false; // is the affine being APPLIED this frame
float gmLastTransPx_ = 0.0f; // estimated global translation magnitude (full-res px), for logging
bool gmHaveEst_ = false;
int gmStableCount_ = 0;
bool gmEngaged_ = false;
float gmLastTransPx_ = 0.0f;
unsigned long long gmFrames_ = 0;
};
} // namespace winfg
}
-8
View File
@@ -1,5 +1,3 @@
// win-fg - logging. On Android goes to logcat (tag "win-fg") so device bring-up
// can trace the layer; elsewhere falls back to stderr.
#pragma once
#if defined(__ANDROID__)
#include <android/log.h>
@@ -11,10 +9,4 @@
#define WFG_LOGE(...) do { std::fprintf(stderr, "[win-fg][E] " __VA_ARGS__); std::fprintf(stderr, "\n"); } while(0)
#endif
// Runtime-gated granular debug trace. The gate is a RUNTIME bool (Config::debug),
// not a compile-time switch - a shipping .so carries the full trail but pays only
// a predicted-not-taken bool test per step when debug is off (no logcat write, no
// arg evaluation of the message). Same "win-fg" tag so the app captures it under
// its own UID. Used to step the present path so a freeze leaves an obvious last
// line at the stage that hung. Usage: WFG_LOGD(dbg, "P#%llu step ...", n);
#define WFG_LOGD(cond, ...) do { if (cond) WFG_LOGI(__VA_ARGS__); } while(0)
+32 -160
View File
@@ -1,57 +1,28 @@
// win-fg - FrameGen::record() and its lazy per-size descriptor/UBO setup.
// Included from framegen.cpp (has access to FrameGen privates). Written for
// win-fg; standard Vulkan compute wiring, no third-party code.
//
// ── C1 GLOBAL-MOTION PRE-WARP (this file wires it end to end) ─────────────────
// The dense SAD flow search melts on fast camera pans because the global motion
// saturates its window. C1 estimates the per-frame camera affine with a cheap
// inverse-compositional Lucas-Kanade solve (of3_gm_reduce accumulates the 6x6
// normal equations at 1/8 res → CPU 6x6 Cholesky here), then of3_gm_prewarp
// removes it from the curr luma pyramid BEFORE the search, so the search only
// sees small, coherent, object-only residual motion. of3_expand(_m4) composes
// the global affine back so wfg_synth is unchanged and the final warp is correct.
//
// DECOUPLED (stall-free) SCHEDULING: a true in-frame CPU solve would need a
// mid-frame GPU submit+readback stall - unacceptable on a GPU-bound title. So we
// read back the reduce SSBO the caller ALREADY fence-waited (its ring slot from a
// couple of presents ago) and run ONE Gauss-Newton step per frame, warm-started
// from the running estimate. Camera motion is temporally smooth, so a ~1-2 frame
// old affine is an excellent predictor; and because the SAME affine is removed
// (prewarp) and added back (expand), the result is EXACT for any affine we pick -
// an approximate/stale one only changes how much residual the search must absorb,
// never correctness. Identity affine ⇒ byte-identical to the pre-C1 pipeline, so
// the bail-to-identity safety path can never be worse than "no pre-warp".
namespace {
struct ScratchState {
// host-visible UBO buffers
VkBuffer synthUbo = VK_NULL_HANDLE; VkDeviceMemory synthUboMem = VK_NULL_HANDLE; void* synthUboPtr = nullptr;
std::vector<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> flowUboPtr;
VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr;
// C2: flow-regularization UBO (shared by all iterations; refreshed per frame).
VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr;
// C1: per-slot global-motion UBO (double-buffered by ring slot so a live GPU
// read is never overwritten by the next frame - see the header note).
VkBuffer gmUbo[winfg::FrameGen::kGmSlots]{};
VkDeviceMemory gmUboMem[winfg::FrameGen::kGmSlots]{};
void* gmUboPtr[winfg::FrameGen::kGmSlots]{};
// persistent descriptor sets
VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> sDownA, sDownB, sFlow;
VkDescriptorSet sExpand[winfg::FrameGen::kGmSlots]{}; // per-slot (binds gmUbo[slot])
// C2: three flow-reg sets covering every (u_in → u_out) pairing of the
// ping-pong. sFlowReg0: in=flowLvl_[F] (=f0), out=A. sFlowRegAB: in=A, out=B.
// sFlowRegBA: in=B, out=A. f0 (binding 33) = flowLvl_[F] in all three.
VkDescriptorSet sExpand[winfg::FrameGen::kGmSlots]{};
VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE;
VkDescriptorSet sSynth = VK_NULL_HANDLE;
// C1: per-slot reduce set + per-slot per-level prewarp sets
VkDescriptorSet sGmReduce[winfg::FrameGen::kGmSlots]{};
std::vector<VkDescriptorSet> sGmPrewarp[winfg::FrameGen::kGmSlots]; // sized kLevels; [flowFinest()..) used
std::vector<VkDescriptorSet> sGmPrewarp[winfg::FrameGen::kGmSlots];
VkExtent2D builtFor{0,0};
bool built = false;
bool flowInited = false; // flow images laid out once, then persist (temporal predictor)
bool flowInited = false;
};
ScratchState g_scratch; // one swapchain in flight in this first-draft engine
ScratchState g_scratch;
}
static bool makeUbo(const winfg::DeviceDispatch* dd, VkDevice dev,
@@ -77,7 +48,6 @@ static VkDescriptorSet allocSet(const winfg::DeviceDispatch* dd, VkDevice dev,
VkDescriptorSet s = VK_NULL_HANDLE; dd->AllocateDescriptorSets(dev, &ai, &s); return s;
}
// write helpers
static void wImg(const winfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding,
VkDescriptorType type, VkImageView view, VkSampler samp, VkImageLayout layout) {
VkDescriptorImageInfo ii{}; ii.imageView = view; ii.sampler = samp; ii.imageLayout = layout;
@@ -102,9 +72,6 @@ static void wSsbo(const winfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet
dd->UpdateDescriptorSets(dev, 1, &w, 0, nullptr);
}
// ── C1 CPU-side linear algebra (clean-room, textbook) ────────────────────────
// 6x6 symmetric positive-definite solve via Cholesky. Returns false if not PD
// (a bad/ill-conditioned frame → caller bails to identity). Damped by the caller.
static bool cholSolve6(double A[6][6], const double b[6], double x[6]) {
double L[6][6] = {{0}};
for (int i = 0; i < 6; ++i) {
@@ -112,7 +79,7 @@ static bool cholSolve6(double A[6][6], const double b[6], double x[6]) {
double s = A[i][j];
for (int k = 0; k < j; ++k) s -= L[i][k] * L[j][k];
if (i == j) {
if (s <= 1e-20) return false; // not positive-definite
if (s <= 1e-20) return false;
L[i][j] = std::sqrt(s);
} else {
L[i][j] = s / L[j][j];
@@ -124,7 +91,6 @@ static bool cholSolve6(double A[6][6], const double b[6], double x[6]) {
for (int i = 5; i >= 0; --i) { double s = y[i]; for (int k = i+1; k < 6; ++k) s -= L[k][i]*x[k]; x[i] = s / L[i][i]; }
return true;
}
// affine <-> params. params p=(p1,p2,p3,p4,p5,p6); M = I + [[p1,p3,p5],[p2,p4,p6]].
static void affFromParams(const double p[6], double M[3][3]) {
M[0][0]=1.0+p[0]; M[0][1]=p[2]; M[0][2]=p[4];
M[1][0]=p[1]; M[1][1]=1.0+p[3]; M[1][2]=p[5];
@@ -153,8 +119,6 @@ static void mulAff(const double A[3][3], const double B[3][3], double out[3][3])
namespace winfg {
// Lazily allocate per-size UBOs + descriptor sets and wire the fixed (internal-
// resource) bindings once. External views (prev/curr/out) are wired per frame.
static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool,
VkSampler samp, VkExtent2D ext,
@@ -168,11 +132,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo,
int kLevels, const Config& cfg);
// Tear down the lazily-built scratch (all UBO buffers + every descriptor set) so a
// live perf_preset rebuild neither leaks them nor exhausts the descriptor pool.
// The CALLER must have made the device idle first - no in-flight command buffer may
// still reference these. Resetting the pool frees every set FrameGen allocated (all
// sets come from this pool); the mapped UBO memory is unmapped + freed explicitly.
static void destroyScratch(const DeviceDispatch* dd, VkDevice dev, VkDescriptorPool pool) {
auto freeUbo = [&](VkBuffer& b, VkDeviceMemory& m, void*& p) {
if (m) dd->UnmapMemory(dev, m);
@@ -186,29 +145,20 @@ static void destroyScratch(const DeviceDispatch* dd, VkDevice dev, VkDescriptorP
freeUbo(S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
for (size_t i = 0; i < S.flowUbo.size(); ++i) freeUbo(S.flowUbo[i], S.flowUboMem[i], S.flowUboPtr[i]);
for (int s = 0; s < FrameGen::kGmSlots; ++s) freeUbo(S.gmUbo[s], S.gmUboMem[s], S.gmUboPtr[s]);
if (pool && dd->ResetDescriptorPool) dd->ResetDescriptorPool(dev, pool, 0); // reclaim all sets at once
S = ScratchState{}; // built=false -> next record() rebuilds via ensureScratch
if (pool && dd->ResetDescriptorPool) dd->ResetDescriptorPool(dev, pool, 0);
S = ScratchState{};
}
// ── perf_preset apply / live rebuild ─────────────────────────────────────────
// Sets the config, resolves the perf_preset -> finest-solved-level, and - when
// that level changed while resources are already live - safely rebuilds the
// affected per-size flow images (a resize) + scratch descriptor sets and resets
// the flow predictor. This makes a perf_preset change FULLY LIVE per-present (the
// conf.toml hot-reload path calls this), so no FG toggle / bg-fg cycle is needed.
void FrameGen::configure(const Config& c) {
cfg_ = c; cfg_.sanitize();
// Map preset -> finest level, clamped so at least TWO solved levels always
// remain (coarse->fine needs a range). With kLevels=7 the presets (1/2/3) never
// hit the clamp; the guard is defensive for future level/preset tuning.
int want = flowFinestForPreset(cfg_.perfPreset);
const int maxFinest = kLevels - 2; // keep >= 2 solved levels
const int maxFinest = kLevels - 2;
if (want > maxFinest) {
WFG_LOGE("perf-preset=%d wants kFlowFinest=%d but only %d pyramid levels exist "
"(need >=2 solved) - clamping to %d", cfg_.perfPreset, want, kLevels, maxFinest);
want = maxFinest;
}
if (want < 1) want = 1; // never solve full-res (level 0)
if (want < 1) want = 1;
const int prevFinest = flowFinest_;
flowFinest_ = want;
@@ -216,35 +166,27 @@ void FrameGen::configure(const Config& c) {
WFG_LOGI("perf-preset=%d -> kFlowFinest=%d (was %d) live-rebuild=%d ready=%d",
cfg_.perfPreset, flowFinest_, prevFinest, live ? 1 : 0, ready_ ? 1 : 0);
if (!live) return; // unchanged, or not yet built (initial configure before onResize)
if (!live) return;
// The per-size flow images (pyrAs_/flowReg*/flowLvl_ wiring) and the scratch
// descriptor sets were built for the OLD finest level. Rebuild them so record()
// never reads/writes mismatched-size images.
dd_->DeviceWaitIdle(device_); // no in-flight cmd buf may touch these
destroyScratch(dd_, device_, descPool_); // free old scratch (UBOs + all sets)
if (!onResize(extent_, VK_FORMAT_UNDEFINED, /*force=*/true))
dd_->DeviceWaitIdle(device_);
destroyScratch(dd_, device_, descPool_);
if (!onResize(extent_, VK_FORMAT_UNDEFINED, true))
WFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - FG disabled until next resize",
extent_.width, extent_.height);
// Reset the persistent flow predictor so stale, differently-scaled state never
// feeds the new resolution (avoids a melt/garbage frame on switch). The per-frame
// flow field (flowLvl_) is already cleared every frame; the cross-frame state is
// the C1 global-motion estimate + its per-slot reduce partials (dispatched against
// the old pyramid) - drop both back to identity.
for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0;
for (int s = 0; s < kGmSlots; ++s) { gmSlotValid_[s] = false; for (int i = 0; i < 6; ++i) gmLinAt_[s][i] = 0.0; }
gmHaveEst_ = false; gmEngaged_ = false; gmStableCount_ = 0; gmLastTransPx_ = 0.0f;
WFG_LOGI("perf-preset live rebuild DONE (kFlowFinest=%d, flow predictor reset)", flowFinest_);
}
// ── C1: read back one reduce SSBO, run one inverse-compositional LK step ──────
// Updates the running/applied global affine. Returns whether GM engages this frame.
bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
++gmFrames_;
if (!gmBuffersReady_ || cfg_.gmMode == 2 /*off*/) {
// off: keep identity applied; keep estimating cheaply is pointless when off.
if (!gmBuffersReady_ || cfg_.gmMode == 2 ) {
gmEngaged_ = false; gmStableCount_ = 0;
// still refresh the linearization record so a live switch to auto starts clean
for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0;
for (int i = 0; i < 6; ++i) gmLinAt_[gmSlot][i] = gmRun_[i];
gmLastTransPx_ = 0.0f;
@@ -260,31 +202,25 @@ bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
for (int k = 0; k < kGmStride; ++k) sums[k] += (double)row[k];
}
double coverage = sums[27];
// require a few percent of the level's pixels as inliers
double lvlpx = double((fullExtent.width >> kGmLevel) * (fullExtent.height >> kGmLevel));
double minCov = 0.03 * (lvlpx > 0 ? lvlpx : 1.0);
if (coverage > minCov && coverage > 64.0) {
double H[6][6]; int idx = 0;
for (int r = 0; r < 6; ++r) for (int c = r; c < 6; ++c) { H[r][c] = H[c][r] = sums[idx]; ++idx; }
double b[6]; for (int i = 0; i < 6; ++i) b[i] = sums[21 + i];
// Levenberg damping for conditioning (relative + tiny absolute).
for (int i = 0; i < 6; ++i) H[i][i] += 1e-3 * H[i][i] + 1e-9;
double dp[6];
if (cholSolve6(H, b, dp)) {
// reject wild steps (something non-affine / a scene cut)
bool bounded = std::fabs(dp[0]) < 0.5 && std::fabs(dp[1]) < 0.5 &&
std::fabs(dp[2]) < 0.5 && std::fabs(dp[3]) < 0.5 &&
std::fabs(dp[4]) < 0.25 && std::fabs(dp[5]) < 0.25;
if (bounded) {
// IC update: M_new = M_lin ∘ W(dp)^-1 (compose onto the SLOT's
// linearization base, which is what this reduce linearized around).
double Mlin[3][3], Md[3][3], Mdi[3][3], Mnew[3][3];
affFromParams(gmLinAt_[gmSlot], Mlin);
affFromParams(dp, Md);
if (invAff(Md, Mdi)) {
mulAff(Mlin, Mdi, Mnew);
double pnew[6]; paramsFromAff(Mnew, pnew);
// final sanity clamp on the composed estimate
bool sane = std::fabs(pnew[0]) < 0.6 && std::fabs(pnew[1]) < 0.6 &&
std::fabs(pnew[2]) < 0.6 && std::fabs(pnew[3]) < 0.6 &&
std::fabs(pnew[4]) < 0.5 && std::fabs(pnew[5]) < 0.5;
@@ -297,17 +233,14 @@ bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
if (good) ++gmStableCount_; else gmStableCount_ = 0;
// engage policy
switch (cfg_.gmMode) {
case 1: gmEngaged_ = gmHaveEst_; break; // on
case 2: gmEngaged_ = false; break; // off (unreachable; handled above)
default: gmEngaged_ = (gmStableCount_ >= 3); break; // auto: 3 consecutive good solves
case 1: gmEngaged_ = gmHaveEst_; break;
case 2: gmEngaged_ = false; break;
default: gmEngaged_ = (gmStableCount_ >= 3); break;
}
// record the linearization base for the reduce we are about to dispatch into
// this slot this frame (i.e. the current running estimate).
for (int i = 0; i < 6; ++i) gmLinAt_[gmSlot][i] = gmRun_[i];
gmSlotValid_[gmSlot] = true; // this frame's reduce will (re)write it
gmSlotValid_[gmSlot] = true;
gmLastTransPx_ = (float)std::sqrt(
(gmRun_[4]*fullExtent.width) * (gmRun_[4]*fullExtent.width) +
@@ -330,9 +263,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_);
}
// ── C1: solve the global-motion affine (reads the SSBO the caller fence-waited) ──
bool gmEngaged = updateGlobalMotion(gmSlot, extent_);
// Build this slot's GMUBO from the running / applied affine.
if (g_scratch.gmUboPtr[gmSlot]) {
GMUBO g{};
g.lin[0]=(float)gmRun_[0]; g.lin[1]=(float)gmRun_[1]; g.lin[2]=(float)gmRun_[2]; g.lin[3]=(float)gmRun_[3];
@@ -340,10 +271,9 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
if (gmEngaged) {
g.app[0]=(float)gmRun_[0]; g.app[1]=(float)gmRun_[1]; g.app[2]=(float)gmRun_[2]; g.app[3]=(float)gmRun_[3];
g.appT[0]=(float)gmRun_[4]; g.appT[1]=(float)gmRun_[5];
} // else app/appT stay 0 -> identity -> prewarp/expand are pre-C1 no-ops
}
std::memcpy(g_scratch.gmUboPtr[gmSlot], &g, sizeof(g));
}
// Log engage state + estimated global translation periodically (tag win-fg).
{
static int lastEng = -1;
if (gmEngaged != (lastEng == 1) || (gmFrames_ % 300ull) == 0) {
@@ -353,12 +283,10 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
}
}
// update UBOs for this frame
SynthUBO su{cfg_.flowScale, alpha, cfg_.beta, cfg_.lambda, cfg_.epsilon, cfg_.photoScale, 0, 0,
cfg_.hudX0, cfg_.hudY0, cfg_.hudX1, cfg_.hudY1};
if (g_scratch.synthUboPtr) std::memcpy(g_scratch.synthUboPtr, &su, sizeof(su));
// wire per-frame external views
wImg(dd_, device_, g_scratch.sLumaCurr, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, g_scratch.sLumaPrev, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, prevView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, g_scratch.sSynth, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, prevView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
@@ -372,23 +300,13 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
};
auto bar = [&](FrameGen::Img& i){ barrier(cmd, i.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL); };
// Internal images are created UNDEFINED and fully recomputed every frame, so
// discard-transition them all to GENERAL up front (all descriptors use GENERAL
// for these). This also fixes the first-frame layout (storage writes require
// GENERAL, not UNDEFINED).
for (auto& i : pyrA_) barrier(cmd, i.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
for (auto& i : pyrB_) barrier(cmd, i.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
for (int l = flowFinest_; l < kLevels; ++l) barrier(cmd, pyrAs_[l].image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowExpA_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowExpB_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
// C2: ping-pong scratch to GENERAL (storage writes require it; contents discarded).
barrier(cmd, flowRegA_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowRegB_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
// Reset the flow field to zero every frame. The coarsest level uses it as its
// search predictor; carrying it across frames lets a spurious vector feed
// forward until it diverges and melts the image (the bg/fg pause was resetting
// it - that's why artifacts vanished on resume). Fresh zero every frame =
// stable, standard pyramid flow, no feedback loop.
{
VkClearColorValue zero{};
VkImageSubresourceRange rng{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
@@ -406,20 +324,14 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
}
}
// 1) luma of curr/prev at full res
disp(pLuma_, g_scratch.sLumaCurr, levelExtent(extent_, 0));
disp(pLuma_, g_scratch.sLumaPrev, levelExtent(extent_, 0));
bar(pyrA_[0]); bar(pyrB_[0]);
// 2) downsample pyramids
for (int l = 1; l < kLevels; ++l) {
disp(pDown_, g_scratch.sDownA[l - 1], levelExtent(extent_, l));
disp(pDown_, g_scratch.sDownB[l - 1], levelExtent(extent_, l));
bar(pyrA_[l]); bar(pyrB_[l]);
}
// 2b) C1: LK normal-equation reduce (fixed grid, 1/8-res) → this slot's SSBO.
// Reads raw prev/curr luma at kGmLevel; writes per-thread partials. A
// compute→host barrier makes the write visible to the CPU readback that
// happens when this slot comes round again (~1-2 frames later).
if (gmBuffersReady_ && g_scratch.sGmReduce[gmSlot]) {
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &g_scratch.sGmReduce[gmSlot], 0, nullptr);
@@ -429,28 +341,15 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
0, 1, &mb, 0, nullptr, 0, nullptr);
}
// 2c) C1: pre-warp curr luma pyramid by the applied affine → stabilized pyramid
// (identity affine ⇒ exact copy, so the flow below is unchanged when
// disengaged). The dense flow reads pyrAs from here on.
for (int l = flowFinest_; l < kLevels; ++l) {
disp(pGmPrewarp_, g_scratch.sGmPrewarp[gmSlot][l], levelExtent(extent_, l));
bar(pyrAs_[l]);
}
// 3) coarse->fine flow (only down to flowFinest_ - reduced res for perf; the
// finest level is perf_preset-selectable). Curr input is now the STABILIZED
// pyramid (pyrAs), wired in ensureScratch.
for (int l = kLevels - 1; l >= flowFinest_; --l) {
disp(flowP, g_scratch.sFlow[l], levelExtent(extent_, l));
bar(flowLvl_[l]);
}
// 3b) ── C2: TV-L1 flow regularization on the finest residual field ──────────
// Run frIters semi-implicit TV-L1 denoising iterations on flowLvl_[flowFinest_]
// (the object-only residual left by C1). flowLvl_[F] is the fixed data term f0
// (read, never written here); u ping-pongs A<->B; the final iterate is copied
// back into flowLvl_[F] so of3_expand consumes the cleaned field unchanged.
// Disengaged (frMode==off or frIters==0) ⇒ flowLvl_[F] untouched ⇒ byte-identical
// to pre-C2. Identity/zero iterations is therefore never worse than "no reg".
const bool frEngaged = (cfg_.frMode != 2) && (cfg_.frIters > 0);
if (frEngaged) {
const int F = flowFinest_;
@@ -471,9 +370,6 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
bar(*outImg);
last = outImg;
}
// Copy the cleaned finest flow back into flowLvl_[F] (GENERAL->GENERAL).
// Barrier: C2's f0 reads (SHADER_READ of flowLvl_[F]) and the last iterate
// write must complete before the transfer overwrites/reads.
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
mb.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
@@ -491,7 +387,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 1, &mb2, 0, nullptr, 0, nullptr);
}
{ // periodic C2 status (tag win-fg), mirrors the C1 log cadence
{
static int lastFr = -1;
int fe = frEngaged ? 1 : 0;
if (fe != lastFr || (gmFrames_ % 300ull) == 0) {
@@ -501,14 +397,11 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
}
}
// 4) expand finest solved flow -> fwd/bwd (+conf), + C1 global-motion add-back.
disp(expandP, g_scratch.sExpand[gmSlot], levelExtent(extent_, 0));
bar(flowExpA_); bar(flowExpB_);
// 5) synthesise interpolated frame
disp(pSynth_, g_scratch.sSynth, levelExtent(extent_, 0));
}
// ---- lazy scratch builder ----
static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool,
VkSampler samp, VkExtent2D ext,
@@ -528,7 +421,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
makeUbo(dd, dev, mp, sizeof(SynthUBO), S.synthUbo, S.synthUboMem, S.synthUboPtr);
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.expandUbo, S.expandUboMem, S.expandUboPtr);
if (S.expandUboPtr) { FlowUBO u{cfg.flowScale, 0, 0.6f, 1.6f}; std::memcpy(S.expandUboPtr, &u, sizeof(u)); }
// C2: flow-reg UBO (params refreshed each frame in record() for hot-reload).
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
@@ -536,19 +428,16 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
}
// C1: per-slot GMUBO (initialised to identity)
for (int s = 0; s < FrameGen::kGmSlots; ++s) {
makeUbo(dd, dev, mp, sizeof(GMUBO), S.gmUbo[s], S.gmUboMem[s], S.gmUboPtr[s]);
if (S.gmUboPtr[s]) { GMUBO g{}; std::memcpy(S.gmUboPtr[s], &g, sizeof(g)); }
}
// luma sets (external src wired per frame; dst is pyramid[0])
S.sLumaCurr = allocSet(dd, dev, pool, pLuma.setLayout);
S.sLumaPrev = allocSet(dd, dev, pool, pLuma.setLayout);
wImg(dd, dev, S.sLumaCurr, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, pyrA[0].view, VK_NULL_HANDLE, GEN);
wImg(dd, dev, S.sLumaPrev, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, pyrB[0].view, VK_NULL_HANDLE, GEN);
// downsample sets (fixed)
S.sDownA.resize(kLevels - 1); S.sDownB.resize(kLevels - 1);
for (int l = 1; l < kLevels; ++l) {
S.sDownA[l-1] = allocSet(dd, dev, pool, pDown.setLayout);
@@ -559,10 +448,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
wImg(dd, dev, S.sDownB[l-1], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, pyrB[l].view, VK_NULL_HANDLE, GEN);
}
// flow sets (fixed): predictor = coarser flow level, or self at coarsest.
// C1: the CURR input (binding 33) is the STABILIZED pyramid pyrAs for the
// solved flow levels; prev stays raw. Below kFlowFinest the level is never
// dispatched, so leaving those at raw curr is harmless.
S.sFlow.resize(kLevels);
for (int l = 0; l < kLevels; ++l) {
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
@@ -575,19 +460,17 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
}
// C1: reduce sets (one per slot) - prev/curr raw luma at kGmLevel + SSBO + GMUBO.
if (gmSsbo) {
for (int s = 0; s < FrameGen::kGmSlots; ++s) {
if (!gmSsbo[s]) continue;
S.sGmReduce[s] = allocSet(dd, dev, pool, pGmReduce.setLayout);
wUbo (dd, dev, S.sGmReduce[s], 1, S.gmUbo[s], sizeof(GMUBO));
wSsbo(dd, dev, S.sGmReduce[s], 16, gmSsbo[s], VK_WHOLE_SIZE);
wImg (dd, dev, S.sGmReduce[s], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[FrameGen::kGmLevel].view, samp, GEN); // prev = template
wImg (dd, dev, S.sGmReduce[s], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrA[FrameGen::kGmLevel].view, samp, GEN); // curr = image
wImg (dd, dev, S.sGmReduce[s], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[FrameGen::kGmLevel].view, samp, GEN);
wImg (dd, dev, S.sGmReduce[s], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrA[FrameGen::kGmLevel].view, samp, GEN);
}
}
// C1: prewarp sets (one per slot, per solved flow level) - raw curr in, stabilized out.
for (int s = 0; s < FrameGen::kGmSlots; ++s) {
S.sGmPrewarp[s].assign(kLevels, VK_NULL_HANDLE);
for (int l = fg->flowFinest(); l < kLevels; ++l) {
@@ -598,7 +481,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
}
}
// expand sets (one per slot): flow inputs fixed; binding 1 = that slot's GMUBO.
for (int s = 0; s < FrameGen::kGmSlots; ++s) {
S.sExpand[s] = allocSet(dd, dev, pool, pExpand.setLayout);
wUbo(dd, dev, S.sExpand[s], 0, S.expandUbo, sizeof(FlowUBO));
@@ -608,9 +490,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
wImg(dd, dev, S.sExpand[s], 49, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, expB.view, VK_NULL_HANDLE, GEN);
}
// C2: flow-reg sets. F = kFlowFinest. f0 (binding 33) = flowLvl_[F] in all; luma
// (binding 34) = prev luma at F (pyrB) for the edge-aware weight. u_in (32) and
// u_out (48) alternate to realize the ping-pong (see ScratchState comment).
{
const int F = fg->flowFinest();
S.sFlowReg0 = allocSet(dd, dev, pool, pFlowReg.setLayout);
@@ -619,26 +498,19 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
VkDescriptorSet all3[3] = {S.sFlowReg0, S.sFlowRegAB, S.sFlowRegBA};
for (VkDescriptorSet s : all3) {
wUbo(dd, dev, s, 0, S.flowRegUbo, sizeof(FlowRegUBO));
wImg(dd, dev, s, 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[F].view, samp, GEN); // f0
wImg(dd, dev, s, 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[F].view, samp, GEN); // luma
wImg(dd, dev, s, 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[F].view, samp, GEN);
wImg(dd, dev, s, 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[F].view, samp, GEN);
}
// iter0: in=flowLvl_[F] (=f0), out=A
wImg(dd, dev, S.sFlowReg0, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[F].view, samp, GEN);
wImg(dd, dev, S.sFlowReg0, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowRegA.view, VK_NULL_HANDLE, GEN);
// odd iters: in=A, out=B
wImg(dd, dev, S.sFlowRegAB, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowRegA.view, samp, GEN);
wImg(dd, dev, S.sFlowRegAB, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowRegB.view, VK_NULL_HANDLE, GEN);
// even iters (>0): in=B, out=A
wImg(dd, dev, S.sFlowRegBA, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowRegB.view, samp, GEN);
wImg(dd, dev, S.sFlowRegBA, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowRegA.view, VK_NULL_HANDLE, GEN);
}
// synth set: external prev/curr/out wired per frame; flow inputs fixed
S.sSynth = allocSet(dd, dev, pool, pSynth.setLayout);
wUbo(dd, dev, S.sSynth, 0, S.synthUbo, sizeof(SynthUBO));
// GENERAL (not SR): these internal flow images stay in GENERAL across the whole
// record() (written as storage by expand, sampled here) - see the discard
// transition at the top of record().
wImg(dd, dev, S.sSynth, 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, expA.view, samp, GEN);
wImg(dd, dev, S.sSynth, 35, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, expB.view, samp, GEN);
@@ -646,4 +518,4 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
return true;
}
} // namespace winfg
}
@@ -1,7 +1,3 @@
// win-fg - minimal Vulkan layer dispatch tables.
// Structure follows the public Khronos loader/layer interface and the
// renderdoc "Vulkan layer guide" skeleton (learning references, Apache-2.0 /
// CC-BY). No code from bionic-fg / lsfg / GameScope.
#pragma once
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
@@ -9,53 +5,35 @@
namespace winfg {
// The loader sets the first pointer-sized word of a dispatchable handle to the
// dispatch table pointer; layers key their own maps on that value so that all
// handles sharing a chain resolve to the same table.
static inline void* dispatch_key(void* handle) { return *reinterpret_cast<void**>(handle); }
// Instance-level functions we call from the layer.
struct InstanceDispatch {
PFN_vkGetInstanceProcAddr GetInstanceProcAddr = nullptr;
PFN_vkDestroyInstance DestroyInstance = nullptr;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties = nullptr;
PFN_vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties = nullptr;
// Device-context logging (affected-device fingerprint). Properties2 is core 1.1;
// may be null on a 1.0 instance - always null-check before calling.
PFN_vkGetPhysicalDeviceProperties GetPhysicalDeviceProperties = nullptr;
PFN_vkGetPhysicalDeviceProperties2 GetPhysicalDeviceProperties2 = nullptr;
// Surface caps - used to clamp the extra-image-headroom request to the surface's
// maxImageCount so the bump never exceeds what the driver can grant.
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr;
};
// Device-level functions we call. Populated by walking vkGetDeviceProcAddr on
// the next layer down at device-create time.
struct DeviceDispatch {
PFN_vkGetDeviceProcAddr GetDeviceProcAddr = nullptr;
PFN_vkDestroyDevice DestroyDevice = nullptr;
PFN_vkGetDeviceQueue GetDeviceQueue = nullptr;
PFN_vkQueueSubmit QueueSubmit = nullptr;
// Synchronization2 submit path (core 1.3 + KHR alias). DXVK may use either the
// legacy QueueSubmit or QueueSubmit2/2KHR; both are hooked for the guest-submit
// diagnostic. May be null if the device did not enable them - always null-check.
PFN_vkQueueSubmit2 QueueSubmit2 = nullptr;
PFN_vkQueueSubmit2KHR QueueSubmit2KHR = nullptr;
PFN_vkQueueWaitIdle QueueWaitIdle = nullptr;
PFN_vkDeviceWaitIdle DeviceWaitIdle = nullptr;
// swapchain / present
PFN_vkCreateSwapchainKHR CreateSwapchainKHR = nullptr;
PFN_vkDestroySwapchainKHR DestroySwapchainKHR = nullptr;
PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR = nullptr;
PFN_vkAcquireNextImageKHR AcquireNextImageKHR = nullptr;
// Alternate acquire entry (VK_KHR_swapchain 1.1+ / device-group). DXVK may use
// either AcquireNextImageKHR or AcquireNextImage2KHR - both hooked for the
// guest-acquire diagnostic. May be null - always null-check.
PFN_vkAcquireNextImage2KHR AcquireNextImage2KHR = nullptr;
PFN_vkQueuePresentKHR QueuePresentKHR = nullptr;
// resources
PFN_vkCreateImage CreateImage = nullptr;
PFN_vkDestroyImage DestroyImage = nullptr;
PFN_vkCreateImageView CreateImageView = nullptr;
@@ -73,7 +51,6 @@ struct DeviceDispatch {
PFN_vkCreateSampler CreateSampler = nullptr;
PFN_vkDestroySampler DestroySampler = nullptr;
// pipeline / descriptors
PFN_vkCreateShaderModule CreateShaderModule = nullptr;
PFN_vkDestroyShaderModule DestroyShaderModule = nullptr;
PFN_vkCreateDescriptorSetLayout CreateDescriptorSetLayout = nullptr;
@@ -84,15 +61,10 @@ struct DeviceDispatch {
PFN_vkDestroyPipeline DestroyPipeline = nullptr;
PFN_vkCreateDescriptorPool CreateDescriptorPool = nullptr;
PFN_vkDestroyDescriptorPool DestroyDescriptorPool = nullptr;
// Frees every set in the pool at once - used by FrameGen::configure() to reclaim
// the old scratch descriptor sets when a perf_preset change forces a live rebuild
// (otherwise repeated preset switches would exhaust the pool). May be null in
// theory; the rebuild path null-checks before calling.
PFN_vkResetDescriptorPool ResetDescriptorPool = nullptr;
PFN_vkAllocateDescriptorSets AllocateDescriptorSets = nullptr;
PFN_vkUpdateDescriptorSets UpdateDescriptorSets = nullptr;
// command recording
PFN_vkCreateCommandPool CreateCommandPool = nullptr;
PFN_vkDestroyCommandPool DestroyCommandPool = nullptr;
PFN_vkAllocateCommandBuffers AllocateCommandBuffers = nullptr;
@@ -104,7 +76,7 @@ struct DeviceDispatch {
PFN_vkCmdDispatch CmdDispatch = nullptr;
PFN_vkCmdPipelineBarrier CmdPipelineBarrier = nullptr;
PFN_vkCmdCopyImage CmdCopyImage = nullptr;
PFN_vkCmdCopyImageToBuffer CmdCopyImageToBuffer = nullptr; // capture readback
PFN_vkCmdCopyImageToBuffer CmdCopyImageToBuffer = nullptr;
PFN_vkCmdBlitImage CmdBlitImage = nullptr;
PFN_vkCmdClearColorImage CmdClearColorImage = nullptr;
PFN_vkCreateFence CreateFence = nullptr;
@@ -120,4 +92,4 @@ static inline void load(PFN& slot, PFN_vkGetDeviceProcAddr gdpa, VkDevice dev, c
slot = reinterpret_cast<PFN>(gdpa(dev, name));
}
} // namespace winfg
}
@@ -1,4 +1,3 @@
// See winfg_engine.h.
#include "winfg_engine.h"
#include "winfg_vkd.h"
#include "log.hpp"
@@ -8,11 +7,6 @@
namespace winfg {
namespace {
// 2x: the guest layer synthesises at 0.35, not 0.5 - biased towards prev to
// cut the double-exposure ghost on HUD/text ("iterative bring-up knob" in
// layer.cpp). Kept for parity, since that is the tuning that was proven.
// 3x/4x: evenly spaced; never exercised by the guest layer, so this is the
// new ground native opens up and the first thing to judge by eye.
float alphaFor(uint32_t k, uint32_t n) {
if (n <= 1) return 0.35f;
return (float)(k + 1) / (float)(n + 1);
@@ -30,7 +24,7 @@ VkImageMemoryBarrier bar(VkImage img, VkImageLayout from, VkImageLayout to,
return b;
}
} // namespace
}
Engine::Engine() = default;
Engine::~Engine() { destroyRing(); fg_.destroy(); }
@@ -65,8 +59,8 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) {
if (unavailable_ || w == 0 || h == 0 || fmt == VK_FORMAT_UNDEFINED) return false;
if (builtW_ == w && builtH_ == h && builtFmt_ == fmt && fg_.valid()) return true;
// onResize rebuilds the pyramids/scratch; our own input ring follows it.
if (!fg_.onResize(VkExtent2D{w, h}, fmt, /*force=*/false)) {
if (!fg_.onResize(VkExtent2D{w, h}, fmt, false)) {
WFG_LOGE("native: onResize %ux%u failed; frame generation unavailable", w, h);
unavailable_ = true;
return false;
@@ -83,21 +77,17 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) {
}
uint32_t Engine::plan(uint32_t capacity) const {
if (!valid() || history_ < 2) return 0; // need prev AND curr
if (!valid() || history_ < 2) return 0;
const uint32_t want = (uint32_t)std::max(cfg_.multiplier - 1, 0);
return std::min({want, capacity, kMaxGenerations});
}
void Engine::process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h,
uint32_t /*generations*/) {
uint32_t ) {
if (!valid()) return;
// Rotate: the slot we are about to overwrite is the OLD prev; after the
// copy it is the new curr and the other slot is prev.
curr_ = 1 - curr_;
Slot& dst = ring_[curr_];
// source is GENERAL (composite render pass leaves it there); the slot may
// be in any layout from last use - UNDEFINED is legal as "discard".
VkImageMemoryBarrier pre[2] = {
bar(source, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT),
@@ -115,8 +105,6 @@ void Engine::process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h
dd_.CmdCopyImage(cmd, source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
dst.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
// source back to GENERAL for the real-frame copy that follows; the new
// curr becomes SHADER_READ_ONLY, which is what the chain samples it as.
VkImageMemoryBarrier post[2] = {
bar(source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT),
@@ -138,17 +126,11 @@ void Engine::generateInto(VkCommandBuffer cmd, uint32_t generation, uint32_t cou
const Slot& curr = ring_[curr_];
if (!prev.valid || !curr.valid) return;
// The chain writes the output through a STORAGE descriptor in GENERAL.
// The composite ring already keeps its targets in GENERAL; make the
// prior contents' writes visible and take ownership for the compute write.
VkImageMemoryBarrier toWrite = bar(targetImage, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT);
dd_.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &toWrite);
// gmSlot indexes the C1 global-motion SSBO read back on the CPU next
// frame; kGmSlots (3) >= our frames in flight (2), so rotating per source
// frame keeps a slot from being read while its reduce is still in flight.
fg_.record(cmd, prev.view, curr.view, targetView, alphaFor(generation, count), gmSlot_);
if (generation + 1 == count) gmSlot_ = (gmSlot_ + 1) % (uint32_t)FrameGen::kGmSlots;
@@ -157,7 +139,6 @@ void Engine::generateInto(VkCommandBuffer cmd, uint32_t generation, uint32_t cou
void Engine::reset() { history_ = 0; frames_ = 0; }
// ---- input ring --------------------------------------------------------------
uint32_t Engine::memType(uint32_t bits, VkMemoryPropertyFlags props) const {
for (uint32_t i = 0; i < memProps_.memoryTypeCount; i++)
@@ -201,4 +182,4 @@ void Engine::destroyRing() {
history_ = 0;
}
} // namespace winfg
}
+4 -37
View File
@@ -1,28 +1,4 @@
#pragma once
// ============================================================================
// winfg_engine - win-fg (Bannerlator's own frame generation) running inside
// the compositor, behind the same contract the LSFG engine uses:
//
// prepare(w, h, format) build/rebuild the chain for this size
// plan(capacity) how many frames to generate this time
// process(cmd, source, w, h, gens) take frame N in (becomes "curr")
// generateInto(cmd, k, n, ...) synthesise generated frame k of n
//
// Why this exists: as a guest-side Vulkan layer, win-fg's generated frames
// had to cross Wine -> DRI3 -> our X server -> the compositor, where the
// per-window latest-wins overwrite dropped them before they were ever
// presented - the HUD counted 2x, the panel got 1x. Here the chain runs in the
// compositor's own command stream and its frames are presented directly, on
// the same multi-present path that is device-proven for LSFG Native.
//
// Unlike LSFG this needs nothing from the user: the ten shaders are ours
// (MIT, see LICENSE.win-fg / NOTICE_FIDELITYFX_OPTICALFLOW.md) and embedded.
//
// The chain (framegen.cpp) is used unmodified. Its inputs are two sampled
// rgba8 views (prev, curr) and its output a GENERAL storage view; the guest
// layer transitions curr to SHADER_READ_ONLY before record() and the output
// UNDEFINED -> GENERAL, so we do exactly the same around the same call.
// ============================================================================
#include <cstdint>
#include <vulkan/vulkan.h>
#include "framegen.hpp"
@@ -32,8 +8,6 @@ struct VkTable;
namespace winfg {
// Hard ceiling on generated frames per source frame (2x..4x -> 1..3), matching
// the LSFG engine and the drawer's buttons.
constexpr uint32_t kMaxGenerations = 3;
class Engine {
@@ -48,22 +22,15 @@ public:
bool valid() const { return fg_.valid() && !unavailable_; }
bool unavailable() const { return unavailable_; }
// model 3/4, perf preset 0..2, flow scale - the same knobs the drawer
// already exposes for win-fg; they map straight onto winfg::Config.
void configure(uint32_t multiplier, int model, int perfPreset, float flowScale);
bool prepare(uint32_t width, uint32_t height, VkFormat format);
// 0 until there is a previous frame to interpolate from.
uint32_t plan(uint32_t capacity) const;
// Copy the composited frame into the input ring as "curr" (the previous
// one becomes "prev"). `source` must be in GENERAL.
void process(VkCommandBuffer cmd, VkImage source, uint32_t width, uint32_t height,
uint32_t generations);
// Synthesise generated frame `generation` of `count` into the storage view.
// The target must be in GENERAL (the composite ring keeps it there).
void generateInto(VkCommandBuffer cmd, uint32_t generation, uint32_t count,
VkImage targetImage, VkImageView targetView,
uint32_t width, uint32_t height);
@@ -91,12 +58,12 @@ private:
bool unavailable_ = false;
Slot ring_[2];
int curr_ = 0; // index of "curr" in ring_; prev is 1 - curr_
uint32_t history_ = 0; // frames copied so far (need 2)
uint32_t gmSlot_ = 0; // rotates through FrameGen::kGmSlots
int curr_ = 0;
uint32_t history_ = 0;
uint32_t gmSlot_ = 0;
uint32_t builtW_ = 0, builtH_ = 0;
VkFormat builtFmt_ = VK_FORMAT_UNDEFINED;
uint64_t frames_ = 0;
};
} // namespace winfg
}
@@ -1,4 +1,3 @@
// See winfg_vkd.h.
#include "winfg_vkd.h"
#include "../VulkanRendererContext.h"
#include <android/log.h>
@@ -1,19 +1,4 @@
#pragma once
// ============================================================================
// winfg_vkd - fill win-fg's own dispatch tables from the renderer's VkTable.
//
// win-fg's chain (framegen.cpp / record_impl.inc) was written as a Vulkan
// LAYER and calls through winfg::DeviceDispatch / InstanceDispatch. Inside the
// compositor there is no layer chain to resolve those from, so they are filled
// from the renderer's per-context table instead - the same bridge lsfg_vkd
// provides for the LSFG chain, for the same reason: an adrenotools driver
// shares no global symbols with the system loader.
//
// Only the entry points the chain actually calls are filled (36 device-level
// plus GetPhysicalDeviceMemoryProperties); everything else in the structs
// stays null and is never reached. winfgVkdInit reports a false if any of
// those failed to resolve, so a null is never called mid-frame.
// ============================================================================
#include "vk_dispatch.hpp"
struct VkTable;
bool winfgVkdInit(const VkTable& table, winfg::DeviceDispatch& dd, winfg::InstanceDispatch& id);