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/// Reads a subtitle file (`format` is `srt` or `webvtt`) into caption cues, returned as JSON
310/// `{ rows, skipped, notes }`.
311///
312/// `rows` holds one caption track's `CaptionCue`s per row ([`caption_rows`]). `skipped` counts
313/// blocks that were not cues; `notes` counts markup read but not kept (`extraVoices`,
314/// `droppedTimestamps`, `droppedClasses`, `flattened`).
315///
316/// # Errors
317/// Refuses an unknown format, a WebVTT file without its header, and cues that need more caption
318/// tracks than a project holds.
319pub fn parse_captions_json(text: &str, format: &str) -> Result<String, String> {
320    let imported = match format {
321        "srt" => parse_srt(text),
322        "webvtt" => parse_webvtt(text),
323        other => return Err(format!("caption format must be srt or webvtt, not {other}")),
324    }
325    .map_err(|error| error.to_string())?;
326    let rows = caption_rows(&imported.cues).map_err(|error| error.to_string())?;
327    let notes = imported.notes;
328    Ok(serde_json::json!({
329        "rows": rows,
330        "skipped": imported.skipped,
331        "notes": {
332            "extraVoices": notes.extra_voices,
333            "droppedTimestamps": notes.dropped_timestamps,
334            "droppedClasses": notes.dropped_classes,
335            "flattened": notes.flattened,
336        },
337    })
338    .to_string())
339}
340
341/// Blank-line-separated blocks of lines, one at a time. `None` stands for a block over
342/// [`MAX_CUE_BLOCK_BYTES`] or [`MAX_CUE_BLOCK_LINES`], whose lines are not kept.
343struct Blocks<'a> {
344    lines: Lines<'a>,
345}
346
347impl<'a> Blocks<'a> {
348    fn new(text: &'a str) -> Self {
349        Self {
350            lines: Lines {
351                text: text.strip_prefix('\u{feff}').unwrap_or(text),
352                at: 0,
353                pending_blanks: 0,
354                done: false,
355            },
356        }
357    }
358}
359
360impl<'a> Iterator for Blocks<'a> {
361    type Item = Option<Vec<&'a str>>;
362
363    fn next(&mut self) -> Option<Self::Item> {
364        let mut block = Vec::new();
365        let mut bytes = 0_usize;
366        let mut oversized = false;
367        for line in self.lines.by_ref() {
368            if line.trim().is_empty() {
369                if oversized || !block.is_empty() {
370                    break;
371                }
372                continue;
373            }
374            if oversized {
375                continue;
376            }
377            bytes += line.len() + 1;
378            if bytes > MAX_CUE_BLOCK_BYTES || block.len() == MAX_CUE_BLOCK_LINES {
379                oversized = true;
380                block = Vec::new();
381                continue;
382            }
383            block.push(line);
384        }
385        if oversized {
386            Some(None)
387        } else {
388            (!block.is_empty()).then_some(Some(block))
389        }
390    }
391}
392
393/// The lines of a text. LF, CR or CRLF ends a line, as does a run of CRs followed by LF. A CR
394/// run without a following LF ends a line per CR.
395struct Lines<'a> {
396    text: &'a str,
397    at: usize,
398    /// Empty lines still owed by a CR run.
399    pending_blanks: usize,
400    done: bool,
401}
402
403impl<'a> Iterator for Lines<'a> {
404    type Item = &'a str;
405
406    fn next(&mut self) -> Option<&'a str> {
407        if self.pending_blanks > 0 {
408            self.pending_blanks -= 1;
409            return Some("");
410        }
411        if self.done {
412            return None;
413        }
414        let bytes = self.text.as_bytes();
415        let start = self.at;
416        let Some(end) = bytes[start..]
417            .iter()
418            .position(|&byte| matches!(byte, b'\n' | b'\r'))
419            .map(|offset| start + offset)
420        else {
421            self.done = true;
422            return Some(&self.text[start..]);
423        };
424        if bytes[end] == b'\n' {
425            self.at = end + 1;
426        } else {
427            let returns = bytes[end..]
428                .iter()
429                .take_while(|&&byte| byte == b'\r')
430                .count();
431            self.at = end + returns;
432            if bytes.get(self.at) == Some(&b'\n') {
433                self.at += 1;
434            } else {
435                self.pending_blanks = returns - 1;
436            }
437        }
438        Some(&self.text[start..end])
439    }
440}
441
442/// `start --> end`, ignoring anything after the end time (WebVTT settings).
443fn timing(line: &str) -> Option<TimeRange> {
444    let (start, rest) = line.split_once("-->")?;
445    let end = rest.split_whitespace().next()?;
446    let (start, end) = (timestamp(start.trim())?, timestamp(end)?);
447    TimeRange::new(start, end)
448        .ok()
449        .filter(|range| !range.is_empty())
450}
451
452/// `[hh:]mm:ss[,.]mmm`, hours any number of digits, up to
453/// [`alpha2_time::MAX_SERIALIZED_TICKS`] (a later cue could not be saved).
454fn timestamp(text: &str) -> Option<MediaTime> {
455    let (clock, millis) = text.split_once([',', '.'])?;
456    if millis.len() != 3 || !millis.bytes().all(|byte| byte.is_ascii_digit()) {
457        return None;
458    }
459    let fields = clock.split(':').collect::<Vec<_>>();
460    let number = |field: &str| {
461        (!field.is_empty() && field.bytes().all(|byte| byte.is_ascii_digit()))
462            .then(|| field.parse::<i64>().ok())
463            .flatten()
464    };
465    let (hours, minutes, seconds) = match fields.as_slice() {
466        [hours, minutes, seconds] => (number(hours)?, number(minutes)?, number(seconds)?),
467        [minutes, seconds] => (0, number(minutes)?, number(seconds)?),
468        _ => return None,
469    };
470    if minutes > 59 || seconds > 59 {
471        return None;
472    }
473    let milliseconds = ((hours.checked_mul(60)?.checked_add(minutes)?)
474        .checked_mul(60)?
475        .checked_add(seconds)?)
476    .checked_mul(1_000)?
477    .checked_add(millis.parse::<i64>().ok()?)?;
478    let ticks = milliseconds.checked_mul(TICKS_PER_MILLISECOND)?;
479    (ticks <= alpha2_time::MAX_SERIALIZED_TICKS).then(|| MediaTime::from_ticks(ticks))
480}
481
482/// Cue text with surrounding blank lines trimmed, or `None` when empty or too long.
483fn cue_text(text: &str) -> Option<String> {
484    let text = text.trim_matches('\n').to_owned();
485    (!text.trim().is_empty() && text.len() <= MAX_TEXT_CONTENT_BYTES).then_some(text)
486}
487
488/// Decodes WebVTT's named and numeric character references; unknown ones stay as written.
489///
490/// A reference is letters, digits, `#` and `+` closed by `;`, so each `&` looks only that
491/// far and the text is read in linear time.
492fn decode_references(text: &str) -> String {
493    let mut output = String::with_capacity(text.len());
494    let mut rest = text;
495    while let Some(start) = rest.find('&') {
496        output.push_str(&rest[..start]);
497        rest = &rest[start + 1..];
498        let length = rest
499            .bytes()
500            .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'#' | b'+'))
501            .count();
502        let decoded = (rest.as_bytes().get(length) == Some(&b';'))
503            .then(|| reference(&rest[..length]))
504            .flatten();
505        match decoded {
506            Some(character) => {
507                output.push(character);
508                rest = &rest[length + 1..];
509            }
510            None => output.push('&'),
511        }
512    }
513    output.push_str(rest);
514    output
515}
516
517/// The character a reference's name, between `&` and `;`, stands for.
518fn reference(name: &str) -> Option<char> {
519    match name {
520        "amp" => Some('&'),
521        "lt" => Some('<'),
522        "gt" => Some('>'),
523        "nbsp" => Some('\u{a0}'),
524        "lrm" => Some('\u{200e}'),
525        "rlm" => Some('\u{200f}'),
526        _ => name
527            .strip_prefix("#x")
528            .or_else(|| name.strip_prefix("#X"))
529            .and_then(|hex| u32::from_str_radix(hex, 16).ok())
530            .or_else(|| name.strip_prefix('#').and_then(|dec| dec.parse().ok()))
531            .and_then(char::from_u32),
532    }
533}
534
535/// A cue's text and what its markup says: its speaker, its runs when any carries a class or a
536/// time (else the plain text stands), and what was dropped.
537struct Marked {
538    text: String,
539    speaker: Option<String>,
540    runs: Option<Vec<TextRun>>,
541    notes: ImportNotes,
542}
543
544/// The `<b>`, `<i>` and `<u>` tags open around a piece of text (WebVTT, "Applying CSS
545/// properties to WebVTT Node Objects": bold, italic, underline; SRT alike).
546#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
547struct Emphasis {
548    bold: bool,
549    italic: bool,
550    underline: bool,
551}
552
553impl Emphasis {
554    fn of<'n>(names: impl IntoIterator<Item = &'n str>) -> Self {
555        let mut emphasis = Self::default();
556        for name in names {
557            match name {
558                "b" => emphasis.bold = true,
559                "i" => emphasis.italic = true,
560                "u" => emphasis.underline = true,
561                _ => {}
562            }
563        }
564        emphasis
565    }
566
567    fn of_open(open: &[String]) -> Self {
568        Self::of(open.iter().map(String::as_str))
569    }
570
571    fn style(self) -> Option<crate::TextRunStyle> {
572        (self != Self::default()).then(|| crate::TextRunStyle {
573            font_weight: self.bold.then_some(700),
574            font_style: self.italic.then_some(crate::FontStyle::Italic),
575            underline: self.underline.then_some(true),
576            ..crate::TextRunStyle::default()
577        })
578    }
579}
580
581/// Builds a cue's text and runs from text pieces, each with its open classes and time segment.
582/// Markup stops being tracked (the cue is imported as plain text) past [`MAX_TEXT_RUNS`] pieces
583/// beyond what trimming can remove.
584struct Runs {
585    text: String,
586    pieces: Vec<(String, Vec<String>, usize, Emphasis)>,
587    tracking: bool,
588    notes: ImportNotes,
589}
590
591impl Runs {
592    fn new() -> Self {
593        Self {
594            text: String::new(),
595            pieces: Vec::new(),
596            tracking: true,
597            notes: ImportNotes::default(),
598        }
599    }
600
601    /// Stops tracking markup: the cue is imported as plain text.
602    fn flatten(&mut self) {
603        if self.tracking {
604            self.tracking = false;
605            self.pieces = Vec::new();
606            self.notes.flattened += 1;
607        }
608    }
609
610    fn push(&mut self, text: &str, classes: &[String], segment: usize, emphasis: Emphasis) {
611        self.text.push_str(text);
612        if !self.tracking {
613            return;
614        }
615        // Leading line feeds are trimmed from the runs as `cue_text` trims them from the text.
616        let text = if self.pieces.is_empty() {
617            text.trim_start_matches('\n')
618        } else {
619            text
620        };
621        if text.is_empty() {
622            return;
623        }
624        match self.pieces.last_mut() {
625            Some((held, open, at, emphasized))
626                if open.as_slice() == classes && *at == segment && *emphasized == emphasis =>
627            {
628                held.push_str(text);
629            }
630            _ => {
631                // Two more than the limit: trailing line feeds can still remove one.
632                if self.pieces.len() > MAX_TEXT_RUNS + 1 {
633                    self.flatten();
634                    return;
635                }
636                self.pieces
637                    .push((text.to_owned(), classes.to_vec(), segment, emphasis));
638            }
639        }
640    }
641
642    /// The text and runs, timed by `bounds` (each segment's start, then the end, in ticks from
643    /// the cue's start), with trailing line feeds trimmed as for plain cue text. No runs when
644    /// none carries a class or a time.
645    fn finish(mut self, speaker: Option<String>, bounds: &[i64]) -> Marked {
646        while let Some(last) = self.pieces.last_mut() {
647            let kept = last.0.trim_end_matches('\n').len();
648            last.0.truncate(kept);
649            if last.0.is_empty() {
650                self.pieces.pop();
651            } else {
652                break;
653            }
654        }
655        if self.pieces.len() > MAX_TEXT_RUNS {
656            self.flatten();
657        }
658        let timed = bounds.len() > 2;
659        let runs = (self.tracking
660            && (timed
661                || self
662                    .pieces
663                    .iter()
664                    .any(|(_, classes, ..)| !classes.is_empty())))
665        .then(|| {
666            self.pieces
667                .into_iter()
668                .map(|(text, mut class, segment, emphasis)| {
669                    if class.len() > MAX_RUN_CLASSES {
670                        self.notes.dropped_classes += class.len() - MAX_RUN_CLASSES;
671                        class.truncate(MAX_RUN_CLASSES);
672                    }
673                    TextRun {
674                        text,
675                        class,
676                        time: timed.then(|| RunTime {
677                            start: MediaTime(bounds[segment]),
678                            end: MediaTime(bounds[segment + 1]),
679                        }),
680                        style: emphasis.style(),
681                    }
682                })
683                .collect()
684        });
685        Marked {
686            text: self.text,
687            speaker,
688            runs,
689            notes: self.notes,
690        }
691    }
692}
693
694/// The classes a tag's dot-separated `names` give; ones a run cannot carry are counted and
695/// dropped.
696fn tag_classes(names: &str, notes: &mut ImportNotes) -> Vec<String> {
697    names
698        .split('.')
699        .filter(|name| !name.is_empty())
700        .filter_map(|name| {
701            if valid_class_name(name) {
702                Some(name.to_owned())
703            } else {
704                notes.dropped_classes += 1;
705                None
706            }
707        })
708        .collect()
709}
710
711/// A WebVTT cue body's text and markup for a cue over `range`: voices, classes, bold, italic and
712/// underline as run classes and styles, and inline timestamps splitting the runs. A `<` with no
713/// `>` after it ends the cue text, as the WebVTT cue text tokenizer does. Linear in the body:
714/// each open tag records how many classes it added, and closing it truncates them.
715fn vtt_markup(body: &str, range: TimeRange) -> Marked {
716    let start = range.start().ticks();
717    let duration = range.duration().map_or(0, MediaTime::ticks);
718    let mut runs = Runs::new();
719    let mut speaker = None;
720    // The tags open, each with the length of `classes` before it opened, innermost last.
721    let mut open: Vec<(&str, usize)> = Vec::new();
722    // The distinct classes the open tags give, in order.
723    let mut classes: Vec<String> = Vec::new();
724    let mut bounds = vec![0_i64];
725    let mut rest = body;
726    loop {
727        let emphasis = Emphasis::of(open.iter().map(|(name, _)| *name));
728        let Some(at) = rest.find('<') else {
729            runs.push(
730                &decode_references(rest),
731                &classes,
732                bounds.len() - 1,
733                emphasis,
734            );
735            break;
736        };
737        runs.push(
738            &decode_references(&rest[..at]),
739            &classes,
740            bounds.len() - 1,
741            emphasis,
742        );
743        let Some(end) = rest[at..].find('>') else {
744            break;
745        };
746        let tag = &rest[at + 1..at + end];
747        rest = &rest[at + end + 1..];
748        if let Some(name) = tag.strip_prefix('/') {
749            let name = name.trim();
750            if let Some(index) = open.iter().rposition(|(open, _)| *open == name) {
751                classes.truncate(open[index].1);
752                open.truncate(index);
753            }
754            continue;
755        }
756        if tag.starts_with(|character: char| character.is_ascii_digit()) {
757            // An inline timestamp: kept only in order and inside the cue.
758            match timestamp(tag.trim()) {
759                Some(time)
760                    if time.ticks() - start > *bounds.last().unwrap_or(&0)
761                        && time.ticks() - start < duration =>
762                {
763                    if runs.tracking {
764                        bounds.push(time.ticks() - start);
765                    }
766                }
767                _ => runs.notes.dropped_timestamps += 1,
768            }
769            continue;
770        }
771        // `name.classes annotation`.
772        let (head, annotation) = tag
773            .split_once([' ', '\t'])
774            .map_or((tag, ""), |(head, annotation)| (head, annotation.trim()));
775        let (name, names) = head.split_once('.').unwrap_or((head, ""));
776        let given = match name {
777            "v" => {
778                if speaker.is_none() && !annotation.is_empty() {
779                    speaker = Some(annotation.to_owned());
780                } else if !annotation.is_empty() {
781                    runs.notes.extra_voices += 1;
782                }
783                let mut given = vec!["voice".to_owned()];
784                given.extend(tag_classes(names, &mut runs.notes));
785                given
786            }
787            "c" => tag_classes(names, &mut runs.notes),
788            "b" | "i" | "u" => {
789                let mut given = vec![name.to_owned()];
790                given.extend(tag_classes(names, &mut runs.notes));
791                given
792            }
793            _ => Vec::new(),
794        };
795        if !runs.tracking {
796            continue;
797        }
798        if open.len() == MAX_OPEN_TAGS {
799            runs.flatten();
800            continue;
801        }
802        open.push((name, classes.len()));
803        for class in given {
804            if !classes.contains(&class) {
805                if classes.len() == MAX_HELD_CLASSES {
806                    runs.flatten();
807                    break;
808                }
809                classes.push(class);
810            }
811        }
812    }
813    bounds.push(duration);
814    let speaker = speaker.filter(|speaker| speaker.len() <= crate::MAX_CAPTION_NAME_BYTES);
815    runs.finish(speaker, &bounds)
816}
817
818/// An SRT cue body's markup: `<b>`, `<i>` and `<u>` as run classes and styles; other tags and
819/// override blocks dropped.
820fn srt_markup(body: &[&str]) -> Marked {
821    let mut runs = Runs::new();
822    let mut open: Vec<String> = Vec::new();
823    for (index, line) in body.iter().enumerate() {
824        if index > 0 {
825            runs.push("\n", &open, 0, Emphasis::of_open(&open));
826        }
827        let line = strip_overrides(line);
828        let mut rest = line.as_str();
829        while let Some(start) = rest.find('<') {
830            runs.push(&rest[..start], &open, 0, Emphasis::of_open(&open));
831            let tag = &rest[start + 1..];
832            let closing = tag.starts_with('/');
833            let name = tag.strip_prefix('/').unwrap_or(tag);
834            match tag.find(['<', '>']) {
835                Some(end)
836                    if tag.as_bytes()[end] == b'>'
837                        && name.starts_with(|character: char| character.is_ascii_alphabetic()) =>
838                {
839                    let tag_name = name[..name.len().min(end - usize::from(closing))]
840                        .split([' ', '\t'])
841                        .next()
842                        .unwrap_or_default()
843                        .to_ascii_lowercase();
844                    if matches!(tag_name.as_str(), "b" | "i" | "u") {
845                        if closing {
846                            if let Some(index) = open.iter().rposition(|open| *open == tag_name) {
847                                open.remove(index);
848                            }
849                        } else if !open.contains(&tag_name) {
850                            open.push(tag_name);
851                        }
852                    }
853                    rest = &tag[end + 1..];
854                }
855                _ => {
856                    runs.push("<", &open, 0, Emphasis::of_open(&open));
857                    rest = tag;
858                }
859            }
860        }
861        runs.push(rest, &open, 0, Emphasis::of_open(&open));
862    }
863    runs.finish(None, &[0, 0])
864}
865
866/// SRT text without its `{\...}` override blocks.
867fn strip_overrides(line: &str) -> String {
868    let mut output = String::with_capacity(line.len());
869    let mut rest = line;
870    while let Some(start) = rest.find("{\\") {
871        output.push_str(&rest[..start]);
872        match rest[start..].find('}') {
873            Some(end) => rest = &rest[start + end + 1..],
874            None => {
875                rest = "";
876            }
877        }
878    }
879    output.push_str(rest);
880    output
881}
882
883#[cfg(test)]
884#[path = "caption_import_tests.rs"]
885mod tests;