forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

sweep.rs497 lines, 21.6 KiBHistoryRawDownload
1//! The re-timing sweep: every op that moves or removes timeline time, against
2//! every grouping shape, under the universal laws -- `delete_in`/`delete_sub_in`,
3//! `set_speed`/`set_speed_live`, `split`/`regroup`, `move_clip`/`trim`,
4//! `move_sub`/`trim_sub`, `paste`, `ripple_delete`/`cut_regions`,
5//! `lift`/`lift_sub`, `place`/`place_take`/`place_sub`, `delete(idx)` and
6//! `retime`. The "there might be other bugs" catcher -- a red cell here is an
7//! op whose shape has drifted from the law, found before a user finds it.
8//!
9//! Left out, by name rather than by omission: `group`/`ungroup`/`group_all`
10//! move no time at all (id bookkeeping alone -- their own law is
11//! `links_are_consistent`, asked directly by their unit tests and by
12//! [`group_all_refuses_a_merge_that_doubles_up_a_lane`](crate::project::tests::group_all_refuses_a_merge_that_doubles_up_a_lane)),
13//! and `remove_lane`/`move_lane`/`remove_source`/`remove_subtitles`/`append_clip`
14//! touch the lane *list* or the source table, never a placement's span --
15//! outside this module's law and covered by their own unit tests in
16//! `project.rs`.
17//!
18//! The laws are the four nothing downstream can live without:
19//!
20//! * **Consistency** -- `links_are_consistent`: a link id names at most one
21//! placement per lane, clips and captions alike.
22//! * **Order** -- every lane sorted and disjoint, both of its lists.
23//! * **Survivor continuity** -- the desync-class law: a placement that
24//! survives an op keeps a consistent source window, verified through the
25//! op's own [`TimelineMap`]: the survivor's old span maps onto a span that
26//! contains where it actually landed, or -- for the ops that move whole
27//! members -- its position is the map of where it was.
28//! * **Undo round-trip** -- one press puts the project back byte for byte,
29//! and the op cost exactly one snapshot to do it.
30//!
31//! Paste is the named exception: it *inserts without rippling* media lanes
32//! (a layer is laid over the timeline) and never touches captions at all,
33//! so its cells assert the no-move shape directly instead of through a map.
34
35use crate::map::TimelineMap;
36use crate::project::{Edge, Lane, LaneKind, Rate, Speed, SubClip};
37use crate::scale::FitPolicy;
38use crate::subtitle::SubtitleTrack;
39use crate::{Clip, Project};
40
41const FILE: &str = "/nonexistent/a.mp4";
42
43fn caption(start: u32, frames: u32) -> SubClip {
44 SubClip {
45 start,
46 frames,
47 track: 0,
48 in_us: 0,
49 out_us: i64::from(frames) * 1_000_000,
50 link: None,
51 }
52}
53
54fn track() -> SubtitleTrack {
55 SubtitleTrack {
56 path: FILE.into(),
57 track: None,
58 language: "eng".into(),
59 name: String::new(),
60 label: "eng".into(),
61 cues: Vec::new(),
62 bitmap: false,
63 refused: None,
64 }
65}
66
67fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip {
68 Clip {
69 fade_in: 0,
70 fade_out: 0,
71 transition_out: 0,
72 start,
73 in_frame,
74 out_frame,
75 source: 0,
76 link: None,
77 eq: None,
78 color: None,
79 transform: None,
80 fit: FitPolicy::Fit,
81 speed: Speed::NORMAL,
82 }
83}
84
85/// The shapes a project is swept in: a lone take, a group of two clips, a
86/// group of two clips and a caption (aligned), and the same offset -- the
87/// hand-built shape the offset model exists for.
88fn project(kind: &str) -> (Project, Option<Lane>) {
89 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
90 match kind {
91 "ungrouped" => (p, None),
92 "clips" => {
93 let v2 = p.add_lane(LaneKind::Video);
94 assert!(p.place(v2, 0, clip(0, 0, 90)));
95 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
96 (p, None)
97 }
98 "aligned" => {
99 let s1 = p.add_lane(LaneKind::Subtitle);
100 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
101 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
102 (p, Some(s1))
103 }
104 _ => {
105 // The offset group: a caption starting 30 frames in, ending 30
106 // early, and a second clip behind the group that nothing may
107 // move out from under.
108 let s1 = p.add_lane(LaneKind::Subtitle);
109 let v2 = p.add_lane(LaneKind::Video);
110 assert!(p.place(v2, 120, clip(120, 90, 180)));
111 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
112 p.place_sub(s1, 90, caption(90, 30)).expect("the follower");
113 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
114 (p, Some(s1))
115 }
116 }
117}
118
119const SHAPES: [&str; 4] = ["ungrouped", "clips", "aligned", "offset"];
120
121/// The four laws, asked of a project after an op and after its undo. `map`
122/// is the op's own answer to "this frame is now where?" -- `None` for the
123/// ops that move whole members rather than time (paste), which the sweep
124/// asks the no-move shape of instead.
125fn laws(p: &Project, what: &str) {
126 crate::project::links_are_consistent_pub(p).expect(what);
127 for lane in p.lanes() {
128 let lists: [Vec<(u32, u32)>; 2] = [
129 p.lane_clips_pub(lane).iter().map(|c| (c.start, c.start + c.frames())).collect(),
130 p.sub_lane(lane).iter().map(|s| (s.start, s.end())).collect(),
131 ];
132 for w in lists {
133 let mut prev_end = 0;
134 for (start, end) in w {
135 assert!(start >= prev_end && end > start, "{what}: {lane:?} out of order");
136 prev_end = end;
137 }
138 }
139 }
140}
141
142/// The undo round-trip + snapshot count: one press returns the project to
143/// `pre` -- the parts captured BEFORE the op, by the caller that had them --
144/// and the op cost exactly one step on top of the history it inherited.
145fn undo_round_trip(mut p: Project, pre: crate::project::SweepParts, what: &str) {
146 let steps = p.history_len();
147 assert!(p.undo(), "{what}: there is a step to take");
148 assert_eq!(p.history_len(), steps.saturating_sub(1), "{what}: one step, no more");
149 assert_eq!(p.parts(), pre, "{what}: undo is byte-identical");
150}
151
152#[test]
153fn the_sweep_delete_from_every_anchor() {
154 for shape in SHAPES {
155 for anchor in ["video", "sound", "caption"] {
156 let (mut p, s1) = project(shape);
157 let had_caption = s1.is_some();
158 let pre = p.parts();
159 let deleted = match (anchor, had_caption) {
160 ("video", _) => p.delete_in(Lane::V1, 0),
161 ("sound", _) => p.delete_in(Lane::A1, 0),
162 ("caption", true) => p.delete_sub_in(s1.unwrap(), 0),
163 // This shape has no caption to delete; the cell is vacuous.
164 ("caption", false) => continue,
165 _ => unreachable!("the sweep names three anchors"),
166 };
167 assert!(deleted, "{shape}/{anchor}: the delete happened");
168 laws(&p, &format!("{shape}/{anchor} after delete"));
169 if shape == "ungrouped" {
170 // `Project::single` links its V1 and A1 clips from the start
171 // (the source is grouped with itself), so the lone-clip law
172 // really is a conjunction: the span leaves EVERY lane.
173 assert!(p.lane(Lane::A1).is_empty() && p.lane(Lane::V1).is_empty(), "{shape}/{anchor}");
174 } else {
175 // The group law: every member gone, from every anchor.
176 assert!(p.lane(Lane::V1).is_empty(), "{shape}/{anchor}: V1 emptied");
177 assert!(p.lane(Lane::A1).is_empty(), "{shape}/{anchor}: A1 emptied");
178 if let Some(s1) = s1 {
179 // Only "aligned"'s one caption is grouped; "offset"
180 // groups just its first caption, leaving the ungrouped
181 // follower to close up behind the hole the delete cuts.
182 match shape {
183 "aligned" => assert!(
184 p.sub_lane(s1).is_empty(),
185 "{shape}/{anchor}: the caption gone with the group"
186 ),
187 "offset" => assert_eq!(
188 p.sub_lane(s1).iter().map(|s| (s.start, s.end())).collect::<Vec<_>>(),
189 vec![(60, 90)],
190 "{shape}/{anchor}: the grouped caption gone, the follower closed up behind it"
191 ),
192 _ => unreachable!("the sweep names three grouped shapes with captions"),
193 }
194 }
195 }
196 undo_round_trip(p, pre, &format!("{shape}/{anchor} delete"));
197 }
198 }
199}
200
201#[test]
202fn the_sweep_speed_keeps_the_group_and_the_playhead_scene() {
203 for shape in SHAPES {
204 for (what, speed) in [("2x", Speed::from_permille(2000)), ("half", Speed::from_permille(500))] {
205 let (mut p, _s1) = project(shape);
206 let pre = p.parts();
207 let at = 45u32;
208 let mapped = p.speeded_playhead(Lane::V1, 0, speed, at);
209 let before = p.span_at(Lane::V1, at).and_then(|s| s.from);
210 // The map the write itself is a shape of, built from the
211 // member's own old geometry -- NOT from the playhead's answer,
212 // which is what it will be checked against.
213 let held = p.lane(Lane::V1)[0];
214 let new_len = (f64::from(held.len()) / speed.as_f64()).round() as u32;
215 let map = TimelineMap::piece(
216 (held.start, held.start + held.frames()),
217 (held.start, held.start + new_len),
218 );
219 if let Err(why) = p.set_speed(Lane::V1, 0, speed) {
220 // A stretch the neighbours leave no room for is refused in
221 // the engine's own words -- a valid cell, not a bug, and the
222 // refusal changed nothing (the laws hold of the untouched
223 // project by construction).
224 assert!(
225 why.to_string().contains("would run to frame"),
226 "{shape}/{what}: a refusal names its wall: {why}"
227 );
228 continue;
229 }
230 laws(&p, &format!("{shape}/{what} after speed"));
231 // Survivor continuity through the map: the clip's old span maps
232 // onto exactly the span it landed in -- the piece's own ends, on
233 // the lane, not inferred back from anything the write produced.
234 let landed = p.lane(Lane::V1)[0];
235 assert_eq!(
236 (landed.start, landed.start + landed.frames()),
237 (map.apply(held.start), map.apply(held.start + held.frames())),
238 "{shape}/{what}: the clip's new span is the map of its old one"
239 );
240 // The scene law to the frame a rate can hold: an odd source
241 // frame at 2x never lands on an integer playhead, so the
242 // tolerance is the one frame the map's own rounding admits.
243 let after = p.span_at(Lane::V1, mapped.unwrap_or(at)).and_then(|s| s.from);
244 let apart = match (before, after) {
245 (Some((_, a)), Some((_, b))) => a.abs_diff(b),
246 (None, None) => 0,
247 _ => u32::MAX,
248 };
249 assert!(
250 apart <= 1,
251 "{shape}/{what}: the scene under the playhead, {before:?} vs {after:?}"
252 );
253 undo_round_trip(p, pre, &format!("{shape}/{what} speed"));
254 }
255 }
256}
257
258#[test]
259fn the_sweep_split_and_regroup_round_trip() {
260 for shape in SHAPES {
261 let (mut p, _s1) = project(shape);
262 let pre = p.parts();
263 assert!(p.split(45), "{shape}: the razor cuts");
264 laws(&p, &format!("{shape} after split"));
265 undo_round_trip(p, pre, &format!("{shape} split"));
266
267 let (mut p, _) = project(shape);
268 assert!(p.split(45), "{shape}: cut");
269 let pre = p.parts();
270 assert!(p.regroup(45), "{shape}: and rejoined");
271 laws(&p, &format!("{shape} after regroup"));
272 undo_round_trip(p, pre, &format!("{shape} regroup"));
273 }
274}
275
276#[test]
277fn the_sweep_move_and_trim_keep_the_group_whole() {
278 for shape in SHAPES[1..].iter() {
279 let shape = *shape;
280 let (mut p, _s1) = project(shape);
281 let pre = p.parts();
282 let before: Vec<Option<u32>> = p.lanes()
283 .into_iter()
284 .flat_map(|l| p.lane(l).iter().map(|c| c.link))
285 .collect();
286 assert!(p.move_clip(Lane::V1, 0, Lane::V1, 30), "{shape}: room to slide");
287 laws(&p, &format!("{shape} after move"));
288 let after: Vec<Option<u32>> = p.lanes()
289 .into_iter()
290 .flat_map(|l| p.lane(l).iter().map(|c| c.link))
291 .collect();
292 assert_eq!(before, after, "{shape}: a move keeps the group's ids");
293 undo_round_trip(p, pre, &format!("{shape} move"));
294
295 let (mut p, _) = project(shape);
296 let pre = p.parts();
297 let end = p.lane(Lane::V1)[0].end();
298 assert!(p.trim(Lane::V1, 0, crate::project::Edge::End, end - 10, &[90]), "{shape}: room to trim");
299 laws(&p, &format!("{shape} after trim"));
300 undo_round_trip(p, pre, &format!("{shape} trim"));
301 }
302}
303
304#[test]
305fn the_sweep_paste_is_the_named_exception() {
306 for shape in SHAPES {
307 let (mut p, s1) = project(shape);
308 let pre = p.parts();
309 let subs_before: Vec<Vec<(u32, u32)>> = s1
310 .map(|s1| vec![p.sub_lane(s1).iter().map(|s| (s.start, s.start + s.frames)).collect()])
311 .unwrap_or_default();
312 assert!(p.paste(10, clip(0, 0, 30)), "{shape}: the paste lands");
313 laws(&p, &format!("{shape} after paste"));
314 // The exception, pinned: the media lanes RIPPLE (nothing stays put
315 // past the insert) and the captions never move at all.
316 let subs_after: Vec<Vec<(u32, u32)>> = s1
317 .map(|s1| vec![p.sub_lane(s1).iter().map(|s| (s.start, s.start + s.frames)).collect()])
318 .unwrap_or_default();
319 assert_eq!(subs_before, subs_after, "{shape}: the words keep their clock");
320 undo_round_trip(p, pre, &format!("{shape} paste"));
321 }
322}
323
324/// The scoped and whole-timeline ripples: [`Project::ripple_delete`] and
325/// [`Project::cut_regions`] both close a hole across every lane they touch,
326/// clips and captions alike -- a span safely inside every shape's geometry
327/// (never on a clip or caption edge, so the cell asks the general law and not
328/// one shape's particular boundary).
329#[test]
330fn the_sweep_ripple_delete_and_cut_regions_close_every_lane() {
331 for shape in SHAPES {
332 let (mut p, _s1) = project(shape);
333 let pre = p.parts();
334 assert!(p.ripple_delete(70, 10), "{shape}: the ripple cuts");
335 laws(&p, &format!("{shape} after ripple_delete"));
336 undo_round_trip(p, pre, &format!("{shape} ripple_delete"));
337
338 let (mut p, _s1) = project(shape);
339 let pre = p.parts();
340 assert!(
341 p.cut_regions(&[(70, 10)], &p.lanes()).is_ok(),
342 "{shape}: the scoped cut lands"
343 );
344 laws(&p, &format!("{shape} after cut_regions"));
345 undo_round_trip(p, pre, &format!("{shape} cut_regions"));
346 }
347}
348
349/// The two single-lane, group-blind lifts: [`Project::lift`] and
350/// [`Project::lift_sub`] take one placement off its own lane and leave a gap
351/// -- no other lane moves, grouped or not, which the law asks by checking
352/// every OTHER lane is untouched.
353#[test]
354fn the_sweep_lift_and_lift_sub_leave_a_gap_alone() {
355 for shape in SHAPES {
356 let (mut p, s1) = project(shape);
357 let before_a1 = p.lane(Lane::A1).to_vec();
358 let pre = p.parts();
359 assert!(p.lift(Lane::V1, 0), "{shape}: the lift takes V1's clip");
360 assert!(p.lane(Lane::V1).is_empty(), "{shape}: V1 left a gap");
361 assert_eq!(p.lane(Lane::A1).to_vec(), before_a1, "{shape}: A1 never asked");
362 laws(&p, &format!("{shape} after lift"));
363 undo_round_trip(p, pre, &format!("{shape} lift"));
364
365 let Some(s1) = s1 else { continue };
366 let (mut p, s1) = (project(shape).0, s1);
367 let before_v1 = p.lane(Lane::V1).to_vec();
368 let pre = p.parts();
369 assert!(p.lift_sub(s1, 0), "{shape}: the lift takes the caption");
370 assert_eq!(p.lane(Lane::V1).to_vec(), before_v1, "{shape}: V1 never asked");
371 laws(&p, &format!("{shape} after lift_sub"));
372 undo_round_trip(p, pre, &format!("{shape} lift_sub"));
373 }
374}
375
376/// The caption's own two edits: [`Project::move_sub`] carries its group's
377/// clips along it, one delta for all of them (exactly as a clip's
378/// [`Project::move_clip`] does), and [`Project::trim_sub`] drags its group's
379/// edge along with its own window, one delta each member clamps to its own
380/// room (`Project::follow_group`) -- the same law, not a caption exception.
381#[test]
382fn the_sweep_move_sub_and_trim_sub_keep_their_own_law() {
383 for shape in ["aligned", "offset"] {
384 let (mut p, s1) = project(shape);
385 let s1 = s1.expect("aligned and offset both carry a caption");
386 let pre = p.parts();
387 let v1_before = p.lane(Lane::V1)[0];
388 let sub_before = p.sub_lane(s1)[0].start;
389 let to = sub_before + 5;
390 assert!(p.move_sub(s1, 0, s1, to).is_ok(), "{shape}: room to drag");
391 laws(&p, &format!("{shape} after move_sub"));
392 let v1_after = p.lane(Lane::V1)[0];
393 assert_eq!(
394 i64::from(v1_after.start) - i64::from(v1_before.start),
395 i64::from(p.sub_lane(s1)[0].start) - i64::from(sub_before),
396 "{shape}: the grouped clip rode the same delta as the caption"
397 );
398 undo_round_trip(p, pre, &format!("{shape} move_sub"));
399
400 // A caption in a group drags its group's edge along with its own
401 // (`Project::follow_group`) -- exactly like `move_sub` above, not the
402 // "own window alone" case this cell first assumed.
403 let (mut p, s1) = project(shape);
404 let s1 = s1.unwrap();
405 let pre = p.parts();
406 let end = p.sub_lane(s1)[0].end();
407 assert!(
408 p.trim_sub(s1, 0, Edge::End, end - 5, 30.0).is_ok(),
409 "{shape}: room to trim"
410 );
411 laws(&p, &format!("{shape} after trim_sub"));
412 undo_round_trip(p, pre, &format!("{shape} trim_sub"));
413 }
414}
415
416/// The three overwrite doors -- [`Project::place`], [`Project::place_take`]
417/// and [`Project::place_sub`] -- are [`the_sweep_paste_is_the_named_exception`]'s
418/// own shape: they land over whatever is there and nothing else on the lane
419/// ripples, media or captions.
420#[test]
421fn the_sweep_place_doors_overwrite_without_rippling() {
422 for shape in SHAPES {
423 let (mut p, _s1) = project(shape);
424 let pre = p.parts();
425 assert!(p.place(Lane::V1, 10, clip(10, 0, 20)), "{shape}: place lands");
426 laws(&p, &format!("{shape} after place"));
427 undo_round_trip(p, pre, &format!("{shape} place"));
428
429 let (mut p, _s1) = project(shape);
430 // `add_lane` costs no undo step of its own (it is metadata until
431 // something places on it), so `pre` is read after it -- the lane
432 // list itself is part of what undo restores.
433 let v2 = p.add_lane(LaneKind::Video);
434 let pre = p.parts();
435 assert!(p.place_take(v2, 10, clip(10, 0, 20)), "{shape}: place_take lands");
436 laws(&p, &format!("{shape} after place_take"));
437 undo_round_trip(p, pre, &format!("{shape} place_take"));
438
439 let (mut p, _s1) = project(shape);
440 let s1 = p.add_lane(LaneKind::Subtitle);
441 let pre = p.parts();
442 assert!(p.place_sub(s1, 5, caption(5, 10)).is_ok(), "{shape}: place_sub lands");
443 laws(&p, &format!("{shape} after place_sub"));
444 undo_round_trip(p, pre, &format!("{shape} place_sub"));
445 }
446}
447
448/// [`Project::delete`] is sugar for [`Project::delete_in`] on `V1` -- the
449/// single-lane front-end door the app's own delete key is wired to. One cell
450/// pinning the delegation rather than the whole delete sweep again.
451#[test]
452fn the_sweep_delete_by_index_is_delete_in_on_v1() {
453 let (mut a, _) = project("clips");
454 let (mut b, _) = project("clips");
455 assert_eq!(a.delete(0), b.delete_in(Lane::V1, 0));
456 laws(&a, "delete(idx)");
457 assert_eq!(a.parts(), b.parts(), "delete(idx) and delete_in(V1, idx) agree");
458}
459
460/// [`Project::set_speed_live`] is the drag sample of [`Project::set_speed`]:
461/// every sample only regrades the rate, and the whole gesture undoes in the
462/// one step the press took ([`a_whole_colour_drag_undoes_in_one_step`]'s law,
463/// for a rate instead of a grade).
464#[test]
465fn the_sweep_speed_live_drags_in_one_step() {
466 for shape in SHAPES {
467 let (mut p, _s1) = project(shape);
468 let pre = p.parts();
469 assert!(p.set_speed(Lane::V1, 0, Speed::from_permille(1100)).is_ok(), "{shape}: the press");
470 for permille in [1200, 1300, 1400] {
471 assert!(
472 p.set_speed_live(Lane::V1, 0, Speed::from_permille(permille)).is_ok(),
473 "{shape}: a live sample"
474 );
475 laws(&p, &format!("{shape} after a live speed sample"));
476 }
477 undo_round_trip(p, pre, &format!("{shape} speed drag"));
478 }
479}
480
481/// [`Project::retime`] moves every frame number without being an edit anyone
482/// made ([`Project::retime`]'s own words) -- no history step to its name, so
483/// the sweep asks it the order and consistency laws alone, never the undo
484/// round trip the rest of this module leans on.
485#[test]
486fn the_sweep_retime_keeps_the_lanes_ordered() {
487 for shape in SHAPES {
488 let (mut p, _s1) = project(shape);
489 let steps = p.history_len();
490 // Old timeline frames per new one: 1:2 doubles every span, a slow-down
491 // wide enough that the geometry the sweep builds still fits.
492 let k = Rate::from_fps(1.0, 2.0).expect("a namable rate");
493 p.retime(k, &[10_000]);
494 assert_eq!(p.history_len(), steps, "retime costs no undo step");
495 laws(&p, &format!("{shape} after retime"));
496 }
497}