Skip to main content

alpha2_eval/
composition.rs

1//! Composition graphs resolved into the steps that draw their output.
2//!
3//! A composition is compiled once, when the index is built. Nodes reachable from the output are
4//! put in dependency order, bypassed nodes are replaced by their pass-through input, and group
5//! nodes and composition-source media nodes are inlined (the latter shifted by the node's start).
6//! A time offset node's input is planned once more, shifted by the node's offset. The result
7//! equals the flattened graph, so evaluating a frame only samples step settings.
8//!
9//! Inlining copies settings per step. Validation bounds the step count ([`MAX_INLINED_NODES`])
10//! and the planner bounds total plan size ([`MAX_PLAN_BYTES`]).
11
12use alpha2_media::SourceId;
13use alpha2_model::{
14    Animated, AnimatedPoint, ClipBlendMode, ClipEffect, Composition, CompositionId,
15    CompositionReads, EffectValue, Generator, Keyframe, MAX_COMPOSITION_DEPTH, MAX_INLINED_NODES,
16    MatteMode, MediaKind, MediaSource, NodeId, NodeOp, Paint, ShapeMask, VisualProperties,
17};
18use alpha2_time::MediaTime;
19use std::collections::{BTreeMap, HashMap};
20use std::sync::Arc;
21
22use crate::GeneratorPlan;
23
24/// Most bytes all compiled composition plans of one project may hold together, estimated per
25/// [`Step`] (node path plus settings heap). Past this none draws ([`PlanError::TooLarge`]).
26pub const MAX_PLAN_BYTES: u64 = 256 * 1024 * 1024;
27
28/// A composition's output, drawn by steps in dependency order.
29#[derive(Clone, Debug, PartialEq)]
30pub struct CompositionPlan {
31    /// The composition.
32    pub id: CompositionId,
33    /// Steps in dependency order; each step's inputs are earlier steps.
34    pub steps: Vec<Step>,
35    /// The step whose image is the composition's picture.
36    pub output: usize,
37    /// Every `media` node of the compositions the steps come from, drawn or not, by inlined path,
38    /// with its start: what a value bound to data reads through.
39    pub media: Vec<(String, MediaTime)>,
40}
41
42impl CompositionPlan {
43    /// The effect, transition and generator effect invocations the steps run, in step order.
44    pub fn effects(&self) -> impl Iterator<Item = &ClipEffect> {
45        self.steps.iter().filter_map(|step| match &step.op {
46            StepOp::Effect { effect, .. }
47            | StepOp::Transition { effect, .. }
48            | StepOp::Generator {
49                generator: Generator::Effect { effect },
50                ..
51            } => Some(effect),
52            _ => None,
53        })
54    }
55
56    /// The start of the `media` node `via` beside step `step`, found as the node of that id in
57    /// the same inlined composition, past the ids of the time offset nodes the step is read
58    /// through.
59    #[must_use]
60    pub fn media_start(&self, step: usize, via: &alpha2_model::NodeId) -> Option<MediaTime> {
61        let path = self.steps.get(step)?.node.as_str();
62        let mut prefix = path.rfind('/').map_or("", |slash| &path[..=slash]);
63        loop {
64            let found = self.media.iter().find_map(|(node, start)| {
65                (node.strip_prefix(prefix) == Some(via.as_str())).then_some(*start)
66            });
67            if found.is_some() {
68                return found;
69            }
70            let outer = prefix.strip_suffix('/')?;
71            prefix = outer.rfind('/').map_or("", |slash| &outer[..=slash]);
72        }
73    }
74
75    /// Whether a step draws the picture of the clip showing the plan at the frame's own time.
76    #[must_use]
77    pub fn uses_clip(&self) -> bool {
78        self.steps
79            .iter()
80            .any(|step| matches!(step.op, StepOp::Clip))
81    }
82
83    /// Whether a step draws the picture of the clip showing the plan, at the frame's own time
84    /// or at another.
85    #[must_use]
86    pub fn draws_clip(&self) -> bool {
87        self.steps
88            .iter()
89            .any(|step| matches!(step.op, StepOp::Clip | StepOp::ShiftedClip { .. }))
90    }
91
92    /// The steps that draw the clip showing the plan at another time, with their shifts.
93    pub fn shifted_clips(&self) -> impl Iterator<Item = (usize, MediaTime)> + '_ {
94        self.steps
95            .iter()
96            .enumerate()
97            .filter_map(|(index, step)| match step.op {
98                StepOp::ShiftedClip { shift } => Some((index, shift)),
99                _ => None,
100            })
101    }
102}
103
104/// One node of a composition, with its inputs resolved to earlier steps.
105#[derive(Clone, Debug, PartialEq)]
106pub struct Step {
107    /// The node path: ids of the group, media and time offset nodes it is drawn through, then
108    /// its own, joined by `/`.
109    pub node: NodeId,
110    /// What it draws.
111    pub op: StepOp,
112    /// Added to the plan's time to sample this step: the starts of the media nodes inlined
113    /// through and the offsets of the time offset nodes it is read through.
114    pub offset: MediaTime,
115}
116
117impl Step {
118    /// The time this step's settings are sampled at when the plan is drawn at `time`.
119    #[must_use]
120    pub fn time(&self, time: MediaTime) -> MediaTime {
121        MediaTime(time.ticks().saturating_add(self.offset.ticks()))
122    }
123}
124
125/// The operation of a [`Step`]. Inputs are indices of earlier steps.
126#[derive(Clone, Debug, PartialEq)]
127pub enum StepOp {
128    /// The picture of the clip showing the composition.
129    Clip,
130    /// The picture of the clip showing the composition as time offset nodes read it: the clip
131    /// at the timeline time `shift` of composition time away
132    /// ([`alpha2_model::TimeScale::shifted_time`]), transparent outside the clip.
133    ShiftedClip {
134        /// The offsets it is read through, added; never zero.
135        shift: MediaTime,
136    },
137    /// A host-supplied source at `start` plus the composition time.
138    Media {
139        /// The source.
140        source_id: SourceId,
141        /// Source time at composition time zero.
142        start: MediaTime,
143        /// What the step shows between two frames of the source; `Hold` for a source without
144        /// frames.
145        frame_interpolation: alpha2_model::FrameInterpolation,
146    },
147    /// A picture the engine draws (a generator node, or a media node naming a generated source).
148    Generator {
149        /// What it draws.
150        generator: Generator,
151        /// Picture time at composition time zero: a media node's start, zero for a generator node.
152        start: MediaTime,
153        /// Planned tree for a shapes or layout generator.
154        plan: Option<Arc<GeneratorPlan>>,
155    },
156    /// A registered effect.
157    Effect {
158        /// The processed image.
159        input: usize,
160        /// Additional named inputs, in name order.
161        inputs: Vec<(String, usize)>,
162        /// The effect.
163        effect: ClipEffect,
164    },
165    /// A registered transition at an explicit progress.
166    Transition {
167        /// The image at progress zero.
168        from: usize,
169        /// The image at progress one.
170        to: usize,
171        /// The transition.
172        effect: ClipEffect,
173        /// Progress in `0..=1`.
174        progress: Animated<f32>,
175    },
176    /// The input placed by a transform.
177    Transform {
178        /// The placed image.
179        input: usize,
180        /// The transform.
181        transform: VisualProperties,
182        /// Whether its motion is averaged over the frame's shutter.
183        motion_blur: bool,
184    },
185    /// Layers composited over transparency, bottom first.
186    Merge {
187        /// The layers.
188        layers: Vec<StepLayer>,
189    },
190    /// The input kept where a second image says.
191    Matte {
192        /// The kept image.
193        input: usize,
194        /// The coverage image.
195        matte: usize,
196        /// Which property of the coverage image counts.
197        mode: MatteMode,
198    },
199    /// The backdrop replaced by the input by `k = opacity x mask alpha`.
200    KeyMix {
201        /// The replaced picture.
202        backdrop: usize,
203        /// The picture replacing it.
204        input: usize,
205        /// The coverage image; `None` covers everywhere.
206        mask: Option<usize>,
207        /// Scales the coverage, in `0..=1`.
208        opacity: Animated<f32>,
209    },
210    /// The input kept inside shapes.
211    ShapeMask {
212        /// The masked image.
213        input: usize,
214        /// The shapes.
215        masks: Vec<ShapeMask>,
216    },
217}
218
219/// One layer of a [`StepOp::Merge`].
220#[derive(Clone, Debug, PartialEq)]
221pub struct StepLayer {
222    /// The layer's image.
223    pub input: usize,
224    /// Its blend mode.
225    pub blend_mode: ClipBlendMode,
226    /// Its opacity.
227    pub opacity: Animated<f32>,
228}
229
230/// Why a composition's output cannot be drawn.
231#[derive(Clone, Debug, PartialEq, Eq)]
232pub enum PlanError {
233    /// The composition selects no output.
234    NoOutput,
235    /// A node the output needs has an unconnected input.
236    MissingInput {
237        /// The node.
238        node: NodeId,
239        /// `input`, `from`, `to`, `matte`, `layers[i]`, `inputs[i]` or `inputs.<name>`.
240        input: String,
241    },
242    /// A group input read where no group node feeds it, or through a time offset node.
243    UnboundGroupInput {
244        /// The node.
245        node: NodeId,
246    },
247    /// A clip node in a composition drawn as a source, which shows no clip.
248    ClipWithoutClip {
249        /// The node.
250        node: NodeId,
251    },
252    /// Compositions and time offsets nest deeper than [`alpha2_model::MAX_COMPOSITION_DEPTH`]
253    /// (unvalidated only).
254    NestedTooDeep {
255        /// The node.
256        node: NodeId,
257    },
258    /// More than [`alpha2_model::MAX_INLINED_NODES`] steps, or the project's plans exceed
259    /// [`MAX_PLAN_BYTES`].
260    TooLarge,
261}
262
263/// Remaining plan bytes, shared by all plans of one project.
264#[derive(Debug)]
265pub(crate) struct PlanBudget {
266    left: u64,
267    exceeded: bool,
268}
269
270impl PlanBudget {
271    pub(crate) const fn new(bytes: u64) -> Self {
272        Self {
273            left: bytes,
274            exceeded: false,
275        }
276    }
277
278    /// Whether a plan needed more than was left.
279    pub(crate) const fn exceeded(&self) -> bool {
280        self.exceeded
281    }
282}
283
284/// A project's compositions and sources by ID, and what each composition reads.
285pub(crate) struct Lookup<'a> {
286    compositions: HashMap<&'a CompositionId, &'a Composition>,
287    sources: HashMap<&'a SourceId, &'a MediaSource>,
288    reads: CompositionReads<'a>,
289    /// The project canvas in pixels.
290    canvas: (u32, u32),
291}
292
293impl<'a> Lookup<'a> {
294    pub(crate) fn new(
295        compositions: &'a [Composition],
296        sources: &'a [MediaSource],
297        canvas: (u32, u32),
298    ) -> Self {
299        let compositions = compositions
300            .iter()
301            .map(|composition| (&composition.id, composition))
302            .collect();
303        let reads = CompositionReads::new(&compositions);
304        Self {
305            compositions,
306            sources: sources.iter().map(|source| (&source.id, source)).collect(),
307            reads,
308            canvas,
309        }
310    }
311
312    /// What each composition reads.
313    pub(crate) const fn reads(&self) -> &CompositionReads<'a> {
314        &self.reads
315    }
316}
317
318/// Compiles `composition`'s output into steps as a clip's composition, where clip nodes draw the
319/// clip's picture. `compositions` resolves group nodes and `sources` resolves media nodes.
320///
321/// The project must be valid ([`alpha2_model::Project::validate`]).
322///
323/// # Errors
324/// Returns [`PlanError`] when there is no output, a needed input is unconnected, or the plan
325/// nests too deep or grows past [`MAX_PLAN_BYTES`].
326pub fn plan_composition(
327    composition: &Composition,
328    compositions: &[Composition],
329    sources: &[MediaSource],
330    canvas: (u32, u32),
331) -> Result<CompositionPlan, PlanError> {
332    plan(
333        composition,
334        &Lookup::new(compositions, sources, canvas),
335        true,
336        &mut PlanBudget::new(MAX_PLAN_BYTES),
337    )
338}
339
340/// [`plan_composition`] drawing from a shared `budget`.
341pub(crate) fn plan_composition_within(
342    composition: &Composition,
343    lookup: &Lookup<'_>,
344    budget: &mut PlanBudget,
345) -> Result<CompositionPlan, PlanError> {
346    plan(composition, lookup, true, budget)
347}
348
349/// Compiles `composition` as a composition source. Like [`plan_composition`], but clip nodes and
350/// group inputs are errors because nothing feeds them.
351///
352/// # Errors
353/// Returns [`PlanError`] as [`plan_composition`] does, and for a needed clip node or group input.
354pub fn plan_source_composition(
355    composition: &Composition,
356    compositions: &[Composition],
357    sources: &[MediaSource],
358    canvas: (u32, u32),
359) -> Result<CompositionPlan, PlanError> {
360    plan(
361        composition,
362        &Lookup::new(compositions, sources, canvas),
363        false,
364        &mut PlanBudget::new(MAX_PLAN_BYTES),
365    )
366}
367
368/// [`plan_source_composition`] drawing from a shared `budget`.
369pub(crate) fn plan_source_composition_within(
370    composition: &Composition,
371    lookup: &Lookup<'_>,
372    budget: &mut PlanBudget,
373) -> Result<CompositionPlan, PlanError> {
374    plan(composition, lookup, false, budget)
375}
376
377fn plan<'a>(
378    composition: &'a Composition,
379    lookup: &Lookup<'a>,
380    clip_allowed: bool,
381    budget: &mut PlanBudget,
382) -> Result<CompositionPlan, PlanError> {
383    let mut planner = Planner {
384        lookup,
385        steps: Vec::new(),
386        media: Vec::new(),
387        budget,
388    };
389    let scope = Scope {
390        composition,
391        inputs: Vec::new(),
392        controls: HashMap::new(),
393        offset: MediaTime::ZERO,
394        prefix: String::new(),
395        clip_allowed,
396        group_inputs_bound: false,
397        depth: 1,
398        shift: MediaTime::ZERO,
399    };
400    let output = planner.output(&scope)?;
401    Ok(CompositionPlan {
402        id: composition.id.clone(),
403        steps: planner.steps,
404        output,
405        media: planner.media,
406    })
407}
408
409/// One composition as it is being drawn: inline in another, or on its own.
410struct Scope<'a> {
411    composition: &'a Composition,
412    /// The step each group input reads, if the composition reads it.
413    inputs: Vec<Option<usize>>,
414    /// Values its group node sets, by node and parameter.
415    controls: HashMap<(&'a NodeId, &'a str), &'a Animated<EffectValue>>,
416    /// Added to the plan's time for its steps.
417    offset: MediaTime,
418    /// Prepended to its node ids in the steps.
419    prefix: String,
420    /// Whether a clip node draws the clip's picture here.
421    clip_allowed: bool,
422    /// Whether a group node feeds its group inputs.
423    group_inputs_bound: bool,
424    /// Nesting depth, one for the plan's own composition.
425    depth: usize,
426    shift: MediaTime,
427}
428
429struct Planner<'a, 'b> {
430    lookup: &'b Lookup<'a>,
431    steps: Vec<Step>,
432    media: Vec<(String, MediaTime)>,
433    budget: &'b mut PlanBudget,
434}
435
436impl<'a> Planner<'a, '_> {
437    /// The step drawing `scope`'s output.
438    fn output(&mut self, scope: &Scope<'a>) -> Result<usize, PlanError> {
439        let output = scope
440            .composition
441            .output
442            .as_ref()
443            .ok_or(PlanError::NoOutput)?;
444        for node in &scope.composition.nodes {
445            if let NodeOp::Media { start, .. } = &node.op {
446                self.media
447                    .push((format!("{}{}", scope.prefix, node.id), *start));
448            }
449        }
450        let nodes: HashMap<&NodeId, &'a alpha2_model::CompositionNode> = scope
451            .composition
452            .nodes
453            .iter()
454            .map(|node| (&node.id, node))
455            .collect();
456        self.resolve(scope, &nodes, output)
457    }
458
459    /// The step drawing node `id` of `scope`, planning its dependencies first.
460    ///
461    /// The walk is iterative so a long chain cannot exhaust the stack. Nesting recurses at most
462    /// [`alpha2_model::MAX_COMPOSITION_DEPTH`] deep, and the planner enforces both limits even
463    /// for unvalidated projects.
464    fn resolve(
465        &mut self,
466        scope: &Scope<'a>,
467        nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
468        id: &'a NodeId,
469    ) -> Result<usize, PlanError> {
470        let mut done: HashMap<&NodeId, usize> = HashMap::new();
471        // Each entry is a node whose needed inputs are pushed before it is revisited.
472        let mut pending = vec![(id, false)];
473        while let Some((current, expanded)) = pending.pop() {
474            if done.contains_key(current) {
475                continue;
476            }
477            let node = nodes[current];
478            let needed = needed_inputs(self.lookup.reads(), &scope.prefix, node)?;
479            if !expanded {
480                pending.push((current, true));
481                let in_this_scope = if shifts(node) { &[][..] } else { &needed[..] };
482                pending.extend(
483                    in_this_scope
484                        .iter()
485                        .rev()
486                        .filter(|input| !done.contains_key(**input))
487                        .map(|input| (*input, false)),
488                );
489                continue;
490            }
491            let step = if node.bypass {
492                done[needed[0]]
493            } else {
494                self.node_step(scope, nodes, node, &done)?
495            };
496            done.insert(current, step);
497        }
498        Ok(done[id])
499    }
500
501    fn generator_step(&self, generator: &Generator, start: MediaTime) -> StepOp {
502        generator_step(generator.clone(), start, self.lookup.canvas)
503    }
504
505    #[expect(clippy::too_many_lines, reason = "one arm per node operation")]
506    fn node_step(
507        &mut self,
508        scope: &Scope<'a>,
509        nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
510        node: &'a alpha2_model::CompositionNode,
511        done: &HashMap<&NodeId, usize>,
512    ) -> Result<usize, PlanError> {
513        let at = |input: &Option<NodeId>| {
514            input
515                .as_ref()
516                .map(|id| done[id])
517                .expect("needed inputs are connected and planned")
518        };
519        let id = || scoped(&scope.prefix, &node.id);
520        let op = match &node.op {
521            NodeOp::Clip {} => {
522                if !scope.clip_allowed {
523                    return Err(PlanError::ClipWithoutClip { node: id() });
524                }
525                if scope.shift == MediaTime::ZERO {
526                    StepOp::Clip
527                } else {
528                    StepOp::ShiftedClip { shift: scope.shift }
529                }
530            }
531            NodeOp::GroupInput { index } => {
532                // Validation keeps the index within the composition's ports.
533                return usize::try_from(*index)
534                    .ok()
535                    .and_then(|index| scope.inputs.get(index).copied().flatten())
536                    .filter(|_| scope.group_inputs_bound)
537                    .ok_or_else(|| PlanError::UnboundGroupInput { node: id() });
538            }
539            NodeOp::TimeOffset { input, offset } => {
540                let input = input.as_ref().expect("needed inputs are connected");
541                return self.shifted(scope, nodes, &id(), input, *offset);
542            }
543            NodeOp::Group {
544                composition,
545                inputs,
546                controls,
547            } => {
548                // Only the ports its composition reads are needed, and planned.
549                let reads = self.lookup.reads();
550                let inputs = inputs
551                    .iter()
552                    .enumerate()
553                    .map(|(port, input)| reads.reads_port(composition, port).then(|| at(input)))
554                    .collect();
555                return self.group(scope, &id(), composition, inputs, controls);
556            }
557            NodeOp::Media {
558                source_id,
559                start,
560                frame_interpolation,
561            } => {
562                let source = self.lookup.sources.get(source_id).copied();
563                if let Some(composition) = source.and_then(|source| source.composition.as_ref()) {
564                    return self.composition_source(scope, &id(), composition, *start);
565                }
566                let generator = source
567                    .filter(|source| source.kind == MediaKind::Generated)
568                    .and_then(|source| source.generator.as_ref());
569                generator.map_or_else(
570                    || StepOp::Media {
571                        source_id: source_id.clone(),
572                        start: *start,
573                        frame_interpolation: source
574                            .filter(|source| source.kind == MediaKind::Video)
575                            .map_or(alpha2_model::FrameInterpolation::Hold, |_| {
576                                *frame_interpolation
577                            }),
578                    },
579                    |generator| self.generator_step(generator, *start),
580                )
581            }
582            NodeOp::Generator { generator } => self.generator_step(generator, MediaTime::ZERO),
583            NodeOp::Effect {
584                input,
585                inputs,
586                effect,
587            } => StepOp::Effect {
588                input: at(input),
589                inputs: named_steps(inputs, &at),
590                effect: controlled(scope, &node.id, effect),
591            },
592            NodeOp::Transition {
593                from,
594                to,
595                effect,
596                progress,
597            } => StepOp::Transition {
598                from: at(from),
599                to: at(to),
600                effect: controlled(scope, &node.id, effect),
601                progress: progress.clone(),
602            },
603            NodeOp::Transform {
604                input,
605                transform,
606                motion_blur,
607            } => StepOp::Transform {
608                input: at(input),
609                transform: transform.clone(),
610                motion_blur: *motion_blur,
611            },
612            NodeOp::Merge { layers } => StepOp::Merge {
613                layers: layers
614                    .iter()
615                    .map(|layer| StepLayer {
616                        input: at(&layer.input),
617                        blend_mode: layer.blend_mode,
618                        opacity: layer.opacity.clone(),
619                    })
620                    .collect(),
621            },
622            NodeOp::Matte { input, matte, mode } => StepOp::Matte {
623                input: at(input),
624                matte: at(matte),
625                mode: *mode,
626            },
627            NodeOp::ShapeMask { input, masks } => StepOp::ShapeMask {
628                input: at(input),
629                masks: masks.clone(),
630            },
631            NodeOp::KeyMix {
632                backdrop,
633                input,
634                mask,
635                opacity,
636            } => StepOp::KeyMix {
637                backdrop: at(backdrop),
638                input: at(input),
639                mask: mask.as_ref().map(|id| done[id]),
640                opacity: opacity.clone(),
641            },
642        };
643        self.push(Step {
644            node: id(),
645            op,
646            offset: scope.offset,
647        })
648    }
649
650    /// Adds `step`, enforcing [`MAX_INLINED_NODES`] and the byte budget.
651    fn push(&mut self, step: Step) -> Result<usize, PlanError> {
652        if self.steps.len() >= MAX_INLINED_NODES {
653            return Err(PlanError::TooLarge);
654        }
655        let bytes = step_bytes(&step);
656        if bytes > self.budget.left {
657            self.budget.exceeded = true;
658            return Err(PlanError::TooLarge);
659        }
660        self.budget.left -= bytes;
661        self.steps.push(step);
662        Ok(self.steps.len() - 1)
663    }
664
665    fn shifted(
666        &mut self,
667        scope: &Scope<'a>,
668        nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
669        node: &NodeId,
670        input: &'a NodeId,
671        offset: MediaTime,
672    ) -> Result<usize, PlanError> {
673        let depth = nested(scope, node)?;
674        let shifted = Scope {
675            composition: scope.composition,
676            inputs: Vec::new(),
677            controls: scope.controls.clone(),
678            offset: MediaTime(scope.offset.ticks().saturating_add(offset.ticks())),
679            prefix: format!("{node}/"),
680            clip_allowed: scope.clip_allowed,
681            group_inputs_bound: false,
682            depth,
683            shift: MediaTime(scope.shift.ticks().saturating_add(offset.ticks())),
684        };
685        self.resolve(&shifted, nodes, input)
686    }
687
688    /// Inlines a group node's composition with its inputs and controls applied.
689    fn group(
690        &mut self,
691        scope: &Scope<'a>,
692        node: &NodeId,
693        composition: &CompositionId,
694        inputs: Vec<Option<usize>>,
695        controls: &'a std::collections::BTreeMap<String, Animated<EffectValue>>,
696    ) -> Result<usize, PlanError> {
697        let target = self.composition(composition);
698        let depth = nested(scope, node)?;
699        let controls = target
700            .controls
701            .iter()
702            .filter_map(|control| {
703                controls
704                    .get(&control.name)
705                    .map(|value| ((&control.node, control.param.as_str()), value))
706            })
707            .collect();
708        self.output(&Scope {
709            composition: target,
710            inputs,
711            controls,
712            offset: scope.offset,
713            prefix: format!("{node}/"),
714            clip_allowed: scope.clip_allowed,
715            group_inputs_bound: true,
716            depth,
717            shift: scope.shift,
718        })
719    }
720
721    /// Inlines a media node's composition source, shifted by `start`.
722    fn composition_source(
723        &mut self,
724        scope: &Scope<'a>,
725        node: &NodeId,
726        composition: &CompositionId,
727        start: MediaTime,
728    ) -> Result<usize, PlanError> {
729        let depth = nested(scope, node)?;
730        self.output(&Scope {
731            composition: self.composition(composition),
732            inputs: Vec::new(),
733            controls: HashMap::new(),
734            offset: MediaTime(scope.offset.ticks().saturating_add(start.ticks())),
735            prefix: format!("{node}/"),
736            clip_allowed: false,
737            group_inputs_bound: false,
738            depth,
739            shift: scope.shift,
740        })
741    }
742
743    fn composition(&self, id: &CompositionId) -> &'a Composition {
744        self.lookup
745            .compositions
746            .get(id)
747            .copied()
748            .expect("validation guarantees referenced compositions exist")
749    }
750}
751
752const fn shifts(node: &alpha2_model::CompositionNode) -> bool {
753    !node.bypass && matches!(node.op, NodeOp::TimeOffset { .. })
754}
755
756fn nested(scope: &Scope<'_>, node: &NodeId) -> Result<usize, PlanError> {
757    let depth = scope.depth + 1;
758    if depth > MAX_COMPOSITION_DEPTH {
759        return Err(PlanError::NestedTooDeep { node: node.clone() });
760    }
761    Ok(depth)
762}
763
764fn scoped(prefix: &str, id: &NodeId) -> NodeId {
765    if prefix.is_empty() {
766        return id.clone();
767    }
768    NodeId::new(format!("{prefix}{id}")).expect("a prefixed id is not empty")
769}
770
771fn named_steps(
772    inputs: &BTreeMap<String, Option<NodeId>>,
773    at: &dyn Fn(&Option<NodeId>) -> usize,
774) -> Vec<(String, usize)> {
775    inputs
776        .iter()
777        .map(|(name, node)| (name.clone(), at(node)))
778        .collect()
779}
780
781fn controlled(scope: &Scope<'_>, node: &NodeId, effect: &ClipEffect) -> ClipEffect {
782    let mut effect = effect.clone();
783    for ((target, param), value) in &scope.controls {
784        if *target == node {
785            effect.params.insert((*param).to_owned(), (*value).clone());
786        }
787    }
788    effect
789}
790
791/// Bytes `step` holds, as [`MAX_PLAN_BYTES`] counts them.
792fn step_bytes(step: &Step) -> u64 {
793    let heap = match &step.op {
794        StepOp::Clip | StepOp::ShiftedClip { .. } | StepOp::Matte { .. } => 0,
795        StepOp::Media { source_id, .. } => source_id.as_str().len(),
796        StepOp::Generator { generator, .. } => generator_bytes(generator),
797        StepOp::Effect { effect, inputs, .. } => {
798            effect_bytes(effect)
799                + inputs
800                    .iter()
801                    .map(|(name, _)| name.len() + size_of::<(String, usize)>())
802                    .sum::<usize>()
803        }
804        StepOp::Transition {
805            effect, progress, ..
806        } => effect_bytes(effect) + keyframe_bytes(progress),
807        StepOp::Transform { transform, .. } => transform_bytes(transform),
808        StepOp::Merge { layers } => layers
809            .iter()
810            .map(|layer| size_of::<StepLayer>() + keyframe_bytes(&layer.opacity))
811            .sum(),
812        StepOp::ShapeMask { masks, .. } => masks.iter().map(mask_bytes).sum(),
813        StepOp::KeyMix { opacity, .. } => keyframe_bytes(opacity),
814    };
815    u64::try_from(size_of::<Step>() + step.node.as_str().len() + heap).unwrap_or(u64::MAX)
816}
817
818/// The heap an animated value's keyframes take; none for a constant.
819fn keyframe_bytes<T>(value: &Animated<T>) -> usize {
820    match value {
821        Animated::Constant { .. } => 0,
822        Animated::Keyframes { keyframes, .. } => keyframes.len() * size_of::<Keyframe<T>>(),
823        Animated::Split { channels } => channel_bytes(channels),
824        Animated::Data(binding) => binding.channel.len(),
825    }
826}
827
828fn channel_bytes(channels: &[Animated<f32>]) -> usize {
829    channels
830        .iter()
831        .map(|channel| size_of::<Animated<f32>>() + keyframe_bytes(channel))
832        .sum()
833}
834
835fn effect_bytes(effect: &ClipEffect) -> usize {
836    effect.id.len()
837        + effect
838            .params
839            .iter()
840            .map(|(name, value)| {
841                name.len() + size_of::<Animated<EffectValue>>() + keyframe_bytes(value)
842            })
843            .sum::<usize>()
844        + effect
845            .resources
846            .iter()
847            .map(|(name, id)| name.len() + id.as_str().len())
848            .sum::<usize>()
849}
850
851fn transform_bytes(transform: &VisualProperties) -> usize {
852    point_bytes(&transform.position)
853        + keyframe_bytes(&transform.scale)
854        + keyframe_bytes(&transform.rotation_degrees)
855        + keyframe_bytes(&transform.opacity)
856}
857
858fn mask_bytes(mask: &ShapeMask) -> usize {
859    size_of::<ShapeMask>() + geometry_bytes(&mask.shape) + keyframe_bytes(&mask.feather)
860}
861
862fn point_bytes(point: &AnimatedPoint) -> usize {
863    match point {
864        AnimatedPoint::Constant { .. } | AnimatedPoint::Data(_) => 0,
865        AnimatedPoint::Split { channels } => channel_bytes(channels),
866        AnimatedPoint::Path(motion) => {
867            keyframe_bytes(&motion.distance)
868                + motion.path.vertex_count() * size_of::<alpha2_model::PathVertex>()
869        }
870        AnimatedPoint::Keyframes { keyframes, .. } => {
871            keyframes.len() * size_of::<alpha2_model::PointKeyframe>()
872        }
873    }
874}
875
876fn path_bytes(path: &Animated<alpha2_model::Path>) -> usize {
877    let one = |path: &alpha2_model::Path| {
878        path.subpaths.len() * size_of::<alpha2_model::Subpath>()
879            + path.vertex_count() * size_of::<alpha2_model::PathVertex>()
880    };
881    match path {
882        Animated::Data(_) | Animated::Split { .. } => 0,
883        Animated::Constant { value } => one(value),
884        Animated::Keyframes { keyframes, .. } => keyframes
885            .iter()
886            .map(|keyframe| size_of::<Keyframe<alpha2_model::Path>>() + one(&keyframe.value))
887            .sum(),
888    }
889}
890
891fn geometry_bytes(geometry: &alpha2_model::ShapeGeometry) -> usize {
892    use alpha2_model::ShapeGeometry;
893    match geometry {
894        ShapeGeometry::Rectangle(rectangle) => {
895            point_bytes(&rectangle.center)
896                + keyframe_bytes(&rectangle.size)
897                + keyframe_bytes(&rectangle.corner_radius)
898                + keyframe_bytes(&rectangle.rotation_degrees)
899        }
900        ShapeGeometry::Ellipse(ellipse) => {
901            point_bytes(&ellipse.center)
902                + keyframe_bytes(&ellipse.size)
903                + keyframe_bytes(&ellipse.rotation_degrees)
904        }
905        ShapeGeometry::Polystar(star) => {
906            point_bytes(&star.center)
907                + keyframe_bytes(&star.points)
908                + keyframe_bytes(&star.outer_radius)
909                + keyframe_bytes(&star.inner_radius)
910                + keyframe_bytes(&star.outer_roundness)
911                + keyframe_bytes(&star.inner_roundness)
912                + keyframe_bytes(&star.rotation_degrees)
913        }
914        ShapeGeometry::Path(path) => path_bytes(&path.path),
915    }
916}
917
918fn paint_bytes(paint: &Paint) -> usize {
919    match paint {
920        Paint::Solid { .. } => 0,
921        Paint::LinearGradient { stops, .. }
922        | Paint::RadialGradient { stops, .. }
923        | Paint::ConicGradient { stops, .. } => {
924            stops.len() * size_of::<alpha2_model::GradientStop>()
925        }
926    }
927}
928
929fn animated_paint_bytes(paint: &Animated<Paint>) -> usize {
930    match paint {
931        Animated::Data(_) | Animated::Split { .. } => 0,
932        Animated::Constant { value } => paint_bytes(value),
933        Animated::Keyframes { keyframes, .. } => keyframes
934            .iter()
935            .map(|keyframe| size_of::<Keyframe<Paint>>() + paint_bytes(&keyframe.value))
936            .sum(),
937    }
938}
939
940/// Approximate bytes a content tree holds. Its plan holds about as much again.
941fn shape_items_bytes(items: &[alpha2_model::ShapeItem]) -> usize {
942    use alpha2_model::{ShapeGeometry, ShapeItem};
943    items
944        .iter()
945        .map(|item| {
946            size_of::<ShapeItem>()
947                + match item {
948                    ShapeItem::Group { items, transform } => {
949                        shape_items_bytes(items)
950                            + keyframe_bytes(&transform.anchor)
951                            + point_bytes(&transform.position)
952                            + keyframe_bytes(&transform.scale)
953                            + keyframe_bytes(&transform.rotation_degrees)
954                            + keyframe_bytes(&transform.opacity)
955                    }
956                    ShapeItem::Rectangle(geometry) => {
957                        geometry_bytes(&ShapeGeometry::Rectangle(geometry.clone()))
958                    }
959                    ShapeItem::Ellipse(geometry) => {
960                        geometry_bytes(&ShapeGeometry::Ellipse(geometry.clone()))
961                    }
962                    ShapeItem::Polystar(geometry) => {
963                        geometry_bytes(&ShapeGeometry::Polystar(geometry.clone()))
964                    }
965                    ShapeItem::Path(geometry) => path_bytes(&geometry.path),
966                    ShapeItem::Fill { paint, opacity, .. } => {
967                        animated_paint_bytes(paint) + keyframe_bytes(opacity)
968                    }
969                    ShapeItem::Stroke(stroke) => {
970                        animated_paint_bytes(&stroke.paint)
971                            + keyframe_bytes(&stroke.width)
972                            + keyframe_bytes(&stroke.opacity)
973                            + stroke.dash.as_ref().map_or(0, |dash| {
974                                dash.pattern
975                                    .iter()
976                                    .map(|entry| size_of::<Animated<f32>>() + keyframe_bytes(entry))
977                                    .sum::<usize>()
978                                    + keyframe_bytes(&dash.offset)
979                            })
980                    }
981                    ShapeItem::Trim(trim) => {
982                        keyframe_bytes(&trim.start)
983                            + keyframe_bytes(&trim.end)
984                            + keyframe_bytes(&trim.offset)
985                    }
986                }
987        })
988        .sum()
989}
990
991fn generator_step(generator: Generator, start: MediaTime, canvas: (u32, u32)) -> StepOp {
992    let plan = GeneratorPlan::new(&generator, canvas).map(Arc::new);
993    StepOp::Generator {
994        generator,
995        start,
996        plan,
997    }
998}
999
1000fn generator_bytes(generator: &Generator) -> usize {
1001    match generator {
1002        Generator::Fill { paint } => paint_bytes(paint),
1003        // Counted twice: the items and their plan.
1004        Generator::Shapes { items } => 2 * shape_items_bytes(items),
1005        Generator::Text { text, style } => {
1006            text.len() + style.font_family.as_ref().map_or(0, String::len)
1007        }
1008        // Counted twice: the tree and its plan.
1009        Generator::Layout { root } => 2 * crate::layout::layout_bytes(root, &shape_items_bytes),
1010        Generator::Effect { effect } => effect_bytes(effect),
1011    }
1012}
1013
1014/// A node's [`CompositionReads::needed_inputs`] in input order, failing on an unconnected one
1015/// (named with `prefix`, like every plan error).
1016fn needed_inputs<'a>(
1017    reads: &CompositionReads<'_>,
1018    prefix: &str,
1019    node: &'a alpha2_model::CompositionNode,
1020) -> Result<Vec<&'a NodeId>, PlanError> {
1021    let needed = reads.needed_inputs(node);
1022    if node.bypass && needed.is_empty() {
1023        // A merge without layers has nothing to pass through.
1024        return Err(PlanError::MissingInput {
1025            node: scoped(prefix, &node.id),
1026            input: "layers[0]".into(),
1027        });
1028    }
1029    needed
1030        .into_iter()
1031        .map(|input| {
1032            input.node().ok_or_else(|| PlanError::MissingInput {
1033                node: scoped(prefix, &node.id),
1034                input: input.name(),
1035            })
1036        })
1037        .collect()
1038}
1039
1040/// A clip's compiled composition and how its time maps onto it.
1041#[derive(Clone, Debug)]
1042pub(crate) struct IndexedComposition {
1043    pub(crate) plan: Arc<Result<CompositionPlan, PlanError>>,
1044    pub(crate) reference: alpha2_model::ClipComposition,
1045}
1046
1047/// A clip's composition at one timeline timestamp.
1048#[derive(Clone, Copy, Debug, PartialEq)]
1049pub struct ActiveComposition<'a> {
1050    plan: &'a CompositionPlan,
1051    time: MediaTime,
1052    data: crate::SampleContext<'a>,
1053    shown_by: Option<ShowingClip<'a>>,
1054}
1055
1056#[derive(Clone, Copy, Debug, PartialEq)]
1057pub(crate) struct ShowingClip<'a> {
1058    pub(crate) timeline_range: alpha2_time::TimeRange,
1059    pub(crate) source_range: alpha2_time::TimeRange,
1060    pub(crate) time_map: &'a alpha2_model::TimeMap,
1061    pub(crate) mirror: crate::Mirror,
1062    pub(crate) scale: alpha2_model::TimeScale,
1063    pub(crate) timeline_time: MediaTime,
1064}
1065
1066impl<'a> ActiveComposition<'a> {
1067    /// `plan` at composition time `time`, reading no data and shown by no clip, so its shifted
1068    /// clip steps are transparent.
1069    #[must_use]
1070    pub const fn new(plan: &'a CompositionPlan, time: MediaTime) -> Self {
1071        Self {
1072            plan,
1073            time,
1074            data: crate::SampleContext::NONE,
1075            shown_by: None,
1076        }
1077    }
1078
1079    pub(crate) const fn shown_by(self, clip: ShowingClip<'a>) -> Self {
1080        Self {
1081            shown_by: Some(clip),
1082            ..self
1083        }
1084    }
1085
1086    /// The same composition reading data through `data`.
1087    #[must_use]
1088    pub const fn with_data(self, data: crate::SampleContext<'a>) -> Self {
1089        Self { data, ..self }
1090    }
1091
1092    /// What step `step`'s settings read data through.
1093    #[must_use]
1094    pub fn step_data(&self, step: usize) -> crate::SampleContext<'a> {
1095        self.data.for_step(self.plan, step)
1096    }
1097
1098    /// The compiled composition.
1099    #[must_use]
1100    pub const fn plan(&self) -> &'a CompositionPlan {
1101        self.plan
1102    }
1103
1104    /// The composition time at which settings are sampled.
1105    #[must_use]
1106    pub const fn time(&self) -> MediaTime {
1107        self.time
1108    }
1109
1110    /// Each host-supplied source a step reads, with step index, source time and what the step
1111    /// shows between two frames.
1112    pub fn media(
1113        &self,
1114    ) -> impl Iterator<
1115        Item = (
1116            usize,
1117            &'a SourceId,
1118            MediaTime,
1119            alpha2_model::FrameInterpolation,
1120        ),
1121    > + 'a {
1122        let time = self.time;
1123        self.plan
1124            .steps
1125            .iter()
1126            .enumerate()
1127            .filter_map(move |(index, step)| match &step.op {
1128                StepOp::Media {
1129                    source_id,
1130                    start,
1131                    frame_interpolation,
1132                } => Some((
1133                    index,
1134                    source_id,
1135                    MediaTime(start.ticks().saturating_add(step.time(time).ticks())),
1136                    *frame_interpolation,
1137                )),
1138                _ => None,
1139            })
1140    }
1141
1142    /// The source time at which a clip step read through offsets adding to `shift` shows the
1143    /// clip: its picture at the shifted timeline time
1144    /// ([`alpha2_model::TimeScale::shifted_time`]) through its time map. `None` when that
1145    /// time is outside the clip, where the step is transparent, and when no clip shows the
1146    /// composition.
1147    #[must_use]
1148    pub fn shifted_clip_time(&self, shift: MediaTime) -> Option<MediaTime> {
1149        let clip = self.shown_by?;
1150        let time = clip
1151            .scale
1152            .shifted_time(clip.timeline_time, shift)
1153            .filter(|time| clip.timeline_range.contains(*time))?;
1154        crate::map_source_time(
1155            clip.timeline_range,
1156            clip.source_range,
1157            clip.time_map,
1158            clip.mirror,
1159            time,
1160        )
1161    }
1162
1163    /// Each step that draws the clip at another time, with the source time it shows
1164    /// ([`Self::shifted_clip_time`]).
1165    pub fn shifted_clips(&self) -> impl Iterator<Item = (usize, Option<MediaTime>)> + use<'a> {
1166        let composition = *self;
1167        self.plan
1168            .shifted_clips()
1169            .map(move |(step, shift)| (step, composition.shifted_clip_time(shift)))
1170    }
1171}
1172
1173#[cfg(test)]
1174#[path = "composition_tests.rs"]
1175mod tests;
1176
1177#[cfg(test)]
1178#[path = "time_offset_tests.rs"]
1179mod time_offset_tests;