Skip to main content

timed_metadata/webvtt/
text.rs

1//! Shared WebVTT / SRT text helpers: the cue-timestamp grammar (both
2//! directions), payload escaping (both directions) and line-terminator
3//! normalisation.
4//!
5//! WebVTT (W3C WebVTT §4.3.1) and SRT (de facto) use the same
6//! `(hh:)?mm:ss<sep>ttt` timestamp grammar, `.` for WebVTT and `,` for SRT;
7//! the caller picks the separator. Before this module the *writer* half lived
8//! here and the *parser* half, the payload *unescape*, and a second copy of the
9//! hour/minute/second digit math lived in `caption-convert` ("kept in
10//! lock-step" by a comment), so a rounding or overflow fix in one never
11//! reached the other. This is now the single owner; `caption-convert` is a
12//! thin client.
13
14use crate::event::MediaTime;
15use alloc::borrow::Cow;
16use alloc::format;
17use alloc::string::String;
18
19/// 90 kHz ticks per millisecond (`crate::PTS_HZ` / 1000): the ratio used to
20/// render and parse a [`MediaTime`] as a cue timestamp.
21const TICKS_PER_MS: u64 = crate::PTS_HZ / 1000;
22/// Milliseconds per hour / minute / second, for timestamp field extraction.
23const MS_PER_HOUR: u64 = 3_600_000;
24const MS_PER_MIN: u64 = 60_000;
25const MS_PER_SEC: u64 = 1_000;
26
27/// A cue timestamp did not match `(hh:)?mm:ss<sep>ttt` (or overflowed).
28#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
29#[error("invalid cue timestamp (expected (hh:)?mm:ss<sep>ttt)")]
30pub struct TimestampError;
31
32/// Split a [`MediaTime`] into `(hours, minutes, seconds, milliseconds)`.
33#[must_use]
34pub fn hms_ms(t: MediaTime) -> (u64, u64, u64, u64) {
35    let total_ms = t.0 / TICKS_PER_MS;
36    let hours = total_ms / MS_PER_HOUR;
37    let mins = (total_ms % MS_PER_HOUR) / MS_PER_MIN;
38    let secs = (total_ms % MS_PER_MIN) / MS_PER_SEC;
39    let ms = total_ms % MS_PER_SEC;
40    (hours, mins, secs, ms)
41}
42
43/// Format a [`MediaTime`] as `hh:mm:ss<sep>ttt`: `.` for WebVTT (W3C WebVTT
44/// §4.3.1), `,` for SRT. Hours are always emitted: the grammar makes them
45/// *optional*, not forbidden, and always including them keeps this function
46/// total and monotonic without a >=1h special case.
47#[must_use]
48pub fn format_timestamp_with(t: MediaTime, ms_sep: char) -> String {
49    let (hours, mins, secs, ms) = hms_ms(t);
50    format!("{hours:02}:{mins:02}:{secs:02}{ms_sep}{ms:03}")
51}
52
53/// ASCII digits only (and non-empty). `str::parse::<u64>` also accepts a
54/// leading `+`, which no timestamp grammar here allows (#1109 CV-O1).
55fn all_digits(s: &str) -> bool {
56    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
57}
58
59/// Parse a `(hh:)?mm:ss<sep>ttt` timestamp into a [`MediaTime`], where
60/// `ms_sep` is the millisecond separator: `.` for WebVTT, `,` for SRT.
61/// Splitting on `ms_sep` in place avoids a per-timestamp `String` (#1109
62/// CV-O3).
63///
64/// # Errors
65/// [`TimestampError`] for any deviation from the grammar (wrong separator,
66/// digit counts, minutes/seconds >= 60, a `+` sign) and for an hour field so
67/// large that the to-milliseconds / to-ticks arithmetic would overflow.
68pub fn parse_timestamp(s: &str, ms_sep: char) -> Result<MediaTime, TimestampError> {
69    let (rest, ms_str) = s.split_once(ms_sep).ok_or(TimestampError)?;
70    if ms_str.len() != 3 || !all_digits(ms_str) {
71        return Err(TimestampError);
72    }
73    let ms: u64 = ms_str.parse().map_err(|_| TimestampError)?;
74
75    let mut fields = rest.split(':');
76    let (first, second, third) = (fields.next(), fields.next(), fields.next());
77    if fields.next().is_some() {
78        return Err(TimestampError);
79    }
80    let (h_str, m, sec) = match (first, second, third) {
81        (Some(m), Some(s), None) => (None, m, s),
82        (Some(h), Some(m), Some(s)) => (Some(h), m, s),
83        _ => return Err(TimestampError),
84    };
85    let h: u64 = match h_str {
86        Some(h) if all_digits(h) => h.parse().map_err(|_| TimestampError)?,
87        Some(_) => return Err(TimestampError),
88        None => 0,
89    };
90    if m.len() != 2 || sec.len() != 2 || !all_digits(m) || !all_digits(sec) {
91        return Err(TimestampError);
92    }
93    let m: u64 = m.parse().map_err(|_| TimestampError)?;
94    let s: u64 = sec.parse().map_err(|_| TimestampError)?;
95    if m >= 60 || s >= 60 {
96        return Err(TimestampError);
97    }
98    // WebVTT's hour field has no digit-count cap (W3C WebVTT §4.3.1: "one or
99    // more" digits), so an attacker-controlled `h` up to `u64::MAX` is a
100    // *validly parsed* value that still overflows the `h*3600 + m*60 + s`
101    // to-milliseconds, and then the `* TICKS_PER_MS` to-90kHz-ticks, widening
102    // multiplications. Debug-assertions builds (fuzz targets, downstream debug
103    // builds) would panic on that overflow; release builds would silently
104    // wrap to a bogus timestamp - checked arithmetic turns both into the same
105    // explicit `TimestampError`.
106    let total_ms = h
107        .checked_mul(MS_PER_HOUR)
108        .and_then(|v| v.checked_add(m * MS_PER_MIN))
109        .and_then(|v| v.checked_add(s * MS_PER_SEC))
110        .and_then(|v| v.checked_add(ms))
111        .ok_or(TimestampError)?;
112    total_ms
113        .checked_mul(TICKS_PER_MS)
114        .map(MediaTime)
115        .ok_or(TimestampError)
116}
117
118/// Escape a cue payload line per W3C WebVTT §6.4: `&` -> `&amp;`,
119/// `<` -> `&lt;`, `>` -> `&gt;` (order is immaterial here: this is a single
120/// left-to-right character scan, not a sequence of whole-string
121/// find-and-replace passes, so an inserted `&amp;` is never re-scanned and
122/// cannot be corrupted by a later `<`/`>` substitution).
123#[must_use]
124pub fn escape_payload(text: &str) -> String {
125    let mut out = String::with_capacity(text.len());
126    for c in text.chars() {
127        match c {
128            '&' => out.push_str("&amp;"),
129            '<' => out.push_str("&lt;"),
130            '>' => out.push_str("&gt;"),
131            _ => out.push(c),
132        }
133    }
134    out
135}
136
137/// Unescape the three entities [`escape_payload`] emits (`&amp;` `&lt;`
138/// `&gt;`), left-to-right, single pass - the exact inverse of
139/// [`escape_payload`]. Other WebVTT-defined entities (`&lrm;` `&rlm;`
140/// `&nbsp;`) are out of scope and pass through literally (a documented, not
141/// silent, limitation - they are rare in real captions and this crate emits
142/// none of them).
143#[must_use]
144pub fn unescape_payload(text: &str) -> String {
145    let mut out = String::with_capacity(text.len());
146    let mut chars = text.chars().peekable();
147    while let Some(c) = chars.next() {
148        if c != '&' {
149            out.push(c);
150            continue;
151        }
152        let rest: String = chars.clone().take(4).collect();
153        if rest.starts_with("amp;") {
154            out.push('&');
155            for _ in 0..4 {
156                chars.next();
157            }
158        } else if rest.starts_with("lt;") {
159            out.push('<');
160            for _ in 0..3 {
161                chars.next();
162            }
163        } else if rest.starts_with("gt;") {
164            out.push('>');
165            for _ in 0..3 {
166                chars.next();
167            }
168        } else {
169            out.push('&');
170        }
171    }
172    out
173}
174
175/// Normalise every line-terminator form to a single `\n`.
176///
177/// W3C WebVTT §4 defines a "line terminator" as one of three forms: a lone LF,
178/// a lone CR *not* followed by LF, or a CRLF pair - i.e. a bare `\r` is itself
179/// a valid line break, not just the `\r` half of `\r\n`. Rust's `str::lines()`
180/// (and a plain `"\r\n" -> "\n"` replace, SRT's own de facto convention) only
181/// recognise LF and CRLF: a lone CR, or a malformed doubled `\r\r\n`, survives
182/// as a literal control character embedded in a parsed cue's payload - and
183/// since `str::lines()` also swallows a `\r` immediately preceding a `\n` even
184/// when that `\r` is genuine payload text, the embedded CR is then silently
185/// dropped the next time that cue is written back out. Normalising every
186/// terminator form up front, before any parser's own `.lines()` /
187/// `"\n\n"`-splitting logic runs, closes both holes. Borrowed (no allocation)
188/// when the input contains no `\r` at all.
189#[must_use]
190pub fn normalize_line_endings(input: &str) -> Cow<'_, str> {
191    if !input.contains('\r') {
192        return Cow::Borrowed(input);
193    }
194    let mut out = String::with_capacity(input.len());
195    let mut chars = input.chars().peekable();
196    while let Some(c) = chars.next() {
197        if c == '\r' {
198            if chars.peek() == Some(&'\n') {
199                chars.next(); // the paired LF of a CRLF terminator
200            }
201            out.push('\n');
202        } else {
203            out.push(c);
204        }
205    }
206    Cow::Owned(out)
207}
208
209/// The non-empty lines of an already-[`normalize_line_endings`]-normalised cue
210/// payload. A blank line terminates a cue block (W3C WebVTT §4.1) and an
211/// SRT reader reads one as the end of the block, so an empty line inside a
212/// payload would truncate the cue and turn the rest into a bogus block: both
213/// writers drop them.
214pub fn payload_lines(normalized: &str) -> impl Iterator<Item = &str> {
215    normalized.split('\n').filter(|l| !l.is_empty())
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn hms_ms_splits_every_field() {
224        // 1h 2m 3s 456ms
225        let ticks = (3_600_000 + 2 * 60_000 + 3_000 + 456) * TICKS_PER_MS;
226        assert_eq!(hms_ms(MediaTime(ticks)), (1, 2, 3, 456));
227    }
228
229    #[test]
230    fn format_uses_the_requested_separator() {
231        let t = MediaTime(90_000 + 45_000);
232        assert_eq!(format_timestamp_with(t, '.'), "00:00:01.500");
233        assert_eq!(format_timestamp_with(t, ','), "00:00:01,500");
234    }
235
236    #[test]
237    fn format_then_parse_round_trips() {
238        for ticks in [
239            0,
240            90,
241            90_000,
242            3_600 * 90_000 + 123 * 90,
243            99 * 3_600 * 90_000,
244        ] {
245            for sep in ['.', ','] {
246                let s = format_timestamp_with(MediaTime(ticks), sep);
247                assert_eq!(parse_timestamp(&s, sep), Ok(MediaTime(ticks)), "{s}");
248            }
249        }
250    }
251
252    #[test]
253    fn parse_basic() {
254        assert_eq!(parse_timestamp("00:00:01.000", '.'), Ok(MediaTime(90_000)));
255        assert_eq!(
256            parse_timestamp("01:00:00.000", '.'),
257            Ok(MediaTime(3_600 * 90_000))
258        );
259        assert_eq!(parse_timestamp("00:00:00.001", '.'), Ok(MediaTime(90)));
260        // hour-less form
261        assert_eq!(
262            parse_timestamp("01:02.500", '.'),
263            Ok(MediaTime(62_500 * 90))
264        );
265    }
266
267    #[test]
268    fn parse_rejects_bad_ms_length() {
269        assert_eq!(parse_timestamp("00:00:01.0", '.'), Err(TimestampError));
270        assert_eq!(parse_timestamp("00:00:01.00000", '.'), Err(TimestampError));
271    }
272
273    #[test]
274    fn parse_rejects_a_one_digit_minutes_or_seconds_field() {
275        // W3C WebVTT §4.3.1: the minutes and seconds fields are exactly two
276        // digits (the hour field, when present, is one or more).
277        for bad in ["1:05.000", "00:1:05.000", "00:01:5.000"] {
278            assert_eq!(parse_timestamp(bad, '.'), Err(TimestampError), "{bad}");
279        }
280    }
281
282    #[test]
283    fn timestamp_error_message_is_the_documented_one() {
284        let message = format!("{}", TimestampError);
285        assert!(!message.is_empty());
286        assert_eq!(
287            message,
288            "invalid cue timestamp (expected (hh:)?mm:ss<sep>ttt)"
289        );
290    }
291
292    #[test]
293    fn parse_rejects_out_of_range_fields() {
294        assert_eq!(parse_timestamp("00:60:00.000", '.'), Err(TimestampError));
295        assert_eq!(parse_timestamp("00:00:60.000", '.'), Err(TimestampError));
296    }
297
298    #[test]
299    fn parse_rejects_missing_separator() {
300        assert_eq!(parse_timestamp("00:00:01", '.'), Err(TimestampError));
301    }
302
303    #[test]
304    fn parse_rejects_hour_overflow_instead_of_panicking() {
305        // W3C WebVTT §4.3.1 puts no digit-count cap on the hour field, so this
306        // is a validly-parsed `u64` that still overflows the to-milliseconds /
307        // to-ticks widening multiplications (found by fuzzing - a
308        // debug-assertions build used to panic on this input).
309        assert_eq!(
310            parse_timestamp("11662322688380341727:00:01.000", '.'),
311            Err(TimestampError)
312        );
313        assert_eq!(
314            parse_timestamp("18446744073709551615:00:00.000", '.'),
315            Err(TimestampError)
316        );
317    }
318
319    #[test]
320    fn the_wrong_separator_is_an_error_not_a_silent_accept() {
321        assert_eq!(
322            parse_timestamp("00:00:01,500", ','),
323            Ok(MediaTime(90_000 + 45_000))
324        );
325        assert_eq!(parse_timestamp("00:00:01,500", '.'), Err(TimestampError));
326        assert_eq!(parse_timestamp("00:00:01.500", ','), Err(TimestampError));
327    }
328
329    /// CV-O1 (#1109): `str::parse::<u64>` accepts a leading `+`; the timestamp
330    /// grammar is digits only.
331    #[test]
332    fn plus_sign_is_rejected_in_every_field() {
333        for bad in [
334            "+0:00:01.000",
335            "00:+1:01.000",
336            "00:00:+1.000",
337            "00:00:01.+00",
338            "+1:00:00:01.000",
339        ] {
340            assert_eq!(parse_timestamp(bad, '.'), Err(TimestampError), "{bad}");
341        }
342        assert!(parse_timestamp("00:00:01.000", '.').is_ok());
343    }
344
345    #[test]
346    fn escape_then_unescape_is_the_identity() {
347        let text = "a < b & c > d &amp; &lt; &gt; &unknown; &";
348        assert_eq!(unescape_payload(&escape_payload(text)), text);
349        assert_eq!(unescape_payload("a &lt; b &amp; c &gt; d"), "a < b & c > d");
350        // Unknown entities and a trailing '&' pass through literally.
351        assert_eq!(unescape_payload("&nbsp; &"), "&nbsp; &");
352    }
353
354    #[test]
355    fn escape_order_is_safe() {
356        assert_eq!(escape_payload("&lt;"), "&amp;lt;");
357        assert_eq!(escape_payload("<&>"), "&lt;&amp;&gt;");
358    }
359
360    #[test]
361    fn line_ending_normalisation_handles_all_three_terminator_forms() {
362        assert_eq!(normalize_line_endings("a\nb"), "a\nb");
363        assert_eq!(normalize_line_endings("a\r\nb"), "a\nb");
364        assert_eq!(normalize_line_endings("a\rb"), "a\nb");
365        assert_eq!(normalize_line_endings("a\r\r\nb"), "a\n\nb");
366        assert_eq!(normalize_line_endings("a\n\rb"), "a\n\nb");
367        assert_eq!(normalize_line_endings(""), "");
368    }
369
370    #[test]
371    fn normalisation_borrows_when_there_is_no_cr() {
372        assert!(matches!(normalize_line_endings("a\nb"), Cow::Borrowed(_)));
373        assert!(matches!(normalize_line_endings("a\rb"), Cow::Owned(_)));
374    }
375
376    #[test]
377    fn payload_lines_drops_blank_lines() {
378        let n = normalize_line_endings("one\r\n\r\ntwo\rthree\n");
379        let lines: alloc::vec::Vec<&str> = payload_lines(&n).collect();
380        assert_eq!(lines, ["one", "two", "three"]);
381    }
382}