diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml
index 4a4e27520f..7259d7212d 100644
--- a/crates/captions/Cargo.toml
+++ b/crates/captions/Cargo.toml
@@ -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
diff --git a/crates/captions/README.md b/crates/captions/README.md
index b2f6a195f0..4568526750 100644
--- a/crates/captions/README.md
+++ b/crates/captions/README.md
@@ -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): `
` 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. |
+| 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 ``, `` or `` 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 | `` blocks, ` ` clears; `
`, ``, ``, ``, `` 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
diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs
index 612aa6f137..e83b868ce2 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), [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, ``
@@ -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 {
if head.starts_with("[Script Info]") {
return Some(Format::Ass);
}
+ if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("' || 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("") || 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 {
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 {
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(),
diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs
new file mode 100644
index 0000000000..5816373712
--- /dev/null
+++ b/crates/captions/src/microdvd.rs
@@ -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
+//! ``, `` or `` 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 {
+ 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 {
+ 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,
+}
+
+/// 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 {
+ 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) -> 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"), "x\nplain");
+ assert_eq!(cue_text("{Y:i}a|b"), "a\nb");
+ assert_eq!(cue_text("{c:$0000ff}red"), "red");
+ assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & 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"), "{hello");
+ assert_eq!(cue_text("{xx:no}{y:b}hello"), "{xx:no}hello");
+ }
+
+ #[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());
+ }
+}
diff --git a/crates/captions/src/mpl2.rs b/crates/captions/src/mpl2.rs
new file mode 100644
index 0000000000..b7613f073d
--- /dev/null
+++ b/crates/captions/src/mpl2.rs
@@ -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 `` 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 {
+ 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\nitalic");
+ 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/italic".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/italic");
+ }
+}
diff --git a/crates/captions/src/sami.rs b/crates/captions/src/sami.rs
new file mode 100644
index 0000000000..29f8281dd9
--- /dev/null
+++ b/crates/captions/src/sami.rs
@@ -0,0 +1,323 @@
+//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions.
+//!
+//! ```text
+//!
+//! First line
second line
+//!
+//!
+//! ```
+//!
+//! A `` block shows its text from that millisecond until the next block; a block
+//! holding only ` ` clears the screen. The last caption lasts four seconds if nothing clears
+//! it. `
` starts a new line; ``, ``, `` and `` are kept, other tags
+//! dropped; `&`, `<`, `>`, ` ` and numeric references are read. A file can hold
+//! several language classes (``, `
`): the first one named is read and
+//! the others skipped with a warning. Writing makes one `ENCC` class, an ` ` 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 {
+ 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("&");
+ }
+ } else {
+ out.push_str(&escape_markup(&c.to_string()));
+ }
+ rest = rest.get(advance..).unwrap_or("");
+ }
+ if space {
+ out.push(' ');
+ }
+ out
+}
+
+/// One `` block's body as (class, cue text) segments, one per ``.
+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("<");
+ 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::().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", true) if open_fonts > 0 => {
+ open_fonts -= 1;
+ last.1.push_str("");
+ }
+ _ => {}
+ }
+ }
+ segs
+}
+
+/// A caption text without the whitespace and non-breaking spaces round its lines.
+fn tidy(text: &str) -> String {
+ let lines: Vec = text
+ .split('\n')
+ .map(|l| l.replace(" ", " ").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 {
+ let lower = text.to_ascii_lowercase();
+ let mut starts: Vec = Vec::new();
+ let mut from = 0;
+ while let Some(i) = lower.get(from..).and_then(|r| r.find(" = 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("