--!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. Not supported: compressed AIFF-C codecs (ima4, 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 Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ 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/Pcm" }, 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" elseif bits <= 16 then return "s16be" elseif bits <= 24 then return "s24be" elseif bits <= 32 then return "s32be" end return nil, "bad sample size " .. bits elseif comp == "sowt" then if bits >= 1 and bits <= 8 then return "s8" elseif bits <= 16 then return "s16le" elseif bits <= 24 then return "s24le" elseif bits <= 32 then return "s32le" end return nil, "bad sample size " .. bits elseif comp == "raw " then return "u8" elseif comp == "in24" then return "s24be" elseif comp == "in32" then return "s32be" elseif comp == "42ni" then return "s32le" elseif comp == "fl32" or comp == "FL32" then return "f32be" elseif comp == "fl64" or comp == "FL64" then return "f64be" elseif comp == "ulaw" or comp == "ULAW" then return "ulaw" elseif comp == "alaw" or comp == "ALAW" then return "alaw" 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 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 = {} local p = base + 12 while p + 8 <= formEnd do local id = buffer.readstring(b, p, 4) local len = bit32.byteswap(buffer.readu32(b, p + 4)) local d = p + 8 local avail = math.min(len, limit - d) 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, 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 p = d + len + len % 2 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 frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format] local present = if ssnd then ssndLen // frameBytes else 0 if present < fi.frames then fi.frames = present fi.truncated = true end fi.dataOffset = ssnd or base 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 local d = dec :: any local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) d:read(d.frames, a.samples) a.tags = d.tags a.meta.source = d.source return a, nil 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 = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) 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