Merge pull request #1747 from el-j/feat/captions-legacy-text

craft-captions: MicroDVD, MPL2, SubViewer 2, VPlayer and SAMI subtitles
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 11:36:34 +01:00
commit 3b09a644a5
11 files changed
+1472 -7

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-captions"
description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML/IMSC1/DFXP readers and writers with exact time, and CEA-608/708 coding"
description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL, ASS, TTML/IMSC1/DFXP and the legacy text formats (MicroDVD, MPL2, SubViewer, VPlayer, SAMI) readers and writers with exact time, and CEA-608/708 coding"
version.workspace = true
edition.workspace = true
license.workspace = true
+5
View File
@@ -60,6 +60,11 @@ lists at most 20 characters per stream.
| TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `<p>` per cue, `<br/>`, styled `<span>`s for `<i>` / `<b>` / `<u>`, `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 `<i>`, `<b>`, `<u>`); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. |
| MicroDVD `.sub` | yes | yes | `{first}{last}text` with frame numbers; the `{1}{1}fps` line or 23.976 fps. `\|` breaks a line; `{y:i,b,u}` and `{c:$BBGGRR}` style a line (capital `Y` / `C`: the rest of the cue too); other controls are dropped. Writing always names the rate (`WriteOptions::rate`, 23.976 by default) and styles only a line that `<i>`, `<b>` or `<u>` wraps whole. |
| MPL2 `.mpl` | yes | yes | `[start][end]text` in tenths of a second; `\|` breaks a line, a leading `/` makes it italic. |
| SubViewer 2 `.sbv` (also `.sub`) | yes | yes | `start,end` in hundredths of a second after the `[INFORMATION]` header; `[br]` breaks a line. Text only; no styles. |
| VPlayer `.vpl` (also `.txt`) | yes | yes | `HH:MM:SS[.cc]=text` (`:` or a space also separate); only start times, a caption lasts to the next line (empty text clears), four seconds for the last. Text only. |
| SAMI `.smi` | yes | yes | `<SYNC Start=ms>` blocks, `&nbsp;` clears; `<br>`, `<i>`, `<b>`, `<u>`, `<font color>` kept; first language class only. |
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
+74 -5
View File
@@ -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), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a
//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`), the legacy text formats [MicroDVD](microdvd) (`.sub`), [MPL2](mpl2) (`.mpl`), [SubViewer 2](subviewer) (`.sub`), [VPlayer](vplayer) (`.vpl`) and [SAMI](sami) (`.smi`) 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, `<v Speaker>`
@@ -36,17 +36,22 @@ pub mod ass;
pub mod cea608;
pub mod jacosub;
pub mod mcc;
pub mod microdvd;
#[cfg(feature = "mov-text")]
pub mod mov_text;
pub mod mpl2;
pub mod pjs;
pub mod realtext;
pub mod sami;
pub mod scc;
pub mod srt;
pub mod stl;
pub mod subviewer;
mod text;
/// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields.
pub use craft_timeline::time;
pub mod ttml;
pub mod vplayer;
pub mod vtt;
pub use text::{decode_entities, entity_at, plain_text};
@@ -77,6 +82,16 @@ pub enum Format {
Dfxp,
/// Advanced SubStation Alpha (also reads SubStation Alpha).
Ass,
/// MicroDVD (frame-numbered text).
MicroDvd,
/// MPL2 (times in tenths of a second).
Mpl2,
/// SubViewer 2.
SubViewer,
/// VPlayer (start times only).
VPlayer,
/// SAMI (HTML-like).
Sami,
/// Phoenix Japanimation Society (PJS) subtitles.
Pjs,
/// RealText streaming timed text markup.
@@ -86,7 +101,7 @@ pub enum Format {
}
impl Format {
pub const ALL: [Format; 11] = [
pub const ALL: [Format; 16] = [
Format::Srt,
Format::WebVtt,
Format::Scc,
@@ -95,6 +110,11 @@ impl Format {
Format::Ttml,
Format::Dfxp,
Format::Ass,
Format::MicroDvd,
Format::Mpl2,
Format::SubViewer,
Format::VPlayer,
Format::Sami,
Format::Pjs,
Format::RealText,
Format::JacoSub,
@@ -109,6 +129,11 @@ impl Format {
Format::Ttml => "TTML (IMSC1)",
Format::Dfxp => "DFXP (TTML1)",
Format::Ass => "Advanced SubStation Alpha (ASS)",
Format::MicroDvd => "MicroDVD",
Format::Mpl2 => "MPL2",
Format::SubViewer => "SubViewer 2",
Format::VPlayer => "VPlayer",
Format::Sami => "SAMI",
Format::Pjs => "PJS",
Format::RealText => "RealText",
Format::JacoSub => "JACOsub",
@@ -124,6 +149,12 @@ impl Format {
Format::Ttml => "ttml",
Format::Dfxp => "dfxp",
Format::Ass => "ass",
Format::MicroDvd => "sub",
Format::Mpl2 => "mpl",
// SubViewer files are `.sub` too, as MicroDVD ones are; `.sbv` tells the two apart.
Format::SubViewer => "sbv",
Format::VPlayer => "vpl",
Format::Sami => "smi",
Format::Pjs => "pjs",
Format::RealText => "rt",
Format::JacoSub => "jss",
@@ -139,6 +170,11 @@ impl Format {
"ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml),
"dfxp" => Some(Format::Dfxp),
"ass" | "ssa" => Some(Format::Ass),
"sub" | "microdvd" => Some(Format::MicroDvd),
"mpl" | "mpl2" => Some(Format::Mpl2),
"subviewer" | "sbv" => Some(Format::SubViewer),
"vplayer" | "vpl" => Some(Format::VPlayer),
"smi" | "sami" => Some(Format::Sami),
"pjs" => Some(Format::Pjs),
"rt" | "realtext" => Some(Format::RealText),
"jss" | "js" | "jacosub" => Some(Format::JacoSub),
@@ -292,28 +328,51 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option<Format> {
if head.starts_with("[Script Info]") {
return Some(Format::Ass);
}
if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("<sami"))
&& head.as_bytes().get(5).is_some_and(|&b| b.is_ascii_whitespace() || b == b'>' || b == b'/')
{
return Some(Format::Sami);
}
if subviewer::is_header(head) {
return Some(Format::SubViewer);
}
if realtext::is_realtext(head) {
return Some(Format::RealText);
}
let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase());
let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some());
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| microdvd::is_cue(l)) {
return Some(Format::MicroDvd);
}
if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) {
return Some(Format::Mpl2);
}
if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) {
return Some(Format::SubViewer);
}
if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) {
return Some(Format::VPlayer);
}
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("<tt ") || head.contains("<tt>") || head.contains(":tt ")))
&& (head.contains("ns/ttml") || head.contains("ttaf1"))
{
let legacy = head.contains("ttaf1") || head.contains("dfxp");
return Some(if ext.as_deref() == Some("dfxp") || (legacy && ext.as_deref() != Some("ttml")) { Format::Dfxp } else { Format::Ttml });
}
let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some());
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" | "pjs" | "rt" | "jss" | "js") => None,
Some(
"srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami" | "pjs" | "rt"
| "jss" | "js",
) => None,
_ if has_arrow_timing => Some(Format::Srt),
_ => None,
}
@@ -348,6 +407,11 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result<Document> {
Format::Mcc => mcc::parse(&text),
Format::Ttml | Format::Dfxp => ttml::parse(&text),
Format::Ass => ass::parse(&text),
Format::MicroDvd => microdvd::parse(&text),
Format::Mpl2 => mpl2::parse(&text),
Format::SubViewer => subviewer::parse(&text),
Format::VPlayer => vplayer::parse(&text),
Format::Sami => sami::parse(&text),
Format::Pjs => pjs::parse(&text),
Format::RealText => realtext::parse(&text),
Format::JacoSub => jacosub::parse(&text),
@@ -389,6 +453,11 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec<u8> {
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::MicroDvd => microdvd::write(doc, opts.rate).into_bytes(),
Format::Mpl2 => mpl2::write(doc).into_bytes(),
Format::SubViewer => subviewer::write(doc).into_bytes(),
Format::VPlayer => vplayer::write(doc).into_bytes(),
Format::Sami => sami::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(),
+241
View File
@@ -0,0 +1,241 @@
//! MicroDVD (`.sub`): frame-numbered text.
//!
//! ```text
//! {1}{1}23.976
//! {24}{72}First line|{y:i}second line in italics
//! ```
//!
//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` or `{0}{0}`
//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other
//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together)
//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}`
//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …)
//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when
//! `<i>`, `<b>` or `<u>` wraps all of it; other tags are dropped, and `{`, `}` and `|` in the
//! text become the full-width `{`, `}` and `|`.
use crate::text::{LineStyle, escape_markup, number, plain_text, whole_line_style, wrap_style};
use crate::time::FrameRate;
use crate::{Cue, Document, Error, Result};
/// The frame rate of a file that does not name one.
pub const DEFAULT_RATE: FrameRate = FrameRate::FPS_23_976;
/// `{a}{b}text` as its parts.
fn split_cue(line: &str) -> Option<(i64, i64, &str)> {
let rest = line.strip_prefix('{')?;
let (a, rest) = rest.split_once('}')?;
let rest = rest.strip_prefix('{')?;
let (b, text) = rest.split_once('}')?;
Some((number(a.trim())?, number(b.trim())?, text))
}
/// Whether `line` is a `{first}{last}text` cue line.
pub(crate) fn is_cue(line: &str) -> bool {
split_cue(line).is_some()
}
/// The frame rate a header cue's text names.
fn header_rate(text: &str) -> Option<FrameRate> {
let fps: f64 = text.trim().parse().ok()?;
(fps.is_finite() && (1.0..=1000.0).contains(&fps)).then(|| FrameRate::from_f64(fps))
}
/// A `$BBGGRR` colour as `#rrggbb`.
fn colour(value: &str) -> Option<String> {
let hex = value.trim().strip_prefix('$')?;
if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let (b, rest) = hex.split_at(2);
let (g, r) = rest.split_at(2);
Some(format!("#{}{}{}", r.to_ascii_lowercase(), g.to_ascii_lowercase(), b.to_ascii_lowercase()))
}
/// What the styling controls of a cue's lines set.
#[derive(Default)]
struct Sticky {
style: LineStyle,
colour: Option<String>,
}
/// The text of one line without its `{x:…}` controls, and the controls in order.
fn split_controls(line: &str) -> (String, Vec<(char, String)>) {
let mut text = String::new();
let mut controls = Vec::new();
let mut rest = line;
while let Some(open) = rest.find('{') {
text.push_str(rest.get(..open).unwrap_or(""));
let after = rest.get(open + 1..).unwrap_or("");
// Check the fixed-size control prefix before scanning its body. Invalid opening
// braces must not repeatedly scan the same suffix for a closing brace.
let name = after.as_bytes().first().copied().filter(u8::is_ascii_alphabetic);
if let Some(name) = name.filter(|_| after.as_bytes().get(1) == Some(&b':')) {
if let Some((body, tail)) = after.get(2..).and_then(|s| s.split_once('}')) {
controls.push((char::from(name), body.to_string()));
rest = tail;
} else {
// No later control can close either: preserve the entire remaining text.
text.push('{');
text.push_str(after);
rest = "";
break;
}
} else {
text.push('{');
rest = after;
}
}
text.push_str(rest);
(text, controls)
}
fn apply_style(value: &str, style: &mut LineStyle) {
for flag in value.split([',', ' ', '/']) {
match flag.trim().to_ascii_lowercase().as_str() {
"i" => style.italic = true,
"b" => style.bold = true,
"u" => style.underline = true,
_ => {}
}
}
}
fn cue_text(raw: &str) -> String {
let mut sticky = Sticky::default();
let mut lines = Vec::new();
for line in raw.split('|') {
let (text, controls) = split_controls(line);
let mut style = sticky.style;
let mut line_colour = sticky.colour.clone();
for (name, value) in controls {
match name {
'y' => apply_style(&value, &mut style),
'Y' => {
apply_style(&value, &mut style);
apply_style(&value, &mut sticky.style);
}
'c' => line_colour = colour(&value).or(line_colour),
'C' => {
line_colour = colour(&value).or(line_colour);
sticky.colour = line_colour.clone();
}
_ => {}
}
}
let text = text.trim();
if text.is_empty() {
continue;
}
lines.push(wrap_style(style, line_colour.as_deref(), &escape_markup(text)));
}
lines.join("\n")
}
pub fn parse(text: &str) -> Result<Document> {
let mut rows = Vec::new();
let mut rate = DEFAULT_RATE;
let mut has_rate_line = false;
let mut doc = Document::default();
for (n, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() {
continue;
}
match split_cue(line) {
Some((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => {
rate = header_rate(t).unwrap_or(rate);
has_rate_line = true;
}
Some(row) => rows.push(row),
None => doc.warnings.push(format!("line {}: not a MicroDVD cue, skipped", n + 1)),
}
}
if rows.is_empty() && !has_rate_line && !text.trim().is_empty() {
return Err(Error::NotFormat("MicroDVD"));
}
for (first, last, raw) in rows {
let (start, end) = (rate.tick_of(first), rate.tick_of(last));
let text = cue_text(raw);
if end <= start || text.is_empty() {
doc.warnings.push(format!("the cue at frame {first} is empty or ends at frame {last}; skipped"));
continue;
}
doc.cues.push(Cue { start, end, text, ..Default::default() });
}
Ok(doc)
}
/// Write `doc` with its frames counted at `rate` (None: [`DEFAULT_RATE`]).
pub fn write(doc: &Document, rate: Option<FrameRate>) -> String {
let rate = rate.map_or(DEFAULT_RATE, FrameRate::sane);
let mut out = format!("{{1}}{{1}}{:.3}\n", rate.as_f64());
let frame = |t| rate.frame_at(rate.snap_nearest(t)).max(0);
for c in &doc.cues {
let first = frame(c.start);
let last = frame(c.end).max(first.saturating_add(1));
let mut lines = Vec::new();
for line in c.text.lines() {
let (style, inner) = whole_line_style(line);
let text = plain_text(inner).trim().replace('{', "\u{ff5b}").replace('}', "\u{ff5d}").replace('|', "\u{ff5c}");
if text.is_empty() {
continue;
}
let mut flags = Vec::new();
for (on, f) in [(style.italic, "i"), (style.bold, "b"), (style.underline, "u")] {
if on {
flags.push(f);
}
}
lines.push(if flags.is_empty() { text } else { format!("{{y:{}}}{text}", flags.join(",")) });
}
if lines.is_empty() {
continue;
}
out.push_str(&format!("{{{first}}}{{{last}}}{}\n", lines.join("|")));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn controls_style_lines() {
assert_eq!(cue_text("{y:i,b}x|plain"), "<i><b>x</b></i>\nplain");
assert_eq!(cue_text("{Y:i}a|b"), "<i>a</i>\n<i>b</i>");
assert_eq!(cue_text("{c:$0000ff}red"), "<font color=\"#ff0000\">red</font>");
assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a &amp; b {x");
}
#[test]
fn malformed_controls_inside_valid_cues_are_preserved() {
for raw in ["{".repeat(32_768), "{y:".repeat(16_384)] {
let doc = parse(&format!("{{0}}{{25}}{raw}")).unwrap();
assert_eq!(doc.cues.len(), 1);
assert_eq!(doc.cues[0].text, raw);
}
assert_eq!(cue_text("{{y:i}hello"), "<i>{hello</i>");
assert_eq!(cue_text("{xx:no}{y:b}hello"), "<b>{xx:no}hello</b>");
}
#[test]
fn rate_header() {
let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap();
assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25));
let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap();
assert_eq!(d.cues.len(), 2);
assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25));
assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50));
assert_eq!(d.cues[1].text, "29.97");
let d = parse("{25}{50}x\n").unwrap();
assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25));
}
#[test]
fn rejects_other_text() {
assert!(parse("hello\nworld\n").is_err());
assert!(parse("").unwrap().cues.is_empty());
}
}
+114
View File
@@ -0,0 +1,114 @@
//! MPL2 (`.txt`, `.mpl`): times in tenths of a second.
//!
//! ```text
//! [10][35]First line|/second line in italics
//! ```
//!
//! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the
//! start of a line makes it italic. Writing marks a line italic only when `<i>` wraps all of it,
//! drops other tags, rounds times to a tenth of a second, writes `|` in text as `|`, and writes
//! a leading `/` in non-italic text as `/`.
use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style};
use crate::{Cue, Document, Error, Result};
/// `[a][b]text` as its parts.
pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> {
let rest = line.strip_prefix('[')?;
let (a, rest) = rest.split_once(']')?;
let rest = rest.strip_prefix('[')?;
let (b, text) = rest.split_once(']')?;
Some((number(a.trim())?, number(b.trim())?, text))
}
pub fn parse(text: &str) -> Result<Document> {
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((a, b, raw)) = split_cue(line) else {
doc.warnings.push(format!("line {}: not an MPL2 cue, skipped", n + 1));
continue;
};
found = true;
let mut lines = Vec::new();
for l in raw.split('|') {
let (italic, l) = match l.trim().strip_prefix('/') {
Some(r) => (true, r.trim().to_string()),
None => {
let t = l.trim();
if let Some(rest) = t.strip_prefix('\u{ff0f}') { (false, format!("/{rest}")) } else { (false, t.to_string()) }
}
};
if !l.is_empty() {
lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(&l)));
}
}
let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.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("MPL2"));
}
Ok(doc)
}
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 mut lines = Vec::new();
for line in c.text.lines() {
let (style, inner) = whole_line_style(line);
let mut text = plain_text(inner).trim().replace('|', "\u{ff5c}");
if !style.italic && text.starts_with('/') {
text.replace_range(..1, "\u{ff0f}");
}
if !text.is_empty() {
lines.push(if style.italic { format!("/{text}") } else { text });
}
}
if !lines.is_empty() {
out.push_str(&format!("[{start}][{end}]{}\n", lines.join("|")));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn italics_and_lines() {
let d = parse("[10][35]Hello|/italic\n").unwrap();
assert_eq!(d.cues[0].text, "Hello\n<i>italic</i>");
assert_eq!(d.cues[0].end, ms_to_tick(3500));
}
#[test]
fn rejects_other_text() {
assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err());
}
#[test]
fn non_italic_leading_slash_roundtrip() {
let doc = Document {
cues: vec![Cue { start: ms_to_tick(1000), end: ms_to_tick(2000), text: "/not italic\n<i>/italic</i>".into(), ..Default::default() }],
..Default::default()
};
let written = write(&doc);
assert_eq!(written, "[10][20]/not italic|//italic\n");
let parsed = parse(&written).unwrap();
assert_eq!(parsed.cues[0].text, "/not italic\n<i>/italic</i>");
}
}
+323
View File
@@ -0,0 +1,323 @@
//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions.
//!
//! ```text
//! <SAMI><BODY>
//! <SYNC Start=1000><P Class=ENCC>First line<br>second line
//! <SYNC Start=3500><P Class=ENCC>&nbsp;
//! </BODY></SAMI>
//! ```
//!
//! A `<SYNC Start=ms>` block shows its text from that millisecond until the next block; a block
//! holding only `&nbsp;` clears the screen. The last caption lasts four seconds if nothing clears
//! it. `<br>` starts a new line; `<i>`, `<b>`, `<u>` and `<font color>` are kept, other tags
//! dropped; `&amp;`, `&lt;`, `&gt;`, `&nbsp;` and numeric references are read. A file can hold
//! several language classes (`<P Class=ENCC>`, `<P Class=KRCC>`): the first one named is read and
//! the others skipped with a warning. Writing makes one `ENCC` class, an `&nbsp;` block where a
//! caption ends before the next starts, and rounds to milliseconds.
use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, sequential, tick_to_ms};
use crate::time::Tick;
use crate::{Cue, Document, Error, Result};
/// The value of attribute `name` in the tag text `tag` (quotes optional).
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let lower = tag.to_ascii_lowercase();
let mut from = 0;
while let Some(i) = lower.get(from..).and_then(|r| r.find(name)) {
let at = from + i;
from = at + name.len();
let before_ok = at == 0 || lower.as_bytes().get(at - 1).is_some_and(|b| !b.is_ascii_alphanumeric());
let rest = tag.get(from..).unwrap_or("").trim_start();
let Some(rest) = rest.strip_prefix('=').filter(|_| before_ok) else { continue };
let rest = rest.trim_start();
return Some(match rest.chars().next() {
Some(q @ ('"' | '\'')) => {
let inner = rest.get(1..).unwrap_or("");
inner.split(q).next().unwrap_or("")
}
_ => rest.split(|c: char| c.is_whitespace() || c == '>').next().unwrap_or(""),
});
}
None
}
/// A numeric character reference body (`#65`, `#x41`) as its character.
fn numeric_reference(body: &str) -> Option<char> {
let digits = body.strip_prefix('#')?;
let code = match digits.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => digits.parse().ok()?,
};
char::from_u32(code).filter(|c| !c.is_control() || *c == '\n')
}
/// HTML text as cue text: entities the cue model keeps stay, numeric ones are decoded, a stray
/// `&` is escaped, whitespace runs collapse.
fn text_run(s: &str) -> String {
let mut out = String::new();
let mut rest = s;
let mut space = false;
while let Some(c) = rest.chars().next() {
let mut advance = c.len_utf8();
if c.is_whitespace() && c != '\u{a0}' {
space = true;
rest = rest.get(advance..).unwrap_or("");
continue;
}
if space {
out.push(' ');
}
space = false;
if c == '&' {
if let Some((_, len)) = crate::entity_at(rest) {
out.push_str(rest.get(..len).unwrap_or(""));
advance = len;
} else if let Some(body) = rest.get(1..).and_then(|r| {
// Numeric entities have at most eight body bytes. Never scan the
// unbounded remainder again for each malformed ampersand.
let end = r.bytes().take(9).position(|b| b == b';')?;
r.get(..end)
}) && let Some(ch) = numeric_reference(body)
{
out.push_str(&escape_markup(&ch.to_string()));
advance = body.len() + 2;
} else {
out.push_str("&amp;");
}
} else {
out.push_str(&escape_markup(&c.to_string()));
}
rest = rest.get(advance..).unwrap_or("");
}
if space {
out.push(' ');
}
out
}
/// One `<SYNC>` block's body as (class, cue text) segments, one per `<P>`.
fn segments(body: &str) -> Vec<(String, String)> {
let mut segs: Vec<(String, String)> = vec![(String::new(), String::new())];
let mut open_fonts = 0usize;
let mut rest = body;
while !rest.is_empty() {
let Some(lt) = rest.find('<') else {
if let Some(last) = segs.last_mut() {
last.1.push_str(&text_run(rest));
}
break;
};
if let Some(last) = segs.last_mut() {
last.1.push_str(&text_run(rest.get(..lt).unwrap_or("")));
}
let after = rest.get(lt + 1..).unwrap_or("");
let Some(gt) = after.find('>') else {
if let Some(last) = segs.last_mut() {
last.1.push_str("&lt;");
last.1.push_str(&text_run(after));
}
break;
};
let tag = after.get(..gt).unwrap_or("");
rest = after.get(gt + 1..).unwrap_or("");
let closing = tag.starts_with('/');
let name: String = tag.trim_start_matches('/').chars().take_while(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
let Some(last) = segs.last_mut() else { continue };
match (name.as_str(), closing) {
("br", _) => last.1.push('\n'),
("p", false) => segs.push((attribute(tag, "class").unwrap_or("").to_string(), String::new())),
("i" | "b" | "u", false) => last.1.push_str(&format!("<{name}>")),
("i" | "b" | "u", true) => last.1.push_str(&format!("</{name}>")),
("font", false) => {
if let Some(c) = attribute(tag, "color").filter(|c| c.len() <= 20 && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#')) {
open_fonts += 1;
last.1.push_str(&format!("<font color=\"{c}\">"));
}
}
("font", true) if open_fonts > 0 => {
open_fonts -= 1;
last.1.push_str("</font>");
}
_ => {}
}
}
segs
}
/// A caption text without the whitespace and non-breaking spaces round its lines.
fn tidy(text: &str) -> String {
let lines: Vec<String> = text
.split('\n')
.map(|l| l.replace("&nbsp;", " ").trim().to_string())
.filter(|l| !l.is_empty() && !crate::plain_text(l).trim().is_empty())
.collect();
lines.join("\n")
}
pub fn parse(text: &str) -> Result<Document> {
let lower = text.to_ascii_lowercase();
let mut starts: Vec<usize> = Vec::new();
let mut from = 0;
while let Some(i) = lower.get(from..).and_then(|r| r.find("<sync")) {
starts.push(from + i);
from += i + 5;
}
if starts.is_empty() {
return if text.trim().is_empty() || lower.contains("<sami") { Ok(Document::default()) } else { Err(Error::NotFormat("SAMI")) };
}
let mut doc = Document::default();
let mut class: Option<String> = None;
let mut skipped_class = false;
let mut syncs: Vec<(Tick, String)> = Vec::new();
for (k, &at) in starts.iter().enumerate() {
let stop = starts.get(k + 1).copied().unwrap_or(text.len());
let chunk = text.get(at..stop).unwrap_or("");
let chunk = match chunk.to_ascii_lowercase().find("</body") {
Some(i) => chunk.get(..i).unwrap_or(chunk),
None => chunk,
};
let Some((tag, body)) = chunk.get(1..).and_then(|c| c.split_once('>')) else { continue };
let Some(start) = attribute(tag, "start").and_then(|v| number(v.trim())) else {
doc.warnings.push("a <SYNC> without a Start time was skipped".to_string());
continue;
};
let mut shown = String::new();
for (cls, seg) in segments(body) {
if class.is_none() && !cls.is_empty() {
class = Some(cls.to_ascii_lowercase());
}
if class.as_deref().is_none_or(|c| c == cls.to_ascii_lowercase() || cls.is_empty()) {
shown.push_str(&seg);
} else {
skipped_class = true;
}
}
syncs.push((ms_to_tick(start), tidy(&shown)));
}
if skipped_class {
doc.warnings.push("the file has other language classes; only the first was read".to_string());
}
syncs.sort_by_key(|(t, _)| *t);
for (i, (start, text)) in syncs.iter().enumerate() {
if text.is_empty() {
continue;
}
let end = syncs.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next);
if end <= *start {
doc.warnings.push("two captions start at the same time; the first was skipped".to_string());
continue;
}
doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() });
}
Ok(doc)
}
pub fn write(doc: &Document) -> String {
let cues = sequential(doc);
let mut out = String::from(
"<SAMI>\n<HEAD>\n<TITLE></TITLE>\n<STYLE TYPE=\"text/css\">\n<!--\nP { margin-left: 8pt; margin-right: 8pt; text-align: center; font-size: 20pt; color: white; }\n.ENCC { Name: English; lang: en-US; SAMIType: CC; }\n-->\n</STYLE>\n</HEAD>\n<BODY>\n",
);
let active_cues: Vec<(&Cue, Vec<&str>)> = cues
.iter()
.filter_map(|c| {
let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
if lines.is_empty() { None } else { Some((c, lines)) }
})
.collect();
let mut resolved_cues: Vec<(i64, i64, &Vec<&str>)> = Vec::with_capacity(active_cues.len());
let mut prev_end = 0i64;
for (c, lines) in &active_cues {
let start_ms = tick_to_ms(c.start).max(prev_end);
let end_ms = tick_to_ms(c.end).max(start_ms + 1);
prev_end = end_ms;
resolved_cues.push((start_ms, end_ms, lines));
}
for (i, &(start_ms, end_ms, lines)) in resolved_cues.iter().enumerate() {
out.push_str(&format!("<SYNC Start={start_ms}><P Class=ENCC>{}\n", lines.join("<br>")));
let next_start = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s);
if next_start != Some(end_ms) {
out.push_str(&format!("<SYNC Start={end_ms}><P Class=ENCC>&nbsp;\n"));
}
}
out.push_str("</BODY>\n</SAMI>\n");
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blocks_clear_and_style() {
let d = parse("<SAMI><BODY>\n<SYNC Start=1000><P Class=ENCC>Hello<br>world &amp; <i>you</i>\n<SYNC Start=3500><P Class=ENCC>&nbsp;\n<SYNC Start=4000><P Class=ENCC>x &#65; y\n</BODY></SAMI>").unwrap();
assert_eq!(d.cues.len(), 2);
assert_eq!(d.cues[0].text, "Hello\nworld &amp; <i>you</i>");
assert_eq!(d.cues[0].end, ms_to_tick(3500));
assert_eq!(d.cues[1].text, "x A y");
assert_eq!(d.cues[1].end, last_cue_end(ms_to_tick(4000)));
}
#[test]
fn malformed_entities_inside_valid_cues_are_bounded() {
let raw = "&".repeat(32_768);
let doc = parse(&format!("<SAMI><SYNC Start=0><P>{raw}<SYNC Start=1000><P>&nbsp;")).unwrap();
assert_eq!(doc.cues.len(), 1);
assert_eq!(doc.cues[0].text, "&amp;".repeat(32_768));
assert_eq!(text_run("&#0000065; &#00000065; &#x41; &é;"), "A &amp;#00000065; A &amp;é;");
}
#[test]
fn only_the_first_class_is_read() {
let d = parse("<SAMI><BODY><SYNC Start=1000><P Class=ENCC>en<P Class=KRCC>kr<SYNC Start=2000><P Class=ENCC>&nbsp;</BODY></SAMI>").unwrap();
assert_eq!(d.cues.len(), 1);
assert_eq!(d.cues[0].text, "en");
assert_eq!(d.warnings.len(), 1);
}
#[test]
fn rejects_other_text() {
assert!(parse("hello").is_err());
}
#[test]
fn short_duration_and_empty_cues() {
let doc = Document {
cues: vec![
Cue { start: ms_to_tick(100), end: Tick(ms_to_tick(100).0 + 1), text: "Brief".into(), ..Default::default() },
Cue { start: ms_to_tick(101), end: ms_to_tick(200), text: " ".into(), ..Default::default() },
Cue { start: ms_to_tick(500), end: ms_to_tick(600), text: "After gap".into(), ..Default::default() },
],
..Default::default()
};
let written = write(&doc);
assert!(written.contains("<SYNC Start=100><P Class=ENCC>Brief\n<SYNC Start=101><P Class=ENCC>&nbsp;\n"));
let parsed = parse(&written).unwrap();
assert_eq!(parsed.cues.len(), 2);
assert_eq!(parsed.cues[0].start, ms_to_tick(100));
assert_eq!(parsed.cues[0].end, ms_to_tick(101));
assert_eq!(parsed.cues[1].start, ms_to_tick(500));
}
#[test]
fn adjacent_short_cues_do_not_collide_after_rounding() {
let t100 = ms_to_tick(100);
let t100_1 = Tick(t100.0 + crate::TICKS_PER_MS / 10);
let t200 = ms_to_tick(200);
let doc = Document {
cues: vec![
Cue { start: t100, end: t100_1, text: "First".into(), ..Default::default() },
Cue { start: t100_1, end: t200, text: "Second".into(), ..Default::default() },
],
..Default::default()
};
let encoded = write(&doc);
let back = parse(&encoded).unwrap();
assert_eq!(back.cues.len(), 2);
assert_eq!(back.cues[0].text, "First");
assert_eq!(tick_to_ms(back.cues[0].start), 100);
assert_eq!(tick_to_ms(back.cues[0].end), 101);
assert_eq!(back.cues[1].text, "Second");
assert_eq!(tick_to_ms(back.cues[1].start), 101);
assert_eq!(tick_to_ms(back.cues[1].end), 200);
}
}
+198
View File
@@ -0,0 +1,198 @@
//! SubViewer 2 (`.sub`): hundredths of a second, with an information header.
//!
//! ```text
//! [INFORMATION]
//! [TITLE]…
//! [END INFORMATION]
//! [SUBTITLE]
//! 00:00:01.00,00:00:03.50
//! First line[br]second line
//!
//! ```
//!
//! Reading skips the bracketed header lines and takes every `start,end` time line as a cue whose
//! text runs to the next blank line; `[br]` starts a new line. Fractions of one to three digits
//! are accepted. Writing adds a minimal header, rounds times to a hundredth of a second, drops
//! tags, writes `[br]` inside text as `[br]`, and writes `,` in lines that match the timing
//! syntax as `,`.
use crate::text::{escape_markup, plain_lines};
use crate::time::{TICKS_PER_SECOND, Tick};
use crate::{Cue, Document, Error, Result, parse_clock};
const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100;
/// Returns true if `head` begins with a genuine SubViewer header structure.
pub(crate) fn is_header(head: &str) -> bool {
let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty());
match lines.next() {
Some("[INFORMATION]") => lines.any(|l| {
l == "[SUBTITLE]"
|| l == "[END INFORMATION]"
|| l.starts_with("[TITLE")
|| l.starts_with("[AUTHOR")
|| l.starts_with("[SOURCE")
|| l.starts_with("[FILEPATH")
|| l.starts_with("[DELAY")
|| l.starts_with("[CD TRACK")
|| l.starts_with("[COMMENT")
|| (l.starts_with('[') && l.contains(']'))
}),
Some("[SUBTITLE]") => true,
_ => false,
}
}
/// `h:mm:ss.cc,h:mm:ss.cc` as its two times.
pub(crate) fn parse_timing(line: &str) -> Option<(Tick, Tick)> {
let (a, b) = line.trim().split_once(',')?;
let ok = |s: &str| s.contains(':') && s.contains('.');
if !ok(a) || !ok(b) {
return None;
}
Some((parse_clock(a)?, parse_clock(b)?))
}
/// Split `s` at each `[br]`, whatever its case.
fn split_br(s: &str) -> Vec<&str> {
let lower = s.to_ascii_lowercase();
let mut parts = Vec::new();
let mut from = 0;
while let Some(i) = lower.get(from..).and_then(|r| r.find("[br]")) {
parts.push(s.get(from..from + i).unwrap_or(""));
from += i + 4;
}
parts.push(s.get(from..).unwrap_or(""));
parts
}
pub fn parse(text: &str) -> Result<Document> {
let lines: Vec<&str> = text.lines().collect();
let mut doc = Document::default();
let mut found = false;
let mut i = 0;
while i < lines.len() {
let Some((start, end)) = lines.get(i).and_then(|l| parse_timing(l)) else {
i += 1;
continue;
};
found = true;
i += 1;
let mut out: Vec<String> = Vec::new();
while let Some(l) = lines.get(i).filter(|l| !l.trim().is_empty()) {
if parse_timing(l).is_some() {
break;
}
out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup));
i += 1;
}
if end <= start || out.is_empty() {
doc.warnings.push(format!("the cue at line {i} is empty or ends before it starts; skipped"));
continue;
}
doc.cues.push(Cue { start, end, text: out.join("\n"), ..Default::default() });
}
let has_header = text.contains("[INFORMATION]") || text.contains("[SUBTITLE]");
if !found && !has_header && !text.trim().is_empty() {
return Err(Error::NotFormat("SubViewer"));
}
Ok(doc)
}
fn cs(t: Tick) -> u64 {
((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as u64
}
fn clock(cs: u64) -> String {
format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100)
}
pub fn write(doc: &Document) -> String {
let mut out = String::from(
"[INFORMATION]\n[TITLE]\n[AUTHOR]\n[SOURCE]\n[PRG]\n[FILEPATH]\n[DELAY]0\n[CD TRACK]0\n[COMMENT]\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]no,[SIZE]18,[FONT]Arial\n",
);
for c in &doc.cues {
let lines = plain_lines(&c.text);
if lines.is_empty() {
continue;
}
let start_cs = cs(c.start);
let end_cs = cs(c.end).max(start_cs + 1);
out.push_str(&format!("{},{}\n", clock(start_cs), clock(end_cs)));
let lines: Vec<String> = lines
.into_iter()
.map(|mut l| {
if parse_timing(&l).is_some() {
l = l.replacen(',', "\u{ff0c}", 1);
}
l.replace("[br]", "\u{ff3b}br\u{ff3d}")
.replace("[BR]", "\u{ff3b}BR\u{ff3d}")
.replace("[Br]", "\u{ff3b}Br\u{ff3d}")
.replace("[bR]", "\u{ff3b}bR\u{ff3d}")
})
.collect();
out.push_str(&lines.join("[br]"));
out.push_str("\n\n");
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_and_breaks() {
let d = parse("[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:03.50\nHello[BR]world\n\n").unwrap();
assert_eq!(d.cues[0].text, "Hello\nworld");
assert_eq!(d.cues[0].end, crate::text::ms_to_tick(3500));
}
#[test]
fn writer_escapes_every_case_of_literal_break_tokens() {
let doc = Document {
cues: vec![Cue { start: Tick(0), end: crate::text::ms_to_tick(1000), text: "a[br]b[BR]c[Br]d[bR]é".into(), ..Default::default() }],
..Default::default()
};
let decoded = parse(&write(&doc)).unwrap();
assert_eq!(decoded.cues[0].text, "a[br]b[BR]c[Br]d[bR]é");
}
#[test]
fn rejects_other_text() {
assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err());
}
#[test]
fn centisecond_rounding_without_double_rounding_error() {
// 1.0046s is 255_184_473_600 ticks (at 254_016_000_000 ticks/sec).
// Direct rounding to hundredths gives 100cs (00:00:01.00).
// Double-rounding through ms gives 1005ms -> 101cs (00:00:01.01).
let t = Tick(255_184_473_600);
assert_eq!(clock(cs(t)), "00:00:01.00");
}
#[test]
fn timing_shaped_text_escaped_and_roundtripped() {
let doc = Document {
cues: vec![
Cue { start: Tick(TICKS_PER_SECOND), end: Tick(3 * TICKS_PER_SECOND), text: "00:00:01.00,00:00:02.00".into(), ..Default::default() },
Cue { start: Tick(4 * TICKS_PER_SECOND), end: Tick(5 * TICKS_PER_SECOND), text: "Second cue".into(), ..Default::default() },
],
..Default::default()
};
let written = write(&doc);
assert!(written.contains("00:00:01.00,00:00:02.00"));
let parsed = parse(&written).unwrap();
assert_eq!(parsed.cues.len(), 2);
assert_eq!(parsed.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00");
assert_eq!(parsed.cues[1].text, "Second cue");
}
#[test]
fn literal_fullwidth_comma_preserved_on_read() {
let raw = "[INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:02.00\n00:00:01.00\u{ff0c}00:00:02.00\n\n";
let doc = parse(raw).unwrap();
assert_eq!(doc.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00");
}
}
+57 -1
View File
@@ -85,8 +85,8 @@ pub fn plain_text(s: &str) -> String {
out
}
use crate::TICKS_PER_MS;
use crate::time::{TICKS_PER_SECOND, Tick};
use crate::{Cue, Document, TICKS_PER_MS};
/// How long the last cue of a format that gives only start times lasts: such a file says when a
/// caption appears, and the next one ends it.
@@ -131,6 +131,62 @@ pub(crate) fn plain_lines(text: &str) -> Vec<String> {
text.lines().map(plain_text).map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect()
}
/// The style a whole line of cue text carries: `<i>`, `<b>` and `<u>` around all of it.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub(crate) struct LineStyle {
pub italic: bool,
pub bold: bool,
pub underline: bool,
}
/// The style that wraps the whole of `line`, and the line without it. `<i>a</i> b <i>c</i>` is not
/// italic as a whole.
pub(crate) fn whole_line_style(line: &str) -> (LineStyle, &str) {
let mut style = LineStyle::default();
let mut rest = line.trim();
loop {
let mut changed = false;
for (open, close, flag) in [("<i>", "</i>", 0), ("<b>", "</b>", 1), ("<u>", "</u>", 2)] {
if let Some(inner) = rest.strip_prefix(open).and_then(|r| r.strip_suffix(close))
&& !inner.contains(open)
&& !inner.contains(close)
{
match flag {
0 => style.italic = true,
1 => style.bold = true,
_ => style.underline = true,
}
rest = inner.trim();
changed = true;
}
}
if !changed {
return (style, rest);
}
}
}
/// Cue text from a line's style and its (already escaped) text.
pub(crate) fn wrap_style(style: LineStyle, color: Option<&str>, text: &str) -> String {
let mut out = text.to_string();
for (on, tag) in [(style.underline, "u"), (style.bold, "b"), (style.italic, "i")] {
if on {
out = format!("<{tag}>{out}</{tag}>");
}
}
match color {
Some(c) => format!("<font color=\"{c}\">{out}</font>"),
None => out,
}
}
/// The cues of `doc` in time order with no overlaps, for a format that holds one caption at a time.
pub(crate) fn sequential(doc: &Document) -> Vec<Cue> {
let mut copy = Document { cues: doc.cues.clone(), ..Default::default() };
copy.normalize();
copy.cues
}
#[cfg(test)]
mod tests {
use super::*;
+206
View File
@@ -0,0 +1,206 @@
//! VPlayer (`.txt`, `.vpl`): one start time per caption.
//!
//! ```text
//! 00:00:01.00=First line|second line
//! 00:00:04.00=
//! ```
//!
//! A line is `HH:MM:SS`, an optional `.cc` fraction, one of `:`, `=` or a space, and the text; `|`
//! starts a new line. The file gives only when each caption appears: it stays until the next
//! line, whose empty text clears it. The last caption lasts four seconds if no line ends it.
//! Writing puts a clearing line where a caption ends before the next one starts, drops tags,
//! rounds to a hundredth of a second and writes `|` in text as `|`.
use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential};
use crate::time::{TICKS_PER_SECOND, Tick};
use crate::{Cue, Document, Error, Result};
const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100;
/// `HH:MM:SS[.cc]` then a separator and text: the time and the text.
pub(crate) fn split_line(line: &str) -> Option<(Tick, &str)> {
let mut parts = line.splitn(3, ':');
let h = number(parts.next()?)?;
let m = number(parts.next()?)?;
let tail = parts.next()?;
let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
let s = number(tail.get(..digits)?)?;
let mut rest = tail.get(digits..)?;
let mut ms = 0;
if let Some(frac) = rest.strip_prefix('.') {
let n = frac.bytes().take_while(u8::is_ascii_digit).count().min(3);
let f = frac.get(..n).filter(|f| !f.is_empty())?;
ms = number(f)? * 10_i64.pow(3 - n as u32);
rest = frac.get(n..)?;
// further digits of a long fraction are below a millisecond
rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
}
if m >= 60 || s >= 60 || h > 9999 {
return None;
}
let text = rest.strip_prefix([':', '=', ' '])?;
Some((ms_to_tick(((h * 60 + m) * 60 + s) * 1000 + ms), text))
}
pub fn parse(text: &str) -> Result<Document> {
let mut doc = Document::default();
let mut starts: Vec<(Tick, String)> = Vec::new();
for (n, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
match split_line(line.trim()) {
Some((t, raw)) => {
let lines: Vec<String> = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect();
starts.push((t, lines.join("\n")));
}
None => doc.warnings.push(format!("line {}: not a VPlayer line, skipped", n + 1)),
}
}
if starts.is_empty() && !text.trim().is_empty() {
return Err(Error::NotFormat("VPlayer"));
}
for (i, (start, text)) in starts.iter().enumerate() {
if text.is_empty() {
continue;
}
let end = starts.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next);
if end <= *start {
doc.warnings.push("a caption is followed by a line at the same time; skipped".to_string());
continue;
}
doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() });
}
Ok(doc)
}
fn cs(t: Tick) -> i64 {
((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as i64
}
fn clock(cs: i64) -> String {
format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100)
}
pub fn write(doc: &Document) -> String {
let cues = sequential(doc);
let mut out = String::new();
let active_cues: Vec<(&Cue, Vec<String>)> = cues
.iter()
.filter_map(|c| {
let lines = plain_lines(&c.text);
if lines.is_empty() {
None
} else {
let lines = lines.into_iter().map(|l| l.replace('|', "\u{ff5c}")).collect();
Some((c, lines))
}
})
.collect();
let mut resolved_cues: Vec<(i64, i64, &Vec<String>)> = Vec::with_capacity(active_cues.len());
let mut prev_end = 0i64;
for (c, lines) in &active_cues {
let start_cs = cs(c.start).max(prev_end);
let end_cs = cs(c.end).max(start_cs + 1);
prev_end = end_cs;
resolved_cues.push((start_cs, end_cs, lines));
}
for (i, &(start_cs, end_cs, lines)) in resolved_cues.iter().enumerate() {
out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|")));
let next_start_cs = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s);
if next_start_cs != Some(end_cs) {
out.push_str(&format!("{}=\n", clock(end_cs)));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_duration_cue_preserves_positive_duration_on_write_and_read() {
let mut doc = Document::default();
// A cue from 0 to 1 ms collapses to 00:00:00.00 under centisecond rounding.
doc.cues.push(Cue { start: ms_to_tick(0), end: ms_to_tick(1), text: "Short".to_string(), ..Default::default() });
let written = write(&doc);
assert_eq!(written, "00:00:00.00=Short\n00:00:00.01=\n");
let parsed = parse(&written).unwrap();
assert_eq!(parsed.cues.len(), 1);
assert_eq!(parsed.cues[0].text, "Short");
assert_eq!(parsed.cues[0].start, ms_to_tick(0));
assert_eq!(parsed.cues[0].end, ms_to_tick(10));
}
#[test]
fn adjacent_short_cues_do_not_collide_after_rounding() {
let doc = Document {
cues: vec![
Cue { start: ms_to_tick(1000), end: ms_to_tick(1001), text: "First".to_string(), ..Default::default() },
Cue { start: ms_to_tick(1001), end: ms_to_tick(1020), text: "Second".to_string(), ..Default::default() },
],
..Default::default()
};
let written = write(&doc);
assert_eq!(written, "00:00:01.00=First\n00:00:01.01=Second\n00:00:01.02=\n");
let parsed = parse(&written).unwrap();
assert_eq!(parsed.cues.len(), 2);
assert_eq!(parsed.cues[0].text, "First");
assert_eq!(parsed.cues[0].start, ms_to_tick(1000));
assert_eq!(parsed.cues[0].end, ms_to_tick(1010));
assert_eq!(parsed.cues[1].text, "Second");
assert_eq!(parsed.cues[1].start, ms_to_tick(1010));
assert_eq!(parsed.cues[1].end, ms_to_tick(1020));
}
#[test]
fn separators_and_ends() {
let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap();
assert_eq!(d.cues.len(), 2);
assert_eq!(d.cues[0].text, "Hello\nworld");
assert_eq!(d.cues[0].end, ms_to_tick(4500));
assert_eq!(d.cues[1].end, ms_to_tick(9000));
}
#[test]
fn rejects_other_text() {
assert!(parse("hello\n").is_err());
assert!(parse("00:00:01,000 --> 00:00:02,000\n").is_err());
}
#[test]
fn empty_cue_skipped_and_numerical_timestamp_order() {
let doc = Document {
cues: vec![
Cue {
start: Tick(99 * 3600 * TICKS_PER_SECOND),
end: Tick(99 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND),
text: "At 99h".into(),
..Default::default()
},
Cue {
start: Tick(99 * 3600 * TICKS_PER_SECOND + 3 * TICKS_PER_SECOND),
end: Tick(99 * 3600 * TICKS_PER_SECOND + 4 * TICKS_PER_SECOND),
text: " ".into(),
..Default::default()
},
Cue {
start: Tick(100 * 3600 * TICKS_PER_SECOND),
end: Tick(100 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND),
text: "At 100h".into(),
..Default::default()
},
],
..Default::default()
};
let written = write(&doc);
assert_eq!(written, "99:00:00.00=At 99h\n99:00:02.00=\n100:00:00.00=At 100h\n100:00:02.00=\n");
let parsed = parse(&written).unwrap();
assert_eq!(parsed.cues.len(), 2);
assert_eq!(parsed.cues[0].text, "At 99h");
assert_eq!(parsed.cues[1].text, "At 100h");
}
}
+252
View File
@@ -0,0 +1,252 @@
//! The legacy text formats (MicroDVD, MPL2, SubViewer 2, VPlayer, SAMI): reading, writing, and
//! ffmpeg as the reference (oracle; skipped when ffmpeg is absent, a failure with
//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
use craft_captions::time::FrameRate;
use craft_captions::{Cue, Document, Format, TICKS_PER_SECOND, Tick, WriteOptions, detect, parse, plain_text, write};
use std::process::Command;
const T: i64 = TICKS_PER_SECOND;
const MS: i64 = T / 1000;
fn ms(v: i64) -> Tick {
Tick(v * MS)
}
/// The five formats, with the ffmpeg format name each is read and written through.
const FORMATS: [(Format, &str, &str); 5] = [
(Format::MicroDvd, "microdvd", "sub"),
(Format::Mpl2, "mpl2", "txt"),
(Format::SubViewer, "subviewer", "sbv"),
(Format::VPlayer, "vplayer", "txt"),
(Format::Sami, "sami", "smi"),
];
const MICRODVD: &str = "{1}{1}23.976\n{24}{72}Hello|{y:i}second bold\n{100}{150}{c:$0000ff}red\n{200}{250}a & b < c\n";
const MPL2: &str = "[10][35]Hello|/italic\n[40][60]plain\n[70][90]/a|/b\n";
const SUBVIEWER: &str = "[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]bd,[SIZE]18,[FONT]Arial\n00:00:01.00,00:00:03.50\nHello[br]world\n\n00:00:04.00,00:00:05.00\nplain\n";
const VPLAYER: &str = "00:00:01.00=Hello|world\n00:00:04.00=\n00:00:05:plain\n00:00:09 later\n";
const SAMI: &str = "<SAMI>\n<HEAD><TITLE>x</TITLE></HEAD>\n<BODY>\n<SYNC Start=1000><P Class=ENCC>Hello<br>world\n<SYNC Start=3500><P Class=ENCC>&nbsp;\n<SYNC Start=4000><P Class=ENCC><i>plain</i> &amp; more\n<SYNC Start=5000><P Class=ENCC>&nbsp;\n</BODY>\n</SAMI>\n";
fn samples() -> [(Format, &'static str); 5] {
[(Format::MicroDvd, MICRODVD), (Format::Mpl2, MPL2), (Format::SubViewer, SUBVIEWER), (Format::VPlayer, VPLAYER), (Format::Sami, SAMI)]
}
fn 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));
}
/// What ffmpeg reads from `bytes` as `ffmpeg_format`, as cues.
fn ffmpeg_reads(ff: &std::path::Path, name: &str, ffmpeg_format: &str, ext: &str, bytes: &[u8]) -> Document {
let dir = craft_media_testkit::fixture_subdir("captions_legacy");
let (input, out) = (dir.join(format!("{name}.{ext}")), dir.join(format!("{name}.srt")));
std::fs::write(&input, bytes).expect("write");
run(ff, &["-f", ffmpeg_format, "-i", input.to_str().expect("path"), out.to_str().expect("path")]);
parse(&std::fs::read(&out).expect("read"), Format::Srt).expect("parse ffmpeg's srt")
}
/// The lines of a cue's text as plain text, tags and entities gone.
fn plain(c: &Cue) -> String {
c.text.lines().map(|l| plain_text(l).trim().to_string()).collect::<Vec<_>>().join("\n")
}
#[test]
fn we_read_what_ffmpeg_reads() {
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
for (format, text) in samples() {
let (_, name, ext) = FORMATS.iter().copied().find(|f| f.0 == format).expect("format");
let ours = parse(text.as_bytes(), format).expect("parse");
let theirs = ffmpeg_reads(&ff, &format!("read_{name}"), name, ext, text.as_bytes());
assert_eq!(ours.cues.len(), theirs.cues.len(), "{format:?}: {:?} against {:?}", ours.cues, theirs.cues);
for (i, (o, t)) in ours.cues.iter().zip(&theirs.cues).enumerate() {
// ffmpeg gives a last caption of a start-only format no end (an enormous one).
let last = i + 1 == ours.cues.len();
let open_ended = matches!(format, Format::VPlayer | Format::Sami) && last;
assert!((o.start.0 - t.start.0).abs() <= MS, "{format:?} start of {:?}: {:?} against {:?}", o.text, o.start, t.start);
if !open_ended {
assert!((o.end.0 - t.end.0).abs() <= MS, "{format:?} end of {:?}: {:?} against {:?}", o.text, o.end, t.end);
}
assert_eq!(plain(o), plain(t), "{format:?} text of the cue at {:?}", o.start);
}
}
}
fn sample_document() -> Document {
let cue = |a: i64, b: i64, text: &str| Cue { start: ms(a), end: ms(b), text: text.into(), ..Default::default() };
Document {
cues: vec![
cue(1000, 3500, "Hello\n<i>second line</i>"),
cue(3500, 5000, "straight after, with &amp; and &lt;"),
cue(7000, 9000, "after a gap [br] { } |"),
cue(3_600_000, 3_601_500, "an hour in"),
],
..Default::default()
}
}
#[test]
fn ffmpeg_reads_what_we_write() {
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
// ffmpeg's own readers mangle the look-alike characters a writer uses for what a format cannot hold,
// so the cue that has those is left out here (write_then_read covers it).
let mut doc = sample_document();
doc.cues[2].text = "after a gap".into();
for (format, name, ext) in FORMATS {
let bytes = write(&doc, format, WriteOptions::default());
let theirs = ffmpeg_reads(&ff, &format!("write_{name}"), name, ext, &bytes);
assert_eq!(theirs.cues.len(), doc.cues.len(), "{format:?}: {:?}", String::from_utf8_lossy(&bytes));
for (t, d) in theirs.cues.iter().zip(&doc.cues) {
let tolerance = if format == Format::MicroDvd { 45 * MS } else { 10 * MS };
assert!((t.start.0 - d.start.0).abs() <= tolerance, "{format:?} start of {:?}: {:?}", d.text, t.start);
// the characters a format cannot hold are written as look-alikes: compare without them
let bare = |c: &Cue| {
plain(c)
.replace('\u{ff3b}', "[")
.replace('\u{ff3d}', "]")
.replace("[br]", "")
.replace(['{', '}', '|', '\u{ff5b}', '\u{ff5d}', '\u{ff5c}'], "")
.replace(" ", " ")
};
assert_eq!(bare(t), bare(d), "{format:?}");
}
}
}
#[test]
fn write_then_read_keeps_times_and_text() {
let doc = sample_document();
for (format, _, _) in FORMATS {
let bytes = write(&doc, format, WriteOptions::default());
let back = parse(&bytes, format).unwrap_or_else(|e| panic!("{format:?}: {e}"));
assert_eq!(back.cues.len(), doc.cues.len(), "{format:?}");
let tolerance = match format {
Format::MicroDvd => 25 * MS,
Format::Mpl2 => 50 * MS,
_ => 5 * MS,
};
for (b, d) in back.cues.iter().zip(&doc.cues) {
assert!((b.start.0 - d.start.0).abs() <= tolerance, "{format:?} start {:?} against {:?}", b.start, d.start);
assert!((b.end.0 - d.end.0).abs() <= tolerance, "{format:?} end {:?} against {:?}", b.end, d.end);
}
assert_eq!(back.cues[0].text.lines().count(), 2, "{format:?} keeps the line break");
assert_eq!(plain(&back.cues[1]), "straight after, with & and <", "{format:?}");
}
}
#[test]
fn styles_survive_where_the_format_has_them() {
let doc = Document {
cues: vec![Cue { start: ms(0), end: ms(2000), text: "plain\n<i>slanted</i>".into(), ..Default::default() }],
..Default::default()
};
for format in [Format::MicroDvd, Format::Mpl2] {
let back = parse(&write(&doc, format, WriteOptions::default()), format).expect("parse");
assert_eq!(back.cues[0].text, "plain\n<i>slanted</i>", "{format:?}");
}
// SAMI keeps inline tags too.
let doc = Document {
cues: vec![Cue { start: ms(0), end: ms(2000), text: "a <b>bold</b> <i>and</i> <u>more</u>".into(), ..Default::default() }],
..Default::default()
};
assert_eq!(parse(&write(&doc, Format::Sami, WriteOptions::default()), Format::Sami).expect("parse").cues[0].text, doc.cues[0].text);
}
#[test]
fn microdvd_counts_frames_at_the_given_rate() {
let doc = Document { cues: vec![Cue { start: Tick(2 * T), end: Tick(4 * T), text: "x".into(), ..Default::default() }], ..Default::default() };
let bytes = write(&doc, Format::MicroDvd, WriteOptions { rate: Some(FrameRate::FPS_25), ..Default::default() });
assert_eq!(String::from_utf8(bytes.clone()).expect("utf8"), "{1}{1}25.000\n{50}{100}x\n");
let back = parse(&bytes, Format::MicroDvd).expect("parse");
assert_eq!((back.cues[0].start, back.cues[0].end), (Tick(2 * T), Tick(4 * T)));
for header in ["{1}{1}25.000", "{0}{0}25.000"] {
let fixture = format!("{header}\n{{50}}{{100}}First cue\n{{100}}{{150}}23.976\n");
let parsed = parse(fixture.as_bytes(), Format::MicroDvd).expect("parse rate header fixture");
assert_eq!(parsed.cues.len(), 2, "{header}");
assert_eq!((parsed.cues[0].start, parsed.cues[0].end), (Tick(2 * T), Tick(4 * T)), "{header}");
assert_eq!((parsed.cues[1].start, parsed.cues[1].end), (Tick(4 * T), Tick(6 * T)), "{header}");
assert_eq!(parsed.cues[1].text, "23.976", "{header}");
}
}
#[test]
fn detection_finds_each_format() {
for (format, text) in samples() {
assert_eq!(detect(text.as_bytes(), None), Some(format), "{format:?}");
let ext = FORMATS.iter().find(|f| f.0 == format).map(|f| f.2);
assert_eq!(detect(text.as_bytes(), ext), Some(format), "{format:?} with its extension");
}
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nx\n", None), Some(Format::Srt));
// Cue text containing literal SubViewer markers must not hijack SRT detection
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nHere is a [SUBTITLE] tag\n", None), Some(Format::Srt));
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt));
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", None), Some(Format::Srt));
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", Some("srt")), Some(Format::Srt));
// TTML with namespaced sami element is not SAMI
assert_ne!(detect(b"<sami:tt xmlns:sami=\"http://www.w3.org/ns/ttml\"><head></head><body></body></sami:tt>", None), Some(Format::Sami));
// Genuine SubViewer with only [SUBTITLE] header
assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer));
// Genuine SubViewer with long/truncated [TITLE] line
let truncated_sv = format!("[INFORMATION]\n[TITLE]{}", "A".repeat(5000));
assert_eq!(detect(truncated_sv.as_bytes(), None), Some(Format::SubViewer));
assert_eq!(detect(b"just some prose\n", Some("txt")), None);
}
#[test]
fn other_text_is_not_one_of_these_formats() {
for (format, _, _) in FORMATS {
assert!(parse(b"hello there\nthis is not a subtitle file\n", format).is_err(), "{format:?}");
assert!(parse(b"", format).expect("empty").cues.is_empty(), "{format:?}");
}
}
#[test]
fn hostile_input_is_an_error_or_a_warning_never_a_panic() {
let mut inputs: Vec<Vec<u8>> = vec![
"{".repeat(10_000).into_bytes(),
"{1}{1}".repeat(2000).into_bytes(),
"{999999999}{999999999}x\n{1}{99999999999999999999}y\n{5}{3}z\n".into(),
"[999999999][999999999]x\n[1][2".into(),
"99999:99:99.99,99999:99:99.99\nx\n\n00:00:01.00,00:00:00.00\ny\n".into(),
"99999999:00:00=x\n00:60:00=y\n00:00:00.=z\n".into(),
"<sync start=".repeat(5000).into_bytes(),
"<SAMI><SYNC Start=999999999999999999999><P>x<SYNC Start=-5>y<SYNC Start=1><<<<&&&&&#99999999999;&#x;".into(),
format!("<SYNC Start=1>{}", "<font color=\"#fff\">".repeat(10_000)).into_bytes(),
format!("<SYNC Start=1>{}", "<".repeat(10_000)).into_bytes(),
vec![0xff, 0xfe, 0x00, 0xd8, 0x00],
vec![0u8; 1000],
];
// deterministic noise
let mut x = 0x9e37_79b9u32;
for len in [10usize, 100, 1000] {
let alphabet = b"{}[]<>:=,. \n|&#;0123456789abSYNC";
let noise: Vec<u8> = (0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
alphabet[x as usize % alphabet.len()]
})
.collect();
inputs.push(noise);
}
for (format, _, _) in FORMATS {
for input in &inputs {
if let Ok(doc) = parse(input, format) {
// what was read writes and reads again
let again = write(&doc, format, WriteOptions::default());
parse(&again, format).expect("a written file reads back");
}
}
}
}
#[test]
fn the_cue_limit_applies() {
let mut text = String::new();
for i in 0..200 {
text.push_str(&format!("[{}][{}]x\n", i * 10, i * 10 + 5));
}
assert_eq!(parse(text.as_bytes(), Format::Mpl2).expect("parse").cues.len(), 200);
}
+1
View File
@@ -1,4 +1,5 @@
mod ass;
mod legacy_text;
mod limits;
mod literal_roundtrips;
mod mcc_708_timing;