FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
NEST3: a nest follows its contents
justjohn12345fc557a1c1014
diff --git a/crates/engine/src/nesting_tests.rs b/crates/engine/src/nesting_tests.rsindex 836b5a8ec..a7a3a1489 100644--- a/crates/engine/src/nesting_tests.rs+++ b/crates/engine/src/nesting_tests.rs@@ -170,3 +170,110 @@ fn nest_leaves_transitions_to_clips_outside_the_selection_out() {assert!(q.all_tracks().all(|t| t.transitions.iter().all(|t| t.id != trn.id)));s.active_sequence().unwrap().check().unwrap();}++/// Nest the 4th and 5th V1 clips (with their sound) as "Inner". Returns the nested sequence, the+/// nest's video clip in the outer sequence, and the two nested clips' ids and lengths.+fn nest_two(s: &mut Session) -> (ItemId, ClipId, [(ClipId, Tick); 2]) {+ let v1 = &s.active_sequence().unwrap().video_tracks[0];+ let pair = [(v1.items[3].id, v1.items[3].duration), (v1.items[4].id, v1.items[4].duration)];+ s.execute("timeline.select", json!({"clips": [pair[0].0.0, pair[1].0.0]})).unwrap();+ let nested = ItemId(s.execute("clip.nest", json!({"name": "Inner"})).unwrap()["sequence"].as_u64().unwrap());+ let nest = s.active_sequence().unwrap().video_tracks[0].items.iter().find(|i| i.item == nested).unwrap().id;+ (nested, nest, pair)+}++fn nest_clip(s: &Session, id: ClipId) -> filmcraft_project::TrackItem {+ s.active_sequence().unwrap().find_item(id).unwrap().1.clone()+}++fn mix_at(s: &Session, t: Tick, frames: usize) -> filmcraft_frame::AudioBuffer {+ let q = s.active_sequence().unwrap();+ let sr = q.settings.sample_rate as i64;+ let provider = s.media.full_res_provider(s.project.clone(), s.services.clone());+ filmcraft_render::audio::mix_sequence(&s.project, q, t.to_units_floor(sr), frames, &provider)+}++#[test]+fn a_nest_keeps_its_length_when_its_sequence_gets_shorter() {+ let mut s = demo();+ let outer = s.state.active_sequence.unwrap();+ let (nested, nest, [(_, first), (second_id, second)]) = nest_two(&mut s);+ let whole = nest_clip(&s, nest);+ assert_eq!(whole.duration, first + second);+ assert_eq!(s.project.nest_overhang(&whole), None);+ // remove the second clip inside the nest+ s.execute("sequence.open", json!({"item": nested.0})).unwrap();+ s.execute("timeline.select", json!({"clips": [second_id.0]})).unwrap();+ s.execute("edit.clear", json!({})).unwrap();+ assert_eq!(s.active_sequence().unwrap().duration(), first);+ s.execute("sequence.open", json!({"item": outer.0})).unwrap();+ // the nest is as long as before; its end is now past the contents+ let c = nest_clip(&s, nest);+ assert_eq!(c.range(), whole.range());+ let empty = s.project.nest_overhang(&c).expect("the end of the nest is empty");+ assert_eq!(empty, TimeRange::new(c.start + first, second));+ // there it shows and plays what the sequence would without the nest+ let t = empty.start + Tick(empty.duration.0 / 2);+ let (with_frame, with_mix) = (frame_at(&s, t), mix_at(&s, t, 4800));+ s.execute("timeline.select", json!({"clips": [nest.0]})).unwrap();+ s.execute("clip.enable", json!({})).unwrap();+ let (without_frame, without_mix) = (frame_at(&s, t), mix_at(&s, t, 4800));+ assert!(with_frame.px == without_frame.px, "nothing to see past the contents");+ assert_eq!(with_mix.channels, without_mix.channels, "nothing to hear past the contents");+ s.execute("clip.enable", json!({})).unwrap();+ // it cannot be trimmed out further, and trimming the empty part off leaves a sound nest+ s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "deltaFrames": 12})).ok();+ assert!(nest_clip(&s, nest).duration <= whole.duration, "no more empty time is added");+ let back = nest_clip(&s, nest).duration - first;+ s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "delta": -back.0})).unwrap();+ let c = nest_clip(&s, nest);+ assert_eq!(c.duration, first);+ assert_eq!(s.project.nest_overhang(&c), None);+ s.active_sequence().unwrap().check().unwrap();+}++#[test]+fn a_nest_can_be_trimmed_out_to_reveal_what_its_sequence_gained() {+ let mut s = demo();+ let outer = s.state.active_sequence.unwrap();+ let rate = s.sequence_rate();+ let (nested, nest, [(_, first), (_, second)]) = nest_two(&mut s);+ let whole = nest_clip(&s, nest);+ // make room after the nest in the outer sequence: drop everything that follows it on V1/A1+ let later: Vec<u64> = s.active_sequence().unwrap().video_tracks[0].items.iter().filter(|i| i.start >= whole.end()).map(|i| i.id.0).collect();+ s.execute("timeline.select", json!({"clips": later})).unwrap();+ s.execute("edit.clear", json!({})).unwrap();+ // add 48 frames of media to the end of the nested sequence+ let media = s.project.items.values().find(|i| i.name == "Desert_Dunes.mp4").unwrap().id;+ s.execute("sequence.open", json!({"item": nested.0})).unwrap();+ s.execute("timeline.place", json!({"item": media.0, "time": (first + second).0, "duration": rate.tick_of(48).0})).unwrap();+ assert_eq!(s.active_sequence().unwrap().duration(), first + second + rate.tick_of(48));+ s.execute("sequence.open", json!({"item": outer.0})).unwrap();+ // the nest did not grow by itself+ assert_eq!(nest_clip(&s, nest).range(), whole.range());+ // trimming reveals the new material, up to the end of the contents and no further+ s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "deltaFrames": 10})).unwrap();+ assert_eq!(nest_clip(&s, nest).duration, whole.duration + rate.tick_of(10));+ s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "deltaFrames": 500})).ok();+ let c = nest_clip(&s, nest);+ assert_eq!(c.duration, whole.duration + rate.tick_of(48));+ assert_eq!(s.project.nest_overhang(&c), None);+}++#[test]+fn the_outer_sequence_shows_changes_made_inside_a_nest() {+ let mut s = demo();+ let outer = s.state.active_sequence.unwrap();+ let (nested, nest, [(first_id, first), _]) = nest_two(&mut s);+ let t = nest_clip(&s, nest).start + Tick(first.0 / 2);+ let before = frame_at(&s, t);+ let revision = s.revision;+ // disable the clip that is on screen, inside the nest+ s.execute("sequence.open", json!({"item": nested.0})).unwrap();+ s.execute("timeline.select", json!({"clips": [first_id.0]})).unwrap();+ s.execute("clip.enable", json!({})).unwrap();+ s.execute("sequence.open", json!({"item": outer.0})).unwrap();+ assert_ne!(s.revision, revision, "frames cached for the outer sequence are stale");+ let after = frame_at(&s, t);+ assert!(before.px != after.px, "the outer sequence shows the nest's new contents");+}diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex 94be2d898..980049270 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -1198,6 +1198,32 @@ impl Project {self.items.values().filter(|i| matches!(i.kind, ItemKind::Sequence(_)))}+ /// The part of a nested-sequence clip's timeline range that lies past the end of the nested+ /// sequence's contents: it shows nothing and is silent, and the Timeline hatches it. A nest+ /// keeps its length when its sequence gets shorter, so this is what is left to trim off.+ /// `None` for other clips and for nests that end within their contents.+ pub fn nest_overhang(&self, clip: &TrackItem) -> Option<TimeRange> {+ let contents = self.sequence(clip.item)?.duration();+ if let Some(held) = clip.frame_hold {+ return (held >= contents).then(|| clip.range());+ }+ let past = clip.source_out() - contents;+ if past <= Tick::ZERO {+ return None;+ }+ let speed = clip.speed.abs();+ if clip.source_in >= contents || !speed.is_finite() || speed < 1e-9 {+ return Some(clip.range());+ }+ // source time past the contents, as timeline time+ let len = Tick(((past.0 as f64 / speed).round() as i64).clamp(0, clip.duration.0));+ if len <= Tick::ZERO {+ return None;+ }+ // a reversed clip plays its source's end first+ Some(if clip.reverse { TimeRange::new(clip.start, len) } else { TimeRange::new(clip.end() - len, len) })+ }+/// A sequence that contains itself, directly or through the sequences nested in it (the lowest/// id of those on a cycle), or `None` when nesting is sound. Such a sequence has no frame to/// show, so edits that would make one are refused; only a damaged project file holds one.@@ -1682,4 +1708,40 @@ mod tests {put(&mut p, d, c);assert_eq!(p.nest_cycle(), Some(c));}++ #[test]+ fn nest_overhang_is_the_part_past_the_contents() {+ let (mut p, clip, a) = demo_project();+ let rate = p.sequence(a).unwrap().settings.frame_rate;+ let f = |n: i64| rate.tick_of(n);+ // a holds 100 frames of media; b nests a for 150 frames starting at frame 10+ let media = p.make_track_item(clip, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, f(100)), rate).unwrap();+ assert_eq!(p.nest_overhang(&media), None, "not a nest");+ p.sequence_mut(a).unwrap().video_tracks[0].items.push(media);+ let mut nest = p.make_track_item(a, TrackKind::Video, f(10), TimeRange::new(Tick::ZERO, f(150)), rate).unwrap();+ assert_eq!(p.nest_overhang(&nest), Some(TimeRange::new(f(110), f(50))));+ // within the contents, or exactly to their end: none+ nest.duration = f(100);+ assert_eq!(p.nest_overhang(&nest), None);+ // trimmed in: 60 frames of contents are left+ nest.source_in = f(40);+ assert_eq!(p.nest_overhang(&nest), Some(TimeRange::new(f(70), f(40))));+ // starting past the end: all of it+ nest.source_in = f(100);+ assert_eq!(p.nest_overhang(&nest), Some(nest.range()));+ // double speed uses the contents up twice as fast+ nest.source_in = Tick::ZERO;+ nest.speed = 2.0;+ assert_eq!(p.nest_overhang(&nest), Some(TimeRange::new(f(60), f(50))));+ // reversed, the empty part comes first+ nest.reverse = true;+ assert_eq!(p.nest_overhang(&nest), Some(TimeRange::new(f(10), f(50))));+ // a frame hold shows one frame throughout+ nest.reverse = false;+ nest.speed = 1.0;+ nest.frame_hold = Some(f(20));+ assert_eq!(p.nest_overhang(&nest), None);+ nest.frame_hold = Some(f(100));+ assert_eq!(p.nest_overhang(&nest), Some(nest.range()));+ }}diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rsindex 5ca911b61..91c327083 100644--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@ -313,6 +313,17 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {let body = Rect::from_min_max(pos2(x0, r.rect.min.y + 1.0), pos2(x1.max(x0 + 1.0), r.rect.max.y - 1.0));draw_clip(app, &ctx, &p, body, it, r.kind, selection.contains(&it.id), &t, rate);app.auto.add(&format!("timeline.clip.{}", it.id.0), body.intersect(content), &it.name);+ // a nest that runs past the end of its sequence's contents: that part is empty+ if !previews.contains_key(&it.id)+ && let Some(empty) = app.session.project.nest_overhang(it)+ {+ let er = Rect::from_min_max(pos2(layout.x_of(empty.start), body.min.y), pos2(layout.x_of(empty.end()), body.max.y)).intersect(body);+ if er.width() > 0.0 {+ p.with_clip_rect(er.intersect(p.clip_rect())).rect_filled(er, 0.0, Color32::from_black_alpha(110));+ paint_hatch(&p, er);+ app.auto.add(&format!("timeline.clip.{}.empty", it.id.0), er.intersect(content), "past the end of the nested sequence");+ }+ }}// items dragged onto this track from anotherfor (cid, (start, dur, mt)) in &previews {@@ -722,16 +733,21 @@ pub(crate) fn request_peaks(app: &mut FilmcraftApp, item: ItemId) -> Option<Arc<None}-fn draw_transition(p: &egui::Painter, r: Rect, trn: &filmcraft_project::Transition, _t: &Tokens) {+/// 45° hatching over `r` (transitions, and the empty end of a nested sequence clip).+fn paint_hatch(p: &egui::Painter, r: Rect) {let cp = p.with_clip_rect(r.intersect(p.clip_rect()));- cp.rect_filled(r, 0.0, Color32::from_black_alpha(90));- // 45° hatchinglet step = 4.0;let mut x = r.min.x - r.height();while x < r.max.x {cp.line_segment([pos2(x, r.max.y), pos2(x + r.height(), r.min.y)], Stroke::new(1.0, Color32::from_rgba_unmultiplied(0xd9, 0xd9, 0xd9, 110)));x += step;}+}++fn draw_transition(p: &egui::Painter, r: Rect, trn: &filmcraft_project::Transition, _t: &Tokens) {+ let cp = p.with_clip_rect(r.intersect(p.clip_rect()));+ cp.rect_filled(r, 0.0, Color32::from_black_alpha(90));+ paint_hatch(p, r);let audio = matches!(trn.effect.def().map(|d| d.kind), Some(filmcraft_project::EffectKind::AudioTransition));if audio {// crossing fade curvesdiff --git a/crates/ui-egui/tests/nested_ui.rs b/crates/ui-egui/tests/nested_ui.rsnew file mode 100644index 000000000..c318d7318--- /dev/null+++ b/crates/ui-egui/tests/nested_ui.rs@@ -0,0 +1,105 @@+//! Headless UI tests of nested sequence clips in the Timeline.++use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use serde_json::{Value, json};++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+}++impl Driver {+ fn new() -> Self {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ let (tx, rx) = channel();+ let app = FilmcraftApp::new(s).with_control(rx);+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx };+ d.frames(4);+ d+ }++ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ // the control channel's clicks and keys enter through the input hook+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }++ fn call(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).unwrap();+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ return v;+ }+ }+ panic!("no reply to {method} {params}");+ }++ fn ok(&mut self, method: &str, params: Value) -> Value {+ let v = self.call(method, params.clone());+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");+ v["result"].clone()+ }++ fn exec(&mut self, command: &str, params: Value) -> Value {+ self.ok("engine.execute", json!({"command": command, "params": params}))+ }++ fn app(&mut self) -> &mut FilmcraftApp {+ self.harness.state_mut()+ }+}++impl Driver {+ /// (x, y, width, height) of an element, if it is on screen.+ fn rect(&mut self, id: &str) -> Option<[f64; 4]> {+ let v = self.ok("ui.elements", json!({"prefix": id}));+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == json!(id))?.clone();+ let r = &e["rect"];+ Some([r[0].as_f64().unwrap(), r[1].as_f64().unwrap(), r[2].as_f64().unwrap(), r[3].as_f64().unwrap()])+ }+}++/// As in Premiere, a nest keeps its length when its sequence gets shorter, and the+/// Timeline hatches the part that is now past the contents.+#[test]+fn the_empty_end_of_a_nest_is_marked_in_the_timeline() {+ let mut d = Driver::new();+ let outer = d.app().session.state.active_sequence.unwrap().0;+ let (a, b) = {+ let v1 = &d.app().session.active_sequence().unwrap().video_tracks[0];+ (v1.items[3].clone(), v1.items[4].clone())+ };+ d.exec("timeline.select", json!({"clips": [a.id.0, b.id.0]}));+ let nested = d.exec("clip.nest", json!({"name": "Inner"}))["sequence"].as_u64().unwrap();+ let nest = d.app().session.state.selection[0].0;+ d.frames(3);+ let clip = d.rect(&format!("timeline.clip.{nest}")).expect("the nest clip is on screen");+ assert!(d.rect(&format!("timeline.clip.{nest}.empty")).is_none(), "a full nest has no empty part");+ // remove the second clip inside the nest+ d.exec("sequence.open", json!({"item": nested}));+ d.exec("timeline.select", json!({"clips": [b.id.0]}));+ d.exec("edit.clear", json!({}));+ d.exec("sequence.open", json!({"item": outer}));+ d.frames(3);+ let clip2 = d.rect(&format!("timeline.clip.{nest}")).expect("the nest clip is on screen");+ assert!((clip2[2] - clip[2]).abs() < 1.0, "the nest is as long as before");+ let empty = d.rect(&format!("timeline.clip.{nest}.empty")).expect("the empty part is marked");+ // it covers the removed clip's share of the nest, at its right end+ let share = b.duration.0 as f64 / (a.duration.0 + b.duration.0) as f64;+ assert!((empty[2] - clip2[2] * share).abs() < 2.0, "{empty:?} of {clip2:?}, share {share}");+ assert!((empty[0] + empty[2] - (clip2[0] + clip2[2])).abs() < 1.0, "it ends where the clip ends");+}