1use crate::animation::{Keyed, Placed, visit_keyed, visit_keyed_point};
7use crate::{
8 Animated, AnimatedPoint, ClipId, CompositionId, Extrapolation, Generator, MediaKind, NodeId,
9 Paint, Project, ShapeGeometry, ShapeItem, TrackId, TrackKind,
10};
11use alpha2_media::SourceId;
12use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
13use serde::Serialize;
14use std::collections::{HashMap, HashSet};
15
16#[derive(Clone, Debug, PartialEq, Serialize)]
18#[serde(tag = "kind", rename_all = "snake_case")]
19#[non_exhaustive]
20pub enum LintIssue {
21 UnreachedKeyframe {
24 owner: LintOwner,
26 property: String,
29 time: MediaTime,
31 },
32 HiddenClip {
35 clip: ClipId,
37 by: ClipId,
39 },
40 ShortTransition {
43 track: TrackId,
45 from_clip: ClipId,
47 to_clip: ClipId,
49 },
50 OffFrameBoundary {
53 owner: LintOwner,
55 edge: LintEdge,
57 time: MediaTime,
59 },
60 UnusedSource {
63 source: SourceId,
65 },
66 HdrSource {
69 source: SourceId,
71 },
72 EmptySubpath {
74 owner: ShapeLintOwner,
76 at: String,
79 },
80 PaintWithoutGeometry {
82 owner: ShapeLintOwner,
84 at: String,
86 },
87 UnusedCaptionStyle {
89 track: TrackId,
91 style: String,
93 },
94 StaleData {
98 data: crate::DataSetId,
100 source: SourceId,
102 },
103 ManyShiftedReads {
106 clip: ClipId,
108 source: SourceId,
110 count: u64,
112 },
113 EmptyTextAnimator {
115 owner: LintOwner,
117 at: String,
120 },
121 MotionBlurWithoutMotion {
125 owner: LintOwner,
127 },
128 HighlightWithoutTimedRuns {
130 owner: LintOwner,
133 at: String,
135 },
136}
137
138fn never_moves(visual: &crate::VisualProperties) -> bool {
139 matches!(visual.position, AnimatedPoint::Constant { .. })
140 && matches!(visual.scale, Animated::Constant { .. })
141 && matches!(visual.rotation_degrees, Animated::Constant { .. })
142 && matches!(visual.opacity, Animated::Constant { .. })
143}
144
145#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
147#[serde(tag = "type", rename_all = "snake_case")]
148#[non_exhaustive]
149pub enum ShapeLintOwner {
150 Source {
152 source: SourceId,
154 },
155 Node {
157 composition: CompositionId,
159 node: NodeId,
161 },
162}
163
164#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
166#[serde(tag = "type", rename_all = "snake_case")]
167#[non_exhaustive]
168pub enum LintOwner {
169 Clip {
171 clip: ClipId,
173 },
174 Transition {
176 track: TrackId,
178 from_clip: ClipId,
180 to_clip: ClipId,
182 },
183 Cue {
185 track: TrackId,
187 index: usize,
189 },
190 CompositionNode {
192 composition: CompositionId,
194 node: NodeId,
196 },
197 Source {
199 source: SourceId,
201 },
202 CaptionTrack {
204 track: TrackId,
206 },
207 CueRun {
209 track: TrackId,
211 cue: usize,
213 run: usize,
215 },
216}
217
218#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
220#[serde(rename_all = "snake_case")]
221pub enum LintEdge {
222 Start,
224 End,
226}
227
228impl Project {
229 #[must_use]
233 pub fn stale_data(
234 &self,
235 mut is_stale: impl FnMut(&SourceId, &crate::MediaFingerprint) -> bool,
236 ) -> Vec<LintIssue> {
237 self.data
238 .iter()
239 .filter_map(|set| {
240 let source = set.anchor.source()?;
241 let made_from = set.made_from.as_ref()?;
242 is_stale(source, made_from).then(|| LintIssue::StaleData {
243 data: set.id.clone(),
244 source: source.clone(),
245 })
246 })
247 .collect()
248 }
249
250 #[must_use]
255 pub fn lint(&self) -> Vec<LintIssue> {
256 let mut issues = Vec::new();
257 let used = self
258 .used_sources()
259 .into_iter()
260 .map(|source| &source.id)
261 .collect::<std::collections::HashSet<_>>();
262 for source in &self.sources {
263 if !used.contains(&source.id) {
264 issues.push(LintIssue::UnusedSource {
265 source: source.id.clone(),
266 });
267 }
268 }
269 self.lint_shapes(&mut issues);
270 let refused = self.settings.color.hdr == crate::HdrSources::Reject;
271 for source in self.hdr_sources().into_iter().filter(|_| refused) {
272 issues.push(LintIssue::HdrSource {
273 source: source.clone(),
274 });
275 }
276 let mattes = self
277 .timeline
278 .tracks
279 .iter()
280 .flat_map(|track| &track.clips)
281 .filter_map(|clip| clip.matte.as_ref().map(|matte| &matte.source))
282 .collect::<HashSet<_>>();
283 let grid = FrameGrid::new(self);
284 let covers = self.covering_clips(&mattes);
285 let shifted_reads = crate::time_offset::shifted_reads(self);
286 for (order, track) in self.timeline.tracks.iter().enumerate() {
287 for clip in &track.clips {
288 self.lint_shifted_reads(clip, &shifted_reads, &mut issues);
289 let owner = LintOwner::Clip {
290 clip: clip.id.clone(),
291 };
292 grid.check(&owner, clip.timeline_range, &mut issues);
293 let mut keyframes = Keyframes {
294 owner: &owner,
295 shown: &[span(clip.timeline_range)],
296 issues: &mut issues,
297 };
298 keyframes.check_clip(clip);
299 if track.kind == TrackKind::Video
300 && !mattes.contains(&clip.id)
301 && let Some(by) = covering_clip(&covers, order, clip.timeline_range)
302 {
303 issues.push(LintIssue::HiddenClip {
304 clip: clip.id.clone(),
305 by: by.clone(),
306 });
307 }
308 if clip.motion_blur && never_moves(&clip.visual) {
309 issues.push(LintIssue::MotionBlurWithoutMotion { owner });
310 }
311 }
312 for transition in &track.transitions {
313 let owner = LintOwner::Transition {
314 track: track.id.clone(),
315 from_clip: transition.from_clip.clone(),
316 to_clip: transition.to_clip.clone(),
317 };
318 if !grid.shows_mixed(transition.timeline_range) {
319 issues.push(LintIssue::ShortTransition {
320 track: track.id.clone(),
321 from_clip: transition.from_clip.clone(),
322 to_clip: transition.to_clip.clone(),
323 });
324 }
325 grid.check(&owner, transition.timeline_range, &mut issues);
326 let mut keyframes = Keyframes {
327 owner: &owner,
328 shown: &[span(transition.timeline_range)],
329 issues: &mut issues,
330 };
331 for (name, value) in &transition.effect.params {
332 keyframes.check(&format!("effect.params.{name}"), value);
333 }
334 }
335 lint_cues(&grid, track, &mut issues);
336 if let Some(captions) = &track.captions {
337 lint_caption_animators(&track.id, captions, &mut issues);
338 }
339 }
340 self.lint_marked_nodes_without_motion(&mut issues);
341 self.lint_keyframes_in_other_times(&mut issues);
342 self.lint_text_animators(&mut issues);
343 self.lint_data_past_its_source(&mut issues);
344 issues
345 }
346
347 fn lint_marked_nodes_without_motion(&self, issues: &mut Vec<LintIssue>) {
348 for composition in &self.compositions {
349 for node in &composition.nodes {
350 if let crate::NodeOp::Transform {
351 transform,
352 motion_blur: true,
353 ..
354 } = &node.op
355 && never_moves(transform)
356 {
357 issues.push(LintIssue::MotionBlurWithoutMotion {
358 owner: LintOwner::CompositionNode {
359 composition: composition.id.clone(),
360 node: node.id.clone(),
361 },
362 });
363 }
364 }
365 }
366 }
367
368 fn lint_data_past_its_source(&self, issues: &mut Vec<LintIssue>) {
370 for set in &self.data {
371 let Some(source) = set.anchor.source() else {
372 continue;
373 };
374 let duration = self
375 .sources
376 .iter()
377 .find(|candidate| &candidate.id == source)
378 .and_then(|source| source.fingerprint.as_ref()?.duration_ticks);
379 if let (Some(duration), Some(last)) = (duration, set.last_time())
380 && last.ticks() > duration
381 {
382 issues.push(LintIssue::StaleData {
383 data: set.id.clone(),
384 source: source.clone(),
385 });
386 }
387 }
388 }
389
390 fn lint_text_animators(&self, issues: &mut Vec<LintIssue>) {
392 let lint = |owner: &LintOwner,
393 generator: &Generator,
394 at: &str,
395 issues: &mut Vec<LintIssue>| {
396 match generator {
397 Generator::Text { text, style } => {
398 empty_animators(
399 owner,
400 &style.animators,
401 &format!("{at}style.animators"),
402 issues,
403 );
404 if style.highlight.is_some() && text.runs().iter().all(|run| run.time.is_none())
405 {
406 issues.push(LintIssue::HighlightWithoutTimedRuns {
407 owner: owner.clone(),
408 at: format!("{at}style.highlight"),
409 });
410 }
411 }
412 Generator::Layout { root } => root.walk(|path, node| {
413 empty_animators(
414 owner,
415 &node.text_animators,
416 &format!("{at}{path}.text_animators"),
417 issues,
418 );
419 }),
420 Generator::Fill { .. } | Generator::Shapes { .. } | Generator::Effect { .. } => {}
421 }
422 };
423 for source in &self.sources {
424 if let Some(generator) = &source.generator {
425 let owner = LintOwner::Source {
426 source: source.id.clone(),
427 };
428 lint(&owner, generator, "", issues);
429 }
430 }
431 for composition in &self.compositions {
432 for node in &composition.nodes {
433 if let crate::NodeOp::Generator { generator } = &node.op {
434 let owner = LintOwner::CompositionNode {
435 composition: composition.id.clone(),
436 node: node.id.clone(),
437 };
438 lint(&owner, generator, "generator.", issues);
439 }
440 }
441 }
442 }
443
444 fn lint_shifted_reads(
445 &self,
446 clip: &crate::Clip,
447 shifted_reads: &crate::time_offset::ShiftedReads<'_>,
448 issues: &mut Vec<LintIssue>,
449 ) {
450 use crate::time_offset::Read;
451 let Some(reads) = clip
452 .composition
453 .as_ref()
454 .and_then(|reference| shifted_reads.get(&reference.id))
455 else {
456 return;
457 };
458 let through_the_clip = reads.get(&Read::Clip).copied().unwrap_or(0);
459 for source in self
460 .sources
461 .iter()
462 .filter(|source| source.kind == MediaKind::Video)
463 {
464 let own = if source.id == clip.source_id {
465 through_the_clip
466 } else {
467 0
468 };
469 let count = reads
470 .get(&Read::Source(&source.id))
471 .copied()
472 .unwrap_or(0)
473 .saturating_add(own);
474 if count > UNREPORTED_SHIFTED_READS {
475 issues.push(LintIssue::ManyShiftedReads {
476 clip: clip.id.clone(),
477 source: source.id.clone(),
478 count,
479 });
480 }
481 }
482 }
483
484 fn lint_keyframes_in_other_times(&self, issues: &mut Vec<LintIssue>) {
488 let shown = Shown::of(self);
489 for composition in &self.compositions {
490 let Some(spans) = shown.compositions.get(&composition.id) else {
491 continue;
492 };
493 let shifts = crate::time_offset::shift_spans(composition);
494 for (position, node) in composition.nodes.iter().enumerate() {
495 let owner = LintOwner::CompositionNode {
496 composition: composition.id.clone(),
497 node: node.id.clone(),
498 };
499 let shifted = shifts
500 .as_ref()
501 .map(|shifts| widened(spans, shifts[position]));
502 let mut keyframes = Keyframes {
503 owner: &owner,
504 shown: shifted.as_deref().unwrap_or(spans),
505 issues,
506 };
507 node_keyed(&node.op, &mut |property, keyed| {
508 if let Keyed::Times(times, before, after) = keyed {
509 keyframes.check_times(property, times, before, after);
510 }
511 });
512 }
513 }
514 for source in &self.sources {
515 let Some(spans) = shown.sources.get(&source.id) else {
516 continue;
517 };
518 let owner = LintOwner::Source {
519 source: source.id.clone(),
520 };
521 let mut keyframes = Keyframes {
522 owner: &owner,
523 shown: spans,
524 issues,
525 };
526 let mut check = |property: &str, keyed: Keyed<'_>| {
527 if let Keyed::Times(times, before, after) = keyed {
528 keyframes.check_times(property, times, before, after);
529 }
530 };
531 match &source.generator {
532 Some(Generator::Shapes { items }) => {
533 crate::shapes::for_each_keyed_item(items, "items", &mut check);
534 }
535 Some(Generator::Layout { root }) => root.for_each_keyed("root", &mut check),
536 Some(Generator::Text { style, .. }) => {
537 crate::text_animation::for_each_keyed_animator(
538 &style.animators,
539 "style.animators",
540 &mut check,
541 );
542 }
543 Some(Generator::Effect { effect }) => {
544 effect_keyed(effect, "effect.params", &mut check);
545 }
546 Some(Generator::Fill { .. }) | None => {}
547 }
548 }
549 }
550
551 fn lint_shapes(&self, issues: &mut Vec<LintIssue>) {
554 let lint = |owner: &ShapeLintOwner, generator: &Generator, issues: &mut Vec<LintIssue>| {
555 match generator {
556 Generator::Shapes { items } => {
557 lint_shape_items(owner, items, "items", issues);
558 }
559 Generator::Layout { root } => root.walk(|at, node| {
560 if let Some(shape) = &node.shape {
561 lint_shape_items(owner, &shape.items, &format!("{at}.shape.items"), issues);
562 }
563 }),
564 Generator::Fill { .. } | Generator::Text { .. } | Generator::Effect { .. } => {}
565 }
566 };
567 for source in &self.sources {
568 if let Some(generator) = &source.generator {
569 let owner = ShapeLintOwner::Source {
570 source: source.id.clone(),
571 };
572 lint(&owner, generator, issues);
573 }
574 }
575 for composition in &self.compositions {
576 for node in &composition.nodes {
577 if let crate::NodeOp::Generator { generator } = &node.op {
578 let owner = ShapeLintOwner::Node {
579 composition: composition.id.clone(),
580 node: node.id.clone(),
581 };
582 lint(&owner, generator, issues);
583 }
584 }
585 }
586 }
587
588 fn covering_clips<'a>(&'a self, mattes: &HashSet<&ClipId>) -> Vec<Cover<'a>> {
592 let sources = self
593 .sources
594 .iter()
595 .map(|source| (&source.id, source))
596 .collect::<HashMap<_, _>>();
597 let mut covers = Vec::new();
598 for (order, track) in self.timeline.tracks.iter().enumerate() {
599 if track.kind != TrackKind::Video {
600 continue;
601 }
602 for clip in &track.clips {
603 if mattes.contains(&clip.id)
604 || !sources
605 .get(&clip.source_id)
606 .is_some_and(|source| is_opaque_full_frame(source, clip))
607 {
608 continue;
609 }
610 let mixed = track
611 .transitions
612 .iter()
613 .filter(|transition| {
614 transition.from_clip == clip.id || transition.to_clip == clip.id
615 })
616 .map(|transition| transition.timeline_range)
617 .collect();
618 covers.push(Cover { order, clip, mixed });
619 }
620 }
621 covers
622 }
623}
624
625struct Cover<'a> {
627 order: usize,
629 clip: &'a crate::Clip,
630 mixed: Vec<TimeRange>,
632}
633
634fn covering_clip<'a>(covers: &[Cover<'a>], order: usize, range: TimeRange) -> Option<&'a ClipId> {
636 covers
637 .iter()
638 .filter(|cover| cover.order > order)
639 .find(|cover| {
640 cover.clip.timeline_range.start() <= range.start()
641 && cover.clip.timeline_range.end() >= range.end()
642 && !cover
643 .mixed
644 .iter()
645 .any(|mixed| mixed.intersection(range).is_some())
646 })
647 .map(|cover| &cover.clip.id)
648}
649
650fn is_opaque_full_frame(source: &crate::MediaSource, clip: &crate::Clip) -> bool {
653 let opaque = source.kind == MediaKind::Generated
654 && matches!(&source.generator, Some(Generator::Fill { paint }) if paint_is_opaque(paint));
655 opaque
656 && clip.visual == crate::VisualProperties::default()
657 && clip.blend_mode == crate::ClipBlendMode::Normal
658 && clip.composition.is_none()
659 && clip.masks.is_empty()
660 && clip.matte.is_none()
661}
662
663fn paint_is_opaque(paint: &Paint) -> bool {
664 match paint {
665 Paint::Solid { color } => color.alpha >= 1.0,
666 Paint::LinearGradient { stops, .. }
667 | Paint::RadialGradient { stops, .. }
668 | Paint::ConicGradient { stops, .. } => stops.iter().all(|stop| stop.color.alpha >= 1.0),
669 }
670}
671
672struct FrameGrid {
675 rate: FrameRate,
676}
677
678impl FrameGrid {
679 fn new(project: &Project) -> Self {
680 Self {
681 rate: project.settings.frame_rate,
682 }
683 }
684
685 fn on_grid(&self, time: MediaTime) -> bool {
686 self.rate
687 .frame_at_or_before(time)
688 .and_then(|frame| self.rate.frame_start(frame))
689 == Some(time)
690 }
691
692 fn shows_mixed(&self, range: TimeRange) -> bool {
696 let first = self
697 .rate
698 .frame_at_or_before(range.start())
699 .and_then(|frame| {
700 let start = self.rate.frame_start(frame)?;
701 if start == range.start() {
702 Some(start)
703 } else {
704 self.rate.frame_start(frame.checked_add(1)?)
705 }
706 });
707 let Some(first) = first else {
708 return true;
709 };
710 let num = i128::from(self.rate.numerator());
711 let elapsed = i128::from(first.ticks()) - i128::from(range.start().ticks());
712 let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
713 first < range.end()
715 && 2 * num * elapsed
716 + i128::from(TICKS_PER_SECOND) * i128::from(self.rate.denominator())
717 < 2 * num * duration
718 }
719
720 fn check(&self, owner: &LintOwner, range: TimeRange, issues: &mut Vec<LintIssue>) {
721 for (edge, time) in [
722 (LintEdge::Start, range.start()),
723 (LintEdge::End, range.end()),
724 ] {
725 if !self.on_grid(time) {
726 issues.push(LintIssue::OffFrameBoundary {
727 owner: owner.clone(),
728 edge,
729 time,
730 });
731 }
732 }
733 }
734}
735
736struct Keyframes<'a> {
739 owner: &'a LintOwner,
740 shown: &'a [(i64, i64)],
741 issues: &'a mut Vec<LintIssue>,
742}
743
744fn span(range: TimeRange) -> (i64, i64) {
746 (range.start().ticks(), range.end().ticks() - 1)
747}
748
749const UNREPORTED_SHIFTED_READS: u64 = 4;
750
751fn widened(spans: &[(i64, i64)], (earliest, latest): (i64, i64)) -> Vec<(i64, i64)> {
752 spans
753 .iter()
754 .map(|&(first, last)| (first.saturating_add(earliest), last.saturating_add(latest)))
755 .collect()
756}
757
758impl Keyframes<'_> {
759 fn check_clip(&mut self, clip: &crate::Clip) {
760 let visual = &clip.visual;
761 self.check_point("visual.position", &visual.position);
762 self.check("visual.scale", &visual.scale);
763 self.check("visual.rotation_degrees", &visual.rotation_degrees);
764 self.check("visual.opacity", &visual.opacity);
765 for (index, mask) in clip.masks.iter().enumerate() {
766 self.check_geometry(&format!("masks[{index}].shape"), &mask.shape);
767 self.check(&format!("masks[{index}].feather"), &mask.feather);
768 }
769 if let crate::TimeMap::Curve {
770 keyframes,
771 before,
772 after,
773 } = &clip.time_map
774 {
775 let times = keyframes.iter().map(|key| key.time).collect::<Vec<_>>();
776 self.check_times("time_map", ×, *before, *after);
777 }
778 self.check("audio.gain", &clip.audio.gain);
779 self.check("audio.pan", &clip.audio.pan);
780 for (index, effect) in clip.audio.effects.iter().enumerate() {
781 effect.for_each_param(&mut |param| {
782 self.check(
783 &format!("audio.effects[{index}].{}", param.path()),
784 param.value,
785 );
786 });
787 }
788 }
789
790 fn check_geometry(&mut self, at: &str, geometry: &ShapeGeometry) {
791 geometry.for_each_keyed(at, &mut |property, keyed| {
792 if let Keyed::Times(times, before, after) = keyed {
793 self.check_times(property, times, before, after);
794 }
795 });
796 }
797
798 fn check_point(&mut self, property: &str, animated: &AnimatedPoint) {
799 visit_keyed_point(property, animated, &mut |property, keyed| {
800 if let Keyed::Times(times, before, after) = keyed {
801 self.check_times(property, times, before, after);
802 }
803 });
804 }
805
806 fn check<T: Placed>(&mut self, property: &str, animated: &Animated<T>) {
807 visit_keyed(property, animated, &mut |property, keyed| {
808 if let Keyed::Times(times, before, after) = keyed {
809 self.check_times(property, times, before, after);
810 }
811 });
812 }
813
814 fn check_times(
815 &mut self,
816 property: &str,
817 times: &[MediaTime],
818 before: Extrapolation,
819 after: Extrapolation,
820 ) {
821 let [start, .., end] = times else {
822 return self.check_held(property, times, &[]);
823 };
824 let shown_before = self.shown.iter().any(|&(first, _)| first < start.ticks());
825 let shown_after = self.shown.iter().any(|&(_, last)| last > end.ticks());
826 let shown_at_the_end = self.shown.iter().any(|&(_, last)| last >= end.ticks());
827 let repeats = |extrapolation| {
828 matches!(
829 extrapolation,
830 Extrapolation::Repeat | Extrapolation::RepeatOffset | Extrapolation::PingPong
831 )
832 };
833 let wraps_at_the_end = matches!(after, Extrapolation::Repeat | Extrapolation::RepeatOffset);
834 if (shown_before && repeats(before))
835 || (shown_after && repeats(after))
836 || (shown_at_the_end && wraps_at_the_end)
837 {
838 return;
839 }
840 let mut continued = Vec::new();
841 if shown_before && before == Extrapolation::Linear {
842 continued.push(1);
843 }
844 if shown_after && after == Extrapolation::Linear {
845 continued.push(times.len() - 2);
846 }
847 self.check_held(property, times, &continued);
848 }
849
850 fn check_held(&mut self, property: &str, times: &[MediaTime], reached_anyway: &[usize]) {
853 for (index, time) in times.iter().enumerate() {
854 let after = index.checked_sub(1).map_or(i64::MIN, |previous| {
855 times[previous].ticks().saturating_add(1)
856 });
857 let before = times
858 .get(index + 1)
859 .map_or(i64::MAX, |next| next.ticks().saturating_sub(1));
860 let reached = reached_anyway.contains(&index)
861 || self
862 .shown
863 .iter()
864 .any(|&(first, last)| after.max(first) <= before.min(last));
865 if !reached {
866 self.issues.push(LintIssue::UnreachedKeyframe {
867 owner: self.owner.clone(),
868 property: property.to_owned(),
869 time: *time,
870 });
871 }
872 }
873 }
874}
875
876#[derive(Default)]
885struct Shown<'a> {
886 compositions: HashMap<&'a CompositionId, Vec<(i64, i64)>>,
887 sources: HashMap<&'a SourceId, Vec<(i64, i64)>>,
888}
889
890impl<'a> Shown<'a> {
891 fn of(project: &'a Project) -> Self {
892 let (base, unbounded) = Self::clips(project);
893 let mut shown = base.propagated(project);
894 shown.drop_unbounded(project, unbounded);
895 shown
896 }
897
898 fn clips(project: &'a Project) -> (Self, Vec<&'a CompositionId>) {
901 let mut base = Self::default();
902 let mut unbounded = Vec::new();
903 for clip in project
904 .timeline
905 .tracks
906 .iter()
907 .flat_map(|track| &track.clips)
908 {
909 let picture = match &clip.time_map {
910 crate::TimeMap::Freeze { source_time } => {
911 (source_time.ticks(), source_time.ticks())
912 }
913 crate::TimeMap::Forward
914 | crate::TimeMap::Reverse
915 | crate::TimeMap::Loop { .. }
916 | crate::TimeMap::Curve { .. } => span(clip.source_range),
917 };
918 base.sources
919 .entry(&clip.source_id)
920 .or_default()
921 .push(picture);
922 if let Some(composition) = &clip.composition {
923 let start = clip.timeline_range.start();
924 let last = MediaTime(clip.timeline_range.end().ticks() - 1);
925 match (
926 composition.local_time(start, start),
927 composition.local_time(start, last),
928 ) {
929 (Some(first), Some(last)) => base
930 .compositions
931 .entry(&composition.id)
932 .or_default()
933 .push((first.ticks(), last.ticks())),
934 _ => unbounded.push(&composition.id),
935 }
936 }
937 }
938 (base, unbounded)
939 }
940
941 fn propagated(self, project: &'a Project) -> Self {
945 let mut shown = Self {
946 compositions: self.compositions.clone(),
947 sources: self.sources.clone(),
948 };
949 shown.normalize();
950 let shifts: HashMap<&CompositionId, Vec<(i64, i64)>> = project
951 .compositions
952 .iter()
953 .filter_map(|composition| {
954 Some((
955 &composition.id,
956 crate::time_offset::shift_spans(composition)?,
957 ))
958 })
959 .collect();
960 for _ in 0..=project.compositions.len() + project.sources.len() {
961 let mut next = Self {
962 compositions: self.compositions.clone(),
963 sources: self.sources.clone(),
964 };
965 for source in &project.sources {
966 if let (Some(composition), Some(spans)) =
967 (&source.composition, shown.sources.get(&source.id))
968 {
969 next.compositions
970 .entry(composition)
971 .or_default()
972 .extend(spans);
973 }
974 }
975 for composition in &project.compositions {
976 let Some(spans) = shown.compositions.get(&composition.id) else {
977 continue;
978 };
979 let shifts = shifts.get(&composition.id);
980 for (position, node) in composition.nodes.iter().enumerate() {
981 let shifted = shifts.map(|shifts| widened(spans, shifts[position]));
982 let spans = shifted.as_ref().unwrap_or(spans);
983 match &node.op {
984 crate::NodeOp::Group { composition, .. } => {
985 next.compositions
986 .entry(composition)
987 .or_default()
988 .extend(spans);
989 }
990 crate::NodeOp::Media {
991 source_id, start, ..
992 } => {
993 next.sources
994 .entry(source_id)
995 .or_default()
996 .extend(spans.iter().map(|&(first, last)| {
997 (
998 first.saturating_add(start.ticks()),
999 last.saturating_add(start.ticks()),
1000 )
1001 }));
1002 }
1003 _ => {}
1004 }
1005 }
1006 }
1007 next.normalize();
1008 if next.compositions == shown.compositions && next.sources == shown.sources {
1009 break;
1010 }
1011 shown = next;
1012 }
1013 shown
1014 }
1015
1016 fn drop_unbounded(&mut self, project: &'a Project, mut unbounded: Vec<&'a CompositionId>) {
1019 while let Some(id) = unbounded.pop() {
1020 self.compositions.remove(id);
1021 let Some(composition) = project.compositions.iter().find(|held| held.id == *id) else {
1022 continue;
1023 };
1024 for node in &composition.nodes {
1025 match &node.op {
1026 crate::NodeOp::Group { composition, .. } => {
1027 if self.compositions.contains_key(composition) {
1028 unbounded.push(composition);
1029 }
1030 }
1031 crate::NodeOp::Media { source_id, .. } => {
1032 self.sources.remove(source_id);
1033 if let Some(inner) = project
1034 .sources
1035 .iter()
1036 .find(|source| source.id == *source_id)
1037 .and_then(|source| source.composition.as_ref())
1038 && self.compositions.contains_key(inner)
1039 {
1040 unbounded.push(inner);
1041 }
1042 }
1043 _ => {}
1044 }
1045 }
1046 }
1047 }
1048
1049 fn normalize(&mut self) {
1051 fn merge(spans: &mut Vec<(i64, i64)>) {
1052 spans.sort_unstable();
1053 let mut merged: Vec<(i64, i64)> = Vec::with_capacity(spans.len());
1054 for &(first, last) in spans.iter() {
1055 match merged.last_mut() {
1056 Some(held) if first <= held.1.saturating_add(1) => held.1 = held.1.max(last),
1057 _ => merged.push((first, last)),
1058 }
1059 }
1060 *spans = merged;
1061 }
1062 self.compositions.values_mut().for_each(merge);
1063 self.sources.values_mut().for_each(merge);
1064 }
1065}
1066
1067pub(crate) fn node_keyed(
1070 op: &crate::NodeOp,
1071 visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1072) {
1073 use crate::animation::{visit_keyed, visit_keyed_point};
1074 match op {
1075 crate::NodeOp::Effect { effect, .. } => effect_keyed(effect, "effect.params", visit),
1076 crate::NodeOp::Transition {
1077 effect, progress, ..
1078 } => {
1079 effect_keyed(effect, "effect.params", visit);
1080 visit_keyed("progress", progress, visit);
1081 }
1082 crate::NodeOp::Transform { transform, .. } => {
1083 visit_keyed_point("transform.position", &transform.position, visit);
1084 visit_keyed("transform.scale", &transform.scale, visit);
1085 visit_keyed(
1086 "transform.rotation_degrees",
1087 &transform.rotation_degrees,
1088 visit,
1089 );
1090 visit_keyed("transform.opacity", &transform.opacity, visit);
1091 }
1092 crate::NodeOp::Merge { layers } => {
1093 for (index, layer) in layers.iter().enumerate() {
1094 visit_keyed(&format!("layers[{index}].opacity"), &layer.opacity, visit);
1095 }
1096 }
1097 crate::NodeOp::KeyMix { opacity, .. } => visit_keyed("opacity", opacity, visit),
1098 crate::NodeOp::ShapeMask { masks, .. } => {
1099 for (index, mask) in masks.iter().enumerate() {
1100 mask.shape
1101 .for_each_keyed(&format!("masks[{index}].shape"), visit);
1102 visit_keyed(&format!("masks[{index}].feather"), &mask.feather, visit);
1103 }
1104 }
1105 crate::NodeOp::Group { controls, .. } => {
1106 for (name, value) in controls {
1107 visit_keyed(&format!("controls.{name}"), value, visit);
1108 }
1109 }
1110 crate::NodeOp::Generator { generator } => match generator {
1111 Generator::Shapes { items } => {
1112 crate::shapes::for_each_keyed_item(items, "generator.items", visit);
1113 }
1114 Generator::Layout { root } => root.for_each_keyed("generator.root", visit),
1115 Generator::Text { style, .. } => crate::text_animation::for_each_keyed_animator(
1116 &style.animators,
1117 "generator.style.animators",
1118 visit,
1119 ),
1120 Generator::Effect { effect } => {
1121 effect_keyed(effect, "generator.effect.params", visit);
1122 }
1123 Generator::Fill { .. } => {}
1124 },
1125 crate::NodeOp::Clip {}
1126 | crate::NodeOp::Media { .. }
1127 | crate::NodeOp::Matte { .. }
1128 | crate::NodeOp::GroupInput { .. }
1129 | crate::NodeOp::TimeOffset { .. } => {}
1130 }
1131}
1132
1133pub(crate) fn effect_keyed(
1134 effect: &crate::ClipEffect,
1135 at: &str,
1136 visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1137) {
1138 for (name, value) in &effect.params {
1139 crate::animation::visit_keyed(&format!("{at}.{name}"), value, visit);
1140 }
1141}
1142
1143fn lint_shape_items(
1146 owner: &ShapeLintOwner,
1147 items: &[ShapeItem],
1148 at: &str,
1149 issues: &mut Vec<LintIssue>,
1150) -> bool {
1151 let mut geometry = false;
1152 for (index, item) in items.iter().enumerate() {
1153 let at = format!("{at}[{index}]");
1154 match item {
1155 ShapeItem::Group { items, .. } => {
1156 geometry |= lint_shape_items(owner, items, &format!("{at}.items"), issues);
1157 }
1158 ShapeItem::Rectangle(_) | ShapeItem::Ellipse(_) | ShapeItem::Polystar(_) => {
1159 geometry = true;
1160 }
1161 ShapeItem::Path(path) => {
1162 geometry = true;
1163 let paths: Vec<&crate::Path> = match &path.path {
1164 Animated::Constant { value } => vec![value],
1165 Animated::Keyframes { keyframes, .. } => {
1166 keyframes.iter().map(|keyframe| &keyframe.value).collect()
1167 }
1168 Animated::Data(_) | Animated::Split { .. } => Vec::new(),
1169 };
1170 if let Some(first) = paths.first() {
1172 for (subpath, entry) in first.subpaths.iter().enumerate() {
1173 if entry.vertices.is_empty() {
1174 issues.push(LintIssue::EmptySubpath {
1175 owner: owner.clone(),
1176 at: format!("{at}.path.subpaths[{subpath}]"),
1177 });
1178 }
1179 }
1180 }
1181 }
1182 ShapeItem::Fill { .. } | ShapeItem::Stroke(_) => {
1183 if !geometry {
1184 issues.push(LintIssue::PaintWithoutGeometry {
1185 owner: owner.clone(),
1186 at,
1187 });
1188 }
1189 }
1190 ShapeItem::Trim(_) => {}
1191 }
1192 }
1193 geometry
1194}
1195
1196fn empty_animators(
1198 owner: &LintOwner,
1199 animators: &[crate::TextAnimator],
1200 at: &str,
1201 issues: &mut Vec<LintIssue>,
1202) {
1203 for (index, animator) in animators.iter().enumerate() {
1204 if animator.properties.is_empty() {
1205 issues.push(LintIssue::EmptyTextAnimator {
1206 owner: owner.clone(),
1207 at: format!("{at}[{index}]"),
1208 });
1209 }
1210 }
1211}
1212
1213fn lint_cues(grid: &FrameGrid, track: &crate::Track, issues: &mut Vec<LintIssue>) {
1215 for (index, cue) in track
1216 .captions
1217 .iter()
1218 .flat_map(|captions| captions.cues.iter())
1219 .enumerate()
1220 {
1221 let owner = LintOwner::Cue {
1222 track: track.id.clone(),
1223 index,
1224 };
1225 grid.check(&owner, cue.timeline_range, issues);
1226 for (run, timed) in cue.text.runs().iter().enumerate() {
1229 let Some(time) = timed.time else {
1230 continue;
1231 };
1232 let start = cue.timeline_range.start().ticks();
1233 let Ok(range) = alpha2_time::TimeRange::new(
1234 MediaTime(start.saturating_add(time.start.ticks())),
1235 MediaTime(start.saturating_add(time.end.ticks())),
1236 ) else {
1237 continue;
1238 };
1239 let owner = LintOwner::CueRun {
1240 track: track.id.clone(),
1241 cue: index,
1242 run,
1243 };
1244 grid.check(&owner, range, issues);
1245 }
1246 }
1247}
1248
1249fn lint_caption_animators(
1252 track: &TrackId,
1253 captions: &crate::Captions,
1254 issues: &mut Vec<LintIssue>,
1255) {
1256 let owner = LintOwner::CaptionTrack {
1257 track: track.clone(),
1258 };
1259 let spans = captions
1260 .cues
1261 .iter()
1262 .filter_map(|cue| cue.timeline_range.duration())
1263 .map(|duration| (0, duration.ticks().saturating_sub(1)))
1264 .collect::<Vec<_>>();
1265 let mut keyframes = Keyframes {
1266 owner: &owner,
1267 shown: &spans,
1268 issues,
1269 };
1270 crate::text_animation::for_each_keyed_animator(
1271 &captions.style.animators,
1272 "style.animators",
1273 &mut |property, keyed| {
1274 if let Keyed::Times(times, before, after) = keyed {
1275 keyframes.check_times(property, times, before, after);
1276 }
1277 },
1278 );
1279 empty_animators(&owner, &captions.style.animators, "style.animators", issues);
1280 let timed = captions
1281 .cues
1282 .iter()
1283 .any(|cue| cue.text.runs().iter().any(|run| run.time.is_some()));
1284 if !timed {
1285 let highlights = captions
1286 .style
1287 .highlight
1288 .is_some()
1289 .then(|| "style.highlight".to_owned())
1290 .into_iter()
1291 .chain(
1292 captions
1293 .styles
1294 .iter()
1295 .filter(|(_, patch)| matches!(patch.highlight, Some(Some(_))))
1296 .map(|(name, _)| format!("styles.{name}.highlight")),
1297 );
1298 for at in highlights {
1299 issues.push(LintIssue::HighlightWithoutTimedRuns {
1300 owner: owner.clone(),
1301 at,
1302 });
1303 }
1304 }
1305 for name in captions.styles.keys() {
1306 let used = captions.cues.iter().any(|cue| {
1307 cue.style.as_deref() == Some(name.as_str())
1308 || (cue.style.is_none() && cue.speaker.as_deref() == Some(name.as_str()))
1309 });
1310 if !used {
1311 issues.push(LintIssue::UnusedCaptionStyle {
1312 track: track.clone(),
1313 style: name.clone(),
1314 });
1315 }
1316 }
1317}