From 363b14932fa91ea431cadcea6a91dc3e4092e332 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:10:23 -0500 Subject: [PATCH 1/9] 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(" Date: Sat, 31 Oct 2026 14:17:57 -0500 Subject: [PATCH 2/9] ws-audio2: audio/adx (CRI ADX read / write, loops) and audio/vag (VAGp / VAGi / KVAG read, VAGp / VAGi write) Bit-exact with vgmstream (ADX, PS-ADPCM) and ffmpeg (KVAG IMA); ADX and PS-ADPCM encoders in codecs/audio/Adpcm. --- src/Formats/Registry.luau | 24 +++ src/Formats/audio/adx/init.luau | 237 +++++++++++++++++++++++ src/Formats/audio/vag/init.luau | 231 ++++++++++++++++++++++ src/Formats/codecs/audio/Adpcm/init.luau | 120 ++++++++++++ tests/audio/_adpcm.luau | 59 ++++++ tests/audio/adx.luau | 90 +++++++++ tests/audio/vag.luau | 89 +++++++++ tools/fixtures/_adpcm.py | 14 +- tools/fixtures/adx.py | 69 +++++++ tools/fixtures/vag.py | 55 ++++++ 10 files changed, 987 insertions(+), 1 deletion(-) create mode 100644 src/Formats/audio/adx/init.luau create mode 100644 src/Formats/audio/vag/init.luau create mode 100644 tests/audio/_adpcm.luau create mode 100644 tests/audio/adx.luau create mode 100644 tests/audio/vag.luau create mode 100644 tools/fixtures/adx.py create mode 100644 tools/fixtures/vag.py diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 790e6f6..ab78992 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -170,6 +170,18 @@ local list: { Entry } = { return require("@formats/audio/adpcm") end, }, + { + name = "adx", + category = "audio", + path = "audio/adx", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + 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, loops = true, channels = 8 }, + load = function() + return require("@formats/audio/adx") + end, + }, { name = "aiff", category = "audio", @@ -254,6 +266,18 @@ local list: { Entry } = { return require("@formats/audio/opus") end, }, + { + name = "vag", + category = "audio", + path = "audio/vag", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + 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, loops = true, channels = 2 }, + load = function() + return require("@formats/audio/vag") + end, + }, { name = "voc", category = "audio", diff --git a/src/Formats/audio/adx/init.luau b/src/Formats/audio/adx/init.luau new file mode 100644 index 0000000..40154f8 --- /dev/null +++ b/src/Formats/audio/adx/init.luau @@ -0,0 +1,237 @@ +--!strict +-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in +-- formats-luau; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), +-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder +-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), +-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, +-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and +-- exponential (4) encoding types, AHX. +-- +-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) +-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) + +-- ------------------------------------------------------------------------------------------------ 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 Adx = { + name = "adx", + category = "audio", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + 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, loops = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Loop = { start: number, stop: number } +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} +export type EncodeOptions = { + loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none + cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FRAME = 18 + +-- ------------------------------------------------------------------------------------------------ sniff +function Adx.sniff(r: Bytes.Reader): number + if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then + return 0 + end + local off = r:peekU8(2) * 256 + r:peekU8(3) + return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Adx.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "ADX holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local loop = o.loop + if loop == nil then + local v = value :: any + local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop + loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil) + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + local cutoff = o.cutoff or 500 + if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then + return nil, Err.new(Err.ARG, "bad cutoff") + end + cutoff = math.floor(cutoff) + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local hist = if ch > 1 then 4 * ch else 8 + local start = 0x18 + hist + (if loop then 0x18 else 0) + 6 + start = (start + 3) // 4 * 4 + local nframes = (n + 31) // 32 + local w = Bytes.writer(start + (nframes + 1) * FRAME * ch) + w:u16be(0x8000) + w:u16be(start - 4) + w:u8(3) + w:u8(FRAME) + w:u8(4) + w:u8(ch) + w:u32be(rate) + w:u32be(n) + w:u16be(cutoff) + w:u16be(0x0400) + w:u32be(0) + w:fill(0, hist) + if loop then + local bytesAt = function(f: number): number + return start + (f // 32) * FRAME * ch + end + w:u16be(0) + w:u16be(1) + w:u32be(1) + w:u32be(loop.start) + w:u32be(bytesAt(loop.start)) + w:u32be(loop.stop) + w:u32be(bytesAt(loop.stop + 31)) + end + w:fill(0, start - 6 - w.pos) + w:string("(c)CRI") + local at = w:reserve(nframes * FRAME * ch) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch) + end + w.pos = at + nframes * FRAME * ch + -- the end marker: scale 0x8001, then the padding size + w:u16be(0x8001) + w:u16be(FRAME - 4) + w:fill(0, FRAME - 4) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Adx.open(r: Bytes.Reader, _opts: any?): (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 + if Adx.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an ADX file") + end + local h = r:sub(0) + local copyright = (h:seek(2) and h:u16be()) or 0 + local start = copyright + 4 + local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8() + local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be() + if h.err then + return nil, h.err + end + if version == 0x0408 or version == 0x0409 then + return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)") + end + if enc ~= 3 then + return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else "")) + end + if fsize ~= FRAME or bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits)) + end + if ch < 1 or ch > 8 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version)) + end + local size = r.limit - r.base - start + if size < 0 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + -- loop points and the initial history (vgmstream's reading of the extra header fields) + local hist: { number }? = nil + local loopsAt: number? = nil + if version == 0x0300 then + if start - 6 >= 0x14 + 0x18 then + loopsAt = 0x14 + end + elseif version == 0x0400 then + local hsize = if ch > 1 then 4 * ch else 8 + hist = {} + for c = 0, ch - 1 do + local hh = r:sub(0x18 + c * 4, 4) + local h1, h2 = hh:i16be(), hh:i16be() + hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2 + end + local ainf = 0 + local ai = r:sub(0x18 + hsize + 4, 8) + if ai:string(4) == "AINF" then + ainf = ai:u32be() + end + if start - ainf - 6 >= 0x18 + hsize + 0x18 then + loopsAt = 0x18 + hsize + end + end + local loopTable: { start: number, stop: number }? = nil + if loopsAt then + local l = r:sub(loopsAt + 4, 0x14) + local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be() + if not l.err and flag ~= 0 and le > ls then + loopTable = { start = ls, stop = le } + end + end + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable } + local d, err = Decoder.interleaved(dec, { + kind = "adx", + buf = r.buf, + offset = r.base + start, + size = size, + interleave = FRAME, + frames = frames, + c1 = c1, + c2 = c2, + v3 = version == 0x0300, + hist = hist, + }) + if not d then + return nil, err + end + d.bitrate = rate * FRAME * ch * 8 // 32 + return d, nil +end + +return Adx diff --git a/src/Formats/audio/vag/init.luau b/src/Formats/audio/vag/init.luau new file mode 100644 index 0000000..86c0e37 --- /dev/null +++ b/src/Formats/audio/vag/init.luau @@ -0,0 +1,231 @@ +--!strict +-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same +-- extension), over codecs/audio/Adpcm. New in formats-luau; the header variants and the PS-ADPCM decoding follow +-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono +-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / +-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. +-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame +-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game +-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). +-- +-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) +-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) + +-- ------------------------------------------------------------------------------------------------ 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 Vag = { + name = "vag", + category = "audio", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + 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, loops = true, channels = 2 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Loop = { start: number, stop: number } +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} +export type EncodeOptions = { + loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the + -- source's meta.source.loop, else none + name: string?, -- the 16-byte name field (default: tags.title) + interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEVAG = { [0x00020001] = true, [0x00030000] = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Vag.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vag.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 2 then + return nil, Err.new(Err.ARG, "VAG holds mono or stereo") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local il = o.interleave or 2048 + 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 + local loop = o.loop + local v = value :: any + if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then + loop = v.meta.source.loop + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + local nf = (n + 27) // 28 -- data frames (after the blank one) + local ls, le = -1, -1 + if loop then + if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1 + if le <= ls then + return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames") + end + end + local chBytes = (nf + 1) * 16 + local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il + local start = if ch == 1 then 0x30 else 0x800 + local out = buffer.create(start + stride * ch) + local title = o.name or (a.tags and a.tags.title) or "" + buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi") + buffer.writeu32(out, 4, bit32.byteswap(0x20)) + if ch == 2 then + buffer.writeu32(out, 8, il) + end + buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride)) + buffer.writeu32(out, 0x10, bit32.byteswap(rate)) + buffer.writestring(out, 0x20, string.sub(title, 1, 16)) + local st = buffer.create(8 * ch) + local plane = buffer.create(chBytes) + for c = 0, ch - 1 do + buffer.fill(plane, 0, 0) + Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16) + for k = 0, nf - 1 do + local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0 + if not loop and k == nf - 1 then + flag = 1 + end + buffer.writeu8(plane, 16 + k * 16 + 1, flag) + end + if ch == 1 then + buffer.copy(out, start, plane, 0, chBytes) + else + for b = 0, stride // il - 1 do + local take = math.clamp(chBytes - b * il, 0, il) + if take > 0 then + buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take) + end + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end +-- flag 3), or nil +local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? + local ls, le = -1, -1 + for k = 0, frames - 1 do + local off = p + (k * 16) // il * il * ch + (k * 16) % il + local flag = bit32.band(buffer.readu8(buf, off + 1), 15) + if flag == 6 and ls < 0 then + ls = k * 28 + elseif flag == 3 and le < 0 then + le = k * 28 + 28 + if ls >= 0 then + break + end + end + end + return if ls >= 0 and le > ls then { start = ls, stop = le } else nil +end + +function Vag.open(r: Bytes.Reader, _opts: any?): (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 h = r:sub(0) + local magic = h:string(4) + local total = r.limit - r.base + if magic == "KVAG" then + local size, rate, stereo = h:u32le(), h:u32le(), h:u16le() + if h.err then + return nil, h.err + end + if rate < 1 or stereo > 1 then + return nil, Err.new(Err.CORRUPT, "bad KVAG header") + end + local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" } + local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true }) + if d then + d.bitrate = rate * 4 * (stereo + 1) + end + return d, err + end + if magic ~= "VAGp" and magic ~= "VAGi" then + return nil, Err.new(Err.CORRUPT, "not a VAG file") + end + local version, il = h:u32be(), h:u32le() + local chSize, rate = h:u32be(), h:u32be() + local name = r:sub(0x20, 16):cstring(16) + if h.err then + return nil, h.err + end + if HEVAG[version] then + return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)") + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local ch, start = 1, 0x30 + if magic == "VAGi" then + ch, start = 2, 0x800 + if il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. il) + end + else + il = 16 + end + if total < start then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + local size = math.min(chSize * ch, total - start) + local p = r.base + start + local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16) + local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops + local tags = {} + if name ~= "" then + tags.title = name + end + local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop } + local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 }) + if d then + d.bitrate = rate * 16 * 8 * ch // 28 + end + return d, err +end + +return Vag diff --git a/src/Formats/codecs/audio/Adpcm/init.luau b/src/Formats/codecs/audio/Adpcm/init.luau index 56eab9c..68b8d25 100644 --- a/src/Formats/codecs/audio/Adpcm/init.luau +++ b/src/Formats/codecs/audio/Adpcm/init.luau @@ -565,4 +565,124 @@ function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: numbe end end +-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and +-- the nibbles in nibs when given; returns the error and the new history +local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) + local err = 0 + for k = 1, 32 do + local pred = (c1 * h1 + c2 * h2) // 4096 + local e = xs[k] - pred + local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale) + n = math.clamp(n, -8, 7) + local s = math.clamp(n * scale + pred, -32768, 32767) + err += (xs[k] - s) * (xs[k] - s) + if nibs then + nibs[k] = band(n, 15) + end + h2 = h1 + h1 = s + end + return err, h1, h2 +end + +-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame +-- past count is padded with silence. State as Adpcm.adx. +function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, + out: buffer, p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(32, 0) + local nibs = table.create(32, 0) + for f = 0, (count + 31) // 32 - 1 do + local peak = 0 + local a, b = h1, h2 + for k = 1, 32 do + local i = f * 32 + k - 1 + local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + v[k] = s + peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096)) + b = a + a = s + end + -- the scale that covers the open-loop residual peak, and a few around it, closed loop + local base = math.max(1, (peak + 6) // 7) + local best, bestErr = base, math.huge + for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do + local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF) + local e = adxTrial(v, sc, c1, c2, h1, h2, nil) + if e < bestErr then + best, bestErr = sc, e + end + end + local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs) + h1, h2 = n1, n2 + local fp = p + f * pstride + writeu8(out, fp, rshift(best - 1, 8)) + writeu8(out, fp + 1, band(best - 1, 255)) + for k = 0, 15 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2]) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM +-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is +-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. +function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(28, 0) + local nibs = table.create(28, 0) + for f = 0, (count + 27) // 28 - 1 do + for k = 1, 28 do + local i = f * 28 + k - 1 + v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + end + local bestErr, bestHead = math.huge, 0 + for fi = 1, 5 do + for shift = 0, 12 do + local mul = 2 ^ (20 - shift) + local a, b = h1, h2 + local err = 0 + for k = 1, 28 do + local pred = psxPred(fi, a, b) + local n = floor((v[k] * 256 - pred) / mul + 0.5) + n = if n > 7 then 7 elseif n < -8 then -8 else n + local s = (n * mul + pred) // 256 + local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s + err += (v[k] - c) * (v[k] - c) + if err >= bestErr then + break + end + b = a + a = s + end + if err < bestErr then + bestErr, bestHead = err, (fi - 1) * 16 + shift + end + end + end + -- the winner again, for its nibbles and history + local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) + local mul = 2 ^ (20 - shift) + for k = 1, 28 do + local pred = psxPred(fi, h1, h2) + local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7) + nibs[k] = band(n, 15) + h2 = h1 + h1 = (n * mul + pred) // 256 + end + local fp = p + f * pstride + writeu8(out, fp, bestHead) + writeu8(out, fp + 1, 0) + for k = 0, 13 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + return Adpcm diff --git a/tests/audio/_adpcm.luau b/tests/audio/_adpcm.luau new file mode 100644 index 0000000..1f61f2c --- /dev/null +++ b/tests/audio/_adpcm.luau @@ -0,0 +1,59 @@ +-- tests/audio/_adpcm: shared checks of the ADPCM game-audio formats (adx, vag, brstm): a file against the reference +-- decoder's s16le output, bit-exact, through decode() and through open() with seeks (forward into unvisited packets, +-- back, the end), loop points; the SNR of an encoder's round trip. +local Bytes = require("@formats/core/Bytes") + +local H = {} + +-- same(f32 buffer, s16le reference buffer, first reference sample, count) -> true when every sample is equal +function H.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 + +function H.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 + +-- check(t, Fmt, c, opts?): c = { name, data, rate, ch, frames?, ref, loopStart?, loopEnd? } +function H.check(t: any, Fmt: any, c: any, opts: any?) + local ref = buffer.fromstring(c.ref) + local frames = buffer.len(ref) // (2 * c.ch) + local a, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts) + t:check(a, c.name .. ": decode: " .. tostring(err)) + if not a then + return + end + t:eq(a.frames, frames, c.name .. ": frames") + t:eq(a.channels, c.ch, c.name .. ": channels") + t:eq(a.sampleRate, c.rate, c.name .. ": rate") + t:check(H.same(a.samples, ref, 0, frames * c.ch), c.name .. ": bit-exact with the reference") + t:eq(a.meta.source.format, Fmt.name, c.name .. ": meta.source.format") + if c.loopStart then + local l = a.meta.source.loop + t:check(l and l.start == c.loopStart and l.stop == c.loopEnd, c.name .. ": loop " .. tostring(l and l.start) .. " " .. tostring(l and l.stop)) + else + t:eq(a.meta.source.loop, nil, c.name .. ": no loop") + end + -- open: seek forward first (unvisited packets), then back, then the end + local dec = Fmt.open(Bytes.reader(buffer.fromstring(c.data)), opts) :: any + for _, f in { frames * 3 // 4, 5, frames // 2 + 13, frames - 2, 0, 4097 } do + f = math.min(f, frames) + dec:seek(f / c.rate) + local b, n = dec:read(50) + t:check(n == math.min(50, frames - f) and H.same(b, ref, f * c.ch, n * c.ch), c.name .. ": seek to " .. f) + end +end + +return H diff --git a/tests/audio/adx.luau b/tests/audio/adx.luau new file mode 100644 index 0000000..aa8b480 --- /dev/null +++ b/tests/audio/adx.luau @@ -0,0 +1,90 @@ +-- audio/adx tests: ffmpeg's ADX files (version 3) and a version 4 file with history and loop points, bit-exact with +-- vgmstream (tools/fixtures/adx.py) through decode and open with seeks; our encoder's files as vgmstream decodes them +-- (equal to our decode, loops reported) and their quality; header errors; the api; the fuzz pass. +local T = require("@tests/T") +local Adx = require("@formats/audio/adx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/adx_cases") +local Ours = require("@tests/gen/adx_ours") +local Sig = require("@tests/gen/adx_sig") + +local t = T.suite("adx") +t:eq(Adx.name, "adx", "name") +t:check(Adx.caps.decode and Adx.caps.encode, "caps") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Adx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + H.check(t, Adx, c) +end +t:note("%d files bit-exact with vgmstream", #Cases) + +-- ------------------------------------------------------------------------------------------------ encoder +local audio = Types.Audio.new(Sig.rate, Sig.channels, Sig.frames) +buffer.writestring(audio.samples, 0, Sig.data) +for _, c in Ours do + H.check(t, Adx, c) + local a = Adx.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + local s = H.snr(audio.samples, a.samples, Sig.frames * Sig.channels) + t:check(s > 22, string.format("ours %s: %.1f dB", c.name, s)) + t:note("encode %s: %.1f dB", c.name, s) + -- deterministic, and the same from a streaming Decoder; the loop is kept through a re-encode + local again = Adx.encode(a) + local back = Adx.decode(Bytes.reader(again :: buffer)) :: any + t:check(back and (c.loopStart == nil or (back.meta.source.loop.start == c.loopStart)), c.name .. ": loop kept on re-encode") +end +do + local out = Adx.encode(audio, { loop = { start = 1000, stop = 8000 } }) + t:check(out and buffer.tostring(out) == Ours[2].data, "encode is deterministic") + local _, e1 = Adx.encode(audio, { loop = { start = 10, stop = 5 } }) + t:check(e1 and e1.code == Err.ARG, "bad loop") + local _, e2 = Adx.encode(Types.Audio.new(8000, 9, 10)) + t:check(e2 and e2.code == Err.ARG, "9 channels") + local _, e3 = Adx.encode(audio, { cutoff = 1e6 }) + t:check(e3 and e3.code == Err.ARG, "bad cutoff") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local base = Cases[1].data + local function patch(at: number, bytes: string): buffer + local b = buffer.fromstring(base) + buffer.writestring(b, at, bytes) + return b + end + local function fails(b: buffer, code: string, label: string) + local d, e = Adx.open(Bytes.reader(b)) + t:check(d == nil and e and e.code == code, label .. ": " .. tostring(e)) + end + fails(patch(0x12, "\4\9"), Err.UNSUPPORTED, "encrypted") + fails(patch(0x04, "\4"), Err.UNSUPPORTED, "exponential type") + fails(patch(0x04, "\17"), Err.UNSUPPORTED, "AHX") + fails(patch(0x07, "\0"), Err.CORRUPT, "0 channels") + fails(patch(0x12, "\6\0"), Err.UNSUPPORTED, "version 6") + fails(buffer.fromstring("not adx at all"), Err.CORRUPT, "not adx") + t:eq(F.detect(base), "adx", "F.detect") + local a = F.audio.load(base) + t:check(a and a.frames == Cases[1].frames, "F.audio.load") + local out = F.save(a, nil, { format = "adx" }) + t:check(out and F.detect(out) == "adx", "F.save adx") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Adx.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 10 }) +t:fuzz("header", function(b: buffer) + return Adx.decode(Bytes.reader(b)) +end, samples, { mutations = 10, keepHeader = 0, garbage = 50 }) + +t:done() diff --git a/tests/audio/vag.luau b/tests/audio/vag.luau new file mode 100644 index 0000000..4b16073 --- /dev/null +++ b/tests/audio/vag.luau @@ -0,0 +1,89 @@ +-- audio/vag tests: VAGp (with and without loop flags), VAGi and KVAG files from our Python encoders, bit-exact with +-- vgmstream / ffmpeg (tools/fixtures/vag.py) through decode and open with seeks; our encoder's files as vgmstream +-- decodes them (loops reported where vgmstream reads them), their quality; errors; the api; the fuzz pass. +local T = require("@tests/T") +local Vag = require("@formats/audio/vag") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/vag_cases") +local Ours = require("@tests/gen/vag_ours") +local Sig = require("@tests/gen/vag_sig") +local Sig1 = require("@tests/gen/vag_sig1") + +local t = T.suite("vag") +t:eq(Vag.name, "vag", "name") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Vag.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + H.check(t, Vag, c) + if c.title then + t:eq(Vag.decode(Bytes.reader(buffer.fromstring(c.data))).tags.title, c.title, c.name .. ": title") + end +end +t:note("%d files bit-exact with vgmstream / ffmpeg", #Cases) + +-- ------------------------------------------------------------------------------------------------ encoder +local function audioOf(S: any): any + local a = Types.Audio.new(S.rate, S.channels, S.frames) + buffer.writestring(a.samples, 0, S.data) + return a +end +for _, c in Ours do + H.check(t, Vag, c) + local src = audioOf(if c.ch == 1 then Sig1 else Sig) + local a = Vag.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + -- the output starts with the blank frame: 28 samples later + local s = H.snr(src.samples, buffer.fromstring(buffer.readstring(a.samples, 28 * c.ch * 4, src.frames * c.ch * 4)), src.frames * c.ch) + t:check(s > 25, string.format("ours %s: %.1f dB", c.name, s)) + t:note("encode %s: %.1f dB", c.name, s) +end +do + local mono = audioOf(Sig1) + local out = Vag.encode(mono, { loop = { start = 600, stop = 5000 } }) + t:check(out and buffer.tostring(out) == Ours[2].data, "encode is deterministic") + mono.tags = { title = "A Title That Is Long" } + local named = Vag.decode(Bytes.reader(Vag.encode(mono) :: buffer)) :: any + t:eq(named.tags.title, "A Title That Is ", "the name field holds 16 bytes") + local _, e1 = Vag.encode(Types.Audio.new(8000, 3, 10)) + t:check(e1 and e1.code == Err.ARG, "3 channels") + local _, e2 = Vag.encode(mono, { loop = { start = 0, stop = 10 } }) + t:check(e2 and e2.code == Err.ARG, "a loop inside one frame") + local _, e3 = Vag.encode(audioOf(Sig), { interleave = 100 }) + t:check(e3 and e3.code == Err.ARG, "bad interleave") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local base = Cases[1].data + local hevag = buffer.fromstring(base) + buffer.writeu32(hevag, 4, bit32.byteswap(0x00030000)) + local _, e1 = Vag.open(Bytes.reader(hevag)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "HEVAG: " .. tostring(e1)) + local _, e2 = Vag.open(Bytes.reader(buffer.fromstring("VAGp\0\0"))) + t:check(e2 and e2.code == Err.TRUNCATED, "short header: " .. tostring(e2)) + local _, e3 = Vag.open(Bytes.reader(buffer.fromstring("RIFF0000WAVE"))) + t:check(e3 and e3.code == Err.CORRUPT, "not vag") + t:eq(F.detect(base), "vag", "F.detect") + local a = F.audio.load(Cases[4].data) + t:check(a and a.channels == 1 and a.meta.source.codec == "ima", "F.audio.load KVAG") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Vag.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 10 }) +t:fuzz("header", function(b: buffer) + return Vag.decode(Bytes.reader(b)) +end, samples, { mutations = 10, keepHeader = 0, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/_adpcm.py b/tools/fixtures/_adpcm.py index 6078a36..b50af19 100644 --- a/tools/fixtures/_adpcm.py +++ b/tools/fixtures/_adpcm.py @@ -316,7 +316,7 @@ def wav_pcm(data): def vgdecode(ctx, data, ext): """vgmstream's decode of a file: (rate, channels, s16le bytes); loop facts come from vgminfo""" A = _audio() - out = A.tool(ctx, "vgmstream", ["vgmstream-cli", "-o", "{out}", "{in}"], data, ext, outext="wav") + out = A.tool(ctx, "vgmstream", ["vgmstream-cli", "-i", "-o", "{out}", "{in}"], data, ext, outext="wav") return wav_pcm(out) @@ -350,3 +350,15 @@ def _audio(): _A = importlib.util.module_from_spec(spec) spec.loader.exec_module(_A) return _A + + +def vagi(samples, rate, ch=2, interleave=0x400): + """a VAGi file (stereo PS-ADPCM, channels interleaved every `interleave` bytes, data at 0x800)""" + ints = s16(samples) + chans = [psx_encode(ints[c::ch]) for c in range(ch)] + size = max(len(x) for x in chans) + size = (size + interleave - 1) // interleave * interleave + chans = [x.ljust(size, b"\0") for x in chans] + data = b"".join(chans[c][k:k + interleave] for k in range(0, size, interleave) for c in range(ch)) + head = b"VAGi" + struct.pack(">I", 0x20) + struct.pack("II", size, rate) + return head.ljust(0x800, b"\0") + data diff --git a/tools/fixtures/adx.py b/tools/fixtures/adx.py new file mode 100644 index 0000000..20f6501 --- /dev/null +++ b/tools/fixtures/adx.py @@ -0,0 +1,69 @@ +# CRI ADX fixtures (tools/fixtures.py): audio/adx. vgmstream is the reference decoder (CRI's scale + 1 and version 3 +# rounding; ffmpeg's ADX decoder differs a little on both). +# tests/gen/adx_cases.luau { name, data, rate, ch, frames, ref (vgmstream s16le), loopStart?, loopEnd? } +# ffmpeg -f adx files (version 3, mono / stereo), and a version 4 file rebuilt around ffmpeg's frames with an +# initial history and loop points (vgmstream -m reports the loop) +# tests/gen/adx_ours.luau our encoder's files (run in this step) with vgmstream's decode and loop report +# tests/gen/adx_sig.luau the encoder input +import importlib.util, os, re, struct + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/adx"] + + +def loops(info): + m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", info, re.S) + return (int(m.group(1)), int(m.group(2))) if m else None + + +def case(ctx, name, data): + rate, ch, ref = D.vgdecode(ctx, data, "adx") + e = dict(name=name, data=data, rate=rate, ch=ch, frames=len(ref) // (2 * ch), ref=ref) + lp = loops(D.vginfo(ctx, data, "adx")) + if lp: + e["loopStart"], e["loopEnd"] = lp + return e + + +def generate(ctx): + cases = [] + for name, rate, ch, kind in (("ffmpeg-mono-22k", 22050, 1, "sweep"), ("ffmpeg-stereo-44k", 44100, 2, "music"), + ("ffmpeg-stereo-32k", 32000, 2, "sine")): + sig = A.signal(kind, rate, ch, 7000, seed=ch) + f = D.ffencode(ctx, A.wav(sig, rate, ch), ["-c:a", "adpcm_adx", "-f", "adx"], "adx") + cases.append(case(ctx, name, f)) + # version 4 with history and loops, around the stereo frames + f = cases[1]["data"] + start = struct.unpack_from(">H", f, 2)[0] + 4 + frames_ = f[start:] + rate, n = struct.unpack_from(">II", f, 8) + head = bytearray(f[:0x14]) + struct.pack_into(">H", head, 0x12, 0x0400) + head += b"\0" * 4 + struct.pack(">hhhh", 300, -200, -150, 90) # 0x14 flags, 0x18 history (2 channels) + head += struct.pack(">HHIIIII", 0, 1, 1, 1024, 0, 6000, 0) + newstart = len(head) + 6 + struct.pack_into(">H", head, 2, newstart - 4) + cases.append(case(ctx, "v4-hist-loop", bytes(head) + b"(c)CRI" + frames_)) + ctx.emit("adx_cases", cases) + + sig = A.signal("music", 32000, 2, 9000, seed=11) + A.emit_signal(ctx, "adx_sig", sig, 32000, 2) + ours = [] + for name, opts in (("plain", "nil"), ("loop", "{ loop = { start = 1000, stop = 8000 } }")): + data = A.encode_luau(ctx, "audio/adx", "adx_sig", opts) + e = case(ctx, name, data) + e["opts"] = opts + ours.append(e) + ctx.emit("adx_ours", ours) diff --git a/tools/fixtures/vag.py b/tools/fixtures/vag.py new file mode 100644 index 0000000..796d19c --- /dev/null +++ b/tools/fixtures/vag.py @@ -0,0 +1,55 @@ +# Sony VAG / KVAG fixtures (tools/fixtures.py): audio/vag. Our Python PS-ADPCM / IMA encoders (tools/fixtures/_adpcm.py) +# write the files; vgmstream decodes VAGp / VAGi (and reports the loops), ffmpeg decodes KVAG (adpcm_ima_ssi). +# tests/gen/vag_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd?, title? } +# tests/gen/vag_ours.luau our encoder's files (run in this step) as vgmstream decodes them +# tests/gen/vag_sig.luau / vag_sig1.luau the encoder inputs (stereo / mono) +import importlib.util, os, re + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/vag"] + + +def vgcase(ctx, name, data, **extra): + rate, ch, ref = D.vgdecode(ctx, data, "vag") + e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref, **extra) + m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, "vag"), re.S) + if m: + e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2)) + return e + + +def generate(ctx): + mono = A.signal("music", 22050, 1, 6000, seed=21) + stereo = A.signal("sine", 32000, 2, 5000, seed=22) + cases = [ + vgcase(ctx, "vagp-mono", D.vag(mono, 22050, b"Mono Song"), title="Mono Song"), + vgcase(ctx, "vagp-loop", D.vag(mono, 22050, loop=(20, 150))), + vgcase(ctx, "vagi-stereo", D.vagi(stereo, 32000)), + ] + for name, sig, ch, rate in (("kvag-mono", mono, 1, 22050), ("kvag-stereo", stereo, 2, 32000)): + f = D.kvag(sig, rate, ch) + cases.append(dict(name=name, data=f, rate=rate, ch=ch, ref=D.ffs16(ctx, f, "vag", fmt="kvag"))) + ctx.emit("vag_cases", cases) + + A.emit_signal(ctx, "vag_sig", stereo, 32000, 2) + A.emit_signal(ctx, "vag_sig1", mono, 22050, 1) + ours = [] + for name, sigmod, opts in (("mono", "vag_sig1", "nil"), ("mono-loop", "vag_sig1", "{ loop = { start = 600, stop = 5000 } }"), + ("stereo", "vag_sig", "nil")): + data = A.encode_luau(ctx, "audio/vag", sigmod, opts) + e = vgcase(ctx, name, data) + e["opts"] = opts + ours.append(e) + ctx.emit("vag_ours", ours) From 5dfaaf752470544d3ef6e426b7c6b6d49208581e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:22:46 -0500 Subject: [PATCH 3/9] ws-audio2: audio/brstm (BRSTM / BCSTM / BFSTM read: DSP ADPCM, PCM16, PCM8, loops) Bit-exact with vgmstream; forward seeks start from the ADPC / SEEK history. codecs/audio/Adpcm/Decoder.interleaved also lays out block-interleaved PCM (s16be / s16le / s8); snapshots take precedence over a format's history table. --- src/Formats/Registry.luau | 12 + src/Formats/audio/brstm/init.luau | 292 ++++++++++++++++++++ src/Formats/codecs/audio/Adpcm/Decoder.luau | 42 ++- tests/audio/brstm.luau | 52 ++++ tools/fixtures/_adpcm.py | 27 +- tools/fixtures/brstm.py | 47 ++++ 6 files changed, 454 insertions(+), 18 deletions(-) create mode 100644 src/Formats/audio/brstm/init.luau create mode 100644 tests/audio/brstm.luau create mode 100644 tools/fixtures/brstm.py diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ab78992..f6960dd 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -206,6 +206,18 @@ local list: { Entry } = { return require("@formats/audio/au") end, }, + { + name = "brstm", + category = "audio", + path = "audio/brstm", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, + load = function() + return require("@formats/audio/brstm") + end, + }, { name = "caf", category = "audio", diff --git a/src/Formats/audio/brstm/init.luau b/src/Formats/audio/brstm/init.luau new file mode 100644 index 0000000..8aac43b --- /dev/null +++ b/src/Formats/audio/brstm/init.luau @@ -0,0 +1,292 @@ +--!strict +-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and +-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in formats-luau; the layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP +-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 +-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } +-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions +-- (the whole stream plays), the track table (channels are not grouped). +-- +-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) + +-- ------------------------------------------------------------------------------------------------ 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 Decoder = require("@formats/codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Brstm = { + name = "brstm", + category = "audio", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Brstm.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then + return 0 + end + local bom = r:peek(2, 4) + return if bom == "\254\255" or bom == "\255\254" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Brstm.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file +-- start); a read out of range records the error in .err and returns 0 +local function view(r: Bytes.Reader, be: boolean) + local v = { err = nil :: string? } + local size = r.limit - r.base + local function at(o: number, n: number): Bytes.Reader? + if o < 0 or o + n > size then + v.err = "an offset points past the end" + return nil + end + return r:sub(o, n) + end + function v.u8(o: number): number + local s = at(o, 1) + return if s then s:u8() else 0 + end + function v.u16(o: number): number + local s = at(o, 2) + return if s then (if be then s:u16be() else s:u16le()) else 0 + end + function v.i16(o: number): number + local s = at(o, 2) + return if s then (if be then s:i16be() else s:i16le()) else 0 + end + function v.u32(o: number): number + local s = at(o, 4) + return if s then (if be then s:u32be() else s:u32le()) else 0 + end + function v.i32(o: number): number + local s = at(o, 4) + return if s then (if be then s:i32be() else s:i32le()) else 0 + end + return v +end + +type Layout = { + codec: number, + loop: boolean, + ch: number, + rate: number, + loopStart: number, + frames: number, + blockSize: number, + lastPadded: number, + data: number, -- the first block (absolute in the file) + adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) + hist: number?, -- the per-block history table: (yn1, yn2) per channel per block + histEntries: number, +} + +local function parseRstm(v: any): (Layout?, string?) + if v.u16(0x06) ~= 0x0100 then + return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07)) + end + local head = v.u32(0x10) + local adpc = v.u32(0x18) + if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian + return nil, "no HEAD chunk" + end + local base = head + 8 + local info = base + v.u32(base + 4) + local chans = base + v.u32(base + 20) + local ch = v.u8(info + 2) + local L: Layout = { + codec = v.u8(info), + loop = v.u8(info + 1) ~= 0, + ch = ch, + rate = v.u16(info + 4), + loopStart = v.u32(info + 8), + frames = v.u32(info + 12), + data = v.u32(info + 16), + blockSize = v.u32(info + 24), + lastPadded = v.u32(info + 40), + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = base + v.u32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = base + v.u32(ci + 4) + end + if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC" + L.hist = adpc + 8 + L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +local function parseFstm(v: any): (Layout?, string?) + local info: number, seek: number, data: number = 0, 0, 0 + local seekSize: number = 0 + for i = 0, math.min(v.u16(0x10), 16) - 1 do + local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4) + if id == 0x4000 then + info = off + elseif id == 0x4001 then + seek = off + seekSize = v.u32(0x14 + i * 12 + 8) :: number + elseif id == 0x4002 then + data = off + end + end + if info == 0 or data == 0 then + return nil, "no INFO or DATA block" + end + local stream = info + 8 + v.i32(info + 0x0C) + local chans = info + 8 + v.i32(info + 0x1C) + local ch = v.u8(stream + 2) + local dataRef = stream + 0x30 + local L: Layout = { + codec = v.u8(stream), + loop = v.u8(stream + 1) ~= 0, + ch = ch, + rate = v.u32(stream + 4), + loopStart = v.u32(stream + 8), + frames = v.u32(stream + 12), + blockSize = v.u32(stream + 20), + lastPadded = v.u32(stream + 36), + data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20, + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = chans + v.i32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = ci + v.i32(ci + 4) + end + if seek > 0 and seekSize > 8 then + L.hist = seek + 8 + L.histEntries = (seekSize - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +function Brstm.open(r: Bytes.Reader, _opts: any?): (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 + if r.limit - r.base < 0x40 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + if Brstm.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file") + end + local magic = r:peek(4) + local be = r:peek(2, 4) == "\254\255" + local v = view(r, be) + local parsed: Layout?, msg: string? + if magic == "RSTM" then + if not be then + return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM") + end + parsed, msg = parseRstm(v) + else + parsed, msg = parseFstm(v) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + elseif not parsed then + return nil, Err.from(msg) + end + local L = parsed :: Layout + local codec = CODECS[L.codec] + if not codec then + return nil, Err.new(Err.CORRUPT, "codec " .. L.codec) + elseif codec == "ima" then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams") + end + local ch = L.ch + if ch < 1 or L.rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate") + end + local size = r.limit - r.base - L.data + if L.data < 0 or size < 0 then + return nil, Err.new(Err.TRUNCATED, "the data starts past the end") + end + local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le" + local coefs: buffer? = nil + local hist: { number }? = nil + if codec == "dsp" then + coefs = buffer.create(64 * ch) + hist = {} + for c = 0, ch - 1 do + local adp = L.adp[c + 1] + for k = 0, 15 do + buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2)) + end + hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + end + end + local histAt, entries = L.hist, L.histEntries + local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil + local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop } + local block = L.blockSize + if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then + return nil, Err.new(Err.CORRUPT, "bad block size " .. block) + end + local d, err = Decoder.interleaved(dec, { + kind = kind :: any, + buf = r.buf, + offset = r.base + L.data, + size = size, + interleave = block, + lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block, + frames = L.frames, + coefs = coefs, + hist = hist, + restore = if codec == "dsp" and histAt + then function(row: number, st: buffer): boolean + if row >= entries then + return false + end + for c = 0, ch - 1 do + local p = (histAt :: number) + (row * ch + c) * 4 + buffer.writei32(st, c * 8, v.i16(p)) + buffer.writei32(st, c * 8 + 4, v.i16(p + 2)) + end + return v.err == nil + end + else nil, + }) + if d then + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + end + return d, err +end + +return Brstm diff --git a/src/Formats/codecs/audio/Adpcm/Decoder.luau b/src/Formats/codecs/audio/Adpcm/Decoder.luau index a4ee4d8..291eac1 100644 --- a/src/Formats/codecs/audio/Adpcm/Decoder.luau +++ b/src/Formats/codecs/audio/Adpcm/Decoder.luau @@ -2,8 +2,8 @@ -- 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. +-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else +-- 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) @@ -14,8 +14,8 @@ -- }) -- -- 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.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), 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 @@ -55,10 +55,10 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) 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 + if snaps[i] then buffer.copy(st, 0, snaps[i]) + elseif restore and restore(i) then + -- the format set the state (BRSTM's seek table) else local j = i - 1 while j > 1 and not snaps[j] do @@ -96,11 +96,29 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) 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 +local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame +local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame + +-- PCM samples of one channel into every ds-th float of dst from float d +local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number) + if kind == "s8" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128) + end + elseif kind == "s16le" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768) + end + else + for k = 0, n - 1 do + local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1) + buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768) + end + end +end export type InterleavedSpec = { - kind: "psx" | "adx" | "dsp", + kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way buf: buffer, offset: number, -- the first row size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames) @@ -177,8 +195,10 @@ function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) 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 + elseif kind == "dsp" then Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch) + else + pcm(kind, buf, p, n, out, d, ch) end end got += n diff --git a/tests/audio/brstm.luau b/tests/audio/brstm.luau new file mode 100644 index 0000000..e9300ff --- /dev/null +++ b/tests/audio/brstm.luau @@ -0,0 +1,52 @@ +-- audio/brstm tests: BRSTM / BCSTM / BFSTM files (DSP ADPCM, PCM16, PCM8; big- and little-endian; loops) from our +-- Python writer, bit-exact with vgmstream (tools/fixtures/brstm.py) through decode and open with seeks (forward seeks +-- start from the ADPC / SEEK history table); errors; the api; the fuzz pass. +local T = require("@tests/T") +local Brstm = require("@formats/audio/brstm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/brstm_cases") + +local t = T.suite("brstm") +t:eq(Brstm.name, "brstm", "name") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Brstm.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + H.check(t, Brstm, c) + t:eq(F.detect(c.data), "brstm", c.name .. ": F.detect") +end +t:note("%d files bit-exact with vgmstream", #Cases) + +do + local base = Cases[1].data + local function fails(b: buffer, code: string, label: string) + local d, e = Brstm.open(Bytes.reader(b)) + t:check(d == nil and e and e.code == code, label .. ": " .. tostring(e)) + end + local beta = buffer.fromstring(base) + buffer.writeu16(beta, 6, 0x0100) -- bytes 01 00 read big-endian: version 0.1 + fails(beta, Err.UNSUPPORTED, "version 0.1") + fails(buffer.fromstring(string.sub(base, 1, 0x30)), Err.TRUNCATED, "short") + fails(buffer.fromstring("RSTM\254\255\1\0" .. string.rep("\0", 100)), Err.CORRUPT, "no HEAD") + local a = F.audio.load(Cases[2].data) + t:check(a and a.meta.source.loop and a.meta.source.loop.start == Cases[2].loopStart, "F.audio.load keeps the loop") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Brstm.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 8 }) +t:fuzz("header", function(b: buffer) + return Brstm.decode(Bytes.reader(b)) +end, samples, { mutations = 12, keepHeader = 0, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/_adpcm.py b/tools/fixtures/_adpcm.py index b50af19..823fb91 100644 --- a/tools/fixtures/_adpcm.py +++ b/tools/fixtures/_adpcm.py @@ -149,6 +149,7 @@ def dsp_frame(xs, h1, h2, coefs): a, b = h1, h2 err = 0 nibs = [] + outs = [] for x in xs: base = 1024 + c1 * a + c2 * b want = ((x << 11) - base) / (scale << 11) @@ -156,36 +157,48 @@ def dsp_frame(xs, h1, h2, coefs): s = clamp16(((n * scale) << 11) + base >> 11) err += (x - s) ** 2 nibs.append(n & 15) + outs.append(s) 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) + best = (err, p << 4 | sc, nibs, outs) return best -def dsp_encode(samples, coefs=DSP_COEFS): +def dsp_encode(samples, coefs=DSP_COEFS, decoded=None): + """DSP frames; decoded (a list) receives the decoded samples (the history a seek table stores)""" 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) + _, head, nibs, outs = 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 + h1, h2 = outs[-1], outs[-2] + if decoded is not None: + decoded += outs[:n] return bytes(out) +def hist(dec, b, spb): + """(yn1, yn2) before block b: the last two decoded samples of the previous block""" + if b == 0 or not dec: + return (0, 0) + return (dec[b * spb - 1], dec[b * spb - 2]) + + 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)] + decs = [[] for _ in range(ch)] if codec == "dsp": - enc = [dsp_encode(x, coefs) for x in chans] + enc = [dsp_encode(x, coefs, decs[c]) for c, x in enumerate(chans)] spb = block // 8 * 14 elif codec == "pcm16": big = kind == "RSTM" or (kind == "FSTM" and not le) @@ -235,7 +248,7 @@ def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec 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_body = b"".join(b"".join(struct.pack(">hh", *hist(decs[c], b, spb)) for c in range(ch)) for b 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:] @@ -279,7 +292,7 @@ def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec 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 = b"SEEK" + struct.pack(E + "I", 0) + b"".join(b"".join(struct.pack(E + "hh", *hist(decs[c], b, spb)) for c in range(ch)) for b 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) diff --git a/tools/fixtures/brstm.py b/tools/fixtures/brstm.py new file mode 100644 index 0000000..76f7997 --- /dev/null +++ b/tools/fixtures/brstm.py @@ -0,0 +1,47 @@ +# Nintendo stream fixtures (tools/fixtures.py): audio/brstm. Our Python writer and DSP encoder (tools/fixtures/_adpcm.py) +# build BRSTM / BCSTM / BFSTM files (DSP ADPCM with a filled ADPC / SEEK history table, PCM16, PCM8; several blocks +# with a short padded last block; loops); vgmstream decodes them and reports the loops. +# tests/gen/brstm_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd? } +import importlib.util, os, re + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/brstm"] + + +def generate(ctx): + stereo = A.signal("music", 32000, 2, 9000, seed=31) + mono = A.signal("sweep", 22050, 1, 8000, seed=32) + made = [ + ("rstm-dsp-stereo", "RSTM", stereo, 32000, 2, dict(block=0x800)), + ("rstm-dsp-mono-loop", "RSTM", mono, 22050, 1, dict(block=0x400, loop=(1000, 8000))), + ("rstm-pcm16-stereo", "RSTM", stereo, 32000, 2, dict(block=0x2000, codec="pcm16")), + ("cstm-dsp-stereo-loop", "CSTM", stereo, 32000, 2, dict(block=0x800, loop=(4000, 9000))), + ("cstm-pcm8-mono", "CSTM", mono, 22050, 1, dict(block=0x1000, codec="pcm8")), + ("fstm-be-dsp-stereo", "FSTM", stereo, 32000, 2, dict(block=0x1000)), + ("fstm-le-dsp-mono", "FSTM", mono, 22050, 1, dict(block=0x800, le=True)), + ("fstm-le-pcm16-stereo", "FSTM", stereo, 32000, 2, dict(block=0x1000, le=True, codec="pcm16")), + ] + cases = [] + for name, kind, sig, rate, ch, kw in made: + data = D.rstm(sig, rate, ch, kind, **kw) + ext = {"RSTM": "brstm", "CSTM": "bcstm", "FSTM": "bfstm"}[kind] + r, c, ref = D.vgdecode(ctx, data, ext) + assert (r, c) == (rate, ch) and len(ref) == len(sig) * 2, (name, r, c, len(ref)) + e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref) + m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, ext), re.S) + if m: + e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2)) + cases.append(e) + ctx.emit("brstm_cases", cases) From f7657635376c922ada1ec190a04e5d04645f4aab Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:26:33 -0500 Subject: [PATCH 4/9] ws-audio2: codecs/audio/Qoa and audio/qoa (QOA read / write, port of qoa.h, MIT) Decode bit-exact with ffmpeg and qoa.h; encode byte-for-byte qoa.h's qoa_encode (fixtures compile the committed qoa.h reference with nix gcc). --- licenses/NOTICE.md | 1 + licenses/qoa-LICENSE.txt | 20 + src/Formats/Registry.luau | 12 + src/Formats/audio/qoa/init.luau | 185 ++++++ src/Formats/codecs/audio/Qoa/init.luau | 297 ++++++++++ tests/audio/qoa.luau | 95 ++++ tests/fixtures/qoa/qoa.h | 758 +++++++++++++++++++++++++ tests/fixtures/qoa/qoa_ref.c | 52 ++ tools/fixtures/qoa.py | 48 ++ 9 files changed, 1468 insertions(+) create mode 100644 licenses/qoa-LICENSE.txt create mode 100644 src/Formats/audio/qoa/init.luau create mode 100644 src/Formats/codecs/audio/Qoa/init.luau create mode 100644 tests/audio/qoa.luau create mode 100644 tests/fixtures/qoa/qoa.h create mode 100644 tests/fixtures/qoa/qoa_ref.c create mode 100644 tools/fixtures/qoa.py diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 9c68de2..504e09c 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `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) | +| `src/Formats/codecs/audio/Qoa/` (port of qoa.h: tables, LMS predictor, decoder, encoder); `tests/fixtures/qoa/qoa.h` (the reference, compiled at fixture time) | qoa.h (phoboslab/qoa, Dominic Szablewski) | MIT: [qoa-LICENSE.txt](qoa-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/qoa-LICENSE.txt b/licenses/qoa-LICENSE.txt new file mode 100644 index 0000000..50ab742 --- /dev/null +++ b/licenses/qoa-LICENSE.txt @@ -0,0 +1,20 @@ +qoa.h - The "Quite OK Audio" format for fast, lossy audio compression +https://github.com/phoboslab/qoa + +Copyright (c) 2023, Dominic Szablewski - https://phoboslab.org +SPDX-License-Identifier: MIT + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index f6960dd..31e60fa 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -278,6 +278,18 @@ local list: { Entry } = { return require("@formats/audio/opus") end, }, + { + name = "qoa", + category = "audio", + path = "audio/qoa", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, + load = function() + return require("@formats/audio/qoa") + end, + }, { name = "vag", category = "audio", diff --git a/src/Formats/audio/qoa/init.luau b/src/Formats/audio/qoa/init.luau new file mode 100644 index 0000000..764c357 --- /dev/null +++ b/src/Formats/audio/qoa/init.luau @@ -0,0 +1,185 @@ +--!strict +-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in +-- formats-luau. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order +-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its +-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): +-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel +-- count or rate change mid-stream (Err.UNSUPPORTED). +-- +-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder +-- local file = Qoa.encode(audio) + +-- ------------------------------------------------------------------------------------------------ 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 Stream = require("@formats/codecs/audio/Stream") +local Codec = require("@formats/codecs/audio/Qoa") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoa = { + name = "qoa", + category = "audio", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoa.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoaf" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Qoa.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then + return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215") + end + local FL = Codec.FRAME_LEN + local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536)) + w:string("qoaf") + w:u32be(0) + local lms = Codec.newLms(ch) + local fb = buffer.create(FL * ch * 4) + local tmp: buffer? = nil + local total = 0 + while true do + -- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them + local have = 0 + while have < FL do + local b, n = src:read(FL - have, tmp) + if n <= 0 then + break + end + tmp = b + buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4) + have += n + end + if have == 0 then + break + end + local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20)) + w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) + total += have + if have < FL then + break + end + end + if src.err then + return nil, src.err + end + if total == 0 then + return nil, Err.new(Err.ARG, "QOA needs at least one sample") + end + if total >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "too many samples for QOA") + end + local out = w:finish() + buffer.writeu32(out, 4, bit32.byteswap(total)) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Qoa.open(r: Bytes.Reader, _opts: any?): (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 h = r:sub(0) + if h:string(4) ~= "qoaf" then + return nil, Err.new(Err.CORRUPT, "not a QOA file") + end + local declared = h:u32be() + if h.err then + return nil, h.err + end + local buf = r.buf + -- the frame index: offsets, first frames + local offs, starts = {}, {} + local p, total = r.base + 8, 0 + local ch, rate = 0, 0 + while p < r.limit do + local info, msg = Codec.frameInfo(buf, p, r.limit - p) + if not info then + if #offs == 0 then + return nil, Err.from(msg, p - r.base) + end + break -- a cut or damaged tail: keep the whole frames + end + if #offs == 0 then + ch, rate = info.channels, info.rate + elseif info.channels ~= ch or info.rate ~= rate then + return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base) + end + table.insert(offs, p) + table.insert(starts, total) + total += info.samples + p += info.size + if declared > 0 and total >= declared then + break + end + end + if #offs == 0 then + return nil, Err.new(Err.TRUNCATED, "no frames") + end + local frames = if declared > 0 then math.min(declared, total) else total + local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)), + tags = {}, + streaming = declared == 0, + } + local limit = r.limit + return Stream.packets(dec, { + count = #offs, + start = function(i: number): number + return if i > #offs then total else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0) + if not n then + return nil, Err.from(msg, offs[i] - r.base) + end + return n, nil + end, + pcm = function(): buffer + return pcm + end, + reset = function() end, + stop = frames, + }) +end + +return Qoa diff --git a/src/Formats/codecs/audio/Qoa/init.luau b/src/Formats/codecs/audio/Qoa/init.luau new file mode 100644 index 0000000..0e7560a --- /dev/null +++ b/src/Formats/codecs/audio/Qoa/init.luau @@ -0,0 +1,297 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale +-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic +-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force +-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). +-- The 64-bit slices are handled as two 32-bit halves. +-- +-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message +-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d +-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] +-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) +-- +-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local readi32, writei32 = buffer.readi32, buffer.writei32 +local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Qoa = {} + +Qoa.SLICE_LEN = 20 +Qoa.SLICES_PER_FRAME = 256 +Qoa.FRAME_LEN = 256 * 20 +Qoa.MAX_CHANNELS = 255 + +local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code +local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 } +-- DEQ[sf * 8 + q + 1] +local DEQ = { + 1, -1, 3, -3, 5, -5, 7, -7, + 5, -5, 18, -18, 32, -32, 49, -49, + 16, -16, 53, -53, 95, -95, 147, -147, + 34, -34, 113, -113, 203, -203, 315, -315, + 63, -63, 210, -210, 378, -378, 588, -588, + 104, -104, 345, -345, 621, -621, 966, -966, + 158, -158, 528, -528, 950, -950, 1477, -1477, + 228, -228, 760, -760, 1368, -1368, 2128, -2128, + 316, -316, 1053, -1053, 1895, -1895, 2947, -2947, + 422, -422, 1405, -1405, 2529, -2529, 3934, -3934, + 548, -548, 1828, -1828, 3290, -3290, 5117, -5117, + 696, -696, 2320, -2320, 4176, -4176, 6496, -6496, + 868, -868, 2893, -2893, 5207, -5207, 8099, -8099, + 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933, + 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005, + 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, +} + +local function be32(b: buffer, p: number): number + return byteswap(readu32(b, p)) +end + +local function s16(v: number): number + return if v >= 32768 then v - 65536 else v +end + +-- frameSize(channels, slices) -> bytes +function Qoa.frameSize(ch: number, slices: number): number + return 8 + 16 * ch + 8 * slices * ch +end + +export type FrameInfo = { channels: number, rate: number, samples: number, size: number } + +-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message +function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) + if avail < 8 then + return nil, "truncated frame header" + end + local hi, lo = be32(b, p), be32(b, p + 4) + local ch = rshift(hi, 24) + local rate = band(hi, 0xFFFFFF) + local samples = rshift(lo, 16) + local size = band(lo, 0xFFFF) + if ch == 0 or rate == 0 or samples == 0 then + return nil, "bad frame header" + end + local slices = (samples + 19) // 20 + local head = 8 + 16 * ch + if slices > 256 or size < head or slices * ch > (size - head) // 8 then + return nil, "bad frame size" + end + if size > avail then + return nil, "truncated frame" + end + return { channels = ch, rate = rate, samples = samples, size = size }, nil +end + +-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state +-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) +function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) + local info, msg = Qoa.frameInfo(b, p, avail) + if not info then + return nil, msg :: string + end + local ch, samples = info.channels, info.samples + for c = 0, ch - 1 do + local lp = p + 8 + c * 16 + local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12) + local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF)) + local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF)) + local sp = p + 8 + 16 * ch + c * 8 + local o = (d + c) * 4 + local os = ch * 4 + local s0 = 0 + while s0 < samples do + local hi, lo = be32(b, sp), be32(b, sp + 4) + local base = rshift(hi, 28) * 8 + 1 + local n = math.min(20, samples - s0) + for k = 0, n - 1 do + local q + if k < 9 then + q = band(rshift(hi, 25 - 3 * k), 7) + elseif k == 9 then + q = band(hi, 1) * 4 + rshift(lo, 30) + else + q = band(rshift(lo, 57 - 3 * k), 7) + end + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + writef32(dst, o, r / 32768) + o += os + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + end + s0 += 20 + sp += 8 * ch + end + end + return samples, info.size +end + +-- ------------------------------------------------------------------------------------------------ encoder +-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +function Qoa.newLms(ch: number): buffer + local st = buffer.create(32 * ch) + for c = 0, ch - 1 do + writei32(st, c * 32 + 24, -8192) + writei32(st, c * 32 + 28, 16384) + end + return st +end + +-- 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 + +-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which +-- wraps for big residuals at scale factor 0), rounding away from zero +local function qdiv(v: number, sf: number): number + local x = v * RECIP[sf + 1] + 32768 + if x >= 2147483648 or x < -2147483648 then + x = (x + 2147483648) % 4294967296 - 2147483648 + end + local n = x // 65536 + local sv = if v > 0 then 1 elseif v < 0 then -1 else 0 + local sn = if n > 0 then 1 elseif n < 0 then -1 else 0 + return n + sv - sn +end + +-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x +-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames +function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number + local slices = (n + 19) // 20 + local size = Qoa.frameSize(ch, slices) + writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) + writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size))) + for c = 0, ch - 1 do + local so = c * 32 + -- the history and weights as big-endian i16 x 4 + for i = 0, 3 do + local hv = band(readi32(lms, so + i * 4), 0xFFFF) + local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF) + buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255)) + end + end + local xs = table.create(20, 0) + local codes = table.create(20, 0) + local best = table.create(20, 0) + local prevSf = table.create(ch, 0) + local sp = p + 8 + 16 * ch + for s = 0, slices - 1 do + local len = math.min(20, n - s * 20) + for c = 0, ch - 1 do + for k = 1, len do + xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4)) + end + local so = c * 32 + local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12) + local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28) + local bestRank, bestSf = math.huge, 0 + local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3 + for sfi = 0, 15 do + local sf = (sfi + prevSf[c + 1]) % 16 + local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3 + local rank = 0 + local base = sf * 8 + 1 + for k = 1, len do + local v = xs[k] + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local res = v - pred + local sc = qdiv(res, sf) + if sc > 8 then + sc = 8 + elseif sc < -8 then + sc = -8 + end + local q = QUANT[sc + 9] + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3 + if sq >= 2147483648 then -- C int arithmetic + sq = (sq + 2147483648) % 4294967296 - 2147483648 + end + local pen = sq // 262144 - 0x8ff + if pen < 0 then + pen = 0 + end + local e = v - r + rank += e * e + pen * pen + if rank > bestRank then + break + end + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + codes[k] = q + end + if rank < bestRank then + bestRank, bestSf = rank, sf + b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3 + for k = 1, len do + best[k] = codes[k] + end + end + end + prevSf[c + 1] = bestSf + writei32(lms, so, b0) + writei32(lms, so + 4, b1) + writei32(lms, so + 8, b2) + writei32(lms, so + 12, b3) + writei32(lms, so + 16, bw0) + writei32(lms, so + 20, bw1) + writei32(lms, so + 24, bw2) + writei32(lms, so + 28, bw3) + -- the slice: sf in the top 4 bits, then the codes, unused codes 0 + local hi, lo = bestSf * 268435456, 0 + for k = 0, 19 do + local q = if k < len then best[k + 1] else 0 + if k < 9 then + hi += q * 2 ^ (25 - 3 * k) + elseif k == 9 then + hi += rshift(q, 2) + lo += band(q, 3) * 1073741824 + else + lo += q * 2 ^ (57 - 3 * k) + end + end + writeu32(out, sp, byteswap(hi)) + writeu32(out, sp + 4, byteswap(lo)) + sp += 8 + end + end + return size +end + +return Qoa diff --git a/tests/audio/qoa.luau b/tests/audio/qoa.luau new file mode 100644 index 0000000..b7343ff --- /dev/null +++ b/tests/audio/qoa.luau @@ -0,0 +1,95 @@ +-- audio/qoa tests: files written by qoa.h (tools/fixtures/qoa.py; 1, 2 and 6 channels, a frame boundary, a partial +-- last slice, clipping signals) decoded bit-exact against ffmpeg and qoa.h; our encoder byte-for-byte equal to +-- qoa.h's qoa_encode, from an Audio and from a streaming Decoder; seeking; streaming files (total 0); a cut file; errors; +-- the api; the fuzz pass. +local T = require("@tests/T") +local Qoa = require("@formats/audio/qoa") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/qoa_cases") + +local Sigs = { + qoa_sig_stereo_44k = require("@tests/gen/qoa_sig_stereo_44k"), + qoa_sig_mono_22k = require("@tests/gen/qoa_sig_mono_22k"), + qoa_sig_6ch_48k = require("@tests/gen/qoa_sig_6ch_48k"), + qoa_sig_loud_mono = require("@tests/gen/qoa_sig_loud_mono"), + qoa_sig_square_stereo = require("@tests/gen/qoa_sig_square_stereo"), +} + +local t = T.suite("qoa") +t:eq(Qoa.name, "qoa", "name") +t:check(Qoa.caps.decode and Qoa.caps.encode, "caps") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Qoa.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + t:check(c.ref == c.qoaref, c.name .. ": ffmpeg and qoa.h agree") + H.check(t, Qoa, c) + -- our encoder: the same bytes as qoa.h + local S = Sigs[c.sig] + local a = Types.Audio.new(S.rate, S.channels, S.frames) + buffer.writestring(a.samples, 0, S.data) + local out, err = Qoa.encode(a) + local same = out ~= nil and buffer.tostring(out) == c.data + if not same and out then + local o = buffer.tostring(out) + for i = 1, math.max(#o, #c.data) do + if string.byte(o, i) ~= string.byte(c.data, i) then + t:note("%s: first difference at byte %d of %d / %d", c.name, i - 1, #o, #c.data) + break + end + end + end + t:check(same, c.name .. ": encode identical to qoa.h: " .. tostring(err)) + local streamed = Qoa.encode(Pcm.audioDecoder(a)) + t:check(streamed and buffer.tostring(streamed) == c.data, c.name .. ": encode from a Decoder") +end +t:note("%d qoa.h files decoded bit-exact (ffmpeg, qoa.h) and re-encoded byte-for-byte", #Cases) + +-- ------------------------------------------------------------------------------------------------ variants +do + local c = Cases[1] + local ref = buffer.fromstring(c.ref) + -- streaming: total 0 in the header + local s = buffer.fromstring(c.data) + buffer.writeu32(s, 4, 0) + local a = Qoa.decode(Bytes.reader(s)) :: any + t:check(a and a.frames == buffer.len(ref) // (2 * c.ch) and H.same(a.samples, ref, 0, a.frames * c.ch), "streaming file") + t:check(a.meta.source.streaming == true, "meta.source.streaming") + -- a cut file keeps its whole frames + local cut = Qoa.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 100)))) :: any + t:check(cut and cut.frames == 5120 * 2 and H.same(cut.samples, ref, 0, cut.frames * c.ch), "cut file: the whole frames") + -- errors + local _, e1 = Qoa.open(Bytes.reader(buffer.fromstring("qoaf\0\0\0\1"))) + t:check(e1 and e1.code == Err.TRUNCATED, "no frames: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writeu8(bad, 8, 0) -- 0 channels + local _, e2 = Qoa.open(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.CORRUPT, "0 channels: " .. tostring(e2)) + local _, e3 = Qoa.encode(Types.Audio.new(8000, 9, 10)) + t:check(e3 and e3.code == Err.ARG, "9 channels") + local _, e4 = Qoa.encode(Types.Audio.new(8000, 1, 0)) + t:check(e4 and e4.code == Err.ARG, "no samples") + local _, e5 = Qoa.decode(Bytes.reader(buffer.fromstring(c.data)), { maxFrames = 10 }) + t:check(e5 and e5.code == Err.LIMIT, "maxFrames") + t:eq(F.detect(c.data), "qoa", "F.detect") + local back = F.save(F.audio.load(c.data), nil, { format = "qoa" }) + t:check(back and F.detect(back) == "qoa", "F.save qoa") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Qoa.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 10 }) + +t:done() diff --git a/tests/fixtures/qoa/qoa.h b/tests/fixtures/qoa/qoa.h new file mode 100644 index 0000000..4f52be9 --- /dev/null +++ b/tests/fixtures/qoa/qoa.h @@ -0,0 +1,758 @@ +/* + +Copyright (c) 2023, Dominic Szablewski - https://phoboslab.org +SPDX-License-Identifier: MIT + +QOA - The "Quite OK Audio" format for fast, lossy audio compression + + +-- Data Format + +QOA encodes pulse-code modulated (PCM) audio data with up to 31 channels, +sample rates from 1 up to 16777215 hertz and a bit depth of 16 bits. + +The compression method employed in QOA is lossy; it discards some information +from the uncompressed PCM data. For many types of audio signals this compression +is "transparent", i.e. the difference from the original file is often not +audible. + +QOA encodes 20 samples of 16 bit PCM data into slices of 64 bits. A single +sample therefore requires 3.2 bits of storage space, resulting in a 5x +compression (16 / 3.2). + +A QOA file consists of an 8 byte file header, followed by a number of frames. +Each frame contains an 8 byte frame header, the current 16 byte en-/decoder +state per channel and 256 slices per channel. Each slice is 8 bytes wide and +encodes 20 samples of audio data. + +All values, including the slices, are big endian. The file layout is as follows: + +struct { + struct { + char magic[4]; // magic bytes "qoaf" + uint32_t samples; // samples per channel in this file + } file_header; + + struct { + struct { + uint8_t num_channels; // no. of channels + uint24_t samplerate; // samplerate in hz + uint16_t fsamples; // samples per channel in this frame + uint16_t fsize; // frame size (includes this header) + } frame_header; + + struct { + int16_t history[4]; // most recent last + int16_t weights[4]; // most recent last + } lms_state[num_channels]; + + qoa_slice_t slices[256][num_channels]; + + } frames[ceil(samples / (256 * 20))]; +} qoa_file_t; + +Each `qoa_slice_t` contains a quantized scalefactor `sf_quant` and 20 quantized +residuals `qrNN`: + +.- QOA_SLICE -- 64 bits, 20 samples --------------------------/ /------------. +| Byte[0] | Byte[1] | Byte[2] \ \ Byte[7] | +| 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 / / 2 1 0 | +|------------+--------+--------+--------+---------+---------+-\ \--+---------| +| sf_quant | qr00 | qr01 | qr02 | qr03 | qr04 | / / | qr19 | +`-------------------------------------------------------------\ \------------` + +Each frame except the last must contain exactly 256 slices per channel. The last +frame may contain between 1 .. 256 (inclusive) slices per channel. The last +slice (for each channel) in the last frame may contain less than 20 samples; the +slice still must be 8 bytes wide, with the unused samples zeroed out. + +Channels are interleaved per slice. E.g. for 2 channel stereo: +slice[0] = L, slice[1] = R, slice[2] = L, slice[3] = R ... + +A valid QOA file or stream must have at least one frame. Each frame must contain +at least one channel and one sample with a samplerate between 1 .. 16777215 +(inclusive). + +If the total number of samples is not known by the encoder, the samples in the +file header may be set to 0x00000000 to indicate that the encoder is +"streaming". In a streaming context, the samplerate and number of channels may +differ from frame to frame. For static files (those with samples set to a +non-zero value), each frame must have the same number of channels and same +samplerate. + +Note that this implementation of QOA only handles files with a known total +number of samples. + +A decoder should support at least 8 channels. The channel layout for channel +counts 1 .. 8 is: + + 1. Mono + 2. L, R + 3. L, R, C + 4. FL, FR, B/SL, B/SR + 5. FL, FR, C, B/SL, B/SR + 6. FL, FR, C, LFE, B/SL, B/SR + 7. FL, FR, C, LFE, B, SL, SR + 8. FL, FR, C, LFE, BL, BR, SL, SR + +QOA predicts each audio sample based on the previously decoded ones using a +"Sign-Sign Least Mean Squares Filter" (LMS). This prediction plus the +dequantized residual forms the final output sample. + +*/ + + + +/* ----------------------------------------------------------------------------- + Header - Public functions */ + +#ifndef QOA_H +#define QOA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define QOA_MIN_FILESIZE 16 +#define QOA_MAX_CHANNELS 8 + +#define QOA_SLICE_LEN 20 +#define QOA_SLICES_PER_FRAME 256 +#define QOA_FRAME_LEN (QOA_SLICES_PER_FRAME * QOA_SLICE_LEN) +#define QOA_LMS_LEN 4 +#define QOA_MAGIC 0x716f6166 /* 'qoaf' */ + +#define QOA_FRAME_SIZE(channels, slices) \ + (8 + QOA_LMS_LEN * 4 * channels + 8 * slices * channels) + +typedef struct { + int history[QOA_LMS_LEN]; + int weights[QOA_LMS_LEN]; +} qoa_lms_t; + +typedef struct { + unsigned int channels; + unsigned int samplerate; + unsigned int samples; + qoa_lms_t lms[QOA_MAX_CHANNELS]; + #ifdef QOA_RECORD_TOTAL_ERROR + double error; + #endif +} qoa_desc; + +unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes); +unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes); +void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len); + +unsigned int qoa_max_frame_size(qoa_desc *qoa); +unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa); +unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len); +short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *file); + +#ifndef QOA_NO_STDIO + +int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa); +void *qoa_read(const char *filename, qoa_desc *qoa); + +#endif /* QOA_NO_STDIO */ + + +#ifdef __cplusplus +} +#endif +#endif /* QOA_H */ + + +/* ----------------------------------------------------------------------------- + Implementation */ + +#ifdef QOA_IMPLEMENTATION +#include + +#ifndef QOA_MALLOC + #define QOA_MALLOC(sz) malloc(sz) + #define QOA_FREE(p) free(p) +#endif + +typedef unsigned long long qoa_uint64_t; + + +/* The quant_tab provides an index into the dequant_tab for residuals in the +range of -8 .. 8. It maps this range to just 3bits and becomes less accurate at +the higher end. Note that the residual zero is identical to the lowest positive +value. This is mostly fine, since the qoa_div() function always rounds away +from zero. */ + +static const int qoa_quant_tab[17] = { + 7, 7, 7, 5, 5, 3, 3, 1, /* -8..-1 */ + 0, /* 0 */ + 0, 2, 2, 4, 4, 6, 6, 6 /* 1.. 8 */ +}; + + +/* We have 16 different scalefactors. Like the quantized residuals these become +less accurate at the higher end. In theory, the highest scalefactor that we +would need to encode the highest 16bit residual is (2**16)/8 = 8192. However we +rely on the LMS filter to predict samples accurately enough that a maximum +residual of one quarter of the 16 bit range is sufficient. I.e. with the +scalefactor 2048 times the quant range of 8 we can encode residuals up to 2**14. + +The scalefactor values are computed as: +scalefactor_tab[s] <- round(pow(s + 1, 2.75)) */ + +static const int qoa_scalefactor_tab[16] = { + 1, 7, 21, 45, 84, 138, 211, 304, 421, 562, 731, 928, 1157, 1419, 1715, 2048 +}; + + +/* The reciprocal_tab maps each of the 16 scalefactors to their rounded +reciprocals 1/scalefactor. This allows us to calculate the scaled residuals in +the encoder with just one multiplication instead of an expensive division. We +do this in .16 fixed point with integers, instead of floats. + +The reciprocal_tab is computed as: +reciprocal_tab[s] <- ((1<<16) + scalefactor_tab[s] - 1) / scalefactor_tab[s] */ + +static const int qoa_reciprocal_tab[16] = { + 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 +}; + + +/* The dequant_tab maps each of the scalefactors and quantized residuals to +their unscaled & dequantized version. + +Since qoa_div rounds away from the zero, the smallest entries are mapped to 3/4 +instead of 1. The dequant_tab assumes the following dequantized values for each +of the quant_tab indices and is computed as: +float dqt[8] = {0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7, -7}; +dequant_tab[s][q] <- round_ties_away_from_zero(scalefactor_tab[s] * dqt[q]) + +The rounding employed here is "to nearest, ties away from zero", i.e. positive +and negative values are treated symmetrically. +*/ + +static const int qoa_dequant_tab[16][8] = { + { 1, -1, 3, -3, 5, -5, 7, -7}, + { 5, -5, 18, -18, 32, -32, 49, -49}, + { 16, -16, 53, -53, 95, -95, 147, -147}, + { 34, -34, 113, -113, 203, -203, 315, -315}, + { 63, -63, 210, -210, 378, -378, 588, -588}, + { 104, -104, 345, -345, 621, -621, 966, -966}, + { 158, -158, 528, -528, 950, -950, 1477, -1477}, + { 228, -228, 760, -760, 1368, -1368, 2128, -2128}, + { 316, -316, 1053, -1053, 1895, -1895, 2947, -2947}, + { 422, -422, 1405, -1405, 2529, -2529, 3934, -3934}, + { 548, -548, 1828, -1828, 3290, -3290, 5117, -5117}, + { 696, -696, 2320, -2320, 4176, -4176, 6496, -6496}, + { 868, -868, 2893, -2893, 5207, -5207, 8099, -8099}, + {1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933}, + {1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005}, + {1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336}, +}; + + +/* The Least Mean Squares Filter is the heart of QOA. It predicts the next +sample based on the previous 4 reconstructed samples. It does so by continuously +adjusting 4 weights based on the residual of the previous prediction. + +The next sample is predicted as the sum of (weight[i] * history[i]). + +The adjustment of the weights is done with a "Sign-Sign-LMS" that adds or +subtracts the residual to each weight, based on the corresponding sample from +the history. This, surprisingly, is sufficient to get worthwhile predictions. + +This is all done with fixed point integers. Hence the right-shifts when updating +the weights and calculating the prediction. */ + +static int qoa_lms_predict(qoa_lms_t *lms) { + int prediction = 0; + for (int i = 0; i < QOA_LMS_LEN; i++) { + prediction += lms->weights[i] * lms->history[i]; + } + return prediction >> 13; +} + +static void qoa_lms_update(qoa_lms_t *lms, int sample, int residual) { + int delta = residual >> 4; + for (int i = 0; i < QOA_LMS_LEN; i++) { + lms->weights[i] += lms->history[i] < 0 ? -delta : delta; + } + + for (int i = 0; i < QOA_LMS_LEN-1; i++) { + lms->history[i] = lms->history[i+1]; + } + lms->history[QOA_LMS_LEN-1] = sample; +} + + +/* qoa_div() implements a rounding division, but avoids rounding to zero for +small numbers. E.g. 0.1 will be rounded to 1. Note that 0 itself still +returns as 0, which is handled in the qoa_quant_tab[]. +qoa_div() takes an index into the .16 fixed point qoa_reciprocal_tab as an +argument, so it can do the division with a cheaper integer multiplication. */ + +static inline int qoa_div(int v, int scalefactor) { + int reciprocal = qoa_reciprocal_tab[scalefactor]; + int n = (v * reciprocal + (1 << 15)) >> 16; + n = n + ((v > 0) - (v < 0)) - ((n > 0) - (n < 0)); /* round away from 0 */ + return n; +} + +static inline int qoa_clamp(int v, int min, int max) { + if (v < min) { return min; } + if (v > max) { return max; } + return v; +} + +/* This specialized clamp function for the signed 16 bit range improves decode +performance quite a bit. The extra if() statement works nicely with the CPUs +branch prediction as this branch is rarely taken. */ + +static inline int qoa_clamp_s16(int v) { + if ((unsigned int)(v + 32768) > 65535) { + if (v < -32768) { return -32768; } + if (v > 32767) { return 32767; } + } + return v; +} + +static inline qoa_uint64_t qoa_read_u64(const unsigned char *bytes, unsigned int *p) { + bytes += *p; + *p += 8; + return + ((qoa_uint64_t)(bytes[0]) << 56) | ((qoa_uint64_t)(bytes[1]) << 48) | + ((qoa_uint64_t)(bytes[2]) << 40) | ((qoa_uint64_t)(bytes[3]) << 32) | + ((qoa_uint64_t)(bytes[4]) << 24) | ((qoa_uint64_t)(bytes[5]) << 16) | + ((qoa_uint64_t)(bytes[6]) << 8) | ((qoa_uint64_t)(bytes[7]) << 0); +} + +static inline void qoa_write_u64(qoa_uint64_t v, unsigned char *bytes, unsigned int *p) { + bytes += *p; + *p += 8; + bytes[0] = (v >> 56) & 0xff; + bytes[1] = (v >> 48) & 0xff; + bytes[2] = (v >> 40) & 0xff; + bytes[3] = (v >> 32) & 0xff; + bytes[4] = (v >> 24) & 0xff; + bytes[5] = (v >> 16) & 0xff; + bytes[6] = (v >> 8) & 0xff; + bytes[7] = (v >> 0) & 0xff; +} + + +/* ----------------------------------------------------------------------------- + Encoder */ + +unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes) { + unsigned int p = 0; + qoa_write_u64(((qoa_uint64_t)QOA_MAGIC << 32) | qoa->samples, bytes, &p); + return p; +} + +unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes) { + unsigned int channels = qoa->channels; + + unsigned int p = 0; + unsigned int slices = (frame_len + QOA_SLICE_LEN - 1) / QOA_SLICE_LEN; + unsigned int frame_size = QOA_FRAME_SIZE(channels, slices); + int prev_scalefactor[QOA_MAX_CHANNELS] = {0}; + + /* Write the frame header */ + qoa_write_u64(( + (qoa_uint64_t)qoa->channels << 56 | + (qoa_uint64_t)qoa->samplerate << 32 | + (qoa_uint64_t)frame_len << 16 | + (qoa_uint64_t)frame_size + ), bytes, &p); + + + for (unsigned int c = 0; c < channels; c++) { + /* Write the current LMS state */ + qoa_uint64_t weights = 0; + qoa_uint64_t history = 0; + for (int i = 0; i < QOA_LMS_LEN; i++) { + history = (history << 16) | (qoa->lms[c].history[i] & 0xffff); + weights = (weights << 16) | (qoa->lms[c].weights[i] & 0xffff); + } + qoa_write_u64(history, bytes, &p); + qoa_write_u64(weights, bytes, &p); + } + + /* We encode all samples with the channels interleaved on a slice level. + E.g. for stereo: (ch-0, slice 0), (ch 1, slice 0), (ch 0, slice 1), ...*/ + for (unsigned int sample_index = 0; sample_index < frame_len; sample_index += QOA_SLICE_LEN) { + + for (unsigned int c = 0; c < channels; c++) { + int slice_len = qoa_clamp(QOA_SLICE_LEN, 0, frame_len - sample_index); + int slice_start = sample_index * channels + c; + int slice_end = (sample_index + slice_len) * channels + c; + + /* Brute force search for the best scalefactor. Just go through all + 16 scalefactors, encode all samples for the current slice and + meassure the total squared error. */ + qoa_uint64_t best_rank = -1; + #ifdef QOA_RECORD_TOTAL_ERROR + qoa_uint64_t best_error = -1; + #endif + qoa_uint64_t best_slice = 0; + qoa_lms_t best_lms; + int best_scalefactor = 0; + + for (int sfi = 0; sfi < 16; sfi++) { + /* There is a strong correlation between the scalefactors of + neighboring slices. As an optimization, start testing + the best scalefactor of the previous slice first. */ + int scalefactor = (sfi + prev_scalefactor[c]) & (16 - 1); + + /* We have to reset the LMS state to the last known good one + before trying each scalefactor, as each pass updates the LMS + state when encoding. */ + qoa_lms_t lms = qoa->lms[c]; + qoa_uint64_t slice = scalefactor; + qoa_uint64_t current_rank = 0; + #ifdef QOA_RECORD_TOTAL_ERROR + qoa_uint64_t current_error = 0; + #endif + + for (int si = slice_start; si < slice_end; si += channels) { + int sample = sample_data[si]; + int predicted = qoa_lms_predict(&lms); + + int residual = sample - predicted; + int scaled = qoa_div(residual, scalefactor); + int clamped = qoa_clamp(scaled, -8, 8); + int quantized = qoa_quant_tab[clamped + 8]; + int dequantized = qoa_dequant_tab[scalefactor][quantized]; + int reconstructed = qoa_clamp_s16(predicted + dequantized); + + + /* If the weights have grown too large, we introduce a penalty + here. This prevents pops/clicks in certain problem cases */ + int weights_penalty = (( + lms.weights[0] * lms.weights[0] + + lms.weights[1] * lms.weights[1] + + lms.weights[2] * lms.weights[2] + + lms.weights[3] * lms.weights[3] + ) >> 18) - 0x8ff; + if (weights_penalty < 0) { + weights_penalty = 0; + } + + long long error = (sample - reconstructed); + qoa_uint64_t error_sq = error * error; + + current_rank += error_sq + weights_penalty * weights_penalty; + #ifdef QOA_RECORD_TOTAL_ERROR + current_error += error_sq; + #endif + if (current_rank > best_rank) { + break; + } + + qoa_lms_update(&lms, reconstructed, dequantized); + slice = (slice << 3) | quantized; + } + + if (current_rank < best_rank) { + best_rank = current_rank; + #ifdef QOA_RECORD_TOTAL_ERROR + best_error = current_error; + #endif + best_slice = slice; + best_lms = lms; + best_scalefactor = scalefactor; + } + } + + prev_scalefactor[c] = best_scalefactor; + + qoa->lms[c] = best_lms; + #ifdef QOA_RECORD_TOTAL_ERROR + qoa->error += best_error; + #endif + + /* If this slice was shorter than QOA_SLICE_LEN, we have to left- + shift all encoded data, to ensure the rightmost bits are the empty + ones. This should only happen in the last frame of a file as all + slices are completely filled otherwise. */ + best_slice <<= (QOA_SLICE_LEN - slice_len) * 3; + qoa_write_u64(best_slice, bytes, &p); + } + } + + return p; +} + +void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len) { + if ( + qoa->samples == 0 || + qoa->samplerate == 0 || qoa->samplerate > 0xffffff || + qoa->channels == 0 || qoa->channels > QOA_MAX_CHANNELS + ) { + return NULL; + } + + /* Calculate the encoded size and allocate */ + unsigned int num_frames = (qoa->samples + QOA_FRAME_LEN-1) / QOA_FRAME_LEN; + unsigned int num_slices = (qoa->samples + QOA_SLICE_LEN-1) / QOA_SLICE_LEN; + unsigned int encoded_size = 8 + /* 8 byte file header */ + num_frames * 8 + /* 8 byte frame headers */ + num_frames * QOA_LMS_LEN * 4 * qoa->channels + /* 4 * 4 bytes lms state per channel */ + num_slices * 8 * qoa->channels; /* 8 byte slices */ + + unsigned char *bytes = QOA_MALLOC(encoded_size); + + for (unsigned int c = 0; c < qoa->channels; c++) { + /* Set the initial LMS weights to {0, 0, -1, 2}. This helps with the + prediction of the first few ms of a file. */ + qoa->lms[c].weights[0] = 0; + qoa->lms[c].weights[1] = 0; + qoa->lms[c].weights[2] = -(1<<13); + qoa->lms[c].weights[3] = (1<<14); + + /* Explicitly set the history samples to 0, as we might have some + garbage in there. */ + for (int i = 0; i < QOA_LMS_LEN; i++) { + qoa->lms[c].history[i] = 0; + } + } + + + /* Encode the header and go through all frames */ + unsigned int p = qoa_encode_header(qoa, bytes); + #ifdef QOA_RECORD_TOTAL_ERROR + qoa->error = 0; + #endif + + int frame_len = QOA_FRAME_LEN; + for (unsigned int sample_index = 0; sample_index < qoa->samples; sample_index += frame_len) { + frame_len = qoa_clamp(QOA_FRAME_LEN, 0, qoa->samples - sample_index); + const short *frame_samples = sample_data + sample_index * qoa->channels; + unsigned int frame_size = qoa_encode_frame(frame_samples, qoa, frame_len, bytes + p); + p += frame_size; + } + + *out_len = p; + return bytes; +} + + + +/* ----------------------------------------------------------------------------- + Decoder */ + +unsigned int qoa_max_frame_size(qoa_desc *qoa) { + return QOA_FRAME_SIZE(qoa->channels, QOA_SLICES_PER_FRAME); +} + +unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa) { + unsigned int p = 0; + if (size < QOA_MIN_FILESIZE) { + return 0; + } + + + /* Read the file header, verify the magic number ('qoaf') and read the + total number of samples. */ + qoa_uint64_t file_header = qoa_read_u64(bytes, &p); + + if ((file_header >> 32) != QOA_MAGIC) { + return 0; + } + + qoa->samples = file_header & 0xffffffff; + if (!qoa->samples) { + return 0; + } + + /* Peek into the first frame header to get the number of channels and + the samplerate. */ + qoa_uint64_t frame_header = qoa_read_u64(bytes, &p); + qoa->channels = (frame_header >> 56) & 0x0000ff; + qoa->samplerate = (frame_header >> 32) & 0xffffff; + + if ( + qoa->channels == 0 || qoa->samples == 0 || qoa->samplerate == 0 || + qoa->channels > QOA_MAX_CHANNELS + ) { + return 0; + } + + return 8; +} + +unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len) { + unsigned int p = 0; + if (frame_len) { + *frame_len = 0; + } + + if (size < 8 + QOA_LMS_LEN * 4 * qoa->channels) { + return 0; + } + + /* Read and verify the frame header */ + qoa_uint64_t frame_header = qoa_read_u64(bytes, &p); + unsigned int channels = (frame_header >> 56) & 0x0000ff; + unsigned int samplerate = (frame_header >> 32) & 0xffffff; + unsigned int samples = (frame_header >> 16) & 0x00ffff; + unsigned int frame_size = (frame_header ) & 0x00ffff; + + unsigned int header_size = 8 + QOA_LMS_LEN * 4 * channels; + unsigned int data_size = frame_size - header_size; + unsigned int max_total_slices = data_size / 8; + unsigned int num_slices = (samples + QOA_SLICE_LEN - 1) / QOA_SLICE_LEN; + + if ( + channels != qoa->channels || + samplerate != qoa->samplerate || + frame_size < header_size || + frame_size > size || + num_slices > QOA_SLICES_PER_FRAME || + num_slices * channels > max_total_slices + ) { + return 0; + } + + + /* Read the LMS state: 4 x 2 bytes history, 4 x 2 bytes weights per channel */ + for (unsigned int c = 0; c < channels; c++) { + qoa_uint64_t history = qoa_read_u64(bytes, &p); + qoa_uint64_t weights = qoa_read_u64(bytes, &p); + for (int i = 0; i < QOA_LMS_LEN; i++) { + qoa->lms[c].history[i] = ((signed short)(history >> 48)); + history <<= 16; + qoa->lms[c].weights[i] = ((signed short)(weights >> 48)); + weights <<= 16; + } + } + + + /* Decode all slices for all channels in this frame */ + for (unsigned int sample_index = 0; sample_index < samples; sample_index += QOA_SLICE_LEN) { + for (unsigned int c = 0; c < channels; c++) { + qoa_uint64_t slice = qoa_read_u64(bytes, &p); + + int scalefactor = (slice >> 60) & 0xf; + slice <<= 4; + + int slice_start = sample_index * channels + c; + int slice_end = qoa_clamp(sample_index + QOA_SLICE_LEN, 0, samples) * channels + c; + + for (int si = slice_start; si < slice_end; si += channels) { + int predicted = qoa_lms_predict(&qoa->lms[c]); + int quantized = (slice >> 61) & 0x7; + int dequantized = qoa_dequant_tab[scalefactor][quantized]; + int reconstructed = qoa_clamp_s16(predicted + dequantized); + + sample_data[si] = reconstructed; + slice <<= 3; + + qoa_lms_update(&qoa->lms[c], reconstructed, dequantized); + } + } + } + + if (frame_len) { + *frame_len = samples; + } + return p; +} + +short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *qoa) { + unsigned int p = qoa_decode_header(bytes, size, qoa); + if (!p) { + return NULL; + } + + /* Calculate the required size of the sample buffer and allocate, round up to full frames */ + unsigned long long num_frames = ((unsigned long long)qoa->samples + QOA_FRAME_LEN - 1) / QOA_FRAME_LEN; + unsigned long long total_samples_ull = num_frames * QOA_FRAME_LEN * (unsigned long long)qoa->channels; + + if (total_samples_ull > 0x7fffffff) { return NULL; } + + unsigned int total_samples = (unsigned int)total_samples_ull; + short *sample_data = QOA_MALLOC(total_samples * sizeof(short)); + if (!sample_data) { return NULL; } + + unsigned int sample_index = 0; + unsigned int frame_len; + unsigned int frame_size; + + /* Decode all frames */ + do { + short *sample_ptr = sample_data + sample_index * qoa->channels; + frame_size = qoa_decode_frame(bytes + p, size - p, qoa, sample_ptr, &frame_len); + + p += frame_size; + sample_index += frame_len; + } while (frame_len == QOA_FRAME_LEN && sample_index < qoa->samples); + + qoa->samples = sample_index; + return sample_data; +} + + + +/* ----------------------------------------------------------------------------- + File read/write convenience functions */ + +#ifndef QOA_NO_STDIO +#include + +int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa) { + FILE *f = fopen(filename, "wb"); + unsigned int size; + void *encoded; + + if (!f) { + return 0; + } + + encoded = qoa_encode(sample_data, qoa, &size); + if (!encoded) { + fclose(f); + return 0; + } + + fwrite(encoded, 1, size, f); + fclose(f); + + QOA_FREE(encoded); + return size; +} + +void *qoa_read(const char *filename, qoa_desc *qoa) { + FILE *f = fopen(filename, "rb"); + int size, bytes_read; + void *data; + short *sample_data; + + if (!f) { + return NULL; + } + + fseek(f, 0, SEEK_END); + size = ftell(f); + if (size <= 0) { + fclose(f); + return NULL; + } + fseek(f, 0, SEEK_SET); + + data = QOA_MALLOC(size); + if (!data) { + fclose(f); + return NULL; + } + + bytes_read = fread(data, 1, size, f); + fclose(f); + + sample_data = qoa_decode(data, bytes_read, qoa); + QOA_FREE(data); + return sample_data; +} + +#endif /* QOA_NO_STDIO */ +#endif /* QOA_IMPLEMENTATION */ diff --git a/tests/fixtures/qoa/qoa_ref.c b/tests/fixtures/qoa/qoa_ref.c new file mode 100644 index 0000000..f691b54 --- /dev/null +++ b/tests/fixtures/qoa/qoa_ref.c @@ -0,0 +1,52 @@ +/* tests/fixtures/qoa/qoa_ref.c: the qoa.h reference encoder / decoder for tools/fixtures/qoa.py. + qoa_ref enc encode raw interleaved s16le with qoa_encode + qoa_ref dec decode with qoa_decode (prints channels rate samples) */ +#include +#include +#include +#define QOA_IMPLEMENTATION +#include "qoa.h" + +static unsigned char *slurp(const char *path, long *size) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + *size = ftell(f); + fseek(f, 0, SEEK_SET); + unsigned char *d = malloc(*size ? *size : 1); + if (fread(d, 1, *size, f) != (size_t)*size) { fclose(f); return NULL; } + fclose(f); + return d; +} + +int main(int argc, char **argv) { + if (argc == 6 && !strcmp(argv[1], "enc")) { + long size; + short *pcm = (short *)slurp(argv[4], &size); + qoa_desc q; + memset(&q, 0, sizeof q); + q.channels = atoi(argv[2]); + q.samplerate = atoi(argv[3]); + q.samples = size / 2 / q.channels; + unsigned int len; + void *out = qoa_encode(pcm, &q, &len); + if (!out) return 1; + FILE *f = fopen(argv[5], "wb"); + fwrite(out, 1, len, f); + fclose(f); + return 0; + } + if (argc == 4 && !strcmp(argv[1], "dec")) { + long size; + unsigned char *d = slurp(argv[2], &size); + qoa_desc q; + short *pcm = qoa_decode(d, (int)size, &q); + if (!pcm) return 1; + FILE *f = fopen(argv[3], "wb"); + fwrite(pcm, 2, (size_t)q.samples * q.channels, f); + fclose(f); + printf("%u %u %u\n", q.channels, q.samplerate, q.samples); + return 0; + } + return 2; +} diff --git a/tools/fixtures/qoa.py b/tools/fixtures/qoa.py new file mode 100644 index 0000000..b4b2859 --- /dev/null +++ b/tools/fixtures/qoa.py @@ -0,0 +1,48 @@ +# QOA fixtures (tools/fixtures.py): audio/qoa and codecs/audio/Qoa. The reference is qoa.h itself +# (tests/fixtures/qoa/qoa.h, MIT, compiled here with nix gcc through tests/fixtures/qoa/qoa_ref.c) plus ffmpeg's decoder. +# tests/gen/qoa_cases.luau { name, data (qoa.h's encoding of the signal), rate, ch, ref (ffmpeg s16le), +# qoaref (qoa.h's decode, s16le), sig (the signal module name) } +# tests/gen/qoa_sig_*.luau the signals (our encoder must write the same bytes as qoa.h) +import importlib.util, os, shutil, struct, subprocess, tempfile + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tests/fixtures/qoa", "src/Formats/codecs/audio/Qoa"] + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="fmt-qoa-") + try: + exe = os.path.join(work, "qoa_ref") + ctx.nix("gcc", ["gcc", "-O2", "-o", exe, os.path.join(ctx.root, "tests/fixtures/qoa/qoa_ref.c")]) + cases = [] + for name, kind, rate, ch, frames in (("stereo-44k", "music", 44100, 2, 12000), ("mono-22k", "sweep", 22050, 1, 5120), + ("6ch-48k", "sine", 48000, 6, 700), ("loud-mono", "loud", 8000, 1, 5121), + ("square-stereo", "square", 32000, 2, 6000)): + sig = A.signal(kind, rate, ch, frames, seed=len(cases) + 40) + mod = "qoa_sig_" + name.replace("-", "_") + A.emit_signal(ctx, mod, sig, rate, ch) + raw = os.path.join(work, "in.raw") + with open(raw, "wb") as f: + f.write(struct.pack("<%dh" % len(sig), *D.s16(sig))) + qoa = os.path.join(work, "out.qoa") + subprocess.run([exe, "enc", str(ch), str(rate), raw, qoa], check=True) + data = open(qoa, "rb").read() + dec = os.path.join(work, "dec.raw") + subprocess.run([exe, "dec", qoa, dec], check=True, capture_output=True) + ref = D.ffs16(ctx, data, "qoa") + cases.append(dict(name=name, data=data, rate=rate, ch=ch, ref=ref, qoaref=open(dec, "rb").read(), sig=mod)) + ctx.emit("qoa_cases", cases) + finally: + shutil.rmtree(work, ignore_errors=True) From 0ce8dd143ffebdb36efc6f1207c81c08205723d5 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:26:41 -0500 Subject: [PATCH 5/9] ws-audio2: regenerate the registry --- docs/FORMATS.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5875495..ed2356a 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -18,13 +18,17 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | adx | .adx | yes | yes | streaming: true, lossy: true, loops: true, channels: 8 | `tests/audio/adx.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 | brstm | .brstm .bcstm .bfstm | yes | - | streaming: true, lossy: true, loops: true, containers: "RSTM", "CSTM", "FSTM" | `tests/audio/brstm.luau` | | audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | | audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` | +| audio | qoa | .qoa | yes | yes | streaming: true, lossy: true, seek: true, channels: 8 | `tests/audio/qoa.luau` | +| audio | vag | .vag | yes | yes | streaming: true, lossy: true, loops: true, channels: 2 | `tests/audio/vag.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | @@ -95,6 +99,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: - codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. + - codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part From 3f6823cbe507d92f249fa8305748aa66e7e75b37 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:28:31 -0500 Subject: [PATCH 6/9] ws-audio2: audio/brstm variant() names bcstm / bfstm for F.detect --- src/Formats/audio/brstm/init.luau | 6 ++++++ tests/audio/brstm.luau | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Formats/audio/brstm/init.luau b/src/Formats/audio/brstm/init.luau index 8aac43b..1e9ddeb 100644 --- a/src/Formats/audio/brstm/init.luau +++ b/src/Formats/audio/brstm/init.luau @@ -44,6 +44,12 @@ function Brstm.sniff(r: Bytes.Reader): number return if bom == "\254\255" or bom == "\255\254" then 1 else 0 end +-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect +function Brstm.variant(r: Bytes.Reader): string? + local m = r:peek(4) + return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil +end + -- ------------------------------------------------------------------------------------------------ decode function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Brstm.open(r) diff --git a/tests/audio/brstm.luau b/tests/audio/brstm.luau index e9300ff..9a4b6a1 100644 --- a/tests/audio/brstm.luau +++ b/tests/audio/brstm.luau @@ -17,7 +17,9 @@ for _, c in Cases do table.insert(samples, c.data) t:eq(Brstm.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") H.check(t, Brstm, c) - t:eq(F.detect(c.data), "brstm", c.name .. ": F.detect") + local flavour = ({ RSTM = "brstm", CSTM = "bcstm", FSTM = "bfstm" })[string.sub(c.data, 1, 4)] + t:eq(F.detect(c.data), flavour, c.name .. ": F.detect names the flavour") + t:check(F.format(flavour) ~= nil or F.format("brstm") ~= nil, c.name .. ": the flavour resolves") end t:note("%d files bit-exact with vgmstream", #Cases) From 27172923668cc881d03b887e6af68b1002cc70b3 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:34:28 -0500 Subject: [PATCH 7/9] ws-audio2: AIFF-C and CAF ima4 (Apple IMA ADPCM) decode through codecs/audio/Adpcm aiff: COMM counts ima4 packets; caf: ima4 through Adpcm/Decoder.blocks (exact seeking), and a constant-size packet stream whose pakt lists no packets now uses bytesPerPacket (was 0 frames). Bit-exact with ffmpeg. --- src/Formats/Registry.luau | 4 ++-- src/Formats/audio/aiff/init.luau | 33 ++++++++++++++++++++++++++------ src/Formats/audio/caf/init.luau | 26 +++++++++++++++++++++---- tests/audio/aiff.luau | 10 ++++++---- tests/audio/caf.luau | 12 ++++++++++++ tools/fixtures/aiff.py | 4 +++- tools/fixtures/caf_ima4.py | 27 ++++++++++++++++++++++++++ 7 files changed, 99 insertions(+), 17 deletions(-) create mode 100644 tools/fixtures/caf_ima4.py diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 20acbb1..ee1029e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -188,7 +188,7 @@ local list: { Entry } = { path = "audio/aiff", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, load = function() return require("@formats/audio/aiff") @@ -224,7 +224,7 @@ local list: { Entry } = { path = "audio/caf", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/caf") diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index a0a4a8c..03f9b0c 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -3,8 +3,9 @@ -- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw -- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated -- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / --- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 / --- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; +-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, +-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -12,6 +13,7 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Chunks = require("@formats/containers/Chunks") local Pcm = require("@formats/codecs/audio/Pcm") +local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Aiff = { @@ -19,7 +21,7 @@ local Aiff = { category = "audio", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, } @@ -115,6 +117,8 @@ local function sampleFormat(comp: string, bits: number): (string?, string?) return "ulaw", nil elseif comp == "alaw" or comp == "ALAW" then return "alaw", nil + elseif comp == "ima4" then + return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks end return nil, "compression " .. string.format("%q", comp) end @@ -138,6 +142,7 @@ type Info = { compression: string, aifc: boolean, dataOffset: number, -- absolute in r.buf + dataSize: number, -- bytes of sample data present truncated: boolean, tags: Types.Tags, } @@ -194,6 +199,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) compression = comp, aifc = aifc, dataOffset = 0, + dataSize = 0, truncated = false, tags = tags, } @@ -228,13 +234,19 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) if fi.frames > 0 and not ssnd then return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) end - local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format] - local present = if ssnd then ssndLen // frameBytes else 0 + local present + if fi.format == "ima4" then + fi.frames *= 64 -- COMM counts packets + present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0 + else + present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0 + end if present < fi.frames then fi.frames = present fi.truncated = true end fi.dataOffset = ssnd or base + fi.dataSize = ssndLen return fi, nil end @@ -360,7 +372,16 @@ function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err. if info.frames > maxFrames then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) end - local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + local dec, derr + if info.format == "ima4" then + local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags } + dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames }) + if dec then + (dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64) + end + else + dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + end if not dec then return nil, derr end diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index fd46e96..cb6f2df 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -3,7 +3,8 @@ -- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac, -- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown -- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / --- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED). +-- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: +-- other compressed formats (UNSUPPORTED). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -14,6 +15,7 @@ local Pcm = require("@formats/codecs/audio/Pcm") local Stream = require("@formats/codecs/audio/Stream") local Aac = require("@formats/codecs/audio/Aac") local Alac = require("@formats/codecs/audio/Alac") +local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Caf = { @@ -21,7 +23,7 @@ local Caf = { category = "audio", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, } @@ -333,7 +335,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) end -- packetised codecs local sizes = p.packets - if not sizes then + if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none if d.bytesPerPacket > 0 then local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket sizes = table.create(n, d.bytesPerPacket) @@ -425,7 +427,23 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E if not p then return nil, err end - local s, serr = source(r, p :: Parsed) + local pp = p :: Parsed + if pp.desc.format == "ima4" then + -- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets + local ch = pp.desc.channels + local packets = (pp.dataEnd - pp.dataStart) // (34 * ch) + local frames = packets * 64 + if pp.validFrames and pp.validFrames >= 0 then + frames = math.min(frames, pp.validFrames) + end + local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 } + local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames }) + if d then + d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64) + end + return d, derr + end + local s, serr = source(r, pp) if not s then return nil, serr end diff --git a/tests/audio/aiff.luau b/tests/audio/aiff.luau index 079f34a..52b4609 100644 --- a/tests/audio/aiff.luau +++ b/tests/audio/aiff.luau @@ -1,5 +1,5 @@ -- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C --- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; +-- sowt / fl32 / fl64 / ulaw / alaw / ima4, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; -- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. -- Fixtures: tools/fixtures/aiff.py. local T = require("@tests/T") @@ -149,9 +149,11 @@ do t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e)) local c = case("ffmpeg-fl32").data local p = string.find(c, "fl32", 1, true) :: number - local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4) - local _, e2 = Aiff.decode(reader(ima)) - t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2)) + local mac = string.sub(c, 1, p - 1) .. "MAC3" .. string.sub(c, p + 4) + local _, e2 = Aiff.decode(reader(mac)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "MAC3: UNSUPPORTED: " .. tostring(e2)) + local i4 = Aiff.decode(reader(case("ffmpeg-ima4").data)) :: any + t:check(i4.meta.source.compression == "ima4" and i4.frames % 64 == 0, "ima4 meta / whole packets") local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30))) t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3)) local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 }) diff --git a/tests/audio/caf.luau b/tests/audio/caf.luau index c0f40ff..450b085 100644 --- a/tests/audio/caf.luau +++ b/tests/audio/caf.luau @@ -174,4 +174,16 @@ do end, samples, { mutations = 30 }) end +-- ------------------------------------------------------------------------------------------------ IMA4 +do + local H = require("@tests/audio/_adpcm") + local Ima4 = require("@tests/gen/caf_ima4") + for _, c in Ima4 do + H.check(t, Caf, c) + local a = Caf.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:eq(a.meta.source.codec, "ima4", c.name .. ": codec") + end + t:note("%d IMA4 files bit-exact with ffmpeg", #Ima4) +end + t:done() diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py index 1dafc07..d31fa69 100644 --- a/tools/fixtures/aiff.py +++ b/tools/fixtures/aiff.py @@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm"] +INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm", "src/Formats/codecs/audio/Adpcm"] def ff(codec, src="{in}", extra=()): @@ -34,6 +34,8 @@ def generate(ctx): ("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]), ("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]), ("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]), + ("ffmpeg-ima4", "ffmpeg", ff("adpcm_ima_qt")), + ("ffmpeg-ima4-mono", "ffmpeg", ff("adpcm_ima_qt", "{in_mono}")), ] encodes = [ ("s16", "nil", 2), diff --git a/tools/fixtures/caf_ima4.py b/tools/fixtures/caf_ima4.py new file mode 100644 index 0000000..1d21ffb --- /dev/null +++ b/tools/fixtures/caf_ima4.py @@ -0,0 +1,27 @@ +# CAF IMA4 fixtures (tools/fixtures.py): audio/caf's Apple IMA ADPCM (codecs/audio/Adpcm), written and decoded by ffmpeg. +# tests/gen/caf_ima4.luau { name, data, rate, ch, ref (ffmpeg s16le) } +import importlib.util, os + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["src/Formats/codecs/audio/Adpcm", "src/Formats/audio/caf"] + + +def generate(ctx): + cases = [] + for name, kind, rate, ch, frames in (("ima4-stereo", "music", 44100, 2, 9000), ("ima4-mono", "sweep", 22050, 1, 4410)): + sig = A.signal(kind, rate, ch, frames, seed=ch + 50) + data = D.ffencode(ctx, A.wav(sig, rate, ch), ["-c:a", "adpcm_ima_qt"], "caf") + cases.append(dict(name=name, data=data, rate=rate, ch=ch, ref=D.ffs16(ctx, data, "caf"))) + ctx.emit("caf_ima4", cases) From 9466c5f471ca7b64521e9a4687eae6e2a4a44bd2 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:37:23 -0500 Subject: [PATCH 8/9] ws-audio2: music/xm decodes ModPlug ADPCM samples (were silence), through codecs/audio/Adpcm.modplug Fixture: tools/fixtures/_tracker.py write_xm gains an optional per-sample "adpcm" payload (two lines, shared with the tracker generators, backward compatible); a new xm case renders the same as openmpt123. --- src/Formats/Registry.luau | 2 +- src/Formats/codecs/audio/Adpcm/init.luau | 19 +++++++++++++++ src/Formats/music/xm/init.luau | 23 ++++++++++++------ tests/codecs/adpcm.luau | 19 +++++++++++++++ tests/music/xm.luau | 10 ++++++-- tools/fixtures/_tracker.py | 5 ++-- tools/fixtures/xm.py | 31 +++++++++++++++++++++++- 7 files changed, 96 insertions(+), 13 deletions(-) diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ee1029e..576cb69 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -956,7 +956,7 @@ local list: { Entry } = { path = "music/xm", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, load = function() return require("@formats/music/xm") diff --git a/src/Formats/codecs/audio/Adpcm/init.luau b/src/Formats/codecs/audio/Adpcm/init.luau index 68b8d25..9741805 100644 --- a/src/Formats/codecs/audio/Adpcm/init.luau +++ b/src/Formats/codecs/audio/Adpcm/init.luau @@ -19,6 +19,7 @@ -- 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 +-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD 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 @@ -685,4 +686,22 @@ function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: b writei32(st, so + 4, h2) end +-- ------------------------------------------------------------------------------------------------ ModPlug +-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at +-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). +-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) + local tab = table.create(16, 0) + for k = 0, 15 do + tab[k + 1] = buffer.readi8(src, p + k) + end + local v = 0 + for i = 0, count - 1 do + local b = readu8(src, p + 16 + rshift(i, 1)) + local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4) + v = (v + tab[nib + 1] + 128) % 256 - 128 + writef32(dst, (d + i) * 4, v / 128) + end +end + return Adpcm diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau index 080795c..cab28dd 100644 --- a/src/Formats/music/xm/init.luau +++ b/src/Formats/music/xm/init.luau @@ -5,13 +5,15 @@ -- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga -- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files -- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). --- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write. +-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's +-- stereo-sample / extra-effect extensions on write. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Tracker = require("@formats/codecs/audio/Tracker") +local Adpcm = require("@formats/codecs/audio/Adpcm") -- ------------------------------------------------------------------------------------------------ contract local Xm = { @@ -19,7 +21,7 @@ local Xm = { category = "music", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, } @@ -240,12 +242,19 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.relativeNote = h.rel s.pan = h.pan local frames = h.len // bps - if h.res == 0xAD then - -- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length) - local bytes = 16 + (h.len + 1) // 2 - r:skip(math.min(bytes, r:remaining())) - frames = h.len + if h.res == 0xAD and bits == 8 then + -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps + -- the samples whose nibbles are present + frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) + total += frames * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end s.data = buffer.create(frames * 4) + if frames > 0 then + Adpcm.modplug(r.buf, r.pos, frames, s.data, 0) + end + r:skip(math.min(16 + (h.len + 1) // 2, r:remaining())) else local avail = r:remaining() // bps local got = math.min(frames, avail) diff --git a/tests/codecs/adpcm.luau b/tests/codecs/adpcm.luau index 207a61e..6742105 100644 --- a/tests/codecs/adpcm.luau +++ b/tests/codecs/adpcm.luau @@ -72,6 +72,22 @@ do t:check(z1 == 0 and z2 == 0, "adx coefs of rate 0") end +-- ModPlug ADPCM: deltas from the table, wrapping as a signed byte +do + local src = buffer.create(18) + for k = 0, 15 do + buffer.writei8(src, k, if k == 1 then 100 elseif k == 2 then -3 else 0) + end + buffer.writeu8(src, 16, 0x11) -- +100, +100 (wraps to -56) + buffer.writeu8(src, 17, 0x02) -- -3, +0 + local out = buffer.create(16) + Adpcm.modplug(src, 0, 4, out, 0) + local want = { 100, -56, -59, -59 } + for i, v in want do + t:eq(buffer.readf32(out, (i - 1) * 4) * 128, v, "modplug sample " .. i) + end +end + -- ------------------------------------------------------------------------------------------------ encoders local function snr(x: buffer, y: buffer, count: number): number local sig, err = 0, 0 @@ -216,6 +232,9 @@ t:fuzz("kernels", function(b: buffer) if n >= 1 then Adpcm.ima(b, 0, 0, 1, math.min(n * 2, 1000), true, st, 32, out, 0, 1) end + if n >= 17 then + Adpcm.modplug(b, 0, math.min((n - 16) * 2, 1000), out, 0) + 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 }) diff --git a/tests/music/xm.luau b/tests/music/xm.luau index 0afd6e2..df696ed 100644 --- a/tests/music/xm.luau +++ b/tests/music/xm.luau @@ -1,5 +1,6 @@ -- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/audio/Tracker and --- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length; a ModPlug ADPCM +-- sample), the XM writer's -- round trip, the contract, and the fuzz no-throw pass. local T = require("@tests/T") local S = require("@tests/music/_similar") @@ -44,7 +45,12 @@ for _, c in Cases do t:check(out, c.name .. ": encode " .. tostring(werr)) local m2 = Xm.decode(Bytes.reader(out :: buffer)) t:check(m2, c.name .. ": re-decode") - t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") + if c.name == "adpcm" then + -- ModPlug ADPCM is written back as delta PCM: the same samples, not the same bytes + t:eq(buffer.tostring(m2.samples[1].data), buffer.tostring(m.samples[1].data), c.name .. ": samples kept") + else + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") + end end -- seek: the position after a seek and the output continuing diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py index eeef247..b038167 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -242,9 +242,10 @@ def write_xm(title, instruments, orders, patterns, channels, speed=6, tempo=125, ls, ll, lt = s.get("loop") or (0, 0, 0) t = lt | (16 if bpsm == 2 else 0) out += struct.pack("= 128 else b + best = min(range(16), key=lambda k: abs(((cur + TABLE[k] + 128) % 256 - 128) - want)) + cur = (cur + TABLE[best] + 128) % 256 - 128 + nibs.append(best) + if len(nibs) % 2: + nibs.append(0) + return bytes(t & 255 for t in TABLE) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, len(nibs), 2)) + + +def song_adpcm(): + """a ModPlug ADPCM sample (OpenMPT's compressed 8-bit samples) played at a few pitches""" + raw = T.s8(T.synth("saw", 400, 100, 0.6)) + smp = {"name": "adpcm", "data": raw, "adpcm": modplug_adpcm(raw), "volume": 64, "pan": 128, "loop": (0, 400, 1)} + p = empty(2) + for i, note in enumerate((49, 53, 56, 61)): + put(p, i * 8, 0, note, 1) + put(p, i * 8 + 4, 1, note - 12, 1) + return T.write_xm("adpcm", [{"name": "adpcm", "samples": [smp]}], [0], [p], 2, speed=4, tempo=125) + + def generate(ctx): cases = [] - for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))): + for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False)), + ("adpcm", song_adpcm())): ref = T.reference(ctx, data, "xm") cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) ctx.emit("xm_cases", cases) From 5216cb29a1563c37331c6c1599eb9df6609d7b5d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:11 -0500 Subject: [PATCH 9/9] ws-audio2: bench lines (IMA / DSP decode, QOA encode / decode) and the guide's game audio section --- docs/guide/audio.md | 38 ++++++++++++++++++++++++++++++- tools/bench.luau | 55 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/docs/guide/audio.md b/docs/guide/audio.md index 94271f6..25f931d 100644 --- a/docs/guide/audio.md +++ b/docs/guide/audio.md @@ -179,6 +179,8 @@ Encoder options: | opus | `bitrate` (default 64000 per channel, 6000..510000); CELT only; resampled to 48 kHz | | aiff, au, voc | `sampleFormat` (see each format's `init.luau`) | | m4a, caf | ALAC (lossless); m4a and caf also keep tags | +| adx, vag | `loop = { start, stop }` (frames; default the source's `meta.source.loop`) | +| adpcm | `codec = "ima" \| "ima_wav" \| "ms"`, `blockAlign` (block codecs), `lowFirst` (ima nibble order) | `bitrate` is in **bits per second** for every encoder (`bitrate = 192000`), as the Decoder's `bitrate` field is. A value below 1000 is read as kbit/s (`bitrate = 192` is 192000), so older code that passed kbit/s to MP3 still works. @@ -189,7 +191,7 @@ Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the f | Read and write | Read only | |---|---| -| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC | +| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC), qoa, adx, vag, adpcm (raw IMA / MS) | aac (ADTS), m4a / caf AAC, brstm / bcstm / bfstm, KVAG, wav / aifc / caf IMA and MS ADPCM | Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see @@ -243,6 +245,40 @@ end Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or visualisers. +### Game audio and ADPCM + +Console and game engines store sound as 4-bit ADPCM or QOA: small, and cheap to decode while the game runs. They load +and save like any other audio. Loop points (ADX, VAG, BRSTM) come out in `meta.source.loop` (and `dec.loop`), in +frames, `stop` exclusive; the encoders write them back. + +```luau +local tone = F.Types.Audio.new(22050, 1, 22050) -- 1 s of 440 Hz +for i = 0, tone.frames - 1 do + buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(2 * math.pi * 440 * i / 22050)) +end +local qoa = assert(F.save(tone, nil, { format = "qoa" })) -- Quite OK Audio: 3.2 bits per sample, as qoa.h writes it +assert(F.detect(qoa) == "qoa" and F.audio.load(qoa).frames == tone.frames) +local adx = assert(F.save(tone, nil, { format = "adx", loop = { start = 0, stop = tone.frames } })) -- CRI ADX +local looped = assert(F.audio.load(adx)) +assert(looped.meta.source.loop.stop == tone.frames) +local vag = assert(F.save(tone, nil, { format = "vag" })) -- PlayStation VAG (mono VAGp; stereo is VAGi) +assert(F.audio.load(vag).frames >= tone.frames) -- + the blank frame VAGs start with, and frame padding +``` + +A raw ADPCM stream has no header, so the layout comes from the options, and only `opts.format` or the `.adpcm` / `.ima` +extension finds it: + + +```luau +local raw = assert(F.save(tone, nil, { format = "adpcm", codec = "ima" })) -- 4 bits per sample +local back = assert(F.audio.load(raw, { format = "adpcm", codec = "ima", sampleRate = 22050, channels = 1 })) +assert(back.frames == tone.frames) +``` + +Read only: Nintendo BRSTM / BCSTM / BFSTM (DSP ADPCM or PCM; `F.detect` names the flavour), KVAG, and the ADPCM +inside WAV (IMA, MS), AIFF-C and CAF (ima4). Decoding is bit-exact with vgmstream (ADX, VAG, BRSTM) and ffmpeg +(IMA, MS, ima4, QOA). Seeking is exact everywhere: the decoders keep the predictor state of every block they pass. + ## Gotchas - `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..a3966dc 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,58 @@ do jitTune(false) end end +-- ws-audio2: adpcm / qoa +do + -- codecs/audio/Adpcm (IMA nibble stream, Nintendo DSP frames) and QOA decode / encode, over generated signals; MB/s + -- of f32 output (MB/s of input for the encoder) + local Adpcm = require("@formats/codecs/audio/Adpcm") + local QoaCodec = require("@formats/codecs/audio/Qoa") + local Qoa = require("@formats/audio/qoa") + local n = 44100 * 5 + local sig = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + local t = i / 44100 + buffer.writef32(sig.samples, i * 8, 0.5 * math.sin(2 * math.pi * 440 * t) + 0.1 * math.sin(2 * math.pi * 3000 * t)) + buffer.writef32(sig.samples, i * 8 + 4, 0.4 * math.sin(2 * math.pi * 660 * t + 1)) + end + -- IMA: encode the left channel as a nibble stream, then decode it + local ima = buffer.create(n // 2) + Adpcm.imaEncode(sig.samples, 0, 2, n, buffer.create(8), 0, ima, 0, 0, 1, false) + local out = buffer.create(n * 4) + bench("adpcm ima decode", 5, n * 4, function() + Adpcm.ima(ima, 0, 0, 1, n, false, buffer.create(8), 0, out, 0, 1) + end) + -- DSP: random frames with 8 coefficient pairs + local frames = n // 14 + local dsp = buffer.create(frames * 8) + local seed = 1 + for i = 0, frames * 8 - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + local v = seed // 65536 % 256 + buffer.writeu8(dsp, i, if i % 8 == 0 then (v % 8) * 16 + v % 12 else v) + end + local coefs = buffer.create(64) + for k = 0, 7 do + buffer.writei32(coefs, k * 8, 1800 + k * 200) + buffer.writei32(coefs, k * 8 + 4, -900 - k * 100) + end + bench("adpcm dsp decode", 5, frames * 14 * 4, function() + Adpcm.dsp(dsp, 0, frames * 14, coefs, 0, buffer.create(8), 0, out, 0, 1) + end) + -- QOA (stereo 44.1 kHz) + local file = assert(Qoa.encode(sig)) + bench("qoa encode", 2, n * 2 * 4, function() + Qoa.encode(sig) + end) + local pcm = buffer.create(QoaCodec.FRAME_LEN * 2 * 4) + bench("qoa decode", 5, n * 2 * 4, function() + local p = 8 + while p < buffer.len(file) do + local _, size = QoaCodec.decodeFrame(file, p, buffer.len(file) - p, pcm, 0) + p += size :: number + end + end) + bench("qoa decode (F.load path)", 5, n * 2 * 4, function() + Qoa.decode(Bytes.reader(file)) + end) +end