--!strict -- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams -- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected -- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by -- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Aac = require("@formats/codecs/Aac") -- ------------------------------------------------------------------------------------------------ contract local AacFormat = { name = "aac", category = "audio", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, } -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22) } -- ------------------------------------------------------------------------------------------------ constants local readu8 = buffer.readu8 -- the size of an ID3v2 tag at p (0 if none) local function id3Size(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 end local s = 0 for i = 6, 9 do s = s * 128 + bit32.band(readu8(b, p + i), 127) end local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0 return 10 + s + footer end -- a few ID3v2.3 / 2.4 text frames -> tags local ID3_TAGS: { [string]: string } = { TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", COMM = "comment", TCOM = "composer", TPE2 = "albumartist", } local function id3Tags(b: buffer, p: number, size: number): Types.Tags local tags: Types.Tags = {} local ver = readu8(b, p + 3) if ver < 3 then return tags end local q, stop = p + 10, p + size while q + 10 <= stop do local id = buffer.readstring(b, q, 4) if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then break end local n = 0 for i = 4, 7 do n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i) end if n < 1 or q + 10 + n > stop then break end local key = ID3_TAGS[id] local enc = readu8(b, q + 10) if key and (enc == 0 or enc == 3) then local s = buffer.readstring(b, q + 11, n - 1) if id == "COMM" and #s > 3 then s = string.sub(s, 4) local z = string.find(s, "\0", 1, true) if z then s = string.sub(s, z + 1) end end s = (string.gsub(s, "%z+$", "")) tags[key] = s end q += 10 + n end return tags end -- ------------------------------------------------------------------------------------------------ sniff function AacFormat.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit p += id3Size(b, p, limit) local h = Aac.adts(b, p, limit) if not h then return 0 end -- a second header right after the first makes it certain local h2 = Aac.adts(b, p + h.frameSize, limit) if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then return 0.9 end return if p + h.frameSize >= limit then 0.7 else 0.4 end -- ------------------------------------------------------------------------------------------------ decode -- the frame index: offsets of every ADTS frame (resyncing over garbage) local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base + id3Size(b, r.base, limit) local offs, sizes = {}, {} local first: Aac.Adts? = nil while p + 7 <= limit do local h = Aac.adts(b, p, limit) if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then h = nil -- a false sync inside the data end if not h then p += 1 continue end if p + h.frameSize > limit then break -- a truncated last frame end if not first then first = h end if h.blocks ~= 1 then return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) end table.insert(offs, p + h.headerSize) table.insert(sizes, h.frameSize - h.headerSize) if #offs > maxFrames then return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") end p += h.frameSize end return offs, sizes, first, nil end function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) if ierr then return nil, ierr end if not first then return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) end local h = first :: Aac.Adts if h.objectType ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") end if h.channelConfig == 0 then return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") end local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) if not dec then return nil, derr end local d = dec :: Aac.Decoder local sr = d.sampleRate local nframes = #offs local total = nframes * 1024 local bytes = 0 for _, s in sizes do bytes += s end local id3 = id3Size(r.buf, r.base, r.limit) local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {} local buf = r.buf local nextFrame = 1 local pendPos, pendN = 0, 0 local drop = 0 local pos = 0 local failed: Err.Err? = nil local out: any = { sampleRate = sr, channels = channels, frames = total, duration = total / sr, bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, tags = tags, codec = "aac", error = nil, } local function fill(): boolean while true do if nextFrame > nframes then return false end local i = nextFrame nextFrame += 1 local n, e = d:decode(buf, offs[i], sizes[i]) if not n then failed = e out.error = e return false end if drop >= n then drop -= n else pendPos, pendN = drop, n drop = 0 return true end end end function out.read(_self: any, n: number, ob: buffer?): (buffer, number) local want = math.max(0, math.floor(n)) local need = want * channels * 4 local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need) local got = 0 local writef32 = buffer.writef32 while got < want do if pendPos >= pendN then if failed or not fill() then break end end local take = math.min(want - got, pendN - pendPos) local src = d.pcm local q = got * channels * 4 local s = pendPos * channels for k = 1, take * channels do writef32(res, q, src[s + k]) q += 4 end pendPos += take got += take end pos += got return res, got end function out.seek(_self: any, seconds: number) local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total) local f = target // 1024 -- frame holding the target (0-based) local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap d:reset() nextFrame = start + 1 drop = target - start * 1024 pendPos, pendN = 0, 0 failed = nil pos = target end function out.position(_self: any): number return pos / sr end if nframes > 0 and not fill() and failed then return nil, failed end return out, nil end function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = AacFormat.open(r, opts) if not dec then return nil, err end local d: any = dec local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) local done = 0 while done < d.frames do local b, n = d:read(math.min(65536, d.frames - done)) if n == 0 then break end buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) done += n end if d.error then return nil, d.error end audio.tags = d.tags audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate } return audio, nil end return AacFormat