1//! Pluggable per-frame neural matte cache (`AutoMatteCache`) and optional native
2//! external SAM 2 + MatAnyone 2 / VideoMaMa worker launcher (`AutoMatteRunner`).
3
4use std::collections::{HashMap, VecDeque};
5use std::collections::hash_map::DefaultHasher;
6use std::hash::{Hash, Hasher};
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, Mutex};
9
10#[cfg(not(target_arch = "wasm32"))]
11use super::prompts::{PromptMode, PromptPoint, QualityTier};
12#[cfg(not(target_arch = "wasm32"))]
13use std::path::{Path, PathBuf};
14
15const DEFAULT_MAX_CACHED_MATTE_FRAMES: usize = 256;
16
17/// Single-channel linear alpha matte frame (`[0.0, 1.0]`, top-down row-major).
18#[derive(Clone, Debug)]
19pub struct CachedMatteFrame {
20 pub size: [u32; 2],
21 /// Row-major top-down alpha values in `[0.0, 1.0]` (`len == size[0] * size[1]`).
22 pub alpha: Vec<f32>,
23 /// Deterministic content hash used to key GPU textures and `NodeCache` entries.
24 pub content_hash: u64,
25}
26
27impl CachedMatteFrame {
28 /// Constructs a cached matte frame from linear `f32` alpha values in `[0.0, 1.0]`.
29 pub fn from_alpha_f32(size: [u32; 2], mut alpha: Vec<f32>) -> Self {
30 let expected = (size[0] as usize).saturating_mul(size[1] as usize);
31 alpha.resize(expected, 0.0);
32 for v in &mut alpha {
33 *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
34 }
35 let content_hash = hash_alpha(size, &alpha);
36 Self { size, alpha, content_hash }
37 }
38
39 /// Constructs a cached matte frame from 8-bit grayscale alpha bytes (`0..=255`).
40 pub fn from_alpha_u8(size: [u32; 2], bytes: &[u8]) -> Self {
41 let expected = (size[0] as usize).saturating_mul(size[1] as usize);
42 let mut alpha = Vec::with_capacity(expected);
43 for &b in bytes.iter().take(expected) {
44 alpha.push(f32::from(b) / 255.0);
45 }
46 Self::from_alpha_f32(size, alpha)
47 }
48
49 /// Decodes a PNG (grayscale 8/16-bit or RGBA) matte buffer into a [`CachedMatteFrame`].
50 pub fn from_png_bytes(bytes: &[u8]) -> Result<Self, String> {
51 let dyn_img = image::load_from_memory(bytes)
52 .map_err(|e| format!("failed to decode AutoMatte PNG: {e}"))?;
53 let w = dyn_img.width();
54 let h = dyn_img.height();
55 if w == 0 || h == 0 {
56 return Err("AutoMatte PNG has zero dimensions".into());
57 }
58 let alpha = match dyn_img {
59 image::DynamicImage::ImageLuma8(g) => {
60 g.as_raw().iter().map(|&v| f32::from(v) / 255.0).collect()
61 }
62 image::DynamicImage::ImageLuma16(g) => {
63 g.as_raw().iter().map(|&v| f32::from(v) / 65535.0).collect()
64 }
65 image::DynamicImage::ImageRgba8(rgba) => {
66 let raw = rgba.as_raw();
67 let all_opaque = raw.chunks_exact(4).all(|px| px[3] == 255);
68 if all_opaque {
69 raw.chunks_exact(4).map(|px| f32::from(px[0]) / 255.0).collect()
70 } else {
71 raw.chunks_exact(4).map(|px| f32::from(px[3]) / 255.0).collect()
72 }
73 }
74 other => {
75 let g = other.to_luma16();
76 g.as_raw().iter().map(|&v| f32::from(v) / 65535.0).collect()
77 }
78 };
79 Ok(Self::from_alpha_f32([w, h], alpha))
80 }
81
82 #[cfg(not(target_arch = "wasm32"))]
83 pub fn from_png_file(path: &Path) -> Result<Self, String> {
84 let bytes = std::fs::read(path)
85 .map_err(|e| format!("failed to read AutoMatte PNG {}: {e}", path.display()))?;
86 Self::from_png_bytes(&bytes)
87 }
88}
89
90fn hash_alpha(size: [u32; 2], alpha: &[f32]) -> u64 {
91 let mut h = DefaultHasher::new();
92 "automate-matte-v1".hash(&mut h);
93 size.hash(&mut h);
94 alpha.len().hash(&mut h);
95 // Stride-sample large frames + include endpoints so hashing stays sub-millisecond at 4K
96 let stride = (alpha.len() / 2048).max(1);
97 for (i, &v) in alpha.iter().enumerate().step_by(stride) {
98 i.hash(&mut h);
99 v.to_bits().hash(&mut h);
100 }
101 if let Some(&last) = alpha.last() {
102 last.to_bits().hash(&mut h);
103 }
104 h.finish()
105}
106
107#[derive(Default)]
108struct CacheInner {
109 frames: HashMap<(String, i64), Arc<CachedMatteFrame>>,
110 order: VecDeque<(String, i64)>,
111 max_entries: usize,
112}
113
114impl CacheInner {
115 fn new(max_entries: usize) -> Self {
116 Self {
117 frames: HashMap::new(),
118 order: VecDeque::new(),
119 max_entries: max_entries.max(1),
120 }
121 }
122
123 fn insert(&mut self, key: (String, i64), frame: Arc<CachedMatteFrame>) {
124 if self.frames.contains_key(&key) {
125 self.order.retain(|k| k != &key);
126 }
127 self.frames.insert(key.clone(), frame);
128 self.order.push_back(key);
129 while self.frames.len() > self.max_entries {
130 if let Some(oldest) = self.order.pop_front() {
131 self.frames.remove(&oldest);
132 } else {
133 break;
134 }
135 }
136 }
137}
138
139/// Thread-safe per-frame cached neural alpha store shared between `Engine` and optional
140/// background neural workers (SAM 2 + MatAnyone 2 / VideoMaMa).
141#[derive(Clone)]
142pub struct AutoMatteCache {
143 inner: Arc<Mutex<CacheInner>>,
144 generation: Arc<AtomicU64>,
145}
146
147impl Default for AutoMatteCache {
148 fn default() -> Self {
149 Self::new()
150 }
151}
152
153impl AutoMatteCache {
154 pub fn new() -> Self {
155 Self::with_capacity(DEFAULT_MAX_CACHED_MATTE_FRAMES)
156 }
157
158 pub fn with_capacity(max_entries: usize) -> Self {
159 Self {
160 inner: Arc::new(Mutex::new(CacheInner::new(max_entries))),
161 generation: Arc::new(AtomicU64::new(0)),
162 }
163 }
164
165 /// Monotonic counter incremented whenever frames are inserted or evicted explicitly.
166 pub fn generation(&self) -> u64 {
167 self.generation.load(Ordering::Relaxed)
168 }
169
170 pub fn insert_frame(&self, node_name: &str, frame: i64, matte: CachedMatteFrame) {
171 if let Ok(mut guard) = self.inner.lock() {
172 guard.insert((node_name.to_owned(), frame), Arc::new(matte));
173 self.generation.fetch_add(1, Ordering::Relaxed);
174 }
175 }
176
177 pub fn insert_alpha_f32(&self, node_name: &str, frame: i64, size: [u32; 2], alpha: Vec<f32>) {
178 self.insert_frame(node_name, frame, CachedMatteFrame::from_alpha_f32(size, alpha));
179 }
180
181 pub fn insert_alpha_u8(&self, node_name: &str, frame: i64, size: [u32; 2], alpha: &[u8]) {
182 self.insert_frame(node_name, frame, CachedMatteFrame::from_alpha_u8(size, alpha));
183 }
184
185 pub fn get_frame(&self, node_name: &str, frame: i64) -> Option<Arc<CachedMatteFrame>> {
186 let guard = self.inner.lock().ok()?;
187 guard
188 .frames
189 .get(&(node_name.to_owned(), frame))
190 .or_else(|| guard.frames.get(&("*".to_owned(), frame)))
191 .cloned()
192 }
193
194 /// Looks up `(node_name, frame)` in memory first, then optionally loads a per-frame PNG
195 /// sequence file from `cache_dir` on native targets.
196 pub fn get_or_load_frame(
197 &self,
198 node_name: &str,
199 frame: i64,
200 cache_dir: Option<&str>,
201 ) -> Option<Arc<CachedMatteFrame>> {
202 if let Some(hit) = self.get_frame(node_name, frame) {
203 return Some(hit);
204 }
205 #[cfg(not(target_arch = "wasm32"))]
206 if let Some(dir) = cache_dir {
207 if let Some(path) = resolve_cached_png_path(Path::new(dir), node_name, frame) {
208 if let Ok(decoded) = CachedMatteFrame::from_png_file(&path) {
209 let arc = Arc::new(decoded);
210 if let Ok(mut guard) = self.inner.lock() {
211 guard.insert((node_name.to_owned(), frame), arc.clone());
212 }
213 return Some(arc);
214 }
215 }
216 }
217 #[cfg(target_arch = "wasm32")]
218 let _ = cache_dir;
219 None
220 }
221
222 pub fn remove_node(&self, node_name: &str) {
223 if let Ok(mut guard) = self.inner.lock() {
224 guard.frames.retain(|(n, _), _| n != node_name);
225 guard.order.retain(|(n, _)| n != node_name);
226 self.generation.fetch_add(1, Ordering::Relaxed);
227 }
228 }
229
230 pub fn clear(&self) {
231 if let Ok(mut guard) = self.inner.lock() {
232 guard.frames.clear();
233 guard.order.clear();
234 self.generation.fetch_add(1, Ordering::Relaxed);
235 }
236 }
237
238 pub fn len(&self) -> usize {
239 self.inner.lock().map_or(0, |g| g.frames.len())
240 }
241
242 pub fn is_empty(&self) -> bool {
243 self.len() == 0
244 }
245}
246
247#[cfg(not(target_arch = "wasm32"))]
248pub(crate) fn resolve_cached_png_path(dir: &Path, node_name: &str, frame: i64) -> Option<PathBuf> {
249 if !dir.exists() {
250 return None;
251 }
252 let f = frame.max(0);
253 let candidates = [
254 dir.join(format!("{f:04}.png")),
255 dir.join(format!("{f:05}.png")),
256 dir.join(format!("{f:06}.png")),
257 dir.join(format!("{f}.png")),
258 dir.join(format!("frame_{f:04}.png")),
259 dir.join(format!("alpha_{f:04}.png")),
260 dir.join(format!("{node_name}_{f:04}.png")),
261 dir.join(node_name).join(format!("{f:04}.png")),
262 ];
263 candidates.into_iter().find(|p| p.is_file())
264}
265
266// -----------------------------------------------------------------------------
267// Native external neural matte runner (SAM 2 + MatAnyone 2 / VideoMaMa)
268// -----------------------------------------------------------------------------
269
270/// Configuration for invoking an external Python neural matting worker on native platforms.
271#[cfg(not(target_arch = "wasm32"))]
272#[derive(Clone, Debug)]
273pub struct AutoMatteWorkerConfig {
274 /// Python executable (e.g. `~/dev/magic-matte/.venv/bin/python` or `python3`).
275 pub python_bin: PathBuf,
276 /// Worker script path accepting `--input`, `--output-dir`, `--quality`, `--mode`,
277 /// `--start-frame`, `--end-frame`, and `--prompts`.
278 pub worker_script: PathBuf,
279 /// Directory where per-frame alpha PNGs (`0000.png`, ...) are written.
280 pub output_dir: PathBuf,
281}
282
283/// Job request submitted to [`AutoMatteRunner`].
284#[cfg(not(target_arch = "wasm32"))]
285#[derive(Clone, Debug)]
286pub struct AutoMatteJobRequest {
287 pub node_name: String,
288 pub input_path: PathBuf,
289 pub frame_range: [i64; 2],
290 pub quality_tier: QualityTier,
291 pub prompt_mode: PromptMode,
292 pub prompts: Vec<PromptPoint>,
293}
294
295/// Lifecycle state of an asynchronous neural matting job.
296#[cfg(not(target_arch = "wasm32"))]
297#[derive(Clone, Debug, PartialEq, Eq)]
298pub enum AutoMatteJobState {
299 Running,
300 Completed { frames_loaded: usize },
301 Failed(String),
302}
303
304/// Optional native helper to launch an external SAM 2 + MatAnyone 2 / VideoMaMa Python worker
305/// asynchronously or synchronously and populate an [`AutoMatteCache`].
306#[cfg(not(target_arch = "wasm32"))]
307#[derive(Clone)]
308pub struct AutoMatteRunner {
309 config: AutoMatteWorkerConfig,
310 cache: AutoMatteCache,
311 states: Arc<Mutex<HashMap<String, AutoMatteJobState>>>,
312}
313
314#[cfg(not(target_arch = "wasm32"))]
315impl AutoMatteRunner {
316 pub fn new(config: AutoMatteWorkerConfig, cache: AutoMatteCache) -> Self {
317 Self {
318 config,
319 cache,
320 states: Arc::new(Mutex::new(HashMap::new())),
321 }
322 }
323
324 /// Probes environment variables (`FISSION_AUTOMATTE_PYTHON`, `FISSION_AUTOMATTE_SCRIPT`)
325 /// without hardcoding any mandatory external dependency. Returns `None` if not configured.
326 pub fn from_env(output_dir: PathBuf, cache: AutoMatteCache) -> Option<Self> {
327 let python_bin = std::env::var_os("FISSION_AUTOMATTE_PYTHON").map(PathBuf::from)?;
328 let worker_script = std::env::var_os("FISSION_AUTOMATTE_SCRIPT").map(PathBuf::from)?;
329 if !python_bin.is_file() || !worker_script.is_file() {
330 return None;
331 }
332 Some(Self::new(
333 AutoMatteWorkerConfig { python_bin, worker_script, output_dir },
334 cache,
335 ))
336 }
337
338 pub fn config(&self) -> &AutoMatteWorkerConfig {
339 &self.config
340 }
341
342 pub fn cache(&self) -> &AutoMatteCache {
343 &self.cache
344 }
345
346 pub fn job_state(&self, node_name: &str) -> Option<AutoMatteJobState> {
347 self.states.lock().ok()?.get(node_name).cloned()
348 }
349
350 /// Runs the external worker synchronously and ingests produced PNG mattes into `self.cache`.
351 pub fn run_blocking(&self, req: &AutoMatteJobRequest) -> Result<usize, String> {
352 run_worker_once(&self.config, &self.cache, req)
353 }
354
355 /// Spawns a background OS thread running the configured external worker and populating
356 /// `self.cache` upon completion.
357 pub fn spawn_job(&self, req: AutoMatteJobRequest) -> Result<(), String> {
358 if !self.config.python_bin.is_file() {
359 return Err(format!(
360 "AutoMatte Python binary not found: {}",
361 self.config.python_bin.display()
362 ));
363 }
364 if !self.config.worker_script.is_file() {
365 return Err(format!(
366 "AutoMatte worker script not found: {}",
367 self.config.worker_script.display()
368 ));
369 }
370 let node_name = req.node_name.clone();
371 if let Ok(mut guard) = self.states.lock() {
372 guard.insert(node_name.clone(), AutoMatteJobState::Running);
373 }
374 let config = self.config.clone();
375 let cache = self.cache.clone();
376 let states = self.states.clone();
377 std::thread::Builder::new()
378 .name(format!("automate-worker-{node_name}"))
379 .spawn(move || {
380 let outcome = match run_worker_once(&config, &cache, &req) {
381 Ok(frames_loaded) => AutoMatteJobState::Completed { frames_loaded },
382 Err(msg) => AutoMatteJobState::Failed(msg),
383 };
384 if let Ok(mut guard) = states.lock() {
385 guard.insert(node_name, outcome);
386 }
387 })
388 .map_err(|e| format!("failed to spawn AutoMatte worker thread: {e}"))?;
389 Ok(())
390 }
391}
392
393#[cfg(not(target_arch = "wasm32"))]
394fn serialize_prompts_json(prompts: &[PromptPoint]) -> String {
395 let mut s = String::from("[");
396 for (i, pt) in prompts.iter().enumerate() {
397 if i > 0 {
398 s.push(',');
399 }
400 let label = if pt.positive { 1 } else { 0 };
401 s.push_str(&format!(
402 "{{\"x\":{:.6},\"y\":{:.6},\"label\":{label}}}",
403 pt.x, pt.y
404 ));
405 }
406 s.push(']');
407 s
408}
409
410#[cfg(not(target_arch = "wasm32"))]
411fn run_worker_once(
412 config: &AutoMatteWorkerConfig,
413 cache: &AutoMatteCache,
414 req: &AutoMatteJobRequest,
415) -> Result<usize, String> {
416 std::fs::create_dir_all(&config.output_dir)
417 .map_err(|e| format!("failed to create AutoMatte output dir: {e}"))?;
418
419 let quality_str = match req.quality_tier {
420 QualityTier::FastInteractive => "fast",
421 QualityTier::MatAnyone2 => "matanyone2",
422 QualityTier::HeroHair => "videomama",
423 };
424 let mode_str = match req.prompt_mode {
425 PromptMode::ClickPoints => "points",
426 PromptMode::AutoPerson => "person",
427 PromptMode::Object => "object",
428 };
429 let prompts_json = serialize_prompts_json(&req.prompts);
430
431 let output = std::process::Command::new(&config.python_bin)
432 .arg(&config.worker_script)
433 .arg("--input")
434 .arg(&req.input_path)
435 .arg("--output-dir")
436 .arg(&config.output_dir)
437 .arg("--quality")
438 .arg(quality_str)
439 .arg("--mode")
440 .arg(mode_str)
441 .arg("--start-frame")
442 .arg(req.frame_range[0].to_string())
443 .arg("--end-frame")
444 .arg(req.frame_range[1].to_string())
445 .arg("--prompts")
446 .arg(&prompts_json)
447 .output()
448 .map_err(|e| format!("failed to execute AutoMatte worker: {e}"))?;
449
450 if !output.status.success() {
451 let stderr = String::from_utf8_lossy(&output.stderr);
452 return Err(format!(
453 "AutoMatte worker exited with {}: {}",
454 output.status,
455 stderr.trim()
456 ));
457 }
458
459 let mut loaded = 0usize;
460 let start = req.frame_range[0];
461 let end = req.frame_range[1].max(start);
462 for frame in start..=end {
463 if let Some(path) = resolve_cached_png_path(&config.output_dir, &req.node_name, frame) {
464 if let Ok(decoded) = CachedMatteFrame::from_png_file(&path) {
465 cache.insert_frame(&req.node_name, frame, decoded);
466 loaded += 1;
467 }
468 }
469 }
470 Ok(loaded)
471}