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:
1 parent
646d18f056
commit
967703a4d4
13 files changed
+3099
-19
No files matched your search
@@ -0,0 +1,341 @@
|
||||
--!strict
|
||||
-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone
|
||||
-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another
|
||||
-- format). New in formats-luau.
|
||||
-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped);
|
||||
-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk;
|
||||
-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3");
|
||||
-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames;
|
||||
-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations);
|
||||
-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout);
|
||||
-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac.
|
||||
--
|
||||
-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format })
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Mux = require("@formats/containers/Ogg/Mux")
|
||||
|
||||
local AudioWrap = {}
|
||||
|
||||
local function allPackets(dmx: any, track: Types.Track): { Types.Packet }
|
||||
local out = {}
|
||||
local n = if dmx.count then dmx:count(track.id) else 0
|
||||
if n > 0 and dmx.get then
|
||||
for k = 1, n do
|
||||
local p = dmx:get(track.id, k)
|
||||
if p then
|
||||
table.insert(out, p)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function concat(packets: { Types.Packet }, prefix: buffer?): buffer
|
||||
local total = if prefix then buffer.len(prefix) else 0
|
||||
for _, p in packets do
|
||||
total += buffer.len(p.data)
|
||||
end
|
||||
local out = buffer.create(total)
|
||||
local o = 0
|
||||
if prefix then
|
||||
buffer.copy(out, 0, prefix)
|
||||
o = buffer.len(prefix)
|
||||
end
|
||||
for _, p in packets do
|
||||
buffer.copy(out, o, p.data)
|
||||
o += buffer.len(p.data)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ WAV
|
||||
local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source)
|
||||
pcm_u8 = { 1, 8, 0 },
|
||||
pcm_s8 = { 1, 8, 0 },
|
||||
pcm_s16le = { 1, 16, 0 },
|
||||
pcm_s24le = { 1, 24, 0 },
|
||||
pcm_s32le = { 1, 32, 0 },
|
||||
pcm_s16be = { 1, 16, 1 },
|
||||
pcm_s24be = { 1, 24, 1 },
|
||||
pcm_s32be = { 1, 32, 1 },
|
||||
pcm_f32le = { 3, 32, 0 },
|
||||
pcm_f64le = { 3, 64, 0 },
|
||||
pcm_f32be = { 3, 32, 1 },
|
||||
pcm_f64be = { 3, 64, 1 },
|
||||
pcm_alaw = { 6, 8, 0 },
|
||||
pcm_mulaw = { 7, 8, 0 },
|
||||
}
|
||||
|
||||
local function wav(fmt: buffer, data: buffer): buffer
|
||||
local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64)
|
||||
local fl = buffer.len(fmt)
|
||||
local dl = buffer.len(data)
|
||||
w:string("RIFF")
|
||||
w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2))
|
||||
w:string("WAVE")
|
||||
w:string("fmt ")
|
||||
w:u32le(fl)
|
||||
w:bytes(fmt)
|
||||
if fl % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
w:string("data")
|
||||
w:u32le(dl)
|
||||
w:bytes(data)
|
||||
if dl % 2 == 1 then
|
||||
w:u8(0)
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
||||
local spec = PCM[track.codec]
|
||||
local ch = track.channels or 1
|
||||
local rate = math.floor((track.sampleRate or 0) + 0.5)
|
||||
if ch < 1 or rate <= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate")
|
||||
end
|
||||
local bits = spec[2]
|
||||
local data = concat(packets)
|
||||
if spec[3] == 1 then
|
||||
local bps = bits // 8
|
||||
for i = 0, buffer.len(data) - bps, bps do
|
||||
for k = 0, bps // 2 - 1 do
|
||||
local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k)
|
||||
buffer.writeu8(data, i + k, b)
|
||||
buffer.writeu8(data, i + bps - 1 - k, a)
|
||||
end
|
||||
end
|
||||
end
|
||||
if track.codec == "pcm_s8" then
|
||||
for i = 0, buffer.len(data) - 1 do
|
||||
buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256)
|
||||
end
|
||||
end
|
||||
local f = Bytes.writer(16)
|
||||
local align = ch * bits // 8
|
||||
f:u16le(spec[1])
|
||||
f:u16le(ch)
|
||||
f:u32le(rate)
|
||||
f:u32le(rate * align)
|
||||
f:u16le(align)
|
||||
f:u16le(bits)
|
||||
return wav(f:finish(), data), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Ogg
|
||||
-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1)
|
||||
local function opusSamples(b: buffer): number
|
||||
local n = buffer.len(b)
|
||||
if n < 1 then
|
||||
return 0
|
||||
end
|
||||
local toc = buffer.readu8(b, 0)
|
||||
local config = toc // 8
|
||||
local fs: number
|
||||
if config < 12 then
|
||||
fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1]
|
||||
elseif config < 16 then
|
||||
fs = if config % 2 == 0 then 480 else 960
|
||||
else
|
||||
fs = ({ 120, 240, 480, 960 })[config % 4 + 1]
|
||||
end
|
||||
local c = toc % 4
|
||||
local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2
|
||||
return fs * frames
|
||||
end
|
||||
|
||||
local function opusHead(track: Types.Track): buffer
|
||||
local c = track.config
|
||||
if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then
|
||||
return c
|
||||
end
|
||||
local w = Bytes.writer(19)
|
||||
w:string("OpusHead")
|
||||
w:u8(1)
|
||||
w:u8(math.clamp(track.channels or 2, 1, 2))
|
||||
w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5))
|
||||
w:u32le(math.floor(track.sampleRate or 48000))
|
||||
w:u16le(0)
|
||||
w:u8(0)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function opusTags(): buffer
|
||||
local w = Bytes.writer(32)
|
||||
w:string("OpusTags")
|
||||
local vendor = "formats-luau"
|
||||
w:u32le(#vendor)
|
||||
w:string(vendor)
|
||||
w:u32le(0)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer
|
||||
local mux = Mux.new({ pageSize = 4096 })
|
||||
local s = mux:stream(1)
|
||||
for i, h in headers do
|
||||
s:packet(h, 0, { flush = i == 1 or i == #headers })
|
||||
end
|
||||
for i, p in packets do
|
||||
s:packet(p.data, granuleOf(p, i), { eos = i == #packets })
|
||||
end
|
||||
return mux:finish()
|
||||
end
|
||||
|
||||
-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data)
|
||||
local function xiphHeaders(c: buffer): { buffer }?
|
||||
local n = buffer.len(c)
|
||||
if n < 3 then
|
||||
return nil
|
||||
end
|
||||
local count = buffer.readu8(c, 0) + 1
|
||||
local p = 1
|
||||
local sizes = {}
|
||||
local total = 0
|
||||
for k = 1, count - 1 do
|
||||
local s = 0
|
||||
while true do
|
||||
if p >= n then
|
||||
return nil
|
||||
end
|
||||
local b = buffer.readu8(c, p)
|
||||
p += 1
|
||||
s += b
|
||||
if b ~= 255 then
|
||||
break
|
||||
end
|
||||
end
|
||||
sizes[k] = s
|
||||
total += s
|
||||
end
|
||||
sizes[count] = n - p - total
|
||||
if sizes[count] < 0 then
|
||||
return nil
|
||||
end
|
||||
local out = {}
|
||||
for k = 1, count do
|
||||
local b = buffer.create(sizes[k])
|
||||
buffer.copy(b, 0, c, p, sizes[k])
|
||||
p += sizes[k]
|
||||
out[k] = b
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ ADTS
|
||||
local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
||||
local c = track.config
|
||||
local profile, rateIndex, chanConfig
|
||||
if c and buffer.len(c) >= 2 then
|
||||
local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1)
|
||||
profile = b0 // 8 -- audio object type
|
||||
rateIndex = (b0 % 8) * 2 + b1 // 128
|
||||
chanConfig = (b1 // 8) % 16
|
||||
else
|
||||
local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
profile = 2
|
||||
rateIndex = 4
|
||||
for i, r in rates do
|
||||
if r == math.floor((track.sampleRate or 44100) + 0.5) then
|
||||
rateIndex = i - 1
|
||||
end
|
||||
end
|
||||
chanConfig = track.channels or 2
|
||||
end
|
||||
if profile < 1 or profile > 4 or rateIndex > 12 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS")
|
||||
end
|
||||
local w = Bytes.writer(64)
|
||||
for _, p in packets do
|
||||
local len = buffer.len(p.data) + 7
|
||||
w:u8(0xFF)
|
||||
w:u8(0xF1)
|
||||
w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4)
|
||||
w:u8((chanConfig % 4) * 64 + (len // 2048) % 4)
|
||||
w:u8((len // 8) % 256)
|
||||
w:u8((len % 8) * 32 + 0x1F)
|
||||
w:u8(0xFC)
|
||||
w:bytes(p.data)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ wrap
|
||||
-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err
|
||||
function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?)
|
||||
if type(track) ~= "table" or track.kind ~= "audio" then
|
||||
return nil, nil, Err.new(Err.ARG, "not an audio track")
|
||||
end
|
||||
if track.unsupported then
|
||||
return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported)
|
||||
end
|
||||
local codec = track.codec
|
||||
local packets = allPackets(dmx, track)
|
||||
if #packets == 0 then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "audio track without packets")
|
||||
end
|
||||
if track.waveFormat and (PCM[codec] == nil or codec == "pcm_s16le" or codec == "pcm_u8") then
|
||||
return wav(track.waveFormat, concat(packets)), "wav", nil
|
||||
end
|
||||
if PCM[codec] then
|
||||
local b, err = pcmWav(track, packets)
|
||||
return b, if b then "wav" else nil, err
|
||||
end
|
||||
if codec == "mp3" or codec == "mp2" or codec == "mp1" then
|
||||
return concat(packets), "mp3", nil
|
||||
end
|
||||
if codec == "flac" then
|
||||
local c = track.config
|
||||
local prefix: buffer? = nil
|
||||
if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then
|
||||
prefix = c
|
||||
elseif c and buffer.len(c) >= 34 then
|
||||
-- metadata blocks without the marker (MP4 dfLa payload after version / flags)
|
||||
local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0
|
||||
local b = buffer.create(4 + buffer.len(c) - start)
|
||||
buffer.writestring(b, 0, "fLaC")
|
||||
buffer.copy(b, 4, c, start)
|
||||
prefix = b
|
||||
else
|
||||
return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO")
|
||||
end
|
||||
return concat(packets, prefix), "flac", nil
|
||||
end
|
||||
if codec == "opus" then
|
||||
local head = opusHead(track)
|
||||
local pre = buffer.readu16(head, 10)
|
||||
local g = pre
|
||||
local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number
|
||||
g += opusSamples(p.data)
|
||||
local d = (p :: any).discardPadding
|
||||
if type(d) == "number" and d > 0 then
|
||||
return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding)
|
||||
end
|
||||
return g
|
||||
end)
|
||||
return out, "opus", nil
|
||||
end
|
||||
if codec == "vorbis" then
|
||||
local c = track.config
|
||||
local headers = c and xiphHeaders(c)
|
||||
if not headers or #headers ~= 3 then
|
||||
return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers")
|
||||
end
|
||||
local rate = track.sampleRate or 44100
|
||||
local scale = track.timescale
|
||||
local out = ogg(headers, packets, function(p: Types.Packet): number
|
||||
return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5)
|
||||
end)
|
||||
return out, "vorbis", nil
|
||||
end
|
||||
if codec == "aac" then
|
||||
local b, err = adts(track, packets)
|
||||
return b, if b then "aac" else nil, err
|
||||
end
|
||||
return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec))
|
||||
end
|
||||
|
||||
return AudioWrap
|
||||
@@ -0,0 +1,287 @@
|
||||
--!strict
|
||||
-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4).
|
||||
-- New in formats-luau. A container parses its file once into an index of packets (track, pts, dts, duration,
|
||||
-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives
|
||||
-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file
|
||||
-- independently), a file-order cursor, keyframe seeking, packet copies on demand.
|
||||
--
|
||||
-- local d = Demux.new("mkv", tracks, src, meta)
|
||||
-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order
|
||||
-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src
|
||||
-- d:finish() -- durations, per-track indexes
|
||||
-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i)
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Demux = {}
|
||||
local D = {}
|
||||
D.__index = D
|
||||
|
||||
export type Demux = typeof(setmetatable(
|
||||
{} :: {
|
||||
kind: "demuxer",
|
||||
format: string,
|
||||
tracks: { Types.Track },
|
||||
duration: number,
|
||||
meta: { [string]: any },
|
||||
src: buffer,
|
||||
n: number,
|
||||
tr: { number },
|
||||
pts: { number },
|
||||
dts: { number },
|
||||
dur: { number },
|
||||
key: { boolean },
|
||||
off: { number },
|
||||
len: { number },
|
||||
data: { [number]: buffer },
|
||||
extra: { [number]: { [string]: any } },
|
||||
byTrack: { [number]: { number } },
|
||||
cur: { [number]: number },
|
||||
gcur: number,
|
||||
},
|
||||
D
|
||||
))
|
||||
|
||||
-- new(format, tracks, src, meta?) -> an empty index
|
||||
function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux
|
||||
return setmetatable({
|
||||
kind = "demuxer" :: "demuxer",
|
||||
format = format,
|
||||
tracks = tracks,
|
||||
duration = 0,
|
||||
meta = meta or {},
|
||||
src = src,
|
||||
n = 0,
|
||||
tr = {},
|
||||
pts = {},
|
||||
dts = {},
|
||||
dur = {},
|
||||
key = {},
|
||||
off = {},
|
||||
len = {},
|
||||
data = {},
|
||||
extra = {},
|
||||
byTrack = {},
|
||||
cur = {},
|
||||
gcur = 1,
|
||||
}, D)
|
||||
end
|
||||
|
||||
-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length)
|
||||
function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number)
|
||||
local i = self.n + 1
|
||||
self.n = i
|
||||
self.tr[i] = track
|
||||
self.pts[i] = pts
|
||||
self.dts[i] = dts or pts
|
||||
self.dur[i] = duration or 0
|
||||
self.key[i] = keyframe
|
||||
self.off[i] = offset
|
||||
self.len[i] = length
|
||||
end
|
||||
|
||||
-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes
|
||||
function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer)
|
||||
self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data))
|
||||
self.data[self.n] = data
|
||||
end
|
||||
|
||||
-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...)
|
||||
function D.setExtra(self: Demux, key: string, value: any)
|
||||
local e = self.extra[self.n]
|
||||
if not e then
|
||||
e = {}
|
||||
self.extra[self.n] = e
|
||||
end
|
||||
e[key] = value
|
||||
end
|
||||
|
||||
-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's
|
||||
-- frame rate), and the track / file durations (seconds) where the container gave none
|
||||
function D.finish(self: Demux)
|
||||
local byTrack: { [number]: { number } } = {}
|
||||
for _, t in self.tracks do
|
||||
byTrack[t.id] = {}
|
||||
end
|
||||
for i = 1, self.n do
|
||||
local list = byTrack[self.tr[i]]
|
||||
if list then
|
||||
table.insert(list, i)
|
||||
end
|
||||
end
|
||||
self.byTrack = byTrack
|
||||
local total = self.duration
|
||||
for _, t in self.tracks do
|
||||
local list = byTrack[t.id]
|
||||
local scale = if t.timescale and t.timescale > 0 then t.timescale else 1
|
||||
t.timescale = scale
|
||||
local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0
|
||||
-- durations from the next packet in presentation order
|
||||
if #list > 0 then
|
||||
local order = table.clone(list)
|
||||
table.sort(order, function(a: number, b: number): boolean
|
||||
return self.pts[a] < self.pts[b]
|
||||
end)
|
||||
for k = 1, #order do
|
||||
local i = order[k]
|
||||
if self.dur[i] <= 0 then
|
||||
local nx = order[k + 1]
|
||||
if nx and self.pts[nx] > self.pts[i] then
|
||||
self.dur[i] = self.pts[nx] - self.pts[i]
|
||||
elseif frameTicks > 0 then
|
||||
self.dur[i] = frameTicks
|
||||
elseif k > 1 then
|
||||
self.dur[i] = self.dur[order[k - 1]]
|
||||
end
|
||||
end
|
||||
end
|
||||
local first, last = order[1], order[#order]
|
||||
local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale
|
||||
if not t.duration or t.duration <= 0 then
|
||||
t.duration = d
|
||||
end
|
||||
t.frames = t.frames or #list
|
||||
end
|
||||
if t.duration and t.duration > total then
|
||||
total = t.duration
|
||||
end
|
||||
self.cur[t.id] = 1
|
||||
end
|
||||
self.duration = total
|
||||
end
|
||||
|
||||
-- the Packet for index entry i (a copy of its bytes)
|
||||
function D._packet(self: Demux, i: number): Types.Packet
|
||||
local data = self.data[i]
|
||||
if not data then
|
||||
local o, l = self.off[i], self.len[i]
|
||||
local src = self.src
|
||||
local n = buffer.len(src)
|
||||
if o < 0 or o > n then
|
||||
o, l = n, 0
|
||||
elseif o + l > n then
|
||||
l = n - o
|
||||
end
|
||||
data = buffer.create(l)
|
||||
buffer.copy(data, 0, src, o, l)
|
||||
end
|
||||
local p: any = {
|
||||
track = self.tr[i],
|
||||
pts = self.pts[i],
|
||||
dts = self.dts[i],
|
||||
duration = self.dur[i],
|
||||
keyframe = self.key[i],
|
||||
data = data :: buffer,
|
||||
}
|
||||
local e = self.extra[i]
|
||||
if e then
|
||||
for k, v in e do
|
||||
p[k] = v
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end
|
||||
function D.read(self: Demux, track: number?): Types.Packet?
|
||||
if track == nil then
|
||||
local i = self.gcur
|
||||
if i > self.n then
|
||||
return nil
|
||||
end
|
||||
self.gcur = i + 1
|
||||
return self:_packet(i)
|
||||
end
|
||||
local list = self.byTrack[track]
|
||||
if not list then
|
||||
return nil
|
||||
end
|
||||
local c = self.cur[track] or 1
|
||||
local i = list[c]
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
self.cur[track] = c + 1
|
||||
return self:_packet(i)
|
||||
end
|
||||
|
||||
-- packets(track?) -> an iterator of Packets from the current position (advancing it)
|
||||
function D.packets(self: Demux, track: number?): () -> Types.Packet?
|
||||
return function(): Types.Packet?
|
||||
return self:read(track)
|
||||
end
|
||||
end
|
||||
|
||||
-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors
|
||||
function D.count(self: Demux, track: number): number
|
||||
local list = self.byTrack[track]
|
||||
return if list then #list else 0
|
||||
end
|
||||
function D.get(self: Demux, track: number, k: number): Types.Packet?
|
||||
local list = self.byTrack[track]
|
||||
local i = list and list[k]
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
return self:_packet(i)
|
||||
end
|
||||
|
||||
-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy)
|
||||
function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?)
|
||||
local list = self.byTrack[track]
|
||||
local i = list and list[k]
|
||||
if not i then
|
||||
return nil
|
||||
end
|
||||
return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i]
|
||||
end
|
||||
|
||||
-- rewind(track?): a track's cursor (or every cursor) back to the start
|
||||
function D.rewind(self: Demux, track: number?)
|
||||
if track then
|
||||
self.cur[track] = 1
|
||||
return
|
||||
end
|
||||
for id in self.cur do
|
||||
self.cur[id] = 1
|
||||
end
|
||||
self.gcur = 1
|
||||
end
|
||||
|
||||
-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest)
|
||||
function D.seek(self: Demux, seconds: number)
|
||||
local g = self.n + 1
|
||||
for _, t in self.tracks do
|
||||
local list = self.byTrack[t.id]
|
||||
if list and #list > 0 then
|
||||
local target = seconds * t.timescale
|
||||
local best = 1
|
||||
for k = 1, #list do
|
||||
local i = list[k]
|
||||
if self.key[i] and self.pts[i] <= target + 1e-6 then
|
||||
best = k
|
||||
end
|
||||
end
|
||||
self.cur[t.id] = best
|
||||
if list[best] < g then
|
||||
g = list[best]
|
||||
end
|
||||
end
|
||||
end
|
||||
self.gcur = if g > self.n then 1 else g
|
||||
end
|
||||
|
||||
-- track(kind) -> the first default track of the kind, else the first of the kind
|
||||
function D.track(self: Demux, kind: string): Types.Track?
|
||||
local first = nil
|
||||
for _, t in self.tracks do
|
||||
if t.kind == kind then
|
||||
if t.default then
|
||||
return t
|
||||
end
|
||||
first = first or t
|
||||
end
|
||||
end
|
||||
return first
|
||||
end
|
||||
|
||||
return Demux
|
||||
@@ -0,0 +1,335 @@
|
||||
--!strict
|
||||
-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in formats-luau.
|
||||
-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it;
|
||||
-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats,
|
||||
-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and
|
||||
-- minimal-length value elements.
|
||||
--
|
||||
-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated
|
||||
-- for id, off, size in Ebml.children(buf, off, limit) do ... end
|
||||
-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish()
|
||||
--
|
||||
-- Never throws: malformed input gives nil (readers) or stops iteration.
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local Ebml = {}
|
||||
|
||||
Ebml.UNKNOWN = -1
|
||||
|
||||
-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1.
|
||||
function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?)
|
||||
if pos >= limit then
|
||||
return nil
|
||||
end
|
||||
local b = readu8(buf, pos)
|
||||
if b == 0 then
|
||||
return nil
|
||||
end
|
||||
local len = 1
|
||||
local mask = 0x80
|
||||
while bit32.band(b, mask) == 0 do
|
||||
len += 1
|
||||
mask = mask // 2
|
||||
end
|
||||
if pos + len > limit then
|
||||
return nil
|
||||
end
|
||||
local v = bit32.band(b, mask - 1)
|
||||
local allOnes = v == mask - 1
|
||||
for i = 1, len - 1 do
|
||||
local c = readu8(buf, pos + i)
|
||||
v = v * 256 + c
|
||||
if c ~= 255 then
|
||||
allOnes = false
|
||||
end
|
||||
end
|
||||
if allOnes then
|
||||
return -1, len
|
||||
end
|
||||
return v, len
|
||||
end
|
||||
|
||||
-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil
|
||||
function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?)
|
||||
local v, len = Ebml.vint(buf, pos, limit)
|
||||
if v == nil or len == nil then
|
||||
return nil
|
||||
end
|
||||
if v == -1 then
|
||||
return nil
|
||||
end
|
||||
return v - (2 ^ (7 * len - 1) - 1), len
|
||||
end
|
||||
|
||||
-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes)
|
||||
function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?)
|
||||
if pos >= limit then
|
||||
return nil
|
||||
end
|
||||
local b = readu8(buf, pos)
|
||||
local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0
|
||||
if len == 0 or pos + len > limit then
|
||||
return nil
|
||||
end
|
||||
local v = b
|
||||
for i = 1, len - 1 do
|
||||
v = v * 256 + readu8(buf, pos + i)
|
||||
end
|
||||
return v, len
|
||||
end
|
||||
|
||||
-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil
|
||||
function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?)
|
||||
local id, il = Ebml.id(buf, pos, limit)
|
||||
if not id or not il then
|
||||
return nil
|
||||
end
|
||||
local size, sl = Ebml.vint(buf, pos + il, limit)
|
||||
if not size or not sl then
|
||||
return nil
|
||||
end
|
||||
return id, size, pos + il + sl
|
||||
end
|
||||
|
||||
-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the
|
||||
-- limit is clipped; a malformed header ends the iteration)
|
||||
function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number)
|
||||
local pos = off
|
||||
return function(): (number?, number, number)
|
||||
if pos >= limit then
|
||||
return nil, 0, 0
|
||||
end
|
||||
local id, size, data = Ebml.header(buf, pos, limit)
|
||||
if not id or not size or not data then
|
||||
pos = limit
|
||||
return nil, 0, 0
|
||||
end
|
||||
if size < 0 or data + size > limit then
|
||||
size = limit - data
|
||||
end
|
||||
pos = data + size
|
||||
return id, data, size
|
||||
end
|
||||
end
|
||||
|
||||
-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements)
|
||||
function Ebml.uint(buf: buffer, off: number, len: number): number
|
||||
local v = 0
|
||||
for i = 0, math.min(len, 8) - 1 do
|
||||
v = v * 256 + readu8(buf, off + i)
|
||||
end
|
||||
return v
|
||||
end
|
||||
function Ebml.int(buf: buffer, off: number, len: number): number
|
||||
if len <= 0 then
|
||||
return 0
|
||||
end
|
||||
local v = Ebml.uint(buf, off, len)
|
||||
local n = math.min(len, 8)
|
||||
if readu8(buf, off) >= 0x80 then
|
||||
v -= 2 ^ (8 * n)
|
||||
end
|
||||
return v
|
||||
end
|
||||
function Ebml.float(buf: buffer, off: number, len: number): number
|
||||
local r = Bytes.reader(buf, off, len)
|
||||
if len == 4 then
|
||||
return r:f32be()
|
||||
elseif len == 8 then
|
||||
return r:f64be()
|
||||
end
|
||||
return 0
|
||||
end
|
||||
function Ebml.string(buf: buffer, off: number, len: number): string
|
||||
local s = buffer.readstring(buf, off, len)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
if z then
|
||||
s = string.sub(s, 1, z - 1)
|
||||
end
|
||||
return s
|
||||
end
|
||||
function Ebml.binary(buf: buffer, off: number, len: number): buffer
|
||||
local b = buffer.create(len)
|
||||
buffer.copy(b, 0, buf, off, len)
|
||||
return b
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writing
|
||||
local W = {}
|
||||
W.__index = W
|
||||
|
||||
export type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W))
|
||||
|
||||
-- writer(capacity?) -> an EBML byte builder
|
||||
function Ebml.writer(capacity: number?): Writer
|
||||
return setmetatable({ w = Bytes.writer(capacity or 65536) }, W)
|
||||
end
|
||||
|
||||
-- idBytes(id) -> the ID's bytes as written
|
||||
local function writeId(w: Bytes.Writer, id: number)
|
||||
if id >= 0x1000000 then
|
||||
w:u32be(id)
|
||||
elseif id >= 0x10000 then
|
||||
w:u24be(id)
|
||||
elseif id >= 0x100 then
|
||||
w:u16be(id)
|
||||
else
|
||||
w:u8(id)
|
||||
end
|
||||
end
|
||||
|
||||
-- size as a minimal vint (n bytes: force a length)
|
||||
local function writeSize(w: Bytes.Writer, size: number, n: number?)
|
||||
local len = n or 1
|
||||
if not n then
|
||||
while size >= 2 ^ (7 * len) - 1 do
|
||||
len += 1
|
||||
end
|
||||
end
|
||||
local v = size + 2 ^ (7 * len) -- the marker bit
|
||||
local bytes = table.create(len, 0)
|
||||
for i = len, 1, -1 do
|
||||
bytes[i] = v % 256
|
||||
v = v // 256
|
||||
end
|
||||
for i = 1, len do
|
||||
w:u8(bytes[i])
|
||||
end
|
||||
end
|
||||
Ebml.writeSize = writeSize
|
||||
|
||||
-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers)
|
||||
function Ebml.vintString(v: number, n: number?): string
|
||||
local w = Bytes.writer(8)
|
||||
writeSize(w, v, n)
|
||||
return buffer.readstring(w:finish(), 0, w:tell())
|
||||
end
|
||||
|
||||
function W.tell(self: Writer): number
|
||||
return self.w:tell()
|
||||
end
|
||||
|
||||
-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder
|
||||
function W.open(self: Writer, id: number): number
|
||||
writeId(self.w, id)
|
||||
local at = self.w:tell()
|
||||
for _ = 1, 8 do
|
||||
self.w:u8(0)
|
||||
end
|
||||
return at
|
||||
end
|
||||
|
||||
-- close(handle): patches the size of the element opened at handle
|
||||
function W.close(self: Writer, at: number)
|
||||
local w = self.w
|
||||
local v = w:tell() - at - 8
|
||||
w:setU8(at, 0x01)
|
||||
for i = 7, 1, -1 do
|
||||
w:setU8(at + i, v % 256)
|
||||
v = v // 256
|
||||
end
|
||||
end
|
||||
|
||||
-- unknownSize(id): a master element with an unknown size (live streams)
|
||||
function W.openUnknown(self: Writer, id: number)
|
||||
writeId(self.w, id)
|
||||
self.w:u8(0x01)
|
||||
for _ = 1, 7 do
|
||||
self.w:u8(0xFF)
|
||||
end
|
||||
end
|
||||
|
||||
function W.uint(self: Writer, id: number, v: number)
|
||||
local n = 1
|
||||
while v >= 2 ^ (8 * n) and n < 8 do
|
||||
n += 1
|
||||
end
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, n)
|
||||
local bytes = table.create(n, 0)
|
||||
local x = v
|
||||
for i = n, 1, -1 do
|
||||
bytes[i] = x % 256
|
||||
x = x // 256
|
||||
end
|
||||
for i = 1, n do
|
||||
self.w:u8(bytes[i])
|
||||
end
|
||||
end
|
||||
|
||||
function W.int(self: Writer, id: number, v: number)
|
||||
local n = 1
|
||||
while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do
|
||||
n += 1
|
||||
end
|
||||
local u = if v < 0 then v + 2 ^ (8 * n) else v
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, n)
|
||||
local bytes = table.create(n, 0)
|
||||
for i = n, 1, -1 do
|
||||
bytes[i] = u % 256
|
||||
u = u // 256
|
||||
end
|
||||
for i = 1, n do
|
||||
self.w:u8(bytes[i])
|
||||
end
|
||||
end
|
||||
|
||||
function W.float(self: Writer, id: number, v: number)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, 8)
|
||||
self.w:f64be(v)
|
||||
end
|
||||
|
||||
function W.string(self: Writer, id: number, s: string)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, #s)
|
||||
self.w:string(s)
|
||||
end
|
||||
|
||||
-- binary(id, buf, off?, len?)
|
||||
function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?)
|
||||
local o = off or 0
|
||||
local n = len or (buffer.len(b) - o)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, n)
|
||||
self.w:bytes(b, o, n)
|
||||
end
|
||||
|
||||
-- raw bytes (a pre-built element, block headers)
|
||||
function W.raw(self: Writer, s: string)
|
||||
self.w:string(s)
|
||||
end
|
||||
function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?)
|
||||
local o = off or 0
|
||||
self.w:bytes(b, o, len or (buffer.len(b) - o))
|
||||
end
|
||||
-- element header for a binary element whose payload follows in pieces: id + size
|
||||
function W.header(self: Writer, id: number, size: number)
|
||||
writeId(self.w, id)
|
||||
writeSize(self.w, size)
|
||||
end
|
||||
|
||||
-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space
|
||||
function W.void(self: Writer, n: number)
|
||||
self.w:u8(0xEC)
|
||||
if n - 2 < 127 then
|
||||
writeSize(self.w, n - 2, 1)
|
||||
for _ = 1, n - 2 do
|
||||
self.w:u8(0)
|
||||
end
|
||||
else
|
||||
writeSize(self.w, n - 9, 8)
|
||||
for _ = 1, n - 9 do
|
||||
self.w:u8(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function W.finish(self: Writer): buffer
|
||||
return self.w:finish()
|
||||
end
|
||||
|
||||
return Ebml
|
||||
Reference in new issue
Block a user