alpha2-model 0.6.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
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
use crate::{ClipId, CompositionId, DataSetId, EffectProblem, EffectResourceId, NodeId, TrackId};
use alpha2_media::SourceId;
use std::fmt;

/// What holds the shape or layout a [`ModelError::InvalidShape`] or
/// [`ModelError::InvalidLayout`] names.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ShapeOwner {
    /// A generated source's shapes or layout generator.
    Source(SourceId),
    /// A clip's masks.
    Clip(ClipId),
    /// A composition node's shapes or layout generator, or its masks.
    Node {
        /// The composition.
        composition: CompositionId,
        /// The node.
        node: NodeId,
    },
}

impl fmt::Display for ShapeOwner {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Source(source) => write!(formatter, "source {source}"),
            Self::Clip(clip) => write!(formatter, "clip {clip}"),
            Self::Node { composition, node } => {
                write!(formatter, "composition {composition} node {node}")
            }
        }
    }
}

/// What holds the value a [`ModelError::InvalidDataBinding`] names.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataOwner {
    /// A clip's visual, masks or audio.
    Clip(ClipId),
    /// A track's bus or caption track.
    Track(TrackId),
    /// The master bus.
    Master,
    /// A timeline transition's effect.
    Transition {
        /// Its track.
        track: TrackId,
        /// Its first clip.
        from: ClipId,
        /// Its second clip.
        to: ClipId,
    },
    /// A composition node's settings.
    Node {
        /// The composition.
        composition: CompositionId,
        /// The node.
        node: NodeId,
    },
    /// A generated source's tree.
    Source(SourceId),
}

impl fmt::Display for DataOwner {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Clip(clip) => write!(formatter, "clip {clip}"),
            Self::Track(track) => write!(formatter, "track {track}"),
            Self::Master => formatter.write_str("the master bus"),
            Self::Transition { track, from, to } => {
                write!(formatter, "track {track} transition {from} to {to}")
            }
            Self::Node { composition, node } => {
                write!(formatter, "composition {composition} node {node}")
            }
            Self::Source(source) => write!(formatter, "source {source}"),
        }
    }
}

/// What holds the effect a [`ModelError::InvalidEffect`] names.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EffectOwner {
    /// A composition's effect, transition or group node.
    Node {
        /// The composition.
        composition: CompositionId,
        /// The node.
        node: NodeId,
    },
    /// A timeline transition.
    Transition {
        /// Its track.
        track: TrackId,
        /// The clip at progress zero.
        from: ClipId,
        /// The clip at progress one.
        to: ClipId,
    },
}

impl fmt::Display for EffectOwner {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Node { composition, node } => {
                write!(formatter, "composition {composition} node {node}")
            }
            Self::Transition { track, from, to } => {
                write!(
                    formatter,
                    "the transition from {from} to {to} on track {track}"
                )
            }
        }
    }
}

impl fmt::Display for EffectProblem {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownBuiltin => formatter.write_str("is not a built-in"),
            Self::Version { expected } => write!(formatter, "needs version {expected}"),
            Self::Kind => formatter.write_str("is used as the wrong kind"),
            Self::UnknownParam(name) => write!(formatter, "has no parameter {name}"),
            Self::InvalidParam(name) => {
                write!(
                    formatter,
                    "has a parameter {name} of the wrong type or out of range"
                )
            }
            Self::Inputs => formatter.write_str("does not get exactly its declared inputs"),
            Self::Resources => formatter.write_str("does not get exactly its declared resources"),
        }
    }
}

/// A document invariant violation.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ModelError {
    /// This build cannot interpret the document version.
    UnsupportedSchemaVersion {
        /// Version found in the decoded document.
        found: u32,
    },
    /// The project has more than [`crate::MAX_DATA_SETS`] data sets.
    TooManyDataSets {
        /// Data sets in the document.
        found: usize,
        /// Largest accepted count.
        maximum: usize,
    },
    /// Two data sets share one ID.
    DuplicateDataSetId(DataSetId),
    /// A data set breaks a rule of its kind.
    InvalidDataSet {
        /// The data set.
        data: DataSetId,
        /// What is wrong.
        problem: crate::DataProblem,
    },
    /// A data binding, correction or caption words reference is unusable where it sits.
    InvalidDataBinding {
        /// What holds it.
        owner: DataOwner,
        /// The property, like `visual.position`, `masks[0].feather`, `effect.params.radius`,
        /// `visual.correction` or `captions.from_words`.
        at: String,
        /// What is wrong.
        problem: crate::BindingProblem,
    },
    /// At least one ID was empty.
    EmptyIdentifier,
    /// Two sources share one ID.
    DuplicateSourceId(SourceId),
    /// Two effect resources share one ID.
    DuplicateEffectResourceId(EffectResourceId),
    /// Two tracks share one ID.
    DuplicateTrackId(TrackId),
    /// Two clips share one ID.
    DuplicateClipId(ClipId),
    /// A source locator was empty.
    EmptyLocator {
        /// Source whose locator was empty.
        source: SourceId,
    },
    /// A still image source says it has audio, which no image holds.
    AudioOnImage {
        /// The image source.
        source: SourceId,
    },
    /// A source's provider does not fit it (wrong source kind, audio, or incoherent settings),
    /// or a generated source has one.
    InvalidProvider {
        /// The source.
        source: SourceId,
    },
    /// A source's fingerprint is malformed, or a generated source has one.
    InvalidFingerprint {
        /// The source.
        source: SourceId,
    },
    /// A source declares a color whose dynamic range contradicts its transfer (HDR is exactly a
    /// PQ or HLG transfer).
    ContradictoryColor {
        /// The source.
        source: SourceId,
    },
    /// A generated source has no valid generator, or has a locator, color metadata or audio; or
    /// another source has a generator.
    InvalidGenerator {
        /// The source.
        source: SourceId,
    },
    /// A shapes content tree or mask outline breaks a limit, has a value out of range, or has
    /// keyframes that cannot interpolate.
    InvalidShape {
        /// What holds the shape.
        owner: ShapeOwner,
        /// Where the problem lies, like `items[2].items[0].path` or `masks[1].shape.size`.
        at: String,
        /// What is wrong there.
        problem: crate::ShapeProblem,
    },
    /// A layout tree breaks a limit or structure rule, has a value out of range, or has
    /// keyframes that cannot interpolate.
    InvalidLayout {
        /// What holds the layout.
        owner: ShapeOwner,
        /// Where in it the problem lies, like `root.children[2].padding`.
        at: String,
        /// What is wrong there.
        problem: crate::LayoutProblem,
    },
    /// An effect resource locator was empty.
    EmptyEffectResourceLocator {
        /// Resource whose locator was empty.
        resource: EffectResourceId,
    },
    /// A clip effect references an absent effect resource.
    UnknownEffectResource {
        /// Clip containing the reference.
        clip: ClipId,
        /// Missing resource identity.
        resource: EffectResourceId,
    },
    /// A clip has an empty source or timeline range.
    EmptyClipRange {
        /// Clip with an empty range.
        clip: ClipId,
    },
    /// A clip starts before the project or source timeline origin.
    NegativeClipRange {
        /// Clip with a negative range start.
        clip: ClipId,
    },
    /// Two clips overlap without one transition covering their intersection.
    OverlappingClips {
        /// Track containing the overlap.
        track: TrackId,
        /// First overlapping clip.
        first: ClipId,
        /// Second overlapping clip.
        second: ClipId,
    },
    /// A clip refers to an absent source.
    UnknownClipSource {
        /// Clip containing the absent source reference.
        clip: ClipId,
        /// Referenced source that was not in the project.
        source: SourceId,
    },
    /// A source cannot be placed on the selected track kind.
    IncompatibleClipSource {
        /// Clip containing the incompatible reference.
        clip: ClipId,
        /// Track that cannot accept the source kind.
        track: TrackId,
        /// Source with the incompatible kind.
        source: SourceId,
    },
    /// A visual clip has non-finite values, invalid opacity, or unordered keyframes.
    InvalidVisualProperties {
        /// Clip containing the invalid presentation data.
        clip: ClipId,
    },
    /// A clip has an invalid gain, pan, fade, or audio effect parameter.
    InvalidAudioProperties {
        /// Clip containing the invalid audio data.
        clip: ClipId,
    },
    /// A track bus has an invalid gain, pan, effect, or ducking parameter.
    InvalidTrackAudio {
        /// Track containing the invalid bus data.
        track: TrackId,
    },
    /// The project master bus has an invalid gain, effect, or limiter parameter.
    InvalidMasterAudio,
    /// A ducking sidechain names a missing track, itself, or forms a cycle.
    InvalidDuckingSidechain {
        /// Track whose ducking reference is unusable.
        track: TrackId,
        /// Referenced sidechain track.
        sidechain: TrackId,
    },
    /// A clip names an absent composition.
    UnknownComposition {
        /// The clip.
        clip: ClipId,
        /// The composition it names.
        composition: CompositionId,
    },
    /// A clip's composition has a non-positive scale, reaches a composition time past
    /// [`alpha2_time::MAX_SERIALIZED_TICKS`] before the clip ends, or is on an audio clip.
    InvalidClipComposition {
        /// The clip.
        clip: ClipId,
    },
    /// Two compositions share one ID.
    DuplicateCompositionId(CompositionId),
    /// A node ID contains `/`, which is reserved for joining the IDs of inlined group and media
    /// nodes.
    InvalidNodeId {
        /// The composition.
        composition: CompositionId,
        /// The node ID.
        node: NodeId,
    },
    /// Two nodes of one composition share an ID.
    DuplicateNodeId {
        /// The composition.
        composition: CompositionId,
        /// The repeated node ID.
        node: NodeId,
    },
    /// A composition has more nodes than the renderer will schedule.
    TooManyCompositionNodes {
        /// The composition.
        composition: CompositionId,
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// A node has an invalid setting: effect identity, version, parameter or value; transform,
    /// progress, opacity or mask out of range; too many merge layers or masks; or a bypass on a
    /// node without inputs.
    InvalidNode {
        /// The composition.
        composition: CompositionId,
        /// The node.
        node: NodeId,
    },
    /// A node input names a node its composition does not have.
    UnknownNodeInput {
        /// The composition.
        composition: CompositionId,
        /// The node whose input it is.
        node: NodeId,
        /// The input: `input`, `from`, `to`, `matte`, `layers[i]`, or `inputs[i]`.
        input: String,
        /// The node named.
        target: NodeId,
    },
    /// A node depends on its own output.
    CompositionCycle {
        /// The composition.
        composition: CompositionId,
        /// A node on the cycle.
        node: NodeId,
    },
    /// A composition's output names a node it does not have.
    UnknownCompositionOutput {
        /// The composition.
        composition: CompositionId,
        /// The node named.
        node: NodeId,
    },
    /// A media node names an absent source or one that is not visual.
    InvalidNodeSource {
        /// The composition.
        composition: CompositionId,
        /// The node.
        node: NodeId,
        /// The source named.
        source: SourceId,
    },
    /// A composition's group inputs are unnamed, repeated or too many, or a control names no
    /// effect setting of its nodes or repeats one.
    InvalidCompositionPorts {
        /// The composition.
        composition: CompositionId,
    },
    /// A group node names an absent composition.
    UnknownGroupComposition {
        /// The composition holding the group node.
        composition: CompositionId,
        /// The group node.
        node: NodeId,
        /// The composition it names.
        target: CompositionId,
    },
    /// A composition uses itself through group nodes or composition sources.
    CompositionUsesItself {
        /// A composition on the loop.
        composition: CompositionId,
    },
    /// Compositions nest, through group nodes or composition sources, more than
    /// [`crate::MAX_COMPOSITION_DEPTH`] deep.
    CompositionNestedTooDeep {
        /// The first such composition, in document order.
        composition: CompositionId,
        /// Deepest supported nesting.
        maximum: usize,
    },
    /// The compositions draw more than [`crate::MAX_INLINED_NODES`] nodes, counting each group
    /// node and composition-source media node as the nodes it draws.
    TooManyInlinedNodes {
        /// Largest supported count.
        maximum: usize,
    },
    /// The clips at one instant draw more than [`crate::MAX_FRAME_INLINED_NODES`] composition
    /// nodes together.
    FrameDrawsTooManyNodes {
        /// The first clip, in document order, starting at the first such instant.
        clip: ClipId,
        /// The nodes the clips at that instant draw.
        found: u64,
        /// Largest supported count.
        maximum: usize,
    },
    /// A composition source names an absent composition, or has what only a host-supplied
    /// source has.
    InvalidCompositionSource {
        /// The source.
        source: SourceId,
    },
    /// An effect or transition under [`crate::BUILTIN_EFFECT_PREFIX`] that does not match its
    /// built-in definition.
    InvalidEffect {
        /// Where it is used.
        owner: Box<EffectOwner>,
        /// The effect id.
        id: String,
        /// How it fails its definition.
        problem: EffectProblem,
    },
    /// A node's effect references an absent effect resource.
    UnknownNodeResource {
        /// The composition.
        composition: CompositionId,
        /// The node.
        node: NodeId,
        /// The resource named.
        resource: EffectResourceId,
    },
    /// A clip has more than [`crate::MAX_CLIP_MASKS`] masks, a mask with a negative or
    /// non-finite value, or masks on an audio track.
    InvalidClipMask {
        /// Clip carrying the invalid mask.
        clip: ClipId,
    },
    /// A caption track has no captions, has clips or transitions, or has invalid cues or style;
    /// or another track has captions.
    InvalidCaptions {
        /// The track.
        track: TrackId,
    },
    /// A caption cue names a style its track does not have.
    UnknownCaptionStyle {
        /// The track.
        track: TrackId,
        /// The cue's position among the track's cues.
        cue: usize,
        /// The style it names.
        name: String,
    },
    /// A caption cue's style (its track's with the cue's patch applied) is out of range.
    InvalidCaptionCueStyle {
        /// The track.
        track: TrackId,
        /// The cue's position among the track's cues.
        cue: usize,
    },
    /// A clip freezes on an instant outside its source range.
    InvalidTimeMap {
        /// The clip.
        clip: ClipId,
    },
    /// A looping clip makes more than [`crate::MAX_LOOP_PASSES`] passes.
    TooManyLoopPasses {
        /// The clip.
        clip: ClipId,
        /// Its passes, rounded up.
        found: u64,
        /// The most passes a clip makes.
        maximum: u64,
    },
    /// A clip's matte names no visual clip, itself, a clip with its own matte, or a clip in a
    /// transition; or an audio clip has a matte.
    InvalidMatte {
        /// Clip whose matte is invalid.
        clip: ClipId,
    },
    /// A transition is not contained in two distinct visual clips on its track.
    InvalidClipTransition {
        /// Track containing the invalid transition.
        track: TrackId,
    },
    /// Transitions active at one instant lead from clip to clip in a circle, leaving no clip to
    /// show.
    TransitionCycle {
        /// Track containing the transitions.
        track: TrackId,
        /// An instant they are all active.
        at: alpha2_time::MediaTime,
    },
    /// Two clips have more than one transition between them, in either direction.
    DuplicateTransition {
        /// Track containing the transitions.
        track: TrackId,
        /// The transition's first clip.
        first: ClipId,
        /// The transition's second clip.
        second: ClipId,
    },
    /// A caption track derives more than [`crate::MAX_DERIVED_CUES`] cues from its words, or maps
    /// more than [`crate::MAX_DATA_WORDS`] words through its clips.
    TooManyDerivedCues {
        /// The caption track.
        track: TrackId,
    },
    /// A time lies past [`alpha2_time::MAX_SERIALIZED_TICKS`] either way, which no document holds.
    UnwritableTime {
        /// The time, in ticks.
        ticks: i64,
    },
    /// The project has more than [`crate::MAX_EFFECT_RESOURCES`] effect resources.
    TooManyEffectResources {
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// The project contains too many compositions.
    TooManyCompositions {
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// The source table exceeds the bounded project resource budget.
    TooManySources {
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// The timeline contains too many tracks.
    TooManyTracks {
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// The timeline contains too many clips in total.
    TooManyClips {
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// More audio effects hold state at once than [`crate::MAX_AUDIO_EFFECTS`] (see
    /// [`crate::Project::audio_effect_load`]).
    TooManyAudioEffects {
        /// The most effects holding state at once.
        found: usize,
        /// Largest supported count.
        maximum: usize,
        /// The earliest timeline position, in ticks, at which `found` hold state.
        at_ticks: i64,
    },
    /// The audio effects hold more than [`crate::MAX_AUDIO_DELAY_MS`] of delay at once (see
    /// [`crate::Project::audio_effect_load`]).
    TooMuchAudioDelay {
        /// The most milliseconds held at once, rounded up.
        found_ms: u64,
        /// Largest supported total.
        maximum_ms: u32,
        /// The earliest timeline position, in ticks, at which `found_ms` is held.
        at_ticks: i64,
    },
    /// One track contains too many clips.
    TooManyClipsOnTrack {
        /// Track containing the excessive clip list.
        track: TrackId,
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// A caption track holds more than [`crate::MAX_CLIPS_PER_TRACK`] cues.
    TooManyCaptionCues {
        /// The caption track.
        track: TrackId,
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// One track contains too many transitions.
    TooManyTransitions {
        /// Track containing the excessive transition list.
        track: TrackId,
        /// Number supplied by the document.
        found: usize,
        /// Largest supported count.
        maximum: usize,
    },
    /// Width or height was zero.
    ZeroCanvasDimension,
    /// A canvas edge exceeds the portable GPU-independent limit.
    CanvasDimensionTooLarge {
        /// Supplied width.
        width: u32,
        /// Supplied height.
        height: u32,
        /// Largest supported edge.
        maximum: u32,
    },
    /// The canvas area exceeds the bounded pixel budget.
    CanvasPixelBudgetExceeded {
        /// Supplied pixel area.
        pixels: u64,
        /// Largest supported pixel area.
        maximum: u64,
    },
    /// A background component is non-finite or outside `0..=1`.
    InvalidBackground,
    /// The color pipeline's HDR peak is outside [`crate::HDR_PEAK_NITS_RANGE`].
    InvalidColorPipeline,
    /// The project sample rate is outside the supported DSP interval.
    UnsupportedSampleRate {
        /// Supplied rate.
        found: u32,
        /// Smallest supported rate.
        minimum: u32,
        /// Largest supported rate.
        maximum: u32,
    },
}

/// The document object a [`ModelError`] is about, by id.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorSubject<'a> {
    /// A timeline clip.
    Clip(&'a ClipId),
    /// A media source.
    Source(&'a SourceId),
    /// A track.
    Track(&'a TrackId),
    /// A composition.
    Composition(&'a CompositionId),
    /// A data set.
    DataSet(&'a DataSetId),
    /// An effect resource.
    EffectResource(&'a EffectResourceId),
}

impl ModelError {
    /// The document object this error is about, or `None` for one about the whole project.
    ///
    /// An overlap names its second clip, a duplicate transition its track.
    #[must_use]
    pub const fn subject(&self) -> Option<ErrorSubject<'_>> {
        use ErrorSubject::{Clip, Composition, DataSet, EffectResource, Source, Track};
        Some(match self {
            Self::UnsupportedSchemaVersion { .. }
            | Self::TooManyDataSets { .. }
            | Self::EmptyIdentifier
            | Self::InvalidMasterAudio
            | Self::TooManyInlinedNodes { .. }
            | Self::TooManyCompositions { .. }
            | Self::TooManyEffectResources { .. }
            | Self::UnwritableTime { .. }
            | Self::TooManySources { .. }
            | Self::TooManyTracks { .. }
            | Self::TooManyClips { .. }
            | Self::TooManyAudioEffects { .. }
            | Self::TooMuchAudioDelay { .. }
            | Self::ZeroCanvasDimension
            | Self::CanvasDimensionTooLarge { .. }
            | Self::CanvasPixelBudgetExceeded { .. }
            | Self::InvalidBackground
            | Self::InvalidColorPipeline
            | Self::UnsupportedSampleRate { .. } => return None,
            Self::DuplicateDataSetId(data) | Self::InvalidDataSet { data, .. } => DataSet(data),
            Self::InvalidDataBinding { owner, .. } => match owner {
                DataOwner::Clip(clip) | DataOwner::Transition { from: clip, .. } => Clip(clip),
                DataOwner::Track(track) => Track(track),
                DataOwner::Master => return None,
                DataOwner::Node { composition, .. } => Composition(composition),
                DataOwner::Source(source) => Source(source),
            },
            Self::InvalidShape { owner, .. } | Self::InvalidLayout { owner, .. } => match owner {
                ShapeOwner::Source(source) => Source(source),
                ShapeOwner::Clip(clip) => Clip(clip),
                ShapeOwner::Node { composition, .. } => Composition(composition),
            },
            Self::InvalidEffect { owner, .. } => match &**owner {
                EffectOwner::Node { composition, .. } => Composition(composition),
                EffectOwner::Transition { from, .. } => Clip(from),
            },
            Self::DuplicateSourceId(source)
            | Self::EmptyLocator { source }
            | Self::AudioOnImage { source }
            | Self::InvalidProvider { source }
            | Self::InvalidFingerprint { source }
            | Self::ContradictoryColor { source }
            | Self::InvalidGenerator { source }
            | Self::InvalidCompositionSource { source } => Source(source),
            Self::DuplicateEffectResourceId(resource)
            | Self::EmptyEffectResourceLocator { resource } => EffectResource(resource),
            Self::DuplicateTrackId(track)
            | Self::InvalidTrackAudio { track }
            | Self::InvalidDuckingSidechain { track, .. }
            | Self::InvalidCaptions { track }
            | Self::UnknownCaptionStyle { track, .. }
            | Self::InvalidCaptionCueStyle { track, .. }
            | Self::InvalidClipTransition { track }
            | Self::TransitionCycle { track, .. }
            | Self::DuplicateTransition { track, .. }
            | Self::TooManyClipsOnTrack { track, .. }
            | Self::TooManyCaptionCues { track, .. }
            | Self::TooManyDerivedCues { track }
            | Self::TooManyTransitions { track, .. } => Track(track),
            Self::DuplicateClipId(clip)
            | Self::UnknownEffectResource { clip, .. }
            | Self::EmptyClipRange { clip }
            | Self::NegativeClipRange { clip }
            | Self::OverlappingClips { second: clip, .. }
            | Self::UnknownClipSource { clip, .. }
            | Self::IncompatibleClipSource { clip, .. }
            | Self::InvalidVisualProperties { clip }
            | Self::InvalidAudioProperties { clip }
            | Self::UnknownComposition { clip, .. }
            | Self::InvalidClipComposition { clip }
            | Self::FrameDrawsTooManyNodes { clip, .. }
            | Self::InvalidClipMask { clip }
            | Self::InvalidTimeMap { clip }
            | Self::TooManyLoopPasses { clip, .. }
            | Self::InvalidMatte { clip } => Clip(clip),
            Self::DuplicateCompositionId(composition)
            | Self::InvalidNodeId { composition, .. }
            | Self::DuplicateNodeId { composition, .. }
            | Self::TooManyCompositionNodes { composition, .. }
            | Self::InvalidNode { composition, .. }
            | Self::UnknownNodeInput { composition, .. }
            | Self::CompositionCycle { composition, .. }
            | Self::UnknownCompositionOutput { composition, .. }
            | Self::InvalidNodeSource { composition, .. }
            | Self::InvalidCompositionPorts { composition }
            | Self::UnknownGroupComposition { composition, .. }
            | Self::CompositionUsesItself { composition }
            | Self::CompositionNestedTooDeep { composition, .. }
            | Self::UnknownNodeResource { composition, .. } => Composition(composition),
        })
    }
}

impl fmt::Display for ModelError {
    #[allow(clippy::too_many_lines)]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedSchemaVersion { found } => {
                write!(formatter, "unsupported schema version {found}")
            }
            Self::EmptyIdentifier => formatter.write_str("document contains an empty identifier"),
            Self::DuplicateSourceId(id) => write!(formatter, "duplicate source ID {id}"),
            Self::DuplicateEffectResourceId(id) => {
                write!(formatter, "duplicate effect resource ID {id}")
            }
            Self::DuplicateTrackId(id) => write!(formatter, "duplicate track ID {id}"),
            Self::DuplicateClipId(id) => write!(formatter, "duplicate clip ID {id}"),
            Self::EmptyLocator { source } => {
                write!(formatter, "source {source} has an empty locator")
            }
            Self::AudioOnImage { source } => {
                write!(
                    formatter,
                    "source {source} is a still image and has no audio"
                )
            }
            Self::InvalidGenerator { source } => {
                write!(formatter, "source {source} has an invalid generator")
            }
            Self::InvalidShape { owner, at, problem } => {
                write!(formatter, "{owner} has an invalid shape: {at} {problem}")
            }
            Self::InvalidLayout { owner, at, problem } => {
                write!(formatter, "{owner} has an invalid layout: {at} {problem}")
            }
            Self::ContradictoryColor { source } => write!(
                formatter,
                "source {source} declares a dynamic range its transfer contradicts"
            ),
            Self::InvalidFingerprint { source } => {
                write!(formatter, "source {source} has an invalid fingerprint")
            }
            Self::InvalidProvider { source } => {
                write!(formatter, "source {source} has an invalid provider")
            }
            Self::EmptyEffectResourceLocator { resource } => {
                write!(formatter, "effect resource {resource} has an empty locator")
            }
            Self::UnknownEffectResource { clip, resource } => {
                write!(
                    formatter,
                    "clip {clip} references unknown effect resource {resource}"
                )
            }
            Self::EmptyClipRange { clip } => write!(formatter, "clip {clip} has an empty range"),
            Self::NegativeClipRange { clip } => {
                write!(formatter, "clip {clip} has a range before timeline origin")
            }
            Self::OverlappingClips {
                track,
                first,
                second,
            } => write!(
                formatter,
                "clips {first} and {second} overlap without a covering transition on track {track}"
            ),
            Self::UnknownClipSource { clip, source } => {
                write!(formatter, "clip {clip} references unknown source {source}")
            }
            Self::IncompatibleClipSource {
                clip,
                track,
                source,
            } => {
                write!(
                    formatter,
                    "clip {clip} cannot use source {source} on track {track}"
                )
            }
            Self::InvalidVisualProperties { clip } => {
                write!(formatter, "clip {clip} has invalid visual properties")
            }
            Self::InvalidAudioProperties { clip } => {
                write!(formatter, "clip {clip} has invalid audio properties")
            }
            Self::InvalidTrackAudio { track } => {
                write!(formatter, "track {track} has invalid audio bus settings")
            }
            Self::InvalidMasterAudio => {
                write!(formatter, "the project master bus is invalid")
            }
            Self::InvalidDuckingSidechain { track, sidechain } => write!(
                formatter,
                "track {track} cannot duck from sidechain track {sidechain}"
            ),
            Self::UnknownComposition { clip, composition } => {
                write!(
                    formatter,
                    "clip {clip} references unknown composition {composition}"
                )
            }
            Self::InvalidClipComposition { clip } => {
                write!(
                    formatter,
                    "clip {clip} has an invalid composition reference"
                )
            }
            Self::DuplicateCompositionId(id) => write!(formatter, "duplicate composition ID {id}"),
            Self::InvalidNodeId { composition, node } => {
                write!(
                    formatter,
                    "composition {composition} has node ID {node}, which has a `/`"
                )
            }
            Self::DuplicateNodeId { composition, node } => {
                write!(
                    formatter,
                    "composition {composition} has duplicate node ID {node}"
                )
            }
            Self::TooManyCompositionNodes {
                composition,
                found,
                maximum,
            } => write!(
                formatter,
                "composition {composition} has {found} nodes; the maximum is {maximum}"
            ),
            Self::InvalidNode { composition, node } => {
                write!(
                    formatter,
                    "node {node} of composition {composition} has an invalid setting"
                )
            }
            Self::UnknownNodeInput {
                composition,
                node,
                input,
                target,
            } => write!(
                formatter,
                "input {input} of node {node} in composition {composition} names unknown node {target}"
            ),
            Self::CompositionCycle { composition, node } => write!(
                formatter,
                "node {node} of composition {composition} depends on its own output"
            ),
            Self::UnknownCompositionOutput { composition, node } => write!(
                formatter,
                "composition {composition} outputs unknown node {node}"
            ),
            Self::InvalidNodeSource {
                composition,
                node,
                source,
            } => write!(
                formatter,
                "node {node} of composition {composition} cannot show source {source}"
            ),
            Self::InvalidCompositionPorts { composition } => write!(
                formatter,
                "composition {composition} has invalid group inputs or controls"
            ),
            Self::UnknownGroupComposition {
                composition,
                node,
                target,
            } => write!(
                formatter,
                "group node {node} of composition {composition} names unknown composition {target}"
            ),
            Self::CompositionUsesItself { composition } => {
                write!(formatter, "composition {composition} uses itself")
            }
            Self::CompositionNestedTooDeep {
                composition,
                maximum,
            } => write!(
                formatter,
                "composition {composition} nests compositions more than {maximum} deep"
            ),
            Self::TooManyInlinedNodes { maximum } => write!(
                formatter,
                "compositions draw more than {maximum} nodes, counting each group and composition source as the nodes it draws"
            ),
            Self::FrameDrawsTooManyNodes {
                clip,
                found,
                maximum,
            } => write!(
                formatter,
                "the clips on the timeline where clip {clip} starts draw {found} composition nodes; a frame draws at most {maximum}"
            ),
            Self::InvalidCompositionSource { source } => {
                write!(
                    formatter,
                    "source {source} is not a valid composition source"
                )
            }
            Self::InvalidEffect { owner, id, problem } => {
                write!(formatter, "effect {id} in {owner} {problem}")
            }
            Self::UnknownNodeResource {
                composition,
                node,
                resource,
            } => write!(
                formatter,
                "node {node} of composition {composition} references unknown effect resource {resource}"
            ),
            Self::InvalidClipMask { clip } => write!(formatter, "clip {clip} has an invalid mask"),
            Self::InvalidMatte { clip } => write!(formatter, "clip {clip} has an invalid matte"),
            Self::InvalidCaptions { track } => {
                write!(formatter, "track {track} has invalid captions")
            }
            Self::UnknownCaptionStyle { track, cue, name } => write!(
                formatter,
                "cue {cue} of track {track} names style {name:?}, which the track does not have"
            ),
            Self::InvalidCaptionCueStyle { track, cue } => write!(
                formatter,
                "cue {cue} of track {track} has a style out of range once its patch is applied"
            ),
            Self::InvalidTimeMap { clip } => {
                write!(formatter, "clip {clip} freezes outside its source range")
            }
            Self::TooManyLoopPasses {
                clip,
                found,
                maximum,
            } => write!(
                formatter,
                "clip {clip} loops {found} times; the maximum is {maximum}"
            ),
            Self::InvalidClipTransition { track } => {
                write!(formatter, "track {track} has an invalid clip transition")
            }
            Self::TransitionCycle { track, at } => write!(
                formatter,
                "transitions on track {track} active at {} ticks lead from clip to clip in a circle",
                at.ticks()
            ),
            Self::DuplicateTransition {
                track,
                first,
                second,
            } => write!(
                formatter,
                "clips {first} and {second} have more than one transition on track {track}"
            ),
            Self::TooManyDerivedCues { track } => write!(
                formatter,
                "track {track} derives more than {} caption cues or maps more than {} words",
                crate::MAX_DERIVED_CUES,
                crate::MAX_DATA_WORDS
            ),
            Self::UnwritableTime { ticks } => write!(
                formatter,
                "a time of {ticks} ticks is beyond {} either way",
                alpha2_time::MAX_SERIALIZED_TICKS
            ),
            Self::TooManyEffectResources { found, maximum } => write!(
                formatter,
                "project has {found} effect resources; the maximum is {maximum}"
            ),
            Self::TooManyCompositions { found, maximum } => write!(
                formatter,
                "project has {found} compositions; the maximum is {maximum}"
            ),
            Self::TooManySources { found, maximum } => {
                write!(
                    formatter,
                    "project has {found} sources; the maximum is {maximum}"
                )
            }
            Self::TooManyTracks { found, maximum } => {
                write!(
                    formatter,
                    "project has {found} tracks; the maximum is {maximum}"
                )
            }
            Self::TooManyClips { found, maximum } => {
                write!(
                    formatter,
                    "project has {found} clips; the maximum is {maximum}"
                )
            }
            Self::TooManyAudioEffects {
                found,
                maximum,
                at_ticks,
            } => write!(
                formatter,
                "project has {found} audio effects holding state at tick {at_ticks}; the maximum at once is {maximum}"
            ),
            Self::TooMuchAudioDelay {
                found_ms,
                maximum_ms,
                at_ticks,
            } => write!(
                formatter,
                "project audio effects hold {found_ms} ms of delay at tick {at_ticks}; the maximum at once is {maximum_ms} ms"
            ),
            Self::TooManyClipsOnTrack {
                track,
                found,
                maximum,
            } => write!(
                formatter,
                "track {track} has {found} clips; the maximum is {maximum}"
            ),
            Self::TooManyCaptionCues {
                track,
                found,
                maximum,
            } => write!(
                formatter,
                "track {track} has {found} caption cues; the maximum is {maximum}"
            ),
            Self::TooManyTransitions {
                track,
                found,
                maximum,
            } => write!(
                formatter,
                "track {track} has {found} transitions; the maximum is {maximum}"
            ),
            Self::ZeroCanvasDimension => formatter.write_str("canvas dimensions must be positive"),
            Self::CanvasDimensionTooLarge {
                width,
                height,
                maximum,
            } => write!(
                formatter,
                "canvas {width}x{height} exceeds the maximum edge {maximum}"
            ),
            Self::CanvasPixelBudgetExceeded { pixels, maximum } => write!(
                formatter,
                "canvas has {pixels} pixels; the maximum is {maximum}"
            ),
            Self::InvalidBackground => {
                formatter.write_str("background color components must be finite and within 0..=1")
            }
            Self::InvalidColorPipeline => {
                formatter.write_str("the HDR peak must be within 100..=10000 nits")
            }
            Self::TooManyDataSets { found, maximum } => write!(
                formatter,
                "project has {found} data sets; the maximum is {maximum}"
            ),
            Self::DuplicateDataSetId(data) => write!(formatter, "duplicate data set id {data}"),
            Self::InvalidDataSet { data, problem } => {
                write!(formatter, "data set {data} {problem}")
            }
            Self::InvalidDataBinding { owner, at, problem } => {
                write!(formatter, "{owner} {at} {problem}")
            }
            Self::UnsupportedSampleRate {
                found,
                minimum,
                maximum,
            } => write!(
                formatter,
                "sample rate {found} is outside {minimum}..={maximum}"
            ),
        }
    }
}

impl std::error::Error for ModelError {}

/// Failure while decoding a serialized project document.
#[derive(Debug)]
#[non_exhaustive]
pub enum ProjectLoadError {
    /// The JSON input exceeded the parser byte budget.
    TooLarge {
        /// Supplied UTF-8 byte length.
        bytes: usize,
        /// Largest accepted byte length.
        maximum: usize,
    },
    /// JSON syntax or shape was invalid.
    Json(serde_json::Error),
    /// The decoded document violated a model invariant.
    InvalidProject(ModelError),
}

impl fmt::Display for ProjectLoadError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooLarge { bytes, maximum } => {
                write!(
                    formatter,
                    "project JSON is {bytes} bytes; the maximum is {maximum}"
                )
            }
            Self::Json(error) => write!(formatter, "invalid project JSON: {error}"),
            Self::InvalidProject(error) => write!(formatter, "invalid project: {error}"),
        }
    }
}

impl std::error::Error for ProjectLoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::TooLarge { .. } => None,
            Self::Json(error) => Some(error),
            Self::InvalidProject(error) => Some(error),
        }
    }
}

/// Why [`crate::Project::to_json`] wrote no document.
#[derive(Debug)]
#[non_exhaustive]
pub enum ProjectWriteError {
    /// The document would be longer than any loader accepts.
    TooLarge {
        /// Largest accepted byte length, which the document passes.
        maximum: usize,
    },
    /// Serialization failed.
    Json(serde_json::Error),
}

impl fmt::Display for ProjectWriteError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooLarge { maximum } => write!(
                formatter,
                "the project JSON would be longer than {maximum} bytes, the maximum a project loads with"
            ),
            Self::Json(error) => write!(formatter, "the project does not serialize: {error}"),
        }
    }
}

impl std::error::Error for ProjectWriteError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::TooLarge { .. } => None,
            Self::Json(error) => Some(error),
        }
    }
}