1use alpha2_media::SourceId;
13use alpha2_model::{
14 Animated, AnimatedPoint, ClipBlendMode, ClipEffect, Composition, CompositionId,
15 CompositionReads, EffectValue, Generator, Keyframe, MAX_COMPOSITION_DEPTH, MAX_INLINED_NODES,
16 MatteMode, MediaKind, MediaSource, NodeId, NodeOp, Paint, ShapeMask, VisualProperties,
17};
18use alpha2_time::MediaTime;
19use std::collections::{BTreeMap, HashMap};
20use std::sync::Arc;
21
22use crate::GeneratorPlan;
23
24pub const MAX_PLAN_BYTES: u64 = 256 * 1024 * 1024;
27
28#[derive(Clone, Debug, PartialEq)]
30pub struct CompositionPlan {
31 pub id: CompositionId,
33 pub steps: Vec<Step>,
35 pub output: usize,
37 pub media: Vec<(String, MediaTime)>,
40}
41
42impl CompositionPlan {
43 pub fn effects(&self) -> impl Iterator<Item = &ClipEffect> {
45 self.steps.iter().filter_map(|step| match &step.op {
46 StepOp::Effect { effect, .. }
47 | StepOp::Transition { effect, .. }
48 | StepOp::Generator {
49 generator: Generator::Effect { effect },
50 ..
51 } => Some(effect),
52 _ => None,
53 })
54 }
55
56 #[must_use]
60 pub fn media_start(&self, step: usize, via: &alpha2_model::NodeId) -> Option<MediaTime> {
61 let path = self.steps.get(step)?.node.as_str();
62 let mut prefix = path.rfind('/').map_or("", |slash| &path[..=slash]);
63 loop {
64 let found = self.media.iter().find_map(|(node, start)| {
65 (node.strip_prefix(prefix) == Some(via.as_str())).then_some(*start)
66 });
67 if found.is_some() {
68 return found;
69 }
70 let outer = prefix.strip_suffix('/')?;
71 prefix = outer.rfind('/').map_or("", |slash| &outer[..=slash]);
72 }
73 }
74
75 #[must_use]
77 pub fn uses_clip(&self) -> bool {
78 self.steps
79 .iter()
80 .any(|step| matches!(step.op, StepOp::Clip))
81 }
82
83 #[must_use]
86 pub fn draws_clip(&self) -> bool {
87 self.steps
88 .iter()
89 .any(|step| matches!(step.op, StepOp::Clip | StepOp::ShiftedClip { .. }))
90 }
91
92 pub fn shifted_clips(&self) -> impl Iterator<Item = (usize, MediaTime)> + '_ {
94 self.steps
95 .iter()
96 .enumerate()
97 .filter_map(|(index, step)| match step.op {
98 StepOp::ShiftedClip { shift } => Some((index, shift)),
99 _ => None,
100 })
101 }
102}
103
104#[derive(Clone, Debug, PartialEq)]
106pub struct Step {
107 pub node: NodeId,
110 pub op: StepOp,
112 pub offset: MediaTime,
115}
116
117impl Step {
118 #[must_use]
120 pub fn time(&self, time: MediaTime) -> MediaTime {
121 MediaTime(time.ticks().saturating_add(self.offset.ticks()))
122 }
123}
124
125#[derive(Clone, Debug, PartialEq)]
127pub enum StepOp {
128 Clip,
130 ShiftedClip {
134 shift: MediaTime,
136 },
137 Media {
139 source_id: SourceId,
141 start: MediaTime,
143 frame_interpolation: alpha2_model::FrameInterpolation,
146 },
147 Generator {
149 generator: Generator,
151 start: MediaTime,
153 plan: Option<Arc<GeneratorPlan>>,
155 },
156 Effect {
158 input: usize,
160 inputs: Vec<(String, usize)>,
162 effect: ClipEffect,
164 },
165 Transition {
167 from: usize,
169 to: usize,
171 effect: ClipEffect,
173 progress: Animated<f32>,
175 },
176 Transform {
178 input: usize,
180 transform: VisualProperties,
182 motion_blur: bool,
184 },
185 Merge {
187 layers: Vec<StepLayer>,
189 },
190 Matte {
192 input: usize,
194 matte: usize,
196 mode: MatteMode,
198 },
199 KeyMix {
201 backdrop: usize,
203 input: usize,
205 mask: Option<usize>,
207 opacity: Animated<f32>,
209 },
210 ShapeMask {
212 input: usize,
214 masks: Vec<ShapeMask>,
216 },
217}
218
219#[derive(Clone, Debug, PartialEq)]
221pub struct StepLayer {
222 pub input: usize,
224 pub blend_mode: ClipBlendMode,
226 pub opacity: Animated<f32>,
228}
229
230#[derive(Clone, Debug, PartialEq, Eq)]
232pub enum PlanError {
233 NoOutput,
235 MissingInput {
237 node: NodeId,
239 input: String,
241 },
242 UnboundGroupInput {
244 node: NodeId,
246 },
247 ClipWithoutClip {
249 node: NodeId,
251 },
252 NestedTooDeep {
255 node: NodeId,
257 },
258 TooLarge,
261}
262
263#[derive(Debug)]
265pub(crate) struct PlanBudget {
266 left: u64,
267 exceeded: bool,
268}
269
270impl PlanBudget {
271 pub(crate) const fn new(bytes: u64) -> Self {
272 Self {
273 left: bytes,
274 exceeded: false,
275 }
276 }
277
278 pub(crate) const fn exceeded(&self) -> bool {
280 self.exceeded
281 }
282}
283
284pub(crate) struct Lookup<'a> {
286 compositions: HashMap<&'a CompositionId, &'a Composition>,
287 sources: HashMap<&'a SourceId, &'a MediaSource>,
288 reads: CompositionReads<'a>,
289 canvas: (u32, u32),
291}
292
293impl<'a> Lookup<'a> {
294 pub(crate) fn new(
295 compositions: &'a [Composition],
296 sources: &'a [MediaSource],
297 canvas: (u32, u32),
298 ) -> Self {
299 let compositions = compositions
300 .iter()
301 .map(|composition| (&composition.id, composition))
302 .collect();
303 let reads = CompositionReads::new(&compositions);
304 Self {
305 compositions,
306 sources: sources.iter().map(|source| (&source.id, source)).collect(),
307 reads,
308 canvas,
309 }
310 }
311
312 pub(crate) const fn reads(&self) -> &CompositionReads<'a> {
314 &self.reads
315 }
316}
317
318pub fn plan_composition(
327 composition: &Composition,
328 compositions: &[Composition],
329 sources: &[MediaSource],
330 canvas: (u32, u32),
331) -> Result<CompositionPlan, PlanError> {
332 plan(
333 composition,
334 &Lookup::new(compositions, sources, canvas),
335 true,
336 &mut PlanBudget::new(MAX_PLAN_BYTES),
337 )
338}
339
340pub(crate) fn plan_composition_within(
342 composition: &Composition,
343 lookup: &Lookup<'_>,
344 budget: &mut PlanBudget,
345) -> Result<CompositionPlan, PlanError> {
346 plan(composition, lookup, true, budget)
347}
348
349pub fn plan_source_composition(
355 composition: &Composition,
356 compositions: &[Composition],
357 sources: &[MediaSource],
358 canvas: (u32, u32),
359) -> Result<CompositionPlan, PlanError> {
360 plan(
361 composition,
362 &Lookup::new(compositions, sources, canvas),
363 false,
364 &mut PlanBudget::new(MAX_PLAN_BYTES),
365 )
366}
367
368pub(crate) fn plan_source_composition_within(
370 composition: &Composition,
371 lookup: &Lookup<'_>,
372 budget: &mut PlanBudget,
373) -> Result<CompositionPlan, PlanError> {
374 plan(composition, lookup, false, budget)
375}
376
377fn plan<'a>(
378 composition: &'a Composition,
379 lookup: &Lookup<'a>,
380 clip_allowed: bool,
381 budget: &mut PlanBudget,
382) -> Result<CompositionPlan, PlanError> {
383 let mut planner = Planner {
384 lookup,
385 steps: Vec::new(),
386 media: Vec::new(),
387 budget,
388 };
389 let scope = Scope {
390 composition,
391 inputs: Vec::new(),
392 controls: HashMap::new(),
393 offset: MediaTime::ZERO,
394 prefix: String::new(),
395 clip_allowed,
396 group_inputs_bound: false,
397 depth: 1,
398 shift: MediaTime::ZERO,
399 };
400 let output = planner.output(&scope)?;
401 Ok(CompositionPlan {
402 id: composition.id.clone(),
403 steps: planner.steps,
404 output,
405 media: planner.media,
406 })
407}
408
409struct Scope<'a> {
411 composition: &'a Composition,
412 inputs: Vec<Option<usize>>,
414 controls: HashMap<(&'a NodeId, &'a str), &'a Animated<EffectValue>>,
416 offset: MediaTime,
418 prefix: String,
420 clip_allowed: bool,
422 group_inputs_bound: bool,
424 depth: usize,
426 shift: MediaTime,
427}
428
429struct Planner<'a, 'b> {
430 lookup: &'b Lookup<'a>,
431 steps: Vec<Step>,
432 media: Vec<(String, MediaTime)>,
433 budget: &'b mut PlanBudget,
434}
435
436impl<'a> Planner<'a, '_> {
437 fn output(&mut self, scope: &Scope<'a>) -> Result<usize, PlanError> {
439 let output = scope
440 .composition
441 .output
442 .as_ref()
443 .ok_or(PlanError::NoOutput)?;
444 for node in &scope.composition.nodes {
445 if let NodeOp::Media { start, .. } = &node.op {
446 self.media
447 .push((format!("{}{}", scope.prefix, node.id), *start));
448 }
449 }
450 let nodes: HashMap<&NodeId, &'a alpha2_model::CompositionNode> = scope
451 .composition
452 .nodes
453 .iter()
454 .map(|node| (&node.id, node))
455 .collect();
456 self.resolve(scope, &nodes, output)
457 }
458
459 fn resolve(
465 &mut self,
466 scope: &Scope<'a>,
467 nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
468 id: &'a NodeId,
469 ) -> Result<usize, PlanError> {
470 let mut done: HashMap<&NodeId, usize> = HashMap::new();
471 let mut pending = vec![(id, false)];
473 while let Some((current, expanded)) = pending.pop() {
474 if done.contains_key(current) {
475 continue;
476 }
477 let node = nodes[current];
478 let needed = needed_inputs(self.lookup.reads(), &scope.prefix, node)?;
479 if !expanded {
480 pending.push((current, true));
481 let in_this_scope = if shifts(node) { &[][..] } else { &needed[..] };
482 pending.extend(
483 in_this_scope
484 .iter()
485 .rev()
486 .filter(|input| !done.contains_key(**input))
487 .map(|input| (*input, false)),
488 );
489 continue;
490 }
491 let step = if node.bypass {
492 done[needed[0]]
493 } else {
494 self.node_step(scope, nodes, node, &done)?
495 };
496 done.insert(current, step);
497 }
498 Ok(done[id])
499 }
500
501 fn generator_step(&self, generator: &Generator, start: MediaTime) -> StepOp {
502 generator_step(generator.clone(), start, self.lookup.canvas)
503 }
504
505 #[expect(clippy::too_many_lines, reason = "one arm per node operation")]
506 fn node_step(
507 &mut self,
508 scope: &Scope<'a>,
509 nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
510 node: &'a alpha2_model::CompositionNode,
511 done: &HashMap<&NodeId, usize>,
512 ) -> Result<usize, PlanError> {
513 let at = |input: &Option<NodeId>| {
514 input
515 .as_ref()
516 .map(|id| done[id])
517 .expect("needed inputs are connected and planned")
518 };
519 let id = || scoped(&scope.prefix, &node.id);
520 let op = match &node.op {
521 NodeOp::Clip {} => {
522 if !scope.clip_allowed {
523 return Err(PlanError::ClipWithoutClip { node: id() });
524 }
525 if scope.shift == MediaTime::ZERO {
526 StepOp::Clip
527 } else {
528 StepOp::ShiftedClip { shift: scope.shift }
529 }
530 }
531 NodeOp::GroupInput { index } => {
532 return usize::try_from(*index)
534 .ok()
535 .and_then(|index| scope.inputs.get(index).copied().flatten())
536 .filter(|_| scope.group_inputs_bound)
537 .ok_or_else(|| PlanError::UnboundGroupInput { node: id() });
538 }
539 NodeOp::TimeOffset { input, offset } => {
540 let input = input.as_ref().expect("needed inputs are connected");
541 return self.shifted(scope, nodes, &id(), input, *offset);
542 }
543 NodeOp::Group {
544 composition,
545 inputs,
546 controls,
547 } => {
548 let reads = self.lookup.reads();
550 let inputs = inputs
551 .iter()
552 .enumerate()
553 .map(|(port, input)| reads.reads_port(composition, port).then(|| at(input)))
554 .collect();
555 return self.group(scope, &id(), composition, inputs, controls);
556 }
557 NodeOp::Media {
558 source_id,
559 start,
560 frame_interpolation,
561 } => {
562 let source = self.lookup.sources.get(source_id).copied();
563 if let Some(composition) = source.and_then(|source| source.composition.as_ref()) {
564 return self.composition_source(scope, &id(), composition, *start);
565 }
566 let generator = source
567 .filter(|source| source.kind == MediaKind::Generated)
568 .and_then(|source| source.generator.as_ref());
569 generator.map_or_else(
570 || StepOp::Media {
571 source_id: source_id.clone(),
572 start: *start,
573 frame_interpolation: source
574 .filter(|source| source.kind == MediaKind::Video)
575 .map_or(alpha2_model::FrameInterpolation::Hold, |_| {
576 *frame_interpolation
577 }),
578 },
579 |generator| self.generator_step(generator, *start),
580 )
581 }
582 NodeOp::Generator { generator } => self.generator_step(generator, MediaTime::ZERO),
583 NodeOp::Effect {
584 input,
585 inputs,
586 effect,
587 } => StepOp::Effect {
588 input: at(input),
589 inputs: named_steps(inputs, &at),
590 effect: controlled(scope, &node.id, effect),
591 },
592 NodeOp::Transition {
593 from,
594 to,
595 effect,
596 progress,
597 } => StepOp::Transition {
598 from: at(from),
599 to: at(to),
600 effect: controlled(scope, &node.id, effect),
601 progress: progress.clone(),
602 },
603 NodeOp::Transform {
604 input,
605 transform,
606 motion_blur,
607 } => StepOp::Transform {
608 input: at(input),
609 transform: transform.clone(),
610 motion_blur: *motion_blur,
611 },
612 NodeOp::Merge { layers } => StepOp::Merge {
613 layers: layers
614 .iter()
615 .map(|layer| StepLayer {
616 input: at(&layer.input),
617 blend_mode: layer.blend_mode,
618 opacity: layer.opacity.clone(),
619 })
620 .collect(),
621 },
622 NodeOp::Matte { input, matte, mode } => StepOp::Matte {
623 input: at(input),
624 matte: at(matte),
625 mode: *mode,
626 },
627 NodeOp::ShapeMask { input, masks } => StepOp::ShapeMask {
628 input: at(input),
629 masks: masks.clone(),
630 },
631 NodeOp::KeyMix {
632 backdrop,
633 input,
634 mask,
635 opacity,
636 } => StepOp::KeyMix {
637 backdrop: at(backdrop),
638 input: at(input),
639 mask: mask.as_ref().map(|id| done[id]),
640 opacity: opacity.clone(),
641 },
642 };
643 self.push(Step {
644 node: id(),
645 op,
646 offset: scope.offset,
647 })
648 }
649
650 fn push(&mut self, step: Step) -> Result<usize, PlanError> {
652 if self.steps.len() >= MAX_INLINED_NODES {
653 return Err(PlanError::TooLarge);
654 }
655 let bytes = step_bytes(&step);
656 if bytes > self.budget.left {
657 self.budget.exceeded = true;
658 return Err(PlanError::TooLarge);
659 }
660 self.budget.left -= bytes;
661 self.steps.push(step);
662 Ok(self.steps.len() - 1)
663 }
664
665 fn shifted(
666 &mut self,
667 scope: &Scope<'a>,
668 nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
669 node: &NodeId,
670 input: &'a NodeId,
671 offset: MediaTime,
672 ) -> Result<usize, PlanError> {
673 let depth = nested(scope, node)?;
674 let shifted = Scope {
675 composition: scope.composition,
676 inputs: Vec::new(),
677 controls: scope.controls.clone(),
678 offset: MediaTime(scope.offset.ticks().saturating_add(offset.ticks())),
679 prefix: format!("{node}/"),
680 clip_allowed: scope.clip_allowed,
681 group_inputs_bound: false,
682 depth,
683 shift: MediaTime(scope.shift.ticks().saturating_add(offset.ticks())),
684 };
685 self.resolve(&shifted, nodes, input)
686 }
687
688 fn group(
690 &mut self,
691 scope: &Scope<'a>,
692 node: &NodeId,
693 composition: &CompositionId,
694 inputs: Vec<Option<usize>>,
695 controls: &'a std::collections::BTreeMap<String, Animated<EffectValue>>,
696 ) -> Result<usize, PlanError> {
697 let target = self.composition(composition);
698 let depth = nested(scope, node)?;
699 let controls = target
700 .controls
701 .iter()
702 .filter_map(|control| {
703 controls
704 .get(&control.name)
705 .map(|value| ((&control.node, control.param.as_str()), value))
706 })
707 .collect();
708 self.output(&Scope {
709 composition: target,
710 inputs,
711 controls,
712 offset: scope.offset,
713 prefix: format!("{node}/"),
714 clip_allowed: scope.clip_allowed,
715 group_inputs_bound: true,
716 depth,
717 shift: scope.shift,
718 })
719 }
720
721 fn composition_source(
723 &mut self,
724 scope: &Scope<'a>,
725 node: &NodeId,
726 composition: &CompositionId,
727 start: MediaTime,
728 ) -> Result<usize, PlanError> {
729 let depth = nested(scope, node)?;
730 self.output(&Scope {
731 composition: self.composition(composition),
732 inputs: Vec::new(),
733 controls: HashMap::new(),
734 offset: MediaTime(scope.offset.ticks().saturating_add(start.ticks())),
735 prefix: format!("{node}/"),
736 clip_allowed: false,
737 group_inputs_bound: false,
738 depth,
739 shift: scope.shift,
740 })
741 }
742
743 fn composition(&self, id: &CompositionId) -> &'a Composition {
744 self.lookup
745 .compositions
746 .get(id)
747 .copied()
748 .expect("validation guarantees referenced compositions exist")
749 }
750}
751
752const fn shifts(node: &alpha2_model::CompositionNode) -> bool {
753 !node.bypass && matches!(node.op, NodeOp::TimeOffset { .. })
754}
755
756fn nested(scope: &Scope<'_>, node: &NodeId) -> Result<usize, PlanError> {
757 let depth = scope.depth + 1;
758 if depth > MAX_COMPOSITION_DEPTH {
759 return Err(PlanError::NestedTooDeep { node: node.clone() });
760 }
761 Ok(depth)
762}
763
764fn scoped(prefix: &str, id: &NodeId) -> NodeId {
765 if prefix.is_empty() {
766 return id.clone();
767 }
768 NodeId::new(format!("{prefix}{id}")).expect("a prefixed id is not empty")
769}
770
771fn named_steps(
772 inputs: &BTreeMap<String, Option<NodeId>>,
773 at: &dyn Fn(&Option<NodeId>) -> usize,
774) -> Vec<(String, usize)> {
775 inputs
776 .iter()
777 .map(|(name, node)| (name.clone(), at(node)))
778 .collect()
779}
780
781fn controlled(scope: &Scope<'_>, node: &NodeId, effect: &ClipEffect) -> ClipEffect {
782 let mut effect = effect.clone();
783 for ((target, param), value) in &scope.controls {
784 if *target == node {
785 effect.params.insert((*param).to_owned(), (*value).clone());
786 }
787 }
788 effect
789}
790
791fn step_bytes(step: &Step) -> u64 {
793 let heap = match &step.op {
794 StepOp::Clip | StepOp::ShiftedClip { .. } | StepOp::Matte { .. } => 0,
795 StepOp::Media { source_id, .. } => source_id.as_str().len(),
796 StepOp::Generator { generator, .. } => generator_bytes(generator),
797 StepOp::Effect { effect, inputs, .. } => {
798 effect_bytes(effect)
799 + inputs
800 .iter()
801 .map(|(name, _)| name.len() + size_of::<(String, usize)>())
802 .sum::<usize>()
803 }
804 StepOp::Transition {
805 effect, progress, ..
806 } => effect_bytes(effect) + keyframe_bytes(progress),
807 StepOp::Transform { transform, .. } => transform_bytes(transform),
808 StepOp::Merge { layers } => layers
809 .iter()
810 .map(|layer| size_of::<StepLayer>() + keyframe_bytes(&layer.opacity))
811 .sum(),
812 StepOp::ShapeMask { masks, .. } => masks.iter().map(mask_bytes).sum(),
813 StepOp::KeyMix { opacity, .. } => keyframe_bytes(opacity),
814 };
815 u64::try_from(size_of::<Step>() + step.node.as_str().len() + heap).unwrap_or(u64::MAX)
816}
817
818fn keyframe_bytes<T>(value: &Animated<T>) -> usize {
820 match value {
821 Animated::Constant { .. } => 0,
822 Animated::Keyframes { keyframes, .. } => keyframes.len() * size_of::<Keyframe<T>>(),
823 Animated::Split { channels } => channel_bytes(channels),
824 Animated::Data(binding) => binding.channel.len(),
825 }
826}
827
828fn channel_bytes(channels: &[Animated<f32>]) -> usize {
829 channels
830 .iter()
831 .map(|channel| size_of::<Animated<f32>>() + keyframe_bytes(channel))
832 .sum()
833}
834
835fn effect_bytes(effect: &ClipEffect) -> usize {
836 effect.id.len()
837 + effect
838 .params
839 .iter()
840 .map(|(name, value)| {
841 name.len() + size_of::<Animated<EffectValue>>() + keyframe_bytes(value)
842 })
843 .sum::<usize>()
844 + effect
845 .resources
846 .iter()
847 .map(|(name, id)| name.len() + id.as_str().len())
848 .sum::<usize>()
849}
850
851fn transform_bytes(transform: &VisualProperties) -> usize {
852 point_bytes(&transform.position)
853 + keyframe_bytes(&transform.scale)
854 + keyframe_bytes(&transform.rotation_degrees)
855 + keyframe_bytes(&transform.opacity)
856}
857
858fn mask_bytes(mask: &ShapeMask) -> usize {
859 size_of::<ShapeMask>() + geometry_bytes(&mask.shape) + keyframe_bytes(&mask.feather)
860}
861
862fn point_bytes(point: &AnimatedPoint) -> usize {
863 match point {
864 AnimatedPoint::Constant { .. } | AnimatedPoint::Data(_) => 0,
865 AnimatedPoint::Split { channels } => channel_bytes(channels),
866 AnimatedPoint::Path(motion) => {
867 keyframe_bytes(&motion.distance)
868 + motion.path.vertex_count() * size_of::<alpha2_model::PathVertex>()
869 }
870 AnimatedPoint::Keyframes { keyframes, .. } => {
871 keyframes.len() * size_of::<alpha2_model::PointKeyframe>()
872 }
873 }
874}
875
876fn path_bytes(path: &Animated<alpha2_model::Path>) -> usize {
877 let one = |path: &alpha2_model::Path| {
878 path.subpaths.len() * size_of::<alpha2_model::Subpath>()
879 + path.vertex_count() * size_of::<alpha2_model::PathVertex>()
880 };
881 match path {
882 Animated::Data(_) | Animated::Split { .. } => 0,
883 Animated::Constant { value } => one(value),
884 Animated::Keyframes { keyframes, .. } => keyframes
885 .iter()
886 .map(|keyframe| size_of::<Keyframe<alpha2_model::Path>>() + one(&keyframe.value))
887 .sum(),
888 }
889}
890
891fn geometry_bytes(geometry: &alpha2_model::ShapeGeometry) -> usize {
892 use alpha2_model::ShapeGeometry;
893 match geometry {
894 ShapeGeometry::Rectangle(rectangle) => {
895 point_bytes(&rectangle.center)
896 + keyframe_bytes(&rectangle.size)
897 + keyframe_bytes(&rectangle.corner_radius)
898 + keyframe_bytes(&rectangle.rotation_degrees)
899 }
900 ShapeGeometry::Ellipse(ellipse) => {
901 point_bytes(&ellipse.center)
902 + keyframe_bytes(&ellipse.size)
903 + keyframe_bytes(&ellipse.rotation_degrees)
904 }
905 ShapeGeometry::Polystar(star) => {
906 point_bytes(&star.center)
907 + keyframe_bytes(&star.points)
908 + keyframe_bytes(&star.outer_radius)
909 + keyframe_bytes(&star.inner_radius)
910 + keyframe_bytes(&star.outer_roundness)
911 + keyframe_bytes(&star.inner_roundness)
912 + keyframe_bytes(&star.rotation_degrees)
913 }
914 ShapeGeometry::Path(path) => path_bytes(&path.path),
915 }
916}
917
918fn paint_bytes(paint: &Paint) -> usize {
919 match paint {
920 Paint::Solid { .. } => 0,
921 Paint::LinearGradient { stops, .. }
922 | Paint::RadialGradient { stops, .. }
923 | Paint::ConicGradient { stops, .. } => {
924 stops.len() * size_of::<alpha2_model::GradientStop>()
925 }
926 }
927}
928
929fn animated_paint_bytes(paint: &Animated<Paint>) -> usize {
930 match paint {
931 Animated::Data(_) | Animated::Split { .. } => 0,
932 Animated::Constant { value } => paint_bytes(value),
933 Animated::Keyframes { keyframes, .. } => keyframes
934 .iter()
935 .map(|keyframe| size_of::<Keyframe<Paint>>() + paint_bytes(&keyframe.value))
936 .sum(),
937 }
938}
939
940fn shape_items_bytes(items: &[alpha2_model::ShapeItem]) -> usize {
942 use alpha2_model::{ShapeGeometry, ShapeItem};
943 items
944 .iter()
945 .map(|item| {
946 size_of::<ShapeItem>()
947 + match item {
948 ShapeItem::Group { items, transform } => {
949 shape_items_bytes(items)
950 + keyframe_bytes(&transform.anchor)
951 + point_bytes(&transform.position)
952 + keyframe_bytes(&transform.scale)
953 + keyframe_bytes(&transform.rotation_degrees)
954 + keyframe_bytes(&transform.opacity)
955 }
956 ShapeItem::Rectangle(geometry) => {
957 geometry_bytes(&ShapeGeometry::Rectangle(geometry.clone()))
958 }
959 ShapeItem::Ellipse(geometry) => {
960 geometry_bytes(&ShapeGeometry::Ellipse(geometry.clone()))
961 }
962 ShapeItem::Polystar(geometry) => {
963 geometry_bytes(&ShapeGeometry::Polystar(geometry.clone()))
964 }
965 ShapeItem::Path(geometry) => path_bytes(&geometry.path),
966 ShapeItem::Fill { paint, opacity, .. } => {
967 animated_paint_bytes(paint) + keyframe_bytes(opacity)
968 }
969 ShapeItem::Stroke(stroke) => {
970 animated_paint_bytes(&stroke.paint)
971 + keyframe_bytes(&stroke.width)
972 + keyframe_bytes(&stroke.opacity)
973 + stroke.dash.as_ref().map_or(0, |dash| {
974 dash.pattern
975 .iter()
976 .map(|entry| size_of::<Animated<f32>>() + keyframe_bytes(entry))
977 .sum::<usize>()
978 + keyframe_bytes(&dash.offset)
979 })
980 }
981 ShapeItem::Trim(trim) => {
982 keyframe_bytes(&trim.start)
983 + keyframe_bytes(&trim.end)
984 + keyframe_bytes(&trim.offset)
985 }
986 }
987 })
988 .sum()
989}
990
991fn generator_step(generator: Generator, start: MediaTime, canvas: (u32, u32)) -> StepOp {
992 let plan = GeneratorPlan::new(&generator, canvas).map(Arc::new);
993 StepOp::Generator {
994 generator,
995 start,
996 plan,
997 }
998}
999
1000fn generator_bytes(generator: &Generator) -> usize {
1001 match generator {
1002 Generator::Fill { paint } => paint_bytes(paint),
1003 Generator::Shapes { items } => 2 * shape_items_bytes(items),
1005 Generator::Text { text, style } => {
1006 text.len() + style.font_family.as_ref().map_or(0, String::len)
1007 }
1008 Generator::Layout { root } => 2 * crate::layout::layout_bytes(root, &shape_items_bytes),
1010 Generator::Effect { effect } => effect_bytes(effect),
1011 }
1012}
1013
1014fn needed_inputs<'a>(
1017 reads: &CompositionReads<'_>,
1018 prefix: &str,
1019 node: &'a alpha2_model::CompositionNode,
1020) -> Result<Vec<&'a NodeId>, PlanError> {
1021 let needed = reads.needed_inputs(node);
1022 if node.bypass && needed.is_empty() {
1023 return Err(PlanError::MissingInput {
1025 node: scoped(prefix, &node.id),
1026 input: "layers[0]".into(),
1027 });
1028 }
1029 needed
1030 .into_iter()
1031 .map(|input| {
1032 input.node().ok_or_else(|| PlanError::MissingInput {
1033 node: scoped(prefix, &node.id),
1034 input: input.name(),
1035 })
1036 })
1037 .collect()
1038}
1039
1040#[derive(Clone, Debug)]
1042pub(crate) struct IndexedComposition {
1043 pub(crate) plan: Arc<Result<CompositionPlan, PlanError>>,
1044 pub(crate) reference: alpha2_model::ClipComposition,
1045}
1046
1047#[derive(Clone, Copy, Debug, PartialEq)]
1049pub struct ActiveComposition<'a> {
1050 plan: &'a CompositionPlan,
1051 time: MediaTime,
1052 data: crate::SampleContext<'a>,
1053 shown_by: Option<ShowingClip<'a>>,
1054}
1055
1056#[derive(Clone, Copy, Debug, PartialEq)]
1057pub(crate) struct ShowingClip<'a> {
1058 pub(crate) timeline_range: alpha2_time::TimeRange,
1059 pub(crate) source_range: alpha2_time::TimeRange,
1060 pub(crate) time_map: &'a alpha2_model::TimeMap,
1061 pub(crate) mirror: crate::Mirror,
1062 pub(crate) scale: alpha2_model::TimeScale,
1063 pub(crate) timeline_time: MediaTime,
1064}
1065
1066impl<'a> ActiveComposition<'a> {
1067 #[must_use]
1070 pub const fn new(plan: &'a CompositionPlan, time: MediaTime) -> Self {
1071 Self {
1072 plan,
1073 time,
1074 data: crate::SampleContext::NONE,
1075 shown_by: None,
1076 }
1077 }
1078
1079 pub(crate) const fn shown_by(self, clip: ShowingClip<'a>) -> Self {
1080 Self {
1081 shown_by: Some(clip),
1082 ..self
1083 }
1084 }
1085
1086 #[must_use]
1088 pub const fn with_data(self, data: crate::SampleContext<'a>) -> Self {
1089 Self { data, ..self }
1090 }
1091
1092 #[must_use]
1094 pub fn step_data(&self, step: usize) -> crate::SampleContext<'a> {
1095 self.data.for_step(self.plan, step)
1096 }
1097
1098 #[must_use]
1100 pub const fn plan(&self) -> &'a CompositionPlan {
1101 self.plan
1102 }
1103
1104 #[must_use]
1106 pub const fn time(&self) -> MediaTime {
1107 self.time
1108 }
1109
1110 pub fn media(
1113 &self,
1114 ) -> impl Iterator<
1115 Item = (
1116 usize,
1117 &'a SourceId,
1118 MediaTime,
1119 alpha2_model::FrameInterpolation,
1120 ),
1121 > + 'a {
1122 let time = self.time;
1123 self.plan
1124 .steps
1125 .iter()
1126 .enumerate()
1127 .filter_map(move |(index, step)| match &step.op {
1128 StepOp::Media {
1129 source_id,
1130 start,
1131 frame_interpolation,
1132 } => Some((
1133 index,
1134 source_id,
1135 MediaTime(start.ticks().saturating_add(step.time(time).ticks())),
1136 *frame_interpolation,
1137 )),
1138 _ => None,
1139 })
1140 }
1141
1142 #[must_use]
1148 pub fn shifted_clip_time(&self, shift: MediaTime) -> Option<MediaTime> {
1149 let clip = self.shown_by?;
1150 let time = clip
1151 .scale
1152 .shifted_time(clip.timeline_time, shift)
1153 .filter(|time| clip.timeline_range.contains(*time))?;
1154 crate::map_source_time(
1155 clip.timeline_range,
1156 clip.source_range,
1157 clip.time_map,
1158 clip.mirror,
1159 time,
1160 )
1161 }
1162
1163 pub fn shifted_clips(&self) -> impl Iterator<Item = (usize, Option<MediaTime>)> + use<'a> {
1166 let composition = *self;
1167 self.plan
1168 .shifted_clips()
1169 .map(move |(step, shift)| (step, composition.shifted_clip_time(shift)))
1170 }
1171}
1172
1173#[cfg(test)]
1174#[path = "composition_tests.rs"]
1175mod tests;
1176
1177#[cfg(test)]
1178#[path = "time_offset_tests.rs"]
1179mod time_offset_tests;