--!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 and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info) 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