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 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
854pub(crate) type InlinedNodes<'a> = std::collections::HashMap<&'a CompositionId, u64>;
856
857fn 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 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 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
934fn 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
987fn 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
1059fn 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
1253fn 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 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;