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
10pub const CURRENT_SCHEMA_VERSION: u32 = 1;
12pub const MAX_PROJECT_JSON_BYTES: usize = 64 * 1024 * 1024;
14pub const MAX_CANVAS_DIMENSION: u32 = alpha2_media::MAX_FRAME_DIMENSION;
16pub const MAX_CANVAS_PIXELS: u64 = alpha2_media::MAX_FRAME_PIXELS;
18pub const SAMPLE_RATE_RANGE: std::ops::RangeInclusive<u32> = 8_000..=96_000;
23pub const MAX_TRACKS: usize = 256;
25pub const MAX_CLIPS: usize = 100_000;
27pub const MAX_CLIPS_PER_TRACK: usize = 4_096;
29pub const MAX_TRANSITIONS_PER_TRACK: usize = 4_096;
31pub const MAX_EFFECT_RESOURCES: usize = 10_000;
33
34#[derive(Clone, Debug, PartialEq, Serialize)]
36pub struct Project {
37 pub schema_version: u32,
39 pub id: ProjectId,
41 pub name: String,
43 pub settings: ProjectSettings,
45 pub sources: Vec<MediaSource>,
47 #[serde(default)]
49 pub effect_resources: Vec<EffectResource>,
50 #[serde(default)]
52 pub compositions: Vec<Composition>,
53 pub timeline: Timeline,
55 #[serde(default)]
57 pub audio: MasterAudio,
58 #[serde(default, skip_serializing_if = "Vec::is_empty")]
61 pub data: Vec<crate::DataSet>,
62}
63
64#[derive(Deserialize)]
69#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
70#[cfg_attr(feature = "schema", schemars(rename = "Project"))]
71#[serde(deny_unknown_fields)]
72pub(crate) struct ProjectWire {
73 #[serde(rename = "$schema", default)]
76 #[allow(dead_code)]
77 pub(crate) schema_url: Option<String>,
78 #[cfg_attr(feature = "schema", schemars(extend("const" = CURRENT_SCHEMA_VERSION)))]
80 pub(crate) schema_version: u32,
81 pub(crate) id: ProjectId,
83 pub(crate) name: String,
85 pub(crate) settings: ProjectSettings,
87 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIPS }>")]
89 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIPS)))]
90 pub(crate) sources: Vec<MediaSource>,
91 #[serde(default)]
93 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EFFECT_RESOURCES }>")]
94 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EFFECT_RESOURCES)))]
95 pub(crate) effect_resources: Vec<EffectResource>,
96 #[serde(default)]
98 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_COMPOSITIONS }>")]
99 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_COMPOSITIONS)))]
100 pub(crate) compositions: Vec<Composition>,
101 pub(crate) timeline: Timeline,
103 #[serde(default)]
105 pub(crate) audio: MasterAudio,
106 #[serde(default)]
108 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_DATA_SETS }>")]
109 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_SETS)))]
110 pub(crate) data: Vec<crate::DataSet>,
111}
112
113impl TryFrom<ProjectWire> for Project {
114 type Error = ModelError;
115
116 fn try_from(wire: ProjectWire) -> Result<Self, Self::Error> {
117 let project = Self {
118 schema_version: wire.schema_version,
119 id: wire.id,
120 name: wire.name,
121 settings: wire.settings,
122 sources: wire.sources,
123 effect_resources: wire.effect_resources,
124 compositions: wire.compositions,
125 timeline: wire.timeline,
126 audio: wire.audio,
127 data: wire.data,
128 };
129 project.validate()?;
130 Ok(project)
131 }
132}
133
134impl<'de> Deserialize<'de> for Project {
135 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
136 where
137 D: Deserializer<'de>,
138 {
139 let wire = ProjectWire::deserialize(deserializer)?;
140 Self::try_from(wire).map_err(D::Error::custom)
141 }
142}
143
144impl Project {
145 pub fn from_json(json: &str) -> Result<Self, ProjectLoadError> {
153 #[derive(Deserialize)]
156 struct VersionProbe {
157 schema_version: u32,
158 }
159
160 if json.len() > MAX_PROJECT_JSON_BYTES {
161 return Err(ProjectLoadError::TooLarge {
162 bytes: json.len(),
163 maximum: MAX_PROJECT_JSON_BYTES,
164 });
165 }
166 if let Ok(VersionProbe { schema_version }) = serde_json::from_str(json)
167 && schema_version != CURRENT_SCHEMA_VERSION
168 {
169 return Err(ProjectLoadError::InvalidProject(
170 ModelError::UnsupportedSchemaVersion {
171 found: schema_version,
172 },
173 ));
174 }
175 let wire = serde_json::from_str::<ProjectWire>(json).map_err(ProjectLoadError::Json)?;
176 Self::try_from(wire).map_err(ProjectLoadError::InvalidProject)
177 }
178
179 pub fn to_json(&self) -> Result<String, ProjectWriteError> {
188 struct Capped(Vec<u8>);
189
190 impl std::io::Write for Capped {
191 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
192 if self.0.len() + bytes.len() > MAX_PROJECT_JSON_BYTES {
193 return Err(std::io::Error::from(std::io::ErrorKind::FileTooLarge));
194 }
195 self.0.extend_from_slice(bytes);
196 Ok(bytes.len())
197 }
198
199 fn flush(&mut self) -> std::io::Result<()> {
200 Ok(())
201 }
202 }
203
204 let mut out = Capped(Vec::with_capacity(4096));
205 match serde_json::to_writer(&mut out, self) {
206 Ok(()) => Ok(String::from_utf8(out.0).expect("serde_json writes UTF-8")),
207 Err(error) if error.io_error_kind() == Some(std::io::ErrorKind::FileTooLarge) => {
208 Err(ProjectWriteError::TooLarge {
209 maximum: MAX_PROJECT_JSON_BYTES,
210 })
211 }
212 Err(error) => Err(ProjectWriteError::Json(error)),
213 }
214 }
215
216 #[must_use]
225 pub fn used_sources(&self) -> Vec<&MediaSource> {
226 let sources = self
227 .sources
228 .iter()
229 .map(|source| (&source.id, source))
230 .collect::<HashMap<_, _>>();
231 let compositions = self
232 .compositions
233 .iter()
234 .map(|composition| (&composition.id, composition))
235 .collect::<HashMap<_, _>>();
236 let reads = crate::CompositionReads::new(&compositions);
237 let mut used = HashSet::new();
238 let mut walked = HashSet::new();
239 let mut pending = Vec::new();
240 for clip in self.timeline.tracks.iter().flat_map(|track| &track.clips) {
241 used.insert(&clip.source_id);
242 let drawn = clip
245 .composition
246 .as_ref()
247 .is_none_or(|reference| reads.draws_clip(&reference.id));
248 pending.extend(
249 sources
250 .get(&clip.source_id)
251 .and_then(|source| source.composition.as_ref())
252 .filter(|_| drawn),
253 );
254 pending.extend(clip.composition.as_ref().map(|reference| &reference.id));
255 }
256 while let Some(id) = pending.pop() {
259 if !walked.insert(id) {
260 continue;
261 }
262 let Some(composition) = compositions.get(id) else {
263 continue;
264 };
265 let nodes = composition
266 .nodes
267 .iter()
268 .map(|node| (&node.id, node))
269 .collect::<HashMap<_, _>>();
270 let mut reached = HashSet::new();
271 let mut frontier = composition.output.iter().collect::<Vec<_>>();
272 while let Some(node) = frontier.pop() {
273 let Some(node) = nodes.get(node).filter(|_| reached.insert(node)) else {
274 continue;
275 };
276 match &node.op {
277 crate::NodeOp::Media { source_id, .. } => {
278 used.insert(source_id);
279 pending.extend(
280 sources
281 .get(source_id)
282 .and_then(|source| source.composition.as_ref()),
283 );
284 }
285 crate::NodeOp::Group { composition, .. } => pending.push(composition),
286 _ => {}
287 }
288 frontier.extend(
289 reads
290 .needed_inputs(node)
291 .into_iter()
292 .filter_map(crate::NodeInput::node),
293 );
294 }
295 }
296 self.sources
297 .iter()
298 .filter(|source| used.contains(&source.id))
299 .collect()
300 }
301
302 #[must_use]
306 pub fn hdr_sources(&self) -> Vec<&alpha2_media::SourceId> {
307 self.sources
308 .iter()
309 .filter(|source| source.effective_color_metadata().is_hdr())
310 .map(|source| &source.id)
311 .collect()
312 }
313
314 #[must_use]
318 pub fn draws_text(&self) -> bool {
319 let is_text = |generator: &crate::Generator| {
320 matches!(
321 generator,
322 crate::Generator::Text { .. } | crate::Generator::Layout { .. }
323 )
324 };
325 self.timeline
326 .tracks
327 .iter()
328 .any(|track| track.captions.is_some())
329 || self
330 .sources
331 .iter()
332 .any(|source| source.generator.as_ref().is_some_and(is_text))
333 || self.compositions.iter().any(|composition| {
334 composition.nodes.iter().any(|node| {
335 matches!(&node.op, crate::NodeOp::Generator { generator } if is_text(generator))
336 })
337 })
338 }
339
340 #[must_use]
343 pub fn extent(&self) -> Option<alpha2_time::TimeRange> {
344 let words = self
345 .timeline
346 .tracks
347 .iter()
348 .filter_map(|track| track.captions.as_ref()?.from_words.as_ref())
349 .filter_map(|from| self.data.iter().find(|set| set.id == from.data))
350 .filter(|set| set.anchor == crate::DataAnchor::Timeline)
351 .filter_map(|set| match &set.values {
352 crate::DataValues::Words(words) => Some((
353 words.first()?.start,
354 words.iter().map(|word| word.end).max()?,
355 )),
356 _ => None,
357 });
358 let mut bounds = self
359 .timeline
360 .extent()
361 .map(|range| (range.start(), range.end()));
362 for (start, end) in words {
363 bounds =
364 Some(bounds.map_or((start, end), |(low, high)| (low.min(start), high.max(end))));
365 }
366 bounds.and_then(|(start, end)| alpha2_time::TimeRange::new(start, end).ok())
367 }
368
369 #[must_use]
373 pub fn default_export_range(&self) -> Option<alpha2_time::TimeRange> {
374 let end = self.extent()?.end();
375 let range = alpha2_time::TimeRange::new(alpha2_time::MediaTime::ZERO, end).ok()?;
376 (end > alpha2_time::MediaTime::ZERO).then_some(range)
377 }
378
379 #[must_use]
381 pub fn new(id: ProjectId, name: impl Into<String>, settings: ProjectSettings) -> Self {
382 Self {
383 schema_version: CURRENT_SCHEMA_VERSION,
384 id,
385 name: name.into(),
386 settings,
387 sources: Vec::new(),
388 effect_resources: Vec::new(),
389 compositions: Vec::new(),
390 timeline: Timeline { tracks: Vec::new() },
391 audio: MasterAudio::default(),
392 data: Vec::new(),
393 }
394 }
395
396 pub fn validate(&self) -> Result<(), ModelError> {
401 if self.schema_version != CURRENT_SCHEMA_VERSION {
402 return Err(ModelError::UnsupportedSchemaVersion {
403 found: self.schema_version,
404 });
405 }
406 self.settings.validate()?;
407 ensure_id(&self.id)?;
408 if !self.audio.validate() {
409 return Err(ModelError::InvalidMasterAudio);
410 }
411 if self.sources.len() > MAX_CLIPS {
412 return Err(ModelError::TooManySources {
413 found: self.sources.len(),
414 maximum: MAX_CLIPS,
415 });
416 }
417 if self.timeline.tracks.len() > MAX_TRACKS {
418 return Err(ModelError::TooManyTracks {
419 found: self.timeline.tracks.len(),
420 maximum: MAX_TRACKS,
421 });
422 }
423
424 let sources = self.validate_sources()?;
425 let effect_resource_ids = self.validate_effect_resources()?;
426 let inlined = crate::composition::validate_compositions(
427 &self.compositions,
428 &self.sources,
429 &sources,
430 &effect_resource_ids,
431 (self.settings.width, self.settings.height),
432 )?;
433 let index = DocumentIndex {
434 sources,
435 compositions: self
436 .compositions
437 .iter()
438 .map(|composition| &composition.id)
439 .collect(),
440 };
441
442 let mut track_ids = HashSet::new();
443 let mut clip_ids = HashSet::new();
444 let mut clip_count = 0_usize;
445 for track in &self.timeline.tracks {
446 ensure_id(&track.id)?;
447 if !track_ids.insert(&track.id) {
448 return Err(ModelError::DuplicateTrackId(track.id.clone()));
449 }
450 if track.clips.len() > MAX_CLIPS_PER_TRACK {
451 return Err(ModelError::TooManyClipsOnTrack {
452 track: track.id.clone(),
453 found: track.clips.len(),
454 maximum: MAX_CLIPS_PER_TRACK,
455 });
456 }
457 validate_captions(track)?;
458 if track.transitions.len() > MAX_TRANSITIONS_PER_TRACK {
459 return Err(ModelError::TooManyTransitions {
460 track: track.id.clone(),
461 found: track.transitions.len(),
462 maximum: MAX_TRANSITIONS_PER_TRACK,
463 });
464 }
465 clip_count =
466 clip_count
467 .checked_add(track.clips.len())
468 .ok_or(ModelError::TooManyClips {
469 found: usize::MAX,
470 maximum: MAX_CLIPS,
471 })?;
472 if clip_count > MAX_CLIPS {
473 return Err(ModelError::TooManyClips {
474 found: clip_count,
475 maximum: MAX_CLIPS,
476 });
477 }
478 for clip in &track.clips {
479 validate_clip(&index, track, clip, &mut clip_ids)?;
480 }
481 for transition in &track.transitions {
482 ensure_effect_resources_exist(
483 &transition.effect,
484 &effect_resource_ids,
485 &transition.to_clip,
486 )?;
487 }
488 ensure_transitions_are_supported(track)?;
489 ensure_transition_effects_match_builtins(track)?;
490 if !track.audio.validate() {
491 return Err(ModelError::InvalidTrackAudio {
492 track: track.id.clone(),
493 });
494 }
495 ensure_overlaps_have_transitions(track)?;
496 }
497 self.ensure_audio_effects_fit()?;
498 crate::data_places::validate_data(self, &index.sources)?;
499 ensure_ducking_is_acyclic(&self.timeline)?;
500 ensure_mattes_are_usable(&self.timeline)?;
501 ensure_frames_fit(&self.timeline, &index.sources, &inlined)?;
502 crate::time_bound::ensure_times_are_writable(self)
503 }
504
505 fn validate_sources(
507 &self,
508 ) -> Result<HashMap<&alpha2_media::SourceId, &MediaSource>, ModelError> {
509 let mut sources = HashMap::with_capacity(self.sources.len());
510 for source in &self.sources {
511 ensure_id(&source.id)?;
512 validate_source_content(source, (self.settings.width, self.settings.height))?;
513 if sources.insert(&source.id, source).is_some() {
514 return Err(ModelError::DuplicateSourceId(source.id.clone()));
515 }
516 }
517 Ok(sources)
518 }
519
520 fn ensure_audio_effects_fit(&self) -> Result<(), ModelError> {
523 let load = self.audio_effect_load();
524 if load.effects > crate::MAX_AUDIO_EFFECTS {
525 return Err(ModelError::TooManyAudioEffects {
526 found: load.effects,
527 maximum: crate::MAX_AUDIO_EFFECTS,
528 at_ticks: load.effects_at_ticks,
529 });
530 }
531 if load.delay_ms() > u64::from(crate::MAX_AUDIO_DELAY_MS) {
532 return Err(ModelError::TooMuchAudioDelay {
533 found_ms: load.delay_ms(),
534 maximum_ms: crate::MAX_AUDIO_DELAY_MS,
535 at_ticks: load.delay_at_ticks,
536 });
537 }
538 Ok(())
539 }
540
541 fn validate_effect_resources(&self) -> Result<HashSet<&EffectResourceId>, ModelError> {
542 if self.effect_resources.len() > MAX_EFFECT_RESOURCES {
543 return Err(ModelError::TooManyEffectResources {
544 found: self.effect_resources.len(),
545 maximum: MAX_EFFECT_RESOURCES,
546 });
547 }
548 let mut ids = HashSet::new();
549 for resource in &self.effect_resources {
550 ensure_id(&resource.id)?;
551 if resource.locator.is_empty() {
552 return Err(ModelError::EmptyEffectResourceLocator {
553 resource: resource.id.clone(),
554 });
555 }
556 if !ids.insert(&resource.id) {
557 return Err(ModelError::DuplicateEffectResourceId(resource.id.clone()));
558 }
559 }
560 Ok(ids)
561 }
562}
563
564fn ensure_effect_resources_exist(
565 effect: &crate::ClipEffect,
566 known: &HashSet<&EffectResourceId>,
567 clip: &crate::ClipId,
568) -> Result<(), ModelError> {
569 for resource in effect.resources.values() {
570 if !known.contains(resource) {
571 return Err(ModelError::UnknownEffectResource {
572 clip: clip.clone(),
573 resource: resource.clone(),
574 });
575 }
576 }
577 Ok(())
578}
579
580fn validate_clip<'a>(
582 index: &DocumentIndex<'a>,
583 track: &'a crate::Track,
584 clip: &'a crate::Clip,
585 clip_ids: &mut HashSet<&'a crate::ClipId>,
586) -> Result<(), ModelError> {
587 ensure_id(&clip.id)?;
588 if clip.timeline_range.is_empty() || clip.source_range.is_empty() {
589 return Err(ModelError::EmptyClipRange {
590 clip: clip.id.clone(),
591 });
592 }
593 if clip.timeline_range.start().ticks() < 0 || clip.source_range.start().ticks() < 0 {
594 return Err(ModelError::NegativeClipRange {
595 clip: clip.id.clone(),
596 });
597 }
598 if !clip_ids.insert(&clip.id) {
599 return Err(ModelError::DuplicateClipId(clip.id.clone()));
600 }
601 let Some(source) = index.sources.get(&clip.source_id) else {
602 return Err(ModelError::UnknownClipSource {
603 clip: clip.id.clone(),
604 source: clip.source_id.clone(),
605 });
606 };
607 if !track.kind.accepts(source.kind) {
608 return Err(ModelError::IncompatibleClipSource {
609 clip: clip.id.clone(),
610 track: track.id.clone(),
611 source: source.id.clone(),
612 });
613 }
614 if !clip.visual.validate() {
615 return Err(ModelError::InvalidVisualProperties {
616 clip: clip.id.clone(),
617 });
618 }
619 if let Some(composition) = &clip.composition {
620 let held = || {
623 let last = MediaTime::from_ticks(clip.timeline_range.end().ticks().saturating_sub(1));
624 composition
625 .local_time(clip.timeline_range.start(), last)
626 .is_some_and(|time| time.ticks() <= alpha2_time::MAX_SERIALIZED_TICKS)
627 };
628 if track.kind != TrackKind::Video || !composition.scale.is_valid() || !held() {
629 return Err(ModelError::InvalidClipComposition {
630 clip: clip.id.clone(),
631 });
632 }
633 if !index.compositions.contains(&composition.id) {
634 return Err(ModelError::UnknownComposition {
635 clip: clip.id.clone(),
636 composition: composition.id.clone(),
637 });
638 }
639 }
640 if !clip.audio.validate() {
641 return Err(ModelError::InvalidAudioProperties {
642 clip: clip.id.clone(),
643 });
644 }
645 let visual = track.kind == TrackKind::Video;
646 if clip.masks.len() > crate::MAX_CLIP_MASKS || (!visual && !clip.masks.is_empty()) {
647 return Err(ModelError::InvalidClipMask {
648 clip: clip.id.clone(),
649 });
650 }
651 crate::mask::validate_masks(&clip.masks).map_err(|issue| ModelError::InvalidShape {
652 owner: crate::ShapeOwner::Clip(clip.id.clone()),
653 at: issue.at,
654 problem: issue.problem,
655 })?;
656 if !visual && clip.matte.is_some() {
657 return Err(ModelError::InvalidMatte {
658 clip: clip.id.clone(),
659 });
660 }
661 if let crate::TimeMap::Freeze { source_time } = clip.time_map
662 && !clip.source_range.contains(source_time)
663 {
664 return Err(ModelError::InvalidTimeMap {
665 clip: clip.id.clone(),
666 });
667 }
668 if let crate::TimeMap::Loop { .. } = clip.time_map {
669 let length = |range: alpha2_time::TimeRange| range.duration().map_or(0, MediaTime::ticks);
670 let found = crate::loop_passes(length(clip.timeline_range), length(clip.source_range));
671 if found > crate::MAX_LOOP_PASSES {
672 return Err(ModelError::TooManyLoopPasses {
673 clip: clip.id.clone(),
674 found,
675 maximum: crate::MAX_LOOP_PASSES,
676 });
677 }
678 }
679 Ok(())
680}
681
682struct DocumentIndex<'a> {
684 sources: HashMap<&'a alpha2_media::SourceId, &'a MediaSource>,
685 compositions: HashSet<&'a crate::CompositionId>,
686}
687
688fn ensure_transitions_are_supported(track: &crate::Track) -> Result<(), ModelError> {
691 let clips = track
692 .clips
693 .iter()
694 .map(|clip| (&clip.id, clip))
695 .collect::<HashMap<_, _>>();
696 let mut pairs = HashSet::with_capacity(track.transitions.len());
697 for transition in &track.transitions {
698 let covers = |id: &crate::ClipId| {
699 clips.get(id).is_some_and(|clip| {
700 clip.timeline_range.start() <= transition.timeline_range.start()
701 && clip.timeline_range.end() >= transition.timeline_range.end()
702 })
703 };
704 let valid = track.kind == TrackKind::Video
705 && transition.from_clip != transition.to_clip
706 && !transition.timeline_range.is_empty()
707 && transition.easing.is_valid()
708 && transition.effect.is_valid()
709 && covers(&transition.from_clip)
710 && covers(&transition.to_clip);
711 if !valid {
712 return Err(ModelError::InvalidClipTransition {
713 track: track.id.clone(),
714 });
715 }
716 let pair = if transition.from_clip < transition.to_clip {
719 (&transition.from_clip, &transition.to_clip)
720 } else {
721 (&transition.to_clip, &transition.from_clip)
722 };
723 if !pairs.insert(pair) {
724 return Err(ModelError::DuplicateTransition {
725 track: track.id.clone(),
726 first: transition.from_clip.clone(),
727 second: transition.to_clip.clone(),
728 });
729 }
730 }
731 Ok(())
732}
733
734fn ensure_transition_effects_match_builtins(track: &crate::Track) -> Result<(), ModelError> {
736 for transition in &track.transitions {
737 crate::effect_spec::check_builtin(&transition.effect, crate::EffectKind::Transition, None)
738 .map_err(|problem| ModelError::InvalidEffect {
739 owner: Box::new(crate::EffectOwner::Transition {
740 track: track.id.clone(),
741 from: transition.from_clip.clone(),
742 to: transition.to_clip.clone(),
743 }),
744 id: transition.effect.id.clone(),
745 problem,
746 })?;
747 }
748 Ok(())
749}
750
751fn ensure_ducking_is_acyclic(timeline: &Timeline) -> Result<(), ModelError> {
758 fn sidechain_of(track: &crate::Track) -> Option<&crate::TrackId> {
759 track
760 .audio
761 .ducking
762 .as_ref()
763 .map(|ducking| &ducking.sidechain_track)
764 }
765 let positions = timeline
767 .tracks
768 .iter()
769 .enumerate()
770 .map(|(position, track)| (&track.id, position))
771 .collect::<HashMap<_, _>>();
772 let next = timeline
773 .tracks
774 .iter()
775 .map(|track| sidechain_of(track).and_then(|sidechain| positions.get(sidechain).copied()))
776 .collect::<Vec<_>>();
777 let cyclic = tracks_on_cycles(&next);
778 for ((track, next), on_cycle) in timeline.tracks.iter().zip(next).zip(cyclic) {
779 let Some(sidechain) = sidechain_of(track) else {
780 continue;
781 };
782 if next.is_none() || on_cycle {
784 return Err(ModelError::InvalidDuckingSidechain {
785 track: track.id.clone(),
786 sidechain: sidechain.clone(),
787 });
788 }
789 }
790 Ok(())
791}
792
793fn tracks_on_cycles(next: &[Option<usize>]) -> Vec<bool> {
800 const UNVISITED: usize = usize::MAX;
801 let mut cyclic = vec![false; next.len()];
802 let mut walk_of = vec![UNVISITED; next.len()];
804 for start in 0..next.len() {
805 let mut cursor = Some(start);
806 while let Some(position) = cursor {
807 match walk_of[position] {
808 UNVISITED => {
809 walk_of[position] = start;
810 cursor = next[position];
811 }
812 walk if walk == start => {
813 let mut member = position;
815 loop {
816 cyclic[member] = true;
817 match next[member] {
818 Some(following) if following != position => member = following,
819 _ => break,
820 }
821 }
822 break;
823 }
824 _ => break,
825 }
826 }
827 }
828 cyclic
829}
830
831fn ensure_mattes_are_usable(timeline: &Timeline) -> Result<(), ModelError> {
837 let visual = timeline
838 .tracks
839 .iter()
840 .filter(|track| track.kind == TrackKind::Video)
841 .flat_map(|track| track.clips.iter().map(|clip| (&clip.id, clip)))
842 .collect::<HashMap<_, _>>();
843 let in_transition = timeline
844 .tracks
845 .iter()
846 .flat_map(|track| &track.transitions)
847 .flat_map(|transition| [&transition.from_clip, &transition.to_clip])
848 .collect::<HashSet<_>>();
849 let clips = timeline
851 .tracks
852 .iter()
853 .filter(|track| track.kind == TrackKind::Video)
854 .flat_map(|track| &track.clips);
855 for clip in clips {
856 let Some(matte) = &clip.matte else {
857 continue;
858 };
859 let usable = matte.source != clip.id
860 && visual
861 .get(&matte.source)
862 .is_some_and(|source| source.matte.is_none())
863 && !in_transition.contains(&matte.source);
864 if !usable {
865 return Err(ModelError::InvalidMatte {
866 clip: clip.id.clone(),
867 });
868 }
869 }
870 Ok(())
871}
872
873fn ensure_frames_fit(
880 timeline: &Timeline,
881 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
882 inlined: &crate::composition::InlinedNodes<'_>,
883) -> Result<(), ModelError> {
884 let nodes = |id: Option<&crate::CompositionId>| id.and_then(|id| inlined.get(id)).copied();
885 let mut edges = Vec::new();
887 for clip in timeline.tracks.iter().flat_map(|track| &track.clips) {
888 let source = sources
889 .get(&clip.source_id)
890 .and_then(|source| source.composition.as_ref());
891 let drawn = nodes(clip.composition.as_ref().map(|reference| &reference.id))
892 .unwrap_or(0)
893 .saturating_add(nodes(source).unwrap_or(0));
894 if drawn > 0 {
895 edges.push((clip.timeline_range.start(), true, drawn, &clip.id));
896 edges.push((clip.timeline_range.end(), false, drawn, &clip.id));
897 }
898 }
899 edges.sort_by_key(|&(time, starts, ..)| (time, starts));
902 let mut drawn = 0_u64;
903 let mut edges = edges.into_iter().peekable();
904 while let Some((time, starts, nodes, clip)) = edges.next() {
905 if !starts {
906 drawn -= nodes;
907 continue;
908 }
909 drawn = drawn.saturating_add(nodes);
910 while let Some((_, _, nodes, _)) =
912 edges.next_if(|&(next, next_starts, ..)| next == time && next_starts)
913 {
914 drawn = drawn.saturating_add(nodes);
915 }
916 if drawn > crate::MAX_FRAME_INLINED_NODES as u64 {
917 return Err(ModelError::FrameDrawsTooManyNodes {
918 clip: clip.clone(),
919 found: drawn,
920 maximum: crate::MAX_FRAME_INLINED_NODES,
921 });
922 }
923 }
924 Ok(())
925}
926
927pub(crate) fn ensure_overlaps_have_transitions(track: &crate::Track) -> Result<(), ModelError> {
932 if track.kind != TrackKind::Video {
933 return Ok(());
934 }
935 let transitions = track
936 .transitions
937 .iter()
938 .flat_map(|transition| {
939 [
940 (
941 &transition.from_clip,
942 &transition.to_clip,
943 transition.timeline_range,
944 ),
945 (
946 &transition.to_clip,
947 &transition.from_clip,
948 transition.timeline_range,
949 ),
950 ]
951 })
952 .collect::<HashSet<_>>();
953 let directed = track
954 .transitions
955 .iter()
956 .map(|transition| (&transition.from_clip, &transition.to_clip))
957 .collect::<HashSet<_>>();
958 let mut ordered = track.clips.iter().collect::<Vec<_>>();
959 ordered.sort_by_key(|clip| (clip.timeline_range.start(), clip.timeline_range.end()));
960 let mut active = Vec::new();
961 for second in ordered {
962 active.retain(|first: &&crate::Clip| {
963 first.timeline_range.end() > second.timeline_range.start()
964 });
965 for first in &active {
966 let Some(intersection) = first.timeline_range.intersection(second.timeline_range)
967 else {
968 continue;
969 };
970 if !transitions.contains(&(&first.id, &second.id, intersection)) {
971 return Err(ModelError::OverlappingClips {
972 track: track.id.clone(),
973 first: first.id.clone(),
974 second: second.id.clone(),
975 });
976 }
977 }
978 active.push(second);
979 if active.len() >= 3 {
984 let mut leads = active
985 .iter()
986 .map(|from| {
987 active
988 .iter()
989 .filter(|to| directed.contains(&(&from.id, &to.id)))
990 .count()
991 })
992 .collect::<Vec<_>>();
993 leads.sort_unstable();
994 if leads.iter().enumerate().any(|(rank, lead)| rank != *lead) {
995 return Err(ModelError::TransitionCycle {
996 track: track.id.clone(),
997 at: second.timeline_range.start(),
998 });
999 }
1000 }
1001 }
1002 Ok(())
1003}
1004
1005fn validate_captions(track: &crate::Track) -> Result<(), ModelError> {
1007 if let Some(captions) = &track.captions
1008 && captions.cues.len() > MAX_CLIPS_PER_TRACK
1009 {
1010 return Err(ModelError::TooManyCaptionCues {
1011 track: track.id.clone(),
1012 found: captions.cues.len(),
1013 maximum: MAX_CLIPS_PER_TRACK,
1014 });
1015 }
1016 let valid = match (&track.kind, &track.captions) {
1017 (TrackKind::Caption, Some(captions)) => {
1018 if !(track.clips.is_empty() && track.transitions.is_empty()) {
1019 return Err(ModelError::InvalidCaptions {
1020 track: track.id.clone(),
1021 });
1022 }
1023 match captions.validate() {
1024 Ok(()) => true,
1025 Err(crate::caption::CaptionIssue::Invalid) => false,
1026 Err(crate::caption::CaptionIssue::UnknownStyle { cue, name }) => {
1027 return Err(ModelError::UnknownCaptionStyle {
1028 track: track.id.clone(),
1029 cue,
1030 name,
1031 });
1032 }
1033 Err(crate::caption::CaptionIssue::CueStyle { cue }) => {
1034 return Err(ModelError::InvalidCaptionCueStyle {
1035 track: track.id.clone(),
1036 cue,
1037 });
1038 }
1039 }
1040 }
1041 (TrackKind::Caption, None) => false,
1042 (_, captions) => captions.is_none(),
1043 };
1044 if valid {
1045 Ok(())
1046 } else {
1047 Err(ModelError::InvalidCaptions {
1048 track: track.id.clone(),
1049 })
1050 }
1051}
1052
1053fn validate_source_content(source: &MediaSource, canvas: (u32, u32)) -> Result<(), ModelError> {
1058 if let Some(fingerprint) = &source.fingerprint
1059 && (source.kind == MediaKind::Generated || !fingerprint.is_valid())
1060 {
1061 return Err(ModelError::InvalidFingerprint {
1062 source: source.id.clone(),
1063 });
1064 }
1065 if source
1066 .color_metadata
1067 .is_some_and(|color| !color.is_consistent())
1068 {
1069 return Err(ModelError::ContradictoryColor {
1070 source: source.id.clone(),
1071 });
1072 }
1073 if let Some(provider) = &source.provider
1074 && (provider.kind() != source.kind || source.has_audio || !provider.is_valid())
1075 {
1076 return Err(ModelError::InvalidProvider {
1077 source: source.id.clone(),
1078 });
1079 }
1080 if source.kind == MediaKind::Composition {
1081 let valid = source.composition.is_some()
1083 && source.generator.is_none()
1084 && source.locator.is_empty()
1085 && source.color_metadata.is_none()
1086 && source.fingerprint.is_none()
1087 && source.provider.is_none()
1088 && !source.has_audio;
1089 return if valid {
1090 Ok(())
1091 } else {
1092 Err(ModelError::InvalidCompositionSource {
1093 source: source.id.clone(),
1094 })
1095 };
1096 }
1097 if source.composition.is_some() {
1098 return Err(ModelError::InvalidCompositionSource {
1099 source: source.id.clone(),
1100 });
1101 }
1102 if source.kind == MediaKind::Generated {
1103 let owner = || crate::ShapeOwner::Source(source.id.clone());
1104 match source
1105 .generator
1106 .as_ref()
1107 .map(|generator| generator.validate_on(canvas.0, canvas.1))
1108 {
1109 Some(Err(crate::GeneratorIssue::Shape(issue))) => {
1110 return Err(ModelError::InvalidShape {
1111 owner: owner(),
1112 at: issue.at,
1113 problem: issue.problem,
1114 });
1115 }
1116 Some(Err(crate::GeneratorIssue::Layout(issue))) => {
1117 return Err(ModelError::InvalidLayout {
1118 owner: owner(),
1119 at: issue.at,
1120 problem: issue.problem,
1121 });
1122 }
1123 _ => {}
1124 }
1125 let valid = source.generator.as_ref().is_some_and(Generator::is_valid)
1126 && source.locator.is_empty()
1127 && source.color_metadata.is_none()
1128 && !source.has_audio;
1129 return if valid {
1130 Ok(())
1131 } else {
1132 Err(ModelError::InvalidGenerator {
1133 source: source.id.clone(),
1134 })
1135 };
1136 }
1137 if source.generator.is_some() {
1138 return Err(ModelError::InvalidGenerator {
1139 source: source.id.clone(),
1140 });
1141 }
1142 if let Some(checked) = validate_fileless_source(source) {
1143 return checked;
1144 }
1145 if source.locator.is_empty() {
1146 return Err(ModelError::EmptyLocator {
1147 source: source.id.clone(),
1148 });
1149 }
1150 if source.kind == MediaKind::Image && source.has_audio {
1151 return Err(ModelError::AudioOnImage {
1152 source: source.id.clone(),
1153 });
1154 }
1155 Ok(())
1156}
1157
1158fn validate_fileless_source(source: &MediaSource) -> Option<Result<(), ModelError>> {
1161 let provider = source.provider.as_ref()?;
1162 (!provider.reads_file()).then(|| {
1163 if source.locator.is_empty() && source.fingerprint.is_none() {
1164 Ok(())
1165 } else {
1166 Err(ModelError::InvalidProvider {
1167 source: source.id.clone(),
1168 })
1169 }
1170 })
1171}
1172
1173fn ensure_id<T: fmt::Display>(id: &T) -> Result<(), ModelError> {
1174 if id.to_string().is_empty() {
1175 Err(ModelError::EmptyIdentifier)
1176 } else {
1177 Ok(())
1178 }
1179}
1180
1181#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1183#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1184#[serde(deny_unknown_fields)]
1185#[non_exhaustive]
1186pub struct ProjectSettings {
1187 pub width: u32,
1189 pub height: u32,
1192 pub frame_rate: FrameRate,
1194 pub sample_rate: u32,
1196 #[serde(default)]
1199 pub background: Rgb,
1200 #[serde(default)]
1202 pub blend_space: BlendSpace,
1203 #[serde(default)]
1205 pub color: ColorPipeline,
1206}
1207
1208#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1216#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1217#[serde(deny_unknown_fields)]
1218pub struct ColorPipeline {
1219 #[serde(default)]
1221 pub hdr: HdrSources,
1222 #[serde(default = "default_hdr_peak")]
1225 pub hdr_peak_nits: u32,
1226}
1227
1228pub const HDR_PEAK_NITS_RANGE: std::ops::RangeInclusive<u32> = 100..=10_000;
1230
1231const fn default_hdr_peak() -> u32 {
1232 1_000
1233}
1234
1235impl Default for ColorPipeline {
1236 fn default() -> Self {
1237 Self {
1238 hdr: HdrSources::default(),
1239 hdr_peak_nits: default_hdr_peak(),
1240 }
1241 }
1242}
1243
1244#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1246#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1247#[serde(rename_all = "snake_case")]
1248pub enum HdrSources {
1249 #[default]
1251 ToneMap,
1252 Reject,
1254}
1255
1256#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1262#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1263#[serde(rename_all = "snake_case")]
1264pub enum BlendSpace {
1265 #[default]
1267 LinearLight,
1268 SrgbEncoded,
1270}
1271
1272#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
1274#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1275#[serde(deny_unknown_fields)]
1276pub struct Rgb {
1277 pub red: f32,
1279 pub green: f32,
1281 pub blue: f32,
1283}
1284
1285impl Rgb {
1286 pub const BLACK: Self = Self::new(0.0, 0.0, 0.0);
1288
1289 #[must_use]
1291 pub const fn new(red: f32, green: f32, blue: f32) -> Self {
1292 Self { red, green, blue }
1293 }
1294
1295 fn is_valid(self) -> bool {
1296 [self.red, self.green, self.blue]
1297 .into_iter()
1298 .all(|component| component.is_finite() && (0.0..=1.0).contains(&component))
1299 }
1300}
1301
1302impl ProjectSettings {
1303 pub fn new(
1308 width: u32,
1309 height: u32,
1310 frame_rate: FrameRate,
1311 sample_rate: u32,
1312 ) -> Result<Self, ModelError> {
1313 let settings = Self {
1314 width,
1315 height,
1316 frame_rate,
1317 sample_rate,
1318 background: Rgb::BLACK,
1319 blend_space: BlendSpace::LinearLight,
1320 color: ColorPipeline::default(),
1321 };
1322 settings.validate()?;
1323 Ok(settings)
1324 }
1325
1326 pub fn with_background(mut self, background: Rgb) -> Result<Self, ModelError> {
1331 self.background = background;
1332 self.validate()?;
1333 Ok(self)
1334 }
1335
1336 fn validate(&self) -> Result<(), ModelError> {
1337 if !HDR_PEAK_NITS_RANGE.contains(&self.color.hdr_peak_nits) {
1338 return Err(ModelError::InvalidColorPipeline);
1339 }
1340 if self.width == 0 || self.height == 0 {
1341 return Err(ModelError::ZeroCanvasDimension);
1342 }
1343 if self.width > MAX_CANVAS_DIMENSION || self.height > MAX_CANVAS_DIMENSION {
1344 return Err(ModelError::CanvasDimensionTooLarge {
1345 width: self.width,
1346 height: self.height,
1347 maximum: MAX_CANVAS_DIMENSION,
1348 });
1349 }
1350 let pixels = u64::from(self.width) * u64::from(self.height);
1351 if pixels > MAX_CANVAS_PIXELS {
1352 return Err(ModelError::CanvasPixelBudgetExceeded {
1353 pixels,
1354 maximum: MAX_CANVAS_PIXELS,
1355 });
1356 }
1357 if !self.background.is_valid() {
1358 return Err(ModelError::InvalidBackground);
1359 }
1360 if !SAMPLE_RATE_RANGE.contains(&self.sample_rate) {
1361 return Err(ModelError::UnsupportedSampleRate {
1362 found: self.sample_rate,
1363 minimum: *SAMPLE_RATE_RANGE.start(),
1364 maximum: *SAMPLE_RATE_RANGE.end(),
1365 });
1366 }
1367 Ok(())
1368 }
1369}