Skip to main content

alpha2_model/
timeline.rs

1use crate::{
2    AudioProperties, AudioRead, Captions, ClipBlendMode, ClipComposition, ClipEffect, ClipId,
3    Easing, Matte, MediaKind, ShapeMask, TimeMap, TrackAudio, TrackId, VisualProperties,
4};
5use alpha2_media::SourceId;
6use alpha2_time::TimeRange;
7use serde::{Deserialize, Serialize};
8
9/// Timeline tracks ordered from back to front for visual tracks.
10#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
11#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
12#[serde(deny_unknown_fields)]
13pub struct Timeline {
14    /// Tracks in composition order.
15    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TRACKS }>")]
16    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TRACKS)))]
17    pub tracks: Vec<Track>,
18}
19
20impl Timeline {
21    /// The smallest interval holding every clip and caption cue. `None` for a timeline that shows
22    /// nothing. A whole-project export covers `Project::default_export_range` instead.
23    #[must_use]
24    pub fn extent(&self) -> Option<TimeRange> {
25        let mut ranges = self.tracks.iter().flat_map(|track| {
26            track.clips.iter().map(|clip| clip.timeline_range).chain(
27                track
28                    .captions
29                    .iter()
30                    .flat_map(|captions| captions.cues.iter().map(|cue| cue.timeline_range)),
31            )
32        });
33        let first = ranges.next()?;
34        let (start, end) = ranges.fold((first.start(), first.end()), |(start, end), range| {
35            (start.min(range.start()), end.max(range.end()))
36        });
37        TimeRange::new(start, end).ok()
38    }
39
40    /// The clips that are another clip's matte. Such a clip is drawn only into the mattes that
41    /// name it and never composited itself.
42    #[must_use]
43    pub fn matte_sources(&self) -> std::collections::HashSet<&ClipId> {
44        self.tracks
45            .iter()
46            .flat_map(|track| &track.clips)
47            .filter_map(|clip| clip.matte.as_ref().map(|matte| &matte.source))
48            .collect()
49    }
50}
51
52/// A homogeneous visual or audio timeline lane.
53#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
54#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
55#[serde(deny_unknown_fields)]
56#[non_exhaustive]
57pub struct Track {
58    /// Stable track identity.
59    pub id: TrackId,
60    /// User-visible track name.
61    pub name: String,
62    /// Controls source compatibility and evaluation behavior.
63    pub kind: TrackKind,
64    /// Clips on this track, in authoring order; evaluation sorts by time. A caption track has
65    /// none.
66    #[serde(default)]
67    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIPS_PER_TRACK }>")]
68    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIPS_PER_TRACK)))]
69    pub clips: Vec<Clip>,
70    /// Explicit transitions between overlapping clips on this track.
71    #[serde(default)]
72    #[serde(
73        deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TRANSITIONS_PER_TRACK }>"
74    )]
75    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TRANSITIONS_PER_TRACK)))]
76    pub transitions: Vec<ClipTransition>,
77    /// Bus controls applied to this track's mixed audio.
78    #[serde(default)]
79    pub audio: TrackAudio,
80    /// The cues and style of a caption track; present exactly for that kind.
81    #[serde(default)]
82    pub captions: Option<Captions>,
83}
84
85impl Track {
86    /// Creates an empty track with default bus controls.
87    #[must_use]
88    pub fn new(id: TrackId, name: impl Into<String>, kind: TrackKind) -> Self {
89        Self {
90            id,
91            name: name.into(),
92            kind,
93            clips: Vec::new(),
94            transitions: Vec::new(),
95            audio: TrackAudio::default(),
96            captions: (kind == TrackKind::Caption).then(Captions::default),
97        }
98    }
99}
100
101/// The media domain accepted by a track.
102#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
103#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
104#[serde(rename_all = "snake_case")]
105#[non_exhaustive]
106pub enum TrackKind {
107    /// A composited visual track.
108    Video,
109    /// A mixed audio track.
110    Audio,
111    /// Timed text, drawn over the tracks before it and under the ones after.
112    Caption,
113}
114
115impl TrackKind {
116    pub(crate) const fn accepts(self, source: MediaKind) -> bool {
117        matches!(
118            (self, source),
119            (
120                Self::Video,
121                MediaKind::Video
122                    | MediaKind::Image
123                    | MediaKind::Generated
124                    | MediaKind::Composition
125                    | MediaKind::Adjustment
126            ) | (Self::Audio, MediaKind::Audio)
127        )
128    }
129}
130
131/// A reference to a source over independent timeline and source ranges.
132#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
133#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
134#[serde(deny_unknown_fields)]
135#[non_exhaustive]
136pub struct Clip {
137    /// Stable clip identity.
138    pub id: ClipId,
139    /// Source consumed by this clip.
140    pub source_id: SourceId,
141    /// Destination interval on the project timeline.
142    pub timeline_range: TimeRange,
143    /// Interval read from the source timeline.
144    pub source_range: TimeRange,
145    /// Resolution-independent visual presentation controls.
146    #[serde(default)]
147    pub visual: VisualProperties,
148    /// The composition graph that builds the clip's picture from its source, with the clip's
149    /// time mapping onto it. Without one the clip shows its source as is. Visual clips only.
150    #[serde(default)]
151    pub composition: Option<ClipComposition>,
152    /// Artistic operation used when this clip is composited over earlier layers.
153    #[serde(default)]
154    pub blend_mode: ClipBlendMode,
155    /// Shapes that limit where the clip is visible, applied in order after its composition and
156    /// before its transform. At most [`crate::MAX_CLIP_MASKS`]; visual clips only.
157    #[serde(default)]
158    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIP_MASKS }>")]
159    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIP_MASKS)))]
160    pub masks: Vec<ShapeMask>,
161    /// Another visual clip whose picture sets where this clip is visible.
162    #[serde(default)]
163    pub matte: Option<Matte>,
164    /// How timeline time maps onto the source range.
165    #[serde(default)]
166    pub time_map: TimeMap,
167    /// Presentation controls applied to this clip's audio.
168    #[serde(default)]
169    pub audio: AudioProperties,
170    /// Whether a runtime may keep and reuse the clip's rendered picture. Never changes what
171    /// renders.
172    #[serde(default, skip_serializing_if = "CacheIntent::is_auto")]
173    pub cache: CacheIntent,
174    /// Whether the motion of the clip's transform is averaged over the project's shutter. The
175    /// picture placed is the one at the frame time. Has no effect on a clip without a picture.
176    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
177    pub motion_blur: bool,
178    /// What the clip shows at a source time between two frames of its source. Has no effect on a
179    /// source without frames (a still, a generated, composition or adjustment source). Clips of a
180    /// video track only.
181    #[serde(default, skip_serializing_if = "FrameInterpolation::is_hold")]
182    pub frame_interpolation: FrameInterpolation,
183}
184
185/// What is shown at a source time between two frames of a video source.
186#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
187#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
188#[serde(rename_all = "snake_case")]
189pub enum FrameInterpolation {
190    /// The frame presented at that time.
191    #[default]
192    Hold,
193    /// That frame and the one after it, added in the project's blend space at weights `1 - w` and
194    /// `w`, where `w` is how far the time lies from the first frame's timestamp to the second's.
195    /// The source's last frame, and a runtime that cannot supply the frame after, show the frame
196    /// alone.
197    Mix,
198}
199
200impl FrameInterpolation {
201    /// Whether it is [`FrameInterpolation::Hold`].
202    #[must_use]
203    pub const fn is_hold(&self) -> bool {
204        matches!(self, Self::Hold)
205    }
206}
207
208/// Whether a runtime may keep and reuse a clip's rendered picture.
209#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
210#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
211#[serde(rename_all = "snake_case")]
212pub enum CacheIntent {
213    /// The runtime decides, keeping pictures whose inputs it can identify.
214    #[default]
215    Auto,
216    /// Keep it ahead of other pictures, and bake its range when a host bakes render caches.
217    Pin,
218    /// Always render it live, never reading from or writing to a cache.
219    Bypass,
220}
221
222impl CacheIntent {
223    /// Whether it is [`CacheIntent::Auto`].
224    #[must_use]
225    pub const fn is_auto(&self) -> bool {
226        matches!(self, Self::Auto)
227    }
228}
229
230impl Clip {
231    /// How the clip's sound is read from its source.
232    #[must_use]
233    pub fn audio_read(&self) -> AudioRead {
234        self.audio
235            .read(&self.time_map, self.timeline_range, self.source_range)
236    }
237
238    /// Whether [`Self::audio_read`] has a stretch stage ([`AudioRead::stretches`]).
239    #[must_use]
240    pub fn stretches_audio(&self) -> bool {
241        self.audio_read().stretches()
242    }
243
244    /// Creates a clip with default visual, blend, and audio controls and no composition.
245    #[must_use]
246    pub fn new(
247        id: ClipId,
248        source_id: SourceId,
249        timeline_range: TimeRange,
250        source_range: TimeRange,
251    ) -> Self {
252        Self {
253            id,
254            source_id,
255            timeline_range,
256            source_range,
257            visual: VisualProperties::default(),
258            composition: None,
259            blend_mode: ClipBlendMode::default(),
260            masks: Vec::new(),
261            matte: None,
262            time_map: TimeMap::Forward,
263            audio: AudioProperties::default(),
264            cache: CacheIntent::Auto,
265            motion_blur: false,
266            frame_interpolation: FrameInterpolation::Hold,
267        }
268    }
269}
270
271/// A two-input transition over the overlap of two visual clips.
272#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
273#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
274#[serde(deny_unknown_fields)]
275pub struct ClipTransition {
276    /// Clip sampled as transition progress zero.
277    pub from_clip: ClipId,
278    /// Clip sampled as transition progress one.
279    pub to_clip: ClipId,
280    /// Half-open timeline interval over which both clips must be active.
281    pub timeline_range: TimeRange,
282    /// Timing curve applied to the transition's linear progress. The eased progress is clamped
283    /// to `0..=1`.
284    pub easing: Easing,
285    /// Versioned transition shader and named parameter values.
286    pub effect: ClipEffect,
287}