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