use crate::animation::{Keyed, Placed, visit_keyed, visit_keyed_point};
use crate::{
Animated, AnimatedPoint, ClipId, CompositionId, Extrapolation, Generator, MediaKind, NodeId,
Paint, Project, ShapeGeometry, ShapeItem, TrackId, TrackKind,
};
use alpha2_media::SourceId;
use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum LintIssue {
UnreachedKeyframe {
owner: LintOwner,
property: String,
time: MediaTime,
},
HiddenClip {
clip: ClipId,
by: ClipId,
},
ShortTransition {
track: TrackId,
from_clip: ClipId,
to_clip: ClipId,
},
OffFrameBoundary {
owner: LintOwner,
edge: LintEdge,
time: MediaTime,
},
UnusedSource {
source: SourceId,
},
HdrSource {
source: SourceId,
},
EmptySubpath {
owner: ShapeLintOwner,
at: String,
},
PaintWithoutGeometry {
owner: ShapeLintOwner,
at: String,
},
UnusedCaptionStyle {
track: TrackId,
style: String,
},
StaleData {
data: crate::DataSetId,
source: SourceId,
},
ManyShiftedReads {
clip: ClipId,
source: SourceId,
count: u64,
},
EmptyTextAnimator {
owner: LintOwner,
at: String,
},
MotionBlurWithoutMotion {
owner: LintOwner,
},
SubFrameClip {
clip: ClipId,
},
HighlightWithoutTimedRuns {
owner: LintOwner,
at: String,
},
}
fn never_moves(visual: &crate::VisualProperties) -> bool {
matches!(visual.position, AnimatedPoint::Constant { .. })
&& matches!(visual.scale, Animated::Constant { .. })
&& matches!(visual.rotation_degrees, Animated::Constant { .. })
&& matches!(visual.opacity, Animated::Constant { .. })
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ShapeLintOwner {
Source {
source: SourceId,
},
Node {
composition: CompositionId,
node: NodeId,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum LintOwner {
Clip {
clip: ClipId,
},
Transition {
track: TrackId,
from_clip: ClipId,
to_clip: ClipId,
},
Cue {
track: TrackId,
index: usize,
},
CompositionNode {
composition: CompositionId,
node: NodeId,
},
Source {
source: SourceId,
},
CaptionTrack {
track: TrackId,
},
CueRun {
track: TrackId,
cue: usize,
run: usize,
},
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LintEdge {
Start,
End,
}
impl Project {
#[must_use]
pub fn stale_data(
&self,
mut is_stale: impl FnMut(&SourceId, &crate::MediaFingerprint) -> bool,
) -> Vec<LintIssue> {
self.data
.iter()
.filter_map(|set| {
let source = set.anchor.source()?;
let made_from = set.made_from.as_ref()?;
is_stale(source, made_from).then(|| LintIssue::StaleData {
data: set.id.clone(),
source: source.clone(),
})
})
.collect()
}
#[must_use]
pub fn lint(&self) -> Vec<LintIssue> {
let mut issues = Vec::new();
let used = self
.used_sources()
.into_iter()
.map(|source| &source.id)
.collect::<std::collections::HashSet<_>>();
for source in &self.sources {
if !used.contains(&source.id) {
issues.push(LintIssue::UnusedSource {
source: source.id.clone(),
});
}
}
self.lint_shapes(&mut issues);
let refused = self.settings.color.hdr == crate::HdrSources::Reject;
for source in self.hdr_sources().into_iter().filter(|_| refused) {
issues.push(LintIssue::HdrSource {
source: source.clone(),
});
}
let mattes = self
.timeline
.tracks
.iter()
.flat_map(|track| &track.clips)
.filter_map(|clip| clip.matte.as_ref().map(|matte| &matte.source))
.collect::<HashSet<_>>();
let grid = FrameGrid::new(self);
let covers = self.covering_clips(&mattes);
let shifted_reads = crate::time_offset::shifted_reads(self);
for (order, track) in self.timeline.tracks.iter().enumerate() {
for clip in &track.clips {
self.lint_shifted_reads(clip, &shifted_reads, &mut issues);
let owner = LintOwner::Clip {
clip: clip.id.clone(),
};
grid.check(&owner, clip.timeline_range, &mut issues);
if grid.shorter_than_a_frame(clip.timeline_range) {
issues.push(LintIssue::SubFrameClip {
clip: clip.id.clone(),
});
}
let mut keyframes = Keyframes {
owner: &owner,
shown: &[span(clip.timeline_range)],
issues: &mut issues,
};
keyframes.check_clip(clip);
if track.kind == TrackKind::Video
&& !mattes.contains(&clip.id)
&& let Some(by) = covering_clip(&covers, order, clip.timeline_range)
{
issues.push(LintIssue::HiddenClip {
clip: clip.id.clone(),
by: by.clone(),
});
}
if clip.motion_blur && never_moves(&clip.visual) {
issues.push(LintIssue::MotionBlurWithoutMotion { owner });
}
}
for transition in &track.transitions {
let owner = LintOwner::Transition {
track: track.id.clone(),
from_clip: transition.from_clip.clone(),
to_clip: transition.to_clip.clone(),
};
if !grid.shows_mixed(transition.timeline_range) {
issues.push(LintIssue::ShortTransition {
track: track.id.clone(),
from_clip: transition.from_clip.clone(),
to_clip: transition.to_clip.clone(),
});
}
grid.check(&owner, transition.timeline_range, &mut issues);
let mut keyframes = Keyframes {
owner: &owner,
shown: &[span(transition.timeline_range)],
issues: &mut issues,
};
for (name, value) in &transition.effect.params {
keyframes.check(&format!("effect.params.{name}"), value);
}
}
lint_cues(&grid, track, &mut issues);
if let Some(captions) = &track.captions {
lint_caption_animators(&track.id, captions, &mut issues);
}
}
self.lint_marked_nodes_without_motion(&mut issues);
self.lint_keyframes_in_other_times(&mut issues);
self.lint_text_animators(&mut issues);
self.lint_data_past_its_source(&mut issues);
issues
}
fn lint_marked_nodes_without_motion(&self, issues: &mut Vec<LintIssue>) {
for composition in &self.compositions {
for node in &composition.nodes {
if let crate::NodeOp::Transform {
transform,
motion_blur: true,
..
} = &node.op
&& never_moves(transform)
{
issues.push(LintIssue::MotionBlurWithoutMotion {
owner: LintOwner::CompositionNode {
composition: composition.id.clone(),
node: node.id.clone(),
},
});
}
}
}
}
fn lint_data_past_its_source(&self, issues: &mut Vec<LintIssue>) {
for set in &self.data {
let Some(source) = set.anchor.source() else {
continue;
};
let duration = self
.sources
.iter()
.find(|candidate| &candidate.id == source)
.and_then(|source| source.fingerprint.as_ref()?.duration_ticks);
if let (Some(duration), Some(last)) = (duration, set.last_time())
&& last.ticks() > duration
{
issues.push(LintIssue::StaleData {
data: set.id.clone(),
source: source.clone(),
});
}
}
}
fn lint_text_animators(&self, issues: &mut Vec<LintIssue>) {
let lint = |owner: &LintOwner,
generator: &Generator,
at: &str,
issues: &mut Vec<LintIssue>| {
match generator {
Generator::Text { text, style } => {
empty_animators(
owner,
&style.animators,
&format!("{at}style.animators"),
issues,
);
if style.highlight.is_some() && text.runs().iter().all(|run| run.time.is_none())
{
issues.push(LintIssue::HighlightWithoutTimedRuns {
owner: owner.clone(),
at: format!("{at}style.highlight"),
});
}
}
Generator::Layout { root } => root.walk(|path, node| {
empty_animators(
owner,
&node.text_animators,
&format!("{at}{path}.text_animators"),
issues,
);
}),
Generator::Fill { .. } | Generator::Shapes { .. } | Generator::Effect { .. } => {}
}
};
for source in &self.sources {
if let Some(generator) = &source.generator {
let owner = LintOwner::Source {
source: source.id.clone(),
};
lint(&owner, generator, "", issues);
}
}
for composition in &self.compositions {
for node in &composition.nodes {
if let crate::NodeOp::Generator { generator } = &node.op {
let owner = LintOwner::CompositionNode {
composition: composition.id.clone(),
node: node.id.clone(),
};
lint(&owner, generator, "generator.", issues);
}
}
}
}
fn lint_shifted_reads(
&self,
clip: &crate::Clip,
shifted_reads: &crate::time_offset::ShiftedReads<'_>,
issues: &mut Vec<LintIssue>,
) {
use crate::time_offset::Read;
let Some(reads) = clip
.composition
.as_ref()
.and_then(|reference| shifted_reads.get(&reference.id))
else {
return;
};
let through_the_clip = reads.get(&Read::Clip).copied().unwrap_or(0);
for source in self
.sources
.iter()
.filter(|source| source.kind == MediaKind::Video)
{
let own = if source.id == clip.source_id {
through_the_clip
} else {
0
};
let count = reads
.get(&Read::Source(&source.id))
.copied()
.unwrap_or(0)
.saturating_add(own);
if count > UNREPORTED_SHIFTED_READS {
issues.push(LintIssue::ManyShiftedReads {
clip: clip.id.clone(),
source: source.id.clone(),
count,
});
}
}
}
fn lint_keyframes_in_other_times(&self, issues: &mut Vec<LintIssue>) {
let shown = Shown::of(self);
for composition in &self.compositions {
let Some(spans) = shown.compositions.get(&composition.id) else {
continue;
};
let shifts = crate::time_offset::shift_spans(composition);
for (position, node) in composition.nodes.iter().enumerate() {
let owner = LintOwner::CompositionNode {
composition: composition.id.clone(),
node: node.id.clone(),
};
let shifted = shifts
.as_ref()
.map(|shifts| widened(spans, shifts[position]));
let mut keyframes = Keyframes {
owner: &owner,
shown: shifted.as_deref().unwrap_or(spans),
issues,
};
node_keyed(&node.op, &mut |property, keyed| {
if let Keyed::Times(times, before, after) = keyed {
keyframes.check_times(property, times, before, after);
}
});
}
}
for source in &self.sources {
let Some(spans) = shown.sources.get(&source.id) else {
continue;
};
let owner = LintOwner::Source {
source: source.id.clone(),
};
let mut keyframes = Keyframes {
owner: &owner,
shown: spans,
issues,
};
let mut check = |property: &str, keyed: Keyed<'_>| {
if let Keyed::Times(times, before, after) = keyed {
keyframes.check_times(property, times, before, after);
}
};
match &source.generator {
Some(Generator::Shapes { items }) => {
crate::shapes::for_each_keyed_item(items, "items", &mut check);
}
Some(Generator::Layout { root }) => root.for_each_keyed("root", &mut check),
Some(Generator::Text { style, .. }) => {
crate::text_animation::for_each_keyed_animator(
&style.animators,
"style.animators",
&mut check,
);
}
Some(Generator::Effect { effect }) => {
effect_keyed(effect, "effect.params", &mut check);
}
Some(Generator::Fill { .. }) | None => {}
}
}
}
fn lint_shapes(&self, issues: &mut Vec<LintIssue>) {
let lint = |owner: &ShapeLintOwner, generator: &Generator, issues: &mut Vec<LintIssue>| {
match generator {
Generator::Shapes { items } => {
lint_shape_items(owner, items, "items", issues);
}
Generator::Layout { root } => root.walk(|at, node| {
if let Some(shape) = &node.shape {
lint_shape_items(owner, &shape.items, &format!("{at}.shape.items"), issues);
}
}),
Generator::Fill { .. } | Generator::Text { .. } | Generator::Effect { .. } => {}
}
};
for source in &self.sources {
if let Some(generator) = &source.generator {
let owner = ShapeLintOwner::Source {
source: source.id.clone(),
};
lint(&owner, generator, issues);
}
}
for composition in &self.compositions {
for node in &composition.nodes {
if let crate::NodeOp::Generator { generator } = &node.op {
let owner = ShapeLintOwner::Node {
composition: composition.id.clone(),
node: node.id.clone(),
};
lint(&owner, generator, issues);
}
}
}
}
fn covering_clips<'a>(&'a self, mattes: &HashSet<&ClipId>) -> Vec<Cover<'a>> {
let sources = self
.sources
.iter()
.map(|source| (&source.id, source))
.collect::<HashMap<_, _>>();
let mut covers = Vec::new();
for (order, track) in self.timeline.tracks.iter().enumerate() {
if track.kind != TrackKind::Video {
continue;
}
for clip in &track.clips {
if mattes.contains(&clip.id)
|| !sources
.get(&clip.source_id)
.is_some_and(|source| is_opaque_full_frame(source, clip))
{
continue;
}
let mixed = track
.transitions
.iter()
.filter(|transition| {
transition.from_clip == clip.id || transition.to_clip == clip.id
})
.map(|transition| transition.timeline_range)
.collect();
covers.push(Cover { order, clip, mixed });
}
}
covers
}
}
struct Cover<'a> {
order: usize,
clip: &'a crate::Clip,
mixed: Vec<TimeRange>,
}
fn covering_clip<'a>(covers: &[Cover<'a>], order: usize, range: TimeRange) -> Option<&'a ClipId> {
covers
.iter()
.filter(|cover| cover.order > order)
.find(|cover| {
cover.clip.timeline_range.start() <= range.start()
&& cover.clip.timeline_range.end() >= range.end()
&& !cover
.mixed
.iter()
.any(|mixed| mixed.intersection(range).is_some())
})
.map(|cover| &cover.clip.id)
}
fn is_opaque_full_frame(source: &crate::MediaSource, clip: &crate::Clip) -> bool {
let opaque = source.kind == MediaKind::Generated
&& matches!(&source.generator, Some(Generator::Fill { paint }) if paint_is_opaque(paint));
opaque
&& clip.visual == crate::VisualProperties::default()
&& clip.blend_mode == crate::ClipBlendMode::Normal
&& clip.composition.is_none()
&& clip.masks.is_empty()
&& clip.matte.is_none()
}
fn paint_is_opaque(paint: &Paint) -> bool {
match paint {
Paint::Solid { color } => color.alpha >= 1.0,
Paint::LinearGradient { stops, .. }
| Paint::RadialGradient { stops, .. }
| Paint::ConicGradient { stops, .. } => stops.iter().all(|stop| stop.color.alpha >= 1.0),
}
}
struct FrameGrid {
rate: FrameRate,
}
impl FrameGrid {
fn new(project: &Project) -> Self {
Self {
rate: project.settings.frame_rate,
}
}
fn on_grid(&self, time: MediaTime) -> bool {
self.rate
.frame_at_or_before(time)
.and_then(|frame| self.rate.frame_start(frame))
== Some(time)
}
fn shows_mixed(&self, range: TimeRange) -> bool {
let first = self
.rate
.frame_at_or_before(range.start())
.and_then(|frame| {
let start = self.rate.frame_start(frame)?;
if start == range.start() {
Some(start)
} else {
self.rate.frame_start(frame.checked_add(1)?)
}
});
let Some(first) = first else {
return true;
};
let num = i128::from(self.rate.numerator());
let elapsed = i128::from(first.ticks()) - i128::from(range.start().ticks());
let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
first < range.end()
&& 2 * num * elapsed
+ i128::from(TICKS_PER_SECOND) * i128::from(self.rate.denominator())
< 2 * num * duration
}
fn shorter_than_a_frame(&self, range: TimeRange) -> bool {
let duration = i128::from(range.end().ticks()) - i128::from(range.start().ticks());
duration * i128::from(self.rate.numerator())
< i128::from(TICKS_PER_SECOND) * i128::from(self.rate.denominator())
}
fn check(&self, owner: &LintOwner, range: TimeRange, issues: &mut Vec<LintIssue>) {
for (edge, time) in [
(LintEdge::Start, range.start()),
(LintEdge::End, range.end()),
] {
if !self.on_grid(time) {
issues.push(LintIssue::OffFrameBoundary {
owner: owner.clone(),
edge,
time,
});
}
}
}
}
struct Keyframes<'a> {
owner: &'a LintOwner,
shown: &'a [(i64, i64)],
issues: &'a mut Vec<LintIssue>,
}
fn span(range: TimeRange) -> (i64, i64) {
(range.start().ticks(), range.end().ticks() - 1)
}
const UNREPORTED_SHIFTED_READS: u64 = 4;
fn widened(spans: &[(i64, i64)], (earliest, latest): (i64, i64)) -> Vec<(i64, i64)> {
spans
.iter()
.map(|&(first, last)| (first.saturating_add(earliest), last.saturating_add(latest)))
.collect()
}
impl Keyframes<'_> {
fn check_clip(&mut self, clip: &crate::Clip) {
let visual = &clip.visual;
self.check_point("visual.position", &visual.position);
self.check("visual.scale", &visual.scale);
self.check("visual.rotation_degrees", &visual.rotation_degrees);
self.check("visual.opacity", &visual.opacity);
for (index, mask) in clip.masks.iter().enumerate() {
self.check_geometry(&format!("masks[{index}].shape"), &mask.shape);
self.check(&format!("masks[{index}].feather"), &mask.feather);
}
if let crate::TimeMap::Curve {
keyframes,
before,
after,
} = &clip.time_map
{
let times = keyframes.iter().map(|key| key.time).collect::<Vec<_>>();
self.check_times("time_map", ×, *before, *after);
}
self.check("audio.gain", &clip.audio.gain);
self.check("audio.pan", &clip.audio.pan);
for (index, effect) in clip.audio.effects.iter().enumerate() {
effect.for_each_param(&mut |param| {
self.check(
&format!("audio.effects[{index}].{}", param.path()),
param.value,
);
});
}
}
fn check_geometry(&mut self, at: &str, geometry: &ShapeGeometry) {
geometry.for_each_keyed(at, &mut |property, keyed| {
if let Keyed::Times(times, before, after) = keyed {
self.check_times(property, times, before, after);
}
});
}
fn check_point(&mut self, property: &str, animated: &AnimatedPoint) {
visit_keyed_point(property, animated, &mut |property, keyed| {
if let Keyed::Times(times, before, after) = keyed {
self.check_times(property, times, before, after);
}
});
}
fn check<T: Placed>(&mut self, property: &str, animated: &Animated<T>) {
visit_keyed(property, animated, &mut |property, keyed| {
if let Keyed::Times(times, before, after) = keyed {
self.check_times(property, times, before, after);
}
});
}
fn check_times(
&mut self,
property: &str,
times: &[MediaTime],
before: Extrapolation,
after: Extrapolation,
) {
let [start, .., end] = times else {
return self.check_held(property, times, &[]);
};
let shown_before = self.shown.iter().any(|&(first, _)| first < start.ticks());
let shown_after = self.shown.iter().any(|&(_, last)| last > end.ticks());
let shown_at_the_end = self.shown.iter().any(|&(_, last)| last >= end.ticks());
let repeats = |extrapolation| {
matches!(
extrapolation,
Extrapolation::Repeat | Extrapolation::RepeatOffset | Extrapolation::PingPong
)
};
let wraps_at_the_end = matches!(after, Extrapolation::Repeat | Extrapolation::RepeatOffset);
if (shown_before && repeats(before))
|| (shown_after && repeats(after))
|| (shown_at_the_end && wraps_at_the_end)
{
return;
}
let mut continued = Vec::new();
if shown_before && before == Extrapolation::Linear {
continued.push(1);
}
if shown_after && after == Extrapolation::Linear {
continued.push(times.len() - 2);
}
self.check_held(property, times, &continued);
}
fn check_held(&mut self, property: &str, times: &[MediaTime], reached_anyway: &[usize]) {
for (index, time) in times.iter().enumerate() {
let after = index.checked_sub(1).map_or(i64::MIN, |previous| {
times[previous].ticks().saturating_add(1)
});
let before = times
.get(index + 1)
.map_or(i64::MAX, |next| next.ticks().saturating_sub(1));
let reached = reached_anyway.contains(&index)
|| self
.shown
.iter()
.any(|&(first, last)| after.max(first) <= before.min(last));
if !reached {
self.issues.push(LintIssue::UnreachedKeyframe {
owner: self.owner.clone(),
property: property.to_owned(),
time: *time,
});
}
}
}
}
#[derive(Default)]
struct Shown<'a> {
compositions: HashMap<&'a CompositionId, Vec<(i64, i64)>>,
sources: HashMap<&'a SourceId, Vec<(i64, i64)>>,
}
impl<'a> Shown<'a> {
fn of(project: &'a Project) -> Self {
let (base, unbounded) = Self::clips(project);
let mut shown = base.propagated(project);
shown.drop_unbounded(project, unbounded);
shown
}
fn clips(project: &'a Project) -> (Self, Vec<&'a CompositionId>) {
let mut base = Self::default();
let mut unbounded = Vec::new();
for clip in project
.timeline
.tracks
.iter()
.flat_map(|track| &track.clips)
{
let picture = match &clip.time_map {
crate::TimeMap::Freeze { source_time } => {
(source_time.ticks(), source_time.ticks())
}
crate::TimeMap::Forward
| crate::TimeMap::Reverse
| crate::TimeMap::Loop { .. }
| crate::TimeMap::Curve { .. } => span(clip.source_range),
};
base.sources
.entry(&clip.source_id)
.or_default()
.push(picture);
if let Some(composition) = &clip.composition {
let start = clip.timeline_range.start();
let last = MediaTime(clip.timeline_range.end().ticks() - 1);
match (
composition.local_time(start, start),
composition.local_time(start, last),
) {
(Some(first), Some(last)) => base
.compositions
.entry(&composition.id)
.or_default()
.push((first.ticks(), last.ticks())),
_ => unbounded.push(&composition.id),
}
}
}
(base, unbounded)
}
fn propagated(self, project: &'a Project) -> Self {
let mut shown = Self {
compositions: self.compositions.clone(),
sources: self.sources.clone(),
};
shown.normalize();
let shifts: HashMap<&CompositionId, Vec<(i64, i64)>> = project
.compositions
.iter()
.filter_map(|composition| {
Some((
&composition.id,
crate::time_offset::shift_spans(composition)?,
))
})
.collect();
for _ in 0..=project.compositions.len() + project.sources.len() {
let mut next = Self {
compositions: self.compositions.clone(),
sources: self.sources.clone(),
};
for source in &project.sources {
if let (Some(composition), Some(spans)) =
(&source.composition, shown.sources.get(&source.id))
{
next.compositions
.entry(composition)
.or_default()
.extend(spans);
}
}
for composition in &project.compositions {
let Some(spans) = shown.compositions.get(&composition.id) else {
continue;
};
let shifts = shifts.get(&composition.id);
for (position, node) in composition.nodes.iter().enumerate() {
let shifted = shifts.map(|shifts| widened(spans, shifts[position]));
let spans = shifted.as_ref().unwrap_or(spans);
match &node.op {
crate::NodeOp::Group { composition, .. } => {
next.compositions
.entry(composition)
.or_default()
.extend(spans);
}
crate::NodeOp::Media {
source_id, start, ..
} => {
next.sources
.entry(source_id)
.or_default()
.extend(spans.iter().map(|&(first, last)| {
(
first.saturating_add(start.ticks()),
last.saturating_add(start.ticks()),
)
}));
}
_ => {}
}
}
}
next.normalize();
if next.compositions == shown.compositions && next.sources == shown.sources {
break;
}
shown = next;
}
shown
}
fn drop_unbounded(&mut self, project: &'a Project, mut unbounded: Vec<&'a CompositionId>) {
while let Some(id) = unbounded.pop() {
self.compositions.remove(id);
let Some(composition) = project.compositions.iter().find(|held| held.id == *id) else {
continue;
};
for node in &composition.nodes {
match &node.op {
crate::NodeOp::Group { composition, .. } => {
if self.compositions.contains_key(composition) {
unbounded.push(composition);
}
}
crate::NodeOp::Media { source_id, .. } => {
self.sources.remove(source_id);
if let Some(inner) = project
.sources
.iter()
.find(|source| source.id == *source_id)
.and_then(|source| source.composition.as_ref())
&& self.compositions.contains_key(inner)
{
unbounded.push(inner);
}
}
_ => {}
}
}
}
}
fn normalize(&mut self) {
fn merge(spans: &mut Vec<(i64, i64)>) {
spans.sort_unstable();
let mut merged: Vec<(i64, i64)> = Vec::with_capacity(spans.len());
for &(first, last) in spans.iter() {
match merged.last_mut() {
Some(held) if first <= held.1.saturating_add(1) => held.1 = held.1.max(last),
_ => merged.push((first, last)),
}
}
*spans = merged;
}
self.compositions.values_mut().for_each(merge);
self.sources.values_mut().for_each(merge);
}
}
pub(crate) fn node_keyed(
op: &crate::NodeOp,
visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
) {
use crate::animation::{visit_keyed, visit_keyed_point};
match op {
crate::NodeOp::Effect { effect, .. } => effect_keyed(effect, "effect.params", visit),
crate::NodeOp::Transition {
effect, progress, ..
} => {
effect_keyed(effect, "effect.params", visit);
visit_keyed("progress", progress, visit);
}
crate::NodeOp::Transform { transform, .. } => {
visit_keyed_point("transform.position", &transform.position, visit);
visit_keyed("transform.scale", &transform.scale, visit);
visit_keyed(
"transform.rotation_degrees",
&transform.rotation_degrees,
visit,
);
visit_keyed("transform.opacity", &transform.opacity, visit);
}
crate::NodeOp::Merge { layers } => {
for (index, layer) in layers.iter().enumerate() {
visit_keyed(&format!("layers[{index}].opacity"), &layer.opacity, visit);
}
}
crate::NodeOp::KeyMix { opacity, .. } => visit_keyed("opacity", opacity, visit),
crate::NodeOp::ShapeMask { masks, .. } => {
for (index, mask) in masks.iter().enumerate() {
mask.shape
.for_each_keyed(&format!("masks[{index}].shape"), visit);
visit_keyed(&format!("masks[{index}].feather"), &mask.feather, visit);
}
}
crate::NodeOp::Group { controls, .. } => {
for (name, value) in controls {
visit_keyed(&format!("controls.{name}"), value, visit);
}
}
crate::NodeOp::Generator { generator } => match generator {
Generator::Shapes { items } => {
crate::shapes::for_each_keyed_item(items, "generator.items", visit);
}
Generator::Layout { root } => root.for_each_keyed("generator.root", visit),
Generator::Text { style, .. } => crate::text_animation::for_each_keyed_animator(
&style.animators,
"generator.style.animators",
visit,
),
Generator::Effect { effect } => {
effect_keyed(effect, "generator.effect.params", visit);
}
Generator::Fill { .. } => {}
},
crate::NodeOp::Clip {}
| crate::NodeOp::Media { .. }
| crate::NodeOp::Matte { .. }
| crate::NodeOp::GroupInput { .. }
| crate::NodeOp::TimeOffset { .. } => {}
}
}
pub(crate) fn effect_keyed(
effect: &crate::ClipEffect,
at: &str,
visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
) {
for (name, value) in &effect.params {
crate::animation::visit_keyed(&format!("{at}.{name}"), value, visit);
}
}
fn lint_shape_items(
owner: &ShapeLintOwner,
items: &[ShapeItem],
at: &str,
issues: &mut Vec<LintIssue>,
) -> bool {
let mut geometry = false;
for (index, item) in items.iter().enumerate() {
let at = format!("{at}[{index}]");
match item {
ShapeItem::Group { items, .. } => {
geometry |= lint_shape_items(owner, items, &format!("{at}.items"), issues);
}
ShapeItem::Rectangle(_) | ShapeItem::Ellipse(_) | ShapeItem::Polystar(_) => {
geometry = true;
}
ShapeItem::Path(path) => {
geometry = true;
let paths: Vec<&crate::Path> = match &path.path {
Animated::Constant { value } => vec![value],
Animated::Keyframes { keyframes, .. } => {
keyframes.iter().map(|keyframe| &keyframe.value).collect()
}
Animated::Data(_) | Animated::Split { .. } => Vec::new(),
};
if let Some(first) = paths.first() {
for (subpath, entry) in first.subpaths.iter().enumerate() {
if entry.vertices.is_empty() {
issues.push(LintIssue::EmptySubpath {
owner: owner.clone(),
at: format!("{at}.path.subpaths[{subpath}]"),
});
}
}
}
}
ShapeItem::Fill { .. } | ShapeItem::Stroke(_) => {
if !geometry {
issues.push(LintIssue::PaintWithoutGeometry {
owner: owner.clone(),
at,
});
}
}
ShapeItem::Trim(_) => {}
}
}
geometry
}
fn empty_animators(
owner: &LintOwner,
animators: &[crate::TextAnimator],
at: &str,
issues: &mut Vec<LintIssue>,
) {
for (index, animator) in animators.iter().enumerate() {
if animator.properties.is_empty() {
issues.push(LintIssue::EmptyTextAnimator {
owner: owner.clone(),
at: format!("{at}[{index}]"),
});
}
}
}
fn lint_cues(grid: &FrameGrid, track: &crate::Track, issues: &mut Vec<LintIssue>) {
for (index, cue) in track
.captions
.iter()
.flat_map(|captions| captions.cues.iter())
.enumerate()
{
let owner = LintOwner::Cue {
track: track.id.clone(),
index,
};
grid.check(&owner, cue.timeline_range, issues);
for (run, timed) in cue.text.runs().iter().enumerate() {
let Some(time) = timed.time else {
continue;
};
let start = cue.timeline_range.start().ticks();
let Ok(range) = alpha2_time::TimeRange::new(
MediaTime(start.saturating_add(time.start.ticks())),
MediaTime(start.saturating_add(time.end.ticks())),
) else {
continue;
};
let owner = LintOwner::CueRun {
track: track.id.clone(),
cue: index,
run,
};
grid.check(&owner, range, issues);
}
}
}
fn lint_caption_animators(
track: &TrackId,
captions: &crate::Captions,
issues: &mut Vec<LintIssue>,
) {
let owner = LintOwner::CaptionTrack {
track: track.clone(),
};
let spans = captions
.cues
.iter()
.filter_map(|cue| cue.timeline_range.duration())
.map(|duration| (0, duration.ticks().saturating_sub(1)))
.collect::<Vec<_>>();
let mut keyframes = Keyframes {
owner: &owner,
shown: &spans,
issues,
};
crate::text_animation::for_each_keyed_animator(
&captions.style.animators,
"style.animators",
&mut |property, keyed| {
if let Keyed::Times(times, before, after) = keyed {
keyframes.check_times(property, times, before, after);
}
},
);
empty_animators(&owner, &captions.style.animators, "style.animators", issues);
let timed = captions
.cues
.iter()
.any(|cue| cue.text.runs().iter().any(|run| run.time.is_some()));
if !timed {
let highlights = captions
.style
.highlight
.is_some()
.then(|| "style.highlight".to_owned())
.into_iter()
.chain(
captions
.styles
.iter()
.filter(|(_, patch)| matches!(patch.highlight, Some(Some(_))))
.map(|(name, _)| format!("styles.{name}.highlight")),
);
for at in highlights {
issues.push(LintIssue::HighlightWithoutTimedRuns {
owner: owner.clone(),
at,
});
}
}
for name in captions.styles.keys() {
let used = captions.cues.iter().any(|cue| {
cue.style.as_deref() == Some(name.as_str())
|| (cue.style.is_none() && cue.speaker.as_deref() == Some(name.as_str()))
});
if !used {
issues.push(LintIssue::UnusedCaptionStyle {
track: track.clone(),
style: name.clone(),
});
}
}
}