diff --git a/crates/engine/src/auto_matte.rs b/crates/engine/src/auto_matte.rs new file mode 100644 index 0000000000000000000000000000000000000000..89125ee848ebf62fac29fae083c93fa2b3927f19 --- /dev/null +++ b/crates/engine/src/auto_matte.rs @@ -0,0 +1,30 @@ +//! `AutoMatte` (`#49`) and diverging Fusion `MagicMask` (`#7`) GPU matting system. +//! +//! Architecture: +//! - **Unified prompt extraction** ([`prompts`]): parses both Fission `AutoMatte` click points / +//! modes and real Fusion `MagicMask` `MagicMaskStrokes` (`BezierSpline` keyframes or inline) + +//! matte controls (`MatteBlur`, `MatteContractExpand`, `Invert`, `OutputMode`, `ShowMask`). +//! - **Stage 1 & 2** ([`cache`]): checks [`AutoMatteCache`] (in-memory + optional disk PNG sequence +//! from SAM 2 + MatAnyone 2 / VideoMaMa), exposes a zero-hardcoded-dependency native +//! [`AutoMatteRunner`] worker launcher, and falls back to a real-time WebGPU-safe multi-seed +//! Oklab color-affinity segmentation + joint-bilateral edge refinement pass when no cached neural +//! matte is available yet. +//! - **Stage 3** ([`gpu`]): real-time GPU port of Clover's `polish_alpha` (floor `0.045`, ceiling +//! `0.985`, toe gamma `1.35` below `0.15`) and `hair_safe_decontaminate` (3-scale normalized- +//! convolution Gaussian foreground color extrapolation at `sigma = 28, 12, 4` scaled by +//! `proxy_scale`). + +mod cache; +mod gpu; +mod prompts; +#[cfg(test)] +mod tests; + +pub use cache::{AutoMatteCache, CachedMatteFrame}; +#[cfg(not(target_arch = "wasm32"))] +pub use cache::{AutoMatteJobRequest, AutoMatteJobState, AutoMatteRunner, AutoMatteWorkerConfig}; +pub(crate) use gpu::AutoMattePipelines; +pub use prompts::{ + AutoMatteParams, OutputMode, PromptMode, PromptPoint, QualityTier, extract_auto_matte_params, + extract_magic_mask_params, parse_magic_mask_strokes_table, +}; diff --git a/crates/engine/src/auto_matte/cache.rs b/crates/engine/src/auto_matte/cache.rs new file mode 100644 index 0000000000000000000000000000000000000000..8ce78381fa4bed16328e0506643dc2da5b7809b6 --- /dev/null +++ b/crates/engine/src/auto_matte/cache.rs @@ -0,0 +1,471 @@ +//! Pluggable per-frame neural matte cache (`AutoMatteCache`) and optional native +//! external SAM 2 + MatAnyone 2 / VideoMaMa worker launcher (`AutoMatteRunner`). + +use std::collections::{HashMap, VecDeque}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +#[cfg(not(target_arch = "wasm32"))] +use super::prompts::{PromptMode, PromptPoint, QualityTier}; +#[cfg(not(target_arch = "wasm32"))] +use std::path::{Path, PathBuf}; + +const DEFAULT_MAX_CACHED_MATTE_FRAMES: usize = 256; + +/// Single-channel linear alpha matte frame (`[0.0, 1.0]`, top-down row-major). +#[derive(Clone, Debug)] +pub struct CachedMatteFrame { + pub size: [u32; 2], + /// Row-major top-down alpha values in `[0.0, 1.0]` (`len == size[0] * size[1]`). + pub alpha: Vec, + /// Deterministic content hash used to key GPU textures and `NodeCache` entries. + pub content_hash: u64, +} + +impl CachedMatteFrame { + /// Constructs a cached matte frame from linear `f32` alpha values in `[0.0, 1.0]`. + pub fn from_alpha_f32(size: [u32; 2], mut alpha: Vec) -> Self { + let expected = (size[0] as usize).saturating_mul(size[1] as usize); + alpha.resize(expected, 0.0); + for v in &mut alpha { + *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + } + let content_hash = hash_alpha(size, &alpha); + Self { size, alpha, content_hash } + } + + /// Constructs a cached matte frame from 8-bit grayscale alpha bytes (`0..=255`). + pub fn from_alpha_u8(size: [u32; 2], bytes: &[u8]) -> Self { + let expected = (size[0] as usize).saturating_mul(size[1] as usize); + let mut alpha = Vec::with_capacity(expected); + for &b in bytes.iter().take(expected) { + alpha.push(f32::from(b) / 255.0); + } + Self::from_alpha_f32(size, alpha) + } + + /// Decodes a PNG (grayscale 8/16-bit or RGBA) matte buffer into a [`CachedMatteFrame`]. + pub fn from_png_bytes(bytes: &[u8]) -> Result { + let dyn_img = image::load_from_memory(bytes) + .map_err(|e| format!("failed to decode AutoMatte PNG: {e}"))?; + let w = dyn_img.width(); + let h = dyn_img.height(); + if w == 0 || h == 0 { + return Err("AutoMatte PNG has zero dimensions".into()); + } + let alpha = match dyn_img { + image::DynamicImage::ImageLuma8(g) => { + g.as_raw().iter().map(|&v| f32::from(v) / 255.0).collect() + } + image::DynamicImage::ImageLuma16(g) => { + g.as_raw().iter().map(|&v| f32::from(v) / 65535.0).collect() + } + image::DynamicImage::ImageRgba8(rgba) => { + let raw = rgba.as_raw(); + let all_opaque = raw.chunks_exact(4).all(|px| px[3] == 255); + if all_opaque { + raw.chunks_exact(4).map(|px| f32::from(px[0]) / 255.0).collect() + } else { + raw.chunks_exact(4).map(|px| f32::from(px[3]) / 255.0).collect() + } + } + other => { + let g = other.to_luma16(); + g.as_raw().iter().map(|&v| f32::from(v) / 65535.0).collect() + } + }; + Ok(Self::from_alpha_f32([w, h], alpha)) + } + + #[cfg(not(target_arch = "wasm32"))] + pub fn from_png_file(path: &Path) -> Result { + let bytes = std::fs::read(path) + .map_err(|e| format!("failed to read AutoMatte PNG {}: {e}", path.display()))?; + Self::from_png_bytes(&bytes) + } +} + +fn hash_alpha(size: [u32; 2], alpha: &[f32]) -> u64 { + let mut h = DefaultHasher::new(); + "automate-matte-v1".hash(&mut h); + size.hash(&mut h); + alpha.len().hash(&mut h); + // Stride-sample large frames + include endpoints so hashing stays sub-millisecond at 4K + let stride = (alpha.len() / 2048).max(1); + for (i, &v) in alpha.iter().enumerate().step_by(stride) { + i.hash(&mut h); + v.to_bits().hash(&mut h); + } + if let Some(&last) = alpha.last() { + last.to_bits().hash(&mut h); + } + h.finish() +} + +#[derive(Default)] +struct CacheInner { + frames: HashMap<(String, i64), Arc>, + order: VecDeque<(String, i64)>, + max_entries: usize, +} + +impl CacheInner { + fn new(max_entries: usize) -> Self { + Self { + frames: HashMap::new(), + order: VecDeque::new(), + max_entries: max_entries.max(1), + } + } + + fn insert(&mut self, key: (String, i64), frame: Arc) { + if self.frames.contains_key(&key) { + self.order.retain(|k| k != &key); + } + self.frames.insert(key.clone(), frame); + self.order.push_back(key); + while self.frames.len() > self.max_entries { + if let Some(oldest) = self.order.pop_front() { + self.frames.remove(&oldest); + } else { + break; + } + } + } +} + +/// Thread-safe per-frame cached neural alpha store shared between `Engine` and optional +/// background neural workers (SAM 2 + MatAnyone 2 / VideoMaMa). +#[derive(Clone)] +pub struct AutoMatteCache { + inner: Arc>, + generation: Arc, +} + +impl Default for AutoMatteCache { + fn default() -> Self { + Self::new() + } +} + +impl AutoMatteCache { + pub fn new() -> Self { + Self::with_capacity(DEFAULT_MAX_CACHED_MATTE_FRAMES) + } + + pub fn with_capacity(max_entries: usize) -> Self { + Self { + inner: Arc::new(Mutex::new(CacheInner::new(max_entries))), + generation: Arc::new(AtomicU64::new(0)), + } + } + + /// Monotonic counter incremented whenever frames are inserted or evicted explicitly. + pub fn generation(&self) -> u64 { + self.generation.load(Ordering::Relaxed) + } + + pub fn insert_frame(&self, node_name: &str, frame: i64, matte: CachedMatteFrame) { + if let Ok(mut guard) = self.inner.lock() { + guard.insert((node_name.to_owned(), frame), Arc::new(matte)); + self.generation.fetch_add(1, Ordering::Relaxed); + } + } + + pub fn insert_alpha_f32(&self, node_name: &str, frame: i64, size: [u32; 2], alpha: Vec) { + self.insert_frame(node_name, frame, CachedMatteFrame::from_alpha_f32(size, alpha)); + } + + pub fn insert_alpha_u8(&self, node_name: &str, frame: i64, size: [u32; 2], alpha: &[u8]) { + self.insert_frame(node_name, frame, CachedMatteFrame::from_alpha_u8(size, alpha)); + } + + pub fn get_frame(&self, node_name: &str, frame: i64) -> Option> { + let guard = self.inner.lock().ok()?; + guard + .frames + .get(&(node_name.to_owned(), frame)) + .or_else(|| guard.frames.get(&("*".to_owned(), frame))) + .cloned() + } + + /// Looks up `(node_name, frame)` in memory first, then optionally loads a per-frame PNG + /// sequence file from `cache_dir` on native targets. + pub fn get_or_load_frame( + &self, + node_name: &str, + frame: i64, + cache_dir: Option<&str>, + ) -> Option> { + if let Some(hit) = self.get_frame(node_name, frame) { + return Some(hit); + } + #[cfg(not(target_arch = "wasm32"))] + if let Some(dir) = cache_dir { + if let Some(path) = resolve_cached_png_path(Path::new(dir), node_name, frame) { + if let Ok(decoded) = CachedMatteFrame::from_png_file(&path) { + let arc = Arc::new(decoded); + if let Ok(mut guard) = self.inner.lock() { + guard.insert((node_name.to_owned(), frame), arc.clone()); + } + return Some(arc); + } + } + } + #[cfg(target_arch = "wasm32")] + let _ = cache_dir; + None + } + + pub fn remove_node(&self, node_name: &str) { + if let Ok(mut guard) = self.inner.lock() { + guard.frames.retain(|(n, _), _| n != node_name); + guard.order.retain(|(n, _)| n != node_name); + self.generation.fetch_add(1, Ordering::Relaxed); + } + } + + pub fn clear(&self) { + if let Ok(mut guard) = self.inner.lock() { + guard.frames.clear(); + guard.order.clear(); + self.generation.fetch_add(1, Ordering::Relaxed); + } + } + + pub fn len(&self) -> usize { + self.inner.lock().map_or(0, |g| g.frames.len()) + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn resolve_cached_png_path(dir: &Path, node_name: &str, frame: i64) -> Option { + if !dir.exists() { + return None; + } + let f = frame.max(0); + let candidates = [ + dir.join(format!("{f:04}.png")), + dir.join(format!("{f:05}.png")), + dir.join(format!("{f:06}.png")), + dir.join(format!("{f}.png")), + dir.join(format!("frame_{f:04}.png")), + dir.join(format!("alpha_{f:04}.png")), + dir.join(format!("{node_name}_{f:04}.png")), + dir.join(node_name).join(format!("{f:04}.png")), + ]; + candidates.into_iter().find(|p| p.is_file()) +} + +// ----------------------------------------------------------------------------- +// Native external neural matte runner (SAM 2 + MatAnyone 2 / VideoMaMa) +// ----------------------------------------------------------------------------- + +/// Configuration for invoking an external Python neural matting worker on native platforms. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug)] +pub struct AutoMatteWorkerConfig { + /// Python executable (e.g. `~/dev/magic-matte/.venv/bin/python` or `python3`). + pub python_bin: PathBuf, + /// Worker script path accepting `--input`, `--output-dir`, `--quality`, `--mode`, + /// `--start-frame`, `--end-frame`, and `--prompts`. + pub worker_script: PathBuf, + /// Directory where per-frame alpha PNGs (`0000.png`, ...) are written. + pub output_dir: PathBuf, +} + +/// Job request submitted to [`AutoMatteRunner`]. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug)] +pub struct AutoMatteJobRequest { + pub node_name: String, + pub input_path: PathBuf, + pub frame_range: [i64; 2], + pub quality_tier: QualityTier, + pub prompt_mode: PromptMode, + pub prompts: Vec, +} + +/// Lifecycle state of an asynchronous neural matting job. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AutoMatteJobState { + Running, + Completed { frames_loaded: usize }, + Failed(String), +} + +/// Optional native helper to launch an external SAM 2 + MatAnyone 2 / VideoMaMa Python worker +/// asynchronously or synchronously and populate an [`AutoMatteCache`]. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone)] +pub struct AutoMatteRunner { + config: AutoMatteWorkerConfig, + cache: AutoMatteCache, + states: Arc>>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl AutoMatteRunner { + pub fn new(config: AutoMatteWorkerConfig, cache: AutoMatteCache) -> Self { + Self { + config, + cache, + states: Arc::new(Mutex::new(HashMap::new())), + } + } + + /// Probes environment variables (`FISSION_AUTOMATTE_PYTHON`, `FISSION_AUTOMATTE_SCRIPT`) + /// without hardcoding any mandatory external dependency. Returns `None` if not configured. + pub fn from_env(output_dir: PathBuf, cache: AutoMatteCache) -> Option { + let python_bin = std::env::var_os("FISSION_AUTOMATTE_PYTHON").map(PathBuf::from)?; + let worker_script = std::env::var_os("FISSION_AUTOMATTE_SCRIPT").map(PathBuf::from)?; + if !python_bin.is_file() || !worker_script.is_file() { + return None; + } + Some(Self::new( + AutoMatteWorkerConfig { python_bin, worker_script, output_dir }, + cache, + )) + } + + pub fn config(&self) -> &AutoMatteWorkerConfig { + &self.config + } + + pub fn cache(&self) -> &AutoMatteCache { + &self.cache + } + + pub fn job_state(&self, node_name: &str) -> Option { + self.states.lock().ok()?.get(node_name).cloned() + } + + /// Runs the external worker synchronously and ingests produced PNG mattes into `self.cache`. + pub fn run_blocking(&self, req: &AutoMatteJobRequest) -> Result { + run_worker_once(&self.config, &self.cache, req) + } + + /// Spawns a background OS thread running the configured external worker and populating + /// `self.cache` upon completion. + pub fn spawn_job(&self, req: AutoMatteJobRequest) -> Result<(), String> { + if !self.config.python_bin.is_file() { + return Err(format!( + "AutoMatte Python binary not found: {}", + self.config.python_bin.display() + )); + } + if !self.config.worker_script.is_file() { + return Err(format!( + "AutoMatte worker script not found: {}", + self.config.worker_script.display() + )); + } + let node_name = req.node_name.clone(); + if let Ok(mut guard) = self.states.lock() { + guard.insert(node_name.clone(), AutoMatteJobState::Running); + } + let config = self.config.clone(); + let cache = self.cache.clone(); + let states = self.states.clone(); + std::thread::Builder::new() + .name(format!("automate-worker-{node_name}")) + .spawn(move || { + let outcome = match run_worker_once(&config, &cache, &req) { + Ok(frames_loaded) => AutoMatteJobState::Completed { frames_loaded }, + Err(msg) => AutoMatteJobState::Failed(msg), + }; + if let Ok(mut guard) = states.lock() { + guard.insert(node_name, outcome); + } + }) + .map_err(|e| format!("failed to spawn AutoMatte worker thread: {e}"))?; + Ok(()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn serialize_prompts_json(prompts: &[PromptPoint]) -> String { + let mut s = String::from("["); + for (i, pt) in prompts.iter().enumerate() { + if i > 0 { + s.push(','); + } + let label = if pt.positive { 1 } else { 0 }; + s.push_str(&format!( + "{{\"x\":{:.6},\"y\":{:.6},\"label\":{label}}}", + pt.x, pt.y + )); + } + s.push(']'); + s +} + +#[cfg(not(target_arch = "wasm32"))] +fn run_worker_once( + config: &AutoMatteWorkerConfig, + cache: &AutoMatteCache, + req: &AutoMatteJobRequest, +) -> Result { + std::fs::create_dir_all(&config.output_dir) + .map_err(|e| format!("failed to create AutoMatte output dir: {e}"))?; + + let quality_str = match req.quality_tier { + QualityTier::FastInteractive => "fast", + QualityTier::MatAnyone2 => "matanyone2", + QualityTier::HeroHair => "videomama", + }; + let mode_str = match req.prompt_mode { + PromptMode::ClickPoints => "points", + PromptMode::AutoPerson => "person", + PromptMode::Object => "object", + }; + let prompts_json = serialize_prompts_json(&req.prompts); + + let output = std::process::Command::new(&config.python_bin) + .arg(&config.worker_script) + .arg("--input") + .arg(&req.input_path) + .arg("--output-dir") + .arg(&config.output_dir) + .arg("--quality") + .arg(quality_str) + .arg("--mode") + .arg(mode_str) + .arg("--start-frame") + .arg(req.frame_range[0].to_string()) + .arg("--end-frame") + .arg(req.frame_range[1].to_string()) + .arg("--prompts") + .arg(&prompts_json) + .output() + .map_err(|e| format!("failed to execute AutoMatte worker: {e}"))?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!( + "AutoMatte worker exited with {}: {}", + output.status, + stderr.trim() + )); + } + + let mut loaded = 0usize; + let start = req.frame_range[0]; + let end = req.frame_range[1].max(start); + for frame in start..=end { + if let Some(path) = resolve_cached_png_path(&config.output_dir, &req.node_name, frame) { + if let Ok(decoded) = CachedMatteFrame::from_png_file(&path) { + cache.insert_frame(&req.node_name, frame, decoded); + loaded += 1; + } + } + } + Ok(loaded) +} diff --git a/crates/engine/src/auto_matte/gpu.rs b/crates/engine/src/auto_matte/gpu.rs new file mode 100644 index 0000000000000000000000000000000000000000..8f7f0394bfa96e1d99d15618ade04d0552682545 --- /dev/null +++ b/crates/engine/src/auto_matte/gpu.rs @@ -0,0 +1,687 @@ +//! WebGPU-safe compute pipeline registry and multi-pass dispatcher for `AutoMatte` & `MagicMask`. +//! +//! All input textures use `TextureSampleType::Float { filterable: false }` (read via `textureLoad`), +//! output storage textures are `WriteOnly`, and uniform buffers use a growable 512-slot chunk ring +//! reset via `Engine::reset_uniform_cursors()` and trimmed via `Engine::trim_uniform_chunks()`. + +use super::cache::CachedMatteFrame; +use super::prompts::{AutoMatteParams, MAX_GPU_SEEDS, OutputMode, QualityTier}; +use crate::cache::{CachedTexture, NodeCache}; +use bytemuck::{Pod, Zeroable}; +use model::BitDepth; +use std::collections::{HashMap, VecDeque}; +use std::num::NonZeroU64; + +const AUTO_MATTE_WGSL: &str = include_str!("../shaders/auto_matte.wgsl"); +const AM_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; +const MAX_UPLOADED_MATTE_CACHE: usize = 8; + +/// Exact 640-byte uniform block matching `AutoMatteUniform` in `auto_matte.wgsl`. +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct AutoMatteUniform { + p: [[f32; 4]; 8], + seeds: [[f32; 4]; MAX_GPU_SEEDS], +} + +impl Default for AutoMatteUniform { + fn default() -> Self { + Self { + p: [[0.0; 4]; 8], + seeds: [[0.0; 4]; MAX_GPU_SEEDS], + } + } +} + +#[derive(Clone, Copy)] +enum AutoMatteOp { + SeedSegment, + BilateralRefine, + PolishAlpha, + MorphoH, + MorphoV, + GaussBlurH, + GaussBlurV, + DecontamInit, + DecontamMergeScale, + CompositeOutput, +} + +fn build_auto_matte_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { + let storage_fmt = match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + let mut src = AUTO_MATTE_WGSL.to_owned(); + if storage_fmt != "rgba8unorm" { + src = src.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + ); + } + if hdr_float { + src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); + } + src +} + +fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + } +} + +struct AutoMatteFormatPipelines { + bgl: wgpu::BindGroupLayout, + seed_segment: wgpu::ComputePipeline, + bilateral_refine: wgpu::ComputePipeline, + polish_alpha: wgpu::ComputePipeline, + morpho_h: wgpu::ComputePipeline, + morpho_v: wgpu::ComputePipeline, + gauss_blur_h: wgpu::ComputePipeline, + gauss_blur_v: wgpu::ComputePipeline, + decontam_init: wgpu::ComputePipeline, + decontam_merge_scale: wgpu::ComputePipeline, + composite_output: wgpu::ComputePipeline, +} + +impl AutoMatteFormatPipelines { + fn pipeline(&self, op: AutoMatteOp) -> &wgpu::ComputePipeline { + match op { + AutoMatteOp::SeedSegment => &self.seed_segment, + AutoMatteOp::BilateralRefine => &self.bilateral_refine, + AutoMatteOp::PolishAlpha => &self.polish_alpha, + AutoMatteOp::MorphoH => &self.morpho_h, + AutoMatteOp::MorphoV => &self.morpho_v, + AutoMatteOp::GaussBlurH => &self.gauss_blur_h, + AutoMatteOp::GaussBlurV => &self.gauss_blur_v, + AutoMatteOp::DecontamInit => &self.decontam_init, + AutoMatteOp::DecontamMergeScale => &self.decontam_merge_scale, + AutoMatteOp::CompositeOutput => &self.composite_output, + } + } +} + +struct UploadedMatteTex { + _texture: wgpu::Texture, + view: wgpu::TextureView, +} + +/// GPU pipeline registry and growable uniform chunk ring for `AutoMatte` and `MagicMask`. +pub(crate) struct AutoMattePipelines { + uniform_stride: u32, + uniform_chunks: Vec, + uniform_cursor: u32, + by_format: HashMap<(wgpu::TextureFormat, bool), AutoMatteFormatPipelines>, + uploaded_mattes: HashMap, + uploaded_order: VecDeque, +} + +impl AutoMattePipelines { + pub(crate) fn new(device: &wgpu::Device) -> Self { + let uniform_size = std::mem::size_of::() as u32; + let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); + let uniform_stride = uniform_size.div_ceil(min_align) * min_align; + Self { + uniform_stride, + uniform_chunks: Vec::new(), + uniform_cursor: 0, + by_format: HashMap::new(), + uploaded_mattes: HashMap::new(), + uploaded_order: VecDeque::new(), + } + } + + pub(crate) fn reset_uniform_cursor(&mut self) { + self.uniform_cursor = 0; + } + + pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) { + self.uniform_cursor = 0; + if self.uniform_chunks.len() > max_chunks { + self.uniform_chunks.truncate(max_chunks); + } + self.uploaded_mattes.clear(); + self.uploaded_order.clear(); + } + + fn alloc_uniform_slot( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + params: &AutoMatteUniform, + ) -> (usize, u32) { + let slot_global = self.uniform_cursor; + let chunk_idx = (slot_global / AM_UNIFORM_SLOTS_PER_CHUNK) as usize; + let slot_in_chunk = slot_global % AM_UNIFORM_SLOTS_PER_CHUNK; + while chunk_idx >= self.uniform_chunks.len() { + let size = u64::from(AM_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("auto-matte-params-ring"), + size, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.uniform_chunks.push(buf); + } + let offset = slot_in_chunk * self.uniform_stride; + queue.write_buffer( + &self.uniform_chunks[chunk_idx], + u64::from(offset), + bytemuck::bytes_of(params), + ); + self.uniform_cursor = slot_global + 1; + (chunk_idx, offset) + } + + fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { + if self.by_format.contains_key(&(format, hdr_float)) { + return; + } + let u_size = std::mem::size_of::() as u64; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("auto-matte-bgl"), + entries: &[ + unfilterable_tex_entry(0), + unfilterable_tex_entry(1), + unfilterable_tex_entry(2), + unfilterable_tex_entry(3), + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(u_size), + }, + count: None, + }, + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("auto-matte-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("auto-matte-wgsl"), + source: wgpu::ShaderSource::Wgsl(build_auto_matte_wgsl(format, hdr_float).into()), + }); + let mk = |entry: &str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&pl), + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + self.by_format.insert( + (format, hdr_float), + AutoMatteFormatPipelines { + bgl, + seed_segment: mk("seed_segment_op"), + bilateral_refine: mk("bilateral_refine_op"), + polish_alpha: mk("polish_alpha_op"), + morpho_h: mk("morpho_h_op"), + morpho_v: mk("morpho_v_op"), + gauss_blur_h: mk("gauss_blur_h_op"), + gauss_blur_v: mk("gauss_blur_v_op"), + decontam_init: mk("decontam_init_op"), + decontam_merge_scale: mk("decontam_merge_scale_op"), + composite_output: mk("composite_output_op"), + }, + ); + } + + #[allow(clippy::too_many_arguments)] + fn dispatch( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + op: AutoMatteOp, + inputs: [&wgpu::TextureView; 4], + dst: &CachedTexture, + params: &AutoMatteUniform, + ) { + let hdr_float = dst.depth.is_float(); + self.ensure_format(device, dst.format, hdr_float); + let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); + let fp = &self.by_format[&(dst.format, hdr_float)]; + let u_size = NonZeroU64::new(std::mem::size_of::() as u64); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("auto-matte-bg"), + layout: &fp.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(inputs[0]) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(inputs[1]) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(inputs[2]) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(inputs[3]) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniform_chunks[chunk_idx], + offset: 0, + size: u_size, + }), + }, + ], + }); + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("auto-matte-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(fp.pipeline(op)); + pass.set_bind_group(0, &bg, &[offset]); + pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); + } + + fn upload_cached_matte( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + matte: &CachedMatteFrame, + ) -> wgpu::TextureView { + if let Some(existing) = self.uploaded_mattes.get(&matte.content_hash) { + return existing.view.clone(); + } + let w = matte.size[0].max(1); + let h = matte.size[1].max(1); + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("auto-matte-cached-r32f"), + size: wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + tex.as_image_copy(), + bytemuck::cast_slice(&matte.alpha), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(w * 4), + rows_per_image: Some(h), + }, + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); + let view_clone = view.clone(); + self.uploaded_mattes.insert( + matte.content_hash, + UploadedMatteTex { _texture: tex, view }, + ); + self.uploaded_order.push_back(matte.content_hash); + while self.uploaded_mattes.len() > MAX_UPLOADED_MATTE_CACHE { + if let Some(old) = self.uploaded_order.pop_front() { + self.uploaded_mattes.remove(&old); + } else { + break; + } + } + view_clone + } + + /// Executes the full AutoMatte / MagicMask GPU pipeline: + /// 1. Stage 1/2: uses `cached_matte` if present, otherwise runs GPU multi-seed segmentation + + /// joint-bilateral edge-aware refinement. + /// 2. Stage 3A: Clover's `polish_alpha` (floor, ceiling, toe gamma, invert) + optional + /// `MatteContractExpand` and `MatteBlur`. + /// 3. Stage 3B: Clover's 3-scale `hair_safe_decontaminate` (`sigma = 28, 12, 4` scaled by + /// `proxy_scale`) + final output mode & `EffectMask` / `Blend` composite. + #[allow(clippy::too_many_arguments)] + pub(crate) fn execute( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + node_cache: &NodeCache, + dummy_view: &wgpu::TextureView, + src: &CachedTexture, + mask_view: &wgpu::TextureView, + has_mask: bool, + mask_inv: bool, + mbm: bool, + skip: [f32; 4], + dst: &CachedTexture, + params: &AutoMatteParams, + cached_matte: Option<&CachedMatteFrame>, + proxy_scale: u32, + ) { + let alloc_f16 = || { + node_cache.acquire_texture_dod_fmt( + device, + src.size, + [0, 0], + src.size, + BitDepth::Float16, + wgpu::TextureFormat::Rgba16Float, + 0, + ) + }; + + // --------------------------------------------------------------------- + // Stage 1 & 2: Acquire raw alpha matte (cached neural OR GPU fallback) + // --------------------------------------------------------------------- + let raw_matte_view: wgpu::TextureView; + let _gpu_fallback_keepalive: Option; + if let Some(cm) = cached_matte { + raw_matte_view = self.upload_cached_matte(device, queue, cm); + _gpu_fallback_keepalive = None; + } else { + let seeds = params.effective_gpu_seeds(); + let seg_tex = alloc_f16(); + let mut u_seg = AutoMatteUniform::default(); + let mut neg_count = 0u32; + let count = seeds.len().min(MAX_GPU_SEEDS); + for (i, pt) in seeds.iter().take(count).enumerate() { + let [u, v] = pt.to_gpu_uv(); + let label = if pt.positive { 1.0 } else { neg_count += 1; -1.0 }; + u_seg.seeds[i] = [u, v, label, pt.weight.max(0.01)]; + } + let aspect = (src.size[0] as f32) / (src.size[1].max(1) as f32); + u_seg.p[0] = [ + count as f32, + neg_count as f32, + 0.12, // perceptual Oklab color sigma + 0.85, // spatial sigma for positive seeds + ]; + u_seg.p[1] = [ + if neg_count == 0 { 1.25 } else { 0.85 }, + 1.0, // enable automatic border background seeds when no negative clicks exist + aspect, + params.quality_tier as u32 as f32, + ]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::SeedSegment, + [&src.view, dummy_view, dummy_view, dummy_view], + &seg_tex, + &u_seg, + ); + + // Joint-bilateral edge-aware alpha refinement guided by original RGB + let refined = match params.quality_tier { + QualityTier::FastInteractive => { + let out = alloc_f16(); + let mut ub = AutoMatteUniform::default(); + ub.p[0] = [3.0, 3.0, 0.08, 1.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::BilateralRefine, + [&src.view, &seg_tex.view, dummy_view, dummy_view], + &out, + &ub, + ); + out + } + QualityTier::MatAnyone2 => { + let mid = alloc_f16(); + let out = alloc_f16(); + let mut u1 = AutoMatteUniform::default(); + u1.p[0] = [3.0, 4.5, 0.075, 2.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::BilateralRefine, + [&src.view, &seg_tex.view, dummy_view, dummy_view], + &mid, + &u1, + ); + let mut u2 = AutoMatteUniform::default(); + u2.p[0] = [3.0, 2.5, 0.06, 1.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::BilateralRefine, + [&src.view, &mid.view, dummy_view, dummy_view], + &out, + &u2, + ); + out + } + QualityTier::HeroHair => { + let mid = alloc_f16(); + let out = alloc_f16(); + let mut u1 = AutoMatteUniform::default(); + u1.p[0] = [4.0, 5.0, 0.06, 2.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::BilateralRefine, + [&src.view, &seg_tex.view, dummy_view, dummy_view], + &mid, + &u1, + ); + let mut u2 = AutoMatteUniform::default(); + u2.p[0] = [3.0, 2.2, 0.045, 1.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::BilateralRefine, + [&src.view, &mid.view, dummy_view, dummy_view], + &out, + &u2, + ); + out + } + }; + raw_matte_view = (*refined.view).clone(); + _gpu_fallback_keepalive = Some(refined); + } + + // --------------------------------------------------------------------- + // Stage 3A: Clover's exact `polish_alpha` + optional morpho & blur + // --------------------------------------------------------------------- + let mut matte_tex = alloc_f16(); + let mut u_pol = AutoMatteUniform::default(); + u_pol.p[0] = [ + params.alpha_floor, + params.alpha_ceiling, + params.toe_gamma, + if params.invert { 1.0 } else { 0.0 }, + ]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::PolishAlpha, + [&raw_matte_view, dummy_view, dummy_view, dummy_view], + &matte_tex, + &u_pol, + ); + + let scale = proxy_scale.max(1) as f32; + if params.matte_contract_expand.abs() > 1e-4 { + let radius_px = (params.matte_contract_expand * (src.size[0] as f32 / 128.0).max(1.0)) + .clamp(-64.0, 64.0); + let tmp = alloc_f16(); + let out = alloc_f16(); + let mut um = AutoMatteUniform::default(); + um.p[0][0] = radius_px; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::MorphoH, + [&matte_tex.view, dummy_view, dummy_view, dummy_view], + &tmp, + &um, + ); + self.dispatch( + device, + queue, + enc, + AutoMatteOp::MorphoV, + [&tmp.view, dummy_view, dummy_view, dummy_view], + &out, + &um, + ); + matte_tex = out; + } + + if params.matte_blur > 1e-3 { + let sigma = (params.matte_blur / scale).clamp(0.1, 64.0); + let max_r = (sigma * 2.5).ceil().clamp(1.0, 76.0); + let tmp = alloc_f16(); + let out = alloc_f16(); + let mut ub = AutoMatteUniform::default(); + ub.p[0] = [sigma, max_r, 0.0, 0.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::GaussBlurH, + [&matte_tex.view, dummy_view, dummy_view, dummy_view], + &tmp, + &ub, + ); + self.dispatch( + device, + queue, + enc, + AutoMatteOp::GaussBlurV, + [&tmp.view, dummy_view, dummy_view, dummy_view], + &out, + &ub, + ); + matte_tex = out; + } + + // --------------------------------------------------------------------- + // Stage 3B: Clover's 3-scale `hair_safe_decontaminate` (sigma = 28, 12, 4) + // --------------------------------------------------------------------- + let need_decontam = params.decontaminate > 1e-4 + && params.output_mode == OutputMode::PremultipliedCutout; + let extrap_keepalive: Option = if need_decontam { + let solid_tex = alloc_f16(); + let u_zero = AutoMatteUniform::default(); + self.dispatch( + device, + queue, + enc, + AutoMatteOp::DecontamInit, + [&src.view, &matte_tex.view, dummy_view, dummy_view], + &solid_tex, + &u_zero, + ); + + let blur_tmp = alloc_f16(); + let blur_out = alloc_f16(); + let extrap_a = alloc_f16(); + let extrap_b = alloc_f16(); + + for (idx, &base_sigma) in [28.0_f32, 12.0, 4.0].iter().enumerate() { + let sigma = (base_sigma / scale).max(0.5); + let max_r = (sigma * 2.5).ceil().clamp(1.0, 76.0); + let mut ub = AutoMatteUniform::default(); + ub.p[0] = [sigma, max_r, 0.0, 0.0]; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::GaussBlurH, + [&solid_tex.view, dummy_view, dummy_view, dummy_view], + &blur_tmp, + &ub, + ); + self.dispatch( + device, + queue, + enc, + AutoMatteOp::GaussBlurV, + [&blur_tmp.view, dummy_view, dummy_view, dummy_view], + &blur_out, + &ub, + ); + let prev_view = match idx { + 0 => &src.view, + 1 => &extrap_a.view, + _ => &extrap_b.view, + }; + let next_tex = if idx % 2 == 0 { &extrap_a } else { &extrap_b }; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::DecontamMergeScale, + [prev_view, &blur_out.view, dummy_view, dummy_view], + next_tex, + &u_zero, + ); + } + Some(extrap_a) + } else { + None + }; + + // --------------------------------------------------------------------- + // Stage 3C: Final composite (cutout / matte / overlay + EffectMask/Blend) + // --------------------------------------------------------------------- + let extrap_view = extrap_keepalive + .as_ref() + .map_or(&src.view, |t| &t.view); + let mut u_comp = AutoMatteUniform::default(); + u_comp.p[0] = [ + params.decontaminate, + params.output_mode as u32 as f32, + params.blend, + if has_mask { 1.0 } else { 0.0 }, + ]; + u_comp.p[1] = [ + if mask_inv { 1.0 } else { 0.0 }, + if mbm { 1.0 } else { 0.0 }, + 0.0, + 0.0, + ]; + u_comp.p[2] = skip; + self.dispatch( + device, + queue, + enc, + AutoMatteOp::CompositeOutput, + [&src.view, &matte_tex.view, extrap_view, mask_view], + dst, + &u_comp, + ); + } +} diff --git a/crates/engine/src/auto_matte/prompts.rs b/crates/engine/src/auto_matte/prompts.rs new file mode 100644 index 0000000000000000000000000000000000000000..4f85fa669ab63a97febadbdd800bae2ab1ff4ff4 --- /dev/null +++ b/crates/engine/src/auto_matte/prompts.rs @@ -0,0 +1,677 @@ +//! Unified prompt & parameter extraction for `AutoMatte` and Fusion `MagicMask`. +//! +//! Handles: +//! - Real Fusion `MagicMask` nodes (`Strokes = Input { SourceOp = "MagicMask1Strokes" }` pointing +//! at a `BezierSpline` whose `KeyFrames` carry `Value = MagicMaskStrokes { PosStrokes, NegStrokes }`, +//! or inline `MagicMaskStrokes` tables, plus `Invert`, `MatteBlur`, `MatteContractExpand`, +//! `ShowMask`, `MatteOnly`, `OutputMode`, `CacheDir`, `Blend`). +//! - Fission `AutoMatte` nodes (`Points`, `PositivePoints`, `NegativePoints`, `PosPoint1..16`, +//! `NegPoint1..16`, `PromptMode`, `QualityTier`, `AlphaFloor`, `AlphaCeiling`, `ToeGamma`, +//! `Decontaminate`, `MatteBlur`, `MatteContractExpand`, `Invert`, `OutputMode`, `CacheDir`, +//! `Blend`). + +use model::{Comp, ExprEngine, LuaKey, LuaTable, LuaValue, Node, ParamValue}; +use std::hash::{Hash, Hasher}; + +/// Maximum seeds packed into the GPU uniform buffer per dispatch. +pub const MAX_GPU_SEEDS: usize = 32; + +/// Default Clover `polish_alpha` floor (kills faint VAE haze <= 0.045). +pub const DEFAULT_ALPHA_FLOOR: f32 = 0.045; +/// Default Clover `polish_alpha` ceiling (crisp solid white >= 0.985). +pub const DEFAULT_ALPHA_CEILING: f32 = 0.985; +/// Default Clover `polish_alpha` toe gamma below 0.15. +pub const DEFAULT_TOE_GAMMA: f32 = 1.35; + +/// Normalized prompt point in Fusion Y-up `[0..1]` space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PromptPoint { + /// Horizontal normalized coordinate in `[0..1]` (left = 0, right = 1). + pub x: f32, + /// Vertical normalized coordinate in Fusion Y-up `[0..1]` (bottom = 0, top = 1). + pub y: f32, + /// `true` = foreground / positive click or stroke; `false` = background / negative. + pub positive: bool, + /// Relative seed weight (default `1.0`). + pub weight: f32, +} + +impl PromptPoint { + pub fn positive(x: f32, y: f32) -> Self { + Self { x, y, positive: true, weight: 1.0 } + } + + pub fn negative(x: f32, y: f32) -> Self { + Self { x, y, positive: false, weight: 1.0 } + } + + /// Converts Fusion Y-up `[0..1]` into top-down GPU texture UV `[0..1]`. + pub fn to_gpu_uv(self) -> [f32; 2] { + [self.x.clamp(0.0, 1.0), (1.0 - self.y).clamp(0.0, 1.0)] + } +} + +/// Prompt mode for `AutoMatte`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[repr(u32)] +pub enum PromptMode { + /// Explicit positive/negative click points or strokes. + #[default] + ClickPoints = 0, + /// Automatic person / center-salient foreground heuristic. + AutoPerson = 1, + /// Automatic central object heuristic. + Object = 2, +} + +impl PromptMode { + pub fn from_i32(v: i32) -> Self { + match v { + 1 => Self::AutoPerson, + 2 => Self::Object, + _ => Self::ClickPoints, + } + } +} + +/// Neural / refinement quality tier for `AutoMatte`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[repr(u32)] +pub enum QualityTier { + /// Fast interactive single-pass refinement. + FastInteractive = 0, + /// Balanced MatAnyone 2 tier (default). + #[default] + MatAnyone2 = 1, + /// Hero Hair / VideoMaMa tier (extra edge-preserving bilateral pass). + HeroHair = 2, +} + +impl QualityTier { + pub fn from_i32(v: i32) -> Self { + match v { + 0 => Self::FastInteractive, + 2 => Self::HeroHair, + _ => Self::MatAnyone2, + } + } +} + +/// Final compositor output mode for `AutoMatte` & `MagicMask`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[repr(u32)] +pub enum OutputMode { + /// Premultiplied cutout `(fg_clean * alpha, alpha)`. + #[default] + PremultipliedCutout = 0, + /// Grayscale matte `(alpha, alpha, alpha, alpha)`. + MatteOnly = 1, + /// Ruby-magenta translucent overlay preview on top of source footage. + OverlayPreview = 2, +} + +impl OutputMode { + pub fn from_i32(v: i32) -> Self { + match v { + 1 => Self::MatteOnly, + 2 => Self::OverlayPreview, + _ => Self::PremultipliedCutout, + } + } +} + +/// Unified evaluated parameters for both `AutoMatte` and `MagicMask`. +#[derive(Clone, Debug)] +pub struct AutoMatteParams { + pub is_magic_mask: bool, + pub prompt_mode: PromptMode, + pub quality_tier: QualityTier, + pub points: Vec, + pub alpha_floor: f32, + pub alpha_ceiling: f32, + pub toe_gamma: f32, + pub decontaminate: f32, + pub matte_blur: f32, + pub matte_contract_expand: f32, + pub invert: bool, + pub output_mode: OutputMode, + pub cache_dir: Option, + pub blend: f32, +} + +impl AutoMatteParams { + /// Deterministic parameter hash for `Engine::NodeCache` keying. + pub fn hash_into(&self, hasher: &mut impl Hasher) { + self.is_magic_mask.hash(hasher); + self.prompt_mode.hash(hasher); + self.quality_tier.hash(hasher); + self.points.len().hash(hasher); + for pt in &self.points { + pt.x.to_bits().hash(hasher); + pt.y.to_bits().hash(hasher); + pt.positive.hash(hasher); + pt.weight.to_bits().hash(hasher); + } + self.alpha_floor.to_bits().hash(hasher); + self.alpha_ceiling.to_bits().hash(hasher); + self.toe_gamma.to_bits().hash(hasher); + self.decontaminate.to_bits().hash(hasher); + self.matte_blur.to_bits().hash(hasher); + self.matte_contract_expand.to_bits().hash(hasher); + self.invert.hash(hasher); + self.output_mode.hash(hasher); + self.cache_dir.hash(hasher); + self.blend.to_bits().hash(hasher); + } + + /// Returns effective seeds for the built-in GPU fallback segmentation, synthesizing + /// center-salient + border background seeds when `PromptMode` is `AutoPerson` or `Object` + /// and no explicit points were specified. + pub fn effective_gpu_seeds(&self) -> Vec { + if !self.points.is_empty() { + return subsample_seeds(&self.points, MAX_GPU_SEEDS); + } + match self.prompt_mode { + PromptMode::ClickPoints => Vec::new(), + PromptMode::AutoPerson => vec![ + PromptPoint::positive(0.50, 0.52), + PromptPoint::positive(0.50, 0.36), + PromptPoint::positive(0.50, 0.68), + PromptPoint::negative(0.04, 0.96), + PromptPoint::negative(0.96, 0.96), + PromptPoint::negative(0.04, 0.50), + PromptPoint::negative(0.96, 0.50), + PromptPoint::negative(0.04, 0.04), + PromptPoint::negative(0.96, 0.04), + ], + PromptMode::Object => vec![ + PromptPoint::positive(0.50, 0.50), + PromptPoint::negative(0.04, 0.04), + PromptPoint::negative(0.96, 0.04), + PromptPoint::negative(0.04, 0.96), + PromptPoint::negative(0.96, 0.96), + ], + } + } +} + +fn subsample_seeds(points: &[PromptPoint], max_total: usize) -> Vec { + if points.len() <= max_total { + return points.to_vec(); + } + let pos: Vec = points.iter().copied().filter(|p| p.positive).collect(); + let neg: Vec = points.iter().copied().filter(|p| !p.positive).collect(); + let (pos_budget, neg_budget) = if neg.is_empty() { + (max_total, 0) + } else if pos.is_empty() { + (0, max_total) + } else { + let neg_share = neg.len().min(max_total / 3).max(1); + let pos_share = max_total.saturating_sub(neg_share).min(pos.len()); + let rem = max_total.saturating_sub(pos_share + neg_share); + (pos_share, (neg_share + rem).min(neg.len())) + }; + let mut out = Vec::with_capacity(max_total); + push_uniform_stride(&pos, pos_budget, &mut out); + push_uniform_stride(&neg, neg_budget, &mut out); + out +} + +fn push_uniform_stride(src: &[PromptPoint], count: usize, dst: &mut Vec) { + if count == 0 || src.is_empty() { + return; + } + if src.len() <= count { + dst.extend_from_slice(src); + return; + } + for i in 0..count { + let idx = (i * (src.len() - 1)) / (count - 1).max(1); + dst.push(src[idx]); + } +} + +fn eval_num_alias( + comp: &Comp, + node: &Node, + primary: &str, + fallback: &str, + time: f64, + default: f64, + expr: &ExprEngine, +) -> f64 { + if node.inputs.contains_key(primary) { + comp.eval_number(node, primary, time, default, expr) + } else if node.inputs.contains_key(fallback) { + comp.eval_number(node, fallback, time, default, expr) + } else { + default + } +} + +fn eval_output_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> OutputMode { + if node.inputs.contains_key("OutputMode") { + if let Some(s) = node.static_str("OutputMode") { + let lower = s.to_ascii_lowercase(); + if lower.contains("matte") || lower.contains("alpha") { + return OutputMode::MatteOnly; + } + if lower.contains("overlay") || lower.contains("mask") { + return OutputMode::OverlayPreview; + } + if lower.contains("cutout") || lower.contains("premult") || lower.contains("final") { + return OutputMode::PremultipliedCutout; + } + } + let v = comp.eval_number(node, "OutputMode", time, 0.0, expr).round() as i32; + return OutputMode::from_i32(v); + } + if comp.eval_number(node, "MatteOnly", time, 0.0, expr) > 0.5 { + return OutputMode::MatteOnly; + } + if comp.eval_number(node, "ShowMask", time, 0.0, expr) > 0.5 { + return OutputMode::OverlayPreview; + } + OutputMode::PremultipliedCutout +} + +fn read_cache_dir(node: &Node) -> Option { + if let Some(dir) = node.static_str("CacheDir") { + let trimmed = dir.trim(); + if !trimmed.is_empty() { + return Some(trimmed.to_owned()); + } + } + if let Some(dir) = node.static_str("MatteDir") { + let trimmed = dir.trim(); + if !trimmed.is_empty() { + return Some(trimmed.to_owned()); + } + } + None +} + +/// Extracts unified parameters for a Fission `AutoMatte` node. +pub fn extract_auto_matte_params( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, +) -> AutoMatteParams { + let prompt_mode = PromptMode::from_i32( + comp.eval_number(node, "PromptMode", time, 0.0, expr).round() as i32, + ); + let quality_tier = QualityTier::from_i32( + comp.eval_number(node, "QualityTier", time, 1.0, expr).round() as i32, + ); + let alpha_floor = comp + .eval_number(node, "AlphaFloor", time, DEFAULT_ALPHA_FLOOR as f64, expr) + .clamp(0.0, 0.95) as f32; + let alpha_ceiling = comp + .eval_number(node, "AlphaCeiling", time, DEFAULT_ALPHA_CEILING as f64, expr) + .clamp((alpha_floor + 0.01) as f64, 1.0) as f32; + let toe_gamma = comp + .eval_number(node, "ToeGamma", time, DEFAULT_TOE_GAMMA as f64, expr) + .clamp(0.1, 4.0) as f32; + let decontaminate = comp + .eval_number(node, "Decontaminate", time, 1.0, expr) + .clamp(0.0, 1.0) as f32; + let matte_blur = eval_num_alias(comp, node, "MatteBlur", "Blur", time, 0.0, expr).max(0.0) as f32; + let matte_contract_expand = eval_num_alias( + comp, + node, + "MatteContractExpand", + "ContractExpand", + time, + 0.0, + expr, + ) as f32; + let invert = eval_num_alias(comp, node, "Invert", "InvertMatte", time, 0.0, expr) > 0.5; + let output_mode = eval_output_mode(comp, node, time, expr); + let blend = comp.eval_number(node, "Blend", time, 1.0, expr).clamp(0.0, 1.0) as f32; + let cache_dir = read_cache_dir(node); + + let mut points = extract_auto_matte_points(comp, node, time, expr); + if points.is_empty() { + points = extract_magic_mask_strokes(comp, node, time); + } + + AutoMatteParams { + is_magic_mask: false, + prompt_mode, + quality_tier, + points, + alpha_floor, + alpha_ceiling, + toe_gamma, + decontaminate, + matte_blur, + matte_contract_expand, + invert, + output_mode, + cache_dir, + blend, + } +} + +/// Extracts unified parameters for a Fusion `MagicMask` node, mapping its real +/// `MagicMaskStrokes` (`PosStrokes` / `NegStrokes`), `MatteBlur`, `MatteContractExpand`, +/// `Invert`, `ShowMask` / `OutputMode` / `MatteOnly`, and `Blend` onto the `AutoMatte` pipeline. +pub fn extract_magic_mask_params( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, +) -> AutoMatteParams { + let points = { + let mut pts = extract_magic_mask_strokes(comp, node, time); + if pts.is_empty() { + pts = extract_auto_matte_points(comp, node, time, expr); + } + pts + }; + + let matte_blur = eval_num_alias(comp, node, "MatteBlur", "Blur", time, 0.0, expr).max(0.0) as f32; + let matte_contract_expand = eval_num_alias( + comp, + node, + "MatteContractExpand", + "ContractExpand", + time, + 0.0, + expr, + ) as f32; + let invert = eval_num_alias(comp, node, "Invert", "InvertMatte", time, 0.0, expr) > 0.5; + let output_mode = eval_output_mode(comp, node, time, expr); + let blend = comp.eval_number(node, "Blend", time, 1.0, expr).clamp(0.0, 1.0) as f32; + let decontaminate = comp + .eval_number(node, "Decontaminate", time, 1.0, expr) + .clamp(0.0, 1.0) as f32; + let alpha_floor = comp + .eval_number(node, "AlphaFloor", time, DEFAULT_ALPHA_FLOOR as f64, expr) + .clamp(0.0, 0.95) as f32; + let alpha_ceiling = comp + .eval_number(node, "AlphaCeiling", time, DEFAULT_ALPHA_CEILING as f64, expr) + .clamp((alpha_floor + 0.01) as f64, 1.0) as f32; + let toe_gamma = comp + .eval_number(node, "ToeGamma", time, DEFAULT_TOE_GAMMA as f64, expr) + .clamp(0.1, 4.0) as f32; + let quality_tier = QualityTier::from_i32( + comp.eval_number(node, "QualityTier", time, 1.0, expr).round() as i32, + ); + let cache_dir = read_cache_dir(node); + + AutoMatteParams { + is_magic_mask: true, + prompt_mode: PromptMode::ClickPoints, + quality_tier, + points, + alpha_floor, + alpha_ceiling, + toe_gamma, + decontaminate, + matte_blur, + matte_contract_expand, + invert, + output_mode, + cache_dir, + blend, + } +} + +/// Parses a Fusion `MagicMaskStrokes { PosStrokes = { ... }, NegStrokes = { ... } }` Lua table. +/// +/// Supports both flat `{ { x, y }, ... }` point arrays (Fusion 18/19/20 `.comp` format) and +/// nested stroke polyline arrays `{ { { x, y }, ... }, ... }`. +pub fn parse_magic_mask_strokes_table(table: &LuaTable) -> Vec { + let mut out = Vec::new(); + if let Some(pos) = table.get_table("PosStrokes") { + collect_point_list(pos, true, &mut out); + } + if let Some(neg) = table.get_table("NegStrokes") { + collect_point_list(neg, false, &mut out); + } + out +} + +fn collect_point_list(table: &LuaTable, positive: bool, out: &mut Vec) { + // Check if `table` itself is a single `{ x, y }` pair + if let Some([x, y]) = read_xy_pair(table) { + out.push(PromptPoint { x, y, positive, weight: 1.0 }); + return; + } + for val in table.positional_values() { + let Some(entry) = val.as_table() else { continue }; + if let Some([x, y]) = read_xy_pair(entry) { + out.push(PromptPoint { x, y, positive, weight: 1.0 }); + } else { + // Nested stroke polyline `{ { x1, y1 }, { x2, y2 }, ... }` + for sub in entry.positional_values() { + if let Some(pt_tbl) = sub.as_table() { + if let Some([x, y]) = read_xy_pair(pt_tbl) { + out.push(PromptPoint { x, y, positive, weight: 1.0 }); + } + } + } + } + } +} + +fn read_xy_pair(t: &LuaTable) -> Option<[f32; 2]> { + let x = t.get_index(1)?.as_f64()?; + let y = t.get_index(2)?.as_f64()?; + if x.is_finite() && y.is_finite() { + Some([x as f32, y as f32]) + } else { + None + } +} + +fn extract_magic_mask_strokes(comp: &Comp, node: &Node, time: f64) -> Vec { + // 1. Follow `Strokes = Input { SourceOp = "MagicMask1Strokes", Source = "Value" }` into + // `comp.raw_root.Tools[source_op].KeyFrames` + for stroke_input in ["Strokes", "LegacyStrokes"] { + if let Some(binding) = node.inputs.get(stroke_input) { + if let Some(src_op) = &binding.source_op { + if let Some(pts) = read_strokes_from_spline_tool(comp, src_op, time) { + if !pts.is_empty() { + return pts; + } + } + } + if let Some(ParamValue::Raw(LuaValue::Table(t))) = &binding.value { + let pts = parse_magic_mask_strokes_table(t); + if !pts.is_empty() { + return pts; + } + } + } + // Also check raw `Inputs..Value` directly + if let Some(val_tbl) = node + .raw + .get_table("Inputs") + .and_then(|i| i.get_table(stroke_input)) + .and_then(|s| s.get_table("Value")) + { + let pts = parse_magic_mask_strokes_table(val_tbl); + if !pts.is_empty() { + return pts; + } + } + } + Vec::new() +} + +fn read_strokes_from_spline_tool(comp: &Comp, spline_name: &str, time: f64) -> Option> { + let tools = comp.raw_root.as_ref()?.get_table("Tools")?; + let spline_tbl = find_tool_table_recursive(tools, spline_name)?; + let kfs = spline_tbl.get_table("KeyFrames")?; + + let mut keyframes: Vec<(f64, &LuaTable)> = Vec::new(); + for (k, v) in &kfs.entries { + let kf_time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + if !kf_time.is_finite() { + continue; + } + let Some(kf_tbl) = v.as_table() else { continue }; + let Some(val_tbl) = kf_tbl.get_table("Value") else { continue }; + keyframes.push((kf_time, val_tbl)); + } + if keyframes.is_empty() { + return None; + } + keyframes.sort_by(|a, b| a.0.total_cmp(&b.0)); + + // Pick closest keyframe <= time, or earliest keyframe if time precedes all keyframes + let chosen = keyframes + .iter() + .rev() + .find(|(t, _)| *t <= time + 1e-6) + .unwrap_or(&keyframes[0]); + Some(parse_magic_mask_strokes_table(chosen.1)) +} + +fn find_tool_table_recursive<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> { + if let Some(t) = tools.get_table(name) { + return Some(t); + } + for (_, val) in &tools.entries { + if let Some(t) = val.as_table() { + if let Some(inner) = t.get_table("Tools") { + if let Some(found) = find_tool_table_recursive(inner, name) { + return Some(found); + } + } + } + } + None +} + +fn extract_auto_matte_points( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, +) -> Vec { + let mut out = Vec::new(); + + // 1. `Points` input: table of `{ x, y, label }` OR string `"x,y,+;x,y,-"` + if let Some(binding) = node.inputs.get("Points") { + match &binding.value { + Some(ParamValue::Text(s)) | Some(ParamValue::FuId(s)) => { + parse_points_string(s, None, &mut out); + } + Some(ParamValue::Raw(LuaValue::Table(t))) => { + parse_mixed_points_table(t, &mut out); + } + Some(ParamValue::Point([x, y])) => { + out.push(PromptPoint::positive(*x as f32, *y as f32)); + } + _ => {} + } + } + + // 2. `PositivePoints` / `NegativePoints`: table of `{ {x, y}, ... }` OR string `"x,y;x,y"` + for (key, positive) in [("PositivePoints", true), ("NegativePoints", false)] { + if let Some(binding) = node.inputs.get(key) { + match &binding.value { + Some(ParamValue::Text(s)) | Some(ParamValue::FuId(s)) => { + parse_points_string(s, Some(positive), &mut out); + } + Some(ParamValue::Raw(LuaValue::Table(t))) => { + collect_point_list(t, positive, &mut out); + } + Some(ParamValue::Point([x, y])) => { + out.push(PromptPoint { + x: *x as f32, + y: *y as f32, + positive, + weight: 1.0, + }); + } + _ => {} + } + } + } + + // 3. Numbered point inputs `PosPoint1..16`, `NegPoint1..16`, `Point1..16` (animated-safe!) + for idx in 1..=16 { + let pos_name = format!("PosPoint{idx}"); + if node.inputs.contains_key(&pos_name) { + let [x, y] = comp.eval_point(node, &pos_name, time, [0.5, 0.5], expr); + out.push(PromptPoint::positive(x as f32, y as f32)); + } + let neg_name = format!("NegPoint{idx}"); + if node.inputs.contains_key(&neg_name) { + let [x, y] = comp.eval_point(node, &neg_name, time, [0.5, 0.5], expr); + out.push(PromptPoint::negative(x as f32, y as f32)); + } + let pt_name = format!("Point{idx}"); + if node.inputs.contains_key(&pt_name) { + let [x, y] = comp.eval_point(node, &pt_name, time, [0.5, 0.5], expr); + let lbl_name = format!("Point{idx}Label"); + let positive = comp.eval_number(node, &lbl_name, time, 1.0, expr) >= 0.5; + out.push(PromptPoint { + x: x as f32, + y: y as f32, + positive, + weight: 1.0, + }); + } + } + + out +} + +fn parse_mixed_points_table(table: &LuaTable, out: &mut Vec) { + // Support `Points = { PosStrokes = ..., NegStrokes = ... }` as well + if table.get_table("PosStrokes").is_some() || table.get_table("NegStrokes").is_some() { + out.extend(parse_magic_mask_strokes_table(table)); + return; + } + for val in table.positional_values() { + let Some(entry) = val.as_table() else { continue }; + let Some([x, y]) = read_xy_pair(entry) else { continue }; + let positive = match entry.get_index(3) { + Some(LuaValue::Number(n)) => *n > 0.0, + Some(LuaValue::Bool(b)) => *b, + Some(LuaValue::String(s)) => !s.starts_with('-') && !s.eq_ignore_ascii_case("neg"), + _ => entry.get_f64("Label").is_none_or(|n| n > 0.0), + }; + out.push(PromptPoint { x, y, positive, weight: 1.0 }); + } +} + +fn parse_points_string(s: &str, forced_positive: Option, out: &mut Vec) { + for raw_item in s.split([';', '\n']) { + let item = raw_item.trim(); + if item.is_empty() { + continue; + } + let parts: Vec<&str> = item + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|t| !t.is_empty()) + .collect(); + if parts.len() < 2 { + continue; + } + let Ok(x) = parts[0].parse::() else { continue }; + let Ok(y) = parts[1].parse::() else { continue }; + if !x.is_finite() || !y.is_finite() { + continue; + } + let positive = if let Some(p) = forced_positive { + p + } else if let Some(tag) = parts.get(2) { + let t = tag.trim().to_ascii_lowercase(); + !(t == "-" || t == "0" || t == "-1" || t == "neg" || t == "bg" || t == "false") + } else { + true + }; + out.push(PromptPoint { x, y, positive, weight: 1.0 }); + } +} diff --git a/crates/engine/src/auto_matte/tests.rs b/crates/engine/src/auto_matte/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..2cbc215244fbae3e6d5cf6e952af36544b7fa1a8 --- /dev/null +++ b/crates/engine/src/auto_matte/tests.rs @@ -0,0 +1,606 @@ +use super::*; +use crate::Engine; +use model::Comp; + +fn mk_comp(tools: &str) -> Comp { + let src = format!( + "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" + ); + Comp::from_fusion_str(&src).expect("parse AutoMatte test comp") +} + +fn px_u8(buf: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] { + let i = ((y * w + x) * 4) as usize; + buf[i..i + 4].try_into().unwrap() +} + +fn px_f32(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] { + let i = ((y * w + x) * 4) as usize; + buf[i..i + 4].try_into().unwrap() +} + +/// 1. Exact GPU verification of Clover's `polish_alpha` (haze floor elimination, ceiling clamping, +/// toe compression below 0.15 while keeping strands >= 0.15 exact, plus Invert/Blur/Morpho/Modes). +#[test] +fn polish_alpha_floor_ceiling_toe_and_modes() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let comp = mk_comp( + r#" + Plate = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 16, }, + Depth = Input { Value = 3, }, + TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, + }, + }, + AM = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + OutputMode = Input { Value = 1, }, + }, + }, + AMInv = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + OutputMode = Input { Value = 1, }, + Invert = Input { Value = 1, }, + }, + }, + AMOverlay = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + OutputMode = Input { Value = 2, }, + }, + }, + "#, + ); + + // Build a 64x16 horizontal ramp of raw alpha values covering haze, toe, strands, and ceiling + let w = 64u32; + let h = 16u32; + let mut ramp = vec![0.0_f32; (w * h) as usize]; + for y in 0..h { + for x in 0..w { + ramp[(y * w + x) as usize] = x as f32 / (w - 1) as f32; + } + } + eng.auto_matte_cache.insert_alpha_f32("AM", 0, [w, h], ramp.clone()); + eng.auto_matte_cache.insert_alpha_f32("AMInv", 0, [w, h], ramp.clone()); + eng.auto_matte_cache.insert_alpha_f32("AMOverlay", 0, [w, h], ramp); + + let (tex, _) = eng.evaluate(&comp, comp.find_node("AM").unwrap(), 0.0); + let f32_buf = eng.readback_rgba_f32(&tex).unwrap(); + + // Check every column against Clover's exact `polish_alpha` formula + let lo = 0.045_f32; + let hi = 0.985_f32; + let toe_gamma = 1.35_f32; + for x in 0..w { + let raw = x as f32 / (w - 1) as f32; + let lin = ((raw - lo) / (hi - lo)).clamp(0.0, 1.0); + let expected = if lin < 0.15 { + (lin / 0.15).powf(toe_gamma) * 0.15 + } else { + lin + }; + let got = px_f32(&f32_buf, w, x, 8); + assert!( + (got[3] - expected).abs() < 2e-3, + "polish_alpha mismatch at x={x} (raw={raw:.4}): got={:.5} expected={:.5}", + got[3], + expected + ); + // OutputMode = 1 outputs grayscale (a, a, a, a) + assert!((got[0] - got[3]).abs() < 2e-3); + } + + // Haze <= 0.045 (x=0,1,2 -> raw <= 0.0317) must be exact 0.0 + assert_eq!(px_f32(&f32_buf, w, 2, 8)[3], 0.0, "VAE haze <= 0.045 must be eliminated"); + // Ceiling >= 0.985 (x=63 -> raw=1.0) must be exact 1.0 + assert_eq!(px_f32(&f32_buf, w, 63, 8)[3], 1.0, "Ceiling >= 0.985 must clamp to 1.0"); + // Toe compression (x=7 -> raw=0.1111 -> lin=0.0703 < 0.15) strictly compressed below linear + let toe_raw = 7.0_f32 / 63.0; + let toe_lin = (toe_raw - lo) / (hi - lo); + let toe_got = px_f32(&f32_buf, w, 7, 8)[3]; + assert!(toe_got > 0.0 && toe_got < toe_lin - 0.01, "toe must compress misty halo: got={toe_got} lin={toe_lin}"); + // Strand > 0.15 (x=20 -> raw=0.3175 -> lin=0.2899) untouched by toe + let strand_raw = 20.0_f32 / 63.0; + let strand_lin = (strand_raw - lo) / (hi - lo); + let strand_got = px_f32(&f32_buf, w, 20, 8)[3]; + assert!((strand_got - strand_lin).abs() < 2e-3, "strand > 0.15 must stay crisp: got={strand_got} lin={strand_lin}"); + + // Invert = 1 flips alpha + let (inv_tex, _) = eng.evaluate(&comp, comp.find_node("AMInv").unwrap(), 0.0); + let inv_buf = eng.readback_rgba_f32(&inv_tex).unwrap(); + assert_eq!(px_f32(&inv_buf, w, 2, 8)[3], 1.0); + assert_eq!(px_f32(&inv_buf, w, 63, 8)[3], 0.0); + + // OutputMode = 2 renders opaque ruby overlay where alpha == 1, untouched plate where alpha == 0 + let (ov_tex, _) = eng.evaluate(&comp, comp.find_node("AMOverlay").unwrap(), 0.0); + let ov_buf = eng.readback_rgba_f32(&ov_tex).unwrap(); + let bg_px = px_f32(&ov_buf, w, 1, 8); + let fg_px = px_f32(&ov_buf, w, 63, 8); + assert!((bg_px[0] - 0.8).abs() < 1e-2 && (bg_px[3] - 1.0).abs() < 1e-2); + assert!(fg_px[0] > bg_px[0] + 0.05 && fg_px[1] < bg_px[1] - 0.1, "overlay tints foreground ruby: {fg_px:?}"); +} + +/// 2. GPU `hair_safe_decontaminate`: eliminates neon-cyan background spill inside semi-transparent +/// hair edge pixels while keeping solid interior (`alpha > 0.94`) RGB bit-exact. +#[test] +fn hair_safe_decontaminate_kills_cyan_spill_and_preserves_solid_interior() { + let Ok(mut eng) = Engine::new_headless() else { return }; + // Left half [0..26): pure solid brown hair RGB = (0.44, 0.22, 0.10) + // Middle band [26..36): wispy hair heavily contaminated with neon cyan (0.0, 1.0, 1.0) + // Right half [36..64): pure neon cyan background (0.0, 1.0, 1.0) + let comp = mk_comp( + r#" + CyanBg = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, + }, + }, + HairMask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.20, 0.5 }, }, Width = Input { Value = 0.40, }, Height = Input { Value = 1.0, }, + }, + }, + HairFg = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.44, }, TopLeftGreen = Input { Value = 0.22, }, TopLeftBlue = Input { Value = 0.10, }, + EffectMask = Input { SourceOp = "HairMask", Source = "Mask", }, + }, + }, + SpillMask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.48, 0.5 }, }, Width = Input { Value = 0.16, }, Height = Input { Value = 1.0, }, + }, + }, + SpillBand = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.15, }, TopLeftGreen = Input { Value = 0.85, }, TopLeftBlue = Input { Value = 0.90, }, + EffectMask = Input { SourceOp = "SpillMask", Source = "Mask", }, + }, + }, + M1 = Merge { + Inputs = { + Background = Input { SourceOp = "CyanBg", Source = "Output", }, + Foreground = Input { SourceOp = "HairFg", Source = "Output", }, + }, + }, + Plate = Merge { + Inputs = { + Background = Input { SourceOp = "M1", Source = "Output", }, + Foreground = Input { SourceOp = "SpillBand", Source = "Output", }, + }, + }, + AMClean = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + Decontaminate = Input { Value = 1.0, }, + AlphaFloor = Input { Value = 0.0, }, + AlphaCeiling = Input { Value = 1.0, }, + ToeGamma = Input { Value = 1.0, }, + }, + }, + AMRaw = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + Decontaminate = Input { Value = 0.0, }, + AlphaFloor = Input { Value = 0.0, }, + AlphaCeiling = Input { Value = 1.0, }, + ToeGamma = Input { Value = 1.0, }, + }, + }, + "#, + ); + + let (w, h) = (64u32, 64u32); + let mut alpha = vec![0.0_f32; (w * h) as usize]; + for y in 0..h { + for x in 0..w { + let a = if x < 25 { + 1.0 + } else if x < 36 { + // Semi-transparent wispy hair strands (< 0.85) sitting directly over cyan spill + 0.50 + } else { + 0.0 + }; + alpha[(y * w + x) as usize] = a; + } + } + eng.auto_matte_cache.insert_alpha_f32("AMClean", 0, [w, h], alpha.clone()); + eng.auto_matte_cache.insert_alpha_f32("AMRaw", 0, [w, h], alpha); + + let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0); + let plate_px = eng.readback_rgba(&plate_tex).unwrap(); + + let (clean_tex, _) = eng.evaluate(&comp, comp.find_node("AMClean").unwrap(), 0.0); + let clean_px = eng.readback_rgba(&clean_tex).unwrap(); + + let (raw_tex, _) = eng.evaluate(&comp, comp.find_node("AMRaw").unwrap(), 0.0); + let raw_px = eng.readback_rgba(&raw_tex).unwrap(); + + // 1. Solid interior (x=10, y=32, alpha=1.0) MUST be bit-exact to original Plate + assert_eq!( + px_u8(&clean_px, w, 10, 32), + px_u8(&plate_px, w, 10, 32), + "solid interior (alpha > 0.94) must remain bit-exact" + ); + + // 2. Wispy edge pixel (x=30, y=32, alpha=0.50): unpremultiplied foreground must match clean + // brown hair (~112, 56, 26), completely removing the cyan spill (~38, 217, 230) seen in AMRaw! + let wisp_clean = px_u8(&clean_px, w, 30, 32); + let wisp_raw = px_u8(&raw_px, w, 30, 32); + assert!((wisp_clean[3] as i32 - 128).abs() <= 2, "wisp alpha preserved: {wisp_clean:?}"); + let clean_unpremult_r = wisp_clean[0] as f32 / (wisp_clean[3] as f32 / 255.0); + let clean_unpremult_g = wisp_clean[1] as f32 / (wisp_clean[3] as f32 / 255.0); + let clean_unpremult_b = wisp_clean[2] as f32 / (wisp_clean[3] as f32 / 255.0); + let raw_unpremult_b = wisp_raw[2] as f32 / (wisp_raw[3] as f32 / 255.0); + + assert!( + raw_unpremult_b > 200.0, + "sanity check: raw non-decontaminated wisp carries heavy cyan blue spill ({raw_unpremult_b:.1})" + ); + assert!( + clean_unpremult_r > 95.0 && clean_unpremult_g < 75.0 && clean_unpremult_b < 45.0, + "hair_safe_decontaminate must replace cyan spill with clean extrapolated brown hair: clean=({clean_unpremult_r:.1}, {clean_unpremult_g:.1}, {clean_unpremult_b:.1})" + ); + + // 3. Background (x=55, y=32, alpha=0.0) must be transparent black + assert_eq!(px_u8(&clean_px, w, 55, 32), [0, 0, 0, 0]); +} + +/// 3. Built-in GPU point-seeded segmentation (`+`/`-` click points + bilateral edge refinement, +/// plus `AutoPerson` center-salient heuristic with zero clicks). +#[test] +fn gpu_seeded_segmentation_separates_fg_from_bg() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let comp = mk_comp( + r#" + BlueBg = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.16, }, TopLeftBlue = Input { Value = 0.86, }, + }, + }, + BoxM = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, }, + }, + }, + RedObj = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.88, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.10, }, + EffectMask = Input { SourceOp = "BoxM", Source = "Mask", }, + }, + }, + Plate = Merge { + Inputs = { + Background = Input { SourceOp = "BlueBg", Source = "Output", }, + Foreground = Input { SourceOp = "RedObj", Source = "Output", }, + }, + }, + AMPoints = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + Points = Input { Value = "0.50,0.50,+;0.10,0.10,-;0.90,0.90,-", }, + QualityTier = Input { Value = 1, }, + }, + }, + AMAutoPerson = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + PromptMode = Input { Value = 1, }, + QualityTier = Input { Value = 0, }, + }, + }, + "#, + ); + + // Explicit +/- click points + let (tex, _) = eng.evaluate(&comp, comp.find_node("AMPoints").unwrap(), 0.0); + let buf = eng.readback_rgba(&tex).unwrap(); + let center = px_u8(&buf, 64, 32, 32); + let corner_tl = px_u8(&buf, 64, 4, 4); + let corner_br = px_u8(&buf, 64, 60, 60); + assert!(center[3] >= 245 && center[0] > 200, "foreground center must be opaque red: {center:?}"); + assert!(corner_tl[3] <= 5 && corner_br[3] <= 5, "background corners must be keyed out: tl={corner_tl:?} br={corner_br:?}"); + + // AutoPerson mode with zero manual points + let (ap_tex, _) = eng.evaluate(&comp, comp.find_node("AMAutoPerson").unwrap(), 0.0); + let ap_buf = eng.readback_rgba(&ap_tex).unwrap(); + assert!(px_u8(&ap_buf, 64, 32, 32)[3] >= 240, "AutoPerson center subject must be opaque"); + assert!(px_u8(&ap_buf, 64, 4, 4)[3] <= 10, "AutoPerson border background must be transparent"); +} + +/// 4. `AutoMatteCache` per-frame injection, disk `CacheDir` PNG loading, real Fusion `MagicMask` +/// `MagicMaskStrokes` spline parsing, and empty-stroke passthrough (0.00% MAE). +#[test] +fn cache_injection_and_fusion_magic_mask_strokes_and_empty_passthrough() { + let Ok(mut eng) = Engine::new_headless() else { return }; + + // Real Fusion MagicMask comp structure matching `/Volumes/Project/trees/fusion/21_ground.comp` + let comp = mk_comp( + r#" + GreenBg = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.72, }, TopLeftBlue = Input { Value = 0.14, }, + }, + }, + CircleM = EllipseMask { + Inputs = { + MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.35, 0.65 }, }, Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, }, + }, + }, + OrangeSubject = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.45, }, TopLeftBlue = Input { Value = 0.05, }, + EffectMask = Input { SourceOp = "CircleM", Source = "Mask", }, + }, + }, + Plate = Merge { + Inputs = { + Background = Input { SourceOp = "GreenBg", Source = "Output", }, + Foreground = Input { SourceOp = "OrangeSubject", Source = "Output", }, + }, + }, + MagicMask1 = MagicMask { + Inputs = { + ReferenceTime = Input { Value = 2466, Disabled = true, }, + UseLegacyMagicMask = Input { Value = 0, Disabled = true, }, + Strokes = Input { SourceOp = "MagicMask1Strokes", Source = "Value", }, + Input = Input { SourceOp = "Plate", Source = "Output", }, + }, + }, + MagicMask1Strokes = BezierSpline { + KeyFrames = { + [2466] = { 0, Flags = { Linear = true, LockedY = true }, Value = MagicMaskStrokes { + PosStrokes = { + { 0.35, 0.65 }, + { 0.38, 0.62 }, + }, + NegStrokes = { + { 0.85, 0.20 }, + } + } } + } + }, + EmptyMagicMask = MagicMask { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + }, + }, + "#, + ); + + // Verify Fusion MagicMaskStrokes extraction (Y-up preserved accurately!) + let mm1_node = comp.node(comp.find_node("MagicMask1").unwrap()); + let params = extract_magic_mask_params(&comp, mm1_node, 2466.0, &eng.expr); + assert!(params.is_magic_mask); + assert_eq!(params.points.len(), 3); + assert!(params.points[0].positive && (params.points[0].x - 0.35).abs() < 1e-5 && (params.points[0].y - 0.65).abs() < 1e-5); + assert!(!params.points[2].positive && (params.points[2].x - 0.85).abs() < 1e-5 && (params.points[2].y - 0.20).abs() < 1e-5); + + // Evaluate MagicMask1 on GPU: Fusion Y-up (0.35, 0.65) -> GPU pixel (~22, ~22) is orange subject; + // Fusion Y-up (0.85, 0.20) -> GPU pixel (~54, ~51) is green background! + let (mm_tex, _) = eng.evaluate(&comp, comp.find_node("MagicMask1").unwrap(), 2466.0); + let mm_buf = eng.readback_rgba(&mm_tex).unwrap(); + let subj_px = px_u8(&mm_buf, 64, 22, 22); + let bg_px = px_u8(&mm_buf, 64, 54, 51); + assert!(subj_px[3] >= 240, "MagicMask positive stroke subject must be opaque: {subj_px:?}"); + assert!(bg_px[3] <= 10, "MagicMask negative stroke background must be transparent: {bg_px:?}"); + + // Empty MagicMask (no strokes, no cached matte) MUST pass foreground through bit-for-bit (0.00% MAE) + let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0); + let (empty_tex, _) = eng.evaluate(&comp, comp.find_node("EmptyMagicMask").unwrap(), 0.0); + assert_eq!( + eng.readback_rgba(&empty_tex).unwrap(), + eng.readback_rgba(&plate_tex).unwrap(), + "empty MagicMask must pass through input bit-exact with 0.00% MAE" + ); + + // Now inject a cached neural matte into EmptyMagicMask for frame 0 -> must immediately override + // passthrough and bust OutputCache automatically! + let mut right_half = vec![0.0_f32; 64 * 64]; + for y in 0..64 { + for x in 32..64 { + right_half[y * 64 + x] = 1.0; + } + } + eng.auto_matte_cache.insert_alpha_f32("EmptyMagicMask", 0, [64, 64], right_half); + let (injected_tex, _) = eng.evaluate(&comp, comp.find_node("EmptyMagicMask").unwrap(), 0.0); + let inj_buf = eng.readback_rgba(&injected_tex).unwrap(); + assert_eq!(px_u8(&inj_buf, 64, 8, 32)[3], 0, "cached matte left half must be transparent"); + assert_eq!(px_u8(&inj_buf, 64, 56, 32)[3], 255, "cached matte right half must be opaque"); + + // Disk CacheDir PNG loading test (native only) + #[cfg(not(target_arch = "wasm32"))] + { + let tmp_dir = std::env::temp_dir().join(format!("fission_automate_test_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).unwrap(); + let mut png_img = image::GrayImage::new(32, 32); + for y in 0..32 { + for x in 0..32 { + png_img.put_pixel(x, y, image::Luma([if y < 16 { 255 } else { 0 }])); + } + } + png_img.save(tmp_dir.join("0005.png")).unwrap(); + + let disk_comp = mk_comp(&format!( + r#" + Bg = Background {{ Inputs = {{ Width = Input {{ Value = 32, }}, Height = Input {{ Value = 32, }}, TopLeftRed = Input {{ Value = 1.0, }}, }}, }}, + DiskAM = AutoMatte {{ + Inputs = {{ + Input = Input {{ SourceOp = "Bg", Source = "Output", }}, + CacheDir = Input {{ Value = "{}", }}, + OutputMode = Input {{ Value = 1, }}, + }}, + }}, + "#, + tmp_dir.to_string_lossy().replace('\\', "/") + )); + let (disk_tex, _) = eng.evaluate(&disk_comp, disk_comp.find_node("DiskAM").unwrap(), 5.0); + let disk_buf = eng.readback_rgba(&disk_tex).unwrap(); + assert_eq!(px_u8(&disk_buf, 32, 16, 4)[3], 255, "top half from 0005.png must be opaque"); + assert_eq!(px_u8(&disk_buf, 32, 16, 28)[3], 0, "bottom half from 0005.png must be transparent"); + let _ = std::fs::remove_dir_all(&tmp_dir); + } +} + +/// 5. MatteContractExpand + MatteBlur + EffectMask + Blend=0 verification. +#[test] +fn matte_contract_expand_blur_and_effect_mask() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let comp = mk_comp( + r#" + Plate = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.9, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.2, }, + }, + }, + AMExpand = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + MatteContractExpand = Input { Value = 3.0, }, + OutputMode = Input { Value = 1, }, + }, + }, + AMContract = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + MatteContractExpand = Input { Value = -3.0, }, + OutputMode = Input { Value = 1, }, + }, + }, + AMBlur = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + MatteBlur = Input { Value = 2.5, }, + OutputMode = Input { Value = 1, }, + }, + }, + AMBlendZero = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + Blend = Input { Value = 0.0, }, + }, + }, + "#, + ); + + let mut box_alpha = vec![0.0_f32; 64 * 64]; + for y in 20..44 { + for x in 20..44 { + box_alpha[y * 64 + x] = 1.0; + } + } + for name in ["AMExpand", "AMContract", "AMBlur", "AMBlendZero"] { + eng.auto_matte_cache.insert_alpha_f32(name, 0, [64, 64], box_alpha.clone()); + } + + let (exp_tex, _) = eng.evaluate(&comp, comp.find_node("AMExpand").unwrap(), 0.0); + let exp_buf = eng.readback_rgba(&exp_tex).unwrap(); + let (con_tex, _) = eng.evaluate(&comp, comp.find_node("AMContract").unwrap(), 0.0); + let con_buf = eng.readback_rgba(&con_tex).unwrap(); + + let exp_count = exp_buf.chunks_exact(4).filter(|p| p[3] > 200).count(); + let con_count = con_buf.chunks_exact(4).filter(|p| p[3] > 200).count(); + assert!( + exp_count > con_count + 400, + "expanded matte ({exp_count}) must be substantially larger than contracted ({con_count})" + ); + + let (blur_tex, _) = eng.evaluate(&comp, comp.find_node("AMBlur").unwrap(), 0.0); + let blur_buf = eng.readback_rgba(&blur_tex).unwrap(); + let edge_a = px_u8(&blur_buf, 64, 20, 32)[3]; + assert!(edge_a > 40 && edge_a < 220, "MatteBlur must produce smooth edge alpha: {edge_a}"); + + let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0); + let (b0_tex, _) = eng.evaluate(&comp, comp.find_node("AMBlendZero").unwrap(), 0.0); + assert_eq!( + eng.readback_rgba(&b0_tex).unwrap(), + eng.readback_rgba(&plate_tex).unwrap(), + "Blend = 0 must pass input through untouched" + ); +} + +/// 6. EffectMask gating, proxy_scale=2 decontamination scaling, and native AutoMatteRunner validation. +#[test] +fn effect_mask_proxy_scale_and_runner_api() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let comp = mk_comp( + r#" + Plate = Background { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.80, }, TopLeftGreen = Input { Value = 0.30, }, TopLeftBlue = Input { Value = 0.20, }, + }, + }, + LeftMask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, + }, + }, + AMMasked = AutoMatte { + Inputs = { + Input = Input { SourceOp = "Plate", Source = "Output", }, + EffectMask = Input { SourceOp = "LeftMask", Source = "Mask", }, + }, + }, + "#, + ); + // All-zero cached matte: inside LeftMask (left half) becomes transparent, outside LeftMask (right half) + // stays original Plate because EffectMask gates the AutoMatte effect! + eng.auto_matte_cache + .insert_alpha_f32("AMMasked", 0, [64, 64], vec![0.0_f32; 64 * 64]); + + let (tex, _) = eng.evaluate(&comp, comp.find_node("AMMasked").unwrap(), 0.0); + let buf = eng.readback_rgba(&tex).unwrap(); + assert_eq!(px_u8(&buf, 64, 8, 32)[3], 0, "inside EffectMask must apply zero alpha"); + assert_eq!(px_u8(&buf, 64, 56, 32)[3], 255, "outside EffectMask must keep original Plate"); + + // Proxy scale = 2: full-res 64x64 cached matte resamples cleanly to 32x32 output + eng.proxy_scale = 2; + eng.auto_matte_cache + .insert_alpha_f32("AMMasked", 1, [64, 64], vec![1.0_f32; 64 * 64]); + let (proxy_tex, _) = eng.evaluate(&comp, comp.find_node("AMMasked").unwrap(), 1.0); + assert_eq!(proxy_tex.size, [32, 32]); + let pbuf = eng.readback_rgba(&proxy_tex).unwrap(); + assert_eq!(px_u8(&pbuf, 32, 4, 16)[3], 255, "proxy_scale=2 resampled cached matte must stay opaque"); + + #[cfg(not(target_arch = "wasm32"))] + { + let runner = AutoMatteRunner::new( + AutoMatteWorkerConfig { + python_bin: std::path::PathBuf::from("/nonexistent/python"), + worker_script: std::path::PathBuf::from("/nonexistent/worker.py"), + output_dir: std::env::temp_dir(), + }, + eng.auto_matte_cache.clone(), + ); + let err = runner.spawn_job(AutoMatteJobRequest { + node_name: "AMMasked".into(), + input_path: std::path::PathBuf::from("/nonexistent/clip.mov"), + frame_range: [0, 0], + quality_tier: QualityTier::HeroHair, + prompt_mode: PromptMode::ClickPoints, + prompts: vec![PromptPoint::positive(0.5, 0.5)], + }); + assert!(err.is_err(), "missing worker binary must return clean Err without panicking"); + } +} + diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index e9d4481d571686ef2fd81ebc8e518d7b9a4d3cae..d3ba0a97f32ced1007f6cf4a64f4a4b15066c659 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -82,6 +82,8 @@ pub struct Engine { warps_masks_pipelines: OnceCell>, fx_fuses_pipelines: OnceCell>, archive_fx2_pipelines: OnceCell>, + auto_matte_pipelines: OnceCell>, + pub auto_matte_cache: crate::auto_matte::AutoMatteCache, motion_blur: crate::motion_blur::MotionBlurPipelines, pub(crate) supports_f32_filter: bool, scene3d: crate::scene3d::Scene3DRenderer, @@ -195,6 +197,8 @@ impl Engine { warps_masks_pipelines: OnceCell::new(), fx_fuses_pipelines: OnceCell::new(), archive_fx2_pipelines: OnceCell::new(), + auto_matte_pipelines: OnceCell::new(), + auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), motion_blur: crate::motion_blur::MotionBlurPipelines::default(), supports_f32_filter, scene3d, @@ -356,6 +360,9 @@ impl Engine { if let Some(fx2) = self.archive_fx2_pipelines.get() { fx2.borrow_mut().reset_uniform_cursor(); } + if let Some(am) = self.auto_matte_pipelines.get() { + am.borrow_mut().reset_uniform_cursor(); + } if let Some(of) = self.optflow.get() { of.reset_uniform_cursor(); } @@ -385,6 +392,9 @@ impl Engine { if let Some(fx2) = self.archive_fx2_pipelines.get() { fx2.borrow_mut().trim_uniform_chunks(2); } + if let Some(am) = self.auto_matte_pipelines.get() { + am.borrow_mut().trim_uniform_chunks(2); + } self.media.trim_nv12_uniform_chunks(2); } @@ -490,7 +500,8 @@ impl Engine { ) -> (CachedTexture, EvalStats) { let t0 = Instant::now(); self.sync_bg_cache_with_vram_drops(); - let out_key = self.output_cache_key(comp, target, time); + let out_key = self.output_cache_key(comp, target, time) + ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); if let Some((tex, unsupported)) = self.output_cache_get(out_key) { let stats = EvalStats { eval_ms: t0.elapsed().as_secs_f64() * 1000.0, @@ -546,7 +557,8 @@ impl Engine { ) -> EvalStats { let t0 = Instant::now(); self.sync_bg_cache_with_vram_drops(); - let out_key = self.output_cache_key(comp, target, time); + let out_key = self.output_cache_key(comp, target, time) + ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); let mut stats = EvalStats::default(); let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("comp-viewer-eval"), @@ -1030,6 +1042,8 @@ impl Engine { "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), "Fuse.Cryptomatte" | "Cryptomatte" => self.eval_cryptomatte(comp, node, time, frame_i, enc, visiting, stats), + "AutoMatte" => self.eval_auto_matte(comp, node, time, frame_i, false, enc, visiting, stats), + "MagicMask" => self.eval_auto_matte(comp, node, time, frame_i, true, enc, visiting, stats), "pRender" => self.eval_p_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "pEmitter" | "pPointForce" @@ -1703,6 +1717,104 @@ impl Engine { dst } + #[allow(clippy::too_many_arguments)] + fn eval_auto_matte( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + is_magic_mask: bool, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let primary_src = node + .connected_node("Input") + .or_else(|| node.connected_node("Image")) + .or_else(|| node.connected_node("Source")) + .or_else(|| node.connected_node("Background")) + .and_then(|s| comp.find_node(s)); + let Some(src_id) = primary_src else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let params = if is_magic_mask { + crate::auto_matte::extract_magic_mask_params(comp, node, time, &self.expr) + } else { + crate::auto_matte::extract_auto_matte_params(comp, node, time, &self.expr) + }; + let mbm = self.multiplies_by_mask(comp, node, time); + if params.blend <= 1e-6 && !mbm { + return src; + } + let cached_matte = self.auto_matte_cache.get_or_load_frame( + &node.name, + frame_i, + params.cache_dir.as_deref(), + ); + // Empty MagicMask / AutoMatte (no strokes/points & no cached neural matte) passes through + // foreground cleanly with 0.00% MAE regression. + if cached_matte.is_none() && params.effective_gpu_seeds().is_empty() { + return src; + } + + let src = self.crop_to_canvas(enc, src); + let (mask, mask_inv) = + self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let matte_hash = cached_matte.as_ref().map_or(0, |m| m.content_hash); + let skip = self.process_skip(comp, node, time); + + let mut ph = DefaultHasher::new(); + params.hash_into(&mut ph); + self.proxy_scale.hash(&mut ph); + mask_inv.hash(&mut ph); + mbm.hash(&mut ph); + for s in skip { + s.to_bits().hash(&mut ph); + } + let param_hash = ph.finish(); + let key = self.make_key( + node, + if is_magic_mask { "MagicMask" } else { "AutoMatte" }, + src.size, + &[src.content_hash, mask_hash, matte_hash, param_hash], + &[], + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = self.alloc_tex(src.size, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + let pipelines = self + .auto_matte_pipelines + .get_or_init(|| RefCell::new(crate::auto_matte::AutoMattePipelines::new(&self.device))); + pipelines.borrow_mut().execute( + &self.device, + &self.queue, + enc, + &self.cache, + &self.dummy.view, + &src, + mv, + mask.is_some(), + mask_inv, + mbm, + skip, + &dst, + ¶ms, + cached_matte.as_deref(), + self.proxy_scale, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 { let mut h = DefaultHasher::new(); self.cache.gpu_salt.hash(&mut h); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 62c2352f30a21f2a5a83d83201bcd0a341fc0e6b..b7d5fc9f517ac06124da76e3539a48b9fe4fffb9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,5 +1,6 @@ #[cfg(not(target_arch = "wasm32"))] pub mod audio; +pub mod auto_matte; pub mod cache; pub mod cryptomatte; pub mod custom_shader; diff --git a/crates/engine/src/shaders/auto_matte.wgsl b/crates/engine/src/shaders/auto_matte.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..9575a11e984dcec7f330583ecc301c93232a13b1 --- /dev/null +++ b/crates/engine/src/shaders/auto_matte.wgsl @@ -0,0 +1,494 @@ +// AutoMatte & Diverging MagicMask GPU compute shaders: +// - Stage 2 GPU fallback: `seed_segment_op` (multi-seed perceptual Oklab color+spatial affinity) +// + `bilateral_refine_op` (joint-bilateral edge-aware alpha refinement). +// - Stage 3 Alpha Polish: `polish_alpha_op` (exact port of Clover's floor/ceiling/toe polish), +// `morpho_h_op` / `morpho_v_op` (MatteContractExpand), `gauss_blur_h_op` / `gauss_blur_v_op`. +// - Stage 3 Hair-Safe Foreground Decontamination: `decontam_init_op` + 3-scale separable +// normalized-convolution Gaussian pyramid (`sigma = 28, 12, 4` scaled by proxy_scale) + +// `decontam_merge_scale_op` + `composite_output_op`. +// +// WebGPU-safe (`wasm32` compatible): +// - All input textures bound with `filterable: false`, read exclusively via `textureLoad`. +// - Output storage texture is WriteOnly (patched at pipeline compile time for rgba16float/rgba32float). +// - Growable 512-slot dynamic uniform ring buffer. + +@group(0) @binding(0) var src_a: texture_2d; +@group(0) @binding(1) var src_b: texture_2d; +@group(0) @binding(2) var src_c: texture_2d; +@group(0) @binding(3) var mask_tex: texture_2d; +@group(0) @binding(4) var dst_tex: texture_storage_2d; + +const HDR_FLOAT: bool = false; +const MAX_SEEDS: u32 = 32u; + +struct AutoMatteUniform { + p: array, 8>, + // Each seed: (uv_x, uv_y [top-down 0..1], label [+1.0 pos / -1.0 neg], weight) + seeds: array, 32>, +}; +@group(0) @binding(5) var u: AutoMatteUniform; + +fn store_dst(p: vec2, col: vec4) { + if (HDR_FLOAT) { + textureStore(dst_tex, p, col); + } else { + textureStore(dst_tex, p, clamp(col, vec4(0.0), vec4(1.0))); + } +} + +fn load_clamped(tex: texture_2d, p: vec2) -> vec4 { + let dims = vec2(textureDimensions(tex)); + let c = clamp(p, vec2(0), max(dims - vec2(1), vec2(0))); + return textureLoad(tex, c, 0); +} + +fn sample_bilinear(tex: texture_2d, uv: vec2) -> vec4 { + let dims = vec2(textureDimensions(tex)); + let max_c = max(dims - vec2(1), vec2(0)); + let f = clamp(uv, vec2(0.0), vec2(1.0)) * vec2(dims) - vec2(0.5); + let fl = floor(f); + let i0 = clamp(vec2(fl), vec2(0), max_c); + let i1 = clamp(i0 + vec2(1), vec2(0), max_c); + let t = clamp(f - fl, vec2(0.0), vec2(1.0)); + let c00 = textureLoad(tex, i0, 0); + let c10 = textureLoad(tex, vec2(i1.x, i0.y), 0); + let c01 = textureLoad(tex, vec2(i0.x, i1.y), 0); + let c11 = textureLoad(tex, i1, 0); + return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); +} + +fn cbrt_safe(x: f32) -> f32 { + return sign(x) * pow(abs(x), 1.0 / 3.0); +} + +// Perceptual Oklab color transform (from linear-ish RGB clamped >= 0). +fn rgb_to_oklab(rgb_in: vec3) -> vec3 { + let rgb = max(rgb_in, vec3(0.0)); + let l = 0.4122214708 * rgb.r + 0.5363325363 * rgb.g + 0.0514459929 * rgb.b; + let m = 0.2119034982 * rgb.r + 0.6806995451 * rgb.g + 0.1073969566 * rgb.b; + let s = 0.0883024619 * rgb.r + 0.2817188376 * rgb.g + 0.6299787005 * rgb.b; + let l_ = cbrt_safe(l); + let m_ = cbrt_safe(m); + let s_ = cbrt_safe(s); + return vec3( + 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_, + 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_, + 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_, + ); +} + +fn sample_seed_oklab(uv: vec2, dims: vec2) -> vec3 { + let px = vec2(clamp(uv, vec2(0.0), vec2(1.0)) * vec2(dims)); + let c0 = load_clamped(src_a, px).rgb; + let c1 = load_clamped(src_a, px + vec2(1, 0)).rgb; + let c2 = load_clamped(src_a, px + vec2(-1, 0)).rgb; + let c3 = load_clamped(src_a, px + vec2(0, 1)).rgb; + let c4 = load_clamped(src_a, px + vec2(0, -1)).rgb; + let avg = (c0 * 2.0 + c1 + c2 + c3 + c4) / 6.0; + return rgb_to_oklab(avg); +} + +fn read_mask(gid: vec2, dims: vec2, has_mask: f32, invert: f32) -> f32 { + if (has_mask < 0.5) { + return 1.0; + } + let uv = (vec2(gid) + 0.5) / vec2(dims); + let m = sample_bilinear(mask_tex, uv).a; + return select(m, 1.0 - m, invert > 0.5); +} + +// ----------------------------------------------------------------------------- +// Stage 2A: Multi-seed perceptual color + spatial affinity segmentation +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn seed_segment_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let dims = vec2(dims_u); + let p = vec2(gid.xy); + let uv = (vec2(gid.xy) + 0.5) / vec2(dims_u); + + let num_seeds = min(u32(u.p[0].x + 0.5), MAX_SEEDS); + let num_neg = u32(u.p[0].y + 0.5); + let sigma_c = max(u.p[0].z, 0.02); + let sigma_s_pos = max(u.p[0].w, 0.05); + let sigma_s_neg = max(u.p[1].x, 0.05); + let use_auto_bg = u.p[1].y > 0.5; + let aspect = max(u.p[1].z, 0.1); + + let inv_sc2 = 1.0 / (sigma_c * sigma_c); + let inv_sp2 = 1.0 / (sigma_s_pos * sigma_s_pos); + let inv_sn2 = 1.0 / (sigma_s_neg * sigma_s_neg); + + let px_lab = rgb_to_oklab(load_clamped(src_a, p).rgb); + + // Pass 1: find minimum energy across positive and negative seeds for numerical stability + var min_e_pos = 1e20; + var min_e_neg = 1e20; + var min_dspa_pos = 1e20; + var pos_count = 0u; + var neg_count = 0u; + + for (var i = 0u; i < num_seeds; i = i + 1u) { + let s = u.seeds[i]; + let s_lab = sample_seed_oklab(s.xy, dims); + let d_col = length(px_lab - s_lab); + let d_uv = (uv - s.xy) * vec2(aspect, 1.0); + let d_spa = length(d_uv); + if (s.z >= 0.0) { + let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sp2; + min_e_pos = min(min_e_pos, e); + min_dspa_pos = min(min_dspa_pos, d_spa); + pos_count = pos_count + 1u; + } else { + let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sn2; + min_e_neg = min(min_e_neg, e); + neg_count = neg_count + 1u; + } + } + + // Automatic border background seeds when only positive seeds were supplied + var auto_bg_pts = array, 8>( + vec2(0.02, 0.02), + vec2(0.98, 0.02), + vec2(0.02, 0.98), + vec2(0.98, 0.98), + vec2(0.50, 0.02), + vec2(0.50, 0.98), + vec2(0.02, 0.50), + vec2(0.98, 0.50), + ); + var auto_bg_valid = array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); + var auto_bg_energy = array(1e20, 1e20, 1e20, 1e20, 1e20, 1e20, 1e20, 1e20); + + if (num_neg == 0u && use_auto_bg && pos_count > 0u) { + for (var b = 0u; b < 8u; b = b + 1u) { + let bp = auto_bg_pts[b]; + let b_lab = sample_seed_oklab(bp, dims); + // Skip border sample if it is close spatially or in color to any positive seed + var ok = true; + for (var i = 0u; i < num_seeds; i = i + 1u) { + let s = u.seeds[i]; + if (s.z >= 0.0) { + let s_dist = length((bp - s.xy) * vec2(aspect, 1.0)); + let s_lab = sample_seed_oklab(s.xy, dims); + let c_dist = length(b_lab - s_lab); + if (s_dist < 0.10 || c_dist < 0.06) { + ok = false; + } + } + } + if (ok) { + let d_col = length(px_lab - b_lab); + let d_uv = (uv - bp) * vec2(aspect, 1.0); + let d_spa = length(d_uv); + let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sn2; + auto_bg_valid[b] = 1.0; + auto_bg_energy[b] = e; + min_e_neg = min(min_e_neg, e); + neg_count = neg_count + 1u; + } + } + } + + var prob = 0.0; + if (pos_count == 0u) { + prob = 0.0; + } else if (neg_count == 0u) { + // Uniform-color fallback: smooth spatial falloff around positive seeds + prob = exp(-(min_dspa_pos * min_dspa_pos) / (0.35 * 0.35)); + } else { + let m = min(min_e_pos, min_e_neg); + var sum_pos = 0.0; + var sum_neg = 0.0; + for (var i = 0u; i < num_seeds; i = i + 1u) { + let s = u.seeds[i]; + let w = max(s.w, 0.01); + let s_lab = sample_seed_oklab(s.xy, dims); + let d_col = length(px_lab - s_lab); + let d_uv = (uv - s.xy) * vec2(aspect, 1.0); + let d_spa = length(d_uv); + if (s.z >= 0.0) { + let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sp2; + sum_pos = sum_pos + w * exp(-min(e - m, 60.0)); + } else { + let e = d_col * d_col * inv_sc2 + d_spa * d_spa * inv_sn2; + sum_neg = sum_neg + w * exp(-min(e - m, 60.0)); + } + } + if (num_neg == 0u && use_auto_bg) { + for (var b = 0u; b < 8u; b = b + 1u) { + if (auto_bg_valid[b] > 0.5) { + sum_neg = sum_neg + 0.65 * exp(-min(auto_bg_energy[b] - m, 60.0)); + } + } + } + prob = sum_pos / max(sum_pos + sum_neg, 1e-6); + } + + store_dst(p, vec4(prob, prob, prob, prob)); +} + +// ----------------------------------------------------------------------------- +// Stage 2B: Joint-bilateral edge-aware alpha refinement +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn bilateral_refine_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let radius = clamp(i32(u.p[0].x + 0.5), 1, 6); + let sigma_s = max(u.p[0].y, 0.5); + let sigma_r = max(u.p[0].z, 0.01); + let stride = clamp(i32(u.p[0].w + 0.5), 1, 4); + + let inv_2s2 = 0.5 / (sigma_s * sigma_s); + let inv_2r2 = 0.5 / (sigma_r * sigma_r); + + let center_lab = rgb_to_oklab(load_clamped(src_a, p).rgb); + var acc_a = 0.0; + var acc_w = 0.0; + + for (var dy = -radius; dy <= radius; dy = dy + 1) { + for (var dx = -radius; dx <= radius; dx = dx + 1) { + let off = vec2(dx * stride, dy * stride); + let q = p + off; + let dist2 = f32(off.x * off.x + off.y * off.y); + let q_lab = rgb_to_oklab(load_clamped(src_a, q).rgb); + let dc = q_lab - center_lab; + let dc2 = dot(dc, dc); + let w = exp(-dist2 * inv_2s2 - dc2 * inv_2r2); + let qa = load_clamped(src_b, q).r; + acc_a = acc_a + w * qa; + acc_w = acc_w + w; + } + } + + let refined = clamp(acc_a / max(acc_w, 1e-6), 0.0, 1.0); + store_dst(p, vec4(refined, refined, refined, refined)); +} + +// ----------------------------------------------------------------------------- +// Stage 3A: Clover's exact `polish_alpha` (floor, ceiling, toe gamma, invert) +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn polish_alpha_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let uv = (vec2(gid.xy) + 0.5) / vec2(dims_u); + + let lo = u.p[0].x; + let hi = u.p[0].y; + let toe_gamma = max(u.p[0].z, 0.01); + let invert = u.p[0].w > 0.5; + + let raw_a = sample_bilinear(src_a, uv).r; + let denom = max(hi - lo, 1e-4); + var a = clamp((raw_a - lo) / denom, 0.0, 1.0); + + // Toe compression below 0.15 kills faint outer VAE haze while keeping wisps >= 0.15 crisp + if (a < 0.15 && abs(toe_gamma - 1.0) > 1e-5) { + a = pow(max(a / 0.15, 0.0), toe_gamma) * 0.15; + } + if (invert) { + a = 1.0 - a; + } + + store_dst(p, vec4(a, a, a, a)); +} + +// ----------------------------------------------------------------------------- +// Stage 3B: Separable morphological erode / dilate for `MatteContractExpand` +// ----------------------------------------------------------------------------- +fn morpho_1d(p: vec2, dir: vec2, signed_radius: f32) -> f32 { + let abs_r = min(abs(signed_radius), 64.0); + let r_int = i32(floor(abs_r)); + let frac = abs_r - f32(r_int); + let dilate = signed_radius > 0.0; + + var acc = load_clamped(src_a, p).r; + for (var i = 1; i <= r_int; i = i + 1) { + let a_pos = load_clamped(src_a, p + dir * i).r; + let a_neg = load_clamped(src_a, p - dir * i).r; + if (dilate) { + acc = max(acc, max(a_pos, a_neg)); + } else { + acc = min(acc, min(a_pos, a_neg)); + } + } + if (frac > 1e-4) { + let edge_i = r_int + 1; + let a_pos = load_clamped(src_a, p + dir * edge_i).r; + let a_neg = load_clamped(src_a, p - dir * edge_i).r; + let edge_v = select(min(acc, min(a_pos, a_neg)), max(acc, max(a_pos, a_neg)), dilate); + acc = mix(acc, edge_v, frac); + } + return clamp(acc, 0.0, 1.0); +} + +@compute @workgroup_size(8, 8) +fn morpho_h_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let a = morpho_1d(p, vec2(1, 0), u.p[0].x); + store_dst(p, vec4(a, a, a, a)); +} + +@compute @workgroup_size(8, 8) +fn morpho_v_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let a = morpho_1d(p, vec2(0, 1), u.p[0].x); + store_dst(p, vec4(a, a, a, a)); +} + +// ----------------------------------------------------------------------------- +// Stage 3C: Separable Gaussian blur (used by MatteBlur & 3-scale decontamination) +// ----------------------------------------------------------------------------- +fn gauss_blur_1d(p: vec2, dir: vec2, sigma: f32, max_r: i32) -> vec4 { + if (sigma < 0.05 || max_r <= 0) { + return load_clamped(src_a, p); + } + let inv_2s2 = 0.5 / (sigma * sigma); + var sum = load_clamped(src_a, p); + var sum_w = 1.0; + + for (var i = 1; i <= max_r; i = i + 1) { + let fi = f32(i); + let w = exp(-fi * fi * inv_2s2); + let c_pos = load_clamped(src_a, p + dir * i); + let c_neg = load_clamped(src_a, p - dir * i); + sum = sum + (c_pos + c_neg) * w; + sum_w = sum_w + 2.0 * w; + } + return sum / sum_w; +} + +@compute @workgroup_size(8, 8) +fn gauss_blur_h_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let sigma = max(u.p[0].x, 0.0); + let max_r = clamp(i32(u.p[0].y + 0.5), 0, 76); + store_dst(p, gauss_blur_1d(p, vec2(1, 0), sigma, max_r)); +} + +@compute @workgroup_size(8, 8) +fn gauss_blur_v_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let sigma = max(u.p[0].x, 0.0); + let max_r = clamp(i32(u.p[0].y + 0.5), 0, 76); + store_dst(p, gauss_blur_1d(p, vec2(0, 1), sigma, max_r)); +} + +// ----------------------------------------------------------------------------- +// Stage 3D: Clover's hair-safe normalized-convolution decontamination +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn decontam_init_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let orig = load_clamped(src_a, p); + let a = load_clamped(src_b, p).r; + // Pure solid interior weight: solid_w = clamp((alpha - 0.82) / 0.14, 0, 1) + let solid_w = clamp((a - 0.82) / 0.14, 0.0, 1.0); + store_dst(p, vec4(orig.rgb * solid_w, solid_w)); +} + +@compute @workgroup_size(8, 8) +fn decontam_merge_scale_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let prev = load_clamped(src_a, p); + let nd = load_clamped(src_b, p); + let den = nd.a; + var out_rgb = prev.rgb; + if (den > 1e-4) { + let filled = nd.rgb / max(den, 1e-4); + let blend_scale = clamp(den * 4.0, 0.0, 1.0); + out_rgb = mix(prev.rgb, filled, blend_scale); + } + store_dst(p, vec4(out_rgb, 1.0)); +} + +// ----------------------------------------------------------------------------- +// Stage 3E: Final hair-safe foreground blend, output mode & EffectMask composite +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn composite_output_op(@builtin(global_invocation_id) gid: vec3) { + let dims_u = textureDimensions(dst_tex); + if (gid.x >= dims_u.x || gid.y >= dims_u.y) { + return; + } + let p = vec2(gid.xy); + let orig = load_clamped(src_a, p); + let a = clamp(load_clamped(src_b, p).r, 0.0, 1.0); + let f_extrap = load_clamped(src_c, p).rgb; + + let decontam_strength = clamp(u.p[0].x, 0.0, 1.0); + let output_mode = i32(u.p[0].y + 0.5); + let blend = clamp(u.p[0].z, 0.0, 1.0); + let has_mask = u.p[0].w; + let mask_inv = u.p[1].x; + let mbm = u.p[1].y; + let skip = u.p[2]; + + // Blend clean extrapolated hair color into low-alpha strands (alpha < 0.85) + // while keeping 100% original pixels bit-exact in solid interior (alpha >= 0.94) + let w_orig = clamp((a - 0.85) / 0.09, 0.0, 1.0); + let f_decontam = mix(f_extrap, orig.rgb, w_orig); + let fg_rgb = mix(orig.rgb, f_decontam, decontam_strength); + + var effect = vec4(0.0); + if (output_mode == 1) { + // Matte / Alpha Only + effect = vec4(a, a, a, a); + } else if (output_mode == 2) { + // Overlay Preview (ruby-magenta translucent mask over footage) + let overlay_col = vec3(1.0, 0.15, 0.28); + effect = vec4(mix(orig.rgb, overlay_col, a * 0.45), 1.0); + } else { + // Premultiplied Cutout + effect = vec4(fg_rgb * a, a); + } + + let mask_v = read_mask(gid.xy, dims_u, has_mask, mask_inv); + let eff = clamp(blend * mask_v, 0.0, 1.0); + var out_c = mix(orig, effect, eff); + if (mbm > 0.5) { + out_c = out_c * mask_v; + } + let final_c = vec4( + select(out_c.r, orig.r, skip.x > 0.5), + select(out_c.g, orig.g, skip.y > 0.5), + select(out_c.b, orig.b, skip.z > 0.5), + select(out_c.a, orig.a, skip.w > 0.5), + ); + store_dst(p, final_c); +}