forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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