User Tools

Site Tools


subtitles_in_markdown

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
subtitles_in_markdown [2026/04/25 18:58] – smickstersubtitles_in_markdown [2026/04/25 19:09] (current) – smickster
Line 3: Line 3:
 This page defines a **strict syntax specification** for a custom Markdown-like subtitle source format. This page defines a **strict syntax specification** for a custom Markdown-like subtitle source format.
 It is designed so you can write subtitles in plain text, then reliably parse and convert them to SRT, WebVTT, ASS, or other formats. It is designed so you can write subtitles in plain text, then reliably parse and convert them to SRT, WebVTT, ASS, or other formats.
 +
 +**Spec version**: 1.1 \\
 +**Last updated**: 2025 \\
 +**Status**: Draft
  
 ===== Technical Overview ===== ===== Technical Overview =====
  
-**Format name**: MDSub Custom (inspired by mdsub and similar tools) \\+**Format name**: MDSub Custom (inspired by [[https://github.com/mdsub|mdsub]] and similar tools) \\
 **Purpose**: Human-readable subtitle authoring with deterministic parsing \\ **Purpose**: Human-readable subtitle authoring with deterministic parsing \\
 **Target outputs**: SRT, WebVTT, ASS/SSA \\ **Target outputs**: SRT, WebVTT, ASS/SSA \\
-**Parser requirements**: Line-by-line regex matching + timestamp validation+**Parser requirements**: Line-by-line regex matching + timestamp validation \\ 
 +**Character encoding**: UTF-8 without BOM (see [[#encoding_and_character_set_notes|Encoding Notes]]) 
 + 
 +===== Output Format Comparison ===== 
 + 
 +Before choosing a target format, use this table to pick the right one for your use case. 
 + 
 +^ Feature ^ SRT ^ WebVTT ^ ASS/SSA ^ 
 +| Browser native support | Limited | Yes (HTML5) | No | 
 +| Styling support | None | Basic (CSS) | Full | 
 +| Positioning control | No | Yes | Yes | 
 +| Right-to-left text | Poor | Yes | Yes | 
 +| Player support | Universal | Modern browsers | Aegisub, MPC, VLC | 
 +| File simplicity | Highest | High | Low | 
 +| Best used for | General distribution | Web video | Fansubs, styled video |
  
 ===== Strict Syntax Rules ===== ===== Strict Syntax Rules =====
Line 15: Line 33:
 Every subtitle file MUST follow these exact rules: Every subtitle file MUST follow these exact rules:
  
-**Lines are processed sequentially** — no lookahead beyond current line \\ +  * Lines are processed sequentially — no lookahead beyond current line 
-**Timestamps use ISO-like format**: `HH:MM:SS.mmm --> HH:MM:SS.mmm` \\ +  * Timestamps use ISO-like format: ''HH:MM:SS.mmm --> HH:MM:SS.mmm'' 
-**Each cue = 1 timestamp line + 1-3 text lines** \\ +  * Each cue = 1 timestamp line + 1-3 text lines 
-**Blank lines separate cues** \\ +  * Blank lines separate cues — the blank line is the cue terminator, not optional whitespace 
-**Comments use `//` prefix** \\ +  * Comments use ''%%//%%'' prefix 
-**File must start with optional metadata header**+  * File must start with optional metadata header 
 +  * Files must be saved as UTF-8 without BOM
  
 ===== Complete Line Types ===== ===== Complete Line Types =====
  
-| Type | Pattern | Example | Parser Action | +^ Type ^ Pattern ^ Example ^ Parser Action ^ 
-|------|---------|---------|---------------| +| Metadata | ''%%// Title: ...%%'' | ''%%// Title: My Video%%'' | Store as metadata | 
-| Metadata | `// Title: ...` | `// Title: My Video` | Store as metadata | +| Metadata | ''%%// Language: ...%%'' | ''%%// Language: en-US%%'' | Store as metadata | 
-| Metadata | `// Language: ...` | `// Language: en-US` | Store as metadata | +| Comment | ''%%// ...%%'' | ''%%// Scene 1 starts%%'' | Ignore for output | 
-| Comment | `// ...` | `// Scene 1 starts` | Ignore for output | +| Timestamp | ''[HH:MM:SS.mmm --> HH:MM:SS.mmm]'' | ''[00:01:23.456 --> 00:01:25.789]'' | Start new cue | 
-| Timestamp | `[HH:MM:SS.mmm --> HH:MM:SS.mmm]` | `[00:01:23.456 --> 00:01:25.789]` | Start new cue | +| Speaker | ''[SPEAKER]'' | ''[NARRATOR]'' | Prefix to next dialogue | 
-| Speaker | `[SPEAKER]` | `[NARRATOR]` | Prefix to next dialogue | +| Dialogue | Plain text | ''This is spoken text.'' | Add to current cue | 
-| Dialogue | Plain text | `This is spoken text.` | Add to current cue | +| Emphasis | ''%%**text**%%'' or ''%%_text_%%'' | ''%%**WARNING**%%'' | Convert per output format | 
-| Emphasis | `**text**` or `_text_` | `**WARNING**` | Convert per output format | +| Style | ''%%<<position:center>>%%'' | ''%%<<position:bottom>>%%'' | ASS positioning tag | 
-| Style | `<<position:center>>` | `<<position:bottom>>` | ASS positioning tag | +| Empty | (blank line) | — | End current cue |
-| Empty | ` ` | `(blank line)` | End current cue |+
  
 ===== File Structure ===== ===== File Structure =====
  
-[Optional metadata block with // lines]+The blank line between cues is structural — the parser uses it as the signal to finalize 
 +and store the current cue. A missing blank line will cause two cues to merge incorrectly.
  
-[00:00:01.000 --> 00:00:03.500] \\ +<code> 
-[NARRATOR] \\+// Title: Example File 
 +// Language: en-US 
 + 
 +[00:00:01.000 --> 00:00:03.500] 
 +[NARRATOR]
 Welcome to the show. Welcome to the show.
  
-[00:00:03.500 --> 00:00:06.000] \\+[00:00:03.500 --> 00:00:06.000]
 This is the first subtitle. This is the first subtitle.
  
-[00:00:06.000 --> 00:00:08.000] \\ +[00:00:06.000 --> 00:00:08.000] 
-[JANE] \\+[JANE]
 Whispering: Did you hear that? Whispering: Did you hear that?
 +</code>
  
 ===== Timestamp Specification ===== ===== Timestamp Specification =====
  
-**Format**: `[HH:MM:SS.mmm --> HH:MM:SS.mmm]` \\ +**Format**: ''[HH:MM:SS.mmm --> HH:MM:SS.mmm]''
-**Validation rules**: \\ +
-- Hours: `00-23` \\ +
-- Minutes/Seconds: `00-59` \\   +
-- Milliseconds: `000-999` \\ +
-- End time > start time \\ +
-- Leading zeros required+
  
-**Parser regex** (PCRE compatible):+**Capture groups in the parser regex** (groups 1–4 = start time, groups 5–8 = end time): 
 +  - Hours (start) 
 +  - Minutes (start) 
 +  - Seconds (start) 
 +  - Milliseconds (start) 
 +  - Hours (end) 
 +  - Minutes (end) 
 +  - Seconds (end) 
 +  - Milliseconds (end)
  
-^\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*$+**Validation rules**: 
 +  * Hours: ''00-23'' 
 +  * Minutes/Seconds: ''00-59'' 
 +  * Milliseconds: ''000-999'' 
 +  * End time must be greater than start time 
 +  * Leading zeros required 
 + 
 +**Parser regex** (PCRE compatible):
  
 +<code>
 +^\[\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*\]$
 +</code>
  
 ===== Parser State Machine ===== ===== Parser State Machine =====
  
-State: IDLE \\ +**State: IDLE** 
-├── Metadata line (//) → Store metadata, stay IDLE \\ +  * Metadata line (''%%//%%'' prefix) → Store metadata, stay IDLE 
-├── Timestamp line → Create new Cue, go to COLLECTING \\ +  * Timestamp line → Create new Cue, go to COLLECTING 
-└── Other → Error +  * Other → Error
- +
-State: COLLECTING \\ +
-├── Blank line → Finalize cue, go to IDLE \\ +
-├── Speaker line → Set cue.speaker, stay COLLECTING \\ +
-├── Dialogue line → Append to cue.text, stay COLLECTING \\ +
-└── Timestamp → Finalize current cue, create new cue, stay COLLECTING \\+
  
 +**State: COLLECTING**
 +  * Blank line → Finalize cue, go to IDLE
 +  * Speaker line → Set cue.speaker, stay COLLECTING
 +  * Dialogue line → Append to cue.text, stay COLLECTING
 +  * Timestamp → Finalize current cue, create new cue, stay COLLECTING
  
 ===== Output Format Mappings ===== ===== Output Format Mappings =====
Line 85: Line 119:
 ==== SRT ==== ==== SRT ====
  
 +Note: SRT uses a comma as the millisecond separator, not a period. This is a common
 +source of bugs when converting from other formats.
 +
 +<code>
 1 1
- 
 00:00:01,000 --> 00:00:03,500 00:00:01,000 --> 00:00:03,500
 [NARRATOR] [NARRATOR]
 Welcome to the show. Welcome to the show.
 +</code>
  
 ==== WebVTT ==== ==== WebVTT ====
  
 +<code>
 WEBVTT WEBVTT
  
Line 99: Line 137:
 [NARRATOR] [NARRATOR]
 Welcome to the show. Welcome to the show.
 +</code>
  
 ==== ASS ==== ==== ASS ====
  
 +ASS is the most complex output format. The ''{\pos(X,Y)}'' tag controls screen position
 +using pixel coordinates. For a 1280×720 canvas, center-bottom is roughly ''{\pos(640,360)}''.
 +The coordinate origin is top-left. ASS requires a full ''[Script Info]'' and ''[V4+ Styles]''
 +header in real files — what is shown below is the Events section only.
 +
 +<code>
 [Events] [Events]
 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
 Dialogue: 0,0:00:01.00,0:00:03.50,Default,,0,0,0,,{\pos(640,360)}[NARRATOR]Welcome to the show. Dialogue: 0,0:00:01.00,0:00:03.50,Default,,0,0,0,,{\pos(640,360)}[NARRATOR]Welcome to the show.
 +</code>
  
 +For full ASS file structure reference, see: [[https://aegisub.org/docs/latest/ass_tags/|Aegisub ASS Tag Reference]]
  
 ===== Markdown Processing Rules ===== ===== Markdown Processing Rules =====
  
-| Source | SRT | WebVTT | ASS | +^ Source ^ SRT ^ WebVTT ^ ASS ^ 
-|--------|-----|--------|-----| +| ''%%**bold**%%'' | ''%%**bold**%%'' | ''<b>bold</b>'' | ''{\b1}bold{\b0}'' | 
-| `**bold**` | `**bold**` | `<b>bold</b>` | `{\b1}bold{\b0}` | +| ''%%_italic_%%'' | ''%%_italic_%%'' | ''<i>italic</i>'' | ''{\i1}italic{\i0}'' | 
-| `_italic_` | `_italic_` | `<i>italic</i>` | `{\i1}italic{\i0}` | +| ''[SPEAKER]'' | ''[SPEAKER]'' | ''[SPEAKER]'' | ''{\c&Hffffff&}[SPEAKER]'' | 
-| `[SPEAKER]` | `[SPEAKER]` | `[SPEAKER]` | `{\c&Hffffff&}[SPEAKER]` | +| ''%%<<position:center>>%%'' | ignored | ignored | ''{\pos(640,360)}'' | 
-| `<<position:center>>` | ignored | ignored | `{\pos(640,360)}` |+ 
 +Note: SRT does not support inline styling in most players. Bold and italic markers are 
 +passed through as literal text for SRT output since behaviour varies by player.
  
 ===== Complete Parser Pseudocode ===== ===== Complete Parser Pseudocode =====
  
-```javascript+<code javascript>
 function parseMDSub(source) { function parseMDSub(source) {
   let cues = [];   let cues = [];
   let currentCue = null;   let currentCue = null;
   let metadata = {};   let metadata = {};
-  +
   for (let line of source.split('\n')) {   for (let line of source.split('\n')) {
     line = line.trim();     line = line.trim();
-    +
     if (line.startsWith('//')) {     if (line.startsWith('//')) {
       parseMetadata(line, metadata);       parseMetadata(line, metadata);
       continue;       continue;
     }     }
-    +
     if (isTimestampLine(line)) {     if (isTimestampLine(line)) {
       if (currentCue) finalizeCue(currentCue, cues);       if (currentCue) finalizeCue(currentCue, cues);
Line 138: Line 186:
       continue;       continue;
     }     }
-    +
     if (line === '') {     if (line === '') {
       if (currentCue) finalizeCue(currentCue, cues);       if (currentCue) finalizeCue(currentCue, cues);
Line 144: Line 192:
       continue;       continue;
     }     }
-    +
     if (currentCue) {     if (currentCue) {
       if (isSpeakerLine(line)) {       if (isSpeakerLine(line)) {
Line 153: Line 201:
     }     }
   }   }
-  +
   if (currentCue) finalizeCue(currentCue, cues);   if (currentCue) finalizeCue(currentCue, cues);
   return { metadata, cues };   return { metadata, cues };
 } }
-```+</code>
  
 ===== Validation Checklist ===== ===== Validation Checklist =====
  
-Before conversion, validate:+Run these checks before conversion. See [[#error_conditions|Error Conditions]] for 
 +how to handle each failure.
  
-- [ ] All timestamps parse correctly +  * All timestamps parse correctly against the regex 
-- [ ] End time > start time for each cue +  * End time > start time for every cue 
-- [ ] No overlapping timestamps +  * No overlapping timestamps between consecutive cues 
-- [ ] Maximum 2 lines per cue (SRT limit) +  * Maximum 2 lines of dialogue per cue (SRT hard limit in many players) 
-- [ ] Maximum 42 characters per line (SRT recommendation) +  * Maximum 42 characters per line (SRT recommendation — not enforced by all players) 
-- [ ] Consistent language metadata+  * Consistent language metadata declared at top of file 
 +  * File is UTF-8 encoded without BOM
  
 ===== Error Conditions ===== ===== Error Conditions =====
  
-| Error | Message | Recovery | +^ Error ^ Message ^ Recovery ^ 
-|-------|---------|----------| +| Invalid timestamp | ''Line X: malformed timestamp'' | Skip line | 
-| Invalid timestamp | "Line X: malformed timestamp" | Skip line | +| Overlapping cues | ''Cue X overlaps with Y'' | Use earliest end time | 
-| Overlapping cues | "Cue X overlaps with Y" | Use earliest end time | +| Empty cue text | ''Timestamp without text'' | Skip cue | 
-| Empty cue text | "Timestamp without text" | Skip cue | +| Unclosed cue at EOF | ''File ends mid-cue'' | Finalize last cue | 
-| Unclosed cue | "File ends mid-cue" | Finalize last cue |+| BOM detected | ''Warning: BOM found, stripping'' | Strip and continue | 
 +| Encoding error | ''Line X: non-UTF-8 bytes'' | Replace with replacement character or abort | 
 + 
 +===== Known Limitations and Edge Cases ===== 
 + 
 +These are areas where the format or its parser may behave unexpectedly. Test these 
 +cases before deploying in production. 
 + 
 +==== Right-to-Left Text ==== 
 + 
 +RTL languages (Arabic, Hebrew, Persian) require Unicode bidi control characters for 
 +correct display. This format passes text through as-is; bidi rendering is the 
 +responsibility of the player or browser. WebVTT and ASS handle RTL significantly 
 +better than SRT. 
 + 
 +==== Overlapping Cues ==== 
 + 
 +The spec recovers overlapping cues by using the earliest end time, but many players 
 +handle overlapping SRT cues differently — some show both, some show only the first, 
 +some show neither. For WebVTT, overlapping cues are valid by spec. For SRT, avoid 
 +overlaps entirely if broad player compatibility is needed. 
 + 
 +==== The 42-Character Line Limit ==== 
 + 
 +This is a guideline from broadcast subtitle conventions, not an enforced SRT rule. 
 +Many desktop players ignore it entirely. However, streaming platforms (Netflix, YouTube 
 +auto-import) may reject or reformat SRT files that exceed it. Treat it as a hard limit 
 +if you're targeting platform upload. 
 + 
 +==== Multi-Line Cue Behaviour ==== 
 + 
 +The spec allows 1–3 text lines per cue, but SRT players typically display a maximum 
 +of 2 lines reliably. A third line may be hidden below the frame on some players. 
 +Limit to 2 lines for safest cross-player compatibility. 
 + 
 +==== Millisecond Precision ==== 
 + 
 +SRT officially supports milliseconds (3 digits). Some legacy SRT players only parse 
 +2-digit centiseconds. If targeting very old hardware players, consider rounding to 
 +centisecond precision in your SRT output. 
 + 
 +==== Encoding and Character Set Notes ==== 
 + 
 +  * Always save as **UTF-8 without BOM** 
 +  * UTF-8 with BOM will break most SRT parsers (the BOM appears as garbage at the start of cue 1) 
 +  * WebVTT requires UTF-8 by specification 
 +  * ASS files traditionally use UTF-8 or local codepage — Aegisub defaults to UTF-8 
 +  * Special characters like em-dash (—), ellipsis (…), and curly quotes should be used 
 +    as Unicode codepoints, not HTML entities, in the source format
  
 ===== Implementation Notes ===== ===== Implementation Notes =====
  
-**Language**: JavaScript/Node.js, Python 3, or Bash +**Language**: JavaScript/Node.js, Python 3, or Bash \\ 
-**Dependencies**: None (pure regex + string processing) +**Dependencies**: None (pure regex + string processing) \\ 
-**Runtime**: O(n) where n = lines +**Runtime**: O(n) where n = lines \\ 
-**File size limit**: 10MB source → ~1M cues +**File size limit**: 10MB source → ~1M cues \\ 
-**Output validation**: Test generated SRT/VTT in VLC, browser+**Output validation**: Test generated SRT/VTT in VLC, Firefox, and your target platform
  
-===== Sample Implementation Links =====+===== Related Tools and Ecosystem =====
  
-*(Add your own scripts here)* +These are the standard tools you are likely to use alongside this format. 
-- Python converter: `scripts/mdsub2srt.py` + 
-- Node.js version: `scripts/mdsub-parser.js` +==== Subtitle Editors ==== 
-- Test files: `tests/sample.mdsub`+ 
 +  * [[https://aegisub.org/|Aegisub]] — The standard open-source editor for ASS/SSA. Also handles SRT and WebVTT import/export. Essential if you are doing styled subtitles. 
 +  * [[https://www.nikse.dk/subtitleedit|Subtitle Edit]] — Windows-native editor with support for 300+ formats including SRT, WebVTT, and ASS. Good for batch conversion. 
 + 
 +==== Conversion and Processing ==== 
 + 
 +  * [[https://ffmpeg.org/|FFmpeg]] — Can mux/demux subtitle streams and convert between SRT, WebVTT, and ASS via ''ffmpeg -i input.mkv -map 0:s:0 output.srt''. Essential for working with video containers. 
 +  * [[https://www.nikse.dk/subtitleedit|Subtitle Edit CLI]] — Batch conversion from the command line. 
 + 
 +==== Validation ==== 
 + 
 +  * [[https://quuz.org/webvtt/|WebVTT Validator]] — Online validator for WebVTT files. 
 +  * VLC Media Player — Reliable real-world test for SRT and WebVTT rendering. Drag subtitle file onto playing video. 
 +  * Firefox DevTools — Open a local HTML5 video with a ''<track>'' element pointing to your VTT file; console will report parse errors. 
 + 
 +==== Reference Specifications ==== 
 + 
 +  * [[https://www.w3.org/TR/webvtt1/|WebVTT W3C Specification]] 
 +  * [[https://www.matroska.org/technical/subtitles.html|Matroska Subtitle Support]] — Relevant if muxing into MKV 
 +  * [[https://aegisub.org/docs/latest/ass_tags/|Aegisub ASS Tag Reference]] 
 +  * [[https://datatracker.ietf.org/doc/html/rfc8216|HLS (RFC 8216)]] — WebVTT is the required subtitle format for HLS streams 
 + 
 +==== Related Pages (this wiki) ==== 
 + 
 +  * [[fountain_syntax|Fountain: Markdown-Like Screenplay Syntax]] — The equivalent solution for screenwriting; covers similar plain-text-to-structured-format concepts
  
 ===== Quick Implementation Template ===== ===== Quick Implementation Template =====
  
-```bash+<code python>
 #!/usr/bin/env python3 #!/usr/bin/env python3
 +# mdsub2srt.py — minimal MDSub to SRT converter
 import re import re
 import sys import sys
  
-TIMESTAMP_RE = re.compile(r'^\[\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*\]$')+TIMESTAMP_RE = re.compile( 
 +    r'^\[\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})\.(\d{3})\s*\]$' 
 +)
  
 def parse_mdsub(filename): def parse_mdsub(filename):
     # Implementation here following spec above     # Implementation here following spec above
 +    pass
 +
 +def print_srt(cues):
 +    # Implementation here
     pass     pass
  
 if __name__ == "__main__": if __name__ == "__main__":
-    cues = parse_mdsub(sys.argv)[1]+    if len(sys.argv) < 2: 
 +        print("Usage: mdsub2srt.py <inputfile>", file=sys.stderr) 
 +        sys.exit(1) 
 +    cues = parse_mdsub(sys.argv[1])
     print_srt(cues)     print_srt(cues)
-```+</code> 
 + 
 +===== Sample Implementation Links ===== 
 + 
 +  * Python converter: ''scripts/mdsub2srt.py'' 
 +  * Node.js version: ''scripts/mdsub-parser.js'' 
 +  * Test files: ''tests/sample.mdsub''
  
 ===== Final Notes ===== ===== Final Notes =====
  
-This spec is complete and deterministic. +This spec is complete and deterministic. Any implementation following these rules will 
-Any implementation following these rules will produce identical output from the same source file. +produce identical output from the same source file. 
-Test thoroughly with edge cases before production use.+ 
 +The format intentionally omits production features like cue numbering (handled on output), 
 +revision marks, and locked timecodes. It is designed for the authoring phase — once 
 +converted to SRT/WebVTT/ASS, use a dedicated editor like Aegisub for production work. 
 + 
 +Test thoroughly with edge cases — particularly encoding, overlapping cues, and RTL text — 
 +before production use.
subtitles_in_markdown.1777143489.txt.gz · Last modified: by smickster

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki