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