--!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 QtPalette = require("@formats/containers/IsoBmff/QtPalette") local readstring = buffer.readstring local function readu16be(b: buffer, o: number): number return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) end 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, ...) bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...) palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF) 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 -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ) t.bitsPerPixel = depth t.palette = pal if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) end 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: { Edit } = {} for _ = 1, n do local dur: number, mt: number if v == 1 then dur, mt = r:u64be(), r:i64be() :: number else dur, mt = r:u32be(), r:i32be() :: number 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: { number }, per: { number }, desc: { number } = {}, {}, {} 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: Options = 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