forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli8 hours ago4263 commits

lib.rs760 lines, 28.9 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 if end_us <= start_us {
241 return None;
242 }
243 let text = column(format, &values, "Text").unwrap_or_default();
244 let (segments, positioning) = body(text, wrap_style);
245 Some(SubtitleCue {
246 start_us,
247 end_us,
248 style_ref: column(format, &values, "Style")
249 .filter(|s| !s.is_empty())
250 .map(str::to_owned),
251 positioning,
252 segments,
253 })
254}
255
256/// The state an override block leaves behind for the runs after it.
257#[derive(Clone, Default)]
258struct Overrides {
259 bold: bool,
260 italic: bool,
261 underline: bool,
262 strike: bool,
263 color: Option<(u8, u8, u8)>,
264 family: Option<String>,
265 size: Option<f32>,
266 /// The syllable the next runs belong to: `(cs, start_cs, mode)`.
267 karaoke: Option<(u32, u32, KaraokeMode)>,
268 /// Where the previous syllable ended; the next `\k` starts here.
269 karaoke_end: u32,
270 /// `\kt`: the absolute start the next `\k` takes instead.
271 karaoke_at: Option<u32>,
272 /// `\2c`: the not-yet-sung colour.
273 secondary: Option<(u8, u8, u8)>,
274 /// `\p1` and up: the text is a drawing, not words.
275 drawing: bool,
276}
277
278/// One `Text` field into runs, plus whatever positioning its overrides state.
279fn body(text: &str, wrap_style: u8) -> (Vec<Segment>, Option<CuePosition>) {
280 let mut out: Vec<Segment> = Vec::new();
281 let mut state = Overrides::default();
282 let mut position = CuePosition::default();
283 let mut positioned = false;
284 let mut run = String::new();
285 let mut rest = text;
286 while let Some(at) = rest.find('{') {
287 let (before, after) = rest.split_at(at);
288 push_text(&mut out, &mut run, before, &state, wrap_style);
289 let Some(end) = after.find('}') else {
290 // An unbalanced brace: the rest of the line is text, braces and all.
291 run.push_str(after);
292 rest = "";
293 break;
294 };
295 let block = &after[1..end];
296 rest = &after[end + 1..];
297 flush(&mut out, &mut run, &state);
298 if let Some(unknown) = overrides(block, &mut state, &mut position, &mut positioned) {
299 out.push(Segment::Raw(unknown));
300 }
301 }
302 push_text(&mut out, &mut run, rest, &state, wrap_style);
303 flush(&mut out, &mut run, &state);
304 (out, positioned.then_some(position))
305}
306
307/// Apply one brace block's overrides. Returns the overrides this does not
308/// model, verbatim, for a [`Segment::Raw`].
309fn overrides(
310 block: &str,
311 state: &mut Overrides,
312 position: &mut CuePosition,
313 positioned: &mut bool,
314) -> Option<String> {
315 let mut unknown = String::new();
316 for tag in tags(block) {
317 let tag = tag.trim_end();
318 if tag.is_empty() {
319 continue;
320 }
321 let Some((name, arg)) = split_tag(tag) else {
322 unknown.push_str(&format!("\\{tag}"));
323 continue;
324 };
325 let flag = || !arg.trim().trim_start_matches('0').is_empty();
326 match name {
327 "b" => state.bold = flag(),
328 "i" => state.italic = flag(),
329 "u" => state.underline = flag(),
330 "s" => state.strike = flag(),
331 "c" | "1c" => state.color = parse_color(arg).map(|(r, g, b, _)| (r, g, b)),
332 "fn" => state.family = Some(arg.trim().to_owned()).filter(|f| !f.is_empty()),
333 "fs" => state.size = arg.trim().parse().ok(),
334 "k" | "K" | "kf" | "ko" => {
335 // libass: a bare or unreadable duration is zero; negatives clamp to zero.
336 let cs = arg
337 .trim()
338 .parse::<i64>()
339 .unwrap_or(0)
340 .clamp(0, u32::MAX as i64 / 2) as u32;
341 let start = state.karaoke_at.take().unwrap_or(state.karaoke_end);
342 let mode = match name {
343 "k" => KaraokeMode::Fill,
344 "ko" => KaraokeMode::Outline,
345 _ => KaraokeMode::Sweep,
346 };
347 state.karaoke = Some((cs, start, mode));
348 state.karaoke_end = start.saturating_add(cs);
349 }
350 "kt" => {
351 state.karaoke_at = arg
352 .trim()
353 .parse::<i64>()
354 .ok()
355 .map(|v| v.clamp(0, u32::MAX as i64 / 2) as u32);
356 }
357 "2c" => state.secondary = parse_color(arg).map(|(r, g, b, _)| (r, g, b)),
358 "r" => {
359 // Back to the style. Which style `\rName` names is for the renderer, so it stays.
360 let (end, name) = (state.karaoke_end, arg.trim());
361 *state = Overrides {
362 karaoke_end: end,
363 ..Overrides::default()
364 };
365 if !name.is_empty() {
366 unknown.push_str(&format!("\\{tag}"));
367 }
368 }
369 "p" => state.drawing = flag(),
370 "an" => {
371 if let Ok(code) = arg.trim().parse::<i32>() {
372 position.align = alignment(code, false);
373 *positioned = true;
374 }
375 }
376 "a" => {
377 if let Ok(code) = arg.trim().parse::<i32>() {
378 position.align = alignment(code, true);
379 *positioned = true;
380 }
381 }
382 "pos" | "move" => {
383 // `\move(x1,y1,x2,y2,…)` starts where `\pos(x,y)` would put it.
384 let mut parts = arg
385 .trim_matches(['(', ')'])
386 .split(',')
387 .filter_map(|n| n.trim().parse().ok());
388 position.x = parts.next();
389 position.y = parts.next();
390 *positioned = true;
391 if name == "move" {
392 unknown.push_str(&format!("\\{tag}"));
393 }
394 }
395 _ => unknown.push_str(&format!("\\{tag}")),
396 }
397 }
398 (!unknown.is_empty()).then(|| format!("{{{unknown}}}"))
399}
400
401/// The `\`-separated tags of one brace block. A backslash inside parentheses belongs to the
402/// enclosing tag: in `\t(0,500,\fs20)` the `\fs20` is an argument of `\t`, not a tag of its own.
403fn tags(block: &str) -> Vec<&str> {
404 let mut out = Vec::new();
405 let mut depth = 0usize;
406 let mut start = None;
407 for (at, c) in block.char_indices() {
408 match c {
409 '(' => depth += 1,
410 ')' => depth = depth.saturating_sub(1),
411 '\\' if depth == 0 => {
412 if let Some(from) = start {
413 out.push(&block[from..at]);
414 }
415 start = Some(at + 1);
416 }
417 _ => {}
418 }
419 }
420 if let Some(from) = start {
421 out.push(&block[from..]);
422 }
423 out
424}
425
426/// An override into its name and its argument.
427///
428/// The names overlap — `\b` is bold and `\blur` is a blur — so a one-letter
429/// name is only that name when what follows it could be its argument: a
430/// number, a `&H` colour, a bracketed list, or nothing at all. Everything else
431/// falls through to [`Segment::Raw`] rather than being half-read.
432fn split_tag(tag: &str) -> Option<(&str, &str)> {
433 const NAMES: [&str; 20] = [
434 "move", "pos", "fn", "fs", "kf", "ko", "kt", "an", "1c", "2c", "c", "b", "i", "u", "s",
435 "k", "K", "p", "a", "r",
436 ];
437 NAMES.iter().find_map(|name| {
438 let arg = tag.strip_prefix(name)?;
439 // A font name is letters, so `\fn` takes whatever follows it.
440 let plausible = matches!(*name, "fn" | "r")
441 || arg.is_empty()
442 || arg.starts_with(|c: char| c.is_ascii_digit() || matches!(c, '-' | '&' | '(' | '.'));
443 plausible.then_some((*name, arg))
444 })
445}
446
447/// Plain text between override blocks, with the three escapes ASS gives it.
448fn push_text(
449 out: &mut Vec<Segment>,
450 run: &mut String,
451 text: &str,
452 state: &Overrides,
453 wrap_style: u8,
454) {
455 let mut chars = text.chars().peekable();
456 while let Some(c) = chars.next() {
457 if c != '\\' {
458 run.push(c);
459 continue;
460 }
461 match chars.next() {
462 // `\N` always breaks; `\n` breaks only where the script asked for
463 // no automatic wrapping (`WrapStyle: 2`), and is a space otherwise,
464 // which is what every renderer does with it.
465 Some('N') => {
466 flush(out, run, state);
467 out.push(Segment::LineBreak);
468 }
469 Some('n') if wrap_style == 2 => {
470 flush(out, run, state);
471 out.push(Segment::LineBreak);
472 }
473 Some('n') => run.push(' '),
474 Some('h') => run.push('\u{a0}'),
475 Some(other) => {
476 run.push('\\');
477 run.push(other);
478 }
479 None => run.push('\\'),
480 }
481 }
482}
483
484/// Close the pending run, wrapping it in whatever the overrides asked for.
485fn flush(out: &mut Vec<Segment>, run: &mut String, state: &Overrides) {
486 if run.is_empty() {
487 return;
488 }
489 let text = std::mem::take(run);
490 // A drawing is shapes, not words: kept whole so a renderer can have it and
491 // `plain_text` says nothing.
492 if state.drawing {
493 out.push(Segment::Raw(text));
494 return;
495 }
496 let mut segment = vec![Segment::Text(text)];
497 if let Some((cs, start_cs, mode)) = state.karaoke {
498 segment = vec![Segment::Karaoke {
499 cs,
500 start_cs,
501 mode,
502 secondary: state.secondary,
503 children: segment,
504 }];
505 }
506 if state.family.is_some() || state.size.is_some() {
507 segment = vec![Segment::Font {
508 family: state.family.clone(),
509 size: state.size,
510 children: segment,
511 }];
512 }
513 if let Some(rgb) = state.color {
514 segment = vec![Segment::Color {
515 rgb,
516 children: segment,
517 }];
518 }
519 for (on, wrap) in [
520 (state.strike, Segment::Strike as fn(Vec<Segment>) -> Segment),
521 (state.underline, Segment::Underline as fn(_) -> _),
522 (state.italic, Segment::Italic as fn(_) -> _),
523 (state.bold, Segment::Bold as fn(_) -> _),
524 ] {
525 if on {
526 segment = vec![wrap(segment)];
527 }
528 }
529 out.extend(segment);
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535 use ec_subs::plain_text;
536
537 const SCRIPT: &str = "[Script Info]\n\
538 Title: A script\n\
539 WrapStyle: 0\n\
540 PlayResX: 1920\n\
541 \n\
542 [V4+ Styles]\n\
543 Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, \
544 Underline, StrikeOut, Alignment, MarginL, MarginR, MarginV, Outline, Shadow, Encoding\n\
545 Style: Default,Arial,48,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,2,10,10,20,2,1,1\n\
546 \n\
547 [Events]\n\
548 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
549 Dialogue: 0,0:00:01.00,0:00:03.50,Default,,0,0,0,,{\\i1}tilted{\\i0} plain\\Nsecond, with comma\n\
550 Comment: 0,0:00:04.00,0:00:05.00,Default,,0,0,0,,not on screen\n\
551 Dialogue: 0,0:00:06.00,0:00:07.00,Default,,0,0,0,,{\\an8\\pos(960,100)}up top\n";
552
553 #[test]
554 fn a_script_parses_header_styles_and_events() {
555 let track = parse(SCRIPT.as_bytes()).unwrap();
556 assert_eq!(track.source, Some(SourceFormat::AssOrSsa));
557 assert_eq!(
558 track.metadata.iter().find(|(k, _)| k == "title").unwrap().1,
559 "A script"
560 );
561 let style = track.style("Default").unwrap();
562 assert_eq!(style.font_family.as_deref(), Some("Arial"));
563 assert_eq!(style.font_size, Some(48.0));
564 assert!(style.bold && !style.italic);
565 assert_eq!(style.primary_color, Some((255, 255, 255, 255)));
566 // `&H80000000` is half transparent, and BGR order means blue is zero.
567 assert_eq!(style.back_color, Some((0, 0, 0, 127)));
568 assert_eq!(style.align, TextAlign::Center);
569
570 // The `Comment:` row is not a cue.
571 assert_eq!(track.cues.len(), 2);
572 let cue = &track.cues[0];
573 assert_eq!((cue.start_us, cue.end_us), (1_000_000, 3_500_000));
574 assert_eq!(cue.style_ref.as_deref(), Some("Default"));
575 // The text field keeps its own commas.
576 assert_eq!(
577 plain_text(&cue.segments),
578 "tilted plain\nsecond, with comma"
579 );
580 assert!(matches!(cue.segments[0], Segment::Italic(_)));
581 assert_eq!(track.skipped, 0);
582 // The header is what a Matroska `CodecPrivate` carries.
583 assert!(track.extradata.starts_with(b"[Script Info]"));
584 assert!(!track.extradata.windows(9).any(|w| w == b"Dialogue:"));
585 }
586
587 #[test]
588 fn positioning_overrides_reach_the_cue() {
589 let track = parse(SCRIPT.as_bytes()).unwrap();
590 let position = track.cues[1].positioning.unwrap();
591 assert_eq!(position.align, TextAlign::Center);
592 assert_eq!((position.x, position.y), (Some(960.0), Some(100.0)));
593 assert_eq!(plain_text(&track.cues[1].segments), "up top");
594 }
595
596 #[test]
597 fn karaoke_drawings_and_unknown_tags() {
598 let doc = "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\
599 Dialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{\\k30}ka{\\k25}ra\n\
600 Dialogue: 0,0:00:01.00,0:00:02.00,,,0,0,0,,{\\p1}m 0 0 l 10 10{\\p0}words\n\
601 Dialogue: 0,0:00:02.00,0:00:03.00,,,0,0,0,,{\\t(0,500,\\fscx120)}moving\n";
602 let track = parse(doc.as_bytes()).unwrap();
603 assert_eq!(plain_text(&track.cues[0].segments), "kara");
604 assert!(matches!(
605 track.cues[0].segments[0],
606 Segment::Karaoke {
607 cs: 30,
608 start_cs: 0,
609 mode: KaraokeMode::Fill,
610 ..
611 }
612 ));
613 assert!(matches!(
614 track.cues[0].segments[1],
615 Segment::Karaoke {
616 cs: 25,
617 start_cs: 30,
618 ..
619 }
620 ));
621 // Drawing commands are not words.
622 assert_eq!(plain_text(&track.cues[1].segments), "words");
623 // An override this does not model survives as itself.
624 assert_eq!(plain_text(&track.cues[2].segments), "moving");
625 assert!(
626 track.cues[2]
627 .segments
628 .iter()
629 .any(|s| matches!(s, Segment::Raw(r) if r.contains("fscx120")))
630 );
631 }
632
633 #[test]
634 fn tolerances_and_the_refusal() {
635 // No `Format:` line, CRLF, a torn row, and `\h` / `\n`.
636 let doc = b"\xef\xbb\xbf[Events]\r\n\
637 Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,a\\hb\\nc\r\n\
638 Dialogue: not a row\r\n";
639 let track = parse(doc).unwrap();
640 assert_eq!(track.cues.len(), 1);
641 assert_eq!(track.skipped, 1);
642 assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b c");
643 // `WrapStyle: 2` makes `\n` a break instead.
644 let wrapped = format!(
645 "[Script Info]\nWrapStyle: 2\n{}",
646 String::from_utf8_lossy(&doc[3..])
647 );
648 let track = parse(wrapped.as_bytes()).unwrap();
649 assert_eq!(plain_text(&track.cues[0].segments), "a\u{a0}b\nc");
650
651 assert!(parse(b"just some prose").is_err());
652 }
653
654 type Syl = (String, u32, u32, KaraokeMode, Option<(u8, u8, u8)>);
655
656 fn syllables(text: &str) -> Vec<Syl> {
657 let doc = format!(
658 "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\
659 Dialogue: 0,0:00:00.00,0:00:09.00,,,0,0,0,,{text}\n"
660 );
661 let track = parse(doc.as_bytes()).unwrap();
662 let mut out = Vec::new();
663 fn walk(segs: &[Segment], out: &mut Vec<Syl>) {
664 for s in segs {
665 match s {
666 Segment::Karaoke {
667 cs,
668 start_cs,
669 mode,
670 secondary,
671 children,
672 } => out.push((plain_text(children), *cs, *start_cs, *mode, *secondary)),
673 Segment::Bold(c) | Segment::Italic(c) | Segment::Color { children: c, .. } => {
674 walk(c, out)
675 }
676 _ => {}
677 }
678 }
679 }
680 walk(&track.cues[0].segments, &mut out);
681 out
682 }
683
684 #[test]
685 fn karaoke_modes_timing_and_colours() {
686 use KaraokeMode::*;
687 let got = syllables("{\\2c&H0000FF&\\k10}a{\\kf20}b{\\K30}c{\\ko40}d{\\k0}e");
688 let red = Some((255, 0, 0));
689 assert_eq!(
690 got,
691 vec![
692 ("a".into(), 10, 0, Fill, red),
693 ("b".into(), 20, 10, Sweep, red),
694 ("c".into(), 30, 30, Sweep, red),
695 ("d".into(), 40, 60, Outline, red),
696 ("e".into(), 0, 100, Fill, red),
697 ]
698 );
699 // `\kt` is absolute, and the next `\k` begins there.
700 let got = syllables("{\\k10}a{\\kt200\\k5}b{\\k5}c");
701 assert_eq!((got[1].2, got[2].2), (200, 205));
702 // Two tags with no text between add up: the empty syllable still takes its time.
703 let got = syllables("{\\k10}{\\k20}x");
704 assert_eq!((got[0].1, got[0].2), (20, 10));
705 // A style block inside a syllable does not start a new one; `\r` ends the effect.
706 let got = syllables("{\\k10}a{\\b1}b{\\r}c");
707 assert_eq!(got.len(), 2);
708 assert_eq!((got[0].1, got[0].2, got[1].1, got[1].2), (10, 0, 10, 0));
709 }
710
711 #[test]
712 fn other_overrides_survive_for_a_renderer() {
713 let tags = [
714 "\\t(0,500,0.5,\\fscx120\\c&H0000FF&)",
715 "\\fad(200,300)",
716 "\\fade(0,255,0,0,100,900,1000)",
717 "\\clip(0,0,100,100)",
718 "\\iclip(m 0 0 l 50 0 50 50)",
719 "\\org(960,540)",
720 "\\frx10\\fry20\\frz30\\fax0.1\\fay0.2",
721 "\\be2\\blur1.5",
722 "\\q2",
723 "\\fsp3",
724 "\\bord2\\shad1",
725 ];
726 for tag in tags {
727 let doc =
728 format!("[Events]\nDialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{{{tag}}}word\n");
729 let track = parse(doc.as_bytes()).unwrap();
730 let segs = &track.cues[0].segments;
731 assert_eq!(plain_text(segs), "word", "{tag}");
732 let raw: String = segs
733 .iter()
734 .filter_map(|s| {
735 if let Segment::Raw(r) = s {
736 Some(r.as_str())
737 } else {
738 None
739 }
740 })
741 .collect();
742 assert_eq!(raw, format!("{{{tag}}}"), "{tag}");
743 assert!(!segs.iter().any(|s| matches!(s, Segment::Bold(_))), "{tag}");
744 }
745 // `\move` keeps its start as the position and its full form as Raw.
746 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";
747 let track = parse(doc.as_bytes()).unwrap();
748 let p = track.cues[0].positioning.unwrap();
749 assert_eq!(
750 (p.x, p.y, p.align),
751 (Some(10.0), Some(20.0), TextAlign::Center)
752 );
753 assert!(
754 matches!(&track.cues[0].segments[0], Segment::Raw(r) if r == "{\\move(10,20,30,40,100,500)}")
755 );
756 // `\r` clears the overrides before it.
757 let got = syllables("{\\b1\\k5}a{\\r}b");
758 assert_eq!(got.len(), 1);
759 }
760}