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;
33pub const ADJUSTMENT_TRANSITION_ID: &str = "alpha2.transition.fade";
35
36#[derive(Clone, Debug, PartialEq, Serialize)]
38pub struct Project {
39 pub schema_version: u32,
41 pub id: ProjectId,
43 pub name: String,
45 pub settings: ProjectSettings,
47 pub sources: Vec<MediaSource>,
49 #[serde(default)]
51 pub effect_resources: Vec<EffectResource>,
52 #[serde(default)]
54 pub compositions: Vec<Composition>,
55 pub timeline: Timeline,
57 #[serde(default)]
59 pub audio: MasterAudio,
60 #[serde(default, skip_serializing_if = "Vec::is_empty")]
63 pub data: Vec<crate::DataSet>,
64}
65
66#[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 #[serde(rename = "$schema", default)]
78 #[allow(dead_code)]
79 pub(crate) schema_url: Option<String>,
80 #[cfg_attr(feature = "schema", schemars(extend("const" = CURRENT_SCHEMA_VERSION)))]
82 pub(crate) schema_version: u32,
83 pub(crate) id: ProjectId,
85 pub(crate) name: String,
87 pub(crate) settings: ProjectSettings,
89 #[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 #[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 #[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 pub(crate) timeline: Timeline,
105 #[serde(default)]
107 pub(crate) audio: MasterAudio,
108 #[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 pub fn from_json(json: &str) -> Result<Self, ProjectLoadError> {
155 #[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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 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 sources = self.validate_sources()?;
427 let effect_resource_ids = self.validate_effect_resources()?;
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 {
436 sources,
437 compositions: self
438 .compositions
439 .iter()
440 .map(|composition| &composition.id)
441 .collect(),
442 };
443
444 let mut track_ids = HashSet::new();
445 let mut clip_ids = HashSet::new();
446 let mut clip_count = 0_usize;
447 for track in &self.timeline.tracks {
448 ensure_id(&track.id)?;
449 if !track_ids.insert(&track.id) {
450 return Err(ModelError::DuplicateTrackId(track.id.clone()));
451 }
452 if track.clips.len() > MAX_CLIPS_PER_TRACK {
453 return Err(ModelError::TooManyClipsOnTrack {
454 track: track.id.clone(),
455 found: track.clips.len(),
456 maximum: MAX_CLIPS_PER_TRACK,
457 });
458 }
459 validate_captions(track)?;
460 if track.transitions.len() > MAX_TRANSITIONS_PER_TRACK {
461 return Err(ModelError::TooManyTransitions {
462 track: track.id.clone(),
463 found: track.transitions.len(),
464 maximum: MAX_TRANSITIONS_PER_TRACK,
465 });
466 }
467 clip_count =
468 clip_count
469 .checked_add(track.clips.len())
470 .ok_or(ModelError::TooManyClips {
471 found: usize::MAX,
472 maximum: MAX_CLIPS,
473 })?;
474 if clip_count > MAX_CLIPS {
475 return Err(ModelError::TooManyClips {
476 found: clip_count,
477 maximum: MAX_CLIPS,
478 });
479 }
480 for clip in &track.clips {
481 validate_clip(&index, track, clip, &mut clip_ids)?;
482 }
483 for transition in &track.transitions {
484 ensure_effect_resources_exist(
485 &transition.effect,
486 &effect_resource_ids,
487 &transition.to_clip,
488 )?;
489 }
490 ensure_transitions_are_supported(track, &index.sources)?;
491 ensure_transition_effects_match_builtins(track)?;
492 if !track.audio.validate() {
493 return Err(ModelError::InvalidTrackAudio {
494 track: track.id.clone(),
495 });
496 }
497 ensure_overlaps_have_transitions(track)?;
498 }
499 self.ensure_audio_effects_fit()?;
500 crate::data_places::validate_data(self, &index.sources)?;
501 ensure_ducking_is_acyclic(&self.timeline)?;
502 ensure_mattes_are_usable(&self.timeline, &index.sources)?;
503 ensure_frames_fit(&self.timeline, &index.sources, &inlined)?;
504 crate::time_bound::ensure_times_are_writable(self)
505 }
506
507 fn validate_sources(
509 &self,
510 ) -> Result<HashMap<&alpha2_media::SourceId, &MediaSource>, ModelError> {
511 let mut sources = HashMap::with_capacity(self.sources.len());
512 for source in &self.sources {
513 ensure_id(&source.id)?;
514 if source.kind == MediaKind::Adjustment {
515 if *source != MediaSource::adjustment(source.id.clone()) {
516 return Err(ModelError::InvalidAdjustmentSource {
517 source: source.id.clone(),
518 });
519 }
520 } else {
521 validate_source_content(source, (self.settings.width, self.settings.height))?;
522 }
523 if sources.insert(&source.id, source).is_some() {
524 return Err(ModelError::DuplicateSourceId(source.id.clone()));
525 }
526 }
527 Ok(sources)
528 }
529
530 fn ensure_audio_effects_fit(&self) -> Result<(), ModelError> {
533 let load = self.audio_effect_load();
534 if load.effects > crate::MAX_AUDIO_EFFECTS {
535 return Err(ModelError::TooManyAudioEffects {
536 found: load.effects,
537 maximum: crate::MAX_AUDIO_EFFECTS,
538 at_ticks: load.effects_at_ticks,
539 });
540 }
541 if load.delay_ms() > u64::from(crate::MAX_AUDIO_DELAY_MS) {
542 return Err(ModelError::TooMuchAudioDelay {
543 found_ms: load.delay_ms(),
544 maximum_ms: crate::MAX_AUDIO_DELAY_MS,
545 at_ticks: load.delay_at_ticks,
546 });
547 }
548 Ok(())
549 }
550
551 fn validate_effect_resources(&self) -> Result<HashSet<&EffectResourceId>, ModelError> {
552 if self.effect_resources.len() > MAX_EFFECT_RESOURCES {
553 return Err(ModelError::TooManyEffectResources {
554 found: self.effect_resources.len(),
555 maximum: MAX_EFFECT_RESOURCES,
556 });
557 }
558 let mut ids = HashSet::new();
559 for resource in &self.effect_resources {
560 ensure_id(&resource.id)?;
561 if resource.locator.is_empty() {
562 return Err(ModelError::EmptyEffectResourceLocator {
563 resource: resource.id.clone(),
564 });
565 }
566 if !ids.insert(&resource.id) {
567 return Err(ModelError::DuplicateEffectResourceId(resource.id.clone()));
568 }
569 }
570 Ok(ids)
571 }
572}
573
574fn ensure_effect_resources_exist(
575 effect: &crate::ClipEffect,
576 known: &HashSet<&EffectResourceId>,
577 clip: &crate::ClipId,
578) -> Result<(), ModelError> {
579 for resource in effect.resources.values() {
580 if !known.contains(resource) {
581 return Err(ModelError::UnknownEffectResource {
582 clip: clip.clone(),
583 resource: resource.clone(),
584 });
585 }
586 }
587 Ok(())
588}
589
590fn validate_clip<'a>(
592 index: &DocumentIndex<'a>,
593 track: &'a crate::Track,
594 clip: &'a crate::Clip,
595 clip_ids: &mut HashSet<&'a crate::ClipId>,
596) -> Result<(), ModelError> {
597 ensure_id(&clip.id)?;
598 if clip.timeline_range.is_empty() || clip.source_range.is_empty() {
599 return Err(ModelError::EmptyClipRange {
600 clip: clip.id.clone(),
601 });
602 }
603 if clip.timeline_range.start().ticks() < 0 || clip.source_range.start().ticks() < 0 {
604 return Err(ModelError::NegativeClipRange {
605 clip: clip.id.clone(),
606 });
607 }
608 if !clip_ids.insert(&clip.id) {
609 return Err(ModelError::DuplicateClipId(clip.id.clone()));
610 }
611 let Some(source) = index.sources.get(&clip.source_id) else {
612 return Err(ModelError::UnknownClipSource {
613 clip: clip.id.clone(),
614 source: clip.source_id.clone(),
615 });
616 };
617 if !track.kind.accepts(source.kind) {
618 return Err(ModelError::IncompatibleClipSource {
619 clip: clip.id.clone(),
620 track: track.id.clone(),
621 source: source.id.clone(),
622 });
623 }
624 if !clip.visual.validate() {
625 return Err(ModelError::InvalidVisualProperties {
626 clip: clip.id.clone(),
627 });
628 }
629 if let Some(composition) = &clip.composition {
630 let held = || {
633 let last = MediaTime::from_ticks(clip.timeline_range.end().ticks().saturating_sub(1));
634 composition
635 .local_time(clip.timeline_range.start(), last)
636 .is_some_and(|time| time.ticks() <= alpha2_time::MAX_SERIALIZED_TICKS)
637 };
638 if track.kind != TrackKind::Video || !composition.scale.is_valid() || !held() {
639 return Err(ModelError::InvalidClipComposition {
640 clip: clip.id.clone(),
641 });
642 }
643 if !index.compositions.contains(&composition.id) {
644 return Err(ModelError::UnknownComposition {
645 clip: clip.id.clone(),
646 composition: composition.id.clone(),
647 });
648 }
649 }
650 if !clip.audio.validate() {
651 return Err(ModelError::InvalidAudioProperties {
652 clip: clip.id.clone(),
653 });
654 }
655 let visual = track.kind == TrackKind::Video;
656 if clip.masks.len() > crate::MAX_CLIP_MASKS || (!visual && !clip.masks.is_empty()) {
657 return Err(ModelError::InvalidClipMask {
658 clip: clip.id.clone(),
659 });
660 }
661 crate::mask::validate_masks(&clip.masks).map_err(|issue| ModelError::InvalidShape {
662 owner: crate::ShapeOwner::Clip(clip.id.clone()),
663 at: issue.at,
664 problem: issue.problem,
665 })?;
666 if (!visual || source.kind == MediaKind::Adjustment) && clip.matte.is_some() {
667 return Err(ModelError::InvalidMatte {
668 clip: clip.id.clone(),
669 });
670 }
671 if let crate::TimeMap::Freeze { source_time } = clip.time_map
672 && !clip.source_range.contains(source_time)
673 {
674 return Err(ModelError::InvalidTimeMap {
675 clip: clip.id.clone(),
676 });
677 }
678 if let crate::TimeMap::Loop { .. } = clip.time_map {
679 let length = |range: alpha2_time::TimeRange| range.duration().map_or(0, MediaTime::ticks);
680 let found = crate::loop_passes(length(clip.timeline_range), length(clip.source_range));
681 if found > crate::MAX_LOOP_PASSES {
682 return Err(ModelError::TooManyLoopPasses {
683 clip: clip.id.clone(),
684 found,
685 maximum: crate::MAX_LOOP_PASSES,
686 });
687 }
688 }
689 Ok(())
690}
691
692struct DocumentIndex<'a> {
694 sources: HashMap<&'a alpha2_media::SourceId, &'a MediaSource>,
695 compositions: HashSet<&'a crate::CompositionId>,
696}
697
698fn ensure_transitions_are_supported(
702 track: &crate::Track,
703 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
704) -> Result<(), ModelError> {
705 let clips = track
706 .clips
707 .iter()
708 .map(|clip| (&clip.id, clip))
709 .collect::<HashMap<_, _>>();
710 let mut pairs = HashSet::with_capacity(track.transitions.len());
711 for transition in &track.transitions {
712 let covers = |id: &crate::ClipId| {
713 clips.get(id).is_some_and(|clip| {
714 clip.timeline_range.start() <= transition.timeline_range.start()
715 && clip.timeline_range.end() >= transition.timeline_range.end()
716 })
717 };
718 let valid = track.kind == TrackKind::Video
719 && transition.from_clip != transition.to_clip
720 && !transition.timeline_range.is_empty()
721 && transition.easing.is_valid()
722 && transition.effect.is_valid()
723 && covers(&transition.from_clip)
724 && covers(&transition.to_clip);
725 if !valid {
726 return Err(ModelError::InvalidClipTransition {
727 track: track.id.clone(),
728 });
729 }
730 let pair = if transition.from_clip < transition.to_clip {
733 (&transition.from_clip, &transition.to_clip)
734 } else {
735 (&transition.to_clip, &transition.from_clip)
736 };
737 if !pairs.insert(pair) {
738 return Err(ModelError::DuplicateTransition {
739 track: track.id.clone(),
740 first: transition.from_clip.clone(),
741 second: transition.to_clip.clone(),
742 });
743 }
744 }
745 ensure_adjustments_only_fade(track, sources)
746}
747
748fn ensure_adjustments_only_fade(
749 track: &crate::Track,
750 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
751) -> Result<(), ModelError> {
752 let adjustments = track
753 .clips
754 .iter()
755 .filter(|clip| {
756 sources
757 .get(&clip.source_id)
758 .is_some_and(|source| source.kind == MediaKind::Adjustment)
759 })
760 .map(|clip| &clip.id)
761 .collect::<HashSet<_>>();
762 if adjustments.is_empty() {
763 return Ok(());
764 }
765 for transition in &track.transitions {
766 if transition.effect.id == ADJUSTMENT_TRANSITION_ID {
767 continue;
768 }
769 if let Some(clip) = [&transition.from_clip, &transition.to_clip]
770 .into_iter()
771 .find(|clip| adjustments.contains(clip))
772 {
773 return Err(ModelError::InvalidAdjustmentTransition {
774 track: track.id.clone(),
775 clip: clip.clone(),
776 });
777 }
778 }
779 Ok(())
780}
781
782fn ensure_transition_effects_match_builtins(track: &crate::Track) -> Result<(), ModelError> {
784 for transition in &track.transitions {
785 crate::effect_spec::check_builtin(&transition.effect, crate::EffectKind::Transition, None)
786 .map_err(|problem| ModelError::InvalidEffect {
787 owner: Box::new(crate::EffectOwner::Transition {
788 track: track.id.clone(),
789 from: transition.from_clip.clone(),
790 to: transition.to_clip.clone(),
791 }),
792 id: transition.effect.id.clone(),
793 problem,
794 })?;
795 }
796 Ok(())
797}
798
799fn ensure_ducking_is_acyclic(timeline: &Timeline) -> Result<(), ModelError> {
806 fn sidechain_of(track: &crate::Track) -> Option<&crate::TrackId> {
807 track
808 .audio
809 .ducking
810 .as_ref()
811 .map(|ducking| &ducking.sidechain_track)
812 }
813 let positions = timeline
815 .tracks
816 .iter()
817 .enumerate()
818 .map(|(position, track)| (&track.id, position))
819 .collect::<HashMap<_, _>>();
820 let next = timeline
821 .tracks
822 .iter()
823 .map(|track| sidechain_of(track).and_then(|sidechain| positions.get(sidechain).copied()))
824 .collect::<Vec<_>>();
825 let cyclic = tracks_on_cycles(&next);
826 for ((track, next), on_cycle) in timeline.tracks.iter().zip(next).zip(cyclic) {
827 let Some(sidechain) = sidechain_of(track) else {
828 continue;
829 };
830 if next.is_none() || on_cycle {
832 return Err(ModelError::InvalidDuckingSidechain {
833 track: track.id.clone(),
834 sidechain: sidechain.clone(),
835 });
836 }
837 }
838 Ok(())
839}
840
841fn tracks_on_cycles(next: &[Option<usize>]) -> Vec<bool> {
848 const UNVISITED: usize = usize::MAX;
849 let mut cyclic = vec![false; next.len()];
850 let mut walk_of = vec![UNVISITED; next.len()];
852 for start in 0..next.len() {
853 let mut cursor = Some(start);
854 while let Some(position) = cursor {
855 match walk_of[position] {
856 UNVISITED => {
857 walk_of[position] = start;
858 cursor = next[position];
859 }
860 walk if walk == start => {
861 let mut member = position;
863 loop {
864 cyclic[member] = true;
865 match next[member] {
866 Some(following) if following != position => member = following,
867 _ => break,
868 }
869 }
870 break;
871 }
872 _ => break,
873 }
874 }
875 }
876 cyclic
877}
878
879fn ensure_mattes_are_usable(
885 timeline: &Timeline,
886 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
887) -> Result<(), ModelError> {
888 let visual = timeline
889 .tracks
890 .iter()
891 .filter(|track| track.kind == TrackKind::Video)
892 .flat_map(|track| track.clips.iter().map(|clip| (&clip.id, clip)))
893 .filter(|(_, clip)| {
894 sources
895 .get(&clip.source_id)
896 .is_none_or(|source| source.kind != MediaKind::Adjustment)
897 })
898 .collect::<HashMap<_, _>>();
899 let in_transition = timeline
900 .tracks
901 .iter()
902 .flat_map(|track| &track.transitions)
903 .flat_map(|transition| [&transition.from_clip, &transition.to_clip])
904 .collect::<HashSet<_>>();
905 let clips = timeline
907 .tracks
908 .iter()
909 .filter(|track| track.kind == TrackKind::Video)
910 .flat_map(|track| &track.clips);
911 for clip in clips {
912 let Some(matte) = &clip.matte else {
913 continue;
914 };
915 let usable = matte.source != clip.id
916 && visual
917 .get(&matte.source)
918 .is_some_and(|source| source.matte.is_none())
919 && !in_transition.contains(&matte.source);
920 if !usable {
921 return Err(ModelError::InvalidMatte {
922 clip: clip.id.clone(),
923 });
924 }
925 }
926 Ok(())
927}
928
929fn ensure_frames_fit(
936 timeline: &Timeline,
937 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
938 inlined: &crate::composition::InlinedNodes<'_>,
939) -> Result<(), ModelError> {
940 let nodes = |id: Option<&crate::CompositionId>| id.and_then(|id| inlined.get(id)).copied();
941 let mut edges = Vec::new();
943 for clip in timeline.tracks.iter().flat_map(|track| &track.clips) {
944 let source = sources
945 .get(&clip.source_id)
946 .and_then(|source| source.composition.as_ref());
947 let drawn = nodes(clip.composition.as_ref().map(|reference| &reference.id))
948 .unwrap_or(0)
949 .saturating_add(nodes(source).unwrap_or(0));
950 if drawn > 0 {
951 edges.push((clip.timeline_range.start(), true, drawn, &clip.id));
952 edges.push((clip.timeline_range.end(), false, drawn, &clip.id));
953 }
954 }
955 edges.sort_by_key(|&(time, starts, ..)| (time, starts));
958 let mut drawn = 0_u64;
959 let mut edges = edges.into_iter().peekable();
960 while let Some((time, starts, nodes, clip)) = edges.next() {
961 if !starts {
962 drawn -= nodes;
963 continue;
964 }
965 drawn = drawn.saturating_add(nodes);
966 while let Some((_, _, nodes, _)) =
968 edges.next_if(|&(next, next_starts, ..)| next == time && next_starts)
969 {
970 drawn = drawn.saturating_add(nodes);
971 }
972 if drawn > crate::MAX_FRAME_INLINED_NODES as u64 {
973 return Err(ModelError::FrameDrawsTooManyNodes {
974 clip: clip.clone(),
975 found: drawn,
976 maximum: crate::MAX_FRAME_INLINED_NODES,
977 });
978 }
979 }
980 Ok(())
981}
982
983pub(crate) fn ensure_overlaps_have_transitions(track: &crate::Track) -> Result<(), ModelError> {
988 if track.kind != TrackKind::Video {
989 return Ok(());
990 }
991 let transitions = track
992 .transitions
993 .iter()
994 .flat_map(|transition| {
995 [
996 (
997 &transition.from_clip,
998 &transition.to_clip,
999 transition.timeline_range,
1000 ),
1001 (
1002 &transition.to_clip,
1003 &transition.from_clip,
1004 transition.timeline_range,
1005 ),
1006 ]
1007 })
1008 .collect::<HashSet<_>>();
1009 let directed = track
1010 .transitions
1011 .iter()
1012 .map(|transition| (&transition.from_clip, &transition.to_clip))
1013 .collect::<HashSet<_>>();
1014 let mut ordered = track.clips.iter().collect::<Vec<_>>();
1015 ordered.sort_by_key(|clip| (clip.timeline_range.start(), clip.timeline_range.end()));
1016 let mut active = Vec::new();
1017 for second in ordered {
1018 active.retain(|first: &&crate::Clip| {
1019 first.timeline_range.end() > second.timeline_range.start()
1020 });
1021 for first in &active {
1022 let Some(intersection) = first.timeline_range.intersection(second.timeline_range)
1023 else {
1024 continue;
1025 };
1026 if !transitions.contains(&(&first.id, &second.id, intersection)) {
1027 return Err(ModelError::OverlappingClips {
1028 track: track.id.clone(),
1029 first: first.id.clone(),
1030 second: second.id.clone(),
1031 });
1032 }
1033 }
1034 active.push(second);
1035 if active.len() >= 3 {
1040 let mut leads = active
1041 .iter()
1042 .map(|from| {
1043 active
1044 .iter()
1045 .filter(|to| directed.contains(&(&from.id, &to.id)))
1046 .count()
1047 })
1048 .collect::<Vec<_>>();
1049 leads.sort_unstable();
1050 if leads.iter().enumerate().any(|(rank, lead)| rank != *lead) {
1051 return Err(ModelError::TransitionCycle {
1052 track: track.id.clone(),
1053 at: second.timeline_range.start(),
1054 });
1055 }
1056 }
1057 }
1058 Ok(())
1059}
1060
1061fn validate_captions(track: &crate::Track) -> Result<(), ModelError> {
1063 if let Some(captions) = &track.captions
1064 && captions.cues.len() > MAX_CLIPS_PER_TRACK
1065 {
1066 return Err(ModelError::TooManyCaptionCues {
1067 track: track.id.clone(),
1068 found: captions.cues.len(),
1069 maximum: MAX_CLIPS_PER_TRACK,
1070 });
1071 }
1072 let valid = match (&track.kind, &track.captions) {
1073 (TrackKind::Caption, Some(captions)) => {
1074 if !(track.clips.is_empty() && track.transitions.is_empty()) {
1075 return Err(ModelError::InvalidCaptions {
1076 track: track.id.clone(),
1077 });
1078 }
1079 match captions.validate() {
1080 Ok(()) => true,
1081 Err(crate::caption::CaptionIssue::Invalid) => false,
1082 Err(crate::caption::CaptionIssue::UnknownStyle { cue, name }) => {
1083 return Err(ModelError::UnknownCaptionStyle {
1084 track: track.id.clone(),
1085 cue,
1086 name,
1087 });
1088 }
1089 Err(crate::caption::CaptionIssue::CueStyle { cue }) => {
1090 return Err(ModelError::InvalidCaptionCueStyle {
1091 track: track.id.clone(),
1092 cue,
1093 });
1094 }
1095 }
1096 }
1097 (TrackKind::Caption, None) => false,
1098 (_, captions) => captions.is_none(),
1099 };
1100 if valid {
1101 Ok(())
1102 } else {
1103 Err(ModelError::InvalidCaptions {
1104 track: track.id.clone(),
1105 })
1106 }
1107}
1108
1109pub(crate) fn generator_error(
1110 owner: crate::ShapeOwner,
1111 issue: crate::GeneratorIssue,
1112) -> Option<ModelError> {
1113 Some(match issue {
1114 crate::GeneratorIssue::Invalid => return None,
1115 crate::GeneratorIssue::Shape(issue) => ModelError::InvalidShape {
1116 owner,
1117 at: issue.at,
1118 problem: issue.problem,
1119 },
1120 crate::GeneratorIssue::Layout(issue) => ModelError::InvalidLayout {
1121 owner,
1122 at: issue.at,
1123 problem: issue.problem,
1124 },
1125 crate::GeneratorIssue::TextRun { run } => ModelError::InvalidTextRunStyle { owner, run },
1126 })
1127}
1128
1129fn validate_source_content(source: &MediaSource, canvas: (u32, u32)) -> Result<(), ModelError> {
1134 if let Some(fingerprint) = &source.fingerprint
1135 && (source.kind == MediaKind::Generated || !fingerprint.is_valid())
1136 {
1137 return Err(ModelError::InvalidFingerprint {
1138 source: source.id.clone(),
1139 });
1140 }
1141 if source
1142 .color_metadata
1143 .is_some_and(|color| !color.is_consistent())
1144 {
1145 return Err(ModelError::ContradictoryColor {
1146 source: source.id.clone(),
1147 });
1148 }
1149 if let Some(provider) = &source.provider
1150 && (provider.kind() != source.kind || source.has_audio || !provider.is_valid())
1151 {
1152 return Err(ModelError::InvalidProvider {
1153 source: source.id.clone(),
1154 });
1155 }
1156 if source.kind == MediaKind::Composition {
1157 let valid = source.composition.is_some()
1159 && source.generator.is_none()
1160 && source.locator.is_empty()
1161 && source.color_metadata.is_none()
1162 && source.fingerprint.is_none()
1163 && source.provider.is_none()
1164 && !source.has_audio;
1165 return if valid {
1166 Ok(())
1167 } else {
1168 Err(ModelError::InvalidCompositionSource {
1169 source: source.id.clone(),
1170 })
1171 };
1172 }
1173 if source.composition.is_some() {
1174 return Err(ModelError::InvalidCompositionSource {
1175 source: source.id.clone(),
1176 });
1177 }
1178 if source.kind == MediaKind::Generated {
1179 let owner = || crate::ShapeOwner::Source(source.id.clone());
1180 if let Some(Err(issue)) = source
1181 .generator
1182 .as_ref()
1183 .map(|generator| generator.validate_on(canvas.0, canvas.1))
1184 && let Some(error) = generator_error(owner(), issue)
1185 {
1186 return Err(error);
1187 }
1188 let valid = source.generator.as_ref().is_some_and(Generator::is_valid)
1189 && source.locator.is_empty()
1190 && source.color_metadata.is_none()
1191 && !source.has_audio;
1192 return if valid {
1193 Ok(())
1194 } else {
1195 Err(ModelError::InvalidGenerator {
1196 source: source.id.clone(),
1197 })
1198 };
1199 }
1200 if source.generator.is_some() {
1201 return Err(ModelError::InvalidGenerator {
1202 source: source.id.clone(),
1203 });
1204 }
1205 if let Some(checked) = validate_fileless_source(source) {
1206 return checked;
1207 }
1208 if source.locator.is_empty() {
1209 return Err(ModelError::EmptyLocator {
1210 source: source.id.clone(),
1211 });
1212 }
1213 if source.kind == MediaKind::Image && source.has_audio {
1214 return Err(ModelError::AudioOnImage {
1215 source: source.id.clone(),
1216 });
1217 }
1218 Ok(())
1219}
1220
1221fn validate_fileless_source(source: &MediaSource) -> Option<Result<(), ModelError>> {
1224 let provider = source.provider.as_ref()?;
1225 (!provider.reads_file()).then(|| {
1226 if source.locator.is_empty() && source.fingerprint.is_none() {
1227 Ok(())
1228 } else {
1229 Err(ModelError::InvalidProvider {
1230 source: source.id.clone(),
1231 })
1232 }
1233 })
1234}
1235
1236fn ensure_id<T: fmt::Display>(id: &T) -> Result<(), ModelError> {
1237 if id.to_string().is_empty() {
1238 Err(ModelError::EmptyIdentifier)
1239 } else {
1240 Ok(())
1241 }
1242}
1243
1244#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1246#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1247#[serde(deny_unknown_fields)]
1248#[non_exhaustive]
1249pub struct ProjectSettings {
1250 pub width: u32,
1252 pub height: u32,
1255 pub frame_rate: FrameRate,
1257 pub sample_rate: u32,
1259 #[serde(default)]
1262 pub background: Rgb,
1263 #[serde(default)]
1265 pub blend_space: BlendSpace,
1266 #[serde(default)]
1268 pub color: ColorPipeline,
1269}
1270
1271#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1279#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1280#[serde(deny_unknown_fields)]
1281pub struct ColorPipeline {
1282 #[serde(default)]
1284 pub hdr: HdrSources,
1285 #[serde(default = "default_hdr_peak")]
1288 pub hdr_peak_nits: u32,
1289}
1290
1291pub const HDR_PEAK_NITS_RANGE: std::ops::RangeInclusive<u32> = 100..=10_000;
1293
1294const fn default_hdr_peak() -> u32 {
1295 1_000
1296}
1297
1298impl Default for ColorPipeline {
1299 fn default() -> Self {
1300 Self {
1301 hdr: HdrSources::default(),
1302 hdr_peak_nits: default_hdr_peak(),
1303 }
1304 }
1305}
1306
1307#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1309#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1310#[serde(rename_all = "snake_case")]
1311pub enum HdrSources {
1312 #[default]
1314 ToneMap,
1315 Reject,
1317}
1318
1319#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1325#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1326#[serde(rename_all = "snake_case")]
1327pub enum BlendSpace {
1328 #[default]
1330 LinearLight,
1331 SrgbEncoded,
1333}
1334
1335#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
1337#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1338#[serde(deny_unknown_fields)]
1339pub struct Rgb {
1340 pub red: f32,
1342 pub green: f32,
1344 pub blue: f32,
1346}
1347
1348impl Rgb {
1349 pub const BLACK: Self = Self::new(0.0, 0.0, 0.0);
1351
1352 #[must_use]
1354 pub const fn new(red: f32, green: f32, blue: f32) -> Self {
1355 Self { red, green, blue }
1356 }
1357
1358 fn is_valid(self) -> bool {
1359 [self.red, self.green, self.blue]
1360 .into_iter()
1361 .all(|component| component.is_finite() && (0.0..=1.0).contains(&component))
1362 }
1363}
1364
1365impl ProjectSettings {
1366 pub fn new(
1371 width: u32,
1372 height: u32,
1373 frame_rate: FrameRate,
1374 sample_rate: u32,
1375 ) -> Result<Self, ModelError> {
1376 let settings = Self {
1377 width,
1378 height,
1379 frame_rate,
1380 sample_rate,
1381 background: Rgb::BLACK,
1382 blend_space: BlendSpace::LinearLight,
1383 color: ColorPipeline::default(),
1384 };
1385 settings.validate()?;
1386 Ok(settings)
1387 }
1388
1389 pub fn with_background(mut self, background: Rgb) -> Result<Self, ModelError> {
1394 self.background = background;
1395 self.validate()?;
1396 Ok(self)
1397 }
1398
1399 fn validate(&self) -> Result<(), ModelError> {
1400 if !HDR_PEAK_NITS_RANGE.contains(&self.color.hdr_peak_nits) {
1401 return Err(ModelError::InvalidColorPipeline);
1402 }
1403 if self.width == 0 || self.height == 0 {
1404 return Err(ModelError::ZeroCanvasDimension);
1405 }
1406 if self.width > MAX_CANVAS_DIMENSION || self.height > MAX_CANVAS_DIMENSION {
1407 return Err(ModelError::CanvasDimensionTooLarge {
1408 width: self.width,
1409 height: self.height,
1410 maximum: MAX_CANVAS_DIMENSION,
1411 });
1412 }
1413 let pixels = u64::from(self.width) * u64::from(self.height);
1414 if pixels > MAX_CANVAS_PIXELS {
1415 return Err(ModelError::CanvasPixelBudgetExceeded {
1416 pixels,
1417 maximum: MAX_CANVAS_PIXELS,
1418 });
1419 }
1420 if !self.background.is_valid() {
1421 return Err(ModelError::InvalidBackground);
1422 }
1423 if !SAMPLE_RATE_RANGE.contains(&self.sample_rate) {
1424 return Err(ModelError::UnsupportedSampleRate {
1425 found: self.sample_rate,
1426 minimum: *SAMPLE_RATE_RANGE.start(),
1427 maximum: *SAMPLE_RATE_RANGE.end(),
1428 });
1429 }
1430 Ok(())
1431 }
1432}