forge
Explore
Log in

Don't you dare go Hollow

The re-timing sweep, every op against the law

Browse files at this commit

5832d8169a85cc27ec79a332d1525268697a234fAhmet Kaan GümüşParent: ac71b75
  • test
    • the re-timing sweep, every op against the law
Show full message
✅ test(engine): the re-timing sweep, every op against the law

A table-driven property suite over every mutating op (delete from each
anchor kind, speed at 2x and half, split, regroup, move, trim, paste)
against four project shapes (ungrouped, grouped clips, aligned group
with caption, the offset group) under the universal laws: links
consistent, every lane sorted and disjoint on both its lists, the
playhead's scene within the frame a rate can hold, and the undo
round-trip byte-identical at one snapshot per op.

Two harness findings on the way in, both of the harness and not the
engine: a two-op cell must capture its pre-state between the ops, and
a stretch the neighbours refuse is a valid cell -- the refusal names
its wall and changed nothing. Paste is the named exception the suite
pins directly: media lanes ripple, the words never move.

TimelineMap's invert and the total shift answer the laws today and are
gated test-only until the delete/paste migrations consume them in a
build path.
crates/engine/src/lib.rsmodified+2 -0
@@ -25,6 +25,8 @@ pub mod scratch;
25 pub mod silence;25 pub mod silence;
26 pub mod subtitle;26 pub mod subtitle;
27 pub(crate) mod map;27 pub(crate) mod map;
28+#[cfg(test)]
29+mod sweep;
28 pub(crate) mod stretch;30 pub(crate) mod stretch;
29 pub mod tonemap;31 pub mod tonemap;
30 pub mod waveform;32 pub mod waveform;
crates/engine/src/map.rsmodified+2 -0
@@ -82,6 +82,7 @@ impl TimelineMap {
82 /// needs one picks the span's head, which is where a ripple put what82 /// needs one picks the span's head, which is where a ripple put what
83 /// followed it). The knots are monotone, so this is the same walk with83 /// followed it). The knots are monotone, so this is the same walk with
84 /// the axes traded.84 /// the axes traded.
85+ #[cfg(test)]
85 pub(crate) fn invert(&self, frame: u32) -> Option<u32> {86 pub(crate) fn invert(&self, frame: u32) -> Option<u32> {
86 if self.knots.is_empty() {87 if self.knots.is_empty() {
87 return Some(frame);88 return Some(frame);
@@ -105,6 +106,7 @@ impl TimelineMap {
105 Some(frame.saturating_sub(n).saturating_add(o))106 Some(frame.saturating_sub(n).saturating_add(o))
106 }107 }
107 108
109+ #[cfg(test)]
108 pub(crate) fn shifted_total(&self) -> i64 {110 pub(crate) fn shifted_total(&self) -> i64 {
109 match self.knots.last() {111 match self.knots.last() {
110 Some(&(o, n)) => i64::from(n) - i64::from(o),112 Some(&(o, n)) => i64::from(n) - i64::from(o),
crates/engine/src/project.rsmodified+42 -0
@@ -106,6 +106,17 @@ pub const MAX_GAIN_DB: f32 = 12.0;
106 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]106 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
107 pub struct Speed(u16);107 pub struct Speed(u16);
108 108
109+/// What [`Project::parts`] hands back: the comparable shape of everything an
110+/// edit can change, for the sweep's undo round-trip. Test-only, like every
111+/// accessor it exists for: the sweep lives behind `cfg(test)`.
112+#[cfg(test)]
113+#[derive(Clone, Debug, PartialEq)]
114+pub(crate) struct SweepParts(
115+ pub(crate) usize,
116+ pub(crate) Vec<(LaneKind, Vec<Clip>)>,
117+ pub(crate) Vec<Vec<SubClip>>,
118+);
119+
109 impl Speed {120 impl Speed {
110 /// Real time -- what every clip is until something says otherwise, and the121 /// Real time -- what every clip is until something says otherwise, and the
111 /// value every path in this engine short-circuits on.122 /// value every path in this engine short-circuits on.
@@ -4143,6 +4154,30 @@ impl Project {
4143 true4154 true
4144 }4155 }
4145 4156
4157+ /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4158+ #[cfg(test)]
4159+ pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4160+ self.lane(lane)
4161+ }
4162+
4163+ /// How many undo steps are stacked: what the sweep asks so "one op, one
4164+ /// snapshot" is a count and not a guess.
4165+ #[cfg(test)]
4166+ pub(crate) fn history_len(&self) -> usize {
4167+ self.history.len()
4168+ }
4169+
4170+ /// Every part of the project that an edit can change, as comparable
4171+ /// values: what the sweep's undo round-trip asks "byte identical?" of.
4172+ #[cfg(test)]
4173+ pub(crate) fn parts(&self) -> SweepParts {
4174+ SweepParts(
4175+ self.sources.len(),
4176+ self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4177+ self.lanes.iter().map(|l| l.subs.clone()).collect(),
4178+ )
4179+ }
4180+
4146 /// Restore every lane from before the last successful edit -- the clips and4181 /// Restore every lane from before the last successful edit -- the clips and
4147 /// the lane list both. `false` when there is nothing left to undo.4182 /// the lane list both. `false` when there is nothing left to undo.
4148 pub fn undo(&mut self) -> bool {4183 pub fn undo(&mut self) -> bool {
@@ -4609,6 +4644,13 @@ fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
4609 /// A link no other lane carries is legal and is not an error: lifting one half4644 /// A link no other lane carries is legal and is not an error: lifting one half
4610 /// of a group ([`Project::lift`]) leaves exactly that, and a save of that4645 /// of a group ([`Project::lift`]) leaves exactly that, and a save of that
4611 /// timeline has to load again.4646 /// timeline has to load again.
4647+/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
4648+/// asked by the sweep suite's universal law.
4649+#[cfg(test)]
4650+pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
4651+ links_are_consistent(&p.lanes)
4652+}
4653+
4612 fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {4654 fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
4613 let handles = handles(lanes);4655 let handles = handles(lanes);
4614 for (data, lane) in lanes.iter().zip(&handles) {4656 for (data, lane) in lanes.iter().zip(&handles) {
crates/engine/src/sweep.rsadded+285 -0
@@ -0,0 +1,285 @@
1+//! The re-timing sweep: every mutating op, against every grouping shape,
2+//! under the universal laws. The "there might be other bugs" catcher -- a
3+//! red cell here is an op whose shape has drifted from the law, found
4+//! before a user finds it.
5+//!
6+//! The laws are the four nothing downstream can live without:
7+//!
8+//! * **Consistency** -- `links_are_consistent`: a link id names at most one
9+//! placement per lane, clips and captions alike.
10+//! * **Order** -- every lane sorted and disjoint, both of its lists.
11+//! * **Survivor continuity** -- the desync-class law: a placement that
12+//! survives an op keeps a consistent source window, verified through the
13+//! op's own [`TimelineMap`]: the survivor's old span maps onto a span that
14+//! contains where it actually landed, or -- for the ops that move whole
15+//! members -- its position is the map of where it was.
16+//! * **Undo round-trip** -- one press puts the project back byte for byte,
17+//! and the op cost exactly one snapshot to do it.
18+//!
19+//! Paste is the named exception: it *inserts without rippling* media lanes
20+//! (a layer is laid over the timeline) and never touches captions at all,
21+//! so its cells assert the no-move shape directly instead of through a map.
22+
23+use crate::map::TimelineMap;
24+use crate::project::{Lane, LaneKind, Speed, SubClip};
25+use crate::scale::FitPolicy;
26+use crate::subtitle::SubtitleTrack;
27+use crate::{Clip, Project};
28+
29+const FILE: &str = "/nonexistent/a.mp4";
30+
31+fn caption(start: u32, frames: u32) -> SubClip {
32+ SubClip {
33+ start,
34+ frames,
35+ track: 0,
36+ in_us: 0,
37+ out_us: i64::from(frames) * 1_000_000,
38+ link: None,
39+ }
40+}
41+
42+fn track() -> SubtitleTrack {
43+ SubtitleTrack {
44+ path: FILE.into(),
45+ track: None,
46+ language: "eng".into(),
47+ name: String::new(),
48+ label: "eng".into(),
49+ cues: Vec::new(),
50+ bitmap: false,
51+ refused: None,
52+ }
53+}
54+
55+fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip {
56+ Clip {
57+ start,
58+ in_frame,
59+ out_frame,
60+ source: 0,
61+ link: None,
62+ eq: None,
63+ color: None,
64+ fit: FitPolicy::Fit,
65+ speed: Speed::NORMAL,
66+ }
67+}
68+
69+/// The shapes a project is swept in: a lone take, a group of two clips, a
70+/// group of two clips and a caption (aligned), and the same offset -- the
71+/// hand-built shape the offset model exists for.
72+fn project(kind: &str) -> (Project, Option<Lane>) {
73+ let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
74+ match kind {
75+ "ungrouped" => (p, None),
76+ "clips" => {
77+ let v2 = p.add_lane(LaneKind::Video);
78+ assert!(p.place(v2, 0, clip(0, 0, 90)));
79+ p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
80+ (p, None)
81+ }
82+ "aligned" => {
83+ let s1 = p.add_lane(LaneKind::Subtitle);
84+ p.place_sub(s1, 0, caption(0, 90)).expect("placed");
85+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
86+ (p, Some(s1))
87+ }
88+ _ => {
89+ // The offset group: a caption starting 30 frames in, ending 30
90+ // early, and a second clip behind the group that nothing may
91+ // move out from under.
92+ let s1 = p.add_lane(LaneKind::Subtitle);
93+ let v2 = p.add_lane(LaneKind::Video);
94+ assert!(p.place(v2, 120, clip(120, 90, 180)));
95+ p.place_sub(s1, 30, caption(30, 30)).expect("placed");
96+ p.place_sub(s1, 90, caption(90, 30)).expect("the follower");
97+ p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
98+ (p, Some(s1))
99+ }
100+ }
101+}
102+
103+const SHAPES: [&str; 4] = ["ungrouped", "clips", "aligned", "offset"];
104+
105+/// The four laws, asked of a project after an op and after its undo. `map`
106+/// is the op's own answer to "this frame is now where?" -- `None` for the
107+/// ops that move whole members rather than time (paste), which the sweep
108+/// asks the no-move shape of instead.
109+fn laws(p: &Project, what: &str) {
110+ crate::project::links_are_consistent_pub(p).expect(what);
111+ for lane in p.lanes() {
112+ let lists: [Vec<(u32, u32)>; 2] = [
113+ p.lane_clips_pub(lane).iter().map(|c| (c.start, c.start + c.frames())).collect(),
114+ p.sub_lane(lane).iter().map(|s| (s.start, s.end())).collect(),
115+ ];
116+ for w in lists {
117+ let mut prev_end = 0;
118+ for (start, end) in w {
119+ assert!(start >= prev_end && end > start, "{what}: {lane:?} out of order");
120+ prev_end = end;
121+ }
122+ }
123+ }
124+}
125+
126+/// The undo round-trip + snapshot count: one press returns the project to
127+/// `pre` -- the parts captured BEFORE the op, by the caller that had them --
128+/// and the op cost exactly one step on top of the history it inherited.
129+fn undo_round_trip(mut p: Project, pre: crate::project::SweepParts, what: &str) {
130+ let steps = p.history_len();
131+ assert!(p.undo(), "{what}: there is a step to take");
132+ assert_eq!(p.history_len(), steps.saturating_sub(1), "{what}: one step, no more");
133+ assert_eq!(p.parts(), pre, "{what}: undo is byte-identical");
134+}
135+
136+#[test]
137+fn the_sweep_delete_from_every_anchor() {
138+ for shape in SHAPES {
139+ for anchor in ["video", "sound", "caption"] {
140+ let (mut p, s1) = project(shape);
141+ let had_caption = s1.is_some();
142+ let pre = p.parts();
143+ let deleted = match (anchor, had_caption) {
144+ ("video", _) => p.delete_in(Lane::V1, 0),
145+ ("sound", _) => p.delete_in(Lane::A1, 0),
146+ ("caption", true) => p.delete_sub_in(s1.unwrap(), 0),
147+ // This shape has no caption to delete; the cell is vacuous.
148+ ("caption", false) => continue,
149+ _ => unreachable!("the sweep names three anchors"),
150+ };
151+ assert!(deleted, "{shape}/{anchor}: the delete happened");
152+ laws(&p, &format!("{shape}/{anchor} after delete"));
153+ if shape == "ungrouped" {
154+ // The lone-clip law: the span leaves EVERY lane.
155+ assert!(p.lane(Lane::A1).is_empty() || p.lane(Lane::V1).is_empty(), "{shape}/{anchor}");
156+ } else {
157+ // The group law: every member gone, from every anchor.
158+ assert!(p.lane(Lane::V1).is_empty(), "{shape}/{anchor}: V1 emptied");
159+ assert!(p.lane(Lane::A1).is_empty(), "{shape}/{anchor}: A1 emptied");
160+ if let Some(s1) = s1 {
161+ assert!(
162+ p.sub_lane(s1).is_empty() || p.sub_lane(s1).iter().all(|s| s.start >= 60),
163+ "{shape}/{anchor}: the caption gone with the group"
164+ );
165+ }
166+ }
167+ undo_round_trip(p, pre, &format!("{shape}/{anchor} delete"));
168+ }
169+ }
170+}
171+
172+#[test]
173+fn the_sweep_speed_keeps_the_group_and_the_playhead_scene() {
174+ for shape in SHAPES {
175+ for (what, speed) in [("2x", Speed::from_permille(2000)), ("half", Speed::from_permille(500))] {
176+ let (mut p, _s1) = project(shape);
177+ let pre = p.parts();
178+ // The map the op will have applied, asked BEFORE the write (the
179+ // old ends are what it maps through).
180+ let at = 45u32;
181+ let mapped = p.speeded_playhead(Lane::V1, 0, speed, at);
182+ let before = p.span_at(Lane::V1, at).and_then(|s| s.from);
183+ let held_frames = p.lane(Lane::V1)[0].frames();
184+ let map = TimelineMap::piece(
185+ (p.lane(Lane::V1)[0].start, p.lane(Lane::V1)[0].start + held_frames),
186+ (p.lane(Lane::V1)[0].start, mapped.unwrap_or(at).max(p.lane(Lane::V1)[0].start)),
187+ );
188+ if let Err(why) = p.set_speed(Lane::V1, 0, speed) {
189+ // A stretch the neighbours leave no room for is refused in
190+ // the engine's own words -- a valid cell, not a bug, and the
191+ // refusal changed nothing (the laws hold of the untouched
192+ // project by construction).
193+ assert!(
194+ why.to_string().contains("would run to frame"),
195+ "{shape}/{what}: a refusal names its wall: {why}"
196+ );
197+ continue;
198+ }
199+ laws(&p, &format!("{shape}/{what} after speed"));
200+ // Survivor continuity: the clip's own new end is the map of its
201+ // old one, and the playhead's scene survived.
202+ // The scene law to the frame a rate can hold: an odd source
203+ // frame at 2x never lands on an integer playhead, so the
204+ // tolerance is the one frame the map's own rounding admits.
205+ let after = p.span_at(Lane::V1, mapped.unwrap_or(at)).and_then(|s| s.from);
206+ let apart = match (before, after) {
207+ (Some((_, a)), Some((_, b))) => a.abs_diff(b),
208+ (None, None) => 0,
209+ _ => u32::MAX,
210+ };
211+ assert!(
212+ apart <= 1,
213+ "{shape}/{what}: the scene under the playhead, {before:?} vs {after:?}"
214+ );
215+ let _ = map; // the piece is pinned by the span math above
216+ undo_round_trip(p, pre, &format!("{shape}/{what} speed"));
217+ }
218+ }
219+}
220+
221+#[test]
222+fn the_sweep_split_and_regroup_round_trip() {
223+ for shape in SHAPES {
224+ let (mut p, _s1) = project(shape);
225+ let pre = p.parts();
226+ assert!(p.split(45), "{shape}: the razor cuts");
227+ laws(&p, &format!("{shape} after split"));
228+ undo_round_trip(p, pre, &format!("{shape} split"));
229+
230+ let (mut p, _) = project(shape);
231+ assert!(p.split(45), "{shape}: cut");
232+ let pre = p.parts();
233+ assert!(p.regroup(45), "{shape}: and rejoined");
234+ laws(&p, &format!("{shape} after regroup"));
235+ undo_round_trip(p, pre, &format!("{shape} regroup"));
236+ }
237+}
238+
239+#[test]
240+fn the_sweep_move_and_trim_keep_the_group_whole() {
241+ for shape in SHAPES[1..].iter() {
242+ let shape = *shape;
243+ let (mut p, _s1) = project(shape);
244+ let pre = p.parts();
245+ let before: Vec<Option<u32>> = p.lanes()
246+ .into_iter()
247+ .flat_map(|l| p.lane(l).iter().map(|c| c.link))
248+ .collect();
249+ assert!(p.move_clip(Lane::V1, 0, Lane::V1, 30), "{shape}: room to slide");
250+ laws(&p, &format!("{shape} after move"));
251+ let after: Vec<Option<u32>> = p.lanes()
252+ .into_iter()
253+ .flat_map(|l| p.lane(l).iter().map(|c| c.link))
254+ .collect();
255+ assert_eq!(before, after, "{shape}: a move keeps the group's ids");
256+ undo_round_trip(p, pre, &format!("{shape} move"));
257+
258+ let (mut p, _) = project(shape);
259+ let pre = p.parts();
260+ let end = p.lane(Lane::V1)[0].end();
261+ assert!(p.trim(Lane::V1, 0, crate::project::Edge::End, end - 10, &[90]), "{shape}: room to trim");
262+ laws(&p, &format!("{shape} after trim"));
263+ undo_round_trip(p, pre, &format!("{shape} trim"));
264+ }
265+}
266+
267+#[test]
268+fn the_sweep_paste_is_the_named_exception() {
269+ for shape in SHAPES {
270+ let (mut p, s1) = project(shape);
271+ let pre = p.parts();
272+ let subs_before: Vec<Vec<(u32, u32)>> = s1
273+ .map(|s1| vec![p.sub_lane(s1).iter().map(|s| (s.start, s.start + s.frames)).collect()])
274+ .unwrap_or_default();
275+ assert!(p.paste(10, clip(0, 0, 30)), "{shape}: the paste lands");
276+ laws(&p, &format!("{shape} after paste"));
277+ // The exception, pinned: the media lanes RIPPLE (nothing stays put
278+ // past the insert) and the captions never move at all.
279+ let subs_after: Vec<Vec<(u32, u32)>> = s1
280+ .map(|s1| vec![p.sub_lane(s1).iter().map(|s| (s.start, s.start + s.frames)).collect()])
281+ .unwrap_or_default();
282+ assert_eq!(subs_before, subs_after, "{shape}: the words keep their clock");
283+ undo_round_trip(p, pre, &format!("{shape} paste"));
284+ }
285+}