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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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/393] 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&lFy1P2UvS<&@*w*2y0- z3QNZ1ZGy1EYqd65*AAWfoS61&^8js?TCJVs%-w#(V`ISrwvZcGm>YY~5#Te=BXTD? zNUS#irU7Vu%We*Pqr-;?vjyNYEjtFzRQ>xYi64HFJ&)}gJ&qFBWG6g#3%*vdI5FoS zxZOHx_KXDB2TfaN)K9Q}4nqY{SoF4-umU;M7_N^}IOC+X&%>IRzM$n|%f_WJi)`dX z9kjo44D53;>vOpqa6x8{$}o&kaOPE&?=!!wrm$}M+hAt@UYS;^#{~Q>@rFSuG*GJ4 z`C8rG<#@-=co&EHqxB915cgpR5r@b^XuxP7R4f!HU#RI7nnasTm(CHT$ojDd54FiI zp79BfJT4LMKI$G&`R`j~`#5|ep3w=3%x-0y?033+GWx{qg zXXcy2poFK4GlGtvmSHF@ei0kRpY(M09JU-TvTa>>VxkT9dGa1l_JEvbh74QQ`V7yK zZt;L7B>Xc-3yTsgYb`;E?-z0kPCn~;W_{EOcup;`z$WeomYVSOAwf@8w_>>>VU~r zV{HUP&ZupesT)z(N41OJX;-Yxyh~(puJ}(wse(&9ynGC`wF8L&cWitAFs-9{zuh9k zUMA$6VjtbrG$z}vzSRvTNLd&Mc1=0|n&+eCTtmUg8&ApwIPUSw(S{kU#706Tq0&{A z4lgRU63d^i_4Cg&PvsQn6?JI7WAC-OA}tWBJ)e6gr+uZj>yHvRcDclH*-IXj2@MGUkp;>2eSf=h0^rng4Qd_ca2=0+4xxa!YN?BD)9G z5IOr7gfUIiR(!k7eTRk9ho;j9tD~-{pPg3``Yxa2$d2_~IvU!4pWy#<%KtB}oFZn= z?afd@--g#-+1gs}pRY=^%n5saxMpGvrP8N~`U(??5T2z=ZRnadr=cNZCw>4^%an2+ zmtp_~7nL#42lZz2#M6d50$Db zm*;QBcfKn+_59Jx=tq?w(95WZlL=wj1qummXsEpIloWL`i@!W)CFbpjGx)P7OUQ44A zOCxhKR(=5t6irmbh6t&Y5-&~9veWnQQg#MEa%D2>2@nRj%hun_*nW~PrvJlaKC!a`CXV(?^vH-ykp zh8fa@Mm(3c(u=7VrPynY$G{!r*`z>0Y0S=F(4y+DXyYe;n~#a|3V1xuo0HH}6(3Wf zky5N_hRyp;ctjWhz9L_XER>I)l5}!{*jqgOu{fwzkwFGR$$N(q6Y|;H8zuZ9y}OIZ zpb%ac|7b4%sGpTkXu&3iZ`X5j@w;xJ`@xfL)H|dx>_umZ|p93r*4k`=EAg z3trnf*3aWxKC`o#zwfxdncxIL@yC_HZq2PsQh!4lzohc<+G|y8FEh|PfD}6#PBl-zTlqPeL#@#|mA|>JVWuS_@ zY1Ys?D&K%yYa++LA$iM@f51-;p1&X7)UxA3mw?b+9)d5rjBXuBDy(v9g_X5}#pN+W zvJ|c9gccRG7NDOv3`{mU9xkkL*1RDY}XEs7T4v3uVFpoXDip>hjg>-FW#?ezQUC3-Ig77s=Ax(^p> z9T(cw?^PehSx`};Sj4cg31e-bUD7)jx=phdO|fV`uueWhwX>OYDjr7Yr*pd;b;m8u z$t}h5z%ga*F@idxd#tSczzIW%G8_=xJywkp0MwyOil8lsf_%%-bpmUgkI3PPkQCxa z@DakHxOa12dwyD}mQ?YzYq%2|;dnwg&APy#cPX!c z1~IzRhzc2|_G5W>Dw_v}VC@6FI@^T({vGkgSS){Uv=n_sTVV-WQ8HX+d;z$w*?#iu zA!WA<#oM}XrM}yRvfKIgTj$$eUg)R$@OoYIH_+=mQN-9N-0|W&<8kB}D2T$bF;Nj0 z`FP|h1`LPjy^ILW!*IeB!Z10caPdC7;cb&Q9!P&Ytp9_Vb4<`VA>}+r{e{|NG%`*( z-*kumURBavnFkazK|5}r;p_2cu13ZAdi|@qX_@XJr{X2!eZ!%E&VkC78H7(`NBw;7 zPzJ{Ir;_prj?7|6@Tz+v00_O+4s^t+dyMIVD!3}^Y&S;T!pbY%$qJh|=t z-jUOp0XOGzRJs9KppT{B=Eb_zl2*>`e|YDtD&b0adZGS&3uVL4Zd53x4UUB6ylSH+xRWk`$bb;gn}KM9?MKu}CJR8pIUsxD{#DE{J21T!2bt zOI@K-HZklrx;>?0NHK};h8d7TAWuc_DYHyvLcl2#>FrkpR-sJu3z3oTNb6{XrNA0s z$*uKN*9b0Q`b~NpP_a`)_{qwk?=Ck2duE_I;IX?od_@Gkhg^p@N6THx=MkEEfMcZj zhk~DDnE&z^;5uS_0g#x;n5XA?&cjj5+JnU{S*3}?^=VfTPSP;BdVupjpc6hg#4P~p zd0|J`YzSL%O^{|H4wQNoB7q57<4MI%Kn$#fS#>rL016=d zn_+qaO!(N>UMk-MKwSo3e;5`5YUKQJ=fe&;%vE~&wL?EppKBhKV+_Ly{`x44h>Ruv zn~mRFD^%O$LYcaod$aS7Tkt(S%Ubwz8kd7ZL4_GB0vc4GJ)RK+IB9iFCg+OX*bi7A z*(>6%r$dw?Jo{B72^xr>c!VY3U*VwSl*a#C$J3PB+ zNw)#|mpC6j_3M#Fyg5j^1(Hs9{0KPym5=;kkzn*68n@K%7Nx)0j0#ZZUh8HgmaT1G zWP;DTbspBVb)?IDQnN^dM4|vR#R|KG$%uO1p3U;-9gPv%7#($$OQCodJMYRT%2gy$ zLs$f1rJEW3gRy!KK5QuHCST9IvC}Lt!0i%la@24-8PyC}mT4_U?fuX>212IF#8cV& zchmjq^z(unSbw9q)s8OLZvODg3@@8@f4lJgV}n`e?@i*K`v9v+AQ4=9erpd8{tCXl zm@q7HeWsrb?D@RGkl_s9y^GOLZB{!uBT3eQd< z5;chkZ5qeiC)_L)v7RUp@O6))m}t4+#0(+KuqMP%WV4!NjN9Kd+53y1_vi2^95h9d7Myax0&W`M^PY6O!qu-92XP z(E2oTh=oH>`&HI`js~OBuE69E;M2T!#Rho+1-OvJR^9%_m~pO*GpDw#30G{w+|kIxQ2?wUM&W7W}G+r_TYq zo+!G!)4z(CDq4M6OwFh+kFIR?|2|+^vhX!1{DQm&yOB=*O|uV!SA99!Y?zxll2Z_+ z-NwA18_}rOeJlYGjlqJ|!jmQCCu>3Z^sRv6WiFsiv<_gG zTQ$~!`c5!C5!nZ>#Q&D7`d@uP|0DwdXvM1^Pb!{uljI#H@J>91MVr4uP{?&Gzy}zjnnI>{AG)*+GePUoCdaXZHOG zlXAZ>57Gc?0x%V&y}hoQlsGrGT&DUL;l;&T`_0iRC(9=f{VBz$h|%2_=DH;wLzMk7 zQ1L}#$`$9{b6g9gmZ@YCoXO#8o3i1%Kcc4=6pa#J0?@h)8=*;&ld<<(q#UFw@zD$@J9qCA5L&ad&qWBsnZ%Vw*`3J3WmKB| zP|JTG8wYF=cyzu%^si?FzH>7GD7-VVO1GwJH-Bbx&*mfg9cpV%x!=N7I964) z-3*SwDoiq`Nd%u!KqDv7bC#Sl#jOhi$ zJ8K=jQR@cxRRzQHRk$G#Y*b20PWgC`PL!wXbaF7CK5KWBwqPyML<%aDa8#@Eb0%Vz zWyX$=O`cioWtcnzdgNF!(PX)^x& zu3p9R!ut#MUXfZMk)DYdLfu*q?Z4zwxZqVi>~wQj=Cp|akm9-sNP15Q(~R>d-|y0@ z+s~hRUFz=x6km*U-Dfk&vkq>~xki2kG~-7`7DvKn$v7qu4|+s)Ox`ff5Fx)BNXt9+ zlnBXQH~&@2{U2UKFx&|N4H~rp($h?va9;rRA>yk&;_8+lBGUOBULNxaB8nL@>7J84 zlzsYMmCVIAmK;B$O0&4e{iv2Z*QalW+lrrPWG=23(-6Vle$i>qv*|xKtVzd!U?-6P ze&W}!^)_A@s2tLqzkfX&AgDi_T`HVsu>&BLaD>MgD8#P$36e{rJJ$l>=YBL>v8aH%jH8i-C~~3nCwXIdJsN6k>-@6G7$+Y zF4MSw9BBn-D9(}rueoh*Z?^0Cn{s3AVILGOe>fW46yt^mq;Ss9ukOUO`J?!u$WT+=ARvNA(bVrHi#$sN z`TNSTrr+FB8lDJur|-JO4iF;8k$JHL2SBQ0ceK-9$>_xVB?9sVY!k}vPn0I33ZVoA zg**m84glZ;Fdzb)V-R2y#O9p!YpuW*YvzI6oNy^}SAL7z4oI{eA`mIlhrwS@#D-52 zXUCd$7r(JQ|7k~`-HTum9YUVJr{g=ixSBv}vzVVax_2^+pZ>V39GJ#|UI0YmMBL>UhI18df@|3BKO&N>)xS3O-kY298IPXor#Y+UhUdFd&|`T%RuDb zo?KSJ>FVh zEjzp(o;$Bby$P@0pIidJLX}!b7+=)W>_`Tqg05q+46NFx@&jOF%^T5$h4CWW6em#ECu2aPdz>p*yP za}U1LK7++!7zwCtO7yw2T`NlMGsks$5OXfNS)q=#m^2Mb`)TS+!o((58eZ=Ytc>I_ zT@a3hFQa=H%?0Lmtq0b%O_s<$GS2^z!x1Mzg02ARuXkkmaMCIuefEy+_P#$Mmb}Os z^wE_O$!$k??Ov%(!up3Lin0f}X60qe1Ph}qbL3=^ zx8JF}5*wUK#=Dwv!?0r)?TQIiQ>;Tz6|;(M`z!xD;IM6t&tYVHF%Ug%bhhN??aM`P zg2fBM#hPNsnF=18^TKKD4RV}m{C#s)u1U7yzCpD%DP+76{pB5Dreg%n(uEH%4IaN_ z?upKn<1qTNwxIC{{1R8)OSCiPg$gHqmaY7AM#(_gx2Xo5g)eRuGn?8ozr3U{#Jv<_ z|E?-sr^sUVqPbHg7r{OHUg+JF_h3N6@u}w(!1qMwVydm~llKm}Gml0bUOs7^u+Hgw z$(7xHuUHfOGc`#Tob=bR9t&Vvj6!I1A|RR`K)AB`I9PeG^xI(NUeyeY{PKf_tCz;b z@D6#m$z3*`b?qV?pg63-oA*bj4tZ9O5P5$@D^G$nCv5rOg)V-GWBfFDxZp>+v|=E)tXqBP zw%`U}#mKfe=bQ3tot6x(!Spnm^NGeWVqzBqoCL^PY3`O_(Pz9pe_osnbtP0J>2}U5 z9X&D8XbDbEv+Z%Ui1A-xMlTvIgr7d+9YaIHezS{4M>Pk#%M$;I^MT%!U zmc$OcwV9QB$Cc;xR>Brw8u)grX8rn{f|9!0hLN7S+FAomiQJi}PG&N#YXzp}RXtA2 z3euTeWJ$fQCQ8XYUu<`;2>U7`35v%&#pBa&Okj`c?!Tc-{KeJ?@e;}cN8XBo#Nw{V z%vM06Ta3=by=9#%yBQVn4HUl+fq5K`=S9xnx0Yv|D{XqA^eTkWTMd5>L~vz|s!Zkr zXRZb>nN#mD(+mJ*`V?6IilwNJBP1OpD;6Q4ce8ZEiGfN*FwGG%qBdP~fBNi&b)#qg9FyN-bP5B!V{@?T~}9sk6)?WZV1ONADO zYN7Rfs-if{rjRp>yl2<>_*kS1|DD{ltUxX_TtXJ7YGW!r>2#lgMu zY&YJUosrIy?`#^KK1Y&Z=S$uzw>bhMMWrLh--Xe<8aaDl$1WU zdHP%Da9jk)+Gyy}4N)Q2Su(IdEV~E*$M5NEqDUbG~N-Ur^{^5UO4v&M(T04LS{BO zbehEA(PtH_n_XvP-cQ7nzvdDwMC;edencEWpPpoA$>3 zRr4X`Tb!lCiB?Qe(-r2-sSyRA`0ER*wrVR)GJu-fqbXGah@_TYHP`IjD4ZkgmC965 zx#V(fU+?DlwkxYI&@l6|eQxx^#o^`IDnBkSejkqdd%R)<`P$un$-|_xvm|`W@y7NsxD#vPyfEfabhKJwOVd9;ZX4K1CLb#z5!= z(63|BSkUBN#SOI&IUqQo<@TGU2!s-&Dz5J2S1xmfVoAY5vv$tb-&PhJ? zcq#Ax*Xzaq(N~S;5s-5yHg+$xMF=(d*1xVc!twL8>V`PLe+V6T;@? z!tanaNU=?X3dYJM+>Z8cYCSmZ(j&J6z?!gO->x$TyhJT_$xob~^wuTxMNsUinz#uz zgbmVesq(o*B1P5V1i7;$Q%B8re%XHrBFg>)u-;u(Grs(TZBsE z|Acbo-9-~;)Z~J*4Vntrh-b9Xm!btM$FMo0$#*ZJ1DS(U%kxs&tItN-N4@XSG&Tme z^4(I+G}4z%nz3LQ&-E%OxhkI>$;H8V<3@9if*6{|X>>f(&3v)1EK^9&O$2*!09)+0 zBu1&9Hb(zs2$&RNJVVS&mFEnkN#V@{2(0M{<<4&GHn7rjbie}91LR#)4Yl$cSYNgI z&fMu&hC+J?R_F%BNrR*C^P|*gt5wi-b`G6etgbezFD4Q)MA@FV$K#$#I0~ZnUA}#b z(;>X!^NJ@$K!)u=kBLG&w-pV63XSm$qS)c7AgU#rd0Fh$jCc1;xq$fS5Ajl9@E-(B zHH;$rfX9#fuw(Wfzyh)Sny6>0=kU~IqSjFW>>hdT4v&6v>l;`mm=|4vG<<%NkbuBx zTy?^mccy#XwJ%MMzD4A7ZkRNS&nu_Bwc02k=IvKzMJrEL0g0qb1C|Q?LtAcU!{;N+ znJ^k)nXu;87p-qwXj&xepDP-#O0YV#k5W%I+n@1tU$HfvZPrv zZ$_j)SuUS_4Dj84S^weGi!ygD=L1pr`Y!oaM0jHVA~@W?qQoDB&&_!s1M3t+*KInO zBOmL_nqaUzbIInL3;anNmch%%W%7cUGwoKj8E^(nYksPK2(YPt|I+uV_5X7J40F*0 z3*!SIFuKqtLY@sEG5E$+nrF8*6Ie%VsGt-C(F+Z(Q`-mMK}`7? zOOeQMIxi)F#+&`}DH=gy94G#B0fRAI{x7Nfz$rcu-$6iSrgA2%g3jn(EaUBG83eLe zMDAgz!AikTg5>~lUmz$f&;5Y8%S~&y_R(H@K%+sy#~cI>1*vFFbA&)Ufu52425xp3 z{EMyBH>k!@=QAqRz?WPX?9(x^n;jeQO@I#)KLV{$g-}5#gvA|aHV(MzDZT<`LkEs% zA$=*<)C6;+@{gUMoRkH8Sgln(ebK9fJVAvYne8#RTQ&hi)gtu-^~B{8MEsKX*8jCb z`6M@}n2NS~O1u_pWAoT(D13SI#A*nz$m5tGGhQC0-RTy48E@Vy79lA>V8=r$X})mZ^#;rGa0-9Wn)z9u@njpz%_`3u<iMBSX5J}y&W zRmmSK1Ofg1+k*}uoSzW|6wuOJ16uJt)Q+N=1htlX`>^Ym{lWT+NY?P;{n#s$vptpm z6Gesx!|Rj5PhQ==@WhJ37f$MoSF^ii7-oi00cSZ5z`KwbKPZY`p{&0Z`wSj$QTyO930BDyH=YI z{tERA@1!MDy7tUsrh{*kcgA_*7@7qPkj6#>n~GZ_0;6ox&H!TqoByPspST+#bSnS8 zKA`)D6W6caR>vRovJ~f8{vNPxP~z&-Yv178>)VRkgMsjg@mabDU{oq{)PUNZw{Y9n z6b#>cV$a`!hs;{RL@M-Q?;a2qJ6}z5*4)LaH%qHd)w;_UE7K}er{p48 zZdBYj*%1C~GC|+}lrjdJu9ly@H^UY@FM0cb#o1&Rwz1aefkx#I8l-5k60o@^hkuO7_2p6@GMysr6X3=3Yn z0wbCCF_~`*p$2*En;yBR(_XIIjY?w<2xfU70YgU@0$WEZIC5lpa&(!0FOFFC8Ym` zCw=&}ZuCekuNlF_7o62WSr;iAD=CInuAWhv4nIp523WE&e&+fF9VAM{P;}m%^N*Gf zx+E+X7?NUiOM@SaNDchl@H!;yMW}YST$H3WltX$2U_9vcxSmYM~GbmYzD|t z?lbalK6}NxW@-#ql0_rsw>!)L&J%oNA^?&gRDQi1U5u<3P26Jm!Wp8Bl_!?b{P`=- z_CFViYhi9)wGt9$)X_4}j@OBSR7-c_0L{ zmJE2*Wn2CFpp18^MJHbn2Ni{dsj|1ovb8jk(2G+Od#B(8v4?q6v7tl9s4)$bf`U-P z9{Rn4JSSk6m!P>qG%Z7F~}qhbQlpa*zDDVs9@`e-y7Et)(a zZn!iyoLc4MJ$6g+NYGEd=Q?7Kbi7qMIraTpU`z#RGj0hAd*7rRY>lKK@uOmzBh z@9j?L!T}LQlSSRbhg;sVNGVaYA^y{W7)ypvMSVV{*><(;d#}!l$PNN>qE)oLYtA;Q zTY$zjh30&zk_16v{jI*7!D!pr8^Z0MUf)*@%Q!DfK76NpVjNI~_mc0t-nIcJ-*9`e zH)1n1T-B{Z{Z`}Jz^wuF0nCpK4-BT%ri>=f>$ldc+0il9wJ3Ao;E-&|Exph$$jek; zxcul`6-Kwm-MZW)rA%P*OHmYj?#R1lIz@eJ+48u2BbFmplt?F4grDl(=JF6iiUn~p z|7l_QH^Yv3vlpp7%bVMXU1Dv2e!#TjjnSJO#l0X*dTiKYg-Sq|&{j2Pb;{`q(^LwU zO7z)Qta~-(ptaMg7qk~!{bogauQof5EsiZtOdN9d9!R*2@*H>oL*ym5QEnlxJ0H0P zA1fhab_i%$1tNGCgy7Wq9Q7l2r;mtuB!b^E@h9B7Z|pl9;0OMUI{P2HLIOa}fG}P) zYJtAa7iQm~!{)=9(al3wn)yUP_XW<^c{4FCuE|~ML&Gf`zTf*joxU_s_MP;LpF6rc z9^9=B;tggG#rH=SLNI6sAc~&Se1ycIa^^$o?IrXLK}R?o7*Ug~DujVBF7zoR1FRZK z3B^zRCIUmnK|q2TWatg}`cPu}Kb2_)%y<|OzCNm8h9fhc2{`K-Ja$*4`)J`-c5mnp zVfLe~+P}gOaDR(q7D*C82^c=0L^iig%rAnoo*IVHqVWd{gzOA2P+eL$jT!Jd^XXX> z*~JvDtgz&3L0Raj5Nd2xx{|;PPxj1#s{Hbp%5ax3V&JtNU9&P0e-@zjQyPj{9jS{%hwOx z+R*RF09c&5<;`5P_3bVAipa)?xflKUrU^R&{wydeuTAE3Ue0Uug59Z(lwb;ptzeSD ztAe%+EvW?3VoOEjoPu)_ZnWMM6CeOq;4O}~4#F=k5P7$=ymnZ%UaJb<+8@o`-}+7t z#xEKC)RUHvni%kO^8Q$L8Ne4bK0E&M90G4|62(~nzDIzX&`wP%z{5h;@BxLZN9ES{ zOY}RBSrGQ_|Jl)Eroc`bAfl(!e;@>he|TAIS(50zWNAQo8VFUI^?PyYX{$M*z5GZD z7&F0H2`BrpT<$JDT;pD%XOu0fa%tc;E4n7!GVUzlzwk8pJf|82ykD%gwC>X}>f> zH?lNUt7uoz?munO$~Vv0SfBbp4-LNX1xsF4e`c-EHxs6LY2FxfKOf&698NTTI#c0% z%LQu2sixZx)`aF48HC?8V-@-Z(Y}Nb%EuVv6RF+~jHfWN*Y~ggU`sZ7HHqV1U5I3Z zQJ$zREMXOGkd}Y)wDL3h8EDfReRn34M~)m%Z^nnv8t(3>=1IKpRH>X93b&}_p4?Nk zGvz3cR)*%z-5`3g%Q?9tY@5vC5UnjcQS@*!U|MkTl1d;0B;t0fat(Rl*u34NVcqhZ zxhGl%YEL2&B`Av{t@WqPEMj;huCsES14QKdULc4Rm4SCC>O%GJB$n?B!?$+!S@Lm( z;Ck8c=0p+GnL+{&0@9H4ky>`5iIR=^0V76s=n?VktY|K2lr1~Av3HDA&EDWkjwa5u z<n8!$`mNZ$C4!5<}ctmlQWTe)NP@sr)#Nhq-D)V#=NLOK;^6KPP% zU<(LZC^N=HGCtS6R%!aMd)6rB9Zggqp!tX7?hCK)Yug>mXRn?3u+&oTkhdI4BRKp| z{}z_|;~O59mfO;w535~p3vPbOp-A^)bOayCu`sw6WYN+wxd>k}vBqbwxFkR3U3sRx zNCclYq?h(`JILj3-rEHrQnR+b<7|E6?zCSctVhlo9NqkG;wVKhwTgKCzsjrl&0i*Q zydp*szqxO)YNa&_@g@**4^>D zZ?D|hS(u1;D+hQ5oQLpxLwue6a>Gss&8sV(N!Z|#?S*Elh>*E(7qwNya!i}Q ziz&%<(e3}R5DA8BkB^Lr1eh z5f_EEUV&cv@;FCq-A}9)v`ma9=%b!3$NZQIBoIU?GdUUL&8D+dc>a3a-?YV8-nVpG=D6{lFwKnuMw8yW!We_Rx9UP( z!HK~-!Lh*_!O;c?+4Qr-G^@?4h*YrXGQAO8ufN+n9XhTg&4-#!Qe)f+0 zi_f=;GUsdWU2npU9k&7atR^ERCr38K`-yuv+bafqX}b#ZT9I$7LemLy6`ksfFmeFA6Tsw5PodPlGwI=Mia{-N-Il%bHQ|m+~f#;ar{kstRZzAu%ySxod zRqhCWdp(wf5vCY+4BWDO^k8>)b-|?uUJ|}cYYzoiU&$SO9XTMBTYRTFp5H-5&|W_A z%eDV z;U6so)4v`)viS`~$TyG>Na20i5UFVxoQ_?LYpgNn zQ+5J!5$v0dUS6M-(}_D)uLVEl3NJrsd9^JXC3vjWeRqX9RC6(}8>mDas_B_R8oSZ8 z^}9Yb04oI97kGc&OYA%r7V@>34LmrF`OhK@|It@@0-Rn?v`6qtv)$9PLuoaO#Y^kw zjpae1gH&nQ2E&k=E0t32gf$6*ZTV$?x`GBT&m{#7NuDH#ZwJ=}9GYpQAYQbwKZJg_ z#@xdc>)^7-^_70zo<|u8oI~$9+sjJW0`&l|GEk2N5U|#`V%GBXmuBbd^DpX=mwaV; z?cA-;NQ_-W_e)Ff7v_%tkEHb|eKZHiaF3(GLqH;OB-nWjF+7|&1&e@Ui4)l$bvUWS zc>c7e>_86jsOhM-R+mnHUu5LM9nGU=q1)V~qnBD4C#@C_hxv3=9nQUx9yv9`(94_? zsCzGkToOw>98OYLq&RiZ57cfYI9@=s>&Q%kIxQ!fh;^+FTblxNTN_?;-p32+h55W@ z3qX8YU|o=Iw@i;P5{QJ#VF5$#r>)7YwXI2wwWwffo7@**1!gpTo$5Pe*dK?HKY~(z zq^iWf?#2^hIHudJvkc%w!(%mLGkL)V$|aRC$3rPr*L${EARy z>~x%0+gm69ks(vx8AtJk_G!11P3;WYwnZ!sM2{K;*X9pe_f!2+PfXzmr50$bQ=qUqv#%9~l00C2HJxs-e=eq0dk03VRVt%ciJak2SGF zl^S#1h|7rE@^cE7!ueUNrXCw<1G8Quydg1xOy`*5A&N@0agdihz8fLMi_sOgV8jlojAYU~E_sh4?iD8f(Z>30 z$-_{q1W68W>&y@@_;y!yJ%JumM@Yy(F)sq;zve*y**F%(u zVs-WWt34eiDjR2Pmx>h>qBWU4?72Zvlhw=ZbHLpZ*XOMMx9}uR44xD7Z1Mno>FvR) ztv4e4pnDe{FzIN{aG0DK?PV>B(9JB-w1`FU6Ij6HAB5dz3{WFWVUbhwH#L0s7lFxt zGR1Bkz3H3MvA*H7vH?_+-WH3t8rOPL(2xeo~wOW z?C#eacjnqh+Rw?!MssN>nO#tl!=Qj&!s?(KW&6e(m&wDj_xaqfwX8g{YKf`-GU~3; z>mp@7ac`dusW=wLb@tif6TZb?HIA9zwB7Q++kXm&{Q3G4_6Md;Be z?%p?s=z+o%u5979-_~~Vy7FCKreh5vufjUvaE#x3vn*y#VP3dmEznOSD%ayeueoX( zxYWR~AT!u^pYvtGG~(XQ#xVL5J`s8oe8bYsJZI@q*5p0VtvRNli|0$>&5&UE0b!}W^dX@OAUBZ7SH1pGM;WoUajdrolAYUnUyHQ-#V6VkPSHAwEWe`uX=0rWC$nouIsG2FwQSlm+(AGx5w)RZ22 zqI~94FRQ(n&O;l0qu5xZ*hp!ELE!Z=1cn83rmLh4qdS6ol#r`wTW>;iAVfaI&pY@4 z35h_6E}R{9fCQ@%6E2Sv@*(s%mZUR@aL7e?JA#S@QV-Mil_w0P3q55k9R$yphp<54 zFgatTDCPlEmy3P zS1b=adu(oTA@U)5^8JAQpoX4SHQ-%Ch}CC8G|r2Nm!<*Ag-v%VyJ1t zWz4vlyRK1F7PHD5e+;d!W$?A3ew81r7WwFe5mYl)=03iPDrF`E3(S}{{7R_*HCI=h zcO*AD^q*JCCc7rqn>B0x8~89p*#OC5WwmF)WEY z=m6x_%W~t`0uEJ1=70`)b7(430jM8ByqN`ovwGXwTp6fW6;lJg>bKf*9J2O&qi0Gg zujlSb+)c;Ml{`I(2Ns`+NxZ>DwL zo&pZ)CcODk(&r+jI1cFG6yX~~UY|8BsWdGq&wZFase5mC^A|bX?-TalkHur}@J~QC zYjjP5(T+0R18w&am-rT8q1cNx3Fa2&7N`{(V44k50r)sH^{AJ?4rvq`hBT6^@=bmc z()0iz?f*;}O_M$#OXtOaD3Qh0 zj_8G7JI|n|Lj}QC3iuHm^%)`KDMQ~VWkbQifaz;2$v}lq@faWOOmUt8H`SlhYzYq?ur0p*vhDUN{K^FQg7` z1mg}Rmd87LOxA4R1iDD@m5v{eG60f^pf^VYz@-T1S~BUS@?hYx45=wJHwhW`h~a~Bk*^>PJDmZ0mU%)E z&0g_8W0flAr-EvsqGwtrxqd=^Z__%IpQTGI_Mfpgi+dP;!!j}<%{1fFt$mgRY! zOjq?q9n=wEqW@`XYG7q{BxkjC1ct4iHdI5Zj@3d3^9+J4Y0X~y_<@~C?4sKWg;y<8IlaPR;KCK(jTvW3-=Dd#Ugka;Xj_N3SG_}oxM@aKnuU(8?JKY zUA#$`@VNk|EW>FIA4kbb!=Bgd-S1lS^#M_;XW)KM{{vttgOiP~0bo-Fk9T2HpDtZt zL;K9&--LV?Zg};i!OQyOh0#ms-g~B)US6}F{#6t| zs2bsr97c}10a&}S|H*=aQM|R2u?(y_fiidYVQt$h^ zRV^q1Mrwz);KzPXm#l!5;uN!^!%Syyl)8nEIkIWo_dZd1!p_~iW$Cc8N@c}wg;-*`uA)^{z;uQ!CBqfU#J*9CnZD5eRF*Fn+ zU^8J&H;_{3bJb^M5V4_UxTtk{8kFA5+%GIIHN7@)y<{hBHJo2IeH{ozw~mZgr}bAg z^gp=rbE_d;&8ypH>u>{|b>>7r+o=oI*{^$^7D`)b@E$5=~S`57^sE*JH46Ut-T*RzTXIj3E@ zo}L+5Jd6G2qTb37JqaUwPz+5jRFcI_F^XsiXWQPD7aA!uib-vQFTtR2{ALr|?W^(e zg$@oa=qjq2Sa~Sa3nDHThl7MNhYUOGh9g~Rv>(B2Xk! zR#kimetnSSaY^fBVlRx?E(umf-w+}E=n(=VQwi+jF^b~18F`5*8a*jr)1ZL(5A}M> z;{)GG!&gqXORwoUyx1#jdG_<|GX@6kJAh8oM+4pc4a^glK`NndZEg4+*qbxGzfy#h zcfuFy>T5l{@k*lZ~P#ZirB@rjjxLAg~bl_3K&_?jO zzo%>c@?e&!nyC>9Px(oukH(W%J0DR<<9x{~vezIOUCJxlY6cD}y;b%7A`vet zspTd>ia-BEmU(Ys%tX(`K$dxHVcZmHJV1!p1=Nk{w6c-@yc@~}9AmV);~z$l(Tj5o zjA?F8JXSW?uA@xbM)QE|gqSYUln3Ss$AFQ9vf>kXG($dYy-s|k>|gi%VN^%fM%wIr zV=buJfMR%T0$0}!K(&ElKrqC%P-l#nFVw&5xzoEtGAg;A>2NE-GzmTNG4BC?RnMor zfAJr7|JWsFr+@%$6*DL=NfJB=uozb5i6^-lNb_h6c%9_c9_N4wr zWuSGVTqA#L!D&lQ`?!(p5=*YpTX_-A$`Q_r;X&a+VFvT=V=D&bn|X~po=i{1_4XWik#(?g)r_>yvq#P$vgj!P^vdOuhPs@{>VZc}@+C+S*=Oc@jDV*}Cjq z0JwOZ*m7Q)0x5LFK4dLsOpSW&6x~7UP2l#Te|PPD*L3_{@L|ihBQI3mot<)D<9YtQ zG0)W>-WTxTPS)k`)KmS9=Qv4SG&ED8nw-0&janb{K(Vi}f(KsX>XJnW!nHl7bT~HdqcMx1Xl0Rvj6Jjy z*lcS!w*hn*4~bACC0qe1Eddk;uizOl4K#ppM8-&x1wtFr3XqQUBqZ`UPb|wyiH16a ze#62cAe#8Hk*7zEiz-Kk}5WyPTrG%yqSRzKiI{-yfM^fVX!aZqLQM<%6 z01C5lP^P}7pC#Cu54=&)r-`2I?CI&%owO1mFczEHIZH4y27Q-@`ge!9rl5lE;3RrA zGT^Ovb_sO_l}OX-<}}=8*(WsLO_S(M0xIYP@tFkeo{lm6NHa0aAt=8Fx6y1JSla5{9ka zj@EjF?>Kd1gN4G2=-Lk;O@~lnbW-p8c(~TYFzzx8-0ex*QS7$W$ z;+oxPTa@Uj02$at@DqwiHp|m=!0nt67J5~f17o~MoT^-~V zE>lkH5h;2Z&isRV@y-$=j$H*O6*6V|;$!$vFoenTI4Lzh0lcC2{EstLunnpY67_tq&XZ20~+(u3C1D1&hWdQ}90KRvS<(y>2%_d6J*5 zv)V>E4&!H+6;O^J@x9B6ns{-%<;Y~rg-FR{@79V(`n);J5!tN0ho!JOLUkK*QaX7U zpiQuF1oOS~7gNgR)dF0z(Dw7U*itN$yP>(aF9uW`IdRyY^xpH~kf}1wI;vU1iKC7P zA*uL}tsxHu)Kk)Kwj$!&g`n#2Bxl71V@grN7%XKkM)AZ!QBe;^BL^|iaXxI4`g}fr zB-3L3QQq#xa8YsaRLi%`H?Q7=ufD$C_dpAhs5}0P{{HJH=YPF{jFAkcXS5M(~p)A=N`Q7TDSu=LFV71FZvT1`W-oeTejZE61$efs4iSQq1&jVT`~gmo3NiqT z2SdRIuZ51qm!94DVNg&qB-57vyh5`78y;3^dU$Gj$XzT|sT5gh0xxnLRvZmtGve10 zNm6`RCOCk=Ov)`1)l(HElS5Tx(Vq4FZl6?|`TNBjbBZ^QKmR3KV-@0!Ek9Jh*k)oj z+NDJ=du84&L@+J0+%YRh<(v^+0EuvH7EaG}EiI`(7UaNrl}Wj7IKR=6I4S#KUa>11 z^1p>BNgYqnB_Xs!d<>U@q&U%sR7g5t?@Cp=NSVtuaGWo(mqYaeEu=nPR(Z^jrcm(7 z{1o9WR*ow~1-Ct4H@wN8ex~LrBaSbNNj1Ts2{TWPASX#kQP+@u25ToVM6knmK(Kg7 z9JnWpn}h-%4@VM90+Sdc1QT#<-5O>M^w(Fq-Kl{c4ig)?F;0G(_}S4WRN>D)Py->3 z+AL)5#r7*3?t@=E*4^wa%jvt@jt|FRfV3m7J^Pc#<}1e(kq#I^{T~7GqGHhDC9{=V ze`H`H=_=-8^xbVzX)oqFLpTiTkbPEIgRT_e9UVFvDqJ8N4qrf=&N!+LtAJ~YBTY%* z9kP+|4g_ZgxjHNsrYasfMslh{u|V3sku`&?6BYnhh9fOWq}628;a?C`2*_*LtyCqI zQ1eg@C_Duo)<~5B>4Yg5%gTj}hmvDSCcya+2h53;VE8dzmmDI(j7KH}Ps2CyznpwH zDf)1%N~sg{5`bjdZ6Y`F^s>4pmny2R12`Mn#$(sbWB1hd)ArBLbhWYd^`qXBw^mm_ zyWZ;COhUo}M;LKFS-iF}i#U@=9erw?ddM9kYXwP6{4!&bR*bd8@Hi^$<6Hw+%rKld3NZdpu4^0@Cihq#%AhC7w4EA)F2; zj`+$;ifvpB0>YE+GwzN3Ta8_t<;@$|Qe%W;aeVO~o!=izh>vwJ?@7BFGn()<(839> z_U}NlQt3UhG!{!6s%~Q&<-D@8*kv~}w?5gA%6swdo-`JtDqSTy_-I!B{wUtFYa^PS z5Vf0iPwW*OYu{BoEkzPvoT+}f*p?jIFpj#?lYVvJX4ntph zX%Jksk%*4uDeTOcx~Y+=>eyvKg>^Xp;-@fVxD1B8FvZd;>EmPit@P~hhrU5cS0=Ox z?^noEB{#g~rgF4DTM`kk@bH1UN`{%L`gqJ2vbD&YEvI$#2{Xwxcyly$n~K$+JsjJ$ z2?sgw1AEDE0W^;Mgujt)juq8U%yiFv&;N*7yh#pVuQ z#^>faqmd>&KWOWj`o#e@OUc8xJ|^toOgU(Tu#O$+Sf1zol#75jM6B1hA7KM-?_!{b zVKe!(32(a|%vc*!Ut*$}9}^o5Ds?s3Nk0#Y+HHS+@A6#h%b4<)1|@XgAB+X9Byex? z9htay|6`ok9qVn%idoK|+cLGtowmz`@2)LVpAD@1+KNaePW`@ruTuN{n8*10sq}ZV z>OTx;0S9WPuT)&{E?Ych(sqq$>FSo{*zDrRsh;_~CKu&fvj7FW#hRk-lXBY$I(i^E&eyE|e`Kjf}wl(1i1v(4EF})b&Br=68Kf z>NL7$rN!qorD>$|PPhIqGosMHE(s`$-g`HRO}W3PvFod6$`d2!&)FRL1Pj6YP-P)C zq+E-nyrzkF_M#ZN4x#Si!a0LZ7rg=p9&&ah1l|CX45h@!gBv$9P)SgPA|w&O2DIkE z`VPK!<(M&W4FCjNfI7`bGbjMXHa@K|U2GIZv*sbYZeX(!mA&2#dcXT9ups~){Xhe- z64(wU2?_Cs!(nuxc#Sy5l2D0b;5jQaXm~T||B;fFpQ#uAFI3(-ioaIHkZ7Y^0H&%@ z!#P%obury}Q%jQyp_sG>g#ynWVGLuUW_>W*OaZ0}BF0Aka93(u;n}{1Q&I4oPNb;Rd2UnGackfA}ADNRU4lBE2hR=AomxRK1Xx zww1W8d*{hYqK95n-6tdiu%PrH>O5LDY`LZpE7aqBK#)#1UD}GjQWWFfkw?S}bL~jA z)hH)MvM?4BtZf3ebEq@yUy5QW1$fP1ALNr3=S0A2YvhLXi1{fs>xaZm;^7i3SZ+RI z;)w=KLP|H|23h9v_!n;=#&fdP5>SIKD7OYfts}Vu7ljGJ!!ul?+ym0m-pK@AH=W7uwM>HL0s!!=^qkh7&`m|T%BiYs4G@>m{6HhF*9>x z)nY*RD$d-(p?wcF<9JpdO@#8GU(b%cIPDs1BrdZx!5-@^u0z5dg40xaSul<^F+}u9 z=sXh{J&7D)Q|e2JE#;>qijp$UB#%SX!{kG5d;2WG;VBXl#58A*0e{12r)KL}PM&@} zKQR!+4wDVL9U&Fr6Cx4fWm2eftxNCB$a-n`nilAnr_})53EgyB?c;{>Pg|nH=0E8j z{^?yHL^>d`BZkG5{$30_Y}z-sq1>er(*yfc%Kb)^#qbBWFW~|(-Dhg4p@GEVcsRPx z_8e5VHWtLxfP?gOLeskpAUzD!JN>o*{jnt#Is3HPMa0gR}PHFqe)8Y{N z{d4#3Df}#F!PIwsdKTRMzhe^ScCa=wfE+?&@r8zHDt=18JHKKXB(A!P`}gx#edKq(!U-?5TvOjIyW9&6|3$8$ z?aQAnM)!hmH~Ak$%1Y7J1ecD@1DM4aVDL>e=qf~%H^O#kOQ#B^&ieSYo?2G6dpvp! zv+yxzWvW#DVlOG|_0_B6?T3PScdinTx^K?BDG$4`=IC358O@!@sepO z8Lw5*tybd4mU=!^2#)si_=#akJNNrb#=px|`bhX{el^Kss{!TwqWX!8-RRtK3@3pl zen{%E&RYxft?q)KY?BzRUt?!CtDS7SfYD(sF3H{4%tOG!qzPyCY-6EE)RC+*%^10l zHW)e{!4!~a2w`8=_Rnb3h6Ivh5bP0^z+Dj0!QgculuX8NC&7Qp#7=<|6Q@pVV(n~d zx`eBI;IZ4$NxC9xX56*Jd-fg|tVJ=|ay2xnV{9Pn3_i_QlMhQp`Z5rmQ*kJpk+4qr zh@CV}MdamCV=%~-*0xsDvTe2K@uRHyd$BJlxZkO$&@4edW5i6n@s*?0HOHr~zt}(R zAA-e1$8hlY7#GKs`Oik5uWm;*0HaU#BPFB$M=NI3U)PPDyw@va8SdN{;6VOjR43=k zwF}gwfcHmv%J|K96r~*pv1fgy`h7gF3NQ8^AlPkvGu7YvzaR1qyy9HVSBfefn?sFd zDcF5FKLi8C3CtKnM4>q;MC}JlPP+(AJ4|wzoV(1KMkEl@jTfJslbn~Pbv`#EyJ;hWpVTQzTN zm5UOc;~Qb2+>pLC@x(Vr6iEAelHc;OMavuJg;pAdX-G3Ma0*hqZj^LBR)jncABCxg zQY5`r19KZ6v~&$X__`}KF3TL_xq4i;Cn5glhQELNkyZH@yt==UOZ)yQx6uDHNp)A` zEGu98*FNknO-8L8K?$y0pI5#+R=q*YbA0J#&E}HxXIO){H`~amkr$+dSU7hS+h0Nj z`532)!ee-0^MiPeuCia&ID{uDu>8-9*buq45L&042%wj?*x>dLXuoOg~IY>$WtH_3bOOZ;cR>ZsJ` zhR>2g#>O#jkj>lipR0e@qPNS!)dWU~=&td-pzs&tvvk+V>bzLGZ{->Epb}4Px^8{q zDnnCYaD07RcpY#oNZuQNSn%YJOTvGZ3b9^CaN2!&;wjna}0 z$Dq|H{}0cf%K8vY9PXq}J;^X6!q6dXQe$m6KwIIpp7_>1ZNfnQ%be28?7#$P=rHFl z840AvUnt1PXI;&SF1WG}6Zv(6tv z%&}H;K56~V+OuilhQDT|Xo)xzg9@n28+qV+vaa2|DF9ql+{Zq-%(Iis+jK>zeYXTn;*od>{ZGBxvvr(6|5wPB+?vgk~ER zjlh$;0;PlCxo8!D5>NkloO`y6JkZEJY!3B~q6d_Xh69HeUJ{B%JYzTrZH>8)E}=d6 zyZnQE??}>9(h>Um%1NSuN~pmd%yIj66siX0(XeeWiaPVfBXyr_Ttcy18~U%qbufdD zb>E>RM&-={LChI_qsrkS=eYIF1|Ce2xdMDwnpM_wG(p9;jZQB>{c*goX-g(GD_rD? z(4-vnwJ(3=LbK>e#ck^QVF|?c;@P;oApkYoErWedaB6-$i7w(se@9 zZ-aEqK$VhAd*?O#a{I3GZrw2sUDlj1-A5(T76I>;GP6uHSaQNtQc`3z(;_mAsRRk` zNF@3wzvSm77xqy;@X)*cX}Uh&Y{nA7*k~tPVuWa>yW)Dxnoxs|k>8a02{&2?*IDrc~22Akerc(;VohEu?_pUDXVM;<&lz=C>2Ee*!6gLe+iwDzwH zP$1*wrbW7JfYM*i7tj|F-Ip0~B$8QzJ`tF_tnZWs`}-UFLZKwIzW$PO7|=0@oqus^ z^fUI$4B6;U1e6$wC+CafiA9S^i`K}4*Hk}P;!0os3c7x`>+E9mH*s-)^0e{WrLqv)*)$<~rbI>>ru%Rc;pFgzJL>I}%FH{%%eLs4dO2@0 zZ`tbepp{QG-La@kmYd0T{ZS%~=ncV5me*;L@qfOf{*M(Q|K$%l3L=Es- z8|#iH0h}?VB<#jWgG0g)sX;sDz$wo=WCAE`2krdv3lKAbF#1sk;ub%ek=$3B!M=sO zr$t#GKWld)pvUJMjNm-C%n(o{!U|bAWbrm%N;A^DxsxG=_lvUwdlf{}k4+-uMrYTg z9zVa!(VV+#Erq69m6rN%IeQ)LsY`ATh@I?g=**uv?k07zt>KN$^eZ<`1V5Pt8hVOU zg{R0$5P{r0XJC5;m&|x&*J72`*|#r7ZOSiLYR2xk!0*k)zNZ1G{64RPegs&-9K44H zGQIcS12Un~DrbxJT`UyFUYu`d`0%G5rfg+cr&&QraizNw7N#xD3^NL)ZN!6#gHquD zIgA~U8-G+R2kV`B=^6)tQAJ7pKX-yrfVP-4UZaI)qBRZadde_n9f_4ls>Uou)G z?aLrwL`4srv;2KfD`?a_+WHhly$b4l$7iUc(I_;IeU9B;9P+E_=|2fbqD7;QcX;Sl z@-BIZEsM>q)C8`?Jk#p7pEN$-NPvH#Vyx$pii-45LTf_-LYD(efhGU8w2GgnD@=Ku z!jkit)@v1p*RNi6a>Nb1tri)s7SV1@dC<<2&Kwcc%c_sf=pFh8SX1MZ_z_X*?ZF4@ zG!Iq>gFy#_$}{fM18ejQBSBF}-iwbB*C9_w3!4u{wy;y_ae|_NH>#jcGM)d#gv8G|AhvU zKIwPHGM4Gb?Kf@u?cYAPEa@g@aw2^&=6L>I{J{SeZqshe3ecOPET~|c9;55ZBKY#% z!Ms&jV|OPKursIVyS#ykg5>%DsEez)i^6-8Y}t%w3)DbuA6tJdOHyPD&f*s-^=qHa~Z z#VLVOB$GB~K2}P2g@q~LNk?luN|bu{rql)6wL02Syp8Goepw;^s#zF2D*-OnI!pJptP1Hq zYOFxdy4qxtBqQ}88FR!rK}seD+Ex6|^o9(;3^NStB$hCq!M^}%`cpm=dMecV;Z9*k z$JMK*nwP}3+XhipQ#JH%OchW`TCgZ?;T3;z#`t_~yE{+H)?*UVLkN@QI+*ckl{+XY zo+6^N_=0FkVhC{2AWV>KGcN35Up^%e(} zAc__F*#~+LN^jo?=s280EqBykbY}2L%N~Pi;9~PDz*evt*s8H#uIg^52nRT01l&mV znEk$k(YZhKEd0%5r64{_iS;I=+jb__an@fBlQabB<5|+`HClC@ zK7`JZ<-{poF*@N}${i)?Wm%sjn}_FHgCh_2+14G>cgPqwvI~~Ieu97WNmZAy0-D^I zU&3}60ao&9rm4o!1xAg5?Dx(cy7TN~$?;|omp$HeCjhiS{+7avePE-nhwZ(KxhL2| z++S<_cZ0O?T~pHZm|tN_@1+vQ-flV#ciSQV8Ea`?wEmsQ?P-zQ?}P_-FiY3o#1_nw zP1pbU@BB^qv)PbKGGn-TCM+ z_kR2SmzqagT+Oa|%`y$5HM{NSY1LoFx}QVxg5eTKei8%lCsfj{MWOO5Sf ze0`$hQMZ@k>luI`7{+vj)sGH)RS=Kn>Bg~_%PVNn_$n86Q~5bY_UI9G9mhHPs|DbL zdhZ-PvY;osCUfIRM|Id|18kpzxVW8%QfV@`lqajhzT~BDv3)RCeYlTAi=fi@$<^OI zQ913+#NSDKC4kfzJ=Jsl>U)8>tSGVI4zbT|n<(6Krco0l5L#5E=E2X8Rg8yCG~_yS zFSu*ob~B0pS$tx8Z}=ziNx(a>Xs6SlU7KT=n2nj&XL28OoLO;y=b}YgZzFsRJO7#> z_%6~j?6jt`xs$_BT<(E#BKtUWP0=s(BfE!e4MPCZ@Av7Rorhcx_!jb=GFw44w%YWe zrrgE0NgHCAxNdxWKqco3^{NlVHgtS^cA}LJBM2|VBTEybXC6MvZi;;NVpk8fzeVoU zjqM)X9q$*C)qWQm`fm=IF5h-C&VBO5WUE?i`why&yh?x56ftx|S6nf|+{FB9Q-ND1 zz!Xv8sPizYH9d=v=R0lUm0p^iLu3-lrx;<3b&ixu>SH8l>ngUC;W6K$Sh6oX%qq?8 zChs7N44uu5QOaCLb!Y%(RrSr&HpYGX#jnVsJ?fP4Mk%* zxQ!BX>hPdZ_h@^v;XEq|$3PIt5j5pgBwffV^7P4{N{6LRAe=~N=!j&S@wA#*!!9v< zb8ezUjRhiyvmDwG;mtw>l?U&G@&xBO^_z1_)_~h(8(G!XvjV}Pm9)rE*byNxiB_{$eqc?pnTIMtQX#u<6MhB*-wBNSmU-OU1 z%>Ujs(Ha=Sw5ZC9i6x_)n`#C;ivKkT+q!HE^gT~ply zQ=4MS@2eg8U?KPmIhb7K6@-WUbU$eHk@cYc*_;ccGMI|$oxT>!bg~OC^tKxQErzmxi786TEslch?#V*&)2i)+3}GB zwjMj}C&KmbIZuDC7qP|&5$}W}zJ_(uVV}`#{rN&!us=B=!hXf`@7clbO#O z3JN@mnmk%Hs?PIpBYi1ENSisM@#%xvn3?^D-hBwYbtQJ~LF`(}{YNYnSC&yu8)7}D zHy^My@jlt#usa+&;q7kS<8$?JG@7D>zGu7JM0xhtIO6|nlBXYkv62tgqLd`Z>e}iC zP1+PX9;rUj_O?H6rK*jXB9i{a#VfA{*5#JuB3s~sUt)BZ5BbC+gzn#iR$d&RI8Oxc zSiVi|Ue$heFsSXGaEMbf2dY1X`n+@))vNxP+f6Ih3Xz-5wkB3oNw>u+8BG>W3XMPS zb)xDRL0wWzV|kr>Oh4@&&Ar$P4qJJlkqry?JeAJ$42@G9Qw}rtZ&g)Zm`uCb-qdZI z^CaGswY%x9ZI0rMsZe+8+rk`4@w9leF$>BrXWC9E72F5zZw4V;po^2^le=TmdH>-V zHO_E-*$QQQstNuldN-e(y*ZonrlRzGK)Vnd{Nv-YYn)V-mvXzaiYKSQJPy6i_-RM? z=Qm+sxpoLmR@w@mNz1*3n-c@@`5s>P*|i1P z7yaCUGG!6{nAGGppG7yO29WaE&~OOa(cTwAdvM#Jo&iEh!7VQ`qT3-wLV^<_4#$|z z<#^Y34DAG3$y9;f!hRE+6hnDzprY11S~d+(HCw3W&6-c!T)-9sHHr#et7+b}8bS*C zN7n_ZF|t6z5pr^=P|4GK3TeyzyyD!eX*p!J9Rh_F^Zh z5~_@4jOe69$1}A!{*=VD-V^6ye)7;m)RieQ-SxJvC*3U-Oes$eZV$F?4&Gl&ygyfy zh}QL*yRn1t$Rp=&$3CfL_k#a3LtCTbHv` z(=2m{kEV)LXT8Ca@8y|)b9{8~_U9*{KRg zAN~v*4WX$f7|sLFpb%9+YLce%;@ERlxyP-M-ra;;BDKalZ7u-c3K)XoAn=C?sQ zPLOe7mj?Tz*IRl@F2E}gP74zclbh)yZ-X?$VFF5BSS8V=+nmoLlbX31#*wcCEshrw z-0_ioS{!DP(j}c4sJ%%C0^E69D8JQ}G?$f!xh^VQ<>^u?qsfPM#9l=2W~$MBOw=0m zZ(cl$n{8sRzHX8Ybaor4iAhLATSR^l+}!hu+;`{su@VOQw=>y5nNwF;+kS9sZuZ26 zR$a{Ci*x-;Os_&22=C8yoU~iDkSvjUz{phyayuvi*)a3&n?G1hW|rtPfjGA7}fa;WWIWJLm%WMN|fIEbB6N2 zr44|!obqD0@L{cuY2wu!J*)If>skNPn};Octff9{90@;oHlXaVBgEl0^V6_I(TWt4 zH}nUBLySh4V=f#$?=4L(&lp424$BzPI)xk!y@*r{-K3dwkNPs`wRvpJL-=h$#EwtO zepcx(G6kfuRBshz%~a?q=k>c$y&I^h1~P=O%Z;>DJa3V79N&lvb|My~(blZyc&$}M zcWWIw4qum}WeJJooH-?$=W}1BzNdgL;zkW6aDiTWdb_A=YccP0oS5s})}kK(Mv+?e zo!%<TQ5L#l$Sg7!nd2&d;5#rv0K&*_3tWDlS$&hhiYPgWc>q{;*dcM&`pC zHyIb4XZxyKd*|f3=cjiNWQ{=2RFnEdnQBNC_zbq4Vx#iMx25f z5{6@jIyDNwb)kwRM{$tPq@TmuLk$t!@C#4{d~zJ56qsG(?pnHc&wALeCe~jTxInrK z<5WM@xr@@>=R@t><4^itQu4RQXhXF}dypvLzzQHyrG0a#66F_nm&OvWZ)yc=&W#n( z{*n>3NSH5T&0Ll>j{9mHght=TCTM$E=Drmnl($!#A60959w9Y7(A+g(*Qn>Hr^sWL zttT@+{XDv6csuV4%EfwYdLyymp4v;;OR1-__5hgsgcFBL`hbDIuu zRm7WRc4%5;_Go5Wz&csdL!UaG!Trz+WDzHFu2j|RHNOMLDXak(3I`qh|0&;GXyr*tW!hICvSuswU#>|kp z-Y@%-Tu#TXl$Aae<$oiX8?BccTxmfW?re6;;J<3dq~xH1u^W zzK2@;#cA<>_z>6bY1i{C;h|#u5Hu8P3T4$W#JV_#vRavE8eZg!fuJk2W#H*B78LtA zpA|_D9#MKyqDTXUyxGLc1||&Eq{l|I2T?mzqvrLwu5B0KJ&7)WsiZCjnQ9l-9k~#K z00hZ+ki_*As(^x|kB0d4sAzv>AblO2wm*oT4DL(|gTL&jrT2?v{;_e6A&>X^=jTuW znuKqSr25fY%+S?S)~od+wO7kSys~IAYVsvMHnMh^BzZmp zuj8*E0x(F~4f~-?Sf{EPL`ACbvd(LEE$x;{Bc0dT?@sf5QgL>ST)t^ZEt6l2rGRJ0 z{OPhxevu`$3UgAhc&s-+mQHlZH5V%WK&lskYIPaO@A9Y3me?&~InF@}5T2d283RSR zlc%pA5_0RiFq?7pO<_h)Q8xMjm2XpHOc?7Ylcvmw2-eICiWP!Rw&SD8&Ctl(oB_ad zj?#>O-!1Q}ZQlOi7b#~TDun~WlSH3(5u^6;y!qgoKGebOi~2TmEsZPpXXP21JSiy9 z_Dr%o<|j`>SK&#LEn+Kw*JY=x{*}(1UhpP;uh`u$Z``eV`p56!uh-PZB9W0uX-zH{ z)VjwoDxqTb(vYG?D3n+Q#7?T5_|6LeB|u8nkSFJ2;iD@r`^u6Qj+M*akz9&8d%N{R z)h=>kdlhh&e(!4hH4;mC>W$K=26QZVH-Q)ZohpQP|KNWvx3?RP#(BrZ`I(n~Y(94W zEtn9AEo`0_DPNqrduzav(Rc9-opgeImr2LqRy=0tB5Yg8GlG&$O8?qZnusA{9Hdd4 zcrkuTIaZy?#j+sIld@HA51D$LKAz?wi6|3!Q?nw$UEdnQTgeUoFj;ZLD)RM7DF?jD zoYO=2$Z|||Mk>mV8_H1;unS{3hgHGFaa-`S)-tu_GV_d6wenia(NuuqEBe21%VTwd&jKvkepNUVaa8|f#``O!|_n#5-jGP;Db zAtx2O@Qi$+DYZL*Hn2vlEry7pY;vG*$b`4mJNN0Q{=#>=g4X8%<9=ho>EcOZIEhB< zeW4u_LbU&2cKCEGGbu7%ZToHfu&vzw;pc+sB*cEw7FviJYtwQC5AMsJWTA z8}hJO`k{;H0zJZ0@M)seXME)>o3%}4uuU7l^(R8Ug!11#xhB}(i5>TYjO z_T4A*zdpo%{HmNd$#<;piyIJm_DwR%Yl5nZ%!CCPT;^AlB<&F^kvKbk3xP?&^xG-{ zDJLXZR{6$-H!_SrpyTMd1zm#od8gQ$V|Ja66uRHexLs;gQ)DG&kQZ_|LwOgyXr11f z6u5Zow*5K6lbxdnj-hi=|EcbTF0N2{9S({sR#A!(>)UUZ2A5DujSFFOeC05}2-LAs z3|o_$McxwTAiDYtT|I#fpeelrVbM9rb2?;?4&(Yr$m0Ng7pkTi01@*`00WWJ=#@Z3 z;nxb$vm!#@=c<0F7u^qn5dN!yk6%B3rxdJK=G1|#V&Wh?U~iXbRfCFjFC6Tv391&h zEA{vMl#n_4KDStcBS3@UfW_0(F5GxHLm0kZVc|kZ{`SM#K4Zi_;q>phahwTqG$M5f z;ZR2k$7Oalw+KH+QX=C1-G-f*7OJ0pGr z^MO;WFRN<((wuw?TZgu`={zJs@LmVf>~wv#jwT;%;*SqzSqX!pxfA-&Uwx7 zA+!M)%Z{KPgvNk0{qhg}FW+znDV>S*51bh&Q&gJ!K(|`%!|Mfb-ylpnI))owaaz}8 zH%y07lU&<|pLE5x=e!jN+0n$Sav!$#<~y_GhA9%n z8ZLHcwKtmP_L>#$WKLyiac)U-)kf0ie$IiCVYF@nSj7VH5r1auK*=b07lDQ7zF(}( z?$qGv&rSya?0%vr5M`SDQ0IMRyJG!omG>+8KS#?uq6TvsYBwgBt>ub+AIj4orDG<> zEB4)se{QUdxIgTz%IN_HgX#>5QAdFTq%qp|knxto*Jl4!$o!4k`JX9x(d0nIP zzLo-zwzvy!x;Db%m|ljG;Hex{UA!k?+yMB|E61EZA23k=WEN$&oJ@0HiLUl3RZnot z(}iPKhso0~faPE6nn(D4;llUp`mfatDW%%ML4R!jxhc-S@sor@<|iISV?XXF>FD5k zGrf$W$(vYJtZ|+x&ulI29)&`Q4@`t%V}D3gp?mnbhsN80#g?e6C6Q;_mMhT$L$E(` zRg7iLP{571@+3u=xSTKs1ODm5OS$s(8qW!lwY-Jfey2%E@o?d_apSIc6g`EHYtuSz zKj~hRdb25&x-N0o>ud8#U6)D)s`l0A2M^#K%BBGpGL!gTI2hiB5*RdR6NM_5#Z_tEX;2 zY5Q_{@3v-!&$$XCeN~R`-g8B&VX33q!I4d2s{KWlK$o0x!2$oc}XYx8^*+?>JeAp_EK1NuAbS|tb)KZ?uSGx^V&U9BfcB83kX%&@e)W?3& z$bR9l%J>^3Q%vvT0jWfn7OlZ;zU?*?mzdR;`7dE^uI2CHy^*zG?$OaX5Fd457~m9tH9u7wl2D2?dRJN?MD^CL*u3 z@R~$O?Regk@fPbiq*f{DJm64HHdT3ZUB{I@OHC;c+8Hd>9LaFb)&v3RceXuM!>JL$ z)))a(m>-qv=ryTp9*-j7O1UUp?QGq7F%znEjPY@(PD3_*mrWL4rLx&|k>sM~JNMsE zSt*)V@jP0*W7kUACSWT3F)`*_`{rNu`-Pm&&sGE>I+#C&E&;7(XMu-adl~+ig{=LC zaGJ-WGZj+C z&ip4FC#uHVl&^b)ePMb`NAvMcA*!A6wXtkwi4lfztf@3|_f10(#&J}2G%EMgLyQ+J zVkL2HZ)8doHRgKZDl^8Uo-n*`Nvtnvkt%TtKgH%iFJm*#G40sQ5NTf16!A{{NE=K! zMv6L2vS_HOoU`arMW2Wdy|_iqW{^?_GogO_q)Z+StiIw?&_{JnE%96b(LK`| zTxjp_k(~g1ewXY-BNkl!#By*-_E>!r1pE$}YPQ z3fU=SNvJ4g4cV7@&RFid{a*g}^ZP%qXRfPru5)IFX3Uv$o$vSa{k%`nQQo=IneD91 zbkjGF;tnq=`ATHenH<%f>60-G|?zY6}Qu65RDC*Nm-q!nV&stbo zWS=PbP;(TX;%3an(;~{v77{qE92j-k%+dw#WuY|c<1|ax`^M6q7W4&fm8aH?`BL9DX#jm@w>3;#d2n=C5H8AQsZ;$4 z{UUL4n7#t&U38PR=f-3m+`oL>2>}Wk&VA?@yJfyLlrXPyc8TQd)UkW-j~y_dl!1Zs zq_Xp*+~&g0mPZ{Muj--HX31kdlvo_Z8d&8g>j!TiGM+g~lJ*Pw(;rl*pC`c%7#81u zSF`*et3v^?8ECx8lkbkb?>G0zQT6n)QT;@r7TYA7+ZNdi_nD{GCLf`ykw{P4a-YL+ zUL#FBkZVi?YNPt&BJ63qip>R+oRf~1vWBkWpYUpKJ;7~yrH**Py>g-!KD>FuY>3Jr zoTmds=LPN{r+Wg%Y?{q>Ud!jNEq&>B0qC7uLlrZUI&X@w)qPeOs{7-|_{?iw#4qrC z+xAdc5r3}4{0D7!yUqW>q~_m06-XtJNSwC&~pSDg3WuTp0i38@iIHKf@rs5^* zp8h*g1RbM|a)%tEUQJj(XO`Bc`uOflB4QfSh`P`MK!>EEWME&USE!Gt&*r7-5rf{Q z*Lp>zSMSaMNX3ymO*IBh)h8AuP|IVN0HbsB_~z7lFLdZiUGSE*`K$X@z#eonntKLq zy;k>Zd30(n8Pfr|4sZ^HAt6kJz|VdPm;5#scx9M)kGE*>@8q9{f z0iIG~{F7g5ZcVigH(ruf*Oxs`sB<@_hhU-8h2(y6A#-Mne2^`X0?tz&Y#9=|q(KAg zS(rI#WDi-av^u_|zxPobA|N3Kqn;5*fIvDLBQZ6=f zyffGWR%AQ~M92I2^r*P*fHDKrrPK9f1Om-)+YUQ`K2j>S#i^fV(S+p%YAhDLS8s3b z6Ao6L;v7yWJAJ>eDq$Z66F~FV#o#|pzXP`91ue&qaH*t(4xAes8v{J>#_sEH%oi?i zyLxd9&qqL zyg?XNX%GZT2Enhoof~|!8tB+~xFlO1Wm|^hK*bPdmeIRsI#kkI^xu`d?uUD30h<6k zI7a3=)J$s9S#*q9pL_LWn6arNq2iC1D0h>2{vuEQ^9;wn za|Ueuri|yM<_{(4cR=a+4w`*o-Z1nws-)Q-B*`!AQvKwLk!}VwjLiE|&UR;_=waW< zY2-UJ`NZejub48(-gw^O9O$TLs!MWKuJ)7_a?1%kOhJTu^5v{p=j+;+uOD~zS8kjX z^YfCbHf++vH?}#^wosFkAk=@###|#eJ4Pp0$O5ygke>hkjcB_r-DV}L#P^B7u=k>c zk_FvJ!VM?e$Jxi_!!v+IzMHtAN=z?c5#uJ{v1>k*umxlr{!LfJ?lUuB%xJ79?N1u#cviLHUw%a^tW zC!1f)+ujHjx^Z`7Or+Xr%2pw}j9bcqM9SgV+(?b9{!g0r{2mBvUc3LG?fOLq-G;=3S%)xQ_cV00~8~T}Er`fS98E!;K-jyK>1d)+e zi*R$?1D`m|+;_@>!D(fz`u4Sv#}&_NU}34@#5j^pj#ss0rNpHLh;)z3glFhw#lYv% zhSP7keBBz1uMg@AP=wtJC%!Bd1mi*AfJx6+1YbpsGN&uRoshHOSCCS_i$Uc_uN)ub z&$8TaK)5K1SEE&(ndXAuH(mRiY2r8E@9%hA&l#kenmMw0Y&W1&B;0$Z4MUdS)i9EU z+<`8V0E8o}1YG6w%8JHk>KWmtopjzz5xiHc5r_zg3jODhm_`p3RBu}RzbeKdXG$qudv``9&^;=FtvL&K`oe(om5XRs{g(l%?KNa0 zBAAIqZWDdaAYbh z48)2JMF!!(-$Jf~&hUJ4KQ-tU{P6aX9Jlt@Ztb5K=~RYdDt&8Xd8WPTWZ8BW#P5hI!kWkOq(@vcVW7 zS<1rX1Jj_#yv>DhV&k4mHnXUcf)OFUc)Uh<4)|#FXSBo@3Bxtw=Ge0*!M4LxBSpV* z@T~#PC5GP+jwGhn{@@##&LN;7xT%s%IQV8xD%LiG^Q_8AeJb=3taI}zP*>Xqf>P_c zooy@j;+Cd>Aw6m!EAsD9^82oQ{~1X>zsJ9Y(K96=Z*04E%wu!g@@!$=+s@8TYlDU% zed{8Crqdx5OjeGu3HFgPdamDue5Z4#%mzi;;%n*+VI*V3MIKt?2Ea&j686i9(?U&` z?R1jGN@w?~mD=~{GzEft9vEkTQRw)K-8F#7r5+0qb@N`3y_;bEHmtAF9=s9bn3`ZoK?9c~Tw0tz`E=&wl@EzF`ad+? z-rYink^V`?MdiIWCGXBhg{|W+nnp`FOHx{@X}l*hM(3MW%-J?{zziuO2{MdipliN{ z#1UzKYF`x)U|$1*2&3==5v)uYA=iY)JA@SlU-+Pm3N(i7Jn#_ZVp&~^O4M=K4AhB? z7a%FA_Q0*kABIQ6+M$|c9D!s|I0`03mI{!R<~?9i4Plmv!AH)Dg~I-TOpi5*ZBAFKQ?rS!P$Wb0)|6?!lF%S+AH!m6 zYF9l33x(B!^!2|Cm9ukmo*f(6Sy94sA{o^kAOxE@obRcVYjtV%MkRW6GM_Z2DQcDU zm9Ygv%34q12vA~J3k(9qLN{+1dTp(~cC#+K9b9~K_%e#UC9Kh34FU#?nP7k$kONAX zAa)|io|y+ifoy}DLco}>C>UVfgn5KN9B}Xf5gh5iG_wO9}{Jmeuzp)AV zxx29hP_&SSxm*D_@x~zhPXKBu8NgOPd%RQ9IdyHN&_ne0Q|4W7O>EmFoF*S<-k-CU z1k7%AnPIbN`*BK^4O~g~XEyOJ%GWJB{i*R9X_R;PeKqw?HPn4dd4>^_p7D1^ka{1* zZuO33G{Z6wsQ;4}&o`tqggZnq$bS9ud(HP|6O=}6Pc$7_S(;j3@a8GzlQ1?sNt>Wq zClWt$0`HDPQ$_l45f@v;6zhaaRzxUEva)Er3%vgi{Lmmqxrh-br~qabVh0XS?%UNX z01@lz?rP8F;%_g@FERT1g?8@%)C~+q*O24-(8xvA{r5wc5)1ZM9ZtTK_d1E2qph{K*rp@@6k}_P+8LceKE31?8zN+U6syce z)bfV}z68sPy_Efwc1@+i;-b1OZB%JhzosoqTEqo-mPwyF2dyJT_KM;*i(5D=Ji?^) zMJ7#gq^>M<7UUQpa=yS=8&-g5#&4F}{dc%orWyG6hyJtfPu7Vb^P2|D7IRC?AFk;b z_jL0Eh3DUV7qOgZV~|ob=#m|el*g`x^O~;9LTic3OVfqq5T`xKiaOV@{)VjF9k?TR zqWUBjIHTcBGvq|?L&R|@Dq{pIfeg*X!LnU{u>3o!(dp0)Ug;-fM;9d@CD}}H&~Q%Y znDuh>1YUfapW1hZi=8s>)+?^_AT`c(1RRB&{CHzVNSGo4PdSjKAu_G)OeWjeJfe?| zExBphkOH6P^9Cy8C6yDe=FIF)SH}peCQY`HX9^Yj4k?>{%pN(LZsDMejC{d%QeAZY z^t~8W`K*aP&=ny{+@QM{w$oR5r$67Msarb_3jbU{^aJgIH}SjG#h=>E|8i%|-+0#n z^A_!LT4HqJ{9^`>ig$K(CpBNrKj_eI+muwUsD>N4Ga1nGC0!VVS!pq!4yULIkCrJS zf|&IPBhE*8%0?}!&xXetMaE~C4>5BT(NeU^rpwL=M&;?Apz+qc zo?+a{jHgQjLWs*MQE461#FNIRl!nGaFJOg_!sejn;im{GePP~GLZq=_#IVC%O_0Hf zIGUh$D1B)TB;rg%jP{O^n?|A;#|F)vBTOh+CoK za{CSa3jTIu{c=hlV;up?1M3T=Ukns~c&~+M8jlx}^0E=Q?KEJ@CRF+XZ_u**{@ZJ{ zEp)vv^{Zd@XE7I%HW4H%X?okN7?Bb-ViO)>WpjjDrynoE?*dmX#4!|YXM}<^b5QMI zq_6TgftrvI6PTF#cAkvJBslG^3KxODP~+z|aNq?|vK9ld2zC_q2RGgNX~IbT930U? zD*bS-rZVv7hgmwH-b~#aeDQcx%=%X7og2!LhagG{N{Pcft1U>AItz>yAc5 z?Ka074ncol3ik)Ub&Hv65y_(nlDJs4xm|Z{Ljv9T@7PdIi8RspAX%sajnKQaqcw^Y zjiH=@?@^-ZtdWQ^cySza4FM|&~7gk13rRt&TPF@vDV@R#uDG>AGx7#09SW`QX7>IS{7 z7!|vUmrC;zSXmLR#jI~sQkS_eEOU!ZUCjh~anV7WcDyxmsX{yd<@6QDi-~(OIE--K zn+E)2|0dS(gHjH+|1>uzhA*=M|e3~h&=*j!pLFc@%|Zai|Dx&70Tu0~nBI@~QW z_z_VZY@T(bv1P=wLGV%7c&X1_We`%%PACj{0jX@h@_ zXXL=LghHHPGTc$MBV>G7{=(U!{5aI_Bg*J}+LZ1w7LmgVjLae)G5R4hrW(NV*g|t) zdg!}E-?QZ2YNP~84d6>;!Vd}5?1Ybkg-k!N`Q5~ws__$uNPkM+uWXOh^;E7#YFY`0 zfDxu2p}t=t;_b;=l-XKfWP+E$1kg7=CncLdvtg+kt%O>yC{NBQSG?~s96Zi|$uB3) zAL;sB^JS*DM7dLhubXq>k0=$8^2B?MNqLUkmBpbwVAFf>chlckb{5*%l4ZU8heVZ< zNNgC_Siqj+`enWIk zsRqTIpQt!*#fvGNEWV@Do|k!nH;bK*I4)i>7oru;nd~n{bX#X7JKyBG|63)^J;gX3 z#+W+vnDEV?xS+*5DTrdMy?@i2{vyVMiS-E&XSXyiB{QI{=g?n@F7S6`=XaJvKt?b> z`5WEzt7D+pO^`EjY~1#ZWD(Jj`65`QlD*aKn{hX^VcAvCM>`i#@lC4&jA9H6w5Ovs z-n;pH3&Fr_k?xme;Qu+e{xdl(FH~lq+4PNMpeg)d?*CWoUEtHz5v&=${L<3kFPma@ z&C?t15AY?==PB zKQvtg*&j4o5$5Dpi(*6zrtLDD4(=Zyvit5JtmPq3K zv|44?bYD^{R=}x=3HPxjdr=;Jrq4n{u_2YF_e(?0gFJc9;33kQbLvB#qPu8MsJ3eQ ztQkf#T_)oQBY0uQ-pRycn#mU83ktc-=X54dwXeQN#sn|(sNzxUoHFH0{tamlry3dj zx44^iGfM(5qn^8Oi8N0SaiDX6BGqQdSWc&;|c@;@fFM6a)YXw zB;GX2n*NzJ96|Be^X+xA2!(eBZ(`LHGhj#7*m6_C%ni))9HWc+bz{z&>toz<%{qE4 zGv3OBBfZ$X)o|mj;5~t605LTwpv&c=yOxW=jcgt&eA~aAijV4Ia zT$4qbWXhcYc_Aq{N-oT2pPQslayY#8x+s+#b9e~=+rHF0drAGhE?rb~r&$RcpmW1_ ze+3X%v!ccPzW*?hzME6W;4Q#_c6N_sFGW(?z3Enq25hAlW`K2R#5~U{1hfYCXQAFF z8!mKtm${D5_0OQx&BB98ip#nCszT{MD)Ke|LYhu3ZeJAkCA& z>sAb*0|oA4J6oUgmM7ynHd;FZ0b?A66=MneEeLBsv+A3hR_M(QXox+OJKvd*DI-uR zwg@D{Ll!f2sTht8Sd+(m@i@H3@aR^zon7Gx8$AH*m)!?^HhrWFx?b-|RIcyUpDnqF zj;fq<+Kx(}-4H5d}$cF{=wTdxx=ZP5hoH2V?prr8)Evx2d z%@00byE9#QbVy(Bybaw%Mwa{`!t+@w^~HpXVHc;^(sj<0J>*q?;@Mo1I+&jwp%ed& z>5X%~^QC9gg8=>L(tsUiMGq+OZM0}U4(_&oAn;qH+`ZfOYcBU4fq(TfC0_h+!SKW7 zMAGyAcwKs8?;Y{6lxB24I%R7o=4P>`hLFbx}j zuK{D(&j7|^pMVtp1Igky@e1e14-^j08K1u{vM6%C`n^i+`)%(l)G@wi&o;mF0*q?5 zCy#F|%y!4r-8HRb&ts7eGrTa}-Ym2>8Q10+*C2VUgbRLKOy>~d2{u6kD`z8HMv^9J z`XSMbyR4*gZ&JzvH)H6%UW?+s#Xl)oGISa8K+H&+ISdBr>nz2$<2S%bq8T_z z{Qr`HbX$`wDjj||NixO#WY;V)vQpx2W=7sha`N>(jN>k&!Fi zpCmw!Cy?RTUO2N{i6~}@VqVb(w(~RH@{E>F8MJxDO64`_lJbHCt%oTt;>I}W3D9-W zYVbZ3E!V=2U5`;+EPwIpqQwRC*CPpgRxSm(SEkAfLQOudmOpAveAMiAEor3MQ6RJL zRWwGqCAe1kO)DI&yR|*NS~&Wf?D{{s3sVnackH>JIC{BHf+4dz1g$GEramtrBz_xk zPm^FmZKO?l>$UZlob}v!2{_Ft<+xL9fp1>;?6rD&IW1SU)PrHvfqL9sqGrp(W&YN3 z-ffNkqMOnl^IHlpgRy_StbsT+r!=emYx@7|a^c4G_>=h96A;@mC@gX0iCYH4JO zR98Anzr!?GxQD0gx-k_PqZo2rTq-y$-AqSUn2^(^l0IHGIt{@Jc%`U;Uo|>s5P#h zOQ`)6_klLqxCgL!aK%_W>@6DJo>>EcNhX5=Vm{w4Jim<>kR{;R?3WYmt_}faYXU|; z3n2Vw`*>X@HI}*sfkMBVX%L26IWJZUo6)ZUmy`#$-dE62uoiT99BxIXlAEzZAx>$wL| zbPh-)3F4Pw`0;IPQ@w-+(N%O)3|jdHR;Nc~YA!SS!bu7IGQ4Xj1kXtLEMLZ5fu>2nkwUe$^XX2_kX%Yl-du`)M7p{RB-71wqp43li&|AFP7m;4 zwaIJML@hB#wJW44oCm#R&Qs8cE)tabe9vVy1=BYHKl;b+%WE+k^x^?3X}upEfPux{ zfNmSl-Q3;$`x?~U5*hu!t;!?MEKdx19;UhGZjCP3L9cG~+A*oza-P!{1}QaiEYVG8s)_m1~yqZRR? z;ccIam9Eei!V<92F@}RSM-6y3yw$7J#|*9(>E&rnQ&u(Y4<6qz9N^yu7CcixapP_^ z<9FQAKR0#0p3?p2W4hfpj}-5Tmvd?{!?jI@jZKf?^|h1}OPc6w+Y=EUiHR+qvM-$bBQkvbXkPiR|y*MJ5<4uLVqAp%caPaG&19D;lXzYM^wNK+qLavnc|w>3Yp ziyzvC2X?_fKukb9$jFQ!HD-1QXuqV_1$gzk_!x4RQRAV666$iN8F3`vj_8F?yDI;aS3CKC>1_BC#1rV^r& zA1_r8mxbQ-88H<%cj@!rQ6i9f#sraKI|DEB4YOwzf{+4l02c6B!n`MFkIs#;Zn8j% zNH$X=Dd_475Q{Mg0fa+k;c9`*P*ra^2@G&%H%>#QN62NWk&Zx6WS~f8x}cL}yLF0B z6?Dl6!hB(1C}}tWAr>x1BsS?GwoCq+GQ2Rm|5p9+f%zw&lV5zIUL3LaW^!O7Qx=Ou zGhpDrqt@b&RqjqVhT;;O@Ao{zS9}lNTqidAn&rH?q}`bgPeXGdIOq|*oEEDDa!cNh zFz1qn#M#sYK11G{$;cPCm}J(P@2mv`e!N2+$(!t;<*e)=t0Jx_t|EYJb2-ocp7=pJ zZ?Y<8IPr91apI|&y_vL`-9iBEe5XetKc*s9dh*ff+bCdh3lkyQ4;1}+CGfwS>2m@R zCUT?tnhT`CD+_8qfN{)L%Iz2f#F)#wt2jeX%L+#8HJ#6vxK?Mm-qNKcRwi|NWO=^b zDvI`Ot!IF4OA*V+m$`NdgR@s5I<3%Js+-V&+7B0~2e66R>~`>GicFs8L7&^P$hFOY z6OKu=8pP%@5Sp9XxM~{vrGKW71zFT_=*P?`P+H#7V4kCTnS0qkm$Nq}OM%zynE z`g^A|j6GT}2IBO}cOT-kJ-d1_G!VL;mz1vX1mjm_5brc6kzmp=_5nN+%Tb^r$_LIpI(qzDS_kr*zEQxLOxoIHiIR+H=7FSl7*ci}bl#>`; z=nxbO`10D`^*s&sLeK94@fLt@u2nSmB06EM?mMegG{cfd%-UGfugZlm-$1*a_7_Lc z?{<$DGv26v63G3aP$FfMVRduVpm(~lur6fI)E>&leDR%_Ew8sXH^qvRSfu<5OV9`GPwiXNRjX zg*}f>K__x3`FPnhE;g4bS)W*VJYNHte~j*&d%PN-qITt0abYgUMsZ;@8CSZFXt|5g z;!viKg4sx1odBk=amoDJlCaycl=BasfBGV9$J7`K5``~(wG#TV$oH!~e}884buJSi zQN%fWh8aPdhrf7q)e)t5B-gkstS(F%raaqrt7G6HBLmDc4|6RG`=r2I7P60JE(N*1 z!R3o}rP;YH_~A;QQ@FKSpLCYYg=1-C;4#Q4Q!f+Yml0l*kCl4LKvyVKnp2eWFzzhC=D4vwi{E^M@n=#d`9t=D(M2u$C1INHBhZAx4{^F* z7a;sP#&?K@n=3HM0F?3(QQ78>n(H|LMM6+N{ZgIjhn zYz66uGq(|7L{2KAu~wozp6_|ua3Y)7h}4ft;ob96mCPDb6~5>ALIMAtgX)vX5%Rf5 z1F-1=n>B=J#9P*dZl8!|@nb3!2P!8gs@(>>1rJO1TMR_+AmaCRx@du>|9BxWGAT4ljIE*P5XK6i>c8~93UTlqXe;7TpT+rY01_$dc^UM{&`YM zNU1imc^Vv1Kdl@EPJalQNC+4{F%jZ>#$c|9Qa#b1tMRiu`1-^&sh>CbeL5HM`ItVs z2W<(;o_=TRqv*LyQqOse-yU;8Wkx8-#2~nj8BpYLG)1ANDYX!J7t~MA+P~(8)-~ECQurk{oxiMK|k|O=PonyoiJ+=%}3srWB`AmN~~0b5o;Md0eD z+xkL^2f7sfrDS@tYqYAf73vwqFLLfok&ynFW4;%*msV!}oyp?sr|CMcf4I`mpULqe zL61L%-kqcgF=U zqbCjr`bbw987Q}(d%5JMR$9@ueh&3zRryQ*bhWuqv`L(~pv~zM07GbCuO{dZx9@#Z zqu-ypes?eCw03-#ganZ4#b58Ukn%^(tEwj-4FN?6%F^=3gt{*2_4f$jP}_(1o@ZJl zZw5FpSAv6TO*v~N=svC+xmE0|XjuinIKAk_xHG9gEI7x}X?+54^8x0>gRS>icK^>D zv$p`x@)x_MQB)&Ub3=E{;y*k;qq^I)#%x#q?El9}*{Tsse`z z^V)*Ya4ZTpyZXVRzTR}BvYN6X)ebxm50UvgV&!>&;aaWA#Fm<#cZ+E($$gaPF~<;> z+*yfRo89kfSqH1}9|C?wokF<@PEKY0gUXb?y~;7_nJ+ze5l59;mU(a9?-P(rJJgAr z&U9!2NCXXlt1#zrv|zlba^|YYiM!8s2g2j_YF`sSFwhUB#cL6kMn+cqZcfp=M7N(T zRgX2ucPd}0Qz;qVa@!eMA4pNRM>J`@12TBnRi^dzYpi_)R;~haZ(`c?eacEKIy@4C zCnc``9DZ~N`F-jm1f%ls$3&(_%=!(?`lS!}Gyj*@ULiEmAD9UfJwgkEZ!`>4xO?#4 zSmsr}jDUJ7Ae|OHOl#y-d=OtaC<&avi#R8+)$<~J&(zCsL~U_;Iv zrJLyl)k|CJVejeNkvkG6~#8B4vqQ}6_cY-lPFSJU;yqcegCKZpUmPD0bK~-m&S?Fg&-Cl)V$t^N_M#k2Tm&q zmS;44SPrWiv$nbjap%^CLKQhnSDL7VQ_Ct2-KihHF1XHQHgiY&Z8G-&T}j z2>_w>CFSZ?;rrT%+5V$`MxBk4c{7PqiHRZcA&IWQN988lXX7{NRlYDTC{_3&LhQJg zE<>i$?{hY;8qk{vT0QynukIU&BT-mbnjKyt-~qLRmX4;u3^ zZz;K?i~gHQ{&#c!gUw&ezQXSq=gdo)kYR%jC8*J>Bxu$#QMU<{_H0BP3mn%M1i=P- z24aWa2~`P2$r#l~h3XYo-WB%?y=qgu(idJ&5p{tqo|uRq zP$t{TqjUvL?XD9V)5$IoDzek!GE(LTMqy00etC%8NuQ9h9Z+D_Z^@#%oS{h#(I5INkpgbT#(RMbm$+T$l8`LL|390 zQ|eJ(tN&0E(cbA1>Btx5x^Gh1f9An7&Lq1UZ$WBxxy<7+l^J3 z1oyMzf{Rk`d@IoQNLwK)MeDQn=G3P~o^a?bakWO(T=AyZnTd;OxjB80#OjT;Ld3QU zZ{h>#N&}~4L3iORAIn-I-ub zBeGRW*QiFgkBx}rVn9ymrNA+{cU8B`aGJeU^#j0Zm+FLs|MsSWg@y0@9mT0`Dy+6{Y|hY89YEX`7;? zS`sJjUfu^X`9h>nG%X=8UkHQ{IKD7h6rLZc^I(E7Q-5B7I*$bM4$=@tAe#ilH`mY! zTXoNNP90iOU7Rw4hhMK^u;Af}>*UkZR${^IcuGpJsyCDar@;y{7sR>sQKMt|an0r7Z>kJe#7mY7^R}%!T>+nu zQ}rIRTjY*+Syh7=zGCM7JF&4e9Bgp;pKR1tz8r zUSIK!FX?yzSES?W(YV~Db$U+afZw$8-el8OlOSQbqnjnc<3L z(ZtnsPAL|OI|QbgH6dmwU+>dA%wa(=_}k{p`T(b(uA}iJWA3c8Fja^wA;^b;G(-#J zpMC}Y&W~uY_f)~0^OU`39Lrzdoo#9k<-&~cb+U}mae_&?6 z?`fYP_=9B$+g?!Y_^)CQyZe~{>G!Cw?BT-c4*}@c5?hngtc7_?1!C^bgI>tV0vYs& z^A9CsX3rW0wpg`>u+ZQV635*OgV~!a4Op@BngXFQGSph=r^SmdeP<4nCf=H0>|&{G zJc<=}Nm9ORvdx!Ok5k&6FENjupdzrTKFr4^A(zwuVx1#Jfrz)lkU7A4&LJ9bRI=Lk&PEYcZE$~@G?yI~# z7tyl$s!7514cSv@G*+VxaTM10&^ZSM{*|*Vs+;HR7nk=SOC#3(`f`CbNs+Pygpzn- zPU2T_ItV?KHk_ZWIs30U#w*Z7v&|UyrDyvL+*&=-aJ@!gxMEi(wu{!8aBT(kh zThha;sLNy86fMW>2e?WNA2W;npnKQsybPwre;6vT#Vqo@o)}%%p`*e-EMPhmVXhP> zVET2e{@;wdR4`R8Jh-De!4;oOWTiQRAsNT3%zC?X|j*AIH2pkTu zv!Z8CaS6WTO!XEhVzN#$wdvQN7HZYC={Ia!Hsn}L;aH4gr)8&QDOSVOi3wP9#kZRm z59Q|lk+Rt1l=}YS_8Zy#!6j+q*MOqgrPVDoFs%#D9y`Z6dhHQ3h7`D-u%d^;{GsZf z_7O!-J@|zvF2g^H^`HM>kp#as@!Xg0+TzabGN*HsxAlsh&Rt*8YU#mK(>yX-5R{sY0vUb>ycJTv2hri$1+dI}wiKFO~s6v)yF0w2aQGO`}<;hPA! zDZAbvv|>c?D5s=2x*suu=H-> zY2HuQcDg)U)=?hxlJX%@X$9p*p=}EUI0znP#*4l$^t~?g7U;`TlQ50e_C(CoTu-1u zw!J?2X>2n!_VOg0)*u#g-O&KQqTP}NT#akcpJ0dEs_&T{ag_MeIo9?z6fnp3&uUdY z=0Uf1s(|YesMpU@D*uhfu^D&5Cu=MNuOcd0C0z{rMaMdYxmN@~uDz-Jn43BPF7VR# zcEZOL%R4$=OwxLw$)XXbW`>AjQDcXoc6;Qv->wq-pd#)V;NnaSQv(4o2dY~8Xd*4&V=TPB>>>8J=A-WSY6uFr)hL z`5$dS+rFI>U={6#On*Dc`$^*IhsQ^a_KzJ(Mgi3Uq0M)BWflVoK>%BePpZ+xN!FS5 z8v2GvnAe?_9t&dT=i;{EYhHZ*X=g?)gQsPj&YA1JPl;)6AO9}WkI4c5fA^M3?{C)P zXW|)=a_t3Lc#8wtYG{B)tZiu*mWKZWkq5;V?U$2oeZ|*Bfxn@4ca?VLBWm4)dev82 zwT0GGD;W2e!HBGt@|Tz@RjXb1$3$fd^0>yyX$HNG=7jYJ39HR+YxrJE&G>H;8N9FG zJ|eQ;&ixyu#;*d!0MMwu`e94+w(BN-aGzwh8k}LOpIJ>=NaG zX%Kq#B@#orWUNnc%IOl5zZmO?v`lq7#~^}j%puPthI^kbBm#6-nnzZi2Kkhv7qCmN z5qQQWFAqF!0+YkoO=RdRQy3b#xbCVIZW%VPiU&1?=?p z#xLE}E`FnWdSIlx+Q3=3(>8IKKe-dIT?P73&Exhee#@8lwC-H|bHx{d*z14zH2h+q zioqQ<5(g15csxXJ1^~W^DH1OE){eS5t={MbzH46mz(jh zVrtR6l2P1p8BAXJl;W;3yyg7i(P=VGp%zP%h<0i4T{}@;=d7oQRglJlDN%gr&wK?Ee@~Psdc1s@jIoINv0`!Ns8GvpxyIoSTiC?sd ze{D9YuH0$+(D~=%;*_p7#_PGeM9v0t+xY^|a^aVWkL` zNBBaDP>}(imwt05PQuxBooW0kjm$lL`8ljRL6yHyUIr3}&_I(HxvYQ? zq&Md1Z~~mUZG!<28zAHyF#wh*I978idUID+$#4irXV*mC}EceAPF(p7&by?hS9bn+NTuAW1%YVvnFLBK>f zZQ?~Fv7C>sUV2nkH+%AKq@0CSr<4(Fy|OxnN6_El+I0j(z1h3%6|*dx`;t;nf^f|v zvUn!=v{4GLYwHqg$4^%0Zr>R#G0baj{I-2wJ@NS2yj}I{tE=P(a07t`o4x*D&l~^N z&pQdf`K4D8yTeM)%9eV0&l<&WBxYVLE~isjLPe|*#z>NuMgD8jQ@EgC|B34izw<_+ z74=sEv+lNtV%?eO+t5T`pzS)L81L=>bD17A<_N`Mx`h<(E#PuPxPN^Mk$7{b7@@`p#hSceVLZ`eI&P-n_Ugqk zEq6^nM}bdXk1Dvh-V^6=zF^uiVr_ezsMI(1;RGvw=B*R@BYy>c63K;q%u9z~hX+ph zzJpjX<{>rUwh(3%2pI_VMuDZkS;!tZ90CQAwfGL{2x-vjFnros{e&Q$fZM}($YR6V zU}jKWGBUy8J5B;kgTvG&me0d}bBiqbP4rrE&i@flI6>KTVY$Z;`hB5c_i%SbU2oD_ z9C@jN5$4Ex{D7rsriKW2y*K<l~Aktmhp)Qvp5>>WHt1_Jn5^|{XG%r-&uZJ zd;Xo<%-1AdOf4lq;{_fOOMbnwCTt+5e{x_b1#N|%*y6sRUbEFstav6%IkMlyM7!Us zqG>M0xe7n5P1>9@i8I*&!Ncdp7$K^5*jtGV&LPCdoaFFSLlDe;+RYd|KF2669TqRG z*<*i-)K4(MBuo)vW`&&D_NEtpFnRYx1{mj2E1^F9bty7%ArD4eb+`HUv_+>@Eh)+uXc-=`dIB z7xBKg)fR;Ken*c`yGd-EP24mo-!yTa>r~0!BQA|@_+0qVKKf?wNaETZ#+P>IP z$9V~Z`DFiuY5b2(^!BH)yYpBKd-_i%=stz|>lKxh>GvJ>*C+_Zurp_PpuH#mD&W0$ z@L)~x<-LRkFKsZaMy60U*Sy}+nC#{z2q(ijYl}yCi2eDGQlRB)q4PjPlYMdzA6UKP zp+B(0)Unmjv!BM;n|rTx*69x{cY4r<5G8zA$ z?%D??R-h#^CzEe1FPuhS6;27YT3JsRk_@0<@?uD@&1NcjbR{QP!PBpd9QX*}>-sk` zD|1s!RG;YwTrvTylrH`uh7v3-ykr0~#iTjg8I!|r2(`cTdU%KZ-46Rp3z9_fhvg3| zhyxnHpIcmc88CwtqnU*vpQ5JAM9pM`)~sBn%$$i)q^NXz3TbOZhZSK6E0-^GUSeh# zs@PupB|WBhCXNC9hgsdk!N=uiQgHKKy|Efkh@`<_qw0~J;uN7(^rjp-o_1q%>t^kZ zI8cV?nM%^@WG3S#y>DdeFL<3gSz%^JfApb^r5GQ^U*`HTPnFq85Nn&1byj+yF|llY zs|wzslU+WS%kL{)zS6QB$d+~iyizFjdG66f0b=Ol{kB+hc3+gY3?tOjq<4JWr01=U zGNod#`q9KAd<^|Ng`>4gN*Kd+F%`k`Q?_~nFV8Beb1CgL!M|th|7}R_`)`4nXO;DV z(zmrQiSDGVc&rQaPt*VMUJE>)7f|2VD^G7V6McSK{g)0$e<*4NkJhj zisBVT^kLu2I6)_cIHYSF_(2?O8t|;t=U_kq3dALffsEBEKS-XEj1KY9%Kt@Ba9^a$o!lmE{fwWKsgq= zsrLV{_a^XAw(TD`k}Z|7MJbH2FIh_2x512k4`oS0Xdz4XJxj8TU6zPKmJmYOQnpZ% zU1SZ}voG_WGw81F?wW>%6WRG}Fvn=Xo5zT8m=VhCC0iW{$-}eaQ7C{*rhUd3H6%!oyXLiC7F@#{@x3K@^S~D(kq9 z>S1QQRi{f+nbYGt4vy6G4$bd+&d6&Dv@cQzy~>QYj7xeHTTFxbpS*)v_2}$6%KwKy z*L~m`m-cJ@>icccmZ5(ZeywmYO^rMI(WSj#-bL&%(+`h zd;+zBn`OfvH^&JEIuPLuEQ-w^4`|{wGr~NB$(PQ}SbrMiVwJcce`Gb8wO=e!W^9pY zPEsz~YRnii&{F=$po)pE;se|}Xg}Uz%jKl8ne()Q92}S0AJ)B{|H4IbuxFd2OXPs@ zQj9Kmb{+EB%CbiTxq;nFlELVU#O@b~ji(?PaPG<9s-7>kvjaRxQ%=PoB`}5m8jaQjK<`Dj2Yl&WCqj+)gZao?VPNJDan( zCsp}+L=yCw>E60mziNA*+a!W-nE zB-ID(>0AMP?Cz#frt_?oqbeY^9I@7vQ>NW3D&5)l6enUrK0B+E=s)0@8fclBZ8JI%GUnud``LXn_n zhmY^KJDk1J>AG3T z-NK*U0_2Q;@ip#n=|Zfjx>)I|0D4+t^TE()ZfWH^w+05xa<|%RBA0t(9ug2iEvMwI zIUfGXq`l&yqQ4EEhj0Zgq{WiOjwARR`{?0Ko#yV|Gv?N9NLtDO6dwE&tS$T^F_*6v zzcM>D8S1sHG%OqIZ0&l@>@s5@2&CLrqCa1y^g=kypuJ@fNSs_ir!-4SPd-}iLs!m&d8y_$Amblti z>hS^S>m_AaAY?>=o-mvf!(T$0hE>jV-J?fb5&cvB3N1!SvIW3N>DBvXFB55l zFz1%t#@(sqll#U;)0i*qem8KpL96UhF@_|K1Se zs(HSK0e_Qy4TLQxJRDtC^`DKIPs75c_zj0PLe~R4O?^#RudvoL@xR`qC#j~meqfwG zaS_8$x~c1}`3YjYOvU{MmfFB{LXT~szAjSXls6v}%AYcr27^jE`G0clCF6FPJcN$F@s>3#ZAKYZz$H zmsE^(OJFb}9V(4tBnme5<&&el4gzkL%O#e}I`)KUpx-&O=8?WOQ0gWR>^GJ&FqS6X z)rA=nz)b+_EAZ7LU1TS44X{T$)3KfTSqM$}uTd<&Ig1;7r1Lf{89Hx9g8up$1C#RM zA*Y1(%{o3@vDpG*SNc^BMf%_(KNG2MtjCwN*mEM(Qd8x$A4O%F9u*?FEtTw}T7R0KO4LV{Al>_2 zb%ue!Oy&~F_-H$4a+G+MyV82xnsA+-6&=PxIO+{Zz@B&8!?FA{aQ*czQBiWjsEKVl z*ts~Ej_-8rr2Kd3h`({)(NR2U&)U_NVDyG6nsXzql*vPQ1A(PEnQ~a4;NK=@pb26i z_m>R5hyR2&iav~~eAHB2YBP>GwEyjXeaa{yxUR>P9{0w*8;g)5ubA=JX&^{(#v?Cb zpW)~6BN!ld{K~#qc+-zKr+K6>BlSyI7hDe?HMsjABo8i?C@M)dERdg=stT5Yud#r% zp_YO@gK6V{(?}JKK;k-*_F!jrR!N+=UF-T znorH(+%r+0!v}l{y1x8XF3^A9K60QZn*y>j{C2+Fuhi#PJEs7bX%ncc#d#Dq%=wW} z!tqMsI8IF!2LgM-%>oO7Cq$kwPkz8(iVcMH85wLiu6VqNkV^DfiMFpn==PI+&3m_C zXfv4hh~XwuK30y)R*eyI9x0AX^#nx@e*_}PM1eRG^V>0l9%3u>`qPF(Uy=m7(t>PZ ze2kF+0SFnuYhtgDtPRir0H-hjZ~{So6fIGJsV_ex1e~Y`k6=U*Vcthj24E`Qv~}_` zT5+k;d-K3gviyId#{ac;zZF~n2|IVOPR1yC4Av=`Vt#4(u32HurnY<3?D(^QNTLMa zNV@&Sb_b{r_BGIX9VkUiq=c^#54X8T70JFba!}430gB35Wz{{V6NTl&M<&gMX^kn% z*G8v)qQleg1SNkaI^o9=-C~1QhO8+ftxUhFjJQO2fhv;+jC8|f>WIaK-zIojtr zij?8;ey7P<+ZtX)D6*0(!_ts&R5+Jo$;wW9vI8ID9mM1!Tz0we#cO}c>Z-UmGsd7Dk5U?Qpg7whpCKQF}J0DKorrO#Vsz*tb^rvZ3d}X-KVo) zgUI`fvw$2D^)yAF*UEzG@sxQx&(jAw`BoND*}_4`Wk@t&sX_?bfKf&TXe20Lcc7aT z>bjZn=%Pw$f*|Vz-Jwy1jcy_Kc6Yt)a zKay3MNTd)+wSzwllw640+*h?Wj4@xSJ}b84xB|8bd;TNt-@}(CotJm)NT?lvA&Jx} zia+;%@Unp)0oqWWuQ22)y6J23cvV!V*sVoYjqRJjN=%LEwNuLBVgp})5-&>$<$Or_ zg{U&I;pPkP3j>C@QB@zHg}@Xp!8C{*Mj%d&cMMWcR6Tv^ov~Dv zl;b|LFVn{!R2FVs@7bD+!vuuJ+^wFwG(C5DJcikRKgbBgK^WIPsC!wLT2})YKMX{{ zG^@A1-dffDs!JA-01t+;K$!3Yr4cDmH53E?p5OqOQ>%Xy9Q@*z;9fXBdphS@;lQh9$+4uY(T}-BQrrQz+29M7*%ao5IG!pDL$gIuVNN7DTG4u>aHu1Vba+DpEs=3~zX``9p@XEhP8M*!7S`M9qzZw9 zA<`4XU8EU@1twbvb(K;_)gYs{3Pu92ac3U(^OLTMPUL8cOMA=rIio08xRH9F482NS zA+Z83Ee%#94bIhbB&~iZtPc zl0!svjwf-D_10D^A$So%#Eeo<8vMJkz)L8Y2`mWFhKLq|%0bVj-GK!%q3BGYK?rrC z+qBR(P$WDM7BE6iX$!sU!@6IN^iJ9eD6b=@L@|aT`0Bm+801>=ZJ&~QZ~A`m{zChV z^M;uLXXD!iQZBy(4As^5ji2zE_n#b}aRdG1`Iwv644O;rXFAIbr(KG^?V6G~rz?7Y z?tkNR=5_kcohE$WrTO{6)uj?N##(iA^V~W6kIwUWO@X%S(u?^Jue@rB!y0(4)Hq7+ zCN%o6`C=j&^|R9q!x6rzkUkYtD5VKS>`ikM^6Jk>mj}b|4jWkp=+eGrw7n<-saN+_ zQ6z#(or(0WRmNcq$x=Ni>9=M&EzhtJVNuToZ^NUZHJw2)ny?E$sn_sSaS4z|o_)kf zT00o&i$`&z{+zE$HXdbyiVs3XPbi4d5LY;lQ914N6W^tXgj8x{irgV8eU%498o+~> zQ4BVg;A=|}#1Fw&p$U*CKFd%S#sfP=n#JcQ z#Y9eFaYzD9qTd$x7r@%q9g}D5^1+k!A{ju}ZfwuK%=Ms;=w000G~X6o+fWrt{Xqx& zul!SgiI|6jr9A@#7|7nVzD)C4P4^Tv>2Emm8Wja@CX?*#2QpY1AI99}i8nk|re{&m za5?oArMl=w>vPc2M~?3X>s$+Vq+CrW>$l|>B*HgCM?9GRItu$s0~dpw_IAiYvWhb$ z=$?(r+4abKL#~@zQN^_ZNKaD^&4j>K7tQEj(T$uR$c-eoo^7HF9Z&KAy**L2F2SSp z^v7qNt}o*j4-UlM6npP@|H1tS{b$_X3%n5kM{fi~Ut;-0&RDq7&tRiJFh|9EFduB` z1*pFGqksQ(I@ACCn|~I2;Q9Rns{RShDEk9t1eRtr@FjlHeX)1Er#ov20%gRx7RSpg zP7KO^j1GpcGB3n1Oj~y^(vL&eTKmMFV;Y9ZG+wfLsI%6^qu9m6)2te6raZVznj~pM zNUkD{X_Xi9I$EVR>hi%)QVcmn@R2Yfyx69i1jOJ$X!6nRI-ZZ36HII@hh z!|-S-9l}RFAViOtkG{J&Hc;x+GSpgrM|_0AO)KnRA~M21N+!%}lg{_>;MScHBr(3U zt)!qmPeo_xhBz>9o{ynveh)qf*iAlfKJV1DOLF0iMx#X5#$n(>FlV$c%0Em#%r8vV zhj9O)rb}QEQ+z6;?SaBwj-PjFKY{e_{6Y}=bAAo1isxw>kLK1tVc6W3KmZ4(n8C-3 zc_m4ePf-ftxD15CcSH^Y1LtELsdDMIg$vo7Q(QAwn-ra7IPRQ6plOH~^2{mh&#c{U zsGcyq-FZe!(S8{q^ey@ZtGcxV`ZR_y77$KwXpM50EJc&vHP@S z!hF2F`lcO40HR|HptXU=8CLhYl&rs$)G@908(|IhuHUO`zW9|y%8pNQiVuL~A@Mj6 zfx}QRI1Z@PR%*6+-MNr?%D!N_({v(=C}*t1yb4nNwdRDuI=_Mu`7C}7>N1qUs9N^I zrVsxV_oeKjkb*a*_xQ)Go8o}UUxX|xi8^T-F`PUM_Fh3QQjwin9ri`+anaM<=(aNb z?>~nBp)vkCAG@Hl2=`o6*-!;1`Y~GKO#fOx5&(x$IE)}N_%t{&ID%S9&(v1$_#KWI z5hj-VVbpLX7%qQqmx?(N>&W3em@D!XQLV;4{!D%{56wBabnur8S)#sl@k+j2l=NAH zx41$Sy#@<}xbEHqm8i?fmY`0kek8jXR0qi^$SKHT{{#p+AsVoe$p0)?dKwd51y`V- za7D8l{|2sTw$vf>{~VY8Ll&j)I~e(VGWy6gT4Hu3M{ZC#)?)n_&K(f?Ksm49=nJg0gBO8Y`6YbDv|%@{lJ!{ zs3Z<8v%Oen*tzx;g?t)F4rL&?dcRtOG?q%rH<@{4q#}1+G@Q5KeJ`c%q<2RP{f)Cr za{eQCV+u}R_#KoGRMBR0{hzvloSse(H;PDJVs>?HBkTC}B-7;93be!H93KR1LZV9`#m}|$HmcT3-qF#gpo(+k(Qg}T44l7@DAZ| zxmr8B5_OUAGGFTWlFO7*eDE&e!zg0Oi#)h*iMO5)!PgMn_LS;ei~(J=?1NR8y5Cys zv^Qic>z&AFrsRN$fA}nZyi@ow-7s*F`d`$_8MMpl3S=+^o)KRytLfQg%=4z;lKOu^x|JRkQTaOaaO0AjyJk!n6bv&jH3db#=VCc;KvZ^I3u zao>*CQX;{~utLn`^y{T{bDO`bwOmJy5-R9=S>=8ZBUPZ(cq?2I`Me~itS(S1Ez?iK ze?^m2pOYFaPAVSsyww#b>VG48`L*zdA(;DN>}FceI=Zi{D1Gfz`uf3AxXV6cl2Hqq z;n(_n>+Oq!Z_Dr5&RjV~9>z?jAQ>q&`B8K9Lg~VIQ!+663h zdK!wF4j^4xItNLgB`#;9Tx zk5;MHw}t&b9;gxUnizbx@Y!BjIkfe7NNIMMdFE!Q6I6lrOmCX#_*}c6wZEK_kr@=n zqdvF?o~FcfNQm_%v<{_6ln4*HpW%c9wLP`Nkxus)eqnsVY2Un?t7l)P$^#=V z-Y!>xM;nDsvj@i?pLWmwur_=SXylW`Jpi1lK{WX(uiaokb*tTpsnc(-(Z4+F{<+`f zf&W|!ec2g9%up5pAW}~m27EVMMq6V${Hq71Kax%)v15PxH+FyULI2aihlcS)%~sLD zL;~ia+x~8oCq7mTV9O1YHDB1q>L$G)LTfh^>t)>DM6 zXBaXfl`hhp)ljLBjYbN8qSl3F`D)5DGBMmE;BHgQa6}Z?+Gg?RFAx_%Y>A1f*~x2R z2sjcyY!Gs+0V+iC3U9t4d}Kq+I>FznY@%*zu}%*>ncCxx_QtWy3}z5N`kKslE$2}`&w)())3$B`o|ft zw28o56w{1{e9CVt(a2oYHaO`osCX$<2PXa<-)X!1-8$>ZP!)yD)&V${?@K(+EjnY0&#{-FAkki3wAJlJByt-2)f!5tSf#o^@yp!H{NC)ir zuhR2-=i{RFB>#u;zagw1+fy+3z>EE17_pN_=k`Er?TdlB*6HnS#}BG4H=&YDDw&)| z0;2H!Bt`>oxPMk1W34s0*w!?mz4dB6fRq!YOCZEYKMLU4$2=(o}LekJrN zz6wh2fcyJ;XbuLJoOc<*NKEQ0$1hC_usgEfbUvxr9RF)fN}rtUN3{<|4Kk08S@US# zqMz6kfL+~nz2y0Ip8hvyt1j(d`g9u(WVeBj$xS(e(18DB(@DiQCMeQ<9v zb0SHz&n5B8gfULn&E@i+S{?gigHg^)#(ST}(~B*(b~$?b&e7L*G-@+by7IqREOA-J zb1RY;1bVhtW%fVKofN!!K-jHUXC~9^ePL$z(`?L%qrQy|aSNfY#!)x;E9X`_FUyo#_z#lA2d3?`NeaGD}H4n~fmunKRkux+tOF zGK93jd7vurq427?8VV;M(>HdS>Gj9LDZNMA6ZH?s<)vl{=mkV4Wjt7X8HOQ1jO#0X zcoDoCfM_ezBW7tJaXn@V15g5rj>a#Ece}-+@*U2Yf{Nw*!b2vQ3d$o``RtWlVc*z~ zEGmpz^gnR3lhMlzJV=7CZB9>ry=1Eby=GN94^>JE2;W02?K8f)wZG#0@Wa6)-60zI zx$^2C0$Yb9$P-kDM`-Ue2_7~%#4vP-0k}fhV&e0hdxO0|{SSML6Fs)dc6aw{tKR?0 zS!ytoBYt9RNK5Lxi3{v&wqwSUt^tbP)7UWX1P)F<#A%JJ61CMOk^{P;4AZu6{iEM= z@SD5g9x4nsQ7)h8k7g?~>x1W`kgi;F$ir@LQcva{D9A}xNQ;quwFgVeKtl9I!&QAJ65~ICfER3H`p=w3KRS2RZN=)%CqE2}WcHPx>{FBeMhH>oGvPXbNnZl%n`Ae3Pw$ z>vi;>)v7ys#a)AbjK1uDaJ%&-fG*dRlM+8+>ih~Y!Ccwc*gOx=;T}lzh51D&NU!VZ z7ucO@Bq1tf%Sf|PdP9OAsR=H_DTi@Z5y@|PJ1+3#-M_Dx5*L?oUZ}L7$GW&Ace!2o z&I4x==h>?=8Nk@`vE}Dw@e40(w+gSmJ#~Da)aG@USusF4%Ew%GF;rN(@rpAaR|i}Q z&y2kpxF_Il-MkcqZQ(=m|ETKcuN3BBt$B1mGYZYa~W~W=ZxCiEWuRqAA8wg zC6o5im)~^92mnKybYNstk!PC8LPgxu3tVgrxYIEr9~S~Tnj07QBtg6T!s?UQ)75^z z6CnH`{`orz5Fm5OX@?&tj+PRanDvl2x7^z4(YaMIpeNquHs%OJ!K)OxCr}=2Zf&aa zekpId6cj{Fct4>c7=jUQIo&W6idBd?J4o~Dd0q>4247(9wzB5JSpW*OY1I9I^mh1a zkVV4-5uNu%<^t~vcUubM?v48g>#%2kuW;=*7ug@~!o*eH;9t_UELSJ0dU6cnr$-2RiSW= zvdb@<%sw9+SpB&2(KOSv?cL=z#g{R%oChMEdJ}Iw2E>9K=iXfBDU=f@t~kCm{xir8 za$}h)d9MQ)rw|=hs=!y6IR{89@tLyK1pmaa&&(i}1QJX5}xSlb^$`6Wr6C{cLK^okR8bif9OZcyEsB<#PSDWc~V_ zlpek*3+)40%&i&8cg0aEl=1Z9lZN8;{Ja)jTuMi&-s4R==vCz1n~X}YaBO%U^9Wdt zm8mKWI8Lv)zq!$MLGZ{yzdRD&2cQFEN=$a}+kfLfpGSjgJwiA}1lsSdB(el9C^Ih} zhs+8X_8YElZqx^WCD*Q@W}M8l#^0b3F_Rq11vm{3|L*dboHSaJV~1i*-su(sy|ac^ zgC@v{gQhD;<#SP^;LKiNw6kS%#bL$KVZ}kONe}xS7I*WE!q*beT~|7}7CJ#V6dM)2 z`LEujn2+c0x=7B)09ibVW1SQ8=y_l>>5jf$**st8W+~>pqUbK| zNIumW*w$0V&h3*CYZ8>vg9WrK`zF%v?@PRN!jg#x!v40t<+g&|$-rfv>Mu~fXa#6M z4U&y*tUocwzQlOZQE<^d2sjUq&%;$nL6XIq=ovB3(9P>-uJ&Keu`dcbMnlCWVZV{w zZ_HeN#{o+;I(v)w+E9Obd7v4p<#@cvSqHZ4i@K@#J{q?l9#l9QOVj6Y=J?&x3)jva z3;!V-^nGUNcS}jY%}c+U4oiO2J-scCzFwDCd1h9uggZV@9k|F5OhoMarD==G;&5Wa zb)N;4Xkb`__hCY+x5v?Wrwr8wHWodmUhfdK4;?mc*cEBY zc#Y@!xVyGrdHZ5%&$f1^k7AjL!M`$Sfq5=~syQ=zJ;rJ%D~ci@FwMJwQ5{+hJ%?fn z2u};BVbc36kCx-6Dyecv3Rrj;ybh)r&i?EtkCxcaUAwKLc?V4oJcob98UM+dpa zDaU8qKGosys^nCNGEscX+@aVIqk58B@AzGlSDBh>nP!)!o*hgeDc+|tlj6|AY>aQ| z8O3|42V=Gu7n(lEe}iq6)S863mo$no{64?tYdMPsB?zrFv#76GSY!<(nqT9#9HK#< zmZpZ8EA28_BnlEHtzIw3+aOCz~+*v$}7BaM{x;2B(2Bt#Kogq zr|T*gCmke-!bUu^vwE}kTb3hen1~C*9i@5$#_d!*??qsj83wV$@?A0A&@wrcs4U~h+XA#s!Eu|x^LXtpB!@-kgz*-jiRYGjBQf#C`8T1}8vA@Lq zEWI}ne7}QS{QXn~d#|VcQJo%3vE;83v!d(CM@>{%owAf?pimsM9#SfX1}`ldU zHy*K$+iL?G<3@{z&;uf9*V*}SOq-+v@!SihuGr@6XNft~|I;pPFXFow(EYFOgK0V~ zDcHQ-B^KP1Gfc)xSLa8^m*d_bVa80=qH;1*60tl9$v|ICMBX@MO&>_z6J%UX7LZN2T zp}MFbDspFyosVLX{!Z_>oKyZw*z(BV-YBvX@{tAiR9@HWN1U zybu%{Q5b#zsk5l7s52Cf3-JVX5t4N^bty33a2g~LJ{(U97q}h}p78o+L9!EH`qwT7 zzYjj#zzMhh8lB{a_vTf3ClGw2r^lw8J8srh4)pm3U;$85>niUEA2KZ0P1RH0E}{sh ziBTIe73e|69rT*Qu`Iz`z8Nk0Am!^J|JVG_A8*%dIbj0j(Wkrc$ zf9IH~q*6@qv%0wQm4*rjcl>pB1b@II6P1U<0lA&wrz+rW%YMh)U%WFL2yP7#4ZD@X zjqXc5rXm}0^i5x!U*pORh3L&D>C^Hgu69Y;-x3RdW^#en-c-G zv=1mhe#?Jgf#QkI<_d<#yLQH6IRonfKk8Pt9-h#wKXGBpO^+`V>VI0j!aDs7q2Le=qd;^ZEsi1#Wk=U zqO5pDF|^dcJ-vW_!!bzFg2V`Uz!6sm|~=5O2|*}z7w zNq1k&2-l~|c#gK>%Du6;iYtYf4R&;IY*#Y(O&9kIB^(gL{m=vd#^v#MOMTHr&;O6v z(j4hnXATLF1=&Dv)u6SFZPVdR+qI7>Bc3uw)2ZS`t2*+yq2tHIp2H)FM$~D-86gJ> z3l_5YAx|_6q)Vh$u3rTZ%&p#DSF2hi2{Bm}jL=+X)YOz>gvmHPJWcPYY+0aP$mH=d z)<-elwFFF5>g7cwi4fUq7)_cCWf&BKFLJARf_q3G_SD}Zr0sYrCqg^pv2jOAj*tHB zpq=K&528WLAkUz_1K0jz`tqBRK1c z_4?M-d`FD~WQ$eyYmlZywT2zA59y}`%u0nciN@T7R^b<~2YA$0+)N2N(i_6XQFF#b+b)5l> zqkm;Qb5o}KeuDuC{^hII==FgKbkB9aRtN+NWf1d(!E$=dT7H)f)#)oc4!Zz#0qll}7B@1grj6(scjUAHkpD#H)tc+-0qb+IeQ(%KYV%STG12_Q*E(I<6AqmK>Vf6l^v;NzOou59Oj^)~rr&21BKzZRvD~M7WHVuRju^qjb zeQ%D$i0itrCv`kO-qd}Sg!|Etr)=mMv>7kA^ksxZ156^qlH1lizb5U0 zguo73@B7REWytqO|D7@RStkH5nP&_c*%81e2yL|CEd;PY@$1n?mcYGB}-n}fJL9&_h>?s6dB>9H9w zowdldd}U+JO7iduSRlokv1J2kbkM8R7o#7={JKOxG@tEy_N|rYv`pPB>zgUsEpzyG zTsD1WSJeFrUQzR@e`&gkVHIKJAVO$v_sbrG==nQJ^Ka0}31diL19MRh9RgfGh#822 zVv!+jqF1NHi{d?I5`y?(K#j<_DA1C2X2C-G5Faf$v6Q!LFw7@hsDaEE4wWQa^DqFq z5a9nZpuUug@c`=DVN9JDY+nRIvJQ-q%Z_i4#|C-@UAbdnvh^Qd`t7U$W%MsveATG* zFj(B$LZd%aB4Nptq7X7~PhQ^BQ`PZ#xg0ONw7-y!cl)p1N@jVcI3;gY7hYl`rJ)_w zI|C^+2v1p-rx>DB{a%Ik!`Nyme#@*fip! z9kQgcviHL5eyNkQ%eTR7Kw@)bqrWM%Rk&{!aE%H=oEx9aS@a#Ls@xF9)1-_Q+AK<$ z#+Fr*Y$i-km}&4y2xfu#FmlG1~yaZ}N7)$_dB27i5R?&yEO>QP~sNdx?mvyQaw-IzZHjz{Fg2toqgx9{wWs@xS(Iu9?n z0Gd%Sx-Lm@)aUmab4*OJ)QSr781$h zZ}M0^`zkx9?rXm6YJbHycR+++T`6HtMF}N>d*KA=BRKC}VtdW+U48$FxngG9WOrGw z{?t{?tdJzYlAp<+;;|pfWgp6lT8fxDqONk^KuS>i)blHLZS(1EO|sF7+>~l+Y8qJ_ zshED&=2M;j2|By^Z&luFz%XXF_8TCS_6oxP&VchpQAvuFuzBY=_WOExZ3{N!j1(

Nb zkjziCMD5R>GGf(gd|E(7N^SpveMfDd0(S>1Vh7|X+60sF+cwH8o>LOQ{-<@sz?a+~8D(}(+OH>qLHp8{ z>K_}!nwH&mVb9>jmbpF#s!x1B{ullEZ$ljT>>2q#A3#I?tDnHtbVT!NTNEBZ&sM)^cZg?Yk*V5h>55)&UU ze{F{I>fUu4IYF1hQ+7n~*BDL@Tw|V*1%Y#v0Ihgc){v7G*vQ4#|w;{3l%+;^^EDUiv8Vqvu*+9$916D_PT-j z?@gd}vH^GKmKnd?Y`>k^ta0=aH$p!l4{Jz|F{NL@D#tOzM9g4MFYLzIYi@glEr$u>oAM<1G|IPtR|^S)dXq~6VpIr*7)2E5i%5m4^;eZk zZRJg(&#zY&Z{SuS7p8pM~aDOt6O1iulI-LY+FeB^si`2ZF1d&+r5}h6mkNI?G`Zy0UCA zlW+#?v|EZ0o#uHM?a{nGQ0eXnd^Er0asy6F5pZ8DXXP`adlidh7*Vm6=cAwuSAeI% zq#+Cqq^5FEX$S;AoB)0a#s{GZB!a`q;k1z8uv)kYj1fYHB=be^%g{mszzJ#037{#bb(PgJfz+Ir&Z)29)c+8B52>8X|3Qdk0PjS)hmMydd=GqVqcd+1z4{Z{4J z$Ssp+@`E=E`Dkx6C|{wu&5UDeOd25*s_k`Rnmd7CFa`CPaITU|t`@4z07)IvjF&TM zP*A5OVy0QP_;OJJKyX*vyn|A8}!~8ee0TKsSjY3uj zLb9b+uh(pe47&?Yi}ksj>afXvulFijN)Ioe@O{O-ud@#~9m?~p%9hLXEQG0EkJ{wu zSZT+9FpK>eX8%{R=Wpi&UK@8h$a-meB-c&QuSzUzQq6Vtwi@*ynGrtQdRp`~)lw06 zqtux+O7+%ssFtD~1xM4Lr$oud!#sik{IW2x?B3=})4{KKGFJDpn9DYh4ndqI9S<`6 z)O^M<_RJPtM7QDCXcsqW}HEA54xY5FhVxItY@m1u4k;5s+OE_C{N5Czvhm0 z7p`?5T^h&(RkRt_1!P3E^Z1w9PL=&!otrS8m(8iiqT^n>lzZP!H)iJZ&!+N{rE zf!2pWQmWR5n~r%IoCF4tR;sB*+m{q1EcT=H(WgB~XVG>W z6?PYSD;X#_lZ9ci@seT4BzC-NmVh)Wx_I)IvWpyaWHB+~Pr~L`$QT(B$_#=Ol5+bXa@bMB2^iR1ZNS8iCp#ZYwTU;jzyUj-ObmvRt6Ut({~YA!hDp&3xm9K z7TCb;fouJa)^+^NH!Wz`u#I!i#B>8Q_^YYo-#-75`)%#bb4Im!h1=-B;Z}QQrEt2m z0F+i0@1vxX>jb^4O&?Egn7dqhNj}GZ)hK28(ZSxc2vIf*-DBP8458Lyk?X}As|ymL zJGiBZ&!?P8)*HWT_47=%p*xk1{{o7=i_EU#{S8m;&v(JV8xnb{&gWlb99XdLQ%~W$ zoadde+8KKzkLEPgRTyFir9={DT9ri#TRX|hyyW<9B+xH9sVlWki@Ny6hS%#SB@M?; znp&2ce`5&#Jh1oszjpKF^C2H>lc3MLu<5e3_DOH5RUmFDB90u%Kpyj@#(i`Zu6j5m zrE2aydgUvUW&~lRKSM5$B)`W8Y#&XSPPV@=4cnI}g+BRt`@o!p?NZXvu%TdA@dpuA z%}mroMFQ{g#2@M?TE`Zgo+n-VvNtmVQ>1?~Ir=LRj4i+-ou44p;N8D1R^B{5fS#t` zw&*Jr(5@H>BqKO-+AINRsXYi*KbFn)N7dR1R_EXU+V*EXi!a}?eaxaXq%Oh-gL>jl z2R>%%fTjAu{d)idxoq4SqXm3%x9*btwBvEGv+3#slfa9>+*Icn)otO^K$~K%xl>%S zQ`Kko!%OgIi9zevpRyyrIy6099}SzzJK>=UmUtmiOF0$hV+a%jK8SQj4WCwNEO3}V z5*FF%4h#2;X(O6%b~^kpDUUh5ULoizi6UMNAFk|Sx+q3N;bYRDuO3LrAbTryUrK6U zH^>ON+{?z6fEa(_JiRQCt<&C|si(&?9qK4oXwv z^)2HbzHoeA{wV%gi8+8A>2Oo|?6QtPIo%WN?A_qo=*Fw=|LCpP6I>>mFoI8jndd~) zn-6TGC2qBO&}(`CA4{hhX*kYavAWLVr=C9fQ$LrgM;Nks^K7EUP0vOTKXzyhjBFAn zDJQ&V+j_}qR?}`)`9}YTRNLqmt=%i+_zcpPyVg+|m2_QjLww<=oSiGqzm~ z`RbY{(gnr+LoXVuUF*cWiSterOr78uif4;NvN678y6?w-r|Ee~VfmTDQaMm(tWWfm zn8iftL7YE-h#6%TyRJsYW#dK=yyWpVB#d2)iJjz@$tb*bt+}*Z@MHU3W}O{g(1)wP zt`**?826iT&mFg6Zu&F_j-@SIW0$#Cd+vII*?@TT?5Kr#N@pKcSI*n~3iW?voln zFCm*I(ws#b$jq<1i){;RnWEiPpKp$=%}BD=Z-yvN`X>=z=hT1GvTsAHfP+>rb5(QB z?~{BDVPAR2?HuWMn;uRwGAYJyTZ_)GZZCdZn$lg)%rTksMGvfcgf3uSYWeW5gi>D# zX8RLMdUt9q!9+r+H34+CvQx4oJbn;ypG3HF_CyEeW8u?&BrSdy#S0U4RX%RKSD!p6 zpKu%HxCb1imZ+0L}p=;M&R23(>eadTOl#FQ;?QS^_n}g zyT=@QVH47}xl)--ZX1RHiWpaY?W9JJz+b^$g-0-l-j8Go_qNrDl~W`}=+R6v)51*BqQx`m?D=&Y;Wk=G z6Z7zwEzGy$<%xMC1;Twz)Pm%Qk&=uw_^<`Yt(hUcw8B8Mke1^?A~ZUnKuRlhZ(R!( zxMrv;EPvVmbgA0;6yT3>=MkMbuCM`ky@lBL;O*SLb9qC9`ygq-6V0rz6R!8+4>d5d z*a$}loUe+25RvtPGwn48Jyj?*An6oQyuJ2^CxnD4 ziIfvmE)@!`qID#aD0-Ka~WPo+&k-Anl{qJ z2vtAZMkE`e0@DBwv8v~*?Pxo2@idpWmNGGe-3q;_gV9l&irTJq8RQtw&#|2rkUHeW z(2zcQH)^$R&~GQ99bdZktp;)~M#Q4_{jRROHg}My>v5>pN}C1~#0TeF^iCsH&aO=( zE&MJ`B*N6V8nzN{g(L-mIH3OBSMaRllC@z6&_H}in#62T2qB7u@HgN+s1eRiOjoO9 zBF9c18IFMa!lc4!8c5;4is&(tlZL$p5j{Q#879O>kFMN8H(}B7s{^n0@Jc^%m0r?; zSo%M{^~QhzL?#iZ)sxpD4C3 zlx42K?Z8;(;ebV=Nlj9whYjS9Y3>j{$-H(EeQwiZ6#f5j_a^XAe*OQyq%5fz6e`P@ zvG1hFzK?yEkew9SN!ckgC}wOadt}K{gzPD0E2Qk9EXf{{-TcoCZJ$q{?Y{5-eSaUn zIp=X*=ep*?!_2ju^FFWl>j}|2Pnn_|(??{}3Wo^Lx*%k(DH1`o($T@>F(mS)1kq;| zZoo>>x}U8NNB?*yJAe(|5o0%46rrx#RRXoNAh z6u4mxXsafkdc9#4d+Pg`(+d0G2SjOInq(ss$t|@k(SZ~(Bq3%8*>vQ2~jk`^?M=rXUaRSQi>a5yK8nC~)9m@n{o;>#$NvQ2?D%vsB>N=Ip#sP=#eus-T!*T0u%O zH0&5X1yWcDr5Nea(KEwp_5j+_gF6C!0VR-e`iZIq4L2rEp#b(AZH3?oF?gbC1a|1j zTLY{MZ4-&Lyda1r1A`ZwnSTQaK(EE;0j&C$ucW50irs&NYyyElkiWpa;Xg_|G#)ls zzE-g|G-GrGK|wMpJ}Wowbsu@*J~fo{OZrLfU0kKeuDdEB9fBE<>l6{}M9Cf8MzB-> zCVB>y!O$Y#@j=SZUB5M&`=%ik+p0I`|aF_$#|=V zHHttR8I^(5VIpNhqS_H;IHnUaNgnfre*_bLGy?9@$MJiM7c^50E$s9Y{LO|0g#HP3 zTwZ`4Ytv~Q*%YH99wcA|38jdjl?Uz^%0vS(2yMRH&i+=9oZ&2oj>?1t=vm2~t*>8A<^mAPFD}IM}*%Wl{=9h5{au z->ft&zJZ_q6Zj|kF?ksPetMHNjy;Iw>rxmvKjk;`VQicH6j`JFdF~x%7czYpySrdE zf-+2sNy)3Z(Iriim-HT7#b}cV;^GK z42K|ST}fpk6p3^+k&5CS+BRqudyFWNg%W(P0G%+YQlg^p*PSp^@@NZ6Ylv!qf+j2r z9nK$vu(oK1lObpYNu_TnszY?xDI>*W?CULG!XXy4u1&Hr3a=0%%!lM)jq-*hn0IJB zLPUT(97c%VMM@ANtu`$_DLyTJi#w5f$Nmr9Wc|&5%%SVdl4sRUMm$)_ez!LGIe@u; zI}f&sG~4PdlXCq0`T%iZA+`#;;A1R?PHAWW0x>)oitkO$NKzmOh;ZK`pC$w+7&%}# z*+S(Zg2>F;i(3;MCCVL-RH_$*GldEuvd=$;X8J{979;n-MR(s)NlF*yz{K)LC}*S) zg!Ldup}Ls-bJyuZ?zXeAT5uj$ZcSG)85V?N!kHpY)~D995K^*9L%T5?jZyX2bfC=4 zV28F5cIE#TZ?dI(Nv2u4;piReZU zt0>D+l$!EgsO-48otB+B5TNmaOMj!bV=G+kVGFJa6Ux#&wq?u$Bt;5>#T6oz)RLXYD6@>2pe^qqd9TK=gTU zNzqs9uXS4}cs%;D(om=0WG=I9v}(a zT%x+a8r~sp6RjS5JxV?5dQkjczOSwVUHXAhsn)c#LbLG$8g&+?TKPR9pO1L%&m?>m zXe^zgEd}+JPxKaEa2b8wtoY!YG0M~61LP<9-#rb&g>SymNN^MM|FkCM&Jn>Pi$_5C zYI(zu@#s>*%!!j*Tqes@W`u#ToM*PMANxp7X?H5kdP?KF9a_;mDQwFyCDa=#lQB z4P{2sMvx=fBcUT%1qV%U(_MdV<#MyPJ^InOOzTL}o>O7&)U$j9pCm86+n~ZBq%7=q ziY@q8mbPh9A?1J-_0P|eUz}CIm4GKhRhS&w#_fDXeboP*z z*d32os>FBPwd%$PsAkK%<);c9RuJOR@7dbuSvo=J^+#t8{NZhl+hCJ~_v zfvj{>^DzYd$7^{qi%6Mf$~js>@v8>8s@&J0l&2z?l}AS-LikN*AJFI~UgN3%q{8ex zIz@3ci0bZ9Z^^m%H%GIYZ);fV6(l$>^j7Tl+B#9aoWN-${Lsi9^J(mr%9Ak$PvC+# zoXk0Owsb1FVl-Lhv1TC7!QF)DCdDVpce2f{d0D_a$I=BiZG(TzY`d_0Ukd+~fb3Ke z{qR#5soTin`1ls%mYDD5^~x(=lTH|A0&{b7E1wU;6Y;{~9tT;ApWoLh`yIQ9J1{Bu zc|jKZNT^*BO}e`Qsx8bKM&7uiOL2t8nTLH5wy#QM_&8izdd1i ze!%peTbFm6(T72vbYtZ>6c5zkPJZZ_NFJNSk~r5cqZY%~>b~U*1BIU7S7zHe%8p%j`XJ-LOooaE#O0Z@6uLkGP)>G3jxN z;2Rncq>_th6jB?hVev8vsY;v%pN))^m+;MHHn)?$+7vRa#H>gv$_<2@gF5>tg?AJ1 z44&c_IY}a((I*JDgBcii^Yo~SdotxYN8P}NrSiztds%4?P{6;$&~pN#*Yk)?~}Z`k9jp6)kHc}qlz7kbEJ3hURBBWqG z{?&~D0i^I|LW^cB(`TPfYu#`ER=N#=BDQu6i)Yvy{gQt44|c{*c51Ld6BVSkx(Ben zCShPw!W98!X5Dq&dif+~>SbY1^dsx~wyDJV-cdW>F!+-T(W?EO^e0#^1}UGy+2OzB z`O@NBG~`g$uHCNv7?9|Glg{^to2PztkN9>uZHqJHk%0IGYu`63y->h6Ll)O6{9hP5@qNLdE-V_-4Ni&!SynnI5wb4a@?odYx>M1X>IabEaXD-`-hJ6ncx1=F^rTR6ahpbiVuK<` zZ_Uj-`E6jl-T2RuOTpZmqTsd4B5sm<-#ABw*J=hYZ*?Fz6Q@0M0ktaIjqUd9r z+nVne<`tKh@$ih1=W@Sd*)V5ou1-{cGxXsI8*%34BPIho7B-+ibxfW!gi&I&TH>`> zrTF`vi{vKM@mjNJQ<(}Gr`-#+Dr*`B3^EL|hhz@O9v~xjE5V_T+`h1&EKkOCr1@Bg^HT-}{Nk*_S^w-Y)_ZUtd|rpOK)9Jp4)9P>ShAMayX%>Il~f+Cd#eoLCdwcc?m%ZkniXOYrw*Qb&?S(>d7}+eBc)!6^3Cav28Dx z{k(Jlf)^G*0v@N1EN~VWc%&K~jZ?C0&TMUL%7*PhQ;`y=-7BR^ctX0md#Z^M;vy?R z9q=MoErjvS1|`LvQ-?VtnTc7WnfL7>o_xfxj|GE=9kJMMw#`;&^;Kmx7m0H5+-kAK zTUF!#1hA{@5X3#cJHLi)wi9)5;qQOzg`-Sx?{JQ62^sBEzDP~2td8`o`(o|c2CZko z{|Vw$v=pbfimn*jHh7D<&!%6RPLT5QS!EfyNULzi6uUfyP>)mOmTc~+)d4=UJsBYo zCgLr#XY0$OewlsM`8d~EkSiO12>1_Me-FXIe{@gyNvrrDnv3_kr^mxNT$s28gq)iz z9}tH*y@=416zsI;_lOWn1g1~##}1_s4+*9mW8o@%XFTjJB7=$;$ia>(w*c6Y*f!+o z+p6c{_gy=@BgbpMjY9vQ*aotZ;|j2it(<0rXQ+*jq`jnBv(PL;mOQjH;bv&9- z(4`1~$nI+mNN;L(AfM)`?1%CtBZ~cXKNn`KiRkkhu!1`$ID4X~lC+Z|SIt^{+4|E3 z*dtU}AjtYErTPk`jPm$|B2s>fcX#SSgTf{cBUj=D7f%Q-ilAQMdbx?2v6``wQJPWT zM*85b%>m;qkBdp26`)UyJIXF`DcN~)qTtrA>!01>Tm=%3n`W!&uv2r54`a99V@FRe zTBn?EwbqLwC4tEk%I$*eW<0`>!Uzki3*=%bvvE1UlvhR zV@xG)wB;Yp$*+PKg$_f`HRf5zKshL3B&a9K@1f?9ziXxvblDSMJigu*{#`c}Pb-tuMvVLT ze8W;3j-<48ripj$!^E)b^^n-z#l;V!^~DCt;ruF;_inviG70iLn*L72b5FNB@>0ze zSzDPLd!a1TE@HXQS+QT(tX7Bv7aFWUW1)cuEZ4GBKWC{fu(31+MAzX6n@O5yc+2$9 z-5NNa&gJgG#yCF?s#IIRl9U#xvs=@%TRtEKfAGpv98sbQN0eAA#uFuk2A=(@^!*~u z=a;!ZsW<=5h4#Sf;$LMU1f4$|AI3}?zq~ZFI5UeI|M=Ccf2m$Aljs(G@s+;RqMg~K z(~~J{wN}q_AQ(?G^>X$gZ8&S85J$puyK1KR&@r)a66iV+>N>Jmwk-tBqcM?dDnF?eL!9$*oL6$z_Z>nZ8?@YIUfzErmuLwZzWe-7=-6Y z>m+<^jvn*w81415e!yuQEvsBI(uaPed**IQxNO`tIGGBqJNriqt@ICXyKlRhs!FsK zzg?GT$rrh&p8NXz!@eB*977(H64%ZauzCpW4tDCf@1lbn;CY#iqcRN=$(UoLpMD0p z<86#mku_BpjwfII;MX}fUQY6NsPnzCQ=+$jA2oD2QV%!Ju#bsZ+`%)Q{`_d=Cdqv! zkVj~yJ>#^3y|*bfxR^XRGl-dB5Nx{J{JfF1QL#=n_%LT77a!BTy#{3WazqXG$_4^2 znzjlvk5hZDddQZU_qRLth{Wtu+~Y{-E5CtSf`GVTQ$w^S2Ytg8|DCcOISf8Pii;Hj zz23H+yjP$=kI!9Ux7s8l#44G9$XURH)lynIym@oZ=_iJ z<||ePD2}t|l;=p)SwkI&pI<)mK8SB!a|Ua*wtDCAGXcL(bCTyi)SMgMOekI{4*z1? z7N#(a_JQ8M%TZzZb@3?UEXUz6nLc`4>Do!F2SnkoIgdXz;{H2n_xQg;@U=@I7ICkN zJeUxMM><8{C|Vy%Xd5hRXmwflm#jnvJP!1XYehi9jOZ9FVwk_!Wl{*A(jo84e5N&3 z$R4FFpRS67902w~sW4~U9_z_xA-TI5UOmnlD89gcJc5kljp_yV*a$Js{Zxc!i7E~< z%nvBscJp+M3+3Ks65voDs?fAx*-$W;RL=o&ow!t0zO*FSiffK!{YE0WJl1EjOCkZY z%zq6pe7WpZd-=?G$^HwsLXICeL-A1boUHrWG09NPwAUZqKhx~Ei^nb{?d;lq4`9`ExD%U7*p+%;T5%eJ4agID z^EdjorwBT)>+FeS@u0LM<~J;*Nn)x}dm2bf8KHBzTEVJv4B3X!l#6mpTs( zgzziJ(5{47-j6v>8G_NGP#A}eP}(E-tAk&f^uO%Upb2?za8Am1eQ3z@poN>}3E*>U z)iE+`4tpFLaATIHkL!`)Ifr+>X~lsd?@!~7Has``-ZZ`Vs_nJb{U9?-gq_>`bn52v ztUt~Y7yR@EQ{a+YTGG|mZLFRo;@pF$N(WS=PjYdxr$mU%KO40qI0wGTc0-2+QT}f`JHC4>OS=CVD zUQYzgC^sclHN~zGq*FzjgwWM@(*~weeKnDpvO#J-kB+^{d}#jUBM60Kw1?%s40R7> zC`w4338DW;(yeLD?Nnnk+V$wE^!>Gj?e1Il{6*gIU9H0fyG`qp(p31Z$J+|B6Wkl? z?u^owld&54YPfz*HQi-c*-{80M516w%8&q2Yi)PE=L)&6`>vrv)#<kVA+`kQ(hJ_D>c76BXb=$cBO6I0rM*3xXWSyQ-{EAd|(1KJ<^j-Kn z&4(ePjNHs-+_~zP(n%_JxJ=))u0GRE3W6>bhutnDe*R`@D)L-A!e&pfjCpIkZf0jO z{_@Y#KPK)z|9Zfx%Vg@AiS9G~u#cJTT&c0rxwd+__Ln*)GDlQ1uvKcU54A`+wA~Pkl(fx5d86|jJ6hrwq_Nl-B;@VPz#73*2UO$n% z^ruwq3$bI;TGqoi+J;eyN6UrK6J+7k%%ny z+}thKE-V2SykLyz^qYj){2Hn6A+LM*(RxJFe`;E8=2?xO7UO!uSH2QCMGsU0i8pT;4id2{_dNDq9+Nj?+N~M$Pyqc zl{%)wIG_|rKu-D*vLs{Pep>j@e%v|nt$SG(sd>L`lWtlj4m?C z`kE!+PEaFBldeX~#RhH;z4k4;`Ka5)p26}1gUH)c;mQ-->mWcF+oGupcw=i$xtqo_ zRnK0CJ3jI{^nS5WbY|A#1FyweS*KtAmm$n59S5#3>^EFadn`Z0c(~Zx#*LD8743{ zzj%Dak`)2tQ=Wft_z9fwkUh4-mAxL_ekCvTMVnaEP*WPo$$EJ{Y_0JUUn?NSOkaFI zogaQP|JG&i zxnj@dVag%QQ_{5bM%sa?x~|f5H*N=**@`Md%8w}-ut^~|R9v`EK>3Yvk^1dgSzHTB z&DYKH|GpXbul^$5p!+l!qq1oSdIhE>51m-SWw3AZrDUD0;oS5Rgc0SW7gN4&&K-~& zdBe_Q{wcVmMV7%>ExRe{Gm%)U0!m~q%ky;l#BCSIa|HZTaUD!zSrA$Ch_|`amlI=p z_|W}mnfe4quHpue)#c>-ok@piOlGvILOg;GVtTZS!2 zq}sHzYG1%74n4?y@v;`6-LE_mU+ji2j`@x|BIRwVGH&^IhTJ>H9Kk(>?gHwOX&tGo z?XLf~BCK2q2ZA)slGeL7BY{ch7SCLY*96^9q^F~w3GuT-wACXx zIYY#EzlZuuKQ(f$s0j+>y=H5h=J4S|i+xewU}eA7B=7Z)GgH+i2hs;B65fx!A9G!5 z`SP+%y4`(0v2?pr_xjS-j!?WZi)Hj^WR$Cz5=|Kp#+BaRO2{RwfT zSzqW4g|YzDE1B`62eBj?J)(0=b)0(jF^N6@ionJfmlvJcGtjO~kjNXBeoU5QMd+jW zdXDuwTrx~SQJ3g#!71*Rgzd=;mF~_N-?L3RYMfLhr3G;v6~-#t)6^2xwLcZRptE=} zPw>7!on`zs-S{^fd-=^xd#tUtYJ7v+s2Ug+B~Om<){36OFtIgP((yeUB!EAGek!Ph z8DeYlq*a(2>-G}$ml(KA>b!ZHC#SG`;?Zi)K2kMNIyn4jh$VT9D`l9VR=pyHUlIVR zzb_RyucP-gPl;JskUAK*2pV>Nlqjx>oX(FfDpe;UBVy>Bk?ee1D#)$-rXfdNm;M0{ z*hx(xk=0in7j_IH#;&KF&8)?o8Z3>Yu$1HKiTH9a#eDjQ=U?4Z%=s;a>@UAloXhn4 z5XC)_wLSiuPq9tQ$u+#Q;DpXR572x_+T?5l370& z)544l(HJ4o5fx=&CO-@US$gBl;V$A3q=~3lJ+pbpL@0x1N&Z(vedKsXzAvvwF%Cj zngmm?APYlNN~4&}Y}QZo`U9Jf9ABkL*SHk-Q;C zT=y|GgK;CFU#`J|joGfqXgZ=t2(<8pX&@spWV_r}oY}!70gMEWlytbIcW9^V`=7kX zetWMb?Xft^bk1(g-|X>tC8o9;pI&BnP0=6gkA__+_r5>v6t<@qrye z(z%L`tALW^dA;-OM2Ux@O@mqRyw0V$@=@oF8v_?u_)SFidrssysXw&pYR^5arwa6W z^uDk}?%T#(I?csJ)K&LRaj7;Jxl%g>Q!&ey>DohINn~7*FGcgl3@DdrI?)gCRGHA6 z7IfA#Z>Z4ppdUC^#pP}g8xl}^-GP092mqqh#N;vBc0HESf)QcbT z`2Mg~4AO>3v&>i9wQU_-2ZR|-f5*#HAwwVI-v-28{j$ubWsRZZ#rK1u@DfbQoseF zv=pJZEF?BK!DjHwxBV~cH3${=N{A5Y@N%$5h3`dJK_5W0%FAw-&H^Y#-?RM@WHF2t zV44`2O1nz?d1YmV^gat7z7#hLzomN8^W5}%0AC6R@Fh4NzBFyIQW$;-SM@zK;jWr+ zgmCm<);|c-NgsV4TN?Mu->kTQ!>=}Tv)6C2_f}q~_vXpB!24v4K9FCMbcvAOY(IJh zz7WqeOz>6BSJ!?u>ND4jNQIUU6qE9D%q|->b3$Y8)u8B)Opl-fXAxF>%ro_ zfv0axpZ1!$tmE@I*1F&NjR6l(P_c}w{tcUEueRdUi8pFTuza7fs$h7z9{ILrWD5Ke z-0%51hWXE`_i_G7#l;V3yXXt4VbU$%{fsmkx zLR^_e3=Zh;H6RAs>opxEBdTmPM!pGVO)1bsJ*sk1WW@CP1CT`D({}=-$t=y8F3on% zT%4FKn7DEMYjNn*i3OM@AaDB>2Rz{qomFtjopuyQ4s<+A6aLJ8_(Zp8$`}7t$FHEK z*76-v6Q>(hmT>aBRjFAj2(_gAHEcBHs=xwMvZ{-8tck1#jKaeI(29A)M9amV(wT6l z?RkxDcEdREdB8k*@)V$&9y*Ci;fo}=79QZi4tQXb{&!7R#KJb{sSW;p-+!S6++DX{ z8c)gQG3S?8e9w2gtd6{yr=WsQ^VWTs%~|t+96S%~0rm#cQ0Kxi_cL|W zUM85UwIx_;>1NZ%&?LmA!X5}@NYYtO&jkpJ?7F0iNYj*qTqV!v)JO42#~bmnnu=E$ zS$iH2Ka{C1o0$+<@J_^;vuFRQimUx6V*@C23H9nC&sk0Me6f{`4`_OP=bgZP_IL+D zT|z~GH6o=WfYTCL2E;5--jdZNQ9RwGLPy5}KWc475>teZk=0RFlp$4OrhN*hwg#PG z0d$CovI9e)+J>`$ziQr_s*Y z^lkN5(yN{KFM($@1@2kh8==hQkENPhuVwW27k3(3o?pe@_MaG!^cQ;c{}ZnX7s{$v z5mX?B1T#|EPB~u4FVV;acBvy-dHQljuHP+7F8yWi{-*;_>7Smm1SD4&;(b$%*Y91nS-Lee&*rLp&}i**znghl z^E2pPaJS&Nsd8*1$Wm6*N5#ZB^yr$2X5Sl>4IME|&NGK4UiPiTrhDk#17t^OVOAz^ zNE59`lT5DS9;imDLNSWhg6bLUT!<BJ{@Gg3FGHSX3cy%@f5txfLs3Ha+=^W<2)YU8E)*4DOy$dzKvW%c_T&wsipYu} z&U)_}>$E+f6B2Ly(^lt_R_EXgPVj|`uO|Lb6*BjCCup4y+)?RQRW8OWgPtcZx-BP- zC!dA>IgZKk@rd)uw+AGZd#|wQuh@kzHNY1Xhx%{x$d-`3;nK>(8{zQ1z|ogB7YkQI z{pXUfHD22`ZcDf$3h5%BTg~6xu$9>UiTtmt`(JMb|D&}4Fks#-%Q%B=y)vHcwlvR+ zy(pFvY5!#v&=W(CEe0~C*W|Dim!HoKR}HvYLiJLU`D&QP1{X!_$tqpU^wZO$fKX*^ zWPOy}@5Qdu^xiB^(?B6EayGlu2i2O4OQTu0^Md5I-aF-5L=vMQ)XZPI);fecpu#8Qg5BG))sm8K>$Jr7(Jaq|~( z^TG2G1b7x5|>JymCiVxortWj2&H09?oexVI5>ZE=CO%gXU8GH_T70r{=od*-WmVH zp8ukd;1_@D8~T?j`*D?Ydtp_MHXv2w(*Lh+o^@*7a1&r+RV^%;6Y`onFg|!UT4u5X z$@Z_Yl5zwf2{vG!H)+>Wt?O~ECGooX?doH4#v z;@J6er!*^Pg#BERe=DI6m(M4Qqa)Rk%Gqqwkvx{ZN?Fy$V1I4{@FQN{SGD8{mnG(J zpyhu}m;aixPxp&Sj(=g-+nM_v=WCW$fuYOi+OnZq9UoK0vKt`3L52$wep#Iw$ay@d zHJ-%;v))ZNbtapNr^x)mo^rSV;pBu-wBu}k7`dkd`#>~N!;ay?hXJZrW`z@LTTx&0 z-{`9q3$^dP@mRZsYkbWN`(e#unB6&f{POj)>0jNbL)yRbTDKd2enI}DcL^p13#@6G zkK+tS*OrD%n^mq{-q>R6pPPfpBgsh)+dGV+*)!4T4|KAOwwJYc%at&_w81!*j6n#s zA1f-er?XKIR zvDQ;lI0LDBOIw=?)GqTsmZJ>wzbPNTUPP*2nO%5eu&-9R zLijPkfh$3ocIRVoFX09tldy7p@Y2SfAlS7x6qhS2O5Q(Vyd`QjpQdQg-#?wZZ)r2Rr?;rVWg76O_qG z$>)1j@FbmVye$no=BLi(@23nC(7tyk1OfJF8$`JcKl=V~fA_;2`2U4w z(sOuoMA&(!sqSNjmDo`1jk3EJZn$15X^ev0wLkA(5ob_dmYa5eMz<(erw7FKtys+G zc^}L=*-WyW6cx7-^e3%KRvPT$G#)32csDW;?{I;BuSB$$e6g98pv}QzFFrmH@(-M@ ze%V!RQ-3M0srSr*t1f^PZrr+5Fx5AEYS^dcg-=Vt(&WqYIP}pSs~rcSZ>#^15$-!M zvJ%IsMgUQsFli0P20Gi>;FVB#vCzlQcT`?JReltf`i`eKRW0pH&fjp*gj^*ybS>zJ zm75-D>FOZAx<6D+;9Q`fr*+QF)3}m%gskpr+D#ghn^q)2)Z)PIOA3&K2=&g>En7H@?v9cE7 zYei{Ochc7}kWSx=ETd!@+~xhTlpR+H><1Y@;a^b$Dk+n~_5)1A5>*maJ1blhS9U^t z-&X;{;D~SaKlG*jtG|Z86Brm%F@Z1Hzk6#avR=Q<31~uSrsh`@UZ4n&1j;N>JqR^6 z4qmsOCUrA~5*4b-mua}HIWQ6(z}|jZ;Jed{*Ob2mFevfVv~e)K-d7z9vR>Xw#P*6i z$X^AX-oS^&GJ+k?-N7*$^Ck~sYjIFTtmEn7|>v55Z| zeih_o7m^DyW6j?BNe*7Dc;?kmzbLx2dc%_N%8)f=Me37YoD|&!vUSH19KVY-;_My z($SO4R?yz}##goS@~!K4vU{dnr}EtjN?Ol6)Hh}=QFjRIqoB6zUh;H+gSbeCBZ^3zrQb}d3SBU!3GcwZZK{M6c(n``kt@pOl$&RB`2dbGzC$V zy!=PtMx;wB(5G}A`SgYgx9{!se{RH5AErVr$j^kivd&gi%KIGp9CD^HM;?P=mtjd+ zti@TWR2r5bk=7wlC?!(}Fk2yjx?w~cZ`Max!ht6XG6ckgDKI3;Aw&T7uA0WB^4(&!X@VS$L5tNxYUy;DSt zW5YhT-t*-jD`Zd{ct+H?>L7+T8j2S&JMEFOT`7irvv~lc`NNu*Deieno@v($ogq!6(kRg~wL;(@%*~q__piw=e-d z%Bw5=?VXky&*?jq`5HIM8r?8`TXt%^{&BMH^qu6gNI7RSLhSTM zaz;XFT371^3Jrrh@N*6fd-YJU!xTgq%S7oC()4n|dK;5R5xfja)xMc*y_epL2vCM} zo(r;%=6*sLrY7K)L0<5J@}yWnaR1oDz3M&b`<_rKEbJ{+KkZ6VM|FIds8mhAac`QS zImv+u{yrwM)xiR_47J0HnJ-cKC_KlkwJ9hPZ z?5DvOiaXy;1Ne8^zmc)xG76V)5U0Tdir*nlwaF*W`uKS0r}RhiY4;Jxhr;&Q7z}7} z>Gw(3(W)ngRRpPM+>8&D?4TI+xqsECDF5!|c7Lh1gtO|eNNz336W?lHnS4!Z8dq_2 zlF=aF)Sh=hp~?~%(@~II%?PTZKFKc?yyRpA?ya-wa5`uRN+uHZReWihU5vI(e=ZSr z`R1q%GUh%yhTNBHSF{)6fu&yi&gV2VWIx9!d9U)2tLnu);L$l#|DO2Cb&w>F zt6&6x8wd=Wef+M4U)@o_yM3lxO;}AB{VsR^rhEUX;qtrD!0$&78eJczZixH(`QyZj zTT;os8f+QSFJ|TCnK=Sp(GJ{>Z2gDur|^qCSraet*%1Gy@lSsQoC^2>1C_I!a=aTg zZmKft=F_Fo7)E!RmgC}G>f-7rYIH4DLJ(KNFWuBg={O zAVD2ir8I`^qwC6HI@4OR;GuR;wXMQ1v;1(dv#Cv<4YLX~CYb$NP2q*fFSx~Wb5-}t zs_yg(){0}UoFDZY@1@SScWa%TS{ZpXb?;iYV*!)KCpM+l*`#BqD%|yE6J7~bu*s{O zi#f=V@>u*}@<}NooZ$*c7y}j9uGHanY--f%7QUHU5(AB#skP+qi|TD7ma9p4D;6}b zJkF5?tR7Oy2>+sf7e)U1f%lt^UNTM{`Wc2;!M1!(8GoE&y4W2l=)pHGX^n;xird|y zShwj>cFsO@=W{>hk&-6kJA(jtc-k!I6{psvx;6_3aiP7t!0orPp{lZ>qQ(v^e`+A3 zh^}pe*13J4uw76BWL;!vq*CP7NQFQWRK4;Os0A)-0~Q8>lR|fMG#4e_!!5uZ-H~HE z<>=2AS^r=w4DUJ-6LD_8A(D=oLK16%GiYO*lJr|V(={crVP<{6ezL%Ha!L=ELmSflDtUd$u~1qH;SCHc|DmY%U=jM-$Oe*Y;I+ zL37=r+8fy7LgbDPU$UX7&rT*8<&8=T*wzPmgf#Q&?_w|v=T(jy?u%MEt;bDj-;q~- zOMN#(SorCud1>at0-vX^@W-T5M&W`R6$pIj{rJ-vpX4jgU@ui}?Lg6>yE11r2PnI7~ zE-!1I=j0Kvw$7KEwbR(eeBHe3wquT0m6acZoPL9;BC9Gv?V51?N;dPn}I>>%E_?sz4F0S zBW21cwKCWJd8S)*UH$$x(_W5vcyGvGgkN8r&M$Eo?gGeJ;E{(R5cnvyg>Bdv8UvA=Z{?dvdq=AcRxaN}_4vlW z9+n*`V)8E0)p0ZhX?&Y2~>i&((2|E5R#by94*xBGMd)_SM6``_y4{^{Sb7!8e7 z7k&(^Xp$MCcdTfljbLxT=zA;z*)P-n*Q|Sq>m*aXUQg!xpTDdthQswEsfiy^3l$2M*wDxsM;<8+qrT7`=vlIS+C-QI#S}z zi-m1OS%pF=QinEP*dkzrw6&h-F@H*uEI9ouiw{HP-mSxJmEn@3Oul+i`;!pSp|NsN zfg49d4!+wAAH8zr=B1VhpTmJ;CYjNP)Le~@9FK>ii;au~tQ+9yCXf$h*6AAxxIZg= zfpx(_L6dtraDmDtGsK!NZ#*a4&J8Gh1L!*?Uu13j41qTJil%+;Tay_|VA=O8J*kW^bPg?I6t{?*FpuUXK)g+;6V zM!`vk{}pPak4#KI!j$|eMxv#*USm_lowA<0oUJ{T#;(u z!Y;w`#dHKJgOn&?IEou`E=)$dDUEyTE+nmv)Z1-}^dO@PA%r@lW4DC>EMQ-3y$nAp zHe+wPxhRnwt6dZeDe5$nl;P({rPk1;(11R5PjtTlOXyF?gB?UYEfo(n^>xbku;){K6`8T&N8g;Mo~@9BWb}vje(|3?;5KukejvAL`y5SG4hztXJxA*MvfbQ7tUEA3qcbD3 zo`q-YStl$lF@kW>v*a<#^9E4$a)HEhDUXGk*lCHYo#F#8tJiCmXM=A%AIanVHuZr= zDa33|%}ent)bdP-@H=R|d7LAoyL(yaZtHC^hlw3VJ$_~X2l?mfze>UXeXv4?_Bj); zo`C>0A@+7wt1ouz74}1fU(JI0xBwhMVBw!{8;rA=Arv8uAU(ZQ$%Xvr7;GgoktwT1 zs~X@==F3k zl@Bb5oC>x^YJ?@Z?G-}PU zN_+=!$!qR9pEBE9WZFMI6yrG%E|=ckeYW;8fUFb_*8aV(^LJmcbkg4Ay}M-;%Dda1 zSC{cMV1u##*UnUQf8O-7#>fYByonW3)w&~GqAAop@4v7#)Z}l+NEAknIJa3qM1Gn6 zCV7?{)#FLhb+a)6MnebXF6PHjt&w5Vw9R?i2-s&zBNUUh8dQF-1kKxn33I&m!*ix{ zyb~V^czXLzDA^_&(>%i|gTfUo-x}X}c<}}ZC3IhDskm|v)bLA>z~hg8Cl-F$^W<+H zhX3X!KL5cLuc^GIiq}*EkIbh9PEt~lPHl@HYG=kHFCqT}$>K{-y$n#zx(+t9&w;)yN+#4Rd~E56lj^zQ)W-qVk(Zcy!%{1#sB>5*$-1D zz6TkeJWd@b1k=1VFW*+%bcyRfJK@e%x<85VrEkO(&7kR6by9D2QnRqmxfpHbR81L% zK;ajnF>d^s0Q40r$F*0VJde~J@(E}tF35IHm{^VblyaBeAOD-A4W=-i*%~kBp~)G{D`2d-{w;VJaNf z*522&LVJ^Aq}ykdh0es&$Q4wj%P2rlJk)21Zmya3L!V#Od7PJY`hKjmRo_YK^-@Qh zy$=Ev#88elkO!d(GU?{$x%+PyU;Hvy5w6uD7pK5OW<>r_)Y`Q@6RlO3CI@^&@4f*! zt1Vja`1aN`Q#p~Vj(NBB4;As~ooRRvCJ{IN=QgAos!t77^SJe0D|snPAId{==IBFa zG2a6za#`&YpT#ck`$}HQ{tGq3@AVD8+XHw@^_A_fh&ShEkF6WlCk#DTeLK$f0u3j> zJ=4M9wsKy!RPGKdUops*A60aO>abFV9*uqv5FYRljdTSW%9~NBw_r}x1_q@hX(BM2 z04^YYZxz~`L`V-w!?GwHAZh^$PM~2;sOn8~5_3l076wIAB8ZZnzA$v zl0C?G$+Iz(lL(;-1a?ca8b(2i%NNo}yILqxuCsBG$?^=lIK!CwStsicE8m)oQh?ar zlE&O~_8E`<{J{$y3mrY_C4a6RCVMMUr(|Qyo7z%LwFM{8!Agw+ zuGDJx_OZ!8!!n}P!p>pz7PxL9TpJ4ztjb#lmupqmoE~rOTde)Z(wN@sZk81F8&@_| zHn8upV=K!WRxjd>*DqmQ1AzvvzX>UE{8{ZPr2s;}+PV?Df@;lN5;Qr5q+0F#)Of>9 zTPRJ>Qe+qsq!M#-iiMIL#XoA!He3TLES4n1?kQZ1lrD-?MuwIcwn*uM5Y9L)t4fCt zh38eexNOzy*9oysUp0{R?_ZdGbwRZpr zr@zZ=`i^t@eQxqD(eMjT_BZI%EY8eL<5CgX-rp;unOb>7P;bv7=7yNhI8o_3 zW6I1B$`g-*-l&Z;=}>6D{X;j|$qL*C0V?QPr^ilvfOJ|@x7dn_IRs2+$&Ms;|9%m4T)`WC`v9a{W? z+=Td_kej}N)kEZE{*RHHNCK!nWr4H?Z01mh&RmKl9Bco#xlOm~At@w3ahr6;DWmyg zQ1VvFzvMRIF-;+8aFP83Zc`kkY!kD*M!FJ$imj{KuB$Ti5x#a+jc+#|m50unnXWB& z1D|0~eWqIfVbFQo2)j&LgnVE1o~U&oi0$s*8fvSr_HIk*$BMQYrX(iT2Pk$vIZZAK zNsY?dc))vbfOMmNB|=Ti$d@zYmPBxstMeZE-cn=$BNk`rg5{e+1^~tl*8c?_C4^%O zS<1u7=+m3!tb=LBzQq^w#P%f|Nw5j-u7%Ghwo59JNUWP@5psXwuc8a*&-3 z(#FzRn32gAe@^ z=1>p0c}*36W9TMUTZ%C&xv&=ECw41w{4*=P)9f@W&kuBR_j!7p5{XR$JFK)4jD!SjOkR}h>l9_`t2D*qhclq#17r)YRAuAj zc=qOUrvJJ^f7dC&b!(6~(2}R|X33e2trOTUnpoOSO^0Dk09rybk)6ofR7MgiLtE2e zyMEO6xUwBS7L*t!0CQ)UVqO$#%{Z}ePWFHR9fVXSNFf3i48CEC5P7IH@v6V+>JTo0 z)2VCg3T_g^^Mv&mgJ(VUiU6)ffs6vURNQ%To=ffZ8K#TNtGpM1u{{{sSC`Y}RTz*1_Bz^-dzxz^)h5v$4byFj!vg^uht zaYSv9@?I#CC=Kv@>bUpXD2H*es2^fz71~kwZd(~z7X{BSBESqPXu#soa)@IgdJ6~_YGDkm z{1nUvt%_pK(0HO`LB)-ZQP>Z=hCW3~XRTJGpbg1JL*!8~c}jXx@=zLZun=eFt+(N>?H4&axhaM zuPKA{Dhz>Jw$LFK6pmg7vT*wb?tu(ma9S{~`p2)Cz1sAe!rcb#z*O9J*_p2Tcg)Yg zxBbHlZ-rKj8`=(p?4v!qa}FrftatU{p^{k9!?zIPJAAb zkR8g=UD}5RJgbaNzDgyj_w6oJ;^sI!zEpSjEi0T$qDgk11z&5zL_xwt?i-K$Q`&E2 zacaR7@Ab6HN7B4R#@=?EgEOfx#RRekcLEpma-6^wr*qv=_^tjuox|?}IoosFE|pQ{ z@^`neb`97*skxPWU*F6tE`nf^vO9THIpDnK15rn2)A7g%NRcdnO zl+i)BK8s`Pi(5A^O&K?gKM^vfpWV&Ri?wb-Sh z&nc15F0UgfDQN}o^Xm-hW{dt-Lo;4{!!}>Z9>;3p4AG~Uq|~fSkr^LQW!v3$`F5ty zIuInIJ>qO$^u`O>n!L=!3ukPg&9EetSmXsqQ=Uxs(pcOVGEx7*1tg&OJy@#E^RB(+ zUF+jD6mW@A+}V$`ZiS8b8+51m55B!W(8V4p_<6rNg;05e8FIl>x)VG{+EJl)l~?7Gy9 zAmC~bZsXGhO+Ed<-wl^#alMq|4r|1Wu|{WNo5t4y;1T~{Z&w}<<@Uy9$>`D;QiNh= z?7OVVK8CRt5!uR`lwF7rVg_LbxnzlOi4>8Ln7COg3KtbwM|L5y%r3CX*KW1|m+Zgmitf21g_V3oZ!P{eEvZ&&C5lkDkBUEv3Jq?&RdLF&ODtRLi2JR@cgDmVeQ=N2 zKoxClv&sN(7NdL9<71#{K1s+f3A$(U_loIGeSlZLoE?q0Q-%-z1h=p19}Sz?$VZTbR@>JoB1+!SFw3gQ>! zCRL9Qc4&x1RYyEjv@%q*48zPaB$dcmg}qo|Rv*>% z@wM`~@@`HUOD=Co*x0iArMM+IrKE@a?C%u^^=FWJzs^JRK#6kV#MI*42$YLj%R|M) z`21g#WtQ30oUxXwJbb!3wHZzz4<%EzM`p)UW)TpdcgyqK_2r!A_XBiu&0ZM4dFP-l z5PucGT5GSC{$@4yxsZ+!xwh{s6TJkWWM_kccdVJ`9Ts;37VR4wknKQiWyy2*uZ!e9 zJ?kV5{Mb$Wq7BUY4KSlGKmFevB);v^hi2i%GuEA_*J~!mQ7K&y)9qa);0SoFIuZPhBIn0Wd~yKI0jYv5d%= zMk8#GoLujl*K??TCC-7VZ(FF$MuipVXJ{bO+Imn;-_-ZwuJ2|R6b7;hPW0mQ|M?9r zVW;ww2Z5hIp58zXl5`${YoS%xb9L##A(vFblj`gO z=>l>Z70hJ<8kQTY6nZ42iwvR z-tG)jCKqrxdt$<3V#J_^L%%vO-k+a&Fg>1UUg33EnVf@@uV&>QyciSbdC$(Q1zU>lsTfpfj z0jEPlscAaF9f5ZisB1$gRK>Z1!D+2&^tu9Ed*XM2c92iX%j$ByvU|fHYR`NQM~~CP zfh3W;!TmwtrGs@O&F(e)SCM`~O8J6V@IBFnifyco*4y%*t;(vkO;^@h$FC<1OpW^u zRxG_+Y2wie*4ojM)l%1#-Snh6Z?!CoqmWpzYvrlJb&s~UN1L;rGbulz3@CV2->bKF zy2S0`iOjO+pUT6q6a)KI)bdp0vxd9P%$AKGDtJv7&R3S|M>flTO*e_Z8m|+NiANJNxkYK!~xfoXiT*w%7d!*d4 z7J~oq_<-e#q_#EF4E1B2J(SBDuVEMT49LvSGdf1zIurSqH`A>>9a zG2xUD6*Gu<9CdTmY57#Hj5wu-*jc_kFo+g?b9SRD$p8=0RYUqg?#3C#qvC+%r3C~c zOI4Nepu)cPjjSuTX;FzD^9W_f9wLGUPWjFds7v(HZXiGmcsAhb36}5#v%7Hq36!_R zwi!xpHnSG*)WKpIXEG?$_j5^q{cNJPk550a_NmLwj$kQ?OTLs8(bsomc1Z611n(dU zPEIPM7LiK*ErC_^vhL+(LSmchF?1xi;?A&)DkWdY9GE`OcFin4=bn9`0e5P9l$uf1RT==s?2#8bx00Cn9peeO?5E3CFb2q#E361)Ew8BPus z@@qs}tF+@inDL0pELHuMEb6|YVW2Tz*Q>?VM{6Z>#wZya3J3t#s9q@c6%lQ3E7rVv zugX{?=~=u-PKyD73~}>Av03_1_Qt~oKWJOX|FX5zbRBxx8w+StPY}cyEE#m z6V6E*n4JRNDT}|cUE`+u8~wTvG%0^g0J1KU9@b2}lsVo?bISP@uU9WERa zONLv-p-Z_Kn>G1P$Qke(vWXzJF=#$P9+%>t#2+uYZ;!0FQ18G zOne~h-Wgm-HN7TQClB*pSi`=QovY{aPiGp42=Wc^C%>)mw$hUzj$#m}KTY)0Qz``X zCmQ=VSA9cGYGbI~G`A!qm+$34TJ(YKvz_AS%`*k|3M>)9t#c2zXHQld=3RfP61GY6tGgY+%BPu|grBU|z2S zdQd6!7)U{+0#1Qw;8?r%HJ^ za!0`kc zPo5hS4GbBd^d?%@+cV&JYWiAa*guV!49RfG_ zI>^<{zCGHoUyO6~DqYP7Wyy13=E0h5Qyg7gfkrF04g?XFl7+47hQ0TBjUaX1$h=#> zM|+ZbO1%ZArHwQQ(U$;G?w}3jE4s(>U>DbcKC{Rk1`6=gMi1B=?>hP%!+PcdVIXVh z1x8;Hl<>`@M5Sb7iX8Ema-zAaOuGsa;M8yj%d z6KC=G*keRoQ5TMK(vD!%$%Bv3*fj<&B?#Wa#|0Gm*j_Jb>3%(V`@T%g^|WQb(woPk zv}GD(?JbLM=j_KwMQRLZXpC(1Q(YdtKCs-Fl*4DnZf?y=yk53znmJud{+EO+Oti~~ zW=G-#wZ6x+B?oq*{H&!v$_6RBDY*#Bl1&D43Y6}|_Qyw8wb={?cx85hc+?D}R*mN% zhmL?$^tohCuHw`k4Sb20l)mgT@T@i=*f|J?3wnH6qv^L*O-4!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 204/393] 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 205/393] 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 206/393] 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 207/393] 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 208/393] 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 209/393] 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 210/393] 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 211/393] #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 212/393] 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 213/393] 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 214/393] 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 215/393] 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 216/393] 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 217/393] 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 218/393] 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 219/393] 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 220/393] 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 221/393] 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 321/393] 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 322/393] 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 323/393] 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 324/393] 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 325/393] 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)] { From 09bfaf10280dc1d542b5505d085a3662f0b41ec8 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:18:34 +0100 Subject: [PATCH 326/393] fix(media): honor clean aperture on movie import --- crates/media/src/craft_source.rs | 225 +++++++++++++++++++++++-------- crates/media/tests/it/footage.rs | 46 ++++++- 2 files changed, 216 insertions(+), 55 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 085329242..f7e31e692 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -9,7 +9,8 @@ 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_frame::{Chroma, PixelData, Region, VideoFrame}; +use craft_media::bitstream::unescape_rbsp; use craft_media::isobmff::{self, Mp4File}; use craft_media::matroska::{self, MkvFile}; use craft_media::{ByteSource, CodecId, CodecParams}; @@ -209,6 +210,58 @@ where Some((audio_tracks, audio_infos)) } +/// When a codec signals its own visible picture, the aperture is relative to that picture, +/// not the coded dimensions some writers store in the sample entry. +fn nal_visible_size(config: &isobmff::CodecConfig) -> Option<(u32, u32)> { + let (_, _, width, height) = match config { + isobmff::CodecConfig::Avc(avc) => { + if avc.pps.is_empty() { + return None; + } + let sps = avc.sps.iter().find(|n| n.first().is_some_and(|h| h & 0x1f == 7))?; + craft_video::h264::decode::params::Sps::parse(&unescape_rbsp(sps.get(1..)?)).ok()?.crop_rect() + } + isobmff::CodecConfig::Hevc(hevc) => { + let (mut vps, mut sps, mut pps) = (false, None, false); + for nal in hevc.arrays.iter().filter(|a| (32..=34).contains(&a.nal_type)).flat_map(|a| &a.nalus) { + match nal.first().map(|h| (h >> 1) & 0x3f) { + Some(32) => vps = true, + Some(33) if sps.is_none() => sps = Some(nal), + Some(34) => pps = true, + _ => {} + } + } + if !vps || !pps { + return None; + } + craft_video::hevc::decode::params::Sps::parse(&unescape_rbsp(sps?.get(2..)?)).ok()?.crop_rect() + } + _ => return None, + }; + (width != 0 && height != 0).then_some((width, height)) +} + +/// Apply a valid container clean aperture in decoded-picture coordinates, before rotation. +fn clean_aperture_region(aperture: isobmff::CleanAperture, (width, height): (u32, u32)) -> Option { + let ratio = |(n, d): (u32, u32)| (d != 0).then(|| f64::from(n) / f64::from(d)); + let offset = |(n, d): (i32, u32)| (d != 0).then(|| f64::from(n) / f64::from(d)); + let w = ratio(aperture.width)?.round(); + let h = ratio(aperture.height)?.round(); + let dx = offset(aperture.horiz_offset)?; + let dy = offset(aperture.vert_offset)?; + let (frame_width, frame_height) = (f64::from(width), f64::from(height)); + if w < 1.0 || h < 1.0 || w > frame_width || h > frame_height { + return None; + } + let x = ((frame_width - w) / 2.0 + dx).round(); + let y = ((frame_height - h) / 2.0 + dy).round(); + if x < 0.0 || y < 0.0 || x + w > frame_width || y + h > frame_height { + return None; + } + let r = Region { x: x as usize, y: y as usize, w: w as usize, h: h as usize }; + (!r.is_full(width as usize, height as usize)).then_some(r) +} + fn open_isobmff(name: &str, source: SharedBytes) -> Option> { let file = isobmff::open(source.clone()).ok()?; let video_idx = @@ -226,6 +279,13 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> .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 aperture = video_track.video().and_then(|v| v.clean_aperture).and_then(|clap| { + (width, height) = nal_visible_size(&video_track.entries[0].codec).unwrap_or((width, height)); + clean_aperture_region(clap, (width, height)) + }); + if let Some(region) = aperture { + (width, height) = (region.w as u32, region.h as u32); + } 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 { @@ -280,9 +340,7 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> source, file: container, video_track_idx: video_idx, - container_color, - par, - rotation, + presentation: FramePresentation { container_color, par, rotation, aperture }, video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), audio_tracks, }))) @@ -362,9 +420,7 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option source, file: container, video_track_idx: video_idx, - container_color, - par, - rotation, + presentation: FramePresentation { container_color, par, rotation, aperture: None }, video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), audio_tracks, }))) @@ -399,14 +455,20 @@ struct AudioTrackEntry { state: Mutex, } +#[derive(Clone, Copy)] +struct FramePresentation { + container_color: Option, + par: (u32, u32), + rotation: u8, + aperture: Option, +} + struct CraftMediaSource { info: MediaInfo, source: SharedBytes, file: ContainerFile, video_track_idx: usize, - container_color: Option, - par: (u32, u32), - rotation: u8, + presentation: FramePresentation, video: Mutex, audio_tracks: Vec, } @@ -451,11 +513,11 @@ impl MediaSource for CraftMediaSource { 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)?; + push_decoded(&mut state.decoded, frames, want_draft, self.presentation, &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)?; + push_decoded(&mut state.decoded, frames, want_draft, self.presentation, &self.file, self.video_track_idx)?; break; } else { break; @@ -600,21 +662,18 @@ fn decode_audio_range( 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, + presentation: FramePresentation, 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)?); + let frame = Arc::new(to_craft_frame(vf, presentation, pts_tick)?); cache.push(CachedFrame { pts, draft, frame }); } if cache.len() > MAX_CACHED_FRAMES { @@ -624,9 +683,9 @@ fn push_decoded( 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(); +fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: Tick) -> Result { + let FramePresentation { container_color, par: default_par, rotation, aperture } = presentation; + let (mut width, mut height) = (vf.width(), vf.height()); let subsampling = vf.subsampling(); let family = vf.family(); let tags = vf.color; @@ -651,17 +710,21 @@ fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option, def let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else { return Err(MediaError::Decode("missing YUV planes".into())); }; + let (luma, chroma_region) = aperture.and_then(|r| aligned_aperture(r, width as usize, height as usize, chroma)).unzip(); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } 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); + let y = Arc::new(plane_u8(y, luma)?); + let cb = Arc::new(plane_u8(cb, chroma_region)?); + let cr = Arc::new(plane_u8(cr, chroma_region)?); + let a = alpha.map(|p| plane_u8(p, luma)).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); + let y = Arc::new(plane_u16(y, luma)?); + let cb = Arc::new(plane_u16(cb, chroma_region)?); + let cr = Arc::new(plane_u16(cr, chroma_region)?); + let a = alpha.map(|p| plane_u16(p, luma)).transpose()?.map(Arc::new); PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a } } } @@ -672,6 +735,20 @@ fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option, def Ok(rotate_frame(frame, rotation)) } +/// Move the origin onto the chroma grid before clipping, keeping the size when it fits. +fn aligned_aperture(region: Region, width: usize, height: usize, chroma: Chroma) -> Option<(Region, Region)> { + let (sx, sy) = chroma.shifts(); + let (xs, ys) = (1usize << sx, 1usize << sy); + let x = region.x.min(width) & !(xs - 1); + let y = region.y.min(height) & !(ys - 1); + let luma = Region { x, y, ..region }.clip(width, height); + if luma.is_empty() || luma.is_full(width, height) { + return None; + } + let chroma = Region { x: luma.x / xs, y: luma.y / ys, w: luma.w.div_ceil(xs), h: luma.h.div_ceil(ys) }; + Some((luma, chroma)) +} + 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(); @@ -770,52 +847,62 @@ fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame { frame } -fn plane_u8(p: Plane) -> Result> { +fn plane_region(aperture: Option, width: usize, height: usize) -> Result { + let r = aperture.unwrap_or(Region { x: 0, y: 0, w: width, h: height }); + if r.clip(width, height) != r { + return Err(MediaError::Decode("clean aperture exceeds a decoded plane".into())); + } + Ok(r) +} + +fn plane_u8(p: Plane, aperture: Option) -> Result> { let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + let r = plane_region(aperture, w, h)?; match p.into_samples() { Samples::U8(mut v) => { - if stride == w { + if stride == w && r.is_full(w, h) { 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]); + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend_from_slice(&v[row..row + r.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)); + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend(v[row..row + r.w].iter().map(|&s| s.min(255) as u8)); } Ok(out) } } } -fn plane_u16(p: Plane) -> Result> { +fn plane_u16(p: Plane, aperture: Option) -> Result> { let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride()); + let r = plane_region(aperture, w, h)?; match p.into_samples() { Samples::U16(mut v) => { - if stride == w { + if stride == w && r.is_full(w, h) { 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]); + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend_from_slice(&v[row..row + r.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))); + let mut out = Vec::with_capacity(r.w * r.h); + for y in r.y..r.y + r.h { + let row = y * stride + r.x; + out.extend(v[row..row + r.w].iter().map(|&s| u16::from(s))); } Ok(out) } @@ -1039,7 +1126,7 @@ mod tests { #[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()); + let out = Plane::packed(2, 2, 8, Samples::U16(vec![10, 20, 30, 255])).ok().and_then(|p| plane_u8(p, None).ok()); assert_eq!(out.as_deref(), Some(&[10, 20, 30, 255][..])); } @@ -1074,13 +1161,13 @@ mod tests { #[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][..])); + assert_eq!(plane_u8(p8, None).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][..])); + assert_eq!(plane_u16(p16, None).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][..])); + assert_eq!(plane_u16(p8_as_16, None).ok().as_deref(), Some(&[7, 8][..])); } let nclc = color_from_isobmff(&isobmff::ColorInfo::Nclc { primaries: 1, transfer: 1, matrix: 1 }); @@ -1097,6 +1184,35 @@ mod tests { assert_eq!(tick_to_units(Tick(craft_time::TICKS_PER_SECOND), 90000), 90000); } + #[test] + fn clean_aperture_rounds_signed_offsets_and_ignores_invalid_regions() { + let aperture = isobmff::CleanAperture { width: (17, 2), height: (15, 2), horiz_offset: (1, 2), vert_offset: (-1, 2) }; + assert_eq!(clean_aperture_region(aperture, (16, 16)), Some(Region { x: 4, y: 4, w: 9, h: 8 })); + assert_eq!(clean_aperture_region(isobmff::CleanAperture { width: (17, 0), ..aperture }, (16, 16)), None); + assert_eq!(clean_aperture_region(isobmff::CleanAperture { horiz_offset: (10, 1), ..aperture }, (16, 16)), None); + let full = isobmff::CleanAperture { width: (16, 1), height: (16, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + assert_eq!(clean_aperture_region(full, (16, 16)), None); + } + + #[test] + fn odd_clean_aperture_crops_luma_chroma_and_alpha_together() { + let luma = Plane::packed(6, 6, 8, Samples::U8((0..36).collect())).unwrap(); + let chroma = Plane::packed(3, 3, 8, Samples::U8((0..9).collect())).unwrap(); + let alpha = Plane::packed(6, 6, 8, Samples::U8((64..100).collect())).unwrap(); + let frame = DecodedVideoFrame::new(6, 6, ColorFamily::YCbCr, Subsampling::S420, vec![luma, chroma.clone(), chroma], Some(alpha)).unwrap(); + let aperture = Some(Region { x: 3, y: 3, w: 3, h: 3 }); + let presentation = FramePresentation { container_color: None, par: (3, 2), rotation: 0, aperture }; + let cropped = to_craft_frame(frame, presentation, Tick::ZERO).unwrap(); + assert_eq!((cropped.width, cropped.height, cropped.par), (3, 3, (3, 2))); + let PixelData::Yuv8 { planes: [y, cb, cr], chroma: Chroma::C420, alpha: Some(a) } = cropped.data else { + panic!("expected cropped 4:2:0 with alpha"); + }; + assert_eq!(y.as_slice(), &[14, 15, 16, 20, 21, 22, 26, 27, 28]); + assert_eq!(cb.as_slice(), &[4, 5, 7, 8]); + assert_eq!(cr.as_slice(), cb.as_slice()); + assert_eq!(a.as_slice(), &[78, 79, 80, 84, 85, 86, 90, 91, 92]); + } + #[test] fn rotated_frame_preserves_container_par_without_double_inversion() { let make_vf = |sar: Option<(u32, u32)>| { @@ -1109,13 +1225,14 @@ mod tests { }; // `default_par` is already rotated by the container opener (e.g. (4, 3) -> (3, 4) for 90°). let container_rotated_par = (3, 4); + let presentation = FramePresentation { container_color: None, par: container_rotated_par, rotation: 1, aperture: None }; 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(); + let out = to_craft_frame(vf_no_sar, presentation, 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(); + let out = to_craft_frame(vf_with_sar, presentation, Tick::ZERO).ok(); assert_eq!(out.map(|f| f.par), Some((3, 4))); } } diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index f1aff6406..3aded20bc 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -385,7 +385,10 @@ fn resampled_audio_read_in_frame_pieces_matches_ffmpeg() { /// The H.264 fixture with the rotation part of its video track header's matrix (`[a b; c d]`, /// 16.16 fixed point) replaced: what a phone writes for a movie shot with the camera turned. fn turned_mp4(p: &Path, abcd: [i32; 4]) -> Arc<[u8]> { - let mut bytes = std::fs::read(p).expect("read"); + turn_mp4_bytes(std::fs::read(p).expect("read"), abcd) +} + +fn turn_mp4_bytes(mut bytes: Vec, abcd: [i32; 4]) -> Arc<[u8]> { // (The video track comes first; a version 0 `tkhd` has its matrix 44 bytes after the type.) let at = bytes.windows(4).position(|w| w == b"tkhd").expect("tkhd"); assert_eq!(bytes[at + 4], 0, "a version 0 tkhd"); @@ -502,6 +505,47 @@ fn prores_alpha_uses_coded_frame_not_mov_depth() { } } +/// A synthetic asymmetrical aperture and rotation must determine what the shared importer shows. +#[test] +fn mov_renders_clean_aperture_before_display_rotation() { + use craft_media::isobmff::{self, Brand, CleanAperture, FourCc, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let profile = Profile::P4444; + let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, true).unwrap(); + // Our generated alpha value uniquely labels each source coordinate. + for (i, p) in frame.alpha.as_mut().unwrap().iter_mut().enumerate() { + *p = i as u16 * 257; + } + let packet = Encoder::new(profile, 16, 16).encode(&frame).unwrap(); + let mut entry = SampleEntry::prores(FourCc(profile.fourcc()), 16, 16); + let clean_aperture = CleanAperture { width: (8, 1), height: (12, 1), horiz_offset: (2, 1), vert_offset: (-1, 1) }; + entry.video.as_mut().unwrap().clean_aperture = Some(clean_aperture); + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let track = writer.add_track(TrackConfig::new(entry, 24)).unwrap(); + writer.write_sample(track, WriteSample { data: &packet, duration: 1, composition_offset: 0, is_sync: true }).unwrap(); + let bytes = turn_mp4_bytes(writer.finish().unwrap().into_inner(), [0, 0x1_0000, -0x1_0000, 0]); + + let mov = isobmff::open(bytes.as_ref()).unwrap(); + assert_eq!(mov.tracks[0].video().unwrap().clean_aperture, Some(clean_aperture)); + assert_eq!(mov.tracks[0].display_rotation(), Some(1)); + let name = "turned_clean_aperture.mov"; + let footage = probe_bytes(name, bytes.clone()).expect("probe the cropped MOV"); + assert_eq!(footage.codec, "ProRes", "must exercise the shared reader, not legacy fallback"); + assert_eq!((footage.width, footage.height), (12, 8)); + + let pool = MediaPool::new(); + pool.add_bytes(name, bytes); + let image = pool.frame_at(&footage, Tick::ZERO).expect("render the cropped MOV"); + assert_eq!((image.width, image.height), (12, 8)); + for (x, y) in [(0, 0), (11, 0), (0, 7), (11, 7), (4, 3)] { + // Rotate 90° after cropping the source box (6, 1, 8, 12). + let source = (6 + y, 12 - x); + let expected = (source.0 + 16 * source.1) as f32 / 255.0; + assert!((image.data[y * 12 + x][3] - expected).abs() < 0.01, "pixel {x},{y} must come from {source:?}"); + } +} + #[test] fn vp9_webm_frames() { let Some(p) = vp9_webm() else { return }; From 46391758e05984189b8b1516bfc9b7c85c261596 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:16:54 +0100 Subject: [PATCH 327/393] fix(media): resolve clean aperture on the decoded picture --- crates/media/src/craft_source.rs | 57 ++++++++++++++++++++++++-------- crates/media/tests/it/footage.rs | 2 +- 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index f7e31e692..c3a23c01f 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -210,15 +210,19 @@ where Some((audio_tracks, audio_infos)) } -/// When a codec signals its own visible picture, the aperture is relative to that picture, -/// not the coded dimensions some writers store in the sample entry. -fn nal_visible_size(config: &isobmff::CodecConfig) -> Option<(u32, u32)> { +/// A probe hint only: a single configured SPS can signal a visible size different from the +/// sample entry. Multiple or in-band parameter sets leave the initial hint to the container. +fn nal_visible_size_hint(config: &isobmff::CodecConfig) -> Option<(u32, u32)> { let (_, _, width, height) = match config { isobmff::CodecConfig::Avc(avc) => { if avc.pps.is_empty() { return None; } - let sps = avc.sps.iter().find(|n| n.first().is_some_and(|h| h & 0x1f == 7))?; + let mut sets = avc.sps.iter().filter(|n| n.first().is_some_and(|h| h & 0x1f == 7)); + let sps = sets.next()?; + if sets.next().is_some() { + return None; + } craft_video::h264::decode::params::Sps::parse(&unescape_rbsp(sps.get(1..)?)).ok()?.crop_rect() } isobmff::CodecConfig::Hevc(hevc) => { @@ -226,7 +230,8 @@ fn nal_visible_size(config: &isobmff::CodecConfig) -> Option<(u32, u32)> { for nal in hevc.arrays.iter().filter(|a| (32..=34).contains(&a.nal_type)).flat_map(|a| &a.nalus) { match nal.first().map(|h| (h >> 1) & 0x3f) { Some(32) => vps = true, - Some(33) if sps.is_none() => sps = Some(nal), + Some(33) if sps.is_some() => return None, + Some(33) => sps = Some(nal), Some(34) => pps = true, _ => {} } @@ -279,12 +284,14 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> .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 aperture = video_track.video().and_then(|v| v.clean_aperture).and_then(|clap| { - (width, height) = nal_visible_size(&video_track.entries[0].codec).unwrap_or((width, height)); - clean_aperture_region(clap, (width, height)) - }); - if let Some(region) = aperture { - (width, height) = (region.w as u32, region.h as u32); + // Probe needs dimensions before decoding. Retain the original rational aperture separately + // so frame conversion can use the actual visible size, even with in-band parameter sets. + let aperture = video_track.video().and_then(|v| v.clean_aperture); + if let Some(clap) = aperture { + (width, height) = nal_visible_size_hint(&video_track.entries[0].codec).unwrap_or((width, height)); + if let Some(region) = clean_aperture_region(clap, (width, height)) { + (width, height) = (region.w as u32, region.h as u32); + } } 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; @@ -460,7 +467,7 @@ struct FramePresentation { container_color: Option, par: (u32, u32), rotation: u8, - aperture: Option, + aperture: Option, } struct CraftMediaSource { @@ -710,7 +717,10 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else { return Err(MediaError::Decode("missing YUV planes".into())); }; - let (luma, chroma_region) = aperture.and_then(|r| aligned_aperture(r, width as usize, height as usize, chroma)).unzip(); + let (luma, chroma_region) = aperture + .and_then(|clap| clean_aperture_region(clap, (width, height))) + .and_then(|r| aligned_aperture(r, width as usize, height as usize, chroma)) + .unzip(); if let Some(r) = luma { (width, height) = (r.w as u32, r.h as u32); } @@ -1200,7 +1210,7 @@ mod tests { let chroma = Plane::packed(3, 3, 8, Samples::U8((0..9).collect())).unwrap(); let alpha = Plane::packed(6, 6, 8, Samples::U8((64..100).collect())).unwrap(); let frame = DecodedVideoFrame::new(6, 6, ColorFamily::YCbCr, Subsampling::S420, vec![luma, chroma.clone(), chroma], Some(alpha)).unwrap(); - let aperture = Some(Region { x: 3, y: 3, w: 3, h: 3 }); + let aperture = Some(isobmff::CleanAperture { width: (3, 1), height: (3, 1), horiz_offset: (3, 2), vert_offset: (3, 2) }); let presentation = FramePresentation { container_color: None, par: (3, 2), rotation: 0, aperture }; let cropped = to_craft_frame(frame, presentation, Tick::ZERO).unwrap(); assert_eq!((cropped.width, cropped.height, cropped.par), (3, 3, (3, 2))); @@ -1213,6 +1223,25 @@ mod tests { assert_eq!(a.as_slice(), &[78, 79, 80, 84, 85, 86, 90, 91, 92]); } + #[test] + fn clean_aperture_uses_the_decoded_picture_not_a_coded_size_hint() { + let luma = Plane::packed(8, 6, 8, Samples::U8((0..48).collect())).unwrap(); + let chroma = Plane::packed(8, 6, 8, Samples::U8(vec![128; 48])).unwrap(); + let frame = DecodedVideoFrame::new(8, 6, ColorFamily::YCbCr, Subsampling::S444, vec![luma, chroma.clone(), chroma], None).unwrap(); + let aperture = isobmff::CleanAperture { width: (4, 1), height: (4, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + // A coded/sample-entry size of 8×8 would put the crop one row too low on the decoded + // 8×6 picture. The aperture remains in rational form until this picture is available. + assert_eq!(clean_aperture_region(aperture, (8, 8)).unwrap().y, 2); + let presentation = FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: Some(aperture) }; + let cropped = to_craft_frame(frame, presentation, Tick::ZERO).unwrap(); + assert_eq!((cropped.width, cropped.height), (4, 4)); + let y = match &cropped.data { + PixelData::Yuv8 { planes, .. } => &planes[0], + _ => panic!("expected cropped luma"), + }; + assert_eq!(y.as_slice(), &[10, 11, 12, 13, 18, 19, 20, 21, 26, 27, 28, 29, 34, 35, 36, 37]); + } + #[test] fn rotated_frame_preserves_container_par_without_double_inversion() { let make_vf = |sar: Option<(u32, u32)>| { diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 3aded20bc..593ab49f7 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -542,7 +542,7 @@ fn mov_renders_clean_aperture_before_display_rotation() { // Rotate 90° after cropping the source box (6, 1, 8, 12). let source = (6 + y, 12 - x); let expected = (source.0 + 16 * source.1) as f32 / 255.0; - assert!((image.data[y * 12 + x][3] - expected).abs() < 0.01, "pixel {x},{y} must come from {source:?}"); + assert!((image.data[y * 12 + x][3] - expected).abs() < 0.002, "pixel {x},{y} must come from {source:?}"); } } From 88a59fd77d3f89c718f13f15914683cdd0deee81 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 19:32:40 -0500 Subject: [PATCH 328/393] media: route audio-only ISO-BMFF and Matroska/WebM through craft-audio (#4004) * media: route audio-only ISO-BMFF and Matroska/WebM through craft-audio * media: use MediaKind::AudioOnly for audio-only CraftMediaSource * media: take max duration across all Matroska audio tracks --- crates/media/src/craft_source.rs | 278 ++++++++++++++++++------------- crates/media/tests/it/footage.rs | 27 +++ 2 files changed, 188 insertions(+), 117 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index c3a23c01f..85b5b5447 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1,9 +1,24 @@ -//! ISO-BMFF (MP4/MOV) and Matroska/WebM media-reader routes backed by `craft-media`, -//! `craft-video`, `craft-audio`, and `craft-media-source`. +//! ISO-BMFF (MP4/MOV/M4A) and Matroska/WebM (MKV/MKA/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. +//! +//! ## Route Matrix (`crates/media`) +//! - **ISO-BMFF (`MP4`/`MOV`/`M4A`, video+audio & audio-only)**: +//! - Shared (`craft-media::isobmff` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, +//! `Vp9`, `Vp8`, `ProRes` (coded alpha via `craft_video::prores::probe`, #3999), `Dnxhd`, +//! `Mpeg2Video`; audio `Aac`, `Alac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. +//! - Fallback (`filmcraft-codecs`): `Mjpeg`, `Mpeg4Video`, `Ffv1`, `Apv`, or unsupported audio. +//! - **Matroska / WebM (`MKV`/`MKA`/`WebM`, video+audio & audio-only)**: +//! - Shared (`craft-media::matroska` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, +//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Opus`, `Ac3`, +//! `Mp3`/`Mp2`/`Mp1` (with `CodecDelay` + `SeekPreRoll` timing). +//! - Fallback (`filmcraft-codecs`): `alpha_mode == 1` (`BlockAdditional` alpha), unreadable/zlib +//! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Flac`/`Pcm`). +//! - **Other containers (`MXF`, `AVI`, `MPEG-TS`/`PS`, `Ogg`, standalone `WAV`/`AIFF`/`FLAC`/`MP3`)**: +//! - Currently routed via `filmcraft-codecs` in `stream.rs` (pending subsequent cutover PRs). use std::sync::{Arc, Mutex}; @@ -269,52 +284,7 @@ fn clean_aperture_region(aperture: isobmff::CleanAperture, (width, height): (u32 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)); - // Probe needs dimensions before decoding. Retain the original rational aperture separately - // so frame conversion can use the actual visible size, even with in-band parameter sets. - let aperture = video_track.video().and_then(|v| v.clean_aperture); - if let Some(clap) = aperture { - (width, height) = nal_visible_size_hint(&video_track.entries[0].codec).unwrap_or((width, height)); - if let Some(region) = clean_aperture_region(clap, (width, height)) { - (width, height) = (region.w as u32, region.h as u32); - } - } - 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 = 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); - let codec_name = video_params.codec.name().to_string(); - + 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 audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file .tracks .iter() @@ -323,67 +293,96 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> .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)?; + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } - 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 (video_info, video_state, presentation, duration) = if let Some(v_idx) = video_idx { + let video_track = &file.tracks[v_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)); + // Probe needs dimensions before decoding. Retain the original rational aperture separately + // so frame conversion can use the actual visible size, even with in-band parameter sets. + let aperture = video_track.video().and_then(|v| v.clean_aperture); + if let Some(clap) = aperture { + (width, height) = nal_visible_size_hint(&video_track.entries[0].codec).unwrap_or((width, height)); + if let Some(region) = clean_aperture_region(clap, (width, height)) { + (width, height) = (region.w as u32, region.h as u32); + } + } + 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 = 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, v_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); + let codec_name = video_params.codec.name().to_string(); + 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 v_info = VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format: String::new(), color, has_alpha, bitrate, hdr: None }; + let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation, aperture }, duration) + } else { + let duration = audio_candidates + .iter() + .map(|&(idx, _, _, _)| { + let t = &file.tracks[idx]; + Tick::from_units(i64::try_from(t.duration).unwrap_or(i64::MAX), i64::from(t.timescale)) + }) + .max() + .unwrap_or(Tick::ZERO); + (None, None, FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) }; + let container = ContainerFile::Isobmff(file); + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + if video_info.is_none() && audio_tracks.is_empty() { + return None; + } + + let kind = if video_info.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; let info = MediaInfo { name: name.to_string(), - kind: MediaKind::Movie, + kind, duration, - video: Some(VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format: String::new(), color, has_alpha, bitrate, hdr: None }), + video: video_info, 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, - presentation: FramePresentation { container_color, par, rotation, aperture }, - video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), - audio_tracks, - }))) + Some(Ok(Arc::new(CraftMediaSource { info, source, file: container, video_track_idx: video_idx, presentation, video: video_state, 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 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 audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file .tracks .iter() @@ -392,19 +391,42 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option .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)?; + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } - 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 { + let container_name = if file.doc_type == "webm" { "webm" } else { "mkv" }.to_string(); + let (video_info, video_state, container_color, par, rotation, duration) = if let Some(v_idx) = video_idx { + let video_track = &file.tracks[v_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 v_meta = video_track.video.as_ref(); + // WebM/Matroska alpha_mode == 1 stores alpha in BlockAdditional; fall back to FilmCraft. + if v_meta.is_some_and(|v| v.alpha_mode == 1) { + return None; + } + let container_color = v_meta.and_then(|v| v.color.as_ref()).map(color_from_matroska); + let color = container_color.unwrap_or(ColorInfo::REC709); + let (mut width, mut height) = v_meta.map_or((0, 0), |v| (v.pixel_width, v.pixel_height)); + let mut par = matroska_par(v_meta, width, height); + let rotation = v_meta.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 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 v_info = VideoStreamInfo { width, height, frame_rate, @@ -415,7 +437,26 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option has_alpha: false, bitrate: None, hdr: None, - }), + }; + let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + (Some(v_info), Some(v_state), container_color, par, rotation, duration) + } else { + let duration = audio_candidates.iter().map(|&(idx, _, _, _)| matroska_duration(&file, &file.tracks[idx])).max().unwrap_or(Tick::ZERO); + (None, None, None, (1, 1), 0, duration) + }; + + let container = ContainerFile::Matroska(Box::new(file)); + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + if video_info.is_none() && audio_tracks.is_empty() { + return None; + } + + let kind = if video_info.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, audio_streams: audio_infos, container: container_name, start_timecode: None, @@ -428,7 +469,7 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option file: container, video_track_idx: video_idx, presentation: FramePresentation { container_color, par, rotation, aperture: None }, - video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }), + video: video_state, audio_tracks, }))) } @@ -474,9 +515,9 @@ struct CraftMediaSource { info: MediaInfo, source: SharedBytes, file: ContainerFile, - video_track_idx: usize, + video_track_idx: Option, presentation: FramePresentation, - video: Mutex, + video: Option>, audio_tracks: Vec, } @@ -486,15 +527,18 @@ impl MediaSource for CraftMediaSource { } 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 (Some(video_idx), Some(video_mutex)) = (self.video_track_idx, &self.video) else { + return Err(MediaError::NoStream("video")); + }; + let (target_idx, target_pts) = self.file.target_sample(video_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); + let mut state = video_mutex.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 sync_idx = self.file.sync_sample_before(video_idx, target_idx); let draft_changed = state.decoder.draft() != want_draft; if draft_changed { state.decoder.set_draft(want_draft); @@ -509,22 +553,22 @@ impl MediaSource for CraftMediaSource { state.flushed = false; } - let sample_count = self.file.sample_count(self.video_track_idx); + let sample_count = self.file.sample_count(video_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 pts = self.file.sample_pts(video_idx, idx); + let pkt = self.file.read_sample(&*self.source, video_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.presentation, &self.file, self.video_track_idx)?; + push_decoded(&mut state.decoded, frames, want_draft, self.presentation, &self.file, video_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.presentation, &self.file, self.video_track_idx)?; + push_decoded(&mut state.decoded, frames, want_draft, self.presentation, &self.file, video_idx)?; break; } else { break; diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 593ab49f7..13f3f4675 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1625,3 +1625,30 @@ fn matroska_opus_audio_timing_and_seek() { 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}"); } + +#[test] +fn audio_only_isobmff_and_matroska_route_through_craft_audio() { + for (file, codec, args) in [ + ("audio_only_aac.m4a", "aac", &["-c:a", "aac"][..]), + ("audio_only_alac.m4a", "alac", &["-c:a", "alac"][..]), + ("audio_only_opus.webm", "libopus", &["-c:a", "libopus"][..]), + ] { + let mut ffmpeg_args = vec!["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=1"]; + ffmpeg_args.extend_from_slice(args); + let Some(p) = try_ffmpeg_fixture(file, &ffmpeg_args) else { + continue; + }; + let f = probe(&p).expect(codec); + assert_eq!(f.kind, FootageKind::Audio, "{file} must probe as Audio"); + assert!(!f.has_video, "{file} has no video"); + assert!(f.has_audio, "{file} has audio"); + assert!(f.duration >= Tick(TICKS_PER_SECOND * 9 / 10), "{file} duration {:?}", f.duration); + let pool = MediaPool::new(); + let start = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000); + let seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000); + assert_eq!(start.len(), 9600); + assert_eq!(seek.len(), 9600); + let rms_seek = (seek.iter().map(|v| v * v).sum::() / seek.len() as f32).sqrt(); + assert!((rms_seek - 0.0625).abs() < 0.02, "{file} seek rms {rms_seek}"); + } +} From b9ab1eaa2e2fec6e4f2b3d7cf66261feee0eb37e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:56:10 +0100 Subject: [PATCH 329/393] fix(media): preserve Matroska audio position on cold seek --- crates/media/src/craft_source.rs | 12 ++++-- crates/media/tests/it/footage.rs | 67 ++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 85b5b5447..3f55082ff 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -173,15 +173,19 @@ impl ContainerFile { } ContainerFile::Matroska(f) => { let track = &f.tracks[track_idx]; + // Indexed PTS already subtracts CodecDelay rounded to the container clock. + // Translate only that rounding difference, not the full delay a second time. + let tick_ns = i128::from(f.info.timestamp_scale.max(1)); let delay_ns = i128::from(track.codec_delay_ns); + let rounding_ns = ((delay_ns + tick_ns / 2) / tick_ns) * tick_ns - 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 target_ns = (i128::from(start.max(0)) * 1_000_000_000) / i128::from(native_rate); + let seek_ns = (target_ns - preroll_ns - rounding_ns).max(0); + let t_track = track.ns_to_ticks(i64::try_from(seek_ns).unwrap_or(i64::MAX)); 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 sample_ns = i128::from(track.ticks_to_ns(sample_pts)) + rounding_ns; let decoded_pos = i64::try_from((sample_ns * i128::from(native_rate)) / 1_000_000_000).unwrap_or(0); (seek_idx, decoded_pos) } diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 13f3f4675..a655efce7 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1592,6 +1592,73 @@ fn filmcraft_fallback_handles_mjpeg_mov() { assert_eq!((img.width, img.height), (160, 120)); } +/// A cold seek and uninterrupted playback must cross the same audible boundary. The PCM is +/// contiguous, so the test isolates reset positioning from separately handled timestamp gaps. +#[test] +fn matroska_cold_seek_applies_codec_delay_once() { + use craft_media::matroska::{self, MkvWriter, MuxOptions, TrackKind, TrackSpec}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + const RATE: u32 = 48_000; + const PACKET_FRAMES: usize = 4_800; + const PACKET_NS: i64 = 100_000_000; + const DELAY_NS: i64 = 8_250_000; // 396 samples, but 8 rounded container ticks. + const CHANGE_PACKET: i64 = 32; + const HALF_WINDOW: usize = 192; + + let profile = Profile::P4444; + let black = Frame::new(16, 16, ChromaFormat::Yuv444, 10, false).unwrap(); + let picture = Encoder::new(profile, 16, 16).encode(&black).unwrap(); + let mut video = TrackSpec::new(TrackKind::Video, "V_PRORES"); + video.video_size = Some((16, 16)); + video.codec_private = profile.fourcc().to_vec(); + video.default_duration_ns = Some(4_000_000_000); + + let mut audio = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); + audio.audio = Some((f64::from(RATE), 1, Some(16))); + audio.codec_delay_ns = DELAY_NS as u64; + audio.default_duration_ns = Some(PACKET_NS as u64); + let mut mux = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![video, audio], MuxOptions::default()).unwrap(); + mux.write_frame(0, 0, true, &picture, None).unwrap(); + let silent = vec![0; PACKET_FRAMES * 2]; + let signal = 16_384i16.to_le_bytes().repeat(PACKET_FRAMES); + for n in 0..40 { + let pcm = if n < CHANGE_PACKET { &silent } else { &signal }; + mux.write_frame(1, n * PACKET_NS - DELAY_NS, true, pcm, None).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let mkv = matroska::open(bytes.as_slice()).unwrap(); + assert_eq!(mkv.tracks[1].samples[0].pts, -8); + + // Distinct files and pools keep the two decoder states independent. + let dir = tempfile::tempdir().unwrap(); + let warm_path = dir.path().join("sequential.mkv"); + let cold_path = dir.path().join("cold.mkv"); + std::fs::write(&warm_path, &bytes).unwrap(); + std::fs::write(&cold_path, &bytes).unwrap(); + let warm = probe(&warm_path).unwrap(); + let cold = probe(&cold_path).unwrap(); + for f in [&warm, &cold] { + assert!(f.has_audio); + assert_eq!(f.codec, "ProRes", "exercise the shared Matroska route, not legacy fallback"); + } + + let warm_pool = MediaPool::new(); + for n in 0..CHANGE_PACKET - 1 { + let t = Tick::from_units(n * PACKET_FRAMES as i64, i64::from(RATE)); + let _ = warm_pool.audio_samples(&warm, t, PACKET_FRAMES, RATE); + } + let boundary = CHANGE_PACKET * PACKET_FRAMES as i64 - DELAY_NS * i64::from(RATE) / 1_000_000_000; + let t = Tick::from_units(boundary - HALF_WINDOW as i64, i64::from(RATE)); + let sequential = warm_pool.audio_samples(&warm, t, 2 * HALF_WINDOW, RATE); + assert_eq!(sequential.len(), 4 * HALF_WINDOW); + assert!(sequential[..2 * HALF_WINDOW].iter().all(|s| s.abs() < 1e-6)); + assert!(sequential[2 * HALF_WINDOW..].iter().all(|s| s.abs() > 0.1)); + + let seek = MediaPool::new().audio_samples(&cold, t, 2 * HALF_WINDOW, RATE); + assert_eq!(seek, sequential, "cold seek must not shift the signal boundary"); +} + #[test] fn matroska_opus_audio_timing_and_seek() { let Some(p) = try_ffmpeg_fixture( From e084232b7095d6d399913b069a16345d25f1e48b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:52:03 +0700 Subject: [PATCH 330/393] Match Matroska cold-seek audio frame rounding --- crates/media/src/craft_source.rs | 19 ++++++++++++------- crates/media/tests/it/footage.rs | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 3f55082ff..f4843db3a 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -174,25 +174,30 @@ impl ContainerFile { ContainerFile::Matroska(f) => { let track = &f.tracks[track_idx]; // Indexed PTS already subtracts CodecDelay rounded to the container clock. - // Translate only that rounding difference, not the full delay a second time. + // Translate between that clock and the warm path's whole-frame delay. let tick_ns = i128::from(f.info.timestamp_scale.max(1)); let delay_ns = i128::from(track.codec_delay_ns); - let rounding_ns = ((delay_ns + tick_ns / 2) / tick_ns) * tick_ns - delay_ns; + let indexed_delay_ns = ((delay_ns + tick_ns / 2) / tick_ns) * tick_ns; + let delay_frames = audio_frames_from_ns(delay_ns, native_rate); 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); - let seek_ns = (target_ns - preroll_ns - rounding_ns).max(0); + let target_ns = ((i128::from(start.max(0)) + delay_frames) * 1_000_000_000) / i128::from(native_rate); + let seek_ns = (target_ns - preroll_ns - indexed_delay_ns).max(0); let t_track = track.ns_to_ticks(i64::try_from(seek_ns).unwrap_or(i64::MAX)); 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)) + rounding_ns; - let decoded_pos = i64::try_from((sample_ns * i128::from(native_rate)) / 1_000_000_000).unwrap_or(0); + let sample_ns = i128::from(track.ticks_to_ns(sample_pts)) + indexed_delay_ns; + let decoded_pos = i64::try_from(audio_frames_from_ns(sample_ns, native_rate) - delay_frames).unwrap_or(0); (seek_idx, decoded_pos) } } } } +fn audio_frames_from_ns(ns: i128, rate: u32) -> i128 { + (ns * i128::from(rate)) / 1_000_000_000 +} + fn open_audio_tracks(container: &ContainerFile, source: &dyn ByteSource, candidates: I) -> Option<(Vec, Vec)> where I: IntoIterator, @@ -213,7 +218,7 @@ where 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); + let delay_samples = i64::try_from(audio_frames_from_ns(i128::from(codec_delay_ns), native_rate)).unwrap_or(0); audio_infos.push(AudioStreamInfo { sample_rate: native_rate, channels, diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index a655efce7..df1751ff6 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1596,13 +1596,21 @@ fn filmcraft_fallback_handles_mjpeg_mov() { /// contiguous, so the test isolates reset positioning from separately handled timestamp gaps. #[test] fn matroska_cold_seek_applies_codec_delay_once() { + assert_matroska_cold_seek_codec_delay(8_250_000); // Exactly 396 samples, but 8 indexed ticks. +} + +#[test] +fn matroska_cold_seek_matches_fractional_codec_delay_rounding() { + assert_matroska_cold_seek_codec_delay(8_260_000); // 396.48 samples, also 8 indexed ticks. +} + +fn assert_matroska_cold_seek_codec_delay(delay_ns: i64) { use craft_media::matroska::{self, MkvWriter, MuxOptions, TrackKind, TrackSpec}; use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; const RATE: u32 = 48_000; const PACKET_FRAMES: usize = 4_800; const PACKET_NS: i64 = 100_000_000; - const DELAY_NS: i64 = 8_250_000; // 396 samples, but 8 rounded container ticks. const CHANGE_PACKET: i64 = 32; const HALF_WINDOW: usize = 192; @@ -1616,7 +1624,7 @@ fn matroska_cold_seek_applies_codec_delay_once() { let mut audio = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); audio.audio = Some((f64::from(RATE), 1, Some(16))); - audio.codec_delay_ns = DELAY_NS as u64; + audio.codec_delay_ns = delay_ns as u64; audio.default_duration_ns = Some(PACKET_NS as u64); let mut mux = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![video, audio], MuxOptions::default()).unwrap(); mux.write_frame(0, 0, true, &picture, None).unwrap(); @@ -1624,7 +1632,7 @@ fn matroska_cold_seek_applies_codec_delay_once() { let signal = 16_384i16.to_le_bytes().repeat(PACKET_FRAMES); for n in 0..40 { let pcm = if n < CHANGE_PACKET { &silent } else { &signal }; - mux.write_frame(1, n * PACKET_NS - DELAY_NS, true, pcm, None).unwrap(); + mux.write_frame(1, n * PACKET_NS - delay_ns, true, pcm, None).unwrap(); } let bytes = mux.finish().unwrap().into_inner(); let mkv = matroska::open(bytes.as_slice()).unwrap(); @@ -1648,7 +1656,7 @@ fn matroska_cold_seek_applies_codec_delay_once() { let t = Tick::from_units(n * PACKET_FRAMES as i64, i64::from(RATE)); let _ = warm_pool.audio_samples(&warm, t, PACKET_FRAMES, RATE); } - let boundary = CHANGE_PACKET * PACKET_FRAMES as i64 - DELAY_NS * i64::from(RATE) / 1_000_000_000; + let boundary = CHANGE_PACKET * PACKET_FRAMES as i64 - delay_ns * i64::from(RATE) / 1_000_000_000; let t = Tick::from_units(boundary - HALF_WINDOW as i64, i64::from(RATE)); let sequential = warm_pool.audio_samples(&warm, t, 2 * HALF_WINDOW, RATE); assert_eq!(sequential.len(), 4 * HALF_WINDOW); From aa623b7577804b07f65ba59449f8aab4d8630327 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 22:10:32 -0500 Subject: [PATCH 331/393] media: preserve contiguous audio packet placement across rounding and gaps (#4008) * media: preserve contiguous audio packet placement across rounding and gaps Port @IppSec's contiguous_starts packet-placement logic from storytold/filmcraft#359 into CraftMediaSource so fixed-frame and Opus packets stay contiguous across 1ms Matroska timestamp rounding and laced blocks, while honoring real silence gaps, overlaps, and delayed first packets on both sequential playback and cold/backward seeks. Refs: storytold/effectcraft#1546 Refs: storytold/filmcraft#359 Co-authored-by: ippsec * media: fix opus_packet_samples helper and TrackDecoder borrow * media: use Footage and re-exported matroska mux types in audio gap tests --------- Co-authored-by: ippsec --- crates/media/src/craft_source.rs | 304 +++++++++++++++++++++++++++---- crates/media/tests/it/footage.rs | 162 ++++++++++++++++ 2 files changed, 431 insertions(+), 35 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index f4843db3a..dad5b9cd4 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -159,37 +159,158 @@ impl ContainerFile { } } - 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) + fn audio_seek_info(audio_starts: &[i64], seek_preroll_samples: i64, start: i64) -> (usize, i64) { + let target = start.saturating_sub(seek_preroll_samples).max(0); + let sample_idx = audio_starts.partition_point(|&s| s <= target).saturating_sub(1); + let seek_idx = sample_idx.saturating_sub(2); + let decoded_pos = audio_starts.get(seek_idx).copied().unwrap_or(0); + (seek_idx, decoded_pos) + } +} + +/// Where the container puts one audio packet, for [`contiguous_starts`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PacketTime { + /// Its timestamp, in output samples. + stamp: i64, + /// Whether `stamp` is the packet's own. A Matroska frame after the first in a laced block + /// without a duration repeats the block's timestamp. + stamped: bool, + /// Samples it decodes to, when known. + samples: Option, +} + +/// Packet start positions in output samples: each packet starts where the previous one ends, +/// unless its own timestamp is more than `tolerance` samples from there (a real gap or overlap in +/// the recording) or the previous packet's length is unknown; then it starts at its timestamp. +/// +/// Container timestamps are coarser than a sample. Matroska stores milliseconds, and a remux to MP4 +/// (OBS's) turns that rounding into uneven sample durations: a 1024-sample AAC frame at 48 kHz +/// lasts 21.33 ms, so frames are stamped at 0, 1008, 2064, 3072… Placing each decoded packet at its +/// stamp overwrote the end of one packet and left a hole of silence after another, a click every +/// few packets: crackling throughout playback and export (`storytold/effectcraft#1546`, +/// `storytold/filmcraft#359`). +fn contiguous_starts(packets: impl IntoIterator, tolerance: i64) -> Vec { + let tolerance = tolerance.max(0).unsigned_abs(); + let mut next: Option = None; + packets + .into_iter() + .map(|p| { + let start = match next { + Some(n) if !p.stamped || n.abs_diff(p.stamp) <= tolerance => n, + _ => p.stamp, + }; + next = p.samples.and_then(|k| start.checked_add(k)); + start + }) + .collect() +} + +fn fixed_packet_samples(dec: &mut AudioTrackDecoder, codec: CodecId, lookahead: &[Vec]) -> Option { + if !matches!(codec, CodecId::Aac | CodecId::HeAac | CodecId::Mp1 | CodecId::Mp2 | CodecId::Mp3 | CodecId::Ac3 | CodecId::Eac3) { + return None; + } + let mut frame_len: Option = None; + for pkt in lookahead { + let Ok(block) = dec.decode(pkt) else { + dec.reset(); + return None; + }; + let n = block.channels.first().map_or(0, Vec::len); + if n == 0 { + dec.reset(); + return None; + } + match frame_len { + None => frame_len = Some(n), + Some(prev) if prev != n => { + dec.reset(); + return None; } - ContainerFile::Matroska(f) => { - let track = &f.tracks[track_idx]; - // Indexed PTS already subtracts CodecDelay rounded to the container clock. - // Translate between that clock and the warm path's whole-frame delay. - let tick_ns = i128::from(f.info.timestamp_scale.max(1)); - let delay_ns = i128::from(track.codec_delay_ns); - let indexed_delay_ns = ((delay_ns + tick_ns / 2) / tick_ns) * tick_ns; - let delay_frames = audio_frames_from_ns(delay_ns, native_rate); - let preroll_ns = i128::from(track.seek_pre_roll_ns.max(80_000_000)); - let target_ns = ((i128::from(start.max(0)) + delay_frames) * 1_000_000_000) / i128::from(native_rate); - let seek_ns = (target_ns - preroll_ns - indexed_delay_ns).max(0); - let t_track = track.ns_to_ticks(i64::try_from(seek_ns).unwrap_or(i64::MAX)); - 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)) + indexed_delay_ns; - let decoded_pos = i64::try_from(audio_frames_from_ns(sample_ns, native_rate) - delay_frames).unwrap_or(0); - (seek_idx, decoded_pos) + Some(_) => {} + } + } + dec.reset(); + frame_len.and_then(|n| i64::try_from(n).ok()) +} + +/// Duration of an Opus packet in 48 kHz samples from its TOC (RFC 6716 §3.1); `None` if invalid. +fn opus_packet_samples(pkt: &[u8]) -> Option { + let &toc = pkt.first()?; + let config = toc >> 3; + let frame = match config { + 0..=11 => [480, 960, 1920, 2880][(config & 3) as usize], + 12..=15 => [480, 960][(config & 1) as usize], + _ => [120, 240, 480, 960][(config & 3) as usize], + }; + let frames = match toc & 3 { + 0 => 1, + 1 | 2 => 2, + _ => (*pkt.get(1)? & 0x3F) as u32, + }; + let n = frame * frames; + (n > 0 && n <= 5760).then_some(n) +} + +fn compute_audio_starts( + container: &ContainerFile, + source: &dyn ByteSource, + track_idx: usize, + codec: CodecId, + native_rate: u32, + fixed_samples: Option, +) -> Vec { + let rate = i128::from(native_rate); + match container { + ContainerFile::Isobmff(f) => { + let Some(track) = f.tracks.get(track_idx) else { return Vec::new() }; + let ts = i128::from(track.timescale.max(1)); + let stamps: Vec = (0..track.samples.len()) + .map(|i| { + let pts = track.presentation_pts(i).unwrap_or(0); + i64::try_from(i128::from(pts) * rate / ts).unwrap_or(0) + }) + .collect(); + let unit = i64::try_from((rate + ts - 1) / ts).unwrap_or(i64::MAX); + if codec == CodecId::Opus { + let packets = stamps.into_iter().enumerate().map(|(i, stamp)| { + let samples = f.read_sample(source, track_idx, i).ok().and_then(|p| opus_packet_samples(&p)).map(i64::from); + PacketTime { stamp, stamped: true, samples } + }); + return contiguous_starts(packets, unit.saturating_mul(2).saturating_add(1)); } + let Some(frame) = fixed_samples else { + return stamps; + }; + let tolerance = (frame / 2).max(unit.saturating_mul(2).saturating_add(1)); + let packets = stamps.into_iter().map(|stamp| PacketTime { stamp, stamped: true, samples: Some(frame) }); + contiguous_starts(packets, tolerance) + } + ContainerFile::Matroska(f) => { + let Some(track) = f.tracks.get(track_idx) else { return Vec::new() }; + // Indexed PTS already subtracts CodecDelay rounded to the container clock. + // Translate between that clock and the warm path's whole-frame delay. + let tick_ns = i128::from(f.info.timestamp_scale.max(1)); + let delay_ns = i128::from(track.codec_delay_ns); + let indexed_delay_ns = ((delay_ns + tick_ns / 2) / tick_ns) * tick_ns; + let delay_frames = audio_frames_from_ns(delay_ns, native_rate); + let stamp_for = |pts: i64| -> i64 { + let ns = i128::from(track.ticks_to_ns(pts)) + indexed_delay_ns; + i64::try_from(audio_frames_from_ns(ns, native_rate) - delay_frames).unwrap_or(0) + }; + let tick_samples = i64::try_from(i128::from(track.ticks_to_ns(2)) * rate / 1_000_000_000).unwrap_or(i64::MAX).saturating_add(1); + if codec == CodecId::Opus { + let packets = track.samples.iter().enumerate().map(|(i, s)| { + let samples = f.read_sample(source, track_idx, i).ok().and_then(|p| opus_packet_samples(&p)).map(i64::from); + PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples } + }); + return contiguous_starts(packets, tick_samples); + } + let Some(frame) = fixed_samples else { + return track.samples.iter().map(|s| stamp_for(s.pts)).collect(); + }; + let packets = track.samples.iter().map(|s| PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples: Some(frame) }); + contiguous_starts(packets, (frame / 2).max(tick_samples)) } } } @@ -204,7 +325,7 @@ where { let mut audio_tracks = Vec::new(); let mut audio_infos = Vec::new(); - for (idx, sample_count, params, codec_delay_ns) in candidates { + for (idx, sample_count, params, _codec_delay_ns) in candidates { if audio_tracks.len() >= MAX_AUDIO_STREAMS { break; } @@ -215,10 +336,20 @@ where lookahead.push(pkt); } let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect(); - let dec = AudioTrackDecoder::new(¶ms, &refs).ok()?; + let mut 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(audio_frames_from_ns(i128::from(codec_delay_ns), native_rate)).unwrap_or(0); + let codec = dec.codec(); + let fixed_samples = fixed_packet_samples(&mut dec, codec, &lookahead); + let audio_starts = compute_audio_starts(container, source, idx, codec, native_rate, fixed_samples); + let seek_preroll_samples = match container { + ContainerFile::Matroska(f) if codec == CodecId::Opus => { + let preroll_ns = i128::from(f.tracks[idx].seek_pre_roll_ns.max(80_000_000)); + i64::try_from(preroll_ns * i128::from(native_rate) / 1_000_000_000).unwrap_or(0) + } + _ => 0, + }; + let initial_pos = audio_starts.first().copied().unwrap_or(0); audio_infos.push(AudioStreamInfo { sample_rate: native_rate, channels, @@ -228,7 +359,9 @@ where 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() }), + audio_starts, + seek_preroll_samples, + state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), }); } Some((audio_tracks, audio_infos)) @@ -509,6 +642,8 @@ struct AudioTrackState { struct AudioTrackEntry { track_idx: usize, native_rate: u32, + audio_starts: Vec, + seek_preroll_samples: i64, state: Mutex, } @@ -622,7 +757,18 @@ impl MediaSource for CraftMediaSource { }; 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)?; + let decoded = decode_audio_range( + &self.file, + &*self.source, + entry.track_idx, + native_rate, + channels_count, + &entry.audio_starts, + entry.seek_preroll_samples, + &mut state, + native_start, + native_frames, + )?; if sample_rate == native_rate { return Ok(AudioBuffer { sample_rate, channels: decoded }); @@ -655,6 +801,8 @@ fn decode_audio_range( track_idx: usize, native_rate: u32, channels_count: usize, + audio_starts: &[i64], + seek_preroll_samples: i64, state: &mut AudioTrackState, start: i64, frames: usize, @@ -668,7 +816,7 @@ fn decode_audio_range( 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); + let (seek_idx, decoded_pos) = ContainerFile::audio_seek_info(audio_starts, seek_preroll_samples, start); state.decoder.reset(); state.next_sample = seek_idx; state.decoded_pos = decoded_pos; @@ -687,9 +835,38 @@ fn decode_audio_range( return Err(MediaError::Cancelled); } let idx = state.next_sample; + let pk_start = audio_starts.get(idx).copied().unwrap_or_else(|| state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64); + if pk_start >= end { + break; + } 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()))?; + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + if buf_len == 0 { + state.decoded_pos = pk_start; + } else { + let buf_end = state.decoded_pos.saturating_add(buf_len); + if pk_start > buf_end { + let gap = usize::try_from(pk_start - buf_end).unwrap_or(0); + for ch in &mut state.buf { + ch.resize(ch.len() + gap, 0.0); + } + } else if pk_start < buf_end { + if pk_start <= state.decoded_pos { + for ch in &mut state.buf { + ch.clear(); + } + state.decoded_pos = pk_start; + } else { + let overlap = usize::try_from(buf_end - pk_start).unwrap_or(0); + for ch in &mut state.buf { + let keep = ch.len().saturating_sub(overlap); + ch.truncate(keep); + } + } + } + } for (c, ch) in state.buf.iter_mut().enumerate() { if let Some(src_ch) = block.channels.get(c) { ch.extend_from_slice(src_ch); @@ -1318,4 +1495,61 @@ mod tests { assert_eq!(out.map(|f| f.par), Some((3, 4))); } } + + /// 1024-sample frames at 48 kHz stamped to the nearest millisecond, then back in samples. + fn ms_stamps(count: i64) -> Vec { + (0..count).map(|k| (k * 1024 * 1000 + 24_000) / 48_000 * 48).collect() + } + + fn timed(stamps: &[i64], samples: Option) -> Vec { + stamps.iter().map(|&stamp| PacketTime { stamp, stamped: true, samples }).collect() + } + + #[test] + fn rounded_stamps_give_back_to_back_packets() { + let stamps = ms_stamps(200); + assert_eq!(&stamps[..4], [0, 1008, 2064, 3072]); + let starts = contiguous_starts(timed(&stamps, Some(1024)), 512); + assert_eq!(starts, (0..200).map(|k| k * 1024).collect::>()); + } + + #[test] + fn real_gaps_and_overlaps_resynchronise() { + // A 100 ms gap after packet 3, then a packet stamped 600 samples early. + let mut stamps: Vec = (0..8).map(|k| k * 1024).collect(); + for s in &mut stamps[4..] { + *s += 4800; + } + stamps[7] -= 600; + let starts = contiguous_starts(timed(&stamps, Some(1024)), 512); + assert_eq!(starts, [0, 1024, 2048, 3072, 8896, 9920, 10944, 11368]); + // Within the tolerance: runs on. + stamps[7] += 200; + assert_eq!(contiguous_starts(timed(&stamps, Some(1024)), 512)[7], 11968); + } + + #[test] + fn unstamped_packets_follow_on_and_unknown_lengths_resynchronise() { + let packets = [0, 1024, 1024, 1024, 4096].map(|stamp| PacketTime { stamp, stamped: true, samples: Some(1024) }); + let mut laced = packets; + laced[2].stamped = false; + laced[3].stamped = false; + assert_eq!(contiguous_starts(laced, 512), [0, 1024, 2048, 3072, 4096]); + let mut unknown = timed(&[0, 1024, 2100, 3124], Some(1024)); + unknown[1].samples = None; + assert_eq!(contiguous_starts(unknown, 512), [0, 1024, 2100, 3124]); + } + + #[test] + fn hostile_values_stay_finite() { + let packets = [ + PacketTime { stamp: i64::MAX, stamped: true, samples: Some(i64::MAX) }, + PacketTime { stamp: i64::MIN, stamped: false, samples: Some(-5) }, + PacketTime { stamp: 0, stamped: true, samples: Some(i64::MIN) }, + PacketTime { stamp: 7, stamped: true, samples: None }, + ]; + assert_eq!(contiguous_starts(packets, i64::MIN).len(), 4); + assert_eq!(contiguous_starts(packets, i64::MAX).len(), 4); + assert!(contiguous_starts([], 512).is_empty()); + } } diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index df1751ff6..adbab9291 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1727,3 +1727,165 @@ fn audio_only_isobmff_and_matroska_route_through_craft_audio() { assert!((rms_seek - 0.0625).abs() < 0.02, "{file} seek rms {rms_seek}"); } } + +fn read_audio_sequential(pool: &MediaPool, f: &Footage, total_frames: usize, chunk_frames: usize, rate: u32) -> Vec { + let mut out = Vec::with_capacity(total_frames * 2); + let mut pos = 0usize; + while pos < total_frames { + let len = chunk_frames.min(total_frames - pos); + let t = Tick::from_units(pos as i64, i64::from(rate)); + out.extend_from_slice(&pool.audio_samples(f, t, len, rate)); + pos += len; + } + out +} + +fn slice_rms(samples: &[f32]) -> f32 { + if samples.is_empty() { + return 0.0; + } + (samples.iter().map(|v| v * v).sum::() / samples.len() as f32).sqrt() +} + +fn assert_samples_close(a: &[f32], b: &[f32], tol: f32, ctx: &str) { + assert_eq!(a.len(), b.len(), "{ctx}: length mismatch"); + let max_diff = a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); + assert!(max_diff <= tol, "{ctx}: max_diff {max_diff} > {tol}"); +} + +#[test] +fn mkv_and_mp4_aac_play_continuously_without_crackle_and_seek_matches_sequential() { + let Some(mp4_path) = + try_ffmpeg_fixture("aac_1546_pair.mp4", &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2", "-c:a", "aac", "-b:a", "128k"]) + else { + return; + }; + let mp4_str = mp4_path.to_string_lossy().into_owned(); + let Some(mkv_path) = try_ffmpeg_fixture("aac_1546_pair.mkv", &["-i", &mp4_str, "-c:a", "copy"]) else { + return; + }; + + let mp4 = probe(&mp4_path).expect("probe mp4"); + let mkv = probe(&mkv_path).expect("probe mkv"); + let rate = 48_000u32; + let total_frames = 80_000usize; + + let mp4_seq = read_audio_sequential(&MediaPool::new(), &mp4, total_frames, 4096, rate); + let mkv_seq = read_audio_sequential(&MediaPool::new(), &mkv, total_frames, 4096, rate); + + // After the initial priming window (0.1s), MKV and MP4 must match without crackle. + let skip = 4800 * 2; + assert_samples_close(&mp4_seq[skip..], &mkv_seq[skip..], 0.01, "mkv vs mp4 sequential"); + + // Cold seeks on fresh MediaPools at t=0.5s and t=1.0s must match sequential playback. + for seek_frame in [24_000usize, 48_000usize] { + let t = Tick::from_units(seek_frame as i64, i64::from(rate)); + let cold = MediaPool::new().audio_samples(&mkv, t, 4800, rate); + let start = seek_frame * 2; + assert_samples_close(&cold, &mkv_seq[start..start + 4800 * 2], 1e-4, "mkv cold seek vs sequential"); + } + + // Backward seek after reading near the end must also match sequential playback. + let back_pool = MediaPool::new(); + let _ = back_pool.audio_samples(&mkv, Tick::from_units(60_000, i64::from(rate)), 4800, rate); + let backward = back_pool.audio_samples(&mkv, Tick::from_units(24_000, i64::from(rate)), 4800, rate); + assert_samples_close(&backward, &mkv_seq[24_000 * 2..24_000 * 2 + 4800 * 2], 1e-4, "mkv backward seek vs sequential"); +} + +fn build_gapped_aac_mkv(out_path: &Path, gap_at_pkt: usize, gap_ns: i64, start_offset_ns: i64) -> Option<()> { + let mp4_path = + try_ffmpeg_fixture("aac_1546_pair.mp4", &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2", "-c:a", "aac", "-b:a", "128k"])?; + let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(std::fs::read(&mp4_path).ok()?); + let mp4 = craft_media::isobmff::open(bytes.clone()).ok()?; + let track_idx = mp4.tracks.iter().position(|t| t.kind == craft_media::isobmff::TrackKind::Audio)?; + let track = &mp4.tracks[track_idx]; + let asc = match &track.entries.first()?.codec { + craft_media::isobmff::CodecConfig::Aac(a) => a.asc.clone(), + _ => return None, + }; + + let mut spec = craft_media::matroska::TrackSpec::new(craft_media::matroska::TrackKind::Audio, "A_AAC"); + spec.codec_private = asc; + spec.audio = Some((48_000.0, u64::from(track.audio().map_or(2, |a| a.channels)), None)); + let mut writer = craft_media::matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], craft_media::matroska::MuxOptions::default()).ok()?; + + let pkt_count = track.samples.len().min(60); + for i in 0..pkt_count { + let pkt = mp4.read_sample(&*bytes, track_idx, i).ok()?; + let base_ns = (i as i64 * 1024 * 1_000_000_000) / 48_000; + let extra = if i >= gap_at_pkt { gap_ns } else { 0 }; + writer.write_frame(0, start_offset_ns + base_ns + extra, true, &pkt, None).ok()?; + } + let mkv_bytes = writer.finish().ok()?.into_inner(); + std::fs::write(out_path, mkv_bytes).ok()?; + Some(()) +} + +#[test] +fn audio_real_silence_gap_honored_on_sequential_and_seek() { + let dir = tempfile::tempdir().expect("tempdir"); + let mkv_path = dir.path().join("real_gap.mkv"); + // 24 packets (~0.512s) at 0, then a 500 ms silence gap before packet 24. + if build_gapped_aac_mkv(&mkv_path, 24, 500_000_000, 0).is_none() { + return; + } + + let f = probe(&mkv_path).expect("probe gapped mkv"); + let rate = 48_000u32; + let total_frames = 72_000usize; + let seq = read_audio_sequential(&MediaPool::new(), &f, total_frames, 4096, rate); + + // Pre-gap tone (0.1s..0.4s), silence gap (0.55s..0.95s), post-gap tone (1.1s..1.4s). + assert!(slice_rms(&seq[4800 * 2..19_200 * 2]) > 0.04, "pre-gap tone expected"); + assert!(slice_rms(&seq[26_400 * 2..45_600 * 2]) < 1e-4, "silence gap expected"); + assert!(slice_rms(&seq[52_800 * 2..67_200 * 2]) > 0.04, "post-gap tone expected"); + + for seek_frame in [9_600usize, 30_000usize, 54_000usize] { + let t = Tick::from_units(seek_frame as i64, i64::from(rate)); + let cold = MediaPool::new().audio_samples(&f, t, 4800, rate); + let start = seek_frame * 2; + assert_samples_close(&cold, &seq[start..start + 4800 * 2], 1e-4, "gap cold seek vs sequential"); + } + + let back_pool = MediaPool::new(); + let _ = back_pool.audio_samples(&f, Tick::from_units(54_000, i64::from(rate)), 4800, rate); + for seek_frame in [30_000usize, 9_600usize] { + let backward = back_pool.audio_samples(&f, Tick::from_units(seek_frame as i64, i64::from(rate)), 4800, rate); + let start = seek_frame * 2; + assert_samples_close(&backward, &seq[start..start + 4800 * 2], 1e-4, "gap backward seek vs sequential"); + } +} + +#[test] +fn audio_delayed_first_packet_honored_on_sequential_and_seek() { + let dir = tempfile::tempdir().expect("tempdir"); + let mkv_path = dir.path().join("delayed_first.mkv"); + // First packet delayed by 500 ms. + if build_gapped_aac_mkv(&mkv_path, usize::MAX, 0, 500_000_000).is_none() { + return; + } + + let f = probe(&mkv_path).expect("probe delayed mkv"); + let rate = 48_000u32; + let total_frames = 57_600usize; + let seq = read_audio_sequential(&MediaPool::new(), &f, total_frames, 4096, rate); + + // Leading silence (0..0.45s) and delayed tone (0.6s..1.0s). + assert!(slice_rms(&seq[..21_600 * 2]) < 1e-4, "leading silence expected"); + assert!(slice_rms(&seq[28_800 * 2..48_000 * 2]) > 0.04, "delayed tone expected"); + + for seek_frame in [4_800usize, 30_000usize] { + let t = Tick::from_units(seek_frame as i64, i64::from(rate)); + let cold = MediaPool::new().audio_samples(&f, t, 4800, rate); + let start = seek_frame * 2; + assert_samples_close(&cold, &seq[start..start + 4800 * 2], 1e-4, "delayed cold seek vs sequential"); + } + + let back_pool = MediaPool::new(); + let _ = back_pool.audio_samples(&f, Tick::from_units(36_000, i64::from(rate)), 4800, rate); + for seek_frame in [30_000usize, 4_800usize] { + let backward = back_pool.audio_samples(&f, Tick::from_units(seek_frame as i64, i64::from(rate)), 4800, rate); + let start = seek_frame * 2; + assert_samples_close(&backward, &seq[start..start + 4800 * 2], 1e-4, "delayed backward seek vs sequential"); + } +} From 3561194af374eac5247629737a30f20845c9f8ce Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 23:55:20 -0500 Subject: [PATCH 332/393] media: route standalone audio (WAV/AIFF/MP3/AAC/AC-3/Ogg Opus) through craft-audio (#4009) * media: route standalone WAV, AIFF, MP3, ADTS AAC, AC-3, and Ogg Opus through craft-audio * media: fix slice indexing and exhaustive SampleFormat match * media: gate standalone audio for wasm, handle rate 0, and read wav markers * media: use ext_of(path) == "wav" for wav_markers in probe * media: deduplicate native_audio_window and drain_audio_window --- Cargo.lock | 2 + crates/media/Cargo.toml | 2 +- crates/media/src/craft_source.rs | 318 +++++++++++++++++++++++++------ crates/media/src/probe.rs | 5 + crates/media/tests/it/footage.rs | 30 +++ 5 files changed, 303 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 360c25794..619e268fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1210,6 +1210,8 @@ version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" dependencies = [ "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "log", "thiserror 2.0.21", ] diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 668828fca..1808f6470 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -27,7 +27,7 @@ craft-dpx = { workspace = true } craft-exr = { workspace = true, features = ["decode"] } craft-gif = { workspace = true, features = ["frames"] } craft-webp = { workspace = true, features = ["frames"] } -craft-audio = { workspace = true, features = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] } craft-color = { workspace = true } craft-frame = { workspace = true } craft-media = { workspace = true, features = ["mpegts"] } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index dad5b9cd4..70614eec2 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -17,8 +17,11 @@ //! `Mp3`/`Mp2`/`Mp1` (with `CodecDelay` + `SeekPreRoll` timing). //! - Fallback (`filmcraft-codecs`): `alpha_mode == 1` (`BlockAdditional` alpha), unreadable/zlib //! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Flac`/`Pcm`). -//! - **Other containers (`MXF`, `AVI`, `MPEG-TS`/`PS`, `Ogg`, standalone `WAV`/`AIFF`/`FLAC`/`MP3`)**: -//! - Currently routed via `filmcraft-codecs` in `stream.rs` (pending subsequent cutover PRs). +//! - **Other containers & standalone audio**: +//! - Shared (`craft_audio::Decoder` with `decode-native`): standalone `WAV`, `AIFF`, `MP3`/`MP2`/`MP1`, +//! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). +//! - Fallback (`filmcraft-codecs`): `MXF`, `AVI`, `MPEG-TS`/`PS`, `Ogg Vorbis`, `FLAC`, `CAF`, or +//! unsupported WAV/AIFF encodings. use std::sync::{Arc, Mutex}; @@ -69,7 +72,7 @@ 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`. +/// Open an in-place ISO-BMFF, Matroska/WebM, or standalone audio source via `craft-media` / `craft-audio`. /// 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> { @@ -79,10 +82,10 @@ pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Opti if looks_like_matroska(head) { return open_matroska(name, reader.clone()); } - None + open_standalone_audio(name, head, reader.clone()) } -/// Open an in-memory ISO-BMFF or Matroska/WebM source via `craft-media` / `craft-video`. +/// Open an in-memory ISO-BMFF, Matroska/WebM, or standalone audio source via `craft-media` / `craft-audio`. pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { if looks_like_isobmff(&bytes) { return open_isobmff(name, Arc::new(bytes)); @@ -90,7 +93,16 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option::len(&bytes).min(64); + let head = bytes[..head_len].to_vec(); + open_standalone_audio(name, &head, Arc::new(bytes)) + } + #[cfg(not(any(unix, windows)))] + { + None + } } enum ContainerFile { @@ -748,13 +760,7 @@ impl MediaSource for CraftMediaSource { } 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 (native_start, native_frames) = native_audio_window(start, frames, native_rate, sample_rate); let mut state = entry.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let decoded = decode_audio_range( @@ -774,24 +780,210 @@ impl MediaSource for CraftMediaSource { 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: resample_audio(&decoded, channels_count, native_rate, sample_rate, frames) }) + } +} + +#[cfg(any(unix, windows))] +struct SharedBytesSource(SharedBytes); + +#[cfg(any(unix, windows))] +impl ByteSource for SharedBytesSource { + fn len(&self) -> u64 { + self.0.len() + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.0.read_at(offset, buf) + } +} + +#[cfg(any(unix, windows))] +struct StandaloneAudioState { + decoder: craft_audio::Decoder<'static>, + decoded_pos: i64, + buf: Vec>, +} + +#[cfg(any(unix, windows))] +struct StandaloneAudioSource { + info: MediaInfo, + native_rate: u32, + state: Mutex, +} + +#[cfg(any(unix, windows))] +impl MediaSource for StandaloneAudioSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, _req: FrameRequest) -> Result> { + Err(MediaError::NoStream("video")) + } + + 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 { + if stream != 0 { + return Err(MediaError::NoStream("audio")); + } + let channels_count = self.info.audio_streams.first().map_or(2, |s| s.channels as usize); + if frames == 0 || sample_rate == 0 { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + } + let native_rate = self.native_rate; + let (native_start, native_frames) = native_audio_window(start, frames, native_rate, sample_rate); + + let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let decoded = decode_standalone_range(native_rate, channels_count, &mut state, native_start, native_frames)?; + if sample_rate == native_rate { + return Ok(AudioBuffer { sample_rate, channels: decoded }); + } + Ok(AudioBuffer { sample_rate, channels: resample_audio(&decoded, channels_count, native_rate, sample_rate, frames) }) + } +} + +#[cfg(any(unix, windows))] +fn decode_standalone_range(native_rate: u32, channels_count: usize, state: &mut StandaloneAudioState, start: i64, frames: usize) -> Result>> { + let end = start.saturating_add(frames as i64); + if end <= 0 { + return Ok(vec![vec![0.0f32; frames]; channels_count]); + } + + 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 target = u64::try_from(start.max(0)).unwrap_or(0); + let actual = state.decoder.seek(target).map_err(|e| MediaError::Decode(e.to_string()))?; + state.decoded_pos = i64::try_from(actual).unwrap_or(i64::MAX); + 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 { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + let Some(block) = state.decoder.next_block().map_err(|e| MediaError::Decode(e.to_string()))? else { + break; + }; + for (c, ch) in state.buf.iter_mut().enumerate() { + if let Some(src_ch) = block.channels.get(c) { + ch.extend_from_slice(src_ch); } } - Ok(AudioBuffer { sample_rate, channels: resampled }) } + + Ok(drain_audio_window(&mut state.buf, &mut state.decoded_pos, channels_count, start, frames)) +} + +fn native_audio_window(start: i64, frames: usize, native_rate: u32, sample_rate: u32) -> (i64, usize) { + if sample_rate == native_rate { + return (start, frames); + } + 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) +} + +fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_count: usize, start: i64, frames: usize) -> Vec> { + let mut out = vec![vec![0.0f32; frames]; channels_count]; + let avail = buf.first().map_or(0, Vec::len); + for i in 0..frames { + let pos = start.saturating_add(i as i64); + if pos >= *decoded_pos { + let off = (pos - *decoded_pos) as usize; + if off < avail { + for (c, out_ch) in out.iter_mut().enumerate() { + out_ch[i] = buf[c][off]; + } + } + } + } + let end = start.saturating_add(frames as i64); + let drop_to = (end - *decoded_pos).max(0) as usize; + let trim = drop_to.min(avail); + if trim > 0 { + for ch in buf { + ch.drain(..trim); + } + *decoded_pos = decoded_pos.saturating_add(trim as i64); + } + out +} + +fn resample_audio(decoded: &[Vec], channels_count: usize, native_rate: u32, sample_rate: u32, frames: usize) -> Vec> { + 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; + } + } + resampled +} + +#[cfg(any(unix, windows))] +fn open_standalone_audio(name: &str, head: &[u8], source: SharedBytes) -> Option> { + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()); + let container = craft_audio::detect_container(head, ext)?; + let container_name = match container { + craft_audio::Container::Wav => "wav", + craft_audio::Container::Aiff => "aiff", + craft_audio::Container::MpegAudio => "mp3", + craft_audio::Container::Adts => "aac", + craft_audio::Container::Ac3 => "ac3", + craft_audio::Container::Ogg => "ogg", + _ => return None, + }; + + let dec = craft_audio::Decoder::open(SharedBytesSource(source.clone()), ext, &craft_audio::DecodeOptions::default()).ok()?; + let audio_info = if dec.length_known() { + dec.info().clone() + } else { + craft_audio::Decoder::open(SharedBytesSource(source.clone()), ext, &craft_audio::DecodeOptions::default()).ok()?.probe().ok()? + }; + + let native_rate = audio_info.sample_rate.max(1); + let channels = u32::from(audio_info.channels).max(1); + let duration = Tick::from_units(i64::try_from(audio_info.frames).unwrap_or(i64::MAX), i64::from(native_rate)); + let bits_per_sample = match audio_info.sample_format { + craft_audio::SampleFormat::Int8 => Some(8), + craft_audio::SampleFormat::Int16 => Some(16), + craft_audio::SampleFormat::Int24 => Some(24), + craft_audio::SampleFormat::Int32 | craft_audio::SampleFormat::Float32 => Some(32), + craft_audio::SampleFormat::Float64 => Some(64), + craft_audio::SampleFormat::Compressed | _ => None, + }; + let info = MediaInfo { + name: name.to_string(), + kind: MediaKind::AudioOnly, + duration, + video: None, + audio_streams: vec![AudioStreamInfo { sample_rate: native_rate, channels, codec: audio_info.codec.name().to_string(), bits_per_sample }], + container: container_name.to_string(), + start_timecode: None, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(StandaloneAudioSource { info, native_rate, state: Mutex::new(StandaloneAudioState { decoder: dec, decoded_pos: 0, buf: Vec::new() }) }))) } #[allow(clippy::too_many_arguments)] @@ -807,10 +999,9 @@ fn decode_audio_range( 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); + return Ok(vec![vec![0.0f32; frames]; channels_count]); } let buf_len = state.buf.first().map_or(0, Vec::len) as i64; @@ -874,29 +1065,7 @@ fn decode_audio_range( } } - 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) + Ok(drain_audio_window(&mut state.buf, &mut state.decoded_pos, channels_count, start, frames)) } fn push_decoded( @@ -1496,6 +1665,49 @@ mod tests { } } + #[test] + fn standalone_wav_opens_seeks_and_resamples_via_craft_audio() { + // Minimal 48 kHz stereo 16-bit PCM WAV with 4800 frames (0.1s). + let frames = 4800u32; + let data_bytes = frames * 4; + let mut wav = Vec::with_capacity(44 + data_bytes as usize); + wav.extend_from_slice(b"RIFF"); + wav.extend_from_slice(&(36 + data_bytes).to_le_bytes()); + wav.extend_from_slice(b"WAVEfmt "); + wav.extend_from_slice(&16u32.to_le_bytes()); + wav.extend_from_slice(&1u16.to_le_bytes()); + wav.extend_from_slice(&2u16.to_le_bytes()); + wav.extend_from_slice(&48_000u32.to_le_bytes()); + wav.extend_from_slice(&(48_000u32 * 4).to_le_bytes()); + wav.extend_from_slice(&4u16.to_le_bytes()); + wav.extend_from_slice(&16u16.to_le_bytes()); + wav.extend_from_slice(b"data"); + wav.extend_from_slice(&data_bytes.to_le_bytes()); + for i in 0..frames * 2 { + let s = (((i as i32 * 257) % 16000) - 8000) as i16; + wav.extend_from_slice(&s.to_le_bytes()); + } + + let src = open_bytes("tone.wav", Arc::from(wav)).expect("recognized").expect("opened"); + let info = src.info(); + assert_eq!(info.container, "wav"); + assert_eq!(info.kind, MediaKind::AudioOnly); + assert_eq!(info.audio_streams[0].sample_rate, 48_000); + assert_eq!(info.audio_streams[0].bits_per_sample, Some(16)); + + let head = src.audio(0, 512, 48_000).expect("head"); + assert_eq!(head.channels[0].len(), 512); + let tail = src.audio(4000, 512, 48_000).expect("forward seek"); + assert!(tail.channels[0].iter().any(|&v| v.abs() > 0.01)); + let back = src.audio(0, 512, 48_000).expect("backward seek"); + assert_eq!(head.channels[0], back.channels[0]); + let neg = src.audio(-50, 100, 48_000).expect("negative start"); + assert!(neg.channels[0][..50].iter().all(|&v| v == 0.0)); + let resampled = src.audio(0, 256, 44_100).expect("resampled"); + assert_eq!(resampled.sample_rate, 44_100); + assert_eq!(resampled.channels[0].len(), 256); + } + /// 1024-sample frames at 48 kHz stamped to the nearest millisecond, then back in samples. fn ms_stamps(count: i64) -> Vec { (0..count).map(|k| (k * 1024 * 1000 + 24_000) / 48_000 * 48).collect() diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 52a29a363..74d8fb9a5 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -28,6 +28,11 @@ pub fn probe(path: impl AsRef) -> Result { // A movie is read in place (its index), not loaded whole. if let Some(src) = crate::stream::probe_source(path) { let mut f = footage_from_source(&path.to_string_lossy(), &src?); + if ext_of(path) == "wav" + && let Ok(bytes) = crate::read_regular_file(path) + { + f.markers = crate::wav_markers::read(&bytes); + } let header = crate::stream::movie_header(path); let turn = header.as_deref().map_or(Orientation::NoTransforms, video_turn); turn_footage(&mut f, turn); diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index adbab9291..08b7158b1 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1728,6 +1728,36 @@ fn audio_only_isobmff_and_matroska_route_through_craft_audio() { } } +#[test] +fn standalone_audio_formats_route_through_craft_audio() { + for (file, args) in [ + ("standalone_tone.wav", &["-c:a", "pcm_s16le"][..]), + ("standalone_tone.aiff", &["-c:a", "pcm_s16be"][..]), + ("standalone_tone.mp3", &["-c:a", "libmp3lame", "-b:a", "128k"][..]), + ("standalone_tone.aac", &["-c:a", "aac", "-b:a", "128k"][..]), + ("standalone_tone.ac3", &["-c:a", "ac3", "-b:a", "192k"][..]), + ("standalone_tone.ogg", &["-c:a", "libopus"][..]), + ] { + let mut ffmpeg_args = vec!["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=1"]; + ffmpeg_args.extend_from_slice(args); + let Some(p) = try_ffmpeg_fixture(file, &ffmpeg_args) else { + continue; + }; + let f = probe(&p).expect(file); + assert_eq!(f.kind, FootageKind::Audio, "{file} must probe as Audio"); + assert!(!f.has_video, "{file} has no video"); + assert!(f.has_audio, "{file} has audio"); + assert!(f.duration >= Tick(TICKS_PER_SECOND * 8 / 10), "{file} duration {:?}", f.duration); + let pool = MediaPool::new(); + let start = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000); + let seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000); + assert_eq!(start.len(), 9600, "{file} start len"); + assert_eq!(seek.len(), 9600, "{file} seek len"); + let rms_seek = (seek.iter().map(|v| v * v).sum::() / seek.len() as f32).sqrt(); + assert!((rms_seek - 0.0625).abs() < 0.03, "{file} seek rms {rms_seek}"); + } +} + fn read_audio_sequential(pool: &MediaPool, f: &Footage, total_frames: usize, chunk_frames: usize, rate: u32) -> Vec { let mut out = Vec::with_capacity(total_frames * 2); let mut pos = 0usize; From 1c9892264cd8c9ea38882d1875344fbcb264f2fd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 00:25:07 -0500 Subject: [PATCH 333/393] media: preserve durationless laced audio and narrow overlap reads (#4013) --- crates/media/src/craft_source.rs | 122 +++++++++++++++++++++++++++++-- 1 file changed, 117 insertions(+), 5 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 70614eec2..ec45a35b5 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -171,10 +171,20 @@ impl ContainerFile { } } - fn audio_seek_info(audio_starts: &[i64], seek_preroll_samples: i64, start: i64) -> (usize, i64) { + fn audio_packet_is_stamped(&self, track_idx: usize, sample_idx: usize) -> bool { + match self { + Self::Isobmff(_) => true, + Self::Matroska(f) => f.tracks[track_idx].samples.get(sample_idx).is_some_and(|s| s.lace == 0 || s.duration > 0), + } + } + + fn audio_seek_info(&self, track_idx: usize, audio_starts: &[i64], seek_preroll_samples: i64, start: i64) -> (usize, i64) { let target = start.saturating_sub(seek_preroll_samples).max(0); let sample_idx = audio_starts.partition_point(|&s| s <= target).saturating_sub(1); - let seek_idx = sample_idx.saturating_sub(2); + let mut seek_idx = sample_idx.saturating_sub(2); + while seek_idx > 0 && !self.audio_packet_is_stamped(track_idx, seek_idx) { + seek_idx -= 1; + } let decoded_pos = audio_starts.get(seek_idx).copied().unwrap_or(0); (seek_idx, decoded_pos) } @@ -1007,7 +1017,7 @@ fn decode_audio_range( 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) = ContainerFile::audio_seek_info(audio_starts, seek_preroll_samples, start); + let (seek_idx, decoded_pos) = file.audio_seek_info(track_idx, audio_starts, seek_preroll_samples, start); state.decoder.reset(); state.next_sample = seek_idx; state.decoded_pos = decoded_pos; @@ -1021,12 +1031,14 @@ fn decode_audio_range( } 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 { + while state.next_sample < sample_count { if filmcraft_media::cancel::cancelled() { return Err(MediaError::Cancelled); } let idx = state.next_sample; - let pk_start = audio_starts.get(idx).copied().unwrap_or_else(|| state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64); + let buf_len = state.buf.first().map_or(0, Vec::len) as i64; + let buf_end = state.decoded_pos.saturating_add(buf_len); + let pk_start = if buf_len > 0 && !file.audio_packet_is_stamped(track_idx, idx) { buf_end } else { audio_starts.get(idx).copied().unwrap_or(buf_end) }; if pk_start >= end { break; } @@ -1764,4 +1776,104 @@ mod tests { assert_eq!(contiguous_starts(packets, i64::MAX).len(), 4); assert!(contiguous_starts([], 512).is_empty()); } + + fn pcm_s16le_bytes(sample: i16, count: usize) -> Vec { + std::iter::repeat_n(sample.to_le_bytes(), count).flatten().collect() + } + + #[test] + fn matroska_durationless_lace_variable_pcm_preserves_all_blocks() { + use std::io::Cursor; + + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_PCM/INT/LIT"); + track.audio = Some((48_000.0, 1, Some(16))); + let mut mux = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default()).unwrap(); + let blocks = [(8_000i16, 120usize), (-16_000i16, 200usize), (24_000i16, 80usize), (4_000i16, 100usize)]; + let pts_ns = [0i64, 2_000_000, 4_000_000, 8_333_333]; + for ((val, len), pts) in blocks.iter().zip(pts_ns) { + mux.write_frame(0, pts, true, &pcm_s16le_bytes(*val, *len), None).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let mut mkv = matroska::open(bytes.as_slice()).unwrap(); + // Simulate a durationless lace for blocks 0..3 sharing block 0's timestamp. + let base_pts = mkv.tracks[0].samples[0].pts; + for (lace, s) in mkv.tracks[0].samples[..3].iter_mut().enumerate() { + s.pts = base_pts; + s.duration = 0; + s.lace = lace as u16; + } + let params = mkv.tracks[0].codec_params(); + let file = ContainerFile::Matroska(Box::new(mkv)); + let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 4, params.clone(), 0)]).unwrap(); + + let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { + decode_audio_range(&file, &bytes, 0, 48_000, 1, &track.audio_starts, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames) + .unwrap() + }; + + let full = decode(&mut tracks[0], 0, 500); + assert_eq!(full[0].len(), 500); + // Each block's samples remain intact at their cumulative offsets (0..120, 120..320, 320..400, 400..500). + assert!((full[0][0] - (8_000.0 / 32_768.0)).abs() < 1e-4); + assert!((full[0][120] - (-16_000.0 / 32_768.0)).abs() < 1e-4); + assert!((full[0][320] - (24_000.0 / 32_768.0)).abs() < 1e-4); + assert!((full[0][400] - (4_000.0 / 32_768.0)).abs() < 1e-4); + + // Chunked sequential reads and a backward seek into the lace must match the full read. + let (mut chunked_tracks, _) = open_audio_tracks(&file, &bytes, [(0, 4, params, 0)]).unwrap(); + let mut chunked = Vec::new(); + for (start, frames) in [(0, 150), (150, 200), (350, 150)] { + chunked.extend_from_slice(&decode(&mut chunked_tracks[0], start, frames)[0]); + } + assert_eq!(chunked, full[0]); + + let rewound = decode(&mut tracks[0], 200, 250); + assert_eq!(rewound[0], full[0][200..450]); + } + + #[test] + fn narrow_read_includes_overlapping_packet_like_wider_read() { + use std::io::Cursor; + + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_PCM/INT/LIT"); + track.audio = Some((48_000.0, 1, Some(16))); + let mut mux = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default()).unwrap(); + mux.write_frame(0, 0, true, &pcm_s16le_bytes(8_000, 1024), None).unwrap(); + mux.write_frame(0, 10_666_667, true, &pcm_s16le_bytes(-16_000, 1024), None).unwrap(); + let bytes = mux.finish().unwrap().into_inner(); + let mkv = matroska::open(bytes.as_slice()).unwrap(); + let params = mkv.tracks[0].codec_params(); + let file = ContainerFile::Matroska(Box::new(mkv)); + + let open_with_overlap = || { + let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 2, params.clone(), 0)]).unwrap(); + tracks[0].audio_starts = vec![0, 512]; + tracks + }; + let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { + decode_audio_range(&file, &bytes, 0, 48_000, 1, &track.audio_starts, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames) + .unwrap() + }; + + let mut wide_tracks = open_with_overlap(); + let wide = decode(&mut wide_tracks[0], 0, 1536); + + // Narrow read [0, 600) ends before packet 0's 1024-sample tail, yet must include packet 1 at 512. + let mut narrow_tracks = open_with_overlap(); + let narrow = decode(&mut narrow_tracks[0], 0, 600); + assert_eq!(narrow[0], wide[0][..600]); + assert!((narrow[0][0] - (8_000.0 / 32_768.0)).abs() < 1e-4); + assert!((narrow[0][512] - (-16_000.0 / 32_768.0)).abs() < 1e-4); + + // Chunked reads and a backward seek over the same interval must also match. + let mut chunked_tracks = open_with_overlap(); + let mut chunked = Vec::new(); + for (start, frames) in [(0, 300), (300, 300)] { + chunked.extend_from_slice(&decode(&mut chunked_tracks[0], start, frames)[0]); + } + assert_eq!(chunked, wide[0][..600]); + + let rewound = decode(&mut wide_tracks[0], 0, 600); + assert_eq!(rewound[0], wide[0][..600]); + } } From 70c195ec28a5f8b76c4ad7d71f05aac181972710 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:46:35 +0700 Subject: [PATCH 334/393] Preserve recorded MOV timecode in the shared reader (#4012) Use the timecode track's presentation clock to rebase EDL source timecodes for compatible continuous edits. Leave ambiguous origins unset. --- crates/media/src/craft_source.rs | 72 ++++++++++++- crates/media/tests/it/file_timecode.rs | 136 +++++++++++++++++++++++-- 2 files changed, 200 insertions(+), 8 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index ec45a35b5..20816535c 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -446,6 +446,75 @@ fn clean_aperture_region(aperture: isobmff::CleanAperture, (width, height): (u32 (!r.is_full(width as usize, height as usize)).then_some(r) } +/// A single unit-rate media span, optionally preceded by one empty span. A +/// scalar EDL origin cannot describe dwell, disjoint edits or respeeding. +fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Option<(i64, i64)> { + const UNIT_RATE: i32 = 0x0001_0000; + let (leading_duration, media) = match track.edits.as_slice() { + [] => return (track.edit_offset == 0).then_some((0, 0)), + [media] => (0, media), + [empty, media] if empty.media_time == -1 && empty.segment_duration > 0 && empty.media_rate == UNIT_RATE => (empty.segment_duration, media), + _ => return None, + }; + if media.media_time < 0 || media.segment_duration == 0 || media.media_rate != UNIT_RATE || movie_timescale == 0 || track.timescale == 0 { + return None; + } + // Check the raw movie-to-media conversion before the demuxer's rounded + // offset can make a fractional delay look like an integral frame. + let lead = i128::from(leading_duration) * i128::from(track.timescale); + let movie_clock = i128::from(movie_timescale); + if lead % movie_clock != 0 { + return None; + } + let offset = i64::try_from(lead / movie_clock - i128::from(media.media_time)).ok()?; + (offset == track.edit_offset).then_some((media.media_time, offset)) +} + +/// The EDL origin is the timecode at presentation time zero, not the raw +/// counter at the start of the timecode sample. Its own track's edit and media +/// clock determine that sample's position; the video may have a different edit. +fn isobmff_timecode_origin(file: &Mp4File, video_idx: usize, video_rate: FrameRate) -> Option { + let video = file.tracks.get(video_idx)?; + continuous_edit_mapping(video, file.timescale)?; + let mut links = video.references.iter().filter(|(kind, _)| kind.0 == *b"tmcd").flat_map(|(_, ids)| ids); + let linked = links.next(); + if links.next().is_some() { + return None; + } + + let mut tracks = file.tracks.iter().filter(|track| track.kind == isobmff::TrackKind::Timecode && linked.is_none_or(|id| track.id == *id)); + let track = tracks.next()?; + if tracks.next().is_some() { + return None; + } + let [entry] = track.entries.as_slice() else { return None }; + let isobmff::CodecConfig::Timecode(tc) = &entry.codec else { return None }; + let [sample] = track.samples.as_slice() else { return None }; + let (media_start, timecode_offset) = continuous_edit_mapping(track, file.timescale)?; + if track.timescale == 0 || tc.timescale == 0 || tc.frame_duration == 0 || video_rate.num <= 0 || video_rate.den <= 0 { + return None; + } + if !track.edits.is_empty() && !(sample.pts..sample.pts.checked_add(i64::from(sample.duration))?).contains(&media_start) { + return None; + } + + // EDL subtracts the origin in native video frames; do not invent a + // rounding or clock-conversion policy for nonmatching or fractional origins. + let num = i128::from(tc.timescale); + let den = i128::from(tc.frame_duration); + if num * i128::from(video_rate.den) != den * i128::from(video_rate.num) + || video.samples.iter().any(|sample| i128::from(sample.duration) * num != i128::from(video.timescale) * den) + { + return None; + } + let delta = (i128::from(sample.pts) + i128::from(timecode_offset)) * num; + let divisor = i128::from(track.timescale) * den; + if delta % divisor != 0 { + return None; + } + i64::try_from(i128::from(tc.start_frame?) - delta / divisor).ok().filter(|&origin| origin >= 0) +} + 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); @@ -523,6 +592,7 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> (None, None, FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) }; + let start_timecode = video_idx.zip(video_info.as_ref()).and_then(|(idx, info)| isobmff_timecode_origin(&file, idx, info.frame_rate)); let container = ContainerFile::Isobmff(file); let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; if video_info.is_none() && audio_tracks.is_empty() { @@ -537,7 +607,7 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> video: video_info, audio_streams: audio_infos, container: "mp4".to_string(), - start_timecode: None, + start_timecode, file_size: Some(source.len()), }; diff --git a/crates/media/tests/it/file_timecode.rs b/crates/media/tests/it/file_timecode.rs index dae3335ba..7a91640fc 100644 --- a/crates/media/tests/it/file_timecode.rs +++ b/crates/media/tests/it/file_timecode.rs @@ -5,18 +5,16 @@ use std::io::Cursor; use craft_media::isobmff::{Brand, Mp4Writer, SampleEntry, TimecodeConfig, TrackConfig, WriteSample, WriterOptions}; use effectcraft_project::FootageKind; -/// A two-frame 24 fps Motion JPEG MOV, with a timecode track from `start_frame` when given. -fn mov(start_frame: Option) -> Vec { - let mut jpeg = Vec::new(); - image::RgbImage::from_pixel(16, 16, image::Rgb([200, 40, 90])).write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).expect("jpeg"); +/// A two-frame 24 fps MOV, with a timecode track from `start_frame` when given. +fn mov(entry: SampleEntry, packet: &[u8], start_frame: Option) -> Vec { let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("writer"); - let v = w.add_track(TrackConfig::new(SampleEntry::jpeg(16, 16), 24)).expect("video track"); + let v = w.add_track(TrackConfig::new(entry, 24)).expect("video track"); if let Some(start) = start_frame { let tc = TimecodeConfig { timescale: 24, frame_duration: 1, frames_per_second: 24, ..Default::default() }; w.add_timecode_track(v, tc, start).expect("timecode track"); } for _ in 0..2 { - w.write_sample(v, WriteSample { data: &jpeg, duration: 1, composition_offset: 0, is_sync: true }).expect("frame"); + w.write_sample(v, WriteSample { data: packet, duration: 1, composition_offset: 0, is_sync: true }).expect("frame"); } w.finish().expect("finish").into_inner() } @@ -25,10 +23,12 @@ fn mov(start_frame: Option) -> Vec { fn a_movies_start_timecode_is_read() { let dir = std::env::temp_dir().join(format!("effectcraft-file-timecode-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("mkdir"); + let mut jpeg = Vec::new(); + image::RgbImage::from_pixel(16, 16, image::Rgb([200, 40, 90])).write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).expect("jpeg"); // 10:00:00:00 at 24 fps, and a movie with no timecode for (name, start) in [("tc.mov", Some(10 * 3600 * 24)), ("none.mov", None)] { let p = dir.join(name); - std::fs::write(&p, mov(start)).expect("write"); + std::fs::write(&p, mov(SampleEntry::jpeg(16, 16), &jpeg, start)).expect("write"); let f = effectcraft_media::probe(&p).expect("probe"); assert_eq!(f.kind, FootageKind::Video, "{name}"); assert_eq!(f.file_timecode, start.map(i64::from), "{name}"); @@ -36,3 +36,125 @@ fn a_movies_start_timecode_is_read() { } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn shared_mov_preserves_recorded_start_timecode() { + use craft_media::isobmff::FourCc; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let dir = tempfile::tempdir().expect("temp dir"); + let profile = Profile::P4444; + let frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, false).expect("ProRes frame"); + let packet = Encoder::new(profile, 16, 16).encode(&frame).expect("encode ProRes"); + for (name, start) in [("tc.mov", Some(10 * 3600 * 24)), ("none.mov", None)] { + let entry = SampleEntry::prores(FourCc(profile.fourcc()), 16, 16); + let bytes = mov(entry, &packet, start); + let path = dir.path().join(name); + std::fs::write(&path, &bytes).expect("write MOV"); + + let from_file = effectcraft_media::probe(&path).expect("probe file"); + let from_bytes = effectcraft_media::probe_bytes(name, bytes.into()).expect("probe bytes"); + for footage in [from_file, from_bytes] { + assert_eq!(footage.kind, FootageKind::Video, "{name}"); + // FilmCraft labels the same sample entry "Apple ProRes 4444". + assert_eq!(footage.codec, "ProRes", "{name}: must use the shared reader"); + assert_eq!(footage.file_timecode, start.map(i64::from), "{name}"); + assert_eq!(footage.start_timecode, None, "{name}: no Interpret Footage override"); + } + } +} + +#[test] +fn shared_mov_timecode_rebases_edl_labels_on_its_own_presentation_clock() { + use craft_media::isobmff::{self, CodecConfig, Edit, FourCc, TrackKind}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + use effectcraft_media::{MediaPool, probe_bytes}; + use effectcraft_time::{FrameRate, Tick}; + + const START: u32 = 10 * 3600 * 24; + const MOVIE_CLOCK: u32 = 24; + const VIDEO_CLOCK: u32 = 48; + const TC_CLOCK: u32 = 96; + const UNIT_RATE: i32 = 0x0001_0000; + let edit = |segment_duration, media_time| Edit { segment_duration, media_time, media_rate: UNIT_RATE }; + + let profile = Profile::P4444; + let mut encoder = Encoder::new(profile, 16, 16); + let mut frame = Frame::new(16, 16, ChromaFormat::Yuv444, 16, false).expect("ProRes frame"); + let packets = [40, 120, 200].map(|luma| { + frame.y.fill(luma << 8); + encoder.encode(&frame).expect("encode ProRes") + }); + + // The timecode track is written independently to vary its real media edit, + // rather than accidentally using the video's edit as a timecode adjustment. + let make_mov = |video_edits: Vec, tc_edits: Vec, counter: u32, movie_clock: u32| { + let mut opts = WriterOptions::new(Brand::Mov); + opts.movie_timescale = movie_clock; + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), opts).expect("writer"); + let mut video_cfg = TrackConfig::new(SampleEntry::prores(FourCc(profile.fourcc()), 16, 16), VIDEO_CLOCK); + video_cfg.edits = video_edits; + let video = w.add_track(video_cfg).expect("video track"); + + let tc = TimecodeConfig { timescale: TC_CLOCK, frame_duration: 4, frames_per_second: 24, ..Default::default() }; + let entry = + SampleEntry { format: FourCc(*b"tmcd"), data_reference_index: 1, codec: CodecConfig::Timecode(tc), video: None, audio: None, bitrate: None }; + let mut tc_cfg = TrackConfig::new(entry, TC_CLOCK); + tc_cfg.edits = tc_edits; + let tc = w.add_track(tc_cfg).expect("timecode track"); + for packet in &packets { + w.write_sample(video, WriteSample { data: packet, duration: 2, composition_offset: 0, is_sync: true }).expect("write ProRes"); + } + w.write_sample(tc, WriteSample { data: &counter.to_be_bytes(), duration: 12, composition_offset: 0, is_sync: true }).expect("write timecode"); + w.finish().expect("finish").into_inner() + }; + + let pool = MediaPool::new(); + let plain: std::sync::Arc<[u8]> = make_mov(vec![], vec![], START, MOVIE_CLOCK).into(); + let unedited = probe_bytes("plain.mov", plain.clone()).expect("probe unedited MOV"); + assert_eq!(unedited.file_timecode, Some(i64::from(START))); + pool.add_bytes("plain.mov", plain); + let at = |presentation_frame| Tick::from_units(presentation_frame, i64::from(MOVIE_CLOCK)); + let pixels = [0, 1, 2].map(|n| pool.frame_at(&unedited, at(n)).expect("decode unedited reference").data[0]); + assert!(pixels[0][0] < pixels[1][0] && pixels[1][0] < pixels[2][0], "reference pictures must be distinct"); + + let cases = [ + ("matched-trim.mov", vec![edit(2, 2)], vec![edit(2, 4)], START, -4, START + 1, [(START + 1, 0, 1), (START + 2, 1, 2)]), + ("video-only-trim.mov", vec![edit(2, 2)], vec![], START + 1, 0, START + 1, [(START + 1, 0, 1), (START + 2, 1, 2)]), + ("matched-delay.mov", vec![edit(1, -1), edit(3, 0)], vec![edit(1, -1), edit(3, 0)], START, 4, START - 1, [(START, 1, 0), (START + 1, 2, 1)]), + ]; + for (name, video_edits, tc_edits, counter, tc_pts, expected_origin, points) in cases { + let bytes: std::sync::Arc<[u8]> = make_mov(video_edits, tc_edits, counter, MOVIE_CLOCK).into(); + let parsed = isobmff::open(bytes.as_ref()).expect("parse generated MOV"); + let tc = parsed.tracks.iter().find(|track| track.kind == TrackKind::Timecode).expect("timecode track"); + assert_eq!(tc.presentation_pts(0), Some(tc_pts), "{name}: fixture timecode edit"); + let footage = probe_bytes(name, bytes.clone()).expect("probe edited MOV"); + assert_eq!(footage.codec, "ProRes", "{name}: must use the shared reader"); + assert_eq!(footage.native_rate.unwrap_or(footage.frame_rate), FrameRate::FPS_24); + let origin = footage.file_timecode.expect("usable presentation timecode"); + assert_eq!(origin, i64::from(expected_origin), "{name}"); + pool.add_bytes(name, bytes); + + for (edl_label, presentation_frame, picture) in points { + // The EDL importer subtracts this origin at the native video rate. + let rebased = i64::from(edl_label) - origin; + assert_eq!(rebased, presentation_frame, "{name}: EDL in-point"); + let image = pool.frame_at(&footage, at(rebased)).expect("decode rebased in-point"); + assert_eq!(image.data[0], pixels[picture], "{name}: decoded source picture"); + } + } + + let disjoint = make_mov(vec![edit(1, 0), edit(1, 4)], vec![], START, MOVIE_CLOCK); + let footage = probe_bytes("disjoint.mov", disjoint.into()).expect("probe disjoint MOV"); + assert_eq!(footage.codec, "ProRes", "ambiguous timecode alone must not force a decoder fallback"); + assert_eq!(footage.file_timecode, None, "a single EDL origin cannot describe disjoint edits"); + + // One millisecond cannot be represented in the 96 Hz timecode track. + // The demuxer reports zero after conversion, but the EDL origin is ambiguous. + let fractional = make_mov(vec![], vec![edit(1, -1), edit(125, 0)], START, 1000); + let parsed = isobmff::open(fractional.as_slice()).expect("parse fractional delay MOV"); + let tc = parsed.tracks.iter().find(|track| track.kind == TrackKind::Timecode).expect("timecode track"); + assert_eq!(tc.presentation_pts(0), Some(0), "demux rounded the empty edit"); + let footage = probe_bytes("fractional.mov", fractional.into()).expect("probe fractional delay MOV"); + assert_eq!(footage.file_timecode, None, "do not turn a fractional delay into a fabricated origin"); +} From a29e69d25799dfd949a73dcbd3015e7a4df7a0c0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 01:22:53 -0500 Subject: [PATCH 335/393] media: generate pure-Rust AAC fixtures for gap and seek tests (#4015) --- crates/media/Cargo.toml | 2 + crates/media/tests/it/footage.rs | 88 +++++++++++++++++++------------- 2 files changed, 55 insertions(+), 35 deletions(-) diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 1808f6470..ffd8ea9fe 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -52,3 +52,5 @@ gif = { workspace = true } tempfile = { workspace = true } # (tests render comps that read layers through effects; already a dependency of effectcraft-render) effectcraft-effects = { workspace = true } +# Pure-Rust AAC test fixture encoding (no external ffmpeg dependency). +craft-audio = { workspace = true, features = ["aac-encode"] } diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 08b7158b1..a542d4439 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1783,17 +1783,51 @@ fn assert_samples_close(a: &[f32], b: &[f32], tol: f32, ctx: &str) { assert!(max_diff <= tol, "{ctx}: max_diff {max_diff} > {tol}"); } +fn pure_rust_aac_packets(duration_secs: usize) -> (Vec, Vec>) { + let mut enc = craft_audio::aac::Encoder::new(craft_audio::aac::EncoderConfig::cbr(48_000, 2, 128_000)).expect("aac encoder"); + let asc = enc.audio_specific_config(); + let samples: Vec = (0..48_000 * duration_secs).map(|i| (2.0 * std::f32::consts::PI * 440.0 * i as f32 / 48_000.0).sin() * 0.25).collect(); + let mut pkts = enc.encode(&[&samples, &samples]); + pkts.extend(enc.flush()); + (asc, pkts) +} + #[test] fn mkv_and_mp4_aac_play_continuously_without_crackle_and_seek_matches_sequential() { - let Some(mp4_path) = - try_ffmpeg_fixture("aac_1546_pair.mp4", &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2", "-c:a", "aac", "-b:a", "128k"]) - else { - return; - }; - let mp4_str = mp4_path.to_string_lossy().into_owned(); - let Some(mkv_path) = try_ffmpeg_fixture("aac_1546_pair.mkv", &["-i", &mp4_str, "-c:a", "copy"]) else { - return; + let dir = tempfile::tempdir().expect("tempdir"); + let mp4_path = dir.path().join("aac_1546_pair.mp4"); + let mkv_path = dir.path().join("aac_1546_pair.mkv"); + let (asc, pkts) = pure_rust_aac_packets(2); + + let entry = craft_media::isobmff::SampleEntry { + format: craft_media::isobmff::FourCc(*b"mp4a"), + data_reference_index: 1, + codec: craft_media::isobmff::CodecConfig::Aac(craft_media::isobmff::AacConfig::from_asc(asc.clone())), + video: None, + audio: Some(craft_media::isobmff::AudioParams { channels: 2, sample_size: 16, sample_rate: 48_000.0, ..Default::default() }), + bitrate: None, }; + let mut mp4_writer = + craft_media::isobmff::Mp4Writer::new(std::io::Cursor::new(Vec::new()), craft_media::isobmff::WriterOptions::new(craft_media::isobmff::Brand::Mp4)) + .expect("mp4 writer"); + mp4_writer.add_track(craft_media::isobmff::TrackConfig::new(entry, 48_000)).expect("add track"); + for pkt in &pkts { + mp4_writer + .write_sample(0, craft_media::isobmff::WriteSample { data: pkt, duration: 1024, composition_offset: 0, is_sync: true }) + .expect("write mp4 sample"); + } + std::fs::write(&mp4_path, mp4_writer.finish().expect("finish mp4").into_inner()).expect("write mp4"); + + let mut spec = craft_media::matroska::TrackSpec::new(craft_media::matroska::TrackKind::Audio, "A_AAC"); + spec.codec_private = asc; + spec.audio = Some((48_000.0, 2, None)); + let mut mkv_writer = + craft_media::matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], craft_media::matroska::MuxOptions::default()).expect("mkv writer"); + for (i, pkt) in pkts.iter().enumerate() { + let pts_ns = (i as i64 * 1024 * 1_000_000_000) / 48_000; + mkv_writer.write_frame(0, pts_ns, true, pkt, None).expect("write mkv frame"); + } + std::fs::write(&mkv_path, mkv_writer.finish().expect("finish mkv").into_inner()).expect("write mkv"); let mp4 = probe(&mp4_path).expect("probe mp4"); let mkv = probe(&mkv_path).expect("probe mkv"); @@ -1822,33 +1856,21 @@ fn mkv_and_mp4_aac_play_continuously_without_crackle_and_seek_matches_sequential assert_samples_close(&backward, &mkv_seq[24_000 * 2..24_000 * 2 + 4800 * 2], 1e-4, "mkv backward seek vs sequential"); } -fn build_gapped_aac_mkv(out_path: &Path, gap_at_pkt: usize, gap_ns: i64, start_offset_ns: i64) -> Option<()> { - let mp4_path = - try_ffmpeg_fixture("aac_1546_pair.mp4", &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2", "-c:a", "aac", "-b:a", "128k"])?; - let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(std::fs::read(&mp4_path).ok()?); - let mp4 = craft_media::isobmff::open(bytes.clone()).ok()?; - let track_idx = mp4.tracks.iter().position(|t| t.kind == craft_media::isobmff::TrackKind::Audio)?; - let track = &mp4.tracks[track_idx]; - let asc = match &track.entries.first()?.codec { - craft_media::isobmff::CodecConfig::Aac(a) => a.asc.clone(), - _ => return None, - }; - +fn build_gapped_aac_mkv(out_path: &Path, gap_at_pkt: usize, gap_ns: i64, start_offset_ns: i64) { + let (asc, pkts) = pure_rust_aac_packets(2); let mut spec = craft_media::matroska::TrackSpec::new(craft_media::matroska::TrackKind::Audio, "A_AAC"); spec.codec_private = asc; - spec.audio = Some((48_000.0, u64::from(track.audio().map_or(2, |a| a.channels)), None)); - let mut writer = craft_media::matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], craft_media::matroska::MuxOptions::default()).ok()?; + spec.audio = Some((48_000.0, 2, None)); + let mut writer = + craft_media::matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], craft_media::matroska::MuxOptions::default()).expect("mkv writer"); - let pkt_count = track.samples.len().min(60); - for i in 0..pkt_count { - let pkt = mp4.read_sample(&*bytes, track_idx, i).ok()?; + for (i, pkt) in pkts.iter().take(60).enumerate() { let base_ns = (i as i64 * 1024 * 1_000_000_000) / 48_000; let extra = if i >= gap_at_pkt { gap_ns } else { 0 }; - writer.write_frame(0, start_offset_ns + base_ns + extra, true, &pkt, None).ok()?; + writer.write_frame(0, start_offset_ns + base_ns + extra, true, pkt, None).expect("write mkv frame"); } - let mkv_bytes = writer.finish().ok()?.into_inner(); - std::fs::write(out_path, mkv_bytes).ok()?; - Some(()) + let mkv_bytes = writer.finish().expect("finish mkv").into_inner(); + std::fs::write(out_path, mkv_bytes).expect("write mkv"); } #[test] @@ -1856,9 +1878,7 @@ fn audio_real_silence_gap_honored_on_sequential_and_seek() { let dir = tempfile::tempdir().expect("tempdir"); let mkv_path = dir.path().join("real_gap.mkv"); // 24 packets (~0.512s) at 0, then a 500 ms silence gap before packet 24. - if build_gapped_aac_mkv(&mkv_path, 24, 500_000_000, 0).is_none() { - return; - } + build_gapped_aac_mkv(&mkv_path, 24, 500_000_000, 0); let f = probe(&mkv_path).expect("probe gapped mkv"); let rate = 48_000u32; @@ -1891,9 +1911,7 @@ fn audio_delayed_first_packet_honored_on_sequential_and_seek() { let dir = tempfile::tempdir().expect("tempdir"); let mkv_path = dir.path().join("delayed_first.mkv"); // First packet delayed by 500 ms. - if build_gapped_aac_mkv(&mkv_path, usize::MAX, 0, 500_000_000).is_none() { - return; - } + build_gapped_aac_mkv(&mkv_path, usize::MAX, 0, 500_000_000); let f = probe(&mkv_path).expect("probe delayed mkv"); let rate = 48_000u32; From c821d6e0e712930887ca8cea128f6a25e57f4656 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:46:35 +0700 Subject: [PATCH 336/393] media: avoid scanning Opus payloads at open (#4011) * Avoid scanning Opus payloads during track open * Apply rustfmt to the Opus timing regression * Split Opus regression scenarios for Clippy --- crates/media/src/craft_source.rs | 428 +++++++++++++++++++++++++++---- 1 file changed, 377 insertions(+), 51 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 20816535c..c0deb4673 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -47,6 +47,7 @@ const MAX_CACHED_FRAMES: usize = 32; /// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`. const AUDIO_LOOKAHEAD: usize = 8; +const AUDIO_SEEK_BACKUP_PACKETS: usize = 2; /// 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; @@ -181,7 +182,7 @@ impl ContainerFile { fn audio_seek_info(&self, track_idx: usize, audio_starts: &[i64], seek_preroll_samples: i64, start: i64) -> (usize, i64) { let target = start.saturating_sub(seek_preroll_samples).max(0); let sample_idx = audio_starts.partition_point(|&s| s <= target).saturating_sub(1); - let mut seek_idx = sample_idx.saturating_sub(2); + let mut seek_idx = sample_idx.saturating_sub(AUDIO_SEEK_BACKUP_PACKETS); while seek_idx > 0 && !self.audio_packet_is_stamped(track_idx, seek_idx) { seek_idx -= 1; } @@ -214,18 +215,103 @@ struct PacketTime { /// `storytold/filmcraft#359`). fn contiguous_starts(packets: impl IntoIterator, tolerance: i64) -> Vec { let tolerance = tolerance.max(0).unsigned_abs(); - let mut next: Option = None; - packets - .into_iter() - .map(|p| { - let start = match next { - Some(n) if !p.stamped || n.abs_diff(p.stamp) <= tolerance => n, - _ => p.stamp, - }; - next = p.samples.and_then(|k| start.checked_add(k)); - start + let mut next = None; + packets.into_iter().map(|p| place_packet(p, &mut next, tolerance)).collect() +} + +fn packet_start(packet: PacketTime, next: Option, tolerance: u64) -> i64 { + match next { + Some(n) if !packet.stamped || n.abs_diff(packet.stamp) <= tolerance => n, + _ => packet.stamp, + } +} + +fn place_packet(packet: PacketTime, next: &mut Option, tolerance: u64) -> i64 { + let start = packet_start(packet, *next, tolerance); + *next = packet.samples.and_then(|n| start.checked_add(n)); + start +} + +struct OpusPrefix { + len: usize, + next: Option, + tolerance: u64, + min_pending_stamp: i64, +} + +struct AudioStarts { + // For Opus, unvisited entries still hold raw container stamps. Resolve in place + // as packets arrive, reusing this table for the finished timeline. + positions: Vec, + opus: Option, +} + +impl AudioStarts { + fn complete(positions: Vec) -> Self { + Self { positions, opus: None } + } + + fn opus(positions: Vec, tolerance: i64) -> Self { + // Open resolves exactly the bounded lookahead before anyone can seek. + let min_pending_stamp = positions.iter().skip(AUDIO_LOOKAHEAD).copied().min().unwrap_or(i64::MIN); + let opus = (!positions.is_empty()).then_some(OpusPrefix { len: 0, next: None, tolerance: tolerance.max(0).unsigned_abs(), min_pending_stamp }); + Self { positions, opus } + } + + fn start(&self, file: &ContainerFile, track: usize, idx: usize) -> Option { + let stamp = *self.positions.get(idx)?; + let Some(prefix) = &self.opus else { return Some(stamp) }; + if idx < prefix.len { + return Some(stamp); + } + debug_assert_eq!(idx, prefix.len); + (idx == prefix.len).then(|| { + let packet = PacketTime { stamp, stamped: file.audio_packet_is_stamped(track, idx), samples: None }; + packet_start(packet, prefix.next, prefix.tolerance) }) - .collect() + } + + fn observe(&mut self, file: &ContainerFile, track: usize, idx: usize, packet: &[u8]) { + let Some(prefix) = &mut self.opus else { return }; + if idx != prefix.len { + return; + } + let timing = + PacketTime { stamp: self.positions[idx], stamped: file.audio_packet_is_stamped(track, idx), samples: opus_packet_samples(packet).map(i64::from) }; + self.positions[idx] = place_packet(timing, &mut prefix.next, prefix.tolerance); + prefix.len += 1; + if prefix.len == self.positions.len() { + self.opus = None; + } + } + + fn seek_proves_first_packet(&self, target: i64) -> bool { + let Some(prefix) = &self.opus else { return false }; + // A normal read that starts before the very first packet looks like a + // backward seek. It need not read the suffix if the ordinary seek + // would back up to packet 0 anyway. Stamped starts can only move by the + // timing tolerance; unstamped continuation moves forward from next. + prefix.min_pending_stamp > target + && prefix.min_pending_stamp.abs_diff(target) > prefix.tolerance + && prefix.next.is_none_or(|next| next > target) + && self.positions.get(AUDIO_SEEK_BACKUP_PACKETS + 1..prefix.len).is_some_and(|p| p.iter().all(|&start| start > target)) + } + + fn finish_for_seek(&mut self, file: &ContainerFile, source: &dyn ByteSource, track: usize) -> Result<()> { + // The exact recurrence can carry a timing phase across arbitrarily many + // rounded or laced packets. A first discontinuous seek may still have to + // index the unread suffix; normal open and sequential decode never do this. + while let Some(idx) = self.opus.as_ref().map(|prefix| prefix.len) { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + // Do not commit a guessed duration after an I/O error; the next + // request can retry this packet without re-reading the valid prefix. + let packet = file.read_sample(source, track, idx)?; + self.observe(file, track, idx, &packet); + } + Ok(()) + } } fn fixed_packet_samples(dec: &mut AudioTrackDecoder, codec: CodecId, lookahead: &[Vec]) -> Option { @@ -274,18 +360,11 @@ fn opus_packet_samples(pkt: &[u8]) -> Option { (n > 0 && n <= 5760).then_some(n) } -fn compute_audio_starts( - container: &ContainerFile, - source: &dyn ByteSource, - track_idx: usize, - codec: CodecId, - native_rate: u32, - fixed_samples: Option, -) -> Vec { +fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: CodecId, native_rate: u32, fixed_samples: Option) -> AudioStarts { let rate = i128::from(native_rate); match container { ContainerFile::Isobmff(f) => { - let Some(track) = f.tracks.get(track_idx) else { return Vec::new() }; + let Some(track) = f.tracks.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; let ts = i128::from(track.timescale.max(1)); let stamps: Vec = (0..track.samples.len()) .map(|i| { @@ -295,21 +374,17 @@ fn compute_audio_starts( .collect(); let unit = i64::try_from((rate + ts - 1) / ts).unwrap_or(i64::MAX); if codec == CodecId::Opus { - let packets = stamps.into_iter().enumerate().map(|(i, stamp)| { - let samples = f.read_sample(source, track_idx, i).ok().and_then(|p| opus_packet_samples(&p)).map(i64::from); - PacketTime { stamp, stamped: true, samples } - }); - return contiguous_starts(packets, unit.saturating_mul(2).saturating_add(1)); + return AudioStarts::opus(stamps, unit.saturating_mul(2).saturating_add(1)); } let Some(frame) = fixed_samples else { - return stamps; + return AudioStarts::complete(stamps); }; let tolerance = (frame / 2).max(unit.saturating_mul(2).saturating_add(1)); let packets = stamps.into_iter().map(|stamp| PacketTime { stamp, stamped: true, samples: Some(frame) }); - contiguous_starts(packets, tolerance) + AudioStarts::complete(contiguous_starts(packets, tolerance)) } ContainerFile::Matroska(f) => { - let Some(track) = f.tracks.get(track_idx) else { return Vec::new() }; + let Some(track) = f.tracks.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; // Indexed PTS already subtracts CodecDelay rounded to the container clock. // Translate between that clock and the warm path's whole-frame delay. let tick_ns = i128::from(f.info.timestamp_scale.max(1)); @@ -322,17 +397,13 @@ fn compute_audio_starts( }; let tick_samples = i64::try_from(i128::from(track.ticks_to_ns(2)) * rate / 1_000_000_000).unwrap_or(i64::MAX).saturating_add(1); if codec == CodecId::Opus { - let packets = track.samples.iter().enumerate().map(|(i, s)| { - let samples = f.read_sample(source, track_idx, i).ok().and_then(|p| opus_packet_samples(&p)).map(i64::from); - PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples } - }); - return contiguous_starts(packets, tick_samples); + return AudioStarts::opus(track.samples.iter().map(|s| stamp_for(s.pts)).collect(), tick_samples); } let Some(frame) = fixed_samples else { - return track.samples.iter().map(|s| stamp_for(s.pts)).collect(); + return AudioStarts::complete(track.samples.iter().map(|s| stamp_for(s.pts)).collect()); }; let packets = track.samples.iter().map(|s| PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples: Some(frame) }); - contiguous_starts(packets, (frame / 2).max(tick_samples)) + AudioStarts::complete(contiguous_starts(packets, (frame / 2).max(tick_samples))) } } } @@ -363,7 +434,12 @@ where let channels = u32::from(dec.layout().channels()).max(1); let codec = dec.codec(); let fixed_samples = fixed_packet_samples(&mut dec, codec, &lookahead); - let audio_starts = compute_audio_starts(container, source, idx, codec, native_rate, fixed_samples); + let mut audio_starts = compute_audio_starts(container, idx, codec, native_rate, fixed_samples); + if codec == CodecId::Opus { + for (s_idx, pkt) in lookahead.iter().enumerate() { + audio_starts.observe(container, idx, s_idx, pkt); + } + } let seek_preroll_samples = match container { ContainerFile::Matroska(f) if codec == CodecId::Opus => { let preroll_ns = i128::from(f.tracks[idx].seek_pre_roll_ns.max(80_000_000)); @@ -371,7 +447,7 @@ where } _ => 0, }; - let initial_pos = audio_starts.first().copied().unwrap_or(0); + let initial_pos = audio_starts.start(container, idx, 0).unwrap_or(0); audio_infos.push(AudioStreamInfo { sample_rate: native_rate, channels, @@ -381,9 +457,8 @@ where audio_tracks.push(AudioTrackEntry { track_idx: idx, native_rate, - audio_starts, seek_preroll_samples, - state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), + state: Mutex::new(AudioTrackState { decoder: dec, audio_starts, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), }); } Some((audio_tracks, audio_infos)) @@ -724,6 +799,7 @@ struct VideoState { struct AudioTrackState { decoder: AudioTrackDecoder, + audio_starts: AudioStarts, next_sample: usize, /// Sample index (in native-rate frames) of `buf[0]` relative to track start (0). decoded_pos: i64, @@ -734,7 +810,6 @@ struct AudioTrackState { struct AudioTrackEntry { track_idx: usize, native_rate: u32, - audio_starts: Vec, seek_preroll_samples: i64, state: Mutex, } @@ -849,7 +924,6 @@ impl MediaSource for CraftMediaSource { entry.track_idx, native_rate, channels_count, - &entry.audio_starts, entry.seek_preroll_samples, &mut state, native_start, @@ -1073,7 +1147,6 @@ fn decode_audio_range( track_idx: usize, native_rate: u32, channels_count: usize, - audio_starts: &[i64], seek_preroll_samples: i64, state: &mut AudioTrackState, start: i64, @@ -1086,8 +1159,15 @@ fn decode_audio_range( 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, audio_starts, seek_preroll_samples, start); + let moves_backward = start < state.decoded_pos; + if moves_backward || start > buf_end + i64::from(native_rate) * 2 { + let target = start.saturating_sub(seek_preroll_samples).max(0); + let (seek_idx, decoded_pos) = if moves_backward && state.next_sample == 0 && state.audio_starts.seek_proves_first_packet(target) { + (0, state.decoded_pos) + } else { + state.audio_starts.finish_for_seek(file, source, track_idx)?; + file.audio_seek_info(track_idx, &state.audio_starts.positions, seek_preroll_samples, start) + }; state.decoder.reset(); state.next_sample = seek_idx; state.decoded_pos = decoded_pos; @@ -1108,11 +1188,16 @@ fn decode_audio_range( let idx = state.next_sample; let buf_len = state.buf.first().map_or(0, Vec::len) as i64; let buf_end = state.decoded_pos.saturating_add(buf_len); - let pk_start = if buf_len > 0 && !file.audio_packet_is_stamped(track_idx, idx) { buf_end } else { audio_starts.get(idx).copied().unwrap_or(buf_end) }; + let pk_start = if buf_len > 0 && !file.audio_packet_is_stamped(track_idx, idx) { + buf_end + } else { + state.audio_starts.start(file, track_idx, idx).unwrap_or(buf_end) + }; if pk_start >= end { break; } let pkt = file.read_sample(source, track_idx, idx)?; + state.audio_starts.observe(file, track_idx, idx, &pkt); state.next_sample = idx + 1; let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; let buf_len = state.buf.first().map_or(0, Vec::len) as i64; @@ -1545,6 +1630,249 @@ fn estimate_matroska_frame_rate(track: &matroska::Track) -> FrameRate { mod tests { use super::*; + // One 20 ms mono packet from craft-audio's generated tone.opus test fixture. + // Re-mux it into ordinary small audio-only files without an external encoder. + const OPUS_TONE: &[u8] = b"\x78\x82\x01\xB7\x6C\x7E\x40\xE6\x00\x00\x0A\xBE\x9A\xA7\xBE\xFF\xB6\x85\xD7\x0A\x71\xE0\xDD\ + \x6B\xA0\xE3\xC6\xC5\xC3\x32\xC6\x64\x1E\x6E\x63\x52\x3A\x45\x0C\x8A\x53\x8F\x44\x18\xB0\x8C\ + \x64\xAB\xEC\x98\x96\x79\x6C\x54\x53\x30\x55\x4E\x82\xE4\x16\xCA\x59\x49\xD8\xC7\x09\x5D\x59"; + + struct OpusPayloadReads { + bytes: Vec, + offsets: Vec, + packets: Mutex>, + fail_once_at: Mutex>, + } + + impl ByteSource for OpusPayloadReads { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + if buf.len() == OPUS_TONE.len() + && let Ok(index) = self.offsets.binary_search(&offset) + { + self.packets.lock().unwrap().push(index); + let mut failure = self.fail_once_at.lock().unwrap(); + if *failure == Some(index) { + *failure = None; + return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "test transient packet read")); + } + } + self.bytes.as_slice().read_at(offset, buf) + } + } + + const OPUS_RATE: u32 = 48_000; + const OPUS_FRAME: usize = 960; + const OPUS_PACKETS: usize = 192; + const OPUS_GAP_AT: usize = 96; + const OPUS_GAP: usize = 9_600; + const OPUS_LEAD: usize = 4_800; + const OPUS_CODEC_DELAY_NS: i64 = 6_500_000; + const OPUS_CODEC_DELAY_FRAMES: i64 = 312; + + struct OpusFixture { + bytes: Vec, + file: ContainerFile, + offsets: Vec, + params: CodecParams, + delay: u64, + } + + fn opus_test_config() -> isobmff::OpusConfig { + isobmff::OpusConfig { output_channels: 1, pre_skip: OPUS_CODEC_DELAY_FRAMES as u16, input_sample_rate: OPUS_RATE, ..Default::default() } + } + + fn generated_opus_matroska(lead: usize, laced: bool) -> OpusFixture { + use std::io::Cursor; + + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_OPUS"); + track.audio = Some((f64::from(OPUS_RATE), 1, None)); + track.codec_private = opus_test_config().opus_head(); + track.codec_delay_ns = OPUS_CODEC_DELAY_NS as u64; + track.seek_pre_roll_ns = 80_000_000; + track.default_duration_ns = Some(20_000_000); + let options = if laced { + matroska::MuxOptions { lacing: matroska::LacingMode::FixedOrEbml, max_lace_frames: 6, cluster_duration_ns: 10_000_000_000, ..Default::default() } + } else { + matroska::MuxOptions::default() + }; + let mut mux = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], options).unwrap(); + let lead_ns = lead as i64 * 1_000_000_000 / i64::from(OPUS_RATE); + for idx in 0..OPUS_PACKETS { + let gap_ns = if idx >= OPUS_GAP_AT { 200_000_000 } else { 0 }; + let jitter = if laced || idx % 2 == 0 { 0 } else { 1_000_000 }; + mux.write_frame(0, idx as i64 * 20_000_000 + lead_ns + gap_ns + jitter - OPUS_CODEC_DELAY_NS, true, OPUS_TONE, None).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let mut file = matroska::open(bytes.as_slice()).unwrap(); + let track = &mut file.tracks[0]; + if laced { + // The writer needs a duration to group real laces. Exercise the + // durationless index representation by clearing it after demuxing. + assert_eq!(track.samples[AUDIO_LOOKAHEAD].lace, 2); + assert_eq!(track.samples[145].lace, 1); + let mut anchor = 0; + for packet in &mut track.samples { + if packet.lace == 0 { + anchor = packet.pts; + } else { + packet.pts = anchor; + } + packet.duration = 0; + } + } + let offsets = track.samples.iter().map(|s| s.offset).collect::>(); + let params = track.codec_params(); + OpusFixture { bytes, file: ContainerFile::Matroska(Box::new(file)), offsets, params, delay: OPUS_CODEC_DELAY_NS as u64 } + } + + fn generated_opus_mp4(lead: usize) -> OpusFixture { + use std::io::Cursor; + + let entry = isobmff::SampleEntry { + format: isobmff::FourCc(*b"Opus"), + data_reference_index: 1, + codec: isobmff::CodecConfig::Opus(opus_test_config()), + video: None, + audio: Some(isobmff::AudioParams { channels: 1, sample_size: 16, sample_rate: f64::from(OPUS_RATE), ..Default::default() }), + bitrate: None, + }; + let mut mux = isobmff::Mp4Writer::new(Cursor::new(Vec::new()), isobmff::WriterOptions::new(isobmff::Brand::Mp4)).unwrap(); + mux.add_track(isobmff::TrackConfig::new(entry, OPUS_RATE)).unwrap(); + for idx in 0..OPUS_PACKETS { + let duration = (if idx + 1 == OPUS_GAP_AT { OPUS_FRAME + OPUS_GAP } else { OPUS_FRAME }) as u32; + mux.write_sample(0, isobmff::WriteSample { data: OPUS_TONE, duration, composition_offset: lead as i32, is_sync: true }).unwrap(); + } + let bytes = mux.finish().unwrap().into_inner(); + let file = isobmff::open(bytes.as_slice()).unwrap(); + let track = &file.tracks[0]; + let offsets = track.samples.iter().map(|s| s.offset).collect::>(); + let params = track.codec_params(); + OpusFixture { bytes, file: ContainerFile::Isobmff(file), offsets, params, delay: 0 } + } + + fn assert_opus_early_and_backward( + file: &ContainerFile, + source: &OpusPayloadReads, + params: &CodecParams, + delay: u64, + expected_positions: &[i64], + lead: usize, + ) -> Vec> { + let (mut tracks, _) = open_audio_tracks(file, source, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); + assert_eq!(*source.packets.lock().unwrap(), (0..AUDIO_LOOKAHEAD).collect::>()); + + let first = expected_positions[0]; + assert_eq!(tracks[0].state.get_mut().unwrap().decoded_pos, first); + let (mut reference, _) = open_audio_tracks(file, &source.bytes, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); + reference[0].state.get_mut().unwrap().audio_starts = AudioStarts::complete(expected_positions.to_vec()); + + let decode = |track: &mut AudioTrackEntry, src: &dyn ByteSource, start, frames| { + decode_audio_range(file, src, 0, OPUS_RATE, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() + }; + // A first read before the initial packet can be ordinary leading silence + // or negative pre-roll. Neither should trigger the cold suffix scan. + let early_start = if lead == 0 { first - 128 } else { 0 }; + let silent_frames = (first - early_start) as usize; + let silent = decode(&mut tracks[0], source, early_start, silent_frames); + assert!(silent[0].iter().all(|&s| s == 0.0)); + assert_eq!(*source.packets.lock().unwrap(), (0..AUDIO_LOOKAHEAD).collect::>()); + assert_eq!(silent, decode(&mut reference[0], &source.bytes, early_start, silent_frames)); + let early_frames = silent_frames + 12 * OPUS_FRAME; + let early = decode(&mut tracks[0], source, early_start, early_frames); + assert_eq!(early, decode(&mut reference[0], &source.bytes, early_start, early_frames)); + assert!(early[0].iter().all(|s| s.is_finite())); + assert!(early[0].iter().any(|s| s.abs() > 1e-5), "real Opus decoding, not a silent fallback"); + { + let reads = source.packets.lock().unwrap(); + assert!(reads.iter().any(|&i| i >= AUDIO_LOOKAHEAD), "exercise the incremental frontier"); + assert!(reads.iter().all(|&i| i < 14) && reads.len() <= AUDIO_LOOKAHEAD + 14, "{reads:?}"); + } + + // A backward read after real decode must still use the exact seek index. + let backward_start = first + 2 * OPUS_FRAME as i64; + let backward = decode(&mut tracks[0], source, backward_start, OPUS_FRAME); + assert_eq!(backward, decode(&mut reference[0], &source.bytes, backward_start, OPUS_FRAME)); + let state = tracks[0].state.get_mut().unwrap(); + assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); + assert!(state.audio_starts.opus.is_none()); + early + } + + fn assert_opus_first_cold_seek_and_retry( + file: &ContainerFile, + source: &OpusPayloadReads, + params: CodecParams, + delay: u64, + expected_positions: &[i64], + laced: bool, + start: i64, + ) { + let first = expected_positions[0]; + let decode = |track: &mut AudioTrackEntry, src: &dyn ByteSource, start, frames| { + decode_audio_range(file, src, 0, OPUS_RATE, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() + }; + // A genuinely random first request is not the leading-silence shortcut. + let (mut fresh, _) = open_audio_tracks(file, source, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); + let (mut eager, _) = open_audio_tracks(file, &source.bytes, [(0, OPUS_PACKETS, params, delay)]).unwrap(); + eager[0].state.get_mut().unwrap().audio_starts = AudioStarts::complete(expected_positions.to_vec()); + if laced { + assert_eq!(file.audio_seek_info(0, expected_positions, fresh[0].seek_preroll_samples, start).0, 144); + } + let transient_packet = 64; + *source.fail_once_at.lock().unwrap() = Some(transient_packet); + { + let entry = &mut fresh[0]; + let preroll = entry.seek_preroll_samples; + let state = entry.state.get_mut().unwrap(); + let error = decode_audio_range(file, source, 0, OPUS_RATE, 1, preroll, state, start, 3 * OPUS_FRAME).unwrap_err(); + assert!(matches!(error, MediaError::Io(_))); + assert_eq!(state.audio_starts.opus.as_ref().unwrap().len, transient_packet); + assert_eq!((state.next_sample, state.decoded_pos), (0, first)); + } + let cold = decode(&mut fresh[0], source, start, 3 * OPUS_FRAME); + assert_eq!(cold, decode(&mut eager[0], &source.bytes, start, 3 * OPUS_FRAME)); + assert!(cold[0].iter().any(|s| s.abs() > 1e-5)); + let state = fresh[0].state.get_mut().unwrap(); + assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); + assert!(state.audio_starts.opus.is_none()); + } + + #[test] + fn opus_open_and_first_sequential_read_do_not_scan_tail_packets() { + assert_eq!(opus_packet_samples(OPUS_TONE), Some(OPUS_FRAME as u32)); + let mut unlaced_matroska_audio = None; + let cases = [(false, 0, false), (true, 0, false), (false, OPUS_LEAD, false), (true, OPUS_LEAD, false), (true, OPUS_LEAD, true)]; + for (matroska_file, lead, laced) in cases { + let fixture = if matroska_file { generated_opus_matroska(lead, laced) } else { generated_opus_mp4(lead) }; + let OpusFixture { bytes, file, offsets, params, delay } = fixture; + assert_eq!(offsets.len(), OPUS_PACKETS); + assert!(offsets.windows(2).all(|w| w[0] < w[1])); + // Start counting after container metadata indexing. This isolates payload reads by the app + // opener, independent of how the demuxer peeks at block headers or buffers the file. + let source = OpusPayloadReads { bytes, offsets, packets: Mutex::new(Vec::new()), fail_once_at: Mutex::new(None) }; + // Independent eager placement oracle: fixed 20 ms packets, an explicit 200 ms gap, + // no drift from alternating Matroska stamp jitter, and delay applied once. + let delay_frames = if matroska_file { OPUS_CODEC_DELAY_FRAMES } else { 0 }; + let expected_positions: Vec<_> = (0..OPUS_PACKETS) + .map(|i| { + let gap = if i >= OPUS_GAP_AT { OPUS_GAP } else { 0 }; + (lead + i * OPUS_FRAME + gap) as i64 - delay_frames + }) + .collect(); + let early = assert_opus_early_and_backward(&file, &source, ¶ms, delay, &expected_positions, lead); + if laced { + assert_eq!(&early, unlaced_matroska_audio.as_ref().unwrap(), "durationless laces must place the same real audio as stamped packets"); + } else if matroska_file && lead == OPUS_LEAD { + unlaced_matroska_audio = Some(early); + } + let start = (lead + 151 * OPUS_FRAME + OPUS_GAP) as i64 - delay_frames; + assert_opus_first_cold_seek_and_retry(&file, &source, params, delay, &expected_positions, laced, start); + } + } + #[test] fn worker_cap_is_bounded() { let cap = worker_cap(); @@ -1877,8 +2205,7 @@ mod tests { let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 4, params.clone(), 0)]).unwrap(); let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { - decode_audio_range(&file, &bytes, 0, 48_000, 1, &track.audio_starts, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames) - .unwrap() + decode_audio_range(&file, &bytes, 0, 48_000, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() }; let full = decode(&mut tracks[0], 0, 500); @@ -1917,12 +2244,11 @@ mod tests { let open_with_overlap = || { let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 2, params.clone(), 0)]).unwrap(); - tracks[0].audio_starts = vec![0, 512]; + tracks[0].state.get_mut().unwrap().audio_starts = AudioStarts::complete(vec![0, 512]); tracks }; let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { - decode_audio_range(&file, &bytes, 0, 48_000, 1, &track.audio_starts, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames) - .unwrap() + decode_audio_range(&file, &bytes, 0, 48_000, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() }; let mut wide_tracks = open_with_overlap(); From 05f181cc041dac379ce6552328fc26597b5de161 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 03:37:05 -0500 Subject: [PATCH 337/393] media: route MXF video and PCM/AES3 sound through craft-media::mxf (#4006) * media: route MXF video and PCM/AES3 sound through craft-media::mxf * media: use SoundFormat::Aes3Element for MXF AES3 sound * media: address MXF presentation window, timecode rate, reorder fallback, and unit coverage * media: fix StartTimecode and MediaSource::audio calls in MXF unit test * media: fix unnecessary cast and add MXF video/trim unit test * media: use PictureCoding::Avc and smoke-test open_mxf video+sound * media: pass raw_bytes Vec to open_bytes in MXF unit test * media: disambiguate Arc<[u8]> type in MXF unit test * media: remove duplicate AudioBackend enum after merge * media: match AudioBackend::Decoder struct variant * media: fix MXF sync_sample_before assertion in unit test --- Cargo.lock | 1 + crates/media/Cargo.toml | 2 +- crates/media/src/craft_source.rs | 389 ++++++++++++++++++++++++++++--- crates/media/tests/it/footage.rs | 27 +++ 4 files changed, 384 insertions(+), 35 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 619e268fd..48e59a0b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1417,6 +1417,7 @@ name = "craft-media" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" dependencies = [ + "chrono", "thiserror 2.0.21", ] diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index ffd8ea9fe..76a86a69a 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -30,7 +30,7 @@ craft-webp = { workspace = true, features = ["frames"] } craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] } craft-color = { workspace = true } craft-frame = { workspace = true } -craft-media = { workspace = true, features = ["mpegts"] } +craft-media = { workspace = true, features = ["mpegts", "mxf"] } craft-media-source = { workspace = true } craft-time = { workspace = true } craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "threads"] } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index c0deb4673..84379fb70 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -17,10 +17,14 @@ //! `Mp3`/`Mp2`/`Mp1` (with `CodecDelay` + `SeekPreRoll` timing). //! - Fallback (`filmcraft-codecs`): `alpha_mode == 1` (`BlockAdditional` alpha), unreadable/zlib //! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Flac`/`Pcm`). +//! - **MXF (`MXF`, video+audio & audio-only OP1a/OP-Atom)**: +//! - Shared (`craft-media::mxf` + `craft-video` + `MxfFile::read_pcm`): `H264`, `Hevc`, `Av1`, +//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; sound `Pcm` and `Aes3` (D-10). +//! - Fallback (`filmcraft-codecs`): compressed MXF sound or unsupported video codecs. //! - **Other containers & standalone audio**: //! - Shared (`craft_audio::Decoder` with `decode-native`): standalone `WAV`, `AIFF`, `MP3`/`MP2`/`MP1`, //! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). -//! - Fallback (`filmcraft-codecs`): `MXF`, `AVI`, `MPEG-TS`/`PS`, `Ogg Vorbis`, `FLAC`, `CAF`, or +//! - Fallback (`filmcraft-codecs`): `AVI`, `MPEG-TS`/`PS`, `Ogg Vorbis`, `FLAC`, `CAF`, or //! unsupported WAV/AIFF encodings. use std::sync::{Arc, Mutex}; @@ -31,6 +35,7 @@ use craft_frame::{Chroma, PixelData, Region, VideoFrame}; use craft_media::bitstream::unescape_rbsp; use craft_media::isobmff::{self, Mp4File}; use craft_media::matroska::{self, MkvFile}; +use craft_media::mxf::{self, MxfFile, SoundFormat}; use craft_media::{ByteSource, CodecId, CodecParams}; use craft_media_source::{ AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo, @@ -73,7 +78,12 @@ fn looks_like_matroska(head: &[u8]) -> bool { head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) } -/// Open an in-place ISO-BMFF, Matroska/WebM, or standalone audio source via `craft-media` / `craft-audio`. +/// True when `head` contains an MXF SMPTE KLV partition pack key. +fn looks_like_mxf(head: &[u8]) -> bool { + head.windows(12).any(|w| w == [0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01]) +} + +/// Open an in-place ISO-BMFF, Matroska/WebM, MXF, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. /// 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> { @@ -83,10 +93,13 @@ pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Opti if looks_like_matroska(head) { return open_matroska(name, reader.clone()); } + if looks_like_mxf(head) { + return open_mxf(name, reader.clone()); + } open_standalone_audio(name, head, reader.clone()) } -/// Open an in-memory ISO-BMFF, Matroska/WebM, or standalone audio source via `craft-media` / `craft-audio`. +/// Open an in-memory ISO-BMFF, Matroska/WebM, MXF, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { if looks_like_isobmff(&bytes) { return open_isobmff(name, Arc::new(bytes)); @@ -94,6 +107,9 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option::len(&bytes).min(64); @@ -109,6 +125,7 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option), + Mxf(Box), } impl ContainerFile { @@ -116,6 +133,7 @@ impl ContainerFile { 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()), + ContainerFile::Mxf(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), } } @@ -123,6 +141,7 @@ impl ContainerFile { 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())), + ContainerFile::Mxf(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), } } @@ -140,6 +159,16 @@ impl ContainerFile { let idx = track.sample_at_pts(t_track)?; Some((idx, track.samples[idx].pts)) } + ContainerFile::Mxf(f) => { + let track = f.tracks.get(track_idx)?; + let offset = track.first_edit_unit(); + let d = tick_to_rational_units(time, i64::from(track.edit_rate.num), i64::from(track.edit_rate.den)); + let presented_len = track.duration.unwrap_or_else(|| i64::try_from(track.display_order.len()).unwrap_or(0).saturating_sub(offset).max(0)); + let max_rel = presented_len.saturating_sub(1).max(0); + let pos = offset.saturating_add(d.clamp(0, max_rel)); + let idx = track.sample_at(pos)?; + Some((idx, track.samples[idx].pts)) + } } } @@ -147,6 +176,7 @@ impl ContainerFile { 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), + ContainerFile::Mxf(f) => f.tracks[track_idx].sync_before(target_idx), } } @@ -154,6 +184,7 @@ impl ContainerFile { match self { ContainerFile::Isobmff(f) => f.tracks[track_idx].samples[sample_idx].pts, ContainerFile::Matroska(f) => f.tracks[track_idx].samples[sample_idx].pts, + ContainerFile::Mxf(f) => f.tracks[track_idx].samples[sample_idx].pts, } } @@ -169,12 +200,17 @@ impl ContainerFile { let ns = track.ticks_to_ns(raw_pts); Tick::from_units(ns, 1_000_000_000) } + ContainerFile::Mxf(f) => { + let track = &f.tracks[track_idx]; + let rel_pts = raw_pts.saturating_sub(track.first_edit_unit()); + Tick::from_units(rel_pts.saturating_mul(i64::from(track.edit_rate.den)), i64::from(track.edit_rate.num.max(1))) + } } } fn audio_packet_is_stamped(&self, track_idx: usize, sample_idx: usize) -> bool { match self { - Self::Isobmff(_) => true, + Self::Isobmff(_) | Self::Mxf(_) => true, Self::Matroska(f) => f.tracks[track_idx].samples.get(sample_idx).is_some_and(|s| s.lace == 0 || s.duration > 0), } } @@ -405,6 +441,7 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code let packets = track.samples.iter().map(|s| PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples: Some(frame) }); AudioStarts::complete(contiguous_starts(packets, (frame / 2).max(tick_samples))) } + ContainerFile::Mxf(_) => AudioStarts::complete(Vec::new()), } } @@ -457,8 +494,10 @@ where audio_tracks.push(AudioTrackEntry { track_idx: idx, native_rate, - seek_preroll_samples, - state: Mutex::new(AudioTrackState { decoder: dec, audio_starts, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), + backend: AudioBackend::Decoder { + seek_preroll_samples, + state: Mutex::new(AudioTrackState { decoder: dec, audio_starts, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), + }, }); } Some((audio_tracks, audio_infos)) @@ -783,6 +822,135 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option }))) } +fn mxf_sound_window(track: &mxf::EssenceTrack) -> (u64, u64) { + let (sp_num, sp_den) = track.samples_per_edit_unit(); + let sp_den = i128::from(sp_den.max(1)); + let sp_num = i128::from(sp_num); + let offset_units = track.first_edit_unit(); + let presented_start = u64::try_from((i128::from(offset_units) * sp_num) / sp_den).unwrap_or(0); + let stored = track.stored_sample_frames(); + let presented_len = match track.duration { + Some(dur_units) => u64::try_from((i128::from(dur_units.max(0)) * sp_num) / sp_den).unwrap_or(u64::MAX).min(stored.saturating_sub(presented_start)), + None => stored.saturating_sub(presented_start), + }; + (presented_start, presented_len) +} + +fn mxf_start_timecode(tc: mxf::Timecode, rate: Option) -> i64 { + let Some(rate) = rate else { + return tc.start; + }; + if tc.rounded_base == 0 || rate.num <= 0 || rate.den <= 0 { + return tc.start; + } + let rounded_media = (rate.num as f64 / rate.den as f64).round().clamp(1.0, f64::from(u16::MAX)) as u16; + if rounded_media == tc.rounded_base { + return tc.start; + } + let (tc_num, tc_den) = if tc.drop_frame { (i128::from(tc.rounded_base) * 1000, 1001i128) } else { (i128::from(tc.rounded_base), 1i128) }; + let converted = (i128::from(tc.start) * tc_den * i128::from(rate.num)) / (tc_num * i128::from(rate.den)); + i64::try_from(converted).unwrap_or(tc.start) +} + +fn open_mxf(name: &str, source: SharedBytes) -> Option> { + let file = mxf::open(&*source).ok()?; + let video_idx = file.tracks.iter().position(|t| t.kind == mxf::TrackKind::Picture && !t.samples.is_empty() && t.edit_rate.is_valid()); + let sound_indices: Vec = + file.tracks.iter().enumerate().filter(|(_, t)| t.kind == mxf::TrackKind::Sound && !t.chunks.is_empty()).map(|(idx, _)| idx).collect(); + + if video_idx.is_none() && sound_indices.is_empty() { + return None; + } + + // Fall back to FilmCraft for compressed MXF sound until MXF compressed audio is wired. + let mut audio_tracks = Vec::new(); + let mut audio_infos = Vec::new(); + for &idx in &sound_indices { + if audio_tracks.len() >= MAX_AUDIO_STREAMS { + break; + } + let t = &file.tracks[idx]; + if !matches!(t.sound_format, SoundFormat::Pcm | SoundFormat::Aes3Element) { + return None; + } + let sound = t.sound.as_ref()?; + let rate = if sound.sample_rate.is_valid() { sound.sample_rate.as_f64().round().clamp(1.0, f64::from(u32::MAX)) as u32 } else { 48_000 }; + let channels = sound.channels.max(1); + let (presented_start, presented_len) = mxf_sound_window(t); + audio_infos.push(AudioStreamInfo { sample_rate: rate, channels, codec: t.codec.codec_id().name().to_string(), bits_per_sample: Some(sound.bits) }); + audio_tracks.push(AudioTrackEntry { track_idx: idx, native_rate: rate, backend: AudioBackend::MxfPcm { presented_start, presented_len } }); + } + + let (video_info, video_state, presentation, duration) = if let Some(v_idx) = video_idx { + let video_track = &file.tracks[v_idx]; + let video_params = video_track.codec_params(); + if !supports_video_codec(video_params.codec) || video_track.needs_reorder { + return None; + } + let (width, height) = video_track.picture.as_ref().map_or((0, 0), |p| (p.frame_width(), p.frame_height())); + let er = video_track.edit_rate; + let fps = f64::from(er.num) / f64::from(er.den.max(1)); + let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(er.num), i64::from(er.den))); + let dur_units = video_track.duration.unwrap_or_else(|| i64::try_from(video_track.display_order.len()).unwrap_or(0)); + let duration = Tick::from_units(dur_units.saturating_mul(i64::from(er.den)), i64::from(er.num.max(1))); + let has_alpha = video_track.picture.as_ref().is_some_and(|p| p.alpha_depth > 0); + 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 v_info = VideoStreamInfo { + width, + height, + frame_rate, + par: (1, 1), + codec: video_params.codec.name().to_string(), + pixel_format: String::new(), + color: ColorInfo::REC709, + has_alpha, + bitrate: None, + hdr: None, + }; + let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + (Some(v_info), Some(v_state), FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) + } else { + let duration = audio_tracks + .iter() + .map(|entry| { + let presented_len = match entry.backend { + AudioBackend::MxfPcm { presented_len, .. } => i64::try_from(presented_len).unwrap_or(i64::MAX), + AudioBackend::Decoder { .. } => 0, + }; + Tick::from_units(presented_len, i64::from(entry.native_rate)) + }) + .max() + .unwrap_or(Tick::ZERO); + (None, None, FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) + }; + + let kind = if video_info.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let start_timecode = file.timecode.map(|tc| mxf_start_timecode(tc, video_info.as_ref().map(|v| v.frame_rate))); + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, + audio_streams: audio_infos, + container: "mxf".to_string(), + start_timecode, + file_size: Some(source.len()), + }; + + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: ContainerFile::Mxf(Box::new(file)), + video_track_idx: video_idx, + presentation, + video: video_state, + audio_tracks, + }))) +} + struct CachedFrame { pts: i64, draft: bool, @@ -807,11 +975,25 @@ struct AudioTrackState { buf: Vec>, } +enum AudioBackend { + Decoder { seek_preroll_samples: i64, state: Mutex }, + MxfPcm { presented_start: u64, presented_len: u64 }, +} + struct AudioTrackEntry { track_idx: usize, native_rate: u32, - seek_preroll_samples: i64, - state: Mutex, + backend: AudioBackend, +} + +#[cfg(test)] +impl AudioTrackEntry { + fn decoder_parts(&mut self) -> (i64, &mut AudioTrackState) { + match &mut self.backend { + AudioBackend::Decoder { seek_preroll_samples, state } => (*seek_preroll_samples, state.get_mut().unwrap()), + AudioBackend::MxfPcm { .. } => panic!("expected decoder audio backend"), + } + } } #[derive(Clone, Copy)] @@ -917,18 +1099,50 @@ impl MediaSource for CraftMediaSource { let native_rate = entry.native_rate; let (native_start, native_frames) = native_audio_window(start, frames, native_rate, sample_rate); - 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, - entry.seek_preroll_samples, - &mut state, - native_start, - native_frames, - )?; + let decoded = match &entry.backend { + AudioBackend::Decoder { seek_preroll_samples, state: state_mutex } => { + let mut state = state_mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + decode_audio_range( + &self.file, + &*self.source, + entry.track_idx, + native_rate, + channels_count, + *seek_preroll_samples, + &mut state, + native_start, + native_frames, + )? + } + AudioBackend::MxfPcm { presented_start, presented_len } => { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + let ContainerFile::Mxf(mxf_file) = &self.file else { + return Err(MediaError::NoStream("audio")); + }; + let req_end = native_start.saturating_add(native_frames as i64); + let win_len = i64::try_from(*presented_len).unwrap_or(i64::MAX); + if *presented_start == 0 && native_start >= 0 && req_end <= win_len { + mxf_file.read_pcm(&*self.source, entry.track_idx, native_start as u64, native_frames).map_err(|e| MediaError::Io(e.to_string()))? + } else { + let mut out = vec![vec![0.0f32; native_frames]; channels_count]; + let clamped_start = native_start.max(0).min(win_len); + let clamped_end = req_end.max(0).min(win_len); + let read_len = usize::try_from(clamped_end.saturating_sub(clamped_start)).unwrap_or(0); + if read_len > 0 { + let dst_off = usize::try_from(clamped_start - native_start).unwrap_or(0); + let stored_start = presented_start.saturating_add(clamped_start as u64); + let read = mxf_file.read_pcm(&*self.source, entry.track_idx, stored_start, read_len).map_err(|e| MediaError::Io(e.to_string()))?; + for (dst, src) in out.iter_mut().zip(&read) { + let n = src.len().min(read_len); + dst[dst_off..dst_off + n].copy_from_slice(&src[..n]); + } + } + out + } + } + }; if sample_rate == native_rate { return Ok(AudioBuffer { sample_rate, channels: decoded }); @@ -1570,6 +1784,12 @@ fn tick_to_matroska_units(t: Tick, timebase: (u64, u64)) -> i64 { i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX }) } +fn tick_to_rational_units(t: Tick, num: i64, den: i64) -> i64 { + let denom = i128::from(craft_time::TICKS_PER_SECOND) * i128::from(den.max(1)); + let v = (i128::from(t.0) * i128::from(num.max(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; @@ -1765,12 +1985,13 @@ mod tests { assert_eq!(*source.packets.lock().unwrap(), (0..AUDIO_LOOKAHEAD).collect::>()); let first = expected_positions[0]; - assert_eq!(tracks[0].state.get_mut().unwrap().decoded_pos, first); + assert_eq!(tracks[0].decoder_parts().1.decoded_pos, first); let (mut reference, _) = open_audio_tracks(file, &source.bytes, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); - reference[0].state.get_mut().unwrap().audio_starts = AudioStarts::complete(expected_positions.to_vec()); + reference[0].decoder_parts().1.audio_starts = AudioStarts::complete(expected_positions.to_vec()); let decode = |track: &mut AudioTrackEntry, src: &dyn ByteSource, start, frames| { - decode_audio_range(file, src, 0, OPUS_RATE, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() + let (preroll, state) = track.decoder_parts(); + decode_audio_range(file, src, 0, OPUS_RATE, 1, preroll, state, start, frames).unwrap() }; // A first read before the initial packet can be ordinary leading silence // or negative pre-roll. Neither should trigger the cold suffix scan. @@ -1795,7 +2016,7 @@ mod tests { let backward_start = first + 2 * OPUS_FRAME as i64; let backward = decode(&mut tracks[0], source, backward_start, OPUS_FRAME); assert_eq!(backward, decode(&mut reference[0], &source.bytes, backward_start, OPUS_FRAME)); - let state = tracks[0].state.get_mut().unwrap(); + let (_, state) = tracks[0].decoder_parts(); assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); assert!(state.audio_starts.opus.is_none()); early @@ -1812,21 +2033,20 @@ mod tests { ) { let first = expected_positions[0]; let decode = |track: &mut AudioTrackEntry, src: &dyn ByteSource, start, frames| { - decode_audio_range(file, src, 0, OPUS_RATE, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() + let (preroll, state) = track.decoder_parts(); + decode_audio_range(file, src, 0, OPUS_RATE, 1, preroll, state, start, frames).unwrap() }; // A genuinely random first request is not the leading-silence shortcut. let (mut fresh, _) = open_audio_tracks(file, source, [(0, OPUS_PACKETS, params.clone(), delay)]).unwrap(); let (mut eager, _) = open_audio_tracks(file, &source.bytes, [(0, OPUS_PACKETS, params, delay)]).unwrap(); - eager[0].state.get_mut().unwrap().audio_starts = AudioStarts::complete(expected_positions.to_vec()); + eager[0].decoder_parts().1.audio_starts = AudioStarts::complete(expected_positions.to_vec()); if laced { - assert_eq!(file.audio_seek_info(0, expected_positions, fresh[0].seek_preroll_samples, start).0, 144); + assert_eq!(file.audio_seek_info(0, expected_positions, fresh[0].decoder_parts().0, start).0, 144); } let transient_packet = 64; *source.fail_once_at.lock().unwrap() = Some(transient_packet); { - let entry = &mut fresh[0]; - let preroll = entry.seek_preroll_samples; - let state = entry.state.get_mut().unwrap(); + let (preroll, state) = fresh[0].decoder_parts(); let error = decode_audio_range(file, source, 0, OPUS_RATE, 1, preroll, state, start, 3 * OPUS_FRAME).unwrap_err(); assert!(matches!(error, MediaError::Io(_))); assert_eq!(state.audio_starts.opus.as_ref().unwrap().len, transient_packet); @@ -1835,7 +2055,7 @@ mod tests { let cold = decode(&mut fresh[0], source, start, 3 * OPUS_FRAME); assert_eq!(cold, decode(&mut eager[0], &source.bytes, start, 3 * OPUS_FRAME)); assert!(cold[0].iter().any(|s| s.abs() > 1e-5)); - let state = fresh[0].state.get_mut().unwrap(); + let (_, state) = fresh[0].decoder_parts(); assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); assert!(state.audio_starts.opus.is_none()); } @@ -2075,6 +2295,105 @@ mod tests { } } + #[test] + fn mxf_sniffer_and_rational_units() { + assert!(looks_like_mxf(&[0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02])); + assert!(!looks_like_mxf(&[0x00, 0x00, 0x00, 0x18, b'f', b't', b'y', b'p'])); + assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 25, 1), 25); + assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 30000, 1001), 29); + } + + #[test] + fn mxf_start_timecode_converts_mismatched_rates_and_preserves_matching() { + let tc = mxf::Timecode { start: 100, rounded_base: 24, drop_frame: false }; + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::FPS_23_976)), 100); + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::FPS_24)), 100); + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::new(48, 1))), 200); + let df = mxf::Timecode { start: 3000, rounded_base: 30, drop_frame: true }; + assert_eq!(mxf_start_timecode(df, Some(FrameRate::FPS_29_97)), 3000); + assert_eq!(mxf_start_timecode(df, Some(FrameRate::new(60_000, 1001))), 6000); + assert_eq!(mxf_start_timecode(df, None), 3000); + } + + #[test] + fn mxf_opatom_pcm_reads_windowed_and_resampled_audio() { + let opts = mxf::write::OpAtomPcm { + sample_rate: 48_000, + bits: 16, + channels: 2, + edit_rate: None, + ids: mxf::write::PackageIds::from_seed("eff-mxf-test", "pcm"), + timecode: Some(mxf::write::StartTimecode { frames: 240, rate: mxf::Rational::new(24, 1), drop_frame: false }), + }; + let samples: Vec = (0..4800 * 2).map(|i| ((i * 137) % 16000) - 8000).collect(); + let bytes = mxf::write::write_opatom_pcm(&opts, &samples).expect("write opatom pcm"); + let src = open_bytes("test.mxf", Arc::from(bytes)).expect("recognized").expect("opened"); + let info = src.info(); + assert_eq!(info.container, "mxf"); + assert_eq!(info.kind, MediaKind::AudioOnly); + assert_eq!(info.audio_streams.len(), 1); + assert_eq!(info.audio_streams[0].sample_rate, 48_000); + assert_eq!(info.audio_streams[0].channels, 2); + + // Direct read at t=0 + let buf = src.audio(0, 1024, 48_000).expect("direct read"); + assert_eq!(buf.channels.len(), 2); + assert_eq!(buf.channels[0].len(), 1024); + assert!(buf.channels[0].iter().any(|&v| v.abs() > 0.01)); + + // Negative start and past-end read zero-fill cleanly + let neg = src.audio(-100, 200, 48_000).expect("negative start"); + assert!(neg.channels[0][..100].iter().all(|&v| v == 0.0)); + assert!(neg.channels[0][100..].iter().any(|&v| v.abs() > 0.01)); + let past = src.audio(4700, 200, 48_000).expect("past end"); + assert!(past.channels[0][..100].iter().any(|&v| v.abs() > 0.01)); + assert!(past.channels[0][100..].iter().all(|&v| v == 0.0)); + + // Resampled read + let resampled = src.audio(0, 512, 44_100).expect("resampled"); + assert_eq!(resampled.sample_rate, 44_100); + assert_eq!(resampled.channels[0].len(), 512); + } + + #[test] + fn mxf_video_window_and_sound_trim_helpers() { + let mut cfg = + mxf::write::WriterConfig::new(mxf::write::Pattern::Op1a, mxf::Rational::new(25, 1), mxf::write::PackageIds::from_seed("eff-mxf-vid", "op1a")); + cfg.picture = Some(mxf::write::PictureDesc::new(mxf::write::PictureCoding::Avc { profile_idc: 66, intra: false }, 16, 16)); + cfg.sound = vec![mxf::write::SoundDesc { sample_rate: 48_000, channels: 1, bits: 16 }]; + let mut w = mxf::write::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).expect("writer"); + let pcm = mxf::write::encode_pcm(&[vec![0.1f32; 1920]], 16); + w.push_picture(&[0x00, 0x00, 0x00, 0x01, 0x65], mxf::write::FrameInfo::intra()).expect("pic0"); + w.push_sound(0, &pcm).expect("snd0"); + w.push_picture(&[0x00, 0x00, 0x00, 0x01, 0x41], mxf::write::FrameInfo::intra()).expect("pic1"); + w.push_sound(0, &pcm).expect("snd1"); + let raw_bytes = w.finish().expect("finish").into_inner(); + let arc_bytes: Arc<[u8]> = Arc::from(raw_bytes.clone()); + let mxf_bytes: SharedBytes = Arc::new(arc_bytes); + let mut file = mxf::open(&*mxf_bytes).expect("open mxf"); + + // Exercise ContainerFile::Mxf video helpers and trimmed sound window. + file.tracks[0].origin = 1; + file.tracks[0].duration = Some(1); + file.tracks[1].origin = 1; + file.tracks[1].duration = Some(1); + let (win_start, win_len) = mxf_sound_window(&file.tracks[1]); + assert_eq!((win_start, win_len), (1920, 1920)); + + let container = ContainerFile::Mxf(Box::new(file)); + assert_eq!(container.sample_count(0), 2); + assert_eq!(container.target_sample(0, Tick::ZERO), Some((1, 1))); + assert_eq!(container.sync_sample_before(0, 1), 1); + assert_eq!(container.sample_pts(0, 1), 1); + assert_eq!(container.pts_to_tick(0, 1), Tick::ZERO); + + // Exercise open_mxf video+sound path on valid Op1a Avc+PCM. + let src = open_bytes("op1a.mxf", Arc::from(raw_bytes)).expect("recognized").expect("opened"); + assert_eq!(src.info().container, "mxf"); + assert_eq!(src.info().audio_streams.len(), 1); + assert!(open_bytes("op1a.mxf", Arc::from(vec![0u8; 4])).is_none()); + } + #[test] fn standalone_wav_opens_seeks_and_resamples_via_craft_audio() { // Minimal 48 kHz stereo 16-bit PCM WAV with 4800 frames (0.1s). @@ -2205,7 +2524,8 @@ mod tests { let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 4, params.clone(), 0)]).unwrap(); let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { - decode_audio_range(&file, &bytes, 0, 48_000, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() + let (preroll, state) = track.decoder_parts(); + decode_audio_range(&file, &bytes, 0, 48_000, 1, preroll, state, start, frames).unwrap() }; let full = decode(&mut tracks[0], 0, 500); @@ -2244,11 +2564,12 @@ mod tests { let open_with_overlap = || { let (mut tracks, _) = open_audio_tracks(&file, &bytes, [(0, 2, params.clone(), 0)]).unwrap(); - tracks[0].state.get_mut().unwrap().audio_starts = AudioStarts::complete(vec![0, 512]); + tracks[0].decoder_parts().1.audio_starts = AudioStarts::complete(vec![0, 512]); tracks }; let decode = |track: &mut AudioTrackEntry, start: i64, frames: usize| { - decode_audio_range(&file, &bytes, 0, 48_000, 1, track.seek_preroll_samples, track.state.get_mut().unwrap(), start, frames).unwrap() + let (preroll, state) = track.decoder_parts(); + decode_audio_range(&file, &bytes, 0, 48_000, 1, preroll, state, start, frames).unwrap() }; let mut wide_tracks = open_with_overlap(); diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index a542d4439..ee722d7eb 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1728,6 +1728,33 @@ fn audio_only_isobmff_and_matroska_route_through_craft_audio() { } } +#[test] +fn mxf_route_backward_seek_cancel_and_pcm_audio() { + use std::sync::atomic::AtomicBool; + let Some(p) = mpeg2_mxf() else { return }; + let f = probe(&p).expect("probe mxf"); + assert_eq!(f.codec, "MPEG-2", "MXF MPEG-2 must route through shared craft-media::mxf"); + let pool = MediaPool::new(); + let f20 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)).expect("frame 20"); + let f5 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("backward seek frame 5"); + assert_eq!((f20.width, f20.height), (1280, 720)); + assert_eq!((f5.width, f5.height), (1280, 720)); + let fresh_f5 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("fresh frame 5"); + assert!(psnr(&f5, &fresh_f5) > 55.0, "MXF backward seek frame 5 matches fresh decode"); + + let off = Arc::new(AtomicBool::new(true)); + let mut cancelled = Some(Arc::clone(&f5)); + pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 30))); + assert!(cancelled.is_none(), "cancelled MXF read must not decode"); + + let pcm_start = pool.audio_samples(&f, Tick::ZERO, 4800, 48_000); + let pcm_seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000); + assert_eq!(pcm_start.len(), 9600); + assert_eq!(pcm_seek.len(), 9600); + let rms_seek = (pcm_seek.iter().map(|v| v * v).sum::() / pcm_seek.len() as f32).sqrt(); + assert!((rms_seek - 0.0625).abs() < 0.02, "MXF PCM seek rms {rms_seek}"); +} + #[test] fn standalone_audio_formats_route_through_craft_audio() { for (file, args) in [ From c03539fafb5b8e7c1a14f057463c0edb8db3536c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 04:24:37 -0500 Subject: [PATCH 338/393] media: route AVI, MPEG-TS, and MPEG-PS through craft-media (#4010) * media: route AVI, MPEG-TS, and MPEG-PS through craft-media * media: add tick_to_rational_units and unwrap CodecParams dims * media: deduplicate container source builder and add AVI/MPEG unit test * media: import avi mux types from craft_media::avi root in test * media: test estimate_mpeg_frame_rate via pts helper * media: expand AVI and MPEG-TS unit test coverage * media: write >=5 TS packets in MPEG-TS unit test for sniff * media: expect MPEG-2 TS container name in unit test * media: restore ContainerFile::Avi arm in target_sample --- crates/media/Cargo.toml | 2 +- crates/media/src/craft_source.rs | 357 ++++++++++++++++++++++++++++++- crates/media/tests/it/footage.rs | 71 ++++++ 3 files changed, 424 insertions(+), 6 deletions(-) diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 76a86a69a..338bdc6f7 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -30,7 +30,7 @@ craft-webp = { workspace = true, features = ["frames"] } craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] } craft-color = { workspace = true } craft-frame = { workspace = true } -craft-media = { workspace = true, features = ["mpegts", "mxf"] } +craft-media = { workspace = true, features = ["mpegts", "avi", "mxf"] } craft-media-source = { workspace = true } craft-time = { workspace = true } craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "threads"] } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 84379fb70..f06391e5c 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -21,20 +21,28 @@ //! - Shared (`craft-media::mxf` + `craft-video` + `MxfFile::read_pcm`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; sound `Pcm` and `Aes3` (D-10). //! - Fallback (`filmcraft-codecs`): compressed MXF sound or unsupported video codecs. +//! - **AVI / MPEG-TS / MPEG-PS**: +//! - Shared (`craft-media::avi`, `craft-media::mpegts` + `craft-video` + `craft-audio`): +//! `H264`, `Hevc`, `Mpeg2Video`, `Av1`, `Vp9`, `Vp8`, `ProRes`, `Dnxhd`; audio `Aac`, +//! `Ac3`/`Eac3`, `Mp3`/`Mp2`/`Mp1`, `Pcm`. +//! - Fallback (`filmcraft-codecs`): unsupported codecs (`Mjpeg`, `Mpeg4Video`, `Ffv1`, `Theora`, +//! `Apv`, raw RGB AVI) or unsupported audio. //! - **Other containers & standalone audio**: //! - Shared (`craft_audio::Decoder` with `decode-native`): standalone `WAV`, `AIFF`, `MP3`/`MP2`/`MP1`, //! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). -//! - Fallback (`filmcraft-codecs`): `AVI`, `MPEG-TS`/`PS`, `Ogg Vorbis`, `FLAC`, `CAF`, or -//! unsupported WAV/AIFF encodings. +//! - Fallback (`filmcraft-codecs`): `Ogg Vorbis`, `FLAC`, `CAF`, or unsupported WAV/AIFF +//! encodings. 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, Region, VideoFrame}; +use craft_media::avi::{self, AviFile}; use craft_media::bitstream::unescape_rbsp; use craft_media::isobmff::{self, Mp4File}; use craft_media::matroska::{self, MkvFile}; +use craft_media::mpegts; use craft_media::mxf::{self, MxfFile, SoundFormat}; use craft_media::{ByteSource, CodecId, CodecParams}; use craft_media_source::{ @@ -83,7 +91,7 @@ fn looks_like_mxf(head: &[u8]) -> bool { head.windows(12).any(|w| w == [0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01]) } -/// Open an in-place ISO-BMFF, Matroska/WebM, MXF, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. +/// Open an in-place ISO-BMFF, Matroska/WebM, MXF, AVI, MPEG-TS/PS, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. /// 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> { @@ -96,10 +104,16 @@ pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Opti if looks_like_mxf(head) { return open_mxf(name, reader.clone()); } + if avi::sniff(head) { + return open_avi(name, reader.clone()); + } + if let Some(fmt) = mpegts::sniff(head) { + return open_mpeg(name, fmt, reader.clone()); + } open_standalone_audio(name, head, reader.clone()) } -/// Open an in-memory ISO-BMFF, Matroska/WebM, MXF, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. +/// Open an in-memory ISO-BMFF, Matroska/WebM, MXF, AVI, MPEG-TS/PS, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option> { if looks_like_isobmff(&bytes) { return open_isobmff(name, Arc::new(bytes)); @@ -110,6 +124,12 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option::len(&bytes).min(64); @@ -125,6 +145,8 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option), + Avi(Box), + Mpeg { file: Box, origin_pts: i64 }, Mxf(Box), } @@ -133,6 +155,8 @@ impl ContainerFile { 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()), + ContainerFile::Avi(f) => f.streams.get(track_idx).map_or(0, |s| s.chunks.len()), + ContainerFile::Mpeg { file, .. } => file.streams.get(track_idx).map_or(0, |s| s.units.len()), ContainerFile::Mxf(f) => f.tracks.get(track_idx).map_or(0, |t| t.samples.len()), } } @@ -141,6 +165,8 @@ impl ContainerFile { 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())), + ContainerFile::Avi(f) => f.read_chunk(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), + ContainerFile::Mpeg { file, .. } => file.read_unit(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), ContainerFile::Mxf(f) => f.read_sample(src, track_idx, sample_idx).map_err(|e| MediaError::Io(e.to_string())), } } @@ -159,6 +185,29 @@ impl ContainerFile { let idx = track.sample_at_pts(t_track)?; Some((idx, track.samples[idx].pts)) } + ContainerFile::Avi(f) => { + let s = f.streams.get(track_idx)?; + if s.chunks.is_empty() || s.rate == 0 || s.scale == 0 { + return None; + } + let max_idx = i64::try_from(s.chunks.len() - 1).unwrap_or(0); + let d = tick_to_rational_units(time, i64::from(s.rate), i64::from(s.scale)).clamp(0, max_idx); + let idx = usize::try_from(d).ok()?; + Some((idx, d)) + } + ContainerFile::Mpeg { file, origin_pts } => { + let s = file.streams.get(track_idx)?; + let t_90k = tick_to_units(time, 90_000).saturating_add(*origin_pts); + let (idx, pts) = s + .units + .iter() + .enumerate() + .filter_map(|(i, u)| u.pts.map(|p| (i, p))) + .filter(|&(_, p)| p <= t_90k) + .max_by_key(|&(_, p)| p) + .or_else(|| s.units.iter().enumerate().find_map(|(i, u)| u.pts.map(|p| (i, p))))?; + Some((idx, pts)) + } ContainerFile::Mxf(f) => { let track = f.tracks.get(track_idx)?; let offset = track.first_edit_unit(); @@ -176,6 +225,16 @@ impl ContainerFile { 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), + ContainerFile::Avi(f) => { + let s = &f.streams[track_idx]; + let i = target_idx.min(s.chunks.len().saturating_sub(1)); + if s.keyframes_known { (0..=i).rev().find(|&k| s.chunks[k].key).unwrap_or(0) } else { 0 } + } + ContainerFile::Mpeg { file, .. } => { + let s = &file.streams[track_idx]; + let i = target_idx.min(s.units.len().saturating_sub(1)); + (0..=i).rev().find(|&k| s.units[k].key).unwrap_or(0) + } ContainerFile::Mxf(f) => f.tracks[track_idx].sync_before(target_idx), } } @@ -184,6 +243,8 @@ impl ContainerFile { match self { ContainerFile::Isobmff(f) => f.tracks[track_idx].samples[sample_idx].pts, ContainerFile::Matroska(f) => f.tracks[track_idx].samples[sample_idx].pts, + ContainerFile::Avi(_) => i64::try_from(sample_idx).unwrap_or(0), + ContainerFile::Mpeg { file, .. } => file.streams[track_idx].units[sample_idx].pts.unwrap_or(0), ContainerFile::Mxf(f) => f.tracks[track_idx].samples[sample_idx].pts, } } @@ -200,6 +261,11 @@ impl ContainerFile { let ns = track.ticks_to_ns(raw_pts); Tick::from_units(ns, 1_000_000_000) } + ContainerFile::Avi(f) => { + let s = &f.streams[track_idx]; + Tick::from_units(raw_pts.saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + } + ContainerFile::Mpeg { origin_pts, .. } => Tick::from_units(raw_pts.saturating_sub(*origin_pts), 90_000), ContainerFile::Mxf(f) => { let track = &f.tracks[track_idx]; let rel_pts = raw_pts.saturating_sub(track.first_edit_unit()); @@ -210,7 +276,7 @@ impl ContainerFile { fn audio_packet_is_stamped(&self, track_idx: usize, sample_idx: usize) -> bool { match self { - Self::Isobmff(_) | Self::Mxf(_) => true, + Self::Isobmff(_) | Self::Avi(_) | Self::Mpeg { .. } | Self::Mxf(_) => true, Self::Matroska(f) => f.tracks[track_idx].samples.get(sample_idx).is_some_and(|s| s.lace == 0 || s.duration > 0), } } @@ -441,6 +507,50 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code let packets = track.samples.iter().map(|s| PacketTime { stamp: stamp_for(s.pts), stamped: s.lace == 0 || s.duration > 0, samples: Some(frame) }); AudioStarts::complete(contiguous_starts(packets, (frame / 2).max(tick_samples))) } + ContainerFile::Avi(f) => { + let Some(s) = f.streams.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; + let den = i128::from(s.rate.max(1)); + let scale = i128::from(s.scale.max(1)); + if s.sample_size > 0 { + let mut acc = 0i64; + return AudioStarts::complete( + s.chunks + .iter() + .map(|c| { + let start = acc; + acc = acc.saturating_add(i64::from(c.size / s.sample_size.max(1))); + start + }) + .collect(), + ); + } + let stamps: Vec = (0..s.chunks.len()).map(|i| i64::try_from(i128::from(i as i64) * scale * rate / den).unwrap_or(0)).collect(); + let Some(frame) = fixed_samples else { + return AudioStarts::complete(stamps); + }; + AudioStarts::complete(contiguous_starts(stamps.into_iter().map(|stamp| PacketTime { stamp, stamped: true, samples: Some(frame) }), frame / 2)) + } + ContainerFile::Mpeg { file, origin_pts } => { + let Some(s) = file.streams.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; + let mut last_stamp = 0i64; + let stamps: Vec = s + .units + .iter() + .map(|u| { + if let Some(p) = u.pts { + last_stamp = i64::try_from(i128::from(p.saturating_sub(*origin_pts)) * rate / 90_000).unwrap_or(0); + } + last_stamp + }) + .collect(); + let Some(frame) = fixed_samples else { + return AudioStarts::complete(stamps); + }; + AudioStarts::complete(contiguous_starts( + s.units.iter().zip(stamps).map(|(u, stamp)| PacketTime { stamp, stamped: u.pts.is_some(), samples: Some(frame) }), + frame / 2, + )) + } ContainerFile::Mxf(_) => AudioStarts::complete(Vec::new()), } } @@ -822,6 +932,51 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option }))) } +struct ContainerVideoPart { + track_idx: usize, + info: VideoStreamInfo, + state: Mutex, +} + +fn finish_container_source( + name: &str, + container_name: &str, + source: SharedBytes, + container: ContainerFile, + video: Option, + duration: Tick, + audio_candidates: Vec<(usize, usize, CodecParams, u64)>, +) -> Option> { + let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + if video.is_none() && audio_tracks.is_empty() { + return None; + } + let kind = if video.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; + let (video_track_idx, video_info, video_state) = match video { + Some(v) => (Some(v.track_idx), Some(v.info), Some(v.state)), + None => (None, None, None), + }; + let info = MediaInfo { + name: name.to_string(), + kind, + duration, + video: video_info, + audio_streams: audio_infos, + container: container_name.to_string(), + start_timecode: None, + file_size: Some(source.len()), + }; + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx, + presentation: FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, + video: video_state, + audio_tracks, + }))) +} + fn mxf_sound_window(track: &mxf::EssenceTrack) -> (u64, u64) { let (sp_num, sp_den) = track.samples_per_edit_unit(); let sp_den = i128::from(sp_den.max(1)); @@ -951,6 +1106,141 @@ fn open_mxf(name: &str, source: SharedBytes) -> Option> { }))) } +fn default_video_info(width: u32, height: u32, frame_rate: FrameRate, codec: &CodecParams) -> VideoStreamInfo { + VideoStreamInfo { + width, + height, + frame_rate, + par: (1, 1), + codec: codec.codec.name().to_string(), + pixel_format: String::new(), + color: ColorInfo::REC709, + has_alpha: false, + bitrate: None, + hdr: None, + } +} + +fn open_avi(name: &str, source: SharedBytes) -> Option> { + let file = avi::open(&*source).ok()?; + let video_idx = file.streams.iter().position(|s| s.kind == avi::StreamKind::Video && !s.chunks.is_empty() && s.rate > 0 && s.scale > 0); + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .streams + .iter() + .enumerate() + .filter(|(_, s)| s.kind == avi::StreamKind::Audio && !s.chunks.is_empty()) + .map(|(idx, s)| (idx, s.chunks.len(), s.codec_params(), 0)) + .collect(); + + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } + + let (video, duration) = if let Some(v_idx) = video_idx { + let video_stream = &file.streams[v_idx]; + let video_params = video_stream.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + let (width, height) = video_stream.video.as_ref().map_or((0, 0), |v| (v.width.unsigned_abs(), v.height.unsigned_abs())); + let fps = f64::from(video_stream.rate) / f64::from(video_stream.scale.max(1)); + let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(video_stream.rate), i64::from(video_stream.scale))); + let total_units = i64::from(video_stream.length.max(video_stream.chunks.len() as u32)); + let duration = Tick::from_units(total_units.saturating_mul(i64::from(video_stream.scale)), i64::from(video_stream.rate.max(1))); + 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 = default_video_info(width, height, frame_rate, &video_params); + let state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) + } else { + let duration = audio_candidates + .iter() + .map(|&(idx, _, _, _)| { + let s = &file.streams[idx]; + Tick::from_units(i64::from(s.length).saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + }) + .max() + .unwrap_or(Tick::ZERO); + (None, duration) + }; + + finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), video, duration, audio_candidates) +} + +fn estimate_mpeg_frame_rate_pts(pts: impl IntoIterator) -> FrameRate { + let mut pts: Vec = pts.into_iter().take(64).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() { + return FrameRate::FPS_30; + } + deltas.sort_unstable(); + let median = deltas[deltas.len() / 2]; + snap_common_fps(90_000.0 / median as f64).unwrap_or(FrameRate::FPS_30) +} + +fn estimate_mpeg_frame_rate(units: &[mpegts::Unit]) -> FrameRate { + estimate_mpeg_frame_rate_pts(units.iter().filter_map(|u| u.pts)) +} + +fn open_mpeg(name: &str, fmt: mpegts::Format, source: SharedBytes) -> Option> { + let file = mpegts::open(&*source).ok()?; + let origin_pts = file.streams.iter().filter_map(|s| s.pts_range().map(|(lo, _)| lo)).min().unwrap_or(0); + let video_idx = file.streams.iter().position(|s| s.kind() == mpegts::Kind::Video && !s.units.is_empty()); + let audio_candidates: Vec<(usize, usize, CodecParams, u64)> = file + .streams + .iter() + .enumerate() + .filter(|(_, s)| s.kind() == mpegts::Kind::Audio && !s.units.is_empty()) + .map(|(idx, s)| (idx, s.units.len(), s.codec_params(), 0)) + .collect(); + + if video_idx.is_none() && audio_candidates.is_empty() { + return None; + } + + let (video, duration) = if let Some(v_idx) = video_idx { + let video_stream = &file.streams[v_idx]; + let video_params = video_stream.codec_params(); + if !supports_video_codec(video_params.codec) { + return None; + } + let mut 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 mut decoded_dims = (video_params.width.unwrap_or(0), video_params.height.unwrap_or(0)); + if decoded_dims.0 == 0 || decoded_dims.1 == 0 { + let start_u = video_stream.units.iter().position(|u| u.key).unwrap_or(0); + for u_idx in start_u..video_stream.units.len().min(start_u + 16) { + if let Ok(pkt) = file.read_unit(&*source, v_idx, u_idx) + && let Ok(frames) = video_decoder.decode(&pkt, video_stream.units[u_idx].pts.unwrap_or(0)) + && let Some(vf) = frames.first() + { + decoded_dims = (vf.width(), vf.height()); + break; + } + } + let _ = video_decoder.reset(); + } + let frame_rate = estimate_mpeg_frame_rate(&video_stream.units); + let duration = video_stream.pts_range().map_or(Tick::ZERO, |(_, hi)| Tick::from_units(hi.saturating_sub(origin_pts), 90_000)); + let info = default_video_info(decoded_dims.0, decoded_dims.1, frame_rate, &video_params); + let state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) + } else { + let duration = audio_candidates + .iter() + .filter_map(|&(idx, _, _, _)| file.streams[idx].pts_range().map(|(_, hi)| Tick::from_units(hi.saturating_sub(origin_pts), 90_000))) + .max() + .unwrap_or(Tick::ZERO); + (None, duration) + }; + + finish_container_source(name, fmt.name(), source, ContainerFile::Mpeg { file: Box::new(file), origin_pts }, video, duration, audio_candidates) +} struct CachedFrame { pts: i64, draft: bool, @@ -2494,6 +2784,63 @@ mod tests { assert!(contiguous_starts([], 512).is_empty()); } + #[test] + fn avi_and_mpeg_helpers_and_in_memory_route() { + assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 24, 1), 24); + assert_eq!(tick_to_rational_units(Tick(-1), 24, 1), 0); + assert_eq!(estimate_mpeg_frame_rate_pts([0, 3000, 6000]), FrameRate::FPS_30); + assert_eq!(estimate_mpeg_frame_rate(&[]), FrameRate::FPS_30); + + let streams = vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"H264", 16, 16, 24, 1)), avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 2, 16))]; + let mut w = avi::AviWriter::new(std::io::Cursor::new(Vec::new()), streams, avi::MuxOptions::default()).expect("avi writer"); + let pcm = vec![0x10u8; 2000 * 4]; + w.write_chunk(0, &[0x00, 0x00, 0x00, 0x01, 0x65], true).expect("v0"); + w.write_chunk(1, &pcm, true).expect("a0"); + w.write_chunk(0, &[0x00, 0x00, 0x00, 0x01, 0x41], false).expect("v1"); + w.write_chunk(1, &pcm, true).expect("a1"); + let raw = w.finish().expect("finish").into_inner(); + let avi_file = avi::open(raw.as_slice()).expect("open avi"); + let avi_container = ContainerFile::Avi(Box::new(avi_file)); + assert_eq!(avi_container.sample_count(0), 2); + assert_eq!(avi_container.target_sample(0, Tick::ZERO), Some((0, 0))); + assert_eq!(avi_container.sync_sample_before(0, 1), 0); + assert_eq!(avi_container.sample_pts(0, 1), 1); + assert!(avi_container.pts_to_tick(0, 1) > Tick::ZERO); + + let src = open_bytes("test.avi", Arc::from(raw)).expect("recognized").expect("opened"); + assert_eq!(src.info().container, "avi"); + assert_eq!(src.info().audio_streams[0].sample_rate, 48_000); + let audio = src.audio(0, 512, 48_000).expect("avi audio"); + assert_eq!(audio.channels[0].len(), 512); + + // Audio-only AVI route. + let mut wa = + avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16))], avi::MuxOptions::default()) + .expect("audio avi writer"); + wa.write_chunk(0, &pcm_s16le_bytes(4_000, 1024), true).expect("a0"); + let audio_avi = + open_bytes("audio.avi", Arc::from(wa.finish().expect("finish audio avi").into_inner())).expect("recognized audio avi").expect("opened audio avi"); + assert_eq!(audio_avi.info().kind, MediaKind::AudioOnly); + assert_eq!(audio_avi.audio(0, 256, 48_000).expect("audio avi read").channels[0].len(), 256); + + // MPEG-TS route and ContainerFile::Mpeg helpers. + let mut ts = mpegts::mux::Muxer::new(Vec::new(), mpegts::mux::Config::default(), &[mpegts::mux::Stream::new(0x100, mpegts::mux::Codec::H264)]) + .expect("ts muxer"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x65, 0x88], pts: 90_000, dts: None, key: true }).expect("ts f0"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x41, 0x9A], pts: 93_000, dts: None, key: false }).expect("ts f1"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x41, 0x9A], pts: 96_000, dts: None, key: false }).expect("ts f2"); + ts.write_frame(0, &mpegts::mux::Frame { data: &[0x00, 0x00, 0x00, 0x01, 0x41, 0x9A], pts: 99_000, dts: None, key: false }).expect("ts f3"); + let ts_bytes = ts.finish().expect("finish ts"); + let ts_file = mpegts::open(ts_bytes.as_slice()).expect("open ts"); + let ts_container = ContainerFile::Mpeg { file: Box::new(ts_file), origin_pts: 90_000 }; + assert!(ts_container.target_sample(0, Tick::ZERO).is_some()); + let _ = ts_container.sync_sample_before(0, 1); + assert_eq!(ts_container.sample_pts(0, 0), 90_000); + assert_eq!(ts_container.pts_to_tick(0, 90_000), Tick::ZERO); + let ts_src = open_bytes("test.ts", Arc::from(ts_bytes)).expect("recognized ts").expect("opened ts"); + assert_eq!(ts_src.info().container, "MPEG-2 TS"); + } + fn pcm_s16le_bytes(sample: i16, count: usize) -> Vec { std::iter::repeat_n(sample.to_le_bytes(), count).flatten().collect() } diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index ee722d7eb..2d6af707c 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -1964,3 +1964,74 @@ fn audio_delayed_first_packet_honored_on_sequential_and_seek() { assert_samples_close(&backward, &seq[start..start + 4800 * 2], 1e-4, "delayed backward seek vs sequential"); } } + +#[test] +fn avi_and_mpegts_route_through_craft_media_with_seek_and_cancel() { + use std::sync::atomic::AtomicBool; + for (file, args) in [ + ( + "route_h264.avi", + &[ + "-f", + "lavfi", + "-i", + "testsrc2=size=160x120:rate=24:duration=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-g", + "12", + "-c:a", + "mp3", + ][..], + ), + ( + "route_h264.ts", + &[ + "-f", + "lavfi", + "-i", + "testsrc2=size=160x120:rate=24:duration=1", + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-g", + "12", + "-c:a", + "aac", + ][..], + ), + ] { + let Some(p) = try_ffmpeg_fixture(file, args) else { + continue; + }; + let f = probe(&p).expect(file); + assert!(f.has_video && f.has_audio, "{file} must have video+audio"); + let pool = MediaPool::new(); + let f15 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 15)).expect("frame 15"); + let f3 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 3)).expect("backward seek frame 3"); + assert_eq!((f15.width, f15.height), (160, 120)); + let fresh_f3 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 3)).expect("fresh frame 3"); + assert!(psnr(&f3, &fresh_f3) > 50.0, "{file} backward seek frame 3 matches fresh"); + + let off = Arc::new(AtomicBool::new(true)); + let mut cancelled = Some(Arc::clone(&f3)); + pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20))); + assert!(cancelled.is_none(), "{file} cancelled read must not decode"); + + let pcm_seek = pool.audio_samples(&f, Tick(TICKS_PER_SECOND / 2), 4800, 48_000); + assert_eq!(pcm_seek.len(), 9600); + let rms = (pcm_seek.iter().map(|v| v * v).sum::() / pcm_seek.len() as f32).sqrt(); + assert!((rms - 0.0625).abs() < 0.03, "{file} audio seek rms {rms}"); + } +} From c4bf4f592540e0627b9eafd17e8838d40a315d37 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:31:31 +0700 Subject: [PATCH 339/393] Round recorded MXF start timecodes to the nearest video frame (#4018) Co-authored-by: Codex --- crates/media/src/craft_source.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index f06391e5c..ae4aac50f 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1003,7 +1003,14 @@ fn mxf_start_timecode(tc: mxf::Timecode, rate: Option) -> i64 { return tc.start; } let (tc_num, tc_den) = if tc.drop_frame { (i128::from(tc.rounded_base) * 1000, 1001i128) } else { (i128::from(tc.rounded_base), 1i128) }; - let converted = (i128::from(tc.start) * tc_den * i128::from(rate.num)) / (tc_num * i128::from(rate.den)); + let Some(numerator) = (i128::from(tc.start) * tc_den).checked_mul(i128::from(rate.num)) else { + return tc.start; + }; + let denominator = tc_num * i128::from(rate.den); + // Match FilmCraft's nearest-frame rounding for recorded nonnegative labels. + // Keep the shared reader's existing truncation for negative counts. + let round_up = numerator >= 0 && numerator % denominator >= denominator - denominator / 2; + let converted = numerator / denominator + i128::from(round_up); i64::try_from(converted).unwrap_or(tc.start) } @@ -2605,6 +2612,29 @@ mod tests { assert_eq!(mxf_start_timecode(df, None), 3000); } + #[test] + fn mxf_start_timecode_rounds_fractional_recorded_frames() { + // Three frames at 25 fps fall at 3.6 frames on a 30 fps track. + let tc = mxf::Timecode { start: 3, rounded_base: 25, drop_frame: false }; + assert_eq!(mxf_start_timecode(tc, Some(FrameRate::FPS_30)), 4); + // Two frames at 24 fps fall exactly halfway between frames 2 and 3. + let half = mxf::Timecode { start: 2, rounded_base: 24, ..tc }; + assert_eq!(mxf_start_timecode(half, Some(FrameRate::FPS_30)), 3); + let integral = mxf::Timecode { start: 5, ..tc }; + assert_eq!(mxf_start_timecode(integral, Some(FrameRate::FPS_30)), 6); + + let negative = mxf::Timecode { start: -100, ..tc }; + assert_eq!(mxf_start_timecode(negative, Some(FrameRate::FPS_30)), -120); + let negative_fraction = mxf::Timecode { start: -3, ..tc }; + assert_eq!(mxf_start_timecode(negative_fraction, Some(FrameRate::FPS_30)), -3); + let fallback = mxf::Timecode { start: i64::MAX - 1, ..tc }; + assert_eq!(mxf_start_timecode(fallback, Some(FrameRate::FPS_50)), i64::MAX - 1); + let too_large = mxf::Timecode { start: i64::MAX, ..tc }; + assert_eq!(mxf_start_timecode(too_large, Some(FrameRate::FPS_50)), i64::MAX); + let extreme = mxf::Timecode { drop_frame: true, ..too_large }; + assert_eq!(mxf_start_timecode(extreme, Some(FrameRate::new(i64::MAX, 1))), i64::MAX); + } + #[test] fn mxf_opatom_pcm_reads_windowed_and_resampled_audio() { let opts = mxf::write::OpAtomPcm { From 0fbf652f49de6bd3441cdbe85456ed29d96a0a5d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:07:08 +0700 Subject: [PATCH 340/393] test: report stalls in the ProRes MOV roundtrip (#4019) --- .config/nextest.toml | 7 ++++++ crates/export/tests/it/roundtrip.rs | 39 +++++++++++++++++++++-------- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 38f939c31..54ea528cf 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -12,3 +12,10 @@ gpu = { max-threads = 1 } [[profile.default.overrides]] filter = 'package(effectcraft-gpu) | package(effectcraft-ui-egui) | package(effectcraft-sam2) | (package(effectcraft-cli) & test(/^cli::gpu_adapter_name_/))' test-group = 'gpu' + +# This sub-second test can stall indefinitely. Keep its assertions and surface the last +# flushed stage on timeout instead of waiting for the whole job to be cancelled. +[[profile.default.overrides]] +filter = 'binary_id(=effectcraft-export::it) & test(=roundtrip::prores_mov_roundtrip)' +slow-timeout = { period = "60s", terminate-after = 2, on-timeout = "fail" } +failure-output = "immediate" diff --git a/crates/export/tests/it/roundtrip.rs b/crates/export/tests/it/roundtrip.rs index 65644f071..fbde6ab1b 100644 --- a/crates/export/tests/it/roundtrip.rs +++ b/crates/export/tests/it/roundtrip.rs @@ -126,7 +126,19 @@ fn check_frame(img: &Image, k: u64, tol: f32) { assert!(near([c[0], c[1], c[2]], want, tol), "frame {k} centre {c:?} want {want:?}"); } -fn decode_movie(path: &Path, frames: u64, tol: f32) -> effectcraft_project::Footage { +/// Write to the test process's stderr, not libtest's buffered per-test capture: nextest can +/// then show the last stage even when it has to terminate a stuck process. +fn prores_stage(trace: bool, stage: std::fmt::Arguments<'_>) { + use std::io::Write as _; + + if trace { + let mut stderr = std::io::stderr().lock(); + let _ = writeln!(stderr, "ProRes MOV roundtrip: {stage}").and_then(|()| stderr.flush()); + } +} + +fn decode_movie(path: &Path, frames: u64, tol: f32, trace: bool) -> effectcraft_project::Footage { + prores_stage(trace, format_args!("native probe")); let f = effectcraft_media::probe(path).expect("probe our output"); assert_eq!((f.width, f.height), (W, H)); assert!(f.has_video); @@ -134,6 +146,7 @@ fn decode_movie(path: &Path, frames: u64, tol: f32) -> effectcraft_project::Foot assert_eq!(n as u64, frames, "frame count from duration {:?} @ {:?}", f.duration, f.frame_rate); let pool = MediaPool::new(); for k in 0..frames { + prores_stage(trace, format_args!("native decode frame {k}")); let img = pool.frame_at(&f, f.frame_rate.tick_of(k as i64)).expect("decode"); check_frame(&img, k, tol); } @@ -153,8 +166,9 @@ fn ffprobe(path: &Path) -> Option { } /// Frame `k` decoded by ffmpeg (external oracle) as RGBA, or `None` without ffmpeg. -fn ffmpeg_frame(path: &Path, k: u64) -> Option { +fn ffmpeg_frame(path: &Path, k: u64, trace: bool) -> Option { let png = path.with_extension(format!("ffmpeg-{k}.png")); + prores_stage(trace, format_args!("FFmpeg decode frame {k}")); let st = Command::new("ffmpeg") .args(["-hide_banner", "-loglevel", "error", "-y", "-i"]) .arg(path) @@ -163,13 +177,14 @@ fn ffmpeg_frame(path: &Path, k: u64) -> Option { .status() .ok()?; assert!(st.success(), "ffmpeg failed to decode {}", path.display()); + prores_stage(trace, format_args!("read FFmpeg oracle PNG for frame {k}")); let img = image::open(&png).expect("ffmpeg png").to_rgba8(); Some(Image::from_rgba8(img.width(), img.height(), img.as_raw())) } -fn ffmpeg_check(path: &Path, tol: f32) { +fn ffmpeg_check(path: &Path, tol: f32, trace: bool) { for k in [0, 4, 5, FRAMES - 1] { - match ffmpeg_frame(path, k) { + match ffmpeg_frame(path, k, trace) { Some(img) => check_frame(&img, k, tol), None => { eprintln!("ffmpeg not found: skipping oracle decode"); @@ -187,8 +202,8 @@ fn h264_mp4_roundtrip() { let path = d.join("comp.mp4"); let r = run(&p, cid, &NoFootage, &om, &path); assert!(r.bytes > 100 && !r.audio); - decode_movie(&path, FRAMES, 0.08); - ffmpeg_check(&path, 0.08); + decode_movie(&path, FRAMES, 0.08, false); + ffmpeg_check(&path, 0.08, false); if let Some(s) = ffprobe(&path) { assert!(s.contains("h264|64|48|yuv420p"), "{s}"); assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}"); @@ -223,17 +238,21 @@ fn h264_odd_size_is_cropped_even() { #[test] fn prores_mov_roundtrip() { + prores_stage(true, format_args!("fixture setup")); let d = out_dir("prores"); let (p, cid) = project(None); let om = OutputModule::for_format(OutputFormat::ProRes); let path = d.join("comp.mov"); + prores_stage(true, format_args!("native export")); run(&p, cid, &NoFootage, &om, &path); - decode_movie(&path, FRAMES, 0.03); - ffmpeg_check(&path, 0.03); + decode_movie(&path, FRAMES, 0.03, true); + ffmpeg_check(&path, 0.03, true); + prores_stage(true, format_args!("ffprobe metadata")); if let Some(s) = ffprobe(&path) { assert!(s.starts_with("prores|64|48"), "{s}"); assert!(s.lines().next().unwrap_or("").ends_with("|12"), "{s}"); } + prores_stage(true, format_args!("complete")); } #[test] @@ -758,12 +777,12 @@ fn webm_vp9_opus_roundtrip() { let r = run(&p, cid, &pool, &om, &path); assert!(r.audio && r.bytes > 200, "{r:?}"); // Decoded back through FilmCraft (Matroska demuxer, VP9 and Opus decoders). - let f = decode_movie(&path, FRAMES, 0.08); + let f = decode_movie(&path, FRAMES, 0.08, false); assert!(f.has_audio); let s = MediaPool::new().audio_samples(&f, Tick::from_seconds_f64(0.3), 24_000, 48_000); let l = rms(s.iter().step_by(2).copied()); assert!((l - 0.3536).abs() < 0.06, "left RMS {l}"); - ffmpeg_check(&path, 0.08); + ffmpeg_check(&path, 0.08, false); if let Some(s) = ffprobe(&path) { assert!(s.contains("vp9|64|48|yuv420p"), "{s}"); assert!(s.contains("opus"), "{s}"); From 7003f0a056f9b001fb8f4877f9f5371d1d03dbc9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 05:19:23 -0500 Subject: [PATCH 341/393] media: switch non-fallback AUDIO_EXTENSIONS and convert tests to craft-libs (#4020) * media: switch non-fallback AUDIO_EXTENSIONS and convert tests to craft-libs * media: accept FrameView in frame_to_image --- crates/media/src/convert.rs | 34 +++++++++++++++------------------- crates/media/src/lib.rs | 2 +- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index bf83a9650..dd3a46801 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -137,7 +137,7 @@ impl<'a> From<&'a crate::stream::DecodedFrame> for FrameView<'a> { /// Convert a FilmCraft frame to an [`Image`]. #[cfg(test)] -pub(crate) fn frame_to_image(f: &VideoFrame, op: AlphaOp) -> Image { +pub(crate) fn frame_to_image<'a>(f: impl Into>, op: AlphaOp) -> Image { frame_to_image_in(f, op, Vec::new()) } @@ -533,25 +533,28 @@ pub(crate) fn straight_to_image(w: u32, h: u32, px: &[[f32; 4]], op: AlphaOp) -> #[cfg(test)] mod tests { use super::*; + use craft_color::ColorInfo; + use craft_frame::{Chroma, PixelData, VideoFrame}; + use craft_time::Tick; use std::sync::Arc; - fn yuv_frame(y: u8, u: u8, v: u8, color: filmcraft_color::ColorInfo) -> VideoFrame { + fn yuv_frame(y: u8, u: u8, v: u8, color: ColorInfo) -> VideoFrame { VideoFrame { width: 4, height: 2, data: PixelData::Yuv8 { planes: [Arc::new(vec![y; 8]), Arc::new(vec![u; 2]), Arc::new(vec![v; 2])], chroma: Chroma::C420, alpha: None }, color, par: (1, 1), - pts: filmcraft_time::Tick::ZERO, + pts: Tick::ZERO, } } #[test] fn limited_range_grey_and_white() { let op = AlphaOp::new(AlphaMode::Straight, [0.0; 3]); - let img = frame_to_image(&yuv_frame(235, 128, 128, filmcraft_color::ColorInfo::REC709), op); + let img = frame_to_image(&yuv_frame(235, 128, 128, ColorInfo::REC709), op); assert!(img.data.iter().all(|p| (p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5 && p[3] == 1.0)); - let img = frame_to_image(&yuv_frame(126, 128, 128, filmcraft_color::ColorInfo::REC709), op); + let img = frame_to_image(&yuv_frame(126, 128, 128, ColorInfo::REC709), op); assert!((img.data[0][0] - 110.0 / 219.0).abs() < 1e-5); } @@ -568,9 +571,9 @@ mod tests { chroma: Chroma::C420, alpha: None, }, - color: filmcraft_color::ColorInfo::REC709, + color: ColorInfo::REC709, par: (1, 1), - pts: filmcraft_time::Tick::ZERO, + pts: Tick::ZERO, } } @@ -588,7 +591,7 @@ mod tests { // More than half the size, odd sizes, other chroma layouts: convert the full frame. assert!(frame_to_image_scaled(&f, 49, 32).is_none()); assert!(frame_to_image_scaled(&smooth_420(95, 64), 40, 30).is_none()); - assert!(frame_to_image_scaled(&yuv_frame(100, 128, 128, filmcraft_color::ColorInfo::REC709), 2, 1).is_some()); + assert!(frame_to_image_scaled(&yuv_frame(100, 128, 128, ColorInfo::REC709), 2, 1).is_some()); let mut f444 = smooth_420(96, 64); if let PixelData::Yuv8 { chroma, .. } = &mut f444.data { *chroma = Chroma::C444; @@ -600,7 +603,7 @@ mod tests { fn bt709_red() { // 8-bit limited BT.709 red: Y 63, Cb 102, Cr 240 let op = AlphaOp::new(AlphaMode::Straight, [0.0; 3]); - let p = frame_to_image(&yuv_frame(63, 102, 240, filmcraft_color::ColorInfo::REC709), op).data[0]; + let p = frame_to_image(&yuv_frame(63, 102, 240, ColorInfo::REC709), op).data[0]; assert!(p[0] > 0.98 && p[1] < 0.02 && p[2] < 0.02, "{p:?}"); } @@ -631,14 +634,7 @@ mod tests { fn rgba8_levels_are_the_quantised_float_frame() { let (w, h) = (37usize, 18usize); let noise = |n: usize, seed: usize| Arc::new((0..n).map(|i| ((i * 7919 + seed * 104_729) % 256) as u8).collect::>()); - let frame = |data| VideoFrame { - width: w as u32, - height: h as u32, - data, - color: filmcraft_color::ColorInfo::REC709, - par: (1, 1), - pts: filmcraft_time::Tick::ZERO, - }; + let frame = |data| VideoFrame { width: w as u32, height: h as u32, data, color: ColorInfo::REC709, par: (1, 1), pts: Tick::ZERO }; let yuv = |chroma: Chroma, alpha: bool| { let n = w.div_ceil(1 << chroma.shifts().0) * h.div_ceil(1 << chroma.shifts().1); frame(PixelData::Yuv8 { planes: [noise(w * h, 1), noise(n, 2), noise(n, 3)], chroma, alpha: alpha.then(|| noise(w * h, 4)) }) @@ -675,9 +671,9 @@ mod tests { chroma: Chroma::C420, alpha: None, }, - color: filmcraft_color::ColorInfo::REC709, + color: ColorInfo::REC709, par: (1, 1), - pts: filmcraft_time::Tick::ZERO, + pts: Tick::ZERO, }; let op = AlphaOp::new(AlphaMode::Straight, [0.0; 3]); for _ in 0..3 { diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index d1a907821..5d3f376d0 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -84,7 +84,7 @@ impl From for MediaError { pub const STILL_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps", "vectorcraft"]; /// File extensions recognised as audio-only files. -pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS; +pub const AUDIO_EXTENSIONS: &[&str] = craft_media_source::AUDIO_EXTENSIONS; pub use effectcraft_project::VIDEO_EXTENSIONS; /// File extensions recognised as 3D models (Advanced 3D model layers). From fd2e7d7b6fa809c4cc29349e5aac5253ce5289be Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 18:30:06 +0800 Subject: [PATCH 342/393] fix(media): preserve leading MOV audio silence and saturate positions (#4005) * fix(media): honor MOV audio edit lists on first read * fix(media): preserve sign on ISO-BMFF edit-list position overflow --------- Co-authored-by: Dylan M. Taylor --- crates/media/src/craft_source.rs | 165 ++++++++++++++++++++++++++----- crates/media/tests/it/footage.rs | 70 +++++++++++++ 2 files changed, 211 insertions(+), 24 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index ae4aac50f..fb99282c5 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -291,6 +291,21 @@ impl ContainerFile { let decoded_pos = audio_starts.get(seek_idx).copied().unwrap_or(0); (seek_idx, decoded_pos) } + + fn audio_silent_prefix(&self, track_idx: usize, start: i64, frames: usize, sample_rate: u32) -> usize { + let Self::Isobmff(file) = self else { return 0 }; + let Some((leading_duration, media_time)) = file.tracks.get(track_idx).and_then(|track| unit_rate_media_edit(&track.edits)) else { + return 0; + }; + if leading_duration == 0 || media_time == 0 || file.timescale == 0 { + return 0; + } + + // The net packet offset includes the trim and can put decoder preroll inside + // the empty edit. Use the empty edit's duration on the output clock instead. + let first_presented = (u128::from(leading_duration) * u128::from(sample_rate)).div_ceil(u128::from(file.timescale)) as i128; + usize::try_from((first_presented - i128::from(start)).max(0)).unwrap_or(usize::MAX).min(frames) + } } /// Where the container puts one audio packet, for [`contiguous_starts`]. @@ -468,12 +483,7 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code ContainerFile::Isobmff(f) => { let Some(track) = f.tracks.get(track_idx) else { return AudioStarts::complete(Vec::new()) }; let ts = i128::from(track.timescale.max(1)); - let stamps: Vec = (0..track.samples.len()) - .map(|i| { - let pts = track.presentation_pts(i).unwrap_or(0); - i64::try_from(i128::from(pts) * rate / ts).unwrap_or(0) - }) - .collect(); + let stamps: Vec = (0..track.samples.len()).map(|i| isobmff_audio_position(track, i, native_rate)).collect(); let unit = i64::try_from((rate + ts - 1) / ts).unwrap_or(i64::MAX); if codec == CodecId::Opus { return AudioStarts::opus(stamps, unit.saturating_mul(2).saturating_add(1)); @@ -559,6 +569,14 @@ fn audio_frames_from_ns(ns: i128, rate: u32) -> i128 { (ns * i128::from(rate)) / 1_000_000_000 } +/// The decoded buffer starts on the presentation timeline, including negative trimmed samples. +/// Using the same signed position on open and seek preserves edit-list trim and leading silence. +fn isobmff_audio_position(track: &isobmff::Track, sample_idx: usize, native_rate: u32) -> i64 { + let pts = track.presentation_pts(sample_idx).unwrap_or(0); + let scaled = (i128::from(pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1)); + i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX }) +} + fn open_audio_tracks(container: &ContainerFile, source: &dyn ByteSource, candidates: I) -> Option<(Vec, Vec)> where I: IntoIterator, @@ -670,17 +688,24 @@ fn clean_aperture_region(aperture: isobmff::CleanAperture, (width, height): (u32 (!r.is_full(width as usize, height as usize)).then_some(r) } -/// A single unit-rate media span, optionally preceded by one empty span. A -/// scalar EDL origin cannot describe dwell, disjoint edits or respeeding. -fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Option<(i64, i64)> { +/// A single unit-rate media span, optionally preceded by one empty span. +fn unit_rate_media_edit(edits: &[isobmff::Edit]) -> Option<(u64, i64)> { const UNIT_RATE: i32 = 0x0001_0000; - let (leading_duration, media) = match track.edits.as_slice() { - [] => return (track.edit_offset == 0).then_some((0, 0)), + let (leading_duration, media) = match edits { [media] => (0, media), [empty, media] if empty.media_time == -1 && empty.segment_duration > 0 && empty.media_rate == UNIT_RATE => (empty.segment_duration, media), _ => return None, }; - if media.media_time < 0 || media.segment_duration == 0 || media.media_rate != UNIT_RATE || movie_timescale == 0 || track.timescale == 0 { + (media.media_time >= 0 && media.segment_duration != 0 && media.media_rate == UNIT_RATE).then_some((leading_duration, media.media_time)) +} + +/// A scalar EDL origin cannot describe dwell, disjoint edits or respeeding. +fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Option<(i64, i64)> { + if track.edits.is_empty() { + return (track.edit_offset == 0).then_some((0, 0)); + } + let (leading_duration, media_time) = unit_rate_media_edit(&track.edits)?; + if movie_timescale == 0 || track.timescale == 0 { return None; } // Check the raw movie-to-media conversion before the demuxer's rounded @@ -690,8 +715,8 @@ fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Opti if lead % movie_clock != 0 { return None; } - let offset = i64::try_from(lead / movie_clock - i128::from(media.media_time)).ok()?; - (offset == track.edit_offset).then_some((media.media_time, offset)) + let offset = i64::try_from(lead / movie_clock - i128::from(media_time)).ok()?; + (offset == track.edit_offset).then_some((media_time, offset)) } /// The EDL origin is the timecode at presentation time zero, not the raw @@ -1389,12 +1414,15 @@ impl MediaSource for CraftMediaSource { 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 silent_frames = self.file.audio_silent_prefix(entry.track_idx, start, frames, sample_rate); + let audible_frames = frames - silent_frames; + if audible_frames == 0 { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); } + let audible_start = i64::try_from(i128::from(start) + silent_frames as i128).unwrap_or(i64::MAX); let native_rate = entry.native_rate; - let (native_start, native_frames) = native_audio_window(start, frames, native_rate, sample_rate); + let (native_start, native_frames) = native_audio_window(audible_start, audible_frames, native_rate, sample_rate); let decoded = match &entry.backend { AudioBackend::Decoder { seek_preroll_samples, state: state_mutex } => { @@ -1441,11 +1469,15 @@ impl MediaSource for CraftMediaSource { } }; - if sample_rate == native_rate { - return Ok(AudioBuffer { sample_rate, channels: decoded }); + let mut channels = + if sample_rate == native_rate { decoded } else { resample_audio(&decoded, channels_count, native_rate, sample_rate, audible_frames) }; + if silent_frames > 0 { + for channel in &mut channels { + channel.resize(frames, 0.0); + channel.rotate_right(silent_frames); + } } - - Ok(AudioBuffer { sample_rate, channels: resample_audio(&decoded, channels_count, native_rate, sample_rate, frames) }) + Ok(AudioBuffer { sample_rate, channels }) } } @@ -1565,7 +1597,7 @@ fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_coun for i in 0..frames { let pos = start.saturating_add(i as i64); if pos >= *decoded_pos { - let off = (pos - *decoded_pos) as usize; + let off = usize::try_from(pos.saturating_sub(*decoded_pos)).unwrap_or(usize::MAX); if off < avail { for (c, out_ch) in out.iter_mut().enumerate() { out_ch[i] = buf[c][off]; @@ -1574,7 +1606,7 @@ fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_coun } } let end = start.saturating_add(frames as i64); - let drop_to = (end - *decoded_pos).max(0) as usize; + let drop_to = usize::try_from(end.saturating_sub(*decoded_pos).max(0)).unwrap_or(usize::MAX); let trim = drop_to.min(avail); if trim > 0 { for ch in buf { @@ -1671,7 +1703,7 @@ fn decode_audio_range( let buf_len = state.buf.first().map_or(0, Vec::len) as i64; let buf_end = state.decoded_pos.saturating_add(buf_len); let moves_backward = start < state.decoded_pos; - if moves_backward || start > buf_end + i64::from(native_rate) * 2 { + if moves_backward || start > buf_end.saturating_add(i64::from(native_rate) * 2) { let target = start.saturating_sub(seek_preroll_samples).max(0); let (seek_idx, decoded_pos) = if moves_backward && state.next_sample == 0 && state.audio_starts.seek_proves_first_packet(target) { (0, state.decoded_pos) @@ -2396,6 +2428,91 @@ mod tests { assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}"); } + /// Generated AAC permits unequal track/sample clocks, unlike the MOV writer's PCM tracks. + #[test] + fn mov_aac_edit_positions_saturate_with_unequal_clocks() { + use craft_audio::aac::{Encoder, EncoderConfig}; + use isobmff::{Brand, Edit, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + const RATE: u32 = 48_000; + let mut encoder = Encoder::new(EncoderConfig::cbr(RATE, 1, 64_000)).unwrap(); + let tone: Vec = (0..2048).map(|i| (i as f32 * 0.13).sin() * 0.25).collect(); + let mut packets = encoder.encode(&[&tone]); + packets.extend(encoder.flush()); + assert!(!packets.is_empty()); + for (offset, expected) in [(10i64, 480i64), (-10, -480), (i64::MAX / 2, i64::MAX), (-i64::MAX / 2, i64::MIN)] { + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let mut config = TrackConfig::new(SampleEntry::aac(encoder.audio_specific_config(), 1, RATE), 1_000); + if offset > 0 { + config.edits.push(Edit { segment_duration: offset as u64, media_time: -1, media_rate: 0x0001_0000 }); + } + config.edits.push(Edit { segment_duration: 100, media_time: (-offset).max(0), media_rate: 0x0001_0000 }); + let track_idx = writer.add_track(config).expect("AAC accepts unequal media and sample clocks"); + for packet in &packets { + writer.write_sample(track_idx, WriteSample { data: packet, duration: 21, composition_offset: 0, is_sync: true }).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let mov = isobmff::open(bytes.as_slice()).unwrap(); + let track = &mov.tracks[0]; + assert_eq!((track.timescale, track.edit_offset, track.presentation_pts(0)), (1_000, offset, Some(offset))); + let params = track.codec_params(); + assert_eq!((params.codec, params.sample_rate), (CodecId::Aac, Some(RATE))); + // Check the conversion itself: a decode error substituted with silence cannot pass. + assert_eq!(isobmff_audio_position(track, 0, RATE), expected); + let file = ContainerFile::Isobmff(mov); + let (mut tracks, infos) = open_audio_tracks(&file, &bytes, [(0, packets.len(), params, 0)]).expect("shared AAC source"); + assert_eq!(infos[0].sample_rate, RATE); + let (preroll, state) = tracks[0].decoder_parts(); + assert_eq!(state.audio_starts.start(&file, 0, 0), Some(expected)); + for start in [0, 6_000, 0] { + let decoded = decode_audio_range(&file, &bytes, 0, RATE, 1, preroll, state, start, 64).expect("the result-returning shared read must succeed"); + assert_eq!(decoded[0].len(), 64); + if expected == i64::MAX || expected == i64::MIN { + assert!(decoded[0].iter().all(|&v| v == 0.0), "out-of-range edits have no audible samples at {start}"); + } + } + } + } + + /// Original PCM generated in memory to exercise an empty edit followed by a trim. + #[test] + fn mov_pcm_trim_after_empty_edit_preserves_leading_silence() { + use isobmff::{Brand, Edit, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + const RATE: u32 = 48_000; + const DELAY_MS: u64 = 100; + const DELAY: i64 = 4_800; + let samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); + for trim in [2_400i64, 4_800, 9_600] { + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 1, sample_rate: f64::from(RATE) }; + let mut config = TrackConfig::new(SampleEntry::pcm(pcm), RATE); + config.edits = vec![ + Edit { segment_duration: DELAY_MS, media_time: -1, media_rate: 0x0001_0000 }, + Edit { segment_duration: 40, media_time: trim, media_rate: 0x0001_0000 }, + ]; + let track = writer.add_track(config).unwrap(); + for chunk in samples.chunks(256) { + let data: Vec = chunk.iter().flat_map(|sample| sample.to_le_bytes()).collect(); + writer.write_sample(track, WriteSample { data: &data, duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let file = isobmff::open(bytes.as_slice()).unwrap(); + assert_eq!(file.timescale, 1_000); + assert_eq!(file.tracks[0].edit_offset, DELAY - trim); + + let source = open_bytes("edited-pcm.mov", bytes.into()).expect("shared MOV route").unwrap(); + let sample = |index: i64| f32::from(samples[index as usize]) / 32_768.0; + let expected = [0.0, 0.0, sample(trim), sample(trim + 1)]; + let read = |start, frames, rate| source.audio(start, frames, rate).expect("direct shared PCM read").channels.remove(0); + assert_eq!(read(DELAY - 2, 4, RATE), expected, "first read, trim {trim}"); + assert_eq!(read(0, DELAY as usize, RATE), vec![0.0; DELAY as usize], "backward seek, trim {trim}"); + assert_eq!(read(DELAY, 2, RATE), expected[2..], "read from first presented sample, trim {trim}"); + assert_eq!(read(DELAY * 2 - 4, 5, RATE * 2), [0.0, 0.0, 0.0, 0.0, sample(trim)], "resampled read, trim {trim}"); + assert_eq!(read(4_408, 3, 44_100), [0.0, 0.0, sample(trim)], "nonintegral resampling ratio, trim {trim}"); + } + } + #[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 }); diff --git a/crates/media/tests/it/footage.rs b/crates/media/tests/it/footage.rs index 2d6af707c..1b03817ab 100644 --- a/crates/media/tests/it/footage.rs +++ b/crates/media/tests/it/footage.rs @@ -505,6 +505,76 @@ fn prores_alpha_uses_coded_frame_not_mov_depth() { } } +/// Generated PCM ramps expose edit-list timing without an external encoder or oracle. +#[test] +fn mov_pcm_edit_lists_preserve_first_read_and_seek_timing() { + use craft_media::isobmff::{self, Brand, Edit, FourCc, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + const RATE: u32 = 48_000; + const AUDIO_FRAMES: usize = 12_000; + let samples: Vec<[i16; 2]> = (0..AUDIO_FRAMES).map(|i| [1000 + (i % 257) as i16 * 32, -2000 - (i % 193) as i16 * 16]).collect(); + let profile = Profile::Hq; + let mut encoder = Encoder::new(profile, 16, 16); + let packet = encoder.encode(&Frame::new(16, 16, ChromaFormat::Yuv422, 10, false).unwrap()).unwrap(); + // The extreme edits also guard signed buffer arithmetic on the first audio request. + for offset in [0i64, 480, -480, -i64::MAX, i64::MAX - i64::MAX % 48] { + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let video = writer.add_track(TrackConfig::new(SampleEntry::prores(FourCc(profile.fourcc()), 16, 16), 24)).unwrap(); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: f64::from(RATE) }; + let mut audio_config = TrackConfig::new(SampleEntry::pcm(pcm), RATE); + if offset > 0 { + audio_config.edits.push(Edit { segment_duration: (offset / 48) as u64, media_time: -1, media_rate: 0x0001_0000 }); + } + if offset != 0 { + audio_config.edits.push(Edit { segment_duration: 240, media_time: (-offset).max(0), media_rate: 0x0001_0000 }); + } + let audio = writer.add_track(audio_config).unwrap(); + writer.write_sample(video, WriteSample { data: &packet, duration: 24, composition_offset: 0, is_sync: true }).unwrap(); + for chunk in samples.chunks(256) { + let data: Vec = chunk.iter().flat_map(|frame| frame.iter().flat_map(|s| s.to_le_bytes())).collect(); + writer.write_sample(audio, WriteSample { data: &data, duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap(); + } + let bytes: Arc<[u8]> = writer.finish().unwrap().into_inner().into(); + let mov = isobmff::open(bytes.as_ref()).unwrap(); + let track = mov.tracks.iter().find(|t| t.kind == isobmff::TrackKind::Audio).unwrap(); + assert_eq!(track.edit_offset, offset, "fixture must carry the requested audio edit"); + assert_eq!(track.presentation_pts(0), Some(offset)); + + let name = format!("pcm-edit-{offset}.mov"); + let footage = probe_bytes(&name, bytes.clone()).expect("probe generated MOV"); + assert_eq!(footage.codec, "ProRes", "must exercise the shared importer"); + assert!(footage.has_audio); + let pool = MediaPool::new(); + pool.add_bytes(&name, bytes); + let check = |start: usize, count: usize| { + let got = pool.audio_samples(&footage, Tick::from_units(start as i64, i64::from(RATE)), count, RATE); + assert_eq!(got.len(), count * 2); + for (i, frame) in got.as_chunks::<2>().0.iter().enumerate() { + let source = i64::try_from(start + i).unwrap().saturating_sub(offset); + let expected = usize::try_from(source).ok().and_then(|p| samples.get(p)).copied().unwrap_or([0, 0]); + for c in 0..2 { + assert_eq!(frame[c], f32::from(expected[c]) / 32768.0, "edit {offset}, request {start}, frame {i}, channel {c}"); + } + } + got + }; + let first = check(0, 2048); + let mut sequential = Vec::new(); + let mut start = 0; + while start < 2048 { + let count = 127.min(2048 - start); + sequential.extend(check(start, count)); + start += count; + } + assert_eq!(sequential, first, "edit {offset}: chunking must preserve samples"); + for start in [3000, 100, 6000, 0, 480, 700] { + check(start, 600); + } + assert_eq!(check(0, 2048), first, "edit {offset}: reopening the decode window must preserve samples"); + } +} + /// A synthetic asymmetrical aperture and rotation must determine what the shared importer shows. #[test] fn mov_renders_clean_aperture_before_display_rotation() { From 0ecc246f05e29d92885a50f7e3783c627fca7f2a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:50:20 +0700 Subject: [PATCH 343/393] media: preserve standalone audio resampling phase across seeks (#4017) Co-authored-by: Codex --- crates/media/src/craft_source.rs | 76 ++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index fb99282c5..a6a7bc37d 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1532,17 +1532,61 @@ impl MediaSource for StandaloneAudioSource { return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); } let native_rate = self.native_rate; - let (native_start, native_frames) = native_audio_window(start, frames, native_rate, sample_rate); + let (native_start, native_frames, phase) = if sample_rate == native_rate { + (start, frames, 0) + } else { + let scaled = i128::from(start) * i128::from(native_rate); + let divisor = i128::from(sample_rate); + let Ok(origin) = i64::try_from(scaled.div_euclid(divisor)) else { + // An unrepresentable source position cannot address this stream. + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + }; + // Reuse the existing window size, but not its truncating start calculation. + (origin, native_audio_window(0, frames, native_rate, sample_rate).1, scaled.rem_euclid(divisor) as u64) + }; let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let decoded = decode_standalone_range(native_rate, channels_count, &mut state, native_start, native_frames)?; if sample_rate == native_rate { return Ok(AudioBuffer { sample_rate, channels: decoded }); } - Ok(AudioBuffer { sample_rate, channels: resample_audio(&decoded, channels_count, native_rate, sample_rate, frames) }) + // Negative output positions are silence, not interpolation into frame zero. + let first_output = if start < 0 { usize::try_from(start.unsigned_abs()).unwrap_or(frames).min(frames) } else { 0 }; + Ok(AudioBuffer { sample_rate, channels: resample_standalone_audio(&decoded, native_rate, sample_rate, frames, phase, first_output) }) } } +/// Step the fractional input position as an exact integer quotient and remainder; +/// rounding happens only when interpolating a sample, independent of the window. +#[cfg(any(unix, windows))] +fn resample_standalone_audio(decoded: &[Vec], native_rate: u32, sample_rate: u32, frames: usize, phase: u64, first_output: usize) -> Vec> { + let mut out = vec![vec![0.0; frames]; decoded.len()]; + let divisor = u64::from(sample_rate); + let first = first_output as u128 * u128::from(native_rate) + u128::from(phase); + let Ok(first_index) = usize::try_from(first / u128::from(divisor)) else { return out }; + let first_remainder = (first % u128::from(divisor)) as u64; + let whole_step = (native_rate / sample_rate) as usize; + let remainder_step = u64::from(native_rate % sample_rate); + let inverse_rate = f64::from(sample_rate).recip(); + for (samples, dst) in decoded.iter().zip(&mut out) { + let (mut index, mut remainder) = (first_index, first_remainder); + for sample in dst.iter_mut().skip(first_output) { + let Some(&a) = samples.get(index) else { break }; + let b = samples.get(index + 1).copied().unwrap_or(a); + let t = (remainder as f64 * inverse_rate) as f32; + *sample = a + (b - a) * t; + remainder += remainder_step; + let carry = remainder >= divisor; + if carry { + remainder -= divisor; + } + let Some(next) = index.checked_add(whole_step + carry as usize) else { break }; + index = next; + } + } + out +} + #[cfg(any(unix, windows))] fn decode_standalone_range(native_rate: u32, channels_count: usize, state: &mut StandaloneAudioState, start: i64, frames: usize) -> Result>> { let end = start.saturating_add(frames as i64); @@ -2854,7 +2898,8 @@ mod tests { wav.extend_from_slice(&s.to_le_bytes()); } - let src = open_bytes("tone.wav", Arc::from(wav)).expect("recognized").expect("opened"); + let wav = Arc::<[u8]>::from(wav); + let src = open_bytes("tone.wav", wav.clone()).expect("recognized").expect("opened"); let info = src.info(); assert_eq!(info.container, "wav"); assert_eq!(info.kind, MediaKind::AudioOnly); @@ -2872,6 +2917,31 @@ mod tests { let resampled = src.audio(0, 256, 44_100).expect("resampled"); assert_eq!(resampled.sample_rate, 44_100); assert_eq!(resampled.channels[0].len(), 256); + + let cold = open_bytes("tone.wav", wav).expect("recognized").expect("opened"); + let alone = cold.audio(1, 1, 44_100).expect("single output frame"); + // Output frame 1 is at input frame 160/147. The left channel's + // input frames 1 and 2 contain -7486 and -6972 in signed 16-bit PCM. + let expected = (-7486.0 + (13.0 / 147.0) * 514.0) / 32768.0; + assert!((alone.channels[0][0] - expected).abs() < 1e-7, "absolute fractional phase"); + for (single, block) in alone.channels.iter().zip(&resampled.channels) { + assert_eq!(single[0], block[1], "reading a frame alone must match a longer block"); + } + let pre_roll = cold.audio(-1, 3, 44_100).expect("negative output window"); + for (shifted, block) in pre_roll.channels.iter().zip(&resampled.channels) { + assert_eq!(shifted[0], 0.0, "silence before frame zero"); + assert_eq!(&shifted[1..], &block[..2], "crossing frame zero must preserve phase"); + } + // Frame 3675 is exactly native frame 4000, where the left ramp is zero. + let crossing = cold.audio(3670, 6, 44_100).expect("cross a zero sample"); + let zero = cold.audio(3675, 1, 44_100).expect("read the zero sample alone"); + assert_eq!(crossing.channels[0][5], 0.0, "a fractional start must not leak into an integral sample"); + assert_eq!(crossing.channels[0][5], zero.channels[0][0]); + + let after_end = cold.audio(4410, 2, 44_100).expect("after EOF"); + assert!(after_end.channels.iter().flatten().all(|&sample| sample == 0.0)); + let out_of_range = cold.audio(i64::MAX / 2, 1, 1).expect("unrepresentable source origin"); + assert!(out_of_range.channels.iter().flatten().all(|&sample| sample == 0.0), "an unreachable origin must not replay frame zero"); } /// 1024-sample frames at 48 kHz stamped to the nearest millisecond, then back in samples. From bf8529941087809f57a705413618adf0e3d58522 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:34:46 +0700 Subject: [PATCH 344/393] media: clamp MXF picture duration and seeking to indexed frames (#4021) * Use the same indexed MXF picture window for duration and seek * Apply hosted rustfmt to MXF window test --------- Co-authored-by: Codex --- crates/media/src/craft_source.rs | 41 ++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index a6a7bc37d..d53dc927b 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -210,11 +210,12 @@ impl ContainerFile { } ContainerFile::Mxf(f) => { let track = f.tracks.get(track_idx)?; - let offset = track.first_edit_unit(); + let (offset, presented_len) = mxf_picture_window(track); + if presented_len == 0 { + return None; + } let d = tick_to_rational_units(time, i64::from(track.edit_rate.num), i64::from(track.edit_rate.den)); - let presented_len = track.duration.unwrap_or_else(|| i64::try_from(track.display_order.len()).unwrap_or(0).saturating_sub(offset).max(0)); - let max_rel = presented_len.saturating_sub(1).max(0); - let pos = offset.saturating_add(d.clamp(0, max_rel)); + let pos = offset.saturating_add(d.clamp(0, presented_len - 1)); let idx = track.sample_at(pos)?; Some((idx, track.samples[idx].pts)) } @@ -1039,8 +1040,19 @@ fn mxf_start_timecode(tc: mxf::Timecode, rate: Option) -> i64 { i64::try_from(converted).unwrap_or(tc.start) } +/// Material-package picture span, limited to indexed display pictures after the origin. +fn mxf_picture_window(track: &mxf::EssenceTrack) -> (i64, i64) { + let start = track.first_edit_unit(); + let available = i64::try_from(track.display_order.len()).unwrap_or(i64::MAX).saturating_sub(start).max(0); + (start, track.duration.unwrap_or(available).clamp(0, available)) +} + fn open_mxf(name: &str, source: SharedBytes) -> Option> { let file = mxf::open(&*source).ok()?; + open_parsed_mxf(name, source, file) +} + +fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Option> { let video_idx = file.tracks.iter().position(|t| t.kind == mxf::TrackKind::Picture && !t.samples.is_empty() && t.edit_rate.is_valid()); let sound_indices: Vec = file.tracks.iter().enumerate().filter(|(_, t)| t.kind == mxf::TrackKind::Sound && !t.chunks.is_empty()).map(|(idx, _)| idx).collect(); @@ -1078,7 +1090,7 @@ fn open_mxf(name: &str, source: SharedBytes) -> Option> { let er = video_track.edit_rate; let fps = f64::from(er.num) / f64::from(er.den.max(1)); let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(er.num), i64::from(er.den))); - let dur_units = video_track.duration.unwrap_or_else(|| i64::try_from(video_track.display_order.len()).unwrap_or(0)); + let (_, dur_units) = mxf_picture_window(video_track); let duration = Tick::from_units(dur_units.saturating_mul(i64::from(er.den)), i64::from(er.num.max(1))); let has_alpha = video_track.picture.as_ref().is_some_and(|p| p.alpha_depth > 0); let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) { @@ -2861,6 +2873,25 @@ mod tests { let (win_start, win_len) = mxf_sound_window(&file.tracks[1]); assert_eq!((win_start, win_len), (1920, 1920)); + // Reuse the demuxed writer fixture and vary just its material-picture metadata. + // The writer itself authors neither an overclaimed nor an absent duration here. + assert_eq!(file.tracks[0].display_order, [0, 1]); + let one_frame = Tick::from_units(40, 1_000); + let beyond = Tick::from_units(80, 1_000); + for (origin, declared, expected_duration, expected_target) in + [(1, Some(2), one_frame, Some((1, 1))), (1, None, one_frame, Some((1, 1))), (1, Some(0), Tick::ZERO, None), (2, Some(2), Tick::ZERO, None)] + { + let mut edited = file.clone(); + edited.tracks[0].origin = origin; + edited.tracks[0].duration = declared; + assert_eq!(edited.tracks[0].first_edit_unit(), origin); + let source = open_parsed_mxf("op1a.mxf", mxf_bytes.clone(), edited.clone()).expect("shared MXF").expect("open parsed"); + assert_eq!(source.info().duration, expected_duration, "origin {origin}, duration {declared:?}"); + let container = ContainerFile::Mxf(Box::new(edited)); + assert_eq!(container.target_sample(0, Tick::ZERO), expected_target); + assert_eq!(container.target_sample(0, beyond), expected_target); + } + let container = ContainerFile::Mxf(Box::new(file)); assert_eq!(container.sample_count(0), 2); assert_eq!(container.target_sample(0, Tick::ZERO), Some((1, 1))); From 917a68783aa3e7003eada07035a3d5661510852b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:31:33 +0700 Subject: [PATCH 345/393] Preserve MXF descriptor pixel aspect in the shared reader (#4022) Co-authored-by: Codex --- crates/media/src/craft_source.rs | 74 +++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index d53dc927b..7acb6058f 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1047,6 +1047,25 @@ fn mxf_picture_window(track: &mxf::EssenceTrack) -> (i64, i64) { (start, track.duration.unwrap_or(available).clamp(0, available)) } +/// Pixel aspect is the descriptor's display aspect divided by the frame's raster aspect. +fn mxf_picture_par(dar: mxf::Rational, width: u32, height: u32) -> (u32, u32) { + const SQUARE: (u32, u32) = (1, 1); + if !dar.is_valid() || width == 0 || height == 0 { + return SQUARE; + } + // Positive i32 by u32 fits u64; reduce before narrowing to the frame's u32 pair. + let num = u64::from(dar.num as u32) * u64::from(height); + let den = u64::from(dar.den as u32) * u64::from(width); + let (mut a, mut b) = (num, den); + while b != 0 { + (a, b) = (b, a % b); + } + match (u32::try_from(num / a), u32::try_from(den / a)) { + (Ok(num), Ok(den)) => (num, den), + _ => SQUARE, + } +} + fn open_mxf(name: &str, source: SharedBytes) -> Option> { let file = mxf::open(&*source).ok()?; open_parsed_mxf(name, source, file) @@ -1087,6 +1106,7 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio return None; } let (width, height) = video_track.picture.as_ref().map_or((0, 0), |p| (p.frame_width(), p.frame_height())); + let par = video_track.picture.as_ref().map_or((1, 1), |p| mxf_picture_par(p.aspect_ratio, width, height)); let er = video_track.edit_rate; let fps = f64::from(er.num) / f64::from(er.den.max(1)); let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(er.num), i64::from(er.den))); @@ -1101,7 +1121,7 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio width, height, frame_rate, - par: (1, 1), + par, codec: video_params.codec.name().to_string(), pixel_format: String::new(), color: ColorInfo::REC709, @@ -1110,7 +1130,7 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio hdr: None, }; let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); - (Some(v_info), Some(v_state), FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, duration) + (Some(v_info), Some(v_state), FramePresentation { container_color: None, par, rotation: 0, aperture: None }, duration) } else { let duration = audio_tracks .iter() @@ -2765,6 +2785,56 @@ mod tests { } } + #[test] + fn mxf_descriptor_aspect_reaches_shared_probe_and_frame() { + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let frame = Frame::new(16, 12, ChromaFormat::Yuv422, 10, false).expect("ProRes frame"); + let packet = Encoder::new(Profile::Hq, 16, 12).encode(&frame).expect("encode ProRes"); + for (dar, expected) in [(mxf::Rational::new(16, 9), (4, 3)), (mxf::Rational::new(0, 0), (1, 1))] { + let ids = mxf::write::PackageIds::from_seed("eff-mxf-par", "op1a"); + let mut cfg = mxf::write::WriterConfig::new(mxf::write::Pattern::Op1a, mxf::Rational::new(25, 1), ids); + let mut picture = mxf::write::PictureDesc::new(mxf::write::PictureCoding::ProRes { profile: 4 }, 16, 12); + picture.aspect = dar; + cfg.picture = Some(picture); + let mut writer = mxf::write::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).expect("writer"); + writer.push_picture(&packet, mxf::write::FrameInfo::intra()).expect("picture"); + let bytes: Arc<[u8]> = writer.finish().expect("finish").into_inner().into(); + + let file = mxf::open(bytes.as_ref()).expect("demux fixture"); + assert_eq!(file.tracks[0].picture.as_ref().expect("picture descriptor").aspect_ratio, dar); + let footage = crate::probe::probe_bytes("aspect.mxf", bytes.clone()).expect("public probe"); + // The FilmCraft backend labels the same essence "Apple ProRes 422 HQ". + assert_eq!(footage.codec, "ProRes", "must use the shared MXF route"); + assert_eq!(footage.pixel_aspect, f64::from(expected.0) / f64::from(expected.1)); + + let source = open_bytes("aspect.mxf", bytes).expect("recognized MXF").expect("shared MXF"); + assert_eq!(source.info().video.as_ref().expect("video").par, expected); + let decoded = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode frame"); + assert_eq!(decoded.par, expected); + } + } + + #[test] + fn mxf_descriptor_aspect_is_bounded_and_yields_to_decoder_sar() { + let wide = mxf::Rational::new(i32::MAX, i32::MAX); + assert_eq!(mxf_picture_par(wide, u32::MAX, u32::MAX), (1, 1)); + assert_eq!(mxf_picture_par(wide, 12, 16), (4, 3)); + assert_eq!(mxf_picture_par(mxf::Rational::new(i32::MAX, 1), 1, u32::MAX), (1, 1)); + assert_eq!(mxf_picture_par(mxf::Rational::new(16, 9), 0, 12), (1, 1)); + + let par = mxf_picture_par(mxf::Rational::new(16, 9), 16, 12); + let presentation = FramePresentation { container_color: None, par, rotation: 0, aperture: None }; + for (sar, expected) in [(None, (4, 3)), (Some((0, 2)), (4, 3)), (Some((2, 1)), (2, 1))] { + let y = Plane::packed(2, 2, 8, Samples::U8(vec![1, 2, 3, 4])).expect("luma"); + let cb = Plane::packed(1, 1, 8, Samples::U8(vec![128])).expect("chroma"); + let cr = Plane::packed(1, 1, 8, Samples::U8(vec![128])).expect("chroma"); + let mut frame = DecodedVideoFrame::new(2, 2, ColorFamily::YCbCr, Subsampling::S420, vec![y, cb, cr], None).expect("decoded frame"); + frame.sar = sar; + assert_eq!(to_craft_frame(frame, presentation, Tick::ZERO).expect("converted").par, expected); + } + } + #[test] fn mxf_sniffer_and_rational_units() { assert!(looks_like_mxf(&[0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02])); From 5f435d45ef90145ad34470918a68a381b58f963b Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sat, 21 Nov 2026 21:24:47 +0800 Subject: [PATCH 346/393] fix(media): silence reads past the MOV audio edit end (#4024) * Stop presenting MOV audio at the edit end * Credit Terra854 in EffectCraft About --- contributors/people.toml | 3 + crates/media/src/craft_source.rs | 123 +++++++++++++++++++++---------- 2 files changed, 89 insertions(+), 37 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 4f77ce8d1..eb363be5d 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -143,3 +143,6 @@ sync_github_name = true real_name = "Nicola Falcier" display_name = "Nicola Falcier" sync_github_name = false + +[people.Terra854] +display_name = "Terra854" diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 7acb6058f..7307a8323 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -293,19 +293,23 @@ impl ContainerFile { (seek_idx, decoded_pos) } - fn audio_silent_prefix(&self, track_idx: usize, start: i64, frames: usize, sample_rate: u32) -> usize { - let Self::Isobmff(file) = self else { return 0 }; - let Some((leading_duration, media_time)) = file.tracks.get(track_idx).and_then(|track| unit_rate_media_edit(&track.edits)) else { - return 0; + fn audio_edit_range(&self, track_idx: usize, start: i64, frames: usize, sample_rate: u32) -> std::ops::Range { + let Self::Isobmff(file) = self else { return 0..frames }; + let Some((leading_duration, media)) = file.tracks.get(track_idx).and_then(|track| unit_rate_media_edit(&track.edits)) else { + return 0..frames; }; - if leading_duration == 0 || media_time == 0 || file.timescale == 0 { - return 0; + if file.timescale == 0 { + return 0..frames; } - // The net packet offset includes the trim and can put decoder preroll inside - // the empty edit. Use the empty edit's duration on the output clock instead. - let first_presented = (u128::from(leading_duration) * u128::from(sample_rate)).div_ceil(u128::from(file.timescale)) as i128; - usize::try_from((first_presented - i128::from(start)).max(0)).unwrap_or(usize::MAX).min(frames) + // Packet positions include preroll. The edit's movie-clock boundaries + // determine which samples are presented, with the end excluded. + let offset = |ticks: u128| { + let frame = (ticks * u128::from(sample_rate)).div_ceil(u128::from(file.timescale)) as i128; + usize::try_from((frame - i128::from(start)).max(0)).unwrap_or(usize::MAX).min(frames) + }; + let leading = u128::from(leading_duration); + offset(leading)..offset(leading + u128::from(media.segment_duration)) } } @@ -690,14 +694,14 @@ fn clean_aperture_region(aperture: isobmff::CleanAperture, (width, height): (u32 } /// A single unit-rate media span, optionally preceded by one empty span. -fn unit_rate_media_edit(edits: &[isobmff::Edit]) -> Option<(u64, i64)> { +fn unit_rate_media_edit(edits: &[isobmff::Edit]) -> Option<(u64, &isobmff::Edit)> { const UNIT_RATE: i32 = 0x0001_0000; let (leading_duration, media) = match edits { [media] => (0, media), [empty, media] if empty.media_time == -1 && empty.segment_duration > 0 && empty.media_rate == UNIT_RATE => (empty.segment_duration, media), _ => return None, }; - (media.media_time >= 0 && media.segment_duration != 0 && media.media_rate == UNIT_RATE).then_some((leading_duration, media.media_time)) + (media.media_time >= 0 && media.segment_duration != 0 && media.media_rate == UNIT_RATE).then_some((leading_duration, media)) } /// A scalar EDL origin cannot describe dwell, disjoint edits or respeeding. @@ -705,7 +709,7 @@ fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Opti if track.edits.is_empty() { return (track.edit_offset == 0).then_some((0, 0)); } - let (leading_duration, media_time) = unit_rate_media_edit(&track.edits)?; + let (leading_duration, media) = unit_rate_media_edit(&track.edits)?; if movie_timescale == 0 || track.timescale == 0 { return None; } @@ -716,8 +720,8 @@ fn continuous_edit_mapping(track: &isobmff::Track, movie_timescale: u32) -> Opti if lead % movie_clock != 0 { return None; } - let offset = i64::try_from(lead / movie_clock - i128::from(media_time)).ok()?; - (offset == track.edit_offset).then_some((media_time, offset)) + let offset = i64::try_from(lead / movie_clock - i128::from(media.media_time)).ok()?; + (offset == track.edit_offset).then_some((media.media_time, offset)) } /// The EDL origin is the timecode at presentation time zero, not the raw @@ -1446,15 +1450,20 @@ impl MediaSource for CraftMediaSource { 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); - let silent_frames = self.file.audio_silent_prefix(entry.track_idx, start, frames, sample_rate); - let audible_frames = frames - silent_frames; + let edit_range = self.file.audio_edit_range(entry.track_idx, start, frames, sample_rate); + let audible_frames = edit_range.len(); if audible_frames == 0 { return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); } - let audible_start = i64::try_from(i128::from(start) + silent_frames as i128).unwrap_or(i64::MAX); + let audible_start = i64::try_from(i128::from(start) + edit_range.start as i128).unwrap_or(i64::MAX); let native_rate = entry.native_rate; - let (native_start, native_frames) = native_audio_window(audible_start, audible_frames, native_rate, sample_rate); + let (native_start, mut native_frames) = native_audio_window(audible_start, audible_frames, native_rate, sample_rate); + if native_rate != sample_rate { + // The resampler asks for lookahead. Do not interpolate with samples + // that are stored in the track but lie beyond the edit. + native_frames = self.file.audio_edit_range(entry.track_idx, native_start, native_frames, native_rate).end; + } let decoded = match &entry.backend { AudioBackend::Decoder { seek_preroll_samples, state: state_mutex } => { @@ -1503,10 +1512,10 @@ impl MediaSource for CraftMediaSource { let mut channels = if sample_rate == native_rate { decoded } else { resample_audio(&decoded, channels_count, native_rate, sample_rate, audible_frames) }; - if silent_frames > 0 { + if audible_frames < frames { for channel in &mut channels { channel.resize(frames, 0.0); - channel.rotate_right(silent_frames); + channel.rotate_right(edit_range.start); } } Ok(AudioBuffer { sample_rate, channels }) @@ -2550,29 +2559,37 @@ mod tests { } } - /// Original PCM generated in memory to exercise an empty edit followed by a trim. + /// Original PCM generated in memory at the MOV writer's default movie timescale. + fn edited_pcm_mov(rate: u32, samples: &[i16], edits: Vec) -> Vec { + use isobmff::{Brand, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 1, sample_rate: f64::from(rate) }; + let mut config = TrackConfig::new(SampleEntry::pcm(pcm), rate); + config.edits = edits; + let track = writer.add_track(config).unwrap(); + for chunk in samples.chunks(256) { + let data: Vec = chunk.iter().flat_map(|sample| sample.to_le_bytes()).collect(); + writer.write_sample(track, WriteSample { data: &data, duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap(); + } + writer.finish().unwrap().into_inner() + } + #[test] fn mov_pcm_trim_after_empty_edit_preserves_leading_silence() { - use isobmff::{Brand, Edit, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions}; - const RATE: u32 = 48_000; const DELAY_MS: u64 = 100; const DELAY: i64 = 4_800; let samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); for trim in [2_400i64, 4_800, 9_600] { - let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); - let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 1, sample_rate: f64::from(RATE) }; - let mut config = TrackConfig::new(SampleEntry::pcm(pcm), RATE); - config.edits = vec![ - Edit { segment_duration: DELAY_MS, media_time: -1, media_rate: 0x0001_0000 }, - Edit { segment_duration: 40, media_time: trim, media_rate: 0x0001_0000 }, - ]; - let track = writer.add_track(config).unwrap(); - for chunk in samples.chunks(256) { - let data: Vec = chunk.iter().flat_map(|sample| sample.to_le_bytes()).collect(); - writer.write_sample(track, WriteSample { data: &data, duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap(); - } - let bytes = writer.finish().unwrap().into_inner(); + let bytes = edited_pcm_mov( + RATE, + &samples, + vec![ + isobmff::Edit { segment_duration: DELAY_MS, media_time: -1, media_rate: 0x0001_0000 }, + isobmff::Edit { segment_duration: 40, media_time: trim, media_rate: 0x0001_0000 }, + ], + ); let file = isobmff::open(bytes.as_slice()).unwrap(); assert_eq!(file.timescale, 1_000); assert_eq!(file.tracks[0].edit_offset, DELAY - trim); @@ -2589,6 +2606,38 @@ mod tests { } } + #[test] + fn mov_pcm_audio_is_silent_after_the_edit_span() { + const RATE: u32 = 48_000; + const EDIT_MS: u64 = 41; + const TRIM: i64 = 9_600; + const EDIT_FRAMES: usize = 1_968; + let samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); + let last = f32::from(samples[TRIM as usize + EDIT_FRAMES - 1]) / 32_768.0; + let previous = f32::from(samples[TRIM as usize + EDIT_FRAMES - 2]) / 32_768.0; + for delay_ms in [0, 100] { + let mut edits = Vec::new(); + if delay_ms > 0 { + edits.push(isobmff::Edit { segment_duration: delay_ms, media_time: -1, media_rate: 0x0001_0000 }); + } + edits.push(isobmff::Edit { segment_duration: EDIT_MS, media_time: TRIM, media_rate: 0x0001_0000 }); + let bytes = edited_pcm_mov(RATE, &samples, edits); + let source = open_bytes("edited-pcm.mov", bytes.into()).expect("shared MOV route").unwrap(); + let read = |start, frames, rate| source.audio(start, frames, rate).expect("direct shared PCM read").channels.remove(0); + + let end = ((delay_ms + EDIT_MS) * 48) as i64; + assert_eq!(read(end - 2, 4, RATE), [previous, last, 0.0, 0.0], "crossing the boundary, delay {delay_ms}"); + assert_eq!(read(end, 2, RATE), [0.0, 0.0], "read after the end"); + assert_eq!(read(end - 2, 2, RATE), [previous, last], "backward seek"); + assert_eq!(read(end * 2 - 4, 6, RATE * 2), [previous, (previous + last) / 2.0, last, last, 0.0, 0.0]); + + let first_silent = ((delay_ms + EDIT_MS) * 44_100).div_ceil(1_000) as i64; + let boundary = read(first_silent - 1, 2, 44_100); + assert!(boundary[0] > 0.0, "sample before the fractional boundary"); + assert_eq!(boundary[1], 0.0, "sample after the fractional boundary"); + } + } + #[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 }); From b71670634aa78d822d9a65f498ec74607088bfa8 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:01:09 +0700 Subject: [PATCH 347/393] media: honor MXF descriptor color fallback for ProRes (#778) (#4023) * media: honor MXF descriptor color fallback for ProRes (#778) * style: format MXF descriptor color fallback --------- Co-authored-by: Codex --- crates/media/src/craft_source.rs | 206 ++++++++++++++++++++++++++++++- crates/media/src/probe.rs | 2 +- 2 files changed, 205 insertions(+), 3 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 7307a8323..d7c2f5d7c 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -64,6 +64,9 @@ const AUDIO_SEEK_BACKUP_PACKETS: usize = 2; /// 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; +/// Complete first-presented sample cap for the MXF ProRes colour probe. Larger samples retain the +/// existing colour policy; the ProRes header parser requires the complete declared frame. +const MAX_MXF_PRORES_COLOR_SAMPLE_BYTES: u32 = 4 * 1024 * 1024; fn worker_cap() -> usize { std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) @@ -1121,6 +1124,8 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio Ok(d) => d, Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), }; + let (color, container_color) = + mxf_prores_color(&file, &*source, v_idx).map_or((ColorInfo::REC709, None), |(probe, descriptor)| (probe, Some(descriptor))); let v_info = VideoStreamInfo { width, height, @@ -1128,13 +1133,13 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio par, codec: video_params.codec.name().to_string(), pixel_format: String::new(), - color: ColorInfo::REC709, + color, has_alpha, bitrate: None, hdr: None, }; let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); - (Some(v_info), Some(v_state), FramePresentation { container_color: None, par, rotation: 0, aperture: None }, duration) + (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation: 0, aperture: None }, duration) } else { let duration = audio_tracks .iter() @@ -2122,6 +2127,48 @@ fn resolve_color(vui: ColorTags, container: Option) -> ColorInfo { ColorInfo { matrix, transfer, primaries, range } } +/// Resolve the clip's initial probe colour from the first presented ProRes frame, without +/// changing decoder state or a project's saved interpretation. Later frames still resolve their +/// own decoder fields against the descriptor; this is not a variable-profile clip probe. +fn mxf_prores_color(file: &MxfFile, source: &dyn ByteSource, track_idx: usize) -> Option<(ColorInfo, ColorInfo)> { + use effectcraft_project::ColorSpace; + + let track = file.tracks.get(track_idx)?; + if !matches!(track.codec, mxf::Codec::ProRes { .. }) { + return None; + } + let descriptor = color_from_mxf(track.picture.as_ref()?)?; + let (start, len) = mxf_picture_window(track); + if len == 0 { + return None; + } + let index = track.sample_at(start)?; + let sample = track.samples.get(index)?; + if !(28..=MAX_MXF_PRORES_COLOR_SAMPLE_BYTES).contains(&sample.size) { + return None; + } + let packet = file.read_sample(source, track_idx, index).ok()?; + let tags = craft_video::prores::probe(&packet).ok()?.color; + let tags = ColorTags { primaries: tags.primaries, transfer: tags.transfer, matrix: tags.matrix, full_range: false }; + let color = resolve_color(tags, Some(descriptor)); + // Only opt in when the managed compositor can represent the resolved primaries/transfer. + // The general profile mapper also approximates some other pairs for existing routes. + match crate::probe::profile_of_craft(&color) { + Some(ColorSpace::Rec2100Pq | ColorSpace::Rec2100Hlg) => Some((color, descriptor)), + Some(ColorSpace::Rec709) if color.primaries == Primaries::Bt709 => Some((color, descriptor)), + _ => None, + } +} + +fn color_from_mxf(picture: &mxf::PictureInfo) -> Option { + let (primaries, transfer, matrix) = picture.color_codes(); + if (primaries, transfer, matrix) == (None, None, None) { + return None; + } + // Use the existing H.273 defaults without changing MXF quantisation range policy. + Some(resolve_color(ColorTags { primaries: primaries.unwrap_or(2), transfer: transfer.unwrap_or(2), matrix: matrix.unwrap_or(2), full_range: false }, None)) +} + fn color_from_isobmff(c: &isobmff::ColorInfo) -> ColorInfo { match c { isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => ColorInfo { @@ -2834,6 +2881,161 @@ mod tests { } } + fn mxf_prores_color_packet(codes: (u8, u8, u8)) -> Vec { + use craft_video::prores::{self, ChromaFormat, Encoder, EncoderConfig, Frame, Profile}; + + let mut frame = Frame::new(16, 12, ChromaFormat::Yuv422, 10, false).expect("ProRes frame"); + frame.y.fill(512); + frame.cb.fill(512); + frame.cr.fill(512); + let (primaries, transfer, matrix) = codes; + let mut encoder = EncoderConfig::new(Profile::Hq, 16, 12); + encoder.color = prores::ColorInfo { primaries, transfer, matrix }; + let packet = Encoder::with_config(encoder).encode(&frame).expect("encode ProRes"); + let bits = prores::probe(&packet).expect("ProRes header").color; + assert_eq!((bits.primaries, bits.transfer, bits.matrix), codes); + packet + } + + fn mxf_prores_color_fixture(color: mxf::write::ColorSpace, packets: &[&[u8]]) -> Arc<[u8]> { + let ids = mxf::write::PackageIds::from_seed("eff-mxf-color", "op1a"); + let mut cfg = mxf::write::WriterConfig::new(mxf::write::Pattern::Op1a, mxf::Rational::new(25, 1), ids); + let mut picture = mxf::write::PictureDesc::new(mxf::write::PictureCoding::ProRes { profile: 4 }, 16, 12); + picture.color = color; + cfg.picture = Some(picture); + let mut writer = mxf::write::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).expect("writer"); + for packet in packets { + writer.push_picture(packet, mxf::write::FrameInfo::intra()).expect("picture"); + } + writer.finish().expect("finish").into_inner().into() + } + + #[test] + fn mxf_descriptor_color_fills_unspecified_shared_prores_fields() { + use effectcraft_project::ColorSpace; + + let pq = ColorInfo { primaries: Primaries::Bt2020, transfer: Transfer::Pq, matrix: Matrix::Bt2020Ncl, range: Range::Limited }; + let mixed = ColorInfo { matrix: Matrix::Bt709, ..pq }; + for (descriptor, descriptor_codes, packet_codes, profile, expected) in [ + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (2, 2, 2), Some(ColorSpace::Rec2100Pq), pq), + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (1, 1, 1), Some(ColorSpace::Rec709), ColorInfo::REC709), + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (2, 2, 1), Some(ColorSpace::Rec2100Pq), mixed), + (mxf::write::ColorSpace::Rec2020Pq, (9, 16, 9), (1, 2, 1), Some(ColorSpace::Rec709), ColorInfo::REC709), + (mxf::write::ColorSpace::Rec709, (1, 1, 1), (2, 2, 2), Some(ColorSpace::Rec709), ColorInfo::REC709), + ] { + let bytes = mxf_prores_color_fixture(descriptor, &[&mxf_prores_color_packet(packet_codes)]); + let file = mxf::open(bytes.as_ref()).expect("demux fixture"); + let picture = file.tracks[0].picture.as_ref().expect("picture descriptor"); + let (p, t, m) = descriptor_codes; + assert_eq!(picture.color_codes(), (Some(p), Some(t), Some(m))); + let footage = crate::probe::probe_bytes("color.mxf", bytes.clone()).expect("public probe"); + assert_eq!(footage.codec, "ProRes", "must use the shared MXF route"); + assert_eq!(footage.color_profile, profile); + + let source = open_bytes("color.mxf", bytes).expect("recognized MXF").expect("shared MXF"); + let info = source.info().video.as_ref().expect("video"); + assert_eq!(info.color, expected); + assert!(info.hdr.is_none(), "color labels alone are not HDR static metadata"); + let decoded = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode frame"); + assert_eq!(decoded.color, expected); + } + } + + #[test] + fn mxf_prores_explicit_rec709_keeps_managed_pixels_and_saved_interpretation() { + use effectcraft_color::{ColorSpace, Label}; + use effectcraft_project::{BitDepth, Comp, ItemKind, LayerSource, Project, build}; + use effectcraft_render::{RenderOpts, Renderer}; + + let packet = mxf_prores_color_packet((1, 1, 1)); + let render = |descriptor, saved_override| { + let bytes = mxf_prores_color_fixture(descriptor, &[&packet]); + let path = "managed-color.mxf"; + let mut footage = crate::probe::probe_bytes(path, bytes.clone()).expect("public probe"); + assert_eq!(footage.codec, "ProRes", "must use the shared MXF route"); + assert_eq!(footage.color_profile, Some(ColorSpace::Rec709)); + if saved_override { + footage.color_profile = Some(ColorSpace::Rec2100Pq); + } + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes); + + let mut project = Project::default(); + project.settings.bit_depth = BitDepth::Bpc32; + project.settings.working_space = Some(ColorSpace::Srgb); + let rate = effectcraft_time::FrameRate::new(25, 1); + let mut comp = Comp::new(16, 12, rate, rate.tick_of(1)); + let item = project.add_item("Footage", Label::Aqua, None, ItemKind::Footage(footage)); + let layer = build::layer(&mut project, &comp, "Footage", LayerSource::Footage { item }, (16, 12), Some(comp.duration)); + comp.layers.push(layer); + let comp_id = project.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.into())); + Renderer::new(&project, &pool, RenderOpts::default()).comp_frame(comp_id, effectcraft_time::Tick::ZERO).get(8, 6) + }; + + let rec709 = render(mxf::write::ColorSpace::Rec709, false); + let conflicting = render(mxf::write::ColorSpace::Rec2020Pq, false); + let overridden = render(mxf::write::ColorSpace::Rec2020Pq, true); + assert!(rec709[0] > 0.1 && rec709[0] < 0.9 && rec709[3] > 0.99, "not an opaque midtone: {rec709:?}"); + assert!(rec709.iter().zip(conflicting).all(|(a, b)| (a - b).abs() < 1e-4), "{rec709:?} vs {conflicting:?}"); + assert!((overridden[0] - conflicting[0]).abs() > 0.02, "saved interpretation did not change the pixel: {overridden:?} vs {conflicting:?}"); + } + + #[test] + fn mxf_prores_color_reads_one_bounded_presented_packet() { + struct Reads<'a> { + bytes: &'a [u8], + log: Mutex>, + fail: bool, + } + impl ByteSource for Reads<'_> { + fn len(&self) -> u64 { + if self.fail { u64::MAX } else { self.bytes.len() as u64 } + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.log.lock().unwrap().push((offset, buf.len())); + if self.fail { + return Err(std::io::Error::other("unreadable fixture packet")); + } + self.bytes.read_at(offset, buf) + } + } + + let unspecified = mxf_prores_color_packet((2, 2, 2)); + let rec709 = mxf_prores_color_packet((1, 1, 1)); + let bytes = mxf_prores_color_fixture(mxf::write::ColorSpace::Rec2020Pq, &[&unspecified, &rec709]); + let mut file = mxf::open(bytes.as_ref()).expect("demux fixture"); + // Exercise a material edit on parsed metadata: stored packet zero is hidden. + file.tracks[0].start_position = 1; + let sample = file.tracks[0].samples[1]; + let mut reads = Reads { bytes: &bytes, log: Mutex::new(Vec::new()), fail: false }; + let (probe, descriptor) = mxf_prores_color(&file, &reads, 0).expect("first presented ProRes header"); + assert_eq!(probe, ColorInfo::REC709); + assert_eq!(descriptor.transfer, Transfer::Pq); + assert_eq!(std::mem::take(reads.log.get_mut().unwrap()), [(sample.offset, sample.size as usize)]); + + reads.fail = true; + assert_eq!(mxf_prores_color(&file, &reads, 0), None); + assert_eq!(std::mem::take(reads.log.get_mut().unwrap()), [(sample.offset, sample.size as usize)]); + // The source reports ample backing so only the cap can explain the skipped read. + file.tracks[0].samples[1].size = MAX_MXF_PRORES_COLOR_SAMPLE_BYTES + 1; + assert_eq!(mxf_prores_color(&file, &reads, 0), None); + assert!(reads.log.get_mut().unwrap().is_empty()); + + file.tracks[0].samples[1] = sample; + file.tracks[0].codec = mxf::Codec::Vc3; + assert_eq!(mxf_prores_color(&file, &reads, 0), None); + assert!(reads.log.get_mut().unwrap().is_empty()); + } + + #[test] + fn mxf_absent_color_labels_keep_defaults_and_range_policy() { + let picture = mxf::PictureInfo { component_depth: 10, black_ref_level: Some(0), white_ref_level: Some(1023), ..Default::default() }; + assert!(picture.full_range()); + assert_eq!(picture.color_codes(), (None, None, None)); + assert_eq!(color_from_mxf(&picture), None); + assert_eq!(resolve_color(ColorTags::UNSPECIFIED, color_from_mxf(&picture)), ColorInfo::REC709); + } + #[test] fn mxf_descriptor_aspect_reaches_shared_probe_and_frame() { use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 74d8fb9a5..954036fc4 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -240,7 +240,7 @@ pub(crate) fn footage_from_craft_info(path: &str, info: &craft_media_source::Med } } -fn profile_of_craft(c: &craft_color::ColorInfo) -> Option { +pub(crate) fn profile_of_craft(c: &craft_color::ColorInfo) -> Option { use craft_color::{Primaries, Transfer}; use effectcraft_project::ColorSpace; match (c.primaries, c.transfer) { From 775b157e66a22df08d8e5a1002360f746f3a7317 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 09:03:46 -0500 Subject: [PATCH 348/393] media: probe AVI ProRes coded alpha parity (#4025) * media: probe AVI ProRes coded alpha parity * media: fix prores::Profile, ChromaFormat, and Encoder::with_config in AVI alpha test --- crates/media/src/craft_source.rs | 66 +++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 6 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index d7c2f5d7c..76b7b19f9 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -72,6 +72,14 @@ fn worker_cap() -> usize { std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) } +fn prores_has_alpha(packet_size: u32, read: impl FnOnce() -> Option>) -> Option { + if packet_size > MAX_PRORES_ALPHA_SAMPLE_BYTES { + return None; + } + let packet = read()?; + Some(craft_video::prores::probe(&packet).ok()?.alpha != craft_video::prores::AlphaType::None) +} + 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) } @@ -818,11 +826,7 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> 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, v_idx, 0).ok()?; - craft_video::prores::probe(&packet).ok()?.alpha != craft_video::prores::AlphaType::None + prores_has_alpha(sample.size, || file.read_sample(&*source, v_idx, 0).ok())? } else { video_track.video().is_some_and(|v| v.depth == 32) }; @@ -1224,7 +1228,12 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { Ok(d) => d, Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), }; - let info = default_video_info(width, height, frame_rate, &video_params); + let mut info = default_video_info(width, height, frame_rate, &video_params); + if video_params.codec == CodecId::ProRes { + // The coded alpha plane is authoritative for ProRes, regardless of AVI header depth. + let chunk = video_stream.chunks.first()?; + info.has_alpha = prores_has_alpha(chunk.size, || file.read_chunk(&*source, v_idx, 0).ok())?; + } let state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) } else { @@ -3509,4 +3518,49 @@ mod tests { let rewound = decode(&mut wide_tracks[0], 0, 600); assert_eq!(rewound[0], wide[0][..600]); } + + #[test] + fn avi_prores_coded_alpha_parity() { + use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; + + let encode_prores_avi = |with_alpha: bool| -> Vec { + let mut cfg = EncoderConfig::new(Profile::P4444, 16, 16); + cfg.encode_alpha = with_alpha; + cfg.threads = false; + let mut enc = Encoder::with_config(cfg); + let frame = ProResFrame { + width: 16, + height: 16, + chroma: ChromaFormat::Yuv444, + bit_depth: 10, + y: vec![512; 256], + cb: vec![512; 256], + cr: vec![512; 256], + alpha: with_alpha.then(|| vec![512; 256]), + interlace: Interlace::Progressive, + color: ProResColor::default(), + aspect_ratio: 0, + frame_rate_code: 0, + }; + let pkt = enc.encode(&frame).expect("encode prores"); + let mut w = avi::AviWriter::new( + std::io::Cursor::new(Vec::new()), + vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 24, 1))], + avi::MuxOptions::default(), + ) + .expect("avi writer"); + w.write_chunk(0, &pkt, true).expect("write prores chunk"); + w.finish().expect("finish avi").into_inner() + }; + + let alpha_src = open_bytes("alpha.avi", Arc::from(encode_prores_avi(true))).expect("recognized").expect("opened"); + assert!(alpha_src.info().video.as_ref().unwrap().has_alpha); + let frame = alpha_src.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode alpha frame"); + assert!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. })); + + let opaque_src = open_bytes("opaque.avi", Arc::from(encode_prores_avi(false))).expect("recognized").expect("opened"); + assert!(!opaque_src.info().video.as_ref().unwrap().has_alpha); + let frame = opaque_src.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode opaque frame"); + assert!(matches!(frame.data, PixelData::Yuv16 { alpha: None, .. })); + } } From 7334a14ac2d993e14d7953e77d4d3a7f3869437f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 09:43:57 -0500 Subject: [PATCH 349/393] media: enable FFV1 and APV decode in craft-video route (#4027) * media: enable FFV1 and APV decode in craft-video route * media: supply FFV1 config_record extradata in TrackDecoder unit test --- crates/media/Cargo.toml | 2 +- crates/media/src/craft_source.rs | 40 +++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 338bdc6f7..cf93c6861 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", "avi", "mxf"] } craft-media-source = { workspace = true } craft-time = { workspace = true } -craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "threads"] } +craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "ffv1", "apv-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 index 76b7b19f9..c7398947a 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -81,7 +81,19 @@ fn prores_has_alpha(packet_size: u32, read: impl FnOnce() -> Option>) -> } 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) + matches!( + codec, + CodecId::H264 + | CodecId::Hevc + | CodecId::Av1 + | CodecId::Vp9 + | CodecId::Vp8 + | CodecId::ProRes + | CodecId::Dnxhd + | CodecId::Mpeg2Video + | CodecId::Ffv1 + | CodecId::Apv + ) } /// True when `head` begins with a plausible ISO-BMFF top-level box. @@ -3519,6 +3531,32 @@ mod tests { assert_eq!(rewound[0], wide[0][..600]); } + #[test] + fn ffv1_and_apv_video_codecs_route_through_craft_video() { + assert!(supports_video_codec(CodecId::Ffv1)); + assert!(supports_video_codec(CodecId::Apv)); + + let template = craft_video::ffv1::Frame { + width: 16, + height: 16, + colorspace: craft_video::ffv1::Colorspace::YCbCr, + bit_depth: 8, + chroma_shift: (1, 1), + planes: vec![vec![128; 256], vec![128; 64], vec![128; 64]], + }; + let ffv1_enc = craft_video::ffv1::Encoder::new(&template, craft_video::ffv1::EncoderConfig::default()).expect("ffv1 encoder"); + let mut ffv1_params = CodecParams::new(CodecId::Ffv1); + ffv1_params.width = Some(16); + ffv1_params.height = Some(16); + ffv1_params.extradata = ffv1_enc.config_record(); + assert!(TrackDecoder::with_options(&ffv1_params, TrackDecoderOptions { threads: Some(1), draft: false }).is_ok(), "Ffv1 decoder"); + + let mut apv_params = CodecParams::new(CodecId::Apv); + apv_params.width = Some(16); + apv_params.height = Some(16); + assert!(TrackDecoder::with_options(&apv_params, TrackDecoderOptions { threads: Some(1), draft: false }).is_ok(), "Apv decoder"); + } + #[test] fn avi_prores_coded_alpha_parity() { use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; From 52c78fd25235851110142c11e006af72a9ff3bd5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:18:42 +0700 Subject: [PATCH 350/393] media: preserve the final picture in regular H.264 transport streams (#778) (#4030) * Preserve the final picture duration in regular H.264 transport streams * Test TS duration through the public H.264 encoder API --------- Co-authored-by: Codex --- crates/media/src/craft_source.rs | 159 ++++++++++++++++++++++++++++++- 1 file changed, 158 insertions(+), 1 deletion(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index c7398947a..d7c050318 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1279,6 +1279,45 @@ fn estimate_mpeg_frame_rate(units: &[mpegts::Unit]) -> FrameRate { estimate_mpeg_frame_rate_pts(units.iter().filter_map(|u| u.pts)) } +/// A timestamp is the start of a picture, not the end of its display interval. +fn regular_ts_picture_end(units: &[mpegts::Unit], origin_pts: i64, rate: FrameRate) -> Option { + let [first, second, rest @ ..] = units else { return None }; + let first_pts = first.pts?; + // A complete index can still contain a unit the public reader refuses to allocate. + let readable = |unit: &mpegts::Unit| unit.size > 0 && unit.size <= mpegts::MAX_UNIT_BYTES; + if !first.key || first_pts != origin_pts || rate.num <= 0 || rate.den <= 0 || !readable(first) || !readable(second) { + return None; + } + let mut last = second.pts?; + let step = last.checked_sub(first_pts)?; + // Do not infer a tail from a snapped rate or extrapolate an irregular track. + if step <= 0 || i128::from(step) * i128::from(rate.num) != 90_000 * i128::from(rate.den) { + return None; + } + for unit in rest { + let pts = unit.pts?; + if pts.checked_sub(last)? != step || !readable(unit) { + return None; + } + last = pts; + } + let end = last.checked_add(step)?.checked_sub(origin_pts)?; + let ticks = i128::from(end) * i128::from(craft_time::TICKS_PER_SECOND) / 90_000; + Some(Tick(i64::try_from(ticks).ok()?)) +} + +fn clean_ts_packet_index(file: &mpegts::File, source: &S) -> bool { + let mpegts::Format::Ts { packet_size, sync_offset } = file.format else { return false }; + if !file.warnings.is_empty() || !matches!(packet_size, 188 | 192 | 204) || sync_offset >= packet_size || !source.len().is_multiple_of(packet_size as u64) { + return false; + } + // Unlike the scanner's recovery path, require the five sync bytes it uses to + // identify a TS to align from byte zero, with no ignored partial packet at EOF. + let mut head = [0u8; 5 * 204]; + let Some(prefix) = head.get_mut(..5 * packet_size) else { return false }; + source.read_at(0, prefix).is_ok() && (0..5).all(|i| prefix.get(i * packet_size + sync_offset) == Some(&0x47)) +} + fn open_mpeg(name: &str, fmt: mpegts::Format, source: SharedBytes) -> Option> { let file = mpegts::open(&*source).ok()?; let origin_pts = file.streams.iter().filter_map(|s| s.pts_range().map(|(lo, _)| lo)).min().unwrap_or(0); @@ -1320,7 +1359,13 @@ fn open_mpeg(name: &str, fmt: mpegts::Format, source: SharedBytes) -> Option Vec { + use craft_video::h264::{Encoder, EncoderConfig, YuvFrame}; + use mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + + let mut config = EncoderConfig::new(16, 16, 25, 1); + config.intra_only = true; + config.threads = 1; + let mut encoder = Encoder::new(config).unwrap(); + let mut packets = Vec::new(); + let uv = [128; 8 * 8]; + for (pts, level) in [(90_000, 48), (93_600, 192)] { + let y = [level; 16 * 16]; + packets.extend(encoder.encode(&YuvFrame { y: &y, u: &uv, v: &uv, y_stride: 16, uv_stride: 8 }, pts).unwrap()); + } + packets.extend(encoder.flush()); + assert_eq!(packets.len(), 2); + let mut mux = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + for packet in packets { + assert!(packet.keyframe); + mux.write_frame(0, &Frame { data: &packet.data, pts: packet.pts, dts: Some(packet.dts), key: true }).unwrap(); + } + mux.finish().unwrap() + } + + #[test] + fn regular_video_only_h264_ts_duration_keeps_the_last_picture_playable() { + let bytes = generated_two_frame_ts(); + let parsed = mpegts::open(bytes.as_slice()).unwrap(); + assert_eq!(parsed.streams.len(), 1); + assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings); + assert_eq!(parsed.streams[0].skipped_bytes, 0); + assert!(clean_ts_packet_index(&parsed, bytes.as_slice())); + let units = &parsed.streams[0].units; + assert_eq!(units.iter().map(|unit| unit.pts).collect::>(), [Some(90_000), Some(93_600)]); + + let bytes: Arc<[u8]> = bytes.into(); + let opened = crate::stream::open_bytes("final-picture.ts", bytes.clone()).unwrap(); + assert!(matches!(opened, crate::stream::MediaSource::Craft(_))); + let film = filmcraft_codecs::open_bytes("final-picture.ts", bytes.clone()).unwrap(); + let rate = effectcraft_time::FrameRate::FPS_25; + assert_eq!(film.info().duration.0, rate.tick_of(2).0); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("final-picture.ts"); + std::fs::write(&path, bytes.as_ref()).unwrap(); + let footage = crate::probe(&path).unwrap(); + let pool = crate::MediaPool::new(); + let first = pool.frame_at(&footage, effectcraft_time::Tick::ZERO).unwrap(); + let last = pool.frame_at(&footage, rate.tick_of(1)).unwrap(); + assert!(last.get(8, 8)[0] > first.get(8, 8)[0] + 0.25, "the earlier duration clamped the last request to the first picture"); + assert_eq!(footage.frame_rate, rate); + assert!(!footage.has_audio); + assert_eq!(footage.duration, rate.tick_of(2)); + } + + #[test] + fn ts_damaged_or_partial_tail_keeps_the_earlier_indexed_duration() { + let mut transport_error = [0xff; 188]; + // A dropped error-marked packet does not alter the two indexed pictures. + transport_error[..4].copy_from_slice(&[0x47, 0x9f, 0xff, 0x10]); + for (tail, warned) in [(&transport_error[..], true), (&[0x47][..], false)] { + let mut bytes = generated_two_frame_ts(); + bytes.extend_from_slice(tail); + let parsed = mpegts::open(bytes.as_slice()).unwrap(); + assert_eq!(parsed.warnings.iter().any(|warning| warning.contains("transport error indicator")), warned); + assert_eq!(parsed.streams[0].units.len(), 2); + assert_eq!(regular_ts_picture_end(&parsed.streams[0].units, 90_000, FrameRate::FPS_25), Some(Tick(craft_time::TICKS_PER_SECOND * 2 / 25))); + assert!(!clean_ts_packet_index(&parsed, bytes.as_slice())); + // The same shared route still opens and retains its prior duration. + let source = crate::stream::open_bytes("damaged-tail.ts", bytes.into()).unwrap(); + let crate::stream::MediaSource::Craft(source) = source else { panic!("existing shared route") }; + assert_eq!(source.info().duration, Tick(craft_time::TICKS_PER_SECOND / 25)); + } + } + + #[test] + fn ts_picture_end_requires_complete_exact_regular_stamps() { + let bytes = generated_two_frame_ts(); + let parsed = mpegts::open(bytes.as_slice()).unwrap(); + let units = &parsed.streams[0].units; + let rate = FrameRate::FPS_25; + assert_eq!(regular_ts_picture_end(units, 90_000, rate), Some(Tick(craft_time::TICKS_PER_SECOND * 2 / 25))); + assert_eq!(regular_ts_picture_end(&units[..1], 90_000, rate), None); + assert_eq!(regular_ts_picture_end(units, 89_999, rate), None); + assert_eq!(regular_ts_picture_end(units, 90_000, FrameRate::FPS_30), None); + + let mut nonkey = units.clone(); + nonkey[0].key = false; + assert_eq!(regular_ts_picture_end(&nonkey, 90_000, rate), None); + let mut missing = units.clone(); + missing[1].pts = None; + assert_eq!(regular_ts_picture_end(&missing, 90_000, rate), None); + let mut irregular = units.clone(); + let mut third = units[1]; + third.pts = Some(97_201); + irregular.push(third); + assert_eq!(regular_ts_picture_end(&irregular, 90_000, rate), None); + + let mut oversized = units.clone(); + oversized[1].size = mpegts::MAX_UNIT_BYTES + 1; + assert_eq!(regular_ts_picture_end(&oversized, 90_000, rate), None); + oversized[1].size = mpegts::MAX_UNIT_BYTES; + assert!(regular_ts_picture_end(&oversized, 90_000, rate).is_some()); + oversized[1].size = 0; + assert_eq!(regular_ts_picture_end(&oversized, 90_000, rate), None); + + let mut overflow = units.clone(); + overflow[0].pts = Some(i64::MAX - 3_600); + overflow[1].pts = Some(i64::MAX); + assert_eq!(regular_ts_picture_end(&overflow, i64::MAX - 3_600, rate), None); + } + fn pcm_s16le_bytes(sample: i16, count: usize) -> Vec { std::iter::repeat_n(sample.to_le_bytes(), count).flatten().collect() } From d46142eb69e282265364987a7deb81e3aff0b9cf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 10:42:03 -0500 Subject: [PATCH 351/393] media: preserve container audio resampling phase across seeks (#4026) --- crates/media/src/craft_source.rs | 129 +++++++++++++++++++++---------- 1 file changed, 88 insertions(+), 41 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index d7c050318..86caca007 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1529,7 +1529,9 @@ impl MediaSource for CraftMediaSource { let audible_start = i64::try_from(i128::from(start) + edit_range.start as i128).unwrap_or(i64::MAX); let native_rate = entry.native_rate; - let (native_start, mut native_frames) = native_audio_window(audible_start, audible_frames, native_rate, sample_rate); + let Some((native_start, mut native_frames, phase)) = resampling_window(audible_start, audible_frames, native_rate, sample_rate) else { + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); + }; if native_rate != sample_rate { // The resampler asks for lookahead. Do not interpolate with samples // that are stored in the track but lie beyond the edit. @@ -1581,8 +1583,12 @@ impl MediaSource for CraftMediaSource { } }; - let mut channels = - if sample_rate == native_rate { decoded } else { resample_audio(&decoded, channels_count, native_rate, sample_rate, audible_frames) }; + let mut channels = if sample_rate == native_rate { + decoded + } else { + let first_output = if audible_start < 0 { usize::try_from(audible_start.unsigned_abs()).unwrap_or(audible_frames).min(audible_frames) } else { 0 }; + resample_audio_with_phase(&decoded, native_rate, sample_rate, audible_frames, phase, first_output) + }; if audible_frames < frames { for channel in &mut channels { channel.resize(frames, 0.0); @@ -1644,17 +1650,9 @@ impl MediaSource for StandaloneAudioSource { return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); } let native_rate = self.native_rate; - let (native_start, native_frames, phase) = if sample_rate == native_rate { - (start, frames, 0) - } else { - let scaled = i128::from(start) * i128::from(native_rate); - let divisor = i128::from(sample_rate); - let Ok(origin) = i64::try_from(scaled.div_euclid(divisor)) else { - // An unrepresentable source position cannot address this stream. - return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); - }; - // Reuse the existing window size, but not its truncating start calculation. - (origin, native_audio_window(0, frames, native_rate, sample_rate).1, scaled.rem_euclid(divisor) as u64) + let Some((native_start, native_frames, phase)) = resampling_window(start, frames, native_rate, sample_rate) else { + // An unrepresentable source position cannot address this stream. + return Ok(AudioBuffer::new(sample_rate, channels_count as u16, frames)); }; let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1664,14 +1662,13 @@ impl MediaSource for StandaloneAudioSource { } // Negative output positions are silence, not interpolation into frame zero. let first_output = if start < 0 { usize::try_from(start.unsigned_abs()).unwrap_or(frames).min(frames) } else { 0 }; - Ok(AudioBuffer { sample_rate, channels: resample_standalone_audio(&decoded, native_rate, sample_rate, frames, phase, first_output) }) + Ok(AudioBuffer { sample_rate, channels: resample_audio_with_phase(&decoded, native_rate, sample_rate, frames, phase, first_output) }) } } /// Step the fractional input position as an exact integer quotient and remainder; /// rounding happens only when interpolating a sample, independent of the window. -#[cfg(any(unix, windows))] -fn resample_standalone_audio(decoded: &[Vec], native_rate: u32, sample_rate: u32, frames: usize, phase: u64, first_output: usize) -> Vec> { +fn resample_audio_with_phase(decoded: &[Vec], native_rate: u32, sample_rate: u32, frames: usize, phase: u64, first_output: usize) -> Vec> { let mut out = vec![vec![0.0; frames]; decoded.len()]; let divisor = u64::from(sample_rate); let first = first_output as u128 * u128::from(native_rate) + u128::from(phase); @@ -1738,13 +1735,15 @@ fn decode_standalone_range(native_rate: u32, channels_count: usize, state: &mut Ok(drain_audio_window(&mut state.buf, &mut state.decoded_pos, channels_count, start, frames)) } -fn native_audio_window(start: i64, frames: usize, native_rate: u32, sample_rate: u32) -> (i64, usize) { +fn resampling_window(start: i64, frames: usize, native_rate: u32, sample_rate: u32) -> Option<(i64, usize, u64)> { if sample_rate == native_rate { - return (start, frames); + return Some((start, frames, 0)); } - let s0 = (i128::from(start) * i128::from(native_rate)) / i128::from(sample_rate); + let scaled = i128::from(start) * i128::from(native_rate); + let divisor = i128::from(sample_rate); + let origin = i64::try_from(scaled.div_euclid(divisor)).ok()?; 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) + Some((origin, len, scaled.rem_euclid(divisor) as u64)) } fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_count: usize, start: i64, frames: usize) -> Vec> { @@ -1773,26 +1772,6 @@ fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_coun out } -fn resample_audio(decoded: &[Vec], channels_count: usize, native_rate: u32, sample_rate: u32, frames: usize) -> Vec> { - 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; - } - } - resampled -} - #[cfg(any(unix, windows))] fn open_standalone_audio(name: &str, head: &[u8], source: SharedBytes) -> Option> { let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()); @@ -3688,6 +3667,74 @@ mod tests { assert_eq!(rewound[0], wide[0][..600]); } + #[test] + fn container_audio_preserves_fractional_resampling_phase_across_seeks() { + let mut mux = + avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16))], avi::MuxOptions::default()) + .unwrap(); + let mut pcm = Vec::with_capacity(4800 * 2); + for i in 0..4800i32 { + // Frame 4000 is exactly 0 so output frame 3675 (at 44.1 kHz) lands on 0.0. + let sample = ((i - 4000) * 5).clamp(-32767, 32767) as i16; + pcm.extend_from_slice(&sample.to_le_bytes()); + } + mux.write_chunk(0, &pcm, true).unwrap(); + let bytes: Arc<[u8]> = Arc::from(mux.finish().unwrap().into_inner()); + + let src = open_bytes("ramp.avi", bytes.clone()).expect("recognized").expect("opened"); + let resampled = src.audio(0, 256, 44_100).expect("resampled"); + + let cold = open_bytes("ramp.avi", bytes).expect("recognized").expect("opened"); + let alone = cold.audio(1, 1, 44_100).expect("single output frame"); + // Output frame 1 at 44.1 kHz is native frame 160/147 (between native 1 and 2: -19995 and -19990). + let expected = (-19995.0 + (13.0 / 147.0) * 5.0) / 32768.0; + assert!((alone.channels[0][0] - expected).abs() < 1e-7, "absolute fractional phase"); + assert_eq!(alone.channels[0][0], resampled.channels[0][1], "single-frame seek matches block"); + + let pre_roll = cold.audio(-1, 3, 44_100).expect("negative output window"); + assert_eq!(pre_roll.channels[0][0], 0.0, "silence before frame zero"); + assert_eq!(&pre_roll.channels[0][1..], &resampled.channels[0][..2], "crossing frame zero preserves phase"); + + let crossing = cold.audio(3670, 6, 44_100).expect("cross zero sample"); + let zero = cold.audio(3675, 1, 44_100).expect("zero sample alone"); + assert_eq!(crossing.channels[0][5], 0.0); + assert_eq!(crossing.channels[0][5], zero.channels[0][0]); + + let after_end = cold.audio(4410, 2, 44_100).expect("after EOF"); + assert!(after_end.channels.iter().flatten().all(|&s| s == 0.0)); + let out_of_range = cold.audio(i64::MAX / 2, 1, 1).expect("unreachable origin"); + assert!(out_of_range.channels.iter().flatten().all(|&s| s == 0.0)); + + // 48->44.1 kHz MOV edit boundary: full read, split read, and fresh seek must all agree, + // sample 6,218 must not blend in the stored tail past the edit, and sample 6,219 must be silent. + const MOV_TRIM: usize = 9_600; + const MOV_EDIT_FRAMES: usize = 1_968; + let mov_samples: Vec = (0..12_000).map(|i| 1_000 + (i % 257) as i16 * 32).collect(); + let last_in_edit = f32::from(mov_samples[MOV_TRIM + MOV_EDIT_FRAMES - 1]) / 32_768.0; + let mov_bytes: Arc<[u8]> = edited_pcm_mov( + 48_000, + &mov_samples, + vec![ + isobmff::Edit { segment_duration: 100, media_time: -1, media_rate: 0x0001_0000 }, + isobmff::Edit { segment_duration: 41, media_time: MOV_TRIM as i64, media_rate: 0x0001_0000 }, + ], + ) + .into(); + let full_mov = open_bytes("edited-pcm.mov", mov_bytes.clone()).expect("recognized").expect("opened"); + let full_window = full_mov.audio(6_200, 25, 44_100).expect("full mov read").channels.remove(0); + assert_eq!(full_window[18], last_in_edit, "sample 6,218 must not blend in the tail past the edit"); + assert_eq!(full_window[19], 0.0, "sample 6,219 must be silent"); + + let split_mov = open_bytes("edited-pcm.mov", mov_bytes.clone()).expect("recognized").expect("opened"); + let mut split_window = split_mov.audio(6_200, 18, 44_100).expect("split part 1").channels.remove(0); + split_window.extend_from_slice(&split_mov.audio(6_218, 7, 44_100).expect("split part 2").channels[0]); + assert_eq!(split_window, full_window, "split read must match full read"); + + let seek_mov = open_bytes("edited-pcm.mov", mov_bytes).expect("recognized").expect("opened"); + let seek_window = seek_mov.audio(6_218, 2, 44_100).expect("fresh seek").channels.remove(0); + assert_eq!(seek_window, full_window[18..20], "fresh seek must match full read"); + } + #[test] fn ffv1_and_apv_video_codecs_route_through_craft_video() { assert!(supports_video_codec(CodecId::Ffv1)); From b76b883e903e446be33f7fe00345da0189d959bb Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:06:55 +0700 Subject: [PATCH 352/393] media: keep shared AVI playback when ProRes alpha cannot be inferred (#4035) Co-authored-by: Codex --- crates/media/src/craft_source.rs | 113 +++++++++++++++++++++---------- 1 file changed, 78 insertions(+), 35 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 86caca007..2ea8a1440 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1242,9 +1242,10 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { }; let mut info = default_video_info(width, height, frame_rate, &video_params); if video_params.codec == CodecId::ProRes { - // The coded alpha plane is authoritative for ProRes, regardless of AVI header depth. - let chunk = video_stream.chunks.first()?; - info.has_alpha = prores_has_alpha(chunk.size, || file.read_chunk(&*source, v_idx, 0).ok())?; + // The coded alpha plane is authoritative when it can be probed. Otherwise, + // keep the old AVI default without dropping an otherwise readable stream. + let alpha = video_stream.chunks.first().and_then(|chunk| prores_has_alpha(chunk.size, || file.read_chunk(&*source, v_idx, 0).ok())); + info.has_alpha = alpha.unwrap_or(false); } let state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) @@ -3761,48 +3762,90 @@ mod tests { assert!(TrackDecoder::with_options(&apv_params, TrackDecoderOptions { threads: Some(1), draft: false }).is_ok(), "Apv decoder"); } - #[test] - fn avi_prores_coded_alpha_parity() { + fn generated_avi_prores(with_alpha: bool, invalid_first: bool) -> Vec { use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; - let encode_prores_avi = |with_alpha: bool| -> Vec { - let mut cfg = EncoderConfig::new(Profile::P4444, 16, 16); - cfg.encode_alpha = with_alpha; - cfg.threads = false; - let mut enc = Encoder::with_config(cfg); - let frame = ProResFrame { - width: 16, - height: 16, - chroma: ChromaFormat::Yuv444, - bit_depth: 10, - y: vec![512; 256], - cb: vec![512; 256], - cr: vec![512; 256], - alpha: with_alpha.then(|| vec![512; 256]), - interlace: Interlace::Progressive, - color: ProResColor::default(), - aspect_ratio: 0, - frame_rate_code: 0, - }; - let pkt = enc.encode(&frame).expect("encode prores"); - let mut w = avi::AviWriter::new( - std::io::Cursor::new(Vec::new()), - vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 24, 1))], - avi::MuxOptions::default(), - ) - .expect("avi writer"); - w.write_chunk(0, &pkt, true).expect("write prores chunk"); - w.finish().expect("finish avi").into_inner() + let mut cfg = EncoderConfig::new(Profile::P4444, 16, 16); + cfg.encode_alpha = with_alpha; + cfg.threads = false; + let mut enc = Encoder::with_config(cfg); + let frame = ProResFrame { + width: 16, + height: 16, + chroma: ChromaFormat::Yuv444, + bit_depth: 10, + y: vec![512; 256], + cb: vec![512; 256], + cr: vec![512; 256], + alpha: with_alpha.then(|| vec![512; 256]), + interlace: Interlace::Progressive, + color: ProResColor::default(), + aspect_ratio: 0, + frame_rate_code: 0, }; + let pkt = enc.encode(&frame).expect("encode prores"); + let mut w = avi::AviWriter::new( + std::io::Cursor::new(Vec::new()), + vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 24, 1))], + avi::MuxOptions::default(), + ) + .expect("avi writer"); + if invalid_first { + w.write_chunk(0, &[0], true).expect("write nonempty invalid first chunk"); + } + w.write_chunk(0, &pkt, true).expect("write prores chunk"); + w.finish().expect("finish avi").into_inner() + } - let alpha_src = open_bytes("alpha.avi", Arc::from(encode_prores_avi(true))).expect("recognized").expect("opened"); + #[test] + fn avi_prores_coded_alpha_parity() { + let alpha_src = open_bytes("alpha.avi", Arc::from(generated_avi_prores(true, false))).expect("recognized").expect("opened"); assert!(alpha_src.info().video.as_ref().unwrap().has_alpha); let frame = alpha_src.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode alpha frame"); assert!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. })); - let opaque_src = open_bytes("opaque.avi", Arc::from(encode_prores_avi(false))).expect("recognized").expect("opened"); + let opaque_src = open_bytes("opaque.avi", Arc::from(generated_avi_prores(false, false))).expect("recognized").expect("opened"); assert!(!opaque_src.info().video.as_ref().unwrap().has_alpha); let frame = opaque_src.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode opaque frame"); assert!(matches!(frame.data, PixelData::Yuv16 { alpha: None, .. })); } + + #[test] + fn avi_prores_unreadable_first_alpha_header_keeps_shared_playback() { + use crate::stream::{DecodedFrame, MediaSource as Opened}; + use effectcraft_project::AlphaMode; + + let bytes: Arc<[u8]> = generated_avi_prores(true, true).into(); + let demuxed = avi::open(bytes.as_ref()).expect("generated AVI"); + let video = &demuxed.streams[0]; + assert_eq!(video.codec_params().codec, CodecId::ProRes); + assert_eq!((video.rate, video.scale), (24, 1)); + assert_eq!(video.chunks.len(), 2); + assert_eq!(video.chunks[0].size, 1); + assert!(video.keyframes_known && video.chunks[1].key); + + let path = "invalid-first-prores.avi"; + let opened = crate::stream::open_bytes(path, bytes.clone()).expect("first unreadable header does not reject AVI"); + let Opened::Craft(shared) = &opened else { panic!("AVI remains on the shared reader") }; + assert!(!shared.info().video.as_ref().unwrap().has_alpha); + assert_eq!(crate::probe_bytes(path, bytes).unwrap().alpha, AlphaMode::Ignore); + + let later = effectcraft_time::Tick(craft_time::TICKS_PER_SECOND / 24); + let DecodedFrame::Craft(frame) = opened.video_frame(later, 1.0).expect("indexed second keyframe remains playable") else { + panic!("expected a shared frame"); + }; + assert_eq!((frame.width, frame.height, frame.pts.0), (16, 16, later.0)); + assert!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. })); + } + + #[test] + fn oversized_prores_alpha_probe_refuses_without_reading() { + let mut read_count = 0; + let alpha = prores_has_alpha(MAX_PRORES_ALPHA_SAMPLE_BYTES + 1, || { + read_count += 1; + None + }); + assert_eq!(alpha, None); + assert_eq!(read_count, 0); + } } From 8de16e41ba9333cab009e38bfb9cf54076c79958 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:14:13 +0700 Subject: [PATCH 353/393] media: preserve APV fallback outside the guarded MP4 subset (#4039) Co-authored-by: Codex --- crates/media/Cargo.toml | 2 + crates/media/src/craft_source.rs | 420 +++++++++++++++++++++++++++++-- 2 files changed, 402 insertions(+), 20 deletions(-) diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index cf93c6861..5c6e728db 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -54,3 +54,5 @@ tempfile = { workspace = true } effectcraft-effects = { workspace = true } # Pure-Rust AAC test fixture encoding (no external ffmpeg dependency). craft-audio = { workspace = true, features = ["aac-encode"] } +# APV import parity fixtures use the existing shared encoder. +craft-video = { workspace = true, features = ["apv-encode"] } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 2ea8a1440..64d1746bd 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -9,8 +9,9 @@ //! - **ISO-BMFF (`MP4`/`MOV`/`M4A`, video+audio & audio-only)**: //! - Shared (`craft-media::isobmff` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes` (coded alpha via `craft_video::prores::probe`, #3999), `Dnxhd`, -//! `Mpeg2Video`; audio `Aac`, `Alac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. -//! - Fallback (`filmcraft-codecs`): `Mjpeg`, `Mpeg4Video`, `Ffv1`, `Apv`, or unsupported audio. +//! `Mpeg2Video`, and strictly admitted video-only `Apv` MP4; +//! audio `Aac`, `Alac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. +//! - Fallback (`filmcraft-codecs`): `Mjpeg`, `Mpeg4Video`, `Ffv1`, other `Apv`, or unsupported audio. //! - **Matroska / WebM (`MKV`/`MKA`/`WebM`, video+audio & audio-only)**: //! - Shared (`craft-media::matroska` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Opus`, `Ac3`, @@ -68,6 +69,12 @@ const MAX_PRORES_ALPHA_SAMPLE_BYTES: u32 = 32 * 1024 * 1024; /// existing colour policy; the ProRes header parser requires the complete declared frame. const MAX_MXF_PRORES_COLOR_SAMPLE_BYTES: u32 = 4 * 1024 * 1024; +/// Only migrate APV MP4 files with bounded complete access-unit reads. +const MAX_SHARED_APV_SAMPLE_BYTES: u32 = 32 * 1024 * 1024; +// Match the Film GOP cache's per-source decoded-plane ceiling. +const MAX_SHARED_APV_CACHE_BYTES: usize = 384 << 20; +const ISOBMFF_IDENTITY_MATRIX: [i32; 9] = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000]; + fn worker_cap() -> usize { std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS) } @@ -83,16 +90,7 @@ fn prores_has_alpha(packet_size: u32, read: impl FnOnce() -> Option>) -> 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 - | CodecId::Ffv1 - | CodecId::Apv + CodecId::H264 | CodecId::Hevc | CodecId::Av1 | CodecId::Vp9 | CodecId::Vp8 | CodecId::ProRes | CodecId::Dnxhd | CodecId::Mpeg2Video | CodecId::Ffv1 ) } @@ -792,6 +790,69 @@ fn isobmff_timecode_origin(file: &Mp4File, video_idx: usize, video_rate: FrameRa i64::try_from(i128::from(tc.start_frame?) - delta / divisor).ok().filter(|&origin| origin >= 0) } +/// Admit only the APV MP4 shape whose timing and explicit color do not need the legacy +/// edit-list, snap/rebase or inferred-color policies. Inspect the existing index only; +/// APV's auxiliary alpha is per access unit and must still be decoded from each frame. +fn simple_mp4_apv_profile(file: &Mp4File, track: &isobmff::Track) -> Option { + use craft_video::apv::Profile; + if file.major_brand.0 != *b"isom" || file.fragmented || file.tracks.len() != 1 || !track.edits.is_empty() || track.edit_offset != 0 { + return None; + } + let [entry] = track.entries.as_slice() else { return None }; + let isobmff::CodecConfig::Apv(cfg) = &entry.codec else { return None }; + let video = entry.video.as_ref()?; + let profile = Profile::from_idc(cfg.profile_idc)?; + // The parser also accepts omitted/incomplete configuration fields. A simple complete + // version-1 record has a single primary-frame descriptor, optionally with four color bytes. + let record_size = if cfg.color_description_present { 22 } else { 18 }; + if !matches!(profile, Profile::P422_10 | Profile::P4444_10) + || cfg.raw_record.len() != record_size + || !cfg.raw_record.starts_with(&[1, 1, 1, 1]) + || cfg.bit_depth_minus8 != 2 + || cfg.chroma_format_idc != profile.default_chroma().idc() + || cfg.frame_width == 0 + || cfg.frame_height == 0 + || (cfg.frame_width, cfg.frame_height) != (u32::from(video.width), u32::from(video.height)) + || (track.width, track.height) != (cfg.frame_width, cfg.frame_height) + || video.clean_aperture.is_some() + || video.mastering_display.is_some() + || video.content_light.is_some() + || video.pixel_aspect.is_some_and(|par| par != (1, 1)) + || track.matrix != ISOBMFF_IDENTITY_MATRIX + || !matches!(video.color.as_ref(), Some(isobmff::ColorInfo::Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false })) + { + return None; + } + let step = track.samples.first()?.duration; + if step == 0 { + return None; + } + let rate = FrameRate::COMMON.into_iter().find(|r| i128::from(track.timescale) * i128::from(r.den) == i128::from(step) * i128::from(r.num))?; + // Coarse timing needs the legacy nominal-grid snap policy before rounding. Admit only + // tracks the Film reader itself would treat as fine, using the same tick quantization. + let den = i64::from(track.timescale); + let unit = filmcraft_time::Tick::from_rational(1, 1, den); + let rate = filmcraft_time::FrameRate::new(rate.num, rate.den); + if unit.0.saturating_mul(2) >= rate.frame_duration().0 { + return None; + } + let mut pos = 0i64; + for sample in &track.samples { + if sample.description_index != 1 + || !sample.is_sync + || sample.size == 0 + || sample.size > MAX_SHARED_APV_SAMPLE_BYTES + || sample.duration != step + || sample.pts != pos + || sample.dts != pos + { + return None; + } + pos = pos.checked_add(i64::from(step))?; + } + (u64::try_from(pos).ok()? == track.duration).then_some(profile) +} + 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); @@ -810,9 +871,14 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> let (video_info, video_state, presentation, duration) = if let Some(v_idx) = video_idx { let video_track = &file.tracks[v_idx]; let video_params = video_track.codec_params(); - if !supports_video_codec(video_params.codec) { - return None; - } + let apv_profile = if video_params.codec == CodecId::Apv { + Some(simple_mp4_apv_profile(&file, video_track)?) + } else { + if !supports_video_codec(video_params.codec) { + return None; + } + 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 @@ -839,18 +905,27 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> // The coded alpha plane is authoritative for ProRes, not the MOV sample-entry depth. let sample = video_track.samples.first()?; prores_has_alpha(sample.size, || file.read_sample(&*source, v_idx, 0).ok())? + } else if let Some(profile) = apv_profile { + profile.default_chroma().has_alpha() } 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); - let codec_name = video_params.codec.name().to_string(); + let (codec_name, pixel_format, bitrate) = if let Some(profile) = apv_profile { + let format = if has_alpha { "YUVA 4:4:4:4 10-bit" } else { "YUV 4:2:2 10-bit" }; + let bytes: u128 = video_track.samples.iter().map(|sample| u128::from(sample.size)).sum(); + let bitrate = (bytes * 8 * u128::from(video_track.timescale)).checked_div(u128::from(video_track.duration)).and_then(|b| u64::try_from(b).ok()); + (profile.name().into(), format.into(), bitrate) + } else { + let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0); + (video_params.codec.name().to_string(), String::new(), bitrate) + }; 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 v_info = VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format: String::new(), color, has_alpha, bitrate, hdr: None }; + let v_info = VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format, color, has_alpha, bitrate, hdr: None }; let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation, aperture }, duration) } else { @@ -866,6 +941,7 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> }; let start_timecode = video_idx.zip(video_info.as_ref()).and_then(|(idx, info)| isobmff_timecode_origin(&file, idx, info.frame_rate)); + let apv_cache = video_idx.is_some_and(|idx| matches!(file.tracks[idx].codec(), Some(isobmff::CodecConfig::Apv(_)))).then(ApvFrameCache::default); let container = ContainerFile::Isobmff(file); let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; if video_info.is_none() && audio_tracks.is_empty() { @@ -884,7 +960,16 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> file_size: Some(source.len()), }; - Some(Ok(Arc::new(CraftMediaSource { info, source, file: container, video_track_idx: video_idx, presentation, video: video_state, audio_tracks }))) + Some(Ok(Arc::new(CraftMediaSource { + info, + source, + file: container, + video_track_idx: video_idx, + presentation, + video: video_state, + audio_tracks, + apv_cache, + }))) } fn open_matroska(name: &str, source: SharedBytes) -> Option> { @@ -978,6 +1063,7 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option presentation: FramePresentation { container_color, par, rotation, aperture: None }, video: video_state, audio_tracks, + apv_cache: None, }))) } @@ -1023,6 +1109,7 @@ fn finish_container_source( presentation: FramePresentation { container_color: None, par: (1, 1), rotation: 0, aperture: None }, video: video_state, audio_tracks, + apv_cache: None, }))) } @@ -1192,6 +1279,7 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio presentation, video: video_state, audio_tracks, + apv_cache: None, }))) } @@ -1442,6 +1530,83 @@ struct CraftMediaSource { presentation: FramePresentation, video: Option>, audio_tracks: Vec, + apv_cache: Option, +} + +#[derive(Default)] +struct ApvFrameCache { + entries: Mutex>, + decode_gate: Mutex<()>, +} + +fn apv_cache_fits_pair(a: usize, b: usize) -> bool { + a.saturating_add(b) <= MAX_SHARED_APV_CACHE_BYTES +} + +impl ApvFrameCache { + fn get(&self, pts: i64) -> Option> { + let entries = self.entries.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + entries.iter().find(|entry| entry.pts == pts).map(|entry| entry.frame.clone()) + } + + fn get_or_decode(&self, pts: i64, decode: impl FnOnce() -> Result) -> Result> { + if let Some(frame) = self.get(pts) { + return Ok(frame); + } + // The short cache lock is not held while waiting or decoding. The decoder and + // pixel adapter must be strictly serial here: Rayon could reenter the same source. + let _gate = self.decode_gate.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(frame) = self.get(pts) { + return Ok(frame); + } + let frame = Arc::new(decode()?); + let mut entries = self.entries.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if entries.len() == 2 { + entries.remove(0); + } + if entries.first().is_some_and(|other| !apv_cache_fits_pair(other.frame.byte_size(), frame.byte_size())) { + entries.clear(); + } + // Like Film, keep the current frame even if it alone exceeds the cache ceiling. + entries.push(CachedFrame { pts, draft: false, frame: frame.clone() }); + Ok(frame) + } +} + +impl CraftMediaSource { + fn apv_frame(&self, track: &isobmff::Track, video_idx: usize, cache: &ApvFrameCache, time: Tick) -> Result> { + // The admitted fine timebase uses Film's nearest-unit lookup, not the floor used + // by other shared routes. Track selection timing is distinct from the frame's pts. + let lookup = filmcraft_time::Tick(time.0.max(0)).to_rational_round(1, i64::from(track.timescale)); + let target = track.sample_at_presentation_time(lookup).ok_or_else(|| MediaError::Decode("no video samples".into()))?; + let pts = track.samples[target].pts; + cache.get_or_decode(pts, || { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + // This is an in-memory copy or positional file read, then a serial decode + // and in-thread plane conversion; none can schedule a nested render. + let packet = self.file.read_sample(&*self.source, video_idx, target)?; + let options = craft_video::apv::DecodeOptions { threads: false, ..Default::default() }; + let mut decoded = craft_video::apv::decode_frame_with(&packet, &options).map_err(|e| MediaError::Decode(e.to_string()))?; + if decoded.chroma == craft_video::apv::ChromaFormat::Monochrome { + // A primary AU with an unexpected monochrome profile is still playable in Film: + // its adapter expands it to neutral 4:4:4 without dropping any auxiliary alpha. + let neutral = 1u16 << decoded.bit_depth.saturating_sub(1); + decoded.chroma = craft_video::apv::ChromaFormat::Yuv444; + decoded.cb = vec![neutral; decoded.y.len()]; + decoded.cr = vec![neutral; decoded.y.len()]; + } + let decoded = DecodedVideoFrame::try_from(decoded).map_err(|e| MediaError::Decode(e.to_string()))?; + let mut frame = to_craft_frame(decoded, self.presentation, Tick::ZERO)?; + // Film's explicit nclx wins for APV YUV, even when the AU says full range. + // The shared converter preserves both coded and per-AU auxiliary alpha. + if let Some(color) = self.presentation.container_color { + frame.color = color; + } + Ok(frame) + }) + } } impl MediaSource for CraftMediaSource { @@ -1453,6 +1618,12 @@ impl MediaSource for CraftMediaSource { let (Some(video_idx), Some(video_mutex)) = (self.video_track_idx, &self.video) else { return Err(MediaError::NoStream("video")); }; + if let Some(cache) = &self.apv_cache + && let ContainerFile::Isobmff(file) = &self.file + && let Some(track) = file.tracks.get(video_idx) + { + return self.apv_frame(track, video_idx, cache, req.time); + } let (target_idx, target_pts) = self.file.target_sample(video_idx, req.time).ok_or_else(|| MediaError::Decode("no video samples".into()))?; let want_draft = req.scale < 0.99; @@ -2455,6 +2626,215 @@ mod tests { OpusFixture { bytes, file: ContainerFile::Matroska(Box::new(file)), offsets, params, delay: OPUS_CODEC_DELAY_NS as u64 } } + #[test] + fn apv_cache_counts_both_frames_without_allocating_8k_planes() { + let yuva_8k = 7_680usize * 4_320 * 4 * 2; + assert!(apv_cache_fits_pair(yuva_8k, MAX_SHARED_APV_CACHE_BYTES - yuva_8k)); + assert!(!apv_cache_fits_pair(yuva_8k, yuva_8k)); + assert!(!apv_cache_fits_pair(usize::MAX, 1)); + } + + #[test] + fn apv_cache_releases_entry_lock_and_does_not_cache_errors_or_duplicate_a_hit() { + let cache = ApvFrameCache::default(); + let failed = cache.get_or_decode(1, || { + assert!(cache.entries.try_lock().is_ok()); + assert!(matches!(cache.decode_gate.try_lock(), Err(std::sync::TryLockError::WouldBlock))); + Err(MediaError::Cancelled) + }); + assert!(matches!(failed, Err(MediaError::Cancelled))); + let frame = cache + .get_or_decode(1, || { + assert!(cache.entries.try_lock().is_ok()); + Ok(VideoFrame { + width: 1, + height: 1, + data: PixelData::Yuv16 { + planes: [Arc::new(vec![200]), Arc::new(vec![512]), Arc::new(vec![512])], + chroma: Chroma::C444, + bits: 10, + alpha: None, + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }) + }) + .unwrap(); + let hit = cache.get_or_decode(1, || panic!("a cache hit must not decode again")).unwrap(); + assert!(Arc::ptr_eq(&frame, &hit)); + } + + struct ApvFixture { + bytes: Arc<[u8]>, + y: Vec>, + alpha: Vec>>, + } + + fn generated_apv_mp4(brand: isobmff::Brand, coded_alpha: bool, incomplete_config: bool, coarse_timebase: bool, rec709: bool) -> ApvFixture { + use std::io::Cursor; + + use craft_video::apv::{Encoder, EncoderConfig, Frame, Profile, decode_frame}; + use isobmff::{ApvConfig, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + let profile = if coded_alpha { Profile::P4444_10 } else { Profile::P422_10 }; + let mut config = EncoderConfig::new(profile, 16, 16); + config.qp = Some(16); + // The APV header and apvC both disagree with the authoritative explicit nclx. + config.color_description_present = true; + config.color.primaries = 9; + config.color.transfer = 16; + config.color.matrix = 9; + config.color.full_range = true; + let mut encoder = Encoder::with_config(config).unwrap(); + let mut record = encoder.decoder_config_record(); + if incomplete_config { + // The legacy decoder takes its dimensions from the AU rather than this record. + record[8..12].fill(0); + } + let mut entry = SampleEntry::apv(ApvConfig::from_record(record).unwrap(), 16, 16); + entry.video.as_mut().unwrap().color = Some(if rec709 { + isobmff::ColorInfo::Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false } + } else { + isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: true } + }); + let mut writer = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(brand)).unwrap(); + let (timescale, duration) = if coarse_timebase { (25, 1) } else { (25_000, 1_000) }; + let idx = writer.add_track(TrackConfig::new(entry, timescale)).unwrap(); + + let mut expected_y = Vec::new(); + let mut expected_alpha = Vec::new(); + for (i, y) in [160, 720].into_iter().enumerate() { + let mut frame = Frame::new(16, 16, profile.default_chroma(), 10, coded_alpha); + frame.y.fill(y); + if let Some(alpha) = frame.alpha.as_mut() { + alpha.fill(if i == 0 { 256 } else { 768 }); + } + let mut au = encoder.encode(&frame).unwrap(); + let mut alpha = if coded_alpha { decode_frame(&au).unwrap().alpha } else { None }; + if i == 1 && !coded_alpha { + let mono_profile = Profile::P400_10; + let mut mono_encoder = Encoder::new(mono_profile, 16, 16).unwrap(); + let mut mono = Frame::new(16, 16, mono_profile.default_chroma(), 10, false); + mono.y.fill(480); + let alpha_au = mono_encoder.encode(&mono).unwrap(); + alpha = Some(decode_frame(&alpha_au).unwrap().y); + // The first generated monochrome PBU becomes the matching auxiliary alpha. + let len = u32::from_be_bytes(alpha_au[4..8].try_into().unwrap()); + au.extend_from_slice(&len.to_be_bytes()); + au.push(27); + au.extend_from_slice(&alpha_au[9..8 + len as usize]); + } + expected_y.push(decode_frame(&au).unwrap().y); + expected_alpha.push(alpha); + writer.write_sample(idx, WriteSample { data: &au, duration, composition_offset: 0, is_sync: true }).unwrap(); + } + ApvFixture { bytes: writer.finish().unwrap().into_inner().into(), y: expected_y, alpha: expected_alpha } + } + + fn assert_apv_seek_parity(shared: &crate::stream::MediaSource, film: &crate::stream::MediaSource, step: i64, y: &[Vec], alpha: &[Option>]) { + use crate::stream::DecodedFrame; + + let boundary = step - craft_time::TICKS_PER_SECOND / 50_000; + for (at, i) in [(step, 1), (0, 0), (boundary - 1, 0), (boundary, 1), (step - 1, 1), (0, 0)] { + let time = effectcraft_time::Tick(at); + let DecodedFrame::Craft(new) = shared.video_frame(time, 1.0).unwrap() else { panic!("shared frame") }; + let DecodedFrame::Film(old) = film.video_frame(time, 1.0).unwrap() else { panic!("legacy frame") }; + assert_eq!(new.color, ColorInfo::REC709); + assert_eq!(old.color, filmcraft_color::ColorInfo::REC709); + // Film carries the presentation position in its cache key, not its APV pixel payload. + assert_eq!(old.pts.0, 0); + assert_eq!(new.pts.0, old.pts.0); + let PixelData::Yuv16 { planes: new_planes, bits, alpha: new_alpha, .. } = &new.data else { panic!("APV 10-bit YUV frame") }; + let filmcraft_frame::PixelData::Yuv16 { planes: old_planes, bits: old_bits, alpha: old_alpha, .. } = &old.data else { + panic!("legacy APV 10-bit YUV frame") + }; + assert_eq!(*bits, 10); + assert_eq!(bits, old_bits); + assert_eq!(new_planes[0].as_ref(), &y[i]); + for (new, old) in new_planes.iter().zip(old_planes) { + assert_eq!(new.as_ref(), old.as_ref()); + } + assert_eq!(new_alpha.as_deref(), alpha[i].as_ref()); + assert_eq!(new_alpha.as_deref(), old_alpha.as_deref()); + } + } + + #[test] + fn simple_apv_mp4_import_preserves_film_color_alpha_and_backward_seek() { + use crate::stream::MediaSource as Opened; + use effectcraft_project::{AlphaMode, ColorSpace}; + + let step = craft_time::TICKS_PER_SECOND / 25; + for coded_alpha in [false, true] { + let ApvFixture { bytes, y, alpha } = generated_apv_mp4(isobmff::Brand::Mp4, coded_alpha, false, false, true); + let path = "paired-apv.mp4"; + assert_ne!(y[0], y[1], "regression requires visibly different frames"); + assert_eq!(alpha[0].is_some(), coded_alpha); + assert!(alpha[1].is_some(), "late auxiliary/coded alpha fixture must be live"); + let direct_film = filmcraft_codecs::open_bytes(path, bytes.clone()).unwrap(); + let old_footage = crate::probe::footage_from_info(path, direct_film.info()); + let shared = crate::stream::open_bytes(path, bytes.clone()).unwrap(); + let Opened::Craft(source) = &shared else { panic!("admitted APV must use shared decoding") }; + let footage = crate::probe_bytes(path, bytes).unwrap(); + assert_eq!((footage.width, footage.height), (16, 16)); + assert_eq!(footage.frame_rate, old_footage.frame_rate); + assert_eq!(footage.native_rate.unwrap_or(footage.frame_rate), old_footage.native_rate.unwrap_or(old_footage.frame_rate)); + assert_eq!(footage.duration, old_footage.duration); + assert_eq!(footage.duration.0, step * 2); + assert_eq!(footage.pixel_aspect, old_footage.pixel_aspect); + assert_eq!(footage.file_timecode, None); + assert_eq!(footage.file_timecode, old_footage.file_timecode); + assert_eq!(footage.alpha, if coded_alpha { AlphaMode::Straight } else { AlphaMode::Ignore }); + assert_eq!(footage.alpha, old_footage.alpha); + assert_eq!(footage.color_profile, Some(ColorSpace::Rec709)); + assert_eq!(footage.color_profile, old_footage.color_profile); + assert_eq!(footage.codec, old_footage.codec); + let shared_video = source.info().video.as_ref().unwrap(); + let film_video = direct_film.info().video.as_ref().unwrap(); + assert_eq!(shared_video.pixel_format, film_video.pixel_format); + assert_eq!(shared_video.bitrate, film_video.bitrate); + + let film = Opened::Film(direct_film); + assert_apv_seek_parity(&shared, &film, step, &y, &alpha); + } + } + + #[test] + fn apv_mov_incomplete_apvc_and_coarse_timebase_keep_the_playable_film_route() { + use crate::stream::MediaSource as Opened; + for (brand, incomplete, coarse) in [(isobmff::Brand::Mov, false, false), (isobmff::Brand::Mp4, true, false), (isobmff::Brand::Mp4, false, true)] { + let bytes = generated_apv_mp4(brand, false, incomplete, coarse, true).bytes; + let parsed = isobmff::open(bytes.as_ref()).unwrap(); + assert_eq!(parsed.is_quicktime, brand == isobmff::Brand::Mov); + // Byte routing, independent of the apparent extension. + let opened = crate::stream::open_bytes("unadmitted-apv.mp4", bytes).unwrap(); + assert!(matches!(opened, Opened::Film(_))); + assert_eq!(opened.video_frame(effectcraft_time::Tick::ZERO, 1.0).unwrap().width(), 16); + } + } + + #[test] + fn clean_pq_apv_mp4_keeps_the_playable_film_route() { + use crate::stream::MediaSource as Opened; + use effectcraft_project::ColorSpace; + + // Same fine-timebase isom encode as the admitted test, differing only in nclx. + let bytes = generated_apv_mp4(isobmff::Brand::Mp4, false, false, false, false).bytes; + let parsed = isobmff::open(bytes.as_ref()).unwrap(); + assert_eq!(parsed.major_brand.0, *b"isom"); + assert_eq!(parsed.tracks[0].timescale, 25_000); + assert!(matches!( + parsed.tracks[0].video().and_then(|video| video.color.as_ref()), + Some(isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: true }) + )); + let path = "pq-apv.mp4"; + let opened = crate::stream::open_bytes(path, bytes.clone()).unwrap(); + assert!(matches!(opened, Opened::Film(_))); + assert_eq!(opened.video_frame(effectcraft_time::Tick::ZERO, 1.0).unwrap().width(), 16); + assert_eq!(crate::probe_bytes(path, bytes).unwrap().color_profile, Some(ColorSpace::Rec2100Pq)); + } + fn generated_opus_mp4(lead: usize) -> OpusFixture { use std::io::Cursor; @@ -3739,7 +4119,7 @@ mod tests { #[test] fn ffv1_and_apv_video_codecs_route_through_craft_video() { assert!(supports_video_codec(CodecId::Ffv1)); - assert!(supports_video_codec(CodecId::Apv)); + assert!(!supports_video_codec(CodecId::Apv), "APV requires the guarded ISO-BMFF admission path"); let template = craft_video::ffv1::Frame { width: 16, From c22f034bf3638f8c10e263c8913327b9727aaf59 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:30:25 +0700 Subject: [PATCH 354/393] media: preserve Matroska FFV1 metadata without CodecPrivate (#4041) Co-authored-by: Codex --- crates/media/src/craft_source.rs | 87 ++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 64d1746bd..db07f56f5 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -993,6 +993,11 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option if !video_track.frames_readable() { return None; } + // Native FFV1 without CodecPrivate cannot initialize the shared v3 decoder. + // Keep FilmCraft's metadata at open; an unsupported read stays a playback error. + if video_track.codec_private.is_empty() && matches!(&video_track.codec, matroska::Codec::Other(id) if id == "V_FFV1") { + return None; + } let video_params = video_track.codec_params(); if !supports_video_codec(video_params.codec) { return None; @@ -3147,6 +3152,88 @@ mod tests { assert_eq!(c.range, Range::Limited); } + #[test] + #[cfg(any(unix, windows))] + fn matroska_ffv1_missing_config_keeps_legacy_probe() { + use crate::stream::{DecodedFrame, MediaSource as Opened}; + use craft_video::ffv1::{Colorspace, Encoder, EncoderConfig, Frame}; + + let mut frame = Frame { + width: 16, + height: 16, + colorspace: Colorspace::YCbCr, + bit_depth: 8, + chroma_shift: (1, 1), + planes: vec![vec![48; 256], vec![96; 64], vec![160; 64]], + }; + let encoder = Encoder::new(&frame, EncoderConfig::default()).expect("FFV1 encoder"); + let first = encoder.encode(&frame).expect("first FFV1 keyframe"); + frame.planes[0].fill(192); + let second = encoder.encode(&frame).expect("second FFV1 keyframe"); + + // The control changes only the container configuration, not the two coded keyframes. + let mux = |configuration| -> Arc<[u8]> { + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1"); + track.video_size = Some((16, 16)); + track.default_duration_ns = Some(40_000_000); + track.codec_private = configuration; + let mut mux = matroska::MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default()).expect("MKV writer"); + mux.write_frame(0, 0, true, &first, None).expect("write first keyframe"); + mux.write_frame(0, 40_000_000, true, &second, None).expect("write second keyframe"); + mux.finish().expect("finish MKV").into_inner().into() + }; + let configured = mux(encoder.config_record()); + let missing = mux(Vec::new()); + let directory = tempfile::tempdir().expect("FFV1 fixture directory"); + let configured_path = directory.path().join("configured.mkv"); + let missing_path = directory.path().join("no-config.mkv"); + std::fs::write(&configured_path, &configured).expect("write configured fixture"); + std::fs::write(&missing_path, &missing).expect("write no-config fixture"); + + let configured_probe = crate::probe(&configured_path).expect("public probe of configured FFV1"); + assert!(configured_probe.has_video); + assert_eq!((configured_probe.width, configured_probe.height), (16, 16)); + assert_eq!((configured_probe.frame_rate.num, configured_probe.frame_rate.den), (25, 1)); + let opened = crate::stream::open_source(&configured_path).expect("open in place").0.expect("open configured FFV1"); + assert!(matches!(&opened, Opened::Craft(_))); + let zero = effectcraft_time::Tick::ZERO; + let later = effectcraft_time::Tick(craft_time::TICKS_PER_SECOND / 25); + for (pts, luma) in [(zero, 48), (later, 192), (zero, 48)] { + let frame = match opened.video_frame(pts, 1.0).expect("decode configured FFV1") { + DecodedFrame::Craft(frame) => Some(frame), + DecodedFrame::Film(_) => None, + } + .expect("decoded through the shared FFV1 reader"); + assert_eq!(frame.pts.0, pts.0); + assert!(matches!(&frame.data, PixelData::Yuv8 { planes, chroma: Chroma::C420, alpha: None } + if planes[0].as_slice() == [luma; 256] && planes[1].as_slice() == [96; 64] && planes[2].as_slice() == [160; 64])); + } + + let name = "no-config.mkv"; + let legacy = filmcraft_codecs::open_bytes(name, missing.clone()).expect("legacy FFV1 metadata opens without config"); + let legacy_probe = crate::probe::footage_from_info(name, legacy.info()); + let legacy_error = legacy + .video_frame(filmcraft_media::FrameRequest { time: filmcraft_time::Tick::ZERO, scale: 1.0 }) + .err() + .map(crate::MediaError::from) + .expect("FilmCraft does not play FFV1"); + assert!(matches!(&legacy_error, crate::MediaError::Unsupported(message) if message.contains("no decoder"))); + + let missing_probe = crate::probe(&missing_path).expect("public probe preserves metadata without config"); + let memory_probe = crate::probe_bytes(name, missing).expect("public memory probe preserves metadata without config"); + for probe in [missing_probe, memory_probe] { + assert!(probe.has_video); + assert_eq!((probe.width, probe.height), (legacy_probe.width, legacy_probe.height)); + assert_eq!(probe.frame_rate, legacy_probe.frame_rate); + assert_eq!(probe.duration, legacy_probe.duration); + assert_eq!(probe.codec, legacy_probe.codec); + } + let opened = crate::stream::open_source(&missing_path).expect("open in place").0.expect("open FFV1 metadata without config"); + assert!(matches!(&opened, Opened::Film(_))); + let err = opened.video_frame(zero, 1.0).err().expect("unsupported is deferred to playback"); + assert_eq!(err.to_string(), legacy_error.to_string()); + } + #[test] fn rotate_frame_swaps_dimensions_and_orients_planes() { let frame = VideoFrame { From f4d45dfef3a280d96aff1d4eb5f1950160adefc2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:35:49 +0700 Subject: [PATCH 355/393] media: fence fractional MOV PCM edits on the packet clock (#778) (#4031) Co-authored-by: Codex Co-authored-by: FredApps --- crates/media/src/craft_source.rs | 126 ++++++++++++++++++++++++++++--- 1 file changed, 114 insertions(+), 12 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index db07f56f5..eb5c38a33 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -332,6 +332,34 @@ impl ContainerFile { let leading = u128::from(leading_duration); offset(leading)..offset(leading + u128::from(media.segment_duration)) } + + /// Exclusive native packet position of the PCM edit's end. Unlike audio_edit_range, + /// this follows the demuxer's truncated packet placement, not the movie output clock. + fn pcm_edit_packet_end(&self, track_idx: usize, native_rate: u32) -> Option { + let Self::Isobmff(file) = self else { return None }; + let track = file.tracks.get(track_idx)?; + // pcm_chunked alone describes how the sample table was indexed from entry one. + // With several descriptions the decoder may have selected a different entry. + let [entry] = track.entries.as_slice() else { return None }; + if !matches!(entry.codec, isobmff::CodecConfig::Pcm(_)) + || !track.pcm_chunked + || native_rate == 0 + || track.timescale != native_rate + || file.timescale == 0 + { + return None; + } + let (leading, media) = unit_rate_media_edit(&track.edits)?; + let movie_clock = u128::from(file.timescale); + let native_clock = u128::from(native_rate); + let packet_start = i128::from(track.edit_offset).checked_add(i128::from(media.media_time))?; + let expected_start = i128::try_from(u128::from(leading) * native_clock / movie_clock).ok()?; + if packet_start != expected_start { + return None; + } + let duration = i128::try_from((u128::from(media.segment_duration) * native_clock).div_ceil(movie_clock)).ok()?; + i64::try_from(packet_start.checked_add(duration)?).ok() + } } /// Where the container puts one audio packet, for [`contiguous_starts`]. @@ -1717,18 +1745,34 @@ impl MediaSource for CraftMediaSource { let decoded = match &entry.backend { AudioBackend::Decoder { seek_preroll_samples, state: state_mutex } => { - let mut state = state_mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - decode_audio_range( - &self.file, - &*self.source, - entry.track_idx, - native_rate, - channels_count, - *seek_preroll_samples, - &mut state, - native_start, - native_frames, - )? + let packet_frames = self + .file + .pcm_edit_packet_end(entry.track_idx, native_rate) + .map_or(native_frames, |end| usize::try_from((i128::from(end) - i128::from(native_start)).max(0)).unwrap_or(usize::MAX).min(native_frames)); + let mut channels = if packet_frames == 0 && native_frames != 0 { + vec![Vec::new(); channels_count] + } else { + let mut state = state_mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + decode_audio_range( + &self.file, + &*self.source, + entry.track_idx, + native_rate, + channels_count, + *seek_preroll_samples, + &mut state, + native_start, + packet_frames, + )? + }; + // A direct read still owes the full output window. For a resampled read, keep + // the clipped buffer short so its last valid sample remains the one-sided guard. + if sample_rate == native_rate && packet_frames < native_frames { + for channel in &mut channels { + channel.resize(native_frames, 0.0); + } + } + channels } AudioBackend::MxfPcm { presented_start, presented_len } => { if filmcraft_media::cancel::cancelled() { @@ -3116,6 +3160,64 @@ mod tests { } } + #[test] + fn mov_pcm_fractional_empty_edit_excludes_packet_tail() { + const RATE: u32 = 44_100; + let mut samples = vec![0i16; 1_024]; + samples[600] = 16_384; + samples[601] = -8_192; + let mux = |leading_ms| { + edited_pcm_mov( + RATE, + &samples, + vec![ + isobmff::Edit { segment_duration: leading_ms, media_time: -1, media_rate: 0x0001_0000 }, + isobmff::Edit { segment_duration: 2, media_time: 512, media_rate: 0x0001_0000 }, + ], + ) + }; + let bytes: Arc<[u8]> = mux(9).into(); + let demuxed = isobmff::open(bytes.as_ref()).expect("generated PCM MOV"); + assert_eq!(demuxed.timescale, 1_000); + assert_eq!(demuxed.tracks[0].timescale, RATE); + assert!(demuxed.tracks[0].pcm_chunked); + assert_eq!(demuxed.tracks[0].edit_offset, -116); + let source = open_bytes("fractional-edit.mov", bytes).expect("shared MOV route").expect("open mapped PCM"); + let read = |start, frames, rate| source.audio(start, frames, rate).expect("direct shared PCM read").channels.remove(0); + + // The output range still includes native position 485. The source edit ends + // before raw frame 601 (position 485), but includes raw frame 600 (position 484). + assert_eq!(read(484, 3, RATE), [0.5, 0.0, 0.0]); + assert_eq!(read(485, 2, RATE), [0.0, 0.0], "packet-content-only tail"); + assert_eq!(read(484, 1, RATE), [0.5], "backward seek retains the last visible source sample"); + assert_eq!(read(968, 4, RATE * 2), [0.5, 0.5, 0.0, 0.0], "do not interpolate with the excluded sample"); + + let aligned = open_bytes("aligned-edit.mov", mux(10).into()).expect("shared MOV").expect("aligned clocks"); + assert_eq!(aligned.audio(529, 3, RATE).expect("aligned PCM").channels[0], [0.5, 0.0, 0.0]); + let unedited = open_bytes("no-edit.mov", edited_pcm_mov(RATE, &samples, Vec::new()).into()).expect("shared MOV").expect("no edit"); + assert_eq!(unedited.audio(600, 2, RATE).expect("unedited PCM").channels[0], [0.5, -0.25]); + + let mut mixed = demuxed.clone(); + let track = &mut mixed.tracks[0]; + let mut non_pcm = track.entries[0].clone(); + non_pcm.codec = isobmff::CodecConfig::Mp3; + track.entries.push(non_pcm.clone()); + track.samples[0].description_index = 2; + assert_ne!(track.codec_params().codec, CodecId::Pcm, "first sample selects the other description"); + assert_eq!(ContainerFile::Isobmff(mixed.clone()).pcm_edit_packet_end(0, RATE), None, "mixed descriptions"); + let track = &mut mixed.tracks[0]; + track.entries = vec![non_pcm]; + track.samples[0].description_index = 1; + assert_eq!(ContainerFile::Isobmff(mixed).pcm_edit_packet_end(0, RATE), None, "sole non-PCM description"); + + let file = ContainerFile::Isobmff(demuxed.clone()); + assert_eq!(file.pcm_edit_packet_end(0, RATE), Some(485)); + assert_eq!(file.pcm_edit_packet_end(0, 48_000), None, "different track and native clocks"); + let mut parsed = demuxed; + parsed.tracks[0].edits[1].segment_duration = u64::MAX; + assert_eq!(ContainerFile::Isobmff(parsed).pcm_edit_packet_end(0, RATE), None, "unrepresentable native end"); + } + #[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 }); From fae7ad76412f29b104a4f070373020f70bd9b479 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:17:12 +0700 Subject: [PATCH 356/393] media: avoid nested ProRes decode work under the MOV reader lock (#4028) Co-authored-by: FredApps Co-authored-by: Codex --- crates/media/src/craft_source.rs | 97 +++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 2 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index eb5c38a33..a6fe63270 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -51,7 +51,7 @@ use craft_media_source::{ }; use craft_time::{FrameRate, Tick}; use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame}; -use craft_video::{TrackDecoder, TrackDecoderOptions}; +use craft_video::{TrackDecoder, TrackDecoderOptions, VideoError, prores}; /// Maximum worker threads per `TrackDecoder` instance. const MAX_WORKERS: usize = 8; @@ -1516,6 +1516,26 @@ struct VideoState { decoded: Vec, } +fn decode_track_packet( + decoder: &mut TrackDecoder, + is_isobmff: bool, + packet: &[u8], + pts: i64, + decode_prores: impl FnOnce(&[u8], &prores::DecodeOptions) -> prores::Result, +) -> std::result::Result, VideoError> { + if !is_isobmff || decoder.codec() != CodecId::ProRes { + return decoder.decode(packet, pts); + } + // The caller holds this source's VideoState lock. Do not let a ProRes band + // job yield to another request for the same source on the decode Rayon pool. + // ProRes packets carry a complete picture: TrackDecoder's ProRes arm adds + // the PTS to this same conversion and has no draft, reset or reorder work. + let options = prores::DecodeOptions { threads: false, ..Default::default() }; + let mut frame = DecodedVideoFrame::try_from(decode_prores(packet, &options)?)?; + frame.pts = Some(pts); + Ok(vec![frame]) +} + struct AudioTrackState { decoder: AudioTrackDecoder, audio_starts: AudioStarts, @@ -1681,6 +1701,7 @@ impl MediaSource for CraftMediaSource { } let sample_count = self.file.sample_count(video_idx); + let is_isobmff = matches!(&self.file, ContainerFile::Isobmff(_)); while !state.decoded.iter().any(|c| c.pts >= target_pts && c.draft == want_draft) { if filmcraft_media::cancel::cancelled() { return Err(MediaError::Cancelled); @@ -1689,7 +1710,8 @@ impl MediaSource for CraftMediaSource { let idx = state.next_decode_idx; let pts = self.file.sample_pts(video_idx, idx); let pkt = self.file.read_sample(&*self.source, video_idx, idx)?; - let frames = state.decoder.decode(&pkt, pts).map_err(|e| MediaError::Decode(e.to_string()))?; + let frames = + decode_track_packet(&mut state.decoder, is_isobmff, &pkt, pts, prores::decode_frame_with).map_err(|e| MediaError::Decode(e.to_string()))?; state.next_decode_idx = idx + 1; push_decoded(&mut state.decoded, frames, want_draft, self.presentation, &self.file, video_idx)?; } else if !state.flushed { @@ -3651,6 +3673,77 @@ mod tests { assert_eq!(resolve_color(ColorTags::UNSPECIFIED, color_from_mxf(&picture)), ColorInfo::REC709); } + #[test] + fn shared_prores_mov_uses_serial_packets_with_edited_frame_and_alpha_parity() { + use isobmff::{Brand, Edit, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + + let mut encoder = prores::Encoder::new(prores::Profile::P4444, 64, 48); + let mut input = prores::Frame::new(64, 48, prores::ChromaFormat::Yuv444, 12, true).expect("ProRes frame"); + let mut entry = SampleEntry::prores(isobmff::FourCc(*b"ap4h"), 64, 48); + entry.video.as_mut().expect("visual entry").pixel_aspect = Some((4, 3)); + let mut config = TrackConfig::new(entry, 1_000); + config.edits = vec![ + Edit { segment_duration: 20, media_time: -1, media_rate: 0x0001_0000 }, + Edit { segment_duration: 120, media_time: 0, media_rate: 0x0001_0000 }, + ]; + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("MOV writer"); + let track = writer.add_track(config).expect("picture track"); + let mut packets = Vec::new(); + for (luma, alpha) in [(512, 1_024), (1_536, 2_048), (3_072, 3_072)] { + input.y.fill(luma); + input.alpha.as_mut().expect("alpha input").fill(alpha); + let packet = encoder.encode(&input).expect("ProRes packet"); + writer.write_sample(track, WriteSample { data: &packet, duration: 40, composition_offset: 0, is_sync: true }).expect("MOV sample"); + packets.push(packet); + } + let bytes = writer.finish().expect("MOV finish").into_inner(); + let demuxed = isobmff::open(bytes.as_slice()).expect("MOV demux"); + assert_eq!(demuxed.tracks[track].edit_offset, 20); + let params = demuxed.tracks[track].codec_params(); + let crate::stream::MediaSource::Craft(source) = crate::stream::open_bytes("serial.mov", bytes.into()).expect("MOV opener") else { + panic!("generated ProRes cannot fall back to FilmCraft"); + }; + assert!(source.info().video.as_ref().expect("video").has_alpha); + + let mut decoder = TrackDecoder::new(¶ms).expect("ProRes decoder"); + let mut passed_serial_options = false; + let selected = decode_track_packet(&mut decoder, true, &packets[1], 40, |packet, options| { + assert!(!options.threads); + assert!(options.bit_depth.is_none()); + passed_serial_options = true; + prores::decode_frame_with(packet, options) + }) + .expect("serial packet"); + assert!(passed_serial_options, "the ISO-BMFF helper must select explicit serial decoding"); + assert_eq!(selected[0].pts, Some(40)); + + // Seek late, then backwards, then forwards. The original parallel TrackDecoder is an + // independent oracle for every plane, including alpha, of each chosen compressed frame. + let presentation = FramePresentation { container_color: None, par: (4, 3), rotation: 0, aperture: None }; + for (index, raw_pts, presented) in [(2, 80, 100), (0, 0, 20), (1, 40, 60)] { + let pts = Tick::from_units(presented, 1_000); + let actual = source.video_frame(FrameRequest::full(pts)).expect("shared MOV frame"); + let packet = &packets[index]; + let mut parallel = + decode_track_packet(&mut decoder, false, packet, raw_pts, |_, _| panic!("expected TrackDecoder")).expect("normal parallel packet"); + let expected = to_craft_frame(parallel.pop().expect("one frame"), presentation, pts).expect("parallel frame"); + assert!(parallel.is_empty()); + assert_eq!((actual.width, actual.height, actual.pts, actual.par, actual.color), (64, 48, pts, (4, 3), expected.color)); + let PixelData::Yuv16 { planes, bits, alpha: Some(alpha), .. } = &actual.data else { panic!("expected 12-bit ProRes with alpha") }; + let PixelData::Yuv16 { planes: expected_planes, bits: expected_bits, alpha: Some(expected_alpha), .. } = &expected.data else { + panic!("expected parallel ProRes with alpha"); + }; + assert_eq!((*bits, *expected_bits), (12, 12)); + assert_eq!(planes, expected_planes); + assert_eq!(alpha, expected_alpha); + assert!(alpha[0] > 0 && alpha[0] < 4_095); + } + + let regular_error = decoder.decode(&[], 0).expect_err("empty ProRes packet").to_string(); + let locked_error = decode_track_packet(&mut decoder, true, &[], 0, prores::decode_frame_with).expect_err("empty ProRes packet").to_string(); + assert_eq!(locked_error, regular_error); + } + #[test] fn mxf_descriptor_aspect_reaches_shared_probe_and_frame() { use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; From eb5fa36bcfc74abc6dbceb2fd6656f044eb46950 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 01:53:34 +0800 Subject: [PATCH 357/393] media: preserve Matroska display aspect on import (#4029) --- crates/media/src/craft_source.rs | 63 +++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index a6fe63270..bdba3747a 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -2497,7 +2497,9 @@ fn primaries_from_code(c: u8) -> Option { 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 + // RFC 9559 §5.1.4.1.28.14 defines 0 as pixels and 3 as a display ratio. + // Use the coded raster because this reader presents frames without Matroska cropping. + if matches!(v.display_unit, 0 | 3) && let (Some(dw), Some(dh)) = (v.display_width, v.display_height) && dw > 0 && dh > 0 @@ -2505,7 +2507,7 @@ fn matroska_par(video: Option<&matroska::VideoInfo>, width: u32, height: u32) -> && height > 0 && (dw != width || dh != height) { - return (dw * height, dh * width); + return dw.checked_mul(height).zip(dh.checked_mul(width)).unwrap_or((1, 1)); } (1, 1) } @@ -3744,6 +3746,63 @@ mod tests { assert_eq!(locked_error, regular_error); } + #[test] + fn matroska_display_aspect_reaches_shared_probe_and_frame() { + use craft_media::matroska::{ebml, element_ids::*}; + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let element = |id, payload: &[u8]| { + let mut bytes = Vec::new(); + ebml::write_id(&mut bytes, id); + ebml::write_size(&mut bytes, payload.len() as u64, 1); + bytes.extend_from_slice(payload); + bytes + }; + + // Generate a single ProRes frame and wrap it using the public Matroska element IDs. + let profile = Profile::Hq; + let frame = Frame::new(16, 12, ChromaFormat::Yuv422, 10, false).expect("ProRes frame"); + let packet = Encoder::new(profile, 16, 12).encode(&frame).expect("encode ProRes"); + let mut block = vec![0x81, 0, 0, 0x80]; // Track 1, timestamp 0, keyframe. + // Matroska omits the eight-byte ProRes size and 'icpf' prefix. + block.extend_from_slice(&packet[8..]); + let cluster = element(CLUSTER, &[element(TIMESTAMP, &[0]), element(SIMPLE_BLOCK, &block)].concat()); + let header = element(EBML, &element(DOC_TYPE, b"matroska")); + + let cases = [(3, (16_u32, 9_u32), (4, 3)), (0, (32, 18), (4, 3)), (4, (16, 9), (1, 1)), (3, (u32::MAX, 1), (1, 1))]; + for (unit, display_size, expected) in cases { + let video = [ + element(PIXEL_WIDTH, &[16]), + element(PIXEL_HEIGHT, &[12]), + element(DISPLAY_UNIT, &[unit]), + element(DISPLAY_WIDTH, &display_size.0.to_be_bytes()), + element(DISPLAY_HEIGHT, &display_size.1.to_be_bytes()), + ] + .concat(); + let track = [ + element(TRACK_NUMBER, &[1]), + element(TRACK_UID, &[1]), + element(TRACK_TYPE, &[1]), + element(CODEC_ID, b"V_PRORES"), + element(CODEC_PRIVATE, &profile.fourcc()), + element(VIDEO, &video), + ] + .concat(); + let tracks = element(TRACKS, &element(TRACK_ENTRY, &track)); + let segment = element(SEGMENT, &[tracks, cluster.clone()].concat()); + let bytes: Arc<[u8]> = [header.clone(), segment].concat().into(); + + let footage = crate::probe::probe_bytes("aspect.mkv", bytes.clone()).expect("public Matroska probe"); + assert_eq!(footage.codec, "ProRes", "must use the shared Matroska route"); + assert_eq!((footage.width, footage.height), (16, 12)); + assert_eq!(footage.pixel_aspect, f64::from(expected.0) / f64::from(expected.1), "display unit {unit}"); + + let source = open_bytes("aspect.mkv", bytes).expect("recognized Matroska").expect("shared Matroska"); + let decoded = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode frame"); + assert_eq!(decoded.par.0 * expected.1, decoded.par.1 * expected.0, "display unit {unit}"); + } + } + #[test] fn mxf_descriptor_aspect_reaches_shared_probe_and_frame() { use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; From 8bc329ac19dbaefd0279136501d59f8aa2d9cb68 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 01:53:37 +0800 Subject: [PATCH 358/393] media: preserve Matroska presentation duration (#4032) --- crates/media/src/craft_source.rs | 72 +++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index bdba3747a..804c6ba73 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -2520,8 +2520,9 @@ fn matroska_duration(file: &MkvFile, track: &matroska::Track) -> Tick { 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) + // Blocks are indexed in coding order, so a future reference can precede a B-picture. + let presentation_end = track.samples.iter().map(|s| s.pts.saturating_add(i64::try_from(s.duration).unwrap_or(0))).max().unwrap_or(0); + Tick::from_units(track.ticks_to_ns(presentation_end), 1_000_000_000) } fn tick_to_units(t: Tick, timescale: u32) -> i64 { @@ -4293,6 +4294,73 @@ mod tests { std::iter::repeat_n(sample.to_le_bytes(), count).flatten().collect() } + #[test] + fn matroska_duration_follows_presentation_order() { + use craft_media::matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec, ebml, element_ids}; + use craft_video::h264::{Encoder, EncoderConfig, PacketFormat, Profile, YuvFrame}; + use std::io::Cursor; + + fn child(data: &[u8], id: u32) -> ebml::Elem<'_> { + ebml::Children::new(data).find(|element| element.id == id).expect("Matroska element") + } + + // Generate three distinct pictures, with the B-picture coded after its future reference. + const PERIOD_NS: i64 = 40_000_000; + let mut cfg = EncoderConfig::new(16, 16, 25, 1); + cfg.profile = Profile::High; + cfg.bframes = 1; + cfg.format = PacketFormat::LengthPrefixed; + let mut encoder = Encoder::new(cfg).expect("H.264 encoder"); + let mut track = TrackSpec::new(TrackKind::Video, "V_MPEG4/ISO/AVC"); + track.codec_private = encoder.avcc(); + track.video_size = Some((16, 16)); + track.default_duration_ns = Some(PERIOD_NS as u64); + let mut mux = MkvWriter::new(Cursor::new(Vec::new()), vec![track], MuxOptions::default()).expect("Matroska writer"); + let mut packets = Vec::new(); + for (pts, luma) in [32, 96, 160].into_iter().enumerate() { + let pic = YuvFrame { y: &[luma; 256], u: &[128; 64], v: &[128; 64], y_stride: 16, uv_stride: 8 }; + packets.extend(encoder.encode(&pic, pts as i64).expect("encode picture")); + } + packets.extend(encoder.flush()); + for packet in packets { + mux.write_frame(0, packet.pts * PERIOD_NS, packet.keyframe, &packet.data, None).expect("write picture"); + } + let mut bytes = mux.finish().expect("finish Matroska").into_inner(); + + let (offset, header_len, payload_len) = { + let segment = child(&bytes, element_ids::SEGMENT); + let info = child(segment.data, element_ids::INFO); + let duration = child(info.data, element_ids::DURATION); + let offset = segment.offset + segment.header_len + info.offset + info.header_len + duration.offset; + (offset, duration.header_len, duration.data.len()) + }; + let end = offset + header_len + payload_len; + // Give the declaration a distinct value to check that it takes precedence. + bytes[offset + header_len..end].copy_from_slice(&160.0_f64.to_be_bytes()); + let declared = crate::probe::probe_bytes("duration.mkv", Arc::from(bytes.clone())).expect("probe declared duration"); + assert_eq!(declared.duration.0, Tick::from_units(160, 1_000).0); + + // Replace Duration with equally sized padding to keep all indexed file offsets. + let mut padding = Vec::new(); + ebml::write_id(&mut padding, element_ids::VOID); + let size_len = header_len - padding.len(); + ebml::write_size(&mut padding, payload_len as u64, size_len); + padding.resize(end - offset, 0); + bytes[offset..end].copy_from_slice(&padding); + let file = matroska::open(bytes.as_slice()).expect("demux Matroska"); + assert_eq!(file.info.duration, None); + assert_eq!(file.tracks[0].samples.iter().map(|sample| sample.pts).collect::>(), [0, 80, 40]); + + let bytes: Arc<[u8]> = bytes.into(); + let footage = crate::probe::probe_bytes("duration.mkv", bytes.clone()).expect("probe inferred duration"); + assert_eq!(footage.codec, "H.264", "must use the shared route"); + assert_eq!(footage.duration.0, Tick::from_units(120, 1_000).0); + let source = open_bytes("duration.mkv", bytes).expect("recognized Matroska").expect("shared Matroska"); + let time = Tick::from_units(80, 1_000); + let picture = source.video_frame(FrameRequest { time, scale: 1.0 }).expect("read final presented picture"); + assert_eq!(picture.pts, time); + } + #[test] fn matroska_durationless_lace_variable_pcm_preserves_all_blocks() { use std::io::Cursor; From 4e97ebe0ae1a79f14f8318fdf395ba4d70969a0c Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 01:53:40 +0800 Subject: [PATCH 359/393] media: include the final AAC transport packet in duration (#4033) --- crates/media/src/craft_source.rs | 64 +++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 804c6ba73..80b7cd366 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -676,6 +676,7 @@ where audio_tracks.push(AudioTrackEntry { track_idx: idx, native_rate, + fixed_packet_samples: fixed_samples, backend: AudioBackend::Decoder { seek_preroll_samples, state: Mutex::new(AudioTrackState { decoder: dec, audio_starts, next_sample: 0, decoded_pos: initial_pos, buf: Vec::new() }), @@ -1115,10 +1116,18 @@ fn finish_container_source( duration: Tick, audio_candidates: Vec<(usize, usize, CodecParams, u64)>, ) -> Option> { - let (audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; + let (mut audio_tracks, audio_infos) = open_audio_tracks(&container, &*source, audio_candidates)?; if video.is_none() && audio_tracks.is_empty() { return None; } + let duration = if video.is_none() + && let ContainerFile::Mpeg { file, .. } = &container + && matches!(file.format, mpegts::Format::Ts { .. }) + { + audio_tracks.iter_mut().filter_map(|entry| adts_track_end(file, entry)).fold(duration, |end, track_end| end.max(track_end)) + } else { + duration + }; let kind = if video.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly }; let (video_track_idx, video_info, video_state) = match video { Some(v) => (Some(v.track_idx), Some(v.info), Some(v.state)), @@ -1146,6 +1155,17 @@ fn finish_container_source( }))) } +/// Use the same packet starts and sample count as playback to include the final ADTS packet. +fn adts_track_end(file: &mpegts::File, entry: &mut AudioTrackEntry) -> Option { + if file.streams.get(entry.track_idx)?.codec != mpegts::Codec::AacAdts { + return None; + } + let samples = entry.fixed_packet_samples?; + let AudioBackend::Decoder { state, .. } = &mut entry.backend else { return None }; + let last_start = *state.get_mut().ok()?.audio_starts.positions.iter().max()?; + Some(Tick::from_units(last_start.saturating_add(samples), i64::from(entry.native_rate))) +} + fn mxf_sound_window(track: &mxf::EssenceTrack) -> (u64, u64) { let (sp_num, sp_den) = track.samples_per_edit_unit(); let sp_den = i128::from(sp_den.max(1)); @@ -1239,7 +1259,12 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio let channels = sound.channels.max(1); let (presented_start, presented_len) = mxf_sound_window(t); audio_infos.push(AudioStreamInfo { sample_rate: rate, channels, codec: t.codec.codec_id().name().to_string(), bits_per_sample: Some(sound.bits) }); - audio_tracks.push(AudioTrackEntry { track_idx: idx, native_rate: rate, backend: AudioBackend::MxfPcm { presented_start, presented_len } }); + audio_tracks.push(AudioTrackEntry { + track_idx: idx, + native_rate: rate, + fixed_packet_samples: None, + backend: AudioBackend::MxfPcm { presented_start, presented_len }, + }); } let (video_info, video_state, presentation, duration) = if let Some(v_idx) = video_idx { @@ -1554,6 +1579,7 @@ enum AudioBackend { struct AudioTrackEntry { track_idx: usize, native_rate: u32, + fixed_packet_samples: Option, backend: AudioBackend, } @@ -3423,6 +3449,40 @@ mod tests { } } + #[test] + fn adts_transport_duration_includes_the_final_packet() { + use craft_audio::aac::{Encoder, EncoderConfig}; + use mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + + const RATE: u32 = 48_000; + const SAMPLES: i64 = 1024; + const PTS_PER_PACKET: i64 = 1_920; + const ORIGIN_PTS: i64 = 90_000; + let mut encoder = Encoder::new(EncoderConfig::cbr(RATE, 1, 96_000).with_adts(true)).expect("ADTS encoder"); + let samples: Vec = (0..8192).map(|i| (f64::from(i) * 0.13).sin() as f32 * 0.4).collect(); + let mut packets = encoder.encode(&[&samples]); + packets.extend(encoder.flush()); + let three_packets = packets.get(..3).expect("three encoded packets"); + + for last_slot in [2, 3] { + let mut mux = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::AacAdts)]).expect("TS muxer"); + for (data, slot) in three_packets.iter().zip([0, 1, last_slot]) { + let pts = ORIGIN_PTS + slot * PTS_PER_PACKET; + mux.write_frame(0, &Frame { data, pts, dts: None, key: true }).expect("write ADTS packet"); + } + let bytes: Arc<[u8]> = mux.finish().expect("finish TS").into(); + let source = open_bytes("audio.ts", bytes.clone()).expect("recognized TS").expect("shared TS audio"); + let final_packet = source.audio(last_slot * SAMPLES, SAMPLES as usize, RATE).expect("read final packet"); + assert!(final_packet.channels[0].iter().any(|sample| sample.abs() > 0.02), "the final packet carries audible samples"); + + let footage = crate::probe::probe_bytes("audio.ts", bytes).expect("public TS probe"); + assert!(footage.has_audio && !footage.has_video); + assert_eq!(footage.codec, "AAC"); + let end = Tick::from_units((last_slot + 1) * SAMPLES, i64::from(RATE)); + assert_eq!(footage.duration.0, end.0, "final packet at slot {last_slot}"); + } + } + #[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])) { From fcf35f3f9ffea13e49b985343d2f42f3741342e1 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 01:53:44 +0800 Subject: [PATCH 360/393] media: derive AVI video duration from indexed frames (#4037) --- crates/media/src/craft_source.rs | 56 ++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 80b7cd366..3512107f1 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1380,8 +1380,10 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { let (width, height) = video_stream.video.as_ref().map_or((0, 0), |v| (v.width.unsigned_abs(), v.height.unsigned_abs())); let fps = f64::from(video_stream.rate) / f64::from(video_stream.scale.max(1)); let frame_rate = snap_common_fps(fps).unwrap_or_else(|| FrameRate::new(i64::from(video_stream.rate), i64::from(video_stream.scale))); - let total_units = i64::from(video_stream.length.max(video_stream.chunks.len() as u32)); - let duration = Tick::from_units(total_units.saturating_mul(i64::from(video_stream.scale)), i64::from(video_stream.rate.max(1))); + // Seeking treats each indexed video chunk as one frame. A stale header + // length can describe pictures beyond the end of the index. + let frames = i64::try_from(video_stream.chunks.len()).unwrap_or(i64::MAX); + let duration = Tick::from_rational(frames, i64::from(video_stream.scale), i64::from(video_stream.rate)); 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()))), @@ -4181,6 +4183,56 @@ mod tests { assert!(contiguous_starts([], 512).is_empty()); } + #[test] + fn avi_video_duration_uses_indexed_frames() { + use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; + + let mut config = EncoderConfig::new(Profile::P4444, 16, 16); + config.encode_alpha = false; + config.threads = false; + let mut encoder = Encoder::with_config(config); + let stream = avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 30_000, 1_001)); + let mut writer = avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![stream], avi::MuxOptions::default()).expect("AVI writer"); + for luma in [256, 768] { + let frame = ProResFrame { + width: 16, + height: 16, + chroma: ChromaFormat::Yuv444, + bit_depth: 10, + y: vec![luma; 256], + cb: vec![512; 256], + cr: vec![512; 256], + alpha: None, + interlace: Interlace::Progressive, + color: ProResColor::default(), + aspect_ratio: 0, + frame_rate_code: 0, + }; + writer.write_chunk(0, &encoder.encode(&frame).expect("encode ProRes"), true).expect("write picture"); + } + let mut bytes = writer.finish().expect("finish AVI").into_inner(); + // dwLength is 32 bytes into the strh payload, after the 8-byte chunk header. + let length_offset = bytes.windows(4).position(|tag| tag == b"strh").expect("stream header") + 8 + 32; + let frame_period = Tick::from_rational(1, 1_001, 30_000); + for declared_length in [1u32, 2, 100] { + bytes[length_offset..length_offset + 4].copy_from_slice(&declared_length.to_le_bytes()); + let stream = &avi::open(bytes.as_slice()).expect("demux fixture").streams[0]; + assert_eq!(stream.length, declared_length); + assert_eq!(stream.chunks.len(), 2); + let input: Arc<[u8]> = Arc::from(bytes.as_slice()); + let footage = crate::probe::probe_bytes("indexed.avi", input.clone()).expect("public probe"); + assert_eq!(footage.codec, "ProRes"); + assert_eq!(footage.duration, effectcraft_time::Tick::from_rational(2, 1_001, 30_000), "declared length {declared_length}"); + + let source = open_bytes("indexed.avi", input).expect("recognized AVI").expect("shared AVI"); + let last = source.video_frame(FrameRequest { time: frame_period, scale: 1.0 }).expect("seek to last picture"); + let PixelData::Yuv16 { planes: [y, ..], .. } = &last.data else { + panic!("expected the decoded ProRes luma plane"); + }; + assert!(y[0] > 512, "expected the brighter second picture"); + } + } + #[test] fn avi_and_mpeg_helpers_and_in_memory_route() { assert_eq!(tick_to_rational_units(Tick(craft_time::TICKS_PER_SECOND), 24, 1), 24); From 6e3459a8ebc88cce8362fece73ed44f657e2fb7f Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 01:53:47 +0800 Subject: [PATCH 361/393] media: use the shared reader for uncompressed RGB AVI (#4050) --- crates/media/src/craft_source.rs | 59 +++++++++-- crates/media/src/craft_source/raw_avi.rs | 96 ++++++++++++++++++ .../media/src/craft_source/raw_avi_tests.rs | 99 +++++++++++++++++++ 3 files changed, 246 insertions(+), 8 deletions(-) create mode 100644 crates/media/src/craft_source/raw_avi.rs create mode 100644 crates/media/src/craft_source/raw_avi_tests.rs diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 3512107f1..48a6b679e 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -25,9 +25,9 @@ //! - **AVI / MPEG-TS / MPEG-PS**: //! - Shared (`craft-media::avi`, `craft-media::mpegts` + `craft-video` + `craft-audio`): //! `H264`, `Hevc`, `Mpeg2Video`, `Av1`, `Vp9`, `Vp8`, `ProRes`, `Dnxhd`; audio `Aac`, -//! `Ac3`/`Eac3`, `Mp3`/`Mp2`/`Mp1`, `Pcm`. +//! `Ac3`/`Eac3`, `Mp3`/`Mp2`/`Mp1`, `Pcm`. AVI also accepts complete 24/32-bit `BI_RGB` streams. //! - Fallback (`filmcraft-codecs`): unsupported codecs (`Mjpeg`, `Mpeg4Video`, `Ffv1`, `Theora`, -//! `Apv`, raw RGB AVI) or unsupported audio. +//! `Apv`, other raw AVI layouts) or unsupported audio. //! - **Other containers & standalone audio**: //! - Shared (`craft_audio::Decoder` with `decode-native`): standalone `WAV`, `AIFF`, `MP3`/`MP2`/`MP1`, //! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). @@ -53,6 +53,9 @@ use craft_time::{FrameRate, Tick}; use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame}; use craft_video::{TrackDecoder, TrackDecoderOptions, VideoError, prores}; +mod raw_avi; +use raw_avi::RawAvi; + /// Maximum worker threads per `TrackDecoder` instance. const MAX_WORKERS: usize = 8; @@ -955,7 +958,7 @@ fn open_isobmff(name: &str, source: SharedBytes) -> Option> Err(e) => return Some(Err(MediaError::Decode(e.to_string()))), }; let v_info = VideoStreamInfo { width, height, frame_rate, par, codec: codec_name, pixel_format, color, has_alpha, bitrate, hdr: None }; - let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + let v_state = VideoState::packet(video_decoder); (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation, aperture }, duration) } else { let duration = audio_candidates @@ -1064,7 +1067,7 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option bitrate: None, hdr: None, }; - let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + let v_state = VideoState::packet(video_decoder); (Some(v_info), Some(v_state), container_color, par, rotation, duration) } else { let duration = audio_candidates.iter().map(|&(idx, _, _, _)| matroska_duration(&file, &file.tracks[idx])).max().unwrap_or(Tick::ZERO); @@ -1299,7 +1302,7 @@ fn open_parsed_mxf(name: &str, source: SharedBytes, file: mxf::MxfFile) -> Optio bitrate: None, hdr: None, }; - let v_state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + let v_state = VideoState::packet(video_decoder); (Some(v_info), Some(v_state), FramePresentation { container_color, par, rotation: 0, aperture: None }, duration) } else { let duration = audio_tracks @@ -1371,6 +1374,25 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { return None; } + if let Some(idx) = video_idx + && let Some(raw) = RawAvi::new(&file.streams[idx]) + { + // Shared AVI audio positions are relative to the first chunk. Keep the + // legacy path for a track with a separate stream start. + if audio_candidates.iter().any(|&(audio, _, _, _)| file.streams[audio].start != 0) { + return None; + } + let duration = audio_candidates + .iter() + .map(|&(audio, _, _, _)| { + let s = &file.streams[audio]; + Tick::from_units(i64::from(s.length).saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + }) + .fold(raw.duration(file.streams[idx].chunks.len()), Tick::max); + let video = ContainerVideoPart { track_idx: idx, info: raw.info(&file.streams[idx]), state: Mutex::new(VideoState::RawAvi(raw)) }; + return finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), Some(video), duration, audio_candidates); + } + let (video, duration) = if let Some(v_idx) = video_idx { let video_stream = &file.streams[v_idx]; let video_params = video_stream.codec_params(); @@ -1395,7 +1417,7 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { let alpha = video_stream.chunks.first().and_then(|chunk| prores_has_alpha(chunk.size, || file.read_chunk(&*source, v_idx, 0).ok())); info.has_alpha = alpha.unwrap_or(false); } - let state = Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }); + let state = VideoState::packet(video_decoder); (Some(ContainerVideoPart { track_idx: v_idx, info, state }), duration) } else { let duration = audio_candidates @@ -1516,7 +1538,7 @@ fn open_mpeg(name: &str, fmt: mpegts::Format, source: SharedBytes) -> Option, } -struct VideoState { +enum VideoState { + Packet(PacketVideoState), + RawAvi(RawAvi), +} + +impl VideoState { + fn packet(decoder: TrackDecoder) -> Mutex { + Mutex::new(Self::Packet(PacketVideoState { decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() })) + } +} + +struct PacketVideoState { decoder: TrackDecoder, next_decode_idx: usize, gop_start_idx: usize, @@ -1709,6 +1742,13 @@ impl MediaSource for CraftMediaSource { let want_draft = req.scale < 0.99; let mut state = video_mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let state = match &mut *state { + VideoState::Packet(state) => state, + VideoState::RawAvi(raw) => { + let ContainerFile::Avi(file) = &self.file else { return Err(MediaError::NoStream("AVI video")) }; + return raw.frame(file, &*self.source, video_idx, target_idx); + } + }; if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts && c.draft == want_draft) { return Ok(hit.frame.clone()); } @@ -2626,6 +2666,9 @@ fn estimate_matroska_frame_rate(track: &matroska::Track) -> FrameRate { FrameRate::FPS_30 } +#[cfg(all(test, any(unix, windows)))] +mod raw_avi_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/media/src/craft_source/raw_avi.rs b/crates/media/src/craft_source/raw_avi.rs new file mode 100644 index 000000000..76dd8f517 --- /dev/null +++ b/crates/media/src/craft_source/raw_avi.rs @@ -0,0 +1,96 @@ +use std::sync::Arc; + +use craft_color::ColorInfo; +use craft_frame::VideoFrame; +use craft_media::{ByteSource, avi}; +use craft_media_source::{MediaError, Result, VideoStreamInfo}; +use craft_time::{FrameRate, Tick}; +use craft_video::raw_video::{self, RawFormat, RawPixels}; + +pub(super) struct RawAvi { + format: RawFormat, + width: u32, + height: u32, + bottom_up: bool, + payload_bytes: usize, + rate: FrameRate, + cached: Option<(usize, Arc)>, +} + +impl RawAvi { + pub(super) fn new(stream: &avi::Stream) -> Option { + let bitmap = stream.video.as_ref()?; + let format = raw_video::RawFormat::from_avi(bitmap.compression, bitmap.bit_count)?; + if !matches!(format, RawFormat::Bgr24 | RawFormat::Bgrx32) || stream.start != 0 { + return None; + } + let width = u32::try_from(bitmap.width).ok()?; + let height = bitmap.height.unsigned_abs(); + if !(1..=16_384).contains(&width) || !(1..=16_384).contains(&height) { + return None; + } + let stride = (u64::from(width) * u64::from(bitmap.bit_count / 8)).next_multiple_of(4); + let payload_bytes = stride * u64::from(height); + let decoded_bytes = u64::from(width) * u64::from(height) * 4; + // A request can hold its input and new picture while the old picture is cached. + if payload_bytes + 2 * decoded_bytes > craft_video::budget::DECODE_MEMORY_BUDGET { + return None; + } + // Empty AVI slots and partial chunks need the legacy reader's recovery policy. + if stream.chunks.iter().any(|chunk| u64::from(chunk.size) < payload_bytes) { + return None; + } + Some(Self { + format, + width, + height, + bottom_up: bitmap.height > 0, + payload_bytes: usize::try_from(payload_bytes).ok()?, + rate: FrameRate::new(i64::from(stream.rate), i64::from(stream.scale)), + cached: None, + }) + } + + pub(super) fn duration(&self, slots: usize) -> Tick { + self.rate.tick_of(i64::try_from(slots).unwrap_or(i64::MAX)) + } + + pub(super) fn info(&self, stream: &avi::Stream) -> VideoStreamInfo { + let bytes: u128 = stream.chunks.iter().map(|chunk| u128::from(chunk.size)).sum(); + let bytes_per_slot = bytes as f64 / stream.chunks.len() as f64; + VideoStreamInfo { + width: self.width, + height: self.height, + frame_rate: self.rate, + par: (1, 1), + codec: self.format.label().to_string(), + pixel_format: String::new(), + color: ColorInfo::SRGB_FULL, + has_alpha: false, + bitrate: Some((bytes_per_slot * 8.0 * self.rate.as_f64()) as u64), + hdr: None, + } + } + + pub(super) fn frame(&mut self, file: &avi::AviFile, source: &dyn ByteSource, stream: usize, index: usize) -> Result> { + if let Some((cached_index, frame)) = &self.cached + && *cached_index == index + { + return Ok(frame.clone()); + } + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } + let packet = file.read_chunk_range(source, stream, index, 0, self.payload_bytes).map_err(|e| MediaError::Io(e.to_string()))?; + let pixels = raw_video::decode(self.format, self.width, self.height, self.bottom_up, &packet) + .map_err(|e| MediaError::Decode(format!("uncompressed AVI picture: {e:?}")))?; + let RawPixels::Rgba(pixels) = pixels else { + return Err(MediaError::Unsupported("unexpected uncompressed AVI pixel layout".into())); + }; + let mut frame = VideoFrame::rgba8(self.width, self.height, pixels).map_err(|e| MediaError::Decode(e.to_string()))?; + frame.pts = self.rate.tick_of(i64::try_from(index).unwrap_or(i64::MAX)); + let frame = Arc::new(frame); + self.cached = Some((index, frame.clone())); + Ok(frame) + } +} diff --git a/crates/media/src/craft_source/raw_avi_tests.rs b/crates/media/src/craft_source/raw_avi_tests.rs new file mode 100644 index 000000000..96ce62454 --- /dev/null +++ b/crates/media/src/craft_source/raw_avi_tests.rs @@ -0,0 +1,99 @@ +use std::io::Cursor; +use std::sync::Arc; + +use craft_color::ColorInfo; +use craft_frame::PixelData; +use craft_media::avi; +use craft_media_source::FrameRequest; +use craft_time::Tick; + +use crate::stream::{self, MediaSource}; + +const WIDTH: u32 = 3; +const HEIGHT: u32 = 2; +const FPS: u32 = 25; +const AUDIO_RATE: u32 = 8_000; +const AUDIO_PER_FRAME: usize = (AUDIO_RATE / FPS) as usize; + +fn rgba(frame: u8, x: u8, y: u8) -> [u8; 4] { + [16 + 30 * frame, 21 + 71 * y, 5 + 17 * x, 255] +} + +fn bitmap(frame: u8, depth: u16, bottom_up: bool) -> Vec { + let stride = (WIDTH as usize * usize::from(depth / 8)).next_multiple_of(4); + let mut bytes = Vec::new(); + for row in 0..HEIGHT as u8 { + let y = if bottom_up { HEIGHT as u8 - 1 - row } else { row }; + for x in 0..WIDTH as u8 { + let [r, g, b, _] = rgba(frame, x, y); + bytes.extend([b, g, r]); + if depth == 32 { + bytes.push(43); + } + } + bytes.resize((usize::from(row) + 1) * stride, 111); + } + bytes +} + +// Original in-memory fixture. The shared AVI muxer writes deterministic test pixels and PCM. +fn fixture(depth: u16, bottom_up: bool, sparse: bool) -> Result, avi::Error> { + let mut video = avi::VideoSpec::new([0; 4], WIDTH, HEIGHT, FPS, 1); + if !bottom_up { + video.format.height = -(HEIGHT as i32); + } + video.format.bit_count = depth; + video.format.size_image = bitmap(0, depth, bottom_up).len() as u32; + let audio = avi::AudioSpec::pcm(AUDIO_RATE, 1, 16); + let mut writer = + avi::AviWriter::new(Cursor::new(Vec::new()), vec![avi::StreamSpec::Video(video), avi::StreamSpec::Audio(audio)], avi::MuxOptions::default())?; + for i in 0..3u8 { + let picture = if sparse && i == 1 { Vec::new() } else { bitmap(i, depth, bottom_up) }; + let sound = (1000 * (i16::from(i) + 1)).to_le_bytes().repeat(AUDIO_PER_FRAME); + writer.write_chunk(0, &picture, true)?; + writer.write_chunk(1, &sound, true)?; + } + Ok(writer.finish()?.into_inner()) +} + +#[test] +fn raw_rgb_avi_preserves_pixels_and_pcm_across_indexed_seeks() -> Result<(), Box> { + let dir = tempfile::tempdir()?; + for (name, depth, bottom_up) in [("bottom-up.avi", 24, true), ("top-down.avi", 32, false)] { + let bytes: Arc<[u8]> = fixture(depth, bottom_up, false)?.into(); + let path = dir.path().join(name); + std::fs::write(&path, &bytes)?; + let disk = stream::open_source(&path).ok_or("unrecognized AVI")?.0?; + let memory = stream::open_bytes(name, bytes)?; + for opened in [disk, memory] { + let MediaSource::Craft(source) = opened else { panic!("{name}: expected shared raw AVI route") }; + let info = source.info(); + let video = info.video.as_ref().ok_or("missing video")?; + assert_eq!((video.width, video.height, video.has_alpha), (WIDTH, HEIGHT, false)); + assert_eq!(video.codec, format!("Uncompressed RGB {depth}-bit")); + assert_eq!(info.duration, Tick::from_units(3, i64::from(FPS))); + for i in [2u8, 0, 1] { + let time = Tick::from_units(2 * i64::from(i) + 1, 2 * i64::from(FPS)); + let frame = source.video_frame(FrameRequest { time, scale: 1.0 })?; + assert_eq!(frame.pts, Tick::from_units(i64::from(i), i64::from(FPS))); + assert_eq!((frame.par, frame.color), ((1, 1), ColorInfo::SRGB_FULL)); + let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected 8-bit RGBA") }; + let expected: Vec = (0..HEIGHT as u8).flat_map(|y| (0..WIDTH as u8).flat_map(move |x| rgba(i, x, y))).collect(); + assert_eq!(pixels.as_slice(), expected); + } + let audio = source.audio(AUDIO_PER_FRAME as i64 - 2, 4, AUDIO_RATE)?; + assert_eq!(audio.channels, [vec![1000.0 / 32768.0, 1000.0 / 32768.0, 2000.0 / 32768.0, 2000.0 / 32768.0]]); + } + } + Ok(()) +} + +#[test] +fn raw_rgb_avi_with_dropped_slot_keeps_legacy_playback() -> Result<(), Box> { + let opened = stream::open_bytes("sparse.avi", fixture(24, true, true)?.into())?; + let MediaSource::Film(source) = opened else { panic!("expected legacy AVI slot handling") }; + let time = filmcraft_time::Tick::from_units(1, i64::from(FPS)); + let frame = source.video_frame(filmcraft_media::FrameRequest { time, scale: 1.0 })?; + assert_eq!((frame.width, frame.height), (WIDTH, HEIGHT)); + Ok(()) +} From f7ab031c3cc4ff84783a52cce8d502300d3408b7 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 01:53:50 +0800 Subject: [PATCH 362/393] media: present monochrome frames from the shared decoder (#4051) --- ATTRIBUTION.md | 1 + crates/media/src/craft_source.rs | 33 +++++++++++- .../src/craft_source/monochrome_tests.rs | 49 ++++++++++++++++++ .../tests/fixtures/generate-monochrome-av1.sh | 9 ++++ .../media/tests/fixtures/monochrome-av1.mkv | Bin 0 -> 1243 bytes .../fixtures/monochrome-av1.mkv.attribution | 7 +++ 6 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 crates/media/src/craft_source/monochrome_tests.rs create mode 100755 crates/media/tests/fixtures/generate-monochrome-av1.sh create mode 100644 crates/media/tests/fixtures/monochrome-av1.mkv create mode 100644 crates/media/tests/fixtures/monochrome-av1.mkv.attribution diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7043e6128..74dbce1fa 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -162,3 +162,4 @@ under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and | Asset | Author | Source | Licence | |---|---|---|---| | `crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture` | Dylan M. Taylor | Original sine waves; reproducible recipe in `crates/media/tests/fixtures/README.md` | MIT OR Apache-2.0 | +| `crates/media/tests/fixtures/monochrome-av1.mkv` | Terra854 | Original grayscale ramps from `crates/media/tests/fixtures/generate-monochrome-av1.sh` | MIT OR Apache-2.0 | diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 48a6b679e..a0212d14d 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -2293,7 +2293,35 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T 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())), + ColorFamily::Gray => { + let y = planes.into_iter().next().ok_or_else(|| MediaError::Decode("missing grayscale plane".into()))?; + let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height))); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + // Chroma is constant, so subsampling does not change the visible grayscale picture. + let chroma = Chroma::C420; + let chroma_len = (width as usize) + .div_ceil(2) + .checked_mul((height as usize).div_ceil(2)) + .ok_or_else(|| MediaError::Decode("monochrome chroma size overflows".into()))?; + match bit_depth { + 8 => { + let y = Arc::new(plane_u8(y, luma)?); + let alpha = alpha.map(|p| plane_u8(p, luma)).transpose()?.map(Arc::new); + let neutral = Arc::new(vec![128; chroma_len]); + PixelData::Yuv8 { planes: [y, neutral.clone(), neutral], chroma, alpha } + } + 9..=16 => { + let y = Arc::new(plane_u16(y, luma)?); + let alpha = alpha.map(|p| plane_u16(p, luma)).transpose()?.map(Arc::new); + let neutral = Arc::new(vec![1u16 << (bit_depth - 1); chroma_len]); + PixelData::Yuv16 { planes: [y, neutral.clone(), neutral], chroma, bits: u32::from(bit_depth), alpha } + } + _ => return Err(MediaError::Unsupported("monochrome bit depth below 8".into())), + } + } + ColorFamily::Rgb => return Err(MediaError::Unsupported("non-YCbCr pixel format".into())), }; let frame = VideoFrame { width, height, data, color, par, pts }; @@ -4793,3 +4821,6 @@ mod tests { assert_eq!(read_count, 0); } } + +#[cfg(test)] +mod monochrome_tests; diff --git a/crates/media/src/craft_source/monochrome_tests.rs b/crates/media/src/craft_source/monochrome_tests.rs new file mode 100644 index 000000000..e3251550d --- /dev/null +++ b/crates/media/src/craft_source/monochrome_tests.rs @@ -0,0 +1,49 @@ +use super::*; +use crate::stream::{self, MediaSource as OpenedSource}; + +#[test] +fn shared_monochrome_av1_retains_luma_on_backward_seek() -> std::result::Result<(), Box> { + let bytes: Arc<[u8]> = Arc::from(include_bytes!("../../tests/fixtures/monochrome-av1.mkv").as_slice()); + let OpenedSource::Craft(source) = stream::open_bytes("monochrome-av1.mkv", bytes)? else { + panic!("expected the shared AV1 reader"); + }; + for i in [2u8, 0, 1] { + let pts = Tick::from_units(i64::from(i), 25); + let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?; + assert_eq!((frame.width, frame.height, frame.pts, frame.color.range), (16, 12, pts, Range::Full)); + let PixelData::Yuv8 { planes: [y, cb, cr], chroma: Chroma::C420, alpha: None } = &frame.data else { + panic!("expected 8-bit luma with neutral chroma"); + }; + let expected: Vec = (0..12).flat_map(|row| (0..16).map(move |col| 16 + 64 * i + col + 2 * row)).collect(); + assert_eq!(y.as_slice(), expected); + assert_eq!(cb.as_slice(), [128; 48]); + assert_eq!(cr.as_slice(), cb.as_slice()); + let rgba = frame.to_rgba8()?; + for (pixel, &sample) in rgba.as_chunks::<4>().0.iter().zip(&expected) { + assert_eq!(*pixel, [sample, sample, sample, 255]); + } + } + Ok(()) +} + +#[test] +fn monochrome_10_bit_preserves_aperture_rotation_alpha_and_layout() -> std::result::Result<(), Box> { + let y = Plane::packed(5, 5, 10, Samples::U16((64..89).collect()))?; + let alpha = Plane::packed(5, 5, 10, Samples::U16((900..925).collect()))?; + let mut decoded = DecodedVideoFrame::new(5, 5, ColorFamily::Gray, Subsampling::S444, vec![y], Some(alpha))?; + decoded.sar = Some((3, 2)); + let aperture = isobmff::CleanAperture { width: (3, 1), height: (3, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + let presentation = FramePresentation { container_color: Some(ColorInfo::REC709), par: (1, 1), rotation: 1, aperture: Some(aperture) }; + let pts = Tick::from_units(4, 25); + let frame = to_craft_frame(decoded, presentation, pts)?; + assert_eq!((frame.width, frame.height, frame.par, frame.pts), (3, 3, (2, 3), pts)); + assert_eq!(frame.color, ColorInfo::REC709); + let PixelData::Yuv16 { planes: [y, cb, cr], chroma: Chroma::C420, bits: 10, alpha: Some(alpha) } = &frame.data else { + panic!("expected 10-bit luma and alpha"); + }; + assert_eq!(y.as_slice(), [80, 75, 70, 81, 76, 71, 82, 77, 72]); + assert_eq!(alpha.as_slice(), [916, 911, 906, 917, 912, 907, 918, 913, 908]); + assert_eq!(cb.as_slice(), [512; 4]); + assert_eq!(cr.as_slice(), cb.as_slice()); + Ok(()) +} diff --git a/crates/media/tests/fixtures/generate-monochrome-av1.sh b/crates/media/tests/fixtures/generate-monochrome-av1.sh new file mode 100755 index 000000000..ecfdfc830 --- /dev/null +++ b/crates/media/tests/fixtures/generate-monochrome-av1.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env sh +set -eu +cd "$(dirname "$0")" +ffmpeg -hide_banner -loglevel error \ + -f lavfi -i "nullsrc=s=16x12:r=25,format=gray,geq=lum='16+64*N+X+2*Y'" \ + -frames:v 3 -c:v libaom-av1 -pix_fmt gray -color_range pc \ + -color_primaries bt709 -color_trc bt709 -colorspace bt709 \ + -g 1 -crf 0 -b:v 0 -aom-params lossless=1 -cpu-used 6 -threads 16 \ + -fflags +bitexact -flags:v +bitexact -f matroska -y monochrome-av1.mkv diff --git a/crates/media/tests/fixtures/monochrome-av1.mkv b/crates/media/tests/fixtures/monochrome-av1.mkv new file mode 100644 index 0000000000000000000000000000000000000000..37749f35e37fcccf6b0043c56a681dcbdce8e12d GIT binary patch literal 1243 zcmb1gy}x*|Q(GgW({~{L)X3uWxsk)EsUtVBq$s~QJJG2fDAd}>BoW+@&d2})EXxIb zXO|q<-{RsP{oQwWckt>KQO}iW!D|{9LU>{!>#~8oGrqfffO0}1htq@CG%+hcxH7@J zfs#!unQtJbF$9ARr7i(-&$9h3$2&UAwXSb$=67=NZD{dHEK3V_1XC`Z9S(62D?yHR z^4s5{wS8sSI*5~)?5{U679Z_^x`}a4BZJb`InAYcDIJXrZLMMPj$ww)jf~2Vn_HNY zq8J`b*w84jtC43`BU9*xme8F*>RlrP%zI1>49Sc78yRF6xHy3ZGS0ub^-~B`lJOdK zy*+B$;0OUwlE1aTrT=qkesS@|Os!UeM$xKSj z&(%#VGfY3R&~ILoDkN#xY7k~^3z+q6g8^-~L Date: Sun, 22 Nov 2026 01:53:55 +0800 Subject: [PATCH 363/393] media: present full-range 8-bit RGB from the shared decoder (#4052) --- crates/media/src/craft_source.rs | 29 ++++++++ crates/media/src/craft_source/rgb8_tests.rs | 81 +++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 crates/media/src/craft_source/rgb8_tests.rs diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index a0212d14d..6534852a6 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -2245,6 +2245,9 @@ fn push_decoded( Ok(()) } +#[cfg(test)] +mod rgb8_tests; + fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: Tick) -> Result { let FramePresentation { container_color, par: default_par, rotation, aperture } = presentation; let (mut width, mut height) = (vf.width(), vf.height()); @@ -2261,6 +2264,28 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T let (planes, alpha) = vf.into_planes(); let data = match family { + ColorFamily::Rgb if color.range == Range::Full && planes.iter().chain(alpha.iter()).all(|p| p.bit_depth() == 8) => { + let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height))); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + let bytes = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(4)) + .filter(|&n| n <= craft_frame::DEFAULT_MAX_FRAME_BYTES) + .ok_or_else(|| MediaError::Decode("RGB picture exceeds the frame buffer limit".into()))?; + let [r, g, b]: [Plane; 3] = planes.try_into().map_err(|_| MediaError::Decode("expected three RGB planes".into()))?; + let r = plane_u8(r, luma)?; + let g = plane_u8(g, luma)?; + let b = plane_u8(b, luma)?; + let alpha = alpha.map(|a| plane_u8(a, luma)).transpose()?.into_iter().flatten().chain(std::iter::repeat(255)); + let mut rgba = Vec::new(); + rgba.try_reserve_exact(bytes).map_err(|_| MediaError::Decode("could not allocate the RGB picture".into()))?; + for (((r, g), b), a) in r.into_iter().zip(g).zip(b).zip(alpha) { + rgba.extend_from_slice(&[r, g, b, a]); + } + PixelData::Rgba8(Arc::new(rgba)) + } ColorFamily::YCbCr => { let chroma = match subsampling { Subsampling::S420 => Chroma::C420, @@ -2393,6 +2418,10 @@ fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame { 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::Rgba8(pixels) => { + let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns); + PixelData::Rgba8(Arc::new(rotated.into_flattened())) + } 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), diff --git a/crates/media/src/craft_source/rgb8_tests.rs b/crates/media/src/craft_source/rgb8_tests.rs new file mode 100644 index 000000000..2cc78d441 --- /dev/null +++ b/crates/media/src/craft_source/rgb8_tests.rs @@ -0,0 +1,81 @@ +use std::io::Cursor; + +use craft_video::ffv1::{self, Colorspace, Encoder, EncoderConfig}; + +use super::*; +use crate::stream::{self, MediaSource as OpenedSource}; + +type TestResult = std::result::Result<(), Box>; + +const WIDTH: u32 = 5; +const HEIGHT: u32 = 3; + +fn rgba(frame: u8, x: u8, y: u8) -> [u8; 4] { + [15 + 55 * frame + x, 59 + 3 * y, 191 + x + y, 255] +} + +#[test] +fn shared_ffv1_rgb8_keeps_opaque_pixels_across_backward_seek() -> TestResult { + let mut raw = ffv1::Frame { width: WIDTH, height: HEIGHT, colorspace: Colorspace::Rgb, bit_depth: 8, chroma_shift: (0, 0), planes: vec![Vec::new(); 3] }; + let encoder = Encoder::new(&raw, EncoderConfig::default())?; + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1"); + track.codec_private = encoder.config_record(); + track.video_size = Some((WIDTH, HEIGHT)); + track.default_duration_ns = Some(40_000_000); + let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?; + + // Original per-channel ramps, encoded and muxed in memory. + let mut expected = Vec::new(); + for n in 0u8..3 { + let pixels: Vec<[u8; 4]> = (0..HEIGHT as u8).flat_map(|y| (0..WIDTH as u8).map(move |x| rgba(n, x, y))).collect(); + for (c, plane) in raw.planes.iter_mut().enumerate() { + *plane = pixels.iter().map(|pixel| u16::from(pixel[c])).collect(); + } + writer.write_frame(0, i64::from(n) * 40_000_000, true, &encoder.encode(&raw)?, Some(40_000_000))?; + expected.push(pixels.into_flattened()); + } + let bytes = writer.finish()?.into_inner(); + let OpenedSource::Craft(source) = stream::open_bytes("rgb-ffv1.mkv", bytes.into())? else { + panic!("expected the shared FFV1 reader"); + }; + for n in [2, 0, 1] { + let pts = Tick::from_units(n as i64, 25); + let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?; + assert_eq!((frame.width, frame.height, frame.pts, frame.color.range), (WIDTH, HEIGHT, pts, Range::Full)); + let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected packed RGBA8") }; + assert_eq!(pixels.as_slice(), expected[n]); + } + Ok(()) +} + +fn presentation() -> FramePresentation { + FramePresentation { container_color: Some(ColorInfo::SRGB_FULL), par: (1, 1), rotation: 0, aperture: None } +} + +#[test] +fn packed_rgb_keeps_stride_aperture_rotation_and_straight_alpha() -> TestResult { + let make_plane = |base: u8| { + let samples: Vec = (0u8..3).flat_map(|y| [base + y * 4, base + y * 4 + 1, base + y * 4 + 2, 250]).collect(); + Plane::new(3, 3, 4, 8, Samples::U8(samples)) + }; + let mut decoded = + DecodedVideoFrame::new(3, 3, ColorFamily::Rgb, Subsampling::S444, vec![make_plane(10)?, make_plane(30)?, make_plane(50)?], Some(make_plane(0)?))?; + decoded.sar = Some((3, 2)); + let aperture = isobmff::CleanAperture { width: (1, 1), height: (3, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + let presentation = FramePresentation { aperture: Some(aperture), rotation: 1, ..presentation() }; + let pts = Tick::from_units(4, 25); + let frame = to_craft_frame(decoded, presentation, pts)?; + assert_eq!((frame.width, frame.height, frame.par, frame.pts), (3, 1, (2, 3), pts)); + assert_eq!(frame.color, ColorInfo::SRGB_FULL); + let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected packed RGBA8") }; + assert_eq!(pixels.as_slice(), [19, 39, 59, 9, 15, 35, 55, 5, 11, 31, 51, 1]); + Ok(()) +} + +#[test] +fn higher_depth_rgb_is_not_quantized_to_packed_bytes() -> TestResult { + let channel = Plane::packed(1, 1, 10, Samples::U16(vec![900]))?; + let decoded = DecodedVideoFrame::new(1, 1, ColorFamily::Rgb, Subsampling::S444, vec![channel; 3], None)?; + assert!(matches!(to_craft_frame(decoded, presentation(), Tick::ZERO), Err(MediaError::Unsupported(_)))); + Ok(()) +} From f02e6412ce80bbe28c5185ae47da4d64f2ff2a73 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:03:27 +0700 Subject: [PATCH 364/393] media: read AAC configuration through the shared byte source (#4046) Co-authored-by: Codex --- crates/media/src/aac.rs | 16 ++++++++-------- crates/media/src/pool.rs | 6 +++--- crates/media/src/stream.rs | 4 ++-- crates/media/tests/it/aac_layout.rs | 7 +++++++ 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/media/src/aac.rs b/crates/media/src/aac.rs index 356a8dff5..0aa987bf0 100644 --- a/crates/media/src/aac.rs +++ b/crates/media/src/aac.rs @@ -7,7 +7,7 @@ use std::io; use craft_audio::aac::AudioSpecificConfig; -use filmcraft_media::ByteReader; +use craft_media::ByteSource; /// How far into an MPEG TS / PS file the audio streams are looked for: the stream is indexed as /// far as this, not through the whole file. @@ -16,7 +16,7 @@ const MPEG_HEAD: u64 = 8 << 20; /// The configuration of the audio track FilmCraft plays, if it is AAC: from an MP4 / MOV `header` /// (its ftyp and moov, or the whole file) and `file`, or else from `file`, read as Matroska or /// MPEG TS / PS. -pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteReader>) -> Option { +pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteSource>) -> Option { let asc = match header.and_then(|h| mp4(h, file)) { Some(asc) => asc, None => { @@ -32,7 +32,7 @@ pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteReader>) -> Op /// The track FilmCraft's MP4 source plays: the first audio track with samples, a sample /// description and a timescale, read from the whole file as it is (a fragmented movie's samples /// are in its fragments, not the `moov`). -fn mp4(header: &[u8], file: Option<&dyn ByteReader>) -> Option> { +fn mp4(header: &[u8], file: Option<&dyn ByteSource>) -> Option> { let mp4 = match file { Some(f) => craft_media::isobmff::open(Head(f, f.len())), None => craft_media::isobmff::open(header), @@ -50,7 +50,7 @@ fn mp4(header: &[u8], file: Option<&dyn ByteReader>) -> Option> { /// The track FilmCraft's Matroska source plays: the first audio track with frames, found by /// indexing the clusters as that source does. -fn matroska(file: &dyn ByteReader) -> Option> { +fn matroska(file: &dyn ByteSource) -> Option> { let mkv = craft_media::matroska::open(Head(file, file.len())).ok()?; match &mkv.tracks.iter().find(|t| t.kind == craft_media::matroska::TrackKind::Audio && !t.samples.is_empty())?.codec { craft_media::matroska::Codec::Aac { asc } => Some(asc.clone()), @@ -61,12 +61,12 @@ fn matroska(file: &dyn ByteReader) -> Option> { /// The configuration of the stream FilmCraft's MPEG source plays: the first audio stream whose /// first unit it can read. Only AAC is asked about, so the streams before that one were refused /// whatever their codec, and an ADTS stream played has no configuration outside its frames. -fn latm(file: &dyn ByteReader) -> Option> { +fn latm(file: &dyn ByteSource) -> Option> { use craft_media::mpegts::{self, Codec}; let head = Head(file, file.len().min(MPEG_HEAD)); let mpeg = mpegts::open(&head).ok()?; let audio = mpeg.streams.iter().enumerate().filter(|(_, s)| s.kind() == mpegts::Kind::Audio && !s.units.is_empty()); - let played = audio.take(filmcraft_media::MAX_AUDIO_STREAMS).find_map(|(i, s)| { + let played = audio.take(craft_media_source::MAX_AUDIO_STREAMS).find_map(|(i, s)| { let first = mpeg.read_unit(&head, i, 0).ok()?; match s.codec { Codec::AacAdts => mpegts::frame_info(&s.codec, &first).map(|_| None), @@ -77,8 +77,8 @@ fn latm(file: &dyn ByteReader) -> Option> { played? } -/// The first `.1` bytes of a file, as the byte source FilmCraft's demuxers read. -struct Head<'a>(&'a dyn ByteReader, u64); +/// The first `.1` bytes available to the AAC container scan. +struct Head<'a>(&'a dyn ByteSource, u64); impl Head<'_> { fn read(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 7bb4ae78b..041b235db 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -568,7 +568,7 @@ struct Opened { impl Opened { /// `src` with what its container says: `header` is an MP4/MOV's ftyp and moov (or the whole /// file), `file` the file for other containers' AAC configuration. - fn new(src: MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Opened { + fn new(src: MediaSource, header: Option<&[u8]>, file: Option<&dyn craft_media::ByteSource>) -> Opened { let turn = header.map_or(Orientation::NoTransforms, crate::probe::video_turn); Opened { order: channel_order(&src, header, file), src, turn } } @@ -576,7 +576,7 @@ impl Opened { /// The order `src`'s audio channels decode in; multichannel AAC's by its configuration, where /// the container's header shows it ([`crate::aac::config`]). -fn channel_order(src: &MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Order { +fn channel_order(src: &MediaSource, header: Option<&[u8]>, file: Option<&dyn craft_media::ByteSource>) -> Order { match src.primary_audio() { Some((_, channels, codec)) if codec.contains("AAC") && channels > 2 => { crate::aac::config(header, file).map_or(Order::Aac, |asc| crate::downmix::aac_order(&asc)) @@ -1220,7 +1220,7 @@ impl Inner { 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 = crate::stream::open_bytes(&name, bytes.clone())?; - Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone())))) + Ok(Opened::new(src, Some(&bytes), Some(&bytes))) }); (opened, read) }); diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index 3bcb9b970..5bebba64a 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -191,12 +191,12 @@ pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStam /// `path` read in place (`None` when it can't be opened, or without a native file system). #[cfg(any(unix, windows))] -pub(crate) fn file_reader(path: &Path) -> Option> { +pub(crate) fn file_reader(path: &Path) -> Option> { Some(Box::new(FileReader::open(path).ok()?)) } #[cfg(not(any(unix, windows)))] -pub(crate) fn file_reader(_path: &Path) -> Option> { +pub(crate) fn file_reader(_path: &Path) -> Option> { None } diff --git a/crates/media/tests/it/aac_layout.rs b/crates/media/tests/it/aac_layout.rs index 5adf762b2..014655a40 100644 --- a/crates/media/tests/it/aac_layout.rs +++ b/crates/media/tests/it/aac_layout.rs @@ -300,6 +300,13 @@ fn mpeg_aac_mixes_by_the_stream_played() { } let p = write(&format!("latm-first-{latm_first}.ts"), &ts.out); check(label, case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe"))); + + let path = format!("/mem/latm-first-{latm_first}.ts"); + let bytes: Arc<[u8]> = ts.out.into(); + let pool = MediaPool::new(); + pool.add_bytes(&path, bytes.clone()); + let footage = probe_bytes(&path, bytes).expect("probe registered MPEG bytes"); + check(&format!("{label} in memory"), case.content, &mix(&pool, &footage)); } } From 951c8b4da72f60ea690ae508a1549996edb5c7e6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:03:31 +0700 Subject: [PATCH 365/393] Seek independent ProRes frames in scanned AVI streams (#4047) Co-authored-by: Codex --- crates/media/src/craft_source.rs | 81 ++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 6534852a6..15ae6bb10 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -264,6 +264,11 @@ impl ContainerFile { } } + fn scanned_avi_has_picture(&self, track_idx: usize, sample_idx: usize) -> bool { + let Self::Avi(file) = self else { return false }; + file.streams.get(track_idx).is_some_and(|s| !s.keyframes_known && s.chunks.get(sample_idx).is_some_and(|c| c.size != 0)) + } + fn sample_pts(&self, track_idx: usize, sample_idx: usize) -> i64 { match self { ContainerFile::Isobmff(f) => f.tracks[track_idx].samples[sample_idx].pts, @@ -1753,7 +1758,10 @@ impl MediaSource for CraftMediaSource { return Ok(hit.frame.clone()); } - let sync_idx = self.file.sync_sample_before(video_idx, target_idx); + // A scan cannot identify AVI keyframes, but each nonempty ProRes chunk is + // an independent picture. Do not read an earlier, possibly damaged chunk. + let direct_avi_prores = state.decoder.codec() == CodecId::ProRes && self.file.scanned_avi_has_picture(video_idx, target_idx); + let sync_idx = if direct_avi_prores { target_idx } else { self.file.sync_sample_before(video_idx, target_idx) }; let draft_changed = state.decoder.draft() != want_draft; if draft_changed { state.decoder.set_draft(want_draft); @@ -4764,13 +4772,17 @@ mod tests { } fn generated_avi_prores(with_alpha: bool, invalid_first: bool) -> Vec { + generated_avi_prores_pictures(with_alpha, invalid_first, &[512]) + } + + fn generated_avi_prores_pictures(with_alpha: bool, invalid_first: bool, luma: &[u16]) -> Vec { use craft_video::prores::{ChromaFormat, ColorInfo as ProResColor, Encoder, EncoderConfig, Frame as ProResFrame, Interlace, Profile}; let mut cfg = EncoderConfig::new(Profile::P4444, 16, 16); cfg.encode_alpha = with_alpha; cfg.threads = false; let mut enc = Encoder::with_config(cfg); - let frame = ProResFrame { + let mut frame = ProResFrame { width: 16, height: 16, chroma: ChromaFormat::Yuv444, @@ -4784,7 +4796,6 @@ mod tests { aspect_ratio: 0, frame_rate_code: 0, }; - let pkt = enc.encode(&frame).expect("encode prores"); let mut w = avi::AviWriter::new( std::io::Cursor::new(Vec::new()), vec![avi::StreamSpec::Video(avi::VideoSpec::new(*b"ap4h", 16, 16, 24, 1))], @@ -4794,7 +4805,11 @@ mod tests { if invalid_first { w.write_chunk(0, &[0], true).expect("write nonempty invalid first chunk"); } - w.write_chunk(0, &pkt, true).expect("write prores chunk"); + for &y in luma { + frame.y.fill(y); + let pkt = enc.encode(&frame).expect("encode prores"); + w.write_chunk(0, &pkt, true).expect("write prores chunk"); + } w.finish().expect("finish avi").into_inner() } @@ -4839,6 +4854,64 @@ mod tests { assert!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. })); } + // The fixture is a tiny AVI generated by this test. Neutralize only RIFF index + // records (not coincidental FourCC strings inside compressed pictures). + fn make_generated_avi_indexless(mut bytes: &mut [u8]) { + while !bytes.is_empty() { + let size = u32::from_le_bytes(bytes[4..8].try_into().expect("generated RIFF length")) as usize; + let (chunk, rest) = bytes.split_at_mut(8 + size + size % 2); + match &chunk[..4] { + b"RIFF" | b"LIST" => make_generated_avi_indexless(&mut chunk[12..8 + size]), + b"indx" | b"idx1" | b"ix00" => chunk[..4].copy_from_slice(b"JUNK"), + b"avih" => chunk[20] &= !0x10, // Clear AVIF_HASINDEX in dwFlags. + _ => {} + } + bytes = rest; + } + } + + fn avi_prores_test_picture(source: &crate::stream::MediaSource, time: effectcraft_time::Tick) -> Arc { + let crate::stream::DecodedFrame::Craft(frame) = source.video_frame(time, 1.0).expect("read shared ProRes picture") else { + panic!("expected the shared AVI reader"); + }; + assert_eq!(frame.pts.0, time.0); + frame + } + + fn avi_prores_test_pixels(frame: &VideoFrame) -> (&[u16], &[u16]) { + let PixelData::Yuv16 { planes, alpha: Some(alpha), .. } = &frame.data else { panic!("expected a YUV picture with coded alpha") }; + (&planes[0], alpha) + } + + #[test] + fn indexless_avi_prores_seeks_independent_pictures_past_a_bad_first_chunk() { + const SLOT: i64 = craft_time::TICKS_PER_SECOND / 24; + let mut bytes = generated_avi_prores_pictures(true, true, &[512, 768]); + let indexed = crate::stream::open_bytes("indexed-prores.avi", Arc::from(bytes.clone())).expect("open indexed control"); + let first = effectcraft_time::Tick(SLOT); + let second = effectcraft_time::Tick(2 * SLOT); + let expected_first = avi_prores_test_picture(&indexed, first); + let expected_second = avi_prores_test_picture(&indexed, second); + assert_ne!(avi_prores_test_pixels(&expected_first).0, avi_prores_test_pixels(&expected_second).0); + + make_generated_avi_indexless(&mut bytes); + let demuxed = avi::open(bytes.as_slice()).expect("open scanned AVI"); + assert_eq!(demuxed.index, avi::IndexSource::Scan); + let video = &demuxed.streams[0]; + assert!(!video.keyframes_known); + assert_eq!((video.chunks.len(), video.chunks[0].size), (3, 1)); + + let opened = crate::stream::open_bytes("scanned-prores.avi", Arc::from(bytes)).expect("open indexless AVI"); + let cold = avi_prores_test_picture(&opened, second); + assert_eq!(avi_prores_test_pixels(&cold), avi_prores_test_pixels(&expected_second)); + assert!(opened.video_frame(effectcraft_time::Tick(0), 1.0).is_err(), "the requested corrupt picture remains an error"); + + let after_error = avi_prores_test_picture(&opened, second); + assert_eq!(avi_prores_test_pixels(&after_error), avi_prores_test_pixels(&expected_second)); + let backward = avi_prores_test_picture(&opened, first); + assert_eq!(avi_prores_test_pixels(&backward), avi_prores_test_pixels(&expected_first)); + } + #[test] fn oversized_prores_alpha_probe_refuses_without_reading() { let mut read_count = 0; From abb7b66de53fd1d9e42f790a3616a477bcbeeb50 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:22:30 +0800 Subject: [PATCH 366/393] psd: share legacy Mac Roman layer-name decoding (#4056) --- Cargo.lock | 1 + Cargo.toml | 1 + crates/psd/Cargo.toml | 1 + crates/psd/src/parse.rs | 7 +------ crates/psd/src/read.rs | 15 ++++++++++----- crates/psd/src/tests/unicode_name.rs | 26 ++++++++++++++++++++++++++ 6 files changed, 40 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 48e59a0b4..68eb957f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2426,6 +2426,7 @@ dependencies = [ name = "effectcraft-psd" version = "0.24.1" dependencies = [ + "craft-codepage", "craft-psd", "miniz_oxide 0.9.1", ] diff --git a/Cargo.toml b/Cargo.toml index 3301c483e..011553b8c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,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 = "3b8e426a260695af840a2cd79a064d40778f939e" } 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 = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" } +craft-codepage = { 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 = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } 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" } diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index 818331cce..aa9e77e07 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] craft-psd = { workspace = true } +craft-codepage = { workspace = true } miniz_oxide = "0.9" [dev-dependencies] diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 2f1ccd2b3..b5a69bb4f 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -102,7 +102,7 @@ impl Psd { hidden: rec.flags.hidden(), protect_transparency: rec.flags.transparency_protected(), channels, - name: mac_roman_string(&rec.name), + name: crate::read::decode_mac_roman(&rec.name), ..Default::default() }; if let craft_psd::MaskData::Mask(m) = &rec.mask { @@ -489,11 +489,6 @@ fn error(e: &craft_psd::PsdError) -> Error { } } -/// A Pascal string's bytes in the system (Mac Roman) encoding; ASCII covers the common case. -fn mac_roman_string(b: &[u8]) -> String { - b.iter().map(|&b| if b < 0x80 { b as char } else { super::read::mac_roman(b) }).collect() -} - /// App representation only; binary field framing belongs to craft-psd. fn from_shared_adjustment(value: craft_psd::adjust::Adjustment) -> Adjustment { use craft_psd::adjust::Adjustment as Shared; diff --git a/crates/psd/src/read.rs b/crates/psd/src/read.rs index 307998066..158675d89 100644 --- a/crates/psd/src/read.rs +++ b/crates/psd/src/read.rs @@ -80,12 +80,17 @@ impl<'a> Reader<'a> { let padded = total.div_ceil(pad) * pad; self.skip(padded - total)?; // Pascal strings are in the system (Mac Roman) encoding; ASCII covers the common case. - Ok(s.iter().map(|&b| if b < 0x80 { b as char } else { mac_roman(b) }).collect()) + Ok(decode_mac_roman(s)) } } -/// Mac OS Roman upper half (0x80..=0xFF), as published by the Unicode Consortium mapping table. -pub(crate) fn mac_roman(b: u8) -> char { - const T: &str = "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ\u{F8FF}ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"; - T.chars().nth((b - 0x80) as usize).unwrap_or('?') +/// Decode the legacy Pascal names in PSD and PSB. +pub(crate) fn decode_mac_roman(bytes: &[u8]) -> String { + bytes + .iter() + .map(|&byte| { + // Keep the ordinary space EffectCraft used for this byte in legacy Pascal names. + if byte == 0xca { ' ' } else { craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, byte) } + }) + .collect() } diff --git a/crates/psd/src/tests/unicode_name.rs b/crates/psd/src/tests/unicode_name.rs index 8785b1a49..a5616099c 100644 --- a/crates/psd/src/tests/unicode_name.rs +++ b/crates/psd/src/tests/unicode_name.rs @@ -84,3 +84,29 @@ fn missing_empty_or_malformed_unicode_name_keeps_pascal_name() { assert_eq!(Psd::parse(file.to_bytes().unwrap()).unwrap().layers[0].name, "Pascal"); } } + +#[test] +fn pascal_layer_name_keeps_legacy_mac_roman_and_unicode_precedence() { + let mut doc = WDoc::new(1, 1); + doc.rle = false; // The raw pixels have the same layout in PSD and PSB. + doc.layers = vec![WLayer::empty("Fallback", vec![])]; + let bytes = write(&doc); + for version in [craft_psd::Version::Psd, craft_psd::Version::Psb] { + let mut file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + file.header.version = version; + file.layer_info.as_mut().unwrap().layers[0].name = b"Caf\x8e\xca\xdb".to_vec(); + + for (unicode, expected) in + [(None, "Caf\u{e9} \u{20ac}"), (Some(vec![0, 0, 0, 1, 0]), "Caf\u{e9} \u{20ac}"), (Some(record(&[0x0041, 0x00a0, 0x0042])), "A\u{a0}B")] + { + let layer = &mut file.layer_info.as_mut().unwrap().layers[0]; + layer.blocks.retain(|b| b.key != *b"luni"); + if let Some(data) = unicode { + layer.blocks.push(craft_psd::tagged::TaggedBlock::new(*b"luni", data)); + } + let parsed = Psd::parse(file.to_bytes().unwrap()).unwrap(); + assert_eq!(parsed.psb, version.is_psb()); + assert_eq!(parsed.layers[0].name, expected); + } + } +} From ea64796b6e8213fc7b7a64eeb6864e3fd378ace4 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:24:09 +0800 Subject: [PATCH 367/393] media: derive audio-only AVI PCM duration from indexed blocks (#4042) Co-authored-by: Dylan M. Taylor --- crates/media/src/craft_source.rs | 39 +++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 15ae6bb10..b100c40de 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1427,9 +1427,15 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { } else { let duration = audio_candidates .iter() - .map(|&(idx, _, _, _)| { - let s = &file.streams[idx]; - Tick::from_units(i64::from(s.length).saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) + .map(|(idx, _, params, _)| { + let s = &file.streams[*idx]; + let units = if params.codec == CodecId::Pcm && s.sample_size > 0 { + // Playback counts complete blocks within each indexed chunk. + s.chunks.iter().fold(0i64, |units, chunk| units.saturating_add(i64::from(chunk.size / s.sample_size))) + } else { + i64::from(s.length) + }; + Tick::from_units(units.saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) }) .max() .unwrap_or(Tick::ZERO); @@ -4514,6 +4520,33 @@ mod tests { std::iter::repeat_n(sample.to_le_bytes(), count).flatten().collect() } + #[test] + fn audio_only_avi_counts_complete_indexed_pcm_blocks() { + let stream = avi::StreamSpec::Audio(avi::AudioSpec::pcm(48_000, 1, 16)); + let mut writer = avi::AviWriter::new(std::io::Cursor::new(Vec::new()), vec![stream], avi::MuxOptions::default()).expect("AVI writer"); + writer.write_chunk(0, &pcm_s16le_bytes(8_192, 7), true).expect("first chunk"); + writer.write_chunk(0, &pcm_s16le_bytes(16_384, 13), true).expect("second chunk"); + let mut bytes = writer.finish().expect("finish AVI").into_inner(); + // dwLength follows the AVI stream header's first 32 payload bytes. + let length_offset = bytes.windows(4).position(|tag| tag == b"strh").expect("stream header") + 8 + 32; + let mut durations = Vec::new(); + for declared_length in [1u32, 20, 200] { + bytes[length_offset..length_offset + 4].copy_from_slice(&declared_length.to_le_bytes()); + let stream = &avi::open(bytes.as_slice()).expect("demux fixture").streams[0]; + assert_eq!(stream.length, declared_length); + assert_eq!(stream.chunks.len(), 2); + let input: Arc<[u8]> = Arc::from(bytes.as_slice()); + let footage = crate::probe::probe_bytes("indexed-pcm.avi", input.clone()).expect("public probe"); + assert!(footage.has_audio && !footage.has_video); + durations.push(footage.duration); + + let source = open_bytes("indexed-pcm.avi", input).expect("recognized AVI").expect("shared AVI"); + let tail = source.audio(19, 2, 48_000).expect("read final sample and EOF"); + assert_eq!(tail.channels[0], [0.5, 0.0]); + } + assert_eq!(durations, [effectcraft_time::Tick::from_units(20, 48_000); 3]); + } + #[test] fn matroska_duration_follows_presentation_order() { use craft_media::matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec, ebml, element_ids}; From 716d03e4621163d1af5d54448eb5ac3a8a8723e7 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:28:05 +0800 Subject: [PATCH 368/393] media: probe Matroska ProRes coded alpha (#4034) * media: probe Matroska ProRes coded alpha * Keep shared Matroska reads when ProRes alpha is unknown --- crates/media/src/craft_source.rs | 69 +++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index b100c40de..720298b9d 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1056,6 +1056,17 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option 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 coded_alpha = if video_params.codec == CodecId::ProRes { + // Bound the reconstructed packet, including the prefix restored by Matroska. + // Unknown alpha must not disable the shared reader for later pictures. + video_track + .sample_size(0) + .and_then(|size| u32::try_from(size).ok()) + .and_then(|size| prores_has_alpha(size, || file.read_sample(&*source, v_idx, 0).ok())) + .unwrap_or(false) + } else { + false + }; 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()))), @@ -1068,7 +1079,7 @@ fn open_matroska(name: &str, source: SharedBytes) -> Option codec: codec_name, pixel_format: String::new(), color, - has_alpha: false, + has_alpha: coded_alpha, bitrate: None, hdr: None, }; @@ -3625,6 +3636,62 @@ mod tests { assert_eq!(tick_to_units(Tick(craft_time::TICKS_PER_SECOND), 90000), 90000); } + fn prores_matroska(packets: &[&[u8]]) -> Arc<[u8]> { + use craft_media::matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec}; + use craft_video::prores::Profile; + use std::io::Cursor; + + let mut track = TrackSpec::new(TrackKind::Video, "V_PRORES"); + track.video_size = Some((16, 16)); + track.codec_private = Profile::P4444.fourcc().to_vec(); + track.default_duration_ns = Some(40_000_000); + let mut mux = MkvWriter::new(Cursor::new(Vec::new()), vec![track], MuxOptions::default()).expect("Matroska writer"); + for (index, packet) in packets.iter().enumerate() { + mux.write_frame(0, index as i64 * 40_000_000, true, packet, None).expect("write ProRes"); + } + mux.finish().expect("finish Matroska").into_inner().into() + } + + #[test] + fn matroska_prores_coded_alpha_reaches_the_public_probe() { + use craft_video::prores::{ChromaFormat, Encoder, EncoderConfig, Frame, Profile}; + use effectcraft_project::AlphaMode; + + for with_alpha in [true, false] { + let mut config = EncoderConfig::new(Profile::P4444, 16, 16); + config.encode_alpha = with_alpha; + config.threads = false; + let mut picture = Frame::new(16, 16, ChromaFormat::Yuv444, 10, with_alpha).expect("allocate picture"); + if let Some(alpha) = &mut picture.alpha { + alpha.fill(512); + } + let packet = Encoder::with_config(config).encode(&picture).expect("encode ProRes"); + let bytes = prores_matroska(&[&packet]); + + let source = open_bytes("alpha.mkv", bytes.clone()).expect("recognized Matroska").expect("shared Matroska"); + let frame = source.video_frame(FrameRequest { time: Tick::ZERO, scale: 1.0 }).expect("decode ProRes"); + assert_eq!(matches!(frame.data, PixelData::Yuv16 { alpha: Some(_), .. }), with_alpha); + + let footage = crate::probe::probe_bytes("alpha.mkv", bytes).expect("public Matroska probe"); + assert_eq!(footage.codec, "ProRes"); + assert_eq!(footage.alpha, if with_alpha { AlphaMode::Straight } else { AlphaMode::Ignore }); + } + } + + #[test] + fn matroska_prores_unreadable_alpha_probe_keeps_the_shared_route() { + use craft_video::prores::{ChromaFormat, Encoder, Frame, Profile}; + + let picture = Frame::new(16, 16, ChromaFormat::Yuv444, 10, false).expect("allocate picture"); + let packet = Encoder::new(Profile::P4444, 16, 16).encode(&picture).expect("encode ProRes"); + let bytes = prores_matroska(&[&[0; 3], &packet]); + let source = open_bytes("later-frame.mkv", bytes).expect("recognized Matroska").expect("shared Matroska"); + assert!(!source.info().video.as_ref().expect("video info").has_alpha); + let time = Tick::from_units(40, 1_000); + let later = source.video_frame(FrameRequest { time, scale: 1.0 }).expect("read intact second picture"); + assert_eq!(later.pts, time); + } + #[test] fn clean_aperture_rounds_signed_offsets_and_ignores_invalid_regions() { let aperture = isobmff::CleanAperture { width: (17, 2), height: (15, 2), horiz_offset: (1, 2), vert_offset: (-1, 2) }; From a28fcd18dd3b3df9a696086169c4f7831a4f7b30 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:30:18 +0800 Subject: [PATCH 369/393] media: route standalone FLAC through craft-audio (#4045) Co-authored-by: Dylan M. Taylor --- crates/media/Cargo.toml | 6 +- crates/media/src/craft_source.rs | 34 ++- .../media/src/craft_source/standalone_flac.rs | 225 ++++++++++++++++++ 3 files changed, 256 insertions(+), 9 deletions(-) create mode 100644 crates/media/src/craft_source/standalone_flac.rs diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 5c6e728db..6a2ddcfdd 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -27,7 +27,7 @@ craft-dpx = { workspace = true } craft-exr = { workspace = true, features = ["decode"] } craft-gif = { workspace = true, features = ["frames"] } craft-webp = { workspace = true, features = ["frames"] } -craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode", "flac-decode"] } craft-color = { workspace = true } craft-frame = { workspace = true } craft-media = { workspace = true, features = ["mpegts", "avi", "mxf"] } @@ -52,7 +52,7 @@ gif = { workspace = true } tempfile = { workspace = true } # (tests render comps that read layers through effects; already a dependency of effectcraft-render) effectcraft-effects = { workspace = true } -# Pure-Rust AAC test fixture encoding (no external ffmpeg dependency). -craft-audio = { workspace = true, features = ["aac-encode"] } +# Pure-Rust AAC and FLAC fixture encoding. +craft-audio = { workspace = true, features = ["aac-encode", "flac-encode"] } # APV import parity fixtures use the existing shared encoder. craft-video = { workspace = true, features = ["apv-encode"] } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 720298b9d..ea98cd383 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -30,9 +30,10 @@ //! `Apv`, other raw AVI layouts) or unsupported audio. //! - **Other containers & standalone audio**: //! - Shared (`craft_audio::Decoder` with `decode-native`): standalone `WAV`, `AIFF`, `MP3`/`MP2`/`MP1`, -//! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). -//! - Fallback (`filmcraft-codecs`): `Ogg Vorbis`, `FLAC`, `CAF`, or unsupported WAV/AIFF -//! encodings. +//! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). Bounded standalone FLAC uses the shared native +//! FLAC decoder and the same resampling policy. +//! - Fallback (`filmcraft-codecs`): `Ogg Vorbis`, `CAF`, or FLAC and WAV/AIFF input the shared +//! readers decline. use std::sync::{Arc, Mutex}; @@ -56,6 +57,8 @@ use craft_video::{TrackDecoder, TrackDecoderOptions, VideoError, prores}; mod raw_avi; use raw_avi::RawAvi; +mod standalone_flac; + /// Maximum worker threads per `TrackDecoder` instance. const MAX_WORKERS: usize = 8; @@ -134,6 +137,9 @@ pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Opti if let Some(fmt) = mpegts::sniff(head) { return open_mpeg(name, fmt, reader.clone()); } + if let Some(source) = standalone_flac::open_reader(name, head, reader) { + return Some(Ok(source)); + } open_standalone_audio(name, head, reader.clone()) } @@ -154,6 +160,9 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option::len(&bytes).min(64); @@ -2004,7 +2013,14 @@ impl MediaSource for StandaloneAudioSource { /// Step the fractional input position as an exact integer quotient and remainder; /// rounding happens only when interpolating a sample, independent of the window. -fn resample_audio_with_phase(decoded: &[Vec], native_rate: u32, sample_rate: u32, frames: usize, phase: u64, first_output: usize) -> Vec> { +fn resample_audio_with_phase( + decoded: &[impl AsRef<[f32]>], + native_rate: u32, + sample_rate: u32, + frames: usize, + phase: u64, + first_output: usize, +) -> Vec> { let mut out = vec![vec![0.0; frames]; decoded.len()]; let divisor = u64::from(sample_rate); let first = first_output as u128 * u128::from(native_rate) + u128::from(phase); @@ -2014,6 +2030,7 @@ fn resample_audio_with_phase(decoded: &[Vec], native_rate: u32, sample_rate let remainder_step = u64::from(native_rate % sample_rate); let inverse_rate = f64::from(sample_rate).recip(); for (samples, dst) in decoded.iter().zip(&mut out) { + let samples = samples.as_ref(); let (mut index, mut remainder) = (first_index, first_remainder); for sample in dst.iter_mut().skip(first_output) { let Some(&a) = samples.get(index) else { break }; @@ -2075,11 +2092,16 @@ fn resampling_window(start: i64, frames: usize, native_rate: u32, sample_rate: u if sample_rate == native_rate { return Some((start, frames, 0)); } + let (origin, phase) = resampling_origin(start, native_rate, sample_rate)?; + let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize; + Some((origin, len, phase)) +} + +fn resampling_origin(start: i64, native_rate: u32, sample_rate: u32) -> Option<(i64, u64)> { let scaled = i128::from(start) * i128::from(native_rate); let divisor = i128::from(sample_rate); let origin = i64::try_from(scaled.div_euclid(divisor)).ok()?; - let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize; - Some((origin, len, scaled.rem_euclid(divisor) as u64)) + Some((origin, scaled.rem_euclid(divisor) as u64)) } fn drain_audio_window(buf: &mut [Vec], decoded_pos: &mut i64, channels_count: usize, start: i64, frames: usize) -> Vec> { diff --git a/crates/media/src/craft_source/standalone_flac.rs b/crates/media/src/craft_source/standalone_flac.rs new file mode 100644 index 000000000..e4b94d6e0 --- /dev/null +++ b/crates/media/src/craft_source/standalone_flac.rs @@ -0,0 +1,225 @@ +//! Standalone FLAC through the pinned shared decoder. The source retains bounded decoded PCM. + +use std::sync::Arc; + +use craft_audio::{AudioBuffer, flac}; +use craft_frame::VideoFrame; +use craft_media_source::{AudioStreamInfo, DEFAULT_MAX_MEDIA_BYTES, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedSource}; +#[cfg(any(unix, windows))] +use craft_media_source::{SharedBytes, read_range}; +use craft_time::Tick; + +use super::{resample_audio_with_phase, resampling_origin}; + +/// Preserve the previous reader's ceiling for an individual PCM request. +const MAX_AUDIO_REQUEST_BYTES: usize = 512 << 20; + +fn looks_like_flac(name: &str, head: &[u8]) -> bool { + head.starts_with(b"fLaC") + || head.starts_with(b"ID3") && std::path::Path::new(name).extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("flac")) +} + +#[cfg(any(unix, windows))] +pub(super) fn open_reader(name: &str, head: &[u8], source: &SharedBytes) -> Option { + if !looks_like_flac(name, head) { + return None; + } + let bytes = read_range(&**source, 0, usize::try_from(source.len()).ok()?).ok()?; + open_bytes(name, &bytes) +} + +pub(super) fn open_bytes(name: &str, bytes: &[u8]) -> Option { + if !looks_like_flac(name, bytes) || bytes.len() > DEFAULT_MAX_MEDIA_BYTES { + return None; + } + // Keep both the compressed and decoded inputs within the shared media buffer budget. + // Declining the file leaves the prior reader available, including its broader recovery. + let max_values = (DEFAULT_MAX_MEDIA_BYTES / std::mem::size_of::()) as u64; + let decoded = flac::decode_with_limit(bytes, max_values).ok()?; + let rate = decoded.info.sample_rate; + let frames = decoded.channels.first()?.len(); + if frames == 0 || rate == 0 { + return None; + } + + let scale = 2.0_f32.powi(1 - i32::from(decoded.info.bits_per_sample)); + let samples = decoded.channels.into_iter().map(|plane| plane.into_iter().map(|sample| sample as f32 * scale).collect()).collect(); + let info = MediaInfo { + name: name.into(), + kind: MediaKind::AudioOnly, + duration: Tick::from_units(i64::try_from(frames).ok()?, i64::from(rate)), + video: None, + audio_streams: vec![AudioStreamInfo { + sample_rate: rate, + channels: u32::from(decoded.info.channels), + codec: "FLAC".into(), + bits_per_sample: Some(u32::from(decoded.info.bits_per_sample)), + }], + container: "FLAC".into(), + start_timecode: None, + file_size: Some(bytes.len() as u64), + }; + Some(Arc::new(FlacSource { info, rate, samples })) +} + +struct FlacSource { + info: MediaInfo, + rate: u32, + samples: Vec>, +} + +impl MediaSource for FlacSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, _req: FrameRequest) -> Result> { + Err(MediaError::NoStream("video")) + } + + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result { + if sample_rate == 0 { + return Err(MediaError::Decode("audio sample rate must be nonzero".into())); + } + if frames.checked_mul(self.samples.len()).and_then(|n| n.checked_mul(std::mem::size_of::())).is_none_or(|n| n > MAX_AUDIO_REQUEST_BYTES) { + return Err(MediaError::Decode("FLAC audio request exceeds the PCM buffer limit".into())); + } + let prefix = if start < 0 { usize::try_from(start.unsigned_abs()).unwrap_or(frames).min(frames) } else { 0 }; + let Some((origin, phase)) = resampling_origin(start.max(0), self.rate, sample_rate) else { + return Ok(AudioBuffer::new(sample_rate, self.samples.len() as u16, frames)); + }; + let origin = usize::try_from(origin).unwrap_or(usize::MAX); + let tail: Vec<&[f32]> = self.samples.iter().map(|plane| plane.get(origin..).unwrap_or_default()).collect(); + // Keep the true end of the PCM tail so interpolation holds the final sample until + // the clip ends. Padding this input tail would fade the final sample into silence. + let mut channels = resample_audio_with_phase(&tail, self.rate, sample_rate, frames - prefix, phase, 0); + if prefix != 0 { + for channel in &mut channels { + channel.resize(frames, 0.0); + channel.rotate_right(prefix); + } + } + Ok(AudioBuffer { sample_rate, channels }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions}; + use craft_media_source::{MediaError, MediaKind, SharedSource}; + use craft_time::Tick; + + use crate::stream::{self, MediaSource as OpenedSource}; + + const RATE: u32 = 48_000; + const FRAMES: usize = 4_501; + + fn fixture() -> (Vec, AudioBuffer) { + let left = (0..FRAMES).map(|i| ((i * 23 % 350) as f32 - 170.0) / 512.0).collect(); + let right = (0..FRAMES).map(|i| (220.0 - (i * 37 % 470) as f32) / 512.0).collect(); + let pcm = AudioBuffer { sample_rate: RATE, channels: vec![left, right] }; + let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int24); + (craft_audio::encode(&pcm, &opts).unwrap(), pcm) + } + + fn require_shared(opened: OpenedSource) -> SharedSource { + let OpenedSource::Craft(source) = opened else { panic!("FLAC should use the shared reader") }; + source + } + + #[test] + #[cfg(any(unix, windows))] + fn standalone_flac_uses_shared_source_for_disk_and_memory() { + let (bytes, pcm) = fixture(); + let bytes: Arc<[u8]> = bytes.into(); + let memory = require_shared(stream::open_bytes("music.flac", bytes.clone()).unwrap()); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("music.flac"); + std::fs::write(&path, &bytes).unwrap(); + let disk = require_shared(stream::open_source(&path).unwrap().0.unwrap()); + let legacy = filmcraft_codecs::open_bytes("music.flac", bytes.clone()).unwrap(); + + for source in [memory, disk] { + let info = source.info(); + let stream = info.audio().unwrap(); + assert_eq!(info.kind, MediaKind::AudioOnly); + assert_eq!(info.duration, Tick::from_units(FRAMES as i64, i64::from(RATE))); + assert_eq!(info.file_size, Some(bytes.len() as u64)); + assert_eq!(info.container, legacy.info().container); + assert_eq!(stream.codec, legacy.info().audio().unwrap().codec); + assert_eq!((stream.sample_rate, stream.channels, stream.bits_per_sample), (RATE, 2, Some(24))); + let decoded = source.audio(0, FRAMES, RATE).unwrap(); + assert_eq!((decoded.sample_rate, decoded.num_channels(), decoded.frames()), (RATE, 2, FRAMES)); + for (got, want) in decoded.channels.iter().flatten().zip(pcm.channels.iter().flatten()) { + assert_eq!(got, want); + } + + // Seek backwards, across the encoder's block boundary, and around both clip edges. + for (rate, start, frames) in [(RATE, 4091, 20), (RATE, -3, 8), (96_000, 8998, 10), (44_100, 251, 39), (44_100, 61, 39)] { + let got = source.audio(start, frames, rate).unwrap(); + let want = legacy.audio(start, frames, rate).unwrap(); + assert_eq!(got.channels[0].len(), frames); + for (got, want) in got.channels.iter().zip(&want.channels) { + for (got, want) in got.iter().zip(want) { + assert!((got - want).abs() <= 1e-6, "output rate {rate}, start {start}: {got} vs {want}"); + } + } + } + + let full = source.audio(61, 63, 44_100).unwrap(); + let left = source.audio(61, 23, 44_100).unwrap(); + let right = source.audio(84, 40, 44_100).unwrap(); + for ((whole, left), right) in full.channels.iter().zip(&left.channels).zip(&right.channels) { + assert_eq!(&whole[..23], left); + assert_eq!(&whole[23..], right); + } + assert!(matches!(source.audio(0, usize::MAX, RATE), Err(MediaError::Decode(_)))); + assert!(matches!(source.audio(0, 1, 0), Err(MediaError::Decode(_)))); + } + } + + #[test] + #[cfg(any(unix, windows))] + fn standalone_flac_keeps_legacy_trailer_compatibility() { + let (mut bytes, pcm) = fixture(); + bytes.extend_from_slice(b"trailing bytes"); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("trailer.flac"); + std::fs::write(&path, &bytes).unwrap(); + let disk = stream::open_source(&path).unwrap().0.unwrap(); + let memory = stream::open_bytes("trailer.flac", bytes.into()).unwrap(); + for opened in [disk, memory] { + let OpenedSource::Film(source) = opened else { panic!("the existing reader should accept the trailer") }; + let prefix = source.audio(0, 32, RATE).unwrap(); + assert_eq!((prefix.channels[0].as_slice(), prefix.channels[1].as_slice()), (&pcm.channels[0][..32], &pcm.channels[1][..32])); + } + } + + #[test] + #[cfg(any(unix, windows))] + fn native_flac_opener_declines_an_oversized_file_without_reading_it() { + use std::sync::atomic::{AtomicBool, Ordering}; + + use craft_media::ByteSource; + use craft_media_source::{DEFAULT_MAX_MEDIA_BYTES, SharedBytes}; + + struct OversizedFile(AtomicBool); + impl ByteSource for OversizedFile { + fn len(&self) -> u64 { + DEFAULT_MAX_MEDIA_BYTES as u64 + 1 + } + + fn read_at(&self, _: u64, _: &mut [u8]) -> std::io::Result<()> { + self.0.store(true, Ordering::Relaxed); + Err(std::io::Error::other("oversized input was read")) + } + } + + let file = Arc::new(OversizedFile(AtomicBool::new(false))); + let source: SharedBytes = file.clone(); + assert!(super::open_reader("oversized.flac", b"fLaC", &source).is_none()); + assert!(!file.0.load(Ordering::Relaxed)); + } +} From f70208cef39195dc82db75068a920730c0283aef Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:31:03 +0800 Subject: [PATCH 370/393] media: route MP4 and Matroska FLAC through craft-audio (#4049) * media: route MP4 and Matroska FLAC through craft-audio * media: propagate errors when generating FLAC test fixtures --------- Co-authored-by: Dylan M. Taylor --- Cargo.lock | 54 ++++---- Cargo.toml | 14 +-- crates/media/src/craft_source.rs | 71 ++++++----- .../src/craft_source/flac_tracks_tests.rs | 116 ++++++++++++++++++ 4 files changed, 194 insertions(+), 61 deletions(-) create mode 100644 crates/media/src/craft_source/flac_tracks_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 68eb957f3..5ec8226e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1207,10 +1207,10 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "log", "thiserror 2.0.21", ] @@ -1266,7 +1266,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "serde", ] @@ -1341,10 +1341,10 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-frame" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "craft-color", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "rayon", "serde", ] @@ -1415,7 +1415,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9 [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "chrono", "thiserror 2.0.21", @@ -1441,13 +1441,13 @@ dependencies = [ [[package]] name = "craft-media-source" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-color", "craft-frame", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "serde", "thiserror 2.0.21", ] @@ -1584,7 +1584,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" dependencies = [ "serde", "thiserror 2.0.21", @@ -1593,7 +1593,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=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ "serde", "thiserror 2.0.21", @@ -1697,9 +1697,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "rav1e", "rayon", "thiserror 2.0.21", @@ -1745,6 +1745,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -2146,11 +2156,11 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-exr", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -2312,17 +2322,17 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-color", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-exr", "craft-frame", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-media-source", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", "craft-webp", "effectcraft-color", "effectcraft-effects", diff --git a/Cargo.toml b/Cargo.toml index 011553b8c..e5753ceff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,13 +97,13 @@ same-file = "1.0" tempfile = "3.27" # codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["isobmff", "matroska"] } -craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", default-features = false, features = ["isobmff", "matroska"] } +craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # 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. diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index ea98cd383..5405c5b9e 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -10,14 +10,14 @@ //! - Shared (`craft-media::isobmff` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes` (coded alpha via `craft_video::prores::probe`, #3999), `Dnxhd`, //! `Mpeg2Video`, and strictly admitted video-only `Apv` MP4; -//! audio `Aac`, `Alac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. +//! audio `Aac`, `Alac`, `Flac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. //! - Fallback (`filmcraft-codecs`): `Mjpeg`, `Mpeg4Video`, `Ffv1`, other `Apv`, or unsupported audio. //! - **Matroska / WebM (`MKV`/`MKA`/`WebM`, video+audio & audio-only)**: //! - Shared (`craft-media::matroska` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, -//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Opus`, `Ac3`, +//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Flac`, `Opus`, `Ac3`, //! `Mp3`/`Mp2`/`Mp1` (with `CodecDelay` + `SeekPreRoll` timing). //! - Fallback (`filmcraft-codecs`): `alpha_mode == 1` (`BlockAdditional` alpha), unreadable/zlib -//! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Flac`/`Pcm`). +//! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Pcm`). //! - **MXF (`MXF`, video+audio & audio-only OP1a/OP-Atom)**: //! - Shared (`craft-media::mxf` + `craft-video` + `MxfFile::read_pcm`): `H264`, `Hevc`, `Av1`, //! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; sound `Pcm` and `Aes3` (D-10). @@ -420,7 +420,7 @@ fn place_packet(packet: PacketTime, next: &mut Option, tolerance: u64) -> i start } -struct OpusPrefix { +struct PacketTimingPrefix { len: usize, next: Option, tolerance: u64, @@ -428,27 +428,28 @@ struct OpusPrefix { } struct AudioStarts { - // For Opus, unvisited entries still hold raw container stamps. Resolve in place + // Unvisited entries still hold raw container stamps. Resolve in place // as packets arrive, reusing this table for the finished timeline. positions: Vec, - opus: Option, + pending: Option, } impl AudioStarts { fn complete(positions: Vec) -> Self { - Self { positions, opus: None } + Self { positions, pending: None } } - fn opus(positions: Vec, tolerance: i64) -> Self { + fn from_packet_timing(positions: Vec, tolerance: i64) -> Self { // Open resolves exactly the bounded lookahead before anyone can seek. let min_pending_stamp = positions.iter().skip(AUDIO_LOOKAHEAD).copied().min().unwrap_or(i64::MIN); - let opus = (!positions.is_empty()).then_some(OpusPrefix { len: 0, next: None, tolerance: tolerance.max(0).unsigned_abs(), min_pending_stamp }); - Self { positions, opus } + let pending = + (!positions.is_empty()).then_some(PacketTimingPrefix { len: 0, next: None, tolerance: tolerance.max(0).unsigned_abs(), min_pending_stamp }); + Self { positions, pending } } fn start(&self, file: &ContainerFile, track: usize, idx: usize) -> Option { let stamp = *self.positions.get(idx)?; - let Some(prefix) = &self.opus else { return Some(stamp) }; + let Some(prefix) = &self.pending else { return Some(stamp) }; if idx < prefix.len { return Some(stamp); } @@ -459,22 +460,26 @@ impl AudioStarts { }) } - fn observe(&mut self, file: &ContainerFile, track: usize, idx: usize, packet: &[u8]) { - let Some(prefix) = &mut self.opus else { return }; + fn observe(&mut self, file: &ContainerFile, track: usize, idx: usize, packet: &[u8], decoder: &AudioTrackDecoder) { + let Some(prefix) = &mut self.pending else { return }; if idx != prefix.len { return; } - let timing = - PacketTime { stamp: self.positions[idx], stamped: file.audio_packet_is_stamped(track, idx), samples: opus_packet_samples(packet).map(i64::from) }; + let samples = match decoder.codec() { + CodecId::Opus => opus_packet_samples(packet).map(i64::from), + CodecId::Flac => decoder.flac_packet_frames(packet).and_then(|n| i64::try_from(n).ok()), + _ => None, + }; + let timing = PacketTime { stamp: self.positions[idx], stamped: file.audio_packet_is_stamped(track, idx), samples }; self.positions[idx] = place_packet(timing, &mut prefix.next, prefix.tolerance); prefix.len += 1; if prefix.len == self.positions.len() { - self.opus = None; + self.pending = None; } } fn seek_proves_first_packet(&self, target: i64) -> bool { - let Some(prefix) = &self.opus else { return false }; + let Some(prefix) = &self.pending else { return false }; // A normal read that starts before the very first packet looks like a // backward seek. It need not read the suffix if the ordinary seek // would back up to packet 0 anyway. Stamped starts can only move by the @@ -485,18 +490,18 @@ impl AudioStarts { && self.positions.get(AUDIO_SEEK_BACKUP_PACKETS + 1..prefix.len).is_some_and(|p| p.iter().all(|&start| start > target)) } - fn finish_for_seek(&mut self, file: &ContainerFile, source: &dyn ByteSource, track: usize) -> Result<()> { + fn finish_for_seek(&mut self, file: &ContainerFile, source: &dyn ByteSource, track: usize, decoder: &AudioTrackDecoder) -> Result<()> { // The exact recurrence can carry a timing phase across arbitrarily many // rounded or laced packets. A first discontinuous seek may still have to // index the unread suffix; normal open and sequential decode never do this. - while let Some(idx) = self.opus.as_ref().map(|prefix| prefix.len) { + while let Some(idx) = self.pending.as_ref().map(|prefix| prefix.len) { if filmcraft_media::cancel::cancelled() { return Err(MediaError::Cancelled); } // Do not commit a guessed duration after an I/O error; the next // request can retry this packet without re-reading the valid prefix. let packet = file.read_sample(source, track, idx)?; - self.observe(file, track, idx, &packet); + self.observe(file, track, idx, &packet, decoder); } Ok(()) } @@ -556,8 +561,8 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code let ts = i128::from(track.timescale.max(1)); let stamps: Vec = (0..track.samples.len()).map(|i| isobmff_audio_position(track, i, native_rate)).collect(); let unit = i64::try_from((rate + ts - 1) / ts).unwrap_or(i64::MAX); - if codec == CodecId::Opus { - return AudioStarts::opus(stamps, unit.saturating_mul(2).saturating_add(1)); + if matches!(codec, CodecId::Opus | CodecId::Flac) { + return AudioStarts::from_packet_timing(stamps, unit.saturating_mul(2).saturating_add(1)); } let Some(frame) = fixed_samples else { return AudioStarts::complete(stamps); @@ -579,8 +584,8 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code i64::try_from(audio_frames_from_ns(ns, native_rate) - delay_frames).unwrap_or(0) }; let tick_samples = i64::try_from(i128::from(track.ticks_to_ns(2)) * rate / 1_000_000_000).unwrap_or(i64::MAX).saturating_add(1); - if codec == CodecId::Opus { - return AudioStarts::opus(track.samples.iter().map(|s| stamp_for(s.pts)).collect(), tick_samples); + if matches!(codec, CodecId::Opus | CodecId::Flac) { + return AudioStarts::from_packet_timing(track.samples.iter().map(|s| stamp_for(s.pts)).collect(), tick_samples); } let Some(frame) = fixed_samples else { return AudioStarts::complete(track.samples.iter().map(|s| stamp_for(s.pts)).collect()); @@ -671,9 +676,9 @@ where let codec = dec.codec(); let fixed_samples = fixed_packet_samples(&mut dec, codec, &lookahead); let mut audio_starts = compute_audio_starts(container, idx, codec, native_rate, fixed_samples); - if codec == CodecId::Opus { + if audio_starts.pending.is_some() { for (s_idx, pkt) in lookahead.iter().enumerate() { - audio_starts.observe(container, idx, s_idx, pkt); + audio_starts.observe(container, idx, s_idx, pkt, &dec); } } let seek_preroll_samples = match container { @@ -688,7 +693,7 @@ where sample_rate: native_rate, channels, codec: params.codec.name().to_string(), - bits_per_sample: params.pcm.map(|p| u32::from(p.bits)), + bits_per_sample: dec.flac_stream_info().map(|info| u32::from(info.bits_per_sample)).or_else(|| params.pcm.map(|p| u32::from(p.bits))), }); audio_tracks.push(AudioTrackEntry { track_idx: idx, @@ -2201,7 +2206,7 @@ fn decode_audio_range( let (seek_idx, decoded_pos) = if moves_backward && state.next_sample == 0 && state.audio_starts.seek_proves_first_packet(target) { (0, state.decoded_pos) } else { - state.audio_starts.finish_for_seek(file, source, track_idx)?; + state.audio_starts.finish_for_seek(file, source, track_idx, &state.decoder)?; file.audio_seek_info(track_idx, &state.audio_starts.positions, seek_preroll_samples, start) }; state.decoder.reset(); @@ -2233,7 +2238,7 @@ fn decode_audio_range( break; } let pkt = file.read_sample(source, track_idx, idx)?; - state.audio_starts.observe(file, track_idx, idx, &pkt); + state.audio_starts.observe(file, track_idx, idx, &pkt, &state.decoder); state.next_sample = idx + 1; let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?; let buf_len = state.buf.first().map_or(0, Vec::len) as i64; @@ -2770,6 +2775,8 @@ fn estimate_matroska_frame_rate(track: &matroska::Track) -> FrameRate { FrameRate::FPS_30 } +#[cfg(all(test, any(unix, windows)))] +mod flac_tracks_tests; #[cfg(all(test, any(unix, windows)))] mod raw_avi_tests; @@ -3154,7 +3161,7 @@ mod tests { assert_eq!(backward, decode(&mut reference[0], &source.bytes, backward_start, OPUS_FRAME)); let (_, state) = tracks[0].decoder_parts(); assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); - assert!(state.audio_starts.opus.is_none()); + assert!(state.audio_starts.pending.is_none()); early } @@ -3185,7 +3192,7 @@ mod tests { let (preroll, state) = fresh[0].decoder_parts(); let error = decode_audio_range(file, source, 0, OPUS_RATE, 1, preroll, state, start, 3 * OPUS_FRAME).unwrap_err(); assert!(matches!(error, MediaError::Io(_))); - assert_eq!(state.audio_starts.opus.as_ref().unwrap().len, transient_packet); + assert_eq!(state.audio_starts.pending.as_ref().unwrap().len, transient_packet); assert_eq!((state.next_sample, state.decoded_pos), (0, first)); } let cold = decode(&mut fresh[0], source, start, 3 * OPUS_FRAME); @@ -3193,7 +3200,7 @@ mod tests { assert!(cold[0].iter().any(|s| s.abs() > 1e-5)); let (_, state) = fresh[0].decoder_parts(); assert_eq!(state.audio_starts.positions.as_slice(), expected_positions); - assert!(state.audio_starts.opus.is_none()); + assert!(state.audio_starts.pending.is_none()); } #[test] diff --git a/crates/media/src/craft_source/flac_tracks_tests.rs b/crates/media/src/craft_source/flac_tracks_tests.rs new file mode 100644 index 000000000..8395c81d1 --- /dev/null +++ b/crates/media/src/craft_source/flac_tracks_tests.rs @@ -0,0 +1,116 @@ +use std::io::Cursor; +use std::sync::Arc; + +use craft_audio::flac::{Encoder, EncoderConfig, STREAMINFO_OFFSET}; +use craft_media::{isobmff, matroska}; +use craft_media_source::MediaKind; + +use crate::stream::{self, MediaSource as OpenedSource}; + +const RATE: u32 = 96_000; +const BLOCK: usize = 1_000; +const FRAMES: usize = 196 * BLOCK + 221; +const COLD_SEEK: usize = 2 * RATE as usize + BLOCK + 200; + +struct Fixture { + private: Vec, + packets: Vec>, + samples: Vec>, +} + +impl Fixture { + fn new() -> Result> { + let left: Vec = (0..FRAMES).map(|i| (i as i32 * 307 % 65_536) - 30_000).collect(); + let right: Vec = (0..FRAMES).map(|i| 28_000 - (i as i32 * 701 % 59_000)).collect(); + let mut config = EncoderConfig::new(RATE, 2, 24); + config.block_size = BLOCK as u16; + let mut encoder = Encoder::new(config)?; + let mut packets = encoder.encode_frames(&[&left, &right])?; + packets.push(encoder.finish()); + let mut private = encoder.header(&[]); + let offset = STREAMINFO_OFFSET as usize; + private[offset..offset + 34].copy_from_slice(&encoder.streaminfo()); + Ok(Self { private, packets, samples: vec![left, right] }) + } + + fn mp4(&self) -> Result, Box> { + let offset = STREAMINFO_OFFSET as usize; + let mut entry = isobmff::SampleEntry::flac(self.private[offset..offset + 34].try_into()?); + entry.audio.as_mut().ok_or("FLAC sample entry needs an audio header")?.sample_rate = 48_000.0; + let mut writer = isobmff::Mp4Writer::new(Cursor::new(Vec::new()), isobmff::WriterOptions::new(isobmff::Brand::Mp4))?; + writer.add_track(isobmff::TrackConfig::new(entry, RATE))?; + for (i, packet) in self.packets.iter().enumerate() { + let duration = (FRAMES - i * BLOCK).min(BLOCK) as u32; + writer.write_sample(0, isobmff::WriteSample { data: packet, duration, composition_offset: 0, is_sync: true })?; + } + Ok(writer.finish()?.into_inner()) + } + + fn mkv(&self, private: &[u8]) -> Result, Box> { + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Audio, "A_FLAC"); + track.audio = Some((f64::from(RATE), 2, Some(24))); + track.codec_private = private.to_vec(); + let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?; + for (i, packet) in self.packets.iter().enumerate() { + // The muxer rounds starts to its millisecond clock. A 1000-frame packet + // at 96 kHz does not start on a millisecond boundary after packet zero. + let pts = (i * BLOCK) as i64 * 1_000_000_000 / i64::from(RATE); + let duration = (FRAMES - i * BLOCK).min(BLOCK) as u64 * 1_000_000_000 / u64::from(RATE); + writer.write_frame(0, pts, true, packet, Some(duration))?; + } + Ok(writer.finish()?.into_inner()) + } +} + +#[test] +fn flac_in_mp4_and_matroska_uses_shared_samples_after_cold_and_backward_seeks() -> Result<(), Box> { + let fixture = Fixture::new()?; + let dir = tempfile::tempdir().unwrap(); + for (name, bytes) in [("audio.mp4", fixture.mp4()?), ("audio.mka", fixture.mkv(&fixture.private)?)] { + let bytes: Arc<[u8]> = bytes.into(); + let path = dir.path().join(name); + std::fs::write(&path, &bytes).unwrap(); + let disk = stream::open_source(&path).unwrap().0.unwrap(); + let memory = stream::open_bytes(name, bytes).unwrap(); + for opened in [disk, memory] { + let OpenedSource::Craft(source) = opened else { panic!("{name}: expected the shared FLAC reader") }; + let info = source.info(); + assert_eq!(info.kind, MediaKind::AudioOnly); + let audio = info.audio().unwrap(); + assert_eq!((audio.codec.as_str(), audio.sample_rate, audio.channels, audio.bits_per_sample), ("FLAC", RATE, 2, Some(24))); + + for (start, frames) in [(COLD_SEEK, 48), (991, 33), (FRAMES - 25, 50), (0, FRAMES)] { + let decoded = source.audio(start as i64, frames, RATE).unwrap(); + assert_eq!((decoded.num_channels(), decoded.frames()), (2, frames)); + for (actual, expected) in decoded.channels.iter().zip(&fixture.samples) { + for (i, &sample) in actual.iter().enumerate() { + let want = expected.get(start + i).copied().unwrap_or(0) as f32 / 8_388_608.0; + assert_eq!(sample, want, "{name} sample {}", start + i); + } + } + } + + let whole = source.audio(451, 93, 44_100).unwrap(); + let first = source.audio(451, 31, 44_100).unwrap(); + let second = source.audio(482, 62, 44_100).unwrap(); + for ((whole, first), second) in whole.channels.iter().zip(&first.channels).zip(&second.channels) { + assert_eq!(&whole[..31], first, "{name} first resampled segment"); + assert_eq!(&whole[31..], second, "{name} second resampled segment"); + } + } + } + Ok(()) +} + +#[test] +fn flac_without_the_expected_private_marker_keeps_matroska_fallback() -> Result<(), Box> { + let fixture = Fixture::new()?; + let mut private = fixture.private.clone(); + private[..4].copy_from_slice(b"test"); + let OpenedSource::Film(source) = stream::open_bytes("legacy.mka", fixture.mkv(&private)?.into()).unwrap() else { + panic!("expected the legacy FLAC reader"); + }; + let decoded = source.audio(0, 16, RATE).unwrap(); + assert!(decoded.channels[0].iter().any(|&sample| sample != 0.0)); + Ok(()) +} From 563fea6582498e5b64a980ba3458a9d583e043bc Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:33:27 +0800 Subject: [PATCH 371/393] media: use the shared GIF text control fix (#4040) * media: use the shared GIF text control fix * chore: repin craft-gif to storytold/craft-libs main (ba25ccd2) --------- Co-authored-by: Dylan M. Taylor --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/media/src/gif_anim.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ec8226e3..81cc29132 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1352,7 +1352,7 @@ dependencies = [ [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ "gif", "image", diff --git a/Cargo.toml b/Cargo.toml index e5753ceff..c1c46eb1d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/c craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } 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 = "3b8e426a260695af840a2cd79a064d40778f939e" } -craft-gif = { 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 = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" } craft-codepage = { 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 = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } diff --git a/crates/media/src/gif_anim.rs b/crates/media/src/gif_anim.rs index dc5f55e27..146f18932 100644 --- a/crates/media/src/gif_anim.rs +++ b/crates/media/src/gif_anim.rs @@ -223,6 +223,32 @@ mod tests { assert!(e.to_lowercase().contains("memory"), "{e}"); } + #[test] + fn gif_probe_and_playback_respect_text_control_scope() { + let mut bytes = Vec::new(); + { + let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &[255, 0, 0, 0, 0, 255]).unwrap(); + for (index, delay, transparent) in [(0, 23, Some(0)), (1, 7, None)] { + let frame = gif::Frame { width: 2, height: 2, delay, transparent, buffer: vec![index; 4].into(), ..gif::Frame::default() }; + encoder.write_frame(&frame).unwrap(); + } + } + let offset = craft_gif::scan(&bytes, 1).unwrap().frames[0].offset; + // A text grid consumes the first Graphic Control Extension. The first + // image then uses the app's default display delay of 100 ms. + let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0]; + bytes.splice(offset..offset, text); + let bytes: std::sync::Arc<[u8]> = bytes.into(); + let footage = probe_bytes("text-control.gif", bytes.clone()).unwrap(); + let pool = MediaPool::new(); + pool.add_bytes("text-control.gif", bytes); + + assert_eq!( + (footage.duration, colour_at(&pool, &footage, 0.09), colour_at(&pool, &footage, 0.11)), + (Tick::from_units(17, 100), [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]) + ); + } + #[test] fn a_zero_delay_is_ten_hundredths_like_in_browsers() { let f = probe_bytes("a.gif", gif(&[(RED, 0), (GREEN, 1)]).into()).unwrap(); From 8fc2bc99c6cd4b83a3ae739db8089164d6374da2 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 03:02:47 +0800 Subject: [PATCH 372/393] media: route MXF through the shared header probe (#4058) Co-authored-by: Dylan M. Taylor --- crates/media/src/craft_source.rs | 79 ++++++++++++++++++++++++++------ crates/media/src/stream.rs | 9 ++-- 2 files changed, 69 insertions(+), 19 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 5405c5b9e..97a2d8b95 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -113,34 +113,34 @@ fn looks_like_matroska(head: &[u8]) -> bool { head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) } -/// True when `head` contains an MXF SMPTE KLV partition pack key. -fn looks_like_mxf(head: &[u8]) -> bool { - head.windows(12).any(|w| w == [0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01]) -} +/// The MXF sniffer needs the 16-byte partition key after the bounded 64 KiB run-in. +#[cfg(any(unix, windows))] +pub(crate) const NATIVE_SNIFF_HEAD_LEN: usize = 64 * 1024 + 16; /// Open an in-place ISO-BMFF, Matroska/WebM, MXF, AVI, MPEG-TS/PS, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. /// 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) { + let usual_head = &head[..head.len().min(craft_media_source::HEAD_LEN)]; + if looks_like_isobmff(usual_head) { return open_isobmff(name, reader.clone()); } - if looks_like_matroska(head) { + if looks_like_matroska(usual_head) { return open_matroska(name, reader.clone()); } - if looks_like_mxf(head) { + if mxf::sniff(head) { return open_mxf(name, reader.clone()); } - if avi::sniff(head) { + if avi::sniff(usual_head) { return open_avi(name, reader.clone()); } - if let Some(fmt) = mpegts::sniff(head) { + if let Some(fmt) = mpegts::sniff(usual_head) { return open_mpeg(name, fmt, reader.clone()); } - if let Some(source) = standalone_flac::open_reader(name, head, reader) { + if let Some(source) = standalone_flac::open_reader(name, usual_head, reader) { return Some(Ok(source)); } - open_standalone_audio(name, head, reader.clone()) + open_standalone_audio(name, usual_head, reader.clone()) } /// Open an in-memory ISO-BMFF, Matroska/WebM, MXF, AVI, MPEG-TS/PS, or standalone audio source via `craft-media` / `craft-video` / `craft-audio`. @@ -151,7 +151,7 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option Option<(Result, FileStamp let stamp = reader.stamp; 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) + if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, crate::craft_source::NATIVE_SNIFF_HEAD_LEN) && let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader) { return Some((res.map(MediaSource::Craft).map_err(MediaError::from), stamp)); @@ -261,9 +261,10 @@ pub(crate) fn probe_source(path: &Path) -> Option> { return None; } let reader = Arc::new(FileReader::open(path).ok()?); - let head = filmcraft_media::reader::read_range(&*reader, 0, filmcraft_media::reader::HEAD_LEN).ok()?; + let head = filmcraft_media::reader::read_range(&*reader, 0, crate::craft_source::NATIVE_SNIFF_HEAD_LEN).ok()?; + let legacy_head = &head[..head.len().min(filmcraft_media::reader::HEAD_LEN)]; let name = path.to_string_lossy(); - if crate::layered::sniff(&name, &head) || image::guess_format(&head).is_ok() { + if crate::layered::sniff(&name, legacy_head) || image::guess_format(legacy_head).is_ok() { return None; } let name = name_of(path); @@ -272,7 +273,7 @@ pub(crate) fn probe_source(path: &Path) -> Option> { return Some(res.map(MediaSource::Craft).map_err(MediaError::from)); } let fc_reader: filmcraft_media::SharedReader = reader; - filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, &head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into)) + filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, legacy_head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into)) } #[cfg(not(any(unix, windows)))] From 2f16feb12f4d5ef601b35b2858f9c9a87077f61e Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 03:10:33 +0800 Subject: [PATCH 373/393] media: present full-range high-depth RGB from the shared decoder (#4063) --- crates/media/src/craft_source.rs | 42 +++++++++- crates/media/src/craft_source/rgb8_tests.rs | 6 +- .../media/src/craft_source/wide_rgb_tests.rs | 82 +++++++++++++++++++ 3 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 crates/media/src/craft_source/wide_rgb_tests.rs diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 97a2d8b95..782496b7e 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -2300,6 +2300,9 @@ fn push_decoded( #[cfg(test)] mod rgb8_tests; +#[cfg(test)] +mod wide_rgb_tests; + fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: Tick) -> Result { let FramePresentation { container_color, par: default_par, rotation, aperture } = presentation; let (mut width, mut height) = (vf.width(), vf.height()); @@ -2311,7 +2314,7 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T Some(sar) => sar, None => default_par, }; - let color = resolve_color(tags, container_color); + let mut color = resolve_color(tags, container_color); let bit_depth = vf.bit_depth(); let (planes, alpha) = vf.into_planes(); @@ -2338,6 +2341,38 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T } PixelData::Rgba8(Arc::new(rgba)) } + ColorFamily::Rgb if color.range == Range::Full && (9..=16).contains(&bit_depth) && planes.iter().all(|p| p.bit_depth() == bit_depth) => { + let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height))); + if let Some(r) = luma { + (width, height) = (r.w as u32, r.h as u32); + } + let samples = (width as usize) + .checked_mul(height as usize) + .and_then(|n| n.checked_mul(4)) + .filter(|&n| n <= craft_frame::DEFAULT_MAX_FRAME_BYTES / size_of::()) + .ok_or_else(|| MediaError::Decode("RGB picture exceeds the frame buffer limit".into()))?; + let [r, g, b]: [Plane; 3] = planes.try_into().map_err(|_| MediaError::Decode("expected three RGB planes".into()))?; + let r = plane_u16(r, luma)?; + let g = plane_u16(g, luma)?; + let b = plane_u16(b, luma)?; + let alpha_max = alpha.as_ref().map_or(1, |a| ((1u32 << a.bit_depth()) - 1) as u16); + let alpha = alpha.map(|a| plane_u16(a, luma)).transpose()?.into_iter().flatten().chain(std::iter::repeat(alpha_max)); + // One transfer lookup per code avoids evaluating the curve per pixel and keeps + // every decoded code distinct, including at 16 bits. + let max_code = (1usize << bit_depth) - 1; + let mut transfer = Vec::new(); + transfer.try_reserve_exact(max_code + 1).map_err(|_| MediaError::Decode("could not allocate the RGB transfer table".into()))?; + transfer.extend((0..=max_code).map(|code| craft_color::to_linear(code as f32 / max_code as f32, color.transfer))); + let linear = |value: u16| transfer[usize::from(value).min(max_code)]; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(samples).map_err(|_| MediaError::Decode("could not allocate the RGB picture".into()))?; + for (((r, g), b), a) in r.into_iter().zip(g).zip(b).zip(alpha) { + let a = (f32::from(a) / f32::from(alpha_max)).min(1.0); + rgba.extend_from_slice(&[linear(r) * a, linear(g) * a, linear(b) * a, a]); + } + color.transfer = Transfer::Linear; + PixelData::RgbaF32(Arc::new(rgba)) + } ColorFamily::YCbCr => { let chroma = match subsampling { Subsampling::S420 => Chroma::C420, @@ -2474,6 +2509,10 @@ fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame { let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns); PixelData::Rgba8(Arc::new(rotated.into_flattened())) } + PixelData::RgbaF32(pixels) => { + let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns); + PixelData::RgbaF32(Arc::new(rotated.into_flattened())) + } 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), @@ -2513,7 +2552,6 @@ fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame { alpha: alpha.map(|a| Arc::new(rotate_plane(&a, w, h, turns))), } } - other => other, }; frame.width = nw; frame.height = nh; diff --git a/crates/media/src/craft_source/rgb8_tests.rs b/crates/media/src/craft_source/rgb8_tests.rs index 2cc78d441..8650f0a75 100644 --- a/crates/media/src/craft_source/rgb8_tests.rs +++ b/crates/media/src/craft_source/rgb8_tests.rs @@ -73,9 +73,11 @@ fn packed_rgb_keeps_stride_aperture_rotation_and_straight_alpha() -> TestResult } #[test] -fn higher_depth_rgb_is_not_quantized_to_packed_bytes() -> TestResult { +fn limited_range_high_depth_rgb_remains_unsupported() -> TestResult { let channel = Plane::packed(1, 1, 10, Samples::U16(vec![900]))?; let decoded = DecodedVideoFrame::new(1, 1, ColorFamily::Rgb, Subsampling::S444, vec![channel; 3], None)?; - assert!(matches!(to_craft_frame(decoded, presentation(), Tick::ZERO), Err(MediaError::Unsupported(_)))); + let color = ColorInfo { range: Range::Limited, ..ColorInfo::SRGB_FULL }; + let presentation = FramePresentation { container_color: Some(color), ..presentation() }; + assert!(matches!(to_craft_frame(decoded, presentation, Tick::ZERO), Err(MediaError::Unsupported(_)))); Ok(()) } diff --git a/crates/media/src/craft_source/wide_rgb_tests.rs b/crates/media/src/craft_source/wide_rgb_tests.rs new file mode 100644 index 000000000..ceb963750 --- /dev/null +++ b/crates/media/src/craft_source/wide_rgb_tests.rs @@ -0,0 +1,82 @@ +use std::io::Cursor; + +use craft_video::ffv1::{self, Colorspace, Encoder, EncoderConfig}; + +use super::*; +use crate::stream::{self, MediaSource as OpenedSource}; + +type TestResult = std::result::Result<(), Box>; + +fn assert_samples(actual: &[f32], expected: &[f32]) { + assert_eq!(actual.len(), expected.len()); + for (i, (&got, &want)) in actual.iter().zip(expected).enumerate() { + assert!((got - want).abs() < 1e-6, "sample {i}: expected {want}, got {got}"); + } +} + +#[test] +fn full_range_rgb_ffv1_keeps_wide_samples_across_backward_seek() -> TestResult { + const WIDTH: u32 = 5; + const HEIGHT: u32 = 3; + let mut raw = ffv1::Frame { width: WIDTH, height: HEIGHT, colorspace: Colorspace::Rgb, bit_depth: 10, chroma_shift: (0, 0), planes: vec![Vec::new(); 3] }; + let encoder = Encoder::new(&raw, EncoderConfig::default())?; + let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1"); + track.codec_private = encoder.config_record(); + track.video_size = Some((WIDTH, HEIGHT)); + track.default_duration_ns = Some(40_000_000); + let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?; + + let mut expected = Vec::new(); + for n in 0u16..3 { + let codes: Vec<[u16; 3]> = (0..WIDTH as u16 * HEIGHT as u16).map(|p| [256 + 96 * n + p, 500 + p, 910 - p]).collect(); + for (c, plane) in raw.planes.iter_mut().enumerate() { + *plane = codes.iter().map(|pixel| pixel[c]).collect(); + } + writer.write_frame(0, i64::from(n) * 40_000_000, true, &encoder.encode(&raw)?, Some(40_000_000))?; + // The existing Rec.709 fallback uses the sRGB preview curve. All fixture codes are + // above its linear segment, and adjacent codes must survive the full conversion. + expected.push( + codes + .into_iter() + .flat_map(|pixel| { + let [r, g, b] = pixel.map(|c| ((f32::from(c) / 1023.0 + 0.055) / 1.055).powf(2.4)); + [r, g, b, 1.0] + }) + .collect::>(), + ); + } + let bytes = writer.finish()?.into_inner(); + let OpenedSource::Craft(source) = stream::open_bytes("wide-rgb-ffv1.mkv", bytes.into())? else { + panic!("expected the shared FFV1 reader"); + }; + for n in [2, 0, 1] { + let pts = Tick::from_units(n as i64, 25); + let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?; + assert_eq!((frame.width, frame.height, frame.pts), (WIDTH, HEIGHT, pts)); + assert_eq!((frame.color.range, frame.color.transfer), (Range::Full, Transfer::Linear)); + let PixelData::RgbaF32(pixels) = &frame.data else { panic!("expected linear floating-point RGBA") }; + assert_samples(pixels, &expected[n]); + } + Ok(()) +} + +#[test] +fn full_range_wide_rgb_crops_rotates_and_premultiplies() -> TestResult { + let plane = |rows| Plane::new(3, 2, 4, 10, Samples::U16(rows)); + let red = plane(vec![8, 1023, 11, 999, 12, 1023, 13, 999])?; + let green = plane(vec![20, 512, 21, 999, 22, 256, 23, 999])?; + let blue = plane(vec![24, 1, 25, 999, 26, 1023, 27, 999])?; + let alpha = plane(vec![0, 512, 0, 999, 0, 0, 0, 999])?; + let mut decoded = DecodedVideoFrame::new(3, 2, ColorFamily::Rgb, Subsampling::S444, vec![red, green, blue], Some(alpha))?; + decoded.sar = Some((5, 4)); + let aperture = isobmff::CleanAperture { width: (1, 1), height: (2, 1), horiz_offset: (0, 1), vert_offset: (0, 1) }; + let color = ColorInfo { transfer: Transfer::Linear, ..ColorInfo::SRGB_FULL }; + let presentation = FramePresentation { container_color: Some(color), par: (1, 1), rotation: 1, aperture: Some(aperture) }; + let pts = Tick::from_units(4, 25); + let frame = to_craft_frame(decoded, presentation, pts)?; + assert_eq!((frame.width, frame.height, frame.par, frame.pts, frame.color), (2, 1, (4, 5), pts, color)); + let PixelData::RgbaF32(pixels) = &frame.data else { panic!("expected linear floating-point RGBA") }; + let half = 512.0 / 1023.0; + assert_samples(pixels, &[0.0, 0.0, 0.0, 0.0, half, half * half, half / 1023.0, half]); + Ok(()) +} From 61dfd6c4dc2b67ac72a2b2c7946a2685099f477a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 14:34:09 -0500 Subject: [PATCH 374/393] EPS: enable sampled images, scale step budget, and align CMYK with After Effects (#4057) * pdf,eps: enable EPS image rendering, scale step budget, and align CMYK with After Effects (#3677) * chore: repin craft-ps to 068e079c for save/restore dictionary journaling (#790) * chore: align craft-pdf/hayro revs and xtask pdf-deps pin to 068e079c --- Cargo.lock | 10 +++--- Cargo.toml | 8 ++--- crates/pdf/src/color.rs | 37 +++++++++++++++++++--- crates/pdf/src/lib.rs | 6 ++-- crates/pdf/src/tests.rs | 2 +- crates/pdf/src/tests/import.rs | 58 ++++++++++++++++++++++++++++++++-- xtask/src/pdf_deps.rs | 2 +- 7 files changed, 102 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81cc29132..cab80bb90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" [[package]] name = "craft-exr" @@ -1485,7 +1485,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" dependencies = [ "hayro-syntax", "thiserror 2.0.21", @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" dependencies = [ "craft-eps", "kurbo", @@ -3761,7 +3761,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" dependencies = [ "hayro-ccitt", ] @@ -3775,7 +3775,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" dependencies = [ "hayro-jbig2", "hayro-jpeg2000", diff --git a/Cargo.toml b/Cargo.toml index c1c46eb1d..b993313dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,13 +13,13 @@ repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] 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-pdf = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", version = "=0.1.0", default-features = false, features = ["read"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-jsonrpc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609" } craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } +craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" } @@ -231,8 +231,8 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.3.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e", version = "=0.3.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/crates/pdf/src/color.rs b/crates/pdf/src/color.rs index 8b150f907..ff141990e 100644 --- a/crates/pdf/src/color.rs +++ b/crates/pdf/src/color.rs @@ -53,10 +53,7 @@ impl Cs { match self { Cs::Gray => [g(0); 3], Cs::Rgb | Cs::Pattern => [g(0), g(1), g(2)], - Cs::Cmyk => { - let k = g(3); - [(1.0 - g(0)) * (1.0 - k), (1.0 - g(1)) * (1.0 - k), (1.0 - g(2)) * (1.0 - k)] - } + Cs::Cmyk => cmyk_to_rgb(g(0), g(1), g(2), g(3)), Cs::Lab => lab_to_rgb(c.first().copied().unwrap_or(0.0), c.get(1).copied().unwrap_or(0.0), c.get(2).copied().unwrap_or(0.0)), Cs::Indexed { base, hival, lookup } => { let i = (c.first().copied().unwrap_or(0.0).round().max(0.0) as usize).min(*hival); @@ -69,6 +66,38 @@ impl Cs { } } +/// The screen colour of each solid overprint of cyan, magenta and yellow, indexed by +/// `c * 4 + m * 2 + y`. Paper is white. +const INK_SOLIDS: [[f64; 3]; 8] = [ + [1.0, 1.0, 1.0], + [0.9422, 0.9861, 0.1296], + [0.9734, 0.1382, 0.5601], + [1.0, 0.1424, 0.0305], + [0.0754, 0.6765, 0.8047], + [0.0, 0.5965, 0.2797], + [0.2292, 0.0166, 0.5538], + [0.0251, 0.002, 0.0], +]; +/// How each ink's value (C, M, Y, K) becomes the area it covers. +const INK_COVERAGE: [f64; 4] = [1.0774, 1.0434, 1.0474, 1.1823]; + +/// DeviceCMYK (each 0 to 1) to RGB, as the Neugebauer equations model halftone printing: the +/// solid colour of every combination of the inks, weighted by the area that combination +/// covers. The solids and the coverage curves are fitted to what After Effects shows for a +/// chart of 1,296 CMYK patches. `(1 - c)(1 - k)` makes every pale pink a bright magenta. +pub(crate) fn cmyk_to_rgb(c: f64, m: f64, y: f64, k: f64) -> [f64; 3] { + let area = |i: usize, v: f64| v.clamp(0.0, 1.0).powf(INK_COVERAGE[i]); + let (ac, am, ay, ak) = (area(0, c), area(1, m), area(2, y), area(3, k)); + let mut out = [0.0; 3]; + for (i, solid) in INK_SOLIDS.iter().enumerate() { + let w = (if i & 4 != 0 { ac } else { 1.0 - ac }) * (if i & 2 != 0 { am } else { 1.0 - am }) * (if i & 1 != 0 { ay } else { 1.0 - ay }); + for (o, s) in out.iter_mut().zip(solid) { + *o += w * s; + } + } + out.map(|v| v * (1.0 - ak)) +} + fn lab_to_rgb(l: f64, a: f64, b: f64) -> [f64; 3] { let fy = (l + 16.0) / 116.0; let fx = fy + a / 500.0; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 4fd5d701c..884ffc1f8 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -253,11 +253,11 @@ fn eps_fallback_font(name: &[u8]) -> Option<&'static [u8]> { } fn parse_eps(bytes: &[u8]) -> Result { + let steps = (bytes.len() as u64).saturating_mul(4).clamp(8_000_000, 256_000_000); let limits = craft_ps::read::Limits { - // Preserve EffectCraft's established 8,000,000-unit PostScript execution budget. - steps: 8_000_000, + steps, stack_overflow_noop: true, - skip_images: true, + skip_images: false, keep_unpainted: true, zero_division_zero: true, fallback_font: Some(eps_fallback_font), diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index c1f519595..9ac6bb6b1 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -129,7 +129,7 @@ fn pdf_forms_rotation_cmyk_and_alpha() { // The form (CMYK red, clipped to its 10×10 box, scaled ×2) covers PDF (0..20, 0..20); the // half-transparent black square covers PDF (0..10, 0..10). /Rotate 90: PDF (x, y) → (y, x). let red = img.get(15, 15); - assert!(red[0] > 0.99 && red[1] < 0.01 && red[3] > 0.99, "{red:?}"); + assert!(red[0] > 0.99 && (red[1] - 0.1424).abs() < 0.01 && (red[2] - 0.0305).abs() < 0.01, "CMYK 0 1 1 0, as After Effects shows it: {red:?}"); let dark = img.get(5, 5); assert!((dark[0] - 0.5).abs() < 0.02 && dark[3] > 0.99, "{dark:?}"); assert_eq!(img.get(30, 30)[3], 0.0, "form clipped to its bounding box"); diff --git a/crates/pdf/src/tests/import.rs b/crates/pdf/src/tests/import.rs index 80be350f6..68d6487c0 100644 --- a/crates/pdf/src/tests/import.rs +++ b/crates/pdf/src/tests/import.rs @@ -49,9 +49,7 @@ fn eps_with_aliased_operators_device_queries_and_embedded_data_draws() { fn eps_filter_on_a_string_source_does_not_skip_the_program() { let square = "1 0 0 setrgbcolor 50 25 moveto 150 25 lineto 150 75 lineto 50 75 lineto closepath fill\n"; let img = "gsave 1 1 8 [1 0 0 1 0 0] (FF) /ASCIIHexDecode filter image grestore\n"; - // Images aren't drawn yet, so this parses without `eps`'s nothing-skipped check. - let doc = parse(format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n{img}{square}").as_bytes()).unwrap(); - assert_eq!(doc.skipped, ["image"]); + let doc = eps(format!("{img}{square}").as_bytes()); assert!(coverage(&render(&doc), 50, 25, 150, 75) > 4900.0, "drawing after an image read from a string"); } @@ -643,3 +641,57 @@ fn eps_unembedded_reencoded_accent_uses_bundled_glyph() { assert!(ia > 50.0 && (ia - ib).abs() < 1.0, "EPS accent {ia} vs PDF accent {ib}"); assert_eq!(ink_x(&a), ink_x(&b)); } + +#[test] +fn eps_images_are_drawn() { + // Hexadecimal data read by a procedure; the program goes on after it. + let doc = eps(b"gsave 100 50 scale 2 1 8 [2 0 0 -1 0 1] { currentfile 6 string readhexstring pop } false 3 colorimage\nFF0000 00FF00\ngrestore 0 0 1 setrgbcolor 150 0 10 10 rectfill\n"); + let img = render(&doc); + let (red, green) = (img.get(25, 75), img.get(75, 75)); + assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.99, "{red:?}"); + assert!(green[1] > 0.9 && green[0] < 0.1 && green[3] > 0.99, "{green:?}"); + assert!(img.get(155, 95)[2] > 0.99, "drawing continues after the image data"); + + // A stencil paints the current colour where its sample is 0. + let doc = eps(b"1 0 0 setrgbcolor 100 50 scale 2 1 false [2 0 0 -1 0 1] {<40>} imagemask\n"); + let img = render(&doc); + assert!(img.get(25, 75)[0] > 0.9 && img.get(25, 75)[3] > 0.9, "{:?}", img.get(25, 75)); + assert_eq!(img.get(75, 75)[3], 0.0); +} + +#[test] +fn cmyk_converts_as_the_measured_chart_does() { + // Measured from After Effects' rendering of a CMYK chart, within 3 of 255. + for (cmyk, want) in [ + ([0.0, 0.0, 0.0, 0.0], [255.0, 255.0, 255.0]), + ([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0]), + ([0.0, 0.25, 0.0, 0.0], [255.0, 205.0, 229.0]), + ([0.0, 0.1, 0.0, 0.0], [255.0, 235.0, 244.0]), + ] { + let got = crate::color::cmyk_to_rgb(cmyk[0], cmyk[1], cmyk[2], cmyk[3]).map(|v| v * 255.0); + for (g, w) in got.iter().zip(want) { + assert!((g - w).abs() < 3.0, "{cmyk:?}: {got:?} vs {want:?}"); + } + } +} + +#[test] +fn a_prolog_keeps_the_built_in_cmyk_conversion() { + // The idiom of Illustrator's EPS prolog: define the operator only when it does not exist. + let doc = eps(b"/setcmykcolor where { pop } { /setcmykcolor { pop pop pop pop 0 1 0 setrgbcolor } def } ifelse 0 1 1 0 setcmykcolor 0 0 10 10 rectfill\n"); + let c = render(&doc).get(5, 95); + assert!(c[0] > 0.9 && c[1] < 0.3, "{c:?}"); + let doc = eps(b"0.1 0.2 0.3 0.4 setcmykcolor currentcmykcolor 0.4 eq exch 0.3 eq and exch 0.2 eq and exch 0.1 eq and { 0 0 10 10 rectfill } if\n"); + assert_eq!(shape_names(&doc).len(), 1); +} + +#[test] +fn eps_restore_undoes_dictionary_changes() { + // Illustrator's prolog counts graphics states in a dictionary and relies on `restore` to + // take the count back down. + let doc = eps(b"/w 10 def /d 1 dict def d /v 1 put save /w 40 def d /v 2 put restore 0 0 w 10 rectfill d /v get 1 eq { 100 0 10 10 rectfill } if\n"); + let img = render(&doc); + assert_eq!(img.get(20, 95)[3], 0.0, "w is 10 again"); + assert!(img.get(5, 95)[3] > 0.99); + assert!(img.get(105, 95)[3] > 0.99, "d's entry is 1 again"); +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index e3aab07a7..15da0dac7 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "808730f49b9637b7909fe2ae56f9d63fdb100cae"; +const REV: &str = "068e079c7be4b100a8a6b305b31ac881e069727e"; const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("craft-ps", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")]; pub fn run(root: &Path) -> Result<(), String> { From 1e139e5914d295e8dcad66ab3dc9cd2b22515963 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 04:46:43 +0800 Subject: [PATCH 375/393] Use shared cancellation in EffectCraft media reads (#4044) * Use the shared cancellation flag in EffectCraft media reads * chore: repin craft-libs media crates to main (ba25ccd2) * deps: align the FilmCraft cancellation context * chore: use origin/main craft-libs pin (587339c7) * chore: repin craft-libs media crates to main (6a061a30) * chore: align craft-media-source (ba25ccd2) and filmcraft (3d746514) to share one cancellation context * deps: use the merged FilmCraft cancellation revision * chore: align craft-media-source (6a061a30) and filmcraft (d6cc257f) --------- Co-authored-by: Dylan M. Taylor --- Cargo.lock | 243 ++++++++++++++----------------- Cargo.toml | 30 ++-- crates/media/src/craft_source.rs | 27 +++- 3 files changed, 145 insertions(+), 155 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cab80bb90..0514a0568 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1182,11 +1182,11 @@ dependencies = [ [[package]] name = "craft-aaf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", - "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-cfb", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "thiserror 2.0.21", ] @@ -1207,10 +1207,10 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "log", "thiserror 2.0.21", ] @@ -1218,36 +1218,20 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "log", "rayon", "symphonia 0.6.1", "thiserror 2.0.21", ] -[[package]] -name = "craft-audio" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" -dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", - "log", - "thiserror 2.0.21", -] - [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" - -[[package]] -name = "craft-cfb" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" [[package]] name = "craft-cms" @@ -1266,7 +1250,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ "serde", ] @@ -1301,7 +1285,7 @@ dependencies = [ [[package]] name = "craft-dpx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "thiserror 2.0.21", ] @@ -1333,6 +1317,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-exr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8b40f1a4b0718916e7c136c1b91b38a5c7531a0e#8b40f1a4b0718916e7c136c1b91b38a5c7531a0e" +dependencies = [ + "flate2", + "serde_json", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1341,10 +1334,10 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-frame" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ "craft-color", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "rayon", "serde", ] @@ -1358,6 +1351,14 @@ dependencies = [ "image", ] +[[package]] +name = "craft-hdr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1384,7 +1385,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9#937ac93c5cf3cd4b6a81e195b078fe161eb081b9" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "thiserror 2.0.21", ] @@ -1415,7 +1416,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9 [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ "chrono", "thiserror 2.0.21", @@ -1424,30 +1425,22 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "chrono", "thiserror 2.0.21", ] -[[package]] -name = "craft-media" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "craft-media-source" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "craft-color", "craft-frame", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "serde", "thiserror 2.0.21", ] @@ -1515,6 +1508,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -1529,7 +1533,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "craft-tiff", "miniz_oxide 0.9.1", @@ -1558,7 +1562,7 @@ dependencies = [ [[package]] name = "craft-tga" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "thiserror 2.0.21", ] @@ -1566,7 +1570,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "serde", "thiserror 2.0.21", @@ -1584,7 +1588,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=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ "serde", "thiserror 2.0.21", @@ -1593,16 +1597,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-time" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "serde", "thiserror 2.0.21", @@ -1619,22 +1614,14 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "serde", "serde_json", ] -[[package]] -name = "craft-timeline" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" -dependencies = [ - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", -] - [[package]] name = "craft-ui" version = "0.1.0" @@ -1697,9 +1684,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "rav1e", "rayon", "thiserror 2.0.21", @@ -1708,9 +1695,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "rav1e", "rayon", "thiserror 2.0.21", @@ -1738,7 +1725,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1748,27 +1735,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3#587339c787682592ed46bab5a15cae52e60da2e3" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1778,7 +1745,7 @@ dependencies = [ [[package]] name = "craft-y4m" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=25c7a8959cf70cf8c3f076d05baadb0990710569#25c7a8959cf70cf8c3f076d05baadb0990710569" +source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" dependencies = [ "thiserror 2.0.21", ] @@ -2156,11 +2123,11 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", - "craft-exr", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -2322,17 +2289,17 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "craft-color", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", - "craft-exr", + "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-frame", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "craft-media-source", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=587339c787682592ed46bab5a15cae52e60da2e3)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", "craft-webp", "effectcraft-color", "effectcraft-effects", @@ -2437,7 +2404,7 @@ name = "effectcraft-psd" version = "0.24.1" dependencies = [ "craft-codepage", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c)", "miniz_oxide 0.9.1", ] @@ -2445,7 +2412,7 @@ dependencies = [ name = "effectcraft-raster" version = "0.24.1" dependencies = [ - "craft-exr", + "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "effectcraft-color", "effectcraft-geom", "rayon", @@ -3031,28 +2998,28 @@ dependencies = [ [[package]] name = "filmcraft-bitstream" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", ] [[package]] name = "filmcraft-cfb" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ - "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93)", + "craft-cfb", ] [[package]] name = "filmcraft-codecs" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "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-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "craft-y4m", "filmcraft-bitstream", "filmcraft-color", @@ -3071,7 +3038,7 @@ dependencies = [ [[package]] name = "filmcraft-color" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ "serde", ] @@ -3079,7 +3046,7 @@ dependencies = [ [[package]] name = "filmcraft-dng" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ "craft-raw", "craft-tiff", @@ -3091,7 +3058,7 @@ dependencies = [ [[package]] name = "filmcraft-frame" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -3102,7 +3069,7 @@ dependencies = [ [[package]] name = "filmcraft-geom" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ "serde", ] @@ -3110,17 +3077,18 @@ dependencies = [ [[package]] name = "filmcraft-interchange" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ "craft-aaf", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "filmcraft-cfb", "filmcraft-color", "filmcraft-geom", "filmcraft-media", "filmcraft-project", "filmcraft-time", + "roxmltree", "serde", "serde_json", "thiserror 2.0.21", @@ -3129,28 +3097,33 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", ] [[package]] name = "filmcraft-matroska" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", ] [[package]] name = "filmcraft-media" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" 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)", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8b40f1a4b0718916e7c136c1b91b38a5c7531a0e)", + "craft-hdr", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media-source", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", "craft-tga", + "craft-tiff", "filmcraft-color", "filmcraft-dng", "filmcraft-frame", @@ -3164,7 +3137,7 @@ dependencies = [ [[package]] name = "filmcraft-project" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ "filmcraft-color", "filmcraft-geom", @@ -3179,9 +3152,9 @@ dependencies = [ [[package]] name = "filmcraft-time" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" dependencies = [ - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b993313dd..94f7ce933 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,25 +97,25 @@ same-file = "1.0" tempfile = "3.27" # codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", default-features = false, features = ["isobmff", "matroska"] } -craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } -craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } -craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } -craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3" } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "587339c787682592ed46bab5a15cae52e60da2e3", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", default-features = false, features = ["isobmff", "matroska"] } +craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } +craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } +craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } +craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # 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 = "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" } +filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } # timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only) -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" } +filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } # gpu (the same wgpu eframe / egui-wgpu use) wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 782496b7e..8a1363194 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -47,6 +47,7 @@ use craft_media::matroska::{self, MkvFile}; use craft_media::mpegts; use craft_media::mxf::{self, MxfFile, SoundFormat}; use craft_media::{ByteSource, CodecId, CodecParams}; +use craft_media_source::cancel::cancelled; use craft_media_source::{ AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo, }; @@ -495,7 +496,7 @@ impl AudioStarts { // rounded or laced packets. A first discontinuous seek may still have to // index the unread suffix; normal open and sequential decode never do this. while let Some(idx) = self.pending.as_ref().map(|prefix| prefix.len) { - if filmcraft_media::cancel::cancelled() { + if cancelled() { return Err(MediaError::Cancelled); } // Do not commit a guessed duration after an I/O error; the next @@ -1810,7 +1811,7 @@ impl MediaSource for CraftMediaSource { let sample_count = self.file.sample_count(video_idx); let is_isobmff = matches!(&self.file, ContainerFile::Isobmff(_)); while !state.decoded.iter().any(|c| c.pts >= target_pts && c.draft == want_draft) { - if filmcraft_media::cancel::cancelled() { + if cancelled() { return Err(MediaError::Cancelled); } if state.next_decode_idx < sample_count { @@ -1904,7 +1905,7 @@ impl MediaSource for CraftMediaSource { channels } AudioBackend::MxfPcm { presented_start, presented_len } => { - if filmcraft_media::cancel::cancelled() { + if cancelled() { return Err(MediaError::Cancelled); } let ContainerFile::Mxf(mxf_file) = &self.file else { @@ -2077,7 +2078,7 @@ fn decode_standalone_range(native_rate: u32, channels_count: usize, state: &mut } while state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64 <= end { - if filmcraft_media::cancel::cancelled() { + if cancelled() { return Err(MediaError::Cancelled); } let Some(block) = state.decoder.next_block().map_err(|e| MediaError::Decode(e.to_string()))? else { @@ -2223,7 +2224,7 @@ fn decode_audio_range( let sample_count = file.sample_count(track_idx); while state.next_sample < sample_count { - if filmcraft_media::cancel::cancelled() { + if cancelled() { return Err(MediaError::Cancelled); } let idx = state.next_sample; @@ -4611,6 +4612,22 @@ mod tests { mux.finish().unwrap() } + #[test] + fn shared_video_read_observes_filmcraft_request_cancellation() { + use std::sync::atomic::AtomicBool; + + let source = crate::stream::open_bytes("cancelled.ts", generated_two_frame_ts().into()).unwrap(); + assert!(matches!(source, crate::stream::MediaSource::Craft(_))); + let cancel = Arc::new(AtomicBool::new(true)); + let request = || source.video_frame(effectcraft_time::Tick::ZERO, 1.0); + let interrupted = filmcraft_media::cancel::with_cancel(&cancel, request); + assert!(matches!(interrupted, Err(crate::MediaError::Cancelled))); + + let interrupted = craft_media_source::cancel::with_cancel(&cancel, request); + assert!(matches!(interrupted, Err(crate::MediaError::Cancelled))); + assert!(request().is_ok()); + } + #[test] fn regular_video_only_h264_ts_duration_keeps_the_last_picture_playable() { let bytes = generated_two_frame_ts(); From 8489edfc90e262e5e1f226304eb4b527997cc1e5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 15:52:25 -0500 Subject: [PATCH 376/393] psd: share plane reading, RLE row counts, and ZIP framing via craft-psd (#786) (#4061) * psd: share plane reading, RLE row counts, and ZIP framing via craft-psd (#786) * psd: fix parity test imports and ImageResource::new arity * psd: fix borrow conflict in parity test helper * psd: use shared zip_decompress_up_to in opt reference decoder * psd: remove shadowed imports in parity tests --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/Cargo.toml | 2 +- crates/psd/src/limits.rs | 5 -- crates/psd/src/pixels.rs | 99 ++++++++++++------------ crates/psd/src/tests.rs | 3 +- crates/psd/src/tests/opt.rs | 5 +- crates/psd/src/tests/parity.rs | 136 +++++++++++++++++++++++++++++++++ 8 files changed, 190 insertions(+), 64 deletions(-) create mode 100644 crates/psd/src/tests/parity.rs diff --git a/Cargo.lock b/Cargo.lock index 0514a0568..1b3f768a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1500,7 +1500,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c#08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" +source = "git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189#53198114310dbc2b41e18e4eaf2fd83e69964189" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 94f7ce933..1dbbffffd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,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 = "068e079c7be4b100a8a6b305b31ac881e069727e", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "53198114310dbc2b41e18e4eaf2fd83e69964189" } craft-codepage = { 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 = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index aa9e77e07..3bf2e0aff 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -12,7 +12,7 @@ workspace = true [dependencies] craft-psd = { workspace = true } craft-codepage = { workspace = true } -miniz_oxide = "0.9" [dev-dependencies] craft-psd = { workspace = true, features = ["testgen"] } +miniz_oxide = "0.9" diff --git a/crates/psd/src/limits.rs b/crates/psd/src/limits.rs index 6db366c00..5c301be7d 100644 --- a/crates/psd/src/limits.rs +++ b/crates/psd/src/limits.rs @@ -105,11 +105,6 @@ impl Budget { } } -/// Inflate a zlib stream to at most `limit` bytes. -pub(crate) fn inflate(src: &[u8], limit: usize) -> Result> { - miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, limit).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status))) -} - /// Give back what a channel buffer from `Psd::channel_bytes` / `Psd::decode_plane` was charged: /// a borrowed one (uncompressed data, or a plane of an inflated stream charged as a whole) was not. pub(crate) fn release_bytes(budget: &mut Budget, raw: Cow<'_, [u8]>) { diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs index 8ce6f2d63..aabd7c2ce 100644 --- a/crates/psd/src/pixels.rs +++ b/crates/psd/src/pixels.rs @@ -1,8 +1,9 @@ #[cfg(test)] use super::counters; -use super::limits::{Budget, DECODE_BUDGET, Error, Result, decode_pixels, finite_sample, inflate, release_bytes, too_large}; +use super::limits::{Budget, DECODE_BUDGET, Error, Result, decode_pixels, finite_sample, release_bytes, too_large}; use super::model::{ColorMode, Layer, Pixels, Rect}; use super::{Psd, Reader}; +use craft_psd::compression::PlaneStream; use std::borrow::Cow; impl Psd { @@ -32,13 +33,15 @@ impl Psd { pub(crate) fn plane_bytes<'a>(&self, comp: u16, r: &mut Reader<'a>, w: usize, h: usize, budget: &mut Budget) -> Result> { let rowb = self.row_bytes(w); let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?; - Ok(match self.open_planes(comp, r, 1, 1, (w, h), budget)? { - PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?), - PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(&counts, 0, r, rowb, h, budget)?), - PlaneStream::Zip(mut v) => { - v.resize(size, 0); - self.zip_plane(comp, &mut v, 0, w, h, budget)?; - Cow::Owned(v) + let mut stream = self.open_planes(comp, r, 1, 1, (w, h), budget)?; + Ok(match &mut stream { + PlaneStream::Raw { .. } => Cow::Borrowed(stream.next_raw_plane(size).map_err(compression_err)?), + PlaneStream::Rle { .. } => Cow::Owned(Self::unpack_plane(&mut stream, 0, rowb, h, budget)?), + PlaneStream::Zip { data } => { + // Single-channel recovery: zero-pad short ZIP streams before un-predicting. + data.resize(size, 0); + self.zip_plane(comp, data, 0, w, h, budget)?; + Cow::Owned(std::mem::take(data)) } }) } @@ -47,39 +50,31 @@ impl Psd { /// `w`×`h` samples, of which the first `want` are decoded: the RLE row sizes of every plane, /// or the inflated ZIP data, which holds all planes one after another (charged to `budget` /// before it is inflated). - fn open_planes(&self, comp: u16, r: &mut Reader, total: usize, want: usize, size: (usize, usize), budget: &mut Budget) -> Result { + fn open_planes<'a>(&self, comp: u16, r: &mut Reader<'a>, total: usize, want: usize, size: (usize, usize), budget: &mut Budget) -> Result> { let (w, h) = size; - let size = self.row_bytes(w).checked_mul(h).ok_or_else(|| too_large(w, h))?; - Ok(match comp { - 0 => PlaneStream::Raw, - 1 => { - let n = total.saturating_mul(h); - let mut counts = Vec::with_capacity(n.min(r.remaining() / 2)); - for _ in 0..n { - counts.push(if self.psb { r.u32()? as usize } else { r.u16()? as usize }); - } - PlaneStream::Rle(counts) - } - 2 | 3 => { - let rest = r.bytes(r.remaining())?; - // One stream holds every plane: what it may decode to is what they need. - let all = size.checked_mul(want).ok_or_else(|| too_large(w, h))?; - budget.charge(all as u64)?; - PlaneStream::Zip(inflate(rest, all)?) - } - c => return Err(Error::Unsupported(format!("compression {c}"))), - }) + let plane_size = self.row_bytes(w).checked_mul(h).ok_or_else(|| too_large(w, h))?; + let zip_limit = if matches!(comp, 2 | 3) { plane_size.checked_mul(want).ok_or_else(|| too_large(w, h))? } else { 0 }; + let rest = r.bytes(r.remaining())?; + PlaneStream::open( + craft_psd::Compression::from_u16(comp), + rest, + total, + h, + if self.psb { craft_psd::Version::Psb } else { craft_psd::Version::Psd }, + zip_limit, + |bytes| budget.charge(bytes as u64).map_err(|e| craft_psd::PsdError::Unsupported(e.to_string())), + ) + .map_err(compression_err) } /// The raw bytes (`row_bytes(w)` × `h`, ZIP prediction undone) of plane `c`: raw and RLE - /// planes are read from `r` in order, raw ones borrowed from the file data, ZIP ones from the - /// inflated buffer (un-predicted in place; already charged by `open_planes`), RLE ones charged - /// to `budget`. + /// planes are read from `stream` in order, raw ones borrowed from the file data, ZIP ones from + /// the inflated buffer (un-predicted in place; already charged by `open_planes`), RLE ones + /// charged to `budget`. fn decode_plane<'x, 'a: 'x>( &self, comp: u16, - planes: &'x mut PlaneStream, - r: &mut Reader<'a>, + planes: &'x mut PlaneStream<'a>, c: usize, size: (usize, usize), budget: &mut Budget, @@ -88,20 +83,20 @@ impl Psd { let rowb = self.row_bytes(w); let size = rowb.checked_mul(h).ok_or_else(|| too_large(w, h))?; Ok(match planes { - PlaneStream::Raw => Cow::Borrowed(r.bytes(size)?), - PlaneStream::Rle(counts) => Cow::Owned(Self::unpack_plane(counts, c, r, rowb, h, budget)?), - PlaneStream::Zip(v) => Cow::Borrowed(self.zip_plane(comp, v, c, w, h, budget)?), + PlaneStream::Raw { .. } => Cow::Borrowed(planes.next_raw_plane(size).map_err(compression_err)?), + PlaneStream::Rle { .. } => Cow::Owned(Self::unpack_plane(planes, c, rowb, h, budget)?), + PlaneStream::Zip { data } => Cow::Borrowed(self.zip_plane(comp, data, c, w, h, budget)?), }) } - /// Unpack the `h` RLE rows of plane `c` (row byte counts `counts`, plane after plane) into a - /// buffer charged to `budget`. - fn unpack_plane(counts: &[usize], c: usize, r: &mut Reader, rowb: usize, h: usize, budget: &mut Budget) -> Result> { + /// Unpack the `h` RLE rows of plane `c` into a buffer charged to `budget`, using padded + /// PackBits recovery. + fn unpack_plane(planes: &mut PlaneStream<'_>, c: usize, rowb: usize, h: usize, budget: &mut Budget) -> Result> { let mut out = budget.vec::(rowb.checked_mul(h).ok_or(Error::Truncated)?)?; - for row in 0..h { - let n = *counts.get(c * h + row).ok_or(Error::Truncated)?; - unpack_bits(r.bytes(n)?, rowb, &mut out)?; - } + planes.next_rle_plane_into(c, rowb, h, true, &mut out).map_err(|e| match e { + craft_psd::PsdError::UnexpectedEof { .. } | craft_psd::PsdError::Decompress(_) => Error::Truncated, + other => Error::Invalid(other.to_string()), + })?; Ok(out) } @@ -263,7 +258,7 @@ impl Psd { let mut black = if self.mode == ColorMode::Cmyk && want > 3 { Some(budget.filled(n, 0.0f32)?) } else { None }; let mut stream = self.open_planes(comp, &mut r, nch, want, (w, h), &mut budget)?; for c in 0..want { - let raw = self.decode_plane(comp, &mut stream, &mut r, c, (w, h), &mut budget)?; + let raw = self.decode_plane(comp, &mut stream, c, (w, h), &mut budget)?; self.store_merged_channel(c, &raw, &mut data, &mut black); release_bytes(&mut budget, raw); } @@ -461,16 +456,16 @@ impl Psd { } } -/// The pixel data of a run of planes, as prepared by `Psd::open_planes`. -enum PlaneStream { - Raw, - /// RLE row byte counts of every plane, plane after plane. - Rle(Vec), - /// The inflated ZIP data of all planes. - Zip(Vec), +fn compression_err(e: craft_psd::PsdError) -> Error { + match e { + craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated, + craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s), + other => Error::Invalid(other.to_string()), + } } /// PackBits decoding of one row (appends exactly `row` bytes, zero-padded). +#[cfg(test)] pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec) -> Result<()> { // The production caller already charges/reserves the complete plane in Budget. // Keep the shared recovery API bounded to this row; never relax the app budget. diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 51e875416..3d18841db 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -7,6 +7,7 @@ mod fixed_adjustments; mod fixed_writers; mod integration; mod opt; +mod parity; mod scalar_blocks; mod section_divider; mod shared_corpus; @@ -527,7 +528,7 @@ fn a_failed_inflate_reports_its_status_not_its_output() { let mut z = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1 << 20], 6); let n = z.len(); z[n - 1] ^= 0xff; - let Err(Error::Invalid(msg)) = crate::limits::inflate(&z, 1 << 21) else { panic!("the checksum fails") }; + let Err(craft_psd::PsdError::Decompress(msg)) = craft_psd::compression::zip_decompress_up_to(&z, 1 << 21) else { panic!("the checksum fails") }; assert!(msg.len() < 100, "{} bytes", msg.len()); } diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index c4fdefcfe..a14287427 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -69,7 +69,7 @@ fn ref_decode_channel(p: &Psd, offset: usize, len: usize, w: usize, h: usize) -> } 2 | 3 => { let rest = r.bytes(r.remaining())?; - let mut v = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?; + let mut v = craft_psd::compression::zip_decompress_up_to(rest, rowb * h).map_err(|e| Error::Invalid(e.to_string()))?; v.resize(rowb * h, 0); if comp == 3 { ref_unpredict(p.depth, &mut v, w, h); @@ -112,8 +112,7 @@ fn ref_composite(p: &Psd) -> Result { } 2 | 3 => { let rest = r.bytes(r.remaining())?; - let v = - miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(rest, want * rowb * h).map_err(|e| Error::Invalid(format!("zip: {:?}", e.status)))?; + let v = craft_psd::compression::zip_decompress_up_to(rest, want * rowb * h).map_err(|e| Error::Invalid(e.to_string()))?; for (c, pl) in planes.iter_mut().enumerate().take(want) { let mut plane = v.get(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?.to_vec(); if comp == 3 { diff --git a/crates/psd/src/tests/parity.rs b/crates/psd/src/tests/parity.rs new file mode 100644 index 000000000..c3b5b945a --- /dev/null +++ b/crates/psd/src/tests/parity.rs @@ -0,0 +1,136 @@ +//! Parity and recovery tests for PSD/PSB composite alpha, malformed resources, +//! RLE/ZIP plane framing, and save/reopen round-trips. + +use crate::write::*; +use crate::*; +use craft_psd::{Compression, ImageResource, Version}; + +/// Convert an encoded PSD into a PSB (or vice versa) with the specified compression +/// for both layers and the merged image, using `craft_psd::PsdFile`. +fn reencode_with(bytes: &[u8], version: Version, comp: Compression, merged_alpha: bool) -> Vec { + let mut file = craft_psd::PsdFile::from_bytes(bytes).expect("parse"); + let depth = file.header.depth; + let old_ver = file.header.version; + file.header.version = version; + file.write_as_psb = version.is_psb(); + if let Some(info) = file.layer_info.as_mut() { + info.merged_alpha = merged_alpha; + for rec in &mut info.layers { + let rects: Vec<(usize, usize)> = rec.channels.iter().map(|ch| rec.channel_rect(ch.id).size().expect("channel rect")).collect(); + for (ch, (w, h)) in rec.channels.iter_mut().zip(rects) { + if w > 0 && h > 0 { + let decoded = ch.decode(w, h, depth, old_ver).expect("decode channel"); + *ch = craft_psd::ChannelData::encode(ch.id, comp, &decoded, w, h, depth, version).expect("encode channel"); + } + } + } + } + let decoded_merged = file.image_data.decode(&craft_psd::Header { version: old_ver, ..file.header.clone() }).expect("decode merged"); + file.image_data = craft_psd::ImageData::encode(comp, &decoded_merged, &file.header).expect("encode merged"); + file.to_bytes().expect("write") +} + +#[test] +fn psd_and_psb_composite_alpha_flag_controls_alpha_channel() { + let mut doc = WDoc::new(4, 3); + doc.layers = vec![WLayer::solid("Semi", Rect::new(0, 0, 4, 3), [0.8, 0.4, 0.2, 0.5])]; + let base = write(&doc); + + for version in [Version::Psd, Version::Psb] { + let with_alpha = reencode_with(&base, version, Compression::Rle, true); + let p_alpha = Psd::parse(with_alpha).expect("parse with alpha"); + assert_eq!(p_alpha.psb, version.is_psb()); + assert!(p_alpha.merged_alpha); + let comp_alpha = p_alpha.composite().expect("composite with alpha"); + assert!((comp_alpha.data[0][3] - 0.5).abs() < 0.02, "{version:?}: {:?}", comp_alpha.data[0]); + + let without_alpha = reencode_with(&base, version, Compression::Rle, false); + let p_opaque = Psd::parse(without_alpha).expect("parse without alpha"); + assert_eq!(p_opaque.psb, version.is_psb()); + assert!(!p_opaque.merged_alpha); + let comp_opaque = p_opaque.composite().expect("composite without alpha"); + assert_eq!(comp_opaque.data[0][3], 1.0, "{version:?}: {:?}", comp_opaque.data[0]); + } +} + +#[test] +fn malformed_resources_recover_in_both_psd_and_psb() { + let mut doc = WDoc::new(6, 4); + doc.layers = vec![WLayer::solid("L", Rect::new(1, 1, 3, 2), [0.2, 0.6, 0.9, 0.75])]; + let base = write(&doc); + + for version in [Version::Psd, Version::Psb] { + let mut file = craft_psd::PsdFile::from_bytes(&reencode_with(&base, version, Compression::Rle, true)).expect("parse"); + file.resources.push(ImageResource::new(1005, vec![0; 16])); + let intact = file.to_bytes().expect("write"); + let want = Psd::parse(intact.clone()).expect("intact parse"); + + // Corrupt the first resource's declared length so it overruns the resource section. + let mut damaged = intact; + let res_at = 30 + u32::from_be_bytes(damaged[26..30].try_into().expect("cmd len")) as usize; + let name_len = 1 + usize::from(damaged[res_at + 4 + 6]); + let len_at = res_at + 4 + 6 + name_len + name_len % 2; + damaged[len_at..len_at + 4].copy_from_slice(&0x7fff_fff0u32.to_be_bytes()); + + let recovered = Psd::parse(damaged).expect("recovered parse"); + assert!(recovered.warnings.is_empty(), "{version:?}: {:?}", recovered.warnings); + assert_eq!(recovered.psb, version.is_psb()); + assert_eq!(recovered.merged_alpha, want.merged_alpha); + assert_eq!(recovered.layers.len(), want.layers.len()); + assert_eq!(recovered.composite().expect("comp").data, want.composite().expect("want comp").data); + assert_eq!(recovered.layer_pixels(0, false).expect("layer").data, want.layer_pixels(0, false).expect("want layer").data); + } +} + +#[test] +fn rle_and_zip_planes_decode_across_psd_and_psb() { + let mut doc = WDoc::new(8, 6); + doc.layers = + vec![WLayer::solid("Base", Rect::new(0, 0, 8, 6), [0.25, 0.5, 0.75, 1.0]), WLayer::solid("Overlay", Rect::new(2, 1, 4, 4), [1.0, 0.25, 0.0, 0.6])]; + let base = write(&doc); + let reference = Psd::parse(base.clone()).expect("base parse"); + let ref_comp = reference.composite().expect("ref comp").data; + let ref_l0 = reference.layer_pixels(0, false).expect("ref l0").data; + let ref_l1 = reference.layer_pixels(1, true).expect("ref l1").data; + + for version in [Version::Psd, Version::Psb] { + for comp in [Compression::Raw, Compression::Rle, Compression::Zip, Compression::ZipPrediction] { + let bytes = reencode_with(&base, version, comp, true); + let p = Psd::parse(bytes).expect("parse"); + assert_eq!(p.psb, version.is_psb()); + assert_eq!(p.composite().expect("comp").data, ref_comp, "{version:?} {comp:?} composite"); + assert_eq!(p.layer_pixels(0, false).expect("l0").data, ref_l0, "{version:?} {comp:?} l0"); + assert_eq!(p.layer_pixels(1, true).expect("l1").data, ref_l1, "{version:?} {comp:?} l1"); + } + } +} + +#[test] +fn save_and_reopen_parity_preserves_psd_and_psb_documents() { + let mut doc = WDoc::new(10, 8); + doc.layers = vec![ + WLayer::group_end(), + WLayer::solid("Child", Rect::new(1, 2, 5, 4), [0.4, 0.8, 0.2, 0.9]).with_blend(b"mul ").with_opacity(200), + WLayer::group("Folder", true, *b"pass"), + ]; + let initial = write(&doc); + + for version in [Version::Psd, Version::Psb] { + for comp in [Compression::Rle, Compression::ZipPrediction] { + let saved = reencode_with(&initial, version, comp, true); + let reopened_bytes = craft_psd::PsdFile::from_bytes(&saved).expect("parse saved").to_bytes().expect("resave"); + assert_eq!(reopened_bytes, saved, "{version:?} {comp:?} round-trip bytes"); + + let a = Psd::parse(saved).expect("parse first"); + let b = Psd::parse(reopened_bytes).expect("parse reopened"); + assert_eq!(a.psb, b.psb); + assert_eq!(a.merged_alpha, b.merged_alpha); + assert_eq!(a.layers.len(), b.layers.len()); + for (la, lb) in a.layers.iter().zip(&b.layers) { + assert_eq!((&la.name, la.blend, la.opacity, la.section), (&lb.name, lb.blend, lb.opacity, lb.section)); + } + assert_eq!(a.composite().expect("comp a").data, b.composite().expect("comp b").data); + assert_eq!(a.layer_pixels(1, true).expect("l1 a").data, b.layer_pixels(1, true).expect("l1 b").data); + } + } +} From e6c3efb3d74976d564a42a6c6424d00afa7f78d8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 16:26:56 -0500 Subject: [PATCH 377/393] chore: sync effectcraft-psd craft-psd rev in Cargo.lock (#4070) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 1b3f768a3..5a2d2bfc9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2404,7 +2404,7 @@ name = "effectcraft-psd" version = "0.24.1" dependencies = [ "craft-codepage", - "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189)", "miniz_oxide 0.9.1", ] From 171e92b0772019357fa3bea724067a32c5875ad7 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:58:34 +0700 Subject: [PATCH 378/393] media: cover legacy Motion JPEG MOV import without FFmpeg (#4064) Co-authored-by: Codex --- crates/media/src/stream.rs | 88 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index dae3c516e..d349a2c86 100644 --- a/crates/media/src/stream.rs +++ b/crates/media/src/stream.rs @@ -280,3 +280,91 @@ pub(crate) fn probe_source(path: &Path) -> Option> { pub(crate) fn probe_source(_path: &Path) -> Option> { None } + +#[cfg(all(test, any(unix, windows)))] +mod tests { + use super::*; + use craft_media::isobmff::{self, Brand, CodecConfig, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; + use filmcraft_frame::PixelData; + use image::ExtendedColorType; + use image::codecs::jpeg::JpegEncoder; + + type TestResult = std::result::Result>; + + const WIDTH: u16 = 16; + const HEIGHT: u16 = 16; + + fn generated_mjpeg_mov() -> TestResult> { + // Original synthetic fixture: encode two authored solid RGB tiles, not external media. + let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov))?; + let video = writer.add_track(TrackConfig::new(SampleEntry::jpeg(WIDTH, HEIGHT), 1_000))?; + for rgb in [[220, 32, 24], [19, 36, 224]] { + let rgb = rgb.repeat(usize::from(WIDTH) * usize::from(HEIGHT)); + let mut jpeg = Vec::new(); + JpegEncoder::new_with_quality(&mut jpeg, 90).encode(&rgb, u32::from(WIDTH), u32::from(HEIGHT), ExtendedColorType::Rgb8)?; + writer.write_sample(video, WriteSample { data: &jpeg, duration: 40, composition_offset: 0, is_sync: true })?; + } + Ok(writer.finish()?.into_inner().into()) + } + + fn legacy_mjpeg_pixels(source: &MediaSource, time: Tick) -> TestResult>> { + let frame = match source.video_frame(time, 1.0)? { + DecodedFrame::Film(frame) => Some(frame), + DecodedFrame::Craft(_) => None, + } + .ok_or("the MJPEG baseline must use FilmCraft")?; + assert_eq!((frame.width, frame.height), (u32::from(WIDTH), u32::from(HEIGHT))); + let rgba = match &frame.data { + PixelData::Rgba8(rgba) => Some(rgba), + _ => None, + } + .ok_or("legacy MJPEG decodes to RGBA8")?; + assert_eq!(rgba.len(), usize::from(WIDTH) * usize::from(HEIGHT) * 4); + Ok(rgba.clone()) + } + + #[test] + fn generated_mjpeg_mov_preserves_legacy_probe_and_seek() -> TestResult<()> { + let bytes = generated_mjpeg_mov()?; + let mov = isobmff::open(bytes.as_ref())?; + assert!(mov.is_quicktime); + assert_eq!(mov.tracks.len(), 1); + let track = &mov.tracks[0]; + assert!(matches!(track.codec(), Some(CodecConfig::Jpeg { .. }))); + assert_eq!(track.timescale, 1_000); + assert_eq!(track.samples.len(), 2); + assert_eq!((track.samples[0].pts, track.samples[1].pts), (0, 40)); + + let dir = tempfile::tempdir()?; + let name = "generated-mjpeg.mov"; + let path = dir.path().join(name); + std::fs::write(&path, bytes.as_ref())?; + let native_probe = crate::probe(&path)?; + let memory_probe = crate::probe_bytes(name, bytes.clone())?; + let direct = filmcraft_codecs::open_bytes(name, bytes.clone())?; + let legacy_probe = crate::probe::footage_from_info(name, direct.info()); + let step = Tick::from_units(1, 25); + for probe in [native_probe, memory_probe] { + assert!(probe.has_video && !probe.has_audio); + assert_eq!((probe.width, probe.height), (u32::from(WIDTH), u32::from(HEIGHT))); + assert_eq!((probe.frame_rate.num, probe.frame_rate.den), (25, 1)); + assert_eq!(probe.duration, Tick::from_units(2, 25)); + assert_eq!(probe.codec, legacy_probe.codec); + assert_eq!(probe.color_profile, legacy_probe.color_profile); + } + + let native = open_source(&path).ok_or("native source")?.0?; + let memory = open_bytes(name, bytes)?; + assert!(matches!(&native, MediaSource::Film(_))); + assert!(matches!(&memory, MediaSource::Film(_))); + let legacy = MediaSource::Film(direct); + for (time, dominant) in [(Tick::ZERO, 0), (step, 2), (Tick::ZERO, 0)] { + let expected = legacy_mjpeg_pixels(&legacy, time)?; + // Independent colour check: a repeated first frame or blank decode cannot pass parity. + assert!(expected.as_chunks::<4>().0.iter().all(|p| p[dominant] > 180 && p[2 - dominant] < 80 && p[3] == 255)); + assert_eq!(legacy_mjpeg_pixels(&native, time)?, expected); + assert_eq!(legacy_mjpeg_pixels(&memory, time)?, expected); + } + Ok(()) + } +} From 108e6362609c05e94570d20f1e456b8fb33ad2d4 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:28:40 +0700 Subject: [PATCH 379/393] test(ui): pump and wait longer while prefetch setup fills the cache (#4096) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #4095. This is a hardening change for a FreeBSD CI flake; it may not fully fix the flake. On the scheduled FreeBSD 15 x86_64 run, ui_preview_align::playback_prefetches_past_the_cached_frames_ahead failed during setup: after requesting frames 0..120 it asserted the cache equalled [0, 1, …, 119] and got only [0]. The wait was eight seconds and did not step the harness. The same test passed on the previous day's scheduled run. This PR steps the harness while waiting, gives the workers up to 60 seconds, and reports how many frames actually landed. If workers never fill the cache under load, the test can still fail. The FreeBSD aarch64 job only cross-compiles tests; it does not run them, so a green aarch64 leg is not a test pass. --- crates/ui-egui/tests/it/ui_preview_align.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/ui_preview_align.rs b/crates/ui-egui/tests/it/ui_preview_align.rs index afafa8a45..a41723d61 100644 --- a/crates/ui-egui/tests/it/ui_preview_align.rs +++ b/crates/ui-egui/tests/it/ui_preview_align.rs @@ -273,13 +273,16 @@ fn playback_prefetches_past_the_cached_frames_ahead() { for f in 0..120 { h.state().request_frame(cid, f, scale); } - for _ in 0..4000 { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while std::time::Instant::now() < deadline { if h.state().frames.cached_frames(&series).len() >= 120 && h.state().frames.inflight() == 0 { break; } + h.step(); std::thread::sleep(std::time::Duration::from_millis(2)); } - assert_eq!(h.state().frames.cached_frames(&series), (0..120).collect::>()); + let cached = h.state().frames.cached_frames(&series); + assert_eq!(cached, (0..120).collect::>(), "setup cached {} frames before playback: {cached:?}", cached.len()); // Rendering/instrumentation time must not move the playhead near the end of the // cached run. Exercise real prefetch workers while holding playback in its first second. h.state_mut().use_manual_clock(); From e7bc3ad808e3e6c0a5c80b542f606b04da7e617c Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Sun, 22 Nov 2026 19:56:45 +0100 Subject: [PATCH 380/393] Audio Levels in the Audio panel show the value at the current time, with keyframes and expressions (#3234) * Audio panel: Audio Levels show the value at the current time, keyframes and expressions included (#3227) The level fields read the property's static base value. They now evaluate Audio Levels the way the Timeline and Effect Controls do (EvalCtx at the current time: keyframes at layer time, the expression host), and they are hot-text fields whose edits run the Timeline's prop.set, so a keyframed property gets a key at the current time. The Timeline's Link Channels state applies (#2485). New automation ids audio.levelLeft and audio.levelRight carry the shown value; the fields are drawn only when the panel is wide enough for them. Fixes #3227 * Audio panel: a Ctrl+Alt scrub of Audio Levels is proportional, as in the Timeline (#3227) The Audio panel's prop.set now carries the proportional flag the Timeline sends for a Ctrl+Alt (Cmd+Opt) scrub, so the change spreads over the selected layers by selection order. * Audio panel: a scrub of expression-driven Audio Levels moves the keyframed value by the scrub (#3227) prop.set takes a scrub's change from the keyframed value under the expression. The Audio panel sent the shown (expression-evaluated) value moved by the scrub, so the expression's offset was added to every selected layer on every frame of the scrub. A scrub now sends the keyframed value moved by the shown change; a typed value is still set as it is. * Audio panel: narrow panels keep the level fields; typing one channel keeps the other's value under the expression (#3227) The level fields were left out below 110 px (the panel showed them down to 80 px before this PR); 80-110 px now get a compact layout with L / R labels. Typing into one channel of an expression-driven Audio Levels wrote the other channel's shown (expression-evaluated) value into the value under the expression; that channel now keeps its own. Adds tests for a linked and an Alt scrub and for typing into an expression-driven field. * Audio panel: Audio Levels evaluate with the session's footage source (#3227) The level fields built their expression context without the footage source, so an expression sampling footage with sampleImage disagreed with the render. They now use the session's source. Regression: nonzero sampled footage drives both channels. * Audio panel: each level scrub is its own undo step (#3234 review) --- crates/ui-egui/src/panels/misc.rs | 122 +++++- crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/ui_audio_panel_levels.rs | 405 ++++++++++++++++++ 3 files changed, 507 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/tests/it/ui_audio_panel_levels.rs diff --git a/crates/ui-egui/src/panels/misc.rs b/crates/ui-egui/src/panels/misc.rs index 0c87721db..a34e0d483 100644 --- a/crates/ui-egui/src/panels/misc.rs +++ b/crates/ui-egui/src/panels/misc.rs @@ -354,36 +354,116 @@ pub fn audio(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { p.text(pos2(sx + 2.0, y), Align2::LEFT_CENTER, format!("{db:.1}"), Tokens::ui(10.0), t.text_faint); } p.text(pos2(sx + 30.0, top - 9.0), Align2::LEFT_CENTER, "dB", Tokens::ui(10.0), t.text_dim); - // Selected layer's Audio Levels. + // Selected layer's Audio Levels: "Left" / "Right" and the editable "-12.0 dB" fields need + // about 110 px; narrower, "L" / "R" (down to 80 px, below which the section is left out). let lx = rect.min.x + 120.0; if rect.max.x - lx < 80.0 { return; } - let sel = app.session.state.selected_layers.first().copied(); - let levels = sel.and_then(|id| { - let c = app.session.active_comp()?; - let l = c.layer(id)?; - let pr = l.props.sub("audio")?.get("levels")?; - Some((l.name.clone(), pr.value.as_vec2())) - }); - match levels { - Some((name, [a, b])) => { - p.text(pos2(lx, top - 9.0), Align2::LEFT_CENTER, &name, Tokens::ui(11.0), t.text_dim); - for (i, (k, v)) in [("Left", a), ("Right", b)].into_iter().enumerate() { - let y = top + 12.0 + i as f32 * 20.0; - p.text(pos2(lx, y), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim); - p.text(pos2(lx + 44.0, y), Align2::LEFT_CENTER, format!("{v:+.1} dB"), Tokens::ui(12.0), t.hot_text); - } - } - None => { - p.text(pos2(lx, top + 12.0), Align2::LEFT_CENTER, tr("No audio layer selected"), Tokens::ui(11.0), t.text_faint); - } - } + audio_levels(app, ui, &p, pos2(lx, top), rect.max.x - lx < 110.0); if app.meter.active() || app.audio.is_some() { ui.ctx().request_repaint(); } } +/// The Audio panel's level fields at `at` (left, top of the meters): the selected layer's Audio +/// Levels at the current time, keyframes (read at layer time) and expression included, as the +/// Timeline and Effect Controls show them (#3227). An edit runs the Timeline's `prop.set`: on a +/// keyframed property it keys the current time; a scrub is one undo step; with the Timeline's +/// Link Channels on, the other channel moves by the same dB (#2485). `compact` labels the channels +/// "L" / "R" to fit a narrow panel. +fn audio_levels(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, at: egui::Pos2, compact: bool) { + let t = app.tokens; + let (lx, top) = (at.x, at.y); + let comp = app.session.active_comp_arc(); + let selected = app.session.state.selected_layers.first().copied(); + let levels = match (comp.as_deref(), app.session.active_comp_id()) { + (Some(comp), Some(cid)) => selected.and_then(|id| comp.layer(id)).and_then(|layer| { + let pr = layer.props.sub("audio")?.get("levels")?; + let project = app.session.project.clone(); + let expr = app.session.expr.clone(); + // The session's footage source, as the render and `prop.get` use it, so an expression + // that samples footage (`sampleImage`) shows what it evaluates to (#3234). + let footage = app.session.footage.clone(); + let ectx = effectcraft_engine::render::EvalCtx { + project: &project, + comp_id: cid, + comp, + time: app.session.time(), + expr: expr.as_deref(), + footage: Some(footage.as_ref()), + property_overrides: &[], + media_overrides: &[], + reads: None, + }; + // The keyframed value before the expression: what `prop.set` writes and scrubs from. + let raw = pr.value_at(layer.layer_time(ectx.time)).as_vec2(); + Some((layer.id.0, pr.uid, pr.has_expression(), layer.name.as_str(), ectx.value(layer, pr).as_vec2(), raw)) + }), + _ => None, + }; + let Some((lid, uid, driven, name, values, raw)) = levels else { + p.text(pos2(lx, top + 12.0), Align2::LEFT_CENTER, tr("No audio layer selected"), Tokens::ui(11.0), t.text_faint); + return; + }; + p.text(pos2(lx, top - 9.0), Align2::LEFT_CENTER, name, Tokens::ui(11.0), t.text_dim); + // The values themselves: red while an expression drives the property (#1306). + let vt = t.for_value(driven); + // As in the Timeline, a scrub moves every selected layer by the same change and a typed value + // sets the typed channel. + let scrub = ui.ctx().dragged_id().is_some() && ui.input(|i| i.pointer.is_decidedly_dragging()); + // Proportional Scrubbing (Ctrl+Alt / Cmd+Opt): the change spreads over the selected layers by + // selection order, as in the Timeline. + let proportional = scrub && ui.input(|i| widgets::proportional_scrub(i.modifiers)); + // Linked channels move together; Alt edits one alone (Ctrl+Alt is a proportional scrub). + let linked = app.ui.timeline.is_linked(uid, false) && !ui.input(|i| i.modifiers.alt && !widgets::proportional_scrub(i.modifiers)); + let mut actions: Vec = vec![]; + // A scrub ended this frame: the edits below still join its undo step, the next scrub starts + // another (#3234 review). + let mut released = false; + let (channels, field_x) = if compact { (["L", "R"], 14.0) } else { (["Left", "Right"], 44.0) }; + for (d, (k, v)) in channels.into_iter().zip(values).enumerate() { + let y = top + 12.0 + d as f32 * 20.0; + p.text(pos2(lx, y), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim); + let spec = widgets::HotSpec { speed: 1.0, range: (-1e9, 1e9), decimals: 1, suffix: " dB" }; + let (r, nv, done) = widgets::hot_number_at(ui, pos2(lx + field_x, y - 9.0), egui::Id::unique(("audio-level", uid, d)), v, &spec, &vt); + released |= done; + app.auto.add(if d == 0 { "audio.levelLeft" } else { "audio.levelRight" }, r, &format!("{v:.1} dB")); + if let Some(nv) = nv { + let merge = format!("audio-levels-{uid}"); + let mut params = json!({"layer": lid, "prop": uid, "merge": merge, "selected": true, "offset": scrub, "proportional": proportional, "dims": [d]}); + let value = if linked { + // The other channel follows by each layer's own change, keeping its balance. + params["follow"] = json!([usize::from(d == 0)]); + widgets::shifted(&values, d, nv) + } else { + let mut value = values.to_vec(); + if let Some(slot) = value.get_mut(d) { + *slot = nv; + } + value + }; + // The fields show the value after the expression; `prop.set` writes (and a scrub takes + // its change from) the keyframed value under it. So each channel is that value moved + // by the change the edit makes to what is shown (every selected layer then moves by + // it), except a typed channel, which is set as typed. + let value: Vec = + value.iter().zip(values.iter().zip(raw)).enumerate().map(|(e, (n, (shown, r)))| if e == d && !scrub { *n } else { r + (n - shown) }).collect(); + params["value"] = json!(value); + actions.push(params); + } + } + let ctx = ui.ctx().clone(); + for params in actions { + if let Err(e) = crate::menus::invoke(app, &ctx, "prop.set", params) { + app.ui.status = e; + } + } + if released { + app.session.history.merge_key = None; + } +} + /// The History panel: every state of the session's branching history, indented under the state it /// grew from, with the current state highlighted and future/abandoned branches dimmed. Only the /// rows in view are drawn; the current state is scrolled into view when it changes. Clicking a diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index f80611a9b..4444fcc5e 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -11,6 +11,7 @@ mod ui_accessibility_audit; mod ui_agent_audit; mod ui_alt_drag_duplicate; mod ui_angles; +mod ui_audio_panel_levels; mod ui_audio_scrub; mod ui_azerty_shortcuts; mod ui_batch_links; diff --git a/crates/ui-egui/tests/it/ui_audio_panel_levels.rs b/crates/ui-egui/tests/it/ui_audio_panel_levels.rs new file mode 100644 index 000000000..9f7121c0b --- /dev/null +++ b/crates/ui-egui/tests/it/ui_audio_panel_levels.rs @@ -0,0 +1,405 @@ +//! The Audio panel's level fields (#3227): they show the selected layer's Audio Levels at the +//! current time, keyframes and expression included, as the Timeline does; typing into one on a +//! keyframed property sets a key at the current time and leaves the static value alone, and with +//! the Timeline's Link Channels on the other channel follows (#2485). + +use effectcraft_engine::Session; +use effectcraft_engine::project::LayerId; +use effectcraft_ui_egui::EffectcraftApp; +use effectcraft_ui_egui::dock::PanelKind; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +const LEFT: &str = "audio.levelLeft"; +const RIGHT: &str = "audio.levelRight"; + +fn center(h: &Harness<'_, EffectcraftApp>, id: &str) -> Pos2 { + let e = h.state().auto.find(id).unwrap_or_else(|| panic!("the Audio panel shows no {id}")); + pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0) +} + +fn label(h: &Harness<'_, EffectcraftApp>, id: &str) -> String { + h.state().auto.find(id).unwrap_or_else(|| panic!("the Audio panel shows no {id}")).label.clone() +} + +fn click(h: &mut Harness<'_, EffectcraftApp>, id: &str) { + let p = center(h, id); + h.input_mut().events.push(Event::PointerMoved(p)); + h.step(); + h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +fn type_value(h: &mut Harness<'_, EffectcraftApp>, id: &str, v: &str) { + click(h, id); + h.input_mut().events.push(Event::Text(v.into())); + h.step(); + h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +/// Comps Sound and Main, and a precomp layer of Sound (which has Audio Levels) in Main at +/// `levels`; its layer id. +fn sound_layer(s: &mut Session, levels: [f64; 2]) -> u64 { + s.execute("comp.new", json!({"name": "Sound", "width": 64, "height": 36, "duration": 4})).unwrap(); + s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "duration": 4})).unwrap(); + let l = s.execute("layer.addItem", json!({"item": "Sound"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("prop.set", json!({"layer": l, "path": "audio/levels", "value": levels})).unwrap(); + l +} + +/// The harness with layer `l` selected and the Audio panel up. +fn harness(mut s: Session, l: u64) -> Harness<'static, EffectcraftApp> { + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s)); + h.state_mut().show_panel(PanelKind::Audio); + h.run_steps(4); + h +} + +fn levels(h: &Harness<'_, EffectcraftApp>, l: u64) -> effectcraft_engine::project::Property { + h.state().session.active_comp().unwrap().layer(LayerId(l)).unwrap().props.prop("audio/levels").unwrap().clone() +} + +/// `prop.get`'s `key` (`value`: keyframed, `evaluated`: after the expression) at the current time. +fn engine_value(h: &mut Harness<'_, EffectcraftApp>, l: u64, key: &str) -> Vec { + let r = h.state_mut().session.execute("prop.get", json!({"layer": l, "path": "audio/levels"})).unwrap(); + r[key].as_array().unwrap_or_else(|| panic!("no {key} in {r}")).iter().map(|v| v.as_f64().unwrap()).collect() +} + +fn db(v: f64) -> String { + format!("{v:.1} dB") +} + +/// Keyframed Audio Levels on a layer that starts 1 s into the comp, with the current time between +/// the keys: the panel shows the value interpolated at layer time, not the static one (nor the one +/// at comp time, past the last key); typing sets a key at the current time. +#[test] +fn keyframed_levels_show_the_value_at_the_current_time_and_typing_keys_it() { + let mut s = Session::default(); + let l = sound_layer(&mut s, [-20.0, -20.0]); + // Keys at layer time 0 s and 1 s (the layer still starts at 0 s, so comp time = layer time). + s.execute("prop.addKey", json!({"layer": l, "path": "audio/levels", "time": 0.0, "value": [-6.0, -12.0]})).unwrap(); + s.execute("prop.addKey", json!({"layer": l, "path": "audio/levels", "time": 1.0, "value": [0.0, 0.0]})).unwrap(); + // The layer moves 1 s later: its keys sit at comp 1 s and 2 s. + let cid = s.active_comp_id().unwrap(); + let one = effectcraft_engine::time::Tick::from_seconds_f64(1.0); + let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(l)).unwrap(); + layer.start_time += one; + layer.in_point += one; + layer.out_point += one; + s.execute("time.set", json!({"time": 1.5})).unwrap(); + let mut h = harness(s, l); + + let now = engine_value(&mut h, l, "value"); + assert!(now[0] > -6.0 && now[0] < 0.0 && now[1] > -12.0 && now[1] < 0.0, "between the keys: {now:?}"); + assert_eq!(label(&h, LEFT), db(now[0]), "Left at the current time"); + assert_eq!(label(&h, RIGHT), db(now[1]), "Right at the current time"); + assert_ne!(label(&h, LEFT), db(-20.0), "not the static value"); + + type_value(&mut h, LEFT, "-1"); + let pr = levels(&h, l); + assert_eq!(pr.value.components(), vec![-20.0, -20.0], "the static value stays"); + let keys: Vec<(f64, Vec)> = pr.keys.iter().map(|k| (k.time.seconds(), k.value.components())).collect(); + assert_eq!(keys.len(), 3, "a key at the current time: {keys:?}"); + assert_eq!(keys[0].1, vec![-6.0, -12.0], "{keys:?}"); + let lt = h.state().session.time().seconds() - 1.0; + assert!((keys[1].0 - lt).abs() < 1e-6, "the new key is at the current layer time {lt}: {keys:?}"); + assert_eq!(keys[1].1[0], -1.0, "the typed Left: {keys:?}"); + assert!((keys[1].1[1] - now[1]).abs() < 1e-9, "Right keeps its value at that time: {keys:?}"); + assert_eq!(keys[2].1, vec![0.0, 0.0], "{keys:?}"); + assert_eq!(label(&h, LEFT), db(-1.0), "the panel shows the new key"); +} + +/// An expression drives Audio Levels: the panel shows what it evaluates to. +#[test] +fn expression_driven_levels_show_the_evaluated_value() { + let mut s = effectcraft_host::session(); + let l = sound_layer(&mut s, [-6.0, -12.0]); + s.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "[-1, -2]"})).unwrap(); + let mut h = harness(s, l); + assert_eq!(engine_value(&mut h, l, "evaluated"), vec![-1.0, -2.0], "the expression runs"); + assert_eq!(label(&h, LEFT), db(-1.0)); + assert_eq!(label(&h, RIGHT), db(-2.0)); +} + +/// Static Audio Levels: typing sets the value and adds no key. +#[test] +fn static_levels_take_a_typed_value_without_a_key() { + let mut s = Session::default(); + let l = sound_layer(&mut s, [-6.0, -12.0]); + let mut h = harness(s, l); + assert_eq!(label(&h, LEFT), db(-6.0)); + assert_eq!(label(&h, RIGHT), db(-12.0)); + type_value(&mut h, RIGHT, "-3"); + let pr = levels(&h, l); + assert_eq!(pr.value.components(), vec![-6.0, -3.0]); + assert!(pr.keys.is_empty(), "no key on a static property"); +} + +/// With the Timeline's Link Channels on (#2485), typing into one channel moves the other by the +/// same dB, as in the Timeline. +#[test] +fn linked_levels_move_both_channels_by_the_same_db() { + let mut s = Session::default(); + let l = sound_layer(&mut s, [-6.0, -12.0]); + let mut h = harness(s, l); + let uid = levels(&h, l).uid; + h.state_mut().ui.timeline.toggle_link(uid, false); + h.run_steps(2); + assert!(h.state().ui.timeline.is_linked(uid, false)); + type_value(&mut h, LEFT, "-3"); + assert_eq!(levels(&h, l).value.components(), vec![-3.0, -9.0], "both rise 3 dB and keep their 6 dB balance"); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(levels(&h, l).value.components(), vec![-6.0, -12.0], "one Undo takes back both channels"); +} + +/// Proportional Scrubbing (After Effects 26.2): with three layers selected, a Ctrl+Alt scrub of +/// Left in the Audio panel (which shows the first selected layer) leaves that layer as it is, +/// moves the last selected by the whole change and the middle one by half, as in the Timeline. +#[test] +fn ctrl_alt_scrub_is_proportional_over_the_selected_layers() { + let mut s = Session::default(); + let first = sound_layer(&mut s, [-20.0, -20.0]); + let mut ids = vec![first]; + for _ in 0..2 { + let l = s.execute("layer.addItem", json!({"item": "Sound"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("prop.set", json!({"layer": l, "path": "audio/levels", "value": [-20.0, -20.0]})).unwrap(); + ids.push(l); + } + // Selection order: the first created (the one the panel shows), then the second, then the third. + let mut h = harness(s, first); + for l in &ids[1..] { + h.state_mut().session.execute("layer.select", json!({"layers": [l], "add": true})).unwrap(); + } + h.run_steps(2); + assert_eq!(h.state().session.state.selected_layers.first().map(|l| l.0), Some(first), "the panel shows the first selected layer"); + let from = center(&h, LEFT); + let ctrl_alt = Modifiers { alt: true, ctrl: true, command: true, ..Default::default() }; + h.input_mut().events.push(Event::PointerMoved(from)); + h.step(); + h.input_mut().events.push(Event::ModifiersChanged(ctrl_alt)); + h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: ctrl_alt }); + h.step(); + let to = from + vec2(40.0, 0.0); + for k in 1..=24 { + h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (k as f32 / 24.0))); + h.step(); + } + h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: ctrl_alt }); + h.step(); + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let moved: Vec = ids.iter().map(|l| levels(&h, *l).value.components()[0] + 20.0).collect(); + assert!(moved[2] > 1.0, "the last selected layer moved: {moved:?}"); + assert!(moved[0].abs() < 1e-9, "the first selected layer stays: {moved:?}"); + assert!((moved[1] - moved[2] / 2.0).abs() < 1e-6, "the middle one moves by half: {moved:?}"); +} + +/// Scrub Left in the Audio panel 40 px to the right with `modifiers`. +fn scrub_left(h: &mut Harness<'_, EffectcraftApp>, modifiers: Modifiers) { + let from = center(h, LEFT); + let to = from + vec2(40.0, 0.0); + h.input_mut().events.push(Event::PointerMoved(from)); + h.step(); + h.input_mut().events.push(Event::ModifiersChanged(modifiers)); + h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.step(); + for k in 1..=24 { + h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (k as f32 / 24.0))); + h.step(); + } + h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + h.step(); + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +/// An expression shifts the shown levels: a scrub moves the keyframed value under it (of the +/// shown layer and of every other selected layer) by the scrub's change, the same as without the +/// expression, not by the change plus the expression's offset; Ctrl+Alt spreads that change. +#[test] +fn a_scrub_of_expression_driven_levels_moves_every_selected_layer_by_the_scrub() { + let mut s = effectcraft_host::session(); + let first = sound_layer(&mut s, [-20.0, -20.0]); + let mut ids = vec![first]; + for _ in 0..2 { + let l = s.execute("layer.addItem", json!({"item": "Sound"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("prop.set", json!({"layer": l, "path": "audio/levels", "value": [-30.0, -30.0]})).unwrap(); + ids.push(l); + } + let mut h = harness(s, first); + for l in &ids[1..] { + h.state_mut().session.execute("layer.select", json!({"layers": [l], "add": true})).unwrap(); + } + h.run_steps(2); + let left = |h: &Harness<'_, EffectcraftApp>| -> Vec { ids.iter().map(|l| levels(h, *l).value.components()[0]).collect() }; + let undo = |h: &mut Harness<'_, EffectcraftApp>| { + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + h.run_steps(2); + }; + let before = left(&h); + // Without an expression: the change a 40 px scrub makes. + scrub_left(&mut h, Modifiers::NONE); + let change = left(&h)[0] - before[0]; + assert!(change > 1.0, "the scrub raised Left: {before:?} -> {:?}", left(&h)); + undo(&mut h); + assert_eq!(left(&h), before); + + for l in &ids { + h.state_mut().session.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "value + [10, 10]"})).unwrap(); + } + h.run_steps(2); + assert_eq!(label(&h, LEFT), db(-10.0), "the panel shows the expression's value"); + scrub_left(&mut h, Modifiers::NONE); + let after = left(&h); + for (i, (a, b)) in after.iter().zip(&before).enumerate() { + assert!((a - b - change).abs() < 1e-6, "layer {i} moved by the scrub ({change}), not by the expression's offset too: {before:?} -> {after:?}"); + } + assert_eq!(label(&h, LEFT), db(after[0] + 10.0), "the panel shows the moved value through the expression"); + undo(&mut h); + + // Proportional: the first selected stays, the middle takes half, the last all of it. + let ctrl_alt = Modifiers { alt: true, ctrl: true, command: true, ..Default::default() }; + scrub_left(&mut h, ctrl_alt); + let moved: Vec = left(&h).iter().zip(&before).map(|(a, b)| a - b).collect(); + assert!(moved[0].abs() < 1e-9, "the first selected layer stays: {moved:?}"); + assert!((moved[2] - change).abs() < 1e-6, "the last selected moves by the scrub's change ({change}): {moved:?}"); + assert!((moved[1] - change / 2.0).abs() < 1e-6, "the middle one moves by half: {moved:?}"); +} + +/// #3234 review: each scrub is its own undo step. A second scrub with nothing between it and +/// the first must not fold into it (one Undo would take both back). +#[test] +fn two_scrubs_are_two_undo_steps() { + let mut s = effectcraft_host::session(); + let l = sound_layer(&mut s, [-20.0, -20.0]); + let mut h = harness(s, l); + let left = |h: &Harness<'_, EffectcraftApp>| levels(h, l).value.components()[0]; + let start = left(&h); + scrub_left(&mut h, Modifiers::NONE); + let first = left(&h); + assert!(first > start + 1.0, "the first scrub raised Left: {start} -> {first}"); + scrub_left(&mut h, Modifiers::NONE); + let second = left(&h); + assert!(second > first + 1.0, "the second scrub raised it again: {first} -> {second}"); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert!((left(&h) - first).abs() < 1e-9, "one Undo takes back the second scrub only: {start} / {first} / {second} -> {}", left(&h)); +} + +/// With Link Channels on, a scrub of Left moves Right by the same dB; Alt scrubs Left alone. +#[test] +fn a_linked_scrub_moves_both_channels_and_alt_moves_one() { + let mut s = Session::default(); + let l = sound_layer(&mut s, [-6.0, -12.0]); + let mut h = harness(s, l); + let uid = levels(&h, l).uid; + h.state_mut().ui.timeline.toggle_link(uid, false); + h.run_steps(2); + scrub_left(&mut h, Modifiers::NONE); + let c = levels(&h, l).value.components(); + assert!(c[0] > -6.0, "the scrub raised Left: {c:?}"); + assert!((c[0] - c[1] - 6.0).abs() < 1e-9, "Right moved by the same dB: {c:?}"); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(levels(&h, l).value.components(), vec![-6.0, -12.0], "one Undo takes back the scrub"); + scrub_left(&mut h, Modifiers { alt: true, ..Default::default() }); + let c = levels(&h, l).value.components(); + assert!(c[0] > -6.0, "the Alt scrub raised Left: {c:?}"); + assert_eq!(c[1], -12.0, "Alt leaves Right alone: {c:?}"); +} + +/// Typed into an expression-driven field, the value is the keyframed value under the expression +/// (what the expression reads as `value`), as in the Timeline. +#[test] +fn typing_into_expression_driven_levels_sets_the_value_under_the_expression() { + let mut s = effectcraft_host::session(); + let l = sound_layer(&mut s, [-6.0, -12.0]); + s.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "value + [10, 10]"})).unwrap(); + let mut h = harness(s, l); + assert_eq!(label(&h, LEFT), db(4.0)); + type_value(&mut h, LEFT, "-5"); + assert_eq!(levels(&h, l).value.components(), vec![-5.0, -12.0], "Left as typed, Right's own value under the expression kept"); + assert_eq!(label(&h, LEFT), db(5.0), "shown through the expression"); + assert_eq!(label(&h, RIGHT), db(-2.0)); +} + +/// A narrow Audio panel (200-230 px) still shows the level fields, labelled "L" / "R", and keeps +/// them inside the panel. +#[test] +fn a_narrow_audio_panel_keeps_the_level_fields_inside_it() { + for width in [200.0, 215.0, 230.0, 320.0] { + let mut s = Session::default(); + let l = sound_layer(&mut s, [-20.0, -20.0]); + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + let panel = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 400.0)); + let mut h = Harness::builder().with_size(vec2(width + 100.0, 400.0)).build_ui_state( + move |ui, app: &mut EffectcraftApp| { + app.auto.begin_frame(); + effectcraft_ui_egui::panels::misc::audio(app, ui, panel); + }, + EffectcraftApp::new(s), + ); + h.run_steps(3); + for id in [LEFT, RIGHT] { + let e = h.state().auto.find(id).unwrap_or_else(|| panic!("{width} px: the Audio panel shows no {id}")).clone(); + assert!(e.rect[0] + e.rect[2] <= width, "{width} px: {id} ends at {} px, past the panel", e.rect[0] + e.rect[2]); + assert_eq!(e.label, db(-20.0), "{width} px"); + } + } +} + +/// Stands in for `sampleImage()` on footage (this harness has no expression language): both +/// channels come from the first frame's pixel through the context's footage source, red and green +/// as minus dB x 100. Fails without the source, as the real one samples transparent. +struct SampleFootage; + +impl effectcraft_engine::render::ExprHost for SampleFootage { + fn eval( + &self, + ctx: &effectcraft_engine::render::EvalCtx, + _: &effectcraft_engine::project::Layer, + _: &effectcraft_engine::project::Property, + _: &effectcraft_engine::keyframe::Value, + ) -> Result { + let src = ctx.footage.ok_or("sampleImage: no footage source")?; + let item = effectcraft_engine::project::ItemId(0); + let img = src.frame(item, &effectcraft_engine::project::Footage::default(), ctx.time).ok_or("no frame")?; + let px = img.get(0, 0); + Ok(effectcraft_engine::keyframe::Value::Vec2([-f64::from(px[0]) * 100.0, -f64::from(px[1]) * 100.0])) + } +} + +/// One frame of nonzero footage for every request. +struct Grey; + +impl effectcraft_engine::render::FootageSource for Grey { + fn frame( + &self, + _: effectcraft_engine::project::ItemId, + _: &effectcraft_engine::project::Footage, + _: effectcraft_engine::time::Tick, + ) -> Option> { + Some(std::sync::Arc::new(effectcraft_engine::raster::Image::filled(4, 4, [0.25, 0.5, 0.0, 1.0]))) + } +} + +/// Audio Levels driven by an expression that samples footage pixels (#3234): the panel evaluates +/// with the session's footage source, as the render does, so it shows the sampled +/// values (-25 dB, -50 dB) rather than a failed evaluation's keyframed ones. +#[test] +fn levels_driven_by_footage_sampling_show_the_sampled_value() { + let mut s = Session::default(); + let l = sound_layer(&mut s, [-6.0, -12.0]); + s.expr = Some(std::sync::Arc::new(SampleFootage)); + s.footage = std::sync::Arc::new(Grey); + s.execute("prop.setExpression", json!({"layer": l, "path": "audio/levels", "expression": "sampleImage([0, 0])"})).unwrap(); + let h = harness(s, l); + assert_eq!(label(&h, LEFT), db(-25.0)); + assert_eq!(label(&h, RIGHT), db(-50.0)); +} From 525dcfc0d815e6a0d36ae2e7deb7ee5afbf53491 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Sun, 22 Nov 2026 19:58:56 +0100 Subject: [PATCH 381/393] =?UTF-8?q?Browse=E2=80=A6=20buttons=20in=20a=20sc?= =?UTF-8?q?ript's=20own=20dialogs=20and=20panels=20open=20the=20file=20dia?= =?UTF-8?q?log=20instead=20of=20doing=20nothing=20(#3253)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Scripts: a ScriptUI Browse… button opens the file dialog Fixes #2778. Fixes #2894. File.openDialog, File.saveDialog, Folder.selectDialog and the instance openDlg / saveDlg / selectDlg were stubs that returned null, so a script dialog's or a dockable ScriptUI panel's Browse… button did nothing. On a script-host thread, in an app that shows them, the script now asks for the dialog (Session::script_ui.file_dialogs, each with an id), hands the session back like a modal dialog's show() does and waits for the answer: a File (an array with multiSelect), a Folder, or null when cancelled. The script's filter becomes the dialog's (its name, "All Files" for *.*); without extensions every file shows. Headless runs, the Script Console, the web and Shutdown scripts get null at once. The app shows the dialog after the pass's events: blocking on Windows (Hooks::pick_file_dialog), without blocking on macOS and Linux, one at a time; a non-blocking dialog that ends without answering counts as cancelled. scriptui.fileDialogs lists the waiting dialogs and scriptui.fileDialog answers one (refused while file access is confined, and refused to scripts). A dialog leaves the list only when its script has the answer; the script's windows refuse events meanwhile, except scriptui.close, which cancels the file dialog first. A script host that ends takes its dialogs with it. * Scripts: carry a file dialog's prompt, start location and filter to the native dialog (#2778) serve_file_dialogs collected the script's prompt, start folder and save filter but dropped them at the host boundary. FileDialog::Script now carries prompt and start, and new ScriptFolder and ScriptSave requests carry the folder dialog's prompt/start and the save dialog's prompt and whole filter (label, extensions, any file) instead of the default name's extension. Both the blocking and the non-blocking host dialogs apply title, initial directory and filters; Save also goes through the blocking hook where one is set. Hook-level regression test asserts all three requests. * Scripts: a hidden window paints so a script's file dialog is shown (#3253 review) * Scripts: formatting (#3253) --- apps/effectcraft/src/file_dialogs.rs | 154 ++++++++++++++++++- crates/automation/src/confine.rs | 2 + crates/automation/src/tests.rs | 1 + crates/engine/src/cmd/scripts.rs | 22 ++- crates/engine/src/scriptui.rs | 104 +++++++++++++ crates/script/src/prelude.js | 24 ++- crates/script/src/runtime.rs | 3 +- crates/script/src/tests/startup.rs | 15 ++ crates/script/src/tests/ui.rs | 122 +++++++++++++++ crates/script/src/ui.rs | 168 ++++++++++++++++++--- crates/ui-egui/src/app.rs | 4 +- crates/ui-egui/src/app/frame.rs | 12 ++ crates/ui-egui/src/app/gpu.rs | 10 ++ crates/ui-egui/src/hooks.rs | 17 +++ crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/lifecycle_tests.rs | 33 ++++ crates/ui-egui/src/panels/scriptui_view.rs | 109 +++++++++++++ crates/ui-egui/tests/it/ui_scriptui.rs | 162 ++++++++++++++++++++ docs/agents.md | 10 +- docs/scripting-parity.md | 2 +- 20 files changed, 945 insertions(+), 34 deletions(-) diff --git a/apps/effectcraft/src/file_dialogs.rs b/apps/effectcraft/src/file_dialogs.rs index 9f3114367..c8cf5181a 100644 --- a/apps/effectcraft/src/file_dialogs.rs +++ b/apps/effectcraft/src/file_dialogs.rs @@ -111,7 +111,9 @@ pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receive let tx = Errors { tx, ctx: ctx.clone() }; let errors = tx.clone(); app.hooks.pick_files = Some(Box::new(move |exts: &[&str]| { - blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("Media", exts).pick_files()).unwrap_or_default().into_iter().map(path_string).collect() + // No extensions (a script's File.openDialog without a filter): every file. + let dialog = || if exts.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter("Media", exts) }; + blocking(&errors, "Open", || dialog().pick_files()).unwrap_or_default().into_iter().map(path_string).collect() })); let errors = tx.clone(); app.hooks.pick_save = Some(Box::new(move |name: &str| { @@ -123,6 +125,12 @@ pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receive })); let errors = tx.clone(); app.hooks.pick_folder = Some(Box::new(move || blocking(&errors, "Choose Folder", || rfd::FileDialog::new().pick_folder()).map(path_string))); + let errors = tx.clone(); + // Scripts' file dialogs where they block (Windows; see `install_file_dialogs` in main.rs). + app.hooks.pick_file_dialog = Some(Box::new(move |dialog: FileDialog| { + let what = title(&dialog); + blocking(&errors, what, || Some(pick_blocking(dialog))).unwrap_or_default() + })); let errors = tx; app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| { blocking(&errors, "Save", || { @@ -170,9 +178,9 @@ pub fn show_asked(asked: &Receiver, frame: &eframe::Frame, ctx: &egui::Co /// The dialog's title, for errors. fn title(dialog: &FileDialog) -> &'static str { match dialog { - FileDialog::Open { .. } | FileDialog::OpenProject => "Open", - FileDialog::Folder => "Choose Folder", - FileDialog::Save { .. } => "Save", + FileDialog::Open { .. } | FileDialog::OpenProject | FileDialog::Script { .. } => "Open", + FileDialog::Folder | FileDialog::ScriptFolder { .. } => "Choose Folder", + FileDialog::Save { .. } | FileDialog::ScriptSave { .. } => "Save", } } @@ -231,6 +239,101 @@ fn path(file: Option) -> Vec { paths(file.map(|f| vec![f])) } +/// The filters of a script's file dialog (#2778): its own, under the script's name for it (else +/// "Files"), then "All Files" when the script's filter offers every file. Without extensions, no +/// filter: every file. macOS takes all the filters' extensions together as the allowed types, so a +/// dialog that also offers every file gets no filter there. +macro_rules! script_filters { + ($dialog:expr, $label:expr, $exts:expr, $any:expr) => {{ + let (d, label, exts, any): (_, &str, &[String], bool) = ($dialog, $label, $exts, $any); + if exts.is_empty() || (any && cfg!(target_os = "macos")) { + d + } else { + let d = d.add_filter(if label.is_empty() { "Files" } else { label }, exts); + if any { d.add_filter("All Files", &["*"]) } else { d } + } + }}; +} + +/// The folder a script's dialog starts in: its `start` when that is a folder, else the folder +/// the file `start` names lives in; `None` when neither exists (the system's choice). +fn start_dir(start: &str) -> Option { + if start.is_empty() { + return None; + } + let at = std::path::Path::new(start); + if at.is_dir() { Some(at.to_path_buf()) } else { at.parent().filter(|d| d.is_dir()).map(std::path::Path::to_path_buf) } +} + +/// The filters of a script's save dialog: the script's own ([`script_filters!`]), else the +/// extension of the default name. +fn save_exts(exts: &[String], default: &str) -> Vec { + if exts.is_empty() { std::path::Path::new(default).extension().map(|e| vec![e.to_string_lossy().to_string()]).unwrap_or_default() } else { exts.to_vec() } +} + +/// A script's file dialog, blocking until it closes (`Hooks::pick_file_dialog`, Windows): its +/// paths, empty when cancelled. Runs inside [`guarded`] (see [`install_pickers`]). +fn pick_blocking(dialog: FileDialog) -> Vec { + let all = + |files: Option>| -> Vec { files.unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() }; + let one = |file: Option| all(file.map(|f| vec![f])); + match dialog { + FileDialog::Script { label, exts, any, many, prompt, start } => { + let mut d = script_filters!(rfd::FileDialog::new(), &label, &exts, any); + if !prompt.is_empty() { + d = d.set_title(&prompt); + } + if let Some(dir) = start_dir(&start) { + d = d.set_directory(dir); + } + if many { all(d.pick_files()) } else { one(d.pick_file()) } + } + FileDialog::ScriptFolder { prompt, start } => { + let mut d = rfd::FileDialog::new(); + if !prompt.is_empty() { + d = d.set_title(&prompt); + } + if let Some(dir) = start_dir(&start) { + d = d.set_directory(dir); + } + one(d.pick_folder()) + } + FileDialog::ScriptSave { default, prompt, label, exts, any } => { + let at = std::path::Path::new(&default); + let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let mut d = script_filters!(rfd::FileDialog::new(), &label, &save_exts(&exts, &default), any); + if !prompt.is_empty() { + d = d.set_title(&prompt); + } + if let Some(dir) = start_dir(&default) { + d = d.set_directory(dir); + } + one(d.set_file_name(name).save_file()) + } + FileDialog::Open { exts, many } => { + let d = if exts.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter("Media", &exts) }; + if many { all(d.pick_files()) } else { one(d.pick_file()) } + } + FileDialog::OpenProject => one(rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file()), + FileDialog::Folder => one(rfd::FileDialog::new().pick_folder()), + FileDialog::Save { default, ext, project } => { + let at = std::path::Path::new(&default); + let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let mut d = if project { + rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]) + } else if ext.is_empty() { + rfd::FileDialog::new() + } else { + rfd::FileDialog::new().add_filter(&ext, &[ext.as_str()]) + }; + if let Some(dir) = at.parent().filter(|d| d.is_dir()) { + d = d.set_directory(dir); + } + one(d.set_file_name(name).save_file()) + } + } +} + /// The dialog, as the blocking hooks show it. On macOS rfd makes the panel here, before the /// future is returned, so a panel AppKit can't make panics here, inside [`guarded`]. /// @@ -242,7 +345,8 @@ fn path(file: Option) -> Vec { fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer { match dialog { FileDialog::Open { exts, many } => { - let d = parented(frame).add_filter("Media", &exts); + // No extensions (a script's File.openDialog without a filter): every file. + let d = if exts.is_empty() { parented(frame) } else { parented(frame).add_filter("Media", &exts) }; if many { let f = d.pick_files(); Box::pin(async move { paths(f.await) }) @@ -251,6 +355,46 @@ fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer { Box::pin(async move { path(f.await) }) } } + FileDialog::Script { label, exts, any, many, prompt, start } => { + let mut d = script_filters!(parented(frame), &label, &exts, any); + if !prompt.is_empty() { + d = d.set_title(&prompt); + } + if let Some(dir) = start_dir(&start) { + d = d.set_directory(dir); + } + if many { + let f = d.pick_files(); + Box::pin(async move { paths(f.await) }) + } else { + let f = d.pick_file(); + Box::pin(async move { path(f.await) }) + } + } + FileDialog::ScriptFolder { prompt, start } => { + let mut d = parented(frame); + if !prompt.is_empty() { + d = d.set_title(&prompt); + } + if let Some(dir) = start_dir(&start) { + d = d.set_directory(dir); + } + let f = d.pick_folder(); + Box::pin(async move { path(f.await) }) + } + FileDialog::ScriptSave { default, prompt, label, exts, any } => { + let at = std::path::Path::new(&default); + let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let mut d = script_filters!(parented(frame), &label, &save_exts(&exts, &default), any); + if !prompt.is_empty() { + d = d.set_title(&prompt); + } + if let Some(dir) = start_dir(&default) { + d = d.set_directory(dir); + } + let f = d.set_file_name(name).save_file(); + Box::pin(async move { path(f.await) }) + } FileDialog::OpenProject => { let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file(); Box::pin(async move { path(f.await) }) diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 70586b798..803317795 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -59,6 +59,8 @@ const REFUSED: &[&str] = &[ "scriptui.set", "scriptui.mouse", "scriptui.close", + // Hands a script the file it waits on, so its code goes on. + "scriptui.fileDialog", "file.executeFile", "effect.helpers.scan", "effect.helpers.load", diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index afee15936..a21248cb5 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -1587,6 +1587,7 @@ fn automation_roots_refuse_running_script_code() { ("scriptui.set", json!({"window": 1, "widget": 2, "value": 1})), ("scriptui.mouse", json!({"window": 1, "widget": 2, "type": "click"})), ("scriptui.close", json!({"window": 1})), + ("scriptui.fileDialog", json!({"host": 1, "paths": null})), ] { let msg = refused(&mut s, "execute_command", json!({"command": command, "params": params})); assert!(msg.contains("not available while file access is confined"), "`{command}`: {msg}"); diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 8c14e03ec..510efd12c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -430,7 +430,12 @@ fn run_startup(s: &mut Session, _: &Value) -> Result { /// (frontends call it as the app quits, after the unsaved-changes prompt). fn run_shutdown(s: &mut Session, _: &Value) -> Result { s.replace_project(effectcraft_project::Project::default(), None); - Ok(run_folder(s, SHUTDOWN_DIR, true)) + // The app is quitting: nothing would show a Shutdown script's file dialog (File.saveDialog…), + // so it gets null at once instead of waiting. + let answers = std::mem::replace(&mut s.script_ui.answers_file_dialogs, false); + let r = run_folder(s, SHUTDOWN_DIR, true); + s.script_ui.answers_file_dialogs = answers; + Ok(r) } /// Window ▸ ``: run the panel script (or bring its panel forward). @@ -599,6 +604,21 @@ pub fn specs() -> Vec { always, scriptui::close ), + crate::query!( + "scriptui.fileDialogs", + "Script File Dialogs", + "{} → [{id, host, kind: open|save|folder, prompt, exts, label, any, many, start, shown}]: the file dialogs scripts wait on (File.openDialog, File.saveDialog, Folder.selectDialog…)", + scriptui::file_dialogs + ), + cmd!( + "scriptui.fileDialog", + "Answer Script File Dialog", + [], + None, + "{id? (from scriptui.fileDialogs; default the only one), host?, paths: [path…] | null (cancelled)} → the waiting script goes on with the picked files", + always, + scriptui::file_dialog + ), ] } diff --git a/crates/engine/src/scriptui.rs b/crates/engine/src/scriptui.rs index 69e572ec2..250ca86bc 100644 --- a/crates/engine/src/scriptui.rs +++ b/crates/engine/src/scriptui.rs @@ -436,6 +436,50 @@ pub struct ScriptUiEvent { /// The ScriptUI mouse events scripts can listen for (`addEventListener`). pub const MOUSE_EVENTS: [&str; 6] = ["mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "click"]; +/// The [`ScriptUiEvent::kind`] that answers a script's file dialog ([`ScriptFileDialog`]); its +/// value is `{host, paths: [path…] | null}` and it goes to the script context `host`, not to a +/// window. +pub const FILE_DIALOG_EVENT: &str = "fileDialog"; + +/// What a script's file dialog picks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FileDialogKind { + /// A file (or several) to open: `File.openDialog`, `file.openDlg`. + #[default] + Open, + /// Where to save: `File.saveDialog`, `file.saveDlg`. + Save, + /// A folder: `Folder.selectDialog`, `folder.selectDlg`. + Folder, +} + +/// A file dialog a script asked for and waits on (#2778). The frontend shows it and answers with +/// `scriptui.fileDialog`; agents can answer it the same way. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ScriptFileDialog { + /// Unique in the process: an answer goes to this dialog only. + pub id: u32, + /// The script context waiting for the answer. + pub host: u32, + pub kind: FileDialogKind, + /// The script's prompt. + pub prompt: String, + /// The extensions the script's filter names, lower case (empty: any file). + pub exts: Vec, + /// The filter's name (`"Audio"` in `"Audio:*.mp3;*.wav"`; empty: none given). + pub label: String, + /// The filter also offers every file (`*.*`). + pub any: bool, + /// `multiSelect`: several files may be picked. + pub many: bool, + /// The file or folder the dialog starts from (`file.saveDlg`: the default name). + pub start: String, + /// A frontend has shown it (it is not shown again). + pub shown: bool, +} + /// Hands an event to the script that owns the window; returns what the handler reported /// (`{ok, output, error}`) and updates [`Session::script_ui`]. pub type ScriptUiDispatch = fn(&mut Session, &ScriptUiEvent) -> std::result::Result; @@ -491,6 +535,13 @@ pub struct ScriptUi { /// replaced, until EffectCraft quits. #[serde(skip)] pub startup_hosts: Vec, + /// The file dialogs scripts wait on, until `scriptui.fileDialog` answers them. + pub file_dialogs: Vec, + /// A frontend shows the scripts' file dialogs (the egui UI sets it). Without one, as in + /// headless runs, `File.openDialog` and the like return `null` at once, so a script never + /// waits on a dialog nobody shows. + #[serde(skip)] + pub answers_file_dialogs: bool, } impl ScriptUi { @@ -859,10 +910,63 @@ pub(crate) fn resize(s: &mut Session, p: &Value) -> Result { dispatch(s, ScriptUiEvent { window, widget: 0, kind: "resize".into(), value: json!([w, h]) }) } +/// `scriptui.fileDialogs`: the file dialogs scripts wait on. +pub(crate) fn file_dialogs(s: &mut Session, _: &Value) -> Result { + Ok(serde_json::to_value(&s.script_ui.file_dialogs).unwrap_or(Value::Null)) +} + +/// `scriptui.fileDialog`: answer a script's file dialog with the picked `paths` (`null` or +/// empty: cancelled); the script goes on with them. The dialog stays pending until its script +/// has the answer, so a refused answer leaves it to be answered again. +pub(crate) fn file_dialog(s: &mut Session, p: &Value) -> Result { + let c = "scriptui.fileDialog"; + // A script answering a dialog (its own or another script's) would only be refused when the + // answer is handed over: scripts can't drive script windows. + if s.running_for_script() { + return Err(crate::commands::bad(c, "scripts can't answer file dialogs")); + } + let num = |k: &str| p.get(k).map(|v| v.as_u64().and_then(|n| u32::try_from(n).ok())); + let pending = &s.script_ui.file_dialogs; + let asked = match (num("id"), num("host")) { + (Some(id), _) => id.and_then(|id| pending.iter().find(|d| d.id == id)), + (None, Some(host)) => host.and_then(|h| pending.iter().find(|d| d.host == h)), + (None, None) if pending.len() == 1 => pending.first(), + (None, None) => None, + }; + let asked = asked.cloned().ok_or_else(|| crate::commands::bad(c, "no such file dialog (give `id` from scriptui.fileDialogs)"))?; + let mut paths: Vec = match p.get("paths").or_else(|| p.get("path")) { + None | Some(Value::Null) => vec![], + Some(Value::String(one)) => vec![one.clone()], + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_string)).collect::>>().ok_or_else(|| crate::commands::bad(c, "`paths` must be strings"))? + } + Some(other) => return Err(crate::commands::bad(c, format!("`paths` must be a list of paths or null, not {other}"))), + }; + paths.retain(|p| !p.is_empty()); + if !asked.many { + paths.truncate(1); + } + let paths = if paths.is_empty() { Value::Null } else { json!(paths) }; + // The scripting engine takes the dialog off the list when its script has the answer. + let value = json!({"id": asked.id, "host": asked.host, "paths": paths}); + dispatch(s, ScriptUiEvent { window: 0, widget: 0, kind: FILE_DIALOG_EVENT.into(), value }) +} + /// `scriptui.close`: close a window (a dialog's `show()` returns `result`, default 2 = Cancel). pub(crate) fn close(s: &mut Session, p: &Value) -> Result { let window = window_p(s, p, "scriptui.close")?; let result = p.get("result").cloned().unwrap_or(json!(2)); + // A script waiting on its file dialog (one whose answer never came) can still be closed: + // the file dialog counts as cancelled first. If that is refused, the close is tried all the + // same (and refused with its own reason). + let host = s.script_ui.window(window).map(|w| w.host); + let asked = host.and_then(|h| s.script_ui.file_dialogs.iter().find(|d| d.host == h)).map(|d| d.id); + if let Some(id) = asked + && let Ok(cancelled) = file_dialog(s, &json!({"id": id, "paths": null})) + && s.script_ui.window(window).is_none() + { + return Ok(cancelled); + } dispatch(s, ScriptUiEvent { window, widget: 0, kind: "close".into(), value: result }) } diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index f33da7091..6f31ec37c 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -287,11 +287,23 @@ File.prototype = { copy: function (to) { return JSON.parse(__file("copy", this.__path, __str(to))); }, rename: function () { throw __err("File.rename is not supported"); }, execute: function () { return JSON.parse(__file("execute", this.__path)); }, - openDlg: function () { return null; }, - saveDlg: function () { return null; }, + openDlg: function (prompt, filter, multiSelect) { return __pickFile("open", prompt, filter, multiSelect, this.__path); }, + saveDlg: function (prompt, filter) { return __pickFile("save", prompt, filter, false, this.__path); }, }; -File.openDialog = function () { return null; }; -File.saveDialog = function () { return null; }; +// The app's file dialog (#2778): a File (an array of them with multiSelect), a Folder for +// "folder", or null when cancelled, and where no dialog can be shown (the Script Console, the +// web, headless runs). Filters are strings ("*.jsx", "Audio:*.mp3;*.wav"); a function (macOS) +// offers every file. +function __pickFile(kind, prompt, filter, multiSelect, start) { + var opt = function (v) { return v === undefined || v === null ? null : __str(v); }; + var r = JSON.parse(__fileDialog(kind, opt(prompt), typeof filter === "string" ? filter : null, !!multiSelect, opt(start))); + if (!r || !r.length) return null; + if (kind === "folder") return new Folder(r[0]); + if (kind === "open" && multiSelect) return r.map(function (p) { return new File(p); }); + return new File(r[0]); +} +File.openDialog = function (prompt, filter, multiSelect) { return __pickFile("open", prompt, filter, multiSelect); }; +File.saveDialog = function (prompt, filter) { return __pickFile("save", prompt, filter, false); }; File.decode = function (s) { return decodeURIComponent(s); }; File.encode = function (s) { return encodeURIComponent(s); }; File.fs = "EffectCraft"; @@ -354,9 +366,9 @@ Folder.prototype = { } return out; }, - selectDlg: function () { return null; }, + selectDlg: function (prompt) { return __pickFile("folder", prompt, null, false, this.__path); }, }; -Folder.selectDialog = function () { return null; }; +Folder.selectDialog = function (prompt) { return __pickFile("folder", prompt, null, false); }; Object.defineProperty(Folder, "current", { get: function () { var d = __get("app").projectDir; return d ? new Folder(d) : null; } }); Object.defineProperty(Folder, "temp", { get: function () { return null; } }); Object.defineProperty(Folder, "desktop", { get: function () { return null; } }); diff --git a/crates/script/src/runtime.rs b/crates/script/src/runtime.rs index 28e490158..ab7e511e5 100644 --- a/crates/script/src/runtime.rs +++ b/crates/script/src/runtime.rs @@ -562,7 +562,7 @@ pub(crate) fn new_context() -> Result { let limits = ctx.runtime_limits_mut(); limits.set_loop_iteration_limit(200_000_000); limits.set_recursion_limit(2000); - let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult); 11] = [ + let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult); 12] = [ (js_string!("__exec"), 2, native_exec), (js_string!("__query"), 2, native_query), (js_string!("__print"), 1, native_print), @@ -574,6 +574,7 @@ pub(crate) fn new_context() -> Result { (js_string!("__uiNewId"), 0, crate::ui::native_new_id), (js_string!("__uiModal"), 1, crate::ui::native_modal), (js_string!("__uiLayoutNative"), 1, crate::ui::native_layout), + (js_string!("__fileDialog"), 5, crate::ui::native_file_dialog), ]; for (name, len, f) in natives { ctx.register_global_callable(name, len, NativeFunction::from_fn_ptr(f)).map_err(|e| e.to_string())?; diff --git a/crates/script/src/tests/startup.rs b/crates/script/src/tests/startup.rs index 67da833c5..079bed416 100644 --- a/crates/script/src/tests/startup.rs +++ b/crates/script/src/tests/startup.rs @@ -288,3 +288,18 @@ fn empty_or_missing_folders_run_nothing() { crate::install(&mut s); assert_eq!(s.execute("file.runShutdownScripts", json!({})).unwrap(), none); } + +/// #2778: the app is quitting, so nothing would show a Shutdown script's file dialog: it gets null +/// at once instead of waiting for good. +#[test] +fn a_shutdown_script_file_dialog_does_not_wait() { + let store = Arc::new(MemoryConfig::default()); + let probe = r#"var f = File.saveDialog("Save the log", "*.txt"); app.settings.saveSetting("Startup Test", "log", f === null ? "none" : "asked");"#; + store.write(&format!("{SHUTDOWN_DIR}/Save Log.jsx"), probe).unwrap(); + let mut s = session(&store); + s.script_ui.answers_file_dialogs = true; + let r = s.execute("file.runShutdownScripts", json!({})).unwrap(); + assert_eq!(r, json!({"ran": ["Save Log.jsx"], "waiting": [], "failed": []})); + assert_eq!(setting(&mut s, "log"), "none"); + assert!(s.script_ui.file_dialogs.is_empty()); +} diff --git a/crates/script/src/tests/ui.rs b/crates/script/src/tests/ui.rs index 460376ac5..52bc0b922 100644 --- a/crates/script/src/tests/ui.rs +++ b/crates/script/src/tests/ui.rs @@ -297,3 +297,125 @@ fn sample_scripts_and_installing() { let _ = std::fs::remove_dir_all(&dir); let _: Value = json!(null); } + +const PICK_AUDIO: &str = r#" +var d = new Window("dialog", "Pick Audio"); +var song = d.add("edittext", undefined, "", { name: "song" }); +var browse = d.add("button", undefined, "Browse...", { name: "browse" }); +browse.onClick = function () { + var f = File.openDialog("Select a song", "Audio:*.MP3;*.wav,All files:*.*"); + song.text = f ? f.fsName : "(cancelled)"; +}; +var where = d.add("button", undefined, "Folder...", { name: "where" }); +where.onClick = function () { + var f = Folder.selectDialog("Output folder"); + song.text = f instanceof Folder ? "folder " + f.fsName : "(cancelled)"; +}; +d.add("button", undefined, "OK", { name: "ok" }); +var r = d.show(); +r + " " + song.text +"#; + +/// #2778: File.openDialog, Folder.selectDialog… in a dialog's Browse… handler. With a frontend +/// that shows scripts' file dialogs, the script waits for `scriptui.fileDialog`'s answer (the +/// picked files, or null when cancelled); headless runs get null at once. +#[test] +fn file_dialogs_wait_for_their_answer() { + let mut s = session(); + // Headless: nothing shows a dialog, so the script never waits on one. + let o = run_code(&mut s, r#"var f = File.openDialog("Pick"); f === null ? "none" : "picked""#, "headless.jsx"); + assert!(!o.waiting && o.error.is_none(), "{o:?}"); + assert_eq!(o.result, json!("none")); + assert!(s.script_ui.file_dialogs.is_empty()); + + s.script_ui.answers_file_dialogs = true; + // At the top of a script, with multiSelect: an array of Files. + let o = run_code(&mut s, r#"var fs = File.openDialog("Pick scripts", "*.jsx", true); fs ? fs.length + " " + fs[1].name : "none""#, "top.jsx"); + assert!(o.waiting, "{o:?}"); + let asked = s.execute("scriptui.fileDialogs", json!({})).unwrap(); + assert_eq!(asked[0]["kind"], "open", "{asked}"); + assert_eq!((asked[0]["prompt"].clone(), asked[0]["exts"].clone(), asked[0]["many"].clone()), (json!("Pick scripts"), json!(["jsx"]), json!(true))); + let r = s.execute("scriptui.fileDialog", json!({"paths": ["/a/x.jsx", "/b/y.jsx"]})).unwrap(); + assert_eq!(r["result"], "2 y.jsx", "{r}"); + assert!(s.script_ui.file_dialogs.is_empty()); + + // In a modal dialog's Browse… handler. + let o = run_code(&mut s, PICK_AUDIO, "pick.jsx"); + assert!(o.waiting, "{o:?}"); + let r = s.execute("scriptui.click", json!({"widget": "browse"})).unwrap(); + assert_eq!(r["waiting"], true, "{r}"); + let asked = s.script_ui.file_dialogs.clone(); + assert_eq!(asked.len(), 1); + assert_eq!(asked[0].exts, ["mp3", "wav"], "the filter's extensions, `*.*` adds none"); + assert_eq!((asked[0].label.as_str(), asked[0].any, asked[0].many), ("Audio", true, false)); + // An answer for another dialog (a stale one) is refused; this one still waits. + let e = s.execute("scriptui.fileDialog", json!({"id": asked[0].id + 1000, "paths": null})).unwrap_err().to_string(); + assert!(e.contains("no such file dialog"), "{e}"); + assert_eq!(s.script_ui.file_dialogs.len(), 1); + // The dialog's controls wait for the answer. + let e = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap_err().to_string(); + assert!(e.contains("waiting for its file dialog"), "{e}"); + // Cancelled: null. + s.execute("scriptui.fileDialog", json!({"paths": null})).unwrap(); + let song = |s: &Session| s.script_ui.windows[0].root.lookup(&json!("song")).map(|w| w.text.clone()).unwrap_or_default(); + assert_eq!(song(&s), "(cancelled)"); + s.execute("scriptui.click", json!({"widget": "browse"})).unwrap(); + // Only one file without multiSelect. + s.execute("scriptui.fileDialog", json!({"paths": ["/media/song.wav", "/media/other.wav"]})).unwrap(); + assert_eq!(song(&s), "/media/song.wav"); + s.execute("scriptui.click", json!({"widget": "where"})).unwrap(); + assert_eq!(s.script_ui.file_dialogs[0].kind, effectcraft_engine::scriptui::FileDialogKind::Folder); + s.execute("scriptui.fileDialog", json!({"paths": ["/media/out"]})).unwrap(); + assert_eq!(song(&s), "folder /media/out"); + let r = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap(); + assert_eq!(r["result"], "1 folder /media/out", "{r}"); + // Nothing waits any more. + assert!(s.execute("scriptui.fileDialog", json!({"paths": null})).is_err()); + + // A file dialog whose answer never comes doesn't trap its script window: closing it cancels + // the file dialog, then closes the window. + let o = run_code(&mut s, PICK_AUDIO, "pick.jsx"); + assert!(o.waiting, "{o:?}"); + s.execute("scriptui.click", json!({"widget": "browse"})).unwrap(); + assert_eq!(s.script_ui.file_dialogs.len(), 1); + let r = s.execute("scriptui.close", json!({})).unwrap(); + assert_eq!(r["result"], "2 (cancelled)", "{r}"); + assert!(s.script_ui.windows.is_empty() && s.script_ui.file_dialogs.is_empty()); +} + +/// A script can't answer or close another script's waiting file dialog (it would take the dialog +/// off the list and leave its script waiting for good): refused, and the window still closes. +#[test] +fn scripts_cannot_strand_a_waiting_file_dialog() { + let mut s = session(); + s.script_ui.answers_file_dialogs = true; + let o = run_code(&mut s, PICK_AUDIO, "pick.jsx"); + assert!(o.waiting, "{o:?}"); + s.execute("scriptui.click", json!({"widget": "browse"})).unwrap(); + let (window, id) = (s.script_ui.windows[0].id, s.script_ui.file_dialogs[0].id); + // From the Script Console. + for (command, params) in [("scriptui.close", json!({"window": window})), ("scriptui.fileDialog", json!({"id": id, "paths": ["/x.wav"]}))] { + let code = format!("try {{ __exec({command:?}, {:?}); \"ran\" }} catch (e) {{ \"refused\" }}", params.to_string()); + let o = crate::run(&mut s, &effectcraft_engine::ScriptRequest { code: &code, name: "console", console: true }); + assert_eq!(o.result, json!("refused"), "{command}: {o:?}"); + assert_eq!(s.script_ui.file_dialogs.len(), 1, "{command}: the dialog still waits"); + } + let r = s.execute("scriptui.close", json!({"window": window})).unwrap(); + assert_eq!(r["result"], "2 (cancelled)", "{r}"); + assert!(s.script_ui.windows.is_empty() && s.script_ui.file_dialogs.is_empty()); +} + +#[test] +fn file_dialog_filters_name_their_extensions() { + use crate::ui::filter_exts; + assert_eq!(filter_exts("*.jsx"), ["jsx"]); + assert_eq!(filter_exts("Audio:*.MP3;*.wav,All files:*.*"), ["mp3", "wav"]); + assert_eq!(filter_exts("Images (*.png, *.jpg)|*.png;*.jpg"), ["png", "jpg"]); + assert!(filter_exts("*.*").is_empty() && filter_exts("").is_empty() && filter_exts("*.").is_empty()); + use crate::ui::{filter_any, filter_label}; + assert_eq!(filter_label("Audio:*.mp3;*.wav,All files:*.*"), "Audio"); + assert_eq!(filter_label("Images (*.png, *.jpg)|*.png;*.jpg"), "Images"); + assert_eq!(filter_label("*.jsx"), ""); + assert!(filter_any("Audio:*.mp3,All files:*.*") && filter_any("Any|*")); + assert!(!filter_any("*.jsx") && !filter_any("")); +} diff --git a/crates/script/src/ui.rs b/crates/script/src/ui.rs index ecf4cd28b..6030ae71e 100644 --- a/crates/script/src/ui.rs +++ b/crates/script/src/ui.rs @@ -18,7 +18,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use boa_engine::{Context, JsResult, JsValue, js_string}; use effectcraft_engine::Session; -use effectcraft_engine::scriptui::{ScriptUiEvent, ScriptWindow, layout}; +use effectcraft_engine::scriptui::{FILE_DIALOG_EVENT, FileDialogKind, ScriptFileDialog, ScriptUiEvent, ScriptWindow, layout}; use serde_json::{Value as J, json}; use web_time::Instant; @@ -126,6 +126,116 @@ pub(crate) fn native_modal(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> } } +/// The extensions a ScriptUI file filter names, lower case: `"*.wav"`, `"Audio:*.mp3;*.wav,All +/// files:*.*"` (Windows), `"Audio (*.mp3, *.wav)|*.mp3;*.wav"`… Wildcard-only patterns (`*.*`) +/// name none; a filter without extensions (or a macOS filter function) offers every file. +pub(crate) fn filter_exts(filter: &str) -> Vec { + const MAX_EXTS: usize = 64; + const MAX_LEN: usize = 16; + let mut out: Vec = vec![]; + for part in filter.split("*.").skip(1) { + let ext: String = part.chars().take_while(char::is_ascii_alphanumeric).collect(); + if ext.is_empty() || ext.len() > MAX_LEN { + continue; + } + let ext = ext.to_ascii_lowercase(); + if !out.contains(&ext) { + out.push(ext); + } + if out.len() >= MAX_EXTS { + break; + } + } + out +} + +/// The name a ScriptUI file filter gives its first entry (`"Audio"` in `"Audio:*.mp3;*.wav"`, +/// `"Audio (*.mp3)|*.mp3"`); empty when it gives none. +pub(crate) fn filter_label(filter: &str) -> String { + const MAX_LEN: usize = 64; + let Some(end) = filter.find([':', '|']) else { return String::new() }; + // "Audio (*.mp3, *.wav)": the name without its list of patterns. + let label = filter.get(..end).unwrap_or_default(); + let label = label.split('(').next().unwrap_or_default().trim(); + if label.contains('*') { String::new() } else { label.chars().take(MAX_LEN).collect() } +} + +/// Whether a ScriptUI file filter also offers every file (`*.*`, or a bare `*` pattern). +pub(crate) fn filter_any(filter: &str) -> bool { + filter.contains("*.*") || filter.split([':', '|', ';', ',']).any(|p| p.trim() == "*") +} + +static NEXT_FILE_DIALOG: AtomicU32 = AtomicU32::new(1); + +/// Argument `i` as text; empty when null or missing. +fn text_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult { + match args.get(i) { + None => Ok(String::new()), + Some(v) if v.is_null() || v.is_undefined() => Ok(String::new()), + Some(v) => Ok(v.to_string(ctx)?.to_std_string_escaped()), + } +} + +/// `__fileDialog(kind, prompt, filter, multiSelect, start)` → `[path…]` JSON or `null`: +/// `File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the instance `openDlg` / +/// `saveDlg` / `selectDlg` (#2778). On a script-host thread, with a frontend that shows the +/// scripts' file dialogs ([`effectcraft_engine::scriptui::ScriptUi::answers_file_dialogs`]), it +/// asks for the dialog ([`ScriptFileDialog`]), hands the session back to the caller like a modal +/// dialog does and waits for `scriptui.fileDialog`'s answer. Elsewhere (the Script Console, the +/// web, headless runs) there is no dialog to wait on: `null`, as a cancelled dialog. +pub(crate) fn native_file_dialog(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { + let kind = match arg_string(args, 0, ctx)?.as_str() { + "save" => FileDialogKind::Save, + "folder" => FileDialogKind::Folder, + _ => FileDialogKind::Open, + }; + let prompt = text_arg(args, 1, ctx)?; + let filter = text_arg(args, 2, ctx)?; + let start = text_arg(args, 4, ctx)?; + let many = kind == FileDialogKind::Open && args.get(3).is_some_and(JsValue::to_boolean); + let id = NEXT_FILE_DIALOG.fetch_add(1, Ordering::Relaxed); + let asked = with_active(|a| { + if a.link.is_none() || !a.session.script_ui.answers_file_dialogs { + return Ok(false); + } + // One dialog at a time per script. + a.session.script_ui.file_dialogs.retain(|d| d.host != a.host); + let folder = kind == FileDialogKind::Folder; + let (exts, label, any) = if folder { (vec![], String::new(), false) } else { (filter_exts(&filter), filter_label(&filter), filter_any(&filter)) }; + a.session.script_ui.file_dialogs.push(ScriptFileDialog { id, host: a.host, kind, prompt, exts, label, any, many, start, shown: false }); + Ok(true) + }) + .unwrap_or(false); + if !asked { + return Ok(JsValue::null()); + } + let forget = || { + let _ = with_active(|a| { + a.session.script_ui.file_dialogs.retain(|d| d.id != id); + Ok(()) + }); + }; + loop { + let windows = snapshot(ctx); + let out = crate::Outcome { output: settle(), waiting: true, ..Default::default() }; + // The caller went away: as cancelled. + let Some(ev) = yield_wait(out, windows, false) else { return Ok(JsValue::null()) }; + if ev.kind == FILE_DIALOG_EVENT { + // An answer to an earlier dialog of this script is not this one's. + if ev.value.get("id").and_then(J::as_u64) == Some(u64::from(id)) { + forget(); + let paths = ev.value.get("paths").cloned().unwrap_or(J::Null); + return Ok(js_str(&paths.to_string())); + } + } else if ev.kind == "close" { + // `dispatch_ui` refuses the script's window events while it waits; a close that got + // here all the same ends the wait as cancelled, so the window can be closed. + forget(); + return Ok(JsValue::null()); + } + } +} + // ---------------------------------------------------------------- script-host threads pub(crate) enum ToHost { @@ -320,8 +430,7 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome { } publish(session, host, &name, windows); if done { - session.script_ui.windows.retain(|w| w.host != host); - session.script_ui.revision += 1; + forget_host(session, host); } else if let Ok(mut h) = hosts().lock() { h.insert(host, HostEnd { next_due, epoch: session.script_ui.project_epoch, ..end }); } @@ -331,6 +440,13 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome { } } +/// A script host has ended: its windows close and nothing waits on its file dialogs. +fn forget_host(session: &mut Session, host: u32) { + session.script_ui.windows.retain(|w| w.host != host); + session.script_ui.file_dialogs.retain(|d| d.host != host); + session.script_ui.revision += 1; +} + /// Run a script file on a new script-host thread (see the module docs). Not on the web, where /// scripts run inline. #[cfg(not(target_arch = "wasm32"))] @@ -434,22 +550,33 @@ pub fn dispatch_ui(session: &mut Session, ev: &ScriptUiEvent) -> Result bool { - !session.script_ui.windows.iter().any(|w| w.host == host) && !session.script_ui.startup_hosts.contains(&host) + // A script waiting on its file dialog goes on when it is answered. + !session.script_ui.windows.iter().any(|w| w.host == host) + && !session.script_ui.startup_hosts.contains(&host) + && !session.script_ui.file_dialogs.iter().any(|d| d.host == host) } /// Run the due tasks of the script-host threads; hosts without windows whose project was closed @@ -501,13 +631,16 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr let Some(end) = h.get(&host) else { continue }; if end.epoch != epoch && ends_with_project(session, host) { // Dropping its end lets the host thread finish. - stale.extend(h.remove(&host)); + stale.extend(h.remove(&host).map(|end| (host, end))); } else if end.next_due.is_some_and(|d| d <= now) { due.push(host); } } } - drop(stale); + for end in stale { + forget_host(session, end.0); + drop(end.1); + } for host in due { if session.script_ui.render_host.is_some() { break; @@ -515,8 +648,7 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr let Some(end) = hosts().lock().ok().and_then(|mut h| h.remove(&host)) else { continue }; if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::Tick(std::mem::take(session), now)) { *session = msg.into_session(); - session.script_ui.windows.retain(|w| w.host != host); - session.script_ui.revision += 1; + forget_host(session, host); continue; } report.add(receive(session, host, end)); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f1373607d..ae0fbf38d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -31,7 +31,9 @@ impl EffectcraftApp { /// Loads and applies the workspaces saved in the session's config directory (a failed load is reported in /// `ui.status`), initializes the default UI, playback and render state, and registers the frontend's commands as /// shortcutable `UiCommand`s on the session. - pub fn new(session: Session) -> Self { + pub fn new(mut session: Session) -> Self { + // Scripts' file dialogs (File.openDialog…) show here ([`panels::scriptui_view::serve_file_dialogs`]). + session.script_ui.answers_file_dialogs = true; let mut ui = UiState::default(); let workspace_store = workspace_state::WorkspaceStore::load(session.config.as_deref(), &mut ui); EffectcraftApp { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 8eef34d4b..59c12267c 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -326,12 +326,21 @@ impl EffectcraftApp { || !self.synthetic.is_empty() || !self.input_waiters.is_empty() || self.pending_screenshots.iter().any(|s| s.slot.is_none()) + || self.script_file_dialog_waits() || (self.playback.playing && child_viewports); if paint { self.request_hidden_paint(ctx); } } + /// A script waits for a file dialog nobody has shown yet: dialogs are served in a UI pass + /// (`serve_file_dialogs`), so a minimized window must paint for it (#3253 review). Not while + /// a non-blocking dialog is up: the next one waits for it. + fn script_file_dialog_waits(&self) -> bool { + let one_at_a_time = self.hooks.file_dialog_async.is_some() && self.file_dialogs.any(); + !one_at_a_time && self.session.script_ui.file_dialogs.iter().any(|d| !d.shown) + } + /// Ask the host for a UI pass even when the window is minimized or occluded. /// /// Native eframe honours `RequestPaintWhileHidden`; the shared web backend does not carry it @@ -529,6 +538,9 @@ impl EffectcraftApp { updates_ui::show(self, &ctx); panels::scriptui_view::sync_panels(self); panels::scriptui_view::show_windows(self, &ctx); + // After the windows' events and the menus' commands: a script that asked for a file + // dialog in this pass gets it now. + panels::scriptui_view::serve_file_dialogs(self); panels::learn::coach(self, &ctx); let lift = panels::media_panels::import_card(self, ui, full); self.draw_toast(ui, full, lift); diff --git a/crates/ui-egui/src/app/gpu.rs b/crates/ui-egui/src/app/gpu.rs index 92ea7665c..96a24c5e0 100644 --- a/crates/ui-egui/src/app/gpu.rs +++ b/crates/ui-egui/src/app/gpu.rs @@ -144,6 +144,16 @@ impl EffectcraftApp { pub(crate) fn run_dialog_answers(&mut self) { while let Ok(answer) = self.dialog_answers.1.try_recv() { self.file_dialogs.answered(); + // A script's file dialog: answered even when cancelled (the script waits on it). + if answer.command == panels::scriptui_view::FILE_DIALOG_COMMAND { + // A dialog that couldn't open says why in the status line and counts as cancelled. + let paths = answer.paths.unwrap_or_else(|e| { + self.ui.status = e; + Vec::new() + }); + panels::scriptui_view::answer_file_dialog(self, &answer.params, paths); + continue; + } menus::dialog_answered(self, answer); } } diff --git a/crates/ui-egui/src/hooks.rs b/crates/ui-egui/src/hooks.rs index 7a87eeb6c..177084a46 100644 --- a/crates/ui-egui/src/hooks.rs +++ b/crates/ui-egui/src/hooks.rs @@ -13,6 +13,19 @@ pub enum FileDialog { OpenProject, /// A folder. Folder, + /// A file (several when `many`) a script asks for (`File.openDialog`, #2778): the script's + /// filter named `label` with these extensions (none: every file), and `any`: every file + /// besides (the filter's `*.*`). + /// `prompt` is the dialog's title (empty: the system's) and `start` the file or folder it + /// opens at (empty: the system's). + Script { label: String, exts: Vec, any: bool, many: bool, prompt: String, start: String }, + /// A folder a script asks for (`Folder.selectDialog`, `folder.selectDlg`) with its `prompt` + /// (the dialog's title) and the folder it starts in (`start`); both empty when not given. + ScriptFolder { prompt: String, start: String }, + /// Where a script wants to save (`File.saveDialog`, `file.saveDlg`): `default` (a file name + /// or path) with the script's filter (`label`, `exts`, `any` as in [`FileDialog::Script`]; no + /// extensions: the default's extension) and the script's `prompt` as the title. + ScriptSave { default: String, prompt: String, label: String, exts: Vec, any: bool }, /// Where to save `default` (a file name or path) with extension `ext` (empty: no filter); /// `project`: the project save dialog, given the file name. Save { default: String, ext: String, project: bool }, @@ -62,6 +75,10 @@ pub struct Hooks { /// a drag over the window (#511), and on Linux a blocking desktop-portal dialog never pumps /// events, so the compositor marks the window as not responding (#1275). pub file_dialog_async: Option>, + /// Shows a [`FileDialog`] and blocks until it closes: the picked paths (empty: cancelled). + /// Scripts' file dialogs use it where [`Hooks::file_dialog_async`] isn't set (Windows); without + /// it they fall back to the pickers above. + pub pick_file_dialog: Option Vec>>, /// Tells the user the graphics device was lost and the window is closing, once. `saved` is /// the auto-save of unsaved changes (`None`: nothing was unsaved), its path or why it failed. pub device_lost: Option>)>>, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5d49d397b..1d39857df 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -538,6 +538,11 @@ impl FileDialogsUp { self.count = self.count.saturating_add(1); } + /// Whether one is up. + pub(crate) fn any(&self) -> bool { + self.count > 0 + } + pub(crate) fn answered(&mut self) { self.count = self.count.saturating_sub(1); } diff --git a/crates/ui-egui/src/lifecycle_tests.rs b/crates/ui-egui/src/lifecycle_tests.rs index 5b97b1961..fe9041987 100644 --- a/crates/ui-egui/src/lifecycle_tests.rs +++ b/crates/ui-egui/src/lifecycle_tests.rs @@ -356,6 +356,39 @@ fn image(width: usize, height: usize) -> Arc { Arc::new(egui::ColorImage::new([width, height], vec![egui::Color32::from_rgb(10, 20, 30); width.checked_mul(height).unwrap()])) } +/// #3253 review: a script waits on a file dialog while the window is hidden. File dialogs are +/// served in a UI pass, so the app asks for one until the dialog is shown; a hidden window with +/// nothing waiting stays quiet. +#[test] +fn a_script_file_dialog_asks_for_a_pass_while_the_window_is_hidden() { + use effectcraft_engine::scriptui::{FileDialogKind, ScriptFileDialog}; + let ctx = egui::Context::default(); + let frame = eframe::Frame::_new_kittest(); + let mut app = app_with_comp(); + ready(&mut app, &ctx, &frame); + let asks = + |out: &egui::LogicOutput| out.viewport_commands.values().flatten().filter(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)).count(); + let size = egui::vec2(800.0, 480.0); + assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 0, "nothing waits: a hidden window stays quiet"); + app.session.script_ui.file_dialogs.push(ScriptFileDialog { + id: 1, + host: 1, + kind: FileDialogKind::Open, + prompt: String::new(), + exts: vec![], + label: String::new(), + any: true, + many: false, + start: String::new(), + shown: false, + }); + assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 1, "a script waits for its dialog: the hidden window paints"); + if let Some(d) = app.session.script_ui.file_dialogs.first_mut() { + d.shown = true; + } + assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 0, "the dialog is shown: no more passes asked for"); +} + #[test] fn a_screenshot_is_issued_only_after_settled_passes_and_writes_from_the_tick() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/panels/scriptui_view.rs b/crates/ui-egui/src/panels/scriptui_view.rs index 2e34757bf..4b365afdf 100644 --- a/crates/ui-egui/src/panels/scriptui_view.rs +++ b/crates/ui-egui/src/panels/scriptui_view.rs @@ -540,6 +540,115 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec) { } } +/// The command that answers a script's file dialog. +pub(crate) const FILE_DIALOG_COMMAND: &str = "scriptui.fileDialog"; + +/// The answer to a script's file dialog shown without blocking. Dropped unanswered (a dialog that +/// ended without its completion handler, a dialog thread that didn't start) it answers +/// "cancelled", so the script never waits for an answer that can't come. +struct PendingAnswer { + tx: std::sync::mpsc::Sender, + answer: Option, +} + +impl PendingAnswer { + fn send(mut self, paths: Result, String>) { + if let Some(a) = self.answer.take() { + let _ = self.tx.send(crate::DialogAnswer { paths, ..a }); + } + } +} + +impl Drop for PendingAnswer { + fn drop(&mut self) { + if let Some(a) = self.answer.take() { + let _ = self.tx.send(a); + } + } +} + +/// Show the file dialog a script waits on (`File.openDialog`, `File.saveDialog`, +/// `Folder.selectDialog`… from a ScriptUI Browse… button, #2778) and hand the answer back +/// through `scriptui.fileDialog`. Where blocking the frame is unsafe the dialog shows without +/// blocking ([`crate::Hooks::file_dialog_async`]), one at a time, and answers when it closes; a +/// host without a dialog answers "cancelled" at once, so the script never waits for nothing. +pub fn serve_file_dialogs(app: &mut EffectcraftApp) { + use effectcraft_engine::scriptui::FileDialogKind; + let spawn = app.hooks.file_dialog_async.is_some(); + // A non-blocking dialog already up: the next one shows after it. + if spawn && app.file_dialogs.any() { + return; + } + let Some(asked) = app.session.script_ui.file_dialogs.iter_mut().find(|d| !d.shown) else { return }; + asked.shown = true; + let asked = asked.clone(); + let params = json!({"id": asked.id}); + // The save dialog's default: the script's file, else a name with the filter's extension. + let default = match (asked.start.is_empty(), asked.exts.first()) { + (false, _) => asked.start.clone(), + (true, Some(ext)) => format!("Untitled.{ext}"), + (true, None) => "Untitled".to_string(), + }; + let request = match asked.kind { + FileDialogKind::Open => crate::FileDialog::Script { + label: asked.label.clone(), + exts: asked.exts.clone(), + any: asked.any, + many: asked.many, + prompt: asked.prompt.clone(), + start: asked.start.clone(), + }, + FileDialogKind::Save => crate::FileDialog::ScriptSave { + default: default.clone(), + prompt: asked.prompt.clone(), + label: asked.label.clone(), + exts: asked.exts.clone(), + any: asked.any, + }, + FileDialogKind::Folder => crate::FileDialog::ScriptFolder { prompt: asked.prompt.clone(), start: asked.start.clone() }, + }; + if let Some(spawn) = app.hooks.file_dialog_async.as_ref() { + let answer = crate::DialogAnswer { command: FILE_DIALOG_COMMAND.to_string(), key: "paths", params, paths: Ok(Vec::new()) }; + let pending = PendingAnswer { tx: app.dialog_answers.0.clone(), answer: Some(answer) }; + app.file_dialogs.opened(); + spawn(request, Box::new(move |paths| pending.send(paths))); + return; + } + let paths: Vec = match (&app.hooks.pick_file_dialog, asked.kind) { + (Some(pick), _) => pick(request), + (_, FileDialogKind::Open) => { + let exts: Vec<&str> = asked.exts.iter().map(String::as_str).collect(); + app.hooks.pick_files.as_ref().map(|pick| pick(&exts)).unwrap_or_default() + } + (_, FileDialogKind::Save) => app.hooks.save_dialog(&default).flatten().into_iter().collect(), + (_, FileDialogKind::Folder) => app.hooks.pick_folder.as_ref().and_then(|pick| pick()).into_iter().collect(), + }; + let paths = if asked.many { paths } else { paths.into_iter().take(1).collect() }; + answer_file_dialog(app, ¶ms, paths); +} + +/// Answer a script's file dialog (`params`: `{id}`) with the picked `paths` (empty: cancelled); +/// what the script then reports shows as [`perform`] shows a handler's. An answer that comes +/// after the dialog was dropped (its script window closed meanwhile) is let go. +pub(crate) fn answer_file_dialog(app: &mut EffectcraftApp, params: &Value, paths: Vec) { + let id = params.get("id").and_then(Value::as_u64); + if !app.session.script_ui.file_dialogs.iter().any(|d| Some(u64::from(d.id)) == id) { + return; + } + let paths = if paths.is_empty() { Value::Null } else { json!(paths) }; + match app.session.execute(FILE_DIALOG_COMMAND, json!({"id": id, "paths": paths})) { + Ok(r) => { + if let Some(e) = r.get("error").filter(|e| !e.is_null()) { + let msg = e["message"].as_str().unwrap_or("script error").to_string(); + app.toast = Some((msg, app.now())); + } else if let Some(o) = r["output"].as_str().filter(|o| !o.is_empty()) { + app.ui.status = o.lines().last().unwrap_or_default().to_string(); + } + } + Err(e) => app.ui.status = e.to_string(), + } +} + /// The floating script windows (dialogs, palettes, windows), drawn over the app. pub fn show_windows(app: &mut EffectcraftApp, ctx: &egui::Context) { let windows: Vec = app.session.script_ui.windows.iter().filter(|w| w.kind != WindowKind::Panel).cloned().collect(); diff --git a/crates/ui-egui/tests/it/ui_scriptui.rs b/crates/ui-egui/tests/it/ui_scriptui.rs index a905ebc5a..6c46e71cf 100644 --- a/crates/ui-egui/tests/it/ui_scriptui.rs +++ b/crates/ui-egui/tests/it/ui_scriptui.rs @@ -398,3 +398,165 @@ fn scheduled_import_reveals_its_composition_without_manual_clicks() { assert!(!h.state().ui.start_screen, "Home must not hide a composition opened by the scheduled import"); h.state_mut().session.execute("scriptui.close", json!({"window":"Automatic import"})).unwrap(); } + +/// #2778: a script dialog's Browse… button calls `File.openDialog` / `Folder.selectDialog`; the +/// app shows its file dialog (with the script's filter) and the script goes on with the picked +/// file, or with null when cancelled. Blocking dialogs (Windows) answer in the same pass; the +/// non-blocking ones (macOS, Linux) when they close. +#[test] +fn script_browse_buttons_open_the_file_dialog() { + use std::sync::{Arc, Mutex}; + let mut h = harness(); + let picked = std::env::temp_dir().join("Song.wav").to_string_lossy().to_string(); + let asked: Arc>>> = Arc::default(); + let (log, file) = (asked.clone(), picked.clone()); + h.state_mut().hooks.pick_files = Some(Box::new(move |exts: &[&str]| { + log.lock().unwrap().push(exts.iter().map(|e| e.to_string()).collect()); + vec![file.clone()] + })); + // Cancelled. + h.state_mut().hooks.pick_folder = Some(Box::new(|| None::)); + let code = r#" + var d = new Window("dialog", "Pick Audio"); + var row = d.add("group"); + var song = row.add("edittext", undefined, "", { name: "song" }); + song.characters = 30; + var browse = row.add("button", undefined, "Browse...", { name: "browse" }); + browse.onClick = function () { + var f = File.openDialog("Select a song", "Audio:*.mp3;*.wav,All files:*.*"); + song.text = f ? f.fsName : "(cancelled)"; + }; + var out = d.add("edittext", undefined, "", { name: "out" }); + var where = d.add("button", undefined, "Folder...", { name: "where" }); + where.onClick = function () { + var f = Folder.selectDialog("Output folder"); + out.text = f ? f.fsName : "(cancelled)"; + }; + d.add("button", undefined, "OK", { name: "ok" }); + if (d.show() === 1) app.project.activeItem.layers.addNull().name = song.text + " | " + out.text; + "#; + let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "pick.jsx"})).unwrap(); + assert_eq!(r["waiting"], true, "{r}"); + h.run_steps(3); + let d = h.state().session.script_ui.windows.iter().find(|w| w.modal).unwrap().id; + let text = |h: &Harness<'_, EffectcraftApp>, name: &str| { + h.state().session.script_ui.window(d).and_then(|w| w.root.lookup(&json!(name))).map(|w| w.text.clone()).unwrap_or_default() + }; + click(&mut h, &format!("scriptui.{d}.browse")); + assert_eq!(*asked.lock().unwrap(), [vec!["mp3".to_string(), "wav".to_string()]], "Browse… opens the file dialog with the script's filter"); + assert_eq!(text(&h, "song"), picked, "the script gets the picked file"); + click(&mut h, &format!("scriptui.{d}.where")); + assert_eq!(text(&h, "out"), "(cancelled)", "a cancelled dialog gives the script null"); + + // A dialog that doesn't block the frame answers when it closes. + let done: Arc>> = Arc::default(); + let queue = done.clone(); + h.state_mut().hooks.file_dialog_async = Some(Box::new(move |dialog, answer| queue.lock().unwrap().push((dialog, answer)))); + click(&mut h, &format!("scriptui.{d}.where")); + let (dialog, answer) = done.lock().unwrap().pop().expect("the folder dialog is asked for"); + assert_eq!(dialog, effectcraft_ui_egui::FileDialog::ScriptFolder { prompt: "Output folder".into(), start: String::new() }); + let folder = std::env::temp_dir().to_string_lossy().to_string(); + answer(Ok(vec![folder.clone()])); + h.run_steps(3); + assert_eq!(text(&h, "out"), folder); + // A dialog that ends without answering (its completion handler never runs) counts as + // cancelled: the script doesn't wait for good. + h.state_mut().hooks.file_dialog_async = Some(Box::new(|_: effectcraft_ui_egui::FileDialog, answer: effectcraft_ui_egui::DialogDone| drop(answer))); + click(&mut h, &format!("scriptui.{d}.where")); + h.run_steps(3); + assert_eq!(text(&h, "out"), "(cancelled)"); + // The dialog still works: OK closes it and the script runs on. + click(&mut h, &format!("scriptui.{d}.ok")); + assert_eq!(layer_names(&h), [format!("{picked} | (cancelled)")]); + assert!(h.state().session.script_ui.windows.is_empty()); +} + +/// #2778 review: the prompt, the start location and the full filter of a script's instance +/// `openDlg` / `saveDlg` / `selectDlg` reach the host's dialog, not just the filter's extensions. +#[test] +fn script_file_dialog_options_reach_the_host_dialog() { + use effectcraft_ui_egui::FileDialog; + use std::sync::{Arc, Mutex}; + let mut h = harness(); + let asked: Arc>> = Arc::default(); + let log = asked.clone(); + h.state_mut().hooks.pick_file_dialog = Some(Box::new(move |dialog| { + log.lock().unwrap().push(dialog); + Vec::new() + })); + let dir = std::env::temp_dir().to_string_lossy().to_string(); + let code = format!( + r#" + var d = new Window("dialog", "Options"); + d.add("button", undefined, "Open", {{ name: "open" }}).onClick = function () {{ new File({dir:?}).openDlg("Pick a song", "Audio:*.mp3;*.wav,All files:*.*", false); }}; + d.add("button", undefined, "Save", {{ name: "save" }}).onClick = function () {{ new File({dir:?} + "/Mix.wav").saveDlg("Save the mix", "Audio:*.wav;*.aif"); }}; + d.add("button", undefined, "Folder", {{ name: "folder" }}).onClick = function () {{ new Folder({dir:?}).selectDlg("Output folder"); }}; + d.add("button", undefined, "OK", {{ name: "ok" }}); + d.show(); + "# + ); + let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "opts.jsx"})).unwrap(); + assert_eq!(r["waiting"], true, "{r}"); + h.run_steps(3); + let d = h.state().session.script_ui.windows.iter().find(|w| w.modal).unwrap().id; + for name in ["open", "save", "folder"] { + click(&mut h, &format!("scriptui.{d}.{name}")); + } + let got = asked.lock().unwrap().clone(); + let exts = |e: &[&str]| e.iter().map(|e| e.to_string()).collect::>(); + assert_eq!( + got, + [ + FileDialog::Script { label: "Audio".into(), exts: exts(&["mp3", "wav"]), any: true, many: false, prompt: "Pick a song".into(), start: dir.clone() }, + FileDialog::ScriptSave { + default: format!("{dir}/Mix.wav"), + prompt: "Save the mix".into(), + label: "Audio".into(), + exts: exts(&["wav", "aif"]), + any: false + }, + FileDialog::ScriptFolder { prompt: "Output folder".into(), start: dir.clone() }, + ], + "the dialogs carry the script's prompt, start location and whole filter" + ); +} + +/// #2894: the same from a dockable ScriptUI panel (Window ▸ ): its button's +/// `File.openDialog` opens the file dialog and the panel's handler goes on with the file. +#[test] +fn a_docked_panel_button_opens_the_file_dialog() { + use effectcraft_engine::config::{ConfigStore, MemoryConfig}; + use std::sync::{Arc, Mutex}; + let store = Arc::new(MemoryConfig::default()); + let panel = r#" + var p = this; + var status = p.add("statictext", undefined, "No file selected", { name: "status" }); + status.characters = 40; + var pick = p.add("button", undefined, "Select SRT File", { name: "pick" }); + pick.onClick = function () { + var f = File.openDialog("Select an SRT file", "Subtitles:*.srt;All Files:*.*"); + status.text = f ? f.name : "No file selected"; + }; + p.layout.layout(true); + "#; + store.write("Scripts/ScriptUI Panels/Subtitles Panel.jsx", panel).unwrap(); + let mut s = effectcraft_host::session(); + s.config = Some(store.clone()); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| EffectcraftApp::new(s)); + h.run_steps(3); + let asked: Arc>>> = Arc::default(); + let log = asked.clone(); + let file = std::env::temp_dir().join("Episode 1.srt").to_string_lossy().to_string(); + h.state_mut().hooks.pick_files = Some(Box::new(move |exts: &[&str]| { + log.lock().unwrap().push(exts.iter().map(|e| e.to_string()).collect()); + vec![file.clone()] + })); + h.state_mut().session.execute("window.scriptPanel", json!({"name": "Subtitles Panel.jsx"})).unwrap(); + h.run_steps(3); + let panel = h.state().session.script_ui.windows.iter().find(|w| w.script == "Subtitles Panel.jsx").expect("the panel's window").id; + assert!(h.state().ui.dock.is_docked(PanelKind::ScriptPanel(panel)), "the panel docks"); + click(&mut h, &format!("scriptui.{panel}.pick")); + assert_eq!(*asked.lock().unwrap(), [vec!["srt".to_string()]], "the panel's button opens the file dialog"); + let status = h.state().session.script_ui.window(panel).and_then(|w| w.root.lookup(&json!("status"))).map(|w| w.text.clone()).unwrap_or_default(); + assert_eq!(status, "Episode 1.srt"); +} diff --git a/docs/agents.md b/docs/agents.md index a83432f04..e09a94957 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -688,7 +688,15 @@ Scripts that build ScriptUI windows publish them to the session; agents drive th A dialog's `show()` waits for the user: the `script.run` / `file.runScript` reply carries `"waiting": true`, and the script continues (its final output arrives in the reply of the click -that closes the dialog). File ▸ Scripts: `file.scripts.list`, `file.runScript {"name": …}`, +that closes the dialog). A script's file dialog (`File.openDialog`, `File.saveDialog`, +`Folder.selectDialog`, `openDlg` / `saveDlg` / `selectDlg`, as a Browse… button calls them) waits +the same way in the app, which shows it. `scriptui.fileDialogs` lists the dialogs scripts wait on +(`{id, host, kind: open|save|folder, prompt, exts, label, any, many, start, shown}`; `shown`: the +app has shown it) and `scriptui.fileDialog {"id": …, "paths": […]}` (or `null`: cancelled) answers +one. On Windows the system dialog blocks the app's window until a person closes it, so an agent +can't answer it there; on macOS and Linux it doesn't block. The script's windows refuse events +meanwhile, except `scriptui.close`, which cancels the file dialog first. Without the app (headless +runs), in the Script Console and in Shutdown scripts these return `null` at once. File ▸ Scripts: `file.scripts.list`, `file.runScript {"name": …}`, `file.installScript` / `file.installScriptUIPanel {"path": …}`, `window.scriptPanel {"name": …}`, `window.restoreScriptPanels` (the panels open when the app last quit), `file.runStartupScripts` and `file.runShutdownScripts` (the scripts in `Scripts/Startup` and `Scripts/Shutdown`; the second closes diff --git a/docs/scripting-parity.md b/docs/scripting-parity.md index 9aa6ca626..662472c96 100644 --- a/docs/scripting-parity.md +++ b/docs/scripting-parity.md @@ -20,7 +20,7 @@ our own scripts; no real-world script library has been run against both apps. | Expression performance | Cached, multi-frame | Per-thread boa contexts | unknown | No benchmark | | Scripting object model | `app`, `Project`, items, layers, properties, keys, eases, render queue, `TextDocument`, `Shape`, markers, `File`/`Folder`, `Socket`, `app.settings` | Same classes, edits run through undoable engine commands; match names table, the properties of Offset Paths and Zig Zag included; layers, groups and properties are callable (`layer("Effects")(1)` is `.property(...)`) | good | `crates/script` tests (≈ 10 test files) | | `$.evalFile`, `BridgeTalk` | Evaluate another script file; identify the host application and message other Adobe applications | `$.evalFile` evaluates a file relative to the calling file (nested at most 32 deep, under the scripts' file gate) and returns its last value; `BridgeTalk` names the host honestly (`appName` `effectcraft`, its version); messaging other applications throws "not supported" | partial | `tests_evalfile.rs` (#760); no inter-application messaging | -| ScriptUI | Dialogs, palettes, dockable panels, resource strings, `onDraw` / ScriptUIGraphics, mouse events | Same, dockable panels reopen at launch; a docked panel gets its dock's size and `onResize` (`scriptui.resize`, #2585); a drag keeps reaching the control it started on past the window edge, and `MouseEvent.buttons` reports the held buttons (#2584) | good | `ui_scriptui`, `tests_ui*` | +| ScriptUI | Dialogs, palettes, dockable panels, resource strings, `onDraw` / ScriptUIGraphics, mouse events | Same, dockable panels reopen at launch; a docked panel gets its dock's size and `onResize` (`scriptui.resize`, #2585); a drag keeps reaching the control it started on past the window edge, and `MouseEvent.buttons` reports the held buttons (#2584); `File.openDialog`, `File.saveDialog` and `Folder.selectDialog` (a Browse… button) show the app's file dialog and the script waits for it (#2778) | good | `ui_scriptui`, `tests_ui*` | | `app.scheduleTask` / `cancelTask` | One-shot and repeating tasks (polling, panel refresh) until `cancelTask` | Same: repeating tasks run every `delay` ms (at least 50 ms, at most 64 pending per script) until `cancelTask`, until they throw (reported once, then cancelled), or until their owner goes: a script's last window closing, or the project closing for scripts without windows (a Startup script's tasks go on until EffectCraft quits); frontends tick them every frame, agents with `script.runTasks` | good | `tests_tasks.rs` (#773); one-shot tasks of a script file still run right after it, not after their delay | | Scripts menu, ScriptUI Panels folder | yes | yes; a subfolder (one level) of either folder is a submenu named after it | same | [plugins.md](plugins.md) | | Startup / Shutdown folders | yes | `Scripts/Startup` runs at launch and `Scripts/Shutdown` runs as the desktop app quits, after the project is closed, each in alphabetical order | partial | `crates/script/src/tests/startup.rs`; each script has its own global scope, so a Startup script's variables and functions are not available to later scripts ([plugins.md](plugins.md)) | From 29d116c6f706171e49dab902e1186249e00bb1ce Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Sun, 22 Nov 2026 20:31:15 +0100 Subject: [PATCH 382/393] Convert To Bezier Path works on a selected shape layer or group, for example right after drawing a rectangle (#3220) * #3057: Convert To Bezier Path converts a selected shape layer's or group's parametric paths Right after drawing with the Rectangle, Ellipse or Polygon tool only the layer is selected, and Convert To Bezier Path fell through to the mask branch and reported "no masks". It only converted when the parametric path row itself (Rectangle Path 1) was selected. - A selected shape group converts the parametric paths inside it, nested groups included. - With only layers selected, a shape layer converts its parametric paths, as a selected layer's masks are targeted. Locked layers are skipped; animated parametric paths are left alone and reported (skippedAnimated), and selecting the path still converts it. - Masks win only when targeted (mask param, selected mask, mask vertices) or when one uses RotoBezier: plain masks no longer turn the command into a silent no-op. - An explicit layer/layers limits selected shape items to those layers; an unmatched mask param is an error instead of converting every path. - Errors say what to select instead of asking for masks. A PSD shape layer importing as a layer with a mask matches After Effects; no change there. Fixes #3057 * #3057: Convert To Bezier Path converts a layer named twice once A layer given twice in `layers` (by id and by name) was widened twice: its parametric paths were queued twice, and the second replacement found no such item, so the whole command failed. The layer list is deduplicated before the widening, which also keeps skippedAnimated from counting a path twice. * #3057: Convert To Bezier Path leaves locked layers and a group's animated paths alone Shape items given as `items` or selected on a locked layer converted anyway (only the layer-wide conversion checked locks); they now go through unlocked(), an error when every one is locked. A selected group skips its keyframed or expression-driven parametric paths and reports them in skippedAnimated, as converting a whole layer does; a path selected itself still converts at the current time. * Doc comments for the functions this PR touches * #3057: Convert To Bezier Path gives an explicit mask priority over shape items With a `mask` given, a selected parametric path (or `items`) was converted instead of the mask, an unmatched `mask` converted the shape rather than reporting the miss, and a locked shape-item layer could reject the call before the mask was looked at. Shape items are now ignored when `mask` is present. * #3057: Convert To Bezier Path converts a selected mask with the selected shape paths With a mask and a parametric path both selected, only the path converted and the mask kept its RotoBezier tangents. Masks the selection targets (a selected mask or its property, mask vertices, on unlocked layers in scope) now convert in the same undo step, the result reports them as masks, and they stay selected with the new paths. An explicit `mask` keeps its priority. * #3057: Convert To Bezier Path keeps mask conversion to an explicit layer With `{"layer": A}` and a RotoBezier mask selected on layer B, the mask branch converted B's mask and left A unchanged. The resolved masks are now scoped to the explicit layer/layers (falling back to those layers' own masks), the priority check only counts selected masks and vertices in scope, and the scoped targets are edited directly instead of being resolved again. * #3057: Convert To Bezier Path leaves masks on locked layers alone A scoped or selected RotoBezier mask on a locked layer was converted through the mask branch. Masks on locked layers are now dropped after the scope and its fallback are resolved, so a locked selected mask does not hand the conversion to other masks; when every targeted mask is locked, the command reports the lock, as it does for shape items. * #3057: Convert To Bezier Path converts in the composition `comp` names With `comp` naming a composition that is not active, an explicit `mask` was resolved there but filtered against the active composition ("no mask matches"), and explicit `items` were looked up in the active composition. convert_to_bezier now works in the composition comp_id resolves, and selected_shape_items returns the composition layer_p resolved for explicit items (also used by Group and Ungroup Shapes); a selection made in another composition does not apply. * Convert To Bezier Path: explicit items add no selected masks With explicit `items`, only those shape paths convert. A RotoBezier mask selected on the same layer no longer loses its RotoBezier flag as a side effect. Regression test added. * Convert To Bezier Path: explicit items without a parametric path convert no mask * Convert To Bezier Path: items count as given only as a list --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/engine/src/cmd/paths.rs | 290 ++++++++++++++++++--- crates/engine/src/tests/stubs.rs | 426 +++++++++++++++++++++++++++++++ 2 files changed, 681 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 2f1e1051b..00c38c502 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -9,7 +9,7 @@ use effectcraft_render::EvalCtx; use serde_json::{Value, json}; use super::layer_menu::target_masks; -use super::{CommandSpec, b_p, bad, f_p, has_comp, has_layers, layer_mut, layer_p, merge_p, str_p}; +use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, has_layers, layer_mut, layer_p, layers_p, merge_p, str_p, unlocked}; use crate::{EngineError, Result, Session, VertexRef, cmd}; mod closed; @@ -153,26 +153,223 @@ fn parametric_path(ctx: &EvalCtx, layer: &effectcraft_project::Layer, g: &PropGr effectcraft_path::from_kurbo(&path).into_iter().next() } +/// How deep [`parametric_in`] looks into nested shape groups; deeper ones are left alone. +const MAX_SHAPE_DEPTH: usize = 64; + +/// The parametric paths in `g` (itself, if it is one), in drawing order. +fn parametric_in(g: &PropGroup, lid: LayerId, depth: usize, out: &mut Vec<(LayerId, Uid)>) { + if PARAMETRIC.contains(&g.match_id.as_str()) { + out.push((lid, g.uid)); + return; + } + if depth >= MAX_SHAPE_DEPTH { + return; + } + for c in g.groups() { + parametric_in(c, lid, depth + 1, out); + } +} + +/// Converts masks and the selected parametric shape paths (Rectangle, Ellipse, Polystar) to editable Bezier paths of the same geometry at the current time. +/// Items on locked layers are skipped, and it errors when nothing is left to convert. fn convert_to_bezier(s: &mut Session, p: &Value) -> Result { // On a shape layer this replaces a Rectangle, Ellipse or Polystar path with an editable // Path 1 of the same geometry, as After Effects does (#932). The parametric properties are // read at the current time and the path that comes out is static: a size or roundness // animation cannot survive the conversion, in After Effects either. - let (cid, items) = selected_shape_items(s, p)?; + const LABEL: &str = "Convert To Bezier Path"; + // An explicit `mask` is what converts: selected shape items (or `items`) don't take its place, + // and a `mask` that matches nothing is reported below rather than converting a shape. + // The composition is the one `comp` names (else the active one), as the mask and layer + // resolvers use; a selection made in another composition doesn't apply to it. + let cid = comp_id(s, p)?; + let mut items = if p.get("mask").is_some() { + Vec::new() + } else { + let (items_cid, items) = selected_shape_items(s, p, "path.convertToBezier")?; + if items_cid == cid { items } else { Vec::new() } + }; + // `items` count as given only as a list, as `selected_shape_items` reads them; a null or other + // value leaves the selection in charge. + let explicit_items = matches!(p.get("items"), Some(Value::Array(_))); + // An explicit `layer` / `layers` limits the selected shape items to those layers. + let explicit_layers = p.get("layer").is_some_and(|v| !v.is_null()) || p.get("layers").is_some(); + if explicit_layers && !explicit_items { + let (_, layers) = layers_p(s, p)?; + items.retain(|(l, _)| layers.contains(l)); + } + // Items on a locked layer are left alone (an error when they all are), whether they come from + // the selection or from `items`. + if !items.is_empty() { + let mut item_layers: Vec = items.iter().map(|(l, _)| *l).collect(); + item_layers.sort(); + item_layers.dedup(); + let open = unlocked(s, cid, item_layers, "path.convertToBezier")?; + items.retain(|(l, _)| open.contains(l)); + } let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?; - let shapes: Vec<(LayerId, Uid)> = items - .into_iter() - .filter(|(l, u)| { - comp.layer(*l).and_then(|l| l.props.sub("contents")).and_then(|c| c.find_group(*u)).is_some_and(|g| PARAMETRIC.contains(&g.match_id.as_str())) - }) - .collect(); - if shapes.is_empty() { - return edit_mask_groups(s, p, "Convert To Bezier Path", |g| { - if let GroupKind::Mask { roto_bezier, .. } = &mut g.kind { - *roto_bezier = false; + // A selected parametric path converts itself, animated or not (After Effects keeps the shape + // at the current time). A selected shape group converts the parametric paths inside it + // (#3057: selecting Rectangle 1 rather than its Rectangle Path 1 reported "no masks"), but + // leaves the animated ones alone, as converting a whole layer does. + let mut shapes: Vec<(LayerId, Uid)> = Vec::new(); + let mut skipped: Vec<(LayerId, Uid)> = Vec::new(); + for (lid, uid) in &items { + let Some(g) = comp.layer(*lid).and_then(|l| l.props.sub("contents")).and_then(|c| c.find_group(*uid)) else { continue }; + if PARAMETRIC.contains(&g.match_id.as_str()) { + shapes.push((*lid, *uid)); + continue; + } + let mut found = Vec::new(); + parametric_in(g, *lid, 0, &mut found); + for (fl, fu) in found { + if g.find_group(fu).is_some_and(PropGroup::any_animated) { + skipped.push((fl, fu)); + } else { + shapes.push((fl, fu)); } - Ok(()) - }); + } + } + shapes.sort(); + shapes.dedup(); + // A path both selected itself and inside a selected group converts; it is not skipped. + skipped.sort(); + skipped.dedup(); + skipped.retain(|x| !shapes.contains(x)); + let mut skipped_animated = skipped.len(); + // Masks the selection targets too (a selected mask or one of its properties, mask vertices) + // convert with the shape paths in the same step, as the command acts on every selected path: + // selecting a mask and a Rectangle path must not convert only the rectangle. + // Explicit `items` name exactly what converts: the selection adds no masks to them. + let mut sel_masks: Vec<(LayerId, Uid)> = Vec::new(); + if !shapes.is_empty() && !explicit_items { + let masks_of = |l: LayerId| comp.layer(l).filter(|ly| !ly.switches.locked).and_then(|ly| ly.masks()); + for (l, u) in &s.state.selected_props { + let Some(m) = masks_of(*l) else { continue }; + sel_masks.extend(m.groups().filter(|g| g.uid == *u || g.find(*u).is_some()).map(|g| (*l, g.uid))); + } + for v in &s.state.selected_vertices { + if masks_of(v.layer).is_some_and(|m| m.groups().any(|g| g.uid == v.mask)) { + sel_masks.push((v.layer, v.mask)); + } + } + if explicit_layers { + let (_, layers) = layers_p(s, p)?; + sel_masks.retain(|(l, _)| layers.contains(l)); + } + sel_masks.sort(); + sel_masks.dedup(); + } + if shapes.is_empty() { + // Explicit `items` with nothing parametric in them (a Fill, a path that is already Bezier) + // convert nothing: they don't hand the conversion to a selected mask or the layer's masks. + if explicit_items && p.get("mask").is_none() { + let why = if skipped_animated > 0 { + "the parametric paths are animated: name the path itself in `items` to convert it at the current time (its animation is lost)" + } else { + "nothing to convert: the given items have no Rectangle, Ellipse or Polystar path" + }; + return Err(bad(LABEL, why)); + } + let (_, mut masks) = masks_for(s, p)?; + let mask_of = |l: LayerId, u: Uid| comp.layer(l).and_then(|l| l.masks()).and_then(|m| m.groups().find(|g| g.uid == u)); + masks.retain(|(l, u)| mask_of(*l, *u).is_some()); + // An explicit `layer` / `layers` is the scope: a mask selected on another layer is not + // converted in its place. With none of the selected masks in scope, the scoped layers' + // own masks are the targets, as for a selected layer. + let scope = if explicit_layers { Some(layers_p(s, p)?.1) } else { None }; + let in_scope = |l: &LayerId| scope.as_ref().is_none_or(|v| v.contains(l)); + if let Some(layers) = &scope { + masks.retain(|(l, _)| layers.contains(l)); + if masks.is_empty() && p.get("mask").is_none() { + for l in layers { + if let Some(m) = comp.layer(*l).and_then(|ly| ly.masks()) { + masks.extend(m.groups().map(|g| (*l, g.uid))); + } + } + } + } + masks.sort(); + masks.dedup(); + // Masks on a locked layer are left alone, as shape items are. This comes after the scope + // and its fallback, so a locked selected mask doesn't hand the conversion to other masks. + let mut mask_layers: Vec = masks.iter().map(|(l, _)| *l).collect(); + mask_layers.dedup(); + masks.retain(|(l, _)| comp.layer(*l).is_some_and(|ly| !ly.switches.locked)); + // Masks take priority when they are targeted (a `mask`, a selected mask or mask vertices) + // or when one of them has RotoBezier tangents to turn off. A selected layer's plain masks + // are already Bezier paths: converting them would do nothing and hide the layer's + // parametric shapes (#3057). + let mask_targeted = p.get("mask").is_some() + || (p.get("layer").is_none() && s.state.selected_vertices.iter().any(|v| in_scope(&v.layer))) + || s.state + .selected_props + .iter() + .any(|(l, u)| in_scope(l) && comp.layer(*l).and_then(|l| l.masks()).is_some_and(|m| m.uid != *u && m.find_group(*u).is_some())); + let any_roto = masks.iter().any(|(l, u)| mask_of(*l, *u).is_some_and(is_roto)); + // Every targeted mask is on a locked layer: say so rather than convert anything else. + if mask_targeted && masks.is_empty() && !mask_layers.is_empty() { + unlocked(s, cid, mask_layers, "path.convertToBezier")?; + return Err(bad(LABEL, "the masks are on locked layers")); + } + // A selected group whose paths were all skipped as animated reports that, rather than + // turning to the layer's masks. + if !masks.is_empty() && (mask_targeted || (any_roto && skipped_animated == 0)) { + // The scoped targets are edited as resolved here, not looked up again. + let n = masks.len(); + s.edit(LABEL, None, |proj, _| { + for (lid, uid) in &masks { + let l = layer_mut(proj, cid, *lid)?; + if let Some(g) = l.props.sub_mut("masks").and_then(|m| m.find_group_mut(*uid)) + && let GroupKind::Mask { roto_bezier, .. } = &mut g.kind + { + *roto_bezier = false; + } + } + Ok(()) + })?; + return Ok(json!({"masks": n})); + } + if p.get("mask").is_some() { + return Err(bad(LABEL, "no mask matches `mask`")); + } + // Only layers selected (#3057): a shape layer drawn with the Rectangle, Ellipse or Polygon + // tool converts its parametric paths, as the masks of a selected layer do. A selected + // shape item with nothing parametric in it (a Fill, a Bezier path) is not widened to the + // whole layer, and an animated parametric path is left alone here: converting keeps only + // the shape at the current time, so that takes selecting the path itself. + if items.is_empty() { + let (lcid, mut layers) = layers_p(s, p)?; + // A layer named twice (`layers: [1, "Shape 1"]`) converts once: its paths would + // otherwise be replaced twice, and the second replacement finds no such item. + layers.sort(); + layers.dedup(); + if lcid == cid { + for lid in unlocked(s, cid, layers, "path.convertToBezier")? { + let Some(l) = comp.layer(lid).filter(|l| matches!(l.source, LayerSource::Shape)) else { continue }; + let Some(contents) = l.props.sub("contents") else { continue }; + let mut found = Vec::new(); + parametric_in(contents, lid, 0, &mut found); + for (fl, fu) in found { + if contents.find_group(fu).is_some_and(PropGroup::any_animated) { + skipped_animated += 1; + } else { + shapes.push((fl, fu)); + } + } + } + } + } + if shapes.is_empty() { + let why = if skipped_animated > 0 { + "the parametric paths are animated: select one in the Timeline to convert it at the current time (its animation is lost)" + } else if !masks.is_empty() { + "nothing to convert: the masks are already Bezier paths" + } else { + "nothing to convert: select a Rectangle, Ellipse or Polystar path, a shape layer with one, or a layer with masks" + }; + return Err(bad(LABEL, why)); + } } let t = s.time(); let n = shapes.len(); @@ -210,13 +407,22 @@ fn convert_to_bezier(s: &mut Session, p: &Value) -> Result { made.push((lid, new_uid)); } proj.next_id = next; - // The new paths are what is selected, so the vertices can be edited straight away. + for (lid, uid) in &sel_masks { + let l = layer_mut(proj, cid, *lid)?; + if let Some(g) = l.props.sub_mut("masks").and_then(|m| m.find_group_mut(*uid)) + && let GroupKind::Mask { roto_bezier, .. } = &mut g.kind + { + *roto_bezier = false; + } + } + // The new paths are what is selected, so the vertices can be edited straight away; the + // converted masks stay selected with them. if !made.is_empty() { - st.selected_props = made.clone(); + st.selected_props = made.iter().chain(&sel_masks).copied().collect(); } Ok(made) })?; - Ok(json!({"paths": made.len(), "of": n})) + Ok(json!({"paths": made.len(), "of": n, "masks": sel_masks.len(), "skippedAnimated": skipped_animated})) } // ---------------------------------------------------------------- mask options @@ -389,24 +595,25 @@ const SHAPE_ITEMS: &[&str] = &[ "wiggle", "wiggler", "merge", "front", "bevel", "side", "back", ]; -/// Selected shape items (contents entries) of shape layers: (layer, uid). -fn selected_shape_items(s: &Session, p: &Value) -> Result<(ItemId, Vec<(LayerId, Uid)>)> { +/// Selected shape items (contents entries) of shape layers: (layer, uid), with their composition. +/// Explicit `items` are on the layer `layer_p` resolves, in the composition it resolves (`comp`, +/// else the active one); selected items are the active composition's. +fn selected_shape_items(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, Vec<(LayerId, Uid)>)> { + if let Some(Value::Array(a)) = p.get("items") { + let (cid, lid) = layer_p(s, p, cmd)?; + return Ok((cid, a.iter().filter_map(Value::as_u64).map(|u| (lid, u)).collect())); + } let cid = s.active_comp_id().ok_or(EngineError::NoComp)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?; let mut out = vec![]; - if let Some(Value::Array(a)) = p.get("items") { - let (_, lid) = layer_p(s, p, "path.groupShapes")?; - out.extend(a.iter().filter_map(Value::as_u64).map(|u| (lid, u))); - } else { - for (lid, uid) in &s.state.selected_props { - let Some(l) = comp.layer(*lid).filter(|l| matches!(l.source, LayerSource::Shape)) else { continue }; - if l.props - .sub("contents") - .and_then(|c| c.find_group(*uid)) - .is_some_and(|g| g.uid != l.props.sub("contents").map(|c| c.uid).unwrap_or(0) && SHAPE_ITEMS.contains(&g.match_id.as_str())) - { - out.push((*lid, *uid)); - } + for (lid, uid) in &s.state.selected_props { + let Some(l) = comp.layer(*lid).filter(|l| matches!(l.source, LayerSource::Shape)) else { continue }; + if l.props + .sub("contents") + .and_then(|c| c.find_group(*uid)) + .is_some_and(|g| g.uid != l.props.sub("contents").map(|c| c.uid).unwrap_or(0) && SHAPE_ITEMS.contains(&g.match_id.as_str())) + { + out.push((*lid, *uid)); } } Ok((cid, out)) @@ -421,8 +628,10 @@ fn has_shape_items(s: &Session) -> std::result::Result<(), String> { if ok { Ok(()) } else { Err("select shape items (Contents ▸ …) in the timeline".into()) } } +/// Wraps the selected shape items of one layer in a new group placed where the first of them was. +/// Errors when no shape items are selected or they do not share one parent group. fn group_shapes(s: &mut Session, p: &Value) -> Result { - let (cid, items) = selected_shape_items(s, p)?; + let (cid, items) = selected_shape_items(s, p, "path.groupShapes")?; let Some(lid) = items.first().map(|x| x.0) else { return Err(bad("path.groupShapes", "select shape items to group")) }; let uids: Vec = items.iter().filter(|(l, _)| *l == lid).map(|(_, u)| *u).collect(); let g = s.edit("Group Shapes", None, |proj, st| { @@ -496,8 +705,10 @@ fn offset_items(g: &mut PropGroup, d: [f64; 2]) { } } +/// Replaces each selected shape group with its children, baking the group's position offset into them. +/// Errors when no group is selected or a group has a scale, rotation, skew, opacity or animated transform. fn ungroup_shapes(s: &mut Session, p: &Value) -> Result { - let (cid, items) = selected_shape_items(s, p)?; + let (cid, items) = selected_shape_items(s, p, "path.ungroupShapes")?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?; let groups: Vec<(LayerId, Uid)> = items .into_iter() @@ -548,11 +759,20 @@ fn ungroup_shapes(s: &mut Session, p: &Value) -> Result { Ok(json!({"ungrouped": n})) } +/// The command specs for the path commands: RotoBezier, Convert To Bezier Path, Group Shapes, Ungroup Shapes and the rest of this module. pub fn specs() -> Vec { vec![ cmd!("path.toggleClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{}", closed::has_paths, closed::toggle_closed), cmd!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?, value?}", has_layers, roto_bezier), - cmd!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?}", has_layers, convert_to_bezier), + cmd!( + "path.convertToBezier", + "Convert To Bezier Path", + ["Layer", "Mask and Shape Path"], + None, + "{layer?, layers?, mask?, items?: [uid]}", + has_layers, + convert_to_bezier + ), cmd!("path.groupShapes", "Group Shapes", ["Layer"], Some("Cmd+G"), "{layer?, items?: [uid]}", has_shape_items, group_shapes), cmd!("path.ungroupShapes", "Ungroup Shapes", ["Layer"], Some("Cmd+Shift+G"), "{layer?, items?: [group uid]}", has_shape_items, ungroup_shapes), cmd!( diff --git a/crates/engine/src/tests/stubs.rs b/crates/engine/src/tests/stubs.rs index 6f89f4f62..58fb21777 100644 --- a/crates/engine/src/tests/stubs.rs +++ b/crates/engine/src/tests/stubs.rs @@ -649,6 +649,432 @@ fn convert_to_bezier_evaluates_corner_expressions() { assert_eq!(path, expected, "the expression-evaluated corner is converted"); } +/// The uid of the first shape item with `match_id` in a shape layer's Contents. +fn shape_item(s: &Session, l: u64, match_id: &str) -> u64 { + /// Depth-first search of a property group tree for the uid of the first group with the given match id. + fn walk(g: &effectcraft_project::PropGroup, id: &str) -> Option { + if g.match_id == id { + return Some(g.uid); + } + g.groups().find_map(|c| walk(c, id)) + } + let ly = layer(s, l); + let contents = ly.props.sub("contents").unwrap(); + contents.groups().find_map(|c| walk(c, match_id)).unwrap() +} + +/// #3057: right after drawing with the Rectangle, Ellipse or Polygon tool only the layer is +/// selected; Convert To Bezier Path then converted nothing and reported "no masks". The selected +/// shape layer's parametric paths convert, as the masks of a selected layer do, and so do those in +/// a selected shape group (Rectangle 1 rather than its Rectangle Path 1). +#[test] +fn convert_to_bezier_on_a_selected_shape_layer_or_group() { + for kind in ["rect", "ellipse", "polygon"] { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": kind, "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(s.state.selected_layers, vec![LayerId(l)], "the new layer is selected"); + assert!(s.state.selected_props.is_empty(), "and no shape item"); + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{kind}: {out}"); + let (new_uid, now) = first_shape(&s, l); + assert_eq!(now, "path", "{kind}: the layer's parametric path is a bezier path now"); + assert_eq!(s.state.selected_props, vec![(LayerId(l), new_uid)], "{kind}: and selected, to edit its vertices"); + } + + // A selected shape group converts the parametric path inside it. + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let group = shape_item(&s, l, "group"); + s.state.selected_props = vec![(LayerId(l), group)]; + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, l).1, "path"); + + // Nothing parametric left: the error says what to select instead of asking for masks. + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string(); + assert!(err.contains("Rectangle, Ellipse or Polystar"), "{err}"); +} + +/// #3057: a selected shape item with nothing parametric in it (a Fill) does not widen the +/// conversion to the rest of the layer. A guard for the fix (it passes on the old code too). +#[test] +fn convert_to_bezier_does_not_widen_a_selected_fill() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + let fill = shape_item(&s, l, "fill"); + s.state.selected_props = vec![(LayerId(l), fill)]; + assert!(s.execute("path.convertToBezier", json!({})).is_err()); + assert_eq!(first_shape(&s, l).1, "rect", "the rectangle stays parametric"); +} + +/// #3057: a selected shape layer's plain masks are already Bezier paths, so they don't hide its +/// rectangle: the rectangle converts. A RotoBezier mask still converts first. +#[test] +fn convert_to_bezier_on_a_shape_layer_with_a_plain_mask() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap(); + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + s.state.selected_vertices.clear(); + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, l).1, "path"); + + // Nothing parametric left and the mask is plain: say so rather than succeed doing nothing. + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + s.state.selected_vertices.clear(); + let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string(); + assert!(err.contains("already Bezier"), "{err}"); +} + +/// #3057: an explicit `mask` that matches no mask converts nothing, rather than every parametric +/// path of the layer. +#[test] +fn convert_to_bezier_with_an_unmatched_mask_converts_nothing() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + assert!(s.execute("path.convertToBezier", json!({"layer": l, "mask": "No Such Mask"})).is_err()); + assert_eq!(first_shape(&s, l).1, "rect", "the rectangle stays parametric"); +} + +/// #3057: an explicit `layer` is the layer converted, even with a path selected on another one. +#[test] +fn convert_to_bezier_follows_an_explicit_layer() { + let mut s = comp(); + let a = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newShape", json!({"kind": "ellipse", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let (a_rect, _) = first_shape(&s, a); + s.state.selected_props = vec![(LayerId(a), a_rect)]; + let out = s.execute("path.convertToBezier", json!({"layer": b})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, b).1, "path", "the given layer converts"); + assert_eq!(first_shape(&s, a).1, "rect", "the selection on another layer does not"); +} + +/// #3057: converting a selected layer leaves an animated parametric path alone (its animation +/// would be lost) and reports it; selecting that path converts it at the current time, as After +/// Effects does. +#[test] +fn convert_to_bezier_skips_animated_paths_of_a_selected_layer() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let (rect, _) = first_shape(&s, l); + let size = layer(&s, l).props.sub("contents").unwrap().find_group(rect).unwrap().get("size").unwrap().uid; + for (t, v) in [(0.0, [120.0, 80.0]), (1.0, [200.0, 100.0])] { + s.execute("prop.addKey", json!({"layer": l, "path": format!("@{size}"), "time": t, "value": v})).unwrap(); + } + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string(); + assert!(err.contains("animated"), "{err}"); + assert_eq!(first_shape(&s, l).1, "rect", "the animated rectangle stays parametric"); + + s.state.selected_props = vec![(LayerId(l), rect)]; + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, l).1, "path", "the selected path converts"); +} + +/// #3057 review: a layer named twice in `layers` (by id and by name) converts once, and its +/// animated paths are counted once. +#[test] +fn convert_to_bezier_with_a_layer_named_twice() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let name = layer(&s, l).name; + let out = s.execute("path.convertToBezier", json!({"layers": [l, name, l]})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(out["of"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, l).1, "path"); + + let mut s = comp(); + let a = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newShape", json!({"kind": "ellipse", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let (rect, _) = first_shape(&s, a); + let size = layer(&s, a).props.sub("contents").unwrap().find_group(rect).unwrap().get("size").unwrap().uid; + for (t, v) in [(0.0, [120.0, 80.0]), (1.0, [200.0, 100.0])] { + s.execute("prop.addKey", json!({"layer": a, "path": format!("@{size}"), "time": t, "value": v})).unwrap(); + } + s.execute("layer.select", json!({"layers": [b]})).unwrap(); + let out = s.execute("path.convertToBezier", json!({"layers": [a, a, b]})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(out["skippedAnimated"].as_u64(), Some(1), "{out}"); +} + +/// #3057 review: shape items on a locked layer don't convert, whether given as `items` or +/// selected; unlocked, they do. +#[test] +fn convert_to_bezier_leaves_a_locked_layer_alone() { + for explicit in [true, false] { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let (rect, _) = first_shape(&s, l); + let lock = |s: &mut Session, v: bool| { + s.execute("layer.setSwitch", json!({"layers": [l], "switch": "locked", "value": v})).unwrap(); + }; + let run = |s: &mut Session| { + if explicit { + s.execute("path.convertToBezier", json!({"layer": l, "items": [rect]})) + } else { + s.state.selected_props = vec![(LayerId(l), rect)]; + s.execute("path.convertToBezier", json!({})) + } + }; + lock(&mut s, true); + let err = run(&mut s).unwrap_err().to_string(); + assert!(err.contains("locked"), "explicit {explicit}: {err}"); + assert_eq!(first_shape(&s, l).1, "rect", "explicit {explicit}: the locked rectangle stays parametric"); + lock(&mut s, false); + let out = run(&mut s).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "explicit {explicit}: {out}"); + assert_eq!(first_shape(&s, l).1, "path"); + } +} + +/// #3057 review: a selected group leaves its animated paths alone and reports them, as +/// converting a whole layer does; the path itself, selected, still converts. +#[test] +fn convert_to_bezier_skips_animated_paths_of_a_selected_group() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let (rect, _) = first_shape(&s, l); + let group = shape_item(&s, l, "group"); + let size = layer(&s, l).props.sub("contents").unwrap().find_group(rect).unwrap().get("size").unwrap().uid; + s.execute("prop.setExpression", json!({"layer": l, "path": format!("@{size}"), "expression": "[100, 100]"})).unwrap(); + + s.state.selected_props = vec![(LayerId(l), group)]; + let err = s.execute("path.convertToBezier", json!({})).unwrap_err().to_string(); + assert!(err.contains("animated"), "{err}"); + assert_eq!(first_shape(&s, l).1, "rect", "the expression-driven rectangle stays parametric"); + + // The group and its path both selected: the path is converted, not skipped. + s.state.selected_props = vec![(LayerId(l), group), (LayerId(l), rect)]; + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(out["skippedAnimated"].as_u64(), Some(0), "{out}"); + assert_eq!(first_shape(&s, l).1, "path"); +} + +/// #3057 review: an explicit `mask` is what converts, even with a parametric path selected or +/// `items` given; a `mask` that matches nothing is an error and converts no shape. +#[test] +fn convert_to_bezier_gives_an_explicit_mask_priority() { + // A shape layer with a rectangle and a RotoBezier mask; the rectangle's path is selected. + let setup = || { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap(); + let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid; + s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap(); + let (rect, _) = first_shape(&s, l); + s.state.selected_props = vec![(LayerId(l), rect)]; + (s, l, m, rect) + }; + + // A matching mask converts, not the selected rectangle. + let (mut s, l, m, _) = setup(); + s.execute("path.convertToBezier", json!({"layer": l, "mask": m})).unwrap(); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: false, .. }), "the mask converts"); + assert_eq!(first_shape(&s, l).1, "rect", "the selected rectangle stays parametric"); + + // An unmatched mask is an error, and the selected rectangle is not converted in its place. + let (mut s, l, _, _) = setup(); + let err = s.execute("path.convertToBezier", json!({"layer": l, "mask": "No Such Mask"})).unwrap_err().to_string(); + assert!(err.contains("mask"), "{err}"); + assert_eq!(first_shape(&s, l).1, "rect"); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. })); + + // `mask` and `items` together: the mask converts, the items don't. + let (mut s, l, m, rect) = setup(); + s.state.selected_props.clear(); + s.execute("path.convertToBezier", json!({"layer": l, "mask": m, "items": [rect]})).unwrap(); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: false, .. }), "the mask converts"); + assert_eq!(first_shape(&s, l).1, "rect", "the listed rectangle stays parametric"); +} + +/// #3057 review: a selected mask and a selected parametric path both convert, in one undo step; +/// neither is dropped for the other. +#[test] +fn convert_to_bezier_converts_a_selected_mask_and_path_together() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap(); + let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid; + s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap(); + let (rect, _) = first_shape(&s, l); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(l), m), (LayerId(l), rect)]; + + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(out["masks"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, l).1, "path", "the rectangle converts"); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: false, .. }), "and so does the mask"); + + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(first_shape(&s, l).1, "rect", "one undo restores the rectangle"); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }), "and the mask"); +} + +/// #3057 review: explicit `items` convert only those shape paths; a RotoBezier mask that happens to +/// be selected on the same layer is not converted along with them. +#[test] +fn convert_to_bezier_with_explicit_items_leaves_a_selected_mask_alone() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap(); + let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid; + s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap(); + let (rect, _) = first_shape(&s, l); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(l), m)]; + let out = s.execute("path.convertToBezier", json!({"layer": l, "items": [rect]})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert!(out.get("masks").is_none_or(|v| v.as_u64().unwrap_or(0) == 0), "{out}"); + assert_eq!(first_shape(&s, l).1, "path", "the listed rectangle converts"); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }), "the selected mask is unchanged"); +} + +/// #3057 review: explicit `items` with nothing parametric in them (a Fill, a path that is already +/// Bezier) are an error and change nothing: neither a selected RotoBezier mask nor, with no mask +/// selected, the layer's own RotoBezier masks are converted in their place. +#[test] +fn convert_to_bezier_with_explicit_non_parametric_items_converts_no_mask() { + for item in ["fill", "path"] { + for mask_selected in [true, false] { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [50, 0], [50, 50], [0, 50]], "closed": true})).unwrap(); + let m = layer(&s, l).masks().unwrap().groups().next().unwrap().uid; + s.execute("path.rotoBezier", json!({"layer": l, "mask": m, "value": true})).unwrap(); + let (rect, _) = first_shape(&s, l); + s.state.selected_vertices.clear(); + s.state.selected_props.clear(); + // An already-Bezier path: the rectangle converted first, the mask left as it is. + if item == "path" { + s.execute("path.convertToBezier", json!({"layer": l, "items": [rect]})).unwrap(); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. })); + } + let uid = shape_item(&s, l, item); + s.state.selected_vertices.clear(); + s.state.selected_props = if mask_selected { vec![(LayerId(l), m)] } else { Vec::new() }; + let before = layer(&s, l).props; + + let err = s.execute("path.convertToBezier", json!({"layer": l, "items": [uid]})).unwrap_err().to_string(); + assert!(err.contains("Rectangle, Ellipse or Polystar"), "{item}, mask selected {mask_selected}: {err}"); + assert!(matches!(mask_kind(&s, l), GroupKind::Mask { roto_bezier: true, .. }), "{item}, mask selected {mask_selected}: the mask is unchanged"); + assert!(layer(&s, l).props == before, "{item}, mask selected {mask_selected}: no shape or mask changed"); + } + } +} + +/// #3057 review: an explicit `layer` scopes the mask conversion too: a RotoBezier mask selected +/// on another layer is left alone, and the given layer's masks convert. +#[test] +fn convert_to_bezier_keeps_masks_to_an_explicit_layer() { + let mut s = comp(); + let (a, _) = masked(&mut s); + let (b, mb) = masked(&mut s); + for l in [a, b] { + s.state.selected_props.clear(); + s.state.selected_vertices.clear(); + s.execute("path.rotoBezier", json!({"layer": l, "value": true})).unwrap(); + } + assert!(matches!(mask_kind(&s, a), GroupKind::Mask { roto_bezier: true, .. })); + assert!(matches!(mask_kind(&s, b), GroupKind::Mask { roto_bezier: true, .. })); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(b), mb)]; + + let out = s.execute("path.convertToBezier", json!({"layer": a})).unwrap(); + assert_eq!(out["masks"].as_u64(), Some(1), "{out}"); + assert!(matches!(mask_kind(&s, a), GroupKind::Mask { roto_bezier: false, .. }), "the given layer's mask converts"); + assert!(matches!(mask_kind(&s, b), GroupKind::Mask { roto_bezier: true, .. }), "the mask selected on another layer does not"); +} + +/// #3057 review: a RotoBezier mask on a locked layer stays as it is, given as the layer or +/// selected, and removing it as a target does not hand the conversion to another layer's mask. +#[test] +fn convert_to_bezier_leaves_a_locked_layers_masks_alone() { + let mut s = comp(); + let (a, ma) = masked(&mut s); + let (b, _) = masked(&mut s); + for l in [a, b] { + s.state.selected_props.clear(); + s.state.selected_vertices.clear(); + s.execute("path.rotoBezier", json!({"layer": l, "value": true})).unwrap(); + } + s.execute("layer.setSwitch", json!({"layers": [a], "switch": "locked", "value": true})).unwrap(); + let roto = |s: &Session, l: u64| matches!(mask_kind(s, l), GroupKind::Mask { roto_bezier: true, .. }); + + // The locked layer given explicitly. + s.state.selected_props.clear(); + s.state.selected_vertices.clear(); + let err = s.execute("path.convertToBezier", json!({"layer": a})).unwrap_err().to_string(); + assert!(err.contains("locked"), "{err}"); + assert!(roto(&s, a), "the locked layer's mask stays RotoBezier"); + + // Its mask selected, with the unlocked layer in scope too: B's mask is not converted instead. + s.state.selected_props = vec![(LayerId(a), ma)]; + let err = s.execute("path.convertToBezier", json!({"layers": [a, b]})).unwrap_err().to_string(); + assert!(err.contains("locked"), "{err}"); + assert!(roto(&s, a) && roto(&s, b), "neither mask converts"); +} + +/// #3057 review: an explicit `comp` that is not the active composition is where `items` and +/// `mask` are looked up and converted. +#[test] +fn convert_to_bezier_in_a_composition_that_is_not_active() { + let mut s = comp(); + let main = s.active_comp_id().unwrap(); + let l = s.execute("layer.newShape", json!({"kind": "rect", "size": [120, 80]})).unwrap()["layer"].as_u64().unwrap(); + let (rect, _) = first_shape(&s, l); + let (solid, m) = masked(&mut s); + s.state.selected_props.clear(); + s.state.selected_vertices.clear(); + s.execute("path.rotoBezier", json!({"layer": solid, "value": true})).unwrap(); + s.execute("comp.new", json!({"name": "Other", "width": 400, "height": 300, "frameRate": 30, "duration": 4})).unwrap(); + assert_ne!(s.active_comp_id(), Some(main), "another composition is active"); + let in_main = |s: &Session| s.project.comp(main).unwrap().clone(); + let main_mask_roto = |s: &Session| { + let c = in_main(s); + matches!(c.layer(LayerId(solid)).unwrap().masks().unwrap().find_group(m).unwrap().kind, GroupKind::Mask { roto_bezier: true, .. }) + }; + + // Explicit shape items. + let out = s.execute("path.convertToBezier", json!({"comp": main.0, "layer": l, "items": [rect]})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + let c = in_main(&s); + let contents = c.layer(LayerId(l)).unwrap().props.sub("contents").unwrap(); + assert!(contents.find_group(rect).is_none(), "the rectangle is replaced in that composition"); + + // An explicit mask. + assert!(main_mask_roto(&s)); + s.execute("path.convertToBezier", json!({"comp": main.0, "layer": solid, "mask": m})).unwrap(); + assert!(!main_mask_roto(&s), "the mask converts in that composition"); +} + +/// #3057: parametric paths in nested groups convert from the layer and from the outer group. +#[test] +fn convert_to_bezier_finds_paths_in_nested_groups() { + for select_outer in [false, true] { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "star", "size": [120, 120]})).unwrap()["layer"].as_u64().unwrap(); + let inner = shape_item(&s, l, "group"); + s.state.selected_props = vec![(LayerId(l), inner)]; + s.execute("path.groupShapes", json!({})).unwrap(); + let outer = shape_item(&s, l, "group"); + assert_ne!(outer, inner, "the shape is nested one group deeper"); + if select_outer { + s.state.selected_props = vec![(LayerId(l), outer)]; + } else { + s.execute("layer.select", json!({"layers": [l]})).unwrap(); + } + let out = s.execute("path.convertToBezier", json!({})).unwrap(); + assert_eq!(out["paths"].as_u64(), Some(1), "{out}"); + assert_eq!(first_shape(&s, l).1, "path"); + } +} + /// #2201: a viewer drag on the free-transform box sends one `path.freeTransform` per frame with a /// shared merge key; one undo must revert the whole drag, not the last frame. #[test] From 268b982ade27845dadf717a533c54e5f48130702 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Mon, 23 Nov 2026 04:36:11 +0800 Subject: [PATCH 383/393] media: honor delayed PCM starts in shared AVI (#4071) --- crates/media/src/craft_source.rs | 43 +++++++++-- .../media/src/craft_source/raw_avi_tests.rs | 74 +++++++++++++++++++ 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index 8a1363194..fe4063b46 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -599,7 +599,7 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code let den = i128::from(s.rate.max(1)); let scale = i128::from(s.scale.max(1)); if s.sample_size > 0 { - let mut acc = 0i64; + let mut acc = delayed_avi_pcm_start(s).map_or(0, |(start, _)| start); return AudioStarts::complete( s.chunks .iter() @@ -1390,6 +1390,33 @@ fn default_video_info(width: u32, height: u32, frame_rate: FrameRate, codec: &Co } } +/// A byte-timed PCM stream uses one indexed unit per interleaved sample frame. +/// Convert its stream-clock start to native samples before counting those units. +fn delayed_avi_pcm_start(stream: &avi::Stream) -> Option<(i64, u32)> { + if stream.start == 0 || stream.scale == 0 || stream.rate == 0 { + return None; + } + let wave = stream.audio.as_ref()?; + if !matches!((wave.format_tag, wave.bits_per_sample), (1, 8 | 16 | 24 | 32) | (3, 32 | 64)) { + return None; + } + let (sample_rate, channels) = filmcraft_media::bounded_audio_dimensions(wave.sample_rate, u32::from(wave.channels)).ok()?; + let packed = u32::from(wave.bits_per_sample.div_ceil(8)) * channels; + // The shared decoder consumes packed PCM. Keep the prior route when the + // indexed sample size or block padding implies a different packet clock. + if stream.sample_size != packed || u32::from(wave.block_align) > packed { + return None; + } + let start = i128::from(stream.start) * i128::from(stream.scale) * i128::from(sample_rate) / i128::from(stream.rate); + Some((i64::try_from(start).ok()?, sample_rate)) +} + +fn delayed_avi_pcm_end(stream: &avi::Stream) -> Option { + let (start, sample_rate) = delayed_avi_pcm_start(stream)?; + let end = stream.chunks.iter().fold(start, |frames, chunk| frames.saturating_add(i64::from(chunk.size / stream.sample_size))); + Some(Tick::from_units(end, i64::from(sample_rate))) +} + fn open_avi(name: &str, source: SharedBytes) -> Option> { let file = avi::open(&*source).ok()?; let video_idx = file.streams.iter().position(|s| s.kind == avi::StreamKind::Video && !s.chunks.is_empty() && s.rate > 0 && s.scale > 0); @@ -1404,22 +1431,25 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { if video_idx.is_none() && audio_candidates.is_empty() { return None; } + let delayed_audio_end = audio_candidates.iter().filter_map(|&(idx, _, _, _)| delayed_avi_pcm_end(&file.streams[idx])).max().unwrap_or(Tick::ZERO); if let Some(idx) = video_idx && let Some(raw) = RawAvi::new(&file.streams[idx]) { - // Shared AVI audio positions are relative to the first chunk. Keep the - // legacy path for a track with a separate stream start. - if audio_candidates.iter().any(|&(audio, _, _, _)| file.streams[audio].start != 0) { + if audio_candidates.iter().any(|&(audio, _, _, _)| { + let stream = &file.streams[audio]; + stream.start != 0 && delayed_avi_pcm_start(stream).is_none() + }) { return None; } let duration = audio_candidates .iter() + .filter(|&&(audio, _, _, _)| file.streams[audio].start == 0) .map(|&(audio, _, _, _)| { let s = &file.streams[audio]; Tick::from_units(i64::from(s.length).saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1))) }) - .fold(raw.duration(file.streams[idx].chunks.len()), Tick::max); + .fold(raw.duration(file.streams[idx].chunks.len()).max(delayed_audio_end), Tick::max); let video = ContainerVideoPart { track_idx: idx, info: raw.info(&file.streams[idx]), state: Mutex::new(VideoState::RawAvi(raw)) }; return finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), Some(video), duration, audio_candidates); } @@ -1453,6 +1483,7 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { } else { let duration = audio_candidates .iter() + .filter(|&&(idx, _, _, _)| delayed_avi_pcm_start(&file.streams[idx]).is_none()) .map(|(idx, _, params, _)| { let s = &file.streams[*idx]; let units = if params.codec == CodecId::Pcm && s.sample_size > 0 { @@ -1468,7 +1499,7 @@ fn open_avi(name: &str, source: SharedBytes) -> Option> { (None, duration) }; - finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), video, duration, audio_candidates) + finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), video, duration.max(delayed_audio_end), audio_candidates) } fn estimate_mpeg_frame_rate_pts(pts: impl IntoIterator) -> FrameRate { diff --git a/crates/media/src/craft_source/raw_avi_tests.rs b/crates/media/src/craft_source/raw_avi_tests.rs index 96ce62454..1dc67aead 100644 --- a/crates/media/src/craft_source/raw_avi_tests.rs +++ b/crates/media/src/craft_source/raw_avi_tests.rs @@ -97,3 +97,77 @@ fn raw_rgb_avi_with_dropped_slot_keeps_legacy_playback() -> Result<(), Box Result { + bytes.windows(12).position(|window| &window[..4] == b"strh" && &window[8..] == b"auds").map(|offset| offset + 8).ok_or("AVI audio stream header") +} + +#[test] +fn delayed_avi_pcm_keeps_raw_rgb_and_reports_the_later_audio_end() -> Result<(), Box> { + let mut bytes = fixture(24, true, false)?; + let at = audio_header(&bytes)?; + let delay = AUDIO_PER_FRAME as u32 + 13; + bytes[at + 28..at + 32].copy_from_slice(&delay.to_le_bytes()); // dwStart + bytes[at + 32..at + 36].copy_from_slice(&1u32.to_le_bytes()); // stale dwLength + + let bytes: Arc<[u8]> = bytes.into(); + let dir = tempfile::tempdir()?; + let path = dir.path().join("delayed-rgb.avi"); + std::fs::write(&path, &bytes)?; + let end = Tick::from_units(i64::from(delay) + 3 * AUDIO_PER_FRAME as i64, i64::from(AUDIO_RATE)); + for info in [crate::probe::probe(&path)?, crate::probe::probe_bytes("delayed-rgb.avi", bytes.clone())?] { + assert_eq!(info.duration.0, end.0); + assert!(info.has_audio && info.has_video); + } + let disk = stream::open_source(&path).ok_or("unrecognized AVI")?.0?; + let memory = stream::open_bytes("delayed-rgb.avi", bytes)?; + for opened in [disk, memory] { + let MediaSource::Craft(source) = opened else { panic!("delayed fixed-size PCM should stay on the shared RGB route") }; + let frame = source.video_frame(FrameRequest { time: Tick::from_units(1, i64::from(FPS)), scale: 1.0 })?; + let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected RGBA picture") }; + assert_eq!(&pixels[..4], &rgba(1, 0, 0)); + + let delay = i64::from(delay); + let after = source.audio(delay + AUDIO_PER_FRAME as i64, 2, AUDIO_RATE)?; + assert_eq!(after.channels[0], [2000.0 / 32768.0; 2]); + let first = source.audio(delay - 2, 4, AUDIO_RATE)?; + assert_eq!(first.channels[0], [0.0, 0.0, 1000.0 / 32768.0, 1000.0 / 32768.0]); + } + Ok(()) +} + +#[test] +fn delayed_avi_pcm_audio_only_uses_the_stream_clock_and_indexed_samples() -> Result<(), Box> { + let audio = avi::StreamSpec::Audio(avi::AudioSpec::pcm(AUDIO_RATE, 1, 16)); + let mut writer = avi::AviWriter::new(Cursor::new(Vec::new()), vec![audio], avi::MuxOptions::default())?; + writer.write_chunk(0, &8192i16.to_le_bytes().repeat(5), true)?; + writer.write_chunk(0, &16384i16.to_le_bytes().repeat(9), true)?; + let mut bytes = writer.finish()?.into_inner(); + let at = audio_header(&bytes)?; + // This stream clock places dwStart at 4.8 native samples, truncated to 4. + bytes[at + 20..at + 24].copy_from_slice(&1u32.to_le_bytes()); + bytes[at + 24..at + 28].copy_from_slice(&5000u32.to_le_bytes()); + bytes[at + 28..at + 32].copy_from_slice(&3u32.to_le_bytes()); + bytes[at + 32..at + 36].copy_from_slice(&200u32.to_le_bytes()); + + let bytes: Arc<[u8]> = bytes.into(); + let opened = stream::open_bytes("delayed-pcm.avi", bytes.clone())?; + let MediaSource::Craft(source) = opened else { panic!("expected shared PCM reader") }; + assert_eq!(source.audio(0, 6, AUDIO_RATE)?.channels[0], [0.0, 0.0, 0.0, 0.0, 0.25, 0.25]); + assert_eq!(source.audio(17, 2, AUDIO_RATE)?.channels[0], [0.5, 0.0]); + let info = crate::probe::probe_bytes("delayed-pcm.avi", bytes)?; + assert_eq!(info.duration.0, Tick::from_units(18, i64::from(AUDIO_RATE)).0); + Ok(()) +} + +#[test] +fn delayed_avi_pcm_with_conflicting_block_size_keeps_legacy_rgb_route() -> Result<(), Box> { + let mut bytes = fixture(24, true, false)?; + let at = audio_header(&bytes)?; + bytes[at + 28..at + 32].copy_from_slice(&16u32.to_le_bytes()); + bytes[at + 44..at + 48].copy_from_slice(&1u32.to_le_bytes()); // dwSampleSize + let opened = stream::open_bytes("delayed-pcm-block.avi", bytes.into())?; + let MediaSource::Film(source) = opened else { panic!("expected legacy PCM block alignment") }; + assert_eq!(source.audio(15, 2, AUDIO_RATE)?.channels[0], [0.0, 1000.0 / 32768.0]); + Ok(()) +} From 7e2d0256209974ffb92a29d8bdb6f2a49078f51f Mon Sep 17 00:00:00 2001 From: Terra854 Date: Mon, 23 Nov 2026 04:58:13 +0800 Subject: [PATCH 384/393] media: cover generated Motion JPEG AVI and PCM (#4069) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/media/tests/it/avi_mjpeg.rs | 67 ++++++++++++++++++++++++++++++ crates/media/tests/it/main.rs | 1 + 2 files changed, 68 insertions(+) create mode 100644 crates/media/tests/it/avi_mjpeg.rs diff --git a/crates/media/tests/it/avi_mjpeg.rs b/crates/media/tests/it/avi_mjpeg.rs new file mode 100644 index 000000000..aa25fa454 --- /dev/null +++ b/crates/media/tests/it/avi_mjpeg.rs @@ -0,0 +1,67 @@ +use std::io::Cursor; +use std::sync::Arc; + +use craft_media::avi::{AudioSpec, AviWriter, MuxOptions, StreamSpec, VideoSpec}; +use effectcraft_media::{MediaPool, probe, probe_bytes}; +use effectcraft_project::FootageKind; +use effectcraft_time::{FrameRate, Tick}; +use image::{ExtendedColorType, codecs::jpeg::JpegEncoder}; + +const SIDE: u32 = 16; +const FPS: u32 = 25; +const SAMPLE_RATE: u32 = 48_000; + +fn mjpeg_with_pcm() -> Arc<[u8]> { + let video = StreamSpec::Video(VideoSpec::new(*b"MJPG", SIDE, SIDE, FPS, 1)); + let audio = StreamSpec::Audio(AudioSpec::pcm(SAMPLE_RATE, 1, 16)); + let mut writer = AviWriter::new(Cursor::new(Vec::new()), vec![video, audio], MuxOptions::default()).expect("AVI writer"); + let samples_per_frame = (SAMPLE_RATE / FPS) as usize; + for (color, sample) in [([220_u8, 40, 30], 8_192_i16), ([30, 40, 220], -8_192)] { + let pixels = color.repeat((SIDE * SIDE) as usize); + let mut jpeg = Vec::new(); + JpegEncoder::new_with_quality(&mut jpeg, 90).encode(&pixels, SIDE, SIDE, ExtendedColorType::Rgb8).expect("JPEG picture"); + writer.write_chunk(0, &jpeg, true).expect("video chunk"); + + let pcm = sample.to_le_bytes().repeat(samples_per_frame); + writer.write_chunk(1, &pcm, true).expect("matching audio chunk"); + } + writer.finish().expect("finish AVI").into_inner().into() +} + +#[test] +fn generated_mjpeg_avi_preserves_video_seek_and_pcm_alignment() { + let bytes = mjpeg_with_pcm(); + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("native-mjpeg.avi"); + std::fs::write(&path, &bytes).expect("write AVI"); + let native = probe(&path).expect("native AVI probe"); + let name = "in-memory-mjpeg.avi"; + let memory = probe_bytes(name, bytes.clone()).expect("in-memory AVI probe"); + + for footage in [&native, &memory] { + assert_eq!(footage.kind, FootageKind::Video); + assert_eq!((footage.width, footage.height), (SIDE, SIDE)); + assert_eq!(footage.frame_rate, FrameRate::FPS_25); + assert_eq!(footage.duration, Tick::from_units(2, i64::from(FPS))); + assert_eq!(footage.codec, "Motion JPEG"); + assert!(footage.has_video && footage.has_audio); + } + + let native_pool = MediaPool::new(); + let memory_pool = MediaPool::new(); + memory_pool.add_bytes(name, bytes); + for (frame, dominant, other, sign) in [(0, 0, 2, 1.0), (1, 2, 0, -1.0), (0, 0, 2, 1.0)] { + let at = Tick::from_units(frame, i64::from(FPS)); + let native_frame = native_pool.frame_at(&native, at).expect("native picture"); + let memory_frame = memory_pool.frame_at(&memory, at).expect("in-memory picture"); + let pixel = native_frame.get(i64::from(SIDE / 2), i64::from(SIDE / 2)); + assert_eq!(pixel, memory_frame.get(i64::from(SIDE / 2), i64::from(SIDE / 2))); + assert!(pixel[dominant] > pixel[other] + 0.4, "picture at frame {frame}: {pixel:?}"); + + let native_pcm = native_pool.audio_samples(&native, at, 16, SAMPLE_RATE); + let memory_pcm = memory_pool.audio_samples(&memory, at, 16, SAMPLE_RATE); + assert_eq!(native_pcm, memory_pcm); + assert_eq!(native_pcm.len(), 32); + assert!(native_pcm.iter().all(|sample| sign * sample > 0.05), "PCM at frame {frame}: {native_pcm:?}"); + } +} diff --git a/crates/media/tests/it/main.rs b/crates/media/tests/it/main.rs index efa69b5a6..afeda890e 100644 --- a/crates/media/tests/it/main.rs +++ b/crates/media/tests/it/main.rs @@ -1,6 +1,7 @@ //! The crate's integration tests, one binary (each module is a former `tests/.rs`). mod aac_layout; +mod avi_mjpeg; mod downmix; mod exif_orientation; mod exr_golden; From 9bea8f827423ed2461d8da229e48ea0ed9dce90b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:35:24 +0700 Subject: [PATCH 385/393] chore(deps): move EffectCraft's media pins to craft-libs 33be3562 and FilmCraft e7345f6e --- Cargo.lock | 224 +++++++++++++++++++++-------------------------------- Cargo.toml | 30 +++---- 2 files changed, 105 insertions(+), 149 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5a2d2bfc9..874327c70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1182,11 +1182,11 @@ dependencies = [ [[package]] name = "craft-aaf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-cfb", - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "thiserror 2.0.21", ] @@ -1207,21 +1207,10 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "log", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-audio" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" -dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "log", "rayon", "symphonia 0.6.1", @@ -1231,7 +1220,7 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-cms" @@ -1250,7 +1239,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", ] @@ -1277,7 +1266,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-dpx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1285,7 +1274,7 @@ dependencies = [ [[package]] name = "craft-dpx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "thiserror 2.0.21", ] @@ -1305,6 +1294,15 @@ name = "craft-eps" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" +[[package]] +name = "craft-exr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +dependencies = [ + "flate2", + "serde_json", +] + [[package]] name = "craft-exr" version = "0.1.0" @@ -1317,15 +1315,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-exr" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8b40f1a4b0718916e7c136c1b91b38a5c7531a0e#8b40f1a4b0718916e7c136c1b91b38a5c7531a0e" -dependencies = [ - "flate2", - "serde_json", -] - [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1334,10 +1323,10 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-frame" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-color", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "rayon", "serde", ] @@ -1354,7 +1343,7 @@ dependencies = [ [[package]] name = "craft-hdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1385,7 +1374,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1416,16 +1405,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9 [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" -dependencies = [ - "chrono", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-media" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", "thiserror 2.0.21", @@ -1434,13 +1414,13 @@ dependencies = [ [[package]] name = "craft-media-source" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-color", "craft-frame", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "serde", "thiserror 2.0.21", ] @@ -1500,7 +1480,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189#53198114310dbc2b41e18e4eaf2fd83e69964189" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "encoding_rs", "flate2", @@ -1511,7 +1491,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189#53198114310dbc2b41e18e4eaf2fd83e69964189" dependencies = [ "encoding_rs", "flate2", @@ -1533,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-tiff", "miniz_oxide 0.9.1", @@ -1544,6 +1524,11 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "craft-sniff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" + [[package]] name = "craft-svg" version = "0.1.0" @@ -1562,7 +1547,7 @@ dependencies = [ [[package]] name = "craft-tga" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1570,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", "thiserror 2.0.21", @@ -1588,16 +1573,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-time" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", "thiserror 2.0.21", @@ -1614,10 +1590,10 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "serde", "serde_json", ] @@ -1684,20 +1660,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "rav1e", - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-video" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" -dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "rav1e", "rayon", "thiserror 2.0.21", @@ -1712,6 +1677,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1722,30 +1697,10 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "craft-y4m" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -2123,11 +2078,11 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-video", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -2289,17 +2244,17 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-color", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-frame", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-media-source", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-video", "craft-webp", "effectcraft-color", "effectcraft-effects", @@ -2998,15 +2953,15 @@ dependencies = [ [[package]] name = "filmcraft-bitstream" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] name = "filmcraft-cfb" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "craft-cfb", ] @@ -3014,12 +2969,12 @@ dependencies = [ [[package]] name = "filmcraft-codecs" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-jpeg", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-video", "craft-y4m", "filmcraft-bitstream", "filmcraft-color", @@ -3038,7 +2993,7 @@ dependencies = [ [[package]] name = "filmcraft-color" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "serde", ] @@ -3046,7 +3001,7 @@ dependencies = [ [[package]] name = "filmcraft-dng" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "craft-raw", "craft-tiff", @@ -3058,7 +3013,7 @@ dependencies = [ [[package]] name = "filmcraft-frame" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -3069,7 +3024,7 @@ dependencies = [ [[package]] name = "filmcraft-geom" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "serde", ] @@ -3077,11 +3032,11 @@ dependencies = [ [[package]] name = "filmcraft-interchange" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "craft-aaf", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "filmcraft-cfb", "filmcraft-color", "filmcraft-geom", @@ -3097,31 +3052,32 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] name = "filmcraft-matroska" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] name = "filmcraft-media" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8b40f1a4b0718916e7c136c1b91b38a5c7531a0e)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-hdr", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-media-source", - "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-sniff", "craft-tga", "craft-tiff", "filmcraft-color", @@ -3137,7 +3093,7 @@ dependencies = [ [[package]] name = "filmcraft-project" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "filmcraft-color", "filmcraft-geom", @@ -3152,9 +3108,9 @@ dependencies = [ [[package]] name = "filmcraft-time" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1dbbffffd..627ea1365 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,25 +97,25 @@ same-file = "1.0" tempfile = "3.27" # codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", default-features = false, features = ["isobmff", "matroska"] } -craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["isobmff", "matroska"] } +craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # 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 = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } # timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only) -filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } # gpu (the same wgpu eframe / egui-wgpu use) wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] } From 38624ac67e646102a8cba66d45c06f058da71626 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:38:10 +0700 Subject: [PATCH 386/393] export: write Targa sequences through craft-tga (craft-libs#778) Use craft_tga::write_top_left_raw from craft-libs#3076, which shares the footerless, uncompressed top-left stream this export wrote with the image crate's encoder. --- Cargo.lock | 1 + Cargo.toml | 1 + crates/export/Cargo.toml | 1 + crates/export/src/lib.rs | 13 ++++++++++--- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 874327c70..e87881ec5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2082,6 +2082,7 @@ dependencies = [ "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-gif", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-tga", "craft-video", "effectcraft-color", "effectcraft-effects", diff --git a/Cargo.toml b/Cargo.toml index 627ea1365..376772e5b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,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 = "068e079c7be4b100a8a6b305b31ac881e069727e", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } +craft-tga = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "53198114310dbc2b41e18e4eaf2fd83e69964189" } craft-codepage = { 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 = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index 6b93a8a7c..a810d21c2 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -18,6 +18,7 @@ craft-video = { workspace = true } craft-audio = { workspace = true } craft-media = { workspace = true } craft-gif = { workspace = true } +craft-tga = { workspace = true } craft-exr = { workspace = true, features = ["decode"] } image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] } rayon = { workspace = true } diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 16d65fabe..b89acbbab 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -413,9 +413,16 @@ fn write_still(cx: &Cx, file: &mut W, img: &I }; match fmt { OutputFormat::PngSequence => image::codecs::png::PngEncoder::new(file).write_image(&data, w, h, ct), - // Uncompressed (the encoder's run-length compression is off), top-left origin, the - // alpha bits in the image descriptor: 8 for RGB + Alpha, 0 otherwise. - OutputFormat::TargaSequence => image::codecs::tga::TgaEncoder::new(file).disable_rle().write_image(&data, w, h, ct), + // The shared footerless writer: uncompressed, top-left origin, the alpha bits in the + // image descriptor: 8 for RGB + Alpha, 0 otherwise. + OutputFormat::TargaSequence => { + let layout = match channels { + Channels::Rgba => craft_tga::Layout::Rgba, + Channels::Alpha => craft_tga::Layout::Gray, + Channels::Rgb => craft_tga::Layout::Rgb, + }; + return craft_tga::write_top_left_raw(file, w, h, layout, &data).map_err(|e| ExportError::Encode(e.to_string())); + } // (the TIFF encoder needs Seek) _ => image::codecs::tiff::TiffEncoder::new(file).write_image(&data, w, h, ct), } From 0ab43ebd680e75500555ae36f0ceaa1905c26729 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:40:23 +0700 Subject: [PATCH 387/393] media: open YUV4MPEG2 through the shared craft-media-source reader --- Cargo.lock | 1 + crates/media/Cargo.toml | 2 +- crates/media/src/craft_source.rs | 146 ++++++++++++++++++++++++------- crates/media/src/stream.rs | 2 +- 4 files changed, 119 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 874327c70..e3dc8cbb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1421,6 +1421,7 @@ dependencies = [ "craft-frame", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-y4m", "serde", "thiserror 2.0.21", ] diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 6a2ddcfdd..c23ceeb05 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -31,7 +31,7 @@ craft-audio = { workspace = true, features = ["decode-native", "aac-decode", "al craft-color = { workspace = true } craft-frame = { workspace = true } craft-media = { workspace = true, features = ["mpegts", "avi", "mxf"] } -craft-media-source = { workspace = true } +craft-media-source = { workspace = true, features = ["y4m"] } craft-time = { workspace = true } craft-video = { workspace = true, features = ["h264-decode", "hevc-decode", "vp9-decode", "vp8-decode", "av1-decode", "prores", "dnx", "mpeg2-decode", "ffv1", "apv-decode", "threads"] } filmcraft-frame = { workspace = true } diff --git a/crates/media/src/craft_source.rs b/crates/media/src/craft_source.rs index fe4063b46..4459ac129 100644 --- a/crates/media/src/craft_source.rs +++ b/crates/media/src/craft_source.rs @@ -1,39 +1,33 @@ -//! ISO-BMFF (MP4/MOV/M4A) and Matroska/WebM (MKV/MKA/WebM) media-reader routes backed by -//! `craft-media`, `craft-video`, `craft-audio`, and `craft-media-source`. +//! ISO-BMFF (MP4/MOV/M4A), Matroska/WebM (MKV/MKA/WebM), MXF, AVI, MPEG-TS/PS, YUV4MPEG2 and +//! standalone audio 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. //! //! ## Route Matrix (`crates/media`) -//! - **ISO-BMFF (`MP4`/`MOV`/`M4A`, video+audio & audio-only)**: -//! - Shared (`craft-media::isobmff` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, -//! `Vp9`, `Vp8`, `ProRes` (coded alpha via `craft_video::prores::probe`, #3999), `Dnxhd`, -//! `Mpeg2Video`, and strictly admitted video-only `Apv` MP4; -//! audio `Aac`, `Alac`, `Flac`, `Opus`, `Ac3`, `Mp3`/`Mp2`/`Mp1`. -//! - Fallback (`filmcraft-codecs`): `Mjpeg`, `Mpeg4Video`, `Ffv1`, other `Apv`, or unsupported audio. -//! - **Matroska / WebM (`MKV`/`MKA`/`WebM`, video+audio & audio-only)**: -//! - Shared (`craft-media::matroska` + `craft-video` + `craft-audio`): `H264`, `Hevc`, `Av1`, -//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; audio `Aac`, `Alac`, `Flac`, `Opus`, `Ac3`, -//! `Mp3`/`Mp2`/`Mp1` (with `CodecDelay` + `SeekPreRoll` timing). -//! - Fallback (`filmcraft-codecs`): `alpha_mode == 1` (`BlockAdditional` alpha), unreadable/zlib -//! encodings, `Mjpeg`/`Ffv1`/`Theora`/`Apv`, or unsupported audio (`Vorbis`/`Pcm`). -//! - **MXF (`MXF`, video+audio & audio-only OP1a/OP-Atom)**: -//! - Shared (`craft-media::mxf` + `craft-video` + `MxfFile::read_pcm`): `H264`, `Hevc`, `Av1`, -//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video`; sound `Pcm` and `Aes3` (D-10). -//! - Fallback (`filmcraft-codecs`): compressed MXF sound or unsupported video codecs. -//! - **AVI / MPEG-TS / MPEG-PS**: -//! - Shared (`craft-media::avi`, `craft-media::mpegts` + `craft-video` + `craft-audio`): -//! `H264`, `Hevc`, `Mpeg2Video`, `Av1`, `Vp9`, `Vp8`, `ProRes`, `Dnxhd`; audio `Aac`, -//! `Ac3`/`Eac3`, `Mp3`/`Mp2`/`Mp1`, `Pcm`. AVI also accepts complete 24/32-bit `BI_RGB` streams. -//! - Fallback (`filmcraft-codecs`): unsupported codecs (`Mjpeg`, `Mpeg4Video`, `Ffv1`, `Theora`, -//! `Apv`, other raw AVI layouts) or unsupported audio. -//! - **Other containers & standalone audio**: -//! - Shared (`craft_audio::Decoder` with `decode-native`): standalone `WAV`, `AIFF`, `MP3`/`MP2`/`MP1`, -//! `AAC` (ADTS), `AC-3`, and `Ogg` (`Opus`). Bounded standalone FLAC uses the shared native -//! FLAC decoder and the same resampling policy. -//! - Fallback (`filmcraft-codecs`): `Ogg Vorbis`, `CAF`, or FLAC and WAV/AIFF input the shared -//! readers decline. +//! Video codecs admitted by [`supports_video_codec`] in every container: `H264`, `Hevc`, `Av1`, +//! `Vp9`, `Vp8`, `ProRes`, `Dnxhd`, `Mpeg2Video` and `Ffv1`. Audio goes through +//! `craft_audio::TrackDecoder` whenever it accepts the track (including `Pcm`); a track it declines +//! sends the whole file to `filmcraft-codecs`. +//! - **ISO-BMFF (`MP4`/`MOV`/`M4A`)**: shared, plus strictly admitted video-only `Apv` MP4. +//! Fallback: `Mjpeg`, `Mpeg4Video`, other `Apv`, or declined audio. +//! - **Matroska / WebM (`MKV`/`MKA`/`WebM`)**: shared, with `CodecDelay` + `SeekPreRoll` timing. +//! Fallback: `alpha_mode == 1` (`BlockAdditional` alpha), unreadable or compressed frame +//! encodings, `V_FFV1` without `CodecPrivate`, `Mjpeg`/`Theora`/`Apv`, or declined audio +//! (for example `Vorbis`). +//! - **MXF (OP1a/OP-Atom)**: shared, with sound `Pcm` and `Aes3` (D-10) read by +//! `MxfFile::read_pcm`. Fallback: compressed sound, video that needs reordering, or other codecs. +//! - **AVI / MPEG-TS / MPEG-PS**: shared; AVI also accepts complete 24/32-bit `BI_RGB` streams. +//! Fallback: other codecs (`Mjpeg`, `Mpeg4Video`, `Theora`, `Apv`), other raw AVI layouts, or +//! declined audio. +//! - **YUV4MPEG2 (`Y4M`)**: `craft_media_source::y4m`. Fallback: files it reports as unsupported +//! (for example a frame above the shared media buffer limit). +//! - **Standalone audio**: `craft_audio::Decoder` with `decode-native` for `WAV`, `AIFF`, +//! `MP3`/`MP2`/`MP1`, `AAC` (ADTS), `AC-3` and `Ogg` (`Opus`); bounded FLAC uses the shared +//! native FLAC decoder. Fallback: `Ogg Vorbis`, `CAF`, or FLAC and WAV/AIFF input the shared +//! readers decline. use std::sync::{Arc, Mutex}; @@ -138,6 +132,9 @@ pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Opti if let Some(fmt) = mpegts::sniff(usual_head) { return open_mpeg(name, fmt, reader.clone()); } + if craft_media_source::y4m::sniff(usual_head) { + return open_y4m(name, reader.clone()); + } if let Some(source) = standalone_flac::open_reader(name, usual_head, reader) { return Some(Ok(source)); } @@ -161,6 +158,9 @@ pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option) -> Option Option> { + match craft_media_source::y4m::Y4mSource::open(name, source) { + Ok(y4m) => Some(Ok(Arc::new(y4m))), + Err(MediaError::Unsupported(_)) => None, + Err(e) => Some(Err(e)), + } +} + enum ContainerFile { Isobmff(Mp4File), Matroska(Box), @@ -3086,6 +3096,82 @@ mod tests { } } + /// Two distinct self-generated pictures of `colour` (`W4 H2`), 16-bit little-endian above 8 bits. + fn generated_y4m(colour: &str, bits: u8, planes: usize, chroma_len: usize) -> Arc<[u8]> { + let mut out = format!("YUV4MPEG2 W4 H2 F25:1 Ip A2:1 C{colour} XCOLORRANGE=FULL\n").into_bytes(); + for frame in 0..2u16 { + out.extend_from_slice(b"FRAME\n"); + for plane in 0..planes { + let len = if plane == 0 || plane == 3 { 8 } else { chroma_len }; + for i in 0..len as u16 { + let v = (frame * 97 + plane as u16 * 31 + i * 13) % (1 << bits.min(10)); + if bits > 8 { + out.extend_from_slice(&v.to_le_bytes()); + } else { + out.push(v as u8); + } + } + } + } + out.into() + } + + #[test] + fn y4m_import_uses_the_shared_source_with_film_parity() { + use crate::stream::{DecodedFrame, MediaSource as Opened}; + + fn planes(frame: DecodedFrame) -> (Vec>, Option>, u32) { + let wide = |p: &[u8]| p.iter().map(|&v| u16::from(v)).collect::>(); + match frame { + DecodedFrame::Craft(f) => match &f.data { + PixelData::Yuv8 { planes, alpha, .. } => (planes.iter().map(|p| wide(p)).collect(), alpha.as_ref().map(|a| wide(a)), 8u32), + PixelData::Yuv16 { planes, alpha, bits, .. } => (planes.iter().map(|p| p.to_vec()).collect(), alpha.as_ref().map(|a| a.to_vec()), *bits), + _ => panic!("shared Y4M frame is planar YUV"), + }, + DecodedFrame::Film(f) => match &f.data { + filmcraft_frame::PixelData::Yuv8 { planes, alpha, .. } => (planes.iter().map(|p| wide(p)).collect(), alpha.as_ref().map(|a| wide(a)), 8u32), + filmcraft_frame::PixelData::Yuv16 { planes, alpha, bits, .. } => { + (planes.iter().map(|p| p.to_vec()).collect(), alpha.as_ref().map(|a| a.to_vec()), *bits) + } + _ => panic!("legacy Y4M frame is planar YUV"), + }, + } + } + + let step = craft_time::TICKS_PER_SECOND / 25; + for (colour, bits, plane_count, chroma_len) in + [("420jpeg", 8, 3, 2), ("444alpha", 8, 4, 8), ("mono", 8, 1, 0), ("420p10", 10, 3, 2), ("422p12", 12, 3, 4)] + { + let bytes = generated_y4m(colour, bits, plane_count, chroma_len); + let path = "generated.y4m"; + let shared = crate::stream::open_bytes(path, bytes.clone()).unwrap(); + assert!(matches!(shared, Opened::Craft(_)), "{colour}: Y4M must use the shared source"); + let direct = filmcraft_codecs::open_bytes(path, bytes.clone()).unwrap(); + let old = crate::probe::footage_from_info(path, direct.info()); + let film = Opened::Film(direct); + let footage = crate::probe_bytes(path, bytes.clone()).unwrap(); + assert_eq!((footage.width, footage.height), (4, 2), "{colour}"); + assert_eq!(footage.frame_rate, old.frame_rate, "{colour}"); + assert_eq!(footage.duration, old.duration, "{colour}"); + assert_eq!(footage.duration.0, step * 2, "{colour}"); + assert_eq!(footage.pixel_aspect, old.pixel_aspect, "{colour}"); + assert_eq!(footage.alpha, old.alpha, "{colour}"); + assert_eq!(footage.color_profile, old.color_profile, "{colour}"); + assert_eq!(footage.codec, old.codec, "{colour}"); + let mut seen = Vec::new(); + for at in [step, 0, step - 1, step, 0] { + let time = effectcraft_time::Tick(at); + let new = planes(shared.video_frame(time, 1.0).unwrap()); + let legacy = planes(film.video_frame(time, 1.0).unwrap()); + assert_eq!(new, legacy, "{colour} at {at}"); + assert_eq!(new.2, u32::from(bits), "{colour}"); + assert_eq!(new.1.is_some(), colour == "444alpha", "{colour}"); + seen.push(new.0); + } + assert_ne!(seen[0], seen[1], "{colour}: the two pictures differ"); + } + } + #[test] fn simple_apv_mp4_import_preserves_film_color_alpha_and_backward_seek() { use crate::stream::MediaSource as Opened; diff --git a/crates/media/src/stream.rs b/crates/media/src/stream.rs index d349a2c86..0de9b427b 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 -/// (ISO-BMFF and Matroska/WebM with supported codecs) and `filmcraft-media` for remaining formats. +/// (the route matrix in `craft_source`) and `filmcraft-media` for remaining formats. #[derive(Clone)] pub(crate) enum MediaSource { Craft(craft_media_source::SharedSource), From d7c7d0d737527c35e1b41378ab37641217729e87 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:48:11 +0700 Subject: [PATCH 388/393] chore(deps): move EffectCraft's media pins to craft-libs 33be3562 and FilmCraft e7345f6e (#4104) --- Cargo.lock | 224 +++++++++++++++++++++-------------------------------- Cargo.toml | 30 +++---- 2 files changed, 105 insertions(+), 149 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5a2d2bfc9..874327c70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1182,11 +1182,11 @@ dependencies = [ [[package]] name = "craft-aaf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-cfb", - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "thiserror 2.0.21", ] @@ -1207,21 +1207,10 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "log", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-audio" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" -dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "log", "rayon", "symphonia 0.6.1", @@ -1231,7 +1220,7 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" [[package]] name = "craft-cms" @@ -1250,7 +1239,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", ] @@ -1277,7 +1266,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-dpx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1285,7 +1274,7 @@ dependencies = [ [[package]] name = "craft-dpx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "thiserror 2.0.21", ] @@ -1305,6 +1294,15 @@ name = "craft-eps" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" +[[package]] +name = "craft-exr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +dependencies = [ + "flate2", + "serde_json", +] + [[package]] name = "craft-exr" version = "0.1.0" @@ -1317,15 +1315,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-exr" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8b40f1a4b0718916e7c136c1b91b38a5c7531a0e#8b40f1a4b0718916e7c136c1b91b38a5c7531a0e" -dependencies = [ - "flate2", - "serde_json", -] - [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1334,10 +1323,10 @@ source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c [[package]] name = "craft-frame" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-color", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "rayon", "serde", ] @@ -1354,7 +1343,7 @@ dependencies = [ [[package]] name = "craft-hdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1385,7 +1374,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1416,16 +1405,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9 [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" -dependencies = [ - "chrono", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-media" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "chrono", "thiserror 2.0.21", @@ -1434,13 +1414,13 @@ dependencies = [ [[package]] name = "craft-media-source" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-color", "craft-frame", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "serde", "thiserror 2.0.21", ] @@ -1500,7 +1480,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189#53198114310dbc2b41e18e4eaf2fd83e69964189" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "encoding_rs", "flate2", @@ -1511,7 +1491,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189#53198114310dbc2b41e18e4eaf2fd83e69964189" dependencies = [ "encoding_rs", "flate2", @@ -1533,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "craft-tiff", "miniz_oxide 0.9.1", @@ -1544,6 +1524,11 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "craft-sniff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" + [[package]] name = "craft-svg" version = "0.1.0" @@ -1562,7 +1547,7 @@ dependencies = [ [[package]] name = "craft-tga" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -1570,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", "thiserror 2.0.21", @@ -1588,16 +1573,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" -dependencies = [ - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-time" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "serde", "thiserror 2.0.21", @@ -1614,10 +1590,10 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "serde", "serde_json", ] @@ -1684,20 +1660,9 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "rav1e", - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-video" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" -dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "rav1e", "rayon", "thiserror 2.0.21", @@ -1712,6 +1677,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1722,30 +1697,10 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6#6a061a30bdd4a6cc24329334d5e44241896edba6" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "craft-y4m" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17#dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17" +source = "git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d#33be35625e252cc4f06aa375b3b428521faea37d" dependencies = [ "thiserror 2.0.21", ] @@ -2123,11 +2078,11 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-video", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -2289,17 +2244,17 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-color", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "craft-frame", "craft-gif", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-media-source", - "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6a061a30bdd4a6cc24329334d5e44241896edba6)", + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-video", "craft-webp", "effectcraft-color", "effectcraft-effects", @@ -2998,15 +2953,15 @@ dependencies = [ [[package]] name = "filmcraft-bitstream" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] name = "filmcraft-cfb" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "craft-cfb", ] @@ -3014,12 +2969,12 @@ dependencies = [ [[package]] name = "filmcraft-codecs" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-jpeg", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-video", "craft-y4m", "filmcraft-bitstream", "filmcraft-color", @@ -3038,7 +2993,7 @@ dependencies = [ [[package]] name = "filmcraft-color" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "serde", ] @@ -3046,7 +3001,7 @@ dependencies = [ [[package]] name = "filmcraft-dng" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "craft-raw", "craft-tiff", @@ -3058,7 +3013,7 @@ dependencies = [ [[package]] name = "filmcraft-frame" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -3069,7 +3024,7 @@ dependencies = [ [[package]] name = "filmcraft-geom" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "serde", ] @@ -3077,11 +3032,11 @@ dependencies = [ [[package]] name = "filmcraft-interchange" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "craft-aaf", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "filmcraft-cfb", "filmcraft-color", "filmcraft-geom", @@ -3097,31 +3052,32 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] name = "filmcraft-matroska" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] name = "filmcraft-media" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", - "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8b40f1a4b0718916e7c136c1b91b38a5c7531a0e)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-hdr", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-media-source", - "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", + "craft-sniff", "craft-tga", "craft-tiff", "filmcraft-color", @@ -3137,7 +3093,7 @@ dependencies = [ [[package]] name = "filmcraft-project" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ "filmcraft-color", "filmcraft-geom", @@ -3152,9 +3108,9 @@ dependencies = [ [[package]] name = "filmcraft-time" version = "0.20.1" -source = "git+https://github.com/storytold/filmcraft?rev=d6cc257f55e83b16af4be6bf9c371e6798f00af6#d6cc257f55e83b16af4be6bf9c371e6798f00af6" +source = "git+https://github.com/storytold/filmcraft?rev=e7345f6e04a9bb921c2613a6aa92d162edf39b3b#e7345f6e04a9bb921c2613a6aa92d162edf39b3b" dependencies = [ - "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1dbbffffd..627ea1365 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,25 +97,25 @@ same-file = "1.0" tempfile = "3.27" # codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", default-features = false, features = ["isobmff", "matroska"] } -craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6" } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6a061a30bdd4a6cc24329334d5e44241896edba6", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["isobmff", "matroska"] } +craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d" } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # 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 = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } # timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only) -filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } -filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d6cc257f55e83b16af4be6bf9c371e6798f00af6" } +filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } +filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "e7345f6e04a9bb921c2613a6aa92d162edf39b3b" } # gpu (the same wgpu eframe / egui-wgpu use) wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] } From 47391863accb86a7556bac0b61b70711bda3209c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 09:33:40 -0500 Subject: [PATCH 389/393] ci(release): forward ARTCRAFT_SERVICES_DISPATCH_TOKEN secret (#4112) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ffbe49afb..b38c3d2b8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -54,3 +54,4 @@ jobs: AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} From e17252b8a3ec6c34cffa494b96801e3978d39fc9 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 23 Nov 2026 10:12:34 -0600 Subject: [PATCH 390/393] fix(gpu): bring the colour kernel's cold compile time back to release level (#4111) The fixed 32-step searches from 3678cc9be and f0a5783a8 were unrolled at every inlined call, so software Vulkan drivers took long enough compiling fxl_point to miss the 10 s readback deadline. Each search now has one call site and runs a host-computed trip count that is the same for every invocation: still bounded, non-divergent and without dynamic lane writes. --- crates/gpu/src/fx_lut.rs | 64 ++++++++++++++++++++++++++++-- crates/gpu/src/shaders/fx_lut.wgsl | 45 ++++++++++++++------- 2 files changed, 91 insertions(+), 18 deletions(-) diff --git a/crates/gpu/src/fx_lut.rs b/crates/gpu/src/fx_lut.rs index cf8df08d6..532679c0e 100644 --- a/crates/gpu/src/fx_lut.rs +++ b/crates/gpu/src/fx_lut.rs @@ -37,16 +37,29 @@ pub(crate) const IDS: &[&str] = &[ /// Largest LUT the kernels take (floats in the storage buffer); bigger ones render on the CPU. const MAX_FLOATS: usize = 1 << 24; +/// Most halvings the kernel's partition searches run (`fxl_search_steps` caps the count there). +const SHADER_MAX_STEPS: u32 = 32; + +/// Halvings a partition search over `n` entries runs: `n`'s bit length, which every search +/// finishes within, plus one to spare. +const fn search_steps(n: usize) -> u32 { + usize::BITS - n.leading_zeros() + 1 +} + +// A program's tables fit in MAX_FLOATS floats, so none needs more halvings than the kernel runs. +const _: () = assert!(search_steps(MAX_FLOATS) <= SHADER_MAX_STEPS); + /// Run effect `id` (one of [`IDS`]); `None` = this parameter combination runs on the CPU. pub(crate) fn apply(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option { let (ops, straight) = effectcraft_effects::color_program(id, ctx)?; if ops.is_empty() { return Some(b); } - let data = encode(&ops)?; + let (data, steps) = encode(&ops)?; let buf = e.data(&data); let mut p = Params::default(); p.u[0][0] = (straight == Straight::Divide) as u32; + p.u[0][1] = steps; let out = e.scratch(b.img.width, b.img.height); e.pixels("fxl_point", &p, &b.img, None, &out, Some(&buf)); Some(GBuf { img: out, ..b }) @@ -79,11 +92,13 @@ pub(crate) fn push_lut(d: &mut Vec, lut: &Lut) -> f32 { at } -/// Program layout: a stream of (opcode, arguments…) ending in 0, followed by LUT data. -fn encode(ops: &[ColorOp]) -> Option> { +/// Program layout: a stream of (opcode, arguments…) ending in 0, followed by LUT data; and the +/// halvings the kernel's partition searches need for this program's tables. +fn encode(ops: &[ColorOp]) -> Option<(Vec, u32)> { if ops.len() > MAX_OPS { return None; } + let mut steps = 0; let mut prog: Vec = vec![]; let mut tables: Vec> = vec![]; // LUT offsets are patched once the program's length is known. @@ -142,6 +157,13 @@ fn encode(ops: &[ColorOp]) -> Option> { prog.extend(lo.iter().chain(hi)); } ColorOp::Lut { lut, shaper, interp, inverse } => { + // The kernel searches an inverted 1D table and every shaper channel. + if *inverse && lut.n3 == 0 { + steps = steps.max(search_steps(lut.n1)); + } + for channel in shaper.iter().flat_map(|s| s.iter()) { + steps = steps.max(search_steps(channel.len())); + } prog.extend([8.0, 0.0, *interp as f32, *inverse as u32 as f32, -1.0]); let mut t = vec![]; push_lut(&mut t, lut); @@ -179,5 +201,39 @@ fn encode(ops: &[ColorOp]) -> Option> { for t in tables { prog.extend(t); } - Some(prog) + Some((prog, steps)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The kernel's partition search (fxl_shape, fxl_inv_1d) run for `steps` halvings over the + /// sorted table 0, 1, …, n - 1: the index of the first entry not below `x`. + fn search(n: usize, steps: u32, x: f64) -> usize { + let (mut lo, mut hi) = (0, n); + for _ in 0..steps { + if lo < hi { + let mid = lo + (hi - lo) / 2; + if (mid as f64) < x { + lo = mid + 1; + } else { + hi = mid; + } + } + } + lo + } + + #[test] + fn search_steps_finish_every_partition_search() { + for n in [1, 2, 3, 4, 5, 255, 256, 257, 1 << 16, (1 << 16) + 1, MAX_FLOATS / 3, MAX_FLOATS] { + let steps = search_steps(n); + assert!(steps <= SHADER_MAX_STEPS, "{n} entries need more halvings than the kernel runs"); + for x in [-1.0, 0.0, 0.5, n as f64 / 3.0 + 0.5, n as f64 - 1.5, n as f64 - 0.5, n as f64 + 1.0] { + let want = (x.ceil().max(0.0) as usize).min(n); + assert_eq!(search(n, steps, x), want, "{n} entries, target {x}"); + } + } + } } diff --git a/crates/gpu/src/shaders/fx_lut.wgsl b/crates/gpu/src/shaders/fx_lut.wgsl index f9081f834..b4d51a0ad 100644 --- a/crates/gpu/src/shaders/fx_lut.wgsl +++ b/crates/gpu/src/shaders/fx_lut.wgsl @@ -120,6 +120,14 @@ fn mix_exact(a: vec3, b: vec3, t: f32) -> vec3 { return a + (b - a) * t; } +// Halvings for the partition searches (fxl_shape, fxl_inv_1d): written per dispatch by fx_lut.rs +// (enough for the largest table the program searches) and capped here. Every invocation runs the +// same count, so the loops stay bounded and non-divergent, but because the count isn't known when +// the shader is compiled, a software driver doesn't unroll every search into the kernel. +fn fxl_search_steps() -> u32 { + return min(P.u[0].y, 32u); +} + // ocio::shape over `n` (x, y) points at `at` (`flip`: the curve with x and y swapped). fn fxl_shape(at: u32, n: u32, x: f32, flip: bool) -> f32 { if (n < 2u) { @@ -130,8 +138,8 @@ fn fxl_shape(at: u32, n: u32, x: f32, flip: bool) -> f32 { // partition_point(|p| p.x < x). var lo = 0u; var hi = n; - // Bound the partition search as for inverse 1D LUTs below. - for (var step = 0u; step < 32u; step++) { + // Bounded as for inverse 1D LUTs below. + for (var step = 0u; step < fxl_search_steps(); step++) { if (lo < hi) { let mid = lo + (hi - lo) / 2u; if (data[at + mid * 2u + kx] < x) { @@ -161,14 +169,17 @@ fn fxl_shaper_at(s: u32, k: u32) -> vec2 { // Evaluate independent shaper channels without dynamically writing vector lanes. fn fxl_shaper_apply(sh: u32, c: vec3, flip: bool) -> vec3 { - let r = fxl_shaper_at(sh, 0u); - let g = fxl_shaper_at(sh, 1u); - let b = fxl_shaper_at(sh, 2u); - return vec3( - fxl_shape(r.x, r.y, c.x, flip), - fxl_shape(g.x, g.y, c.y, flip), - fxl_shape(b.x, b.y, c.z, flip) - ); + // One search per kernel instead of three: a software driver unrolls each fixed-length + // search, so every extra call multiplies compile time. Lanes are read and written with + // select(), never by a dynamic index. + var r = c; + for (var k = 0u; k < 3u; k++) { + let lane = vec3(k == 0u, k == 1u, k == 2u); + let a = fxl_shaper_at(sh, k); + let v = fxl_shape(a.x, a.y, select(select(c.z, c.y, k == 1u), c.x, k == 0u), flip); + r = select(r, vec3(v), lane); + } + return r; } fn fxl_file_fwd(o: u32, sh: i32, c0: vec3, interp: u32) -> vec3 { @@ -188,9 +199,10 @@ fn fxl_inv_1d(o: u32, i: u32, y: f32) -> f32 { // partition_point over the table's values. var lo = 0u; var hi = n; - // A u32 interval needs at most 32 halvings. A fixed trip count avoids - // a divergent data-dependent loop on software Vulkan without changing lookup. - for (var step = 0u; step < 32u; step++) { + // fxl_search_steps() halvings cover every table this program searches. A trip count shared + // by every invocation avoids a divergent data-dependent loop on software Vulkan without + // changing lookup. + for (var step = 0u; step < fxl_search_steps(); step++) { if (lo < hi) { let mid = lo + (hi - lo) / 2u; if (data[b1 + mid * 3u + i] < y) { @@ -218,7 +230,12 @@ fn fxl_file(o: u32, sh: i32, c: vec3, interp: u32, inverse: bool) -> vec3 1u) { - x = vec3(fxl_inv_1d(o, 0u, c.x), fxl_inv_1d(o, 1u, c.y), fxl_inv_1d(o, 2u, c.z)); + // One search call for all three channels, as in fxl_shaper_apply. + for (var k = 0u; k < 3u; k++) { + let lane = vec3(k == 0u, k == 1u, k == 2u); + let v = fxl_inv_1d(o, k, select(select(c.z, c.y, k == 1u), c.x, k == 0u)); + x = select(x, vec3(v), lane); + } } if (sh >= 0) { x = fxl_shaper_apply(u32(sh), x, true); From 53f1312448b9d87ddf9d4ec7ce62112a02da6fa9 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 23 Nov 2026 11:07:49 -0600 Subject: [PATCH 391/393] fix(media): queue source decode roots before entering Rayon (#4074) (#4110) --- crates/media/src/pool.rs | 163 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 153 insertions(+), 10 deletions(-) diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 041b235db..f8c596189 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -554,7 +554,68 @@ impl Sources { /// 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`), with the file's identity as /// opened. -type SourceSlot = Arc, ReadFile)>>; +type SourceSlot = Arc; + +#[derive(Default)] +struct Source { + opened: OnceLock<(Option, ReadFile)>, + #[cfg(not(target_arch = "wasm32"))] + dispatch: Mutex, +} + +#[cfg(not(target_arch = "wasm32"))] +type DecodeJob = Box; + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Dispatch { + active: bool, + pending: VecDeque, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Source { + fn enqueue(self: &Arc, workers: &'static rayon::ThreadPool, job: DecodeJob) { + let mut dispatch = lock(&self.dispatch); + if dispatch.active { + dispatch.pending.push_back(job); + return; + } + dispatch.active = true; + drop(dispatch); + self.start(workers, job); + } + + fn start(self: &Arc, workers: &'static rayon::ThreadPool, job: DecodeJob) { + let source = self.clone(); + workers.spawn_fifo(move || { + // Release on errors and unwinding too. Never hold the dispatch lock during a decode. + let _permit = DecodePermit { source, workers }; + job(); + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct DecodePermit { + source: SourceSlot, + workers: &'static rayon::ThreadPool, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for DecodePermit { + fn drop(&mut self) { + let mut dispatch = lock(&self.source.dispatch); + let next = dispatch.pending.pop_front(); + if next.is_none() { + dispatch.active = false; + } + drop(dispatch); + if let Some(job) = next { + self.source.start(self.workers, job); + } + } +} /// An opened movie/audio source, the turn its picture is shown with and the order its decoded /// audio channels arrive in. @@ -1198,7 +1259,11 @@ impl Inner { /// 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).slot(path); - let (opened, file) = slot.get_or_init(|| self.open(path)); + self.opened_in(path, &slot) + } + + fn opened_in(&self, path: &Arc, slot: &SourceSlot) -> Option { + let (opened, file) = slot.opened.get_or_init(|| self.open(path)); reads::note(file.clone()); opened.clone() } @@ -1634,6 +1699,10 @@ impl Inner { /// (wasm32) or this is one of them. With the files the decode read (see [`crate::reads`]): /// collected on the thread that decodes, not noted anywhere (the caller notes them). fn run_decode(self: &Arc, loc: &Loc, footage: &Footage) -> (Result, ReadFiles) { + // A codec can yield to Rayon while holding its source's decoder mutex. Keep later + // roots for that source OUT of the work-stealing pool until this root finishes (#4074). + // Carry the slot too: forget/reopen must not pair an old permit with a new decoder. + let source = loc.media_t.map(|_| lock(&self.sources).slot(&loc.key.path)); #[cfg(not(target_arch = "wasm32"))] if let Some(threads) = decode_threads() && threads.current_thread_index().is_none() @@ -1642,14 +1711,20 @@ impl Inner { let (me, at, f) = (self.clone(), loc.clone(), footage.clone()); // The request's cancel flag and decoding hints go with it (#329). let hints = filmcraft_media::cancel::Context::current(); - threads.spawn(move || { + let slot = source.clone(); + let job = Box::new(move || { #[cfg(not(test))] - let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f))); + let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f, slot.as_ref()))); // (the decodes counted on that thread are this thread's) #[cfg(test)] - let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f)))); + let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f, slot.as_ref())))); let _ = tx.send(decoded); }); + if let Some(source) = &source { + source.enqueue(threads, job); + } else { + threads.spawn(job); + } // A plain block: this thread runs nothing else meanwhile. return match rx.recv() { #[cfg(not(test))] @@ -1668,11 +1743,14 @@ impl Inner { }; } let _decoding = Decoding::new(); - reads::captured(|| self.decode_source(loc, footage)) + reads::captured(|| self.decode_source(loc, footage, source.as_ref())) } /// Decode the picture `loc` names: a still whole, a movie frame at its size. - fn decode_source(&self, loc: &Loc, footage: &Footage) -> Result { + fn decode_source(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } self.decodes.fetch_add(1, Ordering::Relaxed); #[cfg(test)] { @@ -1684,7 +1762,7 @@ impl Inner { } match loc.media_t { None => self.decode_still(loc, footage).map(|img| Pixels::F32(Arc::new(img))), - Some(_) => self.decode_media(loc, footage), + Some(_) => self.decode_media(loc, footage, source), } } @@ -1748,7 +1826,7 @@ impl Inner { } } - fn decode_media(&self, loc: &Loc, footage: &Footage) -> Result { + fn decode_media(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result { let op = AlphaOp::of(footage, loc.float); let path = &loc.key.path; let f32 = |img| Pixels::F32(Arc::new(img)); @@ -1760,7 +1838,8 @@ impl Inner { Ok(f32(dynamic_to_image(frame, op))) } Some(mt) => { - let Opened { src, turn, .. } = self.opened(path).ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?; + let opened = source.map_or_else(|| self.opened(path), |slot| self.opened_in(path, slot)); + let Opened { src, turn, .. } = opened.ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?; // A movie shown turned a quarter (a phone held upright): the footage's size and // the render's are the turned picture's, the decoded frame's are the file's. let side = |(w, h): (u32, u32)| if crate::probe::swaps_sides(turn) { (h, w) } else { (w, h) }; @@ -2489,6 +2568,70 @@ mod tests { .collect() } + /// #4074: nested codec work may steal another root. A queued same-source root must not + /// re-enter its locked decoder, and an independent source must still make progress. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn movie_dispatch_does_not_reenter_a_locked_source() { + let workers: &'static _ = Box::leak(Box::new(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap())); + let codec = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap()); + let source = SourceSlot::default(); + let decoder = Arc::new(Mutex::new(())); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let first_decoder = decoder.clone(); + source.enqueue( + workers, + Box::new(move || { + let _decoder = lock(&first_decoder); + codec.install(move || { + entered_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + }), + ); + entered_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + source.enqueue( + workers, + Box::new(move || { + let _decoder = lock(&decoder); + done_tx.send(()).unwrap(); + }), + ); + let other = SourceSlot::default(); + let (other_tx, other_rx) = std::sync::mpsc::channel(); + other.enqueue(workers, Box::new(move || other_tx.send(()).unwrap())); + let independent = other_rx.recv_timeout(std::time::Duration::from_secs(2)); + // Always release the codec, including on regression failure. The timeout bounds a + // deadlock; no decode duration or throughput is being asserted. + release_tx.send(()).unwrap(); + assert!(independent.is_ok(), "another source must finish while this codec is parked"); + done_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn movie_dispatch_releases_queued_work_after_a_panic() { + let workers: &'static _ = Box::leak(Box::new(rayon::ThreadPoolBuilder::new().num_threads(1).panic_handler(|_| {}).build().unwrap())); + let source = SourceSlot::default(); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + source.enqueue( + workers, + Box::new(move || { + entered_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + panic!("a codec failed"); + }), + ); + entered_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + source.enqueue(workers, Box::new(move || done_tx.send(()).unwrap())); + release_tx.send(()).unwrap(); + done_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + } + /// #3269: requests for a frame being decoded wait for that decode and take its picture, also /// on rayon workers (the viewer's frame workers), which each decoded a private copy before. #[test] From 5e578049a55aef4e057e775c6cda1f56fdfad859 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 13:16:54 -0500 Subject: [PATCH 392/393] ci(release): publish scheduled nightly prereleases (#4128) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b38c3d2b8..b8b4b2a0f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - dry-run: ${{ github.event_name == 'schedule' }} + nightly: ${{ github.event_name == 'schedule' }} app-name: effectcraft app-title: EffectCraft version: ${{ inputs.version }} From 73bc1a99e475d07d1decb7e8653c48cb74bacad1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:12:36 +0100 Subject: [PATCH 393/393] Release: bump effectcraft to v0.25.1 (#3985) Co-authored-by: FredApps --- Cargo.lock | 70 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 36 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dcdb4f274..b967eb41d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1929,7 +1929,7 @@ dependencies = [ [[package]] name = "effectcraft" -version = "0.24.1" +version = "0.25.1" dependencies = [ "chrono", "cpal", @@ -1958,7 +1958,7 @@ dependencies = [ [[package]] name = "effectcraft-aep" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-aep", "craft-mime", @@ -1975,7 +1975,7 @@ dependencies = [ [[package]] name = "effectcraft-automation" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-jsonrpc", "craft-mime", @@ -1991,7 +1991,7 @@ dependencies = [ [[package]] name = "effectcraft-cli" -version = "0.24.1" +version = "0.25.1" dependencies = [ "cpu-time", "effectcraft-automation", @@ -2010,7 +2010,7 @@ dependencies = [ [[package]] name = "effectcraft-color" -version = "0.24.1" +version = "0.25.1" dependencies = [ "proptest", "serde", @@ -2018,7 +2018,7 @@ dependencies = [ [[package]] name = "effectcraft-effects" -version = "0.24.1" +version = "0.25.1" dependencies = [ "chrono", "craft-cms", @@ -2037,7 +2037,7 @@ dependencies = [ [[package]] name = "effectcraft-engine" -version = "0.24.1" +version = "0.25.1" dependencies = [ "chrono", "craft-docpath", @@ -2077,7 +2077,7 @@ dependencies = [ [[package]] name = "effectcraft-export" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", @@ -2105,7 +2105,7 @@ dependencies = [ [[package]] name = "effectcraft-expr" -version = "0.24.1" +version = "0.25.1" dependencies = [ "boa_engine", "effectcraft-color", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "effectcraft-geom" -version = "0.24.1" +version = "0.25.1" dependencies = [ "proptest", "serde", @@ -2130,7 +2130,7 @@ dependencies = [ [[package]] name = "effectcraft-gpu" -version = "0.24.1" +version = "0.25.1" dependencies = [ "bytemuck", "effectcraft-color", @@ -2153,7 +2153,7 @@ dependencies = [ [[package]] name = "effectcraft-helper-host" -version = "0.24.1" +version = "0.25.1" dependencies = [ "bytemuck", "effectcraft-effects", @@ -2164,7 +2164,7 @@ dependencies = [ [[package]] name = "effectcraft-host" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-vectorcraft-format", "effectcraft-engine", @@ -2192,7 +2192,7 @@ dependencies = [ [[package]] name = "effectcraft-interchange" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)", "effectcraft-color", @@ -2212,7 +2212,7 @@ dependencies = [ [[package]] name = "effectcraft-keyframe" -version = "0.24.1" +version = "0.25.1" dependencies = [ "effectcraft-color", "effectcraft-geom", @@ -2224,7 +2224,7 @@ dependencies = [ [[package]] name = "effectcraft-lottie" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-docpath", "craft-lottie", @@ -2243,7 +2243,7 @@ dependencies = [ [[package]] name = "effectcraft-media" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=33be35625e252cc4f06aa375b3b428521faea37d)", @@ -2286,7 +2286,7 @@ dependencies = [ [[package]] name = "effectcraft-model" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-mesh", "effectcraft-geom", @@ -2298,7 +2298,7 @@ dependencies = [ [[package]] name = "effectcraft-path" -version = "0.24.1" +version = "0.25.1" dependencies = [ "effectcraft-geom", "effectcraft-keyframe", @@ -2311,7 +2311,7 @@ dependencies = [ [[package]] name = "effectcraft-pdf" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-doc", "craft-pdf", @@ -2332,7 +2332,7 @@ dependencies = [ [[package]] name = "effectcraft-plugin" -version = "0.24.1" +version = "0.25.1" dependencies = [ "effectcraft-effects", "effectcraft-keyframe", @@ -2344,7 +2344,7 @@ dependencies = [ [[package]] name = "effectcraft-project" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-ecproj-format", "effectcraft-color", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "effectcraft-psd" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-codepage", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=53198114310dbc2b41e18e4eaf2fd83e69964189)", @@ -2367,7 +2367,7 @@ dependencies = [ [[package]] name = "effectcraft-raster" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "effectcraft-color", @@ -2378,7 +2378,7 @@ dependencies = [ [[package]] name = "effectcraft-render" -version = "0.24.1" +version = "0.25.1" dependencies = [ "effectcraft-color", "effectcraft-effects", @@ -2402,7 +2402,7 @@ dependencies = [ [[package]] name = "effectcraft-sam2" -version = "0.24.1" +version = "0.25.1" dependencies = [ "bytemuck", "candle-core", @@ -2417,7 +2417,7 @@ dependencies = [ [[package]] name = "effectcraft-script" -version = "0.24.1" +version = "0.25.1" dependencies = [ "boa_engine", "effectcraft-engine", @@ -2435,7 +2435,7 @@ dependencies = [ [[package]] name = "effectcraft-segment" -version = "0.24.1" +version = "0.25.1" dependencies = [ "miniz_oxide 0.9.1", "ndarray", @@ -2444,7 +2444,7 @@ dependencies = [ [[package]] name = "effectcraft-svg" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-svg", "effectcraft-geom", @@ -2458,7 +2458,7 @@ dependencies = [ [[package]] name = "effectcraft-text" -version = "0.24.1" +version = "0.25.1" dependencies = [ "effectcraft-keyframe", "harfrust", @@ -2470,7 +2470,7 @@ dependencies = [ [[package]] name = "effectcraft-time" -version = "0.24.1" +version = "0.25.1" dependencies = [ "proptest", "serde", @@ -2478,7 +2478,7 @@ dependencies = [ [[package]] name = "effectcraft-track" -version = "0.24.1" +version = "0.25.1" dependencies = [ "craft-mime", "effectcraft-raster", @@ -2491,7 +2491,7 @@ dependencies = [ [[package]] name = "effectcraft-ui-egui" -version = "0.24.1" +version = "0.25.1" dependencies = [ "bytemuck", "chrono", @@ -2534,7 +2534,7 @@ dependencies = [ [[package]] name = "effectcraft-web" -version = "0.24.1" +version = "0.25.1" dependencies = [ "effectcraft-engine", "effectcraft-export", @@ -8642,7 +8642,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.24.1" +version = "0.25.1" dependencies = [ "chrono", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index 376772e5b..8a9a9d097 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/*"] [workspace.package] -version = "0.24.1" +version = "0.25.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95"