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 check_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    problems: &mut crate::problems::Problems,
703) -> Result<Option<CompositionTable<'a>>, crate::problems::Full> {
704    use crate::ModelError;
705    use std::collections::{HashMap, HashSet};
706
707    if compositions.len() > MAX_COMPOSITIONS {
708        problems.report(ModelError::TooManyCompositions {
709            found: compositions.len(),
710            maximum: MAX_COMPOSITIONS,
711        })?;
712        return Ok(None);
713    }
714    let mut ids = HashSet::with_capacity(compositions.len());
715    if let Some(composition) = compositions
716        .iter()
717        .find(|composition| !ids.insert(&composition.id))
718    {
719        problems.report(ModelError::DuplicateCompositionId(composition.id.clone()))?;
720        return Ok(Some(CompositionTable::broken()));
721    }
722    let by_id: HashMap<&CompositionId, &Composition> = compositions
723        .iter()
724        .map(|composition| (&composition.id, composition))
725        .collect();
726    let mut whole = true;
727    if let Some(source) = sources.iter().find(|source| {
728        source
729            .composition
730            .as_ref()
731            .is_some_and(|id| !by_id.contains_key(id))
732    }) {
733        problems.report(ModelError::InvalidCompositionSource {
734            source: source.id.clone(),
735        })?;
736        whole = false;
737    }
738    for composition in compositions {
739        whole &= problems.unit(check_composition(
740            composition,
741            &by_id,
742            by_source,
743            effect_resources,
744            canvas,
745        ))?;
746    }
747    if !whole {
748        return Ok(Some(CompositionTable::broken()));
749    }
750    if let Some(composition) = reference_cycle_member(compositions, &by_id, by_source) {
751        problems.report(ModelError::CompositionUsesItself {
752            composition: composition.clone(),
753        })?;
754        return Ok(Some(CompositionTable::broken()));
755    }
756    match validate_expansion(compositions, &by_id, sources) {
757        Ok(inlined) => Ok(Some(CompositionTable {
758            inlined: Some(inlined),
759            whole: true,
760        })),
761        Err(error) => {
762            problems.report(error)?;
763            Ok(Some(CompositionTable::broken()))
764        }
765    }
766}
767
768pub(crate) struct CompositionTable<'a> {
769    pub(crate) inlined: Option<InlinedNodes<'a>>,
770    pub(crate) whole: bool,
771}
772
773impl CompositionTable<'_> {
774    const fn broken() -> Self {
775        Self {
776            inlined: None,
777            whole: false,
778        }
779    }
780}
781
782fn check_composition(
783    composition: &Composition,
784    by_id: &std::collections::HashMap<&CompositionId, &Composition>,
785    by_source: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
786    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
787    canvas: (u32, u32),
788) -> Result<(), crate::ModelError> {
789    use crate::ModelError;
790    use std::collections::HashMap;
791
792    if composition.nodes.len() > MAX_COMPOSITION_NODES {
793        return Err(ModelError::TooManyCompositionNodes {
794            composition: composition.id.clone(),
795            found: composition.nodes.len(),
796            maximum: MAX_COMPOSITION_NODES,
797        });
798    }
799    let mut positions = HashMap::with_capacity(composition.nodes.len());
800    for (position, node) in composition.nodes.iter().enumerate() {
801        if node.id.as_str().contains('/') {
802            return Err(ModelError::InvalidNodeId {
803                composition: composition.id.clone(),
804                node: node.id.clone(),
805            });
806        }
807        if positions.insert(&node.id, position).is_some() {
808            return Err(ModelError::DuplicateNodeId {
809                composition: composition.id.clone(),
810                node: node.id.clone(),
811            });
812        }
813    }
814    validate_ports(composition, &positions)?;
815    for node in &composition.nodes {
816        validate_node(
817            composition,
818            node,
819            by_source,
820            by_id,
821            effect_resources,
822            canvas,
823        )?;
824        for input in node.op.inputs() {
825            if let Some(target) = input.node()
826                && !positions.contains_key(target)
827            {
828                return Err(ModelError::UnknownNodeInput {
829                    composition: composition.id.clone(),
830                    node: node.id.clone(),
831                    input: input.name(),
832                    target: target.clone(),
833                });
834            }
835        }
836    }
837    if let Some(output) = &composition.output
838        && !positions.contains_key(output)
839    {
840        return Err(ModelError::UnknownCompositionOutput {
841            composition: composition.id.clone(),
842            node: output.clone(),
843        });
844    }
845    if let Some(node) = cycle_member(composition, &positions) {
846        return Err(ModelError::CompositionCycle {
847            composition: composition.id.clone(),
848            node: node.clone(),
849        });
850    }
851    crate::time_offset::ensure_no_group_input_is_shifted(composition)
852}
853
854/// The nodes each composition draws once inlined, as [`MAX_INLINED_NODES`] counts them.
855pub(crate) type InlinedNodes<'a> = std::collections::HashMap<&'a CompositionId, u64>;
856
857/// Checks that compositions nest at most [`MAX_COMPOSITION_DEPTH`] deep and draw at most
858/// [`MAX_INLINED_NODES`] nodes, and returns the nodes each draws. One iterative walk in
859/// dependency order counts each composition once without risking stack exhaustion.
860fn validate_expansion<'a>(
861    compositions: &'a [Composition],
862    by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
863    sources: &'a [crate::MediaSource],
864) -> Result<InlinedNodes<'a>, crate::ModelError> {
865    use std::collections::HashMap;
866    let composition_sources: HashMap<&SourceId, &CompositionId> = sources
867        .iter()
868        .filter_map(|source| Some((&source.id, source.composition.as_ref()?)))
869        .collect();
870    // The composition a node draws in its place, if any.
871    let draws = |node: &'a CompositionNode| -> Option<&'a CompositionId> {
872        match &node.op {
873            NodeOp::Group { composition, .. } => Some(composition),
874            NodeOp::Media { source_id, .. } => composition_sources.get(source_id).copied(),
875            _ => None,
876        }
877        .filter(|id| by_id.contains_key(id))
878    };
879    // Depth and inlined node count of each composition walked.
880    let mut walked: HashMap<&CompositionId, (usize, u64)> = HashMap::new();
881    let mut total = 0_u64;
882    for root in compositions {
883        let mut stack = vec![(root, false)];
884        while let Some((composition, expanded)) = stack.pop() {
885            if walked.contains_key(&composition.id) {
886                continue;
887            }
888            if !expanded {
889                stack.push((composition, true));
890                stack.extend(
891                    composition
892                        .nodes
893                        .iter()
894                        .filter_map(draws)
895                        .filter(|id| !walked.contains_key(id))
896                        .map(|id| (by_id[id], false)),
897                );
898                continue;
899            }
900            let mut depth = 1;
901            let mut nodes = 0_u64;
902            for node in &composition.nodes {
903                let (inner, count) = draws(node).map_or((0, 1), |id| walked[id]);
904                depth = depth.max(inner + 1);
905                nodes = nodes.saturating_add(count);
906            }
907            if crate::time_offset::has_offsets(composition) {
908                (depth, nodes) = crate::time_offset::depth_and_inlined_nodes(composition, |node| {
909                    draws(node).map_or((0, 1), |id| walked[id])
910                });
911            }
912            walked.insert(&composition.id, (depth, nodes));
913        }
914        let (depth, nodes) = walked[&root.id];
915        if depth > MAX_COMPOSITION_DEPTH {
916            return Err(crate::ModelError::CompositionNestedTooDeep {
917                composition: root.id.clone(),
918                maximum: MAX_COMPOSITION_DEPTH,
919            });
920        }
921        total = total.saturating_add(nodes);
922        if total > MAX_INLINED_NODES as u64 {
923            return Err(crate::ModelError::TooManyInlinedNodes {
924                maximum: MAX_INLINED_NODES,
925            });
926        }
927    }
928    Ok(walked
929        .into_iter()
930        .map(|(id, (_, nodes))| (id, nodes))
931        .collect())
932}
933
934/// Checks that a composition's group inputs are named, distinct and few enough, and its
935/// controls name distinct settings of its effect and transition nodes.
936fn validate_ports(
937    composition: &Composition,
938    positions: &std::collections::HashMap<&NodeId, usize>,
939) -> Result<(), crate::ModelError> {
940    use std::collections::HashSet;
941    let invalid = || crate::ModelError::InvalidCompositionPorts {
942        composition: composition.id.clone(),
943    };
944    let mut names = HashSet::new();
945    if composition.inputs.len() > MAX_GROUP_INPUTS
946        || composition
947            .inputs
948            .iter()
949            .any(|name| name.is_empty() || !names.insert(name))
950    {
951        return Err(invalid());
952    }
953    let mut controls = HashSet::new();
954    let mut settings = HashSet::new();
955    if composition.controls.len() > MAX_COMPOSITION_CONTROLS {
956        return Err(invalid());
957    }
958    for control in &composition.controls {
959        let node = positions
960            .get(&control.node)
961            .map(|position| &composition.nodes[*position]);
962        if control.name.is_empty()
963            || control.param.is_empty()
964            || !controls.insert(&control.name)
965            || !settings.insert((&control.node, &control.param))
966            || node.is_none_or(|node| node.op.effect().is_none())
967        {
968            return Err(invalid());
969        }
970        if let Some(effect) = node.and_then(|node| node.op.effect())
971            && let Some(spec) = crate::builtin_effect(&effect.id)
972            && spec.param(&control.param).is_none()
973        {
974            return Err(crate::ModelError::InvalidEffect {
975                owner: Box::new(crate::EffectOwner::Node {
976                    composition: composition.id.clone(),
977                    node: control.node.clone(),
978                }),
979                id: effect.id.clone(),
980                problem: crate::EffectProblem::UnknownParam(control.param.clone()),
981            });
982        }
983    }
984    Ok(())
985}
986
987/// A composition that uses itself through group nodes or composition sources: the first, in
988/// document order, that a depth-first walk finds on its own path.
989fn reference_cycle_member<'a>(
990    compositions: &'a [Composition],
991    by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
992    sources: &std::collections::HashMap<&SourceId, &'a crate::MediaSource>,
993) -> Option<&'a CompositionId> {
994    #[derive(Clone, Copy, PartialEq)]
995    enum Mark {
996        New,
997        Open,
998        Done,
999    }
1000    let uses = |composition: &'a Composition| -> Vec<&'a CompositionId> {
1001        composition
1002            .nodes
1003            .iter()
1004            .filter_map(|node| match &node.op {
1005                NodeOp::Group { composition, .. } => Some(composition),
1006                NodeOp::Media { source_id, .. } => sources
1007                    .get(source_id)
1008                    .and_then(|source| source.composition.as_ref()),
1009                _ => None,
1010            })
1011            .filter(|id| by_id.contains_key(id))
1012            .collect()
1013    };
1014    let mut marks: std::collections::HashMap<&CompositionId, Mark> = compositions
1015        .iter()
1016        .map(|composition| (&composition.id, Mark::New))
1017        .collect();
1018    for root in compositions {
1019        if marks[&root.id] != Mark::New {
1020            continue;
1021        }
1022        let mut stack = vec![(&root.id, uses(root), 0_usize)];
1023        marks.insert(&root.id, Mark::Open);
1024        while let Some((current, next, at)) = stack.last_mut() {
1025            let Some(target) = next.get(*at).copied() else {
1026                marks.insert(current, Mark::Done);
1027                stack.pop();
1028                continue;
1029            };
1030            *at += 1;
1031            match marks[target] {
1032                Mark::Open => return Some(target),
1033                Mark::New => {
1034                    marks.insert(target, Mark::Open);
1035                    stack.push((target, uses(by_id[target]), 0));
1036                }
1037                Mark::Done => {}
1038            }
1039        }
1040    }
1041    None
1042}
1043
1044fn shape_error(
1045    composition: &Composition,
1046    node: &CompositionNode,
1047    issue: crate::ShapeIssue,
1048) -> crate::ModelError {
1049    crate::ModelError::InvalidShape {
1050        owner: crate::ShapeOwner::Node {
1051            composition: composition.id.clone(),
1052            node: node.id.clone(),
1053        },
1054        at: issue.at,
1055        problem: issue.problem,
1056    }
1057}
1058
1059/// Checks a node's built-in effect or transition, and the values a group node sets on its
1060/// target's built-in parameters, against their definitions.
1061fn check_builtin_effects(
1062    composition: &Composition,
1063    node: &CompositionNode,
1064    compositions: &std::collections::HashMap<&CompositionId, &Composition>,
1065) -> Result<(), crate::ModelError> {
1066    use crate::effect_spec::{EffectKind, EffectProblem, builtin_effect, check_builtin};
1067    let error = |id: &str, problem| crate::ModelError::InvalidEffect {
1068        owner: Box::new(crate::EffectOwner::Node {
1069            composition: composition.id.clone(),
1070            node: node.id.clone(),
1071        }),
1072        id: id.to_owned(),
1073        problem,
1074    };
1075    match &node.op {
1076        NodeOp::Effect { effect, inputs, .. } => {
1077            check_builtin(effect, EffectKind::Effect, Some(inputs))
1078                .map_err(|problem| error(&effect.id, problem))?;
1079        }
1080        NodeOp::Transition { effect, .. } => {
1081            check_builtin(effect, EffectKind::Transition, None)
1082                .map_err(|problem| error(&effect.id, problem))?;
1083        }
1084        NodeOp::Group {
1085            composition: target,
1086            controls,
1087            ..
1088        } => {
1089            let Some(target) = compositions.get(target) else {
1090                return Ok(());
1091            };
1092            for (name, value) in controls {
1093                let Some(control) = target.controls.iter().find(|control| &control.name == name)
1094                else {
1095                    continue;
1096                };
1097                let Some(effect) = target
1098                    .nodes
1099                    .iter()
1100                    .find(|inner| inner.id == control.node)
1101                    .and_then(|inner| inner.op.effect())
1102                else {
1103                    continue;
1104                };
1105                if let Some(param) =
1106                    builtin_effect(&effect.id).and_then(|spec| spec.param(&control.param))
1107                    && !param.accepts_animation(value)
1108                {
1109                    return Err(error(
1110                        &effect.id,
1111                        EffectProblem::InvalidParam(control.param.clone()),
1112                    ));
1113                }
1114            }
1115        }
1116        _ => {}
1117    }
1118    Ok(())
1119}
1120
1121fn validate_node(
1122    composition: &Composition,
1123    node: &CompositionNode,
1124    sources: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
1125    compositions: &std::collections::HashMap<&CompositionId, &Composition>,
1126    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
1127    canvas: (u32, u32),
1128) -> Result<(), crate::ModelError> {
1129    use crate::ModelError;
1130
1131    let invalid = || ModelError::InvalidNode {
1132        composition: composition.id.clone(),
1133        node: node.id.clone(),
1134    };
1135    let unit = |animation: &Animated<f32>| {
1136        crate::animation::valid_scalar_values(animation, |value| (0.0..=1.0).contains(&value))
1137    };
1138    let shape_error = |issue| shape_error(composition, node, issue);
1139    if node.bypass && !node.op.has_inputs() {
1140        return Err(invalid());
1141    }
1142    let valid = match &node.op {
1143        NodeOp::Clip {} | NodeOp::Matte { .. } | NodeOp::TimeOffset { .. } => true,
1144        NodeOp::Media {
1145            source_id, start, ..
1146        } => {
1147            let visual = sources.get(source_id).is_some_and(|source| {
1148                matches!(
1149                    source.kind,
1150                    crate::MediaKind::Video
1151                        | crate::MediaKind::Image
1152                        | crate::MediaKind::Generated
1153                        | crate::MediaKind::Composition
1154                )
1155            });
1156            if !visual {
1157                return Err(ModelError::InvalidNodeSource {
1158                    composition: composition.id.clone(),
1159                    node: node.id.clone(),
1160                    source: source_id.clone(),
1161                });
1162            }
1163            start.ticks() >= 0
1164        }
1165        NodeOp::Generator { generator } => match generator.validate_on(canvas.0, canvas.1) {
1166            Ok(()) => true,
1167            Err(issue) => {
1168                let owner = crate::project::GeneratorOwner::Node {
1169                    composition: &composition.id,
1170                    node: &node.id,
1171                };
1172                match crate::project::generator_error(owner, issue) {
1173                    Some(error) => return Err(error),
1174                    None => false,
1175                }
1176            }
1177        },
1178        NodeOp::Effect { effect, inputs, .. } => {
1179            effect.is_valid()
1180                && inputs.len() <= MAX_EFFECT_INPUTS
1181                && inputs
1182                    .keys()
1183                    .all(|name| crate::effect::valid_binding_name(name))
1184        }
1185        NodeOp::Transition {
1186            effect, progress, ..
1187        } => effect.is_valid() && unit(progress),
1188        NodeOp::Transform { transform, .. } => transform.validate(),
1189        NodeOp::Merge { layers } => {
1190            layers.len() <= MAX_MERGE_LAYERS && layers.iter().all(|layer| unit(&layer.opacity))
1191        }
1192        NodeOp::KeyMix { opacity, .. } => unit(opacity),
1193        NodeOp::ShapeMask { masks, .. } => {
1194            crate::mask::validate_masks(masks).map_err(shape_error)?;
1195            masks.len() <= crate::MAX_CLIP_MASKS
1196        }
1197        NodeOp::Group {
1198            composition: target,
1199            inputs,
1200            controls,
1201        } => {
1202            let Some(target) = compositions.get(target) else {
1203                return Err(ModelError::UnknownGroupComposition {
1204                    composition: composition.id.clone(),
1205                    node: node.id.clone(),
1206                    target: target.clone(),
1207                });
1208            };
1209            inputs.len() == target.inputs.len()
1210                && controls.iter().all(|(name, value)| {
1211                    target.controls.iter().any(|control| &control.name == name)
1212                        && crate::effect::valid_param(value)
1213                })
1214        }
1215        NodeOp::GroupInput { index } => {
1216            usize::try_from(*index).is_ok_and(|index| index < composition.inputs.len())
1217        }
1218    };
1219    if !valid {
1220        return Err(invalid());
1221    }
1222    check_builtin_effects(composition, node, compositions)?;
1223    ensure_node_resources_exist(composition, node, effect_resources)
1224}
1225
1226fn ensure_node_resources_exist(
1227    composition: &Composition,
1228    node: &CompositionNode,
1229    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
1230) -> Result<(), crate::ModelError> {
1231    let generated = match &node.op {
1232        NodeOp::Generator {
1233            generator: Generator::Effect { effect },
1234        } => Some(effect),
1235        _ => None,
1236    };
1237    let missing = node.op.effect().or(generated).and_then(|effect| {
1238        effect
1239            .resources
1240            .values()
1241            .find(|resource| !effect_resources.contains(resource))
1242    });
1243    match missing {
1244        Some(resource) => Err(crate::ModelError::UnknownNodeResource {
1245            composition: composition.id.clone(),
1246            node: node.id.clone(),
1247            resource: resource.clone(),
1248        }),
1249        None => Ok(()),
1250    }
1251}
1252
1253/// A node on a cycle, if any: the first, in document order, that a depth-first walk finds
1254/// on its own path.
1255fn cycle_member<'a>(
1256    composition: &'a Composition,
1257    positions: &std::collections::HashMap<&'a NodeId, usize>,
1258) -> Option<&'a NodeId> {
1259    #[derive(Clone, Copy, PartialEq)]
1260    enum Mark {
1261        New,
1262        Open,
1263        Done,
1264    }
1265    let nodes = &composition.nodes;
1266    let mut marks = vec![Mark::New; nodes.len()];
1267    for root in 0..nodes.len() {
1268        if marks[root] != Mark::New {
1269            continue;
1270        }
1271        // Each entry is a node and how many of its inputs have been walked.
1272        let mut stack = vec![(root, 0_usize)];
1273        marks[root] = Mark::Open;
1274        while let Some((current, next)) = stack.last_mut() {
1275            let inputs = nodes[*current].op.inputs();
1276            let Some(input) = inputs.get(*next) else {
1277                marks[*current] = Mark::Done;
1278                stack.pop();
1279                continue;
1280            };
1281            *next += 1;
1282            let Some(target) = input.node().and_then(|id| positions.get(id)) else {
1283                continue;
1284            };
1285            match marks[*target] {
1286                Mark::Open => return Some(&nodes[*target].id),
1287                Mark::New => {
1288                    marks[*target] = Mark::Open;
1289                    stack.push((*target, 0));
1290                }
1291                Mark::Done => {}
1292            }
1293        }
1294    }
1295    None
1296}
1297
1298#[cfg(test)]
1299#[path = "composition_tests.rs"]
1300mod tests;