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
404
405
406
//! Clip time and time curve services.

use super::curves::{kind_name, tangent_mode};
use super::{time, to_text};
use crate::{ClipTimes, Direction, SpeedPoint};
use alpha2_model::{MAX_KEYFRAMES, TimeMap, TimeMapProblem};
use alpha2_time::{FrameRate, MediaTime, TimeRange};
use serde::Deserialize;
use serde_json::{Value, json};

#[derive(Deserialize)]
struct ClipTime {
    timeline_range: TimeRange,
    source_range: TimeRange,
    #[serde(default)]
    time_map: TimeMap,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SpeedPointWire {
    time: MediaTime,
    speed: f64,
}

fn described(problem: TimeMapProblem) -> String {
    match problem {
        TimeMapProblem::FreezeOutsideSource => "the freeze lies outside the source range".into(),
        TimeMapProblem::KeyframeCount { found } => {
            format!("a time curve takes 2 to {MAX_KEYFRAMES} keyframes, not {found}")
        }
        TimeMapProblem::TimeOrder { keyframe } => {
            format!("keyframe {keyframe} of the time curve is not after the one before it")
        }
        TimeMapProblem::OutsideSource { keyframe } => {
            format!("keyframe {keyframe} of the time curve is outside the source range")
        }
        TimeMapProblem::Interpolation { keyframe } => {
            format!("keyframe {keyframe} of the time curve has an invalid interpolation")
        }
        TimeMapProblem::Passes { found } => {
            format!("the time curve plays {found} segments; the maximum is {MAX_KEYFRAMES}")
        }
    }
}

fn clip(json: &str) -> Result<ClipTime, String> {
    let clip: ClipTime =
        serde_json::from_str(json).map_err(|error| format!("invalid clip: {error}"))?;
    match clip
        .time_map
        .problem(clip.timeline_range, clip.source_range)
    {
        None => Ok(clip),
        Some(problem) => Err(format!("invalid clip: {}", described(problem))),
    }
}

fn rate(num: u32, den: u32) -> Result<FrameRate, String> {
    FrameRate::new(num, den).map_err(|error| format!("invalid frame rate: {error}"))
}

fn clip_times(clip: &ClipTime, rate: FrameRate) -> Result<ClipTimes<'_>, String> {
    ClipTimes::new(clip.timeline_range, clip.source_range, &clip.time_map, rate)
        .ok_or_else(|| "invalid clip: its times do not fit in ticks".to_owned())
}

fn time_map(json: &str) -> Result<TimeMap, String> {
    let map: TimeMap =
        serde_json::from_str(json).map_err(|error| format!("invalid time map: {error}"))?;
    let TimeMap::Curve { keyframes, .. } = &map else {
        return Ok(map);
    };
    let span = |ticks: &dyn Fn(&alpha2_model::TimeKeyframe) -> MediaTime| {
        let least = keyframes.iter().map(ticks).min().unwrap_or(MediaTime(0));
        let greatest = keyframes.iter().map(ticks).max().unwrap_or(MediaTime(0));
        TimeRange::new(least, greatest)
            .map_err(|_| "invalid time map: its times do not fit in ticks".to_owned())
    };
    match map.problem(span(&|key| key.time)?, span(&|key| key.source_time)?) {
        None => Ok(map),
        Some(problem) => Err(format!("invalid time map: {}", described(problem))),
    }
}

fn ticks(times: &[i64]) -> Vec<MediaTime> {
    times.iter().copied().map(MediaTime).collect()
}

/// The time curve of a speed that is linear between points, as JSON
/// `{ timeMap, reach: [least, greatest] }`. `points_json` is `[{ time, speed }]`.
///
/// # Errors
/// Refuses points at fewer than two times or out of order, and a curve beyond ticks.
pub fn time_curve_from_speeds(source_start: f64, points_json: &str) -> Result<String, String> {
    let points: Vec<SpeedPointWire> = serde_json::from_str(points_json)
        .map_err(|error| format!("invalid speed points: {error}"))?;
    let points: Vec<SpeedPoint> = points
        .into_iter()
        .map(|point| SpeedPoint {
            time: point.time,
            speed: point.speed,
        })
        .collect();
    let (map, [least, greatest]) = crate::time_curve_from_speeds(time(source_start)?, &points)
        .map_err(|error| format!("invalid speed points: {error}"))?;
    to_text(&json!({ "timeMap": map, "reach": [least.ticks(), greatest.ticks()] }))
}

/// The source time and speed of a clip at each time, as JSON `[[source_time, speed]]`.
/// `clip_json` holds a clip's `timeline_range`, `source_range` and `time_map`.
///
/// # Errors
/// Refuses a clip whose time map is not valid on its ranges, or a bad frame rate.
pub fn sample_time_curve(
    clip_json: &str,
    (num, den): (u32, u32),
    times: &[i64],
) -> Result<String, String> {
    let clip = clip(clip_json)?;
    let samples: Vec<Value> = crate::sample_time_curve(
        clip.timeline_range,
        clip.source_range,
        &clip.time_map,
        rate(num, den)?,
        &ticks(times),
    )
    .into_iter()
    .map(|sample| json!([sample.source_time, sample.speed]))
    .collect();
    to_text(&samples)
}

/// The segments of a time curve as JSON `[{ kind, start, end, controls }]`, values in ticks
/// of source time. Empty for a time map that is not a curve.
///
/// # Errors
/// Refuses a time map that is not valid.
pub fn time_curve_segments(time_map_json: &str) -> Result<String, String> {
    let map = time_map(time_map_json)?;
    let keys = match &map {
        TimeMap::Curve { keyframes, .. } => keyframes.as_slice(),
        _ => &[],
    };
    let point = |(time, value): (f64, f64)| json!({ "time": time, "value": value });
    let key = |(time, value): (i64, i64)| json!({ "time": time, "value": value });
    let segments: Vec<Value> = crate::time_curve_segments(keys)
        .into_iter()
        .map(|segment| {
            json!({
                "kind": kind_name(segment.kind),
                "start": key(segment.start),
                "end": key(segment.end),
                "controls": segment.controls.map(|[first, second]| json!([point(first), point(second)])),
            })
        })
        .collect();
    to_text(&segments)
}

/// The stretches of a clip as JSON `[{ from, to, direction, low, high }]`.
///
/// # Errors
/// Refuses what [`sample_time_curve`] refuses.
pub fn clip_stretches(clip_json: &str, (num, den): (u32, u32)) -> Result<String, String> {
    let clip = clip(clip_json)?;
    let stretches: Vec<Value> = clip_times(&clip, rate(num, den)?)?
        .stretches()
        .iter()
        .map(|stretch| {
            json!({
                "from": stretch.from,
                "to": stretch.to,
                "direction": match stretch.direction {
                    Direction::Rising => "rising",
                    Direction::Falling => "falling",
                    Direction::Still => "still",
                },
                "low": stretch.low,
                "high": stretch.high,
            })
        })
        .collect();
    to_text(&stretches)
}

/// The time curve with a keyframe added at a time inside its keyframes.
///
/// # Errors
/// Refuses a time map that is not a valid curve, a time outside its keyframes, and a curve
/// already at the keyframe limit.
pub fn insert_time_key(time_map_json: &str, ticks: f64) -> Result<String, String> {
    let mut map = time_map(time_map_json)?;
    if !matches!(map, TimeMap::Curve { .. }) {
        return Err("invalid time map: only a curve takes a keyframe".into());
    }
    crate::insert_time_key(&mut map, time(ticks)?)
        .map_err(|error| format!("invalid time map: {error}"))?;
    to_text(&map)
}

/// The time curve with handles computed from its keyframes, at `keys` or at all of them.
///
/// # Errors
/// Refuses a time map that is not valid, or an unknown mode.
pub fn time_auto_tangents(
    time_map_json: &str,
    mode: &str,
    keys: Option<&[i64]>,
) -> Result<String, String> {
    let mode = tangent_mode(mode)?;
    let mut map = time_map(time_map_json)?;
    let keys = keys.map(ticks);
    crate::time_auto_tangents(&mut map, mode, keys.as_deref());
    to_text(&map)
}

/// The source tick a clip's picture shows at each time, as JSON `[ticks]`; `null` for a
/// time that maps beyond ticks.
///
/// # Errors
/// Refuses what [`sample_time_curve`] refuses.
pub fn clip_source_times(
    clip_json: &str,
    (num, den): (u32, u32),
    times: &[i64],
) -> Result<String, String> {
    let clip = clip(clip_json)?;
    let rate = rate(num, den)?;
    let shown: Vec<Option<i64>> = times
        .iter()
        .map(|tick| {
            crate::picture_source_time(
                clip.timeline_range,
                clip.source_range,
                &clip.time_map,
                rate,
                MediaTime(*tick),
            )
            .map(MediaTime::ticks)
        })
        .collect();
    to_text(&shown)
}

/// The timeline ranges at which a clip's picture shows each source range, as JSON
/// `[[{ start, end }]]`. `ranges` holds a start and an end tick per source range.
///
/// # Errors
/// Refuses what [`sample_time_curve`] refuses, and an odd count of numbers in `ranges`.
pub fn clip_timeline_ranges(
    clip_json: &str,
    (num, den): (u32, u32),
    ranges: &[i64],
) -> Result<String, String> {
    if !ranges.len().is_multiple_of(2) {
        return Err(format!(
            "invalid clip: source ranges are pairs of ticks, not {} numbers",
            ranges.len()
        ));
    }
    let clip = clip(clip_json)?;
    let times = clip_times(&clip, rate(num, den)?)?;
    let found: Vec<Option<Vec<Value>>> = ranges
        .as_chunks::<2>()
        .0
        .iter()
        .map(|[start, end]| {
            times
                .timeline_ranges(MediaTime(*start), MediaTime(*end))
                .map(|ranges| {
                    ranges
                        .into_iter()
                        .map(|range| {
                            json!({ "start": range.start().ticks(), "end": range.end().ticks() })
                        })
                        .collect()
                })
        })
        .collect();
    to_text(&found)
}

/// The timeline times at which a clip's picture reaches each source instant, as JSON
/// `[[ticks]]`, one list per instant.
///
/// # Errors
/// Refuses what [`sample_time_curve`] refuses.
pub fn clip_timeline_times(
    clip_json: &str,
    (num, den): (u32, u32),
    instants: &[i64],
) -> Result<String, String> {
    let clip = clip(clip_json)?;
    let times = clip_times(&clip, rate(num, den)?)?;
    let found: Vec<Vec<i64>> = instants
        .iter()
        .map(|instant| {
            times
                .timeline_times(MediaTime(*instant))
                .into_iter()
                .map(MediaTime::ticks)
                .collect()
        })
        .collect();
    to_text(&found)
}

fn ramp() -> String {
    time_curve_from_speeds(
        12_000.0,
        r#"[ { "time": 0, "speed": 1 }, { "time": 60000, "speed": 0.25 },
            { "time": 60000, "speed": -2 }, { "time": 90000, "speed": 3.5 },
            { "time": 150000, "speed": 3.5 } ]"#,
    )
    .expect("a curve")
}

/// Answers on fixed inputs that every surface gives byte for byte
/// (`tests/golden/time_curve_services.json`), by service name.
///
/// # Panics
/// Panics if a fixed input is refused.
#[must_use]
pub fn parity_cases() -> Vec<(&'static str, String)> {
    let keyed = r#"{ "type": "curve", "after": "ping_pong", "keyframes": [
        { "time": 0, "source_time": 30000,
          "interpolation": { "type": "cubic_bezier", "x1": 0.9, "y1": -0.5, "x2": 0, "y2": 1.5 } },
        { "time": 24000, "source_time": 240000,
          "interpolation": { "type": "value_bezier", "x1": 0.25, "leave": 90000, "x2": 0.5, "arrive": 60000 } },
        { "time": 60000, "source_time": 120000, "interpolation": { "type": "linear" } },
        { "time": 72000, "source_time": 180000, "interpolation": { "type": "hold" } },
        { "time": 84000, "source_time": 200000,
          "interpolation": { "type": "steps", "count": 5, "position": "start" } },
        { "time": 96000, "source_time": 90000, "interpolation": { "type": "points", "points": [
            { "x": 0.25, "y": 1.5 }, { "x": 0.625, "y": -0.5 } ] } },
        { "time": 120000, "source_time": 150000, "interpolation": { "type": "linear" } } ] }"#;
    let clip = |time_map: &str| {
        format!(
            r#"{{ "timeline_range": {{ "start": 6000, "end": 306000 }},
                 "source_range": {{ "start": 0, "end": 360000 }}, "time_map": {time_map} }}"#
        )
    };
    let rate = (30_000, 1_001);
    let times = [
        -30_000, 0, 6_000, 12_000, 24_000, 42_000, 60_000, 66_000, 78_000, 84_000, 86_400, 91_000,
        96_000, 105_000, 120_000, 150_000, 240_000, 305_999,
    ];
    let maps = [
        keyed,
        r#"{ "type": "forward" }"#,
        r#"{ "type": "reverse" }"#,
        r#"{ "type": "freeze", "source_time": 4000 }"#,
        r#"{ "type": "loop", "mode": "ping_pong" }"#,
    ];
    let each = |call: &dyn Fn(&str) -> Result<String, String>| {
        maps.map(|map| call(&clip(map)).expect("an answer"))
            .join("\n")
    };
    vec![
        ("timeCurveFromSpeeds", ramp()),
        (
            "sampleTimeCurve",
            each(&|clip| sample_time_curve(clip, rate, &times)),
        ),
        (
            "timeCurveSegments",
            time_curve_segments(keyed).expect("segments"),
        ),
        ("clipStretches", each(&|clip| clip_stretches(clip, rate))),
        (
            "insertTimeKey",
            [10_000.0, 40_000.0, 66_000.0, 80_000.0, 90_000.0, 100_000.0]
                .map(|time| insert_time_key(keyed, time).expect("a key"))
                .join("\n"),
        ),
        (
            "timeAutoTangents",
            ["smooth", "monotone", "flat", "linear"]
                .map(|mode| time_auto_tangents(keyed, mode, None).expect("tangents"))
                .join("\n"),
        ),
        (
            "timeAutoTangentsAtOneKey",
            time_auto_tangents(keyed, "smooth", Some(&[60_000])).expect("tangents"),
        ),
        (
            "clipSourceTimes",
            each(&|clip| clip_source_times(clip, rate, &times)),
        ),
        (
            "clipTimelineRanges",
            each(&|clip| {
                clip_timeline_ranges(clip, rate, &[0, 360_000, 100_000, 130_000, 3_000, 4_500])
            }),
        ),
        (
            "clipTimelineTimes",
            each(&|clip| clip_timeline_times(clip, rate, &[4_000, 125_000, 359_999])),
        ),
    ]
}

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