alpha2-model 0.5.0

Versioned project and timeline model for alpha2.
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
//! Composition graphs: a clip's picture built from connected nodes.
//!
//! A [`Composition`] is an acyclic graph of image operations stored once in the project. A
//! clip refers to it with a [`ClipComposition`], which also maps the clip's timeline time to
//! composition time. Every node outputs one image and names the nodes it takes inputs from;
//! inputs may be left unconnected while a graph is being built.
//!
//! A [`NodeOp::Group`] node draws another composition, feeding its [`NodeOp::GroupInput`]
//! nodes and setting its [`CompositionControl`]s per group node. A
//! [`crate::MediaKind::Composition`] source shows one on the timeline or in a media node.
//! Compositions may not use themselves. A composition is inlined wherever it is drawn, so
//! nesting is bounded by [`MAX_COMPOSITION_DEPTH`] and total drawn nodes by
//! [`MAX_INLINED_NODES`].
//!
//! Saving checks structure: names resolve, nothing depends on itself, values are in range.
//! Rendering additionally requires every input reachable from the output to be connected.
//! Nodes that do not reach the output are kept and ignored.

use crate::animation::opaque;
use crate::{
    Animated, ClipBlendMode, ClipEffect, CompositionId, EffectValue, Generator, MatteMode, NodeId,
    ShapeMask, VisualProperties,
};
use alpha2_media::SourceId;
use alpha2_time::MediaTime;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::{HashMap, HashSet};

/// Most compositions in one project.
pub const MAX_COMPOSITIONS: usize = 10_000;
/// Most nodes in one composition.
pub const MAX_COMPOSITION_NODES: usize = 256;
/// The most named inputs an effect node gives its effect, matching what an effect definition
/// may declare.
pub const MAX_EFFECT_INPUTS: usize = 8;
/// Most layers in one merge node.
pub const MAX_MERGE_LAYERS: usize = 32;
/// Most inputs a composition takes as a group.
pub const MAX_GROUP_INPUTS: usize = 16;
/// Most controls a composition exposes as a group.
pub const MAX_COMPOSITION_CONTROLS: usize = 64;
/// Deepest nesting of compositions. A composition that draws no other has depth one; one
/// that draws others (via group nodes or composition-source media nodes) is one deeper than
/// the deepest of them.
pub const MAX_COMPOSITION_DEPTH: usize = 64;
/// Most nodes the project's compositions draw in total. Each node counts one, except a group
/// node or composition-source media node, which counts the nodes of the composition it
/// draws. This bounds compile cost however uses multiply.
pub const MAX_INLINED_NODES: usize = 65_536;
/// Most composition nodes the clips at one instant draw together, each clip counted as
/// [`MAX_INLINED_NODES`] counts its composition and composition source. This bounds per-frame
/// work to one composition of the largest allowed size.
pub const MAX_FRAME_INLINED_NODES: usize = 65_536;

/// An acyclic graph of image operations with one selected output.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Composition {
    /// Stable composition identity.
    pub id: CompositionId,
    /// The graph's nodes. Order has no meaning; a node may name a later node as its input.
    #[serde(default)]
    pub nodes: Vec<CompositionNode>,
    /// The node whose image is the composition's picture. A composition without one saves but
    /// cannot be rendered.
    #[serde(default)]
    pub output: Option<NodeId>,
    /// The images a group node gives it, by name, in port order; its [`NodeOp::GroupInput`]
    /// nodes read them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub inputs: Vec<String>,
    /// The node settings a group node may set, by name.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub controls: Vec<CompositionControl>,
}

/// A node setting a composition exposes to group nodes: an effect or transition parameter of
/// one of its nodes.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CompositionControl {
    /// The name a group node sets it by; unique in the composition.
    pub name: String,
    /// The effect or transition node.
    pub node: NodeId,
    /// The parameter of its effect.
    pub param: String,
}

impl Composition {
    /// Creates an empty composition with no output.
    #[must_use]
    pub const fn new(id: CompositionId) -> Self {
        Self {
            id,
            nodes: Vec::new(),
            output: None,
            inputs: Vec::new(),
            controls: Vec::new(),
        }
    }

    /// The node named `id`.
    #[must_use]
    pub fn node(&self, id: &NodeId) -> Option<&CompositionNode> {
        self.nodes.iter().find(|node| &node.id == id)
    }
}

/// One image operation in a [`Composition`].
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CompositionNode {
    /// Identity, unique within its composition.
    pub id: NodeId,
    /// Whether the node passes its [`NodeOp::bypass_input`] through unchanged. A node without
    /// inputs cannot be bypassed.
    #[serde(default)]
    pub bypass: bool,
    /// What the node does, with its inputs and settings.
    pub op: NodeOp,
}

impl CompositionNode {
    /// Creates a node that is not bypassed.
    #[must_use]
    pub const fn new(id: NodeId, op: NodeOp) -> Self {
        Self {
            id,
            bypass: false,
            op,
        }
    }

    /// The inputs drawing the node reads, in input order: only its [`NodeOp::bypass_input`] when
    /// bypassed (none for a merge without layers), every input otherwise.
    #[must_use]
    pub fn needed_inputs(&self) -> Vec<NodeInput<'_>> {
        if self.bypass {
            return self.op.bypass_input().into_iter().collect();
        }
        self.op.inputs()
    }
}

/// The operation of a [`CompositionNode`].
///
/// Animated settings are keyed in composition time (see [`ClipComposition`]).
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum NodeOp {
    /// The picture of the clip showing the composition: its source at the time-mapped source
    /// time, or what its generated source draws.
    Clip {},
    /// Another visual source, read at `start` plus the composition time. Adds no sound to the
    /// mix.
    Media {
        /// The source; a video, image, or generated source.
        source_id: SourceId,
        /// Source time shown at composition time zero. Non-negative.
        #[serde(default)]
        start: MediaTime,
    },
    /// A picture the engine draws.
    Generator {
        /// What is drawn.
        generator: Generator,
    },
    /// A registered effect: its input plus any named images it samples.
    Effect {
        /// The image the effect processes; a bypassed node passes it through.
        #[serde(default)]
        input: Option<NodeId>,
        /// The images the effect samples besides its input, by the names its definition declares
        /// (`sample_<name>` in its shader); at most [`MAX_EFFECT_INPUTS`]. An undeclared name, or a
        /// declared one left out, fails the frames that draw the node.
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        inputs: BTreeMap<String, Option<NodeId>>,
        /// The versioned effect and its parameters.
        effect: ClipEffect,
    },
    /// A registered two-input transition at an explicit progress.
    Transition {
        /// The image at progress zero.
        #[serde(default)]
        from: Option<NodeId>,
        /// The image at progress one.
        #[serde(default)]
        to: Option<NodeId>,
        /// The versioned transition and its parameters.
        effect: ClipEffect,
        /// Progress through the transition, in `0..=1`.
        progress: Animated<f32>,
    },
    /// The input placed on the canvas by a transform and opacity.
    Transform {
        /// The image placed.
        #[serde(default)]
        input: Option<NodeId>,
        /// Position, anchor, scale, rotation, and opacity.
        #[serde(default)]
        transform: VisualProperties,
    },
    /// Ordered layers composited over transparency.
    Merge {
        /// Layers from bottom to top.
        #[serde(default)]
        layers: Vec<MergeLayer>,
    },
    /// The input kept where a second image says.
    Matte {
        /// The image kept.
        #[serde(default)]
        input: Option<NodeId>,
        /// The image whose alpha or luminance is coverage.
        #[serde(default)]
        matte: Option<NodeId>,
        /// Which property of the matte image is coverage.
        mode: MatteMode,
    },
    /// The input kept inside shapes.
    ShapeMask {
        /// The image masked.
        #[serde(default)]
        input: Option<NodeId>,
        /// The shapes, combined in order; at most [`crate::MAX_CLIP_MASKS`]. Geometry is in the
        /// input image's normalized space.
        masks: Vec<ShapeMask>,
    },
    /// Another composition drawn in this one's time as a group: its output, with group inputs
    /// fed from `inputs` and controls set from `controls`.
    Group {
        /// The composition drawn.
        composition: CompositionId,
        /// The image for each of its inputs, in its port order.
        #[serde(default)]
        inputs: Vec<Option<NodeId>>,
        /// Values for its controls, by name; unset controls keep the composition's own value. Keyed
        /// in composition time.
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        controls: BTreeMap<String, Animated<EffectValue>>,
    },
    /// In a composition used as a group, the image the group node gives its input `index`.
    GroupInput {
        /// The input, in the composition's port order.
        index: u32,
    },
}

/// One layer of a [`NodeOp::Merge`].
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MergeLayer {
    /// The layer's image.
    #[serde(default)]
    pub input: Option<NodeId>,
    /// How the layer blends with the layers under it.
    #[serde(default)]
    pub blend_mode: ClipBlendMode,
    /// The layer's opacity, in `0..=1`.
    #[serde(default = "opaque")]
    pub opacity: Animated<f32>,
}

impl MergeLayer {
    /// An opaque, normally blended layer of `input`.
    #[must_use]
    pub const fn new(input: Option<NodeId>) -> Self {
        Self {
            input,
            blend_mode: ClipBlendMode::Normal,
            opacity: Animated::Constant { value: 1.0 },
        }
    }
}

/// What each composition's output reads: the group inputs and clip nodes reachable from its
/// output, following group nodes into their compositions. A group node needs only the ports
/// its composition reads, so unread ports may be left unconnected.
///
/// Built once per project in dependency order, without recursion. A composition that uses
/// itself (refused by validation) is taken to read every port and draw the clip.
#[derive(Clone, Debug, Default)]
pub struct CompositionReads<'a> {
    read: HashMap<&'a CompositionId, Reads>,
}

/// What one composition's output reads.
#[derive(Clone, Debug)]
struct Reads {
    /// By group input index.
    ports: Vec<bool>,
    /// Whether it draws the picture of the clip showing it.
    clip: bool,
}

impl<'a> CompositionReads<'a> {
    /// What each of `compositions` reads, resolving group nodes by ID.
    #[must_use]
    pub fn new(compositions: &HashMap<&'a CompositionId, &'a Composition>) -> Self {
        let mut reads = Self::default();
        let mut walking = HashSet::new();
        let group = |node: &'a CompositionNode| match &node.op {
            NodeOp::Group { composition, .. } => compositions.get(composition).copied(),
            _ => None,
        };
        for root in compositions.values() {
            let mut stack = vec![(*root, false)];
            while let Some((composition, expanded)) = stack.pop() {
                if reads.read.contains_key(&composition.id) {
                    continue;
                }
                if !expanded {
                    if !walking.insert(&composition.id) {
                        continue;
                    }
                    stack.push((composition, true));
                    stack.extend(
                        composition
                            .nodes
                            .iter()
                            .filter_map(group)
                            .filter(|inner| {
                                !reads.read.contains_key(&inner.id) && !walking.contains(&inner.id)
                            })
                            .map(|inner| (inner, false)),
                    );
                    continue;
                }
                walking.remove(&composition.id);
                let read = reads.walk(composition);
                reads.read.insert(&composition.id, read);
            }
        }
        reads
    }

    /// Whether `composition`'s output reads its group input `port`; true for an unknown
    /// composition.
    #[must_use]
    pub fn reads_port(&self, composition: &CompositionId, port: usize) -> bool {
        self.read
            .get(composition)
            .is_none_or(|read| read.ports.get(port).copied().unwrap_or(false))
    }

    /// Whether `composition`, shown by a clip, draws the clip's picture (its output reaches a
    /// clip node, directly or in a group). True for an unknown composition.
    #[must_use]
    pub fn draws_clip(&self, composition: &CompositionId) -> bool {
        self.read.get(composition).is_none_or(|read| read.clip)
    }

    /// The inputs drawing `node` reads, in input order: its [`CompositionNode::needed_inputs`],
    /// restricted for a group node to the ports its composition reads.
    #[must_use]
    pub fn needed_inputs<'n>(&self, node: &'n CompositionNode) -> Vec<NodeInput<'n>> {
        let mut needed = node.needed_inputs();
        if let (false, NodeOp::Group { composition, .. }) = (node.bypass, &node.op) {
            needed.retain(|input| match input {
                NodeInput::Port(port, _) => self.reads_port(composition, *port),
                _ => true,
            });
        }
        needed
    }

    /// What `composition`'s output reaches, given that its group nodes' compositions are known.
    fn walk(&self, composition: &'a Composition) -> Reads {
        let nodes: HashMap<&NodeId, &CompositionNode> = composition
            .nodes
            .iter()
            .map(|node| (&node.id, node))
            .collect();
        let mut read = Reads {
            ports: vec![false; composition.inputs.len()],
            clip: false,
        };
        let mut reached = HashSet::new();
        let mut pending: Vec<&NodeId> = composition.output.iter().collect();
        while let Some(id) = pending.pop() {
            let Some(node) = nodes.get(id).filter(|_| reached.insert(id)) else {
                continue;
            };
            match (node.bypass, &node.op) {
                (false, NodeOp::GroupInput { index }) => {
                    if let Some(port) = usize::try_from(*index)
                        .ok()
                        .and_then(|index| read.ports.get_mut(index))
                    {
                        *port = true;
                    }
                }
                (false, NodeOp::Clip {}) => read.clip = true,
                (false, NodeOp::Group { composition, .. }) => {
                    read.clip |= self.draws_clip(composition);
                }
                _ => {}
            }
            pending.extend(
                self.needed_inputs(node)
                    .into_iter()
                    .filter_map(NodeInput::node),
            );
        }
        read
    }
}

/// One named input of a node, as a node's inputs are listed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NodeInput<'a> {
    /// A named input: `input`, `from`, `to`, or `matte`.
    Named(&'static str, Option<&'a NodeId>),
    /// The input of a merge layer, by layer index.
    Layer(usize, Option<&'a NodeId>),
    /// An input of a group node, by port index.
    Port(usize, Option<&'a NodeId>),
    /// A named input of an effect node.
    EffectInput(&'a str, Option<&'a NodeId>),
}

impl<'a> NodeInput<'a> {
    /// The connected node, if any.
    #[must_use]
    pub const fn node(self) -> Option<&'a NodeId> {
        match self {
            Self::Named(_, node)
            | Self::Layer(_, node)
            | Self::Port(_, node)
            | Self::EffectInput(_, node) => node,
        }
    }

    /// The input's name as a diagnostic shows it: `input`, `from`, `to`, `matte`, `layers[i]`,
    /// `inputs[i]`, or `inputs.<name>`.
    #[must_use]
    pub fn name(self) -> String {
        match self {
            Self::Named(name, _) => name.to_owned(),
            Self::Layer(index, _) => format!("layers[{index}]"),
            Self::Port(index, _) => format!("inputs[{index}]"),
            Self::EffectInput(name, _) => format!("inputs.{name}"),
        }
    }
}

impl NodeOp {
    /// Every input of the operation, connected or not, in a fixed order.
    #[must_use]
    pub fn inputs(&self) -> Vec<NodeInput<'_>> {
        match self {
            Self::Clip {}
            | Self::Media { .. }
            | Self::Generator { .. }
            | Self::GroupInput { .. } => Vec::new(),
            Self::Group { inputs, .. } => inputs
                .iter()
                .enumerate()
                .map(|(index, input)| NodeInput::Port(index, input.as_ref()))
                .collect(),
            Self::Effect { input, inputs, .. } => {
                std::iter::once(NodeInput::Named("input", input.as_ref()))
                    .chain(
                        inputs
                            .iter()
                            .map(|(name, node)| NodeInput::EffectInput(name, node.as_ref())),
                    )
                    .collect()
            }
            Self::Transform { input, .. } | Self::ShapeMask { input, .. } => {
                vec![NodeInput::Named("input", input.as_ref())]
            }
            Self::Transition { from, to, .. } => vec![
                NodeInput::Named("from", from.as_ref()),
                NodeInput::Named("to", to.as_ref()),
            ],
            Self::Matte { input, matte, .. } => vec![
                NodeInput::Named("input", input.as_ref()),
                NodeInput::Named("matte", matte.as_ref()),
            ],
            Self::Merge { layers } => layers
                .iter()
                .enumerate()
                .map(|(index, layer)| NodeInput::Layer(index, layer.input.as_ref()))
                .collect(),
        }
    }

    /// The input a bypassed node passes through: `input` for one-input operations and mattes,
    /// `from` for a transition, a merge's bottom layer, and a group's first input. `None` for
    /// operations without inputs and merges without layers.
    #[must_use]
    pub fn bypass_input(&self) -> Option<NodeInput<'_>> {
        match self {
            Self::Clip {}
            | Self::Media { .. }
            | Self::Generator { .. }
            | Self::GroupInput { .. } => None,
            Self::Merge { layers } => layers
                .first()
                .map(|layer| NodeInput::Layer(0, layer.input.as_ref())),
            _ => self.inputs().into_iter().next(),
        }
    }

    /// Whether the operation takes inputs, and so can be bypassed.
    #[must_use]
    pub const fn has_inputs(&self) -> bool {
        match self {
            Self::Clip {}
            | Self::Media { .. }
            | Self::Generator { .. }
            | Self::GroupInput { .. } => false,
            Self::Group { inputs, .. } => !inputs.is_empty(),
            _ => true,
        }
    }

    /// The effect or transition invocation the operation runs, if any.
    #[must_use]
    pub const fn effect(&self) -> Option<&ClipEffect> {
        match self {
            Self::Effect { effect, .. } | Self::Transition { effect, .. } => Some(effect),
            _ => None,
        }
    }
}

/// A clip's use of a [`Composition`], and how its time maps onto it.
///
/// Composition time is `offset + (t - clip start) * scale` for timeline time `t`, rounded
/// down to a tick. Moving a clip keeps its offset so the animation moves with it; trimming
/// its start by `d` adds `d * scale` to the offset so the rest stays in place. A negative
/// offset holds settings at their first keyframe and media nodes at their first frame.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ClipComposition {
    /// The composition shown.
    pub id: CompositionId,
    /// Composition time at the clip's start.
    #[serde(default)]
    pub offset: MediaTime,
    /// Composition time per timeline time.
    #[serde(default)]
    pub scale: TimeScale,
}

impl ClipComposition {
    /// Shows `id` from its time zero at the timeline's rate.
    #[must_use]
    pub const fn new(id: CompositionId) -> Self {
        Self {
            id,
            offset: MediaTime::ZERO,
            scale: TimeScale::ONE,
        }
    }

    /// The composition time at timeline time `time` of a clip starting at `clip_start`. `None`
    /// when unrepresentable or the scale has a zero denominator.
    #[must_use]
    pub fn local_time(&self, clip_start: MediaTime, time: MediaTime) -> Option<MediaTime> {
        let elapsed = i128::from(time.ticks()) - i128::from(clip_start.ticks());
        let scaled = (elapsed * i128::from(self.scale.num))
            .checked_div_euclid(i128::from(self.scale.den))?;
        let local = i128::from(self.offset.ticks()).checked_add(scaled)?;
        i64::try_from(local).ok().map(MediaTime)
    }
}

/// A positive rational rate of one time against another.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TimeScale {
    /// Numerator; positive.
    pub num: u32,
    /// Denominator; positive.
    pub den: u32,
}

impl TimeScale {
    /// The same rate.
    pub const ONE: Self = Self { num: 1, den: 1 };

    /// Whether both terms are positive.
    #[must_use]
    pub const fn is_valid(self) -> bool {
        self.num > 0 && self.den > 0
    }
}

impl Default for TimeScale {
    fn default() -> Self {
        Self::ONE
    }
}

/// Checks every composition's identity, node settings and connections, and returns the
/// nodes each draws once inlined. `by_source` maps source IDs for media node lookups.
pub(crate) fn validate_compositions<'a>(
    compositions: &'a [Composition],
    sources: &'a [crate::MediaSource],
    by_source: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
    canvas: (u32, u32),
) -> Result<InlinedNodes<'a>, crate::ModelError> {
    use crate::ModelError;
    use std::collections::{HashMap, HashSet};

    if compositions.len() > MAX_COMPOSITIONS {
        return Err(ModelError::TooManyCompositions {
            found: compositions.len(),
            maximum: MAX_COMPOSITIONS,
        });
    }
    let mut ids = HashSet::with_capacity(compositions.len());
    for composition in compositions {
        if !ids.insert(&composition.id) {
            return Err(ModelError::DuplicateCompositionId(composition.id.clone()));
        }
    }
    let by_id: HashMap<&CompositionId, &Composition> = compositions
        .iter()
        .map(|composition| (&composition.id, composition))
        .collect();
    if let Some(source) = sources.iter().find(|source| {
        source
            .composition
            .as_ref()
            .is_some_and(|id| !by_id.contains_key(id))
    }) {
        return Err(ModelError::InvalidCompositionSource {
            source: source.id.clone(),
        });
    }
    for composition in compositions {
        if composition.nodes.len() > MAX_COMPOSITION_NODES {
            return Err(ModelError::TooManyCompositionNodes {
                composition: composition.id.clone(),
                found: composition.nodes.len(),
                maximum: MAX_COMPOSITION_NODES,
            });
        }
        let mut positions = HashMap::with_capacity(composition.nodes.len());
        for (position, node) in composition.nodes.iter().enumerate() {
            if node.id.as_str().contains('/') {
                return Err(ModelError::InvalidNodeId {
                    composition: composition.id.clone(),
                    node: node.id.clone(),
                });
            }
            if positions.insert(&node.id, position).is_some() {
                return Err(ModelError::DuplicateNodeId {
                    composition: composition.id.clone(),
                    node: node.id.clone(),
                });
            }
        }
        validate_ports(composition, &positions)?;
        for node in &composition.nodes {
            validate_node(
                composition,
                node,
                by_source,
                &by_id,
                effect_resources,
                canvas,
            )?;
            for input in node.op.inputs() {
                if let Some(target) = input.node()
                    && !positions.contains_key(target)
                {
                    return Err(ModelError::UnknownNodeInput {
                        composition: composition.id.clone(),
                        node: node.id.clone(),
                        input: input.name(),
                        target: target.clone(),
                    });
                }
            }
        }
        if let Some(output) = &composition.output
            && !positions.contains_key(output)
        {
            return Err(ModelError::UnknownCompositionOutput {
                composition: composition.id.clone(),
                node: output.clone(),
            });
        }
        if let Some(node) = cycle_member(composition, &positions) {
            return Err(ModelError::CompositionCycle {
                composition: composition.id.clone(),
                node: node.clone(),
            });
        }
    }
    if let Some(composition) = reference_cycle_member(compositions, &by_id, by_source) {
        return Err(ModelError::CompositionUsesItself {
            composition: composition.clone(),
        });
    }
    validate_expansion(compositions, &by_id, sources)
}

/// The nodes each composition draws once inlined, as [`MAX_INLINED_NODES`] counts them.
pub(crate) type InlinedNodes<'a> = std::collections::HashMap<&'a CompositionId, u64>;

/// Checks that compositions nest at most [`MAX_COMPOSITION_DEPTH`] deep and draw at most
/// [`MAX_INLINED_NODES`] nodes, and returns the nodes each draws. One iterative walk in
/// dependency order counts each composition once without risking stack exhaustion.
fn validate_expansion<'a>(
    compositions: &'a [Composition],
    by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
    sources: &'a [crate::MediaSource],
) -> Result<InlinedNodes<'a>, crate::ModelError> {
    use std::collections::HashMap;
    let composition_sources: HashMap<&SourceId, &CompositionId> = sources
        .iter()
        .filter_map(|source| Some((&source.id, source.composition.as_ref()?)))
        .collect();
    // The composition a node draws in its place, if any.
    let draws = |node: &'a CompositionNode| -> Option<&'a CompositionId> {
        match &node.op {
            NodeOp::Group { composition, .. } => Some(composition),
            NodeOp::Media { source_id, .. } => composition_sources.get(source_id).copied(),
            _ => None,
        }
        .filter(|id| by_id.contains_key(id))
    };
    // Depth and inlined node count of each composition walked.
    let mut walked: HashMap<&CompositionId, (usize, u64)> = HashMap::new();
    let mut total = 0_u64;
    for root in compositions {
        let mut stack = vec![(root, false)];
        while let Some((composition, expanded)) = stack.pop() {
            if walked.contains_key(&composition.id) {
                continue;
            }
            if !expanded {
                stack.push((composition, true));
                stack.extend(
                    composition
                        .nodes
                        .iter()
                        .filter_map(draws)
                        .filter(|id| !walked.contains_key(id))
                        .map(|id| (by_id[id], false)),
                );
                continue;
            }
            let mut depth = 1;
            let mut nodes = 0_u64;
            for node in &composition.nodes {
                let (inner, count) = draws(node).map_or((0, 1), |id| walked[id]);
                depth = depth.max(inner + 1);
                nodes = nodes.saturating_add(count);
            }
            walked.insert(&composition.id, (depth, nodes));
        }
        let (depth, nodes) = walked[&root.id];
        if depth > MAX_COMPOSITION_DEPTH {
            return Err(crate::ModelError::CompositionNestedTooDeep {
                composition: root.id.clone(),
                maximum: MAX_COMPOSITION_DEPTH,
            });
        }
        total = total.saturating_add(nodes);
        if total > MAX_INLINED_NODES as u64 {
            return Err(crate::ModelError::TooManyInlinedNodes {
                maximum: MAX_INLINED_NODES,
            });
        }
    }
    Ok(walked
        .into_iter()
        .map(|(id, (_, nodes))| (id, nodes))
        .collect())
}

/// Checks that a composition's group inputs are named, distinct and few enough, and its
/// controls name distinct settings of its effect and transition nodes.
fn validate_ports(
    composition: &Composition,
    positions: &std::collections::HashMap<&NodeId, usize>,
) -> Result<(), crate::ModelError> {
    use std::collections::HashSet;
    let invalid = || crate::ModelError::InvalidCompositionPorts {
        composition: composition.id.clone(),
    };
    let mut names = HashSet::new();
    if composition.inputs.len() > MAX_GROUP_INPUTS
        || composition
            .inputs
            .iter()
            .any(|name| name.is_empty() || !names.insert(name))
    {
        return Err(invalid());
    }
    let mut controls = HashSet::new();
    let mut settings = HashSet::new();
    if composition.controls.len() > MAX_COMPOSITION_CONTROLS {
        return Err(invalid());
    }
    for control in &composition.controls {
        let node = positions
            .get(&control.node)
            .map(|position| &composition.nodes[*position]);
        if control.name.is_empty()
            || control.param.is_empty()
            || !controls.insert(&control.name)
            || !settings.insert((&control.node, &control.param))
            || node.is_none_or(|node| node.op.effect().is_none())
        {
            return Err(invalid());
        }
    }
    Ok(())
}

/// A composition that uses itself through group nodes or composition sources: the first, in
/// document order, that a depth-first walk finds on its own path.
fn reference_cycle_member<'a>(
    compositions: &'a [Composition],
    by_id: &std::collections::HashMap<&'a CompositionId, &'a Composition>,
    sources: &std::collections::HashMap<&SourceId, &'a crate::MediaSource>,
) -> Option<&'a CompositionId> {
    #[derive(Clone, Copy, PartialEq)]
    enum Mark {
        New,
        Open,
        Done,
    }
    let uses = |composition: &'a Composition| -> Vec<&'a CompositionId> {
        composition
            .nodes
            .iter()
            .filter_map(|node| match &node.op {
                NodeOp::Group { composition, .. } => Some(composition),
                NodeOp::Media { source_id, .. } => sources
                    .get(source_id)
                    .and_then(|source| source.composition.as_ref()),
                _ => None,
            })
            .filter(|id| by_id.contains_key(id))
            .collect()
    };
    let mut marks: std::collections::HashMap<&CompositionId, Mark> = compositions
        .iter()
        .map(|composition| (&composition.id, Mark::New))
        .collect();
    for root in compositions {
        if marks[&root.id] != Mark::New {
            continue;
        }
        let mut stack = vec![(&root.id, uses(root), 0_usize)];
        marks.insert(&root.id, Mark::Open);
        while let Some((current, next, at)) = stack.last_mut() {
            let Some(target) = next.get(*at).copied() else {
                marks.insert(current, Mark::Done);
                stack.pop();
                continue;
            };
            *at += 1;
            match marks[target] {
                Mark::Open => return Some(target),
                Mark::New => {
                    marks.insert(target, Mark::Open);
                    stack.push((target, uses(by_id[target]), 0));
                }
                Mark::Done => {}
            }
        }
    }
    None
}

fn shape_error(
    composition: &Composition,
    node: &CompositionNode,
    issue: crate::ShapeIssue,
) -> crate::ModelError {
    crate::ModelError::InvalidShape {
        owner: crate::ShapeOwner::Node {
            composition: composition.id.clone(),
            node: node.id.clone(),
        },
        at: issue.at,
        problem: issue.problem,
    }
}

fn layout_error(
    composition: &Composition,
    node: &CompositionNode,
    issue: crate::LayoutIssue,
) -> crate::ModelError {
    crate::ModelError::InvalidLayout {
        owner: crate::ShapeOwner::Node {
            composition: composition.id.clone(),
            node: node.id.clone(),
        },
        at: issue.at,
        problem: issue.problem,
    }
}

fn validate_node(
    composition: &Composition,
    node: &CompositionNode,
    sources: &std::collections::HashMap<&SourceId, &crate::MediaSource>,
    compositions: &std::collections::HashMap<&CompositionId, &Composition>,
    effect_resources: &std::collections::HashSet<&crate::EffectResourceId>,
    canvas: (u32, u32),
) -> Result<(), crate::ModelError> {
    use crate::ModelError;

    let invalid = || ModelError::InvalidNode {
        composition: composition.id.clone(),
        node: node.id.clone(),
    };
    let unit = |animation: &Animated<f32>| {
        crate::animation::valid_scalar_values(animation, |value| (0.0..=1.0).contains(&value))
    };
    let shape_error = |issue| shape_error(composition, node, issue);
    if node.bypass && !node.op.has_inputs() {
        return Err(invalid());
    }
    let valid = match &node.op {
        NodeOp::Clip {} | NodeOp::Matte { .. } => true,
        NodeOp::Media { source_id, start } => {
            let visual = sources.get(source_id).is_some_and(|source| {
                matches!(
                    source.kind,
                    crate::MediaKind::Video
                        | crate::MediaKind::Image
                        | crate::MediaKind::Generated
                        | crate::MediaKind::Composition
                )
            });
            if !visual {
                return Err(ModelError::InvalidNodeSource {
                    composition: composition.id.clone(),
                    node: node.id.clone(),
                    source: source_id.clone(),
                });
            }
            start.ticks() >= 0
        }
        NodeOp::Generator { generator } => match generator.validate_on(canvas.0, canvas.1) {
            Ok(()) => true,
            Err(crate::GeneratorIssue::Shape(issue)) => return Err(shape_error(issue)),
            Err(crate::GeneratorIssue::Layout(issue)) => {
                return Err(layout_error(composition, node, issue));
            }
            Err(crate::GeneratorIssue::Invalid) => false,
        },
        NodeOp::Effect { effect, inputs, .. } => {
            effect.is_valid()
                && inputs.len() <= MAX_EFFECT_INPUTS
                && inputs
                    .keys()
                    .all(|name| crate::effect::valid_binding_name(name))
        }
        NodeOp::Transition {
            effect, progress, ..
        } => effect.is_valid() && unit(progress),
        NodeOp::Transform { transform, .. } => transform.validate(),
        NodeOp::Merge { layers } => {
            layers.len() <= MAX_MERGE_LAYERS && layers.iter().all(|layer| unit(&layer.opacity))
        }
        NodeOp::ShapeMask { masks, .. } => {
            crate::mask::validate_masks(masks).map_err(shape_error)?;
            masks.len() <= crate::MAX_CLIP_MASKS
        }
        NodeOp::Group {
            composition: target,
            inputs,
            controls,
        } => {
            let Some(target) = compositions.get(target) else {
                return Err(ModelError::UnknownGroupComposition {
                    composition: composition.id.clone(),
                    node: node.id.clone(),
                    target: target.clone(),
                });
            };
            inputs.len() == target.inputs.len()
                && controls.iter().all(|(name, value)| {
                    target.controls.iter().any(|control| &control.name == name)
                        && crate::effect::valid_param(value)
                })
        }
        NodeOp::GroupInput { index } => {
            usize::try_from(*index).is_ok_and(|index| index < composition.inputs.len())
        }
    };
    if !valid {
        return Err(invalid());
    }
    if let Some(effect) = node.op.effect()
        && let Some(resource) = effect
            .resources
            .values()
            .find(|resource| !effect_resources.contains(resource))
    {
        return Err(ModelError::UnknownNodeResource {
            composition: composition.id.clone(),
            node: node.id.clone(),
            resource: resource.clone(),
        });
    }
    Ok(())
}

/// A node on a cycle, if any: the first, in document order, that a depth-first walk finds
/// on its own path.
fn cycle_member<'a>(
    composition: &'a Composition,
    positions: &std::collections::HashMap<&'a NodeId, usize>,
) -> Option<&'a NodeId> {
    #[derive(Clone, Copy, PartialEq)]
    enum Mark {
        New,
        Open,
        Done,
    }
    let nodes = &composition.nodes;
    let mut marks = vec![Mark::New; nodes.len()];
    for root in 0..nodes.len() {
        if marks[root] != Mark::New {
            continue;
        }
        // Each entry is a node and how many of its inputs have been walked.
        let mut stack = vec![(root, 0_usize)];
        marks[root] = Mark::Open;
        while let Some((current, next)) = stack.last_mut() {
            let inputs = nodes[*current].op.inputs();
            let Some(input) = inputs.get(*next) else {
                marks[*current] = Mark::Done;
                stack.pop();
                continue;
            };
            *next += 1;
            let Some(target) = input.node().and_then(|id| positions.get(id)) else {
                continue;
            };
            match marks[*target] {
                Mark::Open => return Some(&nodes[*target].id),
                Mark::New => {
                    marks[*target] = Mark::Open;
                    stack.push((*target, 0));
                }
                Mark::Done => {}
            }
        }
    }
    None
}

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