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 effect_resource_ids = self.validate_effect_resources()?;
427 let sources = self.validate_sources(&effect_resource_ids)?;
428 let inlined = crate::composition::validate_compositions(
429 &self.compositions,
430 &self.sources,
431 &sources,
432 &effect_resource_ids,
433 (self.settings.width, self.settings.height),
434 )?;
435 let index = DocumentIndex::new(sources, &self.compositions);
436
437 let mut track_ids = HashSet::new();
438 let mut clip_ids = HashSet::new();
439 let mut clip_count = 0_usize;
440 for track in &self.timeline.tracks {
441 ensure_id(&track.id)?;
442 if !track_ids.insert(&track.id) {
443 return Err(ModelError::DuplicateTrackId(track.id.clone()));
444 }
445 if track.clips.len() > MAX_CLIPS_PER_TRACK {
446 return Err(ModelError::TooManyClipsOnTrack {
447 track: track.id.clone(),
448 found: track.clips.len(),
449 maximum: MAX_CLIPS_PER_TRACK,
450 });
451 }
452 validate_captions(track)?;
453 if track.transitions.len() > MAX_TRANSITIONS_PER_TRACK {
454 return Err(ModelError::TooManyTransitions {
455 track: track.id.clone(),
456 found: track.transitions.len(),
457 maximum: MAX_TRANSITIONS_PER_TRACK,
458 });
459 }
460 clip_count =
461 clip_count
462 .checked_add(track.clips.len())
463 .ok_or(ModelError::TooManyClips {
464 found: usize::MAX,
465 maximum: MAX_CLIPS,
466 })?;
467 if clip_count > MAX_CLIPS {
468 return Err(ModelError::TooManyClips {
469 found: clip_count,
470 maximum: MAX_CLIPS,
471 });
472 }
473 for clip in &track.clips {
474 validate_clip(&index, track, clip, &mut clip_ids)?;
475 }
476 for transition in &track.transitions {
477 ensure_effect_resources_exist(
478 &transition.effect,
479 &effect_resource_ids,
480 &transition.to_clip,
481 )?;
482 }
483 ensure_transitions_are_supported(track, &index.sources)?;
484 ensure_transition_effects_match_builtins(track)?;
485 if !track.audio.validate() {
486 return Err(ModelError::InvalidTrackAudio {
487 track: track.id.clone(),
488 });
489 }
490 ensure_overlaps_have_transitions(track)?;
491 }
492 self.validate_audio_graph()?;
493 crate::data_places::validate_data(self, &index.sources)?;
494
495 ensure_mattes_are_usable(&self.timeline, &index.sources)?;
496 ensure_frames_fit(&self.timeline, &index.sources, &inlined)?;
497 crate::time_bound::ensure_times_are_writable(self)
498 }
499
500 fn validate_sources(
502 &self,
503 effect_resources: &HashSet<&EffectResourceId>,
504 ) -> Result<HashMap<&alpha2_media::SourceId, &MediaSource>, ModelError> {
505 let mut sources = HashMap::with_capacity(self.sources.len());
506 for source in &self.sources {
507 ensure_id(&source.id)?;
508 if source.kind == MediaKind::Adjustment {
509 if *source != MediaSource::adjustment(source.id.clone()) {
510 return Err(ModelError::InvalidAdjustmentSource {
511 source: source.id.clone(),
512 });
513 }
514 } else {
515 validate_source_content(
516 source,
517 (self.settings.width, self.settings.height),
518 effect_resources,
519 )?;
520 }
521 if sources.insert(&source.id, source).is_some() {
522 return Err(ModelError::DuplicateSourceId(source.id.clone()));
523 }
524 }
525 Ok(sources)
526 }
527
528 fn validate_audio_graph(&self) -> Result<(), ModelError> {
529 let buses = &self.audio.buses;
530 if buses.len() > crate::MAX_AUDIO_BUSES {
531 return Err(ModelError::TooManyAudioBuses {
532 found: buses.len(),
533 maximum: crate::MAX_AUDIO_BUSES,
534 });
535 }
536 if let Some(bus) = buses.iter().find(|bus| !bus.validate()) {
537 return Err(ModelError::InvalidAudioBus {
538 bus: bus.id.clone(),
539 });
540 }
541 let track_sends = self.timeline.tracks.iter().map(|track| {
542 (
543 crate::AudioNodeRef::Track(track.id.clone()),
544 &track.audio.sends,
545 )
546 });
547 let bus_sends = buses
548 .iter()
549 .map(|bus| (crate::AudioNodeRef::Bus(bus.id.clone()), &bus.sends));
550 for (from, sends) in track_sends.chain(bus_sends) {
551 if let Some(send) = sends.iter().find(|send| !send.is_valid()) {
552 return Err(ModelError::InvalidAudioSend {
553 from,
554 to: send.to.clone(),
555 });
556 }
557 }
558 self.audio_routing()?;
559 self.ensure_audio_effects_fit()
560 }
561
562 fn ensure_audio_effects_fit(&self) -> Result<(), ModelError> {
565 let load = self.audio_effect_load();
566 if load.effects > crate::MAX_AUDIO_EFFECTS {
567 return Err(ModelError::TooManyAudioEffects {
568 found: load.effects,
569 maximum: crate::MAX_AUDIO_EFFECTS,
570 at_ticks: load.effects_at_ticks,
571 });
572 }
573 if load.delay_ms() > u64::from(crate::MAX_AUDIO_DELAY_MS) {
574 return Err(ModelError::TooMuchAudioDelay {
575 found_ms: load.delay_ms(),
576 maximum_ms: crate::MAX_AUDIO_DELAY_MS,
577 at_ticks: load.delay_at_ticks,
578 });
579 }
580 Ok(())
581 }
582
583 fn validate_effect_resources(&self) -> Result<HashSet<&EffectResourceId>, ModelError> {
584 if self.effect_resources.len() > MAX_EFFECT_RESOURCES {
585 return Err(ModelError::TooManyEffectResources {
586 found: self.effect_resources.len(),
587 maximum: MAX_EFFECT_RESOURCES,
588 });
589 }
590 let mut ids = HashSet::new();
591 for resource in &self.effect_resources {
592 ensure_id(&resource.id)?;
593 if resource.locator.is_empty() {
594 return Err(ModelError::EmptyEffectResourceLocator {
595 resource: resource.id.clone(),
596 });
597 }
598 if !ids.insert(&resource.id) {
599 return Err(ModelError::DuplicateEffectResourceId(resource.id.clone()));
600 }
601 }
602 Ok(ids)
603 }
604}
605
606fn ensure_effect_resources_exist(
607 effect: &crate::ClipEffect,
608 known: &HashSet<&EffectResourceId>,
609 clip: &crate::ClipId,
610) -> Result<(), ModelError> {
611 for resource in effect.resources.values() {
612 if !known.contains(resource) {
613 return Err(ModelError::UnknownEffectResource {
614 clip: clip.clone(),
615 resource: resource.clone(),
616 });
617 }
618 }
619 Ok(())
620}
621
622fn validate_clip<'a>(
624 index: &DocumentIndex<'a>,
625 track: &'a crate::Track,
626 clip: &'a crate::Clip,
627 clip_ids: &mut HashSet<&'a crate::ClipId>,
628) -> Result<(), ModelError> {
629 ensure_id(&clip.id)?;
630 if clip.timeline_range.is_empty() || clip.source_range.is_empty() {
631 return Err(ModelError::EmptyClipRange {
632 clip: clip.id.clone(),
633 });
634 }
635 if clip.timeline_range.start().ticks() < 0 || clip.source_range.start().ticks() < 0 {
636 return Err(ModelError::NegativeClipRange {
637 clip: clip.id.clone(),
638 });
639 }
640 if !clip_ids.insert(&clip.id) {
641 return Err(ModelError::DuplicateClipId(clip.id.clone()));
642 }
643 let Some(source) = index.sources.get(&clip.source_id) else {
644 return Err(ModelError::UnknownClipSource {
645 clip: clip.id.clone(),
646 source: clip.source_id.clone(),
647 });
648 };
649 if !track.kind.accepts(source.kind) {
650 return Err(ModelError::IncompatibleClipSource {
651 clip: clip.id.clone(),
652 track: track.id.clone(),
653 source: source.id.clone(),
654 });
655 }
656 if !clip.visual.validate() {
657 return Err(ModelError::InvalidVisualProperties {
658 clip: clip.id.clone(),
659 });
660 }
661 if let Some(composition) = &clip.composition {
662 let held = || {
665 let last = MediaTime::from_ticks(clip.timeline_range.end().ticks().saturating_sub(1));
666 composition
667 .local_time(clip.timeline_range.start(), last)
668 .is_some_and(|time| time.ticks() <= alpha2_time::MAX_SERIALIZED_TICKS)
669 };
670 if track.kind != TrackKind::Video || !composition.scale.is_valid() || !held() {
671 return Err(ModelError::InvalidClipComposition {
672 clip: clip.id.clone(),
673 });
674 }
675 if !index.compositions.contains(&composition.id) {
676 return Err(ModelError::UnknownComposition {
677 clip: clip.id.clone(),
678 composition: composition.id.clone(),
679 });
680 }
681 crate::time_offset::ensure_clip_can_be_shifted(
682 clip,
683 source,
684 &composition.id,
685 &index.shifted_clip_reads,
686 )?;
687 }
688 if !clip.audio.validate() {
689 return Err(ModelError::InvalidAudioProperties {
690 clip: clip.id.clone(),
691 });
692 }
693 let visual = track.kind == TrackKind::Video;
694 if clip.masks.len() > crate::MAX_CLIP_MASKS || (!visual && !clip.masks.is_empty()) {
695 return Err(ModelError::InvalidClipMask {
696 clip: clip.id.clone(),
697 });
698 }
699 crate::mask::validate_masks(&clip.masks).map_err(|issue| ModelError::InvalidShape {
700 owner: crate::ShapeOwner::Clip(clip.id.clone()),
701 at: issue.at,
702 problem: issue.problem,
703 })?;
704 ensure_picture_settings_have_a_picture(clip, visual, source.kind)?;
705 if let Some(problem) = clip
706 .time_map
707 .problem(clip.timeline_range, clip.source_range)
708 {
709 return Err(ModelError::InvalidTimeMap {
710 clip: clip.id.clone(),
711 problem,
712 });
713 }
714 if let crate::TimeMap::Loop { .. } = &clip.time_map {
715 let length = |range: alpha2_time::TimeRange| range.duration().map_or(0, MediaTime::ticks);
716 let found = crate::loop_passes(length(clip.timeline_range), length(clip.source_range));
717 if found > crate::MAX_LOOP_PASSES {
718 return Err(ModelError::TooManyLoopPasses {
719 clip: clip.id.clone(),
720 found,
721 maximum: crate::MAX_LOOP_PASSES,
722 });
723 }
724 }
725 Ok(())
726}
727
728struct DocumentIndex<'a> {
730 sources: HashMap<&'a alpha2_media::SourceId, &'a MediaSource>,
731 compositions: HashSet<&'a crate::CompositionId>,
732 shifted_clip_reads: crate::time_offset::ShiftedClipReads<'a>,
733}
734
735impl<'a> DocumentIndex<'a> {
736 fn new(
737 sources: HashMap<&'a alpha2_media::SourceId, &'a MediaSource>,
738 compositions: &'a [crate::Composition],
739 ) -> Self {
740 Self {
741 sources,
742 compositions: compositions
743 .iter()
744 .map(|composition| &composition.id)
745 .collect(),
746 shifted_clip_reads: crate::time_offset::shifted_clip_reads(compositions),
747 }
748 }
749}
750
751fn ensure_transitions_are_supported(
755 track: &crate::Track,
756 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
757) -> Result<(), ModelError> {
758 let clips = track
759 .clips
760 .iter()
761 .map(|clip| (&clip.id, clip))
762 .collect::<HashMap<_, _>>();
763 let mut pairs = HashSet::with_capacity(track.transitions.len());
764 for transition in &track.transitions {
765 let covers = |id: &crate::ClipId| {
766 clips.get(id).is_some_and(|clip| {
767 clip.timeline_range.start() <= transition.timeline_range.start()
768 && clip.timeline_range.end() >= transition.timeline_range.end()
769 })
770 };
771 let valid = track.kind == TrackKind::Video
772 && transition.from_clip != transition.to_clip
773 && !transition.timeline_range.is_empty()
774 && transition.easing.is_valid()
775 && transition.effect.is_valid()
776 && covers(&transition.from_clip)
777 && covers(&transition.to_clip);
778 if !valid {
779 return Err(ModelError::InvalidClipTransition {
780 track: track.id.clone(),
781 });
782 }
783 let pair = if transition.from_clip < transition.to_clip {
786 (&transition.from_clip, &transition.to_clip)
787 } else {
788 (&transition.to_clip, &transition.from_clip)
789 };
790 if !pairs.insert(pair) {
791 return Err(ModelError::DuplicateTransition {
792 track: track.id.clone(),
793 first: transition.from_clip.clone(),
794 second: transition.to_clip.clone(),
795 });
796 }
797 }
798 ensure_adjustments_only_fade(track, sources)
799}
800
801fn ensure_adjustments_only_fade(
802 track: &crate::Track,
803 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
804) -> Result<(), ModelError> {
805 let adjustments = track
806 .clips
807 .iter()
808 .filter(|clip| {
809 sources
810 .get(&clip.source_id)
811 .is_some_and(|source| source.kind == MediaKind::Adjustment)
812 })
813 .map(|clip| &clip.id)
814 .collect::<HashSet<_>>();
815 if adjustments.is_empty() {
816 return Ok(());
817 }
818 for transition in &track.transitions {
819 if transition.effect.id == ADJUSTMENT_TRANSITION_ID {
820 continue;
821 }
822 if let Some(clip) = [&transition.from_clip, &transition.to_clip]
823 .into_iter()
824 .find(|clip| adjustments.contains(clip))
825 {
826 return Err(ModelError::InvalidAdjustmentTransition {
827 track: track.id.clone(),
828 clip: clip.clone(),
829 });
830 }
831 }
832 Ok(())
833}
834
835fn ensure_transition_effects_match_builtins(track: &crate::Track) -> Result<(), ModelError> {
837 for transition in &track.transitions {
838 crate::effect_spec::check_builtin(&transition.effect, crate::EffectKind::Transition, None)
839 .map_err(|problem| ModelError::InvalidEffect {
840 owner: Box::new(crate::EffectOwner::Transition {
841 track: track.id.clone(),
842 from: transition.from_clip.clone(),
843 to: transition.to_clip.clone(),
844 }),
845 id: transition.effect.id.clone(),
846 problem,
847 })?;
848 }
849 Ok(())
850}
851
852fn ensure_mattes_are_usable(
858 timeline: &Timeline,
859 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
860) -> Result<(), ModelError> {
861 let visual = timeline
862 .tracks
863 .iter()
864 .filter(|track| track.kind == TrackKind::Video)
865 .flat_map(|track| track.clips.iter().map(|clip| (&clip.id, clip)))
866 .filter(|(_, clip)| {
867 sources
868 .get(&clip.source_id)
869 .is_none_or(|source| source.kind != MediaKind::Adjustment)
870 })
871 .collect::<HashMap<_, _>>();
872 let in_transition = timeline
873 .tracks
874 .iter()
875 .flat_map(|track| &track.transitions)
876 .flat_map(|transition| [&transition.from_clip, &transition.to_clip])
877 .collect::<HashSet<_>>();
878 let clips = timeline
880 .tracks
881 .iter()
882 .filter(|track| track.kind == TrackKind::Video)
883 .flat_map(|track| &track.clips);
884 for clip in clips {
885 let Some(matte) = &clip.matte else {
886 continue;
887 };
888 let usable = matte.source != clip.id
889 && visual
890 .get(&matte.source)
891 .is_some_and(|source| source.matte.is_none())
892 && !in_transition.contains(&matte.source);
893 if !usable {
894 return Err(ModelError::InvalidMatte {
895 clip: clip.id.clone(),
896 });
897 }
898 }
899 Ok(())
900}
901
902fn ensure_frames_fit(
909 timeline: &Timeline,
910 sources: &HashMap<&alpha2_media::SourceId, &MediaSource>,
911 inlined: &crate::composition::InlinedNodes<'_>,
912) -> Result<(), ModelError> {
913 let nodes = |id: Option<&crate::CompositionId>| id.and_then(|id| inlined.get(id)).copied();
914 let mut edges = Vec::new();
916 for clip in timeline.tracks.iter().flat_map(|track| &track.clips) {
917 let source = sources
918 .get(&clip.source_id)
919 .and_then(|source| source.composition.as_ref());
920 let drawn = nodes(clip.composition.as_ref().map(|reference| &reference.id))
921 .unwrap_or(0)
922 .saturating_add(nodes(source).unwrap_or(0));
923 if drawn > 0 {
924 edges.push((clip.timeline_range.start(), true, drawn, &clip.id));
925 edges.push((clip.timeline_range.end(), false, drawn, &clip.id));
926 }
927 }
928 edges.sort_by_key(|&(time, starts, ..)| (time, starts));
931 let mut drawn = 0_u64;
932 let mut edges = edges.into_iter().peekable();
933 while let Some((time, starts, nodes, clip)) = edges.next() {
934 if !starts {
935 drawn -= nodes;
936 continue;
937 }
938 drawn = drawn.saturating_add(nodes);
939 while let Some((_, _, nodes, _)) =
941 edges.next_if(|&(next, next_starts, ..)| next == time && next_starts)
942 {
943 drawn = drawn.saturating_add(nodes);
944 }
945 if drawn > crate::MAX_FRAME_INLINED_NODES as u64 {
946 return Err(ModelError::FrameDrawsTooManyNodes {
947 clip: clip.clone(),
948 found: drawn,
949 maximum: crate::MAX_FRAME_INLINED_NODES,
950 });
951 }
952 }
953 Ok(())
954}
955
956fn ensure_picture_settings_have_a_picture(
957 clip: &crate::Clip,
958 visual: bool,
959 source: MediaKind,
960) -> Result<(), ModelError> {
961 if (!visual || source == MediaKind::Adjustment) && clip.matte.is_some() {
962 return Err(ModelError::InvalidMatte {
963 clip: clip.id.clone(),
964 });
965 }
966 if !visual && !clip.frame_interpolation.is_hold() {
967 return Err(ModelError::InvalidFrameInterpolation {
968 clip: clip.id.clone(),
969 });
970 }
971 Ok(())
972}
973
974pub(crate) fn ensure_overlaps_have_transitions(track: &crate::Track) -> Result<(), ModelError> {
979 if track.kind != TrackKind::Video {
980 return Ok(());
981 }
982 let transitions = track
983 .transitions
984 .iter()
985 .flat_map(|transition| {
986 [
987 (
988 &transition.from_clip,
989 &transition.to_clip,
990 transition.timeline_range,
991 ),
992 (
993 &transition.to_clip,
994 &transition.from_clip,
995 transition.timeline_range,
996 ),
997 ]
998 })
999 .collect::<HashSet<_>>();
1000 let directed = track
1001 .transitions
1002 .iter()
1003 .map(|transition| (&transition.from_clip, &transition.to_clip))
1004 .collect::<HashSet<_>>();
1005 let mut ordered = track.clips.iter().collect::<Vec<_>>();
1006 ordered.sort_by_key(|clip| (clip.timeline_range.start(), clip.timeline_range.end()));
1007 let mut active = Vec::new();
1008 for second in ordered {
1009 active.retain(|first: &&crate::Clip| {
1010 first.timeline_range.end() > second.timeline_range.start()
1011 });
1012 for first in &active {
1013 let Some(intersection) = first.timeline_range.intersection(second.timeline_range)
1014 else {
1015 continue;
1016 };
1017 if !transitions.contains(&(&first.id, &second.id, intersection)) {
1018 return Err(ModelError::OverlappingClips {
1019 track: track.id.clone(),
1020 first: first.id.clone(),
1021 second: second.id.clone(),
1022 });
1023 }
1024 }
1025 active.push(second);
1026 if active.len() >= 3 {
1031 let mut leads = active
1032 .iter()
1033 .map(|from| {
1034 active
1035 .iter()
1036 .filter(|to| directed.contains(&(&from.id, &to.id)))
1037 .count()
1038 })
1039 .collect::<Vec<_>>();
1040 leads.sort_unstable();
1041 if leads.iter().enumerate().any(|(rank, lead)| rank != *lead) {
1042 return Err(ModelError::TransitionCycle {
1043 track: track.id.clone(),
1044 at: second.timeline_range.start(),
1045 });
1046 }
1047 }
1048 }
1049 Ok(())
1050}
1051
1052fn validate_captions(track: &crate::Track) -> Result<(), ModelError> {
1054 if let Some(captions) = &track.captions
1055 && captions.cues.len() > MAX_CLIPS_PER_TRACK
1056 {
1057 return Err(ModelError::TooManyCaptionCues {
1058 track: track.id.clone(),
1059 found: captions.cues.len(),
1060 maximum: MAX_CLIPS_PER_TRACK,
1061 });
1062 }
1063 let valid = match (&track.kind, &track.captions) {
1064 (TrackKind::Caption, Some(captions)) => {
1065 if !(track.clips.is_empty() && track.transitions.is_empty()) {
1066 return Err(ModelError::InvalidCaptions {
1067 track: track.id.clone(),
1068 });
1069 }
1070 match captions.validate() {
1071 Ok(()) => true,
1072 Err(crate::caption::CaptionIssue::Invalid) => false,
1073 Err(crate::caption::CaptionIssue::UnknownStyle { cue, name }) => {
1074 return Err(ModelError::UnknownCaptionStyle {
1075 track: track.id.clone(),
1076 cue,
1077 name,
1078 });
1079 }
1080 Err(crate::caption::CaptionIssue::CueStyle { cue }) => {
1081 return Err(ModelError::InvalidCaptionCueStyle {
1082 track: track.id.clone(),
1083 cue,
1084 });
1085 }
1086 }
1087 }
1088 (TrackKind::Caption, None) => false,
1089 (_, captions) => captions.is_none(),
1090 };
1091 if valid {
1092 Ok(())
1093 } else {
1094 Err(ModelError::InvalidCaptions {
1095 track: track.id.clone(),
1096 })
1097 }
1098}
1099
1100#[derive(Copy, Clone)]
1101pub(crate) enum GeneratorOwner<'a> {
1102 Source(&'a alpha2_media::SourceId),
1103 Node {
1104 composition: &'a crate::CompositionId,
1105 node: &'a crate::NodeId,
1106 },
1107}
1108
1109impl GeneratorOwner<'_> {
1110 fn of_tree(self) -> crate::ShapeOwner {
1111 match self {
1112 Self::Source(source) => crate::ShapeOwner::Source(source.clone()),
1113 Self::Node { composition, node } => crate::ShapeOwner::Node {
1114 composition: composition.clone(),
1115 node: node.clone(),
1116 },
1117 }
1118 }
1119
1120 fn of_effect(self) -> crate::EffectOwner {
1121 match self {
1122 Self::Source(source) => crate::EffectOwner::Source(source.clone()),
1123 Self::Node { composition, node } => crate::EffectOwner::Node {
1124 composition: composition.clone(),
1125 node: node.clone(),
1126 },
1127 }
1128 }
1129}
1130
1131pub(crate) fn generator_error(
1132 owner: GeneratorOwner<'_>,
1133 issue: crate::GeneratorIssue,
1134) -> Option<ModelError> {
1135 Some(match issue {
1136 crate::GeneratorIssue::Invalid => return None,
1137 crate::GeneratorIssue::Shape(issue) => ModelError::InvalidShape {
1138 owner: owner.of_tree(),
1139 at: issue.at,
1140 problem: issue.problem,
1141 },
1142 crate::GeneratorIssue::Layout(issue) => ModelError::InvalidLayout {
1143 owner: owner.of_tree(),
1144 at: issue.at,
1145 problem: issue.problem,
1146 },
1147 crate::GeneratorIssue::TextRun { run } => ModelError::InvalidTextRunStyle {
1148 owner: owner.of_tree(),
1149 run,
1150 },
1151 crate::GeneratorIssue::Effect { id, problem } => ModelError::InvalidEffect {
1152 owner: Box::new(owner.of_effect()),
1153 id,
1154 problem,
1155 },
1156 })
1157}
1158
1159fn validate_source_content(
1164 source: &MediaSource,
1165 canvas: (u32, u32),
1166 effect_resources: &HashSet<&EffectResourceId>,
1167) -> Result<(), ModelError> {
1168 if let Some(fingerprint) = &source.fingerprint
1169 && (source.kind == MediaKind::Generated || !fingerprint.is_valid())
1170 {
1171 return Err(ModelError::InvalidFingerprint {
1172 source: source.id.clone(),
1173 });
1174 }
1175 if source
1176 .color_metadata
1177 .is_some_and(|color| !color.is_consistent())
1178 {
1179 return Err(ModelError::ContradictoryColor {
1180 source: source.id.clone(),
1181 });
1182 }
1183 if let Some(provider) = &source.provider
1184 && (provider.kind() != source.kind || source.has_audio || !provider.is_valid())
1185 {
1186 return Err(ModelError::InvalidProvider {
1187 source: source.id.clone(),
1188 });
1189 }
1190 if source.kind == MediaKind::Composition {
1191 let valid = source.composition.is_some()
1193 && source.generator.is_none()
1194 && source.locator.is_empty()
1195 && source.color_metadata.is_none()
1196 && source.fingerprint.is_none()
1197 && source.provider.is_none()
1198 && !source.has_audio;
1199 return if valid {
1200 Ok(())
1201 } else {
1202 Err(ModelError::InvalidCompositionSource {
1203 source: source.id.clone(),
1204 })
1205 };
1206 }
1207 if source.composition.is_some() {
1208 return Err(ModelError::InvalidCompositionSource {
1209 source: source.id.clone(),
1210 });
1211 }
1212 if source.kind == MediaKind::Generated {
1213 if let Some(Err(issue)) = source
1214 .generator
1215 .as_ref()
1216 .map(|generator| generator.validate_on(canvas.0, canvas.1))
1217 && let Some(error) = generator_error(GeneratorOwner::Source(&source.id), issue)
1218 {
1219 return Err(error);
1220 }
1221 let valid = source.generator.as_ref().is_some_and(Generator::is_valid)
1222 && source.locator.is_empty()
1223 && source.color_metadata.is_none()
1224 && !source.has_audio;
1225 if !valid {
1226 return Err(ModelError::InvalidGenerator {
1227 source: source.id.clone(),
1228 });
1229 }
1230 if let Some(Generator::Effect { effect }) = &source.generator
1231 && let Some(resource) = effect
1232 .resources
1233 .values()
1234 .find(|resource| !effect_resources.contains(resource))
1235 {
1236 return Err(ModelError::UnknownSourceResource {
1237 source: source.id.clone(),
1238 resource: resource.clone(),
1239 });
1240 }
1241 return Ok(());
1242 }
1243 if source.generator.is_some() {
1244 return Err(ModelError::InvalidGenerator {
1245 source: source.id.clone(),
1246 });
1247 }
1248 if let Some(checked) = validate_fileless_source(source) {
1249 return checked;
1250 }
1251 if source.locator.is_empty() {
1252 return Err(ModelError::EmptyLocator {
1253 source: source.id.clone(),
1254 });
1255 }
1256 if source.kind == MediaKind::Image && source.has_audio {
1257 return Err(ModelError::AudioOnImage {
1258 source: source.id.clone(),
1259 });
1260 }
1261 Ok(())
1262}
1263
1264fn validate_fileless_source(source: &MediaSource) -> Option<Result<(), ModelError>> {
1267 let provider = source.provider.as_ref()?;
1268 (!provider.reads_file()).then(|| {
1269 if source.locator.is_empty() && source.fingerprint.is_none() {
1270 Ok(())
1271 } else {
1272 Err(ModelError::InvalidProvider {
1273 source: source.id.clone(),
1274 })
1275 }
1276 })
1277}
1278
1279fn ensure_id<T: fmt::Display>(id: &T) -> Result<(), ModelError> {
1280 if id.to_string().is_empty() {
1281 Err(ModelError::EmptyIdentifier)
1282 } else {
1283 Ok(())
1284 }
1285}
1286
1287#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1289#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1290#[serde(deny_unknown_fields)]
1291#[non_exhaustive]
1292pub struct ProjectSettings {
1293 pub width: u32,
1295 pub height: u32,
1298 pub frame_rate: FrameRate,
1300 pub sample_rate: u32,
1302 #[serde(default)]
1305 pub background: Rgb,
1306 #[serde(default)]
1308 pub blend_space: BlendSpace,
1309 #[serde(default)]
1311 pub color: ColorPipeline,
1312 #[serde(default, skip_serializing_if = "crate::Shutter::is_default")]
1315 pub shutter: crate::Shutter,
1316}
1317
1318#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1326#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1327#[serde(deny_unknown_fields)]
1328pub struct ColorPipeline {
1329 #[serde(default)]
1331 pub hdr: HdrSources,
1332 #[serde(default = "default_hdr_peak")]
1335 pub hdr_peak_nits: u32,
1336}
1337
1338pub const HDR_PEAK_NITS_RANGE: std::ops::RangeInclusive<u32> = 100..=10_000;
1340
1341const fn default_hdr_peak() -> u32 {
1342 1_000
1343}
1344
1345impl Default for ColorPipeline {
1346 fn default() -> Self {
1347 Self {
1348 hdr: HdrSources::default(),
1349 hdr_peak_nits: default_hdr_peak(),
1350 }
1351 }
1352}
1353
1354#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1356#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1357#[serde(rename_all = "snake_case")]
1358pub enum HdrSources {
1359 #[default]
1361 ToneMap,
1362 Reject,
1364}
1365
1366#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1372#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1373#[serde(rename_all = "snake_case")]
1374pub enum BlendSpace {
1375 #[default]
1377 LinearLight,
1378 SrgbEncoded,
1380}
1381
1382#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
1384#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1385#[serde(deny_unknown_fields)]
1386pub struct Rgb {
1387 pub red: f32,
1389 pub green: f32,
1391 pub blue: f32,
1393}
1394
1395impl Rgb {
1396 pub const BLACK: Self = Self::new(0.0, 0.0, 0.0);
1398
1399 #[must_use]
1401 pub const fn new(red: f32, green: f32, blue: f32) -> Self {
1402 Self { red, green, blue }
1403 }
1404
1405 fn is_valid(self) -> bool {
1406 [self.red, self.green, self.blue]
1407 .into_iter()
1408 .all(|component| component.is_finite() && (0.0..=1.0).contains(&component))
1409 }
1410}
1411
1412impl ProjectSettings {
1413 pub fn new(
1418 width: u32,
1419 height: u32,
1420 frame_rate: FrameRate,
1421 sample_rate: u32,
1422 ) -> Result<Self, ModelError> {
1423 let settings = Self {
1424 width,
1425 height,
1426 frame_rate,
1427 sample_rate,
1428 background: Rgb::BLACK,
1429 blend_space: BlendSpace::LinearLight,
1430 color: ColorPipeline::default(),
1431 shutter: crate::Shutter::default(),
1432 };
1433 settings.validate()?;
1434 Ok(settings)
1435 }
1436
1437 pub fn with_background(mut self, background: Rgb) -> Result<Self, ModelError> {
1442 self.background = background;
1443 self.validate()?;
1444 Ok(self)
1445 }
1446
1447 pub fn with_shutter(mut self, shutter: crate::Shutter) -> Result<Self, ModelError> {
1452 self.shutter = shutter;
1453 self.validate()?;
1454 Ok(self)
1455 }
1456
1457 fn validate(&self) -> Result<(), ModelError> {
1458 if !HDR_PEAK_NITS_RANGE.contains(&self.color.hdr_peak_nits) {
1459 return Err(ModelError::InvalidColorPipeline);
1460 }
1461 if self.width == 0 || self.height == 0 {
1462 return Err(ModelError::ZeroCanvasDimension);
1463 }
1464 if self.width > MAX_CANVAS_DIMENSION || self.height > MAX_CANVAS_DIMENSION {
1465 return Err(ModelError::CanvasDimensionTooLarge {
1466 width: self.width,
1467 height: self.height,
1468 maximum: MAX_CANVAS_DIMENSION,
1469 });
1470 }
1471 let pixels = u64::from(self.width) * u64::from(self.height);
1472 if pixels > MAX_CANVAS_PIXELS {
1473 return Err(ModelError::CanvasPixelBudgetExceeded {
1474 pixels,
1475 maximum: MAX_CANVAS_PIXELS,
1476 });
1477 }
1478 if !self.background.is_valid() {
1479 return Err(ModelError::InvalidBackground);
1480 }
1481 self.shutter
1482 .validate()
1483 .map_err(ModelError::InvalidShutter)?;
1484 if !SAMPLE_RATE_RANGE.contains(&self.sample_rate) {
1485 return Err(ModelError::UnsupportedSampleRate {
1486 found: self.sample_rate,
1487 minimum: *SAMPLE_RATE_RANGE.start(),
1488 maximum: *SAMPLE_RATE_RANGE.end(),
1489 });
1490 }
1491 Ok(())
1492 }
1493}