From 36cc7d91f10e6892db02568335abf469bc62309c Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:46:15 +0200 Subject: [PATCH 001/324] Keep Essential Graphics instance keyframes in the comp so valueAtTime and numKeys see them (#1682) --- crates/engine/src/tests_essential_more.rs | 55 ++++++++++++++++++++++- crates/project/src/essential.rs | 10 +++-- crates/render/src/lib.rs | 9 +++- 3 files changed, 69 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests_essential_more.rs b/crates/engine/src/tests_essential_more.rs index a8d8dc808..22b03e8e4 100644 --- a/crates/engine/src/tests_essential_more.rs +++ b/crates/engine/src/tests_essential_more.rs @@ -64,7 +64,7 @@ fn font_and_scale_controls_override_per_instance() { let mut v = vec![]; g.walk("", &mut |_, p| { if let Some(c) = essential::control_of(&p.match_id) { - v.push(essential::Override { control: c, value: p.value.clone() }); + v.push(essential::Override { control: c, value: p.value.clone(), keys: vec![] }); } }); v @@ -102,3 +102,56 @@ fn open_in_essential_graphics_sets_the_primary_comp() { ); assert_eq!(s.execute("essential.list", json!({})).unwrap()["name"], "A"); } + +#[test] +fn instance_keyframes_reach_the_comp_so_expressions_can_look_ahead() { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "frameRate": 30, "duration": 2})).unwrap(); + let inner = s.active_comp_id().unwrap(); + let text = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap(); + let ctl = s.execute("essential.addProperty", json!({"layer": text, "path": "transform/opacity"})).unwrap()["controls"][0].as_u64().unwrap(); + let keys = vec![ + effectcraft_keyframe::Keyframe::new(effectcraft_time::Tick::ZERO, KV::Scalar(0.0)), + effectcraft_keyframe::Keyframe::new(effectcraft_time::Tick::from_seconds_f64(1.0), KV::Scalar(100.0)), + ]; + let over = [essential::Override { control: ctl, value: KV::Scalar(25.0), keys: keys.clone() }]; + let p = essential::with_overrides(&s.project, inner, &over).unwrap(); + let pr = p.comp(inner).unwrap().layer(effectcraft_project::LayerId(text)).unwrap().props.prop("transform/opacity").unwrap(); + assert_eq!(pr.keys, keys); + assert_eq!(pr.value, KV::Scalar(25.0)); +} + +#[test] +fn keys_set_on_an_instance_are_passed_to_the_nested_comp_render() { + use effectcraft_project::LayerId; + use effectcraft_time::Tick; + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "frameRate": 30, "duration": 2})).unwrap(); + let inner = s.active_comp_id().unwrap(); + let solid = s.execute("layer.newSolid", json!({"name": "BG", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("essential.addProperty", json!({"layer": solid, "path": "transform/opacity"})).unwrap(); + s.execute("comp.new", json!({"name": "Scene", "width": 32, "height": 32, "frameRate": 30, "duration": 2})).unwrap(); + let scene = s.active_comp_id().unwrap(); + let inst = s.execute("layer.addItem", json!({"item": inner.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap(); + let path = s.execute("essential.instance", json!({"layer": inst})).unwrap()["controls"][0]["path"].as_str().unwrap().to_string(); + s.execute("prop.addKey", json!({"layer": inst, "path": path, "time": 0.0, "value": 0.0})).unwrap(); + s.execute("prop.addKey", json!({"layer": inst, "path": path, "time": 1.0, "value": 100.0})).unwrap(); + // At 0.25 s the nested comp's opacity carries the instance's keys, so it reads the instance's + // value half a second ahead too (valueAtTime), not only the current one. + let nested_opacity = |s: &Session| { + let comp = s.project.comp(scene).unwrap(); + let layer = comp.layer(LayerId(inst)).unwrap(); + let ctx = effectcraft_render::EvalCtx::new(&s.project, scene, comp, Tick::from_seconds_f64(0.25)); + let over = effectcraft_render::essential_overrides(&ctx, layer); + let p = essential::with_overrides(&s.project, inner, &over).unwrap(); + p.comp(inner).unwrap().layer(LayerId(solid)).unwrap().props.prop("transform/opacity").unwrap().clone() + }; + let pr = nested_opacity(&s); + let ahead = s.project.comp(scene).unwrap().layer(LayerId(inst)).unwrap().props.prop(&path).unwrap().value_at(Tick::from_seconds_f64(0.75)); + assert_eq!(pr.keys.len(), 2); + assert_eq!(pr.value_at(Tick::from_seconds_f64(0.75)), ahead); + assert_ne!(pr.value_at(Tick::from_seconds_f64(0.75)), pr.value_at(Tick::from_seconds_f64(0.25))); + // With Time Remap the instance's layer time is not the nested comp's time: only the value. + s.execute("layer.enableTimeRemap", json!({"layers": [inst]})).unwrap(); + assert!(nested_opacity(&s).keys.is_empty()); +} diff --git a/crates/project/src/essential.rs b/crates/project/src/essential.rs index 3d851f902..5cc21de31 100644 --- a/crates/project/src/essential.rs +++ b/crates/project/src/essential.rs @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; use crate::props::{GroupKind, Node, ParamUi, PropGroup, Property, Uid}; -use crate::{ItemId, ItemKind, Layer, LayerId, LayerSource, Project, Value}; +use crate::{ItemId, ItemKind, Keyframe, Layer, LayerId, LayerSource, Project, Value}; /// Match id of the Essential Properties group on precomp layers. pub const GROUP: &str = "essential"; @@ -652,10 +652,14 @@ pub fn sync_project(before: &Project, after: &mut Project) { pub struct Override { pub control: u64, pub value: Value, + /// The instance property's keyframes, already in the nested comp's time. Empty when the + /// property is not keyed (or its keys can't be mapped); expressions in the comp then see + /// only `value`. + pub keys: Vec, } /// The project as an instance of `comp` renders it: each overridden control's source property -/// set to the instance value (keyframes dropped; its expression, if any, still applies) and +/// set to the instance value and keyframes (its expression, if any, still applies) and /// replaced media swapped in. `None` when nothing applies. pub fn with_overrides(project: &Project, comp: ItemId, overrides: &[Override]) -> Option { let eg = project.comp(comp)?.essential.clone()?; @@ -683,7 +687,7 @@ pub fn with_overrides(project: &Project, comp: ItemId, overrides: &[Override]) - EgKind::Property { .. } => { for (layer, prop) in ctl.kind.targets() { if let Some(pr) = c.layer_mut(layer).and_then(|l| l.props.find_mut(prop)) { - pr.keys.clear(); + pr.keys = o.keys.clone(); pr.value = o.value.clone(); any = true; } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index cfefd02db..b94cdac2f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -369,12 +369,19 @@ pub fn essential_overrides(ctx: &EvalCtx, layer: &Layer) -> Vec 1e-9 + && matches!(layer.source, LayerSource::Comp { item } if ctx.project.comp(item).is_some_and(|nc| !eval::protected_regions(nc).is_empty())); + let same_time = layer.props.get("timeRemap").is_none() && !responsive; let mut out = vec![]; g.walk("", &mut |_, p| { if over.contains(&p.uid) && let Some(control) = essential::control_of(&p.match_id) { - out.push(essential::Override { control, value: ctx.value(layer, p) }); + // An expression on the instance property replaces its keys. + let keys = if same_time && !p.has_expression() { p.keys.clone() } else { vec![] }; + out.push(essential::Override { control, value: ctx.value(layer, p), keys }); } }); out From c6e91da8bbfd9e5862c00616108aee0e0b6ef7f5 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:39:52 +0200 Subject: [PATCH 002/324] Map Essential Graphics instance keys into each target layer's time (#1682) --- crates/engine/src/tests_essential_more.rs | 100 ++++++++++++++++++++++ crates/project/src/essential.rs | 37 ++++++-- 2 files changed, 132 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests_essential_more.rs b/crates/engine/src/tests_essential_more.rs index 22b03e8e4..32f8ac4a6 100644 --- a/crates/engine/src/tests_essential_more.rs +++ b/crates/engine/src/tests_essential_more.rs @@ -155,3 +155,103 @@ fn keys_set_on_an_instance_are_passed_to_the_nested_comp_render() { s.execute("layer.enableTimeRemap", json!({"layers": [inst]})).unwrap(); assert!(nested_opacity(&s).keys.is_empty()); } + +/// Inner comp with two opacity-exposed solids (the second linked to the first's control), an +/// instance of it in Scene keyed 0 -> 100 over 0..1 s. `timing` sets each solid's start (s) and +/// stretch (%). Returns the pieces the checks below need. +fn keyed_instance(timing: [(f64, f64); 2]) -> (Session, effectcraft_project::ItemId, effectcraft_project::ItemId, [u64; 2], u64) { + use effectcraft_project::LayerId; + use effectcraft_time::Tick; + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let inner = s.active_comp_id().unwrap(); + let a = s.execute("layer.newSolid", json!({"name": "A", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap(); + let ctl = s.execute("essential.addProperty", json!({"layer": a, "path": "transform/opacity"})).unwrap()["controls"][0].as_u64().unwrap(); + let b = s.execute("layer.newSolid", json!({"name": "B", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("essential.linkProperty", json!({"control": ctl, "layer": b, "path": "transform/opacity"})).unwrap(); + for (id, (start, stretch)) in [a, b].into_iter().zip(timing) { + let l = std::sync::Arc::make_mut(&mut s.project).comp_mut(inner).unwrap().layer_mut(LayerId(id)).unwrap(); + l.start_time = Tick::from_seconds_f64(start); + l.stretch = stretch; + } + s.execute("comp.new", json!({"name": "Scene", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let scene = s.active_comp_id().unwrap(); + let inst = s.execute("layer.addItem", json!({"item": inner.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap(); + let path = s.execute("essential.instance", json!({"layer": inst})).unwrap()["controls"][0]["path"].as_str().unwrap().to_string(); + s.execute("prop.addKey", json!({"layer": inst, "path": path, "time": 0.0, "value": 0.0})).unwrap(); + s.execute("prop.addKey", json!({"layer": inst, "path": path, "time": 1.0, "value": 100.0})).unwrap(); + (s, scene, inner, [a, b], inst) +} + +/// Opacity of `solid` inside Inner as the instance renders it at nested time `t`, and the +/// overridden property itself (its keys are what `numKeys` / `valueAtTime` read). +fn rendered( + s: &Session, + scene: effectcraft_project::ItemId, + inner: effectcraft_project::ItemId, + inst: u64, + solid: u64, + t: f64, +) -> (f64, effectcraft_project::Property) { + use effectcraft_project::LayerId; + use effectcraft_time::Tick; + let comp = s.project.comp(scene).unwrap(); + let layer = comp.layer(LayerId(inst)).unwrap(); + let ctx = effectcraft_render::EvalCtx::new(&s.project, scene, comp, Tick::from_seconds_f64(t)); + let over = effectcraft_render::essential_overrides(&ctx, layer); + let p = essential::with_overrides(&s.project, inner, &over).unwrap(); + let ic = p.comp(inner).unwrap(); + let il = ic.layer(LayerId(solid)).unwrap(); + let pr = il.props.prop("transform/opacity").unwrap().clone(); + let ictx = effectcraft_render::EvalCtx::new(&p, inner, ic, Tick::from_seconds_f64(t)); + (ictx.value(il, &pr).as_f64(), pr) +} + +#[test] +fn instance_keys_follow_a_nested_layer_that_starts_late() { + use effectcraft_time::Tick; + let (s, scene, inner, [a, _], inst) = keyed_instance([(0.5, 100.0), (0.0, 100.0)]); + // The instance reads 75 at 0.75 s; the layer starting at 0.5 s must too, not 25. + let (v, pr) = rendered(&s, scene, inner, inst, a, 0.75); + assert!((v - 75.0).abs() < 1e-6, "rendered {v}"); + assert_eq!(pr.keys.len(), 2); + // Layer time: the 0 s and 1 s keys sit at -0.5 s and 0.5 s. + assert_eq!(pr.keys[0].time, Tick::from_seconds_f64(-0.5)); + assert_eq!(pr.keys[1].time, Tick::from_seconds_f64(0.5)); + // What valueAtTime reads: layer time 0.5 s is the end key, -0.5 s the start key. + assert_eq!(pr.value_at(Tick::from_seconds_f64(0.5)), KV::Scalar(100.0)); + assert_eq!(pr.value_at(Tick::from_seconds_f64(-0.5)), KV::Scalar(0.0)); +} + +#[test] +fn instance_keys_follow_a_stretched_nested_layer() { + use effectcraft_time::Tick; + let (s, scene, inner, [a, _], inst) = keyed_instance([(0.0, 200.0), (0.0, 100.0)]); + // Stretched to 200 %: nested time 0.5 s is layer time 0.25 s. + let (v, pr) = rendered(&s, scene, inner, inst, a, 0.5); + assert!((v - 50.0).abs() < 1e-6, "rendered {v}"); + assert_eq!(pr.keys.len(), 2); + assert_eq!(pr.keys[1].time, Tick::from_seconds_f64(0.5)); + assert_eq!(pr.value_at(Tick::from_seconds_f64(0.5)), KV::Scalar(100.0)); + // Offset and stretch together: starts at 0.25 s, 50 %: nested 0.5 s is layer time 0.5 s. + let (s, scene, inner, [a, _], inst) = keyed_instance([(0.25, 50.0), (0.0, 100.0)]); + let (v, pr) = rendered(&s, scene, inner, inst, a, 0.5); + assert!((v - 50.0).abs() < 1e-6, "rendered {v}"); + assert_eq!(pr.keys[0].time, Tick::from_seconds_f64(-0.5)); + assert_eq!(pr.keys[1].time, Tick::from_seconds_f64(1.5)); +} + +#[test] +fn one_control_with_targets_of_different_timing_stays_in_step() { + let (s, scene, inner, [a, b], inst) = keyed_instance([(0.5, 100.0), (0.0, 200.0)]); + for t in [0.2, 0.6, 0.75, 0.9] { + let (va, pa) = rendered(&s, scene, inner, inst, a, t); + let (vb, pb) = rendered(&s, scene, inner, inst, b, t); + let want = t * 100.0; + assert!((va - want).abs() < 1e-6, "A at {t}: {va}"); + assert!((vb - want).abs() < 1e-6, "B at {t}: {vb}"); + // Each target carries the keys in its own time. + assert_ne!(pa.keys[0].time, pb.keys[0].time); + assert_ne!(pa.keys[1].time, pb.keys[1].time); + } +} diff --git a/crates/project/src/essential.rs b/crates/project/src/essential.rs index 5cc21de31..021c1a8fc 100644 --- a/crates/project/src/essential.rs +++ b/crates/project/src/essential.rs @@ -16,6 +16,7 @@ use serde::{Deserialize, Serialize}; use crate::props::{GroupKind, Node, ParamUi, PropGroup, Property, Uid}; use crate::{ItemId, ItemKind, Keyframe, Layer, LayerId, LayerSource, Project, Value}; +use effectcraft_time::Tick; /// Match id of the Essential Properties group on precomp layers. pub const GROUP: &str = "essential"; @@ -647,14 +648,35 @@ pub fn sync_project(before: &Project, after: &mut Project) { after.next_id = after.next_id.max(next); } +/// Keys given in comp time, in the time of a layer that starts at `start` and is stretched to +/// `stretch` percent. Empty when the stretch is not a usable factor. +fn keys_in_layer_time(keys: &[Keyframe], start: Tick, stretch: f64) -> Vec { + if stretch.is_finite() && stretch > 0.0 { keys.iter().map(|k| key_in_layer_time(k, start, stretch)).collect() } else { vec![] } +} + +/// A key given in comp time, moved into the layer time of a layer that starts at `start` and is +/// stretched to `stretch` percent (the inverse of `Layer::comp_time`). Ease speeds are per +/// second, so they scale with the time axis; influences are fractions of the segment and stay. +fn key_in_layer_time(k: &Keyframe, start: Tick, stretch: f64) -> Keyframe { + let d = k.time - start; + let mut k = k.clone(); + k.time = if (stretch - 100.0).abs() < 1e-9 { d } else { Tick((d.0 as f64 * 100.0 / stretch) as i64) }; + if (stretch - 100.0).abs() >= 1e-9 { + for e in k.in_ease.iter_mut().chain(k.out_ease.iter_mut()) { + e.speed *= stretch / 100.0; + } + } + k +} + /// One instance override: the control and the value it takes in this instance. #[derive(Clone, Debug, PartialEq)] pub struct Override { pub control: u64, pub value: Value, - /// The instance property's keyframes, already in the nested comp's time. Empty when the - /// property is not keyed (or its keys can't be mapped); expressions in the comp then see - /// only `value`. + /// The instance property's keyframes, in the nested comp's time (`with_overrides` moves them + /// into each target layer's time). Empty when the property is not keyed (or its keys can't + /// be mapped); expressions in the comp then see only `value`. pub keys: Vec, } @@ -686,8 +708,13 @@ pub fn with_overrides(project: &Project, comp: ItemId, overrides: &[Override]) - } EgKind::Property { .. } => { for (layer, prop) in ctl.kind.targets() { - if let Some(pr) = c.layer_mut(layer).and_then(|l| l.props.find_mut(prop)) { - pr.keys = o.keys.clone(); + if let Some(l) = c.layer_mut(layer) { + let (start, stretch) = (l.start_time, l.stretch); + let Some(pr) = l.props.find_mut(prop) else { continue }; + // The keys are in nested comp time; the property reads them in this + // layer's own time (start offset, stretch). Without a usable mapping + // only the value is set. + pr.keys = keys_in_layer_time(&o.keys, start, stretch); pr.value = o.value.clone(); any = true; } From 102dd8be6c77a28848010e9adefd13ea537e9fa2 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:42:21 +0200 Subject: [PATCH 003/324] Give the multi-target Essential Graphics test distinct key times; group the Tick import --- crates/engine/src/tests_essential_more.rs | 2 +- crates/project/src/essential.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests_essential_more.rs b/crates/engine/src/tests_essential_more.rs index 32f8ac4a6..720c87e91 100644 --- a/crates/engine/src/tests_essential_more.rs +++ b/crates/engine/src/tests_essential_more.rs @@ -243,7 +243,7 @@ fn instance_keys_follow_a_stretched_nested_layer() { #[test] fn one_control_with_targets_of_different_timing_stays_in_step() { - let (s, scene, inner, [a, b], inst) = keyed_instance([(0.5, 100.0), (0.0, 200.0)]); + let (s, scene, inner, [a, b], inst) = keyed_instance([(0.5, 100.0), (0.25, 200.0)]); for t in [0.2, 0.6, 0.75, 0.9] { let (va, pa) = rendered(&s, scene, inner, inst, a, t); let (vb, pb) = rendered(&s, scene, inner, inst, b, t); diff --git a/crates/project/src/essential.rs b/crates/project/src/essential.rs index 021c1a8fc..cc3b12209 100644 --- a/crates/project/src/essential.rs +++ b/crates/project/src/essential.rs @@ -12,11 +12,11 @@ //! [`sync_project`] keeps the groups in step with the controls (and refreshes the values of //! controls that are not overridden), [`with_overrides`] builds the project an instance renders. +use effectcraft_time::Tick; use serde::{Deserialize, Serialize}; use crate::props::{GroupKind, Node, ParamUi, PropGroup, Property, Uid}; use crate::{ItemId, ItemKind, Keyframe, Layer, LayerId, LayerSource, Project, Value}; -use effectcraft_time::Tick; /// Match id of the Essential Properties group on precomp layers. pub const GROUP: &str = "essential"; From 7c5b0da99b0ea6c3a3202925d22061ea1bdea997 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 21 Oct 2026 21:37:31 +0530 Subject: [PATCH 004/324] Close, New and Open Project free the closed project's memory `Session::replace_project` (`crates/engine/src/lib.rs`), shared by Close, New, Open and the demo project: - forgets the decoded frames and decoders of the closed project's footage, as well as the new project's (the existing #1070 behaviour); - emits `Event::PurgeCaches` after the swap, so the viewers drop the RAM preview of the closed project. Its comp ids can also collide with the new project's. Cache budgets and LRU order are unchanged; only the release path changes. --- crates/engine/src/lib.rs | 10 +++-- crates/engine/src/tests_menu_cmds.rs | 58 ++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index cdfc7468e..4d8706bff 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1160,9 +1160,10 @@ impl Session { self.script_ui.project_epoch = self.script_ui.project_epoch.wrapping_add(1); p.fix_next_id(); upgrade_effects(&mut p); - // The media layer keys decoded frames by path: files of the new project may have changed - // since an earlier project decoded them (#1070). - for it in p.items.values() { + // Let go of what the closed project decoded (frames, decoders, models), and of what the + // new project's files decoded under an earlier project: the media layer keys them by + // path, and the files may have changed since (#1070). + for it in self.project.items.values().chain(p.items.values()) { if let effectcraft_project::ItemKind::Footage(f) = &it.kind { self.forget_decoded(f); } @@ -1174,6 +1175,9 @@ impl Session { self.path = path; self.bump(); self.mark_saved(); + // The viewers' RAM preview shows the closed project's frames, whose comp ids can collide + // with the new project's. + self.events.push(Event::PurgeCaches); let first = self.project.comps().next().map(|(id, _)| *id); if let Some(c) = first { self.open_comp(c); diff --git a/crates/engine/src/tests_menu_cmds.rs b/crates/engine/src/tests_menu_cmds.rs index 6da07dd40..83f3b609c 100644 --- a/crates/engine/src/tests_menu_cmds.rs +++ b/crates/engine/src/tests_menu_cmds.rs @@ -1767,3 +1767,61 @@ fn old_guides_load_as_pixel_guides_and_percent_round_trips() { // A zero-sized comp never divides by zero. assert!(g.px(0, 0).is_finite()); } + +#[test] +fn replacing_project_releases_old_footage() { + // A footage source that records the paths it is told to forget. + struct Recording(std::sync::Mutex>); + impl crate::render::FootageSource for Recording { + fn frame( + &self, + _: effectcraft_project::ItemId, + _: &effectcraft_project::Footage, + _: effectcraft_time::Tick, + ) -> Option> { + None + } + fn forget(&self, path: &str) { + self.0.lock().unwrap().push(path.to_string()); + } + } + let mut s = comp(); + let src = std::sync::Arc::new(Recording(Default::default())); + s.footage = src.clone(); + let recorded = || src.0.lock().unwrap().clone(); + let with_old = |s: &Session| { + let mut p = (*s.project).clone(); + p.add_item("old", Default::default(), None, ItemKind::Footage(effectcraft_project::Footage { path: "/old.mp4".into(), ..Default::default() })); + p + }; + let old = with_old(&s); + s.replace_project(old, None); + s.drain_events(); + src.0.lock().unwrap().clear(); + + // Close Project lets go of the closed project's footage and clears the RAM preview. + s.execute("file.closeProject", json!({})).unwrap(); + assert!(recorded().contains(&"/old.mp4".to_string()), "{:?}", recorded()); + assert!(s.drain_events().contains(&Event::PurgeCaches)); + + // Opening a project forgets the old project's files and the new project's. + let old = with_old(&s); + s.replace_project(old, None); + s.drain_events(); + src.0.lock().unwrap().clear(); + let mut new = effectcraft_project::Project::default(); + new.add_item("new", Default::default(), None, ItemKind::Footage(effectcraft_project::Footage { path: "/new.mp4".into(), ..Default::default() })); + s.replace_project(new, None); + let paths = recorded(); + assert!(paths.contains(&"/old.mp4".to_string()) && paths.contains(&"/new.mp4".to_string()), "{paths:?}"); + assert!(s.drain_events().contains(&Event::PurgeCaches)); + + // New Project does the same. + let old = with_old(&s); + s.replace_project(old, None); + s.drain_events(); + src.0.lock().unwrap().clear(); + s.execute("file.newProject", json!({})).unwrap(); + assert!(recorded().contains(&"/old.mp4".to_string()), "{:?}", recorded()); + assert!(s.drain_events().contains(&Event::PurgeCaches)); +} From 1dcb8273a45ac0bd9a4a3d05f78f53522e00d585 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 21 Oct 2026 21:47:06 +0530 Subject: [PATCH 005/324] Fast Previews: Adaptive Resolution applies while dragging in the Timeline `timeline::show` keeps a per-frame `dragging` flag. While the primary button is down, it sets the existing `property_interacting` for: - dragging the playhead or the timecode; - moving layer bars, or their in and out points; - dragging keys, and the key alt-scale. A click without movement doesn't set it. The existing clear at the start of each frame handles the release, so the first frame after it is sharp. With Fast Previews off (the default) or a fixed resolution, nothing changes. 9 lines of production code. --- crates/ui-egui/src/panels/timeline.rs | 9 +- crates/ui-egui/src/state.rs | 1 + .../ui-egui/tests/ui_timeline_interacting.rs | 115 ++++++++++++++++++ 3 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/ui_timeline_interacting.rs diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs index b34fbd9d3..1d9703ddb 100644 --- a/crates/ui-egui/src/panels/timeline.rs +++ b/crates/ui-egui/src/panels/timeline.rs @@ -1468,6 +1468,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { p.line_segment([pos2(graph_x0 - 1.0, top), pos2(graph_x0 - 1.0, rect.max.y)], Stroke::new(1.0, t.app_bg)); let mut actions: Vec<(String, serde_json::Value)> = Vec::new(); + let mut dragging = false; // A drag that moves the frame on screen (Fast Previews). if !ui.input(|i| i.pointer.primary_down()) { ctx.data_mut(|d| d.remove::(switch_drag_id())); } @@ -1495,6 +1496,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { app.auto.add("timeline.timecode", tc_rect, &tc); super::toggle_time_display(app, &tc_resp); if tc_resp.dragged() { + dragging = true; let d = tc_resp.drag_delta().x as f64; let f = fr.frame_at(time) + (d * 0.5).round() as i64; let _ = app.session.execute("time.set", json!({"frame": f.max(0)})); @@ -1730,6 +1732,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { if ((rresp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down())) || rresp.clicked()) && let Some(pt) = rresp.interact_pointer_pos() { + dragging |= rresp.dragged(); let mut x = pt.x; // Zoomed in, a scrub held past either end of the ruler scrolls the timeline that way // (faster the further), with the CTI at the edge (After Effects). @@ -2360,6 +2363,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { continue; } if resp.dragged() { + dragging = true; let acc_id = egui::Id::new(("bar-acc", layer.id.0, kind)); let mut acc: f32 = ctx.data(|d| d.get_temp(acc_id).unwrap_or(0.0)); acc += resp.drag_delta().x; @@ -3149,6 +3153,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { let (down, ptr) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.latest_pos())); match ptr.filter(|_| down) { Some(ptr) => { + dragging = true; let frames = (((ptr.x - q.origin_x) as f64 / pps) / fd).round() as i64; if frames != q.applied { q.applied = frames; @@ -3171,6 +3176,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { let (down, ptr, shift) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.latest_pos(), i.modifiers.shift)); match ptr.filter(|_| down) { Some(ptr) => { + dragging = true; let mut target = kd.anchor + (ptr.x - kd.origin_x) as f64 / pps; if shift { // The current time and whatever it snaps to (keys, layer ends, markers), but @@ -3474,7 +3480,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { } } } - if ui.input(|i| i.pointer.primary_down()) && actions.iter().any(|(id, _)| id == "prop.set") { + dragging |= super::graph_tools::alt_scale_active(&ctx); + if ui.input(|i| i.pointer.primary_down()) && (dragging || actions.iter().any(|(id, _)| id == "prop.set")) { app.ui.viewer.property_interacting = true; ctx.request_repaint(); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 1e2f57204..206c70cf3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -264,6 +264,7 @@ pub struct ViewerState { /// The pointer is dragging in the viewer this frame (Adaptive Resolution). #[serde(skip)] pub interacting: bool, + /// A property scrub (Effect Controls, Timeline) or a Timeline drag of the playhead, keys or layer bars is in progress (Adaptive Resolution); cleared once the primary button is up. #[serde(skip)] pub property_interacting: bool, /// Extended Viewer: the comp-space region the viewer renders this frame (comp frame plus diff --git a/crates/ui-egui/tests/ui_timeline_interacting.rs b/crates/ui-egui/tests/ui_timeline_interacting.rs new file mode 100644 index 000000000..29f86b6ff --- /dev/null +++ b/crates/ui-egui/tests/ui_timeline_interacting.rs @@ -0,0 +1,115 @@ +use effectcraft_engine::Session; +use effectcraft_engine::project::LayerId; +use effectcraft_ui_egui::EffectcraftApp; +use egui::{Event, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +fn harness() -> (Harness<'static, EffectcraftApp>, LayerId, u64) { + let mut session = Session::default(); + session.execute("comp.new", json!({"name": "Keys", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap(); + session.execute("layer.newSolid", json!({"name": "Box", "color": "#e04020", "width": 80, "height": 80})).unwrap(); + let id = session.active_comp().unwrap().layers[0].id; + for (time, value) in [(0.0, 0.0), (1.0, 100.0)] { + session.execute("prop.addKey", json!({"layer": id.0, "path": "transform/opacity", "time": time, "value": value})).unwrap(); + } + let uid = session.active_comp().unwrap().layer(id).unwrap().props.prop("transform/opacity").unwrap().uid; + session.execute("layer.select", json!({"layers": [id.0]})).unwrap(); + session.execute("view.fastPreviewMode", json!({"mode": "adaptive"})).unwrap(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(session)); + harness.run_steps(3); + let context = harness.ctx.clone(); + effectcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "timeline.reveal.opacity", json!({})).unwrap(); + harness.run_steps(4); + (harness, id, uid) +} + +fn rect(harness: &Harness<'_, EffectcraftApp>, id: &str) -> egui::Rect { + let entry = harness.state().auto.find(id).expect("timeline element"); + egui::Rect::from_min_size(pos2(entry.rect[0], entry.rect[1]), vec2(entry.rect[2], entry.rect[3])) +} + +fn keys(harness: &Harness<'_, EffectcraftApp>, uid: u64) -> Vec { + let mut positions: Vec = harness + .state() + .auto + .query(&format!("timeline.key.{uid}.")) + .iter() + .map(|entry| pos2(entry.rect[0] + entry.rect[2] / 2.0, entry.rect[1] + entry.rect[3] / 2.0)) + .collect(); + positions.sort_by(|left, right| left.x.total_cmp(&right.x)); + positions +} + +fn hold(harness: &mut Harness<'_, EffectcraftApp>, from: Pos2, to: Pos2) { + harness.input_mut().events.push(Event::PointerMoved(from)); + harness.step(); + harness.input_mut().events.push(Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + harness.step(); + for step in 1..=10 { + harness.input_mut().events.push(Event::PointerMoved(from + (to - from) * (step as f32 / 10.0))); + harness.step(); + } +} + +fn release(harness: &mut Harness<'_, EffectcraftApp>, at: Pos2) { + harness.input_mut().events.push(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + harness.run_steps(2); +} + +fn assert_adaptive_during_drag(harness: &Harness<'_, EffectcraftApp>) { + assert!(harness.state().ui.viewer.property_interacting); + assert!(harness.state().viewer_scale(1.0, 1.0) < 1.0); +} + +fn assert_full_resolution_after_release(harness: &Harness<'_, EffectcraftApp>) { + assert!(!harness.state().ui.viewer.property_interacting); + assert_eq!(harness.state().viewer_scale(1.0, 1.0), 1.0); +} + +#[test] +fn playhead_drag_uses_adaptive_resolution() { + let (mut harness, _, _) = harness(); + let ruler = rect(&harness, "timeline.ruler"); + let from = pos2(ruler.min.x + 40.0, ruler.max.y - 3.0); + let to = from + vec2(200.0, 0.0); + hold(&mut harness, from, to); + assert_adaptive_during_drag(&harness); + release(&mut harness, to); + assert_full_resolution_after_release(&harness); +} + +#[test] +fn layer_bar_drag_uses_adaptive_resolution() { + let (mut harness, layer, _) = harness(); + let from = rect(&harness, &format!("timeline.layer.{}.bar", layer.0)).center(); + let to = from + vec2(60.0, 0.0); + hold(&mut harness, from, to); + assert_adaptive_during_drag(&harness); + release(&mut harness, to); + assert_full_resolution_after_release(&harness); +} + +#[test] +fn key_drag_uses_adaptive_resolution() { + let (mut harness, _, uid) = harness(); + let from = keys(&harness, uid)[0]; + let to = from + vec2(60.0, 0.0); + hold(&mut harness, from, to); + assert_adaptive_during_drag(&harness); + release(&mut harness, to); + assert_full_resolution_after_release(&harness); +} + +#[test] +fn timeline_click_keeps_full_resolution() { + let (mut harness, _, _) = harness(); + let point = rect(&harness, "timeline.ruler").center(); + harness.input_mut().events.push(Event::PointerMoved(point)); + harness.step(); + harness.input_mut().events.push(Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + harness.step(); + assert!(!harness.state().ui.viewer.property_interacting); + assert_eq!(harness.state().viewer_scale(1.0, 1.0), 1.0); + release(&mut harness, point); +} From a8ed8ca7749643887394363789b269ea47f78a07 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 31 Oct 2026 09:45:18 +0000 Subject: [PATCH 006/324] fix(effects): parse_cube rejects a hostile LUT_3D_SIZE before cubing it --- crates/effects/src/utility.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index e41b42e99..17f0a243b 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -202,9 +202,12 @@ pub fn parse_cube(text: &str) -> Option { _ => rows.push(three(&mut it)?), } } + if lut.n3 > 256 { + return None; + } let need1 = lut.n1; let need3 = lut.n3 * lut.n3 * lut.n3; - if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || rows.len() != need1 + need3 || lut.n3 > 256 { + if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) { return None; } lut.d1 = rows[..need1].to_vec(); @@ -464,6 +467,10 @@ mod tests { fn bad_cube_is_passthrough() { assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n1 1 1\n").is_none()); assert!(parse_cube("LUT_3D_SIZE 2\n0 0 zz\n").is_none()); + // A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`. + assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none()); + assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none()); + assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n0 0 0\n", usize::MAX)).is_none()); let img = test_img(); let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone()); assert_eq!(out.img, img); From 25cf11493aec2e3ba7811e5a7b5c63e2d99a659e Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:39:48 +0100 Subject: [PATCH 007/324] Keep Essential Graphics instance keys out of nested comps that preserve their frame rate (#1682) --- crates/engine/src/tests/essential_more.rs | 10 ++++++++++ crates/render/src/fx_host.rs | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/essential_more.rs b/crates/engine/src/tests/essential_more.rs index a417d39ff..b3de8359c 100644 --- a/crates/engine/src/tests/essential_more.rs +++ b/crates/engine/src/tests/essential_more.rs @@ -252,6 +252,16 @@ fn one_control_with_targets_of_different_timing_stays_in_step() { } } +#[test] +fn instance_keys_stay_out_of_a_nested_comp_that_preserves_its_frame_rate() { + let (mut s, scene, inner, [a, _], inst) = keyed_instance([(0.0, 100.0), (0.0, 100.0)]); + std::sync::Arc::make_mut(&mut s.project).comp_mut(inner).unwrap().preserve_frame_rate = true; + // The nested time is floored to the nested comp's frames, so only the instance's value goes in. + let (v, pr) = rendered(&s, scene, inner, inst, a, 0.25); + assert!((v - 25.0).abs() < 1e-6, "rendered {v}"); + assert!(pr.keys.is_empty()); +} + /// #1747: through a collapsed precomp, a Text override and a Font override of the same Source /// Text both apply: the Font merges into the overridden text, as `essential::with_overrides` /// does on the flattened path, instead of one entry replacing the other. diff --git a/crates/render/src/fx_host.rs b/crates/render/src/fx_host.rs index 655c01980..c5983ceca 100644 --- a/crates/render/src/fx_host.rs +++ b/crates/render/src/fx_host.rs @@ -184,7 +184,7 @@ fn effect_param<'a>(layer: &'a Layer, effect_index: usize, id: &str) -> Option<& /// Whether an instance's keys are in the nested comp's time, so they can go into the comp as they /// are: not with Time Remap, Responsive Design - Time (a stretched precomp with protected -/// regions). +/// regions) or a nested comp that preserves its frame rate (its time is floored to its own frames). fn keys_in_nested_time(ctx: &EvalCtx, layer: &Layer) -> bool { if layer.props.get("timeRemap").is_some() { return false; @@ -192,7 +192,7 @@ fn keys_in_nested_time(ctx: &EvalCtx, layer: &Layer) -> bool { let LayerSource::Comp { item } = layer.source else { return true }; let Some(nc) = ctx.project.comp(item) else { return true }; let responsive = (layer.stretch - 100.0).abs() > 1e-9 && !super::eval::protected_regions(nc).is_empty(); - !responsive + !responsive && !nc.preserve_frame_rate } /// The Essential Properties overrides of a precomp layer, evaluated at the context time. From 6c3b49d88ba946dd4fb7d60712cbae724549fd74 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:54:09 +0100 Subject: [PATCH 008/324] Keep Essential Graphics instance keys out of frame-blended layers and collapsed parent overrides (#1682) --- crates/engine/src/tests/essential_more.rs | 47 +++++++++++++++++++++++ crates/render/src/fx_host.rs | 15 +++++--- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests/essential_more.rs b/crates/engine/src/tests/essential_more.rs index b3de8359c..c87d36eec 100644 --- a/crates/engine/src/tests/essential_more.rs +++ b/crates/engine/src/tests/essential_more.rs @@ -291,3 +291,50 @@ fn collapsed_instance_merges_text_and_font_overrides() { o => panic!("{o:?}"), } } + +#[test] +fn instance_keys_stay_out_of_a_layer_that_blends_frames() { + let (mut s, scene, inner, [a, _], inst) = keyed_instance([(0.0, 100.0), (0.0, 100.0)]); + { + let comp = std::sync::Arc::make_mut(&mut s.project).comp_mut(scene).unwrap(); + comp.enable_frame_blending = true; + comp.layer_mut(effectcraft_project::LayerId(inst)).unwrap().switches.frame_blend = effectcraft_project::FrameBlend::FrameMix; + } + // Frame Mix renders the nested comp at two other times, so only the instance's current value goes in. + let (v, pr) = rendered(&s, scene, inner, inst, a, 0.25); + assert!((v - 25.0).abs() < 1e-6, "rendered {v}"); + assert!(pr.keys.is_empty()); +} + +/// An override from a collapsed parent reaches the nested instance as a value only: the keys the +/// nested instance property carries itself must not be copied onto its own target. +#[test] +fn collapsed_parent_override_replaces_the_nested_instance_keys() { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Inner", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let a = s.execute("layer.newSolid", json!({"name": "A", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("essential.addProperty", json!({"layer": a, "path": "transform/opacity"})).unwrap(); + s.execute("comp.new", json!({"name": "Mid", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let mid = s.active_comp_id().unwrap(); + let inner = s.project.find_by_name("Inner").unwrap().id; + let nested = s.execute("layer.addItem", json!({"item": inner.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap(); + let path = s.execute("essential.instance", json!({"layer": nested})).unwrap()["controls"][0]["path"].as_str().unwrap().to_string(); + s.execute("prop.addKey", json!({"layer": nested, "path": path, "time": 0.0, "value": 0.0})).unwrap(); + s.execute("prop.addKey", json!({"layer": nested, "path": path, "time": 1.0, "value": 100.0})).unwrap(); + let ctl = s.execute("essential.addProperty", json!({"layer": nested, "path": path})).unwrap()["controls"][0].as_u64().unwrap(); + s.execute("comp.new", json!({"name": "Top", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap(); + let top = s.active_comp_id().unwrap(); + let inst = s.execute("layer.addItem", json!({"item": mid.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layers": [inst], "switch": "collapse", "value": true})).unwrap(); + s.execute("essential.set", json!({"layer": inst, "control": ctl, "value": 80.0})).unwrap(); + let r = effectcraft_render::Renderer::new(&s.project, &*s.footage, crate::render::RenderOpts::default()); + let ctx = effectcraft_render::EvalCtx::new(&s.project, top, s.project.comp(top).unwrap(), Tick::from_seconds_f64(0.25)); + let layer = ctx.comp.layer(effectcraft_project::LayerId(inst)).unwrap(); + let collapsed = r.collapsed(&ctx, layer).expect("the instance collapses"); + let (_, nctx) = r.collapse_into(&ctx, layer, &collapsed, 1.0).expect("a nested context"); + let nl = nctx.comp.layer(effectcraft_project::LayerId(nested)).unwrap(); + let over = effectcraft_render::essential_overrides(&nctx, nl); + assert_eq!(over.len(), 1); + assert!((over[0].value.as_f64() - 80.0).abs() < 1e-6, "value {:?}", over[0].value); + assert!(over[0].keys.is_empty(), "the nested instance's own keys are stale"); +} diff --git a/crates/render/src/fx_host.rs b/crates/render/src/fx_host.rs index c5983ceca..f15f91c93 100644 --- a/crates/render/src/fx_host.rs +++ b/crates/render/src/fx_host.rs @@ -1,4 +1,5 @@ -use super::{Arc, Buf, EffectHost, EvalCtx, ItemKind, Layer, LayerPixels, LayerSource, Params, Renderer, Tick, three_d}; +use super::frames::frame_blend_mode; +use super::{Arc, Buf, EffectHost, EvalCtx, FrameBlend, ItemKind, Layer, LayerPixels, LayerSource, Params, Renderer, Tick, three_d}; /// Layer parameters and audio for effects (see [`effectcraft_effects::EffectHost`]). What it /// hands out is in effect space (see [`effect_bounds`]): the other layer's for its pixels, the @@ -184,9 +185,11 @@ fn effect_param<'a>(layer: &'a Layer, effect_index: usize, id: &str) -> Option<& /// Whether an instance's keys are in the nested comp's time, so they can go into the comp as they /// are: not with Time Remap, Responsive Design - Time (a stretched precomp with protected -/// regions) or a nested comp that preserves its frame rate (its time is floored to its own frames). +/// regions), a nested comp that preserves its frame rate (its time is floored to its own frames) +/// or a layer with Frame Blending (it renders the nested comp at two other times and mixes them, +/// so keys would pull the next frame's value in early). fn keys_in_nested_time(ctx: &EvalCtx, layer: &Layer) -> bool { - if layer.props.get("timeRemap").is_some() { + if layer.props.get("timeRemap").is_some() || frame_blend_mode(ctx, layer) != FrameBlend::Off { return false; } let LayerSource::Comp { item } = layer.source else { return true }; @@ -206,8 +209,10 @@ pub fn essential_overrides(ctx: &EvalCtx, layer: &Layer) -> Vec Date: Thu, 5 Nov 2026 20:38:37 -0800 Subject: [PATCH 009/324] Plug-in Library: a file URL cannot name a network path A local catalog's file:// URLs were decoded into a path without checking how the path starts. A URL such as file:////server/share/x.wasm, or one whose path holds a backslash or a percent-encoded / or \, could become a network path on Windows, so reading the catalog or a release named in it contacted that host. file_url_path now refuses a decoded path that starts with two separators or holds a backslash, and a percent-encoded / or \, with an error that names the reason. Local paths and drive-letter paths are read as before. The library.refresh params text, docs/plugins.md and docs/publishing-plugins.md say so. --- crates/engine/src/system/library.rs | 80 ++++++++++++++++++++++++----- docs/plugins.md | 3 +- docs/publishing-plugins.md | 4 +- 3 files changed, 72 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/system/library.rs b/crates/engine/src/system/library.rs index 750ed600a..23063957f 100644 --- a/crates/engine/src/system/library.rs +++ b/crates/engine/src/system/library.rs @@ -324,27 +324,44 @@ enum Source { File(PathBuf), } -/// `file:///C:/x` or `file:///home/x` as a path (percent-decoded; no remote hosts). -fn file_url_path(url: &str) -> Option { - let rest = url.strip_prefix("file://")?; +/// `file:///C:/x` or `file:///home/x` as a path (percent-decoded; no remote hosts). A path that +/// starts with two separators or holds a `\` (raw or percent-encoded), or a percent-encoded `/`, +/// is refused: on Windows such a path can name a network share, and reading it contacts that host. +fn file_url_path(url: &str) -> std::result::Result { + let bad = |why: &str| format!("bad file URL `{url}`: {why}"); + let rest = url.strip_prefix("file://").ok_or_else(|| bad("it doesn't start with file://"))?; let rest = rest.strip_prefix("localhost").unwrap_or(rest); if !rest.starts_with('/') { - return None; + return Err(bad("only local files can be read (file:///path)")); } let b = rest.as_bytes(); // `/C:/…` on Windows. - let rest = if b.len() > 2 && b.get(2) == Some(&b':') { rest.get(1..)? } else { rest }; + let rest = + if b.get(1).is_some_and(u8::is_ascii_alphabetic) && b.get(2) == Some(&b':') { rest.get(1..).ok_or_else(|| bad("bad drive letter"))? } else { rest }; let mut out = Vec::with_capacity(rest.len()); let mut bytes = rest.bytes(); while let Some(c) = bytes.next() { if c == b'%' { - let hex = [bytes.next()?, bytes.next()?]; - out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?); + let hex = [bytes.next(), bytes.next()]; + let [Some(hi), Some(lo)] = hex else { return Err(bad("a % isn't followed by two hex digits")) }; + let byte = + std::str::from_utf8(&[hi, lo]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()).ok_or_else(|| bad("a % isn't followed by two hex digits"))?; + if matches!(byte, b'/' | b'\\') { + return Err(bad("a percent-encoded / or \\ isn't allowed")); + } + out.push(byte); } else { out.push(c); } } - String::from_utf8(out).ok().map(PathBuf::from) + let path = String::from_utf8(out).map_err(|_| bad("the path isn't UTF-8"))?; + if path.contains('\\') { + return Err(bad("use / between folders, not \\")); + } + if path.starts_with("//") { + return Err(bad("network paths can't be read, only local files")); + } + Ok(PathBuf::from(path)) } /// Check `url` against the rules: `https://` on GitHub's hosts; `file://` when the catalog @@ -359,7 +376,7 @@ fn source(url: &str, catalog: Option<&str>) -> std::result::Result Vec { "Refresh Plug-in Catalog", [], None, - "{catalog?: https:// or file:// URL of an index.json (default: the community catalog), wait?}", + "{catalog?: https:// or file:// URL of an index.json (default: the community catalog; file:// takes a local path, not a network path such as //server/share), wait?}", always, refresh ), @@ -1177,10 +1194,47 @@ mod tests { assert_eq!(source("file:///C:/p/x.wasm", None), Ok(Source::File(PathBuf::from("C:/p/x.wasm")))); assert!(source("file://", None).is_err()); // Percent-decoded; no remote hosts. - assert_eq!(file_url_path("file:///C:/My%20Plug-ins/Jos%C3%A9%23.wasm"), Some(PathBuf::from("C:/My Plug-ins/José#.wasm"))); - assert_eq!(file_url_path("file://localhost/home/x.wasm"), Some(PathBuf::from("/home/x.wasm"))); + assert_eq!(file_url_path("file:///C:/My%20Plug-ins/Jos%C3%A9%23.wasm"), Ok(PathBuf::from("C:/My Plug-ins/José#.wasm"))); + assert_eq!(file_url_path("file://localhost/home/x.wasm"), Ok(PathBuf::from("/home/x.wasm"))); for no in ["file://server/share/x.wasm", "file:///bad%2", "file:///bad%zz"] { - assert_eq!(file_url_path(no), None, "{no}"); + assert!(file_url_path(no).is_err(), "{no}"); + } + } + + #[test] + fn file_urls_cannot_name_a_network_path() { + for ok in [ + ("file:///C:/p/x.wasm", "C:/p/x.wasm"), + ("file:///c:/p/x.wasm", "c:/p/x.wasm"), + ("file:///home/me/x.wasm", "/home/me/x.wasm"), + ("file://localhost/C:/p/x.wasm", "C:/p/x.wasm"), + ("file:///home/me/a%20b/x.wasm", "/home/me/a b/x.wasm"), + ("file:///C:/p//x.wasm", "C:/p//x.wasm"), + ] { + assert_eq!(file_url_path(ok.0), Ok(PathBuf::from(ok.1)), "{}", ok.0); + } + for no in [ + // Two separators at the start: `//server/share/…`. + "file:////server/share/x.wasm", + "file://localhost//server/share/x.wasm", + "file://///server/share/x.wasm", + "file:////:x.wasm", + // Backslashes, raw or percent-encoded. + "file:///\\\\server\\share\\x.wasm", + "file:///\\server/share/x.wasm", + "file:///C:\\p\\x.wasm", + "file:///%5C%5Cserver/share/x.wasm", + "file:///%5c%5cserver/share/x.wasm", + "file:///C:/p%5Cx.wasm", + // Percent-encoded slashes. + "file:///%2F%2Fserver/share/x.wasm", + "file:///%2fserver/share/x.wasm", + "file:///C:/p%2Fx.wasm", + ] { + let e = file_url_path(no).expect_err(no); + assert!(e.starts_with("bad file URL"), "{no}: {e}"); + assert!(source(no, None).is_err(), "{no}"); + assert!(source(no, Some("file:///tmp/index.json")).is_err(), "{no}"); } } diff --git a/docs/plugins.md b/docs/plugins.md index 3fd8cf944..d7df3d8b1 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -369,7 +369,8 @@ package can't read files, open the network or crash the app. [`storytold/effectcraft-plugins`](https://github.com/storytold/effectcraft-plugins) repository; packages are added by pull request and reviewed there. The app has no field for another catalog; `library.refresh {catalog}` (for plug-in authors testing an entry) takes an `index.json` - on GitHub or a local file, and the page then says it shows a test catalog until Refresh. + on GitHub or a local file, and the page then says it shows a test catalog until Refresh. A file + URL that names a network path (`file:////server/share/…`) is refused. * **Nothing is downloaded until you ask.** Fetch Catalog (`library.refresh`) reads the catalog; Install (`library.install`) downloads the package's `.wasm`, checks its SHA-256 (and its size, when the catalog gives one) against the catalog and loads it. Downloads use the system's `curl`, diff --git a/docs/publishing-plugins.md b/docs/publishing-plugins.md index bd76c3ab5..0083293b6 100644 --- a/docs/publishing-plugins.md +++ b/docs/publishing-plugins.md @@ -226,7 +226,9 @@ Make a folder with an `index.json` that holds only your package: ``` File URLs are absolute: `file:///home/me/glow-rings/index.json` on Linux and macOS, -`file:///C:/Users/me/glow-rings/index.json` on Windows. Write a space as `%20`. +`file:///C:/Users/me/glow-rings/index.json` on Windows. Write a space as `%20`. Separate folders +with `/`: a file URL that holds a `\` or a percent-encoded `/` or `\`, or names a network path +(`file:////server/share/…`), is refused. Use a separate settings folder, so the test doesn't touch your real installation: From 75fed052e3dcb5cd876729863bc5e292aaca022c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 5 Nov 2026 21:51:04 -0800 Subject: [PATCH 010/324] Plug-in Library: a package downloads only release assets of its repository A catalog release's url was checked only for its host: any https:// URL on GitHub's hosts was downloaded, from any repository and any path, including a raw file on a branch or a path with dot segments that curl resolves to another repository. library.install, library.update and library.preview now refuse a url that isn't https://github.com///releases/download//. When the package's repo is a https://github.com// URL, the asset must be in that repository (owner and name compared without case). Dot segments, also percent-encoded, empty segments, backslashes, queries and fragments are refused. file:// releases from a local catalog are read as before, and the SHA-256 and size checks are unchanged. A catalog other than the community one is still read only when library.refresh names it (https:// on GitHub's hosts, or a local file://). docs/plugins.md, docs/publishing-plugins.md and the library.install params text describe the rules. --- crates/engine/src/system/library.rs | 98 ++++++++++++++++++++++++++++- crates/host/tests/it/library.rs | 32 ++++++++++ docs/plugins.md | 6 +- docs/publishing-plugins.md | 2 +- 4 files changed, 134 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/system/library.rs b/crates/engine/src/system/library.rs index 750ed600a..0e55c8acb 100644 --- a/crates/engine/src/system/library.rs +++ b/crates/engine/src/system/library.rs @@ -255,6 +255,58 @@ fn release_problem(r: &Release) -> Option { None } +/// An owner or repository name on GitHub: letters, digits, `.`, `-`, `_`, and not `.` or `..`. +fn valid_repo_part(p: &str) -> bool { + !p.is_empty() && p != "." && p != ".." && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) +} + +/// The rest of `s` after `prefix`, ignoring ASCII case. +fn strip_prefix_ignore_case<'a>(s: &'a str, prefix: &str) -> Option<&'a str> { + let head = s.get(..prefix.len())?; + head.eq_ignore_ascii_case(prefix).then(|| s.get(prefix.len()..)).flatten() +} + +/// `(owner, name)` in lower case of a `https://github.com//` repository URL (an +/// optional trailing `/` or `.git`); `None` for anything else. +fn github_repo(repo: &str) -> Option<(String, String)> { + let rest = strip_prefix_ignore_case(repo.trim(), "https://github.com/")?; + let rest = rest.strip_suffix('/').unwrap_or(rest); + let rest = rest.strip_suffix(".git").unwrap_or(rest); + let mut parts = rest.split('/'); + let (owner, name) = (parts.next()?, parts.next()?); + (parts.next().is_none() && valid_repo_part(owner) && valid_repo_part(name)).then(|| (owner.to_ascii_lowercase(), name.to_ascii_lowercase())) +} + +/// Why an `https://` release URL can't be used, if it can't: it must be a release asset, +/// `https://github.com///releases/download//`, and when the package's +/// `repo` is a GitHub repository URL, `/` must be that repository. +fn release_url_problem(repo: &str, url: &str) -> Option { + let not_asset = || Some(format!("`{url}` isn't a release asset (https://github.com///releases/download//)")); + let Some(rest) = strip_prefix_ignore_case(url, "https://github.com/") else { return not_asset() }; + if rest.contains(['?', '#', '\\']) { + return not_asset(); + } + let parts: Vec<&str> = rest.split('/').collect(); + // `.` and `..` (also percent-encoded) would move the download to another path. + let dot_segment = |p: &&str| { + let p = p.to_ascii_lowercase().replace("%2e", "."); + p == "." || p == ".." + }; + if parts.len() < 6 || parts.iter().any(|p| p.is_empty() || dot_segment(p)) { + return not_asset(); + } + let (Some(owner), Some(name), Some(releases), Some(download)) = (parts.first(), parts.get(1), parts.get(2), parts.get(3)) else { return not_asset() }; + if !valid_repo_part(owner) || !valid_repo_part(name) || *releases != "releases" || *download != "download" { + return not_asset(); + } + match github_repo(repo) { + Some((o, n)) if o != owner.to_ascii_lowercase() || n != name.to_ascii_lowercase() => { + Some(format!("`{url}` isn't a release asset of the package's repository {}", repo.trim())) + } + _ => None, + } +} + /// Read a catalog: packages and releases that are malformed are left out (and reported), so one /// bad entry doesn't hide the others. pub fn parse_catalog(bytes: &[u8]) -> std::result::Result<(Catalog, Vec), String> { @@ -799,7 +851,11 @@ fn pick(s: &Session, c: &str, p: &Value) -> Result<(String, Package, Release)> { ), )); } - source(&rel.url, Some(&url)).map_err(|e| bad(c, e))?; + if let Source::Https(u) = source(&rel.url, Some(&url)).map_err(|e| bad(c, e))? + && let Some(why) = release_url_problem(&pkg.repo, &u) + { + return Err(bad(c, why)); + } Ok((url, pkg, rel)) } @@ -1049,7 +1105,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{id, version?, wait?} — downloads the release, checks its SHA-256 against the catalog, loads it", + "{id, version?, wait?} — downloads the release (a GitHub release asset, in the package's repo when it names one), checks its SHA-256 against the catalog, loads it", always, install ), @@ -1132,6 +1188,44 @@ mod tests { assert!(latest_compatible(&Package::default()).is_none()); } + #[test] + fn release_urls_are_assets_of_the_declared_repository() { + let asset = "https://github.com/Me/Glow/releases/download/v1.0.0/glow.wasm"; + for repo in ["https://github.com/me/glow", "https://github.com/Me/Glow/", "https://GitHub.com/me/glow.git", "", "https://gitlab.com/me/glow"] { + assert_eq!(release_url_problem(repo, asset), None, "{repo}"); + } + assert_eq!(release_url_problem("", "https://github.com/a/b/releases/download/tags/v1/x.wasm"), None, "a tag with a slash"); + assert!( + release_url_problem("https://github.com/me/glow", "https://github.com/me/other/releases/download/v1/x.wasm") + .unwrap() + .contains("package's repository") + ); + assert!(release_url_problem("https://github.com/me/glow", "https://github.com/you/glow/releases/download/v1/x.wasm").is_some()); + for no in [ + "https://raw.githubusercontent.com/me/glow/main/x.wasm", + "https://objects.githubusercontent.com/x.wasm", + "https://github.com/me/glow/blob/main/x.wasm", + "https://github.com/me/glow/releases/download/v1", + "https://github.com/me/glow/releases/download//x.wasm", + "https://github.com/me/glow/releases/download/v1/x.wasm?x=1", + "https://github.com/me/glow/releases/download/v1/x.wasm#x", + "https://github.com/me/glow/releases/download/../../../you/evil/releases/download/v1/x.wasm", + "https://github.com/me/glow/releases/download/%2e%2e/%2E./x/y/x.wasm", + "https://github.com/me/glow/releases/download/./v1/x.wasm", + "https://github.com/me/glow/releases/download/v1\\x.wasm", + "https://github.com/m e/glow/releases/download/v1/x.wasm", + "https://github.com/../glow/releases/download/v1/x.wasm", + "https://github.com.evil.com/me/glow/releases/download/v1/x.wasm", + ] { + assert!(release_url_problem("https://github.com/me/glow", no).is_some(), "{no}"); + assert!(release_url_problem("", no).is_some(), "{no}"); + } + assert_eq!(github_repo("https://github.com/Me/Glow.git"), Some(("me".into(), "glow".into()))); + for no in ["https://github.com/me", "https://github.com/me/glow/tree/main", "http://github.com/me/glow", "me/glow"] { + assert_eq!(github_repo(no), None, "{no}"); + } + } + #[test] fn catalogs_leave_out_bad_entries() { let good = "a".repeat(64); diff --git a/crates/host/tests/it/library.rs b/crates/host/tests/it/library.rs index 4cd94ecdd..f5bd613cc 100644 --- a/crates/host/tests/it/library.rs +++ b/crates/host/tests/it/library.rs @@ -156,6 +156,38 @@ fn a_wrong_checksum_or_a_bad_module_installs_nothing() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn downloads_are_release_assets_of_the_package_repository() { + let dir = tmp("assets"); + let sum = "0".repeat(64); + let pkg = + |id: &str, repo: &str, url: &str| json!({"id": id, "name": id, "repo": repo, "versions": [{"version": "1", "api": 1, "url": url, "sha256": sum}]}); + let catalog = write_catalog( + &dir, + json!([ + pkg("org.test.other", "https://github.com/me/glow", "https://github.com/someone/else/releases/download/v1/glow.wasm"), + pkg("org.test.raw", "https://github.com/me/glow", "https://raw.githubusercontent.com/me/glow/main/glow.wasm"), + pkg("org.test.page", "", "https://github.com/me/glow/blob/main/glow.wasm"), + pkg("org.test.dots", "https://github.com/me/glow", "https://github.com/me/glow/releases/download/%2e%2e/%2E%2E/x/y/glow.wasm"), + ]), + ); + let mut s = session(&dir); + s.execute("library.refresh", json!({"catalog": catalog, "wait": true})).unwrap(); + for (id, why) in [ + ("org.test.other", "isn't a release asset of the package's repository https://github.com/me/glow"), + ("org.test.raw", "isn't a release asset"), + ("org.test.page", "isn't a release asset"), + ("org.test.dots", "isn't a release asset"), + ] { + for c in ["library.install", "library.preview"] { + let e = s.execute(c, json!({"id": id, "wait": true})).unwrap_err().to_string(); + assert!(e.contains(why), "{c} {id}: {e}"); + } + } + assert!(!dir.join("Plug-ins").join("Library").join("installed.json").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn installed_packages_load_at_start_and_changed_files_are_refused() { let dir = tmp("startup"); diff --git a/docs/plugins.md b/docs/plugins.md index 3fd8cf944..99b91874f 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -374,7 +374,11 @@ package can't read files, open the network or crash the app. Install (`library.install`) downloads the package's `.wasm`, checks its SHA-256 (and its size, when the catalog gives one) against the catalog and loads it. Downloads use the system's `curl`, `https://` only and starting on GitHub's hosts (redirects stay on `https://`; the SHA-256 check - is what guarantees the file). + is what guarantees the file). A package's `url` must be a release asset + (`https://github.com///releases/download/…`), in the package's `repo` when that is + a GitHub repository URL. A catalog other than the community one is read only when + `library.refresh {catalog}` names it: an `index.json` on GitHub's hosts over `https://`, or a + local `file://` path. * **Where it goes.** `/Library///.wasm` (the `Plug-ins` folder next to the settings), listed in `Library/installed.json`. Installed packages load at start-up, each checked against the SHA-256 it was installed with. The catalog last fetched is kept as diff --git a/docs/publishing-plugins.md b/docs/publishing-plugins.md index bd76c3ab5..c94f9e2a8 100644 --- a/docs/publishing-plugins.md +++ b/docs/publishing-plugins.md @@ -193,7 +193,7 @@ Release fields (one per entry in `versions`): | `version` | yes | Dotted numbers only, at most 32 characters: `1.0.0`, `1.2`. No `v` and no suffixes such as `-beta`. | | `api` | yes | The plug-in API the module implements: `1`. | | `minApp` | no | The oldest EffectCraft version the release needs (`0.17.0`). Leave it out if any version with this API works. | -| `url` | yes | The release asset's `https://` URL on GitHub. | +| `url` | yes | The release asset's `https://` URL on GitHub: `https://github.com///releases/download//`. When `repo` is a `https://github.com//` URL, the asset must be in that repository. Install and Preview refuse any other `https://` URL. | | `sha256` | yes | The file's SHA-256, 64 hex digits. | | `size` | no, but reviewed | The file's size in bytes. When it is given, a download of another size is refused. | | `effects` | yes | The effect ids the module registers (its manifest's `id`). EffectCraft uses them to find the package that provides an effect a project needs. | From bad3e7c2320d5f8aa8608d3dc725ed301b3ed366 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 31 Oct 2026 09:45:18 +0000 Subject: [PATCH 011/324] fix(effects): parse_cube rejects a hostile LUT_3D_SIZE before cubing it Co-Authored-By: Claude Sonnet 5.5 --- crates/effects/src/utility.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index e87c6d3ff..b38ded8db 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -215,9 +215,12 @@ pub fn parse_cube(text: &str) -> Option { _ => rows.push(three(&mut it)?), } } + if lut.n3 > 256 { + return None; + } let need1 = lut.n1; let need3 = lut.n3 * lut.n3 * lut.n3; - if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || rows.len() != need1 + need3 || lut.n3 > 256 { + if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) { return None; } lut.d1 = rows[..need1].to_vec(); @@ -477,6 +480,10 @@ mod tests { fn bad_cube_is_passthrough() { assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n1 1 1\n").is_none()); assert!(parse_cube("LUT_3D_SIZE 2\n0 0 zz\n").is_none()); + // A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`. + assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none()); + assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none()); + assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n0 0 0\n", usize::MAX)).is_none()); let img = test_img(); let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone()); assert_eq!(out.img, img); From 5dfcadd09bbca14eb53ec52694995eac4199f1be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 5 Nov 2026 23:24:20 -0800 Subject: [PATCH 012/324] Plug-in Library: a package with an unreadable repo URL downloads nothing When a package names a `repo` that isn't a GitHub repository URL (`https://github.com//`, a trailing `/` or `.git` allowed, or a folder in one, `.../tree//`), Install, Update and Preview now refuse its release URLs with an error naming the package. Before, such a `repo` skipped the repository check and any GitHub release asset was downloaded. A package without a `repo` keeps any repository's release asset. The example catalog's schema now holds `repo` and release `url` to the same forms, and `scripts/validate.sh` checks that every release is an asset of the package's `repo` before it downloads anything. --- crates/engine/src/system/library.rs | 100 ++++++++++++++++---- crates/host/tests/it/library.rs | 6 ++ docs/plugins.md | 6 +- docs/publishing-plugins.md | 4 +- examples/plugin-catalog/schema.json | 8 +- examples/plugin-catalog/scripts/validate.sh | 22 ++++- 6 files changed, 117 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/system/library.rs b/crates/engine/src/system/library.rs index 0e55c8acb..d1eaaf0bd 100644 --- a/crates/engine/src/system/library.rs +++ b/crates/engine/src/system/library.rs @@ -266,20 +266,33 @@ fn strip_prefix_ignore_case<'a>(s: &'a str, prefix: &str) -> Option<&'a str> { head.eq_ignore_ascii_case(prefix).then(|| s.get(prefix.len()..)).flatten() } +/// A `.` or `..` path segment, also percent-encoded. +fn dot_segment(p: &str) -> bool { + let p = p.to_ascii_lowercase().replace("%2e", "."); + p == "." || p == ".." +} + /// `(owner, name)` in lower case of a `https://github.com//` repository URL (an -/// optional trailing `/` or `.git`); `None` for anything else. +/// optional trailing `/` or `.git`) or of a folder in one, `https://github.com///tree//`; +/// `None` for anything else. fn github_repo(repo: &str) -> Option<(String, String)> { let rest = strip_prefix_ignore_case(repo.trim(), "https://github.com/")?; + if rest.contains(['?', '#', '\\']) { + return None; + } let rest = rest.strip_suffix('/').unwrap_or(rest); - let rest = rest.strip_suffix(".git").unwrap_or(rest); - let mut parts = rest.split('/'); - let (owner, name) = (parts.next()?, parts.next()?); - (parts.next().is_none() && valid_repo_part(owner) && valid_repo_part(name)).then(|| (owner.to_ascii_lowercase(), name.to_ascii_lowercase())) + let parts: Vec<&str> = rest.split('/').collect(); + let (owner, name) = match parts.as_slice() { + [owner, name] => (*owner, name.strip_suffix(".git").unwrap_or(name)), + [owner, name, "tree", folder @ ..] if !folder.is_empty() && folder.iter().all(|p| !p.is_empty() && !dot_segment(p)) => (*owner, *name), + _ => return None, + }; + (valid_repo_part(owner) && valid_repo_part(name)).then(|| (owner.to_ascii_lowercase(), name.to_ascii_lowercase())) } /// Why an `https://` release URL can't be used, if it can't: it must be a release asset, -/// `https://github.com///releases/download//`, and when the package's -/// `repo` is a GitHub repository URL, `/` must be that repository. +/// `https://github.com///releases/download//`, and when the package +/// names a `repo`, that must be a GitHub repository URL (see [`github_repo`]) of `/`. fn release_url_problem(repo: &str, url: &str) -> Option { let not_asset = || Some(format!("`{url}` isn't a release asset (https://github.com///releases/download//)")); let Some(rest) = strip_prefix_ignore_case(url, "https://github.com/") else { return not_asset() }; @@ -287,11 +300,9 @@ fn release_url_problem(repo: &str, url: &str) -> Option { return not_asset(); } let parts: Vec<&str> = rest.split('/').collect(); - // `.` and `..` (also percent-encoded) would move the download to another path. - let dot_segment = |p: &&str| { - let p = p.to_ascii_lowercase().replace("%2e", "."); - p == "." || p == ".." - }; + // At least six segments, not exactly six: a tag may contain `/` (`release/v1`), and its assets are + // then at `releases/download/release/v1/`. `.` and `..` (also percent-encoded) would move + // the download to another path. if parts.len() < 6 || parts.iter().any(|p| p.is_empty() || dot_segment(p)) { return not_asset(); } @@ -299,11 +310,16 @@ fn release_url_problem(repo: &str, url: &str) -> Option { if !valid_repo_part(owner) || !valid_repo_part(name) || *releases != "releases" || *download != "download" { return not_asset(); } + let repo = repo.trim(); + if repo.is_empty() { + return None; + } match github_repo(repo) { - Some((o, n)) if o != owner.to_ascii_lowercase() || n != name.to_ascii_lowercase() => { - Some(format!("`{url}` isn't a release asset of the package's repository {}", repo.trim())) - } - _ => None, + Some((o, n)) if o == owner.to_ascii_lowercase() && n == name.to_ascii_lowercase() => None, + Some(_) => Some(format!("`{url}` isn't a release asset of the package's repository {repo}")), + None => Some(format!( + "the package's `repo` {repo} isn't a GitHub repository URL (https://github.com//), so `{url}` can't be checked against it" + )), } } @@ -854,7 +870,7 @@ fn pick(s: &Session, c: &str, p: &Value) -> Result<(String, Package, Release)> { if let Source::Https(u) = source(&rel.url, Some(&url)).map_err(|e| bad(c, e))? && let Some(why) = release_url_problem(&pkg.repo, &u) { - return Err(bad(c, why)); + return Err(bad(c, format!("{}: {why}", pkg.name))); } Ok((url, pkg, rel)) } @@ -1191,7 +1207,7 @@ mod tests { #[test] fn release_urls_are_assets_of_the_declared_repository() { let asset = "https://github.com/Me/Glow/releases/download/v1.0.0/glow.wasm"; - for repo in ["https://github.com/me/glow", "https://github.com/Me/Glow/", "https://GitHub.com/me/glow.git", "", "https://gitlab.com/me/glow"] { + for repo in ["https://github.com/me/glow", "https://github.com/Me/Glow/", "https://GitHub.com/me/glow.git", ""] { assert_eq!(release_url_problem(repo, asset), None, "{repo}"); } assert_eq!(release_url_problem("", "https://github.com/a/b/releases/download/tags/v1/x.wasm"), None, "a tag with a slash"); @@ -1221,11 +1237,57 @@ mod tests { assert!(release_url_problem("", no).is_some(), "{no}"); } assert_eq!(github_repo("https://github.com/Me/Glow.git"), Some(("me".into(), "glow".into()))); - for no in ["https://github.com/me", "https://github.com/me/glow/tree/main", "http://github.com/me/glow", "me/glow"] { + assert_eq!(github_repo("https://github.com/Me/Glow/tree/main/plugins/glow"), Some(("me".into(), "glow".into()))); + for no in ["https://github.com/me", "https://github.com/me/glow/tree", "http://github.com/me/glow", "me/glow"] { assert_eq!(github_repo(no), None, "{no}"); } } + #[test] + fn a_repo_that_isnt_a_github_repository_url_refuses_every_release() { + let asset = "https://github.com/me/glow/releases/download/v1/glow.wasm"; + for repo in [ + "https://github.com/me/glow", + "https://github.com/me/glow/", + "https://github.com/me/glow.git", + "https://github.com/me/glow.git/", + " https://github.com/ME/glow ", + "https://github.com/me/glow/tree/main", + "https://github.com/me/glow/tree/main/plugins/glow/", + "", + " ", + ] { + assert_eq!(release_url_problem(repo, asset), None, "{repo:?}"); + } + let elsewhere = release_url_problem("https://github.com/me/glow/tree/main", "https://github.com/you/evil/releases/download/v1/glow.wasm"); + assert!(elsewhere.as_deref().is_some_and(|w| w.contains("package's repository")), "{elsewhere:?}"); + for repo in [ + "https://github.com/me/glow/tree", + "https://github.com/me/glow/tree/", + "https://github.com/me/glow/tree//x", + "https://github.com/me/glow/tree/main/../../you/evil", + "https://github.com/me/glow/tree/main/%2e%2e", + "https://github.com/me/glow/blob/main/README.md", + "https://github.com/me/glow.git/x", + "https://github.com/me/glow/releases", + "https://github.com/me/glow//", + "https://github.com/me", + "https://github.com/me/", + "http://github.com/me/glow", + "github.com/me/glow", + "me/glow", + "https://www.github.com/me/glow", + "https://gitlab.com/me/glow", + "https://github.com/me/glow?tab=readme", + "https://github.com/me/glow#readme", + "https://github.com/me/gl ow", + "https://github.com/me/..", + ] { + let why = release_url_problem(repo, asset); + assert!(why.as_deref().is_some_and(|w| w.contains("isn't a GitHub repository URL")), "{repo:?}: {why:?}"); + } + } + #[test] fn catalogs_leave_out_bad_entries() { let good = "a".repeat(64); diff --git a/crates/host/tests/it/library.rs b/crates/host/tests/it/library.rs index f5bd613cc..35cbf74a7 100644 --- a/crates/host/tests/it/library.rs +++ b/crates/host/tests/it/library.rs @@ -169,6 +169,9 @@ fn downloads_are_release_assets_of_the_package_repository() { pkg("org.test.raw", "https://github.com/me/glow", "https://raw.githubusercontent.com/me/glow/main/glow.wasm"), pkg("org.test.page", "", "https://github.com/me/glow/blob/main/glow.wasm"), pkg("org.test.dots", "https://github.com/me/glow", "https://github.com/me/glow/releases/download/%2e%2e/%2E%2E/x/y/glow.wasm"), + pkg("org.test.tree", "https://github.com/me/glow/tree/main", "https://github.com/someone/else/releases/download/v1/glow.wasm"), + pkg("org.test.http", "http://github.com/me/glow", "https://github.com/me/glow/releases/download/v1/glow.wasm"), + pkg("org.test.blob", "https://github.com/me/glow/blob/main/README.md", "https://github.com/me/glow/releases/download/v1/glow.wasm"), ]), ); let mut s = session(&dir); @@ -178,6 +181,9 @@ fn downloads_are_release_assets_of_the_package_repository() { ("org.test.raw", "isn't a release asset"), ("org.test.page", "isn't a release asset"), ("org.test.dots", "isn't a release asset"), + ("org.test.tree", "isn't a release asset of the package's repository https://github.com/me/glow/tree/main"), + ("org.test.http", "org.test.http: the package's `repo` http://github.com/me/glow isn't a GitHub repository URL"), + ("org.test.blob", "org.test.blob: the package's `repo` https://github.com/me/glow/blob/main/README.md isn't a GitHub repository URL"), ] { for c in ["library.install", "library.preview"] { let e = s.execute(c, json!({"id": id, "wait": true})).unwrap_err().to_string(); diff --git a/docs/plugins.md b/docs/plugins.md index 99b91874f..5302b0b3c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -375,8 +375,10 @@ package can't read files, open the network or crash the app. catalog gives one) against the catalog and loads it. Downloads use the system's `curl`, `https://` only and starting on GitHub's hosts (redirects stay on `https://`; the SHA-256 check is what guarantees the file). A package's `url` must be a release asset - (`https://github.com///releases/download/…`), in the package's `repo` when that is - a GitHub repository URL. A catalog other than the community one is read only when + (`https://github.com///releases/download/…`). When the package names a `repo`, the + asset must be in that repository. A `repo` that isn't `https://github.com//` (with + an optional trailing `/` or `.git`) or a folder in one (`https://github.com///tree//…`) + makes Install and Preview refuse every release of the package. A catalog other than the community one is read only when `library.refresh {catalog}` names it: an `index.json` on GitHub's hosts over `https://`, or a local `file://` path. * **Where it goes.** `/Library///.wasm` (the `Plug-ins` folder next to diff --git a/docs/publishing-plugins.md b/docs/publishing-plugins.md index c94f9e2a8..c28554f14 100644 --- a/docs/publishing-plugins.md +++ b/docs/publishing-plugins.md @@ -181,7 +181,7 @@ Package fields: | `author` | no | You, or your group. | | `description` | no, but reviewed | One or two plain sentences that say what the effect does. | | `license` | no, but reviewed | The licence's SPDX id (`MIT`, `Apache-2.0`, `MIT OR Apache-2.0`…). | -| `repo` | no, but reviewed | The public source repository. The details' "Open on GitHub" opens it. | +| `repo` | no, but reviewed | The public source repository, as `https://github.com//` (a trailing `/` or `.git` is allowed), or a folder in it, `https://github.com///tree//`. The details' "Open on GitHub" opens it. When `repo` is given in any other form, Install and Preview refuse every release of the package. | | `tags` | no | Lower-case words for the tag filter (`blur`, `stylize`, `light`, `distort`…). Reuse tags the catalog already has. | | `preview.video` | no | An `https://` link to a short demo video on YouTube, Vimeo or GitHub. "Watch video" opens it in the browser. A link that isn't `https://` (or is longer than 500 characters) is left out. The live preview doesn't need it. | | `versions` | yes | One entry per release, newest or oldest first. | @@ -193,7 +193,7 @@ Release fields (one per entry in `versions`): | `version` | yes | Dotted numbers only, at most 32 characters: `1.0.0`, `1.2`. No `v` and no suffixes such as `-beta`. | | `api` | yes | The plug-in API the module implements: `1`. | | `minApp` | no | The oldest EffectCraft version the release needs (`0.17.0`). Leave it out if any version with this API works. | -| `url` | yes | The release asset's `https://` URL on GitHub: `https://github.com///releases/download//`. When `repo` is a `https://github.com//` URL, the asset must be in that repository. Install and Preview refuse any other `https://` URL. | +| `url` | yes | The release asset's `https://` URL on GitHub: `https://github.com///releases/download//`. When the package has a `repo`, the asset must be in that repository. Install and Preview refuse any other `https://` URL. | | `sha256` | yes | The file's SHA-256, 64 hex digits. | | `size` | no, but reviewed | The file's size in bytes. When it is given, a download of another size is refused. | | `effects` | yes | The effect ids the module registers (its manifest's `id`). EffectCraft uses them to find the package that provides an effect a project needs. | diff --git a/examples/plugin-catalog/schema.json b/examples/plugin-catalog/schema.json index a2d30676b..5fe914d86 100644 --- a/examples/plugin-catalog/schema.json +++ b/examples/plugin-catalog/schema.json @@ -12,9 +12,9 @@ }, "$defs": { "version": {"type": "string", "maxLength": 32, "pattern": "^[0-9]+(\\.[0-9]+)*$"}, - "github_url": { + "release_url": { "type": "string", - "pattern": "^https://(github\\.com|raw\\.githubusercontent\\.com|objects\\.githubusercontent\\.com|release-assets\\.githubusercontent\\.com)/[^\\s]+$" + "pattern": "^(?!.*/(\\.|%2[eE]){1,2}(/|$))https://[Gg][Ii][Tt][Hh][Uu][Bb]\\.[Cc][Oo][Mm]/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+/releases/download/[^/?#\\\\\\s]+(/[^/?#\\\\\\s]+)+$" }, "package": { "type": "object", @@ -26,7 +26,7 @@ "author": {"type": "string"}, "description": {"type": "string"}, "license": {"type": "string"}, - "repo": {"type": "string", "pattern": "^https://"}, + "repo": {"type": "string", "pattern": "^(?!.*/(\\.|%2[eE]){1,2}(/|$))[Hh][Tt][Tt][Pp][Ss]://[Gg][Ii][Tt][Hh][Uu][Bb]\\.[Cc][Oo][Mm]/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+(/tree(/[^/?#\\\\\\s]+)+)?/?$"}, "tags": {"type": "array", "items": {"type": "string"}}, "preview": { "type": "object", @@ -44,7 +44,7 @@ "version": {"$ref": "#/$defs/version"}, "api": {"type": "integer", "minimum": 0, "maximum": 4294967295}, "minApp": {"$ref": "#/$defs/version"}, - "url": {"$ref": "#/$defs/github_url"}, + "url": {"$ref": "#/$defs/release_url"}, "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"}, "size": {"type": "integer", "minimum": 1, "maximum": 67108864}, "effects": {"type": "array", "minItems": 1, "items": {"type": "string", "pattern": "^(?!ec\\.)[A-Za-z0-9._-]+$"}} diff --git a/examples/plugin-catalog/scripts/validate.sh b/examples/plugin-catalog/scripts/validate.sh index 40e37de7f..60686330a 100644 --- a/examples/plugin-catalog/scripts/validate.sh +++ b/examples/plugin-catalog/scripts/validate.sh @@ -42,7 +42,25 @@ dups=$(jq -r '.packages[].id' "$catalog" | sort | uniq -d) [ -z "$dups" ] || fail "duplicate package ids: $dups" echo "ok" -echo "== 3. downloads" +echo "== 3. release URLs" +# When a package has a `repo`, every release must be an asset of that repository, as Install and +# Preview require (the loader step installs from file:// copies, which skip this check). +bad=$(jq -r ' + # Only the scheme, host, owner and name compare without case; the `.git` suffix is lower case. + def repo_of: + (capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+?)(\\.git)?/?$") + // capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+)/tree/[^?#]+$") + | select(.h | ascii_downcase == "https://github.com") | "\(.o)/\(.n)" | ascii_downcase) // "?"; + .packages[] | . as $pkg | ((.repo // "") | gsub("^\\s+|\\s+$"; "")) as $repo + | select($repo != "") | ($repo | repo_of) as $want + | .versions[] | select(.url | startswith("file://") | not) + | ((.url | ascii_downcase | capture("^https://github\\.com/(?[^/]+)/(?[^/]+)/releases/download/") | "\(.o)/\(.n)") // "?") as $got + | select($want == "?" or $got != $want) + | "\($pkg.id) \(.version): \(.url) is not a release asset of \($repo)"' "$catalog") +[ -z "$bad" ] || fail "release URLs outside the package's repo:"$'\n'"$bad" +echo "ok" + +echo "== 4. downloads" # The checked files are what the loader step installs: a copy of the catalog names them by file://. local_catalog=$(jq '.' "$catalog") while IFS=$'\t' read -r p r id version url sha size; do @@ -58,7 +76,7 @@ done < <(jq -r '.packages | to_entries[] | .key as $p | .value as $pkg | $pkg.ve | [$p, .key, $pkg.id, .value.version, .value.url, .value.sha256, (.value.size // "")] | @tsv' "$catalog") echo "ok" -echo "== 4. load with EffectCraft" +echo "== 5. load with EffectCraft" if [ -z "${EFFECTCRAFT_CLI:-}" ]; then echo "skipped (set EFFECTCRAFT_CLI to an effectcraft-cli build)" exit 0 From 400187f9d91b4b2e9b6995f5afb19b4bba053390 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 5 Nov 2026 23:59:53 -0800 Subject: [PATCH 013/324] Plug-in Library: the catalog validator refuses dot and empty folder segments in repo `scripts/validate.sh` now reads a `repo` folder URL (`https://github.com///tree//`) as EffectCraft does: an empty, `.` or `..` segment (also percent-encoded), or a `?`, `#` or `\`, makes the `repo` unreadable, and every release of the package is reported. A `.` or `..` owner or name is refused too. The check now matches the app when the schema step is skipped. --- examples/plugin-catalog/scripts/validate.sh | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/plugin-catalog/scripts/validate.sh b/examples/plugin-catalog/scripts/validate.sh index 60686330a..6e57e05ce 100644 --- a/examples/plugin-catalog/scripts/validate.sh +++ b/examples/plugin-catalog/scripts/validate.sh @@ -46,11 +46,15 @@ echo "== 3. release URLs" # When a package has a `repo`, every release must be an asset of that repository, as Install and # Preview require (the loader step installs from file:// copies, which skip this check). bad=$(jq -r ' + # A path segment EffectCraft refuses: empty, `.` or `..` (also percent-encoded). + def bad_segment: . == "" or (ascii_downcase | gsub("%2e"; ".") | . == "." or . == ".."); # Only the scheme, host, owner and name compare without case; the `.git` suffix is lower case. def repo_of: (capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+?)(\\.git)?/?$") - // capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+)/tree/[^?#]+$") - | select(.h | ascii_downcase == "https://github.com") | "\(.o)/\(.n)" | ascii_downcase) // "?"; + // (capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+)/tree/(?[^?#\\\\]+?)/?$") + | select(.f | split("/") | any(bad_segment) | not)) + | select((.h | ascii_downcase) == "https://github.com" and (.o | bad_segment | not) and (.n | bad_segment | not)) + | "\(.o)/\(.n)" | ascii_downcase) // "?"; .packages[] | . as $pkg | ((.repo // "") | gsub("^\\s+|\\s+$"; "")) as $repo | select($repo != "") | ($repo | repo_of) as $want | .versions[] | select(.url | startswith("file://") | not) From cc90ad0c3b2f36c5ade8b4d9620f6e5afba0bf32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 6 Nov 2026 00:32:31 -0800 Subject: [PATCH 014/324] Plug-in Library: the catalog validator checks every remote release URL in full scripts/validate.sh now refuses any release URL other than a local file:// path that isn't a release asset (https://github.com///releases/download// with no query, fragment, backslash, or empty, . or .. segment), for packages without a repo too, as Install and Preview do. docs/plugins.md says the release URL rules don't apply to file:// releases from a local catalog. --- docs/plugins.md | 4 ++- examples/plugin-catalog/scripts/validate.sh | 28 +++++++++++++++------ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index 5302b0b3c..cc4f164aa 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -378,7 +378,9 @@ package can't read files, open the network or crash the app. (`https://github.com///releases/download/…`). When the package names a `repo`, the asset must be in that repository. A `repo` that isn't `https://github.com//` (with an optional trailing `/` or `.git`) or a folder in one (`https://github.com///tree//…`) - makes Install and Preview refuse every release of the package. A catalog other than the community one is read only when + makes Install and Preview refuse every `https://` release of the package. These rules don't apply + to a release whose `url` is a local `file://` path, which only a local catalog may name (to test + an entry before its release is published). A catalog other than the community one is read only when `library.refresh {catalog}` names it: an `index.json` on GitHub's hosts over `https://`, or a local `file://` path. * **Where it goes.** `/Library///.wasm` (the `Plug-ins` folder next to diff --git a/examples/plugin-catalog/scripts/validate.sh b/examples/plugin-catalog/scripts/validate.sh index 6e57e05ce..4a0d196fc 100644 --- a/examples/plugin-catalog/scripts/validate.sh +++ b/examples/plugin-catalog/scripts/validate.sh @@ -43,11 +43,24 @@ dups=$(jq -r '.packages[].id' "$catalog" | sort | uniq -d) echo "ok" echo "== 3. release URLs" -# When a package has a `repo`, every release must be an asset of that repository, as Install and -# Preview require (the loader step installs from file:// copies, which skip this check). +# Every release that isn't a local file:// path must be a release asset, and when its package has +# a `repo`, an asset of that repository, as Install and Preview require (the loader step installs +# from file:// copies, which skip this check). bad=$(jq -r ' # A path segment EffectCraft refuses: empty, `.` or `..` (also percent-encoded). def bad_segment: . == "" or (ascii_downcase | gsub("%2e"; ".") | . == "." or . == ".."); + # "owner/name" in lower case of a release asset, + # https://github.com///releases/download// (a tag may contain `/`), with + # no query, fragment, backslash, or empty, `.` or `..` segment; "?" for anything else. + def asset_of: + if startswith("https://") and (.[8:19] | ascii_downcase) == "github.com/" then + .[19:] as $rest + | ($rest | split("/")) as $p + | if ($rest | test("[?#\\\\]")) or ($p | length) < 6 or ($p | any(bad_segment)) + or ($p[0] | test("^[A-Za-z0-9._-]+$") | not) or ($p[1] | test("^[A-Za-z0-9._-]+$") | not) + or $p[2] != "releases" or $p[3] != "download" + then "?" else "\($p[0])/\($p[1])" | ascii_downcase end + else "?" end; # Only the scheme, host, owner and name compare without case; the `.git` suffix is lower case. def repo_of: (capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+?)(\\.git)?/?$") @@ -56,12 +69,13 @@ bad=$(jq -r ' | select((.h | ascii_downcase) == "https://github.com" and (.o | bad_segment | not) and (.n | bad_segment | not)) | "\(.o)/\(.n)" | ascii_downcase) // "?"; .packages[] | . as $pkg | ((.repo // "") | gsub("^\\s+|\\s+$"; "")) as $repo - | select($repo != "") | ($repo | repo_of) as $want + | (if $repo == "" then "" else $repo | repo_of end) as $want | .versions[] | select(.url | startswith("file://") | not) - | ((.url | ascii_downcase | capture("^https://github\\.com/(?[^/]+)/(?[^/]+)/releases/download/") | "\(.o)/\(.n)") // "?") as $got - | select($want == "?" or $got != $want) - | "\($pkg.id) \(.version): \(.url) is not a release asset of \($repo)"' "$catalog") -[ -z "$bad" ] || fail "release URLs outside the package's repo:"$'\n'"$bad" + | (.url | asset_of) as $got + | if $got == "?" then "\($pkg.id) \(.version): \(.url) is not a release asset (https://github.com///releases/download//)" + elif $want != "" and ($want == "?" or $got != $want) then "\($pkg.id) \(.version): \(.url) is not a release asset of \($repo)" + else empty end' "$catalog") +[ -z "$bad" ] || fail "release URLs that Install and Preview refuse:"$'\n'"$bad" echo "ok" echo "== 4. downloads" From 36dc209badfdbab2fa99f44e130798e3c35277ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 6 Nov 2026 00:49:16 -0800 Subject: [PATCH 015/324] Plug-in Library: release and repo URLs with white space are refused Install and Preview, the catalog schema and scripts/validate.sh now refuse a release URL or repo folder that contains white space in any segment, the tag and file name included: any Unicode white space character, and U+FEFF. Before, the app accepted a space or tab in a tag, file name or repo folder that the schema refused. --- crates/engine/src/system/library.rs | 19 +++++++++++++++++-- examples/plugin-catalog/schema.json | 4 ++-- examples/plugin-catalog/scripts/validate.sh | 9 ++++++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/system/library.rs b/crates/engine/src/system/library.rs index d1eaaf0bd..8fb147e53 100644 --- a/crates/engine/src/system/library.rs +++ b/crates/engine/src/system/library.rs @@ -272,12 +272,18 @@ fn dot_segment(p: &str) -> bool { p == "." || p == ".." } +/// A character a release or repository URL may not contain: `?`, `#`, `\`, Unicode white space, +/// or U+FEFF (the catalog schema's `\s` matches it too). +fn bad_url_char(c: char) -> bool { + matches!(c, '?' | '#' | '\\' | '\u{feff}') || c.is_whitespace() +} + /// `(owner, name)` in lower case of a `https://github.com//` repository URL (an /// optional trailing `/` or `.git`) or of a folder in one, `https://github.com///tree//`; /// `None` for anything else. fn github_repo(repo: &str) -> Option<(String, String)> { let rest = strip_prefix_ignore_case(repo.trim(), "https://github.com/")?; - if rest.contains(['?', '#', '\\']) { + if rest.contains(bad_url_char) { return None; } let rest = rest.strip_suffix('/').unwrap_or(rest); @@ -296,7 +302,7 @@ fn github_repo(repo: &str) -> Option<(String, String)> { fn release_url_problem(repo: &str, url: &str) -> Option { let not_asset = || Some(format!("`{url}` isn't a release asset (https://github.com///releases/download//)")); let Some(rest) = strip_prefix_ignore_case(url, "https://github.com/") else { return not_asset() }; - if rest.contains(['?', '#', '\\']) { + if rest.contains(bad_url_char) { return not_asset(); } let parts: Vec<&str> = rest.split('/').collect(); @@ -1230,6 +1236,12 @@ mod tests { "https://github.com/me/glow/releases/download/./v1/x.wasm", "https://github.com/me/glow/releases/download/v1\\x.wasm", "https://github.com/m e/glow/releases/download/v1/x.wasm", + "https://github.com/me/glow/releases/download/v 1/x.wasm", + "https://github.com/me/glow/releases/download/v1/x\t.wasm", + "https://github.com/me/glow/releases/download/v1/x.wasm\n", + "https://github.com/me/glow/releases/download/v1\u{a0}/x.wasm", + "https://github.com/me/glow/releases/download/v1/\u{85}x.wasm", + "https://github.com/me/glow/releases/download/v1/x\u{feff}.wasm", "https://github.com/../glow/releases/download/v1/x.wasm", "https://github.com.evil.com/me/glow/releases/download/v1/x.wasm", ] { @@ -1281,6 +1293,9 @@ mod tests { "https://github.com/me/glow?tab=readme", "https://github.com/me/glow#readme", "https://github.com/me/gl ow", + "https://github.com/me/glow/tree/main/my plug-in", + "https://github.com/me/glow/tree/ma\tin", + "https://github.com/me/glow/tree/main/x\u{feff}", "https://github.com/me/..", ] { let why = release_url_problem(repo, asset); diff --git a/examples/plugin-catalog/schema.json b/examples/plugin-catalog/schema.json index 5fe914d86..c31d57fea 100644 --- a/examples/plugin-catalog/schema.json +++ b/examples/plugin-catalog/schema.json @@ -14,7 +14,7 @@ "version": {"type": "string", "maxLength": 32, "pattern": "^[0-9]+(\\.[0-9]+)*$"}, "release_url": { "type": "string", - "pattern": "^(?!.*/(\\.|%2[eE]){1,2}(/|$))https://[Gg][Ii][Tt][Hh][Uu][Bb]\\.[Cc][Oo][Mm]/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+/releases/download/[^/?#\\\\\\s]+(/[^/?#\\\\\\s]+)+$" + "pattern": "^(?!.*/(\\.|%2[eE]){1,2}(/|$))https://[Gg][Ii][Tt][Hh][Uu][Bb]\\.[Cc][Oo][Mm]/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+/releases/download/[^/?#\\\\\\s\\u0085]+(/[^/?#\\\\\\s\\u0085]+)+$" }, "package": { "type": "object", @@ -26,7 +26,7 @@ "author": {"type": "string"}, "description": {"type": "string"}, "license": {"type": "string"}, - "repo": {"type": "string", "pattern": "^(?!.*/(\\.|%2[eE]){1,2}(/|$))[Hh][Tt][Tt][Pp][Ss]://[Gg][Ii][Tt][Hh][Uu][Bb]\\.[Cc][Oo][Mm]/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+(/tree(/[^/?#\\\\\\s]+)+)?/?$"}, + "repo": {"type": "string", "pattern": "^(?!.*/(\\.|%2[eE]){1,2}(/|$))[Hh][Tt][Tt][Pp][Ss]://[Gg][Ii][Tt][Hh][Uu][Bb]\\.[Cc][Oo][Mm]/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+(/tree(/[^/?#\\\\\\s\\u0085]+)+)?/?$"}, "tags": {"type": "array", "items": {"type": "string"}}, "preview": { "type": "object", diff --git a/examples/plugin-catalog/scripts/validate.sh b/examples/plugin-catalog/scripts/validate.sh index 4a0d196fc..711b69394 100644 --- a/examples/plugin-catalog/scripts/validate.sh +++ b/examples/plugin-catalog/scripts/validate.sh @@ -49,25 +49,28 @@ echo "== 3. release URLs" bad=$(jq -r ' # A path segment EffectCraft refuses: empty, `.` or `..` (also percent-encoded). def bad_segment: . == "" or (ascii_downcase | gsub("%2e"; ".") | . == "." or . == ".."); + # A `?`, `#`, `\` or white space character (Unicode, and U+FEFF), which EffectCraft refuses in a URL. + def bad_char: test("[?#\\\\\t\n\u000b\f\r \u0085   - 

   ]"); # "owner/name" in lower case of a release asset, # https://github.com///releases/download// (a tag may contain `/`), with - # no query, fragment, backslash, or empty, `.` or `..` segment; "?" for anything else. + # no query, fragment, backslash, white space, or empty, `.` or `..` segment; "?" for anything else. def asset_of: if startswith("https://") and (.[8:19] | ascii_downcase) == "github.com/" then .[19:] as $rest | ($rest | split("/")) as $p - | if ($rest | test("[?#\\\\]")) or ($p | length) < 6 or ($p | any(bad_segment)) + | if ($rest | bad_char) or ($p | length) < 6 or ($p | any(bad_segment)) or ($p[0] | test("^[A-Za-z0-9._-]+$") | not) or ($p[1] | test("^[A-Za-z0-9._-]+$") | not) or $p[2] != "releases" or $p[3] != "download" then "?" else "\($p[0])/\($p[1])" | ascii_downcase end else "?" end; # Only the scheme, host, owner and name compare without case; the `.git` suffix is lower case. def repo_of: + if bad_char then "?" else (capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+?)(\\.git)?/?$") // (capture("^(?[^/]+//[^/]+)/(?[A-Za-z0-9._-]+)/(?[A-Za-z0-9._-]+)/tree/(?[^?#\\\\]+?)/?$") | select(.f | split("/") | any(bad_segment) | not)) | select((.h | ascii_downcase) == "https://github.com" and (.o | bad_segment | not) and (.n | bad_segment | not)) - | "\(.o)/\(.n)" | ascii_downcase) // "?"; + | "\(.o)/\(.n)" | ascii_downcase) // "?" end; .packages[] | . as $pkg | ((.repo // "") | gsub("^\\s+|\\s+$"; "")) as $repo | (if $repo == "" then "" else $repo | repo_of end) as $want | .versions[] | select(.url | startswith("file://") | not) From 91443ef25ed750afcdc449cd52007faade922fd0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 6 Nov 2026 22:20:40 +0100 Subject: [PATCH 016/324] Disk cache: record the source files each frame reads Part of #3184 (step 1): renders now report which footage files they read, each with its identity (size and modification time) as read. Nothing uses the list yet: images, cache keys and cache behaviour are unchanged. - render: `reads` module with `FileStamp`, `ReadFile`, `ReadFiles` (sorted, deduplicated, bounded; marked incomplete when it can't vouch for every file) and the thread-safe `ReadLog`. `Renderer::reads` collects a frame's files; `FootageSource::recording` lets a source note what it reads. `file_stamp` uses the same identity. - Layer cache entries keep the files their buffer was made of and report them on every hit; derived entries (styles, blend space, flattened) keep their base's. Buffers from the disk cache or the browser store don't know their files yet and mark the list incomplete. - Media pool: every file read notes its identity, taken from the file it opens. Decoded frames, opened movies, GIFs, models and EXR channels keep it with the cache entry, so a frame served from memory reports its file without touching the disk. - Viewer frame worker collects each frame's list and carries it to where the disk entry is written (step 2 stores it). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/media/Cargo.toml | 4 + crates/media/src/exr_channels.rs | 84 +++++---- crates/media/src/lib.rs | 26 ++- crates/media/src/pool.rs | 198 +++++++++++++-------- crates/media/src/reads.rs | 117 +++++++++++++ crates/media/src/reads/tests.rs | 184 ++++++++++++++++++++ crates/media/src/stream.rs | 15 +- crates/render/src/accel.rs | 20 +-- crates/render/src/cache.rs | 34 ++-- crates/render/src/disk_cache.rs | 15 +- crates/render/src/footage.rs | 17 ++ crates/render/src/fx_host.rs | 2 +- crates/render/src/layers.rs | 38 ++-- crates/render/src/lib.rs | 5 + crates/render/src/pipeline.rs | 164 +++++++++++------- crates/render/src/reads.rs | 230 +++++++++++++++++++++++++ crates/render/src/three_d/adv/scene.rs | 4 +- crates/render/src/three_d/compose.rs | 4 +- crates/ui-egui/src/frames.rs | 53 ++++-- 20 files changed, 968 insertions(+), 247 deletions(-) create mode 100644 crates/media/src/reads.rs create mode 100644 crates/media/src/reads/tests.rs create mode 100644 crates/render/src/reads.rs diff --git a/Cargo.lock b/Cargo.lock index 5b426c8f8..b35796cce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1741,6 +1741,7 @@ version = "0.21.0" dependencies = [ "craft-docpath", "effectcraft-color", + "effectcraft-effects", "effectcraft-model", "effectcraft-pdf", "effectcraft-project", diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index a4070297b..4947d928a 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -36,3 +36,7 @@ rayon = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } + +[dev-dependencies] +# (tests render comps that read layers through effects; already a dependency of effectcraft-render) +effectcraft-effects = { workspace = true } diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index c3e7cfc3d..d0acf590f 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -17,6 +17,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, split_channel}; use effectcraft_raster::{AuxChannels, Image}; +use effectcraft_render::reads::{ReadFile, ReadFiles}; use exr::block::UncompressedBlock; use exr::block::chunk::TileCoordinates; use exr::image::read::image::ReadImage; @@ -477,8 +478,8 @@ fn layered_picture_of(aux: &AuxChannels, op: AlphaOp) -> Option { /// decoded anyway), else of the picture's channels alone (also when the cache has no channels /// for the file: a read that failed, or a broken part the picture doesn't use). `Err(Some(why))` /// when the file is too large to decode, `Err(None)` when it isn't a readable multi-layer EXR. -pub(crate) fn layered_picture(path: &str, bytes: Arc<[u8]>, op: AlphaOp, shared: bool) -> Result> { - if shared && let Some(d) = cache().get(path, Use::Picture, || Some(bytes.clone())) { +pub(crate) fn layered_picture(path: &str, bytes: Arc<[u8]>, file: &ReadFile, op: AlphaOp, shared: bool) -> Result> { + if shared && let Some(d) = cache().get(path, Use::Picture, || read_as(file, bytes.clone())) { return layered_picture_of(&d.aux, op).ok_or(None); } let (d, rgb, a) = picture_only(&bytes).map_err(|r| match r { @@ -499,8 +500,8 @@ pub(crate) fn layered_picture(path: &str, bytes: Arc<[u8]>, op: AlphaOp, shared: /// decoder shows for a file it reads, [`layered_image`]'s rule for one it refuses. `None` when /// the planes can't stand in for the `image` crate's picture (decode with it), or the file is /// not a readable EXR. -pub(crate) fn cached_picture(path: &str, bytes: Arc<[u8]>, op: AlphaOp) -> Option { - let d = cache().get(path, Use::Picture, || Some(bytes))?; +pub(crate) fn cached_picture(path: &str, bytes: Arc<[u8]>, file: &ReadFile, op: AlphaOp) -> Option { + let d = cache().get(path, Use::Picture, || read_as(file, bytes))?; let aux = &d.aux; match d.rgb { Rgb::None => layered_picture_of(aux, op), @@ -536,8 +537,16 @@ const CACHE_FILES: usize = 64; /// rendered at once. The oldest stops being kept when another comes. const HELD_FILES: usize = 4; -/// A file's decode: done once, by the first caller; the others wait for it. -type Slot = Arc>>>; +/// A file's decode: done once, by the first caller; the others wait for it. With the files read +/// for it (see [`crate::reads`]), noted again on every hit. +type Slot = Arc>, ReadFiles)>>; + +/// Bytes the caller already read from `file`, given to the cache as read from it (so the entry +/// keeps the file's identity). +fn read_as(file: &ReadFile, bytes: Arc<[u8]>) -> Option> { + crate::reads::note(file.clone()); + Some(bytes) +} struct Entry { path: String, @@ -554,8 +563,8 @@ impl Entry { fn in_use(&self) -> bool { match self.slot.get() { None => true, - Some(None) => false, - Some(Some(d)) => Arc::strong_count(d) > 1 || Arc::strong_count(&d.aux) > 1, + Some((None, _)) => false, + Some((Some(d), _)) => Arc::strong_count(d) > 1 || Arc::strong_count(&d.aux) > 1, } } } @@ -648,30 +657,18 @@ impl ChannelCache { // is safe because the decode never waits on rayon's global pool (the exr crate // decompresses on a pool of its own and this thread only receives the blocks), so the // decoding thread can't be waiting for this one. - let v = slot - .get_or_init(|| { - decoded_here = true; - self.decodes.fetch_add(1, Ordering::Relaxed); - #[cfg(test)] - count_decode(true); - let _abandon = Abandon { cache: self, slot: &slot }; - let bytes = read()?; - // The planes it will allocate count against the budget while it decodes. - if let Ok(meta) = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(&bytes[..]), false) - && let Some(need) = planes_bytes(&meta, &|_| true) - { - self.account(&slot, need.min(MAX_DECODE_BYTES)); - } - match decode(&bytes, &|_| true) { - Ok(d) => Some(Arc::new(d)), - Err(Refused::TooLarge(why)) => { - log::warn!("media: {path}: {why}"); - None - } - Err(Refused::Unreadable) => None, - } - }) - .clone(); + let (v, files) = slot.get_or_init(|| { + decoded_here = true; + self.decodes.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + count_decode(true); + let _abandon = Abandon { cache: self, slot: &slot }; + let (bytes, files) = crate::reads::captured(read); + (bytes.and_then(|bytes| self.decode_file(path, &slot, &bytes)), files) + }); + // The file(s) the decode was made of, read now or for an earlier caller. + crate::reads::note_all(files); + let v = v.clone(); if decoded_here { self.account(&slot, v.as_ref().map_or(0, |d| d.bytes())); } @@ -692,6 +689,24 @@ impl ChannelCache { v } + /// Decode the file at `path` whose bytes are `bytes` for `slot` (see [`ChannelCache::get`]). + fn decode_file(&self, path: &str, slot: &Slot, bytes: &[u8]) -> Option> { + // The planes it will allocate count against the budget while it decodes. + if let Ok(meta) = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false) + && let Some(need) = planes_bytes(&meta, &|_| true) + { + self.account(slot, need.min(MAX_DECODE_BYTES)); + } + match decode(bytes, &|_| true) { + Ok(d) => Some(Arc::new(d)), + Err(Refused::TooLarge(why)) => { + log::warn!("media: {path}: {why}"); + None + } + Err(Refused::Unreadable) => None, + } + } + /// Drop least recently used files not in use until the rest fit the budget, keeping `newest`. fn evict(entries: &mut Vec, budget: usize, newest: &Slot) { while entries.iter().map(|e| e.bytes).sum::() > budget || entries.len() > CACHE_FILES { @@ -996,7 +1011,7 @@ mod tests { let path = "/474-shared-fallback.exr"; assert!(cache().get(path, Use::Channels, || None).is_none(), "a read that failed"); let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); - let img = layered_picture(path, bytes, op, true).unwrap(); + let img = layered_picture(path, bytes, &ReadFile::new(path, effectcraft_render::reads::FileStamp::Virtual), op, true).unwrap(); assert_eq!(img.get(1, 1), [0.5, 0.5, 0.5, 1.0]); } @@ -1174,7 +1189,8 @@ mod tests { for curve in [FloatCurve::Srgb, FloatCurve::Linear, FloatCurve::Gamma24] { let op = AlphaOp::of(&Footage { alpha, premul_color: [0.2, 0.4, 0.6], ..Default::default() }, curve); let want = crate::convert::dynamic_to_image(&img, op); - let got = cached_picture(&path, bytes.as_slice().into(), op).unwrap(); + let got = cached_picture(&path, bytes.as_slice().into(), &ReadFile::new(path.as_str(), effectcraft_render::reads::FileStamp::Virtual), op) + .unwrap(); assert_eq!((got.width, got.height), (want.width, want.height)); assert_eq!(bits(&got), bits(&want), "file {k} {alpha:?} {curve:?}"); } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 31478f111..0b509c45f 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -25,6 +25,7 @@ mod layered; pub use layered::vector_doc; mod pool; mod probe; +mod reads; mod stream; mod wav_markers; mod webp_anim; @@ -85,7 +86,15 @@ pub fn is_importable(path: &std::path::Path) -> bool { /// A whole file's bytes, refusing anything that isn't a regular file: a project can name /// `/dev/zero` or a FIFO as footage, and reading those never ends (#2134). pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> { + read_regular_file_stamped(path).map(|(bytes, _)| bytes) +} + +/// [`read_regular_file`] with the file's identity, from the metadata of the open file (no +/// second look at the path). +pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Result<(Vec, effectcraft_render::reads::FileStamp)> { use std::io::Read; + #[cfg(test)] + count_open(path); let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { @@ -95,7 +104,22 @@ pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> = std::sync::Mutex::new(Vec::new()); + +/// Count an open of a file (tests: which files a render touched on disk). +#[cfg(test)] +pub(crate) fn count_open(path: &std::path::Path) { + OPENS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(path.to_path_buf()); +} + +/// How many times files under `dir` were opened so far (tests). +#[cfg(test)] +pub(crate) fn opens_under(dir: &std::path::Path) -> usize { + OPENS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|p| p.starts_with(dir)).count() } pub(crate) fn ext_of(path: &std::path::Path) -> String { diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index b0b2f2539..4b7b05603 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -6,6 +6,7 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use effectcraft_project::{AlphaMode, Footage, FootageKind, ItemId}; use effectcraft_raster::{Image, Px}; +use effectcraft_render::reads::{FileStamp, ReadFile, ReadFiles, ReadLog}; use effectcraft_render::{FloatCurve, FootageSource}; use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick}; use filmcraft_media::{FrameRequest, SharedSource}; @@ -14,6 +15,7 @@ use image::metadata::Orientation; use crate::convert::{AlphaOp, dynamic_to_image, frame_to_image_in, frame_to_image_scaled, turned}; use crate::downmix::Order; use crate::gif_anim::{self, Anim}; +use crate::reads; use crate::{MediaError, Result}; /// Default frame-cache budget: 1 GiB of decoded frames. @@ -53,6 +55,8 @@ struct Key { struct Entry { img: Arc, + /// The files the frame was decoded from (see [`crate::reads`]). + files: Arc, stamp: u64, bytes: usize, } @@ -106,18 +110,18 @@ struct Lru { } impl Lru { - fn get(&mut self, k: &Key) -> Option> { + fn get(&mut self, k: &Key) -> Option<(Arc, Arc)> { let e = self.map.get_mut(k)?; self.order.remove(&e.stamp); self.clock += 1; e.stamp = self.clock; self.order.insert(e.stamp, k.clone()); - Some(e.img.clone()) + Some((e.img.clone(), e.files.clone())) } - fn insert(&mut self, k: Key, img: Arc, budget: usize) { + fn insert(&mut self, k: Key, img: Arc, files: Arc, budget: usize) { let bytes = img.data.len() * std::mem::size_of::() + 64; self.clock += 1; - if let Some(old) = self.map.insert(k.clone(), Entry { img, stamp: self.clock, bytes }) { + if let Some(old) = self.map.insert(k.clone(), Entry { img, files, stamp: self.clock, bytes }) { self.order.remove(&old.stamp); self.bytes -= old.bytes; } @@ -180,8 +184,9 @@ struct CacheState { } /// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait -/// for it (`None`: failed to open; not retried until `forget`). -type SourceSlot = Arc>>; +/// for it (`None`: failed to open; not retried until `forget`), with the file's identity as +/// opened. +type SourceSlot = Arc, ReadFile)>>; /// An opened movie/audio source, the turn its picture is shown with and the order its decoded /// audio channels arrive in. @@ -211,7 +216,7 @@ fn channel_order(src: &SharedSource, header: Option<&[u8]>, file: Option<&dyn fi } /// An animated GIF by path, as [`SourceSlot`] (the error message when it failed to load). -type GifSlot = Arc, String>>>; +type GifSlot = Arc, String>, ReadFile)>>; struct Inner { /// Opened movie/audio sources by path. @@ -220,8 +225,9 @@ struct Inner { opened: AtomicU64, /// In-memory files registered with `add_bytes` (web builds, tests). files: Mutex>>, - /// Parsed 3D models by path (`None`: failed to load; not retried until `forget`). - models: Mutex>>>, + /// Parsed 3D models by path (`None`: failed to load; not retried until `forget`), with the + /// files read for them (the model's and the resources it names). + models: Mutex>, Arc)>>, /// Decoded animated GIFs and WebPs by path, loaded by the first caller while the others wait (an /// `Err` is not retried until `forget`). gifs: Mutex, GifSlot>>, @@ -439,11 +445,13 @@ impl MediaPool { } /// The conformed-audio file of `path` at `rate` (named by a hash of the path, size and - /// modification time, so an edited file conforms again, and of `CONFORM_VERSION`). + /// modification time, so an edited file conforms again, and of `CONFORM_VERSION`). Notes + /// `path` as read with that identity (see [`crate::reads`]): its samples come from it. pub fn conformed_path(&self, path: &str, rate: u32) -> Option { use std::hash::{Hash, Hasher}; let folder = lock(&self.inner.conform).clone()?; let meta = std::fs::metadata(path).ok()?; + reads::note(ReadFile::new(path, FileStamp::of_metadata(&meta))); let mut h = std::collections::hash_map::DefaultHasher::new(); (CONFORM_VERSION, path, meta.len(), meta.modified().ok()).hash(&mut h); Some(folder.join(format!("{:016x}_{rate}.ecaf", h.finish()))) @@ -612,16 +620,20 @@ impl Inner { /// A 3D model file and its sibling resources (buffers, textures, MTL files), parsed once. fn model(&self, path: &str) -> Option> { - if let Some(m) = lock(&self.models).get(path) { - return m.clone(); + let found = lock(&self.models).get(path).cloned(); + if let Some((m, files)) = found { + reads::note_all(&files); + return m; } - let loaded = self.read(path).map_err(|e| e.to_string()).and_then(|bytes| { - // Files the model names are read only when local or on the model's own network share. - let resolve = |uri: &str| -> Option> { - let p = craft_docpath::resolve_absolute(uri, Some(std::path::Path::new(path))).ok()?; - self.read(&p.to_string_lossy()).ok().map(|b| b.to_vec()) - }; - effectcraft_model::load(path, &bytes, &resolve).map_err(|e| e.to_string()) + let (loaded, files) = reads::captured(|| { + self.read(path).map_err(|e| e.to_string()).and_then(|bytes| { + // Files the model names are read only when local or on the model's own network share. + let resolve = |uri: &str| -> Option> { + let p = craft_docpath::resolve_absolute(uri, Some(std::path::Path::new(path))).ok()?; + self.read(&p.to_string_lossy()).ok().map(|b| b.to_vec()) + }; + effectcraft_model::load(path, &bytes, &resolve).map_err(|e| e.to_string()) + }) }); let m = match loaded { Ok(m) => Some(Arc::new(m)), @@ -630,14 +642,29 @@ impl Inner { None } }; - lock(&self.models).entry(path.to_string()).or_insert(m).clone() + let (m, files) = lock(&self.models).entry(path.to_string()).or_insert((m, Arc::new(files))).clone(); + reads::note_all(&files); + m } + /// The bytes of the file at `path`, noted as read (see [`crate::reads`]). fn read(&self, path: &str) -> Result> { - if let Some(b) = lock(&self.files).get(path) { - return Ok(b.clone()); + let (bytes, file) = self.read_file(path); + reads::note(file); + bytes + } + + /// The bytes of the file at `path` and its identity as read ([`FileStamp::Missing`] when it + /// can't be read), not noted. + fn read_file(&self, path: &str) -> (Result>, ReadFile) { + let in_memory = lock(&self.files).get(path).cloned(); + if let Some(b) = in_memory { + return (Ok(b), ReadFile::new(path, FileStamp::Virtual)); + } + match crate::read_regular_file_stamped(std::path::Path::new(path)) { + Ok((bytes, stamp)) => (Ok(bytes.into()), ReadFile::new(path, stamp)), + Err(e) => (Err(MediaError::Io(format!("{path}: {e}"))), ReadFile::new(path, FileStamp::Missing)), } - crate::read_regular_file(std::path::Path::new(path)).map(Into::into).map_err(|e| MediaError::Io(format!("{path}: {e}"))) } /// The opened movie/audio source for `path` ([`Opened`]). The first caller opens it, outside @@ -645,35 +672,42 @@ impl Inner { /// files are decoded whole); callers asking for the same file meanwhile wait for that instead /// of opening it again: a preview's frame workers, audio feeder, conform and waveform threads /// each decoded a long FLAC in full at once (#408). + /// Each call notes the file as read (see [`crate::reads`]), with its identity as opened. fn opened(&self, path: &Arc) -> Option { let slot = lock(&self.sources).entry(path.clone()).or_default().clone(); - slot.get_or_init(|| { - self.opened.fetch_add(1, Ordering::Relaxed); - // Files on disk are read in place (the index, then samples on demand) rather than - // whole; in-memory files (`add_bytes`) and wasm32 builds open from bytes. - let in_memory = lock(&self.files).contains_key(&**path); - let file = std::path::Path::new(&**path); - let in_place = if in_memory { None } else { crate::stream::open_source(file) }; - let in_place = in_place.map(|src| { - let (header, reader) = (crate::stream::movie_header(file), crate::stream::file_reader(file)); - src.map(|src| Opened::new(src, header.as_deref(), reader.as_deref())) + let (opened, file) = slot.get_or_init(|| self.open(path)); + reads::note(file.clone()); + opened.clone() + } + + /// Open the movie/audio file at `path` (see [`Inner::opened`]), with its identity as opened. + fn open(&self, path: &Arc) -> (Option, ReadFile) { + self.opened.fetch_add(1, Ordering::Relaxed); + // Files on disk are read in place (the index, then samples on demand) rather than + // whole; in-memory files (`add_bytes`) and wasm32 builds open from bytes. + let in_memory = lock(&self.files).contains_key(&**path); + let file = std::path::Path::new(&**path); + let in_place = if in_memory { None } else { crate::stream::open_source(file) }; + let in_place = in_place.map(|(src, stamp)| { + let (header, reader) = (crate::stream::movie_header(file), crate::stream::file_reader(file)); + (src.map(|src| Opened::new(src, header.as_deref(), reader.as_deref())), ReadFile::new(path.clone(), stamp)) + }); + let (opened, read) = in_place.unwrap_or_else(|| { + let (bytes, read) = self.read_file(path); + let opened = bytes.and_then(|bytes| { + let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(MediaError::from)?; + Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone())))) }); - let opened = in_place.unwrap_or_else(|| { - self.read(path).and_then(|bytes| { - let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(MediaError::from)?; - Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone())))) - }) - }); - match opened { - Ok(s) => Some(s), - Err(e) => { - self.note_problem(path, "", &e); - None - } + (opened, read) + }); + match opened { + Ok(s) => (Some(s), read), + Err(e) => { + self.note_problem(path, "", &e); + (None, read) } - }) - .clone() + } } /// Remember why the movie at `path` cannot be shown (`codec` is the footage's, when known) @@ -694,13 +728,15 @@ impl Inner { /// map's lock; callers asking for the same file meanwhile wait for that. fn gif(&self, path: &Arc) -> Result> { let slot = lock(&self.gifs).entry(path.clone()).or_default().clone(); - let loaded = slot.get_or_init(|| { - let loaded = self.read(path).and_then(|bytes| Anim::load(&bytes)); - loaded.map(Arc::new).map_err(|e| { + let (loaded, file) = slot.get_or_init(|| { + let (bytes, file) = self.read_file(path); + let loaded = bytes.and_then(|bytes| Anim::load(&bytes)).map(Arc::new).map_err(|e| { log::warn!("media: cannot decode {path}: {e}"); e.to_string() - }) + }); + (loaded, file) }); + reads::note(file.clone()); loaded.clone().map_err(|e| MediaError::Decode(format!("{path}: {e}"))) } @@ -783,19 +819,15 @@ impl Inner { let mut c = lock(&self.cache); // sequential playback of a movie: read the next frame ahead if playback && movie { - let prev = c.last.insert(loc.key.path.clone(), loc.key.frame); - if prev == Some(loc.key.frame - 1) && self.read_ahead.load(Ordering::Relaxed) { - let next_t = t + footage.frame_rate.frame_duration(); - let mut next = Self::locate(footage, next_t, float); - next.key.size = loc.key.size; - if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) { - self.prefetch(footage, next_t, size, float); - } - } + self.prefetch_next(&mut c, &loc, footage, t, size, float); } + // (Each exit notes the files the frame came from, see `crate::reads`; a cached frame + // notes those it was decoded from, without touching them.) loop { - if let Some(img) = c.lru.get(&loc.key) { + if let Some((img, files)) = c.lru.get(&loc.key) { self.hits.fetch_add(1, Ordering::Relaxed); + drop(c); + reads::note_all(&files); return Ok(img); } if !c.inflight.contains(&loc.key) { @@ -808,7 +840,9 @@ impl Inner { if rayon::current_thread_index().is_some() { self.misses.fetch_add(1, Ordering::Relaxed); drop(c); - return Ok(Arc::new(self.decode(&loc, footage)?)); + let (img, files) = reads::captured(|| self.decode(&loc, footage)); + reads::note_all(&files); + return Ok(Arc::new(img?)); } c = self.done.wait(c).unwrap_or_else(std::sync::PoisonError::into_inner); } @@ -816,11 +850,26 @@ impl Inner { c.inflight.insert(loc.key.clone()); drop(c); let _guard = Inflight { inner: self, key: loc.key.clone() }; - let img = Arc::new(self.decode(&loc, footage)?); - lock(&self.cache).lru.insert(loc.key, img.clone(), self.budget()); + let (img, files) = reads::captured(|| self.decode(&loc, footage)); + reads::note_all(&files); + let img = Arc::new(img?); + lock(&self.cache).lru.insert(loc.key, img.clone(), Arc::new(files), self.budget()); Ok(img) } + /// Sequential playback of a movie (`loc`, at `t`): read the frame after it ahead. + fn prefetch_next(self: &Arc, c: &mut CacheState, loc: &Loc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) { + let prev = c.last.insert(loc.key.path.clone(), loc.key.frame); + if prev == Some(loc.key.frame - 1) && self.read_ahead.load(Ordering::Relaxed) { + let next_t = t + footage.frame_rate.frame_duration(); + let mut next = Self::locate(footage, next_t, float); + next.key.size = loc.key.size; + if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) { + self.prefetch(footage, next_t, size, float); + } + } + } + #[cfg(not(target_arch = "wasm32"))] fn prefetch(self: &Arc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) { let (me, f) = (self.clone(), footage.clone()); @@ -862,7 +911,9 @@ impl Inner { if &**path == PLACEHOLDER { return Ok(colour_bars(footage.width, footage.height)); } - let bytes = self.read(path)?; + let (bytes, file) = self.read_file(path); + reads::note(file.clone()); + let bytes = bytes?; if let Some(img) = crate::dpx::decode(path, &bytes)? { return Ok(dynamic_to_image(&img, op)); } @@ -880,7 +931,7 @@ impl Inner { let shared = lock(&self.aux_footage).contains(&footage.path); if shared && path.to_ascii_lowercase().ends_with(".exr") - && let Some(img) = crate::exr_channels::cached_picture(path, bytes.clone(), op) + && let Some(img) = crate::exr_channels::cached_picture(path, bytes.clone(), &file, op) { return Ok(img); } @@ -889,7 +940,7 @@ impl Inner { match crate::probe::load_oriented(&bytes, crate::still_format(path, &bytes)) { Ok(img) => Ok(dynamic_to_image(&img, op)), // A multi-layer OpenEXR file without an unnamed RGB layer: its colour layer. - Err(e) => crate::exr_channels::layered_picture(path, bytes, op, shared) + Err(e) => crate::exr_channels::layered_picture(path, bytes, &file, op, shared) .map_err(|why| MediaError::Decode(format!("{path}: {}", why.unwrap_or_else(|| e.to_string())))), } } @@ -957,6 +1008,13 @@ impl FootageSource for MediaPool { fn cancellable(&self, cancel: &Arc, f: &mut dyn FnMut()) { filmcraft_media::cancel::with_cancel(cancel, f) } + /// Every read of a file notes it (see [`crate::reads`]): a frame's image file or sequence + /// frame, a movie, a model and the files it names, an EXR's channels, a movie's audio. A + /// frame (or other entry) served from memory notes the files it was made of, as they were + /// when read, without reading them again. A missing sequence frame (colour bars) reads none. + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + reads::recording(reads, f) + } fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { self.frame_sized(item, footage, t, None, FloatCurve::Srgb) } @@ -1207,13 +1265,13 @@ mod tests { let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0) }; let budget = 3 * (4096 + 64); for i in 0..10 { - c.insert(k(i), img(), budget); + c.insert(k(i), img(), Arc::default(), budget); } assert_eq!(c.map.len(), 3); assert!(c.get(&k(9)).is_some() && c.get(&k(6)).is_none()); // touching 7 makes 8 the oldest c.get(&k(7)); - c.insert(k(10), img(), budget); + c.insert(k(10), img(), Arc::default(), budget); assert!(c.get(&k(7)).is_some() && c.get(&k(8)).is_none()); assert_eq!(c.spare.len(), MAX_SPARE); assert_eq!(c.take_spare(256).len(), 256); diff --git a/crates/media/src/reads.rs b/crates/media/src/reads.rs new file mode 100644 index 000000000..29b2fafac --- /dev/null +++ b/crates/media/src/reads.rs @@ -0,0 +1,117 @@ +//! Which files the [`MediaPool`](crate::MediaPool) reads for a render +//! ([`FootageSource::recording`](effectcraft_render::FootageSource::recording)). +//! +//! Every read of a file notes it, with the identity it had when read, in the innermost scope open +//! on this thread. The pool's caches (decoded frames, opened movies, GIFs, models, EXR channels) +//! keep what their entries were made of and note it again on each hit, so a frame served from +//! memory reports its file without touching the disk. +//! +//! The scopes are per thread: a read noted while a render's scope is open on the thread belongs +//! to that render. A thread waiting inside a decode can run another job meanwhile (rayon); that +//! job's reads go to its own scope when it opens one, and otherwise to the scope below it, which +//! then lists a file more than it read (never fewer). + +use std::cell::RefCell; + +use effectcraft_render::reads::{ReadFile, ReadFiles, ReadLog}; + +/// Scopes nested deeper than this are not opened (a thread that keeps taking jobs while it waits +/// cannot pile them up without bound): their reads go to the scope below, and they come back +/// incomplete. +const MAX_DEPTH: usize = 64; + +thread_local! { + /// The open scopes on this thread, innermost last, each with the files noted in it. + static SCOPES: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Note `file` in the innermost open scope on this thread (nothing when none is open). +pub(crate) fn note(file: ReadFile) { + let _ = SCOPES.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(top) = s.last_mut() + { + top.add(file); + } + }); +} + +/// Note every file of `files` in the innermost open scope on this thread. +pub(crate) fn note_all(files: &ReadFiles) { + if files.is_empty() && files.is_complete() { + return; + } + let _ = SCOPES.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(top) = s.last_mut() + { + top.extend(files); + } + }); +} + +/// Closes the scope it opened, also when what runs inside panics: its files go to `out`. +struct Scope<'a> { + out: Out<'a>, + opened: bool, +} + +enum Out<'a> { + /// A render's log ([`recording`]). + Log(&'a ReadLog), + /// The caller's ([`captured`]). + Files(&'a mut ReadFiles), +} + +impl Scope<'_> { + fn open(out: Out<'_>) -> Scope<'_> { + let opened = SCOPES + .try_with(|s| match s.try_borrow_mut() { + Ok(mut s) if s.len() < MAX_DEPTH => { + s.push(ReadFiles::default()); + true + } + _ => false, + }) + .unwrap_or(false); + Scope { out, opened } + } +} + +impl Drop for Scope<'_> { + fn drop(&mut self) { + let files = if self.opened { SCOPES.try_with(|s| s.try_borrow_mut().ok().and_then(|mut s| s.pop())).ok().flatten() } else { None }; + // A scope that could not open saw nothing: what it made can't name its files. + let files = files.unwrap_or_else(|| { + let mut f = ReadFiles::default(); + f.mark_incomplete(); + f + }); + match &mut self.out { + Out::Log(log) => log.note_all(&files), + Out::Files(out) => out.extend(&files), + } + } +} + +/// Run `f` with the files it reads on this thread noted in `log` +/// ([`FootageSource::recording`](effectcraft_render::FootageSource::recording)). +pub(crate) fn recording(log: &ReadLog, f: &mut dyn FnMut()) { + let _scope = Scope::open(Out::Log(log)); + f(); +} + +/// Run `f` and return what it returns with the files it read on this thread (to keep with a +/// cache entry made of them). They are not noted in the enclosing scope: the caller notes them, +/// as it does on each later hit of the entry. +pub(crate) fn captured(f: impl FnOnce() -> T) -> (T, ReadFiles) { + let mut files = ReadFiles::default(); + let out = { + let _scope = Scope::open(Out::Files(&mut files)); + f() + }; + (out, files) +} + +#[cfg(test)] +mod tests; diff --git a/crates/media/src/reads/tests.rs b/crates/media/src/reads/tests.rs new file mode 100644 index 000000000..f9079820f --- /dev/null +++ b/crates/media/src/reads/tests.rs @@ -0,0 +1,184 @@ +//! The files a render reads, as the media pool reports them (#3184): exactly the files the frame +//! was made of, also when its pixels come from memory. + +use std::path::{Path, PathBuf}; + +use effectcraft_color::Label; +use effectcraft_project::build::{self, Ids}; +use effectcraft_project::{Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerSource, Project, Solid, Value}; +use effectcraft_render::reads::{FileStamp, ReadFiles, ReadLog}; +use effectcraft_render::{LayerCache, RenderOpts, Renderer}; +use effectcraft_time::FrameRate; + +use crate::MediaPool; + +const RATE: FrameRate = FrameRate::FPS_30; +const SIZE: (u32, u32) = (16, 8); + +/// A fresh folder for test `name` (on the build drive, not the system temp folder). +fn folder(name: &str) -> PathBuf { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("../../target/test-reads-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A PNG at `path`, a flat grey of `level`. +fn png(path: &Path, level: u8) -> String { + image::RgbaImage::from_pixel(SIZE.0, SIZE.1, image::Rgba([level, level, level, 255])).save(path).unwrap(); + path.to_string_lossy().to_string() +} + +/// An image sequence of `n` PNG frames in `dir`. +fn sequence(dir: &Path, n: usize) -> Footage { + let files: Vec = (0..n).map(|i| png(&dir.join(format!("seq_{i:04}.png")), 20 + i as u8 * 10)).collect(); + let mut f = Footage { kind: FootageKind::Sequence, sequence: files, frame_rate: RATE, ..crate::probe(dir.join("seq_0000.png")).unwrap() }; + f.sync_sequence_duration(); + f +} + +/// A still footage item of `path`. +fn still(path: &Path, level: u8) -> Footage { + png(path, level); + crate::probe(path).unwrap() +} + +fn comp() -> Comp { + Comp::new(SIZE.0, SIZE.1, RATE, RATE.tick_of(10)) +} + +fn footage_layer(p: &mut Project, comp: &Comp, name: &str, f: Footage) -> Layer { + let item = p.add_item(name, Label::Aqua, None, ItemKind::Footage(f)); + build::layer(p, comp, name, LayerSource::Footage { item }, SIZE, Some(comp.duration)) +} + +fn add_comp(p: &mut Project, name: &str, mut comp: Comp, layers: Vec) -> ItemId { + comp.layers = layers.into(); + p.add_item(name, Label::Sandstone, None, ItemKind::Comp(comp.into())) +} + +/// Render frame `frame` of `comp` with `pool` and `cache`: the picture's top-left pixel and the +/// files the render reports. +fn render(p: &Project, pool: &MediaPool, cache: &LayerCache, comp: ItemId, frame: i64) -> ([f32; 4], ReadFiles) { + let log = ReadLog::new(); + let mut r = Renderer::new(p, pool, RenderOpts::default()); + r.cache = Some(cache); + r.reads = Some(&log); + let img = r.comp_frame(comp, RATE.tick_of(frame)); + (img.get(0, 0), log.into_files()) +} + +fn paths(files: &ReadFiles) -> Vec { + files.files().iter().map(|f| f.path.to_string()).collect() +} + +/// Every listed file has the identity it has on disk now. +fn assert_stamps_match_disk(files: &ReadFiles) { + for f in files.files() { + assert_eq!(Some(f.stamp), FileStamp::native(&f.path), "{}", f.path); + } +} + +/// (a) One frame of a comp with an image-sequence layer reads that frame's file and nothing else +/// of the sequence; a large sequence in the project that no layer uses adds nothing, not even a +/// look at its files. +#[test] +fn a_sequence_frame_reports_only_its_own_file() { + let dir = folder("sequence"); + let unused_dir = dir.join("unused"); + let mut p = Project::default(); + let c = comp(); + let seq = sequence(&dir, 5); + let (frame_2, frame_4) = (seq.sequence[2].clone(), seq.sequence[4].clone()); + let layer = footage_layer(&mut p, &c, "Seq", seq); + // 5000 frames nobody shows (they don't even exist). + let unused = Footage { + kind: FootageKind::Sequence, + sequence: (0..5000).map(|i| unused_dir.join(format!("big_{i:05}.exr")).to_string_lossy().to_string()).collect(), + frame_rate: RATE, + width: SIZE.0, + height: SIZE.1, + has_video: true, + ..Default::default() + }; + p.add_item("Unused", Label::Aqua, None, ItemKind::Footage(unused)); + let cid = add_comp(&mut p, "C", c, vec![layer]); + let (pool, cache) = (MediaPool::new(), LayerCache::default()); + let opened = crate::opens_under(&dir); + let (px, files) = render(&p, &pool, &cache, cid, 2); + assert!((px[0] - 40.0 / 255.0).abs() < 0.01, "frame 2 shows: {px:?}"); + assert_eq!(paths(&files), [frame_2]); + assert!(files.is_complete()); + assert_stamps_match_disk(&files); + assert_eq!(crate::opens_under(&dir) - opened, 1, "one file opened: the frame's"); + assert_eq!(crate::opens_under(&unused_dir), 0, "the unused sequence was not looked at"); + // Another frame reads its own file. + let (_, files) = render(&p, &pool, &cache, cid, 4); + assert_eq!(paths(&files), [frame_4]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (b) A precomp reports the files of what it draws, and an effect that reads another layer +/// reports that layer's files (the layer itself is hidden: its pixels come only through the +/// effect). +#[test] +fn precomps_and_layers_read_by_effects_report_their_files() { + let dir = folder("nested"); + let mut p = Project::default(); + let c = comp(); + let seq = sequence(&dir, 4); + let nested_frame = seq.sequence[3].clone(); + let inner_layer = footage_layer(&mut p, &c, "Seq", seq); + let inner = add_comp(&mut p, "Inner", c.clone(), vec![inner_layer]); + let pre = build::layer(&mut p, &c, "Inner", LayerSource::Comp { item: inner }, SIZE, Some(c.duration)); + let matte_path = dir.join("matte.png"); + let mut matte = footage_layer(&mut p, &c, "Matte", still(&matte_path, 255)); + matte.switches.video = false; + let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: SIZE.0, height: SIZE.1, pixel_aspect: 1.0 })); + let mut solid = build::layer(&mut p, &c, "S", LayerSource::Solid { item: sid }, SIZE, Some(c.duration)); + let spec = effectcraft_effects::find("ec.channel.setmatte").unwrap(); + let mut next = p.next_id; + let mut fx = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [SIZE.0 as f64, SIZE.1 as f64]); + p.next_id = next; + fx.prop_mut("takeMatteFromLayer").unwrap().value = Value::Layer(Some(matte.id.0)); + solid.props.sub_mut("effects").unwrap().children.push(fx.into()); + let cid = add_comp(&mut p, "Outer", c, vec![solid, matte, pre]); + let (pool, cache) = (MediaPool::new(), LayerCache::default()); + let (_, files) = render(&p, &pool, &cache, cid, 3); + let mut want = vec![matte_path.to_string_lossy().to_string(), nested_frame]; + want.sort(); + assert_eq!(paths(&files), want); + assert!(files.is_complete()); + assert_stamps_match_disk(&files); + let _ = std::fs::remove_dir_all(&dir); +} + +/// (c) A frame rendered again comes from memory (the sequence frame from the media pool, the +/// still layer from the layer cache) and reports the same files, with the identities they had +/// when read, without opening anything: here the files are even gone by then. +#[test] +fn a_frame_served_from_memory_reports_its_files_without_touching_them() { + let dir = folder("memory"); + let mut p = Project::default(); + let c = comp(); + // The sequence at half opacity over the still: both show. + let mut seq = footage_layer(&mut p, &c, "Seq", sequence(&dir, 3)); + seq.props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(50.0); + let plate = footage_layer(&mut p, &c, "Plate", still(&dir.join("plate.png"), 128)); + let cid = add_comp(&mut p, "C", c, vec![seq, plate]); + let (pool, cache) = (MediaPool::new(), LayerCache::default()); + let (px, first) = render(&p, &pool, &cache, cid, 1); + assert_eq!(first.len(), 2, "{:?}", paths(&first)); + assert_stamps_match_disk(&first); + std::fs::remove_dir_all(&dir).unwrap(); + let opened = crate::opens_under(&dir); + let hits = cache.stats().hits; + let (again_px, again) = render(&p, &pool, &cache, cid, 1); + assert_eq!(again_px, px, "the same picture"); + assert_eq!(again, first, "the same files, as they were when read"); + assert!(cache.stats().hits > hits, "the still layer came from the layer cache"); + // The media pool alone (a new layer cache) reports them too. + let (_, from_pool) = render(&p, &pool, &LayerCache::default(), cid, 1); + assert_eq!(from_pool, first); + assert_eq!(crate::opens_under(&dir), opened, "nothing was opened on disk"); +} diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 80db21fc4..99b1cb774 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -9,6 +9,7 @@ use std::path::Path; +use effectcraft_render::reads::FileStamp; use filmcraft_media::SharedSource; use crate::Result; @@ -19,17 +20,21 @@ use crate::Result; pub(crate) struct FileReader { file: std::fs::File, len: u64, + /// The file's identity when it was opened. + stamp: FileStamp, } #[cfg(any(unix, windows))] impl FileReader { pub(crate) fn open(path: &Path) -> std::io::Result { + #[cfg(test)] + crate::count_open(path); let file = std::fs::File::open(path)?; let m = file.metadata()?; if !m.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - Ok(Self { file, len: m.len() }) + Ok(Self { file, len: m.len(), stamp: FileStamp::of_metadata(&m) }) } } @@ -72,16 +77,18 @@ fn name_of(path: &Path) -> String { /// Open a movie/audio file for the media pool, reading only what its container needs; files the /// reader openers don't handle are read whole and opened from memory, exactly as before. `None` /// when the file can't be opened in place (the caller reads it whole, which reports the error). +/// With the file's identity as opened. #[cfg(any(unix, windows))] -pub(crate) fn open_source(path: &Path) -> Option> { +pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStamp)> { let reader = FileReader::open(path).ok()?; + let stamp = reader.stamp; let reader: filmcraft_media::SharedReader = std::sync::Arc::new(reader); let opened = filmcraft_media::reader::open_reader(&name_of(path), reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers()); - Some(opened.map_err(Into::into)) + Some((opened.map_err(Into::into), stamp)) } #[cfg(not(any(unix, windows)))] -pub(crate) fn open_source(_path: &Path) -> Option> { +pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStamp)> { None } diff --git a/crates/render/src/accel.rs b/crates/render/src/accel.rs index f545a62ee..eecf05580 100644 --- a/crates/render/src/accel.rs +++ b/crates/render/src/accel.rs @@ -224,7 +224,7 @@ impl<'a> Renderer<'a> { LayerSource::Footage { item } => { let item = ctx.media_item(layer, *item); let ItemKind::Footage(f) = &self.project.item(item)?.kind else { return None }; - let a = self.footage.aux(item, f, ctx.source_time(layer))?; + let a = self.read(|| self.footage.aux(item, f, ctx.source_time(layer)))?; // Aux pixels per layer pixel (the layer is the footage at its nominal size). The // planes are only copied when that changes the scale. let scale = a.width as f64 / f.width as f64; @@ -349,20 +349,16 @@ impl<'a> Renderer<'a> { pub fn adjustment_footprint(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { // Cached, so an accelerator sees the same buffer (and uploads it once) every frame. let key = self.cache.and_then(|_| cache::footprint_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer))); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + if let Some((b, _)) = self.cached(key) { return Some(b); } - let mut foot = self.source(ctx, layer)?; - let _ = masks::apply(ctx, layer, &mut foot, self.mask_blur(ctx, layer)); - let foot = Arc::new(foot); + let (foot, files) = self.recorded(key, |r| { + let mut foot = r.source(ctx, layer)?; + let _ = masks::apply(ctx, layer, &mut foot, r.mask_blur(ctx, layer)); + Some(foot) + }); // The buffer the cache keeps (another worker's, if it kept one first). - let foot = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, foot), - _ => foot, - }; - Some(foot) + Some(self.keep(key, Arc::new(foot?), &files)) } /// Draw one 2D layer into `canvas` on the CPU (any kind: adjustment, wireframe, styled…). diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index cf1a84e82..79b948b89 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -25,6 +25,7 @@ use effectcraft_effects::Buf; use effectcraft_project::{FootageKind, ItemKind, Layer, LayerSource, Node, PropGroup}; use crate::eval::EvalCtx; +use crate::reads::ReadFiles; mod dependencies; @@ -43,6 +44,8 @@ pub struct LayerCache { struct Entry { buf: Arc, + /// The source files the buffer was made of (see [`crate::reads`]). + files: Arc, bytes: usize, last_use: u64, } @@ -147,16 +150,19 @@ impl LayerCache { Some((st.clone(), salted(*salt))) } - pub fn get(&self, key: u64) -> Option> { + /// The buffer kept under `key` and the source files it was made of (see [`crate::reads`]). + /// A buffer from the disk cache or another store doesn't know its files: its list is + /// incomplete. + pub fn get(&self, key: u64) -> Option<(Arc, Arc)> { let mut g = self.inner.lock().ok()?; g.clock += 1; let now = g.clock; match g.map.get_mut(&key) { Some(e) => { e.last_use = now; - let b = e.buf.clone(); + let found = (e.buf.clone(), e.files.clone()); g.hits += 1; - Some(b) + Some(found) } None => { g.misses += 1; @@ -168,7 +174,10 @@ impl LayerCache { // Disk cache: a hit comes back into memory. let (dc, dk) = self.disk_key(key)?; let buf = dc.get_layer(dk)?; - Some(self.insert_mem(key, buf)) + let mut files = ReadFiles::default(); + files.mark_incomplete(); + let files = Arc::new(files); + Some((self.insert_mem(key, buf, files.clone()), files)) } } } @@ -178,8 +187,9 @@ impl LayerCache { /// together each rendered every layer; sharing the first buffer, the GPU compositor uploads /// and packs it once instead of once per worker, which ran it out of memory). Renders don't /// wait for each other: on the frame workers' shared thread pool a wait can end up under - /// the very work it waits for. - pub fn insert(&self, key: u64, buf: Arc) -> Arc { + /// the very work it waits for. `files`: the source files `buf` was made of (see + /// [`crate::reads`]). + pub fn insert(&self, key: u64, buf: Arc, files: Arc) -> Arc { if self.gated() { return buf; } @@ -193,12 +203,12 @@ impl LayerCache { dc.put_layer(dk, &buf); } } - self.insert_mem(key, buf) + self.insert_mem(key, buf, files) } /// See [`LayerCache::insert`]: the buffer kept under `key` (`buf`, unless one was kept first /// or `buf` is too large to keep). - fn insert_mem(&self, key: u64, buf: Arc) -> Arc { + fn insert_mem(&self, key: u64, buf: Arc, files: Arc) -> Arc { let bytes = buf.img.data.len() * std::mem::size_of::(); let Ok(mut g) = self.inner.lock() else { return buf }; if bytes > g.budget / 4 { @@ -210,7 +220,7 @@ impl LayerCache { e.last_use = now; return e.buf.clone(); } - g.map.insert(key, Entry { buf: buf.clone(), bytes, last_use: now }); + g.map.insert(key, Entry { buf: buf.clone(), files, bytes, last_use: now }); g.bytes += bytes; if g.bytes > g.budget { // Evict least-recently used entries down to 3/4 of the budget. @@ -786,8 +796,8 @@ mod shared_insert_tests { let cache = LayerCache::default(); let buf = || Arc::new(Buf { img: Image::new(4, 4), offset: [0.0; 2], scale: 1.0 }); let (a, b) = (buf(), buf()); - assert!(Arc::ptr_eq(&cache.insert(3, a.clone()), &a)); - assert!(Arc::ptr_eq(&cache.insert(3, b), &a), "the later render gets the first buffer"); - assert!(Arc::ptr_eq(&cache.get(3).unwrap(), &a)); + assert!(Arc::ptr_eq(&cache.insert(3, a.clone(), Default::default()), &a)); + assert!(Arc::ptr_eq(&cache.insert(3, b, Default::default()), &a), "the later render gets the first buffer"); + assert!(Arc::ptr_eq(&cache.get(3).unwrap().0, &a)); } } diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 427198ad2..03832643b 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -1055,18 +1055,17 @@ fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { /// Size and content hash of a path that has no native metadata (the browser file table). pub type VirtualFileId<'a> = &'a (dyn Fn(&str) -> Option<(u64, u64)> + Send + Sync); -/// A file's size and modification time (so edited footage gets new keys). When the path has no -/// native metadata, `virtual_id` supplies a durable size and content hash instead. +/// A file's size and modification time (so edited footage gets new keys): the identity a render +/// records for the files it reads ([`crate::reads::FileStamp`]). When the path has no native +/// metadata, `virtual_id` supplies a durable size and content hash instead. fn file_stamp(h: &mut Hash128, path: &str, virtual_id: Option>) { if path.is_empty() { return; } - if let Ok(md) = std::fs::metadata(path) { - h.write_u64(md.len()); - if let Ok(t) = md.modified() - && let Ok(d) = t.duration_since(std::time::UNIX_EPOCH) - { - h.write_u64(d.as_nanos() as u64); + if let Some(crate::reads::FileStamp::Native { len, modified }) = crate::reads::FileStamp::native(path) { + h.write_u64(len); + if let Some(t) = modified { + h.write_u64(t); } return; } diff --git a/crates/render/src/footage.rs b/crates/render/src/footage.rs index 4c90967d3..04957b34e 100644 --- a/crates/render/src/footage.rs +++ b/crates/render/src/footage.rs @@ -1,4 +1,5 @@ use super::{Arc, AtomicBool, Footage, Image, ItemId, ItemKind, Ordering, Tick}; +use crate::reads::ReadLog; /// How a [`FootageSource`] hands over float footage (OpenEXR, float TIFF), whose values are /// linear light: encoded with a curve, as the compositor takes footage, or as stored. Other @@ -92,6 +93,15 @@ pub trait FootageSource: Send + Sync { fn called_off(&self) -> bool { false } + /// Run `f`, which reads from this source on this thread, noting in `reads` every source file + /// those reads use, with its identity as read (see [`crate::reads`]): the file a frame was + /// decoded from, also when it comes from the source's own memory cache (without reading the + /// file again). Sources that can't tell which files they read keep the default, which marks + /// `reads` incomplete. + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + reads.mark_incomplete(); + f() + } /// Why `footage` shows no picture although its file is there: a read of it failed because /// no decoder handles its codec, profile, chroma format or bit depth, or the stream is damaged /// (e.g. "H.264 (High 4:2:2) isn't supported by the built-in decoder: ..."). `None` while it @@ -194,6 +204,9 @@ impl FootageSource for CancellableFootage<'_> { fn called_off(&self) -> bool { self.cancel.load(Ordering::Relaxed) || self.inner.called_off() } + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + self.inner.recording(reads, f) + } fn problem(&self, footage: &Footage) -> Option { self.inner.problem(footage) } @@ -214,4 +227,8 @@ impl FootageSource for NoFootage { fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { None } + /// Reads no files. + fn recording(&self, _: &ReadLog, f: &mut dyn FnMut()) { + f() + } } diff --git a/crates/render/src/fx_host.rs b/crates/render/src/fx_host.rs index 65bafe002..9b1700df8 100644 --- a/crates/render/src/fx_host.rs +++ b/crates/render/src/fx_host.rs @@ -104,7 +104,7 @@ impl EffectHost for FxHost<'_, '_, '_> { return None; } let st = other.layer_time(Tick::from_seconds_f64(start)); - self.r.footage.audio(item, f, st, frames, rate) + self.r.read(|| self.r.footage.audio(item, f, st, frames, rate)) } fn self_at(&self, layer_time: f64, effects: usize) -> Option { diff --git a/crates/render/src/layers.rs b/crates/render/src/layers.rs index d105c6f13..b551d1c1b 100644 --- a/crates/render/src/layers.rs +++ b/crates/render/src/layers.rs @@ -37,18 +37,17 @@ impl Shutter { impl<'a> Renderer<'a> { /// The layer with its styles: exterior passes and body (cached per pass). pub(crate) fn styled(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option { - let (content, ckey) = self.content_buf_timed(ctx, layer, timing.as_deref_mut())?; + let (content, ckey, files) = self.content_buf_timed(ctx, layer, timing.as_deref_mut())?; if !styles::active(ctx, layer) { - return Some(StyledLayer { passes: vec![], body: content.clone(), content, key: ckey, ckey, plain: true }); + return Some(StyledLayer { passes: vec![], body: content.clone(), content, key: ckey, ckey, plain: true, files }); } let modes = styles::pass_modes(ctx, layer); let key = ckey.map(|k| cache::styles_key(ctx, layer, k)); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(body) = c.get(k) - { - let passes: Option> = modes.iter().enumerate().map(|(i, m)| c.get(cache::derive(k, i as u64 + 1)).map(|b| (b, *m))).collect(); + if let Some((body, _)) = self.cached(key) { + let passes: Option> = + modes.iter().enumerate().map(|(i, m)| self.cached(key.map(|k| cache::derive(k, i as u64 + 1))).map(|(b, _)| (b, *m))).collect(); if let Some(passes) = passes { - return Some(StyledLayer { passes, body, content, key, ckey, plain: false }); + return Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }); } } let t0 = web_time::Instant::now(); @@ -59,16 +58,12 @@ impl<'a> Renderer<'a> { t.cached = false; t.effects.push(("layerStyles".into(), t0.elapsed().as_secs_f64() * 1e3)); } - let mut body = Arc::new(st.body); - let mut passes: Vec<_> = st.passes.into_iter().map(|(b, m)| (Arc::new(b), m)).collect(); - // The buffers the cache keeps (another worker's, if it kept them first). - if let (Some(c), Some(k)) = (self.cache_to_keep(), key) { - body = c.insert(k, body); - for (i, (b, _)) in passes.iter_mut().enumerate() { - *b = c.insert(cache::derive(k, i as u64 + 1), b.clone()); - } - } - Some(StyledLayer { passes, body, content, key, ckey, plain: false }) + // The buffers the cache keeps (another worker's, if it kept them first), made of the + // content's files. + let body = self.keep(key, Arc::new(st.body), &files); + let passes: Vec<_> = + st.passes.into_iter().enumerate().map(|(i, (b, m))| (self.keep(key.map(|k| cache::derive(k, i as u64 + 1)), Arc::new(b), &files), m)).collect(); + Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }) } /// The styled layer's buffers in the blending space. @@ -76,9 +71,10 @@ impl<'a> Renderer<'a> { if self.pipe.to_blend().is_none() { return st; } - let body = self.to_blend(st.body, st.key); - let content = if st.plain { body.clone() } else { self.to_blend(st.content, st.ckey) }; - let passes = st.passes.into_iter().enumerate().map(|(i, (b, m))| (self.to_blend(b, st.key.map(|k| cache::derive(k, i as u64 + 1))), m)).collect(); + let body = self.to_blend(st.body, st.key, &st.files); + let content = if st.plain { body.clone() } else { self.to_blend(st.content, st.ckey, &st.files) }; + let passes = + st.passes.into_iter().enumerate().map(|(i, (b, m))| (self.to_blend(b, st.key.map(|k| cache::derive(k, i as u64 + 1)), &st.files), m)).collect(); StyledLayer { passes, body, content, ..st } } @@ -582,6 +578,8 @@ pub struct StyledLayer { ckey: Option, /// No layer styles: composite `body` the usual way. pub plain: bool, + /// The source files the layer's buffers were made of (see [`crate::reads`]). + pub(crate) files: Arc, } /// Where a layer buffer lands (see [`Renderer::placement`]). diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index dbd948320..e09794de2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -17,6 +17,7 @@ use color::Region; pub mod eval; pub mod masks; pub mod passes; +pub mod reads; pub mod shapes; pub mod styles; pub mod text; @@ -69,6 +70,10 @@ pub struct Renderer<'a> { pub opts: RenderOpts, /// Processed-layer cache shared across frames (see [`cache`]). `None` renders everything. pub cache: Option<&'a LayerCache>, + /// Where the source files this render reads are noted (see [`reads`]): the frame's own, + /// from the footage source and from the buffers the layer cache serves. `None` records + /// nothing for the frame (buffers kept in the layer cache still record theirs). + pub reads: Option<&'a reads::ReadLog>, /// Optional per-layer timing sink (`frame --bench` / perf readouts). pub profile: Option<&'a std::sync::Mutex>>, /// GPU backend used when [`RenderOpts::backend`] asks for it. diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index e84348fdf..3564c17f9 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -3,6 +3,7 @@ use super::footage::{FootageSource, is_vector_footage}; use super::frames::{blend_frames, cineon_frame, content_bounds, field_frame, frame_blend_mode, frame_position, frame_size, interpret_pixels, roi_inside}; use super::fx_host::{FxHost, essential_overrides}; use super::opts::{Collapse3d, LayerTiming, MAX_THROUGH, RenderOpts, Through}; +use super::reads::{ReadFiles, ReadLog}; use super::{ Arc, AutoKey, AutoPick, BlendMode, Buf, Comp, EffectCtx, EffectEnv, EvalCtx, Footage, FootageKind, FrameBlend, FrameRate, GroupKind, Image, ItemId, ItemKind, Layer, LayerCache, LayerSource, Params, Project, Quality, Region, Renderer, Tick, cache, color, masks, shapes, styles, text, three_d, vec2, @@ -108,6 +109,7 @@ impl<'a> Renderer<'a> { expr: None, opts, cache: None, + reads: None, profile: None, accel: None, depth: 0, @@ -129,6 +131,52 @@ impl<'a> Renderer<'a> { self.cache.filter(|_| !self.footage.called_off()) } + /// `read`, a read of this render's footage source, with the files it uses noted in + /// [`Renderer::reads`] (see [`FootageSource::recording`]). + pub(crate) fn read(&self, read: impl FnOnce() -> Option) -> Option { + let Some(log) = self.reads else { return read() }; + let (mut read, mut out) = (Some(read), None); + self.footage.recording(log, &mut || out = read.take().and_then(|f| f())); + out + } + + /// The buffer the layer cache keeps under `key`, with the files it was made of noted in + /// [`Renderer::reads`]. + pub(crate) fn cached(&self, key: Option) -> Option<(Arc, Arc)> { + let (buf, files) = self.cache?.get(key?)?; + if let Some(log) = self.reads { + log.note_all(&files); + } + Some((buf, files)) + } + + /// Keep `buf`, made of `files`, under `key` (see [`Renderer::recorded`]): the buffer the cache + /// keeps (another worker's, if it kept one first), or `buf` when nothing is kept. + pub(crate) fn keep(&self, key: Option, buf: Arc, files: &Arc) -> Arc { + match (self.cache_to_keep(), key) { + (Some(c), Some(k)) => c.insert(k, buf, files.clone()), + _ => buf, + } + } + + /// Run `make`, which makes a buffer to keep under `key` in the layer cache, on this renderer + /// with its reads noted apart: what `make` returns and the files it read (from the footage + /// source, or the files of cached buffers it used), which go to [`Renderer::reads`] too. A + /// cached buffer then reports the files it was made of whichever render uses it. Without a + /// cache or a key, `make` runs on this renderer as it is (no files: nothing is kept). + pub(crate) fn recorded(&self, key: Option, make: impl FnOnce(&Renderer<'_>) -> T) -> (T, Arc) { + if key.is_none() || self.cache.is_none() { + return (make(self), Arc::default()); + } + let log = ReadLog::new(); + let out = make(&Renderer { reads: Some(&log), ..*self }); + let files = log.into_files(); + if let Some(own) = self.reads { + own.note_all(&files); + } + (out, Arc::new(files)) + } + /// A layer's Quality switch, limited by the precomp layers above it when /// [`RenderOpts::nested_switches`] is on. pub fn quality(&self, layer: &Layer) -> Quality { @@ -760,7 +808,7 @@ impl<'a> Renderer<'a> { // Continuously rasterised vector footage: drawn at the on-screen scale. if layer.switches.collapse && is_vector_footage(f) { let k = self.raster_scale(ctx, layer); - if let Some(img) = self.footage.vector_frame(item, f, k) { + if let Some(img) = self.read(|| self.footage.vector_frame(item, f, k)) { let mut buf = Buf { img: (*img).clone(), offset: [0.0; 2], scale: k }; if let Some(c) = self.pipe.media_in(f) { color::convert(&mut buf.img, &c); @@ -831,7 +879,7 @@ impl<'a> Renderer<'a> { if f.fields != effectcraft_project::FieldOrder::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) { let field_rate = FrameRate::new(f.frame_rate.num * 2, f.frame_rate.den); let i = field_rate.frame_at(t).max(0); - let img = cineon_frame(self.footage.frame_with(item, f, f.frame_rate.tick_of(i / 2), None, self.pipe.float_curve(f))?, f); + let img = cineon_frame(self.read(|| self.footage.frame_with(item, f, f.frame_rate.tick_of(i / 2), None, self.pipe.float_curve(f)))?, f); let dominant_upper = f.fields == effectcraft_project::FieldOrder::UpperFirst; // Upper field = even lines (0, 2, …). let parity = if (i % 2 == 0) == dominant_upper { 0 } else { 1 }; @@ -865,24 +913,22 @@ impl<'a> Renderer<'a> { } h.finish() }); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + if let Some((b, _)) = self.cached(key) { return Some(Arc::new(b.img.clone())); } // Log scans are converted before they blend: the conversion is not linear. - let a = self.footage.frame_with(item, f, f.frame_rate.tick_of(i), None, float).map(|a| cineon_frame(a, f)); - let b = self.footage.frame_with(item, f, f.frame_rate.tick_of(i + 1), None, float).map(|b| cineon_frame(b, f)); + let ((a, b), files) = self.recorded(key, |r| { + let frame = |i| r.read(|| r.footage.frame_with(item, f, f.frame_rate.tick_of(i), None, float)).map(|a| cineon_frame(a, f)); + (frame(i), frame(i + 1)) + }); if let (Some(a), Some(b)) = (a, b) { let img = blend_frames(mode, &a, &b, w as f32); - if let (Some(c), Some(k)) = (self.cache_to_keep(), key) { - c.insert(k, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 })); - } + self.keep(key, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }), &files); return Some(Arc::new(img)); } } } - self.footage.frame_with(item, f, t, size, float).map(|img| cineon_frame(img, f)) + self.read(|| self.footage.frame_with(item, f, t, size, float)).map(|img| cineon_frame(img, f)) } /// Source → masks, clamped/quantised to the project depth. @@ -902,52 +948,40 @@ impl<'a> Renderer<'a> { /// Fully processed layer buffer (source → masks → effects → layer styles, flattened). /// Served from the layer cache when the layer's content key matches. pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { - self.layer_buf_keyed(ctx, layer).map(|(b, _)| b) + self.layer_buf_keyed(ctx, layer).map(|(b, _, _)| b) } /// [`Self::layer_buf`] in the blending space (linear with Blend Colors Using 1.0 Gamma). pub fn blend_layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { - let (b, k) = self.layer_buf_keyed(ctx, layer)?; - Some(self.to_blend(b, k)) + let (b, k, files) = self.layer_buf_keyed(ctx, layer)?; + Some(self.to_blend(b, k, &files)) } - /// A buffer converted to the blending space (cached under a key derived from `key`). - pub(crate) fn to_blend(&self, b: Arc, key: Option) -> Arc { + /// A buffer converted to the blending space (cached under a key derived from `key`, with + /// `files`, the source files `b` was made of). + pub(crate) fn to_blend(&self, b: Arc, key: Option, files: &Arc) -> Arc { let Some(c) = self.pipe.to_blend() else { return b }; let key = key.map(|k| cache::derive(k, 0x1ea7)); - if let (Some(cache), Some(k)) = (self.cache, key) - && let Some(x) = cache.get(k) - { + if let Some((x, _)) = self.cached(key) { return x; } let mut nb = (*b).clone(); color::convert(&mut nb.img, &c); - let nb = Arc::new(nb); - // The buffer the cache keeps (another worker's, if it kept one first). - match (self.cache_to_keep(), key) { - (Some(cache), Some(k)) => cache.insert(k, nb), - _ => nb, - } + self.keep(key, Arc::new(nb), files) } - fn layer_buf_keyed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Arc, Option)> { + /// The flattened layer buffer, its cache key and the source files it was made of. + fn layer_buf_keyed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Arc, Option, Arc)> { let st = self.styled(ctx, layer, None)?; if st.passes.is_empty() { - return Some((st.body, st.key)); + return Some((st.body, st.key, st.files)); } let key = st.key.map(|k| cache::derive(k, 0xf1a7)); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { - return Some((b, key)); + if let Some((b, files)) = self.cached(key) { + return Some((b, key, files)); } let flat = Arc::new(styles::Styled { passes: st.passes.iter().map(|(b, m)| ((**b).clone(), *m)).collect(), body: (*st.body).clone() }.flatten()); - // The buffer the cache keeps (another worker's, if it kept one first). - let flat = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, flat), - _ => flat, - }; - Some((flat, key)) + Some((self.keep(key, flat, &st.files), key, st.files)) } /// A layer's source pixels at the context time, before masks, effects and the transform @@ -983,28 +1017,29 @@ impl<'a> Renderer<'a> { /// Layer pixels after source → masks → effects (no layer styles). pub fn content_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { - self.content_buf_timed(ctx, layer, None).map(|(b, _)| b) + self.content_buf_timed(ctx, layer, None).map(|(b, _, _)| b) } - pub(crate) fn content_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<(Arc, Option)> { + /// [`Self::content_buf`], its cache key and the source files it was made of. + pub(crate) fn content_buf_timed( + &self, + ctx: &EvalCtx, + layer: &Layer, + mut timing: Option<&mut LayerTiming>, + ) -> Option<(Arc, Option, Arc)> { let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer))); let key = self.content_key(ctx, layer, key); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + if let Some((b, files)) = self.cached(key) { if let Some(t) = timing.as_deref_mut() { t.cached = true; } - return Some((b, key)); + return Some((b, key, files)); } - let buf = self.masked_source(ctx, layer)?; - let buf = Arc::new(self.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects))); - // The buffer the cache keeps (another worker's, if it kept one first). - let buf = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, buf), - _ => buf, - }; - Some((buf, key)) + let (buf, files) = self.recorded(key, |r| { + let buf = r.masked_source(ctx, layer)?; + Some(r.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects))) + }); + Some((self.keep(key, Arc::new(buf?), &files), key, files)) } /// A layer's input at the context time: source → masks → its first `effects` effects @@ -1014,23 +1049,18 @@ impl<'a> Renderer<'a> { pub fn layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option> { let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer), effects)); let key = self.content_key(ctx, layer, key); - if let (Some(c), Some(k)) = (self.cache, key) - && let Some(b) = c.get(k) - { + if let Some((b, _)) = self.cached(key) { return Some(b); } - let mut buf = self.masked_source(ctx, layer)?; - let origin = ctx.effect_bounds(layer).1; - buf.rebase(origin); - if effects > 0 { - buf = self.effect_space_stack(ctx, layer, buf, EffectStack { adjustment: false, limit: effects, origin }, None); - } - let buf = Arc::new(buf); - // The buffer the cache keeps (another worker's, if it kept one first). - let buf = match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, buf), - _ => buf, - }; - Some(buf) + let (buf, files) = self.recorded(key, |r| { + let mut buf = r.masked_source(ctx, layer)?; + let origin = ctx.effect_bounds(layer).1; + buf.rebase(origin); + if effects > 0 { + buf = r.effect_space_stack(ctx, layer, buf, EffectStack { adjustment: false, limit: effects, origin }, None); + } + Some(buf) + }); + Some(self.keep(key, Arc::new(buf?), &files)) } } diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs new file mode 100644 index 000000000..d5648cca6 --- /dev/null +++ b/crates/render/src/reads.rs @@ -0,0 +1,230 @@ +//! The source files a render read: which footage files its pixels came from, each with its +//! identity (size and modification time) as it was when it was read. +//! +//! A [`FootageSource`](crate::FootageSource) that knows which files it opens notes them while +//! [`FootageSource::recording`](crate::FootageSource::recording) runs; the renderer collects them +//! in a [`ReadLog`] ([`Renderer::reads`](crate::Renderer::reads)). Buffers in the layer cache keep +//! the files they were made of, so a frame served from memory reports the same files as the +//! render that made it, without touching the disk. +//! +//! The list is what a cache entry on disk has to check before it is used: a handful of files per +//! frame, never every file of every footage item. + +use std::sync::{Arc, Mutex, PoisonError}; + +/// The identity of a file as a render read it (see [`file_stamp`](crate::disk_cache) for the +/// same identity in content keys). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum FileStamp { + /// A file on disk: its size in bytes and its modification time (nanoseconds since the Unix + /// epoch; `None` where the file system has none). + Native { len: u64, modified: Option }, + /// Bytes given from memory instead of the file system (the browser's file table): their + /// identity is the size and content hash a + /// [`VirtualFileId`](crate::disk_cache::VirtualFileId) gives for the path. + Virtual, + /// The file could not be read (missing, not a regular file, no permission). What was made + /// without it changes once it can be read again. + Missing, +} + +impl FileStamp { + /// The identity of a file from metadata the caller already has (of an open file). + pub fn of_metadata(md: &std::fs::Metadata) -> FileStamp { + let modified = md.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos() as u64); + FileStamp::Native { len: md.len(), modified } + } + + /// The identity of the file at `path` now: one `metadata` call. `None` when the file system + /// can't describe it (missing, or a path served from memory). + pub fn native(path: &str) -> Option { + std::fs::metadata(path).ok().map(|md| FileStamp::of_metadata(&md)) + } +} + +/// One file a render read. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ReadFile { + pub path: Arc, + pub stamp: FileStamp, +} + +impl ReadFile { + pub fn new(path: impl Into>, stamp: FileStamp) -> ReadFile { + ReadFile { path: path.into(), stamp } + } +} + +/// At most this many files are listed per render or cached buffer; more mark the list +/// incomplete (a comp reading more files than this for one frame is not checked file by file). +pub const MAX_READ_FILES: usize = 4096; + +/// The files a render (or one cached buffer) read, each once, sorted by path. +/// +/// Incomplete when it can't say for sure: a footage source that doesn't tell what it reads, a +/// buffer from a store that doesn't keep its files, more than [`MAX_READ_FILES`] files, or one +/// file read with two identities (it changed during the render). A cache entry whose list is +/// incomplete can't be checked against the files, so it must not outlive the session. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct ReadFiles { + files: Vec, + incomplete: bool, +} + +impl ReadFiles { + /// Note a file read (once per path). + pub fn add(&mut self, file: ReadFile) { + match self.files.binary_search_by(|f| f.path.cmp(&file.path)) { + Ok(i) => { + if self.files.get(i).is_some_and(|f| f.stamp != file.stamp) { + self.incomplete = true; + } + } + Err(i) => { + if self.files.len() >= MAX_READ_FILES { + self.incomplete = true; + } else { + self.files.insert(i, file); + } + } + } + } + + /// Note every file of `other` (and whether it is incomplete). + pub fn extend(&mut self, other: &ReadFiles) { + self.incomplete |= other.incomplete; + for f in &other.files { + self.add(f.clone()); + } + } + + /// Some files read may be missing from the list (see [`ReadFiles`]). + pub fn mark_incomplete(&mut self) { + self.incomplete = true; + } + + /// Whether the list names every file read. + pub fn is_complete(&self) -> bool { + !self.incomplete + } + + /// The files, sorted by path. + pub fn files(&self) -> &[ReadFile] { + &self.files + } + + /// The identity `path` was read with. + pub fn get(&self, path: &str) -> Option { + let i = self.files.binary_search_by(|f| (*f.path).cmp(path)).ok()?; + self.files.get(i).map(|f| f.stamp) + } + + pub fn len(&self) -> usize { + self.files.len() + } + + pub fn is_empty(&self) -> bool { + self.files.is_empty() + } +} + +impl FromIterator for ReadFiles { + fn from_iter>(iter: I) -> Self { + let mut out = ReadFiles::default(); + for f in iter { + out.add(f); + } + out + } +} + +/// Collects the files a render reads, from any thread (the layers of a frame render in +/// parallel). +#[derive(Debug, Default)] +pub struct ReadLog { + files: Mutex, +} + +impl ReadLog { + pub fn new() -> ReadLog { + ReadLog::default() + } + + fn lock(&self) -> std::sync::MutexGuard<'_, ReadFiles> { + self.files.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Note a file read. + pub fn note(&self, file: ReadFile) { + self.lock().add(file); + } + + /// Note every file of `files` (and whether it is incomplete). + pub fn note_all(&self, files: &ReadFiles) { + if files.is_empty() && files.is_complete() { + return; + } + self.lock().extend(files); + } + + /// Some files read can't be listed (see [`ReadFiles`]). + pub fn mark_incomplete(&self) { + self.lock().mark_incomplete(); + } + + /// The files noted so far. + pub fn files(&self) -> ReadFiles { + self.lock().clone() + } + + /// The files noted. + pub fn into_files(self) -> ReadFiles { + self.files.into_inner().unwrap_or_else(PoisonError::into_inner) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(path: &str, len: u64) -> ReadFile { + ReadFile::new(path, FileStamp::Native { len, modified: Some(7) }) + } + + #[test] + fn files_are_listed_once_sorted_by_path() { + let files: ReadFiles = [file("/b", 1), file("/a", 2), file("/b", 1)].into_iter().collect(); + assert_eq!(files.files().iter().map(|f| &*f.path).collect::>(), ["/a", "/b"]); + assert!(files.is_complete()); + assert_eq!(files.get("/a"), Some(FileStamp::Native { len: 2, modified: Some(7) })); + assert_eq!(files.get("/c"), None); + } + + /// A file read twice with different identities changed during the render: the list can't + /// vouch for what was made of it. + #[test] + fn a_file_read_with_two_identities_makes_the_list_incomplete() { + let files: ReadFiles = [file("/a", 1), file("/a", 2)].into_iter().collect(); + assert_eq!(files.len(), 1); + assert!(!files.is_complete()); + } + + #[test] + fn the_list_is_bounded() { + let files: ReadFiles = (0..MAX_READ_FILES + 3).map(|i| file(&format!("/f{i:06}"), 1)).collect(); + assert_eq!(files.len(), MAX_READ_FILES); + assert!(!files.is_complete(), "files past the bound make the list incomplete, never silently short"); + } + + #[test] + fn incompleteness_carries_over() { + let mut part = ReadFiles::default(); + part.mark_incomplete(); + let log = ReadLog::new(); + log.note(file("/a", 1)); + log.note_all(&part); + let all = log.into_files(); + assert_eq!(all.len(), 1); + assert!(!all.is_complete()); + } +} diff --git a/crates/render/src/three_d/adv/scene.rs b/crates/render/src/three_d/adv/scene.rs index 22507069e..b706826de 100644 --- a/crates/render/src/three_d/adv/scene.rs +++ b/crates/render/src/three_d/adv/scene.rs @@ -487,7 +487,7 @@ fn model_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { LayerSource::Model { item } => { let Some(it) = r.project.item(*item) else { return }; let ItemKind::Footage(f) = &it.kind else { return }; - let Some(m) = r.footage.model(*item, f) else { return }; + let Some(m) = r.read(|| r.footage.model(*item, f)) else { return }; let unit = geo.map_or(1.0, |g| ctx.f(layer, g, "unitScale", 1.0)); let clip = geo.map_or(0, |g| ctx.e(layer, g, "animation")) as usize; let clip = clip.checked_sub(1).filter(|c| *c < m.animations.len()); @@ -700,7 +700,7 @@ fn card_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { let world = b.outer * ctx.world_matrix(layer); if crate::text::per_char_3d(ctx, layer) { for (buf, m) in crate::text::per_char_planes(ctx, layer, r.opts.scale) { - let buf = r.to_blend(Arc::new(buf), None); + let buf = r.to_blend(Arc::new(buf), None, &Arc::default()); card(b, &buf, world * m, mat); } return; diff --git a/crates/render/src/three_d/compose.rs b/crates/render/src/three_d/compose.rs index a5a7c170e..361f427c3 100644 --- a/crates/render/src/three_d/compose.rs +++ b/crates/render/src/three_d/compose.rs @@ -205,7 +205,9 @@ pub(crate) fn prepare_all<'a>(r: &Renderer, ctx: &EvalCtx<'_>, layer: &'a Layer, if crate::text::per_char_3d(ctx, layer) { return crate::text::per_char_planes(ctx, layer, r.opts.scale) .into_iter() - .filter_map(|(buf, m)| prepare_with(r, ctx, layer, order, out, in_run, PlaneInput { buf: r.to_blend(Arc::new(buf), None), local: m })) + .filter_map(|(buf, m)| { + prepare_with(r, ctx, layer, order, out, in_run, PlaneInput { buf: r.to_blend(Arc::new(buf), None, &Arc::default()), local: m }) + }) .collect(); } prepare(r, ctx, layer, order, out, in_run).into_iter().collect() diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index 001790116..d76624ab3 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -34,6 +34,7 @@ use std::sync::{Arc, Mutex}; use effectcraft_engine::project::{Comp, Heard, ItemId, ItemKind, LayerSource, Node, Project, PropGroup}; use effectcraft_engine::render::disk_cache::{self, DiskCache}; +use effectcraft_engine::render::reads::{ReadFiles, ReadLog}; use effectcraft_engine::render::{CancellableFootage, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer}; use effectcraft_engine::time::Tick; use effectcraft_gpu::{DisplayFrame, FrameError, Gpu}; @@ -1465,7 +1466,9 @@ impl Frames { let gpu_here = job.src.gpu.is_some() && job.src.gpu_display && !(remote.gpu() && comp_has_effects(&job.src.project, job.comp)); if gpu_here { let t0 = web_time::Instant::now(); - if let Some(img) = w.render_gpu(&job) { + // (A frame kept on the GPU is not written to the disk cache: its files are not + // needed.) + if let Some((img, _files)) = w.render_gpu(&job) { w.finish(&job, img, t0); continue; } @@ -1617,10 +1620,11 @@ impl Worker { } }); let disk_hit = from_disk.is_some(); - let ci = match from_disk { - Some(f) => f, + // `files`: the source files the rendered frame was made of (see `render::reads`). + let (ci, files) = match from_disk { + Some(f) => (f, None), None => match self.render_guarded(&job).filter(|_| !job.cancel.load(Ordering::Relaxed)) { - Some(ci) => ci, + Some((ci, files)) => (ci, Some(files)), // Called off (frames it read may be missing) or failed: not cached, and not // "in progress" forever: the viewer asks for it again. None => { @@ -1633,6 +1637,16 @@ impl Worker { // and compression. Persistence still runs on this worker, using the same snapshot. self.finish(&job, ci.clone(), t0); if !disk_hit && let Some((dc, k)) = &disk { + // (#3184: the entry is to keep `files`, checked before it is used again.) + if let Some(files) = &files { + log::trace!( + "frame {} of comp {}: {} source files{}", + job.key.frame, + job.key.comp, + files.len(), + if files.is_complete() { "" } else { " (incomplete)" } + ); + } let written = match &ci { FrameImage::Cpu(img) => { let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_array()).collect(); @@ -1689,9 +1703,13 @@ impl Worker { } /// [`Worker::render_job`], again on the CPU if it panicked (the panic hook has logged it); - /// `None` if that panicked too. - fn render_guarded(&self, job: &Job) -> Option { - let attempt = |gpu: bool| std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.render_job(job, gpu))).ok(); + /// `None` if that panicked too. With the source files the frame was made of. + fn render_guarded(&self, job: &Job) -> Option<(FrameImage, ReadFiles)> { + let attempt = |gpu: bool| { + let files = ReadLog::new(); + let img = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.render_job(job, gpu, &files))).ok()?; + Some((img, files.into_files())) + }; let img = attempt(true).or_else(|| { log::error!("a frame render panicked (frame {})", job.key.frame); job.src.gpu.as_ref().and_then(|_| attempt(false)) @@ -1731,16 +1749,19 @@ impl Worker { !self.gpu_retired.load(Ordering::Acquire) && self.cache.lock().is_ok_and(|c| c.gpu_ready()) } - /// The frame on the GPU, kept there for the viewer, if the compositor can do it alone. - fn render_gpu(&self, job: &Job) -> Option { + /// The frame on the GPU, kept there for the viewer, if the compositor can do it alone, with + /// the source files it was made of. + fn render_gpu(&self, job: &Job) -> Option<(FrameImage, ReadFiles)> { if !self.gpu_ready() { return None; } let g = job.src.gpu.as_ref()?; let footage = job.footage(); + let files = ReadLog::new(); let mut r = Renderer::new(&job.src.project, &footage, job.opts); r.expr = job.src.expr.as_deref(); r.cache = Some(&job.src.layer_cache); + r.reads = Some(&files); r.accel = Some(g as &dyn effectcraft_engine::render::Accelerator); r.active_accel()?; let f = g.within_memory(|| g.render_display(&r, job.comp, job.t)); @@ -1750,7 +1771,7 @@ impl Worker { if f.is_some() { self.gpu_succeeded(); } - f.map(|f| FrameImage::Gpu(Arc::new(f))) + f.map(|f| (FrameImage::Gpu(Arc::new(f)), files.into_files())) } Err(e) => { self.gpu_attempt_failed(g, &e); @@ -1759,11 +1780,13 @@ impl Worker { } } - /// Render a frame; `gpu: false` keeps it off the GPU compositor. - fn render_job(&self, job: &Job, gpu: bool) -> FrameImage { + /// Render a frame; `gpu: false` keeps it off the GPU compositor. The source files it reads + /// are noted in `files` (a GPU attempt that falls back to the CPU notes both renders'). + fn render_job(&self, job: &Job, gpu: bool, files: &ReadLog) -> FrameImage { let footage = job.footage(); let mut r = Renderer::new(&job.src.project, &footage, job.opts); r.expr = job.src.expr.as_deref(); + r.reads = Some(files); let gpu_allowed = gpu && self.gpu_ready(); // A failed GPU attempt may have populated intermediate entries before its scope // reported failure. The CPU retry must compute its own pixels from the snapshot. @@ -1789,7 +1812,7 @@ impl Worker { // Time the GPU's work, not just its recording. g.wait(); if g.context().check_health().is_err() { - return self.render_job(job, false); + return self.render_job(job, false, files); } p.record(key, true, t0.elapsed().as_secs_f64() * 1000.0); } @@ -1802,7 +1825,7 @@ impl Worker { } Err(e) => { self.gpu_attempt_failed(g, &e); - return self.render_job(job, false); + return self.render_job(job, false, files); } } } @@ -1822,7 +1845,7 @@ impl Worker { } Err(e) => { self.gpu_attempt_failed(g, &e); - self.render_job(job, false) + self.render_job(job, false, files) } }; } From 2de2406bccb1e1f5836230927f0482f1e08b3e0d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 6 Nov 2026 22:30:26 +0100 Subject: [PATCH 017/324] Automation: confined footage passes on the files it reads Part of #3184: ConfinedFootage forwards FootageSource::recording to the source it wraps, so renders of an automation session list their files instead of coming back incomplete. The read tests also render through the viewer's CancellableFootage wrapper. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/confine.rs | 5 +++++ crates/media/src/reads/tests.rs | 11 +++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 6d8ce2819..c24f62acb 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -401,6 +401,11 @@ impl FootageSource for ConfinedFootage { fn called_off(&self) -> bool { self.inner.called_off() } + /// The files read inside the roots, as the inner source notes them (footage outside reads + /// nothing). + fn recording(&self, reads: &effectcraft_engine::render::reads::ReadLog, f: &mut dyn FnMut()) { + self.inner.recording(reads, f) + } } /// The session's file reads, only inside the read roots: what a project or an imported file diff --git a/crates/media/src/reads/tests.rs b/crates/media/src/reads/tests.rs index f9079820f..8fee7d211 100644 --- a/crates/media/src/reads/tests.rs +++ b/crates/media/src/reads/tests.rs @@ -112,9 +112,16 @@ fn a_sequence_frame_reports_only_its_own_file() { assert_stamps_match_disk(&files); assert_eq!(crate::opens_under(&dir) - opened, 1, "one file opened: the frame's"); assert_eq!(crate::opens_under(&unused_dir), 0, "the unused sequence was not looked at"); - // Another frame reads its own file. - let (_, files) = render(&p, &pool, &cache, cid, 4); + // Another frame reads its own file, also through the viewer's wrapper of the pool. + let viewer = effectcraft_render::CancellableFootage { inner: &pool, cancel: Default::default() }; + let log = ReadLog::new(); + let mut r = Renderer::new(&p, &viewer, RenderOpts::default()); + r.cache = Some(&cache); + r.reads = Some(&log); + r.comp_frame(cid, RATE.tick_of(4)); + let files = log.into_files(); assert_eq!(paths(&files), [frame_4]); + assert!(files.is_complete()); let _ = std::fs::remove_dir_all(&dir); } From 99b65562de0c7c1c8127788a630440f09375fc3e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 6 Nov 2026 23:19:09 +0100 Subject: [PATCH 018/324] Disk cache: frame entries keep their source files, comp key from memory Part of #3184 (step 2). Fixes #3175: opening a comp no longer stamps every footage file of the project before its first frame can show. - The comp's content key (`disk_cache::comp_content_key`) is taken from the project in memory alone: no footage or proxy file is stamped, no `VirtualFileId` is asked. `comp_content_key_with` is gone; `frame_key` hashes a new entry version, so entries of the earlier format are never looked up again (LRU evicts them). - Frame entries (formats 2 and 3) store the files the frame read (`EntryFiles`: size and modification time as read; size and content hash through `VirtualFileId` for files from memory; missing files), then the pixels. Formats 0 and 1 read as misses and are deleted. - Check on hit: `get_frame`/`get_frame_f16` look only at the listed files (one metadata call each) on the frame worker. A changed, back or unreadable file, or a damaged entry, is a miss: the entry is deleted and the frame rendered and stored again. - A frame whose file list is incomplete is shown but not stored. The RAM preview keeps each frame's files, so `persist_missing` writes only frames with a complete list. - Remote frame worker: `FrameServer` records each frame's reads (`take_files`); the web worker stores them with the entry and the page checks them through the file table before using it. The browser's media epoch existed only for the old key and is removed. Export does not use frame entries. - The cache indicator still only asks whether an entry exists. Tests: entry format round trip and damage, the check per file, and in the viewer: a changed file re-renders exactly its frames (and a reopen reads the rest from disk); a frame checks only its own files in a project with a large unused sequence and the key looks at no file; missing, unreadable files and damaged entries never serve a stale frame. Co-Authored-By: Claude Opus 5.5 --- apps/effectcraft-web/src/app.rs | 2 +- apps/effectcraft-web/src/diskcache.rs | 16 +- apps/effectcraft-web/src/frames.rs | 7 +- apps/effectcraft-web/src/store.rs | 17 +- crates/engine/src/background/remote.rs | 27 +- crates/engine/src/background/remote/tests.rs | 68 +++ crates/render/src/disk_cache.rs | 431 ++++++++++++------ crates/render/src/disk_cache/entry_files.rs | 257 +++++++++++ crates/render/src/reads.rs | 2 +- crates/ui-egui/src/frames.rs | 251 +++++----- crates/ui-egui/src/frames/tests.rs | 318 ++++++++++++- crates/ui-egui/tests/it/ui_web_gpu_storage.rs | 9 +- docs/web.md | 8 +- 13 files changed, 1092 insertions(+), 321 deletions(-) create mode 100644 crates/render/src/disk_cache/entry_files.rs diff --git a/apps/effectcraft-web/src/app.rs b/apps/effectcraft-web/src/app.rs index 2882b16cf..99e71117f 100644 --- a/apps/effectcraft-web/src/app.rs +++ b/apps/effectcraft-web/src/app.rs @@ -329,7 +329,7 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> { if n > 0 { app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n, !query_flag("nogpuworkers"))))); } - app.frames.set_virtual_media(files::STORE.media_epoch(), Arc::new(|path| files::STORE.file_identity(path))); + app.frames.set_virtual_id(Arc::new(|path| files::STORE.file_identity(path))); let (tx, rx) = std::sync::mpsc::channel(); api::set_sender(tx); app = app.with_control(rx); diff --git a/apps/effectcraft-web/src/diskcache.rs b/apps/effectcraft-web/src/diskcache.rs index ef9d46f8c..5ac655cb0 100644 --- a/apps/effectcraft-web/src/diskcache.rs +++ b/apps/effectcraft-web/src/diskcache.rs @@ -4,14 +4,17 @@ //! //! - **Writes** happen in the frame workers: a render request carries the frame's disk-cache key //! (`effectcraft_engine::remote::FrameMsg::Render`), the worker posts the frame, then writes -//! the sealed entry (`disk_cache::frame_entry`: LZ4, checksum) with a synchronous access -//! handle into a temporary file moved into place (`js/host.js` `cacheWrite`), and reports -//! `FrameReply::Stored`. +//! the sealed entry (`disk_cache::frame_entry`: the source files the frame read, LZ4, +//! checksum) with a synchronous access handle into a temporary file moved into place +//! (`js/host.js` `cacheWrite`), and reports `FrameReply::Stored`. A frame whose files can't +//! all be named is not stored. //! - **The index** lives here, on the page ([`DiskIndex`], shared with the desktop's cache): //! rebuilt at startup from the folder listing (oldest files first), updated by the workers' //! `Stored` replies and by reads; eviction deletes the least recently used files. //! - **Reads** are asynchronous: a frame whose key is indexed is read and decoded here instead -//! of rendering it (`crate::frames`); a damaged or missing file is a miss and is forgotten. +//! of rendering it (`crate::frames`), if the files its entry lists still have the size and +//! content hash it was made of (the file table's identities); a damaged or missing entry, or +//! one whose files changed, is a miss and is deleted. //! //! - **Layer buffers** too (`layers/<32 hex>.ecc`): a layer lookup happens in the middle of a //! synchronous render, where the browser's file system can't be read, so the frame workers @@ -187,11 +190,12 @@ pub fn note_miss() { } /// Read and decode a cached frame; `None` (forgotten and deleted) when the file is missing or -/// damaged. +/// damaged, or the source files it was made of changed since. pub async fn read(key: u128) -> Option { let name = disk_cache::entry_name(key); let bytes = JsFuture::from(cache_read(&name)).await.ok().and_then(|b| b.dyn_into::().ok()).map(|b| b.to_vec()); - let frame = bytes.as_deref().and_then(disk_cache::read_frame_entry); + let identity = |path: &str| crate::files::STORE.file_identity(path); + let frame = bytes.as_deref().and_then(|b| disk_cache::read_frame_entry(b, Some(&identity))); ST.with(|s| { let mut s = s.borrow_mut(); if frame.is_some() { diff --git a/apps/effectcraft-web/src/frames.rs b/apps/effectcraft-web/src/frames.rs index 69089e308..0159fe23b 100644 --- a/apps/effectcraft-web/src/frames.rs +++ b/apps/effectcraft-web/src/frames.rs @@ -473,10 +473,13 @@ pub async fn worker_frame(json: String) { g.settled().await; replies = SERVER.with(|c| c.borrow_mut().as_mut().map(|s| s.resume()).unwrap_or_default()); } + // The source files the frame read, kept with its entry (checked by the page before use); a + // frame whose files can't all be named is not stored (#3184). + let (files, virtual_id) = SERVER.with(|c| c.borrow_mut().as_mut().map(|s| (s.take_files(), s.virtual_id().cloned())).unwrap_or_default()); for (r, px) in replies { post_reply(&r, px.as_deref()); - if let (FrameReply::Frame { width, height, .. }, Some(px), Some(key)) = (&r, &px, &disk) { - let entry = effectcraft_engine::render::disk_cache::frame_entry(*width, *height, px); + if let (FrameReply::Frame { width, height, .. }, Some(px), Some(key), Some(files)) = (&r, &px, &disk, &files) { + let Some(entry) = effectcraft_engine::render::disk_cache::frame_entry(*width, *height, px, files, virtual_id.as_deref()) else { continue }; let name = format!("{key}.ecc"); match JsFuture::from(crate::diskcache::cache_write(&name, js_sys::Uint8Array::from(&entry[..]))).await { Ok(n) => post_reply(&FrameReply::Stored { key: key.clone(), bytes: n.as_f64().unwrap_or(entry.len() as f64) as u64, layer: false }, None), diff --git a/apps/effectcraft-web/src/store.rs b/apps/effectcraft-web/src/store.rs index 0cc877948..abda69a77 100644 --- a/apps/effectcraft-web/src/store.rs +++ b/apps/effectcraft-web/src/store.rs @@ -20,7 +20,6 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use effectcraft_engine::config::{ConfigStore, FileOps}; @@ -187,13 +186,11 @@ pub struct Store { pub on_change: OnceLock, /// Clock in milliseconds since the Unix epoch (tests pin it). pub clock: OnceLock f64>, - /// Bumped when a virtual file is written. Preview cache lookups key on it; they do not hash. - media_epoch: Arc, } impl Default for Store { fn default() -> Self { - Self { mirror: Mutex::default(), on_change: OnceLock::new(), clock: OnceLock::new(), media_epoch: Arc::new(AtomicU64::new(0)) } + Self { mirror: Mutex::default(), on_change: OnceLock::new(), clock: OnceLock::new() } } } @@ -218,22 +215,12 @@ impl Store { pub fn put_file(&self, path: &str, data: Arc<[u8]>, persist: bool) { let now = self.now(); let key = file_key(path); - let replaced = self.lock().get(&key).is_none_or(|e| !Arc::ptr_eq(&e.data, &data)); self.lock().put(&key, data, now, persist); - if replaced { - self.media_epoch.fetch_add(1, Ordering::Relaxed); - } if persist { self.changed(); } } - /// The generation preview cache lookups key on. It changes when [`Self::put_file`] writes - /// a different blob, and it is not a content hash. - pub fn media_epoch(&self) -> Arc { - self.media_epoch.clone() - } - /// Size and content hash of the file under `path`. The hash is stored on the entry so a /// later key does not walk the bytes again. pub fn file_identity(&self, path: &str) -> Option<(u64, u64)> { @@ -541,11 +528,9 @@ mod tests { assert_ne!(a, b); assert_eq!(&data[..], b"blue"); assert_eq!(s.file_versioned("/collision.png").map(|f| f.1), Some(b), "reading doesn't change it"); - let epoch = s.media_epoch().load(Ordering::Relaxed); let id = s.file_identity("/collision.png").expect("identity"); assert_eq!(id, (4, content_hash(b"blue"))); assert_eq!(s.file_identity("/collision.png"), Some(id), "the hash is kept on the entry"); - assert!(epoch >= 2, "each new blob bumps the generation the preview keys on"); } /// A write that failed is flushed again with the key's latest state (#215). diff --git a/crates/engine/src/background/remote.rs b/crates/engine/src/background/remote.rs index 27f9396e1..ca11d8220 100644 --- a/crates/engine/src/background/remote.rs +++ b/crates/engine/src/background/remote.rs @@ -20,8 +20,10 @@ //! calls [`FrameServer::resume`] for the next. Backend Auto picks CPU or GPU per comp from //! the frames' total times ([`effectcraft_render::AutoPick`]). //! - Disk cache: a render request may carry the frame's disk-cache key ([`FrameMsg::Render`] -//! `disk`); the transport stores the finished frame under it (the browser: in the Origin -//! Private File System) and reports [`FrameReply::Stored`]. +//! `disk`); the transport stores the finished frame under it with the source files it read +//! ([`FrameServer::take_files`], `disk_cache::frame_entry`; the browser: in the Origin Private +//! File System) and reports [`FrameReply::Stored`]. A frame whose files can't all be named is +//! not stored. The page checks an entry's files before it uses it (#3184). //! - Layer buffers on disk: with `layers`, the server's layer cache is backed by a //! [`PrefetchStore`] ([`FrameServer::set_layer_store`]): before the request the transport //! fetches the entries named in `prefetch` (recent misses that are on disk, chosen by the @@ -37,6 +39,7 @@ use std::sync::Arc; use effectcraft_project::{ItemId, Project}; +use effectcraft_render::reads::{ReadFiles, ReadLog}; use effectcraft_render::{Accelerator, AutoKey, Backend, ExprHost, FootageSource, Image, LayerCache, LayerStore, PrefetchStore, RenderOpts, Renderer}; use effectcraft_time::Tick; use serde::{Deserialize, Serialize}; @@ -265,6 +268,8 @@ pub struct FrameServer { salt: u64, /// Size and content hash for footage paths with no native metadata (the browser file table). virtual_id: Option Option<(u64, u64)> + Send + Sync>>, + /// The source files the last finished frame read ([`FrameServer::take_files`]). + files: Option, } /// A frame whose readbacks are in flight. @@ -297,6 +302,7 @@ impl FrameServer { layer_store: None, salt: 0, virtual_id: None, + files: None, } } @@ -306,6 +312,18 @@ impl FrameServer { self.virtual_id = id; } + /// The source files the frame of the last [`FrameReply::Frame`] read, with their identities + /// as read: what its disk entry keeps (`disk_cache::frame_entry`). Taken once. + pub fn take_files(&mut self) -> Option { + self.files.take() + } + + /// The identity of footage paths with no native metadata (the browser file table), to store + /// with a frame's disk entry. + pub fn virtual_id(&self) -> Option<&Arc Option<(u64, u64)> + Send + Sync>> { + self.virtual_id.as_ref() + } + /// The store behind the layer cache when a request asks for `layers` (the browser: the /// disk cache's layer buffers, fetched before the request). pub fn set_layer_store(&mut self, store: Option>) { @@ -432,12 +450,16 @@ impl FrameServer { /// Run the next pass of the frame in progress; its reply once it is done. pub fn resume(&mut self) -> Vec<(FrameReply, Option>)> { let Some(mut pr) = self.pending.take() else { return vec![] }; + self.files = None; pr.passes += 1; let accel = self.accel.clone().filter(|_| pr.opts.backend != Backend::Cpu); let give_up = pr.passes > MAX_PASSES; + // (each pass renders the whole frame: the last one's files are the frame's) + let reads = ReadLog::new(); let mut r = Renderer::new(&pr.project, self.footage.as_ref(), pr.opts); r.expr = self.expr.as_deref(); r.cache = Some(&self.cache); + r.reads = Some(&reads); if !give_up { r.accel = accel.as_deref(); } @@ -451,6 +473,7 @@ impl FrameServer { } let ms = pr.t0.elapsed().as_secs_f64() * 1000.0; let gpu = r.accel.is_some() && r.active_accel().is_some(); + self.files = Some(reads.files()); let hex = |v: Vec| v.into_iter().map(|k| format!("{k:032x}")).collect::>(); let (layer_misses, layer_hits) = match &self.layer_store { Some(st) => (hex(st.take_misses()), hex(st.take_hits())), diff --git a/crates/engine/src/background/remote/tests.rs b/crates/engine/src/background/remote/tests.rs index e2db10b8e..7a7a59f3f 100644 --- a/crates/engine/src/background/remote/tests.rs +++ b/crates/engine/src/background/remote/tests.rs @@ -375,3 +375,71 @@ fn every_frame_begin_has_a_frame_end() { assert!(matches!(w.handle(req(6, s.revision, comp, cpu))[0].0, FrameReply::Frame { id: 6, .. })); assert_eq!(load(), (3, 3)); } + +/// Footage that reads one file from memory (the browser's file table) for every frame. +struct OneVirtualFile { + /// Tell which files it reads (else every render's list is incomplete). + records: bool, +} + +impl FootageSource for OneVirtualFile { + fn frame(&self, _: ItemId, _: &effectcraft_project::Footage, _: Tick) -> Option> { + Some(Arc::new(Image::filled(4, 4, [1.0, 0.5, 0.0, 1.0]))) + } + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + if self.records { + reads.note(effectcraft_render::reads::ReadFile::new("/clip.png", effectcraft_render::reads::FileStamp::Virtual)); + } else { + reads.mark_incomplete(); + } + f() + } +} + +/// The worker hands the transport the files each frame read, so its disk entry keeps them; the +/// page reads the entry back only while those files are unchanged. A frame whose files can't +/// all be named is not stored (#3184). +#[test] +fn the_worker_reports_the_files_of_each_frame_for_its_disk_entry() { + use effectcraft_project::{Comp, Footage, ItemKind, LayerSource, Project, build}; + use effectcraft_render::disk_cache::{frame_entry, read_frame_entry}; + use effectcraft_time::FrameRate; + let mut p = Project::default(); + let f = Footage { path: "/clip.png".into(), width: 4, height: 4, duration: Tick::from_seconds_f64(1.0), has_video: true, ..Default::default() }; + let fid = p.add_item("clip.png", effectcraft_color::Label::None, None, ItemKind::Footage(f)); + let mut comp = Comp::new(4, 4, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + comp.layers = vec![build::layer(&mut p, &comp, "clip", LayerSource::Footage { item: fid }, (4, 4), None)].into(); + let cid = p.add_item("C", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into())); + let id = |mark: u64| move |path: &str| (path == "/clip.png").then_some((10, mark)); + let (one, two) = (id(1), id(2)); + for records in [true, false] { + let mut w = FrameServer::new(Arc::new(OneVirtualFile { records }), None); + w.set_virtual_id(Some(Arc::new(one))); + let mut m = Mirror::default(); + assert!(w.handle(round(&m.sync(1, &p).unwrap())).is_empty()); + assert!(w.take_files().is_none(), "no frame yet"); + let out = w.handle(round(&FrameMsg::Render { + id: 1, + revision: 1, + comp: cid, + time: Tick::ZERO, + opts: Box::default(), + disk: Some(format!("{:032x}", 5u128)), + layers: false, + prefetch: vec![], + })); + let (FrameReply::Frame { width, height, .. }, Some(px)) = &out[0] else { panic!("{:?}", out[0].0) }; + let files = w.take_files().expect("the frame's files"); + assert!(w.take_files().is_none(), "taken once"); + let vid = w.virtual_id().cloned(); + let entry = frame_entry(*width, *height, px, &files, vid.as_deref()); + if !records { + assert!(!files.is_complete() && entry.is_none(), "an incomplete list is not stored"); + continue; + } + assert_eq!(files.files().iter().map(|f| &*f.path).collect::>(), ["/clip.png"]); + let entry = entry.expect("stored"); + assert_eq!(read_frame_entry(&entry, Some(&one)).map(|f| f.rgba), Some(px.clone())); + assert!(read_frame_entry(&entry, Some(&two)).is_none(), "the file was replaced: a miss"); + } +} diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 03832643b..0a91f11ac 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -2,13 +2,18 @@ //! and layer cache entries kept on disk between sessions, like After Effects' disk cache. //! //! * Entries are files keyed by a 128-bit content hash (`/v1//<2 hex>/<32 hex>.ecc`): -//! frames by the hash of the composition's content (the comp and everything it uses, footage -//! files' size and modification time included) plus frame, scale and view; layer buffers by -//! the layer cache's content key salted with the project's footage fingerprint. A changed -//! project therefore never reads stale pixels: its keys simply change. +//! frames by the hash of the composition's content as it is in memory (the comp and everything +//! it uses, footage items with their settings and paths; no file is looked at) plus frame, +//! scale and view; layer buffers by the layer cache's content key salted with the project's +//! footage fingerprint. A changed project therefore never reads stale pixels: its keys simply +//! change. +//! * A frame entry keeps the source files the frame was made of, each with the size and +//! modification time it was read with ([`EntryFiles`], #3184). An entry is used only while +//! those files are unchanged: a handful of `metadata` calls when the frame is read, never a +//! scan of the project's files. A frame whose files can't all be named is not stored. //! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA (or, for //! 32 bpc viewer frames, half-float RGBA with the bytes shuffled into planes; the entry -//! header's format byte tells them apart, 8-bit entries keep format 0), layer +//! header's format byte tells them apart: 2 and 3, both with their source files first), layer //! buffers as `f32` RGBA with the bytes shuffled into planes (exact, so cached and fresh //! renders are bit-identical), Roto Brush / Object Matte segmentations as //! `FrameSeg::to_bytes` (keyed by their content-keyed chain key and scale, so they are @@ -32,6 +37,11 @@ use std::sync::{Arc, Condvar, Mutex}; use effectcraft_effects::Buf; use effectcraft_raster::Image; +use crate::reads::ReadFiles; + +mod entry_files; +pub use entry_files::{EntryFile, EntryFiles, EntryStamp}; + /// File format version (part of the folder layout). const VERSION: &str = "v1"; const MAGIC: &[u8; 4] = b"ECDC"; @@ -87,9 +97,13 @@ pub struct FrameF16 { pub rgba: Vec, } -/// The entry header's format byte of frame entries. +/// The entry header's format byte: layer buffers and segmentations (and 8-bit frames before +/// #3184). const FORMAT_RGBA8: u8 = 0; -const FORMAT_F16: u8 = 1; +/// Frame entries: their source files ([`EntryFiles`]), then 8-bit or half-float pixels. The +/// formats before them (0: 8-bit, 1: half float, without files) read as misses and are deleted. +const FORMAT_RGBA8_FILES: u8 = 2; +const FORMAT_F16_FILES: u8 = 3; /// Counters for tests, the Info panel and `cache.diskStats`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -286,6 +300,8 @@ pub struct DiskCache { evictions: AtomicU64, dropped: AtomicU64, failed: AtomicU64, + /// Source files looked at to check frame entries ([`DiskCache::file_checks`]). + file_checks: AtomicU64, tmp_counter: AtomicU64, queue: Arc<(Mutex, Condvar)>, /// Layer buffers that took less than this to render are not written (ms). @@ -362,6 +378,7 @@ impl DiskCache { evictions: AtomicU64::new(0), dropped: AtomicU64::new(0), failed: AtomicU64::new(0), + file_checks: AtomicU64::new(0), tmp_counter: AtomicU64::new(0), queue: Arc::new(( Mutex::new(Queue { @@ -541,36 +558,82 @@ impl DiskCache { /// An entry's payload and its header's format byte. fn read_entry(&self, kind: Kind, key: u128) -> Option<(u8, Vec)> { + let entry = self.load(kind, key); + match &entry { + Some(_) => self.hit(kind, key), + None => _ = self.misses.fetch_add(1, Ordering::Relaxed), + } + entry + } + + /// An entry's payload and format byte, without counting it as a hit or miss. A damaged file + /// is deleted; a missing one forgotten. + fn load(&self, kind: Kind, key: u128) -> Option<(u8, Vec)> { if !self.contains(kind, key) { - self.misses.fetch_add(1, Ordering::Relaxed); return None; } let path = self.path(kind, key); let data = std::fs::read(&path).ok(); - let ok = data.as_deref().and_then(|d| verify(d, kind).map(|p| (d[5], p))); - match ok { - Some((format, payload)) => { - let payload = (format, payload.to_vec()); - self.hits.fetch_add(1, Ordering::Relaxed); - if let Ok(mut g) = self.index.lock() { - g.touch(kind, key); - } - // Persist the recency for the next session (best effort). - if let Ok(f) = std::fs::File::options().append(true).open(&path) { - let _ = f.set_modified(std::time::SystemTime::now()); - } - Some(payload) - } - None => { - self.misses.fetch_add(1, Ordering::Relaxed); - // Gone (another process evicted it) or damaged: forget it. - if data.is_some() { - let _ = std::fs::remove_file(&path); - } - self.forget(kind, key); - None + let ok = data.as_deref().and_then(|d| Some((*d.get(5)?, verify(d, kind)?.to_vec()))); + if ok.is_none() { + // Gone (another process evicted it) or damaged: forget it. + if data.is_some() { + let _ = std::fs::remove_file(&path); } + self.forget(kind, key); } + ok + } + + /// Count a hit: the entry becomes the most recently used, also for the next session. + fn hit(&self, kind: Kind, key: u128) { + self.hits.fetch_add(1, Ordering::Relaxed); + if let Ok(mut g) = self.index.lock() { + g.touch(kind, key); + } + // Persist the recency for the next session (best effort). + if let Ok(f) = std::fs::File::options().append(true).open(self.path(kind, key)) { + let _ = f.set_modified(std::time::SystemTime::now()); + } + } + + /// A frame entry of `format` whose source files are unchanged, decoded by `decode`, with + /// those files. An entry whose files changed, of the format before #3184, or damaged, is a + /// miss and is deleted (the frame renders again and is stored anew). An entry of the other + /// current format (8-bit and half-float frames have keys of their own) is a miss and stays. + fn get_checked(&self, key: u128, format: u8, virtual_id: Option>, decode: impl FnOnce(&[u8]) -> Option) -> Option<(T, ReadFiles)> { + let miss = || { + self.misses.fetch_add(1, Ordering::Relaxed); + None + }; + let Some((found, payload)) = self.load(Kind::Frame, key) else { return miss() }; + if found != format { + if found != FORMAT_RGBA8_FILES && found != FORMAT_F16_FILES { + self.discard(Kind::Frame, key); + } + return miss(); + } + let Some((files, pixels)) = EntryFiles::decode(&payload) else { + self.discard(Kind::Frame, key); + return miss(); + }; + self.file_checks.fetch_add(files.len() as u64, Ordering::Relaxed); + if !files.unchanged(virtual_id) { + self.discard(Kind::Frame, key); + return miss(); + } + let Some(frame) = decode(pixels) else { + self.discard(Kind::Frame, key); + return miss(); + }; + self.hit(Kind::Frame, key); + Some((frame, files.to_read_files())) + } + + /// Source files looked at so far to check frame entries before using them (one per file a + /// read frame lists; tests). + pub fn file_checks(&self) -> u64 { + self.file_checks.load(Ordering::Relaxed) } /// A valid file whose payload does not decode: delete it, as a damaged one. @@ -682,50 +745,45 @@ impl DiskCache { // ------------------------------------------------------------ typed entries - /// An 8-bit frame (`None` for a half-float entry of that key, which [`DiskCache::get_frame_f16`] - /// reads). - pub fn get_frame(&self, key: u128) -> Option { - let (format, p) = self.read_entry(Kind::Frame, key)?; - if format != FORMAT_RGBA8 { - return None; - } - decode_frame(&p) + /// An 8-bit frame whose source files are unchanged (see [`DiskCache::get_checked`]), with + /// those files; `None` for a half-float entry of that key, which + /// [`DiskCache::get_frame_f16`] reads. `virtual_id` names files served from memory. + pub fn get_frame(&self, key: u128, virtual_id: Option>) -> Option<(Frame8, ReadFiles)> { + self.get_checked(key, FORMAT_RGBA8_FILES, virtual_id, decode_frame) } - /// A half-float frame (32 bpc viewer frames). A damaged one is deleted. - pub fn get_frame_f16(&self, key: u128) -> Option { - let (format, p) = self.read_entry(Kind::Frame, key)?; - if format != FORMAT_F16 { - return None; - } - let f = decode_frame_f16(&p); - if f.is_none() { - self.discard(Kind::Frame, key); - } - f + /// A half-float frame (32 bpc viewer frames), as [`DiskCache::get_frame`]. + pub fn get_frame_f16(&self, key: u128, virtual_id: Option>) -> Option<(FrameF16, ReadFiles)> { + self.get_checked(key, FORMAT_F16_FILES, virtual_id, decode_frame_f16) } - /// Queue a half-float frame for writing (`width * height * 4` binary16 values). `true` when - /// it is on disk or queued; `false` when refused (wrong size, a full queue). - pub fn put_frame_f16(&self, key: u128, width: u32, height: u32, rgba: &[u16]) -> bool { + /// Queue a half-float frame for writing (`width * height * 4` binary16 values) with the + /// source files it was made of. `true` when it is on disk or queued; `false` when refused + /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]). + pub fn put_frame_f16(&self, key: u128, width: u32, height: u32, rgba: &[u16], files: &ReadFiles, virtual_id: Option>) -> bool { if rgba.len() as u64 != width as u64 * height as u64 * 4 { return false; } - self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_F16, encode_frame_f16(width, height, rgba)) + let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; + self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, with_files(&files, encode_frame_f16(width, height, rgba))) } - /// Write a half-float frame synchronously (tests). - pub fn put_frame_f16_now(&self, key: u128, width: u32, height: u32, rgba: &[u16]) { - self.write_format(Kind::Frame, key, FORMAT_F16, &encode_frame_f16(width, height, rgba)); + /// Write a half-float frame synchronously (tests); a list that can't be stored is not. + pub fn put_frame_f16_now(&self, key: u128, width: u32, height: u32, rgba: &[u16], files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Frame, key, FORMAT_F16_FILES, &with_files(&files, encode_frame_f16(width, height, rgba))); + } } - /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes). `true` - /// when it is on disk or queued; `false` when refused (wrong size, a full queue). - pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8]) -> bool { - if rgba.len() != width as usize * height as usize * 4 { + /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes) with the + /// source files it was made of. `true` when it is on disk or queued; `false` when refused + /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]). + pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>) -> bool { + if rgba.len() as u64 != width as u64 * height as u64 * 4 { return false; } - self.contains(Kind::Frame, key) || self.enqueue(Kind::Frame, key, encode_frame(width, height, rgba)) + let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; + self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, with_files(&files, encode_frame(width, height, rgba))) } pub fn get_layer(&self, key: u128) -> Option { @@ -794,12 +852,22 @@ impl DiskCache { true } - /// Write a frame synchronously (tests). - pub fn put_frame_now(&self, key: u128, width: u32, height: u32, rgba: &[u8]) { - self.write_now(Kind::Frame, key, &encode_frame(width, height, rgba)); + /// Write a frame synchronously (tests); a list that can't be stored is not. + pub fn put_frame_now(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Frame, key, FORMAT_RGBA8_FILES, &with_files(&files, encode_frame(width, height, rgba))); + } } } +/// A frame entry's payload: its source files, then its pixels. +fn with_files(files: &EntryFiles, pixels: Vec) -> Vec { + let mut out = Vec::with_capacity(pixels.len() + 64); + files.encode(&mut out); + out.extend_from_slice(&pixels); + out +} + #[cfg(not(target_arch = "wasm32"))] fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { let (m, cv) = &*q; @@ -860,15 +928,29 @@ fn seal_format(kind: Kind, format: u8, payload: &[u8]) -> Vec { data } -/// A sealed frame entry ([`seal`] of the encoded frame): what the browser's frame workers -/// write to the Origin Private File System. -pub fn frame_entry(width: u32, height: u32, rgba: &[u8]) -> Vec { - seal(Kind::Frame, &encode_frame(width, height, rgba)) +/// A sealed 8-bit frame entry with the source files it was made of: what the browser's frame +/// workers write to the Origin Private File System. `None` when the frame must not be stored +/// (its files can't be checked later, see [`EntryFiles::of`]; or a wrong size). +pub fn frame_entry(width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>) -> Option> { + if rgba.len() as u64 != width as u64 * height as u64 * 4 { + return None; + } + let files = EntryFiles::of(files, virtual_id)?; + Some(seal_format(Kind::Frame, FORMAT_RGBA8_FILES, &with_files(&files, encode_frame(width, height, rgba)))) } -/// A frame from a sealed entry's bytes (`None` when damaged). -pub fn read_frame_entry(data: &[u8]) -> Option { - decode_frame(verify(data, Kind::Frame)?) +/// The frame of a sealed entry's bytes, if its source files are unchanged. `None` when damaged, +/// of another format, or made of files that changed since: a miss, to be rendered again. +pub fn read_frame_entry(data: &[u8], virtual_id: Option>) -> Option { + let payload = verify(data, Kind::Frame)?; + if data.get(5) != Some(&FORMAT_RGBA8_FILES) { + return None; + } + let (files, pixels) = EntryFiles::decode(payload)?; + if !files.unchanged(virtual_id) { + return None; + } + decode_frame(pixels) } /// A sealed layer-buffer entry: what the browser's frame workers write to the Origin Private @@ -1055,9 +1137,9 @@ fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { /// Size and content hash of a path that has no native metadata (the browser file table). pub type VirtualFileId<'a> = &'a (dyn Fn(&str) -> Option<(u64, u64)> + Send + Sync); -/// A file's size and modification time (so edited footage gets new keys): the identity a render -/// records for the files it reads ([`crate::reads::FileStamp`]). When the path has no native -/// metadata, `virtual_id` supplies a durable size and content hash instead. +/// A file's size and modification time (so edited footage gets a new layer salt): the identity a +/// render records for the files it reads ([`crate::reads::FileStamp`]). When the path has no +/// native metadata, `virtual_id` supplies a durable size and content hash instead. fn file_stamp(h: &mut Hash128, path: &str, virtual_id: Option>) { if path.is_empty() { return; @@ -1126,26 +1208,18 @@ pub fn footage_salt_with(project: &effectcraft_project::Project, virtual_id: Opt (v as u64) ^ ((v >> 64) as u64) } -/// Content key of a composition's pixels: project render settings, the comp and everything it -/// uses (nested comps, footage, solids, their proxies and Use Proxy switches, footage and proxy -/// files' size and time). With expressions in play (which can read any comp) the whole project -/// counts. Switches that don't change pixels (Audio, Lock, Shy, Hide Shy Layers) don't count, and -/// neither do markers unless an expression mentions them. +/// Content key of a composition's pixels, from the project in memory alone (no file is looked +/// at: the frame entries check their own source files when read, see [`EntryFiles`]): project +/// render settings, the comp and everything it uses (nested comps, footage items with their +/// settings and paths, solids, their proxies and Use Proxy switches). With expressions in play +/// (which can read any comp) the whole project counts. Switches that don't change pixels (Audio, +/// Lock, Shy, Hide Shy Layers) don't count, and neither do markers unless an expression mentions +/// them. pub fn comp_content_key(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId) -> u128 { - comp_content_key_with(project, comp, None) + comp_content_key_for_renderer(project, comp, RENDER_VERSION) } -/// [`comp_content_key`] with [`VirtualFileId`] for paths `std::fs::metadata` cannot describe. -pub fn comp_content_key_with(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId, virtual_id: Option>) -> u128 { - comp_content_key_for_renderer(project, comp, virtual_id, RENDER_VERSION) -} - -fn comp_content_key_for_renderer( - project: &effectcraft_project::Project, - comp: effectcraft_project::ItemId, - virtual_id: Option>, - renderer: &str, -) -> u128 { +fn comp_content_key_for_renderer(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId, renderer: &str) -> u128 { use effectcraft_project::{ItemKind, LayerSource}; let mut h = Hash128::default(); h.write(renderer.as_bytes()); @@ -1192,21 +1266,21 @@ fn comp_content_key_for_renderer( } k => hash_debug(&mut h, k), } - if let ItemKind::Footage(f) = &it.kind { - footage_stamp(&mut h, f, virtual_id); - } hash_debug(&mut h, &it.proxy); - if let Some(px) = &it.proxy { - footage_stamp(&mut h, &px.footage, virtual_id); - } } h.write_u64(comp.0); h.finish() } +/// Frame entries with their source files (#3184), part of every frame key: entries of the +/// earlier format (keyed by footage stamps instead) are never looked up again; least recently +/// used, they are evicted. +const FRAME_ENTRY_VERSION: &[u8] = b"frame-entry-files-1"; + /// Disk key of one viewer frame. pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 { let mut h = Hash128::default(); + h.write(FRAME_ENTRY_VERSION); h.write(&content.to_le_bytes()); h.write_u64(frame as u64); h.write_u64(scale_milli as u64); @@ -1230,18 +1304,18 @@ mod tests { fn link_frame_serves_a_frame_under_a_new_key() { let dc = DiskCache::open(tmpdir("link"), 1 << 30).unwrap(); let rgba: Vec = (0..16).collect(); - dc.put_frame_now(1, 2, 2, &rgba); + dc.put_frame_now(1, 2, 2, &rgba, &ReadFiles::default()); assert!(dc.link_frame(1, 2)); - assert_eq!(dc.get_frame(2).map(|f| f.rgba), Some(rgba.clone())); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).map(|f| f.rgba), Some(rgba.clone())); assert!(!dc.link_frame(1, 2), "already there"); assert!(!dc.link_frame(3, 4), "nothing to link"); assert!(!dc.contains(Kind::Frame, 4)); - dc.put_frame_now(5, 2, 2, &[7; 16]); + dc.put_frame_now(5, 2, 2, &[7; 16], &ReadFiles::default()); assert!(!dc.link_frame(5, 2), "an existing entry stays"); - assert_eq!(dc.get_frame(2).map(|f| f.rgba), Some(rgba.clone())); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).map(|f| f.rgba), Some(rgba.clone())); let _ = std::fs::remove_file(dc.path(Kind::Frame, 1)); dc.forget(Kind::Frame, 1); - assert_eq!(dc.get_frame(2).map(|f| f.rgba), Some(rgba), "the link outlives the original"); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).map(|f| f.rgba), Some(rgba), "the link outlives the original"); } fn buf(seed: u32, w: u32, h: u32) -> Buf { @@ -1276,11 +1350,21 @@ mod tests { #[test] fn frame_entries_round_trip_and_names_parse() { let rgba: Vec = (0..4 * 6 * 3).map(|i| (i * 7 % 256) as u8).collect(); - let e = frame_entry(6, 3, &rgba); - assert_eq!(read_frame_entry(&e), Some(Frame8 { width: 6, height: 3, rgba: rgba.clone() })); + let files: ReadFiles = [crate::reads::ReadFile::new("/v.png", crate::reads::FileStamp::Virtual)].into_iter().collect(); + let (one, two) = (|_: &str| Some((4, 1)), |_: &str| Some((4, 2))); + assert!(frame_entry(6, 3, &rgba, &files, None).is_none(), "a file from memory needs its identity"); + assert!(frame_entry(6, 3, &rgba[1..], &files, Some(&one)).is_none(), "a wrong size"); + let e = frame_entry(6, 3, &rgba, &files, Some(&one)).unwrap(); + assert_eq!(read_frame_entry(&e, Some(&one)), Some(Frame8 { width: 6, height: 3, rgba: rgba.clone() })); + assert!(read_frame_entry(&e, Some(&two)).is_none(), "the file changed"); + let mut incomplete = files.clone(); + incomplete.mark_incomplete(); + assert!(frame_entry(6, 3, &rgba, &incomplete, Some(&one)).is_none(), "an incomplete list is not stored"); let mut bad = e.clone(); bad[20] ^= 1; - assert!(read_frame_entry(&bad).is_none()); + assert!(read_frame_entry(&bad, Some(&one)).is_none()); + // An entry of the format before #3184 (pixels without files) is never read. + assert!(read_frame_entry(&seal(Kind::Frame, &encode_frame(6, 3, &rgba)), Some(&one)).is_none()); let key = 0x0123_4567_89ab_cdef_0011_2233_4455_6677u128; assert_eq!(parse_entry_name(&entry_name(key)), Some(key)); assert_eq!(parse_entry_name("abc.ecc"), None); @@ -1297,27 +1381,27 @@ mod tests { let (w, h) = (7u32, 5u32); // 4.0, 16.0, -0.25, 65504 and a spread of bit patterns. let rgba: Vec = (0..w * h * 4).map(|i| [0x4400, 0x4c00, 0xb400, 0x7bff][i as usize % 4] ^ ((i * 37) as u16 & 0x03ff)).collect(); - dc.put_frame_f16_now(1, w, h, &rgba); - assert_eq!(dc.get_frame_f16(1), Some(FrameF16 { width: w, height: h, rgba: rgba.clone() })); - assert!(dc.get_frame(1).is_none(), "not an 8-bit frame"); - dc.put_frame_now(2, 2, 2, &[9; 16]); - assert!(dc.get_frame_f16(2).is_none() && dc.contains(Kind::Frame, 2), "an 8-bit entry stays valid"); - assert_eq!(dc.get_frame(2).unwrap().rgba, vec![9; 16]); + dc.put_frame_f16_now(1, w, h, &rgba, &ReadFiles::default()); + assert_eq!(dc.get_frame_f16(1, None).map(|f| f.0), Some(FrameF16 { width: w, height: h, rgba: rgba.clone() })); + assert!(dc.get_frame(1, None).map(|f| f.0).is_none(), "not an 8-bit frame"); + dc.put_frame_now(2, 2, 2, &[9; 16], &ReadFiles::default()); + assert!(dc.get_frame_f16(2, None).map(|f| f.0).is_none() && dc.contains(Kind::Frame, 2), "an 8-bit entry stays valid"); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).unwrap().rgba, vec![9; 16]); assert!(dc.stats().bytes > 0); // Reopened, still there (format byte persisted). drop(dc); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - assert_eq!(dc.get_frame_f16(1).unwrap().rgba, rgba); + assert_eq!(dc.get_frame_f16(1, None).map(|f| f.0).unwrap().rgba, rgba); // A sealed entry with a payload of the wrong size: deleted on read. let p = dc.path(Kind::Frame, 3); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); - std::fs::write(&p, seal_format(Kind::Frame, FORMAT_F16, &encode_frame_f16(w, h + 1, &rgba[..])[..])).unwrap(); + std::fs::write(&p, seal_format(Kind::Frame, FORMAT_F16_FILES, &with_files(&EntryFiles::default(), encode_frame_f16(w, h + 1, &rgba[..])))).unwrap(); dc.rescan(); assert!(dc.contains(Kind::Frame, 3)); - assert!(dc.get_frame_f16(3).is_none()); + assert!(dc.get_frame_f16(3, None).map(|f| f.0).is_none()); assert!(!dc.contains(Kind::Frame, 3) && !p.exists()); // Wrong lengths are not written. - dc.put_frame_f16(4, w, h, &rgba[1..]); + dc.put_frame_f16(4, w, h, &rgba[1..], &ReadFiles::default(), None); dc.flush(); assert!(!dc.contains(Kind::Frame, 4)); let _ = std::fs::remove_dir_all(&dir); @@ -1367,14 +1451,14 @@ mod tests { assert_eq!(back.img, b.img); assert_eq!((back.offset, back.scale), (b.offset, b.scale)); let rgba: Vec = (0..20 * 10 * 4).map(|i| (i % 251) as u8).collect(); - assert!(dc.put_frame(7, 20, 10, &rgba)); - assert!(!dc.put_frame(8, 2, 2, &[0; 3]), "a wrong-size frame is refused"); + assert!(dc.put_frame(7, 20, 10, &rgba, &ReadFiles::default(), None)); + assert!(!dc.put_frame(8, 2, 2, &[0; 3], &ReadFiles::default(), None), "a wrong-size frame is refused"); dc.flush(); - assert_eq!(dc.get_frame(7).unwrap().rgba, rgba); + assert_eq!(dc.get_frame(7, None).map(|f| f.0).unwrap().rgba, rgba); let st = dc.stats(); assert_eq!((st.entries, st.hits, st.misses, st.writes), (2, 2, 1, 2)); // Wrong kind is a miss. - assert!(dc.get_frame(42).is_none()); + assert!(dc.get_frame(42, None).map(|f| f.0).is_none()); } /// Music doesn't change a comp's disk keys (adding it to the timeline kept no blue frame); @@ -1416,7 +1500,7 @@ mod tests { } let rgba = vec![7u8; 32 * 32 * 4]; for k in 0..300 { - dc.put_frame(k, 32, 32, &rgba); + dc.put_frame(k, 32, 32, &rgba, &ReadFiles::default(), None); } dc.flush(); assert!((0..300).all(|k| dc.contains(Kind::Frame, k)), "every frame written"); @@ -1431,17 +1515,17 @@ mod tests { let comp = Comp::new(2, 2, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); let id = project.add_item("Cached composition", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into())); let key = frame_key(comp_content_key(&project, id), 0, 1000, 0); - let previous_key = frame_key(comp_content_key_for_renderer(&project, id, None, "effectcraft-render-5"), 0, 1000, 0); + let previous_key = frame_key(comp_content_key_for_renderer(&project, id, "effectcraft-render-5"), 0, 1000, 0); let dir = tmpdir("previous-renderer"); { let cache = DiskCache::open(&dir, 1 << 30).unwrap(); - cache.put_frame_now(previous_key, 2, 2, &[9; 16]); + cache.put_frame_now(previous_key, 2, 2, &[9; 16], &ReadFiles::default()); } let cache = DiskCache::open(&dir, 1 << 30).unwrap(); - assert_eq!(cache.get_frame(previous_key).unwrap().rgba, vec![9; 16]); - assert!(cache.get_frame(key).is_none()); - cache.put_frame_now(key, 2, 2, &[17; 16]); - assert_eq!(cache.get_frame(key).unwrap().rgba, vec![17; 16]); + assert_eq!(cache.get_frame(previous_key, None).map(|f| f.0).unwrap().rgba, vec![9; 16]); + assert!(cache.get_frame(key, None).map(|f| f.0).is_none()); + cache.put_frame_now(key, 2, 2, &[17; 16], &ReadFiles::default()); + assert_eq!(cache.get_frame(key, None).map(|f| f.0).unwrap().rgba, vec![17; 16]); } #[test] @@ -1450,15 +1534,15 @@ mod tests { { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); dc.put_layer_now(1, &buf(1, 8, 8)); - dc.put_frame_now(2, 2, 2, &[9; 16]); + dc.put_frame_now(2, 2, 2, &[9; 16], &ReadFiles::default()); } let dc = DiskCache::open(&dir, 1 << 30).unwrap(); assert_eq!(dc.stats().entries, 2); assert!(dc.contains(Kind::Layer, 1) && dc.contains(Kind::Frame, 2)); - assert_eq!(dc.get_frame(2).unwrap().rgba, vec![9; 16]); + assert_eq!(dc.get_frame(2, None).map(|f| f.0).unwrap().rgba, vec![9; 16]); dc.clear(); assert_eq!(dc.stats().entries, 0); - assert!(dc.get_frame(2).is_none()); + assert!(dc.get_frame(2, None).map(|f| f.0).is_none()); let again = DiskCache::open(&dir, 1 << 30).unwrap(); assert_eq!(again.stats().entries, 0); } @@ -1569,13 +1653,13 @@ mod tests { fn damaged_files_are_misses() { let dir = tmpdir("damaged"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - dc.put_frame_now(5, 4, 4, &[1; 64]); + dc.put_frame_now(5, 4, 4, &[1; 64], &ReadFiles::default()); let p = dc.path(Kind::Frame, 5); let mut d = std::fs::read(&p).unwrap(); let n = d.len(); d[n / 2] ^= 0xff; std::fs::write(&p, d).unwrap(); - assert!(dc.get_frame(5).is_none()); + assert!(dc.get_frame(5, None).map(|f| f.0).is_none()); assert!(!dc.contains(Kind::Frame, 5)); assert!(!p.exists()); } @@ -1633,9 +1717,11 @@ mod tests { assert_ne!(footage_salt_with(&p, Some(&one)), footage_salt_with(&p, Some(&two)), "read audio counts"); } - /// A path with no native metadata takes its key from the caller's size and content hash (#1253). + /// A path with no native metadata takes the layer salt from the caller's size and content hash + /// (#1253). The comp key is from memory: replaced bytes are caught by the frame entries' + /// check instead (#3184). #[test] - fn virtual_file_bytes_change_content_keys() { + fn virtual_file_bytes_change_the_salt_not_the_comp_key() { use effectcraft_project::build; use effectcraft_project::{Comp, Footage, ItemKind, LayerSource, Project}; use effectcraft_time::{FrameRate, Tick}; @@ -1651,10 +1737,81 @@ mod tests { let (one, two) = (id(1), id(2)); let a = footage_salt_with(&p, Some(&one)); let b = footage_salt_with(&p, Some(&two)); - let ka = comp_content_key_with(&p, cid, Some(&one)); - let kb = comp_content_key_with(&p, cid, Some(&two)); assert_ne!(a, b, "replaced virtual media must not reuse the salt"); - assert_ne!(ka, kb, "replaced virtual media must not reuse the frame key"); - assert_eq!(comp_content_key(&p, cid), comp_content_key_with(&p, cid, None)); + // The frame entry of replaced virtual media is a miss. + let dc = DiskCache::open(tmpdir("virtual"), 1 << 30).unwrap(); + let k = frame_key(comp_content_key(&p, cid), 0, 1000, 0); + let files: ReadFiles = [crate::reads::ReadFile::new("/virtual.mov", crate::reads::FileStamp::Virtual)].into_iter().collect(); + assert!(dc.put_frame(k, 1, 1, &[1, 2, 3, 4], &files, Some(&one))); + dc.flush(); + assert!(dc.get_frame(k, Some(&one)).is_some_and(|(_, f)| f == files)); + assert!(dc.get_frame(k, Some(&two)).is_none() && !dc.contains(Kind::Frame, k), "replaced: a miss, deleted"); + } + + /// A frame entry is used only while the files it lists are what it was made of: a new size, + /// a new time, a missing file that is back, a file replaced by a folder are misses, and the + /// entry is deleted so the frame is rendered and stored again. Only the listed files are + /// looked at. Entries of the format before #3184 are misses and deleted. + #[test] + fn frame_entries_check_their_files() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("check"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let gone = src.join("gone.png").to_string_lossy().to_string(); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap_or(FileStamp::Missing))).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &read(&[&a])); + dc.put_frame_now(2, 1, 1, &[2; 4], &read(&[&b, &gone])); + dc.put_frame_now(3, 1, 1, &[3; 4], &read(&[&b])); + assert_eq!(dc.get_frame(1, None).map(|f| f.1), Some(read(&[&a]))); + assert_eq!(dc.file_checks(), 1, "only the file of that frame"); + // a.png gets a new size: frame 1 is a miss and deleted, the others stay. + std::fs::write(&a, b"aaa").unwrap(); + assert!(dc.get_frame(1, None).is_none() && !dc.contains(Kind::Frame, 1)); + assert!(dc.get_frame(2, None).is_some() && dc.get_frame(3, None).is_some()); + // b.png gets a new time only. + let t = std::fs::metadata(&b).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(&b).unwrap().set_modified(t).unwrap(); + assert!(dc.get_frame(3, None).is_none() && !dc.contains(Kind::Frame, 3)); + assert!(dc.get_frame(2, None).is_none(), "b.png is listed there too"); + // A missing file that is back. + dc.put_frame_now(4, 1, 1, &[4; 4], &read(&[&gone])); + assert!(dc.get_frame(4, None).is_some(), "missing, still missing"); + file("gone.png", b"g"); + assert!(dc.get_frame(4, None).is_none() && !dc.contains(Kind::Frame, 4), "back"); + // A file replaced by a folder (unreadable). + let c = file("c.png", b"cc"); + dc.put_frame_now(5, 1, 1, &[5; 4], &read(&[&c])); + std::fs::remove_file(&c).unwrap(); + std::fs::create_dir(&c).unwrap(); + assert!(dc.get_frame(5, None).is_none() && !dc.contains(Kind::Frame, 5)); + // Written again after the miss: a hit with the new identity. + let fresh = file("d.png", b"dd"); + dc.put_frame_now(1, 1, 1, &[9; 4], &read(&[&fresh])); + assert_eq!(dc.get_frame(1, None).map(|f| f.0.rgba), Some(vec![9; 4])); + // The format before #3184 (no files): a miss, deleted. + dc.write_format(Kind::Frame, 6, FORMAT_RGBA8, &encode_frame(1, 1, &[6; 4])); + assert!(dc.contains(Kind::Frame, 6)); + assert!(dc.get_frame(6, None).is_none() && !dc.contains(Kind::Frame, 6)); + // A valid checksum over a damaged files section: a miss, deleted. + let mut payload = vec![]; + payload.extend_from_slice(&3u32.to_le_bytes()); + payload.extend_from_slice(&encode_frame(1, 1, &[7; 4])); + dc.write_format(Kind::Frame, 7, FORMAT_RGBA8_FILES, &payload); + assert!(dc.get_frame(7, None).is_none() && !dc.contains(Kind::Frame, 7)); + // Frames whose files can't all be named are not stored. + let mut incomplete = read(&[&fresh]); + incomplete.mark_incomplete(); + assert!(!dc.put_frame(8, 1, 1, &[8; 4], &incomplete, None)); + dc.flush(); + assert!(!dc.contains(Kind::Frame, 8)); + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/render/src/disk_cache/entry_files.rs b/crates/render/src/disk_cache/entry_files.rs new file mode 100644 index 000000000..fae8cab8f --- /dev/null +++ b/crates/render/src/disk_cache/entry_files.rs @@ -0,0 +1,257 @@ +//! The source files a frame entry on disk was made of (#3184): stored with the pixels, checked +//! when the entry is used. Only the files that frame read are looked at, never every file of the +//! project. +//! +//! Layout (little endian), before the frame's pixel payload: +//! `u32 count`, then per file `u32 path length`, the path (UTF-8), a tag byte and its fields: +//! `0` a file on disk (`u64 size`, `u8 has time`, `u64 time`), `1` bytes from the browser's file +//! table (`u64 size`, `u64 content hash`), `2` a file that could not be read. + +use std::sync::Arc; + +use super::VirtualFileId; +use crate::reads::{FileStamp, MAX_READ_FILES, ReadFile, ReadFiles}; + +/// Longest path an entry stores (bytes): a longer one is not a path this app opened. +const MAX_PATH_BYTES: usize = 1 << 16; + +/// A file's identity as a frame entry keeps it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EntryStamp { + /// Size and modification time (nanoseconds since the Unix epoch) on disk. + Native { len: u64, modified: Option }, + /// Size and content hash from the [`VirtualFileId`] hook (the browser's file table). + Virtual { len: u64, hash: u64 }, + /// It could not be read when the frame was made: it still must not be readable. + Missing, +} + +/// One file of a frame entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EntryFile { + pub path: Arc, + pub stamp: EntryStamp, +} + +/// Every file a frame entry was made of. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EntryFiles(Vec); + +impl EntryFiles { + /// The list to store for a frame that read `files`: `None` when the frame can't be checked + /// against its files later (the list is incomplete, or a file from memory has no identity), + /// so the frame must not be stored. Native stamps are the ones the files were read with, + /// never a fresh look at the disk (a file changed during the render keeps the old one). + pub fn of(files: &ReadFiles, virtual_id: Option>) -> Option { + if !files.is_complete() { + return None; + } + let mut out = Vec::with_capacity(files.len()); + for f in files.files() { + let stamp = match f.stamp { + FileStamp::Native { len, modified } => EntryStamp::Native { len, modified }, + FileStamp::Virtual => { + let (len, hash) = virtual_id.and_then(|id| id(&f.path))?; + EntryStamp::Virtual { len, hash } + } + FileStamp::Missing => EntryStamp::Missing, + }; + out.push(EntryFile { path: f.path.clone(), stamp }); + } + Some(EntryFiles(out)) + } + + pub fn files(&self) -> &[EntryFile] { + &self.0 + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The files as a render reports them (to keep with the frame in memory). + pub fn to_read_files(&self) -> ReadFiles { + self.0 + .iter() + .map(|f| { + let stamp = match f.stamp { + EntryStamp::Native { len, modified } => FileStamp::Native { len, modified }, + EntryStamp::Virtual { .. } => FileStamp::Virtual, + EntryStamp::Missing => FileStamp::Missing, + }; + ReadFile::new(f.path.clone(), stamp) + }) + .collect() + } + + /// Whether every file still is what the frame was made of: one `metadata` call per file + /// (and the hook for files from memory). + pub fn unchanged(&self, virtual_id: Option>) -> bool { + self.0.iter().all(|f| file_unchanged(f, virtual_id)) + } + + pub(super) fn encode(&self, out: &mut Vec) { + out.extend_from_slice(&(self.0.len() as u32).to_le_bytes()); + for f in &self.0 { + out.extend_from_slice(&(f.path.len() as u32).to_le_bytes()); + out.extend_from_slice(f.path.as_bytes()); + match f.stamp { + EntryStamp::Native { len, modified } => { + out.push(0); + out.extend_from_slice(&len.to_le_bytes()); + out.push(u8::from(modified.is_some())); + out.extend_from_slice(&modified.unwrap_or(0).to_le_bytes()); + } + EntryStamp::Virtual { len, hash } => { + out.push(1); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&hash.to_le_bytes()); + } + EntryStamp::Missing => out.push(2), + } + } + } + + /// The list at the start of `p` and what follows it; `None` when it is damaged. + pub(super) fn decode(p: &[u8]) -> Option<(EntryFiles, &[u8])> { + let mut r = Reader(p); + let n = r.u32()? as usize; + if n > MAX_READ_FILES { + return None; + } + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let len = r.u32()? as usize; + if len > MAX_PATH_BYTES { + return None; + } + let path: Arc = std::str::from_utf8(r.take(len)?).ok()?.into(); + let stamp = match r.u8()? { + 0 => { + let len = r.u64()?; + let has = r.u8()?; + let t = r.u64()?; + match has { + 0 => EntryStamp::Native { len, modified: None }, + 1 => EntryStamp::Native { len, modified: Some(t) }, + _ => return None, + } + } + 1 => EntryStamp::Virtual { len: r.u64()?, hash: r.u64()? }, + 2 => EntryStamp::Missing, + _ => return None, + }; + out.push(EntryFile { path, stamp }); + } + Some((EntryFiles(out), r.0)) + } +} + +fn file_unchanged(f: &EntryFile, virtual_id: Option>) -> bool { + let from_memory = || virtual_id.and_then(|id| id(&f.path)); + match f.stamp { + EntryStamp::Native { len, modified } => FileStamp::native(&f.path) == Some(FileStamp::Native { len, modified }), + EntryStamp::Virtual { len, hash } => from_memory() == Some((len, hash)), + // (a folder at the path is still not a file to read) + EntryStamp::Missing => !std::fs::metadata(&*f.path).is_ok_and(|m| m.is_file()) && from_memory().is_none(), + } +} + +/// Reads little-endian fields off the front of a byte slice. +struct Reader<'a>(&'a [u8]); + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let head = self.0.get(..n)?; + self.0 = self.0.get(n..)?; + Some(head) + } + fn u8(&mut self) -> Option { + self.take(1)?.first().copied() + } + fn u32(&mut self) -> Option { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + fn u64(&mut self) -> Option { + Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn files() -> ReadFiles { + [ + ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(9) }), + ReadFile::new("/b.png", FileStamp::Native { len: 4, modified: None }), + ReadFile::new("/c.png", FileStamp::Missing), + ReadFile::new("/v.mov", FileStamp::Virtual), + ] + .into_iter() + .collect() + } + + #[test] + fn lists_round_trip_and_damage_is_caught() { + let id = |p: &str| (p == "/v.mov").then_some((8, 77)); + let list = EntryFiles::of(&files(), Some(&id)).unwrap(); + assert_eq!(list.files()[3].stamp, EntryStamp::Virtual { len: 8, hash: 77 }); + let mut bytes = vec![]; + list.encode(&mut bytes); + bytes.extend_from_slice(b"rest"); + let (back, rest) = EntryFiles::decode(&bytes).unwrap(); + assert_eq!((back, rest), (list.clone(), &b"rest"[..])); + assert_eq!(list.to_read_files(), files()); + // Every truncation is caught (never a panic, never a shorter list). + let mut plain = vec![]; + list.encode(&mut plain); + for n in 0..plain.len() { + assert!(EntryFiles::decode(&plain[..n]).is_none(), "cut at {n}"); + } + // Bad tags and counts. + let mut bad = plain.clone(); + bad[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(EntryFiles::decode(&bad).is_none()); + } + + #[test] + fn frames_that_cant_be_checked_are_not_stored() { + let mut incomplete = files(); + incomplete.mark_incomplete(); + let id = |_: &str| Some((1, 1)); + assert!(EntryFiles::of(&incomplete, Some(&id)).is_none(), "an incomplete list"); + assert!(EntryFiles::of(&files(), None).is_none(), "a file from memory without the hook"); + assert!(EntryFiles::of(&ReadFiles::default(), None).is_some_and(|l| l.is_empty()), "a frame that reads no file"); + } + + #[test] + fn the_check_looks_at_the_listed_files() { + let dir = std::env::temp_dir().join(format!("effectcraft-entry-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("f.bin"); + std::fs::write(&p, b"abc").unwrap(); + let path = p.to_string_lossy().to_string(); + let gone = dir.join("gone.bin").to_string_lossy().to_string(); + let stamp = FileStamp::native(&path).unwrap(); + let read: ReadFiles = [ReadFile::new(path.as_str(), stamp), ReadFile::new(gone.as_str(), FileStamp::Missing)].into_iter().collect(); + let list = EntryFiles::of(&read, None).unwrap(); + assert!(list.unchanged(None)); + std::fs::write(&p, b"abcd").unwrap(); + assert!(!list.unchanged(None), "a new size"); + std::fs::write(&gone, b"x").unwrap(); + let list = EntryFiles::of(&[ReadFile::new(gone.as_str(), FileStamp::Missing)].into_iter().collect(), None).unwrap(); + assert!(!list.unchanged(None), "a missing file that is back"); + let v: ReadFiles = [ReadFile::new("/v", FileStamp::Virtual)].into_iter().collect(); + let one = |_: &str| Some((1, 1)); + let two = |_: &str| Some((1, 2)); + let list = EntryFiles::of(&v, Some(&one)).unwrap(); + assert!(list.unchanged(Some(&one)) && !list.unchanged(Some(&two)) && !list.unchanged(None)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index d5648cca6..162c04862 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -13,7 +13,7 @@ use std::sync::{Arc, Mutex, PoisonError}; /// The identity of a file as a render read it (see [`file_stamp`](crate::disk_cache) for the -/// same identity in content keys). +/// same identity in the layer-cache salt; frame entries store it, see `disk_cache::EntryFiles`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum FileStamp { /// A file on disk: its size in bytes and its modification time (nanoseconds since the Unix diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index d76624ab3..faacd9b23 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -15,9 +15,12 @@ //! egui frames, within a time budget. //! //! With the disk cache on (Settings ▸ Media & Disk Cache), every CPU-rendered frame is also -//! written to disk under a content key (the comp's content hash, frame, scale, view and render -//! options), and a job first looks there: frames survive restarts and project reopenings. The -//! timeline shows disk-only frames as a blue cache bar. +//! written to disk under a content key (the comp's content hash from the project in memory, +//! frame, scale, view and render options) with the source files it read, and a job first looks +//! there: frames survive restarts and project reopenings. An entry is used only while the files +//! it lists are unchanged, checked by the frame worker when it reads the entry (a frame whose +//! files can't all be named is shown but not stored). The timeline shows disk-only frames as a +//! blue cache bar (present entries; their files are checked only when a frame is used). //! //! With Mercury GPU Acceleration (a [`Gpu`] on egui-wgpu's device and the project's renderer set //! to the GPU) frames stay on the GPU: the compositor writes an RGBA8 texture that the viewer @@ -29,7 +32,7 @@ //! cache keeps them as half-float entries. use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use effectcraft_engine::project::{Comp, Heard, ItemId, ItemKind, LayerSource, Node, Project, PropGroup}; @@ -157,8 +160,18 @@ impl Playhead { } } +/// A frame in the RAM preview and the source files it was made of (`None`: unknown, a frame +/// rendered elsewhere or kept on the GPU), so it can be written to the disk cache later +/// ([`Frames::persist_missing`]). +struct Cached { + img: FrameImage, + /// (the browser's frames are stored by its frame workers, not from here) + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + files: Option>, +} + struct Cache { - map: HashMap, + map: HashMap, order: VecDeque, bytes: usize, /// Bytes of GPU frames (also counted in `bytes`). @@ -175,10 +188,16 @@ struct Cache { } impl Cache { + /// A frame without its source files (tests). + #[cfg(test)] fn insert(&mut self, k: FrameKey, img: FrameImage) { + self.insert_with(k, img, None); + } + /// [`Cache::insert`] with the source files the frame was made of. + fn insert_with(&mut self, k: FrameKey, img: FrameImage, files: Option>) { let (sz, gpu) = (img.bytes(), img.is_gpu()); - if let Some(old) = self.map.insert(k, img) { - self.forget(&old); + if let Some(old) = self.map.insert(k, Cached { img, files }) { + self.forget(&old.img); } else { self.order.push_back(k); } @@ -216,7 +235,7 @@ impl Cache { /// than the one on screen first (a zoom or resolution change). fn evict_gpu(&mut self) { while self.gpu_bytes > self.gpu_budget { - let is_gpu = |k: &FrameKey| self.map.get(k).is_some_and(FrameImage::is_gpu); + let is_gpu = |k: &FrameKey| self.map.get(k).is_some_and(|c| c.img.is_gpu()); let other_scale = self.order.iter().position(|k| Some(k.scale) != self.scale && is_gpu(k)); let Some(i) = other_scale.or_else(|| self.order.iter().position(is_gpu)) else { break }; if let Some(old) = self.order.remove(i) { @@ -254,7 +273,7 @@ impl Cache { } fn remove(&mut self, k: &FrameKey) { if let Some(i) = self.map.remove(k) { - self.forget(&i); + self.forget(&i.img); } } /// Shown again: last in line for eviction. @@ -317,10 +336,10 @@ pub struct RenderSource { /// ([`Frames::identity`]). type Identity = (u64, Option>); -/// Content keys of (project revision, comp, virtual-file generation). The generation is one -/// counter bumped when a browser file is replaced, so a lookup stays a map read. Hashing the -/// new bytes happens only when that generation misses. -type ContentKeys = Arc>>; +/// Disk-cache content keys ([`disk_cache::comp_content_key`]) of (project revision, comp). They +/// come from the project in memory alone: the files a frame read are checked by its entry +/// when it is read (#3184). +type ContentKeys = Arc>>; #[cfg(not(target_arch = "wasm32"))] #[derive(Default)] @@ -329,16 +348,16 @@ struct ContentKeyJobs { pending: VecDeque<(Arc, u64, u64)>, } -fn content_key(keys: &ContentKeys, project: &Project, revision: u64, comp: u64, epoch: u64, virtual_id: Option>) -> u128 { - if let Some(k) = keys.lock().ok().and_then(|m| m.get(&(revision, comp, epoch)).copied()) { +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_with(project, ItemId(comp), virtual_id); + 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, epoch), k); + m.insert((revision, comp), k); } k } @@ -424,18 +443,28 @@ pub fn opts_hash(o: &RenderOpts) -> 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, - epoch: u64, - virtual_id: Option>, -) -> u128 { - let content = content_key(keys, project, key.revision, key.comp, epoch, virtual_id); +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) } +/// Queue `img` for the disk cache under `dk` with the source files it was made of. `false` when +/// refused: a GPU frame (no CPU pixels), files that can't be checked when the entry is read +/// (an incomplete list, #3184: the frame is shown, not stored), a full queue. +fn put_disk_frame(dc: &DiskCache, dk: u128, img: &FrameImage, files: &ReadFiles, virtual_id: Option>) -> bool { + if !files.is_complete() { + return false; + } + match img { + FrameImage::Cpu(img) => { + let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_array()).collect(); + dc.put_frame(dk, img.size[0] as u32, img.size[1] as u32, &rgba, files, virtual_id) + } + FrameImage::CpuF16(f) => dc.put_frame_f16(dk, f.width, f.height, f.bits(), files, virtual_id), + FrameImage::Gpu(_) => false, + } +} + /// A frame for a [`RemoteFrames`] renderer. pub struct RemoteJob { pub project: Arc, @@ -513,9 +542,8 @@ pub struct Frames { /// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout. pub last_ms: Arc>, content_keys: ContentKeys, - /// Bumped when a virtual file is replaced. Lookups key on it instead of statting footage. - virtual_epoch: Arc, - /// Size and content hash for paths with no native metadata. Called only on a cache miss. + /// Size and content hash for paths with no native metadata (the browser's file table): to + /// store and check the files of disk entries. virtual_id: Option Option<(u64, u64)> + Send + Sync>>, #[cfg(not(target_arch = "wasm32"))] content_key_jobs: Arc>, @@ -603,7 +631,6 @@ impl Default for Frames { ctx: None, last_ms: Arc::new(Mutex::new(0.0)), content_keys: Arc::default(), - virtual_epoch: Arc::new(AtomicU64::new(0)), virtual_id: None, #[cfg(not(target_arch = "wasm32"))] content_key_jobs: Arc::default(), @@ -755,7 +782,7 @@ impl Frames { pub fn retire_gpu(&self) { self.gpu_retired.store(true, Ordering::Release); if let Ok(mut cache) = self.cache.lock() { - let keys: Vec<_> = cache.map.iter().filter_map(|(key, image)| image.is_gpu().then_some(*key)).collect(); + let keys: Vec<_> = cache.map.iter().filter_map(|(key, c)| c.img.is_gpu().then_some(*key)).collect(); for key in keys { cache.remove(&key); } @@ -790,7 +817,7 @@ impl Frames { /// The cached frame, which becomes the most recently used. pub fn get(&self, k: &FrameKey) -> Option { let mut c = self.cache.lock().ok()?; - let img = c.map.get(k).cloned()?; + let img = c.map.get(k).map(|c| c.img.clone())?; c.touch(k); Some(img) } @@ -826,7 +853,7 @@ impl Frames { }) .max_by_key(|k| k.revision) .copied()?; - let img = c.map.get(&newest).cloned()?; + let img = c.map.get(&newest).map(|c| c.img.clone())?; c.touch(&newest); Some((newest, img)) } @@ -969,7 +996,6 @@ impl Frames { if src.disk.is_none() && remote.is_none() { return vec![]; } - let epoch = self.virtual_epoch.load(Ordering::Relaxed); #[cfg(not(target_arch = "wasm32"))] { self.note_disk_series(base.comp, base.scale, base.view ^ opts_hash(opts)); @@ -977,7 +1003,7 @@ impl Frames { } #[cfg(not(target_arch = "wasm32"))] let content = { - let known = self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp, epoch)).copied(); + let known = self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp)).copied(); let Some(content) = known else { self.request_content_key(src.project.clone(), base.revision, base.comp); return vec![]; @@ -985,7 +1011,7 @@ impl Frames { content }; #[cfg(target_arch = "wasm32")] - let content = content_key(&self.content_keys, &src.project, base.revision, base.comp, epoch, self.virtual_id.as_deref()); + let content = content_key(&self.content_keys, &src.project, base.revision, base.comp); let ram: HashSet = self.cached_frames(base).into_iter().collect(); let oh = opts_hash(opts); (start..end).filter(|f| !ram.contains(f)).filter(|f| contains(disk_cache::frame_key(content, *f, base.scale, base.view ^ oh))).collect() @@ -996,20 +1022,20 @@ impl Frames { /// are converted on the frame pool, each queued once. `true` while there may be more to /// write (a content key being computed, frames being converted): call again soon, since a /// refused write is only retried by a later call. Disk keys hash `opts` the way the worker - /// writes them (`base.opts` also carries the Roto Brush model stamp). + /// writes them (`base.opts` also carries the Roto Brush model stamp). Only frames that know + /// every source file they were made of are written (an entry is checked against them). #[cfg(not(target_arch = "wasm32"))] pub fn persist_missing(&self, src: &RenderSource, base: &FrameKey, opts: &RenderOpts) -> bool { let Some(dc) = src.disk.clone() else { return false }; let oh = opts_hash(opts); self.note_disk_series(base.comp, base.scale, base.view ^ oh); self.carry_disk(src); - let epoch = self.virtual_epoch.load(Ordering::Relaxed); - let known = self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp, epoch)).copied(); + let known = self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp)).copied(); let Some(content) = known else { self.request_content_key(src.project.clone(), base.revision, base.comp); return true; }; - let (missing, converting): (Vec<(u128, FrameImage)>, bool) = { + let (missing, converting): (Vec<(u128, FrameImage, Arc)>, bool) = { let (Ok(c), Ok(mut queued), Ok(mut written)) = (self.cache.lock(), self.persisted.lock(), self.written.lock()) else { return false }; if queued.len() > 100_000 { queued.clear(); @@ -1022,14 +1048,14 @@ impl Frames { .map .iter() .filter(|(k, _)| k.same_series(base)) - .filter_map(|(k, img)| { - // (GPU frames have no CPU pixels to write) - if img.is_gpu() { - return None; - } + .filter_map(|(k, c)| { + // (GPU frames have no CPU pixels to write; a frame that can't name its files + // can't be checked when read) + let files = c.files.as_ref().filter(|f| f.is_complete() && !c.img.is_gpu())?; let dk = disk_cache::frame_key(content, k.frame, k.scale, k.view ^ oh); let tries = written.1.get(&dk).copied().unwrap_or(0); - (tries < 2 && !dc.contains(disk_cache::Kind::Frame, dk) && !dc.frame_pending(dk) && queued.insert(dk)).then(|| (dk, img.clone())) + (tries < 2 && !dc.contains(disk_cache::Kind::Frame, dk) && !dc.frame_pending(dk) && queued.insert(dk)) + .then(|| (dk, c.img.clone(), files.clone())) }) .collect(); (missing, !queued.is_empty()) @@ -1037,19 +1063,12 @@ impl Frames { if missing.is_empty() { return converting; } - let (persisted, written) = (self.persisted.clone(), self.written.clone()); + let (persisted, written, virtual_id) = (self.persisted.clone(), self.written.clone(), self.virtual_id.clone()); let work = move || { - for (dk, img) in missing { + for (dk, img, files) in missing { // (accepted: the disk cache tracks it until written, and it counts as a try; // refused by a full queue: retried, without counting) - let accepted = match &img { - FrameImage::Cpu(img) => { - let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_array()).collect(); - dc.put_frame(dk, img.size[0] as u32, img.size[1] as u32, &rgba) - } - FrameImage::CpuF16(f) => dc.put_frame_f16(dk, f.width, f.height, f.bits()), - FrameImage::Gpu(_) => false, - }; + let accepted = put_disk_frame(&dc, dk, &img, &files, virtual_id.as_deref()); if accepted && let Ok(mut w) = written.lock() { let n = w.1.entry(dk).or_default(); *n = n.saturating_add(1); @@ -1092,7 +1111,6 @@ impl Frames { return; } let (carries, scheduled, series, ctx) = (self.disk_carries.clone(), self.carry_scheduled.clone(), self.disk_series.clone(), self.ctx.clone()); - let virtual_id = self.virtual_id.clone(); let work = move || { let mut linked = false; loop { @@ -1112,7 +1130,7 @@ impl Frames { let Some(series) = series.lock().ok().and_then(|m| m.get(&c.comp).cloned()) else { return false }; let comp = ItemId(c.comp); let n = c.to.comp(comp).map_or(0, |k| k.frame_rate.frame_at(k.duration)).clamp(0, 100_000); - let key = |p: &Project| disk_cache::comp_content_key_with(p, comp, virtual_id.as_deref()); + let key = |p: &Project| disk_cache::comp_content_key(p, comp); let (a, b) = (key(&c.from), key(&c.to)); if a == b { return false; @@ -1154,7 +1172,6 @@ impl Frames { jobs.running = true; drop(jobs); let (jobs, keys, ctx) = (self.content_key_jobs.clone(), self.content_keys.clone(), self.ctx.clone()); - let (epoch, id) = (self.virtual_epoch.clone(), self.virtual_id.clone()); let work = move || loop { let next = { let mut jobs = jobs.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1165,9 +1182,7 @@ impl Frames { next }; let Some((project, revision, comp)) = next else { return }; - let epoch = epoch.load(Ordering::Relaxed); - let id = id.clone(); - if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| content_key(&keys, &project, revision, comp, epoch, id.as_deref()))).is_err() { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| content_key(&keys, &project, revision, comp))).is_err() { log::error!("could not compute a preview disk-cache key; the cache indicator will retry"); } if let Some(ctx) = &ctx { @@ -1206,9 +1221,8 @@ impl Frames { c.gpu_pressure = None; c.gpu_adjusted = None; } - // Disk keys hash the footage files' size and time, but are remembered per revision; a - // file reloaded from disk without a new revision (a re-rendered image sequence) must be - // keyed again, or the disk cache serves the frames from before. + // (the disk keys of a revision don't depend on files: a file changed on disk is caught + // when its frames' entries are read; they are forgotten with the frames all the same) if let Ok(mut k) = self.content_keys.lock() { k.clear(); } @@ -1395,20 +1409,15 @@ impl Frames { ctx: self.ctx.clone(), last: self.last_ms.clone(), content_keys: self.content_keys.clone(), - virtual_epoch: self.virtual_epoch.clone(), virtual_id: self.virtual_id.clone(), gpu_retired: self.gpu_retired.clone(), } } - /// Browser file table: `epoch` bumps on each replacement, and `id` is the size and content - /// hash used when a content key is rebuilt. Neither runs on a cache hit. - pub fn set_virtual_media(&mut self, epoch: Arc, id: Arc Option<(u64, u64)> + Send + Sync>) { - self.virtual_epoch = epoch; + /// Browser file table: `id` gives the size and content hash of a path served from memory, + /// stored with the disk entries of the frames that read it and checked when they are read. + pub fn set_virtual_id(&mut self, id: Arc Option<(u64, u64)> + Send + Sync>) { self.virtual_id = Some(id); - if let Ok(mut keys) = self.content_keys.lock() { - keys.clear(); - } } /// Render frames with `remote` from now on (`None`: on this thread again). @@ -1469,7 +1478,7 @@ impl Frames { // (A frame kept on the GPU is not written to the disk cache: its files are not // needed.) if let Some((img, _files)) = w.render_gpu(&job) { - w.finish(&job, img, t0); + w.finish(&job, img, None, t0); continue; } } @@ -1481,8 +1490,7 @@ impl Frames { let fw = self.worker(); let busy = self.remote_busy.clone(); let t0 = web_time::Instant::now(); - let epoch = w.virtual_epoch.load(Ordering::Relaxed); - let disk_key = remote.disk().then(|| frame_disk_key(&w.content_keys, &job.src.project, &key, opts_hash(&job.opts), epoch, w.virtual_id.as_deref())); + let disk_key = remote.disk().then(|| frame_disk_key(&w.content_keys, &job.src.project, &key, opts_hash(&job.opts))); let rj = RemoteJob { project: job.src.project.clone(), revision: key.revision, comp: job.comp, t: job.t, opts: job.opts, disk_key }; remote.start( rj, @@ -1493,7 +1501,7 @@ impl Frames { match r { Ok(f) => { let img = egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba); - fw.finish_key(key, urgent, FrameImage::Cpu(Arc::new(img)), t0); + fw.finish_key(key, urgent, FrameImage::Cpu(Arc::new(img)), None, t0); } Err(e) => { // Not rendered (a stale revision, a lost worker): the viewer asks again. @@ -1539,7 +1547,6 @@ struct Worker { ctx: Option, last: Arc>, content_keys: ContentKeys, - virtual_epoch: Arc, virtual_id: Option Option<(u64, u64)> + Send + Sync>>, gpu_retired: Arc, } @@ -1602,29 +1609,14 @@ impl Worker { job }; let t0 = web_time::Instant::now(); - let epoch = self.virtual_epoch.load(Ordering::Relaxed); - let disk = job - .src - .disk - .as_ref() - .map(|dc| (dc.clone(), frame_disk_key(content_keys, &job.src.project, &job.key, opts_hash(&job.opts), epoch, self.virtual_id.as_deref()))); - // Half-float frames (32 bpc) have entries of their own (their key has the options). - let from_disk = disk.as_ref().and_then(|(dc, k)| { - if job.opts.skip_hdr_step { - let f = dc.get_frame_f16(*k)?; - let encoding = effectcraft_engine::viewer::FrameEncoding::of(&job.src.project.settings, true); - Some(FrameImage::CpuF16(Arc::new(F16Frame::from_bits(f.width, f.height, f.rgba, encoding)))) - } else { - let f = dc.get_frame(*k)?; - Some(FrameImage::Cpu(Arc::new(egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba)))) - } - }); + let disk = job.src.disk.as_ref().map(|dc| (dc.clone(), frame_disk_key(content_keys, &job.src.project, &job.key, opts_hash(&job.opts)))); + let from_disk = disk.as_ref().and_then(|(dc, k)| self.disk_frame(dc, *k, &job)); let disk_hit = from_disk.is_some(); - // `files`: the source files the rendered frame was made of (see `render::reads`). + // `files`: the source files the frame was made of (see `render::reads`). let (ci, files) = match from_disk { - Some(f) => (f, None), + Some(hit) => hit, None => match self.render_guarded(&job).filter(|_| !job.cancel.load(Ordering::Relaxed)) { - Some((ci, files)) => (ci, Some(files)), + Some(rendered) => rendered, // Called off (frames it read may be missing) or failed: not cached, and not // "in progress" forever: the viewer asks for it again. None => { @@ -1633,52 +1625,51 @@ impl Worker { } }, }; + let files = Arc::new(files); // Publish the shared frame and wake the viewer before optional RGBA conversion // and compression. Persistence still runs on this worker, using the same snapshot. - self.finish(&job, ci.clone(), t0); - if !disk_hit && let Some((dc, k)) = &disk { - // (#3184: the entry is to keep `files`, checked before it is used again.) - if let Some(files) = &files { - log::trace!( - "frame {} of comp {}: {} source files{}", - job.key.frame, - job.key.comp, - files.len(), - if files.is_complete() { "" } else { " (incomplete)" } - ); - } - let written = match &ci { - FrameImage::Cpu(img) => { - let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_array()).collect(); - dc.put_frame(*k, img.size[0] as u32, img.size[1] as u32, &rgba); - true - } - FrameImage::CpuF16(f) => { - dc.put_frame_f16(*k, f.width, f.height, f.bits()); - true - } - FrameImage::Gpu(_) => false, - }; - if written && let Some(ctx) = &self.ctx { - ctx.request_repaint(); - } + self.finish(&job, ci.clone(), Some(files.clone()), t0); + if !disk_hit + && let Some((dc, k)) = &disk + && put_disk_frame(dc, *k, &ci, &files, self.virtual_id.as_deref()) + && let Some(ctx) = &self.ctx + { + ctx.request_repaint(); } true } - /// Store a finished frame and release its job. - fn finish(&self, job: &Job, img: FrameImage, t0: web_time::Instant) { - self.finish_key(job.key, job.urgent, img, t0); + /// The frame of `job` from the disk cache (key `k`), if its entry is there and the source + /// files it lists are unchanged (checked here, on the frame worker: a few `metadata` calls + /// for that frame's files). An entry whose files changed is deleted: the frame renders again + /// and its new entry replaces it. + fn disk_frame(&self, dc: &DiskCache, k: u128, job: &Job) -> Option<(FrameImage, ReadFiles)> { + let virtual_id = self.virtual_id.as_deref(); + // Half-float frames (32 bpc) have entries of their own (their key has the options). + if job.opts.skip_hdr_step { + let (f, files) = dc.get_frame_f16(k, virtual_id)?; + let encoding = effectcraft_engine::viewer::FrameEncoding::of(&job.src.project.settings, true); + Some((FrameImage::CpuF16(Arc::new(F16Frame::from_bits(f.width, f.height, f.rgba, encoding))), files)) + } else { + let (f, files) = dc.get_frame(k, virtual_id)?; + Some((FrameImage::Cpu(Arc::new(egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba))), files)) + } } - fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, t0: web_time::Instant) { + /// Store a finished frame (with the source files it was made of, when known) and release its + /// job. + fn finish(&self, job: &Job, img: FrameImage, files: Option>, t0: web_time::Instant) { + self.finish_key(job.key, job.urgent, img, files, t0); + } + + fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, files: Option>, t0: web_time::Instant) { if urgent && let Ok(mut l) = self.last.lock() { *l = t0.elapsed().as_secs_f64() * 1000.0; } if let Ok(mut c) = self.cache.lock() && (!img.is_gpu() || !self.gpu_retired.load(Ordering::Acquire)) { - c.insert(key, img); + c.insert_with(key, img, files); } self.release(key, urgent); } diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index df7b3900c..596f3054a 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -60,7 +60,7 @@ fn disk_fixture(stored_frames: &[i64]) -> (Frames, RenderSource, FrameKey, Rende disk.keys.lock().unwrap().extend(stored_frames.iter().map(|frame| disk_cache::frame_key(content, *frame, base.scale, base.view ^ opts_hash(&opts)))); let mut frames = Frames::default(); frames.set_remote(Some(disk.clone())); - frames.content_keys.lock().unwrap().insert((base.revision, base.comp, 0), content); + frames.content_keys.lock().unwrap().insert((base.revision, base.comp), content); let source = RenderSource { project: session.project.clone(), footage: session.footage.clone(), @@ -126,7 +126,7 @@ fn disk_indicator_does_not_hash_on_ui_thread_and_coalesces_edits() { assert_eq!(frames.content_key_jobs.lock().unwrap().pending.len(), 1); release.send(()).unwrap(); let until = Instant::now() + Duration::from_secs(3); - while !frames.content_keys.lock().unwrap().contains_key(&(base.revision, base.comp, 0)) { + while !frames.content_keys.lock().unwrap().contains_key(&(base.revision, base.comp)) { assert!(Instant::now() < until); std::thread::sleep(Duration::from_millis(1)); } @@ -153,7 +153,7 @@ fn disk_indicator_range_tracks_live_membership() { let mut revised = base; revised.revision += 1; - frames.content_keys.lock().unwrap().insert((revised.revision, revised.comp, 0), 5678); + frames.content_keys.lock().unwrap().insert((revised.revision, revised.comp), 5678); assert!(frames.disk_frames(&src, &revised, 10..13, &opts).is_empty()); let changed = FrameKey { scale: base.scale + 1, ..base }; @@ -211,7 +211,7 @@ fn retirement_reaches_existing_workers_and_keeps_cpu_frames_and_completion_live( let next = key(1, 1, 0); frames.inflight.lock().unwrap().insert(next); frames.queue.lock().unwrap().running.insert(next); - worker.finish_key(next, false, img(), web_time::Instant::now()); + worker.finish_key(next, false, img(), None, web_time::Instant::now()); assert!(frames.is_cached(&next), "CPU retry can still publish"); assert_eq!(frames.inflight(), 0); assert!(frames.queue.lock().unwrap().running.is_empty()); @@ -996,7 +996,7 @@ fn the_frames_an_edit_keeps_match_a_fresh_render() { // The work area is a preview and render range: setting it (B, N) keeps every frame, on // disk too. let n = s.project.comp(comp).map(|c| c.frame_rate.frame_at(c.duration)).unwrap(); - let disk = |s: &Session| effectcraft_engine::render::disk_cache::comp_content_key_with(&s.project, comp, None); + let disk = |s: &Session| effectcraft_engine::render::disk_cache::comp_content_key(&s.project, comp); let d0 = disk(&s); let work_area = |start: f64, end: f64| json!({"cmd": "comp.workArea", "params": {"comp": comp.0, "start": start, "end": end}}); assert_eq!(kept(&mut s, comp, work_area(1.0, 4.0)), (0..n).collect::>()); @@ -1616,19 +1616,12 @@ fn ram_frames_missing_on_disk_are_written_as(half: bool) { FrameKey { revision: 1, content: f.content_of(&src.project, 1, cid), comp: cid.0, opts: opts_hash(&RenderOpts::default()) ^ 1, ..key(0, 0, 0) }; for fr in 0..10 { let frame = if half { FrameImage::CpuF16(Arc::new(F16Frame::from_image(&effectcraft_engine::render::Image::new(8, 8), SRGB))) } else { img() }; - f.cache.lock().unwrap().insert(FrameKey { frame: fr, ..series }, frame); + f.cache.lock().unwrap().insert_with(FrameKey { frame: fr, ..series }, frame, Some(Arc::default())); } let on_disk = |fr: i64| { disk.contains( disk_cache::Kind::Frame, - frame_disk_key( - &f.content_keys, - &src.project, - &FrameKey { frame: fr, ..series }, - opts_hash(&RenderOpts::default()), - f.virtual_epoch.load(Ordering::Relaxed), - None, - ), + frame_disk_key(&f.content_keys, &src.project, &FrameKey { frame: fr, ..series }, opts_hash(&RenderOpts::default())), ) }; let persist = || { @@ -1681,7 +1674,7 @@ fn ram_frames_missing_on_disk_are_written_as(half: bool) { fn audio_edits_keep_the_frames_until_something_draws_the_audio() { use effectcraft_engine::Session; use effectcraft_engine::project::{Footage, GroupKind, LayerId, Value, build}; - use effectcraft_engine::render::disk_cache::comp_content_key_with; + use effectcraft_engine::render::disk_cache::comp_content_key; use serde_json::json; let mut s = Session::default(); let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 4, "frameRate": 30})).unwrap()["comp"].as_u64().unwrap()); @@ -1736,7 +1729,7 @@ fn audio_edits_keep_the_frames_until_something_draws_the_audio() { let mut p1 = p0.clone(); edit(Arc::make_mut(&mut p1)); let id1 = f.content_of(&p1, 2, view); - (f.cached_frames(&k(id1, 0)), comp_content_key_with(&p0, view, None) == comp_content_key_with(&p1, view, None)) + (f.cached_frames(&k(id1, 0)), comp_content_key(&p0, view) == comp_content_key(&p1, view)) }; let all: Vec = (0..120).collect(); let edits: [(&str, &dyn Fn(&mut Project)); 3] = [("levels", &levels), ("audio effect", &backwards), ("audio switch", &mute)]; @@ -1933,9 +1926,9 @@ fn disk_frames_outlive_an_edit_that_cant_change_them() { disk: Some(disk.clone()), }; // Every frame of `p0` on disk, none in RAM. - let content0 = disk_cache::comp_content_key_with(&p0, cid, None); + let content0 = disk_cache::comp_content_key(&p0, cid); for f in 0..30 { - disk.put_frame_now(disk_cache::frame_key(content0, f, 1000, oh), 1, 1, &[1, 2, 3, 255]); + disk.put_frame_now(disk_cache::frame_key(content0, f, 1000, oh), 1, 1, &[1, 2, 3, 255], &ReadFiles::default()); } let rename: fn(&mut Project, ItemId, LayerId) = |p, c, l| p.comp_mut(c).unwrap().layer_mut(l).unwrap().name = "Renamed".into(); let trim: fn(&mut Project, ItemId, LayerId) = |p, c, l| { @@ -2041,7 +2034,7 @@ fn a_keyframe_edit_reaches_only_the_keys_around_it() { fn music_volume_keeps_the_frames_with_expressions_that_dont_read_audio() { use effectcraft_engine::Session; use effectcraft_engine::project::{Expression, Footage, FootageKind, LayerId, Value, build}; - use effectcraft_engine::render::disk_cache::comp_content_key_with; + use effectcraft_engine::render::disk_cache::comp_content_key; use serde_json::json; let mut s = Session::default(); let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 4, "frameRate": 30})).unwrap()["comp"].as_u64().unwrap()); @@ -2069,7 +2062,7 @@ fn music_volume_keeps_the_frames_with_expressions_that_dont_read_audio() { let mut p1 = p0.clone(); Arc::make_mut(&mut p1).comp_mut(cid).unwrap().layer_mut(music_id).unwrap().props.prop_mut("audio/levels").unwrap().value = Value::Vec2([-6.0, -6.0]); let id1 = f.content_of(&p1, 2, cid); - (f.cached_frames(&k(id1, 0)).len(), comp_content_key_with(&p0, cid, None) == comp_content_key_with(&p1, cid, None)) + (f.cached_frames(&k(id1, 0)).len(), comp_content_key(&p0, cid) == comp_content_key(&p1, cid)) }; assert_eq!(kept("wiggle(2, 20)"), (120, true), "a wiggle reads no audio"); let (frames, disk) = kept("value + thisComp.layer(\"Music\")(\"Audio\")(\"Audio Levels\")[0]"); @@ -2449,3 +2442,288 @@ fn a_keyframe_edit_beside_muted_keys_reaches_the_keys_that_play() { assert!(same(i), "kept frame {i} renders differently after the edit"); } } + +/// Disk-cache frame entries that keep the source files they were made of (#3184): a sequence +/// comp in a folder of its own, with a large unused sequence in the project. +mod frame_files { + use super::*; + use effectcraft_engine::project::{Footage, FootageKind, build}; + use effectcraft_engine::time::FrameRate; + use std::path::{Path, PathBuf}; + use std::sync::atomic::AtomicUsize; + + const RATE: FrameRate = FrameRate::FPS_30; + const FRAMES: i64 = 5; + + /// A fresh folder for test `name` (on the build drive, not the system temp folder). + fn folder(name: &str) -> PathBuf { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("../../target/test-frame-files-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A flat grey PNG of `level` at `path`. + fn png(path: &Path, level: u8) -> String { + image::RgbaImage::from_pixel(16, 8, image::Rgba([level, level, level, 255])).save(path).unwrap(); + path.to_string_lossy().to_string() + } + + /// The grey level of sequence frame `i` as first written. + fn level(i: i64) -> u8 { + 20 + i as u8 * 30 + } + + /// A project with a comp showing a sequence of [`FRAMES`] PNGs (in `dir/seq`) and, unused, a + /// sequence of 5000 frames that don't even exist. The files of the shown sequence. + fn project(dir: &Path) -> (Arc, ItemId, Vec) { + let seq_dir = dir.join("seq"); + std::fs::create_dir_all(&seq_dir).unwrap(); + let files: Vec = (0..FRAMES).map(|i| png(&seq_dir.join(format!("f_{i:04}.png")), level(i))).collect(); + let mut seq = Footage { kind: FootageKind::Sequence, sequence: files.clone(), frame_rate: RATE, ..effectcraft_media::probe(&files[0]).unwrap() }; + seq.sync_sequence_duration(); + let unused = Footage { + kind: FootageKind::Sequence, + sequence: (0..5000).map(|i| dir.join("unused").join(format!("big_{i:05}.exr")).to_string_lossy().to_string()).collect(), + frame_rate: RATE, + width: 16, + height: 8, + has_video: true, + ..Default::default() + }; + let mut p = Project::default(); + p.add_item("Unused", effectcraft_engine::color::Label::Aqua, None, ItemKind::Footage(unused)); + let item = p.add_item("Seq", effectcraft_engine::color::Label::Aqua, None, ItemKind::Footage(seq)); + let mut comp = Comp::new(16, 8, RATE, RATE.tick_of(FRAMES)); + comp.layers = vec![build::layer(&mut p, &comp, "Seq", LayerSource::Footage { item }, (16, 8), Some(comp.duration))].into(); + let cid = p.add_item("C", effectcraft_engine::color::Label::None, None, ItemKind::Comp(comp.into())); + (Arc::new(p), cid, files) + } + + /// A session over the disk cache in `dir`: a new preview cache, media pool, layer cache and + /// disk cache instance (as after reopening the project), counting the calls of the hook for + /// files served from memory. + struct Session { + frames: Frames, + src: RenderSource, + disk: Arc, + hook_calls: Arc, + } + + fn session(p: &Arc, dir: &Path) -> Session { + let disk = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + let hook_calls = Arc::new(AtomicUsize::new(0)); + let mut frames = Frames::default(); + let calls = hook_calls.clone(); + frames.set_virtual_id(Arc::new(move |_| { + calls.fetch_add(1, Ordering::Relaxed); + None + })); + let src = RenderSource { + project: p.clone(), + footage: Arc::new(effectcraft_media::MediaPool::new()), + expr: None, + layer_cache: Arc::default(), + gpu: None, + gpu_display: false, + disk: Some(disk.clone()), + }; + Session { frames, src, disk, hook_calls } + } + + impl Session { + fn key(&self, cid: ItemId, frame: i64) -> FrameKey { + FrameKey { + revision: 1, + content: self.frames.content_of(&self.src.project, 1, cid), + comp: cid.0, + frame, + scale: 1000, + view: 0, + opts: opts_hash(&RenderOpts::default()), + } + } + + /// Show `frames` of `cid` (rendered or read from disk); the grey level of each, once + /// their disk writes are done. + fn show(&self, cid: ItemId, frames: &[i64]) -> Vec { + for &f in frames { + self.frames.request(&self.src, self.key(cid, f), cid, RATE.tick_of(f), RenderOpts::default()); + } + wait_for_renders(&self.frames); + // (the worker queues the write after it has released the frame) + for _ in 0..400 { + self.disk.flush(); + if frames.iter().all(|f| self.disk.contains(disk_cache::Kind::Frame, self.disk_key(cid, *f))) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + frames + .iter() + .map(|f| match self.frames.get(&self.key(cid, *f)) { + Some(FrameImage::Cpu(c)) => c.pixels[0].r(), + _ => panic!("frame {f}: an 8-bit CPU frame"), + }) + .collect() + } + + fn disk_key(&self, cid: ItemId, frame: i64) -> u128 { + frame_disk_key(&self.frames.content_keys, &self.src.project, &self.key(cid, frame), opts_hash(&RenderOpts::default())) + } + + /// (disk hits, disk misses) so far. + fn hits(&self) -> (u64, u64) { + let s = self.disk.stats(); + (s.hits, s.misses) + } + } + + fn close(a: u8, b: u8) -> bool { + a.abs_diff(b) <= 2 + } + + /// Give `path` a modification time `secs` later, contents and size unchanged. + fn touch(path: &str, secs: u64) { + let t = std::fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(secs); + std::fs::File::options().append(true).open(path).unwrap().set_modified(t).unwrap(); + } + + /// Correct: a source file of the sequence changes (new contents and size; or only a new + /// time): exactly the frames that read it render again and their entries are replaced; the + /// others come from disk, also after reopening. + #[test] + fn a_changed_source_file_re_renders_exactly_its_frames() { + let dir = folder("correct"); + let (p, cid, files) = project(&dir); + let all: Vec = (0..FRAMES).collect(); + let first = session(&p, &dir); + let shown = first.show(cid, &all); + assert!(all.iter().all(|f| close(shown[*f as usize], level(*f))), "{shown:?}"); + assert_eq!(first.hits(), (0, FRAMES as u64), "rendered, nothing on disk yet"); + assert_eq!(first.disk.stats().entries, FRAMES as usize, "every frame stored"); + drop(first); + // Frame 2's file gets new pixels (and size), frame 3's only a new time. + png(Path::new(&files[2]), 250); + touch(&files[3], 30); + let second = session(&p, &dir); + let shown = second.show(cid, &all); + assert!(close(shown[2], 250), "frame 2 shows its new file: {shown:?}"); + assert!([0, 1, 3, 4].iter().all(|f| close(shown[*f as usize], level(*f))), "{shown:?}"); + assert_eq!(second.hits(), (3, 2), "frames 0, 1 and 4 from disk; 2 and 3 rendered again"); + assert_eq!(second.disk.file_checks(), FRAMES as u64, "one file checked per frame read"); + assert_eq!(second.disk.stats().entries, FRAMES as usize, "the entries of 2 and 3 were replaced"); + drop(second); + // Reopened: every frame from disk, the replaced ones with their new pixels. + let third = session(&p, &dir); + let shown = third.show(cid, &all); + assert_eq!(third.hits(), (FRAMES as u64, 0)); + assert!(close(shown[2], 250) && close(shown[3], level(3)), "{shown:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// No scan: opening a comp of a project that also holds a large sequence, and showing a + /// frame, looks only at the files that frame reads; the comp's key looks at no file (it + /// stays the same when its files change, and never asks for the identity of a path). + #[test] + fn showing_a_frame_checks_only_the_files_it_reads() { + let dir = folder("no-scan"); + let (p, cid, files) = project(&dir); + let key = disk_cache::comp_content_key(&p, cid); + png(Path::new(&files[1]), 99); + touch(&files[2], 5); + assert_eq!(disk_cache::comp_content_key(&p, cid), key, "the key looks at no file"); + let first = session(&p, &dir); + first.show(cid, &[2]); + drop(first); + let again = session(&p, &dir); + // (the indicator's key is computed off the UI thread first) + let mut blue = vec![]; + for _ in 0..400 { + blue = again.frames.disk_frames(&again.src, &again.key(cid, 0), 0..FRAMES, &RenderOpts::default()); + if !blue.is_empty() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(blue, vec![2], "the blue bar: present entries, no file looked at"); + assert_eq!(again.disk.file_checks(), 0, "the indicator checks no file"); + let shown = again.show(cid, &[2]); + assert!(close(shown[0], level(2)), "{shown:?}"); + assert_eq!(again.hits(), (1, 0)); + assert_eq!(again.disk.file_checks(), 1, "only the file frame 2 read"); + assert_eq!(again.hook_calls.load(Ordering::Relaxed), 0, "no path of the unused sequence was asked about"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The frame entry files under the cache folder. + fn entries(dir: &Path) -> Vec { + let mut out = vec![]; + let mut stack = vec![dir.join("cache")]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x == "ecc") && p.to_string_lossy().contains("frames") { + out.push(p); + } + } + } + out + } + + /// Safe: a missing source file, an unreadable one (a folder in its place) and a damaged + /// cache entry never serve the frame from before; each is rendered again and stored anew. + #[test] + fn missing_or_unreadable_files_and_damaged_entries_never_serve_a_stale_frame() { + let dir = folder("safe"); + let (p, cid, files) = project(&dir); + let first = session(&p, &dir); + first.show(cid, &[0]); + assert_eq!(first.disk.stats().entries, 1); + drop(first); + // Missing: not served; the frame is rendered without it. + std::fs::remove_file(&files[0]).unwrap(); + let missing = session(&p, &dir); + let shown = missing.show(cid, &[0]); + assert!(!close(shown[0], level(0)), "the frame from before was served: {shown:?}"); + assert_eq!(missing.hits(), (0, 1)); + drop(missing); + // Back, with other pixels: the entry made while it was missing is not served either. + png(Path::new(&files[0]), 180); + let back = session(&p, &dir); + let shown = back.show(cid, &[0]); + assert!(close(shown[0], 180), "{shown:?}"); + assert_eq!(back.hits(), (0, 1)); + drop(back); + // Unreadable (a folder in its place). + std::fs::remove_file(&files[0]).unwrap(); + std::fs::create_dir(&files[0]).unwrap(); + let unreadable = session(&p, &dir); + let shown = unreadable.show(cid, &[0]); + assert!(!close(shown[0], 180), "the frame from before was served: {shown:?}"); + assert_eq!(unreadable.hits(), (0, 1)); + drop(unreadable); + std::fs::remove_dir(&files[0]).unwrap(); + png(Path::new(&files[0]), 120); + let fresh = session(&p, &dir); + assert!(close(fresh.show(cid, &[0])[0], 120)); + drop(fresh); + // A damaged entry: a miss, rendered, stored again, then served. + let found = entries(&dir); + assert_eq!(found.len(), 1, "{found:?}"); + let mut bytes = std::fs::read(&found[0]).unwrap(); + let n = bytes.len() / 2; + bytes[n] ^= 0x5a; + std::fs::write(&found[0], bytes).unwrap(); + let damaged = session(&p, &dir); + assert!(close(damaged.show(cid, &[0])[0], 120)); + assert_eq!(damaged.hits(), (0, 1)); + drop(damaged); + let healed = session(&p, &dir); + assert!(close(healed.show(cid, &[0])[0], 120)); + assert_eq!(healed.hits(), (1, 0), "the rewritten entry is used"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/ui-egui/tests/it/ui_web_gpu_storage.rs b/crates/ui-egui/tests/it/ui_web_gpu_storage.rs index b015da41b..694d98507 100644 --- a/crates/ui-egui/tests/it/ui_web_gpu_storage.rs +++ b/crates/ui-egui/tests/it/ui_web_gpu_storage.rs @@ -61,7 +61,7 @@ impl RemoteFrames for GpuWorker { fn start(&self, job: RemoteJob, done: RemoteDone) { // The page reads a hit from the disk cache instead of asking the worker. if let Some(k) = job.disk_key - && let Some(f) = self.disk.lock().unwrap().get(&k).and_then(|e| disk_cache::read_frame_entry(e)) + && let Some(f) = self.disk.lock().unwrap().get(&k).and_then(|e| disk_cache::read_frame_entry(e, None)) { return done(Ok(RemoteFrame { width: f.width, height: f.height, rgba: f.rgba, ms: 0.0 })); } @@ -91,8 +91,11 @@ impl RemoteFrames for GpuWorker { match out.into_iter().next() { Some((FrameReply::Frame { width, height, ms, passes, gpu, .. }, Some(rgba))) => { self.rendered.lock().unwrap().push((passes, gpu)); - if let Some(k) = job.disk_key { - self.disk.lock().unwrap().insert(k, disk_cache::frame_entry(width, height, &rgba)); + if let Some(k) = job.disk_key + && let Some(files) = server.take_files() + && let Some(entry) = disk_cache::frame_entry(width, height, &rgba, &files, None) + { + self.disk.lock().unwrap().insert(k, entry); } done(Ok(RemoteFrame { width, height, rgba, ms })) } diff --git a/docs/web.md b/docs/web.md index 1cdecab00..832aa86fe 100644 --- a/docs/web.md +++ b/docs/web.md @@ -332,9 +332,11 @@ pixels. Settings ▸ Disk ▸ Disk Cache works in the browser, backed by the **Origin Private File System** (`src/diskcache.rs`): viewer frames are kept under `effectcraft-cache/v1/frames/<32 hex>.ecc` -between visits, in the desktop cache's format (`disk_cache::frame_entry`: 8-bit premultiplied -RGBA, LZ4, a checksum), keyed by the same content hash (the comp and everything it uses, frame, -scale, view, render options). +between visits, in the desktop cache's format (`disk_cache::frame_entry`: the source files the +frame read with their size and content hash, then 8-bit premultiplied RGBA, LZ4, a checksum), +keyed by the same content hash (the comp and everything it uses as held in memory, frame, scale, +view, render options). The page reads an entry only while the files it lists are unchanged; a +frame whose files can't all be named is not stored. - A render request to a frame worker carries the frame's disk key; the worker posts the frame, then writes the entry with a **synchronous access handle** into a temporary file moved into From 726d78d1c090e6b8eb353a57014f75a726f446b7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 00:12:07 +0100 Subject: [PATCH 019/324] Disk cache: layer entries keep their source files, no footage salt Part of #3184 (step 3 of 4). Layer buffers on disk (and in the browser's layer store) now carry the files they were made of, like frame entries since step 2, and are checked against exactly those files when used. The project-wide footage salt is gone: nothing stamps every footage file any more. - Layer entry format 4: the buffer's EntryFiles, then the pixels. A hit checks only the listed files (metadata, or the VirtualFileId hook for files from memory; Missing must still be missing); a change, a damaged entry or the old format 0 is a miss and the entry is deleted, so the re-rendered buffer replaces it. A hit reports its file list, so frames made of buffers from disk are complete and get stored again. - Buffers whose files can't all be named are not written. - Layer disk keys: layer_disk_key = hash of the layer entry version, the renderer version and the layer cache key (which names the footage items with their paths and settings, from memory). - PrefetchStore checks on use; an entry made of changed files is dropped and forgotten, so the new buffer is queued over it. FrameServer passes its virtual-file hook to its layer cache. - Removed: footage_salt(_with), file_stamp, footage_stamp, set_disk_salt, set_store_salt, Session::refresh_disk_salt, poll_disk_salt, footage_fingerprint, disk_salt, disk_salt_background, disk_salt_job, DiskSaltJob, the UI's per-frame poll, the salt in FrameServer and in the availability worker (with its cache_enabled plumbing). The disk cache is attached as soon as it is configured. - Docs: architecture.md, web.md. Tests: layer entries check their files (size, time, missing/back, folder, damaged, old format, incomplete); virtual files; prefetch store; media tests with a real pool across restarts (only the changed file is read, projects with the same item ids never share an entry, missing, unreadable and damaged never serve stale buffers); engine tests that the cache is attached at once and edits do no file work (#1926, #3106). Co-Authored-By: Claude Opus 5.5 --- apps/effectcraft-web/src/diskcache.rs | 8 +- apps/effectcraft/src/main.rs | 3 - crates/engine/src/background/remote.rs | 25 +- crates/engine/src/background/remote/tests.rs | 3 +- crates/engine/src/footage/availability.rs | 43 +- crates/engine/src/footage/footage_check.rs | 2 +- crates/engine/src/footage/footage_reload.rs | 31 +- crates/engine/src/lib.rs | 13 +- crates/engine/src/session.rs | 2 +- crates/engine/src/session/edit.rs | 117 ----- .../engine/src/settings/session_settings.rs | 9 +- crates/engine/src/tests/disk_cache.rs | 143 ++----- crates/engine/src/tests/sequence.rs | 21 +- crates/media/src/reads/tests.rs | 199 +++++++++ crates/render/src/cache.rs | 251 +++++++---- crates/render/src/disk_cache.rs | 400 ++++++++++-------- crates/render/src/reads.rs | 4 +- crates/ui-egui/src/app/frame.rs | 4 - .../ui-egui/tests/it/ui_unreadable_footage.rs | 3 +- docs/architecture.md | 11 +- docs/web.md | 5 +- 21 files changed, 710 insertions(+), 587 deletions(-) diff --git a/apps/effectcraft-web/src/diskcache.rs b/apps/effectcraft-web/src/diskcache.rs index 5ac655cb0..72e9a9e11 100644 --- a/apps/effectcraft-web/src/diskcache.rs +++ b/apps/effectcraft-web/src/diskcache.rs @@ -21,9 +21,11 @@ //! back their layer caches with a `PrefetchStore`. They report each frame's layer-cache //! misses; before the next request the page names the recent misses that are on disk //! ([`layer_prefetch`], `disk_cache::LayerPrefetch`), and the worker reads those entries -//! into memory before rendering, so the lookups find them. Slow buffers are written by the -//! worker after its frame and indexed here like frames (one least-recently-used order for -//! both kinds). +//! into memory before rendering, so the lookups find them; an entry is used only while the +//! files it lists (the file table's size and content hash) are unchanged, and a buffer whose +//! files can't all be named is not written (#3184). Slow buffers are written by the worker +//! after its frame and indexed here like frames (one least-recently-used order for both +//! kinds). use std::cell::RefCell; diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 07d327a21..5350addbe 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -276,9 +276,6 @@ fn main() -> eframe::Result { // written on background threads (M13.14). session.check_footage_on_open = true; session.autosave.background = true; - // The disk cache's footage stamps too: an imported or opened project with thousands of - // sequence frames on a network share took half a minute to stamp. - session.disk_salt_background = true; // Settings, shortcut presets and the crash-recovery sentinel live in the platform // config directory. Agent-driven runs (`--control`) skip crash recovery. if let Some(dir) = effectcraft_host::config_dir() { diff --git a/crates/engine/src/background/remote.rs b/crates/engine/src/background/remote.rs index ca11d8220..153bb324b 100644 --- a/crates/engine/src/background/remote.rs +++ b/crates/engine/src/background/remote.rs @@ -27,8 +27,9 @@ //! - Layer buffers on disk: with `layers`, the server's layer cache is backed by a //! [`PrefetchStore`] ([`FrameServer::set_layer_store`]): before the request the transport //! fetches the entries named in `prefetch` (recent misses that are on disk, chosen by the -//! page, `disk_cache::LayerPrefetch`), so the lookups in the middle of the render find them; -//! the reply lists the layer keys that missed and those served from the store +//! page, `disk_cache::LayerPrefetch`), so the lookups in the middle of the render find them +//! (each entry keeps the source files its buffer was made of and is used only while they are +//! unchanged, #3184); the reply lists the layer keys that missed and those served from the store //! ([`FrameReply::Frame`] `layer_misses` / `layer_hits`), and slow buffers queue up for the //! transport to write after the frame ([`PrefetchStore::take_writes`], reported as //! [`FrameReply::Stored`] with `layer`). @@ -180,7 +181,7 @@ pub enum FrameReply { passes: u32, #[serde(default)] gpu: bool, - /// Layer-cache lookups that missed the store (salted keys, 32 hex digits). + /// Layer-cache lookups that missed the store (disk keys, 32 hex digits). #[serde(default, rename = "layerMisses", skip_serializing_if = "Vec::is_empty")] layer_misses: Vec, /// Layer buffers served from the store (fetched from disk). @@ -263,9 +264,8 @@ pub struct FrameServer { revision: Option, /// The frame being rendered in passes. pending: Option, - /// The disk cache's layer buffers (see the module docs) and the project's salt. + /// The disk cache's layer buffers (see the module docs). layer_store: Option>, - salt: u64, /// Size and content hash for footage paths with no native metadata (the browser file table). virtual_id: Option Option<(u64, u64)> + Send + Sync>>, /// The source files the last finished frame read ([`FrameServer::take_files`]). @@ -300,15 +300,15 @@ impl FrameServer { revision: None, pending: None, layer_store: None, - salt: 0, virtual_id: None, files: None, } } - /// Identity of virtual footage files, used when native metadata cannot describe the path. - /// Called from `FrameServer::load`, not from the UI thread's cache lookup. + /// Identity of virtual footage files, used when native metadata cannot describe the path: + /// what the disk entries of frames and layer buffers keep for them and are checked against. pub fn set_virtual_id(&mut self, id: Option Option<(u64, u64)> + Send + Sync>>) { + self.cache.set_virtual_id(id.clone()); self.virtual_id = id; } @@ -334,11 +334,6 @@ impl FrameServer { self.layer_store.as_ref() } - /// The salt of the replica's layer keys on disk (keys are `(salt, key)`). - pub fn salt(&self) -> u64 { - self.salt - } - /// Render with `accel` when the request's backend asks for it (the worker's GPU). Its miss /// gate keeps placeholder buffers of unfinished passes out of the layer cache. pub fn set_accel(&mut self, accel: Option>) { @@ -365,8 +360,6 @@ impl FrameServer { fn load(&mut self, revision: u64) -> Result<(), String> { let p = Project::from_json(&self.doc.to_string()).map_err(|e| e.to_string())?; - self.salt = effectcraft_render::disk_cache::footage_salt_with(&p, self.virtual_id.as_deref()); - self.cache.set_store_salt(self.salt); self.project = Some(Arc::new(p)); self.revision = Some(revision); Ok(()) @@ -410,7 +403,7 @@ impl FrameServer { } FrameMsg::Render { id, revision, comp, time, opts, layers, .. } => { let store = self.layer_store.clone().filter(|_| layers); - self.cache.set_store(store.map(|s| (s as Arc, self.salt))); + self.cache.set_store(store.map(|s| s as Arc)); let fail = |error: String, stale: bool| vec![(FrameReply::Failed { id, error, stale }, None)]; if self.revision != Some(revision) { return fail(format!("the replica is at {:?}, not {revision}", self.revision), true); diff --git a/crates/engine/src/background/remote/tests.rs b/crates/engine/src/background/remote/tests.rs index 7a7a59f3f..c35d7a717 100644 --- a/crates/engine/src/background/remote/tests.rs +++ b/crates/engine/src/background/remote/tests.rs @@ -69,7 +69,8 @@ fn layer_buffers_go_through_the_disk_store() { assert!(!layer_misses.is_empty() && layer_hits.is_empty()); let writes = store_a.take_writes(); assert!(!writes.is_empty()); - assert!(writes.iter().all(|(k, _)| (*k >> 64) as u64 == a.salt()), "keys are salted per project"); + // Sealed with the files each buffer was made of (none here: the demo reads no footage). + assert!(writes.iter().all(|(_, e)| effectcraft_render::disk_cache::read_layer_entry(e).is_some_and(|(_, f)| f.is_empty()))); let mut index = DiskIndex::default(); let mut disk = std::collections::HashMap::new(); for (k, e) in writes { diff --git a/crates/engine/src/footage/availability.rs b/crates/engine/src/footage/availability.rs index 7ad2bc03f..75e2a1e1c 100644 --- a/crates/engine/src/footage/availability.rs +++ b/crates/engine/src/footage/availability.rs @@ -215,20 +215,18 @@ impl Scanner { } } -/// A disk observation prepared entirely by the existing worker, including the potentially -/// expensive sequence stamps used for disk-cache keys. The UI only swaps a current snapshot. +/// A disk observation prepared entirely by the existing worker. The UI only swaps a current +/// snapshot (the disk cache needs nothing: its entries check their own files when read, #3184). pub(crate) struct Update { before: Arc, after: Arc, paths: BTreeSet, newly_missing: usize, - cache_enabled: bool, - salt: Option<(u64, u64)>, } -/// Prepare a replacement only when availability changed. Project cloning and optional disk -/// salt computation belong on the worker; apply later rejects an outdated project snapshot. -pub(crate) fn prepare(project: &Arc, sources: &[Source], missing: &[bool], cache_enabled: bool) -> Option { +/// Prepare a replacement only when availability changed. Project cloning belongs on the +/// worker; apply later rejects an outdated project snapshot. +pub(crate) fn prepare(project: &Arc, sources: &[Source], missing: &[bool]) -> Option { let mut after = project.clone(); let mut paths = BTreeSet::new(); let mut newly_missing = 0; @@ -245,22 +243,17 @@ pub(crate) fn prepare(project: &Arc, sources: &[Source], missing: &[boo if paths.is_empty() { return None; } - let salt = cache_enabled.then(|| (Session::footage_fingerprint(&after), crate::render::disk_cache::footage_salt(&after))); - Some(Update { before: project.clone(), after, paths, newly_missing, cache_enabled, salt }) + Some(Update { before: project.clone(), after, paths, newly_missing }) } impl Update { - /// False means a newer project or cache configuration needs a fresh observation. + /// False means a newer project needs a fresh observation. pub fn apply(self, s: &mut Session) -> bool { - if !Arc::ptr_eq(&s.project, &self.before) || s.disk_cache.is_some() != self.cache_enabled { + if !Arc::ptr_eq(&s.project, &self.before) { return false; } let dirty = s.is_dirty(); s.project = self.after; - if let Some((fingerprint, salt)) = self.salt { - s.disk_salt = Some((fingerprint, salt)); - s.layer_cache.set_disk_salt(salt); - } s.bump(); if !dirty { s.mark_saved(); @@ -371,7 +364,7 @@ mod tests { fn stale_observation_cannot_mark_a_replacement_missing() { let (mut s, id) = session(Arc::new(Disk::default())); let old = sources(&s); - let update = prepare(&s.project, &old, &[true, true], false).unwrap(); + let update = prepare(&s.project, &old, &[true, true]).unwrap(); if let ItemKind::Footage(f) = &mut Arc::make_mut(&mut s.project).item_mut(id).unwrap().kind { f.path = "/new.png".into(); } @@ -398,9 +391,12 @@ mod tests { assert_eq!(disk.looks.load(Ordering::Relaxed), 2, "one file per source, no scan of an unmounted folder"); } + /// An availability change does no disk-cache work (#3184): the cache stays attached and + /// no file is looked at for it, on the worker or when the UI applies the observation (it + /// used to stamp every footage file for a new layer salt). #[test] - fn applying_prepared_cache_salt_does_not_restat_files_on_the_ui_thread() { - let dir = std::env::temp_dir().join(format!("ec-availability-salt-{}", std::process::id())); + fn applying_an_availability_change_does_no_disk_cache_work() { + let dir = std::env::temp_dir().join(format!("ec-availability-cache-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("plate.png"); std::fs::write(&file, b"plate").unwrap(); @@ -413,16 +409,13 @@ mod tests { ); let cache = crate::render::disk_cache::DiskCache::open(dir.join("cache"), 1 << 20).unwrap(); s.disk_cache = Some(cache.clone()); - s.layer_cache.set_disk(Some((cache, 0))); + s.layer_cache.set_disk(Some(cache.clone())); s.mark_saved(); - let update = prepare(&s.project, &sources(&s), &[false], true).unwrap(); - let expected = update.salt.unwrap().1; - // The filesystem can change again after the worker's observation. Applying it must - // retain that observation's salt, rather than scan the disk a second time on the UI. + let update = prepare(&s.project, &sources(&s), &[false]).unwrap(); std::fs::remove_file(file).unwrap(); - assert_ne!(crate::render::disk_cache::footage_salt(&update.after), expected); assert!(update.apply(&mut s)); - assert_eq!(s.disk_salt.map(|(_, salt)| salt), Some(expected)); + assert!(s.layer_cache.disk().is_some_and(|d| Arc::ptr_eq(&d, &cache)), "still attached"); + assert_eq!(cache.file_checks(), 0, "no file looked at for the disk cache"); assert!(!s.is_dirty()); drop(s); std::fs::remove_dir_all(dir).unwrap(); diff --git a/crates/engine/src/footage/footage_check.rs b/crates/engine/src/footage/footage_check.rs index 9e941a6ed..42401d195 100644 --- a/crates/engine/src/footage/footage_check.rs +++ b/crates/engine/src/footage/footage_check.rs @@ -272,7 +272,7 @@ mod tests { let id = source.id; let mut recovered = source.footage.clone(); recovered.path = "/new/project/plate.png".into(); - let observed = super::super::availability::prepare(&s.project, std::slice::from_ref(&source), &[true], false).unwrap(); + let observed = super::super::availability::prepare(&s.project, std::slice::from_ref(&source), &[true]).unwrap(); assert!(observed.apply(&mut s)); assert!(matches!(&s.project.item(id).unwrap().kind, ItemKind::Footage(f) if f.missing)); let result = apply(&mut s, vec![(source, Found::Moved(Box::new(recovered)))]); diff --git a/crates/engine/src/footage/footage_reload.rs b/crates/engine/src/footage/footage_reload.rs index 7065620af..4232e1d11 100644 --- a/crates/engine/src/footage/footage_reload.rs +++ b/crates/engine/src/footage/footage_reload.rs @@ -76,7 +76,6 @@ pub struct Watched { reload: BTreeSet, sources: Arc>, project: Option>, - cache_enabled: bool, reload_mode: String, stored_paths: crate::doc_path::StoredPaths, } @@ -85,8 +84,7 @@ impl PartialEq for Watched { /// Compare watched inputs, excluding unrelated project edits whose latest Arc is refreshed /// separately without waking the worker or restarting partial sequence scans. fn eq(&self, other: &Self) -> bool { - self.cache_enabled == other.cache_enabled - && self.stored_paths == other.stored_paths + self.stored_paths == other.stored_paths && self.reload_mode == other.reload_mode && self.reload == other.reload && (Arc::ptr_eq(&self.sources, &other.sources) || self.sources == other.sources) @@ -100,7 +98,6 @@ pub fn watched(s: &Session) -> Watched { reload: automatic_paths(s), sources: Arc::new(if s.check_footage_on_open { availability::sources(s) } else { Vec::new() }), project: Some(s.project.clone()), - cache_enabled: s.disk_cache.is_some(), reload_mode: s.prefs.import.auto_reload_footage.clone(), stored_paths: s.stored_paths.clone(), } @@ -139,10 +136,10 @@ pub struct Scan { } impl Scan { - /// Prepare availability and cache state before the session applies the observation. + /// Prepare the availability change before the session applies the observation. /// Automatic callers construct this result on the worker; explicit commands run inline. fn new(watched: Watched, observation: Observation, policy: ReloadPolicy) -> Self { - let update = watched.project.as_ref().and_then(|p| availability::prepare(p, &watched.sources, &observation.missing, watched.cache_enabled)); + let update = watched.project.as_ref().and_then(|p| availability::prepare(p, &watched.sources, &observation.missing)); Self { watched, observation, update, policy } } @@ -281,7 +278,7 @@ fn reload(s: &mut Session, ids: &[ItemId], undoable: bool) -> crate::Result<(usi } let n = updates.len(); apply_reloads(s, updates, undoable)?; - forget(s, &paths); + forget_media(s, &paths); Ok((n, failed)) } @@ -320,14 +317,8 @@ fn apply_reloads(s: &mut Session, updates: Vec<(ItemId, Footage)>, undoable: boo Ok(()) } -/// Make the media layer and the layer cache let go of `paths`, so renders read them again. -fn forget(s: &mut Session, paths: &BTreeSet) { - forget_media(s, paths); - s.refresh_disk_salt(true); -} - -/// Invalidate decoded and rendered buffers without probing the disk for a new salt. -/// Availability updates already carry their worker-computed salt; content reload refreshes it. +/// Make the media layer and the layer cache let go of `paths`, so renders read them again. The +/// disk cache needs nothing: its entries check the files they were made of when read (#3184). pub(crate) fn forget_media(s: &mut Session, paths: &BTreeSet) { for p in paths { s.footage.forget(p); @@ -374,7 +365,7 @@ pub fn apply_stamps(s: &mut Session, now: Vec<(String, Option)>) -> crate return Ok(json!({"files": 0, "reloaded": 0})); } // Changed frames of image sequences (their items keep their metadata). - forget(s, &changed); + forget_media(s, &changed); let files = changed.len(); s.toast(if reloaded > 0 { format!("Reloaded {reloaded} footage item(s) changed on disk") @@ -391,7 +382,6 @@ pub(crate) fn command(s: &mut Session, _: &Value) -> crate::Result { reload: reload_paths(s), sources: Arc::new(availability::sources(s)), project: Some(s.project.clone()), - cache_enabled: s.disk_cache.is_some(), reload_mode: s.prefs.import.auto_reload_footage.clone(), stored_paths: s.stored_paths.clone(), }; @@ -452,12 +442,7 @@ impl Watcher { pub fn update(&mut self, s: &Session) { let same_sources = availability::sources_match(s, &self.paths.sources); let same_data = self.paths.project.as_ref().is_some_and(|before| data_paths(before).eq(data_paths(&s.project))); - if same_sources - && same_data - && self.paths.stored_paths == s.stored_paths - && self.paths.reload_mode == s.prefs.import.auto_reload_footage - && self.paths.cache_enabled == s.disk_cache.is_some() - { + if same_sources && same_data && self.paths.stored_paths == s.stored_paths && self.paths.reload_mode == s.prefs.import.auto_reload_footage { let project = Some(s.project.clone()); self.paths.project = project.clone(); self.pending.lock().unwrap_or_else(PoisonError::into_inner).paths.project = project; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e50b15d04..69d1f9e1b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -97,7 +97,7 @@ pub use error::{EngineError, Result}; pub use event::Event; pub use fonts::{FontRow, font_features, font_menu, font_preview, font_styles, text_families}; pub use services::{FsServices, Importer, Services}; -pub use session::{DiskSaltJob, upgrade_effects}; +pub use session::upgrade_effects; pub struct Session { pub project: Arc, @@ -254,14 +254,6 @@ pub struct Session { /// Each footage file's size and modification time when last seen (Settings ▸ Import ▸ /// Reload Footage Changed on Disk, [`footage_reload`]). pub footage_stamps: std::collections::HashMap, - /// The disk cache's footage salt and the footage it was taken for ([`Session::refresh_disk_salt`]). - pub disk_salt: Option<(u64, u64)>, - /// Take the disk cache's footage salt on a worker thread ([`Session::refresh_disk_salt`]): - /// frontends with an event loop (the desktop app) turn this on and call - /// [`Session::poll_disk_salt`] each frame; headless sessions take it at once. - pub disk_salt_background: bool, - /// The footage salt being taken in the background. - pub disk_salt_job: Option, /// The footage files effects read the channels of, as last given to the footage source /// ([`Session::refresh_aux_footage`]); `None` = not given yet. pub aux_footage: Option>, @@ -391,9 +383,6 @@ impl Default for Session { check_footage_on_open: false, stored_paths: Default::default(), footage_stamps: Default::default(), - disk_salt: None, - disk_salt_background: false, - disk_salt_job: None, aux_footage: None, script_calls: ScriptCalls::default(), } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 31ed40c1d..18b0ff4cf 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,4 +10,4 @@ mod dispatch; mod edit; mod render; -pub use edit::{DiskSaltJob, upgrade_effects}; +pub use edit::upgrade_effects; diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 28813e2ec..67a8e4dcb 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -97,114 +97,10 @@ impl Session { if Arc::ptr_eq(&self.project, &self.saved_project) { self.saved_revision = self.revision; } - self.refresh_disk_salt(false); self.refresh_aux_footage(); self.events.push(Event::ProjectChanged { revision: self.revision }); } - /// Salt the disk cache's layer keys with the project's footage files - /// ([`effectcraft_render::disk_cache::footage_salt`]) and attach the disk cache to the layer - /// cache with it. Taking it reads the size and time of every file, every frame of an image - /// sequence included, so it is taken again only when the footage items changed, or with - /// `force` (a project opened, footage reloaded, the disk cache attached), not at every edit: - /// with a few large sequences that cost each keystroke in a text field over half a second - /// (#1926). - /// - /// With [`Session::disk_salt_background`] the files are read on a worker thread: an imported - /// or opened project with thousands of sequence frames on a network share took half a minute - /// to stamp, all of it on the UI thread. Until [`Session::poll_disk_salt`] picks the salt up, - /// renders use the memory cache only (keys under the old salt may name other files, or - /// another project's items) and this returns `None`. - pub fn refresh_disk_salt(&mut self, force: bool) -> Option { - let Some(dc) = self.disk_cache.clone() else { - self.disk_salt = None; - self.disk_salt_job = None; - return None; - }; - self.poll_disk_salt(); - let footage = Self::footage_fingerprint(&self.project); - if !force { - if let Some((seen, salt)) = self.disk_salt - && seen == footage - { - return Some(salt); - } - if self.disk_salt_job.as_ref().is_some_and(|j| j.footage == footage) { - return None; - } - } - if self.disk_salt_background && !cfg!(target_arch = "wasm32") { - let project = self.project.clone(); - let slot: Arc>> = Arc::default(); - let out = slot.clone(); - let spawned = std::thread::Builder::new().name("ec-disk-salt".into()).spawn(move || { - let salt = effectcraft_render::disk_cache::footage_salt(&project); - if let Ok(mut s) = out.lock() { - *s = Some(salt); - } - }); - // Without a thread the salt is taken here, as before. - if let Ok(thread) = spawned { - self.disk_salt = None; - self.disk_salt_job = Some(DiskSaltJob { footage, slot, thread }); - self.layer_cache.set_disk(None); - return None; - } - } - self.disk_salt_job = None; - let salt = effectcraft_render::disk_cache::footage_salt(&self.project); - self.disk_salt = Some((footage, salt)); - self.layer_cache.set_disk(Some((dc, salt))); - Some(salt) - } - - /// Pick up a footage salt taken in the background ([`Session::refresh_disk_salt`]) and attach - /// the disk cache with it. Returns whether one is still being taken (frontends call this each - /// frame while it is). - pub fn poll_disk_salt(&mut self) -> bool { - let Some(job) = &self.disk_salt_job else { return false }; - // (looked at first: a worker that has finished has left its salt in the slot) - let finished = job.thread.is_finished(); - let salt = job.slot.lock().ok().and_then(|mut s| s.take()); - let footage = job.footage; - match salt { - Some(salt) => { - self.disk_salt_job = None; - if let Some(dc) = self.disk_cache.clone() { - self.disk_salt = Some((footage, salt)); - self.layer_cache.set_disk(Some((dc, salt))); - } - false - } - None if finished => { - // The worker stopped without a salt: the disk cache stays off until the next - // edit takes it again. - log::warn!("disk cache: the footage files could not be stamped; the disk cache is off until the next edit"); - self.disk_salt_job = None; - false - } - None => true, - } - } - - /// In-memory identity of the footage settings represented by a disk salt. Workers use the - /// same fingerprint when preparing availability changes without disk access on the UI. - pub(crate) fn footage_fingerprint(project: &effectcraft_project::Project) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - for (id, item) in &project.items { - if let effectcraft_project::ItemKind::Footage(f) = &item.kind { - id.hash(&mut h); - format!("{f:?}").hash(&mut h); - } - if let Some(proxy) = &item.proxy { - id.hash(&mut h); - format!("{proxy:?}").hash(&mut h); - } - } - h.finish() - } - /// Set a comp's Resolution. As in After Effects it is saved with the project (which becomes /// modified) but is no undo step, and it changes no pixels: the comp's cached frames stay /// valid ([`effectcraft_project::Comp::same_pixels`]). @@ -322,11 +218,6 @@ impl Session { } self.layer_cache.clear(); self.project = Arc::new(p); - // Its files may have changed since they were last stamped. - self.disk_salt = None; - // A salt still being taken is for the old project's files: dropped, so that the next refresh - // stamps the new project anew (a matching fingerprint would otherwise keep the stale job). - self.disk_salt_job = None; // The set of footage effects read the channels of is sent again, even when it is empty. self.aux_footage = None; self.history = History::default(); @@ -389,11 +280,3 @@ pub fn upgrade_effects(p: &mut Project) { p.next_id = next; p.schema = effectcraft_project::SCHEMA_VERSION; } - -/// A footage salt being taken on a worker thread ([`Session::refresh_disk_salt`]). -pub struct DiskSaltJob { - /// The footage it is taken for ([`Session::footage_fingerprint`]). - footage: u64, - slot: Arc>>, - thread: std::thread::JoinHandle<()>, -} diff --git a/crates/engine/src/settings/session_settings.rs b/crates/engine/src/settings/session_settings.rs index 056616201..b479963ed 100644 --- a/crates/engine/src/settings/session_settings.rs +++ b/crates/engine/src/settings/session_settings.rs @@ -137,10 +137,6 @@ impl Session { // over the store of a roto test running beside it. Serialise them with the roto tests. #[cfg(test)] crate::tests::roto::hold_roto_cache_test_lock(); - // Another setting changed (the disk cache stays as it is): its salt still holds, and - // stamping every footage file again would cost each settings change seconds with large - // sequences. - let kept = self.disk_cache.as_ref().is_some_and(|c| c.folder() == folder.as_path()); let dc = match &self.disk_cache { Some(c) if c.folder() == folder.as_path() => { c.set_max_bytes(max); @@ -165,8 +161,9 @@ impl Session { self.disk_cache = Some(dc.clone()); // The reserve applies from the start (a new folder's watcher is idle). self.poll_disk_space(); - // Attaches the disk cache to the layer cache once the footage salt is known. - self.refresh_disk_salt(!kept); + // Used at once (no file is looked at first: each entry checks the source files it lists + // when it is read, #3184). + self.layer_cache.set_disk(Some(dc.clone())); // Roto Brush / Object Matte segmentations persist there too (held weakly: switching the // disk cache off drops it). let store: std::sync::Arc = dc.clone(); diff --git a/crates/engine/src/tests/disk_cache.rs b/crates/engine/src/tests/disk_cache.rs index 4805d68fe..e2b1544b3 100644 --- a/crates/engine/src/tests/disk_cache.rs +++ b/crates/engine/src/tests/disk_cache.rs @@ -76,11 +76,13 @@ fn disk_cache_settings_persistence_and_invalidation() { assert!(s2.layer_cache.disk().is_none()); } +/// The comp key comes from the project in memory: a footage file that changes on disk doesn't +/// change it (the entries check their own files, #3184); edits that change pixels do. #[test] -fn footage_changes_change_the_salt() { - let dir = folder("salt"); +fn comp_content_keys_come_from_memory() { + let dir = folder("keys"); let mut s = session(&dir); - let foot = std::env::temp_dir().join(format!("effectcraft-salt-{}.png", std::process::id())); + let foot = std::env::temp_dir().join(format!("effectcraft-keys-{}.png", std::process::id())); std::fs::write(&foot, b"one").unwrap(); s.edit("add", None, |p, _| { let f = effectcraft_project::Footage { @@ -108,12 +110,10 @@ fn footage_changes_change_the_salt() { Ok(()) }) .unwrap(); - let a = effectcraft_render::disk_cache::footage_salt(&s.project); - std::fs::write(&foot, b"two, longer").unwrap(); - let b = effectcraft_render::disk_cache::footage_salt(&s.project); - assert_ne!(a, b); let cid = project(&mut s); let k1 = effectcraft_render::disk_cache::comp_content_key(&s.project, cid); + std::fs::write(&foot, b"two, longer").unwrap(); + assert_eq!(effectcraft_render::disk_cache::comp_content_key(&s.project, cid), k1, "no file is looked at"); s.execute("prop.set", json!({"layer": "#1", "path": "transform/opacity", "value": 50})).unwrap(); let k2 = effectcraft_render::disk_cache::comp_content_key(&s.project, cid); assert_ne!(k1, k2); @@ -137,66 +137,51 @@ fn footage_changes_change_the_salt() { assert_ne!(set_proxy(&mut s, false), k3); } -/// The desktop app stamps footage files for the disk cache's salt on a worker thread: importing an -/// After Effects project with thousands of sequence frames on a network share stamped them all -/// inside the import's edit, freezing the UI for half a minute. Until the salt lands the disk -/// cache sits out (keys under the old salt may name other files); a newer footage change -/// supersedes a salt still being taken; a settings change keeps the salt. +/// No salt and no scan (#3184, replacing the background footage salt of #3106): the disk cache +/// is attached to the layer cache as soon as it is switched on, and stays attached through +/// edits that add footage (a large image sequence included), settings changes and opening a +/// project, none of which looks at a single file for it. The first render may use it at once. #[test] -fn footage_salt_is_taken_off_the_ui_thread_and_the_disk_cache_waits_for_it() { - let dir = folder("bg-salt"); +fn the_disk_cache_is_attached_at_once_and_edits_do_no_file_work() { + let dir = folder("attach"); let mut s = session(&dir); - s.disk_salt_background = true; - let at = |n: &str| std::env::temp_dir().join(format!("effectcraft-bg-salt-{}-{n}.png", std::process::id())); - let add = |s: &mut Session, path: &std::path::Path| { - let f = effectcraft_project::Footage { - path: path.to_string_lossy().to_string(), - kind: effectcraft_project::FootageKind::Still, - width: 1, - height: 1, - has_video: true, - ..Default::default() - }; - s.edit("add", None, |p, _| { - p.add_item("f.png", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)); - Ok(()) - }) - .unwrap(); + let dc = s.disk_cache.clone().unwrap(); + let attached = |s: &Session| s.layer_cache.disk().is_some_and(|d| std::sync::Arc::ptr_eq(&d, &dc)); + assert!(attached(&s), "attached at once"); + // A sequence of 5000 frames that don't even exist. + let seq_dir = std::env::temp_dir().join(format!("effectcraft-no-scan-{}", std::process::id())); + let f = effectcraft_project::Footage { + path: seq_dir.join("f_00000.exr").to_string_lossy().to_string(), + kind: effectcraft_project::FootageKind::Sequence, + sequence: (0..5000).map(|i| seq_dir.join(format!("f_{i:05}.exr")).to_string_lossy().to_string()).collect(), + width: 8, + height: 8, + has_video: true, + ..Default::default() }; - let wait = |s: &mut Session| { - let t0 = std::time::Instant::now(); - while s.poll_disk_salt() { - assert!(t0.elapsed().as_secs() < 20, "the salt never landed"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - }; - assert!(s.layer_cache.disk().is_some(), "attached with its salt"); - std::fs::write(at("a"), b"one").unwrap(); - add(&mut s, &at("a")); - // The edit returned before the files were stamped, and the disk cache waits for the salt. - assert!(s.disk_salt.is_none() && s.layer_cache.disk().is_none()); - // Edits that leave the footage alone don't start over (and may pick up the salt meanwhile). - s.execute("comp.new", json!({"name": "C", "width": 8, "height": 8, "frameRate": 30, "duration": 1})).unwrap(); - let r = s.refresh_disk_salt(false); - assert!(r.is_none() || r == Some(effectcraft_render::disk_cache::footage_salt(&s.project)), "{r:?}"); - // New footage while it is taken: the salt for the newest footage lands. - std::fs::write(at("b"), b"two").unwrap(); - add(&mut s, &at("b")); - wait(&mut s); - let salt = effectcraft_render::disk_cache::footage_salt(&s.project); - assert_eq!(s.disk_salt.map(|(_, salt)| salt), Some(salt)); - assert_eq!(s.refresh_disk_salt(false), Some(salt)); - assert!(s.layer_cache.disk().is_some(), "attached again"); - // Another setting keeps the salt and the disk cache attached. + s.edit("add", None, |p, _| { + p.add_item("seq", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)); + Ok(()) + }) + .unwrap(); + assert!(attached(&s), "an import keeps it attached"); + let cid = project(&mut s); + s.execute("prop.set", json!({"layer": "#1", "path": "transform/opacity", "value": 50})).unwrap(); s.execute_checked("prefs.set", json!({"key": "disk.diskCacheMaxGb", "value": 30})).unwrap(); - assert!(s.layer_cache.disk().is_some() && s.disk_salt.map(|(_, salt)| salt) == Some(salt)); - // Turned off and on again: stamped anew, in the background. + assert!(attached(&s), "edits and other settings keep it attached"); + let same = (*s.project).clone(); + s.replace_project(same, None); + assert!(attached(&s), "opening a project keeps it attached"); + // The first render uses it: a solid reads no file, so nothing is checked either. + s.render(cid, s.time(), RenderOpts::default()); + dc.flush(); + assert!(dc.stats().entries > 0, "written by the first render"); + assert_eq!(dc.file_checks(), 0, "no file looked at for the disk cache"); + // Switched off and on: attached again at once. s.execute_checked("prefs.set", json!({"key": "disk.diskCacheEnabled", "value": false})).unwrap(); + assert!(s.layer_cache.disk().is_none()); s.execute_checked("prefs.set", json!({"key": "disk.diskCacheEnabled", "value": true})).unwrap(); - wait(&mut s); - assert_eq!(s.refresh_disk_salt(false), Some(salt)); - let _ = std::fs::remove_file(at("a")); - let _ = std::fs::remove_file(at("b")); + assert!(s.layer_cache.disk().is_some()); } /// Marker edits keep the disk key (the sound of a playing preview must not wait for frames to @@ -257,39 +242,3 @@ fn protected_markers_with_a_duration_change_the_content_key() { s.execute("markers.set", json!({"comp": inner.0, "index": index, "duration": 2.0})).unwrap(); assert_ne!(key(&s), k1, "its duration"); } - -/// A project opened while a footage salt is still being taken must not keep that salt when it -/// names the same footage: its files may have changed since the worker read them. -#[test] -fn opening_a_project_drops_the_footage_salt_being_taken() { - let dir = folder("bg-salt-open"); - let mut s = session(&dir); - s.disk_salt_background = true; - let path = std::env::temp_dir().join(format!("effectcraft-bg-salt-open-{}.png", std::process::id())); - std::fs::write(&path, b"one").unwrap(); - let f = effectcraft_project::Footage { - path: path.to_string_lossy().to_string(), - kind: effectcraft_project::FootageKind::Still, - width: 1, - height: 1, - has_video: true, - ..Default::default() - }; - s.edit("add", None, |p, _| { - p.add_item("f.png", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)); - Ok(()) - }) - .unwrap(); - // The file changes after the edit started the salt, before the same footage is opened again. - std::fs::write(&path, b"a longer content").unwrap(); - let same = (*s.project).clone(); - s.replace_project(same, None); - let t0 = std::time::Instant::now(); - while s.poll_disk_salt() { - assert!(t0.elapsed().as_secs() < 20, "the salt never landed"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - let now = effectcraft_render::disk_cache::footage_salt(&s.project); - assert_eq!(s.disk_salt.map(|(_, salt)| salt), Some(now), "the salt reflects the file as it is now"); - let _ = std::fs::remove_file(&path); -} diff --git a/crates/engine/src/tests/sequence.rs b/crates/engine/src/tests/sequence.rs index cf6968e3f..2189a36a8 100644 --- a/crates/engine/src/tests/sequence.rs +++ b/crates/engine/src/tests/sequence.rs @@ -268,30 +268,31 @@ fn dpx_and_cineon_runs_import_as_sequences() { assert_eq!(got, [("plate.[0001-0003].dpx".to_string(), 3), ("scan_[01-02].cin".to_string(), 2)], "{r}"); } -/// #1926: an edit that leaves the footage alone doesn't stamp every frame of its image sequences -/// again for the disk cache's salt (with large sequences each keystroke in a text field took over -/// half a second); Reload Footage does, and so does new footage. +/// #1926, #3184: an edit does no file work at all for the disk cache (it used to stamp every +/// frame of the project's image sequences for a salt; with large sequences each keystroke in a +/// text field took over half a second): the cache stays attached and no file is looked at, after +/// edits, after a frame of the sequence was rewritten, after Reload Footage and new footage. +/// Entries check the files they list when they are read instead. #[test] -fn edits_keep_the_disk_salt_and_reload_stamps_the_files_again() { +fn edits_do_no_disk_cache_file_work() { let dir = folder(&RUN); - let cache = std::env::temp_dir().join(format!("ec-seq-salt-{}", std::process::id())); + let cache = std::env::temp_dir().join(format!("ec-seq-nofiles-{}", std::process::id())); let _ = std::fs::remove_dir_all(&cache); let mut s = session(); s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": cache.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap(); + let dc = s.disk_cache.clone().expect("a disk cache"); + let attached = |s: &Session| s.layer_cache.disk().is_some_and(|d| std::sync::Arc::ptr_eq(&d, &dc)); s.execute("comp.new", json!({"name": "C", "width": 64, "height": 32, "frameRate": 30, "duration": 1})).unwrap(); let r = s.execute("file.import", json!({"paths": [at(&dir, "shot_0002.png")], "sequence": true, "addToComp": true})).unwrap(); let item = r["items"][0].clone(); - let salt = s.refresh_disk_salt(false).expect("a disk cache"); // A frame rewritten in place: same footage settings, another size on disk. std::fs::write(at(&dir, "shot_0004.png"), b"a new render of this frame").unwrap(); s.execute("layer.newText", json!({"text": "title"})).unwrap(); s.execute("layer.setText", json!({"text": "title 2"})).unwrap(); - assert_eq!(s.refresh_disk_salt(false), Some(salt), "edits don't stamp the files again"); s.execute("file.reloadFootage", json!({"items": [item]})).unwrap(); - let reloaded = s.refresh_disk_salt(false).unwrap(); - assert_ne!(reloaded, salt, "Reload Footage stamps them again"); std::fs::write(at(&dir, "extra.png"), b"").unwrap(); s.execute("file.import", json!({"paths": [at(&dir, "extra.png")]})).unwrap(); - assert_ne!(s.refresh_disk_salt(false), Some(reloaded), "new footage counts"); + assert!(attached(&s), "attached all along"); + assert_eq!(dc.file_checks(), 0, "no file looked at for the disk cache"); let _ = std::fs::remove_dir_all(&cache); } diff --git a/crates/media/src/reads/tests.rs b/crates/media/src/reads/tests.rs index 8fee7d211..5dae8415a 100644 --- a/crates/media/src/reads/tests.rs +++ b/crates/media/src/reads/tests.rs @@ -189,3 +189,202 @@ fn a_frame_served_from_memory_reports_its_files_without_touching_them() { assert_eq!(from_pool, first); assert_eq!(crate::opens_under(&dir), opened, "nothing was opened on disk"); } + +// ---------------------------------------------------------------- layer entries on disk (#3184) + +use std::sync::Arc; + +use effectcraft_render::disk_cache::{DiskCache, Kind}; + +/// A "session": a new media pool and layer cache over the disk cache in `cache` (opened anew, +/// as after a restart), writing every layer buffer however quick to render. +fn session(cache: &Path) -> (MediaPool, LayerCache, Arc) { + let dc = DiskCache::open(cache, 1 << 30).unwrap(); + dc.set_min_layer_ms(0); + let lc = LayerCache::default(); + lc.set_disk(Some(dc.clone())); + (MediaPool::new(), lc, dc) +} + +/// Give `path` a later modification time, so a rewrite within the clock's resolution counts. +fn touch_later(path: &Path) { + let t = std::fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(path).unwrap().set_modified(t).unwrap(); +} + +/// Two still plates (the upper one at half opacity, so both show), and a 5000-frame sequence +/// in the project that no layer uses (its files don't even exist). +fn plates(dir: &Path) -> (Project, ItemId, PathBuf) { + let mut p = Project::default(); + let c = comp(); + let a = dir.join("a.png"); + let mut top = footage_layer(&mut p, &c, "A", still(&a, 60)); + top.props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(50.0); + let bottom = footage_layer(&mut p, &c, "B", still(&dir.join("b.png"), 200)); + let unused = dir.join("unused"); + let seq = Footage { + kind: FootageKind::Sequence, + sequence: (0..5000).map(|i| unused.join(format!("big_{i:05}.exr")).to_string_lossy().to_string()).collect(), + frame_rate: RATE, + width: SIZE.0, + height: SIZE.1, + has_video: true, + ..Default::default() + }; + p.add_item("Unused", Label::Aqua, None, ItemKind::Footage(seq)); + let cid = add_comp(&mut p, "C", c, vec![top, bottom]); + (p, cid, a) +} + +/// Correct and no scan: after a restart, only the layer buffer whose source file changed is +/// rendered again (only that file is opened); the other comes from disk with its file list, so +/// the frame's list is complete again (its frame entry can be stored). The disk cache checks +/// exactly the files its entries list, never the unused sequence. The re-rendered buffer +/// replaces its entry: the next restart opens nothing. +#[test] +fn a_changed_file_renders_only_the_layer_buffers_that_read_it_again() { + let dir = folder("layer-disk"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let (p, cid, a) = plates(&src); + let (pool, lc, dc) = session(&cache); + let (px, files) = render(&p, &pool, &lc, cid, 0); + assert!(files.is_complete() && files.len() == 2, "{:?}", paths(&files)); + dc.flush(); + let entries = dc.keys(Kind::Layer).len(); + assert!(entries >= 2, "both plates' buffers are on disk: {entries}"); + drop((pool, lc, dc)); + + // Restart without a change: everything from disk, nothing opened, a complete list. + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (again, files_again) = render(&p, &pool, &lc, cid, 0); + assert_eq!(again, px); + assert_eq!(files_again, files, "the files of the entries, as they were read"); + assert!(files_again.is_complete(), "a frame made of buffers from disk can be stored"); + assert_eq!(crate::opens_under(&src), opened, "nothing opened"); + let checks = dc.file_checks(); + assert!(checks >= 2 && checks as usize <= entries, "one check per entry used: {checks} of {entries}"); + drop((pool, lc, dc)); + + // a.png gets new pixels: only the top plate renders again. + png(&a, 120); + touch_later(&a); + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (changed, files_changed) = render(&p, &pool, &lc, cid, 0); + assert_ne!(changed, px, "the new pixels show"); + assert_eq!(crate::opens_under(&src) - opened, 1, "only the changed file is read"); + assert!(files_changed.is_complete() && files_changed.len() == 2); + assert_stamps_match_disk(&files_changed); + assert!(dc.file_checks() as usize <= entries, "only listed files are checked"); + assert_eq!(crate::opens_under(&src.join("unused")), 0); + dc.flush(); + drop((pool, lc, dc)); + + // Its entry was replaced: the next restart opens nothing and shows the new pixels. + let (pool, lc, _dc) = session(&cache); + let opened = crate::opens_under(&src); + let (last, _) = render(&p, &pool, &lc, cid, 0); + assert_eq!(last, changed); + assert_eq!(crate::opens_under(&src), opened, "both from disk"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two projects whose footage items have the same ids but name different files never share a +/// layer entry: the layer key names the item's path and settings. +#[test] +fn projects_with_the_same_item_ids_never_share_a_layer_entry() { + let dir = folder("layer-disk-projects"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let mut p = Project::default(); + let c = comp(); + let layer = footage_layer(&mut p, &c, "Plate", still(&src.join("one.png"), 40)); + let LayerSource::Footage { item } = layer.source else { panic!("a footage layer") }; + let cid = add_comp(&mut p, "C", c, vec![layer]); + let mut other = p.clone(); + other.item_mut(item).unwrap().kind = ItemKind::Footage(still(&src.join("two.png"), 220)); + let (pool, lc, dc) = session(&cache); + let (one, _) = render(&p, &pool, &lc, cid, 0); + dc.flush(); + drop((pool, lc, dc)); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + let (two, files) = render(&other, &pool, &lc, cid, 0); + assert!((two[0] - 220.0 / 255.0).abs() < 0.01, "the other project's own file shows: {two:?}"); + assert_ne!(two, one); + assert_eq!(dc.stats().hits, hits, "no entry of the first project is used"); + assert_eq!(paths(&files), [src.join("two.png").to_string_lossy().to_string()]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Safe: a damaged layer entry, a source file that is missing, one replaced by something +/// unreadable (a folder), and one back with other pixels never serve a stale buffer after a +/// restart; the damaged entry is rendered again, replaced and then used. +#[test] +fn missing_unreadable_files_and_damaged_layer_entries_never_serve_stale_buffers() { + let dir = folder("layer-disk-safe"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let mut p = Project::default(); + let c = comp(); + let path = src.join("plate.png"); + let layer = footage_layer(&mut p, &c, "Plate", still(&path, 90)); + let cid = add_comp(&mut p, "C", c, vec![layer]); + let (pool, lc, dc) = session(&cache); + let (shown, _) = render(&p, &pool, &lc, cid, 0); + assert!(shown[3] > 0.99, "the plate shows: {shown:?}"); + dc.flush(); + drop((pool, lc, dc)); + + // A damaged entry: a miss, deleted, rendered again and stored anew. + let layers = cache.join("v1").join(Kind::Layer.dir()); + for shard in std::fs::read_dir(&layers).unwrap().flatten() { + for f in std::fs::read_dir(shard.path()).unwrap().flatten() { + let mut d = std::fs::read(f.path()).unwrap(); + let n = d.len() / 2; + d[n] ^= 0x5a; + std::fs::write(f.path(), d).unwrap(); + } + } + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (again, files) = render(&p, &pool, &lc, cid, 0); + assert_eq!(again, shown); + assert_eq!(crate::opens_under(&src) - opened, 1, "read again, not served from the damaged entry"); + assert!(files.is_complete()); + dc.flush(); + drop((pool, lc, dc)); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + assert_eq!(render(&p, &pool, &lc, cid, 0).0, shown); + assert!(dc.stats().hits > hits, "the rewritten entry is used"); + drop((pool, lc, dc)); + + // The file is gone: not the old plate. + std::fs::remove_file(&path).unwrap(); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + let (gone, files) = render(&p, &pool, &lc, cid, 0); + assert!(gone[3] < 0.01, "a missing file shows nothing, never the cached plate: {gone:?}"); + assert_eq!(dc.stats().hits, hits); + assert!(files.files().iter().all(|f| f.stamp == FileStamp::Missing), "{files:?}"); + dc.flush(); + drop((pool, lc, dc)); + + // Something unreadable at its path (a folder): still not the old plate. + std::fs::create_dir(&path).unwrap(); + let (pool, lc, _dc) = session(&cache); + let (unreadable, _) = render(&p, &pool, &lc, cid, 0); + assert!(unreadable[3] < 0.01, "{unreadable:?}"); + std::fs::remove_dir(&path).unwrap(); + + // Back with other pixels: those show, not the entry made of the old file. + png(&path, 240); + touch_later(&path); + let (pool, lc, _dc) = session(&cache); + let (back, _) = render(&p, &pool, &lc, cid, 0); + assert!((back[0] - 240.0 / 255.0).abs() < 0.01, "{back:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 79b948b89..22c0ebf7f 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -24,6 +24,7 @@ use std::sync::{Arc, Mutex}; use effectcraft_effects::Buf; use effectcraft_project::{FootageKind, ItemKind, Layer, LayerSource, Node, PropGroup}; +use crate::disk_cache::{EntryFiles, SharedVirtualFileId, VirtualFileId, layer_disk_key}; use crate::eval::EvalCtx; use crate::reads::ReadFiles; @@ -31,13 +32,17 @@ mod dependencies; /// Thread-safe, memory-budgeted cache of processed layer buffers, optionally backed by the /// persistent [`DiskCache`](crate::disk_cache::DiskCache): a memory miss reads the disk, and -/// buffers that were slow to render are written there (keys salted per project, see -/// [`LayerCache::set_disk`]). +/// buffers that were slow to render are written there with the source files they were made of +/// (keys: [`crate::disk_cache::layer_disk_key`]; an entry is used only while its files are +/// unchanged, #3184). pub struct LayerCache { inner: Mutex, - disk: Mutex, u64)>>, + disk: Mutex>>, /// Another persistent store when there is no disk cache (the browser's, [`PrefetchStore`]). - store: Mutex, u64)>>, + store: Mutex>>, + /// Size and content hash of files served from memory (the browser file table), to store + /// and check the source files of persistent entries. + virtual_id: Mutex>, /// While set, inserts are dropped (see [`LayerCache::set_gate`]). gate: Mutex>>, } @@ -83,6 +88,7 @@ impl LayerCache { inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0, missed_at: HashMap::new() }), disk: Mutex::new(None), store: Mutex::new(None), + virtual_id: Mutex::new(None), gate: Mutex::new(None), } } @@ -101,58 +107,49 @@ impl LayerCache { self.gate.lock().ok().and_then(|g| g.as_ref().map(|g| g.load(std::sync::atomic::Ordering::Relaxed))).unwrap_or(false) } - /// Attach (or detach) the disk cache. `salt` separates projects and footage versions (see - /// `footage_salt`); keys on disk are `(salt, key)`. - pub fn set_disk(&self, disk: Option<(Arc, u64)>) { + /// Attach (or detach) the disk cache. It is used at once: its entries check their own + /// source files when read, so nothing has to be looked at first. + pub fn set_disk(&self, disk: Option>) { if let Ok(mut d) = self.disk.lock() { *d = disk; } } - /// Change the disk salt (after footage changed) keeping the attached disk cache. - pub fn set_disk_salt(&self, salt: u64) { - if let Ok(mut d) = self.disk.lock() - && let Some((_, s)) = d.as_mut() - { - *s = salt; - } - } - pub fn disk(&self) -> Option> { - self.disk.lock().ok()?.as_ref().map(|d| d.0.clone()) + self.disk.lock().ok()?.clone() } /// Attach (or detach) a [`LayerStore`] used when no disk cache is attached (the browser's - /// Origin Private File System through a [`PrefetchStore`]); `salt` as in - /// [`LayerCache::set_disk`]. - pub fn set_store(&self, store: Option<(Arc, u64)>) { + /// Origin Private File System through a [`PrefetchStore`]). + pub fn set_store(&self, store: Option>) { if let Ok(mut s) = self.store.lock() { *s = store; } } - /// Change the store's salt (a new project or footage), keeping the store. - pub fn set_store_salt(&self, salt: u64) { - if let Ok(mut d) = self.store.lock() - && let Some((_, s)) = d.as_mut() - { - *s = salt; + /// Size and content hash of files served from memory (the browser file table): what a + /// persistent entry keeps for them and checks them against. + pub fn set_virtual_id(&self, id: Option) { + if let Ok(mut v) = self.virtual_id.lock() { + *v = id; } } - fn disk_key(&self, key: u64) -> Option<(Arc, u128)> { - let salted = |salt: u64| ((salt as u128) << 64) | key as u128; - if let Some((dc, salt)) = self.disk.lock().ok()?.as_ref() { - return Some((dc.clone() as Arc, salted(*salt))); + fn virtual_id(&self) -> Option { + self.virtual_id.lock().ok()?.clone() + } + + /// The persistent store behind the memory: the disk cache, else the other store. + fn persistent(&self) -> Option> { + if let Some(dc) = self.disk.lock().ok()?.as_ref() { + return Some(dc.clone() as Arc); } - let s = self.store.lock().ok()?; - let (st, salt) = s.as_ref()?; - Some((st.clone(), salted(*salt))) + self.store.lock().ok()?.clone() } /// The buffer kept under `key` and the source files it was made of (see [`crate::reads`]). - /// A buffer from the disk cache or another store doesn't know its files: its list is - /// incomplete. + /// A buffer from the disk cache or another store comes with the files its entry lists, after + /// they were found unchanged. pub fn get(&self, key: u64) -> Option<(Arc, Arc)> { let mut g = self.inner.lock().ok()?; g.clock += 1; @@ -172,10 +169,9 @@ impl LayerCache { g.missed_at.insert(key, web_time::Instant::now()); drop(g); // Disk cache: a hit comes back into memory. - let (dc, dk) = self.disk_key(key)?; - let buf = dc.get_layer(dk)?; - let mut files = ReadFiles::default(); - files.mark_incomplete(); + let store = self.persistent()?; + let id = self.virtual_id(); + let (buf, files) = store.get_layer(layer_disk_key(key), id.as_deref())?; let files = Arc::new(files); Some((self.insert_mem(key, buf, files.clone()), files)) } @@ -188,7 +184,7 @@ impl LayerCache { /// and packs it once instead of once per worker, which ran it out of memory). Renders don't /// wait for each other: on the frame workers' shared thread pool a wait can end up under /// the very work it waits for. `files`: the source files `buf` was made of (see - /// [`crate::reads`]). + /// [`crate::reads`]); a buffer whose files can't all be named stays in memory. pub fn insert(&self, key: u64, buf: Arc, files: Arc) -> Arc { if self.gated() { return buf; @@ -197,10 +193,12 @@ impl LayerCache { return kept; } let started = self.inner.lock().ok().and_then(|mut g| g.missed_at.remove(&key)); - if let Some((dc, dk)) = self.disk_key(key) { - let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= dc.min_layer_ms() as f64); - if slow { - dc.put_layer(dk, &buf); + if let Some(store) = self.persistent() { + let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= store.min_layer_ms() as f64); + let id = self.virtual_id(); + // (an incomplete list, or a file from memory without its identity: not stored) + if slow && let Some(entry) = EntryFiles::of(&files, id.as_deref()) { + store.put_layer(layer_disk_key(key), &buf, &entry); } } self.insert_mem(key, buf, files) @@ -274,12 +272,16 @@ impl LayerCache { } } -/// Persistent storage of layer buffers behind a [`LayerCache`] (keys salted per project). +/// Persistent storage of layer buffers behind a [`LayerCache`] (keys: +/// [`crate::disk_cache::layer_disk_key`]). Every entry keeps the source files its buffer was made +/// of and is used only while they are unchanged (#3184). pub trait LayerStore: Send + Sync { - /// A stored buffer (synchronous: mid-render). - fn get_layer(&self, key: u128) -> Option>; - /// Keep a buffer that was slow to render. - fn put_layer(&self, key: u128, buf: &Buf); + /// A stored buffer whose source files are unchanged, with those files (synchronous: + /// mid-render). An entry whose files changed, or damaged, is a miss and is dropped, so the + /// buffer rendered again replaces it. `virtual_id` names files served from memory. + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)>; + /// Keep a buffer that was slow to render, with the source files it was made of. + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles); /// Buffers faster to render than this (ms) are not stored. fn min_layer_ms(&self) -> u64 { 0 @@ -291,9 +293,10 @@ pub const PREFETCH_MIN_LAYER_MS: u64 = 20; /// A [`LayerStore`] over storage that can't be read in the middle of a render (the browser's /// Origin Private File System, read asynchronously). Lookups are served from buffers fetched -/// before the frame ([`PrefetchStore::provide`]); the keys a render looked up and didn't find -/// are recorded ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next -/// frame; buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the +/// before the frame ([`PrefetchStore::provide`]), once the files their entries list are found +/// unchanged; the keys a render looked up and didn't find are recorded +/// ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next frame; +/// buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the /// transport to write after the frame. Fetched buffers are kept least recently used first, up /// to a byte budget. pub struct PrefetchStore { @@ -302,9 +305,20 @@ pub struct PrefetchStore { min_ms: u64, } +/// A fetched entry: the buffer, the source files it was made of, its last use. +struct Fetched { + buf: Arc, + files: Arc, + used: u64, +} + +fn buf_bytes(b: &Buf) -> usize { + b.img.data.len().saturating_mul(std::mem::size_of::()) +} + #[derive(Default)] struct Prefetched { - ready: HashMap, u64)>, + ready: HashMap, bytes: usize, clock: u64, misses: Vec, @@ -314,6 +328,20 @@ struct Prefetched { known: std::collections::HashSet, } +impl Prefetched { + fn note_miss(&mut self, key: u128) { + if !self.misses.contains(&key) && self.misses.len() < 1024 { + self.misses.push(key); + } + } + + fn remove(&mut self, key: u128) { + if let Some(f) = self.ready.remove(&key) { + self.bytes = self.bytes.saturating_sub(buf_bytes(&f.buf)); + } + } +} + impl Default for PrefetchStore { fn default() -> Self { PrefetchStore::new(256 << 20) @@ -337,23 +365,21 @@ impl PrefetchStore { } /// A fetched entry (sealed bytes, [`crate::disk_cache::layer_entry`]) for `key`; `false` - /// when damaged. + /// when damaged or of another format. Its files are checked when the buffer is used. pub fn provide(&self, key: u128, entry: &[u8]) -> bool { - let Some(buf) = crate::disk_cache::read_layer_entry(entry) else { return false }; - let bytes = buf.img.data.len() * std::mem::size_of::(); + let Some((buf, files)) = crate::disk_cache::read_layer_entry(entry) else { return false }; + let buf = Arc::new(buf); + let bytes = buf_bytes(&buf); let Ok(mut s) = self.st.lock() else { return false }; s.clock += 1; - let now = s.clock; - if let Some((old, _)) = s.ready.insert(key, (Arc::new(buf), now)) { - s.bytes -= old.img.data.len() * std::mem::size_of::(); - } - s.bytes += bytes; + let used = s.clock; + s.remove(key); + s.ready.insert(key, Fetched { buf, files: Arc::new(files), used }); + s.bytes = s.bytes.saturating_add(bytes); s.known.insert(key); while s.bytes > self.budget { - let Some((&k, _)) = s.ready.iter().min_by_key(|(_, (_, t))| *t) else { break }; - if let Some((b, _)) = s.ready.remove(&k) { - s.bytes -= b.img.data.len() * std::mem::size_of::(); - } + let Some(oldest) = s.ready.iter().min_by_key(|(_, f)| f.used).map(|(k, _)| *k) else { break }; + s.remove(oldest); } true } @@ -382,32 +408,44 @@ impl PrefetchStore { } impl LayerStore for PrefetchStore { - fn get_layer(&self, key: u128) -> Option> { + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { + let found = { + let mut s = self.st.lock().ok()?; + s.clock += 1; + let now = s.clock; + match s.ready.get_mut(&key) { + Some(f) => { + f.used = now; + Some((f.buf.clone(), f.files.clone())) + } + None => { + s.note_miss(key); + None + } + } + }; + let (buf, files) = found?; + // (looked at without the lock: one call of the hook, or one `metadata`, per file) + let unchanged = files.unchanged(virtual_id); let mut s = self.st.lock().ok()?; - s.clock += 1; - let now = s.clock; - match s.ready.get_mut(&key) { - Some((b, t)) => { - *t = now; - let b = b.clone(); - if !s.hits.contains(&key) { - s.hits.push(key); - } - Some(b) - } - None => { - if !s.misses.contains(&key) && s.misses.len() < 1024 { - s.misses.push(key); - } - None - } + if !unchanged { + // Made of files that changed since: forgotten, so the buffer rendered again is + // written over its entry. + s.remove(key); + s.known.remove(&key); + s.note_miss(key); + return None; } + if !s.hits.contains(&key) { + s.hits.push(key); + } + Some((buf, files.to_read_files())) } - fn put_layer(&self, key: u128, buf: &Buf) { + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { let Ok(mut s) = self.st.lock() else { return }; if s.known.insert(key) { - s.writes.push((key, crate::disk_cache::layer_entry(buf))); + s.writes.push((key, crate::disk_cache::layer_entry(buf, files))); } } @@ -800,4 +838,47 @@ mod shared_insert_tests { assert!(Arc::ptr_eq(&cache.insert(3, b, Default::default()), &a), "the later render gets the first buffer"); assert!(Arc::ptr_eq(&cache.get(3).unwrap().0, &a)); } + + /// The browser's store (#3184): a fetched entry is used only while the files it lists are + /// unchanged (here from memory, through the hook), and comes with them; one made of files + /// that changed is dropped and counts as a miss, so the buffer rendered again is queued over + /// it. A buffer whose files can't all be named is not queued at all. + #[test] + fn the_prefetch_store_checks_the_files_of_its_entries() { + use super::{LayerStore, PrefetchStore}; + use crate::disk_cache::{EntryFiles, layer_disk_key, layer_entry}; + use crate::reads::{FileStamp, ReadFile, ReadFiles}; + let buf = || Buf { img: Image::new(2, 2), offset: [0.0; 2], scale: 1.0 }; + let files: ReadFiles = [ReadFile::new("/v.png", FileStamp::Virtual)].into_iter().collect(); + let (one, two) = (|_: &str| Some((3, 1)), |_: &str| Some((3, 2))); + let entry = layer_entry(&buf(), &EntryFiles::of(&files, Some(&one)).unwrap()); + let store = PrefetchStore::new(1 << 20).with_min_ms(0); + assert!(store.provide(5, &entry)); + assert!(!store.provide(6, b"damaged")); + let (_, got) = store.get_layer(5, Some(&one)).unwrap(); + assert_eq!(got, files); + assert_eq!(store.take_hits(), [5]); + // The file changed: a miss, forgotten, and the new buffer is queued over it. + assert!(store.get_layer(5, Some(&two)).is_none()); + assert!(!store.has(5)); + assert_eq!(store.take_misses(), [5]); + store.put_layer(5, &buf(), &EntryFiles::of(&files, Some(&two)).unwrap()); + assert_eq!(store.take_writes().len(), 1, "written over the changed entry"); + // Through the layer cache: a hit reports its files; incomplete lists are not queued. + let cache = LayerCache::default(); + let store = Arc::new(PrefetchStore::new(1 << 20).with_min_ms(0)); + cache.set_store(Some(store.clone())); + cache.set_virtual_id(Some(Arc::new(one))); + assert!(store.provide(layer_disk_key(9), &entry)); + let (_, from_store) = cache.get(9).unwrap(); + assert!(*from_store == files && from_store.is_complete()); + let mut incomplete = files.clone(); + incomplete.mark_incomplete(); + assert!(cache.get(10).is_none()); + cache.insert(10, Arc::new(buf()), Arc::new(incomplete)); + assert!(cache.get(11).is_none()); + cache.insert(11, Arc::new(buf()), Arc::new(files.clone())); + let written: Vec = store.take_writes().into_iter().map(|w| w.0).collect(); + assert_eq!(written, [layer_disk_key(11)], "only the buffer whose files are all named"); + } } diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 0a91f11ac..93c949ff2 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -4,18 +4,19 @@ //! * Entries are files keyed by a 128-bit content hash (`/v1//<2 hex>/<32 hex>.ecc`): //! frames by the hash of the composition's content as it is in memory (the comp and everything //! it uses, footage items with their settings and paths; no file is looked at) plus frame, -//! scale and view; layer buffers by the layer cache's content key salted with the project's -//! footage fingerprint. A changed project therefore never reads stale pixels: its keys simply +//! scale and view; layer buffers by the layer cache's content key (which names the footage +//! items a buffer uses with their settings and paths) and the renderer version +//! ([`layer_disk_key`]). A changed project therefore never reads stale pixels: its keys simply //! change. -//! * A frame entry keeps the source files the frame was made of, each with the size and +//! * Frame and layer entries keep the source files they were made of, each with the size and //! modification time it was read with ([`EntryFiles`], #3184). An entry is used only while -//! those files are unchanged: a handful of `metadata` calls when the frame is read, never a -//! scan of the project's files. A frame whose files can't all be named is not stored. +//! those files are unchanged: a handful of `metadata` calls when it is read, never a scan of +//! the project's files. A frame or buffer whose files can't all be named is not stored. //! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA (or, for //! 32 bpc viewer frames, half-float RGBA with the bytes shuffled into planes; the entry //! header's format byte tells them apart: 2 and 3, both with their source files first), layer -//! buffers as `f32` RGBA with the bytes shuffled into planes (exact, so cached and fresh -//! renders are bit-identical), Roto Brush / Object Matte segmentations as +//! buffers (format 4, their source files first) as `f32` RGBA with the bytes shuffled into +//! planes (exact, so cached and fresh renders are bit-identical), Roto Brush / Object Matte segmentations as //! `FrameSeg::to_bytes` (keyed by their content-keyed chain key and scale, so they are //! reused whenever the same frames, settings and prompt come back, also after a restart). Every file ends in a checksum; damaged files read as misses and //! are deleted. @@ -97,13 +98,16 @@ pub struct FrameF16 { pub rgba: Vec, } -/// The entry header's format byte: layer buffers and segmentations (and 8-bit frames before +/// The entry header's format byte: segmentations (and 8-bit frames and layer buffers before /// #3184). const FORMAT_RGBA8: u8 = 0; /// Frame entries: their source files ([`EntryFiles`]), then 8-bit or half-float pixels. The /// formats before them (0: 8-bit, 1: half float, without files) read as misses and are deleted. const FORMAT_RGBA8_FILES: u8 = 2; const FORMAT_F16_FILES: u8 = 3; +/// Layer entries: their source files ([`EntryFiles`]), then the buffer. The format before it +/// (0, without files) reads as a miss and is deleted. +const FORMAT_LAYER_FILES: u8 = 4; /// Counters for tests, the Info panel and `cache.diskStats`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -234,7 +238,7 @@ pub struct LayerPrefetch { const PREFETCH_RECENT: usize = 512; impl LayerPrefetch { - /// A frame's layer-cache misses (salted keys). + /// A frame's layer-cache misses (disk keys, [`layer_disk_key`]). pub fn note_misses(&mut self, keys: impl IntoIterator) { for k in keys { self.recent.retain(|x| *x != k); @@ -300,7 +304,7 @@ pub struct DiskCache { evictions: AtomicU64, dropped: AtomicU64, failed: AtomicU64, - /// Source files looked at to check frame entries ([`DiskCache::file_checks`]). + /// Source files looked at to check frame and layer entries ([`DiskCache::file_checks`]). file_checks: AtomicU64, tmp_counter: AtomicU64, queue: Arc<(Mutex, Condvar)>, @@ -597,41 +601,50 @@ impl DiskCache { } } - /// A frame entry of `format` whose source files are unchanged, decoded by `decode`, with - /// those files. An entry whose files changed, of the format before #3184, or damaged, is a - /// miss and is deleted (the frame renders again and is stored anew). An entry of the other - /// current format (8-bit and half-float frames have keys of their own) is a miss and stays. - fn get_checked(&self, key: u128, format: u8, virtual_id: Option>, decode: impl FnOnce(&[u8]) -> Option) -> Option<(T, ReadFiles)> { + /// An entry of `kind` and `format` whose source files are unchanged, decoded by `decode`, + /// with those files. An entry whose files changed, of the format before #3184, or damaged, + /// is a miss and is deleted (it renders again and is stored anew). A frame entry of the + /// other current frame format (8-bit and half-float frames have keys of their own) is a miss + /// and stays. + fn get_checked( + &self, + kind: Kind, + key: u128, + format: u8, + virtual_id: Option>, + decode: impl FnOnce(&[u8]) -> Option, + ) -> Option<(T, ReadFiles)> { let miss = || { self.misses.fetch_add(1, Ordering::Relaxed); None }; - let Some((found, payload)) = self.load(Kind::Frame, key) else { return miss() }; + let Some((found, payload)) = self.load(kind, key) else { return miss() }; if found != format { - if found != FORMAT_RGBA8_FILES && found != FORMAT_F16_FILES { - self.discard(Kind::Frame, key); + let other_frame_format = kind == Kind::Frame && (found == FORMAT_RGBA8_FILES || found == FORMAT_F16_FILES); + if !other_frame_format { + self.discard(kind, key); } return miss(); } - let Some((files, pixels)) = EntryFiles::decode(&payload) else { - self.discard(Kind::Frame, key); + let Some((files, body)) = EntryFiles::decode(&payload) else { + self.discard(kind, key); return miss(); }; self.file_checks.fetch_add(files.len() as u64, Ordering::Relaxed); if !files.unchanged(virtual_id) { - self.discard(Kind::Frame, key); + self.discard(kind, key); return miss(); } - let Some(frame) = decode(pixels) else { - self.discard(Kind::Frame, key); + let Some(value) = decode(body) else { + self.discard(kind, key); return miss(); }; - self.hit(Kind::Frame, key); - Some((frame, files.to_read_files())) + self.hit(kind, key); + Some((value, files.to_read_files())) } - /// Source files looked at so far to check frame entries before using them (one per file a - /// read frame lists; tests). + /// Source files looked at so far to check frame and layer entries before using them (one per + /// file a read entry lists; tests). pub fn file_checks(&self) -> u64 { self.file_checks.load(Ordering::Relaxed) } @@ -685,10 +698,6 @@ impl DiskCache { } /// Write an entry now (atomic rename), then evict down to the limit. - fn write_now(&self, kind: Kind, key: u128, payload: &[u8]) { - self.write_format(kind, key, FORMAT_RGBA8, payload); - } - fn write_format(&self, kind: Kind, key: u128, format: u8, payload: &[u8]) { if self.contains(kind, key) { return; @@ -749,12 +758,12 @@ impl DiskCache { /// those files; `None` for a half-float entry of that key, which /// [`DiskCache::get_frame_f16`] reads. `virtual_id` names files served from memory. pub fn get_frame(&self, key: u128, virtual_id: Option>) -> Option<(Frame8, ReadFiles)> { - self.get_checked(key, FORMAT_RGBA8_FILES, virtual_id, decode_frame) + self.get_checked(Kind::Frame, key, FORMAT_RGBA8_FILES, virtual_id, decode_frame) } /// A half-float frame (32 bpc viewer frames), as [`DiskCache::get_frame`]. pub fn get_frame_f16(&self, key: u128, virtual_id: Option>) -> Option<(FrameF16, ReadFiles)> { - self.get_checked(key, FORMAT_F16_FILES, virtual_id, decode_frame_f16) + self.get_checked(Kind::Frame, key, FORMAT_F16_FILES, virtual_id, decode_frame_f16) } /// Queue a half-float frame for writing (`width * height * 4` binary16 values) with the @@ -786,22 +795,28 @@ impl DiskCache { self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, with_files(&files, encode_frame(width, height, rgba))) } - pub fn get_layer(&self, key: u128) -> Option { - let p = self.read(Kind::Layer, key)?; - decode_layer(&p) + /// A layer buffer (key: [`layer_disk_key`]) whose source files are unchanged, with those + /// files, as [`DiskCache::get_checked`]: an entry whose files changed, damaged, or of the + /// format before #3184 is a miss and is deleted, so the buffer renders again and replaces it. + /// `virtual_id` names files served from memory. + pub fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Buf, ReadFiles)> { + self.get_checked(Kind::Layer, key, FORMAT_LAYER_FILES, virtual_id, decode_layer) } - /// Queue a layer buffer for writing. - pub fn put_layer(&self, key: u128, buf: &Buf) { + /// Queue a layer buffer for writing with the source files it was made of (see + /// [`EntryFiles::of`]: a buffer whose files can't all be named must not be stored). + pub fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { if self.contains(Kind::Layer, key) { return; } - let _ = self.enqueue(Kind::Layer, key, encode_layer(buf)); + let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, with_files(files, encode_layer(buf))); } - /// Write a layer buffer synchronously (tests). - pub fn put_layer_now(&self, key: u128, buf: &Buf) { - self.write_now(Kind::Layer, key, &encode_layer(buf)); + /// Write a layer buffer synchronously (tests); a list that can't be stored is not. + pub fn put_layer_now(&self, key: u128, buf: &Buf, files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Layer, key, FORMAT_LAYER_FILES, &with_files(&files, encode_layer(buf))); + } } /// A segmentation (chain key, scale) written by [`DiskCache::put_seg`]. @@ -860,7 +875,7 @@ impl DiskCache { } } -/// A frame entry's payload: its source files, then its pixels. +/// A frame or layer entry's payload: its source files, then its pixels. fn with_files(files: &EntryFiles, pixels: Vec) -> Vec { let mut out = Vec::with_capacity(pixels.len() + 64); files.encode(&mut out); @@ -953,15 +968,22 @@ pub fn read_frame_entry(data: &[u8], virtual_id: Option>) -> O decode_frame(pixels) } -/// A sealed layer-buffer entry: what the browser's frame workers write to the Origin Private -/// File System (`layers/<32 hex>.ecc`). -pub fn layer_entry(buf: &Buf) -> Vec { - seal(Kind::Layer, &encode_layer(buf)) +/// A sealed layer-buffer entry with the source files it was made of: what the browser's frame +/// workers write to the Origin Private File System (`layers/<32 hex>.ecc`). +pub fn layer_entry(buf: &Buf, files: &EntryFiles) -> Vec { + seal_format(Kind::Layer, FORMAT_LAYER_FILES, &with_files(files, encode_layer(buf))) } -/// A layer buffer from a sealed entry's bytes (`None` when damaged). -pub fn read_layer_entry(data: &[u8]) -> Option { - decode_layer(verify(data, Kind::Layer)?) +/// A layer buffer and its source files from a sealed entry's bytes (`None` when damaged or of +/// another format). The files are not looked at here: the store checks them when the buffer is +/// used ([`EntryFiles::unchanged`]). +pub fn read_layer_entry(data: &[u8]) -> Option<(Buf, EntryFiles)> { + let payload = verify(data, Kind::Layer)?; + if data.get(5) != Some(&FORMAT_LAYER_FILES) { + return None; + } + let (files, body) = EntryFiles::decode(payload)?; + Some((decode_layer(body)?, files)) } /// The disk key of a segmentation: its chain key and scale. @@ -983,11 +1005,11 @@ impl effectcraft_effects::roto::SegStore for DiskCache { } impl crate::cache::LayerStore for DiskCache { - fn get_layer(&self, key: u128) -> Option> { - DiskCache::get_layer(self, key).map(Arc::new) + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { + DiskCache::get_layer(self, key, virtual_id).map(|(b, f)| (Arc::new(b), f)) } - fn put_layer(&self, key: u128, buf: &Buf) { - DiskCache::put_layer(self, key, buf); + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { + DiskCache::put_layer(self, key, buf, files); } fn min_layer_ms(&self) -> u64 { DiskCache::min_layer_ms(self) @@ -1107,8 +1129,8 @@ fn decode_layer(p: &[u8]) -> Option { let offset = [f(8)?, f(16)?]; let scale = f(24)?; let planes = lz4_flex::decompress_size_prepended(&p[32..]).ok()?; - let n = w as usize * h as usize; - if planes.len() != n * 16 { + let n = (w as usize).checked_mul(h as usize)?; + if planes.len() != n.checked_mul(16)? { return None; } let mut img = Image::new(w, h); @@ -1137,75 +1159,26 @@ fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { /// Size and content hash of a path that has no native metadata (the browser file table). pub type VirtualFileId<'a> = &'a (dyn Fn(&str) -> Option<(u64, u64)> + Send + Sync); -/// A file's size and modification time (so edited footage gets a new layer salt): the identity a -/// render records for the files it reads ([`crate::reads::FileStamp`]). When the path has no -/// native metadata, `virtual_id` supplies a durable size and content hash instead. -fn file_stamp(h: &mut Hash128, path: &str, virtual_id: Option>) { - if path.is_empty() { - return; - } - if let Some(crate::reads::FileStamp::Native { len, modified }) = crate::reads::FileStamp::native(path) { - h.write_u64(len); - if let Some(t) = modified { - h.write_u64(t); - } - return; - } - if let Some((len, hash)) = virtual_id.and_then(|id| id(path)) { - h.write_u64(len); - h.write_u64(hash); - } -} +/// A [`VirtualFileId`] a cache can keep (the browser file table's identities). +pub type SharedVirtualFileId = Arc Option<(u64, u64)> + Send + Sync>; -fn footage_stamp(h: &mut Hash128, f: &effectcraft_project::Footage, virtual_id: Option>) { - file_stamp(h, &f.path, virtual_id); - for p in &f.sequence { - file_stamp(h, p, virtual_id); - } -} +/// Layer entries with their source files (#3184), part of every layer disk key: entries of the +/// earlier format (keyed by a project-wide footage salt instead) are never looked up again; +/// least recently used, they are evicted. +const LAYER_ENTRY_VERSION: &[u8] = b"layer-entry-files-1"; -/// Salt for layer cache keys on disk: the renderer version and every footage file's identity -/// (layer keys name footage items, not file contents). -pub fn footage_salt(project: &effectcraft_project::Project) -> u64 { - footage_salt_with(project, None) -} - -/// [`footage_salt`] with [`VirtualFileId`] for paths `std::fs::metadata` cannot describe. -pub fn footage_salt_with(project: &effectcraft_project::Project, virtual_id: Option>) -> u64 { +/// Disk key of a layer buffer: the layer cache's content key ([`crate::cache::layer_key`] and +/// the keys derived from it), the layer entry format and the renderer version. The content key +/// comes from memory alone: it names the footage items the buffer uses with their settings and +/// paths, so two projects only share an entry for the same pixels of the same files; whether +/// those files still hold what the buffer was made of is checked when the entry is read +/// ([`EntryFiles`]). No file is looked at here. +pub fn layer_disk_key(key: u64) -> u128 { let mut h = Hash128::default(); + h.write(LAYER_ENTRY_VERSION); h.write(RENDER_VERSION.as_bytes()); - // Footage another layer reads (Audio Spectrum's Audio Layer); a read precomp can hold any. - let mut read = std::collections::BTreeSet::new(); - let mut read_comp = false; - for (_, c) in project.comps() { - for l in c.layers.iter() { - for r in l.referenced_layers().into_iter().filter(|r| *r != l.id) { - match c.layer(r).map(|x| &x.source) { - Some(effectcraft_project::LayerSource::Footage { item }) => _ = read.insert(*item), - Some(effectcraft_project::LayerSource::Comp { .. }) => read_comp = true, - _ => {} - } - } - } - } - for (id, it) in &project.items { - // (files without video make layer buffers only through a layer that reads them: - // importing music keeps the keys) - if let effectcraft_project::ItemKind::Footage(f) = &it.kind - && (f.has_video || read_comp || read.contains(id)) - { - h.write_u64(id.0); - hash_debug(&mut h, f); - footage_stamp(&mut h, f, virtual_id); - } - if let Some(proxy) = it.proxy.as_ref().filter(|p| p.enabled) { - h.write_u64(id.0); - hash_debug(&mut h, proxy); - footage_stamp(&mut h, &proxy.footage, virtual_id); - } - } - let v = h.finish(); - (v as u64) ^ ((v >> 64) as u64) + h.write_u64(key); + h.finish() } /// Content key of a composition's pixels, from the project in memory alone (no file is looked @@ -1443,11 +1416,12 @@ mod tests { fn hit_miss_and_exact_round_trip() { let dir = tmpdir("hit"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - assert!(dc.get_layer(42).is_none()); + assert!(dc.get_layer(42, None).is_none()); let b = buf(1, 33, 17); - dc.put_layer(42, &b); + dc.put_layer(42, &b, &EntryFiles::default()); dc.flush(); - let back = dc.get_layer(42).unwrap(); + let (back, files) = dc.get_layer(42, None).unwrap(); + assert!(files.is_empty() && files.is_complete()); assert_eq!(back.img, b.img); assert_eq!((back.offset, back.scale), (b.offset, b.scale)); let rgba: Vec = (0..20 * 10 * 4).map(|i| (i % 251) as u8).collect(); @@ -1462,7 +1436,7 @@ mod tests { } /// Music doesn't change a comp's disk keys (adding it to the timeline kept no blue frame); - /// hiding a clip does. Importing music keeps the layer-cache salt. + /// hiding a clip does. Importing music keeps them too. #[test] fn music_keeps_the_disk_keys() { use effectcraft_project::{Comp, Footage, FootageKind, ItemKind, LayerSource, Project, Solid, build}; @@ -1474,14 +1448,14 @@ mod tests { let clip = build::layer(&mut p, &comp, "Clip", LayerSource::Solid { item: sid }, (64, 64), None); let clip_id = clip.id; p.comp_mut(cid).unwrap().layers.push(clip); - let (key, salt) = (comp_content_key(&p, cid), footage_salt(&p)); + let key = comp_content_key(&p, cid); let song = p.add_item( "song.wav", Default::default(), None, ItemKind::Footage(Footage { kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }), ); - assert_eq!(footage_salt(&p), salt, "importing music"); + assert_eq!(comp_content_key(&p, cid), key, "importing music"); let music = build::layer(&mut p, &comp, "Music", LayerSource::Footage { item: song }, (64, 64), None); p.comp_mut(cid).unwrap().layers.insert(0, music); assert_eq!(comp_content_key(&p, cid), key, "music on the timeline"); @@ -1496,7 +1470,7 @@ mod tests { let dir = tmpdir("burst"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); for k in 0..300 { - dc.put_layer(10_000 + k, &buf(1, 64, 64)); + dc.put_layer(10_000 + k, &buf(1, 64, 64), &EntryFiles::default()); } let rgba = vec![7u8; 32 * 32 * 4]; for k in 0..300 { @@ -1533,7 +1507,7 @@ mod tests { let dir = tmpdir("persist"); { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - dc.put_layer_now(1, &buf(1, 8, 8)); + dc.put_layer_now(1, &buf(1, 8, 8), &ReadFiles::default()); dc.put_frame_now(2, 2, 2, &[9; 16], &ReadFiles::default()); } let dc = DiskCache::open(&dir, 1 << 30).unwrap(); @@ -1552,11 +1526,11 @@ mod tests { let dir = tmpdir("lru"); let dc = DiskCache::open(&dir, u64::MAX).unwrap(); for k in 0..6u128 { - dc.put_layer_now(k, &buf(k as u32, 64, 64)); + dc.put_layer_now(k, &buf(k as u32, 64, 64), &ReadFiles::default()); } let per = dc.stats().bytes / 6; // Touch 0 so it is the most recently used. - assert!(dc.get_layer(0).is_some()); + assert!(dc.get_layer(0, None).is_some()); dc.set_max_bytes(per * 3 + per * 3 / 4); let st = dc.stats(); assert!(st.bytes <= per * 3 + per * 3 / 4, "{st:?}"); @@ -1568,7 +1542,7 @@ mod tests { let files = walk(&dir); assert_eq!(files, 3); // New writes keep evicting. - dc.put_layer_now(99, &buf(9, 64, 64)); + dc.put_layer_now(99, &buf(9, 64, 64), &ReadFiles::default()); assert!(dc.stats().bytes <= per * 3 + per * 3 / 4); } @@ -1593,7 +1567,7 @@ mod tests { let dir = tmpdir("space"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); for k in 0..4u128 { - dc.put_layer_now(k, &buf(k as u32, 64, 64)); + dc.put_layer_now(k, &buf(k as u32, 64, 64), &ReadFiles::default()); } let used = dc.stats().bytes; // Unknown space: the setting alone. @@ -1606,13 +1580,13 @@ mod tests { dc.set_disk_space(Some((100 << 30, 5 << 30))); let st = dc.stats(); assert_eq!((st.max_bytes, st.limit_bytes), (1 << 30, used)); - dc.put_layer_now(9, &buf(9, 64, 64)); + dc.put_layer_now(9, &buf(9, 64, 64), &ReadFiles::default()); let st = dc.stats(); assert!(st.bytes <= st.limit_bytes && st.bytes <= used - used / 10 && st.evictions > 0, "{st:?}"); assert!(dc.contains(Kind::Layer, 9), "the new entry is the most recently used"); // Below the reserve the cache gives its space back, and skips writes that can't fit. dc.set_disk_space(Some((100 << 30, 4 << 30))); - dc.put_layer_now(10, &buf(10, 64, 64)); + dc.put_layer_now(10, &buf(10, 64, 64), &ReadFiles::default()); let st = dc.stats(); assert_eq!((st.limit_bytes, st.entries, st.bytes), (0, 0, 0), "{st:?}"); // Plenty of space again: back to the setting. @@ -1627,8 +1601,8 @@ mod tests { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); // A file where the layers folder should be: every layer write fails. std::fs::write(dir.join(VERSION).join(Kind::Layer.dir()), b"x").unwrap(); - dc.put_layer_now(1, &buf(1, 8, 8)); - dc.put_layer_now(2, &buf(2, 8, 8)); + dc.put_layer_now(1, &buf(1, 8, 8), &ReadFiles::default()); + dc.put_layer_now(2, &buf(2, 8, 8), &ReadFiles::default()); let st = dc.stats(); assert_eq!((st.failed, st.writes, st.entries), (2, 0, 0)); let _ = std::fs::remove_dir_all(&dir); @@ -1677,8 +1651,8 @@ mod tests { for i in 0..20u128 { let k = i % 5; let w = if t % 2 == 0 { &a } else { &b }; - w.put_layer_now(k, &buf(k as u32, 16, 16)); - if let Some(x) = w.get_layer(k) { + w.put_layer_now(k, &buf(k as u32, 16, 16), &ReadFiles::default()); + if let Some((x, _)) = w.get_layer(k, None) { assert_eq!(x.img, buf(k as u32, 16, 16).img); } } @@ -1687,41 +1661,16 @@ mod tests { }); b.rescan(); for k in 0..5u128 { - assert_eq!(b.get_layer(k).unwrap().img, buf(k as u32, 16, 16).img); + assert_eq!(b.get_layer(k, None).unwrap().0.img, buf(k as u32, 16, 16).img); } } - /// An audio file nothing reads stays out of the layer salt; one a layer reads (Audio - /// Spectrum) is in it, so overwriting it doesn't reuse that layer's buffers. + /// Replaced bytes of a path with no native metadata (the browser file table) change neither + /// the comp key nor a layer's disk key (both from memory): the frame and layer entries made + /// of them check the hook's size and content hash when read and are misses, deleted (#1253, + /// #3184). #[test] - fn read_audio_counts_in_the_footage_salt() { - use effectcraft_project::build; - use effectcraft_project::{Comp, Footage, FootageKind, ItemKind, LayerSource, MatteKind, Project, TrackMatte}; - use effectcraft_time::{FrameRate, Tick}; - - let mut p = Project::default(); - let f = Footage { path: "/song.wav".into(), kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }; - let song = p.add_item("song.wav", effectcraft_color::Label::None, None, ItemKind::Footage(f)); - let mut comp = Comp::new(16, 9, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); - let music = build::layer(&mut p, &comp, "music", LayerSource::Footage { item: song }, (16, 9), None); - let mut reader = build::layer(&mut p, &comp, "reader", LayerSource::Null, (16, 9), None); - let music_id = music.id; - comp.layers = vec![reader.clone(), music].into(); - let cid = p.add_item("C", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into())); - - let id = |mark: u64| move |path: &str| (path == "/song.wav").then_some((8, mark)); - let (one, two) = (id(1), id(2)); - assert_eq!(footage_salt_with(&p, Some(&one)), footage_salt_with(&p, Some(&two)), "unread music stays out"); - reader.track_matte = Some(TrackMatte { layer: music_id, kind: MatteKind::Alpha }); - *p.comp_mut(cid).unwrap().layers.first_mut().unwrap() = reader; - assert_ne!(footage_salt_with(&p, Some(&one)), footage_salt_with(&p, Some(&two)), "read audio counts"); - } - - /// A path with no native metadata takes the layer salt from the caller's size and content hash - /// (#1253). The comp key is from memory: replaced bytes are caught by the frame entries' - /// check instead (#3184). - #[test] - fn virtual_file_bytes_change_the_salt_not_the_comp_key() { + fn virtual_file_bytes_are_checked_by_the_entries_not_the_keys() { use effectcraft_project::build; use effectcraft_project::{Comp, Footage, ItemKind, LayerSource, Project}; use effectcraft_time::{FrameRate, Tick}; @@ -1735,10 +1684,6 @@ mod tests { let id = |mark: u64| move |path: &str| (path == "/virtual.mov").then_some((8, mark)); let (one, two) = (id(1), id(2)); - let a = footage_salt_with(&p, Some(&one)); - let b = footage_salt_with(&p, Some(&two)); - assert_ne!(a, b, "replaced virtual media must not reuse the salt"); - // The frame entry of replaced virtual media is a miss. let dc = DiskCache::open(tmpdir("virtual"), 1 << 30).unwrap(); let k = frame_key(comp_content_key(&p, cid), 0, 1000, 0); let files: ReadFiles = [crate::reads::ReadFile::new("/virtual.mov", crate::reads::FileStamp::Virtual)].into_iter().collect(); @@ -1746,6 +1691,113 @@ mod tests { dc.flush(); assert!(dc.get_frame(k, Some(&one)).is_some_and(|(_, f)| f == files)); assert!(dc.get_frame(k, Some(&two)).is_none() && !dc.contains(Kind::Frame, k), "replaced: a miss, deleted"); + // A layer buffer made of it. + let lk = layer_disk_key(7); + dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap()); + dc.flush(); + assert!(dc.get_layer(lk, Some(&one)).is_some_and(|(b, f)| b.img == buf(1, 4, 4).img && f == files && f.is_complete())); + assert!(dc.get_layer(lk, None).is_none() && !dc.contains(Kind::Layer, lk), "no identity: a miss, deleted"); + dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap()); + dc.flush(); + assert!(dc.get_layer(lk, Some(&two)).is_none() && !dc.contains(Kind::Layer, lk), "replaced: a miss, deleted"); + // The browser's sealed layer entries carry the same list. + let e = layer_entry(&buf(2, 3, 2), &EntryFiles::of(&files, Some(&one)).unwrap()); + let (b, list) = read_layer_entry(&e).unwrap(); + assert!(b.img == buf(2, 3, 2).img && list.unchanged(Some(&one)) && !list.unchanged(Some(&two))); + assert!(read_layer_entry(&seal(Kind::Layer, &encode_layer(&buf(2, 3, 2)))).is_none(), "the format before #3184"); + let mut bad = e.clone(); + bad[12] ^= 1; + assert!(read_layer_entry(&bad).is_none(), "damaged"); + } + + /// Layer disk keys come from the layer cache's key alone (no file, no project-wide salt) and + /// differ per key. + #[test] + fn layer_disk_keys_need_no_files() { + assert_eq!(layer_disk_key(1), layer_disk_key(1)); + assert_ne!(layer_disk_key(1), layer_disk_key(2)); + // Not the layout of the salted keys before #3184 (`salt << 64 | key`). + assert_ne!(layer_disk_key(1) as u64, 1); + } + + /// A layer entry is used only while the files it lists are what the buffer was made of: a + /// new size, a new time, a missing file that is back, a file replaced by a folder, a damaged + /// files section and the format before #3184 are misses, and the entry is deleted so the + /// buffer is rendered and stored again. A buffer whose files can't all be named is not + /// stored. Only the listed files are looked at. + #[test] + fn layer_entries_check_their_files() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("layer-check"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let gone = src.join("gone.png").to_string_lossy().to_string(); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap_or(FileStamp::Missing))).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_layer_now(1, &buf(1, 4, 4), &read(&[&a])); + dc.put_layer_now(2, &buf(2, 4, 4), &read(&[&b, &gone])); + dc.put_layer_now(3, &buf(3, 4, 4), &read(&[&b])); + let (one, files) = dc.get_layer(1, None).unwrap(); + assert!(one.img == buf(1, 4, 4).img && files == read(&[&a]) && files.is_complete()); + assert_eq!(dc.file_checks(), 1, "only the file of that buffer"); + // a.png gets a new size: entry 1 is a miss and deleted, the others stay. + std::fs::write(&a, b"aaa").unwrap(); + assert!(dc.get_layer(1, None).is_none() && !dc.contains(Kind::Layer, 1)); + assert!(dc.get_layer(2, None).is_some() && dc.get_layer(3, None).is_some()); + // b.png gets a new time only. + let t = std::fs::metadata(&b).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(&b).unwrap().set_modified(t).unwrap(); + assert!(dc.get_layer(3, None).is_none() && !dc.contains(Kind::Layer, 3)); + assert!(dc.get_layer(2, None).is_none(), "b.png is listed there too"); + // A missing file that is back. + dc.put_layer_now(4, &buf(4, 4, 4), &read(&[&gone])); + assert!(dc.get_layer(4, None).is_some(), "missing, still missing"); + file("gone.png", b"g"); + assert!(dc.get_layer(4, None).is_none() && !dc.contains(Kind::Layer, 4), "back"); + // A file replaced by a folder (unreadable). + let c = file("c.png", b"cc"); + dc.put_layer_now(5, &buf(5, 4, 4), &read(&[&c])); + std::fs::remove_file(&c).unwrap(); + std::fs::create_dir(&c).unwrap(); + assert!(dc.get_layer(5, None).is_none() && !dc.contains(Kind::Layer, 5)); + // Written again after the miss: a hit with the new identity. + dc.put_layer_now(1, &buf(9, 4, 4), &read(&[&a])); + assert_eq!(dc.get_layer(1, None).map(|l| l.0.img), Some(buf(9, 4, 4).img)); + // The format before #3184 (no files): a miss, deleted. + dc.write_format(Kind::Layer, 6, FORMAT_RGBA8, &encode_layer(&buf(6, 4, 4))); + assert!(dc.contains(Kind::Layer, 6)); + assert!(dc.get_layer(6, None).is_none() && !dc.contains(Kind::Layer, 6)); + // A valid checksum over a damaged files section, or over a cut buffer: misses, deleted. + let mut payload = vec![]; + payload.extend_from_slice(&3u32.to_le_bytes()); + payload.extend_from_slice(&encode_layer(&buf(7, 4, 4))); + dc.write_format(Kind::Layer, 7, FORMAT_LAYER_FILES, &payload); + assert!(dc.get_layer(7, None).is_none() && !dc.contains(Kind::Layer, 7)); + let mut cut = vec![]; + EntryFiles::default().encode(&mut cut); + cut.extend_from_slice(&encode_layer(&buf(8, 4, 4))[..40]); + dc.write_format(Kind::Layer, 8, FORMAT_LAYER_FILES, &cut); + assert!(dc.get_layer(8, None).is_none() && !dc.contains(Kind::Layer, 8)); + // A damaged file on disk. + dc.put_layer_now(9, &buf(9, 4, 4), &ReadFiles::default()); + let p = dc.path(Kind::Layer, 9); + let mut d = std::fs::read(&p).unwrap(); + let n = d.len(); + d[n / 2] ^= 0xff; + std::fs::write(&p, d).unwrap(); + assert!(dc.get_layer(9, None).is_none() && !dc.contains(Kind::Layer, 9) && !p.exists()); + // Buffers whose files can't all be named are not stored. + let mut incomplete = read(&[&a]); + incomplete.mark_incomplete(); + dc.put_layer_now(10, &buf(10, 4, 4), &incomplete); + assert!(!dc.contains(Kind::Layer, 10)); + let _ = std::fs::remove_dir_all(&dir); } /// A frame entry is used only while the files it lists are what it was made of: a new size, diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index 162c04862..7f65a0110 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -12,8 +12,8 @@ use std::sync::{Arc, Mutex, PoisonError}; -/// The identity of a file as a render read it (see [`file_stamp`](crate::disk_cache) for the -/// same identity in the layer-cache salt; frame entries store it, see `disk_cache::EntryFiles`). +/// The identity of a file as a render read it (frame and layer entries on disk store it, see +/// [`EntryFiles`](crate::disk_cache::EntryFiles)). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum FileStamp { /// A file on disk: its size in bytes and its modification time (nanoseconds since the Unix diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index e77f07840..8ebea08fc 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -170,10 +170,6 @@ impl EffectcraftApp { self.session.poll_jobs(); ctx.request_repaint_after(std::time::Duration::from_millis(100)); } - // The disk cache's footage salt, taken off the UI thread after footage changed. - if self.session.poll_disk_salt() { - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - } // Analyses running in a worker (the web app). if !self.session.offloaded.is_empty() { self.session.poll_offload(); diff --git a/crates/ui-egui/tests/it/ui_unreadable_footage.rs b/crates/ui-egui/tests/it/ui_unreadable_footage.rs index f1c9707ba..21ca1e7c9 100644 --- a/crates/ui-egui/tests/it/ui_unreadable_footage.rs +++ b/crates/ui-egui/tests/it/ui_unreadable_footage.rs @@ -175,8 +175,7 @@ fn restored_original_and_active_proxy_render_new_pixels_through_media_and_disk_c let cache = effectcraft_render::disk_cache::DiskCache::open(dir.join("cache"), 1 << 20).unwrap(); cache.set_min_layer_ms(0); s.disk_cache = Some(cache.clone()); - let salt = s.refresh_disk_salt(true).unwrap(); - s.layer_cache.set_disk(Some((cache.clone(), salt))); + s.layer_cache.set_disk(Some(cache.clone())); let before = s.render(comp, Tick::ZERO, RenderOpts::default()); assert_eq!(before.data[8 * 16 + 8], if proxy { [0.0, 1.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0, 1.0] }); cache.flush(); diff --git a/docs/architecture.md b/docs/architecture.md index 48413d1c1..213aaaf57 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -242,9 +242,14 @@ frame's float values. The browser keeps 8-bit frames for now (its frame workers A persistent **disk cache** (`render::disk_cache`, Settings ▸ Media & Disk Cache) backs both the layer cache and the viewer's RAM preview: layer buffers that were slow to render and every preview frame are written (LZ4, atomic rename, checksummed) under 128-bit content keys — the -comp's content hash (the comp, what it uses, footage file size and time) plus frame, scale and -view for frames; the layer key salted with the footage fingerprint for layers — so entries -survive restarts and never go stale. Frame entries are 8-bit RGBA, or for 32 bpc viewer frames +comp's content hash (the comp and what it uses, footage items with their settings and paths, +from memory alone) plus frame, scale and view for frames; the layer cache's content key (which +names the footage items a buffer uses with their paths) and the renderer version for layers. +Every frame and layer entry keeps the source files it was made of, with the size and +modification time they were read with, and is used only while they are unchanged: a handful of +`metadata` calls when an entry is read, never a scan of the project's files (#3184). Entries +survive restarts and never go stale; frames and buffers whose files can't all be named are not +written. Frame entries are 8-bit RGBA, or for 32 bpc viewer frames half floats with their bytes shuffled into planes before LZ4 (the entry header's format byte tells them apart; the render options in the key keep the two kinds apart). LRU eviction keeps it under the size limit; Edit ▸ Purge empties it, `cache.diskStats` reports it, and the timeline draws disk-only frames in blue. In the diff --git a/docs/web.md b/docs/web.md index 832aa86fe..4f43b753e 100644 --- a/docs/web.md +++ b/docs/web.md @@ -354,8 +354,9 @@ frame whose files can't all be named is not stored. Cache / `edit.purge {what: "disk"}` clears it. `effectcraft.info().diskCache` has the same. **Layer buffers (M13.30).** Slow layer buffers (≥ 20 ms to render) go to the disk cache too -(`effectcraft-cache/v1/layers/<32 hex>.ecc`, `disk_cache::layer_entry`, keys salted per project -and footage as on the desktop). A layer lookup happens in the middle of a synchronous render, +(`effectcraft-cache/v1/layers/<32 hex>.ecc`, `disk_cache::layer_entry`, keyed as on the desktop: +`disk_cache::layer_disk_key`; each entry keeps the source files its buffer was made of, with +the file table's size and content hash, and is used only while they are unchanged). A layer lookup happens in the middle of a synchronous render, where the browser's file system can't be read, so it is made synchronous by fetching first: 1. Each frame worker backs its layer cache with a `PrefetchStore` (`effectcraft_render::cache`): From 2efa859aa9d8d21875242bbfd5e60370f8bc7f27 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 00:19:15 +0100 Subject: [PATCH 020/324] Disk cache: no-salt worker test, sequence paths in the frame-blend key Part of #3184 (step 3 of 4). - A frame-blended footage frame's layer-cache key now hashes the sequence's file list: with no project-wide salt, two projects whose items share an id and a first frame must not share its disk entry. - Test: a frame worker syncing, patching and rendering a project with an unused 5000-frame sequence asks its file hook only about the file its buffer reads (the salt asked about every file at every sync). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/background/remote/tests.rs | 67 ++++++++++++++++++++ crates/render/src/pipeline.rs | 3 + 2 files changed, 70 insertions(+) diff --git a/crates/engine/src/background/remote/tests.rs b/crates/engine/src/background/remote/tests.rs index c35d7a717..e6d797f9d 100644 --- a/crates/engine/src/background/remote/tests.rs +++ b/crates/engine/src/background/remote/tests.rs @@ -444,3 +444,70 @@ fn the_worker_reports_the_files_of_each_frame_for_its_disk_entry() { assert!(read_frame_entry(&entry, Some(&two)).is_none(), "the file was replaced: a miss"); } } + +/// No salt work at all (#3184, replacing the background salt of #3106): syncing a project with a +/// large image sequence nobody shows, patching it and rendering with the layer store never asks +/// the file hook about the sequence (the salt asked about every file at every sync). Only the +/// file the rendered buffer reads is asked about: to store its entry and, in another worker, to +/// check it before the buffer from the store is used. +#[test] +fn the_worker_asks_only_about_the_files_its_buffers_read() { + use effectcraft_project::{Comp, Footage, FootageKind, ItemKind, LayerSource, Project, build}; + use effectcraft_time::FrameRate; + use std::sync::Mutex; + let mut p = Project::default(); + let f = Footage { path: "/clip.png".into(), width: 4, height: 4, has_video: true, ..Default::default() }; + let fid = p.add_item("clip.png", effectcraft_color::Label::None, None, ItemKind::Footage(f)); + let seq = Footage { + kind: FootageKind::Sequence, + path: "/seq/f_00000.png".into(), + sequence: (0..5000).map(|i| format!("/seq/f_{i:05}.png")).collect(), + width: 4, + height: 4, + has_video: true, + ..Default::default() + }; + p.add_item("seq", effectcraft_color::Label::None, None, ItemKind::Footage(seq)); + let mut comp = Comp::new(4, 4, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + comp.layers = vec![build::layer(&mut p, &comp, "clip", LayerSource::Footage { item: fid }, (4, 4), None)].into(); + let cid = p.add_item("C", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into())); + let asked: Arc>> = Arc::default(); + let worker = || { + let mut w = FrameServer::new(Arc::new(OneVirtualFile { records: true }), None); + let seen = asked.clone(); + w.set_virtual_id(Some(Arc::new(move |path: &str| { + seen.lock().unwrap().push(path.to_string()); + (path == "/clip.png").then_some((10, 1)) + }))); + let store = Arc::new(PrefetchStore::new(1 << 20).with_min_ms(0)); + w.set_layer_store(Some(store.clone())); + (w, store) + }; + let render = |w: &mut FrameServer, revision: u64, prefetch: Vec| { + let out = w.handle(round(&FrameMsg::Render { id: 1, revision, comp: cid, time: Tick::ZERO, opts: Box::default(), disk: None, layers: true, prefetch })); + let FrameReply::Frame { layer_hits, .. } = &out[0].0 else { panic!("{:?}", out[0].0) }; + layer_hits.len() + }; + // Worker A: synced, patched, rendered; its buffer is queued with its file. + let (mut a, store_a) = worker(); + let mut m = Mirror::default(); + assert!(a.handle(round(&m.sync(1, &p).unwrap())).is_empty()); + let mut edited = p.clone(); + edited.item_mut(cid).unwrap().name = "Renamed".into(); + assert!(a.handle(round(&m.sync(2, &edited).unwrap())).is_empty()); + assert!(asked.lock().unwrap().is_empty(), "syncing looks at no file"); + assert_eq!(render(&mut a, 2, vec![]), 0); + let writes = store_a.take_writes(); + assert!(!writes.is_empty(), "the clip's buffer is stored"); + // Worker B: fetched before its frame, checked, used. + let (mut b, store_b) = worker(); + let mut m = Mirror::default(); + assert!(b.handle(round(&m.sync(2, &edited).unwrap())).is_empty()); + for (k, e) in &writes { + assert!(store_b.provide(*k, e)); + } + assert!(render(&mut b, 2, writes.iter().map(|(k, _)| format!("{k:032x}")).collect()) > 0, "served from the store"); + let asked = asked.lock().unwrap(); + assert!(!asked.is_empty(), "the hook names the buffer's file"); + assert!(asked.iter().all(|p| p == "/clip.png"), "only the file the buffer read: {:?}", &asked[..asked.len().min(5)]); +} diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 3564c17f9..f802d7b4a 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -903,6 +903,9 @@ impl<'a> Renderer<'a> { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float).hash(&mut h); + // Every file of a sequence: the key must tell two projects apart whose items + // share an id and a first frame (on disk, no project-wide salt does, #3184). + f.sequence.hash(&mut h); (f.alpha as u8).hash(&mut h); if f.alpha == effectcraft_project::AlphaMode::Premultiplied { f.premul_color.map(f32::to_bits).hash(&mut h); From 642fcb7bcb5720c74837dfe61c905399e5f6eab1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 01:05:11 +0100 Subject: [PATCH 021/324] Disk cache: the comp key covers what its expressions can read With an expression anywhere in the project, every comp's disk key hashed every item of the project, so any edit (another comp, an unused footage item) threw away every comp's frames on disk. The key now covers what the comp can draw plus what the expressions among it can reach (Project::pixel_reach): - without expressions: the items the comp draws, without silent layers, plus the footage its precomp layers swap in (Media Replacement); - with expressions: every layer of the comps they reach, their markers, the comps and footage they name with string literals (comp("Name"), footage("Name")) together with which items have those names now, and the footage named like a reached source (its data is read by name); - the whole project when an expression computes a name, uses the object model's constructors or internals, dynamic code, computed keys or writes, or text the scanner can't read for sure (regex literals, template strings, escapes): expression_reach errs towards reaching more. Markers count only where an expression can read them (#1083). Memory only, no file is looked at. Tests: scanner and reach unit tests in the project crate; engine tests for the key (own-comp expressions keep the key through edits elsewhere, comp("Other") follows Other and not a third comp, a second comp taking the name counts, a computed name counts every item, markers read from another comp); a ui-egui test that the disk frames outside an expression layer are carried when the comp it names changes. Part of #3184. Part of #1492. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests/disk_cache.rs | 97 +++++++ crates/project/src/lib.rs | 2 + crates/project/src/reach.rs | 401 ++++++++++++++++++++++++++ crates/project/src/reach/tests.rs | 177 ++++++++++++ crates/render/src/disk_cache.rs | 52 ++-- crates/ui-egui/src/frames/tests.rs | 74 +++++ 6 files changed, 774 insertions(+), 29 deletions(-) create mode 100644 crates/project/src/reach.rs create mode 100644 crates/project/src/reach/tests.rs diff --git a/crates/engine/src/tests/disk_cache.rs b/crates/engine/src/tests/disk_cache.rs index e2b1544b3..8f4973ae3 100644 --- a/crates/engine/src/tests/disk_cache.rs +++ b/crates/engine/src/tests/disk_cache.rs @@ -242,3 +242,100 @@ fn protected_markers_with_a_duration_change_the_content_key() { s.execute("markers.set", json!({"comp": inner.0, "index": index, "duration": 2.0})).unwrap(); assert_ne!(key(&s), k1, "its duration"); } + +/// With expressions the comp key covers what they can read, not the whole project (#3184, +/// #1492): an expression reading only its own comp keeps the key through edits of another comp +/// and of unused footage; `comp("Other")` makes "Other" count (and which comps have that name), +/// not a third comp; a computed name counts every item. +#[test] +fn expressions_reach_only_what_they_name() { + let mut s = Session::default(); + let comp = |s: &mut Session, name: &str| { + let c = s.execute("comp.new", json!({"name": name, "width": 8, "height": 8, "frameRate": 30, "duration": 1})).unwrap()["comp"].as_u64().unwrap(); + let l = s.execute("layer.newSolid", json!({"comp": c, "color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + (effectcraft_project::ItemId(c), (c, l)) + }; + let (main, ml) = comp(&mut s, "Main"); + let (_, ol) = comp(&mut s, "Other"); + let (third, tl) = comp(&mut s, "Third"); + let unused = s.edit("add", None, |p, _| { + let f = effectcraft_project::Footage { path: "/nowhere/a.png".into(), has_video: true, ..Default::default() }; + Ok(p.add_item("a.png", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f))) + }); + let unused = unused.unwrap(); + let key = |s: &Session| effectcraft_render::disk_cache::comp_content_key(&s.project, main); + let expr = |s: &mut Session, (comp, layer): (u64, u64), text: &str| { + s.execute("prop.setExpression", json!({"comp": comp, "layer": layer, "path": "transform/opacity", "expression": text})).unwrap(); + }; + let opacity = |s: &mut Session, (comp, layer): (u64, u64), v: f64| { + s.execute("prop.set", json!({"comp": comp, "layer": layer, "path": "transform/opacity", "value": v})).unwrap(); + }; + let repath = |s: &mut Session, path: &str| { + let path = path.to_string(); + s.edit("repath", None, move |p, _| { + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(unused).map(|i| &mut i.kind) { + f.path = path; + } + Ok(()) + }) + .unwrap(); + }; + // Its own comp only. + expr(&mut s, ml, "thisComp.layer(1).transform.rotation + wiggle(1, 1)[0]"); + expr(&mut s, ol, "wiggle(2, 10)"); + let k0 = key(&s); + opacity(&mut s, ol, 40.0); + expr(&mut s, tl, "time * 10"); + repath(&mut s, "/nowhere/b.png"); + s.execute("comp.addMarker", json!({"comp": third.0, "time": 0.5})).unwrap(); + assert_eq!(key(&s), k0, "edits elsewhere keep the key"); + // An edit in the comp itself changes it. + opacity(&mut s, ml, 30.0); + assert_ne!(key(&s), k0); + // `comp("Other")`: Other counts, Third doesn't. + expr(&mut s, ml, "comp(\"Other\").layer(1).transform.opacity"); + let k1 = key(&s); + expr(&mut s, ol, "wiggle(3, 10)"); + let k2 = key(&s); + assert_ne!(k2, k1, "the comp it names"); + opacity(&mut s, tl, 20.0); + repath(&mut s, "/nowhere/c.png"); + assert_eq!(key(&s), k2, "a comp it doesn't name"); + // Another comp taking the name changes what it may read. + s.edit("rename", None, |p, _| { + p.item_mut(third).unwrap().name = "Other".into(); + Ok(()) + }) + .unwrap(); + let k3 = key(&s); + assert_ne!(k3, k2, "a second comp named Other"); + // A computed name reaches every item. + expr(&mut s, ml, "comp(\"Oth\" + \"er\").layer(1).transform.opacity"); + let k4 = key(&s); + repath(&mut s, "/nowhere/d.png"); + assert_ne!(key(&s), k4, "unused footage counts with a computed name"); +} + +/// Markers count only for the comps whose expressions can read them (#1083): an expression in +/// another comp that reads markers leaves this comp's markers out of its key. +#[test] +fn markers_count_only_where_an_expression_can_read_them() { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "M", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap(); + let cid = s.active_comp_id().unwrap(); + s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap(); + let other = s.execute("comp.new", json!({"name": "N", "width": 8, "height": 8, "frameRate": 30, "duration": 2})).unwrap()["comp"].as_u64().unwrap(); + let ol = s.execute("layer.newSolid", json!({"comp": other, "color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("prop.setExpression", json!({"comp": other, "layer": ol, "path": "transform/opacity", "expression": "thisComp.marker.numKeys"})).unwrap(); + let key = |s: &Session| effectcraft_render::disk_cache::comp_content_key(&s.project, cid); + let k0 = key(&s); + s.execute("comp.addMarker", json!({"comp": cid.0, "time": 0.5, "comment": "beat"})).unwrap(); + assert_eq!(key(&s), k0, "no expression of M reads its markers"); + s.execute("prop.setExpression", json!({"comp": other, "layer": ol, "path": "transform/opacity", "expression": "comp(\"M\").marker.numKeys"})).unwrap(); + let other_key = |s: &Session| effectcraft_render::disk_cache::comp_content_key(&s.project, effectcraft_project::ItemId(other)); + let n0 = other_key(&s); + s.execute("comp.addMarker", json!({"comp": cid.0, "time": 1.0})).unwrap(); + assert_ne!(other_key(&s), n0, "N reads M's markers"); + assert_eq!(key(&s), k0, "M itself still doesn't"); +} + diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 079b81765..c9322ac37 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -35,6 +35,7 @@ mod footage; mod item; mod layer; mod layers; +mod reach; mod settings; pub use comp::{Comp, Guide, Renderer, Resolution}; @@ -46,6 +47,7 @@ pub use layer::{ reads_other_frames, }; pub use layers::Layers; +pub use reach::{ExprReach, PixelReach, expression_reach}; pub use settings::{ APP_VERSION, BitDepth, ColorEngine, CuePoint, HdrMode, Marker, ProjectError, ProjectSettings, SCHEMA_EFFECT_SPACE, SCHEMA_VERSION, SavedView, TimeDisplayStyle, is_newer_version, saved_by, saved_view, diff --git a/crates/project/src/reach.rs b/crates/project/src/reach.rs new file mode 100644 index 000000000..dd510f9db --- /dev/null +++ b/crates/project/src/reach.rs @@ -0,0 +1,401 @@ +//! What a composition's pixels can depend on, from the project in memory: the items it draws +//! and, when expressions are among them, what those expressions can read (#3184). The disk +//! cache keys a comp's frames by exactly these items, so an edit elsewhere in the project keeps +//! them. +//! +//! An expression reaches its own comp's layers (`thisComp`, `thisLayer`), the sources of the +//! layers it can read (`layer.source`, a precomp's layers through it), and other items by name: +//! `comp("Name")` and `footage("Name")`. A name given as a plain string literal is followed; a +//! computed name (`comp("Shot " + index)`), the object model's constructors and internals +//! (`new Comp(7)`, `__h`), dynamic code (`eval`, `Function`) and anything the scanner can't read +//! for sure (a regular expression literal, a template string, an escape in a name) count as +//! reaching every item of the project. The scan errs on the side of reaching more: an item +//! wrongly left out would serve a stale frame, one wrongly let in only renders again. +//! +//! Known limit (`ponytail`): an expression that builds the names of the object model's private +//! fields at run time into a variable and writes them with a computed key it reads from that +//! variable could forge another comp's id. That is deliberate tampering with the internals, not +//! an expression one writes; the scan refuses every direct form of it (`__` names, the +//! constructors, `Object`, `JSON`, `call`/`apply`/`bind`, computed writes and computed keys). +//! Upgrade: have the expression host record which items an evaluation reached. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::{Comp, ItemId, ItemKind, LayerId, LayerSource, Node, Project, PropGroup, Value}; + +/// What an expression's text can reach outside its own comp and the layers it can read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExprReach { + /// Only items named by string literals: comps by `comp("…")`, footage by `footage("…")`. + Names { comps: Vec, footage: Vec }, + /// Any item of the project. + Anything, +} + +/// Names that hand an expression another item by id, run code built at run time, or give it the +/// tools to forge the object model's private fields. +const REACHES_ANYTHING: &[&str] = &[ + "Comp", + "Footage", + "Layer", + "Prop", + "Markers", + "eval", + "Function", + "globalThis", + "this", + "self", + "window", + "arguments", + "constructor", + "prototype", + "Object", + "Reflect", + "Proxy", + "JSON", + "call", + "apply", + "bind", + "class", + "with", + "import", + "require", + "fromCharCode", + "fromCodePoint", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getPrototypeOf", + "setPrototypeOf", + "defineProperty", +]; + +/// Keywords after which a `/` starts a regular expression. +const BEFORE_REGEX: &[&str] = &["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]; + +/// Keywords whose `( … )` a regular expression may follow (`if (a) /x/.test(s)`). +const CONTROL: &[&str] = &["if", "while", "for", "with"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Tok<'a> { + Ident(&'a str), + /// A string literal's text between its quotes; `plain` when it has no escape. + Str { + text: &'a str, + plain: bool, + }, + Num, + Punct(u8), +} + +/// The tokens of `text`, or `None` when it can't be read for sure. +fn tokens(text: &str) -> Option>> { + let b = text.as_bytes(); + let mut out: Vec> = Vec::new(); + // Per open `(`: whether a control keyword is before it; whether the last `)` closed one + // (only looked at right after a `)`). + let mut parens: Vec = Vec::new(); + let mut control_close = false; + let mut i = 0; + while let Some(&c) = b.get(i) { + match c { + b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c => i += 1, + b'/' if b.get(i + 1) == Some(&b'/') => { + while b.get(i).is_some_and(|c| *c != b'\n') { + i += 1; + } + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = text.get(i + 2..)?.find("*/")?; + i += 2 + end + 2; + } + b'/' => { + if regex_may_start(out.last(), control_close) { + return None; + } + out.push(Tok::Punct(c)); + i += 1; + } + b'"' | b'\'' => { + let start = i + 1; + let mut j = start; + let mut plain = true; + loop { + match *b.get(j)? { + q if q == c => break, + b'\n' | b'\r' => return None, + b'\\' => { + // Only escapes that can't spell a name: `\n`, `\t`, a quote... + if !matches!(b.get(j + 1)?, b'n' | b'r' | b't' | b'b' | b'f' | b'v' | b'\'' | b'"' | b'\\') { + return None; + } + plain = false; + j += 2; + } + _ => j += 1, + } + } + let s = text.get(start..j)?; + if s.contains("__") { + return None; + } + out.push(Tok::Str { text: s, plain }); + i = j + 1; + } + b'0'..=b'9' => { + while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'.') { + i += 1; + } + out.push(Tok::Num); + } + b'.' if b.get(i + 1).is_some_and(u8::is_ascii_digit) => { + i += 1; + while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'.') { + i += 1; + } + out.push(Tok::Num); + } + c if c.is_ascii_alphabetic() || c == b'_' || c == b'$' => { + let start = i; + while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'$') { + i += 1; + } + out.push(Tok::Ident(text.get(start..i)?)); + } + // A template string (code inside `${}`), an escaped identifier, a name in another + // alphabet: not followed. + b'`' | b'\\' => return None, + c if !c.is_ascii() => return None, + c => { + match c { + b'(' => parens.push(matches!(out.last(), Some(Tok::Ident(k)) if CONTROL.contains(k))), + b')' => control_close = parens.pop().unwrap_or(false), + _ => {} + } + out.push(Tok::Punct(c)); + i += 1; + } + } + } + Some(out) +} + +/// Whether a `/` after `prev` may start a regular expression literal (which the scanner doesn't +/// read: its text could hide a quote). +fn regex_may_start(prev: Option<&Tok<'_>>, control_close: bool) -> bool { + match prev { + None => true, + Some(Tok::Ident(k)) => BEFORE_REGEX.contains(k), + Some(Tok::Num | Tok::Str { .. }) => false, + Some(Tok::Punct(b')')) => control_close, + Some(Tok::Punct(b']')) => false, + Some(Tok::Punct(_)) => true, + } +} + +/// What the expression `text` can reach by name, or [`ExprReach::Anything`]. +pub fn expression_reach(text: &str) -> ExprReach { + expression_names(text).map_or(ExprReach::Anything, |(comps, footage)| ExprReach::Names { comps, footage }) +} + +fn expression_names(text: &str) -> Option<(Vec, Vec)> { + let toks = tokens(text)?; + let (mut comps, mut footage) = (Vec::new(), Vec::new()); + // Per open `[`: a computed key (`{[k]: v}`), a computed member (`o[k]`). + let mut brackets: Vec<(bool, bool)> = Vec::new(); + for (i, t) in toks.iter().enumerate() { + let prev = i.checked_sub(1).and_then(|p| toks.get(p)); + let next = |n: usize| toks.get(i + n); + match *t { + Tok::Ident(name) if name.starts_with("__") || REACHES_ANYTHING.contains(&name) => return None, + Tok::Ident(name @ ("comp" | "footage")) => { + // Only a call with a plain literal, not a property of something else. + let (Some(Tok::Punct(b'(')), Some(Tok::Str { text, plain: true }), Some(Tok::Punct(b')'))) = (next(1), next(2), next(3)) else { return None }; + if matches!(prev, Some(Tok::Punct(b'.'))) { + return None; + } + if name == "comp" { comps.push((*text).to_string()) } else { footage.push((*text).to_string()) } + } + Tok::Punct(b'[') => { + let key = matches!(prev, Some(Tok::Punct(b'{' | b',')) | Some(Tok::Ident("get" | "set" | "static" | "async")) | Some(Tok::Punct(b'*'))); + let member = matches!(prev, Some(Tok::Ident(_) | Tok::Str { .. } | Tok::Num | Tok::Punct(b')' | b']' | b'.'))); + brackets.push((key, member)); + } + Tok::Str { .. } if brackets.last().is_some_and(|(_, member)| *member) => return None, + Tok::Punct(b']') => { + let (key, _) = brackets.pop().unwrap_or((true, true)); + // A computed key (`{[k]: v}`, `{[k]() {}}`) or a write through brackets (`o[k] = v`, + // `o[k] ||= v`, `for (o[k] in …)`, `[o[k]] = v`) could name a private field. + if key && matches!(next(1), Some(Tok::Punct(b':' | b'('))) { + return None; + } + if assigns(&toks, i + 1) || matches!(next(1), Some(Tok::Ident("in" | "of"))) { + return None; + } + } + // A destructuring write (`({a: o[k]} = v)`). + Tok::Punct(b'}') if assigns(&toks, i + 1) => return None, + _ => {} + } + } + Some((comps, footage)) +} + +/// Whether the tokens from `at` are an assignment operator (`=`, `+=`, `>>>=`, `??=`...), not a +/// comparison (`==`, `<=`) or an arrow (`=>`). +fn assigns(toks: &[Tok<'_>], at: usize) -> bool { + let mut op = Vec::new(); + for t in toks.iter().skip(at).take(5) { + match t { + Tok::Punct(c) if b"+-*/%&|^<>?=".contains(c) => op.push(*c), + _ => break, + } + } + let Some(eq) = op.iter().position(|c| *c == b'=') else { return false }; + let (before, after) = op.split_at(eq); + if after.get(1).is_some_and(|c| *c == b'=' || *c == b'>') { + return false; + } + matches!(before, b"" | b"+" | b"-" | b"*" | b"/" | b"%" | b"&" | b"|" | b"^" | b"**" | b"<<" | b">>" | b">>>" | b"&&" | b"||" | b"??") +} + +/// The items a comp's pixels can depend on ([`Project::pixel_reach`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PixelReach { + /// The items whose state counts; `None`: every item of the project. + pub items: Option>, + /// Expressions are among them: they can read every layer of the comps they reach (hidden + /// and silent ones too) and the markers, which therefore count as well (#1083). + pub expressions: bool, + /// The names expressions look items up by (`true`: a comp's, `false`: footage's), each with + /// the ids of the items of that kind that have it now, in id order (the first one is what + /// the lookup finds; another item taking or giving up the name changes it). + pub names: Vec<(bool, String, Vec)>, +} + +/// Each property of a group and its subgroups (iterative: no depth limit to hit). +fn each_prop<'a>(g: &'a PropGroup, f: &mut dyn FnMut(&'a crate::Property) -> Option<()>) -> Option<()> { + let mut stack = vec![g]; + while let Some(g) = stack.pop() { + for n in &g.children { + match n { + Node::Prop(p) => f(p)?, + Node::Group(sub) => stack.push(sub), + } + } + } + Some(()) +} + +impl Project { + /// The items comp `comp` draws ([`Self::silent_layers`] aside, with `heard`) and the + /// footage its precomp layers swap in (Essential Graphics Media Replacement); with an + /// expression in any of its comps, everything those expressions can reach + /// ([`expression_reach`]). Memory only: no file is looked at. + pub fn pixel_reach(&self, comp: ItemId, heard: &crate::Heard) -> PixelReach { + let Some(drawn) = self.reach_walk(comp, &|id, c| self.silent_layers(id, c, heard), &mut |_| Some(vec![])) else { return PixelReach::every() }; + let has_expression = |g: &PropGroup| each_prop(g, &mut |p| p.expr.is_none().then_some(())).is_none(); + if !drawn.iter().filter_map(|id| self.comp(*id)).any(|c| c.layers.iter().any(|l| has_expression(&l.props))) { + return PixelReach { items: Some(drawn), expressions: false, names: vec![] }; + } + // Expressions: every layer of a comp they reach counts, and what they name. + let mut names: BTreeMap<(bool, String), Vec> = BTreeMap::new(); + let mut scan = |p: &crate::Property| match p.expr.as_ref().map(|e| expression_reach(&e.text)) { + None => Some(vec![]), + Some(ExprReach::Anything) => None, + Some(ExprReach::Names { comps, footage }) => { + let mut found = vec![]; + for (is_comp, name) in comps.into_iter().map(|n| (true, n)).chain(footage.into_iter().map(|n| (false, n))) { + let ids = self.named(is_comp, &name); + found.extend(ids.iter().copied()); + names.insert((is_comp, name), ids); + } + Some(found) + } + }; + let Some(mut items) = self.reach_walk(comp, &|_, _| BTreeSet::new(), &mut scan) else { return PixelReach::every() }; + // A source's data is read by its name (`layer.source.sourceData`). + let footage_names: BTreeSet<&str> = + items.iter().filter_map(|id| self.item(*id)).filter(|i| matches!(i.kind, ItemKind::Footage(_))).map(|i| i.name.as_str()).collect(); + let same_name: Vec = + self.items.values().filter(|i| matches!(i.kind, ItemKind::Footage(_)) && footage_names.contains(i.name.as_str())).map(|i| i.id).collect(); + items.extend(same_name); + PixelReach { items: Some(items), expressions: true, names: names.into_iter().map(|((c, n), ids)| (c, n, ids)).collect() } + } + + /// The items of one kind (`is_comp`: comps, else footage) named `name`, in id order. + fn named(&self, is_comp: bool, name: &str) -> Vec { + self.items + .values() + .filter(|i| i.name == name && if is_comp { matches!(i.kind, ItemKind::Comp(_)) } else { matches!(i.kind, ItemKind::Footage(_)) }) + .map(|i| i.id) + .collect() + } + + /// The items reached from `comp` through its layers (but those `quiet` names) and the items + /// `scan` returns for each of their properties; `None` when something reaches every item. + /// (A stack and a visited set: each item is visited once, cycles included.) + fn reach_walk( + &self, + comp: ItemId, + quiet: &dyn Fn(ItemId, &Comp) -> BTreeSet, + scan: &mut dyn FnMut(&crate::Property) -> Option>, + ) -> Option> { + let mut seen = BTreeSet::new(); + let mut stack = vec![comp]; + while let Some(id) = stack.pop() { + if !seen.insert(id) { + continue; + } + let Some(c) = self.comp(id) else { continue }; + let quiet = quiet(id, c); + for l in c.layers.iter().filter(|l| !quiet.contains(&l.id)) { + if let LayerSource::Comp { item } | LayerSource::Footage { item } | LayerSource::Solid { item } = l.source { + stack.push(item); + } + stack.extend(self.media_replacements(l)?); + let mut reached = vec![]; + each_prop(&l.props, &mut |p| { + reached.extend(scan(p)?); + Some(()) + })?; + stack.extend(reached); + } + } + Some(seen) + } + + /// The footage a precomp layer swaps in through its Essential Properties (Media Replacement): + /// the items its overridden properties name. `None` when they can't be listed (an + /// expression or keyframes choose the item over time). + fn media_replacements(&self, layer: &crate::Layer) -> Option> { + let over = crate::essential::overridden(layer); + let Some(g) = crate::essential::group(layer).filter(|_| !over.is_empty()) else { return Some(vec![]) }; + let mut out = vec![]; + each_prop(g, &mut |p| { + if !over.contains(&p.uid) { + return Some(()); + } + if p.expr.is_some() || !p.keys.is_empty() { + return None; + } + if let Value::Scalar(id) = p.value { + let item = ItemId(id.max(0.0) as u64); + if matches!(self.item(item).map(|i| &i.kind), Some(ItemKind::Footage(_))) { + out.push(item); + } + } + Some(()) + })?; + Some(out) + } +} + +impl PixelReach { + /// Every item of the project, with expressions. + fn every() -> PixelReach { + PixelReach { items: None, expressions: true, names: vec![] } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/project/src/reach/tests.rs b/crates/project/src/reach/tests.rs new file mode 100644 index 000000000..3a195088d --- /dev/null +++ b/crates/project/src/reach/tests.rs @@ -0,0 +1,177 @@ +use super::*; +use crate::{Expression, Solid, build}; +use effectcraft_time::{FrameRate, Tick}; + +fn names(comps: &[&str], footage: &[&str]) -> ExprReach { + ExprReach::Names { comps: comps.iter().map(|s| s.to_string()).collect(), footage: footage.iter().map(|s| s.to_string()).collect() } +} + +/// Expressions that read their own comp, or other items by literal names, are followed; every +/// way to reach items by a computed name or an id, or text the scanner can't read for sure, +/// reaches everything. +#[test] +fn expression_reach_follows_literal_names_and_refuses_the_rest() { + let follows = [ + ("wiggle(2, 20)", names(&[], &[])), + ("thisComp.layer(\"Comp 1 Layer\").transform.opacity * 2 / 3", names(&[], &[])), + ("value + [10, 0]; value[0] / 2", names(&[], &[])), + ("// comp(name) in a comment\n/* footage(x) */ value", names(&[], &[])), + ("\"a string that says comp(x) and Layer\"", names(&[], &[])), + ("comp(\"Other\").layer(1).transform.position", names(&["Other"], &[])), + ("comp( 'A' ).width + comp(\"B\").height", names(&["A", "B"], &[])), + ("footage(\"data.json\").sourceData.x", names(&[], &["data.json"])), + ("x = a[0] <= b ? a[1] : 0; y = a[0] == 1", names(&[], &[])), + ("thisLayer.source.layer(1).name", names(&[], &[])), + ("if (a) x = 1; else x = 2; (a + b) / 2", names(&[], &[])), + ("\"Ünïcödé name\"", names(&[], &[])), + ("const f = (v) => v * 2; f(1)", names(&[], &[])), + ]; + for (text, want) in follows { + assert_eq!(expression_reach(text), want, "{text}"); + } + let anything = [ + "comp(\"Shot \" + index).layer(1)", + "comp(name)", + "var n = \"Other\"; comp(n)", + "comp(\"O\\\"ther\")", + "x.comp(\"Other\")", + "var comp = 1", + "footage(thisComp.name)", + "new Comp(7).layer(1)", + "Layer(7, 3).name", + "__h(__COMP, 7)", + "o.__c = 7", + "eval('1')", + "Function('return 1')()", + "this.x", + "({}).constructor", + "Object.getPrototypeOf(thisComp)", + "JSON.parse(s)", + "thisComp.layer.call(o, 1)", + "o['_' + '_c']", + "o[k] = 7", + "o[k] ||= 7", + "o[k] += 7", + "[o[k]] = [7]", + "({a: o[k]} = {a: 7})", + "for (o[k] in x) {}", + "({[k]: 7})", + "({a: 1, [k]: 7})", + "o = {'__c': 7}", + "'\\x5f\\x5fc'", + "'\\_\\_c'", + "`${x}`", + "c\\u006fmp('A')", + "comp\u{0430}('A')", + "/\"/.test(s); comp(n); \"", + "return /x/", + "if (a) /\"/.test(s)", + "x = '", + "/* comp(n)", + "class X {}", + "String.fromCharCode(95)", + ]; + for text in anything { + assert_eq!(expression_reach(text), ExprReach::Anything, "{text}"); + } +} + +/// `a / b` divides after a name, a number, a string and a closing bracket or parenthesis. +#[test] +fn division_is_not_a_regular_expression() { + for text in ["a / b", "2 / 3", "'a' / 2", "x[0] / 2", "(a + b) / 2", "f(x) / 2 / g(y)"] { + assert_eq!(expression_reach(text), names(&[], &[]), "{text}"); + } +} + +struct Fixture { + p: Project, + main: ItemId, + other: ItemId, + third: ItemId, + unused: ItemId, + solid: ItemId, +} + +/// Comps "Main" (a solid), "Other" (a solid), "Third" (empty), an unused footage item. +fn fixture() -> Fixture { + let mut p = Project::default(); + let comp = Comp::new(64, 64, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + let solid = + p.add_item("Solid", effectcraft_color::Label::None, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 64, height: 64, pixel_aspect: 1.0 })); + let main = p.add_item("Main", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let other = p.add_item("Other", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let third = p.add_item("Third", effectcraft_color::Label::None, None, ItemKind::Comp(comp.clone().into())); + let unused = p.add_item("unused.png", effectcraft_color::Label::None, None, ItemKind::Footage(crate::Footage { has_video: true, ..Default::default() })); + for c in [main, other] { + let l = build::layer(&mut p, &comp, "S", LayerSource::Solid { item: solid }, (64, 64), None); + p.comp_mut(c).unwrap().layers.push(l); + } + Fixture { p, main, other, third, unused, solid } +} + +fn set_expr(p: &mut Project, comp: ItemId, text: &str) { + let l = p.comp_mut(comp).unwrap().layers.first_mut().unwrap(); + l.props.prop_mut("transform/opacity").unwrap().expr = Some(Expression { text: text.into(), enabled: true }); +} + +fn reach(p: &Project, comp: ItemId) -> PixelReach { + p.pixel_reach(comp, &p.heard_layers()) +} + +#[test] +fn pixel_reach_is_what_the_comp_draws_and_what_its_expressions_name() { + let mut f = fixture(); + let ids = |r: &PixelReach| r.items.clone().map(|s| s.into_iter().collect::>()); + assert_eq!(reach(&f.p, f.main), PixelReach { items: Some([f.solid, f.main].into()), expressions: false, names: vec![] }); + // An expression reading only its own comp: what it draws, with expressions. + set_expr(&mut f.p, f.main, "thisComp.layer(1).transform.opacity"); + let r = reach(&f.p, f.main); + assert!(r.expressions); + assert_eq!(ids(&r), Some(vec![f.solid, f.main])); + // An expression in another comp doesn't reach this one. + set_expr(&mut f.p, f.other, "wiggle(1, 1)"); + assert_eq!(ids(&reach(&f.p, f.main)), Some(vec![f.solid, f.main])); + // A literal name: that comp and what it draws, with the name and the comps that have it. + set_expr(&mut f.p, f.main, "comp(\"Other\").layer(1).transform.opacity"); + let r = reach(&f.p, f.main); + assert_eq!(ids(&r), Some(vec![f.solid, f.main, f.other])); + assert_eq!(r.names, vec![(true, "Other".to_string(), vec![f.other])]); + // Another comp taking the name is part of it, whichever the lookup finds. + f.p.item_mut(f.third).unwrap().name = "Other".into(); + let r = reach(&f.p, f.main); + assert_eq!(r.names, vec![(true, "Other".to_string(), vec![f.other, f.third])]); + assert!(r.items.unwrap().contains(&f.third)); + // A name no item has yet still counts (with no item). + set_expr(&mut f.p, f.main, "footage(\"later.json\").sourceData"); + assert_eq!(reach(&f.p, f.main).names, vec![(false, "later.json".to_string(), vec![])]); + // A computed name reaches everything. + set_expr(&mut f.p, f.main, "comp(\"Ot\" + \"her\").width"); + assert_eq!(reach(&f.p, f.main), PixelReach { items: None, expressions: true, names: vec![] }); + // Footage reached as a layer's source brings the footage of its name (its data is read by + // name). + let comp = f.p.comp(f.main).unwrap().clone(); + let l = build::layer(&mut f.p, &comp, "U", LayerSource::Footage { item: f.unused }, (64, 64), None); + f.p.comp_mut(f.main).unwrap().layers.push(l); + let twin = f.p.add_item("unused.png", effectcraft_color::Label::None, None, ItemKind::Footage(crate::Footage::default())); + set_expr(&mut f.p, f.main, "value"); + let r = reach(&f.p, f.main).items.unwrap(); + assert!(r.contains(&f.unused) && r.contains(&twin), "{r:?}"); +} + +/// A comp nested in the reach is scanned too: its expression's names count for the outer comp. +#[test] +fn nested_comps_bring_their_expressions_reach() { + let mut f = fixture(); + let comp = f.p.comp(f.main).unwrap().clone(); + let pre = build::layer(&mut f.p, &comp, "Pre", LayerSource::Comp { item: f.other }, (64, 64), None); + f.p.comp_mut(f.main).unwrap().layers.push(pre); + set_expr(&mut f.p, f.other, "comp(\"Third\").width"); + let r = reach(&f.p, f.main); + assert!(r.expressions && r.items.unwrap().contains(&f.third)); + // A cycle through names ends. + let l = build::layer(&mut f.p, &comp, "S", LayerSource::Solid { item: f.solid }, (64, 64), None); + f.p.comp_mut(f.third).unwrap().layers.push(l); + set_expr(&mut f.p, f.third, "comp(\"Main\").width"); + assert!(reach(&f.p, f.main).items.unwrap().contains(&f.main)); +} diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 93c949ff2..61f2d8240 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -1183,44 +1183,38 @@ pub fn layer_disk_key(key: u64) -> u128 { /// Content key of a composition's pixels, from the project in memory alone (no file is looked /// at: the frame entries check their own source files when read, see [`EntryFiles`]): project -/// render settings, the comp and everything it uses (nested comps, footage items with their -/// settings and paths, solids, their proxies and Use Proxy switches). With expressions in play -/// (which can read any comp) the whole project counts. Switches that don't change pixels (Audio, -/// Lock, Shy, Hide Shy Layers) don't count, and neither do markers unless an expression mentions -/// them. +/// render settings, the comp and the items it can draw (nested comps, footage items with their +/// settings and paths, solids, Media Replacement footage, their proxies and Use Proxy switches; +/// [`effectcraft_project::Project::pixel_reach`]). With expressions among them, everything those +/// expressions can read counts too: every layer of their comps, markers, the comps and footage +/// they name with literal names (and which items have those names), or the whole project when +/// they compute a name or reach items another way. An edit to an item the comp can't reach keeps +/// its key and its frames on disk (#3184, #1492). Switches that don't change pixels (Audio, Lock, +/// Shy, Hide Shy Layers) don't count, and neither do markers unless an expression can read them. pub fn comp_content_key(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId) -> u128 { comp_content_key_for_renderer(project, comp, RENDER_VERSION) } fn comp_content_key_for_renderer(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId, renderer: &str) -> u128 { - use effectcraft_project::{ItemKind, LayerSource}; + use effectcraft_project::ItemKind; let mut h = Hash128::default(); h.write(renderer.as_bytes()); hash_debug(&mut h, &project.settings); - // Expressions can read anything (every item counts); without them, layers that can't - // change the picture (music, hidden layers nothing reads) and their files don't count. - let expressions = project.reads_markers(); let heard = project.heard_layers(); + let reach = project.pixel_reach(comp, &heard); + // Expressions can read any layer of the comps they reach, hidden or not, and their markers + // (#1083); without them, layers that can't change the picture (music, hidden layers nothing + // reads) don't count. + let expressions = reach.expressions; let silent = |id, c: &effectcraft_project::Comp| if expressions { Default::default() } else { project.silent_layers(id, c, &heard) }; - let mut seen = std::collections::BTreeSet::new(); - let mut stack = vec![comp]; - while let Some(id) = stack.pop() { - if !seen.insert(id) { - continue; - } - let Some(it) = project.item(id) else { continue }; - if let ItemKind::Comp(c) = &it.kind { - let quiet = silent(id, c); - for l in c.layers.iter().filter(|l| !quiet.contains(&l.id)) { - if let LayerSource::Comp { item } | LayerSource::Footage { item } | LayerSource::Solid { item } = l.source { - stack.push(item); - } - } - } + // (the names expressions look items up by: which items have them now) + if !reach.names.is_empty() { + hash_debug(&mut h, &reach.names); } - // Markers are pixels only to the expressions that read them (#1083). - let markers = expressions; - let ids: Vec = if expressions { project.items.keys().copied().collect() } else { seen.into_iter().collect() }; + let ids: Vec = match reach.items { + Some(items) => items.into_iter().collect(), + None => project.items.keys().copied().collect(), + }; for id in ids { let Some(it) = project.item(id) else { continue }; h.write_u64(id.0); @@ -1230,11 +1224,11 @@ fn comp_content_key_for_renderer(project: &effectcraft_project::Project, comp: e let quiet = silent(id, c); let heard = |l| heard.contains(id, l); if quiet.is_empty() { - hash_debug(&mut h, &c.pixel_form_with(markers, &heard)); + hash_debug(&mut h, &c.pixel_form_with(expressions, &heard)); } else { let mut pic = (**c).clone(); pic.layers.retain(|l| !quiet.contains(&l.id)); - hash_debug(&mut h, &pic.pixel_form_with(markers, &heard)); + hash_debug(&mut h, &pic.pixel_form_with(expressions, &heard)); } } k => hash_debug(&mut h, k), diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index 596f3054a..2644095f4 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -1975,6 +1975,80 @@ fn disk_frames_outlive_an_edit_that_cant_change_them() { let _ = std::fs::remove_dir_all(&dir); } +/// With expressions the disk key covers what they can read (#3184, #1492): an edit to a comp no +/// expression names keeps every frame on disk under the same key; an edit to the comp one names +/// gives the comp a new key, and the frames outside the layer with that expression are carried to +/// it (the dirty spans of #2795). +#[test] +fn disk_frames_outlive_edits_their_expressions_cant_read() { + use effectcraft_engine::Session; + use effectcraft_engine::project::{Expression, LayerId, Value}; + use serde_json::json; + let dir = std::env::temp_dir().join(format!("ec-disk-carry-expr-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let disk = DiskCache::open(&dir, 1 << 30).unwrap(); + let mut s = Session::default(); + let comp = |s: &mut Session, name: &str| { + ItemId(s.execute("comp.new", json!({"name": name, "width": 8, "height": 8, "duration": 1, "frameRate": 30})).unwrap()["comp"].as_u64().unwrap()) + }; + let solid = |s: &mut Session, c: ItemId| LayerId(s.execute("layer.newSolid", json!({"comp": c.0, "color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap()); + let cid = comp(&mut s, "A"); + let (a, b) = (solid(&mut s, cid), solid(&mut s, cid)); + let other = comp(&mut s, "Other"); + let o = solid(&mut s, other); + let third = comp(&mut s, "Third"); + let t = solid(&mut s, third); + let fr = s.project.comp(cid).unwrap().frame_rate; + let mut p0 = (*s.project).clone(); + for (l, i, out) in [(a, 0, 15), (b, 15, 30)] { + let l = p0.comp_mut(cid).unwrap().layer_mut(l).unwrap(); + (l.start_time, l.in_point, l.out_point) = (fr.tick_of(i), fr.tick_of(i), fr.tick_of(out)); + } + p0.comp_mut(cid).unwrap().layer_mut(a).unwrap().props.prop_mut("transform/opacity").unwrap().expr = + Some(Expression { text: "comp(\"Other\").layer(1).transform.opacity".into(), enabled: true }); + let p0 = Arc::new(p0); + let opts = RenderOpts::default(); + let oh = opts_hash(&opts); + let src = |p: &Arc| RenderSource { + project: p.clone(), + footage: Arc::new(effectcraft_engine::render::NoFootage), + expr: None, + layer_cache: Arc::default(), + gpu: None, + gpu_display: false, + disk: Some(disk.clone()), + }; + let content0 = disk_cache::comp_content_key(&p0, cid); + for f in 0..30 { + disk.put_frame_now(disk_cache::frame_key(content0, f, 1000, oh), 1, 1, &[1, 2, 3, 255], &ReadFiles::default()); + } + let opacity = |p: &mut Project, c: ItemId, l: LayerId| { + p.comp_mut(c).unwrap().layer_mut(l).unwrap().props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(40.0) + }; + for (name, edited, layer, same_key, kept) in [("Third", third, t, true, (0..30).collect::>()), ("Other", other, o, false, (17..30).collect())] { + let f = Frames::default(); + let series = |p: &Arc, rev: u64| FrameKey { revision: rev, content: f.content_of(p, rev, cid), comp: cid.0, opts: oh, ..key(0, 0, 0) }; + let blue = |p: &Arc, rev: u64, want: &[i64]| { + let base = series(p, rev); + let mut got = vec![]; + for _ in 0..1000 { + got = f.disk_frames(&src(p), &base, 0..30, &opts); + if got == want { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + got + }; + assert_eq!(blue(&p0, 1, &(0..30).collect::>()), (0..30).collect::>(), "{name}: before"); + let mut p1 = p0.clone(); + opacity(Arc::make_mut(&mut p1), edited, layer); + assert_eq!(disk_cache::comp_content_key(&p1, cid) == content0, same_key, "{name}: the key"); + assert_eq!(blue(&p1, 2, &kept), kept, "{name}: after"); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A keyframe edit re-renders only around the keys it changed: two keys either side (auto-Bezier /// and continuous tangents reach the neighbouring segments), and from the layer's in point when /// the first key changes. A static value or an expression still reaches the whole layer. Every From 0bf8bf2b5e0ca0f5239298f71d00337a8930453c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 01:11:55 +0100 Subject: [PATCH 022/324] Disk cache: Reload Footage drops the entries of its files, docs File > Reload Footage now deletes the frame and layer entries whose file lists name the reloaded item's files (DiskCache::drop_files), so a file replaced by one with the same size and modification time, which the check on hit can't tell apart, is read again. The index knows keys, not files: the writer thread reads the files section at the start of each frame and layer entry (not the pixels) after the writes queued before it, and deletes the entries that list one of the files. Until it is done, an entry made of one of them is a miss and frames aren't linked to new keys. The entries are gone for good, so they don't come back after a restart. Automatic reloads don't drop anything: they follow a changed stamp, which the check on hit catches. The browser needs nothing (its file identities are content hashes). Removed: disk_cache::seal, which steps 2 and 3 left without callers (the tests use seal_format). Updated the module, seal_format and forget_media docs, and docs/architecture.md / docs/web.md describe the final design: what is cached, keys from memory, file lists checked on hit, nothing scans the project, incomplete lists stay in memory, Reload Footage drops entries, edits keep the frames they can't change. Tests: render unit tests (same size and time passes the check but not the drop; other files' entries stay; an entry queued before the drop is dropped; a layer entry too; written again afterwards it is used; the drop survives a restart; a pending drop is a miss), and an engine test through file.reloadFootage. Closes #3184. Part of #1492. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/footage/footage_reload.rs | 14 +- crates/engine/src/tests/disk_cache.rs | 58 ++++++ crates/render/src/disk_cache.rs | 212 ++++++++++++++++++-- docs/architecture.md | 48 +++-- docs/web.md | 8 +- 5 files changed, 297 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/footage/footage_reload.rs b/crates/engine/src/footage/footage_reload.rs index 4232e1d11..2744d0224 100644 --- a/crates/engine/src/footage/footage_reload.rs +++ b/crates/engine/src/footage/footage_reload.rs @@ -6,7 +6,8 @@ //! or PDF page an item shows and its interpretation (alpha, conformed frame rate, pixel aspect, //! fields, colour). A Photoshop layer is found again by name when layers were added or removed //! around it. The media layer then forgets the file and the layer cache is emptied, so the next -//! render reads the new pixels. +//! render reads the new pixels; File ▸ Reload Footage also deletes the disk cache entries made of +//! the file (#3184). //! //! The automatic part compares each footage file's size and modification time with what they //! were when the file was last seen. The desktop app keeps a [`Watcher`]: a worker thread that @@ -279,6 +280,12 @@ fn reload(s: &mut Session, ids: &[ItemId], undoable: bool) -> crate::Result<(usi let n = updates.len(); apply_reloads(s, updates, undoable)?; forget_media(s, &paths); + // An explicit reload also reads files again that kept their size and time (the check on hit + // can't tell those apart): their entries in the disk cache go (#3184). An automatic one + // only follows a changed stamp, which the check catches. + if undoable && let Some(dc) = &s.disk_cache { + dc.drop_files(paths.iter().map(String::as_str)); + } Ok((n, failed)) } @@ -317,8 +324,9 @@ fn apply_reloads(s: &mut Session, updates: Vec<(ItemId, Footage)>, undoable: boo Ok(()) } -/// Make the media layer and the layer cache let go of `paths`, so renders read them again. The -/// disk cache needs nothing: its entries check the files they were made of when read (#3184). +/// Make the media layer and the layer cache let go of `paths`, so renders read them again. Disk +/// cache entries check the files they were made of when read (#3184); File ▸ Reload Footage +/// also drops the entries of its files ([`reload`]). pub(crate) fn forget_media(s: &mut Session, paths: &BTreeSet) { for p in paths { s.footage.forget(p); diff --git a/crates/engine/src/tests/disk_cache.rs b/crates/engine/src/tests/disk_cache.rs index 8f4973ae3..fed00e852 100644 --- a/crates/engine/src/tests/disk_cache.rs +++ b/crates/engine/src/tests/disk_cache.rs @@ -339,3 +339,61 @@ fn markers_count_only_where_an_expression_can_read_them() { assert_eq!(key(&s), k0, "M itself still doesn't"); } +/// File ▸ Reload Footage drops the disk entries made of the item's files (#3184): a file +/// replaced by one with the same size and modification time is read again (the check on hit +/// can't tell), and entries of other files stay. +#[test] +fn reload_footage_drops_the_entries_of_its_files() { + use crate::render::reads::{FileStamp, ReadFile, ReadFiles}; + struct Probe; + impl crate::Importer for Probe { + fn probe(&self, path: &str) -> std::result::Result { + Ok(effectcraft_project::Footage { + path: path.into(), + kind: effectcraft_project::FootageKind::Still, + width: 1, + height: 1, + has_video: true, + ..Default::default() + }) + } + } + let dir = folder("reload"); + let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() }; + s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": &dir, "disk.diskCacheEnabled": true}})).unwrap(); + let src = std::path::Path::new(&dir).join("src"); + std::fs::create_dir_all(&src).unwrap(); + let mut add = |name: &str| { + let p = src.join(name); + std::fs::write(&p, b"aa").unwrap(); + let path = p.to_string_lossy().to_string(); + let f = effectcraft_project::Footage { + path: path.clone(), + kind: effectcraft_project::FootageKind::Still, + width: 1, + height: 1, + has_video: true, + ..Default::default() + }; + let id = s.edit("add", None, |p, _| Ok(p.add_item(name, effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)))).unwrap(); + (id, path) + }; + let (a, a_path) = add("a.png"); + let (_, b_path) = add("b.png"); + let dc = s.disk_cache.clone().unwrap(); + let read = |p: &str| -> ReadFiles { [ReadFile::new(p, FileStamp::native(p).unwrap())].into_iter().collect() }; + dc.put_frame_now(1, 1, 1, &[1; 4], &read(&a_path)); + dc.put_frame_now(2, 1, 1, &[2; 4], &read(&b_path)); + dc.put_layer_now(3, &effectcraft_effects::Buf { img: effectcraft_raster::Image::new(1, 1), offset: [0.0; 2], scale: 1.0 }, &read(&a_path)); + // Other bytes, same size, the old time back. + let t = std::fs::metadata(&a_path).unwrap().modified().unwrap(); + std::fs::write(&a_path, b"AA").unwrap(); + std::fs::File::options().append(true).open(&a_path).unwrap().set_modified(t).unwrap(); + assert!(dc.contains(crate::render::disk_cache::Kind::Frame, 1)); + s.execute_checked("file.reloadFootage", json!({"item": a.0})).unwrap(); + dc.flush(); + assert!(dc.get_frame(1, None).is_none(), "the reloaded file's frame renders again"); + assert!(dc.get_layer(3, None).is_none(), "and its layer buffer"); + assert!(dc.get_frame(2, None).is_some(), "another file's frame stays"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 61f2d8240..d92505c98 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -2,16 +2,18 @@ //! and layer cache entries kept on disk between sessions, like After Effects' disk cache. //! //! * Entries are files keyed by a 128-bit content hash (`/v1//<2 hex>/<32 hex>.ecc`): -//! frames by the hash of the composition's content as it is in memory (the comp and everything -//! it uses, footage items with their settings and paths; no file is looked at) plus frame, -//! scale and view; layer buffers by the layer cache's content key (which names the footage -//! items a buffer uses with their settings and paths) and the renderer version -//! ([`layer_disk_key`]). A changed project therefore never reads stale pixels: its keys simply -//! change. +//! frames by the hash of the composition's content as it is in memory (the comp and what it can +//! draw, footage items with their settings and paths, and what its expressions can read; no +//! file is looked at, [`comp_content_key`]) plus frame, scale and view; layer buffers by the +//! layer cache's content key (which names the footage items a buffer uses with their settings +//! and paths) and the renderer version ([`layer_disk_key`]). A changed project therefore never +//! reads stale pixels: its keys simply change, and an edit elsewhere keeps them. //! * Frame and layer entries keep the source files they were made of, each with the size and //! modification time it was read with ([`EntryFiles`], #3184). An entry is used only while //! those files are unchanged: a handful of `metadata` calls when it is read, never a scan of -//! the project's files. A frame or buffer whose files can't all be named is not stored. +//! the project's files. A frame or buffer whose files can't all be named is not stored. File ▸ +//! Reload Footage deletes the entries made of the reloaded files ([`DiskCache::drop_files`]): +//! a file replaced by one of the same size and time is read again. //! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA (or, for //! 32 bpc viewer frames, half-float RGBA with the bytes shuffled into planes; the entry //! header's format byte tells them apart: 2 and 3, both with their source files first), layer @@ -261,6 +263,8 @@ impl LayerPrefetch { enum Job { /// Kind, key, header format byte, payload. Write(Kind, u128, u8, Vec), + /// Delete the frame and layer entries made of these files ([`DiskCache::drop_files`]). + Drop(Vec>), } struct Queue { @@ -279,8 +283,9 @@ impl Queue { #[cfg(not(target_arch = "wasm32"))] fn pop(&mut self) -> Option { if let Some(j) = self.frames.pop_front() { - let Job::Write(_, _, _, p) = &j; - self.frame_bytes = self.frame_bytes.saturating_sub(p.len()); + if let Job::Write(_, _, _, p) = &j { + self.frame_bytes = self.frame_bytes.saturating_sub(p.len()); + } return Some(j); } self.jobs.pop_front() @@ -310,6 +315,9 @@ pub struct DiskCache { queue: Arc<(Mutex, Condvar)>, /// Layer buffers that took less than this to render are not written (ms). min_layer_ms: AtomicU64, + /// Files whose entries are being deleted ([`DiskCache::drop_files`]), each with the number + /// of drops of it pending: until then an entry made of one is a miss. + dropping: Mutex, u32>>, } /// FNV-1a 128-bit (content keys). @@ -395,6 +403,7 @@ impl DiskCache { Condvar::new(), )), min_layer_ms: AtomicU64::new(30), + dropping: Mutex::new(HashMap::new()), }); dc.rescan(); // Shrinking a large cache deletes many files: the writer thread does it. @@ -631,7 +640,7 @@ impl DiskCache { return miss(); }; self.file_checks.fetch_add(files.len() as u64, Ordering::Relaxed); - if !files.unchanged(virtual_id) { + if self.made_of_dropped(&files) || !files.unchanged(virtual_id) { self.discard(kind, key); return miss(); } @@ -752,6 +761,91 @@ impl DiskCache { } } + /// Delete the frame and layer entries made of any of `paths` (File ▸ Reload Footage: a file + /// replaced by one with the same size and modification time must be read again, which the + /// check on hit can't tell). The index knows keys, not files, so the writer thread reads the + /// files section at the start of each frame and layer entry (no pixels) and deletes the + /// entries that list one of `paths`, after the writes queued before (those are swept too); + /// until it is done, an entry made of one of them is a miss. Entries are deleted for good, + /// so they don't come back after a restart. Nothing else in the cache is touched. + pub fn drop_files(&self, paths: impl IntoIterator>>) { + let paths: Vec> = paths.into_iter().map(Into::into).collect(); + if paths.is_empty() { + return; + } + { + let mut d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for p in &paths { + let n = d.entry(p.clone()).or_default(); + *n = n.saturating_add(1); + } + } + #[cfg(not(target_arch = "wasm32"))] + { + let (m, cv) = &*self.queue; + if let Ok(mut q) = m.lock() { + // (never refused for a full queue) + q.jobs.push_back(Job::Drop(paths)); + cv.notify_all(); + return; + } + } + self.sweep(&paths); + } + + /// Whether a [`DiskCache::drop_files`] is pending. + pub fn is_dropping(&self) -> bool { + !self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty() + } + + /// An entry made of a file being dropped. + fn made_of_dropped(&self, files: &EntryFiles) -> bool { + let d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + !d.is_empty() && files.files().iter().any(|f| d.contains_key(&f.path)) + } + + /// The writer's part of [`DiskCache::drop_files`]: delete the entries made of `paths`, then + /// end their drop. + fn sweep(&self, paths: &[Arc]) { + let set: std::collections::HashSet<&str> = paths.iter().map(|p| &**p).collect(); + for kind in [Kind::Frame, Kind::Layer] { + for key in self.keys(kind) { + if self.entry_files(kind, key).is_some_and(|f| f.files().iter().any(|f| set.contains(&*f.path))) { + self.discard(kind, key); + } + } + } + let mut d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for p in paths { + if let Some(n) = d.get_mut(p) { + *n = n.saturating_sub(1); + if *n == 0 { + d.remove(p); + } + } + } + } + + /// The source files a frame or layer entry lists, read from the start of its file (the + /// whole file only when the list is longer than that). `None` when it has none to read (an + /// earlier format, gone, damaged): such an entry is never used anyway. + fn entry_files(&self, kind: Kind, key: u128) -> Option { + use std::io::Read; + const HEAD: u64 = 64 << 10; + let parse = |d: &[u8]| { + let format = *d.get(5)?; + let ours = d.get(..4)? == MAGIC && *d.get(4)? == kind.tag(); + if !ours || !matches!(format, FORMAT_RGBA8_FILES | FORMAT_F16_FILES | FORMAT_LAYER_FILES) { + return None; + } + EntryFiles::decode(d.get(8..)?).map(|(files, _)| files) + }; + let path = self.path(kind, key); + let mut head = Vec::new(); + std::fs::File::open(&path).ok()?.take(HEAD).read_to_end(&mut head).ok()?; + parse(&head).or_else(|| if head.len() as u64 == HEAD { parse(&std::fs::read(&path).ok()?) } else { None }) + } + // ------------------------------------------------------------ typed entries /// An 8-bit frame whose source files are unchanged (see [`DiskCache::get_checked`]), with @@ -840,7 +934,8 @@ impl DiskCache { /// has no links. `false` when `from` isn't cached, `to` already is, or the file system /// refused. (Entries don't contain their key, so the same file serves both.) pub fn link_frame(&self, from: u128, to: u128) -> bool { - if !self.contains(Kind::Frame, from) || self.contains(Kind::Frame, to) { + // (while files are being dropped, `from` may be made of one: it renders again instead) + if !self.contains(Kind::Frame, from) || self.contains(Kind::Frame, to) || self.is_dropping() { return false; } let (src, dst) = (self.path(Kind::Frame, from), self.path(Kind::Frame, to)); @@ -913,12 +1008,20 @@ fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { } }; let Some(cache) = dc.upgrade() else { return }; - let Job::Write(kind, key, format, payload) = job; - cache.write_format(kind, key, format, &payload); + let written = match job { + Job::Write(kind, key, format, payload) => { + cache.write_format(kind, key, format, &payload); + (kind == Kind::Frame).then_some(key) + } + Job::Drop(paths) => { + cache.sweep(&paths); + None + } + }; drop(cache); if let Ok(mut g) = m.lock() { g.busy = false; - if kind == Kind::Frame { + if let Some(key) = written { g.pending_frames.remove(&key); } } @@ -926,12 +1029,9 @@ fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { } } -/// An entry file's bytes: header (magic, kind, format 0), payload, checksum. -pub fn seal(kind: Kind, payload: &[u8]) -> Vec { - seal_format(kind, FORMAT_RGBA8, payload) -} - -/// [`seal`] with the header's format byte (frames: 0 = 8-bit, 1 = half float). +/// An entry file's bytes: header (magic, kind, the format byte: [`FORMAT_RGBA8`] for +/// segmentations, [`FORMAT_RGBA8_FILES`] / [`FORMAT_F16_FILES`] for frames, +/// [`FORMAT_LAYER_FILES`] for layer buffers), payload, checksum. fn seal_format(kind: Kind, format: u8, payload: &[u8]) -> Vec { let mut data = Vec::with_capacity(payload.len() + 16); data.extend_from_slice(MAGIC); @@ -1331,7 +1431,7 @@ mod tests { bad[20] ^= 1; assert!(read_frame_entry(&bad, Some(&one)).is_none()); // An entry of the format before #3184 (pixels without files) is never read. - assert!(read_frame_entry(&seal(Kind::Frame, &encode_frame(6, 3, &rgba)), Some(&one)).is_none()); + assert!(read_frame_entry(&seal_format(Kind::Frame, FORMAT_RGBA8, &encode_frame(6, 3, &rgba)), Some(&one)).is_none()); let key = 0x0123_4567_89ab_cdef_0011_2233_4455_6677u128; assert_eq!(parse_entry_name(&entry_name(key)), Some(key)); assert_eq!(parse_entry_name("abc.ecc"), None); @@ -1698,7 +1798,7 @@ mod tests { let e = layer_entry(&buf(2, 3, 2), &EntryFiles::of(&files, Some(&one)).unwrap()); let (b, list) = read_layer_entry(&e).unwrap(); assert!(b.img == buf(2, 3, 2).img && list.unchanged(Some(&one)) && !list.unchanged(Some(&two))); - assert!(read_layer_entry(&seal(Kind::Layer, &encode_layer(&buf(2, 3, 2)))).is_none(), "the format before #3184"); + assert!(read_layer_entry(&seal_format(Kind::Layer, FORMAT_RGBA8, &encode_layer(&buf(2, 3, 2)))).is_none(), "the format before #3184"); let mut bad = e.clone(); bad[12] ^= 1; assert!(read_layer_entry(&bad).is_none(), "damaged"); @@ -1860,4 +1960,72 @@ mod tests { assert!(!dc.contains(Kind::Frame, 8)); let _ = std::fs::remove_dir_all(&dir); } + + /// Reload Footage drops the entries made of the reloaded files (#3184): a file replaced by + /// one with the same size and modification time passes the check on hit, so only the drop + /// makes the next use a miss. Entries of other files stay; an entry written after the drop + /// is used; a layer entry and one written while the drop waits in the queue are dropped too; + /// the drop survives a restart (the files are gone). + #[test] + fn dropped_files_take_their_entries_with_them() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap())).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &read(&[&a])); + dc.put_frame_now(2, 1, 1, &[2; 4], &read(&[&b])); + dc.put_frame_now(3, 1, 1, &[3; 4], &read(&[&a, &b])); + dc.put_layer_now(4, &buf(4, 2, 2), &read(&[&a])); + // a.png gets other bytes of the same size and its old time back: the check can't tell. + let t = std::fs::metadata(&a).unwrap().modified().unwrap(); + std::fs::write(&a, b"AA").unwrap(); + std::fs::File::options().append(true).open(&a).unwrap().set_modified(t).unwrap(); + assert!(dc.get_frame(1, None).is_some(), "same size and time: still a hit"); + // A frame queued (not written yet) when the drop comes is dropped too. + assert!(dc.put_frame(5, 1, 1, &[5; 4], &read(&[&a]), None)); + dc.drop_files([a.clone()]); + dc.flush(); + assert!(!dc.is_dropping()); + for (kind, key) in [(Kind::Frame, 1), (Kind::Frame, 3), (Kind::Layer, 4), (Kind::Frame, 5)] { + assert!(!dc.contains(kind, key), "{kind:?} {key} made of a.png is gone"); + } + assert!(dc.get_frame(1, None).is_none() && dc.get_layer(4, None).is_none()); + assert_eq!(dc.get_frame(2, None).map(|f| f.0.rgba), Some(vec![2; 4]), "b.png's frame stays"); + // Written again from the reloaded file: used. + dc.put_frame_now(1, 1, 1, &[9; 4], &read(&[&a])); + assert_eq!(dc.get_frame(1, None).map(|f| f.0.rgba), Some(vec![9; 4])); + // The drop is for good: a new session on the folder finds what is left. + drop(dc); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + assert_eq!(dc.keys(Kind::Frame).into_iter().collect::>(), [1, 2].into()); + assert!(dc.keys(Kind::Layer).is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// While a drop waits, an entry made of a dropped file is a miss (and deleted), and frames + /// aren't linked to new keys. + #[test] + fn entries_of_a_pending_drop_are_misses() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop-pending"); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.png"); + std::fs::write(&a, b"aa").unwrap(); + let a = a.to_string_lossy().to_string(); + let files: ReadFiles = [ReadFile::new(a.as_str(), FileStamp::native(&a).unwrap())].into_iter().collect(); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &files); + dc.dropping.lock().unwrap().insert(a.as_str().into(), 1); + assert!(!dc.link_frame(1, 2)); + assert!(dc.get_frame(1, None).is_none() && !dc.contains(Kind::Frame, 1)); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/docs/architecture.md b/docs/architecture.md index 213aaaf57..90573a1c9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -240,21 +240,39 @@ converted on demand with the HDR step and without the exposure; the Info panel s frame's float values. The browser keeps 8-bit frames for now (its frame workers send RGBA8). A persistent **disk cache** (`render::disk_cache`, Settings ▸ Media & Disk Cache) backs both -the layer cache and the viewer's RAM preview: layer buffers that were slow to render and every -preview frame are written (LZ4, atomic rename, checksummed) under 128-bit content keys — the -comp's content hash (the comp and what it uses, footage items with their settings and paths, -from memory alone) plus frame, scale and view for frames; the layer cache's content key (which -names the footage items a buffer uses with their paths) and the renderer version for layers. -Every frame and layer entry keeps the source files it was made of, with the size and -modification time they were read with, and is used only while they are unchanged: a handful of -`metadata` calls when an entry is read, never a scan of the project's files (#3184). Entries -survive restarts and never go stale; frames and buffers whose files can't all be named are not -written. Frame entries are 8-bit RGBA, or for 32 bpc viewer frames -half floats with their bytes shuffled into planes before LZ4 (the entry header's format byte -tells them apart; the render options in the key keep the two kinds apart). LRU eviction keeps it under the size limit; Edit ▸ Purge -empties it, `cache.diskStats` reports it, and the timeline draws disk-only frames in blue. In the -browser the frames live in the Origin Private File System: frame workers write them, the page -keeps the index (`DiskIndex`) and reads hits ([web.md](web.md#disk-cache)). +the layer cache and the viewer's RAM preview: layer buffers that were slow to render, every +preview frame and Roto Brush / Object Matte segmentations are written (LZ4, atomic rename, +checksummed) and survive restarts. The design (#3184): + +- **Keys from memory.** A frame's key is its comp's content key plus frame, scale, view and + render options; the content key hashes the project settings and the items the comp can draw + (its layers but those that can't change the picture, nested comps, footage with its settings + and paths, solids, Media Replacement footage, proxies: `Project::pixel_reach`). Expressions + among them add what they can read: every layer of their comps, the markers, the comps and + footage they name with literal names (`comp("Name")`, `footage("Name")`, and which items have + those names), or the whole project when they compute a name or reach items another way + (`expression_reach`). An edit to anything else keeps the key. A layer buffer's key is the + layer cache's content key (which names the footage it uses with its paths) and the renderer + version. Nothing here looks at a file, and nothing ever scans the project's files. +- **File lists checked on hit.** Every frame and layer entry keeps the source files it was + made of, with the size and modification time they were read with (the browser: size and + content hash). An entry is used only while they are unchanged: one `metadata` call per listed + file when it is read. A changed, missing or unreadable file, a damaged entry or an older + format is a miss; the entry is deleted and the frame renders again and replaces it. +- **Incomplete lists stay in memory.** A frame or buffer whose files can't all be named (a + source that doesn't say what it read, more than 4096 files) is shown but never written. +- **Reload Footage drops entries.** File ▸ Reload Footage deletes the frame and layer entries + whose lists name the item's files (the writer thread reads each entry's list, not its + pixels), so a file replaced by one with the same size and time is read again. +- **Edits keep what they can't change.** RAM frames outside an edit's dirty spans are kept + (`Project::dirty_spans`), and their disk entries are linked to the comp's new key. + +Frame entries are 8-bit RGBA, or for 32 bpc viewer frames half floats with their bytes shuffled +into planes before LZ4 (the entry header's format byte tells them apart; the render options in +the key keep the two kinds apart). LRU eviction keeps the cache under the size limit; Edit ▸ +Purge empties it, `cache.diskStats` reports it, and the timeline draws disk-only frames in blue. +In the browser the frames live in the Origin Private File System: frame workers write them, the +page keeps the index (`DiskIndex`) and reads hits ([web.md](web.md#disk-cache)). **Deferred readbacks** (`effectcraft-gpu` `deferred`): where a readback can't be waited for (WebGPU in a browser worker) a frame renders in passes. `Accelerator::frame_begin` / `pass_begin` / diff --git a/docs/web.md b/docs/web.md index 4f43b753e..666ffe37b 100644 --- a/docs/web.md +++ b/docs/web.md @@ -334,9 +334,11 @@ Settings ▸ Disk ▸ Disk Cache works in the browser, backed by the **Origin Pr (`src/diskcache.rs`): viewer frames are kept under `effectcraft-cache/v1/frames/<32 hex>.ecc` between visits, in the desktop cache's format (`disk_cache::frame_entry`: the source files the frame read with their size and content hash, then 8-bit premultiplied RGBA, LZ4, a checksum), -keyed by the same content hash (the comp and everything it uses as held in memory, frame, scale, -view, render options). The page reads an entry only while the files it lists are unchanged; a -frame whose files can't all be named is not stored. +keyed by the same content hash (from memory: the comp, everything it can draw and what its +expressions can read, frame, scale, view, render options; see +[architecture.md](architecture.md)). The page reads an entry only while the files it lists are +unchanged; a frame whose files can't all be named is not stored. Reload Footage has nothing to +drop here: the file table's identities are content hashes, so a replaced file never matches. - A render request to a frame worker carries the frame's disk key; the worker posts the frame, then writes the entry with a **synchronous access handle** into a temporary file moved into From d2372b7e2da297c8708466d8b5c42df06965ddea Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 01:58:15 +0100 Subject: [PATCH 023/324] Disk cache: file stamps keep the whole modification time A file's modification time was nanoseconds since 1970 as u64: a time before 1970 read as "no time" (two such files of one size looked alike) and times after 2554 were truncated. It is now i128 nanoseconds, negative before the epoch; None only means the file system has no time. The content-key hash writes a presence tag and the full value. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/disk_cache.rs | 8 ++++-- crates/render/src/reads.rs | 50 ++++++++++++++++++++++++++++++--- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 03832643b..335fe293a 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -1064,8 +1064,12 @@ fn file_stamp(h: &mut Hash128, path: &str, virtual_id: Option> } if let Some(crate::reads::FileStamp::Native { len, modified }) = crate::reads::FileStamp::native(path) { h.write_u64(len); - if let Some(t) = modified { - h.write_u64(t); + match modified { + Some(t) => { + h.write(&[1]); + h.write(&t.to_le_bytes()); + } + None => h.write(&[0]), } return; } diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index d5648cca6..b05429893 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -17,8 +17,8 @@ use std::sync::{Arc, Mutex, PoisonError}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum FileStamp { /// A file on disk: its size in bytes and its modification time (nanoseconds since the Unix - /// epoch; `None` where the file system has none). - Native { len: u64, modified: Option }, + /// epoch, negative before it; `None` only where the file system has none). + Native { len: u64, modified: Option }, /// Bytes given from memory instead of the file system (the browser's file table): their /// identity is the size and content hash a /// [`VirtualFileId`](crate::disk_cache::VirtualFileId) gives for the path. @@ -31,8 +31,7 @@ pub enum FileStamp { impl FileStamp { /// The identity of a file from metadata the caller already has (of an open file). pub fn of_metadata(md: &std::fs::Metadata) -> FileStamp { - let modified = md.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos() as u64); - FileStamp::Native { len: md.len(), modified } + FileStamp::Native { len: md.len(), modified: md.modified().ok().map(epoch_nanos) } } /// The identity of the file at `path` now: one `metadata` call. `None` when the file system @@ -42,6 +41,16 @@ impl FileStamp { } } +/// `t` in nanoseconds since the Unix epoch, negative before it: every time a file system can +/// store fits (`i128` nanoseconds span far more than any `SystemTime`), saturating otherwise. +pub fn epoch_nanos(t: std::time::SystemTime) -> i128 { + let nanos = |d: std::time::Duration| i128::try_from(d.as_nanos()).unwrap_or(i128::MAX); + match t.duration_since(std::time::UNIX_EPOCH) { + Ok(after) => nanos(after), + Err(before) => nanos(before.duration()).saturating_neg(), + } +} + /// One file a render read. #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ReadFile { @@ -209,6 +218,39 @@ mod tests { assert!(!files.is_complete()); } + /// Modification times keep their full value: before 1970 (not "no time") and past 2554 + /// (where `u64` nanoseconds end), so two such files never look alike. + #[test] + fn modification_times_are_kept_whole() { + use std::time::{Duration, UNIX_EPOCH}; + let day = Duration::from_secs(86_400); + assert_eq!(epoch_nanos(UNIX_EPOCH), 0); + assert_eq!(epoch_nanos(UNIX_EPOCH - day), -86_400_000_000_000); + let far = 600 * 365 * day; + if let Some(t) = UNIX_EPOCH.checked_add(far) { + assert_eq!(epoch_nanos(t), i128::try_from(far.as_nanos()).unwrap()); + } + let dir = std::env::temp_dir().join(format!("effectcraft-stamp-1969-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (a, b) = (dir.join("a.bin"), dir.join("b.bin")); + let mut stamps = vec![]; + for (p, back) in [(&a, day), (&b, 2 * day)] { + std::fs::write(p, b"abc").unwrap(); + let f = std::fs::File::options().write(true).open(p).unwrap(); + if f.set_modified(UNIX_EPOCH - back).is_err() { + // (a file system that can't store times before 1970) + let _ = std::fs::remove_dir_all(&dir); + return; + } + drop(f); + stamps.push(FileStamp::native(&p.to_string_lossy()).unwrap()); + } + assert!(matches!(stamps[0], FileStamp::Native { modified: Some(t), .. } if t < 0), "{:?}", stamps[0]); + assert_ne!(stamps[0], stamps[1], "two files from before 1970 with the same size"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn the_list_is_bounded() { let files: ReadFiles = (0..MAX_READ_FILES + 3).map(|i| file(&format!("/f{i:06}"), 1)).collect(); From 551ae89c6a08f53c1a88082905b79b1e385e1ae5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 01:58:15 +0100 Subject: [PATCH 024/324] Automation: a refused footage read leaves the render's file list incomplete Footage outside the read roots shows nothing and was noted as no file at all, so a picture made without it had a complete, empty list and could be kept on disk for a later session with other roots. A refused read during `recording` now marks the list incomplete. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/confine.rs | 91 ++++++++++++++++++++++++++++---- 1 file changed, 81 insertions(+), 10 deletions(-) diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index c24f62acb..ebc68900e 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -346,32 +346,51 @@ impl ConfinedFootage { fn inside(&self, f: &Footage) -> bool { std::iter::once(&f.path).chain(&f.sequence).filter(|p| !p.is_empty()).all(|p| self.confinement.check(p, Access::Read).is_ok()) } + + /// [`Self::inside`] for a read: a refused one is counted on this thread, so the render + /// [`recording`](FootageSource::recording) it can't list what it made without the footage. + fn readable(&self, f: &Footage) -> bool { + let inside = self.inside(f); + if !inside { + let _ = REFUSED_READS.try_with(|n| n.set(n.get().wrapping_add(1))); + } + inside + } +} + +thread_local! { + /// Footage reads refused on this thread (see [`ConfinedFootage::readable`]). + static REFUSED_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn refused_reads() -> u64 { + REFUSED_READS.try_with(std::cell::Cell::get).unwrap_or(0) } impl FootageSource for ConfinedFootage { fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { - self.inside(footage).then(|| self.inner.frame(item, footage, t)).flatten() + self.readable(footage).then(|| self.inner.frame(item, footage, t)).flatten() } fn frame_at_size(&self, item: ItemId, footage: &Footage, t: Tick, width: u32, height: u32) -> Option> { - self.inside(footage).then(|| self.inner.frame_at_size(item, footage, t, width, height)).flatten() + self.readable(footage).then(|| self.inner.frame_at_size(item, footage, t, width, height)).flatten() } fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { - self.inside(footage).then(|| self.inner.frame_with(item, footage, t, size, float)).flatten() + self.readable(footage).then(|| self.inner.frame_with(item, footage, t, size, float)).flatten() } fn audio(&self, item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option> { - self.inside(footage).then(|| self.inner.audio(item, footage, t, frames, rate)).flatten() + self.readable(footage).then(|| self.inner.audio(item, footage, t, frames, rate)).flatten() } fn aux(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { - self.inside(footage).then(|| self.inner.aux(item, footage, t)).flatten() + self.readable(footage).then(|| self.inner.aux(item, footage, t)).flatten() } fn set_aux_footage(&self, paths: &[String]) { self.inner.set_aux_footage(paths) } fn model(&self, item: ItemId, footage: &Footage) -> Option> { - self.inside(footage).then(|| self.inner.model(item, footage)).flatten() + self.readable(footage).then(|| self.inner.model(item, footage)).flatten() } fn vector_frame(&self, item: ItemId, footage: &Footage, scale: f64) -> Option> { - self.inside(footage).then(|| self.inner.vector_frame(item, footage, scale)).flatten() + self.readable(footage).then(|| self.inner.vector_frame(item, footage, scale)).flatten() } /// Says why footage outside the roots shows nothing, so the agent can act on it. fn problem(&self, footage: &Footage) -> Option { @@ -401,10 +420,16 @@ impl FootageSource for ConfinedFootage { fn called_off(&self) -> bool { self.inner.called_off() } - /// The files read inside the roots, as the inner source notes them (footage outside reads - /// nothing). + /// The files read inside the roots, as the inner source notes them. Footage outside reads + /// nothing, and what is made without it can't be listed by its files: a refused read makes + /// the list incomplete, so it never outlives the session in a disk cache (another session + /// with other roots would read the footage). fn recording(&self, reads: &effectcraft_engine::render::reads::ReadLog, f: &mut dyn FnMut()) { - self.inner.recording(reads, f) + let refused = refused_reads(); + self.inner.recording(reads, f); + if refused_reads() != refused { + reads.mark_incomplete(); + } } } @@ -598,6 +623,52 @@ mod tests { } } + /// Footage outside the roots shows nothing: a render that asked for it can't be listed by its + /// files (#3184), or a disk cache would keep the empty picture for a session with other + /// roots. Reads inside the roots record as the inner source tells. + #[test] + fn a_refused_footage_read_makes_the_render_unlisted() { + use effectcraft_engine::render::reads::{FileStamp, ReadFile, ReadLog}; + /// Reads every file, noting it. + struct Noting; + impl FootageSource for Noting { + fn frame(&self, _: ItemId, f: &Footage, _: Tick) -> Option> { + NOTED.with(|n| n.borrow_mut().push(f.path.clone())); + Some(Arc::new(Image::new(1, 1))) + } + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + f(); + for p in NOTED.with(|n| std::mem::take(&mut *n.borrow_mut())) { + reads.note(ReadFile::new(p, FileStamp::Missing)); + } + } + } + thread_local! { + static NOTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let base = std::env::temp_dir().join(format!("ec-confine-3184-{}", std::process::id())); + let (inside, outside) = (base.join("in"), base.join("elsewhere")); + for d in [&inside, &outside] { + std::fs::create_dir_all(d).unwrap(); + } + let c = Confinement::new(std::slice::from_ref(&inside), &[]).unwrap(); + let src = ConfinedFootage::new(Arc::new(Noting), c); + let footage = |d: &std::path::Path| Footage { path: d.join("a.png").to_string_lossy().into_owned(), ..Default::default() }; + let read = |f: &Footage| { + let log = ReadLog::new(); + let mut got = None; + src.recording(&log, &mut || got = src.frame(ItemId(1), f, Tick::ZERO)); + (got.is_some(), log.into_files()) + }; + let (shown, files) = read(&footage(&inside)); + assert!(shown && files.is_complete() && files.len() == 1, "inside the roots: {files:?}"); + let (shown, files) = read(&footage(&outside)); + assert!(!shown && !files.is_complete(), "outside the roots: {files:?}"); + // The next render on the thread is not affected. + assert!(read(&footage(&inside)).1.is_complete()); + let _ = std::fs::remove_dir_all(&base); + } + #[test] fn relative_and_outside_paths_of_newly_listed_commands_are_refused() { let base = std::env::temp_dir().join(format!("ec-confine-1243-{}", std::process::id())); From 8d948c231c416580fd1e9219298c3e591cb90ce6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 01:58:15 +0100 Subject: [PATCH 025/324] Render: a buffer kept by another worker comes with its own files LayerCache::insert returns the files of the buffer it keeps, and Renderer::keep notes them in the render's log and returns them, so a render that uses another worker's buffer lists that buffer's files (a file changed between the two reads then has two identities and the list is incomplete). Co-Authored-By: Claude Opus 5.5 --- crates/render/src/accel.rs | 2 +- crates/render/src/cache.rs | 63 ++++++++++++++++++++++++++--------- crates/render/src/layers.rs | 25 +++++++++++--- crates/render/src/pipeline.rs | 29 ++++++++++------ 4 files changed, 89 insertions(+), 30 deletions(-) diff --git a/crates/render/src/accel.rs b/crates/render/src/accel.rs index eecf05580..9e5d2138a 100644 --- a/crates/render/src/accel.rs +++ b/crates/render/src/accel.rs @@ -358,7 +358,7 @@ impl<'a> Renderer<'a> { Some(foot) }); // The buffer the cache keeps (another worker's, if it kept one first). - Some(self.keep(key, Arc::new(foot?), &files)) + Some(self.keep(key, Arc::new(foot?), &files).0) } /// Draw one 2D layer into `canvas` on the CPU (any kind: adjustment, wireframe, styled…). diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 79b948b89..b1c6710c9 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -177,7 +177,7 @@ impl LayerCache { let mut files = ReadFiles::default(); files.mark_incomplete(); let files = Arc::new(files); - Some((self.insert_mem(key, buf, files.clone()), files)) + Some(self.insert_mem(key, buf, files)) } } } @@ -188,12 +188,12 @@ impl LayerCache { /// and packs it once instead of once per worker, which ran it out of memory). Renders don't /// wait for each other: on the frame workers' shared thread pool a wait can end up under /// the very work it waits for. `files`: the source files `buf` was made of (see - /// [`crate::reads`]). - pub fn insert(&self, key: u64, buf: Arc, files: Arc) -> Arc { + /// [`crate::reads`]); the files returned are the ones the returned buffer was made of. + pub fn insert(&self, key: u64, buf: Arc, files: Arc) -> (Arc, Arc) { if self.gated() { - return buf; + return (buf, files); } - if let Some(kept) = self.inner.lock().ok().and_then(|g| g.map.get(&key).map(|e| e.buf.clone())) { + if let Some(kept) = self.inner.lock().ok().and_then(|g| g.map.get(&key).map(|e| (e.buf.clone(), e.files.clone()))) { return kept; } let started = self.inner.lock().ok().and_then(|mut g| g.missed_at.remove(&key)); @@ -206,21 +206,21 @@ impl LayerCache { self.insert_mem(key, buf, files) } - /// See [`LayerCache::insert`]: the buffer kept under `key` (`buf`, unless one was kept first - /// or `buf` is too large to keep). - fn insert_mem(&self, key: u64, buf: Arc, files: Arc) -> Arc { + /// See [`LayerCache::insert`]: the buffer kept under `key` and its files (`buf` and `files`, + /// unless one was kept first or `buf` is too large to keep). + fn insert_mem(&self, key: u64, buf: Arc, files: Arc) -> (Arc, Arc) { let bytes = buf.img.data.len() * std::mem::size_of::(); - let Ok(mut g) = self.inner.lock() else { return buf }; + let Ok(mut g) = self.inner.lock() else { return (buf, files) }; if bytes > g.budget / 4 { - return buf; + return (buf, files); } g.clock += 1; let now = g.clock; if let Some(e) = g.map.get_mut(&key) { e.last_use = now; - return e.buf.clone(); + return (e.buf.clone(), e.files.clone()); } - g.map.insert(key, Entry { buf: buf.clone(), files, bytes, last_use: now }); + g.map.insert(key, Entry { buf: buf.clone(), files: files.clone(), bytes, last_use: now }); g.bytes += bytes; if g.bytes > g.budget { // Evict least-recently used entries down to 3/4 of the budget. @@ -236,7 +236,7 @@ impl LayerCache { } } } - buf + (buf, files) } /// The memory budget in bytes. @@ -796,8 +796,41 @@ mod shared_insert_tests { let cache = LayerCache::default(); let buf = || Arc::new(Buf { img: Image::new(4, 4), offset: [0.0; 2], scale: 1.0 }); let (a, b) = (buf(), buf()); - assert!(Arc::ptr_eq(&cache.insert(3, a.clone(), Default::default()), &a)); - assert!(Arc::ptr_eq(&cache.insert(3, b, Default::default()), &a), "the later render gets the first buffer"); + assert!(Arc::ptr_eq(&cache.insert(3, a.clone(), Default::default()).0, &a)); + assert!(Arc::ptr_eq(&cache.insert(3, b, Default::default()).0, &a), "the later render gets the first buffer"); assert!(Arc::ptr_eq(&cache.get(3).unwrap().0, &a)); } + + /// A render that gets another render's buffer gets that buffer's files too (#3184): when a + /// file changed between the two reads, its frame lists the file with both identities, so the + /// list is incomplete and the frame is not kept on disk with the new identity and the old + /// pixels. + #[test] + fn the_buffer_kept_first_brings_its_files() { + use crate::reads::{FileStamp, ReadFile, ReadFiles, ReadLog}; + use crate::{NoFootage, RenderOpts, Renderer}; + let cache = LayerCache::default(); + let buf = || Arc::new(Buf { img: Image::new(4, 4), offset: [0.0; 2], scale: 1.0 }); + let files = |len| Arc::new([ReadFile::new("/a.png", FileStamp::Native { len, modified: Some(1) })].into_iter().collect::()); + let (first, second) = (files(1), files(2)); + let a = buf(); + cache.insert(3, a.clone(), first.clone()); + let project = effectcraft_project::Project::default(); + let log = ReadLog::new(); + let mut r = Renderer::new(&project, &NoFootage, RenderOpts::default()); + r.cache = Some(&cache); + r.reads = Some(&log); + // (what `Renderer::recorded` noted for the second render) + log.note_all(&second); + let (kept, kept_files) = r.keep(Some(3), buf(), &second); + assert!(Arc::ptr_eq(&kept, &a)); + assert_eq!(kept_files, first); + assert!(!log.files().is_complete()); + // The same files: nothing changes. + let same = ReadLog::new(); + r.reads = Some(&same); + same.note_all(&first); + let _ = r.keep(Some(3), buf(), &files(1)); + assert!(same.files().is_complete()); + } } diff --git a/crates/render/src/layers.rs b/crates/render/src/layers.rs index b551d1c1b..9eb87a47e 100644 --- a/crates/render/src/layers.rs +++ b/crates/render/src/layers.rs @@ -59,10 +59,27 @@ impl<'a> Renderer<'a> { t.effects.push(("layerStyles".into(), t0.elapsed().as_secs_f64() * 1e3)); } // The buffers the cache keeps (another worker's, if it kept them first), made of the - // content's files. - let body = self.keep(key, Arc::new(st.body), &files); - let passes: Vec<_> = - st.passes.into_iter().enumerate().map(|(i, (b, m))| (self.keep(key.map(|k| cache::derive(k, i as u64 + 1)), Arc::new(b), &files), m)).collect(); + // content's files; the styled layer then lists the files of every buffer it holds. + let mut kept_files = vec![]; + let (body, f) = self.keep(key, Arc::new(st.body), &files); + kept_files.push(f); + let passes: Vec<_> = st + .passes + .into_iter() + .enumerate() + .map(|(i, (b, m))| { + let (b, f) = self.keep(key.map(|k| cache::derive(k, i as u64 + 1)), Arc::new(b), &files); + kept_files.push(f); + (b, m) + }) + .collect(); + let files = if kept_files.iter().all(|f| Arc::ptr_eq(f, &files)) { + files + } else { + let mut all = (*files).clone(); + kept_files.iter().for_each(|f| all.extend(f)); + Arc::new(all) + }; Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }) } diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 3564c17f9..e793b2ad4 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -151,12 +151,19 @@ impl<'a> Renderer<'a> { } /// Keep `buf`, made of `files`, under `key` (see [`Renderer::recorded`]): the buffer the cache - /// keeps (another worker's, if it kept one first), or `buf` when nothing is kept. - pub(crate) fn keep(&self, key: Option, buf: Arc, files: &Arc) -> Arc { - match (self.cache_to_keep(), key) { - (Some(c), Some(k)) => c.insert(k, buf, files.clone()), - _ => buf, + /// keeps (another worker's, if it kept one first), or `buf` when nothing is kept, with the + /// files that buffer was made of. Another worker's files are noted in [`Renderer::reads`] + /// too: its pixels are the ones this render uses (a file that changed between the two reads + /// then has two identities, and the list is incomplete). + pub(crate) fn keep(&self, key: Option, buf: Arc, files: &Arc) -> (Arc, Arc) { + let (Some(c), Some(k)) = (self.cache_to_keep(), key) else { return (buf, files.clone()) }; + let (kept, kept_files) = c.insert(k, buf, files.clone()); + if !Arc::ptr_eq(&kept_files, files) + && let Some(log) = self.reads + { + log.note_all(&kept_files); } + (kept, kept_files) } /// Run `make`, which makes a buffer to keep under `key` in the layer cache, on this renderer @@ -923,7 +930,7 @@ impl<'a> Renderer<'a> { }); if let (Some(a), Some(b)) = (a, b) { let img = blend_frames(mode, &a, &b, w as f32); - self.keep(key, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }), &files); + let _kept = self.keep(key, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }), &files); return Some(Arc::new(img)); } } @@ -967,7 +974,7 @@ impl<'a> Renderer<'a> { } let mut nb = (*b).clone(); color::convert(&mut nb.img, &c); - self.keep(key, Arc::new(nb), files) + self.keep(key, Arc::new(nb), files).0 } /// The flattened layer buffer, its cache key and the source files it was made of. @@ -981,7 +988,8 @@ impl<'a> Renderer<'a> { return Some((b, key, files)); } let flat = Arc::new(styles::Styled { passes: st.passes.iter().map(|(b, m)| ((**b).clone(), *m)).collect(), body: (*st.body).clone() }.flatten()); - Some((self.keep(key, flat, &st.files), key, st.files)) + let (flat, files) = self.keep(key, flat, &st.files); + Some((flat, key, files)) } /// A layer's source pixels at the context time, before masks, effects and the transform @@ -1039,7 +1047,8 @@ impl<'a> Renderer<'a> { let buf = r.masked_source(ctx, layer)?; Some(r.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects))) }); - Some((self.keep(key, Arc::new(buf?), &files), key, files)) + let (buf, files) = self.keep(key, Arc::new(buf?), &files); + Some((buf, key, files)) } /// A layer's input at the context time: source → masks → its first `effects` effects @@ -1061,6 +1070,6 @@ impl<'a> Renderer<'a> { } Some(buf) }); - Some(self.keep(key, Arc::new(buf?), &files)) + Some(self.keep(key, Arc::new(buf?), &files).0) } } From d04ccd52344a8b83366df6810b6fef612bfe5fca Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 01:58:15 +0100 Subject: [PATCH 026/324] Render: sampleImage and text fonts note the files they read EvalCtx carries the render's read log. A sampleImage render records its footage reads, keeps them with its per-thread cached buffer and notes them in the evaluating render's log on every use. Text notes the font files it is drawn with, with the identity their bytes were read with; a family that isn't installed, a fallback or missing glyph, or a font from memory leaves the list incomplete. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/analysis/tracking.rs | 2 +- crates/engine/src/cmd/effect.rs | 5 ++ crates/engine/src/cmd/layer/parent.rs | 1 + crates/engine/src/cmd/layer_time.rs | 1 + crates/engine/src/cmd/path_nulls.rs | 2 + crates/engine/src/cmd/prop.rs | 1 + crates/engine/src/cmd/puppet.rs | 13 ++++- crates/engine/src/cmd/rig3d.rs | 1 + crates/engine/src/cmd/three_d.rs | 26 +++++++-- crates/engine/src/tests/crypto_pick.rs | 1 + crates/engine/src/tests/rig3d.rs | 14 ++++- crates/expr/src/host.rs | 1 + crates/expr/src/lib.rs | 1 + crates/expr/src/sample.rs | 22 ++++++-- crates/expr/src/tests.rs | 39 +++++++++++++ crates/gpu/src/tests/adv3d.rs | 2 + crates/host/src/tests.rs | 2 + crates/render/src/eval.rs | 5 +- crates/render/src/pipeline.rs | 23 +++++++- crates/render/src/tests/collapse.rs | 13 ++++- crates/render/src/tests/time.rs | 1 + crates/render/src/text.rs | 39 +++++++++++++ crates/render/src/text/tests.rs | 55 +++++++++++++++++++ crates/render/src/three_d/adv/scene.rs | 4 +- crates/render/src/three_d/adv/tests.rs | 4 ++ crates/render/src/three_d/compose.rs | 2 +- crates/script/src/tests/ui_more.rs | 1 + crates/text/src/fonts.rs | 31 ++++++++++- crates/ui-egui/src/menus/invoke.rs | 1 + .../src/panels/effect_controls/panel.rs | 1 + crates/ui-egui/src/panels/layer_panel.rs | 1 + crates/ui-egui/src/panels/properties.rs | 1 + crates/ui-egui/src/panels/roto_tool.rs | 1 + crates/ui-egui/src/panels/text_panels.rs | 1 + crates/ui-egui/src/panels/timeline.rs | 1 + crates/ui-egui/src/panels/viewer.rs | 1 + crates/ui-egui/src/panels/viewer/shapes.rs | 1 + crates/ui-egui/src/panels/viewer/view.rs | 1 + 38 files changed, 298 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/analysis/tracking.rs b/crates/engine/src/analysis/tracking.rs index 221b28602..912a8adfe 100644 --- a/crates/engine/src/analysis/tracking.rs +++ b/crates/engine/src/analysis/tracking.rs @@ -208,7 +208,7 @@ pub(crate) fn source_frame( t: Tick, expr: Option<&dyn ExprHost>, ) -> Option<(Arc, [f64; 2])> { - let ctx = EvalCtx { project, comp_id: cid, comp, time: t, expr, footage: None, property_overrides: &[], media_overrides: &[] }; + let ctx = EvalCtx { project, comp_id: cid, comp, time: t, expr, footage: None, property_overrides: &[], media_overrides: &[], reads: None }; if let effectcraft_project::LayerSource::Footage { item } = &layer.source && let Some(effectcraft_project::ItemKind::Footage(f)) = project.item(*item).map(|i| &i.kind) && f.has_video diff --git a/crates/engine/src/cmd/effect.rs b/crates/engine/src/cmd/effect.rs index 69bdb5a4a..1d352d192 100644 --- a/crates/engine/src/cmd/effect.rs +++ b/crates/engine/src/cmd/effect.rs @@ -345,6 +345,7 @@ fn warning(s: &mut Session, p: &Value) -> Result { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; Ok(json!({"effect": uid, "warning": effectcraft_effects::warning(g, &mut |pr| ctx.value(layer, pr))})) } @@ -378,6 +379,7 @@ fn pick_color(s: &mut Session, p: &Value) -> Result { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let mut r = effectcraft_render::Renderer::new(&s.project, &*s.footage, effectcraft_render::RenderOpts::default()); r.expr = s.expr.as_deref(); @@ -515,6 +517,7 @@ impl CryptoProbe { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let params = effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr)); let aux = r.layer_aux(&ctx, layer).ok_or(NO_CRYPTO)?; @@ -586,6 +589,7 @@ fn probe_key<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(ProbeKey, Tick footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let frame = probe_frame(&ctx, layer, pos); let o = s.render_opts(Default::default()); @@ -780,6 +784,7 @@ fn crypto_hit(s: &Session, p: &Value, cmd: &str) -> Result { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let selection = effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr)).s("selection").to_string(); let driven = prop.expr.as_ref().is_some_and(|e| e.enabled); diff --git a/crates/engine/src/cmd/layer/parent.rs b/crates/engine/src/cmd/layer/parent.rs index 870d22f5f..271bad28c 100644 --- a/crates/engine/src/cmd/layer/parent.rs +++ b/crates/engine/src/cmd/layer/parent.rs @@ -371,6 +371,7 @@ pub(crate) fn parent_fixes(s: &Session, cid: ItemId, ids: &[LayerId], parent: Op footage: Some(s.footage.as_ref()), property_overrides: &[], media_overrides: &[], + reads: None, }; let space = |id: Option| -> effectcraft_geom::Mat3 { id.and_then(|i| comp.layer(i)).filter(|l| !l.is_3d()).map(|l| ectx.layer_to_comp(l).0).unwrap_or(effectcraft_geom::Mat3::IDENTITY) diff --git a/crates/engine/src/cmd/layer_time.rs b/crates/engine/src/cmd/layer_time.rs index 4ecf725ec..2f8661885 100644 --- a/crates/engine/src/cmd/layer_time.rs +++ b/crates/engine/src/cmd/layer_time.rs @@ -194,6 +194,7 @@ fn freeze(s: &mut Session, p: &Value, last: bool) -> Result { footage: Some(s.footage.as_ref()), property_overrides: &[], media_overrides: &[], + reads: None, }; let now: Vec<(effectcraft_project::LayerId, f64)> = comp .layers diff --git a/crates/engine/src/cmd/path_nulls.rs b/crates/engine/src/cmd/path_nulls.rs index 93d71cd67..a6b51c763 100644 --- a/crates/engine/src/cmd/path_nulls.rs +++ b/crates/engine/src/cmd/path_nulls.rs @@ -87,6 +87,7 @@ fn info(s: &Session, cid: ItemId, lid: LayerId, uid: Uid, cmd: &str) -> Result

Result Res footage: Some(s.footage.as_ref()), property_overrides: &[], media_overrides: &[], + reads: None, }; keys.push(Keyframe::new(layer.layer_time(t), ctx.value(&layer, &pr))); t += fd; diff --git a/crates/engine/src/cmd/puppet.rs b/crates/engine/src/cmd/puppet.rs index d894516c2..bd20bd885 100644 --- a/crates/engine/src/cmd/puppet.rs +++ b/crates/engine/src/cmd/puppet.rs @@ -39,8 +39,17 @@ pub fn puppet_eval(s: &Session, cid: ItemId, lid: LayerId, fx_uid: Uid, t: Tick) let fx = layer.effects()?; let index = fx.groups().position(|g| g.uid == fx_uid)?; let g = fx.groups().nth(index)?; - let ctx = - EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None, property_overrides: &[], media_overrides: &[] }; + let ctx = EvalCtx { + project: &s.project, + comp_id: cid, + comp, + time: t, + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; let mut r = Renderer::new(&s.project, &*s.footage, RenderOpts::default()); r.expr = s.expr.as_deref(); r.cache = Some(&s.layer_cache); diff --git a/crates/engine/src/cmd/rig3d.rs b/crates/engine/src/cmd/rig3d.rs index dbcaa3c3c..e7852fbd2 100644 --- a/crates/engine/src/cmd/rig3d.rs +++ b/crates/engine/src/cmd/rig3d.rs @@ -57,6 +57,7 @@ impl Env { footage: Some(self.footage.as_ref()), property_overrides: &[], media_overrides: &[], + reads: None, } } } diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index f7b1c3e08..de6bc4d7a 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -424,8 +424,17 @@ fn get_3d(s: &mut Session, p: &Value) -> Result { let (w, h) = (comp.width as f64, comp.height as f64); let vs = s.state.views3d.get(&cid).cloned().unwrap_or_default(); let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO); - let ctx = - EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None, property_overrides: &[], media_overrides: &[] }; + let ctx = EvalCtx { + project: &s.project, + comp_id: cid, + comp, + time: t, + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; let cam = vs.override_camera(w, h).unwrap_or_else(|| camera::active_camera(&ctx)); let f = cam.forward(); let lights: Vec = comp @@ -567,8 +576,17 @@ fn auto_orient(s: &mut Session, p: &Value) -> Result { /// through each layer's world matrix; cameras and lights contribute their position). fn layer_points(s: &Session, cid: ItemId, ids: &[LayerId], t: Tick) -> Vec { let Some(comp) = s.project.comp(cid) else { return vec![] }; - let ctx = - EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None, property_overrides: &[], media_overrides: &[] }; + let ctx = EvalCtx { + project: &s.project, + comp_id: cid, + comp, + time: t, + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; let mut out = vec![]; for l in comp.layers.iter().filter(|l| ids.contains(&l.id)) { let m = ctx.world_matrix(l); diff --git a/crates/engine/src/tests/crypto_pick.rs b/crates/engine/src/tests/crypto_pick.rs index e3a8cd50c..82fe21e71 100644 --- a/crates/engine/src/tests/crypto_pick.rs +++ b/crates/engine/src/tests/crypto_pick.rs @@ -214,6 +214,7 @@ fn rendered_matte_of_pick(s: &mut Session, x: f64, y: f64, scale: f64) -> (Strin footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let buf = s.renderer(effectcraft_render::RenderOpts { scale, ..Default::default() }).content_buf(&ctx, layer).unwrap(); let (px, py) = buf.to_px([x, y]); diff --git a/crates/engine/src/tests/rig3d.rs b/crates/engine/src/tests/rig3d.rs index cf2518447..98d67edbb 100644 --- a/crates/engine/src/tests/rig3d.rs +++ b/crates/engine/src/tests/rig3d.rs @@ -40,7 +40,17 @@ fn close3(a: [f64; 3], b: [f64; 3], tol: f64) -> bool { fn frame(s: &Session, id: u64) -> (Vec3, Vec3) { let c = cid(s); let comp = s.project.comp(c).unwrap(); - let ctx = EvalCtx { project: &s.project, comp_id: c, comp, time: Tick::ZERO, expr: None, footage: None, property_overrides: &[], media_overrides: &[] }; + let ctx = EvalCtx { + project: &s.project, + comp_id: c, + comp, + time: Tick::ZERO, + expr: None, + footage: None, + property_overrides: &[], + media_overrides: &[], + reads: None, + }; let (e, f, _) = layer_frame(&ctx, comp.layer(LayerId(id)).unwrap()); (e, f) } @@ -244,7 +254,7 @@ fn parented_camera_keeps_its_frame_under_an_offset_null() { fn frame_at(s: &Session, id: u64, t: Tick) -> (Vec3, Vec3, Vec3) { let c = cid(s); let comp = s.project.comp(c).unwrap(); - let ctx = EvalCtx { project: &s.project, comp_id: c, comp, time: t, expr: None, footage: None, property_overrides: &[], media_overrides: &[] }; + let ctx = EvalCtx { project: &s.project, comp_id: c, comp, time: t, expr: None, footage: None, property_overrides: &[], media_overrides: &[], reads: None }; layer_frame(&ctx, comp.layer(LayerId(id)).unwrap()) } diff --git a/crates/expr/src/host.rs b/crates/expr/src/host.rs index fa2993f97..b0abcaafa 100644 --- a/crates/expr/src/host.rs +++ b/crates/expr/src/host.rs @@ -309,6 +309,7 @@ impl<'a> Resolver<'a> { footage: self.ctx.footage, property_overrides: if same_comp { self.ctx.property_overrides } else { &[] }, media_overrides: if same_comp { self.ctx.media_overrides } else { &[] }, + reads: self.ctx.reads, }) } fn prop(&self, c: u64, l: u64, path: &str) -> Option<(&'a Layer, &'a Property)> { diff --git a/crates/expr/src/lib.rs b/crates/expr/src/lib.rs index 9e78d250f..ae9e647f8 100644 --- a/crates/expr/src/lib.rs +++ b/crates/expr/src/lib.rs @@ -172,6 +172,7 @@ fn evaluate_out( footage: ctx.footage, property_overrides: ctx.property_overrides, media_overrides: ctx.media_overrides, + reads: ctx.reads, }; let comp = ctx.comp_id.0; let path = layer.props.path_of(prop.uid).unwrap_or_else(|| format!("@{}", prop.uid)); diff --git a/crates/expr/src/sample.rs b/crates/expr/src/sample.rs index 28f830bb2..e097691de 100644 --- a/crates/expr/src/sample.rs +++ b/crates/expr/src/sample.rs @@ -4,13 +4,16 @@ //! expression (its footage source; [`EvalCtx::footage`]): source → masks → effects for //! `postEffect = true`, the bare source otherwise, in layer space (before the transform). Buffers //! are cached per thread for the frame, so many expressions sampling the same layer at the same -//! time render it once. +//! time render it once. The source files a sampled render reads are kept with its buffer and +//! noted in the evaluating render's log ([`EvalCtx::reads`]) on every use, so a frame whose +//! expressions sample footage lists that footage too (#3184). use std::cell::RefCell; use std::collections::HashMap; use std::sync::Arc; use effectcraft_project::{ItemId, Layer}; +use effectcraft_render::reads::{ReadFiles, ReadLog}; use effectcraft_render::{EvalCtx, NoFootage, RenderOpts, Renderer}; use effectcraft_time::Tick; @@ -26,7 +29,8 @@ struct Sampled { type Key = (usize, u64, u64, u64, bool, u64); thread_local! { - static CACHE: RefCell>> = RefCell::new(HashMap::new()); + /// The sampled buffers and the source files each was made of. + static CACHE: RefCell, Arc)>> = RefCell::new(HashMap::new()); /// Nested sampleImage renders (a sampled layer whose expressions sample again). static DEPTH: RefCell = const { RefCell::new(0) }; } @@ -48,7 +52,13 @@ fn render(ctx: EvalCtx, comp: ItemId, layer: &Layer, post: bool, t: f64) -> Opti return None; } let key: Key = (ctx.project as *const _ as usize, comp.0, layer.id.0, t.to_bits(), post, fingerprint(layer)); - if let Some(hit) = CACHE.with(|c| c.borrow().get(&key).cloned()) { + let note = |files: &ReadFiles| { + if let Some(log) = ctx.reads { + log.note_all(files); + } + }; + if let Some((hit, files)) = CACHE.with(|c| c.borrow().get(&key).cloned()) { + note(&files); return hit; } DEPTH.with(|d| *d.borrow_mut() += 1); @@ -60,20 +70,24 @@ fn render(ctx: EvalCtx, comp: ItemId, layer: &Layer, post: bool, t: f64) -> Opti } let _pop = Pop; let footage: &dyn effectcraft_render::FootageSource = ctx.footage.unwrap_or(&NoFootage); + let log = ReadLog::new(); let mut r = Renderer::new(ctx.project, footage, RenderOpts { motion_blur: false, ..Default::default() }); r.expr = ctx.expr; + r.reads = Some(&log); let ectx = r.eval_ctx(comp, Tick::from_seconds_f64(t))?; let out = if post { r.content_buf(&ectx, layer).map(|b| Sampled { img: Arc::new(b.img.clone()), offset: b.offset, scale: b.scale }) } else { r.layer_source(&ectx, layer).map(|b| Sampled { img: Arc::new(b.img), offset: b.offset, scale: b.scale }) }; + let files = Arc::new(log.into_files()); + note(&files); CACHE.with(|c| { let mut c = c.borrow_mut(); if c.len() >= MAX_CACHE { c.clear(); } - c.insert(key, out.clone()); + c.insert(key, (out.clone(), files)); }); out } diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index 48f656e52..5f16ac5ee 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1326,6 +1326,7 @@ fn source_dimensions_follow_media_replacement() { footage: None, property_overrides: &[], media_overrides: &[media], + reads: None, }; assert_eq!(ctx.value(l, l.props.prop(ROT).unwrap()), Value::Scalar(130.0)); } @@ -1548,6 +1549,7 @@ fn text_expression_selector_values() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let doc = effectcraft_render::text::source_text(&ctx, l).unwrap(); let lay = effectcraft_text::layout_doc(&doc); @@ -1600,6 +1602,43 @@ fn sample_image_reads_rendered_pixels() { assert_close!(f.num(&code("thisComp.layer(\"B\").sampleImage([-50, -50])"), 0.0), 0.0); } +/// The footage `sampleImage` renders is a file the evaluating render read (#3184): it is noted in +/// the render's log, also when the sampled buffer comes from the per-thread cache. +#[test] +fn sample_image_notes_the_files_it_reads() { + use effectcraft_render::reads::{FileStamp, ReadFile, ReadLog}; + /// A grey picture of any footage, noting `/clip.png` for every read. + struct Clip; + impl effectcraft_render::FootageSource for Clip { + fn frame(&self, _: ItemId, f: &effectcraft_project::Footage, _: Tick) -> Option> { + let mut img = effectcraft_render::Image::new(f.width, f.height); + img.data.fill([0.5, 0.5, 0.5, 1.0]); + Some(std::sync::Arc::new(img)) + } + fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { + f(); + reads.note(ReadFile::new("/clip.png", FileStamp::Native { len: 3, modified: Some(1) })); + } + } + let mut p = Project::default(); + let comp = Comp::new(20, 20, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let footage = + effectcraft_project::Footage { path: "/clip.png".into(), width: 8, height: 8, has_video: true, frame_rate: FrameRate::FPS_30, ..Default::default() }; + let item = p.add_item("Clip", Label::Aqua, None, ItemKind::Footage(footage)); + let layer = build::layer(&mut p, &comp, "Clip", LayerSource::Footage { item }, (8, 8), None); + let cid = p.add_item("C", Label::Sandstone, None, ItemKind::Comp(comp.into())); + let c = p.comp(cid).unwrap(); + for pass in ["rendered", "cached"] { + let log = ReadLog::new(); + let ctx = EvalCtx { footage: Some(&Clip), reads: Some(&log), ..EvalCtx::new(&p, cid, c, Tick::ZERO) }; + let px = crate::sample::sample_image(ctx, cid, &layer, [4.0, 4.0], [0.5, 0.5], false, 0.0).unwrap(); + assert!((px[0] - 0.5).abs() < 1e-3 && px[3] > 0.99, "{pass}: {px:?}"); + let files = log.into_files(); + assert_eq!(files.files().iter().map(|f| &*f.path).collect::>(), ["/clip.png"], "{pass}"); + assert!(files.is_complete(), "{pass}"); + } +} + /// A huge sample point saturates the pixel coordinates; it must not overflow the loop bounds. #[test] fn sample_image_huge_point_is_transparent() { diff --git a/crates/gpu/src/tests/adv3d.rs b/crates/gpu/src/tests/adv3d.rs index 00b1fee14..4914c4912 100644 --- a/crates/gpu/src/tests/adv3d.rs +++ b/crates/gpu/src/tests/adv3d.rs @@ -123,6 +123,7 @@ pub(crate) fn scene(p: &Project, cid: ItemId) -> Scene { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let run: Vec<&effectcraft_project::Layer> = ctx.comp.layers.iter().rev().filter(|l| l.is_3d() && l.has_video()).collect(); adv::scene_of(&r, &ctx, &run, (ctx.comp.width, ctx.comp.height)) @@ -315,6 +316,7 @@ pub(crate) fn run_of(p: &Project, cid: ItemId) -> (EvalCtx<'_>, Vec<&effectcraft footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let run: Vec<&effectcraft_project::Layer> = ctx.comp.layers.iter().rev().filter(|l| l.is_3d() && l.has_video()).collect(); (ctx, run) diff --git a/crates/host/src/tests.rs b/crates/host/src/tests.rs index f628ce4e4..339b48d3d 100644 --- a/crates/host/src/tests.rs +++ b/crates/host/src/tests.rs @@ -343,6 +343,7 @@ fn value(s: &effectcraft_engine::Session, l: u64, path: &str) -> effectcraft_eng footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; ctx.value(layer, layer.props.prop(path).unwrap()) } @@ -606,6 +607,7 @@ fn stereo_rig_expressions_follow_the_master_camera() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; ctx.value(layer, layer.props.prop(path).unwrap()).as_vec3() }; diff --git a/crates/render/src/eval.rs b/crates/render/src/eval.rs index f4d2cbb37..e900ffa6e 100644 --- a/crates/render/src/eval.rs +++ b/crates/render/src/eval.rs @@ -44,11 +44,14 @@ pub struct EvalCtx<'a> { /// Media Replacement values overridden by the Essential Properties of a collapsed precomp /// instance. pub media_overrides: &'a [crate::MediaOverride], + /// Where the source files of what expressions render (`sampleImage`) are noted: the + /// renderer's [`Renderer::reads`](crate::Renderer::reads) while rendering. + pub reads: Option<&'a crate::reads::ReadLog>, } impl<'a> EvalCtx<'a> { pub fn new(project: &'a Project, comp_id: ItemId, comp: &'a Comp, time: Tick) -> EvalCtx<'a> { - EvalCtx { project, comp_id, comp, time, expr: None, footage: None, property_overrides: &[], media_overrides: &[] } + EvalCtx { project, comp_id, comp, time, expr: None, footage: None, property_overrides: &[], media_overrides: &[], reads: None } } pub fn at(&self, time: Tick) -> EvalCtx<'a> { EvalCtx { time, ..*self } diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index e793b2ad4..136874be1 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -140,6 +140,13 @@ impl<'a> Renderer<'a> { out } + /// `ctx` noting what it reads (fonts, `sampleImage`) in this render's [`Renderer::reads`]: + /// a context made by an outer render carries that render's log, not the one of the buffer + /// [`Renderer::recorded`] makes. + pub(crate) fn with_reads<'c>(&'c self, ctx: &EvalCtx<'c>) -> EvalCtx<'c> { + EvalCtx { reads: self.reads, ..*ctx } + } + /// The buffer the layer cache keeps under `key`, with the files it was made of noted in /// [`Renderer::reads`]. pub(crate) fn cached(&self, key: Option) -> Option<(Arc, Arc)> { @@ -422,7 +429,17 @@ impl<'a> Renderer<'a> { } pub(crate) fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> { - EvalCtx { project: self.project, comp_id, comp, time: t, expr: self.expr, footage: Some(self.footage), property_overrides: &[], media_overrides: &[] } + EvalCtx { + project: self.project, + comp_id, + comp, + time: t, + expr: self.expr, + footage: Some(self.footage), + property_overrides: &[], + media_overrides: &[], + reads: self.reads, + } } /// This renderer with another accelerator (or none): the passes of @@ -831,7 +848,9 @@ impl<'a> Renderer<'a> { let img = self.footage_frame(ctx, layer, item, pf, lt, size)?; Some(self.footage_buf(&img, pf, f.width, f.height)) } - LayerSource::Text => Some(self.authored(text::render(ctx, layer, self.raster_scale(ctx, layer)))), + // (the font files go to this render's log, which `ctx` may not carry: see + // [`Renderer::with_reads`]) + LayerSource::Text => Some(self.authored(text::render(&self.with_reads(ctx), layer, self.raster_scale(ctx, layer)))), LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, self.raster_scale(ctx, layer)))), _ => None, } diff --git a/crates/render/src/tests/collapse.rs b/crates/render/src/tests/collapse.rs index 30d2163c1..4104e0b38 100644 --- a/crates/render/src/tests/collapse.rs +++ b/crates/render/src/tests/collapse.rs @@ -161,8 +161,17 @@ fn referenced_layer_overrides_change_the_owner_cache_key() { let opacity = comp.layer(aid).unwrap().props.prop("transform/opacity").unwrap().uid; let key = |value: f64| { let overrides = [crate::PropertyOverride { layer: aid, prop: opacity, value: Value::Scalar(value), font: false }]; - let ctx = - EvalCtx { project: &p, comp_id: cid, comp, time: Tick::ZERO, expr: None, footage: None, property_overrides: &overrides, media_overrides: &[] }; + let ctx = EvalCtx { + project: &p, + comp_id: cid, + comp, + time: Tick::ZERO, + expr: None, + footage: None, + property_overrides: &overrides, + media_overrides: &[], + reads: None, + }; crate::cache::layer_key(&ctx, b, 1.0, false, false) }; let (opaque, half) = (key(100.0), key(50.0)); diff --git a/crates/render/src/tests/time.rs b/crates/render/src/tests/time.rs index e9599f70b..715c37ef0 100644 --- a/crates/render/src/tests/time.rs +++ b/crates/render/src/tests/time.rs @@ -143,6 +143,7 @@ fn input_keys_ignore_later_effects() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &comp.layers[0]; (crate::cache::input_key(&ctx, l, 1.0, false, false, 1), crate::cache::input_key(&ctx, l, 1.0, false, false, 2)) diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 683da82ee..cb7e16fce 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -638,11 +638,49 @@ fn align_index(j: Justify) -> u8 { } } +/// Note the font files `lay` is drawn with in [`EvalCtx::reads`] (#3184), each with its identity +/// as its bytes were read, so a cache entry of the text is checked against them. What the +/// files can't vouch for makes the list incomplete: a family that is not installed (installing +/// it changes the text), a character drawn with a fallback face or with none (another installed +/// font could take it), a font from memory. +fn note_fonts(ctx: &EvalCtx, lay: &TextLayout) { + use crate::reads::{FileStamp, ReadFile}; + use effectcraft_text::fonts; + let Some(log) = ctx.reads else { return }; + let resolved: Vec = lay.styles.iter().map(|s| fonts::resolve(&s.font, &s.style)).collect(); + if resolved.iter().any(|r| r.missing) { + log.mark_incomplete(); + } + let mut faces: Vec = Vec::new(); + for g in &lay.layout.glyphs { + if g.id == 0 || resolved.get(g.run).is_none_or(|r| r.face != g.face) { + log.mark_incomplete(); + } + if !faces.contains(&g.face) { + faces.push(g.face); + } + } + for id in faces { + let face = fonts::face(id); + match &face.info.data { + fonts::FaceData::Static(_) => {} + fonts::FaceData::Shared(_) => log.mark_incomplete(), + fonts::FaceData::File(_) => { + if let Some((path, meta)) = face.file_read() { + let stamp = meta.map_or(FileStamp::Missing, FileStamp::of_metadata); + log.note(ReadFile::new(path.to_string_lossy().as_ref(), stamp)); + } + } + } + } +} + /// Lay out and animate a text layer. pub fn text_geom(ctx: &EvalCtx, layer: &Layer) -> Option { let doc = source_text(ctx, layer)?; let text = layer.props.sub("text")?; let lay = layout_doc(&doc); + note_fonts(ctx, &lay); let xfs = char_transforms(ctx, layer, text, &lay); let three = per_char_3d(ctx, layer); let more = text.sub("moreOptions"); @@ -665,6 +703,7 @@ pub fn text_geom(ctx: &EvalCtx, layer: &Layer) -> Option { // Same character count: the style runs still line up. let d2 = TextDoc { text: chars.into_iter().collect(), ..doc.clone() }; let l2 = layout_doc(&d2); + note_fonts(ctx, &l2); let by_char: std::collections::HashMap = lay.glyphs.iter().zip(&xfs).map(|(g, x)| (g.char_index, *x)).collect(); let x2: Vec = l2.glyphs.iter().map(|g| by_char.get(&g.char_index).copied().unwrap_or_default()).collect(); subs = vec![None; l2.glyphs.len()]; diff --git a/crates/render/src/text/tests.rs b/crates/render/src/text/tests.rs index 0280115a5..cd89ad1d1 100644 --- a/crates/render/src/text/tests.rs +++ b/crates/render/src/text/tests.rs @@ -715,3 +715,58 @@ fn range_bar_drag_values() { assert_eq!(range_value_of(3.6 / 7.0, 0.0, true, 7), 4.0); assert_eq!(range_value_of(3.6 / 7.0, 2.0 / 7.0, true, 7), 2.0, "less a 2-character Offset"); } + +/// Text names the font files it is drawn with (#3184), with their identity as they were read, so +/// a cache entry of it is checked against them; what the files can't vouch for (a family that +/// isn't installed) leaves the list incomplete. +#[test] +fn text_notes_the_font_files_it_draws_with() { + use crate::reads::{FileStamp, ReadLog}; + use effectcraft_text::fonts::{self, FaceData, FaceInfo, FontSource}; + struct OneFile(std::path::PathBuf); + impl FontSource for OneFile { + fn faces(&self) -> Vec { + vec![FaceInfo { + family: "Reads Test Sans".into(), + style: "Regular".into(), + weight: 400, + italic: false, + index: 0, + data: FaceData::File(self.0.clone()), + origin: "system", + native_family: None, + full_name: "Reads Test Sans Regular".into(), + postscript: None, + variable: false, + instances: vec![], + }] + } + } + let dir = std::env::temp_dir().join(format!("effectcraft-font-reads-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let font = dir.join("reads-test-sans.ttf"); + std::fs::write(&font, fonts::INTER_REGULAR).unwrap(); + fonts::add_source(&OneFile(font.clone())); + let stamp = FileStamp::native(&font.to_string_lossy()).unwrap(); + let files_of = |family: &str| { + let (mut p, cid, comp) = setup(200, 80); + let l = + text_layer(&mut p, &comp, TextDoc { text: "Hi there\rtwo".into(), font: family.into(), style: "Regular".into(), size: 30.0, ..Default::default() }); + p.comp_mut(cid).unwrap().layers.push(l); + let log = ReadLog::new(); + let c = EvalCtx { reads: Some(&log), ..ctx(&p, cid, 0.0) }; + assert!(text_geom(&c, &p.comp(cid).unwrap().layers[0]).is_some()); + log.into_files() + }; + let files = files_of("Reads Test Sans"); + assert!(files.is_complete(), "{files:?}"); + assert_eq!(files.files().len(), 1, "{files:?}"); + assert_eq!(files.get(&font.to_string_lossy()), Some(stamp)); + // The bundled family reads no file. + let files = files_of(effectcraft_text::fonts::DEFAULT_FAMILY); + assert!(files.is_complete() && files.is_empty(), "{files:?}"); + // A family that isn't installed falls back: installing it would change the text. + assert!(!files_of("No Such Family 3184").is_complete()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/render/src/three_d/adv/scene.rs b/crates/render/src/three_d/adv/scene.rs index b706826de..9166dc4a4 100644 --- a/crates/render/src/three_d/adv/scene.rs +++ b/crates/render/src/three_d/adv/scene.rs @@ -656,7 +656,7 @@ fn extruded_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, p: &model::extrude let opacity = (ctx.opacity(layer) as f32 * r.opacity_mul()).clamp(0.0, 1.0); let world = b.outer * ctx.world_matrix(layer); let lin = b.s.linear_io; - for (mesh, c, local) in extruded_meshes(ctx, layer, p) { + for (mesh, c, local) in extruded_meshes(&r.with_reads(ctx), layer, p) { let l = |v: f32| if lin { v } else { srgb_to_linear(v) }; let m = b.material(Material { base: [l(c[0]), l(c[1]), l(c[2]), c[3]], @@ -699,7 +699,7 @@ fn card_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { mat.opacity = (ctx.opacity(layer) as f32 * r.opacity_mul()).clamp(0.0, 1.0); let world = b.outer * ctx.world_matrix(layer); if crate::text::per_char_3d(ctx, layer) { - for (buf, m) in crate::text::per_char_planes(ctx, layer, r.opts.scale) { + for (buf, m) in crate::text::per_char_planes(&r.with_reads(ctx), layer, r.opts.scale) { let buf = r.to_blend(Arc::new(buf), None, &Arc::default()); card(b, &buf, world * m, mat); } diff --git a/crates/render/src/three_d/adv/tests.rs b/crates/render/src/three_d/adv/tests.rs index b2612de98..88e805882 100644 --- a/crates/render/src/three_d/adv/tests.rs +++ b/crates/render/src/three_d/adv/tests.rs @@ -822,6 +822,7 @@ fn extruded_text_renders_as_a_mesh() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); @@ -870,6 +871,7 @@ fn shape_surface_items_colour_the_extruded_surfaces() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); @@ -915,6 +917,7 @@ fn text_animators_colour_the_extruded_surfaces() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); @@ -1122,6 +1125,7 @@ fn extruded_strokes_render_as_bevelled_meshes() { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let l = &ctx.comp.layers[0]; let params = scene::extrusion_params(&ctx, l).unwrap(); diff --git a/crates/render/src/three_d/compose.rs b/crates/render/src/three_d/compose.rs index 361f427c3..ff08eb05f 100644 --- a/crates/render/src/three_d/compose.rs +++ b/crates/render/src/three_d/compose.rs @@ -203,7 +203,7 @@ pub(crate) fn prepare<'a>(r: &Renderer, ctx: &EvalCtx<'_>, layer: &'a Layer, ord /// Prepare a layer as planes: one per character for per-character 3D text, else one. pub(crate) fn prepare_all<'a>(r: &Renderer, ctx: &EvalCtx<'_>, layer: &'a Layer, order: usize, out: (u32, u32), in_run: bool) -> Vec> { if crate::text::per_char_3d(ctx, layer) { - return crate::text::per_char_planes(ctx, layer, r.opts.scale) + return crate::text::per_char_planes(&r.with_reads(ctx), layer, r.opts.scale) .into_iter() .filter_map(|(buf, m)| { prepare_with(r, ctx, layer, order, out, in_run, PlaneInput { buf: r.to_blend(Arc::new(buf), None, &Arc::default()), local: m }) diff --git a/crates/script/src/tests/ui_more.rs b/crates/script/src/tests/ui_more.rs index 483d686ef..c15aee0ae 100644 --- a/crates/script/src/tests/ui_more.rs +++ b/crates/script/src/tests/ui_more.rs @@ -231,6 +231,7 @@ fn position_now(s: &Session, layer: u64) -> [f64; 2] { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let v = ctx.value(l, l.props.prop("transform/position").unwrap()).components(); [v[0], v[1]] diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 5388629cf..f9ad858eb 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -158,11 +158,24 @@ fn info_from(n: FaceNames, data: FaceData, origin: &'static str) -> FaceInfo { } } +/// A font file's bytes and its metadata from the same open file (so the metadata describes the +/// bytes, not a later version of the file). +fn read_with_metadata(path: &std::path::Path) -> std::io::Result<(Vec, std::fs::Metadata)> { + use std::io::Read; + let mut f = std::fs::File::open(path)?; + let meta = f.metadata()?; + let mut bytes = Vec::new(); + f.read_to_end(&mut bytes)?; + Ok((bytes, meta)) +} + /// A loaded (or loadable) face. pub struct Face { pub id: FaceId, pub info: FaceInfo, bytes: OnceLock>, + /// The file's metadata as its bytes were read (a [`FaceData::File`] face, once loaded). + file_meta: OnceLock, shaper: OnceLock, } @@ -200,11 +213,23 @@ impl Face { .get_or_init(|| match &self.info.data { FaceData::Static(b) => Some(FaceBytes::Static(b)), FaceData::Shared(b) => Some(FaceBytes::Shared(b.clone())), - FaceData::File(p) => std::fs::read(p).ok().map(|v| FaceBytes::Shared(Arc::new(v))), + FaceData::File(p) => { + let (bytes, meta) = read_with_metadata(p).ok()?; + let _ = self.file_meta.set(meta); + Some(FaceBytes::Shared(Arc::new(bytes))) + } }) .as_ref() .map(FaceBytes::get) } + /// The file a [`FaceData::File`] face is drawn from, with its metadata as its bytes were read + /// (`None` when it could not be read): what text drawn with the face was made of. Loads the + /// face. `None` for bundled faces and faces from memory. + pub fn file_read(&self) -> Option<(&std::path::Path, Option<&std::fs::Metadata>)> { + let FaceData::File(p) = &self.info.data else { return None }; + let _ = self.bytes(); + Some((p, self.file_meta.get())) + } /// The parsed font (None if the file is missing or unreadable). pub fn font(&self) -> Option> { FontRef::from_index(self.bytes()?, self.info.index).ok() @@ -314,7 +339,7 @@ fn bundled_default_face() -> Arc { variable: false, instances: Vec::new(), }); - Arc::new(Face { id: 0, info, bytes: OnceLock::new(), shaper: OnceLock::new() }) + Arc::new(Face { id: 0, info, bytes: OnceLock::new(), file_meta: OnceLock::new(), shaper: OnceLock::new() }) } fn db() -> &'static RwLock { @@ -333,7 +358,7 @@ fn db() -> &'static RwLock { fn push(db: &mut Db, info: FaceInfo) -> FaceId { let id = db.faces.len(); - db.faces.push(Arc::new(Face { id, info, bytes: OnceLock::new(), shaper: OnceLock::new() })); + db.faces.push(Arc::new(Face { id, info, bytes: OnceLock::new(), file_meta: OnceLock::new(), shaper: OnceLock::new() })); id } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 4d2c15b2a..1c34c2cb1 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -163,6 +163,7 @@ fn vertex_delta(app: &EffectcraftApp, layer: effectcraft_engine::project::LayerI footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let (l2c, _) = crate::panels::viewer::l2c(&ectx, l); l2c.inverse().map_or(d, |inv| { diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index 0857dfa3f..39fd4847a 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -186,6 +186,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let hdr = Rect::from_min_size(rect.min, vec2(rect.width(), 24.0)); p.text(pos2(hdr.min.x + 10.0, hdr.center().y), Align2::LEFT_CENTER, format!("{} • {}", comp_name, layer.name), Tokens::ui(11.5), t.text_dim); diff --git a/crates/ui-egui/src/panels/layer_panel.rs b/crates/ui-egui/src/panels/layer_panel.rs index 8e4f3502f..e23e11cfb 100644 --- a/crates/ui-egui/src/panels/layer_panel.rs +++ b/crates/ui-egui/src/panels/layer_panel.rs @@ -113,6 +113,7 @@ fn render_tex( footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let mut r = Renderer::new(&app.session.project, &*app.session.footage, RenderOpts { scale, ..Default::default() }); r.expr = app.session.expr.as_deref(); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 25829be7d..4edcbb31a 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -79,6 +79,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let scroll = widgets::PanelScroll::begin(ui, egui::Id::unique("props-scroll"), rect); let rect = scroll.content; diff --git a/crates/ui-egui/src/panels/roto_tool.rs b/crates/ui-egui/src/panels/roto_tool.rs index 194bba26a..c01a8f07e 100644 --- a/crates/ui-egui/src/panels/roto_tool.rs +++ b/crates/ui-egui/src/panels/roto_tool.rs @@ -114,6 +114,7 @@ pub fn draw_overlay( footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let mut r = Renderer::new(&app.session.project, &*app.session.footage, RenderOpts { scale, ..Default::default() }); r.expr = app.session.expr.as_deref(); diff --git a/crates/ui-egui/src/panels/text_panels.rs b/crates/ui-egui/src/panels/text_panels.rs index 096b41cf2..f22d775a3 100644 --- a/crates/ui-egui/src/panels/text_panels.rs +++ b/crates/ui-egui/src/panels/text_panels.rs @@ -66,6 +66,7 @@ pub fn text_target(app: &EffectcraftApp) -> Option { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; effectcraft_engine::render::text::source_text(&ectx, layer).map(|d| TextTarget { layer: layer.id.0, doc: d, range: None }) } diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs index 038dcc9b9..d7017e7fd 100644 --- a/crates/ui-egui/src/panels/timeline.rs +++ b/crates/ui-egui/src/panels/timeline.rs @@ -1982,6 +1982,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let mut rw = begin_rows(app, ui, tl); let g = &mut rw; diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index b1899e1f8..1e214ab53 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -212,6 +212,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; phase_guides(app, &ectx, &mut v); phase_layers(app, ui, &ectx, &mut v); diff --git a/crates/ui-egui/src/panels/viewer/shapes.rs b/crates/ui-egui/src/panels/viewer/shapes.rs index 0cd579883..903abd42f 100644 --- a/crates/ui-egui/src/panels/viewer/shapes.rs +++ b/crates/ui-egui/src/panels/viewer/shapes.rs @@ -219,6 +219,7 @@ pub(super) fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let inv = l2c(&ectx, &l).0.inverse().unwrap_or(Mat3::IDENTITY); let p0 = inv.apply(gv2(cx - w / 2.0, cy - h / 2.0)); diff --git a/crates/ui-egui/src/panels/viewer/view.rs b/crates/ui-egui/src/panels/viewer/view.rs index 60a68c57c..e837528b3 100644 --- a/crates/ui-egui/src/panels/viewer/view.rs +++ b/crates/ui-egui/src/panels/viewer/view.rs @@ -53,6 +53,7 @@ pub(super) fn aux_views( footage: None, property_overrides: &[], media_overrides: &[], + reads: None, }; let selected = app.session.state.selected_layers.clone(); let mut picked: Option<(usize, View3D)> = None; From 1e569ee3a98dd52defaf6468d4f72a243335eddb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 02:14:17 +0100 Subject: [PATCH 027/324] Disk cache: frame entries store the whole modification time A frame entry's file list stores a file's modification time as i128 nanoseconds since 1970 (negative before), as the file stamps now keep it; the frame entry format version goes to frame-entry-files-2 so entries in the old layout are not read. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/disk_cache.rs | 2 +- crates/render/src/disk_cache/entry_files.rs | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index b4f90fc4d..01ab5118e 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -1279,7 +1279,7 @@ fn comp_content_key_for_renderer(project: &effectcraft_project::Project, comp: e /// Frame entries with their source files (#3184), part of every frame key: entries of the /// earlier format (keyed by footage stamps instead) are never looked up again; least recently /// used, they are evicted. -const FRAME_ENTRY_VERSION: &[u8] = b"frame-entry-files-1"; +const FRAME_ENTRY_VERSION: &[u8] = b"frame-entry-files-2"; /// Disk key of one viewer frame. pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 { diff --git a/crates/render/src/disk_cache/entry_files.rs b/crates/render/src/disk_cache/entry_files.rs index fae8cab8f..4ebd1f2e6 100644 --- a/crates/render/src/disk_cache/entry_files.rs +++ b/crates/render/src/disk_cache/entry_files.rs @@ -4,8 +4,9 @@ //! //! Layout (little endian), before the frame's pixel payload: //! `u32 count`, then per file `u32 path length`, the path (UTF-8), a tag byte and its fields: -//! `0` a file on disk (`u64 size`, `u8 has time`, `u64 time`), `1` bytes from the browser's file -//! table (`u64 size`, `u64 content hash`), `2` a file that could not be read. +//! `0` a file on disk (`u64 size`, `u8 has time`, `i128 time`: nanoseconds since the Unix epoch, +//! negative before it), `1` bytes from the browser's file table (`u64 size`, `u64 content +//! hash`), `2` a file that could not be read. use std::sync::Arc; @@ -18,8 +19,9 @@ const MAX_PATH_BYTES: usize = 1 << 16; /// A file's identity as a frame entry keeps it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EntryStamp { - /// Size and modification time (nanoseconds since the Unix epoch) on disk. - Native { len: u64, modified: Option }, + /// Size and modification time (nanoseconds since the Unix epoch, negative before it) on + /// disk. + Native { len: u64, modified: Option }, /// Size and content hash from the [`VirtualFileId`] hook (the browser's file table). Virtual { len: u64, hash: u64 }, /// It could not be read when the frame was made: it still must not be readable. @@ -134,7 +136,7 @@ impl EntryFiles { 0 => { let len = r.u64()?; let has = r.u8()?; - let t = r.u64()?; + let t = r.i128()?; match has { 0 => EntryStamp::Native { len, modified: None }, 1 => EntryStamp::Native { len, modified: Some(t) }, @@ -179,6 +181,9 @@ impl<'a> Reader<'a> { fn u64(&mut self) -> Option { Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) } + fn i128(&mut self) -> Option { + Some(i128::from_le_bytes(self.take(16)?.try_into().ok()?)) + } } #[cfg(test)] @@ -189,6 +194,9 @@ mod tests { [ ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(9) }), ReadFile::new("/b.png", FileStamp::Native { len: 4, modified: None }), + // Before 1970, and past where `u64` nanoseconds end (2554). + ReadFile::new("/d.png", FileStamp::Native { len: 5, modified: Some(-86_400_000_000_000) }), + ReadFile::new("/e.png", FileStamp::Native { len: 6, modified: Some(i128::from(u64::MAX) + 1) }), ReadFile::new("/c.png", FileStamp::Missing), ReadFile::new("/v.mov", FileStamp::Virtual), ] @@ -200,7 +208,7 @@ mod tests { fn lists_round_trip_and_damage_is_caught() { let id = |p: &str| (p == "/v.mov").then_some((8, 77)); let list = EntryFiles::of(&files(), Some(&id)).unwrap(); - assert_eq!(list.files()[3].stamp, EntryStamp::Virtual { len: 8, hash: 77 }); + assert_eq!(list.files()[5].stamp, EntryStamp::Virtual { len: 8, hash: 77 }); let mut bytes = vec![]; list.encode(&mut bytes); bytes.extend_from_slice(b"rest"); From eeff6f44ffb2eec374922de568aaf810b3d37b1e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 02:30:50 +0100 Subject: [PATCH 028/324] Disk cache: layer entries store the whole modification time Layer entries share the frame entries' file list layout, which now stores the full i128 modification time: the layer entry format version goes to layer-entry-files-2. The module doc names the font files text is drawn with among an entry's source files, and what keeps a list incomplete. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/disk_cache.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 53137bd5c..fe8ec05a5 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -8,10 +8,12 @@ //! items a buffer uses with their settings and paths) and the renderer version //! ([`layer_disk_key`]). A changed project therefore never reads stale pixels: its keys simply //! change. -//! * Frame and layer entries keep the source files they were made of, each with the size and -//! modification time it was read with ([`EntryFiles`], #3184). An entry is used only while -//! those files are unchanged: a handful of `metadata` calls when it is read, never a scan of -//! the project's files. A frame or buffer whose files can't all be named is not stored. +//! * Frame and layer entries keep the source files they were made of (footage, and the font +//! files text is drawn with), each with the size and modification time it was read with +//! ([`EntryFiles`], #3184). An entry is used only while those files are unchanged: a handful +//! of `metadata` calls when it is read, never a scan of the project's files. A frame or +//! buffer whose files can't all be named is not stored (text in a family that isn't installed +//! or with fallback glyphs, footage refused by automation read roots, …). //! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA (or, for //! 32 bpc viewer frames, half-float RGBA with the bytes shuffled into planes; the entry //! header's format byte tells them apart: 2 and 3, both with their source files first), layer @@ -1165,7 +1167,7 @@ pub type SharedVirtualFileId = Arc Option<(u64, u64)> + Send + S /// Layer entries with their source files (#3184), part of every layer disk key: entries of the /// earlier format (keyed by a project-wide footage salt instead) are never looked up again; /// least recently used, they are evicted. -const LAYER_ENTRY_VERSION: &[u8] = b"layer-entry-files-1"; +const LAYER_ENTRY_VERSION: &[u8] = b"layer-entry-files-2"; /// Disk key of a layer buffer: the layer cache's content key ([`crate::cache::layer_key`] and /// the keys derived from it), the layer entry format and the renderer version. The content key From a5e673dd6aa719169010fb3cc10029ae118a76cf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 02:42:22 +0100 Subject: [PATCH 029/324] Layer cache: buffers that read other layers are keyed by the switches passed down MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A layer whose effect reads another layer (Gradient Wipe, Set Matte, Blend…) gets that layer drawn by its own renderer. Through a precomp layer, Switches Affect Nested Comps, the switches inherited from the precomp layers above and motion blur on change those pixels, but the key held only the layers' own switches: a buffer made with the setting on was reused (from memory or the disk cache) with it off. Such layers now derive their key with what the renderer passes down. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/cache.rs | 15 +++++++++++++++ crates/render/src/layers.rs | 4 ++++ crates/render/src/pipeline.rs | 18 ++++++++++++++++++ crates/render/src/tests.rs | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+) diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 015aec26c..881d8b2b7 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -22,6 +22,7 @@ use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; use effectcraft_effects::Buf; +use effectcraft_keyframe::Value; use effectcraft_project::{FootageKind, ItemKind, Layer, LayerSource, Node, PropGroup}; use crate::disk_cache::{EntryFiles, SharedVirtualFileId, VirtualFileId, layer_disk_key}; @@ -790,6 +791,20 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo Some(h.finish()) } +/// Does the layer read another layer through an enabled effect's layer parameter (Gradient Wipe, +/// Set Matte…)? Those layers are drawn by the reading layer's renderer, so the switches it +/// passes down belong in the key (`Renderer::nested_look`). +pub(crate) fn reads_layers(ctx: &EvalCtx, layer: &Layer) -> bool { + fn reads(ctx: &EvalCtx, layer: &Layer, g: &PropGroup, depth: usize) -> bool { + depth < 32 + && g.children.iter().any(|n| match n { + Node::Prop(p) => matches!(p.value, Value::Layer(_)) && ctx.value(layer, p).as_layer().is_some_and(|id| id != layer.id.0), + Node::Group(sub) => sub.enabled && reads(ctx, layer, sub, depth + 1), + }) + } + layer.switches.effects && layer.effects().is_some_and(|fx| fx.groups().any(|g| g.enabled && reads(ctx, layer, g, 0))) +} + /// Does the layer run an effect that reads the comp camera or lights (Card Dance, CC Particle /// World…)? fn reads_comp_scene(layer: &Layer) -> bool { diff --git a/crates/render/src/layers.rs b/crates/render/src/layers.rs index 9eb87a47e..fe0ff0ef1 100644 --- a/crates/render/src/layers.rs +++ b/crates/render/src/layers.rs @@ -250,6 +250,10 @@ impl<'a> Renderer<'a> { /// depends on the content at every sub-sample). pub(crate) fn content_key(&self, ctx: &EvalCtx, layer: &Layer, key: Option) -> Option { let k = key?; + // A layer that reads other layers through its effects' layer parameters gets them drawn + // by this renderer: the switches it passes down (Switches Affect Nested Comps, the + // precomp layers above, motion blur on) change those pixels, not just the layers' own. + let k = if cache::reads_layers(ctx, layer) { cache::derive(k, self.nested_look()) } else { k }; let Some(times) = self.content_times(ctx, layer) else { return Some(k) }; times.iter().try_fold(cache::derive(k, 0x6d62_6c72), |d, t| Some(cache::derive(d, cache::layer_key(&ctx.at(*t), layer, 1.0, false, false)?))) } diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 78ac11fb6..2b55bcea6 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -205,6 +205,24 @@ impl<'a> Renderer<'a> { } } + /// What this renderer passes down to the layers it draws beyond their own switches + /// ([`RenderOpts::nested_switches`], the switches inherited from the precomp layers above, + /// motion blur on): part of the cache key of a buffer that reads other layers. + pub(crate) fn nested_look(&self) -> u64 { + let inherited = match self.inherited { + None => 0, + Some((q, mb)) => { + let q = match q { + Quality::Best => 0, + Quality::Draft => 1, + Quality::Wireframe => 2, + }; + 1 + q * 2 + u64::from(mb) + } + }; + 0x6e65_7374_0000_0000 | inherited << 2 | u64::from(self.opts.nested_switches) << 1 | u64::from(self.opts.motion_blur) + } + /// A layer's Motion Blur switch, limited by the precomp layers above it. pub(crate) fn layer_motion_blur(&self, layer: &Layer) -> bool { layer.switches.motion_blur && self.inherited.is_none_or(|(_, mb)| mb) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index c77fc2d94..3afe5f794 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -820,6 +820,41 @@ fn effects_read_layer_params() { assert!(px[2] > 0.99 && px[0] < 0.01, "{px:?}"); } +/// A cached layer whose effect reads a precomp layer: how the precomp's layers render depends on +/// Switches Affect Nested Comps (the precomp layer's Draft quality passes down) and on the +/// switches the reading layer's own comp inherits, so the key must tell them apart (a buffer +/// made under the other setting, from memory or disk, is stale). +#[test] +fn a_cached_layer_reading_a_precomp_is_keyed_by_the_nested_switches() { + let (mut p, cid, comp) = setup(); + let mut inner = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); + // A rotated square off the pixel grid: Draft (nearest) and Best (bilinear) sampling differ. + let mut dot = solid(&mut p, &inner, [1.0, 1.0, 1.0], 40, 40); + dot.props.prop_mut("transform/position").unwrap().value = Value::Vec3([100.3, 50.6, 0.0]); + dot.props.prop_mut("transform/rotation").unwrap().value = Value::Scalar(30.0); + inner.layers.push(dot); + let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into())); + let mut pre = build::layer(&mut p, &comp, "Inner", LayerSource::Comp { item: iid }, (200, 100), None); + pre.switches.video = false; + pre.switches.quality = effectcraft_project::Quality::Draft; + let mut top = solid(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100); + add_effect_200(&mut p, &mut top, "ec.channel.blend", &[("blendWithLayer", Value::Layer(Some(pre.id.0)))]); + let c = p.comp_mut(cid).unwrap(); + c.layers.push(top); + c.layers.push(pre); + let frame = |nested_switches: bool, cache: Option<&crate::LayerCache>| { + let mut r = crate::Renderer::new(&p, &crate::NoFootage, crate::RenderOpts { nested_switches, ..Default::default() }); + r.cache = cache; + r.comp_frame(cid, Tick::ZERO).data + }; + let (on, off) = (frame(true, None), frame(false, None)); + assert!(on != off, "the precomp layer's Draft quality passes down"); + let cache = crate::LayerCache::default(); + assert!(frame(true, Some(&cache)) == on); + assert!(frame(false, Some(&cache)) == off, "not the buffer made with switches affecting nested comps"); + assert!(frame(true, Some(&cache)) == on, "and back"); +} + /// Records whether the GPU compositor was asked to draw a frame. struct ProbeAccel(std::sync::atomic::AtomicBool); impl crate::Accelerator for ProbeAccel { From e88b847259168506dbff5ef2ba95894c1553730a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 02:51:51 +0100 Subject: [PATCH 030/324] Layer cache: masked buffers are keyed by the mask motion blur gate A mask with Mask Motion Blur On blurs even when the layer's own switch is off, as long as the render's gate is open (Render Settings motion blur, and with Switches Affect Nested Comps the precomp layers above). The key held the layer's own motion blur state only, so a buffer blurred with the gate open was reused with it closed (and the other way round), also from the disk cache. Masked layer, input and footprint keys now tell a closed gate apart. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/accel.rs | 1 + crates/render/src/layers.rs | 11 ++++++++++- crates/render/src/tests/mask_blur.rs | 29 ++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/render/src/accel.rs b/crates/render/src/accel.rs index 9e5d2138a..e794f84f7 100644 --- a/crates/render/src/accel.rs +++ b/crates/render/src/accel.rs @@ -349,6 +349,7 @@ impl<'a> Renderer<'a> { pub fn adjustment_footprint(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { // Cached, so an accelerator sees the same buffer (and uploads it once) every frame. let key = self.cache.and_then(|_| cache::footprint_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer))); + let key = self.mask_gate_key(ctx, layer, key); if let Some((b, _)) = self.cached(key) { return Some(b); } diff --git a/crates/render/src/layers.rs b/crates/render/src/layers.rs index fe0ff0ef1..5a45c0f0b 100644 --- a/crates/render/src/layers.rs +++ b/crates/render/src/layers.rs @@ -249,7 +249,7 @@ impl<'a> Renderer<'a> { /// A processed-layer cache key that also covers content motion blur (the averaged source /// depends on the content at every sub-sample). pub(crate) fn content_key(&self, ctx: &EvalCtx, layer: &Layer, key: Option) -> Option { - let k = key?; + let k = self.mask_gate_key(ctx, layer, key)?; // A layer that reads other layers through its effects' layer parameters gets them drawn // by this renderer: the switches it passes down (Switches Affect Nested Comps, the // precomp layers above, motion blur on) change those pixels, not just the layers' own. @@ -274,6 +274,15 @@ impl<'a> Renderer<'a> { } } + /// A cache key of a masked layer's buffer, told apart when mask motion blur can't run at all + /// in this render ([`Self::mask_blur`]'s gate: the render options, the precomp layers above). + /// The key has the layer's own motion blur state, but a mask set to On blurs without it. + pub(crate) fn mask_gate_key(&self, ctx: &EvalCtx, layer: &Layer, key: Option) -> Option { + let k = key?; + let masked = layer.masks().is_some_and(|m| !m.children.is_empty()); + Some(if masked && !self.mask_blur(ctx, layer).allowed { cache::derive(k, 0x6d62_6f66) } else { k }) + } + /// Motion-blur sub-samples for a layer buffer (1 = no motion blur). As in After Effects, a 2D /// layer gets about one sample per output pixel its corners travel during the shutter, /// at least Samples Per Frame and at most the comp's Adaptive Sample Limit; a layer that diff --git a/crates/render/src/tests/mask_blur.rs b/crates/render/src/tests/mask_blur.rs index 07bc1e95f..5f3ff4e2a 100644 --- a/crates/render/src/tests/mask_blur.rs +++ b/crates/render/src/tests/mask_blur.rs @@ -75,3 +75,32 @@ fn mask_motion_blur_follows_the_render_and_the_comp() { let (p, cid) = project(false); assert!(alpha_at_25(&p, cid, true) < 0.01, "the comp's switch off"); } + +/// Whether mask motion blur may run at all (the render options, Switches Affect Nested Comps with +/// a precomp layer's switch off) is part of the layer cache key, also for a layer whose own +/// switch is off: a buffer made with the gate open must not serve a render with it closed. +#[test] +fn the_mask_motion_blur_gate_keys_the_layer_cache() { + let (mut p, inner) = project(true); + let mut outer = Comp::new(100, 100, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + outer.enable_motion_blur = true; + let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: inner }, (100, 100), None); + pre.switches.motion_blur = false; + outer.layers.push(pre); + let oid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(outer.into())); + let half = Tick::from_seconds_f64(0.5 / 30.0); + let cache = crate::LayerCache::default(); + let render = |cid: ItemId, opts: RenderOpts, cached: bool| { + let mut r = Renderer::new(&p, &NoFootage, opts); + r.cache = cached.then_some(&cache); + r.comp_frame(cid, half).data + }; + let on = RenderOpts { motion_blur: true, nested_switches: true, ..Default::default() }; + let off = RenderOpts { nested_switches: false, ..on }; + assert!(render(oid, on, false) != render(oid, off, false), "the precomp layer's switch closes the gate"); + assert!(render(oid, off, true) == render(oid, off, false)); + assert!(render(oid, on, true) == render(oid, on, false), "not the buffer blurred with the gate open"); + let still = RenderOpts { motion_blur: false, ..on }; + assert!(render(inner, on, true) == render(inner, on, false)); + assert!(render(inner, still, true) == render(inner, still, false), "Render Settings ▸ Motion Blur off"); +} From e6b19c9bc4b723e9600e91185ae3be8d8e46467d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 03:10:25 +0100 Subject: [PATCH 031/324] Render: cached buffers list what their expressions and substituted characters read - Buffers made under `Renderer::recorded` (layer content, a Time effect's input, an adjustment layer's footprint) evaluate their masks, shapes and effects with the context that notes into the buffer's own read log, so a file an expression reads (`sampleImage`, also at shutter times mask motion blur adds and the cache key doesn't see) is in the buffer's files. - A styled layer served from the cache lists the files of the cached body and passes too, so the buffers made of it (flattened, blending space) don't get a complete list when one of them came with an incomplete one. - A character put in by Character Offset or Character Value without a relayout notes the font it is drawn with; a fallback face (or none) leaves the list incomplete. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/accel.rs | 2 + crates/render/src/layers.rs | 37 +++++++++++++----- crates/render/src/pipeline.rs | 3 ++ crates/render/src/tests.rs | 63 +++++++++++++++++++++++++++++++ crates/render/src/tests/styles.rs | 31 +++++++++++++++ crates/render/src/text.rs | 23 +++++++++-- crates/render/src/text/tests.rs | 17 ++++++++- 7 files changed, 161 insertions(+), 15 deletions(-) diff --git a/crates/render/src/accel.rs b/crates/render/src/accel.rs index 9e5d2138a..69fe8e051 100644 --- a/crates/render/src/accel.rs +++ b/crates/render/src/accel.rs @@ -353,6 +353,8 @@ impl<'a> Renderer<'a> { return Some(b); } let (foot, files) = self.recorded(key, |r| { + // (what the masks' expressions read, at shutter times too, goes to the buffer's files) + let ctx = &r.with_reads(ctx); let mut foot = r.source(ctx, layer)?; let _ = masks::apply(ctx, layer, &mut foot, r.mask_blur(ctx, layer)); Some(foot) diff --git a/crates/render/src/layers.rs b/crates/render/src/layers.rs index 9eb87a47e..1eaf2847b 100644 --- a/crates/render/src/layers.rs +++ b/crates/render/src/layers.rs @@ -34,6 +34,17 @@ impl Shutter { } } +/// `files` (a content's) with the files of the buffers made of it that the layer cache kept: +/// `files` itself when they are all its own. +fn with_kept_files(files: Arc, kept: &[Arc]) -> Arc { + if kept.iter().all(|f| Arc::ptr_eq(f, &files)) { + return files; + } + let mut all = (*files).clone(); + kept.iter().for_each(|f| all.extend(f)); + Arc::new(all) +} + impl<'a> Renderer<'a> { /// The layer with its styles: exterior passes and body (cached per pass). pub(crate) fn styled(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option { @@ -43,10 +54,22 @@ impl<'a> Renderer<'a> { } let modes = styles::pass_modes(ctx, layer); let key = ckey.map(|k| cache::styles_key(ctx, layer, k)); - if let Some((body, _)) = self.cached(key) { - let passes: Option> = - modes.iter().enumerate().map(|(i, m)| self.cached(key.map(|k| cache::derive(k, i as u64 + 1))).map(|(b, _)| (b, *m))).collect(); + // (a cached body or pass may have been made of other files than the content: another + // worker's, or one from disk; the styled layer lists the files of every buffer it holds) + if let Some((body, body_files)) = self.cached(key) { + let mut kept_files = vec![body_files]; + let passes: Option> = modes + .iter() + .enumerate() + .map(|(i, m)| { + self.cached(key.map(|k| cache::derive(k, i as u64 + 1))).map(|(b, f)| { + kept_files.push(f); + (b, *m) + }) + }) + .collect(); if let Some(passes) = passes { + let files = with_kept_files(files, &kept_files); return Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }); } } @@ -73,13 +96,7 @@ impl<'a> Renderer<'a> { (b, m) }) .collect(); - let files = if kept_files.iter().all(|f| Arc::ptr_eq(f, &files)) { - files - } else { - let mut all = (*files).clone(); - kept_files.iter().for_each(|f| all.extend(f)); - Arc::new(all) - }; + let files = with_kept_files(files, &kept_files); Some(StyledLayer { passes, body, content, key, ckey, plain: false, files }) } diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 136874be1..9f1d3fba3 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -1063,6 +1063,8 @@ impl<'a> Renderer<'a> { return Some((b, key, files)); } let (buf, files) = self.recorded(key, |r| { + // (what expressions read while it is made, at shutter times too, goes to its files) + let ctx = &r.with_reads(ctx); let buf = r.masked_source(ctx, layer)?; Some(r.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects))) }); @@ -1081,6 +1083,7 @@ impl<'a> Renderer<'a> { return Some(b); } let (buf, files) = self.recorded(key, |r| { + let ctx = &r.with_reads(ctx); let mut buf = r.masked_source(ctx, layer)?; let origin = ctx.effect_bounds(layer).1; buf.rebase(origin); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index c77fc2d94..723671afa 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -482,6 +482,69 @@ impl crate::eval::ExprHost for ControllerRate { } } +/// An expression that reads a file (as `sampleImage` does, into [`EvalCtx::reads`]) and keeps +/// the value. +/// +/// [`EvalCtx::reads`]: crate::eval::EvalCtx::reads +struct ReadsAFile; + +impl crate::eval::ExprHost for ReadsAFile { + fn eval(&self, ctx: &crate::eval::EvalCtx, _: &effectcraft_project::Layer, _: &effectcraft_project::Property, value: &Value) -> Result { + if let Some(log) = ctx.reads { + log.note(crate::reads::ReadFile::new("/sampled.png", crate::reads::FileStamp::Native { len: 3, modified: Some(1) })); + } + Ok(value.clone()) + } +} + +/// What expressions read while a cached buffer is made (a mask expression, which mask motion +/// blur also runs at shutter times the cache key doesn't see) goes to that buffer's files, not +/// only to the frame's (#3184): a later render served the buffer lists the file too. Content, +/// a Time effect's input and an adjustment layer's footprint. +#[test] +fn what_expressions_read_goes_to_the_files_of_the_buffer_they_make() { + use crate::reads::ReadLog; + use crate::{NoFootage, RenderOpts, Renderer}; + let (mut p, cid, comp) = setup(); + for adjustment in [false, true] { + let mut l = solid(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100); + l.switches.adjustment = adjustment; + let mut next = p.next_id; + let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::Add, [255, 255, 0]); + p.next_id = next; + l.props.sub_mut("masks").unwrap().children.push(m.into()); + l.props.prop_mut("masks/#1/path").unwrap().expr = Some(effectcraft_project::Expression { text: "sampled".into(), enabled: true }); + p.comp_mut(cid).unwrap().layers.push(l); + } + let cache = crate::LayerCache::default(); + let c = p.comp(cid).unwrap(); + let (content, adjustment) = (&c.layers[0], &c.layers[1]); + // `make`, rendered once with the expressions (the files go to `log`) and then served from + // the cache to a render without them: the files that render lists. + let files_served = |what: &str, make: &dyn Fn(&Renderer, &crate::eval::EvalCtx) -> bool| { + let log = ReadLog::new(); + let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + r.expr = Some(&ReadsAFile); + r.cache = Some(&cache); + r.reads = Some(&log); + assert!(make(&r, &r.ctx(cid, c, Tick::ZERO)), "{what}"); + assert!(log.files().get("/sampled.png").is_some(), "{what}: the frame lists the file"); + let hits = cache.stats().hits; + let served = ReadLog::new(); + r.expr = None; + r.reads = Some(&served); + assert!(make(&r, &r.ctx(cid, c, Tick::ZERO)), "{what}"); + assert!(cache.stats().hits > hits, "{what}: served from the cache"); + served.into_files() + }; + let files = files_served("content", &|r, ctx| r.content_buf(ctx, content).is_some()); + assert!(files.get("/sampled.png").is_some(), "content: {files:?}"); + let files = files_served("input", &|r, ctx| r.layer_input(ctx, content, 0).is_some()); + assert!(files.get("/sampled.png").is_some(), "input: {files:?}"); + let files = files_served("footprint", &|r, ctx| r.adjustment_footprint(ctx, adjustment).is_some()); + assert!(files.get("/sampled.png").is_some(), "footprint: {files:?}"); +} + /// A Birth Rate expression reading another layer: changing that layer changes the history but /// not the current rate (0) nor this layer's properties, which is all the layer cache key sees. /// CC Particle World layers with expressions therefore aren't layer cached. diff --git a/crates/render/src/tests/styles.rs b/crates/render/src/tests/styles.rs index 2450fcf64..a9de6fb52 100644 --- a/crates/render/src/tests/styles.rs +++ b/crates/render/src/tests/styles.rs @@ -507,3 +507,34 @@ fn workers_styling_a_layer_at_once_share_its_buffers() { assert!(st.passes.iter().zip(&first.passes).all(|(a, b)| std::sync::Arc::ptr_eq(&a.0, &b.0)), "one set of passes"); } } + +/// A styled layer served from the cache lists the files of the body and passes it was served, +/// not only its content's (#3184): one made of other files (another worker's, or from disk, +/// whose list can't vouch for them) passes that on to the buffers made of it (flattened, in the +/// blending space), which are then not kept on disk as complete. +#[test] +fn a_cached_styled_layer_lists_the_files_of_its_cached_buffers() { + let (p, cid) = scene([1.0; 3], None, |p, c, l| add(p, c, l, "dropShadow")); + let layer = &p.comp(cid).unwrap().layers[0]; + let styled = |cache: &crate::LayerCache| { + let mut r = Renderer::new(&p, &NoFootage, RenderOpts::default()); + r.cache = Some(cache); + let ctx = r.eval_ctx(cid, Tick::ZERO).unwrap(); + r.styled_layer(&ctx, layer).unwrap() + }; + let first = styled(&crate::LayerCache::default()); + assert!(first.files.is_complete() && !first.passes.is_empty()); + let key = first.key.unwrap(); + // Body and passes kept with a list that can't vouch for them; the content renders again. + let cache = crate::LayerCache::default(); + let mut unsure = crate::reads::ReadFiles::default(); + unsure.mark_incomplete(); + let unsure = std::sync::Arc::new(unsure); + cache.insert(key, first.body.clone(), unsure.clone()); + for (i, (b, _)) in first.passes.iter().enumerate() { + cache.insert(crate::cache::derive(key, i as u64 + 1), b.clone(), unsure.clone()); + } + let hit = styled(&cache); + assert!(std::sync::Arc::ptr_eq(&hit.body, &first.body), "the cached body"); + assert!(!hit.files.is_complete(), "{:?}", hit.files); +} diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index cb7e16fce..4165d150d 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -644,15 +644,32 @@ fn align_index(j: Justify) -> u8 { /// it changes the text), a character drawn with a fallback face or with none (another installed /// font could take it), a font from memory. fn note_fonts(ctx: &EvalCtx, lay: &TextLayout) { + note_layout_fonts(ctx, &lay.styles, &lay.layout); +} + +/// A character put in by Character Offset or Character Value (`ch`, in style `st`), outside a +/// relayout: its outline and advance, with the font it is drawn with noted as [`note_fonts`] does +/// (the run's face may not have it: a fallback face then draws it). +fn substituted_glyph(ctx: &EvalCtx, st: &effectcraft_keyframe::CharStyle, ch: char) -> (BezPath, f64) { + if ctx.reads.is_some() { + // (the layout `char_glyph_style` makes, served from the layout cache there) + let lay = effectcraft_text::layout_text(&ch.to_string(), &effectcraft_text::text_style(st), &effectcraft_text::ParagraphStyle::default()); + note_layout_fonts(ctx, std::slice::from_ref(st), &lay); + } + char_glyph_style(st, ch) +} + +/// [`note_fonts`] for `layout`, whose glyphs' runs index `styles`. +fn note_layout_fonts(ctx: &EvalCtx, styles: &[effectcraft_keyframe::CharStyle], layout: &effectcraft_text::Layout) { use crate::reads::{FileStamp, ReadFile}; use effectcraft_text::fonts; let Some(log) = ctx.reads else { return }; - let resolved: Vec = lay.styles.iter().map(|s| fonts::resolve(&s.font, &s.style)).collect(); + let resolved: Vec = styles.iter().map(|s| fonts::resolve(&s.font, &s.style)).collect(); if resolved.iter().any(|r| r.missing) { log.mark_incomplete(); } let mut faces: Vec = Vec::new(); - for g in &lay.layout.glyphs { + for g in &layout.glyphs { if g.id == 0 || resolved.get(g.run).is_none_or(|r| r.face != g.face) { log.mark_incomplete(); } @@ -828,7 +845,7 @@ pub fn text_geom(ctx: &EvalCtx, layer: &Layer) -> Option { // Outline (substituted characters aligned in the original slot). let (outline, adv) = match subs[gi] { Some(c) => { - let (p, a) = char_glyph_style(st, c); + let (p, a) = substituted_glyph(ctx, st, c); let dx = match x.char_align { 0 => 0.0, 2 => g.advance - a, diff --git a/crates/render/src/text/tests.rs b/crates/render/src/text/tests.rs index cd89ad1d1..c4e43bb2e 100644 --- a/crates/render/src/text/tests.rs +++ b/crates/render/src/text/tests.rs @@ -749,16 +749,22 @@ fn text_notes_the_font_files_it_draws_with() { std::fs::write(&font, fonts::INTER_REGULAR).unwrap(); fonts::add_source(&OneFile(font.clone())); let stamp = FileStamp::native(&font.to_string_lossy()).unwrap(); - let files_of = |family: &str| { + // (`value`: a Character Value animator puts that character in for every one) + let files_with = |family: &str, value: Option| { let (mut p, cid, comp) = setup(200, 80); - let l = + let mut l = text_layer(&mut p, &comp, TextDoc { text: "Hi there\rtwo".into(), font: family.into(), style: "Regular".into(), size: 30.0, ..Default::default() }); + if let Some(c) = value { + animator(&mut p, &mut l, &["characterValue"], &["range"]); + set(&mut l, "text/animators/#1/properties/characterValue", Value::Scalar(c as u32 as f64)); + } p.comp_mut(cid).unwrap().layers.push(l); let log = ReadLog::new(); let c = EvalCtx { reads: Some(&log), ..ctx(&p, cid, 0.0) }; assert!(text_geom(&c, &p.comp(cid).unwrap().layers[0]).is_some()); log.into_files() }; + let files_of = |family: &str| files_with(family, None); let files = files_of("Reads Test Sans"); assert!(files.is_complete(), "{files:?}"); assert_eq!(files.files().len(), 1, "{files:?}"); @@ -768,5 +774,12 @@ fn text_notes_the_font_files_it_draws_with() { assert!(files.is_complete() && files.is_empty(), "{files:?}"); // A family that isn't installed falls back: installing it would change the text. assert!(!files_of("No Such Family 3184").is_complete()); + // A substituted character the face has is drawn with it: the same one file. + let files = files_with("Reads Test Sans", Some('B')); + assert!(files.is_complete(), "{files:?}"); + assert_eq!(files.get(&font.to_string_lossy()), Some(stamp)); + // One it lacks (Inter has no CJK) is drawn with a fallback face, or none: another installed + // font could take it, so the list can't vouch for the text. + assert!(!files_with("Reads Test Sans", Some('\u{4e2d}')).is_complete()); let _ = std::fs::remove_dir_all(&dir); } From 3095b856ee765bc05431d7a4f7e25aceb112a60f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 04:54:38 +0100 Subject: [PATCH 032/324] Render: text lists the font file of a run that draws no glyph; tests clean their temp dirs An empty first paragraph draws no glyph, but in a box its face sets the first baseline that places every later line. The read list took faces only from glyphs, so it could be complete without that file. Note each style run's resolved face as well. The font-reads and confine tests use tempfile::tempdir(): a fresh directory per run, removed on panic too. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 ++ crates/automation/Cargo.toml | 1 + crates/automation/src/confine.rs | 5 +++-- crates/render/Cargo.toml | 3 +++ crates/render/src/text.rs | 7 +++++++ crates/render/src/text/tests.rs | 29 ++++++++++++++++++++++++----- 6 files changed, 40 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b35796cce..f897737db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1468,6 +1468,7 @@ dependencies = [ "effectcraft-script", "image", "serde_json", + "tempfile", "thiserror 2.0.21", ] @@ -1878,6 +1879,7 @@ dependencies = [ "lz4_flex", "rayon", "serde", + "tempfile", "web-time", ] diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 916cc3501..e0caf3218 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -19,3 +19,4 @@ effectcraft-model = { workspace = true } [dev-dependencies] effectcraft-script = { workspace = true } effectcraft-host = { workspace = true } +tempfile = { workspace = true } diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index ebc68900e..55fa8043c 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -646,7 +646,9 @@ mod tests { thread_local! { static NOTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } - let base = std::env::temp_dir().join(format!("ec-confine-3184-{}", std::process::id())); + // (a fresh directory, removed when the test ends, panicking or not) + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path(); let (inside, outside) = (base.join("in"), base.join("elsewhere")); for d in [&inside, &outside] { std::fs::create_dir_all(d).unwrap(); @@ -666,7 +668,6 @@ mod tests { assert!(!shown && !files.is_complete(), "outside the roots: {files:?}"); // The next render on the thread is not affected. assert!(read(&footage(&inside)).1.is_complete()); - let _ = std::fs::remove_dir_all(&base); } #[test] diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index efbd1fc19..cd67e846a 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -26,3 +26,6 @@ rayon = { workspace = true } web-time = { workspace = true } serde = { workspace = true } log = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 4165d150d..efe95023f 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -668,7 +668,14 @@ fn note_layout_fonts(ctx: &EvalCtx, styles: &[effectcraft_keyframe::CharStyle], if resolved.iter().any(|r| r.missing) { log.mark_incomplete(); } + // Each run's face, glyphs or not: an empty paragraph's face sets its line's metrics (in a + // box, the first baseline that places every later line). let mut faces: Vec = Vec::new(); + for r in &resolved { + if !faces.contains(&r.face) { + faces.push(r.face); + } + } for g in &layout.glyphs { if g.id == 0 || resolved.get(g.run).is_none_or(|r| r.face != g.face) { log.mark_incomplete(); diff --git a/crates/render/src/text/tests.rs b/crates/render/src/text/tests.rs index c4e43bb2e..9b52d3098 100644 --- a/crates/render/src/text/tests.rs +++ b/crates/render/src/text/tests.rs @@ -742,10 +742,9 @@ fn text_notes_the_font_files_it_draws_with() { }] } } - let dir = std::env::temp_dir().join(format!("effectcraft-font-reads-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let font = dir.join("reads-test-sans.ttf"); + // (a fresh directory, removed when the test ends, panicking or not) + let dir = tempfile::tempdir().unwrap(); + let font = dir.path().join("reads-test-sans.ttf"); std::fs::write(&font, fonts::INTER_REGULAR).unwrap(); fonts::add_source(&OneFile(font.clone())); let stamp = FileStamp::native(&font.to_string_lossy()).unwrap(); @@ -781,5 +780,25 @@ fn text_notes_the_font_files_it_draws_with() { // One it lacks (Inter has no CJK) is drawn with a fallback face, or none: another installed // font could take it, so the list can't vouch for the text. assert!(!files_with("Reads Test Sans", Some('\u{4e2d}')).is_complete()); - let _ = std::fs::remove_dir_all(&dir); + // An empty first paragraph in the face draws no glyph, but in a box its face sets the first + // baseline that places the lines after it: the file is read all the same. + let (mut p, cid, comp) = setup(200, 80); + let base = TextDoc { + text: "\rHi".into(), + font: fonts::DEFAULT_FAMILY.into(), + style: "Regular".into(), + size: 30.0, + box_size: Some([180.0, 60.0]), + ..Default::default() + }; + let first = effectcraft_keyframe::CharStyle { font: "Reads Test Sans".into(), ..base.base_style() }; + let runs = vec![effectcraft_keyframe::StyleRun { len: 1, style: first }, effectcraft_keyframe::StyleRun { len: 2, style: base.base_style() }]; + let l = text_layer(&mut p, &comp, TextDoc { runs, ..base }); + p.comp_mut(cid).unwrap().layers.push(l); + let log = ReadLog::new(); + let c = EvalCtx { reads: Some(&log), ..ctx(&p, cid, 0.0) }; + assert!(text_geom(&c, &p.comp(cid).unwrap().layers[0]).is_some()); + let files = log.into_files(); + assert!(files.is_complete(), "{files:?}"); + assert_eq!(files.get(&font.to_string_lossy()), Some(stamp), "{files:?}"); } From 037895f4689d980d1d9f4003f7dc70dc58a86960 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 11:18:42 +0100 Subject: [PATCH 033/324] Disk cache: Reload Footage closes the gaps around its drop (#3184) - A reload while the disk cache is off is kept on the session (pending_disk_drops) and applied when the cache is switched on, before anything is read from it. - Each render takes the cache's drop generation before it reads (frame worker; layer cache at the miss). An entry listing a file dropped after that is refused under the queue's lock, so a render that was under way during the reload can't store pixels from before it. Such a frame is shown with an incomplete file list, so persist_missing skips it too. The per-file record is bounded (past it, everything older is refused). - An entry read while its drop was pending is a miss even when the writer ends the sweep between the read and the check (a stale hit found under load): the pending drops and the generation are taken before the entry is read. - Test: a reopened project serves its frame from disk with no source file opened or decoded. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/footage/footage_reload.rs | 12 +- crates/engine/src/lib.rs | 4 + .../engine/src/settings/session_settings.rs | 5 + crates/engine/src/tests/disk_cache.rs | 70 +++++ crates/render/src/cache.rs | 72 ++++- crates/render/src/disk_cache.rs | 259 +++++++++++++++--- crates/ui-egui/src/frames.rs | 32 ++- crates/ui-egui/src/frames/tests.rs | 29 +- docs/architecture.md | 6 +- 9 files changed, 422 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/footage/footage_reload.rs b/crates/engine/src/footage/footage_reload.rs index 2744d0224..e56e16a96 100644 --- a/crates/engine/src/footage/footage_reload.rs +++ b/crates/engine/src/footage/footage_reload.rs @@ -281,10 +281,14 @@ fn reload(s: &mut Session, ids: &[ItemId], undoable: bool) -> crate::Result<(usi apply_reloads(s, updates, undoable)?; forget_media(s, &paths); // An explicit reload also reads files again that kept their size and time (the check on hit - // can't tell those apart): their entries in the disk cache go (#3184). An automatic one - // only follows a changed stamp, which the check catches. - if undoable && let Some(dc) = &s.disk_cache { - dc.drop_files(paths.iter().map(String::as_str)); + // can't tell those apart): their entries in the disk cache go (#3184), when the cache is + // switched on if it is off now. An automatic one only follows a changed stamp, which the + // check catches. + if undoable { + match &s.disk_cache { + Some(dc) => dc.drop_files(paths.iter().map(String::as_str)), + None => s.pending_disk_drops.extend(paths), + } } Ok((n, failed)) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 69d1f9e1b..599aba1b7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -171,6 +171,9 @@ pub struct Session { pub crypto_probe: Arc>, /// The persistent disk cache (Settings ▸ Media & Disk Cache), when enabled. pub disk_cache: Option>, + /// Files File ▸ Reload Footage reloaded while the disk cache was off: their entries are + /// dropped when it is switched on ([`Session::configure_disk_cache`]), before it is used. + pub pending_disk_drops: std::collections::BTreeSet, /// Settings (Preferences). pub prefs: prefs::Prefs, /// Bumped whenever settings change (frontends re-apply theme, labels…). @@ -348,6 +351,7 @@ impl Default for Session { layer_cache: Arc::new(LayerCache::default()), crypto_probe: Default::default(), disk_cache: None, + pending_disk_drops: Default::default(), prefs: prefs::Prefs::default(), prefs_revision: 0, config: None, diff --git a/crates/engine/src/settings/session_settings.rs b/crates/engine/src/settings/session_settings.rs index b479963ed..8ade9f8a3 100644 --- a/crates/engine/src/settings/session_settings.rs +++ b/crates/engine/src/settings/session_settings.rs @@ -158,6 +158,11 @@ impl Session { } }, }; + // Files reloaded while the cache was off: their entries go before anything is read from + // it (until the writer has deleted them they are misses, and no frame is linked). + if !self.pending_disk_drops.is_empty() { + dc.drop_files(std::mem::take(&mut self.pending_disk_drops)); + } self.disk_cache = Some(dc.clone()); // The reserve applies from the start (a new folder's watcher is idle). self.poll_disk_space(); diff --git a/crates/engine/src/tests/disk_cache.rs b/crates/engine/src/tests/disk_cache.rs index fed00e852..4c610dceb 100644 --- a/crates/engine/src/tests/disk_cache.rs +++ b/crates/engine/src/tests/disk_cache.rs @@ -397,3 +397,73 @@ fn reload_footage_drops_the_entries_of_its_files() { assert!(dc.get_frame(2, None).is_some(), "another file's frame stays"); let _ = std::fs::remove_dir_all(&dir); } + +/// Reload Footage while the disk cache is off (#3184): when it is switched on later in the +/// session, the entries made of the reloaded files are dropped before anything is read from it +/// (a file replaced by one with the same size and time would pass the check on hit); entries of +/// other files stay. +#[test] +fn reload_footage_while_the_disk_cache_is_off_drops_its_entries_when_it_is_on() { + use crate::render::disk_cache::{DiskCache, Kind}; + use crate::render::reads::{FileStamp, ReadFile, ReadFiles}; + struct Probe; + impl crate::Importer for Probe { + fn probe(&self, path: &str) -> std::result::Result { + Ok(effectcraft_project::Footage { + path: path.into(), + kind: effectcraft_project::FootageKind::Still, + width: 1, + height: 1, + has_video: true, + ..Default::default() + }) + } + } + let dir = folder("reload-off"); + let src = std::path::Path::new(&dir).join("src"); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() }; + let mut add = |name: &str| { + let p = src.join(name); + std::fs::write(&p, b"aa").unwrap(); + let path = p.to_string_lossy().to_string(); + let f = effectcraft_project::Footage { + path: path.clone(), + kind: effectcraft_project::FootageKind::Still, + width: 1, + height: 1, + has_video: true, + ..Default::default() + }; + let id = s.edit("add", None, |p, _| Ok(p.add_item(name, effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)))).unwrap(); + (id, path) + }; + let (a, a_path) = add("a.png"); + let (_, b_path) = add("b.png"); + // Entries from an earlier session in the cache folder. + let read = |p: &str| -> ReadFiles { [ReadFile::new(p, FileStamp::native(p).unwrap())].into_iter().collect() }; + { + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_frame_now(1, 1, 1, &[1; 4], &read(&a_path)); + dc.put_frame_now(2, 1, 1, &[2; 4], &read(&b_path)); + dc.put_layer_now(3, &effectcraft_effects::Buf { img: effectcraft_raster::Image::new(1, 1), offset: [0.0; 2], scale: 1.0 }, &read(&a_path)); + } + // Other bytes, same size, the old time back; reloaded while the cache is off. + let t = std::fs::metadata(&a_path).unwrap().modified().unwrap(); + std::fs::write(&a_path, b"AA").unwrap(); + std::fs::File::options().append(true).open(&a_path).unwrap().set_modified(t).unwrap(); + assert!(s.disk_cache.is_none()); + s.execute_checked("file.reloadFootage", json!({"item": a.0})).unwrap(); + // Switched on: the reloaded file's entries are misses from the start, and then gone. + s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": &dir, "disk.diskCacheEnabled": true}})).unwrap(); + let dc = s.disk_cache.clone().unwrap(); + assert!(dc.get_frame(1, None).is_none(), "the reloaded file's frame renders again"); + assert!(dc.get_layer(3, None).is_none(), "and its layer buffer"); + dc.flush(); + assert!(!dc.contains(Kind::Frame, 1) && !dc.contains(Kind::Layer, 3)); + assert!(dc.get_frame(2, None).is_some(), "another file's frame stays"); + assert!(s.pending_disk_drops.is_empty(), "applied once"); + drop(dc); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 881d8b2b7..7b0e7fc4e 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -63,8 +63,9 @@ struct Inner { clock: u64, hits: u64, misses: u64, - /// When each recent miss happened (to time the render that follows it). - missed_at: HashMap, + /// When each recent miss happened (to time the render that follows it), with the store's + /// drop generation then ([`LayerStore::drop_generation`]). + missed_at: HashMap, } /// Hit/miss counters and memory use (for perf readouts and tests). @@ -164,13 +165,18 @@ impl LayerCache { } None => { g.misses += 1; - if g.missed_at.len() > 4096 { - g.missed_at.clear(); - } - g.missed_at.insert(key, web_time::Instant::now()); drop(g); + let store = self.persistent(); + // (before the buffer's reads: what it is made of may be dropped meanwhile) + let since = store.as_ref().map_or(0, |s| s.drop_generation()); + if let Ok(mut g) = self.inner.lock() { + if g.missed_at.len() > 4096 { + g.missed_at.clear(); + } + g.missed_at.insert(key, (web_time::Instant::now(), since)); + } // Disk cache: a hit comes back into memory. - let store = self.persistent()?; + let store = store?; let id = self.virtual_id(); let (buf, files) = store.get_layer(layer_disk_key(key), id.as_deref())?; let files = Arc::new(files); @@ -196,11 +202,13 @@ impl LayerCache { } let started = self.inner.lock().ok().and_then(|mut g| g.missed_at.remove(&key)); if let Some(store) = self.persistent() { - let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= store.min_layer_ms() as f64); let id = self.virtual_id(); // (an incomplete list, or a file from memory without its identity: not stored) - if slow && let Some(entry) = EntryFiles::of(&files, id.as_deref()) { - store.put_layer(layer_disk_key(key), &buf, &entry); + if let Some((t, since)) = started + && t.elapsed().as_secs_f64() * 1e3 >= store.min_layer_ms() as f64 + && let Some(entry) = EntryFiles::of(&files, id.as_deref()) + { + store.put_layer(layer_disk_key(key), &buf, &entry, since); } } self.insert_mem(key, buf, files) @@ -282,8 +290,15 @@ pub trait LayerStore: Send + Sync { /// mid-render). An entry whose files changed, or damaged, is a miss and is dropped, so the /// buffer rendered again replaces it. `virtual_id` names files served from memory. fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)>; - /// Keep a buffer that was slow to render, with the source files it was made of. - fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles); + /// Keep a buffer that was slow to render, with the source files it was made of. `since`: the + /// [`LayerStore::drop_generation`] when its render started (a buffer made of a file dropped + /// after that is refused). + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, since: u64); + /// How many times files were dropped from the store (File ▸ Reload Footage, + /// [`crate::disk_cache::DiskCache::drop_files`]); `0` for a store that never drops. + fn drop_generation(&self) -> u64 { + 0 + } /// Buffers faster to render than this (ms) are not stored. fn min_layer_ms(&self) -> u64 { 0 @@ -444,7 +459,7 @@ impl LayerStore for PrefetchStore { Some((buf, files.to_read_files())) } - fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, _since: u64) { let Ok(mut s) = self.st.lock() else { return }; if s.known.insert(key) { s.writes.push((key, crate::disk_cache::layer_entry(buf, files))); @@ -878,7 +893,7 @@ mod shared_insert_tests { assert!(store.get_layer(5, Some(&two)).is_none()); assert!(!store.has(5)); assert_eq!(store.take_misses(), [5]); - store.put_layer(5, &buf(), &EntryFiles::of(&files, Some(&two)).unwrap()); + store.put_layer(5, &buf(), &EntryFiles::of(&files, Some(&two)).unwrap(), 0); assert_eq!(store.take_writes().len(), 1, "written over the changed entry"); // Through the layer cache: a hit reports its files; incomplete lists are not queued. let cache = LayerCache::default(); @@ -898,6 +913,35 @@ mod shared_insert_tests { assert_eq!(written, [layer_disk_key(11)], "only the buffer whose files are all named"); } + /// A layer buffer whose render started before Reload Footage dropped its file (#3184) is + /// not written to the disk cache when it is kept afterwards; one whose render started after + /// the drop is. + #[test] + fn a_buffer_rendered_across_a_drop_is_not_written() { + use crate::disk_cache::{DiskCache, Kind, layer_disk_key}; + use crate::reads::{FileStamp, ReadFile, ReadFiles}; + let dir = std::env::temp_dir().join(format!("effectcraft-layer-drop-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.set_min_layer_ms(0); + let cache = LayerCache::default(); + cache.set_disk(Some(dc.clone())); + let buf = || Arc::new(Buf { img: Image::new(2, 2), offset: [0.0; 2], scale: 1.0 }); + let files = Arc::new([ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(1) })].into_iter().collect::()); + // The miss starts the render; the file is reloaded before the buffer is kept. + assert!(cache.get(1).is_none()); + dc.drop_files(["/a.png"]); + cache.insert(1, buf(), files.clone()); + // A render after the drop. + assert!(cache.get(2).is_none()); + cache.insert(2, buf(), files); + dc.flush(); + assert!(!dc.contains(Kind::Layer, layer_disk_key(1)), "made of the file as it was before the drop"); + assert!(dc.contains(Kind::Layer, layer_disk_key(2))); + drop((cache, dc)); + let _ = std::fs::remove_dir_all(&dir); + } + /// A render that gets another render's buffer gets that buffer's files too (#3184): when a /// file changed between the two reads, its frame lists the file with both identities, so the /// list is incomplete and the frame is not kept on disk with the new identity and the old diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index c6d590010..67fbc4a7c 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -279,6 +279,44 @@ struct Queue { busy: bool, /// Keys of frames queued or being written. pending_frames: std::collections::HashSet, + /// The drops so far (under the queue's lock: a write is queued either before a drop, which + /// then sweeps it, or after it, when this refuses it if it was made from before). + drops: Drops, +} + +/// Files dropped from the cache files beyond this are not remembered one by one: everything made +/// before the drop that forgot them is refused instead. +const MAX_DROPPED_PATHS: usize = 1 << 16; + +/// The [`DiskCache::drop_files`] calls so far: their number (the drop generation) and the last one +/// of each file. An entry made of a file read before that file's last drop (its render started at +/// an earlier generation) holds the pixels from before and is refused. +#[derive(Default)] +struct Drops { + generation: u64, + last: HashMap, u64>, + /// Everything made before this generation is refused (the per-file record was forgotten). + floor: u64, +} + +impl Drops { + fn record(&mut self, paths: &[Arc]) { + self.generation = self.generation.saturating_add(1); + if self.last.len().saturating_add(paths.len()) > MAX_DROPPED_PATHS { + self.last.clear(); + self.floor = self.generation; + return; + } + for p in paths { + self.last.insert(p.clone(), self.generation); + } + } + + /// Whether something made of `paths`, whose reads started at generation `since`, read one of + /// them before it was dropped. + fn stale<'a>(&self, mut paths: impl Iterator>, since: u64) -> bool { + since < self.floor || paths.any(|p| self.last.get(p).is_some_and(|g| *g > since)) + } } impl Queue { @@ -401,6 +439,7 @@ impl DiskCache { jobs: Default::default(), busy: cfg!(not(target_arch = "wasm32")), pending_frames: Default::default(), + drops: Drops::default(), }), Condvar::new(), )), @@ -629,6 +668,9 @@ impl DiskCache { self.misses.fetch_add(1, Ordering::Relaxed); None }; + // (before the file is read: the writer may finish a drop's sweep between the read and the + // check below, and a drop may start meanwhile) + let drops = self.drops_now(); let Some((found, payload)) = self.load(kind, key) else { return miss() }; if found != format { let other_frame_format = kind == Kind::Frame && (found == FORMAT_RGBA8_FILES || found == FORMAT_F16_FILES); @@ -642,7 +684,7 @@ impl DiskCache { return miss(); }; self.file_checks.fetch_add(files.len() as u64, Ordering::Relaxed); - if self.made_of_dropped(&files) || !files.unchanged(virtual_id) { + if self.made_of_dropped(&files, &drops) || !files.unchanged(virtual_id) { self.discard(kind, key); return miss(); } @@ -674,13 +716,19 @@ impl DiskCache { /// Queue a write; `false` when it was dropped (a full queue). fn enqueue(&self, kind: Kind, key: u128, payload: Vec) -> bool { - self.enqueue_format(kind, key, FORMAT_RGBA8, payload) + self.enqueue_format(kind, key, FORMAT_RGBA8, payload, None) } - /// [`DiskCache::enqueue`] with the entry's header format byte. - fn enqueue_format(&self, kind: Kind, key: u128, format: u8, payload: Vec) -> bool { + /// [`DiskCache::enqueue`] with the entry's header format byte. `made`: the source files of a + /// frame or layer entry and the drop generation its reads started at + /// ([`DiskCache::drop_generation`]); refused (`false`) when one of them was dropped since. + fn enqueue_format(&self, kind: Kind, key: u128, format: u8, payload: Vec, made: Option<(&EntryFiles, u64)>) -> bool { + let stale = |q: &Queue| made.is_some_and(|(files, since)| q.drops.stale(files.files().iter().map(|f| &f.path), since)); #[cfg(target_arch = "wasm32")] { + if self.queue.0.lock().is_ok_and(|q| stale(&q)) { + return false; + } self.write_format(kind, key, format, &payload); true } @@ -688,6 +736,9 @@ impl DiskCache { { let (m, cv) = &*self.queue; let Ok(mut q) = m.lock() else { return false }; + if stale(&q) { + return false; + } let full = match kind { Kind::Frame => q.frame_bytes.saturating_add(payload.len()) > FRAME_QUEUE_BYTES, _ => q.jobs.len() >= QUEUE_LIMIT, @@ -770,6 +821,9 @@ impl DiskCache { /// entries that list one of `paths`, after the writes queued before (those are swept too); /// until it is done, an entry made of one of them is a miss. Entries are deleted for good, /// so they don't come back after a restart. Nothing else in the cache is touched. + /// + /// A render that was under way meanwhile may still offer an entry made of one of `paths` as + /// it was before: it is refused, see [`DiskCache::drop_generation`]. pub fn drop_files(&self, paths: impl IntoIterator>>) { let paths: Vec> = paths.into_iter().map(Into::into).collect(); if paths.is_empty() { @@ -782,28 +836,58 @@ impl DiskCache { *n = n.saturating_add(1); } } - #[cfg(not(target_arch = "wasm32"))] - { - let (m, cv) = &*self.queue; - if let Ok(mut q) = m.lock() { - // (never refused for a full queue) - q.jobs.push_back(Job::Drop(paths)); - cv.notify_all(); - return; + #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] + let (m, cv) = &*self.queue; + match m.lock() { + Ok(mut q) => { + q.drops.record(&paths); + #[cfg(not(target_arch = "wasm32"))] + { + // (never refused for a full queue) + q.jobs.push_back(Job::Drop(paths)); + cv.notify_all(); + return; + } } + // (no writer thread to take the job any more) + Err(poisoned) => poisoned.into_inner().drops.record(&paths), } self.sweep(&paths); } + /// The number of [`DiskCache::drop_files`] calls so far. A render takes it before it starts + /// reading and hands it to `put_frame` / `put_layer` with what it made: an entry listing a + /// file dropped after that is refused (the render may have read the file as it was before). + pub fn drop_generation(&self) -> u64 { + self.queue.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).drops.generation + } + + /// Whether one of `files` was dropped after generation `since` ([`DiskCache::drop_generation`]): + /// what a render that started then made of them is from before the drop (shown, never stored). + pub fn dropped_since(&self, files: &ReadFiles, since: u64) -> bool { + self.queue.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).drops.stale(files.files().iter().map(|f| &f.path), since) + } + /// Whether a [`DiskCache::drop_files`] is pending. pub fn is_dropping(&self) -> bool { !self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty() } - /// An entry made of a file being dropped. - fn made_of_dropped(&self, files: &EntryFiles) -> bool { + /// The drop generation and the files being dropped now, taken before an entry is read + /// (see [`DiskCache::made_of_dropped`]). + fn drops_now(&self) -> (u64, Vec>) { + let generation = self.drop_generation(); let d = self.dropping.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - !d.is_empty() && files.files().iter().any(|f| d.contains_key(&f.path)) + (generation, d.keys().cloned().collect()) + } + + /// An entry read after [`DiskCache::drops_now`] gave `drops` that is made of a file whose + /// drop was pending then (its sweep may have ended since, after the entry was read) or that + /// was dropped since. + fn made_of_dropped(&self, files: &EntryFiles, drops: &(u64, Vec>)) -> bool { + let (since, pending) = drops; + let paths = || files.files().iter().map(|f| &f.path); + paths().any(|p| pending.contains(p)) || self.queue.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).drops.stale(paths(), *since) } /// The writer's part of [`DiskCache::drop_files`]: delete the entries made of `paths`, then @@ -864,13 +948,25 @@ impl DiskCache { /// Queue a half-float frame for writing (`width * height * 4` binary16 values) with the /// source files it was made of. `true` when it is on disk or queued; `false` when refused - /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]). - pub fn put_frame_f16(&self, key: u128, width: u32, height: u32, rgba: &[u16], files: &ReadFiles, virtual_id: Option>) -> bool { + /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]; + /// a file dropped after `since`, the [`DiskCache::drop_generation`] the render started at). + #[allow(clippy::too_many_arguments)] + pub fn put_frame_f16( + &self, + key: u128, + width: u32, + height: u32, + rgba: &[u16], + files: &ReadFiles, + virtual_id: Option>, + since: u64, + ) -> bool { if rgba.len() as u64 != width as u64 * height as u64 * 4 { return false; } let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; - self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, with_files(&files, encode_frame_f16(width, height, rgba))) + let payload = with_files(&files, encode_frame_f16(width, height, rgba)); + self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, payload, Some((&files, since))) } /// Write a half-float frame synchronously (tests); a list that can't be stored is not. @@ -882,13 +978,16 @@ impl DiskCache { /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes) with the /// source files it was made of. `true` when it is on disk or queued; `false` when refused - /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]). - pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>) -> bool { + /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]; + /// a file dropped after `since`, the [`DiskCache::drop_generation`] the render started at). + #[allow(clippy::too_many_arguments)] + pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>, since: u64) -> bool { if rgba.len() as u64 != width as u64 * height as u64 * 4 { return false; } let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; - self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, with_files(&files, encode_frame(width, height, rgba))) + let payload = with_files(&files, encode_frame(width, height, rgba)); + self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, payload, Some((&files, since))) } /// A layer buffer (key: [`layer_disk_key`]) whose source files are unchanged, with those @@ -900,12 +999,14 @@ impl DiskCache { } /// Queue a layer buffer for writing with the source files it was made of (see - /// [`EntryFiles::of`]: a buffer whose files can't all be named must not be stored). - pub fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { + /// [`EntryFiles::of`]: a buffer whose files can't all be named must not be stored). Refused + /// when one of them was dropped after `since`, the [`DiskCache::drop_generation`] its render + /// started at. + pub fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, since: u64) { if self.contains(Kind::Layer, key) { return; } - let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, with_files(files, encode_layer(buf))); + let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, with_files(files, encode_layer(buf)), Some((files, since))); } /// Write a layer buffer synchronously (tests); a list that can't be stored is not. @@ -1110,8 +1211,11 @@ impl crate::cache::LayerStore for DiskCache { fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { DiskCache::get_layer(self, key, virtual_id).map(|(b, f)| (Arc::new(b), f)) } - fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { - DiskCache::put_layer(self, key, buf, files); + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, since: u64) { + DiskCache::put_layer(self, key, buf, files, since); + } + fn drop_generation(&self) -> u64 { + DiskCache::drop_generation(self) } fn min_layer_ms(&self) -> u64 { DiskCache::min_layer_ms(self) @@ -1470,7 +1574,7 @@ mod tests { assert!(dc.get_frame_f16(3, None).map(|f| f.0).is_none()); assert!(!dc.contains(Kind::Frame, 3) && !p.exists()); // Wrong lengths are not written. - dc.put_frame_f16(4, w, h, &rgba[1..], &ReadFiles::default(), None); + dc.put_frame_f16(4, w, h, &rgba[1..], &ReadFiles::default(), None, 0); dc.flush(); assert!(!dc.contains(Kind::Frame, 4)); let _ = std::fs::remove_dir_all(&dir); @@ -1514,15 +1618,15 @@ mod tests { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); assert!(dc.get_layer(42, None).is_none()); let b = buf(1, 33, 17); - dc.put_layer(42, &b, &EntryFiles::default()); + dc.put_layer(42, &b, &EntryFiles::default(), 0); dc.flush(); let (back, files) = dc.get_layer(42, None).unwrap(); assert!(files.is_empty() && files.is_complete()); assert_eq!(back.img, b.img); assert_eq!((back.offset, back.scale), (b.offset, b.scale)); let rgba: Vec = (0..20 * 10 * 4).map(|i| (i % 251) as u8).collect(); - assert!(dc.put_frame(7, 20, 10, &rgba, &ReadFiles::default(), None)); - assert!(!dc.put_frame(8, 2, 2, &[0; 3], &ReadFiles::default(), None), "a wrong-size frame is refused"); + assert!(dc.put_frame(7, 20, 10, &rgba, &ReadFiles::default(), None, 0)); + assert!(!dc.put_frame(8, 2, 2, &[0; 3], &ReadFiles::default(), None, 0), "a wrong-size frame is refused"); dc.flush(); assert_eq!(dc.get_frame(7, None).map(|f| f.0).unwrap().rgba, rgba); let st = dc.stats(); @@ -1566,11 +1670,11 @@ mod tests { let dir = tmpdir("burst"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); for k in 0..300 { - dc.put_layer(10_000 + k, &buf(1, 64, 64), &EntryFiles::default()); + dc.put_layer(10_000 + k, &buf(1, 64, 64), &EntryFiles::default(), 0); } let rgba = vec![7u8; 32 * 32 * 4]; for k in 0..300 { - dc.put_frame(k, 32, 32, &rgba, &ReadFiles::default(), None); + dc.put_frame(k, 32, 32, &rgba, &ReadFiles::default(), None, 0); } dc.flush(); assert!((0..300).all(|k| dc.contains(Kind::Frame, k)), "every frame written"); @@ -1783,17 +1887,17 @@ mod tests { let dc = DiskCache::open(tmpdir("virtual"), 1 << 30).unwrap(); let k = frame_key(comp_content_key(&p, cid), 0, 1000, 0); let files: ReadFiles = [crate::reads::ReadFile::new("/virtual.mov", crate::reads::FileStamp::Virtual)].into_iter().collect(); - assert!(dc.put_frame(k, 1, 1, &[1, 2, 3, 4], &files, Some(&one))); + assert!(dc.put_frame(k, 1, 1, &[1, 2, 3, 4], &files, Some(&one), 0)); dc.flush(); assert!(dc.get_frame(k, Some(&one)).is_some_and(|(_, f)| f == files)); assert!(dc.get_frame(k, Some(&two)).is_none() && !dc.contains(Kind::Frame, k), "replaced: a miss, deleted"); // A layer buffer made of it. let lk = layer_disk_key(7); - dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap()); + dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap(), 0); dc.flush(); assert!(dc.get_layer(lk, Some(&one)).is_some_and(|(b, f)| b.img == buf(1, 4, 4).img && f == files && f.is_complete())); assert!(dc.get_layer(lk, None).is_none() && !dc.contains(Kind::Layer, lk), "no identity: a miss, deleted"); - dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap()); + dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap(), 0); dc.flush(); assert!(dc.get_layer(lk, Some(&two)).is_none() && !dc.contains(Kind::Layer, lk), "replaced: a miss, deleted"); // The browser's sealed layer entries carry the same list. @@ -1957,7 +2061,7 @@ mod tests { // Frames whose files can't all be named are not stored. let mut incomplete = read(&[&fresh]); incomplete.mark_incomplete(); - assert!(!dc.put_frame(8, 1, 1, &[8; 4], &incomplete, None)); + assert!(!dc.put_frame(8, 1, 1, &[8; 4], &incomplete, None, 0)); dc.flush(); assert!(!dc.contains(Kind::Frame, 8)); let _ = std::fs::remove_dir_all(&dir); @@ -1992,7 +2096,7 @@ mod tests { std::fs::File::options().append(true).open(&a).unwrap().set_modified(t).unwrap(); assert!(dc.get_frame(1, None).is_some(), "same size and time: still a hit"); // A frame queued (not written yet) when the drop comes is dropped too. - assert!(dc.put_frame(5, 1, 1, &[5; 4], &read(&[&a]), None)); + assert!(dc.put_frame(5, 1, 1, &[5; 4], &read(&[&a]), None, 0)); dc.drop_files([a.clone()]); dc.flush(); assert!(!dc.is_dropping()); @@ -2012,6 +2116,64 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A render under way when Reload Footage drops its files offers its entries after the drop + /// (#3184), when the writer has already deleted the old ones: made of the files as they were, + /// they are refused, frames and layer buffers alike. What the same render made of other files + /// is stored, and so is what a render that started after the drop makes. + #[test] + fn entries_made_before_a_drop_are_refused_after_it() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop-in-flight"); + std::fs::create_dir_all(&dir).unwrap(); + let file = |name: &str| { + let p = dir.join(name); + std::fs::write(&p, name.as_bytes()).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png"), file("b.png")); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap())).collect() }; + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + // The render starts (and reads a.png and b.png), then a.png is reloaded. + let before = dc.drop_generation(); + dc.drop_files([a.clone()]); + dc.flush(); + assert!(!dc.is_dropping()); + assert!(dc.dropped_since(&read(&[&a]), before) && !dc.dropped_since(&read(&[&b]), before)); + assert!(!dc.put_frame(1, 1, 1, &[1; 4], &read(&[&a, &b]), None, before), "a frame from before the drop"); + assert!(!dc.put_frame_f16(2, 1, 1, &[1; 4], &read(&[&a]), None, before)); + dc.put_layer(3, &buf(3, 2, 2), &EntryFiles::of(&read(&[&a]), None).unwrap(), before); + assert!(dc.put_frame(4, 1, 1, &[4; 4], &read(&[&b]), None, before), "b.png wasn't dropped"); + dc.flush(); + assert!(!dc.contains(Kind::Frame, 1) && !dc.contains(Kind::Frame, 2) && !dc.contains(Kind::Layer, 3)); + assert!(dc.get_frame(1, None).is_none() && dc.get_layer(3, None).is_none()); + assert_eq!(dc.get_frame(4, None).map(|f| f.0.rgba), Some(vec![4; 4])); + // A render that starts after the drop reads the reloaded file: stored and served. + let after = dc.drop_generation(); + assert!(after > before && !dc.dropped_since(&read(&[&a]), after)); + assert!(dc.put_frame(5, 1, 1, &[5; 4], &read(&[&a]), None, after)); + dc.put_layer(6, &buf(6, 2, 2), &EntryFiles::of(&read(&[&a]), None).unwrap(), after); + dc.flush(); + assert_eq!(dc.get_frame(5, None).map(|f| f.0.rgba), Some(vec![5; 4])); + assert!(dc.get_layer(6, None).is_some()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The record of dropped files is bounded: past it, everything made before the drop that + /// forgot the record is refused, and what is made after it is stored. + #[test] + fn the_record_of_dropped_files_is_bounded() { + let mut d = Drops::default(); + let a: Arc = "/a.png".into(); + d.record(std::slice::from_ref(&a)); + assert!(d.stale([&a].into_iter(), 0) && !d.stale([&a].into_iter(), 1)); + let many: Vec> = (0..=MAX_DROPPED_PATHS).map(|i| format!("/f{i}").into()).collect(); + d.record(&many); + assert!(d.last.is_empty(), "forgotten, not grown"); + let other: Arc = "/other.png".into(); + assert!(d.stale([&other].into_iter(), 1), "made before the drop that forgot the record"); + assert!(!d.stale([&a].into_iter(), 2), "made after it"); + } + /// While a drop waits, an entry made of a dropped file is a miss (and deleted), and frames /// aren't linked to new keys. #[test] @@ -2030,4 +2192,27 @@ mod tests { assert!(dc.get_frame(1, None).is_none() && !dc.contains(Kind::Frame, 1)); let _ = std::fs::remove_dir_all(&dir); } + + /// An entry read while its file's drop was pending is a miss even when the writer ends the + /// sweep between the read and the check (it deleted the file, but its bytes were read), and + /// so is one read before a drop that starts meanwhile. Found under load: a stale hit. + #[test] + fn a_sweep_ending_during_a_read_never_makes_a_hit() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("drop-race"); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + let files = EntryFiles::of(&[ReadFile::new("/a.png", FileStamp::Missing)].into_iter().collect(), None).unwrap(); + // Read while the drop is pending; the sweep ends before the check. + dc.dropping.lock().unwrap().insert("/a.png".into(), 1); + let drops = dc.drops_now(); + dc.dropping.lock().unwrap().clear(); + assert!(dc.made_of_dropped(&files, &drops)); + // Read before a drop that starts (and ends) before the check. + let drops = dc.drops_now(); + dc.drop_files(["/a.png"]); + dc.flush(); + assert!(dc.made_of_dropped(&files, &drops)); + assert!(!dc.made_of_dropped(&files, &dc.drops_now()), "read after the drop: used"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index faacd9b23..3595026ee 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -450,17 +450,18 @@ fn frame_disk_key(keys: &ContentKeys, project: &Project, key: &FrameKey, opts_ha /// Queue `img` for the disk cache under `dk` with the source files it was made of. `false` when /// refused: a GPU frame (no CPU pixels), files that can't be checked when the entry is read -/// (an incomplete list, #3184: the frame is shown, not stored), a full queue. -fn put_disk_frame(dc: &DiskCache, dk: u128, img: &FrameImage, files: &ReadFiles, virtual_id: Option>) -> bool { +/// (an incomplete list, #3184: the frame is shown, not stored), a full queue, a file dropped +/// (File ▸ Reload Footage) after `since`, the drop generation its render started at. +fn put_disk_frame(dc: &DiskCache, dk: u128, img: &FrameImage, files: &ReadFiles, virtual_id: Option>, since: u64) -> bool { if !files.is_complete() { return false; } match img { FrameImage::Cpu(img) => { let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_array()).collect(); - dc.put_frame(dk, img.size[0] as u32, img.size[1] as u32, &rgba, files, virtual_id) + dc.put_frame(dk, img.size[0] as u32, img.size[1] as u32, &rgba, files, virtual_id, since) } - FrameImage::CpuF16(f) => dc.put_frame_f16(dk, f.width, f.height, f.bits(), files, virtual_id), + FrameImage::CpuF16(f) => dc.put_frame_f16(dk, f.width, f.height, f.bits(), files, virtual_id, since), FrameImage::Gpu(_) => false, } } @@ -1065,10 +1066,12 @@ impl Frames { } let (persisted, written, virtual_id) = (self.persisted.clone(), self.written.clone(), self.virtual_id.clone()); let work = move || { + // (a frame made of a file dropped while it rendered kept an incomplete list: not here) + let since = dc.drop_generation(); for (dk, img, files) in missing { // (accepted: the disk cache tracks it until written, and it counts as a try; // refused by a full queue: retried, without counting) - let accepted = put_disk_frame(&dc, dk, &img, &files, virtual_id.as_deref()); + let accepted = put_disk_frame(&dc, dk, &img, &files, virtual_id.as_deref(), since); if accepted && let Ok(mut w) = written.lock() { let n = w.1.entry(dk).or_default(); *n = n.saturating_add(1); @@ -1609,8 +1612,11 @@ impl Worker { job }; let t0 = web_time::Instant::now(); - let disk = job.src.disk.as_ref().map(|dc| (dc.clone(), frame_disk_key(content_keys, &job.src.project, &job.key, opts_hash(&job.opts)))); - let from_disk = disk.as_ref().and_then(|(dc, k)| self.disk_frame(dc, *k, &job)); + // (the drop generation before the frame reads anything: File ▸ Reload Footage meanwhile + // makes what it read from a reloaded file stale) + let disk = + job.src.disk.as_ref().map(|dc| (dc.clone(), frame_disk_key(content_keys, &job.src.project, &job.key, opts_hash(&job.opts)), dc.drop_generation())); + let from_disk = disk.as_ref().and_then(|(dc, k, _)| self.disk_frame(dc, *k, &job)); let disk_hit = from_disk.is_some(); // `files`: the source files the frame was made of (see `render::reads`). let (ci, files) = match from_disk { @@ -1625,13 +1631,21 @@ impl Worker { } }, }; + let mut files = files; + if let Some((dc, _, since)) = &disk + && dc.dropped_since(&files, *since) + { + // Made of a file as it was before File ▸ Reload Footage dropped it: shown, but its + // list can't vouch for it, so neither this worker nor `persist_missing` stores it. + files.mark_incomplete(); + } let files = Arc::new(files); // Publish the shared frame and wake the viewer before optional RGBA conversion // and compression. Persistence still runs on this worker, using the same snapshot. self.finish(&job, ci.clone(), Some(files.clone()), t0); if !disk_hit - && let Some((dc, k)) = &disk - && put_disk_frame(dc, *k, &ci, &files, self.virtual_id.as_deref()) + && let Some((dc, k, since)) = &disk + && put_disk_frame(dc, *k, &ci, &files, self.virtual_id.as_deref(), *since) && let Some(ctx) = &self.ctx { ctx.request_repaint(); diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index 2644095f4..959d14de2 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -2582,6 +2582,8 @@ mod frame_files { src: RenderSource, disk: Arc, hook_calls: Arc, + /// The session's media pool (`src.footage`): what it decoded and opened. + pool: Arc, } fn session(p: &Arc, dir: &Path) -> Session { @@ -2593,16 +2595,17 @@ mod frame_files { calls.fetch_add(1, Ordering::Relaxed); None })); + let pool = Arc::new(effectcraft_media::MediaPool::new()); let src = RenderSource { project: p.clone(), - footage: Arc::new(effectcraft_media::MediaPool::new()), + footage: pool.clone(), expr: None, layer_cache: Arc::default(), gpu: None, gpu_display: false, disk: Some(disk.clone()), }; - Session { frames, src, disk, hook_calls } + Session { frames, src, disk, hook_calls, pool } } impl Session { @@ -2696,6 +2699,28 @@ mod frame_files { let _ = std::fs::remove_dir_all(&dir); } + /// Reopened (a new preview cache, media pool, layer cache and disk cache on the same folder): + /// the frame comes from disk, its one source file is checked (a `metadata` call), and no + /// source file is opened or decoded for it. + #[test] + fn a_reopened_project_serves_its_frame_from_disk_without_opening_a_source_file() { + let dir = folder("reopen"); + let (p, cid, _) = project(&dir); + let first = session(&p, &dir); + let shown = first.show(cid, &[1]); + assert!(close(shown[0], level(1)), "{shown:?}"); + assert!(first.pool.stats().misses > 0, "the first session decodes the frame's file: {:?}", first.pool.stats()); + assert!(first.disk.contains(disk_cache::Kind::Frame, first.disk_key(cid, 1))); + drop(first); + let again = session(&p, &dir); + let shown = again.show(cid, &[1]); + assert!(close(shown[0], level(1)), "{shown:?}"); + assert_eq!(again.hits(), (1, 0), "served from disk"); + assert_eq!(again.disk.file_checks(), 1, "its one file checked"); + assert_eq!(again.pool.stats(), effectcraft_media::PoolStats::default(), "no source file opened or decoded"); + let _ = std::fs::remove_dir_all(&dir); + } + /// No scan: opening a comp of a project that also holds a large sequence, and showing a /// frame, looks only at the files that frame reads; the comp's key looks at no file (it /// stays the same when its files change, and never asks for the identity of a path). diff --git a/docs/architecture.md b/docs/architecture.md index 90573a1c9..83c03f14f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -263,7 +263,11 @@ checksummed) and survive restarts. The design (#3184): source that doesn't say what it read, more than 4096 files) is shown but never written. - **Reload Footage drops entries.** File ▸ Reload Footage deletes the frame and layer entries whose lists name the item's files (the writer thread reads each entry's list, not its - pixels), so a file replaced by one with the same size and time is read again. + pixels), so a file replaced by one with the same size and time is read again. A reload while + the cache is off is remembered for the session and applied when it is switched on, before it + is read. A render already under way offers entries made of the files as they were: each + render takes the cache's drop generation before it reads, and an entry listing a file dropped + after that is refused (`DiskCache::drop_generation`); the frame is shown, never stored. - **Edits keep what they can't change.** RAM frames outside an edit's dirty spans are kept (`Project::dirty_spans`), and their disk entries are linked to the comp's new key. From ac34105a57d737088a4254aafb205b4e111acd4c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 11:42:56 +0100 Subject: [PATCH 034/324] Disk cache: RAM frames keep the drop generation their render started at Reload Footage empties the RAM preview, but an idle pass of persist_missing may already hold a frame from before the reload. It took the cache's drop generation when it ran, after the drop, so the old pixels could be written back and, with the file's size and time unchanged, served again after a restart. Each RAM frame now keeps the disk cache its render started with and that cache's drop generation then. persist_missing writes a frame only to that cache, with that generation, and skips it once one of its files was dropped since; a frame rendered without that cache is not written from there. Tests use tempfile directories (the layer drop test, the frame_files folders under target/). Co-Authored-By: Claude Opus 5.5 --- crates/render/src/cache.rs | 6 +- crates/ui-egui/src/frames.rs | 57 ++++++++---- crates/ui-egui/src/frames/tests.rs | 135 +++++++++++++++++++++-------- 3 files changed, 143 insertions(+), 55 deletions(-) diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 7b0e7fc4e..692a80576 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -920,9 +920,8 @@ mod shared_insert_tests { fn a_buffer_rendered_across_a_drop_is_not_written() { use crate::disk_cache::{DiskCache, Kind, layer_disk_key}; use crate::reads::{FileStamp, ReadFile, ReadFiles}; - let dir = std::env::temp_dir().join(format!("effectcraft-layer-drop-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let dc = DiskCache::open(dir.path(), 1 << 30).unwrap(); dc.set_min_layer_ms(0); let cache = LayerCache::default(); cache.set_disk(Some(dc.clone())); @@ -939,7 +938,6 @@ mod shared_insert_tests { assert!(!dc.contains(Kind::Layer, layer_disk_key(1)), "made of the file as it was before the drop"); assert!(dc.contains(Kind::Layer, layer_disk_key(2))); drop((cache, dc)); - let _ = std::fs::remove_dir_all(&dir); } /// A render that gets another render's buffer gets that buffer's files too (#3184): when a diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index 3595026ee..14c3f32ef 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -168,6 +168,28 @@ struct Cached { /// (the browser's frames are stored by its frame workers, not from here) #[cfg_attr(target_arch = "wasm32", allow(dead_code))] files: Option>, + /// The disk cache its render started with and that cache's drop generation then: the frame + /// is written to that cache only, and only while none of its files was dropped since + /// (`None`: rendered without a disk cache, or elsewhere; never written from here). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + since: Option, +} + +/// A disk cache and its drop generation ([`DiskCache::drop_generation`]) when a render started. +#[derive(Clone)] +struct DiskSince(std::sync::Weak, u64); + +impl DiskSince { + fn of(dc: &Arc, generation: u64) -> DiskSince { + DiskSince(Arc::downgrade(dc), generation) + } + + /// The generation, when `dc` is the cache it was taken from (the weak reference keeps that + /// cache's address from being reused by another). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + fn for_cache(&self, dc: &Arc) -> Option { + std::ptr::eq(self.0.as_ptr(), Arc::as_ptr(dc)).then_some(self.1) + } } struct Cache { @@ -191,12 +213,13 @@ impl Cache { /// A frame without its source files (tests). #[cfg(test)] fn insert(&mut self, k: FrameKey, img: FrameImage) { - self.insert_with(k, img, None); + self.insert_with(k, img, None, None); } - /// [`Cache::insert`] with the source files the frame was made of. - fn insert_with(&mut self, k: FrameKey, img: FrameImage, files: Option>) { + /// [`Cache::insert`] with the source files the frame was made of and the disk cache's drop + /// generation when its render started. + fn insert_with(&mut self, k: FrameKey, img: FrameImage, files: Option>, since: Option) { let (sz, gpu) = (img.bytes(), img.is_gpu()); - if let Some(old) = self.map.insert(k, Cached { img, files }) { + if let Some(old) = self.map.insert(k, Cached { img, files, since }) { self.forget(&old.img); } else { self.order.push_back(k); @@ -1036,7 +1059,7 @@ impl Frames { self.request_content_key(src.project.clone(), base.revision, base.comp); return true; }; - let (missing, converting): (Vec<(u128, FrameImage, Arc)>, bool) = { + let (missing, converting): (Vec<(u128, FrameImage, Arc, u64)>, bool) = { let (Ok(c), Ok(mut queued), Ok(mut written)) = (self.cache.lock(), self.persisted.lock(), self.written.lock()) else { return false }; if queued.len() > 100_000 { queued.clear(); @@ -1053,10 +1076,13 @@ impl Frames { // (GPU frames have no CPU pixels to write; a frame that can't name its files // can't be checked when read) let files = c.files.as_ref().filter(|f| f.is_complete() && !c.img.is_gpu())?; + // (only with the generation its render started at, for this cache: a frame + // made of a file Reload Footage dropped since holds the pixels from before) + let since = c.since.as_ref().and_then(|s| s.for_cache(&dc)).filter(|s| !dc.dropped_since(files, *s))?; let dk = disk_cache::frame_key(content, k.frame, k.scale, k.view ^ oh); let tries = written.1.get(&dk).copied().unwrap_or(0); (tries < 2 && !dc.contains(disk_cache::Kind::Frame, dk) && !dc.frame_pending(dk) && queued.insert(dk)) - .then(|| (dk, c.img.clone(), files.clone())) + .then(|| (dk, c.img.clone(), files.clone(), since)) }) .collect(); (missing, !queued.is_empty()) @@ -1066,9 +1092,7 @@ impl Frames { } let (persisted, written, virtual_id) = (self.persisted.clone(), self.written.clone(), self.virtual_id.clone()); let work = move || { - // (a frame made of a file dropped while it rendered kept an incomplete list: not here) - let since = dc.drop_generation(); - for (dk, img, files) in missing { + for (dk, img, files, since) in missing { // (accepted: the disk cache tracks it until written, and it counts as a try; // refused by a full queue: retried, without counting) let accepted = put_disk_frame(&dc, dk, &img, &files, virtual_id.as_deref(), since); @@ -1481,7 +1505,7 @@ impl Frames { // (A frame kept on the GPU is not written to the disk cache: its files are not // needed.) if let Some((img, _files)) = w.render_gpu(&job) { - w.finish(&job, img, None, t0); + w.finish(&job, img, None, None, t0); continue; } } @@ -1504,7 +1528,7 @@ impl Frames { match r { Ok(f) => { let img = egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba); - fw.finish_key(key, urgent, FrameImage::Cpu(Arc::new(img)), None, t0); + fw.finish_key(key, urgent, FrameImage::Cpu(Arc::new(img)), None, None, t0); } Err(e) => { // Not rendered (a stale revision, a lost worker): the viewer asks again. @@ -1642,7 +1666,8 @@ impl Worker { let files = Arc::new(files); // Publish the shared frame and wake the viewer before optional RGBA conversion // and compression. Persistence still runs on this worker, using the same snapshot. - self.finish(&job, ci.clone(), Some(files.clone()), t0); + let since = disk.as_ref().map(|(dc, _, since)| DiskSince::of(dc, *since)); + self.finish(&job, ci.clone(), Some(files.clone()), since, t0); if !disk_hit && let Some((dc, k, since)) = &disk && put_disk_frame(dc, *k, &ci, &files, self.virtual_id.as_deref(), *since) @@ -1672,18 +1697,18 @@ impl Worker { /// Store a finished frame (with the source files it was made of, when known) and release its /// job. - fn finish(&self, job: &Job, img: FrameImage, files: Option>, t0: web_time::Instant) { - self.finish_key(job.key, job.urgent, img, files, t0); + fn finish(&self, job: &Job, img: FrameImage, files: Option>, since: Option, t0: web_time::Instant) { + self.finish_key(job.key, job.urgent, img, files, since, t0); } - fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, files: Option>, t0: web_time::Instant) { + fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, files: Option>, since: Option, t0: web_time::Instant) { if urgent && let Ok(mut l) = self.last.lock() { *l = t0.elapsed().as_secs_f64() * 1000.0; } if let Ok(mut c) = self.cache.lock() && (!img.is_gpu() || !self.gpu_retired.load(Ordering::Acquire)) { - c.insert_with(key, img, files); + c.insert_with(key, img, files, since); } self.release(key, urgent); } diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index 959d14de2..13fda15e8 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -211,7 +211,7 @@ fn retirement_reaches_existing_workers_and_keeps_cpu_frames_and_completion_live( let next = key(1, 1, 0); frames.inflight.lock().unwrap().insert(next); frames.queue.lock().unwrap().running.insert(next); - worker.finish_key(next, false, img(), None, web_time::Instant::now()); + worker.finish_key(next, false, img(), None, None, web_time::Instant::now()); assert!(frames.is_cached(&next), "CPU retry can still publish"); assert_eq!(frames.inflight(), 0); assert!(frames.queue.lock().unwrap().running.is_empty()); @@ -1593,6 +1593,71 @@ fn half_float_ram_frames_missing_on_disk_are_written() { ram_frames_missing_on_disk_are_written_as(true); } +/// A RAM frame whose render started before Reload Footage dropped one of its files (#3184) +/// holds the pixels from before: writing it later to the disk cache (an idle pass after the +/// drop) would bring them back, also after a restart, since the file kept its size and time. It +/// is written only with the drop generation its render started at, for the cache it started +/// with: so it is not written, nor is a frame rendered without that cache. Frames of other files, +/// and frames rendered after the drop, are written. +#[test] +fn ram_frames_from_before_a_drop_are_not_written() { + use effectcraft_engine::Session; + use effectcraft_engine::render::reads::{FileStamp, ReadFile}; + use serde_json::json; + let dir = tempfile::tempdir().unwrap(); + let disk = DiskCache::open(dir.path().join("cache"), 1 << 30).unwrap(); + let other = DiskCache::open(dir.path().join("other"), 1 << 30).unwrap(); + let mut s = Session::default(); + let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 1})).unwrap()["comp"].as_u64().unwrap()); + s.execute("layer.newSolid", json!({})).unwrap(); + let src = RenderSource { + project: s.project.clone(), + footage: Arc::new(effectcraft_engine::render::NoFootage), + expr: None, + layer_cache: Arc::default(), + gpu: None, + gpu_display: false, + disk: Some(disk.clone()), + }; + let f = Frames::default(); + let series = FrameKey { revision: 1, content: f.content_of(&src.project, 1, cid), comp: cid.0, opts: opts_hash(&RenderOpts::default()), ..key(0, 0, 0) }; + let read = |p: &str| Some(Arc::new([ReadFile::new(p, FileStamp::Native { len: 3, modified: Some(1) })].into_iter().collect::())); + let before = DiskSince::of(&disk, disk.drop_generation()); + { + let mut c = f.cache.lock().unwrap(); + c.insert_with(FrameKey { frame: 0, ..series }, img(), read("/a.png"), Some(before.clone())); + c.insert_with(FrameKey { frame: 1, ..series }, img(), read("/b.png"), Some(before)); + c.insert_with(FrameKey { frame: 2, ..series }, img(), read("/a.png"), None); + c.insert_with(FrameKey { frame: 3, ..series }, img(), read("/a.png"), Some(DiskSince::of(&other, other.drop_generation()))); + } + // Reload Footage of a.png. + disk.drop_files(["/a.png"]); + disk.flush(); + f.cache.lock().unwrap().insert_with(FrameKey { frame: 4, ..series }, img(), read("/a.png"), Some(DiskSince::of(&disk, disk.drop_generation()))); + let on_disk = |fr: i64| { + disk.contains( + disk_cache::Kind::Frame, + frame_disk_key(&f.content_keys, &src.project, &FrameKey { frame: fr, ..series }, opts_hash(&RenderOpts::default())), + ) + }; + // Idle passes until there is nothing left to write. + let mut done = false; + for _ in 0..1000 { + let more = f.persist_missing(&src, &series, &RenderOpts::default()); + disk.flush(); + if !more && f.persisted.lock().unwrap().is_empty() { + done = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(done, "the idle passes end"); + assert!(on_disk(1) && on_disk(4), "another file's frame, and a frame rendered after the drop"); + assert!(!on_disk(0), "made of a.png as it was before the drop"); + assert!(!on_disk(2) && !on_disk(3), "rendered without this disk cache"); + assert_eq!(disk.stats().entries, 2); +} + fn ram_frames_missing_on_disk_are_written_as(half: bool) { use effectcraft_engine::Session; use serde_json::json; @@ -1616,7 +1681,7 @@ fn ram_frames_missing_on_disk_are_written_as(half: bool) { FrameKey { revision: 1, content: f.content_of(&src.project, 1, cid), comp: cid.0, opts: opts_hash(&RenderOpts::default()) ^ 1, ..key(0, 0, 0) }; for fr in 0..10 { let frame = if half { FrameImage::CpuF16(Arc::new(F16Frame::from_image(&effectcraft_engine::render::Image::new(8, 8), SRGB))) } else { img() }; - f.cache.lock().unwrap().insert_with(FrameKey { frame: fr, ..series }, frame, Some(Arc::default())); + f.cache.lock().unwrap().insert_with(FrameKey { frame: fr, ..series }, frame, Some(Arc::default()), Some(DiskSince::of(&disk, disk.drop_generation()))); } let on_disk = |fr: i64| { disk.contains( @@ -2529,12 +2594,12 @@ mod frame_files { const RATE: FrameRate = FrameRate::FPS_30; const FRAMES: i64 = 5; - /// A fresh folder for test `name` (on the build drive, not the system temp folder). - fn folder(name: &str) -> PathBuf { - let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("../../target/test-frame-files-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir + /// A fresh folder for test `name` (on the build drive, not the system temp folder), deleted + /// when the guard is dropped. + fn folder(name: &str) -> tempfile::TempDir { + let target = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target"); + std::fs::create_dir_all(&target).unwrap(); + tempfile::Builder::new().prefix(&format!("test-frame-files-{name}-")).tempdir_in(target).unwrap() } /// A flat grey PNG of `level` at `path`. @@ -2671,10 +2736,11 @@ mod frame_files { /// others come from disk, also after reopening. #[test] fn a_changed_source_file_re_renders_exactly_its_frames() { - let dir = folder("correct"); - let (p, cid, files) = project(&dir); + let tmp = folder("correct"); + let dir = tmp.path(); + let (p, cid, files) = project(dir); let all: Vec = (0..FRAMES).collect(); - let first = session(&p, &dir); + let first = session(&p, dir); let shown = first.show(cid, &all); assert!(all.iter().all(|f| close(shown[*f as usize], level(*f))), "{shown:?}"); assert_eq!(first.hits(), (0, FRAMES as u64), "rendered, nothing on disk yet"); @@ -2683,7 +2749,7 @@ mod frame_files { // Frame 2's file gets new pixels (and size), frame 3's only a new time. png(Path::new(&files[2]), 250); touch(&files[3], 30); - let second = session(&p, &dir); + let second = session(&p, dir); let shown = second.show(cid, &all); assert!(close(shown[2], 250), "frame 2 shows its new file: {shown:?}"); assert!([0, 1, 3, 4].iter().all(|f| close(shown[*f as usize], level(*f))), "{shown:?}"); @@ -2692,11 +2758,10 @@ mod frame_files { assert_eq!(second.disk.stats().entries, FRAMES as usize, "the entries of 2 and 3 were replaced"); drop(second); // Reopened: every frame from disk, the replaced ones with their new pixels. - let third = session(&p, &dir); + let third = session(&p, dir); let shown = third.show(cid, &all); assert_eq!(third.hits(), (FRAMES as u64, 0)); assert!(close(shown[2], 250) && close(shown[3], level(3)), "{shown:?}"); - let _ = std::fs::remove_dir_all(&dir); } /// Reopened (a new preview cache, media pool, layer cache and disk cache on the same folder): @@ -2704,21 +2769,21 @@ mod frame_files { /// source file is opened or decoded for it. #[test] fn a_reopened_project_serves_its_frame_from_disk_without_opening_a_source_file() { - let dir = folder("reopen"); - let (p, cid, _) = project(&dir); - let first = session(&p, &dir); + let tmp = folder("reopen"); + let dir = tmp.path(); + let (p, cid, _) = project(dir); + let first = session(&p, dir); let shown = first.show(cid, &[1]); assert!(close(shown[0], level(1)), "{shown:?}"); assert!(first.pool.stats().misses > 0, "the first session decodes the frame's file: {:?}", first.pool.stats()); assert!(first.disk.contains(disk_cache::Kind::Frame, first.disk_key(cid, 1))); drop(first); - let again = session(&p, &dir); + let again = session(&p, dir); let shown = again.show(cid, &[1]); assert!(close(shown[0], level(1)), "{shown:?}"); assert_eq!(again.hits(), (1, 0), "served from disk"); assert_eq!(again.disk.file_checks(), 1, "its one file checked"); assert_eq!(again.pool.stats(), effectcraft_media::PoolStats::default(), "no source file opened or decoded"); - let _ = std::fs::remove_dir_all(&dir); } /// No scan: opening a comp of a project that also holds a large sequence, and showing a @@ -2726,16 +2791,17 @@ mod frame_files { /// stays the same when its files change, and never asks for the identity of a path). #[test] fn showing_a_frame_checks_only_the_files_it_reads() { - let dir = folder("no-scan"); - let (p, cid, files) = project(&dir); + let tmp = folder("no-scan"); + let dir = tmp.path(); + let (p, cid, files) = project(dir); let key = disk_cache::comp_content_key(&p, cid); png(Path::new(&files[1]), 99); touch(&files[2], 5); assert_eq!(disk_cache::comp_content_key(&p, cid), key, "the key looks at no file"); - let first = session(&p, &dir); + let first = session(&p, dir); first.show(cid, &[2]); drop(first); - let again = session(&p, &dir); + let again = session(&p, dir); // (the indicator's key is computed off the UI thread first) let mut blue = vec![]; for _ in 0..400 { @@ -2752,7 +2818,6 @@ mod frame_files { assert_eq!(again.hits(), (1, 0)); assert_eq!(again.disk.file_checks(), 1, "only the file frame 2 read"); assert_eq!(again.hook_calls.load(Ordering::Relaxed), 0, "no path of the unused sequence was asked about"); - let _ = std::fs::remove_dir_all(&dir); } /// The frame entry files under the cache folder. @@ -2776,22 +2841,23 @@ mod frame_files { /// cache entry never serve the frame from before; each is rendered again and stored anew. #[test] fn missing_or_unreadable_files_and_damaged_entries_never_serve_a_stale_frame() { - let dir = folder("safe"); - let (p, cid, files) = project(&dir); - let first = session(&p, &dir); + let tmp = folder("safe"); + let dir = tmp.path(); + let (p, cid, files) = project(dir); + let first = session(&p, dir); first.show(cid, &[0]); assert_eq!(first.disk.stats().entries, 1); drop(first); // Missing: not served; the frame is rendered without it. std::fs::remove_file(&files[0]).unwrap(); - let missing = session(&p, &dir); + let missing = session(&p, dir); let shown = missing.show(cid, &[0]); assert!(!close(shown[0], level(0)), "the frame from before was served: {shown:?}"); assert_eq!(missing.hits(), (0, 1)); drop(missing); // Back, with other pixels: the entry made while it was missing is not served either. png(Path::new(&files[0]), 180); - let back = session(&p, &dir); + let back = session(&p, dir); let shown = back.show(cid, &[0]); assert!(close(shown[0], 180), "{shown:?}"); assert_eq!(back.hits(), (0, 1)); @@ -2799,30 +2865,29 @@ mod frame_files { // Unreadable (a folder in its place). std::fs::remove_file(&files[0]).unwrap(); std::fs::create_dir(&files[0]).unwrap(); - let unreadable = session(&p, &dir); + let unreadable = session(&p, dir); let shown = unreadable.show(cid, &[0]); assert!(!close(shown[0], 180), "the frame from before was served: {shown:?}"); assert_eq!(unreadable.hits(), (0, 1)); drop(unreadable); std::fs::remove_dir(&files[0]).unwrap(); png(Path::new(&files[0]), 120); - let fresh = session(&p, &dir); + let fresh = session(&p, dir); assert!(close(fresh.show(cid, &[0])[0], 120)); drop(fresh); // A damaged entry: a miss, rendered, stored again, then served. - let found = entries(&dir); + let found = entries(dir); assert_eq!(found.len(), 1, "{found:?}"); let mut bytes = std::fs::read(&found[0]).unwrap(); let n = bytes.len() / 2; bytes[n] ^= 0x5a; std::fs::write(&found[0], bytes).unwrap(); - let damaged = session(&p, &dir); + let damaged = session(&p, dir); assert!(close(damaged.show(cid, &[0])[0], 120)); assert_eq!(damaged.hits(), (0, 1)); drop(damaged); - let healed = session(&p, &dir); + let healed = session(&p, dir); assert!(close(healed.show(cid, &[0])[0], 120)); assert_eq!(healed.hits(), (1, 0), "the rewritten entry is used"); - let _ = std::fs::remove_dir_all(&dir); } } From 26dc7b3a5e6a40e13c83665dffaf5fc41aedf7bf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 12:40:04 +0100 Subject: [PATCH 035/324] CC Ball Action: add Coloring, Shading, Scatter Motion, Displace and Displace Property (#3197) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After Effects 24.2 reworked CC Ball Action's controls. EffectCraft now lists them in After Effects' order with its defaults: Grid Spacing (5), Ball Size (100), Coloring (Medium), Shading (-75), Scatter, Scatter Motion, Displace, Displace Property (Brightness), Twist Angle, Twist Property, Rotation Axis, Rotation. Grid Spacing and Ball Size used to default to 4 and 40; saved projects keep their values. - Shading scales the balls' light and shine. -75 is the lit sphere as before, 0 draws flat balls in the layer's colour, larger magnitudes shade more, and the sign mirrors the light's direction. The value is clamped to -100..100 (an assumed range) so huge values stay finite on the GPU. Values other than -75 and 0 use a new sprite shape (Shape::Ball), drawn the same way on the CPU and the GPU. - Coloring is an approximation: Crisp takes the nearest pixel, Medium keeps EffectCraft's earlier smooth sample (for compatibility), Smooth averages 16 samples over the ball's cell. - Scatter Motion is treated as the renamed Instability State, since 24.2 shows no Instability State. Old projects are upgraded through PARAM_ID_ALIASES. - Displace and Displace Property (Red, Green, Blue, Brightness, Saturation, RGB, Radius, Diamond, Spherize) move each ball towards or away from the camera. The scale, direction, pivot and range, and what Radius, Diamond and Spherize compute, are EffectCraft's own choice pending a comparison with After Effects. Displace is clamped to -1000..1000. With the old Grid Spacing and Ball Size, every CC Ball Action golden hash is unchanged, so the new controls at their defaults draw what was drawn before. Only the golden cases that use the default Grid Spacing and Ball Size were reblessed. CC Ball Action has no .aep mapping yet. Sources (behaviour and public descriptions only): - After Effects February 2024 (24.2) feature summary: "Ball Action: Rearranged effect controls with new controls, such as Displacement, Shading, and Coloring" https://helpx.adobe.com/ae_en/after-effects/using/whats-new/2024-2.html - The After Effects screenshot in #3197: control order and defaults. - 163.com, "Ae 效果详解:CC Ball Action": option lists, defaults, and that Shading 0 is flat https://www.163.com/dy/article/JOICG6E10536FE6V.html - Adobe community, "CC Ball Action is broken in update 24.4": the Coloring options Crisp, Medium and Smooth - Mike Murphy, "How To Use CC Ball Action": Shading 0 with Displace on Brightness https://mikemurphy.ai/tutorials/ccballaction/ Fixes #3197 --- crates/effects/src/migrate.rs | 3 + crates/effects/src/sim/sprites.rs | 22 ++++ crates/effects/src/sim2/pixels.rs | 118 +++++++++++++++++- crates/effects/src/sim2/registry.rs | 21 +++- crates/effects/src/sim2/tests.rs | 132 +++++++++++++++++++++ crates/effects/tests/it/particle_golden.rs | 42 +++---- crates/gpu/src/fx_sim.rs | 2 + crates/gpu/src/shaders/fx_sim.wgsl | 21 ++++ crates/gpu/src/tests/fx_particles.rs | 17 ++- docs/effects.md | 4 +- 10 files changed, 347 insertions(+), 35 deletions(-) diff --git a/crates/effects/src/migrate.rs b/crates/effects/src/migrate.rs index 59daca49d..6529e658d 100644 --- a/crates/effects/src/migrate.rs +++ b/crates/effects/src/migrate.rs @@ -44,6 +44,9 @@ pub const PARAM_ID_ALIASES: &[(&str, &str, &str)] = &[ ("ec.key.innerouter", "additionalBackground", "additionalBackground/background1"), // Generate: Radio Waves' growth speed was called Velocity; Velocity now moves the wave. ("ec.generate.radiowaves", "velocity", "waveMotion/expansion"), + // Simulation: CC Ball Action's Instability State is treated as the control After Effects + // 24.2 calls Scatter Motion (#3197; an assumption: 24.2 shows no Instability State). + ("ec.sim.ccballaction", "instabilityState", "scatterMotion"), ]; /// Popup option labels renamed since they were first saved: diff --git a/crates/effects/src/sim/sprites.rs b/crates/effects/src/sim/sprites.rs index 55ba594b4..031bee978 100644 --- a/crates/effects/src/sim/sprites.rs +++ b/crates/effects/src/sim/sprites.rs @@ -93,6 +93,10 @@ pub enum Shape { Disc, /// Lit sphere (upper-left light, specular). Sphere, + /// CC Ball Action's ball: [`Shape::Sphere`]'s light and shine scaled by `|shade|` (1 is the + /// sphere's look, 0 a flat disc; callers keep it finite, the GPU draws the same); a negative + /// `shade` mirrors the light's direction (lit from the lower right). + Ball { shade: f32 }, /// Disc fading linearly to its rim. Faded, /// Thin ring with a highlight. @@ -277,6 +281,24 @@ fn sprite_shade(s: &Sprite, x: f32, y: f32) -> Option { rgb = [rgb[0] * k + spec, rgb[1] * k + spec, rgb[2] * k + spec]; cv } + Shape::Ball { shade } => { + let d = (dx * dx + dy * dy).sqrt(); + let cv = aa(r - d); + if cv <= 0.0 { + return None; + } + let (nx, ny) = (dx / r, dy / r); + let nz = (1.0 - nx * nx - ny * ny).max(0.0).sqrt(); + let m = if shade < 0.0 { -1.0 } else { 1.0 }; + let (lx, ly, lz) = (-0.48 * m, -0.58 * m, 0.66); + let diff = (nx * lx + ny * ly + nz * lz).max(0.0); + let rz = 2.0 * diff * nz - lz; + let st = shade.abs(); + let spec = rz.max(0.0).powi(20) * 0.6 * st; + let k = (1.0 - st * 0.8 * (1.0 - diff)).max(0.0); + rgb = [rgb[0] * k + spec, rgb[1] * k + spec, rgb[2] * k + spec]; + cv + } Shape::Bubble => { let d = (dx * dx + dy * dy).sqrt() / r; if d > 1.0 + 1.0 / r { diff --git a/crates/effects/src/sim2/pixels.rs b/crates/effects/src/sim2/pixels.rs index 2cda428db..4fed8da59 100644 --- a/crates/effects/src/sim2/pixels.rs +++ b/crates/effects/src/sim2/pixels.rs @@ -4,10 +4,91 @@ use super::{Acc, Buf, EffectCtx, IntoParallelIterator, ParallelIterator, Post, S // ------------------------------------------------------------------ CC Ball Action +/// CC Ball Action's Coloring: how a ball takes its colour from the layer under its grid cell. +/// An approximation: After Effects' own meaning is not published beyond "how smooth the +/// balls look". Crisp takes the nearest pixel, Medium keeps EffectCraft's earlier smooth +/// sample at the cell centre (for compatibility), Smooth averages 16 samples over the cell. +pub(super) const BALL_COLORING: &[&str] = &["Crisp", "Medium", "Smooth"]; +pub(super) const BALL_COLORING_MEDIUM: u32 = 1; +/// CC Ball Action's default Shading: the lit sphere (`Shape::Sphere`); 0 draws flat discs. +pub(super) const BALL_SHADING_DEFAULT: f64 = -75.0; +/// CC Ball Action's Displace Property: what pushes a ball towards (high values) or away from +/// (low values) the camera. The option names come from public descriptions; what Radius, +/// Diamond and Spherize compute here is an assumption pending a comparison with After Effects. +pub(super) const BALL_DISPLACE_PROPERTIES: &[&str] = &["Red", "Green", "Blue", "Brightness", "Saturation", "RGB", "Radius", "Diamond", "Spherize"]; +pub(super) const BALL_DISPLACE_BRIGHTNESS: u32 = 3; + pub(super) fn ball_action(ctx: &EffectCtx, b: Buf) -> Buf { ball_action_plan(ctx, &b).finish(b) } +/// A parameter's number, or `default` when the instance does not carry it. +fn f_or(ctx: &EffectCtx, id: &str, default: f64) -> f64 { + ctx.params.values.get(id).map(|v| v.as_f64()).unwrap_or(default) +} + +/// The layer's straight colour and alpha for the ball of the grid cell centred on (`sx`, `sy`) +/// (buffer pixels, cell `cell` buffer pixels wide), by Coloring `coloring`. +fn ball_color(src: &effectcraft_raster::Image, sx: f64, sy: f64, cell: f64, coloring: u32) -> ([f32; 3], f32) { + match coloring { + // Crisp: the pixel under the cell centre. + 0 => unpremul(src.get(sx.floor() as i64, sy.floor() as i64)), + // Smooth: the cell's average (4 × 4 samples, premultiplied). + 2 => { + const N: u32 = 4; + let mut acc = [0.0f32; 4]; + for j in 0..N { + for i in 0..N { + let ox = (f64::from(i) + 0.5) / f64::from(N) - 0.5; + let oy = (f64::from(j) + 0.5) / f64::from(N) - 0.5; + let p = src.sample_bilinear(sx + ox * cell, sy + oy * cell); + for (a, v) in acc.iter_mut().zip(p) { + *a += v; + } + } + } + let n = (N * N) as f32; + unpremul([acc[0] / n, acc[1] / n, acc[2] / n, acc[3] / n]) + } + // Medium: a smooth sample at the cell centre. + _ => unpremul(src.sample_bilinear(sx, sy)), + } +} + +/// CC Ball Action's Displace Property `prop` (0..1) for a ball of straight colour `c` at +/// (`gx`, `gy`) on a `lw` × `lh` layer (`maxr`: half its diagonal). Assumed meanings (not +/// compared with After Effects yet): Radius, Diamond and Spherize are shapes that peak at the +/// layer centre. +fn ball_displace_value(prop: u32, c: [f32; 3], gx: f32, gy: f32, lw: f32, lh: f32, maxr: f32) -> f32 { + let (cx, cy) = (lw * 0.5, lh * 0.5); + let v = match prop { + 0 => c[0], + 1 => c[1], + 2 => c[2], + // Brightness: the brightest channel (HSB brightness). + 3 => c[0].max(c[1]).max(c[2]), + // Saturation: HSB saturation. + 4 => { + let mx = c[0].max(c[1]).max(c[2]); + let mn = c[0].min(c[1]).min(c[2]); + if mx > 0.0 { (mx - mn) / mx } else { 0.0 } + } + // RGB: the channels' mean. + 5 => (c[0] + c[1] + c[2]) / 3.0, + // Radius: high at the centre, low at the corners. + 6 => 1.0 - (gx - cx).hypot(gy - cy) / maxr.max(1.0), + // Diamond: high at the centre, falling linearly to the edge midpoints' diamond. + 7 => 1.0 - ((gx - cx).abs() / cx.max(0.5) + (gy - cy).abs() / cy.max(0.5)) * 0.5, + // Spherize: a hemisphere over the largest centred circle. + _ => { + let rr = cx.min(cy).max(0.5); + let d = (gx - cx).hypot(gy - cy) / rr; + (1.0 - d * d).max(0.0).sqrt() + } + }; + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } +} + /// CC Ball Action's balls (far to near), coloured by the layer's pixels. fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan { let pr = ctx.params; @@ -18,7 +99,29 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan { let twist = pr.f("twistAngle").to_radians(); let spacing = pr.f("gridSpacing").max(1.0) as f32; let size = pr.f("ballSize") as f32 / 100.0; - let instab = pr.f("instabilityState").to_radians() as f32; + // Scatter Motion, treated as the renamed Instability State (an assumption: After Effects + // 24.2 shows Scatter Motion and no Instability State): turns each ball's scatter direction. + let instab = pr.f("scatterMotion").to_radians() as f32; + let coloring = pr.values.get("coloring").map(|v| v.as_enum()).unwrap_or(BALL_COLORING_MEDIUM); + let shading = f_or(ctx, "shading", BALL_SHADING_DEFAULT); + // Shading: -75 is the lit sphere as it always was, 0 flat discs; the magnitude scales the + // light and shine (strength 1 at 75) and the sign mirrors the light's direction (positive + // lights the balls from the lower right). How this compares with After Effects' sign + // (described as concave versus convex) is unverified, as is the -100..100 range. + let shape = if shading == BALL_SHADING_DEFAULT || !shading.is_finite() { + Shape::Sphere + } else if shading == 0.0 { + Shape::Disc + } else { + // Clamped: a huge value would reach the GPU as an infinite strength (and NaN colours). + Shape::Ball { shade: (-shading.clamp(-100.0, 100.0) / 75.0) as f32 } + }; + // Displace: pushes each ball along z by its Displace Property (high values towards the + // camera, pivoting at the property's middle value); 100 moves the extremes by half the + // layer's diagonal. Scale, direction, pivot and range are EffectCraft's own choice, + // pending a comparison with After Effects. Clamped so huge values stay finite. + let displace = pr.f("displace").clamp(-1000.0, 1000.0) as f32; + let displace_prop = pr.values.get("displaceProperty").map(|v| v.as_enum()).unwrap_or(BALL_DISPLACE_BRIGHTNESS); let seed = ctx.seed.wrapping_mul(0x2545f491); let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32); let s = b.scale as f32; @@ -43,7 +146,7 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan { let gx = (i % nx) as f32 * spacing + spacing * 0.5; let gy = (i / nx) as f32 * spacing + spacing * 0.5; let (sx, sy) = b.to_px([gx as f64, gy as f64]); - let (c, a) = unpremul(src.sample_bilinear(sx, sy)); + let (c, a) = ball_color(src, sx, sy, f64::from(spacing * s), coloring); if a <= 0.0 || size <= 0.0 { return None; } @@ -54,11 +157,16 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan { _ => crate::util::rgb3([c[0], c[1], c[2], 0.0]).iter().sum::() / 3.0, } as f64; let ang = rot + twist * tp; - // Scatter: random 3D offsets whose direction drifts with the instability state. + // Scatter: random 3D offsets whose direction drifts with Scatter Motion. let ph = h(i, 1, seed) * std::f32::consts::TAU + instab; let sc = scatter * h(i, 2, seed); let off = [(sc * ph.cos()) as f64, (sc * ph.sin()) as f64, (scatter * hs(i, 3, seed)) as f64]; - let p0 = [gx as f64 - cx + off[0], gy as f64 - cy + off[1], off[2]]; + let mut p0 = [gx as f64 - cx + off[0], gy as f64 - cy + off[1], off[2]]; + // Only when set, so Displace 0 leaves every depth (and the far-to-near order) as is. + if displace != 0.0 && displace.is_finite() { + let v = ball_displace_value(displace_prop, c, gx, gy, lw, lh, maxr); + p0[2] -= f64::from(displace / 100.0 * (v - 0.5) * 2.0 * maxr); + } let m = rot_axis(ax, ang); let q: [f64; 3] = std::array::from_fn(|k| m[k][0] * p0[0] + m[k][1] * p0[1] + m[k][2] * p0[2]); if d + q[2] <= d * 0.05 { @@ -67,7 +175,7 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan { let persp = d / (d + q[2]); let (bx, by) = b.to_px([cx + q[0] * persp, cy + q[1] * persp]); let r = spacing * 0.5 * size * persp as f32 * s; - Some((q[2], Sprite::new(bx as f32, by as f32, r, [c[0], c[1], c[2], a], Shape::Sphere))) + Some((q[2], Sprite::new(bx as f32, by as f32, r, [c[0], c[1], c[2], a], shape))) }) .collect(); balls.sort_by(|a, b| b.0.total_cmp(&a.0)); diff --git a/crates/effects/src/sim2/registry.rs b/crates/effects/src/sim2/registry.rs index 333916a16..28eb8e808 100644 --- a/crates/effects/src/sim2/registry.rs +++ b/crates/effects/src/sim2/registry.rs @@ -1,5 +1,7 @@ use super::foam::{FOAM_TEXTURES, foam}; -use super::pixels::{ball_action, pixel_polly, scatterize}; +use super::pixels::{ + BALL_COLORING, BALL_COLORING_MEDIUM, BALL_DISPLACE_BRIGHTNESS, BALL_DISPLACE_PROPERTIES, BALL_SHADING_DEFAULT, ball_action, pixel_polly, scatterize, +}; use super::shatter::{CD_PROPS, CD_SOURCES, SHATTER_PATTERNS, SHATTER_TEXTURE_MODES, card_dance, shatter}; use super::surfaces::{caustics, wave_world}; use super::{EffectSpec, ParamUi, Value, col, num, p, pct, popup, pt, slider, spec}; @@ -80,15 +82,22 @@ pub fn specs() -> Vec { spec( "ec.sim.ccballaction", "CC Ball Action", + // After Effects' order and defaults since 24.2 (#3197). Scatter Motion is treated as + // the renamed Instability State (an assumption, `migrate::PARAM_ID_ALIASES`). The + // Shading range is not published; -100..100 is an assumption. vec![ + p("gridSpacing", "Grid Spacing", num(5.0), slider(1.0, 200.0, 1.0, 50.0, 0)), + p("ballSize", "Ball Size", num(100.0), slider(0.0, 400.0, 0.0, 200.0, 1)), + p("coloring", "Coloring", Value::Enum(BALL_COLORING_MEDIUM), popup(BALL_COLORING)), + p("shading", "Shading", num(BALL_SHADING_DEFAULT), slider(-100.0, 100.0, -100.0, 100.0, 1)), p("scatter", "Scatter", num(0.0), slider(0.0, 2000.0, 0.0, 300.0, 1)), + p("scatterMotion", "Scatter Motion", num(0.0), ParamUi::Angle), + p("displace", "Displace", num(0.0), slider(-1000.0, 1000.0, 0.0, 100.0, 1)), + p("displaceProperty", "Displace Property", Value::Enum(BALL_DISPLACE_BRIGHTNESS), popup(BALL_DISPLACE_PROPERTIES)), + p("twistAngle", "Twist Angle", num(0.0), ParamUi::Angle), + p("twistProperty", "Twist Property", Value::Enum(0), popup(&["X Axis", "Y Axis", "Radius", "Brightness"])), p("rotationAxis", "Rotation Axis", Value::Enum(0), popup(&["X Axis", "Y Axis", "Z Axis", "XY Axis", "XZ Axis", "YZ Axis", "XYZ Axis"])), p("rotation", "Rotation", num(0.0), ParamUi::Angle), - p("twistProperty", "Twist Property", Value::Enum(0), popup(&["X Axis", "Y Axis", "Radius", "Brightness"])), - p("twistAngle", "Twist Angle", num(0.0), ParamUi::Angle), - p("gridSpacing", "Grid Spacing", num(4.0), slider(1.0, 200.0, 1.0, 50.0, 0)), - p("ballSize", "Ball Size", num(40.0), slider(0.0, 400.0, 0.0, 200.0, 1)), - p("instabilityState", "Instability State", num(0.0), ParamUi::Angle), ], ball_action, ), diff --git a/crates/effects/src/sim2/tests.rs b/crates/effects/src/sim2/tests.rs index 2ef35b122..6ad6eb21c 100644 --- a/crates/effects/src/sim2/tests.rs +++ b/crates/effects/src/sim2/tests.rs @@ -46,6 +46,138 @@ fn ball_action_draws_balls() { assert!(sum_diff(&a, &sc) > 1.0); } +/// #3197: CC Ball Action has After Effects' controls (since 24.2), in its order, with its +/// defaults: Coloring, Shading, Scatter Motion (formerly Instability State), Displace and +/// Displace Property were missing. +#[test] +fn ball_action_has_after_effects_controls() { + let spec = crate::find("ec.sim.ccballaction").unwrap(); + let names: Vec<&str> = spec.params.iter().map(|p| p.name).collect(); + assert_eq!( + names, + [ + "Grid Spacing", + "Ball Size", + "Coloring", + "Shading", + "Scatter", + "Scatter Motion", + "Displace", + "Displace Property", + "Twist Angle", + "Twist Property", + "Rotation Axis", + "Rotation" + ] + ); + let sp = |id: &str| spec.params.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("no {id}")); + assert_eq!(sp("gridSpacing").default, num(5.0)); + assert_eq!(sp("ballSize").default, num(100.0)); + assert_eq!(sp("coloring").default, Value::Enum(1)); + assert_eq!(sp("coloring").ui, ParamUi::Popup { options: vec!["Crisp".into(), "Medium".into(), "Smooth".into()] }); + assert_eq!(sp("shading").default, num(-75.0)); + assert!(matches!(sp("shading").ui, ParamUi::Slider { min, max, .. } if min <= -100.0 && max >= 100.0)); + assert_eq!(sp("scatterMotion").default, num(0.0)); + assert_eq!(sp("scatterMotion").ui, ParamUi::Angle); + assert_eq!(sp("displace").default, num(0.0)); + let ParamUi::Popup { options } = &sp("displaceProperty").ui else { panic!("Displace Property is a popup") }; + let Value::Enum(d) = sp("displaceProperty").default else { panic!("Displace Property defaults to an option") }; + assert_eq!(options.get(d as usize).map(String::as_str), Some("Brightness")); + // Old projects' Instability State becomes Scatter Motion through `PARAM_ID_ALIASES`; the + // engine test `opening_an_old_project_upgrades_effect_instances` covers every alias. +} + +/// #3197: the new controls at After Effects' defaults draw exactly what CC Ball Action drew +/// before (the lit sphere, a smooth colour sample, no displacement). +#[test] +fn ball_action_new_controls_at_defaults_keep_the_render() { + let base = [("ballSize", num(80.0)), ("scatter", num(6.0)), ("rotationAxis", Value::Enum(1)), ("rotation", num(25.0))]; + let a = run("ec.sim.ccballaction", &base, ramp(32, 32), 0.0); + let mut explicit = base.to_vec(); + explicit.extend([ + ("coloring", Value::Enum(1)), + ("shading", num(-75.0)), + ("scatterMotion", num(0.0)), + ("displace", num(0.0)), + ("displaceProperty", Value::Enum(3)), + ]); + assert_eq!(a, run("ec.sim.ccballaction", &explicit, ramp(32, 32), 0.0)); +} + +/// #3197: Shading 0 removes the built-in light: every ball is the layer's flat colour. The +/// default (-75) shades it; a smaller magnitude shades less, a positive value lights the balls +/// from the other side. +#[test] +fn ball_action_shading_zero_is_flat() { + let c = [0.6, 0.3, 0.2, 1.0]; + let shade = |v: f64| run("ec.sim.ccballaction", &[("ballSize", num(100.0)), ("gridSpacing", num(8.0)), ("shading", num(v))], Image::filled(32, 32, c), 0.0); + let flat = shade(0.0); + let covered: Vec<&[f32; 4]> = flat.data.iter().filter(|p| p[3] > 0.999).collect(); + assert!(!covered.is_empty(), "balls drawn"); + for p in &covered { + for k in 0..3 { + assert!((p[k] / p[3] - c[k]).abs() < 1e-4, "flat colour: {p:?}"); + } + } + let lit = shade(-75.0); + assert!(lit.data.iter().any(|p| p[3] > 0.999 && (0..3).any(|k| (p[k] / p[3] - c[k]).abs() > 0.05)), "the default shading lights and darkens the balls"); + let soft = shade(-30.0); + assert!(sum_diff(&flat, &soft) > 0.1 && sum_diff(&flat, &soft) < sum_diff(&flat, &lit), "less shading, closer to flat"); + assert!(sum_diff(&shade(75.0), &lit) > 1.0, "the sign moves the light"); +} + +/// #3197: Coloring Crisp takes the pixel under each ball's cell centre; Medium samples +/// smoothly between pixels. Grid Spacing 4 puts the cell centres on pixel corners (with the +/// default 5 they fall on pixel centres, where Medium's sample equals Crisp's). +#[test] +fn ball_action_coloring_crisp_takes_the_pixel() { + let mut src = Image::new(32, 32); + for y in 0..32u32 { + for x in 0..32u32 { + src.set(x, y, [x as f32 / 32.0, y as f32 / 32.0, ((x * 7 + y * 3) % 5) as f32 / 4.0, 1.0]); + } + } + let col = |m: u32| { + let v = [("gridSpacing", num(4.0)), ("ballSize", num(100.0)), ("shading", num(0.0)), ("coloring", Value::Enum(m))]; + run("ec.sim.ccballaction", &v, src.clone(), 0.0) + }; + let crisp = col(0); + // Flat, opaque balls of radius 2 centred on (4i + 2, 4j + 2): the pixel to the lower right + // of each centre is fully covered by its ball alone. + for j in 0..8i64 { + for i in 0..8i64 { + let (x, y) = (4 * i + 2, 4 * j + 2); + let (got, want) = (crisp.get(x, y), src.get(x, y)); + assert!((0..4).all(|k| (got[k] - want[k]).abs() < 1e-5), "ball ({i}, {j}): {got:?} vs the pixel {want:?}"); + } + } + assert!(sum_diff(&crisp, &col(1)) > 1.0, "medium blends the pixels"); +} + +/// #3197: a huge Shading (typed or from an expression) is clamped, so the balls stay finite. +#[test] +fn ball_action_huge_shading_stays_finite() { + for v in [1e45, -1e45, f64::MAX] { + let o = run("ec.sim.ccballaction", &[("gridSpacing", num(8.0)), ("shading", num(v))], ramp(32, 32), 0.0); + assert!(o.data.iter().all(|p| p.iter().all(|c| c.is_finite())), "shading {v}"); + assert!(o.data.iter().any(|p| p[3] > 0.0), "shading {v}: balls drawn"); + } +} + +/// #3197: Displace pushes the balls along z by the chosen property (Radius: the centre comes +/// towards the camera and grows); 0 leaves them in the layer's plane. +#[test] +fn ball_action_displace_moves_balls_in_depth() { + let flat = run("ec.sim.ccballaction", &[("ballSize", num(80.0))], ramp(32, 32), 0.0); + let d = run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(60.0)), ("displaceProperty", Value::Enum(6))], ramp(32, 32), 0.0); + assert_eq!(d, run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(60.0)), ("displaceProperty", Value::Enum(6))], ramp(32, 32), 0.0)); + assert!(sum_diff(&flat, &d) > 1.0); + for prop in 0..9 { + let o = run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(400.0)), ("displaceProperty", Value::Enum(prop))], ramp(32, 32), 0.0); + assert!(o.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "property {prop}"); + } +} + #[test] fn pixel_polly_breaks_after_start() { let v = [("forceCenter", pt(16.0, 16.0)), ("gridSpacing", num(4.0))]; diff --git a/crates/effects/tests/it/particle_golden.rs b/crates/effects/tests/it/particle_golden.rs index 0dbf19d76..5d0b255b1 100644 --- a/crates/effects/tests/it/particle_golden.rs +++ b/crates/effects/tests/it/particle_golden.rs @@ -192,7 +192,7 @@ fn cases() -> Vec<(&'static str, Vec)> { vec![ vec![], vec![("scatter", n(20.0)), ("rotationAxis", e(6)), ("rotation", n(40.0)), ("twistProperty", e(3)), ("twistAngle", n(90.0))], - vec![("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("instabilityState", n(45.0)), ("twistProperty", e(2)), ("twistAngle", n(30.0))], + vec![("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("scatterMotion", n(45.0)), ("twistProperty", e(2)), ("twistAngle", n(30.0))], ], ), ( @@ -538,26 +538,26 @@ const GOLDEN: &[(&str, u64)] = &[ ("ec.sim.particleplayground/8/32bpc/t1.5", 0xb5b7f0281f26baad), ("ec.sim.particleplayground/8/32bpc/t0.8", 0x8b6934363ef4dcfd), ("ec.sim.particleplayground/8/32bpc/t2.2", 0x0a31c17e8e34b9f5), - ("ec.sim.ccballaction/0/8bpc/t0.5", 0x12698ec8353be38c), - ("ec.sim.ccballaction/0/8bpc/t1.5", 0x12698ec8353be38c), - ("ec.sim.ccballaction/0/8bpc/t0.8", 0x12698ec8353be38c), - ("ec.sim.ccballaction/0/8bpc/t2.2", 0x12698ec8353be38c), - ("ec.sim.ccballaction/0/32bpc/t0.5", 0x3fb733487e120261), - ("ec.sim.ccballaction/0/32bpc/t1.5", 0x3fb733487e120261), - ("ec.sim.ccballaction/0/32bpc/t0.8", 0x3fb733487e120261), - ("ec.sim.ccballaction/0/32bpc/t2.2", 0x3fb733487e120261), - ("ec.sim.ccballaction/0/8bpc/half/t0.5", 0x4946070917cc0945), - ("ec.sim.ccballaction/0/8bpc/half/t1.5", 0x4946070917cc0945), - ("ec.sim.ccballaction/0/8bpc/half/t0.8", 0x4946070917cc0945), - ("ec.sim.ccballaction/0/8bpc/half/t2.2", 0x4946070917cc0945), - ("ec.sim.ccballaction/1/8bpc/t0.5", 0xf34b3be38a4dd468), - ("ec.sim.ccballaction/1/8bpc/t1.5", 0xf34b3be38a4dd468), - ("ec.sim.ccballaction/1/8bpc/t0.8", 0xf34b3be38a4dd468), - ("ec.sim.ccballaction/1/8bpc/t2.2", 0xf34b3be38a4dd468), - ("ec.sim.ccballaction/1/32bpc/t0.5", 0x503b7238edf2912c), - ("ec.sim.ccballaction/1/32bpc/t1.5", 0x503b7238edf2912c), - ("ec.sim.ccballaction/1/32bpc/t0.8", 0x503b7238edf2912c), - ("ec.sim.ccballaction/1/32bpc/t2.2", 0x503b7238edf2912c), + ("ec.sim.ccballaction/0/8bpc/t0.5", 0x5f7401d3d1e5a513), + ("ec.sim.ccballaction/0/8bpc/t1.5", 0x5f7401d3d1e5a513), + ("ec.sim.ccballaction/0/8bpc/t0.8", 0x5f7401d3d1e5a513), + ("ec.sim.ccballaction/0/8bpc/t2.2", 0x5f7401d3d1e5a513), + ("ec.sim.ccballaction/0/32bpc/t0.5", 0x9cf15a7756ab88ed), + ("ec.sim.ccballaction/0/32bpc/t1.5", 0x9cf15a7756ab88ed), + ("ec.sim.ccballaction/0/32bpc/t0.8", 0x9cf15a7756ab88ed), + ("ec.sim.ccballaction/0/32bpc/t2.2", 0x9cf15a7756ab88ed), + ("ec.sim.ccballaction/0/8bpc/half/t0.5", 0xe2e3a624434f8e88), + ("ec.sim.ccballaction/0/8bpc/half/t1.5", 0xe2e3a624434f8e88), + ("ec.sim.ccballaction/0/8bpc/half/t0.8", 0xe2e3a624434f8e88), + ("ec.sim.ccballaction/0/8bpc/half/t2.2", 0xe2e3a624434f8e88), + ("ec.sim.ccballaction/1/8bpc/t0.5", 0x07382912d068a625), + ("ec.sim.ccballaction/1/8bpc/t1.5", 0x07382912d068a625), + ("ec.sim.ccballaction/1/8bpc/t0.8", 0x07382912d068a625), + ("ec.sim.ccballaction/1/8bpc/t2.2", 0x07382912d068a625), + ("ec.sim.ccballaction/1/32bpc/t0.5", 0xa1e843936e72815f), + ("ec.sim.ccballaction/1/32bpc/t1.5", 0xa1e843936e72815f), + ("ec.sim.ccballaction/1/32bpc/t0.8", 0xa1e843936e72815f), + ("ec.sim.ccballaction/1/32bpc/t2.2", 0xa1e843936e72815f), ("ec.sim.ccballaction/2/8bpc/t0.5", 0x0b6bf26753ee4582), ("ec.sim.ccballaction/2/8bpc/t1.5", 0x0b6bf26753ee4582), ("ec.sim.ccballaction/2/8bpc/t0.8", 0x0b6bf26753ee4582), diff --git a/crates/gpu/src/fx_sim.rs b/crates/gpu/src/fx_sim.rs index 944ca6c07..a3f0f7a0c 100644 --- a/crates/gpu/src/fx_sim.rs +++ b/crates/gpu/src/fx_sim.rs @@ -228,6 +228,8 @@ pub(crate) fn sprite_layer(e: &mut Enc, src: &GpuImage, plan: &SpritePlan) -> Op Shape::Square => (6.0, 0.0, 0.0), Shape::Tri => (7.0, 0.0, 0.0), Shape::Line { dx, dy } => (8.0, dx, dy), + // The strength rides in the (otherwise unused) first segment slot. + Shape::Ball { shade } => (9.0, shade, 0.0), }; let mut rec = [kind, s.x, s.y, s.r, s.c[0], s.c[1], s.c[2], s.c[3], s.rot, dx, dy, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; match plan.tints.get(i).copied().unwrap_or(Tint::Fixed) { diff --git a/crates/gpu/src/shaders/fx_sim.wgsl b/crates/gpu/src/shaders/fx_sim.wgsl index 7deeac048..cf4a14a03 100644 --- a/crates/gpu/src/shaders/fx_sim.wgsl +++ b/crates/gpu/src/shaders/fx_sim.wgsl @@ -145,6 +145,27 @@ fn fxm_sprite(at: u32, x: f32, y: f32) -> FxmShade { } cov = fxm_aa(m); } + // sim::Shape::Ball (CC Ball Action's Shading): the sphere's light and shine scaled by + // |shade| (data[at + 9]), lit from the lower right when shade < 0. + case 9u: { + let d = sqrt(dx * dx + dy * dy); + let cv = fxm_aa(r - d); + if (cv <= 0.0) { + return fxm_none(); + } + let shade = data[at + 9u]; + let nx = dx / r; + let ny = dy / r; + let nz = sqrt(max(1.0 - nx * nx - ny * ny, 0.0)); + let m = select(1.0, -1.0, shade < 0.0); + let diff = max(nx * (-0.48 * m) + ny * (-0.58 * m) + nz * 0.66, 0.0); + let rz = 2.0 * diff * nz - 0.66; + let st = abs(shade); + let spec = powz(max(rz, 0.0), 20.0) * 0.6 * st; + let k = max(1.0 - st * 0.8 * (1.0 - diff), 0.0); + rgb = rgb * k + spec; + cov = cv; + } default: { let lx = data[at + 9u]; let ly = data[at + 10u]; diff --git a/crates/gpu/src/tests/fx_particles.rs b/crates/gpu/src/tests/fx_particles.rs index e8c3a7ce6..a4d531a37 100644 --- a/crates/gpu/src/tests/fx_particles.rs +++ b/crates/gpu/src/tests/fx_particles.rs @@ -141,7 +141,22 @@ fn ball_action_pixel_polly_scatterize() { 0.0, 0.0, ); - case("ec.sim.ccballaction", &[("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("instabilityState", n(45.0)), ("twistProperty", e(2))], 0.0, 0.0); + case("ec.sim.ccballaction", &[("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("scatterMotion", n(45.0)), ("twistProperty", e(2))], 0.0, 0.0); + // #3197: Shading (flat, weaker, stronger, lit from the other side), Coloring, Displace. + for shading in [0.0, -30.0, -100.0, 60.0, 1e45] { + case("ec.sim.ccballaction", &[("ballSize", n(80.0)), ("shading", n(shading))], 0.0, 0.0); + } + for coloring in [0, 2] { + case("ec.sim.ccballaction", &[("ballSize", n(80.0)), ("coloring", e(coloring))], 0.0, 0.0); + } + for prop in [3, 6, 8] { + case( + "ec.sim.ccballaction", + &[("ballSize", n(80.0)), ("rotationAxis", e(1)), ("rotation", n(30.0)), ("displace", n(40.0)), ("displaceProperty", e(prop))], + 0.0, + 0.0, + ); + } for object in 0..4 { case("ec.sim.ccpixelpolly", &[("object", e(object)), ("gridSpacing", n(6.0))], 0.6, 0.0); } diff --git a/docs/effects.md b/docs/effects.md index d9f726481..130d00a90 100644 --- a/docs/effects.md +++ b/docs/effects.md @@ -3,7 +3,7 @@ -EffectCraft ships 308 effects with 2988 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over. +EffectCraft ships 308 effects with 2992 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over. - **GPU**: 280 effects also run on the GPU compositor with identical results. - **32**: 308 effects process 32-bit float (HDR, overbright) pixels without clamping. @@ -319,7 +319,7 @@ Effects are addressed by id (`ec..`) or display name in commands | Effect | Id | Params | GPU | 32 | Status | |---|---|---:|:-:|:-:|---| -| CC Ball Action | `ec.sim.ccballaction` | 8 | GPU | 32 | Implemented | +| CC Ball Action | `ec.sim.ccballaction` | 12 | GPU | 32 | Implemented | | CC Bubbles | `ec.sim.ccbubbles` | 7 | GPU | 32 | Implemented | | CC Drizzle | `ec.sim.ccdrizzle` | 14 | GPU | 32 | Implemented | | CC Hair | `ec.sim.cchair` | 20 | GPU | 32 | Implemented | From 1c47f233ea9b18bd74a4eb4a178f406f2896b716 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 12:57:53 +0100 Subject: [PATCH 036/324] Graph Editor: the value curve passes through every key and draws Hold steps vertically Refs #2720 The curve was sampled on an even grid every 2 px, blind to key times. Zoomed out, keys one frame apart sit closer than a sample step, so the polyline cut across the jump instead of passing through the key squares, and a Hold step was drawn as a slope across one step. The samples now also include every visible key time and both sides of the key after a Hold key (so a stretched layer's one-tick rounding or a reversed layer still gives a vertical step). Keys denser than the grid add no samples, so the work stays bounded. This does not change the slanted spans in the issue's screenshot: their key squares sit at different values (about 0.36 vs 0.40, 0.01 vs 0.00), so the curve draws the stored values as they are. --- crates/ui-egui/src/panels/graph.rs | 142 ++++++++++++++++++++++++++++- 1 file changed, 137 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/graph.rs b/crates/ui-egui/src/panels/graph.rs index be18999d4..8a4401d97 100644 --- a/crates/ui-egui/src/panels/graph.rs +++ b/crates/ui-egui/src/panels/graph.rs @@ -130,6 +130,45 @@ fn speed_at(pr: &Property, spatial: bool, d: usize, lt: Tick) -> f64 { } } +/// How far either side of the key after a Hold key the step is sampled (seconds; far below a +/// pixel, far above the tick a stretched layer's time conversion can be off by). +const HOLD_EDGE: f64 = 1e-6; + +/// The comp times (seconds) a curve is sampled at between `t0` and `t1`: `n` evenly spaced +/// times, plus every key time `keys` puts inside the span, and around the key after a key that +/// holds (its out side is Hold) the instants just before and after it. `keys` are the active +/// keys in key order, as (comp seconds, holds); on a reversed layer their comp times descend. +/// Without the key times the polyline only passes near the keys: keys closer together than a +/// sample step (a one-frame jump zoomed out) got cut across, missing their squares, and a Hold +/// step was drawn as a slope across one step instead of a vertical edge (#2720). With no keys +/// this is the plain even grid. Keys denser than the grid (baked keys zoomed out) add nothing +/// visible and would multiply the evaluations, so past `2 * n` key samples only the grid is used. +fn sample_times(t0: f64, t1: f64, n: usize, keys: &[(f64, bool)]) -> Vec { + let n = n.max(2); + let mut ts: Vec = (0..n).map(|i| t0 + (t1 - t0) * i as f64 / (n - 1) as f64).collect(); + let (lo, hi) = (t0.min(t1), t0.max(t1)); + let inside = |t: f64| t > lo && t < hi; + let max_extra = n.saturating_mul(2); + let mut extra = vec![]; + for (i, &(kt, holds)) in keys.iter().enumerate() { + if inside(kt) { + extra.push(kt); + } + if holds && let Some(&(next, _)) = keys.get(i + 1) { + extra.extend([next - HOLD_EDGE, next + HOLD_EDGE].into_iter().filter(|&t| inside(t))); + } + if extra.len() > max_extra { + extra.clear(); + break; + } + } + ts.extend(extra); + ts.retain(|t| t.is_finite()); + ts.sort_by(f64::total_cmp); + ts.dedup(); + ts +} + /// Build the curves for the visible time span. fn curves<'a>(app: &EffectcraftApp, comp: &'a Comp, ectx: &EvalCtx, tm: TMap, plot: Rect, speed: bool) -> Vec> { let sel = &app.session.state.selected_keys; @@ -140,12 +179,14 @@ fn curves<'a>(app: &EffectcraftApp, comp: &'a Comp, ectx: &EvalCtx, tm: TMap, pl let Some(pr) = l.props.find(uid) else { continue }; let spatial = pr.spatial && matches!(pr.value, Value::Vec2(_) | Value::Vec3(_)); let dims = if speed && spatial { 1 } else { shown_dims(l, pr) }; + // The active keys (muted ones are skipped by evaluation) in comp seconds, and whether each + // holds its value up to the next one. + let active: Vec<(f64, bool)> = pr.keys.iter().filter(|k| !k.muted).map(|k| (l.comp_time(k.time).seconds(), k.out_interp == Interp::Hold)).collect(); + let times = sample_times(tm.t(plot.min.x), tm.t(plot.max.x), n, &active); for d in 0..dims { let color = if dims > 1 { DIM_COLORS[d % 4] } else { PROP_COLORS[pi % PROP_COLORS.len()] }; - let mut pts = Vec::with_capacity(n); - for i in 0..n { - let x = plot.min.x + plot.width() * i as f32 / (n - 1) as f32; - let ct = tm.t(x); + let mut pts = Vec::with_capacity(times.len()); + for &ct in × { let tt = Tick::from_seconds_f64(ct); let v = if speed { speed_at(pr, spatial, d, l.layer_time(tt)) } else { ectx.at(tt).value(l, pr).components().get(d).copied().unwrap_or(0.0) }; pts.push((ct, v)); @@ -892,7 +933,98 @@ fn shift_axes(shift: bool, dx: f32, dy: f32) -> (bool, bool) { #[cfg(test)] mod tests { - use super::shift_axes; + use super::{HOLD_EDGE, sample_times, shift_axes}; + use effectcraft_engine::keyframe::{Keyframe, Value, evaluate}; + use effectcraft_engine::time::Tick; + + /// The value-graph polyline of `keys` (layer time = comp time) sampled at `times`. + fn polyline(keys: &[Keyframe], times: &[f64]) -> Vec<(f64, f64)> { + times + .iter() + .map(|&t| { + let v = evaluate(keys, Tick::from_seconds_f64(t), false).map(|v| v.components().first().copied().unwrap_or(f64::NAN)).unwrap_or(f64::NAN); + (t, v) + }) + .collect() + } + + fn active(keys: &[Keyframe]) -> Vec<(f64, bool)> { + keys.iter().map(|k| (k.time.seconds(), k.out_interp == effectcraft_engine::keyframe::Interp::Hold)).collect() + } + + /// #2720: a step one frame wide, zoomed out so it is narrower than a sample step. The curve + /// has to pass through every key square: the old even grid (`sample_times` with no keys) + /// never sampled 0.2 s or 0.2 s + 1 frame and drew a slope from 0 to 1 across the step. + #[test] + fn value_graph_passes_through_keys_narrower_than_a_sample_step() { + let keys = [ + Keyframe::new(Tick::from_seconds_f64(0.0), Value::Scalar(0.0)), + Keyframe::new(Tick::from_seconds_f64(0.2), Value::Scalar(0.0)), + Keyframe::new(Tick::from_seconds_f64(0.2 + 1.0 / 30.0), Value::Scalar(1.0)), + Keyframe::new(Tick::from_seconds_f64(0.9), Value::Scalar(1.0)), + ]; + let times = sample_times(0.0, 1.0, 4, &active(&keys)); + let pts = polyline(&keys, ×); + for k in &keys { + let (t, v) = (k.time.seconds(), k.value.components()[0]); + assert!(pts.iter().any(|p| p.0 == t && (p.1 - v).abs() < 1e-12), "no curve point on the key at {t} s ({v}): {pts:?}"); + } + // The spans between equal keys are flat: no sample between 0 and 0.2 s leaves 0, none + // between 0.2 s + 1 frame and 0.9 s leaves 1. + for &(t, v) in &pts { + if t <= 0.2 { + assert!(v.abs() < 1e-12, "{t} s: {v}"); + } else if (0.2 + 1.0 / 30.0..=0.9).contains(&t) { + assert!((v - 1.0).abs() < 1e-12, "{t} s: {v}"); + } + } + // Times are sorted and unique, the even grid is still there. + assert!(times.windows(2).all(|w| w[0] < w[1]), "{times:?}"); + assert!([0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0].iter().all(|g| times.iter().any(|t| (t - g).abs() < 1e-12)), "{times:?}"); + } + + /// #2720: a Hold key draws a vertical step at the next key, not a slope across a sample step. + #[test] + fn hold_step_is_vertical() { + let keys = [Keyframe::new(Tick::from_seconds_f64(0.1), Value::Scalar(0.0)).hold(), Keyframe::new(Tick::from_seconds_f64(0.5), Value::Scalar(1.0))]; + let pts = polyline(&keys, &sample_times(0.0, 1.0, 4, &active(&keys))); + let at = pts.iter().position(|p| p.0 == 0.5).unwrap_or_else(|| panic!("no sample on the key at 0.5 s: {pts:?}")); + let before = pts[at - 1]; + assert!((0.5 - before.0 - HOLD_EDGE).abs() < 1e-12 && before.1.abs() < 1e-12, "the held value ends right before the next key: {pts:?}"); + assert!((pts[at].1 - 1.0).abs() < 1e-12, "{pts:?}"); + } + + #[test] + fn sample_times_keep_keys_inside_the_span_only() { + let times = sample_times(1.0, 2.0, 3, &[(0.5, true), (1.25, false), (2.5, false)]); + // 0.5 s and 2.5 s are off screen; the hold from 0.5 s ends at 1.25 s, inside it. + assert_eq!(times, vec![1.0, 1.25 - HOLD_EDGE, 1.25, 1.25 + HOLD_EDGE, 1.5, 2.0]); + // Degenerate input never panics: an empty span is one point, a NaN span has no points. + assert_eq!(sample_times(0.0, 0.0, 0, &[]), vec![0.0]); + assert!(sample_times(f64::NAN, 1.0, 4, &[(0.5, true)]).iter().all(|t| t.is_finite())); + } + + /// A reversed layer: its keys run backwards in comp time, and both sides of each step after + /// a Hold key are still sampled. + #[test] + fn sample_times_cover_hold_steps_on_a_reversed_layer() { + let times = sample_times(1.0, 2.0, 10, &[(1.8, true), (1.4, true), (1.1, false)]); + for t in [1.8, 1.4 - HOLD_EDGE, 1.4, 1.4 + HOLD_EDGE, 1.1 - HOLD_EDGE, 1.1, 1.1 + HOLD_EDGE] { + assert!(times.contains(&t), "{t} missing: {times:?}"); + } + assert!(times.windows(2).all(|w| w[0] < w[1]), "{times:?}"); + } + + /// Dense keys zoomed out (100 000 in one second, half of them Hold) don't multiply the samples. + #[test] + fn sample_times_stay_bounded_with_dense_keys() { + let keys: Vec<(f64, bool)> = (0..100_000).map(|i| (i as f64 / 100_000.0, i % 2 == 0)).collect(); + let times = sample_times(0.0, 1.0, 100, &keys); + assert!(times.len() <= 300, "{} samples", times.len()); + // A few keys inside the span are still all sampled. + let few = sample_times(0.0, 1.0, 100, &keys[..50]); + assert!(keys[1..50].iter().all(|(t, _)| few.contains(t)), "{few:?}"); + } #[test] fn shift_locks_drag_to_dominant_axis() { From 36854318db1bbd8a2d1eafacb1efc5611fba8422 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 14:02:20 +0100 Subject: [PATCH 037/324] Viewer: the Rotation tool counts the turn from the press The Rotation gesture seeded its angle from the pointer where egui registered the drag, past the drag threshold, so the sweep round the anchor before that was lost; near the anchor that is a large angle. Count from where the button went down, as After Effects does and as the Create and Pan Behind gestures already do. A press within 3 points of the anchor, or with no anchor on screen, has no direction and still counts from where the drag registered, so the first move doesn't jump. The layer under the press is the one picked. The issue's main cause, a pivot far off for child and 3D layers, was fixed by #2887. Refs #2769 --- crates/ui-egui/src/panels/viewer.rs | 13 ++++-- crates/ui-egui/tests/it/ui_viewer.rs | 61 ++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index b1899e1f8..f17d11795 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -1193,16 +1193,23 @@ fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, }) } Tool::MaskFeather => ov::begin_feather(app, ectx, &paths, &map, press).map(Gesture::Overlay), - Tool::Rotate => pick(app, ectx, cpt, mods.shift).map(|l| { + // The layer under the press is the one that turns. + Tool::Rotate => pick(app, ectx, map.to_comp(press), mods.shift).map(|l| { let layer = comp.layer(l).cloned(); let sign = layer.as_ref().map_or(1.0, |l| rotation_sign(ectx, l)); let others = selected_others(app, comp, l) .into_iter() .filter_map(|o| Some((o.id, ectx.f(o, o.transform()?, "rotation", 0.0), rotation_sign(ectx, o) * sign))) .collect(); - let pivot = layer.as_ref().and_then(|l| anchor_in_comp(ectx, l)).unwrap_or(cpt); + let anchor = layer.as_ref().and_then(|l| anchor_in_comp(ectx, l)); + let pivot = anchor.unwrap_or(cpt); let rot = layer.as_ref().and_then(|l| l.transform().map(|tr| ectx.f(l, tr, "rotation", 0.0))).unwrap_or(0.0); - let last_angle = (cpt[1] - pivot[1]).atan2(cpt[0] - pivot[0]).to_degrees(); + // The turn counts from where the button went down, as in After Effects: by the + // time the drag registers the pointer has already swept some way round the anchor. + // A press on the anchor (or with no anchor to turn about) has no direction, so + // the turn then counts from where the drag registered. + let seed = if anchor.is_some() && press.distance(map.to_screen(pivot)) > 3.0 { map.to_comp(press) } else { cpt }; + let last_angle = (seed[1] - pivot[1]).atan2(seed[0] - pivot[0]).to_degrees(); Gesture::Rotate { layer: l, pivot, sign, last_angle, turned: 0.0, start_rot: rot, others } }), Tool::PanBehind => pick(app, ectx, cpt, false).and_then(|l| { diff --git a/crates/ui-egui/tests/it/ui_viewer.rs b/crates/ui-egui/tests/it/ui_viewer.rs index 7b32fa2ec..bd047088b 100644 --- a/crates/ui-egui/tests/it/ui_viewer.rs +++ b/crates/ui-egui/tests/it/ui_viewer.rs @@ -3022,6 +3022,67 @@ fn rotate_tool_counts_revolutions_both_ways() { assert_eq!(h.state().session.history.undo.len(), undo_before + 1, "one drag, one undo step"); } +/// #2769: the Rotation tool counts the turn from where the button went down, as in After Effects, +/// not from where the drag registered: a first move that sweeps 60° round the anchor turns the +/// layer 60° (it used to drop that sweep, so near the anchor the tool lagged behind the pointer). +#[test] +fn rotate_tool_counts_the_turn_from_the_press() { + let mut h = harness(); + let box_id = h.state().session.active_comp().unwrap().layers[0].id; + h.state_mut().session.execute("layer.select", json!({"layers": [box_id.0]})).unwrap(); + h.state_mut().ui.tool = Tool::Rotate; + h.run_steps(2); + let center = screen(&h, [320.0, 180.0]); + let r = (screen(&h, [350.0, 180.0]) - center).x; + // Press on the box right of its anchor (0°), then one move to 60° clockwise, still on the box. + let press = center + vec2(r * 0.3, 0.0); + let to = center + vec2(r * 60f32.to_radians().cos(), r * 60f32.to_radians().sin()); + h.input_mut().events.push(Event::PointerMoved(press)); + h.input_mut().events.push(Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.input_mut().events.push(Event::PointerMoved(to)); + h.step(); + // The gesture applies the previous frame's pointer: hold a frame. + h.step(); + h.input_mut().events.push(Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + let rot = h.state().session.active_comp().unwrap().layer(box_id).unwrap().props.prop("transform/rotation").unwrap().value.as_f64(); + assert!((rot - 60.0).abs() < 1.0, "the whole sweep from the press turns the layer: {rot}"); +} + +/// #2769: a press right on the anchor point has no direction to count the turn from, so the layer +/// doesn't jump on the first move; the turn counts from where the drag registered. +#[test] +fn rotate_tool_pressed_on_the_anchor_does_not_jump() { + let mut h = harness(); + let box_id = h.state().session.active_comp().unwrap().layers[0].id; + h.state_mut().session.execute("layer.select", json!({"layers": [box_id.0]})).unwrap(); + h.state_mut().ui.tool = Tool::Rotate; + h.run_steps(2); + let rotation = |h: &Harness<'_, EffectcraftApp>| { + h.state().session.active_comp().unwrap().layer(box_id).unwrap().props.prop("transform/rotation").unwrap().value.as_f64() + }; + let center = screen(&h, [320.0, 180.0]); + let r = (screen(&h, [350.0, 180.0]) - center).x; + let at = |deg: f32| center + vec2(r * deg.to_radians().cos(), r * deg.to_radians().sin()); + h.input_mut().events.push(Event::PointerMoved(center)); + h.input_mut().events.push(Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.input_mut().events.push(Event::PointerMoved(at(60.0))); + h.step(); + // The gesture applies the previous frame's pointer: hold a frame. + h.step(); + let first = rotation(&h); + assert!(first.abs() < 1.0, "no jump on the first move: {first}"); + h.input_mut().events.push(Event::PointerMoved(at(90.0))); + h.step(); + h.step(); + let next = rotation(&h); + assert!((next - 30.0).abs() < 1.0, "then turns with the pointer: {next}"); + h.input_mut().events.push(Event::PointerButton { pos: at(90.0), button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); +} + /// A harness whose Box is a child of Plate (anchor 320,180) with `plate` set on Plate first, at /// parent-space position (200, 120). Returns the two layers' ids. fn rotate_child_harness(plate: serde_json::Value) -> (Harness<'static, EffectcraftApp>, u64, u64) { From e109fa6b95310ac84955bef6b272c0c76aa2e2c3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 15:20:11 +0100 Subject: [PATCH 038/324] Graph Editor: a dense key cluster only thins its own grid steps Refs #2720 When the key samples passed the budget, sample_times dropped all of them, so a sparse Hold step elsewhere in view went back to a slope. Key samples are now kept per grid step: up to four as they are, past that only the earliest and latest of that step. Sparse keys keep every sample and a curve still has at most 5 * n samples. --- crates/ui-egui/src/panels/graph.rs | 87 +++++++++++++++++++++++++----- 1 file changed, 73 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/graph.rs b/crates/ui-egui/src/panels/graph.rs index 8a4401d97..397d9cab3 100644 --- a/crates/ui-egui/src/panels/graph.rs +++ b/crates/ui-egui/src/panels/graph.rs @@ -134,6 +134,42 @@ fn speed_at(pr: &Property, spatial: bool, d: usize, lt: Tick) -> f64 { /// pixel, far above the tick a stretched layer's time conversion can be off by). const HOLD_EDGE: f64 = 1e-6; +/// How many key samples one grid step of [`sample_times`] keeps as they are (a key and both +/// sides of a Hold step fit); past that only its earliest and latest are kept. +const BUCKET_KEEP: usize = 4; + +/// The key samples falling in one grid step of [`sample_times`]. +#[derive(Clone)] +struct Bucket { + few: Vec, + first: f64, + last: f64, + /// More than [`BUCKET_KEEP`] samples fell here. + full: bool, +} + +impl Default for Bucket { + fn default() -> Self { + Bucket { few: Vec::new(), first: f64::INFINITY, last: f64::NEG_INFINITY, full: false } + } +} + +impl Bucket { + fn add(&mut self, t: f64) { + self.first = self.first.min(t); + self.last = self.last.max(t); + if self.full { + return; + } + if self.few.len() < BUCKET_KEEP { + self.few.push(t); + } else { + self.full = true; + self.few = Vec::new(); + } + } +} + /// The comp times (seconds) a curve is sampled at between `t0` and `t1`: `n` evenly spaced /// times, plus every key time `keys` puts inside the span, and around the key after a key that /// holds (its out side is Hold) the instants just before and after it. `keys` are the active @@ -142,27 +178,40 @@ const HOLD_EDGE: f64 = 1e-6; /// sample step (a one-frame jump zoomed out) got cut across, missing their squares, and a Hold /// step was drawn as a slope across one step instead of a vertical edge (#2720). With no keys /// this is the plain even grid. Keys denser than the grid (baked keys zoomed out) add nothing -/// visible and would multiply the evaluations, so past `2 * n` key samples only the grid is used. +/// visible and would multiply the evaluations: in a grid step with more than [`BUCKET_KEEP`] +/// key samples only the earliest and latest are kept, so a curve has at most `5 * n` samples +/// and sparse keys elsewhere in view keep every sample. fn sample_times(t0: f64, t1: f64, n: usize, keys: &[(f64, bool)]) -> Vec { let n = n.max(2); let mut ts: Vec = (0..n).map(|i| t0 + (t1 - t0) * i as f64 / (n - 1) as f64).collect(); let (lo, hi) = (t0.min(t1), t0.max(t1)); let inside = |t: f64| t > lo && t < hi; - let max_extra = n.saturating_mul(2); - let mut extra = vec![]; + // One bucket per grid step. + let steps = n - 1; + let mut buckets = vec![Bucket::default(); steps]; + let mut add = |t: f64| { + if !inside(t) { + return; + } + let b = (((t - lo) / (hi - lo) * steps as f64) as usize).min(steps - 1); + if let Some(bucket) = buckets.get_mut(b) { + bucket.add(t); + } + }; for (i, &(kt, holds)) in keys.iter().enumerate() { - if inside(kt) { - extra.push(kt); - } + add(kt); if holds && let Some(&(next, _)) = keys.get(i + 1) { - extra.extend([next - HOLD_EDGE, next + HOLD_EDGE].into_iter().filter(|&t| inside(t))); + add(next - HOLD_EDGE); + add(next + HOLD_EDGE); } - if extra.len() > max_extra { - extra.clear(); - break; + } + for b in &buckets { + if b.full { + ts.extend([b.first, b.last]); + } else { + ts.extend_from_slice(&b.few); } } - ts.extend(extra); ts.retain(|t| t.is_finite()); ts.sort_by(f64::total_cmp); ts.dedup(); @@ -1021,9 +1070,19 @@ mod tests { let keys: Vec<(f64, bool)> = (0..100_000).map(|i| (i as f64 / 100_000.0, i % 2 == 0)).collect(); let times = sample_times(0.0, 1.0, 100, &keys); assert!(times.len() <= 300, "{} samples", times.len()); - // A few keys inside the span are still all sampled. - let few = sample_times(0.0, 1.0, 100, &keys[..50]); - assert!(keys[1..50].iter().all(|(t, _)| few.contains(t)), "{few:?}"); + } + + /// A dense cluster of keys only thins its own grid steps: a Hold step elsewhere in view keeps + /// its key and both sides of the step. + #[test] + fn sample_times_keep_sparse_keys_beside_a_dense_cluster() { + let mut keys: Vec<(f64, bool)> = (0..100_000).map(|i| (0.1 * i as f64 / 100_000.0, i % 2 == 0)).collect(); + keys.extend([(0.5, true), (0.8, false)]); + let times = sample_times(0.0, 1.0, 100, &keys); + assert!(times.len() <= 500, "{} samples", times.len()); + for t in [0.5, 0.8 - HOLD_EDGE, 0.8, 0.8 + HOLD_EDGE] { + assert!(times.contains(&t), "{t} missing"); + } } #[test] From a2728fbf094d79ef92d164b2769228dc938487b2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 15:29:46 +0100 Subject: [PATCH 039/324] Timeline waveform: draw what the mix plays for reversed layers and Backwards (#3238) A time-reversed layer (negative stretch) is silent in the audio mix, but the Timeline drew its waveform; with the Backwards audio effect the mix plays the layer's [in, out) span reversed, but the waveform was drawn forwards. The render crate now exposes the mix's rules as stretch_is_mixed and plays_backwards, and the mix uses them. The waveform uses the same rules, decided once per layer: only the baselines for a layer the mix leaves silent, and comp time mirrored over [in, out) under Backwards, as the mix maps it. Columns are limited to [in, out) so an edge column draws no audio past the out point. Fixes #3238 --- crates/render/src/audio.rs | 15 ++- crates/ui-egui/src/panels/waveform.rs | 177 ++++++++++++++++++++++++-- 2 files changed, 180 insertions(+), 12 deletions(-) diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rs index e2861340c..b715c5efe 100644 --- a/crates/render/src/audio.rs +++ b/crates/render/src/audio.rs @@ -66,6 +66,17 @@ fn generates(l: &Layer) -> bool { audio_effect_groups(l).any(|(id, _)| audio_fx::generates_audio(id)) } +/// Does the mix play the layer at its time stretch? Reversed layers (negative stretch) are +/// silent for now; the Timeline waveform shares this rule so it draws what is heard. +pub fn stretch_is_mixed(l: &Layer) -> bool { + l.stretch > 0.0 +} + +/// Does an enabled audio effect (Backwards) play the layer's [in, out) span reversed? +pub fn plays_backwards(l: &Layer) -> bool { + audio_effect_groups(l).any(|(id, _)| audio_fx::reverses(id)) +} + /// Does the layer contribute to the mix (Audio switch on and something to hear)? pub fn audible(project: &Project, l: &Layer) -> bool { l.switches.audio @@ -210,7 +221,7 @@ impl MixEnv<'_> { if fx.is_empty() { return self.layer_raw(l, i0, n, false); } - let reversed = fx.iter().any(|(id, _, _)| audio_fx::reverses(id)); + let reversed = plays_backwards(l); let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum(); let pre = (pre_s * self.rate as f64).ceil() as usize; let b0 = i0 - pre as i64; @@ -291,7 +302,7 @@ fn mix_into(sources: &AudioSources<'_>, comp_id: ItemId, start: Tick, out: &mut let any_solo = comp.layers.iter().any(|l| l.switches.solo && audible(project, l)); let s0 = start.to_units_floor(rate as i64); for l in &comp.layers { - if !audible(project, l) || (any_solo && !l.switches.solo) || l.stretch <= 0.0 { + if !audible(project, l) || (any_solo && !l.switches.solo) || !stretch_is_mixed(l) { continue; } // Sample range of the block that falls inside the layer's [in, out). diff --git a/crates/ui-egui/src/panels/waveform.rs b/crates/ui-egui/src/panels/waveform.rs index 4e355f951..aa4c218e5 100644 --- a/crates/ui-egui/src/panels/waveform.rs +++ b/crates/ui-egui/src/panels/waveform.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; use effectcraft_engine::project::{ItemId, ItemKind, Layer, LayerSource, Project, Property}; -use effectcraft_engine::render::audio::db_to_gain; +use effectcraft_engine::render::audio::{self, db_to_gain}; use effectcraft_engine::time::Tick; use egui::{Color32, Painter, Rect, Stroke, pos2}; @@ -39,6 +39,39 @@ pub fn audio_item(project: &Project, l: &Layer) -> Option { } } +/// How the layer plays its audio, as far as its waveform goes: `None` when it is silent +/// (reversed, see [`audio::stretch_is_mixed`]), else whether the Backwards effect plays its +/// [in, out) span mirrored ([`audio::plays_backwards`]). The Audio switch and solo are not +/// followed: a muted layer still shows its waveform. +fn played(layer: &Layer) -> Option { + audio::stretch_is_mixed(layer).then(|| audio::plays_backwards(layer)) +} + +/// The summary bins under the Timeline column for comp times `ta .. tb` (seconds, limited to +/// the layer's [in, out) span), as the layer plays them: mirrored over that span when `mirror` +/// (see [`played`]), so the first column shows the last samples. +fn column_bins<'a>(layer: &Layer, s: &'a Summary, ta: f64, tb: f64, mirror: bool) -> Option<&'a [[f32; 4]]> { + let (i, o) = (layer.in_point.seconds(), layer.out_point.seconds()); + let (ta, tb) = (ta.max(i).min(o), tb.max(i).min(o)); + if tb <= ta { + return None; + } + let span = i + o; + let src = |t: f64| { + let t = if mirror { span - t } else { t }; + layer.layer_time(Tick::from_seconds_f64(t)).seconds() * s.bins_per_sec as f64 + }; + let (u, v) = (src(ta), src(tb)); + let n = s.peaks.len() as i64; + let ba = u.min(v).floor() as i64; + let bb = (u.max(v).ceil() as i64).max(ba.saturating_add(1)); + let (ba, bb) = (ba.clamp(0, n), bb.clamp(0, n)); + if ba >= bb { + return None; + } + s.peaks.get(ba as usize..bb as usize) +} + /// The summary for `item`, starting its computation on first request. pub fn summary(app: &EffectcraftApp, ctx: &egui::Context, item: ItemId) -> Option> { let mut m = app.waveforms.map.lock().ok()?; @@ -88,27 +121,23 @@ fn level_gains(levels: Option<&Property>, t: Tick) -> [f32; 2] { } /// Draw `layer`'s waveform in `rect` (left channel above right), columns mapped through the -/// timeline's time map and the layer's time mapping, limited to its [in, out) span. +/// timeline's time map and the layer's time mapping, limited to its [in, out) span and drawn as +/// the layer plays (see [`played`]): only the baselines for a silent layer. pub(crate) fn draw(p: &Painter, rect: Rect, tm: &TMap, layer: &Layer, s: &Summary, color: Color32) { let mid = [rect.min.y + rect.height() * 0.25, rect.min.y + rect.height() * 0.75]; let half = rect.height() * 0.25 - 1.0; let x0 = tm.x(layer.in_point.seconds()).max(rect.min.x).floor() as i32; let x1 = tm.x(layer.out_point.seconds()).min(rect.max.x).ceil() as i32; - let n = s.peaks.len() as i64; let levels = layer.props.sub("audio").and_then(|g| g.get("levels")); for c in 0..2 { p.line_segment([pos2(x0 as f32, mid[c]), pos2(x1 as f32, mid[c])], Stroke::new(1.0, color.gamma_multiply(0.5))); } + let Some(mirror) = played(layer) else { return }; for x in x0..x1 { let (ta, tb) = (tm.t(x as f32), tm.t(x as f32 + 1.0)); - let src = |t: f64| layer.layer_time(Tick::from_seconds_f64(t)).seconds() * s.bins_per_sec as f64; - let (ba, bb) = (src(ta).floor() as i64, src(tb).ceil() as i64); - let (ba, bb) = (ba.min(bb).clamp(0, n), ba.max(bb).max(ba + 1).clamp(0, n)); - if ba >= bb { - continue; - } + let Some(bins) = column_bins(layer, s, ta, tb, mirror) else { continue }; let mut agg = [0.0f32; 4]; - for b in &s.peaks[ba as usize..bb as usize] { + for b in bins { agg[0] = agg[0].min(b[0]); agg[1] = agg[1].max(b[1]); agg[2] = agg[2].min(b[2]); @@ -137,3 +166,131 @@ mod tests { assert_eq!(level_gains(None, Tick::ZERO), [1.0, 1.0]); } } + +#[cfg(test)] +mod played_tests { + use super::*; + use effectcraft_engine::color::Label; + use effectcraft_engine::project::{Comp, Footage, FootageKind, GroupKind, build}; + use effectcraft_engine::render::audio::{footage_peaks, mix_comp}; + use effectcraft_engine::render::{FootageSource, Image}; + use effectcraft_engine::time::FrameRate; + + /// Footage audio equal to its source time (seconds) on both channels over [0, 2) s. + struct Ramp; + impl FootageSource for Ramp { + fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { + None + } + fn audio(&self, _: ItemId, _: &Footage, start: Tick, frames: usize, rate: u32) -> Option> { + let t0 = start.seconds(); + Some( + (0..frames) + .flat_map(|k| { + let t = t0 + k as f64 / rate as f64; + let v = if (0.0..2.0).contains(&t) { t as f32 } else { 0.0 }; + [v, v] + }) + .collect(), + ) + } + } + + /// A project with a 2 s ramp clip and a comp holding one layer of it (start and in 0 s, + /// out 1 s) changed by `edit`, and the clip's peak summary. + fn setup(edit: &dyn Fn(&mut Layer)) -> (Project, ItemId, Layer, Summary) { + let mut p = Project::default(); + let f = Footage { + path: "ramp.wav".into(), + kind: FootageKind::Audio, + has_audio: true, + frame_rate: FrameRate::new(25, 1), + duration: Tick::from_seconds_f64(2.0), + ..Default::default() + }; + let fid = p.add_item("ramp.wav", Label::SeaFoam, None, ItemKind::Footage(f.clone())); + let mut comp = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0)); + let mut l = build::layer(&mut p, &comp, "a", LayerSource::Footage { item: fid }, (0, 0), None); + (l.start_time, l.in_point, l.out_point) = (Tick::ZERO, Tick::ZERO, Tick::from_seconds_f64(1.0)); + edit(&mut l); + comp.layers = vec![l.clone()].into(); + let cid = p.add_item("C", Label::Sandstone, None, ItemKind::Comp(comp.into())); + let peaks = footage_peaks(&Ramp, fid, &f, f.duration, BINS_PER_SEC); + (p, cid, l, Summary { bins_per_sec: BINS_PER_SEC, peaks }) + } + + fn add_backwards(l: &mut Layer, enabled: bool) { + let mut n = 1_000_000; + let mut g = build::Ids(&mut n).group("backwards", "Backwards"); + g.kind = GroupKind::Effect { effect: "ec.audio.backwards".into() }; + g.enabled = enabled; + l.props.group_mut("effects").expect("effects group").children.push(g.into()); + } + + /// The loudest left-channel peak drawn in the column for comp times `ta .. tb`. + fn drawn(l: &Layer, s: &Summary, ta: f64, tb: f64) -> Option { + played(l).and_then(|mirror| column_bins(l, s, ta, tb, mirror)).map(|bins| bins.iter().fold(f32::MIN, |m, b| m.max(b[1]))) + } + + /// The left-channel sample the mix plays at comp time `t`. + fn heard(p: &Project, cid: ItemId, t: f64) -> f32 { + mix_comp(p, &Ramp, None, cid, Tick::from_seconds_f64(t), 1, 8000).first().copied().unwrap_or(f32::NAN) + } + + /// #3238: a time-reversed layer (Time-Reverse Layer: stretch -100 %, start time at its out + /// point) is silent in the mix, so the Timeline draws no waveform columns for it. + #[test] + fn a_reversed_layer_draws_no_waveform_as_the_mix_is_silent() { + let (p, cid, l, s) = setup(&|l| { + l.stretch = -100.0; + l.start_time = Tick::from_seconds_f64(1.0); + }); + for k in 0..200 { + let (ta, tb) = (k as f64 / 200.0, (k + 1) as f64 / 200.0); + assert_eq!(drawn(&l, &s, ta, tb), None, "column at {ta} s"); + } + for t in [0.1, 0.5, 0.9] { + assert_eq!(heard(&p, cid, t), 0.0, "the mix plays the reversed layer at {t} s"); + } + } + + /// #3238: with the Backwards audio effect the first column shows the clip's last samples + /// and the last column its first, matching what the mix plays there. + #[test] + fn backwards_draws_the_waveform_mirrored_as_the_mix_plays_it() { + let (p, cid, l, s) = setup(&|l| add_backwards(l, true)); + let first = drawn(&l, &s, 0.0, 0.005).expect("first column"); + let h = heard(&p, cid, 0.0); + assert!(first > 0.98, "first column draws {first}, not the clip's last samples"); + assert!((first - h).abs() < 0.01, "first column {first}, heard {h}"); + let last = drawn(&l, &s, 0.995, 1.0).expect("last column"); + let h = heard(&p, cid, 0.995); + assert!(last < 0.02, "last column draws {last}, not the clip's first samples"); + assert!((last - h).abs() < 0.01, "last column {last}, heard {h}"); + } + + /// No Backwards effect, a disabled one, or the layer's Effects switch off: the mix plays + /// forwards, and so the waveform is drawn. + #[test] + fn without_an_active_backwards_effect_the_waveform_runs_forwards() { + let edits: [(&str, &dyn Fn(&mut Layer)); 3] = [ + ("no effect", &|_| {}), + ("effect disabled", &|l| add_backwards(l, false)), + ("effects switch off", &|l| { + add_backwards(l, true); + l.switches.effects = false; + }), + ]; + for (name, edit) in edits { + let (p, cid, l, s) = setup(edit); + let first = drawn(&l, &s, 0.0, 0.005).expect("first column"); + let h = heard(&p, cid, 0.004); + assert!(first < 0.02, "{name}: first column draws {first}"); + assert!((first - h).abs() < 0.01, "{name}: first column {first}, heard {h}"); + // A column reaching past the out point draws only up to it. + let edge = drawn(&l, &s, 0.998, 1.003).expect("edge column"); + assert!(edge < 1.001, "{name}: the edge column draws {edge}, past the out point"); + assert_eq!(drawn(&l, &s, 1.0, 1.005), None, "{name}: a column after the out point"); + } + } +} From 2d547200c02dc612ce6b125f3ea395430bdb55f7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:13:20 +0100 Subject: [PATCH 040/324] Effect Controls: Alt-click on a stopwatch adds an expression and edits it in the Timeline Refs #1460. As in After Effects, Alt-click (Option-click) on a stopwatch in Effect Controls adds an expression (it toggled keyframing instead) and Alt-click again removes it. Effect Controls has no expression field, so the property is revealed in the Timeline (the same reveal as a double-click on its name, #1497) and the new expression's editor takes the keyboard with the expression selected. The Timeline's stopwatch and Effect Controls share one helper for that focus request (expression_toggled). The editor takes a request from the pass after the one it was made in: drawn in the same pass as the Alt-click in another panel, its text field gave the keyboard straight back as a click elsewhere. --- .../src/panels/effect_controls/rows.rs | 30 +++++++++--- crates/ui-egui/src/panels/timeline.rs | 33 +++++++++---- crates/ui-egui/tests/it/ui_inline_edit.rs | 48 +++++++++++++++++++ 3 files changed, 94 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/panels/effect_controls/rows.rs b/crates/ui-egui/src/panels/effect_controls/rows.rs index c14630af4..e7f1bfee5 100644 --- a/crates/ui-egui/src/panels/effect_controls/rows.rs +++ b/crates/ui-egui/src/panels/effect_controls/rows.rs @@ -128,6 +128,18 @@ impl PropCx<'_> { } } +/// Shows property `uid` of layer `layer` in the Timeline: its layer and groups twirled open, the +/// property scrolled to and the Timeline brought forward (After Effects' Reveal in Timeline, +/// which a double-click on the property's name does; #1497). +fn reveal_in_timeline(app: &mut EffectcraftApp, ctx: &egui::Context, layer: u64, uid: u64) { + app.ui.timeline.search.clear(); + app.ui.timeline.scroll_to = Some(crate::state::ScrollTo::Property(uid)); + if let Err(e) = crate::menus::frontend(app, ctx, "timeline.revealProps", json!({"props": [{"layer": layer, "prop": uid}]})) { + app.ui.status = e; + } + app.show_panel(crate::dock::PanelKind::Timeline); +} + /// One property row: stopwatch, name, value control (and the keyframe navigator). Returns the /// value fields of a vector, one per dimension, for the pick whip. #[allow(clippy::too_many_arguments)] @@ -167,7 +179,16 @@ fn prop_row( }, ); app.auto.add(&format!("effectControls.prop.{uid}.stopwatch"), swr, &prop.name); - if resp.clicked() { + if resp.clicked() && ui.input(|i| i.modifiers.alt) { + // Alt+click adds an expression (or removes it), as in the Timeline. Effect Controls + // has no expression field: the property shows in the Timeline with its new + // expression's editor taking the keyboard, as After Effects does (#1460). + actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid}))); + if prop.expr.is_none() { + reveal_in_timeline(app, ui.ctx(), layer.id.0, uid); + } + crate::panels::timeline::expression_toggled(app, ui.ctx(), prop); + } else if resp.clicked() { actions.push(("prop.toggleAnimation".into(), json!({"layer": layer.id.0, "prop": uid, "selected": true}))); } } @@ -201,12 +222,7 @@ fn prop_row( p.with_clip_rect(name_clip.intersect(p.clip_rect())).text(pos2(swr.max.x + 6.0, cy), Align2::LEFT_CENTER, &prop.name, Tokens::ui(12.0), t.text); let name_response = ui.interact(name_clip, egui::Id::unique(("ec-prop-name", uid)), Sense::click()); if name_response.double_clicked() { - app.ui.timeline.search.clear(); - app.ui.timeline.scroll_to = Some(crate::state::ScrollTo::Property(uid)); - if let Err(e) = crate::menus::frontend(app, ui.ctx(), "timeline.revealProps", json!({"props": [{"layer": layer.id.0, "prop": uid}]})) { - app.ui.status = e; - } - app.show_panel(crate::dock::PanelKind::Timeline); + reveal_in_timeline(app, ui.ctx(), layer.id.0, uid); } app.auto.add(&format!("effectControls.prop.{uid}.name"), name_clip, &prop.name); // With several layers selected the edit applies to the same effect property of each (#491). diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs index 038dcc9b9..e7f8311c0 100644 --- a/crates/ui-egui/src/panels/timeline.rs +++ b/crates/ui-egui/src/panels/timeline.rs @@ -323,9 +323,27 @@ fn expr_focus_id() -> egui::Id { egui::Id::unique("tl-expr-focus") } +/// Asks the expression editor of property `prop` to take the keyboard when the Timeline next +/// draws it, selecting `select` (counts of characters before the end). fn focus_expression(ctx: &egui::Context, prop: u64, select: [usize; 2]) { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|d| d.insert_temp(expr_focus_id(), ExprFocus { prop, select, pass })); + // The editor takes it in a later pass: make sure one comes without waiting for input. + ctx.request_repaint(); +} + +/// After a `prop.setExpression` toggle of `prop` was queued (an Alt-click on its stopwatch, in the +/// Timeline or in Effect Controls): adding one, its editor opens, comes into view and takes the +/// keyboard with the new expression selected (#1072, #1460); removing it, a pending request for +/// its editor goes, as nothing is left to take the keyboard. +pub(crate) fn expression_toggled(app: &mut EffectcraftApp, ctx: &egui::Context, prop: &Property) { + let uid = prop.uid; + if prop.expr.is_none() { + app.ui.timeline.expr_closed.remove(&uid); + focus_expression(ctx, uid, [usize::MAX, 0]); + } else if ctx.data(|d| d.get_temp::(expr_focus_id())).is_some_and(|f| f.prop == uid) { + ctx.data_mut(|d| d.remove::(expr_focus_id())); + } } #[derive(Clone, Debug)] @@ -3927,7 +3945,10 @@ fn expr_editor_cell(app: &mut EffectcraftApp, ui: &mut egui::Ui, g: &mut Rw, rc: gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, t.expr_bg); let er = Rect::from_min_max(pos2(graph_x0 + 8.0, r.min.y + 3.0), pos2(rect.max.x - 14.0, r.max.y - 3.0)); let mut buf: String = ctx.data(|d| d.get_temp(buf_id)).unwrap_or_else(|| ex.text.clone()); - if let Some(f) = ctx.data(|d| d.get_temp::(expr_focus_id())).filter(|f| f.prop == *uid) { + // Not in the pass it was asked for in: a click that asked for it from another panel (an + // Alt-click on a stopwatch in Effect Controls, drawn before the Timeline) would take the + // keyboard straight back as a click elsewhere (#1460). + if let Some(f) = ctx.data(|d| d.get_temp::(expr_focus_id())).filter(|f| f.prop == *uid && ctx.cumulative_pass_nr() > f.pass) { // Asked for once (a pick whip put a reference in, or an Alt-click added the // expression): editing starts in the expression as it is now. ctx.data_mut(|d| d.remove::(expr_focus_id())); @@ -4079,15 +4100,7 @@ fn prop_stopwatch(app: &mut EffectcraftApp, ui: &mut egui::Ui, g: &mut Rw, rc: & if ui.input(|i| i.modifiers.alt) { if resp.clicked() { actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid}))); - if prop.expr.is_none() { - // Adding one: its editor opens, comes into view and takes the - // keyboard with the new expression selected (#1072). - app.ui.timeline.expr_closed.remove(uid); - focus_expression(&ctx, *uid, [usize::MAX, 0]); - } else if ctx.data(|d| d.get_temp::(expr_focus_id())).is_some_and(|f| f.prop == *uid) { - // Removing it: nothing is left to take the keyboard. - ctx.data_mut(|d| d.remove::(expr_focus_id())); - } + expression_toggled(app, &ctx, prop); } } else if let Some((value, merge)) = switch_gesture(ui, &resp, r, "stopwatch", prop.is_animated()) { actions.push(("prop.toggleAnimation".into(), json!({"layer": layer.id.0, "prop": uid, "value": value, "merge": merge}))); diff --git a/crates/ui-egui/tests/it/ui_inline_edit.rs b/crates/ui-egui/tests/it/ui_inline_edit.rs index 6c29045bb..8271e2f9e 100644 --- a/crates/ui-egui/tests/it/ui_inline_edit.rs +++ b/crates/ui-egui/tests/it/ui_inline_edit.rs @@ -634,6 +634,54 @@ fn an_expression_added_at_the_bottom_of_the_timeline_comes_into_view() { assert_eq!(expression(&h, layer, opacity).as_deref(), Some("25")); } +/// #1460: Alt-clicking an effect property's stopwatch in Effect Controls adds an expression, as in +/// the Timeline (it toggled the animation instead). Effect Controls has no expression field, so, +/// as in After Effects, the property shows in the Timeline (its layer and effect twirled open, +/// scrolled into view) with the new expression's editor taking the keyboard: typing replaces +/// it. Another Alt-click removes it and leaves nothing holding the keyboard. +#[test] +fn alt_clicking_a_stopwatch_in_effect_controls_edits_the_expression_in_the_timeline() { + let (mut h, _) = harness(); + let (layer, slider) = { + let s = &mut h.state_mut().session; + let l = s.execute("layer.newSolid", json!({"name": "Plate", "color": "#406080"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("effect.apply", json!({"layers": [l], "effect": "Slider Control"})).unwrap(); + // Layers above push it below the bottom of the Timeline. + for i in 0..40 { + s.execute("layer.newSolid", json!({"name": format!("Layer {i}"), "color": "#204060"})).unwrap(); + } + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + let slider = s.active_comp().unwrap().layer(effectcraft_engine::project::LayerId(l)).unwrap().props.prop("effects/#1/slider").unwrap().uid; + (l, slider) + }; + h.state_mut().show_panel(effectcraft_ui_egui::dock::PanelKind::EffectControls); + h.run_steps(3); + let editor = format!("timeline.prop.{slider}.expression"); + assert!(h.state().auto.find(&format!("timeline.prop.{slider}.row")).is_none(), "the property is not in the Timeline yet"); + let alt = Modifiers { alt: true, ..Modifiers::NONE }; + let at = center(&h, &format!("effectControls.prop.{slider}.stopwatch")); + click_with(&mut h, at, alt); + assert!(expression(&h, layer, slider).is_some(), "an expression was added"); + let key = h.state().session.active_comp().unwrap().layer(effectcraft_engine::project::LayerId(layer)).unwrap().props.find(slider).unwrap().is_animated(); + assert!(!key, "Alt-click doesn't turn on keyframing"); + assert!(h.state().ui.timeline.reveal_props.contains(&slider), "the property is revealed in the Timeline"); + let rows = h.state().auto.find("timeline.scroll").expect("the Timeline is shown").rect; + let e = h.state().auto.find(&editor).expect("the Timeline draws the expression editor").rect; + assert!(e[1] >= rows[1] - 0.5 && e[1] + e[3] <= rows[1] + rows[3] + 0.5, "the editor is in view: {e:?} in {rows:?}"); + type_text(&mut h, "42"); + commit_expression(&mut h); + assert_eq!(expression(&h, layer, slider).as_deref(), Some("42"), "typing replaced the new expression"); + // Alt-click again removes the expression and its editor with it (the keyboard stays free; + // the editor's focus request was taken when it was added, so this doesn't exercise the + // cancel path). + let at = center(&h, &format!("effectControls.prop.{slider}.stopwatch")); + click_with(&mut h, at, alt); + h.run_steps(5); + assert_eq!(expression(&h, layer, slider), None); + assert!(h.state().auto.find(&editor).is_none(), "the expression editor is gone"); + assert!(!h.ctx.egui_wants_keyboard_input(), "nothing has the keyboard"); +} + /// A primary-button drag from `from` to `to` with `modifiers` held from the press to the release. fn drag_with(h: &mut Harness<'_, EffectcraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { h.input_mut().events.push(Event::PointerMoved(from)); From 932326ced681040605017ee064fdbef0d4805fe1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 19:50:44 +0100 Subject: [PATCH 041/324] Doc comments for the functions this PR touches --- crates/ui-egui/src/panels/viewer.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index f17d11795..cc3666d6a 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -1130,6 +1130,7 @@ fn led_by_a_moved_ancestor(comp: &Comp, layers: &[MoveLayer]) -> Vec { layers.iter().map(|l| led(l.0)).collect() } +/// Starts the viewer drag gesture for the active tool from the press point, picking the layer, vertex or handle under it. fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let comp_rect = v.comp_rect; let zoom = v.zoom; From 8a479a4922dc246462556bce030aa669a052a3ef Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 19:52:49 +0100 Subject: [PATCH 042/324] Doc comments for the functions this PR touches --- apps/effectcraft-web/src/store.rs | 1 + crates/automation/src/confine.rs | 14 ++++++++++++++ crates/engine/src/background/remote.rs | 1 + crates/engine/src/cmd/path_nulls.rs | 2 ++ crates/engine/src/cmd/prop.rs | 2 ++ crates/engine/src/cmd/rig3d.rs | 1 + crates/engine/src/cmd/three_d.rs | 1 + crates/expr/src/host.rs | 1 + crates/expr/src/sample.rs | 2 ++ crates/media/src/pool.rs | 4 ++++ crates/media/src/reads.rs | 3 +++ crates/media/src/stream.rs | 2 ++ crates/project/src/reach.rs | 2 ++ crates/render/src/cache.rs | 8 ++++++++ crates/render/src/disk_cache.rs | 9 +++++++++ crates/render/src/disk_cache/entry_files.rs | 11 +++++++++++ crates/render/src/eval.rs | 1 + crates/render/src/footage.rs | 2 ++ crates/render/src/fx_host.rs | 1 + crates/render/src/pipeline.rs | 4 ++++ crates/render/src/reads.rs | 7 +++++++ crates/render/src/three_d/adv/scene.rs | 3 +++ crates/text/src/fonts.rs | 2 ++ crates/ui-egui/src/frames.rs | 9 +++++++++ crates/ui-egui/src/panels/viewer.rs | 1 + crates/ui-egui/src/panels/viewer/shapes.rs | 1 + 26 files changed, 95 insertions(+) diff --git a/apps/effectcraft-web/src/store.rs b/apps/effectcraft-web/src/store.rs index abda69a77..a4947600b 100644 --- a/apps/effectcraft-web/src/store.rs +++ b/apps/effectcraft-web/src/store.rs @@ -189,6 +189,7 @@ pub struct Store { } impl Default for Store { + /// An empty store with no mirror contents, change callback or clock. fn default() -> Self { Self { mirror: Mutex::default(), on_change: OnceLock::new(), clock: OnceLock::new() } } diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 55fa8043c..570726932 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -363,32 +363,41 @@ thread_local! { static REFUSED_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// The number of reads this thread has refused for lying outside the allowed roots. fn refused_reads() -> u64 { REFUSED_READS.try_with(std::cell::Cell::get).unwrap_or(0) } impl FootageSource for ConfinedFootage { + /// The frame from the inner source, or `None` when the footage lies outside the allowed roots. fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { self.readable(footage).then(|| self.inner.frame(item, footage, t)).flatten() } + /// The frame scaled to `width` by `height`, or `None` when the footage lies outside the allowed roots. fn frame_at_size(&self, item: ItemId, footage: &Footage, t: Tick, width: u32, height: u32) -> Option> { self.readable(footage).then(|| self.inner.frame_at_size(item, footage, t, width, height)).flatten() } + /// The frame with an explicit size and float curve, or `None` when the footage lies outside the allowed roots. fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { self.readable(footage).then(|| self.inner.frame_with(item, footage, t, size, float)).flatten() } + /// The footage audio from the inner source, or `None` when the footage lies outside the allowed roots. fn audio(&self, item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option> { self.readable(footage).then(|| self.inner.audio(item, footage, t, frames, rate)).flatten() } + /// The auxiliary channels of the footage frame, or `None` when the footage lies outside the allowed roots. fn aux(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { self.readable(footage).then(|| self.inner.aux(item, footage, t)).flatten() } + /// Forwards the auxiliary footage paths to the inner source. fn set_aux_footage(&self, paths: &[String]) { self.inner.set_aux_footage(paths) } + /// The 3D model for the footage, or `None` when the footage lies outside the allowed roots. fn model(&self, item: ItemId, footage: &Footage) -> Option> { self.readable(footage).then(|| self.inner.model(item, footage)).flatten() } + /// The rasterised vector footage at `scale`, or `None` when the footage lies outside the allowed roots. fn vector_frame(&self, item: ItemId, footage: &Footage, scale: f64) -> Option> { self.readable(footage).then(|| self.inner.vector_frame(item, footage, scale)).flatten() } @@ -411,12 +420,15 @@ impl FootageSource for ConfinedFootage { fn set_conform_folder(&self, folder: Option) { self.inner.set_conform_folder(folder) } + /// The inner source's cache budget. fn cache_budget(&self) -> Option { self.inner.cache_budget() } + /// Runs `f` under the inner source's cancel flag. fn cancellable(&self, cancel: &Arc, f: &mut dyn FnMut()) { self.inner.cancellable(cancel, f) } + /// Whether the inner source has been called off. fn called_off(&self) -> bool { self.inner.called_off() } @@ -632,10 +644,12 @@ mod tests { /// Reads every file, noting it. struct Noting; impl FootageSource for Noting { + /// Returns a 1x1 frame and notes the footage path it was asked for. fn frame(&self, _: ItemId, f: &Footage, _: Tick) -> Option> { NOTED.with(|n| n.borrow_mut().push(f.path.clone())); Some(Arc::new(Image::new(1, 1))) } + /// Runs `f`, then reports every path noted meanwhile to `reads` as a file with a missing stamp. fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { f(); for p in NOTED.with(|n| std::mem::take(&mut *n.borrow_mut())) { diff --git a/crates/engine/src/background/remote.rs b/crates/engine/src/background/remote.rs index 153bb324b..aea210ec5 100644 --- a/crates/engine/src/background/remote.rs +++ b/crates/engine/src/background/remote.rs @@ -289,6 +289,7 @@ struct Pending { pub const MAX_PASSES: u32 = 24; impl FrameServer { + /// A frame server over `footage` and the optional expression host, with an empty layer cache. pub fn new(footage: Arc, expr: Option>) -> FrameServer { FrameServer { footage, diff --git a/crates/engine/src/cmd/path_nulls.rs b/crates/engine/src/cmd/path_nulls.rs index a6b51c763..6da43afde 100644 --- a/crates/engine/src/cmd/path_nulls.rs +++ b/crates/engine/src/cmd/path_nulls.rs @@ -73,6 +73,8 @@ struct PathInfo { span: (f64, f64), } +/// Reads a mask or shape path at the current time and returns its comp-space vertices, value, expression reference and layer name. +/// Errors when the property is missing, is not a path or has no vertices. fn info(s: &Session, cid: ItemId, lid: LayerId, uid: Uid, cmd: &str) -> Result { let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?; let layer = comp.layer(lid).ok_or(EngineError::NoComp)?; diff --git a/crates/engine/src/cmd/prop.rs b/crates/engine/src/cmd/prop.rs index 70d123957..b23e73575 100644 --- a/crates/engine/src/cmd/prop.rs +++ b/crates/engine/src/cmd/prop.rs @@ -1380,6 +1380,8 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result { convert_one_expr(s, cid, lid, uid) } +/// Replaces the expression on one property with keyframes sampled from its evaluated values. +/// Returns the number of properties converted. fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result { let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone(); diff --git a/crates/engine/src/cmd/rig3d.rs b/crates/engine/src/cmd/rig3d.rs index e7852fbd2..58a4281a8 100644 --- a/crates/engine/src/cmd/rig3d.rs +++ b/crates/engine/src/cmd/rig3d.rs @@ -47,6 +47,7 @@ impl Env { fn of(s: &Session, cid: ItemId) -> Env { Env { time: s.time_of(cid), expr: s.expr.clone(), footage: s.footage.clone() } } + /// The evaluation context of `comp` in `proj` at the session's current time. fn ctx<'a>(&'a self, proj: &'a Project, cid: ItemId, comp: &'a Comp) -> EvalCtx<'a> { EvalCtx { project: proj, diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index de6bc4d7a..58d5d3bc2 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -418,6 +418,7 @@ fn set_view_camera(s: &mut Session, p: &Value) -> Result { Ok(json!({"view": v.id()})) } +/// Returns the active comp's 3D view state, with the comp size, for the 3D view commands. fn get_3d(s: &mut Session, p: &Value) -> Result { let cid = comp_id(s, p)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?; diff --git a/crates/expr/src/host.rs b/crates/expr/src/host.rs index b0abcaafa..43400ea1d 100644 --- a/crates/expr/src/host.rs +++ b/crates/expr/src/host.rs @@ -297,6 +297,7 @@ impl<'a> Resolver<'a> { } self.comp(c)?.layer(LayerId(l)) } + /// The evaluation context for comp `c` at time `t` seconds, or `None` when the comp does not exist. fn ctx_at(&self, c: u64, t: f64) -> Option> { let comp = self.comp(c)?; let same_comp = c == self.ctx.comp_id.0; diff --git a/crates/expr/src/sample.rs b/crates/expr/src/sample.rs index e097691de..38f617289 100644 --- a/crates/expr/src/sample.rs +++ b/crates/expr/src/sample.rs @@ -46,6 +46,8 @@ fn fingerprint(layer: &Layer) -> u64 { h.finish() } +/// Renders `layer` of `comp` at time `t` for an expression sample, before or after effects as `post` says. +/// Returns `None` once the nesting depth limit is reached. fn render(ctx: EvalCtx, comp: ItemId, layer: &Layer, post: bool, t: f64) -> Option { let depth = DEPTH.with(|d| *d.borrow()); if depth >= MAX_DEPTH { diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 4b7b05603..ab4a47568 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -110,6 +110,7 @@ struct Lru { } impl Lru { + /// The cached image and its read files for `k`, marking the entry as most recently used. fn get(&mut self, k: &Key) -> Option<(Arc, Arc)> { let e = self.map.get_mut(k)?; self.order.remove(&e.stamp); @@ -118,6 +119,7 @@ impl Lru { self.order.insert(e.stamp, k.clone()); Some((e.img.clone(), e.files.clone())) } + /// Stores an image with its read files under `k` and evicts the least recently used entries until the cache fits `budget` bytes. fn insert(&mut self, k: Key, img: Arc, files: Arc, budget: usize) { let bytes = img.data.len() * std::mem::size_of::() + 64; self.clock += 1; @@ -905,6 +907,8 @@ impl Inner { } } + /// Decodes the still image at `loc` and applies the footage alpha and float handling. + /// A placeholder path decodes to colour bars. fn decode_still(&self, loc: &Loc, footage: &Footage) -> Result { let op = AlphaOp::of(footage, loc.float); let path = &loc.key.path; diff --git a/crates/media/src/reads.rs b/crates/media/src/reads.rs index 29b2fafac..43ea209b8 100644 --- a/crates/media/src/reads.rs +++ b/crates/media/src/reads.rs @@ -64,6 +64,8 @@ enum Out<'a> { } impl Scope<'_> { + /// Starts collecting the files read on this thread into `out`. + /// At the nesting limit the scope stays closed and reports an incomplete list. fn open(out: Out<'_>) -> Scope<'_> { let opened = SCOPES .try_with(|s| match s.try_borrow_mut() { @@ -79,6 +81,7 @@ impl Scope<'_> { } impl Drop for Scope<'_> { + /// Ends the scope and hands the collected files to its output, marked incomplete when the scope could not be opened. fn drop(&mut self) { let files = if self.opened { SCOPES.try_with(|s| s.try_borrow_mut().ok().and_then(|mut s| s.pop())).ok().flatten() } else { None }; // A scope that could not open saw nothing: what it made can't name its files. diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 99b1cb774..0155b4acd 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -26,6 +26,7 @@ pub(crate) struct FileReader { #[cfg(any(unix, windows))] impl FileReader { + /// Opens `path` for reading and records its length and modification time. pub(crate) fn open(path: &Path) -> std::io::Result { #[cfg(test)] crate::count_open(path); @@ -87,6 +88,7 @@ pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStam Some((opened.map_err(Into::into), stamp)) } +/// Without a native file system there is no in-place source: always `None`. #[cfg(not(any(unix, windows)))] pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStamp)> { None diff --git a/crates/project/src/reach.rs b/crates/project/src/reach.rs index dd510f9db..4cfde8385 100644 --- a/crates/project/src/reach.rs +++ b/crates/project/src/reach.rs @@ -197,6 +197,8 @@ pub fn expression_reach(text: &str) -> ExprReach { expression_names(text).map_or(ExprReach::Anything, |(comps, footage)| ExprReach::Names { comps, footage }) } +/// The comp names and footage names an expression references by literal name. +/// Returns `None` when it can reach anything by a computed name or cannot be tokenised. fn expression_names(text: &str) -> Option<(Vec, Vec)> { let toks = tokens(text)?; let (mut comps, mut footage) = (Vec::new(), Vec::new()); diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 692a80576..a1bd85290 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -117,6 +117,7 @@ impl LayerCache { } } + /// The attached disk cache, if any. pub fn disk(&self) -> Option> { self.disk.lock().ok()?.clone() } @@ -137,6 +138,7 @@ impl LayerCache { } } + /// The attached virtual-file identity lookup, if any. fn virtual_id(&self) -> Option { self.virtual_id.lock().ok()?.clone() } @@ -329,6 +331,7 @@ struct Fetched { used: u64, } +/// The memory a buffer's pixels take, in bytes. fn buf_bytes(b: &Buf) -> usize { b.img.data.len().saturating_mul(std::mem::size_of::()) } @@ -346,12 +349,14 @@ struct Prefetched { } impl Prefetched { + /// Records a missed key for prefetching, up to a fixed bound. fn note_miss(&mut self, key: u128) { if !self.misses.contains(&key) && self.misses.len() < 1024 { self.misses.push(key); } } + /// Drops the prefetched entry for `key` and frees its bytes. fn remove(&mut self, key: u128) { if let Some(f) = self.ready.remove(&key) { self.bytes = self.bytes.saturating_sub(buf_bytes(&f.buf)); @@ -425,6 +430,7 @@ impl PrefetchStore { } impl LayerStore for PrefetchStore { + /// The prefetched layer for `key` with its read files, or `None` when it is not ready. fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { let found = { let mut s = self.st.lock().ok()?; @@ -459,6 +465,7 @@ impl LayerStore for PrefetchStore { Some((buf, files.to_read_files())) } + /// Queues the layer for writing to the persistent store the first time `key` is seen. fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, _since: u64) { let Ok(mut s) = self.st.lock() else { return }; if s.known.insert(key) { @@ -810,6 +817,7 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo /// Set Matte…)? Those layers are drawn by the reading layer's renderer, so the switches it /// passes down belong in the key (`Renderer::nested_look`). pub(crate) fn reads_layers(ctx: &EvalCtx, layer: &Layer) -> bool { + /// Whether any enabled layer-valued property of `layer` points at another layer. fn reads(ctx: &EvalCtx, layer: &Layer, g: &PropGroup, depth: usize) -> bool { depth < 32 && g.children.iter().any(|n| match n { diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 67fbc4a7c..c334c2011 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -300,6 +300,7 @@ struct Drops { } impl Drops { + /// Notes that the given paths were dropped, bumping the generation and tracking them for later checks. fn record(&mut self, paths: &[Arc]) { self.generation = self.generation.saturating_add(1); if self.last.len().saturating_add(paths.len()) > MAX_DROPPED_PATHS { @@ -320,6 +321,7 @@ impl Drops { } impl Queue { + /// Takes the next queued job, frames first, and releases the bytes it held. #[cfg(not(target_arch = "wasm32"))] fn pop(&mut self) -> Option { if let Some(j) = self.frames.pop_front() { @@ -1081,6 +1083,7 @@ fn with_files(files: &EntryFiles, pixels: Vec) -> Vec { out } +/// The writer thread: evicts to the limit at open, then drains the job queue until the cache is dropped. #[cfg(not(target_arch = "wasm32"))] fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { let (m, cv) = &*q; @@ -1208,12 +1211,15 @@ impl effectcraft_effects::roto::SegStore for DiskCache { } impl crate::cache::LayerStore for DiskCache { + /// The layer for `key` from the disk cache, or `None` when it is missing or stale. fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { DiskCache::get_layer(self, key, virtual_id).map(|(b, f)| (Arc::new(b), f)) } + /// Queues a layer write on the disk cache. fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, since: u64) { DiskCache::put_layer(self, key, buf, files, since); } + /// The current drop generation of the disk cache. fn drop_generation(&self) -> u64 { DiskCache::drop_generation(self) } @@ -1325,6 +1331,7 @@ fn encode_layer(b: &Buf) -> Vec { out } +/// Decodes a stored layer payload into a buffer, or `None` when it is too short or damaged. fn decode_layer(p: &[u8]) -> Option { if p.len() < 32 { return None; @@ -1357,6 +1364,7 @@ fn decode_layer(p: &[u8]) -> Option { /// Bump when rendering changes in a way that makes old disk entries wrong. const RENDER_VERSION: &str = "effectcraft-render-6"; +/// Feeds the `Debug` form of `v` into the hash, followed by a separator byte. fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { h.write(format!("{v:?}").as_bytes()); h.write(&[0xff]); @@ -1401,6 +1409,7 @@ pub fn comp_content_key(project: &effectcraft_project::Project, comp: effectcraf comp_content_key_for_renderer(project, comp, RENDER_VERSION) } +/// The content key of `comp` for one renderer: its settings, the comps and footage it uses, and the renderer name. fn comp_content_key_for_renderer(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId, renderer: &str) -> u128 { use effectcraft_project::ItemKind; let mut h = Hash128::default(); diff --git a/crates/render/src/disk_cache/entry_files.rs b/crates/render/src/disk_cache/entry_files.rs index 4ebd1f2e6..a36ca1033 100644 --- a/crates/render/src/disk_cache/entry_files.rs +++ b/crates/render/src/disk_cache/entry_files.rs @@ -63,14 +63,17 @@ impl EntryFiles { Some(EntryFiles(out)) } + /// The listed files. pub fn files(&self) -> &[EntryFile] { &self.0 } + /// The number of listed files. pub fn len(&self) -> usize { self.0.len() } + /// Whether no files are listed. pub fn is_empty(&self) -> bool { self.0.is_empty() } @@ -96,6 +99,7 @@ impl EntryFiles { self.0.iter().all(|f| file_unchanged(f, virtual_id)) } + /// Appends the list to `out` in little-endian binary form. pub(super) fn encode(&self, out: &mut Vec) { out.extend_from_slice(&(self.0.len() as u32).to_le_bytes()); for f in &self.0 { @@ -153,6 +157,7 @@ impl EntryFiles { } } +/// Whether the file still matches its stored stamp, by its native stamp or by its in-memory identity. fn file_unchanged(f: &EntryFile, virtual_id: Option>) -> bool { let from_memory = || virtual_id.and_then(|id| id(&f.path)); match f.stamp { @@ -167,20 +172,25 @@ fn file_unchanged(f: &EntryFile, virtual_id: Option>) -> bool struct Reader<'a>(&'a [u8]); impl<'a> Reader<'a> { + /// Takes the next `n` bytes, or `None` when fewer remain. fn take(&mut self, n: usize) -> Option<&'a [u8]> { let head = self.0.get(..n)?; self.0 = self.0.get(n..)?; Some(head) } + /// Reads one byte. fn u8(&mut self) -> Option { self.take(1)?.first().copied() } + /// Reads a little-endian `u32`. fn u32(&mut self) -> Option { Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) } + /// Reads a little-endian `u64`. fn u64(&mut self) -> Option { Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) } + /// Reads a little-endian `i128`. fn i128(&mut self) -> Option { Some(i128::from_le_bytes(self.take(16)?.try_into().ok()?)) } @@ -190,6 +200,7 @@ impl<'a> Reader<'a> { mod tests { use super::*; + /// A sample list of native, missing and virtual files for the tests. fn files() -> ReadFiles { [ ReadFile::new("/a.png", FileStamp::Native { len: 3, modified: Some(9) }), diff --git a/crates/render/src/eval.rs b/crates/render/src/eval.rs index e900ffa6e..5a0a3dea3 100644 --- a/crates/render/src/eval.rs +++ b/crates/render/src/eval.rs @@ -50,6 +50,7 @@ pub struct EvalCtx<'a> { } impl<'a> EvalCtx<'a> { + /// A context for `comp` at `time` with no expressions, footage, overrides or read log. pub fn new(project: &'a Project, comp_id: ItemId, comp: &'a Comp, time: Tick) -> EvalCtx<'a> { EvalCtx { project, comp_id, comp, time, expr: None, footage: None, property_overrides: &[], media_overrides: &[], reads: None } } diff --git a/crates/render/src/footage.rs b/crates/render/src/footage.rs index 04957b34e..0e17f152d 100644 --- a/crates/render/src/footage.rs +++ b/crates/render/src/footage.rs @@ -204,6 +204,7 @@ impl FootageSource for CancellableFootage<'_> { fn called_off(&self) -> bool { self.cancel.load(Ordering::Relaxed) || self.inner.called_off() } + /// Runs `f` with the inner source, collecting the files it reads into `reads`. fn recording(&self, reads: &ReadLog, f: &mut dyn FnMut()) { self.inner.recording(reads, f) } @@ -224,6 +225,7 @@ pub fn is_vector_footage(f: &Footage) -> bool { pub struct NoFootage; impl FootageSource for NoFootage { + /// Always `None`: there is no footage. fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { None } diff --git a/crates/render/src/fx_host.rs b/crates/render/src/fx_host.rs index 9b1700df8..3a6f1a34c 100644 --- a/crates/render/src/fx_host.rs +++ b/crates/render/src/fx_host.rs @@ -95,6 +95,7 @@ impl EffectHost for FxHost<'_, '_, '_> { Some(self.pixels(other, buf, false)) } + /// The audio of footage layer `id` from `start`, or `None` when the layer is not footage. fn audio(&self, id: u64, start: f64, frames: usize, rate: u32) -> Option> { let other = self.ctx.layer(effectcraft_project::LayerId(id))?; let LayerSource::Footage { item } = &other.source else { return None }; diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 6a0be930d..be3c3da8f 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -102,6 +102,7 @@ fn collapsed_instance(ctx: &EvalCtx, layer: &Layer, item: ItemId) -> Option<(Vec } impl<'a> Renderer<'a> { + /// A renderer over `project` and `footage` with the given options. pub fn new(project: &'a Project, footage: &'a dyn FootageSource, opts: RenderOpts) -> Renderer<'a> { Renderer { project, @@ -446,6 +447,7 @@ impl<'a> Renderer<'a> { } } + /// The evaluation context of `comp` at `t`, carrying this renderer's expressions, footage and read log. pub(crate) fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> { EvalCtx { project: self.project, @@ -936,6 +938,8 @@ impl<'a> Renderer<'a> { if per_pixel { Some(Arc::new(interpret_pixels(&img, f, self.pipe.linear_footage_space(f)))) } else { Some(img) } } + /// The footage frame at source time `t` after frame blending: the average of the source frames one comp frame spans, else a blend of the two neighbouring frames, else the plain frame. + /// Log scans are converted first, and blended frames are cached. fn footage_frame_raw(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option> { let mode = frame_blend_mode(ctx, layer); let float = self.pipe.float_curve(f); diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index 91a0b10bf..326554c5b 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -59,6 +59,7 @@ pub struct ReadFile { } impl ReadFile { + /// A file read with the given path and stamp. pub fn new(path: impl Into>, stamp: FileStamp) -> ReadFile { ReadFile { path: path.into(), stamp } } @@ -128,16 +129,19 @@ impl ReadFiles { self.files.get(i).map(|f| f.stamp) } + /// The number of files in the list. pub fn len(&self) -> usize { self.files.len() } + /// Whether the list holds no files. pub fn is_empty(&self) -> bool { self.files.is_empty() } } impl FromIterator for ReadFiles { + /// Collects files into a list, adding each in turn. fn from_iter>(iter: I) -> Self { let mut out = ReadFiles::default(); for f in iter { @@ -155,10 +159,12 @@ pub struct ReadLog { } impl ReadLog { + /// An empty read log. pub fn new() -> ReadLog { ReadLog::default() } + /// Locks the file list, recovering from a poisoned lock. fn lock(&self) -> std::sync::MutexGuard<'_, ReadFiles> { self.files.lock().unwrap_or_else(PoisonError::into_inner) } @@ -196,6 +202,7 @@ impl ReadLog { mod tests { use super::*; + /// A native file with the given length for the tests. fn file(path: &str, len: u64) -> ReadFile { ReadFile::new(path, FileStamp::Native { len, modified: Some(7) }) } diff --git a/crates/render/src/three_d/adv/scene.rs b/crates/render/src/three_d/adv/scene.rs index 9166dc4a4..6d2b071d5 100644 --- a/crates/render/src/three_d/adv/scene.rs +++ b/crates/render/src/three_d/adv/scene.rs @@ -477,6 +477,7 @@ fn clip_start(ctx: &EvalCtx, layer: &Layer, prop: &Property, lt: Tick) -> Tick { start } +/// Adds a model layer to the Advanced 3D scene with its material options, opacity and world transform. fn model_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { let lin = b.s.linear_io; let (opts, prim_mat) = model_options(ctx, layer, lin); @@ -651,6 +652,7 @@ pub fn extruded_meshes(ctx: &EvalCtx, layer: &Layer, p: &model::extrude::Extrude out } +/// Adds an extruded layer to the Advanced 3D scene with its card material, opacity and world transform. fn extruded_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, p: &model::extrude::ExtrudeParams, b: &mut Builder) { let base = card_material(ctx, layer); let opacity = (ctx.opacity(layer) as f32 * r.opacity_mul()).clamp(0.0, 1.0); @@ -694,6 +696,7 @@ fn card(b: &mut Builder, buf: &Buf, world: Mat4, mut mat: Material) { b.emit(&p, m, &|_| world); } +/// Adds a flat card layer to the Advanced 3D scene with its material, opacity and world transform. fn card_layer(r: &Renderer, ctx: &EvalCtx, layer: &Layer, b: &mut Builder) { let mut mat = card_material(ctx, layer); mat.opacity = (ctx.opacity(layer) as f32 * r.opacity_mul()).clamp(0.0, 1.0); diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index f9ad858eb..d199bf0ff 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -208,6 +208,7 @@ pub struct VMetrics { } impl Face { + /// The font file bytes, loaded once on first use, or `None` when they cannot be read. fn bytes(&self) -> Option<&[u8]> { self.bytes .get_or_init(|| match &self.info.data { @@ -356,6 +357,7 @@ fn db() -> &'static RwLock { }) } +/// Adds a face to the database and returns its id. fn push(db: &mut Db, info: FaceInfo) -> FaceId { let id = db.faces.len(); db.faces.push(Arc::new(Face { id, info, bytes: OnceLock::new(), file_meta: OnceLock::new(), shaper: OnceLock::new() })); diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index 14c3f32ef..c369d8194 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -180,6 +180,7 @@ struct Cached { struct DiskSince(std::sync::Weak, u64); impl DiskSince { + /// A marker for the drop generation of `dc` at the time of a render. fn of(dc: &Arc, generation: u64) -> DiskSince { DiskSince(Arc::downgrade(dc), generation) } @@ -294,6 +295,7 @@ impl Cache { self.gpu_bytes = self.gpu_bytes.saturating_sub(img.bytes()); } } + /// Removes the entry for `k` and releases its image. fn remove(&mut self, k: &FrameKey) { if let Some(i) = self.map.remove(k) { self.forget(&i.img); @@ -371,6 +373,7 @@ struct ContentKeyJobs { pending: VecDeque<(Arc, u64, u64)>, } +/// The content key of `comp` at `revision`, memoised per revision. 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; @@ -1183,6 +1186,7 @@ impl Frames { } } + /// Queues a background hash of `comp` at `revision`, coalescing rapid edits so only a bounded number of snapshots are kept. #[cfg(not(target_arch = "wasm32"))] fn request_content_key(&self, project: Arc, revision: u64, comp: u64) { let mut jobs = self.content_key_jobs.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1235,6 +1239,7 @@ impl Frames { self.cache.lock().map(|c| c.budget).unwrap_or(0) } + /// Drops every cached frame and purges the remote server, if there is one. pub fn clear(&self) { if let Some(r) = &self.remote { r.purge(); @@ -1428,6 +1433,7 @@ impl Frames { } } + /// A render worker sharing this cache's queue, cache and in-flight set. fn worker(&self) -> Worker { Worker { queue: self.queue.clone(), @@ -1701,6 +1707,7 @@ impl Worker { self.finish_key(job.key, job.urgent, img, files, since, t0); } + /// Stores a finished frame in the cache with its read files, records the render time for urgent jobs, then releases the job. fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, files: Option>, since: Option, t0: web_time::Instant) { if urgent && let Ok(mut l) = self.last.lock() { *l = t0.elapsed().as_secs_f64() * 1000.0; @@ -1769,12 +1776,14 @@ impl Worker { } } + /// Tells the cache that a GPU render succeeded. fn gpu_succeeded(&self) { if let Ok(mut c) = self.cache.lock() { c.gpu_succeeded(); } } + /// Whether GPU rendering is available and has not been retired. fn gpu_ready(&self) -> bool { !self.gpu_retired.load(Ordering::Acquire) && self.cache.lock().is_ok_and(|c| c.gpu_ready()) } diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index 1e214ab53..cd0006c0f 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -143,6 +143,7 @@ struct Vw<'a> { puppet_layers: Vec<(&'a Layer, super::puppet_tool::Overlay)>, } +/// Draws the viewer panel in `rect` for the active comp and handles its input. pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { let t = app.tokens; let ctx = ui.ctx().clone(); diff --git a/crates/ui-egui/src/panels/viewer/shapes.rs b/crates/ui-egui/src/panels/viewer/shapes.rs index 903abd42f..76892cbaf 100644 --- a/crates/ui-egui/src/panels/viewer/shapes.rs +++ b/crates/ui-egui/src/panels/viewer/shapes.rs @@ -200,6 +200,7 @@ fn bounds_of(pts: &[Pos2]) -> Option { Some(r) } +/// Creates the shape for a drag from `a` to `b` with the given tool, as a mask or as a shape layer. pub(super) fn create_shape(app: &mut EffectcraftApp, tool: Tool, a: [f64; 2], b: [f64; 2], mods: egui::Modifiers) { let Some(d) = shape_drag(app, tool, a, b, mods) else { return }; let (kind, (w, h), (cx, cy)) = (d.kind, (d.size[0], d.size[1]), (d.centre[0], d.centre[1])); From 4295717ca7f6e6d6285d01e8dd7feaf70f45cb4c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 23:24:43 +0100 Subject: [PATCH 043/324] Disk cache: cap the free-space reserve at 10 GB, skip encodes the limit refuses The reserve the cache leaves free on its disk was max(2 GB, 5% of the disk) (#2551). On a 4 TB disk with 190 GB free that is 200 GB, so a cache set to 20 GB had a limit of 0: every write was refused, the cache never held anything, and only a log warning said so. The reserve is now clamp(5% of the disk, 2 GB, 10 GB). It is there to keep the cache from filling the disk, not to keep a share of a large disk free: 10 GB leaves the system room to work on any disk, a small disk still keeps 2 GB, and a 100 GB disk keeps 5 GB as before. After Effects has only a maximum cache size and no reserve; a clamp keeps the floor for small disks, where a fixed 10 GB would take most of the space. Writes the limit refuses cost no work: DiskCache::accepts_writes (one atomic read) is checked before a frame is converted (put_disk_frame) and before frames and layers are compressed (put_frame, put_frame_f16, put_layer). The frame workers spent about 8 ms per frame and 14 ms per layer on encodes that were then refused. persist_missing returns at once at limit 0 instead of converting the RAM frames on every idle pass. Settings > Disk shows the limit in effect in MB under Maximum Disk Cache Size, with a note when free disk space lowers it (settings.disk.cacheLimit). --- crates/render/src/disk_cache.rs | 139 +++++++++++++++++++++++--- crates/ui-egui/src/frames.rs | 13 ++- crates/ui-egui/src/frames/tests.rs | 65 ++++++++++++ crates/ui-egui/src/panels/settings.rs | 82 ++++++++++++++- docs/preferences.md | 6 +- 5 files changed, 288 insertions(+), 17 deletions(-) diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index c334c2011..ef35a2415 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -353,6 +353,8 @@ pub struct DiskCache { failed: AtomicU64, /// Source files looked at to check frame and layer entries ([`DiskCache::file_checks`]). file_checks: AtomicU64, + /// Frame and layer entries compressed for a queued write ([`DiskCache::encodes`]). + encodes: AtomicU64, tmp_counter: AtomicU64, queue: Arc<(Mutex, Condvar)>, /// Layer buffers that took less than this to render are not written (ms). @@ -396,6 +398,19 @@ fn checksum(data: &[u8]) -> u64 { h } +/// The least free space the disk cache leaves on its disk. +const MIN_DISK_RESERVE: u64 = 2 << 30; +/// The most free space the disk cache leaves on its disk: 5% of a large disk is far more than +/// the system needs to keep working (on a 4 TB disk it held a 20 GB cache at 0 with 190 GB free). +const MAX_DISK_RESERVE: u64 = 10 << 30; + +/// The free space the disk cache leaves on a disk of `total` bytes: 5% of it, at least 2 GB and +/// at most 10 GB. It keeps the cache from filling the disk; the cache's size is the user's +/// Maximum Disk Cache Size (After Effects has that maximum and no reserve). +pub fn disk_reserve(total: u64) -> u64 { + (total / 20).clamp(MIN_DISK_RESERVE, MAX_DISK_RESERVE) +} + /// The platform's default disk cache folder. pub fn default_folder() -> PathBuf { let home = std::env::var_os("HOME").map(PathBuf::from); @@ -433,6 +448,7 @@ impl DiskCache { dropped: AtomicU64::new(0), failed: AtomicU64::new(0), file_checks: AtomicU64::new(0), + encodes: AtomicU64::new(0), tmp_counter: AtomicU64::new(0), queue: Arc::new(( Mutex::new(Queue { @@ -519,13 +535,14 @@ impl DiskCache { self.max_bytes().min(self.disk_cap.load(Ordering::Relaxed)) } - /// The cache's disk: `(total, available)` bytes, `None` = unknown. The cache leaves at least - /// 2 GB or 5% of the disk free, whichever is more (evicting when it must). + /// The cache's disk: `(total, available)` bytes, `None` = unknown. The cache leaves + /// [`disk_reserve`] free (5% of the disk, at least 2 GB and at most 10 GB), evicting when it + /// must. pub fn set_disk_space(&self, space: Option<(u64, u64)>) { let cap = match space { // (a disk reported as 0 bytes, such as an automount map, is unknown) Some((total, available)) if total > 0 => { - let reserve = (2u64 << 30).max(total / 20); + let reserve = disk_reserve(total); let used = self.index.lock().map(|g| g.total()).unwrap_or_default(); // The cache's own files count as free: below the reserve it gives space back. used.saturating_add(available).saturating_sub(reserve) @@ -540,6 +557,25 @@ impl DiskCache { self.evict(); } + /// Whether a write can be stored at all now: `false` while free disk space holds the limit + /// at 0. One atomic read, so frame and layer writes check it before they spend time + /// converting and compressing pixels that [`DiskCache::write_format`] would refuse anyway. + /// (Whether a given entry fits is known only once it is compressed: `write_format` decides.) + pub fn accepts_writes(&self) -> bool { + self.limit_bytes() > 0 + } + + /// Frame and layer entries compressed for writing so far (tests: a write refused up front + /// costs no encode). + pub fn encodes(&self) -> u64 { + self.encodes.load(Ordering::Relaxed) + } + + /// Count one entry compressed for a queued write. + fn count_encode(&self) { + self.encodes.fetch_add(1, Ordering::Relaxed); + } + /// Layer buffers faster to render than this are not worth a disk write. pub fn set_min_layer_ms(&self, ms: u64) { self.min_layer_ms.store(ms, Ordering::Relaxed); @@ -950,8 +986,9 @@ impl DiskCache { /// Queue a half-float frame for writing (`width * height * 4` binary16 values) with the /// source files it was made of. `true` when it is on disk or queued; `false` when refused - /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]; - /// a file dropped after `since`, the [`DiskCache::drop_generation`] the render started at). + /// (wrong size, a full queue, no room on the disk, files that can't be checked later: see + /// [`EntryFiles::of`]; a file dropped after `since`, the [`DiskCache::drop_generation`] the + /// render started at). #[allow(clippy::too_many_arguments)] pub fn put_frame_f16( &self, @@ -967,8 +1004,16 @@ impl DiskCache { return false; } let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; + if self.contains(Kind::Frame, key) { + return true; + } + // (no room on the disk: refused before the pixels are compressed) + if !self.accepts_writes() { + return false; + } + self.count_encode(); let payload = with_files(&files, encode_frame_f16(width, height, rgba)); - self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, payload, Some((&files, since))) + self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, payload, Some((&files, since))) } /// Write a half-float frame synchronously (tests); a list that can't be stored is not. @@ -980,16 +1025,25 @@ impl DiskCache { /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes) with the /// source files it was made of. `true` when it is on disk or queued; `false` when refused - /// (wrong size, a full queue, files that can't be checked later: see [`EntryFiles::of`]; - /// a file dropped after `since`, the [`DiskCache::drop_generation`] the render started at). + /// (wrong size, a full queue, no room on the disk, files that can't be checked later: see + /// [`EntryFiles::of`]; a file dropped after `since`, the [`DiskCache::drop_generation`] the + /// render started at). #[allow(clippy::too_many_arguments)] pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>, since: u64) -> bool { if rgba.len() as u64 != width as u64 * height as u64 * 4 { return false; } let Some(files) = EntryFiles::of(files, virtual_id) else { return false }; + if self.contains(Kind::Frame, key) { + return true; + } + // (no room on the disk: refused before the pixels are compressed) + if !self.accepts_writes() { + return false; + } + self.count_encode(); let payload = with_files(&files, encode_frame(width, height, rgba)); - self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, payload, Some((&files, since))) + self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, payload, Some((&files, since))) } /// A layer buffer (key: [`layer_disk_key`]) whose source files are unchanged, with those @@ -1005,10 +1059,12 @@ impl DiskCache { /// when one of them was dropped after `since`, the [`DiskCache::drop_generation`] its render /// started at. pub fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles, since: u64) { - if self.contains(Kind::Layer, key) { + // (no room on the disk: refused before the buffer is compressed) + if self.contains(Kind::Layer, key) || !self.accepts_writes() { return; } - let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, with_files(files, encode_layer(buf)), Some((files, since))); + self.count_encode(); + let _ =self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, with_files(files, encode_layer(buf)), Some((files, since))); } /// Write a layer buffer synchronously (tests); a list that can't be stored is not. @@ -1785,7 +1841,8 @@ mod tests { // A disk reported as 0 bytes is unknown. dc.set_disk_space(Some((0, 0))); assert_eq!(dc.stats().limit_bytes, 1 << 30); - // 100 GB disk, 5 GB reserved, exactly 5 GB free: the cache may not grow. + // 100 GB disk, 5 GB reserved (5%, between the 2 GB floor and the 10 GB cap), exactly + // 5 GB free: the cache may not grow. dc.set_disk_space(Some((100 << 30, 5 << 30))); let st = dc.stats(); assert_eq!((st.max_bytes, st.limit_bytes), (1 << 30, used)); @@ -1804,6 +1861,64 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The reserve is 5% of the disk, at least 2 GB and at most 10 GB: a large disk with plenty + /// free keeps the user's size. (A 4 TB disk with 190 GB free reserved 200 GB, held a 20 GB + /// cache at 0, and every write was refused.) + #[test] + fn a_large_disk_reserves_at_most_ten_gb() { + const GB: u64 = 1 << 30; + assert_eq!(disk_reserve(4096 * GB), 10 * GB); + assert_eq!(disk_reserve(100 * GB), 5 * GB); + assert_eq!(disk_reserve(32 * GB), 2 * GB); + assert_eq!(disk_reserve(1), 2 * GB); + let dir = tmpdir("space-large"); + let dc = DiskCache::open(&dir, 20 * GB).unwrap(); + dc.set_disk_space(Some((4096 * GB, 190 * GB))); + let st = dc.stats(); + assert_eq!((st.max_bytes, st.limit_bytes), (20 * GB, 20 * GB), "{st:?}"); + assert!(dc.accepts_writes()); + // Just above the 10 GB reserve: the cache may use what is left above it. + dc.set_disk_space(Some((4096 * GB, 15 * GB))); + assert_eq!(dc.stats().limit_bytes, 5 * GB); + // A small disk still keeps 2 GB free: 3 GB free leaves 1 GB for the cache. + dc.set_disk_space(Some((32 * GB, 3 * GB))); + assert_eq!(dc.stats().limit_bytes, GB); + // Below the floor: nothing. + dc.set_disk_space(Some((32 * GB, GB))); + assert_eq!(dc.stats().limit_bytes, 0); + assert!(!dc.accepts_writes()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A write the free disk space refuses is refused before its pixels are compressed: the + /// frame workers spent about 8 ms per frame and 14 ms per layer encoding entries that were + /// then refused (`limit_bytes=0`). + #[test] + fn no_encode_while_the_disk_has_no_room() { + const GB: u64 = 1 << 30; + let dir = tmpdir("space-no-encode"); + let dc = DiskCache::open(&dir, 20 * GB).unwrap(); + // 4 TB disk, 1 GB free: under the 10 GB reserve, the limit is 0. + dc.set_disk_space(Some((4096 * GB, GB))); + assert_eq!(dc.stats().limit_bytes, 0); + let rgba = vec![7u8; 16 * 16 * 4]; + assert!(!dc.put_frame(1, 16, 16, &rgba, &ReadFiles::default(), None, 0), "refused"); + assert!(!dc.put_frame_f16(2, 16, 16, &[0x3c00u16; 16 * 16 * 4], &ReadFiles::default(), None, 0), "refused"); + dc.put_layer(3, &buf(3, 16, 16), &EntryFiles::default(), 0); + dc.flush(); + assert_eq!(dc.encodes(), 0, "nothing compressed"); + assert_eq!(dc.stats().entries, 0); + // Room again: the same writes are compressed and stored. + dc.set_disk_space(Some((4096 * GB, 500 * GB))); + assert!(dc.put_frame(1, 16, 16, &rgba, &ReadFiles::default(), None, 0)); + assert!(dc.put_frame_f16(2, 16, 16, &[0x3c00u16; 16 * 16 * 4], &ReadFiles::default(), None, 0)); + dc.put_layer(3, &buf(3, 16, 16), &EntryFiles::default(), 0); + dc.flush(); + assert_eq!(dc.encodes(), 3); + assert_eq!(dc.stats().entries, 3); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn failed_writes_are_counted() { let dir = tmpdir("failed"); diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index c369d8194..6bca00ff9 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -477,9 +477,10 @@ fn frame_disk_key(keys: &ContentKeys, project: &Project, key: &FrameKey, opts_ha /// Queue `img` for the disk cache under `dk` with the source files it was made of. `false` when /// refused: a GPU frame (no CPU pixels), files that can't be checked when the entry is read /// (an incomplete list, #3184: the frame is shown, not stored), a full queue, a file dropped -/// (File ▸ Reload Footage) after `since`, the drop generation its render started at. +/// (File ▸ Reload Footage) after `since`, the drop generation its render started at; no room on +/// the disk (checked first: the conversion and compression would be wasted). fn put_disk_frame(dc: &DiskCache, dk: u128, img: &FrameImage, files: &ReadFiles, virtual_id: Option>, since: u64) -> bool { - if !files.is_complete() { + if !files.is_complete() || !dc.accepts_writes() { return false; } match img { @@ -1057,7 +1058,13 @@ impl Frames { let oh = opts_hash(opts); self.note_disk_series(base.comp, base.scale, base.view ^ oh); self.carry_disk(src); - let known = self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp)).copied(); + // Free disk space holds the cache at 0: nothing would be stored, so nothing is converted + // (a refusal doesn't count as a try, so every idle pass would convert them all again). + // A later idle pass writes them once there is room. + if !dc.accepts_writes() { + return false; + } + let known =self.content_keys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(base.revision, base.comp)).copied(); let Some(content) = known else { self.request_content_key(src.project.clone(), base.revision, base.comp); return true; diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index 13fda15e8..9f8c55a64 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -1732,6 +1732,71 @@ fn ram_frames_missing_on_disk_are_written_as(half: bool) { let _ = std::fs::remove_dir_all(&dir); } +/// While free disk space holds the disk cache at 0, frames are not converted or compressed for +/// it (the frame workers spent about 8 ms per frame on writes that were then refused), and idle +/// passes don't keep converting the RAM frames; with room again they are written. +#[test] +fn no_frame_is_encoded_while_the_disk_has_no_room() { + use effectcraft_engine::Session; + use serde_json::json; + const GB: u64 = 1 << 30; + let dir = std::env::temp_dir().join(format!("ec-persist-full-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let disk = DiskCache::open(&dir, 20 * GB).unwrap(); + // 4 TB disk, 1 GB free: under the 10 GB reserve. + disk.set_disk_space(Some((4096 * GB, GB))); + assert!(!disk.accepts_writes()); + // The frame worker's write: refused up front. + assert!(!put_disk_frame(&disk, 1, &img(), &ReadFiles::default(), None, disk.drop_generation())); + let mut s = Session::default(); + let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 1})).unwrap()["comp"].as_u64().unwrap()); + s.execute("layer.newSolid", json!({})).unwrap(); + let src = RenderSource { + project: s.project.clone(), + footage: Arc::new(effectcraft_engine::render::NoFootage), + expr: None, + layer_cache: Arc::default(), + gpu: None, + gpu_display: false, + disk: Some(disk.clone()), + }; + let f = Frames::default(); + let series = + FrameKey { revision: 1, content: f.content_of(&src.project, 1, cid), comp: cid.0, opts: opts_hash(&RenderOpts::default()) ^ 1, ..key(0, 0, 0) }; + for fr in 0..10 { + f.cache.lock().unwrap().insert_with(FrameKey { frame: fr, ..series }, img(), Some(Arc::default()), Some(DiskSince::of(&disk, disk.drop_generation()))); + } + // Idle passes: nothing to do, nothing converted. + for _ in 0..20 { + assert!(!f.persist_missing(&src, &series, &RenderOpts::default()), "no idle passes while there is no room"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + disk.flush(); + assert!(f.persisted.lock().unwrap().is_empty()); + assert_eq!((disk.encodes(), disk.stats().entries), (0, 0)); + // Room again: the RAM frames are written. + disk.set_disk_space(Some((4096 * GB, 500 * GB))); + let on_disk = |fr: i64| { + disk.contains( + disk_cache::Kind::Frame, + frame_disk_key(&f.content_keys, &src.project, &FrameKey { frame: fr, ..series }, opts_hash(&RenderOpts::default())), + ) + }; + let mut written = false; + for _ in 0..1000 { + f.persist_missing(&src, &series, &RenderOpts::default()); + disk.flush(); + if (0..10).all(on_disk) && f.persisted.lock().unwrap().is_empty() { + written = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(written, "every RAM frame written once there is room"); + assert_eq!(disk.encodes(), 10); + let _ = std::fs::remove_dir_all(&dir); +} + /// Audio changes pixels only where something draws it: a clip's Audio Levels, audio effects and /// Audio switch keep every frame, in RAM and on disk, until a waveform picks the clip (on another /// layer, on itself, or through a precomp of it); then the frames of the reader render again. diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 72564f112..2dba45855 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -5,7 +5,8 @@ //! //! Automation ids: `settings.page.`, `settings.` (e.g. `settings.general.undoLevels`), //! `settings.labels..name` / `.color`, `settings.button.

xy;iMsxRNT%zw4l0v=V6 zg|`)jnBuNNhcvEkEAX{_r$hE>x!i+lDBl?%G-XLk@wNW~d=l~o3@G`uBvZ(}hV-k^elh|rIOfW$#0D^NvusXH(gZz*qr>q!VTAW|tUsIt416HLL8G~;&#_ZTkb38{=hDM<9Ge4^ZkPhefnxXCeIbwz5Uk*i9n`ta-Yk7 z{I%Of6yhgf6GcnZ#=@a@8d7DC};q zmr~EwCZ-*ntHXNF`<5{4mJi9~lnf;Si074Oulx*!D&gDlmfH^umvtx&D)?<%loAxR ziwMAk`Px4GhBIB19HxA#e$r1Beb5L^2&0+3{lOE`lmrZX#eQ7IFr8!ZGB7iJ`ao!p9uEY8r5A0Q@Bl(6dC~W0+t{sB5Q{X6sO>$ z>#pU?qwxT5$B8M>p8L)F0bh3G%l8J#a>GP1gwDW6x8bq-K&Bo{0_cPw;do&bEkTBl zsQ|{=dTZRtNC;hriIf6RvE; z0?^G_o8@IawOWgVs`!Hxn$PmluWBX^Qz*#UUCQSMdSgC%%Uei?KhzNRS-;`iGknOIomb?Mfe5`B-aG@|$ zJ|`xIBhOenJ4-_~JKgYI>T%8;fd76;PnM&M^7@ug|G5MD<$@I=#g2J79M}7u$V{ST zTmC-z&U~Q!Y8yN;ZV4QXLf`NNPP%|QwrIe3n^r((wLE9H&lF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pFh) z0#8(2sw%9Ojl8IH+CAn9SrlZ+NV5V0;>8|EoyoRBeb^+u%4zeWVe*XiIHk5`o%(?A zCPXCL{}oY^0}P!T1qDR~H&mD+`dL25!@=WTc4a1wgMOHURKD+Hu@4Vx-XzeOw&EJ_ zuw51VY2d!yD-g!}&rM7e?JV|qX`S!)m%TqXgK-yGz3aUg-Ygqqc&m_&w)vf(e3kH2 zj7#$y-g3dp5s{9w5>CjQdlSyW+XR6GpeB($QB6uwefFz+Cn{X3u1!?@Y^vXp#`b2- zbOvjvfntFl-v*0g#g{o}=c>;vF5V6x%?D`Djua#V=240;qtG<&L@zN{VaF^~Vl0P~ zgbpHF@(Q)JIUgHi2ajk99Vij01Uum|8oQvR^2<|JZ#p0KzI>48P_1Wqsk>ApyuJ8j ziA>6ZwD$*_D?H~p9Ho_Q1rTcf=gPft#oPG+BLFV6 zSG#WM)BlMQzo!94n_#AT=KN#U0;w+cQ?1FoI=O?xI203<3luHGv)kjrIUzwP37gFy zExWq`n0kcmEt94>8+C30Mtopnx4Cksl;#?MYn@H|7=RbYgZBu+MFqF6Ig ztD=O;&(}`DbZb9XmJ0Gp7HC#$!Bz7YQ&3k>fzd~S|$1Wn|Z+0I&`4u!c2~y ztdpWyI`x4_o*|`Sov3!0(SA(|+_BqC*=oYcv9`G11nnG+Uh*{8-?$PIX;0I!yJf{d zbVZisq6>aZMEZ$*gSFMk#o6ZL*N$booOwg^1A@Wu$nr@sKJ~{h-JCBNzuDiL2rLd8 zU(mJ4dnMs<)9!6^4RS%~gR5a+R7XbE0^evgYDMhJ;9>jZ1}zz1Wi^gGC6`OJ*_lY? e*pl5P0qF976hunC>nOJ44?ek!#0{X^+W!CyG+68a literal 0 HcmV?d00001 diff --git a/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture.attribution b/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture.attribution new file mode 100644 index 000000000..3f385a1e4 --- /dev/null +++ b/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture.attribution @@ -0,0 +1,7 @@ +asset: pce61-ffmpeg.aac-fixture +title: Synthetic seven-channel AAC PCE tone fixture +author: Dylan M. Taylor +source: crates/media/tests/fixtures/README.md (reproducible generation recipe) +license: MIT OR Apache-2.0 +added: 2026-11-16 +notes: Original sine-wave signals, no recorded audio or copied assets. Encoded using FFmpeg 7.1.5. SHA-256 07c460636dce4aa4163df8ef35f3b76f1214c38bf217aacd23243e608d87071e. diff --git a/crates/media/tests/it/aac_layout.rs b/crates/media/tests/it/aac_layout.rs index 896e4f0a7..5adf762b2 100644 --- a/crates/media/tests/it/aac_layout.rs +++ b/crates/media/tests/it/aac_layout.rs @@ -1,7 +1,8 @@ //! Multichannel AAC reaches stereo by where each channel plays, whatever order its channel -//! configuration decodes in (#1701). Fixtures are tones encoded with craft-audio's AAC encoder (no -//! ffmpeg needed, so nothing is skipped), with the configuration rewritten where the coded -//! elements fit another: configurations 11 and 12 code the same elements as the encoder's 7- and +//! configuration decodes in (#1701). Fixtures are tones encoded with craft-audio's AAC encoder, +//! plus a checked-in genuine FFmpeg-generated 6.1-channel fixture (no external tool at test time, nothing skipped). +//! The configuration is rewritten only where the coded elements fit another: configurations 11 +//! and 12 code the same elements as the encoder's 7- and //! 8-channel output, and a program config element can name any of them. use std::f64::consts::PI; @@ -9,7 +10,7 @@ use std::io::Cursor; use std::path::PathBuf; use std::sync::Arc; -use craft_audio::aac::{AudioSpecificConfig, Encoder, EncoderConfig, ProgramConfig}; +use craft_audio::aac::{AudioSpecificConfig, Encoder, EncoderConfig}; use effectcraft_media::{MediaPool, probe, probe_bytes}; use effectcraft_time::Tick; @@ -59,13 +60,6 @@ fn lc(config: u8) -> Option { Some(AudioSpecificConfig::lc(3, config)) } -fn pce(front: Vec<(bool, u8)>, side: Vec<(bool, u8)>, back: Vec<(bool, u8)>, lfe: Vec, comment: &[u8]) -> Option { - let pce = ProgramConfig { object_type: 1, sf_index: 3, front, side, back, lfe, comment: comment.to_vec(), ..Default::default() }; - let mut asc = AudioSpecificConfig::lc(3, 0); - asc.pce = Some(pce); - Some(asc) -} - use Ch::*; fn cases() -> Vec { @@ -80,15 +74,9 @@ fn cases() -> Vec { Case { name: "config12", content: &[C, L, R, Ls, Rs, Ls, Rs, Lfe], asc: lc(12) }, // the encoder's own 6.1: a PCE listing the centre first Case { name: "pce61-centre-first", content: &[C, L, R, Ls, Rs, Cs, Lfe], asc: None }, - // ffmpeg's 6.1 PCE: front pair and centre, a side SCE, a back pair and SCE, no LFE - // element, its channels in ffmpeg's order L R C LFE Cs Ls Rs. The decoder places the - // encoder's SCE 0 in the front SCE, pair 0 front, pair 1 back, SCE 1 in the back SCE (tag - // 1) and the LFE in the side SCE left over (tag 5). - Case { - name: "pce61-ffmpeg", - content: &[C, L, R, Cs, Ls, Rs, Lfe], - asc: pce(vec![(true, 0), (false, 0)], vec![(false, 5)], vec![(true, 1), (false, 1)], vec![], b"Lavc62.28.102"), - }, + // A genuine FFmpeg-generated 6.1-channel PCE and matching coded elements; rewriting only the ASC of + // our encoder's LFE0 stream to claim a side SCE5 would make an invalid access unit. + Case { name: "pce61-ffmpeg", content: &[C, L, R, Cs, Ls, Rs, Lfe], asc: None }, ] } @@ -110,6 +98,32 @@ fn encode(content: &[Ch], adts: bool) -> (Vec, Vec>) { (enc.audio_specific_config(), units) } +/// Preserve the fixture's real element types/tags instead of changing only its ASC. +/// The envelope and reproducible tone-generation recipe are in `tests/fixtures/README.md`. +fn encode_case(case: &Case) -> (Vec, Vec>) { + if case.name == "pce61-ffmpeg" { + let bytes = include_bytes!("../fixtures/pce61-ffmpeg.aac-fixture"); + assert_eq!(&bytes[..4], b"PCE1"); + let mut rest = &bytes[4..]; + let mut record = || { + let len = u32::from_be_bytes(rest[..4].try_into().unwrap()) as usize; + let (data, tail) = rest[4..].split_at(len); + rest = tail; + data.to_vec() + }; + let asc = record(); + let mut units = Vec::new(); + // The generated fixture contains 95 access units (including encoder priming). + for _ in 0..95 { + units.push(record()); + } + assert!(rest.is_empty(), "fixture has no unparsed records"); + return (asc, units); + } + let (asc, units) = encode(case.content, false); + (case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")), units) +} + fn mp4(asc: Vec, channels: u32, units: &[Vec]) -> Vec { mp4_after(None, asc, channels, units) } @@ -211,8 +225,7 @@ fn lfe_is_coded(case: &Case, bytes: Vec) { #[test] fn every_aac_layout_mixes_by_speaker_in_mp4() { for case in cases() { - let (asc, units) = encode(case.content, false); - let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")); + let (asc, units) = encode_case(&case); let bytes = mp4(asc, case.content.len() as u32, &units); lfe_is_coded(&case, bytes.clone()); let p = write(&format!("{}.mp4", case.name), &bytes); @@ -228,8 +241,7 @@ fn every_aac_layout_mixes_by_speaker_in_mp4() { #[test] fn matroska_aac_layouts_mix_by_speaker() { for case in cases().into_iter().filter(|c| matches!(c.name, "config12" | "pce61-centre-first" | "pce61-ffmpeg")) { - let (asc, units) = encode(case.content, false); - let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")); + let (asc, units) = encode_case(&case); let p = write(&format!("{}.mkv", case.name), &mkv(asc, case.content.len() as u32, &units)); check(case.name, case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe"))); } @@ -254,8 +266,7 @@ fn an_empty_audio_track_lends_its_configuration_to_no_other() { let case = cases().into_iter().find(|c| c.name == name).expect("case"); let n = case.content.len() as u32; let empty = Some((AudioSpecificConfig::lc(3, empty).to_bytes().expect("ASC"), n)); - let (asc, units) = encode(case.content, false); - let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")); + let (asc, units) = encode_case(&case); let p = write(&format!("{name}-after-empty.mp4"), &mp4_after(empty.clone(), asc.clone(), n, &units)); check(&format!("{name} MP4"), case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe"))); let p = write(&format!("{name}-after-empty.mkv"), &mkv_after(empty, asc, n, &units)); From b6d2598b3f217b2bbeb8b6ec86302941cfe21bc5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 11:27:30 -0500 Subject: [PATCH 203/324] interchange: delegate lexical depth preflight to craft-timeline --- Cargo.lock | 18 ++++++++ Cargo.toml | 1 + crates/interchange/Cargo.toml | 1 + crates/interchange/src/import.rs | 73 +------------------------------- 4 files changed, 21 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a38c653da..397da745e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1603,6 +1603,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76#a2560df05b4c58631f53a57e65fb05f0e0e6cf76" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-time" version = "0.1.0" @@ -1623,6 +1632,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76#a2560df05b4c58631f53a57e65fb05f0e0e6cf76" +dependencies = [ + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76)", +] + [[package]] name = "craft-timeline" version = "0.1.0" @@ -2252,6 +2269,7 @@ dependencies = [ name = "effectcraft-interchange" version = "0.24.1" dependencies = [ + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76)", "effectcraft-color", "effectcraft-keyframe", "effectcraft-project", diff --git a/Cargo.toml b/Cargo.toml index 6c0fc585d..a7441a26b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] +craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "a2560df05b4c58631f53a57e65fb05f0e0e6cf76", default-features = false } craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/interchange/Cargo.toml b/crates/interchange/Cargo.toml index 11dfec333..e2caa613d 100644 --- a/crates/interchange/Cargo.toml +++ b/crates/interchange/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-timeline = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } effectcraft-keyframe = { workspace = true } diff --git a/crates/interchange/src/import.rs b/crates/interchange/src/import.rs index 5dd5642ac..a5336f406 100644 --- a/crates/interchange/src/import.rs +++ b/crates/interchange/src/import.rs @@ -49,78 +49,7 @@ pub struct ImportResult { /// a few levels per nested sequence; parsing several thousand levels overflowed the stack. pub const MAX_DEPTH: usize = 256; -/// The deepest element nesting of an XML document (a quick scan that skips comments, CDATA, -/// processing instructions, declarations and quoted attribute values). -pub(crate) fn xml_depth(b: &[u8]) -> usize { - let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize); - let skip_to = |from: usize, end: &[u8]| b.get(from..).and_then(|r| r.windows(end.len()).position(|w| w == end)).map_or(b.len(), |p| from + p + end.len()); - while let Some(&c) = b.get(i) { - if c != b'<' { - i += 1; - continue; - } - let rest = b.get(i..).unwrap_or_default(); - if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else { - // A start tag: find its end outside quotes; `/>` closes it at once. - let mut j = i + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match quote { - Some(q) if c == q => quote = None, - Some(_) => {} - None if c == b'"' || c == b'\'' => quote = Some(c), - None if c == b'>' => break, - None => {} - } - j += 1; - } - if b.get(j.wrapping_sub(1)) != Some(&b'/') { - depth += 1; - max = max.max(depth); - } - i = j + 1; - } - } - max -} - -/// The deepest array / object nesting of a JSON document (strings skipped). -pub(crate) fn json_depth(b: &[u8]) -> usize { - let (mut depth, mut max, mut in_str, mut esc) = (0usize, 0usize, false, false); - for &c in b { - if in_str { - if esc { - esc = false; - } else if c == b'\\' { - esc = true; - } else if c == b'"' { - in_str = false; - } - continue; - } - match c { - b'"' => in_str = true, - b'[' | b'{' => { - depth += 1; - max = max.max(depth); - } - b']' | b'}' => depth = depth.saturating_sub(1), - _ => {} - } - } - max -} +pub(crate) use craft_timeline::preflight::{json_depth, xml_depth}; pub fn import( project: &mut Project, From ee6f04c4fc7e62c79db0c1b00add1b70b4cdc356 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 11:40:58 -0500 Subject: [PATCH 204/324] refactor: pin merged PSD prediction scratch API --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d5411483..121b3b510 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1359,7 +1359,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c864e1e8c9e0f7e2c9f24fca1faa6f298a068bca#c864e1e8c9e0f7e2c9f24fca1faa6f298a068bca" +source = "git+https://github.com/storytold/craft-libs?rev=ce2ec507c2e6a6a078a5f450f641487f8931816d#ce2ec507c2e6a6a078a5f450f641487f8931816d" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 55ba9d0c2..34da549e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c864e1e8c9e0f7e2c9f24fca1faa6f298a068bca" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From a998f04903177e66f5d3a4e56a3c79a823d2041e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 17:49:20 +0100 Subject: [PATCH 205/324] OpenEXR limit: the planes a request ends with count together, held and from the disk cache too (#3749) The limit applied to the planes read from the file just now, so planes held in memory or handed back by the disk cache were never counted and repeated requests could pass it. It now applies to what the request ends with, asked before anything is read or allocated. When the held planes don't fit with the missing ones they are let go and the request is read on its own; only a request that doesn't fit alone is refused. --- crates/media/src/exr_planes.rs | 58 ++++++++++++++------- crates/media/src/exr_planes/tests.rs | 78 +++++++++++++++++++++++++++- crates/media/src/exr_read.rs | 25 ++++++--- 3 files changed, 133 insertions(+), 28 deletions(-) diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index edfea4ea8..584ea76c9 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -907,6 +907,26 @@ fn run(path: &str, source: &ExrSource, flight: &Arc, base: Option Refused { + match e { + ReadError::Cancelled => Refused::Cancelled, + // (a read that failed just now: the next request reads again) + ReadError::Io(why) => { + log::warn!("media: {path}: {why}"); + Refused::Stopped + } + ReadError::TooLarge(why) => { + log::warn!("media: {path}: {why}"); + Refused::TooLarge(why) + } + ReadError::Unreadable(why) => { + log::warn!("media: {path}: {why}"); + Refused::Unreadable + } + } +} + /// Decode what `flight` asks for and `base` doesn't hold, and make the union of both. fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option>, opened: Option) -> Result, Refused> { let _decoding = Decoding::new(); @@ -947,10 +967,25 @@ fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option = wanted.into_iter().filter(|i| *i < index.channels.len()).collect(); - let base = base.filter(|b| Arc::ptr_eq(&b.index, &index)); - let missing: Vec = wanted.iter().copied().filter(|id| !base.as_ref().is_some_and(|b| b.ids.binary_search(id).is_ok())).collect(); - let names: Vec = missing.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); + let mut base = base.filter(|b| Arc::ptr_eq(&b.index, &index)); + let mut missing: Vec = wanted.iter().copied().filter(|id| !base.as_ref().is_some_and(|b| b.ids.binary_search(id).is_ok())).collect(); let (w, h) = index.size(); + // The planes the request ends with (those held plus those missing, whether they come from the + // disk cache or the file) must fit the limit, asked before any of them is allocated (#3749). + // The planes held are only kept for later requests: when they don't fit with the missing + // ones, they are let go and the request is read on its own. + if !missing.is_empty() { + let held = base.as_ref().map_or(0, |b| b.ids.len()); + let together = crate::exr_read::check_total(w, h, held.saturating_add(missing.len()), cap_of(path)); + if together.is_err() && base.is_some() { + base = None; + missing = wanted.clone(); + } + if base.is_none() { + crate::exr_read::check_total(w, h, missing.len(), cap_of(path)).map_err(|e| refused(path, e))?; + } + } + let names: Vec = missing.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); // The disk tier first (#3271): what an earlier session or a decode RAM let go of kept, one // entry per channel (any request is assembled from them, whatever was asked before). // (a file naming two channels alike can't tell their entries apart: not kept) @@ -984,22 +1019,7 @@ fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option> = read.map_err(|e| match e { - ReadError::Cancelled => Refused::Cancelled, - // (a read that failed just now: the next request reads again) - ReadError::Io(why) => { - log::warn!("media: {path}: {why}"); - Refused::Stopped - } - ReadError::TooLarge(why) => { - log::warn!("media: {path}: {why}"); - Refused::TooLarge(why) - } - ReadError::Unreadable(why) => { - log::warn!("media: {path}: {why}"); - Refused::Unreadable - } - })?; + let read: Vec> = read.map_err(|e| refused(path, e))?; let mut read = read.into_iter(); let planes: Vec> = kept.iter_mut().map(|k| k.take().or_else(|| read.next()).unwrap_or_default()).collect(); // The union, in file order: the planes held and the ones just read. diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 1dcde8aae..f1f35dc5c 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1473,18 +1473,92 @@ fn a_refusal_for_size_is_decided_anew_when_the_decode_limit_changes() { let source = ExrSource::Bytes(bytes); let index = crate::exr_index::get(path, &source).unwrap(); let want = Want { all: false, ids: (0..4).collect() }; + // (the refusal is made before anything is read: the decodes are counted as they begin) + let begun = Arc::new(AtomicU64::new(0)); + { + let begun = begun.clone(); + set_before_read( + path, + Some(Arc::new(move |_: &str| { + begun.fetch_add(1, Ordering::SeqCst); + })), + ); + } let refused = || matches!(store.get(path, &source, &index, &want, Use::Other), Err(Refused::TooLarge(_))); assert!(refused()); assert!(refused()); - assert_eq!(decodes_of(path).len(), 1, "the second refusal came from memory"); + assert_eq!(begun.load(Ordering::SeqCst), 1, "the second refusal came from memory"); // (figures under the fixed floor: only the change counts, no other test's limit moves) effectcraft_render::memory::set_decode_limit(Some(1000)); effectcraft_render::memory::set_decode_limit(Some(2000)); assert!(refused(), "still over the caller's own limit"); - assert_eq!(decodes_of(path).len(), 2, "decided anew after the limit changed"); + assert_eq!(begun.load(Ordering::SeqCst), 2, "decided anew after the limit changed"); + set_before_read(path, None); effectcraft_render::memory::set_decode_limit(None); } +/// A file of an 8×8 picture and a depth plane: five planes of 256 bytes. +fn picture_and_depth() -> Vec { + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false)], (8, 8), Compression::ZIP1)], (8, 8)) +} + +/// #3749 (#3301 review): the limit is for the planes a request ends with, not for the ones read +/// just now: channels added to the planes held count with them. When together they are over +/// the limit the planes held are let go and the request is read on its own (it fits alone); a +/// request that doesn't fit alone is refused, whatever is held. +#[test] +fn channels_added_to_the_planes_held_count_toward_the_limit() { + let path = "/3749-held-and-added.exr"; + // Room for four planes: the picture fits, one more with it is five. + set_cap(path, 4 * 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(picture_and_depth().into()); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().unwrap().into_iter().collect() }; + store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits"); + let rest = Want { all: true, ids: Default::default() }; + let depth = store.get(path, &source, &index, &rest, Use::Other).expect("the depth plane fits alone"); + assert!(depth.aux.get("Z").is_some()); + assert!(depth.aux.get("R").is_none(), "the picture's planes were let go: four held and one more are five"); + // The picture again: it fits alone, the depth plane is let go in turn. + let again = store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits alone"); + assert!(again.aux.get("R").is_some() && again.aux.get("Z").is_none()); + // Everything at once is five planes: refused, however it is asked. + let everything = Want { all: true, ids: (0..5).collect() }; + assert!(matches!(store.get(path, &source, &index, &everything, Use::Other).err(), Some(Refused::TooLarge(_)))); +} + +/// #3749 (#3301 review): planes the disk cache gives back count toward the limit of a request +/// like the ones read from the file. +#[test] +fn planes_from_the_disk_cache_count_toward_the_limit() { + use effectcraft_render::disk_cache::DiskCache; + let dir = std::env::temp_dir().join(format!("ec-3749-disk-union-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("union_0001.exr"); + std::fs::write(&file, picture_and_depth()).unwrap(); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + dc.set_read_us_per_mb(0); + use_disk_for(&dir.to_string_lossy()); + set_disk_cache(Some(&dc)); + let path = file.to_string_lossy().to_string(); + let source = ExrSource::File(file.clone()); + let index = crate::exr_index::get(&path, &source).unwrap(); + let all = Want { all: true, ids: (0..5).collect() }; + let first = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).is_ok(); + dc.flush(); + // All five planes are in the disk cache (a store without them in RAM reads them back)... + let warm = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).is_ok(); + let from_disk = decodes_of(&path).last().is_some_and(|d| d.from_disk); + // ...and a request may use four. + set_cap(&path, 4 * 8 * 8 * 4); + let refused = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).err(); + set_disk_cache(None); + let _ = std::fs::remove_dir_all(&dir); + assert!(first && warm && from_disk, "decoded without a limit, then read back from the disk cache"); + assert!(matches!(refused, Some(Refused::TooLarge(_))), "{refused:?}"); +} + /// #3749: a plane the system cannot give is a refusal, not an aborted process (the allocation /// is asked for first). #[test] diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index d0ff02b29..9bdc7c048 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -282,6 +282,23 @@ pub(crate) fn plane(n: usize, fill: f32) -> Option> { Some(samples) } +fn too_large(w: usize, h: usize, need: usize, most: usize) -> ReadError { + ReadError::TooLarge(format!("its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", w, h, gb(need), gb(most))) +} + +/// Refuse a request whose planes together, those already in hand (held in memory or read back +/// from the disk cache) and those still to read, `planes` of a `w` × `h` display window, need +/// more memory than one file may use: the limit is for what a file's request ends with, not +/// for the part of it read just now ([`effectcraft_render::memory::decode_limit`], #3749). +pub(crate) fn check_total(w: usize, h: usize, planes: usize, max_bytes: usize) -> Result<(), ReadError> { + let need = w.saturating_mul(h).saturating_mul(planes).saturating_mul(std::mem::size_of::()); + let most = max_bytes.min(effectcraft_render::memory::decode_limit(MAX_DECODE_BYTES, need)); + if need > most { + return Err(too_large(w, h, need, most)); + } + Ok(()) +} + fn read_into(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest, stats: &mut ReadStats) -> Result>, ReadError> { let level = req.level.min(16); let stride = 1i64 << level; @@ -291,13 +308,7 @@ fn read_into(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest, stats: let need = n.saturating_mul(req.channels.len()).saturating_mul(std::mem::size_of::()); let most = req.max_bytes.min(effectcraft_render::memory::decode_limit(req.floor, need)); if need > most { - return Err(ReadError::TooLarge(format!( - "its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", - w, - h, - gb(need), - gb(most) - ))); + return Err(too_large(w, h, need, most)); } // Per part: the plane slot of each of its channels (`None`: not requested). let mut slots: Vec>> = index.meta.headers.iter().map(|h| vec![None; h.channels.list.len()]).collect(); From de0843b193fa68708504161275f57c2eca418604 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 12:32:32 -0500 Subject: [PATCH 206/324] interchange: pin merged optional marker-color parity fix --- Cargo.lock | 36 ++++++++++++++++++------------------ Cargo.toml | 16 ++++++++-------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a38c653da..3a070ac11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1541,9 +1541,9 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe#402dfe46ad568a97f660bcbe30e3a80429b9e1fe" +source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" dependencies = [ - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)", "miniz_oxide 0.9.1", "rayon", "serde", @@ -1579,7 +1579,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe#402dfe46ad568a97f660bcbe30e3a80429b9e1fe" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "serde", "thiserror 2.0.21", @@ -1588,7 +1588,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" dependencies = [ "serde", "thiserror 2.0.21", @@ -3002,7 +3002,7 @@ dependencies = [ [[package]] name = "filmcraft-bitstream" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", ] @@ -3010,7 +3010,7 @@ dependencies = [ [[package]] name = "filmcraft-cfb" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93)", ] @@ -3018,7 +3018,7 @@ dependencies = [ [[package]] name = "filmcraft-codecs" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9)", @@ -3042,7 +3042,7 @@ dependencies = [ [[package]] name = "filmcraft-color" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "serde", ] @@ -3050,10 +3050,10 @@ dependencies = [ [[package]] name = "filmcraft-dng" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-raw", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=402dfe46ad568a97f660bcbe30e3a80429b9e1fe)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)", "image", "rayon", "thiserror 2.0.21", @@ -3062,7 +3062,7 @@ dependencies = [ [[package]] name = "filmcraft-frame" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -3073,7 +3073,7 @@ dependencies = [ [[package]] name = "filmcraft-geom" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "serde", ] @@ -3081,7 +3081,7 @@ dependencies = [ [[package]] name = "filmcraft-interchange" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-aaf", "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", @@ -3100,7 +3100,7 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", ] @@ -3108,7 +3108,7 @@ dependencies = [ [[package]] name = "filmcraft-matroska" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", ] @@ -3116,7 +3116,7 @@ dependencies = [ [[package]] name = "filmcraft-media" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", @@ -3135,7 +3135,7 @@ dependencies = [ [[package]] name = "filmcraft-project" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "filmcraft-color", "filmcraft-geom", @@ -3150,7 +3150,7 @@ dependencies = [ [[package]] name = "filmcraft-time" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=6e561687f0efc9a674c4bfb1c8251da178d1fb55#6e561687f0efc9a674c4bfb1c8251da178d1fb55" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", ] diff --git a/Cargo.toml b/Cargo.toml index 6c0fc585d..35d8d78ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -98,15 +98,15 @@ craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-lib # footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001). # Only `crates/media`, `crates/export` and `crates/interchange` may depend on these. -filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } -filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } -filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } -filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } -filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } +filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } # timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only) -filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } -filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } -filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "6e561687f0efc9a674c4bfb1c8251da178d1fb55" } +filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } # gpu (the same wgpu eframe / egui-wgpu use) wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] } From e57aa567b9fa408c7506917607eb3d2dbb0cba91 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 13:33:08 -0500 Subject: [PATCH 207/324] interchange: pin merged shared nesting preflight --- Cargo.lock | 22 +++++++++++----------- Cargo.toml | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6f1bb26e5..73d74ecb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1597,7 +1597,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +source = "git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb#0d6dd8bed815b8366869a800d2bf22588ca62dcb" dependencies = [ "serde", "thiserror 2.0.21", @@ -1606,7 +1606,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76#a2560df05b4c58631f53a57e65fb05f0e0e6cf76" +source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" dependencies = [ "serde", "thiserror 2.0.21", @@ -1621,6 +1621,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb#0d6dd8bed815b8366869a800d2bf22588ca62dcb" +dependencies = [ + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)", +] + [[package]] name = "craft-timeline" version = "0.1.0" @@ -1632,14 +1640,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "craft-timeline" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76#a2560df05b4c58631f53a57e65fb05f0e0e6cf76" -dependencies = [ - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76)", -] - [[package]] name = "craft-timeline" version = "0.1.0" @@ -2269,7 +2269,7 @@ dependencies = [ name = "effectcraft-interchange" version = "0.24.1" dependencies = [ - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a2560df05b4c58631f53a57e65fb05f0e0e6cf76)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)", "effectcraft-color", "effectcraft-keyframe", "effectcraft-project", diff --git a/Cargo.toml b/Cargo.toml index 62d4d6287..2889bdc34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] -craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "a2560df05b4c58631f53a57e65fb05f0e0e6cf76", default-features = false } +craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "0d6dd8bed815b8366869a800d2bf22588ca62dcb", default-features = false } craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From 58038903bd0a37f753fe074804b9e307f283aa7b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 21:45:05 +0100 Subject: [PATCH 208/324] Read OpenEXR planes through craft-exr's seekable reader The plane store's index and reader now use craft_exr::seek: Index::build reads and checks the headers and offset tables, read_planes fetches only the chunks of the requested channels, rows and level. The app keeps what is its own: the file identity, plane names and aliases, Cryptomatte manifests, the picture's channels, the memory cap of one read and its message, cancellation and the error mapping. The own chunk reading, batching and header parsing are gone, and the exr crate is only a dev-dependency of effectcraft-media now (the tests write files with it). --- crates/media/Cargo.toml | 3 +- crates/media/src/exr_channels.rs | 20 +- crates/media/src/exr_index.rs | 307 +++++++------------------ crates/media/src/exr_planes.rs | 2 +- crates/media/src/exr_planes/tests.rs | 43 ++-- crates/media/src/exr_read.rs | 320 ++++----------------------- 6 files changed, 159 insertions(+), 536 deletions(-) diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 497dbd9fa..d8f9c63f6 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -31,7 +31,6 @@ craft-media = { workspace = true, features = ["mpegts"] } filmcraft-frame = { workspace = true } filmcraft-color = { workspace = true } filmcraft-time = { workspace = true } -exr = { workspace = true } half = { workspace = true } image = { workspace = true, features = ["gif", "webp", "tiff", "bmp", "exr", "tga", "hdr"] } rayon = { workspace = true } @@ -40,6 +39,8 @@ thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +# Writes the OpenEXR files of the tests (reading is craft-exr's). +exr = { workspace = true } # Writes the animated GIFs of the tests. gif = { workspace = true } tempfile = { workspace = true } diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index 812c612c7..4c67df8c9 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -1,5 +1,5 @@ //! Auxiliary channels from multi-layer OpenEXR files (depth, object / material IDs, normals, -//! Cryptomatte, …) for the 3D Channel effects, read with the pure-Rust `exr` crate. +//! Cryptomatte, …) for the 3D Channel effects, read with `craft-exr`. //! //! Every channel of every layer becomes a plane named `layer.channel` (or just `channel` for //! the unnamed layer), placed in the display window (pixels outside a layer's data window are @@ -12,10 +12,10 @@ //! which the picture of an EXR footage item shares with EXtractoR / Cryptomatte (#474, #3271). //! This module holds the naming and picture rules they share, and whole-file reads of bytes. +use craft_exr::decode::PartInfo; use effectcraft_raster::channels3d::split_channel; use effectcraft_raster::{AuxChannels, Image}; use effectcraft_render::reads::FileStamp; -use exr::meta::header::Header; use crate::convert::{AlphaOp, float_to_image}; use crate::exr_index::ExrIndex; @@ -30,16 +30,16 @@ pub(crate) use craft_exr::channels::{is_depth, part_channel_name as channel_name pub use craft_exr::cryptomatte::parse_manifest; /// The part name channels are prefixed with (`None`: unnamed). -pub(crate) fn part_name(header: &Header) -> Option { - header.own_attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty()) +pub(crate) fn part_name(part: &PartInfo) -> Option { + part.name.clone().filter(|s| !s.is_empty()) } /// Why an OpenEXR file's pixels can't be decoded when its headers name a compression this build /// can't decompress (HTJ2K, OpenEXR 3.4's High-Throughput JPEG 2000): the decoders only said /// "no non-deep rgb channels" or showed a transparent frame (#482). `None` for other files. pub fn unsupported_compression(bytes: &[u8]) -> Option<&'static str> { - let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).ok()?; - crate::exr_index::unsupported(&meta) + let parts = craft_exr::decode::parts(bytes, &craft_exr::decode::Limits::none()).ok()?; + parts.iter().any(|p| p.compression.starts_with("HTJ2K")).then_some(crate::exr_index::HTJ2K) } /// How the `image` crate's OpenEXR decoder would show a file: the first part with exact `R`, `G` @@ -75,7 +75,7 @@ pub const WEB_CACHE_CAP: usize = 256 << 20; /// not a readable EXR or the planes need too much memory. fn read_bytes(bytes: &[u8], ids: Option>) -> Option<(ExrIndex, Vec, Vec>)> { let mut src = std::io::Cursor::new(bytes); - let index = crate::exr_index::build(&mut src, bytes.len() as u64, FileStamp::Virtual).ok()?; + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; let ids = ids.unwrap_or_else(|| (0..index.channels.len()).collect()); let (planes, _) = read_planes(&mut src, &index, &ReadRequest::full(ids.clone())); Some((index, ids, planes.ok()?)) @@ -159,7 +159,7 @@ pub(crate) fn picture_names(aux: &AuxChannels) -> Option<([String; 3], Option Option { let mut src = std::io::Cursor::new(bytes); - let index = crate::exr_index::build(&mut src, bytes.len() as u64, FileStamp::Virtual).ok()?; + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; let (ids, rgb, a) = index.picture.clone()?; let (planes, _) = read_planes(&mut src, &index, &ReadRequest::full(ids.clone())); let aux = aux_of(&index, &ids, planes.ok()?); @@ -186,7 +186,7 @@ pub fn layered_image(bytes: &[u8]) -> Option { /// (import). `None` when it is not a readable EXR. pub(crate) fn layered_size(bytes: &[u8]) -> Option<(u32, u32, bool)> { let mut src = std::io::Cursor::new(bytes); - let index = crate::exr_index::build(&mut src, bytes.len() as u64, FileStamp::Virtual).ok()?; + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; let (_, _, a) = index.picture.as_ref()?; let (w, h) = index.size(); Some((w as u32, h as u32, a.is_some())) @@ -341,7 +341,7 @@ mod tests { let layer = Layer::new((1, 1), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into())); let bytes = file(vec![layer], IntegerBounds::new((0, 0), (16384, 16384))); let mut src = std::io::Cursor::new(bytes.as_slice()); - let index = crate::exr_index::build(&mut src, bytes.len() as u64, FileStamp::Virtual).unwrap(); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); let all = ReadRequest::full((0..index.channels.len()).collect()); match read_planes(&mut src, &index, &all).0 { Err(crate::exr_read::ReadError::TooLarge(why)) => assert!(why.contains("16384×16384") && why.contains("GB"), "{why}"), diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs index b642aba89..dccfc3542 100644 --- a/crates/media/src/exr_index.rs +++ b/crates/media/src/exr_index.rs @@ -1,25 +1,28 @@ //! [`ExrIndex`]: what an OpenEXR file holds, read from its headers and offset tables only -//! (#3271): the parts, every channel by its plane name, where each chunk lies and which rows it -//! holds, the Cryptomatte manifests and the channels its picture is made of. +//! (#3271): the parts, every channel by its plane name, the Cryptomatte manifests and the +//! channels its picture is made of. //! -//! An index is a few kilobytes and is kept per file ([`get`]): the channel popups, -//! `layer.channels`, the Cryptomatte layer lists, import and the planning of a read use it -//! and never decode pixels. The reader ([`crate::exr_read`]) fetches the chunks it lists. +//! The headers and offset tables are read and checked by `craft-exr` +//! ([`craft_exr::seek::Index`]), which also knows where each chunk lies; this index adds the +//! app's view of the file: the plane names and aliases, the manifests, the picture's channels and +//! the file's identity. An index is a few kilobytes and is kept per file ([`get`]): the channel +//! popups, `layer.channels`, the Cryptomatte layer lists, import and the planning of a read use +//! it and never decode pixels. The reader ([`crate::exr_read`]) fetches the chunks it lists. //! //! Everything is validated before anything is sized by it: the display window -//! ([`crate::exr_channels::MAX_DISPLAY_PIXELS`]), the chunk count (eight bytes of offset table -//! each, so never more than the file can hold), and every offset (inside the chunk area; a chunk -//! with a bad offset is never read). +//! ([`crate::exr_channels::MAX_DISPLAY_PIXELS`]), the data windows (four times that), the blocks, +//! the chunk count (eight bytes of offset table each, so never more than the file can hold), and +//! every offset (inside the chunk area; a chunk with a bad offset is never read). use std::collections::{HashMap, VecDeque}; -use std::io::{Read, SeekFrom}; +use std::io::SeekFrom; use std::sync::{Arc, Mutex, PoisonError}; +use craft_exr::decode::{Limits, PartInfo, Window}; +use craft_exr::seek; use effectcraft_raster::AuxChannels; use effectcraft_raster::channels3d::BACKGROUND_DEPTH; use effectcraft_render::reads::FileStamp; -use exr::meta::MetaData; -use exr::meta::attribute::{AttributeValue, IntegerBounds, Text}; use crate::exr_channels::{MAX_DISPLAY_PIXELS, Rgb, channel_name, is_depth, parse_manifest, part_name, picture_names}; use crate::exr_read::{ExrSource, Opened, ReadSeek}; @@ -37,37 +40,14 @@ pub(crate) struct IndexChannel { pub(crate) fill: f32, } -/// One chunk of a part, in offset-table order. -#[derive(Clone, Copy, Debug)] -pub(crate) struct IndexChunk { - /// Where it starts in the file, and how many bytes to read for it (0: its offset is not - /// valid, it is never read). - pub(crate) offset: u64, - pub(crate) len: u64, - /// Its first row in the part's data window and how many rows it holds. - pub(crate) y: i64, - pub(crate) rows: usize, - /// Of the full-resolution level (tiled files also store reduced levels). - pub(crate) largest: bool, -} - -/// One part of the file. -#[derive(Clone, Debug)] -pub(crate) struct IndexPart { - /// The part's data window position in the display window, and the data window's size. - pub(crate) offset: (i64, i64), - pub(crate) layer: (usize, usize), - pub(crate) chunks: Vec, -} - /// What an OpenEXR file holds ([`get`]). pub(crate) struct ExrIndex { - pub(crate) meta: MetaData, + /// The headers and chunk tables, as `craft-exr` reads them. + pub(crate) file: seek::Index, /// The file's identity when indexed: a read of another identity indexes it again. pub(crate) stamp: FileStamp, /// The first part's display window: every plane covers it. - pub(crate) display: IntegerBounds, - pub(crate) parts: Vec, + pub(crate) display: Window, pub(crate) channels: Vec, /// How the `image` crate's decoder would show the file (indices into `channels`). pub(crate) rgb: Rgb, @@ -83,7 +63,7 @@ pub(crate) struct ExrIndex { impl ExrIndex { /// The display window's size. pub(crate) fn size(&self) -> (usize, usize) { - (self.display.size.0, self.display.size.1) + (self.display.width as usize, self.display.height as usize) } /// The channels the picture is made of: the image crate's choice ([`Rgb::Planes`]) or the @@ -108,6 +88,14 @@ impl ExrIndex { let names: std::collections::HashSet<&str> = names.into_iter().collect(); self.channels.iter().enumerate().filter(|(_, c)| names.contains(c.name.as_str())).map(|(i, _)| i).collect() } + + /// About the bytes it holds: `craft-exr`'s index (its chunks and header facts), the channels + /// and the manifests. + pub(crate) fn bytes(&self) -> usize { + let names: usize = self.channels.iter().map(|c| c.name.len() * 2 + 64).sum(); + let manifests: usize = self.names.manifests.iter().map(|(l, m)| l.len() + m.iter().map(|(n, _)| n.len() + 32).sum::()).sum(); + self.file.bytes().saturating_add(names).saturating_add(manifests.saturating_mul(2)) + } } /// Why a file has no index. @@ -121,173 +109,59 @@ pub(crate) enum IndexError { Io, } -/// Bytes counted as they are read (the offset tables start where the headers end). -struct Counted<'r> { - inner: &'r mut dyn Read, - read: u64, -} - -impl Read for Counted<'_> { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - let n = self.inner.read(buf)?; - self.read = self.read.saturating_add(n as u64); - Ok(n) - } -} - -/// The headers of the file in `src` as the high-level reader takes them (headers read strictly, -/// then validated leniently: the files that opened before open now), checked before anything is -/// sized by them, and the offset tables: the headers, the tables and where the chunks start. -/// Read through one buffer (attribute names are read a byte at a time); the bytes taken from it -/// are counted, so the chunk area's start is exact. -fn headers_and_tables(src: &mut dyn ReadSeek, len: u64) -> Result<(MetaData, exr::meta::OffsetTables, u64), IndexError> { - let strict = { - let mut buffered = std::io::BufReader::with_capacity(64 << 10, &mut *src); - let mut counted = Counted { inner: &mut buffered, read: 0 }; - match MetaData::read_from_buffered(&mut counted, true).and_then(|meta| MetaData::validate(&meta.headers, false).map(|_| meta)) { - Ok(meta) => { - let header_end = counted.read; - check(&meta, len, header_end)?; - let tables = MetaData::read_offset_tables(&mut exr::io::PeekRead::new(&mut counted), &meta.headers).map_err(|_| IndexError::Unreadable)?; - Some((meta, tables, counted.read)) - } - Err(_) => None, - } - }; - match strict { - Some(parsed) => Ok(parsed), - None => { - // (an HTJ2K file fails here: say why) - src.seek(SeekFrom::Start(0)).map_err(|_| IndexError::Io)?; - match MetaData::read_from_buffered(std::io::BufReader::new(&mut *src), false).ok().as_ref().and_then(unsupported) { - Some(why) => Err(IndexError::Unsupported(why)), - None => Err(IndexError::Unreadable), - } - } - } -} - -/// The most bytes one uncompressed block of a part may take: the decompressor allocates that -/// much for a block before it looks at the data, so a hostile header (a data window a billion -/// pixels wide over one tiny chunk) would ask for gigabytes. -pub(crate) const MAX_BLOCK_BYTES: usize = 256 << 20; +/// Why an HTJ2K file (OpenEXR 3.4's High-Throughput JPEG 2000) isn't read. +pub(crate) const HTJ2K: &str = "OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression"; /// The most pixels of a part's data window (the display window's limit, four times over: data /// windows may reach past it). const MAX_DATA_PIXELS: usize = 4 * MAX_DISPLAY_PIXELS; -/// The bytes of one uncompressed block of `h` (its pixel bytes times a block's pixels, checked): -/// `None` past [`MAX_BLOCK_BYTES`] or when it doesn't fit in a `usize`. -pub(crate) fn block_bytes(h: &exr::meta::header::Header) -> Option { - let (w, rows) = match h.blocks { - exr::meta::BlockDescription::Tiles(t) => (t.tile_size.0, t.tile_size.1), - exr::meta::BlockDescription::ScanLines => (h.layer_size.0, h.compression.scan_lines_per_block().min(h.layer_size.1.max(1))), - }; - let per_pixel = h.channels.list.iter().map(|c| c.sample_type.bytes_per_sample()).try_fold(0usize, usize::checked_add)?; - per_pixel.checked_mul(w)?.checked_mul(rows).filter(|b| *b <= MAX_BLOCK_BYTES) +/// What `craft-exr` may index: data windows of at most [`MAX_DATA_PIXELS`], of any width or +/// height (the display window is checked against [`MAX_DISPLAY_PIXELS`] in [`build`]). +/// `craft-exr` bounds every block itself (256 MiB uncompressed). +fn limits() -> Limits { + let mut limits = Limits::none(); + limits.max_pixels = MAX_DATA_PIXELS as u64; + limits } -/// Every part of `meta` is safe to decode: its data window and its blocks within bounds. -pub(crate) fn parts_in_bounds(meta: &MetaData) -> bool { - meta.headers.iter().all(|h| h.layer_size.0.checked_mul(h.layer_size.1).is_some_and(|n| n <= MAX_DATA_PIXELS) && block_bytes(h).is_some()) +/// The headers and offset tables of the OpenEXR file in `src`, read and checked by `craft-exr`. +fn index_file(src: &mut dyn ReadSeek) -> Result { + src.seek(SeekFrom::Start(0)).map_err(|e| seek::Error::Io(e.to_string()))?; + // (an index is shared by every request for the file: building one is never called off) + seek::Index::build(src, &limits(), &|| false) } -/// The headers of the OpenEXR `bytes` (read leniently) are safe to hand to a decoder -/// ([`parts_in_bounds`]); `false` for anything else. +/// The headers of the OpenEXR `bytes` are safe to hand to a decoder: no part's data window or +/// block is larger than this reader takes. Damaged headers are left to the decoder to report. pub(crate) fn safe_to_decode(bytes: &[u8]) -> bool { - MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).is_ok_and(|meta| parts_in_bounds(&meta)) + !matches!(index_file(&mut std::io::Cursor::new(bytes)), Err(seek::Error::LimitExceeded(_))) } -/// Refuse headers this reader doesn't take or that ask for more than the file can hold. -fn check(meta: &MetaData, len: u64, header_end: u64) -> Result<(), IndexError> { - if !parts_in_bounds(meta) { - return Err(IndexError::Unreadable); - } - if let Some(why) = unsupported(meta) { - return Err(IndexError::Unsupported(why)); - } - let first = meta.headers.first().ok_or(IndexError::Unreadable)?; +/// Index the OpenEXR file in `src` (identity `stamp`), reading its headers and offset tables +/// only. +pub(crate) fn build(src: &mut dyn ReadSeek, stamp: FileStamp) -> Result { + let file = index_file(src).map_err(|e| match e { + seek::Error::Unsupported(why) if why.contains("HTJ2K") => IndexError::Unsupported(HTJ2K), + seek::Error::Io(_) => IndexError::Io, + _ => IndexError::Unreadable, + })?; + let parts = file.parts(); // Deep data isn't read (the whole file was refused before). - if meta.headers.iter().any(|h| h.deep) { + if parts.iter().any(|p| p.deep) { return Err(IndexError::Unreadable); } - let display = first.shared_attributes.display_window; + let display = file.display(); // Each plane covers the display window: a 60000² window over a 1×1 data window was a // multi-gigabyte allocation per channel (#2141). - display.size.0.checked_mul(display.size.1).filter(|n| *n > 0 && *n <= MAX_DISPLAY_PIXELS).ok_or(IndexError::Unreadable)?; - // Eight bytes of offset table per chunk: a header can't claim more chunks than that. - let chunks: usize = meta.headers.iter().map(|h| h.chunk_count).fold(0, usize::saturating_add); - if (chunks as u64).saturating_mul(8) > len.saturating_sub(header_end) { - return Err(IndexError::Unreadable); - } - Ok(()) -} - -/// [`crate::exr_channels::unsupported_compression`] of parsed headers. -pub(crate) fn unsupported(meta: &MetaData) -> Option<&'static str> { - use exr::compression::Compression; - meta.headers - .iter() - .any(|h| matches!(h.compression, Compression::HTJ2K32 | Compression::HTJ2K256)) - .then_some("OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression") -} - -/// Index the OpenEXR file in `src` (`len` bytes, identity `stamp`), reading its headers and -/// offset tables only. -pub(crate) fn build(src: &mut dyn ReadSeek, len: u64, stamp: FileStamp) -> Result { - src.seek(SeekFrom::Start(0)).map_err(|_| IndexError::Io)?; - let (mut meta, tables, chunks_start) = headers_and_tables(&mut *src, len)?; - // The manifests are parsed, and the other attributes (and previews) aren't kept: an index - // stays small however much a renderer writes into the headers. - let manifests = manifests(&meta); - for h in meta.headers.iter_mut() { - h.shared_attributes.other.clear(); - h.own_attributes.other.clear(); - h.own_attributes.preview = None; - } - let first = meta.headers.first().ok_or(IndexError::Unreadable)?; - let display = first.shared_attributes.display_window; - // Where each chunk ends: at the next chunk's start, or at the end of the file. - let mut starts: Vec = tables.iter().flatten().copied().filter(|o| *o >= chunks_start && *o < len).collect(); - starts.sort_unstable(); - starts.dedup(); - let end_of = |offset: u64| match starts.binary_search(&offset) { - Ok(i) => starts.get(i + 1).copied().unwrap_or(len), - Err(_) => offset, - }; - let mut parts = Vec::with_capacity(meta.headers.len()); - for (pi, h) in meta.headers.iter().enumerate() { - let table = tables.get(pi).ok_or(IndexError::Unreadable)?; - // A chunk is at most its block's bytes plus its own small header (part number, position - // and sizes): never read more for one. - let most = (block_bytes(h).ok_or(IndexError::Unreadable)? as u64).saturating_add(64); - let mut list = Vec::with_capacity(h.chunk_count); - for (i, tile) in h.blocks_increasing_y_order().enumerate() { - let bounds = h.get_absolute_block_pixel_coordinates(tile.location).map_err(|_| IndexError::Unreadable)?; - let offset = table.get(i).copied().unwrap_or(0); - let valid = offset >= chunks_start && offset < len; - let bytes = if valid { end_of(offset).saturating_sub(offset).min(most) } else { 0 }; - list.push(IndexChunk { - offset, - len: bytes, - y: i64::from(bounds.position.1), - rows: bounds.size.1, - largest: tile.location.is_largest_resolution_level(), - }); - } - let pos = h.own_attributes.layer_position; - parts.push(IndexPart { - offset: (i64::from(pos.0) - i64::from(display.position.0), i64::from(pos.1) - i64::from(display.position.1)), - layer: (h.layer_size.0, h.layer_size.1), - chunks: list, - }); - } + (display.width as usize).checked_mul(display.height as usize).filter(|n| *n > 0 && *n <= MAX_DISPLAY_PIXELS).ok_or(IndexError::Unreadable)?; + let manifests = manifests(parts); let mut channels = vec![]; let mut aliases = vec![]; - for (pi, h) in meta.headers.iter().enumerate() { - let prefix = part_name(h); - for (ci, ch) in h.channels.list.iter().enumerate() { - let stored = ch.name.to_string(); + for (pi, p) in parts.iter().enumerate() { + let prefix = part_name(p); + for (ci, ch) in p.channels.iter().enumerate() { + let stored = ch.name.clone(); let name = channel_name(prefix.as_deref(), &stored); // A stored `layer.channel` name inside a part named otherwise is also found as stored // (`Crypto_Material00.R` in part `Crypto_Material`); bare names (`R`) are not. @@ -298,8 +172,8 @@ pub(crate) fn build(src: &mut dyn ReadSeek, len: u64, stamp: FileStamp) -> Resul channels.push(IndexChannel { name, part: pi, channel: ci, fill }); } } - let rgb = rgb_of(&meta, &channels); - let mut names = AuxChannels::new(display.size.0 as u32, display.size.1 as u32, 1.0); + let rgb = rgb_of(parts, display, &channels); + let mut names = AuxChannels::new(display.width, display.height, 1.0); names.channels = channels.iter().map(|c| (c.name.clone(), vec![])).collect(); names.manifests = manifests; names.aliases = aliases; @@ -308,32 +182,22 @@ pub(crate) fn build(src: &mut dyn ReadSeek, len: u64, stamp: FileStamp) -> Resul let ids = channels.iter().enumerate().filter(|(_, c)| rgb.iter().chain(&a).any(|k| k.eq_ignore_ascii_case(&c.name))).map(|(i, _)| i).collect(); (ids, rgb, a) }); - Ok(ExrIndex { meta, stamp, display, parts, channels, rgb, picture, names: Arc::new(names) }) + Ok(ExrIndex { file, stamp, display, channels, rgb, picture, names: Arc::new(names) }) } -/// The Cryptomatte manifests of the headers (`cryptomatte//name` and `…/manifest`), sorted. -fn manifests(meta: &MetaData) -> Vec<(String, Vec<(String, u32)>)> { +/// The Cryptomatte manifests of the headers (`cryptomatte//name` and `…/manifest`, in any +/// part), sorted. +fn manifests(parts: &[PartInfo]) -> Vec<(String, Vec<(String, u32)>)> { let mut crypto: HashMap, Option)> = HashMap::new(); - let mut collect = |other: &HashMap| { - for (k, v) in other { - let key = k.to_string(); - let Some(rest) = key.strip_prefix("cryptomatte/") else { continue }; - let Some((id, field)) = rest.split_once('/') else { continue }; - let AttributeValue::Text(t) = v else { continue }; - let e = crypto.entry(id.to_string()).or_default(); - match field { - "name" => e.0 = Some(t.to_string()), - "manifest" => e.1 = Some(t.to_string()), - _ => {} - } + for (key, value) in parts.iter().flat_map(|p| &p.text_attributes) { + let Some(rest) = key.strip_prefix("cryptomatte/") else { continue }; + let Some((id, field)) = rest.split_once('/') else { continue }; + let e = crypto.entry(id.to_string()).or_default(); + match field { + "name" => e.0 = Some(value.clone()), + "manifest" => e.1 = Some(value.clone()), + _ => {} } - }; - // (the image's attributes are the first part's shared ones, as the decoder reports them) - if let Some(first) = meta.headers.first() { - collect(&first.shared_attributes.other); - } - for h in meta.headers.iter() { - collect(&h.own_attributes.other); } let mut out: Vec<(String, Vec<(String, u32)>)> = crypto.into_values().filter_map(|(name, manifest)| Some((name?, parse_manifest(&manifest?)))).collect(); out.sort(); @@ -344,10 +208,9 @@ fn manifests(meta: &MetaData) -> Vec<(String, Vec<(String, u32)>)> { /// `B` channels (alpha `A` when it has one), unless its planes can't stand in for it (a /// depth-named channel, filled with the background depth outside the data window, or a part /// with its own display window). -fn rgb_of(meta: &MetaData, channels: &[IndexChannel]) -> Rgb { - let Some(display) = meta.headers.first().map(|h| h.shared_attributes.display_window) else { return Rgb::None }; - for (pi, h) in meta.headers.iter().enumerate() { - let find = |c: &str| h.channels.find_index_of_channel(&Text::from(c)); +fn rgb_of(parts: &[PartInfo], display: Window, channels: &[IndexChannel]) -> Rgb { + for (pi, p) in parts.iter().enumerate() { + let find = |c: &str| p.channels.iter().position(|ch| ch.name == c); let (Some(r), Some(g), Some(b)) = (find("R"), find("G"), find("B")) else { continue }; let id = |ci: usize| channels.iter().position(|c| c.part == pi && c.channel == ci); let picked = [Some(r), Some(g), Some(b), find("A")]; @@ -355,7 +218,7 @@ fn rgb_of(meta: &MetaData, channels: &[IndexChannel]) -> Rgb { let (Some(Some(r)), Some(Some(g)), Some(Some(b))) = (ids.first(), ids.get(1), ids.get(2)) else { return Rgb::Unsupported }; let a = ids.get(3).copied().flatten(); let depth = [Some(*r), Some(*g), Some(*b), a].iter().flatten().any(|i| channels.get(*i).is_some_and(|c| is_depth(&c.name))); - if depth || h.shared_attributes.display_window != display { + if depth || p.display_window != display { return Rgb::Unsupported; } return Rgb::Planes([*r, *g, *b], a); @@ -368,18 +231,6 @@ fn rgb_of(meta: &MetaData, channels: &[IndexChannel]) -> Rgb { const INDEXED_FILES: usize = 4096; const INDEXED_BYTES: usize = 64 << 20; -impl ExrIndex { - /// About the bytes it holds: its chunks, channels and manifests (the headers' other - /// attributes are dropped when it is built). - pub(crate) fn bytes(&self) -> usize { - let chunks: usize = self.parts.iter().map(|p| p.chunks.len()).sum(); - let names: usize = self.channels.iter().map(|c| c.name.len() * 2 + 64).sum(); - let manifests: usize = self.names.manifests.iter().map(|(l, m)| l.len() + m.iter().map(|(n, _)| n.len() + 32).sum::()).sum(); - let headers = self.meta.headers.len().saturating_mul(1024); - (chunks * std::mem::size_of::()).saturating_add(names).saturating_add(manifests.saturating_mul(2)).saturating_add(headers) - } -} - /// Indexed files by path. struct Indexes { map: HashMap>, @@ -448,7 +299,7 @@ pub(crate) fn get_opened(path: &str, source: &ExrSource) -> Result<(Arc, base: Option>>, size: (usize, usize)) -> V bytes.into_inner() } +/// Each part's chunks of the OpenEXR `bytes`, in offset-table order: where each starts and how +/// many bytes it takes (up to the next chunk, or the end of the file). Read with the `exr` crate: +/// `craft-exr`'s index keeps them to itself. +fn chunk_table(bytes: &[u8]) -> Vec> { + let mut src = bytes; + let meta = exr::meta::MetaData::read_from_buffered(&mut src, false).unwrap(); + let tables = exr::meta::MetaData::read_offset_tables(&mut exr::io::PeekRead::new(&mut src), &meta.headers).unwrap(); + let mut starts: Vec = tables.iter().flatten().copied().collect(); + starts.sort_unstable(); + let end = |at: u64| starts.iter().copied().find(|s| *s > at).unwrap_or(bytes.len() as u64); + tables.iter().map(|t| t.iter().map(|at| (*at, end(*at) - at)).collect()).collect() +} + const SIZE: (usize, usize) = (64, 64); const RGBA: [(&str, bool); 4] = [("R", true), ("G", true), ("B", true), ("A", true)]; const CRYPTO: [(&str, bool); 4] = @@ -134,8 +147,7 @@ fn a_picture_reads_only_its_part() { assert_eq!(d.len(), 1, "{d:?}"); assert_eq!(d[0].channels, ["beauty.A", "beauty.B", "beauty.G", "beauty.R"]); assert_eq!(d[0].stats.chunks, [SIZE.1, 0, 0], "only the beauty part's chunks"); - let index = crate::exr_index::cached(&path).unwrap(); - let beauty: u64 = index.parts[0].chunks.iter().map(|c| c.len).sum(); + let beauty: u64 = chunk_table(&bytes)[0].iter().map(|(_, len)| len).sum(); assert_eq!(d[0].stats.bytes, beauty, "the beauty part's bytes and nothing else"); } @@ -210,7 +222,7 @@ fn picture_and_aux_share_one_read_and_one_decode() { /// The index and an in-memory source of `bytes`. fn indexed(bytes: &[u8]) -> (Arc, std::io::Cursor>) { let mut src = std::io::Cursor::new(bytes.to_vec()); - let ix = crate::exr_index::build(&mut src, bytes.len() as u64, FileStamp::Virtual).unwrap(); + let ix = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); (Arc::new(ix), src) } @@ -832,7 +844,7 @@ fn a_hostile_data_window_is_refused_not_allocated() { let bytes = with_data_window_x_max(small, (1 << 30) - 3); let path = format!("/3271-hostile-{compression:?}.exr"); assert!(!crate::exr_index::safe_to_decode(&bytes)); - assert!(crate::exr_index::build(&mut std::io::Cursor::new(bytes.as_slice()), bytes.len() as u64, FileStamp::Virtual).is_err()); + assert!(crate::exr_index::build(&mut std::io::Cursor::new(bytes.as_slice()), FileStamp::Virtual).is_err()); assert!(crate::exr_channels::read_exr_channels(&bytes).is_none()); assert!(crate::exr_channels::layered_image(&bytes).is_none()); let b: Arc<[u8]> = bytes.into(); @@ -852,13 +864,7 @@ fn a_hostile_data_window_is_refused_not_allocated() { fn damaged_files_never_panic() { let files = [single_part_zips(), multipart(), write(vec![part(None, &RGBA, (16, 40), Compression::PIZ)], (16, 40))]; for good in &files { - let start = crate::exr_index::build(&mut std::io::Cursor::new(good.as_slice()), good.len() as u64, FileStamp::Virtual) - .unwrap() - .parts - .iter() - .flat_map(|p| p.chunks.iter().map(|c| c.offset)) - .min() - .unwrap() as usize; + let start = chunk_table(good).iter().flatten().map(|(at, _)| *at).min().unwrap() as usize; // From a little before the chunks (the offset tables) to the end, in steps. let from = start.saturating_sub(64); for (i, at) in (from..good.len()).step_by(((good.len() - from) / 150).max(1)).enumerate() { @@ -867,7 +873,7 @@ fn damaged_files_never_panic() { let _ = crate::exr_channels::read_exr_channels(&bad); let _ = crate::exr_channels::layered_image(&bad); let mut src = std::io::Cursor::new(bad.as_slice()); - if let Ok(ix) = crate::exr_index::build(&mut src, bad.len() as u64, FileStamp::Virtual) { + if let Ok(ix) = crate::exr_index::build(&mut src, FileStamp::Virtual) { let req = ReadRequest { rows: Some(3..9), level: 1, ..ReadRequest::full((0..ix.channels.len()).collect()) }; let _ = crate::exr_read::read_planes(&mut src, &ix, &req); } @@ -1229,19 +1235,20 @@ fn a_read_in_several_batches_is_whole_and_stops_between_them() { // Called off while the first batch is read: it stops before the next. let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); let mut flaky = Flaky { inner: std::io::Cursor::new(bytes.clone()), reads: 0, cancel_after: Some((1, flag.clone())), fail_from: None }; - let (got, stats) = filmcraft_media::cancel::with_cancel(&flag, || crate::exr_read::read_planes(&mut flaky, &ix, &all)); + let (got, _) = filmcraft_media::cancel::with_cancel(&flag, || crate::exr_read::read_planes(&mut flaky, &ix, &all)); assert_eq!(got.err(), Some(ReadError::Cancelled)); - assert!(stats.lines < h, "stopped early: {} lines", stats.lines); // Chunks that follow each other in the file are read in one go, not one read per chunk. let mut counted = Flaky { inner: std::io::Cursor::new(bytes.clone()), reads: 0, cancel_after: None, fail_from: None }; assert!(crate::exr_read::read_planes(&mut counted, &ix, &all).0.is_ok()); assert!(counted.reads <= 12, "{} reads for {h} chunks", counted.reads); - // A read failing in a later batch (at chunk 300): an I/O error after the first was decoded. - let at = ix.parts[0].chunks[300].offset; + // (a failed read has no stats: the reads it made tell how far it went) + assert!(flaky.reads < counted.reads, "stopped early: {} of {} reads", flaky.reads, counted.reads); + // A read failing in a later batch (at chunk 300): an I/O error after the first was read. + let at = chunk_table(&bytes)[0][300].0; let mut flaky = Flaky { inner: std::io::Cursor::new(bytes), reads: 0, cancel_after: None, fail_from: Some(at) }; - let (got, stats) = crate::exr_read::read_planes(&mut flaky, &ix, &all); + let (got, _) = crate::exr_read::read_planes(&mut flaky, &ix, &all); assert!(matches!(got, Err(ReadError::Io(_))), "{got:?}"); - assert!(stats.lines > 0, "the batches before it were decoded"); + assert!(flaky.reads > 1, "the batches before it were read"); } /// #3271: dropping entries for bytes (a decode over the budget, the memory accountant) drops diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index dcad343f8..6e719c464 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -1,7 +1,7 @@ -//! The OpenEXR reader (#3271): only the chunks a request needs, fetched by the offset table in -//! file order (part by part as the file stores them), decompressed with the `exr` crate's block -//! API on the thread pool the caller runs on (the footage decode threads), and only the -//! requested channels converted, straight into their display-window planes. +//! The OpenEXR reader (#3271): where a file's bytes come from ([`ExrSource`], its identity and +//! how it is opened) and the app's side of a read ([`ReadRequest`] of the index's channels, the +//! memory one read may take, cancellation and the errors shown). The reading itself is +//! `craft-exr`'s ([`craft_exr::seek`]): //! //! - **No whole-file read.** A request reads the headers it is given ([`ExrIndex`]) and then //! exactly the bytes of the chunks it needs; a multi-part file's other parts are never read. @@ -9,20 +9,16 @@ //! column). With one scan line per chunk (NONE, RLE, ZIPS) a chunk is a line and the lines not //! needed are not read or decompressed; with larger chunks (ZIP, PIZ, DWA, tiles) whole chunks //! are skipped and the rows within a chunk are only skipped when converting. -//! - **Cancellable** between batches of chunks ([`filmcraft_media::cancel::cancelled`]). -//! - **Bit-identical** to the high-level reader: the same decompression, and each line placed -//! as `exr_channels`' planes reader placed it (clipped to the display window, the fill value -//! outside the data window, `u32` samples as `f32`). +//! - **Cancellable** while chunks are read ([`filmcraft_media::cancel::cancelled`]). +//! - **Bit-identical** to the high-level reader: the same decompression, each line clipped to +//! the display window, the fill value outside the data window, `u32` samples as `f32`. -use std::io::{Read, Seek, SeekFrom}; +use std::io::{Read, Seek}; use std::ops::Range; use std::sync::Arc; +use craft_exr::seek; use effectcraft_render::reads::FileStamp; -use exr::block::UncompressedBlock; -use exr::block::chunk::Chunk; -use exr::meta::attribute::SampleType; -use rayon::prelude::*; use crate::exr_index::ExrIndex; @@ -45,7 +41,6 @@ pub(crate) enum ExrSource { /// An opened [`ExrSource`]. pub(crate) struct Opened { pub(crate) reader: Box, - pub(crate) len: u64, pub(crate) stamp: FileStamp, } @@ -144,7 +139,7 @@ impl ExrSource { /// #2134), with its identity from the open file. pub(crate) fn open(&self) -> std::io::Result { match self { - ExrSource::Bytes(b) => Ok(Opened { len: b.len() as u64, reader: Box::new(std::io::Cursor::new(b.clone())), stamp: FileStamp::Virtual }), + ExrSource::Bytes(b) => Ok(Opened { reader: Box::new(std::io::Cursor::new(b.clone())), stamp: FileStamp::Virtual }), ExrSource::File(path) => { #[cfg(test)] crate::count_open(path); @@ -153,7 +148,7 @@ impl ExrSource { if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - Ok(Opened { len: meta.len(), stamp: FileStamp::of_metadata(&meta), reader: Box::new(file) }) + Ok(Opened { stamp: FileStamp::of_metadata(&meta), reader: Box::new(file) }) } ExrSource::Localized { original, copy, stamp } => { let local = || -> std::io::Result { @@ -166,7 +161,7 @@ impl ExrSource { if !meta.is_file() || !complete { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{}: not a complete copy", copy.display()))); } - Ok(Opened { len: meta.len(), stamp: *stamp, reader: Box::new(file) }) + Ok(Opened { stamp: *stamp, reader: Box::new(file) }) }; // (a copy evicted or damaged meanwhile: the share) local().or_else(|_| ExrSource::File(original.clone()).open()) @@ -226,49 +221,26 @@ pub(crate) const MAX_DECODE_BYTES: usize = 8 << 30; #[cfg(not(target_pointer_width = "64"))] pub(crate) const MAX_DECODE_BYTES: usize = 512 << 20; -/// At most this many chunks, or bytes of them, are read before they are decompressed (and the -/// request is checked for being called off). The first batch takes at most [`FIRST_BATCH_BYTES`] -/// and each one after twice the one before, so decoding starts early. -const BATCH_CHUNKS: usize = 256; -const BATCH_BYTES: u64 = 64 << 20; -const FIRST_BATCH_BYTES: u64 = 1 << 20; - -/// The raw chunks of a batch: their bytes one after another, and each chunk's part and bytes. -#[derive(Default)] -struct Raw { - data: Vec, - chunks: Vec<(usize, Range)>, -} - -/// Samples of one line placed in a plane. -struct Placed { - /// The requested channel's position in the request. - slot: usize, - /// The first sample's index in the plane. - start: usize, - values: Vec, -} - /// The size of the planes of a read at `level` of a `w` × `h` display window. -pub(crate) fn level_size((w, h): (usize, usize), level: u32) -> (usize, usize) { - let stride = 1usize << level.min(16); - (w.div_ceil(stride), h.div_ceil(stride)) +#[cfg(test)] +pub(crate) fn level_size(size: (usize, usize), level: u32) -> (usize, usize) { + seek::level_size(size, level) } /// Read `req` from `src` (the file `index` describes): one plane per requested channel, in /// request order, covering the display window at the request's level (the channel's fill value -/// where the file has no samples or the request no rows). +/// where the file has no samples or the request no rows). The stats are a failed read's +/// defaults: `craft-exr` reports none for it. pub(crate) fn read_planes(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> (Result>, ReadError>, ReadStats) { - let mut stats = ReadStats { chunks: vec![0; index.parts.len()], ..Default::default() }; - let planes = read_into(src, index, req, &mut stats); - (planes, stats) + match read(src, index, req) { + Ok((planes, stats)) => (Ok(planes), stats), + Err(e) => (Err(e), ReadStats { chunks: vec![0; index.file.parts().len()], ..Default::default() }), + } } -fn read_into(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest, stats: &mut ReadStats) -> Result>, ReadError> { - let level = req.level.min(16); - let stride = 1i64 << level; +fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<(Vec>, ReadStats), ReadError> { let (w, h) = index.size(); - let (ow, oh) = level_size((w, h), level); + let (ow, oh) = seek::level_size((w, h), req.level.min(16)); let n = ow.checked_mul(oh).ok_or_else(|| ReadError::Unreadable("display window".into()))?; let need = n.saturating_mul(req.channels.len()).saturating_mul(std::mem::size_of::()); let most = req.max_bytes.min(MAX_DECODE_BYTES); @@ -282,233 +254,25 @@ fn read_into(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest, stats: gb(most) ))); } - // Per part: the plane slot of each of its channels (`None`: not requested). - let mut slots: Vec>> = index.meta.headers.iter().map(|h| vec![None; h.channels.list.len()]).collect(); - let mut planes = Vec::with_capacity(req.channels.len()); - for (slot, id) in req.channels.iter().enumerate() { + let mut channels = Vec::with_capacity(req.channels.len()); + let mut fill = Vec::with_capacity(req.channels.len()); + for id in &req.channels { let c = index.channels.get(*id).ok_or_else(|| ReadError::Unreadable("no such channel".into()))?; - if let Some(s) = slots.get_mut(c.part).and_then(|p| p.get_mut(c.channel)) { - *s = Some(slot); - } - planes.push(vec![c.fill; n]); + channels.push((c.part, c.channel)); + fill.push(c.fill); } - let rows = req.rows.clone().unwrap_or(0..h as i64); - let (r0, r1) = (rows.start.max(0), rows.end.min(h as i64)); - // A display row is read: in the rows, on the level's grid. - let wanted = move |ty: i64| ty >= r0 && ty < r1 && ty.rem_euclid(stride) == 0; - // A chunk holding display rows `a..b` has a row read. - let any_wanted = move |a: i64, b: i64| { - let first = a.max(r0); - let first = first + (stride - first.rem_euclid(stride)) % stride; - first < b.min(r1) - }; - // The chunks to read, in file order. - let mut jobs: Vec<(usize, u64, u64)> = vec![]; - for (pi, part) in index.parts.iter().enumerate() { - if !slots.get(pi).is_some_and(|s| s.iter().any(Option::is_some)) { - continue; - } - for c in &part.chunks { - let ty0 = c.y.saturating_add(part.offset.1); - if !c.largest || !any_wanted(ty0, ty0.saturating_add(c.rows as i64)) { - continue; - } - if c.len == 0 { - return Err(ReadError::Unreadable("a chunk offset outside the file".into())); - } - jobs.push((pi, c.offset, c.len)); - } - } - jobs.sort_by_key(|(_, offset, _)| *offset); - let geometry = Geometry { size: (w, h), out: (ow, oh), stride, wanted: &wanted }; - let mut pos: Option = None; - let mut rest = jobs.as_slice(); - let mut raw = Raw::default(); - let mut most = FIRST_BATCH_BYTES; - loop { - if filmcraft_media::cancel::cancelled() { - return Err(ReadError::Cancelled); - } - // The next batch is read on this thread while the one read before decompresses and - // converts on this pool's other threads (a network read overlaps the decoding). - let (batch, more) = rest.split_at(batch_len(rest, most)); - rest = more; - most = most.saturating_mul(2).min(BATCH_BYTES); - let decode = std::mem::take(&mut raw); - let (next, done) = rayon::join( - || read_batch(&mut *src, batch, &mut pos, stats), - || -> Vec, usize), String>> { - let data = &decode.data; - decode - .chunks - .par_iter() - .map(|(pi, r)| chunk_lines(index, *pi, data.get(r.clone()).unwrap_or_default(), slots.get(*pi).map_or(&[][..], Vec::as_slice), &geometry)) - .collect() - }, - ); - // Placed plane by plane, the planes in parallel. - let mut by_slot: Vec> = (0..planes.len()).map(|_| vec![]).collect(); - for d in done { - let (placed, lines) = d.map_err(ReadError::Unreadable)?; - stats.lines = stats.lines.saturating_add(lines); - for p in placed { - if let Some(s) = by_slot.get_mut(p.slot) { - s.push(p); - } - } - } - planes.par_iter_mut().zip(by_slot).for_each(|(plane, placed)| { - for p in placed { - let end = p.start.saturating_add(p.values.len()); - if let Some(dst) = plane.get_mut(p.start..end) { - dst.copy_from_slice(&p.values); - } - } - }); - raw = next?; - if raw.chunks.is_empty() { - break; - } - } - Ok(planes) -} - -/// How many of `jobs` (chunks in file order) the next batch takes: up to [`BATCH_CHUNKS`] chunks -/// or `most` bytes, at least one. -fn batch_len(jobs: &[(usize, u64, u64)], most: u64) -> usize { - let mut take = 0; - let mut bytes = 0u64; - while let Some((_, _, len)) = jobs.get(take) { - if take > 0 && (take >= BATCH_CHUNKS || bytes.saturating_add(*len) > most) { - break; - } - bytes = bytes.saturating_add(*len); - take += 1; - } - take -} - -/// The raw bytes of the chunks `batch` (part, offset, length; in file order): chunks that follow -/// each other in the file are read in one go (one request to a network share, not one per -/// chunk), with one seek per gap (`pos`: where the source stands). A chunk the file ends in -/// keeps the bytes there are. -fn read_batch(src: &mut dyn ReadSeek, batch: &[(usize, u64, u64)], pos: &mut Option, stats: &mut ReadStats) -> Result { - let total = batch.iter().map(|(_, _, len)| *len).fold(0u64, u64::saturating_add); - let mut raw = Raw::default(); - raw.data.try_reserve_exact(usize::try_from(total).map_err(|_| ReadError::Unreadable("chunk size".into()))?).map_err(|e| ReadError::Io(e.to_string()))?; - let mut i = 0; - while let Some((_, start, _)) = batch.get(i) { - // A run of chunks, each starting where the one before ends. - let (start, mut end, mut j) = (*start, *start, i); - while let Some((_, offset, len)) = batch.get(j) - && *offset == end - { - end = offset.saturating_add(*len); - j += 1; - } - if *pos != Some(start) { - src.seek(SeekFrom::Start(start)).map_err(|e| ReadError::Io(e.to_string()))?; - } - let at = raw.data.len(); - (&mut *src).take(end.saturating_sub(start)).read_to_end(&mut raw.data).map_err(|e| ReadError::Io(e.to_string()))?; - let got = raw.data.len().saturating_sub(at); - *pos = Some(start.saturating_add(got as u64)); - for (pi, offset, len) in batch.get(i..j).unwrap_or_default() { - let a = usize::try_from(offset.saturating_sub(start)).map_or(raw.data.len(), |o| at.saturating_add(o)).min(raw.data.len()); - let b = usize::try_from(*len).map_or(raw.data.len(), |l| a.saturating_add(l)).min(raw.data.len()); - raw.chunks.push((*pi, a..b)); - if let Some(c) = stats.chunks.get_mut(*pi) { - *c += 1; - } - } - stats.bytes = stats.bytes.saturating_add(got as u64); - i = j.max(i + 1); - } - Ok(raw) -} - -/// The planes' geometry for [`chunk_lines`]. -struct Geometry<'w> { - /// The display window's size, and the planes' (at the level). - size: (usize, usize), - out: (usize, usize), - stride: i64, - wanted: &'w (dyn Fn(i64) -> bool + Sync), -} - -/// Decompress the chunk `buf` of part `pi` and convert the lines of the requested channels -/// (`slots`: each channel's plane slot): the samples to place, and the scan lines decompressed. -/// A chunk that names another part than its offset-table slot's is not placed. -fn chunk_lines(index: &ExrIndex, pi: usize, buf: &[u8], slots: &[Option], g: &Geometry) -> Result<(Vec, usize), String> { - let meta = &index.meta; - let mut read = buf; - let chunk = Chunk::read(&mut read, meta).map_err(|e| e.to_string())?; - if chunk.layer_index != pi { - return Ok((vec![], 0)); - } - let block = UncompressedBlock::decompress_chunk(chunk, meta, false).map_err(|e| e.to_string())?; - let (Some(header), Some(part)) = (meta.headers.get(pi), index.parts.get(pi)) else { return Ok((vec![], 0)) }; - let lines = block.index.pixel_size.1; - let ((lw, lh), (w, h)) = (part.layer, g.size); - let (ow, _) = g.out; - let mut out = vec![]; - let (mut f16s, mut f32s, mut u32s) = (vec![], vec![], vec![]); - for line in block.lines(&header.channels) { - let Some(Some(slot)) = slots.get(line.location.channel).copied() else { continue }; - let Some(kind) = header.channels.list.get(line.location.channel).map(|c| c.sample_type) else { continue }; - let (x0, y, count) = (line.location.position.0, line.location.position.1, line.location.sample_count); - // The samples of data-window row `y`, columns `x0..x0 + count`, at display row `ty` - // from display column `tx0`; clipped to the display window. - if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) { - continue; - } - let Some(ty) = usize::try_from(y as i64 + part.offset.1).ok().filter(|ty| *ty < h) else { continue }; - if !(g.wanted)(ty as i64) { - continue; - } - let tx0 = x0 as i64 + part.offset.0; - let skip = usize::try_from(-tx0).unwrap_or(0).min(count); - let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX); - let take = (count - skip).min(w.saturating_sub(tx)); - if take == 0 { - continue; - } - let samples: Vec = match kind { - SampleType::F16 => { - f16s.resize(count, exr::prelude::f16::ZERO); - line.read_samples_into_slice(&mut f16s).map_err(|e| e.to_string())?; - // (the slice conversion runs the same per-value conversion, in vector steps) - let mut out = vec![0.0; take]; - if let Some(src) = f16s.get(skip..skip + take) { - half::slice::HalfFloatSliceExt::convert_to_f32_slice(src, &mut out); - } - out - } - SampleType::F32 => { - f32s.resize(count, 0.0); - line.read_samples_into_slice(&mut f32s).map_err(|e| e.to_string())?; - f32s.iter().skip(skip).take(take).copied().collect() - } - SampleType::U32 => { - u32s.resize(count, 0); - line.read_samples_into_slice(&mut u32s).map_err(|e| e.to_string())?; - u32s.iter().skip(skip).take(take).map(|s| *s as f32).collect() - } - }; - if g.stride == 1 { - let Some(start) = ty.checked_mul(w).and_then(|row| row.checked_add(tx)) else { continue }; - out.push(Placed { slot, start, values: samples }); - continue; - } - // A reduced level: every stride-th column of the row, on the level's grid. - let stride = g.stride as usize; - let first = tx.div_ceil(stride) * stride; - let values: Vec = samples.iter().enumerate().filter(|(j, _)| (tx + j) % stride == 0).map(|(_, v)| *v).collect(); - if values.is_empty() { - continue; - } - let Some(start) = (ty / stride).checked_mul(ow).and_then(|row| row.checked_add(first / stride)) else { continue }; - out.push(Placed { slot, start, values }); - } - Ok((out, lines)) + let mut request = seek::Request::new(&channels, most); + request.fill = &fill; + request.rows = req.rows.clone(); + request.level = req.level; + // (as many decoding threads as the pool the caller runs on: the footage decode threads) + request.workers = Some(rayon::current_num_threads()); + let planes = seek::read_planes(src, &index.file, &request, &filmcraft_media::cancel::cancelled).map_err(|e| match e { + seek::Error::Cancelled => ReadError::Cancelled, + seek::Error::Io(why) => ReadError::Io(why), + seek::Error::LimitExceeded(why) => ReadError::TooLarge(format!("its OpenEXR channels need more memory than one file may use ({why})")), + seek::Error::Malformed(why) | seek::Error::Unsupported(why) => ReadError::Unreadable(why), + })?; + let stats = ReadStats { chunks: planes.stats.chunks, bytes: planes.stats.bytes, lines: planes.stats.lines }; + Ok((planes.planes, stats)) } From ccd4c75f4f4d18228eb611c6cc4a47919752f405 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 22:02:29 +0100 Subject: [PATCH 209/324] Keep refusing damaged OpenEXR headers before a decoder sees them safe_to_decode accepts a file only when its headers index (or name a compression or part kind this reader doesn't cover); damaged headers, offset tables longer than the file, oversized parts and failed reads are refused again, as the old lenient parse did. Indexing also refuses a channel list the exr crate's validation refused (a zero sampling factor or one not dividing the data window, channels out of order), since headers are now read leniently only. Follows craft-exr's new UnsupportedCompression error kind for HTJ2K and its non-exhaustive error enum. The damaged-file test now checks that the good files index and read and that damaged ones reach the reader. --- crates/media/src/exr_index.rs | 23 +++++++--- crates/media/src/exr_planes/tests.rs | 65 +++++++++++++++++++++++++++- crates/media/src/exr_read.rs | 3 +- 3 files changed, 84 insertions(+), 7 deletions(-) diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs index dccfc3542..bce3dd920 100644 --- a/crates/media/src/exr_index.rs +++ b/crates/media/src/exr_index.rs @@ -132,23 +132,36 @@ fn index_file(src: &mut dyn ReadSeek) -> Result { seek::Index::build(src, &limits(), &|| false) } -/// The headers of the OpenEXR `bytes` are safe to hand to a decoder: no part's data window or -/// block is larger than this reader takes. Damaged headers are left to the decoder to report. +/// The headers of the OpenEXR `bytes` are safe to hand to a decoder: they can be read and no +/// part's data window or block is larger than this reader takes (#3271 review). A file this +/// reader doesn't cover (deep parts, HTJ2K) is left to the decoder; damaged headers, a part too +/// large and a failed read are refused. pub(crate) fn safe_to_decode(bytes: &[u8]) -> bool { - !matches!(index_file(&mut std::io::Cursor::new(bytes)), Err(seek::Error::LimitExceeded(_))) + matches!(index_file(&mut std::io::Cursor::new(bytes)), Ok(_) | Err(seek::Error::Unsupported(_) | seek::Error::UnsupportedCompression(_))) +} + +/// The channel list of `part` as the `exr` crate's validation took it (#3271): sorted by name, +/// every sampling factor non-zero and dividing the data window's position and size. The headers +/// are read leniently, and the crate's decompressors divide by the sampling of every channel of +/// a chunk, requested or not (where panics abort, in the browser, that would end the app). +fn channels_valid(part: &PartInfo) -> bool { + let w = part.data_window; + let divides = |s: usize, pos: i32, size: u32| i64::try_from(s).ok().filter(|s| *s > 0).is_some_and(|s| i64::from(pos) % s == 0 && i64::from(size) % s == 0); + let sorted = part.channels.windows(2).all(|pair| pair.first().zip(pair.get(1)).is_some_and(|(a, b)| a.name.as_bytes() <= b.name.as_bytes())); + sorted && part.channels.iter().all(|c| divides(c.sampling.0, w.x, w.width) && divides(c.sampling.1, w.y, w.height)) } /// Index the OpenEXR file in `src` (identity `stamp`), reading its headers and offset tables /// only. pub(crate) fn build(src: &mut dyn ReadSeek, stamp: FileStamp) -> Result { let file = index_file(src).map_err(|e| match e { - seek::Error::Unsupported(why) if why.contains("HTJ2K") => IndexError::Unsupported(HTJ2K), + seek::Error::UnsupportedCompression(name) if name.contains("HTJ2K") => IndexError::Unsupported(HTJ2K), seek::Error::Io(_) => IndexError::Io, _ => IndexError::Unreadable, })?; let parts = file.parts(); // Deep data isn't read (the whole file was refused before). - if parts.iter().any(|p| p.deep) { + if parts.iter().any(|p| p.deep || !channels_valid(p)) { return Err(IndexError::Unreadable); } let display = file.display(); diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 263723ec9..95b41e4b9 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -864,9 +864,15 @@ fn a_hostile_data_window_is_refused_not_allocated() { fn damaged_files_never_panic() { let files = [single_part_zips(), multipart(), write(vec![part(None, &RGBA, (16, 40), Compression::PIZ)], (16, 40))]; for good in &files { + // (the good file indexes and reads whole through the same path) + let (ix, mut src) = indexed(good); + let all = ReadRequest::full((0..ix.channels.len()).collect()); + assert!(crate::exr_read::read_planes(&mut src, &ix, &all).0.is_ok()); + assert!(crate::exr_channels::read_exr_channels(good).is_some()); let start = chunk_table(good).iter().flatten().map(|(at, _)| *at).min().unwrap() as usize; // From a little before the chunks (the offset tables) to the end, in steps. let from = start.saturating_sub(64); + let (mut reads, mut read_ok) = (0, 0); for (i, at) in (from..good.len()).step_by(((good.len() - from) / 150).max(1)).enumerate() { let mut bad = good.clone(); bad[at] ^= [0xff, 0x80, 0x01, 0x7f][i % 4]; @@ -875,9 +881,66 @@ fn damaged_files_never_panic() { let mut src = std::io::Cursor::new(bad.as_slice()); if let Ok(ix) = crate::exr_index::build(&mut src, FileStamp::Virtual) { let req = ReadRequest { rows: Some(3..9), level: 1, ..ReadRequest::full((0..ix.channels.len()).collect()) }; - let _ = crate::exr_read::read_planes(&mut src, &ix, &req); + reads += 1; + read_ok += usize::from(crate::exr_read::read_planes(&mut src, &ix, &req).0.is_ok()); } } + // Most damage lies in the chunks: the index stands and the reader meets the damage. + assert!(reads > 50 && read_ok > 0, "{reads} damaged files indexed, {read_ok} read"); + } +} + +/// #3271 review (never crash): damaged headers are refused before a decoder sees them +/// ([`crate::exr_index::safe_to_decode`] guards the `image` crate's decoder), and so is a part +/// larger than this reader takes; a file the reader doesn't cover but whose headers are sound +/// (HTJ2K) is left to the decoders to report. +#[test] +fn damaged_headers_are_not_safe_to_decode() { + let good = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)); + assert!(crate::exr_index::safe_to_decode(&good)); + // Cut inside the headers. + let cut = good.windows(11).position(|w| w == b"compression").unwrap(); + assert!(!crate::exr_index::safe_to_decode(&good[..cut]), "headers cut short"); + // Not an OpenEXR file. + let mut magic = good.clone(); + magic[0] ^= 0xff; + assert!(!crate::exr_index::safe_to_decode(&magic), "no signature"); + // Offset tables longer than the file. + let first_chunk = chunk_table(&good)[0][0].0 as usize; + assert!(!crate::exr_index::safe_to_decode(&good[..first_chunk - 8]), "tables cut short"); + assert!(!crate::exr_index::safe_to_decode(&with_data_window_x_max(good.clone(), (1 << 30) - 3)), "a part too large"); + // HTJ2K (compression 11): sound headers, left to the decoders. + let mut htj2k = good.clone(); + let tag = b"compression\0compression\0\x01\0\0\0"; + let at = htj2k.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len(); + htj2k[at] = 11; + assert_eq!( + crate::exr_index::build(&mut std::io::Cursor::new(htj2k.as_slice()), FileStamp::Virtual).err(), + Some(crate::exr_index::IndexError::Unsupported(crate::exr_index::HTJ2K)) + ); + assert!(crate::exr_index::safe_to_decode(&htj2k)); +} + +/// #3271 review (never crash): the headers are read leniently, so a channel list the `exr` +/// crate's validation refused (a zero sampling factor, which its decompressors divide by, or +/// channels out of order) is refused when indexing, before any chunk is decompressed. +#[test] +fn an_invalid_channel_list_is_refused() { + let good = write(vec![part(None, &[("G", true), ("R", true)], (4, 4), Compression::ZIP1)], (4, 4)); + let tag = b"channels\0chlist\0"; + let list = good.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 4; + // Each entry: name, NUL, pixel type (4), linear (1), reserved (3), x and y sampling (4 + 4). + let mut zero = good.clone(); + let x_sampling = list + 2 + 4 + 1 + 3; + zero[x_sampling..x_sampling + 4].copy_from_slice(&0i32.to_le_bytes()); + let mut swapped = good.clone(); + swapped[list] = b'R'; + swapped[list + 2 + 16] = b'G'; + assert!(crate::exr_index::build(&mut std::io::Cursor::new(good.as_slice()), FileStamp::Virtual).is_ok()); + for bad in [zero, swapped] { + assert!(crate::exr_index::build(&mut std::io::Cursor::new(bad.as_slice()), FileStamp::Virtual).is_err()); + assert!(crate::exr_channels::read_exr_channels(&bad).is_none()); + assert!(crate::exr_channels::layered_image(&bad).is_none()); } } diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index 6e719c464..3fe4f544e 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -271,7 +271,8 @@ fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<( seek::Error::Cancelled => ReadError::Cancelled, seek::Error::Io(why) => ReadError::Io(why), seek::Error::LimitExceeded(why) => ReadError::TooLarge(format!("its OpenEXR channels need more memory than one file may use ({why})")), - seek::Error::Malformed(why) | seek::Error::Unsupported(why) => ReadError::Unreadable(why), + seek::Error::Malformed(why) | seek::Error::Unsupported(why) | seek::Error::UnsupportedCompression(why) => ReadError::Unreadable(why), + other => ReadError::Unreadable(other.to_string()), })?; let stats = ReadStats { chunks: planes.stats.chunks, bytes: planes.stats.bytes, lines: planes.stats.lines }; Ok((planes.planes, stats)) From fa542829e93005433b353f5f42b6be5eb2a0649c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 22:05:56 +0100 Subject: [PATCH 210/324] #3793: build the OCIO test's expected LUT path from its parts join("luts/grade.cube") keeps the forward slash on Windows, while the code resolves the config's LUT as luts\grade.cube, so the test's text lookup in the read log missed there. The code under test is unchanged. --- crates/engine/src/tests/lut_files.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/lut_files.rs b/crates/engine/src/tests/lut_files.rs index 98c95652a..6f6818b23 100644 --- a/crates/engine/src/tests/lut_files.rs +++ b/crates/engine/src/tests/lut_files.rs @@ -192,7 +192,7 @@ fn an_overridden_lut_file_renders_again() { #[test] fn ocio_files_render_again_from_warm_caches() { let dir = tempfile::tempdir().unwrap(); - let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts/grade.cube")); + let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts").join("grade.cube")); std::fs::create_dir_all(dir.path().join("luts")).unwrap(); write(&lut, BLACK, 1_000); write(&grade, BLACK, 1_000); From d671f6e45bbf993a2900c66a21584f9da9c9210f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 22:30:45 +0100 Subject: [PATCH 211/324] Show an OpenEXR file's main picture as After Effects does The picture of an OpenEXR file is now craft-exr's main picture: the unprefixed R, G, B (and A) of the first part that has all three, else the first part's unprefixed Y (and A) as grey. A file of named layers only (Blender's ViewLayer.Combined.R, a compositor's Image.R) has none and shows black at its display window's size, opaque, as After Effects shows it; it still imports and its layers stay readable by effects (EXtractoR, Cryptomatte, the 3D Channel effects). The own picture choice (the beauty pass by name, data passes, the first channel as grey) is gone. The picture's channels keep a fill of 0 outside the data window even in a part named like depth, so the picture of such a file stays what the image crate shows. The golden hashes of the named-layer files are re-pinned (their channels are unchanged), and the docs describe the new rule. --- crates/host/tests/it/exr_layers.rs | 5 +- crates/media/src/exr_channels.rs | 176 +++++++++++---------------- crates/media/src/exr_index.rs | 98 ++++++++------- crates/media/src/exr_planes.rs | 67 +++++----- crates/media/src/exr_planes/tests.rs | 52 ++++++-- crates/media/src/pool.rs | 4 +- crates/media/src/probe.rs | 7 +- crates/media/tests/it/exr_golden.rs | 107 ++++++++-------- docs/agents.md | 5 +- docs/footage.md | 11 +- docs/target-app-parity.md | 2 +- 11 files changed, 273 insertions(+), 261 deletions(-) diff --git a/crates/host/tests/it/exr_layers.rs b/crates/host/tests/it/exr_layers.rs index 39ea95e22..ebed80b35 100644 --- a/crates/host/tests/it/exr_layers.rs +++ b/crates/host/tests/it/exr_layers.rs @@ -39,8 +39,9 @@ fn extractor_shows_the_chosen_layer_and_channels_of_a_layered_exr() { assert_eq!(r["errors"], json!([]), "the file imports: {r}"); s.execute("comp.new", json!({"name": "EXR", "width": 8, "height": 4, "frameRate": 24, "duration": 1})).unwrap(); let layer = s.execute("layer.addItem", json!({"item": r["items"][0]})).unwrap()["layer"].clone(); - // The picture is the colour layer (diffuse: orange). - assert!(near(px(&s), [1.0, 0.735, 0.0]), "{:?}", px(&s)); + // No unnamed R, G, B: no main picture, black as in After Effects (the layers are reached by + // name, below). + assert!(near(px(&s), [0.0, 0.0, 0.0]), "{:?}", px(&s)); let ch = s.execute("layer.channels", json!({"layer": layer})).unwrap(); let names: Vec<&str> = ch["layers"].as_array().unwrap().iter().filter_map(|l| l["name"].as_str()).collect(); diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index 4c67df8c9..cd2f5b7ce 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -13,7 +13,6 @@ //! This module holds the naming and picture rules they share, and whole-file reads of bytes. use craft_exr::decode::PartInfo; -use effectcraft_raster::channels3d::split_channel; use effectcraft_raster::{AuxChannels, Image}; use effectcraft_render::reads::FileStamp; @@ -42,21 +41,6 @@ pub fn unsupported_compression(bytes: &[u8]) -> Option<&'static str> { parts.iter().any(|p| p.compression.starts_with("HTJ2K")).then_some(crate::exr_index::HTJ2K) } -/// How the `image` crate's OpenEXR decoder would show a file: the first part with exact `R`, `G` -/// and `B` channels (alpha `A` when it has one, else opaque), placed in the display window with -/// 0 outside the data window. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Rgb { - /// No part has R, G and B: the decoder refuses the file (a multi-layer file, shown with - /// [`layered_image`]'s rule). - None, - /// The channels (indices into [`ExrIndex::channels`]) hold exactly what it would show. - Planes([usize; 3], Option), - /// The planes can't stand in for it (a depth-named channel, whose plane is filled with the - /// background depth, or another display window): decode with the `image` crate. - Unsupported, -} - /// How many bytes of decoded planes the plane store keeps by itself until the caches' budget is /// set (then it follows the footage frames' cap, see [`crate::exr_planes::set_budget`]: the whole /// common budget on the desktop, #3298), like the frame cache's default @@ -97,79 +81,37 @@ pub fn read_exr_channels(bytes: &[u8]) -> Option { Some(aux_of(&index, &ids, planes)) } -/// Names of the beauty pass, most preferred first, matched against the last part of a layer's -/// name (Blender's `ViewLayer.Combined` is `Combined`): Blender's Combined pass and its -/// compositor's File Output default `Image`, the beauty / rgba / rgb / color of Nuke, Arnold and -/// V-Ray. -const BEAUTY: [&str; 7] = ["combined", "beauty", "image", "rgba", "rgb", "color", "colour"]; - -/// A data pass, never the picture: Cryptomatte (`CryptoMaterial00`), depth, mist, normals, -/// motion vectors, positions, UVs and object / material indices. -fn is_data_layer(layer: &str) -> bool { - let last = layer.rsplit('.').next().unwrap_or(layer).to_ascii_lowercase(); - last.starts_with("crypto") - || ["z", "uv", "id", "mist", "indexob", "indexma"].contains(&last.as_str()) - || ["depth", "normal", "vector", "position", "velocity", "motion", "objectid", "materialid"].iter().any(|k| last.contains(k)) -} - -/// The layer whose colour a multi-layer file shows (see [`layered_image`]). -fn picture_layer<'a>(aux: &AuxChannels, layers: &[&'a str]) -> Option<&'a str> { - // Colour layers: three different channels (not one channel, such as depth, shown in all). - let rgb: Vec<&str> = layers - .iter() - .copied() - .filter(|l| { - let [r, g, b, _] = aux.layer_rgba(l); - !r.is_empty() && !g.is_empty() && !b.is_empty() && r != g - }) - .collect(); - let last = |l: &str| l.rsplit('.').next().unwrap_or(l).to_ascii_lowercase(); - let pictures = || rgb.iter().filter(|l| !is_data_layer(l)); - // The unnamed layer (plain R, G, B), then the beauty pass by name. - rgb.iter() - .find(|l| l.is_empty()) - .or_else(|| BEAUTY.iter().find_map(|k| rgb.iter().find(|l| last(l) == *k))) - .or_else(|| pictures().find(|l| ["combined", "beauty"].iter().any(|k| last(l).contains(k)))) - .or_else(|| pictures().next()) - .or_else(|| layers.iter().find(|l| !is_data_layer(l))) - .or_else(|| rgb.first()) - .or_else(|| layers.first()) - .copied() -} - -/// The planes a multi-layer file's picture is made of (see [`layered_image`]): red, green, blue -/// (one channel thrice for grey) and alpha, by name. Only the names of `aux` are read. -pub(crate) fn picture_names(aux: &AuxChannels) -> Option<([String; 3], Option)> { - let layers = aux.layers(); - let colour = picture_layer(aux, &layers)?; - let names = aux.layer_rgba(colour); - // A layer without R, G and B channels shows its first channel as grey. - let first = aux.names().into_iter().find(|n| split_channel(n).0 == colour).unwrap_or_default(); - let pick = |k: usize| names.get(k).map(String::as_str).filter(|n| !n.is_empty()).unwrap_or(first).to_string(); - let a = names.get(3).filter(|n| !n.is_empty() && aux.get(n).is_some()).cloned(); - Some(([pick(0), pick(1), pick(2)], a)) -} - -/// The picture of a multi-layer OpenEXR file without an unnamed RGB layer (Blender's -/// `ViewLayer.Combined.R`, the compositor's `Image.R`, Nuke's `beauty.R`, …), which the image -/// decoder rejects. After Effects shows a file's main RGBA channels and leaves the other layers -/// to EXtractoR; here that is the beauty pass by name (`BEAUTY`), else the first colour layer -/// that is not a data pass (never Cryptomatte, depth or normals, #412), else the first channel -/// as grey. Linear, straight RGBA as the file stores it. `None` when it is not a readable EXR. -/// Only the picture's channels are decoded (in a multi-part file the other parts aren't read). -pub fn layered_image(bytes: &[u8]) -> Option { +/// The main picture of an OpenEXR file's bytes ([`crate::exr_index::MainPicture`]), linear, +/// straight RGB(A) as the file stores it (a `Y` picture as grey); a file without one (named +/// layers only, as Blender's `ViewLayer.Combined.R`) is black at its display window's size, as +/// After Effects shows it (its layers are reached by name, EXtractoR). Only the picture's +/// channels are decoded (in a multi-part file the other parts aren't read). `None` when it is +/// not a readable EXR. +pub fn picture_image(bytes: &[u8]) -> Option { let mut src = std::io::Cursor::new(bytes); let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; - let (ids, rgb, a) = index.picture.clone()?; + let (w, h) = index.size(); + let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?); + let n = (w as usize).checked_mul(h as usize)?; + let Some(picture) = &index.picture else { + let len = n.checked_mul(3)?; + let mut data: Vec = Vec::new(); + data.try_reserve_exact(len).ok()?; + data.resize(len, 0.0); + return image::Rgb32FImage::from_raw(w, h, data).map(image::DynamicImage::ImageRgb32F); + }; + let ([r, g, b], a) = picture.rgba()?; + let ids = index.picture_ids(); let (planes, _) = read_planes(&mut src, &index, &ReadRequest::full(ids.clone())); - let aux = aux_of(&index, &ids, planes.ok()?); - let [r, g, b] = [aux.get(&rgb[0])?, aux.get(&rgb[1])?, aux.get(&rgb[2])?]; - let a = match &a { - Some(n) => Some(aux.get(n)?), + let planes = planes.ok()?; + let plane = |id: usize| ids.iter().position(|i| *i == id).and_then(|at| planes.get(at)); + let (r, g, b) = (plane(r)?, plane(g)?, plane(b)?); + let a = match a { + Some(a) => Some(plane(a)?), None => None, }; - let n = (aux.width as usize).checked_mul(aux.height as usize)?; - let mut data = Vec::with_capacity(n.checked_mul(4)?); + let mut data = Vec::new(); + data.try_reserve_exact(n.checked_mul(if a.is_some() { 4 } else { 3 })?).ok()?; for i in 0..n { data.extend([r.get(i)?, g.get(i)?, b.get(i)?].map(|v| *v)); if let Some(a) = a { @@ -177,19 +119,24 @@ pub fn layered_image(bytes: &[u8]) -> Option { } } match a { - Some(_) => image::Rgba32FImage::from_raw(aux.width, aux.height, data).map(image::DynamicImage::ImageRgba32F), - None => image::Rgb32FImage::from_raw(aux.width, aux.height, data).map(image::DynamicImage::ImageRgb32F), + Some(_) => image::Rgba32FImage::from_raw(w, h, data).map(image::DynamicImage::ImageRgba32F), + None => image::Rgb32FImage::from_raw(w, h, data).map(image::DynamicImage::ImageRgb32F), } } -/// The size and alpha of a layered file's picture ([`layered_image`]) from its headers alone -/// (import). `None` when it is not a readable EXR. -pub(crate) fn layered_size(bytes: &[u8]) -> Option<(u32, u32, bool)> { +/// The size and alpha of an OpenEXR file's main picture ([`picture_image`]) from its headers +/// alone (import; a file without one is its display window, opaque). `None` when it is not a +/// readable EXR. +pub(crate) fn picture_size(bytes: &[u8]) -> Option<(u32, u32, bool)> { let mut src = std::io::Cursor::new(bytes); let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; - let (_, _, a) = index.picture.as_ref()?; let (w, h) = index.size(); - Some((w as u32, h as u32, a.is_some())) + Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?, index.picture.as_ref().is_some_and(|p| p.has_alpha()))) +} + +/// The black picture of a file without a main picture, `w` × `h`, opaque (no alpha channel). +pub(crate) fn black_picture(w: u32, h: u32, op: AlphaOp) -> Image { + float_to_image(w, h, op, |_| [0.0, 0.0, 0.0, 1.0]) } /// The picture made of planes `rgb` and `a` (opaque without one) of `aux`, as @@ -375,8 +322,11 @@ mod tests { assert!(read_exr_channels(&bytes.into_inner()).is_none()); } + /// A file of named layers only (Blender's single-part multilayer) imports at its display + /// window's size and shows black, opaque, as After Effects does; its layers stay readable by + /// effects (EXtractoR, Cryptomatte) and nothing is an error. #[test] - fn layered_exr_without_an_unnamed_rgb_layer_imports() { + fn layered_exr_without_an_unnamed_rgb_layer_imports_black() { use exr::prelude::*; let (w, h) = (4usize, 2usize); let ch = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); @@ -389,8 +339,13 @@ mod tests { assert_eq!((f.width, f.height, f.alpha), (4, 2, effectcraft_project::AlphaMode::Ignore)); let pool = crate::MediaPool::new(); pool.add_bytes("/layers.exr", b.clone()); - let px = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap().get(1, 1); - assert!((px[0] - 1.0).abs() < 1e-4 && px[1] > 0.3 && px[1] < 0.6 && px[2] < 1e-4 && px[3] == 1.0, "diffuse, sRGB-encoded: {px:?}"); + let img = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((img.width, img.height), (4, 2)); + assert_eq!(img.get(1, 1), [0.0, 0.0, 0.0, 1.0], "black, opaque"); + use effectcraft_render::FootageSource; + let effects = pool.aux(effectcraft_project::ItemId(1), &f, effectcraft_time::Tick::ZERO).expect("the layers, for effects"); + assert_eq!(effects.get("diffuse.R").unwrap(), [1.0; 8].as_slice()); + assert_eq!(effects.get("depth.Z").unwrap(), [7.0; 8].as_slice()); let aux = read_exr_channels(&b).unwrap(); assert_eq!(aux.layers(), ["depth", "diffuse"]); assert_eq!(aux.layer_rgba("diffuse"), ["diffuse.R", "diffuse.G", "diffuse.B", ""].map(String::from)); @@ -427,7 +382,7 @@ mod tests { assert!(aux.get("ViewLayer.Combined.R").is_some()); } - /// Straight RGBA of [`layered_image`] at pixel 0 for a file of single-value channels. + /// Straight RGBA of [`picture_image`] at pixel 0 for a file of single-value channels. fn picture>(channels: &[(S, f32)]) -> Vec { use exr::prelude::*; let (w, h) = (2usize, 2usize); @@ -435,15 +390,17 @@ mod tests { let image = Image::from_layer(Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into()))); let mut bytes = std::io::Cursor::new(Vec::new()); image.write().to_buffered(&mut bytes).unwrap(); - let img = layered_image(bytes.get_ref()).unwrap().to_rgba32f(); + let img = picture_image(bytes.get_ref()).unwrap().to_rgba32f(); + assert_eq!(img.dimensions(), (2, 2), "the display window's size"); img.get_pixel(0, 0).0.to_vec() } - /// #412: a Blender compositor File Output (multilayer) names its beauty pass `Image`, and its - /// Cryptomatte layers (lowercase `r, g, b, a`) sort first. The picture was CryptoMaterial00; - /// it is the Image layer, and data passes are never the picture. + /// The main picture is After Effects': the unprefixed `R`, `G`, `B` (`A`), else `Y` (`A`) as + /// grey. A file of named layers only (Blender's multilayer `ViewLayer.Combined.R`, a + /// compositor's `Image.R`, Cryptomatte, depth) has none and shows black, opaque (#412 chose a + /// beauty pass by name before; its layers are reached by name, EXtractoR). #[test] - fn layered_exr_shows_the_beauty_pass_not_cryptomatte() { + fn the_picture_is_the_unprefixed_channels_else_black() { let mut blender = vec![]; for layer in ["CryptoMaterial00", "CryptoMaterial01", "CryptoMaterial02"] { blender.extend(["r", "g", "b", "a"].map(|c| (format!("{layer}.{c}"), 0.9))); @@ -452,8 +409,8 @@ mod tests { blender.extend(["R", "G", "B", "A"].map(|c| (format!("{layer}.{c}"), v))); } blender.push(("Mist.Z".into(), 0.7)); - assert_eq!(picture(&blender), [0.5; 4], "the Image layer"); - // Blender's render-layer names and Nuke's beauty. + let black = [0.0, 0.0, 0.0, 1.0]; + assert_eq!(picture(&blender), black, "named layers only: no Image or beauty pass by name"); assert_eq!( picture(&[ ("ViewLayer.CryptoObject00.r", 0.9), @@ -463,12 +420,15 @@ mod tests { ("ViewLayer.Combined.G", 0.2), ("ViewLayer.Combined.B", 0.2) ]), - [0.2, 0.2, 0.2, 1.0] + black, + "Blender's Combined pass" ); - // No beauty name: the first colour layer that isn't a data pass. - let no_beauty: Vec<(String, f32)> = blender.iter().filter(|(n, _)| !n.starts_with("Image")).cloned().collect(); - assert_eq!(picture(&no_beauty), [0.3; 4], "GlossCol, not Cryptomatte"); - // Only data and a grey pass: the grey pass, not depth. - assert_eq!(picture(&[("Depth.Z", 9.0), ("AO.Y", 0.25)]), [0.25, 0.25, 0.25, 1.0]); + assert_eq!(picture(&[("Depth.Z", 9.0), ("AO.Y", 0.25)]), black, "a layer's Y is not the picture"); + // Unprefixed channels are, whatever the named layers beside them. + assert_eq!(picture(&[("R", 0.1), ("G", 0.2), ("B", 0.3), ("Image.R", 0.9)]), [0.1, 0.2, 0.3, 1.0]); + assert_eq!(picture(&[("R", 0.1), ("G", 0.2), ("B", 0.3), ("A", 0.5)]), [0.1, 0.2, 0.3, 0.5]); + // Luminance: grey, with its alpha. + assert_eq!(picture(&[("Y", 0.25)]), [0.25, 0.25, 0.25, 1.0]); + assert_eq!(picture(&[("A", 0.5), ("Y", 0.25), ("diffuse.R", 0.9)]), [0.25, 0.25, 0.25, 0.5]); } } diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs index bce3dd920..9de4e2b42 100644 --- a/crates/media/src/exr_index.rs +++ b/crates/media/src/exr_index.rs @@ -18,13 +18,14 @@ use std::collections::{HashMap, VecDeque}; use std::io::SeekFrom; use std::sync::{Arc, Mutex, PoisonError}; +use craft_exr::channels::ColorLayout; use craft_exr::decode::{Limits, PartInfo, Window}; use craft_exr::seek; use effectcraft_raster::AuxChannels; use effectcraft_raster::channels3d::BACKGROUND_DEPTH; use effectcraft_render::reads::FileStamp; -use crate::exr_channels::{MAX_DISPLAY_PIXELS, Rgb, channel_name, is_depth, parse_manifest, part_name, picture_names}; +use crate::exr_channels::{MAX_DISPLAY_PIXELS, channel_name, is_depth, parse_manifest, part_name}; use crate::exr_read::{ExrSource, Opened, ReadSeek}; /// One channel of the file, in file order (parts in order, each part's channels as its header @@ -40,6 +41,30 @@ pub(crate) struct IndexChannel { pub(crate) fill: f32, } +/// A file's main picture: its channels (indices into [`ExrIndex::channels`]) in the layout's +/// order, `R`, `G`, `B` (`A`) or `Y` (`A`). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct MainPicture { + pub(crate) layout: ColorLayout, + pub(crate) ids: Vec, +} + +impl MainPicture { + /// The red, green, blue and alpha channels (a `Y` picture is grey: `Y` three times). + pub(crate) fn rgba(&self) -> Option<([usize; 3], Option)> { + let id = |i: usize| self.ids.get(i).copied(); + match self.layout { + ColorLayout::Rgb | ColorLayout::Rgba => Some(([id(0)?, id(1)?, id(2)?], id(3))), + ColorLayout::Y | ColorLayout::YA => Some(([id(0)?; 3], id(1))), + } + } + + /// It has an alpha channel. + pub(crate) fn has_alpha(&self) -> bool { + matches!(self.layout, ColorLayout::Rgba | ColorLayout::YA) + } +} + /// What an OpenEXR file holds ([`get`]). pub(crate) struct ExrIndex { /// The headers and chunk tables, as `craft-exr` reads them. @@ -49,12 +74,10 @@ pub(crate) struct ExrIndex { /// The first part's display window: every plane covers it. pub(crate) display: Window, pub(crate) channels: Vec, - /// How the `image` crate's decoder would show the file (indices into `channels`). - pub(crate) rgb: Rgb, - /// A file the decoder refuses ([`Rgb::None`]): the channels its picture is made of - /// ([`picture_names`]: red, green, blue and alpha by name) and every channel answering to - /// one of those names (lookups ignore case). - pub(crate) picture: Option<(Vec, [String; 3], Option)>, + /// The file's main picture ([`craft_exr::channels::main_picture`]), as After Effects shows + /// it: `None` for a file of named layers only (it shows black; effects reach its layers by + /// name). + pub(crate) picture: Option, /// The names only (planes empty), manifests and aliases: for the channel lists and for /// resolving what effects declare. Never handed to an effect. pub(crate) names: Arc, @@ -66,20 +89,19 @@ impl ExrIndex { (self.display.width as usize, self.display.height as usize) } - /// The channels the picture is made of: the image crate's choice ([`Rgb::Planes`]) or the - /// layered rule's. `None`: the planes can't make it (decode with the `image` crate). - pub(crate) fn picture_ids(&self) -> Option> { - match self.rgb { - Rgb::Planes([r, g, b], a) => Some([Some(r), Some(g), Some(b), a].into_iter().flatten().collect()), - Rgb::None => self.picture.as_ref().map(|(ids, _, _)| ids.clone()), - Rgb::Unsupported => None, - } + /// The channels the picture is made of, in file order (none for a file without a main + /// picture). + pub(crate) fn picture_ids(&self) -> Vec { + let mut ids = self.picture.as_ref().map(|p| p.ids.clone()).unwrap_or_default(); + ids.sort_unstable(); + ids.dedup(); + ids } /// Every channel but the picture's (what [`crate::exr_planes`] means by all channels: the /// picture is kept converted, by the media pool, not as planes too). pub(crate) fn aux_ids(&self) -> Vec { - let picture = self.picture_ids().unwrap_or_default(); + let picture = self.picture_ids(); (0..self.channels.len()).filter(|i| !picture.contains(i)).collect() } @@ -185,17 +207,19 @@ pub(crate) fn build(src: &mut dyn ReadSeek, stamp: FileStamp) -> Result/name` and `…/manifest`, in any @@ -217,26 +241,14 @@ fn manifests(parts: &[PartInfo]) -> Vec<(String, Vec<(String, u32)>)> { out } -/// How the `image` crate's decoder would show the file: the first part with exact `R`, `G` and -/// `B` channels (alpha `A` when it has one), unless its planes can't stand in for it (a -/// depth-named channel, filled with the background depth outside the data window, or a part -/// with its own display window). -fn rgb_of(parts: &[PartInfo], display: Window, channels: &[IndexChannel]) -> Rgb { - for (pi, p) in parts.iter().enumerate() { - let find = |c: &str| p.channels.iter().position(|ch| ch.name == c); - let (Some(r), Some(g), Some(b)) = (find("R"), find("G"), find("B")) else { continue }; - let id = |ci: usize| channels.iter().position(|c| c.part == pi && c.channel == ci); - let picked = [Some(r), Some(g), Some(b), find("A")]; - let ids: Vec> = picked.iter().map(|c| c.and_then(id)).collect(); - let (Some(Some(r)), Some(Some(g)), Some(Some(b))) = (ids.first(), ids.get(1), ids.get(2)) else { return Rgb::Unsupported }; - let a = ids.get(3).copied().flatten(); - let depth = [Some(*r), Some(*g), Some(*b), a].iter().flatten().any(|i| channels.get(*i).is_some_and(|c| is_depth(&c.name))); - if depth || p.display_window != display { - return Rgb::Unsupported; - } - return Rgb::Planes([*r, *g, *b], a); - } - Rgb::None +/// The file's main picture by the OpenEXR convention, as After Effects shows it +/// ([`craft_exr::channels::main_picture`]: the unprefixed `R`, `G`, `B` (`A`) of the first part +/// that has them, else the first unprefixed `Y` (`A`)), as channel ids. The parts' channels are +/// matched as stored (a part's own `R`, not the `part.R` plane name). +fn main_picture(parts: &[PartInfo], channels: &[IndexChannel]) -> Option { + let (part, layout, picked) = craft_exr::channels::main_picture(parts.iter().map(|p| p.channels.iter().map(|c| c.name.as_str())))?; + let ids = picked.iter().map(|ci| channels.iter().position(|c| c.part == part && c.channel == *ci)).collect::>>()?; + Some(MainPicture { layout, ids }) } /// At most this many files are indexed, and their indexes take at most [`INDEXED_BYTES`]; the diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index 1a102c2d0..40b111d9f 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -34,7 +34,7 @@ use effectcraft_render::reads::ReadFile; use crate::convert::AlphaOp; use crate::exr_channels::CACHE_BUDGET; -use crate::exr_channels::{Rgb, planes_picture}; +use crate::exr_channels::{black_picture, planes_picture}; use crate::exr_index::{self, ExrIndex, IndexError}; use crate::exr_read::{ExrSource, Opened, ReadError, ReadRequest, read_planes}; @@ -1139,10 +1139,10 @@ pub(crate) enum Picture { Legacy, } -/// The picture of the OpenEXR at `path` made of its planes: the channels the `image` crate's -/// decoder would show, or a multi-layer file's colour layer (see -/// [`crate::exr_channels::layered_image`]). With `extra` (an effect reads the footage's -/// channels) those channels are read in the same pass and kept for the effects. +/// The picture of the OpenEXR at `path` made of its planes: its main picture +/// ([`crate::exr_index::MainPicture`]), or black for a file without one (named layers only). +/// With `extra` (an effect reads the footage's channels) those channels are read in the same +/// pass and kept for the effects. pub(crate) fn picture(path: &str, source: &ExrSource, op: AlphaOp, extra: Option<&AuxNeed>) -> Picture { let mut extra = extra; for _ in 0..3 { @@ -1153,14 +1153,17 @@ pub(crate) fn picture(path: &str, source: &ExrSource, op: AlphaOp, extra: Option Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), Err(_) => return Picture::Legacy, }; - let Some(ids) = index.picture_ids() else { return Picture::Legacy }; - let mut want = Want { all: false, ids: ids.into_iter().collect() }; + let mut want = Want { all: false, ids: index.picture_ids().into_iter().collect() }; if let Some(need) = extra { match need_ids(&index, need) { Some(more) => want.ids.extend(more), None => want.all = true, } } + // (no main picture and nothing for the effects: black, nothing read) + if !want.all && want.ids.is_empty() { + return Picture::Done(picture_of(&index, None, op).ok_or_else(|| "the picture can't be made".to_string())); + } let by = if extra.is_some() { Use::Picture } else { Use::Other }; let batch = match store().get_opened(path, source, &index, &want, by, opened, since) { Ok(b) => b, @@ -1175,12 +1178,12 @@ pub(crate) fn picture(path: &str, source: &ExrSource, op: AlphaOp, extra: Option // (the whole file's decode says why) Err(Refused::Stopped | Refused::Unreadable) => return Picture::Legacy, }; - let img = picture_of(&index, &batch, op); + let img = picture_of(&index, Some(&batch), op); // The picture is kept by the pool once converted, not twice: its planes go, but for those // an effect names (EXtractoR reading "R"). if img.is_some() { let named = extra.and_then(|n| need_ids(&index, n)).unwrap_or_default(); - let picture: BTreeSet = index.picture_ids().unwrap_or_default().into_iter().filter(|id| !named.contains(id)).collect(); + let picture: BTreeSet = index.picture_ids().into_iter().filter(|id| !named.contains(id)).collect(); let keep: BTreeSet = batch.ids.iter().copied().filter(|id| !picture.contains(id)).collect(); store().keep_only(path, batch, &keep); } @@ -1192,27 +1195,20 @@ pub(crate) fn picture(path: &str, source: &ExrSource, op: AlphaOp, extra: Option Picture::Legacy } -/// The picture of the file `index` describes, made of the planes of `batch`. -fn picture_of(index: &ExrIndex, batch: &Batch, op: AlphaOp) -> Option { - let aux = &batch.aux; - match index.rgb { - Rgb::Planes([r, g, b], a) => { - let a = match a { - Some(a) => Some(batch.plane(a)?), - None => None, - }; - planes_picture(aux, [batch.plane(r)?, batch.plane(g)?, batch.plane(b)?], a, op) - } - Rgb::None => { - let (_, rgb, a) = index.picture.as_ref()?; - let a = match a { - Some(n) => Some(aux.get(n)?), - None => None, - }; - planes_picture(aux, [aux.get(&rgb[0])?, aux.get(&rgb[1])?, aux.get(&rgb[2])?], a, op) - } - Rgb::Unsupported => None, - } +/// The picture of the file `index` describes, made of the planes of `batch` (black, opaque, for +/// a file without a main picture, which needs no planes). +fn picture_of(index: &ExrIndex, batch: Option<&Batch>, op: AlphaOp) -> Option { + let Some(main) = &index.picture else { + let (w, h) = index.size(); + return Some(black_picture(u32::try_from(w).ok()?, u32::try_from(h).ok()?, op)); + }; + let batch = batch?; + let ([r, g, b], a) = main.rgba()?; + let a = match a { + Some(a) => Some(batch.plane(a)?), + None => None, + }; + planes_picture(&batch.aux, [batch.plane(r)?, batch.plane(g)?, batch.plane(b)?], a, op) } /// The picture of the OpenEXR at `path` (as [`picture`]) of only the display rows `rows`: those @@ -1225,10 +1221,11 @@ pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), Err(_) => return Picture::Legacy, }; - let Some(mut ids) = index.picture_ids() else { return Picture::Legacy }; // (in file order: the planes are looked up by id) - ids.sort_unstable(); - ids.dedup(); + let ids = index.picture_ids(); + if ids.is_empty() { + return Picture::Done(picture_of(&index, None, op).ok_or_else(|| "the picture can't be made".to_string())); + } let opened = match opened { Some(o) => Ok(o), None => source.open(), @@ -1257,7 +1254,7 @@ pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i let file = ReadFile::new(path, opened.stamp); crate::reads::note(file.clone()); let batch = Batch { index: index.clone(), ids, all: false, aux: Arc::new(aux), file }; - match picture_of(&index, &batch, op) { + match picture_of(&index, Some(&batch), op) { Some(img) => Picture::Done(Ok(img)), None => Picture::Legacy, } @@ -1286,7 +1283,7 @@ fn aux_of(path: &str, source: &ExrSource, need: &AuxNeed, with_picture: bool) -> None => Want { all: true, ids: BTreeSet::new() }, }; if with_picture { - want.ids.extend(index.picture_ids().unwrap_or_default()); + want.ids.extend(index.picture_ids()); } match store().get_opened(path, source, &index, &want, Use::Other, opened, since) { Ok(b) => return Some(b.aux.clone()), diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 95b41e4b9..f11985f7a 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -197,6 +197,42 @@ fn multipart_channels_are_found_by_their_stored_names() { assert!(names.channels.iter().all(|(_, p)| p.is_empty()), "no pixels decoded"); } +/// The main picture is the first part with unprefixed `R`, `G`, `B`: a depth part before it +/// isn't the picture (nor read for it), the second part's RGBA is. +#[test] +fn a_depth_part_first_leaves_the_picture_to_the_rgba_part() { + let bytes = write(vec![part(Some("depth"), &[("Z", false)], SIZE, Compression::ZIP1), part(Some("beauty"), &RGBA, SIZE, Compression::ZIP1)], SIZE); + let file = Temp::new("depth-first", &bytes); + let f = crate::probe(&file.0).unwrap(); + assert_eq!((f.width, f.height), (SIZE.0 as u32, SIZE.1 as u32)); + let index = crate::exr_index::get(&f.path, &ExrSource::Bytes(bytes.as_slice().into())).unwrap(); + let names: Vec<&str> = index.picture.as_ref().unwrap().ids.iter().map(|i| index.channels[*i].name.as_str()).collect(); + assert_eq!(names, ["beauty.R", "beauty.G", "beauty.B", "beauty.A"]); + let img = crate::MediaPool::new().frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(bits(&img), bits(&image_crates(&bytes, &f)), "the RGBA part, as the image crate shows it"); + let d = decodes_of(&f.path); + assert_eq!(d.last().unwrap().stats.chunks, [0, SIZE.1], "only the RGBA part's chunks"); +} + +/// A luminance file (`Y` only, no `R`, `G`, `B`) is grey, as before. +#[test] +fn a_luminance_file_is_grey() { + let bytes = write(vec![part(None, &[("Y", true)], SIZE, Compression::ZIP1)], SIZE); + let file = Temp::new("luminance", &bytes); + let f = crate::probe(&file.0).unwrap(); + let path = f.path.clone(); + let source = ExrSource::Bytes(bytes.as_slice().into()); + let Picture::Done(Ok(img)) = picture(&path, &source, AlphaOp::of(&f, FloatCurve::Linear), None) else { panic!("a picture") }; + for (i, px) in img.data.iter().enumerate() { + let y = f16::from_f32(value(i, 0, false)).to_f32(); + assert_eq!([px[0], px[1], px[2], px[3]], [y, y, y, 1.0], "pixel {i}"); + } + assert_eq!( + bits(&crate::MediaPool::new().frame_at(&f, Tick::ZERO).unwrap()), + bits(&crate::convert::dynamic_to_image(&crate::exr_channels::picture_image(&bytes).unwrap(), AlphaOp::of(&f, FloatCurve::Srgb))) + ); +} + /// #3271: footage whose effects read 3 channels decodes its picture with them in one pass: one /// read of the file's chunks, one decode, for the picture and the effect. #[test] @@ -302,7 +338,7 @@ fn a_request_not_covered_decodes_only_what_is_missing() { let source = ExrSource::Bytes(bytes); let store = PlaneStore::new(CACHE_BUDGET); let index = crate::exr_index::get(path, &source).unwrap(); - let picture: BTreeSet = index.picture_ids().unwrap().into_iter().collect(); + let picture: BTreeSet = index.picture_ids().into_iter().collect(); let normal: BTreeSet = index.ids_named(["normal.R", "normal.G"]).into_iter().collect(); store.get(path, &source, &index, &Want { all: false, ids: picture.clone() }, Use::Other).unwrap(); let b = store.get(path, &source, &index, &Want { all: false, ids: normal.clone() }, Use::Other).unwrap(); @@ -570,7 +606,7 @@ fn picture_from_planes_is_the_image_crates() { for (k, bytes) in files.iter().enumerate() { let path = format!("/3271-planes-{k}.exr"); let source = ExrSource::Bytes(bytes.as_slice().into()); - assert!(matches!(crate::exr_index::get(&path, &source).unwrap().rgb, Rgb::Planes(..)), "file {k}"); + assert!(crate::exr_index::get(&path, &source).unwrap().picture.is_some(), "file {k}"); let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); for alpha in [AlphaMode::Straight, AlphaMode::Premultiplied, AlphaMode::Ignore] { for curve in [FloatCurve::Srgb, FloatCurve::Linear, FloatCurve::Gamma24] { @@ -761,7 +797,7 @@ fn picture_from_planes_with_data_window_offsets_is_the_image_crates() { for (k, bytes) in files.iter().enumerate() { let path = format!("/3271-offsets-{k}.exr"); let source = ExrSource::Bytes(bytes.as_slice().into()); - assert!(matches!(crate::exr_index::get(&path, &source).unwrap().rgb, Rgb::Planes(..)), "file {k}"); + assert!(crate::exr_index::get(&path, &source).unwrap().picture.is_some(), "file {k}"); let f = Footage::default(); let Picture::Done(Ok(got)) = picture(&path, &source, AlphaOp::of(&f, FloatCurve::Linear), None) else { panic!("file {k}: a picture") }; let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); @@ -780,7 +816,7 @@ fn a_failed_request_fails_only_requests_as_large() { let source = ExrSource::Bytes(bytes.into()); let store = PlaneStore::new(CACHE_BUDGET); let index = crate::exr_index::get(path, &source).unwrap(); - let picture = Want { all: false, ids: index.picture_ids().unwrap().into_iter().collect() }; + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; let all = Want { all: true, ids: (0..4).collect() }; let held = store.get(path, &source, &index, &picture, Use::Picture).unwrap(); assert_eq!(store.get(path, &source, &index, &all, Use::Other).err(), Some(Refused::Unreadable)); @@ -846,7 +882,7 @@ fn a_hostile_data_window_is_refused_not_allocated() { assert!(!crate::exr_index::safe_to_decode(&bytes)); assert!(crate::exr_index::build(&mut std::io::Cursor::new(bytes.as_slice()), FileStamp::Virtual).is_err()); assert!(crate::exr_channels::read_exr_channels(&bytes).is_none()); - assert!(crate::exr_channels::layered_image(&bytes).is_none()); + assert!(crate::exr_channels::picture_image(&bytes).is_none()); let b: Arc<[u8]> = bytes.into(); assert!(crate::probe_bytes(&path, b.clone()).is_err(), "import refuses it"); let pool = crate::MediaPool::new(); @@ -877,7 +913,7 @@ fn damaged_files_never_panic() { let mut bad = good.clone(); bad[at] ^= [0xff, 0x80, 0x01, 0x7f][i % 4]; let _ = crate::exr_channels::read_exr_channels(&bad); - let _ = crate::exr_channels::layered_image(&bad); + let _ = crate::exr_channels::picture_image(&bad); let mut src = std::io::Cursor::new(bad.as_slice()); if let Ok(ix) = crate::exr_index::build(&mut src, FileStamp::Virtual) { let req = ReadRequest { rows: Some(3..9), level: 1, ..ReadRequest::full((0..ix.channels.len()).collect()) }; @@ -940,7 +976,7 @@ fn an_invalid_channel_list_is_refused() { for bad in [zero, swapped] { assert!(crate::exr_index::build(&mut std::io::Cursor::new(bad.as_slice()), FileStamp::Virtual).is_err()); assert!(crate::exr_channels::read_exr_channels(&bad).is_none()); - assert!(crate::exr_channels::layered_image(&bad).is_none()); + assert!(crate::exr_channels::picture_image(&bad).is_none()); } } @@ -1497,7 +1533,7 @@ fn a_failed_picture_leaves_the_other_channels_readable() { let store = PlaneStore::new(CACHE_BUDGET); let source = ExrSource::Bytes(bytes); let index = crate::exr_index::get(path, &source).unwrap(); - let picture = Want { all: false, ids: index.picture_ids().unwrap().into_iter().collect() }; + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; assert!(matches!(store.get(path, &source, &index, &picture, Use::Other), Err(Refused::TooLarge(_)))); assert!(store.get(path, &source, &index, &picture, Use::Other).is_err(), "remembered"); let rest = store.get(path, &source, &index, &Want { all: true, ids: Default::default() }, Use::Other).expect("the other channels"); diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index b110b5079..7b3644722 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -1668,8 +1668,8 @@ impl Inner { Ok(img) => Ok(dynamic_to_image(&img, op)), // Over the size limit: the layered fallback would allocate its planes anyway. Err(e @ image::ImageError::Limits(_)) => Err(MediaError::Decode(format!("{path}: {e}"))), - // A multi-layer OpenEXR file without an unnamed RGB layer: its colour layer. - Err(e) => match crate::exr_channels::layered_image(&bytes) { + // An OpenEXR file the decoder refuses (no unnamed RGB): its main picture, or black. + Err(e) => match crate::exr_channels::picture_image(&bytes) { Some(img) => Ok(dynamic_to_image(&img, op)), None => Err(MediaError::Decode(format!("{path}: {e}"))), }, diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 3e4682577..789043325 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -292,9 +292,10 @@ fn probe_still_bytes(path: &str, bytes: &[u8], fmt: image::ImageFormat) -> Resul (w, h, dec.color_type().has_alpha()) } Err(e) => { - // A multi-layer OpenEXR file without an unnamed RGB layer: its picture's size and - // alpha from the headers alone (#3271), no pixels decoded. - let size = (fmt == image::ImageFormat::OpenExr).then(|| crate::exr_channels::layered_size(bytes)).flatten(); + // An OpenEXR file without an unnamed RGB part (a `Y` picture, or named layers only, + // shown black): its picture's size and alpha from the headers alone (#3271), no + // pixels decoded. + let size = (fmt == image::ImageFormat::OpenExr).then(|| crate::exr_channels::picture_size(bytes)).flatten(); size.ok_or_else(|| MediaError::Decode(format!("{path}: {e}")))? } }; diff --git a/crates/media/tests/it/exr_golden.rs b/crates/media/tests/it/exr_golden.rs index f760ed7c2..e420de1a3 100644 --- a/crates/media/tests/it/exr_golden.rs +++ b/crates/media/tests/it/exr_golden.rs @@ -248,8 +248,8 @@ fn files() -> Vec<(&'static str, Vec, bool)> { true, ), ( - // The image crate shows the part "depth" (the first with R, G and B), whose planes are - // filled with the background depth outside its data window: decoded by the image crate. + // The picture is the part "depth" (the first with R, G and B, as the image crate shows + // it): its channels are colour, 0 outside the data window, despite the part's name. "multipart_depth_named_rgb_zip16", write( vec![ @@ -336,7 +336,10 @@ fn hashes(name: &str, bytes: &[u8], aux_first: bool) -> Vec<(String, u64, bool)> out } -/// Hashes taken on main before #474's shared decode (`EXR_GOLDEN_PRINT=1`). +/// Hashes taken on main before #474's shared decode (`EXR_GOLDEN_PRINT=1`). The pictures of +/// the files of named layers only (`layered_*`, `multipart_blender5_rle`) were re-pinned when the +/// picture became After Effects' main picture (black for those files, their channels unchanged), +/// and `multipart_depth_named_rgb_zip16`'s channels when the picture's channels kept a fill of 0. const PINNED: &[(&str, &str, u64)] = &[ ("rgba_half_zip16", "probe", 0x0a32e074a28c1f66), ("rgba_half_zip16", "probed/linear", 0xa84600283dce98f6), @@ -352,12 +355,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("rgb_float_piz", "ignore/linear", 0xa6e8fbbad371a2ae), ("rgb_float_piz", "preserve_rgb", 0xa6e8fbbad371a2ae), ("rgb_float_piz", "aux", 0x554623d237c2e5ef), - ("layered_rle", "probe", 0x0a32e074a28c1f66), - ("layered_rle", "probed/linear", 0xa84600283dce98f6), - ("layered_rle", "straight/linear", 0xf028e1367a2fbb30), - ("layered_rle", "premul/linear", 0xa84600283dce98f6), - ("layered_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_rle", "probe", 0x6a38346c4c5662d5), + ("layered_rle", "probed/linear", 0x63d9c6245f75ef06), + ("layered_rle", "straight/linear", 0x63d9c6245f75ef06), + ("layered_rle", "premul/linear", 0x63d9c6245f75ef06), + ("layered_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_rle", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_zip1", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_zip1", "probed/linear", 0xa84600283dce98f6), @@ -380,12 +383,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("multipart_diffuse_then_beauty_zip1", "ignore/linear", 0xa90a57f9a67f7468), ("multipart_diffuse_then_beauty_zip1", "preserve_rgb", 0xa90a57f9a67f7468), ("multipart_diffuse_then_beauty_zip1", "aux", 0x6724d6dfd56a04cb), - ("multipart_blender5_rle", "probe", 0x0a32e074a28c1f66), - ("multipart_blender5_rle", "probed/linear", 0xa84600283dce98f6), - ("multipart_blender5_rle", "straight/linear", 0xf028e1367a2fbb30), - ("multipart_blender5_rle", "premul/linear", 0xa84600283dce98f6), - ("multipart_blender5_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("multipart_blender5_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("multipart_blender5_rle", "probe", 0x6a38346c4c5662d5), + ("multipart_blender5_rle", "probed/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "straight/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "premul/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("multipart_blender5_rle", "aux", 0x522ae4819dd92e89), ("unnamed_rgb_window_smaller_zip16", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_window_smaller_zip16", "probed/linear", 0x19eb3b1a88d108a7), @@ -401,19 +404,19 @@ const PINNED: &[(&str, &str, u64)] = &[ ("rgb_float_window_larger_piz", "ignore/linear", 0x8e3847d48f9967a6), ("rgb_float_window_larger_piz", "preserve_rgb", 0x8e3847d48f9967a6), ("rgb_float_window_larger_piz", "aux", 0x7ccc9f86e6ff6140), - ("layered_window_smaller_zip16", "probe", 0x0a32e074a28c1f66), - ("layered_window_smaller_zip16", "probed/linear", 0x19eb3b1a88d108a7), - ("layered_window_smaller_zip16", "straight/linear", 0x2c73f9acaa936420), - ("layered_window_smaller_zip16", "premul/linear", 0x19eb3b1a88d108a7), - ("layered_window_smaller_zip16", "ignore/linear", 0x3b86057d18a16bf0), - ("layered_window_smaller_zip16", "preserve_rgb", 0x5b999014e4a64bb2), + ("layered_window_smaller_zip16", "probe", 0x6a38346c4c5662d5), + ("layered_window_smaller_zip16", "probed/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "straight/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "premul/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_window_smaller_zip16", "aux", 0x443480a1d789e63c), - ("layered_window_larger_piz", "probe", 0x0a32e074a28c1f66), - ("layered_window_larger_piz", "probed/linear", 0x443afe4029748836), - ("layered_window_larger_piz", "straight/linear", 0xb32b44880f746826), - ("layered_window_larger_piz", "premul/linear", 0x443afe4029748836), - ("layered_window_larger_piz", "ignore/linear", 0xaa01706accce2cc4), - ("layered_window_larger_piz", "preserve_rgb", 0xb2cbb40b10bc56b4), + ("layered_window_larger_piz", "probe", 0x6a38346c4c5662d5), + ("layered_window_larger_piz", "probed/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "straight/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "premul/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_window_larger_piz", "aux", 0xb7d91c8eea56a772), ("unnamed_rgb_plus_layers_tiled_zip16", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_tiled_zip16", "probed/linear", 0x7612f20634fe957e), @@ -422,12 +425,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_tiled_zip16", "ignore/linear", 0xbbf236635dcaac90), ("unnamed_rgb_plus_layers_tiled_zip16", "preserve_rgb", 0x15b555a243d79613), ("unnamed_rgb_plus_layers_tiled_zip16", "aux", 0x3d1439eed2202e41), - ("layered_tiled_rle", "probe", 0x0a32e074a28c1f66), - ("layered_tiled_rle", "probed/linear", 0xa84600283dce98f6), - ("layered_tiled_rle", "straight/linear", 0xf028e1367a2fbb30), - ("layered_tiled_rle", "premul/linear", 0xa84600283dce98f6), - ("layered_tiled_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_tiled_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_tiled_rle", "probe", 0x6a38346c4c5662d5), + ("layered_tiled_rle", "probed/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "straight/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "premul/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_tiled_rle", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_mipmapped_zip16", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_mipmapped_zip16", "probed/linear", 0xa84600283dce98f6), @@ -436,12 +439,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_mipmapped_zip16", "ignore/linear", 0xa90a57f9a67f7468), ("unnamed_rgb_plus_layers_mipmapped_zip16", "preserve_rgb", 0xc8e0050f5efe75b7), ("unnamed_rgb_plus_layers_mipmapped_zip16", "aux", 0x27cc9b53d0862db1), - ("layered_mipmapped_piz", "probe", 0x0a32e074a28c1f66), - ("layered_mipmapped_piz", "probed/linear", 0xa84600283dce98f6), - ("layered_mipmapped_piz", "straight/linear", 0xf028e1367a2fbb30), - ("layered_mipmapped_piz", "premul/linear", 0xa84600283dce98f6), - ("layered_mipmapped_piz", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_mipmapped_piz", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_mipmapped_piz", "probe", 0x6a38346c4c5662d5), + ("layered_mipmapped_piz", "probed/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "straight/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "premul/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_mipmapped_piz", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_decreasing_zip1", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_decreasing_zip1", "probed/linear", 0x19eb3b1a88d108a7), @@ -450,12 +453,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_decreasing_zip1", "ignore/linear", 0x3b86057d18a16bf0), ("unnamed_rgb_plus_layers_decreasing_zip1", "preserve_rgb", 0x5b999014e4a64bb2), ("unnamed_rgb_plus_layers_decreasing_zip1", "aux", 0x8f78d3233450acf3), - ("layered_decreasing_rle", "probe", 0x0a32e074a28c1f66), - ("layered_decreasing_rle", "probed/linear", 0xa84600283dce98f6), - ("layered_decreasing_rle", "straight/linear", 0xf028e1367a2fbb30), - ("layered_decreasing_rle", "premul/linear", 0xa84600283dce98f6), - ("layered_decreasing_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_decreasing_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_decreasing_rle", "probe", 0x6a38346c4c5662d5), + ("layered_decreasing_rle", "probed/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "straight/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "premul/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_decreasing_rle", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_uncompressed", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_uncompressed", "probed/linear", 0xa27668bf31d9426b), @@ -464,12 +467,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_uncompressed", "ignore/linear", 0xb3276cc5126776d4), ("unnamed_rgb_plus_layers_uncompressed", "preserve_rgb", 0xdee1105fa6e6822a), ("unnamed_rgb_plus_layers_uncompressed", "aux", 0x854a5e84e7aaa5c2), - ("layered_uncompressed", "probe", 0x0a32e074a28c1f66), - ("layered_uncompressed", "probed/linear", 0xa84600283dce98f6), - ("layered_uncompressed", "straight/linear", 0xf028e1367a2fbb30), - ("layered_uncompressed", "premul/linear", 0xa84600283dce98f6), - ("layered_uncompressed", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_uncompressed", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_uncompressed", "probe", 0x6a38346c4c5662d5), + ("layered_uncompressed", "probed/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "straight/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "premul/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_uncompressed", "aux", 0xa6b9bd9f02c192ad), ("uint_rgb_zip16", "probe", 0x0a32e074a28c1f66), ("uint_rgb_zip16", "probed/linear", 0xed89310ef0cdb9fd), @@ -484,7 +487,7 @@ const PINNED: &[(&str, &str, u64)] = &[ ("multipart_depth_named_rgb_zip16", "premul/linear", 0x869374e9b0384cea), ("multipart_depth_named_rgb_zip16", "ignore/linear", 0x3b86057d18a16bf0), ("multipart_depth_named_rgb_zip16", "preserve_rgb", 0x3b86057d18a16bf0), - ("multipart_depth_named_rgb_zip16", "aux", 0x0fa56884e83b4417), + ("multipart_depth_named_rgb_zip16", "aux", 0x6651502f552749d5), ]; #[test] diff --git a/docs/agents.md b/docs/agents.md index aff59e00a..a83432f04 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -340,8 +340,9 @@ build real projects through these interfaces; they are worked examples of everyt * **OCIO effects**: with Configuration ▸ Custom, `configFile` is a `.ocio` path or the config's text; `effect.warning {layer, effect}` says what Effect Controls warns about (a config it can't read, a colour space it lacks, transforms that pass colours through) or `null`. -* **Multi-layer OpenEXR**: the footage shows the beauty pass (an unnamed RGBA layer, else - Combined / Beauty / Image / RGBA…, never Cryptomatte or depth). `layer.channels {layer}` +* **Multi-layer OpenEXR**: the footage shows the main picture as After Effects does (the + unprefixed `R`, `G`, `B` (`A`) of the first part with them, else `Y` as grey; a file of named + layers only, such as Blender's `ViewLayer.Combined.R`, is black). `layer.channels {layer}` lists a footage layer's EXR layers and channels (`{"layers":[{"name":"diffuse","rgba":["diffuse.R","diffuse.G","diffuse.B",""]}]}`); EXtractoR shows them when its `red` / `green` / `blue` / `alpha` are set to those names diff --git a/docs/footage.md b/docs/footage.md index aa9023224..b0477af56 100644 --- a/docs/footage.md +++ b/docs/footage.md @@ -117,11 +117,12 @@ false` goes back to Use Source File Timecode). Cineon Settings: `{"logConversion Float OpenEXR renders hold linear light; EffectCraft sRGB-encodes them as they are read, like After Effects with Interpret As Linear Light for 32 bpc, unless the item preserves RGB (above). -A multi-layer file shows its main RGBA channels, as in After Effects. Renders that keep every -pass in named layers (Blender's `ViewLayer.Combined`, its compositor's File Output `Image`, -Nuke's `beauty`) show the beauty pass: the layer named Combined, Beauty, Image, RGBA, RGB or -Color, else the first colour layer that isn't a data pass. Cryptomatte, depth, mist, normals, -vectors, positions and IDs are never the picture. EXtractoR reads every other layer and channel. +A multi-layer file shows its main picture, as in After Effects: the channels without a layer +prefix, `R`, `G`, `B` (and `A`) of the first part that has all three, else the first part's `Y` +(and `A`) as grey. Renders that keep every pass in named layers (Blender's +`ViewLayer.Combined`, its compositor's File Output `Image`, Nuke's `beauty.R`) have no main +picture and show black at the file's size, as After Effects shows them; EXtractoR (and +Cryptomatte and the 3D Channel effects) read every layer and channel by name. Footage on its own keeps only the channels of its picture (a single-part file still decompresses all of its pixels to read them). Once an effect reads an item's channels diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 09f9df6bc..4abfadb74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -454,7 +454,7 @@ Mocha and Cineware are third-party and not counted. | Category | Effects | Notes | |---|---|---| -| 3D Channel | 3D Channel Extract, Cryptomatte, Depth Matte, Depth of Field, EXtractoR, Fog 3D, ID Matte, IDentifier | Read auxiliary channels: multi-layer OpenEXR (any `layer.channel`, Cryptomatte manifests from the header; EXtractoR picks a layer and channels from popups of the footage's layers and channels, `layer.channels`, #295; the footage itself shows the beauty pass, never Cryptomatte or depth, #412) or the compositor's own depth / layer-ID / normal / UV / Cryptomatte pass for precomps of 3D comps. | +| 3D Channel | 3D Channel Extract, Cryptomatte, Depth Matte, Depth of Field, EXtractoR, Fog 3D, ID Matte, IDentifier | Read auxiliary channels: multi-layer OpenEXR (any `layer.channel`, Cryptomatte manifests from the header; EXtractoR picks a layer and channels from popups of the footage's layers and channels, `layer.channels`, #295; the footage itself shows After Effects' main picture: the unprefixed RGB(A), else Y, else black) or the compositor's own depth / layer-ID / normal / UV / Cryptomatte pass for precomps of 3D comps. | | Immersive Video | VR Blur, VR Chromatic Aberrations, VR Color Gradients, VR Converter, VR De-Noise, VR Digital Glitch, VR Fractal Noise, VR Glow, VR Plane to Sphere, VR Rotate Sphere, VR Sharpen, VR Sphere to Plane | Seam-aware equirectangular processing (wrap-around, pole continuation, latitude-scaled filters), mono / over-under / side-by-side layouts; VR Converter between equirectangular, cube maps (4:3, 3:2, 6:1), sphere map and 2D. | | Color Correction | OCIO CDL / Color Space / Display / File / Look Transform, Color Stabilizer | Built-in minimal OCIO-style config (ACES2065-1, ACEScg, ACEScct, sRGB, Rec.709, Rec.2020, Display P3, linear variants, XYZ) from published matrices and transfer functions; `.cube` / `.3dl` / `.csp` / `.spi1d` / `.spi3d` / `.spimtx` LUTs and ASC `.cc` / `.ccc` / `.cdl`. Custom `.ocio` config files are read from the OCIO v2 documentation (Configuration ▸ Custom: colorspaces and display colorspaces with the scene / display reference spaces joined by the default view transform, roles, displays with v1 and v2 views, view transforms, looks; Matrix, File, Exponent, ExponentWithLinear, Log, LogAffine, CDL, Range, Allocation, ColorSpace, Look, DisplayView, Builtin (matrices and display curves) and Group transforms), so Blender 4.x / 5.x configs give the Standard, AgX, Filmic and False Color views (#410). Grading Primary / Tone transforms, the ACES output and gamut-compression builtins and HLG pass colours through, and the effect shows a warning naming them (`effect.warning`). | | Distort | CC Flo Motion, Liquify, Rolling Shutter Repair | Liquify strokes are effect data replayed into a displacement mesh (`liquify.stroke` / `liquify.clear` commands; no interactive viewer brush yet). Rolling Shutter Repair uses the KLT tracker. | From c1aea6d65af78c53d24dc820a08ecae8b020d165 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 22:59:38 +0100 Subject: [PATCH 212/324] Bound OpenEXR pictures in memory and keep effects' depth fill The picture of an OpenEXR file (also the black one of a file without a main picture) is checked before anything is read: no larger than a still may decode to and than one read of the file may allocate, else refused with the reason instead of allocated. Import refuses such a picture as other stills. The fill of a picture channel in a part named like depth is the background depth again, as effects read it; the picture is 0 outside that part's data window when composed instead. A read decompresses on at most four threads of its own, none for a small file. --- crates/media/src/exr_channels.rs | 22 +++++++++++++++----- crates/media/src/exr_index.rs | 31 +++++++++++++++++++--------- crates/media/src/exr_planes.rs | 24 ++++++++++++++++++++- crates/media/src/exr_planes/tests.rs | 21 +++++++++++++++++++ crates/media/src/exr_read.rs | 11 ++++++++-- crates/media/src/probe.rs | 7 ++++++- crates/media/tests/it/exr_golden.rs | 10 ++++----- docs/footage.md | 4 ++-- 8 files changed, 104 insertions(+), 26 deletions(-) diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index cd2f5b7ce..422502c5f 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -93,6 +93,10 @@ pub fn picture_image(bytes: &[u8]) -> Option { let (w, h) = index.size(); let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?); let n = (w as usize).checked_mul(h as usize)?; + // (the caller converts it to a float RGBA picture: a still's bound) + if n as u64 > crate::probe::MAX_STILL_PIXELS { + return None; + } let Some(picture) = &index.picture else { let len = n.checked_mul(3)?; let mut data: Vec = Vec::new(); @@ -112,10 +116,15 @@ pub fn picture_image(bytes: &[u8]) -> Option { }; let mut data = Vec::new(); data.try_reserve_exact(n.checked_mul(if a.is_some() { 4 } else { 3 })?).ok()?; + // (0 outside the picture part's data window where its planes hold another fill) + let width = w as usize; + let shown = |i: usize| picture.inside.is_none_or(|[x0, y0, x1, y1]| (x0..x1).contains(&(i % width.max(1))) && (y0..y1).contains(&(i / width.max(1)))); for i in 0..n { - data.extend([r.get(i)?, g.get(i)?, b.get(i)?].map(|v| *v)); + let on = shown(i); + let pick = |v: &f32| if on { *v } else { 0.0 }; + data.extend([r.get(i)?, g.get(i)?, b.get(i)?].map(pick)); if let Some(a) = a { - data.push(*a.get(i)?); + data.push(pick(a.get(i)?)); } } match a { @@ -142,13 +151,16 @@ pub(crate) fn black_picture(w: u32, h: u32, op: AlphaOp) -> Image { /// The picture made of planes `rgb` and `a` (opaque without one) of `aux`, as /// [`crate::convert::dynamic_to_image`] makes it of the same values. `None` when a plane is /// missing or short. -pub(crate) fn planes_picture(aux: &AuxChannels, rgb: [&[f32]; 3], a: Option<&[f32]>, op: AlphaOp) -> Option { - let n = (aux.width as usize).checked_mul(aux.height as usize)?; +pub(crate) fn planes_picture(aux: &AuxChannels, rgb: [&[f32]; 3], a: Option<&[f32]>, inside: Option<[usize; 4]>, op: AlphaOp) -> Option { + let w = aux.width as usize; + let n = w.checked_mul(aux.height as usize)?; if rgb.iter().chain(&a).any(|p| p.len() < n) { return None; } let [r, g, b] = rgb; - let at = |p: &[f32], i: usize| p.get(i).copied().unwrap_or(0.0); + // (0 outside `inside`, the picture part's data window, where the planes hold another fill) + let shown = |i: usize| inside.is_none_or(|[x0, y0, x1, y1]| (x0..x1).contains(&(i % w.max(1))) && (y0..y1).contains(&(i / w.max(1)))); + let at = |p: &[f32], i: usize| if shown(i) { p.get(i).copied().unwrap_or(0.0) } else { 0.0 }; Some(float_to_image(aux.width, aux.height, op, |i| [at(r, i), at(g, i), at(b, i), a.map_or(1.0, |a| at(a, i))])) } diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs index 9de4e2b42..cd9a7ef2d 100644 --- a/crates/media/src/exr_index.rs +++ b/crates/media/src/exr_index.rs @@ -47,6 +47,11 @@ pub(crate) struct IndexChannel { pub(crate) struct MainPicture { pub(crate) layout: ColorLayout, pub(crate) ids: Vec, + /// When a picture channel's plane isn't 0 outside the part's data window (a part whose name + /// reads as depth, `depth.R`: its planes keep the background depth for effects), the data + /// window in display pixels, `[x0, y0, x1, y1)`: the picture is 0 outside it, as the `image` + /// crate and After Effects show it. + pub(crate) inside: Option<[usize; 4]>, } impl MainPicture { @@ -207,14 +212,7 @@ pub(crate) fn build(src: &mut dyn ReadSeek, stamp: FileStamp) -> Result Vec<(String, Vec<(String, u32)>)> { /// ([`craft_exr::channels::main_picture`]: the unprefixed `R`, `G`, `B` (`A`) of the first part /// that has them, else the first unprefixed `Y` (`A`)), as channel ids. The parts' channels are /// matched as stored (a part's own `R`, not the `part.R` plane name). -fn main_picture(parts: &[PartInfo], channels: &[IndexChannel]) -> Option { +fn main_picture(parts: &[PartInfo], display: Window, channels: &[IndexChannel]) -> Option { let (part, layout, picked) = craft_exr::channels::main_picture(parts.iter().map(|p| p.channels.iter().map(|c| c.name.as_str())))?; let ids = picked.iter().map(|ci| channels.iter().position(|c| c.part == part && c.channel == *ci)).collect::>>()?; - Some(MainPicture { layout, ids }) + let filled = ids.iter().any(|id| channels.get(*id).is_some_and(|c| c.fill != 0.0)); + let inside = match filled { + true => Some(data_window_in_display(parts.get(part)?.data_window, display)), + false => None, + }; + Some(MainPicture { layout, ids, inside }) +} + +/// The part of `data` inside `display`, in display pixels from its top left: `[x0, y0, x1, y1)`. +fn data_window_in_display(data: Window, display: Window) -> [usize; 4] { + let clamp = |v: i64, size: u32| usize::try_from(v.clamp(0, i64::from(size))).unwrap_or(0); + let (x0, y0) = (i64::from(data.x) - i64::from(display.x), i64::from(data.y) - i64::from(display.y)); + let (x1, y1) = (x0.saturating_add(i64::from(data.width)), y0.saturating_add(i64::from(data.height))); + [clamp(x0, display.width), clamp(y0, display.height), clamp(x1, display.width), clamp(y1, display.height)] } /// At most this many files are indexed, and their indexes take at most [`INDEXED_BYTES`]; the diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index 40b111d9f..bf261491b 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -1153,6 +1153,9 @@ pub(crate) fn picture(path: &str, source: &ExrSource, op: AlphaOp, extra: Option Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), Err(_) => return Picture::Legacy, }; + if let Err(why) = picture_fits(path, &index) { + return Picture::Done(Err(why)); + } let mut want = Want { all: false, ids: index.picture_ids().into_iter().collect() }; if let Some(need) = extra { match need_ids(&index, need) { @@ -1208,7 +1211,23 @@ fn picture_of(index: &ExrIndex, batch: Option<&Batch>, op: AlphaOp) -> Option Some(batch.plane(a)?), None => None, }; - planes_picture(&batch.aux, [batch.plane(r)?, batch.plane(g)?, batch.plane(b)?], a, op) + planes_picture(&batch.aux, [batch.plane(r)?, batch.plane(g)?, batch.plane(b)?], a, main.inside, op) +} + +/// The picture of the file `index` describes (float RGBA, 16 bytes a pixel, allocated whole) is +/// no larger than a still may decode to ([`crate::probe::MAX_STILL_PIXELS`]) nor than one read of +/// the file may allocate: else why not, to show. Checked before anything is read, also for the +/// black picture of a file without a main picture. +fn picture_fits(path: &str, index: &ExrIndex) -> Result<(), String> { + let (w, h) = index.size(); + let pixels = (w as u64).saturating_mul(h as u64); + let need = pixels.saturating_mul(16); + let most = (cap_of(path) as u64).min(crate::probe::MAX_STILL_PIXELS.saturating_mul(16)); + if need <= most { + return Ok(()); + } + let gb = |b: u64| b as f64 / f64::from(1u32 << 30); + Err(format!("its {w}×{h} OpenEXR picture needs {:.1} GB of memory, more than the {:.1} GB one file may use", gb(need), gb(most))) } /// The picture of the OpenEXR at `path` (as [`picture`]) of only the display rows `rows`: those @@ -1221,6 +1240,9 @@ pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), Err(_) => return Picture::Legacy, }; + if let Err(why) = picture_fits(path, &index) { + return Picture::Done(Err(why)); + } // (in file order: the planes are looked up by id) let ids = index.picture_ids(); if ids.is_empty() { diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index f11985f7a..d4fd2d824 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -214,6 +214,27 @@ fn a_depth_part_first_leaves_the_picture_to_the_rgba_part() { assert_eq!(d.last().unwrap().stats.chunks, [0, SIZE.1], "only the RGBA part's chunks"); } +/// The black picture of a file without a main picture is allocated whole like any picture: one +/// larger than one read of the file may allocate is refused with the reason, not allocated (an +/// abort in the browser); within it, it is black at the file's size. +#[test] +fn a_black_picture_too_large_is_refused_not_allocated() { + let bytes = write(vec![part(None, &[("depth.Z", false)], (8, 8), Compression::ZIP1)], (8, 8)); + let path = "/no-picture-too-large.exr"; + let source = ExrSource::Bytes(bytes.as_slice().into()); + let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); + set_cap(path, 8 * 8 * 16 - 1); + match picture(path, &source, op, None) { + Picture::Done(Err(why)) => assert!(why.contains("8×8") && why.contains("GB"), "{why}"), + _ => panic!("refused"), + } + let fits = "/no-picture-fits.exr"; + set_cap(fits, 8 * 8 * 16); + let Picture::Done(Ok(img)) = picture(fits, &source, op, None) else { panic!("a black picture") }; + assert_eq!((img.width, img.height), (8, 8)); + assert!(img.data.iter().all(|p| *p == [0.0, 0.0, 0.0, 1.0])); +} + /// A luminance file (`Y` only, no `R`, `G`, `B`) is grey, as before. #[test] fn a_luminance_file_is_grey() { diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index 3fe4f544e..611e9e5fb 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -221,6 +221,11 @@ pub(crate) const MAX_DECODE_BYTES: usize = 8 << 30; #[cfg(not(target_pointer_width = "64"))] pub(crate) const MAX_DECODE_BYTES: usize = 512 << 20; +/// The most threads one read decompresses on (beside the caller's), and the size of a file +/// whose chunks are decompressed on the calling thread alone. +const READ_WORKERS: usize = 4; +const SMALL_FILE: u64 = 1 << 20; + /// The size of the planes of a read at `level` of a `w` × `h` display window. #[cfg(test)] pub(crate) fn level_size(size: (usize, usize), level: u32) -> (usize, usize) { @@ -265,8 +270,10 @@ fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<( request.fill = &fill; request.rows = req.rows.clone(); request.level = req.level; - // (as many decoding threads as the pool the caller runs on: the footage decode threads) - request.workers = Some(rayon::current_num_threads()); + // craft-exr decompresses on threads of its own, started for this read, beside the decode + // pool the caller runs on: a few at most, and none for a small file (its chunks are + // decompressed on the calling thread). + request.workers = Some(if index.file.file_len() < SMALL_FILE { 0 } else { rayon::current_num_threads().min(READ_WORKERS) }); let planes = seek::read_planes(src, &index.file, &request, &filmcraft_media::cancel::cancelled).map_err(|e| match e { seek::Error::Cancelled => ReadError::Cancelled, seek::Error::Io(why) => ReadError::Io(why), diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 789043325..cf62eb910 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -296,7 +296,12 @@ fn probe_still_bytes(path: &str, bytes: &[u8], fmt: image::ImageFormat) -> Resul // shown black): its picture's size and alpha from the headers alone (#3271), no // pixels decoded. let size = (fmt == image::ImageFormat::OpenExr).then(|| crate::exr_channels::picture_size(bytes)).flatten(); - size.ok_or_else(|| MediaError::Decode(format!("{path}: {e}")))? + let (w, h, alpha) = size.ok_or_else(|| MediaError::Decode(format!("{path}: {e}")))?; + // (as every still: no larger than the renderer can hold as floats) + if u64::from(w) * u64::from(h) > MAX_STILL_PIXELS { + return Err(MediaError::Decode(format!("{path}: a {w}×{h} OpenEXR picture is larger than a still may be"))); + } + (w, h, alpha) } }; Ok(still_footage(path, w, h, fmt, has_alpha)) diff --git a/crates/media/tests/it/exr_golden.rs b/crates/media/tests/it/exr_golden.rs index e420de1a3..ff860c326 100644 --- a/crates/media/tests/it/exr_golden.rs +++ b/crates/media/tests/it/exr_golden.rs @@ -248,8 +248,9 @@ fn files() -> Vec<(&'static str, Vec, bool)> { true, ), ( - // The picture is the part "depth" (the first with R, G and B, as the image crate shows - // it): its channels are colour, 0 outside the data window, despite the part's name. + // The picture is the part "depth" (the first with R, G and B), 0 outside its data window + // as the image crate shows it, while its planes keep the background depth there for + // effects (the part's name reads as depth). "multipart_depth_named_rgb_zip16", write( vec![ @@ -338,8 +339,7 @@ fn hashes(name: &str, bytes: &[u8], aux_first: bool) -> Vec<(String, u64, bool)> /// Hashes taken on main before #474's shared decode (`EXR_GOLDEN_PRINT=1`). The pictures of /// the files of named layers only (`layered_*`, `multipart_blender5_rle`) were re-pinned when the -/// picture became After Effects' main picture (black for those files, their channels unchanged), -/// and `multipart_depth_named_rgb_zip16`'s channels when the picture's channels kept a fill of 0. +/// picture became After Effects' main picture (black for those files, their channels unchanged). const PINNED: &[(&str, &str, u64)] = &[ ("rgba_half_zip16", "probe", 0x0a32e074a28c1f66), ("rgba_half_zip16", "probed/linear", 0xa84600283dce98f6), @@ -487,7 +487,7 @@ const PINNED: &[(&str, &str, u64)] = &[ ("multipart_depth_named_rgb_zip16", "premul/linear", 0x869374e9b0384cea), ("multipart_depth_named_rgb_zip16", "ignore/linear", 0x3b86057d18a16bf0), ("multipart_depth_named_rgb_zip16", "preserve_rgb", 0x3b86057d18a16bf0), - ("multipart_depth_named_rgb_zip16", "aux", 0x6651502f552749d5), + ("multipart_depth_named_rgb_zip16", "aux", 0x0fa56884e83b4417), ]; #[test] diff --git a/docs/footage.md b/docs/footage.md index b0477af56..abab92161 100644 --- a/docs/footage.md +++ b/docs/footage.md @@ -118,8 +118,8 @@ false` goes back to Use Source File Timecode). Cineon Settings: `{"logConversion Float OpenEXR renders hold linear light; EffectCraft sRGB-encodes them as they are read, like After Effects with Interpret As Linear Light for 32 bpc, unless the item preserves RGB (above). A multi-layer file shows its main picture, as in After Effects: the channels without a layer -prefix, `R`, `G`, `B` (and `A`) of the first part that has all three, else the first part's `Y` -(and `A`) as grey. Renders that keep every pass in named layers (Blender's +prefix, `R`, `G`, `B` (and `A`) of the first part that has all three, else the first part that +has a `Y` (its `Y` and `A`) as grey. Renders that keep every pass in named layers (Blender's `ViewLayer.Combined`, its compositor's File Output `Image`, Nuke's `beauty.R`) have no main picture and show black at the file's size, as After Effects shows them; EXtractoR (and Cryptomatte and the 3D Channel effects) read every layer and channel by name. From ea4ac2e5edb4199d007873781a4c25c757132d69 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 23:07:23 +0100 Subject: [PATCH 213/324] Refuse OpenEXR blocks larger than their chunk can hold craft-exr now holds every block to what its chunk's bytes can decompress to, using the ratio the index was built with: the index is built with craft-exr's default ratio (no longer unbounded), a file with such a block is refused when indexed and by safe_to_decode before the image crate sees it, and each read checks it again. Memory the system refuses during a read is a read that failed just now, not remembered, instead of a file too large. --- crates/media/src/exr_index.rs | 37 +++++++++++++++++++--------- crates/media/src/exr_planes/tests.rs | 19 ++++++++++++++ crates/media/src/exr_read.rs | 21 ++++++++++------ 3 files changed, 59 insertions(+), 18 deletions(-) diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs index cd9a7ef2d..988c3b370 100644 --- a/crates/media/src/exr_index.rs +++ b/crates/media/src/exr_index.rs @@ -10,9 +10,11 @@ //! it and never decode pixels. The reader ([`crate::exr_read`]) fetches the chunks it lists. //! //! Everything is validated before anything is sized by it: the display window -//! ([`crate::exr_channels::MAX_DISPLAY_PIXELS`]), the data windows (four times that), the blocks, -//! the chunk count (eight bytes of offset table each, so never more than the file can hold), and -//! every offset (inside the chunk area; a chunk with a bad offset is never read). +//! ([`crate::exr_channels::MAX_DISPLAY_PIXELS`]), the data windows (four times that), the chunk +//! count (eight bytes of offset table each, so never more than the file can hold), and every +//! offset (inside the chunk area; a chunk with a bad offset is never read). Every block is held +//! to what its chunk's bytes can decompress to ([`limits`]) when the file is indexed and before +//! it is handed to another decoder ([`safe_to_decode`]); each read checks it again. use std::collections::{HashMap, VecDeque}; use std::io::SeekFrom; @@ -144,11 +146,15 @@ pub(crate) const HTJ2K: &str = "OpenEXR HTJ2K compression isn't supported yet: r const MAX_DATA_PIXELS: usize = 4 * MAX_DISPLAY_PIXELS; /// What `craft-exr` may index: data windows of at most [`MAX_DATA_PIXELS`], of any width or -/// height (the display window is checked against [`MAX_DISPLAY_PIXELS`] in [`build`]). -/// `craft-exr` bounds every block itself (256 MiB uncompressed). +/// height (the display window is checked against [`MAX_DISPLAY_PIXELS`] in [`build`]), and +/// blocks of at most `craft-exr`'s default ratio of bytes per byte of their chunk (four times +/// that for DWA, plus 1 MiB): a hostile header declaring a block of gigabytes over a chunk of a +/// few bytes is refused, by every read and by [`safe_to_decode`]. A read's planes are bounded by +/// its own cap ([`crate::exr_read::MAX_DECODE_BYTES`]). fn limits() -> Limits { let mut limits = Limits::none(); limits.max_pixels = MAX_DATA_PIXELS as u64; + limits.max_ratio = Limits::default().max_ratio; limits } @@ -159,12 +165,17 @@ fn index_file(src: &mut dyn ReadSeek) -> Result { seek::Index::build(src, &limits(), &|| false) } -/// The headers of the OpenEXR `bytes` are safe to hand to a decoder: they can be read and no -/// part's data window or block is larger than this reader takes (#3271 review). A file this -/// reader doesn't cover (deep parts, HTJ2K) is left to the decoder; damaged headers, a part too -/// large and a failed read are refused. +/// The headers of the OpenEXR `bytes` are safe to hand to a decoder (the `image` crate, which +/// allocates every block by its header): they can be read, no part's data window is larger than +/// this reader takes, and no block is larger than its chunk can decompress to ([`limits`]) +/// (#3271 review). A file this reader doesn't cover (deep parts, HTJ2K) is left to the decoder; +/// damaged headers, a part or a block too large, and a failed read are refused. pub(crate) fn safe_to_decode(bytes: &[u8]) -> bool { - matches!(index_file(&mut std::io::Cursor::new(bytes)), Ok(_) | Err(seek::Error::Unsupported(_) | seek::Error::UnsupportedCompression(_))) + match index_file(&mut std::io::Cursor::new(bytes)) { + Ok(index) => index.check_blocks().is_ok(), + Err(seek::Error::Unsupported(_) | seek::Error::UnsupportedCompression(_)) => true, + Err(_) => false, + } } /// The channel list of `part` as the `exr` crate's validation took it (#3271): sorted by name, @@ -183,9 +194,13 @@ fn channels_valid(part: &PartInfo) -> bool { pub(crate) fn build(src: &mut dyn ReadSeek, stamp: FileStamp) -> Result { let file = index_file(src).map_err(|e| match e { seek::Error::UnsupportedCompression(name) if name.contains("HTJ2K") => IndexError::Unsupported(HTJ2K), - seek::Error::Io(_) => IndexError::Io, + // (memory refused just now: another attempt may succeed, nothing is remembered) + seek::Error::Io(_) | seek::Error::OutOfMemory(_) => IndexError::Io, _ => IndexError::Unreadable, })?; + // A block larger than its chunk can decompress to (a hostile header): the file is refused + // as a whole, as every read of it would refuse that chunk. + file.check_blocks().map_err(|_| IndexError::Unreadable)?; let parts = file.parts(); // Deep data isn't read (the whole file was refused before). if parts.iter().any(|p| p.deep || !channels_valid(p)) { diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index d4fd2d824..02f99a2c1 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1544,6 +1544,25 @@ fn a_failure_is_forgotten_once_the_file_changes() { /// #3271 review: a failed picture request (too large here) doesn't refuse a later request for /// the other channels: "all channels" is every channel but the picture's, so it doesn't ask for /// what failed. +/// Memory the system refuses during a read is a read that failed just now, not a file too large: +/// it isn't remembered, and the next request reads again (a file too large is remembered). +#[test] +fn an_allocation_failure_is_not_remembered() { + use crate::exr_read::{ReadError, read_error}; + assert_eq!(read_error(craft_exr::seek::Error::OutOfMemory("planes".into())), ReadError::Io("planes".into())); + assert!(matches!(read_error(craft_exr::seek::Error::LimitExceeded("planes".into())), ReadError::TooLarge(_))); + // A read that failed just now (here: the file can't be opened) is a stop, and the next + // request for the same channels reads them. + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/oom-not-remembered.exr"; + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &ExrSource::Bytes(bytes.clone())).unwrap(); + let want = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + let gone = ExrSource::File(std::env::temp_dir().join("ec-oom-not-remembered-missing.exr")); + assert_eq!(store.get(path, &gone, &index, &want, Use::Other).err(), Some(Refused::Stopped)); + assert!(store.get(path, &ExrSource::Bytes(bytes), &index, &want, Use::Other).is_ok(), "read again, not refused from memory"); +} + #[test] fn a_failed_picture_leaves_the_other_channels_readable() { let bytes: Arc<[u8]> = diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index 611e9e5fb..ca30f6994 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -221,6 +221,19 @@ pub(crate) const MAX_DECODE_BYTES: usize = 8 << 30; #[cfg(not(target_pointer_width = "64"))] pub(crate) const MAX_DECODE_BYTES: usize = 512 << 20; +/// What a failed `craft-exr` read means here. Memory the system refused just now is a read that +/// failed ([`ReadError::Io`]: the plane store doesn't remember it, another read may succeed), +/// not a file too large (remembered until the file changes). +pub(crate) fn read_error(e: seek::Error) -> ReadError { + match e { + seek::Error::Cancelled => ReadError::Cancelled, + seek::Error::Io(why) | seek::Error::OutOfMemory(why) => ReadError::Io(why), + seek::Error::LimitExceeded(why) => ReadError::TooLarge(format!("its OpenEXR channels need more memory than one file may use ({why})")), + seek::Error::Malformed(why) | seek::Error::Unsupported(why) | seek::Error::UnsupportedCompression(why) => ReadError::Unreadable(why), + other => ReadError::Unreadable(other.to_string()), + } +} + /// The most threads one read decompresses on (beside the caller's), and the size of a file /// whose chunks are decompressed on the calling thread alone. const READ_WORKERS: usize = 4; @@ -274,13 +287,7 @@ fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<( // pool the caller runs on: a few at most, and none for a small file (its chunks are // decompressed on the calling thread). request.workers = Some(if index.file.file_len() < SMALL_FILE { 0 } else { rayon::current_num_threads().min(READ_WORKERS) }); - let planes = seek::read_planes(src, &index.file, &request, &filmcraft_media::cancel::cancelled).map_err(|e| match e { - seek::Error::Cancelled => ReadError::Cancelled, - seek::Error::Io(why) => ReadError::Io(why), - seek::Error::LimitExceeded(why) => ReadError::TooLarge(format!("its OpenEXR channels need more memory than one file may use ({why})")), - seek::Error::Malformed(why) | seek::Error::Unsupported(why) | seek::Error::UnsupportedCompression(why) => ReadError::Unreadable(why), - other => ReadError::Unreadable(other.to_string()), - })?; + let planes = seek::read_planes(src, &index.file, &request, &filmcraft_media::cancel::cancelled).map_err(read_error)?; let stats = ReadStats { chunks: planes.stats.chunks, bytes: planes.stats.bytes, lines: planes.stats.lines }; Ok((planes.planes, stats)) } From b591f95ce48c75e876a36319760d13efd15bc47d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 21:49:18 +0100 Subject: [PATCH 214/324] OpenEXR: a file's channels may take what the machine's RAM allows, not a fixed 8 GiB (#3749) The limit of one read is decided here (the 8 GiB floor, or the memory budget when that is more) and handed to craft-exr as the read's max_bytes, so the planes it reserves and the largest block it decompresses follow it. craft-exr reserves the planes fallibly, so the reader's own fallible plane allocation is not needed: memory the system can't give is a read that failed just now (read_error), a plane over the limit a refusal for size. --- .../engine/src/settings/session_settings.rs | 5 ++ crates/host/src/lib.rs | 10 +++ crates/media/src/exr_index.rs | 3 +- crates/media/src/exr_planes.rs | 5 +- crates/media/src/exr_planes/tests.rs | 35 ++++++++ crates/media/src/exr_read.rs | 22 +++-- crates/render/src/memory.rs | 82 +++++++++++++++++++ 7 files changed, 153 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/settings/session_settings.rs b/crates/engine/src/settings/session_settings.rs index cc25f35ea..9a76dd84a 100644 --- a/crates/engine/src/settings/session_settings.rs +++ b/crates/engine/src/settings/session_settings.rs @@ -122,6 +122,11 @@ impl Session { let layers: std::sync::Arc = self.layer_cache.clone(); accountant.register(&layers); accountant.set_budget(b.bytes); + // (what one file's decoded planes may take follows it once the RAM is read, at least the + // fixed limit; until then the host's reader asks when a request is over that, #3749) + if b.installed.is_some() { + effectcraft_render::memory::set_decode_limit(Some(b.bytes)); + } // The process's measured memory as well (#3301: memory nobody accounts for, such as GPU // staging, effect buffers and the allocator's fragmentation): over the purge limit the // caches give way by what it is over, over the hard limit also the frames a playing diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 295476df0..159156a24 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -117,9 +117,19 @@ pub fn session() -> Session { // the settings, and the caches have no limits of their own below it. Without a memory // reading yet, the budget for unknown RAM. s.apply_cache_budgets(); + // The CLI and the MCP server read no memory: a request for a file's planes over the fixed + // limit asks for it once (#3749). + effectcraft_engine::render::memory::set_decode_limit_source(Some(installed_memory_budget)); s } +/// The memory budget of the installed RAM with the default settings: what one file's decoded +/// planes may take when a request is over the fixed limit and the session read no memory. +fn installed_memory_budget() -> Option { + let memory = effectcraft_engine::sysinfo::memory()?; + Some(effectcraft_engine::prefs::Prefs::default().memory_budget(Some(memory), false).bytes) +} + /// External effect helpers run as child processes: native builds only. #[cfg(not(target_arch = "wasm32"))] fn helper_hooks() -> Option { diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs index 988c3b370..425077c0a 100644 --- a/crates/media/src/exr_index.rs +++ b/crates/media/src/exr_index.rs @@ -150,7 +150,8 @@ const MAX_DATA_PIXELS: usize = 4 * MAX_DISPLAY_PIXELS; /// blocks of at most `craft-exr`'s default ratio of bytes per byte of their chunk (four times /// that for DWA, plus 1 MiB): a hostile header declaring a block of gigabytes over a chunk of a /// few bytes is refused, by every read and by [`safe_to_decode`]. A read's planes are bounded by -/// its own cap ([`crate::exr_read::MAX_DECODE_BYTES`]). +/// its own cap ([`crate::exr_read::MAX_DECODE_BYTES`], or more with more memory: +/// [`effectcraft_render::memory::decode_limit`]). fn limits() -> Limits { let mut limits = Limits::none(); limits.max_pixels = MAX_DATA_PIXELS as u64; diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index bf261491b..8b6daf167 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -434,14 +434,15 @@ pub(crate) fn set_cap(path: &str, bytes: usize) { CAPS.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), bytes)); } -/// The most bytes of planes one read of `path` may allocate. +/// The most bytes of planes one read of `path` may allocate by the caller's own limit (none: the +/// system's, [`effectcraft_render::memory::decode_limit`]). fn cap_of(path: &str) -> usize { #[cfg(test)] if let Some((_, c)) = CAPS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path) { return *c; } let _ = path; - crate::exr_read::MAX_DECODE_BYTES + usize::MAX } impl PlaneStore { diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 02f99a2c1..febc926ba 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1580,6 +1580,41 @@ fn a_failed_picture_leaves_the_other_channels_readable() { assert!(rest.aux.get("Z").is_some()); } +/// #3749: a read over the fixed floor is allowed up to what the system's memory gives (the +/// session's figure), never under the floor, and refused with a reason beyond it. The floor is +/// small here: the real one is 8 GiB. +#[test] +fn a_read_over_the_floor_is_allowed_up_to_the_systems_memory() { + let bytes = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)); + let mut src = std::io::Cursor::new(bytes.as_slice()); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); + // Four channels of 8×8 f32 are 1024 bytes; the floor is 512. + let request = ReadRequest { floor: 512, ..ReadRequest::full(vec![0, 1, 2, 3]) }; + let read = |src: &mut std::io::Cursor<&[u8]>| crate::exr_read::read_planes(src, &index, &request).0; + effectcraft_render::memory::set_decode_limit(None); + effectcraft_render::memory::set_decode_limit_source(None); + assert!(matches!(read(&mut src), Err(crate::exr_read::ReadError::TooLarge(_))), "over the floor, memory unknown"); + effectcraft_render::memory::set_decode_limit(Some(2048)); + assert_eq!(read(&mut src).map(|p| p.len()).ok(), Some(4), "the system's memory allows it"); + effectcraft_render::memory::set_decode_limit(Some(800)); + assert!(matches!(read(&mut src), Err(crate::exr_read::ReadError::TooLarge(_))), "still more than the system's memory"); + effectcraft_render::memory::set_decode_limit(None); +} + +/// #3749: a plane the system cannot give is not an aborted process: `craft-exr` asks for the +/// planes' memory first and reports what it can't get, a read that failed just now (asked again, +/// not remembered); a plane over the read's limit (the decode limit handed to it) is a refusal +/// for size with `craft-exr`'s reason. +#[test] +fn a_plane_the_system_cannot_give_is_refused_not_allocated() { + use crate::exr_read::{ReadError, read_error}; + use craft_exr::seek::Error; + let gone = read_error(Error::OutOfMemory("4096 bytes of planes".into())); + assert!(matches!(&gone, ReadError::Io(why) if why.contains("4096 bytes of planes")), "{gone:?}"); + let over = read_error(Error::LimitExceeded("the requested rows need 4096 bytes".into())); + assert!(matches!(&over, ReadError::TooLarge(why) if why.contains("4096 bytes")), "{over:?}"); +} + /// A two-rank Cryptomatte file of `size` with a picture: "cube" and "sphere" meet along a /// diagonal whose pixels hold both IDs (rank 00 the nearer, 55-75 %, rank 01 the other one with /// the rest), IDs and coverage stored as 32-bit floats. diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index ca30f6994..5f9151049 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -178,14 +178,17 @@ pub(crate) struct ReadRequest { pub(crate) rows: Option>, /// Every 2^level-th row and column of the display window (0: full resolution). pub(crate) level: u32, - /// The most bytes of planes the read may allocate. + /// The most bytes of planes the read may allocate (the caller's own limit; `usize::MAX`: only + /// the system's, [`effectcraft_render::memory::decode_limit`]). pub(crate) max_bytes: usize, + /// The fixed limit the system's memory may raise ([`MAX_DECODE_BYTES`]). + pub(crate) floor: usize, } impl ReadRequest { /// Every row of `channels` at full resolution. pub(crate) fn full(channels: Vec) -> ReadRequest { - ReadRequest { channels, rows: None, level: 0, max_bytes: MAX_DECODE_BYTES } + ReadRequest { channels, rows: None, level: 0, max_bytes: usize::MAX, floor: MAX_DECODE_BYTES } } } @@ -214,8 +217,10 @@ pub(crate) enum ReadError { Cancelled, } -/// The most bytes of planes one read allocates (every requested channel is a display-window -/// plane of f32): a header can ask for far more than the file holds. +/// The most bytes of planes one read allocates at least (every requested channel is a +/// display-window plane of f32): a header can ask for far more than the file holds, and a file's +/// size on disk says nothing about it. With more memory in the machine the limit is higher +/// ([`effectcraft_render::memory::decode_limit`], #3749). #[cfg(target_pointer_width = "64")] pub(crate) const MAX_DECODE_BYTES: usize = 8 << 30; #[cfg(not(target_pointer_width = "64"))] @@ -256,14 +261,19 @@ pub(crate) fn read_planes(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRe } } +fn gb(bytes: usize) -> f64 { + bytes as f64 / f64::from(1u32 << 30) +} + fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<(Vec>, ReadStats), ReadError> { let (w, h) = index.size(); let (ow, oh) = seek::level_size((w, h), req.level.min(16)); let n = ow.checked_mul(oh).ok_or_else(|| ReadError::Unreadable("display window".into()))?; let need = n.saturating_mul(req.channels.len()).saturating_mul(std::mem::size_of::()); - let most = req.max_bytes.min(MAX_DECODE_BYTES); + // (the limit is decided here and handed to `craft-exr` as the read's `max_bytes`: the planes + // it reserves, fallibly, and the largest block it decompresses follow it) + let most = req.max_bytes.min(effectcraft_render::memory::decode_limit(req.floor, need)); if need > most { - let gb = |b: usize| b as f64 / f64::from(1u32 << 30); return Err(ReadError::TooLarge(format!( "its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", w, diff --git a/crates/render/src/memory.rs b/crates/render/src/memory.rs index 7859be071..9c2cab435 100644 --- a/crates/render/src/memory.rs +++ b/crates/render/src/memory.rs @@ -419,6 +419,44 @@ impl Accountant { } } +/// What the system's memory allows one request for a file's decoded planes (an OpenEXR's +/// channels) to take; 0: not known yet ([`decode_limit`]). +static DECODE_LIMIT: AtomicUsize = AtomicUsize::new(0); + +/// Reads that limit from the system when nothing set it ([`set_decode_limit_source`]). +static DECODE_SOURCE: Mutex Option>> = Mutex::new(None); + +/// Set what the system's memory allows one request for a file's decoded planes to take +/// (`None`: unknown again). The session sets it with the memory budget once the installed RAM +/// is read. +pub fn set_decode_limit(bytes: Option) { + DECODE_LIMIT.store(bytes.unwrap_or(0), Ordering::Relaxed); +} + +/// Where [`decode_limit`] reads the limit from while nothing set it: the CLI and the MCP server +/// read no memory otherwise. The reading may take a second, so it is only asked for when a +/// request is over the fixed floor. +pub fn set_decode_limit_source(source: Option Option>) { + *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner) = source; +} + +/// The most bytes one request of `need` bytes for a file's decoded planes may take: `floor` +/// (the fixed limit), or what the system's memory allows when that is more. The system is +/// asked only when `need` is over `floor` (and once: the answer is kept, also "unknown", which +/// leaves `floor`). The browser keeps `floor`. +pub fn decode_limit(floor: usize, need: usize) -> usize { + if need <= floor || cfg!(target_arch = "wasm32") { + return floor; + } + let mut known = DECODE_LIMIT.load(Ordering::Relaxed); + if known == 0 { + let source = *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner); + known = source.and_then(|read| read()).unwrap_or(floor); + DECODE_LIMIT.store(known, Ordering::Relaxed); + } + floor.max(known) +} + #[cfg(test)] mod tests { use super::*; @@ -831,4 +869,48 @@ mod tests { acc.set_process_memory(process_now, 1_000, 2_000); assert!(preview.held() <= 200, "{}", preview.held()); } + + static ASKED: AtomicUsize = AtomicUsize::new(0); + + fn ram_says() -> Option { + ASKED.fetch_add(1, Ordering::SeqCst); + Some(300) + } + + fn ram_unknown() -> Option { + ASKED.fetch_add(1, Ordering::SeqCst); + None + } + + /// #3749: a request for a file's planes may take the fixed floor, or the system's memory + /// when that is more: the system is asked only for a request over the floor, once. + #[test] + fn a_request_over_the_floor_is_limited_by_the_systems_memory() { + let _serial = PROCESS_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + set_decode_limit(None); + set_decode_limit_source(Some(ram_says)); + ASKED.store(0, Ordering::SeqCst); + // Under the floor: nobody is asked. + assert_eq!(decode_limit(100, 50), 100); + assert_eq!(ASKED.load(Ordering::SeqCst), 0, "a request under the floor reads no memory"); + // Over it: the system's 300, asked once. + assert_eq!(decode_limit(100, 200), 300); + assert_eq!(decode_limit(100, 250), 300); + assert_eq!(ASKED.load(Ordering::SeqCst), 1, "asked once, then kept"); + // A smaller figure than the floor never lowers it. + set_decode_limit(Some(40)); + assert_eq!(decode_limit(100, 200), 100); + // The session's figure replaces the asked one. + set_decode_limit(Some(900)); + assert_eq!(decode_limit(100, 200), 900); + // Unknown memory leaves the floor, and is not asked again. + set_decode_limit(None); + set_decode_limit_source(Some(ram_unknown)); + ASKED.store(0, Ordering::SeqCst); + assert_eq!(decode_limit(100, 200), 100); + assert_eq!(decode_limit(100, 200), 100); + assert_eq!(ASKED.load(Ordering::SeqCst), 1, "an unknown reading is kept too"); + set_decode_limit(None); + set_decode_limit_source(None); + } } From bdf500f4bad552790dc9decb4af840c928cefe76 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 21:52:34 +0100 Subject: [PATCH 215/324] OpenEXR limit: a refusal for size is decided anew when the limit changes; a failed reading is asked twice (#3749 review) --- crates/media/src/exr_planes.rs | 17 +++++-- crates/media/src/exr_planes/tests.rs | 30 ++++++++++++ crates/render/src/memory.rs | 71 +++++++++++++++++++++++----- 3 files changed, 100 insertions(+), 18 deletions(-) diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index 8b6daf167..5b08d67ec 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -183,6 +183,10 @@ struct Flight { /// When the decode was asked for ([`effectcraft_render::memory::tick`]): what it took is the /// planes' cost to the memory accountant. asked: u64, + /// The decode limit's generation when the decode was asked for + /// ([`effectcraft_render::memory::decode_limit_generation`]): a refusal for its size holds + /// only while the limit stays as it was. + limit_generation: u64, } /// [`Flight::phase`] values. @@ -219,6 +223,7 @@ impl Flight { since, hints: filmcraft_media::cancel::Context::current(), asked: effectcraft_render::memory::tick(), + limit_generation: effectcraft_render::memory::decode_limit_generation(), }) } @@ -276,8 +281,9 @@ struct Entry { flight: Option>, /// Requests that failed for good (unreadable, too large), the index they were made with, and /// why: a request of that index (the file as it was) asking for at - /// least as much fails the same way until the file is forgotten. - failed: Vec<(Arc, Want, Refused)>, + /// least as much fails the same way until the file is forgotten, or the decode limit changed + /// (the last number: its generation when the request was made). + failed: Vec<(Arc, Want, Refused, u64)>, bytes: usize, /// When it was last asked for or finished decoding ([`effectcraft_render::memory::tick`]). used: u64, @@ -522,7 +528,8 @@ impl PlaneStore { return Step::Done(Ok(b)); } // (a failure of the file as it was before: the file changed since, it is read again) - if let Some((_, _, why)) = e.failed.iter().find(|(of, failed, _)| Arc::ptr_eq(of, index) && asks_at_least(index, want, failed)) { + let limit = effectcraft_render::memory::decode_limit_generation(); + if let Some((_, _, why, _)) = e.failed.iter().find(|(of, failed, _, made_at)| Arc::ptr_eq(of, index) && *made_at == limit && asks_at_least(index, want, failed)) { return Step::Done(Err(why.clone())); } if let Some(flight) = e.flight.clone() { @@ -671,11 +678,11 @@ impl PlaneStore { (fs.index.clone(), fs.want.clone()) }; // (failures of another version of the file no longer apply) - e.failed.retain(|(of, _, _)| Arc::ptr_eq(of, &index)); + e.failed.retain(|(of, _, _, made_at)| Arc::ptr_eq(of, &index) && *made_at == flight.limit_generation); if e.failed.len() >= FAILED_KEPT { e.failed.remove(0); } - e.failed.push((index, want, why.clone())); + e.failed.push((index, want, why.clone(), flight.limit_generation)); } // (the file changed: what is held is of the old one) Err(Refused::Changed) => { diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index febc926ba..76b02d4cb 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1580,11 +1580,16 @@ fn a_failed_picture_leaves_the_other_channels_readable() { assert!(rest.aux.get("Z").is_some()); } +/// The tests that move the process-wide decode limit take turns (it also dates the remembered +/// refusals). +static LIMIT_TESTS: Mutex<()> = Mutex::new(()); + /// #3749: a read over the fixed floor is allowed up to what the system's memory gives (the /// session's figure), never under the floor, and refused with a reason beyond it. The floor is /// small here: the real one is 8 GiB. #[test] fn a_read_over_the_floor_is_allowed_up_to_the_systems_memory() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); let bytes = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)); let mut src = std::io::Cursor::new(bytes.as_slice()); let index = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); @@ -1601,6 +1606,31 @@ fn a_read_over_the_floor_is_allowed_up_to_the_systems_memory() { effectcraft_render::memory::set_decode_limit(None); } +/// #3749: a refusal for the request's size is remembered only while the decode limit stays as it +/// was: when the system's memory figure arrives or changes, the request is decided anew. +#[test] +fn a_refusal_for_size_is_decided_anew_when_the_decode_limit_changes() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let path = "/3749-refusal-generation.exr"; + // Room for one plane of 8×8 f32: four are refused. + set_cap(path, 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(bytes); + let index = crate::exr_index::get(path, &source).unwrap(); + let want = Want { all: false, ids: (0..4).collect() }; + let refused = || matches!(store.get(path, &source, &index, &want, Use::Other), Err(Refused::TooLarge(_))); + assert!(refused()); + assert!(refused()); + assert_eq!(decodes_of(path).len(), 1, "the second refusal came from memory"); + // (figures under the fixed floor: only the change counts, no other test's limit moves) + effectcraft_render::memory::set_decode_limit(Some(1000)); + effectcraft_render::memory::set_decode_limit(Some(2000)); + assert!(refused(), "still over the caller's own limit"); + assert_eq!(decodes_of(path).len(), 2, "decided anew after the limit changed"); + effectcraft_render::memory::set_decode_limit(None); +} + /// #3749: a plane the system cannot give is not an aborted process: `craft-exr` asks for the /// planes' memory first and reports what it can't get, a read that failed just now (asked again, /// not remembered); a plane over the read's limit (the decode limit handed to it) is a refusal diff --git a/crates/render/src/memory.rs b/crates/render/src/memory.rs index 9c2cab435..ae8d02104 100644 --- a/crates/render/src/memory.rs +++ b/crates/render/src/memory.rs @@ -423,14 +423,40 @@ impl Accountant { /// channels) to take; 0: not known yet ([`decode_limit`]). static DECODE_LIMIT: AtomicUsize = AtomicUsize::new(0); +/// Counts the changes of that limit: a refusal made under an older one is out of date +/// ([`decode_limit_generation`]). +static DECODE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// How often the system was asked for the limit without an answer ([`decode_limit`]). +static DECODE_UNANSWERED: AtomicUsize = AtomicUsize::new(0); + /// Reads that limit from the system when nothing set it ([`set_decode_limit_source`]). static DECODE_SOURCE: Mutex Option>> = Mutex::new(None); +/// One reading of the system at a time: the second asker takes the first one's answer. +static DECODE_ASKING: Mutex<()> = Mutex::new(()); + +/// The system is asked this often at most for the limit when it does not answer. +const DECODE_ASKS: usize = 2; + +fn store_decode_limit(bytes: usize) { + if DECODE_LIMIT.swap(bytes, Ordering::Relaxed) != bytes { + DECODE_GENERATION.fetch_add(1, Ordering::Relaxed); + } +} + /// Set what the system's memory allows one request for a file's decoded planes to take /// (`None`: unknown again). The session sets it with the memory budget once the installed RAM /// is read. pub fn set_decode_limit(bytes: Option) { - DECODE_LIMIT.store(bytes.unwrap_or(0), Ordering::Relaxed); + store_decode_limit(bytes.unwrap_or(0)); + DECODE_UNANSWERED.store(0, Ordering::Relaxed); +} + +/// Changes whenever [`decode_limit`] gives another answer: a request refused for its size is +/// asked again after that. +pub fn decode_limit_generation() -> u64 { + DECODE_GENERATION.load(Ordering::Relaxed) } /// Where [`decode_limit`] reads the limit from while nothing set it: the CLI and the MCP server @@ -438,23 +464,31 @@ pub fn set_decode_limit(bytes: Option) { /// request is over the fixed floor. pub fn set_decode_limit_source(source: Option Option>) { *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner) = source; + DECODE_UNANSWERED.store(0, Ordering::Relaxed); } /// The most bytes one request of `need` bytes for a file's decoded planes may take: `floor` /// (the fixed limit), or what the system's memory allows when that is more. The system is -/// asked only when `need` is over `floor` (and once: the answer is kept, also "unknown", which -/// leaves `floor`). The browser keeps `floor`. +/// asked only when `need` is over `floor`, and the answer is kept; when it gives none (a reading +/// that failed) it is asked once more later, then `floor` stays. The browser keeps `floor`. pub fn decode_limit(floor: usize, need: usize) -> usize { if need <= floor || cfg!(target_arch = "wasm32") { return floor; } - let mut known = DECODE_LIMIT.load(Ordering::Relaxed); - if known == 0 { - let source = *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner); - known = source.and_then(|read| read()).unwrap_or(floor); - DECODE_LIMIT.store(known, Ordering::Relaxed); + if DECODE_LIMIT.load(Ordering::Relaxed) == 0 && DECODE_UNANSWERED.load(Ordering::Relaxed) < DECODE_ASKS { + let _asking = DECODE_ASKING.lock().unwrap_or_else(PoisonError::into_inner); + // (another thread may have just read it) + if DECODE_LIMIT.load(Ordering::Relaxed) == 0 { + let source = *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner); + match source.and_then(|read| read()) { + Some(bytes) => store_decode_limit(bytes), + None => { + DECODE_UNANSWERED.fetch_add(1, Ordering::Relaxed); + } + } + } } - floor.max(known) + floor.max(DECODE_LIMIT.load(Ordering::Relaxed)) } #[cfg(test)] @@ -903,13 +937,24 @@ mod tests { // The session's figure replaces the asked one. set_decode_limit(Some(900)); assert_eq!(decode_limit(100, 200), 900); - // Unknown memory leaves the floor, and is not asked again. + // Unknown memory leaves the floor; a reading that failed once is tried once more, then + // not asked again (and what is not known is never kept as the floor). set_decode_limit(None); set_decode_limit_source(Some(ram_unknown)); ASKED.store(0, Ordering::SeqCst); - assert_eq!(decode_limit(100, 200), 100); - assert_eq!(decode_limit(100, 200), 100); - assert_eq!(ASKED.load(Ordering::SeqCst), 1, "an unknown reading is kept too"); + for _ in 0..4 { + assert_eq!(decode_limit(100, 200), 100); + } + assert_eq!(ASKED.load(Ordering::SeqCst), 2, "a failed reading is tried twice"); + // A source that answers later is not shut out by the floor kept earlier. + set_decode_limit_source(Some(ram_says)); + assert_eq!(decode_limit(7, 200), 300, "a limit is not tied to the floor of an earlier request"); + // The generation tells that the limit changed. + let before = decode_limit_generation(); + set_decode_limit(Some(300)); + assert_eq!(decode_limit_generation(), before, "the same figure is no change"); + set_decode_limit(Some(500)); + assert_ne!(decode_limit_generation(), before); set_decode_limit(None); set_decode_limit_source(None); } From a7e7cb6b6a688a2191d05a03f6d4b77fd1cc0d33 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 21:53:52 +0100 Subject: [PATCH 216/324] OpenEXR limit: only a refusal for size depends on the limit's generation; sequentially consistent counters (#3749 review) --- crates/media/src/exr_planes.rs | 8 ++++++-- crates/render/src/memory.rs | 16 +++++++++------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index 5b08d67ec..a7a3c62cc 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -529,7 +529,9 @@ impl PlaneStore { } // (a failure of the file as it was before: the file changed since, it is read again) let limit = effectcraft_render::memory::decode_limit_generation(); - if let Some((_, _, why, _)) = e.failed.iter().find(|(of, failed, _, made_at)| Arc::ptr_eq(of, index) && *made_at == limit && asks_at_least(index, want, failed)) { + if let Some((_, _, why, _)) = e.failed.iter().find(|(of, failed, refusal, made_at)| { + Arc::ptr_eq(of, index) && (!matches!(refusal, Refused::TooLarge(_)) || *made_at == limit) && asks_at_least(index, want, failed) + }) { return Step::Done(Err(why.clone())); } if let Some(flight) = e.flight.clone() { @@ -678,7 +680,9 @@ impl PlaneStore { (fs.index.clone(), fs.want.clone()) }; // (failures of another version of the file no longer apply) - e.failed.retain(|(of, _, _, made_at)| Arc::ptr_eq(of, &index) && *made_at == flight.limit_generation); + // (a refusal for the size counts under the limit it was made under only) + e.failed + .retain(|(of, _, old, made_at)| Arc::ptr_eq(of, &index) && (!matches!(old, Refused::TooLarge(_)) || *made_at == flight.limit_generation)); if e.failed.len() >= FAILED_KEPT { e.failed.remove(0); } diff --git a/crates/render/src/memory.rs b/crates/render/src/memory.rs index ae8d02104..d1600551b 100644 --- a/crates/render/src/memory.rs +++ b/crates/render/src/memory.rs @@ -440,8 +440,10 @@ static DECODE_ASKING: Mutex<()> = Mutex::new(()); const DECODE_ASKS: usize = 2; fn store_decode_limit(bytes: usize) { - if DECODE_LIMIT.swap(bytes, Ordering::Relaxed) != bytes { - DECODE_GENERATION.fetch_add(1, Ordering::Relaxed); + // (the limit before its generation, both sequentially consistent: whoever sees the new + // generation sees the new limit) + if DECODE_LIMIT.swap(bytes, Ordering::SeqCst) != bytes { + DECODE_GENERATION.fetch_add(1, Ordering::SeqCst); } } @@ -456,7 +458,7 @@ pub fn set_decode_limit(bytes: Option) { /// Changes whenever [`decode_limit`] gives another answer: a request refused for its size is /// asked again after that. pub fn decode_limit_generation() -> u64 { - DECODE_GENERATION.load(Ordering::Relaxed) + DECODE_GENERATION.load(Ordering::SeqCst) } /// Where [`decode_limit`] reads the limit from while nothing set it: the CLI and the MCP server @@ -475,10 +477,10 @@ pub fn decode_limit(floor: usize, need: usize) -> usize { if need <= floor || cfg!(target_arch = "wasm32") { return floor; } - if DECODE_LIMIT.load(Ordering::Relaxed) == 0 && DECODE_UNANSWERED.load(Ordering::Relaxed) < DECODE_ASKS { + if DECODE_LIMIT.load(Ordering::SeqCst) == 0 { let _asking = DECODE_ASKING.lock().unwrap_or_else(PoisonError::into_inner); - // (another thread may have just read it) - if DECODE_LIMIT.load(Ordering::Relaxed) == 0 { + // (another thread may have just read it, or have used up the asks) + if DECODE_LIMIT.load(Ordering::SeqCst) == 0 && DECODE_UNANSWERED.load(Ordering::Relaxed) < DECODE_ASKS { let source = *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner); match source.and_then(|read| read()) { Some(bytes) => store_decode_limit(bytes), @@ -488,7 +490,7 @@ pub fn decode_limit(floor: usize, need: usize) -> usize { } } } - floor.max(DECODE_LIMIT.load(Ordering::Relaxed)) + floor.max(DECODE_LIMIT.load(Ordering::SeqCst)) } #[cfg(test)] From f08a2290c223f50797a01d0dae1e79da0272d1d3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 17:49:20 +0100 Subject: [PATCH 217/324] OpenEXR limit: the planes a request ends with count together, held and from the disk cache too (#3749) The limit applied to the planes read from the file just now, so planes held in memory or handed back by the disk cache were never counted and repeated requests could pass it. It now applies to what the request ends with, asked before anything is read or allocated. When the held planes don't fit with the missing ones they are let go and the request is read on its own; only a request that doesn't fit alone is refused. --- crates/media/src/exr_planes.rs | 58 ++++++++++++++------- crates/media/src/exr_planes/tests.rs | 78 +++++++++++++++++++++++++++- crates/media/src/exr_read.rs | 25 ++++++--- 3 files changed, 133 insertions(+), 28 deletions(-) diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index a7a3c62cc..917dab4e3 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -907,6 +907,26 @@ fn run(path: &str, source: &ExrSource, flight: &Arc, base: Option Refused { + match e { + ReadError::Cancelled => Refused::Cancelled, + // (a read that failed just now: the next request reads again) + ReadError::Io(why) => { + log::warn!("media: {path}: {why}"); + Refused::Stopped + } + ReadError::TooLarge(why) => { + log::warn!("media: {path}: {why}"); + Refused::TooLarge(why) + } + ReadError::Unreadable(why) => { + log::warn!("media: {path}: {why}"); + Refused::Unreadable + } + } +} + /// Decode what `flight` asks for and `base` doesn't hold, and make the union of both. fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option>, opened: Option) -> Result, Refused> { let _decoding = Decoding::new(); @@ -947,10 +967,25 @@ fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option = wanted.into_iter().filter(|i| *i < index.channels.len()).collect(); - let base = base.filter(|b| Arc::ptr_eq(&b.index, &index)); - let missing: Vec = wanted.iter().copied().filter(|id| !base.as_ref().is_some_and(|b| b.ids.binary_search(id).is_ok())).collect(); - let names: Vec = missing.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); + let mut base = base.filter(|b| Arc::ptr_eq(&b.index, &index)); + let mut missing: Vec = wanted.iter().copied().filter(|id| !base.as_ref().is_some_and(|b| b.ids.binary_search(id).is_ok())).collect(); let (w, h) = index.size(); + // The planes the request ends with (those held plus those missing, whether they come from the + // disk cache or the file) must fit the limit, asked before any of them is allocated (#3749). + // The planes held are only kept for later requests: when they don't fit with the missing + // ones, they are let go and the request is read on its own. + if !missing.is_empty() { + let held = base.as_ref().map_or(0, |b| b.ids.len()); + let together = crate::exr_read::check_total(w, h, held.saturating_add(missing.len()), cap_of(path)); + if together.is_err() && base.is_some() { + base = None; + missing = wanted.clone(); + } + if base.is_none() { + crate::exr_read::check_total(w, h, missing.len(), cap_of(path)).map_err(|e| refused(path, e))?; + } + } + let names: Vec = missing.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); // The disk tier first (#3271): what an earlier session or a decode RAM let go of kept, one // entry per channel (any request is assembled from them, whatever was asked before). // (a file naming two channels alike can't tell their entries apart: not kept) @@ -984,22 +1019,7 @@ fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option> = read.map_err(|e| match e { - ReadError::Cancelled => Refused::Cancelled, - // (a read that failed just now: the next request reads again) - ReadError::Io(why) => { - log::warn!("media: {path}: {why}"); - Refused::Stopped - } - ReadError::TooLarge(why) => { - log::warn!("media: {path}: {why}"); - Refused::TooLarge(why) - } - ReadError::Unreadable(why) => { - log::warn!("media: {path}: {why}"); - Refused::Unreadable - } - })?; + let read: Vec> = read.map_err(|e| refused(path, e))?; let mut read = read.into_iter(); let planes: Vec> = kept.iter_mut().map(|k| k.take().or_else(|| read.next()).unwrap_or_default()).collect(); // The union, in file order: the planes held and the ones just read. diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 76b02d4cb..313302a4a 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1619,18 +1619,92 @@ fn a_refusal_for_size_is_decided_anew_when_the_decode_limit_changes() { let source = ExrSource::Bytes(bytes); let index = crate::exr_index::get(path, &source).unwrap(); let want = Want { all: false, ids: (0..4).collect() }; + // (the refusal is made before anything is read: the decodes are counted as they begin) + let begun = Arc::new(AtomicU64::new(0)); + { + let begun = begun.clone(); + set_before_read( + path, + Some(Arc::new(move |_: &str| { + begun.fetch_add(1, Ordering::SeqCst); + })), + ); + } let refused = || matches!(store.get(path, &source, &index, &want, Use::Other), Err(Refused::TooLarge(_))); assert!(refused()); assert!(refused()); - assert_eq!(decodes_of(path).len(), 1, "the second refusal came from memory"); + assert_eq!(begun.load(Ordering::SeqCst), 1, "the second refusal came from memory"); // (figures under the fixed floor: only the change counts, no other test's limit moves) effectcraft_render::memory::set_decode_limit(Some(1000)); effectcraft_render::memory::set_decode_limit(Some(2000)); assert!(refused(), "still over the caller's own limit"); - assert_eq!(decodes_of(path).len(), 2, "decided anew after the limit changed"); + assert_eq!(begun.load(Ordering::SeqCst), 2, "decided anew after the limit changed"); + set_before_read(path, None); effectcraft_render::memory::set_decode_limit(None); } +/// A file of an 8×8 picture and a depth plane: five planes of 256 bytes. +fn picture_and_depth() -> Vec { + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false)], (8, 8), Compression::ZIP1)], (8, 8)) +} + +/// #3749 (#3301 review): the limit is for the planes a request ends with, not for the ones read +/// just now: channels added to the planes held count with them. When together they are over +/// the limit the planes held are let go and the request is read on its own (it fits alone); a +/// request that doesn't fit alone is refused, whatever is held. +#[test] +fn channels_added_to_the_planes_held_count_toward_the_limit() { + let path = "/3749-held-and-added.exr"; + // Room for four planes: the picture fits, one more with it is five. + set_cap(path, 4 * 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(picture_and_depth().into()); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits"); + let rest = Want { all: true, ids: Default::default() }; + let depth = store.get(path, &source, &index, &rest, Use::Other).expect("the depth plane fits alone"); + assert!(depth.aux.get("Z").is_some()); + assert!(depth.aux.get("R").is_none(), "the picture's planes were let go: four held and one more are five"); + // The picture again: it fits alone, the depth plane is let go in turn. + let again = store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits alone"); + assert!(again.aux.get("R").is_some() && again.aux.get("Z").is_none()); + // Everything at once is five planes: refused, however it is asked. + let everything = Want { all: true, ids: (0..5).collect() }; + assert!(matches!(store.get(path, &source, &index, &everything, Use::Other).err(), Some(Refused::TooLarge(_)))); +} + +/// #3749 (#3301 review): planes the disk cache gives back count toward the limit of a request +/// like the ones read from the file. +#[test] +fn planes_from_the_disk_cache_count_toward_the_limit() { + use effectcraft_render::disk_cache::DiskCache; + let dir = std::env::temp_dir().join(format!("ec-3749-disk-union-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("union_0001.exr"); + std::fs::write(&file, picture_and_depth()).unwrap(); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + dc.set_read_us_per_mb(0); + use_disk_for(&dir.to_string_lossy()); + set_disk_cache(Some(&dc)); + let path = file.to_string_lossy().to_string(); + let source = ExrSource::File(file.clone()); + let index = crate::exr_index::get(&path, &source).unwrap(); + let all = Want { all: true, ids: (0..5).collect() }; + let first = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).is_ok(); + dc.flush(); + // All five planes are in the disk cache (a store without them in RAM reads them back)... + let warm = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).is_ok(); + let from_disk = decodes_of(&path).last().is_some_and(|d| d.from_disk); + // ...and a request may use four. + set_cap(&path, 4 * 8 * 8 * 4); + let refused = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).err(); + set_disk_cache(None); + let _ = std::fs::remove_dir_all(&dir); + assert!(first && warm && from_disk, "decoded without a limit, then read back from the disk cache"); + assert!(matches!(refused, Some(Refused::TooLarge(_))), "{refused:?}"); +} + /// #3749: a plane the system cannot give is not an aborted process: `craft-exr` asks for the /// planes' memory first and reports what it can't get, a read that failed just now (asked again, /// not remembered); a plane over the read's limit (the decode limit handed to it) is a refusal diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index 5f9151049..5624fc2d0 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -265,6 +265,23 @@ fn gb(bytes: usize) -> f64 { bytes as f64 / f64::from(1u32 << 30) } +fn too_large(w: usize, h: usize, need: usize, most: usize) -> ReadError { + ReadError::TooLarge(format!("its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", w, h, gb(need), gb(most))) +} + +/// Refuse a request whose planes together, those already in hand (held in memory or read back +/// from the disk cache) and those still to read, `planes` of a `w` × `h` display window, need +/// more memory than one file may use: the limit is for what a file's request ends with, not +/// for the part of it read just now ([`effectcraft_render::memory::decode_limit`], #3749). +pub(crate) fn check_total(w: usize, h: usize, planes: usize, max_bytes: usize) -> Result<(), ReadError> { + let need = w.saturating_mul(h).saturating_mul(planes).saturating_mul(std::mem::size_of::()); + let most = max_bytes.min(effectcraft_render::memory::decode_limit(MAX_DECODE_BYTES, need)); + if need > most { + return Err(too_large(w, h, need, most)); + } + Ok(()) +} + fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<(Vec>, ReadStats), ReadError> { let (w, h) = index.size(); let (ow, oh) = seek::level_size((w, h), req.level.min(16)); @@ -274,13 +291,7 @@ fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<( // it reserves, fallibly, and the largest block it decompresses follow it) let most = req.max_bytes.min(effectcraft_render::memory::decode_limit(req.floor, need)); if need > most { - return Err(ReadError::TooLarge(format!( - "its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", - w, - h, - gb(need), - gb(most) - ))); + return Err(too_large(w, h, need, most)); } let mut channels = Vec::with_capacity(req.channels.len()); let mut fill = Vec::with_capacity(req.channels.len()); From c0c53353fefd5229b7054d0b2afb0d9050e2208c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 23:35:44 +0100 Subject: [PATCH 218/324] OpenEXR limit: memory the system refuses is neither remembered nor read again at once, and never handed to the whole file's decode (#3749 review) craft-exr's OutOfMemory is now a refusal of its own (ReadError::OutOfMemory, Refused::NoMemory) instead of a failed read: the store doesn't remember it, doesn't retry it or read a copy, and a picture without memory for its effects' channels is read alone, else refused with the reason, as for a file too large; never the image crate's decode of the whole file. The planes held, copied into a request's new set, are reserved fallibly too; a copy for the disk cache that can't be had is not written. The tests that set the process-wide disk cache take turns, and a test shows that an unreadable request stays refused when the decode limit changes. --- crates/media/src/exr_planes.rs | 86 ++++++++++++++++++--- crates/media/src/exr_planes/tests.rs | 111 +++++++++++++++++++++++++-- crates/media/src/exr_read.rs | 13 +++- 3 files changed, 191 insertions(+), 19 deletions(-) diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs index 917dab4e3..13e46da60 100644 --- a/crates/media/src/exr_planes.rs +++ b/crates/media/src/exr_planes.rs @@ -150,6 +150,9 @@ pub(crate) enum Refused { Unreadable, /// More planes than one file may allocate (the reason; remembered). TooLarge(String), + /// The system refused the memory the planes need just now (the reason): not remembered, + /// but not asked again at once either, nor read as a whole file another way (#3749). + NoMemory(String), /// The request was called off. Cancelled, /// The file changed since it was indexed: index it again and ask again. @@ -430,8 +433,9 @@ pub(crate) fn set_before_read(path: &str, hook: Option) { } } -/// Planes of `path` may take at most this many bytes in a read (tests: a small cap in place of -/// [`crate::exr_read::MAX_DECODE_BYTES`]). +/// Planes of `path` may take at most this many bytes in a read (tests: a cap of the caller's own, +/// below the system's limit; outside tests there is none, `usize::MAX`, and only +/// [`effectcraft_render::memory::decode_limit`] applies). #[cfg(test)] static CAPS: Mutex> = Mutex::new(Vec::new()); @@ -657,7 +661,7 @@ impl PlaneStore { let clock = effectcraft_render::memory::tick(); let Some(e) = st.entries.iter_mut().find(|e| e.path == path && e.flight.as_ref().is_some_and(|f| Arc::ptr_eq(f, flight))) else { let outcome = match outcome { - Err(e @ (Refused::Cancelled | Refused::Stopped)) => Err(e), + Err(e @ (Refused::Cancelled | Refused::Stopped | Refused::NoMemory(_))) => Err(e), _ => Err(Refused::Forgotten), }; return (outcome, 0); @@ -694,7 +698,8 @@ impl PlaneStore { e.bytes = 0; e.cost_us = 0; } - Err(Refused::Cancelled | Refused::Forgotten | Refused::Stopped) => {} + // (memory refused just now: another request may get it) + Err(Refused::Cancelled | Refused::Forgotten | Refused::Stopped | Refused::NoMemory(_)) => {} } let grown = st.entries.iter().find(|e| e.path == path).map_or(0, |e| e.bytes.saturating_sub(had)); Self::drop_oldest(&mut st, self.budget(), CACHE_FILES, Some(path)); @@ -920,6 +925,10 @@ fn refused(path: &str, e: ReadError) -> Refused { log::warn!("media: {path}: {why}"); Refused::TooLarge(why) } + ReadError::OutOfMemory(why) => { + log::warn!("media: {path}: {why}"); + Refused::NoMemory(why) + } ReadError::Unreadable(why) => { log::warn!("media: {path}: {why}"); Refused::Unreadable @@ -927,6 +936,53 @@ fn refused(path: &str, e: ReadError) -> Refused { } } +/// A copy of `plane`, or `None` when the system can't give the memory for it (an allocation that +/// fails aborts the process, so it is asked for first). +fn copy_plane(plane: &[f32]) -> Option> { + let mut copy: Vec = Vec::new(); + copy.try_reserve_exact(plane.len()).ok()?; + copy.extend_from_slice(plane); + Some(copy) +} + +/// Why `planes` planes of a `w` × `h` display window couldn't be had (to show). +fn no_memory_for(w: usize, h: usize, planes: usize) -> String { + let bytes = w.saturating_mul(h).saturating_mul(planes).saturating_mul(std::mem::size_of::()); + format!("its {w}×{h} OpenEXR channels need {:.1} GB more memory than the system can give just now", bytes as f64 / f64::from(1u32 << 30)) +} + +/// Fails the reads of a path as a test says, for the channels read ([`set_read_error`]). +#[cfg(test)] +pub(crate) type ForcedError = Arc Option + Send + Sync>; +#[cfg(test)] +static READ_ERRORS: Mutex> = Mutex::new(Vec::new()); + +/// Make reads of `path` fail as `error` says for the channels read, instead of reading (`None`: +/// read again; tests: memory the system refuses). Keyed by path, so tests running at the same +/// time don't see each other's. +#[cfg(test)] +pub(crate) fn set_read_error(path: &str, error: Option) { + let mut errors = READ_ERRORS.lock().unwrap_or_else(PoisonError::into_inner); + errors.retain(|(p, _)| p != path); + if let Some(e) = error { + errors.push((path.to_string(), e)); + } +} + +/// How a test makes the read of `ids` of `path` fail ([`set_read_error`]); never outside tests. +fn forced_read_error(path: &str, ids: &[usize]) -> Option { + #[cfg(test)] + { + let error = READ_ERRORS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, e)| e.clone()); + error.and_then(|e| e(ids)) + } + #[cfg(not(test))] + { + let _ = (path, ids); + None + } +} + /// Decode what `flight` asks for and `base` doesn't hold, and make the union of both. fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option>, opened: Option) -> Result, Refused> { let _decoding = Decoding::new(); @@ -1010,6 +1066,8 @@ fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option, base: Option, base: Option b, Err(Refused::Changed) => continue, // The channels with it are too many: the picture alone (the effects ask for theirs). - Err(Refused::TooLarge(_)) if extra.is_some() => { + // (also when the system has no memory for them just now, #3749) + Err(Refused::TooLarge(_) | Refused::NoMemory(_)) if extra.is_some() => { extra = None; continue; } - Err(Refused::TooLarge(why)) => return Picture::Done(Err(why)), + // (never the whole file's decode: the memory isn't there for it either) + Err(Refused::TooLarge(why) | Refused::NoMemory(why)) => return Picture::Done(Err(why)), Err(Refused::Cancelled | Refused::Forgotten) => return Picture::Cancelled, // (the whole file's decode says why) Err(Refused::Stopped | Refused::Unreadable) => return Picture::Legacy, @@ -1290,7 +1353,10 @@ pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i return picture(path, source, op, None); } let request = ReadRequest { rows: Some(rows.0..rows.1), max_bytes: cap_of(path), ..ReadRequest::full(ids.clone()) }; - let (planes, stats) = read_planes(&mut *opened.reader, &index, &request); + let (planes, stats) = match forced_read_error(path, &ids) { + Some(e) => (Err(e), Default::default()), + None => read_planes(&mut *opened.reader, &index, &request), + }; let names: Vec = ids.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); #[cfg(test)] DECODES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), DecodeRecord { channels: names.clone(), stats, from_disk: false })); @@ -1299,7 +1365,7 @@ pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i let planes = match planes { Ok(p) => p, Err(ReadError::Cancelled) => return Picture::Cancelled, - Err(ReadError::TooLarge(why)) => return Picture::Done(Err(why)), + Err(ReadError::TooLarge(why) | ReadError::OutOfMemory(why)) => return Picture::Done(Err(why)), Err(_) => return Picture::Legacy, }; let (w, h) = index.size(); diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index 313302a4a..a08dc87fc 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1075,8 +1075,12 @@ fn a_new_frame_opens_its_file_once() { /// them go they are read back from there, bit for bit (Cryptomatte IDs included), whatever was /// asked for before (the picture first, then the channels, then all of it after an eviction); /// Reload Footage drops them. +/// The tests that set the process-wide disk cache take turns (one would switch off another's). +static DISK_TESTS: Mutex<()> = Mutex::new(()); + #[test] fn decoded_planes_are_kept_on_disk_and_read_back_exactly() { + let _disk = DISK_TESTS.lock().unwrap_or_else(PoisonError::into_inner); use effectcraft_render::disk_cache::{DiskCache, Kind}; let dir = std::env::temp_dir().join(format!("ec-3271-disk-planes-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -1549,7 +1553,7 @@ fn a_failure_is_forgotten_once_the_file_changes() { #[test] fn an_allocation_failure_is_not_remembered() { use crate::exr_read::{ReadError, read_error}; - assert_eq!(read_error(craft_exr::seek::Error::OutOfMemory("planes".into())), ReadError::Io("planes".into())); + assert!(matches!(read_error(craft_exr::seek::Error::OutOfMemory("planes".into())), ReadError::OutOfMemory(why) if why.contains("planes"))); assert!(matches!(read_error(craft_exr::seek::Error::LimitExceeded("planes".into())), ReadError::TooLarge(_))); // A read that failed just now (here: the file can't be opened) is a stop, and the next // request for the same channels reads them. @@ -1678,6 +1682,7 @@ fn channels_added_to_the_planes_held_count_toward_the_limit() { /// like the ones read from the file. #[test] fn planes_from_the_disk_cache_count_toward_the_limit() { + let _disk = DISK_TESTS.lock().unwrap_or_else(PoisonError::into_inner); use effectcraft_render::disk_cache::DiskCache; let dir = std::env::temp_dir().join(format!("ec-3749-disk-union-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -1706,19 +1711,115 @@ fn planes_from_the_disk_cache_count_toward_the_limit() { } /// #3749: a plane the system cannot give is not an aborted process: `craft-exr` asks for the -/// planes' memory first and reports what it can't get, a read that failed just now (asked again, -/// not remembered); a plane over the read's limit (the decode limit handed to it) is a refusal -/// for size with `craft-exr`'s reason. +/// planes' memory first and reports what it can't get, memory refused just now (not remembered, +/// not read again at once); a plane over the read's limit (the decode limit handed to it) is a +/// refusal for size with `craft-exr`'s reason. #[test] fn a_plane_the_system_cannot_give_is_refused_not_allocated() { use crate::exr_read::{ReadError, read_error}; use craft_exr::seek::Error; let gone = read_error(Error::OutOfMemory("4096 bytes of planes".into())); - assert!(matches!(&gone, ReadError::Io(why) if why.contains("4096 bytes of planes")), "{gone:?}"); + assert!(matches!(&gone, ReadError::OutOfMemory(why) if why.contains("4096 bytes of planes")), "{gone:?}"); let over = read_error(Error::LimitExceeded("the requested rows need 4096 bytes".into())); assert!(matches!(&over, ReadError::TooLarge(why) if why.contains("4096 bytes")), "{over:?}"); } +/// Reads of `path` fail for lack of memory when `fails` says so for the channels read; the reads +/// asked for are counted. +fn no_memory_when(path: &str, fails: impl Fn(&[usize]) -> bool + Send + Sync + 'static) -> Arc { + let asked = Arc::new(AtomicU64::new(0)); + let counted = asked.clone(); + set_read_error( + path, + Some(Arc::new(move |ids: &[usize]| { + counted.fetch_add(1, Ordering::SeqCst); + fails(ids).then(|| crate::exr_read::ReadError::OutOfMemory("no memory just now".into())) + })), + ); + asked +} + +/// #3749 review: memory the system refuses during a read is neither read again at once (the +/// store's retries, a copy) nor remembered: the request is refused with the reason, and the next +/// request reads again. +#[test] +fn memory_the_system_cannot_give_is_neither_retried_nor_remembered() { + let path = "/3749-no-memory.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let want = Want { all: true, ids: (0..5).collect() }; + let asked = no_memory_when(path, |_| true); + let refused = store.get(path, &source, &index, &want, Use::Other).err(); + assert!(matches!(&refused, Some(Refused::NoMemory(why)) if why.contains("no memory just now")), "{refused:?}"); + assert_eq!(asked.load(Ordering::SeqCst), 1, "read once, not again at once"); + let asked = no_memory_when(path, |_| false); + assert!(store.get(path, &source, &index, &want, Use::Other).is_ok(), "not remembered: the memory is there now"); + assert_eq!(asked.load(Ordering::SeqCst), 1); + set_read_error(path, None); +} + +/// #3749 review: a picture whose channels the system has no memory for just now is read alone +/// without the effects' channels, and refused with the reason when even that doesn't fit; never +/// handed to the whole file's decode (which would ask for more memory, infallibly). +#[test] +fn a_picture_without_memory_is_read_alone_or_refused_never_decoded_whole() { + let path = "/3749-no-memory-picture.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); + // With the depth plane it is five planes, more than the system gives: the picture alone. + no_memory_when(path, |ids| ids.len() > 4); + let Picture::Done(Ok(img)) = picture(path, &source, op, Some(&AuxNeed::All)) else { panic!("the picture alone") }; + assert_eq!((img.width, img.height), (8, 8)); + // Not even the picture: refused with the reason, also for some of its rows. + no_memory_when(path, |_| true); + match picture(path, &source, op, None) { + Picture::Done(Err(why)) => assert!(why.contains("no memory just now"), "{why}"), + _ => panic!("refused with the reason"), + } + match picture_rows(path, &source, op, (0, 4)) { + Picture::Done(Err(why)) => assert!(why.contains("no memory just now"), "{why}"), + _ => panic!("rows refused with the reason"), + } + set_read_error(path, None); +} + +/// #3749 review: only a refusal for size is decided anew when the decode limit changes; an +/// unreadable request stays refused, also when another request fails under the new limit. +#[test] +fn an_unreadable_request_stays_refused_when_the_decode_limit_changes() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let path = "/3749-unreadable-generation.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let asked = Arc::new(AtomicU64::new(0)); + { + let counted = asked.clone(); + set_read_error( + path, + Some(Arc::new(move |_: &[usize]| { + counted.fetch_add(1, Ordering::SeqCst); + Some(crate::exr_read::ReadError::Unreadable("damaged".into())) + })), + ); + } + let red = Want { all: false, ids: [0].into_iter().collect() }; + let unreadable = |want: &Want| matches!(store.get(path, &source, &index, want, Use::Other), Err(Refused::Unreadable)); + assert!(unreadable(&red)); + // (figures under the fixed floor: only the change counts, no other test's limit moves) + effectcraft_render::memory::set_decode_limit(Some(1000)); + effectcraft_render::memory::set_decode_limit(Some(2000)); + assert!(unreadable(&red)); + assert_eq!(asked.load(Ordering::SeqCst), 1, "remembered across the change"); + // Another request fails under the new limit: the first refusal is still remembered. + assert!(unreadable(&Want { all: false, ids: [4].into_iter().collect() })); + assert!(unreadable(&red)); + assert_eq!(asked.load(Ordering::SeqCst), 2, "only the other request was read"); + effectcraft_render::memory::set_decode_limit(None); + set_read_error(path, None); +} + /// A two-rank Cryptomatte file of `size` with a picture: "cube" and "sphere" meet along a /// diagonal whose pixels hold both IDs (rank 00 the nearer, 55-75 %, rank 01 the other one with /// the rest), IDs and coverage stored as 32-bit floats. diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index 5624fc2d0..9a11dea3e 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -213,6 +213,9 @@ pub(crate) enum ReadError { Io(String), /// The planes need more memory than one read may allocate (the reason, to show). TooLarge(String), + /// The system refused the memory the planes need just now (the reason, to show): not a file + /// too large, but not to be asked again at once either (#3749). + OutOfMemory(String), /// The request was called off. Cancelled, } @@ -226,13 +229,15 @@ pub(crate) const MAX_DECODE_BYTES: usize = 8 << 30; #[cfg(not(target_pointer_width = "64"))] pub(crate) const MAX_DECODE_BYTES: usize = 512 << 20; -/// What a failed `craft-exr` read means here. Memory the system refused just now is a read that -/// failed ([`ReadError::Io`]: the plane store doesn't remember it, another read may succeed), -/// not a file too large (remembered until the file changes). +/// What a failed `craft-exr` read means here. Memory the system refused just now is +/// [`ReadError::OutOfMemory`]: the plane store doesn't remember it (another request may +/// succeed), but doesn't read it again at once nor fall back to decoding the whole file +/// either; a file too large is remembered until the file or the limit changes. pub(crate) fn read_error(e: seek::Error) -> ReadError { match e { seek::Error::Cancelled => ReadError::Cancelled, - seek::Error::Io(why) | seek::Error::OutOfMemory(why) => ReadError::Io(why), + seek::Error::Io(why) => ReadError::Io(why), + seek::Error::OutOfMemory(why) => ReadError::OutOfMemory(format!("its OpenEXR channels need more memory than the system can give just now ({why})")), seek::Error::LimitExceeded(why) => ReadError::TooLarge(format!("its OpenEXR channels need more memory than one file may use ({why})")), seek::Error::Malformed(why) | seek::Error::Unsupported(why) | seek::Error::UnsupportedCompression(why) => ReadError::Unreadable(why), other => ReadError::Unreadable(other.to_string()), From ba2cb5f7592c3e56e481b137a86033d3e902d5ab Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 23:38:19 +0100 Subject: [PATCH 219/324] OpenEXR limit: one decompressed block stays at 8 GiB whatever memory a read may use (#3749 review) The read's limit (the floor or the memory budget) bounds the planes it allocates; one block the decompressor allocates whole is capped apart, at the fixed floor (8 GiB, 512 MiB in the browser), with craft-exr's max_block_bytes. A larger block is a damaged or hostile header, refused for its size before anything is read. That refusal doesn't depend on the limit, so remembering it for requests asking at least as much stays right; after a limit change it is only decided once more. --- crates/media/src/exr_planes/tests.rs | 44 ++++++++++++++++++++++++++++ crates/media/src/exr_read.rs | 11 ++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs index a08dc87fc..c3a831250 100644 --- a/crates/media/src/exr_planes/tests.rs +++ b/crates/media/src/exr_planes/tests.rs @@ -1724,6 +1724,50 @@ fn a_plane_the_system_cannot_give_is_refused_not_allocated() { assert!(matches!(&over, ReadError::TooLarge(why) if why.contains("4096 bytes")), "{over:?}"); } +/// A source that counts the bytes read from it. +struct Counted { + inner: R, + read: usize, +} + +impl std::io::Read for Counted { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read += n; + Ok(n) + } +} + +impl std::io::Seek for Counted { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(to) + } +} + +/// #3749 review: one decompressed block may take 8 GiB at most, whatever memory the read may +/// use: a file whose block is larger (a data window a billion pixels wide over one large chunk, +/// so that the chunk could hold it) is refused for its size before anything is read, also with a +/// decode limit far above the block. +#[test] +fn a_block_over_the_fixed_limit_is_refused_whatever_the_decode_limit() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let f32s = [("R", false), ("G", false), ("B", false), ("A", false)]; + let small = write(vec![part(None, &f32s, (1, 1), Compression::ZIP1)], (1, 1)); + // One line of 2^30 - 2 pixels of four f32 channels: a block of 16 GiB... + let mut bytes = with_data_window_x_max(small, (1 << 30) - 3); + // ...over a chunk long enough to hold it at craft-exr's ratio (2^16 bytes a byte). + bytes.extend(std::iter::repeat_n(0u8, 300 << 10)); + let index = crate::exr_index::build(&mut std::io::Cursor::new(bytes.as_slice()), FileStamp::Virtual).expect("indexed: the chunk can hold the block"); + // The read may use 64 GiB (the floor is tiny, the system's figure high). + effectcraft_render::memory::set_decode_limit(Some(64 << 30)); + let request = ReadRequest { floor: 8, ..ReadRequest::full(vec![0, 1, 2, 3]) }; + let mut src = Counted { inner: std::io::Cursor::new(bytes.as_slice()), read: 0 }; + let (read, _) = crate::exr_read::read_planes(&mut src, &index, &request); + effectcraft_render::memory::set_decode_limit(None); + assert!(matches!(&read, Err(crate::exr_read::ReadError::TooLarge(why)) if why.contains("one block of this read may use")), "{read:?}"); + assert_eq!(src.read, 0, "refused before anything was read"); +} + /// Reads of `path` fail for lack of memory when `fails` says so for the channels read; the reads /// asked for are counted. fn no_memory_when(path: &str, fails: impl Fn(&[usize]) -> bool + Send + Sync + 'static) -> Arc { diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs index 9a11dea3e..60175806e 100644 --- a/crates/media/src/exr_read.rs +++ b/crates/media/src/exr_read.rs @@ -244,6 +244,13 @@ pub(crate) fn read_error(e: seek::Error) -> ReadError { } } +/// The most bytes one decompressed block of a read may take, whatever the read's limit +/// ([`MAX_DECODE_BYTES`]: 8 GiB, 512 MiB in the browser): the decompressor allocates a block +/// whole before it looks at the data, and a block is one strip of the file, so a larger one is a +/// damaged or hostile header, not a file with more channels (#3749). A refusal for it doesn't +/// depend on the limit: a request asking at least as much, refused for it before, would be again. +pub(crate) const MAX_BLOCK_BYTES: usize = MAX_DECODE_BYTES; + /// The most threads one read decompresses on (beside the caller's), and the size of a file /// whose chunks are decompressed on the calling thread alone. const READ_WORKERS: usize = 4; @@ -293,7 +300,8 @@ fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<( let n = ow.checked_mul(oh).ok_or_else(|| ReadError::Unreadable("display window".into()))?; let need = n.saturating_mul(req.channels.len()).saturating_mul(std::mem::size_of::()); // (the limit is decided here and handed to `craft-exr` as the read's `max_bytes`: the planes - // it reserves, fallibly, and the largest block it decompresses follow it) + // it reserves, fallibly, follow it; one decompressed block stays at the fixed floor however + // much memory the machine has, see `MAX_BLOCK_BYTES`) let most = req.max_bytes.min(effectcraft_render::memory::decode_limit(req.floor, need)); if need > most { return Err(too_large(w, h, need, most)); @@ -309,6 +317,7 @@ fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<( request.fill = &fill; request.rows = req.rows.clone(); request.level = req.level; + request.max_block_bytes = Some(MAX_BLOCK_BYTES); // craft-exr decompresses on threads of its own, started for this read, beside the decode // pool the caller runs on: a few at most, and none for a small file (its chunks are // decompressed on the calling thread). From 3972e5181b1a6cad3a47a09524a9760f9a37f109 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:38:19 -0500 Subject: [PATCH 220/324] svg: delegate stylesheet parsing and matching to craft-svg --- Cargo.lock | 138 +++--------------------- Cargo.toml | 2 +- crates/svg/src/lib.rs | 231 ++-------------------------------------- crates/svg/src/tests.rs | 33 ------ 4 files changed, 24 insertions(+), 380 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 73d74ecb5..a11599fd7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -147,21 +147,6 @@ dependencies = [ "equator", ] -[[package]] -name = "alloc-no-stdlib" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" - -[[package]] -name = "alloc-stdlib" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" -dependencies = [ - "alloc-no-stdlib", -] - [[package]] name = "allocator-api2" version = "0.2.21" @@ -796,16 +781,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "brotli-decompressor" -version = "6.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", -] - [[package]] name = "built" version = "0.8.1" @@ -1376,39 +1351,6 @@ dependencies = [ "writeable", ] -[[package]] -name = "craft-image-codecs" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" -dependencies = [ - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", - "craft-metadata", - "crc32fast", - "exr", - "flate2", - "half", - "hayro-jpeg2000", - "image", - "image-webp", - "jpeg-encoder", - "png", - "rayon", - "serde_json", - "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", - "zune-jpegxl", -] - -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "craft-jpeg" version = "0.1.0" @@ -1461,18 +1403,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "craft-metadata" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" -dependencies = [ - "brotli-decompressor", - "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", - "quick-xml 0.41.0", - "serde", -] - [[package]] name = "craft-mime" version = "0.1.0" @@ -1543,7 +1473,7 @@ name = "craft-raw" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" dependencies = [ - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)", + "craft-tiff", "miniz_oxide 0.9.1", "rayon", "serde", @@ -1555,10 +1485,9 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=c3d9015ec985450386a86b04713d6f1cee597951#c3d9015ec985450386a86b04713d6f1cee597951" dependencies = [ - "craft-image-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c3d9015ec985450386a86b04713d6f1cee597951)", "flate2", "kurbo", "quick-xml 0.41.0", @@ -1576,15 +1505,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-tiff" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - [[package]] name = "craft-tiff" version = "0.1.0" @@ -1747,16 +1667,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "craft-xml" version = "0.1.0" @@ -1777,6 +1687,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c3d9015ec985450386a86b04713d6f1cee597951#c3d9015ec985450386a86b04713d6f1cee597951" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-y4m" version = "0.1.0" @@ -3039,7 +2959,7 @@ version = "0.20.1" source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9)", + "craft-jpeg", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", "craft-y4m", @@ -3071,7 +2991,7 @@ version = "0.20.1" source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "craft-raw", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac)", + "craft-tiff", "image", "rayon", "thiserror 2.0.21", @@ -3760,9 +3680,6 @@ name = "hayro-jpeg2000" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" -dependencies = [ - "fearless_simd", -] [[package]] name = "hayro-syntax" @@ -4024,7 +3941,6 @@ dependencies = [ "moxcms", "num-traits", "png", - "qoi", "tiff", "zune-core", "zune-jpeg", @@ -4175,12 +4091,6 @@ dependencies = [ "libc", ] -[[package]] -name = "jpeg-encoder" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" - [[package]] name = "js-sys" version = "0.3.106" @@ -5573,15 +5483,6 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" -[[package]] -name = "qoi" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" -dependencies = [ - "bytemuck", -] - [[package]] name = "quick-error" version = "1.2.3" @@ -9001,15 +8902,6 @@ dependencies = [ "zune-core", ] -[[package]] -name = "zune-jpegxl" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4" -dependencies = [ - "zune-core", -] - [[package]] name = "zvariant" version = "5.15.0" diff --git a/Cargo.toml b/Cargo.toml index 2889bdc34..bf9f999be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,7 @@ craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" } -craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c3d9015ec985450386a86b04713d6f1cee597951" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index fd4baa543..94977d153 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -425,186 +425,12 @@ enum PaintRef { Current, } -/// The most selectors (each entry of a comma list counts) the ` + + + + + + + + + + + + + "##; + let doc = effectcraft_svg::parse(svg).unwrap(); + let mut next_id = 1u64; + let mut ids = Ids(&mut next_id); + let items = svg_contents(&mut ids, &doc); + assert_eq!(items.len(), 1); + let layer = &items[0]; + assert_eq!(layer.name, "layer"); + assert!((layer.prop("transform/opacity").unwrap().value.as_f64() - 50.0).abs() < 1e-9); + + // Paint order is reversed (top of paint order first). + let children: Vec<_> = layer.sub("contents").unwrap().groups().collect(); + let names: Vec<_> = children.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, vec!["fallback", "grad", "hole", "rect-a"]); + + // rect-a: viewBox (10, 10, 40, 20) -> (80, 40) scales by 2x; translate(10, 10) lands at (0, 0) in comp space, + // and 1em = 10 -> 20x20 rect centered at (10, 10). + let rect_a: Vec<_> = children[3].sub("contents").unwrap().groups().collect(); + assert_eq!(rect_a[0].get("size").unwrap().value.as_vec2(), [20.0, 20.0]); + assert_eq!(rect_a[0].get("position").unwrap().value.as_vec2(), [10.0, 10.0]); + assert_eq!(rect_a[1].get("color").unwrap().value, Value::Color([1.0, 0.0, 0.0, 1.0])); + + // hole: EvenOdd fill rule preserved. + let hole: Vec<_> = children[2].sub("contents").unwrap().groups().collect(); + let hole_fill = hole.iter().find(|g| g.match_id == "fill").unwrap(); + assert_eq!(hole_fill.get("rule").unwrap().value, Value::Enum(1)); + + // grad: gradient fill mapped with both stops. + let grad: Vec<_> = children[1].sub("contents").unwrap().groups().collect(); + assert!(grad.iter().any(|g| g.match_id == "gfill")); + + // fallback: missing paint server keeps fallback solid color. + let fb: Vec<_> = children[0].sub("contents").unwrap().groups().collect(); + let fb_fill = fb.iter().find(|g| g.match_id == "fill").unwrap(); + assert_eq!(fb_fill.get("color").unwrap().value, Value::Color([0.0, 0.0, 1.0, 1.0])); + } } diff --git a/crates/host/tests/it/vector_import.rs b/crates/host/tests/it/vector_import.rs index 81b0d8e59..451a30db8 100644 --- a/crates/host/tests/it/vector_import.rs +++ b/crates/host/tests/it/vector_import.rs @@ -1097,3 +1097,67 @@ fn a_vectorcraft_document_without_a_pdf_reports_the_option_to_turn_on() { assert_eq!(r["items"], json!([]), "{import_as}: {r}"); } } + +#[test] +fn svg_scene_mapping_render_parity() { + let svg = br##" + + + + + + + + + + + + + + + + + + + + + + + "##; + let path = tmp("scene-parity.svg"); + std::fs::write(&path, svg).unwrap(); + let doc = effectcraft_svg::parse(svg).unwrap(); + let (w, h) = doc.pixel_size(); + assert_eq!((w, h), (120, 80)); + + let mut s = effectcraft_host::session(); + let r = s.execute_checked("file.import", json!({"paths": [path]})).unwrap(); + assert_eq!(r["errors"], json!([]), "{r}"); + let item = r["items"][0].as_u64().unwrap(); + s.execute("comp.new", json!({"name": "Parity", "width": w, "height": h, "frameRate": 30, "duration": 1})).unwrap(); + let lid = s.execute_checked("layer.addItem", json!({"item": item})).unwrap()["layer"].as_u64().unwrap(); + let cid = s.active_comp_id().unwrap(); + let t = effectcraft_time::Tick::ZERO; + + let footage = s.render(cid, t, RenderOpts::default()); + let direct = effectcraft_svg::rasterize(&doc, w, h, 1.0); + assert!(mean_diff(&footage, &direct) < 1.0 / 255.0, "footage = rasterised SVG"); + + s.execute("layer.select", json!({"layers": [lid]})).unwrap(); + let r = s.execute_checked("layer.create", json!({"op": "shapesFromVector"})).unwrap(); + let sid = r["layers"][0].as_u64().unwrap(); + let shapes = s.render(cid, t, RenderOpts::default()); + let d1 = mean_diff(&shapes, &direct); + assert!(d1 < 0.02, "shapes vs SVG mean diff {d1}"); + + s.execute("prop.set", json!({"layer": sid, "path": "transform/scale", "value": [300, 300]})).unwrap(); + s.execute("prop.set", json!({"layer": sid, "path": "transform/position", "value": [0, 0]})).unwrap(); + s.execute("prop.set", json!({"layer": sid, "path": "transform/anchor", "value": [0, 0]})).unwrap(); + let big = s.render(cid, t, RenderOpts::default()); + let direct3 = effectcraft_svg::rasterize(&doc, w, h, 3.0); + let d3 = mean_diff(&big, &direct3); + assert!(d3 < 0.03, "shapes x3 vs SVG x3 mean diff {d3}"); +} diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 672ef5910..ccbf58dea 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -1343,3 +1343,247 @@ fn axis_rect_recognises_only_axis_aligned_rectangles() { folded.close_path(); assert_eq!(axis_rect(&folded, Affine::IDENTITY), None); } + +#[test] +fn css_cascade_specificity_display_visibility_and_group_opacity_parity() { + let svg = br##" + + + + + + + + + + + + + + + + "##; + let doc = parse(svg).unwrap(); + let shapes = doc.flatten(); + // 5 top-row rects + 1 visible child in hidden group + 2 rects in opacity group = 8. + assert_eq!(shapes.len(), 8); + assert_eq!(shapes[0].2.fill, Some(Paint::Color([1.0, 0.0, 0.0]))); + assert_eq!(shapes[1].2.fill, Some(Paint::Color([0.0, 1.0, 0.0]))); + assert_eq!(shapes[2].2.fill, Some(Paint::Color([0.0, 1.0, 1.0]))); + assert_eq!(shapes[3].2.fill, Some(Paint::Color([0.0, 0.0, 1.0]))); + assert_eq!(shapes[4].2.fill, Some(Paint::Color([1.0, 1.0, 0.0]))); + // Group opacity multiplies in flatten() rather than mutating child fill_opacity. + assert!((shapes[6].1 - 0.5).abs() < 1e-12); + assert!((shapes[6].2.fill_opacity - 1.0).abs() < 1e-12); + + let img = rasterize(&doc, 60, 20, 1.0); + assert!(near(px(&img, 5, 5), [1.0, 0.0, 0.0, 1.0], 1e-3)); + assert!(near(px(&img, 15, 5), [0.0, 1.0, 0.0, 1.0], 1e-3)); + assert!(near(px(&img, 25, 5), [0.0, 1.0, 1.0, 1.0], 1e-3)); + assert!(near(px(&img, 35, 5), [0.0, 0.0, 1.0, 1.0], 1e-3)); + assert!(near(px(&img, 45, 5), [1.0, 1.0, 0.0, 1.0], 1e-3)); + // display:none suppresses the entire subtree. + assert_eq!(px(&img, 55, 5)[3], 0.0); + // visibility:hidden suppresses the first child, visibility:visible restores the second. + assert_eq!(px(&img, 5, 15)[3], 0.0); + assert!(near(px(&img, 15, 15), [0.0, 1.0, 0.0, 1.0], 1e-3)); + // Isolated group opacity: blue over red inside opacity=0.5 yields premultiplied [0, 0, 0.5, 0.5], + // without red bleeding through the opaque blue rect. + assert!(near(px(&img, 25, 15), [0.0, 0.0, 0.5, 0.5], 2e-3)); +} + +#[test] +fn inherited_attributes_current_color_and_use_inheritance_parity() { + let svg = br##" + + + + + + + + + + + "##; + let doc = parse(svg).unwrap(); + let shapes = doc.flatten(); + assert_eq!(shapes.len(), 4); + + let inh = shapes[0].2; + assert_eq!(inh.fill, Some(Paint::Color([1.0, 0.0, 0.0]))); + assert!((inh.fill_opacity - 0.5).abs() < 1e-12); + assert_eq!(inh.fill_rule, FillRule::EvenOdd); + let st = inh.stroke.as_ref().expect("inherited stroke"); + assert_eq!(st.paint, Paint::Color([0.0, 0.0, 1.0])); + assert_eq!(st.width, 2.0); + assert_eq!(st.cap, Cap::Round); + assert_eq!(st.join, Join::Bevel); + assert_eq!(st.miter, 6.0); + assert_eq!(st.dash, Some((vec![4.0, 2.0], 1.0))); + + let ovr = shapes[1].2; + assert_eq!(ovr.fill, Some(Paint::Color([0.0, 1.0, 0.0]))); + assert!((ovr.fill_opacity - 1.0).abs() < 1e-12); + assert!(ovr.stroke.is_none()); + + // passes its inherited fill to #tpl (which has no fill), while #own keeps its own fill. + assert_eq!(shapes[2].2.fill, Some(Paint::Color([1.0, 1.0, 0.0]))); + assert_eq!(shapes[3].2.fill, Some(Paint::Color([0.0, 1.0, 0.0]))); + + let img = rasterize(&doc, 50, 20, 1.0); + assert!(near(px(&img, 15, 5), [0.0, 1.0, 0.0, 1.0], 1e-3)); + // Both elements inherit fill-opacity="0.5" from the enclosing . + assert!(near(px(&img, 25, 5), [0.5, 0.5, 0.0, 0.5], 1e-3)); + assert!(near(px(&img, 35, 5), [0.0, 0.5, 0.0, 0.5], 1e-3)); +} + +#[test] +fn length_units_and_font_size_inheritance_parity() { + let svg = br#" + + + + + + "#; + let doc = parse(svg).unwrap(); + let shapes = doc.flatten(); + assert_eq!(shapes.len(), 3); + + let (em, abs, mm) = (shapes[0].2, shapes[1].2, shapes[2].2); + assert!(matches!(em.geom, Geom::Rect { x, y, w, h, .. } + if (x - 20.0).abs() < 1e-9 && (y - 20.0).abs() < 1e-9 && (w - 40.0).abs() < 1e-9 && (h - 20.0).abs() < 1e-9)); + assert!((em.stroke.as_ref().unwrap().width - 5.0).abs() < 1e-9); + assert!(matches!(abs.geom, Geom::Rect { x, y, w, h, .. } + if (x - 96.0).abs() < 1e-9 && (y - 16.0).abs() < 1e-9 && (w - 96.0).abs() < 1e-9 && (h - 96.0).abs() < 1e-9)); + assert!(matches!(mm.geom, Geom::Rect { x, w, h, .. } + if (x - 96.0).abs() < 1e-9 && (w - 20.0).abs() < 1e-9 && (h - 20.0).abs() < 1e-9)); +} + +#[test] +fn viewbox_preserve_aspect_ratio_and_implicit_dimensions_parity() { + // Non-zero min-x/min-y and preserveAspectRatio modes into an 80x40 viewport. + for (par, pt_expect) in [ + ("none", (40.0, 20.0)), + ("xMidYMid meet", (40.0, 20.0)), + ("xMinYMin meet", (20.0, 20.0)), + ("xMaxYMax meet", (60.0, 20.0)), + ("xMidYMid slice", (40.0, 20.0)), + ("xMinYMin slice", (40.0, 40.0)), + ] { + let svg = format!( + r#" + + "# + ); + let doc = parse(svg.as_bytes()).unwrap(); + let shapes = doc.flatten(); + assert_eq!(shapes.len(), 1); + // Center of viewBox (20, 30) in root pixel space. + let center = shapes[0].0 * kurbo::Point::new(20.0, 30.0); + assert!((center.x - pt_expect.0).abs() < 1e-9 && (center.y - pt_expect.1).abs() < 1e-9, "{par}: {center:?}"); + } + + // Pixel check for xMinYMin meet vs xMaxYMax meet: 20x20 viewBox in 80x40 -> 40x40 square. + let min_doc = parse(br#""#).unwrap(); + let min_img = rasterize(&min_doc, 80, 40, 1.0); + assert!(near(px(&min_img, 10, 20), [1.0, 0.0, 0.0, 1.0], 1e-3)); + assert_eq!(px(&min_img, 60, 20)[3], 0.0); + + let max_doc = parse(br#""#).unwrap(); + let max_img = rasterize(&max_doc, 80, 40, 1.0); + assert_eq!(px(&max_img, 10, 20)[3], 0.0); + assert!(near(px(&max_img, 60, 20), [1.0, 0.0, 0.0, 1.0], 1e-3)); + + // Omitted width/height derive from viewBox aspect ratio. + let implicit = parse(br#""#).unwrap(); + assert_eq!((implicit.width, implicit.height), (100.0, 50.0)); + let only_w = parse(br#""#).unwrap(); + assert_eq!((only_w.width, only_w.height), (200.0, 100.0)); + let only_h = parse(br#""#).unwrap(); + assert_eq!((only_h.width, only_h.height), (50.0, 25.0)); +} + +#[test] +fn transform_functions_chaining_and_raster_parity() { + let svg = br#" + + + + + + + "#; + let doc = parse(svg).unwrap(); + let shapes = doc.flatten(); + assert_eq!(shapes.len(), 4); + + // rotate(180 5 5) maps (0, 0) -> (10, 10) and keeps the [0,10]^2 square covered. + let p = shapes[1].0 * kurbo::Point::new(0.0, 0.0); + assert!((p.x - 10.0).abs() < 1e-9 && (p.y - 10.0).abs() < 1e-9); + // skewX(45) at y=2 shifts x by +2 -> (0, 2) lands at (2+2, 26) = (4, 26). + let s = shapes[2].0 * kurbo::Point::new(0.0, 2.0); + assert!((s.x - 4.0).abs() < 1e-9 && (s.y - 26.0).abs() < 1e-9); + + let img = rasterize(&doc, 40, 40, 1.0); + assert!(near(px(&img, 20, 20), [1.0, 0.0, 0.0, 1.0], 1e-3)); + assert!(near(px(&img, 5, 5), [0.0, 0.0, 1.0, 1.0], 1e-3)); + assert!(near(px(&img, 6, 26), [0.0, 128.0 / 255.0, 0.0, 1.0], 1e-3)); + assert!(near(px(&img, 28, 28), [1.0, 1.0, 0.0, 1.0], 1e-3)); +} + +#[test] +fn paint_references_gradients_fallbacks_and_stroke_styles_parity() { + let svg = br##" + + + + + + + + + + + + + + + + + "##; + let doc = parse(svg).unwrap(); + let shapes = doc.flatten(); + assert_eq!(shapes.len(), 5); + + let Some(Paint::Gradient(lg)) = &shapes[0].2.fill else { panic!("linearGradient expected") }; + assert!(!lg.bbox_units); + assert_eq!(lg.spread, Spread::Reflect); + assert_eq!(lg.stops.len(), 2); + + assert_eq!(shapes[2].2.fill, Some(Paint::Color([1.0, 0.0, 1.0]))); + assert_eq!(shapes[2].2.stroke.as_ref().map(|s| &s.paint), Some(&Paint::Color([0.0, 1.0, 1.0]))); + + let img = rasterize(&doc, 80, 40, 1.0); + // Reflected gradient: red at x=0, blue at x=10, back toward red at x=19. + assert!(px(&img, 0, 5)[0] > 0.8 && px(&img, 10, 5)[2] > 0.8 && px(&img, 19, 5)[0] > 0.8); + // Radial gradient white center at (50, 10). + assert!(near(px(&img, 50, 10), [1.0, 1.0, 1.0, 1.0], 0.05)); + // Fallback solid fill. + assert!(near(px(&img, 5, 25), [1.0, 0.0, 1.0, 1.0], 1e-3)); + // Even-odd hole at (28, 28) is transparent, outer ring at (22, 28) is green. + assert_eq!(px(&img, 28, 28)[3], 0.0); + assert!(near(px(&img, 22, 28), [0.0, 1.0, 0.0, 1.0], 1e-3)); + // Dashed stroke (6 on, 8 off, square cap extends each end by 2): on at x=43, gap at x=50. + assert!(near(px(&img, 43, 30), [1.0, 1.0, 1.0, 1.0], 1e-3)); + assert_eq!(px(&img, 50, 30)[3], 0.0); +} From c561e7352f6047d335db75a32cda45553ed34cf0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 11:54:22 -0500 Subject: [PATCH 320/324] mcp: add protocol transcript tests for initialize, cancel, and batch (#3990) --- crates/automation/src/tests.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index a97a5f91e..afee15936 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -2112,3 +2112,28 @@ fn bridged_contact_sheet_keeps_the_times_asked_for() { let info = call_json(&mut s, "render_frame", json!({"times": [1.5, 0.25, 3], "inline": false})); assert_eq!(info["times"], json!([1.5, 0.25, 3.0])); } + +#[test] +fn stdio_batch_transcript() { + let input = concat!( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\"}}\n", + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n", + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":1,\"reason\":\"client\"}}\n", + "[]\n", + "[{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":9}}]\n", + "[{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"},{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}]\n", + "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\",\"params\":{}}\n" + ); + let mut s = server(); + let mut out = Vec::new(); + s.serve(std::io::Cursor::new(input), &mut out).unwrap(); + + let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 4, "{replies:?}"); + assert_eq!(replies[0]["id"], 1); + assert_eq!(replies[0]["result"]["serverInfo"]["name"], "effectcraft"); + assert_eq!(replies[1]["id"], Value::Null); + assert_eq!(replies[1]["error"]["code"], -32600); + assert_eq!(replies[2], json!([{"jsonrpc": "2.0", "id": 2, "result": {}}])); + assert_eq!(replies[3], json!({"jsonrpc": "2.0", "id": 3, "result": {}})); +} From 3376eaa06a0b0eb28bff571ccbd94c060dc2c6dd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 14:33:25 -0500 Subject: [PATCH 321/324] media: route ISO-BMFF and Matroska/WebM codecs through craft-video (#3989) * media: route ISO-BMFF and Matroska/WebM codecs through craft-video * media: fix rotation, WebM alpha fallback, draft cache separation, and Matroska audio timing * media: remove nonexistent discard_padding_ns field on matroska::Sample * test: use MediaPool::audio_samples in matroska_opus_audio_timing_and_seek * media: support 8-bit planes stored in Samples::U16 (AV1) * media: fix clippy lints, wasm cfg, and expand unit test coverage * test: include kind field in isobmff::ColorInfo::Icc test literal * test: avoid clippy::assertions_on_constants in craft_source unit tests * media: avoid double-inverting container PAR fallback on rotated frames --- crates/media/Cargo.toml | 2 +- crates/media/src/craft_source.rs | 1109 ++++++++++++++++++++++++++++++ crates/media/src/lib.rs | 2 +- crates/media/src/mp4_h264.rs | 597 ---------------- crates/media/src/stream.rs | 8 +- crates/media/tests/it/footage.rs | 179 +++++ 6 files changed, 1294 insertions(+), 603 deletions(-) create mode 100644 crates/media/src/craft_source.rs delete mode 100644 crates/media/src/mp4_h264.rs diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 39ad32f14..668828fca 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -33,7 +33,7 @@ craft-frame = { workspace = true } craft-media = { workspace = true, features = ["mpegts"] } craft-media-source = { workspace = true } craft-time = { workspace = true } -craft-video = { workspace = true, features = ["h264-decode", "threads"] } +craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "threads"] } filmcraft-frame = { workspace = true } filmcraft-color = { workspace = true } filmcraft-time = { workspace = true } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs new file mode 100644 index 000000000..24e88cc30 --- /dev/null +++ b/crates/media/src/craft_source.rs @@ -0,0 +1,1109 @@ +//! ISO-BMFF (MP4/MOV) and Matroska/WebM media-reader routes backed by `craft-media`, +//! `craft-video`, `craft-audio`, and `craft-media-source`. +//! +//! Preserves sync-sample backward seek, B-frame reordering, cooperative cancellation, VUI + +//! container colour resolution, draft mode for reduced-resolution playback, and bounded worker +//! threads, while falling back to `filmcraft-codecs` for unsupported codecs or audio streams. + +use std::sync::{Arc, Mutex}; + +use craft_audio::{AudioBuffer, TrackDecoder as AudioTrackDecoder}; +use craft_color::{ColorInfo, Matrix, Primaries, Range, Transfer}; +use craft_frame::{Chroma, PixelData, VideoFrame}; +use craft_media::isobmff::{self, Mp4File}; +use craft_media::matroska::{self, MkvFile}; +use craft_media::{ByteSource, CodecId, CodecParams}; +use craft_media_source::{ + AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo, +}; +use craft_time::{FrameRate, Tick}; +use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame}; +use craft_video::{TrackDecoder, TrackDecoderOptions}; + +/// Maximum worker threads per `TrackDecoder` instance. +const MAX_WORKERS: usize = 8; + +/// Maximum decoded frames retained in the per-source GOP window cache. +const MAX_CACHED_FRAMES: usize = 32; + +/// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`. +const AUDIO_LOOKAHEAD: usize = 8; + +fn worker_cap() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) +} + +fn supports_video_codec(codec: CodecId) -> bool { + matches!(codec, CodecId::H264 | CodecId::Hevc | CodecId::Av1 | CodecId::Vp9 | CodecId::Vp8 | CodecId::ProRes | CodecId::Dnxhd | CodecId::Mpeg2Video) +} + +/// True when `head` begins with a plausible ISO-BMFF top-level box. +fn looks_like_isobmff(head: &[u8]) -> bool { + if head.len() < 8 { + return false; + } + matches!(&head[4..8], b"ftyp" | b"moov" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot" | b"uuid") +} + +/// True when `head` begins with an EBML header (Matroska / WebM). +fn looks_like_matroska(head: &[u8]) -> bool { + head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) +} + +/// Open an in-place ISO-BMFF or Matroska/WebM source via `craft-media` / `craft-video`. +/// Returns `None` when the container/codec/audio combination should fall back to `filmcraft-codecs`. +#[cfg(any(unix, windows))] +pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Option> { + if looks_like_isobmff(head) { + return open_isobmff(name, reader.clone()); + } + if looks_like_matroska(head) { + return open_matroska(name, reader.clone()); + } + None +} + +/// Open an in-memory ISO-BMFF or Matroska/WebM source via `craft-media` / `craft-video`. +pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { + if looks_like_isobmff(&bytes) { + return open_isobmff(name, Arc::new(bytes)); + } + if looks_like_matroska(&bytes) { + return open_matroska(name, Arc::new(bytes)); + } + None +} + +enum ContainerFile { + Isobmff(Mp4File), + Matroska(Box), +} + +impl ContainerFile { + fn sample_count(&self, track_idx: usize) -> usize { + match self { + ContainerFile::Isobmff(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), + ContainerFile::Matroska(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), + } + } + + fn read_sample(&self, src: &dyn ByteSource, track_idx: usize, sample_idx: usize) -> Result> { + match self { + ContainerFile::Isobmff(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + ContainerFile::Matroska(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + } + } + + fn target_sample(&self, track_idx: usize, time: Tick) -> Option<(usize, i64)> { + match self { + ContainerFile::Isobmff(f) => { + let track = f.tracks.get(track_idx)?; + let t_track = tick_to_units(time, track.timescale); + let idx = track.sample_at_presentation_time(t_track)?; + Some((idx, track.samples[idx].pts)) + } + ContainerFile::Matroska(f) => { + let track = f.tracks.get(track_idx)?; + let t_track = tick_to_matroska_units(time, track.timebase); + let idx = track.sample_at_pts(t_track)?; + Some((idx, track.samples[idx].pts)) + } + } + } + + fn sync_sample_before(&self, track_idx: usize, target_idx: usize) -> usize { + match self { + ContainerFile::Isobmff(f) => f.tracks[track_idx].sync_sample_before(target_idx), + ContainerFile::Matroska(f) => f.tracks[track_idx].sync_sample_before(target_idx), + } + } + + fn sample_pts(&self, track_idx: usize, sample_idx: usize) -> i64 { + match self { + ContainerFile::Isobmff(f) => f.tracks[track_idx].samples[sample_idx].pts, + ContainerFile::Matroska(f) => f.tracks[track_idx].samples[sample_idx].pts, + } + } + + fn pts_to_tick(&self, track_idx: usize, raw_pts: i64) -> Tick { + match self { + ContainerFile::Isobmff(f) => { + let track = &f.tracks[track_idx]; + let pts_units = raw_pts.saturating_add(track.edit_offset); + Tick::from_units(pts_units, i64::from(track.timescale.max(1))) + } + ContainerFile::Matroska(f) => { + let track = &f.tracks[track_idx]; + let ns = track.ticks_to_ns(raw_pts); + Tick::from_units(ns, 1_000_000_000) + } + } + } + + fn audio_seek_info(&self, track_idx: usize, start: i64, native_rate: u32) -> (usize, i64) { + match self { + ContainerFile::Isobmff(f) => { + let track = &f.tracks[track_idx]; + let t_track = (i128::from(start.max(0)) * i128::from(track.timescale)) / i128::from(native_rate); + let sample_idx = track.sample_at_presentation_time(i64::try_from(t_track).unwrap_or(0)).unwrap_or(0); + // Back up a few packets for AAC/Opus overlap/preroll. + let seek_idx = sample_idx.saturating_sub(2); + let sample_pts = track.presentation_pts(seek_idx).unwrap_or(0); + let decoded_pos = i64::try_from((i128::from(sample_pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1))).unwrap_or(0); + (seek_idx, decoded_pos) + } + ContainerFile::Matroska(f) => { + let track = &f.tracks[track_idx]; + let delay_ns = i128::from(track.codec_delay_ns); + let preroll_ns = i128::from(track.seek_pre_roll_ns.max(80_000_000)); + let target_ns = (i128::from(start.max(0)) * 1_000_000_000) / i128::from(native_rate) + delay_ns; + let seek_ns = (target_ns - preroll_ns).max(0); + let t_track = track.ns_to_ticks(i64::try_from(seek_ns).unwrap_or(0)); + let sample_idx = track.sample_at_pts(t_track).unwrap_or(0); + let seek_idx = sample_idx.saturating_sub(2); + let sample_pts = track.samples.get(seek_idx).map_or(0, |s| s.pts); + let sample_ns = i128::from(track.ticks_to_ns(sample_pts)) - delay_ns; + let decoded_pos = i64::try_from((sample_ns * i128::from(native_rate)) / 1_000_000_000).unwrap_or(0); + (seek_idx, decoded_pos) + } + } + } +} + +fn open_audio_tracks(container: &ContainerFile, source: &dyn ByteSource, candidates: I) -> Option<(Vec, Vec)> +where + I: IntoIterator, +{ + let mut audio_tracks = Vec::new(); + let mut audio_infos = Vec::new(); + for (idx, sample_count, params, codec_delay_ns) in candidates { + if audio_tracks.len() >= MAX_AUDIO_STREAMS { + break; + } + let n = AUDIO_LOOKAHEAD.min(sample_count); + let mut lookahead = Vec::with_capacity(n); + for s_idx in 0..n { + let pkt = container.read_sample(source, idx, s_idx).ok()?; + lookahead.push(pkt); + } + let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect(); + let dec = AudioTrackDecoder::new(¶ms, &refs).ok()?; + let native_rate = dec.sample_rate().max(1); + let channels = u32::from(dec.layout().channels()).max(1); + let delay_samples = i64::try_from((i128::from(codec_delay_ns) * i128::from(native_rate)) / 1_000_000_000).unwrap_or(0); + audio_infos.push(AudioStreamInfo { + sample_rate: native_rate, + channels, + codec: params.codec.name().to_string(), + bits_per_sample: params.pcm.map(|p| u32::from(p.bits)), + }); + audio_tracks.push(AudioTrackEntry { + track_idx: idx, + native_rate, + state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: -delay_samples, buf: Vec::new() }), + }); + } + Some((audio_tracks, audio_infos)) +} + +fn open_isobmff(name: &str, source: SharedBytes) -> Option> { + let file = isobmff::open(source.clone()).ok()?; + let video_idx = + file.tracks.iter().position(|t| t.kind == isobmff::TrackKind::Video && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0)?; + let video_track = &file.tracks[video_idx]; + let video_params = video_track.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + + let container_color = video_track.video().and_then(|v| v.color.as_ref()).map(color_from_isobmff); + let color = container_color.unwrap_or(ColorInfo::REC709); + let (mut width, mut height) = video_track + .video() + .map(|v| (u32::from(v.width), u32::from(v.height))) + .filter(|&(w, h)| w > 0 && h > 0) + .unwrap_or((video_track.width, video_track.height)); + let mut par = video_track.video().and_then(|v| v.pixel_aspect).filter(|&(n, d)| n > 0 && d > 0).unwrap_or((1, 1)); + let rotation = video_track.display_rotation().unwrap_or(0) % 4; + if rotation % 2 == 1 { + std::mem::swap(&mut width, &mut height); + par = (par.1, par.0); + } + let has_alpha = video_track.video().is_some_and(|v| v.depth == 32); + let frame_rate = estimate_isobmff_frame_rate(video_track); + let duration = Tick::from_units(i64::try_from(video_track.duration).unwrap_or(i64::MAX), i64::from(video_track.timescale)); + let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0); + let codec_name = video_params.codec.name().to_string(); + + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .tracks + .iter() + .enumerate() + .filter(|(_, t)| t.kind == isobmff::TrackKind::Audio && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0) + .map(|(idx, t)| (idx, t.samples.len(), t.codec_params(), 0)) + .collect(); + + let container = ContainerFile::Isobmff(file); + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + + let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) { + Ok(d) => d, + Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), + }; + + let info = MediaInfo { + name: name.to_string(), + kind: MediaKind::Movie, + duration, + video: Some(VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format: String::new(), color, has_alpha, bitrate, hdr: None }), + audio_streams: audio_infos, + container: "mp4".to_string(), + start_timecode: None, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx: video_idx, + container_color, + par, + rotation, + video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), + audio_tracks, + }))) +} + +fn open_matroska(name: &str, source: SharedBytes) -> Option> { + let file = matroska::open(source.clone()).ok()?; + let video_idx = file.tracks.iter().position(|t| t.kind == matroska::TrackKind::Video && !t.samples.is_empty() && t.timebase.0 > 0 && t.timebase.1 > 0)?; + let video_track = &file.tracks[video_idx]; + if !video_track.frames_readable() { + return None; + } + let video_params = video_track.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + + let video_info = video_track.video.as_ref(); + // WebM/Matroska alpha_mode == 1 stores alpha in BlockAdditional; fall back to FilmCraft. + if video_info.is_some_and(|v| v.alpha_mode == 1) { + return None; + } + let container_color = video_info.and_then(|v| v.color.as_ref()).map(color_from_matroska); + let color = container_color.unwrap_or(ColorInfo::REC709); + let (mut width, mut height) = video_info.map_or((0, 0), |v| (v.pixel_width, v.pixel_height)); + let mut par = matroska_par(video_info, width, height); + let rotation = video_info.and_then(|v| v.display_rotation()).unwrap_or(0) % 4; + if rotation % 2 == 1 { + std::mem::swap(&mut width, &mut height); + par = (par.1, par.0); + } + let frame_rate = estimate_matroska_frame_rate(video_track); + let duration = matroska_duration(&file, video_track); + let codec_name = video_params.codec.name().to_string(); + let container_name = if file.doc_type == "webm" { "webm" } else { "mkv" }.to_string(); + + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .tracks + .iter() + .enumerate() + .filter(|(_, t)| t.kind == matroska::TrackKind::Audio && !t.samples.is_empty() && t.timebase.0 > 0 && t.timebase.1 > 0 && t.frames_readable()) + .map(|(idx, t)| (idx, t.samples.len(), t.codec_params(), t.codec_delay_ns)) + .collect(); + + let container = ContainerFile::Matroska(Box::new(file)); + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + + let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) { + Ok(d) => d, + Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), + }; + + let info = MediaInfo { + name: name.to_string(), + kind: MediaKind::Movie, + duration, + video: Some(VideoStreamInfo { + width, + height, + frame_rate, + par, + codec: codec_name, + pixel_format: String::new(), + color, + has_alpha: false, + bitrate: None, + hdr: None, + }), + audio_streams: audio_infos, + container: container_name, + start_timecode: None, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx: video_idx, + container_color, + par, + rotation, + video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), + audio_tracks, + }))) +} + +struct CachedFrame { + pts: i64, + draft: bool, + frame: Arc, +} + +struct VideoState { + decoder: TrackDecoder, + next_decode_idx: usize, + gop_start_idx: usize, + flushed: bool, + decoded: Vec, +} + +struct AudioTrackState { + decoder: AudioTrackDecoder, + next_sample: usize, + /// Sample index (in native-rate frames) of `buf[0]` relative to track start (0). + decoded_pos: i64, + /// Planar: one `Vec` per channel. + buf: Vec>, +} + +struct AudioTrackEntry { + track_idx: usize, + native_rate: u32, + state: Mutex, +} + +struct CraftMediaSource { + info: MediaInfo, + source: SharedBytes, + file: ContainerFile, + video_track_idx: usize, + container_color: Option, + par: (u32, u32), + rotation: u8, + video: Mutex, + audio_tracks: Vec, +} + +impl MediaSource for CraftMediaSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, req: FrameRequest) -> Result> { + let (target_idx, target_pts) = self.file.target_sample(self.video_track_idx, req.time).ok_or_else(|| MediaError::Decode("no video samples".into()))?; + let want_draft = req.scale < 0.99; + + let mut state = self.video.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts && c.draft == want_draft) { + return Ok(hit.frame.clone()); + } + + let sync_idx = self.file.sync_sample_before(self.video_track_idx, target_idx); + let draft_changed = state.decoder.draft() != want_draft; + if draft_changed { + state.decoder.set_draft(want_draft); + } + // Backward seek, jump to a later GOP, or draft/full-quality mode switch: reset decoder to + // the target sync sample so full-quality frames never reuse draft-decoded references. + if draft_changed || target_idx < state.next_decode_idx || sync_idx > state.gop_start_idx { + state.decoder.reset().map_err(|e| MediaError::Decode(e.to_string()))?; + state.decoded.clear(); + state.next_decode_idx = sync_idx; + state.gop_start_idx = sync_idx; + state.flushed = false; + } + + let sample_count = self.file.sample_count(self.video_track_idx); + while !state.decoded.iter().any(|c| c.pts >= target_pts && c.draft == want_draft) { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + if state.next_decode_idx < sample_count { + let idx = state.next_decode_idx; + let pts = self.file.sample_pts(self.video_track_idx, idx); + let pkt = self.file.read_sample(&*self.source, self.video_track_idx, idx)?; + let frames = state.decoder.decode(&pkt, pts).map_err(|e| MediaError::Decode(e.to_string()))?; + state.next_decode_idx = idx + 1; + push_decoded(&mut state.decoded, frames, want_draft, self.container_color, self.par, self.rotation, &self.file, self.video_track_idx)?; + } else if !state.flushed { + let frames = state.decoder.flush().map_err(|e| MediaError::Decode(e.to_string()))?; + state.flushed = true; + push_decoded(&mut state.decoded, frames, want_draft, self.container_color, self.par, self.rotation, &self.file, self.video_track_idx)?; + break; + } else { + break; + } + } + + if let Some(exact) = state.decoded.iter().find(|c| c.pts == target_pts && c.draft == want_draft) { + return Ok(exact.frame.clone()); + } + // Fallback: latest decoded frame at or before target_pts, or earliest available. + let best = state + .decoded + .iter() + .filter(|c| c.draft == want_draft && c.pts <= target_pts) + .max_by_key(|c| c.pts) + .or_else(|| state.decoded.iter().find(|c| c.draft == want_draft)) + .ok_or_else(|| MediaError::Decode("video decoder produced no frame".into()))?; + Ok(best.frame.clone()) + } + + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { + self.audio_stream(0, start, frames, sample_rate) + } + + fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { + let entry = self.audio_tracks.get(stream).ok_or(MediaError::NoStream("audio"))?; + if sample_rate == 0 { + return Err(MediaError::Decode("invalid audio sample rate 0".into())); + } + let channels_count = self.info.audio_streams.get(stream).map_or(2, |s| s.channels as usize); + if frames == 0 { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, 0)); + } + + let native_rate = entry.native_rate; + let (native_start, native_frames) = if sample_rate == native_rate { + (start, frames) + } else { + let s0 = (i128::from(start) * i128::from(native_rate)) / i128::from(sample_rate); + let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize; + (i64::try_from(s0).unwrap_or(0), len) + }; + + let mut state = entry.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let decoded = decode_audio_range(&self.file, &*self.source, entry.track_idx, native_rate, channels_count, &mut state, native_start, native_frames)?; + + if sample_rate == native_rate { + return Ok(AudioBuffer { sample_rate, channels: decoded }); + } + + let mut resampled = vec![vec![0.0f32; frames]; channels_count]; + let ratio = f64::from(native_rate) / f64::from(sample_rate); + for (c, out_ch) in resampled.iter_mut().enumerate() { + let in_ch = &decoded[c]; + if in_ch.is_empty() { + continue; + } + for (i, dst) in out_ch.iter_mut().enumerate() { + let pos = i as f64 * ratio; + let idx = pos.floor() as usize; + let frac = (pos - idx as f64) as f32; + let s0 = in_ch.get(idx).copied().unwrap_or(0.0); + let s1 = in_ch.get(idx + 1).copied().unwrap_or(s0); + *dst = s0 + (s1 - s0) * frac; + } + } + Ok(AudioBuffer { sample_rate, channels: resampled }) + } +} + +#[allow(clippy::too_many_arguments)] +fn decode_audio_range( + file: &ContainerFile, + source: &dyn ByteSource, + track_idx: usize, + native_rate: u32, + channels_count: usize, + state: &mut AudioTrackState, + start: i64, + frames: usize, +) -> Result>> { + let mut out = vec![vec![0.0f32; frames]; channels_count]; + let end = start.saturating_add(frames as i64); + if end <= 0 { + return Ok(out); + } + + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + let buf_end = state.decoded_pos.saturating_add(buf_len); + if start < state.decoded_pos || start > buf_end + i64::from(native_rate) * 2 { + let (seek_idx, decoded_pos) = file.audio_seek_info(track_idx, start, native_rate); + state.decoder.reset(); + state.next_sample = seek_idx; + state.decoded_pos = decoded_pos; + for ch in &mut state.buf { + ch.clear(); + } + } + + if state.buf.len() != channels_count { + state.buf = vec![Vec::new(); channels_count]; + } + + let sample_count = file.sample_count(track_idx); + while state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64 <= end && state.next_sample < sample_count { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + let idx = state.next_sample; + let pkt = file.read_sample(source, track_idx, idx)?; + state.next_sample = idx + 1; + let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; + for (c, ch) in state.buf.iter_mut().enumerate() { + if let Some(src_ch) = block.channels.get(c) { + ch.extend_from_slice(src_ch); + } + } + } + + let avail = state.buf.first().map_or(0, Vec::len); + for i in 0..frames { + let pos = start.saturating_add(i as i64); + if pos >= state.decoded_pos { + let off = (pos - state.decoded_pos) as usize; + if off < avail { + for (c, out_ch) in out.iter_mut().enumerate() { + out_ch[i] = state.buf[c][off]; + } + } + } + } + + let drop_to = (end - state.decoded_pos).max(0) as usize; + let trim = drop_to.min(avail); + if trim > 0 { + for ch in &mut state.buf { + ch.drain(..trim); + } + state.decoded_pos = state.decoded_pos.saturating_add(trim as i64); + } + + Ok(out) +} + +#[allow(clippy::too_many_arguments)] +fn push_decoded( + cache: &mut Vec, + frames: Vec, + draft: bool, + container_color: Option, + par: (u32, u32), + rotation: u8, + file: &ContainerFile, + track_idx: usize, +) -> Result<()> { + for vf in frames { + let pts = vf.pts.unwrap_or(0); + let pts_tick = file.pts_to_tick(track_idx, pts); + let frame = Arc::new(to_craft_frame(vf, container_color, par, rotation, pts_tick)?); + cache.push(CachedFrame { pts, draft, frame }); + } + if cache.len() > MAX_CACHED_FRAMES { + let excess = cache.len() - MAX_CACHED_FRAMES; + cache.drain(..excess); + } + Ok(()) +} + +fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option, default_par: (u32, u32), rotation: u8, pts: Tick) -> Result { + let width = vf.width(); + let height = vf.height(); + let subsampling = vf.subsampling(); + let family = vf.family(); + let tags = vf.color; + let par = match vf.sar.filter(|&(n, d)| n > 0 && d > 0) { + Some((n, d)) if rotation % 2 == 1 => (d, n), + Some(sar) => sar, + None => default_par, + }; + let color = resolve_color(tags, container_color); + let bit_depth = vf.bit_depth(); + let (planes, alpha) = vf.into_planes(); + + let data = match family { + ColorFamily::YCbCr => { + let chroma = match subsampling { + Subsampling::S420 => Chroma::C420, + Subsampling::S422 => Chroma::C422, + Subsampling::S444 => Chroma::C444, + _ => return Err(MediaError::Unsupported("unsupported YCbCr subsampling".into())), + }; + let mut iter = planes.into_iter(); + let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else { + return Err(MediaError::Decode("missing YUV planes".into())); + }; + if bit_depth <= 8 { + let y = Arc::new(plane_u8(y)?); + let cb = Arc::new(plane_u8(cb)?); + let cr = Arc::new(plane_u8(cr)?); + let a = alpha.map(plane_u8).transpose()?.map(Arc::new); + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha: a } + } else { + let y = Arc::new(plane_u16(y)?); + let cb = Arc::new(plane_u16(cb)?); + let cr = Arc::new(plane_u16(cr)?); + let a = alpha.map(plane_u16).transpose()?.map(Arc::new); + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a } + } + } + ColorFamily::Rgb | ColorFamily::Gray => return Err(MediaError::Unsupported("non-YCbCr pixel format".into())), + }; + + let frame = VideoFrame { width, height, data, color, par, pts }; + Ok(rotate_frame(frame, rotation)) +} + +fn rotate_plane(src: &[T], w: usize, h: usize, turns: u8) -> Vec { + if w == 0 || h == 0 || src.len() < w * h { + return src.to_vec(); + } + let mut dst = vec![T::default(); w * h]; + match turns % 4 { + 1 => { + for y in 0..h { + for x in 0..w { + dst[x * h + (h - 1 - y)] = src[y * w + x]; + } + } + } + 2 => { + for y in 0..h { + for x in 0..w { + dst[(h - 1 - y) * w + (w - 1 - x)] = src[y * w + x]; + } + } + } + 3 => { + for y in 0..h { + for x in 0..w { + dst[(w - 1 - x) * h + y] = src[y * w + x]; + } + } + } + _ => return src.to_vec(), + } + dst +} + +fn upsample_horiz(src: &[T], cw: usize, ch: usize, full_w: usize) -> Vec { + let mut out = Vec::with_capacity(full_w * ch); + for y in 0..ch { + let row = &src[y * cw..(y + 1) * cw]; + for x in 0..full_w { + out.push(row[(x / 2).min(cw.saturating_sub(1))]); + } + } + out +} + +fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame { + let turns = turns % 4; + if turns == 0 { + return frame; + } + let (w, h) = (frame.width as usize, frame.height as usize); + let (nw, nh) = if turns % 2 == 1 { (frame.height, frame.width) } else { (frame.width, frame.height) }; + let data = match frame.data { + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha } => { + let (cw, ch, out_chroma) = match chroma { + Chroma::C420 => (w.div_ceil(2), h.div_ceil(2), Chroma::C420), + Chroma::C422 if turns % 2 == 1 => (w, h, Chroma::C444), + Chroma::C422 => (w.div_ceil(2), h, Chroma::C422), + Chroma::C444 => (w, h, Chroma::C444), + }; + let (cb_r, cr_r) = if chroma == Chroma::C422 && turns % 2 == 1 { + let src_cw = w.div_ceil(2); + (rotate_plane(&upsample_horiz(&cb, src_cw, h, w), w, h, turns), rotate_plane(&upsample_horiz(&cr, src_cw, h, w), w, h, turns)) + } else { + (rotate_plane(&cb, cw, ch, turns), rotate_plane(&cr, cw, ch, turns)) + }; + PixelData::Yuv8 { + planes: [Arc::new(rotate_plane(&y, w, h, turns)), Arc::new(cb_r), Arc::new(cr_r)], + chroma: out_chroma, + alpha: alpha.map(|a| Arc::new(rotate_plane(&a, w, h, turns))), + } + } + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits, alpha } => { + let (cw, ch, out_chroma) = match chroma { + Chroma::C420 => (w.div_ceil(2), h.div_ceil(2), Chroma::C420), + Chroma::C422 if turns % 2 == 1 => (w, h, Chroma::C444), + Chroma::C422 => (w.div_ceil(2), h, Chroma::C422), + Chroma::C444 => (w, h, Chroma::C444), + }; + let (cb_r, cr_r) = if chroma == Chroma::C422 && turns % 2 == 1 { + let src_cw = w.div_ceil(2); + (rotate_plane(&upsample_horiz(&cb, src_cw, h, w), w, h, turns), rotate_plane(&upsample_horiz(&cr, src_cw, h, w), w, h, turns)) + } else { + (rotate_plane(&cb, cw, ch, turns), rotate_plane(&cr, cw, ch, turns)) + }; + PixelData::Yuv16 { + planes: [Arc::new(rotate_plane(&y, w, h, turns)), Arc::new(cb_r), Arc::new(cr_r)], + chroma: out_chroma, + bits, + alpha: alpha.map(|a| Arc::new(rotate_plane(&a, w, h, turns))), + } + } + other => other, + }; + frame.width = nw; + frame.height = nh; + frame.data = data; + frame +} + +fn plane_u8(p: Plane) -> Result> { + let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + match p.into_samples() { + Samples::U8(mut v) => { + if stride == w { + v.truncate(w * h); + return Ok(v); + } + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + let row = y * stride; + out.extend_from_slice(&v[row..row + w]); + } + Ok(out) + } + Samples::U16(v) => { + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + let row = y * stride; + out.extend(v[row..row + w].iter().map(|&s| s.min(255) as u8)); + } + Ok(out) + } + } +} + +fn plane_u16(p: Plane) -> Result> { + let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + match p.into_samples() { + Samples::U16(mut v) => { + if stride == w { + v.truncate(w * h); + return Ok(v); + } + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + let row = y * stride; + out.extend_from_slice(&v[row..row + w]); + } + Ok(out) + } + Samples::U8(v) => { + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + let row = y * stride; + out.extend(v[row..row + w].iter().map(|&s| u16::from(s))); + } + Ok(out) + } + } +} + +fn resolve_color(vui: ColorTags, container: Option) -> ColorInfo { + let base = container.unwrap_or(ColorInfo::REC709); + let matrix = Matrix::from_code(vui.matrix).unwrap_or(base.matrix); + let transfer = Transfer::from_code(vui.transfer).unwrap_or(base.transfer); + let primaries = primaries_from_code(vui.primaries).unwrap_or(base.primaries); + let range = if vui.full_range { Range::Full } else { base.range }; + ColorInfo { matrix, transfer, primaries, range } +} + +fn color_from_isobmff(c: &isobmff::ColorInfo) -> ColorInfo { + match c { + isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => ColorInfo { + matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), + transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), + primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709), + range: if *full_range { Range::Full } else { Range::Limited }, + }, + isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => ColorInfo { + matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), + transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), + primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709), + range: Range::Limited, + }, + isobmff::ColorInfo::Icc { .. } => ColorInfo::REC709, + } +} + +fn color_from_matroska(c: &matroska::Color) -> ColorInfo { + ColorInfo { + matrix: c.matrix_coefficients.and_then(|m| u8::try_from(m).ok()).and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), + transfer: c.transfer_characteristics.and_then(|t| u8::try_from(t).ok()).and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), + primaries: c.primaries.and_then(|p| u8::try_from(p).ok()).and_then(primaries_from_code).unwrap_or(Primaries::Bt709), + range: if c.full_range() { Range::Full } else { Range::Limited }, + } +} + +fn primaries_from_code(c: u8) -> Option { + match c { + 1 => Some(Primaries::Bt709), + 5 => Some(Primaries::Bt601_625), + 6 => Some(Primaries::Bt601_525), + 9 => Some(Primaries::Bt2020), + 11 | 12 => Some(Primaries::P3D65), + _ => None, + } +} + +fn matroska_par(video: Option<&matroska::VideoInfo>, width: u32, height: u32) -> (u32, u32) { + let Some(v) = video else { return (1, 1) }; + if v.display_unit == 0 + && let (Some(dw), Some(dh)) = (v.display_width, v.display_height) + && dw > 0 + && dh > 0 + && width > 0 + && height > 0 + && (dw != width || dh != height) + { + return (dw * height, dh * width); + } + (1, 1) +} + +fn matroska_duration(file: &MkvFile, track: &matroska::Track) -> Tick { + if let Some(d) = file.info.duration + && d.is_finite() + && d > 0.0 + { + let ns = (d * file.info.timestamp_scale as f64).round() as i64; + return Tick::from_units(ns, 1_000_000_000); + } + let last_end = track.samples.last().map_or(0, |s| s.pts.saturating_add(i64::try_from(s.duration).unwrap_or(0))); + Tick::from_units(track.ticks_to_ns(last_end), 1_000_000_000) +} + +fn tick_to_units(t: Tick, timescale: u32) -> i64 { + let v = (i128::from(t.0) * i128::from(timescale)) / i128::from(craft_time::TICKS_PER_SECOND); + i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) +} + +fn tick_to_matroska_units(t: Tick, timebase: (u64, u64)) -> i64 { + let denom = i128::from(craft_time::TICKS_PER_SECOND) * i128::from(timebase.0.max(1)); + let v = (i128::from(t.0) * i128::from(timebase.1)) / denom; + i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) +} + +fn snap_common_fps(fps: f64) -> Option { + if !fps.is_finite() || fps <= 0.0 { + return None; + } + FrameRate::COMMON + .into_iter() + .map(|r| (r, (fps / r.as_f64() - 1.0).abs())) + .filter(|&(_, off)| off <= 0.005) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(r, _)| r) +} + +fn estimate_isobmff_frame_rate(track: &isobmff::Track) -> FrameRate { + let ts = i128::from(track.timescale); + if ts <= 0 || track.samples.is_empty() { + return FrameRate::FPS_30; + } + let mut durs: Vec = track.samples.iter().map(|s| s.duration).filter(|&d| d > 0).collect(); + if durs.is_empty() { + return FrameRate::FPS_30; + } + durs.sort_unstable(); + let median = durs[durs.len() / 2]; + for r in FrameRate::COMMON { + if ts * i128::from(r.den) == i128::from(median) * i128::from(r.num) { + return r; + } + } + let fps = track.timescale as f64 / f64::from(median); + snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(track.timescale), i64::from(median))) +} + +fn estimate_matroska_frame_rate(track: &matroska::Track) -> FrameRate { + if let Some(ns) = track.default_duration_ns + && ns > 0 + { + let fps = 1_000_000_000.0 / ns as f64; + return snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(1_000_000_000, i64::try_from(ns).unwrap_or(i64::MAX))); + } + if track.samples.len() >= 2 { + let mut pts: Vec = track.samples.iter().map(|s| s.pts).collect(); + pts.sort_unstable(); + let mut deltas: Vec = pts.windows(2).map(|w| w[1] - w[0]).filter(|&d| d > 0).collect(); + if !deltas.is_empty() { + deltas.sort_unstable(); + let median_ticks = deltas[deltas.len() / 2]; + let median_ns = track.ticks_to_ns(median_ticks); + if median_ns > 0 { + let fps = 1_000_000_000.0 / median_ns as f64; + return snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(1_000_000_000, median_ns)); + } + } + } + FrameRate::FPS_30 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn worker_cap_is_bounded() { + let cap = worker_cap(); + assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}"); + } + + #[test] + fn vui_overrides_container_color_and_falls_back_when_unspecified() { + let container = color_from_isobmff(&isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: false }); + assert_eq!(container.primaries, Primaries::Bt2020); + assert_eq!(container.transfer, Transfer::Pq); + assert_eq!(container.matrix, Matrix::Bt2020Ncl); + assert_eq!(container.range, Range::Limited); + + // Unspecified VUI (2) falls back to container color. + let resolved = resolve_color(ColorTags::UNSPECIFIED, Some(container)); + assert_eq!(resolved, container); + + // Explicit VUI overrides container color. + let vui = ColorTags { primaries: 1, transfer: 1, matrix: 1, full_range: true }; + let resolved = resolve_color(vui, Some(container)); + assert_eq!(resolved.primaries, Primaries::Bt709); + assert_eq!(resolved.transfer, Transfer::Bt709); + assert_eq!(resolved.matrix, Matrix::Bt709); + assert_eq!(resolved.range, Range::Full); + } + + #[test] + fn matroska_color_and_sniffer_preserve_policies() { + assert!(looks_like_matroska(&[0x1A, 0x45, 0xDF, 0xA3, 0x01, 0x00])); + assert!(!looks_like_matroska(&[0x00, 0x00, 0x00, 0x18, b'f', b't', b'y', b'p'])); + assert!(looks_like_isobmff(&[0x00, 0x00, 0x00, 0x18, b'f', b't', b'y', b'p'])); + + let mkv_hdr = + matroska::Color { matrix_coefficients: Some(9), transfer_characteristics: Some(16), primaries: Some(9), range: Some(1), ..Default::default() }; + let c = color_from_matroska(&mkv_hdr); + assert_eq!(c.primaries, Primaries::Bt2020); + assert_eq!(c.transfer, Transfer::Pq); + assert_eq!(c.matrix, Matrix::Bt2020Ncl); + assert_eq!(c.range, Range::Limited); + } + + #[test] + fn rotate_frame_swaps_dimensions_and_orients_planes() { + let frame = VideoFrame { + width: 4, + height: 2, + data: PixelData::Yuv8 { + planes: [Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8]), Arc::new(vec![10, 20]), Arc::new(vec![30, 40])], + chroma: Chroma::C420, + alpha: Some(Arc::new(vec![11, 12, 13, 14, 15, 16, 17, 18])), + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + let rot90 = rotate_frame(frame.clone(), 1); + assert_eq!((rot90.width, rot90.height), (2, 4)); + assert!(matches!(rot90.data, PixelData::Yuv8 { alpha: Some(_), .. })); + if let PixelData::Yuv8 { planes: [y, ..], alpha: Some(a), .. } = &rot90.data { + assert_eq!(&**y, &[5, 1, 6, 2, 7, 3, 8, 4]); + assert_eq!(&**a, &[15, 11, 16, 12, 17, 13, 18, 14]); + } + let rot360 = rotate_frame(rot90, 3); + assert_eq!((rot360.width, rot360.height), (4, 2)); + if let PixelData::Yuv8 { planes: [y, ..], .. } = &rot360.data { + assert_eq!(&**y, &[1, 2, 3, 4, 5, 6, 7, 8]); + } + } + + #[test] + fn plane_u8_handles_8bit_u16_storage_as_av1_produces() { + let out = Plane::packed(2, 2, 8, Samples::U16(vec![10, 20, 30, 255])).ok().and_then(|p| plane_u8(p).ok()); + assert_eq!(out.as_deref(), Some(&[10, 20, 30, 255][..])); + } + + #[test] + fn rotate_frame_covers_180_270_c422_and_yuv16() { + let f16 = VideoFrame { + width: 4, + height: 2, + data: PixelData::Yuv16 { + planes: [Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8]), Arc::new(vec![10, 20, 30, 40]), Arc::new(vec![50, 60, 70, 80])], + chroma: Chroma::C422, + bits: 10, + alpha: Some(Arc::new(vec![100; 8])), + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + let r180 = rotate_frame(f16.clone(), 2); + assert_eq!((r180.width, r180.height), (4, 2)); + if let PixelData::Yuv16 { planes: [y, ..], chroma, .. } = &r180.data { + assert_eq!(*chroma, Chroma::C422); + assert_eq!(&**y, &[8, 7, 6, 5, 4, 3, 2, 1]); + } + let r270 = rotate_frame(f16, 1); + assert_eq!((r270.width, r270.height), (2, 4)); + if let PixelData::Yuv16 { chroma, .. } = &r270.data { + assert_eq!(*chroma, Chroma::C444); + } + } + + #[test] + fn plane_stride_and_container_helpers_cover_variants() { + if let Ok(p8) = Plane::new(2, 2, 4, 8, Samples::U8(vec![1, 2, 9, 9, 3, 4])) { + assert_eq!(plane_u8(p8).ok().as_deref(), Some(&[1, 2, 3, 4][..])); + } + if let Ok(p16) = Plane::new(2, 2, 4, 10, Samples::U16(vec![10, 20, 99, 99, 30, 40])) { + assert_eq!(plane_u16(p16).ok().as_deref(), Some(&[10, 20, 30, 40][..])); + } + if let Ok(p8_as_16) = Plane::packed(2, 1, 8, Samples::U8(vec![7, 8])) { + assert_eq!(plane_u16(p8_as_16).ok().as_deref(), Some(&[7, 8][..])); + } + + let nclc = color_from_isobmff(&isobmff::ColorInfo::Nclc { primaries: 1, transfer: 1, matrix: 1 }); + assert_eq!(nclc, ColorInfo::REC709); + let icc = color_from_isobmff(&isobmff::ColorInfo::Icc { kind: isobmff::FourCc(*b"prof"), profile: Vec::new() }); + assert_eq!(icc, ColorInfo::REC709); + + let v = matroska::VideoInfo { display_width: Some(1280), display_height: Some(720), display_unit: 0, ..Default::default() }; + assert_eq!(matroska_par(Some(&v), 640, 720), (1280 * 720, 720 * 640)); + assert_eq!(matroska_par(None, 640, 360), (1, 1)); + assert_eq!(snap_common_fps(23.976), Some(FrameRate::FPS_23_976)); + assert_eq!(snap_common_fps(f64::NAN), None); + assert_eq!(tick_to_matroska_units(Tick(craft_time::TICKS_PER_SECOND), (1, 1000)), 1000); + assert_eq!(tick_to_units(Tick(craft_time::TICKS_PER_SECOND), 90000), 90000); + } + + #[test] + fn rotated_frame_preserves_container_par_without_double_inversion() { + let make_vf = |sar: Option<(u32, u32)>| { + let y = Plane::packed(2, 2, 8, Samples::U8(vec![1, 2, 3, 4])).ok()?; + let cb = Plane::packed(1, 1, 8, Samples::U8(vec![128])).ok()?; + let cr = Plane::packed(1, 1, 8, Samples::U8(vec![128])).ok()?; + let mut vf = DecodedVideoFrame::new(2, 2, ColorFamily::YCbCr, Subsampling::S420, vec![y, cb, cr], None).ok()?; + vf.sar = sar; + Some(vf) + }; + // `default_par` is already rotated by the container opener (e.g. (4, 3) -> (3, 4) for 90°). + let container_rotated_par = (3, 4); + if let Some(vf_no_sar) = make_vf(None) { + let out = to_craft_frame(vf_no_sar, None, container_rotated_par, 1, Tick::ZERO).ok(); + assert_eq!(out.map(|f| f.par), Some((3, 4))); + } + // Decoder-supplied SAR is in coded coordinates and must be inverted once under 90° rotation. + if let Some(vf_with_sar) = make_vf(Some((4, 3))) { + let out = to_craft_frame(vf_with_sar, None, container_rotated_par, 1, Tick::ZERO).ok(); + assert_eq!(out.map(|f| f.par), Some((3, 4))); + } + } +} diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 4f337c0bf..d1a907821 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -17,6 +17,7 @@ mod aac; mod convert; +mod craft_source; pub mod downmix; mod dpx; pub mod exr_channels; @@ -26,7 +27,6 @@ mod exr_read; mod gif_anim; mod layered; mod localize; -mod mp4_h264; pub use layered::vector_doc; mod pool; mod probe; diff --git a/crates/media/src/mp4_h264.rs b/crates/media/src/mp4_h264.rs deleted file mode 100644 index 456fcd92b..000000000 --- a/crates/media/src/mp4_h264.rs +++ /dev/null @@ -1,597 +0,0 @@ -//! Software MP4/MOV H.264 route backed by `craft-media`, `craft-video`, `craft-audio`, and -//! `craft-media-source`. -//! -//! Preserves sync-sample backward seek, B-frame reordering, cooperative cancellation, VUI + -//! container colour resolution, draft mode for reduced-resolution playback, and bounded worker -//! threads. - -use std::sync::{Arc, Mutex}; - -use craft_audio::{AudioBuffer, TrackDecoder as AudioTrackDecoder}; -use craft_color::{ColorInfo, Matrix, Primaries, Range, Transfer}; -use craft_frame::{Chroma, PixelData, VideoFrame}; -use craft_media::isobmff::{self, Mp4File, Track, TrackKind}; -use craft_media::{ByteSource, CodecId}; -use craft_media_source::{ - AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo, -}; -use craft_time::{FrameRate, Tick}; -use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame}; -use craft_video::{TrackDecoder, TrackDecoderOptions}; - -/// Maximum worker threads per `TrackDecoder` instance. -const MAX_WORKERS: usize = 8; - -/// Maximum decoded frames retained in the per-source GOP window cache. -const MAX_CACHED_FRAMES: usize = 32; - -/// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`. -const AUDIO_LOOKAHEAD: usize = 8; - -fn worker_cap() -> usize { - std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) -} - -/// True when `head` begins with a plausible ISO-BMFF top-level box. -fn looks_like_isobmff(head: &[u8]) -> bool { - if head.len() < 8 { - return false; - } - matches!(&head[4..8], b"ftyp" | b"moov" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot" | b"uuid") -} - -/// Open an in-place MP4/MOV H.264 source via `craft-media` / `craft-video`. -/// Returns `None` when the file is not ISO-BMFF, has no H.264 video track, or has an audio track -/// whose codec is not yet handled by `craft-audio`. -pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Option> { - if !looks_like_isobmff(head) { - return None; - } - open_byte_source(name, reader.clone()) -} - -/// Open an in-memory MP4/MOV H.264 source via `craft-media` / `craft-video`. -pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { - if !looks_like_isobmff(&bytes) { - return None; - } - open_byte_source(name, Arc::new(bytes)) -} - -fn open_byte_source(name: &str, source: SharedBytes) -> Option> { - let file = isobmff::open(source.clone()).ok()?; - let video_idx = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0)?; - let video_track = &file.tracks[video_idx]; - let video_params = video_track.codec_params(); - if video_params.codec != CodecId::H264 { - return None; - } - - // Collect playable audio tracks and ensure `craft-audio` can decode every one of them. - let mut audio_tracks = Vec::new(); - let mut audio_infos = Vec::new(); - for (idx, track) in file.tracks.iter().enumerate() { - if audio_tracks.len() >= MAX_AUDIO_STREAMS { - break; - } - if track.kind != TrackKind::Audio || track.samples.is_empty() || track.entries.is_empty() || track.timescale == 0 { - continue; - } - let params = track.codec_params(); - let mut lookahead = Vec::with_capacity(AUDIO_LOOKAHEAD.min(track.samples.len())); - for s_idx in 0..AUDIO_LOOKAHEAD.min(track.samples.len()) { - let Ok(pkt) = file.read_sample(&*source, idx, s_idx) else { - return None; - }; - lookahead.push(pkt); - } - let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect(); - let Ok(dec) = AudioTrackDecoder::new(¶ms, &refs) else { - return None; - }; - let native_rate = dec.sample_rate().max(1); - let channels = u32::from(dec.layout().channels()).max(1); - audio_infos.push(AudioStreamInfo { - sample_rate: native_rate, - channels, - codec: params.codec.name().to_string(), - bits_per_sample: params.pcm.map(|p| u32::from(p.bits)), - }); - audio_tracks.push(AudioTrackEntry { - track_idx: idx, - native_rate, - state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: 0, buf: Vec::new() }), - }); - } - - let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) { - Ok(d) => d, - Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), - }; - - let container_color = video_track.video().and_then(|v| v.color.as_ref()).map(color_from_isobmff); - let color = container_color.unwrap_or(ColorInfo::REC709); - let (width, height) = video_track - .video() - .map(|v| (u32::from(v.width), u32::from(v.height))) - .filter(|&(w, h)| w > 0 && h > 0) - .unwrap_or((video_track.width, video_track.height)); - let par = video_track.video().and_then(|v| v.pixel_aspect).filter(|&(n, d)| n > 0 && d > 0).unwrap_or((1, 1)); - let frame_rate = estimate_frame_rate(video_track); - let duration = Tick::from_units(i64::try_from(video_track.duration).unwrap_or(i64::MAX), i64::from(video_track.timescale)); - let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0); - - let info = MediaInfo { - name: name.to_string(), - kind: MediaKind::Movie, - duration, - video: Some(VideoStreamInfo { - width, - height, - frame_rate, - par, - codec: "H.264".to_string(), - pixel_format: "yuv420p".to_string(), - color, - has_alpha: false, - bitrate, - hdr: None, - }), - audio_streams: audio_infos, - container: "mp4".to_string(), - start_timecode: None, - file_size: Some(source.len()), - }; - - Some(Ok(Arc::new(Mp4H264Source { - info, - source, - file, - video_track_idx: video_idx, - container_color, - par, - video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), - audio_tracks, - }))) -} - -struct CachedFrame { - pts: i64, - frame: Arc, -} - -struct VideoState { - decoder: TrackDecoder, - next_decode_idx: usize, - gop_start_idx: usize, - flushed: bool, - decoded: Vec, -} - -struct AudioTrackState { - decoder: AudioTrackDecoder, - next_sample: usize, - /// Sample index (in native-rate frames) of `buf[0]` relative to track start (0). - decoded_pos: i64, - /// Interleaved or planar? Planar: one `Vec` per channel. - buf: Vec>, -} - -struct AudioTrackEntry { - track_idx: usize, - native_rate: u32, - state: Mutex, -} - -struct Mp4H264Source { - info: MediaInfo, - source: SharedBytes, - file: Mp4File, - video_track_idx: usize, - container_color: Option, - par: (u32, u32), - video: Mutex, - audio_tracks: Vec, -} - -impl MediaSource for Mp4H264Source { - fn info(&self) -> &MediaInfo { - &self.info - } - - fn video_frame(&self, req: FrameRequest) -> Result> { - let track = &self.file.tracks[self.video_track_idx]; - let t_track = tick_to_units(req.time, track.timescale); - let target_idx = track.sample_at_presentation_time(t_track).ok_or_else(|| MediaError::Decode("no video samples".into()))?; - let target_pts = track.samples[target_idx].pts; - - let mut state = self.video.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts) { - return Ok(hit.frame.clone()); - } - - let sync_idx = track.sync_sample_before(target_idx); - // Backward seek or jump to a later GOP: reset the decoder to the target sync sample. - if target_idx < state.next_decode_idx || sync_idx > state.gop_start_idx { - state.decoder.reset().map_err(|e| MediaError::Decode(e.to_string()))?; - state.decoded.clear(); - state.next_decode_idx = sync_idx; - state.gop_start_idx = sync_idx; - state.flushed = false; - } - - let want_draft = req.scale < 0.99; - if state.decoder.draft() != want_draft { - state.decoder.set_draft(want_draft); - } - - while !state.decoded.iter().any(|c| c.pts >= target_pts) { - if filmcraft_media::cancel::cancelled() { - return Err(MediaError::Cancelled); - } - if state.next_decode_idx < track.samples.len() { - let idx = state.next_decode_idx; - let sample = track.samples[idx]; - let pkt = self.file.read_sample(&*self.source, self.video_track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?; - let frames = state.decoder.decode(&pkt, sample.pts).map_err(|e| MediaError::Decode(e.to_string()))?; - state.next_decode_idx = idx + 1; - push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?; - } else if !state.flushed { - let frames = state.decoder.flush().map_err(|e| MediaError::Decode(e.to_string()))?; - state.flushed = true; - push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?; - break; - } else { - break; - } - } - - if let Some(exact) = state.decoded.iter().find(|c| c.pts == target_pts) { - return Ok(exact.frame.clone()); - } - // Fallback: latest decoded frame at or before target_pts, or earliest available. - let best = state - .decoded - .iter() - .filter(|c| c.pts <= target_pts) - .max_by_key(|c| c.pts) - .or_else(|| state.decoded.first()) - .ok_or_else(|| MediaError::Decode("H.264 decoder produced no frame".into()))?; - Ok(best.frame.clone()) - } - - fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { - self.audio_stream(0, start, frames, sample_rate) - } - - fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { - let entry = self.audio_tracks.get(stream).ok_or(MediaError::NoStream("audio"))?; - if sample_rate == 0 { - return Err(MediaError::Decode("invalid audio sample rate 0".into())); - } - let channels_count = self.info.audio_streams.get(stream).map_or(2, |s| s.channels as usize); - if frames == 0 { - return Ok(AudioBuffer::new(sample_rate, channels_count as u16, 0)); - } - - let native_rate = entry.native_rate; - let (native_start, native_frames) = if sample_rate == native_rate { - (start, frames) - } else { - let s0 = (i128::from(start) * i128::from(native_rate)) / i128::from(sample_rate); - let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize; - (i64::try_from(s0).unwrap_or(0), len) - }; - - let track = &self.file.tracks[entry.track_idx]; - let mut state = entry.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let decoded = - decode_audio_range(&self.file, &*self.source, entry.track_idx, track, native_rate, channels_count, &mut state, native_start, native_frames)?; - - if sample_rate == native_rate { - return Ok(AudioBuffer { sample_rate, channels: decoded }); - } - - let mut resampled = vec![vec![0.0f32; frames]; channels_count]; - let ratio = f64::from(native_rate) / f64::from(sample_rate); - for (c, out_ch) in resampled.iter_mut().enumerate() { - let in_ch = &decoded[c]; - if in_ch.is_empty() { - continue; - } - for (i, dst) in out_ch.iter_mut().enumerate() { - let pos = i as f64 * ratio; - let idx = pos.floor() as usize; - let frac = (pos - idx as f64) as f32; - let s0 = in_ch.get(idx).copied().unwrap_or(0.0); - let s1 = in_ch.get(idx + 1).copied().unwrap_or(s0); - *dst = s0 + (s1 - s0) * frac; - } - } - Ok(AudioBuffer { sample_rate, channels: resampled }) - } -} - -#[allow(clippy::too_many_arguments)] -fn decode_audio_range( - file: &Mp4File, - source: &dyn ByteSource, - track_idx: usize, - track: &Track, - native_rate: u32, - channels_count: usize, - state: &mut AudioTrackState, - start: i64, - frames: usize, -) -> Result>> { - let mut out = vec![vec![0.0f32; frames]; channels_count]; - let end = start.saturating_add(frames as i64); - if end <= 0 { - return Ok(out); - } - - let buf_len = state.buf.first().map_or(0, Vec::len) as i64; - let buf_end = state.decoded_pos.saturating_add(buf_len); - if start < state.decoded_pos || start > buf_end + i64::from(native_rate) * 2 { - // Seek to the sample at or before `start` in track timescale. - let t_track = (i128::from(start.max(0)) * i128::from(track.timescale)) / i128::from(native_rate); - let sample_idx = track.sample_at_presentation_time(i64::try_from(t_track).unwrap_or(0)).unwrap_or(0); - // Back up a few packets for AAC/Opus overlap/preroll. - let seek_idx = sample_idx.saturating_sub(2); - state.decoder.reset(); - state.next_sample = seek_idx; - let sample_pts = track.presentation_pts(seek_idx).unwrap_or(0); - state.decoded_pos = i64::try_from((i128::from(sample_pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1))).unwrap_or(0); - for ch in &mut state.buf { - ch.clear(); - } - } - - if state.buf.len() != channels_count { - state.buf = vec![Vec::new(); channels_count]; - } - - while state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64 <= end && state.next_sample < track.samples.len() { - if filmcraft_media::cancel::cancelled() { - return Err(MediaError::Cancelled); - } - let idx = state.next_sample; - let pkt = file.read_sample(source, track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?; - state.next_sample = idx + 1; - let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; - for (c, ch) in state.buf.iter_mut().enumerate() { - if let Some(src_ch) = block.channels.get(c) { - ch.extend_from_slice(src_ch); - } - } - } - - let avail = state.buf.first().map_or(0, Vec::len); - for i in 0..frames { - let pos = start.saturating_add(i as i64); - if pos >= state.decoded_pos { - let off = (pos - state.decoded_pos) as usize; - if off < avail { - for (c, out_ch) in out.iter_mut().enumerate() { - out_ch[i] = state.buf[c][off]; - } - } - } - } - - // Trim already-consumed audio older than `end` minus a small safety margin. - let drop_to = (end - state.decoded_pos).max(0) as usize; - let trim = drop_to.min(avail); - if trim > 0 { - for ch in &mut state.buf { - ch.drain(..trim); - } - state.decoded_pos = state.decoded_pos.saturating_add(trim as i64); - } - - Ok(out) -} - -fn push_decoded( - cache: &mut Vec, - frames: Vec, - container_color: Option, - par: (u32, u32), - timescale: u32, - edit_offset: i64, -) -> Result<()> { - for vf in frames { - let pts = vf.pts.unwrap_or(0); - let frame = Arc::new(to_craft_frame(vf, container_color, par, timescale, edit_offset)?); - cache.push(CachedFrame { pts, frame }); - } - if cache.len() > MAX_CACHED_FRAMES { - let excess = cache.len() - MAX_CACHED_FRAMES; - cache.drain(..excess); - } - Ok(()) -} - -fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option, default_par: (u32, u32), timescale: u32, edit_offset: i64) -> Result { - let width = vf.width(); - let height = vf.height(); - let subsampling = vf.subsampling(); - let family = vf.family(); - let tags = vf.color; - let pts_units = vf.pts.unwrap_or(0).saturating_add(edit_offset); - let pts = Tick::from_units(pts_units, i64::from(timescale.max(1))); - let par = vf.sar.filter(|&(n, d)| n > 0 && d > 0).unwrap_or(default_par); - let color = resolve_color(tags, container_color); - let bit_depth = vf.bit_depth(); - let (planes, alpha) = vf.into_planes(); - - let data = match family { - ColorFamily::YCbCr => { - let chroma = match subsampling { - Subsampling::S420 => Chroma::C420, - Subsampling::S422 => Chroma::C422, - Subsampling::S444 => Chroma::C444, - _ => return Err(MediaError::Unsupported("unsupported YCbCr subsampling".into())), - }; - let mut iter = planes.into_iter(); - let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else { - return Err(MediaError::Decode("missing YUV planes".into())); - }; - if bit_depth <= 8 { - let y = Arc::new(plane_u8(y)?); - let cb = Arc::new(plane_u8(cb)?); - let cr = Arc::new(plane_u8(cr)?); - let a = alpha.map(plane_u8).transpose()?.map(Arc::new); - PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha: a } - } else { - let y = Arc::new(plane_u16(y)?); - let cb = Arc::new(plane_u16(cb)?); - let cr = Arc::new(plane_u16(cr)?); - let a = alpha.map(plane_u16).transpose()?.map(Arc::new); - PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a } - } - } - ColorFamily::Rgb | ColorFamily::Gray => return Err(MediaError::Unsupported("non-YCbCr H.264 pixel format".into())), - }; - - Ok(VideoFrame { width, height, data, color, par, pts }) -} - -fn plane_u8(p: Plane) -> Result> { - let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); - match p.into_samples() { - Samples::U8(mut v) => { - if stride == w { - v.truncate(w * h); - return Ok(v); - } - let mut out = Vec::with_capacity(w * h); - for y in 0..h { - let row = y * stride; - out.extend_from_slice(&v[row..row + w]); - } - Ok(out) - } - Samples::U16(_) => Err(MediaError::Decode("expected 8-bit plane".into())), - } -} - -fn plane_u16(p: Plane) -> Result> { - let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); - match p.into_samples() { - Samples::U16(mut v) => { - if stride == w { - v.truncate(w * h); - return Ok(v); - } - let mut out = Vec::with_capacity(w * h); - for y in 0..h { - let row = y * stride; - out.extend_from_slice(&v[row..row + w]); - } - Ok(out) - } - Samples::U8(_) => Err(MediaError::Decode("expected 16-bit plane".into())), - } -} - -fn resolve_color(vui: ColorTags, container: Option) -> ColorInfo { - let base = container.unwrap_or(ColorInfo::REC709); - let matrix = Matrix::from_code(vui.matrix).unwrap_or(base.matrix); - let transfer = Transfer::from_code(vui.transfer).unwrap_or(base.transfer); - let primaries = primaries_from_code(vui.primaries).unwrap_or(base.primaries); - let range = if vui.full_range { Range::Full } else { base.range }; - ColorInfo { matrix, transfer, primaries, range } -} - -fn color_from_isobmff(c: &isobmff::ColorInfo) -> ColorInfo { - match c { - isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => ColorInfo { - matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), - transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), - primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709), - range: if *full_range { Range::Full } else { Range::Limited }, - }, - isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => ColorInfo { - matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709), - transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709), - primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709), - range: Range::Limited, - }, - isobmff::ColorInfo::Icc { .. } => ColorInfo::REC709, - } -} - -fn primaries_from_code(c: u8) -> Option { - match c { - 1 => Some(Primaries::Bt709), - 5 => Some(Primaries::Bt601_625), - 6 => Some(Primaries::Bt601_525), - 9 => Some(Primaries::Bt2020), - 11 | 12 => Some(Primaries::P3D65), - _ => None, - } -} - -fn tick_to_units(t: Tick, timescale: u32) -> i64 { - let v = (i128::from(t.0) * i128::from(timescale)) / i128::from(craft_time::TICKS_PER_SECOND); - i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) -} - -fn estimate_frame_rate(track: &Track) -> FrameRate { - let ts = i128::from(track.timescale); - if ts <= 0 || track.samples.is_empty() { - return FrameRate::FPS_30; - } - let mut durs: Vec = track.samples.iter().map(|s| s.duration).filter(|&d| d > 0).collect(); - if durs.is_empty() { - return FrameRate::FPS_30; - } - durs.sort_unstable(); - let median = durs[durs.len() / 2]; - for r in FrameRate::COMMON { - if ts * i128::from(r.den) == i128::from(median) * i128::from(r.num) { - return r; - } - } - let fps = track.timescale as f64 / f64::from(median); - FrameRate::COMMON - .into_iter() - .map(|r| (r, (fps / r.as_f64() - 1.0).abs())) - .filter(|&(_, off)| off <= 0.005) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(r, _)| r) - .unwrap_or_else(|| FrameRate::new(i64::from(track.timescale), i64::from(median))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn worker_cap_is_bounded() { - let cap = worker_cap(); - assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}"); - } - - #[test] - fn vui_overrides_container_color_and_falls_back_when_unspecified() { - let container = color_from_isobmff(&isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: false }); - assert_eq!(container.primaries, Primaries::Bt2020); - assert_eq!(container.transfer, Transfer::Pq); - assert_eq!(container.matrix, Matrix::Bt2020Ncl); - assert_eq!(container.range, Range::Limited); - - // Unspecified VUI (2) falls back to container color. - let resolved = resolve_color(ColorTags::UNSPECIFIED, Some(container)); - assert_eq!(resolved, container); - - // Explicit VUI overrides container color. - let vui = ColorTags { primaries: 1, transfer: 1, matrix: 1, full_range: true }; - let resolved = resolve_color(vui, Some(container)); - assert_eq!(resolved.primaries, Primaries::Bt709); - assert_eq!(resolved.transfer, Transfer::Bt709); - assert_eq!(resolved.matrix, Matrix::Bt709); - assert_eq!(resolved.range, Range::Full); - } -} diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 5f81239f3..3bcb9b970 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -38,7 +38,7 @@ impl DecodedFrame { } /// An opened movie/audio source, routed through `craft-media-source` for migrated formats -/// (currently software MP4/H.264) and `filmcraft-media` for remaining formats. +/// (ISO-BMFF and Matroska/WebM with supported codecs) and `filmcraft-media` for remaining formats. #[derive(Clone)] pub(crate) enum MediaSource { Craft(craft_media_source::SharedSource), @@ -74,7 +74,7 @@ impl MediaSource { /// Open an in-memory movie/audio source, trying migrated `craft-media-source` routes first. pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Result { - if let Some(res) = crate::mp4_h264::open_bytes(name, bytes.clone()) { + if let Some(res) = crate::craft_source::open_bytes(name, bytes.clone()) { return res.map(MediaSource::Craft).map_err(MediaError::from); } filmcraft_codecs::open_bytes(name, bytes).map(MediaSource::Film).map_err(MediaError::from) @@ -174,7 +174,7 @@ pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStamp let name = name_of(path); let craft_reader: craft_media_source::SharedBytes = reader.clone(); if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, craft_media_source::HEAD_LEN) - && let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader) + && let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader) { return Some((res.map(MediaSource::Craft).map_err(MediaError::from), stamp)); } @@ -268,7 +268,7 @@ pub(crate) fn probe_source(path: &Path) -> Option> { } let name = name_of(path); let craft_reader: craft_media_source::SharedBytes = reader.clone(); - if let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader) { + if let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader) { return Some(res.map(MediaSource::Craft).map_err(MediaError::from)); } let fc_reader: filmcraft_media::SharedReader = reader; diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 944a88721..9a350223f 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1361,3 +1361,182 @@ fn h264_bframe_route_backward_seek_cancel_color_and_draft() { pool.cancellable(&on, &mut || resumed = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20))); assert_eq!(resumed.map(|i| (i.width, i.height)), Some((320, 180))); } + +fn assert_seek_draft_cancel_parity(p: &Path, expected_size: (u32, u32), expected_color: Option) { + use std::sync::atomic::AtomicBool; + let f = probe(p).expect("probe"); + assert_eq!((f.width, f.height), expected_size); + if let Some(c) = expected_color { + assert_eq!(f.color_profile, Some(c)); + } + + let pool = MediaPool::new(); + let f18 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 18)).expect("frame 18"); + let f13 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 13)).expect("frame 13"); + let f7 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("frame 7"); + let f0 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 0)).expect("frame 0"); + for img in [&f18, &f13, &f7, &f0] { + assert_eq!((img.width, img.height), expected_size); + } + let fresh_f7 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("fresh frame 7"); + assert!(psnr(&f7, &fresh_f7) > 55.0, "backward seek frame 7 must match fresh decode"); + + let (dw, dh) = (expected_size.0 / 2, expected_size.1 / 2); + let draft = pool.frame_at_size(ItemId(1), &f, t_of(f.frame_rate, 5), dw, dh).expect("draft frame"); + let full = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("full frame"); + assert_eq!((draft.width, draft.height), (dw, dh)); + assert!(psnr(&draft, &effectcraft_raster::resample(&full, dw, dh)) > 40.0, "draft frame matches resampled full frame"); + + let off = Arc::new(AtomicBool::new(true)); + let mut cancelled = Some(Arc::clone(&f0)); + pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20))); + assert!(cancelled.is_none(), "cancelled read must not decode"); + let on = Arc::new(AtomicBool::new(false)); + let mut resumed = None; + pool.cancellable(&on, &mut || resumed = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20))); + assert_eq!(resumed.map(|i| (i.width, i.height)), Some(expected_size)); +} + +#[test] +fn hevc_bframe_route_backward_seek_cancel_color_and_draft() { + let Some(p) = try_ffmpeg_fixture( + "hevc_bframes_bt709.mp4", + &[ + "-f", + "lavfi", + "-i", + "testsrc2=size=320x180:rate=24:duration=1", + "-c:v", + "libx265", + "-preset", + "fast", + "-x265-params", + "keyint=12:bframes=2:log-level=error", + "-pix_fmt", + "yuv420p", + "-colorspace", + "bt709", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", + "-color_range", + "tv", + ], + ) else { + return; + }; + assert_seek_draft_cancel_parity(&p, (320, 180), Some(effectcraft_project::ColorSpace::Rec709)); +} + +#[test] +fn vp9_webm_route_backward_seek_cancel_and_draft() { + let Some(p) = vp9_webm() else { return }; + assert_seek_draft_cancel_parity(&p, (640, 360), None); +} + +#[test] +fn draft_and_full_quality_cache_do_not_bleed() { + if h264_encoder() != Some("libx264") { + return; + } + let Some(p) = try_ffmpeg_fixture( + "h264_draft_full_cache.mp4", + &["-f", "lavfi", "-i", "testsrc2=size=320x180:rate=24:duration=1", "-c:v", "libx264", "-preset", "fast", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"], + ) else { + return; + }; + let f = probe(&p).expect("probe"); + let pool = MediaPool::new(); + let t = t_of(f.frame_rate, 7); + // Request draft at `t` first, then full quality at the exact same `t` and a neighbour in the same GOP. + let draft = pool.frame_at_size(ItemId(1), &f, t, 160, 90).expect("draft frame"); + assert_eq!((draft.width, draft.height), (160, 90)); + let full = pool.frame_at(&f, t).expect("full frame after draft"); + let full_next = pool.frame_at(&f, t_of(f.frame_rate, 8)).expect("full neighbour after draft"); + let fresh = MediaPool::new().frame_at(&f, t).expect("fresh full frame"); + let fresh_next = MediaPool::new().frame_at(&f, t_of(f.frame_rate, 8)).expect("fresh full neighbour"); + assert!(psnr(&full, &fresh) > 55.0, "full frame after draft must match fresh full decode"); + assert!(psnr(&full_next, &fresh_next) > 55.0, "full GOP neighbour after draft must not reuse draft references"); +} + +#[test] +fn rotated_mp4_matches_reference_orientation() { + if h264_encoder() != Some("libx264") { + return; + } + let Some(p) = try_ffmpeg_fixture( + "h264_rotate_90.mp4", + &["-f", "lavfi", "-i", "testsrc2=size=320x180:rate=24:duration=0.5", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-metadata:s:v:0", "rotate=90"], + ) else { + return; + }; + let f = probe(&p).expect("probe rotated mp4"); + assert_eq!((f.width, f.height), (180, 320), "90-degree rotated mp4 swaps width and height"); + let pool = MediaPool::new(); + let img = pool.frame_at(&f, Tick::ZERO).expect("rotated frame"); + assert_eq!((img.width, img.height), (180, 320)); + assert!(psnr(&img, &reference_frame(&p, 0)) > 35.0, "rotated frame pixels match ffmpeg auto-rotated reference"); +} + +#[test] +fn webm_alpha_falls_back_to_filmcraft_preserving_alpha() { + let Some(p) = try_ffmpeg_fixture( + "vp9_alpha_fallback.webm", + &["-f", "lavfi", "-i", "format=rgba,geq=r='255':g='0':b='0':a='255*X/W':s=128x64:r=24", "-t", "0.25", "-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p"], + ) else { + return; + }; + let f = probe(&p).expect("probe webm alpha"); + assert_eq!(f.alpha, AlphaMode::Straight, "WebM alpha_mode=1 must preserve Straight alpha"); + let pool = MediaPool::new(); + let img = pool.frame_at(&f, Tick::ZERO).expect("webm alpha frame"); + assert!(img.data[0][3] < 0.05 && img.data[127][3] > 0.95, "alpha ramp preserved via fallback"); +} + +#[test] +fn filmcraft_fallback_handles_mjpeg_mov() { + let Some(p) = try_ffmpeg_fixture("mjpeg_fallback.mov", &["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=24:duration=0.25", "-c:v", "mjpeg", "-q:v", "3"]) + else { + return; + }; + let f = probe(&p).expect("probe mjpeg fallback"); + assert_eq!((f.width, f.height), (160, 120)); + let pool = MediaPool::new(); + let img = pool.frame_at(&f, Tick::ZERO).expect("mjpeg fallback frame"); + assert_eq!((img.width, img.height), (160, 120)); +} + +#[test] +fn matroska_opus_audio_timing_and_seek() { + let Some(p) = try_ffmpeg_fixture( + "vp9_opus_timing.webm", + &[ + "-f", + "lavfi", + "-i", + "testsrc2=size=160x120:rate=24:duration=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=1", + "-c:v", + "libvpx-vp9", + "-c:a", + "libopus", + ], + ) else { + return; + }; + let f = probe(&p).expect("probe webm with opus"); + assert!(f.has_audio, "opus audio stream detected"); + let pool = MediaPool::new(); + let start_audio = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000); + assert_eq!(start_audio.len(), 9600); + let rms_start = (start_audio.iter().map(|v| v * v).sum::() / start_audio.len() as f32).sqrt(); + assert!((rms_start - 0.0625).abs() < 0.02, "opus audio at t=0 rms {rms_start}"); + let seek_audio = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000); + assert_eq!(seek_audio.len(), 9600); + let rms_seek = (seek_audio.iter().map(|v| v * v).sum::() / seek_audio.len() as f32).sqrt(); + assert!((rms_seek - 0.0625).abs() < 0.02, "opus audio after seek rms {rms_seek}"); +} From 799c687031010a52b870272f167f24bf0373b6dd Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:27:51 +0100 Subject: [PATCH 322/324] fix(media): probe coded ProRes alpha for import defaults --- crates/media/src/craft_source.rs | 15 ++++++++++++++- crates/media/tests/it/footage.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 24e88cc30..085329242 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -29,6 +29,9 @@ const MAX_CACHED_FRAMES: usize = 32; /// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`. const AUDIO_LOOKAHEAD: usize = 8; +/// Complete first-sample read cap for the ProRes alpha probe; larger samples use the legacy route. +const MAX_PRORES_ALPHA_SAMPLE_BYTES: u32 = 32 * 1024 * 1024; + fn worker_cap() -> usize { std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) } @@ -229,7 +232,17 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> std::mem::swap(&mut width, &mut height); par = (par.1, par.0); } - let has_alpha = video_track.video().is_some_and(|v| v.depth == 32); + let has_alpha = if video_params.codec == CodecId::ProRes { + // The coded alpha plane is authoritative for ProRes, not the MOV sample-entry depth. + let sample = video_track.samples.first()?; + if sample.size > MAX_PRORES_ALPHA_SAMPLE_BYTES { + return None; + } + let packet = file.read_sample(&*source, video_idx, 0).ok()?; + craft_video::prores::probe(&packet).ok()?.alpha != craft_video::prores::AlphaType::None + } else { + video_track.video().is_some_and(|v| v.depth == 32) + }; let frame_rate = estimate_isobmff_frame_rate(video_track); let duration = Tick::from_units(i64::try_from(video_track.duration).unwrap_or(i64::MAX), i64::from(video_track.timescale)); let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0); diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 9a350223f..937bab8dc 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -437,6 +437,8 @@ fn rotated_mp4_imports_upright() { #[test] fn prores_4444_with_alpha() { + use craft_media::isobmff::{self, Brand, Mp4Writer, TrackConfig, TrackKind, WriteSample, WriterOptions}; + let Some(p) = prores_mov() else { return }; let f = probe(&p).expect("probe"); assert_eq!(f.kind, FootageKind::Video); @@ -459,6 +461,35 @@ fn prores_4444_with_alpha() { let mut g = f.clone(); g.alpha = AlphaMode::Ignore; assert!(pool.frame_at(&g, Tick::ZERO).expect("frame").data.iter().all(|p| p[3] == 1.0)); + + // Older ProRes writers can signal depth 24 yet carry a coded alpha plane. + let input = std::fs::read(&p).unwrap(); + let source = isobmff::open(input.as_slice()).unwrap(); + let (track_id, track) = source.tracks.iter().enumerate().find(|(_, t)| t.kind == TrackKind::Video).unwrap(); + assert_eq!(track.entries.len(), 1); + let packet = source.read_sample(input.as_slice(), track_id, 0).unwrap(); + let mut entry = track.entries[0].clone(); + entry.video.as_mut().unwrap().depth = 24; + + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let output_track = writer.add_track(TrackConfig::new(entry, track.timescale)).unwrap(); + let sample = WriteSample { data: &packet, duration: track.samples[0].duration, composition_offset: 0, is_sync: true }; + writer.write_sample(output_track, sample).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + + let remux = isobmff::open(bytes.as_slice()).unwrap(); + assert_eq!(remux.tracks[0].video().unwrap().depth, 24); + let remux_packet = remux.read_sample(bytes.as_slice(), 0, 0).unwrap(); + assert_ne!(craft_video::prores::probe(&remux_packet).unwrap().alpha, craft_video::prores::AlphaType::None); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("prores4444_depth24.mov"); + std::fs::write(&path, bytes).unwrap(); + let remuxed = probe(&path).expect("probe depth-24 ProRes"); + assert_eq!(remuxed.codec, "ProRes", "depth-24 fixture must exercise the shared reader, not legacy fallback"); + assert_eq!(remuxed.alpha, AlphaMode::Straight, "coded ProRes alpha overrides the sample-entry depth"); + let img = pool.frame_at(&remuxed, Tick::ZERO).expect("decode depth-24 ProRes frame"); + assert!(img.data[0][3] < 0.02 && img.data[img.width as usize - 1][3] > 0.97); } #[test] From 9a74bb992c2761f3d1a9b8a46a9602e00a99783a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:40:23 +0100 Subject: [PATCH 323/324] test(media): make ProRes alpha parity coverage unconditional --- crates/media/tests/it/footage.rs | 68 ++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 937bab8dc..e8af44e46 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1,7 +1,7 @@ //! Footage import against ffmpeg as an external oracle. //! -//! Fixtures are generated with ffmpeg into `target/fixtures/media` (never committed); every test -//! skips (passes with a note) when ffmpeg is not installed. Decoded frames are compared with +//! Oracle fixtures are generated with ffmpeg into `target/fixtures/media` (never committed); +//! tests using them skip when ffmpeg is not installed. Decoded frames are compared with //! frames ffmpeg extracts to PNG (PSNR, premultiplied RGBA). use std::path::{Path, PathBuf}; @@ -437,8 +437,6 @@ fn rotated_mp4_imports_upright() { #[test] fn prores_4444_with_alpha() { - use craft_media::isobmff::{self, Brand, Mp4Writer, TrackConfig, TrackKind, WriteSample, WriterOptions}; - let Some(p) = prores_mov() else { return }; let f = probe(&p).expect("probe"); assert_eq!(f.kind, FootageKind::Video); @@ -461,35 +459,47 @@ fn prores_4444_with_alpha() { let mut g = f.clone(); g.alpha = AlphaMode::Ignore; assert!(pool.frame_at(&g, Tick::ZERO).expect("frame").data.iter().all(|p| p[3] == 1.0)); +} - // Older ProRes writers can signal depth 24 yet carry a coded alpha plane. - let input = std::fs::read(&p).unwrap(); - let source = isobmff::open(input.as_slice()).unwrap(); - let (track_id, track) = source.tracks.iter().enumerate().find(|(_, t)| t.kind == TrackKind::Video).unwrap(); - assert_eq!(track.entries.len(), 1); - let packet = source.read_sample(input.as_slice(), track_id, 0).unwrap(); - let mut entry = track.entries[0].clone(); - entry.video.as_mut().unwrap().depth = 24; +/// The alpha mode follows the coded frame, even when a MOV writer signals an inconsistent depth. +#[test] +fn prores_alpha_uses_coded_frame_not_mov_depth() { + use craft_media::isobmff::{self, Brand, FourCc, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; - let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); - let output_track = writer.add_track(TrackConfig::new(entry, track.timescale)).unwrap(); - let sample = WriteSample { data: &packet, duration: track.samples[0].duration, composition_offset: 0, is_sync: true }; - writer.write_sample(output_track, sample).unwrap(); - let bytes = writer.finish().unwrap().into_inner(); + let profile = Profile::P4444; + let mut encoder = Encoder::new(profile, 16, 16); + let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, true).unwrap(); + for row in frame.alpha.as_mut().unwrap().chunks_exact_mut(16) { + row[..8].fill(0); + } + for (depth, mode) in [(24, AlphaMode::Straight), (32, AlphaMode::Ignore)] { + if mode == AlphaMode::Ignore { + frame.alpha = None; + } + let packet = encoder.encode(&frame).unwrap(); + let mut entry = SampleEntry::prores(FourCc(profile.fourcc()), 16, 16); + entry.video.as_mut().unwrap().depth = depth; + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let output_track = writer.add_track(TrackConfig::new(entry, 24)).unwrap(); + writer.write_sample(output_track, WriteSample { data: &packet, duration: 1, composition_offset: 0, is_sync: true }).unwrap(); + let bytes: Arc<[u8]> = writer.finish().unwrap().into_inner().into(); - let remux = isobmff::open(bytes.as_slice()).unwrap(); - assert_eq!(remux.tracks[0].video().unwrap().depth, 24); - let remux_packet = remux.read_sample(bytes.as_slice(), 0, 0).unwrap(); - assert_ne!(craft_video::prores::probe(&remux_packet).unwrap().alpha, craft_video::prores::AlphaType::None); + let mov = isobmff::open(bytes.as_ref()).unwrap(); + assert_eq!(mov.tracks[0].video().unwrap().depth, depth); + let name = format!("prores4444_depth{depth}.mov"); + let footage = probe_bytes(&name, bytes.clone()).expect("probe ProRes 4444"); + assert_eq!(footage.codec, "ProRes", "must exercise the shared reader, not legacy fallback"); + assert_eq!(footage.alpha, mode, "MOV depth {depth}"); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("prores4444_depth24.mov"); - std::fs::write(&path, bytes).unwrap(); - let remuxed = probe(&path).expect("probe depth-24 ProRes"); - assert_eq!(remuxed.codec, "ProRes", "depth-24 fixture must exercise the shared reader, not legacy fallback"); - assert_eq!(remuxed.alpha, AlphaMode::Straight, "coded ProRes alpha overrides the sample-entry depth"); - let img = pool.frame_at(&remuxed, Tick::ZERO).expect("decode depth-24 ProRes frame"); - assert!(img.data[0][3] < 0.02 && img.data[img.width as usize - 1][3] > 0.97); + let pool = MediaPool::new(); + pool.add_bytes(&name, bytes); + let image = pool.frame_at(&footage, Tick::ZERO).expect("decode ProRes 4444"); + assert_eq!((image.width, image.height), (16, 16)); + let left_alpha = if mode == AlphaMode::Straight { 0.0 } else { 1.0 }; + assert!((image.data[0][3] - left_alpha).abs() < 0.02); + assert!(image.data[15][3] > 0.97); + } } #[test] From f2b569469f0688afe6f150f1f318c2955b82622f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:20:31 +0100 Subject: [PATCH 324/324] test(media): use array chunks in ProRes alpha fixture --- crates/media/tests/it/footage.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index e8af44e46..f1aff6406 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -470,7 +470,7 @@ fn prores_alpha_uses_coded_frame_not_mov_depth() { let profile = Profile::P4444; let mut encoder = Encoder::new(profile, 16, 16); let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, true).unwrap(); - for row in frame.alpha.as_mut().unwrap().chunks_exact_mut(16) { + for row in frame.alpha.as_mut().unwrap().as_chunks_mut::<16>().0 { row[..8].fill(0); } for (depth, mode) in [(24, AlphaMode::Straight), (32, AlphaMode::Ignore)] {