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
11pub const CURRENT_SCHEMA_VERSION: u32 = 1;
13pub const MAX_PROJECT_JSON_BYTES: usize = 64 * 1024 * 1024;
15pub const MAX_CANVAS_DIMENSION: u32 = alpha2_media::MAX_FRAME_DIMENSION;
17pub const MAX_CANVAS_PIXELS: u64 = alpha2_media::MAX_FRAME_PIXELS;
19pub const SAMPLE_RATE_RANGE: std::ops::RangeInclusive<u32> = 8_000..=96_000;
24pub const MAX_TRACKS: usize = 256;
26pub const MAX_CLIPS: usize = 100_000;
28pub const MAX_CLIPS_PER_TRACK: usize = 4_096;
30pub const MAX_TRANSITIONS_PER_TRACK: usize = 4_096;
32pub const MAX_EFFECT_RESOURCES: usize = 10_000;
34pub const ADJUSTMENT_TRANSITION_ID: &str = "alpha2.transition.fade";
36
37#[derive(Clone, Debug, PartialEq, Serialize)]
39pub struct Project {
40 pub schema_version: u32,
42 pub id: ProjectId,
44 pub name: String,
46 pub settings: ProjectSettings,
48 pub sources: Vec<MediaSource>,
50 #[serde(default)]
52 pub effect_resources: Vec<EffectResource>,
53 #[serde(default)]
55 pub compositions: Vec<Composition>,
56 pub timeline: Timeline,
58 #[serde(default)]
60 pub audio: MasterAudio,
61 #[serde(default, skip_serializing_if = "Vec::is_empty")]
64 pub data: Vec<crate::DataSet>,
65}
66
67#[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 #[serde(rename = "$schema", default)]
79 #[allow(dead_code)]
80 pub(crate) schema_url: Option<String>,
81 #[cfg_attr(feature = "schema", schemars(extend("const" = CURRENT_SCHEMA_VERSION)))]
83 pub(crate) schema_version: u32,
84 pub(crate) id: ProjectId,
86 pub(crate) name: String,
88 pub(crate) settings: ProjectSettings,
90 #[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 #[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 #[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 pub(crate) timeline: Timeline,
106 #[serde(default)]
108 pub(crate) audio: MasterAudio,
109 #[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 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 #[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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 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 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 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
743fn 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 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
849struct 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
879fn 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 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
963fn 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
980fn 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 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
1030fn 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 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 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 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
1102pub(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 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
1180fn 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
1287fn 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 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
1392fn 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#[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 pub width: u32,
1423 pub height: u32,
1426 pub frame_rate: FrameRate,
1428 pub sample_rate: u32,
1430 #[serde(default)]
1433 pub background: Rgb,
1434 #[serde(default)]
1436 pub blend_space: BlendSpace,
1437 #[serde(default)]
1439 pub color: ColorPipeline,
1440 #[serde(default, skip_serializing_if = "crate::Shutter::is_default")]
1443 pub shutter: crate::Shutter,
1444}
1445
1446#[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 #[serde(default)]
1459 pub hdr: HdrSources,
1460 #[serde(default = "default_hdr_peak")]
1463 pub hdr_peak_nits: u32,
1464}
1465
1466pub 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#[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 #[default]
1489 ToneMap,
1490 Reject,
1492}
1493
1494#[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 #[default]
1505 LinearLight,
1506 SrgbEncoded,
1508}
1509
1510#[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 pub red: f32,
1517 pub green: f32,
1519 pub blue: f32,
1521}
1522
1523impl Rgb {
1524 pub const BLACK: Self = Self::new(0.0, 0.0, 0.0);
1526
1527 #[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 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 pub fn with_background(mut self, background: Rgb) -> Result<Self, ModelError> {
1570 self.background = background;
1571 self.validate()?;
1572 Ok(self)
1573 }
1574
1575 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}