Files
rosetta/src/Formats/audio/aiff/init.luau
T
4DBug 2717292366 ws-audio2: AIFF-C and CAF ima4 (Apple IMA ADPCM) decode through codecs/audio/Adpcm
aiff: COMM counts ima4 packets; caf: ima4 through Adpcm/Decoder.blocks (exact seeking), and a constant-size
packet stream whose pakt lists no packets now uses bytesPerPacket (was 0 frames). Bit-exact with ffmpeg.
2026-10-31 14:34:28 -05:00

401 lines
13 KiB
Luau

--!strict
-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs.
-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw
-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated
-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 /
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm;
-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6,
-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Chunks = require("@formats/containers/Chunks")
local Pcm = require("@formats/codecs/audio/Pcm")
local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Aiff = {
name = "aiff",
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only
-- take 16-bit sowt, so other formats return Err.ARG)
aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it)
}
-- ------------------------------------------------------------------------------------------------ constants
local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" }
local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } }
local AIFC_VERSION = 0xA2805140
-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian)
local function ext80(b: buffer, o: number): number
local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
local hi = bit32.byteswap(buffer.readu32(b, o + 2))
local lo = bit32.byteswap(buffer.readu32(b, o + 6))
local e = bit32.band(se, 0x7FFF)
if e == 0 and hi == 0 and lo == 0 then
return 0
end
if e == 0x7FFF then
return math.huge
end
local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63)
return if se >= 0x8000 then -v else v
end
-- the 10 bytes of x (> 0) as an 80-bit extended float
local function writeExt80(w: Bytes.Writer, x: number)
if x <= 0 or x ~= x then
w:fill(0, 10)
return
end
local e = 0
while x >= 2 ^ (e + 1) do
e += 1
end
while x < 2 ^ e do
e -= 1
end
local m = x * 2 ^ (63 - e) -- in [2^63, 2^64)
local hi = math.floor(m / 4294967296)
local lo = m - hi * 4294967296
w:u16be(e + 16383)
w:u32be(hi)
w:u32be(math.floor(lo))
end
-- the sample format of a COMM chunk: Pcm format name | nil, message
local function sampleFormat(comp: string, bits: number): (string?, string?)
if comp == "NONE" or comp == "twos" or comp == "" then
if bits >= 1 and bits <= 8 then
return "s8", nil
elseif bits <= 16 then
return "s16be", nil
elseif bits <= 24 then
return "s24be", nil
elseif bits <= 32 then
return "s32be", nil
end
return nil, "bad sample size " .. bits
elseif comp == "sowt" then
if bits >= 1 and bits <= 8 then
return "s8", nil
elseif bits <= 16 then
return "s16le", nil
elseif bits <= 24 then
return "s24le", nil
elseif bits <= 32 then
return "s32le", nil
end
return nil, "bad sample size " .. bits
elseif comp == "raw " then
return "u8", nil
elseif comp == "in24" then
return "s24be", nil
elseif comp == "in32" then
return "s32be", nil
elseif comp == "42ni" then
return "s32le", nil
elseif comp == "fl32" or comp == "FL32" then
return "f32be", nil
elseif comp == "fl64" or comp == "FL64" then
return "f64be", nil
elseif comp == "ulaw" or comp == "ULAW" then
return "ulaw", nil
elseif comp == "alaw" or comp == "ALAW" then
return "alaw", nil
elseif comp == "ima4" then
return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks
end
return nil, "compression " .. string.format("%q", comp)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Aiff.sniff(r: Bytes.Reader): number
if r:remaining() < 12 or r:peek(4) ~= "FORM" then
return 0
end
local form = buffer.readstring(r.buf, r.pos + 8, 4)
return if form == "AIFF" or form == "AIFC" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Info = {
channels: number,
frames: number,
sampleRate: number,
bits: number,
format: string,
compression: string,
aifc: boolean,
dataOffset: number, -- absolute in r.buf
dataSize: number, -- bytes of sample data present
truncated: boolean,
tags: Types.Tags,
}
-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples)
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local b = r.buf
local base, limit = r.base, r.limit
if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then
return nil, Err.new(Err.CORRUPT, "not a FORM file", base)
end
local form = buffer.readstring(b, base + 8, 4)
if form ~= "AIFF" and form ~= "AIFC" then
return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8)
end
local aifc = form == "AIFC"
local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4)))
local info: Info? = nil
local comm = false
local ssnd: number? = nil
local ssndLen = 0
local tags: Types.Tags = {}
-- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body)
for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do
local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start
if p + 8 > formEnd then
break
end
if id == "COMM" then
if avail < 18 or (aifc and avail < 22) then
return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p)
end
local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1)
local frames = bit32.byteswap(buffer.readu32(b, d + 2))
local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7)
local rate = ext80(b, d + 8)
local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE"
if ch < 1 then
return nil, Err.new(Err.CORRUPT, "no channels", d)
end
if not (rate > 0 and rate < 2 ^ 31) then
return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8)
end
local fmt, why = sampleFormat(comp, bits)
if not fmt then
return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18)
end
info = {
channels = ch,
frames = frames,
sampleRate = rate,
bits = bits,
format = fmt,
compression = comp,
aifc = aifc,
dataOffset = 0,
dataSize = 0,
truncated = false,
tags = tags,
}
comm = true
elseif id == "SSND" then
if avail < 8 then
return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p)
end
local off = bit32.byteswap(buffer.readu32(b, d))
ssnd = d + 8 + off
ssndLen = math.max(0, avail - 8 - off)
if len >= 8 + off then
ssndLen = math.min(ssndLen, len - 8 - off)
end
elseif TEXT_TAGS[id] then
local s = buffer.readstring(b, d, avail)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
local key = TEXT_TAGS[id]
tags[key] = if tags[key] then tags[key] .. "\n" .. s else s
end
if len > formEnd - d then
break
end
end
if not comm or not info then
return nil, Err.new(Err.CORRUPT, "no COMM chunk", base)
end
local fi = info :: Info
if fi.frames > 0 and not ssnd then
return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base)
end
local present
if fi.format == "ima4" then
fi.frames *= 64 -- COMM counts packets
present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0
else
present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0
end
if present < fi.frames then
fi.frames = present
fi.truncated = true
end
fi.dataOffset = ssnd or base
fi.dataSize = ssndLen
return fi, nil
end
-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err
function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?)
return parse(r)
end
function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Aiff.open(r, opts)
if not dec then
return nil, err
end
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
local FORMATS = {
s8 = { "s8", 8, "NONE" },
s16 = { "s16be", 16, "NONE" },
s24 = { "s24be", 24, "NONE" },
s32 = { "s32be", 32, "NONE" },
f32 = { "f32be", 32, "fl32" },
f64 = { "f64be", 64, "fl64" },
ulaw = { "ulaw", 16, "ulaw" },
alaw = { "alaw", 16, "alaw" },
}
local LE = { s16be = "s16le" }
local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" }
function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = FORMATS[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
local fmt, bits, comp = spec[1], spec[2], spec[3]
if o.littleEndian then
if not LE[fmt] then
return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples")
end
fmt, comp = LE[fmt], "sowt"
end
if src.channels > 65535 then
return nil, Err.new(Err.ARG, "too many channels")
end
local aifc = o.aifc or comp ~= "NONE"
local w = Bytes.writer(65536)
w:string("FORM")
w:u32be(0) -- patched
w:string(if aifc then "AIFC" else "AIFF")
if aifc then
w:string("FVER")
w:u32be(4)
w:u32be(AIFC_VERSION)
end
-- text chunks from the tags
for _, pair in TEXT_ORDER do
local id, key = pair[1], pair[2]
local s = src.tags[key]
if type(s) == "string" and #s > 0 then
w:string(id)
w:u32be(#s)
w:string(s)
if #s % 2 == 1 then
w:u8(0)
end
end
end
local commAt = w:tell()
w:string("COMM")
if aifc then
local name = COMP_NAMES[comp] or ""
local plen = 1 + #name
plen += plen % 2
w:u32be(22 + plen)
else
w:u32be(18)
end
w:u16be(src.channels)
w:u32be(0) -- frames, patched
w:u16be(bits)
writeExt80(w, src.sampleRate)
if aifc then
w:string(comp)
local name = COMP_NAMES[comp] or ""
w:u8(#name)
w:string(name)
if (1 + #name) % 2 == 1 then
w:u8(0)
end
end
local ssndAt = w:tell()
w:string("SSND")
w:u32be(0) -- patched
w:u32be(0) -- offset
w:u32be(0) -- block size
local frames, perr = Pcm.encode(src, fmt, w)
if not frames then
return nil, perr
end
local dataLen = w:tell() - ssndAt - 16
if dataLen % 2 == 1 then
w:u8(0)
end
w:setU32be(ssndAt + 4, dataLen + 8)
w:setU32be(commAt + 10, frames)
w:setU32be(4, w:tell() - 8)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local info, err = parse(r)
if not info then
return nil, err
end
local maxFrames = opts and opts.maxFrames or 2 ^ 28
if info.frames > maxFrames then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames))
end
local dec, derr
if info.format == "ima4" then
local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags }
dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames })
if dec then
(dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64)
end
else
dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
end
if not dec then
return nil, derr
end
local d = dec :: any
d.source = {
format = "aiff",
aifc = info.aifc,
compression = info.compression,
bitDepth = info.bits,
sampleFormat = info.format,
truncated = info.truncated or nil,
}
return dec, nil
end
return Aiff