From cfad8f0bcca6900ddd88361220fb5ed432ce817e Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 17 Nov 2026 03:30:57 +0100 Subject: [PATCH] craft-captions: PJS, RealText and JACOsub subtitle formats (#1557) (#1788) --- crates/captions/src/jacosub.rs | 242 +++++++++++++++++ crates/captions/src/lib.rs | 50 +++- crates/captions/src/pjs.rs | 102 ++++++++ crates/captions/src/realtext.rs | 247 ++++++++++++++++++ crates/captions/src/text.rs | 46 ++++ crates/captions/tests/it/main.rs | 1 + .../captions/tests/it/pjs_realtext_jacosub.rs | 174 ++++++++++++ 7 files changed, 860 insertions(+), 2 deletions(-) create mode 100644 crates/captions/src/jacosub.rs create mode 100644 crates/captions/src/pjs.rs create mode 100644 crates/captions/src/realtext.rs create mode 100644 crates/captions/tests/it/pjs_realtext_jacosub.rs diff --git a/crates/captions/src/jacosub.rs b/crates/captions/src/jacosub.rs new file mode 100644 index 000000000..30233b6f1 --- /dev/null +++ b/crates/captions/src/jacosub.rs @@ -0,0 +1,242 @@ +//! JACOsub (`.jss`, `.js`): multi-feature scriptable subtitle format. +//! +//! ```text +//! # JACOsub file +//! #TimeRes 100 +//! 0:00:01.00 0:00:03.00 D0 First line\nsecond line +//! ``` +//! +//! Lines beginning with `#` are comments or header directives. Timed caption lines begin with +//! `START STOP [DIRECTIVE] Text`, where timestamps are `H:MM:SS.FF` (or `@units`) relative to +//! the declared `#TimeRes` (default 30). Inside the text, `\n` represents a newline. + +use crate::text::{escape_markup, ms_to_tick, plain_text, tick_to_ms}; +use crate::{Cue, Document, Error, Result}; + +/// Parse a JACOsub timestamp `H:MM:SS.FF` or `@units` into milliseconds. +pub(crate) fn parse_time(s: &str, time_res: i64) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + + if let Some(units_str) = s.strip_prefix('@') { + let units: i64 = units_str.trim().parse().ok()?; + let time_res = if time_res > 0 { time_res } else { 30 }; + return Some(units.saturating_mul(1000) / time_res); + } + + let (h_str, rest) = s.split_once(':')?; + let (m_str, rest) = rest.split_once(':')?; + let (s_str, f_str) = rest.split_once('.')?; + + let h: i64 = h_str.trim().parse().ok()?; + let m: i64 = m_str.trim().parse().ok()?; + let sec: i64 = s_str.trim().parse().ok()?; + let frac: i64 = f_str.trim().parse().ok()?; + + let time_res = if time_res > 0 { time_res } else { 30 }; + let frac_ms = frac.saturating_mul(1000) / time_res; + + let total_secs = h.saturating_mul(3600).saturating_add(m.saturating_mul(60)).saturating_add(sec); + Some(total_secs.saturating_mul(1000).saturating_add(frac_ms)) +} + +/// Format milliseconds into JACOsub timestamp string `H:MM:SS.cc` (at 100 centiseconds/sec). +pub(crate) fn format_time(ms: i64) -> String { + let ms = ms.max(0); + let total_secs = ms / 1000; + let centis = (ms % 1000) / 10; + let hours = total_secs / 3600; + let mins = (total_secs % 3600) / 60; + let secs = total_secs % 60; + + format!("{hours}:{mins:02}:{secs:02}.{centis:02}") +} + +/// Check if a line is a JACOsub timed caption line: `H:MM:SS.FF H:MM:SS.FF ...` or `@units @units ...`. +pub(crate) fn is_timed_line(line: &str) -> bool { + let line = line.trim(); + if line.starts_with('#') { + return false; + } + let mut parts = line.split_whitespace(); + let Some(t0) = parts.next() else { return false }; + let Some(t1) = parts.next() else { return false }; + (t0.contains(':') && t0.contains('.') && t1.contains(':') && t1.contains('.')) || (t0.starts_with('@') && t1.starts_with('@')) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut time_res: i64 = 30; // standard default + let mut shift_ms: i64 = 0; + let mut found = false; + + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + + if let Some(cmd) = line.strip_prefix('#') { + let cmd_lower = cmd.to_ascii_lowercase(); + if cmd_lower.starts_with("timeres") || cmd_lower.starts_with('t') { + let parts: Vec<&str> = cmd.split_whitespace().collect(); + if parts.len() >= 2 + && let Ok(res) = parts[1].parse::() + && res > 0 + { + time_res = res; + } + } else if cmd_lower.starts_with("shift") || cmd_lower.starts_with('s') { + let parts: Vec<&str> = cmd.split_whitespace().collect(); + if parts.len() >= 2 { + let s_val = parts[1].trim(); + let (neg, s_raw) = if let Some(stripped) = s_val.strip_prefix('-') { + (true, stripped) + } else if let Some(stripped) = s_val.strip_prefix('+') { + (false, stripped) + } else { + (false, s_val) + }; + if let Some(ms) = parse_time(s_raw, time_res) { + shift_ms = if neg { -ms } else { ms }; + } + } + } + continue; + } + + if !is_timed_line(line) { + continue; + } + + let mut parts = line.split_whitespace(); + let Some(start_str) = parts.next() else { continue }; + let Some(end_str) = parts.next() else { continue }; + + let start_ms = match parse_time(start_str, time_res) { + Some(ms) => ms.saturating_add(shift_ms).max(0), + None => { + doc.warnings.push(format!("line {}: invalid start timestamp, skipped", n + 1)); + continue; + } + }; + let end_ms = match parse_time(end_str, time_res) { + Some(ms) => ms.saturating_add(shift_ms).max(0), + None => { + doc.warnings.push(format!("line {}: invalid end timestamp, skipped", n + 1)); + continue; + } + }; + + found = true; + + // Skip to after the end timestamp in the original line to preserve exact spaces + let after_end_pos = match line.find(end_str) { + Some(idx) => idx + end_str.len(), + None => continue, + }; + let remainder = &line[after_end_pos..]; + let trimmed_rem = remainder.trim_start(); + + // Check if there is a directive prefix: either [Directive] or a single non-space word starting with D + let text_part = if let Some(stripped) = trimmed_rem.strip_prefix('[') { + match stripped.find(']') { + Some(end_bracket) => stripped[end_bracket + 1..].trim_start(), + None => trimmed_rem, + } + } else if let Some(space_idx) = trimmed_rem.find(' ') { + let first_token = &trimmed_rem[..space_idx]; + if first_token.starts_with('D') && first_token[1..].chars().all(|c| c.is_ascii_digit()) { + trimmed_rem[space_idx + 1..].trim_start() + } else { + trimmed_rem + } + } else { + trimmed_rem + }; + + // Text parsing: `\n` represents newline + let raw_lines: Vec<&str> = text_part.split(r"\n").map(str::trim).filter(|l| !l.is_empty()).collect(); + let lines: Vec = raw_lines.into_iter().map(escape_markup).collect(); + + let start = ms_to_tick(start_ms); + let end = ms_to_tick(end_ms); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("JACOsub")); + } + + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + out.push_str("# JACOsub file\n"); + out.push_str("#TimeRes 100\n\n"); + + for c in &doc.cues { + let start_ms = tick_to_ms(c.start); + let end_ms = tick_to_ms(c.end).max(start_ms + 10); + let raw_lines = plain_text(&c.text); + let lines: Vec<&str> = raw_lines.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + + if !lines.is_empty() { + let text = lines.join(r"\n"); + out.push_str(&format!("{} {} D0 {}\n", format_time(start_ms), format_time(end_ms), text)); + } + } + + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_write_roundtrip() { + let jss = "# JACOsub file\n#TimeRes 100\n\n0:00:01.00 0:00:03.00 D0 First line\\nsecond line\n0:00:04.50 0:00:06.00 D0 Second cue\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(3000)); + assert_eq!(doc.cues[0].text, "First line\nsecond line"); + assert_eq!(doc.cues[1].start, ms_to_tick(4500)); + assert_eq!(doc.cues[1].end, ms_to_tick(6000)); + assert_eq!(doc.cues[1].text, "Second cue"); + + let written = write(&doc); + assert_eq!(written, jss); + } + + #[test] + fn parse_bracketed_directive() { + let jss = "#TimeRes 100\n0:00:01.00 0:00:03.00 [Style1] Bracketed style text\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, "Bracketed style text"); + } + + #[test] + fn negative_shift_under_one_hour() { + let jss = "#TimeRes 100\n#Shift -0:00:01.00\n0:00:02.00 0:00:04.00 D0 Shifted line\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(3000)); + } + + #[test] + fn rejects_non_jacosub() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nHello\n").is_err()); + } +} diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e8a492722..ca99dba43 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -34,7 +34,10 @@ struct ReadmeExamples; pub mod ass; pub mod cea608; +pub mod jacosub; pub mod mcc; +pub mod pjs; +pub mod realtext; pub mod scc; pub mod srt; pub mod stl; @@ -72,10 +75,28 @@ pub enum Format { Dfxp, /// Advanced SubStation Alpha (also reads SubStation Alpha). Ass, + /// Phoenix Japanimation Society (PJS) subtitles. + Pjs, + /// RealText streaming timed text markup. + RealText, + /// JACOsub scriptable subtitles. + JacoSub, } impl Format { - pub const ALL: [Format; 8] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp, Format::Ass]; + pub const ALL: [Format; 11] = [ + Format::Srt, + Format::WebVtt, + Format::Scc, + Format::Mcc, + Format::Stl, + Format::Ttml, + Format::Dfxp, + Format::Ass, + Format::Pjs, + Format::RealText, + Format::JacoSub, + ]; pub fn name(self) -> &'static str { match self { Format::Srt => "SubRip (SRT)", @@ -86,6 +107,9 @@ impl Format { Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", Format::Ass => "Advanced SubStation Alpha (ASS)", + Format::Pjs => "PJS", + Format::RealText => "RealText", + Format::JacoSub => "JACOsub", } } pub fn extension(self) -> &'static str { @@ -98,6 +122,9 @@ impl Format { Format::Ttml => "ttml", Format::Dfxp => "dfxp", Format::Ass => "ass", + Format::Pjs => "pjs", + Format::RealText => "rt", + Format::JacoSub => "jss", } } pub fn from_name(s: &str) -> Option { @@ -110,6 +137,9 @@ impl Format { "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), "ass" | "ssa" => Some(Format::Ass), + "pjs" => Some(Format::Pjs), + "rt" | "realtext" => Some(Format::RealText), + "jss" | "js" | "jacosub" => Some(Format::JacoSub), _ => None, } } @@ -260,6 +290,16 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("[Script Info]") { return Some(Format::Ass); } + if realtext::is_realtext(head) { + return Some(Format::RealText); + } + let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); + if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { + return Some(Format::Pjs); + } + if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) { + return Some(Format::JacoSub); + } 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")) @@ -271,7 +311,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" | "ass" | "ssa") => None, + Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -306,6 +346,9 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), Format::Ass => ass::parse(&text), + Format::Pjs => pjs::parse(&text), + Format::RealText => realtext::parse(&text), + Format::JacoSub => jacosub::parse(&text), Format::Stl => stl::parse(bytes), } } @@ -344,6 +387,9 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { 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(), + Format::Pjs => pjs::write(doc).into_bytes(), + Format::RealText => realtext::write(doc).into_bytes(), + Format::JacoSub => jacosub::write(doc).into_bytes(), } } diff --git a/crates/captions/src/pjs.rs b/crates/captions/src/pjs.rs new file mode 100644 index 000000000..91874941b --- /dev/null +++ b/crates/captions/src/pjs.rs @@ -0,0 +1,102 @@ +//! Phoenix Japanimation Society (PJS) subtitles (`.pjs`): times in tenths of a second. +//! +//! ```text +//! 10,50,"First line" +//! 60,120,"Second line|with break" +//! ``` +//! +//! Lines are comma-separated `start,end,"text"` with times in deciseconds (tenths of a second). +//! Inside the quotes, `|` breaks a line. + +use crate::text::{escape_markup, ms_to_tick, number, plain_lines, tick_to_ms}; +use crate::{Cue, Document, Error, Result}; + +/// `start,end,"text"` as its parts. +pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let (start_str, rest) = line.split_once(',')?; + let (end_str, text_str) = rest.split_once(',')?; + let start = number(start_str.trim())?; + let end = number(end_str.trim())?; + let text = text_str.trim(); + let text = if let Some(stripped) = text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) { stripped } else { text }; + Some((start, end, text)) +} + +/// Parse a PJS subtitle document. +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut found = false; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Some((start_ds, end_ds, raw)) = split_cue(line) else { + doc.warnings.push(format!("line {}: not a PJS cue, skipped", n + 1)); + continue; + }; + found = true; + let mut lines = Vec::new(); + for l in raw.split('|') { + let trimmed = l.trim(); + if !trimmed.is_empty() { + let unquoted = trimmed.replace("\"\"", "\""); + lines.push(escape_markup(&unquoted)); + } + } + let start = ms_to_tick(start_ds.saturating_mul(100)); + let end = ms_to_tick(end_ds.saturating_mul(100)); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("PJS")); + } + Ok(doc) +} + +/// Serialize a document into PJS format. +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + let ds = |t| (tick_to_ms(t) + 50) / 100; + for c in &doc.cues { + let start = ds(c.start); + let end = ds(c.end).max(start + 1); + let lines: Vec = + plain_lines(&c.text).into_iter().map(|l| l.replace('"', "\"\"").replace('|', "|")).filter(|l| !l.is_empty()).collect(); + if !lines.is_empty() { + out.push_str(&format!("{start},{end},\"{}\"\n", lines.join("|"))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_write_roundtrip() { + let pjs = "10,50,\"First line\"\n60,120,\"Second line|with break\"\n130,150,\"Say \"\"Hi\"\"\"\n"; + let doc = parse(pjs).expect("parse"); + assert_eq!(doc.cues.len(), 3); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(5000)); + assert_eq!(doc.cues[0].text, "First line"); + assert_eq!(doc.cues[1].start, ms_to_tick(6000)); + assert_eq!(doc.cues[1].end, ms_to_tick(12000)); + assert_eq!(doc.cues[1].text, "Second line\nwith break"); + assert_eq!(doc.cues[2].text, "Say \"Hi\""); + + let written = write(&doc); + assert_eq!(written, pjs); + } + + #[test] + fn rejects_non_pjs() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nHello\n").is_err()); + } +} diff --git a/crates/captions/src/realtext.rs b/crates/captions/src/realtext.rs new file mode 100644 index 000000000..1c4328a3b --- /dev/null +++ b/crates/captions/src/realtext.rs @@ -0,0 +1,247 @@ +//! RealText (`.rt`): streaming HTML-like timed text markup. +//! +//! ```text +//! +//! +//! ``` +//! +//! RealText documents encapsulate timed text inside a `` container with `