SRT/WebVTT/ASS parsing, PGS bitmaps, oxideav shims
Browse files at this commit1f445c1f920cf6fce50436d34930dee712776e78Parent: 2c0d9b8- feat
- SRT/WebVTT/ASS parsing, PGS bitmaps, oxideav shims
21 changed files +3338 -0
- crates/ec-ass/Cargo.toml +11 -0
- crates/ec-ass/src/lib.rs +562 -0
- crates/ec-pgs/Cargo.toml +10 -0
- crates/ec-pgs/src/lib.rs +578 -0
- crates/ec-subs/Cargo.toml +14 -0
- crates/ec-subs/src/ir.rs +270 -0
- crates/ec-subs/src/lib.rs +33 -0
- crates/ec-subs/src/markup.rs +474 -0
- crates/ec-subs/src/srt.rs +131 -0
- crates/ec-subs/src/webvtt.rs +174 -0
- crates/ec-subs/tests/real_library.rs +142 -0
- scripts/gen-subtitle-fixtures.sh +65 -0
- shims/oxideav-ass/Cargo.toml +13 -0
- shims/oxideav-ass/src/lib.rs +37 -0
- shims/oxideav-core/Cargo.toml +11 -0
- shims/oxideav-core/src/lib.rs +484 -0
- shims/oxideav-sub-image/Cargo.toml +16 -0
- shims/oxideav-sub-image/src/lib.rs +80 -0
- shims/oxideav-sub-image/tests/replica_call_shapes.rs +157 -0
- shims/oxideav-subtitle/Cargo.toml +12 -0
- shims/oxideav-subtitle/src/lib.rs +64 -0
crates/ec-ass/Cargo.tomladded+11 -0
| @@ -0,0 +1,11 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-ass" | ||
| 3 | +description = "Advanced SubStation Alpha (ASS/SSA) parsing into the edith_codecs subtitle IR." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
| 11 | +ec-subs = { path = "../ec-subs", version = "0.1.0" } | ||
crates/ec-ass/src/lib.rsadded+562 -0
| @@ -0,0 +1,562 @@ | |||
| 1 | +//! Advanced SubStation Alpha, and the SSA v4 it grew out of. | ||
| 2 | +//! | ||
| 3 | +//! An `.ass` is an INI: `[Script Info]` keys, a `[V4+ Styles]` table and an | ||
| 4 | +//! `[Events]` table, each table declaring its own column order on a `Format:` | ||
| 5 | +//! line. That declaration is why this parses the header rather than assuming | ||
| 6 | +//! positions — Aegisub's order is the usual one, but the file gets to say. | ||
| 7 | +//! | ||
| 8 | +//! The cue text carries override tags in braces: `{\i1}` turns italics on until | ||
| 9 | +//! `{\i0}`, `{\an8}` puts the line at the top, `{\pos(x,y)}` puts it exactly, | ||
| 10 | +//! `{\k30}` is a karaoke beat, and `{\p1}` switches the *text* to vector | ||
| 11 | +//! drawing commands until `{\p0}`. Those become [`ec_subs::Segment`] runs, so | ||
| 12 | +//! a caller that wants words ([`ec_subs::plain_text`]) gets words and a caller | ||
| 13 | +//! that will one day draw them has the tree. | ||
| 14 | +//! | ||
| 15 | +//! What the format states and this drops on the floor: transforms, animation, | ||
| 16 | +//! clipping and every other override that only a renderer can honour. They are | ||
| 17 | +//! kept verbatim as [`ec_subs::Segment::Raw`] rather than deleted. | ||
| 18 | + | ||
| 19 | +#![forbid(unsafe_code)] | ||
| 20 | + | ||
| 21 | +use ec_core::{Error, Result}; | ||
| 22 | +use ec_subs::ir::{ | ||
| 23 | + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, | ||
| 24 | +}; | ||
| 25 | +use ec_subs::{decode, parse_clock}; | ||
| 26 | + | ||
| 27 | +/// Parse an ASS or SSA document. | ||
| 28 | +/// | ||
| 29 | +/// `Err` only when there is no `Dialogue:` line and no `[Events]` section in | ||
| 30 | +/// the whole document — that is not this format. Torn rows are skipped and | ||
| 31 | +/// counted in [`SubtitleTrack::skipped`], because one bad line in a | ||
| 32 | +/// twelve-hundred-line script is not a reason to lose the other eleven hundred. | ||
| 33 | +pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> { | ||
| 34 | + let text = decode(bytes); | ||
| 35 | + let mut track = SubtitleTrack::new().with_source(SourceFormat::AssOrSsa); | ||
| 36 | + let mut section = Section::None; | ||
| 37 | + let mut style_format: Vec<String> = Vec::new(); | ||
| 38 | + let mut event_format: Vec<String> = Vec::new(); | ||
| 39 | + let mut header_end = 0; | ||
| 40 | + let mut in_events = false; | ||
| 41 | + let mut saw_events = false; | ||
| 42 | + for line in text.split_inclusive('\n') { | ||
| 43 | + let trimmed = line.trim(); | ||
| 44 | + // Everything up to the first event row is the script header — what a | ||
| 45 | + // Matroska track carries as `CodecPrivate`. | ||
| 46 | + if trimmed.starts_with("Dialogue:") || trimmed.starts_with("Comment:") { | ||
| 47 | + in_events = true; | ||
| 48 | + } else if !in_events { | ||
| 49 | + header_end += line.len(); | ||
| 50 | + } | ||
| 51 | + if trimmed.is_empty() || trimmed.starts_with(';') || trimmed.starts_with('!') { | ||
| 52 | + continue; | ||
| 53 | + } | ||
| 54 | + if let Some(name) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { | ||
| 55 | + section = Section::of(name); | ||
| 56 | + saw_events |= matches!(section, Section::Events); | ||
| 57 | + continue; | ||
| 58 | + } | ||
| 59 | + let Some((key, value)) = trimmed.split_once(':') else { | ||
| 60 | + continue; | ||
| 61 | + }; | ||
| 62 | + let value = value.trim(); | ||
| 63 | + match (section, key.trim()) { | ||
| 64 | + (Section::ScriptInfo, key) => { | ||
| 65 | + track.metadata.push((snake_case(key), value.to_owned())); | ||
| 66 | + } | ||
| 67 | + (Section::Styles { .. }, "Format") => style_format = fields(value), | ||
| 68 | + (Section::Styles { v4 }, "Style") => match style(&style_format, value, v4) { | ||
| 69 | + Some(style) => track.styles.push(style), | ||
| 70 | + None => track.skipped += 1, | ||
| 71 | + }, | ||
| 72 | + (Section::Events, "Format") => event_format = fields(value), | ||
| 73 | + (Section::Events, "Dialogue") => { | ||
| 74 | + let wrap_style = track | ||
| 75 | + .metadata | ||
| 76 | + .iter() | ||
| 77 | + .find(|(k, _)| k == "wrap_style") | ||
| 78 | + .and_then(|(_, v)| v.parse::<u8>().ok()) | ||
| 79 | + .unwrap_or(0); | ||
| 80 | + match dialogue(&event_format, value, wrap_style) { | ||
| 81 | + Some(cue) => track.cues.push(cue), | ||
| 82 | + None => track.skipped += 1, | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + // `Comment:` events are the script's own scratch lines: real rows | ||
| 86 | + // of the events table, never on screen. | ||
| 87 | + _ => {} | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + if track.cues.is_empty() && !saw_events { | ||
| 91 | + return Err(Error::corrupt( | ||
| 92 | + "no [Events] section: not an ASS or SSA script", | ||
| 93 | + )); | ||
| 94 | + } | ||
| 95 | + track.extradata = text.as_bytes()[..header_end.min(text.len())].to_vec(); | ||
| 96 | + Ok(track) | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +#[derive(Clone, Copy)] | ||
| 100 | +enum Section { | ||
| 101 | + None, | ||
| 102 | + ScriptInfo, | ||
| 103 | + /// `v4` marks the SSA-era table, whose alignment codes differ. | ||
| 104 | + Styles { | ||
| 105 | + v4: bool, | ||
| 106 | + }, | ||
| 107 | + Events, | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +impl Section { | ||
| 111 | + fn of(name: &str) -> Section { | ||
| 112 | + let lower = name.trim().to_ascii_lowercase(); | ||
| 113 | + match lower.as_str() { | ||
| 114 | + "script info" => Section::ScriptInfo, | ||
| 115 | + "events" => Section::Events, | ||
| 116 | + "v4 styles" => Section::Styles { v4: true }, | ||
| 117 | + _ if lower.ends_with("styles") => Section::Styles { v4: false }, | ||
| 118 | + _ => Section::None, | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// `PlayResX` → `play_res_x`, `Original Script` → `original_script`: metadata | ||
| 124 | +/// keys are one shape whichever way the script wrote them. | ||
| 125 | +fn snake_case(key: &str) -> String { | ||
| 126 | + let mut out = String::with_capacity(key.len() + 4); | ||
| 127 | + let mut previous = ' '; | ||
| 128 | + for c in key.trim().chars() { | ||
| 129 | + match c { | ||
| 130 | + ' ' | '-' => out.push('_'), | ||
| 131 | + c => { | ||
| 132 | + if c.is_ascii_uppercase() | ||
| 133 | + && (previous.is_ascii_lowercase() || previous.is_ascii_digit()) | ||
| 134 | + { | ||
| 135 | + out.push('_'); | ||
| 136 | + } | ||
| 137 | + out.push(c.to_ascii_lowercase()); | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + previous = c; | ||
| 141 | + } | ||
| 142 | + out | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +fn fields(value: &str) -> Vec<String> { | ||
| 146 | + value.split(',').map(|f| f.trim().to_owned()).collect() | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// Column `name` of a row, by the order the table's `Format:` line declared. | ||
| 150 | +fn column<'a>(format: &[String], values: &'a [&'a str], name: &str) -> Option<&'a str> { | ||
| 151 | + let at = format.iter().position(|f| f.eq_ignore_ascii_case(name))?; | ||
| 152 | + values.get(at).map(|v| v.trim()) | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +fn style(format: &[String], row: &str, v4: bool) -> Option<SubtitleStyle> { | ||
| 156 | + // A table with no `Format:` line at all uses the order every tool writes. | ||
| 157 | + const DEFAULT: &str = "Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,\ | ||
| 158 | + BackColour,Bold,Italic,Underline,StrikeOut,ScaleX,ScaleY,Spacing,Angle,BorderStyle,\ | ||
| 159 | + Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding"; | ||
| 160 | + let fallback = fields(DEFAULT); | ||
| 161 | + let format = if format.is_empty() { &fallback } else { format }; | ||
| 162 | + let values: Vec<&str> = row.split(',').collect(); | ||
| 163 | + let name = column(format, &values, "Name")?; | ||
| 164 | + let number = |key: &str| column(format, &values, key).and_then(|v| v.parse::<f32>().ok()); | ||
| 165 | + let margin = |key: &str| column(format, &values, key).and_then(|v| v.parse::<i32>().ok()); | ||
| 166 | + let flag = |key: &str| column(format, &values, key).is_some_and(|v| v.trim() != "0"); | ||
| 167 | + Some(SubtitleStyle { | ||
| 168 | + name: name.to_owned(), | ||
| 169 | + font_family: column(format, &values, "Fontname").map(str::to_owned), | ||
| 170 | + font_size: number("Fontsize"), | ||
| 171 | + primary_color: column(format, &values, "PrimaryColour").and_then(parse_color), | ||
| 172 | + outline_color: column(format, &values, "OutlineColour") | ||
| 173 | + .or_else(|| column(format, &values, "TertiaryColour")) | ||
| 174 | + .and_then(parse_color), | ||
| 175 | + back_color: column(format, &values, "BackColour").and_then(parse_color), | ||
| 176 | + bold: flag("Bold"), | ||
| 177 | + italic: flag("Italic"), | ||
| 178 | + underline: flag("Underline"), | ||
| 179 | + strike: flag("StrikeOut"), | ||
| 180 | + align: column(format, &values, "Alignment") | ||
| 181 | + .and_then(|v| v.parse().ok()) | ||
| 182 | + .map(|code| alignment(code, v4)) | ||
| 183 | + .unwrap_or_default(), | ||
| 184 | + margin_l: margin("MarginL"), | ||
| 185 | + margin_r: margin("MarginR"), | ||
| 186 | + margin_v: margin("MarginV"), | ||
| 187 | + outline: number("Outline"), | ||
| 188 | + shadow: number("Shadow"), | ||
| 189 | + }) | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +/// ASS alignment is the numeric keypad (`\an`): 1/4/7 left, 2/5/8 centre, | ||
| 193 | +/// 3/6/9 right. SSA v4 used a different code with the same three columns in | ||
| 194 | +/// its low two bits. | ||
| 195 | +fn alignment(code: i32, v4: bool) -> TextAlign { | ||
| 196 | + let column = match v4 { | ||
| 197 | + true => code & 0b11, | ||
| 198 | + false => (code - 1) % 3 + 1, | ||
| 199 | + }; | ||
| 200 | + match column { | ||
| 201 | + 1 => TextAlign::Left, | ||
| 202 | + 2 => TextAlign::Center, | ||
| 203 | + 3 => TextAlign::Right, | ||
| 204 | + _ => TextAlign::default(), | ||
| 205 | + } | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +/// `&HAABBGGRR&`: BGR with a *transparency* byte, so 0 is opaque. | ||
| 209 | +fn parse_color(value: &str) -> Option<(u8, u8, u8, u8)> { | ||
| 210 | + let digits: String = value | ||
| 211 | + .trim() | ||
| 212 | + .trim_start_matches(['&', 'H', 'h']) | ||
| 213 | + .trim_end_matches('&') | ||
| 214 | + .chars() | ||
| 215 | + .take_while(char::is_ascii_hexdigit) | ||
| 216 | + .collect(); | ||
| 217 | + let packed = u32::from_str_radix(&digits, 16).ok()?; | ||
| 218 | + Some(( | ||
| 219 | + (packed & 0xFF) as u8, | ||
| 220 | + ((packed >> 8) & 0xFF) as u8, | ||
| 221 | + ((packed >> 16) & 0xFF) as u8, | ||
| 222 | + 255 - ((packed >> 24) & 0xFF) as u8, | ||
| 223 | + )) | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +fn dialogue(format: &[String], row: &str, wrap_style: u8) -> Option<SubtitleCue> { | ||
| 227 | + const DEFAULT: &str = "Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text"; | ||
| 228 | + let fallback = fields(DEFAULT); | ||
| 229 | + let format = if format.is_empty() { &fallback } else { format }; | ||
| 230 | + // `Text` is last and holds commas of its own, so the row is split into | ||
| 231 | + // exactly as many fields as the table declares and no further. | ||
| 232 | + let values: Vec<&str> = row.splitn(format.len(), ',').collect(); | ||
| 233 | + let start_us = parse_clock(column(format, &values, "Start")?)?; | ||
| 234 | + let end_us = parse_clock(column(format, &values, "End")?)?; | ||
| 235 | + let text = column(format, &values, "Text").unwrap_or_default(); | ||
| 236 | + let (segments, positioning) = body(text, wrap_style); | ||
| 237 | + Some(SubtitleCue { | ||
| 238 | + start_us, | ||
| 239 | + end_us: end_us.max(start_us), | ||
| 240 | + style_ref: column(format, &values, "Style") | ||
| 241 | + .filter(|s| !s.is_empty()) | ||
| 242 | + .map(str::to_owned), | ||
| 243 | + positioning, | ||
| 244 | + segments, | ||
| 245 | + }) | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +/// The state an override block leaves behind for the runs after it. | ||
| 249 | +#[derive(Clone, Default)] | ||
| 250 | +struct Overrides { | ||
| 251 | + bold: bool, | ||
| 252 | + italic: bool, | ||
| 253 | + underline: bool, | ||
| 254 | + strike: bool, | ||
| 255 | + color: Option<(u8, u8, u8)>, | ||
| 256 | + family: Option<String>, | ||
| 257 | + size: Option<f32>, | ||
| 258 | + karaoke: Option<u32>, | ||
| 259 | + /// `\p1` and up: the text is a drawing, not words. | ||
| 260 | + drawing: bool, | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +/// One `Text` field into runs, plus whatever positioning its overrides state. | ||
| 264 | +fn body(text: &str, wrap_style: u8) -> (Vec<Segment>, Option<CuePosition>) { | ||
| 265 | + let mut out: Vec<Segment> = Vec::new(); | ||
| 266 | + let mut state = Overrides::default(); | ||
| 267 | + let mut position = CuePosition::default(); | ||
| 268 | + let mut positioned = false; | ||
| 269 | + let mut run = String::new(); | ||
| 270 | + let mut rest = text; | ||
| 271 | + while let Some(at) = rest.find('{') { | ||
| 272 | + let (before, after) = rest.split_at(at); | ||
| 273 | + push_text(&mut out, &mut run, before, &state, wrap_style); | ||
| 274 | + let Some(end) = after.find('}') else { | ||
| 275 | + // An unbalanced brace: the rest of the line is text, braces and all. | ||
| 276 | + run.push_str(after); | ||
| 277 | + rest = ""; | ||
| 278 | + break; | ||
| 279 | + }; | ||
| 280 | + let block = &after[1..end]; | ||
| 281 | + rest = &after[end + 1..]; | ||
| 282 | + flush(&mut out, &mut run, &state); | ||
| 283 | + if let Some(unknown) = overrides(block, &mut state, &mut position, &mut positioned) { | ||
| 284 | + out.push(Segment::Raw(unknown)); | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + push_text(&mut out, &mut run, rest, &state, wrap_style); | ||
| 288 | + flush(&mut out, &mut run, &state); | ||
| 289 | + (out, positioned.then_some(position)) | ||
| 290 | +} | ||
| 291 | + | ||
| 292 | +/// Apply one brace block's overrides. Returns the overrides this does not | ||
| 293 | +/// model, verbatim, for a [`Segment::Raw`]. | ||
| 294 | +fn overrides( | ||
| 295 | + block: &str, | ||
| 296 | + state: &mut Overrides, | ||
| 297 | + position: &mut CuePosition, | ||
| 298 | + positioned: &mut bool, | ||
| 299 | +) -> Option<String> { | ||
| 300 | + let mut unknown = String::new(); | ||
| 301 | + for tag in block.split('\\').skip(1) { | ||
| 302 | + let tag = tag.trim_end(); | ||
| 303 | + if tag.is_empty() { | ||
| 304 | + continue; | ||
| 305 | + } | ||
| 306 | + let Some((name, arg)) = split_tag(tag) else { | ||
| 307 | + unknown.push_str(&format!("\\{tag}")); | ||
| 308 | + continue; | ||
| 309 | + }; | ||
| 310 | + let flag = || !arg.trim().trim_start_matches('0').is_empty(); | ||
| 311 | + match name { | ||
| 312 | + "b" => state.bold = flag(), | ||
| 313 | + "i" => state.italic = flag(), | ||
| 314 | + "u" => state.underline = flag(), | ||
| 315 | + "s" => state.strike = flag(), | ||
| 316 | + "c" | "1c" => state.color = parse_color(arg).map(|(r, g, b, _)| (r, g, b)), | ||
| 317 | + "fn" => state.family = Some(arg.trim().to_owned()).filter(|f| !f.is_empty()), | ||
| 318 | + "fs" => state.size = arg.trim().parse().ok(), | ||
| 319 | + "k" | "K" | "kf" | "ko" => state.karaoke = arg.trim().parse().ok(), | ||
| 320 | + "p" => state.drawing = flag(), | ||
| 321 | + "an" => { | ||
| 322 | + if let Ok(code) = arg.trim().parse::<i32>() { | ||
| 323 | + position.align = alignment(code, false); | ||
| 324 | + *positioned = true; | ||
| 325 | + } | ||
| 326 | + } | ||
| 327 | + "a" => { | ||
| 328 | + if let Ok(code) = arg.trim().parse::<i32>() { | ||
| 329 | + position.align = alignment(code, true); | ||
| 330 | + *positioned = true; | ||
| 331 | + } | ||
| 332 | + } | ||
| 333 | + "pos" | "move" => { | ||
| 334 | + // `\move(x1,y1,x2,y2,…)` starts where `\pos(x,y)` would put it. | ||
| 335 | + let mut parts = arg | ||
| 336 | + .trim_matches(['(', ')']) | ||
| 337 | + .split(',') | ||
| 338 | + .filter_map(|n| n.trim().parse().ok()); | ||
| 339 | + position.x = parts.next(); | ||
| 340 | + position.y = parts.next(); | ||
| 341 | + *positioned = true; | ||
| 342 | + if name == "move" { | ||
| 343 | + unknown.push_str(&format!("\\{tag}")); | ||
| 344 | + } | ||
| 345 | + } | ||
| 346 | + _ => unknown.push_str(&format!("\\{tag}")), | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | + (!unknown.is_empty()).then(|| format!("{{{unknown}}}")) | ||
| 350 | +} | ||
| 351 | + | ||
| 352 | +/// An override into its name and its argument. | ||
| 353 | +/// | ||
| 354 | +/// The names overlap — `\b` is bold and `\blur` is a blur — so a one-letter | ||
| 355 | +/// name is only that name when what follows it could be its argument: a | ||
| 356 | +/// number, a `&H` colour, a bracketed list, or nothing at all. Everything else | ||
| 357 | +/// falls through to [`Segment::Raw`] rather than being half-read. | ||
| 358 | +fn split_tag(tag: &str) -> Option<(&str, &str)> { | ||
| 359 | + const NAMES: [&str; 16] = [ | ||
| 360 | + "move", "pos", "fn", "fs", "kf", "ko", "an", "1c", "c", "b", "i", "u", "s", "k", "p", "a", | ||
| 361 | + ]; | ||
| 362 | + NAMES.iter().find_map(|name| { | ||
| 363 | + let arg = tag.strip_prefix(name)?; | ||
| 364 | + // A font name is letters, so `\fn` takes whatever follows it. | ||
| 365 | + let plausible = *name == "fn" | ||
| 366 | + || arg.is_empty() | ||
| 367 | + || arg.starts_with(|c: char| c.is_ascii_digit() || matches!(c, '-' | '&' | '(' | '.')); | ||
| 368 | + plausible.then_some((*name, arg)) | ||
| 369 | + }) | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +/// Plain text between override blocks, with the three escapes ASS gives it. | ||
| 373 | +fn push_text( | ||
| 374 | + out: &mut Vec<Segment>, | ||
| 375 | + run: &mut String, | ||
| 376 | + text: &str, | ||
| 377 | + state: &Overrides, | ||
| 378 | + wrap_style: u8, | ||
| 379 | +) { | ||
| 380 | + let mut chars = text.chars().peekable(); | ||
| 381 | + while let Some(c) = chars.next() { | ||
| 382 | + if c != '\\' { | ||
| 383 | + run.push(c); | ||
| 384 | + continue; | ||
| 385 | + } | ||
| 386 | + match chars.next() { | ||
| 387 | + // `\N` always breaks; `\n` breaks only where the script asked for | ||
| 388 | + // no automatic wrapping (`WrapStyle: 2`), and is a space otherwise, | ||
| 389 | + // which is what every renderer does with it. | ||
| 390 | + Some('N') => { | ||
| 391 | + flush(out, run, state); | ||
| 392 | + out.push(Segment::LineBreak); | ||
| 393 | + } | ||
| 394 | + Some('n') if wrap_style == 2 => { | ||
| 395 | + flush(out, run, state); | ||
| 396 | + out.push(Segment::LineBreak); | ||
| 397 | + } | ||
| 398 | + Some('n') => run.push(' '), | ||
| 399 | + Some('h') => run.push('\u{a0}'), | ||
| 400 | + Some(other) => { | ||
| 401 | + run.push('\\'); | ||
| 402 | + run.push(other); | ||
| 403 | + } | ||
| 404 | + None => run.push('\\'), | ||
| 405 | + } | ||
| 406 | + } | ||
| 407 | +} | ||
| 408 | + | ||
| 409 | +/// Close the pending run, wrapping it in whatever the overrides asked for. | ||
| 410 | +fn flush(out: &mut Vec<Segment>, run: &mut String, state: &Overrides) { | ||
| 411 | + if run.is_empty() { | ||
| 412 | + return; | ||
| 413 | + } | ||
| 414 | + let text = std::mem::take(run); | ||
| 415 | + // A drawing is shapes, not words: kept whole so a renderer can have it and | ||
| 416 | + // `plain_text` says nothing. | ||
| 417 | + if state.drawing { | ||
| 418 | + out.push(Segment::Raw(text)); | ||
| 419 | + return; | ||
| 420 | + } | ||
| 421 | + let mut segment = vec![Segment::Text(text)]; | ||
| 422 | + if let Some(cs) = state.karaoke { | ||
| 423 | + segment = vec![Segment::Karaoke { | ||
| 424 | + cs, | ||
| 425 | + children: segment, | ||
| 426 | + }]; | ||
| 427 | + } | ||
| 428 | + if state.family.is_some() || state.size.is_some() { | ||
| 429 | + segment = vec![Segment::Font { | ||
| 430 | + family: state.family.clone(), | ||
| 431 | + size: state.size, | ||
| 432 | + children: segment, | ||
| 433 | + }]; | ||
| 434 | + } | ||
| 435 | + if let Some(rgb) = state.color { | ||
| 436 | + segment = vec![Segment::Color { | ||
| 437 | + rgb, | ||
| 438 | + children: segment, | ||
| 439 | + }]; | ||
| 440 | + } | ||
| 441 | + for (on, wrap) in [ | ||
| 442 | + (state.strike, Segment::Strike as fn(Vec<Segment>) -> Segment), | ||
| 443 | + (state.underline, Segment::Underline as fn(_) -> _), | ||
| 444 | + (state.italic, Segment::Italic as fn(_) -> _), | ||
| 445 | + (state.bold, Segment::Bold as fn(_) -> _), | ||
| 446 | + ] { | ||
| 447 | + if on { | ||
| 448 | + segment = vec![wrap(segment)]; | ||
| 449 | + } | ||
| 450 | + } | ||
| 451 | + out.extend(segment); | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +#[cfg(test)] | ||
| 455 | +mod tests { | ||
| 456 | + use super::*; | ||
| 457 | + use ec_subs::plain_text; | ||
| 458 | + | ||
| 459 | + const SCRIPT: &str = "[Script Info]\n\ | ||
| 460 | + Title: A script\n\ | ||
| 461 | + WrapStyle: 0\n\ | ||
| 462 | + PlayResX: 1920\n\ | ||
| 463 | + \n\ | ||
| 464 | + [V4+ Styles]\n\ | ||
| 465 | + Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, \ | ||
| 466 | + Underline, StrikeOut, Alignment, MarginL, MarginR, MarginV, Outline, Shadow, Encoding\n\ | ||
| 467 | + Style: Default,Arial,48,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,2,10,10,20,2,1,1\n\ | ||
| 468 | + \n\ | ||
| 469 | + [Events]\n\ | ||
| 470 | + Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\ | ||
| 471 | + Dialogue: 0,0:00:01.00,0:00:03.50,Default,,0,0,0,,{\\i1}tilted{\\i0} plain\\Nsecond, with comma\n\ | ||
| 472 | + Comment: 0,0:00:04.00,0:00:05.00,Default,,0,0,0,,not on screen\n\ | ||
| 473 | + Dialogue: 0,0:00:06.00,0:00:07.00,Default,,0,0,0,,{\\an8\\pos(960,100)}up top\n"; | ||
| 474 | + | ||
| 475 | + #[test] | ||
| 476 | + fn a_script_parses_header_styles_and_events() { | ||
| 477 | + let track = parse(SCRIPT.as_bytes()).unwrap(); | ||
| 478 | + assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); | ||
| 479 | + assert_eq!( | ||
| 480 | + track.metadata.iter().find(|(k, _)| k == "title").unwrap().1, | ||
| 481 | + "A script" | ||
| 482 | + ); | ||
| 483 | + let style = track.style("Default").unwrap(); | ||
| 484 | + assert_eq!(style.font_family.as_deref(), Some("Arial")); | ||
| 485 | + assert_eq!(style.font_size, Some(48.0)); | ||
| 486 | + assert!(style.bold && !style.italic); | ||
| 487 | + assert_eq!(style.primary_color, Some((255, 255, 255, 255))); | ||
| 488 | + // `&H80000000` is half transparent, and BGR order means blue is zero. | ||
| 489 | + assert_eq!(style.back_color, Some((0, 0, 0, 127))); | ||
| 490 | + assert_eq!(style.align, TextAlign::Center); | ||
| 491 | + | ||
| 492 | + // The `Comment:` row is not a cue. | ||
| 493 | + assert_eq!(track.cues.len(), 2); | ||
| 494 | + let cue = &track.cues[0]; | ||
| 495 | + assert_eq!((cue.start_us, cue.end_us), (1_000_000, 3_500_000)); | ||
| 496 | + assert_eq!(cue.style_ref.as_deref(), Some("Default")); | ||
| 497 | + // The text field keeps its own commas. | ||
| 498 | + assert_eq!( | ||
| 499 | + plain_text(&cue.segments), | ||
| 500 | + "tilted plain\nsecond, with comma" | ||
| 501 | + ); | ||
| 502 | + assert!(matches!(cue.segments[0], Segment::Italic(_))); | ||
| 503 | + assert_eq!(track.skipped, 0); | ||
| 504 | + // The header is what a Matroska `CodecPrivate` carries. | ||
| 505 | + assert!(track.extradata.starts_with(b"[Script Info]")); | ||
| 506 | + assert!(!track.extradata.windows(9).any(|w| w == b"Dialogue:")); | ||
| 507 | + } | ||
| 508 | + | ||
| 509 | + #[test] | ||
| 510 | + fn positioning_overrides_reach_the_cue() { | ||
| 511 | + let track = parse(SCRIPT.as_bytes()).unwrap(); | ||
| 512 | + let position = track.cues[1].positioning.unwrap(); | ||
| 513 | + assert_eq!(position.align, TextAlign::Center); | ||
| 514 | + assert_eq!((position.x, position.y), (Some(960.0), Some(100.0))); | ||
| 515 | + assert_eq!(plain_text(&track.cues[1].segments), "up top"); | ||
| 516 | + } | ||
| 517 | + | ||
| 518 | + #[test] | ||
| 519 | + fn karaoke_drawings_and_unknown_tags() { | ||
| 520 | + let doc = "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ | ||
| 521 | + Dialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{\\k30}ka{\\k25}ra\n\ | ||
| 522 | + Dialogue: 0,0:00:01.00,0:00:02.00,,,0,0,0,,{\\p1}m 0 0 l 10 10{\\p0}words\n\ | ||
| 523 | + Dialogue: 0,0:00:02.00,0:00:03.00,,,0,0,0,,{\\t(0,500,\\fscx120)}moving\n"; | ||
| 524 | + let track = parse(doc.as_bytes()).unwrap(); | ||
| 525 | + assert_eq!(plain_text(&track.cues[0].segments), "kara"); | ||
| 526 | + assert!(matches!( | ||
| 527 | + track.cues[0].segments[0], | ||
| 528 | + Segment::Karaoke { cs: 30, .. } | ||
| 529 | + )); | ||
| 530 | + // Drawing commands are not words. | ||
| 531 | + assert_eq!(plain_text(&track.cues[1].segments), "words"); | ||
| 532 | + // An override this does not model survives as itself. | ||
| 533 | + assert_eq!(plain_text(&track.cues[2].segments), "moving"); | ||
| 534 | + assert!( | ||
| 535 | + track.cues[2] | ||
| 536 | + .segments | ||
| 537 | + .iter() | ||
| 538 | + .any(|s| matches!(s, Segment::Raw(r) if r.contains("fscx120"))) | ||
| 539 | + ); | ||
| 540 | + } | ||
| 541 | + | ||
| 542 | + #[test] | ||
| 543 | + fn tolerances_and_the_refusal() { | ||
| 544 | + // No `Format:` line, CRLF, a torn row, and `\h` / `\n`. | ||
| 545 | + let doc = b"\xef\xbb\xbf[Events]\r\n\ | ||
| 546 | + Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,a\\hb\\nc\r\n\ | ||
| 547 | + Dialogue: not a row\r\n"; | ||
| 548 | + let track = parse(doc).unwrap(); | ||
| 549 | + assert_eq!(track.cues.len(), 1); | ||
| 550 | + assert_eq!(track.skipped, 1); | ||
| 551 | + assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b c"); | ||
| 552 | + // `WrapStyle: 2` makes `\n` a break instead. | ||
| 553 | + let wrapped = format!( | ||
| 554 | + "[Script Info]\nWrapStyle: 2\n{}", | ||
| 555 | + String::from_utf8_lossy(&doc[3..]) | ||
| 556 | + ); | ||
| 557 | + let track = parse(wrapped.as_bytes()).unwrap(); | ||
| 558 | + assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b\nc"); | ||
| 559 | + | ||
| 560 | + assert!(parse(b"just some prose").is_err()); | ||
| 561 | + } | ||
| 562 | +} | ||
crates/ec-pgs/Cargo.tomladded+10 -0
| @@ -0,0 +1,10 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-pgs" | ||
| 3 | +description = "Blu-ray Presentation Graphic Stream (PGS/SUP) subtitle bitmap decoding." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
crates/ec-pgs/src/lib.rsadded+578 -0
| @@ -0,0 +1,578 @@ | |||
| 1 | +//! Blu-ray Presentation Graphic Stream: the subtitles that are *pictures*. | ||
| 2 | +//! | ||
| 3 | +//! A PGS stream is a sequence of display sets, each a handful of segments: a | ||
| 4 | +//! presentation composition (PCS — the canvas and where the objects go on it), a | ||
| 5 | +//! window definition (WDS), a palette (PDS), one or more run-length objects | ||
| 6 | +//! (ODS) and an end marker (END). A set is decoded against the state the sets | ||
| 7 | +//! before it left behind, which is why this is a decoder with an epoch and not | ||
| 8 | +//! a function: an acquisition point re-states everything, a normal-case set may | ||
| 9 | +//! re-use an object or merely swap the palette. | ||
| 10 | +//! | ||
| 11 | +//! What comes out is one straight-alpha RGBA frame per display set, the size of | ||
| 12 | +//! the composition's own canvas (1920×1080 off a disc), transparent everywhere | ||
| 13 | +//! the cue paints nothing. That is the shape a compositor wants and the shape | ||
| 14 | +//! `.sup` tooling shows: a caller lays the whole canvas over the film rather | ||
| 15 | +//! than placing a sprite. | ||
| 16 | +//! | ||
| 17 | +//! The framing read here is the `.sup` one — `PG`, two timestamps, type, size — | ||
| 18 | +//! because that is what a `.sup` file holds and what a Matroska block becomes | ||
| 19 | +//! once its header is put back on ([`ec_subs`] is the text half of the same | ||
| 20 | +//! story). Colour is BT.601 limited-range, which is what the palette entries of | ||
| 21 | +//! a disc are and what every other decoder of this format assumes. | ||
| 22 | + | ||
| 23 | +#![forbid(unsafe_code)] | ||
| 24 | + | ||
| 25 | +use std::collections::HashMap; | ||
| 26 | + | ||
| 27 | +use ec_core::{ | ||
| 28 | + CodecId, CodecParameters, Decoder, Error, Frame, PixelFormat, Plane, Result, VideoFrame, | ||
| 29 | +}; | ||
| 30 | + | ||
| 31 | +/// Palette definition segment. | ||
| 32 | +pub const SEG_PDS: u8 = 0x14; | ||
| 33 | +/// Object definition segment: the run-length bitmap itself. | ||
| 34 | +pub const SEG_ODS: u8 = 0x15; | ||
| 35 | +/// Presentation composition segment: canvas size and object placement. | ||
| 36 | +pub const SEG_PCS: u8 = 0x16; | ||
| 37 | +/// Window definition segment. | ||
| 38 | +pub const SEG_WDS: u8 = 0x17; | ||
| 39 | +/// End of display set — the point at which a frame is complete. | ||
| 40 | +pub const SEG_END: u8 = 0x80; | ||
| 41 | + | ||
| 42 | +/// The magic every `.sup` segment starts with. | ||
| 43 | +const MAGIC: [u8; 2] = *b"PG"; | ||
| 44 | +/// Bytes before a segment's body: magic, PTS, DTS, type, size. | ||
| 45 | +const HEADER: usize = 13; | ||
| 46 | + | ||
| 47 | +/// A decoder over a `.sup` byte stream. | ||
| 48 | +/// | ||
| 49 | +/// Feed it whole segments ([`PgsDecoder::push`]) — a partial one is held until | ||
| 50 | +/// the rest arrives, so a caller may split the stream anywhere — and take a | ||
| 51 | +/// frame per display set ([`PgsDecoder::take_frame`]). | ||
| 52 | +pub struct PgsDecoder { | ||
| 53 | + params: CodecParameters, | ||
| 54 | + /// Bytes not yet forming a whole segment. | ||
| 55 | + pending: Vec<u8>, | ||
| 56 | + /// Objects by id, decoded run-length data as the stream stated it. | ||
| 57 | + objects: HashMap<u16, Object>, | ||
| 58 | + /// The object being assembled out of a multi-segment ODS sequence. | ||
| 59 | + partial: Option<(u16, Object)>, | ||
| 60 | + /// Palettes by id: 256 straight-alpha RGBA entries each. | ||
| 61 | + palettes: HashMap<u8, Box<[[u8; 4]; 256]>>, | ||
| 62 | + /// Windows by id, for clipping. | ||
| 63 | + windows: HashMap<u8, Rect>, | ||
| 64 | + /// The composition the current display set is building. | ||
| 65 | + composition: Composition, | ||
| 66 | + /// Frames finished but not yet taken. | ||
| 67 | + ready: Vec<VideoFrame>, | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +#[derive(Clone, Default)] | ||
| 71 | +struct Object { | ||
| 72 | + width: u32, | ||
| 73 | + height: u32, | ||
| 74 | + rle: Vec<u8>, | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +#[derive(Clone, Copy, Default)] | ||
| 78 | +struct Rect { | ||
| 79 | + x: u32, | ||
| 80 | + y: u32, | ||
| 81 | + width: u32, | ||
| 82 | + height: u32, | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +#[derive(Clone, Default)] | ||
| 86 | +struct Composition { | ||
| 87 | + width: u32, | ||
| 88 | + height: u32, | ||
| 89 | + palette_id: u8, | ||
| 90 | + objects: Vec<Placement>, | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +#[derive(Clone, Copy)] | ||
| 94 | +struct Placement { | ||
| 95 | + object_id: u16, | ||
| 96 | + window_id: u8, | ||
| 97 | + x: u32, | ||
| 98 | + y: u32, | ||
| 99 | + crop: Option<Rect>, | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +impl Default for PgsDecoder { | ||
| 103 | + fn default() -> Self { | ||
| 104 | + PgsDecoder::new() | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +impl PgsDecoder { | ||
| 109 | + /// A decoder with no epoch yet: the first display set states everything. | ||
| 110 | + pub fn new() -> PgsDecoder { | ||
| 111 | + PgsDecoder { | ||
| 112 | + params: CodecParameters::new(CodecId::Pgs), | ||
| 113 | + pending: Vec::new(), | ||
| 114 | + objects: HashMap::new(), | ||
| 115 | + partial: None, | ||
| 116 | + palettes: HashMap::new(), | ||
| 117 | + windows: HashMap::new(), | ||
| 118 | + composition: Composition::default(), | ||
| 119 | + ready: Vec::new(), | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// Feed stream bytes. Every complete segment in them is consumed; a partial | ||
| 124 | + /// tail is kept for the next call. | ||
| 125 | + /// | ||
| 126 | + /// A segment whose body is nonsense (a palette entry short, an object | ||
| 127 | + /// claiming more pixels than its bitmap holds) is dropped and the stream | ||
| 128 | + /// carries on: one torn display set out of eleven thousand must not cost | ||
| 129 | + /// the track. | ||
| 130 | + pub fn push(&mut self, bytes: &[u8]) -> Result<()> { | ||
| 131 | + let mut buffer = std::mem::take(&mut self.pending); | ||
| 132 | + buffer.extend_from_slice(bytes); | ||
| 133 | + let mut data: &[u8] = &buffer; | ||
| 134 | + loop { | ||
| 135 | + if data.len() < HEADER { | ||
| 136 | + break; | ||
| 137 | + } | ||
| 138 | + if data[..2] != MAGIC { | ||
| 139 | + // Not a segment boundary at all: resynchronising would invent | ||
| 140 | + // structure, so this is the one hard error. | ||
| 141 | + return Err(Error::corrupt("PGS: segment does not start with `PG`")); | ||
| 142 | + } | ||
| 143 | + let size = u16::from_be_bytes([data[11], data[12]]) as usize; | ||
| 144 | + if data.len() < HEADER + size { | ||
| 145 | + break; | ||
| 146 | + } | ||
| 147 | + let kind = data[10]; | ||
| 148 | + let body = &data[HEADER..HEADER + size]; | ||
| 149 | + self.segment(kind, body); | ||
| 150 | + data = &data[HEADER + size..]; | ||
| 151 | + } | ||
| 152 | + self.pending = data.to_vec(); | ||
| 153 | + Ok(()) | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + /// The next finished display set, oldest first. | ||
| 157 | + pub fn take_frame(&mut self) -> Option<VideoFrame> { | ||
| 158 | + match self.ready.is_empty() { | ||
| 159 | + true => None, | ||
| 160 | + false => Some(self.ready.remove(0)), | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + /// One segment against the running state. | ||
| 165 | + fn segment(&mut self, kind: u8, body: &[u8]) { | ||
| 166 | + match kind { | ||
| 167 | + SEG_PCS => self.pcs(body), | ||
| 168 | + SEG_WDS => self.wds(body), | ||
| 169 | + SEG_PDS => self.pds(body), | ||
| 170 | + SEG_ODS => self.ods(body), | ||
| 171 | + SEG_END => { | ||
| 172 | + if let Some(frame) = self.render() { | ||
| 173 | + self.ready.push(frame); | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | + _ => {} | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + fn pcs(&mut self, body: &[u8]) { | ||
| 181 | + if body.len() < 11 { | ||
| 182 | + return; | ||
| 183 | + } | ||
| 184 | + let composition_state = body[7]; | ||
| 185 | + // Epoch start: nothing from before this point is referenced again. | ||
| 186 | + if composition_state & 0x80 != 0 { | ||
| 187 | + self.objects.clear(); | ||
| 188 | + self.palettes.clear(); | ||
| 189 | + self.windows.clear(); | ||
| 190 | + self.partial = None; | ||
| 191 | + } | ||
| 192 | + let mut composition = Composition { | ||
| 193 | + width: u32::from(u16::from_be_bytes([body[0], body[1]])), | ||
| 194 | + height: u32::from(u16::from_be_bytes([body[2], body[3]])), | ||
| 195 | + palette_id: body[9], | ||
| 196 | + objects: Vec::new(), | ||
| 197 | + }; | ||
| 198 | + let count = body[10] as usize; | ||
| 199 | + let mut at = 11; | ||
| 200 | + for _ in 0..count { | ||
| 201 | + if body.len() < at + 8 { | ||
| 202 | + break; | ||
| 203 | + } | ||
| 204 | + let flags = body[at + 3]; | ||
| 205 | + let cropped = flags & 0x80 != 0; | ||
| 206 | + let placement = Placement { | ||
| 207 | + object_id: u16::from_be_bytes([body[at], body[at + 1]]), | ||
| 208 | + window_id: body[at + 2], | ||
| 209 | + x: u32::from(u16::from_be_bytes([body[at + 4], body[at + 5]])), | ||
| 210 | + y: u32::from(u16::from_be_bytes([body[at + 6], body[at + 7]])), | ||
| 211 | + crop: match cropped && body.len() >= at + 16 { | ||
| 212 | + true => Some(Rect { | ||
| 213 | + x: u32::from(u16::from_be_bytes([body[at + 8], body[at + 9]])), | ||
| 214 | + y: u32::from(u16::from_be_bytes([body[at + 10], body[at + 11]])), | ||
| 215 | + width: u32::from(u16::from_be_bytes([body[at + 12], body[at + 13]])), | ||
| 216 | + height: u32::from(u16::from_be_bytes([body[at + 14], body[at + 15]])), | ||
| 217 | + }), | ||
| 218 | + false => None, | ||
| 219 | + }, | ||
| 220 | + }; | ||
| 221 | + at += if cropped { 16 } else { 8 }; | ||
| 222 | + composition.objects.push(placement); | ||
| 223 | + } | ||
| 224 | + self.composition = composition; | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + fn wds(&mut self, body: &[u8]) { | ||
| 228 | + let count = body.first().copied().unwrap_or(0) as usize; | ||
| 229 | + for i in 0..count { | ||
| 230 | + let at = 1 + i * 9; | ||
| 231 | + if body.len() < at + 9 { | ||
| 232 | + break; | ||
| 233 | + } | ||
| 234 | + self.windows.insert( | ||
| 235 | + body[at], | ||
| 236 | + Rect { | ||
| 237 | + x: u32::from(u16::from_be_bytes([body[at + 1], body[at + 2]])), | ||
| 238 | + y: u32::from(u16::from_be_bytes([body[at + 3], body[at + 4]])), | ||
| 239 | + width: u32::from(u16::from_be_bytes([body[at + 5], body[at + 6]])), | ||
| 240 | + height: u32::from(u16::from_be_bytes([body[at + 7], body[at + 8]])), | ||
| 241 | + }, | ||
| 242 | + ); | ||
| 243 | + } | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + fn pds(&mut self, body: &[u8]) { | ||
| 247 | + if body.len() < 2 { | ||
| 248 | + return; | ||
| 249 | + } | ||
| 250 | + // A palette segment *updates* the palette it names: entries it does not | ||
| 251 | + // mention keep whatever the epoch left there. | ||
| 252 | + let palette = self | ||
| 253 | + .palettes | ||
| 254 | + .entry(body[0]) | ||
| 255 | + .or_insert_with(|| Box::new([[0, 0, 0, 0]; 256])); | ||
| 256 | + for entry in body[2..].chunks_exact(5) { | ||
| 257 | + palette[entry[0] as usize] = rgba(entry[1], entry[2], entry[3], entry[4]); | ||
| 258 | + } | ||
| 259 | + } | ||
| 260 | + | ||
| 261 | + fn ods(&mut self, body: &[u8]) { | ||
| 262 | + if body.len() < 4 { | ||
| 263 | + return; | ||
| 264 | + } | ||
| 265 | + let id = u16::from_be_bytes([body[0], body[1]]); | ||
| 266 | + let sequence = body[3]; | ||
| 267 | + if sequence & 0x80 != 0 { | ||
| 268 | + // First (or only) segment of the sequence: the dimensions ride here. | ||
| 269 | + if body.len() < 11 { | ||
| 270 | + return; | ||
| 271 | + } | ||
| 272 | + let object = Object { | ||
| 273 | + width: u32::from(u16::from_be_bytes([body[7], body[8]])), | ||
| 274 | + height: u32::from(u16::from_be_bytes([body[9], body[10]])), | ||
| 275 | + rle: body[11..].to_vec(), | ||
| 276 | + }; | ||
| 277 | + self.partial = Some((id, object)); | ||
| 278 | + } else if let Some((pending_id, object)) = self.partial.as_mut() | ||
| 279 | + && *pending_id == id | ||
| 280 | + { | ||
| 281 | + object.rle.extend_from_slice(&body[4..]); | ||
| 282 | + } | ||
| 283 | + if sequence & 0x40 != 0 | ||
| 284 | + && let Some((id, object)) = self.partial.take() | ||
| 285 | + { | ||
| 286 | + self.objects.insert(id, object); | ||
| 287 | + } | ||
| 288 | + } | ||
| 289 | + | ||
| 290 | + /// The current composition as one RGBA canvas, or `None` when it states no | ||
| 291 | + /// canvas at all (a display set seen before any PCS). | ||
| 292 | + fn render(&mut self) -> Option<VideoFrame> { | ||
| 293 | + let (width, height) = (self.composition.width, self.composition.height); | ||
| 294 | + if width == 0 || height == 0 { | ||
| 295 | + return None; | ||
| 296 | + } | ||
| 297 | + let stride = width as usize * 4; | ||
| 298 | + let mut canvas = vec![0u8; stride.checked_mul(height as usize)?]; | ||
| 299 | + let palette = self.palettes.get(&self.composition.palette_id); | ||
| 300 | + for placement in &self.composition.objects { | ||
| 301 | + let (Some(object), Some(palette)) = (self.objects.get(&placement.object_id), palette) | ||
| 302 | + else { | ||
| 303 | + continue; | ||
| 304 | + }; | ||
| 305 | + let Some(indices) = decode_rle(&object.rle, object.width, object.height) else { | ||
| 306 | + continue; | ||
| 307 | + }; | ||
| 308 | + // A window clips its objects; a crop takes a rectangle out of the | ||
| 309 | + // object before it is placed. | ||
| 310 | + let window = self.windows.get(&placement.window_id).copied(); | ||
| 311 | + let crop = placement.crop.unwrap_or(Rect { | ||
| 312 | + x: 0, | ||
| 313 | + y: 0, | ||
| 314 | + width: object.width, | ||
| 315 | + height: object.height, | ||
| 316 | + }); | ||
| 317 | + for row in 0..crop.height.min(object.height.saturating_sub(crop.y)) { | ||
| 318 | + let target_y = placement.y + row; | ||
| 319 | + if target_y >= height { | ||
| 320 | + break; | ||
| 321 | + } | ||
| 322 | + for col in 0..crop.width.min(object.width.saturating_sub(crop.x)) { | ||
| 323 | + let target_x = placement.x + col; | ||
| 324 | + if target_x >= width { | ||
| 325 | + break; | ||
| 326 | + } | ||
| 327 | + if let Some(w) = window | ||
| 328 | + && (target_x < w.x | ||
| 329 | + || target_y < w.y | ||
| 330 | + || target_x >= w.x + w.width | ||
| 331 | + || target_y >= w.y + w.height) | ||
| 332 | + { | ||
| 333 | + continue; | ||
| 334 | + } | ||
| 335 | + let index = indices[((crop.y + row) * object.width + crop.x + col) as usize]; | ||
| 336 | + let colour = palette[index as usize]; | ||
| 337 | + // Fully transparent palette entries paint nothing, which is | ||
| 338 | + // what lets two objects share a window. | ||
| 339 | + if colour[3] == 0 { | ||
| 340 | + continue; | ||
| 341 | + } | ||
| 342 | + let at = target_y as usize * stride + target_x as usize * 4; | ||
| 343 | + canvas[at..at + 4].copy_from_slice(&colour); | ||
| 344 | + } | ||
| 345 | + } | ||
| 346 | + } | ||
| 347 | + VideoFrame::try_new( | ||
| 348 | + PixelFormat::Rgba8, | ||
| 349 | + width, | ||
| 350 | + height, | ||
| 351 | + vec![Plane::new(canvas, stride)], | ||
| 352 | + ) | ||
| 353 | + .ok() | ||
| 354 | + } | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +impl Decoder for PgsDecoder { | ||
| 358 | + fn codec_parameters(&self) -> &CodecParameters { | ||
| 359 | + &self.params | ||
| 360 | + } | ||
| 361 | + | ||
| 362 | + fn send_packet(&mut self, packet: &ec_core::Packet) -> Result<()> { | ||
| 363 | + self.push(&packet.data) | ||
| 364 | + } | ||
| 365 | + | ||
| 366 | + fn receive_frame(&mut self) -> Result<Frame> { | ||
| 367 | + match self.take_frame() { | ||
| 368 | + Some(frame) => Ok(Frame::Video(frame)), | ||
| 369 | + None => Err(Error::NeedMore), | ||
| 370 | + } | ||
| 371 | + } | ||
| 372 | + | ||
| 373 | + fn flush(&mut self) -> Result<()> { | ||
| 374 | + Ok(()) | ||
| 375 | + } | ||
| 376 | + | ||
| 377 | + fn reset(&mut self) { | ||
| 378 | + let params = self.params.clone(); | ||
| 379 | + *self = PgsDecoder::new(); | ||
| 380 | + self.params = params; | ||
| 381 | + } | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +/// A PGS decoder as the family's registry hands one out. | ||
| 385 | +pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> { | ||
| 386 | + Ok(Box::new(PgsDecoder::new())) | ||
| 387 | +} | ||
| 388 | + | ||
| 389 | +/// One palette entry: BT.601 limited-range Y'CbCr with straight alpha, the way | ||
| 390 | +/// a disc writes it, into RGBA. | ||
| 391 | +fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] { | ||
| 392 | + let y = 298 * (i32::from(y) - 16); | ||
| 393 | + let cb = i32::from(cb) - 128; | ||
| 394 | + let cr = i32::from(cr) - 128; | ||
| 395 | + let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8; | ||
| 396 | + [ | ||
| 397 | + clamp(y + 409 * cr), | ||
| 398 | + clamp(y - 100 * cb - 208 * cr), | ||
| 399 | + clamp(y + 516 * cb), | ||
| 400 | + alpha, | ||
| 401 | + ] | ||
| 402 | +} | ||
| 403 | + | ||
| 404 | +/// The run-length coding of §8.2 of the format: a byte is a pixel of that | ||
| 405 | +/// palette index; a zero byte opens a run whose length and colour follow. | ||
| 406 | +/// | ||
| 407 | +/// `None` for data that does not describe a `width` × `height` bitmap — a | ||
| 408 | +/// truncated object, or one whose rows run past their width. | ||
| 409 | +fn decode_rle(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> { | ||
| 410 | + let (width, height) = (width as usize, height as usize); | ||
| 411 | + let mut out = vec![0u8; width.checked_mul(height)?]; | ||
| 412 | + let mut at = 0; | ||
| 413 | + let mut x = 0; | ||
| 414 | + let mut y = 0; | ||
| 415 | + while at < data.len() { | ||
| 416 | + let (colour, run) = match data[at] { | ||
| 417 | + 0 => { | ||
| 418 | + let flags = *data.get(at + 1)?; | ||
| 419 | + match flags { | ||
| 420 | + // A line ends where the encoder says it does, even short. | ||
| 421 | + 0 => { | ||
| 422 | + at += 2; | ||
| 423 | + x = 0; | ||
| 424 | + y += 1; | ||
| 425 | + continue; | ||
| 426 | + } | ||
| 427 | + // 00 0LLLLLL — L pixels of entry 0. | ||
| 428 | + f if f & 0xC0 == 0x00 => { | ||
| 429 | + at += 2; | ||
| 430 | + (0, usize::from(f & 0x3F)) | ||
| 431 | + } | ||
| 432 | + // 00 01LLLLLL LLLLLLLL — 14-bit run of entry 0. | ||
| 433 | + f if f & 0xC0 == 0x40 => { | ||
| 434 | + let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?); | ||
| 435 | + at += 3; | ||
| 436 | + (0, run) | ||
| 437 | + } | ||
| 438 | + // 00 10LLLLLL CC — L pixels of entry CC. | ||
| 439 | + f if f & 0xC0 == 0x80 => { | ||
| 440 | + let colour = *data.get(at + 2)?; | ||
| 441 | + at += 3; | ||
| 442 | + (colour, usize::from(f & 0x3F)) | ||
| 443 | + } | ||
| 444 | + // 00 11LLLLLL LLLLLLLL CC — 14-bit run of entry CC. | ||
| 445 | + f => { | ||
| 446 | + let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?); | ||
| 447 | + let colour = *data.get(at + 3)?; | ||
| 448 | + at += 4; | ||
| 449 | + (colour, run) | ||
| 450 | + } | ||
| 451 | + } | ||
| 452 | + } | ||
| 453 | + colour => { | ||
| 454 | + at += 1; | ||
| 455 | + (colour, 1) | ||
| 456 | + } | ||
| 457 | + }; | ||
| 458 | + if y >= height || x + run > width { | ||
| 459 | + return None; | ||
| 460 | + } | ||
| 461 | + out[y * width + x..y * width + x + run].fill(colour); | ||
| 462 | + x += run; | ||
| 463 | + } | ||
| 464 | + Some(out) | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +#[cfg(test)] | ||
| 468 | +mod tests { | ||
| 469 | + use super::*; | ||
| 470 | + | ||
| 471 | + /// One `.sup` segment: the framing a Matroska block gets back on the way in. | ||
| 472 | + fn segment(kind: u8, body: &[u8]) -> Vec<u8> { | ||
| 473 | + let mut out = Vec::with_capacity(HEADER + body.len()); | ||
| 474 | + out.extend_from_slice(&MAGIC); | ||
| 475 | + out.extend_from_slice(&[0; 8]); | ||
| 476 | + out.push(kind); | ||
| 477 | + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); | ||
| 478 | + out.extend_from_slice(body); | ||
| 479 | + out | ||
| 480 | + } | ||
| 481 | + | ||
| 482 | + /// A display set: an 8×2 white-on-transparent object at (2, 1) of a 16×4 | ||
| 483 | + /// canvas. | ||
| 484 | + fn display_set() -> Vec<u8> { | ||
| 485 | + let mut pcs = vec![0, 16, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1]; | ||
| 486 | + pcs.extend_from_slice(&[0, 0, 0, 0, 0, 2, 0, 1]); // object 0, window 0, at (2,1) | ||
| 487 | + let wds = vec![1, 0, 0, 0, 0, 0, 0, 16, 0, 4]; | ||
| 488 | + // Entry 1 is opaque white, entry 2 opaque black; entry 0 stays clear. | ||
| 489 | + let pds = vec![0, 0, 1, 235, 128, 128, 255, 2, 16, 128, 128, 255]; | ||
| 490 | + // Two rows of 8: a run of 8 of entry 1, then a run of 8 of entry 2. | ||
| 491 | + let rle = vec![0x00, 0x88, 0x01, 0x00, 0x00, 0x00, 0x88, 0x02, 0x00, 0x00]; | ||
| 492 | + let mut ods = vec![0, 0, 0, 0xC0]; | ||
| 493 | + ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); | ||
| 494 | + ods.extend_from_slice(&[0, 8, 0, 2]); | ||
| 495 | + ods.extend_from_slice(&rle); | ||
| 496 | + [ | ||
| 497 | + segment(SEG_PCS, &pcs), | ||
| 498 | + segment(SEG_WDS, &wds), | ||
| 499 | + segment(SEG_PDS, &pds), | ||
| 500 | + segment(SEG_ODS, &ods), | ||
| 501 | + segment(SEG_END, &[]), | ||
| 502 | + ] | ||
| 503 | + .concat() | ||
| 504 | + } | ||
| 505 | + | ||
| 506 | + #[test] | ||
| 507 | + fn a_display_set_decodes_to_the_canvas_it_composes() { | ||
| 508 | + let mut decoder = PgsDecoder::new(); | ||
| 509 | + decoder.push(&display_set()).unwrap(); | ||
| 510 | + let frame = decoder.take_frame().expect("one frame per display set"); | ||
| 511 | + assert_eq!((frame.width, frame.height), (16, 4)); | ||
| 512 | + assert_eq!(frame.format, PixelFormat::Rgba8); | ||
| 513 | + let stride = frame.planes[0].stride; | ||
| 514 | + let pixel = |x: usize, y: usize| &frame.planes[0].data[y * stride + x * 4..][..4]; | ||
| 515 | + // Outside the object: nothing painted at all. | ||
| 516 | + assert_eq!(pixel(0, 0), [0, 0, 0, 0]); | ||
| 517 | + assert_eq!(pixel(1, 1), [0, 0, 0, 0]); | ||
| 518 | + // Row 1 of the object is white, row 2 is black, both opaque. | ||
| 519 | + assert_eq!(pixel(2, 1), [255, 255, 255, 255]); | ||
| 520 | + assert_eq!(pixel(9, 1), [255, 255, 255, 255]); | ||
| 521 | + assert_eq!(pixel(2, 2), [0, 0, 0, 255]); | ||
| 522 | + // Past the object's width again. | ||
| 523 | + assert_eq!(pixel(10, 1), [0, 0, 0, 0]); | ||
| 524 | + assert!(decoder.take_frame().is_none()); | ||
| 525 | + } | ||
| 526 | + | ||
| 527 | + #[test] | ||
| 528 | + fn a_stream_split_anywhere_decodes_the_same() { | ||
| 529 | + let bytes = display_set(); | ||
| 530 | + for split in [1, 7, 13, 20, bytes.len() - 1] { | ||
| 531 | + let mut decoder = PgsDecoder::new(); | ||
| 532 | + decoder.push(&bytes[..split]).unwrap(); | ||
| 533 | + decoder.push(&bytes[split..]).unwrap(); | ||
| 534 | + let frame = decoder.take_frame().expect("split framing still decodes"); | ||
| 535 | + assert_eq!((frame.width, frame.height), (16, 4)); | ||
| 536 | + } | ||
| 537 | + } | ||
| 538 | + | ||
| 539 | + #[test] | ||
| 540 | + fn rubbish_never_panics() { | ||
| 541 | + // Not segment framing at all. | ||
| 542 | + let mut decoder = PgsDecoder::new(); | ||
| 543 | + assert!(decoder.push(b"not a sup file at all").is_err()); | ||
| 544 | + // Well-framed segments with torn bodies: dropped, no frame, no panic. | ||
| 545 | + let mut decoder = PgsDecoder::new(); | ||
| 546 | + let torn = [ | ||
| 547 | + segment(SEG_PCS, &[0, 16, 0, 4]), | ||
| 548 | + segment(SEG_ODS, &[0, 0, 0, 0x80, 9, 9, 9]), | ||
| 549 | + segment(SEG_PDS, &[0]), | ||
| 550 | + segment(SEG_END, &[]), | ||
| 551 | + ] | ||
| 552 | + .concat(); | ||
| 553 | + decoder.push(&torn).unwrap(); | ||
| 554 | + assert!(decoder.take_frame().is_none()); | ||
| 555 | + } | ||
| 556 | + | ||
| 557 | + #[test] | ||
| 558 | + fn run_length_shapes_and_their_refusals() { | ||
| 559 | + // Short form, long form, coloured runs, end of line. | ||
| 560 | + let data = [0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00]; | ||
| 561 | + let out = decode_rle(&data, 4, 2).unwrap(); | ||
| 562 | + assert_eq!(out, [0, 0, 0, 1, 2, 2, 2, 0]); | ||
| 563 | + // A run past the row is a refusal, not a wrap. | ||
| 564 | + assert!(decode_rle(&[0x00, 0x08, 0x01], 4, 1).is_none()); | ||
| 565 | + // A truncated run is a refusal too. | ||
| 566 | + assert!(decode_rle(&[0x00, 0x80], 4, 1).is_none()); | ||
| 567 | + } | ||
| 568 | + | ||
| 569 | + #[test] | ||
| 570 | + fn palette_entries_are_bt601_limited_range() { | ||
| 571 | + // Y=235 is white, Y=16 is black, and alpha rides through untouched. | ||
| 572 | + assert_eq!(rgba(235, 128, 128, 255), [255, 255, 255, 255]); | ||
| 573 | + assert_eq!(rgba(16, 128, 128, 128), [0, 0, 0, 128]); | ||
| 574 | + // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601. | ||
| 575 | + let red = rgba(81, 240, 90, 255); | ||
| 576 | + assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}"); | ||
| 577 | + } | ||
| 578 | +} | ||
crates/ec-subs/Cargo.tomladded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-subs" | ||
| 3 | +description = "Text subtitle parsing for the edith_codecs family: SubRip and WebVTT into one cue IR." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
| 11 | + | ||
| 12 | +[dev-dependencies] | ||
| 13 | +ec-ass = { path = "../ec-ass", version = "0.1.0" } | ||
| 14 | +ec-pgs = { path = "../ec-pgs", version = "0.1.0" } | ||
crates/ec-subs/src/ir.rsadded+270 -0
| @@ -0,0 +1,270 @@ | |||
| 1 | +//! The one cue model every subtitle parser in the family answers with. | ||
| 2 | +//! | ||
| 3 | +//! A cue is a time range and a *tree* of inline runs rather than a string: | ||
| 4 | +//! italics, colour, a karaoke beat and a line break are all things a renderer | ||
| 5 | +//! will want and a plain-text caller can drop in one call | ||
| 6 | +//! ([`plain_text`]). Positioning that the format states — WebVTT cue settings, | ||
| 7 | +//! ASS `\pos` and `\an` — rides beside the runs instead of inside them, because | ||
| 8 | +//! it applies to the cue as a whole. | ||
| 9 | + | ||
| 10 | +/// One inline run of a cue body. | ||
| 11 | +#[derive(Clone, Debug, PartialEq)] | ||
| 12 | +pub enum Segment { | ||
| 13 | + /// Literal text. | ||
| 14 | + Text(String), | ||
| 15 | + /// Hard line break (SRT/WebVTT newline, ASS `\N`). | ||
| 16 | + LineBreak, | ||
| 17 | + /// Bold children (`<b>`, ASS `\b1`). | ||
| 18 | + Bold(Vec<Segment>), | ||
| 19 | + /// Italic children (`<i>`, ASS `\i1`). | ||
| 20 | + Italic(Vec<Segment>), | ||
| 21 | + /// Underlined children (`<u>`, ASS `\u1`). | ||
| 22 | + Underline(Vec<Segment>), | ||
| 23 | + /// Struck-through children (`<s>`, ASS `\s1`). | ||
| 24 | + Strike(Vec<Segment>), | ||
| 25 | + /// Children in an explicit colour (`<font color>`, ASS `\c` / `\1c`). | ||
| 26 | + Color { | ||
| 27 | + /// Text colour, one byte per channel. | ||
| 28 | + rgb: (u8, u8, u8), | ||
| 29 | + /// What the colour applies to. | ||
| 30 | + children: Vec<Segment>, | ||
| 31 | + }, | ||
| 32 | + /// Children under a font override (`<font face size>`, ASS `\fn` / `\fs`). | ||
| 33 | + Font { | ||
| 34 | + /// Family name; `None` inherits. | ||
| 35 | + family: Option<String>, | ||
| 36 | + /// Size in the source format's own units; `None` inherits. | ||
| 37 | + size: Option<f32>, | ||
| 38 | + /// What the override applies to. | ||
| 39 | + children: Vec<Segment>, | ||
| 40 | + }, | ||
| 41 | + /// WebVTT `<v Speaker>`. | ||
| 42 | + Voice { | ||
| 43 | + /// The speaker the annotation names. | ||
| 44 | + name: String, | ||
| 45 | + /// What that voice says. | ||
| 46 | + children: Vec<Segment>, | ||
| 47 | + }, | ||
| 48 | + /// WebVTT `<c.class>`. | ||
| 49 | + Class { | ||
| 50 | + /// Class name without the leading dot. | ||
| 51 | + name: String, | ||
| 52 | + /// What the class applies to. | ||
| 53 | + children: Vec<Segment>, | ||
| 54 | + }, | ||
| 55 | + /// ASS `{\k<cs>}`: the run is highlighted for `cs` centiseconds. | ||
| 56 | + Karaoke { | ||
| 57 | + /// Beat length in centiseconds. | ||
| 58 | + cs: u32, | ||
| 59 | + /// The syllable under the beat. | ||
| 60 | + children: Vec<Segment>, | ||
| 61 | + }, | ||
| 62 | + /// WebVTT inline timestamp `<00:00:01.500>`, microseconds from stream start. | ||
| 63 | + Timestamp { | ||
| 64 | + /// The instant the tag names. | ||
| 65 | + offset_us: i64, | ||
| 66 | + }, | ||
| 67 | + /// Markup this parser does not model, kept verbatim so a re-emit stays | ||
| 68 | + /// faithful and [`plain_text`] can drop it whole. ASS drawing commands | ||
| 69 | + /// (`{\p1}` … `{\p0}`) land here too: they are shapes, not words. | ||
| 70 | + Raw(String), | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Horizontal alignment of a cue or a style row. | ||
| 74 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | ||
| 75 | +pub enum TextAlign { | ||
| 76 | + /// Start edge of the text direction — left in a left-to-right script. | ||
| 77 | + #[default] | ||
| 78 | + Start, | ||
| 79 | + /// Centred. | ||
| 80 | + Center, | ||
| 81 | + /// End edge of the text direction. | ||
| 82 | + End, | ||
| 83 | + /// Left edge whatever the text direction. | ||
| 84 | + Left, | ||
| 85 | + /// Right edge whatever the text direction. | ||
| 86 | + Right, | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// Where the format asked for the cue to be drawn. | ||
| 90 | +/// | ||
| 91 | +/// The units are the source's own: WebVTT `position`/`line`/`size` are | ||
| 92 | +/// percentages of the viewport, ASS `\pos` is pixels in the `PlayResX` × | ||
| 93 | +/// `PlayResY` canvas. | ||
| 94 | +#[derive(Clone, Copy, Debug, Default, PartialEq)] | ||
| 95 | +pub struct CuePosition { | ||
| 96 | + /// Horizontal position, or `None` for the format default. | ||
| 97 | + pub x: Option<f32>, | ||
| 98 | + /// Vertical position, or `None` for the format default. | ||
| 99 | + pub y: Option<f32>, | ||
| 100 | + /// Horizontal alignment of the cue's lines. | ||
| 101 | + pub align: TextAlign, | ||
| 102 | + /// WebVTT `size:N%`; meaningless for ASS. | ||
| 103 | + pub size: Option<f32>, | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// A named style a cue can reference — an ASS `Style:` row, essentially. | ||
| 107 | +#[derive(Clone, Debug, Default, PartialEq)] | ||
| 108 | +pub struct SubtitleStyle { | ||
| 109 | + /// Style name, which is what [`SubtitleCue::style_ref`] holds. | ||
| 110 | + pub name: String, | ||
| 111 | + /// Font family. | ||
| 112 | + pub font_family: Option<String>, | ||
| 113 | + /// Font size in the source's units. | ||
| 114 | + pub font_size: Option<f32>, | ||
| 115 | + /// Fill colour, RGBA. | ||
| 116 | + pub primary_color: Option<(u8, u8, u8, u8)>, | ||
| 117 | + /// Outline colour, RGBA. | ||
| 118 | + pub outline_color: Option<(u8, u8, u8, u8)>, | ||
| 119 | + /// Box/shadow colour, RGBA. | ||
| 120 | + pub back_color: Option<(u8, u8, u8, u8)>, | ||
| 121 | + /// Bold. | ||
| 122 | + pub bold: bool, | ||
| 123 | + /// Italic. | ||
| 124 | + pub italic: bool, | ||
| 125 | + /// Underline. | ||
| 126 | + pub underline: bool, | ||
| 127 | + /// Strikeout. | ||
| 128 | + pub strike: bool, | ||
| 129 | + /// Alignment of the style's lines. | ||
| 130 | + pub align: TextAlign, | ||
| 131 | + /// Left margin. | ||
| 132 | + pub margin_l: Option<i32>, | ||
| 133 | + /// Right margin. | ||
| 134 | + pub margin_r: Option<i32>, | ||
| 135 | + /// Vertical margin. | ||
| 136 | + pub margin_v: Option<i32>, | ||
| 137 | + /// Outline thickness. | ||
| 138 | + pub outline: Option<f32>, | ||
| 139 | + /// Shadow depth. | ||
| 140 | + pub shadow: Option<f32>, | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +impl SubtitleStyle { | ||
| 144 | + /// An otherwise defaulted style called `name`. | ||
| 145 | + pub fn new(name: impl Into<String>) -> SubtitleStyle { | ||
| 146 | + SubtitleStyle { | ||
| 147 | + name: name.into(), | ||
| 148 | + ..SubtitleStyle::default() | ||
| 149 | + } | ||
| 150 | + } | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/// One cue: when it is up, what it says, and how it was asked to be drawn. | ||
| 154 | +#[derive(Clone, Debug, Default, PartialEq)] | ||
| 155 | +pub struct SubtitleCue { | ||
| 156 | + /// Start, microseconds from the start of the media. | ||
| 157 | + pub start_us: i64, | ||
| 158 | + /// End, microseconds from the start of the media. Never before | ||
| 159 | + /// [`start_us`](Self::start_us): a backwards pair is clamped at parse. | ||
| 160 | + pub end_us: i64, | ||
| 161 | + /// The style this cue names, when the format has named styles. | ||
| 162 | + pub style_ref: Option<String>, | ||
| 163 | + /// Positioning the cue itself states. | ||
| 164 | + pub positioning: Option<CuePosition>, | ||
| 165 | + /// The body, as runs. | ||
| 166 | + pub segments: Vec<Segment>, | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// Which on-disk flavour a track was parsed from. | ||
| 170 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 171 | +pub enum SourceFormat { | ||
| 172 | + /// SubRip (`.srt`). | ||
| 173 | + Srt, | ||
| 174 | + /// WebVTT (`.vtt`). | ||
| 175 | + WebVtt, | ||
| 176 | + /// Advanced SubStation Alpha or its SSA predecessor. | ||
| 177 | + AssOrSsa, | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// A parsed subtitle file: where it came from, its styles, its cues. | ||
| 181 | +#[derive(Clone, Debug, Default, PartialEq)] | ||
| 182 | +pub struct SubtitleTrack { | ||
| 183 | + /// The flavour, when the parser knows it. | ||
| 184 | + pub source: Option<SourceFormat>, | ||
| 185 | + /// Named styles, in file order. | ||
| 186 | + pub styles: Vec<SubtitleStyle>, | ||
| 187 | + /// Cues, in file order — *not* sorted by time, because a file's own order | ||
| 188 | + /// is information (an overlapping pair is a pair, not an error). | ||
| 189 | + pub cues: Vec<SubtitleCue>, | ||
| 190 | + /// Track-level keys: `title`, `play_res_x`, `wrap_style`, `header`, … | ||
| 191 | + pub metadata: Vec<(String, String)>, | ||
| 192 | + /// Header bytes worth replaying: the ASS script header, the WebVTT | ||
| 193 | + /// preamble. What a Matroska `CodecPrivate` holds for this track. | ||
| 194 | + pub extradata: Vec<u8>, | ||
| 195 | + /// Blocks the parser could not read and skipped. Never an error on its own | ||
| 196 | + /// — a file with one torn cue is still a file of cues — but a caller that | ||
| 197 | + /// wants to say so has the count. | ||
| 198 | + pub skipped: usize, | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +impl SubtitleTrack { | ||
| 202 | + /// An empty track. | ||
| 203 | + pub fn new() -> SubtitleTrack { | ||
| 204 | + SubtitleTrack::default() | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + /// The same track, tagged with the format it was read from. | ||
| 208 | + pub fn with_source(mut self, source: SourceFormat) -> SubtitleTrack { | ||
| 209 | + self.source = Some(source); | ||
| 210 | + self | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + /// A style by name. | ||
| 214 | + pub fn style(&self, name: &str) -> Option<&SubtitleStyle> { | ||
| 215 | + self.styles.iter().find(|s| s.name == name) | ||
| 216 | + } | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// The words of a cue body, markup resolved and dropped: `\n` between lines, | ||
| 220 | +/// nothing at all for a run that is a drawing or an override this does not | ||
| 221 | +/// model. | ||
| 222 | +pub fn plain_text(segments: &[Segment]) -> String { | ||
| 223 | + let mut out = String::new(); | ||
| 224 | + append_plain(segments, &mut out); | ||
| 225 | + out | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +fn append_plain(segments: &[Segment], out: &mut String) { | ||
| 229 | + for segment in segments { | ||
| 230 | + match segment { | ||
| 231 | + Segment::Text(s) => out.push_str(s), | ||
| 232 | + Segment::LineBreak => out.push('\n'), | ||
| 233 | + Segment::Bold(children) | ||
| 234 | + | Segment::Italic(children) | ||
| 235 | + | Segment::Underline(children) | ||
| 236 | + | Segment::Strike(children) => append_plain(children, out), | ||
| 237 | + Segment::Color { children, .. } | ||
| 238 | + | Segment::Font { children, .. } | ||
| 239 | + | Segment::Voice { children, .. } | ||
| 240 | + | Segment::Class { children, .. } | ||
| 241 | + | Segment::Karaoke { children, .. } => append_plain(children, out), | ||
| 242 | + Segment::Timestamp { .. } | Segment::Raw(_) => {} | ||
| 243 | + } | ||
| 244 | + } | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +#[cfg(test)] | ||
| 248 | +mod tests { | ||
| 249 | + use super::*; | ||
| 250 | + | ||
| 251 | + #[test] | ||
| 252 | + fn plain_text_walks_the_tree_and_drops_what_cannot_be_said() { | ||
| 253 | + let segments = vec![ | ||
| 254 | + Segment::Italic(vec![Segment::Text("tilted".into())]), | ||
| 255 | + Segment::Text(" and ".into()), | ||
| 256 | + Segment::Color { | ||
| 257 | + rgb: (255, 0, 0), | ||
| 258 | + children: vec![Segment::Text("red".into())], | ||
| 259 | + }, | ||
| 260 | + Segment::LineBreak, | ||
| 261 | + Segment::Raw("{\\p1}m 0 0 l 1 1".into()), | ||
| 262 | + Segment::Timestamp { offset_us: 5 }, | ||
| 263 | + Segment::Karaoke { | ||
| 264 | + cs: 42, | ||
| 265 | + children: vec![Segment::Text("ka".into())], | ||
| 266 | + }, | ||
| 267 | + ]; | ||
| 268 | + assert_eq!(plain_text(&segments), "tilted and red\nka"); | ||
| 269 | + } | ||
| 270 | +} | ||
crates/ec-subs/src/lib.rsadded+33 -0
| @@ -0,0 +1,33 @@ | |||
| 1 | +//! Text subtitles: SubRip and WebVTT into one cue IR ([`ir`]). | ||
| 2 | +//! | ||
| 3 | +//! Both formats are read the same way and for the same reason: what a timeline | ||
| 4 | +//! wants is *when* a line is on screen and *what it says*, and the markup | ||
| 5 | +//! around that ranges from `<i>` to a dozen dialects of override tag. So a | ||
| 6 | +//! parse answers with a [`ir::SubtitleTrack`] — cues of time ranges and | ||
| 7 | +//! [`ir::Segment`] runs — and a caller that draws nothing yet takes | ||
| 8 | +//! [`ir::plain_text`] and drops the rest. | ||
| 9 | +//! | ||
| 10 | +//! Tolerance is the point. Subtitle files are hand-edited, machine-translated, | ||
| 11 | +//! re-encoded and truncated; a parser that refuses one is a parser that refuses | ||
| 12 | +//! the file the user actually has. BOMs (UTF-8 and UTF-16), CRLF and lone CR, | ||
| 13 | +//! invalid UTF-8, missing or wrong indices, dotted fractions, overlapping and | ||
| 14 | +//! backwards cues all parse. A block this cannot read is skipped and counted | ||
| 15 | +//! ([`ir::SubtitleTrack::skipped`]); only a document with no timing line in it | ||
| 16 | +//! at all is an error, because that is a document of another kind. | ||
| 17 | +//! | ||
| 18 | +//! ASS/SSA is the same IR from `ec-ass`, and PGS bitmaps from `ec-pgs`. | ||
| 19 | + | ||
| 20 | +#![forbid(unsafe_code)] | ||
| 21 | + | ||
| 22 | +pub mod ir; | ||
| 23 | +mod markup; | ||
| 24 | +pub mod srt; | ||
| 25 | +pub mod webvtt; | ||
| 26 | + | ||
| 27 | +pub use ir::{ | ||
| 28 | + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, | ||
| 29 | + plain_text, | ||
| 30 | +}; | ||
| 31 | +/// The byte-level tolerances every subtitle format needs, shared with `ec-ass`: | ||
| 32 | +/// BOM and line-ending normalisation, and the clock every one of them writes. | ||
| 33 | +pub use markup::{decode, parse_clock}; | ||
crates/ec-subs/src/markup.rsadded+474 -0
| @@ -0,0 +1,474 @@ | |||
| 1 | +//! The angle-bracket markup SubRip and WebVTT share, plus the byte-level | ||
| 2 | +//! tolerances every text format here needs. | ||
| 3 | +//! | ||
| 4 | +//! Both formats carry a subset of HTML — `<i>`, `<b>`, `<u>`, `<s>`, `<font>`, | ||
| 5 | +//! and WebVTT's `<v Speaker>`, `<c.class>` and inline timestamps — written by a | ||
| 6 | +//! thousand tools with a thousand degrees of care. So the rule is that nothing | ||
| 7 | +//! here fails: an unclosed tag closes at the end of the cue, a stray `</i>` | ||
| 8 | +//! with nothing open is dropped, and a `<` that begins no tag at all is the | ||
| 9 | +//! character it looks like. | ||
| 10 | + | ||
| 11 | +use crate::ir::Segment; | ||
| 12 | + | ||
| 13 | +/// Bytes to text, the way a subtitle file has to be read: a UTF-8 or UTF-16 BOM | ||
| 14 | +/// consumed, invalid sequences replaced rather than refused, and CRLF (or a | ||
| 15 | +/// lone CR, which classic Mac tools still write) folded to LF so every parser | ||
| 16 | +/// after this sees one line ending. | ||
| 17 | +pub fn decode(bytes: &[u8]) -> String { | ||
| 18 | + let text = if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) { | ||
| 19 | + String::from_utf8_lossy(rest).into_owned() | ||
| 20 | + } else if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) { | ||
| 21 | + utf16(rest, u16::from_le_bytes) | ||
| 22 | + } else if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) { | ||
| 23 | + utf16(rest, u16::from_be_bytes) | ||
| 24 | + } else { | ||
| 25 | + String::from_utf8_lossy(bytes).into_owned() | ||
| 26 | + }; | ||
| 27 | + if text.contains('\r') { | ||
| 28 | + text.replace("\r\n", "\n").replace('\r', "\n") | ||
| 29 | + } else { | ||
| 30 | + text | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +fn utf16(bytes: &[u8], unit: fn([u8; 2]) -> u16) -> String { | ||
| 35 | + let units: Vec<u16> = bytes.chunks_exact(2).map(|c| unit([c[0], c[1]])).collect(); | ||
| 36 | + String::from_utf16_lossy(&units) | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// `hh:mm:ss,mmm` in microseconds — the timing both text formats state, with | ||
| 40 | +/// every part they are written with in practice: comma or dot before the | ||
| 41 | +/// fraction, hours optional, a fraction of one to six digits, a leading minus | ||
| 42 | +/// on a file whose author shifted it too far. | ||
| 43 | +pub fn parse_clock(field: &str) -> Option<i64> { | ||
| 44 | + let field = field.trim(); | ||
| 45 | + let (sign, field) = match field.strip_prefix('-') { | ||
| 46 | + Some(rest) => (-1, rest), | ||
| 47 | + None => (1, field), | ||
| 48 | + }; | ||
| 49 | + let (clock, fraction) = match field.split_once([',', '.']) { | ||
| 50 | + Some((clock, fraction)) => (clock, fraction), | ||
| 51 | + None => (field, ""), | ||
| 52 | + }; | ||
| 53 | + let mut parts = clock.split(':').rev(); | ||
| 54 | + let seconds: i64 = parts.next()?.trim().parse().ok()?; | ||
| 55 | + let minutes: i64 = parts.next().map_or(Ok(0), |m| m.trim().parse()).ok()?; | ||
| 56 | + let hours: i64 = parts.next().map_or(Ok(0), |h| h.trim().parse()).ok()?; | ||
| 57 | + if parts.next().is_some() { | ||
| 58 | + return None; | ||
| 59 | + } | ||
| 60 | + // A fraction is a fraction whatever its length: `.5` is half a second and | ||
| 61 | + // `.500000` is the same instant. | ||
| 62 | + let digits: String = fraction | ||
| 63 | + .chars() | ||
| 64 | + .take_while(char::is_ascii_digit) | ||
| 65 | + .take(6) | ||
| 66 | + .collect(); | ||
| 67 | + let micros = if digits.is_empty() { | ||
| 68 | + 0 | ||
| 69 | + } else { | ||
| 70 | + let value: i64 = digits.parse().ok()?; | ||
| 71 | + value * 10i64.pow(6 - digits.len() as u32) | ||
| 72 | + }; | ||
| 73 | + Some(sign * ((hours * 3600 + minutes * 60 + seconds) * 1_000_000 + micros)) | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// One cue body's markup as runs. `webvtt` turns on the two tags only WebVTT | ||
| 77 | +/// has — `<v>` and `<c>` — and the inline timestamps that go with them. | ||
| 78 | +pub(crate) fn parse_inline(body: &str, webvtt: bool) -> Vec<Segment> { | ||
| 79 | + // A stack of open tags, each with the children collected inside it so far; | ||
| 80 | + // the bottom frame is the cue itself and can never be popped. | ||
| 81 | + let mut stack: Vec<(Option<Open>, Vec<Segment>)> = vec![(None, Vec::new())]; | ||
| 82 | + let mut text = String::new(); | ||
| 83 | + let mut rest = body; | ||
| 84 | + while let Some(at) = rest.find('<') { | ||
| 85 | + text.push_str(&unescape(&rest[..at])); | ||
| 86 | + let after = &rest[at + 1..]; | ||
| 87 | + let Some(end) = after.find('>') else { | ||
| 88 | + // No closing bracket anywhere: the rest of the cue is text. | ||
| 89 | + text.push_str(&unescape(&rest[at..])); | ||
| 90 | + rest = ""; | ||
| 91 | + break; | ||
| 92 | + }; | ||
| 93 | + let tag = &after[..end]; | ||
| 94 | + rest = &after[end + 1..]; | ||
| 95 | + match classify(tag, webvtt) { | ||
| 96 | + Tag::Text => { | ||
| 97 | + text.push('<'); | ||
| 98 | + text.push_str(&unescape(tag)); | ||
| 99 | + text.push('>'); | ||
| 100 | + } | ||
| 101 | + Tag::Timestamp(offset_us) => { | ||
| 102 | + flush(&mut text, &mut stack); | ||
| 103 | + push(&mut stack, Segment::Timestamp { offset_us }); | ||
| 104 | + } | ||
| 105 | + Tag::Raw => { | ||
| 106 | + flush(&mut text, &mut stack); | ||
| 107 | + push(&mut stack, Segment::Raw(format!("<{tag}>"))); | ||
| 108 | + } | ||
| 109 | + Tag::Open(open) => { | ||
| 110 | + flush(&mut text, &mut stack); | ||
| 111 | + stack.push((Some(open), Vec::new())); | ||
| 112 | + } | ||
| 113 | + Tag::Close(name) => { | ||
| 114 | + flush(&mut text, &mut stack); | ||
| 115 | + // Close the innermost frame with that name, and everything | ||
| 116 | + // inside it: `<b><i></b>` closes both, which is what a browser | ||
| 117 | + // does with the same bytes. | ||
| 118 | + let found = stack | ||
| 119 | + .iter() | ||
| 120 | + .rposition(|(open, _)| open.as_ref().is_some_and(|o| o.name == name)); | ||
| 121 | + if let Some(depth) = found { | ||
| 122 | + while stack.len() > depth { | ||
| 123 | + close_top(&mut stack); | ||
| 124 | + } | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + text.push_str(&unescape(rest)); | ||
| 130 | + flush(&mut text, &mut stack); | ||
| 131 | + while stack.len() > 1 { | ||
| 132 | + close_top(&mut stack); | ||
| 133 | + } | ||
| 134 | + stack | ||
| 135 | + .pop() | ||
| 136 | + .map(|(_, children)| children) | ||
| 137 | + .unwrap_or_default() | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// An open tag: its name and the arguments the closing wrapper will need. | ||
| 141 | +struct Open { | ||
| 142 | + name: String, | ||
| 143 | + color: Option<(u8, u8, u8)>, | ||
| 144 | + family: Option<String>, | ||
| 145 | + size: Option<f32>, | ||
| 146 | + annotation: String, | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +enum Tag { | ||
| 150 | + Open(Open), | ||
| 151 | + Close(String), | ||
| 152 | + Timestamp(i64), | ||
| 153 | + Raw, | ||
| 154 | + /// Not a tag at all — a `<` that means `<`. | ||
| 155 | + Text, | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +fn classify(tag: &str, webvtt: bool) -> Tag { | ||
| 159 | + let trimmed = tag.trim(); | ||
| 160 | + if trimmed.is_empty() { | ||
| 161 | + return Tag::Text; | ||
| 162 | + } | ||
| 163 | + if let Some(name) = trimmed.strip_prefix('/') { | ||
| 164 | + let name = name.trim().to_ascii_lowercase(); | ||
| 165 | + let name = name.split(['.', ' ']).next().unwrap_or("").to_owned(); | ||
| 166 | + return Tag::Close(name); | ||
| 167 | + } | ||
| 168 | + // `<00:00:01.500>` is a cue timestamp, not an element. | ||
| 169 | + if webvtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) { | ||
| 170 | + return match parse_clock(trimmed) { | ||
| 171 | + Some(offset_us) => Tag::Timestamp(offset_us), | ||
| 172 | + None => Tag::Text, | ||
| 173 | + }; | ||
| 174 | + } | ||
| 175 | + let (head, attrs) = match trimmed.split_once(char::is_whitespace) { | ||
| 176 | + Some((head, attrs)) => (head, attrs), | ||
| 177 | + None => (trimmed, ""), | ||
| 178 | + }; | ||
| 179 | + let (head, classes) = match head.split_once('.') { | ||
| 180 | + Some((head, classes)) => (head, classes), | ||
| 181 | + None => (head, ""), | ||
| 182 | + }; | ||
| 183 | + let name = head.trim_end_matches('/').to_ascii_lowercase(); | ||
| 184 | + match name.as_str() { | ||
| 185 | + "b" | "i" | "u" | "s" => Tag::Open(Open { | ||
| 186 | + name, | ||
| 187 | + color: None, | ||
| 188 | + family: None, | ||
| 189 | + size: None, | ||
| 190 | + annotation: String::new(), | ||
| 191 | + }), | ||
| 192 | + "font" => Tag::Open(Open { | ||
| 193 | + name, | ||
| 194 | + color: attribute(attrs, "color").and_then(|v| parse_color(&v)), | ||
| 195 | + family: attribute(attrs, "face"), | ||
| 196 | + size: attribute(attrs, "size").and_then(|v| v.trim().parse().ok()), | ||
| 197 | + annotation: String::new(), | ||
| 198 | + }), | ||
| 199 | + "v" | "c" if webvtt => Tag::Open(Open { | ||
| 200 | + annotation: match name.as_str() { | ||
| 201 | + "v" => attrs.trim().to_owned(), | ||
| 202 | + _ => classes.replace('.', " "), | ||
| 203 | + }, | ||
| 204 | + name, | ||
| 205 | + color: None, | ||
| 206 | + family: None, | ||
| 207 | + size: None, | ||
| 208 | + }), | ||
| 209 | + _ => Tag::Raw, | ||
| 210 | + } | ||
| 211 | +} | ||
| 212 | + | ||
| 213 | +/// `name="value"` / `name=value` out of a tag's attribute text. | ||
| 214 | +fn attribute(attrs: &str, name: &str) -> Option<String> { | ||
| 215 | + let lower = attrs.to_ascii_lowercase(); | ||
| 216 | + let mut from = 0; | ||
| 217 | + loop { | ||
| 218 | + let at = lower[from..].find(name)? + from; | ||
| 219 | + let after = attrs[at + name.len()..].trim_start(); | ||
| 220 | + match after.strip_prefix('=') { | ||
| 221 | + Some(value) => { | ||
| 222 | + let value = value.trim_start(); | ||
| 223 | + let quoted = value.strip_prefix(['"', '\'']); | ||
| 224 | + return Some(match quoted { | ||
| 225 | + Some(v) => v.split(['"', '\'']).next().unwrap_or(v).to_owned(), | ||
| 226 | + None => value | ||
| 227 | + .split_whitespace() | ||
| 228 | + .next() | ||
| 229 | + .unwrap_or_default() | ||
| 230 | + .trim_end_matches('/') | ||
| 231 | + .to_owned(), | ||
| 232 | + }); | ||
| 233 | + } | ||
| 234 | + None => from = at + name.len(), | ||
| 235 | + } | ||
| 236 | + } | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +/// `#rrggbb`, `#rgb`, or one of the sixteen names HTML has always had. | ||
| 240 | +fn parse_color(value: &str) -> Option<(u8, u8, u8)> { | ||
| 241 | + let value = value.trim(); | ||
| 242 | + if let Some(hex) = value.strip_prefix('#') { | ||
| 243 | + let digits: String = hex.chars().take_while(char::is_ascii_hexdigit).collect(); | ||
| 244 | + let byte = |s: &str| u8::from_str_radix(s, 16).ok(); | ||
| 245 | + return match digits.len() { | ||
| 246 | + 3 => { | ||
| 247 | + let mut c = digits.chars().map(|c| byte(&format!("{c}{c}"))); | ||
| 248 | + Some((c.next()??, c.next()??, c.next()??)) | ||
| 249 | + } | ||
| 250 | + 6 | 8 => Some(( | ||
| 251 | + byte(&digits[0..2])?, | ||
| 252 | + byte(&digits[2..4])?, | ||
| 253 | + byte(&digits[4..6])?, | ||
| 254 | + )), | ||
| 255 | + _ => None, | ||
| 256 | + }; | ||
| 257 | + } | ||
| 258 | + let named = [ | ||
| 259 | + ("black", (0, 0, 0)), | ||
| 260 | + ("silver", (192, 192, 192)), | ||
| 261 | + ("gray", (128, 128, 128)), | ||
| 262 | + ("grey", (128, 128, 128)), | ||
| 263 | + ("white", (255, 255, 255)), | ||
| 264 | + ("maroon", (128, 0, 0)), | ||
| 265 | + ("red", (255, 0, 0)), | ||
| 266 | + ("purple", (128, 0, 128)), | ||
| 267 | + ("fuchsia", (255, 0, 255)), | ||
| 268 | + ("green", (0, 128, 0)), | ||
| 269 | + ("lime", (0, 255, 0)), | ||
| 270 | + ("olive", (128, 128, 0)), | ||
| 271 | + ("yellow", (255, 255, 0)), | ||
| 272 | + ("navy", (0, 0, 128)), | ||
| 273 | + ("blue", (0, 0, 255)), | ||
| 274 | + ("teal", (0, 128, 128)), | ||
| 275 | + ("aqua", (0, 255, 255)), | ||
| 276 | + ("cyan", (0, 255, 255)), | ||
| 277 | + ("magenta", (255, 0, 255)), | ||
| 278 | + ]; | ||
| 279 | + let lower = value.to_ascii_lowercase(); | ||
| 280 | + named | ||
| 281 | + .iter() | ||
| 282 | + .find(|(name, _)| *name == lower) | ||
| 283 | + .map(|(_, rgb)| *rgb) | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +/// The handful of entities subtitle text is written with, plus numeric ones. | ||
| 287 | +fn unescape(text: &str) -> String { | ||
| 288 | + if !text.contains('&') { | ||
| 289 | + return text.to_owned(); | ||
| 290 | + } | ||
| 291 | + let mut out = String::with_capacity(text.len()); | ||
| 292 | + let mut rest = text; | ||
| 293 | + while let Some(at) = rest.find('&') { | ||
| 294 | + out.push_str(&rest[..at]); | ||
| 295 | + let after = &rest[at + 1..]; | ||
| 296 | + let end = after.find(';').filter(|&e| e <= 10); | ||
| 297 | + let Some(end) = end else { | ||
| 298 | + out.push('&'); | ||
| 299 | + rest = after; | ||
| 300 | + continue; | ||
| 301 | + }; | ||
| 302 | + let name = &after[..end]; | ||
| 303 | + let replacement = match name.to_ascii_lowercase().as_str() { | ||
| 304 | + "amp" => Some('&'), | ||
| 305 | + "lt" => Some('<'), | ||
| 306 | + "gt" => Some('>'), | ||
| 307 | + "quot" => Some('"'), | ||
| 308 | + "apos" => Some('\''), | ||
| 309 | + "nbsp" => Some('\u{a0}'), | ||
| 310 | + "lrm" => Some('\u{200e}'), | ||
| 311 | + "rlm" => Some('\u{200f}'), | ||
| 312 | + other => other | ||
| 313 | + .strip_prefix('#') | ||
| 314 | + .and_then(|n| match n.strip_prefix(['x', 'X']) { | ||
| 315 | + Some(hex) => u32::from_str_radix(hex, 16).ok(), | ||
| 316 | + None => n.parse().ok(), | ||
| 317 | + }) | ||
| 318 | + .and_then(char::from_u32), | ||
| 319 | + }; | ||
| 320 | + match replacement { | ||
| 321 | + Some(c) => { | ||
| 322 | + out.push(c); | ||
| 323 | + rest = &after[end + 1..]; | ||
| 324 | + } | ||
| 325 | + None => { | ||
| 326 | + out.push('&'); | ||
| 327 | + rest = after; | ||
| 328 | + } | ||
| 329 | + } | ||
| 330 | + } | ||
| 331 | + out.push_str(rest); | ||
| 332 | + out | ||
| 333 | +} | ||
| 334 | + | ||
| 335 | +fn flush(text: &mut String, stack: &mut [(Option<Open>, Vec<Segment>)]) { | ||
| 336 | + if !text.is_empty() { | ||
| 337 | + let taken = std::mem::take(text); | ||
| 338 | + // A newline inside a cue body is a line break, not whitespace. | ||
| 339 | + let mut lines = taken.split('\n'); | ||
| 340 | + if let Some(first) = lines.next() | ||
| 341 | + && !first.is_empty() | ||
| 342 | + { | ||
| 343 | + stack | ||
| 344 | + .last_mut() | ||
| 345 | + .unwrap() | ||
| 346 | + .1 | ||
| 347 | + .push(Segment::Text(first.into())); | ||
| 348 | + } | ||
| 349 | + for line in lines { | ||
| 350 | + let children = &mut stack.last_mut().unwrap().1; | ||
| 351 | + children.push(Segment::LineBreak); | ||
| 352 | + if !line.is_empty() { | ||
| 353 | + children.push(Segment::Text(line.into())); | ||
| 354 | + } | ||
| 355 | + } | ||
| 356 | + } | ||
| 357 | +} | ||
| 358 | + | ||
| 359 | +fn push(stack: &mut [(Option<Open>, Vec<Segment>)], segment: Segment) { | ||
| 360 | + stack.last_mut().unwrap().1.push(segment); | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +fn close_top(stack: &mut Vec<(Option<Open>, Vec<Segment>)>) { | ||
| 364 | + let Some((open, children)) = stack.pop() else { | ||
| 365 | + return; | ||
| 366 | + }; | ||
| 367 | + let Some(open) = open else { return }; | ||
| 368 | + let parent = &mut stack.last_mut().unwrap().1; | ||
| 369 | + match open.name.as_str() { | ||
| 370 | + "b" => parent.push(Segment::Bold(children)), | ||
| 371 | + "i" => parent.push(Segment::Italic(children)), | ||
| 372 | + "u" => parent.push(Segment::Underline(children)), | ||
| 373 | + "s" => parent.push(Segment::Strike(children)), | ||
| 374 | + "v" => parent.push(Segment::Voice { | ||
| 375 | + name: open.annotation, | ||
| 376 | + children, | ||
| 377 | + }), | ||
| 378 | + "c" => parent.push(Segment::Class { | ||
| 379 | + name: open.annotation, | ||
| 380 | + children, | ||
| 381 | + }), | ||
| 382 | + // `<font>`: whichever of colour and face/size it stated. One that | ||
| 383 | + // stated neither is a frame with nothing to say, so it is unwrapped | ||
| 384 | + // rather than kept as an empty node. | ||
| 385 | + _ => { | ||
| 386 | + if let Some(rgb) = open.color { | ||
| 387 | + parent.push(Segment::Color { rgb, children }); | ||
| 388 | + } else if open.family.is_some() || open.size.is_some() { | ||
| 389 | + parent.push(Segment::Font { | ||
| 390 | + family: open.family, | ||
| 391 | + size: open.size, | ||
| 392 | + children, | ||
| 393 | + }); | ||
| 394 | + } else { | ||
| 395 | + parent.extend(children); | ||
| 396 | + } | ||
| 397 | + } | ||
| 398 | + } | ||
| 399 | +} | ||
| 400 | + | ||
| 401 | +#[cfg(test)] | ||
| 402 | +mod tests { | ||
| 403 | + use super::*; | ||
| 404 | + use crate::ir::plain_text; | ||
| 405 | + | ||
| 406 | + #[test] | ||
| 407 | + fn clocks_are_read_in_every_shape_a_file_writes_them() { | ||
| 408 | + assert_eq!(parse_clock("00:00:01,500"), Some(1_500_000)); | ||
| 409 | + assert_eq!(parse_clock("00:00:01.5"), Some(1_500_000)); | ||
| 410 | + assert_eq!(parse_clock("1:02:03.250"), Some(3_723_250_000)); | ||
| 411 | + // Hours omitted, as WebVTT allows. | ||
| 412 | + assert_eq!(parse_clock("02:03.000"), Some(123_000_000)); | ||
| 413 | + // Six digits and beyond. | ||
| 414 | + assert_eq!(parse_clock("0:00:00.123456"), Some(123_456)); | ||
| 415 | + assert_eq!(parse_clock("0:00:00.1234569"), Some(123_456)); | ||
| 416 | + assert_eq!(parse_clock("-0:00:01.000"), Some(-1_000_000)); | ||
| 417 | + assert_eq!(parse_clock("not a time"), None); | ||
| 418 | + assert_eq!(parse_clock("1:2:3:4.0"), None); | ||
| 419 | + } | ||
| 420 | + | ||
| 421 | + #[test] | ||
| 422 | + fn decode_takes_the_bom_and_folds_the_line_endings() { | ||
| 423 | + assert_eq!(decode(b"\xef\xbb\xbfa\r\nb\rc"), "a\nb\nc"); | ||
| 424 | + assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, b'i', 0]), "hi"); | ||
| 425 | + // Invalid UTF-8 is replaced, never refused. | ||
| 426 | + assert_eq!(decode(b"a\xffb"), "a\u{fffd}b"); | ||
| 427 | + } | ||
| 428 | + | ||
| 429 | + #[test] | ||
| 430 | + fn markup_nests_and_forgives() { | ||
| 431 | + let segments = parse_inline("<i>a</i> <b>b", false); | ||
| 432 | + assert_eq!(plain_text(&segments), "a b"); | ||
| 433 | + assert!(matches!(segments[0], Segment::Italic(_))); | ||
| 434 | + assert!(matches!(segments[2], Segment::Bold(_))); | ||
| 435 | + // Mismatched close, stray close, and a `<` that is just a `<`. | ||
| 436 | + assert_eq!(plain_text(&parse_inline("<b><i>x</b>y", false)), "xy"); | ||
| 437 | + assert_eq!(plain_text(&parse_inline("</i>plain", false)), "plain"); | ||
| 438 | + assert_eq!(plain_text(&parse_inline("a < b", false)), "a < b"); | ||
| 439 | + assert_eq!( | ||
| 440 | + plain_text(&parse_inline("2 < 3 & 4", false)), | ||
| 441 | + "2 < 3 & 4" | ||
| 442 | + ); | ||
| 443 | + } | ||
| 444 | + | ||
| 445 | + #[test] | ||
| 446 | + fn webvtt_only_tags_are_off_for_srt() { | ||
| 447 | + let vtt = parse_inline("<v Ann>hi</v>", true); | ||
| 448 | + assert!(matches!(vtt[0], Segment::Voice { .. })); | ||
| 449 | + assert_eq!(plain_text(&vtt), "hi"); | ||
| 450 | + let srt = parse_inline("<v Ann>hi", false); | ||
| 451 | + assert_eq!(plain_text(&srt), "hi"); | ||
| 452 | + assert!(matches!(srt[0], Segment::Raw(_))); | ||
| 453 | + } | ||
| 454 | + | ||
| 455 | + #[test] | ||
| 456 | + fn font_colour_is_read_by_hex_and_by_name() { | ||
| 457 | + let segments = parse_inline("<font color=\"#ff0000\">red</font>", false); | ||
| 458 | + assert!(matches!( | ||
| 459 | + segments[0], | ||
| 460 | + Segment::Color { | ||
| 461 | + rgb: (255, 0, 0), | ||
| 462 | + .. | ||
| 463 | + } | ||
| 464 | + )); | ||
| 465 | + let named = parse_inline("<font color=lime>green</font>", false); | ||
| 466 | + assert!(matches!( | ||
| 467 | + named[0], | ||
| 468 | + Segment::Color { | ||
| 469 | + rgb: (0, 255, 0), | ||
| 470 | + .. | ||
| 471 | + } | ||
| 472 | + )); | ||
| 473 | + } | ||
| 474 | +} | ||
crates/ec-subs/src/srt.rsadded+131 -0
| @@ -0,0 +1,131 @@ | |||
| 1 | +//! SubRip (`.srt`). | ||
| 2 | +//! | ||
| 3 | +//! The format is a list of blocks separated by blank lines: an index, a timing | ||
| 4 | +//! line, then the text. In the wild the index is optional, wrong, or repeated; | ||
| 5 | +//! the fraction is a comma or a dot; the timing line trails coordinates | ||
| 6 | +//! (`X1:0 X2:640 …`) that nothing reads any more. So the *timing line* is what | ||
| 7 | +//! identifies a block here — a block without one is skipped and counted rather | ||
| 8 | +//! than taken as text of the block before it. | ||
| 9 | + | ||
| 10 | +use ec_core::{Error, Result}; | ||
| 11 | + | ||
| 12 | +use crate::ir::{SourceFormat, SubtitleCue, SubtitleTrack}; | ||
| 13 | +use crate::markup::{decode, parse_clock, parse_inline}; | ||
| 14 | + | ||
| 15 | +/// Parse a SubRip document. | ||
| 16 | +/// | ||
| 17 | +/// `Err` only when the bytes are not this format at all — text with no timing | ||
| 18 | +/// line anywhere in it. A file with some torn blocks parses to the blocks that | ||
| 19 | +/// are whole, with [`SubtitleTrack::skipped`] counting the rest. | ||
| 20 | +pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> { | ||
| 21 | + let text = decode(bytes); | ||
| 22 | + let mut track = SubtitleTrack::new().with_source(SourceFormat::Srt); | ||
| 23 | + for block in blocks(&text) { | ||
| 24 | + // The timing line is the anchor: everything before it is an index (or | ||
| 25 | + // rubbish), everything after it is the cue's text. | ||
| 26 | + let Some((at, (start_us, end_us))) = block | ||
| 27 | + .iter() | ||
| 28 | + .enumerate() | ||
| 29 | + .find_map(|(i, line)| timing(line).map(|t| (i, t))) | ||
| 30 | + else { | ||
| 31 | + track.skipped += 1; | ||
| 32 | + continue; | ||
| 33 | + }; | ||
| 34 | + let body = block[at + 1..].join("\n"); | ||
| 35 | + track.cues.push(SubtitleCue { | ||
| 36 | + start_us, | ||
| 37 | + // A file that ends a cue before it starts says nothing about how | ||
| 38 | + // long it is up; the cue is kept, with no duration rather than a | ||
| 39 | + // negative one. | ||
| 40 | + end_us: end_us.max(start_us), | ||
| 41 | + style_ref: None, | ||
| 42 | + positioning: None, | ||
| 43 | + segments: parse_inline(body.trim_end(), false), | ||
| 44 | + }); | ||
| 45 | + } | ||
| 46 | + if track.cues.is_empty() && text.split_whitespace().next().is_some() { | ||
| 47 | + return Err(Error::corrupt( | ||
| 48 | + "no SubRip timing line in the whole document", | ||
| 49 | + )); | ||
| 50 | + } | ||
| 51 | + Ok(track) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// Blocks, split on blank lines, blank ones dropped. | ||
| 55 | +fn blocks(text: &str) -> impl Iterator<Item = Vec<&str>> { | ||
| 56 | + let mut out: Vec<Vec<&str>> = Vec::new(); | ||
| 57 | + let mut current: Vec<&str> = Vec::new(); | ||
| 58 | + for line in text.lines() { | ||
| 59 | + if line.trim().is_empty() { | ||
| 60 | + if !current.is_empty() { | ||
| 61 | + out.push(std::mem::take(&mut current)); | ||
| 62 | + } | ||
| 63 | + } else { | ||
| 64 | + current.push(line); | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | + if !current.is_empty() { | ||
| 68 | + out.push(current); | ||
| 69 | + } | ||
| 70 | + out.into_iter() | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// `00:00:01,000 --> 00:00:02,000` with anything after it ignored. | ||
| 74 | +pub(crate) fn timing(line: &str) -> Option<(i64, i64)> { | ||
| 75 | + let (start, rest) = line.split_once("-->")?; | ||
| 76 | + let end = rest.split_whitespace().next().unwrap_or_default(); | ||
| 77 | + Some((parse_clock(start)?, parse_clock(end)?)) | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +#[cfg(test)] | ||
| 81 | +mod tests { | ||
| 82 | + use super::*; | ||
| 83 | + use crate::ir::plain_text; | ||
| 84 | + | ||
| 85 | + #[test] | ||
| 86 | + fn an_ordinary_file_parses() { | ||
| 87 | + let doc = "1\n00:00:01,000 --> 00:00:02,500\nfirst line\nsecond line\n\n\ | ||
| 88 | + 2\n00:00:03,000 --> 00:00:04,000\n<i>tilted</i>\n"; | ||
| 89 | + let track = parse(doc.as_bytes()).unwrap(); | ||
| 90 | + assert_eq!(track.source, Some(SourceFormat::Srt)); | ||
| 91 | + assert_eq!(track.cues.len(), 2); | ||
| 92 | + assert_eq!(track.cues[0].start_us, 1_000_000); | ||
| 93 | + assert_eq!(track.cues[0].end_us, 2_500_000); | ||
| 94 | + assert_eq!( | ||
| 95 | + plain_text(&track.cues[0].segments), | ||
| 96 | + "first line\nsecond line" | ||
| 97 | + ); | ||
| 98 | + assert_eq!(plain_text(&track.cues[1].segments), "tilted"); | ||
| 99 | + assert_eq!(track.skipped, 0); | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + #[test] | ||
| 103 | + fn the_tolerances_a_real_file_needs() { | ||
| 104 | + // BOM, CRLF, no indices, dotted fraction, trailing coordinates, an | ||
| 105 | + // overlapping pair, and a block that is text with no timing at all. | ||
| 106 | + let doc = b"\xef\xbb\xbf00:00:01.000 --> 00:00:04,000 X1:0 X2:640\r\none\r\n\r\n\ | ||
| 107 | + junk with no timing\r\n\r\n\ | ||
| 108 | + 00:00:02,000 --> 00:00:03,000\r\ntwo\r\n"; | ||
| 109 | + let track = parse(doc).unwrap(); | ||
| 110 | + assert_eq!(track.cues.len(), 2); | ||
| 111 | + assert_eq!(track.skipped, 1); | ||
| 112 | + assert_eq!(track.cues[0].end_us, 4_000_000); | ||
| 113 | + // Overlapping cues stay in file order, both of them. | ||
| 114 | + assert_eq!(track.cues[1].start_us, 2_000_000); | ||
| 115 | + assert_eq!(plain_text(&track.cues[1].segments), "two"); | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + #[test] | ||
| 119 | + fn a_backwards_pair_is_clamped_not_negative() { | ||
| 120 | + let doc = "1\n00:00:05,000 --> 00:00:01,000\nback\n"; | ||
| 121 | + let cue = &parse(doc.as_bytes()).unwrap().cues[0]; | ||
| 122 | + assert_eq!((cue.start_us, cue.end_us), (5_000_000, 5_000_000)); | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + #[test] | ||
| 126 | + fn text_that_is_not_a_subtitle_file_is_refused_but_empty_is_not() { | ||
| 127 | + assert!(parse(b"this is a text file\nwith no timings").is_err()); | ||
| 128 | + assert_eq!(parse(b"").unwrap().cues.len(), 0); | ||
| 129 | + assert_eq!(parse(b"\n\n \n").unwrap().cues.len(), 0); | ||
| 130 | + } | ||
| 131 | +} | ||
crates/ec-subs/src/webvtt.rsadded+174 -0
| @@ -0,0 +1,174 @@ | |||
| 1 | +//! WebVTT (`.vtt`). | ||
| 2 | +//! | ||
| 3 | +//! SubRip's shape with a `WEBVTT` header, optional cue identifiers, cue | ||
| 4 | +//! settings after the timing line, and two tags of its own (`<v Speaker>`, | ||
| 5 | +//! `<c.class>`) plus inline timestamps. `NOTE`, `STYLE` and `REGION` blocks | ||
| 6 | +//! are read past: they say nothing about *when* anything is on screen, which | ||
| 7 | +//! is what this IR carries. | ||
| 8 | + | ||
| 9 | +use ec_core::{Error, Result}; | ||
| 10 | + | ||
| 11 | +use crate::ir::{CuePosition, SourceFormat, SubtitleCue, SubtitleTrack, TextAlign}; | ||
| 12 | +use crate::markup::{decode, parse_inline}; | ||
| 13 | +use crate::srt::timing; | ||
| 14 | + | ||
| 15 | +/// Parse a WebVTT document. | ||
| 16 | +/// | ||
| 17 | +/// The `WEBVTT` signature is *expected*, not required — a file missing it but | ||
| 18 | +/// full of cues is a file of cues. `Err` is for text with no timing line | ||
| 19 | +/// anywhere, exactly as in [`crate::srt::parse`]. | ||
| 20 | +pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> { | ||
| 21 | + let text = decode(bytes); | ||
| 22 | + let mut track = SubtitleTrack::new().with_source(SourceFormat::WebVtt); | ||
| 23 | + let mut blocks = text.split("\n\n").peekable(); | ||
| 24 | + if let Some(first) = blocks.peek() | ||
| 25 | + && let Some(header) = first.trim_start().strip_prefix("WEBVTT") | ||
| 26 | + { | ||
| 27 | + let header = header.trim(); | ||
| 28 | + if !header.is_empty() { | ||
| 29 | + track | ||
| 30 | + .metadata | ||
| 31 | + .push(("header".to_owned(), header.to_owned())); | ||
| 32 | + } | ||
| 33 | + track.extradata = first.trim_start().as_bytes().to_vec(); | ||
| 34 | + blocks.next(); | ||
| 35 | + } | ||
| 36 | + for block in blocks { | ||
| 37 | + let lines: Vec<&str> = block.lines().filter(|l| !l.trim().is_empty()).collect(); | ||
| 38 | + let Some(first) = lines.first() else { continue }; | ||
| 39 | + // Blocks that are not cues, by their first word. | ||
| 40 | + let keyword = first.split_whitespace().next().unwrap_or_default(); | ||
| 41 | + if matches!(keyword, "NOTE" | "STYLE" | "REGION") { | ||
| 42 | + continue; | ||
| 43 | + } | ||
| 44 | + let Some((at, (start_us, end_us))) = lines | ||
| 45 | + .iter() | ||
| 46 | + .enumerate() | ||
| 47 | + .find_map(|(i, line)| timing(line).map(|t| (i, t))) | ||
| 48 | + else { | ||
| 49 | + track.skipped += 1; | ||
| 50 | + continue; | ||
| 51 | + }; | ||
| 52 | + // Anything before the timing line is the cue identifier, which names | ||
| 53 | + // the cue for styling and says nothing about its timing or its text. | ||
| 54 | + let body = lines[at + 1..].join("\n"); | ||
| 55 | + track.cues.push(SubtitleCue { | ||
| 56 | + start_us, | ||
| 57 | + end_us: end_us.max(start_us), | ||
| 58 | + style_ref: None, | ||
| 59 | + positioning: settings(lines[at]), | ||
| 60 | + segments: parse_inline(body.trim_end(), true), | ||
| 61 | + }); | ||
| 62 | + } | ||
| 63 | + if track.cues.is_empty() && text.split_whitespace().next().is_some() { | ||
| 64 | + return Err(Error::corrupt( | ||
| 65 | + "no WebVTT timing line in the whole document", | ||
| 66 | + )); | ||
| 67 | + } | ||
| 68 | + Ok(track) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// The `align:`, `position:`, `line:` and `size:` settings after a timing line. | ||
| 72 | +/// `None` when the line carries none of them. | ||
| 73 | +fn settings(line: &str) -> Option<CuePosition> { | ||
| 74 | + let after = line.split_once("-->")?.1; | ||
| 75 | + // The end timestamp first, then the settings. | ||
| 76 | + let mut position = CuePosition::default(); | ||
| 77 | + let mut any = false; | ||
| 78 | + for setting in after.split_whitespace().skip(1) { | ||
| 79 | + let Some((key, value)) = setting.split_once(':') else { | ||
| 80 | + continue; | ||
| 81 | + }; | ||
| 82 | + // `position:10%,line-left` — the alignment suffix is not the number. | ||
| 83 | + let number = || { | ||
| 84 | + value | ||
| 85 | + .split(',') | ||
| 86 | + .next() | ||
| 87 | + .unwrap_or_default() | ||
| 88 | + .trim_end_matches('%') | ||
| 89 | + .parse::<f32>() | ||
| 90 | + .ok() | ||
| 91 | + }; | ||
| 92 | + match key { | ||
| 93 | + "align" => { | ||
| 94 | + position.align = match value { | ||
| 95 | + "start" => TextAlign::Start, | ||
| 96 | + "center" | "middle" => TextAlign::Center, | ||
| 97 | + "end" => TextAlign::End, | ||
| 98 | + "left" => TextAlign::Left, | ||
| 99 | + "right" => TextAlign::Right, | ||
| 100 | + _ => continue, | ||
| 101 | + }; | ||
| 102 | + any = true; | ||
| 103 | + } | ||
| 104 | + "position" => { | ||
| 105 | + position.x = number(); | ||
| 106 | + any |= position.x.is_some(); | ||
| 107 | + } | ||
| 108 | + // A `line` without a `%` is a line *number*, not a percentage; | ||
| 109 | + // it is carried as given, which is what the renderer will need. | ||
| 110 | + "line" => { | ||
| 111 | + position.y = number(); | ||
| 112 | + any |= position.y.is_some(); | ||
| 113 | + } | ||
| 114 | + "size" => { | ||
| 115 | + position.size = number(); | ||
| 116 | + any |= position.size.is_some(); | ||
| 117 | + } | ||
| 118 | + _ => {} | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + any.then_some(position) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +#[cfg(test)] | ||
| 125 | +mod tests { | ||
| 126 | + use super::*; | ||
| 127 | + use crate::ir::{Segment, plain_text}; | ||
| 128 | + | ||
| 129 | + #[test] | ||
| 130 | + fn header_identifiers_notes_and_settings() { | ||
| 131 | + let doc = "WEBVTT - a title\n\n\ | ||
| 132 | + NOTE this block says nothing\n\n\ | ||
| 133 | + cue-1\n00:00:01.000 --> 00:00:02.000 align:center position:40% line:90%\n\ | ||
| 134 | + <v Ann>hello</v>\n\n\ | ||
| 135 | + 00:01:00.000 --> 00:01:02.000\nplain\n"; | ||
| 136 | + let track = parse(doc.as_bytes()).unwrap(); | ||
| 137 | + assert_eq!(track.source, Some(SourceFormat::WebVtt)); | ||
| 138 | + assert_eq!( | ||
| 139 | + track.metadata, | ||
| 140 | + vec![("header".to_owned(), "- a title".to_owned())] | ||
| 141 | + ); | ||
| 142 | + assert_eq!(track.cues.len(), 2); | ||
| 143 | + let first = &track.cues[0]; | ||
| 144 | + assert_eq!((first.start_us, first.end_us), (1_000_000, 2_000_000)); | ||
| 145 | + let position = first.positioning.unwrap(); | ||
| 146 | + assert_eq!(position.align, TextAlign::Center); | ||
| 147 | + assert_eq!((position.x, position.y), (Some(40.0), Some(90.0))); | ||
| 148 | + assert_eq!(plain_text(&first.segments), "hello"); | ||
| 149 | + assert!(matches!(first.segments[0], Segment::Voice { .. })); | ||
| 150 | + assert_eq!(track.cues[1].positioning, None); | ||
| 151 | + assert_eq!(track.cues[1].start_us, 60_000_000); | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + #[test] | ||
| 155 | + fn inline_timestamps_and_classes_are_runs_not_words() { | ||
| 156 | + let doc = "WEBVTT\n\n00:00:00.000 --> 00:00:09.000\n\ | ||
| 157 | + <c.loud>shout</c><00:00:03.000>then quiet\n"; | ||
| 158 | + let cue = &parse(doc.as_bytes()).unwrap().cues[0]; | ||
| 159 | + assert_eq!(plain_text(&cue.segments), "shoutthen quiet"); | ||
| 160 | + assert!(cue.segments.iter().any(|s| matches!( | ||
| 161 | + s, | ||
| 162 | + Segment::Timestamp { | ||
| 163 | + offset_us: 3_000_000 | ||
| 164 | + } | ||
| 165 | + ))); | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + #[test] | ||
| 169 | + fn a_file_without_the_signature_still_parses_and_prose_does_not() { | ||
| 170 | + let track = parse(b"00:00:01.000 --> 00:00:02.000\nhi\n").unwrap(); | ||
| 171 | + assert_eq!(track.cues.len(), 1); | ||
| 172 | + assert!(parse(b"WEBVTT\n\nNOTE just a note\n\nnot a cue block").is_err()); | ||
| 173 | + } | ||
| 174 | +} | ||
crates/ec-subs/tests/real_library.rsadded+142 -0
| @@ -0,0 +1,142 @@ | |||
| 1 | +//! The three parsers against streams taken out of the user's own library. | ||
| 2 | +//! | ||
| 3 | +//! Hand-written cases live in the crates' unit tests; what cannot be written by | ||
| 4 | +//! hand is a disc's PGS display set or a fansub's thousand-line ASS script. | ||
| 5 | +//! `scripts/gen-subtitle-fixtures.sh` extracts them (fixtures are gitignored, | ||
| 6 | +//! the script is not), and every test here *skips* when its fixture is absent | ||
| 7 | +//! so a fresh clone still runs green. | ||
| 8 | + | ||
| 9 | +use std::path::PathBuf; | ||
| 10 | + | ||
| 11 | +use ec_subs::{SourceFormat, plain_text}; | ||
| 12 | + | ||
| 13 | +fn fixture(name: &str) -> Option<Vec<u8>> { | ||
| 14 | + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 15 | + .join("../../fixtures/subs") | ||
| 16 | + .join(name); | ||
| 17 | + match std::fs::read(&path) { | ||
| 18 | + Ok(bytes) => Some(bytes), | ||
| 19 | + Err(_) => { | ||
| 20 | + eprintln!("skipping: no {name} — run scripts/gen-subtitle-fixtures.sh"); | ||
| 21 | + None | ||
| 22 | + } | ||
| 23 | + } | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +#[test] | ||
| 27 | +fn a_real_subrip_track_parses_whole() { | ||
| 28 | + let Some(bytes) = fixture("real.srt") else { | ||
| 29 | + return; | ||
| 30 | + }; | ||
| 31 | + let track = ec_subs::srt::parse(&bytes).unwrap(); | ||
| 32 | + assert_eq!(track.source, Some(SourceFormat::Srt)); | ||
| 33 | + assert!(track.cues.len() > 100, "{} cues", track.cues.len()); | ||
| 34 | + assert_eq!(track.skipped, 0, "a whole file should have no torn blocks"); | ||
| 35 | + // Every cue is up for a positive time and says something. | ||
| 36 | + for cue in &track.cues { | ||
| 37 | + assert!(cue.end_us >= cue.start_us); | ||
| 38 | + assert!( | ||
| 39 | + !plain_text(&cue.segments).trim().is_empty(), | ||
| 40 | + "empty cue at {}us", | ||
| 41 | + cue.start_us | ||
| 42 | + ); | ||
| 43 | + } | ||
| 44 | + // A subtitle track runs forwards. | ||
| 45 | + assert!( | ||
| 46 | + track | ||
| 47 | + .cues | ||
| 48 | + .windows(2) | ||
| 49 | + .all(|w| w[1].start_us >= w[0].start_us) | ||
| 50 | + ); | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +#[test] | ||
| 54 | +fn a_real_ass_script_parses_whole() { | ||
| 55 | + let Some(bytes) = fixture("real.ass") else { | ||
| 56 | + return; | ||
| 57 | + }; | ||
| 58 | + let track = ec_ass::parse(&bytes).unwrap(); | ||
| 59 | + assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); | ||
| 60 | + assert!(!track.styles.is_empty(), "a script declares styles"); | ||
| 61 | + assert!(track.cues.len() > 100, "{} cues", track.cues.len()); | ||
| 62 | + assert_eq!(track.skipped, 0, "a whole script should have no torn rows"); | ||
| 63 | + // Every cue names a style the script declared, and most say words: a | ||
| 64 | + // signs-and-songs script has drawing-only lines, which are not words. | ||
| 65 | + let with_text = track | ||
| 66 | + .cues | ||
| 67 | + .iter() | ||
| 68 | + .filter(|c| !plain_text(&c.segments).trim().is_empty()) | ||
| 69 | + .count(); | ||
| 70 | + assert!( | ||
| 71 | + with_text * 10 > track.cues.len() * 9, | ||
| 72 | + "{with_text} of {}", | ||
| 73 | + track.cues.len() | ||
| 74 | + ); | ||
| 75 | + for cue in &track.cues { | ||
| 76 | + assert!(cue.end_us >= cue.start_us); | ||
| 77 | + if let Some(style) = &cue.style_ref { | ||
| 78 | + assert!( | ||
| 79 | + track.style(style).is_some(), | ||
| 80 | + "cue names undeclared style {style:?}" | ||
| 81 | + ); | ||
| 82 | + } | ||
| 83 | + // Override tags never leak into the words. | ||
| 84 | + let text = plain_text(&cue.segments); | ||
| 85 | + assert!(!text.contains("{\\"), "override tag in text: {text:?}"); | ||
| 86 | + } | ||
| 87 | + // The header is replayable as a Matroska `CodecPrivate`. | ||
| 88 | + assert!(track.extradata.windows(8).any(|w| w == b"[Events]")); | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +#[test] | ||
| 92 | +fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { | ||
| 93 | + let Some(bytes) = fixture("pgs-1080p.sup") else { | ||
| 94 | + return; | ||
| 95 | + }; | ||
| 96 | + let mut decoder = ec_pgs::PgsDecoder::new(); | ||
| 97 | + decoder.push(&bytes).unwrap(); | ||
| 98 | + let mut frames = 0; | ||
| 99 | + let mut painted = 0; | ||
| 100 | + let mut coverage_max = 0.0f64; | ||
| 101 | + while let Some(frame) = decoder.take_frame() { | ||
| 102 | + frames += 1; | ||
| 103 | + // A disc composes against its own video frame, and this one is HD. | ||
| 104 | + assert_eq!((frame.width, frame.height), (1920, 1080)); | ||
| 105 | + let stride = frame.planes[0].stride; | ||
| 106 | + assert_eq!(stride, 1920 * 4); | ||
| 107 | + let opaque = frame.planes[0] | ||
| 108 | + .data | ||
| 109 | + .chunks_exact(4) | ||
| 110 | + .filter(|p| p[3] > 0) | ||
| 111 | + .count(); | ||
| 112 | + if opaque == 0 { | ||
| 113 | + // An erase display set: a set that composes nothing at all. | ||
| 114 | + continue; | ||
| 115 | + } | ||
| 116 | + painted += 1; | ||
| 117 | + let coverage = opaque as f64 / (1920.0 * 1080.0); | ||
| 118 | + coverage_max = coverage_max.max(coverage); | ||
| 119 | + // Subtitles are lines of text over a film: ink, not a filled canvas. | ||
| 120 | + assert!( | ||
| 121 | + coverage > 0.000_1 && coverage < 0.25, | ||
| 122 | + "display set {frames} covers {:.3}% of the canvas", | ||
| 123 | + coverage * 100.0 | ||
| 124 | + ); | ||
| 125 | + // The ink sits in the lower or upper band, never as a single stray row. | ||
| 126 | + let rows = (0..1080) | ||
| 127 | + .filter(|y| { | ||
| 128 | + frame.planes[0].data[y * stride..(y + 1) * stride] | ||
| 129 | + .chunks_exact(4) | ||
| 130 | + .any(|p| p[3] > 0) | ||
| 131 | + }) | ||
| 132 | + .count(); | ||
| 133 | + assert!(rows > 4, "display set {frames} paints {rows} rows"); | ||
| 134 | + } | ||
| 135 | + assert!(frames > 100, "{frames} display sets"); | ||
| 136 | + assert!( | ||
| 137 | + painted * 3 > frames, | ||
| 138 | + "{painted} of {frames} display sets painted anything" | ||
| 139 | + ); | ||
| 140 | + assert!(coverage_max < 0.25, "widest cue covers {coverage_max}"); | ||
| 141 | + eprintln!("pgs: {frames} display sets, {painted} painted, widest {coverage_max:.4}"); | ||
| 142 | +} | ||
scripts/gen-subtitle-fixtures.shadded+65 -0
| @@ -0,0 +1,65 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# gen-subtitle-fixtures.sh — extract real subtitle streams out of the library. | ||
| 3 | +# | ||
| 4 | +# READ-ONLY on the library; writes only under fixtures/ (gitignored). Picks the | ||
| 5 | +# first manifest file carrying each subtitle codec and copies that stream out | ||
| 6 | +# without re-encoding, so what the tests parse is exactly the bytes a disc rip | ||
| 7 | +# holds. The synthetic .srt/.vtt/.ass cases live inside the crates' own unit | ||
| 8 | +# tests; what cannot be written by hand is a real PGS display set. | ||
| 9 | +# | ||
| 10 | +# Usage: scripts/gen-subtitle-fixtures.sh | ||
| 11 | +# Env: EC_FIXTURES=<dir> (default <repo>/fixtures) | ||
| 12 | +# EC_PGS_SECONDS=<n> (default 900 — a whole film's worth is 30 MB) | ||
| 13 | +# In: fixtures/real-library-manifest.tsv (scripts/scan-real-library.sh) | ||
| 14 | +# Out: fixtures/subs/{pgs-1080p.sup,real.ass,real.srt} | ||
| 15 | + | ||
| 16 | +set -uo pipefail | ||
| 17 | + | ||
| 18 | +ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd) | ||
| 19 | +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} | ||
| 20 | +MANIFEST=$FIXTURES/real-library-manifest.tsv | ||
| 21 | +OUT=$FIXTURES/subs | ||
| 22 | +SECONDS_LIMIT=${EC_PGS_SECONDS:-900} | ||
| 23 | + | ||
| 24 | +command -v ffmpeg >/dev/null || { echo "gen-subtitle-fixtures: ffmpeg not found" >&2; exit 2; } | ||
| 25 | +[ -r "$MANIFEST" ] || { echo "gen-subtitle-fixtures: run scripts/scan-real-library.sh first" >&2; exit 2; } | ||
| 26 | + | ||
| 27 | +mkdir -p -- "$OUT" | ||
| 28 | + | ||
| 29 | +# first_with <codec_name> — path of the first manifest file holding such a | ||
| 30 | +# subtitle stream, empty when the library has none. | ||
| 31 | +first_with() { | ||
| 32 | + local codec=$1 path | ||
| 33 | + while IFS=$'\t' read -r path _; do | ||
| 34 | + [ -r "$path" ] || continue | ||
| 35 | + if ffprobe -v error -select_streams s -show_entries stream=codec_name -of csv=p=0 -- "$path" 2>/dev/null | | ||
| 36 | + grep -qx "$codec"; then | ||
| 37 | + printf '%s\n' "$path" | ||
| 38 | + return 0 | ||
| 39 | + fi | ||
| 40 | + done < <(tail -n +2 -- "$MANIFEST") | ||
| 41 | + return 1 | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +# extract <codec_name> <output> [ffmpeg args...] | ||
| 45 | +extract() { | ||
| 46 | + local codec=$1 out=$2; shift 2 | ||
| 47 | + local src | ||
| 48 | + if ! src=$(first_with "$codec"); then | ||
| 49 | + echo "gen-subtitle-fixtures: no $codec stream in the library — skipping $(basename "$out")" >&2 | ||
| 50 | + return 0 | ||
| 51 | + fi | ||
| 52 | + # -map by codec so a dual-subtitle file gives the stream we asked for. | ||
| 53 | + local index | ||
| 54 | + index=$(ffprobe -v error -select_streams s -show_entries stream=index,codec_name -of csv=p=0 -- "$src" | | ||
| 55 | + awk -F, -v c="$codec" '$2 == c {print $1; exit}') | ||
| 56 | + if ffmpeg -v error -y "$@" -i "$src" -map "0:$index" -c copy -- "$out"; then | ||
| 57 | + printf '%s\t%s\n' "$(basename "$out")" "$src" | ||
| 58 | + else | ||
| 59 | + echo "gen-subtitle-fixtures: ffmpeg failed on $src" >&2 | ||
| 60 | + fi | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +extract hdmv_pgs_subtitle "$OUT/pgs-1080p.sup" -t "$SECONDS_LIMIT" | ||
| 64 | +extract ass "$OUT/real.ass" | ||
| 65 | +extract subrip "$OUT/real.srt" | ||
shims/oxideav-ass/Cargo.tomladded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "oxideav-ass" | ||
| 3 | +description = "Compatibility shim: the oxideav-ass surface edith consumes, over ec-ass." | ||
| 4 | +version = "0.0.9" | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | +publish = false | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +ec-ass = { path = "../../crates/ec-ass", version = "0.1.0" } | ||
| 12 | +ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" } | ||
| 13 | +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } | ||
shims/oxideav-ass/src/lib.rsadded+37 -0
| @@ -0,0 +1,37 @@ | |||
| 1 | +//! `oxideav-ass` as edith consumes it, over [`ec_ass`]. | ||
| 2 | +//! | ||
| 3 | +//! One item: `parse`, answering the same [`SubtitleTrack`] the SubRip and | ||
| 4 | +//! WebVTT parsers do — the replica hands all three around as one function | ||
| 5 | +//! pointer type and reads `cues`, `segments` and `plain_text` off the result. | ||
| 6 | + | ||
| 7 | +#![forbid(unsafe_code)] | ||
| 8 | + | ||
| 9 | +use oxideav_core::Result; | ||
| 10 | + | ||
| 11 | +pub use ec_subs::ir::{ | ||
| 12 | + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, | ||
| 13 | +}; | ||
| 14 | + | ||
| 15 | +/// Parse an ASS or SSA script. | ||
| 16 | +pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> { | ||
| 17 | + Ok(ec_ass::parse(bytes)?) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +#[cfg(test)] | ||
| 21 | +mod tests { | ||
| 22 | + use super::*; | ||
| 23 | + | ||
| 24 | + #[test] | ||
| 25 | + fn a_script_parses_through_the_shim() { | ||
| 26 | + type Parse = fn(&[u8]) -> Result<SubtitleTrack>; | ||
| 27 | + let parse: Parse = parse; | ||
| 28 | + let doc = "[Events]\n\ | ||
| 29 | + Format: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ | ||
| 30 | + Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi{\\i0}\\Nthere\n"; | ||
| 31 | + let track = parse(doc.as_bytes()).unwrap(); | ||
| 32 | + assert_eq!(track.cues.len(), 1); | ||
| 33 | + assert_eq!(track.cues[0].start_us, 1_000_000); | ||
| 34 | + assert_eq!(ec_subs::plain_text(&track.cues[0].segments), "hi\nthere"); | ||
| 35 | + assert!(!parse(b"not a script").unwrap_err().to_string().is_empty()); | ||
| 36 | + } | ||
| 37 | +} | ||
shims/oxideav-core/Cargo.tomladded+11 -0
| @@ -0,0 +1,11 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "oxideav-core" | ||
| 3 | +description = "Compatibility shim: the oxideav-core surface edith consumes, over ec-core." | ||
| 4 | +version = "0.1.34" | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | +publish = false | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +ec-core.workspace = true | ||
shims/oxideav-core/src/lib.rsadded+484 -0
| @@ -0,0 +1,484 @@ | |||
| 1 | +//! `oxideav-core` as edith consumes it, over [`ec_core`]. | ||
| 2 | +//! | ||
| 3 | +//! A shim, not a port: it carries the incumbent's package name and version so a | ||
| 4 | +//! swap is a `[patch.crates-io]` line and nothing else, and it exposes exactly | ||
| 5 | +//! the items the replica names — no more, because an item nobody calls is an | ||
| 6 | +//! item nobody can check. The list, and where each is called from, is in the | ||
| 7 | +//! subtitle and export paths of the engine: `Packet::new`, `TimeBase::new`, | ||
| 8 | +//! `Error::NeedMore`, `CodecId`, `CodecParameters::{audio,subtitle}`, | ||
| 9 | +//! `CodecRegistry`, `Decoder`, `Frame`, `Muxer`, `StreamInfo`, `Result`. | ||
| 10 | +//! | ||
| 11 | +//! Where the two IRs differ in *shape* the shim owns the difference: | ||
| 12 | +//! `oxideav`'s codec id is a string and `ec_core`'s is an enum, its frames own | ||
| 13 | +//! their bytes and `ec_core`'s share a refcounted buffer. Those are converted | ||
| 14 | +//! here, once, rather than at every call site of the replica. | ||
| 15 | +//! | ||
| 16 | +//! [`Packet`] and [`TimeBase`] are `ec_core`'s own: their signatures already | ||
| 17 | +//! match what the replica writes, so a re-export is the whole adapter. | ||
| 18 | + | ||
| 19 | +#![forbid(unsafe_code)] | ||
| 20 | + | ||
| 21 | +use std::collections::HashMap; | ||
| 22 | +use std::fmt; | ||
| 23 | + | ||
| 24 | +pub use ec_core::{Packet, TimeBase}; | ||
| 25 | + | ||
| 26 | +/// What a call into this family can go wrong with. | ||
| 27 | +/// | ||
| 28 | +/// `NeedMore` is load-bearing: the replica's AC-3 path treats it as "not an | ||
| 29 | +/// error, feed me another packet" and everything else as a failure. | ||
| 30 | +#[derive(Debug)] | ||
| 31 | +#[non_exhaustive] | ||
| 32 | +pub enum Error { | ||
| 33 | + /// The decoder wants another packet before it can hand back a frame. | ||
| 34 | + NeedMore, | ||
| 35 | + /// End of stream. | ||
| 36 | + Eof, | ||
| 37 | + /// Well-formed but not supported. | ||
| 38 | + Unsupported(String), | ||
| 39 | + /// Malformed input. | ||
| 40 | + InvalidData(String), | ||
| 41 | + /// No codec in the registry claims these parameters. | ||
| 42 | + CodecNotFound(String), | ||
| 43 | + /// Underlying I/O. | ||
| 44 | + Io(std::io::Error), | ||
| 45 | + /// Anything else. | ||
| 46 | + Other(String), | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +impl fmt::Display for Error { | ||
| 50 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 51 | + match self { | ||
| 52 | + Error::NeedMore => write!(f, "more input needed"), | ||
| 53 | + Error::Eof => write!(f, "end of stream"), | ||
| 54 | + Error::Unsupported(what) => write!(f, "unsupported: {what}"), | ||
| 55 | + Error::InvalidData(what) => write!(f, "invalid data: {what}"), | ||
| 56 | + Error::CodecNotFound(id) => write!(f, "no codec {id}"), | ||
| 57 | + Error::Io(e) => write!(f, "{e}"), | ||
| 58 | + Error::Other(what) => write!(f, "{what}"), | ||
| 59 | + } | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl std::error::Error for Error {} | ||
| 64 | + | ||
| 65 | +impl From<std::io::Error> for Error { | ||
| 66 | + fn from(e: std::io::Error) -> Error { | ||
| 67 | + Error::Io(e) | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl From<ec_core::Error> for Error { | ||
| 72 | + fn from(e: ec_core::Error) -> Error { | ||
| 73 | + match e { | ||
| 74 | + ec_core::Error::NeedMore => Error::NeedMore, | ||
| 75 | + ec_core::Error::Eof => Error::Eof, | ||
| 76 | + ec_core::Error::Unsupported { what, why } => { | ||
| 77 | + Error::Unsupported(format!("{what}: {why}")) | ||
| 78 | + } | ||
| 79 | + ec_core::Error::Corrupt { context } => Error::InvalidData(context), | ||
| 80 | + ec_core::Error::Io(e) => Error::Io(e), | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// This family's result. | ||
| 86 | +pub type Result<T> = std::result::Result<T, Error>; | ||
| 87 | + | ||
| 88 | +/// A codec's identifier, as a string: `"ac3"`, `"pgs"`, `"vorbis"`. | ||
| 89 | +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] | ||
| 90 | +pub struct CodecId(pub String); | ||
| 91 | + | ||
| 92 | +impl CodecId { | ||
| 93 | + /// The id named by `s`. | ||
| 94 | + pub fn new(s: impl Into<String>) -> CodecId { | ||
| 95 | + CodecId(s.into()) | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + /// The name itself. | ||
| 99 | + pub fn as_str(&self) -> &str { | ||
| 100 | + &self.0 | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + /// The `ec_core` codec this names, when the family carries it. | ||
| 104 | + pub fn to_ec(&self) -> Option<ec_core::CodecId> { | ||
| 105 | + use ec_core::CodecId::*; | ||
| 106 | + Some(match self.0.as_str() { | ||
| 107 | + "h264" | "avc1" => H264, | ||
| 108 | + "h265" | "hevc" => H265, | ||
| 109 | + "vp8" => Vp8, | ||
| 110 | + "vp9" => Vp9, | ||
| 111 | + "av1" => Av1, | ||
| 112 | + "aac" => Aac, | ||
| 113 | + "ac3" => Ac3, | ||
| 114 | + "eac3" => EAc3, | ||
| 115 | + "alac" => Alac, | ||
| 116 | + "flac" => Flac, | ||
| 117 | + "mp3" => Mp3, | ||
| 118 | + "opus" => Opus, | ||
| 119 | + "vorbis" => Vorbis, | ||
| 120 | + "srt" | "subrip" => Srt, | ||
| 121 | + "webvtt" | "vtt" => WebVtt, | ||
| 122 | + "ass" | "ssa" => Ass, | ||
| 123 | + "pgs" => Pgs, | ||
| 124 | + "tx3g" => Tx3g, | ||
| 125 | + _ => return None, | ||
| 126 | + }) | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +impl fmt::Display for CodecId { | ||
| 131 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 132 | + f.write_str(&self.0) | ||
| 133 | + } | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// What kind of stream a set of parameters describes. | ||
| 137 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | ||
| 138 | +pub enum MediaType { | ||
| 139 | + /// Audio samples. | ||
| 140 | + Audio, | ||
| 141 | + /// Video pictures. | ||
| 142 | + Video, | ||
| 143 | + /// Timed text or subtitle bitmaps. | ||
| 144 | + Subtitle, | ||
| 145 | + /// Opaque payload. | ||
| 146 | + Data, | ||
| 147 | + /// Not yet determined. | ||
| 148 | + #[default] | ||
| 149 | + Unknown, | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// Everything a decoder is told before its first packet. | ||
| 153 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| 154 | +pub struct CodecParameters { | ||
| 155 | + /// Which codec. | ||
| 156 | + pub codec_id: CodecId, | ||
| 157 | + /// Which kind of stream. | ||
| 158 | + pub media_type: MediaType, | ||
| 159 | + /// Audio sample rate. | ||
| 160 | + pub sample_rate: Option<u32>, | ||
| 161 | + /// Audio channel count — the replica asks for `Some(2)` to get a downmix. | ||
| 162 | + pub channels: Option<u16>, | ||
| 163 | + /// Coded width. | ||
| 164 | + pub width: Option<u32>, | ||
| 165 | + /// Coded height. | ||
| 166 | + pub height: Option<u32>, | ||
| 167 | + /// Codec setup bytes. | ||
| 168 | + pub extradata: Vec<u8>, | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +impl CodecParameters { | ||
| 172 | + /// Audio parameters for `codec_id`. | ||
| 173 | + pub fn audio(codec_id: CodecId) -> CodecParameters { | ||
| 174 | + CodecParameters { | ||
| 175 | + codec_id, | ||
| 176 | + media_type: MediaType::Audio, | ||
| 177 | + ..CodecParameters::default() | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | + | ||
| 181 | + /// Video parameters for `codec_id`. | ||
| 182 | + pub fn video(codec_id: CodecId) -> CodecParameters { | ||
| 183 | + CodecParameters { | ||
| 184 | + codec_id, | ||
| 185 | + media_type: MediaType::Video, | ||
| 186 | + ..CodecParameters::default() | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + | ||
| 190 | + /// Subtitle parameters for `codec_id`. | ||
| 191 | + pub fn subtitle(codec_id: CodecId) -> CodecParameters { | ||
| 192 | + CodecParameters { | ||
| 193 | + codec_id, | ||
| 194 | + media_type: MediaType::Subtitle, | ||
| 195 | + ..CodecParameters::default() | ||
| 196 | + } | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + /// Data-stream parameters for `codec_id`. | ||
| 200 | + pub fn data(codec_id: CodecId) -> CodecParameters { | ||
| 201 | + CodecParameters { | ||
| 202 | + codec_id, | ||
| 203 | + media_type: MediaType::Data, | ||
| 204 | + ..CodecParameters::default() | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/// One stream of a container, as a muxer is told about it. | ||
| 210 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 211 | +pub struct StreamInfo { | ||
| 212 | + /// Index the stream's packets carry. | ||
| 213 | + pub index: u32, | ||
| 214 | + /// The unit its timestamps are in. | ||
| 215 | + pub time_base: TimeBase, | ||
| 216 | + /// Duration in `time_base` ticks. | ||
| 217 | + pub duration: Option<i64>, | ||
| 218 | + /// First timestamp in `time_base` ticks. | ||
| 219 | + pub start_time: Option<i64>, | ||
| 220 | + /// What is in it. | ||
| 221 | + pub params: CodecParameters, | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// One decoded picture. | ||
| 225 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| 226 | +pub struct VideoFrame { | ||
| 227 | + /// Width in pixels. | ||
| 228 | + pub width: u32, | ||
| 229 | + /// Height in pixels. | ||
| 230 | + pub height: u32, | ||
| 231 | + /// Presentation time in the stream's time base. | ||
| 232 | + pub pts: Option<i64>, | ||
| 233 | + /// One plane per component group; packed formats have exactly one. | ||
| 234 | + pub planes: Vec<VideoPlane>, | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +/// One plane of a [`VideoFrame`]. | ||
| 238 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| 239 | +pub struct VideoPlane { | ||
| 240 | + /// Bytes between the starts of two rows. | ||
| 241 | + pub stride: usize, | ||
| 242 | + /// The plane's bytes. | ||
| 243 | + pub data: Vec<u8>, | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +/// One decoded block of audio. | ||
| 247 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| 248 | +pub struct AudioFrame { | ||
| 249 | + /// Frames per channel in this block. | ||
| 250 | + pub samples: u32, | ||
| 251 | + /// Presentation time in the stream's time base. | ||
| 252 | + pub pts: Option<i64>, | ||
| 253 | + /// Interleaved (one entry) or planar (one entry per channel) bytes. | ||
| 254 | + pub data: Vec<Vec<u8>>, | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// What a decoder hands back. | ||
| 258 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 259 | +pub enum Frame { | ||
| 260 | + /// A picture. | ||
| 261 | + Video(VideoFrame), | ||
| 262 | + /// An audio block. | ||
| 263 | + Audio(AudioFrame), | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +impl From<ec_core::Frame> for Frame { | ||
| 267 | + fn from(frame: ec_core::Frame) -> Frame { | ||
| 268 | + match frame { | ||
| 269 | + ec_core::Frame::Video(video) => Frame::Video(VideoFrame { | ||
| 270 | + width: video.width, | ||
| 271 | + height: video.height, | ||
| 272 | + pts: video.pts.map(|t| t.ticks), | ||
| 273 | + planes: video | ||
| 274 | + .planes | ||
| 275 | + .into_iter() | ||
| 276 | + .map(|plane| VideoPlane { | ||
| 277 | + stride: plane.stride, | ||
| 278 | + data: plane.data.to_vec(), | ||
| 279 | + }) | ||
| 280 | + .collect(), | ||
| 281 | + }), | ||
| 282 | + ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame { | ||
| 283 | + samples: audio.samples as u32, | ||
| 284 | + pts: audio.pts.map(|t| t.ticks), | ||
| 285 | + data: audio.data.iter().map(|buf| buf.to_vec()).collect(), | ||
| 286 | + }), | ||
| 287 | + } | ||
| 288 | + } | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +/// A decoder: packets in, frames out. | ||
| 292 | +pub trait Decoder: Send { | ||
| 293 | + /// The codec this decodes. | ||
| 294 | + fn codec_id(&self) -> &CodecId; | ||
| 295 | + | ||
| 296 | + /// Feed one packet. | ||
| 297 | + fn send_packet(&mut self, packet: &Packet) -> Result<()>; | ||
| 298 | + | ||
| 299 | + /// Take one frame, or [`Error::NeedMore`] when the decoder wants another | ||
| 300 | + /// packet first. | ||
| 301 | + fn receive_frame(&mut self) -> Result<Frame>; | ||
| 302 | +} | ||
| 303 | + | ||
| 304 | +/// A container writer. | ||
| 305 | +pub trait Muxer: Send { | ||
| 306 | + /// The format's short name. | ||
| 307 | + fn format_name(&self) -> &str; | ||
| 308 | + | ||
| 309 | + /// Write whatever precedes the first packet. | ||
| 310 | + fn write_header(&mut self) -> Result<()>; | ||
| 311 | + | ||
| 312 | + /// Write one packet. | ||
| 313 | + fn write_packet(&mut self, packet: &Packet) -> Result<()>; | ||
| 314 | + | ||
| 315 | + /// Write whatever follows the last one. | ||
| 316 | + fn write_trailer(&mut self) -> Result<()>; | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +/// How a codec crate hands out decoders. | ||
| 320 | +pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>; | ||
| 321 | + | ||
| 322 | +/// One codec's registration. | ||
| 323 | +#[derive(Clone)] | ||
| 324 | +pub struct CodecInfo { | ||
| 325 | + /// The id this claims. | ||
| 326 | + pub id: CodecId, | ||
| 327 | + /// How to build a decoder for it. | ||
| 328 | + pub decoder_factory: Option<DecoderFactory>, | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +impl CodecInfo { | ||
| 332 | + /// An empty registration for `id`. | ||
| 333 | + pub fn new(id: CodecId) -> CodecInfo { | ||
| 334 | + CodecInfo { | ||
| 335 | + id, | ||
| 336 | + decoder_factory: None, | ||
| 337 | + } | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + /// The same registration, with a decoder. | ||
| 341 | + pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo { | ||
| 342 | + self.decoder_factory = Some(factory); | ||
| 343 | + self | ||
| 344 | + } | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +/// The codecs a caller has registered, in registration order per id. | ||
| 348 | +/// | ||
| 349 | +/// The replica builds one of these per AC-3 segment, registers that crate's | ||
| 350 | +/// codecs into it and asks for the first decoder that claims the parameters. | ||
| 351 | +#[derive(Clone, Default)] | ||
| 352 | +pub struct CodecRegistry { | ||
| 353 | + by_id: HashMap<CodecId, Vec<CodecInfo>>, | ||
| 354 | +} | ||
| 355 | + | ||
| 356 | +impl CodecRegistry { | ||
| 357 | + /// An empty registry. | ||
| 358 | + pub fn new() -> CodecRegistry { | ||
| 359 | + CodecRegistry::default() | ||
| 360 | + } | ||
| 361 | + | ||
| 362 | + /// Add one codec. | ||
| 363 | + pub fn register(&mut self, info: CodecInfo) { | ||
| 364 | + self.by_id.entry(info.id.clone()).or_default().push(info); | ||
| 365 | + } | ||
| 366 | + | ||
| 367 | + /// True when something registered can decode `id`. | ||
| 368 | + pub fn has_decoder(&self, id: &CodecId) -> bool { | ||
| 369 | + self.by_id | ||
| 370 | + .get(id) | ||
| 371 | + .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some())) | ||
| 372 | + } | ||
| 373 | + | ||
| 374 | + /// A decoder from the first registration that offers one. | ||
| 375 | + pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> { | ||
| 376 | + let factory = self | ||
| 377 | + .by_id | ||
| 378 | + .get(¶ms.codec_id) | ||
| 379 | + .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory)) | ||
| 380 | + .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?; | ||
| 381 | + factory(params) | ||
| 382 | + } | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +/// A [`Decoder`] over one of the family's own, converting the frames on the way | ||
| 386 | +/// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap. | ||
| 387 | +pub struct EcDecoder { | ||
| 388 | + id: CodecId, | ||
| 389 | + inner: Box<dyn ec_core::Decoder>, | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +impl EcDecoder { | ||
| 393 | + /// Wrap `inner`, which decodes the codec named `id`. | ||
| 394 | + pub fn new(id: CodecId, inner: Box<dyn ec_core::Decoder>) -> EcDecoder { | ||
| 395 | + EcDecoder { id, inner } | ||
| 396 | + } | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +impl Decoder for EcDecoder { | ||
| 400 | + fn codec_id(&self) -> &CodecId { | ||
| 401 | + &self.id | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + fn send_packet(&mut self, packet: &Packet) -> Result<()> { | ||
| 405 | + Ok(self.inner.send_packet(packet)?) | ||
| 406 | + } | ||
| 407 | + | ||
| 408 | + fn receive_frame(&mut self) -> Result<Frame> { | ||
| 409 | + Ok(self.inner.receive_frame()?.into()) | ||
| 410 | + } | ||
| 411 | +} | ||
| 412 | + | ||
| 413 | +#[cfg(test)] | ||
| 414 | +mod tests { | ||
| 415 | + use super::*; | ||
| 416 | + | ||
| 417 | + /// A decoder that answers one frame per packet, for the registry test. | ||
| 418 | + struct Stub(CodecId); | ||
| 419 | + | ||
| 420 | + impl Decoder for Stub { | ||
| 421 | + fn codec_id(&self) -> &CodecId { | ||
| 422 | + &self.0 | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + fn send_packet(&mut self, _packet: &Packet) -> Result<()> { | ||
| 426 | + Ok(()) | ||
| 427 | + } | ||
| 428 | + | ||
| 429 | + fn receive_frame(&mut self) -> Result<Frame> { | ||
| 430 | + Err(Error::NeedMore) | ||
| 431 | + } | ||
| 432 | + } | ||
| 433 | + | ||
| 434 | + fn stub(params: &CodecParameters) -> Result<Box<dyn Decoder>> { | ||
| 435 | + Ok(Box::new(Stub(params.codec_id.clone()))) | ||
| 436 | + } | ||
| 437 | + | ||
| 438 | + #[test] | ||
| 439 | + fn the_registry_hands_back_what_was_registered_and_names_what_was_not() { | ||
| 440 | + let mut registry = CodecRegistry::new(); | ||
| 441 | + registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub)); | ||
| 442 | + let params = CodecParameters::audio(CodecId::new("ac3")); | ||
| 443 | + let mut decoder = registry.first_decoder(¶ms).unwrap(); | ||
| 444 | + assert_eq!(decoder.codec_id().as_str(), "ac3"); | ||
| 445 | + assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore))); | ||
| 446 | + assert!(registry.has_decoder(&CodecId::new("ac3"))); | ||
| 447 | + | ||
| 448 | + let missing = CodecParameters::audio(CodecId::new("truehd")); | ||
| 449 | + assert!(matches!( | ||
| 450 | + registry.first_decoder(&missing), | ||
| 451 | + Err(Error::CodecNotFound(id)) if id == "truehd" | ||
| 452 | + )); | ||
| 453 | + } | ||
| 454 | + | ||
| 455 | + #[test] | ||
| 456 | + fn frames_and_errors_cross_the_boundary_intact() { | ||
| 457 | + let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4); | ||
| 458 | + let video = | ||
| 459 | + ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap(); | ||
| 460 | + let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else { | ||
| 461 | + panic!("a video frame stays a video frame"); | ||
| 462 | + }; | ||
| 463 | + assert_eq!((frame.width, frame.height), (1, 1)); | ||
| 464 | + assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]); | ||
| 465 | + assert_eq!(frame.planes[0].stride, 4); | ||
| 466 | + | ||
| 467 | + // The one error the replica matches on by name. | ||
| 468 | + assert!(matches!( | ||
| 469 | + Error::from(ec_core::Error::NeedMore), | ||
| 470 | + Error::NeedMore | ||
| 471 | + )); | ||
| 472 | + assert_eq!( | ||
| 473 | + Error::from(ec_core::Error::corrupt("torn")).to_string(), | ||
| 474 | + "invalid data: torn" | ||
| 475 | + ); | ||
| 476 | + } | ||
| 477 | + | ||
| 478 | + #[test] | ||
| 479 | + fn a_packet_is_written_the_way_the_replica_writes_one() { | ||
| 480 | + let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]); | ||
| 481 | + assert_eq!(packet.data.len(), 8); | ||
| 482 | + assert_eq!(packet.time_base, TimeBase::new(1, 90_000)); | ||
| 483 | + } | ||
| 484 | +} | ||
shims/oxideav-sub-image/Cargo.tomladded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "oxideav-sub-image" | ||
| 3 | +description = "Compatibility shim: the oxideav-sub-image PGS surface edith consumes, over ec-pgs." | ||
| 4 | +version = "0.0.7" | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | +publish = false | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +ec-pgs = { path = "../../crates/ec-pgs", version = "0.1.0" } | ||
| 12 | +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } | ||
| 13 | + | ||
| 14 | +[dev-dependencies] | ||
| 15 | +oxideav-subtitle = { path = "../oxideav-subtitle", version = "0.1.2" } | ||
| 16 | +oxideav-ass = { path = "../oxideav-ass", version = "0.0.9" } | ||
shims/oxideav-sub-image/src/lib.rsadded+80 -0
| @@ -0,0 +1,80 @@ | |||
| 1 | +//! `oxideav-sub-image` as edith consumes it, over [`ec_pgs`]. | ||
| 2 | +//! | ||
| 3 | +//! Four items: [`PGS_CODEC_ID`], [`pgs::make_decoder`], [`pgs::SEG_PCS`] and | ||
| 4 | +//! [`pgs::SEG_END`] — the replica reads a Matroska block's segments, puts the | ||
| 5 | +//! `.sup` framing back on and stops at the `END` that closes the first set | ||
| 6 | +//! which composes something, then decodes that through the trait. | ||
| 7 | + | ||
| 8 | +#![forbid(unsafe_code)] | ||
| 9 | + | ||
| 10 | +/// The codec id a PGS track is named by. | ||
| 11 | +pub const PGS_CODEC_ID: &str = "pgs"; | ||
| 12 | + | ||
| 13 | +/// Presentation Graphic Stream. | ||
| 14 | +pub mod pgs { | ||
| 15 | + use oxideav_core::{CodecId, CodecParameters, Decoder, EcDecoder, Result}; | ||
| 16 | + | ||
| 17 | + pub use ec_pgs::{SEG_END, SEG_ODS, SEG_PCS, SEG_PDS, SEG_WDS}; | ||
| 18 | + | ||
| 19 | + /// A PGS decoder: `.sup`-framed segments in, one RGBA canvas per display | ||
| 20 | + /// set out. The parameters say nothing a PGS stream does not state itself. | ||
| 21 | + pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> { | ||
| 22 | + Ok(Box::new(EcDecoder::new( | ||
| 23 | + CodecId::new(crate::PGS_CODEC_ID), | ||
| 24 | + Box::new(ec_pgs::PgsDecoder::new()), | ||
| 25 | + ))) | ||
| 26 | + } | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +#[cfg(test)] | ||
| 30 | +mod tests { | ||
| 31 | + use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase}; | ||
| 32 | + | ||
| 33 | + use super::*; | ||
| 34 | + | ||
| 35 | + /// The `.sup` framing the replica rebuilds around a Matroska block. | ||
| 36 | + fn segment(kind: u8, body: &[u8]) -> Vec<u8> { | ||
| 37 | + let mut out = Vec::new(); | ||
| 38 | + out.extend_from_slice(b"PG"); | ||
| 39 | + out.extend_from_slice(&[0; 8]); | ||
| 40 | + out.push(kind); | ||
| 41 | + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); | ||
| 42 | + out.extend_from_slice(body); | ||
| 43 | + out | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + #[test] | ||
| 47 | + fn a_display_set_decodes_through_the_replica_s_own_call_shape() { | ||
| 48 | + let params = CodecParameters::subtitle(CodecId::new(PGS_CODEC_ID)); | ||
| 49 | + let mut decoder = pgs::make_decoder(¶ms).unwrap(); | ||
| 50 | + | ||
| 51 | + // A 4x2 canvas with one 2x1 opaque-white object at (1, 0). | ||
| 52 | + let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1]; | ||
| 53 | + pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]); | ||
| 54 | + let pds = vec![0, 0, 1, 235, 128, 128, 255]; | ||
| 55 | + let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00]; | ||
| 56 | + let mut ods = vec![0, 0, 0, 0xC0]; | ||
| 57 | + ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); | ||
| 58 | + ods.extend_from_slice(&[0, 2, 0, 1]); | ||
| 59 | + ods.extend_from_slice(&rle); | ||
| 60 | + let mut sup = segment(pgs::SEG_PCS, &pcs); | ||
| 61 | + // The composition object count is where the replica reads whether the | ||
| 62 | + // set shows anything. | ||
| 63 | + assert_eq!(pcs[10], 1); | ||
| 64 | + sup.extend(segment(pgs::SEG_PDS, &pds)); | ||
| 65 | + sup.extend(segment(pgs::SEG_ODS, &ods)); | ||
| 66 | + sup.extend(segment(pgs::SEG_END, &[])); | ||
| 67 | + | ||
| 68 | + decoder | ||
| 69 | + .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) | ||
| 70 | + .unwrap(); | ||
| 71 | + let Ok(Frame::Video(frame)) = decoder.receive_frame() else { | ||
| 72 | + panic!("a display set is a picture"); | ||
| 73 | + }; | ||
| 74 | + assert_eq!((frame.width, frame.height), (4, 2)); | ||
| 75 | + let data = frame.planes.into_iter().next().unwrap().data; | ||
| 76 | + assert_eq!(data.len(), 4 * 2 * 4); | ||
| 77 | + assert_eq!(&data[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); | ||
| 78 | + assert_eq!(&data[0..4], &[0, 0, 0, 0]); | ||
| 79 | + } | ||
| 80 | +} | ||
shims/oxideav-sub-image/tests/replica_call_shapes.rsadded+157 -0
| @@ -0,0 +1,157 @@ | |||
| 1 | +//! The replica's own call shapes, transcribed, so a swap is proven at compile | ||
| 2 | +//! time and not at the first PGS track a user opens. | ||
| 3 | +//! | ||
| 4 | +//! Every block below is the engine's code with its surroundings removed: | ||
| 5 | +//! `subtitle.rs:33` (`plain_text`), `:90-125` (`CueImage::rgba` — the `.sup` | ||
| 6 | +//! framing rebuilt around a Matroska block and decoded), `:518` (`srt::parse` | ||
| 7 | +//! around a synthetic timing line), `:555` (`oxideav_ass::parse`) and | ||
| 8 | +//! `:603-607` (the four parsers as one function-pointer type). If any of them | ||
| 9 | +//! stops compiling against these shims, the swap has broken, whatever the | ||
| 10 | +//! crates' own tests say. | ||
| 11 | + | ||
| 12 | +use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase}; | ||
| 13 | +use oxideav_subtitle::ir::plain_text; | ||
| 14 | + | ||
| 15 | +/// `subtitle.rs:604-607` — the extension-to-parser table, as one `fn` type. | ||
| 16 | +type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>; | ||
| 17 | + | ||
| 18 | +fn parser_for(ext: &str) -> Option<Parse> { | ||
| 19 | + match ext { | ||
| 20 | + "srt" => Some(oxideav_subtitle::srt::parse), | ||
| 21 | + "vtt" | "webvtt" => Some(oxideav_subtitle::webvtt::parse), | ||
| 22 | + "ass" | "ssa" => Some(oxideav_ass::parse), | ||
| 23 | + _ => None, | ||
| 24 | + } | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +#[test] | ||
| 28 | +fn the_parser_table_and_the_cue_fields_the_replica_reads() { | ||
| 29 | + for (ext, doc) in [ | ||
| 30 | + ("srt", "1\n00:00:01,000 --> 00:00:02,000\n<i>hi</i>\n"), | ||
| 31 | + ( | ||
| 32 | + "vtt", | ||
| 33 | + "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n<i>hi</i>\n", | ||
| 34 | + ), | ||
| 35 | + ( | ||
| 36 | + "ass", | ||
| 37 | + "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ | ||
| 38 | + Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi\n", | ||
| 39 | + ), | ||
| 40 | + ] { | ||
| 41 | + let parse = parser_for(ext).expect("the replica routes these four extensions"); | ||
| 42 | + let track = parse(doc.as_bytes()).unwrap(); | ||
| 43 | + // `subtitle.rs:623-632`: cues mapped onto the engine's own `Cue`. | ||
| 44 | + let cues: Vec<(i64, i64, String)> = track | ||
| 45 | + .cues | ||
| 46 | + .iter() | ||
| 47 | + .map(|c| (c.start_us, c.end_us, plain_text(&c.segments))) | ||
| 48 | + .collect(); | ||
| 49 | + assert_eq!(cues, vec![(1_000_000, 2_000_000, "hi".to_owned())], "{ext}"); | ||
| 50 | + } | ||
| 51 | + assert!(parser_for("txt").is_none()); | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// `subtitle.rs:516-527` — an `S_TEXT/UTF8` block's markup resolved by wrapping | ||
| 55 | +/// it in a synthetic SRT. | ||
| 56 | +#[test] | ||
| 57 | +fn a_matroska_text_block_is_resolved_through_the_srt_parser() { | ||
| 58 | + let text = "<i>tilted</i> and plain"; | ||
| 59 | + let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); | ||
| 60 | + let resolved = match oxideav_subtitle::srt::parse(doc.as_bytes()) { | ||
| 61 | + Ok(track) => track | ||
| 62 | + .cues | ||
| 63 | + .first() | ||
| 64 | + .map(|c| plain_text(&c.segments)) | ||
| 65 | + .unwrap_or_default(), | ||
| 66 | + Err(_) => text.trim_end().to_owned(), | ||
| 67 | + }; | ||
| 68 | + assert_eq!(resolved, "tilted and plain"); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// `subtitle.rs:89-125` — a Matroska PGS block, framed back into a `.sup` and | ||
| 72 | +/// decoded to straight RGBA the size of the disc's own canvas. | ||
| 73 | +#[test] | ||
| 74 | +fn a_matroska_pgs_block_decodes_the_way_the_replica_decodes_one() { | ||
| 75 | + let set = matroska_block(); | ||
| 76 | + let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID)); | ||
| 77 | + let mut decoder = oxideav_sub_image::pgs::make_decoder(¶ms).unwrap(); | ||
| 78 | + let mut sup = Vec::with_capacity(set.len() + 64); | ||
| 79 | + let mut shows = false; | ||
| 80 | + for (kind, body) in segments(&set).unwrap() { | ||
| 81 | + sup.extend_from_slice(b"PG"); | ||
| 82 | + sup.extend_from_slice(&[0; 8]); | ||
| 83 | + sup.push(kind); | ||
| 84 | + sup.extend_from_slice(&(body.len() as u16).to_be_bytes()); | ||
| 85 | + sup.extend_from_slice(body); | ||
| 86 | + match kind { | ||
| 87 | + oxideav_sub_image::pgs::SEG_PCS => { | ||
| 88 | + shows = body.get(10).is_some_and(|&n| n > 0); | ||
| 89 | + } | ||
| 90 | + oxideav_sub_image::pgs::SEG_END if shows => break, | ||
| 91 | + _ => {} | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + decoder | ||
| 95 | + .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) | ||
| 96 | + .unwrap(); | ||
| 97 | + let rgba = match decoder.receive_frame().unwrap() { | ||
| 98 | + Frame::Video(frame) => frame.planes.into_iter().next().map(|p| p.data), | ||
| 99 | + _ => None, | ||
| 100 | + } | ||
| 101 | + .expect("a display set is a picture"); | ||
| 102 | + // The whole canvas, transparent where the cue paints nothing. | ||
| 103 | + assert_eq!(rgba.len(), 4 * 2 * 4); | ||
| 104 | + assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); | ||
| 105 | + assert_eq!(&rgba[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); | ||
| 106 | + | ||
| 107 | + // The erase set after the composition must not be what gets decoded: the | ||
| 108 | + // loop above stops at the `END` that closes the showing set. | ||
| 109 | + let all: Vec<u8> = set.clone(); | ||
| 110 | + assert!( | ||
| 111 | + segments(&all).unwrap().len() > 5, | ||
| 112 | + "the block holds both sets" | ||
| 113 | + ); | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// `subtitle.rs:131-140` — the segments of a display set as a Matroska block | ||
| 117 | +/// holds them: type, big-endian size, body. | ||
| 118 | +fn segments(set: &[u8]) -> Option<Vec<(u8, &[u8])>> { | ||
| 119 | + let mut out = Vec::new(); | ||
| 120 | + let mut at = 0; | ||
| 121 | + while at < set.len() { | ||
| 122 | + let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize; | ||
| 123 | + out.push((set[at], set.get(at + 3..at + 3 + size)?)); | ||
| 124 | + at += 3 + size; | ||
| 125 | + } | ||
| 126 | + Some(out) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// A block holding a composition *and* the erase that follows it — the packing | ||
| 130 | +/// the replica's comment warns about. | ||
| 131 | +fn matroska_block() -> Vec<u8> { | ||
| 132 | + let block = |kind: u8, body: &[u8]| { | ||
| 133 | + let mut out = vec![kind]; | ||
| 134 | + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); | ||
| 135 | + out.extend_from_slice(body); | ||
| 136 | + out | ||
| 137 | + }; | ||
| 138 | + let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1]; | ||
| 139 | + pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]); | ||
| 140 | + let pds = vec![0, 0, 1, 235, 128, 128, 255]; | ||
| 141 | + let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00]; | ||
| 142 | + let mut ods = vec![0, 0, 0, 0xC0]; | ||
| 143 | + ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); | ||
| 144 | + ods.extend_from_slice(&[0, 2, 0, 1]); | ||
| 145 | + ods.extend_from_slice(&rle); | ||
| 146 | + // The erase: a composition with no objects at all. | ||
| 147 | + let erase = vec![0, 4, 0, 2, 0x10, 0, 1, 0, 0, 0, 0]; | ||
| 148 | + [ | ||
| 149 | + block(oxideav_sub_image::pgs::SEG_PCS, &pcs), | ||
| 150 | + block(oxideav_sub_image::pgs::SEG_PDS, &pds), | ||
| 151 | + block(oxideav_sub_image::pgs::SEG_ODS, &ods), | ||
| 152 | + block(oxideav_sub_image::pgs::SEG_END, &[]), | ||
| 153 | + block(oxideav_sub_image::pgs::SEG_PCS, &erase), | ||
| 154 | + block(oxideav_sub_image::pgs::SEG_END, &[]), | ||
| 155 | + ] | ||
| 156 | + .concat() | ||
| 157 | +} | ||
shims/oxideav-subtitle/Cargo.tomladded+12 -0
| @@ -0,0 +1,12 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "oxideav-subtitle" | ||
| 3 | +description = "Compatibility shim: the oxideav-subtitle surface edith consumes, over ec-subs." | ||
| 4 | +version = "0.1.2" | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | +publish = false | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" } | ||
| 12 | +oxideav-core = { path = "../oxideav-core", version = "0.1.34" } | ||
shims/oxideav-subtitle/src/lib.rsadded+64 -0
| @@ -0,0 +1,64 @@ | |||
| 1 | +//! `oxideav-subtitle` as edith consumes it, over [`ec_subs`]. | ||
| 2 | +//! | ||
| 3 | +//! Three items and their types: `ir::plain_text`, `ir::SubtitleTrack`, | ||
| 4 | +//! `srt::parse` and `webvtt::parse`. The IR is `ec_subs`'s own — the field | ||
| 5 | +//! names were chosen to match, so this is a re-export and not a conversion — | ||
| 6 | +//! and the only adapter is the error type, because the replica writes the parse | ||
| 7 | +//! functions as `fn(&[u8]) -> oxideav_core::Result<SubtitleTrack>` and takes | ||
| 8 | +//! their address. | ||
| 9 | + | ||
| 10 | +#![forbid(unsafe_code)] | ||
| 11 | + | ||
| 12 | +/// The cue IR, which is [`ec_subs::ir`] under its incumbent name. | ||
| 13 | +pub mod ir { | ||
| 14 | + pub use ec_subs::ir::{ | ||
| 15 | + CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, | ||
| 16 | + plain_text, | ||
| 17 | + }; | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +pub use ir::{SourceFormat, SubtitleTrack}; | ||
| 21 | + | ||
| 22 | +/// SubRip. | ||
| 23 | +pub mod srt { | ||
| 24 | + use oxideav_core::Result; | ||
| 25 | + | ||
| 26 | + use crate::ir::SubtitleTrack; | ||
| 27 | + | ||
| 28 | + /// Parse a SubRip document. | ||
| 29 | + pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> { | ||
| 30 | + Ok(ec_subs::srt::parse(bytes)?) | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/// WebVTT. | ||
| 35 | +pub mod webvtt { | ||
| 36 | + use oxideav_core::Result; | ||
| 37 | + | ||
| 38 | + use crate::ir::SubtitleTrack; | ||
| 39 | + | ||
| 40 | + /// Parse a WebVTT document. | ||
| 41 | + pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> { | ||
| 42 | + Ok(ec_subs::webvtt::parse(bytes)?) | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +#[cfg(test)] | ||
| 47 | +mod tests { | ||
| 48 | + use super::*; | ||
| 49 | + | ||
| 50 | + /// The replica takes these as function pointers of one type and calls | ||
| 51 | + /// `plain_text` on whatever comes back; that is the whole contract. | ||
| 52 | + #[test] | ||
| 53 | + fn the_parsers_are_interchangeable_function_pointers() { | ||
| 54 | + type Parse = fn(&[u8]) -> oxideav_core::Result<ir::SubtitleTrack>; | ||
| 55 | + for parse in [srt::parse as Parse, webvtt::parse as Parse] { | ||
| 56 | + let track = parse(b"1\n00:00:01,000 --> 00:00:02,000\n<i>hi</i>\n").unwrap(); | ||
| 57 | + assert_eq!(ir::plain_text(&track.cues[0].segments), "hi"); | ||
| 58 | + assert_eq!(track.cues[0].start_us, 1_000_000); | ||
| 59 | + } | ||
| 60 | + // A file of the wrong kind is an error the replica can print. | ||
| 61 | + let error = srt::parse(b"prose, not subtitles").unwrap_err(); | ||
| 62 | + assert!(!error.to_string().is_empty()); | ||
| 63 | + } | ||
| 64 | +} | ||