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;
7use crate::{
8    Animated, AnimatedPoint, ClipId, CompositionId, Generator, MediaKind, NodeId, Paint, Project,
9    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 text animator that sets no property, which changes nothing.
104    EmptyTextAnimator {
105        /// What holds the text.
106        owner: LintOwner,
107        /// The animator, like `style.animators[0]` or, in a layout,
108        /// `root.children[1].text_animators[0]`.
109        at: String,
110    },
111    /// A highlight over a text with no timed run, which draws nothing.
112    HighlightWithoutTimedRuns {
113        /// What holds the text: a text generator, or a caption track none of whose cues has a
114        /// timed run.
115        owner: LintOwner,
116        /// The highlight, like `style.highlight` or `styles.loud.highlight`.
117        at: String,
118    },
119}
120
121/// The shapes or layout generator a shape [`LintIssue`] is about.
122#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
123#[serde(tag = "type", rename_all = "snake_case")]
124#[non_exhaustive]
125pub enum ShapeLintOwner {
126    /// A generated source's.
127    Source {
128        /// The source.
129        source: SourceId,
130    },
131    /// A composition's generator node's.
132    Node {
133        /// The composition.
134        composition: CompositionId,
135        /// The node.
136        node: NodeId,
137    },
138}
139
140/// What a [`LintIssue`] is about.
141#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
142#[serde(tag = "type", rename_all = "snake_case")]
143#[non_exhaustive]
144pub enum LintOwner {
145    /// A clip.
146    Clip {
147        /// The clip.
148        clip: ClipId,
149    },
150    /// A transition.
151    Transition {
152        /// Its track.
153        track: TrackId,
154        /// Its first clip.
155        from_clip: ClipId,
156        /// Its second clip.
157        to_clip: ClipId,
158    },
159    /// A caption cue.
160    Cue {
161        /// Its caption track.
162        track: TrackId,
163        /// Its position among the track's cues.
164        index: usize,
165    },
166    /// A composition's node, whose settings are keyed in composition time.
167    CompositionNode {
168        /// The composition.
169        composition: CompositionId,
170        /// The node.
171        node: NodeId,
172    },
173    /// A generated source, whose shapes or layout tree is keyed in picture time.
174    Source {
175        /// The source.
176        source: SourceId,
177    },
178    /// A caption track, whose style's animators are keyed in each cue's time from its start.
179    CaptionTrack {
180        /// The track.
181        track: TrackId,
182    },
183    /// A timed run of a caption cue, whose times are from the cue's start.
184    CueRun {
185        /// Its caption track.
186        track: TrackId,
187        /// Its cue's position among the track's cues.
188        cue: usize,
189        /// Its position among the cue's runs.
190        run: usize,
191    },
192}
193
194/// The end of a range a [`LintIssue`] is about.
195#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
196#[serde(rename_all = "snake_case")]
197pub enum LintEdge {
198    /// The start.
199    Start,
200    /// The end.
201    End,
202}
203
204impl Project {
205    /// [`LintIssue::StaleData`] for each source-anchored data set with a `made_from` that
206    /// `is_stale` judges different from its source's current fingerprint, in data order.
207    /// Hosts pass their fingerprint comparison; the model holds no current fingerprints.
208    #[must_use]
209    pub fn stale_data(
210        &self,
211        mut is_stale: impl FnMut(&SourceId, &crate::MediaFingerprint) -> bool,
212    ) -> Vec<LintIssue> {
213        self.data
214            .iter()
215            .filter_map(|set| {
216                let source = set.anchor.source()?;
217                let made_from = set.made_from.as_ref()?;
218                is_stale(source, made_from).then(|| LintIssue::StaleData {
219                    data: set.id.clone(),
220                    source: source.clone(),
221                })
222            })
223            .collect()
224    }
225
226    /// Diagnostics that do not stop the project rendering, in a fixed order: unused sources,
227    /// shapes generators (sources', then composition nodes'), HDR sources, each track's clips,
228    /// transitions and cues, composition nodes, then generated sources' trees.
229    #[must_use]
230    pub fn lint(&self) -> Vec<LintIssue> {
231        let mut issues = Vec::new();
232        let used = self
233            .used_sources()
234            .into_iter()
235            .map(|source| &source.id)
236            .collect::<std::collections::HashSet<_>>();
237        for source in &self.sources {
238            if !used.contains(&source.id) {
239                issues.push(LintIssue::UnusedSource {
240                    source: source.id.clone(),
241                });
242            }
243        }
244        self.lint_shapes(&mut issues);
245        let refused = self.settings.color.hdr == crate::HdrSources::Reject;
246        for source in self.hdr_sources().into_iter().filter(|_| refused) {
247            issues.push(LintIssue::HdrSource {
248                source: source.clone(),
249            });
250        }
251        let mattes = self
252            .timeline
253            .tracks
254            .iter()
255            .flat_map(|track| &track.clips)
256            .filter_map(|clip| clip.matte.as_ref().map(|matte| &matte.source))
257            .collect::<HashSet<_>>();
258        let grid = FrameGrid::new(self);
259        let covers = self.covering_clips(&mattes);
260        for (order, track) in self.timeline.tracks.iter().enumerate() {
261            for clip in &track.clips {
262                let owner = LintOwner::Clip {
263                    clip: clip.id.clone(),
264                };
265                grid.check(&owner, clip.timeline_range, &mut issues);
266                let mut keyframes = Keyframes {
267                    owner: &owner,
268                    shown: &[span(clip.timeline_range)],
269                    issues: &mut issues,
270                };
271                keyframes.check_clip(clip);
272                if track.kind == TrackKind::Video
273                    && !mattes.contains(&clip.id)
274                    && let Some(by) = covering_clip(&covers, order, clip.timeline_range)
275                {
276                    issues.push(LintIssue::HiddenClip {
277                        clip: clip.id.clone(),
278                        by: by.clone(),
279                    });
280                }
281            }
282            for transition in &track.transitions {
283                let owner = LintOwner::Transition {
284                    track: track.id.clone(),
285                    from_clip: transition.from_clip.clone(),
286                    to_clip: transition.to_clip.clone(),
287                };
288                if !grid.shows_mixed(transition.timeline_range) {
289                    issues.push(LintIssue::ShortTransition {
290                        track: track.id.clone(),
291                        from_clip: transition.from_clip.clone(),
292                        to_clip: transition.to_clip.clone(),
293                    });
294                }
295                grid.check(&owner, transition.timeline_range, &mut issues);
296                let mut keyframes = Keyframes {
297                    owner: &owner,
298                    shown: &[span(transition.timeline_range)],
299                    issues: &mut issues,
300                };
301                for (name, value) in &transition.effect.params {
302                    keyframes.check(&format!("effect.params.{name}"), value);
303                }
304            }
305            lint_cues(&grid, track, &mut issues);
306            if let Some(captions) = &track.captions {
307                lint_caption_animators(&track.id, captions, &mut issues);
308            }
309        }
310        self.lint_keyframes_in_other_times(&mut issues);
311        self.lint_text_animators(&mut issues);
312        self.lint_data_past_its_source(&mut issues);
313        issues
314    }
315
316    /// Every source-anchored data set with a time past its source's recorded duration.
317    fn lint_data_past_its_source(&self, issues: &mut Vec<LintIssue>) {
318        for set in &self.data {
319            let Some(source) = set.anchor.source() else {
320                continue;
321            };
322            let duration = self
323                .sources
324                .iter()
325                .find(|candidate| &candidate.id == source)
326                .and_then(|source| source.fingerprint.as_ref()?.duration_ticks);
327            if let (Some(duration), Some(last)) = (duration, set.last_time())
328                && last.ticks() > duration
329            {
330                issues.push(LintIssue::StaleData {
331                    data: set.id.clone(),
332                    source: source.clone(),
333                });
334            }
335        }
336    }
337
338    /// Every text animator that sets nothing, in text generators and layout text nodes.
339    fn lint_text_animators(&self, issues: &mut Vec<LintIssue>) {
340        let lint =
341            |owner: &LintOwner, generator: &Generator, at: &str, issues: &mut Vec<LintIssue>| {
342                match generator {
343                    Generator::Text { text, style } => {
344                        empty_animators(
345                            owner,
346                            &style.animators,
347                            &format!("{at}style.animators"),
348                            issues,
349                        );
350                        if style.highlight.is_some()
351                            && text.runs().iter().all(|run| run.time.is_none())
352                        {
353                            issues.push(LintIssue::HighlightWithoutTimedRuns {
354                                owner: owner.clone(),
355                                at: format!("{at}style.highlight"),
356                            });
357                        }
358                    }
359                    Generator::Layout { root } => root.walk(|path, node| {
360                        empty_animators(
361                            owner,
362                            &node.text_animators,
363                            &format!("{at}{path}.text_animators"),
364                            issues,
365                        );
366                    }),
367                    Generator::Fill { .. } | Generator::Shapes { .. } => {}
368                }
369            };
370        for source in &self.sources {
371            if let Some(generator) = &source.generator {
372                let owner = LintOwner::Source {
373                    source: source.id.clone(),
374                };
375                lint(&owner, generator, "", issues);
376            }
377        }
378        for composition in &self.compositions {
379            for node in &composition.nodes {
380                if let crate::NodeOp::Generator { generator } = &node.op {
381                    let owner = LintOwner::CompositionNode {
382                        composition: composition.id.clone(),
383                        node: node.id.clone(),
384                    };
385                    lint(&owner, generator, "generator.", issues);
386                }
387            }
388        }
389    }
390
391    /// Unreached keyframes in the other two time bases: composition nodes' settings in
392    /// composition time and generated sources' trees in picture time. Compositions or sources
393    /// that no clip shows, or whose shown times cannot be bounded, are skipped.
394    fn lint_keyframes_in_other_times(&self, issues: &mut Vec<LintIssue>) {
395        let shown = Shown::of(self);
396        for composition in &self.compositions {
397            let Some(spans) = shown.compositions.get(&composition.id) else {
398                continue;
399            };
400            for node in &composition.nodes {
401                let owner = LintOwner::CompositionNode {
402                    composition: composition.id.clone(),
403                    node: node.id.clone(),
404                };
405                let mut keyframes = Keyframes {
406                    owner: &owner,
407                    shown: spans,
408                    issues,
409                };
410                node_keyed(&node.op, &mut |property, keyed| {
411                    if let Keyed::Times(times) = keyed {
412                        keyframes.check_times(property, times);
413                    }
414                });
415            }
416        }
417        for source in &self.sources {
418            let Some(spans) = shown.sources.get(&source.id) else {
419                continue;
420            };
421            let owner = LintOwner::Source {
422                source: source.id.clone(),
423            };
424            let mut keyframes = Keyframes {
425                owner: &owner,
426                shown: spans,
427                issues,
428            };
429            let mut check = |property: &str, keyed: Keyed<'_>| {
430                if let Keyed::Times(times) = keyed {
431                    keyframes.check_times(property, times);
432                }
433            };
434            match &source.generator {
435                Some(Generator::Shapes { items }) => {
436                    crate::shapes::for_each_keyed_item(items, "items", &mut check);
437                }
438                Some(Generator::Layout { root }) => root.for_each_keyed("root", &mut check),
439                Some(Generator::Text { style, .. }) => {
440                    crate::text_animation::for_each_keyed_animator(
441                        &style.animators,
442                        "style.animators",
443                        &mut check,
444                    );
445                }
446                _ => {}
447            }
448        }
449    }
450
451    /// Empty subpaths and paints without geometry in every shapes generator and layout shape
452    /// node: sources' first, then composition nodes'.
453    fn lint_shapes(&self, issues: &mut Vec<LintIssue>) {
454        let lint = |owner: &ShapeLintOwner, generator: &Generator, issues: &mut Vec<LintIssue>| {
455            match generator {
456                Generator::Shapes { items } => {
457                    lint_shape_items(owner, items, "items", issues);
458                }
459                Generator::Layout { root } => root.walk(|at, node| {
460                    if let Some(shape) = &node.shape {
461                        lint_shape_items(owner, &shape.items, &format!("{at}.shape.items"), issues);
462                    }
463                }),
464                Generator::Fill { .. } | Generator::Text { .. } => {}
465            }
466        };
467        for source in &self.sources {
468            if let Some(generator) = &source.generator {
469                let owner = ShapeLintOwner::Source {
470                    source: source.id.clone(),
471                };
472                lint(&owner, generator, issues);
473            }
474        }
475        for composition in &self.compositions {
476            for node in &composition.nodes {
477                if let crate::NodeOp::Generator { generator } = &node.op {
478                    let owner = ShapeLintOwner::Node {
479                        composition: composition.id.clone(),
480                        node: node.id.clone(),
481                    };
482                    lint(&owner, generator, issues);
483                }
484            }
485        }
486    }
487
488    /// The video-track clips that certainly cover the whole frame opaquely outside their
489    /// transitions: composited (not a matte) and [`is_opaque_full_frame`]. In track then clip
490    /// order.
491    fn covering_clips<'a>(&'a self, mattes: &HashSet<&ClipId>) -> Vec<Cover<'a>> {
492        let sources = self
493            .sources
494            .iter()
495            .map(|source| (&source.id, source))
496            .collect::<HashMap<_, _>>();
497        let mut covers = Vec::new();
498        for (order, track) in self.timeline.tracks.iter().enumerate() {
499            if track.kind != TrackKind::Video {
500                continue;
501            }
502            for clip in &track.clips {
503                if mattes.contains(&clip.id)
504                    || !sources
505                        .get(&clip.source_id)
506                        .is_some_and(|source| is_opaque_full_frame(source, clip))
507                {
508                    continue;
509                }
510                let mixed = track
511                    .transitions
512                    .iter()
513                    .filter(|transition| {
514                        transition.from_clip == clip.id || transition.to_clip == clip.id
515                    })
516                    .map(|transition| transition.timeline_range)
517                    .collect();
518                covers.push(Cover { order, clip, mixed });
519            }
520        }
521        covers
522    }
523}
524
525/// A clip that covers the whole frame opaquely, except during its transitions.
526struct Cover<'a> {
527    /// Its track's position.
528    order: usize,
529    clip: &'a crate::Clip,
530    /// Its transitions' ranges, where it is mixed with another clip.
531    mixed: Vec<TimeRange>,
532}
533
534/// A clip on a track after `order` that covers the frame for all of `range`.
535fn covering_clip<'a>(covers: &[Cover<'a>], order: usize, range: TimeRange) -> Option<&'a ClipId> {
536    covers
537        .iter()
538        .filter(|cover| cover.order > order)
539        .find(|cover| {
540            cover.clip.timeline_range.start() <= range.start()
541                && cover.clip.timeline_range.end() >= range.end()
542                && !cover
543                    .mixed
544                    .iter()
545                    .any(|mixed| mixed.intersection(range).is_some())
546        })
547        .map(|cover| &cover.clip.id)
548}
549
550/// Whether a clip draws an opaque fill over the whole frame: a generated fill of opaque
551/// paint with no transform, blend, mask or composition.
552fn is_opaque_full_frame(source: &crate::MediaSource, clip: &crate::Clip) -> bool {
553    let opaque = source.kind == MediaKind::Generated
554        && matches!(&source.generator, Some(Generator::Fill { paint }) if paint_is_opaque(paint));
555    opaque
556        && clip.visual == crate::VisualProperties::default()
557        && clip.blend_mode == crate::ClipBlendMode::Normal
558        && clip.composition.is_none()
559        && clip.masks.is_empty()
560        && clip.matte.is_none()
561}
562
563fn paint_is_opaque(paint: &Paint) -> bool {
564    match paint {
565        Paint::Solid { color } => color.alpha >= 1.0,
566        Paint::LinearGradient { stops, .. }
567        | Paint::RadialGradient { stops, .. }
568        | Paint::ConicGradient { stops, .. } => stops.iter().all(|stop| stop.color.alpha >= 1.0),
569    }
570}
571
572/// The project's frames as the engine renders them: frame `k` at
573/// [`FrameRate::frame_start`], its exact start rounded down to a tick.
574struct FrameGrid {
575    rate: FrameRate,
576}
577
578impl FrameGrid {
579    fn new(project: &Project) -> Self {
580        Self {
581            rate: project.settings.frame_rate,
582        }
583    }
584
585    fn on_grid(&self, time: MediaTime) -> bool {
586        self.rate
587            .frame_at_or_before(time)
588            .and_then(|frame| self.rate.frame_start(frame))
589            == Some(time)
590    }
591
592    /// Whether a frame shows a transition over `range` as a mix, i.e. the evaluator's progress
593    /// `clamp((t - start + F/2) / D, 0, 1)` is below 1 at some frame start `t` in the range.
594    /// Progress grows with `t`, so the first frame start decides. Unsure counts as shown.
595    fn shows_mixed(&self, range: TimeRange) -> bool {
596        let first = self
597            .rate
598            .frame_at_or_before(range.start())
599            .and_then(|frame| {
600                let start = self.rate.frame_start(frame)?;
601                if start == range.start() {
602                    Some(start)
603                } else {
604                    self.rate.frame_start(frame.checked_add(1)?)
605                }
606            });
607        let Some(first) = first else {
608            return true;
609        };
610        let num = i128::from(self.rate.numerator());
611        let elapsed = i128::from(first.ticks()) - i128::from(range.start().ticks());
612        let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
613        // Scaled by 2 * num, as the evaluator's `centred_progress` is.
614        first < range.end()
615            && 2 * num * elapsed
616                + i128::from(TICKS_PER_SECOND) * i128::from(self.rate.denominator())
617                < 2 * num * duration
618    }
619
620    fn check(&self, owner: &LintOwner, range: TimeRange, issues: &mut Vec<LintIssue>) {
621        for (edge, time) in [
622            (LintEdge::Start, range.start()),
623            (LintEdge::End, range.end()),
624        ] {
625            if !self.on_grid(time) {
626                issues.push(LintIssue::OffFrameBoundary {
627                    owner: owner.clone(),
628                    edge,
629                    time,
630                });
631            }
632        }
633    }
634}
635
636/// Finds keyframes no shown time depends on. `shown` holds every tick span (first, last) the
637/// owner may be shown at.
638struct Keyframes<'a> {
639    owner: &'a LintOwner,
640    shown: &'a [(i64, i64)],
641    issues: &'a mut Vec<LintIssue>,
642}
643
644/// The first and last ticks of `range`.
645fn span(range: TimeRange) -> (i64, i64) {
646    (range.start().ticks(), range.end().ticks() - 1)
647}
648
649impl Keyframes<'_> {
650    fn check_clip(&mut self, clip: &crate::Clip) {
651        let visual = &clip.visual;
652        self.check_point("visual.position", &visual.position);
653        self.check("visual.scale", &visual.scale);
654        self.check("visual.rotation_degrees", &visual.rotation_degrees);
655        self.check("visual.opacity", &visual.opacity);
656        for (index, mask) in clip.masks.iter().enumerate() {
657            self.check_geometry(&format!("masks[{index}].shape"), &mask.shape);
658            self.check(&format!("masks[{index}].feather"), &mask.feather);
659        }
660        self.check("audio.gain", &clip.audio.gain);
661        self.check("audio.pan", &clip.audio.pan);
662    }
663
664    fn check_geometry(&mut self, at: &str, geometry: &ShapeGeometry) {
665        geometry.for_each_keyed(at, &mut |property, keyed| {
666            if let Keyed::Times(times) = keyed {
667                self.check_times(property, times);
668            }
669        });
670    }
671
672    fn check_point(&mut self, property: &str, animated: &AnimatedPoint) {
673        if let AnimatedPoint::Keyframes { keyframes } = animated {
674            let times: Vec<MediaTime> = keyframes.iter().map(|keyframe| keyframe.time).collect();
675            self.check_times(property, &times);
676        }
677    }
678
679    fn check<T>(&mut self, property: &str, animated: &Animated<T>) {
680        if let Animated::Keyframes { keyframes } = animated {
681            let times: Vec<MediaTime> = keyframes.iter().map(|keyframe| keyframe.time).collect();
682            self.check_times(property, &times);
683        }
684    }
685
686    /// Keyframe `i` affects values only strictly between its neighbours' times (open-ended for
687    /// the first and last), so outside every shown tick it has no effect.
688    fn check_times(&mut self, property: &str, times: &[MediaTime]) {
689        for (index, time) in times.iter().enumerate() {
690            let after = index.checked_sub(1).map_or(i64::MIN, |previous| {
691                times[previous].ticks().saturating_add(1)
692            });
693            let before = times
694                .get(index + 1)
695                .map_or(i64::MAX, |next| next.ticks().saturating_sub(1));
696            let reached = self
697                .shown
698                .iter()
699                .any(|&(first, last)| after.max(first) <= before.min(last));
700            if !reached {
701                self.issues.push(LintIssue::UnreachedKeyframe {
702                    owner: self.owner.clone(),
703                    property: property.to_owned(),
704                    time: *time,
705                });
706            }
707        }
708    }
709}
710
711/// Every tick span (first, last) each composition and each generated or composition source
712/// may be shown at.
713///
714/// Composition time comes from a clip's [`crate::ClipComposition`] mapping, a composition
715/// source's picture time, or a parent composition drawing it as a group. Picture time comes
716/// from a clip's source range through its time map, or a media node's `start` plus its
717/// composition's time. Spans may over-cover, so a keyframe outside all of them is certainly
718/// unreached. Anything whose time cannot be represented is left out with all it shows.
719#[derive(Default)]
720struct Shown<'a> {
721    compositions: HashMap<&'a CompositionId, Vec<(i64, i64)>>,
722    sources: HashMap<&'a SourceId, Vec<(i64, i64)>>,
723}
724
725impl<'a> Shown<'a> {
726    fn of(project: &'a Project) -> Self {
727        let (base, unbounded) = Self::clips(project);
728        let mut shown = base.propagated(project);
729        shown.drop_unbounded(project, unbounded);
730        shown
731    }
732
733    /// What the clips show directly (sources at their time-mapped picture times, compositions at
734    /// their mapped times), and the compositions mapped to unrepresentable times.
735    fn clips(project: &'a Project) -> (Self, Vec<&'a CompositionId>) {
736        let mut base = Self::default();
737        let mut unbounded = Vec::new();
738        for clip in project
739            .timeline
740            .tracks
741            .iter()
742            .flat_map(|track| &track.clips)
743        {
744            let picture = match clip.time_map {
745                crate::TimeMap::Freeze { source_time } => {
746                    (source_time.ticks(), source_time.ticks())
747                }
748                crate::TimeMap::Forward | crate::TimeMap::Reverse | crate::TimeMap::Loop { .. } => {
749                    span(clip.source_range)
750                }
751            };
752            base.sources
753                .entry(&clip.source_id)
754                .or_default()
755                .push(picture);
756            if let Some(composition) = &clip.composition {
757                let start = clip.timeline_range.start();
758                let last = MediaTime(clip.timeline_range.end().ticks() - 1);
759                match (
760                    composition.local_time(start, start),
761                    composition.local_time(start, last),
762                ) {
763                    (Some(first), Some(last)) => base
764                        .compositions
765                        .entry(&composition.id)
766                        .or_default()
767                        .push((first.ticks(), last.ticks())),
768                    _ => unbounded.push(&composition.id),
769                }
770            }
771        }
772        (base, unbounded)
773    }
774
775    /// Extends `self` with what it shows in turn: composition sources' compositions, groups'
776    /// compositions, and media nodes' sources. Each pass adds one level; the graph is acyclic,
777    /// so one pass per composition and source reaches every level.
778    fn propagated(self, project: &'a Project) -> Self {
779        let mut shown = Self {
780            compositions: self.compositions.clone(),
781            sources: self.sources.clone(),
782        };
783        shown.normalize();
784        for _ in 0..=project.compositions.len() + project.sources.len() {
785            let mut next = Self {
786                compositions: self.compositions.clone(),
787                sources: self.sources.clone(),
788            };
789            for source in &project.sources {
790                if let (Some(composition), Some(spans)) =
791                    (&source.composition, shown.sources.get(&source.id))
792                {
793                    next.compositions
794                        .entry(composition)
795                        .or_default()
796                        .extend(spans);
797                }
798            }
799            for composition in &project.compositions {
800                let Some(spans) = shown.compositions.get(&composition.id) else {
801                    continue;
802                };
803                for node in &composition.nodes {
804                    match &node.op {
805                        crate::NodeOp::Group { composition, .. } => {
806                            next.compositions
807                                .entry(composition)
808                                .or_default()
809                                .extend(spans);
810                        }
811                        crate::NodeOp::Media { source_id, start } => {
812                            next.sources
813                                .entry(source_id)
814                                .or_default()
815                                .extend(spans.iter().map(|&(first, last)| {
816                                    (
817                                        first.saturating_add(start.ticks()),
818                                        last.saturating_add(start.ticks()),
819                                    )
820                                }));
821                        }
822                        _ => {}
823                    }
824                }
825            }
826            next.normalize();
827            if next.compositions == shown.compositions && next.sources == shown.sources {
828                break;
829            }
830            shown = next;
831        }
832        shown
833    }
834
835    /// Leaves out the compositions in `unbounded` and what they draw (groups' compositions and
836    /// media nodes' sources).
837    fn drop_unbounded(&mut self, project: &'a Project, mut unbounded: Vec<&'a CompositionId>) {
838        while let Some(id) = unbounded.pop() {
839            self.compositions.remove(id);
840            let Some(composition) = project.compositions.iter().find(|held| held.id == *id) else {
841                continue;
842            };
843            for node in &composition.nodes {
844                match &node.op {
845                    crate::NodeOp::Group { composition, .. } => {
846                        if self.compositions.contains_key(composition) {
847                            unbounded.push(composition);
848                        }
849                    }
850                    crate::NodeOp::Media { source_id, .. } => {
851                        self.sources.remove(source_id);
852                        if let Some(inner) = project
853                            .sources
854                            .iter()
855                            .find(|source| source.id == *source_id)
856                            .and_then(|source| source.composition.as_ref())
857                            && self.compositions.contains_key(inner)
858                        {
859                            unbounded.push(inner);
860                        }
861                    }
862                    _ => {}
863                }
864            }
865        }
866    }
867
868    /// Sorts each list and merges spans that meet or touch.
869    fn normalize(&mut self) {
870        fn merge(spans: &mut Vec<(i64, i64)>) {
871            spans.sort_unstable();
872            let mut merged: Vec<(i64, i64)> = Vec::with_capacity(spans.len());
873            for &(first, last) in spans.iter() {
874                match merged.last_mut() {
875                    Some(held) if first <= held.1.saturating_add(1) => held.1 = held.1.max(last),
876                    _ => merged.push((first, last)),
877                }
878            }
879            *spans = merged;
880        }
881        self.compositions.values_mut().for_each(merge);
882        self.sources.values_mut().for_each(merge);
883    }
884}
885
886/// Calls `visit` with each keyframed setting of a node, by its path in the node
887/// (`effect.params.radius`, `generator.items[0].transform.scale`, ...), and its times.
888pub(crate) fn node_keyed(
889    op: &crate::NodeOp,
890    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
891) {
892    use crate::animation::{visit_keyed, visit_keyed_point};
893    let params = |effect: &crate::ClipEffect,
894                  visit: &mut dyn FnMut(&str, crate::animation::Keyed<'_>)| {
895        for (name, value) in &effect.params {
896            visit_keyed(&format!("effect.params.{name}"), value, &mut |at, keyed| {
897                visit(at, keyed);
898            });
899        }
900    };
901    match op {
902        crate::NodeOp::Effect { effect, .. } => params(effect, visit),
903        crate::NodeOp::Transition {
904            effect, progress, ..
905        } => {
906            params(effect, visit);
907            visit_keyed("progress", progress, visit);
908        }
909        crate::NodeOp::Transform { transform, .. } => {
910            visit_keyed_point("transform.position", &transform.position, visit);
911            visit_keyed("transform.scale", &transform.scale, visit);
912            visit_keyed(
913                "transform.rotation_degrees",
914                &transform.rotation_degrees,
915                visit,
916            );
917            visit_keyed("transform.opacity", &transform.opacity, visit);
918        }
919        crate::NodeOp::Merge { layers } => {
920            for (index, layer) in layers.iter().enumerate() {
921                visit_keyed(&format!("layers[{index}].opacity"), &layer.opacity, visit);
922            }
923        }
924        crate::NodeOp::KeyMix { opacity, .. } => visit_keyed("opacity", opacity, visit),
925        crate::NodeOp::ShapeMask { masks, .. } => {
926            for (index, mask) in masks.iter().enumerate() {
927                mask.shape
928                    .for_each_keyed(&format!("masks[{index}].shape"), visit);
929                visit_keyed(&format!("masks[{index}].feather"), &mask.feather, visit);
930            }
931        }
932        crate::NodeOp::Group { controls, .. } => {
933            for (name, value) in controls {
934                visit_keyed(&format!("controls.{name}"), value, visit);
935            }
936        }
937        crate::NodeOp::Generator { generator } => match generator {
938            Generator::Shapes { items } => {
939                crate::shapes::for_each_keyed_item(items, "generator.items", visit);
940            }
941            Generator::Layout { root } => root.for_each_keyed("generator.root", visit),
942            Generator::Text { style, .. } => crate::text_animation::for_each_keyed_animator(
943                &style.animators,
944                "generator.style.animators",
945                visit,
946            ),
947            Generator::Fill { .. } => {}
948        },
949        crate::NodeOp::Clip {}
950        | crate::NodeOp::Media { .. }
951        | crate::NodeOp::Matte { .. }
952        | crate::NodeOp::GroupInput { .. } => {}
953    }
954}
955
956/// Reports a content tree's empty subpaths and paints with nothing before them, in document
957/// order. Returns whether the items hold any geometry, for an enclosing group's paints.
958fn lint_shape_items(
959    owner: &ShapeLintOwner,
960    items: &[ShapeItem],
961    at: &str,
962    issues: &mut Vec<LintIssue>,
963) -> bool {
964    let mut geometry = false;
965    for (index, item) in items.iter().enumerate() {
966        let at = format!("{at}[{index}]");
967        match item {
968            ShapeItem::Group { items, .. } => {
969                geometry |= lint_shape_items(owner, items, &format!("{at}.items"), issues);
970            }
971            ShapeItem::Rectangle(_) | ShapeItem::Ellipse(_) | ShapeItem::Polystar(_) => {
972                geometry = true;
973            }
974            ShapeItem::Path(path) => {
975                geometry = true;
976                let paths: Vec<&crate::Path> = match &path.path {
977                    Animated::Constant { value } => vec![value],
978                    Animated::Keyframes { keyframes } => {
979                        keyframes.iter().map(|keyframe| &keyframe.value).collect()
980                    }
981                    Animated::Data(_) => Vec::new(),
982                };
983                // Keyframes share their structure, so the first tells.
984                if let Some(first) = paths.first() {
985                    for (subpath, entry) in first.subpaths.iter().enumerate() {
986                        if entry.vertices.is_empty() {
987                            issues.push(LintIssue::EmptySubpath {
988                                owner: owner.clone(),
989                                at: format!("{at}.path.subpaths[{subpath}]"),
990                            });
991                        }
992                    }
993                }
994            }
995            ShapeItem::Fill { .. } | ShapeItem::Stroke(_) => {
996                if !geometry {
997                    issues.push(LintIssue::PaintWithoutGeometry {
998                        owner: owner.clone(),
999                        at,
1000                    });
1001                }
1002            }
1003            ShapeItem::Trim(_) => {}
1004        }
1005    }
1006    geometry
1007}
1008
1009/// Each of `animators` that sets nothing, under `at`.
1010fn empty_animators(
1011    owner: &LintOwner,
1012    animators: &[crate::TextAnimator],
1013    at: &str,
1014    issues: &mut Vec<LintIssue>,
1015) {
1016    for (index, animator) in animators.iter().enumerate() {
1017        if animator.properties.is_empty() {
1018            issues.push(LintIssue::EmptyTextAnimator {
1019                owner: owner.clone(),
1020                at: format!("{at}[{index}]"),
1021            });
1022        }
1023    }
1024}
1025
1026/// Each cue's timeline range, and each timed run's, against the frame grid.
1027fn lint_cues(grid: &FrameGrid, track: &crate::Track, issues: &mut Vec<LintIssue>) {
1028    for (index, cue) in track
1029        .captions
1030        .iter()
1031        .flat_map(|captions| captions.cues.iter())
1032        .enumerate()
1033    {
1034        let owner = LintOwner::Cue {
1035            track: track.id.clone(),
1036            index,
1037        };
1038        grid.check(&owner, cue.timeline_range, issues);
1039        // A karaoke switch between frames shows at the next frame, so check each run's ends on the
1040        // timeline.
1041        for (run, timed) in cue.text.runs().iter().enumerate() {
1042            let Some(time) = timed.time else {
1043                continue;
1044            };
1045            let start = cue.timeline_range.start().ticks();
1046            let Ok(range) = alpha2_time::TimeRange::new(
1047                MediaTime(start.saturating_add(time.start.ticks())),
1048                MediaTime(start.saturating_add(time.end.ticks())),
1049            ) else {
1050                continue;
1051            };
1052            let owner = LintOwner::CueRun {
1053                track: track.id.clone(),
1054                cue: index,
1055                run,
1056            };
1057            grid.check(&owner, range, issues);
1058        }
1059    }
1060}
1061
1062/// A caption track's animators: keyframes in cue time against every cue's span, empty
1063/// animators, then styles no cue takes.
1064fn lint_caption_animators(
1065    track: &TrackId,
1066    captions: &crate::Captions,
1067    issues: &mut Vec<LintIssue>,
1068) {
1069    let owner = LintOwner::CaptionTrack {
1070        track: track.clone(),
1071    };
1072    let spans = captions
1073        .cues
1074        .iter()
1075        .filter_map(|cue| cue.timeline_range.duration())
1076        .map(|duration| (0, duration.ticks().saturating_sub(1)))
1077        .collect::<Vec<_>>();
1078    let mut keyframes = Keyframes {
1079        owner: &owner,
1080        shown: &spans,
1081        issues,
1082    };
1083    crate::text_animation::for_each_keyed_animator(
1084        &captions.style.animators,
1085        "style.animators",
1086        &mut |property, keyed| {
1087            if let Keyed::Times(times) = keyed {
1088                keyframes.check_times(property, times);
1089            }
1090        },
1091    );
1092    empty_animators(&owner, &captions.style.animators, "style.animators", issues);
1093    let timed = captions
1094        .cues
1095        .iter()
1096        .any(|cue| cue.text.runs().iter().any(|run| run.time.is_some()));
1097    if !timed {
1098        let highlights = captions
1099            .style
1100            .highlight
1101            .is_some()
1102            .then(|| "style.highlight".to_owned())
1103            .into_iter()
1104            .chain(
1105                captions
1106                    .styles
1107                    .iter()
1108                    .filter(|(_, patch)| matches!(patch.highlight, Some(Some(_))))
1109                    .map(|(name, _)| format!("styles.{name}.highlight")),
1110            );
1111        for at in highlights {
1112            issues.push(LintIssue::HighlightWithoutTimedRuns {
1113                owner: owner.clone(),
1114                at,
1115            });
1116        }
1117    }
1118    for name in captions.styles.keys() {
1119        let used = captions.cues.iter().any(|cue| {
1120            cue.style.as_deref() == Some(name.as_str())
1121                || (cue.style.is_none() && cue.speaker.as_deref() == Some(name.as_str()))
1122        });
1123        if !used {
1124            issues.push(LintIssue::UnusedCaptionStyle {
1125                track: track.clone(),
1126                style: name.clone(),
1127            });
1128        }
1129    }
1130}