1use alpha2_media::SourceId;
12use alpha2_model::{
13 Animated, AnimatedPoint, ClipBlendMode, ClipEffect, Composition, CompositionId,
14 CompositionReads, EffectValue, Generator, Keyframe, MAX_COMPOSITION_DEPTH, MAX_INLINED_NODES,
15 MatteMode, MediaKind, MediaSource, NodeId, NodeOp, Paint, ShapeMask, VisualProperties,
16};
17use alpha2_time::MediaTime;
18use std::collections::{BTreeMap, HashMap};
19use std::sync::Arc;
20
21use crate::GeneratorPlan;
22
23pub const MAX_PLAN_BYTES: u64 = 256 * 1024 * 1024;
26
27#[derive(Clone, Debug, PartialEq)]
29pub struct CompositionPlan {
30 pub id: CompositionId,
32 pub steps: Vec<Step>,
34 pub output: usize,
36 pub media: Vec<(String, MediaTime)>,
39}
40
41impl CompositionPlan {
42 pub fn effects(&self) -> impl Iterator<Item = &ClipEffect> {
44 self.steps.iter().filter_map(|step| match &step.op {
45 StepOp::Effect { effect, .. } | StepOp::Transition { effect, .. } => Some(effect),
46 _ => None,
47 })
48 }
49
50 #[must_use]
53 pub fn media_start(&self, step: usize, via: &alpha2_model::NodeId) -> Option<MediaTime> {
54 let path = self.steps.get(step)?.node.as_str();
55 let prefix = path.rfind('/').map_or("", |slash| &path[..=slash]);
56 self.media.iter().find_map(|(node, start)| {
57 (node.strip_prefix(prefix) == Some(via.as_str())).then_some(*start)
58 })
59 }
60
61 #[must_use]
63 pub fn uses_clip(&self) -> bool {
64 self.steps
65 .iter()
66 .any(|step| matches!(step.op, StepOp::Clip))
67 }
68}
69
70#[derive(Clone, Debug, PartialEq)]
72pub struct Step {
73 pub node: NodeId,
75 pub op: StepOp,
77 pub offset: MediaTime,
79}
80
81impl Step {
82 #[must_use]
84 pub fn time(&self, time: MediaTime) -> MediaTime {
85 MediaTime(time.ticks().saturating_add(self.offset.ticks()))
86 }
87}
88
89#[derive(Clone, Debug, PartialEq)]
91pub enum StepOp {
92 Clip,
94 Media {
96 source_id: SourceId,
98 start: MediaTime,
100 },
101 Generator {
103 generator: Generator,
105 start: MediaTime,
107 plan: Option<Arc<GeneratorPlan>>,
109 },
110 Effect {
112 input: usize,
114 inputs: Vec<(String, usize)>,
116 effect: ClipEffect,
118 },
119 Transition {
121 from: usize,
123 to: usize,
125 effect: ClipEffect,
127 progress: Animated<f32>,
129 },
130 Transform {
132 input: usize,
134 transform: VisualProperties,
136 },
137 Merge {
139 layers: Vec<StepLayer>,
141 },
142 Matte {
144 input: usize,
146 matte: usize,
148 mode: MatteMode,
150 },
151 KeyMix {
153 backdrop: usize,
155 input: usize,
157 mask: Option<usize>,
159 opacity: Animated<f32>,
161 },
162 ShapeMask {
164 input: usize,
166 masks: Vec<ShapeMask>,
168 },
169}
170
171#[derive(Clone, Debug, PartialEq)]
173pub struct StepLayer {
174 pub input: usize,
176 pub blend_mode: ClipBlendMode,
178 pub opacity: Animated<f32>,
180}
181
182#[derive(Clone, Debug, PartialEq, Eq)]
184pub enum PlanError {
185 NoOutput,
187 MissingInput {
189 node: NodeId,
191 input: String,
193 },
194 UnboundGroupInput {
196 node: NodeId,
198 },
199 ClipWithoutClip {
201 node: NodeId,
203 },
204 NestedTooDeep {
206 node: NodeId,
208 },
209 TooLarge,
212}
213
214#[derive(Debug)]
216pub(crate) struct PlanBudget {
217 left: u64,
218 exceeded: bool,
219}
220
221impl PlanBudget {
222 pub(crate) const fn new(bytes: u64) -> Self {
223 Self {
224 left: bytes,
225 exceeded: false,
226 }
227 }
228
229 pub(crate) const fn exceeded(&self) -> bool {
231 self.exceeded
232 }
233}
234
235pub(crate) struct Lookup<'a> {
237 compositions: HashMap<&'a CompositionId, &'a Composition>,
238 sources: HashMap<&'a SourceId, &'a MediaSource>,
239 reads: CompositionReads<'a>,
240 canvas: (u32, u32),
242}
243
244impl<'a> Lookup<'a> {
245 pub(crate) fn new(
246 compositions: &'a [Composition],
247 sources: &'a [MediaSource],
248 canvas: (u32, u32),
249 ) -> Self {
250 let compositions = compositions
251 .iter()
252 .map(|composition| (&composition.id, composition))
253 .collect();
254 let reads = CompositionReads::new(&compositions);
255 Self {
256 compositions,
257 sources: sources.iter().map(|source| (&source.id, source)).collect(),
258 reads,
259 canvas,
260 }
261 }
262
263 pub(crate) const fn reads(&self) -> &CompositionReads<'a> {
265 &self.reads
266 }
267}
268
269pub fn plan_composition(
278 composition: &Composition,
279 compositions: &[Composition],
280 sources: &[MediaSource],
281 canvas: (u32, u32),
282) -> Result<CompositionPlan, PlanError> {
283 plan(
284 composition,
285 &Lookup::new(compositions, sources, canvas),
286 true,
287 &mut PlanBudget::new(MAX_PLAN_BYTES),
288 )
289}
290
291pub(crate) fn plan_composition_within(
293 composition: &Composition,
294 lookup: &Lookup<'_>,
295 budget: &mut PlanBudget,
296) -> Result<CompositionPlan, PlanError> {
297 plan(composition, lookup, true, budget)
298}
299
300pub fn plan_source_composition(
306 composition: &Composition,
307 compositions: &[Composition],
308 sources: &[MediaSource],
309 canvas: (u32, u32),
310) -> Result<CompositionPlan, PlanError> {
311 plan(
312 composition,
313 &Lookup::new(compositions, sources, canvas),
314 false,
315 &mut PlanBudget::new(MAX_PLAN_BYTES),
316 )
317}
318
319pub(crate) fn plan_source_composition_within(
321 composition: &Composition,
322 lookup: &Lookup<'_>,
323 budget: &mut PlanBudget,
324) -> Result<CompositionPlan, PlanError> {
325 plan(composition, lookup, false, budget)
326}
327
328fn plan<'a>(
329 composition: &'a Composition,
330 lookup: &Lookup<'a>,
331 clip_allowed: bool,
332 budget: &mut PlanBudget,
333) -> Result<CompositionPlan, PlanError> {
334 let mut planner = Planner {
335 lookup,
336 steps: Vec::new(),
337 media: Vec::new(),
338 budget,
339 };
340 let scope = Scope {
341 composition,
342 inputs: Vec::new(),
343 controls: HashMap::new(),
344 offset: MediaTime::ZERO,
345 prefix: String::new(),
346 clip_allowed,
347 group_inputs_bound: false,
348 depth: 1,
349 };
350 let output = planner.output(&scope)?;
351 Ok(CompositionPlan {
352 id: composition.id.clone(),
353 steps: planner.steps,
354 output,
355 media: planner.media,
356 })
357}
358
359struct Scope<'a> {
361 composition: &'a Composition,
362 inputs: Vec<Option<usize>>,
364 controls: HashMap<(&'a NodeId, &'a str), &'a Animated<EffectValue>>,
366 offset: MediaTime,
368 prefix: String,
370 clip_allowed: bool,
372 group_inputs_bound: bool,
374 depth: usize,
376}
377
378struct Planner<'a, 'b> {
379 lookup: &'b Lookup<'a>,
380 steps: Vec<Step>,
381 media: Vec<(String, MediaTime)>,
382 budget: &'b mut PlanBudget,
383}
384
385impl<'a> Planner<'a, '_> {
386 fn output(&mut self, scope: &Scope<'a>) -> Result<usize, PlanError> {
388 let output = scope
389 .composition
390 .output
391 .as_ref()
392 .ok_or(PlanError::NoOutput)?;
393 for node in &scope.composition.nodes {
394 if let NodeOp::Media { start, .. } = &node.op {
395 self.media
396 .push((format!("{}{}", scope.prefix, node.id), *start));
397 }
398 }
399 let nodes: HashMap<&NodeId, &'a alpha2_model::CompositionNode> = scope
400 .composition
401 .nodes
402 .iter()
403 .map(|node| (&node.id, node))
404 .collect();
405 self.resolve(scope, &nodes, output)
406 }
407
408 fn resolve(
414 &mut self,
415 scope: &Scope<'a>,
416 nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
417 id: &'a NodeId,
418 ) -> Result<usize, PlanError> {
419 let mut done: HashMap<&NodeId, usize> = HashMap::new();
420 let mut pending = vec![(id, false)];
422 while let Some((current, expanded)) = pending.pop() {
423 if done.contains_key(current) {
424 continue;
425 }
426 let node = nodes[current];
427 let needed = needed_inputs(self.lookup.reads(), &scope.prefix, node)?;
428 if !expanded {
429 pending.push((current, true));
430 pending.extend(
431 needed
432 .iter()
433 .rev()
434 .filter(|input| !done.contains_key(**input))
435 .map(|input| (*input, false)),
436 );
437 continue;
438 }
439 let step = if node.bypass {
440 done[needed[0]]
441 } else {
442 self.node_step(scope, node, &done)?
443 };
444 done.insert(current, step);
445 }
446 Ok(done[id])
447 }
448
449 fn generator_step(&self, generator: &Generator, start: MediaTime) -> StepOp {
450 generator_step(generator.clone(), start, self.lookup.canvas)
451 }
452
453 #[expect(clippy::too_many_lines, reason = "one arm per node operation")]
454 fn node_step(
455 &mut self,
456 scope: &Scope<'a>,
457 node: &'a alpha2_model::CompositionNode,
458 done: &HashMap<&NodeId, usize>,
459 ) -> Result<usize, PlanError> {
460 let at = |input: &Option<NodeId>| {
461 input
462 .as_ref()
463 .map(|id| done[id])
464 .expect("needed inputs are connected and planned")
465 };
466 let id = || scoped(&scope.prefix, &node.id);
467 let op = match &node.op {
468 NodeOp::Clip {} => {
469 if !scope.clip_allowed {
470 return Err(PlanError::ClipWithoutClip { node: id() });
471 }
472 StepOp::Clip
473 }
474 NodeOp::GroupInput { index } => {
475 return usize::try_from(*index)
477 .ok()
478 .and_then(|index| scope.inputs.get(index).copied().flatten())
479 .filter(|_| scope.group_inputs_bound)
480 .ok_or_else(|| PlanError::UnboundGroupInput { node: id() });
481 }
482 NodeOp::Group {
483 composition,
484 inputs,
485 controls,
486 } => {
487 let reads = self.lookup.reads();
489 let inputs = inputs
490 .iter()
491 .enumerate()
492 .map(|(port, input)| reads.reads_port(composition, port).then(|| at(input)))
493 .collect();
494 return self.group(scope, &id(), composition, inputs, controls);
495 }
496 NodeOp::Media { source_id, start } => {
497 let source = self.lookup.sources.get(source_id).copied();
498 if let Some(composition) = source.and_then(|source| source.composition.as_ref()) {
499 return self.composition_source(scope, &id(), composition, *start);
500 }
501 let generator = source
502 .filter(|source| source.kind == MediaKind::Generated)
503 .and_then(|source| source.generator.as_ref());
504 generator.map_or_else(
505 || StepOp::Media {
506 source_id: source_id.clone(),
507 start: *start,
508 },
509 |generator| self.generator_step(generator, *start),
510 )
511 }
512 NodeOp::Generator { generator } => self.generator_step(generator, MediaTime::ZERO),
513 NodeOp::Effect {
514 input,
515 inputs,
516 effect,
517 } => StepOp::Effect {
518 input: at(input),
519 inputs: named_steps(inputs, &at),
520 effect: controlled(scope, &node.id, effect),
521 },
522 NodeOp::Transition {
523 from,
524 to,
525 effect,
526 progress,
527 } => StepOp::Transition {
528 from: at(from),
529 to: at(to),
530 effect: controlled(scope, &node.id, effect),
531 progress: progress.clone(),
532 },
533 NodeOp::Transform { input, transform } => StepOp::Transform {
534 input: at(input),
535 transform: transform.clone(),
536 },
537 NodeOp::Merge { layers } => StepOp::Merge {
538 layers: layers
539 .iter()
540 .map(|layer| StepLayer {
541 input: at(&layer.input),
542 blend_mode: layer.blend_mode,
543 opacity: layer.opacity.clone(),
544 })
545 .collect(),
546 },
547 NodeOp::Matte { input, matte, mode } => StepOp::Matte {
548 input: at(input),
549 matte: at(matte),
550 mode: *mode,
551 },
552 NodeOp::ShapeMask { input, masks } => StepOp::ShapeMask {
553 input: at(input),
554 masks: masks.clone(),
555 },
556 NodeOp::KeyMix {
557 backdrop,
558 input,
559 mask,
560 opacity,
561 } => StepOp::KeyMix {
562 backdrop: at(backdrop),
563 input: at(input),
564 mask: mask.as_ref().map(|id| done[id]),
565 opacity: opacity.clone(),
566 },
567 };
568 self.push(Step {
569 node: id(),
570 op,
571 offset: scope.offset,
572 })
573 }
574
575 fn push(&mut self, step: Step) -> Result<usize, PlanError> {
577 if self.steps.len() >= MAX_INLINED_NODES {
578 return Err(PlanError::TooLarge);
579 }
580 let bytes = step_bytes(&step);
581 if bytes > self.budget.left {
582 self.budget.exceeded = true;
583 return Err(PlanError::TooLarge);
584 }
585 self.budget.left -= bytes;
586 self.steps.push(step);
587 Ok(self.steps.len() - 1)
588 }
589
590 fn group(
592 &mut self,
593 scope: &Scope<'a>,
594 node: &NodeId,
595 composition: &CompositionId,
596 inputs: Vec<Option<usize>>,
597 controls: &'a std::collections::BTreeMap<String, Animated<EffectValue>>,
598 ) -> Result<usize, PlanError> {
599 let target = self.composition(composition);
600 let depth = nested(scope, node)?;
601 let controls = target
602 .controls
603 .iter()
604 .filter_map(|control| {
605 controls
606 .get(&control.name)
607 .map(|value| ((&control.node, control.param.as_str()), value))
608 })
609 .collect();
610 self.output(&Scope {
611 composition: target,
612 inputs,
613 controls,
614 offset: scope.offset,
615 prefix: format!("{node}/"),
616 clip_allowed: scope.clip_allowed,
617 group_inputs_bound: true,
618 depth,
619 })
620 }
621
622 fn composition_source(
624 &mut self,
625 scope: &Scope<'a>,
626 node: &NodeId,
627 composition: &CompositionId,
628 start: MediaTime,
629 ) -> Result<usize, PlanError> {
630 let depth = nested(scope, node)?;
631 self.output(&Scope {
632 composition: self.composition(composition),
633 inputs: Vec::new(),
634 controls: HashMap::new(),
635 offset: MediaTime(scope.offset.ticks().saturating_add(start.ticks())),
636 prefix: format!("{node}/"),
637 clip_allowed: false,
638 group_inputs_bound: false,
639 depth,
640 })
641 }
642
643 fn composition(&self, id: &CompositionId) -> &'a Composition {
644 self.lookup
645 .compositions
646 .get(id)
647 .copied()
648 .expect("validation guarantees referenced compositions exist")
649 }
650}
651
652fn nested(scope: &Scope<'_>, node: &NodeId) -> Result<usize, PlanError> {
653 let depth = scope.depth + 1;
654 if depth > MAX_COMPOSITION_DEPTH {
655 return Err(PlanError::NestedTooDeep { node: node.clone() });
656 }
657 Ok(depth)
658}
659
660fn scoped(prefix: &str, id: &NodeId) -> NodeId {
661 if prefix.is_empty() {
662 return id.clone();
663 }
664 NodeId::new(format!("{prefix}{id}")).expect("a prefixed id is not empty")
665}
666
667fn named_steps(
668 inputs: &BTreeMap<String, Option<NodeId>>,
669 at: &dyn Fn(&Option<NodeId>) -> usize,
670) -> Vec<(String, usize)> {
671 inputs
672 .iter()
673 .map(|(name, node)| (name.clone(), at(node)))
674 .collect()
675}
676
677fn controlled(scope: &Scope<'_>, node: &NodeId, effect: &ClipEffect) -> ClipEffect {
678 let mut effect = effect.clone();
679 for ((target, param), value) in &scope.controls {
680 if *target == node {
681 effect.params.insert((*param).to_owned(), (*value).clone());
682 }
683 }
684 effect
685}
686
687fn step_bytes(step: &Step) -> u64 {
689 let heap = match &step.op {
690 StepOp::Clip | StepOp::Matte { .. } => 0,
691 StepOp::Media { source_id, .. } => source_id.as_str().len(),
692 StepOp::Generator { generator, .. } => generator_bytes(generator),
693 StepOp::Effect { effect, inputs, .. } => {
694 effect_bytes(effect)
695 + inputs
696 .iter()
697 .map(|(name, _)| name.len() + size_of::<(String, usize)>())
698 .sum::<usize>()
699 }
700 StepOp::Transition {
701 effect, progress, ..
702 } => effect_bytes(effect) + keyframe_bytes(progress),
703 StepOp::Transform { transform, .. } => transform_bytes(transform),
704 StepOp::Merge { layers } => layers
705 .iter()
706 .map(|layer| size_of::<StepLayer>() + keyframe_bytes(&layer.opacity))
707 .sum(),
708 StepOp::ShapeMask { masks, .. } => masks.iter().map(mask_bytes).sum(),
709 StepOp::KeyMix { opacity, .. } => keyframe_bytes(opacity),
710 };
711 u64::try_from(size_of::<Step>() + step.node.as_str().len() + heap).unwrap_or(u64::MAX)
712}
713
714fn keyframe_bytes<T>(value: &Animated<T>) -> usize {
716 match value {
717 Animated::Constant { .. } => 0,
718 Animated::Keyframes { keyframes } => keyframes.len() * size_of::<Keyframe<T>>(),
719 Animated::Data(binding) => binding.channel.len(),
720 }
721}
722
723fn effect_bytes(effect: &ClipEffect) -> usize {
724 effect.id.len()
725 + effect
726 .params
727 .iter()
728 .map(|(name, value)| {
729 name.len() + size_of::<Animated<EffectValue>>() + keyframe_bytes(value)
730 })
731 .sum::<usize>()
732 + effect
733 .resources
734 .iter()
735 .map(|(name, id)| name.len() + id.as_str().len())
736 .sum::<usize>()
737}
738
739fn transform_bytes(transform: &VisualProperties) -> usize {
740 point_bytes(&transform.position)
741 + keyframe_bytes(&transform.scale)
742 + keyframe_bytes(&transform.rotation_degrees)
743 + keyframe_bytes(&transform.opacity)
744}
745
746fn mask_bytes(mask: &ShapeMask) -> usize {
747 size_of::<ShapeMask>() + geometry_bytes(&mask.shape) + keyframe_bytes(&mask.feather)
748}
749
750fn point_bytes(point: &AnimatedPoint) -> usize {
751 match point {
752 AnimatedPoint::Constant { .. } | AnimatedPoint::Data(_) => 0,
753 AnimatedPoint::Keyframes { keyframes } => {
754 keyframes.len() * size_of::<alpha2_model::PointKeyframe>()
755 }
756 }
757}
758
759fn path_bytes(path: &Animated<alpha2_model::Path>) -> usize {
760 let one = |path: &alpha2_model::Path| {
761 path.subpaths.len() * size_of::<alpha2_model::Subpath>()
762 + path.vertex_count() * size_of::<alpha2_model::PathVertex>()
763 };
764 match path {
765 Animated::Data(_) => 0,
766 Animated::Constant { value } => one(value),
767 Animated::Keyframes { keyframes } => keyframes
768 .iter()
769 .map(|keyframe| size_of::<Keyframe<alpha2_model::Path>>() + one(&keyframe.value))
770 .sum(),
771 }
772}
773
774fn geometry_bytes(geometry: &alpha2_model::ShapeGeometry) -> usize {
775 use alpha2_model::ShapeGeometry;
776 match geometry {
777 ShapeGeometry::Rectangle(rectangle) => {
778 point_bytes(&rectangle.center)
779 + keyframe_bytes(&rectangle.size)
780 + keyframe_bytes(&rectangle.corner_radius)
781 + keyframe_bytes(&rectangle.rotation_degrees)
782 }
783 ShapeGeometry::Ellipse(ellipse) => {
784 point_bytes(&ellipse.center)
785 + keyframe_bytes(&ellipse.size)
786 + keyframe_bytes(&ellipse.rotation_degrees)
787 }
788 ShapeGeometry::Polystar(star) => {
789 point_bytes(&star.center)
790 + keyframe_bytes(&star.points)
791 + keyframe_bytes(&star.outer_radius)
792 + keyframe_bytes(&star.inner_radius)
793 + keyframe_bytes(&star.outer_roundness)
794 + keyframe_bytes(&star.inner_roundness)
795 + keyframe_bytes(&star.rotation_degrees)
796 }
797 ShapeGeometry::Path(path) => path_bytes(&path.path),
798 }
799}
800
801fn paint_bytes(paint: &Paint) -> usize {
802 match paint {
803 Paint::Solid { .. } => 0,
804 Paint::LinearGradient { stops, .. }
805 | Paint::RadialGradient { stops, .. }
806 | Paint::ConicGradient { stops, .. } => {
807 stops.len() * size_of::<alpha2_model::GradientStop>()
808 }
809 }
810}
811
812fn animated_paint_bytes(paint: &Animated<Paint>) -> usize {
813 match paint {
814 Animated::Data(_) => 0,
815 Animated::Constant { value } => paint_bytes(value),
816 Animated::Keyframes { keyframes } => keyframes
817 .iter()
818 .map(|keyframe| size_of::<Keyframe<Paint>>() + paint_bytes(&keyframe.value))
819 .sum(),
820 }
821}
822
823fn shape_items_bytes(items: &[alpha2_model::ShapeItem]) -> usize {
825 use alpha2_model::{ShapeGeometry, ShapeItem};
826 items
827 .iter()
828 .map(|item| {
829 size_of::<ShapeItem>()
830 + match item {
831 ShapeItem::Group { items, transform } => {
832 shape_items_bytes(items)
833 + keyframe_bytes(&transform.anchor)
834 + point_bytes(&transform.position)
835 + keyframe_bytes(&transform.scale)
836 + keyframe_bytes(&transform.rotation_degrees)
837 + keyframe_bytes(&transform.opacity)
838 }
839 ShapeItem::Rectangle(geometry) => {
840 geometry_bytes(&ShapeGeometry::Rectangle(geometry.clone()))
841 }
842 ShapeItem::Ellipse(geometry) => {
843 geometry_bytes(&ShapeGeometry::Ellipse(geometry.clone()))
844 }
845 ShapeItem::Polystar(geometry) => {
846 geometry_bytes(&ShapeGeometry::Polystar(geometry.clone()))
847 }
848 ShapeItem::Path(geometry) => path_bytes(&geometry.path),
849 ShapeItem::Fill { paint, opacity, .. } => {
850 animated_paint_bytes(paint) + keyframe_bytes(opacity)
851 }
852 ShapeItem::Stroke(stroke) => {
853 animated_paint_bytes(&stroke.paint)
854 + keyframe_bytes(&stroke.width)
855 + keyframe_bytes(&stroke.opacity)
856 + stroke.dash.as_ref().map_or(0, |dash| {
857 dash.pattern
858 .iter()
859 .map(|entry| size_of::<Animated<f32>>() + keyframe_bytes(entry))
860 .sum::<usize>()
861 + keyframe_bytes(&dash.offset)
862 })
863 }
864 ShapeItem::Trim(trim) => {
865 keyframe_bytes(&trim.start)
866 + keyframe_bytes(&trim.end)
867 + keyframe_bytes(&trim.offset)
868 }
869 }
870 })
871 .sum()
872}
873
874fn generator_step(generator: Generator, start: MediaTime, canvas: (u32, u32)) -> StepOp {
875 let plan = GeneratorPlan::new(&generator, canvas).map(Arc::new);
876 StepOp::Generator {
877 generator,
878 start,
879 plan,
880 }
881}
882
883fn generator_bytes(generator: &Generator) -> usize {
884 match generator {
885 Generator::Fill { paint } => paint_bytes(paint),
886 Generator::Shapes { items } => 2 * shape_items_bytes(items),
888 Generator::Text { text, style } => {
889 text.len() + style.font_family.as_ref().map_or(0, String::len)
890 }
891 Generator::Layout { root } => 2 * crate::layout::layout_bytes(root, &shape_items_bytes),
893 }
894}
895
896fn needed_inputs<'a>(
899 reads: &CompositionReads<'_>,
900 prefix: &str,
901 node: &'a alpha2_model::CompositionNode,
902) -> Result<Vec<&'a NodeId>, PlanError> {
903 let needed = reads.needed_inputs(node);
904 if node.bypass && needed.is_empty() {
905 return Err(PlanError::MissingInput {
907 node: scoped(prefix, &node.id),
908 input: "layers[0]".into(),
909 });
910 }
911 needed
912 .into_iter()
913 .map(|input| {
914 input.node().ok_or_else(|| PlanError::MissingInput {
915 node: scoped(prefix, &node.id),
916 input: input.name(),
917 })
918 })
919 .collect()
920}
921
922#[derive(Clone, Debug)]
924pub(crate) struct IndexedComposition {
925 pub(crate) plan: Arc<Result<CompositionPlan, PlanError>>,
926 pub(crate) reference: alpha2_model::ClipComposition,
927}
928
929#[derive(Clone, Copy, Debug, PartialEq)]
931pub struct ActiveComposition<'a> {
932 plan: &'a CompositionPlan,
933 time: MediaTime,
934 data: crate::SampleContext<'a>,
935}
936
937impl<'a> ActiveComposition<'a> {
938 #[must_use]
940 pub const fn new(plan: &'a CompositionPlan, time: MediaTime) -> Self {
941 Self {
942 plan,
943 time,
944 data: crate::SampleContext::NONE,
945 }
946 }
947
948 #[must_use]
950 pub const fn with_data(self, data: crate::SampleContext<'a>) -> Self {
951 Self { data, ..self }
952 }
953
954 #[must_use]
956 pub fn step_data(&self, step: usize) -> crate::SampleContext<'a> {
957 self.data.for_step(self.plan, step)
958 }
959
960 #[must_use]
962 pub const fn plan(&self) -> &'a CompositionPlan {
963 self.plan
964 }
965
966 #[must_use]
968 pub const fn time(&self) -> MediaTime {
969 self.time
970 }
971
972 pub fn media(&self) -> impl Iterator<Item = (usize, &'a SourceId, MediaTime)> + 'a {
974 let time = self.time;
975 self.plan
976 .steps
977 .iter()
978 .enumerate()
979 .filter_map(move |(index, step)| match &step.op {
980 StepOp::Media { source_id, start } => Some((
981 index,
982 source_id,
983 MediaTime(start.ticks().saturating_add(step.time(time).ticks())),
984 )),
985 _ => None,
986 })
987 }
988}
989
990#[cfg(test)]
991#[path = "composition_tests.rs"]
992mod tests;