From f66594908c04d7790a877d1bf2b57a5190bfb2de Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:03:04 -0500 Subject: [PATCH] ws-m4a: codecs/Aac (AAC-LC decoder: ASC / PCE / ADTS, all tools, SBR/PS extension hook), codecs/Alac (decoder + encoder), audio/m4a (AAC + ALAC read, ALAC write, tags, gapless, seek), audio/aac (ADTS), audio/caf (lpcm/alac/aac/ulaw/alaw read, lpcm/alac write); fixtures checked by ffmpeg / fdkaac / MP4Box Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 5 + licenses/NOTICE.md | 2 + src/Formats/Registry.luau | 36 ++ src/Formats/audio/aac/init.luau | 277 +++++++++ src/Formats/audio/caf/init.luau | 746 +++++++++++++++++++++++ src/Formats/audio/m4a/init.luau | 439 ++++++++++++++ src/Formats/codecs/Aac/Decode.luau | 903 ++++++++++++++++++++++++++++ src/Formats/codecs/Aac/Tables.luau | 335 +++++++++++ src/Formats/codecs/Aac/init.luau | 336 +++++++++++ src/Formats/codecs/Alac/Decode.luau | 427 +++++++++++++ src/Formats/codecs/Alac/Encode.luau | 427 +++++++++++++ src/Formats/codecs/Alac/init.luau | 251 ++++++++ tests/audio/_encode_cases.luau | 12 + tests/audio/_signal.luau | 42 ++ tests/audio/aac.luau | 117 ++++ tests/audio/caf.luau | 177 ++++++ tests/audio/m4a.luau | 218 +++++++ tests/codecs/aac.luau | 182 ++++++ tests/codecs/alac.luau | 181 ++++++ tools/fixtures/_m4a_encode.luau | 31 + tools/fixtures/_m4a_signal.py | 41 ++ tools/fixtures/m4a.py | 195 ++++++ 22 files changed, 5380 insertions(+) create mode 100644 src/Formats/audio/aac/init.luau create mode 100644 src/Formats/audio/caf/init.luau create mode 100644 src/Formats/audio/m4a/init.luau create mode 100644 src/Formats/codecs/Aac/Decode.luau create mode 100644 src/Formats/codecs/Aac/Tables.luau create mode 100644 src/Formats/codecs/Aac/init.luau create mode 100644 src/Formats/codecs/Alac/Decode.luau create mode 100644 src/Formats/codecs/Alac/Encode.luau create mode 100644 src/Formats/codecs/Alac/init.luau create mode 100644 tests/audio/_encode_cases.luau create mode 100644 tests/audio/_signal.luau create mode 100644 tests/audio/aac.luau create mode 100644 tests/audio/caf.luau create mode 100644 tests/audio/m4a.luau create mode 100644 tests/codecs/aac.luau create mode 100644 tests/codecs/alac.luau create mode 100644 tools/fixtures/_m4a_encode.luau create mode 100644 tools/fixtures/_m4a_signal.py create mode 100644 tools/fixtures/m4a.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 4a451fa..4e93b14 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,8 +6,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | +| audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | +| audio | m4a | .m4a .m4b .m4r .aac.mp4 | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..7e67528 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -4,6 +4,8 @@ |---|---|---| | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | +| `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data | +| `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..7c810a6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,42 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "aac", + category = "audio", + path = "audio/aac", + 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 }, + load = function() + return require("@formats/audio/aac") + end, + }, + { + name = "caf", + category = "audio", + path = "audio/caf", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, + load = function() + return require("@formats/audio/caf") + end, + }, + { + name = "m4a", + category = "audio", + path = "audio/m4a", + extensions = { "m4a", "m4b", "m4r", "aac.mp4" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, + load = function() + return require("@formats/audio/m4a") + end, + }, } return list diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau new file mode 100644 index 0000000..6c3e45d --- /dev/null +++ b/src/Formats/audio/aac/init.luau @@ -0,0 +1,277 @@ +--!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 = 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 diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau new file mode 100644 index 0000000..f602434 --- /dev/null +++ b/src/Formats/audio/caf/init.luau @@ -0,0 +1,746 @@ +--!strict +-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear +-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac, +-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown +-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / +-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Aac = require("@formats/codecs/Aac") +local Alac = require("@formats/codecs/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local Caf = { + name = "caf", + category = "audio", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPackets: number?, -- packet table limit (default 2^24) +} +export type EncodeOptions = { + codec: ("pcm" | "alac")?, -- default "alac" + bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24 + tags: Types.Tags?, -- default: the audio's tags +} + +-- ------------------------------------------------------------------------------------------------ constants +local INFO_TAGS: { [string]: string } = { + title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", + comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", + ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", +} +local TAG_INFO: { [string]: string } = {} +for k, v in INFO_TAGS do + TAG_INFO[v] = k +end + +-- mu-law / A-law -> linear 16-bit +local ULAW, ALAW = table.create(256, 0), table.create(256, 0) +for i = 0, 255 do + local u = 255 - i + local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) + ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132 + local a = bit32.bxor(i, 0x55) + local seg = bit32.band(bit32.rshift(a, 4), 7) + local m = bit32.band(a, 15) * 16 + 8 + if seg > 0 then + m = (m + 256) * 2 ^ (seg - 1) + end + ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Caf.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } +type Parsed = { + desc: Desc, + dataStart: number, -- absolute offset of the audio data + dataEnd: number, + cookie: buffer?, + packets: { number }?, -- sizes (pakt) + packetFrames: { number }?, + priming: number, + remainder: number, + validFrames: number?, + tags: Types.Tags, +} + +-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo +local function esdsConfig(b: buffer): buffer? + local r = Bytes.reader(b) + if r:peekU8() ~= 3 then + r:skip(4) -- the esds atom's version / flags + end + local function len(): 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 + while not r:eof() and not r.err do + local tag = r:u8() + local n = len() + if tag == 3 then + r:skip(2) + local f = r:u8() + if bit32.band(f, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(f, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(f, 0x20) ~= 0 then + r:skip(2) + end + elseif tag == 4 then + r:skip(13) + elseif tag == 5 then + if n > 0 and r:need(n) then + return r:bytes(n) + end + return nil + else + r:skip(n) + end + end + return nil +end + +local function vlq(r: Bytes.Reader): number + local v = 0 + for _ = 1, 8 do + local c = r:u8() + v = v * 128 + bit32.band(c, 127) + if c < 128 then + return v + end + end + r:fail(Err.CORRUPT, "bad packet table entry") + return 0 +end + +local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) + if Caf.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) + end + r:seek(8) + local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } + local haveData = false + while r:remaining() >= 12 do + local typ = r:string(4) + local size = r:i64be() + local start = r.pos + if size == -1 and typ == "data" then + size = r.limit - start + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12) + end + local stop = start + size + if stop > r.limit then + if typ ~= "data" then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12) + end + stop = r.limit -- a truncated data chunk: play what is there + end + local c = Bytes.reader(r.buf, start, stop - start) + if typ == "desc" then + p.desc = { + rate = c:f64be(), + format = c:string(4), + flags = c:u32be(), + bytesPerPacket = c:u32be(), + framesPerPacket = c:u32be(), + channels = c:u32be(), + bits = c:u32be(), + } + if c.err then + return nil, c.err + end + elseif typ == "data" then + p.dataStart = start + 4 -- edit count + p.dataEnd = stop + haveData = true + elseif typ == "kuki" then + p.cookie = c:bytes(stop - start) + elseif typ == "pakt" then + local n = c:i64be() + p.validFrames = c:i64be() + p.priming = c:i32be() + p.remainder = c:i32be() + if c.err then + return nil, c.err + end + if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then + return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) + end + local d = p.desc + if not d then + return nil, Err.new(Err.CORRUPT, "pakt before desc", start) + end + local sizes, frames = table.create(n, 0), nil + if d.framesPerPacket == 0 then + frames = table.create(n, 0) + end + for i = 1, n do + sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket + if frames then + frames[i] = vlq(c) + end + end + if c.err then + return nil, c.err + end + p.packets, p.packetFrames = sizes, frames + elseif typ == "info" then + local n = c:u32be() + for _ = 1, math.min(n, 1000) do + local k = c:cstring() + local v = c:cstring() + if c.err then + break + end + p.tags[INFO_TAGS[string.lower(k)] or k] = v + end + end + r.pos = stop + if typ == "data" and stop >= r.limit then + break + end + end + if not p.desc then + return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) + end + if not haveData then + return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) + end + local d = p.desc + if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then + return nil, Err.new(Err.CORRUPT, "bad stream description") + end + return p, nil +end + +-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err +type Source = { + channels: number, + rate: number, + packetCount: number, + packetFrames: (number) -> number, + decode: (number) -> (number?, Err.Err?), + pcm: { number }, + reset: () -> (), + codec: string, + bits: number?, +} + +local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) + local d = p.desc + local b = r.buf + local ch = d.channels + local fmt = d.format + if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then + local bits = if fmt == "lpcm" then d.bits else 8 + local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 + local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 + local bpf = d.bytesPerPacket + if bpf == 0 then + bpf = ch * (bits // 8) + end + if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then + return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") + end + local bps = bits // 8 + if bpf < ch * bps then + return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") + end + local total = (p.dataEnd - p.dataStart) // bpf + local per = 1024 + local pcm = table.create(per * ch, 0) + local scale = 1 / 2 ^ (bits - 1) + local readu8, readi8 = buffer.readu8, buffer.readi8 + local src: Source = { + channels = ch, + rate = d.rate, + packetCount = (total + per - 1) // per, + packetFrames = function(i: number): number + return math.min(per, total - (i - 1) * per) + end, + pcm = pcm, + reset = function() end, + codec = if fmt == "lpcm" then "pcm" else fmt, + bits = bits, + decode = function(i: number): (number?, Err.Err?) + local f0 = (i - 1) * per + local n = math.min(per, total - f0) + local k = 1 + for f = f0, f0 + n - 1 do + local q = p.dataStart + f * bpf + for _ = 1, ch do + local v + if fmt == "ulaw" then + v = ULAW[readu8(b, q) + 1] / 32768 + elseif fmt == "alaw" then + v = ALAW[readu8(b, q) + 1] / 32768 + elseif float then + if bits == 32 then + v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be() + else + v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be() + end + elseif bits == 8 then + v = readi8(b, q) * scale + elseif bits == 16 then + v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1) + v *= scale + elseif bits == 24 then + if little then + v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) + else + v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + end + v *= scale + else + if little then + v = buffer.readi32(b, q) + else + v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) + end + v *= scale + end + pcm[k] = v + k += 1 + q += bps + end + end + return n, nil + end, + } + return src, nil + end + -- packetised codecs + local sizes = p.packets + if not sizes then + if d.bytesPerPacket > 0 then + local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket + sizes = table.create(n, d.bytesPerPacket) + else + return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") + end + end + local offsets = table.create(#sizes, 0) + local o = p.dataStart + for i, s in sizes :: { number } do + offsets[i] = o + o += s + if o > p.dataEnd then + -- a truncated file: keep the whole packets + offsets[i] = nil :: any + sizes = table.move(sizes :: { number }, 1, i - 1, 1, {}) + break + end + end + local count = #(sizes :: { number }) + local fpp = d.framesPerPacket + local pf = p.packetFrames + local function framesOf(i: number): number + return if pf then pf[i] else fpp + end + local cookie = p.cookie + if fmt == "alac" then + if not cookie then + return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") + end + local cfg, err = Alac.config(cookie :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + return { + channels = cfg.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = pcm, + reset = function() end, + codec = "alac", + bits = cfg.bitDepth, + decode = function(i: number): (number?, Err.Err?) + local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i]) + if not n then + return nil, e + end + local src = dec.pcm + for k = 1, n * cfg.channels do + pcm[k] = src[k] * scale + end + return n, nil + end, + }, nil + elseif fmt == "aac " then + local asc = if cookie then esdsConfig(cookie :: buffer) else nil + if not asc then + return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") + end + local dec, err = Aac.decoder(asc :: buffer) + if not dec then + return nil, err + end + local ad = dec :: Aac.Decoder + return { + channels = ad.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = ad.pcm, + reset = function() + ad:reset() + end, + codec = "aac", + decode = function(i: number): (number?, Err.Err?) + return ad:decode(b, offsets[i], (sizes :: { number })[i]) + end, + }, nil + end + return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") +end + +function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local p, err = parse(r, opts or {}) + if not p then + return nil, err + end + local s, serr = source(r, p :: Parsed) + if not s then + return nil, serr + end + local src = s :: Source + local ch, rate = src.channels, src.rate + local starts = table.create(src.packetCount + 1, 0) + local total = 0 + for i = 1, src.packetCount do + starts[i] = total + total += src.packetFrames(i) + end + starts[src.packetCount + 1] = total + local skip = math.max(0, p.priming) + local stopAt = total + if p.validFrames and p.validFrames >= 0 then + stopAt = math.min(total, skip + p.validFrames) + elseif p.remainder > 0 then + stopAt = math.max(skip, total - p.remainder) + end + local frames = math.max(0, stopAt - skip) + local nextPacket = 1 + local decoded = 0 + local pendPos, pendN = 0, 0 + local dropUntil = skip + local pos = 0 + local failed: Err.Err? = nil + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0, + tags = p.tags, + codec = src.codec, + bitsPerSample = src.bits, + error = nil, + } + local function fill(): boolean + while true do + if nextPacket > src.packetCount or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local start = starts[i] + local n, e = src.decode(i) + if not n then + failed = e + dec.error = e + return false + end + decoded = start + n + local a = math.max(start, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos, pendN = a - start, b - start + return true + end + end + end + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * ch * 4 + local ob = if out and buffer.len(out) >= need then out 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 q = got * ch * 4 + local sidx = pendPos * ch + local pcm = src.pcm + for k = 1, take * ch do + writef32(ob, q, pcm[sidx + k]) + q += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + function dec.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip + local lo, hi, found = 1, src.packetCount, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if starts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if src.codec == "aac" then + found = math.max(1, found - 1) + end + src.reset() + nextPacket = found + decoded = starts[found] + dropUntil = target + pendPos, pendN = 0, 0 + failed = nil + pos = target - skip + end + function dec.position(_self: any): number + return pos / rate + end + if src.packetCount > 0 and frames > 0 and not fill() and failed then + return nil, failed + end + return dec, nil +end + +function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Caf.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 = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample } + return audio, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function chunk(w: Bytes.Writer, typ: string, size: number) + w:string(typ) + w:i64be(size) +end + +-- encode(audio | decoder, opts?) -> buffer | nil, Err +function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local codec = o.codec or "alac" + if codec ~= "alac" and codec ~= "pcm" then + return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") + end + local sr, ch = value.sampleRate, value.channels + local depth = o.bitDepth or 16 + if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") + end + if ch < 1 or ch > 64 or sr <= 0 then + return nil, Err.new(Err.ARG, "bad sample rate / channels") + end + -- the source frames + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + local done = 0 + local chunkBuf: buffer? = nil + local function nextBlock(n: number): (buffer?, number, number) + if isAudio then + local k = math.min(n, value.frames - done) + local base = done * ch * 4 + done += k + return value.samples, base, k + end + local b, got = value:read(n, chunkBuf) + chunkBuf = b + done += got + return b, 0, got + end + local readf32 = buffer.readf32 + local data = Bytes.writer(65536) + local sizes: { number } = {} + local enc: Alac.Encoder? = nil + if codec == "alac" then + local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) + if not e then + return nil, err + end + enc = e + local ints = table.create(4096 * ch, 0) + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) + ints[i + 1] = math.clamp(v, -peak, peak - 1) + end + local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n) + if not pkt then + return nil, perr + end + data:bytes(pkt) + table.insert(sizes, buffer.len(pkt)) + end + else + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local f = readf32(b, base + i * 4) + if depth == 32 then + data:f32be(f) + else + local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) + if depth == 16 then + data:u16be(v % 65536) + else + data:u24be(v % 16777216) + end + end + end + end + end + local frames = done + local w = Bytes.writer(data:tell() + 1024) + w:string("caff") + w:u16be(1) + w:u16be(0) + chunk(w, "desc", 32) + w:f64be(sr) + if codec == "alac" then + w:string("alac") + w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) + w:u32be(0) + w:u32be(4096) + w:u32be(ch) + w:u32be(0) + else + w:string("lpcm") + w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer + w:u32be(ch * depth // 8) + w:u32be(1) + w:u32be(ch) + w:u32be(depth) + end + local tags = o.tags or value.tags or {} + local keys = {} + for k, v in tags do + if type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + if #keys > 0 then + local info = Bytes.writer(256) + info:u32be(#keys) + for _, k in keys do + info:cstring(TAG_INFO[k] or k) + info:cstring(tags[k]) + end + chunk(w, "info", info:tell()) + w:bytes(info.buf, 0, info:tell()) + end + if enc then + local cookie = Alac.cookie(enc.config) + chunk(w, "kuki", buffer.len(cookie)) + w:bytes(cookie) + local pk = Bytes.writer(64 + #sizes * 2) + pk:i64be(#sizes) + pk:i64be(frames) + pk:u32be(0) + pk:u32be(#sizes * 4096 - frames) + for _, s in sizes do + -- BER variable-length integer + local bytes = { s % 128 } + local v = s // 128 + while v > 0 do + table.insert(bytes, 1, 128 + v % 128) + v //= 128 + end + for _, x in bytes do + pk:u8(x) + end + end + chunk(w, "pakt", pk:tell()) + w:bytes(pk.buf, 0, pk:tell()) + end + chunk(w, "data", data:tell() + 4) + w:u32be(0) -- edit count + w:bytes(data.buf, 0, data:tell()) + return w:finish(), nil +end + +return Caf diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau new file mode 100644 index 0000000..39e9589 --- /dev/null +++ b/src/Formats/audio/m4a/init.luau @@ -0,0 +1,439 @@ +--!strict +-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading +-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless +-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); +-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs +-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local IsoBmff = require("@formats/containers/IsoBmff") +local Aac = require("@formats/codecs/Aac") +local Alac = require("@formats/codecs/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local M4a = { + name = "m4a", + category = "audio", + extensions = { "m4a", "m4b", "m4r", "aac.mp4" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + track: number?, -- the track id to play (default: the first AAC / ALAC track) + gapless: boolean?, -- apply the edit list (default true) + maxSamples: number?, -- sample table limit (default 2^25) +} +export type EncodeOptions = { + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- samples per packet, default 4096 + tags: Types.Tags?, -- default: the audio's tags + pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function M4a.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil then + return 0 + end + if AUDIO_BRANDS[brand] then + return AUDIO_BRANDS[brand] + end + if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then + return 0 + end + return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats +type PacketDecoder = { + channels: number, + sampleRate: number, + frameSize: number, + pcm: { number }, + decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?), + reset: () -> (), +} + +local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) + if not t.config then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") + end + if t.codec == "alac" then + local cfg, err = Alac.config(t.config :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + local pd: PacketDecoder = { + channels = cfg.channels, + sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100), + frameSize = cfg.frameLength, + pcm = pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + local n, e = dec:decode(buf, off, len) + if not n then + return nil, e + end + local src = dec.pcm + for i = 1, n * cfg.channels do + pcm[i] = src[i] * scale + end + return n, nil + end, + reset = function() end, + } + return pd, nil + elseif t.codec == "aac" then + local dec, err = Aac.decoder(t.config :: buffer) + if not dec then + return nil, err + end + local d = dec :: Aac.Decoder + local pd: PacketDecoder = { + channels = d.channels, + sampleRate = d.sampleRate, + frameSize = d.frameLength, + pcm = d.pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + return d:decode(buf, off, len) + end, + reset = function() + d:reset() + end, + } + return pd, nil + end + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") +end + +-- open(r, opts?) -> Types.Decoder | nil, Err +function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o = opts or {} + local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) + if not movie then + return nil, err + end + local track: IsoBmff.Track? = nil + local other: IsoBmff.Track? = nil + for _, t in movie.tracks do + if t.kind == "audio" then + if o.track and t.id ~= o.track then + continue + end + if t.codec == "aac" or t.codec == "alac" then + track = t + break + end + other = other or t + end + end + if not track then + if other then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") + end + return nil, Err.new(Err.CORRUPT, "no audio track") + end + local t = track :: IsoBmff.Track + local pd, perr = packetDecoder(t) + if not pd then + return nil, perr + end + local p = pd :: PacketDecoder + local channels, sr = p.channels, p.sampleRate + -- media ticks -> sample frames + local tickScale = sr / t.timescale + local gapless = o.gapless ~= false + local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 + local total = 0 + for i = 1, t.sampleCount do + total += t.durations[i] + end + total = math.floor(total * tickScale + 0.5) + if gapless and t.playDuration then + total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) + end + local tags, pictures = IsoBmff.tags(r, movie) + -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 ..." (hex) + local smpb = tags.iTunSMPB + if gapless and not t.edits and smpb then + local f = {} + for w in string.gmatch(smpb, "%x+") do + table.insert(f, tonumber(w, 16)) + end + if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then + skip = f[2] + total = f[2] + f[4] + end + end + local frames = math.max(0, total - skip) + local buf = r.buf + -- streaming state + local nextPacket = 1 + local decoded = 0 -- frames produced by the packets decoded so far (before trimming) + local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned + local dropUntil = skip -- absolute frame index of the first frame to return + local stopAt = total + local pos = 0 -- frames returned + local failed: Err.Err? = nil + + local dec: any = { + sampleRate = sr, + channels = channels, + frames = frames, + duration = frames / sr, + bitrate = if movie.duration > 0 then math.floor((r.limit - r.base) * 8 / math.max(frames / sr, 1e-9)) else 0, + tags = tags, + pictures = pictures, + codec = t.codec, + track = t, + movie = movie, + error = nil, + } + if t.bitrate then + dec.bitrate = t.bitrate + end + + -- decode the next packet into pend; false at the end / on an error + local function fill(): boolean + while true do + if nextPacket > t.sampleCount or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local start = decoded + local n, e = p.decode(buf, t.offsets[i], t.sizes[i]) + if not n then + failed = e + dec.error = e + return false + end + decoded += n + -- the part of this packet inside [dropUntil, stopAt) + local a = math.max(start, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos = a - start + pendN = b - start + return true + end + end + end + + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * channels * 4 + local ob = if out and buffer.len(out) >= need then out 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 = pend + local o = got * channels * 4 + local s = pendPos * channels + for k = 1, take * channels do + writef32(ob, o, src[s + k]) + o += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + + function dec.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame + -- the last packet starting at or before the target, minus one for the codec's overlap (AAC) + local ticks = target / tickScale + local lo, hi, found = 1, t.sampleCount, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= ticks then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found + p.reset() + nextPacket = startPacket + decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5) + dropUntil = math.max(target, skip) + pendPos, pendN = 0, 0 + failed = nil + pos = target - skip + end + + function dec.position(_self: any): number + return pos / sr + end + + -- prime: surface a broken first packet as an open error + if t.sampleCount > 0 and frames > 0 then + if not fill() and failed then + return nil, failed + end + end + return dec, nil +end + +-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) +function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = M4a.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 + local chunk = buffer.create(65536 * d.channels * 4) + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done), chunk) + 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 + if done < d.frames then + local short = buffer.create(done * d.channels * 4) + buffer.copy(short, 0, audio.samples, 0, buffer.len(short)) + audio.samples = short + audio.frames = done + end + audio.tags = d.tags + audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand } + if #d.pictures > 0 then + audio.meta.pictures = d.pictures + end + return audio, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A +function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local sr, ch = value.sampleRate, value.channels + local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) + if not enc then + return nil, eerr + end + local e = enc :: Alac.Encoder + local depth = e.config.bitDepth + local fl = e.config.frameLength + local peak = 2 ^ (depth - 1) + local packets: { buffer } = {} + local durations: { number } = {} + local ints = table.create(fl * ch, 0) + local floor = math.floor + local readf32 = buffer.readf32 + -- frames from an Audio buffer or a streaming Decoder + local src: buffer, srcFrames = nil :: any, 0 + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if isAudio then + src, srcFrames = value.samples, value.frames + if buffer.len(src) < srcFrames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local done = 0 + local chunk: buffer? = nil + while true do + local n, b, base + if isAudio then + n = math.min(fl, srcFrames - done) + b, base = src, done * ch * 4 + else + local got + b, got = value:read(fl, chunk) + chunk = b + n, base = got, 0 + end + if n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = floor(readf32(b, base + i * 4) * peak + 0.5) + if v >= peak then + v = peak - 1 + elseif v < -peak then + v = -peak + end + ints[i + 1] = v + end + local pkt, perr = e:encode(ints, 1, n) + if not pkt then + return nil, perr + end + table.insert(packets, pkt) + table.insert(durations, n) + done += n + if isAudio and done >= srcFrames then + break + end + end + local tags = o.tags or value.tags or {} + local pictures = o.pictures or (value.meta and value.meta.pictures) or nil + local timescale = if sr < 65536 then sr else 0 + local file, merr = IsoBmff.mux({ + brand = "M4A ", + minor = 0, + compatible = { "M4A ", "mp42", "isom" }, + timescale = 1000, + tracks = { + { + kind = "audio", + entry = "alac", + timescale = if timescale > 0 then timescale else 48000, + samples = packets, + durations = if timescale > 0 then durations else (function() + local d = {} + for i, v in durations do + d[i] = math.floor(v * 48000 / sr + 0.5) + end + return d + end)(), + sampleRate = sr, + channels = ch, + bitsPerSample = depth, + config = Alac.cookie(e.config), + }, + }, + tags = tags, + pictures = pictures, + }) + if not file then + return nil, merr + end + return file, nil +end + +return M4a diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/Aac/Decode.luau new file mode 100644 index 0000000..ce4a88b --- /dev/null +++ b/src/Formats/codecs/Aac/Decode.luau @@ -0,0 +1,903 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / +-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity +-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo, +-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four +-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook +-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message. +local Mdct = require("@formats/codecs/Mdct") +local Tables = require("@formats/codecs/Aac/Tables") + +local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band +local floor, sqrt, abs = math.floor, math.sqrt, math.abs + +local Decode = {} + +local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 +local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 + +-- ------------------------------------------------------------------------------------------------ bit reader +-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) +local B: buffer = buffer.create(16) +local BP = 0 -- bit position +local BL = 0 -- bit limit +local OVER = false + +local function getBits(n: number): number -- 1 .. 25 + local p = BP + BP = p + n + if p > BL then + OVER = true + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function peekBits(n: number): number + local p = BP + if p > BL then + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function getLong(n: number): number + if n > 24 then + local hi = getBits(n - 16) + return hi * 65536 + getBits(16) + end + return getBits(n) +end + +-- ------------------------------------------------------------------------------------------------ Huffman +local PEEK = 10 +type Book = { tab: { number }, map: { [number]: number }, maxLen: number } + +local function book(codes: { number }, bits: { number }): Book + local tab = table.create(2 ^ PEEK, 0) + local map = {} + local maxLen = 0 + for s = 1, #codes do + local c, l = codes[s], bits[s] + maxLen = math.max(maxLen, l) + if l <= PEEK then + local shift = 2 ^ (PEEK - l) + for k = 0, shift - 1 do + tab[c * shift + k + 1] = (s - 1) * 32 + l + end + else + map[l * 2 ^ 20 + c] = s - 1 + end + end + return { tab = tab, map = map, maxLen = maxLen } +end + +local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) +local SPEC_BOOK: { Book } = {} +for i = 1, 11 do + SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) +end + +-- the next symbol of a book, -1 for an invalid code +local function huff(bk: Book): number + local e = bk.tab[peekBits(PEEK) + 1] + if e > 0 then + BP += band(e, 31) + return rshift(e, 5) + end + -- a code longer than PEEK bits + local code = getBits(PEEK) + local map = bk.map + for l = PEEK + 1, bk.maxLen do + code = code * 2 + getBits(1) + local s = map[l * 1048576 + code] + if s then + return s + end + end + return -1 +end + +-- per codebook: dimension, unsigned, modulus, offset +local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } +local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } +local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } +local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } + +-- |q|^(4/3) +local POW43 = table.create(8192, 0) +for i = 0, 8191 do + POW43[i + 1] = i ^ (4 / 3) +end + +-- ------------------------------------------------------------------------------------------------ windows +local SINE_LONG = Mdct.window("sine", 2048) :: { number } +local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number } +local SINE_SHORT = Mdct.window("sine", 256) :: { number } +local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number } +local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan +local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ state +export type Channel = { + spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows) + overlap: { number }, -- 1024 samples carried to the next frame + prevShape: number, + -- this frame's ics + windowSequence: number, + windowShape: number, + maxSfb: number, + numGroups: number, + groupLen: { number }, + bandType: { number }, -- [g * maxSfb + sfb + 1] + sf: { number }, + -- tns + tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter +} + +export type State = { + sfIndex: number, + channels: number, -- configured channels (0: as found) + frameLength: number, + ch: { Channel }, + pcm: { number }, -- interleaved output floats + random: number, -- PNS generator state + time: { number }, -- 2048 IMDCT scratch + frame: { number }, -- 2048 windowed frame scratch + short: { number }, -- 256 scratch + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + extensions: number, -- extension payloads seen (SBR / PS / ...) + sbr: boolean, -- an SBR payload was seen + map: { number }?, -- element channel order -> output channel (1-based) +} + +local function newChannel(): Channel + return { + spec = table.create(1024, 0), + overlap = table.create(1024, 0), + prevShape = 0, + windowSequence = 0, + windowShape = 0, + maxSfb = 0, + numGroups = 1, + groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, + bandType = table.create(8 * 64, 0), + sf = table.create(8 * 64, 0), + tnsFilters = {}, + } +end +Decode.newChannel = newChannel + +-- ------------------------------------------------------------------------------------------------ ics +local function icsInfo(st: State, c: Channel): string? + if getBits(1) ~= 0 then + return "reserved ics bit set" + end + c.windowSequence = getBits(2) + c.windowShape = getBits(1) + if c.windowSequence == EIGHT_SHORT then + c.maxSfb = getBits(4) + local grouping = getBits(7) + local ng = 1 + local gl = c.groupLen + gl[1] = 1 + for w = 1, 7 do + if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then + gl[ng] += 1 + else + ng += 1 + gl[ng] = 1 + end + end + c.numGroups = ng + if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then + return "max_sfb over the short band count" + end + else + c.maxSfb = getBits(6) + c.numGroups = 1 + c.groupLen[1] = 1 + if getBits(1) ~= 0 then + return "prediction (AAC Main / LTP) is not supported" + end + if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "max_sfb over the long band count" + end + end + return nil +end + +local function sectionData(c: Channel): string? + local long = c.windowSequence ~= EIGHT_SHORT + local bits = if long then 5 else 3 + local esc = 2 ^ bits - 1 + local maxSfb = c.maxSfb + local bt = c.bandType + for g = 0, c.numGroups - 1 do + local k = 0 + while k < maxSfb do + local cb = getBits(4) + if cb == 12 then + return "reserved codebook 12" + end + local len = 0 + while true do + local inc = getBits(bits) + len += inc + if inc ~= esc then + break + end + if OVER then + return "section data runs past the end" + end + end + if k + len > maxSfb then + return "section runs past max_sfb" + end + for s = k, k + len - 1 do + bt[g * maxSfb + s + 1] = cb + end + k += len + if OVER then + return "section data runs past the end" + end + end + end + return nil +end + +local function scaleFactors(c: Channel, globalGain: number): string? + local sfv = globalGain + local noise = globalGain - 90 + local is = 0 + local firstNoise = true + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + for g = 0, c.numGroups - 1 do + for s = 0, maxSfb - 1 do + local i = g * maxSfb + s + 1 + local cb = bt[i] + if cb == ZERO_HCB then + sf[i] = 0 + elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + is += d - 60 + sf[i] = math.clamp(is, -155, 100) + elseif cb == NOISE_HCB then + if firstNoise then + noise += getBits(9) - 256 + firstNoise = false + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + noise += d - 60 + end + sf[i] = math.clamp(noise, -100, 155) + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + sfv += d - 60 + if sfv < 0 or sfv > 255 then + return "scalefactor out of range" + end + sf[i] = sfv + end + end + end + return nil +end + +local function tnsData(st: State, c: Channel): string? + local short = c.windowSequence == EIGHT_SHORT + local nw = if short then 8 else 1 + local filters = {} + for w = 1, nw do + local list = {} + local nFilt = getBits(if short then 1 else 2) + if nFilt > 0 then + local coefRes = getBits(1) + for _ = 1, nFilt do + local length = getBits(if short then 4 else 6) + local order = getBits(if short then 3 else 5) + local f = { length, order, 0 } + if order > (if short then 7 else 12) then + return "TNS order too high" + end + if order > 0 then + f[3] = getBits(1) + local compress = getBits(1) + local resBits = coefRes + 3 + local nb = resBits - compress + local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) + local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) + local tmp = table.create(order, 0) + for k = 1, order do + local v = getBits(nb) + if v >= 2 ^ (nb - 1) then + v -= 2 ^ nb + end + tmp[k] = math.sin(v / (if v >= 0 then iq else iqm)) + end + -- parcor -> LPC + local a = table.create(order + 1, 0) + local b = table.create(order + 1, 0) + a[1] = 1 + for m = 1, order do + for i = 1, m - 1 do + b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] + end + for i = 1, m - 1 do + a[i + 1] = b[i + 1] + end + a[m + 1] = tmp[m] + end + for k = 1, order do + f[3 + k] = a[k + 1] + end + end + table.insert(list, f) + end + end + filters[w] = list + end + c.tnsFilters = filters + local _ = st + return nil +end + +local function applyTns(st: State, c: Channel) + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] + local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] + local mmm = math.min(maxBands, c.maxSfb) + if mmm == 0 then + return + end + local spec = c.spec + for w, list in c.tnsFilters do + local bottom = numSwb + for _, f in list do + local top = bottom + bottom = math.max(0, top - f[1]) + local order = f[2] + if order > 0 then + local start = swb[math.min(bottom, mmm) + 1] + local stop = swb[math.min(top, mmm) + 1] + local size = stop - start + if size > 0 then + local inc = 1 + local p = (w - 1) * 128 + start + 1 + if f[3] == 1 then + inc = -1 + p = (w - 1) * 128 + stop + end + for m = 0, size - 1 do + local y = spec[p] + local lim = if m < order then m else order + for i = 1, lim do + y -= spec[p - i * inc] * f[3 + i] + end + spec[p] = y + p += inc + end + end + end + end + end +end + +-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) +local function spectralData(st: State, c: Channel, pulses: { number }?): string? + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local spec = c.spec + for i = 1, 1024 do + spec[i] = 0 + end + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + local win = 0 + for g = 0, c.numGroups - 1 do + local glen = c.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = bt[idx] + local lo, hi = swb[s + 1], swb[s + 2] + local width = hi - lo + if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + -- zeros (intensity bands are filled from the other channel later) + continue + elseif cb == NOISE_HCB then + local scale = 2 ^ (0.25 * sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local energy = 0 + local r = st.random + for k = 1, width do + r = (r * 1664525 + 1013904223) % 4294967296 + local v = if r >= 2147483648 then r - 4294967296 else r + spec[base + k] = v + energy += v * v + end + st.random = r + local m = if energy > 0 then scale / sqrt(energy) else 0 + for k = 1, width do + spec[base + k] *= m + end + end + continue + end + local bk = SPEC_BOOK[cb] + local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local k = 0 + while k < width do + local sym = huff(bk) + if sym < 0 then + return "bad spectral code" + end + -- unpack the symbol into dim values (first value most significant) + local vals1, vals2, vals3, vals4 + if dim == 4 then + vals4 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals3 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals2 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals1 = sym % mod - off + else + vals2 = sym % mod - off + vals1 = (sym - (sym % mod)) / mod - off + end + if uns then + if vals1 ~= 0 and getBits(1) == 1 then + vals1 = -vals1 + end + if vals2 ~= 0 and getBits(1) == 1 then + vals2 = -vals2 + end + if dim == 4 then + if vals3 ~= 0 and getBits(1) == 1 then + vals3 = -vals3 + end + if vals4 ~= 0 and getBits(1) == 1 then + vals4 = -vals4 + end + end + if cb == ESC_HCB then + for e = 1, 2 do + local v = if e == 1 then vals1 else vals2 + if v == 16 or v == -16 then + local n = 0 + while getBits(1) == 1 do + n += 1 + if n > 8 or OVER then + return "bad escape" + end + end + local esc = 2 ^ (n + 4) + getBits(n + 4) + if v < 0 then + esc = -esc + end + if e == 1 then + vals1 = esc + else + vals2 = esc + end + end + end + end + end + local p = base + k + 1 + spec[p] = vals1 + spec[p + 1] = vals2 + if dim == 4 then + spec[p + 2] = vals3 + spec[p + 3] = vals4 + end + k += dim + end + if OVER then + return "spectral data runs past the end" + end + end + -- dequantise (pulses are added to the quantised values first: long windows only, applied below) + if not pulses then + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + for k = 1, width do + local q = spec[base + k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[base + k] = if q < 0 then -v else v + end + end + end + end + end + win += glen + end + if pulses then + -- long window: add the pulses to the quantised values, then dequantise every band + for i = 1, #pulses, 2 do + local pos = pulses[i] + 1 + if pos <= 1024 then + local q = spec[pos] + spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1] + end + end + for s = 0, maxSfb - 1 do + local idx = s + 1 + local cb = bt[idx] + if cb ~= ZERO_HCB and cb < NOISE_HCB then + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for k = swb[s + 1] + 1, swb[s + 2] do + local q = spec[k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[k] = if q < 0 then -v else v + end + end + end + end + end + return nil +end + +-- individual_channel_stream +local function ics(st: State, c: Channel, commonWindow: boolean): string? + local globalGain = getBits(8) + if not commonWindow then + local e = icsInfo(st, c) + if e then + return e + end + end + local e = sectionData(c) + if e then + return e + end + e = scaleFactors(c, globalGain) + if e then + return e + end + local pulses: { number }? = nil + if getBits(1) == 1 then + if c.windowSequence == EIGHT_SHORT then + return "pulse data in a short window" + end + local n = getBits(2) + 1 + local startSfb = getBits(6) + if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "bad pulse start band" + end + local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] + local list = {} + for _ = 1, n do + pos += getBits(5) + table.insert(list, pos) + table.insert(list, getBits(4)) + end + pulses = list + end + c.tnsFilters = {} + if getBits(1) == 1 then + e = tnsData(st, c) + if e then + return e + end + end + if getBits(1) == 1 then + return "gain control (AAC SSR) is not supported" + end + if OVER then + return "channel stream runs past the end" + end + return spectralData(st, c, pulses) +end + +-- ------------------------------------------------------------------------------------------------ stereo +local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) + local short = l.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = l.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, l.numGroups - 1 do + local glen = l.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + local m, sd = a[k], b[k] + a[k], b[k] = m + sd, m - sd + end + end + end + end + win += glen + end +end + +local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) + local short = r.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = r.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, r.numGroups - 1 do + local glen = r.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = r.bandType[idx] + if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local sign = if cb == INTENSITY_HCB then 1 else -1 + if msPresent ~= 0 and mask[idx] == 1 then + sign = -sign + end + local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + b[k] = a[k] * scale + end + end + end + end + win += glen + end +end + +-- ------------------------------------------------------------------------------------------------ filterbank +local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) + local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape + local spec, overlap = c.spec, c.overlap + local frame = st.frame + local scale = 1 / 32768 + if seq == EIGHT_SHORT then + for i = 1, 2048 do + frame[i] = 0 + end + local tmp = st.short + local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT + local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT + for w = 0, 7 do + Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) + local rise = if w == 0 then rise0 else wcur + local base = 448 + w * 128 + for n = 1, 128 do + frame[base + n] += tmp[n] * rise[n] + frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n] + end + end + else + local t = st.time + Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) + -- left half + if seq == LONG_STOP then + local rise = if prev == 1 then KBD_SHORT else SINE_SHORT + for n = 1, 448 do + frame[n] = 0 + end + for n = 1, 128 do + frame[448 + n] = t[448 + n] * rise[n] + end + for n = 577, 1024 do + frame[n] = t[n] + end + else + local rise = if prev == 1 then KBD_LONG else SINE_LONG + for n = 1, 1024 do + frame[n] = t[n] * rise[n] + end + end + -- right half + if seq == LONG_START then + local fall = if shape == 1 then KBD_SHORT else SINE_SHORT + for n = 1025, 1472 do + frame[n] = t[n] + end + for n = 1, 128 do + frame[1472 + n] = t[1472 + n] * fall[128 + n] + end + for n = 1601, 2048 do + frame[n] = 0 + end + else + local fall = if shape == 1 then KBD_LONG else SINE_LONG + for n = 1025, 2048 do + frame[n] = t[n] * fall[n] + end + end + end + local p = offset + for n = 1, 1024 do + out[p] = (frame[n] + overlap[n]) * scale + overlap[n] = frame[1024 + n] + p += stride + end + c.prevShape = shape +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if buffer.len(B) < len + 16 then + B = buffer.create(len + 256) + end + buffer.copy(B, 0, buf, off, len) + buffer.fill(B, len, 0, 16) + BP, BL, OVER = 0, len * 8, false + local chans = st.ch + local nextCh = 1 + local order: { Channel } = {} + local lastElement = -1 + while true do + if BP + 3 > BL then + break -- tolerate a missing END + end + local id = getBits(3) + if id == 7 then + break + end + if id == 0 or id == 3 then -- SCE / LFE + getBits(4) + local c = chans[nextCh] + if not c then + c = newChannel() + chans[nextCh] = c + end + local e = ics(st, c, false) + if e then + return nil, e + end + applyTns(st, c) + table.insert(order, c) + nextCh += 1 + lastElement = id + elseif id == 1 then -- CPE + getBits(4) + local l, r = chans[nextCh], chans[nextCh + 1] + if not l then + l = newChannel() + chans[nextCh] = l + end + if not r then + r = newChannel() + chans[nextCh + 1] = r + end + local common = getBits(1) == 1 + local msPresent = 0 + local mask = table.create(8 * 64, 0) + if common then + local e = icsInfo(st, l) + if e then + return nil, e + end + r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups + for i = 1, 8 do + r.groupLen[i] = l.groupLen[i] + end + msPresent = getBits(2) + if msPresent == 1 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = getBits(1) + end + elseif msPresent == 2 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = 1 + end + elseif msPresent == 3 then + return nil, "reserved ms_mask_present" + end + end + local e = ics(st, l, common) + if e then + return nil, e + end + e = ics(st, r, common) + if e then + return nil, e + end + if common and msPresent ~= 0 then + msStereo(st, l, r, mask) + end + if common then + intensity(st, l, r, mask, msPresent) + end + applyTns(st, l) + applyTns(st, r) + table.insert(order, l) + table.insert(order, r) + nextCh += 2 + lastElement = id + elseif id == 2 then + return nil, "coupling channel elements are not supported" + elseif id == 4 then -- DSE + getBits(4) + local align = getBits(1) + local count = getBits(8) + if count == 255 then + count += getBits(8) + end + if align == 1 then + BP = (BP + 7) // 8 * 8 + end + BP += count * 8 + elseif id == 5 then -- PCE: skipped here (parsed from the configuration) + return nil, "program config element inside the stream is not supported" + elseif id == 6 then -- FIL + local count = getBits(4) + if count == 15 then + count += getBits(8) - 1 + end + if count > 0 then + local start = BP + local kind = getBits(4) + if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC + st.sbr = true + end + st.extensions += 1 + local hook = st.onExtension + if hook then + hook(kind, lastElement, B, start, count * 8) + end + BP = start + count * 8 + end + end + if OVER or BP > BL then + return nil, "frame runs past the end" + end + if nextCh > 9 then + return nil, "more than 8 channels" + end + end + local n = #order + if n == 0 then + return 0, nil + end + local pcm = st.pcm + local map = st.map + for i, c in order do + local o = if map and map[i] then map[i] else i + filterbank(st, c, pcm, n, o) + end + return n, nil +end + +function Decode.state(sfIndex: number): State + return { + sfIndex = sfIndex, + channels = 0, + frameLength = 1024, + ch = {}, + pcm = table.create(1024 * 8, 0), + random = 0x1f2e3d4c, + time = table.create(2048, 0), + frame = table.create(2048, 0), + short = table.create(256, 0), + onExtension = nil, + extensions = 0, + sbr = false, + map = nil, + } +end + +local _ = abs +local _2 = floor +return Decode diff --git a/src/Formats/codecs/Aac/Tables.luau b/src/Formats/codecs/Aac/Tables.luau new file mode 100644 index 0000000..65305fb --- /dev/null +++ b/src/Formats/codecs/Aac/Tables.luau @@ -0,0 +1,335 @@ +--!strict +-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven +-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128 +-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; +-- see licenses/NOTICE.md). Generated; do not edit. +local Tables = {} + +Tables.SF_CODES = { + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +} + +Tables.SF_BITS = { + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, + 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, + 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, + 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, +} + +Tables.SPEC_CODES = { + { + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, + }, + { + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, + }, + { + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, + }, + { + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, + }, + { + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, + }, + { + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, + }, + { + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, + }, + { + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, + }, + { + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, + }, + { + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, + }, + { + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, + }, +} + +Tables.SPEC_BITS = { + { + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, + }, + { + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, + 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, + 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, + }, + { + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, + 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, + 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, + }, + { + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, + 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, + 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, + }, + { + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, + 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, + }, + { + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, + 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, + }, + { + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, + 11, 11, 12, 12, + }, + { + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, + 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, + 9, 9, 9, 10, + }, + { + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, + 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, + 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, + 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, + 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, + }, + { + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, + 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, + 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, + }, + { + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, + 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, + 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, + 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, + 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, + 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, + }, +} + +Tables.SWB_LONG = { + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, + 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, +} + +Tables.SWB_SHORT = { + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, +} + +Tables.NUM_SWB_LONG = { + 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, +} + +Tables.NUM_SWB_SHORT = { + 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, +} + +Tables.TNS_MAX_BANDS_LONG = { + 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, +} + +Tables.TNS_MAX_BANDS_SHORT = { + 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +} + +return Tables + diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/Aac/init.luau new file mode 100644 index 0000000..c7e5e0b --- /dev/null +++ b/src/Formats/codecs/Aac/init.luau @@ -0,0 +1,336 @@ +--!strict +-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding +-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. +-- Written from the standard (tables: codecs/Aac/Tables); no third-party code. +-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD +-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads) +-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a +-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain +-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED). +-- +-- local Aac = require("@formats/codecs/Aac") +-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels } +-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats) +-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... } +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bits = require("@formats/core/Bits") +local Decode = require("@formats/codecs/Aac/Decode") + +local Aac = {} + +Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } +local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } +-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 +local CONFIG_MAP: { [number]: { number } } = { + [3] = { 3, 1, 2 }, + [4] = { 3, 1, 2, 4 }, + [5] = { 3, 1, 2, 4, 5 }, + [6] = { 3, 1, 2, 5, 6, 4 }, + [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, +} + +export type Config = { + objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) + sfIndex: number, + sampleRate: number, -- the core rate + channelConfig: number, + channels: number, + sbr: boolean, -- SBR signalled (explicitly or backward-compatibly) + ps: boolean, + extensionRate: number?, -- the SBR output rate + frameLength: number, +} + +local function rateIndex(rate: number): number + -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) + local best, bi = math.huge, 4 + for i, r in Aac.RATES do + if math.abs(r - rate) < best then + best, bi = math.abs(r - rate), i - 1 + end + end + return bi +end + +local function objectType(br: Bits.BitReader): number + local t = br:read(5) + if t == 31 then + t = 32 + br:read(6) + end + return t +end + +local function frequency(br: Bits.BitReader): (number, number) + local i = br:read(4) + if i == 15 then + local f = br:read(24) + return rateIndex(f), f + end + return i, Aac.RATES[i + 1] or 0 +end + +-- pce(br) -> channels (program_config_element) +local function pce(br: Bits.BitReader): number + br:read(4 + 2 + 4) + local front, side, back = br:read(4), br:read(4), br:read(4) + local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(3) + end + local channels = 0 + for _ = 1, front + side + back do + channels += if br:read(1) == 1 then 2 else 1 + br:read(4) + end + channels += lfe + br:skip(lfe * 4 + assoc * 4 + cc * 5) + br:align() + br:skip(br:read(8) * 8) + return channels +end + +-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig +function Aac.config(asc: buffer): (Config?, Err.Err?) + if type(asc) ~= "buffer" or buffer.len(asc) < 2 then + return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") + end + local br = Bits.msbReader(asc) + local aot = objectType(br) + local sfi, rate = frequency(br) + local chcfg = br:read(4) + local sbr, ps = false, false + local extRate: number? = nil + if aot == 5 or aot == 29 then + sbr = true + ps = aot == 29 + local _, er = frequency(br) + extRate = er + aot = objectType(br) + if aot == 22 then + br:read(4) + end + end + if aot ~= 2 and aot ~= 1 and aot ~= 4 then + if aot == 0 or br.err then + return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") + end + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") + end + if aot ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP") + end + -- GASpecificConfig + local frameLengthFlag = br:read(1) + if br:read(1) == 1 then + br:read(14) + end + local ext = br:read(1) + local channels = CONFIG_CHANNELS[chcfg] or 0 + if chcfg == 0 then + channels = pce(br) + elseif chcfg > 7 then + return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) + end + if ext == 1 then + br:read(1) -- extensionFlag3 + end + -- backward-compatible SBR signalling + if not sbr and br:bitsLeft() >= 16 then + if br:read(11) == 0x2b7 then + local et = objectType(br) + if et == 5 and br:read(1) == 1 then + sbr = true + local _, er = frequency(br) + extRate = er + if br:bitsLeft() >= 12 and br:read(11) == 0x548 then + ps = br:read(1) == 1 + end + end + end + end + if br.err and channels == 0 then + return nil, br.err + end + if sfi > 12 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) + end + if frameLengthFlag == 1 then + return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") + end + if channels < 1 or channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") + end + return { + objectType = aot, + sfIndex = sfi, + sampleRate = rate, + channelConfig = chcfg, + channels = channels, + sbr = sbr, + ps = ps, + extensionRate = extRate, + frameLength = 1024, + }, nil +end + +-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig +function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer + local b = buffer.create(2) + local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 + buffer.writeu8(b, 0, bit32.rshift(v, 8)) + buffer.writeu8(b, 1, bit32.band(v, 255)) + return b +end + +export type Adts = { + headerSize: number, -- 7, or 9 with a CRC + frameSize: number, -- the whole frame, header included + objectType: number, + sfIndex: number, + sampleRate: number, + channelConfig: number, + blocks: number, -- raw_data_blocks in the frame (1 .. 4) + protected: boolean, +} + +-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) +function Aac.adts(b: buffer, o: number, limit: number): Adts? + if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then + return nil + end + local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) + if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 + return nil + end + local protected = bit32.band(b1, 1) == 0 + local profile = bit32.rshift(b2, 6) + local sfi = bit32.band(bit32.rshift(b2, 2), 15) + local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) + local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) + local blocks = bit32.band(b6, 3) + 1 + local hs = if protected then 9 else 7 + if sfi > 12 or size < hs then + return nil + end + return { + headerSize = hs, + frameSize = size, + objectType = profile + 1, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = ch, + blocks = blocks, + protected = protected, + } +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + config: Config, + channels: number, + sampleRate: number, + frameLength: number, + pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order + sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local st = self.state + st.onExtension = self.onExtension + local chans, msg = Decode.frame(st, buf, o, n) + if not chans then + return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) + end + if st.sbr then + self.sbr = true + end + if chans == 0 then + -- an empty frame (only fill elements): silence + for i = 1, 1024 * self.channels do + st.pcm[i] = 0 + end + return 1024, nil + end + if chans ~= self.channels then + return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) + end + return 1024, nil +end + +local function reset(self: Decoder) + for _, c in self.state.ch do + for i = 1, 1024 do + c.overlap[i] = 0 + end + c.prevShape = 0 + end +end + +-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err +function Aac.decoder(asc: any): (Decoder?, Err.Err?) + local cfg: Config + if type(asc) == "buffer" then + local c, err = Aac.config(asc) + if not c then + return nil, err + end + cfg = c + elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then + local sfi = asc.sfIndex + if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then + return nil, Err.new(Err.ARG, "bad sampling index / channels") + end + if (asc.objectType or 2) ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") + end + cfg = { + objectType = 2, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = asc.channelConfig or asc.channels, + channels = asc.channels, + sbr = false, + ps = false, + frameLength = 1024, + } + else + return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") + end + local st = Decode.state(cfg.sfIndex) + st.channels = cfg.channels + if cfg.channelConfig >= 3 then + st.map = CONFIG_MAP[cfg.channelConfig] + end + return { + config = cfg, + channels = cfg.channels, + sampleRate = cfg.sampleRate, + frameLength = 1024, + pcm = st.pcm, + sbr = cfg.sbr, + onExtension = nil, + decode = decode, + reset = reset, + state = st, + }, nil +end + +return Aac diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/Alac/Decode.luau new file mode 100644 index 0000000..932d7e7 --- /dev/null +++ b/src/Formats/codecs/Alac/Decode.luau @@ -0,0 +1,427 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice +-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes, +-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple +-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message. +local readu32, readu8 = buffer.readu32, buffer.readu8 +local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot +local floor = math.floor + +local Decode = {} + +export type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + maxRun: number, + scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) + pred: { { number } }, -- per element channel (0, 1): residuals / predictor output + mix: { { number } }, + shift: { number }, + out: { number }, -- interleaved output samples (integers), frames * channels +} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. +local function bitsAt(b: buffer, pos: number, n: number): number + local w = byteswap(readu32(b, rshift(pos, 3))) + return rshift(lshift(w, band(pos, 7)), 32 - n) +end + +local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits +local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) + local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) + local pre = countlz(bnot(w)) + if pre >= 9 then + pos += 9 + local v + if bps > 25 then + v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) + else + v = bitsAt(b, pos, bps) + end + return v, pos + bps + end + pos += pre + 1 + if k == 1 then + return pre, pos + end + local v = bitsAt(b, pos, k) + local x = pre * m + if v > 1 then + return x + v - 1, pos + k + end + return x, pos + k - 1 +end + +-- residuals: n values into out[1..n]; returns the new bit position or -1 +local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local i = 1 + while i <= n do + if pos > limit then + return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes + end + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local x + x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) + x += signMod + signMod = 0 + out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2 + if x > 0xFFFF then + history = 0xFFFF + else + history += x * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + if pos > limit then + return -1 + end + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run + run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) + if run > 0 then + if run > n - i then + return -1 + end + for j = i + 1, i + run do + out[j] = 0 + end + i += run + end + if run < 0xFFFF then + signMod = 1 -- the next value is not 0 (unless the run hit its maximum) + end + history = 0 + end + i += 1 + end + return pos +end + +-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place +local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + out[1] = err[1] + if n <= 1 then + return + end + if order == 0 then + if out ~= err then + for i = 2, n do + out[i] = err[i] + end + end + return + end + if order == 31 then + for i = 2, n do + out[i] = signExtend(out[i - 1] + err[i], bps) + end + return + end + local i = 2 + while i <= order + 1 and i <= n do + out[i] = signExtend(out[i - 1] + err[i], bps) + i += 1 + end + local half = if quant > 0 then POW[quant] else 0 + local qd = POW[quant + 1] + -- coefs[1] multiplies the most recent sample + while i <= n do + local d = out[i - order - 1] + local val = 0 + for j = 1, order do + val += (out[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local e = err[i] + out[i] = signExtend(val + d + e, bps) + if e ~= 0 then + local es = if e > 0 then 1 else -1 + -- adapt from the oldest sample to the newest while the error keeps its sign + for j = order, 1, -1 do + if e * es <= 0 then + break + end + local v = d - out[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + e -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the +-- ALAC element order. +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if len <= 0 then + return nil, "empty packet" + end + local b = st.scratch + if buffer.len(b) < len + 16 then + b = buffer.create(len + 64) + st.scratch = b + end + buffer.copy(b, 0, buf, off, len) + buffer.fill(b, len, 0, 16) + local limit = len * 8 + local pos = 0 + local channels = st.channels + local ch = 0 -- next output channel + local frames = -1 + local out = st.out + while true do + if pos + 3 > limit then + return nil, "frame runs past the end" + end + local tag = bitsAt(b, pos, 3) + pos += 3 + if tag == 7 then -- END + break + elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE + local nch = if tag == 1 then 2 else 1 + if ch + nch > channels then + return nil, "more channels than the configuration" + end + pos += 4 -- element instance tag + if bitsAt(b, pos, 12) ~= 0 then + return nil, "bad element header" + end + pos += 12 + local h = bitsAt(b, pos, 4) + pos += 4 + local partial = rshift(h, 3) + local shiftBytes = band(rshift(h, 1), 3) + local escape = band(h, 1) + if shiftBytes == 3 then + return nil, "bad shift" + end + local n = st.frameLength + if partial == 1 then + n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) + pos += 32 + end + if n < 1 or n > st.frameLength then + return nil, "bad frame length " .. n + end + if frames >= 0 and n ~= frames then + return nil, "elements of different lengths" + end + frames = n + if #out < n * channels then + for k = #out + 1, n * channels do + out[k] = 0 + end + end + local shift = shiftBytes * 8 + local bps = st.bitDepth - shift + nch - 1 + if bps > 32 or bps < 1 then + return nil, "bad sample size" + end + if pos > limit then + return nil, "frame runs past the end" + end + local mixBits, mixRes = 0, 0 + local p0, p1 = st.pred[1], st.pred[2] + local m0, m1 = st.mix[1], st.mix[2] + local shiftBuf = st.shift + if escape == 0 then + mixBits = bitsAt(b, pos, 8) + mixRes = bitsAt(b, pos + 8, 8) + pos += 16 + if mixRes >= 128 then + mixRes -= 256 + end + local mode, denShift, pbFactor, order = {}, {}, {}, {} + local coefs = { {}, {} } + for c = 1, nch do + local x = bitsAt(b, pos, 8) + local y = bitsAt(b, pos + 8, 8) + pos += 16 + mode[c], denShift[c] = rshift(x, 4), band(x, 15) + pbFactor[c], order[c] = rshift(y, 5), band(y, 31) + if pos + order[c] * 16 > limit then + return nil, "frame runs past the end" + end + for j = 1, order[c] do + local v = bitsAt(b, pos, 16) + pos += 16 + coefs[c][j] = if v >= 32768 then v - 65536 else v + end + end + if pos > limit then + return nil, "frame runs past the end" + end + local shiftPos = pos + if shift > 0 then + pos += shift * n * nch + end + for c = 1, nch do + local p = if c == 1 then p0 else p1 + local mb = if c == 1 then m0 else m1 + pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) + if pos < 0 or pos > limit then + return nil, "bad residuals" + end + if mode[c] == 15 then + predict(p, p, n, bps, {}, 31, 0) + elseif mode[c] ~= 0 then + return nil, "unknown prediction mode " .. mode[c] + end + predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) + end + if shift > 0 then + local sp = shiftPos + for i = 1, n * nch do + shiftBuf[i] = bitsAt(b, sp, shift) + sp += shift + end + end + else + -- uncompressed: interleaved samples of bitDepth bits + local bits = st.bitDepth + if pos + n * nch * bits > limit then + return nil, "frame runs past the end" + end + for i = 1, n do + for c = 1, nch do + local v + if bits > 25 then + v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) + else + v = bitsAt(b, pos, bits) + end + pos += bits + v = signExtend(v, bits) + if c == 1 then + m0[i] = v + else + m1[i] = v + end + end + end + shift = 0 + end + -- unmix + shifted bytes -> interleaved output + local sm = POW[shift + 1] + if nch == 2 then + local den = POW[mixBits + 1] + for i = 1, n do + local u, v = m0[i], m1[i] + local l, r + if mixRes ~= 0 then + l = u + v - floor(mixRes * v / den) + r = l - v + else + l, r = u, v + end + if shift > 0 then + l = l * sm + shiftBuf[2 * i - 1] + r = r * sm + shiftBuf[2 * i] + end + local o = (i - 1) * channels + ch + 1 + out[o] = l + out[o + 1] = r + end + else + for i = 1, n do + local v = m0[i] + if shift > 0 then + v = v * sm + shiftBuf[i] + end + out[(i - 1) * channels + ch + 1] = v + end + end + ch += nch + elseif tag == 4 then -- DSE + pos += 4 + local align = bitsAt(b, pos, 1) + local count = bitsAt(b, pos + 1, 8) + pos += 9 + if count == 255 then + count += bitsAt(b, pos, 8) + pos += 8 + end + if align == 1 then + pos = (pos + 7) // 8 * 8 + end + pos += count * 8 + elseif tag == 6 then -- FIL + local count = bitsAt(b, pos, 4) + pos += 4 + if count == 15 then + count += bitsAt(b, pos, 8) - 1 + pos += 8 + end + pos += count * 8 + else + return nil, "unsupported element " .. tag + end + if pos > limit then + return nil, "frame runs past the end" + end + end + if frames < 0 then + return 0, nil + end + if ch < channels then + -- missing channels: silence + for i = 1, frames do + for c = ch + 1, channels do + out[(i - 1) * channels + c] = 0 + end + end + end + return frames, nil +end + +-- the scratch state for a configuration +function Decode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + maxRun = cfg.maxRun, + scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), + pred = { table.create(n, 0), table.create(n, 0) }, + mix = { table.create(n, 0), table.create(n, 0) }, + shift = table.create(n * 2, 0), + out = table.create(n * cfg.channels, 0), + } +end + +local _ = readu8 +return Decode diff --git a/src/Formats/codecs/Alac/Encode.luau b/src/Formats/codecs/Alac/Encode.luau new file mode 100644 index 0000000..4309bd5 --- /dev/null +++ b/src/Formats/codecs/Alac/Encode.luau @@ -0,0 +1,427 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of +-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation, +-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the +-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit +-- input. Written for this library from the ALAC format; no third-party code. Never throws. +local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor, abs = math.floor, math.abs + +local Encode = {} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +local DENSHIFT = 9 +local PB_FACTOR = 4 + +export type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + out: buffer, -- packet scratch + pos: number, -- bit position in out + cap: number, -- bits available + u: { number }, + v: { number }, + err: { number }, + work: { number }, +} + +-- ------------------------------------------------------------------------------------------------ bit writer +local function put(st: State, v: number, n: number) + local pos = st.pos + if pos + n > st.cap then + st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame + return + end + local b = st.out + while n > 0 do + local byte = rshift(pos, 3) + local free = 8 - band(pos, 7) + local take = if n < free then n else free + local bits = band(rshift(v, n - take), POW[take + 1] - 1) + writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) + pos += take + n -= take + end + st.pos = pos +end + +local function putBig(st: State, v: number, n: number) + if n > 24 then + local lo = v % 65536 + put(st, (v - lo) / 65536, n - 16) + put(st, lo, 16) + else + put(st, v, n) + end +end + +-- ------------------------------------------------------------------------------------------------ rice code +local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the bits of one scalar (no writing) +local function scalarBits(x: number, k: number, m: number, bps: number): number + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + return 9 + bps + end + if k == 1 then + return pre + 1 + end + local r = x - pre * m + return pre + 1 + (if r == 0 then k - 1 else k) +end + +local function scalar(st: State, x: number, k: number, m: number, bps: number) + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + put(st, 511, 9) + putBig(st, x, bps) + return + end + -- pre ones and a zero + put(st, POW[pre + 2] - 2, pre + 1) + if k ~= 1 then + local r = x - pre * m + if r == 0 then + put(st, 0, k - 1) + else + put(st, r + 1, k) + end + end +end + +-- code the residuals e[1..n] (write = false: just count the bits) +local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local bits = 0 + local i = 1 + while i <= n do + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local v = e[i] + local zz = if v >= 0 then 2 * v else -2 * v - 1 + local x = zz - signMod + signMod = 0 + local m = POW[k + 1] - 1 + if write then + scalar(st, x, k, m, bps) + else + bits += scalarBits(x, k, m, bps) + end + if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back + history = 0xFFFF + else + history += zz * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run = 0 + while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do + run += 1 + end + m = POW[k + 1] - 1 + if write then + scalar(st, run, k, m, 16) + else + bits += scalarBits(run, k, m, 16) + end + i += run + if run < 0xFFFF then + signMod = 1 + end + history = 0 + end + i += 1 + end + return bits +end + +-- ------------------------------------------------------------------------------------------------ prediction +-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) +local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + e[1] = x[1] + if n <= 1 then + return + end + local i = 2 + while i <= order + 1 and i <= n do + e[i] = signExtend(x[i] - x[i - 1], bps) + i += 1 + end + local half = POW[quant] + local qd = POW[quant + 1] + while i <= n do + local d = x[i - order - 1] + local val = 0 + for j = 1, order do + val += (x[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local r = signExtend(x[i] - val - d, bps) + e[i] = r + if r ~= 0 then + local es = if r > 0 then 1 else -1 + for j = order, 1, -1 do + if r * es <= 0 then + break + end + local v = d - x[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + r -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised +local function lpc(x: { number }, n: number, order: number, work: { number }): { number } + local ac = table.create(order + 1, 0) + for i = 1, n do + local t = (2 * (i - 1) - (n - 1)) / (n + 1) + work[i] = x[i] * (1 - t * t) + end + for lag = 0, order do + local s = 0 + for i = lag + 1, n do + s += work[i] * work[i - lag] + end + ac[lag + 1] = s + end + local coefs = table.create(order, 0) + if ac[1] <= 0 then + return coefs + end + ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable + local a = table.create(order + 1, 0) + local tmp = table.create(order + 1, 0) + local errv = ac[1] + for i = 1, order do + local acc = ac[i + 1] + for j = 1, i - 1 do + acc -= a[j] * ac[i - j + 1] + end + local kc = acc / errv + for j = 1, i - 1 do + tmp[j] = a[j] - kc * a[i - j] + end + for j = 1, i - 1 do + a[j] = tmp[j] + end + a[i] = kc + errv *= (1 - kc * kc) + if errv <= 0 then + break + end + end + local scale = POW[DENSHIFT + 1] + for j = 1, order do + coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) + end + return coefs +end + +-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits +local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) + local mult = floor(st.pb * PB_FACTOR / 4) + local bestOrder, bestCoefs, bestBits = 0, {}, math.huge + for _, order in { 4, 8 } do + if order >= n then + continue + end + local coefs = lpc(x, n, order, st.work) + local trial = table.clone(coefs) + residuals(x, st.err, n, bps, trial, order, DENSHIFT) + local bits = rice(st, st.err, n, bps, mult, false) + order * 16 + if bits < bestBits then + bestOrder, bestCoefs, bestBits = order, coefs, bits + end + end + if bestBits == math.huge then + -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) + for i = 1, n do + st.err[i] = x[i] + end + return 0, {}, rice(st, st.err, n, bps, mult, false) + end + return bestOrder, bestCoefs, bestBits +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index +-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts +function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer + local channels, depth = st.channels, st.bitDepth + local n = frames + local partial = n ~= st.frameLength + local rawBits = n * channels * depth + local need = rawBits + 64 * #elements + 64 + if st.cap < need + 8 * 32 * 2 * #elements * 16 then + local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16 + st.out = buffer.create(bytes) + st.cap = bytes * 8 + end + buffer.fill(st.out, 0, 0) + st.pos = 0 + local u, v = st.u, st.v + local mult = floor(st.pb * PB_FACTOR / 4) + local compressed = true + local ch = 1 + for _, nch in elements do + local a, b = map[ch], map[ch + 1] + local bps = depth + nch - 1 + local mixRes = 0 + if nch == 2 then + -- the mix with the smallest first-difference energy + local best = math.huge + for res = 0, 4 do + local cost = 0 + local pu, pv = 0, 0 + for i = 0, n - 1 do + local l = samples[first + i * channels + a - 1] + local r = samples[first + i * channels + b - 1] + local uu, vv + if res == 0 then + uu, vv = l, r + else + uu, vv = floor((res * l + (4 - res) * r) / 4), l - r + end + cost += abs(uu - pu) + abs(vv - pv) + pu, pv = uu, vv + end + if cost < best then + best, mixRes = cost, res + end + end + for i = 1, n do + local l = samples[first + (i - 1) * channels + a - 1] + local r = samples[first + (i - 1) * channels + b - 1] + if mixRes == 0 then + u[i], v[i] = l, r + else + u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r + end + end + else + for i = 1, n do + u[i] = samples[first + (i - 1) * channels + a - 1] + end + end + -- header + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 0, 1) + if partial then + putBig(st, n, 32) + end + put(st, if mixRes == 0 then 0 else 2, 8) + put(st, mixRes, 8) + local orders, coefsList = {}, {} + for c = 1, nch do + local x = if c == 1 then u else v + local order, coefs = analyse(st, x, n, bps) + orders[c], coefsList[c] = order, coefs + put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift + put(st, PB_FACTOR * 32 + order, 8) + for j = 1, order do + put(st, coefs[j] % 65536, 16) + end + end + for c = 1, nch do + local x = if c == 1 then u else v + local order = orders[c] + if order == 0 then + for i = 1, n do + st.err[i] = x[i] + end + else + residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) + end + rice(st, st.err, n, bps, mult, true) + end + ch += nch + if st.pos > rawBits + 64 * #elements then + compressed = false + break + end + end + if not compressed then + -- uncompressed frame + buffer.fill(st.out, 0, 0) + st.pos = 0 + ch = 1 + for _, nch in elements do + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 1, 1) + if partial then + putBig(st, n, 32) + end + for i = 0, n - 1 do + for c = 0, nch - 1 do + putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) + end + end + ch += nch + end + end + put(st, 7, 3) -- END + local bytes = (st.pos + 7) // 8 + local pkt = buffer.create(bytes) + buffer.copy(pkt, 0, st.out, 0, bytes) + return pkt +end + +function Encode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + out = buffer.create(16), + pos = 0, + cap = 0, + u = table.create(n, 0), + v = table.create(n, 0), + err = table.create(n, 0), + work = table.create(n, 0), + } +end + +return Encode diff --git a/src/Formats/codecs/Alac/init.luau b/src/Formats/codecs/Alac/init.luau new file mode 100644 index 0000000..7af082b --- /dev/null +++ b/src/Formats/codecs/Alac/init.luau @@ -0,0 +1,251 @@ +--!strict +-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). +-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice +-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 / +-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels). +-- +-- local Alac = require("@formats/codecs/Alac") +-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped) +-- local dec = Alac.decoder(cfg) +-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order) +-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) +-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) +-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled +-- +-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Decode = require("@formats/codecs/Alac/Decode") +local Encode = require("@formats/codecs/Alac/Encode") + +local Alac = {} + +export type Config = { + frameLength: number, -- samples per packet (4096) + compatibleVersion: number, + bitDepth: number, + pb: number, -- 40 + mb: number, -- 10 + kb: number, -- 14 + channels: number, + maxRun: number, -- 255 + maxFrameBytes: number, + avgBitRate: number, + sampleRate: number, +} + +-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count +local TO_WAV: { { number } } = { + { 1 }, + { 1, 2 }, + { 3, 1, 2 }, + { 3, 1, 2, 4 }, + { 3, 1, 2, 4, 5 }, + { 3, 1, 2, 5, 6, 4 }, + { 3, 1, 2, 5, 6, 7, 4 }, + { 3, 7, 8, 1, 2, 5, 6, 4 }, +} +-- the element layout (channels per element) the encoder writes +local ELEMENTS: { { number } } = { + { 1 }, + { 2 }, + { 1, 2 }, + { 1, 2, 1 }, + { 1, 2, 2 }, + { 1, 2, 2, 1 }, + { 1, 2, 2, 1, 1 }, + { 1, 2, 2, 2, 1 }, +} +Alac.TO_WAV = TO_WAV + +-- config(buf, offset?, length?) -> Config | nil, Err +function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?) + local r = Bytes.reader(buf, offset, length) + -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie + for _ = 1, 2 do + local typ = r:peek(4, 4) + if typ == "frma" then + r:skip(12) + elseif typ == "alac" then + r:skip(12) + end + end + if r:remaining() < 24 then + return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") + end + local c: Config = { + frameLength = r:u32be(), + compatibleVersion = r:u8(), + bitDepth = r:u8(), + pb = r:u8(), + mb = r:u8(), + kb = r:u8(), + channels = r:u8(), + maxRun = r:u16be(), + maxFrameBytes = r:u32be(), + avgBitRate = r:u32be(), + sampleRate = r:u32be(), + } + if c.compatibleVersion ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) + end + if c.frameLength < 1 or c.frameLength > 65536 then + return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) + end + if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) + end + if c.channels < 1 or c.channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") + end + if c.kb < 1 or c.kb > 24 then + return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) + end + return c, nil +end + +-- cookie(cfg) -> the 24-byte ALACSpecificConfig +function Alac.cookie(c: Config): buffer + local w = Bytes.writer(24) + w:u32be(c.frameLength) + w:u8(0) + w:u8(c.bitDepth) + w:u8(c.pb) + w:u8(c.mb) + w:u8(c.kb) + w:u8(c.channels) + w:u16be(c.maxRun) + w:u32be(c.maxFrameBytes) + w:u32be(c.avgBitRate) + w:u32be(c.sampleRate) + return w:finish() +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + config: Config, + pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local frames, msg = Decode.frame(self.state, buf, o, n) + if not frames then + return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) + end + local ch = self.config.channels + local src, dst = self.state.out, self.pcm + if ch <= 2 then + for i = 1, frames * ch do + dst[i] = src[i] + end + else + local map = TO_WAV[ch] + for f = 0, frames - 1 do + local base = f * ch + for k = 1, ch do + dst[base + map[k]] = src[base + k] + end + end + end + return frames, nil +end + +-- decoder(cfg) -> Decoder +function Alac.decoder(cfg: Config): Decoder + return { + config = cfg, + pcm = table.create(cfg.frameLength * cfg.channels, 0), + decode = decode, + state = Decode.state(cfg), + } +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Encoder = { + config: Config, + encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), + state: Encode.State, + bytes: number, + frames: number, +} + +local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?) + local cfg = self.config + if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") + end + if first < 1 or first + frames * cfg.channels - 1 > #samples then + return nil, Err.new(Err.ARG, "encode: the samples end early") + end + local ch = cfg.channels + local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) + local n = buffer.len(pkt) + self.bytes += n + self.frames += frames + if n > cfg.maxFrameBytes then + cfg.maxFrameBytes = n + end + if self.frames > 0 then + cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) + end + return pkt, nil +end + +export type EncoderOptions = { + sampleRate: number, + channels: number, -- 1 .. 8 + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- default 4096 +} + +-- encoder(opts) -> Encoder | nil, Err +function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) + if type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "encoder: expected options") + end + local depth = opts.bitDepth or 16 + local ch = opts.channels + if depth ~= 16 and depth ~= 20 and depth ~= 24 then + return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") + end + if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") + end + local sr = opts.sampleRate + if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: bad sampleRate") + end + local fl = opts.frameLength or 4096 + if fl < 16 or fl > 16384 or fl % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") + end + local cfg: Config = { + frameLength = fl, + compatibleVersion = 0, + bitDepth = depth, + pb = 40, + mb = 10, + kb = 14, + channels = ch, + maxRun = 255, + maxFrameBytes = 0, + avgBitRate = 0, + sampleRate = sr, + } + return { + config = cfg, + encode = encode, + state = Encode.state(cfg), + bytes = 0, + frames = 0, + }, nil +end + +return Alac diff --git a/tests/audio/_encode_cases.luau b/tests/audio/_encode_cases.luau new file mode 100644 index 0000000..1e7bd23 --- /dev/null +++ b/tests/audio/_encode_cases.luau @@ -0,0 +1,12 @@ +-- tests/audio/_encode_cases: the files our ALAC / CAF writers produce for the reference check (tools/fixtures/m4a.py +-- runs tools/fixtures/_m4a_encode.luau over them; tests/audio/m4a.luau and caf.luau re-encode and compare). +return { + { name = "ours_alac16_stereo", container = "m4a", rate = 44100, frames = 4096 * 3 + 1234, channels = 2, bits = 16, seed = 1, tags = { title = "Our Title \u{e9}", artist = "formats-luau", album = "Tests", track = "5", tracktotal = "10", date = "2026", genre = "Test", comment = "round trip" } }, + { name = "ours_alac16_mono", container = "m4a", rate = 22050, frames = 5000, channels = 1, bits = 16, seed = 2 }, + { name = "ours_alac24_stereo", container = "m4a", rate = 48000, frames = 9000, channels = 2, bits = 24, seed = 3 }, + { name = "ours_alac16_6ch", container = "m4a", rate = 48000, frames = 4500, channels = 6, bits = 16, seed = 4 }, + { name = "ours_alac20_stereo", container = "m4a", rate = 96000, frames = 3000, channels = 2, bits = 20, seed = 5 }, + { name = "ours_caf_alac16", container = "caf", codec = "alac", rate = 44100, frames = 7000, channels = 2, bits = 16, seed = 6 }, + { name = "ours_caf_pcm16", container = "caf", codec = "pcm", rate = 44100, frames = 3000, channels = 2, bits = 16, seed = 7 }, + { name = "ours_caf_pcm24", container = "caf", codec = "pcm", rate = 48000, frames = 2000, channels = 1, bits = 24, seed = 8 }, +} diff --git a/tests/audio/_signal.luau b/tests/audio/_signal.luau new file mode 100644 index 0000000..4986a7e --- /dev/null +++ b/tests/audio/_signal.luau @@ -0,0 +1,42 @@ +-- tests/audio/_signal: the deterministic integer test signal of tools/fixtures/_m4a_signal.py (the same numbers), as +-- an interleaved integer array and as a Types.Audio (f32, exact for up to 24 bits). Used by the m4a / caf tests and the +-- fixture-time encoder runs (tools/fixtures/_m4a_encode.luau). +local Types = require("@formats/Types") + +local Signal = {} + +function Signal.ints(frames: number, channels: number, bits: number, seed: number): { number } + local s = seed + local peak = 2 ^ (bits - 1) - 1 + local out = table.create(frames * channels, 0) + local k = 1 + for i = 0, frames - 1 do + for c = 0, channels - 1 do + s = (s * 48271) % 2147483647 + local p1 = 97 + 31 * c + local tri = math.abs((i % p1) * 2 - p1) * 2 - p1 + local v = tri * (peak // (4 * p1)) + local p2 = 1500 + 200 * c + v += if (i // p2) % 2 == 0 then peak // 6 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3 then + v += peak // 2 + end + out[k] = math.clamp(v, -peak - 1, peak) + k += 1 + end + end + return out +end + +function Signal.audio(rate: number, frames: number, channels: number, bits: number, seed: number): Types.Audio + local ints = Signal.ints(frames, channels, bits, seed) + local a = Types.Audio.new(rate, channels, frames) + local scale = 1 / 2 ^ (bits - 1) + for i, v in ints do + buffer.writef32(a.samples, (i - 1) * 4, v * scale) + end + return a +end + +return Signal diff --git a/tests/audio/aac.luau b/tests/audio/aac.luau new file mode 100644 index 0000000..360d39a --- /dev/null +++ b/tests/audio/aac.luau @@ -0,0 +1,117 @@ +-- audio/aac tests: ADTS streams from ffmpeg and fdkaac (stereo, mono 32 kHz) against ffmpeg's float decode (SNR, +-- length); an HE-AAC ADTS stream plays its core; a leading ID3v2 tag (skipped, text frames as tags) and garbage before +-- the first frame (resync); a truncated last frame; streaming + seek; sniff; errors; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local AacF = require("@formats/audio/aac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +local function snr(a: any, ref: string, skip: number?): number + local off = (skip or 0) * a.channels + local n = math.min(a.frames * a.channels - off, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, (off + i) * 4) - r + sig += r * r + err += d * d + end + return if err == 0 then math.huge else 10 * math.log10(sig / err) +end + +t:eq(AacF.name, "aac", "name") +t:check(AacF.caps.decode and not AacF.caps.encode and AacF.encode == nil, "caps: decode only") + +local first +for _, c in Fx do + if c.container ~= "adts" then + continue + end + first = first or c + local r = reader(c.data) + t:check(AacF.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = AacF.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames (ADTS keeps the priming)") + local s = snr(a, c.ref) + t:check(s > 90, string.format("%s: SNR %.1f dB", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC ADTS: the core +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local a, err = AacF.decode(reader(c.data)) + t:check(a and a.sampleRate == c.rate // 2 and a.frames > 0, c.name .. ": core decode: " .. tostring(err)) + end +end + +-- ID3v2 in front + garbage, truncated tail +do + local function frame(id: string, text: string): string + local body = "\3" .. text + local n = #body + return id .. string.char(0, 0, n // 128, n % 128) .. "\0\0" .. body + end + local frames = frame("TIT2", "Adts Title") .. frame("TPE1", "Someone") + local n = #frames + local id3 = "ID3\4\0\0" .. string.char(0, 0, n // 128, n % 128) .. frames + local data = id3 .. "\0\1\2garbage" .. first.data + local a, err = AacF.decode(reader(data)) + t:check(a, "id3 + garbage: " .. tostring(err)) + t:check(a.tags.title == "Adts Title" and a.tags.artist == "Someone", "id3 tags") + t:eq(a.frames, first.frames, "id3 + garbage: same frames") + t:check(snr(a, first.ref) > 90, "id3 + garbage: same audio") + local cut = AacF.decode(reader(string.sub(first.data, 1, #first.data - 5))) :: any + t:check(cut and cut.frames == first.frames - 1024, "truncated last frame dropped") +end + +-- streaming + seek +do + local whole = AacF.decode(reader(first.data)) :: any + local dec = AacF.open(reader(first.data)) :: any + for _, at in { 0.3, 0.0, 0.5123 } do + dec:seek(at) + local b, n = dec:read(600) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + -- (the stream has no PNS: noise substitution would draw different noise after a seek) + t:check(n == 600 and maxd < 1e-6, string.format("seek %.3f s (max diff %g)", at, maxd)) + end +end + +-- errors +do + t:eq(AacF.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = AacF.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + if c.container == "adts" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + t:fuzz("decode", function(b: buffer) + return AacF.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/caf.luau b/tests/audio/caf.luau new file mode 100644 index 0000000..c0f40ff --- /dev/null +++ b/tests/audio/caf.luau @@ -0,0 +1,177 @@ +-- audio/caf tests: ALAC CAF from ffmpeg bit-exact; AAC CAF (ffmpeg's ADTS frames wrapped by the fixture) against +-- ffmpeg's float decode; our CAF writer (PCM 16 / 24-bit, ALAC; re-encoded here and compared with the bytes ffmpeg +-- decoded bit-exactly); PCM layouts (little / big endian, float) through our writer + a hand-built header; info tags; +-- seek; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Caf = require("@formats/audio/caf") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("caf") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +t:eq(Caf.name, "caf", "name") +t:check(Caf.caps.decode and Caf.caps.encode, "caps") + +for _, c in Alac do + if c.container == "caf" then + local r = reader(c.data) + t:eq(Caf.sniff(r), 1, c.name .. ": sniff") + local a, err = Caf.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate and a.frames == c.frames, c.name .. ": format / length (pakt)") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": bit-exact") + end +end + +for _, c in Aac do + if c.container == "caf" then + local a, err = Caf.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local rb = buffer.fromstring(c.ref) + local sig, e = 0, 0 + for i = 0, a.frames * a.channels - 1 do + local r = buffer.readf32(rb, i * 4) + sig += r * r + e += (buffer.readf32(a.samples, i * 4) - r) ^ 2 + end + local snr = if e == 0 then math.huge else 10 * math.log10(sig / e) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: SNR %.1f dB vs ffmpeg", c.name, snr) + end +end + +-- our writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "caf" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg, c.name .. ": ffmpeg decoded it bit-exactly") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + local file = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) :: buffer + t:eq(string.format("%08x", Crc32.of(file)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + local back = Caf.decode(reader(file)) :: any + t:check(back and back.frames == c.frames, c.name .. ": our length") + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = true + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + end +end + +-- float PCM, tags, a decoder as the source, a hand-built little-endian header +do + local a = Signal.audio(32000, 3000, 3, 16, 12) + a.tags = { title = "Caf Title", artist = "A", date = "1999", comment = "c", custom = "x" } + local file = Caf.encode(a, { codec = "pcm", bitDepth = 32 }) :: buffer + local back = Caf.decode(reader(file)) :: any + t:check(back.frames == 3000 and buffer.tostring(back.samples) == buffer.tostring(a.samples), "float PCM round trip") + for k, v in a.tags do + t:eq(back.tags[k], v, "tag " .. k) + end + local dec = Caf.open(reader(file)) :: any + local again = Caf.encode(dec, { codec = "alac" }) :: buffer + local b2 = Caf.decode(reader(again)) :: any + t:check(b2.frames == 3000 and buffer.tostring(b2.samples) == buffer.tostring(a.samples), "ALAC from a streaming decoder") + -- little-endian 24-bit integer PCM, data chunk of unknown size (-1) + local w = Bytes.writer(64) + w:string("caff") + w:u16be(1) + w:u16be(0) + w:string("desc") + w:u64be(32) + w:f64be(8000) + w:string("lpcm") + w:u32be(2) + w:u32be(3) + w:u32be(1) + w:u32be(1) + w:u32be(24) + w:string("data") + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + w:u32be(0) + for _, v in { 0, 4194304, -4194304, 8388607, -8388608 } do + w:u24le(v % 16777216) + end + local le = Caf.decode(Bytes.reader(w:finish())) :: any + t:check(le and le.frames == 5, "24-bit LE, data size -1") + t:check(le and math.abs(buffer.readf32(le.samples, 4) - 0.5) < 1e-7 and math.abs(buffer.readf32(le.samples, 16) + 1) < 1e-7, "24-bit LE values") +end + +-- seek +do + local c = Alac[#Alac] + local whole = Caf.decode(reader(c.data)) :: any + local dec = Caf.open(reader(c.data)) :: any + for _, at in { 0.1, 0.0, 0.15 } do + dec:seek(at) + local b, n = dec:read(400) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local same = n == 400 + for i = 0, n * whole.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4) + end + t:check(same, string.format("seek %.2f s", at)) + end +end + +-- errors +do + t:eq(Caf.sniff(reader("caff\0\2\0\0")), 0, "sniff: wrong version") + local _, e = Caf.decode(reader("caff\0\1\0\0")) + t:check(e and e.code == Err.CORRUPT, "no desc: " .. tostring(e)) + local _, e2 = Caf.encode(Signal.audio(8000, 10, 1, 16, 1), { codec = "mp3" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad codec: " .. tostring(e2)) +end + +-- fuzz +do + local samples = {} + for _, c in Alac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + for _, c in Aac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + local pcm = Caf.encode(Signal.audio(8000, 300, 2, 16, 3), { codec = "pcm" }) :: buffer + table.insert(samples, buffer.tostring(pcm)) + t:fuzz("decode", function(b: buffer) + return Caf.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/m4a.luau b/tests/audio/m4a.luau new file mode 100644 index 0000000..273f71e --- /dev/null +++ b/tests/audio/m4a.luau @@ -0,0 +1,218 @@ +-- audio/m4a tests: ALAC files from ffmpeg decode bit-exactly (16 / 24-bit, mono / stereo / 5.1, partial frames); +-- AAC-LC files from ffmpeg and fdkaac (stereo / mono / 5.1, 8 - 96 kHz, PNS / intensity / M/S / TNS) against ffmpeg's +-- float decode (SNR, gapless length through the edit list); HE-AAC / HE-AACv2 play their core; our ALAC writer +-- (re-encoded here, compared with the bytes ffmpeg decoded bit-exactly and MP4Box accepted in the fixture step); tags +-- and cover art round trips; streaming reads, seeking; the contract; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local M4a = require("@formats/audio/m4a") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("m4a") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +-- the integers of a decoded Audio (exact for <= 24-bit sources), CRC-32 as little-endian int32 +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +local function snr(a: any, ref: string): (number, number) + local n = math.min(a.frames * a.channels, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, i * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge, n + end + return 10 * math.log10(sig / err), n +end + +-- the contract +t:eq(M4a.name, "m4a", "name") +t:eq(M4a.category, "audio", "category") +t:check(M4a.caps.decode and M4a.caps.encode, "caps") + +-- ALAC from ffmpeg: bit-exact +for _, c in Alac do + if c.container ~= "m4a" then + continue + end + local r = reader(c.data) + t:check(M4a.sniff(r) == 1, c.name .. ": sniff") + local a, err = M4a.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": samples bit-exact") + t:eq(a.meta.source.codec, "alac", c.name .. ": codec") +end +t:note("%d ffmpeg ALAC files decode bit-exactly", #Alac - 1) + +-- AAC: against ffmpeg's float decode +local worst = math.huge +for _, c in Aac do + if c.container ~= "m4a" then + continue + end + local a, err = M4a.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": gapless length") + local s = snr(a, c.ref) + worst = math.min(worst, s) + t:check(s > 90, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC: the AAC-LC core at half the rate, SBR seen +for _, c in He do + if string.sub(c.name, -4) ~= ".m4a" then + continue + end + local dec, err = M4a.open(reader(c.data)) + t:check(dec, c.name .. ": " .. tostring(err)) + t:eq(dec.sampleRate, c.rate // 2, c.name .. ": core rate") + local b, n = dec:read(8192) + local e = 0 + for i = 0, n * dec.channels - 1 do + e += buffer.readf32(b, i * 4) ^ 2 + end + t:check(n == 8192 and e > 1, c.name .. ": the core decodes (energy " .. e .. ")") +end + +-- our ALAC writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "m4a" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg and o.mp4box and o.codec == "alac", c.name .. ": ffmpeg decoded it bit-exactly, MP4Box read it") + t:eq(o.frames, c.frames, c.name .. ": ffmpeg's length") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local file, err = M4a.encode(a, { bitDepth = c.bits }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + -- and our own decoder gets the integers back + local back = M4a.decode(Bytes.reader(file :: buffer)) :: any + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = back.frames == c.frames + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints, 7 do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + if c.tags then + for k, v in c.tags do + t:eq(back.tags[k], v, c.name .. ": tag " .. k) + end + t:eq(o.tags.title, c.tags.title, c.name .. ": ffprobe title") + t:eq(o.tags.track, c.tags.track .. "/" .. c.tags.tracktotal, c.name .. ": ffprobe track") + t:eq(o.tags.artist, c.tags.artist, c.name .. ": ffprobe artist") + end + t:note("%s: %d bytes (%.0f%% of PCM)", c.name, buffer.len(file :: buffer), 100 * buffer.len(file :: buffer) / (c.frames * c.channels * c.bits / 8)) + end +end + +-- cover art + streaming a decoder into the encoder +do + local a = Signal.audio(44100, 5000, 2, 16, 9) + a.meta.pictures = { { mime = "image/png", data = buffer.fromstring("\137PNG fake") } } + a.tags = { title = "Pic" } + local file = M4a.encode(a) :: buffer + local back = M4a.decode(Bytes.reader(file)) :: any + t:check(back.meta.pictures and #back.meta.pictures == 1 and back.meta.pictures[1].mime == "image/png", "cover art round trip") + local dec = M4a.open(Bytes.reader(file)) :: any + local again = M4a.encode(dec) :: buffer + local back2 = M4a.decode(Bytes.reader(again)) :: any + t:check(back2.frames == 5000 and buffer.tostring(back2.samples) == buffer.tostring(back.samples), "encode from a streaming decoder") + local _, e = M4a.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-audio returns Err.ARG") + local _, e2 = M4a.encode(a, { bitDepth = 12 }) + t:check(e2 and e2.code == Err.ARG, "bad bitDepth returns Err.ARG") +end + +-- streaming + seek (AAC without PNS: its noise is random, so a seek changes it; and ALAC) +for _, c in { Aac[1], Alac[1] } do + local whole = M4a.decode(reader(c.data)) :: any + local dec = M4a.open(reader(c.data)) :: any + t:eq(dec.frames, whole.frames, c.name .. ": decoder frames") + -- read in odd chunks + local got, out = 0, buffer.create(whole.frames * whole.channels * 4) + while true do + local b, n = dec:read(777) + if n == 0 then + break + end + buffer.copy(out, got * whole.channels * 4, b, 0, n * whole.channels * 4) + got += n + end + t:check(got == whole.frames and buffer.tostring(out) == buffer.tostring(whole.samples), c.name .. ": chunked reads equal the whole decode") + for _, at in { 0.1, 0.0, 0.05 } do + dec:seek(at) + local b, n = dec:read(500) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + t:check(n == 500 and maxd < 1e-6, string.format("%s: seek %.2f s (max diff %g)", c.name, at, maxd)) + t:check(math.abs(dec:position() - (f0 + 500) / whole.sampleRate) < 1e-9, c.name .. ": position after seek") + end +end + +-- errors +do + local _, e = M4a.decode(reader("\0\0\0\8ftypM4A ")) + t:check(e ~= nil, "a lone ftyp: " .. tostring(e)) + local _, e2 = M4a.decode(reader("hello world, not an mp4")) + t:check(e2 ~= nil and Err.is(e2), "junk: " .. tostring(e2)) + t:eq(M4a.sniff(reader("hello")), 0, "sniff junk") +end + +-- fuzz +do + local samples = {} + for i, c in Alac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 12000)) + end + end + for i, c in Aac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + t:fuzz("decode", function(b: buffer) + return M4a.decode(Bytes.reader(b)) + end, samples, { mutations = 25 }) +end + +t:done() diff --git a/tests/codecs/aac.luau b/tests/codecs/aac.luau new file mode 100644 index 0000000..b340bd4 --- /dev/null +++ b/tests/codecs/aac.luau @@ -0,0 +1,182 @@ +-- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac, +-- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded +-- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors, +-- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Aac = require("@formats/codecs/Aac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Bits = require("@formats/core/Bits") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac-codec") + +-- ADTS frames of a stream: { offset, size } of the raw blocks +local function frames(data: buffer): ({ { number } }, Aac.Adts?) + local out, p, first = {}, 0, nil + while true do + local h = Aac.adts(data, p, buffer.len(data)) + if not h or p + h.frameSize > buffer.len(data) then + break + end + first = first or h + table.insert(out, { p + h.headerSize, h.frameSize - h.headerSize }) + p += h.frameSize + end + return out, first +end + +-- ASCs from the M4A fixtures +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.objectType == 2 and cfg.sampleRate == c.rate and cfg.channels == c.channels and not cfg.sbr, c.name .. ": AAC-LC config") + end +end +for _, c in He do + if string.sub(c.name, -4) == ".m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.sbr and cfg.sampleRate == c.rate // 2 and cfg.extensionRate == c.rate, c.name .. ": SBR signalled, core at half rate") + t:eq(cfg.ps, c.ps, c.name .. ": PS signalled") + end +end + +-- crafted configs +do + local asc = Aac.asc(2, 4, 2) + local cfg = Aac.config(asc) :: Aac.Config + t:check(cfg and cfg.sampleRate == 44100 and cfg.channels == 2, "asc(2, 44.1 kHz, stereo)") + local _, e1 = Aac.config(Aac.asc(1, 4, 2)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "AAC Main: " .. tostring(e1)) + local _, e2 = Aac.config(Aac.asc(23, 4, 2)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ER AAC LD") + local b960 = Aac.asc(2, 3, 1) + buffer.writeu8(b960, 1, bit32.bor(buffer.readu8(b960, 1), 4)) -- frameLengthFlag + local _, e3 = Aac.config(b960) + t:check(e3 and e3.code == Err.UNSUPPORTED, "960-sample frames") + -- channel configuration 0 with a PCE: front C (SCE) + L/R (CPE), back L/R (CPE), one LFE = 6 channels + local bw = Bits.msbWriter() + bw:write(2, 5) + bw:write(3, 4) + bw:write(0, 4) + bw:write(0, 3) -- GASpecificConfig flags + bw:write(0, 4) -- PCE: tag + bw:write(1, 2) + bw:write(3, 4) + bw:write(2, 4) -- front + bw:write(0, 4) -- side + bw:write(1, 4) -- back + bw:write(1, 2) -- lfe + bw:write(0, 3) + bw:write(0, 4) + bw:write(0, 3) -- mixdowns + bw:write(0, 5) + bw:write(16 + 1, 5) -- front: SCE 0, CPE 1 + bw:write(16 + 2, 5) -- back: CPE 2 + bw:write(0, 4) -- lfe tag + bw:align() + bw:write(0, 8) -- comment + local pcfg, perr = Aac.config(bw:finish()) + t:check(pcfg and pcfg.channels == 6 and pcfg.channelConfig == 0, "PCE: 6 channels: " .. tostring(perr)) + local _, e4 = Aac.decoder("nope" :: any) + t:check(e4 and e4.code == Err.ARG, "decoder of a string") +end + +-- ADTS headers + raw frames against ffmpeg +for _, c in Fx do + if c.container ~= "adts" then + continue + end + local data = buffer.fromstring(c.data) + local list, h = frames(data) + t:check(h and h.objectType == 2 and h.sampleRate == c.rate, c.name .. ": ADTS header") + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + local ref = buffer.fromstring(c.ref) + local sig, err = 0, 0 + local o = 0 + for _, f in list do + local n, e = dec:decode(data, f[1], f[2]) + t:check(n == 1024, c.name .. ": frame: " .. tostring(e)) + for k = 1, 1024 * c.channels do + local r = buffer.readf32(ref, o) + sig += r * r + err += (dec.pcm[k] - r) ^ 2 + o += 4 + end + end + local snr = 10 * math.log10(sig / math.max(err, 1e-30)) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: %d raw frames, SNR %.1f dB vs ffmpeg", c.name, #list, snr) + -- reset: decoding again from the start gives the same first frames + dec:reset() + dec:decode(data, list[1][1], list[1][2]) + local again = table.clone(dec.pcm) + local dec2 = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + dec2:decode(data, list[1][1], list[1][2]) + local same = true + for k = 1, 1024 * c.channels do + same = same and again[k] == dec2.pcm[k] + end + t:check(same, c.name .. ": reset clears the overlap") +end + +-- the extension hook on HE-AAC (implicit SBR in ADTS) +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = 2 }) :: Aac.Decoder + local seen, bits = 0, 0 + dec.onExtension = function(kind: number, _element: number, _buf: buffer, _pos: number, n: number) + if kind == 13 or kind == 14 then + seen += 1 + bits += n + end + end + for _, f in list do + dec:decode(data, f[1], f[2]) + end + t:check(seen == #list and dec.sbr, string.format("%s: an SBR payload per frame (%d of %d, %d bits)", c.name, seen, #list, bits)) + end +end + +-- errors +do + local dec = Aac.decoder(Aac.asc(2, 4, 2)) :: Aac.Decoder + local _, e = dec:decode(buffer.fromstring("\x20\x00\x00\x00\x00")) + t:check(e and e.code == Err.CORRUPT, "garbage frame: " .. tostring(e)) + local _, e2 = dec:decode(buffer.create(4), 3, 10) + t:check(e2 and e2.code == Err.ARG, "range out of the buffer") + t:check(Aac.adts(buffer.fromstring("\255\241"), 0, 2) == nil, "short ADTS header") +end + +-- fuzz raw frames (stereo with every tool, mono, 5.1) +do + local pick = {} + for _, c in Fx do + if c.container == "adts" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local f = list[math.min(#list, 9)] + local raw = buffer.create(f[2]) + buffer.copy(raw, 0, data, f[1], f[2]) + table.insert(pick, { raw, (h :: Aac.Adts).sfIndex, c.channels }) + end + end + for _, p in pick do + local dec = Aac.decoder({ sfIndex = p[2], channels = p[3] }) :: Aac.Decoder + t:fuzz("raw frame " .. p[3] .. " ch", function(b: buffer) + return dec:decode(b) + end, { p[1] }, { mutations = 60, garbage = 100 }) + end +end + +t:done() diff --git a/tests/codecs/alac.luau b/tests/codecs/alac.luau new file mode 100644 index 0000000..8dff395 --- /dev/null +++ b/tests/codecs/alac.luau @@ -0,0 +1,181 @@ +-- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames), +-- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC +-- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms, +-- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Alac = require("@formats/codecs/Alac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_alac") + +local t = T.suite("alac") +local rand = T.rng(42) + +local function roundTrip(label: string, ch: number, bits: number, frames: number, gen: (number, number) -> number, fl: number?) + local enc = Alac.encoder({ sampleRate = 44100, channels = ch, bitDepth = bits, frameLength = fl }) :: Alac.Encoder + t:check(enc, label .. ": encoder") + local per = enc.config.frameLength + local src = table.create(frames * ch, 0) + for i = 0, frames - 1 do + for c = 1, ch do + src[i * ch + c] = gen(i, c) + end + end + local packets = {} + local bytes = 0 + local f = 0 + while f < frames do + local n = math.min(per, frames - f) + local p, err = enc:encode(src, f * ch + 1, n) + t:check(p, label .. ": encode: " .. tostring(err)) + table.insert(packets, { p, n }) + bytes += buffer.len(p :: buffer) + f += n + end + local cfg = Alac.config(Alac.cookie(enc.config)) :: Alac.Config + t:check(cfg and cfg.maxFrameBytes >= 1 and cfg.channels == ch and cfg.bitDepth == bits, label .. ": cookie") + local dec = Alac.decoder(cfg) + local ok = true + local at = 0 + for _, pk in packets do + local n, err = dec:decode(pk[1]) + if n ~= pk[2] then + ok = false + t:check(false, label .. ": decode: " .. tostring(err)) + break + end + for k = 1, n * ch do + if dec.pcm[k] ~= src[at * ch + k] then + ok = false + end + end + at += n + end + t:check(ok, label .. ": round trip") + return bytes / (frames * ch * bits / 8) +end + +local peakOf = function(bits: number): number + return 2 ^ (bits - 1) +end + +for _, bits in { 16, 20, 24 } do + local pk = peakOf(bits) + for _, ch in { 1, 2, 3, 6, 8 } do + local r1 = roundTrip(string.format("tone %d-bit %d ch", bits, ch), ch, bits, 9000, function(i, c) + return math.floor(math.sin(i * 0.031 * c) * (pk * 0.6) + math.sin(i * 0.0071) * pk * 0.2) + end) + if ch == 2 then + t:note("%d-bit stereo tone: %.0f%% of PCM", bits, r1 * 100) + end + end + roundTrip(bits .. "-bit silence (zero runs)", 2, bits, 10000, function() + return 0 + end) + local r = roundTrip(bits .. "-bit full-scale noise (escape frames)", 2, bits, 5000, function() + return rand(2 ^ bits) - pk + end) + t:check(r < 1.01, bits .. "-bit noise stays near PCM size") + roundTrip(bits .. "-bit extremes", 1, bits, 600, function(i) + return if i % 2 == 0 then pk - 1 else -pk + end) + roundTrip(bits .. "-bit sparse clicks (zero runs + values)", 2, bits, 7000, function(i, c) + return if i % 997 == c then pk // 3 else 0 + end) +end +for _, n in { 1, 2, 3, 5, 9, 17, 4095 } do + roundTrip("partial frame of " .. n, 2, 16, n, function(i, c) + return (i * 37 + c * 1000) % 3000 - 1500 + end) +end +roundTrip("frame length 1024", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.05) * 10000) +end, 1024) +roundTrip("identical channels", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.02) * 20000) +end) + +-- ffmpeg's packets +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tr = movie.tracks[1] + local cfg = Alac.config(tr.config :: buffer) :: Alac.Config + t:check(cfg and cfg.bitDepth == c.bits and cfg.channels == c.channels, c.name .. ": cookie") + local dec = Alac.decoder(cfg) + local out = buffer.create(c.frames * c.channels * 4) + local o = 0 + for i = 1, tr.sampleCount do + local n, err = dec:decode(r.buf, tr.offsets[i], tr.sizes[i]) + t:check(n, c.name .. ": packet " .. i .. ": " .. tostring(err)) + for k = 1, (n :: number) * c.channels do + buffer.writei32(out, o, dec.pcm[k]) + o += 4 + end + end + t:eq(Crc32.of(out), c.crc, c.name .. ": ffmpeg's packets decode to the source") + end +end + +-- the cookie behind QuickTime atoms, bad cookies +do + local enc = Alac.encoder({ sampleRate = 48000, channels = 2 }) :: Alac.Encoder + local plain = Alac.cookie(enc.config) + local w = Bytes.writer(64) + w:u32be(12) + w:string("frma") + w:string("alac") + w:u32be(36) + w:string("alac") + w:u32be(0) + w:bytes(plain) + local cfg = Alac.config(w:finish()) + t:check(cfg and cfg.sampleRate == 48000 and cfg.frameLength == 4096, "cookie behind frma / alac atoms") + local bad = buffer.fromstring(buffer.tostring(plain)) + buffer.writeu8(bad, 5, 12) + local _, e = Alac.config(bad) + t:check(e and e.code == Err.UNSUPPORTED, "12-bit cookie: " .. tostring(e)) + local _, e2 = Alac.config(buffer.create(10)) + t:check(e2 and e2.code == Err.TRUNCATED, "short cookie") + local _, e3 = Alac.encoder({ sampleRate = 44100, channels = 9 }) + t:check(e3 and e3.code == Err.ARG, "9 channels") + local _, e4 = enc:encode({ 1, 2 }, 1, 5) + t:check(e4 and e4.code == Err.ARG, "too few samples") + local dec = Alac.decoder(cfg :: Alac.Config) + local _, e5 = dec:decode(buffer.fromstring("\1\255\255\255")) + t:check(e5 and e5.code == Err.CORRUPT, "bad packet: " .. tostring(e5)) +end + +-- fuzz the packet decoder +do + local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) :: Alac.Encoder + local src = table.create(2 * 3000, 0) + for i = 1, #src do + src[i] = math.floor(math.sin(i * 0.01) * 8000) + rand(64) + end + local samples = {} + table.insert(samples, (enc:encode(src, 1, 3000))) + for i = 1, #src do + src[i] = if i % 300 < 3 then 5000 else 0 + end + table.insert(samples, (enc:encode(src, 1, 3000))) + local dec = Alac.decoder(enc.config) + local enc24 = Alac.encoder({ sampleRate = 44100, channels = 1, bitDepth = 24 }) :: Alac.Encoder + local dec24 = Alac.decoder(enc24.config) + local s24 = table.create(2000, 0) + for i = 1, 2000 do + s24[i] = rand(2 ^ 24) - 2 ^ 23 + end + local p24 = enc24:encode(s24, 1, 2000) :: buffer + t:fuzz("decode packet", function(b: buffer) + return dec:decode(b) + end, samples, { mutations = 40 }) + t:fuzz("decode 24-bit escape packet", function(b: buffer) + return dec24:decode(b) + end, { p24 }, { mutations = 20, garbage = 50 }) +end + +t:done() diff --git a/tools/fixtures/_m4a_encode.luau b/tools/fixtures/_m4a_encode.luau new file mode 100644 index 0000000..8a42eb5 --- /dev/null +++ b/tools/fixtures/_m4a_encode.luau @@ -0,0 +1,31 @@ +-- tools/fixtures/_m4a_encode: run by tools/fixtures/m4a.py (luau, from the repo root) so the reference tools can check +-- our writers: encodes the test signal (tests/audio/_signal) to ALAC M4A (audio/m4a) and ALAC / PCM CAF (audio/caf) +-- and prints " " lines. The tests re-encode and compare the CRC with the file ffmpeg validated. +local Signal = require("@tests/audio/_signal") +local M4a = require("@formats/audio/m4a") +local Caf = require("@formats/audio/caf") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local Cases = require("@tests/audio/_encode_cases") +for _, c in Cases do + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local out, err + if c.container == "caf" then + out, err = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) + else + out, err = M4a.encode(a, { bitDepth = c.bits }) + end + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + print(c.name .. " " .. hex(out)) + end +end diff --git a/tools/fixtures/_m4a_signal.py b/tools/fixtures/_m4a_signal.py new file mode 100644 index 0000000..7eb72ed --- /dev/null +++ b/tools/fixtures/_m4a_signal.py @@ -0,0 +1,41 @@ +# The deterministic integer test signal shared by tools/fixtures/m4a.py, tools/fixtures/caf.py and the Luau side +# (tests/audio/_signal.luau computes the same numbers): triangle + square + MINSTD noise (exact in doubles) + clicks, per channel. +import struct + + +def signal(frames, channels, bits, seed): + s = seed + peak = 2 ** (bits - 1) - 1 + out = [] + for i in range(frames): + for c in range(channels): + s = (s * 48271) % 2147483647 + p1 = 97 + 31 * c + tri = abs((i % p1) * 2 - p1) * 2 - p1 + v = tri * (peak // (4 * p1)) + p2 = 1500 + 200 * c + v += (peak // 6) if (i // p2) % 2 == 0 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3: + v += peak // 2 + out.append(max(-peak - 1, min(peak, v))) + return out + + +def pack(samples, bits, big=False): + e = ">" if big else "<" + if bits == 16: + return struct.pack(e + "%dh" % len(samples), *samples) + if bits == 24: + b = bytearray() + for v in samples: + x = struct.pack("> 5) + frames.append(adts[p + hs:p + size]) + sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1 + p += size + rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi] + asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3)) + dsi = b"\x05" + bytes([len(asc)]) + asc + dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi + esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02" + + def ber(n): + out = [n & 127] + n >>= 7 + while n: + out.insert(0, 128 | (n & 127)) + n >>= 7 + return bytes(out) + + def chunk(t, body): + return t + struct.pack(">q", len(body)) + body + + desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0) + pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames) + data = b"\x00\x00\x00\x00" + b"".join(frames) + return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="m4a-fx-") + try: + # --- ALAC from ffmpeg: lossless, the decode must equal the source integers + alac = [] + for name, frames, ch, rate, bits, container in ( + ("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"), + ("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"), + ("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"), + ("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"), + ("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"), + ): + ints = signal(frames, ch, bits, 11 + frames) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, bits)) + fmt = "-sample_fmt s32p" if bits == 24 else "" + run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "bits": bits, "frames": frames, "crc": crc_ints(ints)}) + ctx.emit("m4a_alac", alac) + + # --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode + aac = [] + specs = ( + # name, frames, channels, rate, encoder command (in.wav -> name) + ("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"), + ("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"), + ("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"), + ("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"), + ("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"), + ("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"), + ("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"), + ("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"), + ("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"), + ("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"), + ("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"), + ) + for name, frames, ch, rate, cmd in specs: + ints = music(frames, ch, rate, frames + ch) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, cmd % name, d) + if name.endswith(".caf"): + # ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data) + with open(os.path.join(d, name + ".adts"), "rb") as f: + adts = f.read() + with open(os.path.join(d, name), "wb") as f: + f.write(adts_to_caf(adts)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d) + container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a") + aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "frames": len(ref) // (4 * ch), "ref": ref}) + ctx.emit("m4a_aac", aac) + # HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate + he = [] + for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)): + ints = music(frames, ch, rate, 99) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d) + with open(os.path.join(d, name), "rb") as f: + he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29}) + ctx.emit("m4a_he", he) + + # --- our writers, checked by ffmpeg / ffprobe / MP4Box + luau = os.environ.get("LUAU") or shutil.which("luau") + if luau: + out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")]) + ours = [] + meta = { + # name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau) + "ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2), + "ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4), + "ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6), + "ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8), + } + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + ext = "caf" if "caf" in name else "m4a" + path = name + "." + ext + with open(os.path.join(d, path), "wb") as f: + f.write(data) + frames, ch, bits, seed = meta[name] + ints = signal(frames, ch, bits, seed) + wide = bits > 16 + want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16) + got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d) + fbytes = (4 if wide else 2) * ch + # ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files): + # accept its output when it is an exact prefix of ours + ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got)) + probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d)) + tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()} + mp4box = True + if ext == "m4a": + try: + run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d) + except subprocess.CalledProcessError: + mp4box = False + ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes, + "tags": tags, "mp4box": mp4box, + "codec": probe["streams"][0]["codec_name"]}) + ctx.emit("m4a_ours", ours) + finally: + shutil.rmtree(d, ignore_errors=True)