Skip to main content

alpha2_model/
composition.rs

1//! Composition graphs: a clip's picture built from connected nodes.
2//!
3//! A [`Composition`] is an acyclic graph of image operations stored once in the project. A
4//! clip refers to it with a [`ClipComposition`], which also maps the clip's timeline time to
5//! composition time. Every node outputs one image and names the nodes it takes inputs from;
6//! inputs may be left unconnected while a graph is being built.
7//!
8//! A [`NodeOp::Group`] node draws another composition, feeding its [`NodeOp::GroupInput`]
9//! nodes and setting its [`CompositionControl`]s per group node. A
10//! [`crate::MediaKind::Composition`] source shows one on the timeline or in a media node.
11//! Compositions may not use themselves. A composition is inlined wherever it is drawn, so
12//! nesting is bounded by [`MAX_COMPOSITION_DEPTH`] and total drawn nodes by
13//! [`MAX_INLINED_NODES`].
14//!
15//! Saving checks structure: names resolve, nothing depends on itself, values are in range.
16//! Rendering additionally requires every input reachable from the output to be connected.
17//! Nodes that do not reach the output are kept and ignored.
18
19use crate::animation::opaque;
20use crate::{
21    Animated, ClipBlendMode, ClipEffect, CompositionId, EffectValue, Generator, MatteMode, NodeId,
22    ShapeMask, VisualProperties,
23};
24use alpha2_media::SourceId;
25use alpha2_time::MediaTime;
26use serde::{Deserialize, Serialize};
27use std::collections::BTreeMap;
28use std::collections::{HashMap, HashSet};
29
30/// Most compositions in one project.
31pub const MAX_COMPOSITIONS: usize = 10_000;
32/// Most nodes in one composition.
33pub const MAX_COMPOSITION_NODES: usize = 256;
34/// The most named inputs an effect node gives its effect, matching what an effect definition
35/// may declare.
36pub const MAX_EFFECT_INPUTS: usize = 8;
37/// Most layers in one merge node.
38pub const MAX_MERGE_LAYERS: usize = 32;
39/// Most inputs a composition takes as a group.
40pub const MAX_GROUP_INPUTS: usize = 16;
41/// Most controls a composition exposes as a group.
42pub const MAX_COMPOSITION_CONTROLS: usize = 64;
43/// Deepest nesting of compositions. A composition that draws no other has depth one; one
44/// that draws others (via group nodes or composition-source media nodes) is one deeper than
45/// the deepest of them.
46pub const MAX_COMPOSITION_DEPTH: usize = 64;
47/// Most nodes the project's compositions draw in total. Each node counts one, except a group
48/// node or composition-source media node, which counts the nodes of the composition it
49/// draws. This bounds compile cost however uses multiply.
50pub const MAX_INLINED_NODES: usize = 65_536;
51/// Most composition nodes the clips at one instant draw together, each clip counted as
52/// [`MAX_INLINED_NODES`] counts its composition and composition source. This bounds per-frame
53/// work to one composition of the largest allowed size.
54pub const MAX_FRAME_INLINED_NODES: usize = 65_536;
55
56/// An acyclic graph of image operations with one selected output.
57#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(deny_unknown_fields)]
60pub struct Composition {
61    /// Stable composition identity.
62    pub id: CompositionId,
63    /// The graph's nodes. Order has no meaning; a node may name a later node as its input.
64    #[serde(default)]
65    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_COMPOSITION_NODES }>")]
66    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_COMPOSITION_NODES)))]
67    pub nodes: Vec<CompositionNode>,
68    /// The node whose image is the composition's picture. A composition without one saves but
69    /// cannot be rendered.
70    #[serde(default)]
71    pub output: Option<NodeId>,
72    /// The images a group node gives it, by name, in port order; its [`NodeOp::GroupInput`]
73    /// nodes read them.
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GROUP_INPUTS }>")]
76    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GROUP_INPUTS)))]
77    pub inputs: Vec<String>,
78    /// The node settings a group node may set, by name.
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_COMPOSITION_CONTROLS }>")]
81    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_COMPOSITION_CONTROLS)))]
82    pub controls: Vec<CompositionControl>,
83}
84
85/// A node setting a composition exposes to group nodes: an effect or transition parameter of
86/// one of its nodes.
87#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
88#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
89#[serde(deny_unknown_fields)]
90pub struct CompositionControl {
91    /// The name a group node sets it by; unique in the composition.
92    pub name: String,
93    /// The effect or transition node.
94    pub node: NodeId,
95    /// The parameter of its effect.
96    pub param: String,
97}
98
99impl Composition {
100    /// Creates an empty composition with no output.
101    #[must_use]
102    pub const fn new(id: CompositionId) -> Self {
103        Self {
104            id,
105            nodes: Vec::new(),
106            output: None,
107            inputs: Vec::new(),
108            controls: Vec::new(),
109        }
110    }
111
112    /// The node named `id`.
113    #[must_use]
114    pub fn node(&self, id: &NodeId) -> Option<&CompositionNode> {
115        self.nodes.iter().find(|node| &node.id == id)
116    }
117}
118
119/// One image operation in a [`Composition`].
120#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
121#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
122#[serde(deny_unknown_fields)]
123pub struct CompositionNode {
124    /// Identity, unique within its composition.
125    pub id: NodeId,
126    /// Whether the node passes its [`NodeOp::bypass_input`] through unchanged. A node without
127    /// inputs cannot be bypassed.
128    #[serde(default)]
129    pub bypass: bool,
130    /// What the node does, with its inputs and settings.
131    pub op: NodeOp,
132}
133
134impl CompositionNode {
135    /// Creates a node that is not bypassed.
136    #[must_use]
137    pub const fn new(id: NodeId, op: NodeOp) -> Self {
138        Self {
139            id,
140            bypass: false,
141            op,
142        }
143    }
144
145    /// The inputs drawing the node reads, in input order: only its [`NodeOp::bypass_input`] when
146    /// bypassed (none for a merge without layers), every input otherwise except an unconnected
147    /// key mix mask.
148    #[must_use]
149    pub fn needed_inputs(&self) -> Vec<NodeInput<'_>> {
150        if self.bypass {
151            return self.op.bypass_input().into_iter().collect();
152        }
153        let mut inputs = self.op.inputs();
154        if let NodeOp::KeyMix { mask: None, .. } = self.op {
155            inputs.retain(|input| *input != NodeInput::Named("mask", None));
156        }
157        inputs
158    }
159}
160
161/// The operation of a [`CompositionNode`].
162///
163/// Animated settings are keyed in composition time (see [`ClipComposition`]).
164#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
165#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
166#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
167pub enum NodeOp {
168    /// The picture of the clip showing the composition: its source at the time-mapped source
169    /// time, or what its generated source draws. For an adjustment clip, the scene composited
170    /// beneath it.
171    Clip {},
172    /// Another visual source, read at `start` plus the composition time. Adds no sound to the
173    /// mix.
174    Media {
175        /// The source; a video, image, or generated source.
176        source_id: SourceId,
177        /// Source time shown at composition time zero. Non-negative.
178        #[serde(default)]
179        start: MediaTime,
180    },
181    /// A picture the engine draws.
182    Generator {
183        /// What is drawn.
184        generator: Generator,
185    },
186    /// A registered effect: its input plus any named images it samples.
187    Effect {
188        /// The image the effect processes; a bypassed node passes it through.
189        #[serde(default)]
190        input: Option<NodeId>,
191        /// The images the effect samples besides its input, by the names its definition declares
192        /// (`sample_<name>` in its shader); at most [`MAX_EFFECT_INPUTS`]. An undeclared name, or a
193        /// declared one left out, is invalid for a built-in and fails the frames that draw the
194        /// node otherwise.
195        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
196        #[serde(deserialize_with = "crate::bounded::map::<_, _, _, { MAX_EFFECT_INPUTS }>")]
197        #[cfg_attr(feature = "schema", schemars(extend("maxProperties" = MAX_EFFECT_INPUTS)))]
198        inputs: BTreeMap<String, Option<NodeId>>,
199        /// The versioned effect and its parameters.
200        effect: ClipEffect,
201    },
202    /// A registered two-input transition at an explicit progress.
203    Transition {
204        /// The image at progress zero.
205        #[serde(default)]
206        from: Option<NodeId>,
207        /// The image at progress one.
208        #[serde(default)]
209        to: Option<NodeId>,
210        /// The versioned transition and its parameters.
211        effect: ClipEffect,
212        /// Progress through the transition, in `0..=1`.
213        progress: Animated<f32>,
214    },
215    /// The input placed on the canvas by a transform and opacity.
216    Transform {
217        /// The image placed.
218        #[serde(default)]
219        input: Option<NodeId>,
220        /// Position, anchor, scale, rotation, and opacity.
221        #[serde(default)]
222        transform: VisualProperties,
223    },
224    /// Ordered layers composited over transparency.
225    Merge {
226        /// Layers from bottom to top.
227        #[serde(
228            default,
229            deserialize_with = "crate::bounded::seq::<_, _, { MAX_MERGE_LAYERS }>"
230        )]
231        #[cfg_attr(feature = "schema", schemars(length(max = MAX_MERGE_LAYERS)))]
232        layers: Vec<MergeLayer>,
233    },
234    /// The input kept where a second image says.
235    Matte {
236        /// The image kept.
237        #[serde(default)]
238        input: Option<NodeId>,
239        /// The image whose alpha or luminance is coverage.
240        #[serde(default)]
241        matte: Option<NodeId>,
242        /// Which property of the matte image is coverage.
243        mode: MatteMode,
244    },
245    /// The backdrop replaced by the input by `k = opacity x mask alpha`, as
246    /// `(1 - k) backdrop + k input` on premultiplied values: exactly the backdrop where `k` is 0
247    /// and the input where it is 1 (Nuke's `KeyMix` with an opacity). Bypassed, it passes the
248    /// backdrop through.
249    KeyMix {
250        /// The picture replaced.
251        #[serde(default)]
252        backdrop: Option<NodeId>,
253        /// The picture that replaces it.
254        #[serde(default)]
255        input: Option<NodeId>,
256        /// The image whose alpha is coverage; unconnected, the coverage is `opacity` everywhere.
257        #[serde(default)]
258        mask: Option<NodeId>,
259        /// Scales the coverage, in `0..=1`.
260        #[serde(default = "opaque")]
261        opacity: Animated<f32>,
262    },
263    /// The input kept inside shapes.
264    ShapeMask {
265        /// The image masked.
266        #[serde(default)]
267        input: Option<NodeId>,
268        /// The shapes, combined in order; at most [`crate::MAX_CLIP_MASKS`]. Geometry is in the
269        /// input image's normalized space.
270        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIP_MASKS }>")]
271        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIP_MASKS)))]
272        masks: Vec<ShapeMask>,
273    },
274    /// Another composition drawn in this one's time as a group: its output, with group inputs
275    /// fed from `inputs` and controls set from `controls`.
276    Group {
277        /// The composition drawn.
278        composition: CompositionId,
279        /// The image for each of its inputs, in its port order.
280        #[serde(default)]
281        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GROUP_INPUTS }>")]
282        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GROUP_INPUTS)))]
283        inputs: Vec<Option<NodeId>>,
284        /// Values for its controls, by name; unset controls keep the composition's own value. Keyed
285        /// in composition time.
286        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
287        controls: BTreeMap<String, Animated<EffectValue>>,
288    },
289    /// In a composition used as a group, the image the group node gives its input `index`.
290    GroupInput {
291        /// The input, in the composition's port order.
292        index: u32,
293    },
294}
295
296/// One layer of a [`NodeOp::Merge`].
297#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
298#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
299#[serde(deny_unknown_fields)]
300pub struct MergeLayer {
301    /// The layer's image.
302    #[serde(default)]
303    pub input: Option<NodeId>,
304    /// How the layer blends with the layers under it.
305    #[serde(default)]
306    pub blend_mode: ClipBlendMode,
307    /// The layer's opacity, in `0..=1`.
308    #[serde(default = "opaque")]
309    pub opacity: Animated<f32>,
310}
311
312impl MergeLayer {
313    /// An opaque, normally blended layer of `input`.
314    #[must_use]
315    pub const fn new(input: Option<NodeId>) -> Self {
316        Self {
317            input,
318            blend_mode: ClipBlendMode::Normal,
319            opacity: Animated::Constant { value: 1.0 },
320        }
321    }
322}
323
324/// What each composition's output reads: the group inputs and clip nodes reachable from its
325/// output, following group nodes into their compositions. A group node needs only the ports
326/// its composition reads, so unread ports may be left unconnected.
327///
328/// Built once per project in dependency order, without recursion. A composition that uses
329/// itself (refused by validation) is taken to read every port and draw the clip.
330#[derive(Clone, Debug, Default)]
331pub struct CompositionReads<'a> {
332    read: HashMap<&'a CompositionId, Reads>,
333}
334
335/// What one composition's output reads.
336#[derive(Clone, Debug)]
337struct Reads {
338    /// By group input index.
339    ports: Vec<bool>,
340    /// Whether it draws the picture of the clip showing it.
341    clip: bool,
342}
343
344impl<'a> CompositionReads<'a> {
345    /// What each of `compositions` reads, resolving group nodes by ID.
346    #[must_use]
347    pub fn new(compositions: &HashMap<&'a CompositionId, &'a Composition>) -> Self {
348        let mut reads = Self::default();
349        let mut walking = HashSet::new();
350        let group = |node: &'a CompositionNode| match &node.op {
351            NodeOp::Group { composition, .. } => compositions.get(composition).copied(),
352            _ => None,
353        };
354        for root in compositions.values() {
355            let mut stack = vec![(*root, false)];
356            while let Some((composition, expanded)) = stack.pop() {
357                if reads.read.contains_key(&composition.id) {
358                    continue;
359                }
360                if !expanded {
361                    if !walking.insert(&composition.id) {
362                        continue;
363                    }
364                    stack.push((composition, true));
365                    stack.extend(
366                        composition
367                            .nodes
368                            .iter()
369                            .filter_map(group)
370                            .filter(|inner| {
371                                !reads.read.contains_key(&inner.id) && !walking.contains(&inner.id)
372                            })
373                            .map(|inner| (inner, false)),
374                    );
375                    continue;
376                }
377                walking.remove(&composition.id);
378                let read = reads.walk(composition);
379                reads.read.insert(&composition.id, read);
380            }
381        }
382        reads
383    }
384
385    /// Whether `composition`'s output reads its group input `port`; true for an unknown
386    /// composition.
387    #[must_use]
388    pub fn reads_port(&self, composition: &CompositionId, port: usize) -> bool {
389        self.read
390            .get(composition)
391            .is_none_or(|read| read.ports.get(port).copied().unwrap_or(false))
392    }
393
394    /// Whether `composition`, shown by a clip, draws the clip's picture (its output reaches a
395    /// clip node, directly or in a group). True for an unknown composition.
396    #[must_use]
397    pub fn draws_clip(&self, composition: &CompositionId) -> bool {
398        self.read.get(composition).is_none_or(|read| read.clip)
399    }
400
401    /// The inputs drawing `node` reads, in input order: its [`CompositionNode::needed_inputs`],
402    /// restricted for a group node to the ports its composition reads.
403    #[must_use]
404    pub fn needed_inputs<'n>(&self, node: &'n CompositionNode) -> Vec<NodeInput<'n>> {
405        let mut needed = node.needed_inputs();
406        if let (false, NodeOp::Group { composition, .. }) = (node.bypass, &node.op) {
407            needed.retain(|input| match input {
408                NodeInput::Port(port, _) => self.reads_port(composition, *port),
409                _ => true,
410            });
411        }
412        needed
413    }
414
415    /// What `composition`'s output reaches, given that its group nodes' compositions are known.
416    fn walk(&self, composition: &'a Composition) -> Reads {
417        let nodes: HashMap<&NodeId, &CompositionNode> = composition
418            .nodes
419            .iter()
420            .map(|node| (&node.id, node))
421            .collect();
422        let mut read = Reads {
423            ports: vec![false; composition.inputs.len()],
424            clip: false,
425        };
426        let mut reached = HashSet::new();
427        let mut pending: Vec<&NodeId> = composition.output.iter().collect();
428        while let Some(id) = pending.pop() {
429            let Some(node) = nodes.get(id).filter(|_| reached.insert(id)) else {
430                continue;
431            };
432            match (node.bypass, &node.op) {
433                (false, NodeOp::GroupInput { index }) => {
434                    if let Some(port) = usize::try_from(*index)
435                        .ok()
436                        .and_then(|index| read.ports.get_mut(index))
437                    {
438                        *port = true;
439                    }
440                }
441                (false, NodeOp::Clip {}) => read.clip = true,
442                (false, NodeOp::Group { composition, .. }) => {
443                    read.clip |= self.draws_clip(composition);
444                }
445                _ => {}
446            }
447            pending.extend(
448                self.needed_inputs(node)
449                    .into_iter()
450                    .filter_map(NodeInput::node),
451            );
452        }
453        read
454    }
455}
456
457/// One named input of a node, as a node's inputs are listed.
458#[derive(Clone, Copy, Debug, Eq, PartialEq)]
459pub enum NodeInput<'a> {
460    /// A named input: `input`, `from`, `to`, `matte`, `backdrop` or `mask`.
461    Named(&'static str, Option<&'a NodeId>),
462    /// The input of a merge layer, by layer index.
463    Layer(usize, Option<&'a NodeId>),
464    /// An input of a group node, by port index.
465    Port(usize, Option<&'a NodeId>),
466    /// A named input of an effect node.
467    EffectInput(&'a str, Option<&'a NodeId>),
468}
469
470impl<'a> NodeInput<'a> {
471    /// The connected node, if any.
472    #[must_use]
473    pub const fn node(self) -> Option<&'a NodeId> {
474        match self {
475            Self::Named(_, node)
476            | Self::Layer(_, node)
477            | Self::Port(_, node)
478            | Self::EffectInput(_, node) => node,
479        }
480    }
481
482    /// The input's name as a diagnostic shows it: `input`, `from`, `to`, `matte`, `layers[i]`,
483    /// `inputs[i]`, or `inputs.<name>`.
484    #[must_use]
485    pub fn name(self) -> String {
486        match self {
487            Self::Named(name, _) => name.to_owned(),
488            Self::Layer(index, _) => format!("layers[{index}]"),
489            Self::Port(index, _) => format!("inputs[{index}]"),
490            Self::EffectInput(name, _) => format!("inputs.{name}"),
491        }
492    }
493}
494
495impl NodeOp {
496    /// Every input of the operation, connected or not, in a fixed order.
497    #[must_use]
498    pub fn inputs(&self) -> Vec<NodeInput<'_>> {
499        match self {
500            Self::Clip {}
501            | Self::Media { .. }
502            | Self::Generator { .. }
503            | Self::GroupInput { .. } => Vec::new(),
504            Self::Group { inputs, .. } => inputs
505                .iter()
506                .enumerate()
507                .map(|(index, input)| NodeInput::Port(index, input.as_ref()))
508                .collect(),
509            Self::Effect { input, inputs, .. } => {
510                std::iter::once(NodeInput::Named("input", input.as_ref()))
511                    .chain(
512                        inputs
513                            .iter()
514                            .map(|(name, node)| NodeInput::EffectInput(name, node.as_ref())),
515                    )
516                    .collect()
517            }
518            Self::Transform { input, .. } | Self::ShapeMask { input, .. } => {
519                vec![NodeInput::Named("input", input.as_ref())]
520            }
521            Self::Transition { from, to, .. } => vec![
522                NodeInput::Named("from", from.as_ref()),
523                NodeInput::Named("to", to.as_ref()),
524            ],
525            Self::Matte { input, matte, .. } => vec![
526                NodeInput::Named("input", input.as_ref()),
527                NodeInput::Named("matte", matte.as_ref()),
528            ],
529            Self::KeyMix {
530                backdrop,
531                input,
532                mask,
533                ..
534            } => vec![
535                NodeInput::Named("backdrop", backdrop.as_ref()),
536                NodeInput::Named("input", input.as_ref()),
537                NodeInput::Named("mask", mask.as_ref()),
538            ],
539            Self::Merge { layers } => layers
540                .iter()
541                .enumerate()
542                .map(|(index, layer)| NodeInput::Layer(index, layer.input.as_ref()))
543                .collect(),
544        }
545    }
546
547    /// The input a bypassed node passes through: `input` for one-input operations and mattes,
548    /// `from` for a transition, `backdrop` for a key mix, a merge's bottom layer, and a group's
549    /// first input. `None` for
550    /// operations without inputs and merges without layers.
551    #[must_use]
552    pub fn bypass_input(&self) -> Option<NodeInput<'_>> {
553        match self {
554            Self::Clip {}
555            | Self::Media { .. }
556            | Self::Generator { .. }
557            | Self::GroupInput { .. } => None,
558            Self::Merge { layers } => layers
559                .first()
560                .map(|layer| NodeInput::Layer(0, layer.input.as_ref())),
561            _ => self.inputs().into_iter().next(),
562        }
563    }
564
565    /// Whether the operation takes inputs, and so can be bypassed.
566    #[must_use]
567    pub const fn has_inputs(&self) -> bool {
568        match self {
569            Self::Clip {}
570            | Self::Media { .. }
571            | Self::Generator { .. }
572            | Self::GroupInput { .. } => false,
573            Self::Group { inputs, .. } => !inputs.is_empty(),
574            _ => true,
575        }
576    }
577
578    /// The effect or transition invocation the operation runs, if any.
579    #[must_use]
580    pub const fn effect(&self) -> Option<&ClipEffect> {
581        match self {
582            Self::Effect { effect, .. } | Self::Transition { effect, .. } => Some(effect),
583            _ => None,
584        }
585    }
586}
587
588/// A clip's use of a [`Composition`], and how its time maps onto it.
589///
590/// Composition time is `offset + (t - clip start) * scale` for timeline time `t`, rounded
591/// down to a tick. Moving a clip keeps its offset so the animation moves with it; trimming
592/// its start by `d` adds `d * scale` to the offset so the rest stays in place. A negative
593/// offset holds settings at their first keyframe and media nodes at their first frame.
594#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
595#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
596#[serde(deny_unknown_fields)]
597pub struct ClipComposition {
598    /// The composition shown.
599    pub id: CompositionId,
600    /// Composition time at the clip's start.
601    #[serde(default)]
602    pub offset: MediaTime,
603    /// Composition time per timeline time.
604    #[serde(default)]
605    pub scale: TimeScale,
606}
607
608impl ClipComposition {
609    /// Shows `id` from its time zero at the timeline's rate.
610    #[must_use]
611    pub const fn new(id: CompositionId) -> Self {
612        Self {
613            id,
614            offset: MediaTime::ZERO,
615            scale: TimeScale::ONE,
616        }
617    }
618
619    /// The composition time at timeline time `time` of a clip starting at `clip_start`. `None`
620    /// when unrepresentable or the scale has a zero denominator.
621    #[must_use]
622    pub fn local_time(&self, clip_start: MediaTime, time: MediaTime) -> Option<MediaTime> {
623        let elapsed = i128::from(time.ticks()) - i128::from(clip_start.ticks());
624        let scaled = (elapsed * i128::from(self.scale.num))
625            .checked_div_euclid(i128::from(self.scale.den))?;
626        let local = i128::from(self.offset.ticks()).checked_add(scaled)?;
627        i64::try_from(local).ok().map(MediaTime)
628    }
629}
630
631/// A positive rational rate of one time against another.
632#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
633#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
634#[serde(deny_unknown_fields)]
635pub struct TimeScale {
636    /// Numerator; positive.
637    pub num: u32,
638    /// Denominator; positive.
639    pub den: u32,
640}
641
642impl TimeScale {
643    /// The same rate.
644    pub const ONE: Self = Self { num: 1, den: 1 };
645
646    /// Whether both terms are positive.
647    #[must_use]
648    pub const fn is_valid(self) -> bool {
649        self.num > 0 && self.den > 0
650    }
651}
652
653impl Default for TimeScale {
654    fn default() -> Self {
655        Self::ONE
656    }
657}
658
659/// Checks every composition's identity, node settings and connections, and returns the
660/// nodes each draws once inlined. `by_source` maps source IDs for media node lookups.
661pub(crate) fn validate_compositions<'a>(
662    compositions: &'a [Composition],
663    sources: &'a [crate::MediaSource],
664    by_source: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
665    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
666    canvas: (u32, u32),
667) -> Result<InlinedNodes<'a>, crate::ModelError> {
668    use crate::ModelError;
669    use std::collections::{HashMap, HashSet};
670
671    if compositions.len() > MAX_COMPOSITIONS {
672        return Err(ModelError::TooManyCompositions {
673            found: compositions.len(),
674            maximum: MAX_COMPOSITIONS,
675        });
676    }
677    let mut ids = HashSet::with_capacity(compositions.len());
678    for composition in compositions {
679        if !ids.insert(&composition.id) {
680            return Err(ModelError::DuplicateCompositionId(composition.id.clone()));
681        }
682    }
683    let by_id: HashMap<&CompositionId, &Composition> = compositions
684        .iter()
685        .map(|composition| (&composition.id, composition))
686        .collect();
687    if let Some(source) = sources.iter().find(|source| {
688        source
689            .composition
690            .as_ref()
691            .is_some_and(|id| !by_id.contains_key(id))
692    }) {
693        return Err(ModelError::InvalidCompositionSource {
694            source: source.id.clone(),
695        });
696    }
697    for composition in compositions {
698        if composition.nodes.len() > MAX_COMPOSITION_NODES {
699            return Err(ModelError::TooManyCompositionNodes {
700                composition: composition.id.clone(),
701                found: composition.nodes.len(),
702                maximum: MAX_COMPOSITION_NODES,
703            });
704        }
705        let mut positions = HashMap::with_capacity(composition.nodes.len());
706        for (position, node) in composition.nodes.iter().enumerate() {
707            if node.id.as_str().contains('/') {
708                return Err(ModelError::InvalidNodeId {
709                    composition: composition.id.clone(),
710                    node: node.id.clone(),
711                });
712            }
713            if positions.insert(&node.id, position).is_some() {
714                return Err(ModelError::DuplicateNodeId {
715                    composition: composition.id.clone(),
716                    node: node.id.clone(),
717                });
718            }
719        }
720        validate_ports(composition, &positions)?;
721        for node in &composition.nodes {
722            validate_node(
723                composition,
724                node,
725                by_source,
726                &by_id,
727                effect_resources,
728                canvas,
729            )?;
730            for input in node.op.inputs() {
731                if let Some(target) = input.node()
732                    && !positions.contains_key(target)
733                {
734                    return Err(ModelError::UnknownNodeInput {
735                        composition: composition.id.clone(),
736                        node: node.id.clone(),
737                        input: input.name(),
738                        target: target.clone(),
739                    });
740                }
741            }
742        }
743        if let Some(output) = &composition.output
744            && !positions.contains_key(output)
745        {
746            return Err(ModelError::UnknownCompositionOutput {
747                composition: composition.id.clone(),
748                node: output.clone(),
749            });
750        }
751        if let Some(node) = cycle_member(composition, &positions) {
752            return Err(ModelError::CompositionCycle {
753                composition: composition.id.clone(),
754                node: node.clone(),
755            });
756        }
757    }
758    if let Some(composition) = reference_cycle_member(compositions, &by_id, by_source) {
759        return Err(ModelError::CompositionUsesItself {
760            composition: composition.clone(),
761        });
762    }
763    validate_expansion(compositions, &by_id, sources)
764}
765
766/// The nodes each composition draws once inlined, as [`MAX_INLINED_NODES`] counts them.
767pub(crate) type InlinedNodes<'a> = std::collections::HashMap<&'a CompositionId, u64>;
768
769/// Checks that compositions nest at most [`MAX_COMPOSITION_DEPTH`] deep and draw at most
770/// [`MAX_INLINED_NODES`] nodes, and returns the nodes each draws. One iterative walk in
771/// dependency order counts each composition once without risking stack exhaustion.
772fn validate_expansion<'a>(
773    compositions: &'a [Composition],
774    by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
775    sources: &'a [crate::MediaSource],
776) -> Result<InlinedNodes<'a>, crate::ModelError> {
777    use std::collections::HashMap;
778    let composition_sources: HashMap<&SourceId, &CompositionId> = sources
779        .iter()
780        .filter_map(|source| Some((&source.id, source.composition.as_ref()?)))
781        .collect();
782    // The composition a node draws in its place, if any.
783    let draws = |node: &'a CompositionNode| -> Option<&'a CompositionId> {
784        match &node.op {
785            NodeOp::Group { composition, .. } => Some(composition),
786            NodeOp::Media { source_id, .. } => composition_sources.get(source_id).copied(),
787            _ => None,
788        }
789        .filter(|id| by_id.contains_key(id))
790    };
791    // Depth and inlined node count of each composition walked.
792    let mut walked: HashMap<&CompositionId, (usize, u64)> = HashMap::new();
793    let mut total = 0_u64;
794    for root in compositions {
795        let mut stack = vec![(root, false)];
796        while let Some((composition, expanded)) = stack.pop() {
797            if walked.contains_key(&composition.id) {
798                continue;
799            }
800            if !expanded {
801                stack.push((composition, true));
802                stack.extend(
803                    composition
804                        .nodes
805                        .iter()
806                        .filter_map(draws)
807                        .filter(|id| !walked.contains_key(id))
808                        .map(|id| (by_id[id], false)),
809                );
810                continue;
811            }
812            let mut depth = 1;
813            let mut nodes = 0_u64;
814            for node in &composition.nodes {
815                let (inner, count) = draws(node).map_or((0, 1), |id| walked[id]);
816                depth = depth.max(inner + 1);
817                nodes = nodes.saturating_add(count);
818            }
819            walked.insert(&composition.id, (depth, nodes));
820        }
821        let (depth, nodes) = walked[&root.id];
822        if depth > MAX_COMPOSITION_DEPTH {
823            return Err(crate::ModelError::CompositionNestedTooDeep {
824                composition: root.id.clone(),
825                maximum: MAX_COMPOSITION_DEPTH,
826            });
827        }
828        total = total.saturating_add(nodes);
829        if total > MAX_INLINED_NODES as u64 {
830            return Err(crate::ModelError::TooManyInlinedNodes {
831                maximum: MAX_INLINED_NODES,
832            });
833        }
834    }
835    Ok(walked
836        .into_iter()
837        .map(|(id, (_, nodes))| (id, nodes))
838        .collect())
839}
840
841/// Checks that a composition's group inputs are named, distinct and few enough, and its
842/// controls name distinct settings of its effect and transition nodes.
843fn validate_ports(
844    composition: &Composition,
845    positions: &std::collections::HashMap<&NodeId, usize>,
846) -> Result<(), crate::ModelError> {
847    use std::collections::HashSet;
848    let invalid = || crate::ModelError::InvalidCompositionPorts {
849        composition: composition.id.clone(),
850    };
851    let mut names = HashSet::new();
852    if composition.inputs.len() > MAX_GROUP_INPUTS
853        || composition
854            .inputs
855            .iter()
856            .any(|name| name.is_empty() || !names.insert(name))
857    {
858        return Err(invalid());
859    }
860    let mut controls = HashSet::new();
861    let mut settings = HashSet::new();
862    if composition.controls.len() > MAX_COMPOSITION_CONTROLS {
863        return Err(invalid());
864    }
865    for control in &composition.controls {
866        let node = positions
867            .get(&control.node)
868            .map(|position| &composition.nodes[*position]);
869        if control.name.is_empty()
870            || control.param.is_empty()
871            || !controls.insert(&control.name)
872            || !settings.insert((&control.node, &control.param))
873            || node.is_none_or(|node| node.op.effect().is_none())
874        {
875            return Err(invalid());
876        }
877        if let Some(effect) = node.and_then(|node| node.op.effect())
878            && let Some(spec) = crate::builtin_effect(&effect.id)
879            && spec.param(&control.param).is_none()
880        {
881            return Err(crate::ModelError::InvalidEffect {
882                owner: Box::new(crate::EffectOwner::Node {
883                    composition: composition.id.clone(),
884                    node: control.node.clone(),
885                }),
886                id: effect.id.clone(),
887                problem: crate::EffectProblem::UnknownParam(control.param.clone()),
888            });
889        }
890    }
891    Ok(())
892}
893
894/// A composition that uses itself through group nodes or composition sources: the first, in
895/// document order, that a depth-first walk finds on its own path.
896fn reference_cycle_member<'a>(
897    compositions: &'a [Composition],
898    by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
899    sources: &std::collections::HashMap<&SourceId, &'a crate::MediaSource>,
900) -> Option<&'a CompositionId> {
901    #[derive(Clone, Copy, PartialEq)]
902    enum Mark {
903        New,
904        Open,
905        Done,
906    }
907    let uses = |composition: &'a Composition| -> Vec<&'a CompositionId> {
908        composition
909            .nodes
910            .iter()
911            .filter_map(|node| match &node.op {
912                NodeOp::Group { composition, .. } => Some(composition),
913                NodeOp::Media { source_id, .. } => sources
914                    .get(source_id)
915                    .and_then(|source| source.composition.as_ref()),
916                _ => None,
917            })
918            .filter(|id| by_id.contains_key(id))
919            .collect()
920    };
921    let mut marks: std::collections::HashMap<&CompositionId, Mark> = compositions
922        .iter()
923        .map(|composition| (&composition.id, Mark::New))
924        .collect();
925    for root in compositions {
926        if marks[&root.id] != Mark::New {
927            continue;
928        }
929        let mut stack = vec![(&root.id, uses(root), 0_usize)];
930        marks.insert(&root.id, Mark::Open);
931        while let Some((current, next, at)) = stack.last_mut() {
932            let Some(target) = next.get(*at).copied() else {
933                marks.insert(current, Mark::Done);
934                stack.pop();
935                continue;
936            };
937            *at += 1;
938            match marks[target] {
939                Mark::Open => return Some(target),
940                Mark::New => {
941                    marks.insert(target, Mark::Open);
942                    stack.push((target, uses(by_id[target]), 0));
943                }
944                Mark::Done => {}
945            }
946        }
947    }
948    None
949}
950
951fn node_owner(composition: &Composition, node: &CompositionNode) -> crate::ShapeOwner {
952    crate::ShapeOwner::Node {
953        composition: composition.id.clone(),
954        node: node.id.clone(),
955    }
956}
957
958fn shape_error(
959    composition: &Composition,
960    node: &CompositionNode,
961    issue: crate::ShapeIssue,
962) -> crate::ModelError {
963    crate::ModelError::InvalidShape {
964        owner: crate::ShapeOwner::Node {
965            composition: composition.id.clone(),
966            node: node.id.clone(),
967        },
968        at: issue.at,
969        problem: issue.problem,
970    }
971}
972
973/// Checks a node's built-in effect or transition, and the values a group node sets on its
974/// target's built-in parameters, against their definitions.
975fn check_builtin_effects(
976    composition: &Composition,
977    node: &CompositionNode,
978    compositions: &std::collections::HashMap<&CompositionId, &Composition>,
979) -> Result<(), crate::ModelError> {
980    use crate::effect_spec::{EffectKind, EffectProblem, builtin_effect, check_builtin};
981    let error = |id: &str, problem| crate::ModelError::InvalidEffect {
982        owner: Box::new(crate::EffectOwner::Node {
983            composition: composition.id.clone(),
984            node: node.id.clone(),
985        }),
986        id: id.to_owned(),
987        problem,
988    };
989    match &node.op {
990        NodeOp::Effect { effect, inputs, .. } => {
991            check_builtin(effect, EffectKind::Effect, Some(inputs))
992                .map_err(|problem| error(&effect.id, problem))?;
993        }
994        NodeOp::Transition { effect, .. } => {
995            check_builtin(effect, EffectKind::Transition, None)
996                .map_err(|problem| error(&effect.id, problem))?;
997        }
998        NodeOp::Group {
999            composition: target,
1000            controls,
1001            ..
1002        } => {
1003            let Some(target) = compositions.get(target) else {
1004                return Ok(());
1005            };
1006            for (name, value) in controls {
1007                let Some(control) = target.controls.iter().find(|control| &control.name == name)
1008                else {
1009                    continue;
1010                };
1011                let Some(effect) = target
1012                    .nodes
1013                    .iter()
1014                    .find(|inner| inner.id == control.node)
1015                    .and_then(|inner| inner.op.effect())
1016                else {
1017                    continue;
1018                };
1019                if let Some(param) =
1020                    builtin_effect(&effect.id).and_then(|spec| spec.param(&control.param))
1021                    && !param.accepts_animation(value)
1022                {
1023                    return Err(error(
1024                        &effect.id,
1025                        EffectProblem::InvalidParam(control.param.clone()),
1026                    ));
1027                }
1028            }
1029        }
1030        _ => {}
1031    }
1032    Ok(())
1033}
1034
1035fn validate_node(
1036    composition: &Composition,
1037    node: &CompositionNode,
1038    sources: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
1039    compositions: &std::collections::HashMap<&CompositionId, &Composition>,
1040    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
1041    canvas: (u32, u32),
1042) -> Result<(), crate::ModelError> {
1043    use crate::ModelError;
1044
1045    let invalid = || ModelError::InvalidNode {
1046        composition: composition.id.clone(),
1047        node: node.id.clone(),
1048    };
1049    let unit = |animation: &Animated<f32>| {
1050        crate::animation::valid_scalar_values(animation, |value| (0.0..=1.0).contains(&value))
1051    };
1052    let shape_error = |issue| shape_error(composition, node, issue);
1053    if node.bypass && !node.op.has_inputs() {
1054        return Err(invalid());
1055    }
1056    let valid = match &node.op {
1057        NodeOp::Clip {} | NodeOp::Matte { .. } => true,
1058        NodeOp::Media { source_id, start } => {
1059            let visual = sources.get(source_id).is_some_and(|source| {
1060                matches!(
1061                    source.kind,
1062                    crate::MediaKind::Video
1063                        | crate::MediaKind::Image
1064                        | crate::MediaKind::Generated
1065                        | crate::MediaKind::Composition
1066                )
1067            });
1068            if !visual {
1069                return Err(ModelError::InvalidNodeSource {
1070                    composition: composition.id.clone(),
1071                    node: node.id.clone(),
1072                    source: source_id.clone(),
1073                });
1074            }
1075            start.ticks() >= 0
1076        }
1077        NodeOp::Generator { generator } => match generator.validate_on(canvas.0, canvas.1) {
1078            Ok(()) => true,
1079            Err(issue) => {
1080                match crate::project::generator_error(node_owner(composition, node), issue) {
1081                    Some(error) => return Err(error),
1082                    None => false,
1083                }
1084            }
1085        },
1086        NodeOp::Effect { effect, inputs, .. } => {
1087            effect.is_valid()
1088                && inputs.len() <= MAX_EFFECT_INPUTS
1089                && inputs
1090                    .keys()
1091                    .all(|name| crate::effect::valid_binding_name(name))
1092        }
1093        NodeOp::Transition {
1094            effect, progress, ..
1095        } => effect.is_valid() && unit(progress),
1096        NodeOp::Transform { transform, .. } => transform.validate(),
1097        NodeOp::Merge { layers } => {
1098            layers.len() <= MAX_MERGE_LAYERS && layers.iter().all(|layer| unit(&layer.opacity))
1099        }
1100        NodeOp::KeyMix { opacity, .. } => unit(opacity),
1101        NodeOp::ShapeMask { masks, .. } => {
1102            crate::mask::validate_masks(masks).map_err(shape_error)?;
1103            masks.len() <= crate::MAX_CLIP_MASKS
1104        }
1105        NodeOp::Group {
1106            composition: target,
1107            inputs,
1108            controls,
1109        } => {
1110            let Some(target) = compositions.get(target) else {
1111                return Err(ModelError::UnknownGroupComposition {
1112                    composition: composition.id.clone(),
1113                    node: node.id.clone(),
1114                    target: target.clone(),
1115                });
1116            };
1117            inputs.len() == target.inputs.len()
1118                && controls.iter().all(|(name, value)| {
1119                    target.controls.iter().any(|control| &control.name == name)
1120                        && crate::effect::valid_param(value)
1121                })
1122        }
1123        NodeOp::GroupInput { index } => {
1124            usize::try_from(*index).is_ok_and(|index| index < composition.inputs.len())
1125        }
1126    };
1127    if !valid {
1128        return Err(invalid());
1129    }
1130    check_builtin_effects(composition, node, compositions)?;
1131    if let Some(effect) = node.op.effect()
1132        && let Some(resource) = effect
1133            .resources
1134            .values()
1135            .find(|resource| !effect_resources.contains(resource))
1136    {
1137        return Err(ModelError::UnknownNodeResource {
1138            composition: composition.id.clone(),
1139            node: node.id.clone(),
1140            resource: resource.clone(),
1141        });
1142    }
1143    Ok(())
1144}
1145
1146/// A node on a cycle, if any: the first, in document order, that a depth-first walk finds
1147/// on its own path.
1148fn cycle_member<'a>(
1149    composition: &'a Composition,
1150    positions: &std::collections::HashMap<&'a NodeId, usize>,
1151) -> Option<&'a NodeId> {
1152    #[derive(Clone, Copy, PartialEq)]
1153    enum Mark {
1154        New,
1155        Open,
1156        Done,
1157    }
1158    let nodes = &composition.nodes;
1159    let mut marks = vec![Mark::New; nodes.len()];
1160    for root in 0..nodes.len() {
1161        if marks[root] != Mark::New {
1162            continue;
1163        }
1164        // Each entry is a node and how many of its inputs have been walked.
1165        let mut stack = vec![(root, 0_usize)];
1166        marks[root] = Mark::Open;
1167        while let Some((current, next)) = stack.last_mut() {
1168            let inputs = nodes[*current].op.inputs();
1169            let Some(input) = inputs.get(*next) else {
1170                marks[*current] = Mark::Done;
1171                stack.pop();
1172                continue;
1173            };
1174            *next += 1;
1175            let Some(target) = input.node().and_then(|id| positions.get(id)) else {
1176                continue;
1177            };
1178            match marks[*target] {
1179                Mark::Open => return Some(&nodes[*target].id),
1180                Mark::New => {
1181                    marks[*target] = Mark::Open;
1182                    stack.push((*target, 0));
1183                }
1184                Mark::Done => {}
1185            }
1186        }
1187    }
1188    None
1189}
1190
1191#[cfg(test)]
1192#[path = "composition_tests.rs"]
1193mod tests;