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;
51pub const MAX_FRAME_INLINED_NODES: usize = 65_536;
55
56#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(deny_unknown_fields)]
60pub struct Composition {
61 pub id: CompositionId,
63 #[serde(default)]
65 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_COMPOSITION_NODES }>")]
66 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_COMPOSITION_NODES)))]
67 pub nodes: Vec<CompositionNode>,
68 #[serde(default)]
71 pub output: Option<NodeId>,
72 #[serde(default, skip_serializing_if = "Vec::is_empty")]
75 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GROUP_INPUTS }>")]
76 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GROUP_INPUTS)))]
77 pub inputs: Vec<String>,
78 #[serde(default, skip_serializing_if = "Vec::is_empty")]
80 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_COMPOSITION_CONTROLS }>")]
81 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_COMPOSITION_CONTROLS)))]
82 pub controls: Vec<CompositionControl>,
83}
84
85#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
88#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
89#[serde(deny_unknown_fields)]
90pub struct CompositionControl {
91 pub name: String,
93 pub node: NodeId,
95 pub param: String,
97}
98
99impl Composition {
100 #[must_use]
102 pub const fn new(id: CompositionId) -> Self {
103 Self {
104 id,
105 nodes: Vec::new(),
106 output: None,
107 inputs: Vec::new(),
108 controls: Vec::new(),
109 }
110 }
111
112 #[must_use]
114 pub fn node(&self, id: &NodeId) -> Option<&CompositionNode> {
115 self.nodes.iter().find(|node| &node.id == id)
116 }
117}
118
119#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
121#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
122#[serde(deny_unknown_fields)]
123pub struct CompositionNode {
124 pub id: NodeId,
126 #[serde(default)]
129 pub bypass: bool,
130 pub op: NodeOp,
132}
133
134impl CompositionNode {
135 #[must_use]
137 pub const fn new(id: NodeId, op: NodeOp) -> Self {
138 Self {
139 id,
140 bypass: false,
141 op,
142 }
143 }
144
145 #[must_use]
149 pub fn needed_inputs(&self) -> Vec<NodeInput<'_>> {
150 if self.bypass {
151 return self.op.bypass_input().into_iter().collect();
152 }
153 let mut inputs = self.op.inputs();
154 if let NodeOp::KeyMix { mask: None, .. } = self.op {
155 inputs.retain(|input| *input != NodeInput::Named("mask", None));
156 }
157 inputs
158 }
159}
160
161#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
165#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
166#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
167pub enum NodeOp {
168 Clip {},
172 Media {
175 source_id: SourceId,
177 #[serde(default)]
179 start: MediaTime,
180 },
181 Generator {
183 generator: Generator,
185 },
186 Effect {
188 #[serde(default)]
190 input: Option<NodeId>,
191 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
196 #[serde(deserialize_with = "crate::bounded::map::<_, _, _, { MAX_EFFECT_INPUTS }>")]
197 #[cfg_attr(feature = "schema", schemars(extend("maxProperties" = MAX_EFFECT_INPUTS)))]
198 inputs: BTreeMap<String, Option<NodeId>>,
199 effect: ClipEffect,
201 },
202 Transition {
204 #[serde(default)]
206 from: Option<NodeId>,
207 #[serde(default)]
209 to: Option<NodeId>,
210 effect: ClipEffect,
212 progress: Animated<f32>,
214 },
215 Transform {
217 #[serde(default)]
219 input: Option<NodeId>,
220 #[serde(default)]
222 transform: VisualProperties,
223 },
224 Merge {
226 #[serde(
228 default,
229 deserialize_with = "crate::bounded::seq::<_, _, { MAX_MERGE_LAYERS }>"
230 )]
231 #[cfg_attr(feature = "schema", schemars(length(max = MAX_MERGE_LAYERS)))]
232 layers: Vec<MergeLayer>,
233 },
234 Matte {
236 #[serde(default)]
238 input: Option<NodeId>,
239 #[serde(default)]
241 matte: Option<NodeId>,
242 mode: MatteMode,
244 },
245 KeyMix {
250 #[serde(default)]
252 backdrop: Option<NodeId>,
253 #[serde(default)]
255 input: Option<NodeId>,
256 #[serde(default)]
258 mask: Option<NodeId>,
259 #[serde(default = "opaque")]
261 opacity: Animated<f32>,
262 },
263 ShapeMask {
265 #[serde(default)]
267 input: Option<NodeId>,
268 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIP_MASKS }>")]
271 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIP_MASKS)))]
272 masks: Vec<ShapeMask>,
273 },
274 Group {
277 composition: CompositionId,
279 #[serde(default)]
281 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GROUP_INPUTS }>")]
282 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GROUP_INPUTS)))]
283 inputs: Vec<Option<NodeId>>,
284 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
287 controls: BTreeMap<String, Animated<EffectValue>>,
288 },
289 GroupInput {
291 index: u32,
293 },
294}
295
296#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
298#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
299#[serde(deny_unknown_fields)]
300pub struct MergeLayer {
301 #[serde(default)]
303 pub input: Option<NodeId>,
304 #[serde(default)]
306 pub blend_mode: ClipBlendMode,
307 #[serde(default = "opaque")]
309 pub opacity: Animated<f32>,
310}
311
312impl MergeLayer {
313 #[must_use]
315 pub const fn new(input: Option<NodeId>) -> Self {
316 Self {
317 input,
318 blend_mode: ClipBlendMode::Normal,
319 opacity: Animated::Constant { value: 1.0 },
320 }
321 }
322}
323
324#[derive(Clone, Debug, Default)]
331pub struct CompositionReads<'a> {
332 read: HashMap<&'a CompositionId, Reads>,
333}
334
335#[derive(Clone, Debug)]
337struct Reads {
338 ports: Vec<bool>,
340 clip: bool,
342}
343
344impl<'a> CompositionReads<'a> {
345 #[must_use]
347 pub fn new(compositions: &HashMap<&'a CompositionId, &'a Composition>) -> Self {
348 let mut reads = Self::default();
349 let mut walking = HashSet::new();
350 let group = |node: &'a CompositionNode| match &node.op {
351 NodeOp::Group { composition, .. } => compositions.get(composition).copied(),
352 _ => None,
353 };
354 for root in compositions.values() {
355 let mut stack = vec![(*root, false)];
356 while let Some((composition, expanded)) = stack.pop() {
357 if reads.read.contains_key(&composition.id) {
358 continue;
359 }
360 if !expanded {
361 if !walking.insert(&composition.id) {
362 continue;
363 }
364 stack.push((composition, true));
365 stack.extend(
366 composition
367 .nodes
368 .iter()
369 .filter_map(group)
370 .filter(|inner| {
371 !reads.read.contains_key(&inner.id) && !walking.contains(&inner.id)
372 })
373 .map(|inner| (inner, false)),
374 );
375 continue;
376 }
377 walking.remove(&composition.id);
378 let read = reads.walk(composition);
379 reads.read.insert(&composition.id, read);
380 }
381 }
382 reads
383 }
384
385 #[must_use]
388 pub fn reads_port(&self, composition: &CompositionId, port: usize) -> bool {
389 self.read
390 .get(composition)
391 .is_none_or(|read| read.ports.get(port).copied().unwrap_or(false))
392 }
393
394 #[must_use]
397 pub fn draws_clip(&self, composition: &CompositionId) -> bool {
398 self.read.get(composition).is_none_or(|read| read.clip)
399 }
400
401 #[must_use]
404 pub fn needed_inputs<'n>(&self, node: &'n CompositionNode) -> Vec<NodeInput<'n>> {
405 let mut needed = node.needed_inputs();
406 if let (false, NodeOp::Group { composition, .. }) = (node.bypass, &node.op) {
407 needed.retain(|input| match input {
408 NodeInput::Port(port, _) => self.reads_port(composition, *port),
409 _ => true,
410 });
411 }
412 needed
413 }
414
415 fn walk(&self, composition: &'a Composition) -> Reads {
417 let nodes: HashMap<&NodeId, &CompositionNode> = composition
418 .nodes
419 .iter()
420 .map(|node| (&node.id, node))
421 .collect();
422 let mut read = Reads {
423 ports: vec![false; composition.inputs.len()],
424 clip: false,
425 };
426 let mut reached = HashSet::new();
427 let mut pending: Vec<&NodeId> = composition.output.iter().collect();
428 while let Some(id) = pending.pop() {
429 let Some(node) = nodes.get(id).filter(|_| reached.insert(id)) else {
430 continue;
431 };
432 match (node.bypass, &node.op) {
433 (false, NodeOp::GroupInput { index }) => {
434 if let Some(port) = usize::try_from(*index)
435 .ok()
436 .and_then(|index| read.ports.get_mut(index))
437 {
438 *port = true;
439 }
440 }
441 (false, NodeOp::Clip {}) => read.clip = true,
442 (false, NodeOp::Group { composition, .. }) => {
443 read.clip |= self.draws_clip(composition);
444 }
445 _ => {}
446 }
447 pending.extend(
448 self.needed_inputs(node)
449 .into_iter()
450 .filter_map(NodeInput::node),
451 );
452 }
453 read
454 }
455}
456
457#[derive(Clone, Copy, Debug, Eq, PartialEq)]
459pub enum NodeInput<'a> {
460 Named(&'static str, Option<&'a NodeId>),
462 Layer(usize, Option<&'a NodeId>),
464 Port(usize, Option<&'a NodeId>),
466 EffectInput(&'a str, Option<&'a NodeId>),
468}
469
470impl<'a> NodeInput<'a> {
471 #[must_use]
473 pub const fn node(self) -> Option<&'a NodeId> {
474 match self {
475 Self::Named(_, node)
476 | Self::Layer(_, node)
477 | Self::Port(_, node)
478 | Self::EffectInput(_, node) => node,
479 }
480 }
481
482 #[must_use]
485 pub fn name(self) -> String {
486 match self {
487 Self::Named(name, _) => name.to_owned(),
488 Self::Layer(index, _) => format!("layers[{index}]"),
489 Self::Port(index, _) => format!("inputs[{index}]"),
490 Self::EffectInput(name, _) => format!("inputs.{name}"),
491 }
492 }
493}
494
495impl NodeOp {
496 #[must_use]
498 pub fn inputs(&self) -> Vec<NodeInput<'_>> {
499 match self {
500 Self::Clip {}
501 | Self::Media { .. }
502 | Self::Generator { .. }
503 | Self::GroupInput { .. } => Vec::new(),
504 Self::Group { inputs, .. } => inputs
505 .iter()
506 .enumerate()
507 .map(|(index, input)| NodeInput::Port(index, input.as_ref()))
508 .collect(),
509 Self::Effect { input, inputs, .. } => {
510 std::iter::once(NodeInput::Named("input", input.as_ref()))
511 .chain(
512 inputs
513 .iter()
514 .map(|(name, node)| NodeInput::EffectInput(name, node.as_ref())),
515 )
516 .collect()
517 }
518 Self::Transform { input, .. } | Self::ShapeMask { input, .. } => {
519 vec![NodeInput::Named("input", input.as_ref())]
520 }
521 Self::Transition { from, to, .. } => vec![
522 NodeInput::Named("from", from.as_ref()),
523 NodeInput::Named("to", to.as_ref()),
524 ],
525 Self::Matte { input, matte, .. } => vec![
526 NodeInput::Named("input", input.as_ref()),
527 NodeInput::Named("matte", matte.as_ref()),
528 ],
529 Self::KeyMix {
530 backdrop,
531 input,
532 mask,
533 ..
534 } => vec![
535 NodeInput::Named("backdrop", backdrop.as_ref()),
536 NodeInput::Named("input", input.as_ref()),
537 NodeInput::Named("mask", mask.as_ref()),
538 ],
539 Self::Merge { layers } => layers
540 .iter()
541 .enumerate()
542 .map(|(index, layer)| NodeInput::Layer(index, layer.input.as_ref()))
543 .collect(),
544 }
545 }
546
547 #[must_use]
552 pub fn bypass_input(&self) -> Option<NodeInput<'_>> {
553 match self {
554 Self::Clip {}
555 | Self::Media { .. }
556 | Self::Generator { .. }
557 | Self::GroupInput { .. } => None,
558 Self::Merge { layers } => layers
559 .first()
560 .map(|layer| NodeInput::Layer(0, layer.input.as_ref())),
561 _ => self.inputs().into_iter().next(),
562 }
563 }
564
565 #[must_use]
567 pub const fn has_inputs(&self) -> bool {
568 match self {
569 Self::Clip {}
570 | Self::Media { .. }
571 | Self::Generator { .. }
572 | Self::GroupInput { .. } => false,
573 Self::Group { inputs, .. } => !inputs.is_empty(),
574 _ => true,
575 }
576 }
577
578 #[must_use]
580 pub const fn effect(&self) -> Option<&ClipEffect> {
581 match self {
582 Self::Effect { effect, .. } | Self::Transition { effect, .. } => Some(effect),
583 _ => None,
584 }
585 }
586}
587
588#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
595#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
596#[serde(deny_unknown_fields)]
597pub struct ClipComposition {
598 pub id: CompositionId,
600 #[serde(default)]
602 pub offset: MediaTime,
603 #[serde(default)]
605 pub scale: TimeScale,
606}
607
608impl ClipComposition {
609 #[must_use]
611 pub const fn new(id: CompositionId) -> Self {
612 Self {
613 id,
614 offset: MediaTime::ZERO,
615 scale: TimeScale::ONE,
616 }
617 }
618
619 #[must_use]
622 pub fn local_time(&self, clip_start: MediaTime, time: MediaTime) -> Option<MediaTime> {
623 let elapsed = i128::from(time.ticks()) - i128::from(clip_start.ticks());
624 let scaled = (elapsed * i128::from(self.scale.num))
625 .checked_div_euclid(i128::from(self.scale.den))?;
626 let local = i128::from(self.offset.ticks()).checked_add(scaled)?;
627 i64::try_from(local).ok().map(MediaTime)
628 }
629}
630
631#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
633#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
634#[serde(deny_unknown_fields)]
635pub struct TimeScale {
636 pub num: u32,
638 pub den: u32,
640}
641
642impl TimeScale {
643 pub const ONE: Self = Self { num: 1, den: 1 };
645
646 #[must_use]
648 pub const fn is_valid(self) -> bool {
649 self.num > 0 && self.den > 0
650 }
651}
652
653impl Default for TimeScale {
654 fn default() -> Self {
655 Self::ONE
656 }
657}
658
659pub(crate) fn validate_compositions<'a>(
662 compositions: &'a [Composition],
663 sources: &'a [crate::MediaSource],
664 by_source: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
665 effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
666 canvas: (u32, u32),
667) -> Result<InlinedNodes<'a>, crate::ModelError> {
668 use crate::ModelError;
669 use std::collections::{HashMap, HashSet};
670
671 if compositions.len() > MAX_COMPOSITIONS {
672 return Err(ModelError::TooManyCompositions {
673 found: compositions.len(),
674 maximum: MAX_COMPOSITIONS,
675 });
676 }
677 let mut ids = HashSet::with_capacity(compositions.len());
678 for composition in compositions {
679 if !ids.insert(&composition.id) {
680 return Err(ModelError::DuplicateCompositionId(composition.id.clone()));
681 }
682 }
683 let by_id: HashMap<&CompositionId, &Composition> = compositions
684 .iter()
685 .map(|composition| (&composition.id, composition))
686 .collect();
687 if let Some(source) = sources.iter().find(|source| {
688 source
689 .composition
690 .as_ref()
691 .is_some_and(|id| !by_id.contains_key(id))
692 }) {
693 return Err(ModelError::InvalidCompositionSource {
694 source: source.id.clone(),
695 });
696 }
697 for composition in compositions {
698 if composition.nodes.len() > MAX_COMPOSITION_NODES {
699 return Err(ModelError::TooManyCompositionNodes {
700 composition: composition.id.clone(),
701 found: composition.nodes.len(),
702 maximum: MAX_COMPOSITION_NODES,
703 });
704 }
705 let mut positions = HashMap::with_capacity(composition.nodes.len());
706 for (position, node) in composition.nodes.iter().enumerate() {
707 if node.id.as_str().contains('/') {
708 return Err(ModelError::InvalidNodeId {
709 composition: composition.id.clone(),
710 node: node.id.clone(),
711 });
712 }
713 if positions.insert(&node.id, position).is_some() {
714 return Err(ModelError::DuplicateNodeId {
715 composition: composition.id.clone(),
716 node: node.id.clone(),
717 });
718 }
719 }
720 validate_ports(composition, &positions)?;
721 for node in &composition.nodes {
722 validate_node(
723 composition,
724 node,
725 by_source,
726 &by_id,
727 effect_resources,
728 canvas,
729 )?;
730 for input in node.op.inputs() {
731 if let Some(target) = input.node()
732 && !positions.contains_key(target)
733 {
734 return Err(ModelError::UnknownNodeInput {
735 composition: composition.id.clone(),
736 node: node.id.clone(),
737 input: input.name(),
738 target: target.clone(),
739 });
740 }
741 }
742 }
743 if let Some(output) = &composition.output
744 && !positions.contains_key(output)
745 {
746 return Err(ModelError::UnknownCompositionOutput {
747 composition: composition.id.clone(),
748 node: output.clone(),
749 });
750 }
751 if let Some(node) = cycle_member(composition, &positions) {
752 return Err(ModelError::CompositionCycle {
753 composition: composition.id.clone(),
754 node: node.clone(),
755 });
756 }
757 }
758 if let Some(composition) = reference_cycle_member(compositions, &by_id, by_source) {
759 return Err(ModelError::CompositionUsesItself {
760 composition: composition.clone(),
761 });
762 }
763 validate_expansion(compositions, &by_id, sources)
764}
765
766pub(crate) type InlinedNodes<'a> = std::collections::HashMap<&'a CompositionId, u64>;
768
769fn validate_expansion<'a>(
773 compositions: &'a [Composition],
774 by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
775 sources: &'a [crate::MediaSource],
776) -> Result<InlinedNodes<'a>, crate::ModelError> {
777 use std::collections::HashMap;
778 let composition_sources: HashMap<&SourceId, &CompositionId> = sources
779 .iter()
780 .filter_map(|source| Some((&source.id, source.composition.as_ref()?)))
781 .collect();
782 let draws = |node: &'a CompositionNode| -> Option<&'a CompositionId> {
784 match &node.op {
785 NodeOp::Group { composition, .. } => Some(composition),
786 NodeOp::Media { source_id, .. } => composition_sources.get(source_id).copied(),
787 _ => None,
788 }
789 .filter(|id| by_id.contains_key(id))
790 };
791 let mut walked: HashMap<&CompositionId, (usize, u64)> = HashMap::new();
793 let mut total = 0_u64;
794 for root in compositions {
795 let mut stack = vec![(root, false)];
796 while let Some((composition, expanded)) = stack.pop() {
797 if walked.contains_key(&composition.id) {
798 continue;
799 }
800 if !expanded {
801 stack.push((composition, true));
802 stack.extend(
803 composition
804 .nodes
805 .iter()
806 .filter_map(draws)
807 .filter(|id| !walked.contains_key(id))
808 .map(|id| (by_id[id], false)),
809 );
810 continue;
811 }
812 let mut depth = 1;
813 let mut nodes = 0_u64;
814 for node in &composition.nodes {
815 let (inner, count) = draws(node).map_or((0, 1), |id| walked[id]);
816 depth = depth.max(inner + 1);
817 nodes = nodes.saturating_add(count);
818 }
819 walked.insert(&composition.id, (depth, nodes));
820 }
821 let (depth, nodes) = walked[&root.id];
822 if depth > MAX_COMPOSITION_DEPTH {
823 return Err(crate::ModelError::CompositionNestedTooDeep {
824 composition: root.id.clone(),
825 maximum: MAX_COMPOSITION_DEPTH,
826 });
827 }
828 total = total.saturating_add(nodes);
829 if total > MAX_INLINED_NODES as u64 {
830 return Err(crate::ModelError::TooManyInlinedNodes {
831 maximum: MAX_INLINED_NODES,
832 });
833 }
834 }
835 Ok(walked
836 .into_iter()
837 .map(|(id, (_, nodes))| (id, nodes))
838 .collect())
839}
840
841fn validate_ports(
844 composition: &Composition,
845 positions: &std::collections::HashMap<&NodeId, usize>,
846) -> Result<(), crate::ModelError> {
847 use std::collections::HashSet;
848 let invalid = || crate::ModelError::InvalidCompositionPorts {
849 composition: composition.id.clone(),
850 };
851 let mut names = HashSet::new();
852 if composition.inputs.len() > MAX_GROUP_INPUTS
853 || composition
854 .inputs
855 .iter()
856 .any(|name| name.is_empty() || !names.insert(name))
857 {
858 return Err(invalid());
859 }
860 let mut controls = HashSet::new();
861 let mut settings = HashSet::new();
862 if composition.controls.len() > MAX_COMPOSITION_CONTROLS {
863 return Err(invalid());
864 }
865 for control in &composition.controls {
866 let node = positions
867 .get(&control.node)
868 .map(|position| &composition.nodes[*position]);
869 if control.name.is_empty()
870 || control.param.is_empty()
871 || !controls.insert(&control.name)
872 || !settings.insert((&control.node, &control.param))
873 || node.is_none_or(|node| node.op.effect().is_none())
874 {
875 return Err(invalid());
876 }
877 if let Some(effect) = node.and_then(|node| node.op.effect())
878 && let Some(spec) = crate::builtin_effect(&effect.id)
879 && spec.param(&control.param).is_none()
880 {
881 return Err(crate::ModelError::InvalidEffect {
882 owner: Box::new(crate::EffectOwner::Node {
883 composition: composition.id.clone(),
884 node: control.node.clone(),
885 }),
886 id: effect.id.clone(),
887 problem: crate::EffectProblem::UnknownParam(control.param.clone()),
888 });
889 }
890 }
891 Ok(())
892}
893
894fn reference_cycle_member<'a>(
897 compositions: &'a [Composition],
898 by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
899 sources: &std::collections::HashMap<&SourceId, &'a crate::MediaSource>,
900) -> Option<&'a CompositionId> {
901 #[derive(Clone, Copy, PartialEq)]
902 enum Mark {
903 New,
904 Open,
905 Done,
906 }
907 let uses = |composition: &'a Composition| -> Vec<&'a CompositionId> {
908 composition
909 .nodes
910 .iter()
911 .filter_map(|node| match &node.op {
912 NodeOp::Group { composition, .. } => Some(composition),
913 NodeOp::Media { source_id, .. } => sources
914 .get(source_id)
915 .and_then(|source| source.composition.as_ref()),
916 _ => None,
917 })
918 .filter(|id| by_id.contains_key(id))
919 .collect()
920 };
921 let mut marks: std::collections::HashMap<&CompositionId, Mark> = compositions
922 .iter()
923 .map(|composition| (&composition.id, Mark::New))
924 .collect();
925 for root in compositions {
926 if marks[&root.id] != Mark::New {
927 continue;
928 }
929 let mut stack = vec![(&root.id, uses(root), 0_usize)];
930 marks.insert(&root.id, Mark::Open);
931 while let Some((current, next, at)) = stack.last_mut() {
932 let Some(target) = next.get(*at).copied() else {
933 marks.insert(current, Mark::Done);
934 stack.pop();
935 continue;
936 };
937 *at += 1;
938 match marks[target] {
939 Mark::Open => return Some(target),
940 Mark::New => {
941 marks.insert(target, Mark::Open);
942 stack.push((target, uses(by_id[target]), 0));
943 }
944 Mark::Done => {}
945 }
946 }
947 }
948 None
949}
950
951fn node_owner(composition: &Composition, node: &CompositionNode) -> crate::ShapeOwner {
952 crate::ShapeOwner::Node {
953 composition: composition.id.clone(),
954 node: node.id.clone(),
955 }
956}
957
958fn shape_error(
959 composition: &Composition,
960 node: &CompositionNode,
961 issue: crate::ShapeIssue,
962) -> crate::ModelError {
963 crate::ModelError::InvalidShape {
964 owner: crate::ShapeOwner::Node {
965 composition: composition.id.clone(),
966 node: node.id.clone(),
967 },
968 at: issue.at,
969 problem: issue.problem,
970 }
971}
972
973fn check_builtin_effects(
976 composition: &Composition,
977 node: &CompositionNode,
978 compositions: &std::collections::HashMap<&CompositionId, &Composition>,
979) -> Result<(), crate::ModelError> {
980 use crate::effect_spec::{EffectKind, EffectProblem, builtin_effect, check_builtin};
981 let error = |id: &str, problem| crate::ModelError::InvalidEffect {
982 owner: Box::new(crate::EffectOwner::Node {
983 composition: composition.id.clone(),
984 node: node.id.clone(),
985 }),
986 id: id.to_owned(),
987 problem,
988 };
989 match &node.op {
990 NodeOp::Effect { effect, inputs, .. } => {
991 check_builtin(effect, EffectKind::Effect, Some(inputs))
992 .map_err(|problem| error(&effect.id, problem))?;
993 }
994 NodeOp::Transition { effect, .. } => {
995 check_builtin(effect, EffectKind::Transition, None)
996 .map_err(|problem| error(&effect.id, problem))?;
997 }
998 NodeOp::Group {
999 composition: target,
1000 controls,
1001 ..
1002 } => {
1003 let Some(target) = compositions.get(target) else {
1004 return Ok(());
1005 };
1006 for (name, value) in controls {
1007 let Some(control) = target.controls.iter().find(|control| &control.name == name)
1008 else {
1009 continue;
1010 };
1011 let Some(effect) = target
1012 .nodes
1013 .iter()
1014 .find(|inner| inner.id == control.node)
1015 .and_then(|inner| inner.op.effect())
1016 else {
1017 continue;
1018 };
1019 if let Some(param) =
1020 builtin_effect(&effect.id).and_then(|spec| spec.param(&control.param))
1021 && !param.accepts_animation(value)
1022 {
1023 return Err(error(
1024 &effect.id,
1025 EffectProblem::InvalidParam(control.param.clone()),
1026 ));
1027 }
1028 }
1029 }
1030 _ => {}
1031 }
1032 Ok(())
1033}
1034
1035fn validate_node(
1036 composition: &Composition,
1037 node: &CompositionNode,
1038 sources: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
1039 compositions: &std::collections::HashMap<&CompositionId, &Composition>,
1040 effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
1041 canvas: (u32, u32),
1042) -> Result<(), crate::ModelError> {
1043 use crate::ModelError;
1044
1045 let invalid = || ModelError::InvalidNode {
1046 composition: composition.id.clone(),
1047 node: node.id.clone(),
1048 };
1049 let unit = |animation: &Animated<f32>| {
1050 crate::animation::valid_scalar_values(animation, |value| (0.0..=1.0).contains(&value))
1051 };
1052 let shape_error = |issue| shape_error(composition, node, issue);
1053 if node.bypass && !node.op.has_inputs() {
1054 return Err(invalid());
1055 }
1056 let valid = match &node.op {
1057 NodeOp::Clip {} | NodeOp::Matte { .. } => true,
1058 NodeOp::Media { source_id, start } => {
1059 let visual = sources.get(source_id).is_some_and(|source| {
1060 matches!(
1061 source.kind,
1062 crate::MediaKind::Video
1063 | crate::MediaKind::Image
1064 | crate::MediaKind::Generated
1065 | crate::MediaKind::Composition
1066 )
1067 });
1068 if !visual {
1069 return Err(ModelError::InvalidNodeSource {
1070 composition: composition.id.clone(),
1071 node: node.id.clone(),
1072 source: source_id.clone(),
1073 });
1074 }
1075 start.ticks() >= 0
1076 }
1077 NodeOp::Generator { generator } => match generator.validate_on(canvas.0, canvas.1) {
1078 Ok(()) => true,
1079 Err(issue) => {
1080 match crate::project::generator_error(node_owner(composition, node), issue) {
1081 Some(error) => return Err(error),
1082 None => false,
1083 }
1084 }
1085 },
1086 NodeOp::Effect { effect, inputs, .. } => {
1087 effect.is_valid()
1088 && inputs.len() <= MAX_EFFECT_INPUTS
1089 && inputs
1090 .keys()
1091 .all(|name| crate::effect::valid_binding_name(name))
1092 }
1093 NodeOp::Transition {
1094 effect, progress, ..
1095 } => effect.is_valid() && unit(progress),
1096 NodeOp::Transform { transform, .. } => transform.validate(),
1097 NodeOp::Merge { layers } => {
1098 layers.len() <= MAX_MERGE_LAYERS && layers.iter().all(|layer| unit(&layer.opacity))
1099 }
1100 NodeOp::KeyMix { opacity, .. } => unit(opacity),
1101 NodeOp::ShapeMask { masks, .. } => {
1102 crate::mask::validate_masks(masks).map_err(shape_error)?;
1103 masks.len() <= crate::MAX_CLIP_MASKS
1104 }
1105 NodeOp::Group {
1106 composition: target,
1107 inputs,
1108 controls,
1109 } => {
1110 let Some(target) = compositions.get(target) else {
1111 return Err(ModelError::UnknownGroupComposition {
1112 composition: composition.id.clone(),
1113 node: node.id.clone(),
1114 target: target.clone(),
1115 });
1116 };
1117 inputs.len() == target.inputs.len()
1118 && controls.iter().all(|(name, value)| {
1119 target.controls.iter().any(|control| &control.name == name)
1120 && crate::effect::valid_param(value)
1121 })
1122 }
1123 NodeOp::GroupInput { index } => {
1124 usize::try_from(*index).is_ok_and(|index| index < composition.inputs.len())
1125 }
1126 };
1127 if !valid {
1128 return Err(invalid());
1129 }
1130 check_builtin_effects(composition, node, compositions)?;
1131 if let Some(effect) = node.op.effect()
1132 && let Some(resource) = effect
1133 .resources
1134 .values()
1135 .find(|resource| !effect_resources.contains(resource))
1136 {
1137 return Err(ModelError::UnknownNodeResource {
1138 composition: composition.id.clone(),
1139 node: node.id.clone(),
1140 resource: resource.clone(),
1141 });
1142 }
1143 Ok(())
1144}
1145
1146fn cycle_member<'a>(
1149 composition: &'a Composition,
1150 positions: &std::collections::HashMap<&'a NodeId, usize>,
1151) -> Option<&'a NodeId> {
1152 #[derive(Clone, Copy, PartialEq)]
1153 enum Mark {
1154 New,
1155 Open,
1156 Done,
1157 }
1158 let nodes = &composition.nodes;
1159 let mut marks = vec![Mark::New; nodes.len()];
1160 for root in 0..nodes.len() {
1161 if marks[root] != Mark::New {
1162 continue;
1163 }
1164 let mut stack = vec![(root, 0_usize)];
1166 marks[root] = Mark::Open;
1167 while let Some((current, next)) = stack.last_mut() {
1168 let inputs = nodes[*current].op.inputs();
1169 let Some(input) = inputs.get(*next) else {
1170 marks[*current] = Mark::Done;
1171 stack.pop();
1172 continue;
1173 };
1174 *next += 1;
1175 let Some(target) = input.node().and_then(|id| positions.get(id)) else {
1176 continue;
1177 };
1178 match marks[*target] {
1179 Mark::Open => return Some(&nodes[*target].id),
1180 Mark::New => {
1181 marks[*target] = Mark::Open;
1182 stack.push((*target, 0));
1183 }
1184 Mark::Done => {}
1185 }
1186 }
1187 }
1188 None
1189}
1190
1191#[cfg(test)]
1192#[path = "composition_tests.rs"]
1193mod tests;