From 7b4d5f992c98ac8f8bff92505166254bd455ab92 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 15:18:25 +0100 Subject: [PATCH 1/2] craft-captions: ASS and SSA subtitles (Format::Ass) Reads the [Events] section of ASS v4+ and SSA v4 files and writes a minimal ASS v4+ file. Keeps line breaks, the Name field as the speaker and the \i, \b, \u override tags; other override tags and vector drawings are dropped. Closes #1550 --- Cargo.lock | 1 + crates/captions/Cargo.toml | 2 + crates/captions/README.md | 1 + crates/captions/src/ass.rs | 239 +++++++++++++++++++++++++++++++ crates/captions/src/lib.rs | 17 ++- crates/captions/tests/it/ass.rs | 113 +++++++++++++++ crates/captions/tests/it/main.rs | 1 + 7 files changed, 371 insertions(+), 3 deletions(-) create mode 100644 crates/captions/src/ass.rs create mode 100644 crates/captions/tests/it/ass.rs diff --git a/Cargo.lock b/Cargo.lock index 8e12a6995..55552f9f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1425,6 +1425,7 @@ version = "0.1.0" name = "craft-captions" version = "0.1.0" dependencies = [ + "craft-media-testkit", "craft-timeline", "craft-xml", "proptest", diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index df665336d..cd09f7e16 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -19,3 +19,5 @@ thiserror = { workspace = true } proptest = { workspace = true } # A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. roxmltree = "0.21" +# ffmpeg as the reference for the ASS tests (tests/it/ass.rs). +craft-media-testkit = { workspace = true } diff --git a/crates/captions/README.md b/crates/captions/README.md index 0676d1d72..7380a3ce4 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -55,6 +55,7 @@ lists at most 20 characters per stream. | EBU STL `.stl` | yes | yes | EBU Tech 3264-E: GSI block + 128-byte TTI blocks, `STL25.01` (25 fps) or `STL30.01` (read/written as 29.97 fps, non-drop labels), ISO/IEC 6937 Latin text (accents as diacritic + letter), italics / underline codes as `` / ``, extension blocks for long subtitles, start-of-programme (TCP) subtracted. | | TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `

` per cue, `
`, styled ``s for `` / `` / ``, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. | | DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). | +| ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as ``, ``, ``); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. | All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and diff --git a/crates/captions/src/ass.rs b/crates/captions/src/ass.rs new file mode 100644 index 000000000..3c907c829 --- /dev/null +++ b/crates/captions/src/ass.rs @@ -0,0 +1,239 @@ +//! Advanced SubStation Alpha and SubStation Alpha (`.ass`, `.ssa`). +//! +//! Reading takes the `[Events]` section: its `Format:` line gives the field order (ASS v4+ and SSA +//! v4 differ in the first field only), each `Dialogue:` line becomes a cue; `Comment:` lines and +//! the other sections are skipped. A cue gets the `Name` field as its speaker. The text keeps what +//! the neutral model can show: `\N` and `\n` become a line break and a space, `\h` a no-break +//! space, and the override tags `\i`, `\b` and `\u` become ``, `` and ``. Every other +//! override tag (colours, fonts, positions, karaoke, animation) is dropped, and a line that draws +//! vector shapes (`\p1`) is skipped with a warning. +//! +//! Writing gives a minimal ASS v4+ file: one `Default` style, one `Dialogue:` line per cue with +//! times to the centisecond. Braces in the text, which ASS reads as override blocks, are written +//! as the full-width `{` and `}`. + +use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, Error, Result}; + +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + +/// `H:MM:SS.cc`, the form SSA and ASS use (any number of fraction digits is read). +fn parse_time(s: &str) -> Option { + let s = s.trim(); + let (hms, frac) = s.split_once('.').unwrap_or((s, "")); + let mut parts = hms.split(':'); + let (h, m, sec) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() { + return None; + } + let num = |p: &str| -> Option { (!p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())).then(|| p.parse().ok()).flatten() }; + let (h, m, sec) = (num(h)?, num(m)?, num(sec)?); + if m >= 60 || sec >= 60 || h > 9999 { + return None; + } + let mut ticks = ((h * 60 + m) * 60 + sec) * TICKS_PER_SECOND; + if !frac.is_empty() { + if frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let d: i64 = frac.parse().ok()?; + ticks += (i128::from(d) * i128::from(TICKS_PER_SECOND) / 10i128.pow(frac.len() as u32)) as i64; + } + Some(Tick(ticks)) +} + +fn format_time(t: Tick) -> String { + let cs = (i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS); + let (h, m, s, c) = (cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100); + format!("{h}:{m:02}:{s:02}.{c:02}") +} + +/// The Text field of a Dialogue line as cue text; `None` when the line draws shapes. +fn convert_text(raw: &str) -> Option { + let mut out = String::new(); + // Open ``, ``, `` in the order they were opened. + let mut open: Vec = Vec::new(); + let mut chars = raw.chars().peekable(); + let mut drawing = false; + let mut dropped_drawing = false; + while let Some(c) = chars.next() { + match c { + '{' => { + let mut block = String::new(); + let mut closed = false; + for b in chars.by_ref() { + if b == '}' { + closed = true; + break; + } + block.push(b); + } + if !closed { + // An unterminated block is literal text. + out.push('{'); + out.push_str(&block); + continue; + } + for tag in block.split('\\').skip(1) { + let tag = tag.trim_end(); + let (name, val) = tag.split_at(tag.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(tag.len())); + match name { + "i" | "b" | "u" => { + let letter = name.chars().next().unwrap_or('i'); + let on = val.trim() != "0"; + if on && !open.contains(&letter) { + open.push(letter); + out.push_str(&format!("<{letter}>")); + } else if !on && open.contains(&letter) { + // Close back to it, reopening what was opened after. + let at = open.iter().position(|&o| o == letter).unwrap_or(0); + let after: Vec = open.split_off(at + 1); + for o in after.iter().rev() { + out.push_str(&format!("")); + } + open.pop(); + out.push_str(&format!("")); + for o in after { + open.push(o); + out.push_str(&format!("<{o}>")); + } + } + } + "p" => drawing = val.trim().parse::().unwrap_or(0) != 0, + _ => {} + } + } + } + '\\' => match chars.peek() { + Some('N') => { + chars.next(); + out.push('\n'); + } + Some('n') => { + chars.next(); + out.push(' '); + } + Some('h') => { + chars.next(); + out.push('\u{a0}'); + } + _ => out.push('\\'), + }, + c => { + if drawing { + dropped_drawing = true; + } else { + out.push(c); + } + } + } + } + if dropped_drawing && out.trim().is_empty() { + return None; + } + while let Some(o) = open.pop() { + out.push_str(&format!("")); + } + Some(out) +} + +pub fn parse(text: &str) -> Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut doc = Document::default(); + let mut in_events = false; + let mut saw_events = false; + // Column of each field in a Dialogue line. + let mut cols: Vec = + ["layer", "start", "end", "style", "name", "marginl", "marginr", "marginv", "effect", "text"].map(String::from).to_vec(); + let mut drawings = 0usize; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.starts_with('[') && line.ends_with(']') { + in_events = line.eq_ignore_ascii_case("[events]"); + saw_events |= in_events; + continue; + } + if !in_events { + continue; + } + let Some((key, rest)) = line.split_once(':') else { continue }; + let rest = rest.trim_start(); + match key.trim().to_ascii_lowercase().as_str() { + "format" => cols = rest.split(',').map(|f| f.trim().to_ascii_lowercase()).collect(), + "dialogue" => { + // The last column (Text) keeps its commas. + let fields: Vec<&str> = rest.splitn(cols.len(), ',').collect(); + let get = |name: &str| cols.iter().position(|c| c == name).and_then(|i| fields.get(i)).copied(); + let (Some(start), Some(end), Some(raw)) = (get("start").and_then(parse_time), get("end").and_then(parse_time), get("text")) else { + doc.warnings.push(format!("line {}: not a Dialogue line this reader understands", n + 1)); + continue; + }; + let Some(text) = convert_text(raw) else { + drawings += 1; + continue; + }; + let name = get("name").map(str::trim).filter(|s| !s.is_empty()); + doc.cues.push(Cue { start, end, text, speaker: name.map(str::to_string), ..Default::default() }); + } + _ => {} + } + } + if !saw_events { + return Err(Error::NotFormat("ASS")); + } + if drawings > 0 { + doc.warnings.push(format!("{drawings} vector drawing line(s) were skipped")); + } + Ok(doc) +} + +fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 8); + let mut rest = text; + while !rest.is_empty() { + if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\i1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\i0}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\b1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\b0}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\u1}"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { + out.push_str("{\\u0}"); + rest = r; + } else if let Some(c) = rest.chars().next() { + match c { + '\n' => out.push_str("\\N"), + '{' => out.push('\u{ff5b}'), + '}' => out.push('\u{ff5d}'), + '\u{a0}' => out.push_str("\\h"), + c => out.push(c), + } + rest = &rest[c.len_utf8()..]; + } + } + out +} + +pub fn write(doc: &Document) -> String { + let mut out = String::from( + "[Script Info]\n; Written by craft-captions\nScriptType: v4.00+\nWrapStyle: 0\nScaledBorderAndShadow: yes\nPlayResX: 384\nPlayResY: 288\n\n\ + [V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n\ + Style: Default,Arial,16,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1\n\n\ + [Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n", + ); + for c in &doc.cues { + // A comma in the Name field would shift the columns; the other fields are fixed text. + let name = c.speaker.as_deref().unwrap_or("").replace([',', '\n'], " "); + out.push_str(&format!("Dialogue: 0,{},{},Default,{},0,0,0,,{}\n", format_time(c.start), format_time(c.end), name, escape(&c.text))); + } + out +} diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 0ba9f2ba5..e8a492722 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -4,7 +4,7 @@ //! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`, //! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc) //! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU -//! Tech 3264) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a +//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a //! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252 //! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank //! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `` @@ -32,6 +32,7 @@ #[doc = include_str!("../README.md")] struct ReadmeExamples; +pub mod ass; pub mod cea608; pub mod mcc; pub mod scc; @@ -69,10 +70,12 @@ pub enum Format { Ttml, /// DFXP (TTML1). Dfxp, + /// Advanced SubStation Alpha (also reads SubStation Alpha). + Ass, } impl Format { - pub const ALL: [Format; 7] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp]; + pub const ALL: [Format; 8] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp, Format::Ass]; pub fn name(self) -> &'static str { match self { Format::Srt => "SubRip (SRT)", @@ -82,6 +85,7 @@ impl Format { Format::Stl => "EBU STL", Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", + Format::Ass => "Advanced SubStation Alpha (ASS)", } } pub fn extension(self) -> &'static str { @@ -93,6 +97,7 @@ impl Format { Format::Stl => "stl", Format::Ttml => "ttml", Format::Dfxp => "dfxp", + Format::Ass => "ass", } } pub fn from_name(s: &str) -> Option { @@ -104,6 +109,7 @@ impl Format { "stl" | "ebu-stl" | "ebustl" | "ebu" => Some(Format::Stl), "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), + "ass" | "ssa" => Some(Format::Ass), _ => None, } } @@ -251,6 +257,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("File Format=MacCaption_MCC") { return Some(Format::Mcc); } + if head.starts_with("[Script Info]") { + return Some(Format::Ass); + } let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) @@ -262,7 +271,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml") => None, + Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa") => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -296,6 +305,7 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Scc => scc::parse(&text), Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), + Format::Ass => ass::parse(&text), Format::Stl => stl::parse(bytes), } } @@ -333,6 +343,7 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Stl => stl::write(doc, opts.rate, opts.program), Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), + Format::Ass => ass::write(doc).into_bytes(), } } diff --git a/crates/captions/tests/it/ass.rs b/crates/captions/tests/it/ass.rs new file mode 100644 index 000000000..de5d43167 --- /dev/null +++ b/crates/captions/tests/it/ass.rs @@ -0,0 +1,113 @@ +//! SubStation Alpha / Advanced SubStation Alpha: reading, writing, and ffmpeg as the reference +//! (oracle; skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_captions::{Cue, Document, Format, Tick, WriteOptions, detect, parse, write}; +use std::process::Command; + +const T: i64 = craft_captions::TICKS_PER_SECOND; + +fn cs(n: i64) -> Tick { + Tick(n * (T / 100)) +} + +const SAMPLE: &str = "\u{feff}[Script Info]\n; a comment\nTitle: Test\nScriptType: v4.00+\n\n[V4+ Styles]\nFormat: Name, Fontname\nStyle: Default,Arial\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nComment: 0,0:00:00.00,0:00:01.00,Default,,0,0,0,,not a cue\nDialogue: 0,0:00:01.50,0:00:03.25,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}\\Nsecond {\\b1}line{\\b0}\nDialogue: 0,1:02:03.04,1:02:04.5,Default,,0,0,0,,{\\pos(10,20)\\c&H0000FF&}Red\\hspace\\nsoft\nDialogue: 0,0:00:09.00,0:00:10.00,Default,,0,0,0,,{\\p1}m 0 0 l 100 0 100 100{\\p0}\n"; + +#[test] +fn reads_dialogue_lines_with_commas_overrides_and_line_breaks() { + let doc = parse(SAMPLE.as_bytes(), Format::Ass).unwrap(); + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, cs(150)); + assert_eq!(doc.cues[0].end, cs(325)); + assert_eq!(doc.cues[0].text, "Hello, world\nsecond line"); + assert_eq!(doc.cues[0].speaker.as_deref(), Some("Bob")); + // 1:02:03.04, a one-digit fraction, an override block dropped, \h and \n. + assert_eq!(doc.cues[1].start, Tick((3600 + 120 + 3) * T + 4 * (T / 100))); + assert_eq!(doc.cues[1].end, Tick((3600 + 120 + 4) * T + T / 2)); + assert_eq!(doc.cues[1].text, "Red\u{a0}space soft"); + assert!(doc.warnings.iter().any(|w| w.contains("vector drawing")), "{:?}", doc.warnings); +} + +#[test] +fn ssa_v4_files_read_through_their_own_format_line() { + let ssa = "[Script Info]\nScriptType: v4.00\n\n[V4 Styles]\nFormat: Name\n\n[Events]\nFormat: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: Marked=0,0:00:01.00,0:00:02.00,*Default,,0000,0000,0000,,Old style\n"; + let doc = parse(ssa.as_bytes(), Format::Ass).unwrap(); + assert_eq!((doc.cues[0].start, doc.cues[0].end, doc.cues[0].text.as_str()), (cs(100), cs(200), "Old style")); +} + +#[test] +fn write_then_read_keeps_times_text_and_speaker() { + let cues = vec![ + Cue { start: cs(100), end: cs(250), text: "Line one\nline two".into(), speaker: Some("Ann".into()), ..Default::default() }, + Cue { + start: Tick(7200 * T + 99 * (T / 100)), + end: Tick(7203 * T), + text: "bold and under {braces}".into(), + ..Default::default() + }, + ]; + let doc = Document { cues, ..Default::default() }; + let bytes = write(&doc, Format::Ass, WriteOptions::default()); + assert_eq!(detect(&bytes, Some("ass")), Some(Format::Ass)); + let back = parse(&bytes, Format::Ass).unwrap(); + assert_eq!(back.cues[0], doc.cues[0]); + assert_eq!(back.cues[1].start, doc.cues[1].start); + // Braces are written full-width, as ASS reads `{` as the start of an override block. + assert_eq!(back.cues[1].text, "bold and under \u{ff5b}braces\u{ff5d}"); +} + +#[test] +fn files_without_an_events_section_are_not_ass() { + assert!(parse(b"[Script Info]\nTitle: x\n", Format::Ass).is_err()); + assert!(parse(b"hello", Format::Ass).is_err()); + assert_eq!(detect(b"hello", Some("ass")), None); +} + +#[test] +fn bad_lines_are_skipped_with_a_warning() { + let text = "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: 0,garbage,0:00:02.00,Default,,0,0,0,,x\nDialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,ok\n"; + let doc = parse(text.as_bytes(), Format::Ass).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.warnings.len(), 1); +} + +fn ffmpeg_run(ff: &std::path::Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +const SRT: &str = "1\n00:00:01,500 --> 00:00:03,250\nHello, world\nsecond line\n\n2\n00:00:04,000 --> 00:00:05,990\nPlain, with a comma\n\n3\n01:00:00,010 --> 01:00:02,999\nUnder and italic both\n"; + +#[test] +fn we_read_what_ffmpeg_writes() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("captions_ass"); + let (srt, ass) = (dir.join("in.srt"), dir.join("ffmpeg.ass")); + std::fs::write(&srt, SRT).expect("write"); + ffmpeg_run(&ff, &["-i", srt.to_str().expect("path"), ass.to_str().expect("path")]); + let from_ass = parse(&std::fs::read(&ass).expect("read"), Format::Ass).expect("parse ass"); + let from_srt = parse(SRT.as_bytes(), Format::Srt).expect("parse srt"); + assert_eq!(from_ass.cues.len(), from_srt.cues.len()); + for (a, s) in from_ass.cues.iter().zip(&from_srt.cues) { + // ASS times are centiseconds; the SRT ones round to them. + assert_eq!(a.start, cs((s.start.0 + T / 200) / (T / 100)), "start of {:?}", s.text); + assert_eq!(a.end, cs((s.end.0 + T / 200) / (T / 100)), "end of {:?}", s.text); + assert_eq!(a.text, s.text); + } +} + +#[test] +fn ffmpeg_reads_what_we_write() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("captions_ass"); + let doc = parse(SRT.as_bytes(), Format::Srt).expect("parse srt"); + let (ass, srt) = (dir.join("ours.ass"), dir.join("back.srt")); + std::fs::write(&ass, write(&doc, Format::Ass, WriteOptions::default())).expect("write"); + ffmpeg_run(&ff, &["-i", ass.to_str().expect("path"), srt.to_str().expect("path")]); + let theirs = parse(&std::fs::read(&srt).expect("read"), Format::Srt).expect("parse back"); + assert_eq!(theirs.cues.len(), doc.cues.len()); + for (t, d) in theirs.cues.iter().zip(&doc.cues) { + assert_eq!(t.start, cs((d.start.0 + T / 200) / (T / 100))); + assert_eq!(t.end, cs((d.end.0 + T / 200) / (T / 100))); + assert_eq!(t.text, d.text, "text of the cue at {:?}", d.start); + } +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index 16f8fcbb6..be03d2855 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -1,3 +1,4 @@ +mod ass; mod limits; mod literal_roundtrips; mod mcc_708_timing; From d3024d0cd5af26edecc04b0a68689436952bd116 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 11:05:39 -0500 Subject: [PATCH 2/2] fix(captions): preserve literal ASS escapes and normalize newlines --- crates/captions/src/ass.rs | 11 ++++++++--- crates/captions/tests/it/ass.rs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/captions/src/ass.rs b/crates/captions/src/ass.rs index 3c907c829..2d0a1df55 100644 --- a/crates/captions/src/ass.rs +++ b/crates/captions/src/ass.rs @@ -191,7 +191,10 @@ fn escape(text: &str) -> String { let mut out = String::with_capacity(text.len() + 8); let mut rest = text; while !rest.is_empty() { - if let Some(r) = rest.strip_prefix("") { + if let Some(r) = rest.strip_prefix("\r\n") { + out.push_str("\\N"); + rest = r; + } else if let Some(r) = rest.strip_prefix("") { out.push_str("{\\i1}"); rest = r; } else if let Some(r) = rest.strip_prefix("") { @@ -211,7 +214,9 @@ fn escape(text: &str) -> String { rest = r; } else if let Some(c) = rest.chars().next() { match c { - '\n' => out.push_str("\\N"), + '\n' | '\r' => out.push_str("\\N"), + // Empty override block separates a literal slash from N/n/h. + '\\' => out.push_str("\\{}"), '{' => out.push('\u{ff5b}'), '}' => out.push('\u{ff5d}'), '\u{a0}' => out.push_str("\\h"), @@ -232,7 +237,7 @@ pub fn write(doc: &Document) -> String { ); for c in &doc.cues { // A comma in the Name field would shift the columns; the other fields are fixed text. - let name = c.speaker.as_deref().unwrap_or("").replace([',', '\n'], " "); + let name = c.speaker.as_deref().unwrap_or("").replace([',', '\n', '\r'], " "); out.push_str(&format!("Dialogue: 0,{},{},Default,{},0,0,0,,{}\n", format_time(c.start), format_time(c.end), name, escape(&c.text))); } out diff --git a/crates/captions/tests/it/ass.rs b/crates/captions/tests/it/ass.rs index de5d43167..fb6d4e01e 100644 --- a/crates/captions/tests/it/ass.rs +++ b/crates/captions/tests/it/ass.rs @@ -99,7 +99,8 @@ fn we_read_what_ffmpeg_writes() { fn ffmpeg_reads_what_we_write() { let Some(ff) = craft_media_testkit::ffmpeg() else { return }; let dir = craft_media_testkit::fixture_subdir("captions_ass"); - let doc = parse(SRT.as_bytes(), Format::Srt).expect("parse srt"); + let mut doc = parse(SRT.as_bytes(), Format::Srt).expect("parse srt"); + doc.cues.push(Cue { start: cs(400_000), end: cs(400_100), text: r"C:\New\notes\hello and \N \n \h".into(), ..Default::default() }); let (ass, srt) = (dir.join("ours.ass"), dir.join("back.srt")); std::fs::write(&ass, write(&doc, Format::Ass, WriteOptions::default())).expect("write"); ffmpeg_run(&ff, &["-i", ass.to_str().expect("path"), srt.to_str().expect("path")]); @@ -111,3 +112,31 @@ fn ffmpeg_reads_what_we_write() { assert_eq!(t.text, d.text, "text of the cue at {:?}", d.start); } } + +#[test] +fn literal_backslashes_survive_ass_round_trip() { + let text = r"C:\New\notes\hello and \N \n \h"; + let doc = Document { cues: vec![Cue { start: cs(100), end: cs(200), text: text.into(), ..Default::default() }], ..Default::default() }; + let bytes = write(&doc, Format::Ass, WriteOptions::default()); + assert_eq!(parse(&bytes, Format::Ass).unwrap().cues[0].text, text); +} + +#[test] +fn carriage_returns_cannot_create_dialogue_records() { + let doc = Document { + cues: vec![Cue { + start: cs(100), + end: cs(200), + text: "first\rsecond\r\nthird".into(), + speaker: Some("Ann\rOther".into()), + ..Default::default() + }], + ..Default::default() + }; + let bytes = write(&doc, Format::Ass, WriteOptions::default()); + assert!(!bytes.contains(&b'\r')); + let back = parse(&bytes, Format::Ass).unwrap(); + assert_eq!(back.cues.len(), 1); + assert_eq!(back.cues[0].text, "first\nsecond\nthird"); + assert_eq!(back.cues[0].speaker.as_deref(), Some("Ann Other")); +}