Skip to main content

alpha2_eval/
retime.rs

1use alpha2_model::{LoopMode, TimeMap};
2use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
3
4/// Frame grid that reverse playback and ping-pong backward passes mirror by: frame `k` starts
5/// at `floor(k * ticks / per)`, like project frames.
6///
7/// Pictures mirror by project frame, so a reversed clip shows the forward clip's frames in
8/// reverse order at any rate and clip bounds. Sound mirrors by tick, the closest ticks get to the
9/// mixer's per-sample mirror.
10#[derive(Copy, Clone, Debug, Eq, PartialEq)]
11pub(crate) struct Mirror {
12    ticks: i128,
13    per: i128,
14}
15
16impl Mirror {
17    /// One tick.
18    pub(crate) const TICK: Self = Self { ticks: 1, per: 1 };
19
20    /// One frame at `rate`.
21    pub(crate) fn frame(rate: FrameRate) -> Self {
22        Self {
23            ticks: i128::from(TICKS_PER_SECOND) * i128::from(rate.denominator()),
24            per: i128::from(rate.numerator()),
25        }
26    }
27
28    fn start_of(self, frame: i128) -> Option<i128> {
29        Some(frame.checked_mul(self.ticks)?.div_euclid(self.per))
30    }
31
32    fn frame_of(self, tick: i128) -> Option<i128> {
33        Some(
34            tick.checked_add(1)?
35                .checked_mul(self.per)?
36                .checked_sub(1)?
37                .div_euclid(self.ticks),
38        )
39    }
40
41    /// Forward offset `floor(e' * scale / length)` shown by the mirror of `elapsed` in a window
42    /// of `length` ticks from `start`.
43    ///
44    /// With `k0`/`k1` the first/last frames starting in the window and `k` the frame containing
45    /// `start + elapsed` (clamped to `k0`), `e'` is `start_of(k0 + k1 - k)` minus the time into
46    /// `k`, relative to the window start and floored at zero. A window with no frame start gives 0.
47    fn offset(self, start: i128, length: i128, elapsed: i128, scale: i128) -> Option<i128> {
48        let first = self.frame_of(start.checked_sub(1)?)?.checked_add(1)?;
49        let last = self.frame_of(start.checked_add(length)?.checked_sub(1)?)?;
50        if first > last {
51            return Some(0);
52        }
53        let tick = start.checked_add(elapsed)?;
54        let frame = self.frame_of(tick)?;
55        let (frame, into) = if frame < first {
56            (first, 0)
57        } else {
58            (frame, tick.checked_sub(self.start_of(frame)?)?)
59        };
60        let mirrored = self
61            .start_of(first.checked_add(last)?.checked_sub(frame)?)?
62            .checked_sub(into)?
63            .checked_sub(start)?;
64        if mirrored <= 0 {
65            return Some(0);
66        }
67        Some(mirrored.checked_mul(scale)?.div_euclid(length))
68    }
69}
70
71/// The source instant a clip shows at timeline `time`, in whole ticks.
72///
73/// With `e = time - timeline.start`, `T` the timeline duration, `S` the
74/// source duration, and `mirror` the frames reversing mirrors by:
75///
76/// - forward: `source.start + floor(e * S / T)`;
77/// - reverse: the forward instant at the mirrored frame less the time into the frame
78///   ([`Mirror`]), clamped to the source start;
79/// - freeze: its instant;
80/// - a repeating loop: `source.start + (e mod S)`;
81/// - a ping-pong loop: the same on even passes, mirrored on odd ones;
82/// - a curve: the tick it names ([`crate::TimeCurve::shown`]), held inside the source range.
83///
84/// Returns `None` for an empty range or a value that does not fit in ticks.
85pub(crate) fn map_source_time(
86    timeline: TimeRange,
87    source: TimeRange,
88    time_map: &TimeMap,
89    mirror: Mirror,
90    time: MediaTime,
91) -> Option<MediaTime> {
92    let timeline_duration = i128::from(timeline.duration()?.ticks());
93    let source_duration = i128::from(source.duration()?.ticks());
94    if timeline_duration == 0 || source_duration == 0 {
95        return None;
96    }
97    let elapsed = i128::from(time.ticks()) - i128::from(timeline.start().ticks());
98    let offset = match time_map {
99        TimeMap::Forward => elapsed
100            .checked_mul(source_duration)?
101            .div_euclid(timeline_duration),
102        TimeMap::Reverse => mirror.offset(
103            i128::from(timeline.start().ticks()),
104            timeline_duration,
105            elapsed,
106            source_duration,
107        )?,
108        TimeMap::Freeze { source_time } => return Some(*source_time),
109        TimeMap::Curve { .. } => {
110            let shown = crate::TimeCurve::of(time_map)?.shown(time.ticks())?;
111            let (first, last) = (source.start().ticks(), source.end().ticks() - 1);
112            return Some(MediaTime(shown.clamp(first, last)));
113        }
114        TimeMap::Loop { mode } => {
115            let within = elapsed.rem_euclid(source_duration);
116            let pass = elapsed.div_euclid(source_duration);
117            match mode {
118                LoopMode::PingPong if pass.rem_euclid(2) == 1 => mirror.offset(
119                    i128::from(timeline.start().ticks())
120                        .checked_add(pass.checked_mul(source_duration)?)?,
121                    source_duration,
122                    within,
123                    source_duration,
124                )?,
125                LoopMode::Repeat | LoopMode::PingPong => within,
126            }
127        }
128    };
129    let mapped = i128::from(source.start().ticks()).checked_add(offset)?;
130    i64::try_from(mapped).ok().map(MediaTime::from_ticks)
131}
132
133/// The source instant a clip's picture shows at timeline `time`, mirroring by project frames at
134/// `frame_rate` exactly as evaluation draws it.
135///
136/// `tests/golden/time-rules-corpus.json` pins this for the TypeScript port.
137///
138/// Returns `None` for an empty range or a value that does not fit in ticks.
139#[must_use]
140pub fn picture_source_time(
141    timeline: TimeRange,
142    source: TimeRange,
143    time_map: &TimeMap,
144    frame_rate: FrameRate,
145    time: MediaTime,
146) -> Option<MediaTime> {
147    map_source_time(timeline, source, time_map, Mirror::frame(frame_rate), time)
148}
149
150/// Which way the shown source time moves over a [`Stretch`].
151#[derive(Copy, Clone, Debug, Eq, PartialEq)]
152pub enum Direction {
153    /// To later source times, or staying.
154    Rising,
155    /// To earlier source times, or staying.
156    Falling,
157    /// One source time throughout.
158    Still,
159}
160
161/// A span of a clip's timeline over which the shown source time moves one way.
162#[derive(Copy, Clone, Debug, Eq, PartialEq)]
163pub struct Stretch {
164    /// Its first tick.
165    pub from: i64,
166    /// One past its last tick.
167    pub to: i64,
168    /// Which way the shown time moves.
169    pub direction: Direction,
170    /// The least source tick shown in it.
171    pub low: i64,
172    /// The greatest source tick shown in it.
173    pub high: i64,
174}
175
176/// A clip's time map with its stretches worked out, for asking where it shows source times.
177///
178/// Built once per clip and asked many times: every question walks the stretches and searches
179/// only those whose shown times can hold the answer.
180#[derive(Clone, Debug)]
181pub struct ClipTimes<'a> {
182    timeline: TimeRange,
183    source: TimeRange,
184    time_map: &'a TimeMap,
185    frame_rate: FrameRate,
186    stretches: Vec<Stretch>,
187    shown: (i64, i64),
188}
189
190pub(crate) const MAX_STRETCHES: usize = 1 << 22;
191
192impl<'a> ClipTimes<'a> {
193    /// The stretches of a clip of the two ranges under `time_map`, with pictures mirrored by
194    /// project frames at `frame_rate`. `None` for a time beyond ticks or more stretches than a
195    /// valid clip has.
196    #[must_use]
197    pub fn new(
198        timeline: TimeRange,
199        source: TimeRange,
200        time_map: &'a TimeMap,
201        frame_rate: FrameRate,
202    ) -> Option<Self> {
203        let mut times = Self {
204            timeline,
205            source,
206            time_map,
207            frame_rate,
208            stretches: Vec::new(),
209            shown: (i64::MAX, i64::MIN),
210        };
211        times.stretches = times.work_out()?;
212        times.shown = times
213            .stretches
214            .iter()
215            .fold(times.shown, |(low, high), stretch| {
216                (low.min(stretch.low), high.max(stretch.high))
217            });
218        Some(times)
219    }
220
221    /// The stretches in timeline order; together they cover the clip.
222    #[must_use]
223    pub fn stretches(&self) -> &[Stretch] {
224        &self.stretches
225    }
226
227    fn shown(&self, tick: i64) -> i64 {
228        picture_source_time(
229            self.timeline,
230            self.source,
231            self.time_map,
232            self.frame_rate,
233            MediaTime(tick),
234        )
235        .map_or(i64::MIN, MediaTime::ticks)
236    }
237
238    fn stretch(&self, from: i64, to: i64, direction: Option<Direction>) -> Stretch {
239        let (first, last) = (self.shown(from), self.shown(to - 1));
240        Stretch {
241            from,
242            to,
243            direction: direction.unwrap_or(match last.cmp(&first) {
244                std::cmp::Ordering::Greater => Direction::Rising,
245                std::cmp::Ordering::Less => Direction::Falling,
246                std::cmp::Ordering::Equal => Direction::Still,
247            }),
248            low: first.min(last),
249            high: first.max(last),
250        }
251    }
252
253    fn work_out(&self) -> Option<Vec<Stretch>> {
254        let (start, end) = (self.timeline.start().ticks(), self.timeline.end().ticks());
255        let source_length = self.source.duration()?.ticks();
256        if start >= end || source_length <= 0 {
257            return Some(Vec::new());
258        }
259        match self.time_map {
260            TimeMap::Forward => Some(vec![self.stretch(start, end, Some(Direction::Rising))]),
261            TimeMap::Reverse => Some(vec![self.stretch(start, end, Some(Direction::Falling))]),
262            TimeMap::Freeze { .. } => Some(vec![self.stretch(start, end, Some(Direction::Still))]),
263            TimeMap::Loop { mode } => {
264                let passes = (i128::from(end) - i128::from(start) - 1) / i128::from(source_length);
265                let last_end = i128::from(start) + (passes + 1) * i128::from(source_length);
266                i64::try_from(last_end).ok()?;
267                let passes = usize::try_from(passes + 1)
268                    .ok()
269                    .filter(|passes| *passes <= MAX_STRETCHES)?;
270                let mut stretches = Vec::with_capacity(passes);
271                let mut from = start;
272                for pass in 0..passes {
273                    let to = from.saturating_add(source_length).min(end);
274                    let direction = if *mode == LoopMode::PingPong && pass % 2 == 1 {
275                        Direction::Falling
276                    } else {
277                        Direction::Rising
278                    };
279                    stretches.push(self.stretch(from, to, Some(direction)));
280                    from = to;
281                }
282                Some(stretches)
283            }
284            TimeMap::Curve { .. } => {
285                let cuts = crate::TimeCurve::of(self.time_map)?.cuts(start, end, MAX_STRETCHES)?;
286                let mut stretches: Vec<Stretch> = Vec::with_capacity(cuts.len());
287                let ends = cuts.iter().skip(1).copied().chain([end]);
288                for (from, to) in cuts.iter().copied().zip(ends) {
289                    let leg = self.stretch(from, to, None);
290                    match stretches.last_mut() {
291                        Some(previous) if continues(previous, &leg) => {
292                            if previous.direction == Direction::Still {
293                                previous.direction = leg.direction;
294                            }
295                            previous.to = leg.to;
296                            previous.low = previous.low.min(leg.low);
297                            previous.high = previous.high.max(leg.high);
298                        }
299                        _ => stretches.push(leg),
300                    }
301                }
302                Some(stretches)
303            }
304        }
305    }
306
307    pub(crate) fn line_breaks(&self) -> Vec<i64> {
308        let mut breaks = Vec::new();
309        for stretch in &self.stretches {
310            let (from, to) = (stretch.from, stretch.to);
311            breaks.extend([from, to - 1]);
312            if stretch.direction == Direction::Falling {
313                let (top, bottom) = (stretch.high, stretch.low);
314                breaks.push(first_reached(from, to, |tick| self.shown(tick) < top) - 1);
315                breaks.push(first_reached(from, to, |tick| self.shown(tick) <= bottom));
316            }
317        }
318        breaks.sort_unstable();
319        breaks.dedup();
320        breaks
321    }
322
323    /// The timeline ranges at which the clip's picture shows a source time in
324    /// `[range_start, range_end)`, in timeline order and disjoint. `None` for a range beyond
325    /// ticks.
326    #[must_use]
327    pub fn timeline_ranges(
328        &self,
329        range_start: MediaTime,
330        range_end: MediaTime,
331    ) -> Option<Vec<TimeRange>> {
332        if range_start >= range_end {
333            return Some(Vec::new());
334        }
335        let (low, high) = (range_start.ticks(), range_end.ticks());
336        if covers_source(self.time_map, self.source, range_start, range_end) {
337            return Some(if self.stretches.is_empty() {
338                Vec::new()
339            } else {
340                vec![self.timeline]
341            });
342        }
343        let mut ranges: Vec<TimeRange> = Vec::new();
344        if self.shown.1 < low || self.shown.0 >= high {
345            return Some(ranges);
346        }
347        for stretch in &self.stretches {
348            if stretch.high < low || stretch.low >= high {
349                continue;
350            }
351            let (from, to) = (stretch.from, stretch.to);
352            let (first, last) = match stretch.direction {
353                Direction::Rising => (
354                    first_reached(from, to, |tick| self.shown(tick) >= low),
355                    first_reached(from, to, |tick| self.shown(tick) >= high),
356                ),
357                Direction::Falling => (
358                    first_reached(from, to, |tick| self.shown(tick) < high),
359                    first_reached(from, to, |tick| self.shown(tick) < low),
360                ),
361                Direction::Still => (from, to),
362            };
363            if first < last {
364                let range = TimeRange::new(MediaTime(first), MediaTime(last)).ok()?;
365                match ranges.last_mut() {
366                    Some(previous) if previous.end() == range.start() => {
367                        *previous = TimeRange::new(previous.start(), range.end()).ok()?;
368                    }
369                    _ => ranges.push(range),
370                }
371            }
372        }
373        Some(ranges)
374    }
375
376    /// The timeline times at which the clip's picture reaches source time `instant`: per
377    /// stretch that passes it, the first tick at which the shown time has reached it in that
378    /// stretch's direction. A still stretch passes nothing.
379    #[must_use]
380    pub fn timeline_times(&self, instant: MediaTime) -> Vec<MediaTime> {
381        let at = instant.ticks();
382        let mut times = Vec::new();
383        if self.shown.1 < at || self.shown.0 > at {
384            return times;
385        }
386        for stretch in &self.stretches {
387            if stretch.high < at || stretch.low > at {
388                continue;
389            }
390            let (from, to) = (stretch.from, stretch.to);
391            let found = match stretch.direction {
392                Direction::Rising => first_reached(from, to, |tick| self.shown(tick) >= at),
393                Direction::Falling => first_reached(from, to, |tick| self.shown(tick) <= at),
394                Direction::Still => to,
395            };
396            if found < to {
397                times.push(MediaTime(found));
398            }
399        }
400        times
401    }
402}
403
404fn continues(previous: &Stretch, leg: &Stretch) -> bool {
405    use Direction::{Falling, Rising, Still};
406    match (previous.direction, leg.direction) {
407        (Rising, Rising) => previous.high <= leg.low,
408        (Falling, Falling) => previous.low >= leg.high,
409        (Still | Rising, Still) | (Still, Rising) => previous.high == leg.low,
410        (Falling, Still) | (Still, Falling) => previous.low == leg.high,
411        (Rising, Falling) | (Falling, Rising) => false,
412    }
413}
414
415pub(crate) fn picture_line_breaks(
416    timeline: TimeRange,
417    source: TimeRange,
418    time_map: &TimeMap,
419    frame_rate: FrameRate,
420) -> Option<Vec<i64>> {
421    Some(ClipTimes::new(timeline, source, time_map, frame_rate)?.line_breaks())
422}
423
424/// The first tick in `from..to` at which `reached` holds, for a `reached` that never stops
425/// holding once it does; `to` when it never holds.
426pub(crate) fn first_reached(from: i64, to: i64, reached: impl Fn(i64) -> bool) -> i64 {
427    let (mut low, mut high) = (from, to);
428    while low < high {
429        let middle = low + (high - low) / 2;
430        if reached(middle) {
431            high = middle;
432        } else {
433            low = middle + 1;
434        }
435    }
436    low
437}
438
439/// The timeline ranges of a clip at which its picture shows a source time in
440/// `[range_start, range_end)`, the full preimage of [`picture_source_time`].
441///
442/// Forward and stretched clips give one range, reversed clips one mirrored range, loops one per
443/// pass that reaches the interval, a freeze the whole clip when its instant lies inside the
444/// interval, and a curve one per stretch that reaches it. Ranges are in timeline order and
445/// disjoint. `None` for a time beyond ticks. [`ClipTimes`] answers many of these for one clip.
446#[must_use]
447pub fn source_range_to_timeline(
448    timeline: TimeRange,
449    source: TimeRange,
450    time_map: &TimeMap,
451    frame_rate: FrameRate,
452    range_start: MediaTime,
453    range_end: MediaTime,
454) -> Option<Vec<TimeRange>> {
455    if range_start >= range_end {
456        return Some(Vec::new());
457    }
458    if covers_source(time_map, source, range_start, range_end) {
459        return Some(if timeline.is_empty() || source.is_empty() {
460            Vec::new()
461        } else {
462            vec![timeline]
463        });
464    }
465    ClipTimes::new(timeline, source, time_map, frame_rate)?.timeline_ranges(range_start, range_end)
466}
467
468fn covers_source(time_map: &TimeMap, source: TimeRange, start: MediaTime, end: MediaTime) -> bool {
469    !matches!(time_map, TimeMap::Freeze { .. }) && start <= source.start() && end >= source.end()
470}
471
472/// The timeline times at which a clip's picture reaches source time `instant`: per stretch over
473/// which the shown time moves one way, the first tick at which it has reached `instant` in that
474/// stretch's direction, if the stretch passes it. A freeze passes nothing.
475#[must_use]
476pub fn source_instant_to_timeline(
477    timeline: TimeRange,
478    source: TimeRange,
479    time_map: &TimeMap,
480    frame_rate: FrameRate,
481    instant: MediaTime,
482) -> Option<Vec<MediaTime>> {
483    Some(ClipTimes::new(timeline, source, time_map, frame_rate)?.timeline_times(instant))
484}