Skip to main content

threers_captions/
lib.rs

1//! The caption data model: timed-text tracks and cues, their style, and
2//! SubRip / WebVTT parsing and writing, with WCAG legibility checks. No
3//! dependencies, so the renderer can have captions without the codecs.
4//!
5//! `threers-codec` re-exports this as `threers_codec::captions` and writes
6//! these tracks into MP4 and WebM as soft subtitle streams. Drawing captions
7//! (fonts, shaping, bidi, compositing into frames, the on-screen overlay) is
8//! `threers::captions`, which re-exports everything here.
9//!
10//! ```
11//! use threers_captions::CaptionTrack;
12//!
13//! let track = CaptionTrack::parse_srt(
14//!     "1\n00:00:00,000 --> 00:00:02,500\nHello, world!\n",
15//! ).unwrap();
16//! assert_eq!(track.active_at(1.0).len(), 1);
17//! ```
18
19pub mod contrast;
20pub mod legibility;
21pub mod srt;
22pub mod vtt;
23
24/// Horizontal alignment of caption lines within the caption box.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
26pub enum CaptionAlign {
27    /// Flush left.
28    Left,
29    /// Centred.
30    #[default]
31    Center,
32    /// Flush right.
33    Right,
34}
35
36/// Which edge of the frame the caption block is anchored to.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
38pub enum CaptionAnchor {
39    /// Hang from the top edge.
40    Top,
41    /// Centre vertically.
42    Middle,
43    /// Sit on the bottom edge, where subtitles usually go.
44    #[default]
45    Bottom,
46}
47
48/// Timed-text file format.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum CaptionFormat {
51    /// SubRip (`.srt`) — the most widely accepted sidecar format.
52    Srt,
53    /// WebVTT (`.vtt`) — the format `<track>` takes in browsers.
54    Vtt,
55}
56
57impl CaptionFormat {
58    /// File extension without the dot (`"srt"`, `"vtt"`).
59    pub fn extension(self) -> &'static str {
60        match self {
61            CaptionFormat::Srt => "srt",
62            CaptionFormat::Vtt => "vtt",
63        }
64    }
65
66    /// MIME type, for browser downloads / `Blob` construction.
67    pub fn mime_type(self) -> &'static str {
68        match self {
69            CaptionFormat::Srt => "application/x-subrip",
70            CaptionFormat::Vtt => "text/vtt",
71        }
72    }
73
74    /// Infer the format from a file name / path extension.
75    pub fn from_path(path: &str) -> Option<Self> {
76        let ext = path.rsplit('.').next()?.to_ascii_lowercase();
77        match ext.as_str() {
78            "srt" => Some(CaptionFormat::Srt),
79            "vtt" | "webvtt" => Some(CaptionFormat::Vtt),
80            _ => None,
81        }
82    }
83}
84
85/// Why parsing a subtitle file failed.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub enum CaptionError {
88    /// A timestamp line was not `HH:MM:SS,mmm --> HH:MM:SS,mmm`.
89    BadTimestamp {
90        /// 1-based line number.
91        line: usize,
92        /// The line as written.
93        text: String,
94    },
95    /// A cue block had no `-->` timing line.
96    MissingTiming {
97        /// 1-based line number of the cue block.
98        line: usize,
99    },
100    /// The input had no cues at all.
101    Empty,
102    /// Text did not look like the requested format (e.g. no `WEBVTT` header).
103    NotRecognized,
104}
105
106impl std::fmt::Display for CaptionError {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        match self {
109            CaptionError::BadTimestamp { line, text } => {
110                write!(f, "line {line}: malformed cue timing {text:?}")
111            }
112            CaptionError::MissingTiming { line } => {
113                write!(f, "line {line}: cue block has no \"-->\" timing line")
114            }
115            CaptionError::Empty => write!(f, "no cues found"),
116            CaptionError::NotRecognized => write!(f, "input is not SubRip or WebVTT"),
117        }
118    }
119}
120impl std::error::Error for CaptionError {}
121
122/// One timed caption: a time range plus the text shown during it.
123///
124/// Times are seconds from the start of the media. `text` keeps its original
125/// line breaks (`\n`) and any inline markup; use [`Cue::plain_text`] for a
126/// markup-free version suitable for rasterizing.
127#[derive(Clone, Debug, PartialEq)]
128pub struct Cue {
129    /// Optional cue identifier (the numeric counter in SubRip, the free-form
130    /// name in WebVTT). Regenerated on serialize when `None`.
131    pub id: Option<String>,
132    /// Start time in seconds.
133    pub start: f64,
134    /// End time in seconds.
135    pub end: f64,
136    /// Cue text; `\n` separates lines.
137    pub text: String,
138    /// Per-cue horizontal alignment override (WebVTT `align:`).
139    pub align: Option<CaptionAlign>,
140    /// Per-cue vertical placement as a fraction of frame height from the top
141    /// (WebVTT `line:NN%`). `None` uses the style's anchor + margin.
142    pub line: Option<f32>,
143    /// Per-cue horizontal placement as a fraction of frame width from the left
144    /// (WebVTT `position:NN%`). `None` centers within the style's max width.
145    pub position: Option<f32>,
146}
147
148impl Cue {
149    /// A cue spanning `start..end` seconds showing `text`.
150    pub fn new(start: f64, end: f64, text: impl Into<String>) -> Self {
151        Self {
152            id: None,
153            start,
154            end,
155            text: text.into(),
156            align: None,
157            line: None,
158            position: None,
159        }
160    }
161
162    /// Set the cue identifier.
163    pub fn id(mut self, id: impl Into<String>) -> Self {
164        self.id = Some(id.into());
165        self
166    }
167
168    /// Override horizontal alignment for this cue.
169    pub fn align(mut self, align: CaptionAlign) -> Self {
170        self.align = Some(align);
171        self
172    }
173
174    /// Place the cue vertically at `line` (0 = top, 1 = bottom of the frame).
175    pub fn at_line(mut self, line: f32) -> Self {
176        self.line = Some(line);
177        self
178    }
179
180    /// Place the cue horizontally at `position` (0 = left, 1 = right).
181    pub fn at_position(mut self, position: f32) -> Self {
182        self.position = Some(position);
183        self
184    }
185
186    /// Duration in seconds (never negative).
187    pub fn duration(&self) -> f64 {
188        (self.end - self.start).max(0.0)
189    }
190
191    /// Whether the cue is showing at `time` seconds (start inclusive, end
192    /// exclusive — so back-to-back cues never both match).
193    pub fn is_active_at(&self, time: f64) -> bool {
194        time >= self.start && time < self.end
195    }
196
197    /// Cue text with inline markup removed and HTML entities decoded — what
198    /// the rasterizer draws.
199    ///
200    /// Strips WebVTT/SubRip tags (`<i>`, `<b>`, `<u>`, `<c.yellow>`, `<v Bob>`,
201    /// `<00:00:01.000>`), ASS-style overrides (`{\an8}`), and decodes `&amp;`,
202    /// `&lt;`, `&gt;`, `&nbsp;`, `&lrm;`, `&rlm;`.
203    pub fn plain_text(&self) -> String {
204        strip_markup(&self.text)
205    }
206}
207
208/// Remove inline caption markup and decode the entity set WebVTT defines.
209pub fn strip_markup(text: &str) -> String {
210    let mut out = String::with_capacity(text.len());
211    let mut chars = text.chars().peekable();
212    while let Some(c) = chars.next() {
213        match c {
214            // <i> </i> <c.classname> <v Speaker> <00:00:01.000> …
215            '<' => {
216                for t in chars.by_ref() {
217                    if t == '>' {
218                        break;
219                    }
220                }
221            }
222            // ASS/SSA override blocks such as {\an8}.
223            '{' if matches!(chars.peek(), Some('\\')) => {
224                for t in chars.by_ref() {
225                    if t == '}' {
226                        break;
227                    }
228                }
229            }
230            '&' => {
231                let mut name = String::new();
232                let mut closed = false;
233                // Entities are short; anything longer is literal text.
234                while let Some(&t) = chars.peek() {
235                    if t == ';' {
236                        chars.next();
237                        closed = true;
238                        break;
239                    }
240                    if !t.is_ascii_alphanumeric() && t != '#' || name.len() > 8 {
241                        break;
242                    }
243                    name.push(t);
244                    chars.next();
245                }
246                match (closed, name.as_str()) {
247                    (true, "amp") => out.push('&'),
248                    (true, "lt") => out.push('<'),
249                    (true, "gt") => out.push('>'),
250                    (true, "quot") => out.push('"'),
251                    (true, "apos") => out.push('\''),
252                    (true, "nbsp") => out.push(' '),
253                    // Bidi marks are invisible controls — drop them.
254                    (true, "lrm") | (true, "rlm") => {}
255                    _ => {
256                        out.push('&');
257                        out.push_str(&name);
258                        if closed {
259                            out.push(';');
260                        }
261                    }
262                }
263            }
264            _ => out.push(c),
265        }
266    }
267    out
268}
269
270/// An ordered list of [`Cue`]s plus the metadata a subtitle track carries.
271///
272/// ```
273/// use threers_captions::CaptionTrack;
274/// let track = CaptionTrack::new()
275///     .language("en")
276///     .label("English")
277///     .cue(0.0, 2.0, "First line")
278///     .cue(2.0, 4.0, "Second line");
279/// assert_eq!(track.duration(), 4.0);
280/// assert!(track.to_vtt().starts_with("WEBVTT"));
281/// ```
282#[derive(Clone, Debug, Default, PartialEq)]
283pub struct CaptionTrack {
284    /// Cues, kept sorted by start time by [`push`](Self::push) / [`cue`](Self::cue).
285    pub cues: Vec<Cue>,
286    /// BCP-47 language tag (`"en"`, `"pt-BR"`, …). Empty means undetermined.
287    pub language: String,
288    /// Human-readable track name shown in player menus.
289    pub label: String,
290}
291
292impl CaptionTrack {
293    /// An empty track.
294    pub fn new() -> Self {
295        Self::default()
296    }
297
298    /// Set the BCP-47 language tag.
299    pub fn language(mut self, language: impl Into<String>) -> Self {
300        self.language = language.into();
301        self
302    }
303
304    /// Set the human-readable track label.
305    pub fn label(mut self, label: impl Into<String>) -> Self {
306        self.label = label.into();
307        self
308    }
309
310    /// Append a cue (builder form). Keeps `cues` sorted by start time.
311    pub fn cue(mut self, start: f64, end: f64, text: impl Into<String>) -> Self {
312        self.push(Cue::new(start, end, text));
313        self
314    }
315
316    /// Append a cue, keeping `cues` sorted by start time.
317    pub fn push(&mut self, cue: Cue) {
318        let at = self
319            .cues
320            .iter()
321            .rposition(|c| c.start <= cue.start)
322            .map(|i| i + 1)
323            .unwrap_or(0);
324        self.cues.insert(at, cue);
325    }
326
327    /// Re-sort cues by start time (then end time). Only needed if `cues` was
328    /// mutated directly.
329    pub fn sort(&mut self) {
330        self.cues.sort_by(|a, b| {
331            a.start
332                .partial_cmp(&b.start)
333                .unwrap_or(std::cmp::Ordering::Equal)
334                .then(
335                    a.end
336                        .partial_cmp(&b.end)
337                        .unwrap_or(std::cmp::Ordering::Equal),
338                )
339        });
340    }
341
342    /// Number of cues.
343    pub fn len(&self) -> usize {
344        self.cues.len()
345    }
346
347    /// Whether the track has no cues.
348    pub fn is_empty(&self) -> bool {
349        self.cues.is_empty()
350    }
351
352    /// End time of the last cue, in seconds (`0.0` when empty).
353    pub fn duration(&self) -> f64 {
354        self.cues.iter().fold(0.0f64, |acc, c| acc.max(c.end))
355    }
356
357    /// Every cue showing at `time` seconds, in track order.
358    pub fn active_at(&self, time: f64) -> Vec<&Cue> {
359        self.cues.iter().filter(|c| c.is_active_at(time)).collect()
360    }
361
362    /// The first cue showing at `time` seconds — the common case, since most
363    /// tracks show one cue at a time.
364    pub fn cue_at(&self, time: f64) -> Option<&Cue> {
365        self.cues.iter().find(|c| c.is_active_at(time))
366    }
367
368    /// Concatenated [`plain_text`](Cue::plain_text) of every cue active at
369    /// `time`, joined with newlines. Empty when nothing is showing.
370    pub fn text_at(&self, time: f64) -> String {
371        let mut out = String::new();
372        for c in self.cues.iter().filter(|c| c.is_active_at(time)) {
373            if !out.is_empty() {
374                out.push('\n');
375            }
376            out.push_str(c.plain_text().trim_end_matches('\n'));
377        }
378        out
379    }
380
381    /// Shift every cue by `seconds` (negative moves earlier). Cues never move
382    /// before zero.
383    pub fn shift(&mut self, seconds: f64) {
384        for c in &mut self.cues {
385            c.start = (c.start + seconds).max(0.0);
386            c.end = (c.end + seconds).max(0.0);
387        }
388    }
389
390    /// Scale every cue time by `factor` — e.g. `24.0 / 25.0` to retime a 25 fps
391    /// track for 24 fps playback.
392    pub fn scale(&mut self, factor: f64) {
393        for c in &mut self.cues {
394            c.start *= factor;
395            c.end *= factor;
396        }
397    }
398
399    /// Parse SubRip (`.srt`).
400    pub fn parse_srt(text: &str) -> Result<Self, CaptionError> {
401        srt::parse(text)
402    }
403
404    /// Parse WebVTT (`.vtt`).
405    pub fn parse_vtt(text: &str) -> Result<Self, CaptionError> {
406        vtt::parse(text)
407    }
408
409    /// Parse either format, sniffing the `WEBVTT` magic.
410    pub fn parse(text: &str) -> Result<Self, CaptionError> {
411        if text
412            .trim_start_matches('\u{feff}')
413            .trim_start()
414            .starts_with("WEBVTT")
415        {
416            vtt::parse(text)
417        } else {
418            srt::parse(text)
419        }
420    }
421
422    /// Serialize to SubRip.
423    pub fn to_srt(&self) -> String {
424        srt::write(self)
425    }
426
427    /// Serialize to WebVTT.
428    pub fn to_vtt(&self) -> String {
429        vtt::write(self)
430    }
431
432    /// Serialize to `format`.
433    pub fn to_format(&self, format: CaptionFormat) -> String {
434        match format {
435            CaptionFormat::Srt => self.to_srt(),
436            CaptionFormat::Vtt => self.to_vtt(),
437        }
438    }
439}
440
441/// Look, placement, and wrapping of burned-in / on-screen captions.
442///
443/// Sizes are in pixels at the frame resolution the caption is drawn into. Use
444/// [`scaled`](Self::scaled) to keep the look consistent across resolutions.
445#[derive(Clone, Debug, PartialEq)]
446pub struct CaptionStyle {
447    /// Cap-to-descender type size in pixels.
448    pub font_size: f32,
449    /// Fill color, RGBA.
450    pub color: [u8; 4],
451    /// Outline (stroke) color, RGBA. Alpha `0` disables the outline.
452    pub outline_color: [u8; 4],
453    /// Outline half-width in pixels. `0` disables the outline.
454    pub outline_width: f32,
455    /// Drop-shadow color, RGBA. Alpha `0` disables the shadow.
456    pub shadow_color: [u8; 4],
457    /// Drop-shadow offset in pixels, `[dx, dy]`.
458    pub shadow_offset: [f32; 2],
459    /// Background box color, RGBA. Alpha `0` disables the box.
460    pub background: [u8; 4],
461    /// Padding between the text and the background box edge, in pixels.
462    pub padding: f32,
463    /// Line advance as a multiple of `font_size`.
464    pub line_height: f32,
465    /// Extra tracking between glyphs, in pixels.
466    pub letter_spacing: f32,
467    /// Horizontal alignment of lines within the caption block.
468    pub align: CaptionAlign,
469    /// Frame edge the block is anchored to.
470    pub anchor: CaptionAnchor,
471    /// Distance from the anchored edge, in pixels. Ignored for
472    /// [`CaptionAnchor::Middle`].
473    pub margin: f32,
474    /// Widest a line may get before wrapping, as a fraction of frame width.
475    pub max_width: f32,
476}
477
478impl Default for CaptionStyle {
479    /// Broadcast-style bottom-centered white text with a black outline and a
480    /// translucent box, sized for 1080p.
481    fn default() -> Self {
482        Self {
483            font_size: 34.0,
484            color: [255, 255, 255, 255],
485            outline_color: [0, 0, 0, 255],
486            outline_width: 2.0,
487            shadow_color: [0, 0, 0, 0],
488            shadow_offset: [2.0, 2.0],
489            background: [0, 0, 0, 140],
490            padding: 10.0,
491            line_height: 1.25,
492            letter_spacing: 0.0,
493            align: CaptionAlign::Center,
494            anchor: CaptionAnchor::Bottom,
495            margin: 48.0,
496            max_width: 0.8,
497        }
498    }
499}
500
501impl CaptionStyle {
502    /// Type size in pixels.
503    pub fn font_size(mut self, px: f32) -> Self {
504        self.font_size = px.max(1.0);
505        self
506    }
507
508    /// Text fill color.
509    pub fn color(mut self, rgba: [u8; 4]) -> Self {
510        self.color = rgba;
511        self
512    }
513
514    /// Outline color and half-width in pixels. Width `0` removes the outline.
515    pub fn outline(mut self, rgba: [u8; 4], width: f32) -> Self {
516        self.outline_color = rgba;
517        self.outline_width = width.max(0.0);
518        self
519    }
520
521    /// Drop shadow color and offset. Alpha `0` removes the shadow.
522    pub fn shadow(mut self, rgba: [u8; 4], dx: f32, dy: f32) -> Self {
523        self.shadow_color = rgba;
524        self.shadow_offset = [dx, dy];
525        self
526    }
527
528    /// Background box color. Alpha `0` removes the box.
529    pub fn background(mut self, rgba: [u8; 4]) -> Self {
530        self.background = rgba;
531        self
532    }
533
534    /// Padding inside the background box, in pixels.
535    pub fn padding(mut self, px: f32) -> Self {
536        self.padding = px.max(0.0);
537        self
538    }
539
540    /// Line advance as a multiple of the type size.
541    pub fn line_height(mut self, factor: f32) -> Self {
542        self.line_height = factor.max(0.1);
543        self
544    }
545
546    /// Extra tracking between glyphs, in pixels.
547    pub fn letter_spacing(mut self, px: f32) -> Self {
548        self.letter_spacing = px;
549        self
550    }
551
552    /// Horizontal alignment of lines within the block.
553    pub fn align(mut self, align: CaptionAlign) -> Self {
554        self.align = align;
555        self
556    }
557
558    /// Frame edge to anchor the block to.
559    pub fn anchor(mut self, anchor: CaptionAnchor) -> Self {
560        self.anchor = anchor;
561        self
562    }
563
564    /// Distance from the anchored edge, in pixels.
565    pub fn margin(mut self, px: f32) -> Self {
566        self.margin = px.max(0.0);
567        self
568    }
569
570    /// Wrap width as a fraction (`0..=1`) of the frame width.
571    pub fn max_width(mut self, fraction: f32) -> Self {
572        self.max_width = fraction.clamp(0.05, 1.0);
573        self
574    }
575
576    /// A copy with every pixel measurement multiplied by `factor` — the way to
577    /// keep one style looking right at several output sizes.
578    ///
579    /// ```
580    /// use threers_captions::CaptionStyle;
581    /// // 1080p defaults, retargeted to 720p.
582    /// let style = CaptionStyle::default().scaled(720.0 / 1080.0);
583    /// assert!((style.font_size - 34.0 * 2.0 / 3.0).abs() < 1e-4);
584    /// ```
585    pub fn scaled(&self, factor: f32) -> Self {
586        let f = factor.max(0.01);
587        Self {
588            font_size: self.font_size * f,
589            outline_width: self.outline_width * f,
590            shadow_offset: [self.shadow_offset[0] * f, self.shadow_offset[1] * f],
591            padding: self.padding * f,
592            letter_spacing: self.letter_spacing * f,
593            margin: self.margin * f,
594            ..self.clone()
595        }
596    }
597
598    /// A copy sized for a frame `height` pixels tall, treating the current
599    /// values as authored for 1080p.
600    ///
601    /// ```
602    /// use threers_captions::CaptionStyle;
603    /// let s = CaptionStyle::default().for_height(2160);
604    /// assert!((s.font_size - 68.0).abs() < 1e-4);
605    /// ```
606    pub fn for_height(&self, height: u32) -> Self {
607        self.scaled(height.max(1) as f32 / 1080.0)
608    }
609}
610
611/// Best-effort ISO-639-2/T three-letter language code for a BCP-47 tag, as MP4
612/// (`mdhd.language`) and Matroska (`Language`) both want.
613///
614/// Three-letter tags pass through, common two-letter tags are mapped, and
615/// anything unrecognized becomes `und` (undetermined).
616///
617/// ```
618/// use threers_captions::iso639_2;
619/// assert_eq!(&iso639_2("en-US"), b"eng");
620/// assert_eq!(&iso639_2("por"), b"por");
621/// assert_eq!(&iso639_2(""), b"und");
622/// ```
623pub fn iso639_2(language: &str) -> [u8; 3] {
624    let primary = language
625        .split(['-', '_'])
626        .next()
627        .unwrap_or("")
628        .to_ascii_lowercase();
629    let bytes = primary.as_bytes();
630    if bytes.len() == 3 && bytes.iter().all(|b| b.is_ascii_lowercase()) {
631        return [bytes[0], bytes[1], bytes[2]];
632    }
633    let mapped = match primary.as_str() {
634        "aa" => "aar",
635        "ab" => "abk",
636        "af" => "afr",
637        "am" => "amh",
638        "ar" => "ara",
639        "az" => "aze",
640        "be" => "bel",
641        "bg" => "bul",
642        "bn" => "ben",
643        "bs" => "bos",
644        "ca" => "cat",
645        "cs" => "ces",
646        "cy" => "cym",
647        "da" => "dan",
648        "de" => "deu",
649        "el" => "ell",
650        "en" => "eng",
651        "eo" => "epo",
652        "es" => "spa",
653        "et" => "est",
654        "eu" => "eus",
655        "fa" => "fas",
656        "fi" => "fin",
657        "fr" => "fra",
658        "ga" => "gle",
659        "gl" => "glg",
660        "he" => "heb",
661        "hi" => "hin",
662        "hr" => "hrv",
663        "hu" => "hun",
664        "hy" => "hye",
665        "id" => "ind",
666        "is" => "isl",
667        "it" => "ita",
668        "ja" => "jpn",
669        "ka" => "kat",
670        "kk" => "kaz",
671        "km" => "khm",
672        "kn" => "kan",
673        "ko" => "kor",
674        "lt" => "lit",
675        "lv" => "lav",
676        "mk" => "mkd",
677        "ml" => "mal",
678        "mn" => "mon",
679        "mr" => "mar",
680        "ms" => "msa",
681        "mt" => "mlt",
682        "my" => "mya",
683        "nb" => "nob",
684        "ne" => "nep",
685        "nl" => "nld",
686        "nn" => "nno",
687        "no" => "nor",
688        "pa" => "pan",
689        "pl" => "pol",
690        "ps" => "pus",
691        "pt" => "por",
692        "ro" => "ron",
693        "ru" => "rus",
694        "si" => "sin",
695        "sk" => "slk",
696        "sl" => "slv",
697        "sq" => "sqi",
698        "sr" => "srp",
699        "sv" => "swe",
700        "sw" => "swa",
701        "ta" => "tam",
702        "te" => "tel",
703        "th" => "tha",
704        "tl" => "tgl",
705        "tr" => "tur",
706        "uk" => "ukr",
707        "ur" => "urd",
708        "uz" => "uzb",
709        "vi" => "vie",
710        "zh" => "zho",
711        "zu" => "zul",
712        _ => "und",
713    };
714    let b = mapped.as_bytes();
715    [b[0], b[1], b[2]]
716}
717
718/// Format `seconds` as `HH:MM:SS,mmm` (SubRip) or `HH:MM:SS.mmm` (WebVTT).
719pub(crate) fn format_timestamp(seconds: f64, millis_sep: char) -> String {
720    let total_ms = (seconds.max(0.0) * 1000.0).round() as u64;
721    let ms = total_ms % 1000;
722    let total_s = total_ms / 1000;
723    let s = total_s % 60;
724    let m = (total_s / 60) % 60;
725    let h = total_s / 3600;
726    format!("{h:02}:{m:02}:{s:02}{millis_sep}{ms:03}")
727}
728
729/// Parse `HH:MM:SS,mmm`, `HH:MM:SS.mmm`, or `MM:SS.mmm` into seconds.
730pub(crate) fn parse_timestamp(text: &str) -> Option<f64> {
731    let text = text.trim();
732    if text.is_empty() {
733        return None;
734    }
735    // Split the fractional part off first — it may use ',' or '.'.
736    let (clock, frac) = match text.rfind([',', '.']) {
737        Some(i) => (&text[..i], &text[i + 1..]),
738        None => (text, ""),
739    };
740    if !frac.is_empty() && !frac.bytes().all(|b| b.is_ascii_digit()) {
741        return None;
742    }
743    let mut seconds = 0f64;
744    let mut parts = 0;
745    for part in clock.split(':') {
746        if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
747            return None;
748        }
749        seconds = seconds * 60.0 + part.parse::<f64>().ok()?;
750        parts += 1;
751        if parts > 3 {
752            return None;
753        }
754    }
755    if parts == 0 {
756        return None;
757    }
758    if !frac.is_empty() {
759        // Right-pad/truncate to milliseconds so "5", "50" and "500" all mean 0.5 s.
760        let mut digits = frac.to_string();
761        digits.truncate(3);
762        while digits.len() < 3 {
763            digits.push('0');
764        }
765        seconds += digits.parse::<f64>().ok()? / 1000.0;
766    }
767    Some(seconds)
768}
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773
774    #[test]
775    fn timestamps_round_trip() {
776        assert_eq!(parse_timestamp("00:00:01,500"), Some(1.5));
777        assert_eq!(parse_timestamp("00:00:01.500"), Some(1.5));
778        assert_eq!(parse_timestamp("01:02:03,004"), Some(3723.004));
779        assert_eq!(parse_timestamp("02:03.250"), Some(123.25));
780        assert_eq!(parse_timestamp("00:00:01,5"), Some(1.5));
781        assert_eq!(parse_timestamp("bogus"), None);
782        assert_eq!(parse_timestamp("00:xx:01,500"), None);
783        assert_eq!(format_timestamp(3723.004, ','), "01:02:03,004");
784        assert_eq!(format_timestamp(1.5, '.'), "00:00:01.500");
785        assert_eq!(format_timestamp(-4.0, ','), "00:00:00,000");
786    }
787
788    #[test]
789    fn cues_stay_sorted_and_lookup_by_time() {
790        let track = CaptionTrack::new()
791            .cue(4.0, 6.0, "third")
792            .cue(0.0, 2.0, "first")
793            .cue(2.0, 4.0, "second");
794        let order: Vec<&str> = track.cues.iter().map(|c| c.text.as_str()).collect();
795        assert_eq!(order, ["first", "second", "third"]);
796        assert_eq!(track.cue_at(0.0).unwrap().text, "first");
797        // End is exclusive, so the boundary belongs to exactly one cue.
798        assert_eq!(track.cue_at(2.0).unwrap().text, "second");
799        assert!(track.cue_at(6.0).is_none());
800        assert_eq!(track.duration(), 6.0);
801    }
802
803    #[test]
804    fn overlapping_cues_all_report_active() {
805        let track = CaptionTrack::new()
806            .cue(0.0, 4.0, "speaker one")
807            .cue(1.0, 3.0, "speaker two");
808        assert_eq!(track.active_at(2.0).len(), 2);
809        assert_eq!(track.text_at(2.0), "speaker one\nspeaker two");
810        assert_eq!(track.text_at(3.5), "speaker one");
811        assert_eq!(track.text_at(9.0), "");
812    }
813
814    #[test]
815    fn markup_and_entities_are_stripped() {
816        let cue = Cue::new(
817            0.0,
818            1.0,
819            "<i>Ich</i> &amp; <c.yellow>du</c> {\\an8}<v Bob>hi",
820        );
821        assert_eq!(cue.plain_text(), "Ich & du hi");
822        // A bare ampersand is not an entity and must survive verbatim.
823        assert_eq!(strip_markup("Tom & Jerry"), "Tom & Jerry");
824        assert_eq!(strip_markup("a &lt;b&gt; c"), "a <b> c");
825        assert_eq!(strip_markup("x&nbsp;y"), "x y");
826    }
827
828    #[test]
829    fn shift_and_scale_retime_the_track() {
830        let mut track = CaptionTrack::new().cue(1.0, 2.0, "a").cue(10.0, 11.0, "b");
831        track.shift(-2.0);
832        assert_eq!(track.cues[0].start, 0.0); // clamped, never negative
833        assert_eq!(track.cues[1].start, 8.0);
834        track.scale(0.5);
835        assert_eq!(track.cues[1].start, 4.0);
836    }
837
838    #[test]
839    fn style_scaling_is_proportional() {
840        let base = CaptionStyle::default();
841        let half = base.scaled(0.5);
842        assert_eq!(half.font_size, base.font_size * 0.5);
843        assert_eq!(half.margin, base.margin * 0.5);
844        assert_eq!(half.padding, base.padding * 0.5);
845        // Non-pixel properties are carried through untouched.
846        assert_eq!(half.color, base.color);
847        assert_eq!(half.max_width, base.max_width);
848    }
849
850    #[test]
851    fn format_detection_from_path() {
852        assert_eq!(
853            CaptionFormat::from_path("a/b.SRT"),
854            Some(CaptionFormat::Srt)
855        );
856        assert_eq!(CaptionFormat::from_path("x.vtt"), Some(CaptionFormat::Vtt));
857        assert_eq!(CaptionFormat::from_path("x.mp4"), None);
858    }
859}