alpha2-model 0.9.0

Versioned project and timeline model for alpha2.
Documentation
//! 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;