forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

lib.rs757 lines, 28.8 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, KaraokeMode, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack,
24 TextAlign,
25};
26use ec_subs::{decode, parse_clock};
27
28/// Parse an ASS or SSA document.
29///
30/// `Err` only when there is no `Dialogue:` line and no `[Events]` section in
31/// the whole document — that is not this format. Torn rows are skipped and
32/// counted in [`SubtitleTrack::skipped`], because one bad line in a
33/// twelve-hundred-line script is not a reason to lose the other eleven hundred.
34pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
35 let text = decode(bytes);
36 let mut track = SubtitleTrack::new().with_source(SourceFormat::AssOrSsa);
37 let mut section = Section::None;
38 let mut style_format: Vec<String> = Vec::new();
39 let mut event_format: Vec<String> = Vec::new();
40 let mut header_end = 0;
41 let mut in_events = false;
42 let mut saw_events = false;
43 // `WrapStyle` is read once, when its line is seen; scanning the metadata for
44 // every Dialogue line instead made a long script quadratic.
45 let mut wrap_style = 0u8;
46 let mut wrap_seen = false;
47 for line in text.split_inclusive('\n') {
48 let trimmed = line.trim();
49 // Everything up to the first event row is the script header — what a
50 // Matroska track carries as `CodecPrivate`.
51 if trimmed.starts_with("Dialogue:") || trimmed.starts_with("Comment:") {
52 in_events = true;
53 } else if !in_events {
54 header_end += line.len();
55 }
56 if trimmed.is_empty() || trimmed.starts_with(';') || trimmed.starts_with('!') {
57 continue;
58 }
59 if let Some(name) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
60 section = Section::of(name);
61 saw_events |= matches!(section, Section::Events);
62 continue;
63 }
64 let Some((key, value)) = trimmed.split_once(':') else {
65 continue;
66 };
67 let value = value.trim();
68 match (section, key.trim()) {
69 (Section::ScriptInfo, key) => {
70 let key = snake_case(key);
71 // The first `WrapStyle` line counts, as it always did.
72 if key == "wrap_style" && !wrap_seen {
73 wrap_style = value.parse::<u8>().unwrap_or(0);
74 wrap_seen = true;
75 }
76 track.metadata.push((key, value.to_owned()));
77 }
78 (Section::Styles { .. }, "Format") => style_format = fields(value),
79 (Section::Styles { v4 }, "Style") => match style(&style_format, value, v4) {
80 Some(style) => track.styles.push(style),
81 None => track.skipped += 1,
82 },
83 (Section::Events, "Format") => event_format = fields(value),
84 (Section::Events, "Dialogue") => match dialogue(&event_format, value, wrap_style) {
85 Some(cue) => track.cues.push(cue),
86 None => track.skipped += 1,
87 },
88 // `Comment:` events are the script's own scratch lines: real rows
89 // of the events table, never on screen.
90 _ => {}
91 }
92 }
93 if track.cues.is_empty() && !saw_events {
94 return Err(Error::corrupt(
95 "no [Events] section: not an ASS or SSA script",
96 ));
97 }
98 track.extradata = text.as_bytes()[..header_end.min(text.len())].to_vec();
99 Ok(track)
100}
101
102#[derive(Clone, Copy)]
103enum Section {
104 None,
105 ScriptInfo,
106 /// `v4` marks the SSA-era table, whose alignment codes differ.
107 Styles {
108 v4: bool,
109 },
110 Events,
111}
112
113impl Section {
114 fn of(name: &str) -> Section {
115 let lower = name.trim().to_ascii_lowercase();
116 match lower.as_str() {
117 "script info" => Section::ScriptInfo,
118 "events" => Section::Events,
119 "v4 styles" => Section::Styles { v4: true },
120 _ if lower.ends_with("styles") => Section::Styles { v4: false },
121 _ => Section::None,
122 }
123 }
124}
125
126/// `PlayResX` → `play_res_x`, `Original Script` → `original_script`: metadata
127/// keys are one shape whichever way the script wrote them.
128fn snake_case(key: &str) -> String {
129 let mut out = String::with_capacity(key.len() + 4);
130 let mut previous = ' ';
131 for c in key.trim().chars() {
132 match c {
133 ' ' | '-' => out.push('_'),
134 c => {
135 if c.is_ascii_uppercase()
136 && (previous.is_ascii_lowercase() || previous.is_ascii_digit())
137 {
138 out.push('_');
139 }
140 out.push(c.to_ascii_lowercase());
141 }
142 }
143 previous = c;
144 }
145 out
146}
147
148fn fields(value: &str) -> Vec<String> {
149 value.split(',').map(|f| f.trim().to_owned()).collect()
150}
151
152/// Column `name` of a row, by the order the table's `Format:` line declared.
153fn column<'a>(format: &[String], values: &'a [&'a str], name: &str) -> Option<&'a str> {
154 let at = format.iter().position(|f| f.eq_ignore_ascii_case(name))?;
155 values.get(at).map(|v| v.trim())
156}
157
158fn style(format: &[String], row: &str, v4: bool) -> Option<SubtitleStyle> {
159 // A table with no `Format:` line at all uses the order every tool writes.
160 const DEFAULT: &str = "Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,\
161 BackColour,Bold,Italic,Underline,StrikeOut,ScaleX,ScaleY,Spacing,Angle,BorderStyle,\
162 Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding";
163 let fallback = fields(DEFAULT);
164 let format = if format.is_empty() { &fallback } else { format };
165 let values: Vec<&str> = row.split(',').collect();
166 let name = column(format, &values, "Name")?;
167 let number = |key: &str| column(format, &values, key).and_then(|v| v.parse::<f32>().ok());
168 let margin = |key: &str| column(format, &values, key).and_then(|v| v.parse::<i32>().ok());
169 let flag = |key: &str| column(format, &values, key).is_some_and(|v| v.trim() != "0");
170 Some(SubtitleStyle {
171 name: name.to_owned(),
172 font_family: column(format, &values, "Fontname").map(str::to_owned),
173 font_size: number("Fontsize"),
174 primary_color: column(format, &values, "PrimaryColour").and_then(parse_color),
175 secondary_color: column(format, &values, "SecondaryColour").and_then(parse_color),
176 outline_color: column(format, &values, "OutlineColour")
177 .or_else(|| column(format, &values, "TertiaryColour"))
178 .and_then(parse_color),
179 back_color: column(format, &values, "BackColour").and_then(parse_color),
180 bold: flag("Bold"),
181 italic: flag("Italic"),
182 underline: flag("Underline"),
183 strike: flag("StrikeOut"),
184 align: column(format, &values, "Alignment")
185 .and_then(|v| v.parse().ok())
186 .map(|code| alignment(code, v4))
187 .unwrap_or_default(),
188 margin_l: margin("MarginL"),
189 margin_r: margin("MarginR"),
190 margin_v: margin("MarginV"),
191 outline: number("Outline"),
192 shadow: number("Shadow"),
193 })
194}
195
196/// ASS alignment is the numeric keypad (`\an`): 1/4/7 left, 2/5/8 centre,
197/// 3/6/9 right. SSA v4 used a different code with the same three columns in
198/// its low two bits.
199fn alignment(code: i32, v4: bool) -> TextAlign {
200 let column = match v4 {
201 true => code & 0b11,
202 // `wrapping_sub`: `code - 1` panics at i32::MIN, and that code is a number a file can state.
203 false => code.wrapping_sub(1) % 3 + 1,
204 };
205 match column {
206 1 => TextAlign::Left,
207 2 => TextAlign::Center,
208 3 => TextAlign::Right,
209 _ => TextAlign::default(),
210 }
211}
212
213/// `&HAABBGGRR&`: BGR with a *transparency* byte, so 0 is opaque.
214fn parse_color(value: &str) -> Option<(u8, u8, u8, u8)> {
215 let digits: String = value
216 .trim()
217 .trim_start_matches(['&', 'H', 'h'])
218 .trim_end_matches('&')
219 .chars()
220 .take_while(char::is_ascii_hexdigit)
221 .collect();
222 let packed = u32::from_str_radix(&digits, 16).ok()?;
223 Some((
224 (packed & 0xFF) as u8,
225 ((packed >> 8) & 0xFF) as u8,
226 ((packed >> 16) & 0xFF) as u8,
227 255 - ((packed >> 24) & 0xFF) as u8,
228 ))
229}
230
231fn dialogue(format: &[String], row: &str, wrap_style: u8) -> Option<SubtitleCue> {
232 const DEFAULT: &str = "Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text";
233 let fallback = fields(DEFAULT);
234 let format = if format.is_empty() { &fallback } else { format };
235 // `Text` is last and holds commas of its own, so the row is split into
236 // exactly as many fields as the table declares and no further.
237 let values: Vec<&str> = row.splitn(format.len(), ',').collect();
238 let start_us = parse_clock(column(format, &values, "Start")?)?;
239 let end_us = parse_clock(column(format, &values, "End")?)?;
240 let text = column(format, &values, "Text").unwrap_or_default();
241 let (segments, positioning) = body(text, wrap_style);
242 Some(SubtitleCue {
243 start_us,
244 end_us: end_us.max(start_us),
245 style_ref: column(format, &values, "Style")
246 .filter(|s| !s.is_empty())
247 .map(str::to_owned),
248 positioning,
249 segments,
250 })
251}
252
253/// The state an override block leaves behind for the runs after it.
254#[derive(Clone, Default)]
255struct Overrides {
256 bold: bool,
257 italic: bool,
258 underline: bool,
259 strike: bool,
260 color: Option<(u8, u8, u8)>,
261 family: Option<String>,
262 size: Option<f32>,
263 /// The syllable the next runs belong to: `(cs, start_cs, mode)`.
264 karaoke: Option<(u32, u32, KaraokeMode)>,
265 /// Where the previous syllable ended; the next `\k` starts here.
266 karaoke_end: u32,
267 /// `\kt`: the absolute start the next `\k` takes instead.
268 karaoke_at: Option<u32>,
269 /// `\2c`: the not-yet-sung colour.
270 secondary: Option<(u8, u8, u8)>,
271 /// `\p1` and up: the text is a drawing, not words.
272 drawing: bool,
273}
274
275/// One `Text` field into runs, plus whatever positioning its overrides state.
276fn body(text: &str, wrap_style: u8) -> (Vec<Segment>, Option<CuePosition>) {
277 let mut out: Vec<Segment> = Vec::new();
278 let mut state = Overrides::default();
279 let mut position = CuePosition::default();
280 let mut positioned = false;
281 let mut run = String::new();
282 let mut rest = text;
283 while let Some(at) = rest.find('{') {
284 let (before, after) = rest.split_at(at);
285 push_text(&mut out, &mut run, before, &state, wrap_style);
286 let Some(end) = after.find('}') else {
287 // An unbalanced brace: the rest of the line is text, braces and all.
288 run.push_str(after);
289 rest = "";
290 break;
291 };
292 let block = &after[1..end];
293 rest = &after[end + 1..];
294 flush(&mut out, &mut run, &state);
295 if let Some(unknown) = overrides(block, &mut state, &mut position, &mut positioned) {
296 out.push(Segment::Raw(unknown));
297 }
298 }
299 push_text(&mut out, &mut run, rest, &state, wrap_style);
300 flush(&mut out, &mut run, &state);
301 (out, positioned.then_some(position))
302}
303
304/// Apply one brace block's overrides. Returns the overrides this does not
305/// model, verbatim, for a [`Segment::Raw`].
306fn overrides(
307 block: &str,
308 state: &mut Overrides,
309 position: &mut CuePosition,
310 positioned: &mut bool,
311) -> Option<String> {
312 let mut unknown = String::new();
313 for tag in tags(block) {
314 let tag = tag.trim_end();
315 if tag.is_empty() {
316 continue;
317 }
318 let Some((name, arg)) = split_tag(tag) else {
319 unknown.push_str(&format!("\\{tag}"));
320 continue;
321 };
322 let flag = || !arg.trim().trim_start_matches('0').is_empty();
323 match name {
324 "b" => state.bold = flag(),
325 "i" => state.italic = flag(),
326 "u" => state.underline = flag(),
327 "s" => state.strike = flag(),
328 "c" | "1c" => state.color = parse_color(arg).map(|(r, g, b, _)| (r, g, b)),
329 "fn" => state.family = Some(arg.trim().to_owned()).filter(|f| !f.is_empty()),
330 "fs" => state.size = arg.trim().parse().ok(),
331 "k" | "K" | "kf" | "ko" => {
332 // libass: a bare or unreadable duration is zero; negatives clamp to zero.
333 let cs = arg
334 .trim()
335 .parse::<i64>()
336 .unwrap_or(0)
337 .clamp(0, u32::MAX as i64 / 2) as u32;
338 let start = state.karaoke_at.take().unwrap_or(state.karaoke_end);
339 let mode = match name {
340 "k" => KaraokeMode::Fill,
341 "ko" => KaraokeMode::Outline,
342 _ => KaraokeMode::Sweep,
343 };
344 state.karaoke = Some((cs, start, mode));
345 state.karaoke_end = start.saturating_add(cs);
346 }
347 "kt" => {
348 state.karaoke_at = arg
349 .trim()
350 .parse::<i64>()
351 .ok()
352 .map(|v| v.clamp(0, u32::MAX as i64 / 2) as u32);
353 }
354 "2c" => state.secondary = parse_color(arg).map(|(r, g, b, _)| (r, g, b)),
355 "r" => {
356 // Back to the style. Which style `\rName` names is for the renderer, so it stays.
357 let (end, name) = (state.karaoke_end, arg.trim());
358 *state = Overrides {
359 karaoke_end: end,
360 ..Overrides::default()
361 };
362 if !name.is_empty() {
363 unknown.push_str(&format!("\\{tag}"));
364 }
365 }
366 "p" => state.drawing = flag(),
367 "an" => {
368 if let Ok(code) = arg.trim().parse::<i32>() {
369 position.align = alignment(code, false);
370 *positioned = true;
371 }
372 }
373 "a" => {
374 if let Ok(code) = arg.trim().parse::<i32>() {
375 position.align = alignment(code, true);
376 *positioned = true;
377 }
378 }
379 "pos" | "move" => {
380 // `\move(x1,y1,x2,y2,…)` starts where `\pos(x,y)` would put it.
381 let mut parts = arg
382 .trim_matches(['(', ')'])
383 .split(',')
384 .filter_map(|n| n.trim().parse().ok());
385 position.x = parts.next();
386 position.y = parts.next();
387 *positioned = true;
388 if name == "move" {
389 unknown.push_str(&format!("\\{tag}"));
390 }
391 }
392 _ => unknown.push_str(&format!("\\{tag}")),
393 }
394 }
395 (!unknown.is_empty()).then(|| format!("{{{unknown}}}"))
396}
397
398/// The `\`-separated tags of one brace block. A backslash inside parentheses belongs to the
399/// enclosing tag: in `\t(0,500,\fs20)` the `\fs20` is an argument of `\t`, not a tag of its own.
400fn tags(block: &str) -> Vec<&str> {
401 let mut out = Vec::new();
402 let mut depth = 0usize;
403 let mut start = None;
404 for (at, c) in block.char_indices() {
405 match c {
406 '(' => depth += 1,
407 ')' => depth = depth.saturating_sub(1),
408 '\\' if depth == 0 => {
409 if let Some(from) = start {
410 out.push(&block[from..at]);
411 }
412 start = Some(at + 1);
413 }
414 _ => {}
415 }
416 }
417 if let Some(from) = start {
418 out.push(&block[from..]);
419 }
420 out
421}
422
423/// An override into its name and its argument.
424///
425/// The names overlap — `\b` is bold and `\blur` is a blur — so a one-letter
426/// name is only that name when what follows it could be its argument: a
427/// number, a `&H` colour, a bracketed list, or nothing at all. Everything else
428/// falls through to [`Segment::Raw`] rather than being half-read.
429fn split_tag(tag: &str) -> Option<(&str, &str)> {
430 const NAMES: [&str; 20] = [
431 "move", "pos", "fn", "fs", "kf", "ko", "kt", "an", "1c", "2c", "c", "b", "i", "u", "s",
432 "k", "K", "p", "a", "r",
433 ];
434 NAMES.iter().find_map(|name| {
435 let arg = tag.strip_prefix(name)?;
436 // A font name is letters, so `\fn` takes whatever follows it.
437 let plausible = matches!(*name, "fn" | "r")
438 || arg.is_empty()
439 || arg.starts_with(|c: char| c.is_ascii_digit() || matches!(c, '-' | '&' | '(' | '.'));
440 plausible.then_some((*name, arg))
441 })
442}
443
444/// Plain text between override blocks, with the three escapes ASS gives it.
445fn push_text(
446 out: &mut Vec<Segment>,
447 run: &mut String,
448 text: &str,
449 state: &Overrides,
450 wrap_style: u8,
451) {
452 let mut chars = text.chars().peekable();
453 while let Some(c) = chars.next() {
454 if c != '\\' {
455 run.push(c);
456 continue;
457 }
458 match chars.next() {
459 // `\N` always breaks; `\n` breaks only where the script asked for
460 // no automatic wrapping (`WrapStyle: 2`), and is a space otherwise,
461 // which is what every renderer does with it.
462 Some('N') => {
463 flush(out, run, state);
464 out.push(Segment::LineBreak);
465 }
466 Some('n') if wrap_style == 2 => {
467 flush(out, run, state);
468 out.push(Segment::LineBreak);
469 }
470 Some('n') => run.push(' '),
471 Some('h') => run.push('\u{a0}'),
472 Some(other) => {
473 run.push('\\');
474 run.push(other);
475 }
476 None => run.push('\\'),
477 }
478 }
479}
480
481/// Close the pending run, wrapping it in whatever the overrides asked for.
482fn flush(out: &mut Vec<Segment>, run: &mut String, state: &Overrides) {
483 if run.is_empty() {
484 return;
485 }
486 let text = std::mem::take(run);
487 // A drawing is shapes, not words: kept whole so a renderer can have it and
488 // `plain_text` says nothing.
489 if state.drawing {
490 out.push(Segment::Raw(text));
491 return;
492 }
493 let mut segment = vec![Segment::Text(text)];
494 if let Some((cs, start_cs, mode)) = state.karaoke {
495 segment = vec![Segment::Karaoke {
496 cs,
497 start_cs,
498 mode,
499 secondary: state.secondary,
500 children: segment,
501 }];
502 }
503 if state.family.is_some() || state.size.is_some() {
504 segment = vec![Segment::Font {
505 family: state.family.clone(),
506 size: state.size,
507 children: segment,
508 }];
509 }
510 if let Some(rgb) = state.color {
511 segment = vec![Segment::Color {
512 rgb,
513 children: segment,
514 }];
515 }
516 for (on, wrap) in [
517 (state.strike, Segment::Strike as fn(Vec<Segment>) -> Segment),
518 (state.underline, Segment::Underline as fn(_) -> _),
519 (state.italic, Segment::Italic as fn(_) -> _),
520 (state.bold, Segment::Bold as fn(_) -> _),
521 ] {
522 if on {
523 segment = vec![wrap(segment)];
524 }
525 }
526 out.extend(segment);
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532 use ec_subs::plain_text;
533
534 const SCRIPT: &str = "[Script Info]\n\
535 Title: A script\n\
536 WrapStyle: 0\n\
537 PlayResX: 1920\n\
538 \n\
539 [V4+ Styles]\n\
540 Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, \
541 Underline, StrikeOut, Alignment, MarginL, MarginR, MarginV, Outline, Shadow, Encoding\n\
542 Style: Default,Arial,48,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,2,10,10,20,2,1,1\n\
543 \n\
544 [Events]\n\
545 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
546 Dialogue: 0,0:00:01.00,0:00:03.50,Default,,0,0,0,,{\\i1}tilted{\\i0} plain\\Nsecond, with comma\n\
547 Comment: 0,0:00:04.00,0:00:05.00,Default,,0,0,0,,not on screen\n\
548 Dialogue: 0,0:00:06.00,0:00:07.00,Default,,0,0,0,,{\\an8\\pos(960,100)}up top\n";
549
550 #[test]
551 fn a_script_parses_header_styles_and_events() {
552 let track = parse(SCRIPT.as_bytes()).unwrap();
553 assert_eq!(track.source, Some(SourceFormat::AssOrSsa));
554 assert_eq!(
555 track.metadata.iter().find(|(k, _)| k == "title").unwrap().1,
556 "A script"
557 );
558 let style = track.style("Default").unwrap();
559 assert_eq!(style.font_family.as_deref(), Some("Arial"));
560 assert_eq!(style.font_size, Some(48.0));
561 assert!(style.bold && !style.italic);
562 assert_eq!(style.primary_color, Some((255, 255, 255, 255)));
563 // `&H80000000` is half transparent, and BGR order means blue is zero.
564 assert_eq!(style.back_color, Some((0, 0, 0, 127)));
565 assert_eq!(style.align, TextAlign::Center);
566
567 // The `Comment:` row is not a cue.
568 assert_eq!(track.cues.len(), 2);
569 let cue = &track.cues[0];
570 assert_eq!((cue.start_us, cue.end_us), (1_000_000, 3_500_000));
571 assert_eq!(cue.style_ref.as_deref(), Some("Default"));
572 // The text field keeps its own commas.
573 assert_eq!(
574 plain_text(&cue.segments),
575 "tilted plain\nsecond, with comma"
576 );
577 assert!(matches!(cue.segments[0], Segment::Italic(_)));
578 assert_eq!(track.skipped, 0);
579 // The header is what a Matroska `CodecPrivate` carries.
580 assert!(track.extradata.starts_with(b"[Script Info]"));
581 assert!(!track.extradata.windows(9).any(|w| w == b"Dialogue:"));
582 }
583
584 #[test]
585 fn positioning_overrides_reach_the_cue() {
586 let track = parse(SCRIPT.as_bytes()).unwrap();
587 let position = track.cues[1].positioning.unwrap();
588 assert_eq!(position.align, TextAlign::Center);
589 assert_eq!((position.x, position.y), (Some(960.0), Some(100.0)));
590 assert_eq!(plain_text(&track.cues[1].segments), "up top");
591 }
592
593 #[test]
594 fn karaoke_drawings_and_unknown_tags() {
595 let doc = "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\
596 Dialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{\\k30}ka{\\k25}ra\n\
597 Dialogue: 0,0:00:01.00,0:00:02.00,,,0,0,0,,{\\p1}m 0 0 l 10 10{\\p0}words\n\
598 Dialogue: 0,0:00:02.00,0:00:03.00,,,0,0,0,,{\\t(0,500,\\fscx120)}moving\n";
599 let track = parse(doc.as_bytes()).unwrap();
600 assert_eq!(plain_text(&track.cues[0].segments), "kara");
601 assert!(matches!(
602 track.cues[0].segments[0],
603 Segment::Karaoke {
604 cs: 30,
605 start_cs: 0,
606 mode: KaraokeMode::Fill,
607 ..
608 }
609 ));
610 assert!(matches!(
611 track.cues[0].segments[1],
612 Segment::Karaoke {
613 cs: 25,
614 start_cs: 30,
615 ..
616 }
617 ));
618 // Drawing commands are not words.
619 assert_eq!(plain_text(&track.cues[1].segments), "words");
620 // An override this does not model survives as itself.
621 assert_eq!(plain_text(&track.cues[2].segments), "moving");
622 assert!(
623 track.cues[2]
624 .segments
625 .iter()
626 .any(|s| matches!(s, Segment::Raw(r) if r.contains("fscx120")))
627 );
628 }
629
630 #[test]
631 fn tolerances_and_the_refusal() {
632 // No `Format:` line, CRLF, a torn row, and `\h` / `\n`.
633 let doc = b"\xef\xbb\xbf[Events]\r\n\
634 Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,a\\hb\\nc\r\n\
635 Dialogue: not a row\r\n";
636 let track = parse(doc).unwrap();
637 assert_eq!(track.cues.len(), 1);
638 assert_eq!(track.skipped, 1);
639 assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b c");
640 // `WrapStyle: 2` makes `\n` a break instead.
641 let wrapped = format!(
642 "[Script Info]\nWrapStyle: 2\n{}",
643 String::from_utf8_lossy(&doc[3..])
644 );
645 let track = parse(wrapped.as_bytes()).unwrap();
646 assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b\nc");
647
648 assert!(parse(b"just some prose").is_err());
649 }
650
651 type Syl = (String, u32, u32, KaraokeMode, Option<(u8, u8, u8)>);
652
653 fn syllables(text: &str) -> Vec<Syl> {
654 let doc = format!(
655 "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\
656 Dialogue: 0,0:00:00.00,0:00:09.00,,,0,0,0,,{text}\n"
657 );
658 let track = parse(doc.as_bytes()).unwrap();
659 let mut out = Vec::new();
660 fn walk(segs: &[Segment], out: &mut Vec<Syl>) {
661 for s in segs {
662 match s {
663 Segment::Karaoke {
664 cs,
665 start_cs,
666 mode,
667 secondary,
668 children,
669 } => out.push((plain_text(children), *cs, *start_cs, *mode, *secondary)),
670 Segment::Bold(c) | Segment::Italic(c) | Segment::Color { children: c, .. } => {
671 walk(c, out)
672 }
673 _ => {}
674 }
675 }
676 }
677 walk(&track.cues[0].segments, &mut out);
678 out
679 }
680
681 #[test]
682 fn karaoke_modes_timing_and_colours() {
683 use KaraokeMode::*;
684 let got = syllables("{\\2c&H0000FF&\\k10}a{\\kf20}b{\\K30}c{\\ko40}d{\\k0}e");
685 let red = Some((255, 0, 0));
686 assert_eq!(
687 got,
688 vec![
689 ("a".into(), 10, 0, Fill, red),
690 ("b".into(), 20, 10, Sweep, red),
691 ("c".into(), 30, 30, Sweep, red),
692 ("d".into(), 40, 60, Outline, red),
693 ("e".into(), 0, 100, Fill, red),
694 ]
695 );
696 // `\kt` is absolute, and the next `\k` begins there.
697 let got = syllables("{\\k10}a{\\kt200\\k5}b{\\k5}c");
698 assert_eq!((got[1].2, got[2].2), (200, 205));
699 // Two tags with no text between add up: the empty syllable still takes its time.
700 let got = syllables("{\\k10}{\\k20}x");
701 assert_eq!((got[0].1, got[0].2), (20, 10));
702 // A style block inside a syllable does not start a new one; `\r` ends the effect.
703 let got = syllables("{\\k10}a{\\b1}b{\\r}c");
704 assert_eq!(got.len(), 2);
705 assert_eq!((got[0].1, got[0].2, got[1].1, got[1].2), (10, 0, 10, 0));
706 }
707
708 #[test]
709 fn other_overrides_survive_for_a_renderer() {
710 let tags = [
711 "\\t(0,500,0.5,\\fscx120\\c&H0000FF&)",
712 "\\fad(200,300)",
713 "\\fade(0,255,0,0,100,900,1000)",
714 "\\clip(0,0,100,100)",
715 "\\iclip(m 0 0 l 50 0 50 50)",
716 "\\org(960,540)",
717 "\\frx10\\fry20\\frz30\\fax0.1\\fay0.2",
718 "\\be2\\blur1.5",
719 "\\q2",
720 "\\fsp3",
721 "\\bord2\\shad1",
722 ];
723 for tag in tags {
724 let doc =
725 format!("[Events]\nDialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{{{tag}}}word\n");
726 let track = parse(doc.as_bytes()).unwrap();
727 let segs = &track.cues[0].segments;
728 assert_eq!(plain_text(segs), "word", "{tag}");
729 let raw: String = segs
730 .iter()
731 .filter_map(|s| {
732 if let Segment::Raw(r) = s {
733 Some(r.as_str())
734 } else {
735 None
736 }
737 })
738 .collect();
739 assert_eq!(raw, format!("{{{tag}}}"), "{tag}");
740 assert!(!segs.iter().any(|s| matches!(s, Segment::Bold(_))), "{tag}");
741 }
742 // `\move` keeps its start as the position and its full form as Raw.
743 let doc = "[Events]\nDialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{\\an8\\move(10,20,30,40,100,500)}m\n";
744 let track = parse(doc.as_bytes()).unwrap();
745 let p = track.cues[0].positioning.unwrap();
746 assert_eq!(
747 (p.x, p.y, p.align),
748 (Some(10.0), Some(20.0), TextAlign::Center)
749 );
750 assert!(
751 matches!(&track.cues[0].segments[0], Segment::Raw(r) if r == "{\\move(10,20,30,40,100,500)}")
752 );
753 // `\r` clears the overrides before it.
754 let got = syllables("{\\b1\\k5}a{\\r}b");
755 assert_eq!(got.len(), 1);
756 }
757}