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 cdcb5b0b77
commit dfe3d3afd3
9 files changed
+1337

No files matched your search

+3
View File
@@ -6,6 +6,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` |
| subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` |
| subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
+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
+109
View File
@@ -0,0 +1,109 @@
-- subtitle/ass tests: ffmpeg's ASS output of a random script (times to the centisecond, text through the override
-- markup), hand-written ASS (styles, comments, commas in text, overrides, [Fonts]) and SSA v4 files against ffmpeg's
-- SRT conversion of them, styles as data, round trips through the encoder, the contract and the fuzz pass.
-- Fixtures: tools/fixtures/subtitles.py.
local T = require("@tests/T")
local Ass = require("@formats/subtitle/ass")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/subtitles")
local t = T.suite("ass")
local function decode(s: string): (any, any)
return Ass.decode(Bytes.reader(buffer.fromstring(s)))
end
local function plain(s: string): string
s = string.gsub(s, "<[^>]*>", "")
s = string.gsub(s, "{[^}]*}", "")
return s
end
local function same(subs: any, want: any, label: string, tol: number)
t:eq(#subs.cues, #want, label .. ": cue count")
for i, w in want do
local c = subs.cues[i]
t:check(math.abs(c.start * 1000 - w.start) <= tol, label .. ": cue " .. i .. " start " .. c.start)
t:check(math.abs(c.stop * 1000 - w.stop) <= tol, label .. ": cue " .. i .. " stop " .. c.stop)
t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text")
end
end
t:eq(Ass.name, "ass", "name")
t:check(Ass.caps.decode and Ass.caps.encode, "caps")
t:eq(Ass.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_ass))), 1, "sniff")
-- ffmpeg converts SRT to ASS with its own rounding (start and duration to centiseconds): within 10 ms
local subs, err = decode(Fx.ffmpeg_ass)
t:check(subs, "ffmpeg ass: " .. tostring(err))
same(subs, Fx.cues, "ffmpeg ass", 10)
t:eq(subs.styles.Default.Fontname, "Arial", "ffmpeg's Default style")
t:eq(subs.meta.scriptInfo.PlayResX, "384", "script info")
for _, h in Fx.hand do
if h.name ~= "vtt" then
local s, e = decode(h.data)
t:check(s, h.name .. ": " .. tostring(e))
same(s, h.cues, h.name .. " vs ffmpeg", 0.5)
end
end
local a = decode(Fx.hand[2].data)
t:eq(a.meta.scriptInfo.Title, "test", "Title")
t:eq(a.meta.scriptInfoOrder[1], "; Script generated by hand", "comment kept in order")
t:eq(a.styles.Top.Fontname, "Verdana", "style field")
t:eq(a.styles.Top.Alignment, "8", "style alignment")
t:eq(a.meta.styleOrder[2], "Top", "style order")
t:eq(a.cues[1].name, "Bob", "actor")
t:eq(a.cues[1].text, "Hello, <i>world</i>!", "italic markup")
t:eq(a.cues[1].raw, "Hello, {\\i1}world{\\i0}!", "raw text")
t:eq(a.cues[2].layer, 1, "layer")
t:eq(a.cues[2].style, "Top", "style")
t:eq(a.cues[2].text, "<b>Bold top</b>\nsecond line", "bold, \\N, an8 dropped")
t:eq(a.cues[3].text, "commas, inside, the text", "commas in the text field")
t:eq(#a.meta.comments, 1, "comment event")
t:eq(a.meta.sections[1].name, "Fonts", "[Fonts] kept")
t:eq(a.meta.sections[1].lines[2], "ABCDEF", "[Fonts] lines")
local ssa = decode(Fx.hand[3].data)
t:eq(ssa.meta.source.scriptType, "v4.00", "SSA script type")
t:eq(ssa.styles.Default.TertiaryColour, "65535", "SSA style field")
t:eq(ssa.cues[1].marked, "Marked=0", "SSA Marked")
-- round trips: the hand files exactly (same fields, same order), and the ffmpeg file through the cues
for _, s in { a, ssa, subs } do
local out = Ass.encode(s) :: buffer
local back = Ass.decode(Bytes.reader(out))
t:check(back, "round trip")
t:eq(#back.cues, #s.cues, "rt count")
for i, c in s.cues do
t:eq(math.floor(back.cues[i].start * 100 + 0.5), math.floor(c.start * 100 + 0.5), "rt start")
t:eq(math.floor(back.cues[i].stop * 100 + 0.5), math.floor(c.stop * 100 + 0.5), "rt stop")
t:eq(back.cues[i].text, c.text, "rt text")
t:eq(back.cues[i].raw, c.raw, "rt raw")
t:eq(back.cues[i].style, c.style, "rt style")
end
for nm, st in s.styles do
for k, v in st do
t:eq(back.styles[nm][k], v, "rt style " .. nm .. "." .. k)
end
end
end
t:eq(buffer.tostring(Ass.encode(a) :: buffer), Fx.hand[2].data, "hand ASS written back byte for byte")
-- cues from another format: markup converted, a Default style made
do
local out = Ass.encode({ kind = "subtitles", cues = { { start = 1, stop = 2.5, text = "<i>it</i> and <b>bold</b>\nline <font color=\"red\">x</font>" } }, styles = {}, meta = {} } :: any) :: buffer
local back = Ass.decode(Bytes.reader(out))
t:eq(back.cues[1].raw, "{\\i1}it{\\i0} and {\\b1}bold{\\b0}\\Nline x", "markup to overrides")
t:check(back.styles.Default ~= nil, "a Default style")
t:eq(back.cues[1].style, "Default", "cue style")
end
do
local _, e = decode("Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,x")
t:check(e and e.code == Err.CORRUPT, "no [Script Info]")
local _, e2 = Ass.encode({ cues = { { start = 0, stop = "x", text = "" } } } :: any)
t:check(e2 and e2.code == Err.ARG, "encode: bad stop")
end
t:fuzz("decode", function(b: buffer)
return Ass.decode(Bytes.reader(b))
end, { Fx.ffmpeg_ass, Fx.hand[2].data, Fx.hand[3].data }, { keepHeader = 13 })
t:done()
+102
View File
@@ -0,0 +1,102 @@
-- subtitle/srt tests: a random SRT script against ffmpeg (its own parse via its srt muxer: times to the millisecond,
-- text), ffmpeg's conversions of WebVTT / ASS / SSA files to SRT, odd layouts (no index, blank lines in text, CRLF,
-- BOM, dot decimals, coordinates), round trips through the encoder, the contract and the fuzz pass.
-- Fixtures: tools/fixtures/subtitles.py.
local T = require("@tests/T")
local Srt = require("@formats/subtitle/srt")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/subtitles")
local t = T.suite("srt")
local function decode(s: string): (any, any)
return Srt.decode(Bytes.reader(buffer.fromstring(s)))
end
local function plain(s: string): string
s = string.gsub(s, "<[^>]*>", "")
s = string.gsub(s, "{[^}]*}", "")
return s
end
local function ms(x: number): number
return math.floor(x * 1000 + 0.5)
end
local function same(subs: any, want: any, label: string)
t:eq(#subs.cues, #want, label .. ": cue count")
for i, w in want do
local c = subs.cues[i]
t:eq(ms(c.start), w.start, label .. ": cue " .. i .. " start")
t:eq(ms(c.stop), w.stop, label .. ": cue " .. i .. " stop")
t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text")
end
end
t:eq(Srt.name, "srt", "name")
t:eq(Srt.category, "subtitle", "category")
t:check(Srt.caps.decode and Srt.caps.encode, "caps")
-- the random script and ffmpeg's re-mux of it
local subs, err = decode(Fx.srt)
t:check(subs, "decode: " .. tostring(err))
same(subs, Fx.cues, "random")
t:eq(subs.cues[3].text, "<u>dog</u>\nalpha dog dog na\195\175ve alpha", "markup and lines kept")
t:eq(subs.cues[1].id, "1", "id")
same(decode(Fx.ffmpeg_srt), Fx.cues, "ffmpeg srt")
t:eq(Srt.sniff(Bytes.reader(buffer.fromstring(Fx.srt))), 0.9, "sniff")
t:eq(Srt.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_vtt))), 0, "sniff a vtt")
for _, h in Fx.hand do
same(decode(h.ffmpeg_srt), h.cues, "ffmpeg " .. h.name .. " -> srt")
end
-- odd layouts
do
local s = "\239\187\1911\r\n00:00:01.5 --> 00:00:02,25 X1:10 X2:20 Y1:5 Y2:6\r\nfirst\r\n\r\nsecond paragraph\r\n\r\n\r\n00:00:03,000 --> 00:00:04,000\r\nno index\r\n2\r\n00:00:05,000-->00:00:06,000\r\n"
local r = decode(s)
t:check(r, "odd layouts")
t:eq(#r.cues, 3, "odd: count")
t:eq(r.cues[1].start, 1.5, "odd: 1-digit fraction")
t:eq(r.cues[1].stop, 2.25, "odd: 2-digit fraction")
t:eq(r.cues[1].text, "first\n\nsecond paragraph", "odd: blank line inside a cue")
t:eq(r.cues[1].settings, "X1:10 X2:20 Y1:5 Y2:6", "odd: coordinates")
t:eq(r.cues[2].text, "no index", "odd: cue without an index, the next index stripped")
t:eq(r.cues[2].id, nil, "odd: no id")
t:eq(r.cues[3].text, "", "odd: empty cue")
local again = decode(buffer.tostring(Srt.encode(r) :: buffer))
t:eq(again.cues[1].text, r.cues[1].text, "odd: round trip keeps the blank line")
t:eq(again.cues[1].settings, r.cues[1].settings, "odd: round trip keeps the coordinates")
end
-- round trips (LF and CRLF)
for _, crlf in { false, true } do
local out = Srt.encode(subs, { crlf = crlf }) :: buffer
local back = Srt.decode(Bytes.reader(out))
t:check(back, "round trip decode")
t:eq(#back.cues, #subs.cues, "round trip count")
for i, c in subs.cues do
t:eq(ms(back.cues[i].start), ms(c.start), "round trip start " .. i)
t:eq(ms(back.cues[i].stop), ms(c.stop), "round trip stop " .. i)
t:eq(back.cues[i].text, c.text, "round trip text " .. i)
end
if not crlf then
t:eq(buffer.tostring(out), Fx.srt, "the encoder writes the canonical file byte for byte")
end
end
-- errors
do
local _, e = decode("just some text\nno timings")
t:check(e and e.code == Err.CORRUPT, "no cues: " .. tostring(e))
local _, e2 = decode("1\n00:00:01,000 --> 00:00:02,000\n\0bin")
t:check(e2 and e2.code == Err.CORRUPT, "NUL bytes")
local empty = decode("")
t:check(empty and #empty.cues == 0, "empty file: no cues")
local _, e3 = Srt.encode({ cues = { { start = -1, stop = 1, text = "x" } } } :: any)
t:check(e3 and e3.code == Err.ARG, "encode: negative time")
local _, e4 = Srt.encode(5 :: any)
t:check(e4 and e4.code == Err.ARG, "encode: not Subtitles")
end
t:fuzz("decode", function(b: buffer)
return Srt.decode(Bytes.reader(b))
end, { Fx.srt, Fx.ffmpeg_srt, Fx.hand[1].ffmpeg_srt })
t:done()
+95
View File
@@ -0,0 +1,95 @@
-- subtitle/vtt tests: ffmpeg's WebVTT output of a random script (times, text), a hand-written file with a header,
-- STYLE / REGION / NOTE blocks, ids, settings and hour timestamps against ffmpeg's SRT conversion of it, round trips
-- through the encoder, the contract and the fuzz pass. Fixtures: tools/fixtures/subtitles.py.
local T = require("@tests/T")
local Vtt = require("@formats/subtitle/vtt")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/subtitles")
local t = T.suite("vtt")
local function decode(s: string): (any, any)
return Vtt.decode(Bytes.reader(buffer.fromstring(s)))
end
local function plain(s: string): string
s = string.gsub(s, "<[^>]*>", "")
s = string.gsub(s, "{[^}]*}", "")
s = string.gsub(s, "&amp;", "&")
return s
end
local function ms(x: number): number
return math.floor(x * 1000 + 0.5)
end
local function same(subs: any, want: any, label: string)
t:eq(#subs.cues, #want, label .. ": cue count")
for i, w in want do
local c = subs.cues[i]
t:eq(ms(c.start), w.start, label .. ": cue " .. i .. " start")
t:eq(ms(c.stop), w.stop, label .. ": cue " .. i .. " stop")
t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text")
end
end
t:eq(Vtt.name, "vtt", "name")
t:check(Vtt.caps.decode and Vtt.caps.encode, "caps")
t:eq(Vtt.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_vtt))), 1, "sniff")
t:eq(Vtt.sniff(Bytes.reader(buffer.fromstring("WEBVTTX"))), 0, "sniff WEBVTTX")
local subs, err = decode(Fx.ffmpeg_vtt)
t:check(subs, "ffmpeg vtt: " .. tostring(err))
same(subs, Fx.cues, "ffmpeg vtt")
local hand
for _, h in Fx.hand do
if h.name == "vtt" then
hand = h
end
end
local v, verr = decode(hand.data)
t:check(v, "hand vtt: " .. tostring(verr))
same(v, hand.cues, "hand vtt vs ffmpeg")
t:eq(v.meta.header, "- a test file\nKind: captions", "header")
t:eq(v.meta.css[1], "::cue { color: yellow }", "STYLE")
t:eq(v.meta.regions[1], "id:r1 width:40%", "REGION")
t:eq(v.meta.notes[1], "this is a comment\nover two lines", "NOTE")
t:eq(v.cues[1].id, "intro", "id")
t:eq(v.cues[1].settings, "align:start position:10%", "settings")
t:eq(v.cues[1].text, "<v Roger>Hello <i>there</i></v>", "text kept")
t:eq(v.cues[3].settings, "line:0", "settings 3")
for _, s in { subs, v } do
local out = Vtt.encode(s) :: buffer
local back = Vtt.decode(Bytes.reader(out))
t:check(back, "round trip")
t:eq(#back.cues, #s.cues, "round trip count")
for i, c in s.cues do
t:eq(ms(back.cues[i].start), ms(c.start), "rt start")
t:eq(ms(back.cues[i].stop), ms(c.stop), "rt stop")
t:eq(back.cues[i].text, c.text, "rt text")
t:eq(back.cues[i].id, c.id, "rt id")
t:eq(back.cues[i].settings, c.settings, "rt settings")
end
t:eq(back.meta.header, s.meta.header, "rt header")
end
do
local back = decode(buffer.tostring(Vtt.encode(v) :: buffer))
t:eq(back.meta.css[1], v.meta.css[1], "rt css")
t:eq(back.meta.regions[1], v.meta.regions[1], "rt region")
-- text that WebVTT cannot hold
local w = Vtt.encode({ kind = "subtitles", cues = { { start = 0, stop = 1, text = "a\n\nb --> c" } }, styles = {}, meta = {} } :: any) :: buffer
local wb = Vtt.decode(Bytes.reader(w))
t:eq(wb.cues[1].text, "a\nb --&gt; c", "blank lines dropped, arrow escaped")
end
do
local _, e = decode("1\n00:00:01,000 --> 00:00:02,000\nx")
t:check(e and e.code == Err.CORRUPT, "no signature")
local _, e2 = Vtt.encode({ cues = { { start = 0, stop = 1 } } } :: any)
t:check(e2 and e2.code == Err.ARG, "encode: cue without text")
end
t:fuzz("decode", function(b: buffer)
return Vtt.decode(Bytes.reader(b))
end, { Fx.ffmpeg_vtt, hand.data }, { keepHeader = 6 })
t:done()
+140
View File
@@ -0,0 +1,140 @@
# Subtitle fixtures (tests/gen/subtitles.luau, for tests/subtitle/srt.luau, vtt.luau and ass.luau) with
# ffmpeg as the reference: a random SRT script converted by ffmpeg to SRT / WebVTT / ASS, and hand-written WebVTT /
# ASS / SSA files with their features, converted by ffmpeg to SRT. Every case carries the expected cues
# ({ start_ms, stop_ms, plain text }) so the tests compare our decode with ffmpeg's view of the same file.
import os, random, re, shutil, subprocess, tempfile
WORDS = ["alpha", "beta", "gamma", "delta", "omega", "café", "naïve", "日本", "fox", "dog", "42", "hello", "world"]
def ffmpeg(ctx, src_bytes, src_ext, dst_ext):
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "in." + src_ext)
dst = os.path.join(d, "out." + dst_ext)
open(src, "wb").write(src_bytes)
argv = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, dst]
if shutil.which("ffmpeg"):
subprocess.run(argv, check=True, capture_output=True)
else:
ctx.nix("ffmpeg", argv)
return open(dst, "rb").read()
def plain(s):
return re.sub(r"{[^}]*}", "", re.sub(r"<[^>]*>", "", s)).replace("&amp;", "&")
def srt_time(ms):
return "%02d:%02d:%02d,%03d" % (ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
def random_srt(rng, n):
cues, t = [], 500
for i in range(n):
start = t + rng.randrange(0, 3000)
stop = start + rng.randrange(300, 5000)
t = stop
lines = []
for _ in range(rng.randrange(1, 3)):
words = [rng.choice(WORDS) for _ in range(rng.randrange(1, 6))]
if rng.random() < 0.3:
k = rng.randrange(len(words))
tag = rng.choice("ibu")
words[k] = "<%s>%s</%s>" % (tag, words[k], tag)
lines.append(" ".join(words))
cues.append((start, stop, "\n".join(lines)))
text = "".join("%d\n%s --> %s\n%s\n\n" % (i + 1, srt_time(a), srt_time(b), t) for i, (a, b, t) in enumerate(cues))
return text.encode(), [{"start": a, "stop": b, "plain": plain(t)} for a, b, t in cues]
VTT = """WEBVTT - a test file
Kind: captions
STYLE
::cue { color: yellow }
REGION
id:r1 width:40%
NOTE this is a comment
over two lines
intro
00:01.000 --> 00:04.500 align:start position:10%
<v Roger>Hello <i>there</i></v>
00:05.250 --> 00:07.000
first line
second line
01:00:02.000 --> 01:00:03.123 line:0
<c.loud>an hour in</c> &amp; more
"""
ASS = """[Script Info]
; Script generated by hand
Title: test
ScriptType: v4.00+
PlayResX: 640
PlayResY: 480
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
Style: Top,Verdana,24,&H0000FFFF,&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,2,0,8,10,10,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:03.50,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}!
Comment: 0,0:00:02.00,0:00:04.00,Default,,0,0,0,,a comment line
Dialogue: 1,0:00:04.20,0:00:06.00,Top,,0,0,0,,{\\an8\\b1}Bold top{\\b0}\\Nsecond line
Dialogue: 0,0:01:02.03,0:01:05.99,Default,,0,0,0,,{\\pos(10,20)}commas, inside, the text
[Fonts]
fontname: x.ttf
ABCDEF
"""
SSA = """[Script Info]
Title: old
ScriptType: v4.00
[V4 Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding
Style: Default,Tahoma,24,16777215,65535,65535,-2147483640,-1,0,1,3,0,2,30,30,30,0,0
[Events]
Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: Marked=0,0:00:00.50,0:00:02.00,Default,,0000,0000,0000,,old style
Dialogue: Marked=0,0:00:02.50,0:00:04.25,Default,,0000,0000,0000,,{\\i1}two{\\i0}\\Nlines
"""
def parse_srt(data):
"""the cues of an SRT (ffmpeg's output) -> [{start, stop, plain}]"""
out = []
text = data.decode("utf-8-sig").replace("\r\n", "\n")
for block in re.split(r"\n\s*\n", text.strip()):
lines = block.split("\n")
for k, l in enumerate(lines):
m = re.match(r"(\d+):(\d+):(\d+)[,.](\d+) --> (\d+):(\d+):(\d+)[,.](\d+)", l)
if m:
g = [int(x) for x in m.groups()]
out.append({"start": ((g[0] * 60 + g[1]) * 60 + g[2]) * 1000 + g[3], "stop": ((g[4] * 60 + g[5]) * 60 + g[6]) * 1000 + g[7], "plain": plain("\n".join(lines[k + 1:]))})
break
return out
def generate(ctx):
rng = random.Random(7)
src, cues = random_srt(rng, 40)
out = {"srt": src, "cues": cues}
for ext in ("srt", "vtt", "ass"):
out["ffmpeg_" + ext] = ffmpeg(ctx, src, "srt", ext)
hand = []
for name, ext, data in (("vtt", "vtt", VTT), ("ass", "ass", ASS), ("ssa", "ssa", SSA)):
b = data.encode()
ref = ffmpeg(ctx, b, ext, "srt")
hand.append({"name": name, "data": b, "ffmpeg_srt": ref, "cues": parse_srt(ref)})
out["hand"] = hand
ctx.emit("subtitles", out)