Files
rosetta/src/Formats/video/mkv/Parse.luau
T
4DBug d73b93c740 ws-apifix: videos save as animated images (F.save(video, gif | apng | webp), F.convert(avi, "gif"): frames / fps / maxFrames (300) / maxPixels (2^25)); VideoFrame.index restarts at the seek position; F.detect names WebM files "webm"
api: encoderFor finds image formats for a VideoDecoder, videoToImage() collects the frames; F.detect asks a
format's optional variant(r) for a more precise name (video/mkv: Mkv.variant, from Parse.docType).
codecs/video/Video: index after seek = round(pts * frameRate) + 1.
2026-10-31 14:00:36 -05:00

692 lines
20 KiB
Luau

--!strict
-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles
-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration,
-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression,
-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by
-- default). Interpreted (it only walks headers); never throws.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Ebml = require("@formats/containers/Ebml")
local Demux = require("@formats/containers/Demux")
local Video = require("@formats/codecs/video/Video")
local Deflate = require("@formats/codecs/compress/Deflate")
local Parse = {}
-- element IDs
local ID = {
EBML = 0x1A45DFA3,
DocType = 0x4282,
Segment = 0x18538067,
SeekHead = 0x114D9B74,
Info = 0x1549A966,
TimecodeScale = 0x2AD7B1,
Duration = 0x4489,
Title = 0x7BA9,
MuxingApp = 0x4D80,
WritingApp = 0x5741,
DateUTC = 0x4461,
Tracks = 0x1654AE6B,
TrackEntry = 0xAE,
TrackNumber = 0xD7,
TrackUID = 0x73C5,
TrackType = 0x83,
FlagEnabled = 0xB9,
FlagDefault = 0x88,
FlagForced = 0x55AA,
FlagLacing = 0x9C,
DefaultDuration = 0x23E383,
Name = 0x536E,
Language = 0x22B59C,
LanguageBCP47 = 0x22B59D,
CodecID = 0x86,
CodecPrivate = 0x63A2,
CodecDelay = 0x56AA,
SeekPreRoll = 0x56BB,
Video = 0xE0,
PixelWidth = 0xB0,
PixelHeight = 0xBA,
DisplayWidth = 0x54B0,
DisplayHeight = 0x54BA,
ColourSpace = 0x2EB524,
Audio = 0xE1,
SamplingFrequency = 0xB5,
OutputSamplingFrequency = 0x78B5,
Channels = 0x9F,
BitDepth = 0x6264,
ContentEncodings = 0x6D80,
ContentEncoding = 0x6240,
ContentEncodingType = 0x5033,
ContentEncodingScope = 0x5032,
ContentCompression = 0x5034,
ContentCompAlgo = 0x4254,
ContentCompSettings = 0x4255,
ContentEncryption = 0x5035,
Cluster = 0x1F43B675,
Timecode = 0xE7,
SimpleBlock = 0xA3,
BlockGroup = 0xA0,
Block = 0xA1,
BlockDuration = 0x9B,
ReferenceBlock = 0xFB,
DiscardPadding = 0x75A2,
Cues = 0x1C53BB6B,
CuePoint = 0xBB,
CueTime = 0xB3,
CueTrackPositions = 0xB7,
CueTrack = 0xF7,
CueClusterPosition = 0xF1,
CueRelativePosition = 0xF0,
Tags = 0x1254C367,
Tag = 0x7373,
SimpleTag = 0x67C8,
TagName = 0x45A3,
TagString = 0x4487,
Targets = 0x63C0,
Chapters = 0x1043A770,
Attachments = 0x1941A469,
Void = 0xEC,
Crc32 = 0xBF,
}
Parse.ID = ID
-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts)
local TOP: { [number]: boolean } = {
[ID.SeekHead] = true,
[ID.Info] = true,
[ID.Tracks] = true,
[ID.Cluster] = true,
[ID.Cues] = true,
[ID.Tags] = true,
[ID.Chapters] = true,
[ID.Attachments] = true,
[ID.Segment] = true,
[ID.EBML] = true,
}
-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/video/Video registry)
local AUDIO: { [string]: string } = {
A_VORBIS = "vorbis",
A_OPUS = "opus",
A_FLAC = "flac",
["A_MPEG/L3"] = "mp3",
["A_MPEG/L2"] = "mp2",
["A_MPEG/L1"] = "mp1",
A_AAC = "aac",
["A_AAC/MPEG4/LC"] = "aac",
["A_AAC/MPEG4/LC/SBR"] = "aac",
["A_AAC/MPEG2/LC"] = "aac",
A_AC3 = "ac3",
A_EAC3 = "eac3",
A_DTS = "dts",
A_ALAC = "alac",
A_TTA1 = "tta",
A_WAVPACK4 = "wavpack",
["A_MS/ACM"] = "acm",
}
local SUBS: { [string]: string } = {
["S_TEXT/UTF8"] = "text",
["S_TEXT/ASCII"] = "text",
["S_TEXT/WEBVTT"] = "webvtt",
["S_TEXT/ASS"] = "ass",
["S_TEXT/SSA"] = "ssa",
["S_ASS"] = "ass",
["S_SSA"] = "ssa",
["S_VOBSUB"] = "dvdsub",
["S_HDMV/PGS"] = "pgs",
}
-- codecFor(CodecID, bitDepth) -> our codec id
local function codecFor(id: string, kind: string, bits: number?): string
if kind == "video" then
return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", "")))
end
if id == "A_PCM/INT/LIT" then
return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le"
elseif id == "A_PCM/INT/BIG" then
return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be"
elseif id == "A_PCM/FLOAT/IEEE" then
return "pcm_f" .. (bits or 32) .. "le"
end
return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", "")))
end
Parse.codecFor = codecFor
type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? }
local function parseVideo(buf: buffer, off: number, len: number, t: any)
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.PixelWidth then
t.width = Ebml.uint(buf, o, n)
elseif id == ID.PixelHeight then
t.height = Ebml.uint(buf, o, n)
elseif id == ID.DisplayWidth then
t.displayWidth = Ebml.uint(buf, o, n)
elseif id == ID.DisplayHeight then
t.displayHeight = Ebml.uint(buf, o, n)
elseif id == ID.ColourSpace then
t.colourSpace = buffer.readstring(buf, o, math.min(n, 4))
end
end
end
local function parseAudio(buf: buffer, off: number, len: number, t: any)
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.SamplingFrequency then
t.sampleRate = Ebml.float(buf, o, n)
elseif id == ID.OutputSamplingFrequency then
t.outputSampleRate = Ebml.float(buf, o, n)
elseif id == ID.Channels then
t.channels = Ebml.uint(buf, o, n)
elseif id == ID.BitDepth then
t.bitsPerSample = Ebml.uint(buf, o, n)
end
end
end
-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption
-- are not
local function parseEncodings(buf: buffer, off: number, len: number, t: any): string?
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.ContentEncoding then
local etype = 0
local scope = 1
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.ContentEncodingScope then
scope = Ebml.uint(buf, o2, n2)
elseif id2 == ID.ContentEncodingType then
etype = Ebml.uint(buf, o2, n2)
elseif id2 == ID.ContentCompression then
local algo, settings = 0, nil
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
if id3 == ID.ContentCompAlgo then
algo = Ebml.uint(buf, o3, n3)
elseif id3 == ID.ContentCompSettings then
settings = Ebml.binary(buf, o3, n3)
end
end
if algo == 3 then
t.strip = settings
elseif algo == 0 then
t.zlib = scope -- 1: frames, 2: CodecPrivate
else
return "content compression algorithm " .. algo
end
elseif id2 == ID.ContentEncryption then
return "encrypted track"
end
end
if etype ~= 0 then
return "encrypted track"
end
end
end
return nil
end
local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string })
local tracks: { TrackInfo } = {}
local problems: { [number]: string } = {}
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.TrackEntry then
local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" }
local ttype, codecId = 0, ""
local problem: string? = nil
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.TrackNumber then
t.id = Ebml.uint(buf, o2, n2)
elseif id2 == ID.TrackUID then
t.uid = Ebml.uint(buf, o2, n2)
elseif id2 == ID.TrackType then
ttype = Ebml.uint(buf, o2, n2)
elseif id2 == ID.FlagDefault then
t.default = Ebml.uint(buf, o2, n2) ~= 0
elseif id2 == ID.FlagEnabled then
t.enabled = Ebml.uint(buf, o2, n2) ~= 0
elseif id2 == ID.FlagLacing then
t.lacing = Ebml.uint(buf, o2, n2) ~= 0
elseif id2 == ID.DefaultDuration then
t.defaultDurationNs = Ebml.uint(buf, o2, n2)
elseif id2 == ID.Name then
t.name = Ebml.string(buf, o2, n2)
elseif id2 == ID.Language then
t.language = Ebml.string(buf, o2, n2)
elseif id2 == ID.CodecID then
codecId = Ebml.string(buf, o2, n2)
elseif id2 == ID.CodecPrivate then
t.config = Ebml.binary(buf, o2, n2)
elseif id2 == ID.CodecDelay then
t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9
elseif id2 == ID.SeekPreRoll then
t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9
elseif id2 == ID.Video then
parseVideo(buf, o2, n2, t)
elseif id2 == ID.Audio then
parseAudio(buf, o2, n2, t)
elseif id2 == ID.ContentEncodings then
problem = parseEncodings(buf, o2, n2, t)
end
end
if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then
local c = Deflate.zlib(t.config)
if c then
t.config = c
else
problem = "bad zlib-compressed CodecPrivate"
end
end
t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data"
t.codecTag = codecId
t.codec = codecFor(codecId, t.kind, t.bitsPerSample)
if t.kind == "audio" then
t.sampleRate = t.sampleRate or 8000
t.channels = t.channels or 1
end
if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then
t.frameRate = 1e9 / t.defaultDurationNs
end
if t.id > 0 then
table.insert(tracks, t)
if problem then
problems[t.id] = problem
end
end
end
end
return tracks, problems
end
local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?)
local scale, duration = 1000000, nil
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.TimecodeScale then
scale = Ebml.uint(buf, o, n)
elseif id == ID.Duration then
duration = Ebml.float(buf, o, n)
elseif id == ID.Title then
meta.title = Ebml.string(buf, o, n)
elseif id == ID.MuxingApp then
meta.muxingApp = Ebml.string(buf, o, n)
elseif id == ID.WritingApp then
meta.writingApp = Ebml.string(buf, o, n)
end
end
if scale <= 0 then
scale = 1000000
end
return scale, duration
end
local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } }
local cues = {}
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.CuePoint then
local time = 0
local positions = {}
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.CueTime then
time = Ebml.uint(buf, o2, n2)
elseif id2 == ID.CueTrackPositions then
local tr, pos = 0, 0
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
if id3 == ID.CueTrack then
tr = Ebml.uint(buf, o3, n3)
elseif id3 == ID.CueClusterPosition then
pos = Ebml.uint(buf, o3, n3)
end
end
table.insert(positions, { tr, pos })
end
end
for _, p in positions do
table.insert(cues, { time = time, track = p[1], position = segData + p[2] })
end
end
end
return cues
end
local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any })
local tags = meta.tags or {}
meta.tags = tags
for id, o, n in Ebml.children(buf, off, off + len) do
if id == ID.Tag then
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if id2 == ID.SimpleTag then
local name, value = nil, nil
for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do
if id3 == ID.TagName then
name = Ebml.string(buf, o3, n3)
elseif id3 == ID.TagString then
value = Ebml.string(buf, o3, n3)
end
end
if name and value and tags[string.lower(name)] == nil then
tags[string.lower(name)] = value
end
end
end
end
end
end
type Ctx = {
buf: buffer,
dmx: any,
byNum: { [number]: TrackInfo },
scaleNs: number,
err: string?,
maxPackets: number,
}
-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing
local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?)
local buf = ctx.buf
local limit = off + len
local tn, tl = Ebml.vint(buf, off, limit)
if not tn or not tl or tn < 0 or off + tl + 3 > limit then
return
end
local p = off + tl
local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1)
if rel >= 32768 then
rel -= 65536
end
local flags = buffer.readu8(buf, p + 2)
p += 3
local t = ctx.byNum[tn]
if not t then
return
end
local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false)
if t.kind == "audio" or t.kind == "subtitle" then
key = true
end
local pts = clusterTime + rel
local lacing = bit32.band(bit32.rshift(flags, 1), 3)
local sizes: { number } = {}
if lacing == 0 then
sizes[1] = limit - p
else
if p >= limit then
return
end
local count = buffer.readu8(buf, p) + 1
p += 1
if lacing == 1 then -- Xiph
local total = 0
for k = 1, count - 1 do
local s = 0
while true do
if p >= limit then
return
end
local b = buffer.readu8(buf, p)
p += 1
s += b
if b ~= 255 then
break
end
end
sizes[k] = s
total += s
end
sizes[count] = limit - p - total
elseif lacing == 3 then -- EBML
local s, l = Ebml.vint(buf, p, limit)
if not s or not l or s < 0 then
return
end
p += l
sizes[1] = s
local total = s
for k = 2, count - 1 do
local d, dl = Ebml.svint(buf, p, limit)
if not d or not dl then
return
end
p += dl
s += d
if s < 0 then
return
end
sizes[k] = s
total += s
end
sizes[count] = limit - p - total
else -- fixed
local each = (limit - p) // count
for k = 1, count do
sizes[k] = each
end
end
if sizes[count] < 0 then
return
end
end
-- frames after the first of a lace: the track's default duration
local stepTicks = 0
if t.defaultDurationNs and t.defaultDurationNs > 0 then
stepTicks = t.defaultDurationNs / ctx.scaleNs
elseif durTicks and #sizes > 0 then
stepTicks = durTicks / #sizes
end
local dmx = ctx.dmx
for k, s in sizes do
if p + s > limit then
return
end
if dmx.n >= ctx.maxPackets then
ctx.err = "too many packets"
return
end
local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil)
local kf = key and (k == 1 or t.kind ~= "video")
local strip = t.strip
local z = (t :: any).zlib
if z and bit32.band(z, 1) ~= 0 then
local out = Deflate.zlib(buf, p, s)
if out then
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out)
end
elseif strip then
local nb = buffer.create(buffer.len(strip) + s)
buffer.copy(nb, 0, strip)
buffer.copy(nb, buffer.len(strip), buf, p, s)
dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb)
else
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s)
end
if discardNs and k == #sizes then
dmx:setExtra("discardPadding", discardNs / 1e9)
end
p += s
end
end
-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended
local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number
local buf = ctx.buf
local pos = off
local time = 0
while pos < limit and not ctx.err do
local id, size, data = Ebml.header(buf, pos, limit)
if not id or not size or not data then
return limit
end
if unknown and TOP[id] then
return pos
end
if size < 0 then
size = limit - data -- an unknown-size child: to the end
end
if data + size > limit then
size = limit - data
end
if id == ID.Timecode then
time = Ebml.uint(buf, data, size)
elseif id == ID.SimpleBlock then
block(ctx, data, size, time, true)
elseif id == ID.BlockGroup then
local bo, bl = -1, 0
local ref, dur, discard = false, nil, nil
for id2, o2, n2 in Ebml.children(buf, data, data + size) do
if id2 == ID.Block then
bo, bl = o2, n2
elseif id2 == ID.ReferenceBlock then
ref = true
elseif id2 == ID.BlockDuration then
dur = Ebml.uint(buf, o2, n2)
elseif id2 == ID.DiscardPadding then
discard = Ebml.int(buf, o2, n2)
end
end
if bo >= 0 then
block(ctx, bo, bl, time, false, not ref, dur, discard)
end
end
pos = data + size
end
return pos
end
export type Options = { maxPackets: number? }
-- parse(buf, base, limit, opts) -> a Demux | nil, Err
-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data
-- offset | nil, Err
function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?)
local id, size, data = Ebml.header(buf, base, limit)
if id ~= ID.EBML or not size or not data then
return nil, Err.new(Err.CORRUPT, "not an EBML file", base)
end
if size < 0 then
return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base)
end
local docType = "matroska"
for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do
if cid == ID.DocType then
docType = Ebml.string(buf, o, n)
end
end
return docType, size, data
end
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
local docType, size, data = Parse.docType(buf, base, limit)
if not docType then
return nil, size
end
if docType ~= "matroska" and docType ~= "webm" then
return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType)
end
local pos = data + size
-- the Segment (skip anything else at the top level)
local segData, segEnd = -1, limit
while pos < limit do
local sid, ssize, sdata = Ebml.header(buf, pos, limit)
if not sid or not ssize or not sdata then
break
end
if sid == ID.Segment then
segData = sdata
segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize
break
end
if ssize < 0 then
break
end
pos = sdata + ssize
end
if segData < 0 then
return nil, Err.new(Err.TRUNCATED, "no Segment")
end
local meta: { [string]: any } = { docType = docType }
local scaleNs, duration = 1000000, nil :: number?
local tracks: { TrackInfo } = {}
local problems: { [number]: string } = {}
local cuesAt: { number } = {}
local clusters: { { number } } = {}
-- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead)
pos = segData
while pos < segEnd do
local cid, csize, cdata = Ebml.header(buf, pos, segEnd)
if not cid or not csize or not cdata then
break
end
local unknown = csize < 0
local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize
if cid == ID.Info then
local d
scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta)
duration = d
elseif cid == ID.Tracks then
tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs)
elseif cid == ID.Cluster then
if unknown then
-- find its end: walk children until a top-level ID
local p = cdata
while p < segEnd do
local xid, xsize, xdata = Ebml.header(buf, p, segEnd)
if not xid or not xsize or not xdata or TOP[xid] then
break
end
if xsize < 0 then
p = segEnd
break
end
p = math.min(segEnd, xdata + xsize)
end
cend = p
end
table.insert(clusters, { cdata, cend })
elseif cid == ID.Cues then
table.insert(cuesAt, cdata)
table.insert(cuesAt, cend - cdata)
elseif cid == ID.Tags then
parseTags(buf, cdata, cend - cdata, meta)
end
if cend <= pos then
break
end
pos = cend
end
if #tracks == 0 then
return nil, Err.new(Err.CORRUPT, "no tracks")
end
-- track timescales follow the final TimecodeScale (Info may follow Tracks)
local byNum: { [number]: TrackInfo } = {}
for _, t in tracks do
t.timescale = 1e9 / scaleNs
byNum[t.id] = t
end
local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta)
local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 }
for _, c in clusters do
cluster(ctx, c[1], c[2], false)
if ctx.err then
return nil, Err.new(Err.LIMIT, ctx.err)
end
end
if duration then
dmx.duration = duration * scaleNs / 1e9
end
local cues = {}
for k = 1, #cuesAt, 2 do
for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do
c.time = c.time * scaleNs / 1e9
table.insert(cues, c)
end
end
meta.cues = cues
meta.timecodeScale = scaleNs
for tid, msg in problems do
local t = byNum[tid]
t.unsupported = msg
end
dmx:finish()
return dmx, nil
end
return Parse