alpha2-eval 0.10.0

Pure alpha2 timeline evaluation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
//! Composition graphs resolved into the steps that draw their output.
//!
//! A composition is compiled once, when the index is built. Nodes reachable from the output are
//! put in dependency order, bypassed nodes are replaced by their pass-through input, and group
//! nodes and composition-source media nodes are inlined (the latter shifted by the node's start).
//! A time offset node's input is planned once more, shifted by the node's offset. The result
//! equals the flattened graph, so evaluating a frame only samples step settings.
//!
//! Inlining copies settings per step. Validation bounds the step count ([`MAX_INLINED_NODES`])
//! and the planner bounds total plan size ([`MAX_PLAN_BYTES`]).

use alpha2_media::SourceId;
use alpha2_model::{
    Animated, AnimatedPoint, ClipBlendMode, ClipEffect, Composition, CompositionId,
    CompositionReads, EffectValue, Generator, Keyframe, MAX_COMPOSITION_DEPTH, MAX_INLINED_NODES,
    MatteMode, MediaKind, MediaSource, NodeId, NodeOp, Paint, ShapeMask, VisualProperties,
};
use alpha2_time::MediaTime;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use crate::GeneratorPlan;

/// Most bytes all compiled composition plans of one project may hold together, estimated per
/// [`Step`] (node path plus settings heap). Past this none draws ([`PlanError::TooLarge`]).
pub const MAX_PLAN_BYTES: u64 = 256 * 1024 * 1024;

/// A composition's output, drawn by steps in dependency order.
#[derive(Clone, Debug, PartialEq)]
pub struct CompositionPlan {
    /// The composition.
    pub id: CompositionId,
    /// Steps in dependency order; each step's inputs are earlier steps.
    pub steps: Vec<Step>,
    /// The step whose image is the composition's picture.
    pub output: usize,
    /// Every `media` node of the compositions the steps come from, drawn or not, by inlined path,
    /// with its start: what a value bound to data reads through.
    pub media: Vec<(String, MediaTime)>,
}

impl CompositionPlan {
    /// The effect, transition and generator effect invocations the steps run, in step order.
    pub fn effects(&self) -> impl Iterator<Item = &ClipEffect> {
        self.steps.iter().filter_map(|step| match &step.op {
            StepOp::Effect { effect, .. }
            | StepOp::Transition { effect, .. }
            | StepOp::Generator {
                generator: Generator::Effect { effect },
                ..
            } => Some(effect),
            _ => None,
        })
    }

    /// The start of the `media` node `via` beside step `step`, found as the node of that id in
    /// the same inlined composition, past the ids of the time offset nodes the step is read
    /// through.
    #[must_use]
    pub fn media_start(&self, step: usize, via: &alpha2_model::NodeId) -> Option<MediaTime> {
        let path = self.steps.get(step)?.node.as_str();
        let mut prefix = path.rfind('/').map_or("", |slash| &path[..=slash]);
        loop {
            let found = self.media.iter().find_map(|(node, start)| {
                (node.strip_prefix(prefix) == Some(via.as_str())).then_some(*start)
            });
            if found.is_some() {
                return found;
            }
            let outer = prefix.strip_suffix('/')?;
            prefix = outer.rfind('/').map_or("", |slash| &outer[..=slash]);
        }
    }

    /// Whether a step draws the picture of the clip showing the plan at the frame's own time.
    #[must_use]
    pub fn uses_clip(&self) -> bool {
        self.steps
            .iter()
            .any(|step| matches!(step.op, StepOp::Clip))
    }

    /// Whether a step draws the picture of the clip showing the plan, at the frame's own time
    /// or at another.
    #[must_use]
    pub fn draws_clip(&self) -> bool {
        self.steps
            .iter()
            .any(|step| matches!(step.op, StepOp::Clip | StepOp::ShiftedClip { .. }))
    }

    /// The steps that draw the clip showing the plan at another time, with their shifts.
    pub fn shifted_clips(&self) -> impl Iterator<Item = (usize, MediaTime)> + '_ {
        self.steps
            .iter()
            .enumerate()
            .filter_map(|(index, step)| match step.op {
                StepOp::ShiftedClip { shift } => Some((index, shift)),
                _ => None,
            })
    }
}

/// One node of a composition, with its inputs resolved to earlier steps.
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
    /// The node path: ids of the group, media and time offset nodes it is drawn through, then
    /// its own, joined by `/`.
    pub node: NodeId,
    /// What it draws.
    pub op: StepOp,
    /// Added to the plan's time to sample this step: the starts of the media nodes inlined
    /// through and the offsets of the time offset nodes it is read through.
    pub offset: MediaTime,
}

impl Step {
    /// The time this step's settings are sampled at when the plan is drawn at `time`.
    #[must_use]
    pub fn time(&self, time: MediaTime) -> MediaTime {
        MediaTime(time.ticks().saturating_add(self.offset.ticks()))
    }
}

/// The operation of a [`Step`]. Inputs are indices of earlier steps.
#[derive(Clone, Debug, PartialEq)]
pub enum StepOp {
    /// The picture of the clip showing the composition.
    Clip,
    /// The picture of the clip showing the composition as time offset nodes read it: the clip
    /// at the timeline time `shift` of composition time away
    /// ([`alpha2_model::TimeScale::shifted_time`]), transparent outside the clip.
    ShiftedClip {
        /// The offsets it is read through, added; never zero.
        shift: MediaTime,
    },
    /// A host-supplied source at `start` plus the composition time.
    Media {
        /// The source.
        source_id: SourceId,
        /// Source time at composition time zero.
        start: MediaTime,
        /// What the step shows between two frames of the source; `Hold` for a source without
        /// frames.
        frame_interpolation: alpha2_model::FrameInterpolation,
    },
    /// A picture the engine draws (a generator node, or a media node naming a generated source).
    Generator {
        /// What it draws.
        generator: Generator,
        /// Picture time at composition time zero: a media node's start, zero for a generator node.
        start: MediaTime,
        /// Planned tree for a shapes or layout generator.
        plan: Option<Arc<GeneratorPlan>>,
    },
    /// A registered effect.
    Effect {
        /// The processed image.
        input: usize,
        /// Additional named inputs, in name order.
        inputs: Vec<(String, usize)>,
        /// The effect.
        effect: ClipEffect,
    },
    /// A registered transition at an explicit progress.
    Transition {
        /// The image at progress zero.
        from: usize,
        /// The image at progress one.
        to: usize,
        /// The transition.
        effect: ClipEffect,
        /// Progress in `0..=1`.
        progress: Animated<f32>,
    },
    /// The input placed by a transform.
    Transform {
        /// The placed image.
        input: usize,
        /// The transform.
        transform: VisualProperties,
        /// Whether its motion is averaged over the frame's shutter.
        motion_blur: bool,
    },
    /// Layers composited over transparency, bottom first.
    Merge {
        /// The layers.
        layers: Vec<StepLayer>,
    },
    /// The input kept where a second image says.
    Matte {
        /// The kept image.
        input: usize,
        /// The coverage image.
        matte: usize,
        /// Which property of the coverage image counts.
        mode: MatteMode,
    },
    /// The backdrop replaced by the input by `k = opacity x mask alpha`.
    KeyMix {
        /// The replaced picture.
        backdrop: usize,
        /// The picture replacing it.
        input: usize,
        /// The coverage image; `None` covers everywhere.
        mask: Option<usize>,
        /// Scales the coverage, in `0..=1`.
        opacity: Animated<f32>,
    },
    /// The input kept inside shapes.
    ShapeMask {
        /// The masked image.
        input: usize,
        /// The shapes.
        masks: Vec<ShapeMask>,
    },
}

/// One layer of a [`StepOp::Merge`].
#[derive(Clone, Debug, PartialEq)]
pub struct StepLayer {
    /// The layer's image.
    pub input: usize,
    /// Its blend mode.
    pub blend_mode: ClipBlendMode,
    /// Its opacity.
    pub opacity: Animated<f32>,
}

/// Why a composition's output cannot be drawn.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanError {
    /// The composition selects no output.
    NoOutput,
    /// A node the output needs has an unconnected input.
    MissingInput {
        /// The node.
        node: NodeId,
        /// `input`, `from`, `to`, `matte`, `layers[i]`, `inputs[i]` or `inputs.<name>`.
        input: String,
    },
    /// A group input read where no group node feeds it, or through a time offset node.
    UnboundGroupInput {
        /// The node.
        node: NodeId,
    },
    /// A clip node in a composition drawn as a source, which shows no clip.
    ClipWithoutClip {
        /// The node.
        node: NodeId,
    },
    /// Compositions and time offsets nest deeper than [`alpha2_model::MAX_COMPOSITION_DEPTH`]
    /// (unvalidated only).
    NestedTooDeep {
        /// The node.
        node: NodeId,
    },
    /// More than [`alpha2_model::MAX_INLINED_NODES`] steps, or the project's plans exceed
    /// [`MAX_PLAN_BYTES`].
    TooLarge,
}

/// Remaining plan bytes, shared by all plans of one project.
#[derive(Debug)]
pub(crate) struct PlanBudget {
    left: u64,
    exceeded: bool,
}

impl PlanBudget {
    pub(crate) const fn new(bytes: u64) -> Self {
        Self {
            left: bytes,
            exceeded: false,
        }
    }

    /// Whether a plan needed more than was left.
    pub(crate) const fn exceeded(&self) -> bool {
        self.exceeded
    }
}

/// A project's compositions and sources by ID, and what each composition reads.
pub(crate) struct Lookup<'a> {
    compositions: HashMap<&'a CompositionId, &'a Composition>,
    sources: HashMap<&'a SourceId, &'a MediaSource>,
    reads: CompositionReads<'a>,
    /// The project canvas in pixels.
    canvas: (u32, u32),
}

impl<'a> Lookup<'a> {
    pub(crate) fn new(
        compositions: &'a [Composition],
        sources: &'a [MediaSource],
        canvas: (u32, u32),
    ) -> Self {
        let compositions = compositions
            .iter()
            .map(|composition| (&composition.id, composition))
            .collect();
        let reads = CompositionReads::new(&compositions);
        Self {
            compositions,
            sources: sources.iter().map(|source| (&source.id, source)).collect(),
            reads,
            canvas,
        }
    }

    /// What each composition reads.
    pub(crate) const fn reads(&self) -> &CompositionReads<'a> {
        &self.reads
    }
}

/// Compiles `composition`'s output into steps as a clip's composition, where clip nodes draw the
/// clip's picture. `compositions` resolves group nodes and `sources` resolves media nodes.
///
/// The project must be valid ([`alpha2_model::Project::validate`]).
///
/// # Errors
/// Returns [`PlanError`] when there is no output, a needed input is unconnected, or the plan
/// nests too deep or grows past [`MAX_PLAN_BYTES`].
pub fn plan_composition(
    composition: &Composition,
    compositions: &[Composition],
    sources: &[MediaSource],
    canvas: (u32, u32),
) -> Result<CompositionPlan, PlanError> {
    plan(
        composition,
        &Lookup::new(compositions, sources, canvas),
        true,
        &mut PlanBudget::new(MAX_PLAN_BYTES),
    )
}

/// [`plan_composition`] drawing from a shared `budget`.
pub(crate) fn plan_composition_within(
    composition: &Composition,
    lookup: &Lookup<'_>,
    budget: &mut PlanBudget,
) -> Result<CompositionPlan, PlanError> {
    plan(composition, lookup, true, budget)
}

/// Compiles `composition` as a composition source. Like [`plan_composition`], but clip nodes and
/// group inputs are errors because nothing feeds them.
///
/// # Errors
/// Returns [`PlanError`] as [`plan_composition`] does, and for a needed clip node or group input.
pub fn plan_source_composition(
    composition: &Composition,
    compositions: &[Composition],
    sources: &[MediaSource],
    canvas: (u32, u32),
) -> Result<CompositionPlan, PlanError> {
    plan(
        composition,
        &Lookup::new(compositions, sources, canvas),
        false,
        &mut PlanBudget::new(MAX_PLAN_BYTES),
    )
}

/// [`plan_source_composition`] drawing from a shared `budget`.
pub(crate) fn plan_source_composition_within(
    composition: &Composition,
    lookup: &Lookup<'_>,
    budget: &mut PlanBudget,
) -> Result<CompositionPlan, PlanError> {
    plan(composition, lookup, false, budget)
}

fn plan<'a>(
    composition: &'a Composition,
    lookup: &Lookup<'a>,
    clip_allowed: bool,
    budget: &mut PlanBudget,
) -> Result<CompositionPlan, PlanError> {
    let mut planner = Planner {
        lookup,
        steps: Vec::new(),
        media: Vec::new(),
        budget,
    };
    let scope = Scope {
        composition,
        inputs: Vec::new(),
        controls: HashMap::new(),
        offset: MediaTime::ZERO,
        prefix: String::new(),
        clip_allowed,
        group_inputs_bound: false,
        depth: 1,
        shift: MediaTime::ZERO,
    };
    let output = planner.output(&scope)?;
    Ok(CompositionPlan {
        id: composition.id.clone(),
        steps: planner.steps,
        output,
        media: planner.media,
    })
}

/// One composition as it is being drawn: inline in another, or on its own.
struct Scope<'a> {
    composition: &'a Composition,
    /// The step each group input reads, if the composition reads it.
    inputs: Vec<Option<usize>>,
    /// Values its group node sets, by node and parameter.
    controls: HashMap<(&'a NodeId, &'a str), &'a Animated<EffectValue>>,
    /// Added to the plan's time for its steps.
    offset: MediaTime,
    /// Prepended to its node ids in the steps.
    prefix: String,
    /// Whether a clip node draws the clip's picture here.
    clip_allowed: bool,
    /// Whether a group node feeds its group inputs.
    group_inputs_bound: bool,
    /// Nesting depth, one for the plan's own composition.
    depth: usize,
    shift: MediaTime,
}

struct Planner<'a, 'b> {
    lookup: &'b Lookup<'a>,
    steps: Vec<Step>,
    media: Vec<(String, MediaTime)>,
    budget: &'b mut PlanBudget,
}

impl<'a> Planner<'a, '_> {
    /// The step drawing `scope`'s output.
    fn output(&mut self, scope: &Scope<'a>) -> Result<usize, PlanError> {
        let output = scope
            .composition
            .output
            .as_ref()
            .ok_or(PlanError::NoOutput)?;
        for node in &scope.composition.nodes {
            if let NodeOp::Media { start, .. } = &node.op {
                self.media
                    .push((format!("{}{}", scope.prefix, node.id), *start));
            }
        }
        let nodes: HashMap<&NodeId, &'a alpha2_model::CompositionNode> = scope
            .composition
            .nodes
            .iter()
            .map(|node| (&node.id, node))
            .collect();
        self.resolve(scope, &nodes, output)
    }

    /// The step drawing node `id` of `scope`, planning its dependencies first.
    ///
    /// The walk is iterative so a long chain cannot exhaust the stack. Nesting recurses at most
    /// [`alpha2_model::MAX_COMPOSITION_DEPTH`] deep, and the planner enforces both limits even
    /// for unvalidated projects.
    fn resolve(
        &mut self,
        scope: &Scope<'a>,
        nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
        id: &'a NodeId,
    ) -> Result<usize, PlanError> {
        let mut done: HashMap<&NodeId, usize> = HashMap::new();
        // Each entry is a node whose needed inputs are pushed before it is revisited.
        let mut pending = vec![(id, false)];
        while let Some((current, expanded)) = pending.pop() {
            if done.contains_key(current) {
                continue;
            }
            let node = nodes[current];
            let needed = needed_inputs(self.lookup.reads(), &scope.prefix, node)?;
            if !expanded {
                pending.push((current, true));
                let in_this_scope = if shifts(node) { &[][..] } else { &needed[..] };
                pending.extend(
                    in_this_scope
                        .iter()
                        .rev()
                        .filter(|input| !done.contains_key(**input))
                        .map(|input| (*input, false)),
                );
                continue;
            }
            let step = if node.bypass {
                done[needed[0]]
            } else {
                self.node_step(scope, nodes, node, &done)?
            };
            done.insert(current, step);
        }
        Ok(done[id])
    }

    fn generator_step(&self, generator: &Generator, start: MediaTime) -> StepOp {
        generator_step(generator.clone(), start, self.lookup.canvas)
    }

    #[expect(clippy::too_many_lines, reason = "one arm per node operation")]
    fn node_step(
        &mut self,
        scope: &Scope<'a>,
        nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
        node: &'a alpha2_model::CompositionNode,
        done: &HashMap<&NodeId, usize>,
    ) -> Result<usize, PlanError> {
        let at = |input: &Option<NodeId>| {
            input
                .as_ref()
                .map(|id| done[id])
                .expect("needed inputs are connected and planned")
        };
        let id = || scoped(&scope.prefix, &node.id);
        let op = match &node.op {
            NodeOp::Clip {} => {
                if !scope.clip_allowed {
                    return Err(PlanError::ClipWithoutClip { node: id() });
                }
                if scope.shift == MediaTime::ZERO {
                    StepOp::Clip
                } else {
                    StepOp::ShiftedClip { shift: scope.shift }
                }
            }
            NodeOp::GroupInput { index } => {
                // Validation keeps the index within the composition's ports.
                return usize::try_from(*index)
                    .ok()
                    .and_then(|index| scope.inputs.get(index).copied().flatten())
                    .filter(|_| scope.group_inputs_bound)
                    .ok_or_else(|| PlanError::UnboundGroupInput { node: id() });
            }
            NodeOp::TimeOffset { input, offset } => {
                let input = input.as_ref().expect("needed inputs are connected");
                return self.shifted(scope, nodes, &id(), input, *offset);
            }
            NodeOp::Group {
                composition,
                inputs,
                controls,
            } => {
                // Only the ports its composition reads are needed, and planned.
                let reads = self.lookup.reads();
                let inputs = inputs
                    .iter()
                    .enumerate()
                    .map(|(port, input)| reads.reads_port(composition, port).then(|| at(input)))
                    .collect();
                return self.group(scope, &id(), composition, inputs, controls);
            }
            NodeOp::Media {
                source_id,
                start,
                frame_interpolation,
            } => {
                let source = self.lookup.sources.get(source_id).copied();
                if let Some(composition) = source.and_then(|source| source.composition.as_ref()) {
                    return self.composition_source(scope, &id(), composition, *start);
                }
                let generator = source
                    .filter(|source| source.kind == MediaKind::Generated)
                    .and_then(|source| source.generator.as_ref());
                generator.map_or_else(
                    || StepOp::Media {
                        source_id: source_id.clone(),
                        start: *start,
                        frame_interpolation: source
                            .filter(|source| source.kind == MediaKind::Video)
                            .map_or(alpha2_model::FrameInterpolation::Hold, |_| {
                                *frame_interpolation
                            }),
                    },
                    |generator| self.generator_step(generator, *start),
                )
            }
            NodeOp::Generator { generator } => self.generator_step(generator, MediaTime::ZERO),
            NodeOp::Effect {
                input,
                inputs,
                effect,
            } => StepOp::Effect {
                input: at(input),
                inputs: named_steps(inputs, &at),
                effect: controlled(scope, &node.id, effect),
            },
            NodeOp::Transition {
                from,
                to,
                effect,
                progress,
            } => StepOp::Transition {
                from: at(from),
                to: at(to),
                effect: controlled(scope, &node.id, effect),
                progress: progress.clone(),
            },
            NodeOp::Transform {
                input,
                transform,
                motion_blur,
            } => StepOp::Transform {
                input: at(input),
                transform: transform.clone(),
                motion_blur: *motion_blur,
            },
            NodeOp::Merge { layers } => StepOp::Merge {
                layers: layers
                    .iter()
                    .map(|layer| StepLayer {
                        input: at(&layer.input),
                        blend_mode: layer.blend_mode,
                        opacity: layer.opacity.clone(),
                    })
                    .collect(),
            },
            NodeOp::Matte { input, matte, mode } => StepOp::Matte {
                input: at(input),
                matte: at(matte),
                mode: *mode,
            },
            NodeOp::ShapeMask { input, masks } => StepOp::ShapeMask {
                input: at(input),
                masks: masks.clone(),
            },
            NodeOp::KeyMix {
                backdrop,
                input,
                mask,
                opacity,
            } => StepOp::KeyMix {
                backdrop: at(backdrop),
                input: at(input),
                mask: mask.as_ref().map(|id| done[id]),
                opacity: opacity.clone(),
            },
        };
        self.push(Step {
            node: id(),
            op,
            offset: scope.offset,
        })
    }

    /// Adds `step`, enforcing [`MAX_INLINED_NODES`] and the byte budget.
    fn push(&mut self, step: Step) -> Result<usize, PlanError> {
        if self.steps.len() >= MAX_INLINED_NODES {
            return Err(PlanError::TooLarge);
        }
        let bytes = step_bytes(&step);
        if bytes > self.budget.left {
            self.budget.exceeded = true;
            return Err(PlanError::TooLarge);
        }
        self.budget.left -= bytes;
        self.steps.push(step);
        Ok(self.steps.len() - 1)
    }

    fn shifted(
        &mut self,
        scope: &Scope<'a>,
        nodes: &HashMap<&NodeId, &'a alpha2_model::CompositionNode>,
        node: &NodeId,
        input: &'a NodeId,
        offset: MediaTime,
    ) -> Result<usize, PlanError> {
        let depth = nested(scope, node)?;
        let shifted = Scope {
            composition: scope.composition,
            inputs: Vec::new(),
            controls: scope.controls.clone(),
            offset: MediaTime(scope.offset.ticks().saturating_add(offset.ticks())),
            prefix: format!("{node}/"),
            clip_allowed: scope.clip_allowed,
            group_inputs_bound: false,
            depth,
            shift: MediaTime(scope.shift.ticks().saturating_add(offset.ticks())),
        };
        self.resolve(&shifted, nodes, input)
    }

    /// Inlines a group node's composition with its inputs and controls applied.
    fn group(
        &mut self,
        scope: &Scope<'a>,
        node: &NodeId,
        composition: &CompositionId,
        inputs: Vec<Option<usize>>,
        controls: &'a std::collections::BTreeMap<String, Animated<EffectValue>>,
    ) -> Result<usize, PlanError> {
        let target = self.composition(composition);
        let depth = nested(scope, node)?;
        let controls = target
            .controls
            .iter()
            .filter_map(|control| {
                controls
                    .get(&control.name)
                    .map(|value| ((&control.node, control.param.as_str()), value))
            })
            .collect();
        self.output(&Scope {
            composition: target,
            inputs,
            controls,
            offset: scope.offset,
            prefix: format!("{node}/"),
            clip_allowed: scope.clip_allowed,
            group_inputs_bound: true,
            depth,
            shift: scope.shift,
        })
    }

    /// Inlines a media node's composition source, shifted by `start`.
    fn composition_source(
        &mut self,
        scope: &Scope<'a>,
        node: &NodeId,
        composition: &CompositionId,
        start: MediaTime,
    ) -> Result<usize, PlanError> {
        let depth = nested(scope, node)?;
        self.output(&Scope {
            composition: self.composition(composition),
            inputs: Vec::new(),
            controls: HashMap::new(),
            offset: MediaTime(scope.offset.ticks().saturating_add(start.ticks())),
            prefix: format!("{node}/"),
            clip_allowed: false,
            group_inputs_bound: false,
            depth,
            shift: scope.shift,
        })
    }

    fn composition(&self, id: &CompositionId) -> &'a Composition {
        self.lookup
            .compositions
            .get(id)
            .copied()
            .expect("validation guarantees referenced compositions exist")
    }
}

const fn shifts(node: &alpha2_model::CompositionNode) -> bool {
    !node.bypass && matches!(node.op, NodeOp::TimeOffset { .. })
}

fn nested(scope: &Scope<'_>, node: &NodeId) -> Result<usize, PlanError> {
    let depth = scope.depth + 1;
    if depth > MAX_COMPOSITION_DEPTH {
        return Err(PlanError::NestedTooDeep { node: node.clone() });
    }
    Ok(depth)
}

fn scoped(prefix: &str, id: &NodeId) -> NodeId {
    if prefix.is_empty() {
        return id.clone();
    }
    NodeId::new(format!("{prefix}{id}")).expect("a prefixed id is not empty")
}

fn named_steps(
    inputs: &BTreeMap<String, Option<NodeId>>,
    at: &dyn Fn(&Option<NodeId>) -> usize,
) -> Vec<(String, usize)> {
    inputs
        .iter()
        .map(|(name, node)| (name.clone(), at(node)))
        .collect()
}

fn controlled(scope: &Scope<'_>, node: &NodeId, effect: &ClipEffect) -> ClipEffect {
    let mut effect = effect.clone();
    for ((target, param), value) in &scope.controls {
        if *target == node {
            effect.params.insert((*param).to_owned(), (*value).clone());
        }
    }
    effect
}

/// Bytes `step` holds, as [`MAX_PLAN_BYTES`] counts them.
fn step_bytes(step: &Step) -> u64 {
    let heap = match &step.op {
        StepOp::Clip | StepOp::ShiftedClip { .. } | StepOp::Matte { .. } => 0,
        StepOp::Media { source_id, .. } => source_id.as_str().len(),
        StepOp::Generator { generator, .. } => generator_bytes(generator),
        StepOp::Effect { effect, inputs, .. } => {
            effect_bytes(effect)
                + inputs
                    .iter()
                    .map(|(name, _)| name.len() + size_of::<(String, usize)>())
                    .sum::<usize>()
        }
        StepOp::Transition {
            effect, progress, ..
        } => effect_bytes(effect) + keyframe_bytes(progress),
        StepOp::Transform { transform, .. } => transform_bytes(transform),
        StepOp::Merge { layers } => layers
            .iter()
            .map(|layer| size_of::<StepLayer>() + keyframe_bytes(&layer.opacity))
            .sum(),
        StepOp::ShapeMask { masks, .. } => masks.iter().map(mask_bytes).sum(),
        StepOp::KeyMix { opacity, .. } => keyframe_bytes(opacity),
    };
    u64::try_from(size_of::<Step>() + step.node.as_str().len() + heap).unwrap_or(u64::MAX)
}

/// The heap an animated value's keyframes take; none for a constant.
fn keyframe_bytes<T>(value: &Animated<T>) -> usize {
    match value {
        Animated::Constant { .. } => 0,
        Animated::Keyframes { keyframes, .. } => keyframes.len() * size_of::<Keyframe<T>>(),
        Animated::Split { channels } => channel_bytes(channels),
        Animated::Data(binding) => binding.channel.len(),
    }
}

fn channel_bytes(channels: &[Animated<f32>]) -> usize {
    channels
        .iter()
        .map(|channel| size_of::<Animated<f32>>() + keyframe_bytes(channel))
        .sum()
}

fn effect_bytes(effect: &ClipEffect) -> usize {
    effect.id.len()
        + effect
            .params
            .iter()
            .map(|(name, value)| {
                name.len() + size_of::<Animated<EffectValue>>() + keyframe_bytes(value)
            })
            .sum::<usize>()
        + effect
            .resources
            .iter()
            .map(|(name, id)| name.len() + id.as_str().len())
            .sum::<usize>()
}

fn transform_bytes(transform: &VisualProperties) -> usize {
    point_bytes(&transform.position)
        + keyframe_bytes(&transform.scale)
        + keyframe_bytes(&transform.rotation_degrees)
        + keyframe_bytes(&transform.opacity)
}

fn mask_bytes(mask: &ShapeMask) -> usize {
    size_of::<ShapeMask>() + geometry_bytes(&mask.shape) + keyframe_bytes(&mask.feather)
}

fn point_bytes(point: &AnimatedPoint) -> usize {
    match point {
        AnimatedPoint::Constant { .. } | AnimatedPoint::Data(_) => 0,
        AnimatedPoint::Split { channels } => channel_bytes(channels),
        AnimatedPoint::Path(motion) => {
            keyframe_bytes(&motion.distance)
                + motion.path.vertex_count() * size_of::<alpha2_model::PathVertex>()
        }
        AnimatedPoint::Keyframes { keyframes, .. } => {
            keyframes.len() * size_of::<alpha2_model::PointKeyframe>()
        }
    }
}

fn path_bytes(path: &Animated<alpha2_model::Path>) -> usize {
    let one = |path: &alpha2_model::Path| {
        path.subpaths.len() * size_of::<alpha2_model::Subpath>()
            + path.vertex_count() * size_of::<alpha2_model::PathVertex>()
    };
    match path {
        Animated::Data(_) | Animated::Split { .. } => 0,
        Animated::Constant { value } => one(value),
        Animated::Keyframes { keyframes, .. } => keyframes
            .iter()
            .map(|keyframe| size_of::<Keyframe<alpha2_model::Path>>() + one(&keyframe.value))
            .sum(),
    }
}

fn geometry_bytes(geometry: &alpha2_model::ShapeGeometry) -> usize {
    use alpha2_model::ShapeGeometry;
    match geometry {
        ShapeGeometry::Rectangle(rectangle) => {
            point_bytes(&rectangle.center)
                + keyframe_bytes(&rectangle.size)
                + keyframe_bytes(&rectangle.corner_radius)
                + keyframe_bytes(&rectangle.rotation_degrees)
        }
        ShapeGeometry::Ellipse(ellipse) => {
            point_bytes(&ellipse.center)
                + keyframe_bytes(&ellipse.size)
                + keyframe_bytes(&ellipse.rotation_degrees)
        }
        ShapeGeometry::Polystar(star) => {
            point_bytes(&star.center)
                + keyframe_bytes(&star.points)
                + keyframe_bytes(&star.outer_radius)
                + keyframe_bytes(&star.inner_radius)
                + keyframe_bytes(&star.outer_roundness)
                + keyframe_bytes(&star.inner_roundness)
                + keyframe_bytes(&star.rotation_degrees)
        }
        ShapeGeometry::Path(path) => path_bytes(&path.path),
    }
}

fn paint_bytes(paint: &Paint) -> usize {
    match paint {
        Paint::Solid { .. } => 0,
        Paint::LinearGradient { stops, .. }
        | Paint::RadialGradient { stops, .. }
        | Paint::ConicGradient { stops, .. } => {
            stops.len() * size_of::<alpha2_model::GradientStop>()
        }
    }
}

fn animated_paint_bytes(paint: &Animated<Paint>) -> usize {
    match paint {
        Animated::Data(_) | Animated::Split { .. } => 0,
        Animated::Constant { value } => paint_bytes(value),
        Animated::Keyframes { keyframes, .. } => keyframes
            .iter()
            .map(|keyframe| size_of::<Keyframe<Paint>>() + paint_bytes(&keyframe.value))
            .sum(),
    }
}

/// Approximate bytes a content tree holds. Its plan holds about as much again.
fn shape_items_bytes(items: &[alpha2_model::ShapeItem]) -> usize {
    use alpha2_model::{ShapeGeometry, ShapeItem};
    items
        .iter()
        .map(|item| {
            size_of::<ShapeItem>()
                + match item {
                    ShapeItem::Group { items, transform } => {
                        shape_items_bytes(items)
                            + keyframe_bytes(&transform.anchor)
                            + point_bytes(&transform.position)
                            + keyframe_bytes(&transform.scale)
                            + keyframe_bytes(&transform.rotation_degrees)
                            + keyframe_bytes(&transform.opacity)
                    }
                    ShapeItem::Rectangle(geometry) => {
                        geometry_bytes(&ShapeGeometry::Rectangle(geometry.clone()))
                    }
                    ShapeItem::Ellipse(geometry) => {
                        geometry_bytes(&ShapeGeometry::Ellipse(geometry.clone()))
                    }
                    ShapeItem::Polystar(geometry) => {
                        geometry_bytes(&ShapeGeometry::Polystar(geometry.clone()))
                    }
                    ShapeItem::Path(geometry) => path_bytes(&geometry.path),
                    ShapeItem::Fill { paint, opacity, .. } => {
                        animated_paint_bytes(paint) + keyframe_bytes(opacity)
                    }
                    ShapeItem::Stroke(stroke) => {
                        animated_paint_bytes(&stroke.paint)
                            + keyframe_bytes(&stroke.width)
                            + keyframe_bytes(&stroke.opacity)
                            + stroke.dash.as_ref().map_or(0, |dash| {
                                dash.pattern
                                    .iter()
                                    .map(|entry| size_of::<Animated<f32>>() + keyframe_bytes(entry))
                                    .sum::<usize>()
                                    + keyframe_bytes(&dash.offset)
                            })
                    }
                    ShapeItem::Trim(trim) => {
                        keyframe_bytes(&trim.start)
                            + keyframe_bytes(&trim.end)
                            + keyframe_bytes(&trim.offset)
                    }
                }
        })
        .sum()
}

fn generator_step(generator: Generator, start: MediaTime, canvas: (u32, u32)) -> StepOp {
    let plan = GeneratorPlan::new(&generator, canvas).map(Arc::new);
    StepOp::Generator {
        generator,
        start,
        plan,
    }
}

fn generator_bytes(generator: &Generator) -> usize {
    match generator {
        Generator::Fill { paint } => paint_bytes(paint),
        // Counted twice: the items and their plan.
        Generator::Shapes { items } => 2 * shape_items_bytes(items),
        Generator::Text { text, style } => {
            text.len() + style.font_family.as_ref().map_or(0, String::len)
        }
        // Counted twice: the tree and its plan.
        Generator::Layout { root } => 2 * crate::layout::layout_bytes(root, &shape_items_bytes),
        Generator::Effect { effect } => effect_bytes(effect),
    }
}

/// A node's [`CompositionReads::needed_inputs`] in input order, failing on an unconnected one
/// (named with `prefix`, like every plan error).
fn needed_inputs<'a>(
    reads: &CompositionReads<'_>,
    prefix: &str,
    node: &'a alpha2_model::CompositionNode,
) -> Result<Vec<&'a NodeId>, PlanError> {
    let needed = reads.needed_inputs(node);
    if node.bypass && needed.is_empty() {
        // A merge without layers has nothing to pass through.
        return Err(PlanError::MissingInput {
            node: scoped(prefix, &node.id),
            input: "layers[0]".into(),
        });
    }
    needed
        .into_iter()
        .map(|input| {
            input.node().ok_or_else(|| PlanError::MissingInput {
                node: scoped(prefix, &node.id),
                input: input.name(),
            })
        })
        .collect()
}

/// A clip's compiled composition and how its time maps onto it.
#[derive(Clone, Debug)]
pub(crate) struct IndexedComposition {
    pub(crate) plan: Arc<Result<CompositionPlan, PlanError>>,
    pub(crate) reference: alpha2_model::ClipComposition,
}

/// A clip's composition at one timeline timestamp.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ActiveComposition<'a> {
    plan: &'a CompositionPlan,
    time: MediaTime,
    data: crate::SampleContext<'a>,
    shown_by: Option<ShowingClip<'a>>,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ShowingClip<'a> {
    pub(crate) timeline_range: alpha2_time::TimeRange,
    pub(crate) source_range: alpha2_time::TimeRange,
    pub(crate) time_map: &'a alpha2_model::TimeMap,
    pub(crate) mirror: crate::Mirror,
    pub(crate) scale: alpha2_model::TimeScale,
    pub(crate) timeline_time: MediaTime,
}

impl<'a> ActiveComposition<'a> {
    /// `plan` at composition time `time`, reading no data and shown by no clip, so its shifted
    /// clip steps are transparent.
    #[must_use]
    pub const fn new(plan: &'a CompositionPlan, time: MediaTime) -> Self {
        Self {
            plan,
            time,
            data: crate::SampleContext::NONE,
            shown_by: None,
        }
    }

    pub(crate) const fn shown_by(self, clip: ShowingClip<'a>) -> Self {
        Self {
            shown_by: Some(clip),
            ..self
        }
    }

    /// The same composition reading data through `data`.
    #[must_use]
    pub const fn with_data(self, data: crate::SampleContext<'a>) -> Self {
        Self { data, ..self }
    }

    /// What step `step`'s settings read data through.
    #[must_use]
    pub fn step_data(&self, step: usize) -> crate::SampleContext<'a> {
        self.data.for_step(self.plan, step)
    }

    /// The compiled composition.
    #[must_use]
    pub const fn plan(&self) -> &'a CompositionPlan {
        self.plan
    }

    /// The composition time at which settings are sampled.
    #[must_use]
    pub const fn time(&self) -> MediaTime {
        self.time
    }

    /// Each host-supplied source a step reads, with step index, source time and what the step
    /// shows between two frames.
    pub fn media(
        &self,
    ) -> impl Iterator<
        Item = (
            usize,
            &'a SourceId,
            MediaTime,
            alpha2_model::FrameInterpolation,
        ),
    > + 'a {
        let time = self.time;
        self.plan
            .steps
            .iter()
            .enumerate()
            .filter_map(move |(index, step)| match &step.op {
                StepOp::Media {
                    source_id,
                    start,
                    frame_interpolation,
                } => Some((
                    index,
                    source_id,
                    MediaTime(start.ticks().saturating_add(step.time(time).ticks())),
                    *frame_interpolation,
                )),
                _ => None,
            })
    }

    /// The source time at which a clip step read through offsets adding to `shift` shows the
    /// clip: its picture at the shifted timeline time
    /// ([`alpha2_model::TimeScale::shifted_time`]) through its time map. `None` when that
    /// time is outside the clip, where the step is transparent, and when no clip shows the
    /// composition.
    #[must_use]
    pub fn shifted_clip_time(&self, shift: MediaTime) -> Option<MediaTime> {
        let clip = self.shown_by?;
        let time = clip
            .scale
            .shifted_time(clip.timeline_time, shift)
            .filter(|time| clip.timeline_range.contains(*time))?;
        crate::map_source_time(
            clip.timeline_range,
            clip.source_range,
            clip.time_map,
            clip.mirror,
            time,
        )
    }

    /// Each step that draws the clip at another time, with the source time it shows
    /// ([`Self::shifted_clip_time`]).
    pub fn shifted_clips(&self) -> impl Iterator<Item = (usize, Option<MediaTime>)> + use<'a> {
        let composition = *self;
        self.plan
            .shifted_clips()
            .map(move |(step, shift)| (step, composition.shifted_clip_time(shift)))
    }
}

#[cfg(test)]
#[path = "composition_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "time_offset_tests.rs"]
mod time_offset_tests;