ws-m4a: containers/IsoBmff (box tree, demux: stsd entries + codec configs, stts/ctts/stsc/stsz/stz2/stco/co64/stss, elst, fragments; HEIF/AVIF items; iTunes tags read/write; progressive muxer), tested packet-for-packet against ffprobe

This commit is contained in:
4DBug committed 2026-10-31 08:37:32 -05:00
1 parent 859a96ea79
commit 064af84d63
7 files changed
+2604

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
--!strict
-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit
-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container
-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...).
-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws.
local Err = require("@formats/core/Err")
local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring
local byteswap = bit32.byteswap
local Box = {}
export type Box = {
type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid`
start: number, -- absolute offset of the box in the buffer
size: number, -- the whole box, header included
data: number, -- absolute offset of the payload (after size / type / largesize / uuid)
stop: number, -- absolute offset just past the box (start + size, clamped to the parent)
uuid: string?,
children: { Box }?, -- container boxes
truncated: boolean?, -- the box claims more bytes than its parent has (clamped)
}
-- plain container boxes: their payload is a list of boxes
local CONTAINERS = {
moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true,
mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true,
schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true,
strk = true, strd = true, grpl = true, meco = true, mere = true,
}
-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes
local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 }
Box.CONTAINERS = CONTAINERS
local function be32(b: buffer, o: number): number
return byteswap(readu32(b, o))
end
Box.be32 = be32
-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes
local function isIlstItem(parentType: string?): boolean
return parentType == "ilst"
end
-- header(buf, p, limit) -> Box (without children) | nil, Err
function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?)
if p + 8 > limit then
return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p)
end
local size = be32(b, p)
local typ = readstring(b, p + 4, 4)
local data = p + 8
if size == 1 then
if p + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p)
end
size = be32(b, p + 8) * 4294967296 + be32(b, p + 12)
data = p + 16
elseif size == 0 then
size = limit - p
end
local uuid: string? = nil
if typ == "uuid" then
if data + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p)
end
uuid = readstring(b, data, 16)
data += 16
end
if size < data - p then
return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p)
end
local stop = p + size
local truncated: boolean? = nil
if stop > limit then
stop = limit
truncated = true
end
return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil
end
-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A
-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any.
function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?)
local d = depth or 0
local out: { Box } = {}
local firstErr: Err.Err? = nil
if d > 32 then
return out, Err.new(Err.CORRUPT, "boxes nested too deep", p)
end
while p + 8 <= limit do
local box, err = Box.header(b, p, limit)
if not box then
firstErr = firstErr or err
break
end
if box.truncated then
firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p)
end
local t = box.type
local kids: { Box }? = nil
local kerr: Err.Err? = nil
if CONTAINERS[t] or isIlstItem(parentType) then
kids, kerr = Box.list(b, box.data, box.stop, t, d + 1)
elseif FULL_CONTAINERS[t] then
local q = box.data + 4 + FULL_CONTAINERS[t]
-- QuickTime writes udta/meta as a plain container: its first child box follows directly
if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then
q = box.data
end
if q <= box.stop then
kids, kerr = Box.list(b, q, box.stop, t, d + 1)
end
elseif t == "iinf" then
if box.data + 4 <= box.stop then
local v = readu8(b, box.data)
local q = box.data + 4 + (if v == 0 then 2 else 4)
if q <= box.stop then
kids, kerr = Box.list(b, q, box.stop, t, d + 1)
end
end
end
box.children = kids
if kerr then
firstErr = firstErr or kerr
end
table.insert(out, box)
if box.stop <= p then
break
end
p = box.stop
end
return out, firstErr
end
-- child(box, type) -> the first child of that type
function Box.child(box: Box?, typ: string): Box?
if not box or not box.children then
return nil
end
for _, c in box.children :: { Box } do
if c.type == typ then
return c
end
end
return nil
end
-- children(box, type) -> every child of that type
function Box.childrenOf(box: Box?, typ: string): { Box }
local out = {}
if box and box.children then
for _, c in box.children :: { Box } do
if c.type == typ then
table.insert(out, c)
end
end
end
return out
end
-- path(boxes or box, "moov/trak/mdia") -> the first box along the path
function Box.path(root: any, path: string): Box?
local cur: any = root
for part in string.gmatch(path, "[^/]+") do
if cur == nil then
return nil
end
local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur
local found = nil
if list then
for _, c in list do
if c.type == part then
found = c
break
end
end
end
cur = found
end
return cur
end
-- version / flags of a full box
function Box.fullHeader(b: buffer, box: Box): (number, number)
if box.data + 4 > box.stop then
return -1, 0
end
local v = be32(b, box.data)
return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF)
end
return Box
+848
View File
@@ -0,0 +1,848 @@
--!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.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local readstring = buffer.readstring
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",
codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc
entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...)
handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...)
timescale: number,
duration: number, -- seconds (media duration; the edit list may shorten it)
mediaDuration: number, -- ticks
language: string?, -- ISO 639-2 ("und", "eng", ...)
width: number?,
height: number?,
sampleRate: number?,
channels: number?,
bitsPerSample: number?,
config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...)
objectType: number?, -- esds objectTypeIndication
pcm: { bits: number, float: boolean, little: boolean }?,
entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...)
edits: { Edit }?,
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 },
dts: { number }, -- decode times in ticks
durations: { number },
cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets
sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample)
sampleDescription: { number }?, -- stsd index per sample when there are several entries
[string]: any,
}
export type Options = { maxSamples: number? }
local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = {
soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle",
sbtl = "subtitle", clcp = "subtitle",
}
local CODEC: { [string]: string } = {
mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3",
lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm",
ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb",
avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9",
mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1",
["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text",
}
-- esds objectTypeIndication -> codec
local OTI: { [number]: string } = {
[0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1",
[0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3",
[0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis",
}
-- the box holding each video / audio codec's configuration
local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" }
local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true }
local function payload(b: buffer, box: Box.Box, skip: number?): buffer
local o = box.data + (skip or 0)
local n = math.max(0, box.stop - o)
local out = buffer.create(n)
if n > 0 then
buffer.copy(out, 0, b, o, n)
end
return out
end
local function reader(b: buffer, box: Box.Box): Bytes.Reader
return Bytes.reader(b, box.data, box.stop - box.data)
end
-- expandable descriptor length (ISO 14496-1 8.3.3)
local function descLen(r: Bytes.Reader): number
local n = 0
for _ = 1, 4 do
local c = r:u8()
n = n * 128 + bit32.band(c, 127)
if c < 128 then
break
end
end
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
if r:u8() ~= 3 then
return nil, nil, nil
end
descLen(r)
r:skip(2) -- ES_ID
local flags = r:u8()
if bit32.band(flags, 0x80) ~= 0 then
r:skip(2)
end
if bit32.band(flags, 0x40) ~= 0 then
r:skip(r:u8())
end
if bit32.band(flags, 0x20) ~= 0 then
r:skip(2)
end
if r:u8() ~= 4 then
return nil, nil, nil
end
local dlen = descLen(r)
local dstart = r.pos
local oti = r:u8()
r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate
local avg = r:u32be()
local dsi: buffer? = nil
if r.pos < dstart + dlen and r:u8() == 5 then
local n = descLen(r)
if n > 0 and r:need(n) then
dsi = r:bytes(n)
end
end
if r.err then
return oti, nil, nil
end
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)
r:skip(2) -- data reference index
local typ = e.type
t.entry = typ
t.codec = CODEC[typ] or typ
local kind = t.kind
local childStart
if kind == "audio" then
local version = r:u16be()
r:skip(2 + 4) -- revision, vendor
local channels = r:u16be()
local bits = r:u16be()
r:skip(4) -- compression id, packet size
local rate = r:u32be() / 65536
if version == 1 then
r:skip(16)
elseif version == 2 then
r:skip(4)
rate = r:f64be()
channels = r:u32be()
r:skip(4)
bits = r:u32be()
local lpcmFlags = r:u32be()
r:skip(8)
if typ == "lpcm" then
t.pcm = {
bits = bits,
float = bit32.band(lpcmFlags, 1) ~= 0,
little = bit32.band(lpcmFlags, 2) == 0,
}
end
end
t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits
if not t.pcm and t.codec == "pcm" then
local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 }
t.pcm = {
bits = B[typ] or bits,
float = typ == "fl32" or typ == "fl64",
little = typ == "sowt",
}
end
childStart = r.pos
elseif kind == "video" then
r:skip(16)
t.width = r:u16be()
t.height = r:u16be()
r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2)
childStart = r.pos
else
childStart = r.pos
end
if r.err then
t.entryBoxes = {}
return
end
local kids = Box.list(b, childStart, e.stop, typ)
t.entryBoxes = kids
-- QuickTime puts the codec boxes inside 'wave'
local all = table.clone(kids)
local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave")
if wave and wave.children then
for _, c in wave.children :: { Box.Box } do
table.insert(all, c)
end
end
local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any
local esds = Box.child(holder, "esds")
if esds then
local oti, dsi, avg = Demux.esds(b, esds)
t.objectType = oti
if oti and OTI[oti] then
t.codec = OTI[oti]
end
t.config = dsi
if avg and avg > 0 then
t.bitrate = avg
end
end
if typ == "alac" then
local a = Box.child(holder, "alac")
if a then
t.config = payload(b, a, 4)
end
end
for _, name in CONFIG_BOX do
local c = Box.child(holder, name)
if c then
t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0)
break
end
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")
if not tkhd or not mdia then
return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start)
end
local t: Track = {
id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0,
entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {},
}
do
local r = reader(b, tkhd)
local v = r:u8()
r:skip(3)
if v == 1 then
r:skip(16)
t.id = r:u32be()
r:skip(4 + 8)
else
r:skip(8)
t.id = r:u32be()
r:skip(4 + 4)
end
r:skip(8 + 2 + 2 + 2 + 2 + 36)
local w, h = r:u32be() / 65536, r:u32be() / 65536
if r.err then
return nil, r.err
end
if w > 0 and h > 0 then
t.width, t.height = math.floor(w), math.floor(h)
end
end
local mdhd = Box.child(mdia, "mdhd")
if mdhd then
local r = reader(b, mdhd)
local v = r:u8()
r:skip(3)
if v == 1 then
r:skip(16)
t.timescale = r:u32be()
t.mediaDuration = r:u64be()
else
r:skip(8)
t.timescale = r:u32be()
t.mediaDuration = r:u32be()
end
local lang = r:u16be()
if not r.err and lang ~= 0 and lang ~= 0x7FFF then
t.language = string.char(
96 + bit32.band(bit32.rshift(lang, 10), 31),
96 + bit32.band(bit32.rshift(lang, 5), 31),
96 + bit32.band(lang, 31)
)
end
if t.timescale == 0 then
t.timescale = 1
end
end
local hdlr = Box.child(mdia, "hdlr")
if hdlr and hdlr.data + 12 <= hdlr.stop then
t.handler = readstring(b, hdlr.data + 8, 4)
end
t.kind = HANDLER_KIND[t.handler] or "data"
local stbl = Box.path(mdia, "minf/stbl")
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")
if entries[1] then
sampleEntry(b, entries[1], t.handler, t)
end
t.sampleEntries = entries
end
-- edit list
local elst = Box.path(trak, "edts/elst")
if elst then
local r = reader(b, elst)
local v = r:u8()
r:skip(3)
local n = r:u32be()
if n <= (elst.stop - elst.data) // 12 then
local edits = {}
for _ = 1, n do
local dur, mt
if v == 1 then
dur, mt = r:u64be(), r:i64be()
else
dur, mt = r:u32be(), r:i32be()
end
local rate = r:i32be() / 65536
if r.err then
break
end
table.insert(edits, { duration = dur, mediaTime = mt, rate = rate })
end
t.edits = edits
local play = 0
local started = false
for _, ed in edits do
if ed.mediaTime == -1 then
if not started then
t.delay += ed.duration
end
else
if not started then
t.skip = ed.mediaTime
started = true
end
play += ed.duration * t.timescale / math.max(1, movieTimescale)
end
end
if started and play > 0 then
t.playDuration = math.floor(play + 0.5)
end
end
end
-- sample sizes
local maxSamples = o.maxSamples or 2 ^ 25
local sizes = t.sizes
local count = 0
local stsz = Box.child(stbl, "stsz")
local stz2 = Box.child(stbl, "stz2")
if stsz then
local r = reader(b, stsz)
r:skip(4)
local fixed = r:u32be()
count = r:u32be()
if r.err then
return nil, r.err
end
if count > maxSamples then
return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start)
end
if fixed ~= 0 then
for i = 1, count do
sizes[i] = fixed
end
else
if count * 4 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start)
end
for i = 1, count do
sizes[i] = r:u32be()
end
end
elseif stz2 then
local r = reader(b, stz2)
r:skip(4 + 3)
local fieldSize = r:u8()
count = r:u32be()
if r.err then
return nil, r.err
end
if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then
return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start)
end
if count * fieldSize / 8 > r:remaining() + 1 then
return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start)
end
for i = 1, count do
if fieldSize == 16 then
sizes[i] = r:u16be()
elseif fieldSize == 8 then
sizes[i] = r:u8()
else
local byte = r:peekU8()
if i % 2 == 1 then
sizes[i] = bit32.rshift(math.max(byte, 0), 4)
else
sizes[i] = bit32.band(math.max(byte, 0), 15)
r:skip(1)
end
end
end
end
-- decode times
local dts, durs = t.dts, t.durations
local stts = Box.child(stbl, "stts")
if stts and count > 0 then
local r = reader(b, stts)
r:skip(4)
local n = r:u32be()
if n * 8 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start)
end
local i, time = 1, 0
for _ = 1, n do
local c, d = r:u32be(), r:u32be()
for _ = 1, c do
if i > count then
break
end
dts[i], durs[i] = time, d
time += d
i += 1
end
end
-- fewer stts entries than samples: repeat the last duration
local last = if i > 1 then durs[i - 1] else 0
while i <= count do
dts[i], durs[i] = time, last
time += last
i += 1
end
else
for i = 1, count do
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)
local v = r:u8()
r:skip(3)
local n = r:u32be()
if n * 8 <= r:remaining() then
local cts = table.create(count, 0)
local i = 1
for _ = 1, n do
local c = r:u32be()
local off = if v == 1 then r:i32be() else r:u32be()
if v == 0 and off >= 2147483648 then
off -= 4294967296 -- writers put negative offsets in version 0 too
end
for _ = 1, c do
if i > count then
break
end
cts[i] = off
i += 1
end
end
t.cts = cts
end
end
-- sync samples
local stss = Box.child(stbl, "stss")
if stss then
local r = reader(b, stss)
r:skip(4)
local n = r:u32be()
if n * 4 <= r:remaining() then
local sync = {}
for _ = 1, n do
sync[r:u32be()] = true
end
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 } = {}
if stco or co64 then
local box = (stco or co64) :: Box.Box
local r = reader(b, box)
r:skip(4)
local n = r:u32be()
local w = if co64 then 8 else 4
if n * w > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start)
end
for i = 1, n do
chunks[i] = if co64 then r:u64be() else r:u32be()
end
end
local stsc = Box.child(stbl, "stsc")
local offsets = t.offsets
if count > 0 then
if not stsc or #chunks == 0 then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start)
end
local r = reader(b, stsc)
r:skip(4)
local n = r:u32be()
if n * 12 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start)
end
local first, per, desc = {}, {}, {}
for k = 1, n do
first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be()
end
local sdi: { number }? = nil
if n > 0 then
for k = 1, n do
if desc[k] ~= desc[1] then
sdi = table.create(count, 1)
end
end
end
local i = 1
local base = 0 -- added by the caller (the file's offset in the buffer)
for k = 1, n do
local c0 = first[k]
local c1 = if k < n then first[k + 1] - 1 else #chunks
if c0 < 1 then
return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start)
end
for c = c0, math.min(c1, #chunks) do
local off = chunks[c] + base
for _ = 1, per[k] do
if i > count then
break
end
offsets[i] = off
if sdi then
sdi[i] = desc[k]
end
off += sizes[i]
i += 1
end
if i > count then
break
end
end
if i > count then
break
end
end
if i <= count then
return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start)
end
t.sampleDescription = sdi
end
t.sampleCount = count
-- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024
-- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio.
if t.kind == "audio" and count > 1 and not t.cts and not t.sync then
local fixed = sizes[1]
local uniform = fixed > 0
for i = 1, count do
if sizes[i] ~= fixed or durs[i] ~= 1 then
uniform = false
break
end
end
if uniform then
local no, ns, nd, nu = {}, {}, {}, {}
local i = 1
while i <= count do
local k = 1
while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do
k += 1
end
table.insert(no, offsets[i])
table.insert(ns, k * fixed)
table.insert(nd, dts[i])
table.insert(nu, k)
i += k
end
t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu
t.sampleCount = #no
t.frameSize = fixed
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
if moof.type ~= "moof" then
continue
end
local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end)
local prevEnd = moofStart
for _, traf in Box.childrenOf(moof, "traf") do
local tfhd = Box.child(traf, "tfhd")
if not tfhd then
continue
end
local r = reader(b, tfhd)
r:skip(1)
local flags = r:u24be()
local id = r:u32be()
local t = byId[id]
if r.err or not t then
continue
end
local trex = t.trex or {}
local base
if bit32.band(flags, 0x1) ~= 0 then
base = r:u64be()
elseif bit32.band(flags, 0x20000) ~= 0 then
base = moofStart
else
base = prevEnd
end
if bit32.band(flags, 0x2) ~= 0 then
r:skip(4)
end
local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0)
local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0)
local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0)
if r.err then
return r.err
end
local n0 = t.sampleCount
local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0
local tfdt = Box.child(traf, "tfdt")
if tfdt then
local q = reader(b, tfdt)
local v = q:u8()
q:skip(3)
local bt = if v == 1 then q:u64be() else q:u32be()
if not q.err then
time = bt
end
end
local dataPos = base
for _, trun in Box.childrenOf(traf, "trun") do
local q = reader(b, trun)
local v = q:u8()
local tf = q:u24be()
local n = q:u32be()
if q.err then
return q.err
end
if t.sampleCount + n > maxSamples then
return Err.new(Err.LIMIT, "too many fragment samples", trun.start)
end
if bit32.band(tf, 0x1) ~= 0 then
dataPos = base + q:i32be()
end
local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil
local per = 0
for _, bit in { 0x100, 0x200, 0x400, 0x800 } do
if bit32.band(tf, bit) ~= 0 then
per += 4
end
end
if n * per > q:remaining() then
return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start)
end
for k = 1, n do
local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur
local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize
local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags)
local cto = 0
if bit32.band(tf, 0x800) ~= 0 then
cto = if v == 1 then q:i32be() else q:u32be()
end
local i = t.sampleCount + 1
t.sampleCount = i
t.offsets[i] = dataPos
t.sizes[i] = size
t.dts[i] = time
t.durations[i] = dur
if cto ~= 0 or t.cts then
if not t.cts then
t.cts = table.create(i - 1, 0)
end
(t.cts :: { number })[i] = cto
end
-- sample_is_non_sync_sample (bit 16)
local nonSync = bit32.band(sf, 0x10000) ~= 0
if nonSync then
if not t.sync then
local s = {}
for j = 1, i - 1 do
s[j] = true
end
t.sync = s
end
elseif t.sync then
(t.sync :: any)[i] = true
end
time += dur
dataPos += size
end
prevEnd = dataPos
end
end
end
return nil
end
export type Movie = {
brand: string?,
minor: number?,
compatible: { string },
timescale: number,
duration: number, -- seconds
tracks: { Track },
boxes: { Box.Box },
moov: Box.Box?,
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 = opts or {}
local b = r.buf
local top, terr = Box.list(b, r.base, r.limit)
if #top == 0 then
return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base)
end
local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false }
local ftyp = Box.child({ children = top } :: any, "ftyp")
if ftyp and ftyp.data + 8 <= ftyp.stop then
m.brand = readstring(b, ftyp.data, 4)
m.minor = Box.be32(b, ftyp.data + 4)
local p = ftyp.data + 8
while p + 4 <= ftyp.stop do
table.insert(m.compatible, readstring(b, p, 4))
p += 4
end
end
local moov = Box.child({ children = top } :: any, "moov")
m.moov = moov
if not moov then
return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks
end
local mvhd = Box.child(moov, "mvhd")
local movieDuration = 0
if mvhd then
local q = reader(b, mvhd)
local v = q:u8()
q:skip(3)
if v == 1 then
q:skip(16)
m.timescale = q:u32be()
movieDuration = q:u64be()
else
q:skip(8)
m.timescale = q:u32be()
movieDuration = q:u32be()
end
if q.err or m.timescale == 0 then
m.timescale = 1000
end
end
local trex = {}
local mvex = Box.child(moov, "mvex")
if mvex then
m.fragmented = true
for _, x in Box.childrenOf(mvex, "trex") do
local q = reader(b, x)
q:skip(4)
local id = q:u32be()
q:skip(4)
local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() }
if not q.err then
trex[id] = d
end
end
end
local byId = {}
for _, trak in Box.childrenOf(moov, "trak") do
local t, err = track(b, trak, m.timescale, trex, o)
if not t then
return nil, err
end
table.insert(m.tracks, t)
byId[t.id] = t
end
if m.fragmented then
local ferr = fragments(b, r.base, top, byId, o)
if ferr then
return nil, ferr
end
end
-- durations; drop samples outside the buffer (a truncated file) but keep what is there
for _, t in m.tracks do
local n = t.sampleCount
local ticks = t.mediaDuration
if n > 0 then
ticks = math.max(ticks, t.dts[n] + t.durations[n])
end
t.mediaDuration = ticks
t.duration = ticks / t.timescale
for i = 1, n do
local off = t.offsets[i]
if off < 0 or off + t.sizes[i] > r.limit - r.base then
t.sampleCount = i - 1
t.truncated = true
break
end
end
-- the tables hold file offsets; make them buffer offsets
local base = r.base
if base ~= 0 then
local offs = t.offsets
for i = 1, t.sampleCount do
offs[i] += base
end
end
end
m.duration = movieDuration / m.timescale
if m.duration == 0 then
for _, t in m.tracks do
m.duration = math.max(m.duration, t.duration)
end
end
return m, nil
end
return Demux
+526
View File
@@ -0,0 +1,526 @@
--!strict
-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc
-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC
-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn /
-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer.
-- Never throws.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local readstring = buffer.readstring
local Meta = {}
local function reader(b: buffer, box: Box.Box): Bytes.Reader
return Bytes.reader(b, box.data, box.stop - box.data)
end
local function uint(r: Bytes.Reader, size: number): number
if size == 0 then
return 0
elseif size == 4 then
return r:u32be()
elseif size == 8 then
return r:u64be()
elseif size == 2 then
return r:u16be()
elseif size == 1 then
return r:u8()
end
r:fail(Err.CORRUPT, "bad iloc field size " .. size)
return 0
end
-- ------------------------------------------------------------------------------------------------ HEIF items
export type Property = { type: string, box: Box.Box, [string]: any }
export type Item = {
id: number,
type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ...
name: string,
contentType: string?,
hidden: boolean,
construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item)
baseOffset: number,
extents: { { offset: number, length: number } },
properties: { Property }, -- in ipma order
essential: { [number]: boolean }, -- by index into properties
refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...)
}
export type Items = {
primary: number?,
items: { [number]: Item },
order: { number }, -- item ids in iinf order
idat: Box.Box?,
properties: { Property }, -- ipco, in order
}
local function property(b: buffer, box: Box.Box): Property
local p: Property = { type = box.type, box = box }
local r = reader(b, box)
local t = box.type
if t == "ispe" then
r:skip(4)
p.width, p.height = r:u32be(), r:u32be()
elseif t == "pixi" then
r:skip(4)
local n = r:u8()
local bits = {}
for i = 1, math.min(n, 16) do
bits[i] = r:u8()
end
p.bits = bits
elseif t == "colr" then
local ct = r:string(4)
p.colourType = ct
if ct == "nclx" then
p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be()
p.fullRange = bit32.band(r:u8(), 0x80) ~= 0
elseif ct == "rICC" or ct == "prof" then
p.icc = r:bytes(r:remaining())
end
elseif t == "irot" then
p.angle = bit32.band(r:u8(), 3) * 90
elseif t == "imir" then
p.axis = bit32.band(r:u8(), 1)
elseif t == "clap" then
local function frac(): number
local n, d = r:i32be(), r:u32be()
return if d == 0 then 0 else n / d
end
p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac()
elseif t == "auxC" then
r:skip(4)
p.auxType = r:cstring()
else
local n = box.stop - box.data
local cfg = buffer.create(math.max(0, n))
if n > 0 then
buffer.copy(cfg, 0, b, box.data, n)
end
p.config = cfg
end
return p
end
-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box)
function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?)
local out: Items = { items = {}, order = {}, properties = {} }
local pitm = Box.child(meta, "pitm")
if pitm then
local r = reader(b, pitm)
local v = r:u8()
r:skip(3)
out.primary = if v == 0 then r:u16be() else r:u32be()
end
local iinf = Box.child(meta, "iinf")
if iinf then
for _, infe in Box.childrenOf(iinf, "infe") do
local r = reader(b, infe)
local v = r:u8()
local flags = r:u24be()
local it: Item = {
id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0,
extents = {}, properties = {}, essential = {}, refs = {},
}
if v >= 2 then
it.id = if v == 2 then r:u16be() else r:u32be()
r:skip(2)
it.type = r:string(4)
it.name = r:cstring()
if it.type == "mime" and r:remaining() > 0 then
it.contentType = r:cstring()
end
else
it.id = r:u16be()
r:skip(2)
it.name = r:cstring()
it.contentType = r:cstring()
it.type = "mime"
end
if r.err and it.id == 0 then
return nil, r.err
end
out.items[it.id] = it
table.insert(out.order, it.id)
end
end
local iloc = Box.child(meta, "iloc")
if iloc then
local r = reader(b, iloc)
local v = r:u8()
r:skip(3)
local a, c = r:u8(), r:u8()
local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4)
local idxSize = if v >= 1 then bit32.band(c, 15) else 0
local n = if v < 2 then r:u16be() else r:u32be()
if r.err then
return nil, r.err
end
for _ = 1, n do
local id = if v < 2 then r:u16be() else r:u32be()
local method = 0
if v >= 1 then
method = bit32.band(r:u16be(), 15)
end
r:skip(2) -- data reference index
local base = uint(r, baseSize)
local ne = r:u16be()
if r.err then
return nil, r.err
end
if ne * (offSize + lenSize + idxSize) > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start)
end
local extents = {}
for k = 1, ne do
if idxSize > 0 then
uint(r, idxSize)
end
extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) }
end
if r.err then
return nil, r.err
end
local it = out.items[id]
if not it then
it = {
id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {},
properties = {}, essential = {}, refs = {},
}
out.items[id] = it
table.insert(out.order, id)
end
it.construction, it.baseOffset, it.extents = method, base, extents
end
end
local iref = Box.child(meta, "iref")
if iref then
local v = Box.fullHeader(b, iref)
for _, ref in (iref.children or {}) :: { Box.Box } do
local r = reader(b, ref)
local from = if v == 0 then r:u16be() else r:u32be()
local n = r:u16be()
local to = {}
for k = 1, n do
to[k] = if v == 0 then r:u16be() else r:u32be()
end
local it = out.items[from]
if it and not r.err then
it.refs[ref.type] = to
end
end
end
local ipco = Box.path(meta, "iprp/ipco")
if ipco and ipco.children then
for i, pb in ipco.children :: { Box.Box } do
out.properties[i] = property(b, pb)
end
end
local ipma = Box.path(meta, "iprp/ipma")
if ipma then
local r = reader(b, ipma)
local v = r:u8()
local flags = r:u24be()
local n = r:u32be()
for _ = 1, n do
if r.err then
break
end
local id = if v < 1 then r:u16be() else r:u32be()
local na = r:u8()
local it = out.items[id]
for _ = 1, na do
local idx, ess
if bit32.band(flags, 1) ~= 0 then
local x = r:u16be()
idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000
else
local x = r:u8()
idx, ess = bit32.band(x, 0x7F), x >= 0x80
end
local p = out.properties[idx]
if it and p and not r.err then
table.insert(it.properties, p)
if ess then
it.essential[#it.properties] = true
end
end
end
end
end
out.idat = Box.child(meta, "idat")
return out, nil
end
-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit
-- bound the file in the buffer
function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?)
local it = items.items[id]
if not it then
return nil, Err.new(Err.CORRUPT, "no item " .. id)
end
local origin, stop
if it.construction == 0 then
origin, stop = base, limit
elseif it.construction == 1 then
local idat = items.idat
if not idat then
return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat")
end
origin, stop = idat.data, idat.stop
else
return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction)
end
local total = 0
for _, e in it.extents do
local len = e.length
if len == 0 then -- the whole rest of the file
len = stop - origin - e.offset
end
if e.offset < 0 or len < 0 or origin + e.offset + len > stop then
return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end")
end
total += len
end
if total > 2 ^ 30 then
return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big")
end
local out = buffer.create(total)
local p = 0
for _, e in it.extents do
local len = if e.length == 0 then stop - origin - e.offset else e.length
buffer.copy(out, p, b, origin + e.offset, len)
p += len
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ iTunes tags
-- ilst item -> standard tag name
local TAG: { [string]: string } = {
["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date",
["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder",
["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription",
sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort",
tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate",
["\169pub"] = "publisher", ["\169xyz"] = "location",
}
local TAG_ATOM: { [string]: string } = {}
for atom, name in TAG do
TAG_ATOM[name] = atom
end
Meta.TAG = TAG
Meta.TAG_ATOM = TAG_ATOM
-- the ID3v1 genres gnre indexes (1-based in gnre)
local GENRES = {
"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age",
"Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
"Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion",
"Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock",
"Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic",
"Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult",
"Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
"Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro",
"Musical", "Rock & Roll", "Hard Rock",
}
export type Picture = { mime: string, data: buffer }
-- tags(buf, ilst) -> Tags, { Picture }
function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture })
local tags: { [string]: string } = {}
local pics: { Picture } = {}
if not ilst or not ilst.children then
return tags, pics
end
for _, item in ilst.children :: { Box.Box } do
local typ = item.type
local freeName: string? = nil
if typ == "----" then
local nm = Box.child(item, "name")
if nm and nm.data + 4 <= nm.stop then
freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4)
end
end
for _, d in Box.childrenOf(item, "data") do
if d.data + 8 > d.stop then
continue
end
local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF)
local p, n = d.data + 8, d.stop - d.data - 8
if typ == "trkn" or typ == "disk" then
if n >= 6 then
local num = Box.be32(b, p) % 65536
local total = Box.be32(b, p + 2) % 65536
local key = if typ == "trkn" then "track" else "disc"
if num > 0 then
tags[key] = tostring(num)
end
if total > 0 then
tags[key .. "total"] = tostring(total)
end
end
elseif typ == "gnre" then
if n >= 2 then
local g = GENRES[Box.be32(b, p - 2) % 65536]
if g and not tags.genre then
tags.genre = g
end
end
elseif typ == "tmpo" then
if n >= 2 then
tags.bpm = tostring(Box.be32(b, p - 2) % 65536)
end
elseif typ == "cpil" or typ == "pgap" then
if n >= 1 then
tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p))
end
elseif typ == "covr" then
local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg"
local data = buffer.create(n)
buffer.copy(data, 0, b, p, n)
table.insert(pics, { mime = mime, data = data })
elseif kind == 1 or kind == 0 then
local s = readstring(b, p, n)
local key = freeName or TAG[typ] or typ
if typ == "\169gen" or not tags[key] then
tags[key] = s
end
end
end
end
return tags, pics
end
-- ------------------------------------------------------------------------------------------------ ilst writer
local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ())
local start = w:tell()
w:u32be(0)
w:string(typ)
body(w)
w:setU32be(start, w:tell() - start)
end
Meta.box = box
local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer)
box(w, "data", function()
w:u32be(kind)
w:u32be(0)
if type(value) == "string" then
w:string(value)
else
w:bytes(value)
end
end)
end
local function num(s: string?): number
local v = tonumber(s or "")
if not v then
return 0
end
return math.clamp(math.floor(v), 0, 65535)
end
-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----'
-- freeform com.apple.iTunes items) and cover pictures
function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "ilst", function()
local keys = {}
for k in tags do
table.insert(keys, k)
end
table.sort(keys)
local done: { [string]: boolean } = {}
for _, k in keys do
local v = tags[k]
if type(v) ~= "string" or done[k] then
continue
end
if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then
local base = if k == "track" or k == "tracktotal" then "track" else "disc"
if done[base] then
continue
end
done[base] = true
local atom = if base == "track" then "trkn" else "disk"
local n, total = num(tags[base]), num(tags[base .. "total"])
box(w, atom, function()
box(w, "data", function()
w:u32be(0)
w:u32be(0)
w:u16be(0)
w:u16be(n)
w:u16be(total)
if atom == "trkn" then
w:u16be(0)
end
end)
end)
elseif k == "bpm" then
box(w, "tmpo", function()
box(w, "data", function()
w:u32be(21)
w:u32be(0)
w:u16be(num(v))
end)
end)
elseif k == "compilation" or k == "gapless" then
box(w, if k == "compilation" then "cpil" else "pgap", function()
box(w, "data", function()
w:u32be(21)
w:u32be(0)
w:u8(if num(v) ~= 0 then 1 else 0)
end)
end)
elseif TAG_ATOM[k] then
box(w, TAG_ATOM[k], function()
dataBox(w, 1, v)
end)
else
box(w, "----", function()
box(w, "mean", function()
w:u32be(0)
w:string("com.apple.iTunes")
end)
box(w, "name", function()
w:u32be(0)
w:string(k)
end)
dataBox(w, 1, v)
end)
end
done[k] = true
end
if pictures and #pictures > 0 then
box(w, "covr", function()
for _, p in pictures do
dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data)
end
end)
end
end)
end
-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst
function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "udta", function()
box(w, "meta", function()
w:u32be(0)
box(w, "hdlr", function()
w:u32be(0)
w:u32be(0)
w:string("mdir")
w:string("appl")
w:u32be(0)
w:u32be(0)
w:u8(0)
end)
Meta.writeIlst(w, tags, pictures)
end)
end)
end
return Meta
+519
View File
@@ -0,0 +1,519 @@
--!strict
-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak
-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks
-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample
-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... +
-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Meta = require("@formats/containers/IsoBmff/Meta")
local Mux = {}
export type MuxTrack = {
kind: "audio" | "video" | "subtitle" | "data",
entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ...
timescale: number, -- ticks per second (audio: the sample rate)
samples: { buffer }?, -- one buffer per sample, or
data: buffer?, -- the samples back to back, with
sizes: { number }?, -- their sizes
durations: { number } | number, -- ticks per sample (or one constant)
cts: { number }?, -- composition offsets (video with B-frames)
sync: { [number]: boolean }?, -- sync samples (nil: all)
sampleRate: number?,
channels: number?,
bitsPerSample: number?, -- default 16
width: number?,
height: number?,
config: buffer?, -- the codec configuration, written as the entry's configuration box
configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC)
objectType: number?, -- esds objectTypeIndication (default 0x40, AAC)
bitrate: number?, -- esds average bitrate
boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads)
language: string?, -- ISO 639-2, default "und"
name: string?, -- hdlr name
skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming)
playDuration: number?, -- media ticks to play (edit list)
}
export type MuxSpec = {
brand: string?, -- default "isom"
minor: number?,
compatible: { string }?,
timescale: number?, -- movie timescale, default 1000
tracks: { MuxTrack },
tags: { [string]: string }?,
pictures: { Meta.Picture }?,
chunkDuration: number?, -- seconds of samples per chunk, default 1
}
local DEFAULT_CONFIG_BOX: { [string]: string } = {
mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC",
hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3",
}
local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true }
local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" }
local box = Meta.box
local function lang(s: string?): number
local l = s or "und"
if #l ~= 3 then
l = "und"
end
local v = 0
for i = 1, 3 do
v = v * 32 + bit32.band(string.byte(l, i) - 96, 31)
end
return v
end
local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ())
local inner = Bytes.writer(64)
body(inner)
local n = inner:tell()
w:u8(tag)
-- 4-byte expandable length (the common iTunes / ffmpeg form)
w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127))
w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127))
w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127))
w:u8(bit32.band(n, 127))
w:bytes(inner.buf, 0, n)
end
local function esds(w: Bytes.Writer, t: MuxTrack)
box(w, "esds", function()
w:u32be(0)
descriptor(w, 3, function(d)
d:u16be(0) -- ES_ID
d:u8(0)
descriptor(d, 4, function(c)
c:u8(t.objectType or 0x40)
c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1
c:u24be(0)
c:u32be(t.bitrate or 0)
c:u32be(t.bitrate or 0)
if t.config then
descriptor(c, 5, function(s)
s:bytes(t.config :: buffer)
end)
end
end)
descriptor(d, 6, function(s)
s:u8(2)
end)
end)
end)
end
local function sampleEntry(w: Bytes.Writer, t: MuxTrack)
box(w, t.entry, function()
w:fill(0, 6)
w:u16be(1) -- data reference index
if t.kind == "audio" then
w:u16be(0) -- version
w:u16be(0)
w:u32be(0)
w:u16be(t.channels or 2)
w:u16be(t.bitsPerSample or 16)
w:u16be(0)
w:u16be(0)
local sr = t.sampleRate or t.timescale
w:u32be(if sr < 65536 then sr * 65536 else 0)
elseif t.kind == "video" then
w:fill(0, 16)
w:u16be(t.width or 0)
w:u16be(t.height or 0)
w:u32be(0x00480000)
w:u32be(0x00480000)
w:u32be(0)
w:u16be(1) -- frame count
w:fill(0, 32) -- compressor name
w:u16be(0x18)
w:i16be(-1)
end
local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry]
if t.config and cb then
if cb == "esds" then
esds(w, t)
else
box(w, cb, function()
if FULL_BOX[cb] then
w:u32be(0)
end
w:bytes(t.config :: buffer)
end)
end
end
for _, x in t.boxes or {} do
box(w, x.type, function()
w:bytes(x.data)
end)
end
end)
end
type Chunk = { track: number, first: number, count: number, time: number, offset: number }
-- runs of equal values: { { count, value } }
local function runs(n: number, value: (number) -> number): { { number } }
local out = {}
for i = 1, n do
local v = value(i)
local last = out[#out]
if last and last[2] == v then
last[1] += 1
else
table.insert(out, { 1, v })
end
end
return out
end
type Prepared = {
t: MuxTrack,
n: number,
sizes: { number },
dur: (number) -> number,
total: number, -- media ticks
chunks: { Chunk },
sample: (number) -> (buffer, number), -- buffer, offset
}
local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean)
local mts = spec.timescale or 1000
local function toMovie(p: Prepared, ticks: number): number
return math.floor(ticks * mts / p.t.timescale + 0.5)
end
local movieDur = 0
for _, p in prep do
local play = p.t.playDuration or (p.total - (p.t.skip or 0))
movieDur = math.max(movieDur, toMovie(p, play))
end
box(w, "moov", function()
box(w, "mvhd", function()
w:u32be(0)
w:u32be(0)
w:u32be(0)
w:u32be(mts)
w:u32be(movieDur)
w:u32be(0x00010000)
w:u16be(0x0100)
w:fill(0, 10)
for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
w:u32be(v)
end
w:fill(0, 24)
w:u32be(#prep + 1)
end)
for id, p in prep do
local t = p.t
local play = t.playDuration or (p.total - (t.skip or 0))
box(w, "trak", function()
box(w, "tkhd", function()
w:u32be(3) -- enabled, in movie
w:u32be(0)
w:u32be(0)
w:u32be(id)
w:u32be(0)
w:u32be(toMovie(p, play))
w:fill(0, 8)
w:u16be(0)
w:u16be(0)
w:u16be(if t.kind == "audio" then 0x0100 else 0)
w:u16be(0)
for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
w:u32be(v)
end
w:u32be((t.width or 0) * 65536)
w:u32be((t.height or 0) * 65536)
end)
if t.skip or t.playDuration then
box(w, "edts", function()
box(w, "elst", function()
w:u32be(0)
w:u32be(1)
w:u32be(toMovie(p, play))
w:u32be(t.skip or 0)
w:u32be(0x00010000)
end)
end)
end
box(w, "mdia", function()
box(w, "mdhd", function()
w:u32be(0)
w:u32be(0)
w:u32be(0)
w:u32be(t.timescale)
w:u32be(p.total)
w:u16be(lang(t.language))
w:u16be(0)
end)
box(w, "hdlr", function()
w:u32be(0)
w:u32be(0)
w:string(HANDLER[t.kind] or "meta")
w:fill(0, 12)
w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler"))
end)
box(w, "minf", function()
if t.kind == "audio" then
box(w, "smhd", function()
w:u32be(0)
w:u32be(0)
end)
elseif t.kind == "video" then
box(w, "vmhd", function()
w:u32be(1)
w:fill(0, 8)
end)
else
box(w, "nmhd", function()
w:u32be(0)
end)
end
box(w, "dinf", function()
box(w, "dref", function()
w:u32be(0)
w:u32be(1)
box(w, "url ", function()
w:u32be(1) -- self-contained
end)
end)
end)
box(w, "stbl", function()
box(w, "stsd", function()
w:u32be(0)
w:u32be(1)
sampleEntry(w, t)
end)
local stts = runs(p.n, p.dur)
box(w, "stts", function()
w:u32be(0)
w:u32be(#stts)
for _, r in stts do
w:u32be(r[1])
w:u32be(r[2])
end
end)
local cts = t.cts
if cts then
local cr = runs(p.n, function(i)
return cts[i] or 0
end)
box(w, "ctts", function()
w:u32be(0x01000000) -- version 1: signed offsets
w:u32be(#cr)
for _, r in cr do
w:u32be(r[1])
w:i32be(r[2])
end
end)
end
local sync = t.sync
if sync then
local list = {}
for i = 1, p.n do
if sync[i] then
table.insert(list, i)
end
end
box(w, "stss", function()
w:u32be(0)
w:u32be(#list)
for _, i in list do
w:u32be(i)
end
end)
end
local stsc = runs(#p.chunks, function(i)
return p.chunks[i].count
end)
box(w, "stsc", function()
w:u32be(0)
w:u32be(#stsc)
local c = 1
for _, r in stsc do
w:u32be(c)
w:u32be(r[2])
w:u32be(1)
c += r[1]
end
end)
box(w, "stsz", function()
w:u32be(0)
local fixed = p.sizes[1] or 0
for i = 2, p.n do
if p.sizes[i] ~= fixed then
fixed = -1
break
end
end
if fixed >= 0 and p.n > 0 then
w:u32be(fixed)
w:u32be(p.n)
else
w:u32be(0)
w:u32be(p.n)
for i = 1, p.n do
w:u32be(p.sizes[i])
end
end
end)
box(w, if co64 then "co64" else "stco", function()
w:u32be(0)
w:u32be(#p.chunks)
for _, c in p.chunks do
if co64 then
w:u64be(c.offset)
else
w:u32be(c.offset)
end
end
end)
end)
end)
end)
end)
end
if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then
Meta.writeUdta(w, spec.tags or {}, spec.pictures)
end
end)
end
-- mux(spec) -> buffer | nil, Err
function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?)
if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then
return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }")
end
local prep: { Prepared } = {}
local all: { Chunk } = {}
for k, t in spec.tracks do
if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale")
end
if not HANDLER[t.kind] then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind))
end
local n, sizes, sample
if t.samples then
local list = t.samples
n = #list
sizes = table.create(n, 0)
for i = 1, n do
if type(list[i]) ~= "buffer" then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer")
end
sizes[i] = buffer.len(list[i])
end
sample = function(i: number): (buffer, number)
return list[i], 0
end
elseif t.data and t.sizes then
n = #t.sizes
sizes = t.sizes
local starts = table.create(n, 0)
local o = 0
for i = 1, n do
starts[i] = o
o += sizes[i]
end
if o > buffer.len(t.data) then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data")
end
local data = t.data
sample = function(i: number): (buffer, number)
return data, starts[i]
end
else
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes")
end
local durs = t.durations
local dur
if type(durs) == "number" then
dur = function(_: number): number
return durs
end
elseif type(durs) == "table" then
dur = function(i: number): number
return durs[i] or 0
end
else
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations")
end
local total = 0
local chunks: { Chunk } = {}
local per = (spec.chunkDuration or 1) * t.timescale
local cur: Chunk? = nil
for i = 1, n do
if not cur or total - cur.time >= per then
cur = { track = k, first = i, count = 0, time = total, offset = 0 }
table.insert(chunks, cur :: Chunk)
table.insert(all, cur :: Chunk)
end
(cur :: Chunk).count += 1
total += dur(i)
end
prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample }
end
-- interleave the chunks by time
table.sort(all, function(a: Chunk, b: Chunk): boolean
local ta = a.time / prep[a.track].t.timescale
local tb = b.time / prep[b.track].t.timescale
if ta ~= tb then
return ta < tb
end
if a.track ~= b.track then
return a.track < b.track
end
return a.first < b.first
end)
local mdatSize = 0
for _, c in all do
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
mdatSize += p.sizes[i]
end
end
local co64 = mdatSize > 4294967295 - 2 ^ 24
-- ftyp
local w = Bytes.writer(mdatSize + 4096)
box(w, "ftyp", function()
w:string(spec.brand or "isom")
w:u32be(spec.minor or 0x200)
for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do
w:string(string.sub(c .. " ", 1, 4))
end
end)
-- moov twice: the first pass measures it, the second has the real chunk offsets
local probe = Bytes.writer(4096)
moov(probe, spec, prep, co64)
local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8
local o = w:tell() + probe:tell() + mdatHeader
for _, c in all do
c.offset = o
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
o += p.sizes[i]
end
end
moov(w, spec, prep, co64)
if mdatHeader == 16 then
w:u32be(1)
w:string("mdat")
w:u64be(mdatSize + 16)
else
w:u32be(mdatSize + 8)
w:string("mdat")
end
for _, c in all do
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
local b, off = p.sample(i)
w:bytes(b, off, p.sizes[i])
end
end
return w:finish(), nil
end
return Mux
+188
View File
@@ -0,0 +1,188 @@
--!strict
-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime)
-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4,
-- mov, heif, avif build on it. Written from the specifications; no third-party code.
--
-- local IsoBmff = require("@formats/containers/IsoBmff")
-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables)
-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s)
-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta)
-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs
-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes
-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... })
--
-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit
-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave',
-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls),
-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local Demux = require("@formats/containers/IsoBmff/Demux")
local Meta = require("@formats/containers/IsoBmff/Meta")
local Mux = require("@formats/containers/IsoBmff/Mux")
local IsoBmff = {}
IsoBmff.Box = Box
IsoBmff.Demux = Demux
IsoBmff.Meta = Meta
export type Track = Demux.Track
export type Movie = Demux.Movie
export type Items = Meta.Items
export type Item = Meta.Item
export type MuxSpec = Mux.MuxSpec
export type MuxTrack = Mux.MuxTrack
export type Picture = Meta.Picture
local TOP: { [string]: boolean } = {
ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true,
styp = true, sidx = true, meta = true, uuid = true, PICT = true,
}
-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box,
-- nil when it is not an ISO BMFF file
function IsoBmff.sniff(r: Bytes.Reader): string?
local head = r:peek(12)
if #head < 8 then
return nil
end
local typ = string.sub(head, 5, 8)
if typ == "ftyp" then
return if #head >= 12 then string.sub(head, 9, 12) else ""
end
if TOP[typ] then
local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4)
if size == 1 or size == 0 or size >= 8 then
return ""
end
end
return nil
end
-- parse(r, opts?) -> Movie | nil, Err
function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?)
return Demux.parse(r, opts)
end
-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta)
function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture })
local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst")
return Meta.tags(r.buf, ilst)
end
-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file)
function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?)
local meta = Box.path(movie.boxes, "meta")
if not meta then
return nil, Err.new(Err.CORRUPT, "no top-level meta box")
end
return Meta.items(r.buf, meta)
end
-- itemData(r, items, id) -> buffer | nil, Err
function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?)
return Meta.itemData(r.buf, r.base, r.limit, items, id)
end
-- sample(r, track, i) -> a copy of sample i (1-based)
function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer?
if i < 1 or i > t.sampleCount then
return nil
end
local n = t.sizes[i]
local out = buffer.create(n)
buffer.copy(out, 0, r.buf, t.offsets[i], n)
return out
end
-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts /
-- dts / duration in their track's timescale ticks and a copy of the sample bytes.
function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
local movie, err = Demux.parse(r, opts)
if not movie then
return nil, err
end
local cursor: { [number]: number } = {}
local byId: { [number]: Track } = {}
for _, t in movie.tracks do
cursor[t.id] = 1
byId[t.id] = t
end
local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie }
local function packet(t: Track, i: number): any
local dts = t.dts[i]
local cts = t.cts
return {
track = t.id,
dts = dts,
pts = dts + (if cts then cts[i] or 0 else 0),
duration = t.durations[i],
keyframe = t.sync == nil or (t.sync :: any)[i] == true,
data = IsoBmff.sample(r, t, i),
index = i,
}
end
function dmx.packets(_self: any, trackId: number?): () -> any
return function(): any
if trackId then
local t = byId[trackId]
if not t then
return nil
end
local i = cursor[trackId]
if i > t.sampleCount then
return nil
end
cursor[trackId] = i + 1
return packet(t, i)
end
-- all tracks in file order
local best: Track? = nil
local bestOff = math.huge
for _, t in movie.tracks do
local i = cursor[t.id]
if i <= t.sampleCount and t.offsets[i] < bestOff then
best, bestOff = t, t.offsets[i]
end
end
if not best then
return nil
end
local i = cursor[best.id]
cursor[best.id] = i + 1
return packet(best, i)
end
end
-- seek(seconds): every track to its last sync sample at or before the time
function dmx.seek(_self: any, seconds: number)
for _, t in movie.tracks do
local target = seconds * t.timescale
local lo, hi = 1, t.sampleCount
local found = 1
while lo <= hi do
local mid = (lo + hi) // 2
if t.dts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if t.sync then
while found > 1 and not (t.sync :: any)[found] do
found -= 1
end
end
cursor[t.id] = found
end
end
return dmx, nil
end
-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux)
function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?)
return Mux.mux(spec)
end
return IsoBmff
+241
View File
@@ -0,0 +1,241 @@
-- containers/IsoBmff tests: ffmpeg / MP4Box files (H.264 + AAC with B-frames, fast start, QuickTime MJPEG + PCM, HEVC,
-- fragmented by ffmpeg and MP4Box, stz2 + co64, ALAC) demuxed packet for packet against ffprobe (-ignore_editlist);
-- track facts and codec configurations; iTunes tags and cover art; AVIF items (libavif, plain and with alpha); the
-- muxer round-trips through the demuxer (sizes, times, cts, sync, tags, 64-bit sizes); a sub-range reader; the fuzz
-- no-throw pass. Fixtures: tools/fixtures/isobmff.py.
local T = require("@tests/T")
local IsoBmff = require("@formats/containers/IsoBmff")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/isobmff")
local t = T.suite("isobmff")
local CODEC = { h264 = "h264", aac = "aac", mjpeg = "mjpeg", pcm_s16be = "pcm", hevc = "hevc", alac = "alac" }
local function reader(s: string, pad: number?): Bytes.Reader
if pad then
local b = buffer.create(#s + pad * 2)
buffer.writestring(b, pad, s)
return Bytes.reader(b, pad, #s)
end
return Bytes.reader(buffer.fromstring(s))
end
-- every fixture against ffprobe
for _, c in Fx.cases do
for _, pad in { 0, 5 } do
local r = reader(c.data, if pad > 0 then pad else nil)
local label = c.name .. (if pad > 0 then " (sub-range)" else "")
t:check(IsoBmff.sniff(r) ~= nil, label .. ": sniff")
local dmx, err = IsoBmff.demux(r)
t:check(dmx, label .. ": " .. tostring(err))
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
for i, s in c.streams do
local tr = dmx.tracks[i]
t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind")
t:eq(tr.codec, CODEC[s.codec] or s.codec, label .. ": track " .. i .. " codec")
t:eq(tr.timescale, s.timescale, label .. ": timescale")
if s.width then
t:check(tr.width == s.width and tr.height == s.height, label .. ": video size")
end
if s.sampleRate then
t:check(tr.sampleRate == s.sampleRate and tr.channels == s.channels, label .. ": audio format")
end
if s.extradata > 0 and s.codec ~= "alac" then
t:eq(if tr.config then buffer.len(tr.config) else 0, s.extradata, label .. ": codec config size")
end
end
-- packets in file order
local n, bad = 0, nil
local base = r.base
for p in dmx:packets() do
n += 1
local want = c.packets[n]
if not want then
bad = bad or ("extra packet " .. n)
break
end
local tr = dmx.tracks[want.stream]
if p.track ~= tr.id then
bad = bad or ("packet " .. n .. " track")
end
local off = tr.offsets[p.index]
if off - base ~= want.pos or buffer.len(p.data) ~= want.size or p.dts ~= want.dts or p.pts ~= want.pts or p.keyframe ~= want.key then
bad = bad or string.format("packet %d: pos %d/%d size %d/%d dts %d/%d pts %d/%d key %s/%s", n, off - base, want.pos, buffer.len(p.data), want.size, p.dts, want.dts, p.pts, want.pts, tostring(p.keyframe), tostring(want.key))
end
end
t:check(bad == nil, label .. ": " .. tostring(bad))
t:eq(n, #c.packets, label .. ": packet count")
if pad == 0 then
t:note("%s: %d tracks, %d packets match ffprobe", c.name, #c.streams, n)
end
end
end
-- per-track packets, seek
do
local c = Fx.cases[1]
local dmx = IsoBmff.demux(reader(c.data))
local v = dmx.tracks[1]
local count = 0
for p in dmx:packets(v.id) do
count += 1
t:eq(p.track, v.id, "per-track packets")
end
t:eq(count, v.sampleCount, "per-track packet count")
dmx:seek(0.75)
local p = dmx:packets(v.id)()
t:check(p and p.keyframe and p.dts / v.timescale <= 0.75, "seek lands on a keyframe before the time")
t:check(v.skip >= 0 and v.edits ~= nil, "edit list parsed")
end
-- tags and cover
do
local r = reader(Fx.tagged.data)
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
local tags, pics = IsoBmff.tags(r, movie)
for k, v in Fx.tagged.tags do
t:eq(tags[k], v, "tag " .. k)
end
t:check(tags.encoder ~= nil, "encoder tag")
t:eq(#pics, 1, "one cover")
t:eq(pics[1] and buffer.len(pics[1].data), Fx.tagged.cover, "cover bytes")
t:eq(pics[1] and pics[1].mime, "image/png", "cover mime")
end
-- AVIF items
for _, c in Fx.avif do
local r = reader(c.data)
t:check(IsoBmff.sniff(r) == "avif", c.name .. ": brand")
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
t:check(movie and #movie.tracks == 0, c.name .. ": no tracks")
local items, err = IsoBmff.items(r, movie)
t:check(items, c.name .. ": items: " .. tostring(err))
local prim = items.items[items.primary]
t:check(prim and prim.type == "av01", c.name .. ": primary item is av01")
local ispe, av1C
for _, p in prim.properties do
if p.type == "ispe" then
ispe = p
elseif p.type == "av1C" then
av1C = p
end
end
t:check(ispe and ispe.width == c.width and ispe.height == c.height, c.name .. ": ispe")
t:check(av1C and av1C.config and buffer.readu8(av1C.config, 0) == 0x81, c.name .. ": av1C marker / version")
local data = IsoBmff.itemData(r, items, items.primary :: number)
t:check(data and buffer.len(data) > 10, c.name .. ": item data")
-- an AV1 OBU stream: the first OBU is a sequence header (type 1) or a temporal delimiter (2)
local obu = data and bit32.band(bit32.rshift(buffer.readu8(data, 0), 3), 15)
t:check(obu == 1 or obu == 2, c.name .. ": AV1 OBU stream")
local auxl = nil
for _, id in items.order do
local it = items.items[id]
if it.refs.auxl then
auxl = it
end
end
t:eq(auxl ~= nil, c.alpha, c.name .. ": alpha auxiliary item")
end
-- the muxer: round trip through the demuxer
do
local rand = T.rng(5)
local function sample(n: number): buffer
local b = buffer.create(n)
for i = 0, n - 1 do
buffer.writeu8(b, i, rand(256))
end
return b
end
local aud, vid = {}, {}
for i = 1, 90 do
aud[i] = sample(50 + rand(200))
end
for i = 1, 30 do
vid[i] = sample(100 + rand(900))
end
local cts = {}
local sync = {}
for i = 1, 30 do
cts[i] = (i % 3) * 512
sync[i] = i % 10 == 1
end
local cfg = buffer.fromstring("\x12\x10")
local file, err = IsoBmff.mux({
brand = "mp42",
compatible = { "mp42", "isom" },
tracks = {
{ kind = "video", entry = "avc1", timescale = 15360, samples = vid, durations = 512, cts = cts, sync = sync, width = 64, height = 48, config = buffer.fromstring("\1\100\0\10\255") },
{ kind = "audio", entry = "mp4a", timescale = 44100, samples = aud, durations = 1024, sampleRate = 44100, channels = 2, config = cfg, skip = 1024, playDuration = 44100 * 2 },
},
tags = { title = "Mux Test", artist = "Me", track = "2", tracktotal = "9", custom = "free form", bpm = "120" },
pictures = { { mime = "image/jpeg", data = buffer.fromstring("\255\216\255\217") } },
chunkDuration = 0.25,
})
t:check(file, "mux: " .. tostring(err))
local r = Bytes.reader(file :: buffer)
local dmx = IsoBmff.demux(r)
t:check(dmx and #dmx.tracks == 2, "mux: demux our file")
local v, a = dmx.tracks[1], dmx.tracks[2]
t:check(v.codec == "h264" and v.width == 64 and v.height == 48 and v.config and buffer.len(v.config) == 5, "mux: video track")
t:check(a.codec == "aac" and a.sampleRate == 44100 and a.channels == 2 and a.config and buffer.tostring(a.config) == "\x12\x10", "mux: audio track + esds")
t:check(a.skip == 1024 and a.playDuration == 88200, "mux: edit list")
local ok = true
for i = 1, 30 do
local s = IsoBmff.sample(r, v, i) :: buffer
ok = ok and buffer.tostring(s) == buffer.tostring(vid[i]) and v.dts[i] == (i - 1) * 512 and (v.cts :: any)[i] == cts[i] and ((v.sync :: any)[i] == true) == sync[i]
end
t:check(ok, "mux: video samples, times, cts, sync")
ok = true
for i = 1, 90 do
ok = ok and buffer.tostring(IsoBmff.sample(r, a, i) :: buffer) == buffer.tostring(aud[i]) and a.durations[i] == 1024
end
t:check(ok, "mux: audio samples")
-- interleaved: offsets alternate between the tracks
t:check(v.offsets[30] > a.offsets[1] and a.offsets[90] > v.offsets[1], "mux: interleaved chunks")
local tags, pics = IsoBmff.tags(r, dmx.movie)
t:check(tags.title == "Mux Test" and tags.artist == "Me" and tags.track == "2" and tags.tracktotal == "9" and tags.custom == "free form" and tags.bpm == "120", "mux: tags round trip")
t:check(#pics == 1 and buffer.len(pics[1].data) == 4, "mux: cover round trip")
t:note("mux: %d bytes, crc %08x", buffer.len(file :: buffer), Crc32.of(file :: buffer))
-- data + sizes form, bad specs
local f2 = IsoBmff.mux({ tracks = { { kind = "audio", entry = "alac", timescale = 8000, data = buffer.create(30), sizes = { 10, 10, 10 }, durations = { 4096, 4096, 100 }, config = buffer.create(24) } } })
local d2 = IsoBmff.demux(Bytes.reader(f2 :: buffer))
t:check(d2 and d2.tracks[1].codec == "alac" and d2.tracks[1].sampleCount == 3 and d2.tracks[1].durations[3] == 100 and buffer.len(d2.tracks[1].config) == 24, "mux: data + sizes, alac cookie")
for _, bad in { {}, { tracks = {} }, { tracks = { { kind = "audio", entry = "toolong", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "x", entry = "abcd", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "audio", entry = "abcd", timescale = 1 } } } } do
local f, e = IsoBmff.mux(bad :: any)
t:check(f == nil and e and e.code == "ARG", "mux: bad spec -> ARG")
end
end
-- fuzz
do
local samples = {}
for _, c in Fx.cases do
table.insert(samples, string.sub(c.data, 1, 6000))
table.insert(samples, c.data)
end
for _, c in Fx.avif do
table.insert(samples, c.data)
end
t:fuzz("demux", function(b: buffer)
local r = Bytes.reader(b)
local dmx = IsoBmff.demux(r)
if dmx then
for p in dmx:packets() do
local _ = p
end
IsoBmff.tags(r, dmx.movie)
local items = IsoBmff.items(r, dmx.movie)
if items then
for _, id in items.order do
IsoBmff.itemData(r, items, id)
end
end
end
return dmx
end, samples, { mutations = 12 })
end
t:done()
+89
View File
@@ -0,0 +1,89 @@
# containers/IsoBmff fixtures (tools/fixtures.py): small files from ffmpeg / MP4Box / avifenc (nix) with ffprobe's
# packet lists as the reference.
# tests/gen/isobmff.luau { cases = { { name, data, streams = { { codec, kind, timescale, width?, height?,
# sampleRate?, channels?, extradata }, ... }, packets = { { stream, pos, size, dts, pts, key },
# ... } } }, tagged = { data, tags, cover }, avif = { { name, data, width, height, alpha } } }
import json, os, shutil, subprocess, tempfile
PKGS = ["ffmpeg", "gpac", "libavif"]
def sh(ctx, script, cwd):
return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, script)])
def probe(ctx, path, cwd):
out = sh(ctx, "ffprobe -v error -ignore_editlist 1 -show_streams -show_packets -of json '%s'" % path, cwd)
j = json.loads(out)
streams = []
for s in j["streams"]:
kind = s["codec_type"]
if kind == "video" and s.get("disposition", {}).get("attached_pic"):
continue
tb = s["time_base"].split("/")
e = {"codec": s["codec_name"], "kind": kind, "timescale": int(tb[1]), "index": s["index"],
"extradata": int(s.get("extradata_size", 0))}
if kind == "video":
e["width"], e["height"] = s["width"], s["height"]
if kind == "audio":
e["sampleRate"], e["channels"] = int(s["sample_rate"]), s["channels"]
streams.append(e)
index = {s["index"]: i + 1 for i, s in enumerate(streams)}
packets = []
for p in j["packets"]:
if p["stream_index"] not in index:
continue
packets.append({"stream": index[p["stream_index"]], "pos": int(p["pos"]), "size": int(p["size"]),
"dts": int(p["dts"]), "pts": int(p["pts"]), "key": "K" in p["flags"]})
for s in streams:
del s["index"]
return streams, packets
def generate(ctx):
d = tempfile.mkdtemp(prefix="isobmff-fx-")
try:
src_v = "-f lavfi -i testsrc=size=64x48:rate=10 -t 1.2"
src_a = "-f lavfi -i sine=frequency=440:sample_rate=44100 -t 1.0"
steps = [
("h264_aac.mp4", "ffmpeg -v error %s %s -c:v libx264 -bf 2 -g 5 -pix_fmt yuv420p -c:a aac -b:a 64k -ac 2 h264_aac.mp4" % (src_v, src_a)),
("faststart.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags +faststart faststart.mp4"),
("mjpeg_pcm.mov", "ffmpeg -v error %s %s -c:v mjpeg -c:a pcm_s16be mjpeg_pcm.mov" % (src_v, src_a)),
("hevc.mp4", "ffmpeg -v error %s -c:v libx265 -x265-params log-level=none -tag:v hvc1 hevc.mp4" % src_v),
("frag.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags frag_keyframe+empty_moov+default_base_moof frag.mp4"),
("mp4box_frag.mp4", "MP4Box -quiet -frag 300 -out mp4box_frag.mp4 h264_aac.mp4 >/dev/null 2>&1"),
("stz2_co64.mp4", "MP4Box -quiet -add h264_aac.mp4#video -add h264_aac.mp4#audio:stz2 -co64 -new stz2_co64.mp4 >/dev/null 2>&1"),
("alac.m4a", "ffmpeg -v error %s -c:a alac alac.m4a" % src_a),
]
cases = []
for name, cmd in steps:
sh(ctx, cmd, d)
streams, packets = probe(ctx, name, d)
with open(os.path.join(d, name), "rb") as f:
data = f.read()
cases.append({"name": name, "data": data, "streams": streams, "packets": packets})
# tags + cover
sh(ctx, "ffmpeg -v error -f lavfi -i color=red:size=8x8 -frames:v 1 -update 1 cover.png", d)
tags = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024",
"genre": "Electronic", "comment": "a comment", "composer": "Composer X", "album_artist": "AA"}
meta = " ".join("-metadata %s='%s'" % (k, v) for k, v in tags.items())
sh(ctx, "ffmpeg -v error %s -i cover.png -map 0 -map 1 -c:a aac -b:a 48k -c:v png -disposition:v attached_pic -t 1 %s -metadata track=3/12 -metadata disc=1/2 tagged.m4a" % (src_a, meta), d)
with open(os.path.join(d, "tagged.m4a"), "rb") as f:
tagged = f.read()
with open(os.path.join(d, "cover.png"), "rb") as f:
cover = f.read()
want = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024",
"genre": "Electronic", "comment": "a comment", "composer": "Composer X", "albumartist": "AA",
"track": "3", "tracktotal": "12", "disc": "1", "disctotal": "2"}
# AVIF stills (libavif): plain and with alpha
avif = []
sh(ctx, "ffmpeg -v error -f lavfi -i testsrc=size=40x24 -frames:v 1 still.png && "
"ffmpeg -v error -f lavfi -i 'testsrc=size=40x24,format=rgba,geq=r=r(X\\,Y):a=X*6' -frames:v 1 alpha.png", d)
for name, png, alpha in (("still.avif", "still.png", False), ("alpha.avif", "alpha.png", True)):
sh(ctx, "avifenc -q 60 -s 10 %s %s >/dev/null" % (png, name), d)
with open(os.path.join(d, name), "rb") as f:
avif.append({"name": name, "data": f.read(), "width": 40, "height": 24, "alpha": alpha})
ctx.emit("isobmff", {"cases": cases, "tagged": {"data": tagged, "tags": want, "cover": len(cover)},
"avif": avif})
finally:
shutil.rmtree(d, ignore_errors=True)