From 363b14932fa91ea431cadcea6a91dc3e4092e332 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:10:23 -0500 Subject: [PATCH] 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). --- docs/FORMATS.md | 2 + licenses/NOTICE.md | 1 + licenses/vgmstream-LICENSE.txt | 23 + src/Formats/Registry.luau | 14 +- src/Formats/audio/adpcm/init.luau | 155 ++++++ src/Formats/audio/wav/Codecs.luau | 157 +----- src/Formats/audio/wav/init.luau | 10 +- src/Formats/codecs/audio/Adpcm/Decoder.luau | 308 +++++++++++ src/Formats/codecs/audio/Adpcm/init.luau | 568 ++++++++++++++++++++ src/Formats/codecs/audio/Stream.luau | 14 +- tests/audio/adpcm.luau | 127 +++++ tests/codecs/adpcm.luau | 228 ++++++++ tools/fixtures/_adpcm.py | 352 ++++++++++++ tools/fixtures/adpcm.py | 138 +++++ 14 files changed, 1931 insertions(+), 166 deletions(-) create mode 100644 licenses/vgmstream-LICENSE.txt create mode 100644 src/Formats/audio/adpcm/init.luau create mode 100644 src/Formats/codecs/audio/Adpcm/Decoder.luau create mode 100644 src/Formats/codecs/audio/Adpcm/init.luau create mode 100644 tests/audio/adpcm.luau create mode 100644 tests/codecs/adpcm.luau create mode 100644 tools/fixtures/_adpcm.py create mode 100644 tools/fixtures/adpcm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..5875495 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,6 +17,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | | audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | +| audio | adpcm | .adpcm .ima | yes | yes | streaming: true, lossy: true, headerless: true, codecs: "ima", "ima_wav", "ms", "ima_qt", "psx" | `tests/audio/adpcm.luau` | | audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | | audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` | | audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | @@ -87,6 +88,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **audio** - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program + - codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..9c68de2 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -37,6 +37,7 @@ | `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | +| `src/Formats/codecs/audio/Adpcm/` (the ADX coefficient derivation, PS-ADPCM / DSP / ADX decode details, followed for bit-exact output; the container layouts of audio/adx, audio/vag, audio/brstm) | vgmstream r2117 | ISC-style: [vgmstream-LICENSE.txt](vgmstream-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/licenses/vgmstream-LICENSE.txt b/licenses/vgmstream-LICENSE.txt new file mode 100644 index 0000000..033f42a --- /dev/null +++ b/licenses/vgmstream-LICENSE.txt @@ -0,0 +1,23 @@ +Copyright (c) 2008-2025 Adam Gashlin, Fastelbja, Ronny Elfert, bnnm, + Christopher Snowhill, NicknineTheEagle, bxaimc, + Thealexbarney, CyberBotX, EdnessP, et al + +Portions Copyright (c) 2004-2008, Marko Kreen +Portions Copyright 2001-2007 jagarl / Kazunori Ueno +Portions Copyright (c) 1998, Justin Frankel/Nullsoft Inc. +Portions Copyright (C) 2006 Nullsoft, Inc. +Portions Copyright (c) 2005-2007 Paul Hsieh +Portions Copyright (C) 2000-2004 Leshade Entis, Entis-soft. +Portions Public Domain originating with Sun Microsystems + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..790e6f6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -158,6 +158,18 @@ local list: { Entry } = { return require("@formats/audio/aac") end, }, + { + name = "adpcm", + category = "audio", + path = "audio/adpcm", + 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" } }, + load = function() + return require("@formats/audio/adpcm") + end, + }, { name = "aiff", category = "audio", @@ -272,7 +284,7 @@ local list: { Entry } = { path = "audio/wav", 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 }, load = function() return require("@formats/audio/wav") diff --git a/src/Formats/audio/adpcm/init.luau b/src/Formats/audio/adpcm/init.luau new file mode 100644 index 0000000..16627c5 --- /dev/null +++ b/src/Formats/audio/adpcm/init.luau @@ -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 diff --git a/src/Formats/audio/wav/Codecs.luau b/src/Formats/audio/wav/Codecs.luau index 4094c07..5b219bc 100644 --- a/src/Formats/audio/wav/Codecs.luau +++ b/src/Formats/audio/wav/Codecs.luau @@ -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) diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index cf5e65c..ccf655a 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -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 diff --git a/src/Formats/codecs/audio/Adpcm/Decoder.luau b/src/Formats/codecs/audio/Adpcm/Decoder.luau new file mode 100644 index 0000000..a4ee4d8 --- /dev/null +++ b/src/Formats/codecs/audio/Adpcm/Decoder.luau @@ -0,0 +1,308 @@ +--!strict +-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the +-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus +-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it +-- passes; a seek restores the snapshot, or the format's own state for that packet (BRSTM's ADPC history), or decodes +-- forward from the nearest earlier snapshot. New in formats-luau. +-- +-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) +-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) +-- frames = total, -- output frames +-- state = st, -- the codec state buffer decode advances +-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 +-- restore = function(i) return false end, -- optional: set st for packet i, true if it could +-- }) +-- +-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: +-- Decoder.interleaved(dec, spec) psx / adx / dsp frames, channels interleaved every spec.interleave bytes (VAG, +-- ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) +-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) +-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes +-- per channel), raw or inside AIFF-C / CAF +-- +-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +local Err = require("@formats/core/Err") +local Stream = require("@formats/codecs/audio/Stream") +local Adpcm = require("@formats/codecs/audio/Adpcm") + +local Decoder = {} + +export type Spec = { + count: number, + packetFrames: number, + frames: number, + state: buffer, + decode: (i: number, out: buffer) -> (number?, Err.Err?), + restore: ((i: number) -> boolean)?, +} + +function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) + local ch = dec.channels + local pf = spec.packetFrames + local st = spec.state + local out = buffer.create(pf * ch * 4) + local decodeP = spec.decode + local restore = spec.restore + local snaps: { [number]: buffer } = {} + local nextPacket = 1 + local function snap(i: number) + if not snaps[i] then + local b = buffer.create(buffer.len(st)) + buffer.copy(b, 0, st) + snaps[i] = b + end + end + snap(1) + local function decode(i: number): (number?, Err.Err?) + if i ~= nextPacket then + if restore and restore(i) then + -- the format set the state + elseif snaps[i] then + buffer.copy(st, 0, snaps[i]) + else + local j = i - 1 + while j > 1 and not snaps[j] do + j -= 1 + end + buffer.copy(st, 0, snaps[j]) + for k = j, i - 1 do + local n, e = decodeP(k, out) + if not n then + return nil, e + end + snap(k + 1) + end + end + end + local n, e = decodeP(i, out) + if n then + nextPacket = i + 1 + snap(i + 1) + end + return n, e + end + return Stream.packets(dec, { + count = spec.count, + start = function(i: number): number + return (i - 1) * pf + end, + decode = decode, + pcm = function(): buffer + return out + end, + reset = function() end, + stop = spec.frames, + }) +end + +-- ------------------------------------------------------------------------------------------------ layouts +local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8 } -- bytes per frame +local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14 } -- samples per frame + +export type InterleavedSpec = { + kind: "psx" | "adx" | "dsp", + buf: buffer, + offset: number, -- the first row + size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames) + interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple) + lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave + frames: number?, -- frames to output (default: what the data holds) + c1: number?, -- adx: the predictor (Adpcm.adxCoefs) + c2: number?, + v3: boolean?, -- adx: version 3 rounding + coefs: buffer?, -- dsp: 16 i32 per channel + hist: { number }?, -- initial history, h1 / h2 per channel (default 0) + restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) +} + +-- interleaved(dec, spec) -> Decoder | nil, Err +function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local fsize, spf = FRAME[kind], SPF[kind] + local il = spec.interleave + local last = spec.lastInterleave or il + if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il)) + end + local buf, base, size = spec.buf, spec.offset, spec.size + local rowBytes = il * ch + -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) + local rows = math.max(1, math.ceil(size / rowBytes)) + local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel + local width = if r == rows - 1 then last else il + -- channel c sits at c * width in the row: the last channel is the one a cut file shortens + local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) + return (per // fsize) * spf + end + local fullFrames = (il // fsize) * spf + local total = (rows - 1) * fullFrames + rowFrames(rows - 1) + local frames = math.min(spec.frames or total, total) + local st = buffer.create(8 * ch) + if spec.hist then + for c = 0, ch - 1 do + buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0) + buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0) + end + end + local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames) + local pf = rowsPer * fullFrames + local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs + local restore = spec.restore + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / pf)), + packetFrames = pf, + frames = frames, + state = st, + restore = if restore + then function(i: number): boolean + return restore(i - 1, st) + end + else nil, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local got = 0 + for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do + local n = math.min(rowFrames(r), frames - r * fullFrames) + if n <= 0 then + break + end + local nf = math.ceil(n / spf) + local width = if r == rows - 1 then last else il + for c = 0, ch - 1 do + local p = base + r * rowBytes + c * width + local d = got * ch + c + if kind == "psx" then + Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch) + elseif kind == "adx" then + Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch) + else + Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch) + end + end + got += n + end + return got, nil + end, + }) +end + +export type NibbleSpec = { + buf: buffer, + offset: number, + size: number, -- bytes + hi: boolean?, -- the high nibble first (DVI / KVAG); default low first + frames: number?, -- default: every whole frame of nibbles +} + +-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... +function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?) + local ch = dec.channels + local buf, base = spec.buf, spec.offset + local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch) + local st = buffer.create(8 * ch) + local hi = spec.hi == true + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / 4096)), + packetFrames = 4096, + frames = frames, + state = st, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local f0 = (i - 1) * 4096 + local n = math.min(4096, frames - f0) + for c = 0, ch - 1 do + Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch) + end + return n, nil + end, + }) +end + +export type BlockSpec = { + kind: "ms" | "ima_wav" | "ima_qt", + buf: buffer, + offset: number, + size: number, + blockAlign: number?, -- ms / ima_wav: bytes per block + frames: number?, -- default: what the blocks hold + coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) +} + +-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers +function Decoder.blockFrames(kind: string, ba: number, ch: number): number? + if kind == "ima_qt" then + return 64 + elseif kind == "ms" then + return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil + end + return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil +end + +-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has +function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0 + local spb = Decoder.blockFrames(kind, ba, ch) + if not spb then + return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small") + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + local buf, base, size = spec.buf, spec.offset, spec.size + local full = size // ba + local rest = size - full * ba + local total = full * spb + if kind ~= "ima_qt" and rest > 0 then + -- a partial last block: the frames it holds whole + if kind == "ms" then + total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0 + elseif rest >= 4 * ch then + total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + end + local frames = math.min(spec.frames or total, total) + local ncoef = 7 + local cf = spec.coefs + if cf and #cf >= 2 then + ncoef = math.min(256, #cf // 2) + end + local coefs = buffer.create(ncoef * 8) + for k = 0, ncoef - 1 do + buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1]) + buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1]) + end + local scratch = buffer.create(20 * ch) + dec.frames = frames + dec.duration = frames / dec.sampleRate + dec.blockAlign = ba + dec.samplesPerBlock = spb + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / spb)), + packetFrames = spb, + frames = frames, + state = scratch, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local off = base + (i - 1) * ba + local avail = math.min(ba, base + size - off) + if kind == "ms" then + return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil + elseif kind == "ima_wav" then + return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil + end + if avail < ba then + return 0, nil + end + for c = 0, ch - 1 do + Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch) + end + return 64, nil + end, + }) +end + +return Decoder diff --git a/src/Formats/codecs/audio/Adpcm/init.luau b/src/Formats/codecs/audio/Adpcm/init.luau new file mode 100644 index 0000000..56eab9c --- /dev/null +++ b/src/Formats/codecs/audio/Adpcm/init.luau @@ -0,0 +1,568 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and +-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo +-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: +-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 +-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. +-- +-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running +-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), +-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). +-- +-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... +-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples +-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) +-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block +-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples +-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 +-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples +-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples +-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) +-- +-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are +-- documented on each). Never throws. +local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 +local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift +local floor = math.floor + +local Adpcm = {} + +-- ------------------------------------------------------------------------------------------------ IMA +local IMA_STEP = { + 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, +} +local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } +-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as +-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently) +local IMA_DIFF = table.create(89 * 8, 0) +-- IMA_NEXT[index * 16 + nibble + 1]: the next step index +local IMA_NEXT = table.create(89 * 16, 0) +for i = 0, 88 do + local step = IMA_STEP[i + 1] + for n = 0, 7 do + local d = rshift(step, 3) + if band(n, 1) ~= 0 then + d += rshift(step, 2) + end + if band(n, 2) ~= 0 then + d += rshift(step, 1) + end + if band(n, 4) ~= 0 then + d += step + end + IMA_DIFF[i * 8 + n + 1] = d + end + for n = 0, 15 do + IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88) + end +end +Adpcm.IMA_STEP = IMA_STEP + +-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is +-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes +-- p .. p + (q0 + (count - 1) * qs) // 2. +function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + local o = d * 4 + local os = ds * 4 + for _ = 1, count do + local b = readu8(src, p + rshift(q, 1)) + local nib + if (band(q, 1) == 0) == hi then + nib = rshift(b, 4) + else + nib = band(b, 15) + end + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o, pred / 32768) + o += os + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step +-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while +-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet +-- (zeros before the first). +function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) + local h = readu8(src, p) * 256 + readu8(src, p + 1) + local pred = band(h, 0xFF80) + if pred >= 32768 then + pred -= 65536 + end + local index = band(h, 0x7F) + if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then + writei32(st, so, pred) + writei32(st, so + 4, index) + end + Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) +end + +-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the +-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the +-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float +-- index d; returns the frame count (<= spb). +function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number + if avail < 4 * ch then + return 0 + end + local groups = (avail - 4 * ch) // (4 * ch) + local frames = math.min(spb, 1 + groups * 8) + local o = d * 4 + for c = 0, ch - 1 do + local pred = readi16(src, off + c * 4) + local index = math.min(readu8(src, off + c * 4 + 2), 88) + writef32(dst, o + c * 4, pred / 32768) + local f = 1 + local g = 0 + while f < frames do + local p = off + 4 * ch + (g * ch + c) * 4 + local k = 0 + while k < 8 and f < frames do + local b = readu8(src, p + rshift(k, 1)) + local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o + (f * ch + c) * 4, pred / 32768) + f += 1 + k += 1 + end + g += 1 + end + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ MS ADPCM +local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } +Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } +Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } + +-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for +-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x +-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from +-- float index d; returns the frame count (<= spb). +function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, + 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) + local o = d * 4 + for c = 0, ch - 1 do + local pi = math.min(readu8(src, off + c), ncoef - 1) + 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 + writei32(state, so, readi32(coefs, pi * 8)) + writei32(state, so + 4, readi32(coefs, pi * 8 + 4)) + writei32(state, so + 8, idelta) + writei32(state, so + 12, s1) + writei32(state, so + 16, s2) + writef32(dst, o + c * 4, s2 / 32768) + if frames > 1 then + writef32(dst, o + (ch + c) * 4, s1 / 32768) + end + end + 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 so = (k % ch) * 20 + local c1, c2 = readi32(state, so), readi32(state, so + 4) + local idelta = readi32(state, so + 8) + local s1, s2 = readi32(state, so + 12), readi32(state, so + 16) + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + p += (if nib >= 8 then nib - 16 else nib) * idelta + if p > 32767 then + p = 32767 + elseif p < -32768 then + p = -32768 + end + idelta = (MS_ADAPT[nib + 1] * idelta) // 256 + if idelta < 16 then + idelta = 16 + elseif idelta > 2796202 then -- INT_MAX / 768 + idelta = 2796202 + end + writei32(state, so + 8, idelta) + writei32(state, so + 12, p) + writei32(state, so + 16, s1) + writef32(dst, o + (2 * ch + k) * 4, p / 32768) + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ CRI ADX +local F32 = buffer.create(4) +local function f32(x: number): number + writef32(F32, 0, x) + return readf32(F32, 0) +end + +-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the +-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) + if rate <= 0 then + return 0, 0 + end + local z = f32(math.cos(f32(2 * math.pi * cutoff / rate))) + local a = f32(math.sqrt(2) - z) + local b = f32(math.sqrt(2) - 1) + local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b) + local c1 = c * 8192 + local c2 = f32(c * c) * -4096 + c1 = if c1 >= 0 then floor(c1) else -floor(-c1) + c2 = if c2 >= 0 then floor(c2) else -floor(-c2) + return c1, c2 +end + +-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from +-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as +-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, + st: buffer, so: number, dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local scale = readu8(src, fp) * 256 + readu8(src, fp + 1) + if scale == 0x8001 then + scale = 0 + elseif scale >= 32768 then + scale -= 65535 -- the signed value + 1 + else + scale += 1 + end + for k = 0, 31 do + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s + if v3 then + s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096 + else + s = n * scale + (c1 * h1 + c2 * h2) // 4096 + end + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ PS-ADPCM +local PSX1 = { 0, 60, 115, 98, 122 } +local PSX2 = { 0, 0, -52, -55, -60 } + +-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: +-- exact in integers while the products fit a float's 24 bits +local function psxPred(f: number, h1: number, h2: number): number + local x = PSX1[f] * h1 + PSX2[f] * h2 + if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then + return 4 * x + end + local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256 + return if v >= 0 then floor(v) else -floor(-v) +end + +-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart +-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The +-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, + d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local head = readu8(src, fp) + local filter = rshift(head, 4) + local shift = band(head, 15) + if filter > 4 then + filter = 0 + end + if shift > 12 then + shift = 9 + end + local mul = 2 ^ (20 - shift) + local fi = filter + 1 + local silent = band(readu8(src, fp + 1), 15) == 7 + for k = 0, 27 do + local s = 0 + if not silent then + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + if n >= 8 then + n -= 16 + end + s = (n * mul + psxPred(fi, h1, h2)) // 256 + end + h2 = h1 + h1 = s + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ Nintendo DSP +-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). +-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. +-- p + ceil(count / 14) * 8 - 1. +function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + local done = 0 + local fp = p + while done < count do + local head = readu8(src, fp) + local pi = math.min(rshift(head, 4), 7) + local scale = 2 ^ band(head, 15) * 2048 + local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4) + local n14 = math.min(14, count - done) + for k = 0, n14 - 1 do + local b = readu8(src, fp + 1 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048 + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + done += n14 + fp += 8 + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ encoders +-- the nearest s16 to x * 32768 (NaN -> 0) +local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end +Adpcm.toS16 = toS16 + +-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) +local function imaNibble(x: number, pred: number, index: number): number + local base = index * 8 + 1 + local best, bestErr = 0, math.huge + for m = 0, 7 do + local diff = IMA_DIFF[base + m] + local up = math.min(pred + diff, 32767) + local e = math.abs(x - up) + if e < bestErr then + best, bestErr = m, e + end + local down = math.max(pred - diff, -32768) + e = math.abs(x - down) + if e < bestErr then + best, bestErr = m + 8, e + end + end + return best +end + +-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... +-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. +-- p + (q0 + (count - 1) * qs) // 2. +function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, q0: number, qs: number, hi: boolean) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + for i = 0, count - 1 do + local v = toS16(readf32(x, (xi + i * xs) * 4)) + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = p + rshift(q, 1) + local b = readu8(out, bp) + if (band(q, 1) == 0) == hi then + b = bor(band(b, 0x0F), lshift(nib, 4)) + else + b = bor(band(b, 0xF0), nib) + end + writeu8(out, bp, b) + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames +-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch +-- bytes carrying the step index from block to block. +function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) + local groups = (spb - 1) // 8 + for c = 0, ch - 1 do + local so = c * 8 + local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0 + writei32(st, so, first) + local index = math.clamp(readi32(st, so + 4), 0, 88) + writei32(st, so + 4, index) + buffer.writei16(out, off + c * 4, first) + writeu8(out, off + c * 4 + 2, index) + writeu8(out, off + c * 4 + 3, 0) + local pred = first + for g = 0, groups - 1 do + local gp = off + 4 * ch + (g * ch + c) * 4 + for k = 0, 7 do + local f = 1 + g * 8 + k + local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = gp + rshift(k, 1) + if band(k, 1) == 0 then + writeu8(out, bp, nib) + else + writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4))) + end + end + end + writei32(st, so + 4, index) + end +end + +-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first +-- delta; returns the squared error and the nibbles in nibs (when given) +local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number + local s1, s2 = xs[2], xs[1] + local idelta = delta0 + local err = 0 + for i = 3, n do + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + local e = xs[i] - p + local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta) + nib = math.clamp(nib, -8, 7) + local v = math.clamp(p + nib * idelta, -32768, 32767) + err += (xs[i] - v) * (xs[i] - v) + if nibs then + nibs[i] = band(nib, 15) + end + idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202) + s2 = s1 + s1 = v + end + return err +end + +-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf +-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel +-- takes the predictor with the least error. +function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) + local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local xs = table.create(spb, 0) + local nibs = table.create(spb, 0) + local all = table.create(spb * ch, 0) + for c = 0, ch - 1 do + for i = 1, spb do + xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 + end + -- the first delta from the first steps + local sum = 0 + for i = 3, math.min(spb, 10) do + sum += math.abs(xs[i] - xs[i - 1]) + end + local delta0 = math.clamp(sum // 16, 16, 32767) + local best, bestErr = 1, math.huge + for k = 1, 7 do + local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil) + if e < bestErr then + best, bestErr = k, e + end + end + msTrial(xs, spb, C1[best], C2[best], delta0, nibs) + writeu8(out, off + c, best - 1) + writeu16(out, off + ch + c * 2, delta0) + buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0) + buffer.writei16(out, off + 5 * ch + c * 2, xs[1]) + for i = 3, spb do + all[(i - 3) * ch + c + 1] = nibs[i] + end + end + local total = (spb - 2) * ch + for k = 0, total - 1, 2 do + writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0)) + end +end + +return Adpcm diff --git a/src/Formats/codecs/audio/Stream.luau b/src/Formats/codecs/audio/Stream.luau index ef69611..33f08d0 100644 --- a/src/Formats/codecs/audio/Stream.luau +++ b/src/Formats/codecs/audio/Stream.luau @@ -10,7 +10,7 @@ -- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position -- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before -- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm() --- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode +-- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode -- reset = function() end, -- forget codec state (before a seek) -- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop) -- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1) @@ -26,7 +26,7 @@ export type Spec = { count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), - pcm: () -> { number }, + pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0 reset: () -> (), skip: number?, -- default 0 stop: number?, -- default start(count + 1) @@ -91,9 +91,13 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local src = pcmOf() local q = got * ch * 4 local s = pendPos * ch - for k = 1, take * ch do - writef32(ob, q, src[s + k]) - q += 4 + if type(src) == "buffer" then + buffer.copy(ob, q, src, s * 4, take * ch * 4) + else + for k = 1, take * ch do + writef32(ob, q, src[s + k]) + q += 4 + end end pendPos += take got += take diff --git a/tests/audio/adpcm.luau b/tests/audio/adpcm.luau new file mode 100644 index 0000000..bf3ca90 --- /dev/null +++ b/tests/audio/adpcm.luau @@ -0,0 +1,127 @@ +-- audio/adpcm tests: headerless streams (IMA nibbles, IMA WAV / MS blocks, Apple ima4, PS-ADPCM) decoded with the +-- layout in the options, bit-exact against ffmpeg / vgmstream (tools/fixtures/adpcm.py), with seeking; our encoder's +-- streams (ima, ms, ima_wav) as ffmpeg decodes them (wrapped in KVAG / WAV in the fixture step) against our decode of +-- the same bytes, and their quality; options and errors; the api by format name; the fuzz pass. +local T = require("@tests/T") +local Raw = require("@formats/audio/adpcm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local Cases = require("@tests/gen/adpcm_raw") +local Ours = require("@tests/gen/adpcm_ours") +local Sig = require("@tests/gen/adpcm_sig") + +local t = T.suite("adpcm") + +t:eq(Raw.name, "adpcm", "name") +t:check(Raw.caps.decode and Raw.caps.encode and Raw.open ~= nil, "caps") +t:eq(Raw.sniff(Bytes.reader(buffer.fromstring("RIFF....WAVE"))), 0, "sniff is always 0") + +local function same(out: buffer, ref: buffer, from: number, count: number): boolean + for i = 0, count - 1 do + if buffer.readf32(out, i * 4) * 32768 ~= buffer.readi16(ref, (from + i) * 2) then + return false + end + end + return true +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + local opts = { codec = c.codec, sampleRate = c.rate, channels = c.ch, blockAlign = c.blockAlign } + local ref = buffer.fromstring(c.ref) + local frames = buffer.len(ref) // (2 * c.ch) + local a, err = Raw.decode(Bytes.reader(buffer.fromstring(c.data)), opts) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.frames, frames, c.name .. ": frames") + t:check(same(a.samples, ref, 0, frames * c.ch), c.name .. ": bit-exact") + t:eq(a.meta.source.codec, c.codec, c.name .. ": meta.source.codec") + local dec = Raw.open(Bytes.reader(buffer.fromstring(c.data)), opts) :: any + for _, f in { frames // 2, 7, frames - 3, 1000, 0 } do + dec:seek(f / c.rate) + local b, n = dec:read(40) + t:check(n == math.min(40, frames - f) and same(b, ref, f * c.ch, n * c.ch), c.name .. ": seek to " .. f) + end +end +t:note("%d raw streams bit-exact with ffmpeg / vgmstream", #Cases) + +-- ------------------------------------------------------------------------------------------------ encoder +local function snr(x: buffer, y: buffer, count: number): number + local sig, err = 0, 0 + for i = 0, count - 1 do + local a = buffer.readf32(x, i * 4) + local e = a - buffer.readf32(y, i * 4) + sig += a * a + err += e * e + end + return if err == 0 then 200 else 10 * math.log10(sig / err) +end + +local audio = Types.Audio.new(Sig.rate, Sig.channels, Sig.frames) +buffer.writestring(audio.samples, 0, Sig.data) +for _, c in Ours do + local opts = (if c.name == "ima" then { codec = "ima" } else { codec = c.name, blockAlign = 512 }) :: any + opts.channels, opts.sampleRate = 2, Sig.rate + local out, err = Raw.encode(audio, opts) + t:check(out and buffer.tostring(out) == c.data, c.name .. ": encode is deterministic: " .. tostring(err)) + local ref = buffer.fromstring(c.ref) + local back = Raw.decode(Bytes.reader(buffer.fromstring(c.data)), opts) :: any + local n = buffer.len(ref) // 4 + t:eq(back.frames, n, c.name .. ": ffmpeg and we decode as many frames") + t:check(same(back.samples, ref, 0, n * 2), c.name .. ": ffmpeg decodes our stream as we do") + local s = snr(audio.samples, back.samples, Sig.frames * 2) + t:check(s > 20, string.format("%s: %.1f dB", c.name, s)) + t:note("encode %s: %.1f dB", c.name, s) + -- from a streaming Decoder too + local again = Raw.encode(Raw.open(Bytes.reader(out :: buffer), opts) :: any, opts) + t:check(again ~= nil, c.name .. ": encode from a Decoder") +end +do + local _, e1 = Raw.encode(audio, { codec = "psx" } :: any) + t:check(e1 and e1.code == Err.ARG, "encode psx: ARG") + local _, e2 = Raw.encode(audio, { codec = "ms", blockAlign = 8 }) + t:check(e2 and e2.code == Err.ARG, "encode: tiny blockAlign") + local _, e3 = Raw.encode(audio, { codec = "ima_wav", blockAlign = 514 }) + t:check(e3 and e3.code == Err.ARG, "encode ima_wav: blockAlign not a multiple of 4 * channels") + local _, e4 = Raw.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode {}") + local _, e5 = Raw.open(Bytes.reader(buffer.create(10)), { codec = "dsp" } :: any) + t:check(e5 and e5.code == Err.ARG, "open: unknown codec") + local _, e6 = Raw.open(Bytes.reader(buffer.create(10)), { channels = 0 }) + t:check(e6 and e6.code == Err.ARG, "open: 0 channels") + local _, e7 = Raw.open(Bytes.reader(buffer.create(10)), { codec = "ms", channels = 2, blockAlign = 9 }) + t:check(e7 and e7.code == Err.CORRUPT, "open: block too small") + local _, e8 = Raw.decode(Bytes.reader(buffer.create(100)), { maxFrames = 10 }) + t:check(e8 and e8.code == Err.LIMIT, "maxFrames") + local lo = Raw.decode(Bytes.reader(buffer.fromstring("\1\2\3")), { lowFirst = true }) :: any + local hi = Raw.decode(Bytes.reader(buffer.fromstring("\16\32\48"))) :: any + t:check(lo.frames == 6 and buffer.tostring(lo.samples) == buffer.tostring(hi.samples), "nibble order") +end + +-- ------------------------------------------------------------------------------------------------ api +do + local c = Cases[1] + local a, err = F.audio.load(c.data, { format = "adpcm", codec = c.codec, sampleRate = c.rate, channels = c.ch }) + t:check(a and a.frames == buffer.len(buffer.fromstring(c.ref)) // (2 * c.ch), "F.audio.load by format: " .. tostring(err)) + t:eq(F.detect(c.data, { name = "sound.ima" }), "adpcm", "F.detect by extension") + local out = F.save(a, nil, { format = "adpcm", codec = "ms" }) + t:check(out ~= nil and buffer.len(out) % 256 == 0, "F.save adpcm") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +local kinds = { "ima", "ima_wav", "ms", "ima_qt", "psx" } +local k = 0 +t:fuzz("open + read + seek", function(b: buffer) + k += 1 + local dec = Raw.open(Bytes.reader(b), { codec = kinds[k % 5 + 1] :: any, channels = k % 3 + 1, blockAlign = 64 + k % 7 * 4, interleave = 32 }) + if dec then + dec:read(100000) + dec:seek(dec.duration / 3) + dec:read(77) + end + return dec +end, samples, { mutations = 6 }) + +t:done() diff --git a/tests/codecs/adpcm.luau b/tests/codecs/adpcm.luau new file mode 100644 index 0000000..207a61e --- /dev/null +++ b/tests/codecs/adpcm.luau @@ -0,0 +1,228 @@ +-- codecs/adpcm tests: every decoder kernel of codecs/audio/Adpcm against a reference decoder, bit-exact as s16 +-- (tools/fixtures/adpcm.py: ADX from ffmpeg and PS-ADPCM / DSP from our Python encoders decoded by vgmstream, Apple +-- ima4 from ffmpeg, IMA nibble streams decoded by ffmpeg); ADX coefficients; the encoders (IMA nibbles, IMA WAV +-- blocks, MS blocks) decoded back with a signal-to-noise floor; the Decoder layouts (seeking matches a straight +-- read); a fuzz pass of random bytes through every kernel (ranges valid, contents random) and the layouts. +local T = require("@tests/T") +local Adpcm = require("@formats/codecs/audio/Adpcm") +local Decoder = require("@formats/codecs/audio/Adpcm/Decoder") +local Cases = require("@tests/gen/adpcm_codec") +local Sig = require("@tests/gen/adpcm_sig") + +local t = T.suite("adpcm codec") + +-- s16le reference vs interleaved f32: the count of differing samples and the first one +local function compare(out: buffer, ref: string, count: number): (number, number) + local r = buffer.fromstring(ref) + local bad, first = 0, -1 + for i = 0, count - 1 do + if buffer.readf32(out, i * 4) * 32768 ~= buffer.readi16(r, i * 2) then + bad += 1 + if first < 0 then + first = i + end + end + end + return bad, first +end + +-- ------------------------------------------------------------------------------------------------ kernels +for _, c in Cases do + local src = buffer.fromstring(c.data) + local ch, frames = c.ch, c.frames + local out = buffer.create((frames + 64) * ch * 4) + local st = buffer.create(8 * ch) + if c.kind == "adx" then + local c1, c2 = Adpcm.adxCoefs(c.cutoff, c.rate) + local nf = math.ceil(frames / 32) + for k = 0, ch - 1 do + Adpcm.adx(src, k * 18, 18 * ch, nf, c1, c2, c.v3, st, k * 8, out, k, ch) + end + elseif c.kind == "psx" then + Adpcm.psx(src, 0, 16, frames // 28, st, 0, out, 0, 1) + elseif c.kind == "dsp" then + local coefs = buffer.create(64) + for i, v in c.coefs do + buffer.writei32(coefs, (i - 1) * 4, v) + end + -- in pieces: the state carries over + Adpcm.dsp(src, 0, 14 * 9, coefs, 0, st, 0, out, 0, 1) + Adpcm.dsp(src, 8 * 9, frames - 14 * 9, coefs, 0, st, 0, out, 14 * 9, 1) + elseif c.kind == "ima_qt" then + for p = 0, frames // 64 - 1 do + for k = 0, ch - 1 do + Adpcm.imaQt(src, (p * ch + k) * 34, st, k * 8, out, p * 64 * ch + k, ch) + end + end + elseif c.kind == "ima" then + for k = 0, ch - 1 do + Adpcm.ima(src, 0, k, ch, frames, true, st, k * 8, out, k, ch) + end + end + local bad, first = compare(out, c.ref, frames * ch) + t:check(bad == 0, string.format("%s: %d of %d samples differ (first at %d)", c.name, bad, frames * ch, first)) +end +t:note("%d streams bit-exact with the reference decoders", #Cases) + +-- ADX coefficients: 500 Hz at 44.1 kHz / 22.05 kHz (CRI's single-precision derivation, as vgmstream) +do + local a1, a2 = Adpcm.adxCoefs(500, 44100) + t:check(a1 == 7334 and a2 == -3283, "adx coefs 44100: " .. a1 .. " " .. a2) + local z1, z2 = Adpcm.adxCoefs(0, 0) + t:check(z1 == 0 and z2 == 0, "adx coefs of rate 0") +end + +-- ------------------------------------------------------------------------------------------------ encoders +local function snr(x: buffer, y: buffer, count: number): number + local sig, err = 0, 0 + for i = 0, count - 1 do + local a = buffer.readf32(x, i * 4) + local e = a - buffer.readf32(y, i * 4) + sig += a * a + err += e * e + end + return if err == 0 then 200 else 10 * math.log10(sig / err) +end + +do + local x = buffer.fromstring(Sig.data) + local ch, n = Sig.channels, Sig.frames + -- IMA nibbles, both nibble orders + for _, hi in { true, false } do + local raw = 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, raw, 0, c, ch, hi) + end + local back = buffer.create(n * ch * 4) + local ds = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.ima(raw, 0, c, ch, n, hi, ds, c * 8, back, c, ch) + end + local s = snr(x, back, n * ch) + t:check(s > 20, string.format("ima encode (hi %s): %.1f dB", tostring(hi), s)) + t:check(buffer.readi32(st, 0) == buffer.readi32(ds, 0), "ima encoder and decoder end in the same state") + end + -- IMA WAV and MS blocks + for _, kind in { "ima_wav", "ms" } do + local ba = 512 + local spb = Decoder.blockFrames(kind, ba, ch) :: number + local blocks = (n + spb - 1) // spb + local raw = buffer.create(blocks * ba) + local st = buffer.create(8 * ch) + for b = 0, blocks - 1 do + if kind == "ms" then + Adpcm.msEncode(x, b * spb, n - b * spb, ch, spb, raw, b * ba) + else + Adpcm.imaWavEncode(x, b * spb, n - b * spb, ch, spb, st, raw, b * ba) + end + end + local back = buffer.create(blocks * spb * ch * 4) + local coefs = buffer.create(56) + for k = 0, 6 do + buffer.writei32(coefs, k * 8, Adpcm.MS_COEF1[k + 1]) + buffer.writei32(coefs, k * 8 + 4, Adpcm.MS_COEF2[k + 1]) + end + local scratch = buffer.create(20 * ch) + for b = 0, blocks - 1 do + local got + if kind == "ms" then + got = Adpcm.msBlock(raw, b * ba, ba, ch, spb, back, b * spb * ch, coefs, 7, scratch) + else + got = Adpcm.imaWav(raw, b * ba, ba, ch, spb, back, b * spb * ch) + end + t:eq(got, spb, kind .. ": block frames") + end + local s = snr(x, back, n * ch) + t:check(s > (if kind == "ms" then 24 else 20), string.format("%s encode: %.1f dB", kind, s)) + end +end + +-- ------------------------------------------------------------------------------------------------ Decoder layouts +local function readAll(dec: any, step: number): buffer + local out = buffer.create(dec.frames * dec.channels * 4) + local got = 0 + while true do + local b, n = dec:read(step) + if n == 0 then + break + end + buffer.copy(out, got * dec.channels * 4, b, 0, n * dec.channels * 4) + got += n + end + t:eq(got, dec.frames, "layout: frames read") + return out +end + +do + -- psx in rows of 64 bytes per channel (stereo), seeking back and forth lands on the same samples + local rng = T.rng(5) + local ch, il, rows = 2, 64, 40 + local data = buffer.create(il * ch * rows) + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, if i % 16 == 0 then rng(5) * 16 + rng(13) elseif i % 16 == 1 then 0 else rng(256)) + end + for _, kind in { "psx", "dsp" } do + local coefs = buffer.create(64 * ch) + for k = 0, 16 * ch - 1 do + buffer.writei32(coefs, k * 4, (k % 2 == 0) and 1800 or -700) + end + local il2 = if kind == "dsp" then 64 else il + local dec = Decoder.interleaved({ sampleRate = 8000, channels = ch, tags = {} }, { + kind = kind :: any, buf = data, offset = 0, size = buffer.len(data), interleave = il2, coefs = coefs }) + t:check(dec ~= nil, kind .. ": interleaved decoder") + local all = readAll(dec, 1000) + for _, f in { 500, 3, dec.frames - 7, 1234, 0 } do + dec:seek(f / 8000) + local b, n = dec:read(5) + local same = n == math.min(5, dec.frames - f) + for k = 0, n * ch - 1 do + same = same and buffer.readf32(b, k * 4) == buffer.readf32(all, (f * ch + k) * 4) + end + t:check(same, kind .. ": seek to " .. f .. " is exact") + end + end + -- a cut file: the whole frames of every channel + local dec = Decoder.interleaved({ sampleRate = 8000, channels = 2, tags = {} }, { + kind = "psx", buf = data, offset = 0, size = il * ch * 3 + il + 20, interleave = il }) + t:eq(dec.frames, 3 * 4 * 28 + 28, "cut interleaved: the whole frames both channels have") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("kernels", function(b: buffer) + local n = buffer.len(b) + local out = buffer.create(64 * 64 * 4) + local st = buffer.create(64) + local coefs = buffer.create(64) + for k = 0, 15 do + buffer.writei32(coefs, k * 4, if n > k then buffer.readi8(b, k) * 64 else 0) + end + if n >= 18 then + Adpcm.adx(b, 0, 18, 1, 7334, -3283, n % 2 == 0, st, 0, out, 0, 1) + end + if n >= 16 then + Adpcm.psx(b, 0, 16, 1, st, 8, out, 0, 1) + end + if n >= 8 then + Adpcm.dsp(b, 0, 14, coefs, 0, st, 16, out, 0, 1) + end + if n >= 34 then + Adpcm.imaQt(b, 0, st, 24, out, 0, 1) + end + if n >= 1 then + Adpcm.ima(b, 0, 0, 1, math.min(n * 2, 1000), true, st, 32, out, 0, 1) + end + Adpcm.imaWav(b, 0, n, 2, 1017, buffer.create(1017 * 2 * 4), 0) + Adpcm.msBlock(b, 0, n, 2, 1012, buffer.create(1012 * 2 * 4), 0, coefs, 8, buffer.create(40)) + local dec = Decoder.interleaved({ sampleRate = 8000, channels = 2, tags = {} }, { kind = "adx", buf = b, offset = 0, size = n, interleave = 18, c1 = 7334, c2 = -3283 }) + if dec then + dec:read(100000) + dec:seek(0) + end + return true +end, samples, { mutations = 6, garbage = 60 }) +t:done() diff --git a/tools/fixtures/_adpcm.py b/tools/fixtures/_adpcm.py new file mode 100644 index 0000000..6078a36 --- /dev/null +++ b/tools/fixtures/_adpcm.py @@ -0,0 +1,352 @@ +# Shared helpers for the ADPCM fixture generators (adpcm, adx, vag, brstm): small Python ADPCM encoders that build the +# game containers ffmpeg cannot write (Sony VAG, Nintendo BRSTM / BCSTM / BFSTM, Simon & Schuster KVAG); the files are +# decoded by vgmstream / ffmpeg as the references, so these encoders only need to be valid, not good. +# A = _adpcm.load() +# A.ima_encode(samples, ch, high_first=False) -> raw IMA nibble stream (state 0 / 0; channels interleaved by nibble) +# A.kvag(samples, rate, ch) -> a KVAG file (IMA, high nibble first) +# A.psx_encode(samples) -> bytes of 16-byte PS-ADPCM frames (mono); A.vag(samples, rate, name, loop=None) +# A.dsp_encode(samples, coefs) -> bytes of 8-byte DSP frames (mono); A.DSP_COEFS: the 16 coefficients used +# A.rstm(samples, rate, ch, kind="RSTM"|"CSTM"|"FSTM", loop=None, block=0x2000, le=None, codec="dsp"|"pcm16"|"pcm8") +# A.s16(floats) -> clipped ints +import math, struct, sys + +IMA_STEP = [ + 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] +IMA_INDEX = [-1, -1, -1, -1, 2, 4, 6, 8] + + +def load(): + return sys.modules[__name__] + + +def s16(floats): + return [max(-32768, min(32767, int(math.floor(v * 32768 + 0.5)))) for v in floats] + + +def clamp16(v): + return -32768 if v < -32768 else 32767 if v > 32767 else v + + +def ima_step(pred, index, nib): + step = IMA_STEP[index] + d = step >> 3 + if nib & 1: + d += step >> 2 + if nib & 2: + d += step >> 1 + if nib & 4: + d += step + pred = clamp16(pred - d if nib & 8 else pred + d) + index = max(0, min(88, index + IMA_INDEX[nib & 7])) + return pred, index + + +def ima_nibble(pred, index, x): + best = None + for nib in range(16): + p, _ = ima_step(pred, index, nib) + e = abs(x - p) + if best is None or e < best[0]: + best = (e, nib) + return best[1] + + +def ima_encode(samples, ch, high_first=False): + ints = s16(samples) + st = [[0, 0] for _ in range(ch)] + nibs = [] + for i, x in enumerate(ints): + c = i % ch + n = ima_nibble(st[c][0], st[c][1], x) + st[c][0], st[c][1] = ima_step(st[c][0], st[c][1], n) + nibs.append(n) + if len(nibs) % 2: + nibs.append(0) + out = bytearray() + for k in range(0, len(nibs), 2): + a, b = nibs[k], nibs[k + 1] + out.append((a << 4 | b) if high_first else (b << 4 | a)) + return bytes(out) + + +def kvag(samples, rate, ch): + data = ima_encode(samples, ch, high_first=True) # DVI order: the high nibble first (ffmpeg adpcm_ima_ssi, vgmstream) + return b"KVAG" + struct.pack("> 8; pick the nibble closest to x + want = ((x << 8) - pred) / (1 << (20 - shift)) + n = max(-8, min(7, int(round(want)))) + s = (n * (1 << (20 - shift)) + pred) >> 8 + cs = clamp16(s) + err += (x - cs) ** 2 + nibs.append(n & 15) + a, b = s, a + if best is not None and err >= best[0]: + break + else: + if best is None or err < best[0]: + best = (err, f << 4 | shift, nibs, a, b) + return best + + +def psx_encode(samples, loop=None): + """PS-ADPCM frames (mono ints) after the usual blank frame; loop = (start frame, end frame) sets the flags""" + out = bytearray(16) + h1 = h2 = 0 + n = (len(samples) + 27) // 28 + for k in range(n): + xs = samples[k * 28:(k + 1) * 28] + xs = xs + [0] * (28 - len(xs)) + _, head, nibs, h1, h2 = psx_frame(xs, h1, h2) + flag = 0 + if loop: + if k == loop[0]: + flag = 6 + elif k == loop[1] - 1: + flag = 3 + elif loop[0] < k < loop[1] - 1: + flag = 2 + elif k == n - 1: + flag = 1 + out += bytes([head, flag]) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, 28, 2)) + return bytes(out) + + +def vag(samples, rate, name=b"formats-luau", loop=None): + data = psx_encode(s16(samples), loop) + head = b"VAGp" + struct.pack(">IIII", 0x20, 0, len(data), rate) + b"\0" * 12 + name[:16].ljust(16, b"\0") + return head + data + + +# ------------------------------------------------------------------------------------------------ Nintendo DSP +DSP_COEFS = [0, 0, 2048, 0, 0, 2048, 4096, -2048, 3600, -1700, 3000, -1100, 1024, 0, 3900, -1950] + + +def dsp_frame(xs, h1, h2, coefs): + best = None + for p in range(8): + c1, c2 = coefs[2 * p], coefs[2 * p + 1] + for sc in range(12): + scale = 1 << sc + a, b = h1, h2 + err = 0 + nibs = [] + for x in xs: + base = 1024 + c1 * a + c2 * b + want = ((x << 11) - base) / (scale << 11) + n = max(-8, min(7, int(round(want)))) + s = clamp16(((n * scale) << 11) + base >> 11) + err += (x - s) ** 2 + nibs.append(n & 15) + a, b = s, a + if best is not None and err >= best[0]: + break + else: + if best is None or err < best[0]: + best = (err, p << 4 | sc, nibs, a, b) + return best + + +def dsp_encode(samples, coefs=DSP_COEFS): + out = bytearray() + h1 = h2 = 0 + for k in range(0, len(samples), 14): + xs = samples[k:k + 14] + n = len(xs) + xs = xs + [0] * (14 - n) + _, head, nibs, a, b = dsp_frame(xs, h1, h2, coefs) + out.append(head) + out += bytes(nibs[i] << 4 | nibs[i + 1] for i in range(0, 14, 2)) + h1, h2 = a, b + return bytes(out) + + +def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec="dsp", coefs=DSP_COEFS): + """a BRSTM (kind RSTM, big-endian), BCSTM (CSTM, little-endian) or BFSTM (FSTM, big-endian unless le) file""" + ints = s16(samples) + frames = len(ints) // ch + chans = [ints[c::ch] for c in range(ch)] + if codec == "dsp": + enc = [dsp_encode(x, coefs) for x in chans] + spb = block // 8 * 14 + elif codec == "pcm16": + big = kind == "RSTM" or (kind == "FSTM" and not le) + enc = [b"".join(struct.pack(">h" if big else "> 8) & 255 for v in x) for x in chans] + spb = block + nblocks = (frames + spb - 1) // spb + last_samples = frames - (nblocks - 1) * spb + last_size = len(enc[0]) - (nblocks - 1) * block + last_padded = (last_size + 31) // 32 * 32 + data = bytearray() + for b in range(nblocks): + for c in range(ch): + part = enc[c][b * block:(b + 1) * block] + if b == nblocks - 1: + part = part.ljust(last_padded, b"\0") + data += part + codec_id = {"pcm8": 0, "pcm16": 1, "dsp": 2}[codec] + ls, le_ = (loop if loop else (0, frames)) + if kind == "RSTM": + info = struct.pack(">BBBBHHIIIIIIIIIIII", codec_id, 1 if loop else 0, ch, 0, rate, 0, ls, frames, 0, nblocks, + block, spb, last_size, last_samples, last_padded, spb, 4, 0) + # HEAD: 3 references, the stream info, track info, channel info + + def ref(off): + return struct.pack(">II", 0x01000000, off) + p_info = 0x18 + p_track = p_info + len(info) + track_table = struct.pack(">BBBB", 1, 0, 0, 0) # 1 track, type 0 + p_trackent = p_track + 4 + 8 + track_ent = struct.pack(">BBBB", 127, 64, 0, 0) + struct.pack(">I", 0) + struct.pack(">BBBB", ch, 0, 1, 0) + track_blob = track_table + ref(p_trackent) + track_ent + p_chan = p_track + len(track_blob) + chan_head = struct.pack(">BBBB", ch, 0, 0, 0) + p_chinfo = p_chan + 4 + 8 * ch + chan_refs = b"" + chan_infos = b"" + for c in range(ch): + me = p_chinfo + len(chan_infos) + chan_refs += ref(me) + adp = struct.pack(">16h", *coefs) + struct.pack(">HHhhHhhH", 0, enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0) + chan_infos += ref(me + 8) + adp + body = info + track_blob + chan_head + chan_refs + chan_infos + body = ref(p_info) + ref(p_track) + ref(p_chan) + body + head = b"HEAD" + struct.pack(">I", 0) + body + head = head.ljust((len(head) + 31) // 32 * 32, b"\0") + head = head[:4] + struct.pack(">I", len(head)) + head[8:] + adpc_body = b"".join(struct.pack(">hh", 0, 0) * ch for _ in range(nblocks)) + adpc = b"ADPC" + struct.pack(">I", 0) + adpc_body + adpc = adpc.ljust((len(adpc) + 31) // 32 * 32, b"\0") + adpc = adpc[:4] + struct.pack(">I", len(adpc)) + adpc[8:] + hsize = 0x40 + o_head = hsize + o_adpc = o_head + len(head) + o_data = o_adpc + len(adpc) + datac = b"DATA" + struct.pack(">II", len(data) + 0x20, 0x18) + b"\0" * 0x14 + bytes(data) + start = o_data + 0x20 + head = bytearray(head) + struct.pack_into(">I", head, 8 + 8 * 3 + 0x10, start) # data offset (absolute) + total = o_data + len(datac) + hdr = b"RSTM" + struct.pack(">HHIHH", 0xFEFF, 0x0100, total, hsize, 2) + struct.pack(">IIIIII", o_head, len(head), o_adpc, + len(adpc), o_data, len(datac)) + hdr = hdr.ljust(hsize, b"\0") + return hdr + bytes(head) + adpc + datac + # CSTM / FSTM + E = ">" if (kind == "FSTM" and not le) else "<" + + def ref(t, off): + return struct.pack(E + "HHi", t, 0, off) + # INFO: refs (stream info, track table, channel table), stream info, channel table, channel infos, dsp infos + stream_info = struct.pack(E + "BBBB", codec_id, 1 if loop else 0, ch, 0) + struct.pack( + E + "IIIIIIIIIII", rate, ls, frames, nblocks, block, spb, last_size, last_samples, last_padded, 4 * ch, spb) + stream_info += ref(0x1F00, 0x18) # sample data: DATA + 8 + 0x18 + p_stream = 0x18 + p_chtab = p_stream + len(stream_info) + chtab = struct.pack(E + "I", ch) + p_chinfo = p_chtab + 4 + 8 * ch + infos = b"" + adps = b"" + for c in range(ch): + chtab += ref(0x4102, p_chinfo + 8 * c - p_chtab) + p_adp = p_chinfo + 8 * ch + for c in range(ch): + me = p_chinfo + 8 * c + adp_at = p_adp + len(adps) + infos += ref(0x0300, adp_at - me) if codec == "dsp" else ref(0, -1) + adps += struct.pack(E + "16h", *coefs) + struct.pack(E + "HhhHhhH", enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0) + body = ref(0x4100, p_stream) + ref(0, -1) + ref(0x0101, p_chtab) + stream_info + chtab + infos + adps + info = b"INFO" + struct.pack(E + "I", 0) + body + info = info.ljust((len(info) + 31) // 32 * 32, b"\0") + info = info[:4] + struct.pack(E + "I", len(info)) + info[8:] + seek = b"SEEK" + struct.pack(E + "I", 0) + b"".join(struct.pack(E + "hh", 0, 0) * ch for _ in range(nblocks)) + seek = seek.ljust((len(seek) + 31) // 32 * 32, b"\0") + seek = seek[:4] + struct.pack(E + "I", len(seek)) + seek[8:] + datac = b"DATA" + struct.pack(E + "I", len(data) + 0x20) + b"\0" * 0x18 + bytes(data) + hsize = 0x40 + o_info = hsize + o_seek = o_info + len(info) + o_data = o_seek + len(seek) + total = o_data + len(datac) + ver = 0x02000000 if kind == "CSTM" else 0x00040000 + hdr = kind.encode() + (b"\xfe\xff" if E == ">" else b"\xff\xfe") + struct.pack(E + "HII", hsize, ver, total) + hdr += struct.pack(E + "HH", 3, 0) + hdr += struct.pack(E + "HHII", 0x4000, 0, o_info, len(info)) + hdr += struct.pack(E + "HHII", 0x4001, 0, o_seek, len(seek)) + hdr += struct.pack(E + "HHII", 0x4002, 0, o_data, len(datac)) + hdr = hdr.ljust(hsize, b"\0") + return hdr + info + seek + datac + + +# ------------------------------------------------------------------------------------------------ references +def wav_pcm(data): + """(rate, channels, s16le bytes) of a 16-bit PCM WAV (vgmstream's output)""" + p = 12 + rate = ch = None + while p + 8 <= len(data): + cid, size = data[p:p + 4], struct.unpack_from("I", d, p + 4)[0] + if cid == b"SSND": + off = struct.unpack_from(">I", d, p + 8)[0] + return d[p + 16 + off:p + 8 + size] + p += 8 + size + (size & 1) + raise ValueError("no SSND") + + +def wav_data(d): + p = 12 + fmt = None + while p + 8 <= len(d): + cid, size = d[p:p + 4], struct.unpack_from("H", f, 2)[0] + 4 + rate, frames, cutoff, ver = struct.unpack_from(">IIHH", f, 8) + _, rch, ref = D.vgdecode(ctx, f, "adx") + assert rch == ch and len(ref) == frames * ch * 2, (len(ref), frames) + codec.append(dict(name=name, kind="adx", data=f[start:], ch=ch, frames=frames, ref=ref, rate=rate, + cutoff=cutoff, v3=ver == 0x0300)) + + # PS-ADPCM in a VAG (mono) + v = D.vag(mono, RATE) + _, _, ref = D.vgdecode(ctx, v, "vag") + codec.append(dict(name="psx", kind="psx", data=v[0x30:], ch=1, frames=len(ref) // 2, ref=ref)) + raw.append(dict(name="psx", codec="psx", data=v[0x30:], rate=RATE, ch=1, ref=ref)) + + # DSP in a mono BRSTM (one block holds everything) + ints = D.s16(mono) + dspdata = D.dsp_encode(ints) + f = D.rstm(mono, RATE, 1, "RSTM", block=(len(dspdata) + 31) // 32 * 32) + _, _, ref = D.vgdecode(ctx, f, "brstm") + assert len(ref) == len(ints) * 2 + codec.append(dict(name="dsp", kind="dsp", data=dspdata, ch=1, frames=len(ints), ref=ref, coefs=D.DSP_COEFS)) + + # Apple ima4 (AIFF-C) + for name, w, ch in (("ima_qt-mono", w1, 1), ("ima_qt-stereo", w2, 2)): + f = D.ffencode(ctx, w, ["-c:a", "adpcm_ima_qt", "-f", "aiff"], "aiff") + data = aiff_ssnd(f) + ref = D.ffs16(ctx, f, "aiff") + codec.append(dict(name=name, kind="ima_qt", data=data, ch=ch, frames=len(ref) // (2 * ch), ref=ref)) + raw.append(dict(name=name, codec="ima_qt", data=data, rate=RATE, ch=ch, ref=ref)) + + # IMA nibble streams (KVAG, high nibble first) + for name, sig, ch in (("ima-mono", mono, 1), ("ima-stereo", stereo, 2)): + f = D.kvag(sig, RATE, ch) + ref = D.ffs16(ctx, f, "vag", fmt="kvag") + codec.append(dict(name=name, kind="ima", data=f[14:], ch=ch, frames=len(ref) // (2 * ch), ref=ref)) + raw.append(dict(name=name, codec="ima", data=f[14:], rate=RATE, ch=ch, ref=ref)) + + # MS ADPCM / IMA WAV blocks (ffmpeg), as raw block streams + for name, codec_, w, ch in (("ms-stereo", "adpcm_ms", w2, 2), ("ms-mono", "adpcm_ms", w1, 1), + ("ima_wav-stereo", "adpcm_ima_wav", w2, 2)): + f = D.ffencode(ctx, w, ["-c:a", codec_, "-f", "wav"], "wav") + fmt, data = wav_data(f) + ba = struct.unpack_from(" containers ffmpeg reads -> ffmpeg's decode; the test decodes the same bytes itself + A.emit_signal(ctx, "adpcm_sig", stereo, RATE, 2) + ours = [] + for codec_, opts in (("ima", '{ codec = "ima" }'), ("ms", '{ codec = "ms", blockAlign = 512 }'), + ("ima_wav", '{ codec = "ima_wav", blockAlign = 512 }')): + data = A.encode_luau(ctx, "audio/adpcm", "adpcm_sig", opts) + if codec_ == "ima": + f = b"KVAG" + struct.pack("