Skip to main content

alpha2_model/
project.rs

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