1use 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
30pub const MAX_COMPOSITIONS: usize = 10_000;
32pub const MAX_COMPOSITION_NODES: usize = 256;
34pub const MAX_EFFECT_INPUTS: usize = 8;
37pub const MAX_MERGE_LAYERS: usize = 32;
39pub const MAX_GROUP_INPUTS: usize = 16;
41pub const MAX_COMPOSITION_CONTROLS: usize = 64;
43pub const MAX_COMPOSITION_DEPTH: usize = 64;
47pub const MAX_INLINED_NODES: usize = 65_536;
53pub const MAX_FRAME_INLINED_NODES: usize = 65_536;
57
58#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
60#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
61#[serde(deny_unknown_fields)]
62pub struct Composition {
63 pub id: CompositionId,
65 #[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 #[serde(default)]
73 pub output: Option<NodeId>,
74 #[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 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
90#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
91#[serde(deny_unknown_fields)]
92pub struct CompositionControl {
93 pub name: String,
95 pub node: NodeId,
97 pub param: String,
99}
100
101impl Composition {
102 #[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 #[must_use]
116 pub fn node(&self, id: &NodeId) -> Option<&CompositionNode> {
117 self.nodes.iter().find(|node| &node.id == id)
118 }
119}
120
121#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
123#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
124#[serde(deny_unknown_fields)]
125pub struct CompositionNode {
126 pub id: NodeId,
128 #[serde(default)]
131 pub bypass: bool,
132 pub op: NodeOp,
134}
135
136impl CompositionNode {
137 #[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 #[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#[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 Clip {},
174 Media {
177 source_id: SourceId,
179 #[serde(default)]
181 start: MediaTime,
182 #[serde(default, skip_serializing_if = "crate::FrameInterpolation::is_hold")]
184 frame_interpolation: crate::FrameInterpolation,
185 },
186 Generator {
188 generator: Generator,
190 },
191 Effect {
193 #[serde(default)]
195 input: Option<NodeId>,
196 #[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 effect: ClipEffect,
206 },
207 Transition {
209 #[serde(default)]
211 from: Option<NodeId>,
212 #[serde(default)]
214 to: Option<NodeId>,
215 effect: ClipEffect,
217 progress: Animated<f32>,
219 },
220 Transform {
222 #[serde(default)]
224 input: Option<NodeId>,
225 #[serde(default)]
227 transform: VisualProperties,
228 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
231 motion_blur: bool,
232 },
233 Merge {
235 #[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 Matte {
245 #[serde(default)]
247 input: Option<NodeId>,
248 #[serde(default)]
250 matte: Option<NodeId>,
251 mode: MatteMode,
253 },
254 KeyMix {
259 #[serde(default)]
261 backdrop: Option<NodeId>,
262 #[serde(default)]
264 input: Option<NodeId>,
265 #[serde(default)]
267 mask: Option<NodeId>,
268 #[serde(default = "opaque")]
270 opacity: Animated<f32>,
271 },
272 ShapeMask {
274 #[serde(default)]
276 input: Option<NodeId>,
277 #[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 Group {
286 composition: CompositionId,
288 #[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 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
296 controls: BTreeMap<String, Animated<EffectValue>>,
297 },
298 GroupInput {
300 index: u32,
302 },
303 TimeOffset {
309 #[serde(default)]
311 input: Option<NodeId>,
312 offset: MediaTime,
314 },
315}
316
317#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
319#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
320#[serde(deny_unknown_fields)]
321pub struct MergeLayer {
322 #[serde(default)]
324 pub input: Option<NodeId>,
325 #[serde(default)]
327 pub blend_mode: ClipBlendMode,
328 #[serde(default = "opaque")]
330 pub opacity: Animated<f32>,
331}
332
333impl MergeLayer {
334 #[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#[derive(Clone, Debug, Default)]
352pub struct CompositionReads<'a> {
353 read: HashMap<&'a CompositionId, Reads>,
354}
355
356#[derive(Clone, Debug)]
358struct Reads {
359 ports: Vec<bool>,
361 clip: bool,
363}
364
365impl<'a> CompositionReads<'a> {
366 #[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 #[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 #[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 #[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 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
480pub enum NodeInput<'a> {
481 Named(&'static str, Option<&'a NodeId>),
483 Layer(usize, Option<&'a NodeId>),
485 Port(usize, Option<&'a NodeId>),
487 EffectInput(&'a str, Option<&'a NodeId>),
489}
490
491impl<'a> NodeInput<'a> {
492 #[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 #[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 #[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 #[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 #[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 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
618#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
619#[serde(deny_unknown_fields)]
620pub struct ClipComposition {
621 pub id: CompositionId,
623 #[serde(default)]
625 pub offset: MediaTime,
626 #[serde(default)]
628 pub scale: TimeScale,
629}
630
631impl ClipComposition {
632 #[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 #[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#[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 pub num: u32,
661 pub den: u32,
663}
664
665impl TimeScale {
666 pub const ONE: Self = Self { num: 1, den: 1 };
668
669 #[must_use]
671 pub const fn is_valid(self) -> bool {
672 self.num > 0 && self.den > 0
673 }
674
675 #[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
694pub(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
802pub(crate) type InlinedNodes<'a> = std::collections::HashMap<&'a CompositionId, u64>;
804
805fn 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 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 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
882fn 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
935fn 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
1007fn 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
1201fn 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 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;