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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
//! A keyed time map: the source time a curve names at a timeline time.
//!
//! Line, step and hold segments are exact in integer ticks. Curved segments use the value
//! arithmetic of number curves with the two ends in `f64`, then round down.

use crate::keyed::{Placed, placed};
use alpha2_model::{Extrapolation, Interpolation, TimeKeyframe, TimeMap, ValueBezier};
use alpha2_time::{MediaTime, TimeRange};

mod edits;
mod services;

pub use edits::{insert_time_key, time_auto_tangents};
pub use services::{
    SpeedPoint, TimeControlSegment, TimeCurveError, TimeCurveSample, clip_stretches,
    sample_time_curve, time_curve_from_speeds, time_curve_segments,
};

/// The keyframes of a [`TimeMap::Curve`] and what it does outside them.
#[derive(Copy, Clone, Debug)]
pub struct TimeCurve<'a> {
    /// Its keyframes, ascending in time.
    pub keys: &'a [TimeKeyframe],
    /// What it does before the first keyframe.
    pub before: Extrapolation,
    /// What it does from the last keyframe on.
    pub after: Extrapolation,
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum Spot {
    Keyed {
        segment: usize,
        elapsed: i128,
        passes: i64,
    },
    Last {
        passes: i64,
    },
    Beyond {
        ticks: i128,
    },
}

#[derive(Copy, Clone, Debug, PartialEq)]
struct Place {
    segment: usize,
    pass_start: i64,
    backward: bool,
}

/// A span of a time curve over which the source time moves along one key segment of one pass.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TimePiece {
    /// Its first tick; `i64::MIN` when it reaches back without end.
    pub from: i64,
    /// One past its last tick; `i64::MAX` when it goes on without end.
    pub to: i64,
    /// How the source time moves over it.
    pub motion: PieceMotion,
    /// Whether the source time jumps where the piece starts: a `repeat` end starts over there.
    pub jumps_in: bool,
    /// Whether the source time jumps where the piece ends.
    pub jumps_out: bool,
    place: Option<Place>,
}

/// How the source time moves over a [`TimePiece`].
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PieceMotion {
    /// It stays, steps, or lies outside the source range: there is no sound.
    Level,
    /// Along a line through `source_time` at `time`, moving `by` ticks every `over` ticks.
    Line {
        /// A timeline tick on the line.
        time: i64,
        /// The source tick there.
        source_time: i64,
        /// Timeline ticks, more than zero.
        over: i64,
        /// Source ticks moved in `over`: negative when the line falls, never zero.
        by: i64,
    },
    /// Along a curve, read with [`TimeCurve::position`].
    Curved {
        /// A speed the curve never exceeds on the piece, in source ticks per timeline tick;
        /// infinite when no bound is known.
        steepest: f64,
    },
}

impl PieceMotion {
    const fn line(time: i64, source_time: i64, over: i64, by: i64) -> Self {
        if over > 0 && by != 0 {
            Self::Line {
                time,
                source_time,
                over,
                by,
            }
        } else {
            Self::Level
        }
    }
}

impl TimePiece {
    const fn level(from: i64, to: i64) -> Self {
        Self {
            from,
            to,
            motion: PieceMotion::Level,
            jumps_in: false,
            jumps_out: false,
            place: None,
        }
    }

    fn cut_at(&mut self, cut: i64, tick: i64) {
        if cut <= self.from || cut >= self.to {
            return;
        }
        if tick < cut {
            (self.to, self.jumps_out) = (cut, false);
        } else {
            (self.from, self.jumps_in) = (cut, false);
        }
    }

    fn inside(mut self, tick: i64, source: TimeRange) -> Self {
        let PieceMotion::Line {
            time,
            source_time,
            over,
            by,
        } = self.motion
        else {
            return self;
        };
        let (over, by) = (i128::from(over), i128::from(by));
        let reach =
            |target: MediaTime| (i128::from(target.ticks()) - i128::from(source_time)) * over;
        let at = |offset: i128| {
            i64::try_from(i128::from(time) + offset).unwrap_or(if offset < 0 {
                i64::MIN
            } else {
                i64::MAX
            })
        };
        let floor = |value: i128| (value * by.signum()).div_euclid(by.abs());
        let ceil = |value: i128| -floor(-value);
        let (enters, leaves) = if by > 0 {
            (
                at(ceil(reach(source.start()))),
                at(floor(reach(source.end())) + 1),
            )
        } else {
            (
                at(ceil(reach(source.end()))),
                at(floor(reach(source.start())) + 1),
            )
        };
        if tick < enters {
            return Self::level(self.from, enters.min(self.to));
        }
        if tick >= leaves {
            return Self::level(leaves.max(self.from), self.to);
        }
        self.cut_at(enters, tick);
        self.cut_at(leaves, tick);
        self
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum Motion {
    Line,
    Stairs,
    Bend,
}

impl<'a> TimeCurve<'a> {
    /// The curve of `map`, if it is one with keyframes.
    #[must_use]
    pub fn of(map: &'a TimeMap) -> Option<Self> {
        match map {
            TimeMap::Curve {
                keyframes,
                before,
                after,
            } if !keyframes.is_empty() => Some(Self {
                keys: keyframes,
                before: *before,
                after: *after,
            }),
            _ => None,
        }
    }

    pub(crate) fn first(&self) -> &'a TimeKeyframe {
        &self.keys[0]
    }

    pub(crate) fn last(&self) -> &'a TimeKeyframe {
        &self.keys[self.keys.len() - 1]
    }

    pub(crate) fn rise(&self) -> i128 {
        i128::from(self.last().source_time.ticks()) - i128::from(self.first().source_time.ticks())
    }

    pub(crate) fn spot(&self, tick: i64) -> Spot {
        let (first, last) = (self.first().time, self.last().time);
        match placed(first, last, MediaTime(tick), self.before, self.after) {
            Placed::Beyond { ticks } => Spot::Beyond { ticks },
            Placed::Inside { time, passes } => {
                let next = self.keys.partition_point(|key| key.time <= time);
                let left = next.saturating_sub(1);
                if next >= self.keys.len() {
                    Spot::Last { passes }
                } else {
                    Spot::Keyed {
                        segment: left,
                        elapsed: i128::from(time.ticks())
                            - i128::from(self.keys[left].time.ticks()),
                        passes,
                    }
                }
            }
        }
    }

    /// The source tick the curve names at timeline `tick`, before any clamp to a source range.
    /// `None` when it does not fit in ticks.
    #[must_use]
    pub fn shown(&self, tick: i64) -> Option<i64> {
        let value = match self.spot(tick) {
            Spot::Last { passes } => {
                i128::from(self.last().source_time.ticks()) + i128::from(passes) * self.rise()
            }
            Spot::Keyed {
                segment,
                elapsed,
                passes,
            } => {
                let (left, right) = (&self.keys[segment], &self.keys[segment + 1]);
                segment_tick(left, right, elapsed)? + i128::from(passes) * self.rise()
            }
            Spot::Beyond { ticks } => self.beyond(ticks)?,
        };
        i64::try_from(value).ok()
    }

    pub(crate) fn motion_at(&self, tick: i64) -> Motion {
        let Spot::Keyed { segment, .. } = self.spot(tick) else {
            return Motion::Line;
        };
        let (left, right) = (&self.keys[segment], &self.keys[segment + 1]);
        let level = left.source_time == right.source_time;
        match &left.interpolation {
            Interpolation::ValueBezier(_) => Motion::Bend,
            Interpolation::CubicBezier(_) | Interpolation::Points { .. } if !level => Motion::Bend,
            Interpolation::Steps(_) if !level => Motion::Stairs,
            _ => Motion::Line,
        }
    }

    fn period(&self) -> Option<i64> {
        self.last()
            .time
            .ticks()
            .checked_sub(self.first().time.ticks())
            .filter(|period| *period > 0)
    }

    fn keyed_tick(&self, offset: i64) -> i64 {
        self.first()
            .time
            .ticks()
            .checked_add(offset)
            .and_then(|tick| self.shown(tick))
            .unwrap_or(i64::MIN)
    }

    fn keyed_cuts(&self, period: i64) -> Vec<i64> {
        let start = self.first().time.ticks();
        let mut cuts = Vec::new();
        for segment in 0..self.keys.len() - 1 {
            if segment > 0 {
                cuts.push(self.keys[segment].time.ticks() - start);
            }
            self.turn_cuts(segment, &mut cuts);
        }
        cuts.retain(|cut| *cut > 0 && *cut < period);
        cuts.sort_unstable();
        cuts.dedup();
        cuts
    }

    fn turn_cuts(&self, segment: usize, cuts: &mut Vec<i64>) {
        let start = self.first().time.ticks();
        let (left, right) = (&self.keys[segment], &self.keys[segment + 1]);
        let (from, to) = (left.time.ticks() - start, right.time.ticks() - start);
        let length = wide(i128::from(to - from));
        self.each_turn(segment, |progress| {
            let turn = wide(i128::from(from)) + progress * length;
            self.cuts_around(from, to, turn, cuts);
        });
    }

    fn each_turn(&self, segment: usize, mut each: impl FnMut(f64)) {
        let (left, right) = (&self.keys[segment], &self.keys[segment + 1]);
        let ends = (wide_ticks(left.source_time), wide_ticks(right.source_time));
        let level = left.source_time == right.source_time;
        let mut inside = |progress: f64| {
            if progress > 0.0 && progress < 1.0 {
                each(progress);
            }
        };
        match &left.interpolation {
            Interpolation::CubicBezier(curve) if !level => {
                curve.turns().into_iter().flatten().for_each(inside);
            }
            Interpolation::Points { points } if !level => {
                for point in points {
                    inside(f64::from(point.x));
                }
            }
            Interpolation::ValueBezier(curve) => curve
                .turns_between(ends.0, ends.1)
                .into_iter()
                .flatten()
                .for_each(inside),
            _ => {}
        }
    }

    /// The least and greatest source time the curve names over timeline times `from..=to`
    /// inside `piece`, neither rounded.
    #[must_use]
    pub fn hull(&self, piece: &TimePiece, from: f64, to: f64) -> (f64, f64) {
        let (first, last) = (self.position(from).0, self.position(to).0);
        let mut hull = (first.min(last), first.max(last));
        let Some(place) = piece.place else {
            return hull;
        };
        let (left, right) = (&self.keys[place.segment], &self.keys[place.segment + 1]);
        let (start, length) = (
            wide_ticks(left.time) - wide_ticks(self.first().time),
            wide_ticks(right.time) - wide_ticks(left.time),
        );
        let period = wide_ticks(self.last().time) - wide_ticks(self.first().time);
        self.each_turn(place.segment, |progress| {
            let keyed = start + progress * length;
            let offset = if place.backward {
                period - keyed
            } else {
                keyed
            };
            let time = wide(i128::from(place.pass_start)) + offset;
            if time > from && time < to {
                let value = self.position(time).0;
                hull = (hull.0.min(value), hull.1.max(value));
            }
        });
        hull
    }

    #[expect(clippy::cast_possible_truncation, reason = "a tick inside the segment")]
    fn cuts_around(&self, from: i64, to: i64, turn: f64, cuts: &mut Vec<i64>) {
        const TICKS_EITHER_SIDE: i64 = 2;
        let at = libm::floor(turn) as i64;
        let first = (at - TICKS_EITHER_SIDE).max(from);
        let last = (at + 1 + TICKS_EITHER_SIDE).min(to);
        cuts.extend([first, last]);
        let mut run_start = first;
        let mut previous = self.keyed_tick(first);
        let mut moving = std::cmp::Ordering::Equal;
        for offset in first + 1..=last {
            let value = self.keyed_tick(offset);
            let step = value.cmp(&previous);
            if step == std::cmp::Ordering::Equal {
                continue;
            }
            if moving != std::cmp::Ordering::Equal && step != moving {
                cuts.push(run_start);
            }
            (moving, run_start, previous) = (step, offset, value);
        }
    }

    pub(crate) fn cuts(&self, from: i64, to: i64, most: usize) -> Option<Vec<i64>> {
        let mut cuts = vec![from];
        let Some(period) = self.period() else {
            return Some(cuts);
        };
        let (start, end) = (self.first().time.ticks(), self.last().time.ticks());
        let keyed = self.keyed_cuts(period);
        let repeats = |extrapolation| {
            matches!(
                extrapolation,
                Extrapolation::Repeat | Extrapolation::RepeatOffset | Extrapolation::PingPong
            )
        };
        let pass_of = |tick: i64| {
            let pass = (i128::from(tick) - i128::from(start)).div_euclid(i128::from(period));
            if (pass < 0 && !repeats(self.before)) || (pass > 0 && !repeats(self.after)) {
                0
            } else {
                pass
            }
        };
        let (first_pass, last_pass) = (
            pass_of(from),
            pass_of(to.saturating_sub(1)).max(pass_of(from)),
        );
        let passes = usize::try_from(last_pass - first_pass + 1).ok()?;
        if passes.checked_mul(keyed.len() + 2)? > most {
            return None;
        }
        let mut pass_cuts = Vec::with_capacity(keyed.len() + 1);
        for pass in first_pass..=last_pass {
            let pass_start = i128::from(start) + pass * i128::from(period);
            let side = if pass < 0 { self.before } else { self.after };
            let backward = pass != 0 && side == Extrapolation::PingPong && pass.rem_euclid(2) == 1;
            pass_cuts.clear();
            pass_cuts.push(pass_start);
            pass_cuts.extend(keyed.iter().map(|cut| {
                pass_start
                    + if backward {
                        i128::from(period) - i128::from(*cut) + 1
                    } else {
                        i128::from(*cut)
                    }
            }));
            pass_cuts.sort_unstable();
            cuts.extend(
                pass_cuts
                    .iter()
                    .filter_map(|cut| i64::try_from(*cut).ok())
                    .filter(|cut| *cut > from && *cut < to),
            );
        }
        if end > from && end < to {
            cuts.push(end);
        }
        cuts.sort_unstable();
        cuts.dedup();
        Some(cuts)
    }

    /// The piece of the curve that timeline `tick` falls on, for reading sound along it:
    /// one key segment on one pass, cut where a line leaves `source`.
    #[must_use]
    pub fn piece(&self, tick: i64, source: TimeRange) -> TimePiece {
        let (first, last) = (self.first().time.ticks(), self.last().time.ticks());
        let Some(period) = self.period() else {
            return TimePiece::level(i64::MIN, i64::MAX);
        };
        let side = if tick < first {
            Some(self.before)
        } else if tick >= last {
            Some(self.after)
        } else {
            None
        };
        let at_end = tick >= last;
        match side {
            Some(Extrapolation::Hold) if at_end => TimePiece::level(last, i64::MAX),
            Some(Extrapolation::Hold) => TimePiece::level(i64::MIN, first),
            Some(Extrapolation::Linear) => self.continued_piece(at_end).inside(tick, source),
            _ => self
                .keyed_piece(tick, period, side)
                .map_or(TimePiece::level(tick, tick.saturating_add(1)), |piece| {
                    piece.inside(tick, source)
                }),
        }
    }

    fn continued_piece(&self, at_end: bool) -> TimePiece {
        let (left, right) = self.end_segment(at_end);
        let edge = if at_end { right } else { left };
        let (from, to) = if at_end {
            (edge.time.ticks(), i64::MAX)
        } else {
            (i64::MIN, edge.time.ticks())
        };
        let over = right.time.ticks().saturating_sub(left.time.ticks());
        let by = right
            .source_time
            .ticks()
            .saturating_sub(left.source_time.ticks());
        let motion = if matches!(left.interpolation, Interpolation::Linear) {
            PieceMotion::line(edge.time.ticks(), edge.source_time.ticks(), over, by)
        } else {
            let speed = end_speed(left, right, at_end);
            if speed.is_finite() && speed != 0.0 {
                PieceMotion::Curved {
                    steepest: speed.abs(),
                }
            } else {
                PieceMotion::Level
            }
        };
        TimePiece {
            from,
            to,
            motion,
            jumps_in: false,
            jumps_out: false,
            place: None,
        }
    }

    fn keyed_piece(
        &self,
        tick: i64,
        period: i64,
        side: Option<Extrapolation>,
    ) -> Option<TimePiece> {
        let first = self.first().time.ticks();
        let pass = match side {
            None => 0,
            Some(_) => (i128::from(tick) - i128::from(first)).div_euclid(i128::from(period)),
        };
        let pass_start = i64::try_from(i128::from(first) + pass * i128::from(period)).ok()?;
        let backward = side == Some(Extrapolation::PingPong) && pass.rem_euclid(2) == 1;
        let offset = tick.checked_sub(pass_start)?;
        let keyed = if backward { period - offset } else { offset };
        let after = |key: &TimeKeyframe| {
            let at = key.time.ticks() - first;
            if backward { at < keyed } else { at <= keyed }
        };
        let segment = self.keys.partition_point(after).checked_sub(1)?;
        let (left, right) = (self.keys.get(segment)?, self.keys.get(segment + 1)?);
        let (start, end) = (left.time.ticks() - first, right.time.ticks() - first);
        let (from, to) = if backward {
            (period - end, period - start)
        } else {
            (start, end)
        };
        let (from, to) = (pass_start.checked_add(from)?, pass_start.checked_add(to)?);
        let raised = if side == Some(Extrapolation::RepeatOffset) {
            i64::try_from(pass * self.rise()).ok()?
        } else {
            0
        };
        let change = right
            .source_time
            .ticks()
            .checked_sub(left.source_time.ticks())?;
        let (leaves, by) = if backward {
            (right.source_time.ticks(), change.checked_neg()?)
        } else {
            (left.source_time.ticks(), change)
        };
        let motion = match &left.interpolation {
            Interpolation::Hold | Interpolation::Steps(_) => PieceMotion::Level,
            Interpolation::Linear => {
                PieceMotion::line(from, leaves.checked_add(raised)?, end - start, by)
            }
            Interpolation::CubicBezier(_) | Interpolation::Points { .. } if change == 0 => {
                PieceMotion::Level
            }
            Interpolation::CubicBezier(_) | Interpolation::Points { .. } => PieceMotion::Curved {
                steepest: f64::INFINITY,
            },
            Interpolation::ValueBezier(curve) => PieceMotion::Curved {
                steepest: steepest(*curve, left, right),
            },
        };
        let wraps = |pass_after: bool| {
            let end = if pass_after { self.after } else { self.before };
            end == Extrapolation::Repeat
        };
        let last = self.keys.len() - 2;
        Some(TimePiece {
            from,
            to,
            motion,
            jumps_in: segment == if backward { last } else { 0 } && wraps(pass >= 1),
            jumps_out: segment == if backward { 0 } else { last } && wraps(pass >= 0),
            place: Some(Place {
                segment,
                pass_start,
                backward,
            }),
        })
    }

    fn end_segment(&self, at_end: bool) -> (&'a TimeKeyframe, &'a TimeKeyframe) {
        let count = self.keys.len();
        if at_end && count >= 2 {
            (&self.keys[count - 2], &self.keys[count - 1])
        } else {
            (self.first(), &self.keys[1.min(count - 1)])
        }
    }

    fn beyond(&self, ticks: i128) -> Option<i128> {
        let at_end = ticks > 0;
        let (left, right) = self.end_segment(at_end);
        let edge = i128::from(if at_end { right } else { left }.source_time.ticks());
        let length = i128::from(right.time.ticks()) - i128::from(left.time.ticks());
        if length <= 0 {
            return Some(edge);
        }
        let change = i128::from(right.source_time.ticks()) - i128::from(left.source_time.ticks());
        if matches!(left.interpolation, Interpolation::Linear) {
            return Some(edge + ticks.checked_mul(change)?.div_euclid(length));
        }
        whole(continued(left, right, at_end, wide(ticks) / wide(length)))
    }

    /// The source time the curve names at timeline time `time`, both in ticks and neither
    /// rounded, with the speed there in source ticks per timeline tick.
    ///
    /// At a keyframe the value is the keyframe's and the speed that of the segment after it;
    /// inside a `steps` segment the value is the step's and the speed zero.
    #[must_use]
    pub fn position(&self, time: f64) -> (f64, f64) {
        let (first, last) = (self.first(), self.last());
        let (start, end) = (wide_ticks(first.time), wide_ticks(last.time));
        let period = end - start;
        let rise = wide_ticks(last.source_time) - wide_ticks(first.source_time);
        let side = if time < start {
            self.before
        } else if time > end
            || (time >= end
                && matches!(
                    self.after,
                    Extrapolation::Repeat | Extrapolation::RepeatOffset
                ))
        {
            self.after
        } else {
            return self.keyed_position(time);
        };
        let edge = if time < start { first } else { last };
        if period <= 0.0 {
            return (wide_ticks(edge.source_time), 0.0);
        }
        match side {
            Extrapolation::Hold => (wide_ticks(edge.source_time), 0.0),
            Extrapolation::Linear => {
                let at_end = time >= end;
                let (left, right) = self.end_segment(at_end);
                let length = wide_ticks(right.time) - wide_ticks(left.time);
                let outside = (time - if at_end { end } else { start }) / length;
                (
                    continued(left, right, at_end, outside),
                    end_speed(left, right, at_end),
                )
            }
            Extrapolation::Repeat | Extrapolation::RepeatOffset => {
                let passes = libm::floor((time - start) / period);
                let (value, speed) = self.keyed_position(time - passes * period);
                let offset = if side == Extrapolation::RepeatOffset {
                    passes * rise
                } else {
                    0.0
                };
                (value + offset, speed)
            }
            Extrapolation::PingPong => {
                let double = 2.0 * period;
                let offset = (time - start) - libm::floor((time - start) / double) * double;
                if offset <= period {
                    self.keyed_position(start + offset)
                } else {
                    let (value, speed) = self.keyed_position(start + (double - offset));
                    (value, -speed)
                }
            }
        }
    }

    fn keyed_position(&self, time: f64) -> (f64, f64) {
        let next = self
            .keys
            .partition_point(|key| wide_ticks(key.time) <= time);
        let Some(right) = self.keys.get(next) else {
            return (wide_ticks(self.last().source_time), 0.0);
        };
        let Some(left) = next.checked_sub(1).map(|index| &self.keys[index]) else {
            return (wide_ticks(self.first().source_time), 0.0);
        };
        let length = wide_ticks(right.time) - wide_ticks(left.time);
        segment_position(left, right, (time - wide_ticks(left.time)) / length)
    }
}

fn segment_position(left: &TimeKeyframe, right: &TimeKeyframe, progress: f64) -> (f64, f64) {
    let (from, to) = (wide_ticks(left.source_time), wide_ticks(right.source_time));
    let length = wide_ticks(right.time) - wide_ticks(left.time);
    match &left.interpolation {
        Interpolation::Hold => (from, 0.0),
        Interpolation::Linear => (from + (to - from) * progress, (to - from) / length),
        Interpolation::Steps(_) if progress <= 0.0 => (from, 0.0),
        Interpolation::Steps(steps) => (from + (to - from) * steps.apply(progress), 0.0),
        Interpolation::CubicBezier(curve) => (
            from + (to - from) * curve.apply(progress),
            (to - from) * curve.slope(progress) / length,
        ),
        Interpolation::Points { points } => (
            from + (to - from) * alpha2_model::easing_points_at(points, progress),
            (to - from) * alpha2_model::easing_points_slope(points, progress) / length,
        ),
        Interpolation::ValueBezier(curve) => (
            curve.value_between(from, to, progress),
            curve.slope_between(from, to, progress) / length,
        ),
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "ticks are whole below 2^53, far past any media time"
)]
pub(crate) const fn wide(ticks: i128) -> f64 {
    ticks as f64
}

pub(crate) const fn wide_ticks(time: MediaTime) -> f64 {
    wide(time.ticks() as i128)
}

/// `value` rounded down to a whole tick. `None` for a value that is not finite.
#[expect(
    clippy::cast_possible_truncation,
    reason = "a float to integer cast saturates"
)]
fn whole(value: f64) -> Option<i128> {
    value.is_finite().then(|| libm::floor(value) as i128)
}

fn scaled(elapsed: i128, change: i128, length: i128) -> Option<i128> {
    if let (Ok(elapsed), Ok(change), Ok(length)) = (
        i64::try_from(elapsed),
        i64::try_from(change),
        i64::try_from(length),
    ) && let Some(product) = elapsed.checked_mul(change)
    {
        return Some(i128::from(product.div_euclid(length)));
    }
    Some(elapsed.checked_mul(change)?.div_euclid(length))
}

fn segment_tick(left: &TimeKeyframe, right: &TimeKeyframe, elapsed: i128) -> Option<i128> {
    let from = i128::from(left.source_time.ticks());
    if elapsed == 0 {
        return Some(from);
    }
    let change = i128::from(right.source_time.ticks()) - from;
    let length = i128::from(right.time.ticks()) - i128::from(left.time.ticks());
    let amount = |amount: f64| whole(wide(from) + wide(change) * amount);
    let progress = || wide(elapsed) / wide(length);
    match &left.interpolation {
        Interpolation::Hold => Some(from),
        Interpolation::Linear => Some(from + scaled(elapsed, change, length)?),
        Interpolation::Steps(steps) => {
            let (rises, of) = steps.fraction(steps.index(elapsed, length));
            Some(from + rises.checked_mul(change)?.div_euclid(of))
        }
        Interpolation::CubicBezier(curve) => amount(curve.apply(progress())),
        Interpolation::Points { points } => {
            amount(alpha2_model::easing_points_at(points, progress()))
        }
        Interpolation::ValueBezier(curve) => {
            whole(curve.value_between(wide(from), wide(from + change), progress()))
        }
    }
}

fn continued(left: &TimeKeyframe, right: &TimeKeyframe, at_end: bool, outside: f64) -> f64 {
    let (from, to) = (wide_ticks(left.source_time), wide_ticks(right.source_time));
    let edge = if at_end { to } else { from };
    match &left.interpolation {
        Interpolation::ValueBezier(curve) => {
            edge + curve.end_slope_between(from, to, at_end) * outside
        }
        timing => match timing.end_slope(at_end) {
            Some(slope) if slope != 0.0 => {
                from + (to - from) * (if at_end { 1.0 } else { 0.0 } + slope * outside)
            }
            _ => edge,
        },
    }
}

fn steepest(curve: ValueBezier, left: &TimeKeyframe, right: &TimeKeyframe) -> f64 {
    if curve.weights().is_some() {
        return f64::INFINITY;
    }
    let (from, to) = (wide_ticks(left.source_time), wide_ticks(right.source_time));
    let (leave, arrive) = (f64::from(curve.leave), f64::from(curve.arrive));
    let legs = [leave, to + arrive - from - leave, arrive];
    let longest = legs
        .iter()
        .fold(0.0_f64, |longest, leg| longest.max(leg.abs()));
    3.0 * longest / (wide_ticks(right.time) - wide_ticks(left.time))
}

fn end_speed(left: &TimeKeyframe, right: &TimeKeyframe, at_end: bool) -> f64 {
    let (from, to) = (wide_ticks(left.source_time), wide_ticks(right.source_time));
    let length = wide_ticks(right.time) - wide_ticks(left.time);
    match &left.interpolation {
        Interpolation::ValueBezier(curve) => curve.end_slope_between(from, to, at_end) / length,
        timing => (to - from) * timing.end_slope(at_end).unwrap_or(0.0) / length,
    }
}

#[cfg(test)]
#[path = "time_curve_tests.rs"]
mod tests;