--!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