Files
rosetta/src/Formats/subtitle/ass/init.luau
T
4DBugandClaude Opus 5.5 9c553b9d1a ws-cleanup: shared plumbing: Err.from, core/Sniff, Pcm.drain, Bits.msbPut; DUP lint; tools/move.py
- core/Err.from(message, offset?, kind?): the private-submodule -> Err plumbing (a kind, or a 'code: ' prefix /
  'truncated' / 'past the end' in the message) that Brotli, Bzip2, Zstd, Jpeg, WOFF2, FBX, plist, msgpack and
  bmfont each wrote.
- core/Sniff (new): Sniff.text(r, n, trim?) (the start of a text file without its BOM), Sniff.dropBom(s),
  Sniff.magic(r, s); 13 text formats' sniff / decode BOM handling goes through it.
- codecs/Pcm.drain(dec, source?, maxFrames?): a format's decode() through its open(); the collect-the-Decoder
  loops of aac, aiff, au, caf, flac, m4a, mp3, opus, vorbis and wav are one call each.
- core/Bits.msbPut: the MSB-first bit writer the MP3 / MP2 / FLAC encoders each copied.
- tools/lint_rules.py DUP: a function body of 12+ code lines repeated token for token in another module fails.
- tools/move.py: moves a module and rewrites every reference (requires, deps, headers, fixture INPUTS, docs).
- tools/fixtures/zstd.py: the incompressible corpus is smaller (zstd.luau 15.1 -> 13.4 MB; every fixture module is
  now under 14.3 MB).
- tools/bench.luau: MPEG-1 also runs with the api's LuaJIT trace limits; the sections that compare tuned / default
  limits set them explicitly (jitTune), so the order of sections no longer leaks the tuning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:00:59 -05:00

457 lines
15 KiB
Luau

--!strict
-- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of
-- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles]
-- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the
-- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any
-- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times.
-- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become
-- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw.
-- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it,
-- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported:
-- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Sniff = require("@formats/core/Sniff")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Ass = {
name = "ass",
category = "subtitle",
extensions = { "ass", "ssa" },
mime = { "text/x-ssa", "text/x-ass" },
deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" },
caps = { decode = true, encode = true, styles = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {
crlf: boolean?, -- CRLF line ends (default false)
}
-- ------------------------------------------------------------------------------------------------ constants
local STYLE_FORMAT = { "Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour", "Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle", "Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding" }
local STYLE_DEFAULT: { [string]: string } = {
Name = "Default",
Fontname = "Arial",
Fontsize = "16",
PrimaryColour = "&Hffffff",
SecondaryColour = "&Hffffff",
OutlineColour = "&H0",
TertiaryColour = "&H0",
BackColour = "&H0",
Bold = "0",
Italic = "0",
Underline = "0",
StrikeOut = "0",
ScaleX = "100",
ScaleY = "100",
Spacing = "0",
Angle = "0",
BorderStyle = "1",
Outline = "1",
Shadow = "0",
Alignment = "2",
MarginL = "10",
MarginR = "10",
MarginV = "10",
AlphaLevel = "0",
Encoding = "0",
}
local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" }
-- event fields -> cue keys (the rest keep their field name)
local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" }
local function trim(s: string): string
return (string.match(s, "^%s*(.-)%s*$")) :: string
end
local function fields(s: string): { string }
local out = {}
for _, f in string.split(s, ",") do
table.insert(out, trim(f))
end
return out
end
-- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil
local function time(s: string): number?
local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$")
if not h then
return nil
end
local fr = if f ~= "" then (tonumber(f) :: number) / 10 ^ #(f :: string) else 0
return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr
end
-- ASS text -> the shared markup
local TAGS = { i = "i", b = "b", u = "u", s = "s" }
function Ass.toMarkup(raw: string): string
local open: { [string]: boolean } = {}
local out = string.gsub(raw, "{([^}]*)}", function(block: string): string
local acc = {}
for tag, arg in string.gmatch(block, "\\(%a+)([^\\]*)") do
local t = TAGS[tag]
if t then
local on = arg == "" or (tonumber(arg) or 0) ~= 0
if arg == "" then
on = not open[t]
end
if on and not open[t] then
table.insert(acc, "<" .. t .. ">")
open[t] = true
elseif not on and open[t] then
table.insert(acc, "</" .. t .. ">")
open[t] = false
end
elseif tag == "r" then
for _, k in { "s", "u", "b", "i" } do
if open[k] then
table.insert(acc, "</" .. k .. ">")
open[k] = false
end
end
end
end
return table.concat(acc)
end)
out = string.gsub(out, "\\[Nn]", "\n")
out = string.gsub(out, "\\h", "\194\160")
for _, k in { "s", "u", "b", "i" } do
if open[k] then
out ..= "</" .. k .. ">"
end
end
return out
end
-- the shared markup -> ASS text
function Ass.fromMarkup(text: string): string
local s = string.gsub(text, "\r\n?", "\n")
s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string
local t = TAGS[string.lower(tag)]
if not t then
return ""
end
return "{\\" .. t .. (if close == "/" then "0" else "1") .. "}"
end)
s = string.gsub(s, "\n", "\\N")
return s
end
-- ------------------------------------------------------------------------------------------------ sniff
function Ass.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 64)
if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
if r.limit - r.base > maxBytes then
return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit")
end
if Ass.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "missing [Script Info]", r.base)
end
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if string.find(s, "\0", 1, true) then
return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format")
end
s = Sniff.dropBom(s)
s = string.gsub(s, "\r\n", "\n")
s = string.gsub(s, "\r", "\n")
local subs = Types.Subtitles.new()
local info: { [string]: string } = {}
local infoOrder: { string } = {}
local styleFormat: { string }? = nil
local styleOrder: { string } = {}
local eventFormat: { string } = EVENT_FORMAT
local comments = {}
local sections: { { name: string, lines: { string } } } = {}
local section = ""
local stylesName: string? = nil
for _, line in string.split(s, "\n") do
local name = string.match(line, "^%s*%[(.-)%]%s*$")
if name then
section = string.lower(name)
if section == "v4+ styles" or section == "v4 styles" or section == "v4 styles+" then
stylesName = name
section = "styles"
elseif section ~= "script info" and section ~= "events" then
table.insert(sections, { name = name, lines = {} :: { string } })
end
continue
end
if section == "script info" then
if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then
table.insert(infoOrder, line) -- a comment line, kept in place
else
local k, v = string.match(line, "^([^:]+):%s?(.*)$")
if k then
k = trim(k)
if info[k] == nil then
table.insert(infoOrder, k)
end
info[k] = v :: string
end
end
elseif section == "styles" then
local k, v = string.match(line, "^%s*(%a+):%s*(.*)$")
if k == "Format" then
styleFormat = fields(v :: string)
elseif k == "Style" then
local fmt = styleFormat or STYLE_FORMAT
local vals = string.split(v :: string, ",")
local st: { [string]: string } = {}
for fi, f in fmt do
st[f] = trim(vals[fi] or "")
end
local sname = st.Name or ""
if subs.styles[sname] == nil then
table.insert(styleOrder, sname)
end
subs.styles[sname] = st
end
elseif section == "events" then
local k, v = string.match(line, "^%s*(%a+):%s?(.*)$")
if k == "Format" then
eventFormat = fields(v :: string)
elseif k == "Dialogue" or k == "Comment" then
local vals: { string } = {}
local rest = v :: string
for fi = 1, #eventFormat do
if fi == #eventFormat then
vals[fi] = rest
else
local c = string.find(rest, ",", 1, true)
if not c then
vals[fi] = rest
rest = ""
else
vals[fi] = string.sub(rest, 1, c - 1)
rest = string.sub(rest, c + 1)
end
end
end
local cue: { [string]: any } = { text = "", start = 0, stop = 0 }
local ok = true
for fi, f in eventFormat do
local val = vals[fi] or ""
if f == "Start" or f == "End" then
local t = time(val)
if not t then
ok = false
else
cue[if f == "Start" then "start" else "stop"] = t
end
elseif f == "Text" then
cue.raw = val
cue.text = Ass.toMarkup(val)
elseif f == "Style" then
cue.style = trim(val)
elseif f == "Layer" then
cue.layer = tonumber(trim(val)) or 0
else
cue[EVENT_KEY[f] or f] = trim(val)
end
end
if ok then
if k == "Comment" then
cue.after = #subs.cues -- written back after that many dialogue lines
table.insert(comments, cue)
else
table.insert(subs.cues, cue :: any)
end
end
end
elseif section ~= "" then
table.insert(sections[#sections].lines, line)
end
end
subs.meta.scriptInfo = info
subs.meta.scriptInfoOrder = infoOrder
subs.meta.styleFormat = styleFormat
subs.meta.styleOrder = styleOrder
subs.meta.stylesSection = stylesName
subs.meta.eventFormat = eventFormat
if #comments > 0 then
subs.meta.comments = comments
end
if #sections > 0 then
-- drop trailing blank lines (the writer adds its own)
for _, sec in sections do
while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do
table.remove(sec.lines)
end
end
subs.meta.sections = sections
end
subs.meta.source = { format = "ass", scriptType = info.ScriptType }
return subs, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function stamp(t: number): string
local cs = math.floor(t * 100 + 0.5)
return string.format("%d:%02d:%02d.%02d", cs // 360000, cs // 6000 % 60, cs // 100 % 60, cs % 100)
end
local function field(v: any): string
return (string.gsub(tostring(v), "[\r\n,]", " "))
end
function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(subs) ~= "table" or type(subs.cues) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Subtitles value")
end
local meta: any = if type(subs.meta) == "table" then subs.meta else {}
local out = { "[Script Info]" }
local info: any = if type(meta.scriptInfo) == "table" then meta.scriptInfo else {}
local order = if type(meta.scriptInfoOrder) == "table" then meta.scriptInfoOrder else {}
local written: { [string]: boolean } = {}
if info.ScriptType == nil then
table.insert(out, "ScriptType: v4.00+")
end
for _, k in order do
if type(k) == "string" and (string.sub(k, 1, 1) == ";" or string.sub(k, 1, 1) == "!") then
table.insert(out, k)
elseif info[k] ~= nil and not written[k] then
table.insert(out, k .. ": " .. tostring(info[k]))
written[k] = true
end
end
local rest = {}
for k, v in info do
if not written[k] and type(k) == "string" then
table.insert(rest, k .. ": " .. string.gsub(tostring(v), "[\r\n]", " "))
end
end
table.sort(rest)
table.move(rest, 1, #rest, #out + 1, out)
-- styles
local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00"
local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT
table.insert(out, "")
table.insert(out, "[" .. (if type(meta.stylesSection) == "string" then meta.stylesSection elseif ssa then "V4 Styles" else "V4+ Styles") .. "]")
table.insert(out, "Format: " .. table.concat(sfmt, ", "))
local names: { string } = {}
local seen: { [string]: boolean } = {}
if type(meta.styleOrder) == "table" then
for _, nm in meta.styleOrder do
if type(nm) == "string" and type(subs.styles) == "table" and subs.styles[nm] ~= nil and not seen[nm] then
table.insert(names, nm)
seen[nm] = true
end
end
end
local extra = {}
if type(subs.styles) == "table" then
for nm, st in subs.styles do
if type(nm) == "string" and type(st) == "table" and not seen[nm] then
table.insert(extra, nm)
end
end
end
table.sort(extra)
table.move(extra, 1, #extra, #names + 1, names)
if #names == 0 then
names = { "Default" }
end
for _, nm in names do
local st = if type(subs.styles) == "table" and type(subs.styles[nm]) == "table" then subs.styles[nm] else {}
local vals = {}
for fi, f in sfmt do
local v = if f == "Name" then nm else st[f]
vals[fi] = field(if v ~= nil then v else (STYLE_DEFAULT[f] or "0"))
end
table.insert(out, "Style: " .. table.concat(vals, ","))
end
-- events
local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT
if efmt[#efmt] ~= "Text" then
return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text")
end
table.insert(out, "")
table.insert(out, "[Events]")
table.insert(out, "Format: " .. table.concat(efmt, ", "))
local function event(kind: string, c: any, i: number): Err.Err?
if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then
return Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string")
end
local vals = {}
for fi, f in efmt do
local v: any
if f == "Start" then
v = stamp(c.start)
elseif f == "End" then
v = stamp(c.stop)
elseif f == "Style" then
v = field(c.style or names[1])
elseif f == "Text" then
if type(c.raw) == "string" and Ass.toMarkup(c.raw) == c.text then
v = string.gsub(c.raw, "[\r\n]", " ")
else
v = Ass.fromMarkup(c.text)
end
elseif f == "Layer" then
v = tostring(tonumber(c.layer) or 0)
elseif f == "Marked" then
v = field(c.marked or "Marked=0")
else
local key = EVENT_KEY[f] or f
local x = c[key]
v = field(if x ~= nil then x elseif string.sub(f, 1, 6) == "Margin" then "0" else "")
end
vals[fi] = v
end
table.insert(out, kind .. ": " .. table.concat(vals, ","))
return nil
end
local comments = if type(meta.comments) == "table" then meta.comments else {}
local function commentsAfter(n: number?): Err.Err?
for i, c in comments do
if (type(c) == "table" and c.after == n) or (n == nil and (type(c) ~= "table" or type(c.after) ~= "number" or c.after > #subs.cues)) then
local e = event("Comment", c, i)
if e then
return e
end
end
end
return nil
end
for i = 0, #subs.cues do
local e = (if i > 0 then event("Dialogue", subs.cues[i], i) else nil) or commentsAfter(i)
if e then
return nil, e
end
end
local e = commentsAfter(nil)
if e then
return nil, e
end
if type(meta.sections) == "table" then
for _, sec in meta.sections do
if type(sec) == "table" and type(sec.name) == "string" and type(sec.lines) == "table" then
table.insert(out, "")
table.insert(out, "[" .. sec.name .. "]")
for _, l in sec.lines do
table.insert(out, tostring(l))
end
end
end
end
table.insert(out, "")
local nl = if opts and opts.crlf then "\r\n" else "\n"
return buffer.fromstring(table.concat(out, nl)), nil
end
return Ass