Skip to main content

alpha2_eval/
frame.rs

1use crate::{EffectParamValue, SampleContext, sample_effect_param};
2use alpha2_media::SourceId;
3use alpha2_model::{
4    BlendSpace, ClipBlendMode, ClipEffect, ClipId, EffectResourceId, Generator, Matte, Rgb,
5    ShapeMask, TextStyle, TrackId, Vec2,
6};
7use alpha2_time::{FrameRate, MediaTime};
8
9/// A timestamp-specific composition description with no GPU handles.
10///
11/// Identities and authored effects are borrowed from the [`crate::ActiveIndex`] (`'a`), so
12/// evaluating a frame copies none of them.
13#[derive(Clone, Debug, PartialEq)]
14pub struct FrameDesc<'a> {
15    /// Timestamp evaluated on the project timeline.
16    pub time: MediaTime,
17    /// Opaque color under every visual layer, or `None` for transparent black (alpha output).
18    pub background: Option<Rgb>,
19    /// The space in which blend modes are evaluated.
20    pub blend_space: BlendSpace,
21    /// The project canvas in pixels, which effects sized in project pixels refer to; `None`
22    /// draws them at the render size.
23    pub canvas: Option<(u32, u32)>,
24    /// Active visual clips in composition order.
25    pub visual: Vec<ActiveClip<'a>>,
26    /// Active audio clips in mix order.
27    pub audio: Vec<ActiveClip<'a>>,
28    /// Active two-input transitions by start, then track order, then position in their track's
29    /// `transitions`. The engine's fold makes the picture independent of this order.
30    pub transitions: Vec<ActiveTransition<'a>>,
31    /// The cue each caption track shows, in track order.
32    pub captions: Vec<ActiveCaption<'a>>,
33    /// The shutter that clips with [`ActiveClip::motion`] and transform steps marked for motion
34    /// blur are averaged over; `None` draws them as unmarked ones.
35    pub shutter: Option<FrameShutter>,
36}
37
38/// The shutter of one frame: the project's, the frame it is measured in, and how many samples a
39/// runtime lets it average.
40#[derive(Copy, Clone, Debug, PartialEq)]
41pub struct FrameShutter {
42    /// The project's shutter.
43    pub shutter: alpha2_model::Shutter,
44    /// The project's frame rate; one of its frames is 360 degrees of the shutter.
45    pub frame_rate: FrameRate,
46    /// Most samples one layer is averaged from: the shutter's, or fewer where a runtime caps
47    /// them. A power of two, at least [`alpha2_model::MIN_SHUTTER_SAMPLES`].
48    pub max_samples: u32,
49}
50
51impl FrameShutter {
52    /// The project's shutter with every sample it allows.
53    #[must_use]
54    pub const fn new(shutter: alpha2_model::Shutter, frame_rate: FrameRate) -> Self {
55        Self {
56            shutter,
57            frame_rate,
58            max_samples: shutter.samples,
59        }
60    }
61
62    /// This shutter averaging at most `samples` samples, rounded down to a power of two; `None`
63    /// when that leaves fewer than [`alpha2_model::MIN_SHUTTER_SAMPLES`], which averages nothing.
64    #[must_use]
65    pub fn capped(self, samples: u32) -> Option<Self> {
66        let max_samples = 1 << self.max_samples.min(samples).checked_ilog2()?;
67        (max_samples >= alpha2_model::MIN_SHUTTER_SAMPLES).then_some(Self {
68            max_samples,
69            ..self
70        })
71    }
72
73    /// The instant sample `index` of `count` reads for the frame (or composition step) at `time`.
74    #[must_use]
75    pub fn sample_time(&self, time: MediaTime, index: u32, count: u32) -> MediaTime {
76        self.shutter
77            .sample_time(time, self.frame_rate, index, count)
78    }
79}
80
81impl FrameDesc<'_> {
82    /// Whether the frame draws `clip`'s picture. A matte ([`ActiveClip::is_matte`]) is drawn
83    /// only while an active clip names it.
84    #[must_use]
85    pub fn draws(&self, clip: &ActiveClip<'_>) -> bool {
86        !clip.is_matte
87            || self.visual.iter().any(|other| {
88                other
89                    .matte
90                    .is_some_and(|matte| &matte.source == clip.clip_id)
91            })
92    }
93}
94
95/// The cue one caption track shows at a timestamp.
96#[derive(Clone, Copy, Debug, PartialEq)]
97pub struct ActiveCaption<'a> {
98    /// The caption track.
99    pub track_id: &'a TrackId,
100    /// The cue's text.
101    pub text: &'a alpha2_model::TextContent,
102    /// Time since the cue started, which keys its style's animators.
103    pub local_time: alpha2_time::MediaTime,
104    /// The track style with the cue's (or else its speaker's) named style patch applied.
105    pub style: &'a TextStyle,
106    /// How many [`FrameDesc::visual`] clips lie under the caption by track order, counting clips
107    /// the frame does not draw ([`FrameDesc::draws`]) so an undrawn clip never shifts a caption.
108    pub layers_below: usize,
109}
110
111/// A visible or audible clip mapped to its source timestamp.
112#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct ActiveClip<'a> {
114    /// Active clip identity.
115    pub clip_id: &'a ClipId,
116    /// Media source needed for this clip.
117    pub source_id: &'a SourceId,
118    /// Track containing the clip.
119    pub track_id: &'a TrackId,
120    /// Source timestamp selected by the clip's time map.
121    pub source_time: MediaTime,
122    /// Evaluated visual presentation, present only for visual tracks.
123    pub visual: Option<EvaluatedVisual>,
124    /// The clip's transform when it is marked for motion blur, to sample across the frame's
125    /// shutter with [`crate::sample_shutter`]; present only for visual tracks.
126    pub motion: Option<&'a alpha2_model::VisualProperties>,
127    /// The composition that builds the clip's picture; `None` shows the source as is.
128    pub composition: Option<crate::ActiveComposition<'a>>,
129    /// Artistic blend operation used by visual composition.
130    pub blend_mode: ClipBlendMode,
131    /// Whether a runtime may keep and reuse the clip's rendered picture.
132    pub cache: alpha2_model::CacheIntent,
133    /// What the clip shows between two frames of its source; `Hold` for a source without frames.
134    pub frame_interpolation: alpha2_model::FrameInterpolation,
135    /// Shape masks in order. Evaluate outlines with [`crate::evaluate_geometry`] and feathers with
136    /// [`crate::sample_scalar`] at the frame's time.
137    pub masks: &'a [ShapeMask],
138    /// The clip whose picture sets where this one is visible.
139    pub matte: Option<&'a Matte>,
140    /// Whether this clip is another clip's matte, drawn only into that matte.
141    pub is_matte: bool,
142    /// Whether the clip is an adjustment clip: it has no picture, and its composition's clip steps
143    /// read the scene composited beneath it. It has no generator, plan, source composition or
144    /// correction, and needs only the frames its composition's media steps read.
145    pub adjustment: bool,
146    /// Generated source content, drawn at `source_time` with no host frame.
147    pub generator: Option<&'a Generator>,
148    /// Planned shapes or layout generator tree, to evaluate at `source_time`.
149    pub plan: Option<&'a crate::GeneratorPlan>,
150    /// For a composition source, its composition at the clip's source time (no host frame).
151    pub source_composition: Option<crate::ActiveComposition<'a>>,
152    /// What the clip's timeline-time values (its masks) read data through.
153    pub data: SampleContext<'a>,
154    /// The correction drawn between the clip's finished picture and its visual, when it has one
155    /// with a value at this time.
156    pub correction: Option<crate::Correction>,
157}
158
159impl ActiveClip<'_> {
160    /// Whether the clip draws its own host-supplied source frame at the frame's own time.
161    #[must_use]
162    pub fn needs_source(&self) -> bool {
163        self.has_host_picture()
164            && self
165                .composition
166                .is_none_or(|composition| composition.plan().uses_clip())
167    }
168
169    /// Whether the clip's picture is a host-supplied frame: not the scene beneath an adjustment
170    /// clip, a generator's drawing or a composition source.
171    #[must_use]
172    pub const fn has_host_picture(&self) -> bool {
173        !self.adjustment && self.generator.is_none() && self.source_composition.is_none()
174    }
175}
176
177/// Visual properties evaluated at one timeline timestamp.
178#[derive(Copy, Clone, Debug, PartialEq)]
179pub struct EvaluatedVisual {
180    /// Normalized output translation.
181    pub position: Vec2,
182    /// Normalized source anchor.
183    pub anchor: Vec2,
184    /// Per-axis scale.
185    pub scale: Vec2,
186    /// Clockwise rotation in degrees.
187    pub rotation_degrees: f32,
188    /// Opacity from zero to one.
189    pub opacity: f32,
190}
191
192/// A source-frame request emitted for host prefetch and decode scheduling.
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub struct FrameNeed {
195    /// Clip consumer that owns the sequential decoder cursor.
196    ///
197    /// Multiple clips may read the same source at unrelated timestamps. Hosts
198    /// must not make those clips share one seek position.
199    pub clip_id: ClipId,
200    /// The composition step reading the source, if not the clip at the frame's own time: its
201    /// [`crate::Step::node`] path, prefixed with `/` for steps of a composition source. Each
202    /// (clip, reader) pair keeps its own decoder cursor.
203    pub reader: Option<alpha2_model::NodeId>,
204    /// Source to decode or retrieve.
205    pub source_id: SourceId,
206    /// Timestamp requested on the source timeline.
207    pub media_time: MediaTime,
208    /// The host also supplies the frame after the one presented at `media_time`, and both frames'
209    /// presentation times.
210    pub following: bool,
211}
212
213/// A transition evaluated at one timeline timestamp.
214#[derive(Clone, Copy, Debug, PartialEq)]
215pub struct ActiveTransition<'a> {
216    /// Clip sampled at progress zero.
217    pub from_clip: &'a ClipId,
218    /// Clip sampled at progress one.
219    pub to_clip: &'a ClipId,
220    /// Versioned shader invocation, with parameters sampled at the frame's time.
221    pub effect: ActiveEffect<'a>,
222    /// Eased progress in the inclusive unit interval.
223    pub progress: f32,
224}
225
226/// One effect invocation at one timestamp (timeline time for transitions, composition time for
227/// composition steps).
228#[derive(Clone, Copy, Debug, PartialEq)]
229pub struct ActiveEffect<'a> {
230    effect: &'a ClipEffect,
231    time: MediaTime,
232    context: SampleContext<'a>,
233}
234
235impl<'a> ActiveEffect<'a> {
236    /// The invocation `effect` sampled at `time`, with data bindings read through `context`.
237    #[must_use]
238    pub const fn new(effect: &'a ClipEffect, time: MediaTime, context: SampleContext<'a>) -> Self {
239        Self {
240            effect,
241            time,
242            context,
243        }
244    }
245
246    /// Stable effect definition identifier.
247    #[must_use]
248    pub fn id(&self) -> &'a str {
249        &self.effect.id
250    }
251
252    /// Exact effect definition version.
253    #[must_use]
254    pub const fn version(&self) -> u32 {
255        self.effect.version
256    }
257
258    /// Every authored parameter sampled at this timestamp. Omitted ones use definition defaults.
259    pub fn params(&self) -> impl Iterator<Item = (&'a str, EffectParamValue)> + 'a {
260        let time = self.time;
261        let context = self.context;
262        self.effect.params.iter().map(move |(name, animation)| {
263            (
264                name.as_str(),
265                sample_effect_param(animation, time, &context),
266            )
267        })
268    }
269
270    /// One parameter sampled at this timestamp, if the invocation sets it.
271    #[must_use]
272    pub fn param(&self, name: &str) -> Option<EffectParamValue> {
273        self.effect
274            .params
275            .get(name)
276            .map(|animation| sample_effect_param(animation, self.time, &self.context))
277    }
278
279    /// Named external resources matched against the effect definition.
280    pub fn resources(&self) -> impl Iterator<Item = (&'a str, &'a EffectResourceId)> + 'a {
281        self.effect
282            .resources
283            .iter()
284            .map(|(name, id)| (name.as_str(), id))
285    }
286
287    /// The authored invocation, with its parameters unevaluated.
288    #[must_use]
289    pub const fn authored(&self) -> &'a ClipEffect {
290        self.effect
291    }
292}