alpha2-model 0.9.0

Versioned project and timeline model for alpha2.
Documentation
use crate::{
    AudioProperties, AudioRead, Captions, ClipBlendMode, ClipComposition, ClipEffect, ClipId,
    Easing, Matte, MediaKind, ShapeMask, TimeMap, TrackAudio, TrackId, VisualProperties,
};
use alpha2_media::SourceId;
use alpha2_time::TimeRange;
use serde::{Deserialize, Serialize};

/// Timeline tracks ordered from back to front for visual tracks.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Timeline {
    /// Tracks in composition order.
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TRACKS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TRACKS)))]
    pub tracks: Vec<Track>,
}

impl Timeline {
    /// The smallest interval holding every clip and caption cue. `None` for a timeline that shows
    /// nothing. A whole-project export covers `Project::default_export_range` instead.
    #[must_use]
    pub fn extent(&self) -> Option<TimeRange> {
        let mut ranges = self.tracks.iter().flat_map(|track| {
            track.clips.iter().map(|clip| clip.timeline_range).chain(
                track
                    .captions
                    .iter()
                    .flat_map(|captions| captions.cues.iter().map(|cue| cue.timeline_range)),
            )
        });
        let first = ranges.next()?;
        let (start, end) = ranges.fold((first.start(), first.end()), |(start, end), range| {
            (start.min(range.start()), end.max(range.end()))
        });
        TimeRange::new(start, end).ok()
    }

    /// The clips that are another clip's matte. Such a clip is drawn only into the mattes that
    /// name it and never composited itself.
    #[must_use]
    pub fn matte_sources(&self) -> std::collections::HashSet<&ClipId> {
        self.tracks
            .iter()
            .flat_map(|track| &track.clips)
            .filter_map(|clip| clip.matte.as_ref().map(|matte| &matte.source))
            .collect()
    }
}

/// A homogeneous visual or audio timeline lane.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Track {
    /// Stable track identity.
    pub id: TrackId,
    /// User-visible track name.
    pub name: String,
    /// Controls source compatibility and evaluation behavior.
    pub kind: TrackKind,
    /// Clips on this track, in authoring order; evaluation sorts by time. A caption track has
    /// none.
    #[serde(default)]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIPS_PER_TRACK }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIPS_PER_TRACK)))]
    pub clips: Vec<Clip>,
    /// Explicit transitions between overlapping clips on this track.
    #[serde(default)]
    #[serde(
        deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TRANSITIONS_PER_TRACK }>"
    )]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TRANSITIONS_PER_TRACK)))]
    pub transitions: Vec<ClipTransition>,
    /// Bus controls applied to this track's mixed audio.
    #[serde(default)]
    pub audio: TrackAudio,
    /// The cues and style of a caption track; present exactly for that kind.
    #[serde(default)]
    pub captions: Option<Captions>,
}

impl Track {
    /// Creates an empty track with default bus controls.
    #[must_use]
    pub fn new(id: TrackId, name: impl Into<String>, kind: TrackKind) -> Self {
        Self {
            id,
            name: name.into(),
            kind,
            clips: Vec::new(),
            transitions: Vec::new(),
            audio: TrackAudio::default(),
            captions: (kind == TrackKind::Caption).then(Captions::default),
        }
    }
}

/// The media domain accepted by a track.
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TrackKind {
    /// A composited visual track.
    Video,
    /// A mixed audio track.
    Audio,
    /// Timed text, drawn over the tracks before it and under the ones after.
    Caption,
}

impl TrackKind {
    pub(crate) const fn accepts(self, source: MediaKind) -> bool {
        matches!(
            (self, source),
            (
                Self::Video,
                MediaKind::Video
                    | MediaKind::Image
                    | MediaKind::Generated
                    | MediaKind::Composition
                    | MediaKind::Adjustment
            ) | (Self::Audio, MediaKind::Audio)
        )
    }
}

/// A reference to a source over independent timeline and source ranges.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Clip {
    /// Stable clip identity.
    pub id: ClipId,
    /// Source consumed by this clip.
    pub source_id: SourceId,
    /// Destination interval on the project timeline.
    pub timeline_range: TimeRange,
    /// Interval read from the source timeline.
    pub source_range: TimeRange,
    /// Resolution-independent visual presentation controls.
    #[serde(default)]
    pub visual: VisualProperties,
    /// The composition graph that builds the clip's picture from its source, with the clip's
    /// time mapping onto it. Without one the clip shows its source as is. Visual clips only.
    #[serde(default)]
    pub composition: Option<ClipComposition>,
    /// Artistic operation used when this clip is composited over earlier layers.
    #[serde(default)]
    pub blend_mode: ClipBlendMode,
    /// Shapes that limit where the clip is visible, applied in order after its composition and
    /// before its transform. At most [`crate::MAX_CLIP_MASKS`]; visual clips only.
    #[serde(default)]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIP_MASKS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIP_MASKS)))]
    pub masks: Vec<ShapeMask>,
    /// Another visual clip whose picture sets where this clip is visible.
    #[serde(default)]
    pub matte: Option<Matte>,
    /// How timeline time maps onto the source range.
    #[serde(default)]
    pub time_map: TimeMap,
    /// Presentation controls applied to this clip's audio.
    #[serde(default)]
    pub audio: AudioProperties,
    /// Whether a runtime may keep and reuse the clip's rendered picture. Never changes what
    /// renders.
    #[serde(default, skip_serializing_if = "CacheIntent::is_auto")]
    pub cache: CacheIntent,
    /// Whether the motion of the clip's transform is averaged over the project's shutter. The
    /// picture placed is the one at the frame time. Has no effect on a clip without a picture.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub motion_blur: bool,
    /// What the clip shows at a source time between two frames of its source. Has no effect on a
    /// source without frames (a still, a generated, composition or adjustment source). Clips of a
    /// video track only.
    #[serde(default, skip_serializing_if = "FrameInterpolation::is_hold")]
    pub frame_interpolation: FrameInterpolation,
}

/// What is shown at a source time between two frames of a video source.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FrameInterpolation {
    /// The frame presented at that time.
    #[default]
    Hold,
    /// That frame and the one after it, added in the project's blend space at weights `1 - w` and
    /// `w`, where `w` is how far the time lies from the first frame's timestamp to the second's.
    /// The source's last frame, and a runtime that cannot supply the frame after, show the frame
    /// alone.
    Mix,
}

impl FrameInterpolation {
    /// Whether it is [`FrameInterpolation::Hold`].
    #[must_use]
    pub const fn is_hold(&self) -> bool {
        matches!(self, Self::Hold)
    }
}

/// Whether a runtime may keep and reuse a clip's rendered picture.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum CacheIntent {
    /// The runtime decides, keeping pictures whose inputs it can identify.
    #[default]
    Auto,
    /// Keep it ahead of other pictures, and bake its range when a host bakes render caches.
    Pin,
    /// Always render it live, never reading from or writing to a cache.
    Bypass,
}

impl CacheIntent {
    /// Whether it is [`CacheIntent::Auto`].
    #[must_use]
    pub const fn is_auto(&self) -> bool {
        matches!(self, Self::Auto)
    }
}

impl Clip {
    /// How the clip's sound is read from its source.
    #[must_use]
    pub fn audio_read(&self) -> AudioRead {
        self.audio
            .read(&self.time_map, self.timeline_range, self.source_range)
    }

    /// Whether [`Self::audio_read`] has a stretch stage ([`AudioRead::stretches`]).
    #[must_use]
    pub fn stretches_audio(&self) -> bool {
        self.audio_read().stretches()
    }

    /// Creates a clip with default visual, blend, and audio controls and no composition.
    #[must_use]
    pub fn new(
        id: ClipId,
        source_id: SourceId,
        timeline_range: TimeRange,
        source_range: TimeRange,
    ) -> Self {
        Self {
            id,
            source_id,
            timeline_range,
            source_range,
            visual: VisualProperties::default(),
            composition: None,
            blend_mode: ClipBlendMode::default(),
            masks: Vec::new(),
            matte: None,
            time_map: TimeMap::Forward,
            audio: AudioProperties::default(),
            cache: CacheIntent::Auto,
            motion_blur: false,
            frame_interpolation: FrameInterpolation::Hold,
        }
    }
}

/// A two-input transition over the overlap of two visual clips.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ClipTransition {
    /// Clip sampled as transition progress zero.
    pub from_clip: ClipId,
    /// Clip sampled as transition progress one.
    pub to_clip: ClipId,
    /// Half-open timeline interval over which both clips must be active.
    pub timeline_range: TimeRange,
    /// Timing curve applied to the transition's linear progress. The eased progress is clamped
    /// to `0..=1`.
    pub easing: Easing,
    /// Versioned transition shader and named parameter values.
    pub effect: ClipEffect,
}