File versions 3.95+ (3.99+ verified; the 3.95-3.98 range-coder model is ported without a reference fixture), every level (fast .. insane), 8/16/24/32-bit int and 32-bit float, 1-32 channels, special frames, frame CRCs, seeking, APEv2 tags, ID3v2 in front. 35 fixtures (mac 13.28, the FATE luckynight sample) bit-exact against mac -d. tests/audio/_lossless.luau: the per-fixture checks shared by the lossless format tests. tools/bench.luau: the ws-audio2 lossless block.
230 lines
8.2 KiB
Luau
230 lines
8.2 KiB
Luau
--!strict
|
|
-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28
|
|
-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor /
|
|
-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame
|
|
-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the
|
|
-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high,
|
|
-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence,
|
|
-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit
|
|
-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned
|
|
-- as numbers either way).
|
|
--
|
|
-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table
|
|
-- local dec = Ape.decoder(info)
|
|
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats)
|
|
--
|
|
-- Never throws: bad data returns nil, Err.
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Decode = require("@formats/codecs/audio/Ape/Decode")
|
|
|
|
local Ape = {}
|
|
|
|
export type Info = {
|
|
version: number, -- file version * 1000 (3990)
|
|
programVersion: number, -- 13280 (0 when not stored)
|
|
level: number, -- 1000 (fast) .. 5000 (insane)
|
|
flags: number,
|
|
channels: number,
|
|
sampleRate: number,
|
|
bitsPerSample: number,
|
|
float: boolean,
|
|
blocksPerFrame: number,
|
|
finalFrameBlocks: number,
|
|
totalFrames: number,
|
|
totalBlocks: number,
|
|
frameStart: { number }, -- byte offset of each frame
|
|
firstFrame: number, -- byte offset of frame 1 (the word alignment origin)
|
|
dataEnd: number, -- the end of the frame data
|
|
limit: number, -- the end of the file data (frames past it are truncated)
|
|
md5: string?,
|
|
}
|
|
|
|
local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096
|
|
|
|
-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil
|
|
function Ape.find(buf: buffer, base: number, limit: number): number?
|
|
local at = base
|
|
if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then
|
|
local size = 0
|
|
for i = 6, 9 do
|
|
size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127)
|
|
end
|
|
local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0
|
|
at += size + (if footer then 20 else 10)
|
|
if not footer then
|
|
while at < limit and buffer.readu8(buf, at) == 0 do
|
|
at += 1
|
|
end
|
|
end
|
|
end
|
|
if at + 4 > limit then
|
|
return nil
|
|
end
|
|
local id = buffer.readstring(buf, at, 4)
|
|
if id == "MAC " or id == "MACF" then
|
|
return at
|
|
end
|
|
local s = buffer.readstring(buf, at, math.min(limit - at, 1048576))
|
|
local k = string.find(s, "MAC ", 1, true)
|
|
return if k then at + k - 1 else nil
|
|
end
|
|
|
|
-- info(buf, base, limit) -> Info | nil, Err
|
|
function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?)
|
|
local at = Ape.find(buf, base, limit)
|
|
if not at then
|
|
return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header")
|
|
end
|
|
local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2)
|
|
local r = Bytes.reader(buf, at, limit - at)
|
|
r:skip(4)
|
|
local version = r:u16le()
|
|
if r.err then
|
|
return nil, r.err
|
|
end
|
|
if version < 3950 then
|
|
return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)")
|
|
end
|
|
local info: any = { version = version, programVersion = 0 }
|
|
local seekCount, seekAt
|
|
if version >= 3980 then
|
|
info.programVersion = r:u16le()
|
|
local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le()
|
|
local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le()
|
|
local md5 = r:string(16)
|
|
r:seek(descBytes)
|
|
info.level = r:u16le()
|
|
info.flags = r:u16le()
|
|
info.blocksPerFrame = r:u32le()
|
|
info.finalFrameBlocks = r:u32le()
|
|
info.totalFrames = r:u32le()
|
|
info.bitsPerSample = r:u16le()
|
|
info.channels = r:u16le()
|
|
info.sampleRate = r:u32le()
|
|
if r.err then
|
|
return nil, r.err
|
|
end
|
|
seekAt = at + descBytes + headBytes
|
|
seekCount = seekBytes // 4
|
|
info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296
|
|
local _ = termBytes
|
|
local hex = table.create(16, "")
|
|
local any = false
|
|
for k = 1, 16 do
|
|
local b = string.byte(md5, k)
|
|
any = any or b ~= 0
|
|
hex[k] = string.format("%02x", b)
|
|
end
|
|
info.md5 = if any then table.concat(hex) else nil
|
|
else
|
|
info.level = r:u16le()
|
|
info.flags = r:u16le()
|
|
info.channels = r:u16le()
|
|
info.sampleRate = r:u32le()
|
|
local headerBytes = r:u32le()
|
|
r:u32le() -- terminating bytes
|
|
info.totalFrames = r:u32le()
|
|
info.finalFrameBlocks = r:u32le()
|
|
if bit32.band(info.flags, FLAG_PEAK) ~= 0 then
|
|
r:skip(4)
|
|
end
|
|
seekCount = info.totalFrames
|
|
if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then
|
|
seekCount = r:u32le()
|
|
end
|
|
if bit32.band(info.flags, FLAG_WAVHDR) == 0 then
|
|
r:skip(headerBytes)
|
|
end
|
|
if r.err then
|
|
return nil, r.err
|
|
end
|
|
info.blocksPerFrame = 73728 * 4
|
|
info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16
|
|
seekAt = r:tell()
|
|
info.dataEnd = limit
|
|
end
|
|
local C, bits = info.channels, info.bitsPerSample
|
|
if C < 1 or C > 32 then
|
|
return nil, Err.new(Err.CORRUPT, "bad channel count " .. C)
|
|
end
|
|
if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then
|
|
return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples")
|
|
end
|
|
if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then
|
|
return nil, Err.new(Err.CORRUPT, "bad header")
|
|
end
|
|
if info.totalFrames < 1 then
|
|
return nil, Err.new(Err.CORRUPT, "no frames")
|
|
end
|
|
info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32
|
|
info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks
|
|
if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then
|
|
return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete")
|
|
end
|
|
local starts = table.create(info.totalFrames, 0)
|
|
local add, prev = 0, 0
|
|
for i = 1, info.totalFrames do
|
|
local v = buffer.readu32(buf, seekAt + (i - 1) * 4)
|
|
if v < prev then
|
|
add += 4294967296
|
|
end
|
|
prev = v
|
|
starts[i] = base + junk + add + v
|
|
end
|
|
for i = 1, info.totalFrames do
|
|
if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then
|
|
return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i)
|
|
end
|
|
end
|
|
info.frameStart = starts
|
|
info.firstFrame = starts[1]
|
|
info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit)
|
|
info.limit = limit
|
|
return info :: Info, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decoder
|
|
export type Decoder = {
|
|
info: Info,
|
|
pcm: { number },
|
|
frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?),
|
|
state: Decode.State,
|
|
}
|
|
|
|
local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
|
|
local info = self.info
|
|
if i < 1 or i > info.totalFrames then
|
|
return nil, Err.new(Err.ARG, "no frame " .. i)
|
|
end
|
|
local start = info.frameStart[i]
|
|
local rem = (start - info.firstFrame) % 4
|
|
local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4
|
|
local stop = math.min(want, info.limit, buffer.len(buf))
|
|
if start + 8 > stop then
|
|
return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start)
|
|
end
|
|
local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks
|
|
local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4)
|
|
if not n2 then
|
|
return nil, Err.from(msg, start)
|
|
end
|
|
return n2, nil
|
|
end
|
|
|
|
-- decoder(info) -> Decoder | nil, Err
|
|
function Ape.decoder(info: Info): (Decoder?, Err.Err?)
|
|
local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels)
|
|
if not st then
|
|
return nil, Err.from(msg)
|
|
end
|
|
return {
|
|
info = info,
|
|
pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0),
|
|
frame = frame,
|
|
state = st,
|
|
}, nil
|
|
end
|
|
|
|
return Ape
|