1use super::{TimeCurve, end_speed, segment_position, whole, wide, wide_ticks};
2use crate::curves::{SegmentKind, narrow};
3use crate::{ClipTimes, Stretch, picture_source_time};
4use alpha2_model::{
5 Extrapolation, Interpolation, LoopMode, MAX_KEYFRAMES, TimeKeyframe, TimeMap, ValueBezier,
6};
7use alpha2_time::{FrameRate, MediaTime, TimeRange};
8
9#[derive(Copy, Clone, Debug, PartialEq)]
11pub struct SpeedPoint {
12 pub time: MediaTime,
14 pub speed: f64,
17}
18
19#[derive(Copy, Clone, Debug, Eq, PartialEq)]
21pub enum TimeCurveError {
22 TooFewPoints,
24 NotAscending,
26 NotFinite,
28 TooManyKeys,
30 BeyondTicks,
32}
33
34impl std::fmt::Display for TimeCurveError {
35 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 formatter.write_str(match self {
37 Self::TooFewPoints => "speed points lie at two times or more",
38 Self::NotAscending => "a speed point lies before the one it follows",
39 Self::NotFinite => "a speed is not finite",
40 Self::TooManyKeys => "the curve would hold too many keyframes",
41 Self::BeyondTicks => "the curve reaches a source time that does not fit in ticks",
42 })
43 }
44}
45
46impl std::error::Error for TimeCurveError {}
47
48const LONGEST_HANDLE: f64 = 4_194_304.0;
49
50fn key(
51 time: i128,
52 source_time: f64,
53 interpolation: Interpolation,
54) -> Result<TimeKeyframe, TimeCurveError> {
55 let tick = |value: Option<i128>| {
56 value
57 .and_then(|value| i64::try_from(value).ok())
58 .map(MediaTime)
59 .ok_or(TimeCurveError::BeyondTicks)
60 };
61 Ok(TimeKeyframe {
62 time: tick(Some(time))?,
63 source_time: tick(whole(source_time))?,
64 interpolation,
65 })
66}
67
68#[expect(
69 clippy::cast_possible_truncation,
70 reason = "a count of keyframes, checked against the most a curve holds"
71)]
72fn parts(speeds: (f64, f64), length: f64, room: usize) -> Result<i128, TimeCurveError> {
73 let parts = if speeds.1 - speeds.0 == 0.0 {
74 1.0
75 } else {
76 let handle = speeds.0.abs().max(speeds.1.abs()) * length / 3.0;
77 libm::ceil(handle / LONGEST_HANDLE).clamp(1.0, length)
78 };
79 if parts <= wide(room as i128) {
80 Ok(parts as i128)
81 } else {
82 Err(TimeCurveError::TooManyKeys)
83 }
84}
85
86fn reach(keys: &[TimeKeyframe]) -> Result<[MediaTime; 2], TimeCurveError> {
87 let mut reach = [i64::MAX, i64::MIN];
88 let mut add = |tick: i64| reach = [reach[0].min(tick), reach[1].max(tick)];
89 for pair in keys.windows(2) {
90 add(pair[0].source_time.ticks());
91 add(pair[1].source_time.ticks());
92 let Interpolation::ValueBezier(curve) = pair[0].interpolation else {
93 continue;
94 };
95 let (from, to) = (
96 wide_ticks(pair[0].source_time),
97 wide_ticks(pair[1].source_time),
98 );
99 for turn in curve.turns_between(from, to).into_iter().flatten() {
100 let tick = whole(curve.value_between(from, to, turn))
101 .and_then(|tick| i64::try_from(tick).ok())
102 .ok_or(TimeCurveError::BeyondTicks)?;
103 add(tick);
104 }
105 }
106 Ok(reach.map(MediaTime))
107}
108
109pub fn time_curve_from_speeds(
124 source_start: MediaTime,
125 points: &[SpeedPoint],
126) -> Result<(TimeMap, [MediaTime; 2]), TimeCurveError> {
127 if points.iter().any(|point| !point.speed.is_finite()) {
128 return Err(TimeCurveError::NotFinite);
129 }
130 if points.windows(2).any(|pair| pair[1].time < pair[0].time) {
131 return Err(TimeCurveError::NotAscending);
132 }
133 let start = wide_ticks(source_start);
134 let mut keys: Vec<TimeKeyframe> = Vec::new();
135 let mut travelled = 0.0;
136 for pair in points.windows(2) {
137 let (from, to) = (pair[0], pair[1]);
138 if from.time == to.time {
139 continue;
140 }
141 let first = i128::from(from.time.ticks());
142 let ticks = i128::from(to.time.ticks()) - first;
143 let length = wide(ticks);
144 let ramp = to.speed - from.speed;
145 let count = parts(
146 (from.speed, to.speed),
147 length,
148 (MAX_KEYFRAMES - 1).saturating_sub(keys.len()),
149 )?;
150 let speed = |elapsed: i128| from.speed + ramp * (wide(elapsed) / length);
151 let area = |elapsed: i128| {
152 let elapsed = wide(elapsed);
153 from.speed * elapsed + ramp * elapsed * elapsed / (2.0 * length)
154 };
155 for part in 0..count {
156 let (left, right) = (ticks * part / count, ticks * (part + 1) / count);
157 let interpolation = if ramp == 0.0 {
158 Interpolation::Linear
159 } else {
160 let third = wide(right - left) / 3.0;
161 Interpolation::ValueBezier(ValueBezier::unweighted(
162 narrow(speed(left) * third),
163 narrow(0.0 - speed(right) * third),
164 ))
165 };
166 keys.push(key(
167 first + left,
168 start + (travelled + area(left)),
169 interpolation,
170 )?);
171 }
172 travelled += (from.speed + to.speed) * length / 2.0;
173 }
174 let (Some(last), false) = (points.last(), keys.is_empty()) else {
175 return Err(TimeCurveError::TooFewPoints);
176 };
177 keys.push(key(
178 i128::from(last.time.ticks()),
179 start + travelled,
180 Interpolation::Linear,
181 )?);
182 let reach = reach(&keys)?;
183 let curve = TimeMap::Curve {
184 keyframes: keys,
185 before: Extrapolation::Linear,
186 after: Extrapolation::Linear,
187 };
188 Ok((curve, reach))
189}
190
191#[derive(Copy, Clone, Debug, PartialEq)]
193pub struct TimeCurveSample {
194 pub source_time: f64,
197 pub speed: f64,
201}
202
203fn finite(speed: f64) -> f64 {
204 if speed.is_nan() {
205 0.0
206 } else {
207 speed.clamp(-f64::MAX, f64::MAX)
208 }
209}
210
211fn arriving_speed(curve: &TimeCurve<'_>, tick: i64) -> f64 {
212 let keys = curve.keys;
213 let (start, end, at) = (
214 i128::from(curve.first().time.ticks()),
215 i128::from(curve.last().time.ticks()),
216 i128::from(tick),
217 );
218 let period = end - start;
219 if period <= 0 {
220 return 0.0;
221 }
222 let within = |left: usize, at: i128| {
223 let (left, right) = (&keys[left], &keys[left + 1]);
224 let elapsed = at - i128::from(left.time.ticks());
225 let length = i128::from(right.time.ticks()) - i128::from(left.time.ticks());
226 segment_position(left, right, wide(elapsed) / wide(length)).1
227 };
228 let before = |at: i128| {
229 let right = keys.partition_point(|key| i128::from(key.time.ticks()) < at);
230 within(right - 1, at)
231 };
232 let after = |at: i128| {
233 let right = keys.partition_point(|key| i128::from(key.time.ticks()) <= at);
234 within(right - 1, at)
235 };
236 let side = if at <= start {
237 curve.before
238 } else if at > end {
239 curve.after
240 } else {
241 return before(at);
242 };
243 match side {
244 Extrapolation::Hold => 0.0,
245 Extrapolation::Linear if at > end => end_speed(&keys[keys.len() - 2], curve.last(), true),
246 Extrapolation::Linear => end_speed(curve.first(), &keys[1], false),
247 Extrapolation::Repeat | Extrapolation::RepeatOffset => {
248 let offset = (at - start).rem_euclid(period);
249 before(start + if offset == 0 { period } else { offset })
250 }
251 Extrapolation::PingPong => {
252 let offset = (at - start).rem_euclid(2 * period);
253 if offset == 0 {
254 0.0 - after(start)
255 } else if offset <= period {
256 before(start + offset)
257 } else {
258 0.0 - after(start + 2 * period - offset)
259 }
260 }
261 }
262}
263
264#[must_use]
270pub fn sample_time_curve(
271 timeline: TimeRange,
272 source: TimeRange,
273 time_map: &TimeMap,
274 frame_rate: FrameRate,
275 times: &[MediaTime],
276) -> Vec<TimeCurveSample> {
277 let lengths = timeline
278 .duration()
279 .zip(source.duration())
280 .map(|(timeline, source)| (i128::from(timeline.ticks()), i128::from(source.ticks())))
281 .filter(|(timeline, source)| *timeline > 0 && *source > 0);
282 let first = wide_ticks(source.start());
283 let curve = TimeCurve::of(time_map);
284 times
285 .iter()
286 .map(|time| {
287 let shown = || {
288 picture_source_time(timeline, source, time_map, frame_rate, *time)
289 .map_or(first, wide_ticks)
290 };
291 let elapsed = i128::from(time.ticks()) - i128::from(timeline.start().ticks());
292 let (source_time, speed) = match (time_map, lengths) {
293 (TimeMap::Curve { .. }, _) => curve.map_or((first, 0.0), |curve| {
294 (
295 curve.position(wide_ticks(*time)).0,
296 arriving_speed(&curve, time.ticks()),
297 )
298 }),
299 (TimeMap::Freeze { source_time }, _) => (wide_ticks(*source_time), 0.0),
300 (_, None) => (first, 0.0),
301 (TimeMap::Forward, Some((length, played))) => {
302 let ratio = wide(played) / wide(length);
303 (first + wide(elapsed) * wide(played) / wide(length), ratio)
304 }
305 (TimeMap::Reverse, Some((length, played))) => {
306 (shown(), 0.0 - wide(played) / wide(length))
307 }
308 (TimeMap::Loop { mode }, Some((_, played))) => {
309 let pass = (elapsed - 1).max(0).div_euclid(played);
310 let returning = *mode == LoopMode::PingPong && pass.rem_euclid(2) == 1;
311 (shown(), if returning { -1.0 } else { 1.0 })
312 }
313 };
314 TimeCurveSample {
315 source_time,
316 speed: finite(speed),
317 }
318 })
319 .collect()
320}
321
322#[derive(Copy, Clone, Debug, PartialEq)]
325pub struct TimeControlSegment {
326 pub start: (i64, i64),
328 pub end: (i64, i64),
330 pub controls: Option<[(f64, f64); 2]>,
333 pub kind: SegmentKind,
335}
336
337#[must_use]
339pub fn time_curve_segments(keys: &[TimeKeyframe]) -> Vec<TimeControlSegment> {
340 keys.windows(2)
341 .map(|pair| {
342 let (left, right) = (&pair[0], &pair[1]);
343 let (start, length) = (
344 wide_ticks(left.time),
345 wide_ticks(right.time) - wide_ticks(left.time),
346 );
347 let (from, to) = (wide_ticks(left.source_time), wide_ticks(right.source_time));
348 let (controls, kind) = match left.interpolation {
349 Interpolation::Hold => (None, SegmentKind::Hold),
350 Interpolation::Linear => (None, SegmentKind::Linear),
351 Interpolation::Steps(_) => (None, SegmentKind::Steps),
352 Interpolation::Points { .. } => (None, SegmentKind::Points),
353 Interpolation::CubicBezier(curve) => (
354 Some([
355 (f64::from(curve.x1), f64::from(curve.y1) * (to - from)),
356 (
357 f64::from(curve.x2),
358 (f64::from(curve.y2) - 1.0) * (to - from),
359 ),
360 ]),
361 SegmentKind::Timing,
362 ),
363 Interpolation::ValueBezier(curve) => {
364 let (x1, x2) = curve.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
365 (f64::from(x1), f64::from(x2))
366 });
367 (
368 Some([(x1, f64::from(curve.leave)), (x2, f64::from(curve.arrive))]),
369 SegmentKind::Value,
370 )
371 }
372 };
373 TimeControlSegment {
374 start: (left.time.ticks(), left.source_time.ticks()),
375 end: (right.time.ticks(), right.source_time.ticks()),
376 controls: controls.map(|[(x1, leave), (x2, arrive)]| {
377 [
378 (start + x1 * length, from + leave),
379 (start + x2 * length, to + arrive),
380 ]
381 }),
382 kind,
383 }
384 })
385 .collect()
386}
387
388#[must_use]
392pub fn clip_stretches(
393 timeline: TimeRange,
394 source: TimeRange,
395 time_map: &TimeMap,
396 frame_rate: FrameRate,
397) -> Option<Vec<Stretch>> {
398 ClipTimes::new(timeline, source, time_map, frame_rate).map(|times| times.stretches().to_vec())
399}
400
401#[cfg(test)]
402#[path = "services_tests.rs"]
403mod tests;