M13.30: Content-Aware Fill in a job worker on its GPU

contentFill.generate sends its plan (FillPlan) to a browser job worker:
the layer's frames render in passes on the worker's WebGPU device, the PNG
sequence goes back to browser storage (Services::store_file), and the page
adds the fill layer when the plan returns (WorkerReply::Fill). The smoke
test checks it; docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-04 03:15:54 -04:00
co-authored by Claude Opus 5.5
parent 91f4a603a9
commit 3921e6c680
10 changed files with 350 additions and 71 deletions
+139 -59
View File
@@ -3,7 +3,10 @@
//! whole layer, render the result as a PNG sequence and add it as a "Fill" layer above the
//! source, like After Effects. The algorithms are `effectcraft_raster::inpaint` (Object:
//! flow-guided propagation + PatchMatch; Surface: propagation + one synthesised fill carried by
//! the flow; Edge Blend: membrane fill). It runs as a background job (Window ▸ Progress).
//! the flow; Edge Blend: membrane fill). It runs as a background job (Window ▸ Progress); in
//! the browser the job goes to a job worker ([`FillPlan`], `offload::WorkerJob::ContentFill`),
//! whose own WebGPU device renders the layer's frames in passes, and the files come back to
//! browser storage.
use std::sync::Arc;
@@ -11,7 +14,7 @@ use effectcraft_color::Label;
use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind, LayerId, LayerSource, build};
use effectcraft_raster::Image;
use effectcraft_raster::inpaint::{FillInput, FillMethod, FillOpts, dilate, fill_sequence};
use effectcraft_render::{EvalCtx, RenderOpts, Renderer};
use effectcraft_render::{Accelerator, EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -127,22 +130,118 @@ fn png(img: &Image) -> std::result::Result<Vec<u8>, String> {
}
fn default_dir(s: &Session, name: &str) -> String {
let base = s
.path
.as_deref()
.and_then(|p| std::path::Path::new(p).parent().map(|d| d.join("Fill")))
.unwrap_or_else(|| std::env::temp_dir().join("effectcraft-fill"));
let base = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent().map(|d| d.join("Fill"))).unwrap_or_else(|| {
// (the browser has no temporary folder: its storage)
if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/Fill") } else { std::env::temp_dir().join("effectcraft-fill") }
});
let safe: String = name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
let mut k = 1;
loop {
let d = base.join(format!("{safe}_Fill_{k}"));
if !d.exists() {
return d.to_string_lossy().to_string();
let ds = d.to_string_lossy().to_string();
if !s.services.exists(&ds) && !s.services.exists(&format!("{ds}/fill_00000.png")) {
return ds;
}
k += 1;
}
}
/// A fill job, detached from the session (it also travels to a browser job worker).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FillPlan {
pub comp: ItemId,
pub layer: LayerId,
/// The source layer's name.
pub name: String,
/// The layer's size (the frames' size).
pub width: u32,
pub height: u32,
/// Comp times of the filled frames.
pub times: Vec<Tick>,
/// `object`, `surface` or `edgeBlend`.
pub method: String,
pub lighting: f32,
/// Alpha expansion (px).
pub expand: usize,
/// Reference frame: (layer, comp time).
pub reference: Option<(LayerId, Tick)>,
/// Folder of the PNG sequence.
pub dir: String,
}
/// Run a fill: the layer's frames (rendered in passes with a job worker's GPU), the fill, the
/// PNG sequence written into `plan.dir` (`Services::store_file`). Returns the files.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_plan(
plan: &FillPlan,
project: &effectcraft_project::Project,
footage: &dyn FootageSource,
expr: Option<&dyn ExprHost>,
cache: &LayerCache,
services: &dyn crate::Services,
accel: Option<&dyn Accelerator>,
progress: &mut dyn FnMut(u64, u64) -> bool,
message: &mut dyn FnMut(&str),
) -> std::result::Result<Vec<String>, String> {
message("Reading frames");
let (cid, w, h) = (plan.comp, plan.width, plan.height);
let comp = project.comp(cid).ok_or("composition missing")?;
let layer = comp.layer(plan.layer).ok_or("layer missing")?;
let mut r = Renderer::new(project, footage, crate::offload::analysis_opts(accel));
r.expr = expr;
r.cache = Some(cache);
let r = &r;
let ctx0 = EvalCtx { expr, ..EvalCtx::new(project, cid, comp, Tick::ZERO) };
let times = &plan.times;
let n = times.len() as u64;
let mut frames = Vec::with_capacity(times.len());
let mut holes = Vec::with_capacity(times.len());
for (k, t) in times.iter().enumerate() {
let (img, hole) = crate::offload::in_passes(accel, |a| masked_frame(&r.with_accel(a), &ctx0.at(*t), layer, w, h)).await;
holes.push(dilate(&hole, w as usize, h as usize, plan.expand));
frames.push(img);
if !progress(k as u64 + 1, n * 3) {
return Err(crate::render_queue::CANCELLED.into());
}
}
if !holes.iter().any(|h| h.iter().any(|b| *b)) {
return Err("the layer has no transparent area to fill: draw a mask (Subtract) around what to remove".into());
}
let mut references = vec![];
if let Some((rl, rt)) = plan.reference
&& let Some(l) = comp.layer(rl)
{
let (img, hole) = crate::offload::in_passes(accel, |a| masked_frame(&r.with_accel(a), &ctx0.at(rt), l, w, h)).await;
if hole.iter().all(|b| !*b) {
let k = times.iter().enumerate().min_by_key(|(_, t)| (t.0 - rt.0).abs()).map(|(k, _)| k).unwrap_or(0);
references.push((k, img));
}
}
message("Filling");
let opts = FillOpts { method: FillMethod::from_name(&plan.method).unwrap_or_default(), lighting: plan.lighting, ..Default::default() };
let input = FillInput { frames, holes, references };
let out = fill_sequence(&input, &opts, &mut |d, t| progress(n + (d as u64 * n / t.max(1) as u64), n * 3)).ok_or(crate::render_queue::CANCELLED)?;
message("Writing the fill layer");
let dir = &plan.dir;
let mut paths = vec![];
for (k, img) in out.iter().enumerate() {
let path = std::path::Path::new(dir).join(format!("fill_{k:05}.png")).to_string_lossy().to_string();
services.store_file(&path, &png(img)?).map_err(|e| format!("{path}: {e}"))?;
paths.push(path);
if !progress(2 * n + k as u64 + 1, n * 3) {
return Err(crate::render_queue::CANCELLED.into());
}
}
Ok(paths)
}
/// Add the fill layer of a finished plan (one undo step).
pub(crate) fn apply_plan(s: &mut Session, plan: &FillPlan, paths: Vec<String>) -> Result<Value> {
let importer = s.importer.clone();
add_fill_layer(s, plan.comp, plan.layer, &plan.name, paths, (plan.width, plan.height), plan.times[0], plan.times.len(), importer)
}
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
let c = "contentFill.generate";
let (cid, lid) = layer_p(s, p, c)?;
@@ -184,61 +283,42 @@ fn generate(s: &mut Session, p: &Value) -> Result<Value> {
let expand = st.alpha_expansion.round().max(0.0) as usize;
let reference = st.reference_layer.filter(|r| comp.layer(*r).is_some()).map(|r| (r, Tick::from_seconds_f64(st.reference_time.unwrap_or(0.0))));
let dir = str_p(p, "outputDir").map(str::to_string).unwrap_or_else(|| default_dir(s, &layer.name));
let plan = FillPlan {
comp: cid,
layer: lid,
name: layer.name.clone(),
width: w,
height: h,
times,
method: opts.method.name().to_string(),
lighting: opts.lighting,
expand,
reference,
dir,
};
let wait = b_p(p, "wait").unwrap_or(false);
// The browser: a job worker (its own GPU), the page keeps running.
if !wait && s.offloads() {
s.offload_analysis(crate::offload::WorkerJob::ContentFill { plan: Box::new(plan) }).map_err(EngineError::Other)?;
return Ok(json!({"job": "contentFill", "started": true, "worker": true}));
}
let lf = LayerFrames::new(s, cid, lid);
let services = s.services.clone();
let importer = s.importer.clone();
let wait = b_p(p, "wait").unwrap_or(false);
let name = layer.name.clone();
s.spawn_task("contentFill", format!("Content-Aware Fill: {name}"), wait, move |ctl| {
ctl.message("Reading frames");
let project = lf.project.clone();
let comp = project.comp(cid).ok_or("composition missing")?;
let layer = comp.layer(lid).ok_or("layer missing")?;
let mut r = Renderer::new(&project, lf.footage.as_ref(), RenderOpts::default());
r.expr = lf.expr.as_deref();
r.cache = Some(&lf.cache);
let ctx0 = EvalCtx { expr: lf.expr.as_deref(), ..EvalCtx::new(&project, cid, comp, Tick::ZERO) };
let n = times.len() as u64;
let mut frames = Vec::with_capacity(times.len());
let mut holes = Vec::with_capacity(times.len());
for (k, t) in times.iter().enumerate() {
let (img, hole) = masked_frame(&r, &ctx0.at(*t), layer, w, h);
holes.push(dilate(&hole, w as usize, h as usize, expand));
frames.push(img);
if !ctl.progress(k as u64 + 1, n * 3) {
return Err(crate::render_queue::CANCELLED.into());
}
}
if !holes.iter().any(|h| h.iter().any(|b| *b)) {
return Err("the layer has no transparent area to fill: draw a mask (Subtract) around what to remove".into());
}
let mut references = vec![];
if let Some((rl, rt)) = reference
&& let Some(l) = comp.layer(rl)
{
let (img, hole) = masked_frame(&r, &ctx0.at(rt), l, w, h);
if hole.iter().all(|b| !*b) {
let k = times.iter().enumerate().min_by_key(|(_, t)| (t.0 - rt.0).abs()).map(|(k, _)| k).unwrap_or(0);
references.push((k, img));
}
}
ctl.message("Filling");
let input = FillInput { frames, holes, references };
let out = fill_sequence(&input, &opts, &mut |d, t| ctl.progress(n + (d as u64 * n / t.max(1) as u64), n * 3)).ok_or(crate::render_queue::CANCELLED)?;
ctl.message("Writing the fill layer");
std::fs::create_dir_all(&dir).map_err(|e| format!("{dir}: {e}"))?;
let mut paths = vec![];
for (k, img) in out.iter().enumerate() {
let path = std::path::Path::new(&dir).join(format!("fill_{k:05}.png")).to_string_lossy().to_string();
services.write_file(&path, &png(img)?).map_err(|e| format!("{path}: {e}"))?;
paths.push(path);
if !ctl.progress(2 * n + k as u64 + 1, n * 3) {
return Err(crate::render_queue::CANCELLED.into());
}
}
let start = times[0];
let count = times.len();
let apply: Apply = Box::new(move |s: &mut Session| add_fill_layer(s, cid, lid, &name, paths, (w, h), start, count, importer));
let paths = effectcraft_render::passes::block_on(run_plan(
&plan,
&lf.project,
lf.footage.as_ref(),
lf.expr.as_deref(),
&lf.cache,
services.as_ref(),
None,
&mut |d, t| ctl.progress(d, t),
&mut |m| ctl.message(m),
))?;
let apply: Apply = Box::new(move |s: &mut Session| add_fill_layer(s, cid, lid, &name, paths, (w, h), plan.times[0], plan.times.len(), importer));
Ok(apply)
})
}
+4
View File
@@ -262,6 +262,9 @@ impl Session {
{
out.push(info("roto", "roto", "Roto Brush propagation".into(), p.done, p.total, true, String::new()));
}
if let Some(j) = self.offloaded(crate::offload::JobKind::ContentFill) {
out.push(info("contentFill", "contentFill", "Content-Aware Fill".into(), j.progress.done, j.progress.total, true, String::new()));
}
for t in &self.tasks {
let s = lock(&t.ctl.state).clone();
out.push(info(&format!("task:{}", t.id), t.kind, t.label.clone(), s.done, s.total, !s.finished, s.message));
@@ -278,6 +281,7 @@ impl Session {
"warp" => self.stop_warp(),
"camera" => self.stop_camera(),
"roto" => self.stop_roto(),
"contentFill" => self.cancel_offloaded(crate::offload::JobKind::ContentFill),
"all" => {
let ids: Vec<String> = self.jobs().into_iter().map(|j| j.id).collect();
ids.iter().fold(false, |a, j| self.cancel_job(j) | a)
+87
View File
@@ -20,6 +20,7 @@
//! | Roto Brush Freeze | the freeze | the effect group |
//! | Roto Brush propagation | the propagation | segmentations ([`WorkerReply::Segs`], streamed while it runs) go into the page's segmentation cache |
//! | 3D Camera Tracker analysis | [`Session::start_camera`] | the effect's property group |
//! | Content-Aware Fill | the fill ([`crate::commands::content_fill::FillPlan`]) | its PNG files (to the host's storage), then the fill layer (one undo step) |
//!
//! Viewer frames go to a separate, long-lived frame worker fed with project diffs
//! ([`crate::remote`]).
@@ -107,6 +108,11 @@ pub enum WorkerJob {
method: MaskMethod,
times: Vec<Tick>,
},
/// Content-Aware Fill: the files go to the host's storage, the plan and their paths come
/// back as [`WorkerReply::Fill`].
ContentFill {
plan: Box<crate::commands::content_fill::FillPlan>,
},
}
impl WorkerJob {
@@ -119,6 +125,7 @@ impl WorkerJob {
WorkerJob::RotoPropagate { .. } => JobKind::RotoPropagate,
WorkerJob::Track { .. } => JobKind::Track,
WorkerJob::MaskTrack { .. } => JobKind::MaskTrack,
WorkerJob::ContentFill { .. } => JobKind::ContentFill,
}
}
@@ -132,6 +139,7 @@ impl WorkerJob {
| WorkerJob::RotoPropagate { comp, layer, effect, .. } => Some((comp, layer, effect)),
WorkerJob::Track { comp, layer, tracker, .. } => Some((comp, layer, tracker)),
WorkerJob::MaskTrack { comp, layer, mask, .. } => Some((comp, layer, mask)),
WorkerJob::ContentFill { ref plan } => Some((plan.comp, plan.layer, 0)),
}
}
}
@@ -146,6 +154,7 @@ pub enum JobKind {
RotoPropagate,
Track,
MaskTrack,
ContentFill,
}
impl JobKind {
@@ -159,6 +168,7 @@ impl JobKind {
JobKind::RotoPropagate => "Roto Brush Propagation",
JobKind::Track => "Analyze Track",
JobKind::MaskTrack => "Track Mask",
JobKind::ContentFill => "Content-Aware Fill",
}
}
}
@@ -191,6 +201,12 @@ pub enum WorkerReply {
Segs {
segs: Vec<SegData>,
},
/// A Content-Aware Fill finished: its plan and the PNG files written (already in the
/// host's storage).
Fill {
plan: Box<crate::commands::content_fill::FillPlan>,
files: Vec<String>,
},
Failed {
error: String,
},
@@ -448,6 +464,7 @@ async fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), Stri
.await
}
WorkerJob::RotoPropagate { comp, layer, effect, direction } => propagate(s, comp, layer, effect, direction, post).await,
WorkerJob::ContentFill { plan } => fill(s, *plan, post).await,
WorkerJob::Track { comp, layer, tracker, direction, settings, points, times } => {
analysis(s, kind, target, post, |s| {
let work = crate::tracking::Work {
@@ -485,6 +502,36 @@ async fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), Stri
}
}
/// Content-Aware Fill in a worker: the layer's frames render on the worker's GPU (in passes),
/// the files are written through the session's services (the browser: back to the page's
/// storage) and the plan comes back for the page to add the fill layer.
async fn fill(s: &mut Session, plan: crate::commands::content_fill::FillPlan, post: Post) -> Result<(), String> {
let p = post.clone();
let mut last = None::<web_time::Instant>;
let mut progress = move |done: u64, total: u64| {
if last.is_none_or(|t: web_time::Instant| t.elapsed().as_millis() >= 100) {
last = Some(web_time::Instant::now());
p(WorkerReply::Progress { done, total });
}
true
};
let accel = job_accel();
let files = crate::commands::content_fill::run_plan(
&plan,
&s.project,
s.footage.as_ref(),
s.expr.as_deref(),
&s.layer_cache,
s.services.as_ref(),
accel.as_deref(),
&mut progress,
&mut |_| {},
)
.await?;
post(WorkerReply::Fill { plan: Box::new(plan), files });
Ok(())
}
/// Roto Brush propagation in a worker: the segmentations stream back (at most every 250 ms)
/// as they are computed, so stopping the job keeps what was propagated.
async fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: crate::roto::Direction, post: Post) -> Result<(), String> {
@@ -674,6 +721,7 @@ impl Session {
}
let mut changed = false;
let mut results = vec![];
let mut fills = vec![];
for j in &mut self.offloaded {
if j.progress.cancelled {
continue;
@@ -686,6 +734,7 @@ impl Session {
j.progress.total = total;
}
WorkerReply::Group { comp, layer, group, message } => results.push((j.kind, comp, layer, group, message)),
WorkerReply::Fill { plan, files } => fills.push((plan, files)),
WorkerReply::Segs { segs } => {
for sd in &segs {
sd.store();
@@ -699,6 +748,13 @@ impl Session {
}
j.progress.elapsed = j.started.elapsed().as_secs_f64();
}
for (plan, files) in fills {
let n = files.len();
match crate::commands::content_fill::apply_plan(self, &plan, files) {
Ok(_) => self.events.push(Event::Toast { message: format!("Content-Aware Fill: {n} frame(s) filled"), error: false }),
Err(e) => self.events.push(Event::Toast { message: format!("Content-Aware Fill: {e}"), error: true }),
}
}
for (kind, comp, layer, group, message) in results {
let uid = group.uid;
let r = self.edit(kind.label(), None, |p, _| {
@@ -821,6 +877,21 @@ mod tests {
method: MaskMethod::Perspective,
times: vec![Tick::from_seconds_f64(1.0)],
},
WorkerJob::ContentFill {
plan: Box::new(crate::commands::content_fill::FillPlan {
comp,
layer: LayerId(2),
name: "Clip".into(),
width: 4,
height: 3,
times: vec![Tick::ZERO],
method: "object".into(),
lighting: 0.5,
expand: 1,
reference: Some((LayerId(1), Tick::ZERO)),
dir: "/Fill/Clip_Fill_1".into(),
}),
},
];
for job in reqs {
let kind = job.kind();
@@ -839,6 +910,22 @@ mod tests {
WorkerReply::Progress { done: 1, total: 2 },
WorkerReply::Group { comp, layer: LayerId(1), group: Box::new(g), message: "ok".into() },
WorkerReply::Segs { segs: vec![SegData::new(5, &effectcraft_track::roto::FrameSeg::empty(4, 3))] },
WorkerReply::Fill {
plan: Box::new(crate::commands::content_fill::FillPlan {
comp,
layer: LayerId(2),
name: "Clip".into(),
width: 4,
height: 3,
times: vec![Tick::ZERO],
method: "object".into(),
lighting: 0.5,
expand: 1,
reference: Some((LayerId(1), Tick::ZERO)),
dir: "/Fill/Clip_Fill_1".into(),
}),
files: vec!["/Fill/Clip_Fill_1/fill_00000.png".into()],
},
WorkerReply::Failed { error: "boom".into() },
WorkerReply::Done,
] {
+52
View File
@@ -335,6 +335,58 @@ fn content_aware_fill_runs_in_the_background() {
std::fs::remove_dir_all(&out).unwrap();
}
/// The browser: Content-Aware Fill goes to a job worker (its files written through the
/// worker's services), and the page adds the fill layer when the plan comes back.
#[test]
fn content_aware_fill_runs_in_a_job_worker() {
#[derive(Default)]
struct Manual(std::sync::Mutex<Vec<(crate::offload::WorkerRequest, Arc<crate::offload::Inbox>)>>);
impl crate::offload::Offload for Manual {
fn start(&self, req: crate::offload::WorkerRequest, inbox: Arc<crate::offload::Inbox>) -> std::result::Result<(), String> {
self.0.lock().unwrap().push((req, inbox));
Ok(())
}
fn cancel(&self, _: u64) {}
}
let (mut s, cid, clip, _) = setup(48, 32, 0.2, |f| {
let mut img = Image::new(48, 32);
for y in 0..32 {
for x in 0..48 {
img.set(x, y, bg(x as f32 + f as f32, y as f32));
}
}
img
});
let off = Arc::new(Manual::default());
s.offload = Some(off.clone());
s.execute("layer.addMask", json!({"rect": [20.0, 10.0, 8.0, 8.0], "mode": "subtract"})).unwrap();
let out = tmp("cafworker");
let r = s.execute("contentFill.generate", json!({"method": "edgeBlend", "outputDir": out.to_string_lossy()})).unwrap();
assert_eq!((r["job"].as_str(), r["worker"].as_bool()), (Some("contentFill"), Some(true)), "{r}");
assert!(s.jobs().iter().any(|j| j.id == "contentFill"));
let (req, inbox) = off.0.lock().unwrap().pop().unwrap();
let back: crate::offload::WorkerRequest = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap();
// The worker: the same footage, the default (file system) services.
let mut w = Session { footage: s.footage.clone(), ..Default::default() };
let post: crate::offload::Post = std::rc::Rc::new(move |r| inbox.push(r));
crate::offload::run_request(&mut w, back, &post);
s.poll_offload();
let comp = s.project.comp(cid).unwrap().clone();
let i = comp.layers.iter().position(|l| l.id == clip).unwrap();
assert!(i > 0, "a fill layer above the source");
let fill = &comp.layers[i - 1];
assert!(fill.name.starts_with("Fill 1"), "{}", fill.name);
let LayerSource::Footage { item } = fill.source else { panic!("footage") };
let Some(ItemKind::Footage(f)) = s.project.item(item).map(|i| &i.kind) else { panic!() };
assert_eq!(f.sequence.len(), 5);
assert!(f.sequence.iter().all(|p| std::path::Path::new(p).exists()));
assert!(s.jobs().is_empty());
// One undo step.
assert!(s.undo());
assert_eq!(s.project.comp(cid).unwrap().layers.len(), comp.layers.len() - 1);
std::fs::remove_dir_all(&out).unwrap();
}
// ---------------------------------------------------------------- Scene Edit Detection
fn shot_frame(f: u32) -> Image {