forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4c07cbcTahinli2 months ago3583 commits

lib.rs562 lines, 21.4 KiBHistoryRawDownload
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
21use ec_core::{Error, Result};
22use ec_subs::ir::{
23 CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign,
24};
25use 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.
33pub 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)]
100enum 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
110impl 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.
125fn 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
145fn 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.
150fn 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
155fn 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.
195fn 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.
209fn 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
226fn 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)]
250struct 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.
264fn 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`].
294fn 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.
358fn 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.
373fn 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.
410fn 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)]
455mod 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}