comments: containers MpegTs / IsoBmff Demux

This commit is contained in:
4DBug committed 2026-11-01 01:57:14 -05:00
1 parent a0a11af953
commit facdf124a1
2 files changed
+5 -49

No files matched your search

+3 -22
View File
@@ -1,10 +1,7 @@
--!strict
-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8):
-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration
-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 /
-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun).
-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the
-- reader's buffer. Never throws.
-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8),
-- edit lists and fragments (mvex / trex, moof / traf / tfhd / tfdt / trun). The per-sample tables are columnar arrays,
-- offsets absolute in the reader's buffer. Never throws.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Box = require("@rosetta/containers/IsoBmff/Box")
@@ -20,8 +17,6 @@ local Demux = {}
export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty)
-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the
-- sample tables and the ISO facts
export type Track = {
id: number,
kind: "video" | "audio" | "subtitle" | "data",
@@ -47,7 +42,6 @@ export type Track = {
skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming)
delay: number, -- movie ticks of an initial empty edit
playDuration: number?, -- media ticks the edit list plays (nil: all)
-- samples
sampleCount: number,
offsets: { number }, -- absolute offsets in the buffer
sizes: { number },
@@ -110,7 +104,6 @@ local function descLen(r: Bytes.Reader): number
return n
end
-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate
function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?)
local r = reader(b, box)
r:skip(4) -- version / flags
@@ -150,7 +143,6 @@ function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?)
return oti, dsi, avg
end
-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t
local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
local r = reader(b, e)
r:skip(6)
@@ -253,7 +245,6 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
end
end
-- media handler / header / sample tables of one trak -> Track | nil, Err
local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?)
local tkhd = Box.child(trak, "tkhd")
local mdia = Box.child(trak, "mdia")
@@ -321,7 +312,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
if not stbl then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start)
end
-- sample descriptions
local stsd = Box.child(stbl, "stsd")
if stsd and stsd.data + 8 <= stsd.stop then
local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd")
@@ -330,7 +320,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
end
t.sampleEntries = entries
end
-- edit list
local elst = Box.path(trak, "edts/elst")
if elst then
local r = reader(b, elst)
@@ -373,7 +362,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
end
end
end
-- sample sizes
local maxSamples = o.maxSamples or 2 ^ 25
local sizes = t.sizes
local count = 0
@@ -432,7 +420,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
end
end
end
-- decode times
local dts, durs = t.dts, t.durations
local stts = Box.child(stbl, "stts")
if stts and count > 0 then
@@ -466,7 +453,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
dts[i], durs[i] = 0, 0
end
end
-- composition offsets
local ctts = Box.child(stbl, "ctts")
if ctts and count > 0 then
local r = reader(b, ctts)
@@ -493,7 +479,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
t.cts = cts
end
end
-- sync samples
local stss = Box.child(stbl, "stss")
if stss then
local r = reader(b, stss)
@@ -507,7 +492,6 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
t.sync = sync
end
end
-- chunk offsets + sample-to-chunk -> sample offsets
local stco = Box.child(stbl, "stco")
local co64 = Box.child(stbl, "co64")
local chunks: { number } = {}
@@ -614,12 +598,10 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
t.sampleDescription = nil
end
end
-- fragment defaults
t.trex = trex[t.id]
return t, nil
end
-- the movie fragments (moof) after the moov: appends their samples to the tracks
local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err?
local maxSamples = o.maxSamples or 2 ^ 25
for _, moof in top do
@@ -751,7 +733,6 @@ export type Movie = {
fragmented: boolean,
}
-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included)
function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?)
local o: Options = opts or {}
local b = r.buf
+2 -27
View File
@@ -1,16 +1,8 @@
--!strict
--!native
-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same
-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a
-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections
-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity
-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS.
--
-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... }
-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed
--
-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is
-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised.
-- author; no third-party code); changed: the unit queue keeps an explicit tail (#q on a table with holes at its front
-- loses units under LuaJIT's border rule). Never throws: bad input is skipped and counted in `stats`.
local Crc32 = require("@rosetta/core/Crc32")
local MpegTs = {}
@@ -172,7 +164,6 @@ function MpegTs.new(): Demuxer
return self
end
-- PSI ---------------------------------------------------------------------------------------------------------
local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?)
local info = CODECS[streamType]
@@ -259,7 +250,6 @@ local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: bu
end
buffer.copy(s.buf, s.len, src, from, n)
s.len += n
-- every complete section in the buffer
while s.active and s.len >= 3 do
if readu8(s.buf, 0) == 0xFF then
s.active = false -- stuffing: no more sections until the next unit start
@@ -304,7 +294,6 @@ local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buff
sectionBytes(self, pid, s, b, pos, stop)
end
-- PES ---------------------------------------------------------------------------------------------------------
local function completePes(self: Demuxer, pid: number, st: PesState)
st.active = false
@@ -516,7 +505,6 @@ local function pesPayload(
end
end
-- packets -----------------------------------------------------------------------------------------------------
local function packet(self: Demuxer, b: buffer, pk: number)
local stats = self.stats
@@ -572,7 +560,6 @@ local function packet(self: Demuxer, b: buffer, pk: number)
return -- adaptation field only: the counter does not advance
end
end
-- continuity counter
local ccError = false
local last = self._cc[pid]
if last ~= nil and not discontinuity then
@@ -592,8 +579,6 @@ local function packet(self: Demuxer, b: buffer, pk: number)
end
end
-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for
-- pull(). Returns false for a bad argument.
function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
@@ -612,7 +597,6 @@ function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len
if n < 0 then
return false
end
-- append to the pending bytes
local need = self._pendLen + n
if need > buffer.len(self._pend) then
local cap = buffer.len(self._pend)
@@ -678,7 +662,6 @@ function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len
return true
end
-- The next completed unit (any PID), or nil.
function Demuxer.pull(self: Demuxer): Unit?
local q = self._queue
local h = self._qhead
@@ -697,8 +680,6 @@ function Demuxer.pull(self: Demuxer): Unit?
return u
end
-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next
-- unit start). Units still queue up for pull().
function Demuxer.flush(self: Demuxer)
local pids = {}
for pid, st in self._pes do
@@ -713,7 +694,6 @@ function Demuxer.flush(self: Demuxer)
self._pendLen = 0
end
-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek).
function Demuxer.reset(self: Demuxer)
self._pendLen = 0
for _, st in self._pes do
@@ -732,7 +712,6 @@ function Demuxer.reset(self: Demuxer)
self._qtail = 0
end
-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT).
function Demuxer.streamFor(self: Demuxer, kind: string): Stream?
for _, s in self.streams do
if s.kind == kind then
@@ -744,9 +723,6 @@ end
export type DemuxOptions = { videoPid: number?, audioPid: number? }
-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid /
-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video /
-- audio (PES stream_id). Never throws; a bad argument gives empty lists.
function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
local d = MpegTs.new()
d:push(data)
@@ -796,7 +772,6 @@ function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
}
end
-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open).
function MpegTs.concat(units: { Unit }): buffer
local n = 0
for _, u in units do