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

This commit is contained in:
4DBug committed 2026-10-31 09:03:04 -05:00
1 parent 064af84d63
commit 83d43f6c6d
22 files changed
+5380

No files matched your search

+277
View File
@@ -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
+746
View File
@@ -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
+439
View File
@@ -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 <priming> <padding> <samples> ..." (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