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};
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SpeedPoint {
pub time: MediaTime,
pub speed: f64,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum TimeCurveError {
TooFewPoints,
NotAscending,
NotFinite,
TooManyKeys,
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))
}
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))
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TimeCurveSample {
pub source_time: f64,
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)
}
}
}
}
#[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()
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TimeControlSegment {
pub start: (i64, i64),
pub end: (i64, i64),
pub controls: Option<[(f64, f64); 2]>,
pub kind: SegmentKind,
}
#[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()
}
#[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;