--!strict --!optimize 2 -- 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("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Box = require("@rosetta/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 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 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 = {}, } :: Item 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 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 -- 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 -- freeform (----) names: tags keys are lower case; these keep their usual spelling when written back local FREEFORM: { [string]: string } = { itunsmpb = "iTunSMPB", itunnorm = "iTunNORM", itunes_cddb_ids = "iTunes_CDDB_IDs" } -- 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 } 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 = if freeName then string.lower(freeName) else TAG[typ] or string.lower(typ) if typ == "\169gen" or not tags[key] then tags[key] = s end end end end return tags, pics end 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 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(FREEFORM[k] or 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 :: { Picture } 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 -- 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