alpha2-eval 0.10.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
use super::{TimeCurve, end_speed, segment_position, whole, wide, wide_ticks};
use crate::curves::{SegmentKind, narrow};
use crate::{ClipTimes, Stretch, picture_source_time};
use alpha2_model::{
    Extrapolation, Interpolation, LoopMode, MAX_KEYFRAMES, TimeKeyframe, TimeMap, ValueBezier,
};
use alpha2_time::{FrameRate, MediaTime, TimeRange};

/// A playback speed at a timeline time.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SpeedPoint {
    /// The timeline time.
    pub time: MediaTime,
    /// Source time per timeline time there: 1 is the source's own speed, 0 holds, and a
    /// negative speed plays backward.
    pub speed: f64,
}

/// Why [`time_curve_from_speeds`] made no curve.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum TimeCurveError {
    /// Fewer than two points, or every point at one time.
    TooFewPoints,
    /// A point lies before the one it follows.
    NotAscending,
    /// A speed is not finite.
    NotFinite,
    /// The curve would hold more than [`MAX_KEYFRAMES`] keyframes.
    TooManyKeys,
    /// The curve reaches a source time that does not fit in ticks.
    BeyondTicks,
}

impl std::fmt::Display for TimeCurveError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::TooFewPoints => "speed points lie at two times or more",
            Self::NotAscending => "a speed point lies before the one it follows",
            Self::NotFinite => "a speed is not finite",
            Self::TooManyKeys => "the curve would hold too many keyframes",
            Self::BeyondTicks => "the curve reaches a source time that does not fit in ticks",
        })
    }
}

impl std::error::Error for TimeCurveError {}

const LONGEST_HANDLE: f64 = 4_194_304.0;

fn key(
    time: i128,
    source_time: f64,
    interpolation: Interpolation,
) -> Result<TimeKeyframe, TimeCurveError> {
    let tick = |value: Option<i128>| {
        value
            .and_then(|value| i64::try_from(value).ok())
            .map(MediaTime)
            .ok_or(TimeCurveError::BeyondTicks)
    };
    Ok(TimeKeyframe {
        time: tick(Some(time))?,
        source_time: tick(whole(source_time))?,
        interpolation,
    })
}

#[expect(
    clippy::cast_possible_truncation,
    reason = "a count of keyframes, checked against the most a curve holds"
)]
fn parts(speeds: (f64, f64), length: f64, room: usize) -> Result<i128, TimeCurveError> {
    let parts = if speeds.1 - speeds.0 == 0.0 {
        1.0
    } else {
        let handle = speeds.0.abs().max(speeds.1.abs()) * length / 3.0;
        libm::ceil(handle / LONGEST_HANDLE).clamp(1.0, length)
    };
    if parts <= wide(room as i128) {
        Ok(parts as i128)
    } else {
        Err(TimeCurveError::TooManyKeys)
    }
}

fn reach(keys: &[TimeKeyframe]) -> Result<[MediaTime; 2], TimeCurveError> {
    let mut reach = [i64::MAX, i64::MIN];
    let mut add = |tick: i64| reach = [reach[0].min(tick), reach[1].max(tick)];
    for pair in keys.windows(2) {
        add(pair[0].source_time.ticks());
        add(pair[1].source_time.ticks());
        let Interpolation::ValueBezier(curve) = pair[0].interpolation else {
            continue;
        };
        let (from, to) = (
            wide_ticks(pair[0].source_time),
            wide_ticks(pair[1].source_time),
        );
        for turn in curve.turns_between(from, to).into_iter().flatten() {
            let tick = whole(curve.value_between(from, to, turn))
                .and_then(|tick| i64::try_from(tick).ok())
                .ok_or(TimeCurveError::BeyondTicks)?;
            add(tick);
        }
    }
    Ok(reach.map(MediaTime))
}

/// The time curve of a speed that is linear between `points`, playing `source_start` at the
/// first point's time, and the least and greatest source time it names between its points.
///
/// Two points at one time are a jump in speed. The curve's ends are `linear`, so the first
/// and last speeds go on outside the points. Each keyframe holds the integral of the speed
/// from the first point, rounded down to a tick, so rounding does not add up; between
/// keyframes the curve names a source time within one tick of that integral. A ramp is one
/// unweighted `value_bezier` segment; one that covers more source time than its `f32` handles
/// hold to a fraction of a tick is cut into equal parts, with a keyframe between them.
///
/// # Errors
///
/// [`TimeCurveError`]: points at fewer than two times or out of order, a speed that is not
/// finite, or a curve with too many keyframes or beyond ticks.
pub fn time_curve_from_speeds(
    source_start: MediaTime,
    points: &[SpeedPoint],
) -> Result<(TimeMap, [MediaTime; 2]), TimeCurveError> {
    if points.iter().any(|point| !point.speed.is_finite()) {
        return Err(TimeCurveError::NotFinite);
    }
    if points.windows(2).any(|pair| pair[1].time < pair[0].time) {
        return Err(TimeCurveError::NotAscending);
    }
    let start = wide_ticks(source_start);
    let mut keys: Vec<TimeKeyframe> = Vec::new();
    let mut travelled = 0.0;
    for pair in points.windows(2) {
        let (from, to) = (pair[0], pair[1]);
        if from.time == to.time {
            continue;
        }
        let first = i128::from(from.time.ticks());
        let ticks = i128::from(to.time.ticks()) - first;
        let length = wide(ticks);
        let ramp = to.speed - from.speed;
        let count = parts(
            (from.speed, to.speed),
            length,
            (MAX_KEYFRAMES - 1).saturating_sub(keys.len()),
        )?;
        let speed = |elapsed: i128| from.speed + ramp * (wide(elapsed) / length);
        let area = |elapsed: i128| {
            let elapsed = wide(elapsed);
            from.speed * elapsed + ramp * elapsed * elapsed / (2.0 * length)
        };
        for part in 0..count {
            let (left, right) = (ticks * part / count, ticks * (part + 1) / count);
            let interpolation = if ramp == 0.0 {
                Interpolation::Linear
            } else {
                let third = wide(right - left) / 3.0;
                Interpolation::ValueBezier(ValueBezier::unweighted(
                    narrow(speed(left) * third),
                    narrow(0.0 - speed(right) * third),
                ))
            };
            keys.push(key(
                first + left,
                start + (travelled + area(left)),
                interpolation,
            )?);
        }
        travelled += (from.speed + to.speed) * length / 2.0;
    }
    let (Some(last), false) = (points.last(), keys.is_empty()) else {
        return Err(TimeCurveError::TooFewPoints);
    };
    keys.push(key(
        i128::from(last.time.ticks()),
        start + travelled,
        Interpolation::Linear,
    )?);
    let reach = reach(&keys)?;
    let curve = TimeMap::Curve {
        keyframes: keys,
        before: Extrapolation::Linear,
        after: Extrapolation::Linear,
    };
    Ok((curve, reach))
}

/// A clip's time map at one timeline time.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TimeCurveSample {
    /// The source time the map names there, in ticks. A curve's and a forward clip's are not
    /// rounded to a tick, and a curve's is not held inside the source range.
    pub source_time: f64,
    /// How fast the source time moves there, in source ticks per timeline tick: 1 is the
    /// source's own speed. Where the map has a corner it is the speed the map arrives with.
    /// Finite: a vertical tangent gives the largest finite `f64` with its sign.
    pub speed: f64,
}

fn finite(speed: f64) -> f64 {
    if speed.is_nan() {
        0.0
    } else {
        speed.clamp(-f64::MAX, f64::MAX)
    }
}

fn arriving_speed(curve: &TimeCurve<'_>, tick: i64) -> f64 {
    let keys = curve.keys;
    let (start, end, at) = (
        i128::from(curve.first().time.ticks()),
        i128::from(curve.last().time.ticks()),
        i128::from(tick),
    );
    let period = end - start;
    if period <= 0 {
        return 0.0;
    }
    let within = |left: usize, at: i128| {
        let (left, right) = (&keys[left], &keys[left + 1]);
        let elapsed = at - i128::from(left.time.ticks());
        let length = i128::from(right.time.ticks()) - i128::from(left.time.ticks());
        segment_position(left, right, wide(elapsed) / wide(length)).1
    };
    let before = |at: i128| {
        let right = keys.partition_point(|key| i128::from(key.time.ticks()) < at);
        within(right - 1, at)
    };
    let after = |at: i128| {
        let right = keys.partition_point(|key| i128::from(key.time.ticks()) <= at);
        within(right - 1, at)
    };
    let side = if at <= start {
        curve.before
    } else if at > end {
        curve.after
    } else {
        return before(at);
    };
    match side {
        Extrapolation::Hold => 0.0,
        Extrapolation::Linear if at > end => end_speed(&keys[keys.len() - 2], curve.last(), true),
        Extrapolation::Linear => end_speed(curve.first(), &keys[1], false),
        Extrapolation::Repeat | Extrapolation::RepeatOffset => {
            let offset = (at - start).rem_euclid(period);
            before(start + if offset == 0 { period } else { offset })
        }
        Extrapolation::PingPong => {
            let offset = (at - start).rem_euclid(2 * period);
            if offset == 0 {
                0.0 - after(start)
            } else if offset <= period {
                before(start + offset)
            } else {
                0.0 - after(start + 2 * period - offset)
            }
        }
    }
}

/// The source time and speed of a clip of the two ranges under `time_map` at each of `times`,
/// with pictures mirrored by project frames at `frame_rate`.
///
/// A forward clip reports the ratio of its two lengths, a reversed clip that ratio below zero,
/// a freeze 0, a loop 1 or, on the returning passes of a ping-pong, -1, and a curve its slope.
#[must_use]
pub fn sample_time_curve(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    frame_rate: FrameRate,
    times: &[MediaTime],
) -> Vec<TimeCurveSample> {
    let lengths = timeline
        .duration()
        .zip(source.duration())
        .map(|(timeline, source)| (i128::from(timeline.ticks()), i128::from(source.ticks())))
        .filter(|(timeline, source)| *timeline > 0 && *source > 0);
    let first = wide_ticks(source.start());
    let curve = TimeCurve::of(time_map);
    times
        .iter()
        .map(|time| {
            let shown = || {
                picture_source_time(timeline, source, time_map, frame_rate, *time)
                    .map_or(first, wide_ticks)
            };
            let elapsed = i128::from(time.ticks()) - i128::from(timeline.start().ticks());
            let (source_time, speed) = match (time_map, lengths) {
                (TimeMap::Curve { .. }, _) => curve.map_or((first, 0.0), |curve| {
                    (
                        curve.position(wide_ticks(*time)).0,
                        arriving_speed(&curve, time.ticks()),
                    )
                }),
                (TimeMap::Freeze { source_time }, _) => (wide_ticks(*source_time), 0.0),
                (_, None) => (first, 0.0),
                (TimeMap::Forward, Some((length, played))) => {
                    let ratio = wide(played) / wide(length);
                    (first + wide(elapsed) * wide(played) / wide(length), ratio)
                }
                (TimeMap::Reverse, Some((length, played))) => {
                    (shown(), 0.0 - wide(played) / wide(length))
                }
                (TimeMap::Loop { mode }, Some((_, played))) => {
                    let pass = (elapsed - 1).max(0).div_euclid(played);
                    let returning = *mode == LoopMode::PingPong && pass.rem_euclid(2) == 1;
                    (shown(), if returning { -1.0 } else { 1.0 })
                }
            };
            TimeCurveSample {
                source_time,
                speed: finite(speed),
            }
        })
        .collect()
}

/// One segment of a time curve in (timeline ticks, source ticks): its two ends and, for a
/// Bezier kind, its two control points.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TimeControlSegment {
    /// The left keyframe.
    pub start: (i64, i64),
    /// The right keyframe.
    pub end: (i64, i64),
    /// The two inner control points of a Bezier kind, the same for a timing curve and for the
    /// value curve that draws the same line.
    pub controls: Option<[(f64, f64); 2]>,
    /// What draws the segment.
    pub kind: SegmentKind,
}

/// The segments between `keys`, for drawing a time curve and its handles.
#[must_use]
pub fn time_curve_segments(keys: &[TimeKeyframe]) -> Vec<TimeControlSegment> {
    keys.windows(2)
        .map(|pair| {
            let (left, right) = (&pair[0], &pair[1]);
            let (start, length) = (
                wide_ticks(left.time),
                wide_ticks(right.time) - wide_ticks(left.time),
            );
            let (from, to) = (wide_ticks(left.source_time), wide_ticks(right.source_time));
            let (controls, kind) = match left.interpolation {
                Interpolation::Hold => (None, SegmentKind::Hold),
                Interpolation::Linear => (None, SegmentKind::Linear),
                Interpolation::Steps(_) => (None, SegmentKind::Steps),
                Interpolation::Points { .. } => (None, SegmentKind::Points),
                Interpolation::CubicBezier(curve) => (
                    Some([
                        (f64::from(curve.x1), f64::from(curve.y1) * (to - from)),
                        (
                            f64::from(curve.x2),
                            (f64::from(curve.y2) - 1.0) * (to - from),
                        ),
                    ]),
                    SegmentKind::Timing,
                ),
                Interpolation::ValueBezier(curve) => {
                    let (x1, x2) = curve.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
                        (f64::from(x1), f64::from(x2))
                    });
                    (
                        Some([(x1, f64::from(curve.leave)), (x2, f64::from(curve.arrive))]),
                        SegmentKind::Value,
                    )
                }
            };
            TimeControlSegment {
                start: (left.time.ticks(), left.source_time.ticks()),
                end: (right.time.ticks(), right.source_time.ticks()),
                controls: controls.map(|[(x1, leave), (x2, arrive)]| {
                    [
                        (start + x1 * length, from + leave),
                        (start + x2 * length, to + arrive),
                    ]
                }),
                kind,
            }
        })
        .collect()
}

/// The spans of a clip's timeline over which its picture's source time moves one way, in
/// timeline order; together they cover the clip. Pictures are 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 clip_stretches(
    timeline: TimeRange,
    source: TimeRange,
    time_map: &TimeMap,
    frame_rate: FrameRate,
) -> Option<Vec<Stretch>> {
    ClipTimes::new(timeline, source, time_map, frame_rate).map(|times| times.stretches().to_vec())
}

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