Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

M15.2: merge main (disk cache, 3D Camera Tracker); camera analysis in workers; no disk cache on wasm32

Brandon Thomas4fffbace5c30
diff --cc crates/engine/src/camera_track.rs
index 000000000,1b984aac2..0b823135a
mode 000000,100644..100644
--- a/crates/engine/src/camera_track.rs
+++ b/crates/engine/src/camera_track.rs
@@@ -1,0 -1,640 +1,655 @@@
+ //! 3D Camera Tracker runtime: the analysis job (`camera.analyze`, `track.camera`), keeping
+ //! analyses valid, and turning a solve into composition layers (`camera.createFromSolve`).
+ //!
+ //! The job renders the layer's input to the effect (`Renderer::layer_input`) for every frame
+ //! between the layer's In and Out points on a background thread and tracks features through
+ //! them (step 1 of 2, "Analyzing in background"), then solves the camera (step 2, "Solving
+ //! camera"). When only the solve settings changed (Shot Type, Angle of View, Solve Method,
+ //! deleted points) the stored tracks are re-solved without re-tracking. Results are written into
+ //! the effect's hidden parameters as one undo step; edits that change the layer's frames clear
+ //! them and queue the effect again ([`invalidate`], run after every edit), like After Effects.
+ //!
+ //! Composition space: the solve's canonical frame maps to comp world by
+ //! [`CameraSolve::world`] with the zoom of the first solved frame (focal length × the layer's
+ //! scale in the comp), so the "3D Tracker Camera" reproduces the footage's view and created
+ //! layers sit on the selected points.
+
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::{Arc, Mutex};
+
+ use effectcraft_effects::camera_tracker::{self as ct, AVERAGE_ERROR, METHOD_USED, SOLVE, SOLVE_KEY, TRACKS, TRACKS_KEY};
+ use effectcraft_keyframe::{Keyframe, Value};
+ use effectcraft_project::{AutoOrient, GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid};
+ use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
+ use effectcraft_time::Tick;
+ use effectcraft_track::camtrack::linalg::{self, Similarity, V3};
+ use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer};
+ use serde::Serialize;
+
++use crate::offload::JobKind;
+ use crate::tracking::lock;
+ use crate::warp::{analysis_times, signature};
+ use crate::{Event, Session};
+
+ /// Live analysis progress (serde for agents / the control channel).
+ #[derive(Clone, Debug, Default, Serialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct CameraProgress {
+ /// 1 = tracking features, 2 = solving the camera.
+ pub step: u8,
+ pub done: u64,
+ pub total: u64,
+ pub elapsed: f64,
+ pub fps: f64,
+ pub finished: bool,
+ pub cancelled: bool,
+ pub error: Option<String>,
+ /// Re-solving stored tracks (no tracking step).
+ pub solve_only: bool,
+ }
+
+ impl CameraProgress {
+ /// The viewer banner text, as After Effects words it.
+ pub fn banner(&self) -> String {
+ match self.step {
+ 2 => "Solving camera".into(),
+ _ => {
+ let pc = (100 * self.done).checked_div(self.total).unwrap_or(0);
+ format!("Analyzing in background (step 1 of 2): {pc}%")
+ }
+ }
+ }
+ }
+
+ struct CamResult {
+ /// New tracks (None for a re-solve).
+ tracks: Option<CameraTracks>,
+ solve: Result<CameraSolve, String>,
+ }
+
+ #[derive(Default)]
+ pub struct CameraShared {
+ pub cancel: AtomicBool,
+ pub state: Mutex<CameraProgress>,
+ result: Mutex<Option<CamResult>>,
+ }
+
+ /// A running (or finished, not yet polled) camera analysis.
+ pub struct CameraJob {
+ pub shared: Arc<CameraShared>,
+ thread: Option<std::thread::JoinHandle<()>>,
+ pub comp: ItemId,
+ pub layer: LayerId,
+ pub effect: Uid,
+ /// The layer signature the tracks are made from, and the solve settings key.
+ key: String,
+ solve_key: String,
+ }
+
+ impl CameraJob {
+ pub fn is_finished(&self) -> bool {
+ lock(&self.shared.state).finished
+ }
+ pub fn progress(&self) -> CameraProgress {
+ lock(&self.shared.state).clone()
+ }
+ }
+
+ struct CamWork {
+ project: Arc<Project>,
+ footage: Arc<dyn FootageSource>,
+ expr: Option<Arc<dyn ExprHost>>,
+ cache: Arc<LayerCache>,
+ comp: ItemId,
+ layer: LayerId,
+ effect_index: usize,
+ size: [f64; 2],
+ detailed: bool,
+ times: Vec<Tick>,
+ /// Stored tracks to re-solve (skips step 1).
+ tracks: Option<Arc<CameraTracks>>,
+ settings: SolveSettings,
+ }
+
+ pub(crate) fn is_tracker(g: &PropGroup) -> bool {
+ matches!(&g.kind, GroupKind::Effect { effect } if effect == ct::ID)
+ }
+
+ fn str_of(g: &PropGroup, m: &str) -> String {
+ match g.prop(m).map(|p| &p.value) {
+ Some(Value::Str(s)) => s.clone(),
+ _ => String::new(),
+ }
+ }
+
+ /// What a tracker's tracks are made from: the layer's frames and Detailed Analysis.
+ fn tracks_key(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> String {
+ let detailed = effectcraft_effects::warp_stab::param(&static_params(g), "advanced/detailedAnalysis").is_some_and(Value::as_bool);
+ format!("{}{}", signature(project, cid, l), if detailed { "+detailed" } else { "" })
+ }
+
+ /// Parameters of an instance from static values (the tracker's settings are not animated).
+ pub fn static_params(g: &PropGroup) -> effectcraft_effects::Params {
+ effectcraft_effects::flatten_params(g, &mut |p| p.value.clone())
+ }
+
+ fn clear(g: &mut PropGroup, all: bool) {
+ let mut ids = vec![SOLVE, SOLVE_KEY, METHOD_USED];
+ if all {
+ ids.extend([TRACKS, TRACKS_KEY]);
+ }
+ for m in ids {
+ if let Some(p) = g.prop_mut(m) {
+ p.value = Value::Str(String::new());
+ p.keys.clear();
+ }
+ }
+ if let Some(p) = g.prop_mut(AVERAGE_ERROR) {
+ p.value = Value::Scalar(0.0);
+ }
+ }
+
+ /// Clear analyses that no longer match, after an edit: tracks made from other frames (and their
+ /// solve), and solves made with other settings. Returns the trackers that need (re-)analysis:
+ /// cleared ones and newly applied, unanalysed ones.
+ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerId, Uid)> {
+ let mut todo = vec![];
+ let mut clears = vec![];
+ for (cid, it) in &after.items {
+ let ItemKind::Comp(c) = &it.kind else { continue };
+ for l in &c.layers {
+ let Some(fx) = l.effects() else { continue };
+ if !fx.groups().any(is_tracker) {
+ continue;
+ }
+ let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id));
+ for g in fx.groups().filter(|g| is_tracker(g)) {
+ let tracked = !str_of(g, TRACKS).is_empty();
+ if tracked && str_of(g, TRACKS_KEY) != tracks_key(after, *cid, l, g) {
+ clears.push((*cid, l.id, g.uid, true));
+ todo.push((*cid, l.id, g.uid));
+ } else if tracked && str_of(g, SOLVE_KEY) != ct::solve_key(&ct::settings(&static_params(g))) {
+ clears.push((*cid, l.id, g.uid, false));
+ todo.push((*cid, l.id, g.uid));
+ } else if !tracked && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() {
+ todo.push((*cid, l.id, g.uid));
+ }
+ }
+ }
+ }
+ for (cid, lid, uid, all) in clears {
+ if let Some(g) = after.comp_mut(cid).and_then(|c| c.layer_mut(lid)).and_then(|l| l.props.find_group_mut(uid)) {
+ clear(g, all);
+ }
+ }
+ todo
+ }
+
+ fn input_frame(r: &Renderer, ctx: &EvalCtx, layer: &Layer, effect_index: usize) -> Option<(Arc<effectcraft_raster::Image>, [f64; 2])> {
+ let buf = r.layer_input(ctx, layer, effect_index)?;
+ if (buf.scale - 1.0).abs() > 1e-9 && buf.scale > 0.0 {
+ let w = (buf.img.width as f64 / buf.scale).round().max(1.0) as u32;
+ let h = (buf.img.height as f64 / buf.scale).round().max(1.0) as u32;
+ let off = [buf.offset[0] / buf.scale, buf.offset[1] / buf.scale];
+ return Some((Arc::new(effectcraft_raster::resample(&buf.img, w, h)), off));
+ }
+ Some((Arc::new(buf.img.clone()), buf.offset))
+ }
+
+ fn run_work(w: CamWork, shared: &CameraShared) {
+ let t0 = web_time::Instant::now();
+ let fail = |msg: &str| {
+ let mut s = lock(&shared.state);
+ s.error = Some(msg.to_string());
+ s.finished = true;
+ };
+ let cancelled = || {
+ let mut s = lock(&shared.state);
+ s.cancelled = true;
+ s.finished = true;
+ };
+ let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
+ let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
+ let lt0 = layer.layer_time(w.times[0]).seconds();
+ let fd = if w.times.len() > 1 { layer.layer_time(w.times[1]).seconds() - lt0 } else { comp.frame_duration().seconds() };
+ let (tracks, fresh) = match w.tracks.clone() {
+ Some(t) => (t, false),
+ None => {
+ let mut r = Renderer::new(&w.project, w.footage.as_ref(), RenderOpts { scale: 1.0, ..Default::default() });
+ r.expr = w.expr.as_deref();
+ r.cache = Some(&w.cache);
+ let r = &r;
+ let ctx0 = EvalCtx::new(&w.project, w.comp, comp, Tick::ZERO);
+ let ctx0 = EvalCtx { expr: w.expr.as_deref(), ..ctx0 };
+ let frame_at = |t: Tick| input_frame(r, &ctx0.at(t), layer, w.effect_index);
+ {
+ let mut s = lock(&shared.state);
+ s.step = 1;
+ s.total = w.times.len() as u64;
+ }
+ let mut an = TrackAnalyzer::new(w.size, AnalyzeOpts { detailed: w.detailed });
+ let mut next = frame_at(w.times[0]);
+ for k in 0..w.times.len() {
+ if shared.cancel.load(Ordering::Relaxed) {
+ return cancelled();
+ }
+ let Some(cur) = next.take() else { return fail(&format!("no frame at {:.3} s", w.times[k].seconds())) };
+ let ((), nf) = rayon::join(
+ || an.push(&effectcraft_track::Frame { img: &cur.0, offset: cur.1 }),
+ || if k + 1 < w.times.len() { frame_at(w.times[k + 1]) } else { None },
+ );
+ next = nf;
+ let mut s = lock(&shared.state);
+ s.done = k as u64 + 1;
+ s.elapsed = t0.elapsed().as_secs_f64();
+ s.fps = if s.elapsed > 0.0 { s.done as f64 / s.elapsed } else { 0.0 };
++ crate::offload::report(s.done, s.total);
+ }
+ (Arc::new(an.finish(lt0, fd)), true)
+ }
+ };
+ lock(&shared.state).step = 2;
+ let solve = effectcraft_track::camtrack::solve(&tracks, &w.settings, Some(&shared.cancel)).map_err(|e| e.0);
+ if shared.cancel.load(Ordering::Relaxed) {
+ return cancelled();
+ }
+ *lock(&shared.result) = Some(CamResult { tracks: fresh.then(|| (*tracks).clone()), solve });
+ let mut s = lock(&shared.state);
+ s.elapsed = t0.elapsed().as_secs_f64();
+ s.finished = true;
+ }
+
+ impl Session {
+ pub fn is_camera_analyzing(&self) -> bool {
- self.camera_job.as_ref().is_some_and(|j| !j.is_finished())
++ self.camera_job.as_ref().is_some_and(|j| !j.is_finished()) || self.offloaded(JobKind::Camera).is_some()
+ }
+
+ /// Progress of the running (or just finished) analysis.
+ pub fn camera_progress(&self) -> Option<CameraProgress> {
- self.camera_job.as_ref().map(|j| j.progress())
++ self.camera_job.as_ref().map(|j| j.progress()).or_else(|| {
++ self.offloaded(JobKind::Camera).map(|j| {
++ let p = &j.progress;
++ CameraProgress { step: 1, done: p.done, total: p.total, elapsed: p.elapsed, fps: crate::offload::rate(p.done, p.elapsed), ..Default::default() }
++ })
++ })
+ }
+
+ /// The tracker being analysed: (comp, layer, effect uid).
+ pub fn camera_target(&self) -> Option<(ItemId, LayerId, Uid)> {
- self.camera_job.as_ref().map(|j| (j.comp, j.layer, j.effect))
++ self.camera_job.as_ref().map(|j| (j.comp, j.layer, j.effect)).or_else(|| self.offloaded(JobKind::Camera).map(|j| (j.comp, j.layer, j.uid)))
+ }
+
+ /// Cancel the running analysis (nothing is written).
+ pub fn stop_camera(&mut self) -> bool {
++ if self.cancel_offloaded(JobKind::Camera) {
++ return true;
++ }
+ match &self.camera_job {
+ Some(j) if !j.is_finished() => {
+ j.shared.cancel.store(true, Ordering::Relaxed);
+ true
+ }
+ _ => false,
+ }
+ }
+
+ /// Start analysing 3D Camera Tracker `effect` on `layer` (re-solving the stored tracks when
+ /// they are still valid). `wait`: block until done (wasm32 always does). Returns the number
+ /// of frames.
+ pub fn start_camera(&mut self, comp: ItemId, layer: LayerId, effect: Uid, wait: bool) -> Result<usize, String> {
+ if self.is_camera_analyzing() {
+ return Err("a 3D Camera Tracker analysis is already running".into());
+ }
+ self.poll_camera_job();
+ self.camera_pending.retain(|x| *x != (comp, layer, effect));
+ let c = self.project.comp(comp).ok_or("no composition")?;
+ let l = c.layer(layer).ok_or("no layer")?;
+ let fx = l.effects().ok_or("the layer has no effects")?;
+ let index = fx.groups().position(|g| g.uid == effect).ok_or("no such effect")?;
+ let g = fx.groups().nth(index).filter(|g| is_tracker(g)).ok_or("not a 3D Camera Tracker")?;
+ if l.switches.adjustment {
+ return Err("3D Camera Tracker needs footage, not an adjustment layer".into());
+ }
+ let times = analysis_times(c, l);
+ if times.len() < 2 {
+ return Err("the layer must be at least two frames long".into());
+ }
+ let (w, h) = effectcraft_render::source_size(&self.project, l);
+ let size = if w == 0 { [c.width as f64, c.height as f64] } else { [w as f64, h as f64] };
+ let params = static_params(g);
+ let key = tracks_key(&self.project, comp, l, g);
+ let settings = ct::settings(&params);
+ let solve_key = ct::solve_key(&settings);
+ let tracks = ct::tracks(&params).filter(|_| str_of(g, TRACKS_KEY) == key);
+ let n = times.len();
+ let work = CamWork {
+ project: self.project.clone(),
+ footage: self.footage.clone(),
+ expr: self.expr.clone(),
+ cache: self.layer_cache.clone(),
+ comp,
+ layer,
+ effect_index: index,
+ size,
+ detailed: params.values.iter().any(|(k, v)| k.ends_with("detailedAnalysis") && v.as_bool()),
+ times,
+ tracks: tracks.clone(),
+ settings,
+ };
++ if !wait && self.offloads() {
++ drop(work);
++ self.offload_analysis(crate::offload::WorkerJob::Camera { comp, layer, effect })?;
++ return Ok(n);
++ }
+ let wait = wait || cfg!(target_arch = "wasm32");
+ let shared = Arc::new(CameraShared::default());
+ {
+ let mut st = lock(&shared.state);
+ st.solve_only = tracks.is_some();
+ st.step = if tracks.is_some() { 2 } else { 1 };
+ st.total = n as u64;
+ }
+ let thread = if wait {
+ run_work(work, &shared);
+ None
+ } else {
+ let sh = shared.clone();
+ Some(std::thread::Builder::new().name("camera-track".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
+ };
+ self.camera_job = Some(CameraJob { shared, thread, comp, layer, effect, key, solve_key });
+ self.events.push(Event::ProjectChanged { revision: self.revision });
+ self.poll_camera_job();
+ Ok(n)
+ }
+
+ /// Write a finished analysis into its effect (one undo step) and drop the job.
+ fn poll_camera_job(&mut self) -> bool {
+ let Some(job) = &self.camera_job else { return false };
+ if !job.is_finished() {
+ return false;
+ }
+ let mut job = self.camera_job.take().expect("job");
+ if let Some(t) = job.thread.take() {
+ let _ = t.join();
+ }
+ let st = job.progress();
+ let result = lock(&job.shared.result).take();
+ match (result, &st.error) {
+ (Some(res), None) if !st.cancelled => {
+ let (cid, lid, uid) = (job.comp, job.layer, job.effect);
+ let (key, skey) = (job.key.clone(), job.solve_key.clone());
+ let tracks_json = res.tracks.as_ref().map(CameraTracks::to_json);
+ let (solve_json, method, avg, msg, failed) = match &res.solve {
+ Ok(s) => (
+ s.to_json(),
+ s.method_used.label().to_string(),
+ s.average_error,
+ format!(
+ "3D Camera Tracker: solved {} frame(s), {} points, average error {:.2} px ({:.1} s)",
+ s.frames.len(),
+ s.points.len(),
+ s.average_error,
+ st.elapsed
+ ),
+ false,
+ ),
+ Err(e) => (String::new(), String::new(), 0.0, format!("3D Camera Tracker: {e}"), true),
+ };
+ let r = self.edit(if st.solve_only { "3D Camera Tracker Solve" } else { "3D Camera Tracker Analysis" }, None, |p, _| {
+ let g = p
+ .comp_mut(cid)
+ .and_then(|c| c.layer_mut(lid))
+ .and_then(|l| l.props.find_group_mut(uid))
+ .ok_or_else(|| crate::EngineError::Other("the 3D Camera Tracker was removed during analysis".into()))?;
+ let mut set = |m: &str, v: Value| {
+ if let Some(pr) = g.prop_mut(m) {
+ pr.value = v;
+ }
+ };
+ if let Some(t) = &tracks_json {
+ set(TRACKS, Value::Str(t.clone()));
+ set(TRACKS_KEY, Value::Str(key.clone()));
+ }
+ set(SOLVE, Value::Str(solve_json.clone()));
+ set(SOLVE_KEY, Value::Str(skey.clone()));
+ set(METHOD_USED, Value::Str(method.clone()));
+ set(AVERAGE_ERROR, Value::Scalar(avg));
+ Ok(())
+ });
+ let (msg, failed) = match r {
+ Ok(()) => (msg, failed),
+ Err(e) => (format!("3D Camera Tracker: {e}"), true),
+ };
+ self.events.push(Event::Toast { message: msg, error: failed });
+ }
+ _ => {
+ let msg = match &st.error {
+ Some(e) => format!("3D Camera Tracker analysis failed: {e}"),
+ None => "3D Camera Tracker analysis cancelled".into(),
+ };
+ self.events.push(Event::Toast { message: msg, error: st.error.is_some() });
+ self.bump();
+ }
+ }
+ true
+ }
+
+ /// Frontends call this every frame: finishes analyses and (with `auto`) starts queued
+ /// (re-)analyses in the background, like After Effects.
+ pub fn poll_camera(&mut self, auto: bool) -> bool {
+ let changed = self.poll_camera_job();
- if auto && self.camera_job.is_none() {
++ if auto && self.camera_job.is_none() && self.offloaded(JobKind::Camera).is_none() {
+ while let Some((c, l, e)) = self.camera_pending.first().copied() {
+ self.camera_pending.remove(0);
+ if self.start_camera(c, l, e, false).is_ok() {
+ return true;
+ }
+ }
+ }
+ changed
+ }
+ }
+
+ // ---------------------------------------------------------------- solve → composition
+
+ /// A tracker's solve placed in its composition.
+ pub struct Placed {
+ pub solve: Arc<CameraSolve>,
+ /// Canonical → comp world.
+ pub world: Similarity,
+ /// Comp pixels per layer pixel.
+ pub scale: f64,
+ /// Comp times of the analysed frames.
+ pub times: Vec<Tick>,
+ pub comp_size: [f64; 2],
+ }
+
+ impl Placed {
+ /// Comp-world position of a canonical point.
+ pub fn to_world(&self, x: V3) -> V3 {
+ self.world.apply(x)
+ }
+ /// Canonical position of a comp-world point.
+ pub fn from_world(&self, x: V3) -> V3 {
+ let r = &self.world;
+ linalg::scale(linalg::mtv(&r.r, linalg::sub(x, r.t)), 1.0 / r.s)
+ }
+ /// The 3D Tracker Camera on frame `k`: (position, orientation degrees, zoom).
+ pub fn camera(&self, k: usize) -> (V3, V3, f64) {
+ let c = &self.solve.frames[k];
+ let m = linalg::mm(&self.world.r, &linalg::mt(&c.r()));
+ (self.to_world(c.center), linalg::euler_xyz(&m), c.focal * self.scale)
+ }
+ /// Analysed frame at comp time `t`.
+ pub fn frame_at(&self, t: Tick) -> usize {
+ self.times.iter().enumerate().min_by_key(|(_, x)| (x.0 - t.0).abs()).map(|(i, _)| i).unwrap_or(0).min(self.solve.frames.len().saturating_sub(1))
+ }
+ }
+
+ /// Comp pixels per layer pixel of `layer` (its 2D transform at its In point).
+ fn layer_scale(project: &Project, cid: ItemId, layer: &Layer) -> f64 {
+ let Some(comp) = project.comp(cid) else { return 1.0 };
+ let ctx = EvalCtx::new(project, cid, comp, layer.in_point.max(Tick::ZERO));
+ let m = ctx.world_matrix(layer).0;
+ let s = m[0][0].hypot(m[1][0]);
+ if s.is_finite() && s > 1e-9 { s } else { 1.0 }
+ }
+
+ /// The solve of tracker `uid` on `lid`, placed in the comp.
+ pub fn placed(project: &Project, cid: ItemId, lid: LayerId, uid: Uid) -> Option<Placed> {
+ let comp = project.comp(cid)?;
+ let layer = comp.layer(lid)?;
+ let g = layer.props.find_group(uid).filter(|g| is_tracker(g))?;
+ let solve = ct::solve(&static_params(g))?;
+ let scale = layer_scale(project, cid, layer);
+ let k0 = solve.first_solved()?;
+ let comp_size = [comp.width as f64, comp.height as f64];
+ let world = solve.world(comp_size, solve.frames[k0].focal * scale);
+ let mut times = analysis_times(comp, layer);
+ times.truncate(solve.frames.len());
+ Some(Placed { solve, world, scale, times, comp_size })
+ }
+
+ /// What to create from a target (`camera.createFromSolve`).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum CreateKind {
+ Text,
+ Solid,
+ Null,
+ ShadowCatcher,
+ /// Only the camera.
+ Camera,
+ }
+
+ impl CreateKind {
+ pub fn from_name(s: &str) -> Option<CreateKind> {
+ match s.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {
+ "text" => Some(CreateKind::Text),
+ "solid" => Some(CreateKind::Solid),
+ "null" => Some(CreateKind::Null),
+ "shadowcatcher" | "shadow" => Some(CreateKind::ShadowCatcher),
+ "camera" => Some(CreateKind::Camera),
+ _ => None,
+ }
+ }
+ }
+
+ /// Rotation (layer → world) of a layer lying on a plane with unit `normal` (towards the camera),
+ /// its x axis along `right` projected on the plane: the layer's front (−z) faces the camera.
+ pub fn plane_orientation(normal: V3, right: V3) -> V3 {
+ let z = linalg::scale(normal, -1.0);
+ let mut x = linalg::sub(right, linalg::scale(z, linalg::dot(right, z)));
+ if linalg::norm(x) < 1e-9 {
+ x = if z[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
+ x = linalg::sub(x, linalg::scale(z, linalg::dot(x, z)));
+ }
+ let x = linalg::normalize(x);
+ let y = linalg::cross(z, x);
+ let m = linalg::from_cols(x, y, z);
+ norm_angles(linalg::euler_xyz(&m))
+ }
+
+ fn norm_angles(a: V3) -> V3 {
+ a.map(|v| {
+ let r = v.rem_euclid(360.0);
+ if (r - 360.0).abs() < 1e-9 { 0.0 } else { r }
+ })
+ }
+
+ /// Key `path` on `l` at every `(time, value)`.
+ pub(crate) fn key_all(l: &mut Layer, path: &str, keys: &[(Tick, Value)]) {
+ if let Some(pr) = l.props.prop_mut(path) {
+ pr.keys = keys.iter().map(|(t, v)| Keyframe::new(*t, v.clone())).collect();
+ if let Some((_, v)) = keys.first() {
+ pr.value = v.clone();
+ }
+ }
+ }
+
+ /// Write the solved camera path into camera layer `l` (one-node, keyed on every analysed frame;
+ /// Zoom keyed for Variable Zoom).
+ pub(crate) fn write_camera(l: &mut Layer, pl: &Placed) {
+ l.auto_orient = AutoOrient::Off;
+ let n = pl.times.len().min(pl.solve.frames.len());
+ let mut pos = Vec::with_capacity(n);
+ let mut ori = Vec::with_capacity(n);
+ let mut zoom = Vec::with_capacity(n);
+ let mut prev: Option<V3> = None;
+ for k in 0..n {
+ let (p, o, z) = pl.camera(k);
+ // Unwrap the angles so per-frame keys interpolate the short way.
+ let o = match prev {
+ None => norm_angles(o),
+ Some(q) => [0, 1, 2].map(|i| q[i] + (o[i] - q[i] + 180.0).rem_euclid(360.0) - 180.0),
+ };
+ prev = Some(o);
+ let t = l.layer_time(pl.times[k]);
+ pos.push((t, Value::Vec3(p)));
+ ori.push((t, Value::Vec3(o)));
+ zoom.push((t, Value::Scalar(z)));
+ }
+ key_all(l, "transform/position", &pos);
+ key_all(l, "transform/orientation", &ori);
+ let variable = pl.solve.frames.iter().any(|f| (f.focal - pl.solve.frames[0].focal).abs() > 1e-6 * f.focal);
+ if variable {
+ key_all(l, "cameraOptions/zoom", &zoom);
+ } else if let Some((_, z)) = zoom.first()
+ && let Some(pr) = l.props.prop_mut("cameraOptions/zoom")
+ {
+ pr.keys.clear();
+ pr.value = z.clone();
+ }
+ if let Some((_, z)) = zoom.first()
+ && let Some(pr) = l.props.prop_mut("cameraOptions/focusDistance")
+ {
+ pr.value = z.clone();
+ }
+ // A one-node camera has no Point of Interest.
+ if let Some(tr) = l.props.sub_mut("transform") {
+ tr.children.retain(|c| !matches!(c, effectcraft_project::Node::Prop(p) if p.match_id == "poi"));
+ }
+ for rot in ["transform/rotationX", "transform/rotationY", "transform/rotation"] {
+ if let Some(pr) = l.props.prop_mut(rot) {
+ pr.keys.clear();
+ pr.value = Value::Scalar(0.0);
+ }
+ }
+ }
+
+ /// The target for `ids` on frame `k`: when fewer than three points are given, the nearest
+ /// solved neighbours (in 3D) complete the plane.
+ pub fn target_for(solve: &CameraSolve, ids: &[u32], k: usize) -> Option<Target> {
+ let mut use_ids: Vec<u32> = ids.iter().copied().filter(|i| solve.point(*i).is_some()).collect();
+ if use_ids.is_empty() {
+ return None;
+ }
+ if use_ids.len() < 3 {
+ let c = solve.point(use_ids[0])?.pos;
+ let mut others: Vec<(f64, u32)> = solve.visible(k).filter(|p| !use_ids.contains(&p.id)).map(|p| (linalg::norm(linalg::sub(p.pos, c)), p.id)).collect();
+ others.sort_by(|a, b| a.0.total_cmp(&b.0));
+ for (_, id) in others.into_iter().take(6usize.saturating_sub(use_ids.len())) {
+ use_ids.push(id);
+ }
+ let mut t = solve.target(&use_ids, k)?;
+ // The target sits on the chosen point(s).
+ let pts: Vec<V3> = ids.iter().filter_map(|i| solve.point(*i)).map(|p| p.pos).collect();
+ t.center = linalg::scale(pts.iter().fold([0.0; 3], |a, b| linalg::add(a, *b)), 1.0 / pts.len() as f64);
+ return Some(t);
+ }
+ solve.target(&use_ids, k)
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn plane_orientation_faces_the_normal() {
+ let n = linalg::normalize([0.2, -0.9, -0.3]);
+ let o = plane_orientation(n, [1.0, 0.0, 0.0]);
+ let m = linalg::from_euler_xyz(o);
+ // Layer −z (its front) is the normal.
+ let front = linalg::mv(&m, [0.0, 0.0, -1.0]);
+ assert!(linalg::norm(linalg::sub(front, n)) < 1e-9);
+ }
+ }
diff --cc crates/engine/src/lib.rs
index 187058b02,a6dbe2c4b..4662f302d
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -15,8 -16,8 +16,9 @@@ pub mod demo
pub mod links;
pub mod mask_track;
pub mod menus;
+pub mod offload;
pub mod prefs;
+ pub mod psd_import;
pub mod render_queue;
pub mod roto;
mod session_settings;
diff --cc crates/engine/src/offload.rs
index 7505a5afe,000000000..3e92fbd45
mode 100644,000000..100644
--- a/crates/engine/src/offload.rs
+++ b/crates/engine/src/offload.rs
@@@ -1,741 -1,0 +1,754 @@@
+//! Background jobs where the platform has no threads (the browser).
+//!
+//! On the desktop, renders and analyses run on threads that share the session's project and
+//! footage. A wasm build without atomics has one thread per instance, so the web app runs a
+//! second engine instance in a Web Worker instead and talks to it with messages: an
+//! [`Offload`] (set as [`Session::offload`]) ships a [`WorkerRequest`] — the serialized project,
+//! the footage files it reads and the job — and feeds the worker's [`WorkerReply`]s back into an
+//! [`Inbox`] that the session drains every frame ([`Session::poll_render`],
+//! [`Session::poll_offload`]). The worker side is [`run_request`]: a plain session fed the
+//! project runs the job blocking and reports through a callback.
+//!
+//! | Job | Worker runs | Reply applied on the UI thread |
+//! |---|---|---|
+//! | Render Queue | the export of every queued item | item status, progress; files arrive through the host |
+//! | Warp Stabilizer analysis | [`Session::start_warp`] | the effect's property group (one undo step) |
+//! | Track Motion / Stabilize Motion | the tracker analysis | the tracker group |
+//! | Mask tracking | the mask track | the mask group |
+//! | Roto Brush Freeze | the freeze | the effect group |
++//! | 3D Camera Tracker analysis | [`Session::start_camera`] | the effect's property group |
+//!
+//! Roto Brush propagation fills the session's segmentation cache rather than the project, so it
+//! keeps running on the UI thread.
+//!
+//! Cancelling terminates the worker: what an analysis tracked so far is dropped and the Render
+//! Queue item being rendered becomes "User Stopped".
+
+use std::cell::{Cell, RefCell};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+
+use effectcraft_keyframe::ShapePath;
+use effectcraft_project::render_queue::{RenderQueueItem, RenderStatus};
+use effectcraft_project::tracking::TrackerSettings;
+use effectcraft_project::{ItemId, ItemKind, LayerId, Project, PropGroup, Uid};
+use effectcraft_time::Tick;
+use serde::{Deserialize, Serialize};
+
+use crate::mask_track::MaskMethod;
+use crate::render_queue::{ItemUpdate, JobShared, JobState};
+use crate::tracking::PointValues;
+use crate::{Event, Session};
+
+/// One job for a worker.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkerRequest {
+ pub id: u64,
+ /// The project ([`Project::to_json`]).
+ pub project: String,
+ /// Footage files the job reads; the host ships their bytes before the request.
+ pub files: Vec<String>,
+ pub job: WorkerJob,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum WorkerJob {
+ /// Render Queue: per item, one (item with that output module, resolved output path) per
+ /// output module.
+ Render {
+ items: Vec<Vec<(RenderQueueItem, String)>>,
+ },
+ Warp {
+ comp: ItemId,
+ layer: LayerId,
+ effect: Uid,
+ },
++ Camera {
++ comp: ItemId,
++ layer: LayerId,
++ effect: Uid,
++ },
+ RotoFreeze {
+ comp: ItemId,
+ layer: LayerId,
+ effect: Uid,
+ },
+ Track {
+ comp: ItemId,
+ layer: LayerId,
+ tracker: Uid,
+ direction: crate::tracking::Direction,
+ settings: TrackerSettings,
+ points: Vec<PointValues>,
+ times: Vec<Tick>,
+ },
+ MaskTrack {
+ comp: ItemId,
+ layer: LayerId,
+ mask: Uid,
+ direction: crate::tracking::Direction,
+ path: ShapePath,
+ method: MaskMethod,
+ times: Vec<Tick>,
+ },
+}
+
+impl WorkerJob {
+ pub fn kind(&self) -> JobKind {
+ match self {
+ WorkerJob::Render { .. } => JobKind::Render,
+ WorkerJob::Warp { .. } => JobKind::Warp,
++ WorkerJob::Camera { .. } => JobKind::Camera,
+ WorkerJob::RotoFreeze { .. } => JobKind::RotoFreeze,
+ WorkerJob::Track { .. } => JobKind::Track,
+ WorkerJob::MaskTrack { .. } => JobKind::MaskTrack,
+ }
+ }
+
+ /// (comp, layer, property group uid) an analysis writes to.
+ pub fn target(&self) -> Option<(ItemId, LayerId, Uid)> {
+ match *self {
+ WorkerJob::Render { .. } => None,
- WorkerJob::Warp { comp, layer, effect } | WorkerJob::RotoFreeze { comp, layer, effect } => Some((comp, layer, effect)),
++ WorkerJob::Warp { comp, layer, effect } | WorkerJob::Camera { comp, layer, effect } | WorkerJob::RotoFreeze { 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)),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum JobKind {
+ Render,
+ Warp,
++ Camera,
+ RotoFreeze,
+ Track,
+ MaskTrack,
+}
+
+impl JobKind {
+ /// The undo step an analysis result becomes.
+ pub fn label(self) -> &'static str {
+ match self {
+ JobKind::Render => "Render",
+ JobKind::Warp => "Warp Stabilizer Analysis",
++ JobKind::Camera => "3D Camera Tracker Analysis",
+ JobKind::RotoFreeze => "Freeze",
+ JobKind::Track => "Analyze Track",
+ JobKind::MaskTrack => "Track Mask",
+ }
+ }
+}
+
+/// What a worker reports.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "camelCase")]
+pub enum WorkerReply {
+ /// Render Queue progress.
+ Render {
+ state: JobState,
+ },
+ /// A Render Queue item started or finished.
+ Item {
+ update: ItemUpdate,
+ },
+ /// Analysis progress (frames).
+ Progress {
+ done: u64,
+ total: u64,
+ },
+ /// An analysis finished: its property group after the job, and the job's message.
+ Group {
+ comp: ItemId,
+ layer: LayerId,
+ group: Box<PropGroup>,
+ message: String,
+ },
+ Failed {
+ error: String,
+ },
+ /// The job ended (always the last reply).
+ Done,
+}
+
+/// Replies waiting for the UI thread.
+#[derive(Default)]
+pub struct Inbox(Mutex<Vec<WorkerReply>>);
+
+impl Inbox {
+ pub fn push(&self, r: WorkerReply) {
+ self.0.lock().unwrap_or_else(|e| e.into_inner()).push(r);
+ }
+ pub fn take(&self) -> Vec<WorkerReply> {
+ std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()))
+ }
+}
+
+/// Runs jobs off the UI thread (the web app: a pool of Web Workers).
+pub trait Offload: Send + Sync {
+ /// Start `req`; replies go to `inbox` (ending with [`WorkerReply::Done`]).
+ fn start(&self, req: WorkerRequest, inbox: Arc<Inbox>) -> Result<(), String>;
+ /// Stop job `id` now (the worker is terminated; no more replies arrive).
+ fn cancel(&self, id: u64);
+}
+
+static NEXT_ID: AtomicU64 = AtomicU64::new(1);
+
+pub fn next_id() -> u64 {
+ NEXT_ID.fetch_add(1, Ordering::Relaxed)
+}
+
+/// Footage files a project reads (paths, sequence frames).
+pub fn footage_files(p: &Project) -> Vec<String> {
+ let mut v: Vec<String> = p
+ .items
+ .values()
+ .filter_map(|i| match &i.kind {
+ ItemKind::Footage(f) if !f.path.is_empty() => Some(std::iter::once(f.path.clone()).chain(f.sequence.iter().cloned()).collect::<Vec<_>>()),
+ _ => None,
+ })
+ .flatten()
+ .collect();
+ v.sort();
+ v.dedup();
+ v
+}
+
+// ---------------------------------------------------------------- progress hook (worker side)
+
+thread_local! {
+ static HOOK: RefCell<Option<Box<dyn FnMut(u64, u64)>>> = const { RefCell::new(None) };
+}
+
+/// Analyses call this as frames complete; a worker forwards it (no-op elsewhere).
+pub fn report(done: u64, total: u64) {
+ HOOK.with(|h| {
+ if let Ok(mut h) = h.try_borrow_mut()
+ && let Some(f) = h.as_mut()
+ {
+ f(done, total);
+ }
+ });
+}
+
+fn with_hook<R>(hook: Box<dyn FnMut(u64, u64)>, f: impl FnOnce() -> R) -> R {
+ HOOK.with(|h| *h.borrow_mut() = Some(hook));
+ let r = f();
+ HOOK.with(|h| *h.borrow_mut() = None);
+ r
+}
+
+// ---------------------------------------------------------------- worker side
+
+/// Where a worker sends its replies.
+pub type Post = Rc<dyn Fn(WorkerReply)>;
+
+/// Run `req` on `s` (a session with footage, expressions and an exporter, but no project yet),
+/// blocking, reporting through `post`. Always ends with [`WorkerReply::Done`].
+pub fn run_request(s: &mut Session, req: WorkerRequest, post: &Post) {
+ match Project::from_json(&req.project) {
+ Ok(p) => {
+ s.replace_project(p, None);
+ if let Err(e) = run_job(s, req.job, post.clone()) {
+ post(WorkerReply::Failed { error: e });
+ }
+ }
+ Err(e) => post(WorkerReply::Failed { error: format!("project: {e}") }),
+ }
+ post(WorkerReply::Done);
+}
+
+fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), String> {
+ let kind = job.kind();
+ let target = job.target();
+ match job {
+ WorkerJob::Render { items } => {
+ let exporter = s.exporter.clone().ok_or("export is not available in this build")?;
+ let shared = JobShared::default();
+ // Item updates and progress go out as they happen (progress at most every 100 ms).
+ let last = Cell::new(None::<web_time::Instant>);
+ let notify = |sh: &JobShared, force: bool| {
+ let ups = std::mem::take(&mut *crate::render_queue::lock(&sh.updates));
+ for u in ups {
+ post(WorkerReply::Item { update: u });
+ }
+ if force || last.get().is_none_or(|t| t.elapsed().as_millis() >= 100) {
+ last.set(Some(web_time::Instant::now()));
+ post(WorkerReply::Render { state: sh.snapshot() });
+ }
+ };
+ crate::render_queue::run_items(s, exporter, items, &shared, &mut |sh| notify(sh, false));
+ notify(&shared, true);
+ Ok(())
+ }
+ WorkerJob::Warp { comp, layer, effect } => analysis(s, kind, target, post, |s| s.start_warp(comp, layer, effect, true).map(|_| ())),
++ WorkerJob::Camera { comp, layer, effect } => analysis(s, kind, target, post, |s| s.start_camera(comp, layer, effect, true).map(|_| ())),
+ WorkerJob::RotoFreeze { comp, layer, effect } => analysis(s, kind, target, post, |s| {
+ s.start_roto(comp, layer, effect, crate::roto::RotoTask::Freeze, crate::roto::Direction::Both, true).map(|_| ())
+ }),
+ WorkerJob::Track { comp, layer, tracker, direction, settings, points, times } => analysis(s, kind, target, post, |s| {
+ let work = crate::tracking::Work {
+ project: s.project.clone(),
+ footage: s.footage.clone(),
+ expr: s.expr.clone(),
+ cache: s.layer_cache.clone(),
+ comp,
+ layer,
+ settings,
+ points,
+ times,
+ };
+ s.start_track(work, tracker, direction, true)
+ }),
+ WorkerJob::MaskTrack { comp, layer, mask, direction, path, method, times } => analysis(s, kind, target, post, |s| {
+ let work = crate::mask_track::MaskWork {
+ project: s.project.clone(),
+ footage: s.footage.clone(),
+ expr: s.expr.clone(),
+ cache: s.layer_cache.clone(),
+ comp,
+ layer,
+ path,
+ method,
+ times,
+ };
+ s.start_mask_track(work, mask, direction, true)
+ }),
+ }
+}
+
+fn analysis(
+ s: &mut Session,
+ kind: JobKind,
+ target: Option<(ItemId, LayerId, Uid)>,
+ post: Post,
+ run: impl FnOnce(&mut Session) -> Result<(), String>,
+) -> Result<(), String> {
+ let (comp, layer, uid) = target.ok_or("no target")?;
+ let rev = s.revision;
+ // Progress at most every 100 ms.
+ let p = post.clone();
+ let mut last = None::<web_time::Instant>;
+ let hook = Box::new(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 });
+ }
+ });
+ with_hook(hook, || run(s))?;
+ let message = s
+ .events
+ .iter()
+ .rev()
+ .find_map(|e| match e {
+ Event::Toast { message, .. } => Some(message.clone()),
+ _ => None,
+ })
+ .unwrap_or_default();
+ let failed = s.events.iter().any(|e| matches!(e, Event::Toast { error: true, .. }));
+ if failed {
+ return Err(message);
+ }
+ if s.revision == rev && kind != JobKind::Track && kind != JobKind::MaskTrack {
+ // Nothing written (e.g. the analysis was empty).
+ return Err(if message.is_empty() { "nothing was analysed".into() } else { message });
+ }
+ let group = s.project.comp(comp).and_then(|c| c.layer(layer)).and_then(|l| l.props.find_group(uid)).cloned().ok_or("the analysed property is gone")?;
+ post(WorkerReply::Group { comp, layer, group: Box::new(group), message });
+ Ok(())
+}
+
+// ---------------------------------------------------------------- UI side
+
+/// Analysis progress of an offloaded job.
+#[derive(Clone, Debug, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OffloadProgress {
+ pub done: u64,
+ pub total: u64,
+ pub elapsed: f64,
+ pub finished: bool,
+ pub cancelled: bool,
+ pub error: Option<String>,
+}
+
+/// Frames per second of `done` frames in `elapsed` seconds.
+pub(crate) fn rate(done: u64, elapsed: f64) -> f64 {
+ if elapsed > 0.0 { done as f64 / elapsed } else { 0.0 }
+}
+
+impl OffloadProgress {
+ pub(crate) fn track(&self) -> crate::tracking::TrackProgress {
+ crate::tracking::TrackProgress { done: self.done, total: self.total, elapsed: self.elapsed, fps: rate(self.done, self.elapsed), ..Default::default() }
+ }
+}
+
+/// An analysis running in a worker.
+pub struct OffloadedJob {
+ pub id: u64,
+ pub kind: JobKind,
+ pub comp: ItemId,
+ pub layer: LayerId,
+ pub uid: Uid,
+ pub inbox: Arc<Inbox>,
+ pub progress: OffloadProgress,
+ started: web_time::Instant,
+}
+
+/// A Render Queue job running in a worker (see [`crate::render_queue::RenderJob`]).
+pub struct RemoteRender {
+ pub id: u64,
+ pub inbox: Arc<Inbox>,
+ /// The queue items in the job.
+ pub ids: Vec<u64>,
+}
+
+impl Session {
+ /// Whether jobs started without `wait` go to the [`Offload`].
+ pub fn offloads(&self) -> bool {
+ self.offload.is_some()
+ }
+
+ /// The offloaded analysis of `kind`, if one runs.
+ pub fn offloaded(&self, kind: JobKind) -> Option<&OffloadedJob> {
+ self.offloaded.iter().find(|j| j.kind == kind && !j.progress.finished)
+ }
+
+ /// Send an analysis to the worker.
+ pub(crate) fn offload_analysis(&mut self, job: WorkerJob) -> Result<(), String> {
+ let off = self.offload.clone().ok_or("no background worker")?;
+ let kind = job.kind();
+ let (comp, layer, uid) = job.target().ok_or("not an analysis")?;
+ if self.offloaded(kind).is_some() {
+ return Err(format!("a {} job is already running", kind.label()));
+ }
+ let id = next_id();
+ let inbox = Arc::new(Inbox::default());
+ let req = WorkerRequest { id, project: self.project.to_json(), files: footage_files(&self.project), job };
+ off.start(req, inbox.clone())?;
+ self.offloaded.push(OffloadedJob { id, kind, comp, layer, uid, inbox, progress: OffloadProgress::default(), started: web_time::Instant::now() });
+ self.events.push(Event::ProjectChanged { revision: self.revision });
+ Ok(())
+ }
+
+ /// Cancel the offloaded analysis of `kind` (nothing is written).
+ pub fn cancel_offloaded(&mut self, kind: JobKind) -> bool {
+ let off = self.offload.clone();
+ let Some(j) = self.offloaded.iter_mut().find(|j| j.kind == kind && !j.progress.finished) else { return false };
+ if let Some(off) = off {
+ off.cancel(j.id);
+ }
+ j.progress.cancelled = true;
+ j.progress.finished = true;
+ true
+ }
+
+ /// Apply worker replies to offloaded analyses (results become one undo step each) and drop
+ /// finished jobs. Frontends call this every frame while [`Session::offloaded`] is not empty.
+ pub fn poll_offload(&mut self) -> bool {
+ if self.offloaded.is_empty() {
+ return false;
+ }
+ let mut changed = false;
+ let mut results = vec![];
+ for j in &mut self.offloaded {
+ if j.progress.cancelled {
+ continue;
+ }
+ for r in j.inbox.take() {
+ changed = true;
+ match r {
+ WorkerReply::Progress { done, total } => {
+ j.progress.done = done;
+ j.progress.total = total;
+ }
+ WorkerReply::Group { comp, layer, group, message } => results.push((j.kind, comp, layer, group, message)),
+ WorkerReply::Failed { error } => j.progress.error = Some(error),
+ WorkerReply::Done => j.progress.finished = true,
+ WorkerReply::Render { .. } | WorkerReply::Item { .. } => {}
+ }
+ }
+ j.progress.elapsed = j.started.elapsed().as_secs_f64();
+ }
+ for (kind, comp, layer, group, message) in results {
+ let uid = group.uid;
+ let r = self.edit(kind.label(), None, |p, _| {
+ let g = p
+ .comp_mut(comp)
+ .and_then(|c| c.layer_mut(layer))
+ .and_then(|l| l.props.find_group_mut(uid))
+ .ok_or_else(|| crate::EngineError::Other("the analysed property was removed during the analysis".into()))?;
+ *g = *group;
+ Ok(())
+ });
+ match r {
+ Ok(()) => self.events.push(Event::Toast { message, error: false }),
+ Err(e) => self.events.push(Event::Toast { message: format!("{}: {e}", kind.label()), error: true }),
+ }
+ }
+ let mut done = vec![];
+ self.offloaded.retain(|j| {
+ if j.progress.finished {
+ done.push((j.kind, j.progress.clone()));
+ }
+ !j.progress.finished
+ });
+ for (kind, p) in done {
+ changed = true;
+ if let Some(e) = p.error {
+ self.events.push(Event::Toast { message: format!("{}: {e}", kind.label()), error: true });
+ } else if p.cancelled {
+ self.events.push(Event::Toast { message: format!("{} stopped", kind.label()), error: false });
+ }
+ self.bump();
+ }
+ changed
+ }
+
+ /// Feed a remote render's replies into its [`JobShared`]; a cancelled one is wrapped up here
+ /// (the item being rendered and the ones after it become "User Stopped").
+ pub(crate) fn drain_remote_render(&mut self) {
+ let Some(job) = &self.render_job else { return };
+ let Some(remote) = &job.remote else { return };
+ let shared = job.shared.clone();
+ for r in remote.inbox.take() {
+ match r {
+ WorkerReply::Render { state } => {
+ let fin = crate::render_queue::lock(&shared.state).finished;
+ *crate::render_queue::lock(&shared.state) = JobState { finished: fin, ..state };
+ }
+ WorkerReply::Item { update } => crate::render_queue::lock(&shared.updates).push(update),
+ WorkerReply::Failed { error } => {
+ log::warn!("render worker: {error}");
+ let cur = crate::render_queue::lock(&shared.state).current;
+ if let Some(id) = cur {
+ crate::render_queue::lock(&shared.updates).push(ItemUpdate::Finished {
+ id,
+ status: RenderStatus::Failed(error),
+ seconds: 0.0,
+ output: None,
+ });
+ }
+ }
+ WorkerReply::Done => crate::render_queue::lock(&shared.state).finished = true,
+ _ => {}
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn round<T: Serialize + for<'de> Deserialize<'de>>(v: &T) -> String {
+ let a = serde_json::to_string(v).unwrap();
+ let back: T = serde_json::from_str(&a).unwrap();
+ let b = serde_json::to_string(&back).unwrap();
+ assert_eq!(a, b);
+ a
+ }
+
+ #[test]
+ fn protocol_round_trips() {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", serde_json::json!({})).unwrap();
+ let comp = s.active_comp_id().unwrap();
+ s.execute("renderQueue.add", serde_json::json!({})).unwrap();
+ let item = s.project.render_queue[0].clone();
+ let reqs = [
+ WorkerJob::Render { items: vec![vec![(item.clone(), "/out.gif".into())]] },
+ WorkerJob::Warp { comp, layer: LayerId(3), effect: 9 },
+ WorkerJob::RotoFreeze { comp, layer: LayerId(3), effect: 9 },
++ WorkerJob::Camera { comp, layer: LayerId(3), effect: 9 },
+ WorkerJob::Track {
+ comp,
+ layer: LayerId(1),
+ tracker: 4,
+ direction: crate::tracking::Direction::Backward,
+ settings: TrackerSettings::default(),
+ points: vec![PointValues {
+ uid: 5,
+ spec: effectcraft_track::PointSpec { center: [1.0, 2.0], feature_size: [3.0, 4.0], search_offset: [0.5, 0.0], search_size: [9.0, 9.0] },
+ attach_offset: [0.25, -1.0],
+ }],
+ times: vec![Tick::ZERO, Tick::from_seconds_f64(0.5)],
+ },
+ WorkerJob::MaskTrack {
+ comp,
+ layer: LayerId(2),
+ mask: 7,
+ direction: crate::tracking::Direction::Forward,
+ path: ShapePath::ellipse([10.0, 20.0], 5.0, 6.0),
+ method: MaskMethod::Perspective,
+ times: vec![Tick::from_seconds_f64(1.0)],
+ },
+ ];
+ for job in reqs {
+ let kind = job.kind();
+ let req = WorkerRequest { id: 42, project: s.project.to_json(), files: footage_files(&s.project), job };
+ let t = round(&req);
+ assert!(t.contains("\"kind\":"), "{kind:?}");
+ let back: WorkerRequest = serde_json::from_str(&t).unwrap();
+ assert_eq!(back.job.kind(), kind);
+ assert_eq!(Project::from_json(&back.project).unwrap(), *s.project);
+ }
+ let g = s.active_comp().unwrap().layers[0].props.clone();
+ for r in [
+ WorkerReply::Render { state: JobState { current: Some(3), done: 4, total: 10, items_total: 1, ..Default::default() } },
+ WorkerReply::Item { update: ItemUpdate::Started { id: 3, unix: 1_700_000_000 } },
+ WorkerReply::Item { update: ItemUpdate::Finished { id: 3, status: RenderStatus::Failed("x".into()), seconds: 1.5, output: Some("/a.gif".into()) } },
+ WorkerReply::Progress { done: 1, total: 2 },
+ WorkerReply::Group { comp, layer: LayerId(1), group: Box::new(g), message: "ok".into() },
+ WorkerReply::Failed { error: "boom".into() },
+ WorkerReply::Done,
+ ] {
+ let t = round(&r);
+ assert!(t.starts_with("{\"type\":"), "{t}");
+ }
+ }
+
+ /// An [`Offload`] that runs the job right away in a second session, through JSON (what a
+ /// Web Worker does, minus the threads).
+ struct Inline;
+ impl Offload for Inline {
+ fn start(&self, req: WorkerRequest, inbox: Arc<Inbox>) -> Result<(), String> {
+ let req: WorkerRequest = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap();
+ let mut w = Session { exporter: Some(Arc::new(crate::rq_tests::MockExporter { log: Default::default() })), ..Default::default() };
+ let post: Post = Rc::new(move |r| inbox.push(serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap()));
+ run_request(&mut w, req, &post);
+ Ok(())
+ }
+ fn cancel(&self, _: u64) {}
+ }
+
+ #[test]
+ fn render_runs_through_the_offload() {
+ let mut s = Session {
+ exporter: Some(Arc::new(crate::rq_tests::MockExporter { log: Default::default() })),
+ offload: Some(Arc::new(Inline)),
+ ..Default::default()
+ };
+ s.execute("file.openDemoProject", serde_json::json!({})).unwrap();
+ s.execute("renderQueue.add", serde_json::json!({"output": "/x.gif"})).unwrap();
+ let ids = s.start_render(false).unwrap();
+ // (the inline offload has replied already; replies are applied when polled)
+ s.poll_render();
+ assert!(s.render_job.is_none());
+ let it = s.project.render_queue.iter().find(|i| i.id == ids[0]).unwrap();
+ assert_eq!(it.status, RenderStatus::Done, "{:?}", it.status);
+ assert!(it.last_output.as_deref().is_some_and(|o| o.ends_with("x.gif")));
+ // `wait` renders inline.
+ s.execute("renderQueue.add", serde_json::json!({"output": "/y.gif"})).unwrap();
+ s.start_render(true).unwrap();
+ assert!(s.render_job.is_none() || s.render_job.as_ref().unwrap().remote.is_none());
+ }
+
+ /// Runs jobs in a session sharing `footage` (the synthetic clip of the tracking tests).
+ struct InlineWith(Arc<dyn effectcraft_render::FootageSource>);
+ impl Offload for InlineWith {
+ fn start(&self, req: WorkerRequest, inbox: Arc<Inbox>) -> Result<(), String> {
+ let req: WorkerRequest = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap();
+ let mut w = Session { footage: self.0.clone(), ..Default::default() };
+ let post: Post = Rc::new(move |r| inbox.push(serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap()));
+ run_request(&mut w, req, &post);
+ Ok(())
+ }
+ fn cancel(&self, _: u64) {}
+ }
+
+ /// Never replies (a job still running); records cancellations.
+ #[derive(Default)]
+ struct Hanging(Mutex<Vec<u64>>);
+ impl Offload for Hanging {
+ fn start(&self, _: WorkerRequest, _: Arc<Inbox>) -> Result<(), String> {
+ Ok(())
+ }
+ fn cancel(&self, id: u64) {
+ self.0.lock().unwrap().push(id);
+ }
+ }
+
+ fn pose(f: u32) -> ([f64; 2], f64, f64) {
+ ([150.0 + 2.0 * f as f64, 110.0 + 1.0 * f as f64], 0.0, 1.0)
+ }
+
+ #[test]
+ fn track_analysis_runs_through_the_offload_as_one_undo_step() {
+ let (mut s, clip, _) = crate::tests_track::setup(crate::tests_track::patch_frames(pose));
+ s.offload = Some(Arc::new(InlineWith(s.footage.clone())));
+ s.execute("track.motion", serde_json::json!({})).unwrap();
+ s.execute("track.setPoint", serde_json::json!({"point": 1, "center": pose(0).0, "featureSize": [36, 36], "searchSize": [80, 80]})).unwrap();
+ let undo = s.history.undo.len();
+ s.execute("track.analyze", serde_json::json!({"direction": "forward"})).unwrap();
+ assert!(s.is_tracking() && s.track_job.is_none(), "offloaded, not on a thread");
+ assert!(s.track_progress().is_some());
+ assert!(s.poll_offload());
+ assert!(!s.is_tracking() && s.offloaded.is_empty());
+ let l = s.active_comp().unwrap().layer(clip).unwrap();
+ let tp = l.trackers().next().unwrap().0.track_points().next().unwrap().clone();
+ let fc = tp.get("featureCenter").unwrap();
+ assert_eq!(fc.keys.len(), 25);
+ let v = fc.value_at(crate::tests_track::frame_time(12)).as_vec2();
+ assert!((v[0] - pose(12).0[0]).abs() < 0.3 && (v[1] - pose(12).0[1]).abs() < 0.3, "{v:?}");
+ assert_eq!(s.history.undo.len(), undo + 1);
+ assert_eq!(s.history.undo.last().unwrap().0, "Analyze Track");
+ assert!(s.events.iter().any(|e| matches!(e, Event::Toast { message, error: false } if message.starts_with("Tracked"))));
+ assert!(s.undo());
+ let l = s.active_comp().unwrap().layer(clip).unwrap();
+ assert!(l.trackers().next().unwrap().0.track_points().next().unwrap().get("featureCenter").unwrap().keys.is_empty());
+ // `wait` runs inline.
+ s.redo();
+ s.execute("track.analyze", serde_json::json!({"direction": "forward", "wait": true})).ok();
+ assert!(s.offloaded.is_empty());
+ }
+
+ #[test]
+ fn cancelling_offloaded_jobs() {
+ let (mut s, _, _) = crate::tests_track::setup(crate::tests_track::patch_frames(pose));
+ let off = Arc::new(Hanging::default());
+ s.offload = Some(off.clone());
+ s.exporter = Some(Arc::new(crate::rq_tests::MockExporter { log: Default::default() }));
+ // Analysis: stopping drops the job, nothing is written.
+ s.execute("track.motion", serde_json::json!({})).unwrap();
+ let rev = s.revision;
+ s.execute("track.analyze", serde_json::json!({})).unwrap();
+ assert!(s.is_tracking());
+ assert!(s.execute("track.analyze", serde_json::json!({})).is_err(), "one at a time");
+ assert!(s.stop_track());
+ s.poll_offload();
+ assert!(!s.is_tracking());
+ assert_eq!(off.0.lock().unwrap().len(), 1);
+ assert!(s.events.iter().any(|e| matches!(e, Event::Toast { message, .. } if message.contains("stopped"))));
+ assert!(s.revision > rev);
+ // Render: the queued items become User Stopped.
+ s.execute("renderQueue.add", serde_json::json!({"output": "/a.gif"})).unwrap();
+ let ids = s.start_render(false).unwrap();
+ assert!(s.is_rendering());
+ assert!(s.stop_render());
+ s.poll_render();
+ assert!(!s.is_rendering());
+ assert_eq!(off.0.lock().unwrap().len(), 2);
+ let it = s.project.render_queue.iter().find(|i| i.id == ids[0]).unwrap();
+ assert_eq!(it.status, RenderStatus::UserStopped);
+ }
+
+ #[test]
+ fn progress_hook_is_scoped() {
+ report(1, 2); // no hook: nothing happens
+ let seen = Rc::new(RefCell::new(vec![]));
+ let s2 = seen.clone();
+ with_hook(Box::new(move |d, t| s2.borrow_mut().push((d, t))), || {
+ report(1, 3);
+ report(2, 3);
+ });
+ report(3, 3);
+ assert_eq!(*seen.borrow(), vec![(1, 3), (2, 3)]);
+ }
+}
diff --cc crates/engine/src/session_settings.rs
index a38012cbb,e54eb93bb..1a3370e47
--- a/crates/engine/src/session_settings.rs
+++ b/crates/engine/src/session_settings.rs
@@@ -36,6 -37,42 +37,43 @@@ impl Session
self.prefs_revision += 1;
}
+ /// Apply Settings ▸ Media & Disk Cache ▸ Disk Cache: open (or close) the persistent cache
+ /// and attach it to the layer cache. Without a folder setting the platform cache folder is
+ /// used, but only by frontends with a settings store (headless sessions stay off disk).
+ pub fn configure_disk_cache(&mut self) {
+ use effectcraft_render::disk_cache::{DiskCache, default_folder, footage_salt};
+ let d = &self.prefs.disk;
+ let folder = if d.disk_cache_folder.trim().is_empty() {
- self.config.is_some().then(default_folder)
++ (self.config.is_some() && !cfg!(target_arch = "wasm32")).then(default_folder)
+ } else {
+ Some(std::path::PathBuf::from(d.disk_cache_folder.trim()))
+ };
+ let max = d.disk_cache_max_gb.max(1) as u64 * (1 << 30);
- let Some(folder) = folder.filter(|_| d.disk_cache_enabled) else {
++ // (no file system in the browser: the disk cache stays off there)
++ let Some(folder) = folder.filter(|_| d.disk_cache_enabled && !cfg!(target_arch = "wasm32")) else {
+ self.disk_cache = None;
+ self.layer_cache.set_disk(None);
+ return;
+ };
+ let dc = match &self.disk_cache {
+ Some(c) if c.folder() == folder.as_path() => {
+ c.set_max_bytes(max);
+ c.clone()
+ }
+ _ => match DiskCache::open(&folder, max) {
+ Ok(c) => c,
+ Err(e) => {
+ log::warn!("disk cache at {}: {e}", folder.display());
+ self.disk_cache = None;
+ self.layer_cache.set_disk(None);
+ return;
+ }
+ },
+ };
+ self.layer_cache.set_disk(Some((dc.clone(), footage_salt(&self.project))));
+ self.disk_cache = Some(dc);
+ }
+
/// Write settings to the config store.
pub fn save_prefs(&self) {
if let Some(c) = &self.config
diff --cc crates/ui-egui/src/frames.rs
index 3d3bef947,d0e5a6d93..fd6283514
--- a/crates/ui-egui/src/frames.rs
+++ b/crates/ui-egui/src/frames.rs
@@@ -118,12 -124,41 +124,43 @@@ pub struct RenderSource
pub layer_cache: Arc<LayerCache>,
/// GPU compositor on the viewer's device (Mercury GPU Acceleration), if available.
pub gpu: Option<Gpu>,
- /// Keep GPU frames on the GPU for the viewer (native egui-wgpu textures). Off by default:
- /// Show Channel / exposure / region-of-interest drawing read the CPU frame texture, so GPU
- /// frames are read back (the compositing still runs on the GPU).
+ /// Keep GPU frames on the GPU for the viewer (native egui-wgpu textures). Off on the
+ /// desktop: Show Channel / exposure / region-of-interest drawing read the CPU frame texture,
+ /// so GPU frames are read back (the compositing still runs on the GPU). On in the browser
+ /// while the viewer draws plainly, because there frames can't be read back synchronously
+ /// (`EffectcraftApp::gpu_display`).
pub gpu_display: bool,
+ /// The persistent disk cache, when enabled.
+ pub disk: Option<Arc<DiskCache>>,
+ }
+
+ /// Content keys of (project revision, comp), computed once per revision.
+ type ContentKeys = Arc<Mutex<HashMap<(u64, u64), u128>>>;
+
+ fn content_key(keys: &ContentKeys, project: &Project, revision: u64, comp: u64) -> u128 {
+ if let Some(k) = keys.lock().ok().and_then(|m| m.get(&(revision, comp)).copied()) {
+ return k;
+ }
+ let k = disk_cache::comp_content_key(project, ItemId(comp));
+ if let Ok(mut m) = keys.lock() {
+ if m.len() > 256 {
+ m.clear();
+ }
+ m.insert((revision, comp), k);
+ }
+ k
+ }
+
+ fn opts_hash(o: &RenderOpts) -> u64 {
+ let mut h = disk_cache::Hash128::default();
+ h.write(format!("{o:?}").as_bytes());
+ h.finish() as u64
+ }
+
+ /// Disk key of a viewer frame (render options included: region of interest, draft…).
+ fn frame_disk_key(keys: &ContentKeys, project: &Project, key: &FrameKey, opts_hash: u64) -> u128 {
+ let content = content_key(keys, project, key.revision, key.comp);
+ disk_cache::frame_key(content, key.frame, key.scale, key.view ^ opts_hash)
}
pub struct Frames {
diff --cc crates/ui-egui/src/lib.rs
index 9670e882e,0976c47a0..212028e4b
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -326,7 -323,8 +326,8 @@@ impl EffectcraftApp
expr: self.session.expr.clone(),
layer_cache: self.session.layer_cache.clone(),
gpu: self.gpu.clone(),
- gpu_display: false,
+ gpu_display: self.gpu_display(),
+ disk: self.session.disk_cache.clone(),
}
}
diff --cc docs/parity.md
index 9fee79ca5,32cb65b79..dadce4cd8
--- a/docs/parity.md
+++ b/docs/parity.md
@@@ -93,9 -120,9 +120,9 @@@ the disk cache in the formats wave; th
| Compositions | 72% | 6.0 | Essential Graphics panel (the marker dialog and Composition Flowchart landed) |
| Animation | 65% | 10.4 | puppet, Wiggler/Smoother/Motion Sketch (motion-path handles and the graph editor transform box landed in M5.8) |
| Text | ≈ 86% | 1.3 | vertical type is basic (upright characters, no tate-chu-yoko), no OpenType feature panel, no extruded strokes (extruded, bevelled text landed in M7.6); per-character styles, paragraph settings, on-canvas editing and the `sourceText` style API landed (M9.9–M9.10) |
-| Web | 60% | 2.5 | threads, browser storage, audio |
+| Web | 85% | 1.0 | viewer frames and Roto Brush propagation still on the page's thread; GPU effects in the browser (browser storage, Web Audio, Web Worker renders/analyses, WebGPU viewer and offline install landed in M15.2) |
- | 3D | 72% | 12.0 | 3D camera tracker, multi-view layouts, Advanced 3D motion blur and blend modes, cameras/lights from models; Advanced 3D (glTF/OBJ models, primitives, extruded text and shapes, PBR, image-based light, shadow maps, GPU rasteriser) landed in M7.4–M7.6 |
- | Effects | ≈ 75% | 5.0 | GPU versions of more effects and the 3D Camera Tracker (every other After Effects effect exists since M9.11 and M12.5) |
+ | 3D | 76% | 10.0 | multi-view layouts, Advanced 3D motion blur and blend modes, cameras/lights from models; Advanced 3D (glTF/OBJ models, primitives, extruded text and shapes, PBR, image-based light, shadow maps, GPU rasteriser) landed in M7.4–M7.6 |
+ | Effects | ≈ 75% | 5.0 | GPU versions of more effects (every After Effects effect exists since M9.11, M12.5 and M12.6) |
| Interface | 70% | 6.0 | Timeline horizontal scrolling of many columns, a richer Learn area (native macOS menu bar, Timeline columns/search/reveal-add, Home screen with recent projects and all AE workspaces landed; viewer rulers/snapping/channels/snapshots landed in M0.13) |
| Project | 53% | 8.1 | 8/16/32-bit pipeline and colour management, auto-save, proxies, folder moves |
| Masks & roto | 68% | 6.0 | variable-width mask feather points, Roto Brush's learned (3.0) segmentation model (mask tracking and Mask Interpolation landed in M6.6; Roto Brush & Refine Edge with graph-cut segmentation, flow propagation, edge matting, decontamination and Freeze in M6.7) |
diff --cc docs/web.md
index 2c3d7ea3e,7c4ec31da..041ef76cf
--- a/docs/web.md
+++ b/docs/web.md
@@@ -49,103 -40,23 +49,103 @@@ thread), `?nosw` (don't register the se
| Desktop | Web |
|---|---|
| frame render thread pool (`ui-egui/src/frames.rs`) | `Frames::pump`: queued frames render on the UI thread after each egui frame, most important first (the viewer's frame, then prefetch), within 40 ms (24 ms while playing) |
-| Render Queue on a background thread | `Session::start_render` always runs inline on wasm32: the page waits until the render is done |
+| Render Queue on a background thread | a Web Worker running a second engine instance (below); progress streams back, the page never waits |
- | tracker / mask tracker / Warp Stabilizer / Roto Brush Freeze threads | the same workers; the analysed property group comes back as one undo step |
++| tracker / mask tracker / Warp Stabilizer / 3D Camera Tracker / Roto Brush Freeze threads | the same workers; the analysed property group comes back as one undo step |
| `rayon` parallel loops (raster, effects, export batches) | rayon's global pool falls back to the calling thread when threads are unavailable: same code, serial |
| `std::time::Instant` / `SystemTime` (panic on wasm32) | `web-time` (re-exports `std::time` on native) |
-| `std::fs` project reads/writes (`FsServices`) | `files::WebServices`: an in-memory file table; saving downloads the `.ecproj` |
+| `std::fs` project reads/writes (`FsServices`) | `files::WebServices`: the virtual file table, persisted (below); saving also downloads the `.ecproj` |
+| config directory: settings, shortcut presets, recent projects, the recovery sentinel | `store::WebConfig` in browser storage |
+| auto-save folder | `/EffectCraft Auto-Save/` in browser storage (`ConfigStore::files`) |
| media reads (`MediaPool`, `probe`) | `files::WebImporter`: bytes from the file table, handed to `MediaPool::add_bytes` / `probe_bytes` |
| export writes (`effectcraft-export`) | the job's `sink` (`effectcraft_host::FileExporter { sink }`): files land in the table and download after the render; several files (an image sequence) download as one stored `.zip` |
| rfd file dialogs | `<input type=file>` for File ▸ Open / Import; drop files anywhere on the page (`.ecproj` opens, everything else imports); "Save As" / "Output To" pick a download name |
| system fonts | not scanned; the bundled fonts (Inter, Noto Serif, JetBrains Mono) are always there |
| TCP control channel / MCP | `window.effectcraft` (below) |
-| audio output | none yet (if `cpal` lands for desktop playback it must stay behind a cfg/feature off wasm32; a WebAudio backend would replace it) |
+| cpal audio output | Web Audio (below) |
+| GPU compositor on the desktop's wgpu device | the same compositor on eframe's WebGPU device (below) |
-### Threads
+### Persistence
-wasm threads need a cross-origin isolated page **and** a wasm build with atomics (a nightly
-`build-std` toolchain), so this build is single-threaded: frames, effects and exports run on the UI
-thread. A long Render Queue job freezes the page until it finishes; keep web renders short or
-small (resolution, time span).
+Everything that lives in files on the desktop lives in the browser's **Origin Private File
+System** (OPFS); where OPFS can't be written from the page (older Safari), **IndexedDB**; with
+neither (some private windows), memory only. `effectcraft.info().storage.backend` says which.
+The page asks for persistent storage (`navigator.storage.persist()`), which browsers grant to
+installed apps, so the store isn't evicted under storage pressure.
+
+The engine's storage traits are synchronous and the browser's are not, so the app works on an
+in-memory mirror (`store.rs`): every stored entry is read before the app starts, reads and writes
+hit the mirror, and changes flush in the background (one write per changed key, in order; OPFS
+writes are atomic: a swap file replaced on close). Keys:
+
+| Key | What |
+|---|---|
+| `config/prefs.json`, `config/shortcuts.json` | Settings (with File ▸ Open Recent's list) and keyboard shortcut presets |
+| `config/session.lock` | the crash-recovery sentinel |
+| `config/session.ecproj`, `config/session.json` | the session snapshot: the open project and editor state (active comp, time, selection), written at most once a second while they change |
+| `files/<path>` | the file table: imported media, projects saved with File ▸ Save / Save As or `saveToBrowser`, auto-saves |
+
+On the next visit the app reopens the snapshot (unsaved changes stay unsaved: the project is
+dirty), registers every stored media file with the media pool so its footage decodes, and File ▸
+Open Recent reopens saved projects from storage. Without a snapshot (first visit) it opens the
+demo project. Render outputs are not stored: they download.
+
+### Background jobs: Web Workers
+
+wasm threads need shared memory, which needs a nightly `build-std` toolchain, so this build is
+single-threaded per instance. Long jobs run in **Web Workers** instead, each with its own instance
+of the same module (the page compiles it once and posts the `WebAssembly.Module`, so nothing is
+compiled twice) and its own memory (`crates/engine/src/offload.rs`, `src/worker.rs`):
+
+1. The session's `Offload` serializes a `WorkerRequest`: the project JSON, the footage paths it
- reads, and the job (`render` with the resolved queue items and output paths; `warp`, `track`,
- `maskTrack`, `rotoFreeze` with the target and analysis parameters).
++ reads, and the job (`render` with the resolved queue items and output paths; `warp`, `camera`,
++ `track`, `maskTrack`, `rotoFreeze` with the target and analysis parameters).
+2. `js/host.js` takes an idle worker from its pool (or starts one), sends it the footage bytes it
+ doesn't have yet, then the request.
+3. The worker runs the job on a plain engine session, blocking, and posts `WorkerReply`s: render
+ progress (at most every 100 ms), item started/finished, rendered files (transferred), analysis
+ progress, the analysed property group, `failed`, `done`.
+4. The page applies them every frame: `Session::poll_render` updates the queue items and the
+ progress bar, `Session::poll_offload` writes an analysis result as one undo step (the effect /
+ tracker / mask group is replaced; other edits made meanwhile are kept) and the downloads start.
+
+Stopping a job terminates its worker (a worker can't be interrupted mid-frame): the item being
+rendered becomes "User Stopped", an analysis writes nothing. `renderQueue.render {wait: true}` (the
+default for agents) and analysis commands with `wait: true` still run on the page's thread and
+return when done. Roto Brush propagation fills the session's segmentation cache rather than the
+project, so it runs on the page's thread too, as do viewer frames (`Frames::pump`).
+
+### Audio
+
+Audio preview goes through **Web Audio**: an AudioWorklet (`audio-worklet.js`; a
+ScriptProcessorNode where worklets are unavailable) plays interleaved stereo blocks. The mixdown
+is the desktop's (`AudioPlayback`, `mix_comp`): without a feeder thread, `AudioPlayback::pump`
+mixes ahead on every UI frame (≈ 350 ms queued) and the output device takes what keeps it
+≈ 150 ms ahead of the playhead. A/V sync follows `AudioContext.currentTime`: the playback clock
+is the frames played by the context clock minus its output latency, and the viewer shows the
+frame under the audible sample, as on the desktop. The Audio panel's meters read the same feed.
+
+Browsers start an AudioContext suspended until the user interacts with the page; the app resumes
+it on the first pointer or key event, so audio plays from the first preview after any click or
+key press.
+
+### GPU
+
+eframe starts on WebGPU where the browser has it (WebGL2 otherwise), and the GPU compositor
+(`effectcraft-gpu`) runs on the same device: viewer frames are composited by compute shaders and
+drawn straight from their texture, with no readback. Steps that need the CPU mid-render (3D runs,
+adjustment layers, CPU-only effects) fall back to the CPU renderer for that frame, because the
+page's thread can't wait for a GPU readback. The Info panel's pixel readout and the eyedroppers
+read GPU frames back asynchronously (`Gpu::read_display_async`: the pixels arrive a frame
+later). On WebGL2, or without a usable adapter, everything renders on the CPU.
+`effectcraft.info().gpu` reports `{compositor, viewerOnGpu}`.
+
+### Offline and install (PWA)
+
+`manifest.webmanifest` (name, icons, standalone display) makes the app installable; `sw.js`
+precaches every file of the build into a cache named after the build's hash, serves them
+cache-first (the cached responses keep the server's COOP/COEP headers, so the page stays
+cross-origin isolated offline), and drops older caches when a new build activates. After the
+first visit the app loads without a network.
## `window.effectcraft`: the agent / test API
@@@ -192,19 -94,10 +192,20 @@@ cargo xtask web --serve 8765
node apps/effectcraft-web/tests/smoke.mjs --url http://127.0.0.1:8765/ --out target/web/smoke
```
+Native unit tests cover the storage model (`apps/effectcraft-web/src/store.rs`: write
+coalescing, file table, `ConfigStore` / `FileOps`, auto-save and crash recovery through the
+browser store) and the worker protocol (`crates/engine/src/offload.rs`: serde round trips of
+every request and reply, a render through an in-process offload).
+
## Gaps
-- Single-threaded (above); Render Queue renders block the page.
-- No audio playback.
-- Imported media live in memory for the session only (nothing is persisted; reload = fresh start).
+- Viewer frames, RAM preview and Roto Brush propagation still render on the page's thread (one
+ frame at a time between UI frames).
+- GPU effects run only in the desktop GPU path: in the browser, effects run on the CPU (inside
+ workers for renders) because the page's thread can't wait for mid-render readbacks.
++- No disk cache (Settings ▸ Media & Disk Cache) in the browser: the layer cache stays in memory.
+- Cancelling an analysis drops its partial result (the worker is terminated).
+- Stored media count against the origin's storage quota; `effectcraft.listStored()` shows usage,
+ `removeStored` frees it (there is no storage manager in the UI yet).
- `engine.execute` rejects the spread Render Settings / Output Module keys of `renderQueue.add`
(`resolution`, `timeSpan`…) through its strict parameter check; use `ui.menu.invoke` as above.