Files
rosetta/src/Formats/containers/Demux.luau
T
4DBug 967703a4d4 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.
2026-10-31 09:31:21 -05:00

288 lines
7.9 KiB
Luau

--!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