vec: subtitle/srt, subtitle/vtt, subtitle/ass (SSA too) read + write into Subtitles; tests against ffmpeg conversions, round trips, fuzz

This commit is contained in:
4DBug committed 2026-10-31 08:27:04 -05:00
1 parent ccb06775c5
commit 2521f3dfa6
9 files changed
+1337

No files matched your search

+36
View File
@@ -26,6 +26,42 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "ass",
category = "subtitle",
path = "subtitle/ass",
extensions = { "ass", "ssa" },
mime = { "text/x-ssa", "text/x-ass" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
load = function()
return require("@formats/subtitle/ass")
end,
},
{
name = "srt",
category = "subtitle",
path = "subtitle/srt",
extensions = { "srt" },
mime = { "application/x-subrip", "text/srt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = false },
load = function()
return require("@formats/subtitle/srt")
end,
},
{
name = "vtt",
category = "subtitle",
path = "subtitle/vtt",
extensions = { "vtt", "webvtt" },
mime = { "text/vtt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
load = function()
return require("@formats/subtitle/vtt")
end,
},
}
return list
+459
View File
@@ -0,0 +1,459 @@
--!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.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
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" },
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 = r:peek(64)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
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
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
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 = {} })
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
+181
View File
@@ -0,0 +1,181 @@
--!strict
-- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or
-- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing
-- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends
-- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> /
-- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text.
-- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Srt = {
name = "srt",
category = "subtitle",
extensions = { "srt" },
mime = { "application/x-subrip", "text/srt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = false },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {
crlf: boolean?, -- CRLF line ends (default false: LF)
}
-- ------------------------------------------------------------------------------------------------ constants
local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$"
-- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary)
local function text(r: Bytes.Reader): string?
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if string.find(s, "\0", 1, true) then
return nil
end
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
s = string.gsub(s, "\r\n", "\n")
s = string.gsub(s, "\r", "\n")
return s
end
local function frac(digits: string): number
return (tonumber(digits) :: number) / 10 ^ #digits
end
-- timing(line) -> start, stop, settings | nil
local function timing(line: string): (number?, number?, string?)
local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING)
if not h1 then
return nil, nil, nil
end
local a = tonumber(h1) :: number * 3600 + tonumber(m1) :: number * 60 + tonumber(s1) :: number + frac(f1 :: string)
local b = tonumber(h2) :: number * 3600 + tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string)
return a, b, rest
end
-- ------------------------------------------------------------------------------------------------ sniff
function Srt.sniff(r: Bytes.Reader): number
local head = r:peek(512)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
head = string.gsub(head, "\r", "\n")
local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)")
if first and string.match(first, "^%d+%s*$") and second and timing(second) then
return 0.9
end
if first and timing(first) then
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Srt.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
local s = text(r)
if not s then
return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format")
end
local lines = string.split(s, "\n")
local n = #lines
local subs = Types.Subtitles.new()
local i = 1
local function isStart(k: number): boolean -- a cue starts at line k (index + timing, or a timing)
local l = lines[k]
if l == nil then
return false
end
if timing(l) then
return true
end
return string.match(l, "^%s*%d+%s*$") ~= nil and lines[k + 1] ~= nil and timing(lines[k + 1]) ~= nil
end
while i <= n do
local line = lines[i]
local a, b, settings = timing(line)
if a then
local id: string? = nil
if i > 1 then
local prev = string.match(lines[i - 1], "^%s*(%d+)%s*$")
id = prev
end
i += 1
local body = {}
while i <= n do
local l = lines[i]
if string.match(l, "^%s*$") then
-- blank: the end of the cue unless more text follows before the next cue
local k = i
while k <= n and string.match(lines[k], "^%s*$") do
k += 1
end
if k > n or isStart(k) then
break
end
for _ = i, k - 1 do
table.insert(body, "")
end
i = k
elseif timing(l) then
break -- a cue without the blank separator
else
table.insert(body, l)
i += 1
end
end
-- an index line right before the next timing belongs to the next cue
if #body > 0 and i <= n and timing(lines[i]) and string.match(body[#body], "^%s*%d+%s*$") then
table.remove(body)
end
local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(body, "\n"), id = id }
if settings and settings ~= "" then
cue.settings = settings
end
table.insert(subs.cues, cue)
else
i += 1
end
end
if #subs.cues == 0 and string.find(s, "%S") then
return nil, Err.new(Err.CORRUPT, "no cues (no `-->` timing line)")
end
subs.meta.source = { format = "srt" }
return subs, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function stamp(t: number): string
local ms = math.floor(t * 1000 + 0.5)
return string.format("%02d:%02d:%02d,%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
end
function Srt.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 nl = if opts and opts.crlf then "\r\n" else "\n"
local out = table.create(#subs.cues)
for i, c in subs.cues do
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 nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string")
end
-- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue
local body = string.gsub(c.text, "\r\n?", "\n")
local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else ""
out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl
end
return buffer.fromstring(table.concat(out, nl) .. nl), nil
end
return Srt
+212
View File
@@ -0,0 +1,212 @@
--!strict
-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in
-- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments
-- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept
-- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities).
-- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text
-- are dropped and `-->` escaped (WebVTT cue text cannot hold them).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Vtt = {
name = "vtt",
category = "subtitle",
extensions = { "vtt", "webvtt" },
mime = { "text/vtt" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, styles = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
}
export type EncodeOptions = {}
-- ------------------------------------------------------------------------------------------------ constants
local function frac(digits: string): number
return (tonumber(digits) :: number) / 10 ^ #digits
end
-- one timestamp at the start of s: seconds, the rest | nil
local function timestamp(s: string): (number?, string)
local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$")
if h then
return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + frac(f :: string), rest :: string
end
local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$")
if m2 then
return tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string), rest2 :: string
end
return nil, s
end
-- timing(line) -> start, stop, settings | nil
local function timing(line: string): (number?, number?, string?)
local a, rest = timestamp((string.gsub(line, "^%s+", "")))
if not a then
return nil, nil, nil
end
local after = string.match(rest, "^%s*%-%->%s*(.*)$")
if not after then
return nil, nil, nil
end
local b, rest2 = timestamp(after)
if not b then
return nil, nil, nil
end
local settings = string.match(rest2, "^%s*(.-)%s*$") or ""
return a, b, settings
end
-- ------------------------------------------------------------------------------------------------ sniff
function Vtt.sniff(r: Bytes.Reader): number
local head = r:peek(10)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.sub(head, 1, 6) == "WEBVTT" then
local c = string.sub(head, 7, 7)
if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then
return 1
end
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vtt.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 Vtt.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", 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
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
s = string.gsub(s, "\r\n", "\n")
s = string.gsub(s, "\r", "\n")
local lines = string.split(s, "\n")
local n = #lines
local subs = Types.Subtitles.new()
-- the header block: WEBVTT[ text] + lines up to the first blank
local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" }
local i = 2
while i <= n and lines[i] ~= "" do
table.insert(header, lines[i])
i += 1
end
if #header > 1 or header[1] ~= "" then
subs.meta.header = table.concat(header, "\n")
end
local notes, css, regions = {}, {}, {}
while i <= n do
if lines[i] == "" then
i += 1
continue
end
-- a block: lines up to the next blank
local first = i
while i <= n and lines[i] ~= "" do
i += 1
end
local block = table.move(lines, first, i - 1, 1, {})
local head = block[1]
if string.match(head, "^NOTE[ \t]") or head == "NOTE" then
table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", "")))
elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then
table.insert(css, table.concat(block, "\n", 2))
elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then
table.insert(regions, table.concat(block, "\n", 2))
else
local k, id = 1, nil
local a, b, settings = timing(block[1])
if not a and block[2] then
id = block[1]
k = 2
a, b, settings = timing(block[2])
end
if a then
local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(block, "\n", k + 1), id = id }
if settings and settings ~= "" then
cue.settings = settings
end
table.insert(subs.cues, cue)
end
-- a block with no timing is skipped (the spec's parser ignores it)
end
end
if #notes > 0 then
subs.meta.notes = notes
end
if #css > 0 then
subs.meta.css = css
end
if #regions > 0 then
subs.meta.regions = regions
end
subs.meta.source = { format = "vtt" }
return subs, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function stamp(t: number): string
local ms = math.floor(t * 1000 + 0.5)
return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
end
-- one block's text: no blank lines (they end a block), no `-->`
local function clean(s: string): string
s = string.gsub(s, "\r\n?", "\n")
s = string.gsub(s, "\n[ \t]*\n", "\n")
s = string.gsub(s, "\n[ \t]*\n", "\n")
s = string.gsub(s, "^\n+", "")
s = string.gsub(s, "%-%->", "--&gt;")
return s
end
function Vtt.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 = {}
local header = if type(meta.header) == "string" and meta.header ~= "" then meta.header else nil
if header then
local h = string.gsub(clean(header), "%-%-&gt;", "")
table.insert(out, "WEBVTT " .. h .. "\n")
else
table.insert(out, "WEBVTT\n")
end
for _, key in { "regions", "css" } do
local list = meta[key]
if type(list) == "table" then
for _, b in list do
if type(b) == "string" then
table.insert(out, (if key == "css" then "STYLE\n" else "REGION\n") .. clean(b) .. "\n")
end
end
end
end
for i, c in subs.cues do
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 nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string")
end
local id = if type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) then (string.gsub(c.id, "[\r\n]", " ")) .. "\n" else ""
local settings = if type(c.settings) == "string" and c.settings ~= "" then " " .. (string.gsub(c.settings, "[\r\n]", " ")) else ""
local body = clean(c.text)
table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (if body ~= "" then "\n" else ""))
end
return buffer.fromstring(table.concat(out, "\n")), nil
end
return Vtt