Skip to main content

alpha2_eval/
evaluate.rs

1use crate::{
2    ActiveCaption, ActiveClip, ActiveComposition, ActiveEffect, ActiveIndex, ActiveTransition,
3    EvalError, FrameDesc, FrameNeed, collect_active, map_source_time, sample_visual,
4};
5use alpha2_model::{Project, TrackKind};
6use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
7
8/// Evaluates visual and audio clip descriptions at one timeline timestamp.
9///
10/// The result borrows identities and effects from `index`. Vectors are sized exactly, so an
11/// evaluation allocates one scratch list plus one list per non-empty field.
12///
13/// # Errors
14/// Returns an error for mismatched indexes or unrepresentable retiming.
15pub fn evaluate<'a>(
16    project: &'a Project,
17    index: &'a ActiveIndex,
18    time: MediaTime,
19) -> Result<FrameDesc<'a>, EvalError> {
20    ensure_index_matches(project, index)?;
21    let context = crate::SampleContext::timeline(project, &index.data);
22    let aspect = f64::from(project.settings.width) / f64::from(project.settings.height.max(1));
23    // No instant has more clips active than the index's deepest overlap.
24    let mut active = Vec::with_capacity(index.max_active);
25    if let Some(root) = index.root {
26        collect_active(&index.nodes, root, time, &mut active);
27    }
28    active.sort_unstable_by_key(|entry| (entry.track_order, entry.clip_order));
29
30    let visual_count = active
31        .iter()
32        .filter(|entry| entry.track_kind == TrackKind::Video)
33        .count();
34    let audio_count = active
35        .iter()
36        .filter(|entry| entry.track_kind == TrackKind::Audio)
37        .count();
38    // A caption lies over the clips of the tracks before it.
39    let captions = index
40        .captions
41        .iter()
42        .filter_map(|track| {
43            let cues = &track.captions.cues;
44            // Cues are ordered and disjoint, so only the last one starting at or before `time` can
45            // be active.
46            let candidate = cues.partition_point(|cue| cue.timeline_range.start() <= time);
47            let index = candidate.checked_sub(1)?;
48            let cue = &cues[index];
49            cue.timeline_range.contains(time).then(|| ActiveCaption {
50                track_id: &track.track_id,
51                text: &cue.text,
52                local_time: MediaTime(time.ticks() - cue.timeline_range.start().ticks()),
53                style: &track.styles[track.cue_styles[index]],
54                layers_below: active
55                    .iter()
56                    .filter(|entry| {
57                        entry.track_kind == TrackKind::Video
58                            && entry.track_order < track.track_order
59                    })
60                    .count(),
61            })
62        })
63        .collect();
64    let mut visual = Vec::with_capacity(visual_count);
65    let mut audio = Vec::with_capacity(audio_count);
66    let frame_mirror = crate::Mirror::frame(project.settings.frame_rate);
67    for entry in active {
68        let item = active_clip(entry, frame_mirror, time, aspect, &context)?;
69        match entry.track_kind {
70            TrackKind::Video => visual.push(item),
71            TrackKind::Audio => audio.push(item),
72            _ => {}
73        }
74    }
75    let frame_rate = project.settings.frame_rate;
76    let active_transitions = || {
77        index
78            .transitions
79            .iter()
80            .take_while(move |transition| transition.timeline_range.start() <= time)
81            .filter(move |transition| transition.timeline_range.contains(time))
82    };
83    let mut transitions = Vec::with_capacity(active_transitions().count());
84    transitions.extend(active_transitions().map(|transition| {
85        let linear_progress = centred_progress(transition.timeline_range, frame_rate, time);
86        // Transition shaders are defined on 0..=1; clamp overshooting curves.
87        #[allow(clippy::cast_possible_truncation)]
88        let progress = transition.easing.apply(linear_progress).clamp(0.0, 1.0) as f32;
89        ActiveTransition {
90            from_clip: &transition.from_clip,
91            to_clip: &transition.to_clip,
92            effect: ActiveEffect::new(&transition.effect, time, context),
93            progress,
94        }
95    }));
96    Ok(FrameDesc {
97        time,
98        background: Some(project.settings.background),
99        blend_space: project.settings.blend_space,
100        canvas: Some((project.settings.width, project.settings.height)),
101        visual,
102        audio,
103        transitions,
104        captions,
105    })
106}
107
108fn active_clip<'a>(
109    entry: &'a crate::IndexedClip,
110    frame_mirror: crate::Mirror,
111    time: MediaTime,
112    aspect: f64,
113    context: &crate::SampleContext<'a>,
114) -> Result<ActiveClip<'a>, EvalError> {
115    let source_time = map_source_time(
116        entry.timeline_range,
117        entry.source_range,
118        entry.time_map,
119        frame_mirror,
120        time,
121    )
122    .ok_or_else(|| EvalError::UnmappableClip {
123        clip: entry.clip_id.clone(),
124    })?;
125    Ok(ActiveClip {
126        clip_id: &entry.clip_id,
127        source_id: &entry.source_id,
128        track_id: &entry.track_id,
129        source_time,
130        visual: (entry.track_kind == TrackKind::Video)
131            .then(|| sample_visual(&entry.visual, time, aspect, context)),
132        composition: active_composition(entry, time)?.map(|plan| plan.with_data(*context)),
133        blend_mode: entry.blend_mode,
134        cache: entry.cache,
135        masks: &entry.masks,
136        matte: entry.matte.as_ref(),
137        is_matte: entry.is_matte,
138        adjustment: entry.adjustment,
139        generator: entry.generator.as_ref(),
140        plan: entry.plan.as_deref(),
141        source_composition: active_source_composition(entry, source_time)?
142            .map(|plan| plan.with_data(*context)),
143        data: *context,
144        correction: (entry.track_kind == TrackKind::Video && !entry.adjustment)
145            .then(|| {
146                crate::data::clip_correction(
147                    &entry.visual,
148                    (entry.timeline_range, entry.source_range, entry.time_map),
149                    time,
150                    context,
151                )
152            })
153            .flatten(),
154    })
155}
156
157fn active_source_composition(
158    entry: &crate::IndexedClip,
159    source_time: MediaTime,
160) -> Result<Option<ActiveComposition<'_>>, EvalError> {
161    entry
162        .source_composition
163        .as_ref()
164        .filter(|_| entry.track_kind == TrackKind::Video)
165        .map(|(id, plan)| {
166            plan.as_ref()
167                .as_ref()
168                .map(|plan| ActiveComposition::new(plan, source_time))
169                .map_err(|reason| EvalError::IncompleteComposition {
170                    clip: entry.clip_id.clone(),
171                    composition: id.clone(),
172                    reason: reason.clone(),
173                })
174        })
175        .transpose()
176}
177
178fn active_composition(
179    entry: &crate::IndexedClip,
180    time: MediaTime,
181) -> Result<Option<ActiveComposition<'_>>, EvalError> {
182    let Some(indexed) = entry
183        .composition
184        .as_ref()
185        .filter(|_| entry.track_kind == TrackKind::Video)
186    else {
187        return Ok(None);
188    };
189    let plan =
190        indexed
191            .plan
192            .as_ref()
193            .as_ref()
194            .map_err(|reason| EvalError::IncompleteComposition {
195                clip: entry.clip_id.clone(),
196                composition: indexed.reference.id.clone(),
197                reason: reason.clone(),
198            })?;
199    let local = indexed
200        .reference
201        .local_time(entry.timeline_range.start(), time)
202        .ok_or_else(|| EvalError::UnmappableClip {
203            clip: entry.clip_id.clone(),
204        })?;
205    Ok(Some(ActiveComposition::new(plan, local)))
206}
207
208/// A transition's linear progress, `clamp((t - start + F/2) / D, 0, 1)`.
209///
210/// `F` is one project frame and `D` the duration. Sampling at frame centres makes frame `i` of
211/// `N` show `(i + 0.5) / N`, so every frame mixes both clips and reversed playback shows `1 - p`.
212fn centred_progress(range: TimeRange, frame_rate: FrameRate, time: MediaTime) -> f64 {
213    let elapsed = i128::from(time.ticks()) - i128::from(range.start().ticks());
214    let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
215    // F / 2 = TICKS_PER_SECOND * den / (2 * num); scale by 2 * num to stay exact until the division.
216    let num = i128::from(frame_rate.numerator());
217    let den = i128::from(frame_rate.denominator());
218    let numerator = 2 * num * elapsed + i128::from(TICKS_PER_SECOND) * den;
219    let denominator = 2 * num * duration;
220    #[allow(clippy::cast_precision_loss)]
221    let progress = (numerator as f64 / denominator as f64).clamp(0.0, 1.0);
222    progress
223}
224
225/// Describes all source frames needed at a timestamp.
226///
227/// The list is in evaluation order with no duplicate `(source, timestamp)` pairs. Generated
228/// sources and audio clips need no frames. A visual clip needs its own source only when it draws
229/// it ([`ActiveClip::needs_source`]) plus every source its composition reads. A matte clip needs
230/// frames only while an active clip names it ([`FrameDesc::draws`]).
231///
232/// # Errors
233///
234/// Returns any error emitted by [`evaluate`].
235pub fn frame_needs(
236    project: &Project,
237    index: &ActiveIndex,
238    time: MediaTime,
239) -> Result<Vec<FrameNeed>, EvalError> {
240    let frame = evaluate(project, index, time)?;
241    let mut needs = Needs::default();
242    for item in frame.visual.iter().filter(|item| frame.draws(item)) {
243        if item.needs_source() {
244            needs.ask(item.clip_id, item.source_id, item.source_time, || None);
245        }
246        let plans = item
247            .composition
248            .iter()
249            .map(|composition| (composition, false))
250            .chain(
251                item.source_composition
252                    .iter()
253                    .map(|composition| (composition, true)),
254            );
255        for (composition, of_source) in plans {
256            let steps = &composition.plan().steps;
257            for (step, source_id, time) in composition.media() {
258                let node = &steps[step].node;
259                // Prefix source-composition steps with `/`, which no own-composition path starts with.
260                needs.ask(item.clip_id, source_id, time, || {
261                    if of_source {
262                        alpha2_model::NodeId::new(format!("/{node}")).ok()
263                    } else {
264                        Some(node.clone())
265                    }
266                });
267            }
268        }
269    }
270    Ok(needs.list)
271}
272
273/// Needs deduplicated by linear scan before switching to a hash set. Frames usually need only a
274/// few sources, but a composition may read tens of thousands.
275pub(crate) const SCANNED_NEEDS: usize = 32;
276
277#[cfg(test)]
278thread_local! {
279    /// Comparisons made by [`Needs::ask`] on this thread.
280    pub(crate) static COMPARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
281}
282
283#[derive(Default)]
284struct Needs<'a> {
285    list: Vec<FrameNeed>,
286    /// Needs past the first [`SCANNED_NEEDS`], borrowing IDs so lookups clone nothing.
287    hashed: std::collections::HashSet<(&'a alpha2_media::SourceId, MediaTime)>,
288}
289
290impl<'a> Needs<'a> {
291    /// Records `source_id` at `media_time` unless already recorded. `reader` runs only for a new
292    /// need.
293    fn ask(
294        &mut self,
295        clip_id: &alpha2_model::ClipId,
296        source_id: &'a alpha2_media::SourceId,
297        media_time: MediaTime,
298        reader: impl FnOnce() -> Option<alpha2_model::NodeId>,
299    ) {
300        let scanned = &self.list[..self.list.len().min(SCANNED_NEEDS)];
301        #[cfg(test)]
302        COMPARED.with(|compared| compared.set(compared.get() + scanned.len()));
303        let repeat = scanned
304            .iter()
305            .any(|need| need.media_time == media_time && need.source_id == *source_id)
306            || (self.list.len() > SCANNED_NEEDS && self.hashed.contains(&(source_id, media_time)));
307        if repeat {
308            return;
309        }
310        if self.list.len() >= SCANNED_NEEDS {
311            self.hashed.insert((source_id, media_time));
312        }
313        self.list.push(FrameNeed {
314            clip_id: clip_id.clone(),
315            reader: reader(),
316            source_id: source_id.clone(),
317            media_time,
318        });
319    }
320}
321
322pub(crate) fn ensure_index_matches(
323    project: &Project,
324    index: &ActiveIndex,
325) -> Result<(), EvalError> {
326    if project.id == index.project_id {
327        Ok(())
328    } else {
329        Err(EvalError::IndexProjectMismatch {
330            index_project: index.project_id.clone(),
331            evaluated_project: project.id.clone(),
332        })
333    }
334}