SPB Git

Repository Public License

subtitle.md 11.3 KB 137 lines markdown

1# Subtitle engine (`subtitle`) — compatibility23Package `Packages/EngineSubtitle`, module `EngineSubtitle`, factory `makeEngines()`. Pure Swift, no third-party code,4no helper process. State on 2026-11-21 (macOS 27.0, arm64): **30 declared paths, 36 tests, all passing**5(`swift test`: `Test run with 36 tests in 5 suites passed`; the parameterised matrix test converts every one of the630 paths).78## Formats910| Format | Read | Write | Time unit in the file |11|---|---|---|---|12| SubRip `.srt` | yes | yes | millisecond |13| WebVTT `.vtt` | yes | yes | millisecond |14| Advanced SubStation Alpha `.ass` | yes | yes | centisecond |15| SubStation Alpha `.ssa` | yes | yes | centisecond |16| MicroDVD `.sub` | yes | yes | frame (needs a frame rate) |1718Internally every cue has integer-millisecond start and end, a list of text runs with bold / italic / underline /19strike-through / colour / font, an optional numpad alignment (1–9) and an optional position in percent of the frame.2021## Declared paths2223All 20 ordered pairs among the five formats (plain conversion), plus two same-format operations per format.24Every path is `supported`, fidelity `structural` (the text and timing are kept; the markup is rewritten).25Test for all of them: `MatrixTests.everyDeclaredPathConvertsAndValidates(path:)` — converts a six-cue fixture that26exists in the five formats, runs the core's generic validation and the engine's, then re-reads the output and27compares start, end and plain text of every cue with the known values.2829| Source → destination | Preserves | Limitations shown to the user |30|---|---|---|31| 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. |32| 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. |33| 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. |34| 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. |35| 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. |36| **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`). |37| 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. |38| 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). |3940## What is measured and reported on the actual file4142`preflight` runs the whole pipeline in memory and returns the same warnings `convert` then emits (a test asserts the43two sets are equal). Counted per file: cues with positions dropped or approximated, karaoke cues, cues with effects44(move, fade, transform, clip, rotation, border/shadow overrides, `Effect` field), drawing cues (`\p1`: dropped, never45written as text), cues relying on a named style / region / vertical text, speaker / language / ruby / class46annotations, style definitions, embedded fonts and pictures, comment and non-dialogue events, VTT STYLE / REGION47blocks, runs with a font or strike-through that the destination lacks, lines whose runs have different styles48(MicroDVD), SSA style settings dropped, cues whose timing was rounded, characters the output encoding cannot hold,49unreadable blocks, cues with a derived end, cues dropped or clamped before 00:00, and every repair or clean-up made.5051A plain SRT converted to VTT produces **no** warning.5253## Timing rules (tested)5455- SRT ↔ VTT: exact to the millisecond. Test `srtAndVttRoundTripToTheMillisecond`: 2 600 random cues spanning more56  than three hours, SRT → VTT → SRT, byte-identical file.57- ASS / SSA: centiseconds = `(ms + 5) / 10` (round half up); the number of cues affected is reported.58  Test `assRoundsHalfUpToTheCentisecond` (1004 → 1.00 s, 1005 → 1.01 s, 995 → 1.00 s…).59- MicroDVD: frame rates are exact rationals (`23.976` → 24000/1001, `29.97` → 30000/1001, `59.94` → 60000/1001,60  `a/b` accepted). Frame → time: `round(frame × 1000 × den / num)`; time → frame: nearest. `frame → ms → frame` is61  the identity: test `frameToTimeToFrameIsTheIdentityOverThreeHours` checks **every** frame of 3.1 hours at62  23.976, 24, 25, 29.97, 30, 50, 59.94, 60 and 120 fps; `microDVDRoundTripsThroughSubRipWithoutDrift` converts a63  3-hour file SUB → SRT → SUB at 25, 23.976 and 29.97 fps and gets the same bytes back.64- Retiming is one affine map `t ↦ (t·a + b) / c` evaluated in 128-bit integers and rounded once: frame-rate65  conversion (25 → 23.976 multiplies by exactly 1001/960), two-point sync, then shift. Cues ending before 00:00 are66  removed and counted; cues starting before 00:00 are clamped and counted.67- Repairs are off unless asked: sort + renumber, overlaps (a cue ends where the next starts; two cues with the same68  start are left alone and counted), negative durations (swapped), zero durations (minimum duration, or 1 s),69  minimum / maximum duration.7071## Text encodings7273Input: BOM (UTF-8, UTF-16 LE/BE) → pure ASCII → valid UTF-8 → UTF-16 without BOM (NUL pattern) → scoring heuristic over74Windows-1250/1251/1252/1253/1254/1255/1256, ISO-8859-2/5/7/15, KOI8-R, Shift-JIS, GBK (GB 18030), Big5, EUC-KR.75The result always says how it was obtained and a confidence; a heuristic guess is never reported as certain and76produces the warning `encoding-guessed`. The user can force any of the 19 encodings (undecodable bytes are replaced77and counted). Output: any of the same 19, UTF-8 by default, optional BOM, LF or CRLF; characters the encoding cannot78hold become `?` and are counted (`characters-unrepresentable`, data loss).7980Tested (`legacyCodePagesAreDetected`): one paragraph of ordinary prose per code page — French (1252), Czech/Polish81(1250), Russian (1251 and KOI8-R), Greek (1253), Turkish (1254), Hebrew (1255), Arabic (1256), Japanese (Shift-JIS),82Simplified Chinese (GBK), Traditional Chinese (Big5), Korean (EUC-KR) — all 12 detected correctly, plus ISO-8859-283versus Windows-1250 on Czech. **This is a heuristic without language models**: short files, files with very few84non-ASCII letters, and languages sharing a code page layout (Western European languages other than those tested,85Baltic, Vietnamese, Thai — not candidates at all) can be misdetected. ISO-8859-1 text is reported as Windows-125286(its superset). ISO-8859-9 is not a candidate (Windows-1254 covers it).8788## Parsers: what they tolerate (tested)8990SRT: missing indices, `.` or `,` decimals, short fractions, no spaces around `-->`, coordinates after the timing,91stray blank lines inside a cue, a missing blank line between cues, CRLF / lone CR, BOM, overlapping `<b><i></b></i>`,92unknown tags (kept as text), `{\an8}` alignment, `{i}` tags. VTT: header text and metadata, NOTE / STYLE / REGION93blocks, cue identifiers, cue settings (line, position, align, size, region, vertical), `<c.class>`, `<v>`, `<lang>`,94`<ruby>`, inline timestamps, character references, a missing blank line between cues. ASS/SSA: reordered `Format:`95lines for styles and events, commas in the text, comments, `[Fonts]` / `[Graphics]` / unknown sections, headerless96files, `Comment:` and non-dialogue events. MicroDVD: `{y:…}`, `{c:$BBGGRR}`, `{f:…}`, upper-case (whole cue) and97lower-case (one line) codes, the leading `/` italic shorthand, missing end frames, the `{1}{1}fps` header.9899A timing line that cannot be read makes its whole block a skipped block (counted), never part of a neighbour.100Fuzz test `garbageNeverCrashesTheParsers`: 400 inputs per format (random bytes, random syntax characters, mutated101and truncated fixtures), each parsed and, when it parses, written to all five formats and re-parsed.102Limits: files above 64 MB are refused; at most 500 000 cues are kept.103104## Validation105106`validate` re-runs the pipeline on the source to obtain the expected cues, re-parses the output file with the107destination's parser, and checks: no unreadable block, same cue count, every start and end equal at the108destination's resolution (millisecond, centisecond or frame), plain text equal after collapsing whitespace.109The reader is this engine's own parser (there is no other subtitle parser on the system); the matrix test adds a110comparison with values written by hand in the fixtures.111112## Measured113114Debug build, Apple M5 Max, one run on 2026-11-21 (`MeasurementTests.measureLargeFileThroughput`):115a 100 000-cue SRT file (4.78 MB, about 60 times a feature film) converts in **2.2 s** to VTT, ASS or MicroDVD;116validation takes 2.6–4.2 s more. The whole test suite runs in 19–27 s (the machine was busy), most of it this117measurement 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).118119## Evaluated and not implemented120121- **TTML, SBV, LRC, SAMI, MPL2, SCC, EBU STL, VobSub (`.sub` + `.idx`, bitmap)**: not implemented. The catalog has no122  format identifiers for them, and each needs its own parser, writer and tests; none was "cheap" enough to do123  properly here. A VobSub `.sub` (binary MPEG stream) is not MicroDVD and is rejected as having no cue.124- **Language detection**: not done, by decision; `inspect` says so.125- **ASS rendering semantics** (style inheritance into the inline model, `\r` to a named style, margins, layers,126  collision handling, `\t` animations): not modelled. The inline model takes bold / italic / underline /127  strike-through / colour / font from override tags only, not from the style a line uses; a line that is bold128  because its *style* is bold is written without bold in SRT / VTT, and counted under "rely on a named style" when129  the style is not `Default`.130- **VTT `::cue` CSS**: STYLE blocks are preserved for VTT → VTT but not interpreted (except the colour classes this131  engine writes itself, and the eight standard colour classes).132- **Hearing-impaired clean-up** is pattern-based (bracketed / parenthesised text, music-only lines, upper-case133  speaker labels); it cannot tell a real parenthesis from an annotation. Off by default; OCR fixes are limited to a134  lone `l` / `|` standing for "I" and `''` for `"`, off by default.135- **Rewrap** counts UTF-16 units, not display width: CJK and combining sequences may wrap earlier than expected.136- A line of SRT text containing `-->` ends the cue (it is read as a broken timing line).137
Files main
Menu

Theme