Skip to main content

alpha2_model/
project.rs

1use crate::{
2    Composition, EffectResource, EffectResourceId, Generator, MasterAudio, MediaKind, MediaSource,
3    ModelError, ProjectId, ProjectLoadError, ProjectWriteError, Timeline, TrackKind,
4};
5use alpha2_time::{FrameRate, MediaTime};
6use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
7use std::collections::{HashMap, HashSet};
8use std::fmt;
9
10/// The newest project-document schema understood by this build.
11pub const CURRENT_SCHEMA_VERSION: u32 = 1;
12/// Largest project document accepted by [`Project::from_json`].
13pub const MAX_PROJECT_JSON_BYTES: usize = 64 * 1024 * 1024;
14/// Largest canvas edge accepted by the portable project model.
15pub const MAX_CANVAS_DIMENSION: u32 = alpha2_media::MAX_FRAME_DIMENSION;
16/// Largest total canvas area accepted before quality scaling.
17pub const MAX_CANVAS_PIXELS: u64 = alpha2_media::MAX_FRAME_PIXELS;
18/// Supported project audio sample-rate interval.
19///
20/// 96 kHz is the highest rate an export codec here takes (AAC-LC), and staying below the
21/// 120 kHz tick rate keeps every sample on a distinct tick. Faster sources are resampled.
22pub const SAMPLE_RATE_RANGE: std::ops::RangeInclusive<u32> = 8_000..=96_000;
23/// Maximum number of tracks in one project.
24pub const MAX_TRACKS: usize = 256;
25/// Maximum number of clips across one project, and of sources in it.
26pub const MAX_CLIPS: usize = 100_000;
27/// Maximum number of clips on one track.
28pub const MAX_CLIPS_PER_TRACK: usize = 4_096;
29/// Maximum number of transitions on one track.
30pub const MAX_TRANSITIONS_PER_TRACK: usize = 4_096;
31/// Maximum number of effect resources in one project.
32pub const MAX_EFFECT_RESOURCES: usize = 10_000;
33
34/// A complete serializable project document.
35#[derive(Clone, Debug, PartialEq, Serialize)]
36pub struct Project {
37    /// Version used to serialize this document.
38    pub schema_version: u32,
39    /// Stable identity of this project.
40    pub id: ProjectId,
41    /// Human-readable project name. It has no semantic meaning.
42    pub name: String,
43    /// Output-wide timeline settings.
44    pub settings: ProjectSettings,
45    /// Media resources referenced by clips.
46    pub sources: Vec<MediaSource>,
47    /// Non-media resources referenced by effect invocations.
48    #[serde(default)]
49    pub effect_resources: Vec<EffectResource>,
50    /// Composition graphs that clips show.
51    #[serde(default)]
52    pub compositions: Vec<Composition>,
53    /// Ordered visual and audio tracks.
54    pub timeline: Timeline,
55    /// Master bus applied to the summed track audio.
56    #[serde(default)]
57    pub audio: MasterAudio,
58    /// Values derived from media that properties and caption tracks can follow.
59    /// At most [`crate::MAX_DATA_SETS`].
60    #[serde(default, skip_serializing_if = "Vec::is_empty")]
61    pub data: Vec<crate::DataSet>,
62}
63
64/// The deserialized shape of a [`Project`] before its invariants are checked.
65///
66/// This is the wire contract the published JSON Schema is derived from; [`Project::validate`]
67/// then decides whether a well-shaped document is valid.
68#[derive(Deserialize)]
69#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
70#[cfg_attr(feature = "schema", schemars(rename = "Project"))]
71#[serde(deny_unknown_fields)]
72pub(crate) struct ProjectWire {
73    /// The schema the document follows (`https://alpha2.sh/schema/project.v1.json`), for editors
74    /// and validators. The engine does not read or keep it.
75    #[serde(rename = "$schema", default)]
76    #[allow(dead_code)]
77    pub(crate) schema_url: Option<String>,
78    /// Document version. This build reads and writes only [`CURRENT_SCHEMA_VERSION`].
79    #[cfg_attr(feature = "schema", schemars(extend("const" = CURRENT_SCHEMA_VERSION)))]
80    pub(crate) schema_version: u32,
81    /// Stable identity of this project.
82    pub(crate) id: ProjectId,
83    /// Human-readable project name. It has no semantic meaning.
84    pub(crate) name: String,
85    /// Output-wide timeline settings.
86    pub(crate) settings: ProjectSettings,
87    /// Media resources referenced by clips.
88    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIPS }>")]
89    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIPS)))]
90    pub(crate) sources: Vec<MediaSource>,
91    /// Non-media resources referenced by effect invocations.
92    #[serde(default)]
93    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EFFECT_RESOURCES }>")]
94    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EFFECT_RESOURCES)))]
95    pub(crate) effect_resources: Vec<EffectResource>,
96    /// Composition graphs that clips show.
97    #[serde(default)]
98    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_COMPOSITIONS }>")]
99    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_COMPOSITIONS)))]
100    pub(crate) compositions: Vec<Composition>,
101    /// Ordered visual and audio tracks.
102    pub(crate) timeline: Timeline,
103    /// Master bus applied to the summed track audio.
104    #[serde(default)]
105    pub(crate) audio: MasterAudio,
106    /// Values derived from media, which properties and caption tracks can follow. At most 256.
107    #[serde(default)]
108    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_DATA_SETS }>")]
109    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_SETS)))]
110    pub(crate) data: Vec<crate::DataSet>,
111}
112
113impl TryFrom<ProjectWire> for Project {
114    type Error = ModelError;
115
116    fn try_from(wire: ProjectWire) -> Result<Self, Self::Error> {
117        let project = Self {
118            schema_version: wire.schema_version,
119            id: wire.id,
120            name: wire.name,
121            settings: wire.settings,
122            sources: wire.sources,
123            effect_resources: wire.effect_resources,
124            compositions: wire.compositions,
125            timeline: wire.timeline,
126            audio: wire.audio,
127            data: wire.data,
128        };
129        project.validate()?;
130        Ok(project)
131    }
132}
133
134impl<'de> Deserialize<'de> for Project {
135    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
136    where
137        D: Deserializer<'de>,
138    {
139        let wire = ProjectWire::deserialize(deserializer)?;
140        Self::try_from(wire).map_err(D::Error::custom)
141    }
142}
143
144impl Project {
145    /// Parses and validates a serialized project document.
146    ///
147    /// `schema_version` is read first, so a document of another version reports
148    /// [`ModelError::UnsupportedSchemaVersion`] rather than a shape error.
149    ///
150    /// # Errors
151    /// [`ProjectLoadError`] for a malformed, unsupported, or structurally invalid document.
152    pub fn from_json(json: &str) -> Result<Self, ProjectLoadError> {
153        // Reads only the version and skips every other field. A failed probe leaves the error to
154        // the full parse below.
155        #[derive(Deserialize)]
156        struct VersionProbe {
157            schema_version: u32,
158        }
159
160        if json.len() > MAX_PROJECT_JSON_BYTES {
161            return Err(ProjectLoadError::TooLarge {
162                bytes: json.len(),
163                maximum: MAX_PROJECT_JSON_BYTES,
164            });
165        }
166        if let Ok(VersionProbe { schema_version }) = serde_json::from_str(json)
167            && schema_version != CURRENT_SCHEMA_VERSION
168        {
169            return Err(ProjectLoadError::InvalidProject(
170                ModelError::UnsupportedSchemaVersion {
171                    found: schema_version,
172                },
173            ));
174        }
175        let wire = serde_json::from_str::<ProjectWire>(json).map_err(ProjectLoadError::Json)?;
176        Self::try_from(wire).map_err(ProjectLoadError::InvalidProject)
177    }
178
179    /// The document as compact JSON, refused once it passes [`MAX_PROJECT_JSON_BYTES`], so a
180    /// writer never hands out text [`Project::from_json`] would refuse. Writing stops at the cap.
181    ///
182    /// # Errors
183    /// [`ProjectWriteError::TooLarge`] past the cap.
184    ///
185    /// # Panics
186    /// Never; `serde_json` writes UTF-8.
187    pub fn to_json(&self) -> Result<String, ProjectWriteError> {
188        struct Capped(Vec<u8>);
189
190        impl std::io::Write for Capped {
191            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
192                if self.0.len() + bytes.len() > MAX_PROJECT_JSON_BYTES {
193                    return Err(std::io::Error::from(std::io::ErrorKind::FileTooLarge));
194                }
195                self.0.extend_from_slice(bytes);
196                Ok(bytes.len())
197            }
198
199            fn flush(&mut self) -> std::io::Result<()> {
200                Ok(())
201            }
202        }
203
204        let mut out = Capped(Vec::with_capacity(4096));
205        match serde_json::to_writer(&mut out, self) {
206            Ok(()) => Ok(String::from_utf8(out.0).expect("serde_json writes UTF-8")),
207            Err(error) if error.io_error_kind() == Some(std::io::ErrorKind::FileTooLarge) => {
208                Err(ProjectWriteError::TooLarge {
209                    maximum: MAX_PROJECT_JSON_BYTES,
210                })
211            }
212            Err(error) => Err(ProjectWriteError::Json(error)),
213        }
214    }
215
216    /// The sources a render of this project can read, in source order: each clip's own, and
217    /// those read by media nodes its compositions draw.
218    ///
219    /// From a composition's output the walk follows the inputs each node reads
220    /// ([`crate::CompositionReads::needed_inputs`], as the renderer plans them), into group and
221    /// composition-source compositions. A composition source counts only where the clip's own
222    /// composition draws the clip ([`crate::CompositionReads::draws_clip`]). Unconnected nodes,
223    /// unshown compositions, inputs a bypassed node skips and unread group ports read nothing.
224    #[must_use]
225    pub fn used_sources(&self) -> Vec<&MediaSource> {
226        let sources = self
227            .sources
228            .iter()
229            .map(|source| (&source.id, source))
230            .collect::<HashMap<_, _>>();
231        let compositions = self
232            .compositions
233            .iter()
234            .map(|composition| (&composition.id, composition))
235            .collect::<HashMap<_, _>>();
236        let reads = crate::CompositionReads::new(&compositions);
237        let mut used = HashSet::new();
238        let mut walked = HashSet::new();
239        let mut pending = Vec::new();
240        for clip in self.timeline.tracks.iter().flat_map(|track| &track.clips) {
241            used.insert(&clip.source_id);
242            // A composition source is the clip's picture, drawn only where the clip's own
243            // composition draws the clip.
244            let drawn = clip
245                .composition
246                .as_ref()
247                .is_none_or(|reference| reads.draws_clip(&reference.id));
248            pending.extend(
249                sources
250                    .get(&clip.source_id)
251                    .and_then(|source| source.composition.as_ref())
252                    .filter(|_| drawn),
253            );
254            pending.extend(clip.composition.as_ref().map(|reference| &reference.id));
255        }
256        // Validation rules out cycles. `walked` also keeps a composition that many clips or groups
257        // draw from being walked again.
258        while let Some(id) = pending.pop() {
259            if !walked.insert(id) {
260                continue;
261            }
262            let Some(composition) = compositions.get(id) else {
263                continue;
264            };
265            let nodes = composition
266                .nodes
267                .iter()
268                .map(|node| (&node.id, node))
269                .collect::<HashMap<_, _>>();
270            let mut reached = HashSet::new();
271            let mut frontier = composition.output.iter().collect::<Vec<_>>();
272            while let Some(node) = frontier.pop() {
273                let Some(node) = nodes.get(node).filter(|_| reached.insert(node)) else {
274                    continue;
275                };
276                match &node.op {
277                    crate::NodeOp::Media { source_id, .. } => {
278                        used.insert(source_id);
279                        pending.extend(
280                            sources
281                                .get(source_id)
282                                .and_then(|source| source.composition.as_ref()),
283                        );
284                    }
285                    crate::NodeOp::Group { composition, .. } => pending.push(composition),
286                    _ => {}
287                }
288                frontier.extend(
289                    reads
290                        .needed_inputs(node)
291                        .into_iter()
292                        .filter_map(crate::NodeInput::node),
293                );
294            }
295        }
296        self.sources
297            .iter()
298            .filter(|source| used.contains(&source.id))
299            .collect()
300    }
301
302    /// Returns the HDR sources (PQ, HLG or declared HDR, per
303    /// [`alpha2_media::ColorMetadata::is_hdr`]), which the project tone-maps or refuses as its
304    /// [`ColorPipeline`] says.
305    #[must_use]
306    pub fn hdr_sources(&self) -> Vec<&alpha2_media::SourceId> {
307        self.sources
308            .iter()
309            .filter(|source| source.effective_color_metadata().is_hdr())
310            .map(|source| &source.id)
311            .collect()
312    }
313
314    /// Whether anything in the project may draw text: a caption track, or a text or layout
315    /// generator in a source or composition. A project that draws none needs no fonts. Layouts
316    /// count even without text because the text host resolves them.
317    #[must_use]
318    pub fn draws_text(&self) -> bool {
319        let is_text = |generator: &crate::Generator| {
320            matches!(
321                generator,
322                crate::Generator::Text { .. } | crate::Generator::Layout { .. }
323            )
324        };
325        self.timeline
326            .tracks
327            .iter()
328            .any(|track| track.captions.is_some())
329            || self
330                .sources
331                .iter()
332                .any(|source| source.generator.as_ref().is_some_and(is_text))
333            || self.compositions.iter().any(|composition| {
334                composition.nodes.iter().any(|node| {
335                    matches!(&node.op, crate::NodeOp::Generator { generator } if is_text(generator))
336                })
337            })
338    }
339
340    /// The smallest interval holding every clip, caption cue and timeline-anchored word a caption
341    /// track shows. `None` for a project that shows nothing.
342    #[must_use]
343    pub fn extent(&self) -> Option<alpha2_time::TimeRange> {
344        let words = self
345            .timeline
346            .tracks
347            .iter()
348            .filter_map(|track| track.captions.as_ref()?.from_words.as_ref())
349            .filter_map(|from| self.data.iter().find(|set| set.id == from.data))
350            .filter(|set| set.anchor == crate::DataAnchor::Timeline)
351            .filter_map(|set| match &set.values {
352                crate::DataValues::Words(words) => Some((
353                    words.first()?.start,
354                    words.iter().map(|word| word.end).max()?,
355                )),
356                _ => None,
357            });
358        let mut bounds = self
359            .timeline
360            .extent()
361            .map(|range| (range.start(), range.end()));
362        for (start, end) in words {
363            bounds =
364                Some(bounds.map_or((start, end), |(low, high)| (low.min(start), high.max(end))));
365        }
366        bounds.and_then(|(start, end)| alpha2_time::TimeRange::new(start, end).ok())
367    }
368
369    /// The range a whole-project export covers when none is asked for: from time 0, the origin
370    /// keyframes, markers and caption times count from, to the end of the [`Self::extent`].
371    /// `None` for a project that shows nothing or nothing after time 0.
372    #[must_use]
373    pub fn default_export_range(&self) -> Option<alpha2_time::TimeRange> {
374        let end = self.extent()?.end();
375        let range = alpha2_time::TimeRange::new(alpha2_time::MediaTime::ZERO, end).ok()?;
376        (end > alpha2_time::MediaTime::ZERO).then_some(range)
377    }
378
379    /// Creates an empty project using the current schema version.
380    #[must_use]
381    pub fn new(id: ProjectId, name: impl Into<String>, settings: ProjectSettings) -> Self {
382        Self {
383            schema_version: CURRENT_SCHEMA_VERSION,
384            id,
385            name: name.into(),
386            settings,
387            sources: Vec::new(),
388            effect_resources: Vec::new(),
389            compositions: Vec::new(),
390            timeline: Timeline { tracks: Vec::new() },
391            audio: MasterAudio::default(),
392            data: Vec::new(),
393        }
394    }
395
396    /// Checks structural invariants without performing media I/O.
397    ///
398    /// # Errors
399    /// Returns the first invalid document invariant encountered.
400    pub fn validate(&self) -> Result<(), ModelError> {
401        if self.schema_version != CURRENT_SCHEMA_VERSION {
402            return Err(ModelError::UnsupportedSchemaVersion {
403                found: self.schema_version,
404            });
405        }
406        self.settings.validate()?;
407        ensure_id(&self.id)?;
408        if !self.audio.validate() {
409            return Err(ModelError::InvalidMasterAudio);
410        }
411        if self.sources.len() > MAX_CLIPS {
412            return Err(ModelError::TooManySources {
413                found: self.sources.len(),
414                maximum: MAX_CLIPS,
415            });
416        }
417        if self.timeline.tracks.len() > MAX_TRACKS {
418            return Err(ModelError::TooManyTracks {
419                found: self.timeline.tracks.len(),
420                maximum: MAX_TRACKS,
421            });
422        }
423
424        let sources = self.validate_sources()?;
425        let effect_resource_ids = self.validate_effect_resources()?;
426        let inlined = crate::composition::validate_compositions(
427            &self.compositions,
428            &self.sources,
429            &sources,
430            &effect_resource_ids,
431            (self.settings.width, self.settings.height),
432        )?;
433        let index = DocumentIndex {
434            sources,
435            compositions: self
436                .compositions
437                .iter()
438                .map(|composition| &composition.id)
439                .collect(),
440        };
441
442        let mut track_ids = HashSet::new();
443        let mut clip_ids = HashSet::new();
444        let mut clip_count = 0_usize;
445        for track in &self.timeline.tracks {
446            ensure_id(&track.id)?;
447            if !track_ids.insert(&track.id) {
448                return Err(ModelError::DuplicateTrackId(track.id.clone()));
449            }
450            if track.clips.len() > MAX_CLIPS_PER_TRACK {
451                return Err(ModelError::TooManyClipsOnTrack {
452                    track: track.id.clone(),
453                    found: track.clips.len(),
454                    maximum: MAX_CLIPS_PER_TRACK,
455                });
456            }
457            validate_captions(track)?;
458            if track.transitions.len() > MAX_TRANSITIONS_PER_TRACK {
459                return Err(ModelError::TooManyTransitions {
460                    track: track.id.clone(),
461                    found: track.transitions.len(),
462                    maximum: MAX_TRANSITIONS_PER_TRACK,
463                });
464            }
465            clip_count =
466                clip_count
467                    .checked_add(track.clips.len())
468                    .ok_or(ModelError::TooManyClips {
469                        found: usize::MAX,
470                        maximum: MAX_CLIPS,
471                    })?;
472            if clip_count > MAX_CLIPS {
473                return Err(ModelError::TooManyClips {
474                    found: clip_count,
475                    maximum: MAX_CLIPS,
476                });
477            }
478            for clip in &track.clips {
479                validate_clip(&index, track, clip, &mut clip_ids)?;
480            }
481            for transition in &track.transitions {
482                ensure_effect_resources_exist(
483                    &transition.effect,
484                    &effect_resource_ids,
485                    &transition.to_clip,
486                )?;
487            }
488            ensure_transitions_are_supported(track)?;
489            ensure_transition_effects_match_builtins(track)?;
490            if !track.audio.validate() {
491                return Err(ModelError::InvalidTrackAudio {
492                    track: track.id.clone(),
493                });
494            }
495            ensure_overlaps_have_transitions(track)?;
496        }
497        self.ensure_audio_effects_fit()?;
498        crate::data_places::validate_data(self, &index.sources)?;
499        ensure_ducking_is_acyclic(&self.timeline)?;
500        ensure_mattes_are_usable(&self.timeline)?;
501        ensure_frames_fit(&self.timeline, &index.sources, &inlined)?;
502        crate::time_bound::ensure_times_are_writable(self)
503    }
504
505    /// Checks each source, and returns them by ID.
506    fn validate_sources(
507        &self,
508    ) -> Result<HashMap<&alpha2_media::SourceId, &MediaSource>, ModelError> {
509        let mut sources = HashMap::with_capacity(self.sources.len());
510        for source in &self.sources {
511            ensure_id(&source.id)?;
512            validate_source_content(source, (self.settings.width, self.settings.height))?;
513            if sources.insert(&source.id, source).is_some() {
514                return Err(ModelError::DuplicateSourceId(source.id.clone()));
515            }
516        }
517        Ok(sources)
518    }
519
520    /// Bounds the audio effect state held at once (see [`Project::audio_effect_load`]) to
521    /// [`crate::MAX_AUDIO_EFFECTS`] effects and [`crate::MAX_AUDIO_DELAY_MS`] of delay.
522    fn ensure_audio_effects_fit(&self) -> Result<(), ModelError> {
523        let load = self.audio_effect_load();
524        if load.effects > crate::MAX_AUDIO_EFFECTS {
525            return Err(ModelError::TooManyAudioEffects {
526                found: load.effects,
527                maximum: crate::MAX_AUDIO_EFFECTS,
528                at_ticks: load.effects_at_ticks,
529            });
530        }
531        if load.delay_ms() > u64::from(crate::MAX_AUDIO_DELAY_MS) {
532            return Err(ModelError::TooMuchAudioDelay {
533                found_ms: load.delay_ms(),
534                maximum_ms: crate::MAX_AUDIO_DELAY_MS,
535                at_ticks: load.delay_at_ticks,
536            });
537        }
538        Ok(())
539    }
540
541    fn validate_effect_resources(&self) -> Result<HashSet<&EffectResourceId>, ModelError> {
542        if self.effect_resources.len() > MAX_EFFECT_RESOURCES {
543            return Err(ModelError::TooManyEffectResources {
544                found: self.effect_resources.len(),
545                maximum: MAX_EFFECT_RESOURCES,
546            });
547        }
548        let mut ids = HashSet::new();
549        for resource in &self.effect_resources {
550            ensure_id(&resource.id)?;
551            if resource.locator.is_empty() {
552                return Err(ModelError::EmptyEffectResourceLocator {
553                    resource: resource.id.clone(),
554                });
555            }
556            if !ids.insert(&resource.id) {
557                return Err(ModelError::DuplicateEffectResourceId(resource.id.clone()));
558            }
559        }
560        Ok(ids)
561    }
562}
563
564fn ensure_effect_resources_exist(
565    effect: &crate::ClipEffect,
566    known: &HashSet<&EffectResourceId>,
567    clip: &crate::ClipId,
568) -> Result<(), ModelError> {
569    for resource in effect.resources.values() {
570        if !known.contains(resource) {
571            return Err(ModelError::UnknownEffectResource {
572                clip: clip.clone(),
573                resource: resource.clone(),
574            });
575        }
576    }
577    Ok(())
578}
579
580/// Checks one clip's identity, ranges, source compatibility, and visual and audio settings.
581fn validate_clip<'a>(
582    index: &DocumentIndex<'a>,
583    track: &'a crate::Track,
584    clip: &'a crate::Clip,
585    clip_ids: &mut HashSet<&'a crate::ClipId>,
586) -> Result<(), ModelError> {
587    ensure_id(&clip.id)?;
588    if clip.timeline_range.is_empty() || clip.source_range.is_empty() {
589        return Err(ModelError::EmptyClipRange {
590            clip: clip.id.clone(),
591        });
592    }
593    if clip.timeline_range.start().ticks() < 0 || clip.source_range.start().ticks() < 0 {
594        return Err(ModelError::NegativeClipRange {
595            clip: clip.id.clone(),
596        });
597    }
598    if !clip_ids.insert(&clip.id) {
599        return Err(ModelError::DuplicateClipId(clip.id.clone()));
600    }
601    let Some(source) = index.sources.get(&clip.source_id) else {
602        return Err(ModelError::UnknownClipSource {
603            clip: clip.id.clone(),
604            source: clip.source_id.clone(),
605        });
606    };
607    if !track.kind.accepts(source.kind) {
608        return Err(ModelError::IncompatibleClipSource {
609            clip: clip.id.clone(),
610            track: track.id.clone(),
611            source: source.id.clone(),
612        });
613    }
614    if !clip.visual.validate() {
615        return Err(ModelError::InvalidVisualProperties {
616            clip: clip.id.clone(),
617        });
618    }
619    if let Some(composition) = &clip.composition {
620        // Check the reference's own terms first since what follows computes with them. Composition
621        // time grows with timeline time, so the clip's last instant has the largest value.
622        let held = || {
623            let last = MediaTime::from_ticks(clip.timeline_range.end().ticks().saturating_sub(1));
624            composition
625                .local_time(clip.timeline_range.start(), last)
626                .is_some_and(|time| time.ticks() <= alpha2_time::MAX_SERIALIZED_TICKS)
627        };
628        if track.kind != TrackKind::Video || !composition.scale.is_valid() || !held() {
629            return Err(ModelError::InvalidClipComposition {
630                clip: clip.id.clone(),
631            });
632        }
633        if !index.compositions.contains(&composition.id) {
634            return Err(ModelError::UnknownComposition {
635                clip: clip.id.clone(),
636                composition: composition.id.clone(),
637            });
638        }
639    }
640    if !clip.audio.validate() {
641        return Err(ModelError::InvalidAudioProperties {
642            clip: clip.id.clone(),
643        });
644    }
645    let visual = track.kind == TrackKind::Video;
646    if clip.masks.len() > crate::MAX_CLIP_MASKS || (!visual && !clip.masks.is_empty()) {
647        return Err(ModelError::InvalidClipMask {
648            clip: clip.id.clone(),
649        });
650    }
651    crate::mask::validate_masks(&clip.masks).map_err(|issue| ModelError::InvalidShape {
652        owner: crate::ShapeOwner::Clip(clip.id.clone()),
653        at: issue.at,
654        problem: issue.problem,
655    })?;
656    if !visual && clip.matte.is_some() {
657        return Err(ModelError::InvalidMatte {
658            clip: clip.id.clone(),
659        });
660    }
661    if let crate::TimeMap::Freeze { source_time } = clip.time_map
662        && !clip.source_range.contains(source_time)
663    {
664        return Err(ModelError::InvalidTimeMap {
665            clip: clip.id.clone(),
666        });
667    }
668    if let crate::TimeMap::Loop { .. } = clip.time_map {
669        let length = |range: alpha2_time::TimeRange| range.duration().map_or(0, MediaTime::ticks);
670        let found = crate::loop_passes(length(clip.timeline_range), length(clip.source_range));
671        if found > crate::MAX_LOOP_PASSES {
672            return Err(ModelError::TooManyLoopPasses {
673                clip: clip.id.clone(),
674                found,
675                maximum: crate::MAX_LOOP_PASSES,
676            });
677        }
678    }
679    Ok(())
680}
681
682/// The document's sources and compositions by ID, so validation looks up each reference once.
683struct DocumentIndex<'a> {
684    sources: HashMap<&'a alpha2_media::SourceId, &'a MediaSource>,
685    compositions: HashSet<&'a crate::CompositionId>,
686}
687
688/// Rejects transitions on audio tracks, transitions not fully covered by both clips, and a
689/// second transition between two clips.
690fn ensure_transitions_are_supported(track: &crate::Track) -> Result<(), ModelError> {
691    let clips = track
692        .clips
693        .iter()
694        .map(|clip| (&clip.id, clip))
695        .collect::<HashMap<_, _>>();
696    let mut pairs = HashSet::with_capacity(track.transitions.len());
697    for transition in &track.transitions {
698        let covers = |id: &crate::ClipId| {
699            clips.get(id).is_some_and(|clip| {
700                clip.timeline_range.start() <= transition.timeline_range.start()
701                    && clip.timeline_range.end() >= transition.timeline_range.end()
702            })
703        };
704        let valid = track.kind == TrackKind::Video
705            && transition.from_clip != transition.to_clip
706            && !transition.timeline_range.is_empty()
707            && transition.easing.is_valid()
708            && transition.effect.is_valid()
709            && covers(&transition.from_clip)
710            && covers(&transition.to_clip);
711        if !valid {
712            return Err(ModelError::InvalidClipTransition {
713                track: track.id.clone(),
714            });
715        }
716        // The engine folds one transition over another: the same pair twice mixes twice, and both
717        // directions hide both clips.
718        let pair = if transition.from_clip < transition.to_clip {
719            (&transition.from_clip, &transition.to_clip)
720        } else {
721            (&transition.to_clip, &transition.from_clip)
722        };
723        if !pairs.insert(pair) {
724            return Err(ModelError::DuplicateTransition {
725                track: track.id.clone(),
726                first: transition.from_clip.clone(),
727                second: transition.to_clip.clone(),
728            });
729        }
730    }
731    Ok(())
732}
733
734/// Checks each transition's built-in effect against its definition.
735fn ensure_transition_effects_match_builtins(track: &crate::Track) -> Result<(), ModelError> {
736    for transition in &track.transitions {
737        crate::effect_spec::check_builtin(&transition.effect, crate::EffectKind::Transition, None)
738            .map_err(|problem| ModelError::InvalidEffect {
739                owner: Box::new(crate::EffectOwner::Transition {
740                    track: track.id.clone(),
741                    from: transition.from_clip.clone(),
742                    to: transition.to_clip.clone(),
743                }),
744                id: transition.effect.id.clone(),
745                problem,
746            })?;
747    }
748    Ok(())
749}
750
751/// Rejects sidechain references to missing tracks, the referencing track itself, or any
752/// cycle between ducked tracks.
753///
754/// Either track kind may duck or be ducked. The track reported is the first in document
755/// order with an unusable sidechain. Each track ID is looked up once, so the check is linear
756/// in the tracks however long the chains.
757fn ensure_ducking_is_acyclic(timeline: &Timeline) -> Result<(), ModelError> {
758    fn sidechain_of(track: &crate::Track) -> Option<&crate::TrackId> {
759        track
760            .audio
761            .ducking
762            .as_ref()
763            .map(|ducking| &ducking.sidechain_track)
764    }
765    // Track IDs are unique by now, so each names one position.
766    let positions = timeline
767        .tracks
768        .iter()
769        .enumerate()
770        .map(|(position, track)| (&track.id, position))
771        .collect::<HashMap<_, _>>();
772    let next = timeline
773        .tracks
774        .iter()
775        .map(|track| sidechain_of(track).and_then(|sidechain| positions.get(sidechain).copied()))
776        .collect::<Vec<_>>();
777    let cyclic = tracks_on_cycles(&next);
778    for ((track, next), on_cycle) in timeline.tracks.iter().zip(next).zip(cyclic) {
779        let Some(sidechain) = sidechain_of(track) else {
780            continue;
781        };
782        // A missing sidechain, or one that leads back to this track (itself included).
783        if next.is_none() || on_cycle {
784            return Err(ModelError::InvalidDuckingSidechain {
785                track: track.id.clone(),
786                sidechain: sidechain.clone(),
787            });
788        }
789    }
790    Ok(())
791}
792
793/// Which tracks lie on a sidechain cycle, given for each track the position of the track named
794/// as its sidechain.
795///
796/// Each track names at most one sidechain, so a track is on a cycle exactly when its own walk
797/// returns to it. Each walk stops at the first track an earlier walk reached, so every track
798/// is visited once overall.
799fn tracks_on_cycles(next: &[Option<usize>]) -> Vec<bool> {
800    const UNVISITED: usize = usize::MAX;
801    let mut cyclic = vec![false; next.len()];
802    // The walk that first reached each track; a walk that meets its own mark has closed a cycle.
803    let mut walk_of = vec![UNVISITED; next.len()];
804    for start in 0..next.len() {
805        let mut cursor = Some(start);
806        while let Some(position) = cursor {
807            match walk_of[position] {
808                UNVISITED => {
809                    walk_of[position] = start;
810                    cursor = next[position];
811                }
812                walk if walk == start => {
813                    // Mark the cycle by going round it once from where the walk closed it.
814                    let mut member = position;
815                    loop {
816                        cyclic[member] = true;
817                        match next[member] {
818                            Some(following) if following != position => member = following,
819                            _ => break,
820                        }
821                    }
822                    break;
823                }
824                _ => break,
825            }
826        }
827    }
828    cyclic
829}
830
831/// Rejects a matte that names no visual clip, the clip itself, a clip with its own matte, or
832/// a clip in a transition.
833///
834/// A chain of mattes would need an evaluation order the document does not give, and a clip
835/// in a transition is drawn by the transition.
836fn ensure_mattes_are_usable(timeline: &Timeline) -> Result<(), ModelError> {
837    let visual = timeline
838        .tracks
839        .iter()
840        .filter(|track| track.kind == TrackKind::Video)
841        .flat_map(|track| track.clips.iter().map(|clip| (&clip.id, clip)))
842        .collect::<HashMap<_, _>>();
843    let in_transition = timeline
844        .tracks
845        .iter()
846        .flat_map(|track| &track.transitions)
847        .flat_map(|transition| [&transition.from_clip, &transition.to_clip])
848        .collect::<HashSet<_>>();
849    // In document order, so the reported clip is the same on every platform.
850    let clips = timeline
851        .tracks
852        .iter()
853        .filter(|track| track.kind == TrackKind::Video)
854        .flat_map(|track| &track.clips);
855    for clip in clips {
856        let Some(matte) = &clip.matte else {
857            continue;
858        };
859        let usable = matte.source != clip.id
860            && visual
861                .get(&matte.source)
862                .is_some_and(|source| source.matte.is_none())
863            && !in_transition.contains(&matte.source);
864        if !usable {
865            return Err(ModelError::InvalidMatte {
866                clip: clip.id.clone(),
867            });
868        }
869    }
870    Ok(())
871}
872
873/// Checks that the clips at no instant draw more than [`crate::MAX_FRAME_INLINED_NODES`]
874/// composition nodes together. A composition compiles once however many clips show it, but
875/// each clip on screen draws all of it.
876///
877/// The clip reported is the first, in document order, starting at the first instant over the
878/// bound; the count covers all clips there.
879fn ensure_frames_fit(
880    timeline: &Timeline,
881    sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
882    inlined: &crate::composition::InlinedNodes<'_>,
883) -> Result<(), ModelError> {
884    let nodes = |id: Option<&crate::CompositionId>| id.and_then(|id| inlined.get(id)).copied();
885    // Each clip drawing a composition, with its node count, at its start (+) and end (-).
886    let mut edges = Vec::new();
887    for clip in timeline.tracks.iter().flat_map(|track| &track.clips) {
888        let source = sources
889            .get(&clip.source_id)
890            .and_then(|source| source.composition.as_ref());
891        let drawn = nodes(clip.composition.as_ref().map(|reference| &reference.id))
892            .unwrap_or(0)
893            .saturating_add(nodes(source).unwrap_or(0));
894        if drawn > 0 {
895            edges.push((clip.timeline_range.start(), true, drawn, &clip.id));
896            edges.push((clip.timeline_range.end(), false, drawn, &clip.id));
897        }
898    }
899    // By instant, ends before starts since ranges are half-open, and in document order since the
900    // sort is stable.
901    edges.sort_by_key(|&(time, starts, ..)| (time, starts));
902    let mut drawn = 0_u64;
903    let mut edges = edges.into_iter().peekable();
904    while let Some((time, starts, nodes, clip)) = edges.next() {
905        if !starts {
906            drawn -= nodes;
907            continue;
908        }
909        drawn = drawn.saturating_add(nodes);
910        // Every clip starting at this instant, so the count is the frame's.
911        while let Some((_, _, nodes, _)) =
912            edges.next_if(|&(next, next_starts, ..)| next == time && next_starts)
913        {
914            drawn = drawn.saturating_add(nodes);
915        }
916        if drawn > crate::MAX_FRAME_INLINED_NODES as u64 {
917            return Err(ModelError::FrameDrawsTooManyNodes {
918                clip: clip.clone(),
919                found: drawn,
920                maximum: crate::MAX_FRAME_INLINED_NODES,
921            });
922        }
923    }
924    Ok(())
925}
926
927/// Rejects visual overlaps that no transition covers.
928///
929/// Two overlapping visual clips have no defined composite without a transition. Audio tracks
930/// may overlap freely because the mixer sums them.
931pub(crate) fn ensure_overlaps_have_transitions(track: &crate::Track) -> Result<(), ModelError> {
932    if track.kind != TrackKind::Video {
933        return Ok(());
934    }
935    let transitions = track
936        .transitions
937        .iter()
938        .flat_map(|transition| {
939            [
940                (
941                    &transition.from_clip,
942                    &transition.to_clip,
943                    transition.timeline_range,
944                ),
945                (
946                    &transition.to_clip,
947                    &transition.from_clip,
948                    transition.timeline_range,
949                ),
950            ]
951        })
952        .collect::<HashSet<_>>();
953    let directed = track
954        .transitions
955        .iter()
956        .map(|transition| (&transition.from_clip, &transition.to_clip))
957        .collect::<HashSet<_>>();
958    let mut ordered = track.clips.iter().collect::<Vec<_>>();
959    ordered.sort_by_key(|clip| (clip.timeline_range.start(), clip.timeline_range.end()));
960    let mut active = Vec::new();
961    for second in ordered {
962        active.retain(|first: &&crate::Clip| {
963            first.timeline_range.end() > second.timeline_range.start()
964        });
965        for first in &active {
966            let Some(intersection) = first.timeline_range.intersection(second.timeline_range)
967            else {
968                continue;
969            };
970            if !transitions.contains(&(&first.id, &second.id, intersection)) {
971                return Err(ModelError::OverlappingClips {
972                    track: track.id.clone(),
973                    first: first.id.clone(),
974                    second: second.id.clone(),
975                });
976            }
977        }
978        active.push(second);
979        // Every clip active here covers this instant, and so does the transition between each two.
980        // The engine folds them clip to clip, which needs no cycle: a tournament is acyclic exactly
981        // when its clips lead to 0, 1, ..., k - 1 others. A set only grows at a start, so starts
982        // are the instants to check.
983        if active.len() >= 3 {
984            let mut leads = active
985                .iter()
986                .map(|from| {
987                    active
988                        .iter()
989                        .filter(|to| directed.contains(&(&from.id, &to.id)))
990                        .count()
991                })
992                .collect::<Vec<_>>();
993            leads.sort_unstable();
994            if leads.iter().enumerate().any(|(rank, lead)| rank != *lead) {
995                return Err(ModelError::TransitionCycle {
996                    track: track.id.clone(),
997                    at: second.timeline_range.start(),
998                });
999            }
1000        }
1001    }
1002    Ok(())
1003}
1004
1005/// Checks that a caption track holds only valid captions and that no other track holds any.
1006fn validate_captions(track: &crate::Track) -> Result<(), ModelError> {
1007    if let Some(captions) = &track.captions
1008        && captions.cues.len() > MAX_CLIPS_PER_TRACK
1009    {
1010        return Err(ModelError::TooManyCaptionCues {
1011            track: track.id.clone(),
1012            found: captions.cues.len(),
1013            maximum: MAX_CLIPS_PER_TRACK,
1014        });
1015    }
1016    let valid = match (&track.kind, &track.captions) {
1017        (TrackKind::Caption, Some(captions)) => {
1018            if !(track.clips.is_empty() && track.transitions.is_empty()) {
1019                return Err(ModelError::InvalidCaptions {
1020                    track: track.id.clone(),
1021                });
1022            }
1023            match captions.validate() {
1024                Ok(()) => true,
1025                Err(crate::caption::CaptionIssue::Invalid) => false,
1026                Err(crate::caption::CaptionIssue::UnknownStyle { cue, name }) => {
1027                    return Err(ModelError::UnknownCaptionStyle {
1028                        track: track.id.clone(),
1029                        cue,
1030                        name,
1031                    });
1032                }
1033                Err(crate::caption::CaptionIssue::CueStyle { cue }) => {
1034                    return Err(ModelError::InvalidCaptionCueStyle {
1035                        track: track.id.clone(),
1036                        cue,
1037                    });
1038                }
1039            }
1040        }
1041        (TrackKind::Caption, None) => false,
1042        (_, captions) => captions.is_none(),
1043    };
1044    if valid {
1045        Ok(())
1046    } else {
1047        Err(ModelError::InvalidCaptions {
1048            track: track.id.clone(),
1049        })
1050    }
1051}
1052
1053/// Checks one source. A generated source has a valid generator and nothing a host would
1054/// supply; any other source has a locator and no generator, and an image has no audio. A
1055/// declared color is HDR exactly when its transfer is PQ or HLG. `canvas` is the project's,
1056/// which a layout's pixel lengths refer to.
1057fn validate_source_content(source: &MediaSource, canvas: (u32, u32)) -> Result<(), ModelError> {
1058    if let Some(fingerprint) = &source.fingerprint
1059        && (source.kind == MediaKind::Generated || !fingerprint.is_valid())
1060    {
1061        return Err(ModelError::InvalidFingerprint {
1062            source: source.id.clone(),
1063        });
1064    }
1065    if source
1066        .color_metadata
1067        .is_some_and(|color| !color.is_consistent())
1068    {
1069        return Err(ModelError::ContradictoryColor {
1070            source: source.id.clone(),
1071        });
1072    }
1073    if let Some(provider) = &source.provider
1074        && (provider.kind() != source.kind || source.has_audio || !provider.is_valid())
1075    {
1076        return Err(ModelError::InvalidProvider {
1077            source: source.id.clone(),
1078        });
1079    }
1080    if source.kind == MediaKind::Composition {
1081        // Whether the composition exists is checked with the compositions.
1082        let valid = source.composition.is_some()
1083            && source.generator.is_none()
1084            && source.locator.is_empty()
1085            && source.color_metadata.is_none()
1086            && source.fingerprint.is_none()
1087            && source.provider.is_none()
1088            && !source.has_audio;
1089        return if valid {
1090            Ok(())
1091        } else {
1092            Err(ModelError::InvalidCompositionSource {
1093                source: source.id.clone(),
1094            })
1095        };
1096    }
1097    if source.composition.is_some() {
1098        return Err(ModelError::InvalidCompositionSource {
1099            source: source.id.clone(),
1100        });
1101    }
1102    if source.kind == MediaKind::Generated {
1103        let owner = || crate::ShapeOwner::Source(source.id.clone());
1104        match source
1105            .generator
1106            .as_ref()
1107            .map(|generator| generator.validate_on(canvas.0, canvas.1))
1108        {
1109            Some(Err(crate::GeneratorIssue::Shape(issue))) => {
1110                return Err(ModelError::InvalidShape {
1111                    owner: owner(),
1112                    at: issue.at,
1113                    problem: issue.problem,
1114                });
1115            }
1116            Some(Err(crate::GeneratorIssue::Layout(issue))) => {
1117                return Err(ModelError::InvalidLayout {
1118                    owner: owner(),
1119                    at: issue.at,
1120                    problem: issue.problem,
1121                });
1122            }
1123            _ => {}
1124        }
1125        let valid = source.generator.as_ref().is_some_and(Generator::is_valid)
1126            && source.locator.is_empty()
1127            && source.color_metadata.is_none()
1128            && !source.has_audio;
1129        return if valid {
1130            Ok(())
1131        } else {
1132            Err(ModelError::InvalidGenerator {
1133                source: source.id.clone(),
1134            })
1135        };
1136    }
1137    if source.generator.is_some() {
1138        return Err(ModelError::InvalidGenerator {
1139            source: source.id.clone(),
1140        });
1141    }
1142    if let Some(checked) = validate_fileless_source(source) {
1143        return checked;
1144    }
1145    if source.locator.is_empty() {
1146        return Err(ModelError::EmptyLocator {
1147            source: source.id.clone(),
1148        });
1149    }
1150    if source.kind == MediaKind::Image && source.has_audio {
1151        return Err(ModelError::AudioOnImage {
1152            source: source.id.clone(),
1153        });
1154    }
1155    Ok(())
1156}
1157
1158/// Checks a source whose provider reads no file has no locator or fingerprint. `None` for any
1159/// source whose media is a file.
1160fn validate_fileless_source(source: &MediaSource) -> Option<Result<(), ModelError>> {
1161    let provider = source.provider.as_ref()?;
1162    (!provider.reads_file()).then(|| {
1163        if source.locator.is_empty() && source.fingerprint.is_none() {
1164            Ok(())
1165        } else {
1166            Err(ModelError::InvalidProvider {
1167                source: source.id.clone(),
1168            })
1169        }
1170    })
1171}
1172
1173fn ensure_id<T: fmt::Display>(id: &T) -> Result<(), ModelError> {
1174    if id.to_string().is_empty() {
1175        Err(ModelError::EmptyIdentifier)
1176    } else {
1177        Ok(())
1178    }
1179}
1180
1181/// Output-wide settings independent of a renderer or encoder.
1182#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1183#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1184#[serde(deny_unknown_fields)]
1185#[non_exhaustive]
1186pub struct ProjectSettings {
1187    /// Canvas width in output pixels, at most [`MAX_CANVAS_DIMENSION`].
1188    pub width: u32,
1189    /// Canvas height in output pixels, at most [`MAX_CANVAS_DIMENSION`]. The canvas is at most
1190    /// [`MAX_CANVAS_PIXELS`] in area.
1191    pub height: u32,
1192    /// Timeline frame rate.
1193    pub frame_rate: FrameRate,
1194    /// Internal audio sample rate, within [`SAMPLE_RATE_RANGE`].
1195    pub sample_rate: u32,
1196    /// Opaque color under every layer, in preview and export alike, so empty canvas is never
1197    /// left to a host or encoder.
1198    #[serde(default)]
1199    pub background: Rgb,
1200    /// The space in which clips' blend modes are evaluated, in preview and export alike.
1201    #[serde(default)]
1202    pub blend_space: BlendSpace,
1203    /// How sources' colors come into the working space.
1204    #[serde(default)]
1205    pub color: ColorPipeline,
1206}
1207
1208/// How sources' colors come into the working space.
1209///
1210/// The working space is display-referred linear light with BT.709 primaries, `1.0` being SDR
1211/// white (100 nits); every export is SDR BT.709. SDR sources decode through the sRGB EOTF and
1212/// wide-gamut ones are converted to BT.709. An HDR (PQ or HLG) source is either refused or
1213/// linearized, converted to BT.709, and tone-mapped from [`Self::hdr_peak_nits`] to SDR white
1214/// by the ITU-R BT.2390 EETF on each pixel's largest component, preserving hue.
1215#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1216#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1217#[serde(deny_unknown_fields)]
1218pub struct ColorPipeline {
1219    /// What an HDR source does.
1220    #[serde(default)]
1221    pub hdr: HdrSources,
1222    /// The luminance, in nits, HDR sources are taken to peak at: PQ above it is clipped, HLG is
1223    /// displayed at it, and the tone map brings it to SDR white. Within [`HDR_PEAK_NITS_RANGE`].
1224    #[serde(default = "default_hdr_peak")]
1225    pub hdr_peak_nits: u32,
1226}
1227
1228/// Supported [`ColorPipeline::hdr_peak_nits`]: SDR white to PQ's ceiling.
1229pub const HDR_PEAK_NITS_RANGE: std::ops::RangeInclusive<u32> = 100..=10_000;
1230
1231const fn default_hdr_peak() -> u32 {
1232    1_000
1233}
1234
1235impl Default for ColorPipeline {
1236    fn default() -> Self {
1237        Self {
1238            hdr: HdrSources::default(),
1239            hdr_peak_nits: default_hdr_peak(),
1240        }
1241    }
1242}
1243
1244/// What a project does with HDR sources.
1245#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1246#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1247#[serde(rename_all = "snake_case")]
1248pub enum HdrSources {
1249    /// Tone-map them into the SDR working space.
1250    #[default]
1251    ToneMap,
1252    /// Refuse to render them.
1253    Reject,
1254}
1255
1256/// The color space in which blend modes are evaluated.
1257///
1258/// Compositing is always premultiplied; this chooses what the blend formulas see. Contrast
1259/// modes such as overlay and soft-light match design tools only in
1260/// [`BlendSpace::SrgbEncoded`].
1261#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1262#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1263#[serde(rename_all = "snake_case")]
1264pub enum BlendSpace {
1265    /// Linear light, where blending is physically meaningful.
1266    #[default]
1267    LinearLight,
1268    /// sRGB-encoded values, as design tools and CSS blend.
1269    SrgbEncoded,
1270}
1271
1272/// An opaque color as a color picker shows it: straight, sRGB-encoded components in `0..=1`.
1273#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
1274#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1275#[serde(deny_unknown_fields)]
1276pub struct Rgb {
1277    /// Red component.
1278    pub red: f32,
1279    /// Green component.
1280    pub green: f32,
1281    /// Blue component.
1282    pub blue: f32,
1283}
1284
1285impl Rgb {
1286    /// Opaque black, the default background.
1287    pub const BLACK: Self = Self::new(0.0, 0.0, 0.0);
1288
1289    /// Creates a color from sRGB-encoded components.
1290    #[must_use]
1291    pub const fn new(red: f32, green: f32, blue: f32) -> Self {
1292        Self { red, green, blue }
1293    }
1294
1295    fn is_valid(self) -> bool {
1296        [self.red, self.green, self.blue]
1297            .into_iter()
1298            .all(|component| component.is_finite() && (0.0..=1.0).contains(&component))
1299    }
1300}
1301
1302impl ProjectSettings {
1303    /// Creates validated output settings.
1304    ///
1305    /// # Errors
1306    /// Returns a model error when dimensions or sample rate exceed supported bounds.
1307    pub fn new(
1308        width: u32,
1309        height: u32,
1310        frame_rate: FrameRate,
1311        sample_rate: u32,
1312    ) -> Result<Self, ModelError> {
1313        let settings = Self {
1314            width,
1315            height,
1316            frame_rate,
1317            sample_rate,
1318            background: Rgb::BLACK,
1319            blend_space: BlendSpace::LinearLight,
1320            color: ColorPipeline::default(),
1321        };
1322        settings.validate()?;
1323        Ok(settings)
1324    }
1325
1326    /// Replaces the background color.
1327    ///
1328    /// # Errors
1329    /// Returns [`ModelError::InvalidBackground`] for a non-finite or out-of-range component.
1330    pub fn with_background(mut self, background: Rgb) -> Result<Self, ModelError> {
1331        self.background = background;
1332        self.validate()?;
1333        Ok(self)
1334    }
1335
1336    fn validate(&self) -> Result<(), ModelError> {
1337        if !HDR_PEAK_NITS_RANGE.contains(&self.color.hdr_peak_nits) {
1338            return Err(ModelError::InvalidColorPipeline);
1339        }
1340        if self.width == 0 || self.height == 0 {
1341            return Err(ModelError::ZeroCanvasDimension);
1342        }
1343        if self.width > MAX_CANVAS_DIMENSION || self.height > MAX_CANVAS_DIMENSION {
1344            return Err(ModelError::CanvasDimensionTooLarge {
1345                width: self.width,
1346                height: self.height,
1347                maximum: MAX_CANVAS_DIMENSION,
1348            });
1349        }
1350        let pixels = u64::from(self.width) * u64::from(self.height);
1351        if pixels > MAX_CANVAS_PIXELS {
1352            return Err(ModelError::CanvasPixelBudgetExceeded {
1353                pixels,
1354                maximum: MAX_CANVAS_PIXELS,
1355            });
1356        }
1357        if !self.background.is_valid() {
1358            return Err(ModelError::InvalidBackground);
1359        }
1360        if !SAMPLE_RATE_RANGE.contains(&self.sample_rate) {
1361            return Err(ModelError::UnsupportedSampleRate {
1362                found: self.sample_rate,
1363                minimum: *SAMPLE_RATE_RANGE.start(),
1364                maximum: *SAMPLE_RATE_RANGE.end(),
1365            });
1366        }
1367        Ok(())
1368    }
1369}