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