From 1f445c1f920cf6fce50436d34930dee712776e78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 08:56:07 +0300 Subject: [PATCH] feat(subs): SRT/WebVTT/ASS parsing, PGS bitmaps, oxideav shims MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ec-subs carries the cue IR the family answers with (time range plus styled runs, positioning beside them) and the SubRip and WebVTT parsers over it; ec-ass reads ASS/SSA into the same IR, override tags included; ec-pgs decodes Blu-ray display sets to straight RGBA canvases. Tolerance is the point on the text side: BOM (UTF-8 and UTF-16), CRLF and lone CR, invalid UTF-8, missing or wrong indices, dotted fractions, trailing SubRip coordinates, overlapping and backwards cues all parse; a block that cannot be read is skipped and counted, and only a document with no timing line at all is refused. The PGS decoder holds an epoch across display sets, keeps a partial segment until the rest arrives and drops a torn set rather than the track. shims/oxideav-{core,subtitle,ass,sub-image} carry the incumbent package names and versions and cover exactly the surface the replica consumes, so the swap is a [patch.crates-io] line. The replica's own call shapes are transcribed as a test, which is what proves the swap rather than the crates' own suites. Checks: 34 tests green (unit plus real streams extracted from the library by scripts/gen-subtitle-fixtures.sh); the first painted display set of a 1080p PGS track agrees with ffmpeg's own render of the same set — same bounding box within two pixels, every reference ink pixel painted, colours within 1/255. --- crates/ec-ass/Cargo.toml | 11 + crates/ec-ass/src/lib.rs | 562 +++++++++++++++++ crates/ec-pgs/Cargo.toml | 10 + crates/ec-pgs/src/lib.rs | 578 ++++++++++++++++++ crates/ec-subs/Cargo.toml | 14 + crates/ec-subs/src/ir.rs | 270 ++++++++ crates/ec-subs/src/lib.rs | 33 + crates/ec-subs/src/markup.rs | 474 ++++++++++++++ crates/ec-subs/src/srt.rs | 131 ++++ crates/ec-subs/src/webvtt.rs | 174 ++++++ crates/ec-subs/tests/real_library.rs | 142 +++++ scripts/gen-subtitle-fixtures.sh | 65 ++ shims/oxideav-ass/Cargo.toml | 13 + shims/oxideav-ass/src/lib.rs | 37 ++ shims/oxideav-core/Cargo.toml | 11 + shims/oxideav-core/src/lib.rs | 484 +++++++++++++++ shims/oxideav-sub-image/Cargo.toml | 16 + shims/oxideav-sub-image/src/lib.rs | 80 +++ .../tests/replica_call_shapes.rs | 157 +++++ shims/oxideav-subtitle/Cargo.toml | 12 + shims/oxideav-subtitle/src/lib.rs | 64 ++ 21 files changed, 3338 insertions(+) create mode 100644 crates/ec-ass/Cargo.toml create mode 100644 crates/ec-ass/src/lib.rs create mode 100644 crates/ec-pgs/Cargo.toml create mode 100644 crates/ec-pgs/src/lib.rs create mode 100644 crates/ec-subs/Cargo.toml create mode 100644 crates/ec-subs/src/ir.rs create mode 100644 crates/ec-subs/src/lib.rs create mode 100644 crates/ec-subs/src/markup.rs create mode 100644 crates/ec-subs/src/srt.rs create mode 100644 crates/ec-subs/src/webvtt.rs create mode 100644 crates/ec-subs/tests/real_library.rs create mode 100755 scripts/gen-subtitle-fixtures.sh create mode 100644 shims/oxideav-ass/Cargo.toml create mode 100644 shims/oxideav-ass/src/lib.rs create mode 100644 shims/oxideav-core/Cargo.toml create mode 100644 shims/oxideav-core/src/lib.rs create mode 100644 shims/oxideav-sub-image/Cargo.toml create mode 100644 shims/oxideav-sub-image/src/lib.rs create mode 100644 shims/oxideav-sub-image/tests/replica_call_shapes.rs create mode 100644 shims/oxideav-subtitle/Cargo.toml create mode 100644 shims/oxideav-subtitle/src/lib.rs diff --git a/crates/ec-ass/Cargo.toml b/crates/ec-ass/Cargo.toml new file mode 100644 index 00000000..e8a1fbf5 --- /dev/null +++ b/crates/ec-ass/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "ec-ass" +description = "Advanced SubStation Alpha (ASS/SSA) parsing into the edith_codecs subtitle IR." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true +ec-subs = { path = "../ec-subs", version = "0.1.0" } diff --git a/crates/ec-ass/src/lib.rs b/crates/ec-ass/src/lib.rs new file mode 100644 index 00000000..a5149fd1 --- /dev/null +++ b/crates/ec-ass/src/lib.rs @@ -0,0 +1,562 @@ +//! Advanced SubStation Alpha, and the SSA v4 it grew out of. +//! +//! An `.ass` is an INI: `[Script Info]` keys, a `[V4+ Styles]` table and an +//! `[Events]` table, each table declaring its own column order on a `Format:` +//! line. That declaration is why this parses the header rather than assuming +//! positions — Aegisub's order is the usual one, but the file gets to say. +//! +//! The cue text carries override tags in braces: `{\i1}` turns italics on until +//! `{\i0}`, `{\an8}` puts the line at the top, `{\pos(x,y)}` puts it exactly, +//! `{\k30}` is a karaoke beat, and `{\p1}` switches the *text* to vector +//! drawing commands until `{\p0}`. Those become [`ec_subs::Segment`] runs, so +//! a caller that wants words ([`ec_subs::plain_text`]) gets words and a caller +//! that will one day draw them has the tree. +//! +//! What the format states and this drops on the floor: transforms, animation, +//! clipping and every other override that only a renderer can honour. They are +//! kept verbatim as [`ec_subs::Segment::Raw`] rather than deleted. + +#![forbid(unsafe_code)] + +use ec_core::{Error, Result}; +use ec_subs::ir::{ + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, +}; +use ec_subs::{decode, parse_clock}; + +/// Parse an ASS or SSA document. +/// +/// `Err` only when there is no `Dialogue:` line and no `[Events]` section in +/// the whole document — that is not this format. Torn rows are skipped and +/// counted in [`SubtitleTrack::skipped`], because one bad line in a +/// twelve-hundred-line script is not a reason to lose the other eleven hundred. +pub fn parse(bytes: &[u8]) -> Result { + let text = decode(bytes); + let mut track = SubtitleTrack::new().with_source(SourceFormat::AssOrSsa); + let mut section = Section::None; + let mut style_format: Vec = Vec::new(); + let mut event_format: Vec = Vec::new(); + let mut header_end = 0; + let mut in_events = false; + let mut saw_events = false; + for line in text.split_inclusive('\n') { + let trimmed = line.trim(); + // Everything up to the first event row is the script header — what a + // Matroska track carries as `CodecPrivate`. + if trimmed.starts_with("Dialogue:") || trimmed.starts_with("Comment:") { + in_events = true; + } else if !in_events { + header_end += line.len(); + } + if trimmed.is_empty() || trimmed.starts_with(';') || trimmed.starts_with('!') { + continue; + } + if let Some(name) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { + section = Section::of(name); + saw_events |= matches!(section, Section::Events); + continue; + } + let Some((key, value)) = trimmed.split_once(':') else { + continue; + }; + let value = value.trim(); + match (section, key.trim()) { + (Section::ScriptInfo, key) => { + track.metadata.push((snake_case(key), value.to_owned())); + } + (Section::Styles { .. }, "Format") => style_format = fields(value), + (Section::Styles { v4 }, "Style") => match style(&style_format, value, v4) { + Some(style) => track.styles.push(style), + None => track.skipped += 1, + }, + (Section::Events, "Format") => event_format = fields(value), + (Section::Events, "Dialogue") => { + let wrap_style = track + .metadata + .iter() + .find(|(k, _)| k == "wrap_style") + .and_then(|(_, v)| v.parse::().ok()) + .unwrap_or(0); + match dialogue(&event_format, value, wrap_style) { + Some(cue) => track.cues.push(cue), + None => track.skipped += 1, + } + } + // `Comment:` events are the script's own scratch lines: real rows + // of the events table, never on screen. + _ => {} + } + } + if track.cues.is_empty() && !saw_events { + return Err(Error::corrupt( + "no [Events] section: not an ASS or SSA script", + )); + } + track.extradata = text.as_bytes()[..header_end.min(text.len())].to_vec(); + Ok(track) +} + +#[derive(Clone, Copy)] +enum Section { + None, + ScriptInfo, + /// `v4` marks the SSA-era table, whose alignment codes differ. + Styles { + v4: bool, + }, + Events, +} + +impl Section { + fn of(name: &str) -> Section { + let lower = name.trim().to_ascii_lowercase(); + match lower.as_str() { + "script info" => Section::ScriptInfo, + "events" => Section::Events, + "v4 styles" => Section::Styles { v4: true }, + _ if lower.ends_with("styles") => Section::Styles { v4: false }, + _ => Section::None, + } + } +} + +/// `PlayResX` → `play_res_x`, `Original Script` → `original_script`: metadata +/// keys are one shape whichever way the script wrote them. +fn snake_case(key: &str) -> String { + let mut out = String::with_capacity(key.len() + 4); + let mut previous = ' '; + for c in key.trim().chars() { + match c { + ' ' | '-' => out.push('_'), + c => { + if c.is_ascii_uppercase() + && (previous.is_ascii_lowercase() || previous.is_ascii_digit()) + { + out.push('_'); + } + out.push(c.to_ascii_lowercase()); + } + } + previous = c; + } + out +} + +fn fields(value: &str) -> Vec { + value.split(',').map(|f| f.trim().to_owned()).collect() +} + +/// Column `name` of a row, by the order the table's `Format:` line declared. +fn column<'a>(format: &[String], values: &'a [&'a str], name: &str) -> Option<&'a str> { + let at = format.iter().position(|f| f.eq_ignore_ascii_case(name))?; + values.get(at).map(|v| v.trim()) +} + +fn style(format: &[String], row: &str, v4: bool) -> Option { + // A table with no `Format:` line at all uses the order every tool writes. + const DEFAULT: &str = "Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,\ + BackColour,Bold,Italic,Underline,StrikeOut,ScaleX,ScaleY,Spacing,Angle,BorderStyle,\ + Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding"; + let fallback = fields(DEFAULT); + let format = if format.is_empty() { &fallback } else { format }; + let values: Vec<&str> = row.split(',').collect(); + let name = column(format, &values, "Name")?; + let number = |key: &str| column(format, &values, key).and_then(|v| v.parse::().ok()); + let margin = |key: &str| column(format, &values, key).and_then(|v| v.parse::().ok()); + let flag = |key: &str| column(format, &values, key).is_some_and(|v| v.trim() != "0"); + Some(SubtitleStyle { + name: name.to_owned(), + font_family: column(format, &values, "Fontname").map(str::to_owned), + font_size: number("Fontsize"), + primary_color: column(format, &values, "PrimaryColour").and_then(parse_color), + outline_color: column(format, &values, "OutlineColour") + .or_else(|| column(format, &values, "TertiaryColour")) + .and_then(parse_color), + back_color: column(format, &values, "BackColour").and_then(parse_color), + bold: flag("Bold"), + italic: flag("Italic"), + underline: flag("Underline"), + strike: flag("StrikeOut"), + align: column(format, &values, "Alignment") + .and_then(|v| v.parse().ok()) + .map(|code| alignment(code, v4)) + .unwrap_or_default(), + margin_l: margin("MarginL"), + margin_r: margin("MarginR"), + margin_v: margin("MarginV"), + outline: number("Outline"), + shadow: number("Shadow"), + }) +} + +/// ASS alignment is the numeric keypad (`\an`): 1/4/7 left, 2/5/8 centre, +/// 3/6/9 right. SSA v4 used a different code with the same three columns in +/// its low two bits. +fn alignment(code: i32, v4: bool) -> TextAlign { + let column = match v4 { + true => code & 0b11, + false => (code - 1) % 3 + 1, + }; + match column { + 1 => TextAlign::Left, + 2 => TextAlign::Center, + 3 => TextAlign::Right, + _ => TextAlign::default(), + } +} + +/// `&HAABBGGRR&`: BGR with a *transparency* byte, so 0 is opaque. +fn parse_color(value: &str) -> Option<(u8, u8, u8, u8)> { + let digits: String = value + .trim() + .trim_start_matches(['&', 'H', 'h']) + .trim_end_matches('&') + .chars() + .take_while(char::is_ascii_hexdigit) + .collect(); + let packed = u32::from_str_radix(&digits, 16).ok()?; + Some(( + (packed & 0xFF) as u8, + ((packed >> 8) & 0xFF) as u8, + ((packed >> 16) & 0xFF) as u8, + 255 - ((packed >> 24) & 0xFF) as u8, + )) +} + +fn dialogue(format: &[String], row: &str, wrap_style: u8) -> Option { + const DEFAULT: &str = "Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text"; + let fallback = fields(DEFAULT); + let format = if format.is_empty() { &fallback } else { format }; + // `Text` is last and holds commas of its own, so the row is split into + // exactly as many fields as the table declares and no further. + let values: Vec<&str> = row.splitn(format.len(), ',').collect(); + let start_us = parse_clock(column(format, &values, "Start")?)?; + let end_us = parse_clock(column(format, &values, "End")?)?; + let text = column(format, &values, "Text").unwrap_or_default(); + let (segments, positioning) = body(text, wrap_style); + Some(SubtitleCue { + start_us, + end_us: end_us.max(start_us), + style_ref: column(format, &values, "Style") + .filter(|s| !s.is_empty()) + .map(str::to_owned), + positioning, + segments, + }) +} + +/// The state an override block leaves behind for the runs after it. +#[derive(Clone, Default)] +struct Overrides { + bold: bool, + italic: bool, + underline: bool, + strike: bool, + color: Option<(u8, u8, u8)>, + family: Option, + size: Option, + karaoke: Option, + /// `\p1` and up: the text is a drawing, not words. + drawing: bool, +} + +/// One `Text` field into runs, plus whatever positioning its overrides state. +fn body(text: &str, wrap_style: u8) -> (Vec, Option) { + let mut out: Vec = Vec::new(); + let mut state = Overrides::default(); + let mut position = CuePosition::default(); + let mut positioned = false; + let mut run = String::new(); + let mut rest = text; + while let Some(at) = rest.find('{') { + let (before, after) = rest.split_at(at); + push_text(&mut out, &mut run, before, &state, wrap_style); + let Some(end) = after.find('}') else { + // An unbalanced brace: the rest of the line is text, braces and all. + run.push_str(after); + rest = ""; + break; + }; + let block = &after[1..end]; + rest = &after[end + 1..]; + flush(&mut out, &mut run, &state); + if let Some(unknown) = overrides(block, &mut state, &mut position, &mut positioned) { + out.push(Segment::Raw(unknown)); + } + } + push_text(&mut out, &mut run, rest, &state, wrap_style); + flush(&mut out, &mut run, &state); + (out, positioned.then_some(position)) +} + +/// Apply one brace block's overrides. Returns the overrides this does not +/// model, verbatim, for a [`Segment::Raw`]. +fn overrides( + block: &str, + state: &mut Overrides, + position: &mut CuePosition, + positioned: &mut bool, +) -> Option { + let mut unknown = String::new(); + for tag in block.split('\\').skip(1) { + let tag = tag.trim_end(); + if tag.is_empty() { + continue; + } + let Some((name, arg)) = split_tag(tag) else { + unknown.push_str(&format!("\\{tag}")); + continue; + }; + let flag = || !arg.trim().trim_start_matches('0').is_empty(); + match name { + "b" => state.bold = flag(), + "i" => state.italic = flag(), + "u" => state.underline = flag(), + "s" => state.strike = flag(), + "c" | "1c" => state.color = parse_color(arg).map(|(r, g, b, _)| (r, g, b)), + "fn" => state.family = Some(arg.trim().to_owned()).filter(|f| !f.is_empty()), + "fs" => state.size = arg.trim().parse().ok(), + "k" | "K" | "kf" | "ko" => state.karaoke = arg.trim().parse().ok(), + "p" => state.drawing = flag(), + "an" => { + if let Ok(code) = arg.trim().parse::() { + position.align = alignment(code, false); + *positioned = true; + } + } + "a" => { + if let Ok(code) = arg.trim().parse::() { + position.align = alignment(code, true); + *positioned = true; + } + } + "pos" | "move" => { + // `\move(x1,y1,x2,y2,…)` starts where `\pos(x,y)` would put it. + let mut parts = arg + .trim_matches(['(', ')']) + .split(',') + .filter_map(|n| n.trim().parse().ok()); + position.x = parts.next(); + position.y = parts.next(); + *positioned = true; + if name == "move" { + unknown.push_str(&format!("\\{tag}")); + } + } + _ => unknown.push_str(&format!("\\{tag}")), + } + } + (!unknown.is_empty()).then(|| format!("{{{unknown}}}")) +} + +/// An override into its name and its argument. +/// +/// The names overlap — `\b` is bold and `\blur` is a blur — so a one-letter +/// name is only that name when what follows it could be its argument: a +/// number, a `&H` colour, a bracketed list, or nothing at all. Everything else +/// falls through to [`Segment::Raw`] rather than being half-read. +fn split_tag(tag: &str) -> Option<(&str, &str)> { + const NAMES: [&str; 16] = [ + "move", "pos", "fn", "fs", "kf", "ko", "an", "1c", "c", "b", "i", "u", "s", "k", "p", "a", + ]; + NAMES.iter().find_map(|name| { + let arg = tag.strip_prefix(name)?; + // A font name is letters, so `\fn` takes whatever follows it. + let plausible = *name == "fn" + || arg.is_empty() + || arg.starts_with(|c: char| c.is_ascii_digit() || matches!(c, '-' | '&' | '(' | '.')); + plausible.then_some((*name, arg)) + }) +} + +/// Plain text between override blocks, with the three escapes ASS gives it. +fn push_text( + out: &mut Vec, + run: &mut String, + text: &str, + state: &Overrides, + wrap_style: u8, +) { + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + run.push(c); + continue; + } + match chars.next() { + // `\N` always breaks; `\n` breaks only where the script asked for + // no automatic wrapping (`WrapStyle: 2`), and is a space otherwise, + // which is what every renderer does with it. + Some('N') => { + flush(out, run, state); + out.push(Segment::LineBreak); + } + Some('n') if wrap_style == 2 => { + flush(out, run, state); + out.push(Segment::LineBreak); + } + Some('n') => run.push(' '), + Some('h') => run.push('\u{a0}'), + Some(other) => { + run.push('\\'); + run.push(other); + } + None => run.push('\\'), + } + } +} + +/// Close the pending run, wrapping it in whatever the overrides asked for. +fn flush(out: &mut Vec, run: &mut String, state: &Overrides) { + if run.is_empty() { + return; + } + let text = std::mem::take(run); + // A drawing is shapes, not words: kept whole so a renderer can have it and + // `plain_text` says nothing. + if state.drawing { + out.push(Segment::Raw(text)); + return; + } + let mut segment = vec![Segment::Text(text)]; + if let Some(cs) = state.karaoke { + segment = vec![Segment::Karaoke { + cs, + children: segment, + }]; + } + if state.family.is_some() || state.size.is_some() { + segment = vec![Segment::Font { + family: state.family.clone(), + size: state.size, + children: segment, + }]; + } + if let Some(rgb) = state.color { + segment = vec![Segment::Color { + rgb, + children: segment, + }]; + } + for (on, wrap) in [ + (state.strike, Segment::Strike as fn(Vec) -> Segment), + (state.underline, Segment::Underline as fn(_) -> _), + (state.italic, Segment::Italic as fn(_) -> _), + (state.bold, Segment::Bold as fn(_) -> _), + ] { + if on { + segment = vec![wrap(segment)]; + } + } + out.extend(segment); +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_subs::plain_text; + + const SCRIPT: &str = "[Script Info]\n\ + Title: A script\n\ + WrapStyle: 0\n\ + PlayResX: 1920\n\ + \n\ + [V4+ Styles]\n\ + Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, \ + Underline, StrikeOut, Alignment, MarginL, MarginR, MarginV, Outline, Shadow, Encoding\n\ + Style: Default,Arial,48,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,2,10,10,20,2,1,1\n\ + \n\ + [Events]\n\ + Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\ + Dialogue: 0,0:00:01.00,0:00:03.50,Default,,0,0,0,,{\\i1}tilted{\\i0} plain\\Nsecond, with comma\n\ + Comment: 0,0:00:04.00,0:00:05.00,Default,,0,0,0,,not on screen\n\ + Dialogue: 0,0:00:06.00,0:00:07.00,Default,,0,0,0,,{\\an8\\pos(960,100)}up top\n"; + + #[test] + fn a_script_parses_header_styles_and_events() { + let track = parse(SCRIPT.as_bytes()).unwrap(); + assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); + assert_eq!( + track.metadata.iter().find(|(k, _)| k == "title").unwrap().1, + "A script" + ); + let style = track.style("Default").unwrap(); + assert_eq!(style.font_family.as_deref(), Some("Arial")); + assert_eq!(style.font_size, Some(48.0)); + assert!(style.bold && !style.italic); + assert_eq!(style.primary_color, Some((255, 255, 255, 255))); + // `&H80000000` is half transparent, and BGR order means blue is zero. + assert_eq!(style.back_color, Some((0, 0, 0, 127))); + assert_eq!(style.align, TextAlign::Center); + + // The `Comment:` row is not a cue. + assert_eq!(track.cues.len(), 2); + let cue = &track.cues[0]; + assert_eq!((cue.start_us, cue.end_us), (1_000_000, 3_500_000)); + assert_eq!(cue.style_ref.as_deref(), Some("Default")); + // The text field keeps its own commas. + assert_eq!( + plain_text(&cue.segments), + "tilted plain\nsecond, with comma" + ); + assert!(matches!(cue.segments[0], Segment::Italic(_))); + assert_eq!(track.skipped, 0); + // The header is what a Matroska `CodecPrivate` carries. + assert!(track.extradata.starts_with(b"[Script Info]")); + assert!(!track.extradata.windows(9).any(|w| w == b"Dialogue:")); + } + + #[test] + fn positioning_overrides_reach_the_cue() { + let track = parse(SCRIPT.as_bytes()).unwrap(); + let position = track.cues[1].positioning.unwrap(); + assert_eq!(position.align, TextAlign::Center); + assert_eq!((position.x, position.y), (Some(960.0), Some(100.0))); + assert_eq!(plain_text(&track.cues[1].segments), "up top"); + } + + #[test] + fn karaoke_drawings_and_unknown_tags() { + let doc = "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ + Dialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{\\k30}ka{\\k25}ra\n\ + Dialogue: 0,0:00:01.00,0:00:02.00,,,0,0,0,,{\\p1}m 0 0 l 10 10{\\p0}words\n\ + Dialogue: 0,0:00:02.00,0:00:03.00,,,0,0,0,,{\\t(0,500,\\fscx120)}moving\n"; + let track = parse(doc.as_bytes()).unwrap(); + assert_eq!(plain_text(&track.cues[0].segments), "kara"); + assert!(matches!( + track.cues[0].segments[0], + Segment::Karaoke { cs: 30, .. } + )); + // Drawing commands are not words. + assert_eq!(plain_text(&track.cues[1].segments), "words"); + // An override this does not model survives as itself. + assert_eq!(plain_text(&track.cues[2].segments), "moving"); + assert!( + track.cues[2] + .segments + .iter() + .any(|s| matches!(s, Segment::Raw(r) if r.contains("fscx120"))) + ); + } + + #[test] + fn tolerances_and_the_refusal() { + // No `Format:` line, CRLF, a torn row, and `\h` / `\n`. + let doc = b"\xef\xbb\xbf[Events]\r\n\ + Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,a\\hb\\nc\r\n\ + Dialogue: not a row\r\n"; + let track = parse(doc).unwrap(); + assert_eq!(track.cues.len(), 1); + assert_eq!(track.skipped, 1); + assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b c"); + // `WrapStyle: 2` makes `\n` a break instead. + let wrapped = format!( + "[Script Info]\nWrapStyle: 2\n{}", + String::from_utf8_lossy(&doc[3..]) + ); + let track = parse(wrapped.as_bytes()).unwrap(); + assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b\nc"); + + assert!(parse(b"just some prose").is_err()); + } +} diff --git a/crates/ec-pgs/Cargo.toml b/crates/ec-pgs/Cargo.toml new file mode 100644 index 00000000..9a886c18 --- /dev/null +++ b/crates/ec-pgs/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-pgs" +description = "Blu-ray Presentation Graphic Stream (PGS/SUP) subtitle bitmap decoding." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-pgs/src/lib.rs b/crates/ec-pgs/src/lib.rs new file mode 100644 index 00000000..4093cfb5 --- /dev/null +++ b/crates/ec-pgs/src/lib.rs @@ -0,0 +1,578 @@ +//! Blu-ray Presentation Graphic Stream: the subtitles that are *pictures*. +//! +//! A PGS stream is a sequence of display sets, each a handful of segments: a +//! presentation composition (PCS — the canvas and where the objects go on it), a +//! window definition (WDS), a palette (PDS), one or more run-length objects +//! (ODS) and an end marker (END). A set is decoded against the state the sets +//! before it left behind, which is why this is a decoder with an epoch and not +//! a function: an acquisition point re-states everything, a normal-case set may +//! re-use an object or merely swap the palette. +//! +//! What comes out is one straight-alpha RGBA frame per display set, the size of +//! the composition's own canvas (1920×1080 off a disc), transparent everywhere +//! the cue paints nothing. That is the shape a compositor wants and the shape +//! `.sup` tooling shows: a caller lays the whole canvas over the film rather +//! than placing a sprite. +//! +//! The framing read here is the `.sup` one — `PG`, two timestamps, type, size — +//! because that is what a `.sup` file holds and what a Matroska block becomes +//! once its header is put back on ([`ec_subs`] is the text half of the same +//! story). Colour is BT.601 limited-range, which is what the palette entries of +//! a disc are and what every other decoder of this format assumes. + +#![forbid(unsafe_code)] + +use std::collections::HashMap; + +use ec_core::{ + CodecId, CodecParameters, Decoder, Error, Frame, PixelFormat, Plane, Result, VideoFrame, +}; + +/// Palette definition segment. +pub const SEG_PDS: u8 = 0x14; +/// Object definition segment: the run-length bitmap itself. +pub const SEG_ODS: u8 = 0x15; +/// Presentation composition segment: canvas size and object placement. +pub const SEG_PCS: u8 = 0x16; +/// Window definition segment. +pub const SEG_WDS: u8 = 0x17; +/// End of display set — the point at which a frame is complete. +pub const SEG_END: u8 = 0x80; + +/// The magic every `.sup` segment starts with. +const MAGIC: [u8; 2] = *b"PG"; +/// Bytes before a segment's body: magic, PTS, DTS, type, size. +const HEADER: usize = 13; + +/// A decoder over a `.sup` byte stream. +/// +/// Feed it whole segments ([`PgsDecoder::push`]) — a partial one is held until +/// the rest arrives, so a caller may split the stream anywhere — and take a +/// frame per display set ([`PgsDecoder::take_frame`]). +pub struct PgsDecoder { + params: CodecParameters, + /// Bytes not yet forming a whole segment. + pending: Vec, + /// Objects by id, decoded run-length data as the stream stated it. + objects: HashMap, + /// The object being assembled out of a multi-segment ODS sequence. + partial: Option<(u16, Object)>, + /// Palettes by id: 256 straight-alpha RGBA entries each. + palettes: HashMap>, + /// Windows by id, for clipping. + windows: HashMap, + /// The composition the current display set is building. + composition: Composition, + /// Frames finished but not yet taken. + ready: Vec, +} + +#[derive(Clone, Default)] +struct Object { + width: u32, + height: u32, + rle: Vec, +} + +#[derive(Clone, Copy, Default)] +struct Rect { + x: u32, + y: u32, + width: u32, + height: u32, +} + +#[derive(Clone, Default)] +struct Composition { + width: u32, + height: u32, + palette_id: u8, + objects: Vec, +} + +#[derive(Clone, Copy)] +struct Placement { + object_id: u16, + window_id: u8, + x: u32, + y: u32, + crop: Option, +} + +impl Default for PgsDecoder { + fn default() -> Self { + PgsDecoder::new() + } +} + +impl PgsDecoder { + /// A decoder with no epoch yet: the first display set states everything. + pub fn new() -> PgsDecoder { + PgsDecoder { + params: CodecParameters::new(CodecId::Pgs), + pending: Vec::new(), + objects: HashMap::new(), + partial: None, + palettes: HashMap::new(), + windows: HashMap::new(), + composition: Composition::default(), + ready: Vec::new(), + } + } + + /// Feed stream bytes. Every complete segment in them is consumed; a partial + /// tail is kept for the next call. + /// + /// A segment whose body is nonsense (a palette entry short, an object + /// claiming more pixels than its bitmap holds) is dropped and the stream + /// carries on: one torn display set out of eleven thousand must not cost + /// the track. + pub fn push(&mut self, bytes: &[u8]) -> Result<()> { + let mut buffer = std::mem::take(&mut self.pending); + buffer.extend_from_slice(bytes); + let mut data: &[u8] = &buffer; + loop { + if data.len() < HEADER { + break; + } + if data[..2] != MAGIC { + // Not a segment boundary at all: resynchronising would invent + // structure, so this is the one hard error. + return Err(Error::corrupt("PGS: segment does not start with `PG`")); + } + let size = u16::from_be_bytes([data[11], data[12]]) as usize; + if data.len() < HEADER + size { + break; + } + let kind = data[10]; + let body = &data[HEADER..HEADER + size]; + self.segment(kind, body); + data = &data[HEADER + size..]; + } + self.pending = data.to_vec(); + Ok(()) + } + + /// The next finished display set, oldest first. + pub fn take_frame(&mut self) -> Option { + match self.ready.is_empty() { + true => None, + false => Some(self.ready.remove(0)), + } + } + + /// One segment against the running state. + fn segment(&mut self, kind: u8, body: &[u8]) { + match kind { + SEG_PCS => self.pcs(body), + SEG_WDS => self.wds(body), + SEG_PDS => self.pds(body), + SEG_ODS => self.ods(body), + SEG_END => { + if let Some(frame) = self.render() { + self.ready.push(frame); + } + } + _ => {} + } + } + + fn pcs(&mut self, body: &[u8]) { + if body.len() < 11 { + return; + } + let composition_state = body[7]; + // Epoch start: nothing from before this point is referenced again. + if composition_state & 0x80 != 0 { + self.objects.clear(); + self.palettes.clear(); + self.windows.clear(); + self.partial = None; + } + let mut composition = Composition { + width: u32::from(u16::from_be_bytes([body[0], body[1]])), + height: u32::from(u16::from_be_bytes([body[2], body[3]])), + palette_id: body[9], + objects: Vec::new(), + }; + let count = body[10] as usize; + let mut at = 11; + for _ in 0..count { + if body.len() < at + 8 { + break; + } + let flags = body[at + 3]; + let cropped = flags & 0x80 != 0; + let placement = Placement { + object_id: u16::from_be_bytes([body[at], body[at + 1]]), + window_id: body[at + 2], + x: u32::from(u16::from_be_bytes([body[at + 4], body[at + 5]])), + y: u32::from(u16::from_be_bytes([body[at + 6], body[at + 7]])), + crop: match cropped && body.len() >= at + 16 { + true => Some(Rect { + x: u32::from(u16::from_be_bytes([body[at + 8], body[at + 9]])), + y: u32::from(u16::from_be_bytes([body[at + 10], body[at + 11]])), + width: u32::from(u16::from_be_bytes([body[at + 12], body[at + 13]])), + height: u32::from(u16::from_be_bytes([body[at + 14], body[at + 15]])), + }), + false => None, + }, + }; + at += if cropped { 16 } else { 8 }; + composition.objects.push(placement); + } + self.composition = composition; + } + + fn wds(&mut self, body: &[u8]) { + let count = body.first().copied().unwrap_or(0) as usize; + for i in 0..count { + let at = 1 + i * 9; + if body.len() < at + 9 { + break; + } + self.windows.insert( + body[at], + Rect { + x: u32::from(u16::from_be_bytes([body[at + 1], body[at + 2]])), + y: u32::from(u16::from_be_bytes([body[at + 3], body[at + 4]])), + width: u32::from(u16::from_be_bytes([body[at + 5], body[at + 6]])), + height: u32::from(u16::from_be_bytes([body[at + 7], body[at + 8]])), + }, + ); + } + } + + fn pds(&mut self, body: &[u8]) { + if body.len() < 2 { + return; + } + // A palette segment *updates* the palette it names: entries it does not + // mention keep whatever the epoch left there. + let palette = self + .palettes + .entry(body[0]) + .or_insert_with(|| Box::new([[0, 0, 0, 0]; 256])); + for entry in body[2..].chunks_exact(5) { + palette[entry[0] as usize] = rgba(entry[1], entry[2], entry[3], entry[4]); + } + } + + fn ods(&mut self, body: &[u8]) { + if body.len() < 4 { + return; + } + let id = u16::from_be_bytes([body[0], body[1]]); + let sequence = body[3]; + if sequence & 0x80 != 0 { + // First (or only) segment of the sequence: the dimensions ride here. + if body.len() < 11 { + return; + } + let object = Object { + width: u32::from(u16::from_be_bytes([body[7], body[8]])), + height: u32::from(u16::from_be_bytes([body[9], body[10]])), + rle: body[11..].to_vec(), + }; + self.partial = Some((id, object)); + } else if let Some((pending_id, object)) = self.partial.as_mut() + && *pending_id == id + { + object.rle.extend_from_slice(&body[4..]); + } + if sequence & 0x40 != 0 + && let Some((id, object)) = self.partial.take() + { + self.objects.insert(id, object); + } + } + + /// The current composition as one RGBA canvas, or `None` when it states no + /// canvas at all (a display set seen before any PCS). + fn render(&mut self) -> Option { + let (width, height) = (self.composition.width, self.composition.height); + if width == 0 || height == 0 { + return None; + } + let stride = width as usize * 4; + let mut canvas = vec![0u8; stride.checked_mul(height as usize)?]; + let palette = self.palettes.get(&self.composition.palette_id); + for placement in &self.composition.objects { + let (Some(object), Some(palette)) = (self.objects.get(&placement.object_id), palette) + else { + continue; + }; + let Some(indices) = decode_rle(&object.rle, object.width, object.height) else { + continue; + }; + // A window clips its objects; a crop takes a rectangle out of the + // object before it is placed. + let window = self.windows.get(&placement.window_id).copied(); + let crop = placement.crop.unwrap_or(Rect { + x: 0, + y: 0, + width: object.width, + height: object.height, + }); + for row in 0..crop.height.min(object.height.saturating_sub(crop.y)) { + let target_y = placement.y + row; + if target_y >= height { + break; + } + for col in 0..crop.width.min(object.width.saturating_sub(crop.x)) { + let target_x = placement.x + col; + if target_x >= width { + break; + } + if let Some(w) = window + && (target_x < w.x + || target_y < w.y + || target_x >= w.x + w.width + || target_y >= w.y + w.height) + { + continue; + } + let index = indices[((crop.y + row) * object.width + crop.x + col) as usize]; + let colour = palette[index as usize]; + // Fully transparent palette entries paint nothing, which is + // what lets two objects share a window. + if colour[3] == 0 { + continue; + } + let at = target_y as usize * stride + target_x as usize * 4; + canvas[at..at + 4].copy_from_slice(&colour); + } + } + } + VideoFrame::try_new( + PixelFormat::Rgba8, + width, + height, + vec![Plane::new(canvas, stride)], + ) + .ok() + } +} + +impl Decoder for PgsDecoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &ec_core::Packet) -> Result<()> { + self.push(&packet.data) + } + + fn receive_frame(&mut self) -> Result { + match self.take_frame() { + Some(frame) => Ok(Frame::Video(frame)), + None => Err(Error::NeedMore), + } + } + + fn flush(&mut self) -> Result<()> { + Ok(()) + } + + fn reset(&mut self) { + let params = self.params.clone(); + *self = PgsDecoder::new(); + self.params = params; + } +} + +/// A PGS decoder as the family's registry hands one out. +pub fn make_decoder(_params: &CodecParameters) -> Result> { + Ok(Box::new(PgsDecoder::new())) +} + +/// One palette entry: BT.601 limited-range Y'CbCr with straight alpha, the way +/// a disc writes it, into RGBA. +fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] { + let y = 298 * (i32::from(y) - 16); + let cb = i32::from(cb) - 128; + let cr = i32::from(cr) - 128; + let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8; + [ + clamp(y + 409 * cr), + clamp(y - 100 * cb - 208 * cr), + clamp(y + 516 * cb), + alpha, + ] +} + +/// The run-length coding of §8.2 of the format: a byte is a pixel of that +/// palette index; a zero byte opens a run whose length and colour follow. +/// +/// `None` for data that does not describe a `width` × `height` bitmap — a +/// truncated object, or one whose rows run past their width. +fn decode_rle(data: &[u8], width: u32, height: u32) -> Option> { + let (width, height) = (width as usize, height as usize); + let mut out = vec![0u8; width.checked_mul(height)?]; + let mut at = 0; + let mut x = 0; + let mut y = 0; + while at < data.len() { + let (colour, run) = match data[at] { + 0 => { + let flags = *data.get(at + 1)?; + match flags { + // A line ends where the encoder says it does, even short. + 0 => { + at += 2; + x = 0; + y += 1; + continue; + } + // 00 0LLLLLL — L pixels of entry 0. + f if f & 0xC0 == 0x00 => { + at += 2; + (0, usize::from(f & 0x3F)) + } + // 00 01LLLLLL LLLLLLLL — 14-bit run of entry 0. + f if f & 0xC0 == 0x40 => { + let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?); + at += 3; + (0, run) + } + // 00 10LLLLLL CC — L pixels of entry CC. + f if f & 0xC0 == 0x80 => { + let colour = *data.get(at + 2)?; + at += 3; + (colour, usize::from(f & 0x3F)) + } + // 00 11LLLLLL LLLLLLLL CC — 14-bit run of entry CC. + f => { + let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?); + let colour = *data.get(at + 3)?; + at += 4; + (colour, run) + } + } + } + colour => { + at += 1; + (colour, 1) + } + }; + if y >= height || x + run > width { + return None; + } + out[y * width + x..y * width + x + run].fill(colour); + x += run; + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// One `.sup` segment: the framing a Matroska block gets back on the way in. + fn segment(kind: u8, body: &[u8]) -> Vec { + let mut out = Vec::with_capacity(HEADER + body.len()); + out.extend_from_slice(&MAGIC); + out.extend_from_slice(&[0; 8]); + out.push(kind); + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); + out.extend_from_slice(body); + out + } + + /// A display set: an 8×2 white-on-transparent object at (2, 1) of a 16×4 + /// canvas. + fn display_set() -> Vec { + let mut pcs = vec![0, 16, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1]; + pcs.extend_from_slice(&[0, 0, 0, 0, 0, 2, 0, 1]); // object 0, window 0, at (2,1) + let wds = vec![1, 0, 0, 0, 0, 0, 0, 16, 0, 4]; + // Entry 1 is opaque white, entry 2 opaque black; entry 0 stays clear. + let pds = vec![0, 0, 1, 235, 128, 128, 255, 2, 16, 128, 128, 255]; + // Two rows of 8: a run of 8 of entry 1, then a run of 8 of entry 2. + let rle = vec![0x00, 0x88, 0x01, 0x00, 0x00, 0x00, 0x88, 0x02, 0x00, 0x00]; + let mut ods = vec![0, 0, 0, 0xC0]; + ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); + ods.extend_from_slice(&[0, 8, 0, 2]); + ods.extend_from_slice(&rle); + [ + segment(SEG_PCS, &pcs), + segment(SEG_WDS, &wds), + segment(SEG_PDS, &pds), + segment(SEG_ODS, &ods), + segment(SEG_END, &[]), + ] + .concat() + } + + #[test] + fn a_display_set_decodes_to_the_canvas_it_composes() { + let mut decoder = PgsDecoder::new(); + decoder.push(&display_set()).unwrap(); + let frame = decoder.take_frame().expect("one frame per display set"); + assert_eq!((frame.width, frame.height), (16, 4)); + assert_eq!(frame.format, PixelFormat::Rgba8); + let stride = frame.planes[0].stride; + let pixel = |x: usize, y: usize| &frame.planes[0].data[y * stride + x * 4..][..4]; + // Outside the object: nothing painted at all. + assert_eq!(pixel(0, 0), [0, 0, 0, 0]); + assert_eq!(pixel(1, 1), [0, 0, 0, 0]); + // Row 1 of the object is white, row 2 is black, both opaque. + assert_eq!(pixel(2, 1), [255, 255, 255, 255]); + assert_eq!(pixel(9, 1), [255, 255, 255, 255]); + assert_eq!(pixel(2, 2), [0, 0, 0, 255]); + // Past the object's width again. + assert_eq!(pixel(10, 1), [0, 0, 0, 0]); + assert!(decoder.take_frame().is_none()); + } + + #[test] + fn a_stream_split_anywhere_decodes_the_same() { + let bytes = display_set(); + for split in [1, 7, 13, 20, bytes.len() - 1] { + let mut decoder = PgsDecoder::new(); + decoder.push(&bytes[..split]).unwrap(); + decoder.push(&bytes[split..]).unwrap(); + let frame = decoder.take_frame().expect("split framing still decodes"); + assert_eq!((frame.width, frame.height), (16, 4)); + } + } + + #[test] + fn rubbish_never_panics() { + // Not segment framing at all. + let mut decoder = PgsDecoder::new(); + assert!(decoder.push(b"not a sup file at all").is_err()); + // Well-framed segments with torn bodies: dropped, no frame, no panic. + let mut decoder = PgsDecoder::new(); + let torn = [ + segment(SEG_PCS, &[0, 16, 0, 4]), + segment(SEG_ODS, &[0, 0, 0, 0x80, 9, 9, 9]), + segment(SEG_PDS, &[0]), + segment(SEG_END, &[]), + ] + .concat(); + decoder.push(&torn).unwrap(); + assert!(decoder.take_frame().is_none()); + } + + #[test] + fn run_length_shapes_and_their_refusals() { + // Short form, long form, coloured runs, end of line. + let data = [0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00]; + let out = decode_rle(&data, 4, 2).unwrap(); + assert_eq!(out, [0, 0, 0, 1, 2, 2, 2, 0]); + // A run past the row is a refusal, not a wrap. + assert!(decode_rle(&[0x00, 0x08, 0x01], 4, 1).is_none()); + // A truncated run is a refusal too. + assert!(decode_rle(&[0x00, 0x80], 4, 1).is_none()); + } + + #[test] + fn palette_entries_are_bt601_limited_range() { + // Y=235 is white, Y=16 is black, and alpha rides through untouched. + assert_eq!(rgba(235, 128, 128, 255), [255, 255, 255, 255]); + assert_eq!(rgba(16, 128, 128, 128), [0, 0, 0, 128]); + // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601. + let red = rgba(81, 240, 90, 255); + assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}"); + } +} diff --git a/crates/ec-subs/Cargo.toml b/crates/ec-subs/Cargo.toml new file mode 100644 index 00000000..e144c83a --- /dev/null +++ b/crates/ec-subs/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "ec-subs" +description = "Text subtitle parsing for the edith_codecs family: SubRip and WebVTT into one cue IR." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true + +[dev-dependencies] +ec-ass = { path = "../ec-ass", version = "0.1.0" } +ec-pgs = { path = "../ec-pgs", version = "0.1.0" } diff --git a/crates/ec-subs/src/ir.rs b/crates/ec-subs/src/ir.rs new file mode 100644 index 00000000..40142ad7 --- /dev/null +++ b/crates/ec-subs/src/ir.rs @@ -0,0 +1,270 @@ +//! The one cue model every subtitle parser in the family answers with. +//! +//! A cue is a time range and a *tree* of inline runs rather than a string: +//! italics, colour, a karaoke beat and a line break are all things a renderer +//! will want and a plain-text caller can drop in one call +//! ([`plain_text`]). Positioning that the format states — WebVTT cue settings, +//! ASS `\pos` and `\an` — rides beside the runs instead of inside them, because +//! it applies to the cue as a whole. + +/// One inline run of a cue body. +#[derive(Clone, Debug, PartialEq)] +pub enum Segment { + /// Literal text. + Text(String), + /// Hard line break (SRT/WebVTT newline, ASS `\N`). + LineBreak, + /// Bold children (``, ASS `\b1`). + Bold(Vec), + /// Italic children (``, ASS `\i1`). + Italic(Vec), + /// Underlined children (``, ASS `\u1`). + Underline(Vec), + /// Struck-through children (``, ASS `\s1`). + Strike(Vec), + /// Children in an explicit colour (``, ASS `\c` / `\1c`). + Color { + /// Text colour, one byte per channel. + rgb: (u8, u8, u8), + /// What the colour applies to. + children: Vec, + }, + /// Children under a font override (``, ASS `\fn` / `\fs`). + Font { + /// Family name; `None` inherits. + family: Option, + /// Size in the source format's own units; `None` inherits. + size: Option, + /// What the override applies to. + children: Vec, + }, + /// WebVTT ``. + Voice { + /// The speaker the annotation names. + name: String, + /// What that voice says. + children: Vec, + }, + /// WebVTT ``. + Class { + /// Class name without the leading dot. + name: String, + /// What the class applies to. + children: Vec, + }, + /// ASS `{\k}`: the run is highlighted for `cs` centiseconds. + Karaoke { + /// Beat length in centiseconds. + cs: u32, + /// The syllable under the beat. + children: Vec, + }, + /// WebVTT inline timestamp `<00:00:01.500>`, microseconds from stream start. + Timestamp { + /// The instant the tag names. + offset_us: i64, + }, + /// Markup this parser does not model, kept verbatim so a re-emit stays + /// faithful and [`plain_text`] can drop it whole. ASS drawing commands + /// (`{\p1}` … `{\p0}`) land here too: they are shapes, not words. + Raw(String), +} + +/// Horizontal alignment of a cue or a style row. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TextAlign { + /// Start edge of the text direction — left in a left-to-right script. + #[default] + Start, + /// Centred. + Center, + /// End edge of the text direction. + End, + /// Left edge whatever the text direction. + Left, + /// Right edge whatever the text direction. + Right, +} + +/// Where the format asked for the cue to be drawn. +/// +/// The units are the source's own: WebVTT `position`/`line`/`size` are +/// percentages of the viewport, ASS `\pos` is pixels in the `PlayResX` × +/// `PlayResY` canvas. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CuePosition { + /// Horizontal position, or `None` for the format default. + pub x: Option, + /// Vertical position, or `None` for the format default. + pub y: Option, + /// Horizontal alignment of the cue's lines. + pub align: TextAlign, + /// WebVTT `size:N%`; meaningless for ASS. + pub size: Option, +} + +/// A named style a cue can reference — an ASS `Style:` row, essentially. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SubtitleStyle { + /// Style name, which is what [`SubtitleCue::style_ref`] holds. + pub name: String, + /// Font family. + pub font_family: Option, + /// Font size in the source's units. + pub font_size: Option, + /// Fill colour, RGBA. + pub primary_color: Option<(u8, u8, u8, u8)>, + /// Outline colour, RGBA. + pub outline_color: Option<(u8, u8, u8, u8)>, + /// Box/shadow colour, RGBA. + pub back_color: Option<(u8, u8, u8, u8)>, + /// Bold. + pub bold: bool, + /// Italic. + pub italic: bool, + /// Underline. + pub underline: bool, + /// Strikeout. + pub strike: bool, + /// Alignment of the style's lines. + pub align: TextAlign, + /// Left margin. + pub margin_l: Option, + /// Right margin. + pub margin_r: Option, + /// Vertical margin. + pub margin_v: Option, + /// Outline thickness. + pub outline: Option, + /// Shadow depth. + pub shadow: Option, +} + +impl SubtitleStyle { + /// An otherwise defaulted style called `name`. + pub fn new(name: impl Into) -> SubtitleStyle { + SubtitleStyle { + name: name.into(), + ..SubtitleStyle::default() + } + } +} + +/// One cue: when it is up, what it says, and how it was asked to be drawn. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SubtitleCue { + /// Start, microseconds from the start of the media. + pub start_us: i64, + /// End, microseconds from the start of the media. Never before + /// [`start_us`](Self::start_us): a backwards pair is clamped at parse. + pub end_us: i64, + /// The style this cue names, when the format has named styles. + pub style_ref: Option, + /// Positioning the cue itself states. + pub positioning: Option, + /// The body, as runs. + pub segments: Vec, +} + +/// Which on-disk flavour a track was parsed from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SourceFormat { + /// SubRip (`.srt`). + Srt, + /// WebVTT (`.vtt`). + WebVtt, + /// Advanced SubStation Alpha or its SSA predecessor. + AssOrSsa, +} + +/// A parsed subtitle file: where it came from, its styles, its cues. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SubtitleTrack { + /// The flavour, when the parser knows it. + pub source: Option, + /// Named styles, in file order. + pub styles: Vec, + /// Cues, in file order — *not* sorted by time, because a file's own order + /// is information (an overlapping pair is a pair, not an error). + pub cues: Vec, + /// Track-level keys: `title`, `play_res_x`, `wrap_style`, `header`, … + pub metadata: Vec<(String, String)>, + /// Header bytes worth replaying: the ASS script header, the WebVTT + /// preamble. What a Matroska `CodecPrivate` holds for this track. + pub extradata: Vec, + /// Blocks the parser could not read and skipped. Never an error on its own + /// — a file with one torn cue is still a file of cues — but a caller that + /// wants to say so has the count. + pub skipped: usize, +} + +impl SubtitleTrack { + /// An empty track. + pub fn new() -> SubtitleTrack { + SubtitleTrack::default() + } + + /// The same track, tagged with the format it was read from. + pub fn with_source(mut self, source: SourceFormat) -> SubtitleTrack { + self.source = Some(source); + self + } + + /// A style by name. + pub fn style(&self, name: &str) -> Option<&SubtitleStyle> { + self.styles.iter().find(|s| s.name == name) + } +} + +/// The words of a cue body, markup resolved and dropped: `\n` between lines, +/// nothing at all for a run that is a drawing or an override this does not +/// model. +pub fn plain_text(segments: &[Segment]) -> String { + let mut out = String::new(); + append_plain(segments, &mut out); + out +} + +fn append_plain(segments: &[Segment], out: &mut String) { + for segment in segments { + match segment { + Segment::Text(s) => out.push_str(s), + Segment::LineBreak => out.push('\n'), + Segment::Bold(children) + | Segment::Italic(children) + | Segment::Underline(children) + | Segment::Strike(children) => append_plain(children, out), + Segment::Color { children, .. } + | Segment::Font { children, .. } + | Segment::Voice { children, .. } + | Segment::Class { children, .. } + | Segment::Karaoke { children, .. } => append_plain(children, out), + Segment::Timestamp { .. } | Segment::Raw(_) => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_text_walks_the_tree_and_drops_what_cannot_be_said() { + let segments = vec![ + Segment::Italic(vec![Segment::Text("tilted".into())]), + Segment::Text(" and ".into()), + Segment::Color { + rgb: (255, 0, 0), + children: vec![Segment::Text("red".into())], + }, + Segment::LineBreak, + Segment::Raw("{\\p1}m 0 0 l 1 1".into()), + Segment::Timestamp { offset_us: 5 }, + Segment::Karaoke { + cs: 42, + children: vec![Segment::Text("ka".into())], + }, + ]; + assert_eq!(plain_text(&segments), "tilted and red\nka"); + } +} diff --git a/crates/ec-subs/src/lib.rs b/crates/ec-subs/src/lib.rs new file mode 100644 index 00000000..1570a83d --- /dev/null +++ b/crates/ec-subs/src/lib.rs @@ -0,0 +1,33 @@ +//! Text subtitles: SubRip and WebVTT into one cue IR ([`ir`]). +//! +//! Both formats are read the same way and for the same reason: what a timeline +//! wants is *when* a line is on screen and *what it says*, and the markup +//! around that ranges from `` to a dozen dialects of override tag. So a +//! parse answers with a [`ir::SubtitleTrack`] — cues of time ranges and +//! [`ir::Segment`] runs — and a caller that draws nothing yet takes +//! [`ir::plain_text`] and drops the rest. +//! +//! Tolerance is the point. Subtitle files are hand-edited, machine-translated, +//! re-encoded and truncated; a parser that refuses one is a parser that refuses +//! the file the user actually has. BOMs (UTF-8 and UTF-16), CRLF and lone CR, +//! invalid UTF-8, missing or wrong indices, dotted fractions, overlapping and +//! backwards cues all parse. A block this cannot read is skipped and counted +//! ([`ir::SubtitleTrack::skipped`]); only a document with no timing line in it +//! at all is an error, because that is a document of another kind. +//! +//! ASS/SSA is the same IR from `ec-ass`, and PGS bitmaps from `ec-pgs`. + +#![forbid(unsafe_code)] + +pub mod ir; +mod markup; +pub mod srt; +pub mod webvtt; + +pub use ir::{ + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, + plain_text, +}; +/// The byte-level tolerances every subtitle format needs, shared with `ec-ass`: +/// BOM and line-ending normalisation, and the clock every one of them writes. +pub use markup::{decode, parse_clock}; diff --git a/crates/ec-subs/src/markup.rs b/crates/ec-subs/src/markup.rs new file mode 100644 index 00000000..3525ab70 --- /dev/null +++ b/crates/ec-subs/src/markup.rs @@ -0,0 +1,474 @@ +//! The angle-bracket markup SubRip and WebVTT share, plus the byte-level +//! tolerances every text format here needs. +//! +//! Both formats carry a subset of HTML — ``, ``, ``, ``, ``, +//! and WebVTT's ``, `` and inline timestamps — written by a +//! thousand tools with a thousand degrees of care. So the rule is that nothing +//! here fails: an unclosed tag closes at the end of the cue, a stray `` +//! with nothing open is dropped, and a `<` that begins no tag at all is the +//! character it looks like. + +use crate::ir::Segment; + +/// Bytes to text, the way a subtitle file has to be read: a UTF-8 or UTF-16 BOM +/// consumed, invalid sequences replaced rather than refused, and CRLF (or a +/// lone CR, which classic Mac tools still write) folded to LF so every parser +/// after this sees one line ending. +pub fn decode(bytes: &[u8]) -> String { + let text = if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) { + String::from_utf8_lossy(rest).into_owned() + } else if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) { + utf16(rest, u16::from_le_bytes) + } else if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) { + utf16(rest, u16::from_be_bytes) + } else { + String::from_utf8_lossy(bytes).into_owned() + }; + if text.contains('\r') { + text.replace("\r\n", "\n").replace('\r', "\n") + } else { + text + } +} + +fn utf16(bytes: &[u8], unit: fn([u8; 2]) -> u16) -> String { + let units: Vec = bytes.chunks_exact(2).map(|c| unit([c[0], c[1]])).collect(); + String::from_utf16_lossy(&units) +} + +/// `hh:mm:ss,mmm` in microseconds — the timing both text formats state, with +/// every part they are written with in practice: comma or dot before the +/// fraction, hours optional, a fraction of one to six digits, a leading minus +/// on a file whose author shifted it too far. +pub fn parse_clock(field: &str) -> Option { + let field = field.trim(); + let (sign, field) = match field.strip_prefix('-') { + Some(rest) => (-1, rest), + None => (1, field), + }; + let (clock, fraction) = match field.split_once([',', '.']) { + Some((clock, fraction)) => (clock, fraction), + None => (field, ""), + }; + let mut parts = clock.split(':').rev(); + let seconds: i64 = parts.next()?.trim().parse().ok()?; + let minutes: i64 = parts.next().map_or(Ok(0), |m| m.trim().parse()).ok()?; + let hours: i64 = parts.next().map_or(Ok(0), |h| h.trim().parse()).ok()?; + if parts.next().is_some() { + return None; + } + // A fraction is a fraction whatever its length: `.5` is half a second and + // `.500000` is the same instant. + let digits: String = fraction + .chars() + .take_while(char::is_ascii_digit) + .take(6) + .collect(); + let micros = if digits.is_empty() { + 0 + } else { + let value: i64 = digits.parse().ok()?; + value * 10i64.pow(6 - digits.len() as u32) + }; + Some(sign * ((hours * 3600 + minutes * 60 + seconds) * 1_000_000 + micros)) +} + +/// 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())]; + 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) { + 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 }); + } + Tag::Raw => { + flush(&mut text, &mut stack); + push(&mut stack, Segment::Raw(format!("<{tag}>"))); + } + Tag::Open(open) => { + flush(&mut text, &mut stack); + stack.push((Some(open), Vec::new())); + } + Tag::Close(name) => { + flush(&mut text, &mut stack); + // 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)); + if let Some(depth) = found { + while stack.len() > depth { + close_top(&mut stack); + } + } + } + } + } + text.push_str(&unescape(rest)); + flush(&mut text, &mut stack); + while stack.len() > 1 { + close_top(&mut stack); + } + stack + .pop() + .map(|(_, children)| children) + .unwrap_or_default() +} + +/// An open tag: its name and the arguments the closing wrapper will need. +struct Open { + name: String, + color: Option<(u8, u8, u8)>, + family: Option, + size: Option, + annotation: String, +} + +enum Tag { + Open(Open), + Close(String), + Timestamp(i64), + Raw, + /// Not a tag at all — a `<` that means `<`. + Text, +} + +fn classify(tag: &str, webvtt: bool) -> Tag { + let trimmed = tag.trim(); + if trimmed.is_empty() { + return Tag::Text; + } + if let Some(name) = trimmed.strip_prefix('/') { + let name = name.trim().to_ascii_lowercase(); + let name = name.split(['.', ' ']).next().unwrap_or("").to_owned(); + 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()) { + return match parse_clock(trimmed) { + Some(offset_us) => Tag::Timestamp(offset_us), + None => Tag::Text, + }; + } + let (head, attrs) = match trimmed.split_once(char::is_whitespace) { + Some((head, attrs)) => (head, attrs), + None => (trimmed, ""), + }; + let (head, classes) = match head.split_once('.') { + Some((head, classes)) => (head, classes), + None => (head, ""), + }; + let name = head.trim_end_matches('/').to_ascii_lowercase(); + match name.as_str() { + "b" | "i" | "u" | "s" => Tag::Open(Open { + name, + color: None, + family: None, + size: None, + annotation: String::new(), + }), + "font" => Tag::Open(Open { + name, + color: attribute(attrs, "color").and_then(|v| parse_color(&v)), + family: attribute(attrs, "face"), + size: attribute(attrs, "size").and_then(|v| v.trim().parse().ok()), + annotation: String::new(), + }), + "v" | "c" if webvtt => Tag::Open(Open { + annotation: match name.as_str() { + "v" => attrs.trim().to_owned(), + _ => classes.replace('.', " "), + }, + name, + color: None, + family: None, + size: None, + }), + _ => Tag::Raw, + } +} + +/// `name="value"` / `name=value` out of a tag's attribute text. +fn attribute(attrs: &str, name: &str) -> Option { + let lower = attrs.to_ascii_lowercase(); + let mut from = 0; + loop { + let at = lower[from..].find(name)? + from; + let after = attrs[at + name.len()..].trim_start(); + match after.strip_prefix('=') { + Some(value) => { + let value = value.trim_start(); + let quoted = value.strip_prefix(['"', '\'']); + return Some(match quoted { + Some(v) => v.split(['"', '\'']).next().unwrap_or(v).to_owned(), + None => value + .split_whitespace() + .next() + .unwrap_or_default() + .trim_end_matches('/') + .to_owned(), + }); + } + None => from = at + name.len(), + } + } +} + +/// `#rrggbb`, `#rgb`, or one of the sixteen names HTML has always had. +fn parse_color(value: &str) -> Option<(u8, u8, u8)> { + let value = value.trim(); + if let Some(hex) = value.strip_prefix('#') { + let digits: String = hex.chars().take_while(char::is_ascii_hexdigit).collect(); + let byte = |s: &str| u8::from_str_radix(s, 16).ok(); + return match digits.len() { + 3 => { + let mut c = digits.chars().map(|c| byte(&format!("{c}{c}"))); + Some((c.next()??, c.next()??, c.next()??)) + } + 6 | 8 => Some(( + byte(&digits[0..2])?, + byte(&digits[2..4])?, + byte(&digits[4..6])?, + )), + _ => None, + }; + } + let named = [ + ("black", (0, 0, 0)), + ("silver", (192, 192, 192)), + ("gray", (128, 128, 128)), + ("grey", (128, 128, 128)), + ("white", (255, 255, 255)), + ("maroon", (128, 0, 0)), + ("red", (255, 0, 0)), + ("purple", (128, 0, 128)), + ("fuchsia", (255, 0, 255)), + ("green", (0, 128, 0)), + ("lime", (0, 255, 0)), + ("olive", (128, 128, 0)), + ("yellow", (255, 255, 0)), + ("navy", (0, 0, 128)), + ("blue", (0, 0, 255)), + ("teal", (0, 128, 128)), + ("aqua", (0, 255, 255)), + ("cyan", (0, 255, 255)), + ("magenta", (255, 0, 255)), + ]; + let lower = value.to_ascii_lowercase(); + named + .iter() + .find(|(name, _)| *name == lower) + .map(|(_, rgb)| *rgb) +} + +/// The handful of entities subtitle text is written with, plus numeric ones. +fn unescape(text: &str) -> String { + if !text.contains('&') { + return text.to_owned(); + } + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.find('&') { + out.push_str(&rest[..at]); + let after = &rest[at + 1..]; + let end = after.find(';').filter(|&e| e <= 10); + let Some(end) = end else { + out.push('&'); + rest = after; + continue; + }; + let name = &after[..end]; + let replacement = match name.to_ascii_lowercase().as_str() { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some('\u{a0}'), + "lrm" => Some('\u{200e}'), + "rlm" => Some('\u{200f}'), + other => other + .strip_prefix('#') + .and_then(|n| match n.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => n.parse().ok(), + }) + .and_then(char::from_u32), + }; + match replacement { + Some(c) => { + out.push(c); + rest = &after[end + 1..]; + } + None => { + out.push('&'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +fn flush(text: &mut String, stack: &mut [(Option, Vec)]) { + 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())); + } + for line in lines { + let children = &mut stack.last_mut().unwrap().1; + children.push(Segment::LineBreak); + if !line.is_empty() { + children.push(Segment::Text(line.into())); + } + } + } +} + +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::*; + use crate::ir::plain_text; + + #[test] + fn clocks_are_read_in_every_shape_a_file_writes_them() { + assert_eq!(parse_clock("00:00:01,500"), Some(1_500_000)); + assert_eq!(parse_clock("00:00:01.5"), Some(1_500_000)); + assert_eq!(parse_clock("1:02:03.250"), Some(3_723_250_000)); + // Hours omitted, as WebVTT allows. + assert_eq!(parse_clock("02:03.000"), Some(123_000_000)); + // Six digits and beyond. + assert_eq!(parse_clock("0:00:00.123456"), Some(123_456)); + assert_eq!(parse_clock("0:00:00.1234569"), Some(123_456)); + assert_eq!(parse_clock("-0:00:01.000"), Some(-1_000_000)); + assert_eq!(parse_clock("not a time"), None); + assert_eq!(parse_clock("1:2:3:4.0"), None); + } + + #[test] + fn decode_takes_the_bom_and_folds_the_line_endings() { + assert_eq!(decode(b"\xef\xbb\xbfa\r\nb\rc"), "a\nb\nc"); + assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, b'i', 0]), "hi"); + // Invalid UTF-8 is replaced, never refused. + assert_eq!(decode(b"a\xffb"), "a\u{fffd}b"); + } + + #[test] + fn markup_nests_and_forgives() { + let segments = parse_inline("a b", false); + 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("2 < 3 & 4", false)), + "2 < 3 & 4" + ); + } + + #[test] + fn webvtt_only_tags_are_off_for_srt() { + let vtt = parse_inline("hi", true); + assert!(matches!(vtt[0], Segment::Voice { .. })); + assert_eq!(plain_text(&vtt), "hi"); + let srt = parse_inline("hi", false); + 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); + assert!(matches!( + segments[0], + Segment::Color { + rgb: (255, 0, 0), + .. + } + )); + let named = parse_inline("green", false); + assert!(matches!( + named[0], + Segment::Color { + rgb: (0, 255, 0), + .. + } + )); + } +} diff --git a/crates/ec-subs/src/srt.rs b/crates/ec-subs/src/srt.rs new file mode 100644 index 00000000..432675ba --- /dev/null +++ b/crates/ec-subs/src/srt.rs @@ -0,0 +1,131 @@ +//! SubRip (`.srt`). +//! +//! The format is a list of blocks separated by blank lines: an index, a timing +//! line, then the text. In the wild the index is optional, wrong, or repeated; +//! the fraction is a comma or a dot; the timing line trails coordinates +//! (`X1:0 X2:640 …`) that nothing reads any more. So the *timing line* is what +//! identifies a block here — a block without one is skipped and counted rather +//! than taken as text of the block before it. + +use ec_core::{Error, Result}; + +use crate::ir::{SourceFormat, SubtitleCue, SubtitleTrack}; +use crate::markup::{decode, parse_clock, parse_inline}; + +/// Parse a SubRip document. +/// +/// `Err` only when the bytes are not this format at all — text with no timing +/// line anywhere in it. A file with some torn blocks parses to the blocks that +/// are whole, with [`SubtitleTrack::skipped`] counting the rest. +pub fn parse(bytes: &[u8]) -> Result { + let text = decode(bytes); + let mut track = SubtitleTrack::new().with_source(SourceFormat::Srt); + for block in blocks(&text) { + // The timing line is the anchor: everything before it is an index (or + // rubbish), everything after it is the cue's text. + let Some((at, (start_us, end_us))) = block + .iter() + .enumerate() + .find_map(|(i, line)| timing(line).map(|t| (i, t))) + else { + track.skipped += 1; + continue; + }; + let body = block[at + 1..].join("\n"); + track.cues.push(SubtitleCue { + start_us, + // A file that ends a cue before it starts says nothing about how + // long it is up; the cue is kept, with no duration rather than a + // negative one. + end_us: end_us.max(start_us), + style_ref: None, + positioning: None, + segments: parse_inline(body.trim_end(), false), + }); + } + if track.cues.is_empty() && text.split_whitespace().next().is_some() { + return Err(Error::corrupt( + "no SubRip timing line in the whole document", + )); + } + Ok(track) +} + +/// Blocks, split on blank lines, blank ones dropped. +fn blocks(text: &str) -> impl Iterator> { + let mut out: Vec> = Vec::new(); + let mut current: Vec<&str> = Vec::new(); + for line in text.lines() { + if line.trim().is_empty() { + if !current.is_empty() { + out.push(std::mem::take(&mut current)); + } + } else { + current.push(line); + } + } + if !current.is_empty() { + out.push(current); + } + out.into_iter() +} + +/// `00:00:01,000 --> 00:00:02,000` with anything after it ignored. +pub(crate) fn timing(line: &str) -> Option<(i64, i64)> { + let (start, rest) = line.split_once("-->")?; + let end = rest.split_whitespace().next().unwrap_or_default(); + Some((parse_clock(start)?, parse_clock(end)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir::plain_text; + + #[test] + fn an_ordinary_file_parses() { + let doc = "1\n00:00:01,000 --> 00:00:02,500\nfirst line\nsecond line\n\n\ + 2\n00:00:03,000 --> 00:00:04,000\ntilted\n"; + let track = parse(doc.as_bytes()).unwrap(); + assert_eq!(track.source, Some(SourceFormat::Srt)); + assert_eq!(track.cues.len(), 2); + assert_eq!(track.cues[0].start_us, 1_000_000); + assert_eq!(track.cues[0].end_us, 2_500_000); + assert_eq!( + plain_text(&track.cues[0].segments), + "first line\nsecond line" + ); + assert_eq!(plain_text(&track.cues[1].segments), "tilted"); + assert_eq!(track.skipped, 0); + } + + #[test] + fn the_tolerances_a_real_file_needs() { + // BOM, CRLF, no indices, dotted fraction, trailing coordinates, an + // overlapping pair, and a block that is text with no timing at all. + let doc = b"\xef\xbb\xbf00:00:01.000 --> 00:00:04,000 X1:0 X2:640\r\none\r\n\r\n\ + junk with no timing\r\n\r\n\ + 00:00:02,000 --> 00:00:03,000\r\ntwo\r\n"; + let track = parse(doc).unwrap(); + assert_eq!(track.cues.len(), 2); + assert_eq!(track.skipped, 1); + assert_eq!(track.cues[0].end_us, 4_000_000); + // Overlapping cues stay in file order, both of them. + assert_eq!(track.cues[1].start_us, 2_000_000); + assert_eq!(plain_text(&track.cues[1].segments), "two"); + } + + #[test] + fn a_backwards_pair_is_clamped_not_negative() { + let doc = "1\n00:00:05,000 --> 00:00:01,000\nback\n"; + let cue = &parse(doc.as_bytes()).unwrap().cues[0]; + assert_eq!((cue.start_us, cue.end_us), (5_000_000, 5_000_000)); + } + + #[test] + fn text_that_is_not_a_subtitle_file_is_refused_but_empty_is_not() { + assert!(parse(b"this is a text file\nwith no timings").is_err()); + assert_eq!(parse(b"").unwrap().cues.len(), 0); + assert_eq!(parse(b"\n\n \n").unwrap().cues.len(), 0); + } +} diff --git a/crates/ec-subs/src/webvtt.rs b/crates/ec-subs/src/webvtt.rs new file mode 100644 index 00000000..795392e8 --- /dev/null +++ b/crates/ec-subs/src/webvtt.rs @@ -0,0 +1,174 @@ +//! WebVTT (`.vtt`). +//! +//! SubRip's shape with a `WEBVTT` header, optional cue identifiers, cue +//! settings after the timing line, and two tags of its own (``, +//! ``) plus inline timestamps. `NOTE`, `STYLE` and `REGION` blocks +//! are read past: they say nothing about *when* anything is on screen, which +//! is what this IR carries. + +use ec_core::{Error, Result}; + +use crate::ir::{CuePosition, SourceFormat, SubtitleCue, SubtitleTrack, TextAlign}; +use crate::markup::{decode, parse_inline}; +use crate::srt::timing; + +/// Parse a WebVTT document. +/// +/// The `WEBVTT` signature is *expected*, not required — a file missing it but +/// full of cues is a file of cues. `Err` is for text with no timing line +/// anywhere, exactly as in [`crate::srt::parse`]. +pub fn parse(bytes: &[u8]) -> Result { + let text = decode(bytes); + let mut track = SubtitleTrack::new().with_source(SourceFormat::WebVtt); + let mut blocks = text.split("\n\n").peekable(); + if let Some(first) = blocks.peek() + && let Some(header) = first.trim_start().strip_prefix("WEBVTT") + { + let header = header.trim(); + if !header.is_empty() { + track + .metadata + .push(("header".to_owned(), header.to_owned())); + } + track.extradata = first.trim_start().as_bytes().to_vec(); + blocks.next(); + } + for block in blocks { + let lines: Vec<&str> = block.lines().filter(|l| !l.trim().is_empty()).collect(); + let Some(first) = lines.first() else { continue }; + // Blocks that are not cues, by their first word. + let keyword = first.split_whitespace().next().unwrap_or_default(); + if matches!(keyword, "NOTE" | "STYLE" | "REGION") { + continue; + } + let Some((at, (start_us, end_us))) = lines + .iter() + .enumerate() + .find_map(|(i, line)| timing(line).map(|t| (i, t))) + else { + track.skipped += 1; + continue; + }; + // Anything before the timing line is the cue identifier, which names + // the cue for styling and says nothing about its timing or its text. + let body = lines[at + 1..].join("\n"); + track.cues.push(SubtitleCue { + start_us, + end_us: end_us.max(start_us), + style_ref: None, + positioning: settings(lines[at]), + segments: parse_inline(body.trim_end(), true), + }); + } + if track.cues.is_empty() && text.split_whitespace().next().is_some() { + return Err(Error::corrupt( + "no WebVTT timing line in the whole document", + )); + } + Ok(track) +} + +/// The `align:`, `position:`, `line:` and `size:` settings after a timing line. +/// `None` when the line carries none of them. +fn settings(line: &str) -> Option { + let after = line.split_once("-->")?.1; + // The end timestamp first, then the settings. + let mut position = CuePosition::default(); + let mut any = false; + for setting in after.split_whitespace().skip(1) { + let Some((key, value)) = setting.split_once(':') else { + continue; + }; + // `position:10%,line-left` — the alignment suffix is not the number. + let number = || { + value + .split(',') + .next() + .unwrap_or_default() + .trim_end_matches('%') + .parse::() + .ok() + }; + match key { + "align" => { + position.align = match value { + "start" => TextAlign::Start, + "center" | "middle" => TextAlign::Center, + "end" => TextAlign::End, + "left" => TextAlign::Left, + "right" => TextAlign::Right, + _ => continue, + }; + any = true; + } + "position" => { + position.x = number(); + any |= position.x.is_some(); + } + // A `line` without a `%` is a line *number*, not a percentage; + // it is carried as given, which is what the renderer will need. + "line" => { + position.y = number(); + any |= position.y.is_some(); + } + "size" => { + position.size = number(); + any |= position.size.is_some(); + } + _ => {} + } + } + any.then_some(position) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir::{Segment, plain_text}; + + #[test] + fn header_identifiers_notes_and_settings() { + let doc = "WEBVTT - a title\n\n\ + NOTE this block says nothing\n\n\ + cue-1\n00:00:01.000 --> 00:00:02.000 align:center position:40% line:90%\n\ + hello\n\n\ + 00:01:00.000 --> 00:01:02.000\nplain\n"; + let track = parse(doc.as_bytes()).unwrap(); + assert_eq!(track.source, Some(SourceFormat::WebVtt)); + assert_eq!( + track.metadata, + vec![("header".to_owned(), "- a title".to_owned())] + ); + assert_eq!(track.cues.len(), 2); + let first = &track.cues[0]; + assert_eq!((first.start_us, first.end_us), (1_000_000, 2_000_000)); + let position = first.positioning.unwrap(); + assert_eq!(position.align, TextAlign::Center); + assert_eq!((position.x, position.y), (Some(40.0), Some(90.0))); + assert_eq!(plain_text(&first.segments), "hello"); + assert!(matches!(first.segments[0], Segment::Voice { .. })); + assert_eq!(track.cues[1].positioning, None); + assert_eq!(track.cues[1].start_us, 60_000_000); + } + + #[test] + fn inline_timestamps_and_classes_are_runs_not_words() { + let doc = "WEBVTT\n\n00:00:00.000 --> 00:00:09.000\n\ + shout<00:00:03.000>then quiet\n"; + let cue = &parse(doc.as_bytes()).unwrap().cues[0]; + assert_eq!(plain_text(&cue.segments), "shoutthen quiet"); + assert!(cue.segments.iter().any(|s| matches!( + s, + Segment::Timestamp { + offset_us: 3_000_000 + } + ))); + } + + #[test] + fn a_file_without_the_signature_still_parses_and_prose_does_not() { + let track = parse(b"00:00:01.000 --> 00:00:02.000\nhi\n").unwrap(); + assert_eq!(track.cues.len(), 1); + assert!(parse(b"WEBVTT\n\nNOTE just a note\n\nnot a cue block").is_err()); + } +} diff --git a/crates/ec-subs/tests/real_library.rs b/crates/ec-subs/tests/real_library.rs new file mode 100644 index 00000000..a7ec75c8 --- /dev/null +++ b/crates/ec-subs/tests/real_library.rs @@ -0,0 +1,142 @@ +//! The three parsers against streams taken out of the user's own library. +//! +//! Hand-written cases live in the crates' unit tests; what cannot be written by +//! hand is a disc's PGS display set or a fansub's thousand-line ASS script. +//! `scripts/gen-subtitle-fixtures.sh` extracts them (fixtures are gitignored, +//! the script is not), and every test here *skips* when its fixture is absent +//! so a fresh clone still runs green. + +use std::path::PathBuf; + +use ec_subs::{SourceFormat, plain_text}; + +fn fixture(name: &str) -> Option> { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/subs") + .join(name); + match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(_) => { + eprintln!("skipping: no {name} — run scripts/gen-subtitle-fixtures.sh"); + None + } + } +} + +#[test] +fn a_real_subrip_track_parses_whole() { + let Some(bytes) = fixture("real.srt") else { + return; + }; + let track = ec_subs::srt::parse(&bytes).unwrap(); + assert_eq!(track.source, Some(SourceFormat::Srt)); + assert!(track.cues.len() > 100, "{} cues", track.cues.len()); + assert_eq!(track.skipped, 0, "a whole file should have no torn blocks"); + // Every cue is up for a positive time and says something. + for cue in &track.cues { + assert!(cue.end_us >= cue.start_us); + assert!( + !plain_text(&cue.segments).trim().is_empty(), + "empty cue at {}us", + cue.start_us + ); + } + // A subtitle track runs forwards. + assert!( + track + .cues + .windows(2) + .all(|w| w[1].start_us >= w[0].start_us) + ); +} + +#[test] +fn a_real_ass_script_parses_whole() { + let Some(bytes) = fixture("real.ass") else { + return; + }; + let track = ec_ass::parse(&bytes).unwrap(); + assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); + assert!(!track.styles.is_empty(), "a script declares styles"); + assert!(track.cues.len() > 100, "{} cues", track.cues.len()); + assert_eq!(track.skipped, 0, "a whole script should have no torn rows"); + // Every cue names a style the script declared, and most say words: a + // signs-and-songs script has drawing-only lines, which are not words. + let with_text = track + .cues + .iter() + .filter(|c| !plain_text(&c.segments).trim().is_empty()) + .count(); + assert!( + with_text * 10 > track.cues.len() * 9, + "{with_text} of {}", + track.cues.len() + ); + for cue in &track.cues { + assert!(cue.end_us >= cue.start_us); + if let Some(style) = &cue.style_ref { + assert!( + track.style(style).is_some(), + "cue names undeclared style {style:?}" + ); + } + // Override tags never leak into the words. + let text = plain_text(&cue.segments); + assert!(!text.contains("{\\"), "override tag in text: {text:?}"); + } + // The header is replayable as a Matroska `CodecPrivate`. + assert!(track.extradata.windows(8).any(|w| w == b"[Events]")); +} + +#[test] +fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { + let Some(bytes) = fixture("pgs-1080p.sup") else { + return; + }; + let mut decoder = ec_pgs::PgsDecoder::new(); + decoder.push(&bytes).unwrap(); + let mut frames = 0; + let mut painted = 0; + let mut coverage_max = 0.0f64; + while let Some(frame) = decoder.take_frame() { + frames += 1; + // A disc composes against its own video frame, and this one is HD. + assert_eq!((frame.width, frame.height), (1920, 1080)); + let stride = frame.planes[0].stride; + assert_eq!(stride, 1920 * 4); + let opaque = frame.planes[0] + .data + .chunks_exact(4) + .filter(|p| p[3] > 0) + .count(); + if opaque == 0 { + // An erase display set: a set that composes nothing at all. + continue; + } + painted += 1; + let coverage = opaque as f64 / (1920.0 * 1080.0); + coverage_max = coverage_max.max(coverage); + // Subtitles are lines of text over a film: ink, not a filled canvas. + assert!( + coverage > 0.000_1 && coverage < 0.25, + "display set {frames} covers {:.3}% of the canvas", + coverage * 100.0 + ); + // The ink sits in the lower or upper band, never as a single stray row. + let rows = (0..1080) + .filter(|y| { + frame.planes[0].data[y * stride..(y + 1) * stride] + .chunks_exact(4) + .any(|p| p[3] > 0) + }) + .count(); + assert!(rows > 4, "display set {frames} paints {rows} rows"); + } + assert!(frames > 100, "{frames} display sets"); + assert!( + painted * 3 > frames, + "{painted} of {frames} display sets painted anything" + ); + assert!(coverage_max < 0.25, "widest cue covers {coverage_max}"); + eprintln!("pgs: {frames} display sets, {painted} painted, widest {coverage_max:.4}"); +} diff --git a/scripts/gen-subtitle-fixtures.sh b/scripts/gen-subtitle-fixtures.sh new file mode 100755 index 00000000..4bc41b63 --- /dev/null +++ b/scripts/gen-subtitle-fixtures.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# gen-subtitle-fixtures.sh — extract real subtitle streams out of the library. +# +# READ-ONLY on the library; writes only under fixtures/ (gitignored). Picks the +# first manifest file carrying each subtitle codec and copies that stream out +# without re-encoding, so what the tests parse is exactly the bytes a disc rip +# holds. The synthetic .srt/.vtt/.ass cases live inside the crates' own unit +# tests; what cannot be written by hand is a real PGS display set. +# +# Usage: scripts/gen-subtitle-fixtures.sh +# Env: EC_FIXTURES= (default /fixtures) +# EC_PGS_SECONDS= (default 900 — a whole film's worth is 30 MB) +# In: fixtures/real-library-manifest.tsv (scripts/scan-real-library.sh) +# Out: fixtures/subs/{pgs-1080p.sup,real.ass,real.srt} + +set -uo pipefail + +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} +MANIFEST=$FIXTURES/real-library-manifest.tsv +OUT=$FIXTURES/subs +SECONDS_LIMIT=${EC_PGS_SECONDS:-900} + +command -v ffmpeg >/dev/null || { echo "gen-subtitle-fixtures: ffmpeg not found" >&2; exit 2; } +[ -r "$MANIFEST" ] || { echo "gen-subtitle-fixtures: run scripts/scan-real-library.sh first" >&2; exit 2; } + +mkdir -p -- "$OUT" + +# first_with — path of the first manifest file holding such a +# subtitle stream, empty when the library has none. +first_with() { + local codec=$1 path + while IFS=$'\t' read -r path _; do + [ -r "$path" ] || continue + if ffprobe -v error -select_streams s -show_entries stream=codec_name -of csv=p=0 -- "$path" 2>/dev/null | + grep -qx "$codec"; then + printf '%s\n' "$path" + return 0 + fi + done < <(tail -n +2 -- "$MANIFEST") + return 1 +} + +# extract [ffmpeg args...] +extract() { + local codec=$1 out=$2; shift 2 + local src + if ! src=$(first_with "$codec"); then + echo "gen-subtitle-fixtures: no $codec stream in the library — skipping $(basename "$out")" >&2 + return 0 + fi + # -map by codec so a dual-subtitle file gives the stream we asked for. + local index + index=$(ffprobe -v error -select_streams s -show_entries stream=index,codec_name -of csv=p=0 -- "$src" | + awk -F, -v c="$codec" '$2 == c {print $1; exit}') + if ffmpeg -v error -y "$@" -i "$src" -map "0:$index" -c copy -- "$out"; then + printf '%s\t%s\n' "$(basename "$out")" "$src" + else + echo "gen-subtitle-fixtures: ffmpeg failed on $src" >&2 + fi +} + +extract hdmv_pgs_subtitle "$OUT/pgs-1080p.sup" -t "$SECONDS_LIMIT" +extract ass "$OUT/real.ass" +extract subrip "$OUT/real.srt" diff --git a/shims/oxideav-ass/Cargo.toml b/shims/oxideav-ass/Cargo.toml new file mode 100644 index 00000000..5b1aff3d --- /dev/null +++ b/shims/oxideav-ass/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "oxideav-ass" +description = "Compatibility shim: the oxideav-ass surface edith consumes, over ec-ass." +version = "0.0.9" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-ass = { path = "../../crates/ec-ass", version = "0.1.0" } +ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" } +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } diff --git a/shims/oxideav-ass/src/lib.rs b/shims/oxideav-ass/src/lib.rs new file mode 100644 index 00000000..f88f595b --- /dev/null +++ b/shims/oxideav-ass/src/lib.rs @@ -0,0 +1,37 @@ +//! `oxideav-ass` as edith consumes it, over [`ec_ass`]. +//! +//! One item: `parse`, answering the same [`SubtitleTrack`] the SubRip and +//! WebVTT parsers do — the replica hands all three around as one function +//! pointer type and reads `cues`, `segments` and `plain_text` off the result. + +#![forbid(unsafe_code)] + +use oxideav_core::Result; + +pub use ec_subs::ir::{ + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, +}; + +/// Parse an ASS or SSA script. +pub fn parse(bytes: &[u8]) -> Result { + Ok(ec_ass::parse(bytes)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_script_parses_through_the_shim() { + type Parse = fn(&[u8]) -> Result; + let parse: Parse = parse; + let doc = "[Events]\n\ + Format: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ + Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi{\\i0}\\Nthere\n"; + let track = parse(doc.as_bytes()).unwrap(); + assert_eq!(track.cues.len(), 1); + assert_eq!(track.cues[0].start_us, 1_000_000); + assert_eq!(ec_subs::plain_text(&track.cues[0].segments), "hi\nthere"); + assert!(!parse(b"not a script").unwrap_err().to_string().is_empty()); + } +} diff --git a/shims/oxideav-core/Cargo.toml b/shims/oxideav-core/Cargo.toml new file mode 100644 index 00000000..6ded82fb --- /dev/null +++ b/shims/oxideav-core/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "oxideav-core" +description = "Compatibility shim: the oxideav-core surface edith consumes, over ec-core." +version = "0.1.34" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-core.workspace = true diff --git a/shims/oxideav-core/src/lib.rs b/shims/oxideav-core/src/lib.rs new file mode 100644 index 00000000..e124cd3c --- /dev/null +++ b/shims/oxideav-core/src/lib.rs @@ -0,0 +1,484 @@ +//! `oxideav-core` as edith consumes it, over [`ec_core`]. +//! +//! A shim, not a port: it carries the incumbent's package name and version so a +//! swap is a `[patch.crates-io]` line and nothing else, and it exposes exactly +//! the items the replica names — no more, because an item nobody calls is an +//! item nobody can check. The list, and where each is called from, is in the +//! subtitle and export paths of the engine: `Packet::new`, `TimeBase::new`, +//! `Error::NeedMore`, `CodecId`, `CodecParameters::{audio,subtitle}`, +//! `CodecRegistry`, `Decoder`, `Frame`, `Muxer`, `StreamInfo`, `Result`. +//! +//! Where the two IRs differ in *shape* the shim owns the difference: +//! `oxideav`'s codec id is a string and `ec_core`'s is an enum, its frames own +//! their bytes and `ec_core`'s share a refcounted buffer. Those are converted +//! here, once, rather than at every call site of the replica. +//! +//! [`Packet`] and [`TimeBase`] are `ec_core`'s own: their signatures already +//! match what the replica writes, so a re-export is the whole adapter. + +#![forbid(unsafe_code)] + +use std::collections::HashMap; +use std::fmt; + +pub use ec_core::{Packet, TimeBase}; + +/// What a call into this family can go wrong with. +/// +/// `NeedMore` is load-bearing: the replica's AC-3 path treats it as "not an +/// error, feed me another packet" and everything else as a failure. +#[derive(Debug)] +#[non_exhaustive] +pub enum Error { + /// The decoder wants another packet before it can hand back a frame. + NeedMore, + /// End of stream. + Eof, + /// Well-formed but not supported. + Unsupported(String), + /// Malformed input. + InvalidData(String), + /// No codec in the registry claims these parameters. + CodecNotFound(String), + /// Underlying I/O. + Io(std::io::Error), + /// Anything else. + Other(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NeedMore => write!(f, "more input needed"), + Error::Eof => write!(f, "end of stream"), + Error::Unsupported(what) => write!(f, "unsupported: {what}"), + Error::InvalidData(what) => write!(f, "invalid data: {what}"), + Error::CodecNotFound(id) => write!(f, "no codec {id}"), + Error::Io(e) => write!(f, "{e}"), + Error::Other(what) => write!(f, "{what}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: std::io::Error) -> Error { + Error::Io(e) + } +} + +impl From for Error { + fn from(e: ec_core::Error) -> Error { + match e { + ec_core::Error::NeedMore => Error::NeedMore, + ec_core::Error::Eof => Error::Eof, + ec_core::Error::Unsupported { what, why } => { + Error::Unsupported(format!("{what}: {why}")) + } + ec_core::Error::Corrupt { context } => Error::InvalidData(context), + ec_core::Error::Io(e) => Error::Io(e), + } + } +} + +/// This family's result. +pub type Result = std::result::Result; + +/// A codec's identifier, as a string: `"ac3"`, `"pgs"`, `"vorbis"`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct CodecId(pub String); + +impl CodecId { + /// The id named by `s`. + pub fn new(s: impl Into) -> CodecId { + CodecId(s.into()) + } + + /// The name itself. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// The `ec_core` codec this names, when the family carries it. + pub fn to_ec(&self) -> Option { + use ec_core::CodecId::*; + Some(match self.0.as_str() { + "h264" | "avc1" => H264, + "h265" | "hevc" => H265, + "vp8" => Vp8, + "vp9" => Vp9, + "av1" => Av1, + "aac" => Aac, + "ac3" => Ac3, + "eac3" => EAc3, + "alac" => Alac, + "flac" => Flac, + "mp3" => Mp3, + "opus" => Opus, + "vorbis" => Vorbis, + "srt" | "subrip" => Srt, + "webvtt" | "vtt" => WebVtt, + "ass" | "ssa" => Ass, + "pgs" => Pgs, + "tx3g" => Tx3g, + _ => return None, + }) + } +} + +impl fmt::Display for CodecId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +/// What kind of stream a set of parameters describes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum MediaType { + /// Audio samples. + Audio, + /// Video pictures. + Video, + /// Timed text or subtitle bitmaps. + Subtitle, + /// Opaque payload. + Data, + /// Not yet determined. + #[default] + Unknown, +} + +/// Everything a decoder is told before its first packet. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CodecParameters { + /// Which codec. + pub codec_id: CodecId, + /// Which kind of stream. + pub media_type: MediaType, + /// Audio sample rate. + pub sample_rate: Option, + /// Audio channel count — the replica asks for `Some(2)` to get a downmix. + pub channels: Option, + /// Coded width. + pub width: Option, + /// Coded height. + pub height: Option, + /// Codec setup bytes. + pub extradata: Vec, +} + +impl CodecParameters { + /// Audio parameters for `codec_id`. + pub fn audio(codec_id: CodecId) -> CodecParameters { + CodecParameters { + codec_id, + media_type: MediaType::Audio, + ..CodecParameters::default() + } + } + + /// Video parameters for `codec_id`. + pub fn video(codec_id: CodecId) -> CodecParameters { + CodecParameters { + codec_id, + media_type: MediaType::Video, + ..CodecParameters::default() + } + } + + /// Subtitle parameters for `codec_id`. + pub fn subtitle(codec_id: CodecId) -> CodecParameters { + CodecParameters { + codec_id, + media_type: MediaType::Subtitle, + ..CodecParameters::default() + } + } + + /// Data-stream parameters for `codec_id`. + pub fn data(codec_id: CodecId) -> CodecParameters { + CodecParameters { + codec_id, + media_type: MediaType::Data, + ..CodecParameters::default() + } + } +} + +/// One stream of a container, as a muxer is told about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamInfo { + /// Index the stream's packets carry. + pub index: u32, + /// The unit its timestamps are in. + pub time_base: TimeBase, + /// Duration in `time_base` ticks. + pub duration: Option, + /// First timestamp in `time_base` ticks. + pub start_time: Option, + /// What is in it. + pub params: CodecParameters, +} + +/// One decoded picture. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct VideoFrame { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Presentation time in the stream's time base. + pub pts: Option, + /// One plane per component group; packed formats have exactly one. + pub planes: Vec, +} + +/// One plane of a [`VideoFrame`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct VideoPlane { + /// Bytes between the starts of two rows. + pub stride: usize, + /// The plane's bytes. + pub data: Vec, +} + +/// One decoded block of audio. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AudioFrame { + /// Frames per channel in this block. + pub samples: u32, + /// Presentation time in the stream's time base. + pub pts: Option, + /// Interleaved (one entry) or planar (one entry per channel) bytes. + pub data: Vec>, +} + +/// What a decoder hands back. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Frame { + /// A picture. + Video(VideoFrame), + /// An audio block. + Audio(AudioFrame), +} + +impl From for Frame { + fn from(frame: ec_core::Frame) -> Frame { + match frame { + ec_core::Frame::Video(video) => Frame::Video(VideoFrame { + width: video.width, + height: video.height, + pts: video.pts.map(|t| t.ticks), + planes: video + .planes + .into_iter() + .map(|plane| VideoPlane { + stride: plane.stride, + data: plane.data.to_vec(), + }) + .collect(), + }), + ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame { + samples: audio.samples as u32, + pts: audio.pts.map(|t| t.ticks), + data: audio.data.iter().map(|buf| buf.to_vec()).collect(), + }), + } + } +} + +/// A decoder: packets in, frames out. +pub trait Decoder: Send { + /// The codec this decodes. + fn codec_id(&self) -> &CodecId; + + /// Feed one packet. + fn send_packet(&mut self, packet: &Packet) -> Result<()>; + + /// Take one frame, or [`Error::NeedMore`] when the decoder wants another + /// packet first. + fn receive_frame(&mut self) -> Result; +} + +/// A container writer. +pub trait Muxer: Send { + /// The format's short name. + fn format_name(&self) -> &str; + + /// Write whatever precedes the first packet. + fn write_header(&mut self) -> Result<()>; + + /// Write one packet. + fn write_packet(&mut self, packet: &Packet) -> Result<()>; + + /// Write whatever follows the last one. + fn write_trailer(&mut self) -> Result<()>; +} + +/// How a codec crate hands out decoders. +pub type DecoderFactory = fn(&CodecParameters) -> Result>; + +/// One codec's registration. +#[derive(Clone)] +pub struct CodecInfo { + /// The id this claims. + pub id: CodecId, + /// How to build a decoder for it. + pub decoder_factory: Option, +} + +impl CodecInfo { + /// An empty registration for `id`. + pub fn new(id: CodecId) -> CodecInfo { + CodecInfo { + id, + decoder_factory: None, + } + } + + /// The same registration, with a decoder. + pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo { + self.decoder_factory = Some(factory); + self + } +} + +/// The codecs a caller has registered, in registration order per id. +/// +/// The replica builds one of these per AC-3 segment, registers that crate's +/// codecs into it and asks for the first decoder that claims the parameters. +#[derive(Clone, Default)] +pub struct CodecRegistry { + by_id: HashMap>, +} + +impl CodecRegistry { + /// An empty registry. + pub fn new() -> CodecRegistry { + CodecRegistry::default() + } + + /// Add one codec. + pub fn register(&mut self, info: CodecInfo) { + self.by_id.entry(info.id.clone()).or_default().push(info); + } + + /// True when something registered can decode `id`. + pub fn has_decoder(&self, id: &CodecId) -> bool { + self.by_id + .get(id) + .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some())) + } + + /// A decoder from the first registration that offers one. + pub fn first_decoder(&self, params: &CodecParameters) -> Result> { + let factory = self + .by_id + .get(¶ms.codec_id) + .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory)) + .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?; + factory(params) + } +} + +/// A [`Decoder`] over one of the family's own, converting the frames on the way +/// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap. +pub struct EcDecoder { + id: CodecId, + inner: Box, +} + +impl EcDecoder { + /// Wrap `inner`, which decodes the codec named `id`. + pub fn new(id: CodecId, inner: Box) -> EcDecoder { + EcDecoder { id, inner } + } +} + +impl Decoder for EcDecoder { + fn codec_id(&self) -> &CodecId { + &self.id + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + Ok(self.inner.send_packet(packet)?) + } + + fn receive_frame(&mut self) -> Result { + Ok(self.inner.receive_frame()?.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A decoder that answers one frame per packet, for the registry test. + struct Stub(CodecId); + + impl Decoder for Stub { + fn codec_id(&self) -> &CodecId { + &self.0 + } + + fn send_packet(&mut self, _packet: &Packet) -> Result<()> { + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + Err(Error::NeedMore) + } + } + + fn stub(params: &CodecParameters) -> Result> { + Ok(Box::new(Stub(params.codec_id.clone()))) + } + + #[test] + fn the_registry_hands_back_what_was_registered_and_names_what_was_not() { + let mut registry = CodecRegistry::new(); + registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub)); + let params = CodecParameters::audio(CodecId::new("ac3")); + let mut decoder = registry.first_decoder(¶ms).unwrap(); + assert_eq!(decoder.codec_id().as_str(), "ac3"); + assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore))); + assert!(registry.has_decoder(&CodecId::new("ac3"))); + + let missing = CodecParameters::audio(CodecId::new("truehd")); + assert!(matches!( + registry.first_decoder(&missing), + Err(Error::CodecNotFound(id)) if id == "truehd" + )); + } + + #[test] + fn frames_and_errors_cross_the_boundary_intact() { + let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4); + let video = + ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap(); + let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else { + panic!("a video frame stays a video frame"); + }; + assert_eq!((frame.width, frame.height), (1, 1)); + assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]); + assert_eq!(frame.planes[0].stride, 4); + + // The one error the replica matches on by name. + assert!(matches!( + Error::from(ec_core::Error::NeedMore), + Error::NeedMore + )); + assert_eq!( + Error::from(ec_core::Error::corrupt("torn")).to_string(), + "invalid data: torn" + ); + } + + #[test] + fn a_packet_is_written_the_way_the_replica_writes_one() { + let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]); + assert_eq!(packet.data.len(), 8); + assert_eq!(packet.time_base, TimeBase::new(1, 90_000)); + } +} diff --git a/shims/oxideav-sub-image/Cargo.toml b/shims/oxideav-sub-image/Cargo.toml new file mode 100644 index 00000000..c4ed0e40 --- /dev/null +++ b/shims/oxideav-sub-image/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "oxideav-sub-image" +description = "Compatibility shim: the oxideav-sub-image PGS surface edith consumes, over ec-pgs." +version = "0.0.7" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-pgs = { path = "../../crates/ec-pgs", version = "0.1.0" } +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } + +[dev-dependencies] +oxideav-subtitle = { path = "../oxideav-subtitle", version = "0.1.2" } +oxideav-ass = { path = "../oxideav-ass", version = "0.0.9" } diff --git a/shims/oxideav-sub-image/src/lib.rs b/shims/oxideav-sub-image/src/lib.rs new file mode 100644 index 00000000..eb7508b6 --- /dev/null +++ b/shims/oxideav-sub-image/src/lib.rs @@ -0,0 +1,80 @@ +//! `oxideav-sub-image` as edith consumes it, over [`ec_pgs`]. +//! +//! Four items: [`PGS_CODEC_ID`], [`pgs::make_decoder`], [`pgs::SEG_PCS`] and +//! [`pgs::SEG_END`] — the replica reads a Matroska block's segments, puts the +//! `.sup` framing back on and stops at the `END` that closes the first set +//! which composes something, then decodes that through the trait. + +#![forbid(unsafe_code)] + +/// The codec id a PGS track is named by. +pub const PGS_CODEC_ID: &str = "pgs"; + +/// Presentation Graphic Stream. +pub mod pgs { + use oxideav_core::{CodecId, CodecParameters, Decoder, EcDecoder, Result}; + + pub use ec_pgs::{SEG_END, SEG_ODS, SEG_PCS, SEG_PDS, SEG_WDS}; + + /// A PGS decoder: `.sup`-framed segments in, one RGBA canvas per display + /// set out. The parameters say nothing a PGS stream does not state itself. + pub fn make_decoder(_params: &CodecParameters) -> Result> { + Ok(Box::new(EcDecoder::new( + CodecId::new(crate::PGS_CODEC_ID), + Box::new(ec_pgs::PgsDecoder::new()), + ))) + } +} + +#[cfg(test)] +mod tests { + use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase}; + + use super::*; + + /// The `.sup` framing the replica rebuilds around a Matroska block. + fn segment(kind: u8, body: &[u8]) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(b"PG"); + out.extend_from_slice(&[0; 8]); + out.push(kind); + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); + out.extend_from_slice(body); + out + } + + #[test] + fn a_display_set_decodes_through_the_replica_s_own_call_shape() { + let params = CodecParameters::subtitle(CodecId::new(PGS_CODEC_ID)); + let mut decoder = pgs::make_decoder(¶ms).unwrap(); + + // A 4x2 canvas with one 2x1 opaque-white object at (1, 0). + let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1]; + pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]); + let pds = vec![0, 0, 1, 235, 128, 128, 255]; + let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00]; + let mut ods = vec![0, 0, 0, 0xC0]; + ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); + ods.extend_from_slice(&[0, 2, 0, 1]); + ods.extend_from_slice(&rle); + let mut sup = segment(pgs::SEG_PCS, &pcs); + // The composition object count is where the replica reads whether the + // set shows anything. + assert_eq!(pcs[10], 1); + sup.extend(segment(pgs::SEG_PDS, &pds)); + sup.extend(segment(pgs::SEG_ODS, &ods)); + sup.extend(segment(pgs::SEG_END, &[])); + + decoder + .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) + .unwrap(); + let Ok(Frame::Video(frame)) = decoder.receive_frame() else { + panic!("a display set is a picture"); + }; + assert_eq!((frame.width, frame.height), (4, 2)); + let data = frame.planes.into_iter().next().unwrap().data; + assert_eq!(data.len(), 4 * 2 * 4); + assert_eq!(&data[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); + assert_eq!(&data[0..4], &[0, 0, 0, 0]); + } +} diff --git a/shims/oxideav-sub-image/tests/replica_call_shapes.rs b/shims/oxideav-sub-image/tests/replica_call_shapes.rs new file mode 100644 index 00000000..8879674a --- /dev/null +++ b/shims/oxideav-sub-image/tests/replica_call_shapes.rs @@ -0,0 +1,157 @@ +//! The replica's own call shapes, transcribed, so a swap is proven at compile +//! time and not at the first PGS track a user opens. +//! +//! Every block below is the engine's code with its surroundings removed: +//! `subtitle.rs:33` (`plain_text`), `:90-125` (`CueImage::rgba` — the `.sup` +//! framing rebuilt around a Matroska block and decoded), `:518` (`srt::parse` +//! around a synthetic timing line), `:555` (`oxideav_ass::parse`) and +//! `:603-607` (the four parsers as one function-pointer type). If any of them +//! stops compiling against these shims, the swap has broken, whatever the +//! crates' own tests say. + +use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase}; +use oxideav_subtitle::ir::plain_text; + +/// `subtitle.rs:604-607` — the extension-to-parser table, as one `fn` type. +type Parse = fn(&[u8]) -> oxideav_core::Result; + +fn parser_for(ext: &str) -> Option { + match ext { + "srt" => Some(oxideav_subtitle::srt::parse), + "vtt" | "webvtt" => Some(oxideav_subtitle::webvtt::parse), + "ass" | "ssa" => Some(oxideav_ass::parse), + _ => None, + } +} + +#[test] +fn the_parser_table_and_the_cue_fields_the_replica_reads() { + for (ext, doc) in [ + ("srt", "1\n00:00:01,000 --> 00:00:02,000\nhi\n"), + ( + "vtt", + "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nhi\n", + ), + ( + "ass", + "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ + Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi\n", + ), + ] { + let parse = parser_for(ext).expect("the replica routes these four extensions"); + let track = parse(doc.as_bytes()).unwrap(); + // `subtitle.rs:623-632`: cues mapped onto the engine's own `Cue`. + let cues: Vec<(i64, i64, String)> = track + .cues + .iter() + .map(|c| (c.start_us, c.end_us, plain_text(&c.segments))) + .collect(); + assert_eq!(cues, vec![(1_000_000, 2_000_000, "hi".to_owned())], "{ext}"); + } + assert!(parser_for("txt").is_none()); +} + +/// `subtitle.rs:516-527` — an `S_TEXT/UTF8` block's markup resolved by wrapping +/// it in a synthetic SRT. +#[test] +fn a_matroska_text_block_is_resolved_through_the_srt_parser() { + let text = "tilted and plain"; + let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); + let resolved = match oxideav_subtitle::srt::parse(doc.as_bytes()) { + Ok(track) => track + .cues + .first() + .map(|c| plain_text(&c.segments)) + .unwrap_or_default(), + Err(_) => text.trim_end().to_owned(), + }; + assert_eq!(resolved, "tilted and plain"); +} + +/// `subtitle.rs:89-125` — a Matroska PGS block, framed back into a `.sup` and +/// decoded to straight RGBA the size of the disc's own canvas. +#[test] +fn a_matroska_pgs_block_decodes_the_way_the_replica_decodes_one() { + let set = matroska_block(); + let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID)); + let mut decoder = oxideav_sub_image::pgs::make_decoder(¶ms).unwrap(); + let mut sup = Vec::with_capacity(set.len() + 64); + let mut shows = false; + for (kind, body) in segments(&set).unwrap() { + sup.extend_from_slice(b"PG"); + sup.extend_from_slice(&[0; 8]); + sup.push(kind); + sup.extend_from_slice(&(body.len() as u16).to_be_bytes()); + sup.extend_from_slice(body); + match kind { + oxideav_sub_image::pgs::SEG_PCS => { + shows = body.get(10).is_some_and(|&n| n > 0); + } + oxideav_sub_image::pgs::SEG_END if shows => break, + _ => {} + } + } + decoder + .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) + .unwrap(); + let rgba = match decoder.receive_frame().unwrap() { + Frame::Video(frame) => frame.planes.into_iter().next().map(|p| p.data), + _ => None, + } + .expect("a display set is a picture"); + // The whole canvas, transparent where the cue paints nothing. + assert_eq!(rgba.len(), 4 * 2 * 4); + assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); + assert_eq!(&rgba[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); + + // The erase set after the composition must not be what gets decoded: the + // loop above stops at the `END` that closes the showing set. + let all: Vec = set.clone(); + assert!( + segments(&all).unwrap().len() > 5, + "the block holds both sets" + ); +} + +/// `subtitle.rs:131-140` — the segments of a display set as a Matroska block +/// holds them: type, big-endian size, body. +fn segments(set: &[u8]) -> Option> { + let mut out = Vec::new(); + let mut at = 0; + while at < set.len() { + let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize; + out.push((set[at], set.get(at + 3..at + 3 + size)?)); + at += 3 + size; + } + Some(out) +} + +/// A block holding a composition *and* the erase that follows it — the packing +/// the replica's comment warns about. +fn matroska_block() -> Vec { + let block = |kind: u8, body: &[u8]| { + let mut out = vec![kind]; + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); + out.extend_from_slice(body); + out + }; + let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1]; + pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]); + let pds = vec![0, 0, 1, 235, 128, 128, 255]; + let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00]; + let mut ods = vec![0, 0, 0, 0xC0]; + ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); + ods.extend_from_slice(&[0, 2, 0, 1]); + ods.extend_from_slice(&rle); + // The erase: a composition with no objects at all. + let erase = vec![0, 4, 0, 2, 0x10, 0, 1, 0, 0, 0, 0]; + [ + block(oxideav_sub_image::pgs::SEG_PCS, &pcs), + block(oxideav_sub_image::pgs::SEG_PDS, &pds), + block(oxideav_sub_image::pgs::SEG_ODS, &ods), + block(oxideav_sub_image::pgs::SEG_END, &[]), + block(oxideav_sub_image::pgs::SEG_PCS, &erase), + block(oxideav_sub_image::pgs::SEG_END, &[]), + ] + .concat() +} diff --git a/shims/oxideav-subtitle/Cargo.toml b/shims/oxideav-subtitle/Cargo.toml new file mode 100644 index 00000000..bacce801 --- /dev/null +++ b/shims/oxideav-subtitle/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "oxideav-subtitle" +description = "Compatibility shim: the oxideav-subtitle surface edith consumes, over ec-subs." +version = "0.1.2" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" } +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } diff --git a/shims/oxideav-subtitle/src/lib.rs b/shims/oxideav-subtitle/src/lib.rs new file mode 100644 index 00000000..b060cb7f --- /dev/null +++ b/shims/oxideav-subtitle/src/lib.rs @@ -0,0 +1,64 @@ +//! `oxideav-subtitle` as edith consumes it, over [`ec_subs`]. +//! +//! Three items and their types: `ir::plain_text`, `ir::SubtitleTrack`, +//! `srt::parse` and `webvtt::parse`. The IR is `ec_subs`'s own — the field +//! names were chosen to match, so this is a re-export and not a conversion — +//! and the only adapter is the error type, because the replica writes the parse +//! functions as `fn(&[u8]) -> oxideav_core::Result` and takes +//! their address. + +#![forbid(unsafe_code)] + +/// The cue IR, which is [`ec_subs::ir`] under its incumbent name. +pub mod ir { + pub use ec_subs::ir::{ + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, + plain_text, + }; +} + +pub use ir::{SourceFormat, SubtitleTrack}; + +/// SubRip. +pub mod srt { + use oxideav_core::Result; + + use crate::ir::SubtitleTrack; + + /// Parse a SubRip document. + pub fn parse(bytes: &[u8]) -> Result { + Ok(ec_subs::srt::parse(bytes)?) + } +} + +/// WebVTT. +pub mod webvtt { + use oxideav_core::Result; + + use crate::ir::SubtitleTrack; + + /// Parse a WebVTT document. + pub fn parse(bytes: &[u8]) -> Result { + Ok(ec_subs::webvtt::parse(bytes)?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The replica takes these as function pointers of one type and calls + /// `plain_text` on whatever comes back; that is the whole contract. + #[test] + fn the_parsers_are_interchangeable_function_pointers() { + type Parse = fn(&[u8]) -> oxideav_core::Result; + for parse in [srt::parse as Parse, webvtt::parse as Parse] { + let track = parse(b"1\n00:00:01,000 --> 00:00:02,000\nhi\n").unwrap(); + assert_eq!(ir::plain_text(&track.cues[0].segments), "hi"); + assert_eq!(track.cues[0].start_us, 1_000_000); + } + // A file of the wrong kind is an error the replica can print. + let error = srt::parse(b"prose, not subtitles").unwrap_err(); + assert!(!error.to_string().is_empty()); + } +}