Skip to main content

alpha2_eval/
index.rs

1//! The per-snapshot interval index that frame and audio evaluation query.
2//!
3//! The evaluator has no GPU, decoder, filesystem, clock or global state. A host builds an
4//! [`ActiveIndex`] once per immutable [`Project`] and may evaluate any timestamp on any thread.
5
6use crate::{EvalError, IndexedCaptions, IndexedClip, IndexedTransition, IntervalNode, build_tree};
7use alpha2_media::SourceId;
8use alpha2_model::{CompositionId, Project, ProjectId};
9use alpha2_time::TimeRange;
10
11/// A precomputed interval index for a validated project snapshot.
12#[derive(Clone, Debug)]
13pub struct ActiveIndex {
14    pub(crate) project_id: ProjectId,
15    pub(crate) nodes: Vec<IntervalNode>,
16    pub(crate) root: Option<usize>,
17    pub(crate) transitions: Vec<IndexedTransition>,
18    /// Caption tracks in track order.
19    pub(crate) captions: Vec<IndexedCaptions>,
20    /// The most clips active at any one instant.
21    pub(crate) max_active: usize,
22    /// The project's data sets and clips by id, for data bindings.
23    pub(crate) data: crate::DataIndex,
24    /// Whether the compositions together exceed [`crate::MAX_PLAN_BYTES`], so none draws.
25    pub(crate) plans_too_large: bool,
26}
27
28impl ActiveIndex {
29    /// The data index for sampling `project`'s timeline-time values; `project` must be the one
30    /// this index was built from.
31    #[must_use]
32    pub fn sample_context<'a>(
33        &'a self,
34        project: &'a alpha2_model::Project,
35    ) -> crate::SampleContext<'a> {
36        crate::SampleContext::timeline(project, &self.data)
37    }
38
39    /// The project's data sets and clips by id.
40    #[must_use]
41    pub const fn data(&self) -> &crate::DataIndex {
42        &self.data
43    }
44
45    /// Builds an immutable interval tree from a structurally valid project.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`EvalError::InvalidProject`] when the model is invalid.
50    #[allow(clippy::too_many_lines)]
51    pub fn build(project: &Project) -> Result<Self, EvalError> {
52        project.validate().map_err(EvalError::InvalidProject)?;
53        let mut entries = Vec::new();
54        let mut transitions = Vec::new();
55        let matte_sources = project.timeline.matte_sources();
56        let lookup = crate::composition::Lookup::new(
57            &project.compositions,
58            &project.sources,
59            (project.settings.width, project.settings.height),
60        );
61        let (plans, source_plans, plans_too_large) = compile_plans(project, &lookup);
62        let sources = project
63            .sources
64            .iter()
65            .map(|source| (&source.id, source))
66            .collect::<std::collections::HashMap<_, _>>();
67        let generators = generator_plans(project);
68        for (track_order, track) in project.timeline.tracks.iter().enumerate() {
69            for (clip_order, clip) in track.clips.iter().enumerate() {
70                // Validation guarantees the source exists.
71                let source = sources.get(&clip.source_id).copied();
72                let source_is_audible = source.is_some_and(alpha2_model::MediaSource::is_audible);
73                let generator = source.and_then(|source| source.generator.clone());
74                // A composition source is planned only if the clip's own composition draws the clip.
75                let drawn = clip
76                    .composition
77                    .as_ref()
78                    .is_none_or(|reference| lookup.reads().draws_clip(&reference.id));
79                let source_composition = source
80                    .filter(|_| drawn)
81                    .and_then(|source| source_composition_of(source, &source_plans));
82                entries.push(IndexedClip {
83                    clip_id: clip.id.clone(),
84                    source_id: clip.source_id.clone(),
85                    track_id: track.id.clone(),
86                    track_kind: track.kind,
87                    timeline_range: clip.timeline_range,
88                    source_range: clip.source_range,
89                    time_map: clip.time_map,
90                    visual: clip.visual.clone(),
91                    // Validation guarantees the composition exists.
92                    composition: clip.composition.as_ref().and_then(|reference| {
93                        plans
94                            .get(&reference.id)
95                            .map(|plan| crate::IndexedComposition {
96                                plan: std::sync::Arc::clone(plan),
97                                reference: reference.clone(),
98                            })
99                    }),
100                    blend_mode: clip.blend_mode,
101                    cache: clip.cache,
102                    masks: clip.masks.clone(),
103                    matte: clip.matte.clone(),
104                    is_matte: matte_sources.contains(&clip.id),
105                    adjustment: source
106                        .is_some_and(|source| source.kind == alpha2_model::MediaKind::Adjustment),
107                    audio: clip.audio.clone(),
108                    source_is_audible,
109                    generator,
110                    plan: generators.get(&clip.source_id).cloned(),
111                    source_composition,
112                    track_order,
113                    clip_order,
114                });
115            }
116            transitions.extend(track.transitions.iter().enumerate().map(
117                |(list_order, transition)| IndexedTransition {
118                    from_clip: transition.from_clip.clone(),
119                    to_clip: transition.to_clip.clone(),
120                    timeline_range: transition.timeline_range,
121                    easing: transition.easing,
122                    effect: transition.effect.clone(),
123                    track_order,
124                    list_order,
125                },
126            ));
127        }
128        let captions = project
129            .timeline
130            .tracks
131            .iter()
132            .enumerate()
133            .filter_map(|(track_order, track)| {
134                track.captions.as_ref().map(|captions| {
135                    let mut shown = captions.clone();
136                    if shown.from_words.is_some() {
137                        shown.cues = crate::caption_cues(project, &track.id, captions)
138                            .map_err(EvalError::InvalidProject)?;
139                    }
140                    Ok(IndexedCaptions::new(track.id.clone(), track_order, shown))
141                })
142            })
143            .collect::<Result<_, EvalError>>()?;
144        entries.sort_unstable_by_key(|entry| {
145            (
146                entry.timeline_range.start(),
147                entry.track_order,
148                entry.clip_order,
149            )
150        });
151        let max_active = deepest_overlap(&entries);
152        let (nodes, root) = build_tree(entries);
153        transitions.sort_unstable_by_key(|transition| {
154            (
155                transition.timeline_range.start(),
156                transition.track_order,
157                transition.list_order,
158            )
159        });
160        Ok(Self {
161            project_id: project.id.clone(),
162            nodes,
163            root,
164            transitions,
165            captions,
166            max_active,
167            data: crate::DataIndex::new(project),
168            plans_too_large,
169        })
170    }
171
172    /// The errors [`crate::evaluate`] would return in `range` because a clip shows a composition
173    /// that cannot draw, one per clip, in the order the clips start. An export checks its range
174    /// with this before its first frame instead of failing at the frame that shows the clip. When
175    /// the compositions together exceed [`crate::MAX_PLAN_BYTES`] (see [`Self::plans_too_large`])
176    /// only the first is listed, since the cause is the whole document.
177    #[must_use]
178    pub fn plan_errors(&self, range: TimeRange) -> Vec<EvalError> {
179        let mut found = Vec::new();
180        for entry in self.nodes.iter().map(IntervalNode::entry) {
181            if entry.track_kind != alpha2_model::TrackKind::Video
182                || entry.timeline_range.intersection(range).is_none()
183            {
184                continue;
185            }
186            let own = entry
187                .composition
188                .as_ref()
189                .map(|indexed| (&indexed.reference.id, &indexed.plan));
190            let shown = entry
191                .source_composition
192                .as_ref()
193                .map(|(id, plan)| (id, plan));
194            if let Some((composition, Err(reason))) = own
195                .into_iter()
196                .chain(shown)
197                .map(|(id, plan)| (id, plan.as_ref().as_ref()))
198                .find(|(_, plan)| plan.is_err())
199            {
200                found.push((
201                    entry.timeline_range.start(),
202                    entry.track_order,
203                    EvalError::IncompleteComposition {
204                        clip: entry.clip_id.clone(),
205                        composition: composition.clone(),
206                        reason: reason.clone(),
207                    },
208                ));
209            }
210        }
211        found.sort_by_key(|(start, track, _)| (*start, *track));
212        if self.plans_too_large {
213            found.truncate(1);
214        }
215        found.into_iter().map(|(_, _, error)| error).collect()
216    }
217
218    /// Whether the project's compositions together exceed [`crate::MAX_PLAN_BYTES`], so none draws.
219    #[must_use]
220    pub const fn plans_too_large(&self) -> bool {
221        self.plans_too_large
222    }
223
224    /// Returns the project identity used to build this index.
225    #[must_use]
226    pub fn project_id(&self) -> &ProjectId {
227        &self.project_id
228    }
229
230    /// Returns the number of clips indexed.
231    #[must_use]
232    pub fn len(&self) -> usize {
233        self.nodes.len()
234    }
235
236    /// Returns whether the index has no clips.
237    #[must_use]
238    pub fn is_empty(&self) -> bool {
239        self.nodes.is_empty()
240    }
241
242    /// Every effect invocation the project can draw: steps of each compiled composition (once
243    /// each, in order of first use) and each transition.
244    pub fn effects(&self) -> impl Iterator<Item = &alpha2_model::ClipEffect> {
245        let mut seen = std::collections::HashSet::new();
246        let plans = self
247            .nodes
248            .iter()
249            .flat_map(|node| clip_plans(node.entry()))
250            .flatten()
251            .filter(|slot| seen.insert(std::sync::Arc::as_ptr(slot)))
252            .filter_map(|slot| slot.as_ref().as_ref().ok())
253            .collect::<Vec<_>>();
254        plans
255            .into_iter()
256            .flat_map(crate::CompositionPlan::effects)
257            .chain(self.transitions.iter().map(|transition| &transition.effect))
258    }
259
260    /// Peak number of concurrent host-source reads selected by `counted` in `range`, or 0.
261    ///
262    /// Each read (a clip's own source per [`crate::ActiveClip::needs_source`], or a media step of
263    /// its compositions) gets its own decoder cursor in [`crate::frame_needs`], so this is the
264    /// number of decoders active at once.
265    #[must_use]
266    pub fn peak_source_reads(
267        &self,
268        range: TimeRange,
269        mut counted: impl FnMut(&SourceId) -> bool,
270    ) -> usize {
271        // Keyed by the shared plan allocation so each composition is counted once.
272        let mut plan_reads = std::collections::HashMap::new();
273        let mut events = Vec::new();
274        for entry in self.nodes.iter().map(IntervalNode::entry) {
275            let Some(span) = entry.timeline_range.intersection(range) else {
276                continue;
277            };
278            let [composition, source_composition] = clip_plans(entry);
279            let mut reads = usize::from(draws_own_source(entry) && counted(&entry.source_id));
280            for slot in [composition, source_composition].into_iter().flatten() {
281                reads += *plan_reads
282                    .entry(std::sync::Arc::as_ptr(slot))
283                    .or_insert_with(|| {
284                        slot.as_ref().as_ref().map_or(0, |plan| {
285                            plan.steps
286                                .iter()
287                                .filter(|step| match &step.op {
288                                    crate::StepOp::Media { source_id, .. } => counted(source_id),
289                                    _ => false,
290                                })
291                                .count()
292                        })
293                    });
294            }
295            if reads > 0 {
296                let delta = isize::try_from(reads).unwrap_or(isize::MAX);
297                events.extend([(span.start(), delta), (span.end(), -delta)]);
298            }
299        }
300        // Half-open ranges: ends sort before starts at the same instant.
301        events.sort_unstable_by_key(|&(time, delta)| (time, delta.signum()));
302        let mut active = 0_usize;
303        let mut peak = 0;
304        for (_, delta) in events {
305            active = active.saturating_add_signed(delta);
306            peak = peak.max(active);
307        }
308        peak
309    }
310
311    /// Every host-source read selected by `counted` over `range`, in index order, with readers
312    /// named as in [`crate::frame_needs`]. These are the reads [`Self::peak_source_reads`] counts.
313    ///
314    /// A reader reads only inside its span, so a host can close its decoder once the span ends.
315    /// Within the span it may still skip frames (deduplicated needs, unused mattes).
316    #[must_use]
317    pub fn source_reads(
318        &self,
319        range: TimeRange,
320        mut counted: impl FnMut(&SourceId) -> bool,
321    ) -> Vec<SourceRead> {
322        let mut reads = Vec::new();
323        for entry in self.nodes.iter().map(IntervalNode::entry) {
324            let Some(span) = entry.timeline_range.intersection(range) else {
325                continue;
326            };
327            let read = |source_id: &SourceId, reader| SourceRead {
328                source_id: source_id.clone(),
329                clip_id: entry.clip_id.clone(),
330                reader,
331                span,
332            };
333            if draws_own_source(entry) && counted(&entry.source_id) {
334                reads.push(read(&entry.source_id, None));
335            }
336            let [composition, source_composition] = clip_plans(entry);
337            for (slot, of_source) in [(composition, false), (source_composition, true)] {
338                let Some(Ok(plan)) = slot.map(|slot| slot.as_ref().as_ref()) else {
339                    continue;
340                };
341                for step in &plan.steps {
342                    let crate::StepOp::Media { source_id, .. } = &step.op else {
343                        continue;
344                    };
345                    if !counted(source_id) {
346                        continue;
347                    }
348                    let reader = if of_source {
349                        alpha2_model::NodeId::new(format!("/{}", step.node)).ok()
350                    } else {
351                        Some(step.node.clone())
352                    };
353                    reads.push(read(source_id, reader));
354                }
355            }
356        }
357        reads
358    }
359}
360
361/// One reader of a source over an export range ([`ActiveIndex::source_reads`]).
362#[derive(Clone, Debug, Eq, PartialEq)]
363pub struct SourceRead {
364    /// The source read.
365    pub source_id: SourceId,
366    /// The clip that reads it or shows the reading composition.
367    pub clip_id: alpha2_model::ClipId,
368    /// The reading composition step as in [`crate::FrameNeed::reader`]; `None` for the clip.
369    pub reader: Option<alpha2_model::NodeId>,
370    /// Where on the timeline it may read.
371    pub span: TimeRange,
372}
373
374fn draws_own_source(entry: &IndexedClip) -> bool {
375    let [composition, source_composition] = clip_plans(entry);
376    entry.generator.is_none()
377        && source_composition.is_none()
378        && composition.is_none_or(|slot| {
379            slot.as_ref()
380                .as_ref()
381                .is_ok_and(crate::CompositionPlan::uses_clip)
382        })
383}
384
385/// The compiled compositions `entry` draws: its own, then its composition source's.
386fn clip_plans(entry: &IndexedClip) -> [Option<&PlanSlot>; 2] {
387    [
388        entry
389            .composition
390            .as_ref()
391            .map(|composition| &composition.plan),
392        entry.source_composition.as_ref().map(|(_, plan)| plan),
393    ]
394}
395
396type Plans<'a> = std::collections::HashMap<&'a CompositionId, PlanSlot>;
397
398/// Compiles each used composition once. Together they hold at most [`crate::MAX_PLAN_BYTES`];
399/// past that none draws, so the outcome does not depend on compile order.
400fn compile_plans<'a>(
401    project: &'a Project,
402    lookup: &crate::composition::Lookup<'a>,
403) -> (Plans<'a>, Plans<'a>, bool) {
404    let shown = project
405        .timeline
406        .tracks
407        .iter()
408        .flat_map(|track| &track.clips)
409        .filter_map(|clip| clip.composition.as_ref().map(|reference| &reference.id))
410        .collect::<std::collections::HashSet<_>>();
411    // The composition sources a clip draws, or a media node may read.
412    let sourced = project
413        .sources
414        .iter()
415        .filter_map(|source| source.composition.as_ref())
416        .collect::<std::collections::HashSet<_>>();
417    let mut budget = crate::composition::PlanBudget::new(crate::MAX_PLAN_BYTES);
418    let mut plans = Plans::new();
419    let mut source_plans = Plans::new();
420    let refused = std::sync::Arc::new(Err(crate::PlanError::TooLarge));
421    for composition in &project.compositions {
422        // Past the budget nothing draws, so nothing more is compiled.
423        if budget.exceeded() {
424            if shown.contains(&composition.id) {
425                plans.insert(&composition.id, std::sync::Arc::clone(&refused));
426            }
427            if sourced.contains(&composition.id) {
428                source_plans.insert(&composition.id, std::sync::Arc::clone(&refused));
429            }
430            continue;
431        }
432        if shown.contains(&composition.id) {
433            let plan =
434                crate::composition::plan_composition_within(composition, lookup, &mut budget);
435            plans.insert(&composition.id, std::sync::Arc::new(plan));
436        }
437        if sourced.contains(&composition.id) {
438            let plan = crate::composition::plan_source_composition_within(
439                composition,
440                lookup,
441                &mut budget,
442            );
443            source_plans.insert(&composition.id, std::sync::Arc::new(plan));
444        }
445    }
446    if budget.exceeded() {
447        for plan in plans.values_mut().chain(source_plans.values_mut()) {
448            *plan = std::sync::Arc::clone(&refused);
449        }
450    }
451    (plans, source_plans, budget.exceeded())
452}
453
454fn source_composition_of(
455    source: &alpha2_model::MediaSource,
456    plans: &Plans<'_>,
457) -> Option<(CompositionId, PlanSlot)> {
458    let id = source.composition.as_ref()?;
459    Some((id.clone(), std::sync::Arc::clone(plans.get(id)?)))
460}
461
462/// A compiled plan shared by every clip showing its composition, or the reason it cannot draw.
463pub(crate) type PlanSlot = std::sync::Arc<Result<crate::CompositionPlan, crate::PlanError>>;
464
465fn deepest_overlap(entries: &[IndexedClip]) -> usize {
466    // Half-open intervals: ends (-1) sort before starts (+1) at the same instant.
467    let mut edges: Vec<_> = entries
468        .iter()
469        .flat_map(|entry| {
470            [
471                (entry.timeline_range.start(), 1_i8),
472                (entry.timeline_range.end(), -1),
473            ]
474        })
475        .collect();
476    edges.sort_unstable();
477    let mut depth = 0_usize;
478    let mut deepest = 0;
479    for (_, step) in edges {
480        depth = depth.saturating_add_signed(isize::from(step));
481        deepest = deepest.max(depth);
482    }
483    deepest
484}
485
486/// Plans each shapes or layout source once, however many clips show it.
487fn generator_plans(
488    project: &Project,
489) -> std::collections::HashMap<&SourceId, std::sync::Arc<crate::GeneratorPlan>> {
490    project
491        .sources
492        .iter()
493        .filter_map(|source| {
494            let plan = crate::GeneratorPlan::new(
495                source.generator.as_ref()?,
496                (project.settings.width, project.settings.height),
497            )?;
498            Some((&source.id, std::sync::Arc::new(plan)))
499        })
500        .collect()
501}