ws-video: video foundation: Types video section made concrete (Track / Packet / Demuxer / VideoFrame / VideoDecoder / VideoCodecDecoder), codecs/Video (codec registry by id / FourCC / Matroska id, generic VideoDecoder over a Demuxer, frames-backed videos, Source for writers), codecs/Yuv, containers/Demux (indexed demuxer), containers/Ebml, containers/AudioWrap; video/mkv (Matroska / WebM demux + mux, WIP: tests next)

api (init.luau, small, backward compatible): KIND_CATEGORY.video; withHooks adds opts.openAudio (audio tracks of video containers reach the audio formats through AudioWrap); F.load of a video format returns its VideoDecoder instead of draining it as audio; F.open passes the hooks and opens animated images as frames-backed videos (F.video.open(gif)); F.save of an Image to a video format wraps it (F.convert(gif, 'avi')); F.video.fromImage, F.video.codecs.
This commit is contained in:
4DBug committed 2026-10-31 09:31:21 -05:00
1 parent 75c677074a
commit 8a905a4510
13 files changed
+3099 -19

No files matched your search

+285
View File
@@ -0,0 +1,285 @@
--!strict
-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration),
-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of
-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative
-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come
-- from codecs/Video/Source (copied packets or encoded frames). Interpreted; never throws.
local Err = require("@formats/core/Err")
local Ebml = require("@formats/containers/Ebml")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
local Parse = require("@formats/video/mkv/Parse")
local ID = Parse.ID
local Mux = {}
local AUDIO_IDS: { [string]: string } = {
vorbis = "A_VORBIS",
opus = "A_OPUS",
flac = "A_FLAC",
mp3 = "A_MPEG/L3",
mp2 = "A_MPEG/L2",
mp1 = "A_MPEG/L1",
aac = "A_AAC",
ac3 = "A_AC3",
eac3 = "A_EAC3",
alac = "A_ALAC",
pcm_u8 = "A_PCM/INT/LIT",
pcm_s16le = "A_PCM/INT/LIT",
pcm_s24le = "A_PCM/INT/LIT",
pcm_s32le = "A_PCM/INT/LIT",
pcm_s16be = "A_PCM/INT/BIG",
pcm_s24be = "A_PCM/INT/BIG",
pcm_s32be = "A_PCM/INT/BIG",
pcm_f32le = "A_PCM/FLOAT/IEEE",
pcm_f64le = "A_PCM/FLOAT/IEEE",
}
Mux.AUDIO_IDS = AUDIO_IDS
-- codecId(stream) -> the Matroska CodecID | nil
function Mux.codecId(kind: string, codec: string): string?
if kind == "video" then
local e = Video.entry(codec)
local m = e and e.matroska
return m and m[1]
end
return AUDIO_IDS[codec]
end
local function pcmBits(codec: string): number?
local b = string.match(codec, "^pcm_[suf](%d+)")
if b then
return tonumber(b)
end
if codec == "pcm_u8" then
return 8
end
return nil
end
export type Options = {
webm: boolean?,
title: string?,
app: string?,
clusterSeconds: number?, -- default 2
}
-- mux(streams, opts) -> buffer | nil, Err
function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?)
local webm = opts.webm == true
local app = opts.app or "formats-luau"
local clusterSpan = opts.clusterSeconds or 2
-- tracks
local ids: { string } = {}
local videoIndex = 0
for i, s in streams do
local cid = Mux.codecId(s.kind, s.codec)
if not cid then
return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec)
end
ids[i] = cid
if s.kind == "video" and videoIndex == 0 then
videoIndex = i
end
end
local order = Source.interleave(streams)
local duration = 0
for _, s in streams do
for _, p in s.packets do
local e = p.pts + (p.duration or 0)
if e > duration then
duration = e
end
end
end
-- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known)
local body = Ebml.writer(65536)
local infoAt = body:tell()
local info = body:open(ID.Info)
body:uint(ID.TimecodeScale, 1000000)
body:string(ID.MuxingApp, app)
body:string(ID.WritingApp, app)
if opts.title then
body:string(ID.Title, opts.title)
end
body:float(ID.Duration, duration * 1000)
body:close(info)
local tracksAt = body:tell()
local tracks = body:open(ID.Tracks)
for i, s in streams do
local te = body:open(ID.TrackEntry)
body:uint(ID.TrackNumber, i)
body:uint(ID.TrackUID, i)
body:uint(ID.TrackType, if s.kind == "video" then 1 else 2)
body:uint(ID.FlagLacing, 0)
body:string(ID.Language, "und")
body:string(ID.CodecID, ids[i])
if s.config and buffer.len(s.config) > 0 then
body:binary(ID.CodecPrivate, s.config)
end
if s.kind == "video" then
if s.frameRate and s.frameRate > 0 then
body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5))
end
local v = body:open(ID.Video)
body:uint(ID.PixelWidth, s.width or 0)
body:uint(ID.PixelHeight, s.height or 0)
body:close(v)
else
if s.codec == "opus" then
local pre = 0
local c = s.config
if c and buffer.len(c) >= 12 then
pre = buffer.readu16(c, 10)
end
body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5))
body:uint(ID.SeekPreRoll, 80000000)
end
local a = body:open(ID.Audio)
body:float(ID.SamplingFrequency, s.sampleRate or 48000)
body:uint(ID.Channels, s.channels or 1)
local bits = pcmBits(s.codec) or s.bitsPerSample
if bits and string.sub(s.codec, 1, 4) == "pcm_" then
body:uint(ID.BitDepth, bits)
end
body:close(a)
end
body:close(te)
end
body:close(tracks)
-- clusters
local cues: { { number } } = {} -- { time ms, track, cluster offset in body }
local cl: number? = nil
local clTime = 0
local clStart = 0
for _, item in order do
local si: number, p = item[1], item[2]
local ms = math.floor(p.pts * 1000 + 0.5)
local isVideoKey = si == videoIndex and p.keyframe
local need = cl == nil
or ms - clTime > 30000
or ms < clTime
or (isVideoKey and ms - clStart >= clusterSpan * 1000)
or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000)
if need then
if cl then
body:close(cl)
end
local at = body:tell()
cl = body:open(ID.Cluster)
clTime = ms
clStart = ms
body:uint(ID.Timecode, ms)
if videoIndex == 0 or isVideoKey then
table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at })
end
end
local data: buffer = p.data
local hdr = Ebml.vintString(si, 1)
local rel = ms - clTime
local size = #hdr + 3 + buffer.len(data)
body:header(ID.SimpleBlock, size)
body:raw(hdr)
body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0))
body:rawBuffer(data)
end
if cl then
body:close(cl)
end
local cuesAt = body:tell()
if #cues > 0 then
local c = body:open(ID.Cues)
for _, q in cues do
local cp = body:open(ID.CuePoint)
body:uint(ID.CueTime, q[1])
local tp = body:open(ID.CueTrackPositions)
body:uint(ID.CueTrack, q[2])
body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length
body:close(tp)
body:close(cp)
end
body:close(c)
end
local bodyBuf = body:finish()
-- the SeekHead: its own length shifts every position, so build it until its size is stable
local function seekHead(shift: number): buffer
local w = Ebml.writer(256)
local sh = w:open(ID.SeekHead)
local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } }
if #cues > 0 then
table.insert(entries, { ID.Cues, cuesAt })
end
for _, e in entries do
local sk = w:open(0x4DBB)
local idv = e[1]
local bytes = {}
while idv > 0 do
table.insert(bytes, 1, idv % 256)
idv = idv // 256
end
w:header(0x53AB, #bytes)
for _, b in bytes do
w:raw(string.char(b))
end
w:uint(0x53AC, e[2] + shift)
w:close(sk)
end
w:close(sh)
return w:finish()
end
local shift = 0
local head = seekHead(0)
for _ = 1, 4 do
local n = buffer.len(head)
if n == shift then
break
end
shift = n
head = seekHead(shift)
end
shift = buffer.len(head)
-- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element
-- (its uint widths may grow, but Cues are last, so nothing after them moves)
if #cues > 0 then
local w = Ebml.writer(4096)
local c = w:open(ID.Cues)
for _, q in cues do
local cp = w:open(ID.CuePoint)
w:uint(ID.CueTime, q[1])
local tp = w:open(ID.CueTrackPositions)
w:uint(ID.CueTrack, q[2])
w:uint(ID.CueClusterPosition, q[3] + shift)
w:close(tp)
w:close(cp)
end
w:close(c)
local cuesBuf = w:finish()
local nb = buffer.create(cuesAt + buffer.len(cuesBuf))
buffer.copy(nb, 0, bodyBuf, 0, cuesAt)
buffer.copy(nb, cuesAt, cuesBuf)
bodyBuf = nb
end
-- the file
local out = Ebml.writer(buffer.len(bodyBuf) + 256)
local eb = out:open(ID.EBML)
out:uint(0x4286, 1)
out:uint(0x42F7, 1)
out:uint(0x42F2, 4)
out:uint(0x42F3, 8)
out:string(ID.DocType, if webm then "webm" else "matroska")
out:uint(0x4287, 4)
out:uint(0x4285, 2)
out:close(eb)
local seg = out:open(ID.Segment)
out:rawBuffer(head)
out:rawBuffer(bodyBuf)
out:close(seg)
return out:finish(), nil
end
return Mux
+658
View File
@@ -0,0 +1,658 @@
--!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")
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,
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 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) is supported; zlib / 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
for id2, o2, n2 in Ebml.children(buf, o, o + n) do
if 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
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
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 strip = t.strip
if 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, key and k == 1, nb)
else
dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, key and (k == 1 or t.kind ~= "video"), 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
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
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
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
+160
View File
@@ -0,0 +1,160 @@
--!strict
-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in
-- formats-luau, on containers/Ebml.
-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing,
-- header-stripping compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video
-- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio
-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text
-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone.
-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied
-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from
-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration.
-- Not supported: zlib / bzip2 / lzo content compression and encryption (the track's packets are left as stored,
-- track.unsupported says why), chapters / attachments (skipped), writing subtitles.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Video = require("@formats/codecs/Video")
local Source = require("@formats/codecs/Video/Source")
local Parse = require("@formats/video/mkv/Parse")
local Mux = require("@formats/video/mkv/Mux")
-- ------------------------------------------------------------------------------------------------ contract
local Mkv = {
name = "mkv",
category = "video",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec)
track: number?, -- the video track number to decode (default: the first video track)
audio: boolean?, -- false: do not open the audio track
maxPackets: number?, -- refuse files with more packets (default 2^24)
maxPixels: number?,
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
}
export type EncodeOptions = {
format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska
webm: boolean?, -- the same as format = "webm"
quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90)
reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG)
video: boolean?, -- false: no video stream
audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped)
title: string?,
clusterSeconds: number?, -- target cluster length (default 2)
}
-- ------------------------------------------------------------------------------------------------ constants
local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true }
local WEBM_AUDIO = { opus = true, vorbis = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Mkv.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "\26\69\223\163" then
return 0
end
local head = r:peek(math.min(64, r:remaining()))
if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then
return 1
end
return 0.5
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image)
-- or a Demuxer
function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = opts or {}
local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm")
local want: Source.Want
if webm then
want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } }
else
local copy: { [string]: boolean } = {}
for id, e in Video.codecs do
if e.matroska then
copy[id] = true
end
end
want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } }
end
local so = table.clone(o)
so.quality = so.quality or 90
local streams, err = Source.streams(value, so, want)
if not streams then
return nil, err
end
if not webm then
-- audio codecs Matroska cannot name: PCM instead
for i, s in streams do
if s.kind == "audio" and not Mux.codecId("audio", s.codec) then
local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } })
if alt and alt[1] then
streams[i] = alt[1]
else
return nil, aerr
end
end
end
end
local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds })
if not ok then
return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf))
end
return buf, merr
end
-- ------------------------------------------------------------------------------------------------ open
-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err
function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?)
local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx))
end
return dmx, err
end
-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err
function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local dmx, err = Mkv.demux(r, opts)
if not dmx then
return nil, err
end
return Video.open(dmx, opts)
end
-- ------------------------------------------------------------------------------------------------ extras
-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil
function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles?
local track = nil
for _, t in dmx.tracks do
if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then
track = t
break
end
end
if not track then
return nil
end
local subs = Types.Subtitles.new()
subs.meta.codec = track.codec
subs.meta.language = track.language
for k = 1, dmx:count(track.id) do
local p = dmx:get(track.id, k)
if p then
local start = p.pts / track.timescale
local stop = start + (p.duration or 0) / track.timescale
table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) })
end
end
return subs
end
return Mkv