Skip to main content

alpha2_model/
time_map.rs

1//! How a clip's timeline time maps onto its source range.
2
3use crate::{Extrapolation, Interpolation, MAX_KEYFRAMES};
4use alpha2_time::{MediaTime, TimeRange};
5use serde::{Deserialize, Serialize};
6
7/// How a clip plays its source range over its timeline range.
8///
9/// `forward` and `reverse` stretch the source range over the timeline range, so their speed
10/// is the ratio of the two. A loop plays the source range at its own speed for as long as the
11/// timeline range lasts. A curve names the source time at each timeline time, at any speed and
12/// in either direction.
13#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
14#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
15#[serde(tag = "type", rename_all = "snake_case", from = "TimeMapWire")]
16pub enum TimeMap {
17    /// From the start of the source range to its end.
18    #[default]
19    Forward,
20    /// From the end of the source range to its start: pictures in reverse order and sound
21    /// played backwards.
22    Reverse,
23    /// One source instant for the whole clip, and silence.
24    Freeze {
25        /// The instant shown; inside the source range.
26        source_time: MediaTime,
27    },
28    /// The source range again and again, at its own speed.
29    Loop {
30        /// How each pass follows the one before.
31        mode: LoopMode,
32    },
33    /// Source time keyed over timeline time: speed ramps, reverse play and holds in one clip.
34    ///
35    /// The picture shows the curve's value rounded down to a tick and held inside
36    /// `source_range`; a falling stretch shows the instants it names, so it is not `reverse`'s
37    /// mirror by frame. Sound follows the curve and is silent where it stands still.
38    Curve {
39        /// 2 to [`MAX_KEYFRAMES`] keyframes, strictly ascending in time. They may lie outside
40        /// the clip's timeline range.
41        keyframes: Vec<TimeKeyframe>,
42        /// What the curve does before the first keyframe.
43        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
44        before: Extrapolation,
45        /// What the curve does from the last keyframe on.
46        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
47        after: Extrapolation,
48    },
49}
50
51/// The wire form of [`TimeMap`]: empty struct variants reject extra fields
52/// where serde's unit variants would ignore them.
53#[derive(Deserialize)]
54#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
55#[cfg_attr(feature = "schema", schemars(rename = "TimeMap"))]
56#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
57pub(crate) enum TimeMapWire {
58    /// From the start of the source range to its end.
59    Forward {},
60    /// From the end of the source range to its start: pictures in reverse order and sound
61    /// played backwards.
62    Reverse {},
63    /// One source instant for the whole clip, and silence.
64    Freeze {
65        /// The instant shown; inside the source range.
66        source_time: MediaTime,
67    },
68    /// The source range again and again, at its own speed.
69    Loop {
70        /// How each pass follows the one before.
71        mode: LoopMode,
72    },
73    /// Source time keyed over timeline time: speed ramps, reverse play and holds in one clip.
74    ///
75    /// The picture shows the curve's value rounded down to a tick and held inside
76    /// `source_range`; a falling stretch shows the instants it names, so it is not `reverse`'s
77    /// mirror by frame. Sound follows the curve and is silent where it stands still.
78    Curve {
79        /// 2 to [`MAX_KEYFRAMES`] keyframes, strictly ascending in time. They may lie outside
80        /// the clip's timeline range.
81        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { MAX_KEYFRAMES }>")]
82        #[cfg_attr(feature = "schema", schemars(length(max = MAX_KEYFRAMES)))]
83        keyframes: Vec<TimeKeyframe>,
84        /// What the curve does before the first keyframe.
85        #[serde(default)]
86        before: Extrapolation,
87        /// What the curve does from the last keyframe on.
88        #[serde(default)]
89        after: Extrapolation,
90    },
91}
92
93impl From<TimeMapWire> for TimeMap {
94    fn from(wire: TimeMapWire) -> Self {
95        match wire {
96            TimeMapWire::Forward {} => Self::Forward,
97            TimeMapWire::Reverse {} => Self::Reverse,
98            TimeMapWire::Freeze { source_time } => Self::Freeze { source_time },
99            TimeMapWire::Loop { mode } => Self::Loop { mode },
100            TimeMapWire::Curve {
101                keyframes,
102                before,
103                after,
104            } => Self::Curve {
105                keyframes,
106                before,
107                after,
108            },
109        }
110    }
111}
112
113/// One keyframe of a [`TimeMap::Curve`].
114#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
116#[serde(deny_unknown_fields)]
117pub struct TimeKeyframe {
118    /// Timeline time of this value.
119    pub time: MediaTime,
120    /// Source time shown at `time`; from the start of the clip's source range to its end.
121    pub source_time: MediaTime,
122    /// Interpolation from this keyframe to its successor. A `value_bezier`'s `leave` and
123    /// `arrive` are in ticks of source time.
124    pub interpolation: Interpolation,
125}
126
127/// What is wrong with a clip's [`TimeMap`].
128#[derive(Copy, Clone, Debug, Eq, PartialEq)]
129pub enum TimeMapProblem {
130    /// A freeze on an instant outside the source range.
131    FreezeOutsideSource,
132    /// A curve with fewer than two keyframes or more than [`MAX_KEYFRAMES`].
133    KeyframeCount {
134        /// Its keyframes.
135        found: usize,
136    },
137    /// A keyframe at or before the time of the one before it.
138    TimeOrder {
139        /// Its position among the curve's keyframes.
140        keyframe: usize,
141    },
142    /// A keyframe whose source time is outside the source range.
143    OutsideSource {
144        /// Its position among the curve's keyframes.
145        keyframe: usize,
146    },
147    /// A keyframe whose interpolation is not usable.
148    Interpolation {
149        /// Its position among the curve's keyframes.
150        keyframe: usize,
151    },
152    /// A repeating curve plays more than [`MAX_KEYFRAMES`] key segments over the clip.
153    Passes {
154        /// The key segments it plays, counting every pass; `u64::MAX` for more than that.
155        found: u64,
156    },
157}
158
159impl TimeMap {
160    /// The first thing wrong with this map on a clip of the two ranges, if anything.
161    #[must_use]
162    pub fn problem(&self, timeline: TimeRange, source: TimeRange) -> Option<TimeMapProblem> {
163        match self {
164            Self::Forward | Self::Reverse | Self::Loop { .. } => None,
165            Self::Freeze { source_time } => {
166                (!source.contains(*source_time)).then_some(TimeMapProblem::FreezeOutsideSource)
167            }
168            Self::Curve {
169                keyframes,
170                before,
171                after,
172            } => curve_problem(keyframes, *before, *after, timeline, source),
173        }
174    }
175}
176
177fn curve_problem(
178    keys: &[TimeKeyframe],
179    before: Extrapolation,
180    after: Extrapolation,
181    timeline: TimeRange,
182    source: TimeRange,
183) -> Option<TimeMapProblem> {
184    let ([first, .., last], true) = (keys, keys.len() <= MAX_KEYFRAMES) else {
185        return Some(TimeMapProblem::KeyframeCount { found: keys.len() });
186    };
187    for (index, key) in keys.iter().enumerate() {
188        if index > 0 && keys[index - 1].time >= key.time {
189            return Some(TimeMapProblem::TimeOrder { keyframe: index });
190        }
191        if key.source_time < source.start() || key.source_time > source.end() {
192            return Some(TimeMapProblem::OutsideSource { keyframe: index });
193        }
194        if !key.interpolation.is_valid() {
195            return Some(TimeMapProblem::Interpolation { keyframe: index });
196        }
197    }
198    let found = curve_segments_played(
199        (first.time.ticks(), last.time.ticks(), keys.len()),
200        before,
201        after,
202        timeline,
203    );
204    (found > MAX_KEYFRAMES as u128).then(|| TimeMapProblem::Passes {
205        found: u64::try_from(found).unwrap_or(u64::MAX),
206    })
207}
208
209fn curve_segments_played(
210    (first, last, keys): (i64, i64, usize),
211    before: Extrapolation,
212    after: Extrapolation,
213    timeline: TimeRange,
214) -> u128 {
215    let period = (i128::from(last) - i128::from(first)).unsigned_abs().max(1);
216    let passes = |extrapolation: Extrapolation, ticks: i128| {
217        if matches!(extrapolation, Extrapolation::Hold | Extrapolation::Linear) || ticks <= 0 {
218            0
219        } else {
220            ticks.unsigned_abs().div_ceil(period)
221        }
222    };
223    let ahead = passes(
224        before,
225        i128::from(first) - i128::from(timeline.start().ticks()),
226    );
227    let behind = passes(after, i128::from(timeline.end().ticks()) - i128::from(last));
228    (ahead + behind + 1) * (keys as u128 - 1)
229}
230
231/// How each pass of a [`TimeMap::Loop`] follows the one before.
232#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
233#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
234#[serde(rename_all = "snake_case")]
235pub enum LoopMode {
236    /// Every pass plays forward from the start. Sound fades out and in over
237    /// [`LOOP_FADE_SECONDS`] at each wrap so the jump does not click.
238    Repeat,
239    /// Passes alternate forward and backward.
240    PingPong,
241}
242
243/// Most passes a looping clip makes over its timeline range. A longer loop is several clips.
244pub const MAX_LOOP_PASSES: u64 = 65_536;
245
246/// Passes a `source`-tick loop makes over `timeline` ticks, rounded up; zero for an empty source.
247#[must_use]
248pub fn loop_passes(timeline: i64, source: i64) -> u64 {
249    if source <= 0 || timeline <= 0 {
250        return 0;
251    }
252    timeline.unsigned_abs().div_ceil(source.unsigned_abs())
253}
254
255/// How long sound fades out before, and in after, each wrap of a repeating loop.
256pub const LOOP_FADE_SECONDS: f64 = 0.005;