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 highlight over a text with no timed run, which draws nothing.
129    HighlightWithoutTimedRuns {
130        /// What holds the text: a text generator, or a caption track none of whose cues has a
131        /// timed run.
132        owner: LintOwner,
133        /// The highlight, like `style.highlight` or `styles.loud.highlight`.
134        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/// The shapes or layout generator a shape [`LintIssue`] is about.
146#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
147#[serde(tag = "type", rename_all = "snake_case")]
148#[non_exhaustive]
149pub enum ShapeLintOwner {
150    /// A generated source's.
151    Source {
152        /// The source.
153        source: SourceId,
154    },
155    /// A composition's generator node's.
156    Node {
157        /// The composition.
158        composition: CompositionId,
159        /// The node.
160        node: NodeId,
161    },
162}
163
164/// What a [`LintIssue`] is about.
165#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
166#[serde(tag = "type", rename_all = "snake_case")]
167#[non_exhaustive]
168pub enum LintOwner {
169    /// A clip.
170    Clip {
171        /// The clip.
172        clip: ClipId,
173    },
174    /// A transition.
175    Transition {
176        /// Its track.
177        track: TrackId,
178        /// Its first clip.
179        from_clip: ClipId,
180        /// Its second clip.
181        to_clip: ClipId,
182    },
183    /// A caption cue.
184    Cue {
185        /// Its caption track.
186        track: TrackId,
187        /// Its position among the track's cues.
188        index: usize,
189    },
190    /// A composition's node, whose settings are keyed in composition time.
191    CompositionNode {
192        /// The composition.
193        composition: CompositionId,
194        /// The node.
195        node: NodeId,
196    },
197    /// A generated source, whose shapes or layout tree is keyed in picture time.
198    Source {
199        /// The source.
200        source: SourceId,
201    },
202    /// A caption track, whose style's animators are keyed in each cue's time from its start.
203    CaptionTrack {
204        /// The track.
205        track: TrackId,
206    },
207    /// A timed run of a caption cue, whose times are from the cue's start.
208    CueRun {
209        /// Its caption track.
210        track: TrackId,
211        /// Its cue's position among the track's cues.
212        cue: usize,
213        /// Its position among the cue's runs.
214        run: usize,
215    },
216}
217
218/// The end of a range a [`LintIssue`] is about.
219#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
220#[serde(rename_all = "snake_case")]
221pub enum LintEdge {
222    /// The start.
223    Start,
224    /// The end.
225    End,
226}
227
228impl Project {
229    /// [`LintIssue::StaleData`] for each source-anchored data set with a `made_from` that
230    /// `is_stale` judges different from its source's current fingerprint, in data order.
231    /// Hosts pass their fingerprint comparison; the model holds no current fingerprints.
232    #[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    /// Diagnostics that do not stop the project rendering, in a fixed order: unused sources,
251    /// shapes generators (sources', then composition nodes'), HDR sources, each track's clips,
252    /// transitions and cues, transform nodes marked for motion blur, composition nodes, then
253    /// generated sources' trees.
254    #[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    /// Every source-anchored data set with a time past its source's recorded duration.
369    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    /// Every text animator that sets nothing, in text generators and layout text nodes.
391    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    /// Unreached keyframes in the other two time bases: composition nodes' settings in
485    /// composition time and generated sources' trees in picture time. Compositions or sources
486    /// that no clip shows, or whose shown times cannot be bounded, are skipped.
487    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    /// Empty subpaths and paints without geometry in every shapes generator and layout shape
552    /// node: sources' first, then composition nodes'.
553    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    /// The video-track clips that certainly cover the whole frame opaquely outside their
589    /// transitions: composited (not a matte) and [`is_opaque_full_frame`]. In track then clip
590    /// order.
591    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
625/// A clip that covers the whole frame opaquely, except during its transitions.
626struct Cover<'a> {
627    /// Its track's position.
628    order: usize,
629    clip: &'a crate::Clip,
630    /// Its transitions' ranges, where it is mixed with another clip.
631    mixed: Vec<TimeRange>,
632}
633
634/// A clip on a track after `order` that covers the frame for all of `range`.
635fn 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
650/// Whether a clip draws an opaque fill over the whole frame: a generated fill of opaque
651/// paint with no transform, blend, mask or composition.
652fn 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
672/// The project's frames as the engine renders them: frame `k` at
673/// [`FrameRate::frame_start`], its exact start rounded down to a tick.
674struct 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    /// Whether a frame shows a transition over `range` as a mix, i.e. the evaluator's progress
693    /// `clamp((t - start + F/2) / D, 0, 1)` is below 1 at some frame start `t` in the range.
694    /// Progress grows with `t`, so the first frame start decides. Unsure counts as shown.
695    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        // Scaled by 2 * num, as the evaluator's `centred_progress` is.
714        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
736/// Finds keyframes no shown time depends on. `shown` holds every tick span (first, last) the
737/// owner may be shown at.
738struct Keyframes<'a> {
739    owner: &'a LintOwner,
740    shown: &'a [(i64, i64)],
741    issues: &'a mut Vec<LintIssue>,
742}
743
744/// The first and last ticks of `range`.
745fn 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", &times, *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    /// Keyframe `i` affects values only strictly between its neighbours' times (open-ended for
851    /// the first and last), so outside every shown tick it has no effect.
852    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/// Every tick span (first, last) each composition and each generated or composition source
877/// may be shown at.
878///
879/// Composition time comes from a clip's [`crate::ClipComposition`] mapping, a composition
880/// source's picture time, or a parent composition drawing it as a group. Picture time comes
881/// from a clip's source range through its time map, or a media node's `start` plus its
882/// composition's time. Spans may over-cover, so a keyframe outside all of them is certainly
883/// unreached. Anything whose time cannot be represented is left out with all it shows.
884#[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    /// What the clips show directly (sources at their time-mapped picture times, compositions at
899    /// their mapped times), and the compositions mapped to unrepresentable times.
900    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    /// Extends `self` with what it shows in turn: composition sources' compositions, groups'
942    /// compositions, and media nodes' sources. Each pass adds one level; the graph is acyclic,
943    /// so one pass per composition and source reaches every level.
944    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    /// Leaves out the compositions in `unbounded` and what they draw (groups' compositions and
1017    /// media nodes' sources).
1018    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    /// Sorts each list and merges spans that meet or touch.
1050    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
1067/// Calls `visit` with each keyframed setting of a node, by its path in the node
1068/// (`effect.params.radius`, `generator.items[0].transform.scale`, ...), and its times.
1069pub(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
1143/// Reports a content tree's empty subpaths and paints with nothing before them, in document
1144/// order. Returns whether the items hold any geometry, for an enclosing group's paints.
1145fn 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                // Keyframes share their structure, so the first tells.
1171                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
1196/// Each of `animators` that sets nothing, under `at`.
1197fn 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
1213/// Each cue's timeline range, and each timed run's, against the frame grid.
1214fn 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        // A karaoke switch between frames shows at the next frame, so check each run's ends on the
1227        // timeline.
1228        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
1249/// A caption track's animators: keyframes in cue time against every cue's span, empty
1250/// animators, then styles no cue takes.
1251fn 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}