Skip to main content

alpha2_model/
error.rs

1use crate::{ClipId, CompositionId, DataSetId, EffectProblem, EffectResourceId, NodeId, TrackId};
2use alpha2_media::SourceId;
3use std::fmt;
4
5/// What holds the shape or layout a [`ModelError::InvalidShape`] or
6/// [`ModelError::InvalidLayout`] names.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub enum ShapeOwner {
9    /// A generated source's shapes or layout generator.
10    Source(SourceId),
11    /// A clip's masks.
12    Clip(ClipId),
13    /// A composition node's shapes or layout generator, or its masks.
14    Node {
15        /// The composition.
16        composition: CompositionId,
17        /// The node.
18        node: NodeId,
19    },
20}
21
22impl fmt::Display for ShapeOwner {
23    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::Source(source) => write!(formatter, "source {source}"),
26            Self::Clip(clip) => write!(formatter, "clip {clip}"),
27            Self::Node { composition, node } => {
28                write!(formatter, "composition {composition} node {node}")
29            }
30        }
31    }
32}
33
34/// What holds the value a [`ModelError::InvalidDataBinding`] names.
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub enum DataOwner {
37    /// A clip's visual, masks or audio.
38    Clip(ClipId),
39    /// A track's bus or caption track.
40    Track(TrackId),
41    /// The master bus.
42    Master,
43    /// A timeline transition's effect.
44    Transition {
45        /// Its track.
46        track: TrackId,
47        /// Its first clip.
48        from: ClipId,
49        /// Its second clip.
50        to: ClipId,
51    },
52    /// A composition node's settings.
53    Node {
54        /// The composition.
55        composition: CompositionId,
56        /// The node.
57        node: NodeId,
58    },
59    /// A generated source's tree.
60    Source(SourceId),
61}
62
63impl fmt::Display for DataOwner {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            Self::Clip(clip) => write!(formatter, "clip {clip}"),
67            Self::Track(track) => write!(formatter, "track {track}"),
68            Self::Master => formatter.write_str("the master bus"),
69            Self::Transition { track, from, to } => {
70                write!(formatter, "track {track} transition {from} to {to}")
71            }
72            Self::Node { composition, node } => {
73                write!(formatter, "composition {composition} node {node}")
74            }
75            Self::Source(source) => write!(formatter, "source {source}"),
76        }
77    }
78}
79
80/// What holds the effect a [`ModelError::InvalidEffect`] names.
81#[derive(Clone, Debug, Eq, PartialEq)]
82pub enum EffectOwner {
83    /// A composition's effect, transition or group node.
84    Node {
85        /// The composition.
86        composition: CompositionId,
87        /// The node.
88        node: NodeId,
89    },
90    /// A timeline transition.
91    Transition {
92        /// Its track.
93        track: TrackId,
94        /// The clip at progress zero.
95        from: ClipId,
96        /// The clip at progress one.
97        to: ClipId,
98    },
99}
100
101impl fmt::Display for EffectOwner {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::Node { composition, node } => {
105                write!(formatter, "composition {composition} node {node}")
106            }
107            Self::Transition { track, from, to } => {
108                write!(
109                    formatter,
110                    "the transition from {from} to {to} on track {track}"
111                )
112            }
113        }
114    }
115}
116
117impl fmt::Display for EffectProblem {
118    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
119        match self {
120            Self::UnknownBuiltin => formatter.write_str("is not a built-in"),
121            Self::Version { expected } => write!(formatter, "needs version {expected}"),
122            Self::Kind => formatter.write_str("is used as the wrong kind"),
123            Self::UnknownParam(name) => write!(formatter, "has no parameter {name}"),
124            Self::InvalidParam(name) => {
125                write!(
126                    formatter,
127                    "has a parameter {name} of the wrong type or out of range"
128                )
129            }
130            Self::Inputs => formatter.write_str("does not get exactly its declared inputs"),
131            Self::Resources => formatter.write_str("does not get exactly its declared resources"),
132        }
133    }
134}
135
136/// A document invariant violation.
137#[derive(Clone, Debug, Eq, PartialEq)]
138#[non_exhaustive]
139pub enum ModelError {
140    /// This build cannot interpret the document version.
141    UnsupportedSchemaVersion {
142        /// Version found in the decoded document.
143        found: u32,
144    },
145    /// The project has more than [`crate::MAX_DATA_SETS`] data sets.
146    TooManyDataSets {
147        /// Data sets in the document.
148        found: usize,
149        /// Largest accepted count.
150        maximum: usize,
151    },
152    /// Two data sets share one ID.
153    DuplicateDataSetId(DataSetId),
154    /// A data set breaks a rule of its kind.
155    InvalidDataSet {
156        /// The data set.
157        data: DataSetId,
158        /// What is wrong.
159        problem: crate::DataProblem,
160    },
161    /// A data binding, correction or caption words reference is unusable where it sits.
162    InvalidDataBinding {
163        /// What holds it.
164        owner: DataOwner,
165        /// The property, like `visual.position`, `masks[0].feather`, `effect.params.radius`,
166        /// `visual.correction` or `captions.from_words`.
167        at: String,
168        /// What is wrong.
169        problem: crate::BindingProblem,
170    },
171    /// At least one ID was empty.
172    EmptyIdentifier,
173    /// Two sources share one ID.
174    DuplicateSourceId(SourceId),
175    /// Two effect resources share one ID.
176    DuplicateEffectResourceId(EffectResourceId),
177    /// Two tracks share one ID.
178    DuplicateTrackId(TrackId),
179    /// Two clips share one ID.
180    DuplicateClipId(ClipId),
181    /// A source locator was empty.
182    EmptyLocator {
183        /// Source whose locator was empty.
184        source: SourceId,
185    },
186    /// A still image source says it has audio, which no image holds.
187    AudioOnImage {
188        /// The image source.
189        source: SourceId,
190    },
191    /// A source's provider does not fit it (wrong source kind, audio, or incoherent settings),
192    /// or a generated source has one.
193    InvalidProvider {
194        /// The source.
195        source: SourceId,
196    },
197    /// A source's fingerprint is malformed, or a generated source has one.
198    InvalidFingerprint {
199        /// The source.
200        source: SourceId,
201    },
202    /// A source declares a color whose dynamic range contradicts its transfer (HDR is exactly a
203    /// PQ or HLG transfer).
204    ContradictoryColor {
205        /// The source.
206        source: SourceId,
207    },
208    /// A generated source has no valid generator, or has a locator, color metadata or audio; or
209    /// another source has a generator.
210    InvalidGenerator {
211        /// The source.
212        source: SourceId,
213    },
214    /// A shapes content tree or mask outline breaks a limit, has a value out of range, or has
215    /// keyframes that cannot interpolate.
216    InvalidShape {
217        /// What holds the shape.
218        owner: ShapeOwner,
219        /// Where the problem lies, like `items[2].items[0].path` or `masks[1].shape.size`.
220        at: String,
221        /// What is wrong there.
222        problem: crate::ShapeProblem,
223    },
224    /// A layout tree breaks a limit or structure rule, has a value out of range, or has
225    /// keyframes that cannot interpolate.
226    InvalidLayout {
227        /// What holds the layout.
228        owner: ShapeOwner,
229        /// Where in it the problem lies, like `root.children[2].padding`.
230        at: String,
231        /// What is wrong there.
232        problem: crate::LayoutProblem,
233    },
234    /// A text generator's run has a style out of range once applied, or the runs draw in more
235    /// than [`crate::MAX_TEXT_FONT_SELECTIONS`] font selections from this run on.
236    InvalidTextRunStyle {
237        /// What holds the text generator.
238        owner: ShapeOwner,
239        /// The run's position among the text's runs.
240        run: usize,
241    },
242    /// An effect resource locator was empty.
243    EmptyEffectResourceLocator {
244        /// Resource whose locator was empty.
245        resource: EffectResourceId,
246    },
247    /// A clip effect references an absent effect resource.
248    UnknownEffectResource {
249        /// Clip containing the reference.
250        clip: ClipId,
251        /// Missing resource identity.
252        resource: EffectResourceId,
253    },
254    /// A clip has an empty source or timeline range.
255    EmptyClipRange {
256        /// Clip with an empty range.
257        clip: ClipId,
258    },
259    /// A clip starts before the project or source timeline origin.
260    NegativeClipRange {
261        /// Clip with a negative range start.
262        clip: ClipId,
263    },
264    /// Two clips overlap without one transition covering their intersection.
265    OverlappingClips {
266        /// Track containing the overlap.
267        track: TrackId,
268        /// First overlapping clip.
269        first: ClipId,
270        /// Second overlapping clip.
271        second: ClipId,
272    },
273    /// A clip refers to an absent source.
274    UnknownClipSource {
275        /// Clip containing the absent source reference.
276        clip: ClipId,
277        /// Referenced source that was not in the project.
278        source: SourceId,
279    },
280    /// A source cannot be placed on the selected track kind.
281    IncompatibleClipSource {
282        /// Clip containing the incompatible reference.
283        clip: ClipId,
284        /// Track that cannot accept the source kind.
285        track: TrackId,
286        /// Source with the incompatible kind.
287        source: SourceId,
288    },
289    /// A visual clip has non-finite values, invalid opacity, or unordered keyframes.
290    InvalidVisualProperties {
291        /// Clip containing the invalid presentation data.
292        clip: ClipId,
293    },
294    /// A clip has an invalid gain, pan, fade, or audio effect parameter.
295    InvalidAudioProperties {
296        /// Clip containing the invalid audio data.
297        clip: ClipId,
298    },
299    /// A track bus has an invalid gain, pan, effect, or ducking parameter.
300    InvalidTrackAudio {
301        /// Track containing the invalid bus data.
302        track: TrackId,
303    },
304    /// The project master bus has an invalid gain, effect, or limiter parameter.
305    InvalidMasterAudio,
306    /// A ducking sidechain names a missing track, itself, or forms a cycle.
307    InvalidDuckingSidechain {
308        /// Track whose ducking reference is unusable.
309        track: TrackId,
310        /// Referenced sidechain track.
311        sidechain: TrackId,
312    },
313    /// A clip names an absent composition.
314    UnknownComposition {
315        /// The clip.
316        clip: ClipId,
317        /// The composition it names.
318        composition: CompositionId,
319    },
320    /// A clip's composition has a non-positive scale, reaches a composition time past
321    /// [`alpha2_time::MAX_SERIALIZED_TICKS`] before the clip ends, or is on an audio clip.
322    InvalidClipComposition {
323        /// The clip.
324        clip: ClipId,
325    },
326    /// Two compositions share one ID.
327    DuplicateCompositionId(CompositionId),
328    /// A node ID contains `/`, which is reserved for joining the IDs of inlined group and media
329    /// nodes.
330    InvalidNodeId {
331        /// The composition.
332        composition: CompositionId,
333        /// The node ID.
334        node: NodeId,
335    },
336    /// Two nodes of one composition share an ID.
337    DuplicateNodeId {
338        /// The composition.
339        composition: CompositionId,
340        /// The repeated node ID.
341        node: NodeId,
342    },
343    /// A composition has more nodes than the renderer will schedule.
344    TooManyCompositionNodes {
345        /// The composition.
346        composition: CompositionId,
347        /// Number supplied by the document.
348        found: usize,
349        /// Largest supported count.
350        maximum: usize,
351    },
352    /// A node has an invalid setting: effect identity, version, parameter or value; transform,
353    /// progress, opacity or mask out of range; too many merge layers or masks; or a bypass on a
354    /// node without inputs.
355    InvalidNode {
356        /// The composition.
357        composition: CompositionId,
358        /// The node.
359        node: NodeId,
360    },
361    /// A node input names a node its composition does not have.
362    UnknownNodeInput {
363        /// The composition.
364        composition: CompositionId,
365        /// The node whose input it is.
366        node: NodeId,
367        /// The input: `input`, `from`, `to`, `matte`, `layers[i]`, or `inputs[i]`.
368        input: String,
369        /// The node named.
370        target: NodeId,
371    },
372    /// A node depends on its own output.
373    CompositionCycle {
374        /// The composition.
375        composition: CompositionId,
376        /// A node on the cycle.
377        node: NodeId,
378    },
379    /// A composition's output names a node it does not have.
380    UnknownCompositionOutput {
381        /// The composition.
382        composition: CompositionId,
383        /// The node named.
384        node: NodeId,
385    },
386    /// A media node names an absent source or one that is not visual.
387    InvalidNodeSource {
388        /// The composition.
389        composition: CompositionId,
390        /// The node.
391        node: NodeId,
392        /// The source named.
393        source: SourceId,
394    },
395    /// A composition's group inputs are unnamed, repeated or too many, or a control names no
396    /// effect setting of its nodes or repeats one.
397    InvalidCompositionPorts {
398        /// The composition.
399        composition: CompositionId,
400    },
401    /// A group node names an absent composition.
402    UnknownGroupComposition {
403        /// The composition holding the group node.
404        composition: CompositionId,
405        /// The group node.
406        node: NodeId,
407        /// The composition it names.
408        target: CompositionId,
409    },
410    /// A composition uses itself through group nodes or composition sources.
411    CompositionUsesItself {
412        /// A composition on the loop.
413        composition: CompositionId,
414    },
415    /// Compositions nest, through group nodes or composition sources, more than
416    /// [`crate::MAX_COMPOSITION_DEPTH`] deep.
417    CompositionNestedTooDeep {
418        /// The first such composition, in document order.
419        composition: CompositionId,
420        /// Deepest supported nesting.
421        maximum: usize,
422    },
423    /// The compositions draw more than [`crate::MAX_INLINED_NODES`] nodes, counting each group
424    /// node and composition-source media node as the nodes it draws.
425    TooManyInlinedNodes {
426        /// Largest supported count.
427        maximum: usize,
428    },
429    /// The clips at one instant draw more than [`crate::MAX_FRAME_INLINED_NODES`] composition
430    /// nodes together.
431    FrameDrawsTooManyNodes {
432        /// The first clip, in document order, starting at the first such instant.
433        clip: ClipId,
434        /// The nodes the clips at that instant draw.
435        found: u64,
436        /// Largest supported count.
437        maximum: usize,
438    },
439    /// A composition source names an absent composition, or has what only a host-supplied
440    /// source has.
441    InvalidCompositionSource {
442        /// The source.
443        source: SourceId,
444    },
445    /// An adjustment source has more than an ID and its kind: a locator, generator,
446    /// composition, color, fingerprint, provider or audio.
447    InvalidAdjustmentSource {
448        /// The source.
449        source: SourceId,
450    },
451    /// A transition from or to an adjustment clip is not `alpha2.transition.fade`.
452    InvalidAdjustmentTransition {
453        /// The track holding the transition.
454        track: TrackId,
455        /// The adjustment clip it names, its `from_clip` first.
456        clip: ClipId,
457    },
458    /// An effect or transition under [`crate::BUILTIN_EFFECT_PREFIX`] that does not match its
459    /// built-in definition.
460    InvalidEffect {
461        /// Where it is used.
462        owner: Box<EffectOwner>,
463        /// The effect id.
464        id: String,
465        /// How it fails its definition.
466        problem: EffectProblem,
467    },
468    /// A node's effect references an absent effect resource.
469    UnknownNodeResource {
470        /// The composition.
471        composition: CompositionId,
472        /// The node.
473        node: NodeId,
474        /// The resource named.
475        resource: EffectResourceId,
476    },
477    /// A clip has more than [`crate::MAX_CLIP_MASKS`] masks, a mask with a negative or
478    /// non-finite value, or masks on an audio track.
479    InvalidClipMask {
480        /// Clip carrying the invalid mask.
481        clip: ClipId,
482    },
483    /// A caption track has no captions, has clips or transitions, or has invalid cues or style;
484    /// or another track has captions.
485    InvalidCaptions {
486        /// The track.
487        track: TrackId,
488    },
489    /// A caption cue names a style its track does not have.
490    UnknownCaptionStyle {
491        /// The track.
492        track: TrackId,
493        /// The cue's position among the track's cues.
494        cue: usize,
495        /// The style it names.
496        name: String,
497    },
498    /// A caption cue's style (its track's with the cue's patch applied), or the style of one of
499    /// its runs over it, is out of range, or its runs draw in more than
500    /// [`crate::MAX_TEXT_FONT_SELECTIONS`] font selections.
501    InvalidCaptionCueStyle {
502        /// The track.
503        track: TrackId,
504        /// The cue's position among the track's cues.
505        cue: usize,
506    },
507    /// A clip freezes on an instant outside its source range.
508    InvalidTimeMap {
509        /// The clip.
510        clip: ClipId,
511    },
512    /// A looping clip makes more than [`crate::MAX_LOOP_PASSES`] passes.
513    TooManyLoopPasses {
514        /// The clip.
515        clip: ClipId,
516        /// Its passes, rounded up.
517        found: u64,
518        /// The most passes a clip makes.
519        maximum: u64,
520    },
521    /// A clip's matte names no visual clip, itself, a clip with its own matte, an adjustment
522    /// clip, or a clip in a transition; or an audio or adjustment clip has a matte.
523    InvalidMatte {
524        /// Clip whose matte is invalid.
525        clip: ClipId,
526    },
527    /// A transition is not contained in two distinct visual clips on its track.
528    InvalidClipTransition {
529        /// Track containing the invalid transition.
530        track: TrackId,
531    },
532    /// Transitions active at one instant lead from clip to clip in a circle, leaving no clip to
533    /// show.
534    TransitionCycle {
535        /// Track containing the transitions.
536        track: TrackId,
537        /// An instant they are all active.
538        at: alpha2_time::MediaTime,
539    },
540    /// Two clips have more than one transition between them, in either direction.
541    DuplicateTransition {
542        /// Track containing the transitions.
543        track: TrackId,
544        /// The transition's first clip.
545        first: ClipId,
546        /// The transition's second clip.
547        second: ClipId,
548    },
549    /// A caption track derives more than [`crate::MAX_DERIVED_CUES`] cues from its words, or maps
550    /// more than [`crate::MAX_DATA_WORDS`] words through its clips.
551    TooManyDerivedCues {
552        /// The caption track.
553        track: TrackId,
554    },
555    /// A time lies past [`alpha2_time::MAX_SERIALIZED_TICKS`] either way, which no document holds.
556    UnwritableTime {
557        /// The time, in ticks.
558        ticks: i64,
559    },
560    /// The project has more than [`crate::MAX_EFFECT_RESOURCES`] effect resources.
561    TooManyEffectResources {
562        /// Number supplied by the document.
563        found: usize,
564        /// Largest supported count.
565        maximum: usize,
566    },
567    /// The project contains too many compositions.
568    TooManyCompositions {
569        /// Number supplied by the document.
570        found: usize,
571        /// Largest supported count.
572        maximum: usize,
573    },
574    /// The source table exceeds the bounded project resource budget.
575    TooManySources {
576        /// Number supplied by the document.
577        found: usize,
578        /// Largest supported count.
579        maximum: usize,
580    },
581    /// The timeline contains too many tracks.
582    TooManyTracks {
583        /// Number supplied by the document.
584        found: usize,
585        /// Largest supported count.
586        maximum: usize,
587    },
588    /// The timeline contains too many clips in total.
589    TooManyClips {
590        /// Number supplied by the document.
591        found: usize,
592        /// Largest supported count.
593        maximum: usize,
594    },
595    /// More audio effects hold state at once than [`crate::MAX_AUDIO_EFFECTS`] (see
596    /// [`crate::Project::audio_effect_load`]).
597    TooManyAudioEffects {
598        /// The most effects holding state at once.
599        found: usize,
600        /// Largest supported count.
601        maximum: usize,
602        /// The earliest timeline position, in ticks, at which `found` hold state.
603        at_ticks: i64,
604    },
605    /// The audio effects hold more than [`crate::MAX_AUDIO_DELAY_MS`] of delay at once (see
606    /// [`crate::Project::audio_effect_load`]).
607    TooMuchAudioDelay {
608        /// The most milliseconds held at once, rounded up.
609        found_ms: u64,
610        /// Largest supported total.
611        maximum_ms: u32,
612        /// The earliest timeline position, in ticks, at which `found_ms` is held.
613        at_ticks: i64,
614    },
615    /// One track contains too many clips.
616    TooManyClipsOnTrack {
617        /// Track containing the excessive clip list.
618        track: TrackId,
619        /// Number supplied by the document.
620        found: usize,
621        /// Largest supported count.
622        maximum: usize,
623    },
624    /// A caption track holds more than [`crate::MAX_CLIPS_PER_TRACK`] cues.
625    TooManyCaptionCues {
626        /// The caption track.
627        track: TrackId,
628        /// Number supplied by the document.
629        found: usize,
630        /// Largest supported count.
631        maximum: usize,
632    },
633    /// One track contains too many transitions.
634    TooManyTransitions {
635        /// Track containing the excessive transition list.
636        track: TrackId,
637        /// Number supplied by the document.
638        found: usize,
639        /// Largest supported count.
640        maximum: usize,
641    },
642    /// Width or height was zero.
643    ZeroCanvasDimension,
644    /// A canvas edge exceeds the portable GPU-independent limit.
645    CanvasDimensionTooLarge {
646        /// Supplied width.
647        width: u32,
648        /// Supplied height.
649        height: u32,
650        /// Largest supported edge.
651        maximum: u32,
652    },
653    /// The canvas area exceeds the bounded pixel budget.
654    CanvasPixelBudgetExceeded {
655        /// Supplied pixel area.
656        pixels: u64,
657        /// Largest supported pixel area.
658        maximum: u64,
659    },
660    /// A background component is non-finite or outside `0..=1`.
661    InvalidBackground,
662    /// The color pipeline's HDR peak is outside [`crate::HDR_PEAK_NITS_RANGE`].
663    InvalidColorPipeline,
664    /// The project sample rate is outside the supported DSP interval.
665    UnsupportedSampleRate {
666        /// Supplied rate.
667        found: u32,
668        /// Smallest supported rate.
669        minimum: u32,
670        /// Largest supported rate.
671        maximum: u32,
672    },
673}
674
675/// The document object a [`ModelError`] is about, by id.
676#[derive(Clone, Copy, Debug, Eq, PartialEq)]
677#[non_exhaustive]
678pub enum ErrorSubject<'a> {
679    /// A timeline clip.
680    Clip(&'a ClipId),
681    /// A media source.
682    Source(&'a SourceId),
683    /// A track.
684    Track(&'a TrackId),
685    /// A composition.
686    Composition(&'a CompositionId),
687    /// A data set.
688    DataSet(&'a DataSetId),
689    /// An effect resource.
690    EffectResource(&'a EffectResourceId),
691}
692
693impl ModelError {
694    /// The document object this error is about, or `None` for one about the whole project.
695    ///
696    /// An overlap names its second clip, a duplicate transition its track.
697    #[must_use]
698    pub const fn subject(&self) -> Option<ErrorSubject<'_>> {
699        use ErrorSubject::{Clip, Composition, DataSet, EffectResource, Source, Track};
700        Some(match self {
701            Self::UnsupportedSchemaVersion { .. }
702            | Self::TooManyDataSets { .. }
703            | Self::EmptyIdentifier
704            | Self::InvalidMasterAudio
705            | Self::TooManyInlinedNodes { .. }
706            | Self::TooManyCompositions { .. }
707            | Self::TooManyEffectResources { .. }
708            | Self::UnwritableTime { .. }
709            | Self::TooManySources { .. }
710            | Self::TooManyTracks { .. }
711            | Self::TooManyClips { .. }
712            | Self::TooManyAudioEffects { .. }
713            | Self::TooMuchAudioDelay { .. }
714            | Self::ZeroCanvasDimension
715            | Self::CanvasDimensionTooLarge { .. }
716            | Self::CanvasPixelBudgetExceeded { .. }
717            | Self::InvalidBackground
718            | Self::InvalidColorPipeline
719            | Self::UnsupportedSampleRate { .. } => return None,
720            Self::DuplicateDataSetId(data) | Self::InvalidDataSet { data, .. } => DataSet(data),
721            Self::InvalidDataBinding { owner, .. } => match owner {
722                DataOwner::Clip(clip) | DataOwner::Transition { from: clip, .. } => Clip(clip),
723                DataOwner::Track(track) => Track(track),
724                DataOwner::Master => return None,
725                DataOwner::Node { composition, .. } => Composition(composition),
726                DataOwner::Source(source) => Source(source),
727            },
728            Self::InvalidShape { owner, .. }
729            | Self::InvalidLayout { owner, .. }
730            | Self::InvalidTextRunStyle { owner, .. } => match owner {
731                ShapeOwner::Source(source) => Source(source),
732                ShapeOwner::Clip(clip) => Clip(clip),
733                ShapeOwner::Node { composition, .. } => Composition(composition),
734            },
735            Self::InvalidEffect { owner, .. } => match &**owner {
736                EffectOwner::Node { composition, .. } => Composition(composition),
737                EffectOwner::Transition { from, .. } => Clip(from),
738            },
739            Self::DuplicateSourceId(source)
740            | Self::EmptyLocator { source }
741            | Self::AudioOnImage { source }
742            | Self::InvalidProvider { source }
743            | Self::InvalidFingerprint { source }
744            | Self::ContradictoryColor { source }
745            | Self::InvalidGenerator { source }
746            | Self::InvalidCompositionSource { source }
747            | Self::InvalidAdjustmentSource { source } => Source(source),
748            Self::DuplicateEffectResourceId(resource)
749            | Self::EmptyEffectResourceLocator { resource } => EffectResource(resource),
750            Self::DuplicateTrackId(track)
751            | Self::InvalidTrackAudio { track }
752            | Self::InvalidDuckingSidechain { track, .. }
753            | Self::InvalidCaptions { track }
754            | Self::UnknownCaptionStyle { track, .. }
755            | Self::InvalidCaptionCueStyle { track, .. }
756            | Self::InvalidClipTransition { track }
757            | Self::TransitionCycle { track, .. }
758            | Self::DuplicateTransition { track, .. }
759            | Self::TooManyClipsOnTrack { track, .. }
760            | Self::TooManyCaptionCues { track, .. }
761            | Self::TooManyDerivedCues { track }
762            | Self::TooManyTransitions { track, .. } => Track(track),
763            Self::DuplicateClipId(clip)
764            | Self::UnknownEffectResource { clip, .. }
765            | Self::EmptyClipRange { clip }
766            | Self::NegativeClipRange { clip }
767            | Self::OverlappingClips { second: clip, .. }
768            | Self::UnknownClipSource { clip, .. }
769            | Self::IncompatibleClipSource { clip, .. }
770            | Self::InvalidVisualProperties { clip }
771            | Self::InvalidAudioProperties { clip }
772            | Self::UnknownComposition { clip, .. }
773            | Self::InvalidClipComposition { clip }
774            | Self::FrameDrawsTooManyNodes { clip, .. }
775            | Self::InvalidClipMask { clip }
776            | Self::InvalidTimeMap { clip }
777            | Self::TooManyLoopPasses { clip, .. }
778            | Self::InvalidAdjustmentTransition { clip, .. }
779            | Self::InvalidMatte { clip } => Clip(clip),
780            Self::DuplicateCompositionId(composition)
781            | Self::InvalidNodeId { composition, .. }
782            | Self::DuplicateNodeId { composition, .. }
783            | Self::TooManyCompositionNodes { composition, .. }
784            | Self::InvalidNode { composition, .. }
785            | Self::UnknownNodeInput { composition, .. }
786            | Self::CompositionCycle { composition, .. }
787            | Self::UnknownCompositionOutput { composition, .. }
788            | Self::InvalidNodeSource { composition, .. }
789            | Self::InvalidCompositionPorts { composition }
790            | Self::UnknownGroupComposition { composition, .. }
791            | Self::CompositionUsesItself { composition }
792            | Self::CompositionNestedTooDeep { composition, .. }
793            | Self::UnknownNodeResource { composition, .. } => Composition(composition),
794        })
795    }
796}
797
798impl fmt::Display for ModelError {
799    #[allow(clippy::too_many_lines)]
800    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
801        match self {
802            Self::UnsupportedSchemaVersion { found } => {
803                write!(formatter, "unsupported schema version {found}")
804            }
805            Self::EmptyIdentifier => formatter.write_str("document contains an empty identifier"),
806            Self::DuplicateSourceId(id) => write!(formatter, "duplicate source ID {id}"),
807            Self::DuplicateEffectResourceId(id) => {
808                write!(formatter, "duplicate effect resource ID {id}")
809            }
810            Self::DuplicateTrackId(id) => write!(formatter, "duplicate track ID {id}"),
811            Self::DuplicateClipId(id) => write!(formatter, "duplicate clip ID {id}"),
812            Self::EmptyLocator { source } => {
813                write!(formatter, "source {source} has an empty locator")
814            }
815            Self::AudioOnImage { source } => {
816                write!(
817                    formatter,
818                    "source {source} is a still image and has no audio"
819                )
820            }
821            Self::InvalidGenerator { source } => {
822                write!(formatter, "source {source} has an invalid generator")
823            }
824            Self::InvalidShape { owner, at, problem } => {
825                write!(formatter, "{owner} has an invalid shape: {at} {problem}")
826            }
827            Self::InvalidLayout { owner, at, problem } => {
828                write!(formatter, "{owner} has an invalid layout: {at} {problem}")
829            }
830            Self::InvalidTextRunStyle { owner, run } => {
831                write!(
832                    formatter,
833                    "{owner} has text run {run} with a style out of range"
834                )
835            }
836            Self::ContradictoryColor { source } => write!(
837                formatter,
838                "source {source} declares a dynamic range its transfer contradicts"
839            ),
840            Self::InvalidFingerprint { source } => {
841                write!(formatter, "source {source} has an invalid fingerprint")
842            }
843            Self::InvalidProvider { source } => {
844                write!(formatter, "source {source} has an invalid provider")
845            }
846            Self::EmptyEffectResourceLocator { resource } => {
847                write!(formatter, "effect resource {resource} has an empty locator")
848            }
849            Self::UnknownEffectResource { clip, resource } => {
850                write!(
851                    formatter,
852                    "clip {clip} references unknown effect resource {resource}"
853                )
854            }
855            Self::EmptyClipRange { clip } => write!(formatter, "clip {clip} has an empty range"),
856            Self::NegativeClipRange { clip } => {
857                write!(formatter, "clip {clip} has a range before timeline origin")
858            }
859            Self::OverlappingClips {
860                track,
861                first,
862                second,
863            } => write!(
864                formatter,
865                "clips {first} and {second} overlap without a covering transition on track {track}"
866            ),
867            Self::UnknownClipSource { clip, source } => {
868                write!(formatter, "clip {clip} references unknown source {source}")
869            }
870            Self::IncompatibleClipSource {
871                clip,
872                track,
873                source,
874            } => {
875                write!(
876                    formatter,
877                    "clip {clip} cannot use source {source} on track {track}"
878                )
879            }
880            Self::InvalidVisualProperties { clip } => {
881                write!(formatter, "clip {clip} has invalid visual properties")
882            }
883            Self::InvalidAudioProperties { clip } => {
884                write!(formatter, "clip {clip} has invalid audio properties")
885            }
886            Self::InvalidTrackAudio { track } => {
887                write!(formatter, "track {track} has invalid audio bus settings")
888            }
889            Self::InvalidMasterAudio => {
890                write!(formatter, "the project master bus is invalid")
891            }
892            Self::InvalidDuckingSidechain { track, sidechain } => write!(
893                formatter,
894                "track {track} cannot duck from sidechain track {sidechain}"
895            ),
896            Self::UnknownComposition { clip, composition } => {
897                write!(
898                    formatter,
899                    "clip {clip} references unknown composition {composition}"
900                )
901            }
902            Self::InvalidClipComposition { clip } => {
903                write!(
904                    formatter,
905                    "clip {clip} has an invalid composition reference"
906                )
907            }
908            Self::DuplicateCompositionId(id) => write!(formatter, "duplicate composition ID {id}"),
909            Self::InvalidNodeId { composition, node } => {
910                write!(
911                    formatter,
912                    "composition {composition} has node ID {node}, which has a `/`"
913                )
914            }
915            Self::DuplicateNodeId { composition, node } => {
916                write!(
917                    formatter,
918                    "composition {composition} has duplicate node ID {node}"
919                )
920            }
921            Self::TooManyCompositionNodes {
922                composition,
923                found,
924                maximum,
925            } => write!(
926                formatter,
927                "composition {composition} has {found} nodes; the maximum is {maximum}"
928            ),
929            Self::InvalidNode { composition, node } => {
930                write!(
931                    formatter,
932                    "node {node} of composition {composition} has an invalid setting"
933                )
934            }
935            Self::UnknownNodeInput {
936                composition,
937                node,
938                input,
939                target,
940            } => write!(
941                formatter,
942                "input {input} of node {node} in composition {composition} names unknown node {target}"
943            ),
944            Self::CompositionCycle { composition, node } => write!(
945                formatter,
946                "node {node} of composition {composition} depends on its own output"
947            ),
948            Self::UnknownCompositionOutput { composition, node } => write!(
949                formatter,
950                "composition {composition} outputs unknown node {node}"
951            ),
952            Self::InvalidNodeSource {
953                composition,
954                node,
955                source,
956            } => write!(
957                formatter,
958                "node {node} of composition {composition} cannot show source {source}"
959            ),
960            Self::InvalidCompositionPorts { composition } => write!(
961                formatter,
962                "composition {composition} has invalid group inputs or controls"
963            ),
964            Self::UnknownGroupComposition {
965                composition,
966                node,
967                target,
968            } => write!(
969                formatter,
970                "group node {node} of composition {composition} names unknown composition {target}"
971            ),
972            Self::CompositionUsesItself { composition } => {
973                write!(formatter, "composition {composition} uses itself")
974            }
975            Self::CompositionNestedTooDeep {
976                composition,
977                maximum,
978            } => write!(
979                formatter,
980                "composition {composition} nests compositions more than {maximum} deep"
981            ),
982            Self::TooManyInlinedNodes { maximum } => write!(
983                formatter,
984                "compositions draw more than {maximum} nodes, counting each group and composition source as the nodes it draws"
985            ),
986            Self::FrameDrawsTooManyNodes {
987                clip,
988                found,
989                maximum,
990            } => write!(
991                formatter,
992                "the clips on the timeline where clip {clip} starts draw {found} composition nodes; a frame draws at most {maximum}"
993            ),
994            Self::InvalidCompositionSource { source } => {
995                write!(
996                    formatter,
997                    "source {source} is not a valid composition source"
998                )
999            }
1000            Self::InvalidAdjustmentSource { source } => write!(
1001                formatter,
1002                "source {source} is not a valid adjustment source: it has only an id and its kind"
1003            ),
1004            Self::InvalidAdjustmentTransition { track, clip } => write!(
1005                formatter,
1006                "a transition on track {track} names adjustment clip {clip}, which only fades"
1007            ),
1008            Self::InvalidEffect { owner, id, problem } => {
1009                write!(formatter, "effect {id} in {owner} {problem}")
1010            }
1011            Self::UnknownNodeResource {
1012                composition,
1013                node,
1014                resource,
1015            } => write!(
1016                formatter,
1017                "node {node} of composition {composition} references unknown effect resource {resource}"
1018            ),
1019            Self::InvalidClipMask { clip } => write!(formatter, "clip {clip} has an invalid mask"),
1020            Self::InvalidMatte { clip } => write!(formatter, "clip {clip} has an invalid matte"),
1021            Self::InvalidCaptions { track } => {
1022                write!(formatter, "track {track} has invalid captions")
1023            }
1024            Self::UnknownCaptionStyle { track, cue, name } => write!(
1025                formatter,
1026                "cue {cue} of track {track} names style {name:?}, which the track does not have"
1027            ),
1028            Self::InvalidCaptionCueStyle { track, cue } => write!(
1029                formatter,
1030                "cue {cue} of track {track} has a style out of range once its patch is applied"
1031            ),
1032            Self::InvalidTimeMap { clip } => {
1033                write!(formatter, "clip {clip} freezes outside its source range")
1034            }
1035            Self::TooManyLoopPasses {
1036                clip,
1037                found,
1038                maximum,
1039            } => write!(
1040                formatter,
1041                "clip {clip} loops {found} times; the maximum is {maximum}"
1042            ),
1043            Self::InvalidClipTransition { track } => {
1044                write!(formatter, "track {track} has an invalid clip transition")
1045            }
1046            Self::TransitionCycle { track, at } => write!(
1047                formatter,
1048                "transitions on track {track} active at {} ticks lead from clip to clip in a circle",
1049                at.ticks()
1050            ),
1051            Self::DuplicateTransition {
1052                track,
1053                first,
1054                second,
1055            } => write!(
1056                formatter,
1057                "clips {first} and {second} have more than one transition on track {track}"
1058            ),
1059            Self::TooManyDerivedCues { track } => write!(
1060                formatter,
1061                "track {track} derives more than {} caption cues or maps more than {} words",
1062                crate::MAX_DERIVED_CUES,
1063                crate::MAX_DATA_WORDS
1064            ),
1065            Self::UnwritableTime { ticks } => write!(
1066                formatter,
1067                "a time of {ticks} ticks is beyond {} either way",
1068                alpha2_time::MAX_SERIALIZED_TICKS
1069            ),
1070            Self::TooManyEffectResources { found, maximum } => write!(
1071                formatter,
1072                "project has {found} effect resources; the maximum is {maximum}"
1073            ),
1074            Self::TooManyCompositions { found, maximum } => write!(
1075                formatter,
1076                "project has {found} compositions; the maximum is {maximum}"
1077            ),
1078            Self::TooManySources { found, maximum } => {
1079                write!(
1080                    formatter,
1081                    "project has {found} sources; the maximum is {maximum}"
1082                )
1083            }
1084            Self::TooManyTracks { found, maximum } => {
1085                write!(
1086                    formatter,
1087                    "project has {found} tracks; the maximum is {maximum}"
1088                )
1089            }
1090            Self::TooManyClips { found, maximum } => {
1091                write!(
1092                    formatter,
1093                    "project has {found} clips; the maximum is {maximum}"
1094                )
1095            }
1096            Self::TooManyAudioEffects {
1097                found,
1098                maximum,
1099                at_ticks,
1100            } => write!(
1101                formatter,
1102                "project has {found} audio effects holding state at tick {at_ticks}; the maximum at once is {maximum}"
1103            ),
1104            Self::TooMuchAudioDelay {
1105                found_ms,
1106                maximum_ms,
1107                at_ticks,
1108            } => write!(
1109                formatter,
1110                "project audio effects hold {found_ms} ms of delay at tick {at_ticks}; the maximum at once is {maximum_ms} ms"
1111            ),
1112            Self::TooManyClipsOnTrack {
1113                track,
1114                found,
1115                maximum,
1116            } => write!(
1117                formatter,
1118                "track {track} has {found} clips; the maximum is {maximum}"
1119            ),
1120            Self::TooManyCaptionCues {
1121                track,
1122                found,
1123                maximum,
1124            } => write!(
1125                formatter,
1126                "track {track} has {found} caption cues; the maximum is {maximum}"
1127            ),
1128            Self::TooManyTransitions {
1129                track,
1130                found,
1131                maximum,
1132            } => write!(
1133                formatter,
1134                "track {track} has {found} transitions; the maximum is {maximum}"
1135            ),
1136            Self::ZeroCanvasDimension => formatter.write_str("canvas dimensions must be positive"),
1137            Self::CanvasDimensionTooLarge {
1138                width,
1139                height,
1140                maximum,
1141            } => write!(
1142                formatter,
1143                "canvas {width}x{height} exceeds the maximum edge {maximum}"
1144            ),
1145            Self::CanvasPixelBudgetExceeded { pixels, maximum } => write!(
1146                formatter,
1147                "canvas has {pixels} pixels; the maximum is {maximum}"
1148            ),
1149            Self::InvalidBackground => {
1150                formatter.write_str("background color components must be finite and within 0..=1")
1151            }
1152            Self::InvalidColorPipeline => {
1153                formatter.write_str("the HDR peak must be within 100..=10000 nits")
1154            }
1155            Self::TooManyDataSets { found, maximum } => write!(
1156                formatter,
1157                "project has {found} data sets; the maximum is {maximum}"
1158            ),
1159            Self::DuplicateDataSetId(data) => write!(formatter, "duplicate data set id {data}"),
1160            Self::InvalidDataSet { data, problem } => {
1161                write!(formatter, "data set {data} {problem}")
1162            }
1163            Self::InvalidDataBinding { owner, at, problem } => {
1164                write!(formatter, "{owner} {at} {problem}")
1165            }
1166            Self::UnsupportedSampleRate {
1167                found,
1168                minimum,
1169                maximum,
1170            } => write!(
1171                formatter,
1172                "sample rate {found} is outside {minimum}..={maximum}"
1173            ),
1174        }
1175    }
1176}
1177
1178impl std::error::Error for ModelError {}
1179
1180/// Failure while decoding a serialized project document.
1181#[derive(Debug)]
1182#[non_exhaustive]
1183pub enum ProjectLoadError {
1184    /// The JSON input exceeded the parser byte budget.
1185    TooLarge {
1186        /// Supplied UTF-8 byte length.
1187        bytes: usize,
1188        /// Largest accepted byte length.
1189        maximum: usize,
1190    },
1191    /// JSON syntax or shape was invalid.
1192    Json(serde_json::Error),
1193    /// The decoded document violated a model invariant.
1194    InvalidProject(ModelError),
1195}
1196
1197impl fmt::Display for ProjectLoadError {
1198    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1199        match self {
1200            Self::TooLarge { bytes, maximum } => {
1201                write!(
1202                    formatter,
1203                    "project JSON is {bytes} bytes; the maximum is {maximum}"
1204                )
1205            }
1206            Self::Json(error) => write!(formatter, "invalid project JSON: {error}"),
1207            Self::InvalidProject(error) => write!(formatter, "invalid project: {error}"),
1208        }
1209    }
1210}
1211
1212impl std::error::Error for ProjectLoadError {
1213    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1214        match self {
1215            Self::TooLarge { .. } => None,
1216            Self::Json(error) => Some(error),
1217            Self::InvalidProject(error) => Some(error),
1218        }
1219    }
1220}
1221
1222/// Why [`crate::Project::to_json`] wrote no document.
1223#[derive(Debug)]
1224#[non_exhaustive]
1225pub enum ProjectWriteError {
1226    /// The document would be longer than any loader accepts.
1227    TooLarge {
1228        /// Largest accepted byte length, which the document passes.
1229        maximum: usize,
1230    },
1231    /// Serialization failed.
1232    Json(serde_json::Error),
1233}
1234
1235impl fmt::Display for ProjectWriteError {
1236    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1237        match self {
1238            Self::TooLarge { maximum } => write!(
1239                formatter,
1240                "the project JSON would be longer than {maximum} bytes, the maximum a project loads with"
1241            ),
1242            Self::Json(error) => write!(formatter, "the project does not serialize: {error}"),
1243        }
1244    }
1245}
1246
1247impl std::error::Error for ProjectWriteError {
1248    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1249        match self {
1250            Self::TooLarge { .. } => None,
1251            Self::Json(error) => Some(error),
1252        }
1253    }
1254}