SPB Git

Repository Public License

subtitle.md 11.3 KB

# Subtitle engine (subtitle) — compatibility

Package Packages/EngineSubtitle, module EngineSubtitle, factory makeEngines(). Pure Swift, no third-party code, no helper process. State on 2026-11-21 (macOS 27.0, arm64): 30 declared paths, 36 tests, all passing (swift test: Test run with 36 tests in 5 suites passed; the parameterised matrix test converts every one of the 30 paths).

# Formats

Format Read Write Time unit in the file
SubRip .srt yes yes millisecond
WebVTT .vtt yes yes millisecond
Advanced SubStation Alpha .ass yes yes centisecond
SubStation Alpha .ssa yes yes centisecond
MicroDVD .sub yes yes frame (needs a frame rate)

Internally every cue has integer-millisecond start and end, a list of text runs with bold / italic / underline / strike-through / colour / font, an optional numpad alignment (1–9) and an optional position in percent of the frame.

# Declared paths

All 20 ordered pairs among the five formats (plain conversion), plus two same-format operations per format. Every path is supported, fidelity structural (the text and timing are kept; the markup is rewritten). Test for all of them: MatrixTests.everyDeclaredPathConvertsAndValidates(path:) — converts a six-cue fixture that exists in the five formats, runs the core's generic validation and the engine's, then re-reads the output and compares start, end and plain text of every cue with the known values.

Source → destination Preserves Limitations shown to the user
vtt, ass, ssa, sub → srt timing, text styles SubRip holds text, timing and simple bold / italic / underline / colour tags only. From ASS/SSA: style definitions, positions, karaoke, effects, drawings and embedded fonts are not carried over. From VTT: positions, regions, STYLE blocks and speaker annotations are not carried over.
srt, ass, ssa, sub → vtt timing, text styles No font tag and no strike-through in WebVTT; colours are written as cue classes with a STYLE block. From ASS/SSA: style definitions, karaoke, effects, drawings, embedded fonts are not carried over; alignment is kept, exact positions are approximated.
srt, vtt, sub → ass / ssa timing, text styles A single default style is written (font, size, resolution are settings). Times are rounded to the centisecond (nearest, halves up). SSA has no underline or strike-through.
ass ↔ ssa timing, text styles Override tags are kept as written, except alignment tags (\an ↔ \a), which are translated; style colours and alignment numbering are translated; SSA has no underline / strike-out / scale / spacing / rotation in styles.
srt, vtt, ass, ssa → sub timing MicroDVD counts frames: times are rounded to the nearest frame of the rate given (23.976 fps assumed otherwise, with a warning). Whole-line styles only; no positions, karaoke or effects.
sub → anything as above Without a {1}{1}fps header or a frame-rate setting, 23.976 fps is assumed to compute times (warning framerate-assumed).
X → X, subtitle.retime timing, text styles Only the timing changes; text and markup are written back as read. ASS/SSA: header, styles, [Fonts] / [Graphics] kept, non-dialogue events (Picture, Sound, Movie, Command) not kept. VTT: NOTE blocks not kept. MicroDVD: rounded to whole frames.
X → X, subtitle.clean timing, text styles Clean-up edits the text; a cue whose text was edited loses markup the model does not hold (kept for untouched cues).

# What is measured and reported on the actual file

preflight runs the whole pipeline in memory and returns the same warnings convert then emits (a test asserts the two sets are equal). Counted per file: cues with positions dropped or approximated, karaoke cues, cues with effects (move, fade, transform, clip, rotation, border/shadow overrides, Effect field), drawing cues (\p1: dropped, never written as text), cues relying on a named style / region / vertical text, speaker / language / ruby / class annotations, style definitions, embedded fonts and pictures, comment and non-dialogue events, VTT STYLE / REGION blocks, runs with a font or strike-through that the destination lacks, lines whose runs have different styles (MicroDVD), SSA style settings dropped, cues whose timing was rounded, characters the output encoding cannot hold, unreadable blocks, cues with a derived end, cues dropped or clamped before 00:00, and every repair or clean-up made.

A plain SRT converted to VTT produces no warning.

# Timing rules (tested)

  • SRT ↔ VTT: exact to the millisecond. Test srtAndVttRoundTripToTheMillisecond: 2 600 random cues spanning more than three hours, SRT → VTT → SRT, byte-identical file.
  • ASS / SSA: centiseconds = (ms + 5) / 10 (round half up); the number of cues affected is reported. Test assRoundsHalfUpToTheCentisecond (1004 → 1.00 s, 1005 → 1.01 s, 995 → 1.00 s…).
  • MicroDVD: frame rates are exact rationals (23.976 → 24000/1001, 29.97 → 30000/1001, 59.94 → 60000/1001, a/b accepted). Frame → time: round(frame × 1000 × den / num); time → frame: nearest. frame → ms → frame is the identity: test frameToTimeToFrameIsTheIdentityOverThreeHours checks every frame of 3.1 hours at 23.976, 24, 25, 29.97, 30, 50, 59.94, 60 and 120 fps; microDVDRoundTripsThroughSubRipWithoutDrift converts a 3-hour file SUB → SRT → SUB at 25, 23.976 and 29.97 fps and gets the same bytes back.
  • Retiming is one affine map t ↦ (t·a + b) / c evaluated in 128-bit integers and rounded once: frame-rate conversion (25 → 23.976 multiplies by exactly 1001/960), two-point sync, then shift. Cues ending before 00:00 are removed and counted; cues starting before 00:00 are clamped and counted.
  • Repairs are off unless asked: sort + renumber, overlaps (a cue ends where the next starts; two cues with the same start are left alone and counted), negative durations (swapped), zero durations (minimum duration, or 1 s), minimum / maximum duration.

# Text encodings

Input: BOM (UTF-8, UTF-16 LE/BE) → pure ASCII → valid UTF-8 → UTF-16 without BOM (NUL pattern) → scoring heuristic over Windows-1250/1251/1252/1253/1254/1255/1256, ISO-8859-2/5/7/15, KOI8-R, Shift-JIS, GBK (GB 18030), Big5, EUC-KR. The result always says how it was obtained and a confidence; a heuristic guess is never reported as certain and produces the warning encoding-guessed. The user can force any of the 19 encodings (undecodable bytes are replaced and counted). Output: any of the same 19, UTF-8 by default, optional BOM, LF or CRLF; characters the encoding cannot hold become ? and are counted (characters-unrepresentable, data loss).

Tested (legacyCodePagesAreDetected): one paragraph of ordinary prose per code page — French (1252), Czech/Polish (1250), Russian (1251 and KOI8-R), Greek (1253), Turkish (1254), Hebrew (1255), Arabic (1256), Japanese (Shift-JIS), Simplified Chinese (GBK), Traditional Chinese (Big5), Korean (EUC-KR) — all 12 detected correctly, plus ISO-8859-2 versus Windows-1250 on Czech. This is a heuristic without language models: short files, files with very few non-ASCII letters, and languages sharing a code page layout (Western European languages other than those tested, Baltic, Vietnamese, Thai — not candidates at all) can be misdetected. ISO-8859-1 text is reported as Windows-1252 (its superset). ISO-8859-9 is not a candidate (Windows-1254 covers it).

# Parsers: what they tolerate (tested)

SRT: missing indices, . or , decimals, short fractions, no spaces around -->, coordinates after the timing, stray blank lines inside a cue, a missing blank line between cues, CRLF / lone CR, BOM, overlapping <b><i></b></i>, unknown tags (kept as text), {\an8} alignment, {i} tags. VTT: header text and metadata, NOTE / STYLE / REGION blocks, cue identifiers, cue settings (line, position, align, size, region, vertical), <c.class>, <v>, <lang>, <ruby>, inline timestamps, character references, a missing blank line between cues. ASS/SSA: reordered Format: lines for styles and events, commas in the text, comments, [Fonts] / [Graphics] / unknown sections, headerless files, Comment: and non-dialogue events. MicroDVD: {y:…}, {c:$BBGGRR}, {f:…}, upper-case (whole cue) and lower-case (one line) codes, the leading / italic shorthand, missing end frames, the {1}{1}fps header.

A timing line that cannot be read makes its whole block a skipped block (counted), never part of a neighbour. Fuzz test garbageNeverCrashesTheParsers: 400 inputs per format (random bytes, random syntax characters, mutated and truncated fixtures), each parsed and, when it parses, written to all five formats and re-parsed. Limits: files above 64 MB are refused; at most 500 000 cues are kept.

# Validation

validate re-runs the pipeline on the source to obtain the expected cues, re-parses the output file with the destination's parser, and checks: no unreadable block, same cue count, every start and end equal at the destination's resolution (millisecond, centisecond or frame), plain text equal after collapsing whitespace. The reader is this engine's own parser (there is no other subtitle parser on the system); the matrix test adds a comparison with values written by hand in the fixtures.

# Measured

Debug build, Apple M5 Max, one run on 2026-11-21 (MeasurementTests.measureLargeFileThroughput): a 100 000-cue SRT file (4.78 MB, about 60 times a feature film) converts in 2.2 s to VTT, ASS or MicroDVD; validation takes 2.6–4.2 s more. The whole test suite runs in 19–27 s (the machine was busy), most of it this measurement and the every-frame identity checks. A feature film (about 1 500 cues) is a few tens of milliseconds. Memory was not measured (the whole file is held in memory, bounded by the 64 MB limit).

# Evaluated and not implemented

  • TTML, SBV, LRC, SAMI, MPL2, SCC, EBU STL, VobSub (.sub + .idx, bitmap): not implemented. The catalog has no format identifiers for them, and each needs its own parser, writer and tests; none was "cheap" enough to do properly here. A VobSub .sub (binary MPEG stream) is not MicroDVD and is rejected as having no cue.
  • Language detection: not done, by decision; inspect says so.
  • ASS rendering semantics (style inheritance into the inline model, \r to a named style, margins, layers, collision handling, \t animations): not modelled. The inline model takes bold / italic / underline / strike-through / colour / font from override tags only, not from the style a line uses; a line that is bold because its style is bold is written without bold in SRT / VTT, and counted under "rely on a named style" when the style is not Default.
  • VTT ::cue CSS: STYLE blocks are preserved for VTT → VTT but not interpreted (except the colour classes this engine writes itself, and the eight standard colour classes).
  • Hearing-impaired clean-up is pattern-based (bracketed / parenthesised text, music-only lines, upper-case speaker labels); it cannot tell a real parenthesis from an annotation. Off by default; OCR fixes are limited to a lone l / | standing for "I" and '' for ", off by default.
  • Rewrap counts UTF-16 units, not display width: CJK and combining sequences may wrap earlier than expected.
  • A line of SRT text containing --> ends the cue (it is read as a broken timing line).
Files main
Menu

Theme