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