forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB33ae7d9Tahinli3 months ago699 commits

map.rs284 lines, 13.1 KiBHistoryRawDownload
1//! The timeline's re-timing map: one piecewise-affine answer to "this frame
2//! is now where?", built by every operation that moves time.
3//!
4//! THE ARCHITECTURE LAW: a re-timing op NEVER touches lanes directly. It
5//! (1) resolves its [`Members`](crate::project) once via `group_of`, (2)
6//! builds a `TimelineMap` from each member's OWN geometry -- one piece per
7//! clip or caption, that member's own old span onto its own new one -- (3)
8//! applies that member's map to only its own lane, media clips AND
9//! captions uniformly, and (4) the caller maps the playhead through the
10//! SAME per-member map. The app never re-derives group or time semantics;
11//! the engine's gates stay the single questions.
12//!
13//! The map itself is a sorted list of knots `(old frame, new frame)` with
14//! affine interpolation between neighbours and identity outside the ends: a
15//! compression is two knots with a shallower slope between them, a removal
16//! is a knot pair that collapses a span onto a point, an insertion the same
17//! run backwards, and a piece whose new span starts earlier than its old
18//! one (a slow-down pulling a member's head earlier than its own old frame)
19//! carries an extra knot that folds the run between the two los into that
20//! same kind of collapse, so the piece never doubles back on the identity
21//! run before it. Old frames strictly increase knot to knot; new frames
22//! only need to not decrease -- a collapse ties two of them together on
23//! purpose -- which is what keeps [`TimelineMap::invert`]'s walk a single
24//! pass, never a step backward.
25
26/// A piecewise-affine old→new frame map, identity outside its knots. Built
27/// once per edit and read many times; `Clone` for the tests that pin its
28/// laws, `Debug` for the messages those tests print when they fail.
29#[derive(Clone, Debug, PartialEq)]
30pub(crate) struct TimelineMap {
31 /// Knot points, sorted by `old`, strictly increasing on `old` and
32 /// non-decreasing on `new` -- a collapse ties two knots' `new` value
33 /// together on purpose, the span it drops entering one new frame.
34 knots: Vec<(u32, u32)>,
35}
36
37impl TimelineMap {
38 /// The map that moves nothing: the base every piece is cut into.
39 pub(crate) fn identity() -> Self {
40 Self { knots: Vec::new() }
41 }
42
43 /// One non-identity piece -- `[old_lo, old_hi)` maps onto `[new_lo,
44 /// new_hi)` -- over an identity base. The whole of a compression (a
45 /// re-rate of a member); a removal is `new` collapsed onto its own lo
46 /// (`new_lo == new_hi`, a literal point); an insertion is that run
47 /// backwards; and a piece whose `new_lo` lands before `old_lo` (a
48 /// slow-down pulling a member's head earlier than its own old frame)
49 /// gets an extra anchor knot collapsing the run between the two los
50 /// onto `new_lo`, so the piece stays non-decreasing instead of doubling
51 /// back on the identity run before it. An empty old span (`old_lo >=
52 /// old_hi`) comes out identity, because there is nothing in it to move;
53 /// an inverted new span clamps its hi up to its lo, the collapse it means.
54 pub(crate) fn piece(old: (u32, u32), new: (u32, u32)) -> Self {
55 if old.0 >= old.1 {
56 return Self::identity();
57 }
58 let new = (new.0, new.1.max(new.0));
59 let mut knots = Vec::with_capacity(3);
60 // The anchor: without it, frames below `old_lo` stay identity and
61 // land ON the piece's own new_lo image the moment old_lo is
62 // crossed -- a decreasing step, the non-monotone bug a shift-left
63 // piece used to be. Folding the run into the same collapse a
64 // removal already does keeps `apply` a single non-decreasing walk.
65 if new.0 < old.0 {
66 knots.push((new.0, new.0));
67 }
68 // Half-open boundary knots: interpolation runs between them and
69 // the frame *at* the hi knot is the piece's own to give back
70 // (the caller clamps inside), never a step past its new end.
71 knots.push((old.0, new.0));
72 knots.push((old.1, new.1));
73 Self { knots }
74 }
75
76 /// Where `frame` lands. Affine between knots, identity outside them,
77 /// rounded to the nearest frame -- the same rounding every placement in
78 /// this engine already makes -- and never past the new end of the piece
79 /// it is inside, which a round-up at the last frame would do.
80 pub(crate) fn apply(&self, frame: u32) -> u32 {
81 let mut prev: Option<(u32, u32)> = None;
82 for &(o, n) in &self.knots {
83 if frame == o {
84 return n;
85 }
86 if frame < o {
87 return match prev {
88 // Before the first knot: identity from the head.
89 None => frame,
90 Some(po) => lerp(po, (o, n), frame).min(n.saturating_sub(1)).max(po.1),
91 };
92 }
93 prev = Some((o, n));
94 }
95 match prev {
96 // Past the last knot: identity at the total shift it left.
97 Some((o, n)) => frame.saturating_add(n).saturating_sub(o),
98 None => frame,
99 }
100 }
101
102 /// The inverse question, `None` off the surviving domain (inside a
103 /// removed span there is no frame to come back to -- the caller that
104 /// needs one picks the span's head, which is where a ripple put what
105 /// followed it). The knots are monotone, so this is the same walk with
106 /// the axes traded.
107 #[cfg(test)]
108 pub(crate) fn invert(&self, frame: u32) -> Option<u32> {
109 if self.knots.is_empty() {
110 return Some(frame);
111 }
112 // Below the first knot the map is identity on the old axis *up to
113 // the piece's old lo*, which on the new axis is the run from 0 to
114 // the piece's new lo. A SHIFTED piece (new lo < old lo) puts part of
115 // that run inside the piece's own destination, so the lerp through
116 // the knot is right; an unshifted one has new lo == old lo and the
117 // lerp degenerates to identity -- either way the single run covers
118 // it, and a frame below min(old lo, new lo) is identity outright.
119 if frame < self.knots[0].0.min(self.knots[0].1) {
120 return Some(frame);
121 }
122 // Between old_lo and new_lo of an unanchored (shift-right / plain
123 // expansion) piece, `apply` never lands: old frames below old_lo
124 // stay identity (image 0..old_lo) and the piece's own image starts
125 // at new_lo > old_lo, leaving [old_lo, new_lo) a true hole. A
126 // shift-left's anchor knot ties old==new here, so this window is
127 // empty for it and the branch is never live.
128 if frame < self.knots[0].1 {
129 return None;
130 }
131 let mut prev = self.knots[0];
132 for &(o, n) in &self.knots {
133 if frame == n {
134 return Some(o);
135 }
136 if frame < n {
137 return Some(lerp((prev.1, prev.0), (n, o), frame));
138 }
139 prev = (o, n);
140 }
141 let (o, n) = *self.knots.last().expect("checked non-empty");
142 Some(frame.saturating_sub(n).saturating_add(o))
143 }
144
145 #[cfg(test)]
146 pub(crate) fn shifted_total(&self) -> i64 {
147 match self.knots.last() {
148 Some(&(o, n)) => i64::from(n) - i64::from(o),
149 None => 0,
150 }
151 }
152}
153
154/// The one interpolation this module is: `frame`'s place between two knots,
155/// carried across to the other axis. Independent of the axes' order, which
156/// is what [`TimelineMap::invert`] reuses it for.
157fn lerp(a: (u32, u32), b: (u32, u32), frame: u32) -> u32 {
158 if b.0 <= a.0 {
159 return a.1;
160 }
161 let t = f64::from(frame.saturating_sub(a.0)) / f64::from(b.0 - a.0);
162 (f64::from(a.1) + t * f64::from(b.1.saturating_sub(a.1))).round() as u32
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 /// The piece laws on every shape the engine cuts: monotone, identity
170 /// outside, exact on the ends, invertible on what survives, and the
171 /// total shift the caller reads for the timeline's new length.
172 #[test]
173 fn a_piece_is_monotone_exact_and_invertible() {
174 // A compression: [100, 200) onto [100, 150).
175 let m = TimelineMap::piece((100, 200), (100, 150));
176 assert_eq!(m.apply(0), 0, "identity before");
177 assert_eq!(m.apply(99), 99);
178 assert_eq!(m.apply(100), 100, "the lo knot is exact");
179 assert_eq!(m.apply(150), 125, "the middle halves");
180 assert_eq!(m.apply(199), 149, "the last surviving frame");
181 assert_eq!(m.apply(200), 150, "identity at the new shift");
182 assert_eq!(m.apply(1_000), 950);
183 assert_eq!(m.shifted_total(), -50);
184 // Monotone: a walk up the whole range never goes down.
185 let mut last = 0;
186 for f in 0..400 {
187 let now = m.apply(f);
188 assert!(now >= last, "frame {f} went back to {now}");
189 last = now;
190 }
191 // Round trip in the law's own direction: every new frame's inverse
192 // maps back onto it. The other direction cannot be identity under
193 // rounding -- a compression sends two neighbouring frames to one.
194 for n in 0..400 {
195 let back = m.invert(n).expect("the image is total");
196 assert_eq!(m.apply(back), n, "new frame {n} round trips");
197 }
198 let m = TimelineMap::piece((100, 200), (100, 300));
199 assert_eq!(m.apply(150), 200, "the middle doubles");
200 assert_eq!(m.apply(1_000), 1_100);
201 assert_eq!(m.shifted_total(), 100);
202
203 // A removal: [100, 200) onto [100, 100) -- nothing survives inside,
204 // and what followed stands where the span began.
205 let m = TimelineMap::piece((100, 200), (100, 101));
206 assert_eq!(m.apply(99), 99);
207 assert_eq!(m.apply(150), 100, "inside collapses to the head");
208 assert_eq!(m.apply(200), 101, "after shifts up tight");
209 assert_eq!(m.shifted_total(), -99);
210 }
211
212 /// The laws every piece keeps, whatever shape cut it: `apply` walking
213 /// old frames up never goes back down, and every new frame's own
214 /// inverse answers back exactly through `apply` again -- the right
215 /// inverse a many-to-one piece (a compression, a collapse, the run a
216 /// shift folds into its own anchor) can still give, even where the
217 /// left inverse can't (many old frames landing on one new frame means
218 /// only one of them gets its own value back). Old frames strictly
219 /// below `min(old_lo, new_lo)`, and at or past `old_hi`, sit outside
220 /// the piece's own collapse -- pure identity or a pure shift, both
221 /// exact bijections -- so those get the stronger left-inverse check.
222 fn assert_piece_laws(old: (u32, u32), new: (u32, u32), span: u32) {
223 let m = TimelineMap::piece(old, new);
224 let mut last = 0;
225 // The image `apply` actually produces over the span -- an
226 // expansion skips new frames between old ones (no old frame answers
227 // them), so the right-inverse law is only fair to ask of frames
228 // `apply` really lands on, never the whole new axis blind.
229 let mut image = std::collections::BTreeSet::new();
230 for f in 0..span {
231 let now = m.apply(f);
232 assert!(now >= last, "{old:?}->{new:?}: frame {f} went back to {now} from {last}");
233 image.insert(now);
234 last = now;
235 }
236 for n in image {
237 let back = m.invert(n).expect("the image is total");
238 assert_eq!(m.apply(back), n, "{old:?}->{new:?}: new frame {n} round trips");
239 }
240 let lo = old.0.min(new.0);
241 for f in (0..lo).chain(old.1 + 1..span) {
242 assert_eq!(m.invert(m.apply(f)), Some(f), "{old:?}->{new:?}: frame {f} outside the piece round trips");
243 }
244 }
245
246 /// Every piece shape the engine cuts, run through the laws above: an
247 /// expansion, a compression, a shift-left (the shape a slow-down's
248 /// caption overhang gives, and the one that used to go non-monotone),
249 /// a shift-right, and a collapse to a literal point.
250 #[test]
251 fn a_piece_holds_its_laws_on_every_shape() {
252 assert_piece_laws((100, 200), (100, 300), 500);
253 assert_piece_laws((100, 200), (100, 150), 500);
254 assert_piece_laws((30, 60), (15, 30), 200);
255 assert_piece_laws((30, 60), (45, 90), 200);
256 assert_piece_laws((100, 200), (100, 100), 500);
257 }
258
259 /// The hole a shift-right/expansion piece leaves in its own image: new
260 /// frames between old_lo and new_lo have no old frame that lands on
261 /// them, so `invert` must say so instead of fabricating one.
262 #[test]
263 fn invert_is_none_inside_a_pieces_own_hole() {
264 let m = TimelineMap::piece((30, 60), (45, 90));
265 for f in 30..45 {
266 assert_eq!(m.invert(f), None, "new frame {f} has no preimage");
267 }
268 // Just outside the hole, both ends still answer.
269 assert_eq!(m.invert(29), Some(29));
270 assert_eq!(m.invert(45), Some(30));
271 }
272
273 /// Identity is the base: everything maps to itself, in both directions,
274 /// and the timeline's length never moved.
275 #[test]
276 fn identity_moves_nothing() {
277 let m = TimelineMap::identity();
278 for f in [0u32, 1, 999, u32::MAX / 2] {
279 assert_eq!(m.apply(f), f);
280 assert_eq!(m.invert(f), Some(f));
281 }
282 assert_eq!(m.shifted_total(), 0);
283 }
284}