alpha2-eval 0.9.0

Pure alpha2 timeline evaluation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use alpha2_model::{LoopMode, TimeMap};
use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};

/// Frame grid that reverse playback and ping-pong backward passes mirror by: frame `k` starts
/// at `floor(k * ticks / per)`, like project frames.
///
/// Pictures mirror by project frame, so a reversed clip shows the forward clip's frames in
/// reverse order at any rate and clip bounds. Sound mirrors by tick, the closest ticks get to the
/// mixer's per-sample mirror.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) struct Mirror {
    ticks: i128,
    per: i128,
}

impl Mirror {
    /// One tick.
    pub(crate) const TICK: Self = Self { ticks: 1, per: 1 };

    /// One frame at `rate`.
    pub(crate) fn frame(rate: FrameRate) -> Self {
        Self {
            ticks: i128::from(TICKS_PER_SECOND) * i128::from(rate.denominator()),
            per: i128::from(rate.numerator()),
        }
    }

    fn start_of(self, frame: i128) -> Option<i128> {
        Some(frame.checked_mul(self.ticks)?.div_euclid(self.per))
    }

    fn frame_of(self, tick: i128) -> Option<i128> {
        Some(
            tick.checked_add(1)?
                .checked_mul(self.per)?
                .checked_sub(1)?
                .div_euclid(self.ticks),
        )
    }

    /// Forward offset `floor(e' * scale / length)` shown by the mirror of `elapsed` in a window
    /// of `length` ticks from `start`.
    ///
    /// With `k0`/`k1` the first/last frames starting in the window and `k` the frame containing
    /// `start + elapsed` (clamped to `k0`), `e'` is `start_of(k0 + k1 - k)` minus the time into
    /// `k`, relative to the window start and floored at zero. A window with no frame start gives 0.
    fn offset(self, start: i128, length: i128, elapsed: i128, scale: i128) -> Option<i128> {
        let first = self.frame_of(start.checked_sub(1)?)?.checked_add(1)?;
        let last = self.frame_of(start.checked_add(length)?.checked_sub(1)?)?;
        if first > last {
            return Some(0);
        }
        let tick = start.checked_add(elapsed)?;
        let frame = self.frame_of(tick)?;
        let (frame, into) = if frame < first {
            (first, 0)
        } else {
            (frame, tick.checked_sub(self.start_of(frame)?)?)
        };
        let mirrored = self
            .start_of(first.checked_add(last)?.checked_sub(frame)?)?
            .checked_sub(into)?
            .checked_sub(start)?;
        if mirrored <= 0 {
            return Some(0);
        }
        Some(mirrored.checked_mul(scale)?.div_euclid(length))
    }
}

/// The source instant a clip shows at timeline `time`, in whole ticks.
///
/// With `e = time - timeline.start`, `T` the timeline duration, `S` the
/// source duration, and `mirror` the frames reversing mirrors by:
///
/// - forward: `source.start + floor(e * S / T)`;
/// - reverse: the forward instant at the mirrored frame less the time into the frame
///   ([`Mirror`]), clamped to the source start;
/// - freeze: its instant;
/// - a repeating loop: `source.start + (e mod S)`;
/// - a ping-pong loop: the same on even passes, mirrored on odd ones;
/// - a curve: the tick it names ([`crate::TimeCurve::shown`]), held inside the source range.
///
/// Returns `None` for an empty range or a value that does not fit in ticks.
pub(crate) fn map_source_time(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    mirror: Mirror,
    time: MediaTime,
) -> Option<MediaTime> {
    let timeline_duration = i128::from(timeline.duration()?.ticks());
    let source_duration = i128::from(source.duration()?.ticks());
    if timeline_duration == 0 || source_duration == 0 {
        return None;
    }
    let elapsed = i128::from(time.ticks()) - i128::from(timeline.start().ticks());
    let offset = match time_map {
        TimeMap::Forward => elapsed
            .checked_mul(source_duration)?
            .div_euclid(timeline_duration),
        TimeMap::Reverse => mirror.offset(
            i128::from(timeline.start().ticks()),
            timeline_duration,
            elapsed,
            source_duration,
        )?,
        TimeMap::Freeze { source_time } => return Some(*source_time),
        TimeMap::Curve { .. } => {
            let shown = crate::TimeCurve::of(time_map)?.shown(time.ticks())?;
            let (first, last) = (source.start().ticks(), source.end().ticks() - 1);
            return Some(MediaTime(shown.clamp(first, last)));
        }
        TimeMap::Loop { mode } => {
            let within = elapsed.rem_euclid(source_duration);
            let pass = elapsed.div_euclid(source_duration);
            match mode {
                LoopMode::PingPong if pass.rem_euclid(2) == 1 => mirror.offset(
                    i128::from(timeline.start().ticks())
                        .checked_add(pass.checked_mul(source_duration)?)?,
                    source_duration,
                    within,
                    source_duration,
                )?,
                LoopMode::Repeat | LoopMode::PingPong => within,
            }
        }
    };
    let mapped = i128::from(source.start().ticks()).checked_add(offset)?;
    i64::try_from(mapped).ok().map(MediaTime::from_ticks)
}

/// The source instant a clip's picture shows at timeline `time`, mirroring by project frames at
/// `frame_rate` exactly as evaluation draws it.
///
/// `tests/golden/time-rules-corpus.json` pins this for the TypeScript port.
///
/// Returns `None` for an empty range or a value that does not fit in ticks.
#[must_use]
pub fn picture_source_time(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    frame_rate: FrameRate,
    time: MediaTime,
) -> Option<MediaTime> {
    map_source_time(timeline, source, time_map, Mirror::frame(frame_rate), time)
}

/// Which way the shown source time moves over a [`Stretch`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Direction {
    /// To later source times, or staying.
    Rising,
    /// To earlier source times, or staying.
    Falling,
    /// One source time throughout.
    Still,
}

/// A span of a clip's timeline over which the shown source time moves one way.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Stretch {
    /// Its first tick.
    pub from: i64,
    /// One past its last tick.
    pub to: i64,
    /// Which way the shown time moves.
    pub direction: Direction,
    /// The least source tick shown in it.
    pub low: i64,
    /// The greatest source tick shown in it.
    pub high: i64,
}

/// A clip's time map with its stretches worked out, for asking where it shows source times.
///
/// Built once per clip and asked many times: every question walks the stretches and searches
/// only those whose shown times can hold the answer.
#[derive(Clone, Debug)]
pub struct ClipTimes<'a> {
    timeline: TimeRange,
    source: TimeRange,
    time_map: &'a TimeMap,
    frame_rate: FrameRate,
    stretches: Vec<Stretch>,
    shown: (i64, i64),
}

pub(crate) const MAX_STRETCHES: usize = 1 << 22;

impl<'a> ClipTimes<'a> {
    /// The stretches of a clip of the two ranges under `time_map`, with pictures mirrored by
    /// project frames at `frame_rate`. `None` for a time beyond ticks or more stretches than a
    /// valid clip has.
    #[must_use]
    pub fn new(
        timeline: TimeRange,
        source: TimeRange,
        time_map: &'a TimeMap,
        frame_rate: FrameRate,
    ) -> Option<Self> {
        let mut times = Self {
            timeline,
            source,
            time_map,
            frame_rate,
            stretches: Vec::new(),
            shown: (i64::MAX, i64::MIN),
        };
        times.stretches = times.work_out()?;
        times.shown = times
            .stretches
            .iter()
            .fold(times.shown, |(low, high), stretch| {
                (low.min(stretch.low), high.max(stretch.high))
            });
        Some(times)
    }

    /// The stretches in timeline order; together they cover the clip.
    #[must_use]
    pub fn stretches(&self) -> &[Stretch] {
        &self.stretches
    }

    fn shown(&self, tick: i64) -> i64 {
        picture_source_time(
            self.timeline,
            self.source,
            self.time_map,
            self.frame_rate,
            MediaTime(tick),
        )
        .map_or(i64::MIN, MediaTime::ticks)
    }

    fn stretch(&self, from: i64, to: i64, direction: Option<Direction>) -> Stretch {
        let (first, last) = (self.shown(from), self.shown(to - 1));
        Stretch {
            from,
            to,
            direction: direction.unwrap_or(match last.cmp(&first) {
                std::cmp::Ordering::Greater => Direction::Rising,
                std::cmp::Ordering::Less => Direction::Falling,
                std::cmp::Ordering::Equal => Direction::Still,
            }),
            low: first.min(last),
            high: first.max(last),
        }
    }

    fn work_out(&self) -> Option<Vec<Stretch>> {
        let (start, end) = (self.timeline.start().ticks(), self.timeline.end().ticks());
        let source_length = self.source.duration()?.ticks();
        if start >= end || source_length <= 0 {
            return Some(Vec::new());
        }
        match self.time_map {
            TimeMap::Forward => Some(vec![self.stretch(start, end, Some(Direction::Rising))]),
            TimeMap::Reverse => Some(vec![self.stretch(start, end, Some(Direction::Falling))]),
            TimeMap::Freeze { .. } => Some(vec![self.stretch(start, end, Some(Direction::Still))]),
            TimeMap::Loop { mode } => {
                let passes = (i128::from(end) - i128::from(start) - 1) / i128::from(source_length);
                let last_end = i128::from(start) + (passes + 1) * i128::from(source_length);
                i64::try_from(last_end).ok()?;
                let passes = usize::try_from(passes + 1)
                    .ok()
                    .filter(|passes| *passes <= MAX_STRETCHES)?;
                let mut stretches = Vec::with_capacity(passes);
                let mut from = start;
                for pass in 0..passes {
                    let to = from.saturating_add(source_length).min(end);
                    let direction = if *mode == LoopMode::PingPong && pass % 2 == 1 {
                        Direction::Falling
                    } else {
                        Direction::Rising
                    };
                    stretches.push(self.stretch(from, to, Some(direction)));
                    from = to;
                }
                Some(stretches)
            }
            TimeMap::Curve { .. } => {
                let cuts = crate::TimeCurve::of(self.time_map)?.cuts(start, end, MAX_STRETCHES)?;
                let mut stretches: Vec<Stretch> = Vec::with_capacity(cuts.len());
                let ends = cuts.iter().skip(1).copied().chain([end]);
                for (from, to) in cuts.iter().copied().zip(ends) {
                    let leg = self.stretch(from, to, None);
                    match stretches.last_mut() {
                        Some(previous) if continues(previous, &leg) => {
                            if previous.direction == Direction::Still {
                                previous.direction = leg.direction;
                            }
                            previous.to = leg.to;
                            previous.low = previous.low.min(leg.low);
                            previous.high = previous.high.max(leg.high);
                        }
                        _ => stretches.push(leg),
                    }
                }
                Some(stretches)
            }
        }
    }

    pub(crate) fn line_breaks(&self) -> Vec<i64> {
        let mut breaks = Vec::new();
        for stretch in &self.stretches {
            let (from, to) = (stretch.from, stretch.to);
            breaks.extend([from, to - 1]);
            if stretch.direction == Direction::Falling {
                let (top, bottom) = (stretch.high, stretch.low);
                breaks.push(first_reached(from, to, |tick| self.shown(tick) < top) - 1);
                breaks.push(first_reached(from, to, |tick| self.shown(tick) <= bottom));
            }
        }
        breaks.sort_unstable();
        breaks.dedup();
        breaks
    }

    /// The timeline ranges at which the clip's picture shows a source time in
    /// `[range_start, range_end)`, in timeline order and disjoint. `None` for a range beyond
    /// ticks.
    #[must_use]
    pub fn timeline_ranges(
        &self,
        range_start: MediaTime,
        range_end: MediaTime,
    ) -> Option<Vec<TimeRange>> {
        if range_start >= range_end {
            return Some(Vec::new());
        }
        let (low, high) = (range_start.ticks(), range_end.ticks());
        if covers_source(self.time_map, self.source, range_start, range_end) {
            return Some(if self.stretches.is_empty() {
                Vec::new()
            } else {
                vec![self.timeline]
            });
        }
        let mut ranges: Vec<TimeRange> = Vec::new();
        if self.shown.1 < low || self.shown.0 >= high {
            return Some(ranges);
        }
        for stretch in &self.stretches {
            if stretch.high < low || stretch.low >= high {
                continue;
            }
            let (from, to) = (stretch.from, stretch.to);
            let (first, last) = match stretch.direction {
                Direction::Rising => (
                    first_reached(from, to, |tick| self.shown(tick) >= low),
                    first_reached(from, to, |tick| self.shown(tick) >= high),
                ),
                Direction::Falling => (
                    first_reached(from, to, |tick| self.shown(tick) < high),
                    first_reached(from, to, |tick| self.shown(tick) < low),
                ),
                Direction::Still => (from, to),
            };
            if first < last {
                let range = TimeRange::new(MediaTime(first), MediaTime(last)).ok()?;
                match ranges.last_mut() {
                    Some(previous) if previous.end() == range.start() => {
                        *previous = TimeRange::new(previous.start(), range.end()).ok()?;
                    }
                    _ => ranges.push(range),
                }
            }
        }
        Some(ranges)
    }

    /// The timeline times at which the clip's picture reaches source time `instant`: per
    /// stretch that passes it, the first tick at which the shown time has reached it in that
    /// stretch's direction. A still stretch passes nothing.
    #[must_use]
    pub fn timeline_times(&self, instant: MediaTime) -> Vec<MediaTime> {
        let at = instant.ticks();
        let mut times = Vec::new();
        if self.shown.1 < at || self.shown.0 > at {
            return times;
        }
        for stretch in &self.stretches {
            if stretch.high < at || stretch.low > at {
                continue;
            }
            let (from, to) = (stretch.from, stretch.to);
            let found = match stretch.direction {
                Direction::Rising => first_reached(from, to, |tick| self.shown(tick) >= at),
                Direction::Falling => first_reached(from, to, |tick| self.shown(tick) <= at),
                Direction::Still => to,
            };
            if found < to {
                times.push(MediaTime(found));
            }
        }
        times
    }
}

fn continues(previous: &Stretch, leg: &Stretch) -> bool {
    use Direction::{Falling, Rising, Still};
    match (previous.direction, leg.direction) {
        (Rising, Rising) => previous.high <= leg.low,
        (Falling, Falling) => previous.low >= leg.high,
        (Still | Rising, Still) | (Still, Rising) => previous.high == leg.low,
        (Falling, Still) | (Still, Falling) => previous.low == leg.high,
        (Rising, Falling) | (Falling, Rising) => false,
    }
}

pub(crate) fn picture_line_breaks(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    frame_rate: FrameRate,
) -> Option<Vec<i64>> {
    Some(ClipTimes::new(timeline, source, time_map, frame_rate)?.line_breaks())
}

/// The first tick in `from..to` at which `reached` holds, for a `reached` that never stops
/// holding once it does; `to` when it never holds.
pub(crate) fn first_reached(from: i64, to: i64, reached: impl Fn(i64) -> bool) -> i64 {
    let (mut low, mut high) = (from, to);
    while low < high {
        let middle = low + (high - low) / 2;
        if reached(middle) {
            high = middle;
        } else {
            low = middle + 1;
        }
    }
    low
}

/// The timeline ranges of a clip at which its picture shows a source time in
/// `[range_start, range_end)`, the full preimage of [`picture_source_time`].
///
/// Forward and stretched clips give one range, reversed clips one mirrored range, loops one per
/// pass that reaches the interval, a freeze the whole clip when its instant lies inside the
/// interval, and a curve one per stretch that reaches it. Ranges are in timeline order and
/// disjoint. `None` for a time beyond ticks. [`ClipTimes`] answers many of these for one clip.
#[must_use]
pub fn source_range_to_timeline(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    frame_rate: FrameRate,
    range_start: MediaTime,
    range_end: MediaTime,
) -> Option<Vec<TimeRange>> {
    if range_start >= range_end {
        return Some(Vec::new());
    }
    if covers_source(time_map, source, range_start, range_end) {
        return Some(if timeline.is_empty() || source.is_empty() {
            Vec::new()
        } else {
            vec![timeline]
        });
    }
    ClipTimes::new(timeline, source, time_map, frame_rate)?.timeline_ranges(range_start, range_end)
}

fn covers_source(time_map: &TimeMap, source: TimeRange, start: MediaTime, end: MediaTime) -> bool {
    !matches!(time_map, TimeMap::Freeze { .. }) && start <= source.start() && end >= source.end()
}

/// The timeline times at which a clip's picture reaches source time `instant`: per stretch over
/// which the shown time moves one way, the first tick at which it has reached `instant` in that
/// stretch's direction, if the stretch passes it. A freeze passes nothing.
#[must_use]
pub fn source_instant_to_timeline(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    frame_rate: FrameRate,
    instant: MediaTime,
) -> Option<Vec<MediaTime>> {
    Some(ClipTimes::new(timeline, source, time_map, frame_rate)?.timeline_times(instant))
}