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