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        shutter: Some(crate::FrameShutter::new(
106            project.settings.shutter,
107            project.settings.frame_rate,
108        )),
109    })
110}
111
112fn active_clip<'a>(
113    entry: &'a crate::IndexedClip,
114    frame_mirror: crate::Mirror,
115    time: MediaTime,
116    aspect: f64,
117    context: &crate::SampleContext<'a>,
118) -> Result<ActiveClip<'a>, EvalError> {
119    let source_time = map_source_time(
120        entry.timeline_range,
121        entry.source_range,
122        &entry.time_map,
123        frame_mirror,
124        time,
125    )
126    .ok_or_else(|| EvalError::UnmappableClip {
127        clip: entry.clip_id.clone(),
128    })?;
129    Ok(ActiveClip {
130        clip_id: &entry.clip_id,
131        source_id: &entry.source_id,
132        track_id: &entry.track_id,
133        source_time,
134        visual: (entry.track_kind == TrackKind::Video)
135            .then(|| sample_visual(&entry.visual, time, aspect, context)),
136        motion: (entry.track_kind == TrackKind::Video && entry.motion_blur)
137            .then_some(&entry.visual),
138        composition: active_composition(entry, frame_mirror, time)?
139            .map(|plan| plan.with_data(*context)),
140        blend_mode: entry.blend_mode,
141        cache: entry.cache,
142        frame_interpolation: entry.frame_interpolation,
143        masks: &entry.masks,
144        matte: entry.matte.as_ref(),
145        is_matte: entry.is_matte,
146        adjustment: entry.adjustment,
147        generator: entry.generator.as_ref(),
148        plan: entry.plan.as_deref(),
149        source_composition: active_source_composition(entry, source_time)?
150            .map(|plan| plan.with_data(*context)),
151        data: *context,
152        correction: (entry.track_kind == TrackKind::Video && !entry.adjustment)
153            .then(|| {
154                crate::data::clip_correction(
155                    &entry.visual,
156                    (entry.timeline_range, entry.source_range, &entry.time_map),
157                    time,
158                    context,
159                )
160            })
161            .flatten(),
162    })
163}
164
165fn active_source_composition(
166    entry: &crate::IndexedClip,
167    source_time: MediaTime,
168) -> Result<Option<ActiveComposition<'_>>, EvalError> {
169    entry
170        .source_composition
171        .as_ref()
172        .filter(|_| entry.track_kind == TrackKind::Video)
173        .map(|(id, plan)| {
174            plan.as_ref()
175                .as_ref()
176                .map(|plan| ActiveComposition::new(plan, source_time))
177                .map_err(|reason| EvalError::IncompleteComposition {
178                    clip: entry.clip_id.clone(),
179                    composition: id.clone(),
180                    reason: reason.clone(),
181                })
182        })
183        .transpose()
184}
185
186fn active_composition(
187    entry: &crate::IndexedClip,
188    frame_mirror: crate::Mirror,
189    time: MediaTime,
190) -> Result<Option<ActiveComposition<'_>>, EvalError> {
191    let Some(indexed) = entry
192        .composition
193        .as_ref()
194        .filter(|_| entry.track_kind == TrackKind::Video)
195    else {
196        return Ok(None);
197    };
198    let plan =
199        indexed
200            .plan
201            .as_ref()
202            .as_ref()
203            .map_err(|reason| EvalError::IncompleteComposition {
204                clip: entry.clip_id.clone(),
205                composition: indexed.reference.id.clone(),
206                reason: reason.clone(),
207            })?;
208    let local = indexed
209        .reference
210        .local_time(entry.timeline_range.start(), time)
211        .ok_or_else(|| EvalError::UnmappableClip {
212            clip: entry.clip_id.clone(),
213        })?;
214    let shown_by = crate::composition::ShowingClip {
215        timeline_range: entry.timeline_range,
216        source_range: entry.source_range,
217        time_map: &entry.time_map,
218        mirror: frame_mirror,
219        scale: indexed.reference.scale,
220        timeline_time: time,
221    };
222    Ok(Some(ActiveComposition::new(plan, local).shown_by(shown_by)))
223}
224
225/// A transition's linear progress, `clamp((t - start + F/2) / D, 0, 1)`.
226///
227/// `F` is one project frame and `D` the duration. Sampling at frame centres makes frame `i` of
228/// `N` show `(i + 0.5) / N`, so every frame mixes both clips and reversed playback shows `1 - p`.
229fn centred_progress(range: TimeRange, frame_rate: FrameRate, time: MediaTime) -> f64 {
230    let elapsed = i128::from(time.ticks()) - i128::from(range.start().ticks());
231    let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
232    // F / 2 = TICKS_PER_SECOND * den / (2 * num); scale by 2 * num to stay exact until the division.
233    let num = i128::from(frame_rate.numerator());
234    let den = i128::from(frame_rate.denominator());
235    let numerator = 2 * num * elapsed + i128::from(TICKS_PER_SECOND) * den;
236    let denominator = 2 * num * duration;
237    #[allow(clippy::cast_precision_loss)]
238    let progress = (numerator as f64 / denominator as f64).clamp(0.0, 1.0);
239    progress
240}
241
242/// Describes all source frames needed at a timestamp.
243///
244/// The list is in evaluation order with no duplicate `(source, timestamp)` pairs. Generated
245/// sources and audio clips need no frames. A visual clip needs its own source only when it draws
246/// it ([`ActiveClip::needs_source`]) plus every source its composition reads, and its own source
247/// once more per step that draws the clip at another time inside the clip
248/// ([`ActiveComposition::shifted_clips`]), each with the step as its reader. A matte clip needs
249/// frames only while an active clip names it ([`FrameDesc::draws`]).
250///
251/// # Errors
252///
253/// Returns any error emitted by [`evaluate`].
254pub fn frame_needs(
255    project: &Project,
256    index: &ActiveIndex,
257    time: MediaTime,
258) -> Result<Vec<FrameNeed>, EvalError> {
259    let frame = evaluate(project, index, time)?;
260    let mut needs = Needs::default();
261    for item in frame.visual.iter().filter(|item| frame.draws(item)) {
262        let mixes = !item.frame_interpolation.is_hold();
263        if item.needs_source() {
264            needs.ask(
265                item.clip_id,
266                item.source_id,
267                item.source_time,
268                mixes,
269                || None,
270            );
271        }
272        let plans = item
273            .composition
274            .iter()
275            .map(|composition| (composition, false))
276            .chain(
277                item.source_composition
278                    .iter()
279                    .map(|composition| (composition, true)),
280            );
281        for (composition, of_source) in plans {
282            let steps = &composition.plan().steps;
283            for (step, source_id, time, interpolation) in composition.media() {
284                let node = &steps[step].node;
285                // Prefix source-composition steps with `/`, which no own-composition path starts with.
286                needs.ask(
287                    item.clip_id,
288                    source_id,
289                    time,
290                    !interpolation.is_hold(),
291                    || {
292                        if of_source {
293                            alpha2_model::NodeId::new(format!("/{node}")).ok()
294                        } else {
295                            Some(node.clone())
296                        }
297                    },
298                );
299            }
300        }
301        for composition in item.composition.iter().filter(|_| item.has_host_picture()) {
302            for (step, time) in composition.shifted_clips() {
303                if let Some(time) = time {
304                    needs.ask(item.clip_id, item.source_id, time, mixes, || {
305                        Some(composition.plan().steps[step].node.clone())
306                    });
307                }
308            }
309        }
310    }
311    Ok(needs.list)
312}
313
314/// Needs deduplicated by linear scan before switching to a hash set. Frames usually need only a
315/// few sources, but a composition may read tens of thousands.
316pub(crate) const SCANNED_NEEDS: usize = 32;
317
318#[cfg(test)]
319thread_local! {
320    /// Comparisons made by [`Needs::ask`] on this thread.
321    pub(crate) static COMPARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
322}
323
324#[derive(Default)]
325struct Needs<'a> {
326    list: Vec<FrameNeed>,
327    /// Needs past the first [`SCANNED_NEEDS`], borrowing IDs so lookups clone nothing.
328    hashed: std::collections::HashSet<(&'a alpha2_media::SourceId, MediaTime)>,
329}
330
331impl<'a> Needs<'a> {
332    /// Records `source_id` at `media_time` unless already recorded. `reader` runs only for a new
333    /// need.
334    fn ask(
335        &mut self,
336        clip_id: &alpha2_model::ClipId,
337        source_id: &'a alpha2_media::SourceId,
338        media_time: MediaTime,
339        following: bool,
340        reader: impl FnOnce() -> Option<alpha2_model::NodeId>,
341    ) {
342        let scanned = &self.list[..self.list.len().min(SCANNED_NEEDS)];
343        #[cfg(test)]
344        COMPARED.with(|compared| compared.set(compared.get() + scanned.len()));
345        let repeat = scanned
346            .iter()
347            .any(|need| need.media_time == media_time && need.source_id == *source_id)
348            || (self.list.len() > SCANNED_NEEDS && self.hashed.contains(&(source_id, media_time)));
349        if repeat {
350            if following {
351                self.follow(source_id, media_time);
352            }
353            return;
354        }
355        if self.list.len() >= SCANNED_NEEDS {
356            self.hashed.insert((source_id, media_time));
357        }
358        self.list.push(FrameNeed {
359            clip_id: clip_id.clone(),
360            reader: reader(),
361            source_id: source_id.clone(),
362            media_time,
363            following,
364        });
365    }
366
367    fn follow(&mut self, source_id: &alpha2_media::SourceId, media_time: MediaTime) {
368        if let Some(need) = self
369            .list
370            .iter_mut()
371            .find(|need| need.media_time == media_time && need.source_id == *source_id)
372        {
373            need.following = true;
374        }
375    }
376}
377
378pub(crate) fn ensure_index_matches(
379    project: &Project,
380    index: &ActiveIndex,
381) -> Result<(), EvalError> {
382    if project.id == index.project_id {
383        Ok(())
384    } else {
385        Err(EvalError::IndexProjectMismatch {
386            index_project: index.project_id.clone(),
387            evaluated_project: project.id.clone(),
388        })
389    }
390}