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
//! How a clip's timeline time maps onto its source range.
use crate::{Extrapolation, Interpolation, MAX_KEYFRAMES};
use alpha2_time::{MediaTime, TimeRange};
use serde::{Deserialize, Serialize};
/// How a clip plays its source range over its timeline range.
///
/// `forward` and `reverse` stretch the source range over the timeline range, so their speed
/// is the ratio of the two. A loop plays the source range at its own speed for as long as the
/// timeline range lasts. A curve names the source time at each timeline time, at any speed and
/// in either direction.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case", from = "TimeMapWire")]
pub enum TimeMap {
/// From the start of the source range to its end.
#[default]
Forward,
/// From the end of the source range to its start: pictures in reverse order and sound
/// played backwards.
Reverse,
/// One source instant for the whole clip, and silence.
Freeze {
/// The instant shown; inside the source range.
source_time: MediaTime,
},
/// The source range again and again, at its own speed.
Loop {
/// How each pass follows the one before.
mode: LoopMode,
},
/// Source time keyed over timeline time: speed ramps, reverse play and holds in one clip.
///
/// The picture shows the curve's value rounded down to a tick and held inside
/// `source_range`; a falling stretch shows the instants it names, so it is not `reverse`'s
/// mirror by frame. Sound follows the curve and is silent where it stands still.
Curve {
/// 2 to [`MAX_KEYFRAMES`] keyframes, strictly ascending in time. They may lie outside
/// the clip's timeline range.
keyframes: Vec<TimeKeyframe>,
/// What the curve does before the first keyframe.
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
before: Extrapolation,
/// What the curve does from the last keyframe on.
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
after: Extrapolation,
},
}
/// The wire form of [`TimeMap`]: empty struct variants reject extra fields
/// where serde's unit variants would ignore them.
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "TimeMap"))]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum TimeMapWire {
/// From the start of the source range to its end.
Forward {},
/// From the end of the source range to its start: pictures in reverse order and sound
/// played backwards.
Reverse {},
/// One source instant for the whole clip, and silence.
Freeze {
/// The instant shown; inside the source range.
source_time: MediaTime,
},
/// The source range again and again, at its own speed.
Loop {
/// How each pass follows the one before.
mode: LoopMode,
},
/// Source time keyed over timeline time: speed ramps, reverse play and holds in one clip.
///
/// The picture shows the curve's value rounded down to a tick and held inside
/// `source_range`; a falling stretch shows the instants it names, so it is not `reverse`'s
/// mirror by frame. Sound follows the curve and is silent where it stands still.
Curve {
/// 2 to [`MAX_KEYFRAMES`] keyframes, strictly ascending in time. They may lie outside
/// the clip's timeline range.
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { MAX_KEYFRAMES }>")]
#[cfg_attr(feature = "schema", schemars(length(max = MAX_KEYFRAMES)))]
keyframes: Vec<TimeKeyframe>,
/// What the curve does before the first keyframe.
#[serde(default)]
before: Extrapolation,
/// What the curve does from the last keyframe on.
#[serde(default)]
after: Extrapolation,
},
}
impl From<TimeMapWire> for TimeMap {
fn from(wire: TimeMapWire) -> Self {
match wire {
TimeMapWire::Forward {} => Self::Forward,
TimeMapWire::Reverse {} => Self::Reverse,
TimeMapWire::Freeze { source_time } => Self::Freeze { source_time },
TimeMapWire::Loop { mode } => Self::Loop { mode },
TimeMapWire::Curve {
keyframes,
before,
after,
} => Self::Curve {
keyframes,
before,
after,
},
}
}
}
/// One keyframe of a [`TimeMap::Curve`].
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TimeKeyframe {
/// Timeline time of this value.
pub time: MediaTime,
/// Source time shown at `time`; from the start of the clip's source range to its end.
pub source_time: MediaTime,
/// Interpolation from this keyframe to its successor. A `value_bezier`'s `leave` and
/// `arrive` are in ticks of source time.
pub interpolation: Interpolation,
}
/// What is wrong with a clip's [`TimeMap`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum TimeMapProblem {
/// A freeze on an instant outside the source range.
FreezeOutsideSource,
/// A curve with fewer than two keyframes or more than [`MAX_KEYFRAMES`].
KeyframeCount {
/// Its keyframes.
found: usize,
},
/// A keyframe at or before the time of the one before it.
TimeOrder {
/// Its position among the curve's keyframes.
keyframe: usize,
},
/// A keyframe whose source time is outside the source range.
OutsideSource {
/// Its position among the curve's keyframes.
keyframe: usize,
},
/// A keyframe whose interpolation is not usable.
Interpolation {
/// Its position among the curve's keyframes.
keyframe: usize,
},
/// A repeating curve plays more than [`MAX_KEYFRAMES`] key segments over the clip.
Passes {
/// The key segments it plays, counting every pass; `u64::MAX` for more than that.
found: u64,
},
}
impl TimeMap {
/// The first thing wrong with this map on a clip of the two ranges, if anything.
#[must_use]
pub fn problem(&self, timeline: TimeRange, source: TimeRange) -> Option<TimeMapProblem> {
match self {
Self::Forward | Self::Reverse | Self::Loop { .. } => None,
Self::Freeze { source_time } => {
(!source.contains(*source_time)).then_some(TimeMapProblem::FreezeOutsideSource)
}
Self::Curve {
keyframes,
before,
after,
} => curve_problem(keyframes, *before, *after, timeline, source),
}
}
}
fn curve_problem(
keys: &[TimeKeyframe],
before: Extrapolation,
after: Extrapolation,
timeline: TimeRange,
source: TimeRange,
) -> Option<TimeMapProblem> {
let ([first, .., last], true) = (keys, keys.len() <= MAX_KEYFRAMES) else {
return Some(TimeMapProblem::KeyframeCount { found: keys.len() });
};
for (index, key) in keys.iter().enumerate() {
if index > 0 && keys[index - 1].time >= key.time {
return Some(TimeMapProblem::TimeOrder { keyframe: index });
}
if key.source_time < source.start() || key.source_time > source.end() {
return Some(TimeMapProblem::OutsideSource { keyframe: index });
}
if !key.interpolation.is_valid() {
return Some(TimeMapProblem::Interpolation { keyframe: index });
}
}
let found = curve_segments_played(
(first.time.ticks(), last.time.ticks(), keys.len()),
before,
after,
timeline,
);
(found > MAX_KEYFRAMES as u128).then(|| TimeMapProblem::Passes {
found: u64::try_from(found).unwrap_or(u64::MAX),
})
}
fn curve_segments_played(
(first, last, keys): (i64, i64, usize),
before: Extrapolation,
after: Extrapolation,
timeline: TimeRange,
) -> u128 {
let period = (i128::from(last) - i128::from(first)).unsigned_abs().max(1);
let passes = |extrapolation: Extrapolation, ticks: i128| {
if matches!(extrapolation, Extrapolation::Hold | Extrapolation::Linear) || ticks <= 0 {
0
} else {
ticks.unsigned_abs().div_ceil(period)
}
};
let ahead = passes(
before,
i128::from(first) - i128::from(timeline.start().ticks()),
);
let behind = passes(after, i128::from(timeline.end().ticks()) - i128::from(last));
(ahead + behind + 1) * (keys as u128 - 1)
}
/// How each pass of a [`TimeMap::Loop`] follows the one before.
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum LoopMode {
/// Every pass plays forward from the start. Sound fades out and in over
/// [`LOOP_FADE_SECONDS`] at each wrap so the jump does not click.
Repeat,
/// Passes alternate forward and backward.
PingPong,
}
/// Most passes a looping clip makes over its timeline range. A longer loop is several clips.
pub const MAX_LOOP_PASSES: u64 = 65_536;
/// Passes a `source`-tick loop makes over `timeline` ticks, rounded up; zero for an empty source.
#[must_use]
pub fn loop_passes(timeline: i64, source: i64) -> u64 {
if source <= 0 || timeline <= 0 {
return 0;
}
timeline.unsigned_abs().div_ceil(source.unsigned_abs())
}
/// How long sound fades out before, and in after, each wrap of a repeating loop.
pub const LOOP_FADE_SECONDS: f64 = 0.005;