Files
rosetta/src/Rosetta/subtitle/ass/init.luau
T

443 lines
14 KiB
Luau

--!strict
-- subtitle/ass: ASS (v4.00+) / SSA (v4.00) scripts (de-facto spec of Aegisub / libass / ffmpeg). Supports: Script
-- Info, Styles, Events (Dialogue / Comment), other sections verbatim, H:MM:SS.cc; {\i1} {\b1} {\u1} {\s1} as the shared
-- markup (cue.raw keeps the original). Not supported: rendering, karaoke timing (\k), embedded font / graphic decoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/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?, -- default 64 MB
}
export type EncodeOptions = {
crlf: boolean?, -- 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" }
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
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
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
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) -- `;` / `!` 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
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
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)
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
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