diff --git a/crates/ec-subs/src/markup.rs b/crates/ec-subs/src/markup.rs index 9ee5af6a..02d355e2 100644 --- a/crates/ec-subs/src/markup.rs +++ b/crates/ec-subs/src/markup.rs @@ -86,70 +86,119 @@ pub fn parse_clock(field: &str) -> Option { /// quadratic to close or the tree too deep to walk. const MAX_NEST: usize = 64; -/// One cue body's markup as runs. `webvtt` turns on the two tags only WebVTT +/// Which markup a cue body is written in. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Dialect { + Srt, + WebVtt, +} + +/// The cue being built: its top-level runs, and the open tags above them, innermost last. +#[derive(Default)] +struct Tree { + root: Vec, + open: Vec<(Open, Vec)>, +} + +impl Tree { + fn top(&mut self) -> &mut Vec { + match self.open.last_mut() { + Some((_, children)) => children, + None => &mut self.root, + } + } + + fn close_top(&mut self) { + let Some((open, children)) = self.open.pop() else { + return; + }; + let parent = self.top(); + match open.name.as_str() { + "b" => parent.push(Segment::Bold(children)), + "i" => parent.push(Segment::Italic(children)), + "u" => parent.push(Segment::Underline(children)), + "s" => parent.push(Segment::Strike(children)), + "v" => parent.push(Segment::Voice { + name: open.annotation, + children, + }), + "c" => parent.push(Segment::Class { + name: open.annotation, + children, + }), + _ => { + if let Some(rgb) = open.color { + parent.push(Segment::Color { rgb, children }); + } else if open.family.is_some() || open.size.is_some() { + parent.push(Segment::Font { + family: open.family, + size: open.size, + children, + }); + } else { + parent.extend(children); + } + } + } + } +} + +/// One cue body's markup as runs. `WebVtt` turns on the two tags only WebVTT /// has — `` and `` — and the inline timestamps that go with them. -pub(crate) fn parse_inline(body: &str, webvtt: bool) -> Vec { - // A stack of open tags, each with the children collected inside it so far; - // the bottom frame is the cue itself and can never be popped. - let mut stack: Vec<(Option, Vec)> = vec![(None, Vec::new())]; +pub(crate) fn parse_inline(body: &str, dialect: Dialect) -> Vec { + let mut tree = Tree::default(); let mut text = String::new(); let mut rest = body; while let Some(at) = rest.find('<') { text.push_str(&unescape(&rest[..at])); let after = &rest[at + 1..]; let Some(end) = after.find('>') else { - // No closing bracket anywhere: the rest of the cue is text. text.push_str(&unescape(&rest[at..])); rest = ""; break; }; let tag = &after[..end]; rest = &after[end + 1..]; - match classify(tag, webvtt) { + match classify(tag, dialect) { Tag::Text => { text.push('<'); text.push_str(&unescape(tag)); text.push('>'); } Tag::Timestamp(offset_us) => { - flush(&mut text, &mut stack); - push(&mut stack, Segment::Timestamp { offset_us }); + flush(&mut text, &mut tree); + tree.top().push(Segment::Timestamp { offset_us }); } Tag::Raw => { - flush(&mut text, &mut stack); - push(&mut stack, Segment::Raw(format!("<{tag}>"))); + flush(&mut text, &mut tree); + tree.top().push(Segment::Raw(format!("<{tag}>"))); } Tag::Open(open) => { - flush(&mut text, &mut stack); - if stack.len() <= MAX_NEST { - stack.push((Some(open), Vec::new())); + flush(&mut text, &mut tree); + if tree.open.len() < MAX_NEST { + tree.open.push((open, Vec::new())); } } Tag::Close(name) => { - flush(&mut text, &mut stack); + flush(&mut text, &mut tree); // Close the innermost frame with that name, and everything // inside it: `` closes both, which is what a browser // does with the same bytes. - let found = stack - .iter() - .rposition(|(open, _)| open.as_ref().is_some_and(|o| o.name == name)); + let found = tree.open.iter().rposition(|(open, _)| open.name == name); if let Some(depth) = found { - while stack.len() > depth { - close_top(&mut stack); + while tree.open.len() > depth { + tree.close_top(); } } } } } text.push_str(&unescape(rest)); - flush(&mut text, &mut stack); - while stack.len() > 1 { - close_top(&mut stack); + flush(&mut text, &mut tree); + while !tree.open.is_empty() { + tree.close_top(); } - stack - .pop() - .map(|(_, children)| children) - .unwrap_or_default() + tree.root } /// An open tag: its name and the arguments the closing wrapper will need. @@ -170,7 +219,7 @@ enum Tag { Text, } -fn classify(tag: &str, webvtt: bool) -> Tag { +fn classify(tag: &str, dialect: Dialect) -> Tag { let trimmed = tag.trim(); if trimmed.is_empty() { return Tag::Text; @@ -181,7 +230,7 @@ fn classify(tag: &str, webvtt: bool) -> Tag { return Tag::Close(name); } // `<00:00:01.500>` is a cue timestamp, not an element. - if webvtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) { + if dialect == Dialect::WebVtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) { return match parse_clock(trimmed) { Some(offset_us) => Tag::Timestamp(offset_us), None => Tag::Text, @@ -211,7 +260,7 @@ fn classify(tag: &str, webvtt: bool) -> Tag { size: attribute(attrs, "size").and_then(|v| v.trim().parse().ok()), annotation: String::new(), }), - "v" | "c" if webvtt => Tag::Open(Open { + "v" | "c" if dialect == Dialect::WebVtt => Tag::Open(Open { annotation: match name.as_str() { "v" => attrs.trim().to_owned(), _ => classes.replace('.', " "), @@ -350,22 +399,17 @@ fn unescape(text: &str) -> String { out } -fn flush(text: &mut String, stack: &mut [(Option, Vec)]) { +fn flush(text: &mut String, tree: &mut Tree) { if !text.is_empty() { let taken = std::mem::take(text); - // A newline inside a cue body is a line break, not whitespace. let mut lines = taken.split('\n'); if let Some(first) = lines.next() && !first.is_empty() { - stack - .last_mut() - .unwrap() - .1 - .push(Segment::Text(first.into())); + tree.top().push(Segment::Text(first.into())); } for line in lines { - let children = &mut stack.last_mut().unwrap().1; + let children = tree.top(); children.push(Segment::LineBreak); if !line.is_empty() { children.push(Segment::Text(line.into())); @@ -374,48 +418,6 @@ fn flush(text: &mut String, stack: &mut [(Option, Vec)]) { } } -fn push(stack: &mut [(Option, Vec)], segment: Segment) { - stack.last_mut().unwrap().1.push(segment); -} - -fn close_top(stack: &mut Vec<(Option, Vec)>) { - let Some((open, children)) = stack.pop() else { - return; - }; - let Some(open) = open else { return }; - let parent = &mut stack.last_mut().unwrap().1; - match open.name.as_str() { - "b" => parent.push(Segment::Bold(children)), - "i" => parent.push(Segment::Italic(children)), - "u" => parent.push(Segment::Underline(children)), - "s" => parent.push(Segment::Strike(children)), - "v" => parent.push(Segment::Voice { - name: open.annotation, - children, - }), - "c" => parent.push(Segment::Class { - name: open.annotation, - children, - }), - // ``: whichever of colour and face/size it stated. One that - // stated neither is a frame with nothing to say, so it is unwrapped - // rather than kept as an empty node. - _ => { - if let Some(rgb) = open.color { - parent.push(Segment::Color { rgb, children }); - } else if open.family.is_some() || open.size.is_some() { - parent.push(Segment::Font { - family: open.family, - size: open.size, - children, - }); - } else { - parent.extend(children); - } - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -446,33 +448,33 @@ mod tests { #[test] fn markup_nests_and_forgives() { - let segments = parse_inline("a b", false); + let segments = parse_inline("a b", Dialect::Srt); assert_eq!(plain_text(&segments), "a b"); assert!(matches!(segments[0], Segment::Italic(_))); assert!(matches!(segments[2], Segment::Bold(_))); // Mismatched close, stray close, and a `<` that is just a `<`. - assert_eq!(plain_text(&parse_inline("xy", false)), "xy"); - assert_eq!(plain_text(&parse_inline("plain", false)), "plain"); - assert_eq!(plain_text(&parse_inline("a < b", false)), "a < b"); + assert_eq!(plain_text(&parse_inline("xy", Dialect::Srt)), "xy"); + assert_eq!(plain_text(&parse_inline("plain", Dialect::Srt)), "plain"); + assert_eq!(plain_text(&parse_inline("a < b", Dialect::Srt)), "a < b"); assert_eq!( - plain_text(&parse_inline("2 < 3 & 4", false)), + plain_text(&parse_inline("2 < 3 & 4", Dialect::Srt)), "2 < 3 & 4" ); } #[test] fn webvtt_only_tags_are_off_for_srt() { - let vtt = parse_inline("hi", true); + let vtt = parse_inline("hi", Dialect::WebVtt); assert!(matches!(vtt[0], Segment::Voice { .. })); assert_eq!(plain_text(&vtt), "hi"); - let srt = parse_inline("hi", false); + let srt = parse_inline("hi", Dialect::Srt); assert_eq!(plain_text(&srt), "hi"); assert!(matches!(srt[0], Segment::Raw(_))); } #[test] fn font_colour_is_read_by_hex_and_by_name() { - let segments = parse_inline("red", false); + let segments = parse_inline("red", Dialect::Srt); assert!(matches!( segments[0], Segment::Color { @@ -480,7 +482,7 @@ mod tests { .. } )); - let named = parse_inline("green", false); + let named = parse_inline("green", Dialect::Srt); assert!(matches!( named[0], Segment::Color { diff --git a/crates/ec-subs/src/srt.rs b/crates/ec-subs/src/srt.rs index 432675ba..6001c996 100644 --- a/crates/ec-subs/src/srt.rs +++ b/crates/ec-subs/src/srt.rs @@ -10,7 +10,7 @@ use ec_core::{Error, Result}; use crate::ir::{SourceFormat, SubtitleCue, SubtitleTrack}; -use crate::markup::{decode, parse_clock, parse_inline}; +use crate::markup::{decode, parse_clock, parse_inline, Dialect}; /// Parse a SubRip document. /// @@ -40,7 +40,7 @@ pub fn parse(bytes: &[u8]) -> Result { end_us: end_us.max(start_us), style_ref: None, positioning: None, - segments: parse_inline(body.trim_end(), false), + segments: parse_inline(body.trim_end(), Dialect::Srt), }); } if track.cues.is_empty() && text.split_whitespace().next().is_some() { diff --git a/crates/ec-subs/src/webvtt.rs b/crates/ec-subs/src/webvtt.rs index 795392e8..673d9c2d 100644 --- a/crates/ec-subs/src/webvtt.rs +++ b/crates/ec-subs/src/webvtt.rs @@ -9,7 +9,7 @@ use ec_core::{Error, Result}; use crate::ir::{CuePosition, SourceFormat, SubtitleCue, SubtitleTrack, TextAlign}; -use crate::markup::{decode, parse_inline}; +use crate::markup::{decode, parse_inline, Dialect}; use crate::srt::timing; /// Parse a WebVTT document. @@ -57,7 +57,7 @@ pub fn parse(bytes: &[u8]) -> Result { end_us: end_us.max(start_us), style_ref: None, positioning: settings(lines[at]), - segments: parse_inline(body.trim_end(), true), + segments: parse_inline(body.trim_end(), Dialect::WebVtt), }); } if track.cues.is_empty() && text.split_whitespace().next().is_some() {