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.
This commit is contained in:
4DBug committed 2026-10-31 14:34:28 -05:00
1 parent 3f6823cbe5
commit 2717292366
7 files changed
+99 -17

No files matched your search

+2 -2
View File
@@ -188,7 +188,7 @@ local list: { Entry } = {
path = "audio/aiff",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
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 },
load = function()
return require("@formats/audio/aiff")
@@ -224,7 +224,7 @@ local list: { Entry } = {
path = "audio/caf",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
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")
+27 -6
View File
@@ -3,8 +3,9 @@
-- 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.
-- 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")
@@ -12,6 +13,7 @@ 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 = {
@@ -19,7 +21,7 @@ local Aiff = {
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
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 },
}
@@ -115,6 +117,8 @@ local function sampleFormat(comp: string, bits: number): (string?, string?)
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
@@ -138,6 +142,7 @@ type Info = {
compression: string,
aifc: boolean,
dataOffset: number, -- absolute in r.buf
dataSize: number, -- bytes of sample data present
truncated: boolean,
tags: Types.Tags,
}
@@ -194,6 +199,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
compression = comp,
aifc = aifc,
dataOffset = 0,
dataSize = 0,
truncated = false,
tags = tags,
}
@@ -228,13 +234,19 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
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
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
@@ -360,7 +372,16 @@ function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.
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)
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
+22 -4
View File
@@ -3,7 +3,8 @@
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/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).
-- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported:
-- other compressed formats (UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -14,6 +15,7 @@ local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local Aac = require("@formats/codecs/audio/Aac")
local Alac = require("@formats/codecs/audio/Alac")
local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Caf = {
@@ -21,7 +23,7 @@ local Caf = {
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
}
@@ -333,7 +335,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
end
-- packetised codecs
local sizes = p.packets
if not sizes then
if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none
if d.bytesPerPacket > 0 then
local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
sizes = table.create(n, d.bytesPerPacket)
@@ -425,7 +427,23 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
if not p then
return nil, err
end
local s, serr = source(r, p :: Parsed)
local pp = p :: Parsed
if pp.desc.format == "ima4" then
-- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets
local ch = pp.desc.channels
local packets = (pp.dataEnd - pp.dataStart) // (34 * ch)
local frames = packets * 64
if pp.validFrames and pp.validFrames >= 0 then
frames = math.min(frames, pp.validFrames)
end
local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 }
local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames })
if d then
d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64)
end
return d, derr
end
local s, serr = source(r, pp)
if not s then
return nil, serr
end
+6 -4
View File
@@ -1,5 +1,5 @@
-- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C
-- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks;
-- sowt / fl32 / fl64 / ulaw / alaw / ima4, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks;
-- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz.
-- Fixtures: tools/fixtures/aiff.py.
local T = require("@tests/T")
@@ -149,9 +149,11 @@ do
t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e))
local c = case("ffmpeg-fl32").data
local p = string.find(c, "fl32", 1, true) :: number
local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4)
local _, e2 = Aiff.decode(reader(ima))
t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2))
local mac = string.sub(c, 1, p - 1) .. "MAC3" .. string.sub(c, p + 4)
local _, e2 = Aiff.decode(reader(mac))
t:check(e2 and e2.code == Err.UNSUPPORTED, "MAC3: UNSUPPORTED: " .. tostring(e2))
local i4 = Aiff.decode(reader(case("ffmpeg-ima4").data)) :: any
t:check(i4.meta.source.compression == "ima4" and i4.frames % 64 == 0, "ima4 meta / whole packets")
local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30)))
t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3))
local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 })
+12
View File
@@ -174,4 +174,16 @@ do
end, samples, { mutations = 30 })
end
-- ------------------------------------------------------------------------------------------------ IMA4
do
local H = require("@tests/audio/_adpcm")
local Ima4 = require("@tests/gen/caf_ima4")
for _, c in Ima4 do
H.check(t, Caf, c)
local a = Caf.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
t:eq(a.meta.source.codec, "ima4", c.name .. ": codec")
end
t:note("%d IMA4 files bit-exact with ffmpeg", #Ima4)
end
t:done()
+3 -1
View File
@@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di
A = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(A)
INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm"]
INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm", "src/Formats/codecs/audio/Adpcm"]
def ff(codec, src="{in}", extra=()):
@@ -34,6 +34,8 @@ def generate(ctx):
("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]),
("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]),
("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]),
("ffmpeg-ima4", "ffmpeg", ff("adpcm_ima_qt")),
("ffmpeg-ima4-mono", "ffmpeg", ff("adpcm_ima_qt", "{in_mono}")),
]
encodes = [
("s16", "nil", 2),
+27
View File
@@ -0,0 +1,27 @@
# CAF IMA4 fixtures (tools/fixtures.py): audio/caf's Apple IMA ADPCM (codecs/audio/Adpcm), written and decoded by ffmpeg.
# tests/gen/caf_ima4.luau { name, data, rate, ch, ref (ffmpeg s16le) }
import importlib.util, os
_dir = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
A = _load("_audio")
D = _load("_adpcm")
INPUTS = ["src/Formats/codecs/audio/Adpcm", "src/Formats/audio/caf"]
def generate(ctx):
cases = []
for name, kind, rate, ch, frames in (("ima4-stereo", "music", 44100, 2, 9000), ("ima4-mono", "sweep", 22050, 1, 4410)):
sig = A.signal(kind, rate, ch, frames, seed=ch + 50)
data = D.ffencode(ctx, A.wav(sig, rate, ch), ["-c:a", "adpcm_ima_qt"], "caf")
cases.append(dict(name=name, data=data, rate=rate, ch=ch, ref=D.ffs16(ctx, data, "caf")))
ctx.emit("caf_ima4", cases)