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()
}
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()] }))
}
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
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")
}
#[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, ×)),
),
(
"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, ×)),
),
(
"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;