ws-audio2: codecs/audio/Adpcm (IMA / ima4 / IMA WAV / MS / ADX / PS-ADPCM / DSP decode, IMA + MS encode, Decoder layouts) and audio/adpcm (raw streams)

- codecs/audio/Adpcm: decoder kernels bit-exact with ffmpeg (IMA, ima4, MS) and vgmstream (ADX, PS-ADPCM, DSP);
  IMA nibble / IMA WAV / MS block encoders. Adpcm/Decoder: streaming Decoders over the shared layouts (channel
  interleaved frames, nibble streams, self-contained blocks) with exact seeking through state snapshots.
- audio/wav: its IMA / MS block decoders moved to codecs/audio/Adpcm (wav tests unchanged and green).
- codecs/audio/Stream (shared, small and backward compatible): pcm() may return a buffer of f32 (copied with
  buffer.copy) instead of a table.
- audio/adpcm: headerless ima / ima_wav / ms / ima_qt / psx streams by options; encode ima / ima_wav / ms.
- licenses: vgmstream (ISC).
This commit is contained in:
4DBug committed 2026-10-31 14:10:23 -05:00
1 parent de4f14a343
commit 363b14932f
14 files changed
+1931 -166

No files matched your search

+155
View File
@@ -0,0 +1,155 @@
--!strict
-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in
-- formats-luau. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by
-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such
-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs
-- here are the layouts those containers use:
-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first
-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order
-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024)
-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024)
-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime
-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16)
-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients
-- live in a header: see audio/brstm and audio/adx).
--
-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 })
-- local raw = Adpcm.encode(a, { codec = "ima" })
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/audio/Pcm")
local Adpcm = require("@formats/codecs/audio/Adpcm")
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Raw = {
name = "adpcm",
category = "audio",
extensions = { "adpcm", "ima" },
mime = { "audio/x-adpcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx"
export type Options = {
codec: Codec?, -- default "ima"
sampleRate: number?, -- default 22050 (decode)
channels: number?, -- default 1 (decode)
blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding)
lowFirst: boolean?, -- ima: the low nibble first
interleave: number?, -- psx: bytes per channel before the next channel (default 16)
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Raw.sniff(_r: Bytes.Reader): number
return 0 -- no header: found by extension or opts.format only
end
-- ------------------------------------------------------------------------------------------------ decode
function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?)
local dec, err = Raw.open(r, opts)
if not dec then
return nil, err
end
local limit = opts and opts.maxFrames or 2 ^ 28
if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames))
end
return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o: Options = opts or {}
local codec = o.codec or "ima"
if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then
return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms")
end
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local a, cerr = Pcm.collect(src)
if not a then
return nil, cerr
end
local ch, n, x = a.channels, a.frames, a.samples
if codec == "ima" then
local out = buffer.create((n * ch + 1) // 2)
local st = buffer.create(8 * ch)
for c = 0, ch - 1 do
Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst)
end
return out, nil
end
local ba = o.blockAlign or 256 * ch
local spb = Decoder.blockFrames(codec, ba, ch)
if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then
return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba))
end
if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then
return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels")
end
local blocks = (n + spb - 1) // spb
local out = buffer.create(blocks * ba)
local st = buffer.create(8 * ch)
for b = 0, blocks - 1 do
local f0 = b * spb
if codec == "ms" then
Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba)
else
Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba)
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local o: Options = opts or {}
local codec = o.codec or "ima"
local rate, ch = o.sampleRate or 22050, o.channels or 1
if not CODECS[codec] then
return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec))
end
if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
end
local size = r.limit - r.base
local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 }
local d, err
if codec == "ima" then
d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst })
elseif codec == "psx" then
local il = o.interleave or 16
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
end
d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il })
else
local ba = o.blockAlign or 1024
if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then
return nil, Err.new(Err.ARG, "bad blockAlign")
end
d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba })
end
if not d then
return nil, err
end
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
return d, nil
end
return Raw
+2 -155
View File
@@ -1,7 +1,8 @@
--!strict
--!native
--!optimize 2
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers).
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The
-- ADPCM block decoders moved to codecs/audio/Adpcm.
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
-- only calls them with ranges it has checked against the source length and the output size.
local readu8, readi8, readu16, readi16, readu32, readi32 =
@@ -102,160 +103,6 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num
end
end
local IMA_STEP = buffer.create(89 * 4)
do
local steps = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724,
796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026,
4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500,
20350, 22385, 24623, 27086, 29794, 32767,
}
for i, s in steps do
buffer.writei32(IMA_STEP, (i - 1) * 4, s)
end
end
local IMA_INDEX = buffer.create(16 * 4)
do
local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
for i, v in t do
buffer.writei32(IMA_INDEX, (i - 1) * 4, v)
end
end
-- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a
-- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and
-- returns the frame count.
function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number
if avail < 4 * ch then
return 0
end
-- groups of 8 samples per channel (4 bytes each) after the per-channel headers
local groups = (avail - 4 * ch) // (4 * ch)
local frames = math.min(spb, 1 + groups * 8)
for c = 0, ch - 1 do
local pred = readi16(src, off + c * 4)
local index = readu8(src, off + c * 4 + 2)
if index > 88 then
index = 88
end
writef32(dst, c * 4, pred / 32768)
local f = 1
local g = 0
while f < frames do
local p = off + 4 * ch + (g * ch + c) * 4
for k = 0, 7 do
if f >= frames then
break
end
local b = readu8(src, p + rshift(k, 1))
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
local step = buffer.readi32(IMA_STEP, index * 4)
local diff = rshift(step, 3)
if band(nib, 1) ~= 0 then
diff += rshift(step, 2)
end
if band(nib, 2) ~= 0 then
diff += rshift(step, 1)
end
if band(nib, 4) ~= 0 then
diff += step
end
if band(nib, 8) ~= 0 then
pred -= diff
else
pred += diff
end
if pred > 32767 then
pred = 32767
elseif pred < -32768 then
pred = -32768
end
index += buffer.readi32(IMA_INDEX, nib * 4)
if index < 0 then
index = 0
elseif index > 88 then
index = 88
end
writef32(dst, (f * ch + c) * 4, pred / 32768)
f += 1
end
g += 1
end
end
return frames
end
local MS_ADAPT = buffer.create(16 * 4)
do
local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
for i, v in t do
buffer.writei32(MS_ADAPT, (i - 1) * 4, v)
end
end
-- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch.
-- Returns the frame count (a truncated last block decodes the whole bytes it has).
function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer,
coefs: buffer, ncoef: number, state: buffer): number
local hdr = 7 * ch
if avail < hdr or ncoef < 1 then
return 0
end
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
-- state per channel: c1, c2, idelta, s1, s2 (5 i32)
for c = 0, ch - 1 do
local pi = readu8(src, off + c)
if pi >= ncoef then
pi = ncoef - 1
end
local idelta = readi16(src, off + ch + c * 2)
local s1 = readi16(src, off + 3 * ch + c * 2)
local s2 = readi16(src, off + 5 * ch + c * 2)
local so = c * 20
buffer.writei32(state, so, buffer.readi32(coefs, pi * 8))
buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4))
buffer.writei32(state, so + 8, idelta)
buffer.writei32(state, so + 12, s1)
buffer.writei32(state, so + 16, s2)
writef32(dst, c * 4, s2 / 32768)
if frames > 1 then
writef32(dst, (ch + c) * 4, s1 / 32768)
end
end
-- nibbles, high first, channels interleaved per nibble
local total = (frames - 2) * ch
for k = 0, total - 1 do
local b = readu8(src, off + hdr + rshift(k, 1))
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
local c = k % ch
local so = c * 20
local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4)
local idelta = buffer.readi32(state, so + 8)
local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16)
local p = s1 * c1 + s2 * c2
p = if p >= 0 then p // 256 else -((-p) // 256)
local sn = if nib >= 8 then nib - 16 else nib
p += sn * idelta
if p > 32767 then
p = 32767
elseif p < -32768 then
p = -32768
end
idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256
if idelta < 16 then
idelta = 16
elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg
idelta = 2796202
end
buffer.writei32(state, so + 8, idelta)
buffer.writei32(state, so + 12, p)
buffer.writei32(state, so + 16, s1)
writef32(dst, (2 * ch + k) * 4, p / 32768)
end
return frames
end
-- copy frames from a block cache into the output: count f32 values
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
+5 -5
View File
@@ -21,6 +21,7 @@ local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/audio/Pcm")
local Riff = require("@formats/containers/Riff")
local Codecs = require("@formats/audio/wav/Codecs")
local Adpcm = require("@formats/codecs/audio/Adpcm")
-- ------------------------------------------------------------------------------------------------ contract
local Wav = {
@@ -28,7 +29,7 @@ local Wav = {
category = "audio",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
}
@@ -488,8 +489,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
spb = computed
end
-- coefficients from the fmt extension, else the 7 standard pairs
local c1 = { 256, 512, 0, 192, 240, 460, 392 }
local c2 = { 0, -256, 0, 64, 0, -208, -232 }
local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
local ncoef = 7
if fmt.avail >= 22 then
local k = u16(fmt.body + 20)
@@ -592,9 +592,9 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
local avail = math.min(ba, self.dataOffset + self.dataSize - off)
local got
if kind == "ima_adpcm" then
got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache)
got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0)
else
got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef,
got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef,
self._state :: buffer)
end
self._cacheBlock = block