avio 0.17.0

Video and audio editing engine: build a Timeline of clips, edit with undo/redo, and render to a file
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Pure, informational validation of a [`Timeline`] document.
//!
//! [`Timeline::validate`] returns a typed list of [`TimelineIssue`]s so a host can
//! surface problems (overlaps, bad trims, unbounded generated clips, dangling
//! references) before rendering. It is purely informational: it performs no I/O,
//! never opens source files, and does not block [`Timeline::render`] on its own.

use std::collections::HashMap;

use ff_filter::AnimationTrack;

use crate::clip::Clip;
use crate::edit::clip_footprint;
use crate::ids::{ClipId, TrackId};
use crate::timeline::Timeline;
use crate::track::Track;

/// A single problem found by [`Timeline::validate`].
///
/// Each variant names the offending [`ClipId`] / [`TrackId`] (or animation key)
/// and the cause. This is informational, not an error: a timeline may render even
/// with issues present.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimelineIssue {
    /// Two clips on the same track overlap in time (their timeline spans intersect).
    ///
    /// Only clips whose footprint is known (both trim points set) are checked.
    ClipOverlap {
        /// Track holding both clips.
        track: TrackId,
        /// The clip that starts earlier.
        earlier: ClipId,
        /// The clip that starts later.
        later: ClipId,
    },
    /// A clip's out-point is before its in-point (an invalid trim).
    TrimOutBeforeIn {
        /// The offending clip.
        clip: ClipId,
    },
    /// A clip's trim yields a zero-length footprint (out-point equals in-point).
    EmptyFootprint {
        /// The offending clip.
        clip: ClipId,
    },
    /// A generated (text/solid) clip has no out-point to bound its infinite source.
    ///
    /// Mirrors the render-time
    /// [`GeneratedSourceNeedsDuration`](crate::TimelineError::GeneratedSourceNeedsDuration)
    /// check.
    GeneratedClipWithoutOutPoint {
        /// The offending clip.
        clip: ClipId,
    },
    /// A clip carries a transition but is the first clip on its track, so there is
    /// no preceding clip to cross-fade from (the transition is ignored at render).
    DanglingTransition {
        /// Track holding the clip.
        track: TrackId,
        /// The offending clip.
        clip: ClipId,
    },
    /// An animation-map key is malformed, or targets a track index that does not
    /// exist (so the animation reaches no layer).
    UnknownAnimationKey {
        /// The offending key.
        key: String,
    },
}

impl Timeline {
    /// Validates this timeline and returns a list of structured diagnostics.
    ///
    /// Pure and informational: it performs **no I/O**, never opens source files,
    /// and does not mutate the timeline or block [`render`](Self::render). Checks
    /// that depend on a clip's timeline footprint (overlap detection) apply only
    /// to clips whose trim points are set, since an unset in/out point has no
    /// finite footprint.
    ///
    /// # Examples
    ///
    /// ```
    /// use avio::{Clip, Timeline};
    /// use std::time::Duration;
    ///
    /// let timeline = Timeline::builder()
    ///     .canvas(1920, 1080)
    ///     .frame_rate(30.0)
    ///     .video_track(vec![Clip::new("a.mp4")])
    ///     .build()
    ///     .unwrap();
    /// assert!(timeline.validate().is_empty());
    /// ```
    #[must_use]
    pub fn validate(&self) -> Vec<TimelineIssue> {
        let mut issues = Vec::new();
        for track in self.video_tracks.iter().chain(self.audio_tracks.iter()) {
            check_track(track, &mut issues);
        }
        check_animation_keys(
            "video",
            &self.video_animations,
            self.video_tracks.len(),
            &["x", "y", "scale_x", "scale_y", "rotation", "opacity"],
            &mut issues,
        );
        check_animation_keys(
            "audio",
            &self.audio_animations,
            self.audio_tracks.len(),
            &["volume", "pan"],
            &mut issues,
        );
        issues
    }
}

/// Per-clip and per-track invariants for one track.
fn check_track(track: &Track, issues: &mut Vec<TimelineIssue>) {
    // Per-clip checks.
    for clip in &track.clips {
        check_clip_trim(clip, issues);
        // A generated (text/solid) source is infinite; an out-point must bound it.
        if clip.source_path().is_none() && clip.out_point.is_none() {
            issues.push(TimelineIssue::GeneratedClipWithoutOutPoint { clip: clip.id });
        }
    }

    // A transition on the first clip has no predecessor to cross-fade from.
    if let Some(first) = track.clips.first()
        && first.transition.is_some()
    {
        issues.push(TimelineIssue::DanglingTransition {
            track: track.id,
            clip: first.id,
        });
    }

    check_overlaps(track, issues);
}

/// Flags an out-of-order trim (out < in) or a zero-length one (out == in).
fn check_clip_trim(clip: &Clip, issues: &mut Vec<TimelineIssue>) {
    if let (Some(in_point), Some(out_point)) = (clip.in_point, clip.out_point) {
        if out_point < in_point {
            issues.push(TimelineIssue::TrimOutBeforeIn { clip: clip.id });
        } else if out_point == in_point {
            issues.push(TimelineIssue::EmptyFootprint { clip: clip.id });
        }
    }
}

/// Flags overlapping clips on a track. Only clips with a known footprint are
/// considered; their timeline spans are `[offset, offset + footprint)`.
fn check_overlaps(track: &Track, issues: &mut Vec<TimelineIssue>) {
    // (id, start, end) for clips with a known footprint, sorted by start.
    let mut spans: Vec<(ClipId, std::time::Duration, std::time::Duration)> = track
        .clips
        .iter()
        .filter_map(|c| clip_footprint(c).map(|fp| (c.id, c.offset, c.offset.saturating_add(fp))))
        .collect();
    spans.sort_by_key(|&(_, start, _)| start);

    for i in 0..spans.len() {
        let (id_i, _start_i, end_i) = spans[i];
        for &(id_j, start_j, _end_j) in &spans[i + 1..] {
            // Sorted by start, so once a later clip starts at/after clip i's end no
            // further clip can overlap i.
            if start_j >= end_i {
                break;
            }
            issues.push(TimelineIssue::ClipOverlap {
                track: track.id,
                earlier: id_i,
                later: id_j,
            });
        }
    }
}

/// Flags animation keys that do not match `{prefix}_{track_index}_{property}`, or
/// whose track index is out of range for the current track count.
fn check_animation_keys(
    prefix: &str,
    animations: &HashMap<String, AnimationTrack<f64>>,
    track_count: usize,
    valid_props: &[&str],
    issues: &mut Vec<TimelineIssue>,
) {
    for key in animations.keys() {
        let parts: Vec<&str> = key.splitn(3, '_').collect();
        let idx = parts.get(1).and_then(|p| p.parse::<usize>().ok());
        let ok = parts.len() == 3
            && parts[0] == prefix
            && idx.is_some_and(|i| i < track_count)
            && valid_props.contains(&parts[2]);
        if !ok {
            issues.push(TimelineIssue::UnknownAnimationKey { key: key.clone() });
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use std::time::Duration;

    use ff_filter::{AnimationTrack, XfadeTransition};
    use ff_format::Color;

    use super::*;

    fn base(clips: Vec<Clip>) -> crate::timeline::TimelineBuilder {
        Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(clips)
    }

    #[test]
    fn validate_clean_timeline_should_have_no_issues() {
        let t = base(vec![
            Clip::new("a.mp4").trim(Duration::ZERO, Duration::from_secs(4)),
            Clip::new("b.mp4")
                .trim(Duration::ZERO, Duration::from_secs(4))
                .offset(Duration::from_secs(4)),
        ])
        .build()
        .unwrap();
        assert!(
            t.validate().is_empty(),
            "clean timeline: {:?}",
            t.validate()
        );
    }

    #[test]
    fn validate_should_detect_track_overlap() {
        // a: [0, 4), b: [2, 6) -> overlap.
        let t = base(vec![
            Clip::new("a.mp4").trim(Duration::ZERO, Duration::from_secs(4)),
            Clip::new("b.mp4")
                .trim(Duration::ZERO, Duration::from_secs(4))
                .offset(Duration::from_secs(2)),
        ])
        .build()
        .unwrap();
        let ids: Vec<_> = t.video_tracks()[0].clips.iter().map(|c| c.id).collect();
        assert!(t.validate().contains(&TimelineIssue::ClipOverlap {
            track: t.video_tracks()[0].id,
            earlier: ids[0],
            later: ids[1],
        }));
    }

    #[test]
    fn validate_overlap_should_catch_a_long_clip_spanning_a_far_one() {
        // a: [0, 10) (a long clip), b: [2, 4), c: [6, 8). `a` overlaps both `b`
        // and `c`; `b` and `c` do not touch. The far a-c overlap must not be lost
        // by the sorted break in `check_overlaps`.
        let t = base(vec![
            Clip::new("a.mp4").trim(Duration::ZERO, Duration::from_secs(10)),
            Clip::new("b.mp4")
                .trim(Duration::ZERO, Duration::from_secs(2))
                .offset(Duration::from_secs(2)),
            Clip::new("c.mp4")
                .trim(Duration::ZERO, Duration::from_secs(2))
                .offset(Duration::from_secs(6)),
        ])
        .build()
        .unwrap();
        let track = t.video_tracks()[0].id;
        let ids: Vec<_> = t.video_tracks()[0].clips.iter().map(|c| c.id).collect();
        let overlaps: Vec<_> = t
            .validate()
            .into_iter()
            .filter(|i| matches!(i, TimelineIssue::ClipOverlap { .. }))
            .collect();
        assert!(overlaps.contains(&TimelineIssue::ClipOverlap {
            track,
            earlier: ids[0],
            later: ids[1],
        }));
        assert!(
            overlaps.contains(&TimelineIssue::ClipOverlap {
                track,
                earlier: ids[0],
                later: ids[2],
            }),
            "the far a-c overlap must be detected"
        );
        assert_eq!(overlaps.len(), 2, "b and c do not overlap each other");
    }

    #[test]
    fn validate_should_detect_trim_out_before_in() {
        let t = base(vec![
            Clip::new("a.mp4").trim(Duration::from_secs(5), Duration::from_secs(2)),
        ])
        .build()
        .unwrap();
        let id = t.video_tracks()[0].clips[0].id;
        assert!(
            t.validate()
                .contains(&TimelineIssue::TrimOutBeforeIn { clip: id })
        );
    }

    #[test]
    fn validate_should_detect_empty_footprint() {
        let t = base(vec![
            Clip::new("a.mp4").trim(Duration::from_secs(3), Duration::from_secs(3)),
        ])
        .build()
        .unwrap();
        let id = t.video_tracks()[0].clips[0].id;
        assert!(
            t.validate()
                .contains(&TimelineIssue::EmptyFootprint { clip: id })
        );
    }

    #[test]
    fn validate_should_detect_generated_clip_without_out_point() {
        let t = base(vec![Clip::solid(Color::rgb(0, 0, 0))])
            .build()
            .unwrap();
        let id = t.video_tracks()[0].clips[0].id;
        assert!(
            t.validate()
                .contains(&TimelineIssue::GeneratedClipWithoutOutPoint { clip: id })
        );
        // A bounded generated clip is fine.
        let ok = base(vec![
            Clip::solid(Color::rgb(0, 0, 0)).trim(Duration::ZERO, Duration::from_secs(1)),
        ])
        .build()
        .unwrap();
        assert!(
            !ok.validate()
                .iter()
                .any(|i| matches!(i, TimelineIssue::GeneratedClipWithoutOutPoint { .. }))
        );
    }

    #[test]
    fn validate_should_detect_dangling_transition() {
        let t = base(vec![
            Clip::new("a.mp4")
                .trim(Duration::ZERO, Duration::from_secs(4))
                .with_transition(XfadeTransition::Fade, Duration::from_millis(500)),
        ])
        .build()
        .unwrap();
        let id = t.video_tracks()[0].clips[0].id;
        assert!(t.validate().contains(&TimelineIssue::DanglingTransition {
            track: t.video_tracks()[0].id,
            clip: id,
        }));
    }

    #[test]
    fn validate_should_detect_unknown_animation_key() {
        // "bogus" is malformed; "video_9_x" targets a non-existent track index.
        let t = base(vec![
            Clip::new("a.mp4").trim(Duration::ZERO, Duration::from_secs(4)),
        ])
        .video_animation("bogus", AnimationTrack::new())
        .video_animation("video_9_x", AnimationTrack::new())
        .video_animation("video_0_x", AnimationTrack::new()) // valid
        .build()
        .unwrap();
        let issues = t.validate();
        assert!(issues.contains(&TimelineIssue::UnknownAnimationKey {
            key: "bogus".into()
        }));
        assert!(issues.contains(&TimelineIssue::UnknownAnimationKey {
            key: "video_9_x".into()
        }));
        assert!(
            !issues.contains(&TimelineIssue::UnknownAnimationKey {
                key: "video_0_x".into()
            }),
            "a valid, in-range key is not flagged"
        );
    }

    #[test]
    fn validate_should_not_open_source_files() {
        // Nonexistent paths with an explicit canvas: `build` does not probe, and
        // `validate` must not touch the filesystem either. A File clip is never
        // flagged as a generated-source issue, regardless of whether the path
        // exists, and no I/O error surfaces.
        let t = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![
                Clip::new("does_not_exist_1.mp4").trim(Duration::ZERO, Duration::from_secs(2)),
            ])
            .audio_track(vec![Clip::new("does_not_exist_2.mp3")])
            .build()
            .unwrap();
        assert!(
            !t.validate()
                .iter()
                .any(|i| matches!(i, TimelineIssue::GeneratedClipWithoutOutPoint { .. }))
        );
    }
}