Skip to main content

rff_format/
chapter.rs

1//! Chapters (FFmpeg's `AVChapter`): a titled span of the presentation.
2//!
3//! A demuxer gives them as [`Demuxer::chapters`](crate::Demuxer::chapters) (a
4//! QuickTime chapter text track or Nero `chpl` in MP4/MOV, `Chapters` in
5//! Matroska/WebM); a muxer takes them with
6//! [`Muxer::set_chapters`](crate::Muxer::set_chapters).
7
8use rff_core::{Dictionary, Rational};
9
10/// The most chapters a demuxer reads from one file: far above any real one,
11/// it bounds what a hostile index can make a reader build.
12pub const MAX_CHAPTERS: usize = 1 << 16;
13
14/// One chapter: `[start, end)` in [`time_base`](Chapter::time_base) units on
15/// the presentation timeline, and its metadata (`title`, ...).
16#[derive(Debug, Clone, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct Chapter {
19    /// The container's identifier: Matroska `ChapterUID`, the position in the
20    /// list for MP4.
21    pub id: u64,
22    pub time_base: Rational,
23    pub start: i64,
24    /// Where the chapter ends; equal to `start` for a zero-length chapter.
25    /// Where the container records only starts (Nero `chpl`), the demuxer
26    /// fills in the next chapter's start, or the end of the file.
27    pub end: i64,
28    /// `title`, and any other tag the container attaches to the chapter.
29    pub metadata: Dictionary,
30}
31
32impl Chapter {
33    pub fn new(id: u64, time_base: Rational, start: i64, end: i64) -> Chapter {
34        Chapter {
35            id,
36            time_base,
37            start,
38            end,
39            metadata: Dictionary::new(),
40        }
41    }
42
43    /// This chapter with the title `title`.
44    pub fn with_title(mut self, title: impl Into<String>) -> Chapter {
45        self.metadata.set("title", title);
46        self
47    }
48
49    pub fn title(&self) -> Option<&str> {
50        self.metadata.get("title")
51    }
52
53    /// `start` in units of `1 / scale` s, rounded to nearest.
54    pub fn start_in(&self, scale: u32) -> i64 {
55        rescale(self.start, self.time_base, scale)
56    }
57
58    /// `end` in units of `1 / scale` s, rounded to nearest, never before the
59    /// start.
60    pub fn end_in(&self, scale: u32) -> i64 {
61        rescale(self.end.max(self.start), self.time_base, scale)
62    }
63}
64
65/// `n / d` rounded to nearest (halves away from zero), saturating; 0 for an
66/// invalid divisor.
67fn div_round(n: i128, d: i128) -> i64 {
68    if d <= 0 {
69        return 0;
70    }
71    let q = if n >= 0 {
72        (n + d / 2) / d
73    } else {
74        -((-n + d / 2) / d)
75    };
76    q.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
77}
78
79/// `v` in `tb` units as `1 / scale` s units; 0 for an invalid time base.
80fn rescale(v: i64, tb: Rational, scale: u32) -> i64 {
81    if tb.num <= 0 {
82        return 0;
83    }
84    div_round(
85        i128::from(v) * i128::from(tb.num) * i128::from(scale),
86        i128::from(tb.den),
87    )
88}
89
90/// Give every chapter whose position in `open` is set (its end is not
91/// recorded) an end, as FFmpeg's `compute_chapters_end` does: the next start
92/// in time order when that is later, else the end of the file (`duration_us`
93/// microseconds, when known), and never before its own start.
94pub fn fill_ends(chapters: &mut [Chapter], open: &[bool], duration_us: Option<i64>) {
95    let mut order: Vec<usize> = (0..chapters.len()).collect();
96    order.sort_by_key(|&i| chapters[i].start_in(1_000_000_000));
97    for (k, &i) in order.iter().enumerate() {
98        if !open.get(i).copied().unwrap_or(false) {
99            continue;
100        }
101        let (tb, start) = (chapters[i].time_base, chapters[i].start);
102        let to_tb = |v: i64, from: Rational| -> i64 {
103            div_round(
104                i128::from(v) * i128::from(from.num.max(0)) * i128::from(tb.den.max(0)),
105                i128::from(from.den) * i128::from(tb.num.max(1)),
106            )
107        };
108        let mut end = duration_us
109            .filter(|&d| d > 0)
110            .map(|d| to_tb(d, Rational::new(1, 1_000_000)));
111        if let Some(&n) = order.get(k + 1) {
112            let next = to_tb(chapters[n].start, chapters[n].time_base);
113            if next > start && end.is_none_or(|e| next < e) {
114                end = Some(next);
115            }
116        }
117        chapters[i].end = end.filter(|&e| e >= start).unwrap_or(start);
118    }
119}
120
121/// `chapters` by start, as listed where starts are equal. A chapter track can
122/// hold no other order, and FFmpeg's Matroska demuxer skips a chapter listed
123/// after a later one, so muxers write them this way.
124pub fn in_time_order(chapters: &[Chapter]) -> Vec<Chapter> {
125    let mut out = chapters.to_vec();
126    out.sort_by_key(|c| c.start_in(1_000_000_000));
127    out
128}
129
130/// Chapters for an output cut to the window `[start_s, end_s)` (seconds),
131/// moved so the window begins at zero: what FFmpeg does with `-ss` / `-t`.
132/// Chapters outside the window are left out, the rest clipped.
133pub fn trim(chapters: &[Chapter], start_s: f64, end_s: Option<f64>) -> Vec<Chapter> {
134    chapters
135        .iter()
136        .filter_map(|c| {
137            let tb = c.time_base;
138            let ticks = |s: f64| (s * f64::from(tb.den) / f64::from(tb.num.max(1))).round() as i64;
139            let off = ticks(start_s);
140            if c.end < off {
141                return None;
142            }
143            let mut out = c.clone();
144            out.start = c.start.saturating_sub(off).max(0);
145            out.end = c.end.saturating_sub(off).max(out.start);
146            if let Some(end) = end_s {
147                let stop = ticks(end);
148                if c.start > stop {
149                    return None;
150                }
151                out.end = out.end.min(stop.saturating_sub(off)).max(out.start);
152            }
153            Some(out)
154        })
155        .collect()
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    fn ms(id: u64, start: i64, end: i64) -> Chapter {
163        Chapter::new(id, Rational::new(1, 1000), start, end)
164    }
165
166    #[test]
167    fn open_ends_run_to_the_next_start_in_time_order() {
168        let mut c = [
169            ms(0, 5000, 0),
170            ms(1, 0, 0),
171            ms(2, 5000, 0),
172            ms(3, 7000, 7000),
173        ];
174        fill_ends(&mut c, &[true, true, true, false], Some(10_000_000));
175        let ends: Vec<i64> = c.iter().map(|c| c.end).collect();
176        // Two chapters share a start: the first of them has no later start
177        // right after it and runs to the end of the file, as in FFmpeg.
178        assert_eq!(ends, [10_000, 5000, 7000, 7000]);
179        let mut c = [ms(0, 9, 0)];
180        fill_ends(&mut c, &[true], None);
181        assert_eq!(c[0].end, 9);
182        fill_ends(&mut c, &[true], Some(1_000)); // the file ends before it
183        assert_eq!(c[0].end, 9);
184    }
185
186    #[test]
187    fn scales_round_to_nearest_and_saturate() {
188        let c = Chapter::new(0, Rational::new(1001, 30000), 100, 50);
189        assert_eq!(c.start_in(1000), 3337);
190        assert_eq!(c.end_in(1000), 3337); // never before the start
191        let c = Chapter::new(0, Rational::new(i32::MAX, 1), i64::MAX, i64::MAX);
192        assert_eq!(c.start_in(u32::MAX), i64::MAX);
193        assert_eq!(Chapter::new(0, Rational::new(1, 0), 5, 9).start_in(10), 0);
194        assert_eq!(ms(0, -1500, 0).start_in(1), -2);
195    }
196
197    #[test]
198    fn a_trim_window_clips_and_moves_chapters() {
199        let c = [
200            ms(0, 0, 2000),
201            ms(1, 2000, 6000),
202            ms(2, 6000, 9000),
203            ms(3, 9000, 10_000),
204        ];
205        let t = trim(&c, 3.0, Some(8.0));
206        let spans: Vec<(u64, i64, i64)> = t.iter().map(|c| (c.id, c.start, c.end)).collect();
207        assert_eq!(spans, [(1, 0, 3000), (2, 3000, 5000)]);
208        assert_eq!(trim(&c, 0.0, None), c);
209    }
210}