#783: Object Matte tracks in the background and freezes

Problem: Object Matte computed its frames only on demand while rendering, so
playing a shot stalled on every untracked frame, there was no progress or way
to stop, and nothing kept the mattes once computed.

Fix: Object Matte runs through Roto Brush's job machinery (one job slot,
cancellable with roto.cancel, a worker thread on the desktop, a Web Worker in
the browser, never the UI thread). objectMatte.propagate computes the frames
around the reference frame (clipped to the layer) outward, filling the same
content-keyed segmentation cache the renderer reads; the engine's sync now
queues an instance for background tracking when its frames or prompt change.
objectMatte.freeze stores the final mattes in a new hidden Frozen parameter
(Roto Brush's FrozenCache format) under a key of the input, prompt, span,
model and matte settings; renders use them without segmenting while the key
matches; a frozen prompt is refused until objectMatte.unfreeze. Freeze is one
undo step and is dropped if the prompt changed meanwhile.
objectMatte.status reports progress, frozen state and computed frames. Effect
Controls shows Freeze / Unfreeze and Track / Stop with a status line (progress
banner). The frontend now polls Roto Brush / Object Matte jobs on their own:
before, a finished job (and so a Freeze result) was only picked up while a
Warp Stabilizer job was active. Job progress is set before the worker starts.

Tests: engine tests_roto::object_matte_background_job_cancel_and_freeze
(queued by the edit, returns at once with progress, cancel keeps a partial
result, completion computes all 25 frames, frozen renders recompute nothing,
unfreeze recomputes, undo restores); effects object_matte job_frames and
frozen-matte tests (stored pattern used, key mismatch and damaged data
ignored); ui-egui ui_object_matte Effect Controls Freeze end to end.
docs/agents.md: Object Matte section; docs/effects.md regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76
2026-10-11 14:02:50 +02:00
co-authored by Claude Opus 5.5
parent 0c695cff77
commit 560767dfe7
11 changed files with 618 additions and 54 deletions
+184 -9
View File
@@ -16,8 +16,12 @@
//! ([`crate::roto::cached`]): the chain seed holds the engine-maintained Input Key (what the
//! frames are made of), the layer size, the frame rate, the mode and the model, and every
//! frame's key the prompt, so edits upstream or to the prompt recompute it and undo never sees a
//! stale matte. **Feather**, **Contrast** and **Shift Edge** shape the matte, **Invert** keeps
//! everything but the object and **View ▸ Matte** shows the matte in grey.
//! stale matte. The engine fills that cache in a background job (`objectMatte.propagate`,
//! outward from the reference frame over [`job_frames`]) and **Freeze** (`objectMatte.freeze`)
//! stores the final mattes in the hidden **Frozen** parameter ([`FrozenCache`], as Roto Brush
//! does): they are used, without segmenting, while [`frozen_key`] still matches. **Feather**,
//! **Contrast** and **Shift Edge** shape the matte, **Invert** keeps everything but the object
//! and **View ▸ Matte** shows the matte in grey.
use std::sync::Arc;
@@ -26,10 +30,10 @@ use effectcraft_project::ParamUi;
use effectcraft_raster::Image;
use effectcraft_segment::MaskModel;
use effectcraft_track::roto::refine::MatteParams;
use effectcraft_track::roto::{RotoData, SegOpts, Stroke, StrokeKind};
use effectcraft_track::roto::{FrameSeg, RotoData, SegOpts, Stroke, StrokeKind, rle};
use rayon::prelude::*;
use crate::roto::{self, Chain, INPUT_KEY};
use crate::roto::{self, Chain, FROZEN, FrozenCache, INPUT_KEY};
use crate::warp_stab::param;
use crate::{Buf, EffectCtx, EffectSpec, Params, num, p, popup, slider};
@@ -71,6 +75,7 @@ pub fn specs() -> Vec<EffectSpec> {
p("invert", "Invert", Value::Bool(false), ParamUi::Checkbox),
p("view", "View", Value::Enum(0), popup(&VIEWS)),
p(INPUT_KEY, "Input Key", Value::Str(String::new()), ParamUi::Hidden),
p(FROZEN, "Frozen", Value::Str(String::new()), ParamUi::Hidden),
],
render,
gpu: false,
@@ -197,6 +202,127 @@ pub fn seed(params: &Params, layer_size: [f64; 2], fps: f64, model: Option<&dyn
h
}
/// The layer frames a background job computes, outward from the reference frame: the tracked
/// span (Frames Before / After around it), clipped to `limits` (the layer's frames). Without
/// Track Object, the same frames, each segmented on its own.
pub fn job_frames(params: &Params, limits: [i64; 2]) -> Vec<i64> {
let base = reference_frame(params);
let [before, after] = reach(params);
let (lo, hi) = (base.saturating_sub(before).max(limits[0]), base.saturating_add(after).min(limits[1]));
if base < limits[0] || base > limits[1] {
return vec![];
}
let mut v = vec![base];
v.extend(base.saturating_add(1)..=hi);
v.extend((lo..base).rev());
v
}
/// The segmentation chain the matte of layer frame `f` comes from (`None`: no usable prompt).
pub fn chain(params: &Params, layer_size: [f64; 2], fps: f64, f: i64, scale: f64, model: Option<Arc<dyn MaskModel>>) -> Option<Chain> {
let data = roto_data(params, layer_size, f, model.is_some())?;
let keys = data.chain_keys(seed(params, layer_size, fps, model.as_deref()));
Some(Chain { data: Arc::new(data), keys, opts: seg_opts(scale), refine_radius: 0.0, model })
}
/// Frame `f`'s segmentation at full resolution, computing what is missing (the background
/// job's step). `None` outside the tracked span, without a prompt, or when cancelled.
pub fn ensure(
params: &Params,
layer_size: [f64; 2],
fps: f64,
f: i64,
model: Option<Arc<dyn MaskModel>>,
frame: &mut dyn FnMut(i64) -> Option<Arc<Image>>,
cancel: &dyn Fn() -> bool,
) -> Option<Arc<FrameSeg>> {
let ch = chain(params, layer_size, fps, f, 1.0, model)?;
if !ch.data.in_span(f) {
return None;
}
ch.ensure(f, frame, cancel)
}
/// The chain key of each of `frames` (what a computed segmentation is cached under).
pub fn frame_keys(params: &Params, layer_size: [f64; 2], fps: f64, frames: &[i64], model: Option<Arc<dyn MaskModel>>) -> Vec<(i64, u64)> {
if tracks(params) {
let Some(ch) = chain(params, layer_size, fps, 0, 1.0, model) else { return vec![] };
return frames.iter().filter_map(|f| Some((*f, *ch.keys.get(f)?))).collect();
}
frames.iter().filter_map(|f| Some((*f, *chain(params, layer_size, fps, *f, 1.0, model.clone())?.keys.get(f)?))).collect()
}
/// What frozen mattes depend on: what the frames are (the seed: Input Key, size, rate, mode,
/// model), the prompt, the tracked span and the matte settings.
pub fn frozen_key(params: &Params, layer_size: [f64; 2], fps: f64, model: Option<&dyn MaskModel>) -> String {
let mut h = seed(params, layer_size, fps, model);
let base = reference_frame(params);
if let Some(st) = prompt_strokes(params, layer_size, base, model.is_some()) {
fnv(&mut h, serde_json::to_string(&st).unwrap_or_default().as_bytes());
}
for v in [base, reach(params)[0], reach(params)[1]] {
fnv(&mut h, &v.to_le_bytes());
}
fnv(&mut h, format!("{:?}", matte_params(params)).as_bytes());
format!("{h:016x}")
}
/// Whether the instance is frozen (has frozen mattes).
pub fn is_frozen(params: &Params) -> bool {
!s(params, FROZEN).is_empty()
}
/// Frame `f`'s frozen matte on a `w`×`h` grid, when the instance is frozen, the mattes still
/// match ([`frozen_key`]) and `f` is one of them.
pub fn frozen_alpha(params: &Params, layer_size: [f64; 2], fps: f64, f: i64, w: usize, h: usize, model: Option<&dyn MaskModel>) -> Option<Vec<f32>> {
let j = s(params, FROZEN);
if j.is_empty() {
return None;
}
let fc = frozen_cache(j)?;
if fc.key != frozen_key(params, layer_size, fps, model) {
return None;
}
let fr = fc.frames.get(&f)?;
let a = rle::decode(&fr.a)?;
let [fw, fh] = fc.size;
if fw == 0 || fh == 0 || a.len() != fw.checked_mul(fh)? {
return None;
}
let af: Vec<f32> = a.iter().map(|v| *v as f32 / 255.0).collect();
if fw == w && fh == h {
return Some(af);
}
let mut out = vec![0.0f32; w * h];
for y in 0..h {
for x in 0..w {
let (sx, sy) = ((x as f64 + 0.5) * fw as f64 / w as f64, (y as f64 + 0.5) * fh as f64 / h as f64);
out[y * w + x] = effectcraft_track::roto::matting::sample(&af, fw, fh, sx, sy);
}
}
Some(out)
}
/// The parsed Frozen parameter (parsed once per content).
fn frozen_cache(j: &str) -> Option<Arc<FrozenCache>> {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static C: OnceLock<Mutex<HashMap<u64, Arc<FrozenCache>>>> = OnceLock::new();
let mut h = 0xcbf2_9ce4_8422_2325;
fnv(&mut h, j.as_bytes());
let c = C.get_or_init(Default::default);
if let Some(d) = c.lock().unwrap_or_else(|e| e.into_inner()).get(&h) {
return Some(d.clone());
}
let d = Arc::new(FrozenCache::from_json(j)?);
let mut m = c.lock().unwrap_or_else(|e| e.into_inner());
if m.len() > 8 {
m.clear();
}
m.insert(h, d.clone());
Some(d)
}
/// Segmentation settings at `scale` (Roto Brush's defaults).
fn seg_opts(scale: f64) -> SegOpts {
SegOpts { scale, search_radius: 15.0, motion_threshold: 10.0, motion_damping: 20.0, best: false }
@@ -242,12 +368,10 @@ pub fn frame_matte(
frame: &mut dyn FnMut(i64) -> Option<Arc<Image>>,
cancel: &dyn Fn() -> bool,
) -> FrameMatte {
let Some(data) = roto_data(params, layer_size, f, model.is_some()) else { return FrameMatte::NoPrompt };
if !data.in_span(f) {
let Some(chain) = chain(params, layer_size, fps, f, scale, model) else { return FrameMatte::NoPrompt };
if !chain.data.in_span(f) {
return FrameMatte::Outside;
}
let keys = data.chain_keys(seed(params, layer_size, fps, model.as_deref()));
let chain = Chain { data: Arc::new(data), keys, opts: seg_opts(scale), refine_radius: 0.0, model };
let Some(seg) = chain.ensure(f, frame, cancel) else { return FrameMatte::Outside };
let (w, h) = (img.width as usize, img.height as usize);
let seg = if seg.w == w && seg.h == h { (*seg).clone() } else { roto::resample(&seg, w, h) };
@@ -275,7 +399,12 @@ fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
let im = roto::layer_grid(&other, layer_size);
(im.width as usize == w && im.height as usize == h).then(|| Arc::new(im))
};
let alpha = match frame_matte(ctx.params, layer_size, fps, f, sc, &img, roto::installed_model(), &mut frame, &|| false) {
let model = roto::installed_model();
// Frozen mattes are used as they are (no segmentation).
if let Some(a) = frozen_alpha(ctx.params, layer_size, fps, f, w, h, model.as_deref()) {
return compose(&buf, Some(&a), w, h, b(ctx.params, "invert"), param(ctx.params, "view").map(Value::as_enum).unwrap_or(0) == 1);
}
let alpha = match frame_matte(ctx.params, layer_size, fps, f, sc, &img, model, &mut frame, &|| false) {
FrameMatte::Alpha(a) if a.len() == w * h => Some(a),
FrameMatte::NoPrompt => return buf,
_ => None,
@@ -513,4 +642,50 @@ mod tests {
let _ = frame_matte(&p, [100.0, 80.0], 25.0, 0, 0.5, &half, Some(stub.clone()), &mut frame, &|| false);
assert_eq!(*stub.bbox.lock().unwrap(), Some([37.0, 27.0, 50.0, 40.0]));
}
#[test]
fn job_frames_go_outward_from_the_reference_frame_inside_the_layer() {
let p = params(&[
("objectTracking/referenceFrame", Value::Scalar(5.0)),
("objectTracking/framesBefore", Value::Scalar(2.0)),
("objectTracking/framesAfter", Value::Scalar(3.0)),
]);
assert_eq!(job_frames(&p, [0, 100]), [5, 6, 7, 8, 4, 3]);
assert_eq!(job_frames(&p, [4, 6]), [5, 6, 4]);
assert!(job_frames(&p, [10, 20]).is_empty());
let huge = params(&[("objectTracking/referenceFrame", Value::Scalar(1e300)), ("objectTracking/framesAfter", Value::Scalar(f64::INFINITY))]);
assert!(job_frames(&huge, [0, 100]).is_empty());
}
/// Frozen mattes are used as stored while their key matches (no segmentation: a stored
/// pattern the segmentation could never produce comes out), and ignored once it doesn't.
#[test]
fn frozen_mattes_are_used_while_their_key_matches() {
let mut p = params(&[("objectPoint", Value::Vec2([40.0, 40.0])), ("objectTracking/framesAfter", Value::Scalar(3.0))]);
p.values.insert(INPUT_KEY.into(), Value::Str("frozen-test".into()));
// Left half opaque on frame 2.
let alpha: Vec<f32> = (0..100 * 80).map(|i| ((i % 100) < 50) as u8 as f32).collect();
let mut fc = FrozenCache { key: frozen_key(&p, [100.0, 80.0], 25.0, None), size: [100, 80], ..Default::default() };
fc.frames.insert(2, roto::freeze_frame(&alpha, &[]));
p.values.insert(FROZEN.into(), Value::Str(fc.to_json()));
assert!(is_frozen(&p));
let out = run(&p, 2);
assert!(out.data[40 * 100 + 10][3] > 0.99 && out.data[40 * 100 + 90][3] < 0.01, "the frozen matte is used");
// At half resolution too.
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 50, 40, None).map(|a| (a[20 * 50 + 5], a[20 * 50 + 45])), Some((1.0, 0.0)));
// A frame without a frozen matte is computed (the disk).
assert!(wrong(&run(&p, 1), 42.0) < 30);
// Another prompt: the frozen mattes no longer apply.
p.values.insert("objectPoint".into(), Value::Vec2([41.0, 40.0]));
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 100, 80, None), None);
assert!(wrong(&run(&p, 2), 44.0) < 30);
// Damaged frozen data is ignored, not a crash.
p.values.insert(FROZEN.into(), Value::Str("{\"key\": 3, \"frames\": [".into()));
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 100, 80, None), None);
let mut fc2 = fc.clone();
fc2.size = [usize::MAX, 2];
p.values.insert("objectPoint".into(), Value::Vec2([40.0, 40.0]));
p.values.insert(FROZEN.into(), Value::Str(fc2.to_json()));
assert_eq!(frozen_alpha(&p, [100.0, 80.0], 25.0, 2, 100, 80, None), None);
}
}