A sweep for duplicated function bodies, CRC tables and base64 across src/Formats: - core/Crc32.msb / MSB_TABLE: the MSB-first 0x04C11DB7 CRC-32 that containers/Ogg (Page + Mux), containers/MpegTs and codecs/Bzip2 each built (test vectors CRC-32/MPEG-2 and /BZIP2 in tests/core/bytes). - audio/flac/Encode uses audio/flac/Frame's CRC-8 / CRC-16 tables (Frame.crc8 added) instead of its own copy. - core/Bytes.toBuffer / Bytes.span: the (buffer | string, offset, length) argument checking codecs/Deflate, codecs/Lzma and codecs/Brotli each carried. - codecs/Text.utf8char: one copy instead of four (codecs/Json, codecs/Xml, data/yaml, data/toml). - Types.keyLess / Types.isArray (small additions to Types, backward compatible): data/msgpack, data/cbor and data/yaml/Emit had identical copies. - playlist/pls: dead copies of m3u's attributes / extinf removed. Left on purpose: per-codec bit readers / writers in hot loops (STYLE.md: inner loops keep their own bit buffers), same-folder helpers (Alac signExtend, Vorbis ilog), Zip's DOS-date civil() (a different epoch helper).
816 lines
21 KiB
Luau
816 lines
21 KiB
Luau
--!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.
|
|
local Crc32 = require("@formats/core/Crc32")
|
|
|
|
local MpegTs = {}
|
|
|
|
export type Stream = {
|
|
pid: number,
|
|
streamType: number, -- PMT stream_type (0 when the stream was found without a PMT)
|
|
kind: string, -- "video" | "audio" | "other"
|
|
codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ...
|
|
program: number, -- program_number (0 without a PMT)
|
|
language: string?, -- ISO 639 language descriptor, when present
|
|
}
|
|
|
|
export type Unit = {
|
|
pid: number,
|
|
kind: string,
|
|
codec: string,
|
|
streamType: number,
|
|
streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio)
|
|
pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID)
|
|
dts: number?, -- seconds; equals pts when the PES carries no DTS
|
|
pts90: number?, -- the same in 90 kHz ticks
|
|
dts90: number?,
|
|
data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio)
|
|
ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit
|
|
randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set
|
|
discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set
|
|
}
|
|
|
|
export type Stats = {
|
|
packets: number,
|
|
syncLosses: number, -- resyncs (bytes skipped to find 0x47 again)
|
|
skippedBytes: number,
|
|
teiErrors: number, -- transport_error_indicator packets (dropped)
|
|
ccErrors: number, -- continuity counter gaps
|
|
duplicates: number, -- duplicate packets (same CC), dropped
|
|
crcErrors: number, -- PSI sections with a bad CRC (ignored)
|
|
pesErrors: number, -- PES units without a valid header (dropped)
|
|
scrambled: number, -- scrambled packets (dropped)
|
|
pcr: number?, -- last PCR seen, seconds
|
|
}
|
|
|
|
export type Demuxed = {
|
|
video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order
|
|
audio: { Unit }, -- units of the selected audio PID
|
|
streams: { Stream }, -- every elementary stream, PMT order
|
|
units: { Unit }, -- every unit of every PID, in completion order
|
|
videoPid: number?,
|
|
audioPid: number?,
|
|
stats: Stats,
|
|
}
|
|
|
|
type PesState = {
|
|
buf: buffer,
|
|
len: number,
|
|
active: boolean,
|
|
expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start)
|
|
hdrChecked: boolean,
|
|
ccError: boolean,
|
|
randomAccess: boolean,
|
|
discontinuity: boolean,
|
|
lastPts: number, -- for 33-bit wrap unwrapping
|
|
wrapOffset: number,
|
|
}
|
|
|
|
type SectionState = { buf: buffer, len: number, active: boolean }
|
|
|
|
local TS_SIZE = 188
|
|
local SYNC = 0x47
|
|
local MAX_SECTION = 4096 + 188
|
|
local WRAP = 8589934592 -- 2^33
|
|
|
|
local readu8 = buffer.readu8
|
|
local band = bit32.band
|
|
local bor = bit32.bor
|
|
local lshift = bit32.lshift
|
|
local rshift = bit32.rshift
|
|
|
|
local CODECS: { [number]: { string } } = {
|
|
[0x01] = { "video", "mpeg1video" },
|
|
[0x02] = { "video", "mpeg2video" },
|
|
[0x03] = { "audio", "mpegaudio" },
|
|
[0x04] = { "audio", "mpegaudio" },
|
|
[0x0F] = { "audio", "aac" },
|
|
[0x10] = { "video", "mpeg4" },
|
|
[0x11] = { "audio", "aac_latm" },
|
|
[0x1B] = { "video", "h264" },
|
|
[0x24] = { "video", "hevc" },
|
|
[0x81] = { "audio", "ac3" },
|
|
[0x87] = { "audio", "eac3" },
|
|
}
|
|
|
|
-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0
|
|
local function crc32(b: buffer, off: number, n: number): number
|
|
return Crc32.msb(b, off, n, 0xFFFFFFFF)
|
|
end
|
|
MpegTs.crc32 = crc32
|
|
|
|
local function u16(b: buffer, p: number): number
|
|
return readu8(b, p) * 256 + readu8(b, p + 1)
|
|
end
|
|
|
|
-- 33-bit timestamp from the 5-byte PES encoding at p
|
|
local function readTs(b: buffer, p: number): number
|
|
local b0 = readu8(b, p)
|
|
local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30
|
|
local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15
|
|
local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0
|
|
return hi + mid * 32768 + lo
|
|
end
|
|
|
|
local Demuxer = {}
|
|
Demuxer.__index = Demuxer
|
|
|
|
export type Demuxer = typeof(setmetatable(
|
|
{} :: {
|
|
_pend: buffer,
|
|
_pendLen: number,
|
|
_pmtPids: { [number]: number },
|
|
_streams: { [number]: Stream },
|
|
_pes: { [number]: PesState },
|
|
_sections: { [number]: SectionState },
|
|
_cc: { [number]: number },
|
|
_queue: { Unit },
|
|
_qhead: number,
|
|
_qtail: number,
|
|
streams: { Stream },
|
|
stats: Stats,
|
|
},
|
|
Demuxer
|
|
))
|
|
|
|
function MpegTs.new(): Demuxer
|
|
local self = setmetatable({
|
|
_pend = buffer.create(64 * 1024),
|
|
_pendLen = 0,
|
|
_pmtPids = {},
|
|
_streams = {},
|
|
_pes = {},
|
|
_sections = {},
|
|
_cc = {},
|
|
_queue = {},
|
|
_qhead = 1,
|
|
_qtail = 0,
|
|
streams = {},
|
|
stats = {
|
|
packets = 0,
|
|
syncLosses = 0,
|
|
skippedBytes = 0,
|
|
teiErrors = 0,
|
|
ccErrors = 0,
|
|
duplicates = 0,
|
|
crcErrors = 0,
|
|
pesErrors = 0,
|
|
scrambled = 0,
|
|
pcr = nil,
|
|
} :: Stats,
|
|
}, Demuxer)
|
|
return self
|
|
end
|
|
|
|
-- PSI ---------------------------------------------------------------------------------------------------------
|
|
|
|
local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?)
|
|
local info = CODECS[streamType]
|
|
local s = self._streams[pid]
|
|
if s == nil then
|
|
s = {
|
|
pid = pid,
|
|
streamType = streamType,
|
|
kind = if info then info[1] else "other",
|
|
codec = if info then info[2] else "unknown",
|
|
program = program,
|
|
language = language,
|
|
}
|
|
self._streams[pid] = s
|
|
table.insert(self.streams, s)
|
|
else
|
|
s.streamType = streamType
|
|
s.kind = if info then info[1] else "other"
|
|
s.codec = if info then info[2] else "unknown"
|
|
s.program = program
|
|
s.language = language
|
|
end
|
|
end
|
|
|
|
local function parseSection(self: Demuxer, pid: number, b: buffer, n: number)
|
|
-- n >= 3 bytes: table_id, section_length (n = 3 + section_length)
|
|
if n < 12 then
|
|
return
|
|
end
|
|
if band(readu8(b, 1), 0x80) == 0 then
|
|
return -- no section_syntax_indicator: not a PAT / PMT
|
|
end
|
|
if crc32(b, 0, n) ~= 0 then
|
|
self.stats.crcErrors += 1
|
|
return
|
|
end
|
|
if band(readu8(b, 5), 1) == 0 then
|
|
return -- current_next_indicator = 0: a future table
|
|
end
|
|
local tid = readu8(b, 0)
|
|
local stop = n - 4
|
|
if tid == 0x00 and pid == 0 then
|
|
local p = 8
|
|
while p + 4 <= stop do
|
|
local prog = u16(b, p)
|
|
local pmt = band(u16(b, p + 2), 0x1FFF)
|
|
if prog ~= 0 then
|
|
self._pmtPids[pmt] = prog
|
|
end
|
|
p += 4
|
|
end
|
|
elseif tid == 0x02 and self._pmtPids[pid] ~= nil then
|
|
local program = u16(b, 3)
|
|
local p = 12 + band(u16(b, 10), 0x0FFF)
|
|
while p + 5 <= stop do
|
|
local st = readu8(b, p)
|
|
local epid = band(u16(b, p + 1), 0x1FFF)
|
|
local esl = band(u16(b, p + 3), 0x0FFF)
|
|
local d = p + 5
|
|
local dend = math.min(d + esl, stop)
|
|
local language: string? = nil
|
|
while d + 2 <= dend do
|
|
local tag, len = readu8(b, d), readu8(b, d + 1)
|
|
if tag == 0x0A and len >= 3 and d + 5 <= dend then
|
|
language = buffer.readstring(b, d + 2, 3)
|
|
end
|
|
d += 2 + len
|
|
end
|
|
addStream(self, epid, st, program, language)
|
|
p += 5 + esl
|
|
end
|
|
end
|
|
end
|
|
|
|
local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number)
|
|
local n = to - from
|
|
if n <= 0 then
|
|
return
|
|
end
|
|
if s.len + n > MAX_SECTION then
|
|
s.active = false
|
|
s.len = 0
|
|
return
|
|
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
|
|
s.len = 0
|
|
return
|
|
end
|
|
local need = 3 + band(u16(s.buf, 1), 0x0FFF)
|
|
if s.len < need then
|
|
return
|
|
end
|
|
parseSection(self, pid, s.buf, need)
|
|
local rest = s.len - need
|
|
if rest > 0 then
|
|
buffer.copy(s.buf, 0, s.buf, need, rest)
|
|
end
|
|
s.len = rest
|
|
end
|
|
end
|
|
|
|
local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number)
|
|
local s = self._sections[pid]
|
|
if s == nil then
|
|
s = { buf = buffer.create(MAX_SECTION), len = 0, active = false }
|
|
self._sections[pid] = s
|
|
end
|
|
if pusi then
|
|
if pos >= stop then
|
|
return
|
|
end
|
|
local ptr = readu8(b, pos)
|
|
pos += 1
|
|
local tail = math.min(pos + ptr, stop)
|
|
if s.active then
|
|
sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section
|
|
end
|
|
s.active = true
|
|
s.len = 0
|
|
pos = tail
|
|
elseif not s.active then
|
|
return
|
|
end
|
|
sectionBytes(self, pid, s, b, pos, stop)
|
|
end
|
|
|
|
-- PES ---------------------------------------------------------------------------------------------------------
|
|
|
|
local function completePes(self: Demuxer, pid: number, st: PesState)
|
|
st.active = false
|
|
local b, len = st.buf, st.len
|
|
if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then
|
|
self.stats.pesErrors += 1
|
|
return
|
|
end
|
|
local sid = readu8(b, 3)
|
|
local stop = if st.expected > 0 then math.min(st.expected, len) else len
|
|
local start = 6
|
|
local pts: number?, dts: number? = nil, nil
|
|
if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then
|
|
if stop < 9 then
|
|
self.stats.pesErrors += 1
|
|
return
|
|
end
|
|
if band(readu8(b, 6), 0xC0) == 0x80 then
|
|
-- MPEG-2 PES header
|
|
local flags = readu8(b, 7)
|
|
local hl = readu8(b, 8)
|
|
start = 9 + hl
|
|
if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then
|
|
pts = readTs(b, 9)
|
|
if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then
|
|
dts = readTs(b, 14)
|
|
end
|
|
end
|
|
else
|
|
-- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS
|
|
local p = 6
|
|
local k = 0
|
|
while p < stop and readu8(b, p) == 0xFF and k < 16 do
|
|
p += 1
|
|
k += 1
|
|
end
|
|
if p < stop and band(readu8(b, p), 0xC0) == 0x40 then
|
|
p += 2
|
|
end
|
|
if p < stop then
|
|
local c = band(readu8(b, p), 0xF0)
|
|
if c == 0x20 and p + 5 <= stop then
|
|
pts = readTs(b, p)
|
|
p += 5
|
|
elseif c == 0x30 and p + 10 <= stop then
|
|
pts = readTs(b, p)
|
|
dts = readTs(b, p + 5)
|
|
p += 10
|
|
else
|
|
p += 1
|
|
end
|
|
end
|
|
start = p
|
|
end
|
|
end
|
|
if start > stop then
|
|
self.stats.pesErrors += 1
|
|
return
|
|
end
|
|
-- unwrap the 33-bit clock (per PID)
|
|
if pts ~= nil then
|
|
pts += st.wrapOffset
|
|
if st.lastPts >= 0 then
|
|
if pts < st.lastPts - WRAP / 2 then
|
|
st.wrapOffset += WRAP
|
|
pts += WRAP
|
|
elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then
|
|
st.wrapOffset -= WRAP
|
|
pts -= WRAP
|
|
end
|
|
end
|
|
st.lastPts = pts
|
|
if dts ~= nil then
|
|
dts += st.wrapOffset
|
|
if dts > pts + WRAP / 2 then
|
|
dts -= WRAP
|
|
elseif dts < pts - WRAP / 2 then
|
|
dts += WRAP
|
|
end
|
|
else
|
|
dts = pts
|
|
end
|
|
end
|
|
local n = stop - start
|
|
local data = buffer.create(n)
|
|
if n > 0 then
|
|
buffer.copy(data, 0, b, start, n)
|
|
end
|
|
local s = self._streams[pid]
|
|
local kind, codec, streamType
|
|
if s then
|
|
kind, codec, streamType = s.kind, s.codec, s.streamType
|
|
elseif sid >= 0xE0 and sid <= 0xEF then
|
|
kind, codec, streamType = "video", "unknown", 0
|
|
elseif sid >= 0xC0 and sid <= 0xDF then
|
|
kind, codec, streamType = "audio", "mpegaudio", 0
|
|
else
|
|
kind, codec, streamType = "other", "unknown", 0
|
|
end
|
|
local unit: Unit = {
|
|
pid = pid,
|
|
kind = kind,
|
|
codec = codec,
|
|
streamType = streamType,
|
|
streamId = sid,
|
|
pts = if pts then pts / 90000 else nil,
|
|
dts = if dts then dts / 90000 else nil,
|
|
pts90 = pts,
|
|
dts90 = dts,
|
|
data = data,
|
|
ccError = st.ccError,
|
|
randomAccess = st.randomAccess,
|
|
discontinuity = st.discontinuity,
|
|
}
|
|
local tail = self._qtail + 1
|
|
self._qtail = tail
|
|
self._queue[tail] = unit
|
|
end
|
|
|
|
local function pesPayload(
|
|
self: Demuxer,
|
|
pid: number,
|
|
pusi: boolean,
|
|
b: buffer,
|
|
pos: number,
|
|
stop: number,
|
|
ccError: boolean,
|
|
randomAccess: boolean,
|
|
discontinuity: boolean
|
|
)
|
|
local st = self._pes[pid]
|
|
-- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored
|
|
local startCode = pusi
|
|
and stop - pos >= 3
|
|
and readu8(b, pos) == 0
|
|
and readu8(b, pos + 1) == 0
|
|
and readu8(b, pos + 2) == 1
|
|
if st == nil then
|
|
if not startCode then
|
|
return
|
|
end
|
|
st = {
|
|
buf = buffer.create(16 * 1024),
|
|
len = 0,
|
|
active = false,
|
|
expected = 0,
|
|
hdrChecked = false,
|
|
ccError = false,
|
|
randomAccess = false,
|
|
discontinuity = false,
|
|
lastPts = -1,
|
|
wrapOffset = 0,
|
|
}
|
|
self._pes[pid] = st
|
|
end
|
|
if ccError and st.active then
|
|
st.ccError = true -- packets of the unit in progress were lost
|
|
end
|
|
if pusi then
|
|
if st.active then
|
|
completePes(self, pid, st)
|
|
end
|
|
if not startCode then
|
|
if self._streams[pid] ~= nil then
|
|
self.stats.pesErrors += 1
|
|
end
|
|
return
|
|
end
|
|
st.active = true
|
|
st.len = 0
|
|
st.expected = 0
|
|
st.hdrChecked = false
|
|
st.ccError = false
|
|
st.randomAccess = randomAccess
|
|
st.discontinuity = discontinuity
|
|
elseif not st.active then
|
|
return
|
|
end
|
|
local n = stop - pos
|
|
if n <= 0 then
|
|
return
|
|
end
|
|
if st.len + n > buffer.len(st.buf) then
|
|
local cap = buffer.len(st.buf) * 2
|
|
while cap < st.len + n do
|
|
cap *= 2
|
|
end
|
|
if cap > 64 * 1024 * 1024 then
|
|
st.active = false -- runaway unit (no unit start for 64 MB): drop it
|
|
st.len = 0
|
|
self.stats.pesErrors += 1
|
|
return
|
|
end
|
|
local nb = buffer.create(cap)
|
|
buffer.copy(nb, 0, st.buf, 0, st.len)
|
|
st.buf = nb
|
|
end
|
|
buffer.copy(st.buf, st.len, b, pos, n)
|
|
st.len += n
|
|
if not st.hdrChecked and st.len >= 6 then
|
|
st.hdrChecked = true
|
|
local plen = u16(st.buf, 4)
|
|
if plen > 0 then
|
|
st.expected = 6 + plen
|
|
end
|
|
end
|
|
if st.expected > 0 and st.len >= st.expected then
|
|
completePes(self, pid, st)
|
|
end
|
|
end
|
|
|
|
-- packets -----------------------------------------------------------------------------------------------------
|
|
|
|
local function packet(self: Demuxer, b: buffer, pk: number)
|
|
local stats = self.stats
|
|
stats.packets += 1
|
|
local b1 = readu8(b, pk + 1)
|
|
if band(b1, 0x80) ~= 0 then
|
|
stats.teiErrors += 1
|
|
return
|
|
end
|
|
local pusi = band(b1, 0x40) ~= 0
|
|
local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2)
|
|
if pid == 0x1FFF then
|
|
return
|
|
end
|
|
local b3 = readu8(b, pk + 3)
|
|
if band(b3, 0xC0) ~= 0 then
|
|
stats.scrambled += 1
|
|
return
|
|
end
|
|
local afc = band(rshift(b3, 4), 3)
|
|
local cc = band(b3, 15)
|
|
if afc == 0 then
|
|
return
|
|
end
|
|
local pos = pk + 4
|
|
local stop = pk + TS_SIZE
|
|
local discontinuity, randomAccess = false, false
|
|
if afc >= 2 then
|
|
local afl = readu8(b, pos)
|
|
pos += 1
|
|
if afl > 183 then
|
|
return
|
|
end
|
|
if afl > 0 then
|
|
local flags = readu8(b, pos)
|
|
discontinuity = band(flags, 0x80) ~= 0
|
|
randomAccess = band(flags, 0x40) ~= 0
|
|
if band(flags, 0x10) ~= 0 and afl >= 7 then
|
|
local base = readu8(b, pos + 1) * 33554432
|
|
+ readu8(b, pos + 2) * 131072
|
|
+ readu8(b, pos + 3) * 512
|
|
+ readu8(b, pos + 4) * 2
|
|
+ rshift(readu8(b, pos + 5), 7)
|
|
local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6)
|
|
stats.pcr = base / 90000 + ext / 27000000
|
|
end
|
|
end
|
|
pos += afl
|
|
if afc == 2 then
|
|
if discontinuity then
|
|
self._cc[pid] = nil
|
|
end
|
|
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
|
|
if cc == last then
|
|
stats.duplicates += 1
|
|
return
|
|
elseif cc ~= band(last + 1, 15) then
|
|
ccError = true
|
|
stats.ccErrors += 1
|
|
end
|
|
end
|
|
self._cc[pid] = cc
|
|
if pid == 0 or self._pmtPids[pid] ~= nil then
|
|
sectionPayload(self, pid, pusi, b, pos, stop)
|
|
elseif pid >= 0x10 then
|
|
pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity)
|
|
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
|
|
src = buffer.fromstring(data)
|
|
elseif type(data) == "buffer" then
|
|
src = data
|
|
else
|
|
return false
|
|
end
|
|
local off = math.max(0, math.floor(offset or 0))
|
|
local total = buffer.len(src)
|
|
if off > total then
|
|
return false
|
|
end
|
|
local n = math.min(math.floor(len or (total - off)), total - off)
|
|
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)
|
|
while cap < need do
|
|
cap *= 2
|
|
end
|
|
local nb = buffer.create(cap)
|
|
buffer.copy(nb, 0, self._pend, 0, self._pendLen)
|
|
self._pend = nb
|
|
end
|
|
if n > 0 then
|
|
buffer.copy(self._pend, self._pendLen, src, off, n)
|
|
end
|
|
self._pendLen = need
|
|
local b, avail = self._pend, self._pendLen
|
|
local p = 0
|
|
while p + TS_SIZE <= avail do
|
|
if readu8(b, p) ~= SYNC then
|
|
-- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data)
|
|
self.stats.syncLosses += 1
|
|
local q = p + 1
|
|
local found = -1
|
|
local waitAt = -1
|
|
while q < avail do
|
|
if readu8(b, q) == SYNC then
|
|
if q + TS_SIZE < avail then
|
|
if readu8(b, q + TS_SIZE) == SYNC then
|
|
found = q
|
|
break
|
|
end
|
|
elseif q + TS_SIZE == avail then
|
|
found = q
|
|
break
|
|
else
|
|
waitAt = q -- not enough bytes to confirm: wait for more
|
|
break
|
|
end
|
|
end
|
|
q += 1
|
|
end
|
|
if found >= 0 then
|
|
self.stats.skippedBytes += found - p
|
|
p = found
|
|
elseif waitAt >= 0 then
|
|
self.stats.skippedBytes += waitAt - p
|
|
p = waitAt
|
|
break
|
|
else
|
|
self.stats.skippedBytes += avail - p
|
|
p = avail
|
|
break
|
|
end
|
|
else
|
|
packet(self, b, p)
|
|
p += TS_SIZE
|
|
end
|
|
end
|
|
local rest = avail - p
|
|
if rest > 0 and p > 0 then
|
|
buffer.copy(b, 0, b, p, rest)
|
|
end
|
|
self._pendLen = rest
|
|
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
|
|
local u = q[h]
|
|
if u == nil then
|
|
return nil
|
|
end
|
|
q[h] = nil :: any
|
|
h += 1
|
|
if h > self._qtail then
|
|
table.clear(q)
|
|
h = 1
|
|
self._qtail = 0
|
|
end
|
|
self._qhead = h
|
|
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
|
|
if st.active then
|
|
table.insert(pids, pid)
|
|
end
|
|
end
|
|
table.sort(pids)
|
|
for _, pid in pids do
|
|
completePes(self, pid, self._pes[pid])
|
|
end
|
|
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
|
|
st.active = false
|
|
st.len = 0
|
|
st.lastPts = -1
|
|
st.wrapOffset = 0
|
|
end
|
|
for _, s in self._sections do
|
|
s.active = false
|
|
s.len = 0
|
|
end
|
|
table.clear(self._cc)
|
|
table.clear(self._queue)
|
|
self._qhead = 1
|
|
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
|
|
return s
|
|
end
|
|
end
|
|
return nil
|
|
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)
|
|
d:flush()
|
|
local units = {}
|
|
while true do
|
|
local u = d:pull()
|
|
if u == nil then
|
|
break
|
|
end
|
|
table.insert(units, u)
|
|
end
|
|
local videoPid = opts and opts.videoPid
|
|
local audioPid = opts and opts.audioPid
|
|
if videoPid == nil then
|
|
local s = d:streamFor("video")
|
|
videoPid = if s then s.pid else nil
|
|
end
|
|
if audioPid == nil then
|
|
local s = d:streamFor("audio")
|
|
audioPid = if s then s.pid else nil
|
|
end
|
|
for _, u in units do
|
|
if videoPid == nil and u.kind == "video" then
|
|
videoPid = u.pid
|
|
end
|
|
if audioPid == nil and u.kind == "audio" then
|
|
audioPid = u.pid
|
|
end
|
|
end
|
|
local video, audio = {}, {}
|
|
for _, u in units do
|
|
if u.pid == videoPid then
|
|
table.insert(video, u)
|
|
elseif u.pid == audioPid then
|
|
table.insert(audio, u)
|
|
end
|
|
end
|
|
return {
|
|
video = video,
|
|
audio = audio,
|
|
streams = d.streams,
|
|
units = units,
|
|
videoPid = videoPid,
|
|
audioPid = audioPid,
|
|
stats = d.stats,
|
|
}
|
|
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
|
|
n += buffer.len(u.data)
|
|
end
|
|
local out = buffer.create(n)
|
|
local p = 0
|
|
for _, u in units do
|
|
local l = buffer.len(u.data)
|
|
buffer.copy(out, p, u.data, 0, l)
|
|
p += l
|
|
end
|
|
return out
|
|
end
|
|
|
|
return MpegTs
|