Skip to main content

alpha2_model/
lint.rs

1//! Non-fatal diagnostics: what a valid project probably does not mean to do.
2//!
3//! [`Project::lint`] never refuses a project. Checks are conservative: every reported issue
4//! is certain, and a missed one is not an error.
5
6use 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/// Something in a project that is valid but probably not meant.
17#[derive(Clone, Debug, PartialEq, Serialize)]
18#[serde(tag = "kind", rename_all = "snake_case")]
19#[non_exhaustive]
20pub enum LintIssue {
21    /// A keyframe that no shown time depends on, checked in the owner's own time (timeline,
22    /// composition, or picture time).
23    UnreachedKeyframe {
24        /// What the keyframe animates.
25        owner: LintOwner,
26        /// The animated property as a path, such as `visual.opacity`, `masks[0].feather`,
27        /// `effect.params.radius` or `items[0].transform.opacity`.
28        property: String,
29        /// The keyframe's time.
30        time: MediaTime,
31    },
32    /// A clip wholly covered for its whole time by an opaque full-frame clip on a later track.
33    /// Matte clips are never reported, since they are never composited.
34    HiddenClip {
35        /// The covered clip.
36        clip: ClipId,
37        /// The clip that covers it.
38        by: ClipId,
39    },
40    /// A transition no project frame shows as a mix: shorter than a frame, or about a frame long
41    /// and starting between frames.
42    ShortTransition {
43        /// Its track.
44        track: TrackId,
45        /// Its first clip.
46        from_clip: ClipId,
47        /// Its second clip.
48        to_clip: ClipId,
49    },
50    /// A boundary that is not where a project frame starts, so the change shows at the next
51    /// frame. A frame starts at its exact start rounded down to a tick.
52    OffFrameBoundary {
53        /// Whose boundary.
54        owner: LintOwner,
55        /// Which end.
56        edge: LintEdge,
57        /// The boundary's time.
58        time: MediaTime,
59    },
60    /// A source no render reads: no clip shows it and no `media` node of a shown composition
61    /// reads it.
62    UnusedSource {
63        /// The source.
64        source: SourceId,
65    },
66    /// A high-dynamic-range source in a project whose color pipeline refuses HDR, so rendering
67    /// it fails.
68    HdrSource {
69        /// The source.
70        source: SourceId,
71    },
72    /// A path's subpath without vertices, which draws nothing.
73    EmptySubpath {
74        /// The shapes generator.
75        owner: ShapeLintOwner,
76        /// The empty subpath, like `items[0].path.subpaths[1]` or, in a layout,
77        /// `root.children[0].shape.items[0].path.subpaths[1]`.
78        at: String,
79    },
80    /// A fill or stroke with no geometry before it in its group, which paints nothing.
81    PaintWithoutGeometry {
82        /// The shapes generator.
83        owner: ShapeLintOwner,
84        /// The paint item, like `items[1].items[0]`.
85        at: String,
86    },
87    /// A caption style no cue names and no cue's speaker matches.
88    UnusedCaptionStyle {
89        /// The caption track.
90        track: TrackId,
91        /// The style's name.
92        style: String,
93    },
94    /// A source-anchored data set made from other media: its `made_from` differs from its
95    /// source's current fingerprint ([`Project::stale_data`], where the host compares), or one of
96    /// its times is past the duration its source's fingerprint records ([`Project::lint`]).
97    StaleData {
98        /// The data set.
99        data: crate::DataSetId,
100        /// Its source.
101        source: SourceId,
102    },
103    /// A clip whose composition reads one host-supplied video at more than four other times
104    /// through time offset nodes. Each such read keeps a decoder of its own.
105    ManyShiftedReads {
106        /// The clip.
107        clip: ClipId,
108        /// The video read.
109        source: SourceId,
110        /// The reads at other times.
111        count: u64,
112    },
113    /// A text animator that sets no property, which changes nothing.
114    EmptyTextAnimator {
115        /// What holds the text.
116        owner: LintOwner,
117        /// The animator, like `style.animators[0]` or, in a layout,
118        /// `root.children[1].text_animators[0]`.
119        at: String,
120    },
121    /// A clip or a composition `transform` node marked `motion_blur` whose position, scale,
122    /// rotation and opacity are all constants, so nothing is averaged and the flag changes
123    /// nothing.
124    MotionBlurWithoutMotion {
125        /// The clip or the node.
126        owner: LintOwner,
127    },
128    /// A clip on the timeline for less than one project frame, which at most one frame shows.
129    SubFrameClip {
130        /// The clip.
131        clip: ClipId,
132    },
133    /// A highlight over a text with no timed run, which draws nothing.
134    HighlightWithoutTimedRuns {
135        /// What holds the text: a text generator, or a caption track none of whose cues has a
136        /// timed run.
137        owner: LintOwner,
138        /// The highlight, like `style.highlight` or `styles.loud.highlight`.
139        at: String,
140    },
141}
142
143fn never_moves(visual: &crate::VisualProperties) -> bool {
144    matches!(visual.position, AnimatedPoint::Constant { .. })
145        && matches!(visual.scale, Animated::Constant { .. })
146        && matches!(visual.rotation_degrees, Animated::Constant { .. })
147        && matches!(visual.opacity, Animated::Constant { .. })
148}
149
150/// The shapes or layout generator a shape [`LintIssue`] is about.
151#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
152#[serde(tag = "type", rename_all = "snake_case")]
153#[non_exhaustive]
154pub enum ShapeLintOwner {
155    /// A generated source's.
156    Source {
157        /// The source.
158        source: SourceId,
159    },
160    /// A composition's generator node's.
161    Node {
162        /// The composition.
163        composition: CompositionId,
164        /// The node.
165        node: NodeId,
166    },
167}
168
169/// What a [`LintIssue`] is about.
170#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
171#[serde(tag = "type", rename_all = "snake_case")]
172#[non_exhaustive]
173pub enum LintOwner {
174    /// A clip.
175    Clip {
176        /// The clip.
177        clip: ClipId,
178    },
179    /// A transition.
180    Transition {
181        /// Its track.
182        track: TrackId,
183        /// Its first clip.
184        from_clip: ClipId,
185        /// Its second clip.
186        to_clip: ClipId,
187    },
188    /// A caption cue.
189    Cue {
190        /// Its caption track.
191        track: TrackId,
192        /// Its position among the track's cues.
193        index: usize,
194    },
195    /// A composition's node, whose settings are keyed in composition time.
196    CompositionNode {
197        /// The composition.
198        composition: CompositionId,
199        /// The node.
200        node: NodeId,
201    },
202    /// A generated source, whose shapes or layout tree is keyed in picture time.
203    Source {
204        /// The source.
205        source: SourceId,
206    },
207    /// A caption track, whose style's animators are keyed in each cue's time from its start.
208    CaptionTrack {
209        /// The track.
210        track: TrackId,
211    },
212    /// A timed run of a caption cue, whose times are from the cue's start.
213    CueRun {
214        /// Its caption track.
215        track: TrackId,
216        /// Its cue's position among the track's cues.
217        cue: usize,
218        /// Its position among the cue's runs.
219        run: usize,
220    },
221}
222
223/// The end of a range a [`LintIssue`] is about.
224#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
225#[serde(rename_all = "snake_case")]
226pub enum LintEdge {
227    /// The start.
228    Start,
229    /// The end.
230    End,
231}
232
233impl Project {
234    /// [`LintIssue::StaleData`] for each source-anchored data set with a `made_from` that
235    /// `is_stale` judges different from its source's current fingerprint, in data order.
236    /// Hosts pass their fingerprint comparison; the model holds no current fingerprints.
237    #[must_use]
238    pub fn stale_data(
239        &self,
240        mut is_stale: impl FnMut(&SourceId, &crate::MediaFingerprint) -> bool,
241    ) -> Vec<LintIssue> {
242        self.data
243            .iter()
244            .filter_map(|set| {
245                let source = set.anchor.source()?;
246                let made_from = set.made_from.as_ref()?;
247                is_stale(source, made_from).then(|| LintIssue::StaleData {
248                    data: set.id.clone(),
249                    source: source.clone(),
250                })
251            })
252            .collect()
253    }
254
255    /// Diagnostics that do not stop the project rendering, in a fixed order: unused sources,
256    /// shapes generators (sources', then composition nodes'), HDR sources, each track's clips,
257    /// transitions and cues, transform nodes marked for motion blur, composition nodes, then
258    /// generated sources' trees.
259    #[must_use]
260    pub fn lint(&self) -> Vec<LintIssue> {
261        let mut issues = Vec::new();
262        let used = self
263            .used_sources()
264            .into_iter()
265            .map(|source| &source.id)
266            .collect::<std::collections::HashSet<_>>();
267        for source in &self.sources {
268            if !used.contains(&source.id) {
269                issues.push(LintIssue::UnusedSource {
270                    source: source.id.clone(),
271                });
272            }
273        }
274        self.lint_shapes(&mut issues);
275        let refused = self.settings.color.hdr == crate::HdrSources::Reject;
276        for source in self.hdr_sources().into_iter().filter(|_| refused) {
277            issues.push(LintIssue::HdrSource {
278                source: source.clone(),
279            });
280        }
281        let mattes = self
282            .timeline
283            .tracks
284            .iter()
285            .flat_map(|track| &track.clips)
286            .filter_map(|clip| clip.matte.as_ref().map(|matte| &matte.source))
287            .collect::<HashSet<_>>();
288        let grid = FrameGrid::new(self);
289        let covers = self.covering_clips(&mattes);
290        let shifted_reads = crate::time_offset::shifted_reads(self);
291        for (order, track) in self.timeline.tracks.iter().enumerate() {
292            for clip in &track.clips {
293                self.lint_shifted_reads(clip, &shifted_reads, &mut issues);
294                let owner = LintOwner::Clip {
295                    clip: clip.id.clone(),
296                };
297                grid.check(&owner, clip.timeline_range, &mut issues);
298                if grid.shorter_than_a_frame(clip.timeline_range) {
299                    issues.push(LintIssue::SubFrameClip {
300                        clip: clip.id.clone(),
301                    });
302                }
303                let mut keyframes = Keyframes {
304                    owner: &owner,
305                    shown: &[span(clip.timeline_range)],
306                    issues: &mut issues,
307                };
308                keyframes.check_clip(clip);
309                if track.kind == TrackKind::Video
310                    && !mattes.contains(&clip.id)
311                    && let Some(by) = covering_clip(&covers, order, clip.timeline_range)
312                {
313                    issues.push(LintIssue::HiddenClip {
314                        clip: clip.id.clone(),
315                        by: by.clone(),
316                    });
317                }
318                if clip.motion_blur && never_moves(&clip.visual) {
319                    issues.push(LintIssue::MotionBlurWithoutMotion { owner });
320                }
321            }
322            for transition in &track.transitions {
323                let owner = LintOwner::Transition {
324                    track: track.id.clone(),
325                    from_clip: transition.from_clip.clone(),
326                    to_clip: transition.to_clip.clone(),
327                };
328                if !grid.shows_mixed(transition.timeline_range) {
329                    issues.push(LintIssue::ShortTransition {
330                        track: track.id.clone(),
331                        from_clip: transition.from_clip.clone(),
332                        to_clip: transition.to_clip.clone(),
333                    });
334                }
335                grid.check(&owner, transition.timeline_range, &mut issues);
336                let mut keyframes = Keyframes {
337                    owner: &owner,
338                    shown: &[span(transition.timeline_range)],
339                    issues: &mut issues,
340                };
341                for (name, value) in &transition.effect.params {
342                    keyframes.check(&format!("effect.params.{name}"), value);
343                }
344            }
345            lint_cues(&grid, track, &mut issues);
346            if let Some(captions) = &track.captions {
347                lint_caption_animators(&track.id, captions, &mut issues);
348            }
349        }
350        self.lint_marked_nodes_without_motion(&mut issues);
351        self.lint_keyframes_in_other_times(&mut issues);
352        self.lint_text_animators(&mut issues);
353        self.lint_data_past_its_source(&mut issues);
354        issues
355    }
356
357    fn lint_marked_nodes_without_motion(&self, issues: &mut Vec<LintIssue>) {
358        for composition in &self.compositions {
359            for node in &composition.nodes {
360                if let crate::NodeOp::Transform {
361                    transform,
362                    motion_blur: true,
363                    ..
364                } = &node.op
365                    && never_moves(transform)
366                {
367                    issues.push(LintIssue::MotionBlurWithoutMotion {
368                        owner: LintOwner::CompositionNode {
369                            composition: composition.id.clone(),
370                            node: node.id.clone(),
371                        },
372                    });
373                }
374            }
375        }
376    }
377
378    /// Every source-anchored data set with a time past its source's recorded duration.
379    fn lint_data_past_its_source(&self, issues: &mut Vec<LintIssue>) {
380        for set in &self.data {
381            let Some(source) = set.anchor.source() else {
382                continue;
383            };
384            let duration = self
385                .sources
386                .iter()
387                .find(|candidate| &candidate.id == source)
388                .and_then(|source| source.fingerprint.as_ref()?.duration_ticks);
389            if let (Some(duration), Some(last)) = (duration, set.last_time())
390                && last.ticks() > duration
391            {
392                issues.push(LintIssue::StaleData {
393                    data: set.id.clone(),
394                    source: source.clone(),
395                });
396            }
397        }
398    }
399
400    /// Every text animator that sets nothing, in text generators and layout text nodes.
401    fn lint_text_animators(&self, issues: &mut Vec<LintIssue>) {
402        let lint = |owner: &LintOwner,
403                    generator: &Generator,
404                    at: &str,
405                    issues: &mut Vec<LintIssue>| {
406            match generator {
407                Generator::Text { text, style } => {
408                    empty_animators(
409                        owner,
410                        &style.animators,
411                        &format!("{at}style.animators"),
412                        issues,
413                    );
414                    if style.highlight.is_some() && text.runs().iter().all(|run| run.time.is_none())
415                    {
416                        issues.push(LintIssue::HighlightWithoutTimedRuns {
417                            owner: owner.clone(),
418                            at: format!("{at}style.highlight"),
419                        });
420                    }
421                }
422                Generator::Layout { root } => root.walk(|path, node| {
423                    empty_animators(
424                        owner,
425                        &node.text_animators,
426                        &format!("{at}{path}.text_animators"),
427                        issues,
428                    );
429                }),
430                Generator::Fill { .. } | Generator::Shapes { .. } | Generator::Effect { .. } => {}
431            }
432        };
433        for source in &self.sources {
434            if let Some(generator) = &source.generator {
435                let owner = LintOwner::Source {
436                    source: source.id.clone(),
437                };
438                lint(&owner, generator, "", issues);
439            }
440        }
441        for composition in &self.compositions {
442            for node in &composition.nodes {
443                if let crate::NodeOp::Generator { generator } = &node.op {
444                    let owner = LintOwner::CompositionNode {
445                        composition: composition.id.clone(),
446                        node: node.id.clone(),
447                    };
448                    lint(&owner, generator, "generator.", issues);
449                }
450            }
451        }
452    }
453
454    fn lint_shifted_reads(
455        &self,
456        clip: &crate::Clip,
457        shifted_reads: &crate::time_offset::ShiftedReads<'_>,
458        issues: &mut Vec<LintIssue>,
459    ) {
460        use crate::time_offset::Read;
461        let Some(reads) = clip
462            .composition
463            .as_ref()
464            .and_then(|reference| shifted_reads.get(&reference.id))
465        else {
466            return;
467        };
468        let through_the_clip = reads.get(&Read::Clip).copied().unwrap_or(0);
469        for source in self
470            .sources
471            .iter()
472            .filter(|source| source.kind == MediaKind::Video)
473        {
474            let own = if source.id == clip.source_id {
475                through_the_clip
476            } else {
477                0
478            };
479            let count = reads
480                .get(&Read::Source(&source.id))
481                .copied()
482                .unwrap_or(0)
483                .saturating_add(own);
484            if count > UNREPORTED_SHIFTED_READS {
485                issues.push(LintIssue::ManyShiftedReads {
486                    clip: clip.id.clone(),
487                    source: source.id.clone(),
488                    count,
489                });
490            }
491        }
492    }
493
494    /// Unreached keyframes in the other two time bases: composition nodes' settings in
495    /// composition time and generated sources' trees in picture time. Compositions or sources
496    /// that no clip shows, or whose shown times cannot be bounded, are skipped.
497    fn lint_keyframes_in_other_times(&self, issues: &mut Vec<LintIssue>) {
498        let shown = Shown::of(self);
499        for composition in &self.compositions {
500            let Some(spans) = shown.compositions.get(&composition.id) else {
501                continue;
502            };
503            let shifts = crate::time_offset::shift_spans(composition);
504            for (position, node) in composition.nodes.iter().enumerate() {
505                let owner = LintOwner::CompositionNode {
506                    composition: composition.id.clone(),
507                    node: node.id.clone(),
508                };
509                let shifted = shifts
510                    .as_ref()
511                    .map(|shifts| widened(spans, shifts[position]));
512                let mut keyframes = Keyframes {
513                    owner: &owner,
514                    shown: shifted.as_deref().unwrap_or(spans),
515                    issues,
516                };
517                node_keyed(&node.op, &mut |property, keyed| {
518                    if let Keyed::Times(times, before, after) = keyed {
519                        keyframes.check_times(property, times, before, after);
520                    }
521                });
522            }
523        }
524        for source in &self.sources {
525            let Some(spans) = shown.sources.get(&source.id) else {
526                continue;
527            };
528            let owner = LintOwner::Source {
529                source: source.id.clone(),
530            };
531            let mut keyframes = Keyframes {
532                owner: &owner,
533                shown: spans,
534                issues,
535            };
536            let mut check = |property: &str, keyed: Keyed<'_>| {
537                if let Keyed::Times(times, before, after) = keyed {
538                    keyframes.check_times(property, times, before, after);
539                }
540            };
541            match &source.generator {
542                Some(Generator::Shapes { items }) => {
543                    crate::shapes::for_each_keyed_item(items, "items", &mut check);
544                }
545                Some(Generator::Layout { root }) => root.for_each_keyed("root", &mut check),
546                Some(Generator::Text { style, .. }) => {
547                    crate::text_animation::for_each_keyed_animator(
548                        &style.animators,
549                        "style.animators",
550                        &mut check,
551                    );
552                }
553                Some(Generator::Effect { effect }) => {
554                    effect_keyed(effect, "effect.params", &mut check);
555                }
556                Some(Generator::Fill { .. }) | None => {}
557            }
558        }
559    }
560
561    /// Empty subpaths and paints without geometry in every shapes generator and layout shape
562    /// node: sources' first, then composition nodes'.
563    fn lint_shapes(&self, issues: &mut Vec<LintIssue>) {
564        let lint = |owner: &ShapeLintOwner, generator: &Generator, issues: &mut Vec<LintIssue>| {
565            match generator {
566                Generator::Shapes { items } => {
567                    lint_shape_items(owner, items, "items", issues);
568                }
569                Generator::Layout { root } => root.walk(|at, node| {
570                    if let Some(shape) = &node.shape {
571                        lint_shape_items(owner, &shape.items, &format!("{at}.shape.items"), issues);
572                    }
573                }),
574                Generator::Fill { .. } | Generator::Text { .. } | Generator::Effect { .. } => {}
575            }
576        };
577        for source in &self.sources {
578            if let Some(generator) = &source.generator {
579                let owner = ShapeLintOwner::Source {
580                    source: source.id.clone(),
581                };
582                lint(&owner, generator, issues);
583            }
584        }
585        for composition in &self.compositions {
586            for node in &composition.nodes {
587                if let crate::NodeOp::Generator { generator } = &node.op {
588                    let owner = ShapeLintOwner::Node {
589                        composition: composition.id.clone(),
590                        node: node.id.clone(),
591                    };
592                    lint(&owner, generator, issues);
593                }
594            }
595        }
596    }
597
598    /// The video-track clips that certainly cover the whole frame opaquely outside their
599    /// transitions: composited (not a matte) and [`is_opaque_full_frame`]. In track then clip
600    /// order.
601    fn covering_clips<'a>(&'a self, mattes: &HashSet<&ClipId>) -> Vec<Cover<'a>> {
602        let sources = self
603            .sources
604            .iter()
605            .map(|source| (&source.id, source))
606            .collect::<HashMap<_, _>>();
607        let mut covers = Vec::new();
608        for (order, track) in self.timeline.tracks.iter().enumerate() {
609            if track.kind != TrackKind::Video {
610                continue;
611            }
612            for clip in &track.clips {
613                if mattes.contains(&clip.id)
614                    || !sources
615                        .get(&clip.source_id)
616                        .is_some_and(|source| is_opaque_full_frame(source, clip))
617                {
618                    continue;
619                }
620                let mixed = track
621                    .transitions
622                    .iter()
623                    .filter(|transition| {
624                        transition.from_clip == clip.id || transition.to_clip == clip.id
625                    })
626                    .map(|transition| transition.timeline_range)
627                    .collect();
628                covers.push(Cover { order, clip, mixed });
629            }
630        }
631        covers
632    }
633}
634
635/// A clip that covers the whole frame opaquely, except during its transitions.
636struct Cover<'a> {
637    /// Its track's position.
638    order: usize,
639    clip: &'a crate::Clip,
640    /// Its transitions' ranges, where it is mixed with another clip.
641    mixed: Vec<TimeRange>,
642}
643
644/// A clip on a track after `order` that covers the frame for all of `range`.
645fn covering_clip<'a>(covers: &[Cover<'a>], order: usize, range: TimeRange) -> Option<&'a ClipId> {
646    covers
647        .iter()
648        .filter(|cover| cover.order > order)
649        .find(|cover| {
650            cover.clip.timeline_range.start() <= range.start()
651                && cover.clip.timeline_range.end() >= range.end()
652                && !cover
653                    .mixed
654                    .iter()
655                    .any(|mixed| mixed.intersection(range).is_some())
656        })
657        .map(|cover| &cover.clip.id)
658}
659
660/// Whether a clip draws an opaque fill over the whole frame: a generated fill of opaque
661/// paint with no transform, blend, mask or composition.
662fn is_opaque_full_frame(source: &crate::MediaSource, clip: &crate::Clip) -> bool {
663    let opaque = source.kind == MediaKind::Generated
664        && matches!(&source.generator, Some(Generator::Fill { paint }) if paint_is_opaque(paint));
665    opaque
666        && clip.visual == crate::VisualProperties::default()
667        && clip.blend_mode == crate::ClipBlendMode::Normal
668        && clip.composition.is_none()
669        && clip.masks.is_empty()
670        && clip.matte.is_none()
671}
672
673fn paint_is_opaque(paint: &Paint) -> bool {
674    match paint {
675        Paint::Solid { color } => color.alpha >= 1.0,
676        Paint::LinearGradient { stops, .. }
677        | Paint::RadialGradient { stops, .. }
678        | Paint::ConicGradient { stops, .. } => stops.iter().all(|stop| stop.color.alpha >= 1.0),
679    }
680}
681
682/// The project's frames as the engine renders them: frame `k` at
683/// [`FrameRate::frame_start`], its exact start rounded down to a tick.
684struct FrameGrid {
685    rate: FrameRate,
686}
687
688impl FrameGrid {
689    fn new(project: &Project) -> Self {
690        Self {
691            rate: project.settings.frame_rate,
692        }
693    }
694
695    fn on_grid(&self, time: MediaTime) -> bool {
696        self.rate
697            .frame_at_or_before(time)
698            .and_then(|frame| self.rate.frame_start(frame))
699            == Some(time)
700    }
701
702    /// Whether a frame shows a transition over `range` as a mix, i.e. the evaluator's progress
703    /// `clamp((t - start + F/2) / D, 0, 1)` is below 1 at some frame start `t` in the range.
704    /// Progress grows with `t`, so the first frame start decides. Unsure counts as shown.
705    fn shows_mixed(&self, range: TimeRange) -> bool {
706        let first = self
707            .rate
708            .frame_at_or_before(range.start())
709            .and_then(|frame| {
710                let start = self.rate.frame_start(frame)?;
711                if start == range.start() {
712                    Some(start)
713                } else {
714                    self.rate.frame_start(frame.checked_add(1)?)
715                }
716            });
717        let Some(first) = first else {
718            return true;
719        };
720        let num = i128::from(self.rate.numerator());
721        let elapsed = i128::from(first.ticks()) - i128::from(range.start().ticks());
722        let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
723        // Scaled by 2 * num, as the evaluator's `centred_progress` is.
724        first < range.end()
725            && 2 * num * elapsed
726                + i128::from(TICKS_PER_SECOND) * i128::from(self.rate.denominator())
727                < 2 * num * duration
728    }
729
730    fn shorter_than_a_frame(&self, range: TimeRange) -> bool {
731        let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
732        duration * i128::from(self.rate.numerator())
733            < i128::from(TICKS_PER_SECOND) * i128::from(self.rate.denominator())
734    }
735
736    fn check(&self, owner: &LintOwner, range: TimeRange, issues: &mut Vec<LintIssue>) {
737        for (edge, time) in [
738            (LintEdge::Start, range.start()),
739            (LintEdge::End, range.end()),
740        ] {
741            if !self.on_grid(time) {
742                issues.push(LintIssue::OffFrameBoundary {
743                    owner: owner.clone(),
744                    edge,
745                    time,
746                });
747            }
748        }
749    }
750}
751
752/// Finds keyframes no shown time depends on. `shown` holds every tick span (first, last) the
753/// owner may be shown at.
754struct Keyframes<'a> {
755    owner: &'a LintOwner,
756    shown: &'a [(i64, i64)],
757    issues: &'a mut Vec<LintIssue>,
758}
759
760/// The first and last ticks of `range`.
761fn span(range: TimeRange) -> (i64, i64) {
762    (range.start().ticks(), range.end().ticks() - 1)
763}
764
765const UNREPORTED_SHIFTED_READS: u64 = 4;
766
767fn widened(spans: &[(i64, i64)], (earliest, latest): (i64, i64)) -> Vec<(i64, i64)> {
768    spans
769        .iter()
770        .map(|&(first, last)| (first.saturating_add(earliest), last.saturating_add(latest)))
771        .collect()
772}
773
774impl Keyframes<'_> {
775    fn check_clip(&mut self, clip: &crate::Clip) {
776        let visual = &clip.visual;
777        self.check_point("visual.position", &visual.position);
778        self.check("visual.scale", &visual.scale);
779        self.check("visual.rotation_degrees", &visual.rotation_degrees);
780        self.check("visual.opacity", &visual.opacity);
781        for (index, mask) in clip.masks.iter().enumerate() {
782            self.check_geometry(&format!("masks[{index}].shape"), &mask.shape);
783            self.check(&format!("masks[{index}].feather"), &mask.feather);
784        }
785        if let crate::TimeMap::Curve {
786            keyframes,
787            before,
788            after,
789        } = &clip.time_map
790        {
791            let times = keyframes.iter().map(|key| key.time).collect::<Vec<_>>();
792            self.check_times("time_map", &times, *before, *after);
793        }
794        self.check("audio.gain", &clip.audio.gain);
795        self.check("audio.pan", &clip.audio.pan);
796        for (index, effect) in clip.audio.effects.iter().enumerate() {
797            effect.for_each_param(&mut |param| {
798                self.check(
799                    &format!("audio.effects[{index}].{}", param.path()),
800                    param.value,
801                );
802            });
803        }
804    }
805
806    fn check_geometry(&mut self, at: &str, geometry: &ShapeGeometry) {
807        geometry.for_each_keyed(at, &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_point(&mut self, property: &str, animated: &AnimatedPoint) {
815        visit_keyed_point(property, animated, &mut |property, keyed| {
816            if let Keyed::Times(times, before, after) = keyed {
817                self.check_times(property, times, before, after);
818            }
819        });
820    }
821
822    fn check<T: Placed>(&mut self, property: &str, animated: &Animated<T>) {
823        visit_keyed(property, animated, &mut |property, keyed| {
824            if let Keyed::Times(times, before, after) = keyed {
825                self.check_times(property, times, before, after);
826            }
827        });
828    }
829
830    fn check_times(
831        &mut self,
832        property: &str,
833        times: &[MediaTime],
834        before: Extrapolation,
835        after: Extrapolation,
836    ) {
837        let [start, .., end] = times else {
838            return self.check_held(property, times, &[]);
839        };
840        let shown_before = self.shown.iter().any(|&(first, _)| first < start.ticks());
841        let shown_after = self.shown.iter().any(|&(_, last)| last > end.ticks());
842        let shown_at_the_end = self.shown.iter().any(|&(_, last)| last >= end.ticks());
843        let repeats = |extrapolation| {
844            matches!(
845                extrapolation,
846                Extrapolation::Repeat | Extrapolation::RepeatOffset | Extrapolation::PingPong
847            )
848        };
849        let wraps_at_the_end = matches!(after, Extrapolation::Repeat | Extrapolation::RepeatOffset);
850        if (shown_before && repeats(before))
851            || (shown_after && repeats(after))
852            || (shown_at_the_end && wraps_at_the_end)
853        {
854            return;
855        }
856        let mut continued = Vec::new();
857        if shown_before && before == Extrapolation::Linear {
858            continued.push(1);
859        }
860        if shown_after && after == Extrapolation::Linear {
861            continued.push(times.len() - 2);
862        }
863        self.check_held(property, times, &continued);
864    }
865
866    /// Keyframe `i` affects values only strictly between its neighbours' times (open-ended for
867    /// the first and last), so outside every shown tick it has no effect.
868    fn check_held(&mut self, property: &str, times: &[MediaTime], reached_anyway: &[usize]) {
869        for (index, time) in times.iter().enumerate() {
870            let after = index.checked_sub(1).map_or(i64::MIN, |previous| {
871                times[previous].ticks().saturating_add(1)
872            });
873            let before = times
874                .get(index + 1)
875                .map_or(i64::MAX, |next| next.ticks().saturating_sub(1));
876            let reached = reached_anyway.contains(&index)
877                || self
878                    .shown
879                    .iter()
880                    .any(|&(first, last)| after.max(first) <= before.min(last));
881            if !reached {
882                self.issues.push(LintIssue::UnreachedKeyframe {
883                    owner: self.owner.clone(),
884                    property: property.to_owned(),
885                    time: *time,
886                });
887            }
888        }
889    }
890}
891
892/// Every tick span (first, last) each composition and each generated or composition source
893/// may be shown at.
894///
895/// Composition time comes from a clip's [`crate::ClipComposition`] mapping, a composition
896/// source's picture time, or a parent composition drawing it as a group. Picture time comes
897/// from a clip's source range through its time map, or a media node's `start` plus its
898/// composition's time. Spans may over-cover, so a keyframe outside all of them is certainly
899/// unreached. Anything whose time cannot be represented is left out with all it shows.
900#[derive(Default)]
901struct Shown<'a> {
902    compositions: HashMap<&'a CompositionId, Vec<(i64, i64)>>,
903    sources: HashMap<&'a SourceId, Vec<(i64, i64)>>,
904}
905
906impl<'a> Shown<'a> {
907    fn of(project: &'a Project) -> Self {
908        let (base, unbounded) = Self::clips(project);
909        let mut shown = base.propagated(project);
910        shown.drop_unbounded(project, unbounded);
911        shown
912    }
913
914    /// What the clips show directly (sources at their time-mapped picture times, compositions at
915    /// their mapped times), and the compositions mapped to unrepresentable times.
916    fn clips(project: &'a Project) -> (Self, Vec<&'a CompositionId>) {
917        let mut base = Self::default();
918        let mut unbounded = Vec::new();
919        for clip in project
920            .timeline
921            .tracks
922            .iter()
923            .flat_map(|track| &track.clips)
924        {
925            let picture = match &clip.time_map {
926                crate::TimeMap::Freeze { source_time } => {
927                    (source_time.ticks(), source_time.ticks())
928                }
929                crate::TimeMap::Forward
930                | crate::TimeMap::Reverse
931                | crate::TimeMap::Loop { .. }
932                | crate::TimeMap::Curve { .. } => span(clip.source_range),
933            };
934            base.sources
935                .entry(&clip.source_id)
936                .or_default()
937                .push(picture);
938            if let Some(composition) = &clip.composition {
939                let start = clip.timeline_range.start();
940                let last = MediaTime(clip.timeline_range.end().ticks() - 1);
941                match (
942                    composition.local_time(start, start),
943                    composition.local_time(start, last),
944                ) {
945                    (Some(first), Some(last)) => base
946                        .compositions
947                        .entry(&composition.id)
948                        .or_default()
949                        .push((first.ticks(), last.ticks())),
950                    _ => unbounded.push(&composition.id),
951                }
952            }
953        }
954        (base, unbounded)
955    }
956
957    /// Extends `self` with what it shows in turn: composition sources' compositions, groups'
958    /// compositions, and media nodes' sources. Each pass adds one level; the graph is acyclic,
959    /// so one pass per composition and source reaches every level.
960    fn propagated(self, project: &'a Project) -> Self {
961        let mut shown = Self {
962            compositions: self.compositions.clone(),
963            sources: self.sources.clone(),
964        };
965        shown.normalize();
966        let shifts: HashMap<&CompositionId, Vec<(i64, i64)>> = project
967            .compositions
968            .iter()
969            .filter_map(|composition| {
970                Some((
971                    &composition.id,
972                    crate::time_offset::shift_spans(composition)?,
973                ))
974            })
975            .collect();
976        for _ in 0..=project.compositions.len() + project.sources.len() {
977            let mut next = Self {
978                compositions: self.compositions.clone(),
979                sources: self.sources.clone(),
980            };
981            for source in &project.sources {
982                if let (Some(composition), Some(spans)) =
983                    (&source.composition, shown.sources.get(&source.id))
984                {
985                    next.compositions
986                        .entry(composition)
987                        .or_default()
988                        .extend(spans);
989                }
990            }
991            for composition in &project.compositions {
992                let Some(spans) = shown.compositions.get(&composition.id) else {
993                    continue;
994                };
995                let shifts = shifts.get(&composition.id);
996                for (position, node) in composition.nodes.iter().enumerate() {
997                    let shifted = shifts.map(|shifts| widened(spans, shifts[position]));
998                    let spans = shifted.as_ref().unwrap_or(spans);
999                    match &node.op {
1000                        crate::NodeOp::Group { composition, .. } => {
1001                            next.compositions
1002                                .entry(composition)
1003                                .or_default()
1004                                .extend(spans);
1005                        }
1006                        crate::NodeOp::Media {
1007                            source_id, start, ..
1008                        } => {
1009                            next.sources
1010                                .entry(source_id)
1011                                .or_default()
1012                                .extend(spans.iter().map(|&(first, last)| {
1013                                    (
1014                                        first.saturating_add(start.ticks()),
1015                                        last.saturating_add(start.ticks()),
1016                                    )
1017                                }));
1018                        }
1019                        _ => {}
1020                    }
1021                }
1022            }
1023            next.normalize();
1024            if next.compositions == shown.compositions && next.sources == shown.sources {
1025                break;
1026            }
1027            shown = next;
1028        }
1029        shown
1030    }
1031
1032    /// Leaves out the compositions in `unbounded` and what they draw (groups' compositions and
1033    /// media nodes' sources).
1034    fn drop_unbounded(&mut self, project: &'a Project, mut unbounded: Vec<&'a CompositionId>) {
1035        while let Some(id) = unbounded.pop() {
1036            self.compositions.remove(id);
1037            let Some(composition) = project.compositions.iter().find(|held| held.id == *id) else {
1038                continue;
1039            };
1040            for node in &composition.nodes {
1041                match &node.op {
1042                    crate::NodeOp::Group { composition, .. } => {
1043                        if self.compositions.contains_key(composition) {
1044                            unbounded.push(composition);
1045                        }
1046                    }
1047                    crate::NodeOp::Media { source_id, .. } => {
1048                        self.sources.remove(source_id);
1049                        if let Some(inner) = project
1050                            .sources
1051                            .iter()
1052                            .find(|source| source.id == *source_id)
1053                            .and_then(|source| source.composition.as_ref())
1054                            && self.compositions.contains_key(inner)
1055                        {
1056                            unbounded.push(inner);
1057                        }
1058                    }
1059                    _ => {}
1060                }
1061            }
1062        }
1063    }
1064
1065    /// Sorts each list and merges spans that meet or touch.
1066    fn normalize(&mut self) {
1067        fn merge(spans: &mut Vec<(i64, i64)>) {
1068            spans.sort_unstable();
1069            let mut merged: Vec<(i64, i64)> = Vec::with_capacity(spans.len());
1070            for &(first, last) in spans.iter() {
1071                match merged.last_mut() {
1072                    Some(held) if first <= held.1.saturating_add(1) => held.1 = held.1.max(last),
1073                    _ => merged.push((first, last)),
1074                }
1075            }
1076            *spans = merged;
1077        }
1078        self.compositions.values_mut().for_each(merge);
1079        self.sources.values_mut().for_each(merge);
1080    }
1081}
1082
1083/// Calls `visit` with each keyframed setting of a node, by its path in the node
1084/// (`effect.params.radius`, `generator.items[0].transform.scale`, ...), and its times.
1085pub(crate) fn node_keyed(
1086    op: &crate::NodeOp,
1087    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1088) {
1089    use crate::animation::{visit_keyed, visit_keyed_point};
1090    match op {
1091        crate::NodeOp::Effect { effect, .. } => effect_keyed(effect, "effect.params", visit),
1092        crate::NodeOp::Transition {
1093            effect, progress, ..
1094        } => {
1095            effect_keyed(effect, "effect.params", visit);
1096            visit_keyed("progress", progress, visit);
1097        }
1098        crate::NodeOp::Transform { transform, .. } => {
1099            visit_keyed_point("transform.position", &transform.position, visit);
1100            visit_keyed("transform.scale", &transform.scale, visit);
1101            visit_keyed(
1102                "transform.rotation_degrees",
1103                &transform.rotation_degrees,
1104                visit,
1105            );
1106            visit_keyed("transform.opacity", &transform.opacity, visit);
1107        }
1108        crate::NodeOp::Merge { layers } => {
1109            for (index, layer) in layers.iter().enumerate() {
1110                visit_keyed(&format!("layers[{index}].opacity"), &layer.opacity, visit);
1111            }
1112        }
1113        crate::NodeOp::KeyMix { opacity, .. } => visit_keyed("opacity", opacity, visit),
1114        crate::NodeOp::ShapeMask { masks, .. } => {
1115            for (index, mask) in masks.iter().enumerate() {
1116                mask.shape
1117                    .for_each_keyed(&format!("masks[{index}].shape"), visit);
1118                visit_keyed(&format!("masks[{index}].feather"), &mask.feather, visit);
1119            }
1120        }
1121        crate::NodeOp::Group { controls, .. } => {
1122            for (name, value) in controls {
1123                visit_keyed(&format!("controls.{name}"), value, visit);
1124            }
1125        }
1126        crate::NodeOp::Generator { generator } => match generator {
1127            Generator::Shapes { items } => {
1128                crate::shapes::for_each_keyed_item(items, "generator.items", visit);
1129            }
1130            Generator::Layout { root } => root.for_each_keyed("generator.root", visit),
1131            Generator::Text { style, .. } => crate::text_animation::for_each_keyed_animator(
1132                &style.animators,
1133                "generator.style.animators",
1134                visit,
1135            ),
1136            Generator::Effect { effect } => {
1137                effect_keyed(effect, "generator.effect.params", visit);
1138            }
1139            Generator::Fill { .. } => {}
1140        },
1141        crate::NodeOp::Clip {}
1142        | crate::NodeOp::Media { .. }
1143        | crate::NodeOp::Matte { .. }
1144        | crate::NodeOp::GroupInput { .. }
1145        | crate::NodeOp::TimeOffset { .. } => {}
1146    }
1147}
1148
1149pub(crate) fn effect_keyed(
1150    effect: &crate::ClipEffect,
1151    at: &str,
1152    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1153) {
1154    for (name, value) in &effect.params {
1155        crate::animation::visit_keyed(&format!("{at}.{name}"), value, visit);
1156    }
1157}
1158
1159/// Reports a content tree's empty subpaths and paints with nothing before them, in document
1160/// order. Returns whether the items hold any geometry, for an enclosing group's paints.
1161fn lint_shape_items(
1162    owner: &ShapeLintOwner,
1163    items: &[ShapeItem],
1164    at: &str,
1165    issues: &mut Vec<LintIssue>,
1166) -> bool {
1167    let mut geometry = false;
1168    for (index, item) in items.iter().enumerate() {
1169        let at = format!("{at}[{index}]");
1170        match item {
1171            ShapeItem::Group { items, .. } => {
1172                geometry |= lint_shape_items(owner, items, &format!("{at}.items"), issues);
1173            }
1174            ShapeItem::Rectangle(_) | ShapeItem::Ellipse(_) | ShapeItem::Polystar(_) => {
1175                geometry = true;
1176            }
1177            ShapeItem::Path(path) => {
1178                geometry = true;
1179                let paths: Vec<&crate::Path> = match &path.path {
1180                    Animated::Constant { value } => vec![value],
1181                    Animated::Keyframes { keyframes, .. } => {
1182                        keyframes.iter().map(|keyframe| &keyframe.value).collect()
1183                    }
1184                    Animated::Data(_) | Animated::Split { .. } => Vec::new(),
1185                };
1186                // Keyframes share their structure, so the first tells.
1187                if let Some(first) = paths.first() {
1188                    for (subpath, entry) in first.subpaths.iter().enumerate() {
1189                        if entry.vertices.is_empty() {
1190                            issues.push(LintIssue::EmptySubpath {
1191                                owner: owner.clone(),
1192                                at: format!("{at}.path.subpaths[{subpath}]"),
1193                            });
1194                        }
1195                    }
1196                }
1197            }
1198            ShapeItem::Fill { .. } | ShapeItem::Stroke(_) => {
1199                if !geometry {
1200                    issues.push(LintIssue::PaintWithoutGeometry {
1201                        owner: owner.clone(),
1202                        at,
1203                    });
1204                }
1205            }
1206            ShapeItem::Trim(_) => {}
1207        }
1208    }
1209    geometry
1210}
1211
1212/// Each of `animators` that sets nothing, under `at`.
1213fn empty_animators(
1214    owner: &LintOwner,
1215    animators: &[crate::TextAnimator],
1216    at: &str,
1217    issues: &mut Vec<LintIssue>,
1218) {
1219    for (index, animator) in animators.iter().enumerate() {
1220        if animator.properties.is_empty() {
1221            issues.push(LintIssue::EmptyTextAnimator {
1222                owner: owner.clone(),
1223                at: format!("{at}[{index}]"),
1224            });
1225        }
1226    }
1227}
1228
1229/// Each cue's timeline range, and each timed run's, against the frame grid.
1230fn lint_cues(grid: &FrameGrid, track: &crate::Track, issues: &mut Vec<LintIssue>) {
1231    for (index, cue) in track
1232        .captions
1233        .iter()
1234        .flat_map(|captions| captions.cues.iter())
1235        .enumerate()
1236    {
1237        let owner = LintOwner::Cue {
1238            track: track.id.clone(),
1239            index,
1240        };
1241        grid.check(&owner, cue.timeline_range, issues);
1242        // A karaoke switch between frames shows at the next frame, so check each run's ends on the
1243        // timeline.
1244        for (run, timed) in cue.text.runs().iter().enumerate() {
1245            let Some(time) = timed.time else {
1246                continue;
1247            };
1248            let start = cue.timeline_range.start().ticks();
1249            let Ok(range) = alpha2_time::TimeRange::new(
1250                MediaTime(start.saturating_add(time.start.ticks())),
1251                MediaTime(start.saturating_add(time.end.ticks())),
1252            ) else {
1253                continue;
1254            };
1255            let owner = LintOwner::CueRun {
1256                track: track.id.clone(),
1257                cue: index,
1258                run,
1259            };
1260            grid.check(&owner, range, issues);
1261        }
1262    }
1263}
1264
1265/// A caption track's animators: keyframes in cue time against every cue's span, empty
1266/// animators, then styles no cue takes.
1267fn lint_caption_animators(
1268    track: &TrackId,
1269    captions: &crate::Captions,
1270    issues: &mut Vec<LintIssue>,
1271) {
1272    let owner = LintOwner::CaptionTrack {
1273        track: track.clone(),
1274    };
1275    let spans = captions
1276        .cues
1277        .iter()
1278        .filter_map(|cue| cue.timeline_range.duration())
1279        .map(|duration| (0, duration.ticks().saturating_sub(1)))
1280        .collect::<Vec<_>>();
1281    let mut keyframes = Keyframes {
1282        owner: &owner,
1283        shown: &spans,
1284        issues,
1285    };
1286    crate::text_animation::for_each_keyed_animator(
1287        &captions.style.animators,
1288        "style.animators",
1289        &mut |property, keyed| {
1290            if let Keyed::Times(times, before, after) = keyed {
1291                keyframes.check_times(property, times, before, after);
1292            }
1293        },
1294    );
1295    empty_animators(&owner, &captions.style.animators, "style.animators", issues);
1296    let timed = captions
1297        .cues
1298        .iter()
1299        .any(|cue| cue.text.runs().iter().any(|run| run.time.is_some()));
1300    if !timed {
1301        let highlights = captions
1302            .style
1303            .highlight
1304            .is_some()
1305            .then(|| "style.highlight".to_owned())
1306            .into_iter()
1307            .chain(
1308                captions
1309                    .styles
1310                    .iter()
1311                    .filter(|(_, patch)| matches!(patch.highlight, Some(Some(_))))
1312                    .map(|(name, _)| format!("styles.{name}.highlight")),
1313            );
1314        for at in highlights {
1315            issues.push(LintIssue::HighlightWithoutTimedRuns {
1316                owner: owner.clone(),
1317                at,
1318            });
1319        }
1320    }
1321    for name in captions.styles.keys() {
1322        let used = captions.cues.iter().any(|cue| {
1323            cue.style.as_deref() == Some(name.as_str())
1324                || (cue.style.is_none() && cue.speaker.as_deref() == Some(name.as_str()))
1325        });
1326        if !used {
1327            issues.push(LintIssue::UnusedCaptionStyle {
1328                track: track.clone(),
1329                style: name.clone(),
1330            });
1331        }
1332    }
1333}