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