Skip to main content

alpha2_model/
caption_import.rs

1//! SRT and WebVTT import: subtitle files to caption cues.
2//!
3//! A millisecond is exactly 120 ticks, so import is lossless. Markup that says who speaks or
4//! what a word is becomes the cue's speaker and runs: a WebVTT voice (`<v Name>`) sets the
5//! speaker and gives classes `voice` plus the voice's classes, `<c.a.b>` gives `a` and `b`,
6//! `<b>`, `<i>` and `<u>` (also in SRT) give `b`, `i` and `u` and draw bold, italic and
7//! underlined (a run style, as WebVTT applies CSS to them), and WebVTT inline timestamps
8//! split the text into runs timed from the cue's start. Other markup is dropped: SRT's other
9//! tags and `{\...}` overrides, WebVTT's `ruby`, `rt` and `lang` tags (text kept) and cue
10//! settings. WebVTT character references are decoded. A `<` in SRT that opens no tag is
11//! text. Blocks that do not parse are skipped and counted.
12//!
13//! A line ends at LF, CR or CRLF, as WebVTT defines; repeated CRs before an LF (line endings
14//! converted twice) end one line.
15//!
16//! Reading is linear in file size. Files over [`MAX_CAPTION_FILE_BYTES`] or with more than
17//! [`MAX_CAPTION_FILE_CUES`] cues are refused early. A block over [`MAX_CUE_BLOCK_BYTES`] or
18//! [`MAX_CUE_BLOCK_LINES`] is skipped without being held. One pass over a cue's markup gives both
19//! its text and its runs; a cue with more than [`MAX_OPEN_TAGS`] tags open, [`MAX_HELD_CLASSES`]
20//! classes held or [`MAX_TEXT_RUNS`] runs is imported as plain text.
21
22use std::cmp::Reverse;
23use std::collections::{BTreeSet, BinaryHeap};
24
25use crate::{
26    CaptionCue, MAX_CLIPS_PER_TRACK, MAX_PROJECT_JSON_BYTES, MAX_RUN_CLASSES,
27    MAX_TEXT_CONTENT_BYTES, MAX_TEXT_RUNS, MAX_TRACKS, RunTime, TextContent, TextRun,
28    valid_class_name,
29};
30use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
31
32/// The largest subtitle file read, in bytes. A cue's JSON is longer than its subtitle block,
33/// so a larger file holds more cues than a project can.
34pub const MAX_CAPTION_FILE_BYTES: usize = MAX_PROJECT_JSON_BYTES;
35
36/// The most cues read from one subtitle file: a day of continuous captions at one cue every
37/// 1.3 s.
38pub const MAX_CAPTION_FILE_CUES: usize = 65_536;
39
40/// The longest block read as a cue, in bytes; a longer one is skipped.
41pub const MAX_CUE_BLOCK_BYTES: usize = 65_536;
42
43/// The most lines of a block read as a cue; a longer one is skipped.
44pub const MAX_CUE_BLOCK_LINES: usize = 1_024;
45
46/// The most WebVTT tags open at once in a cue whose markup is kept.
47pub const MAX_OPEN_TAGS: usize = 32;
48
49/// The most distinct classes the open tags of a cue whose markup is kept give at once.
50pub const MAX_HELD_CLASSES: usize = 64;
51
52/// Cues read from a subtitle file.
53#[derive(Clone, Debug, Default, PartialEq)]
54pub struct ImportedCaptions {
55    /// Cues in file order, sorted by start time. They may overlap; see [`caption_rows`].
56    pub cues: Vec<CaptionCue>,
57    /// Blocks that were not cues and could not be read as one.
58    pub skipped: usize,
59    /// Markup read but not kept.
60    pub notes: ImportNotes,
61}
62
63/// What an import read but could not keep, counted.
64#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
65pub struct ImportNotes {
66    /// Voices after a cue's first, whose names are not its speaker. Their text still takes the
67    /// class `voice`.
68    pub extra_voices: usize,
69    /// Inline timestamps out of order or outside their cue, which WebVTT renderers ignore.
70    pub dropped_timestamps: usize,
71    /// Class names a run cannot carry (not `A-Z a-z 0-9 _ -`, longer than 64 bytes, or past
72    /// [`MAX_RUN_CLASSES`]).
73    pub dropped_classes: usize,
74    /// Cues imported as plain text because their markup had more than [`MAX_TEXT_RUNS`] runs,
75    /// 32 tags open or 64 classes held.
76    pub flattened: usize,
77}
78
79/// Why a file is not a subtitle file at all.
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
81#[non_exhaustive]
82pub enum CaptionImportError {
83    /// A WebVTT file does not begin with `WEBVTT`.
84    MissingWebVttHeader,
85    /// The file is larger than [`MAX_CAPTION_FILE_BYTES`].
86    FileTooLarge {
87        /// The file's size in bytes.
88        bytes: usize,
89        /// The largest file read.
90        maximum: usize,
91    },
92    /// The file holds more than [`MAX_CAPTION_FILE_CUES`] cues.
93    TooManyCues {
94        /// The most cues read from a file.
95        maximum: usize,
96    },
97    /// The cues need more caption tracks than a project holds: too many overlap at once, or there
98    /// are too many to fit [`MAX_CLIPS_PER_TRACK`] to a track.
99    TooManyRows {
100        /// Caption tracks the cues need.
101        rows: usize,
102        /// Tracks a project holds.
103        maximum: usize,
104    },
105}
106
107impl std::fmt::Display for CaptionImportError {
108    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        match self {
110            Self::MissingWebVttHeader => formatter.write_str("a WebVTT file begins with WEBVTT"),
111            Self::FileTooLarge { bytes, maximum } => write!(
112                formatter,
113                "the subtitle file is {bytes} bytes; at most {maximum} are read"
114            ),
115            Self::TooManyCues { maximum } => write!(
116                formatter,
117                "the subtitle file holds more than {maximum} cues"
118            ),
119            Self::TooManyRows { rows, maximum } => write!(
120                formatter,
121                "the captions need {rows} caption tracks; a project holds at most {maximum} tracks"
122            ),
123        }
124    }
125}
126
127impl std::error::Error for CaptionImportError {}
128
129const TICKS_PER_MILLISECOND: i64 = TICKS_PER_SECOND / 1_000;
130
131/// Reads SubRip (`.srt`) text.
132///
133/// # Errors
134/// Returns [`CaptionImportError::FileTooLarge`] or [`CaptionImportError::TooManyCues`] for a
135/// file past the import limits.
136pub fn parse_srt(text: &str) -> Result<ImportedCaptions, CaptionImportError> {
137    check_file_size(text)?;
138    let mut imported = ImportedCaptions::default();
139    for block in Blocks::new(text) {
140        let Some(block) = block else {
141            imported.skipped += 1;
142            continue;
143        };
144        let mut lines = block.iter().copied();
145        let Some(mut first) = lines.next() else {
146            continue;
147        };
148        // An optional sequence number before the timing line.
149        if !first.contains("-->") {
150            match lines.next() {
151                Some(line) if first.trim().chars().all(|c| c.is_ascii_digit()) => first = line,
152                _ => {
153                    imported.skipped += 1;
154                    continue;
155                }
156            }
157        }
158        let body = lines.collect::<Vec<_>>();
159        let range = timing(first);
160        let marked = range.map(|_| srt_markup(&body));
161        imported.read(range, marked)?;
162    }
163    imported.cues.sort_by_key(|cue| cue.timeline_range.start());
164    Ok(imported)
165}
166
167/// Reads WebVTT (`.vtt`) text. `NOTE`, `STYLE`, and `REGION` blocks are ignored.
168///
169/// # Errors
170/// Returns [`CaptionImportError::MissingWebVttHeader`] unless the text begins with `WEBVTT`,
171/// and [`CaptionImportError::FileTooLarge`] or [`CaptionImportError::TooManyCues`] for a
172/// file past the import limits.
173pub fn parse_webvtt(text: &str) -> Result<ImportedCaptions, CaptionImportError> {
174    check_file_size(text)?;
175    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
176    let header_ok = text
177        .strip_prefix("WEBVTT")
178        .is_some_and(|rest| rest.is_empty() || rest.starts_with([' ', '\t', '\n', '\r']));
179    if !header_ok {
180        return Err(CaptionImportError::MissingWebVttHeader);
181    }
182    let mut imported = ImportedCaptions::default();
183    let mut blocks = Blocks::new(text);
184    // The header is the first block up to a timing line; as in the WebVTT parser, a cue may
185    // follow it without a blank line. An oversized header holds no cue that is read.
186    let header = blocks.next().flatten().unwrap_or_default();
187    let cue_under_header = header
188        .iter()
189        .position(|line| line.contains("-->"))
190        .map(|start| Some(header[start..].to_vec()));
191    for block in cue_under_header.into_iter().chain(blocks) {
192        let Some(block) = block else {
193            imported.skipped += 1;
194            continue;
195        };
196        let first = block[0];
197        if ["NOTE", "STYLE", "REGION"].iter().any(|keyword| {
198            first
199                .strip_prefix(keyword)
200                .is_some_and(|rest| rest.is_empty() || rest.starts_with([' ', '\t']))
201        }) {
202            continue;
203        }
204        // An optional cue identifier before the timing line.
205        let (timing_line, body) = if first.contains("-->") {
206            (first, &block[1..])
207        } else if block.len() > 1 && block[1].contains("-->") {
208            (block[1], &block[2..])
209        } else {
210            imported.skipped += 1;
211            continue;
212        };
213        let range = timing(timing_line);
214        let marked = range.map(|range| vtt_markup(&body.join("\n"), range));
215        imported.read(range, marked)?;
216    }
217    imported.cues.sort_by_key(|cue| cue.timeline_range.start());
218    Ok(imported)
219}
220
221impl ImportedCaptions {
222    /// Keeps a block's cue, or counts it skipped when its timing or text is invalid. `marked` is
223    /// the cue's text with the speaker and runs its markup gives.
224    fn read(
225        &mut self,
226        range: Option<TimeRange>,
227        marked: Option<Marked>,
228    ) -> Result<(), CaptionImportError> {
229        let (Some(range), Some(marked)) = (range, marked) else {
230            self.skipped += 1;
231            return Ok(());
232        };
233        let Some(text) = cue_text(&marked.text) else {
234            self.skipped += 1;
235            return Ok(());
236        };
237        if self.cues.len() == MAX_CAPTION_FILE_CUES {
238            return Err(CaptionImportError::TooManyCues {
239                maximum: MAX_CAPTION_FILE_CUES,
240            });
241        }
242        let mut cue = CaptionCue::new(range, text);
243        let notes = &mut self.notes;
244        notes.extra_voices += marked.notes.extra_voices;
245        notes.dropped_timestamps += marked.notes.dropped_timestamps;
246        notes.dropped_classes += marked.notes.dropped_classes;
247        notes.flattened += marked.notes.flattened;
248        cue.speaker = marked.speaker;
249        if let Some(runs) = marked.runs.filter(|runs| !runs.is_empty()) {
250            cue.text = TextContent::Runs(runs);
251        }
252        self.cues.push(cue);
253        Ok(())
254    }
255}
256
257fn check_file_size(text: &str) -> Result<(), CaptionImportError> {
258    if text.len() > MAX_CAPTION_FILE_BYTES {
259        return Err(CaptionImportError::FileTooLarge {
260            bytes: text.len(),
261            maximum: MAX_CAPTION_FILE_BYTES,
262        });
263    }
264    Ok(())
265}
266
267/// Splits cues onto rows, one caption track each. Every cue goes to the first row with room
268/// (a track holds [`MAX_CLIPS_PER_TRACK`]) whose last cue has ended by its start.
269/// O(n log n) in the cues, however many overlap.
270///
271/// # Errors
272/// Returns [`CaptionImportError::TooManyRows`] for cues that need more rows than a project
273/// holds tracks.
274pub fn caption_rows(cues: &[CaptionCue]) -> Result<Vec<Vec<CaptionCue>>, CaptionImportError> {
275    let mut sorted = cues.to_vec();
276    sorted.sort_by_key(|cue| cue.timeline_range.start());
277    let mut rows: Vec<Vec<CaptionCue>> = Vec::new();
278    // Rows with room, split into those whose last cue has ended by the cue being placed and the
279    // others keyed by when theirs ends. A full row is in neither.
280    let mut ended = BTreeSet::<usize>::new();
281    let mut ending = BinaryHeap::<Reverse<(MediaTime, usize)>>::new();
282    for cue in sorted {
283        let start = cue.timeline_range.start();
284        while let Some(&Reverse((end, row))) = ending.peek()
285            && end <= start
286        {
287            ending.pop();
288            ended.insert(row);
289        }
290        let row = ended.pop_first().unwrap_or_else(|| {
291            rows.push(Vec::new());
292            rows.len() - 1
293        });
294        let end = cue.timeline_range.end();
295        rows[row].push(cue);
296        if rows[row].len() < MAX_CLIPS_PER_TRACK {
297            ending.push(Reverse((end, row)));
298        }
299    }
300    if rows.len() > MAX_TRACKS {
301        return Err(CaptionImportError::TooManyRows {
302            rows: rows.len(),
303            maximum: MAX_TRACKS,
304        });
305    }
306    Ok(rows)
307}
308
309/// Blank-line-separated blocks of lines, one at a time. `None` stands for a block over
310/// [`MAX_CUE_BLOCK_BYTES`] or [`MAX_CUE_BLOCK_LINES`], whose lines are not kept.
311struct Blocks<'a> {
312    lines: Lines<'a>,
313}
314
315impl<'a> Blocks<'a> {
316    fn new(text: &'a str) -> Self {
317        Self {
318            lines: Lines {
319                text: text.strip_prefix('\u{feff}').unwrap_or(text),
320                at: 0,
321                pending_blanks: 0,
322                done: false,
323            },
324        }
325    }
326}
327
328impl<'a> Iterator for Blocks<'a> {
329    type Item = Option<Vec<&'a str>>;
330
331    fn next(&mut self) -> Option<Self::Item> {
332        let mut block = Vec::new();
333        let mut bytes = 0_usize;
334        let mut oversized = false;
335        for line in self.lines.by_ref() {
336            if line.trim().is_empty() {
337                if oversized || !block.is_empty() {
338                    break;
339                }
340                continue;
341            }
342            if oversized {
343                continue;
344            }
345            bytes += line.len() + 1;
346            if bytes > MAX_CUE_BLOCK_BYTES || block.len() == MAX_CUE_BLOCK_LINES {
347                oversized = true;
348                block = Vec::new();
349                continue;
350            }
351            block.push(line);
352        }
353        if oversized {
354            Some(None)
355        } else {
356            (!block.is_empty()).then_some(Some(block))
357        }
358    }
359}
360
361/// The lines of a text. LF, CR or CRLF ends a line, as does a run of CRs followed by LF. A CR
362/// run without a following LF ends a line per CR.
363struct Lines<'a> {
364    text: &'a str,
365    at: usize,
366    /// Empty lines still owed by a CR run.
367    pending_blanks: usize,
368    done: bool,
369}
370
371impl<'a> Iterator for Lines<'a> {
372    type Item = &'a str;
373
374    fn next(&mut self) -> Option<&'a str> {
375        if self.pending_blanks > 0 {
376            self.pending_blanks -= 1;
377            return Some("");
378        }
379        if self.done {
380            return None;
381        }
382        let bytes = self.text.as_bytes();
383        let start = self.at;
384        let Some(end) = bytes[start..]
385            .iter()
386            .position(|&byte| matches!(byte, b'\n' | b'\r'))
387            .map(|offset| start + offset)
388        else {
389            self.done = true;
390            return Some(&self.text[start..]);
391        };
392        if bytes[end] == b'\n' {
393            self.at = end + 1;
394        } else {
395            let returns = bytes[end..]
396                .iter()
397                .take_while(|&&byte| byte == b'\r')
398                .count();
399            self.at = end + returns;
400            if bytes.get(self.at) == Some(&b'\n') {
401                self.at += 1;
402            } else {
403                self.pending_blanks = returns - 1;
404            }
405        }
406        Some(&self.text[start..end])
407    }
408}
409
410/// `start --> end`, ignoring anything after the end time (WebVTT settings).
411fn timing(line: &str) -> Option<TimeRange> {
412    let (start, rest) = line.split_once("-->")?;
413    let end = rest.split_whitespace().next()?;
414    let (start, end) = (timestamp(start.trim())?, timestamp(end)?);
415    TimeRange::new(start, end)
416        .ok()
417        .filter(|range| !range.is_empty())
418}
419
420/// `[hh:]mm:ss[,.]mmm`, hours any number of digits, up to
421/// [`alpha2_time::MAX_SERIALIZED_TICKS`] (a later cue could not be saved).
422fn timestamp(text: &str) -> Option<MediaTime> {
423    let (clock, millis) = text.split_once([',', '.'])?;
424    if millis.len() != 3 || !millis.bytes().all(|byte| byte.is_ascii_digit()) {
425        return None;
426    }
427    let fields = clock.split(':').collect::<Vec<_>>();
428    let number = |field: &str| {
429        (!field.is_empty() && field.bytes().all(|byte| byte.is_ascii_digit()))
430            .then(|| field.parse::<i64>().ok())
431            .flatten()
432    };
433    let (hours, minutes, seconds) = match fields.as_slice() {
434        [hours, minutes, seconds] => (number(hours)?, number(minutes)?, number(seconds)?),
435        [minutes, seconds] => (0, number(minutes)?, number(seconds)?),
436        _ => return None,
437    };
438    if minutes > 59 || seconds > 59 {
439        return None;
440    }
441    let milliseconds = ((hours.checked_mul(60)?.checked_add(minutes)?)
442        .checked_mul(60)?
443        .checked_add(seconds)?)
444    .checked_mul(1_000)?
445    .checked_add(millis.parse::<i64>().ok()?)?;
446    let ticks = milliseconds.checked_mul(TICKS_PER_MILLISECOND)?;
447    (ticks <= alpha2_time::MAX_SERIALIZED_TICKS).then(|| MediaTime::from_ticks(ticks))
448}
449
450/// Cue text with surrounding blank lines trimmed, or `None` when empty or too long.
451fn cue_text(text: &str) -> Option<String> {
452    let text = text.trim_matches('\n').to_owned();
453    (!text.trim().is_empty() && text.len() <= MAX_TEXT_CONTENT_BYTES).then_some(text)
454}
455
456/// Decodes WebVTT's named and numeric character references; unknown ones stay as written.
457///
458/// A reference is letters, digits, `#` and `+` closed by `;`, so each `&` looks only that
459/// far and the text is read in linear time.
460fn decode_references(text: &str) -> String {
461    let mut output = String::with_capacity(text.len());
462    let mut rest = text;
463    while let Some(start) = rest.find('&') {
464        output.push_str(&rest[..start]);
465        rest = &rest[start + 1..];
466        let length = rest
467            .bytes()
468            .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'#' | b'+'))
469            .count();
470        let decoded = (rest.as_bytes().get(length) == Some(&b';'))
471            .then(|| reference(&rest[..length]))
472            .flatten();
473        match decoded {
474            Some(character) => {
475                output.push(character);
476                rest = &rest[length + 1..];
477            }
478            None => output.push('&'),
479        }
480    }
481    output.push_str(rest);
482    output
483}
484
485/// The character a reference's name, between `&` and `;`, stands for.
486fn reference(name: &str) -> Option<char> {
487    match name {
488        "amp" => Some('&'),
489        "lt" => Some('<'),
490        "gt" => Some('>'),
491        "nbsp" => Some('\u{a0}'),
492        "lrm" => Some('\u{200e}'),
493        "rlm" => Some('\u{200f}'),
494        _ => name
495            .strip_prefix("#x")
496            .or_else(|| name.strip_prefix("#X"))
497            .and_then(|hex| u32::from_str_radix(hex, 16).ok())
498            .or_else(|| name.strip_prefix('#').and_then(|dec| dec.parse().ok()))
499            .and_then(char::from_u32),
500    }
501}
502
503/// A cue's text and what its markup says: its speaker, its runs when any carries a class or a
504/// time (else the plain text stands), and what was dropped.
505struct Marked {
506    text: String,
507    speaker: Option<String>,
508    runs: Option<Vec<TextRun>>,
509    notes: ImportNotes,
510}
511
512/// The `<b>`, `<i>` and `<u>` tags open around a piece of text (WebVTT, "Applying CSS
513/// properties to WebVTT Node Objects": bold, italic, underline; SRT alike).
514#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
515struct Emphasis {
516    bold: bool,
517    italic: bool,
518    underline: bool,
519}
520
521impl Emphasis {
522    fn of<'n>(names: impl IntoIterator<Item = &'n str>) -> Self {
523        let mut emphasis = Self::default();
524        for name in names {
525            match name {
526                "b" => emphasis.bold = true,
527                "i" => emphasis.italic = true,
528                "u" => emphasis.underline = true,
529                _ => {}
530            }
531        }
532        emphasis
533    }
534
535    fn of_open(open: &[String]) -> Self {
536        Self::of(open.iter().map(String::as_str))
537    }
538
539    fn style(self) -> Option<crate::TextRunStyle> {
540        (self != Self::default()).then(|| crate::TextRunStyle {
541            font_weight: self.bold.then_some(700),
542            font_style: self.italic.then_some(crate::FontStyle::Italic),
543            underline: self.underline.then_some(true),
544            ..crate::TextRunStyle::default()
545        })
546    }
547}
548
549/// Builds a cue's text and runs from text pieces, each with its open classes and time segment.
550/// Markup stops being tracked (the cue is imported as plain text) past [`MAX_TEXT_RUNS`] pieces
551/// beyond what trimming can remove.
552struct Runs {
553    text: String,
554    pieces: Vec<(String, Vec<String>, usize, Emphasis)>,
555    tracking: bool,
556    notes: ImportNotes,
557}
558
559impl Runs {
560    fn new() -> Self {
561        Self {
562            text: String::new(),
563            pieces: Vec::new(),
564            tracking: true,
565            notes: ImportNotes::default(),
566        }
567    }
568
569    /// Stops tracking markup: the cue is imported as plain text.
570    fn flatten(&mut self) {
571        if self.tracking {
572            self.tracking = false;
573            self.pieces = Vec::new();
574            self.notes.flattened += 1;
575        }
576    }
577
578    fn push(&mut self, text: &str, classes: &[String], segment: usize, emphasis: Emphasis) {
579        self.text.push_str(text);
580        if !self.tracking {
581            return;
582        }
583        // Leading line feeds are trimmed from the runs as `cue_text` trims them from the text.
584        let text = if self.pieces.is_empty() {
585            text.trim_start_matches('\n')
586        } else {
587            text
588        };
589        if text.is_empty() {
590            return;
591        }
592        match self.pieces.last_mut() {
593            Some((held, open, at, emphasized))
594                if open.as_slice() == classes && *at == segment && *emphasized == emphasis =>
595            {
596                held.push_str(text);
597            }
598            _ => {
599                // Two more than the limit: trailing line feeds can still remove one.
600                if self.pieces.len() > MAX_TEXT_RUNS + 1 {
601                    self.flatten();
602                    return;
603                }
604                self.pieces
605                    .push((text.to_owned(), classes.to_vec(), segment, emphasis));
606            }
607        }
608    }
609
610    /// The text and runs, timed by `bounds` (each segment's start, then the end, in ticks from
611    /// the cue's start), with trailing line feeds trimmed as for plain cue text. No runs when
612    /// none carries a class or a time.
613    fn finish(mut self, speaker: Option<String>, bounds: &[i64]) -> Marked {
614        while let Some(last) = self.pieces.last_mut() {
615            let kept = last.0.trim_end_matches('\n').len();
616            last.0.truncate(kept);
617            if last.0.is_empty() {
618                self.pieces.pop();
619            } else {
620                break;
621            }
622        }
623        if self.pieces.len() > MAX_TEXT_RUNS {
624            self.flatten();
625        }
626        let timed = bounds.len() > 2;
627        let runs = (self.tracking
628            && (timed
629                || self
630                    .pieces
631                    .iter()
632                    .any(|(_, classes, ..)| !classes.is_empty())))
633        .then(|| {
634            self.pieces
635                .into_iter()
636                .map(|(text, mut class, segment, emphasis)| {
637                    if class.len() > MAX_RUN_CLASSES {
638                        self.notes.dropped_classes += class.len() - MAX_RUN_CLASSES;
639                        class.truncate(MAX_RUN_CLASSES);
640                    }
641                    TextRun {
642                        text,
643                        class,
644                        time: timed.then(|| RunTime {
645                            start: MediaTime(bounds[segment]),
646                            end: MediaTime(bounds[segment + 1]),
647                        }),
648                        style: emphasis.style(),
649                    }
650                })
651                .collect()
652        });
653        Marked {
654            text: self.text,
655            speaker,
656            runs,
657            notes: self.notes,
658        }
659    }
660}
661
662/// The classes a tag's dot-separated `names` give; ones a run cannot carry are counted and
663/// dropped.
664fn tag_classes(names: &str, notes: &mut ImportNotes) -> Vec<String> {
665    names
666        .split('.')
667        .filter(|name| !name.is_empty())
668        .filter_map(|name| {
669            if valid_class_name(name) {
670                Some(name.to_owned())
671            } else {
672                notes.dropped_classes += 1;
673                None
674            }
675        })
676        .collect()
677}
678
679/// A WebVTT cue body's text and markup for a cue over `range`: voices, classes, bold, italic and
680/// underline as run classes and styles, and inline timestamps splitting the runs. A `<` with no
681/// `>` after it ends the cue text, as the WebVTT cue text tokenizer does. Linear in the body:
682/// each open tag records how many classes it added, and closing it truncates them.
683fn vtt_markup(body: &str, range: TimeRange) -> Marked {
684    let start = range.start().ticks();
685    let duration = range.duration().map_or(0, MediaTime::ticks);
686    let mut runs = Runs::new();
687    let mut speaker = None;
688    // The tags open, each with the length of `classes` before it opened, innermost last.
689    let mut open: Vec<(&str, usize)> = Vec::new();
690    // The distinct classes the open tags give, in order.
691    let mut classes: Vec<String> = Vec::new();
692    let mut bounds = vec![0_i64];
693    let mut rest = body;
694    loop {
695        let emphasis = Emphasis::of(open.iter().map(|(name, _)| *name));
696        let Some(at) = rest.find('<') else {
697            runs.push(
698                &decode_references(rest),
699                &classes,
700                bounds.len() - 1,
701                emphasis,
702            );
703            break;
704        };
705        runs.push(
706            &decode_references(&rest[..at]),
707            &classes,
708            bounds.len() - 1,
709            emphasis,
710        );
711        let Some(end) = rest[at..].find('>') else {
712            break;
713        };
714        let tag = &rest[at + 1..at + end];
715        rest = &rest[at + end + 1..];
716        if let Some(name) = tag.strip_prefix('/') {
717            let name = name.trim();
718            if let Some(index) = open.iter().rposition(|(open, _)| *open == name) {
719                classes.truncate(open[index].1);
720                open.truncate(index);
721            }
722            continue;
723        }
724        if tag.starts_with(|character: char| character.is_ascii_digit()) {
725            // An inline timestamp: kept only in order and inside the cue.
726            match timestamp(tag.trim()) {
727                Some(time)
728                    if time.ticks() - start > *bounds.last().unwrap_or(&0)
729                        && time.ticks() - start < duration =>
730                {
731                    if runs.tracking {
732                        bounds.push(time.ticks() - start);
733                    }
734                }
735                _ => runs.notes.dropped_timestamps += 1,
736            }
737            continue;
738        }
739        // `name.classes annotation`.
740        let (head, annotation) = tag
741            .split_once([' ', '\t'])
742            .map_or((tag, ""), |(head, annotation)| (head, annotation.trim()));
743        let (name, names) = head.split_once('.').unwrap_or((head, ""));
744        let given = match name {
745            "v" => {
746                if speaker.is_none() && !annotation.is_empty() {
747                    speaker = Some(annotation.to_owned());
748                } else if !annotation.is_empty() {
749                    runs.notes.extra_voices += 1;
750                }
751                let mut given = vec!["voice".to_owned()];
752                given.extend(tag_classes(names, &mut runs.notes));
753                given
754            }
755            "c" => tag_classes(names, &mut runs.notes),
756            "b" | "i" | "u" => {
757                let mut given = vec![name.to_owned()];
758                given.extend(tag_classes(names, &mut runs.notes));
759                given
760            }
761            _ => Vec::new(),
762        };
763        if !runs.tracking {
764            continue;
765        }
766        if open.len() == MAX_OPEN_TAGS {
767            runs.flatten();
768            continue;
769        }
770        open.push((name, classes.len()));
771        for class in given {
772            if !classes.contains(&class) {
773                if classes.len() == MAX_HELD_CLASSES {
774                    runs.flatten();
775                    break;
776                }
777                classes.push(class);
778            }
779        }
780    }
781    bounds.push(duration);
782    let speaker = speaker.filter(|speaker| speaker.len() <= crate::MAX_CAPTION_NAME_BYTES);
783    runs.finish(speaker, &bounds)
784}
785
786/// An SRT cue body's markup: `<b>`, `<i>` and `<u>` as run classes and styles; other tags and
787/// override blocks dropped.
788fn srt_markup(body: &[&str]) -> Marked {
789    let mut runs = Runs::new();
790    let mut open: Vec<String> = Vec::new();
791    for (index, line) in body.iter().enumerate() {
792        if index > 0 {
793            runs.push("\n", &open, 0, Emphasis::of_open(&open));
794        }
795        let line = strip_overrides(line);
796        let mut rest = line.as_str();
797        while let Some(start) = rest.find('<') {
798            runs.push(&rest[..start], &open, 0, Emphasis::of_open(&open));
799            let tag = &rest[start + 1..];
800            let closing = tag.starts_with('/');
801            let name = tag.strip_prefix('/').unwrap_or(tag);
802            match tag.find(['<', '>']) {
803                Some(end)
804                    if tag.as_bytes()[end] == b'>'
805                        && name.starts_with(|character: char| character.is_ascii_alphabetic()) =>
806                {
807                    let tag_name = name[..name.len().min(end - usize::from(closing))]
808                        .split([' ', '\t'])
809                        .next()
810                        .unwrap_or_default()
811                        .to_ascii_lowercase();
812                    if matches!(tag_name.as_str(), "b" | "i" | "u") {
813                        if closing {
814                            if let Some(index) = open.iter().rposition(|open| *open == tag_name) {
815                                open.remove(index);
816                            }
817                        } else if !open.contains(&tag_name) {
818                            open.push(tag_name);
819                        }
820                    }
821                    rest = &tag[end + 1..];
822                }
823                _ => {
824                    runs.push("<", &open, 0, Emphasis::of_open(&open));
825                    rest = tag;
826                }
827            }
828        }
829        runs.push(rest, &open, 0, Emphasis::of_open(&open));
830    }
831    runs.finish(None, &[0, 0])
832}
833
834/// SRT text without its `{\...}` override blocks.
835fn strip_overrides(line: &str) -> String {
836    let mut output = String::with_capacity(line.len());
837    let mut rest = line;
838    while let Some(start) = rest.find("{\\") {
839        output.push_str(&rest[..start]);
840        match rest[start..].find('}') {
841            Some(end) => rest = &rest[start + end + 1..],
842            None => {
843                rest = "";
844            }
845        }
846    }
847    output.push_str(rest);
848    output
849}
850
851#[cfg(test)]
852#[path = "caption_import_tests.rs"]
853mod tests;