diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b154d28..7a98235 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -21,6 +21,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | ape | .ape | yes | - | streaming: true, seek: true, lossless: true, float: true, depths: 8, 16, 24, 32 | `tests/audio/ape.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` | @@ -30,10 +31,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mpc | .mpc .mp+ .mpp | yes | - | codecs: "musepack", versions: 7, 8, streaming: true, lossy: true | `tests/audio/mpc.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 | tta | .tta | yes | - | streaming: true, seek: true, lossless: true, depths: 8, 16, 24 | `tests/audio/tta.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` | +| audio | wavpack | .wv | yes | - | streaming: true, seek: true, lossless: true, hybrid: true, float: true, depths: 8, 12, 16, 20, 24, 32 | `tests/audio/wavpack.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | | video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | @@ -102,6 +105,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the - 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/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 - codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, - codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats @@ -116,8 +120,10 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - 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 - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read + - codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description - codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. + - codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec - **compress** - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec diff --git a/docs/guide/audio.md b/docs/guide/audio.md index 84d8600..1168fc5 100644 --- a/docs/guide/audio.md +++ b/docs/guide/audio.md @@ -192,7 +192,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), qoa, adx, vag, adpcm (raw IMA / MS) | aac (ADTS), m4a / caf AAC, mpc (Musepack SV7 / SV8), ac3 (Dolby Digital), brstm / bcstm / bfstm, KVAG, wav / aifc / caf IMA and MS ADPCM | +| 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, mpc (Musepack SV7 / SV8), ac3 (Dolby Digital), brstm / bcstm / bfstm, KVAG, wav / aifc / caf IMA and MS ADPCM, wavpack (.wv + .wvc), ape, tta | 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 @@ -301,6 +301,40 @@ Read only: Nintendo BRSTM / BCSTM / BFSTM (DSP ADPCM or PCM; `F.detect` names th 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. +### Lossless: WavPack, Monkey's Audio, TTA + +WavPack (`.wv`), Monkey's Audio (`.ape`) and TTA (`.tta`) open and load like FLAC. Their tags (APEv2) come out in +`tags` with lower-case keys. Integer streams also have `readInt`, which returns the exact samples as i32. Every +frame of these formats is independent, so `seek` lands on the exact sample. + +```luau +local wv = assert(F.audio.open(wvBytes)) +assert(wv.bitsPerSample == 16 and wv.lossless and wv.tags.title == "Docs Tone") +local exact, n = wv:readInt(1024) -- i32 samples, as wvunpack writes them +assert(n == 1024 and buffer.readi32(exact, 0) == 0) +local ape = assert(F.audio.load(apeBytes)) -- any level, fast .. insane +assert(ape.meta.source.format == "ape" and ape.tags.artist == "formats-luau") +local tta = assert(F.audio.open(ttaBytes)) +tta:seek(0.5) +assert(math.abs(tta:position() - 0.5) < 1e-6) +``` + +A hybrid WavPack file holds a lossy stream. Its `.wvc` correction file makes it lossless again. Pass the correction +file as `correction`. When you load a file by path, the `.wvc` next to it is found automatically. Without it, the +file decodes lossy. + +```luau +local lossy = assert(F.audio.open(hybridWvBytes)) +local full = assert(F.audio.open(hybridWvBytes, { correction = hybridWvcBytes })) +assert(lossy.hybrid and not lossy.lossless and full.lossless) +``` + + +```luau +local song = assert(F.audio.load("assets/tone_hybrid.wv")) -- reads assets/tone_hybrid.wvc too +assert(song.meta.source.correction == true) +``` + ## 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/licenses/NOTICE.md b/licenses/NOTICE.md index 0b8cae8..8cb35d3 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -42,6 +42,8 @@ | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | | `src/Formats/codecs/audio/Hively/` (Tables, Load, Player: the AHX / HVL loaders, waveform generator and replayer) | port of HivelyTracker hvl2wav replay.c 1.9 by Pete Gordon (Xeron/IRIS); `tests/gen/ahx_cases` / `hvl_cases` also embed songs from its Songs/ directory (fixture time, not committed) | BSD-3-Clause: [hivelytracker-LICENSE.txt](hivelytracker-LICENSE.txt) | | `src/Formats/codecs/audio/Musepack/` (Decode, Tables, init: the SV7 / SV8 bitstream, Huffman tables, requantisation, synthesis, stream headers) | port of libmpcdec (musepack_src_r475, The Musepack Development Team) | BSD-3-Clause: [libmpcdec-BSD.txt](libmpcdec-BSD.txt) | +| `src/Formats/codecs/audio/WavPack/` (Block, Tables), `src/Formats/audio/wavpack/` | Luau port of the WavPack 5.9.0 decoder by David Bryant: unpack.c, read_words.c, unpack_floats.c, decorr_utils.c, entropy_utils.c (tables, wp_log2 / wp_exp2s), open_utils.c (metadata, block checksum) | BSD-3-Clause: [wavpack-LICENSE.txt](wavpack-LICENSE.txt) | +| `src/Formats/codecs/audio/Ape/` (Decode, init), `src/Formats/audio/ape/` | Luau port of the Monkey's Audio SDK 13.28 decoder by Matthew T. Ashland: UnBitArray.cpp / Old/UnBitArrayOld.cpp (range coder), NNFilter, NewPredictor.cpp, ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare), APEDecompressCore.cpp, APEHeader.cpp, FloatTransform.cpp | BSD-3-Clause (since SDK v10): [monkeys-audio-LICENSE.txt](monkeys-audio-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/monkeys-audio-LICENSE.txt b/licenses/monkeys-audio-LICENSE.txt new file mode 100644 index 0000000..e4a0ca5 --- /dev/null +++ b/licenses/monkeys-audio-LICENSE.txt @@ -0,0 +1,11 @@ +Monkey's Audio License Agreement (3 clause BSD) + +Copyright 2000-2026 Matthew T. Ashland. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +3) Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/licenses/wavpack-LICENSE.txt b/licenses/wavpack-LICENSE.txt new file mode 100644 index 0000000..a013696 --- /dev/null +++ b/licenses/wavpack-LICENSE.txt @@ -0,0 +1,25 @@ + Copyright (c) 1998 - 2025 David Bryant + All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index dda476b..31cfbd1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -206,6 +206,18 @@ local list: { Entry } = { return require("@formats/audio/aiff") end, }, + { + name = "ape", + category = "audio", + path = "audio/ape", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, + load = function() + return require("@formats/audio/ape") + end, + }, { name = "au", category = "audio", @@ -314,6 +326,18 @@ local list: { Entry } = { return require("@formats/audio/qoa") end, }, + { + name = "tta", + category = "audio", + path = "audio/tta", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, + load = function() + return require("@formats/audio/tta") + end, + }, { name = "vag", category = "audio", @@ -362,6 +386,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "wavpack", + category = "audio", + path = "audio/wavpack", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, + load = function() + return require("@formats/audio/wavpack") + end, + }, { name = "avi", category = "video", diff --git a/src/Formats/audio/ape/init.luau b/src/Formats/audio/ape/init.luau new file mode 100644 index 0000000..72d25dc --- /dev/null +++ b/src/Formats/audio/ape/init.luau @@ -0,0 +1,134 @@ +--!strict +-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), +-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end +-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). +-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 +-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. +-- +-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 +-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them +-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.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 ApeTag = require("@formats/codecs/audio/ApeTag") +local ApeCodec = require("@formats/codecs/audio/Ape") + +-- ------------------------------------------------------------------------------------------------ contract +local Ape = { + name = "ape", + category = "audio", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ape.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "MAC " or head == "MACF" then -- MACF: float samples + return 1 + end + if string.sub(head, 1, 3) == "ID3" then + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + local id = r:peek(4, 10 + sz + (if footer then 10 else 0)) + return if id == "MAC " or id == "MACF" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ape.open(r, opts) + 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, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = ApeCodec.info(buf, base, stop) + if not info then + return nil, err + end + if info.channels * info.blocksPerFrame > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks") + end + local codec, cerr = ApeCodec.decoder(info) + if not codec then + return nil, cerr + end + local frames = info.totalBlocks + local bpf = info.blocksPerFrame + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + level = LEVELS[info.level] or tostring(info.level), + version = info.version, + md5 = info.md5, + source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items }, + } + local count = info.totalFrames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * bpf + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1), + ints = not info.float, + }) +end + +return Ape diff --git a/src/Formats/audio/tta/init.luau b/src/Formats/audio/tta/init.luau new file mode 100644 index 0000000..63d197f --- /dev/null +++ b/src/Formats/audio/tta/init.luau @@ -0,0 +1,123 @@ +--!strict +-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the +-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). +-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. +-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. +-- +-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt +-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.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 ApeTag = require("@formats/codecs/audio/ApeTag") +local TtaCodec = require("@formats/codecs/audio/Tta") + +-- ------------------------------------------------------------------------------------------------ contract +local Tta = { + name = "tta", + category = "audio", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- the size of an ID3v2 tag at the reader's start (0 when none) +local function id3Size(r: Bytes.Reader): number + if r:peek(3) ~= "ID3" then + return 0 + end + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return 10 + sz + (if footer then 10 else 0) +end + +function Tta.sniff(r: Bytes.Reader): number + return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Tta.open(r, opts) + 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, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local at = base + id3Size(r) + local tags, tagInfo = ApeTag.find(buf, at, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = TtaCodec.info(buf, at, stop) + if not info then + return nil, err + end + if info.channels * info.frameLength > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames") + end + local codec = TtaCodec.decoder(info, stop) + local frames = info.samples + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = false, + source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items }, + } + local fl, count = info.frameLength, info.frames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * fl + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = 1 / 2 ^ (info.bitsPerSample - 1), + ints = true, + }) +end + +return Tta diff --git a/src/Formats/audio/wavpack/init.luau b/src/Formats/audio/wavpack/init.luau new file mode 100644 index 0000000..022594b --- /dev/null +++ b/src/Formats/audio/wavpack/init.luau @@ -0,0 +1,219 @@ +--!strict +-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction +-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 +-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the +-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("c") +-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking +-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file +-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. +-- +-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... +-- local f32, n = dec:read(4096) +-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them +-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.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 ApeTag = require("@formats/codecs/audio/ApeTag") +local WavPackCodec = require("@formats/codecs/audio/WavPack") + +-- ------------------------------------------------------------------------------------------------ contract +local WavPack = { + name = "wavpack", + category = "audio", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) + resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths) + name: string?, -- the file name (the api passes it) + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function WavPack.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "wvpk" then + return 0 + end + local v = r:peekU8(9) + return if v == 4 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = WavPack.open(r, opts) + 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, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } + +-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence +local function index(buf: buffer, base: number, limit: number): (Index?, string?) + local at = base + local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } + local cur: { number }? = nil + local initial = -1 + local resyncs = 0 + while at + 32 <= limit do + local h = WavPackCodec.header(buf, at, limit) + if not h then + -- garbage (or a tag) between blocks: search the next header + if resyncs > 64 then + break + end + local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576)) + local k = string.find(s, "wvpk", 1, true) + if not k then + break + end + at = at + k + resyncs += 1 + continue + end + if initial < 0 then + initial = h.index + idx.total = h.total + end + if h.samples > 0 then + if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then + cur = { at } + table.insert(idx.offsets, cur) + table.insert(idx.starts, h.index - initial) + table.insert(idx.samples, h.samples) + if idx.first < 0 then + idx.first = at + end + else + table.insert(cur, at) + end + if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then + cur = nil + end + else + idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit) + end + at += h.size + end + if idx.first < 0 then + return nil, "no audio blocks" + end + return idx, nil +end + +local function correctionFile(opts: OpenOptions?): buffer? + if not opts then + return nil + end + local c = opts.correction + if type(c) == "string" then + return buffer.fromstring(c) + elseif type(c) == "buffer" then + return c + end + if type(opts.resolve) == "function" and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") + if base then + local ok, b = pcall(opts.resolve, base .. "c") + if ok and type(b) == "buffer" then + return b + end + end + end + return nil +end + +-- open(r, opts?) -> Decoder | nil, Err +function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local idx, ierr = index(buf, base, stop) + if not idx then + return nil, Err.from(ierr, base) + end + local info, err = WavPackCodec.info(buf, idx.first, stop) + if not info then + return nil, err + end + if info.channels > 256 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels") + end + local count = #idx.offsets + local last = idx.starts[count] + idx.samples[count] + local frames = if idx.total >= 0 then math.min(idx.total, last) else last + -- the correction file: its frames by start sample + local cbuf = if info.hybrid then correctionFile(opts) else nil + local cfor: { [number]: { number } } = {} + if cbuf then + local cidx = index(cbuf, 0, buffer.len(cbuf)) + if cidx then + for i, offs in cidx.offsets do + cfor[cidx.starts[i]] = offs + end + else + cbuf = nil + end + end + local codec = WavPackCodec.decoder(info.channels) + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + hybrid = info.hybrid, + lossless = not info.hybrid or cbuf ~= nil, + channelMask = info.channelMask, + md5 = idx.md5, + source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items }, + } + local starts, offsets = idx.starts, idx.offsets + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then last else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local co = if cbuf then cfor[starts[i]] else nil + return codec:frame(buf, offsets[i], if co then cbuf else nil, co) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1), + ints = not info.float, + }) +end + +return WavPack diff --git a/src/Formats/codecs/audio/Ape/Decode.luau b/src/Formats/codecs/audio/Ape/Decode.luau new file mode 100644 index 0000000..5b9ebee --- /dev/null +++ b/src/Formats/codecs/audio/Ape/Decode.luau @@ -0,0 +1,778 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T. +-- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model, +-- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the +-- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 +-- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp +-- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +local Crc32 = require("@formats/core/Crc32") + +local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap +local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32 +local readi16, readi32 = buffer.readi16, buffer.readi32 +local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor +local sign = math.sign + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local PAD = 64 + +-- the range coder's symbol models (UnBitArrayBase.h) +local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 } + +-- symbol(total) lookup buffers (RangeOverflowTable), built on first use +local OVT: { [number]: buffer } = {} +local function overflowTable(rt: { number }): buffer + local t = OVT[rt[2]] + if t then + return t + end + t = buffer.create(65536) + local o = 0 + for z = 0, 65535 do + if z >= rt[o + 2] then + o += 1 + end + writeu8(t, z, o) + end + OVT[rt[2]] = t + return t +end + +local function wrap32(v: number): number + if v >= TWO31 or v < -TWO31 then + return (v + TWO31) % TWO32 - TWO31 + end + return v +end + +-- C integer division by 2 (toward zero) +local function half(v: number): number + return if v >= 0 then v // 2 else -((-v) // 2) +end + +export type Filter = { order: number, shift: number, M: buffer, I: buffer, D: buffer } +export type State = { + version: number, + bits: number, + channels: number, + filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) + V: { { number } }, -- per channel: the frame's values through the stages + S: buffer, -- the frame bytes, word-swapped (+ PAD zeros) + crcbuf: buffer, + scratch: buffer, + lastX: number, + rc: Rc, +} + +local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order + [1000] = {}, + [2000] = { 16, 11 }, + [3000] = { 64, 11 }, + [4000] = { 256, 13, 32, 10 }, + [5000] = { 1280, 15, 256, 13, 16, 11 }, +} + +-- state(version, level, bits, channels) -> State | nil, message +function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) + local spec = FILTERS[level] + if not spec then + return nil, "unsupported: compression level " .. level + end + local filters: { Filter } = {} + for k = 1, #spec, 2 do + local order = spec[k] + local es = if bits >= 32 then 4 else 2 + table.insert(filters, { + order = order, + shift = spec[k + 1], + M = buffer.create(order * es), + I = buffer.create((512 + order + 1) * es), + D = buffer.create((512 + order + 1) * es), + }) + end + local V = {} + for c = 1, channels do + V[c] = {} + end + return { + version = version, + bits = bits, + channels = channels, + filters = filters, + V = V, + S = buffer.create(1024), + crcbuf = buffer.create(1024), + scratch = buffer.create(4), + lastX = 0, + rc = { q = 0, low = 0, range = 0, prev = 0 }, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ entropy +-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) +type Rc = { q: number, low: number, range: number, prev: number } +local function rcBits(rc: Rc, S: buffer, nb: number): number + local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 2 ^ nb + local r = 0 + if range > 0 then + r = low // range + low %= range + end + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + return r +end + +-- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of +-- `order` (decode order), from byte q of st.S (the range coder starts there) +local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) + local S = st.S + local V = st.V + local version = st.version + -- FlushBitArray: a dummy byte, then the first byte + local prev = readu8(S, q + 1) + q += 2 + local low = rshift(prev, 1) + local range = 128 + local nch = #order + local ksum = table.create(nch, 16384) + local kk = table.create(nch, 10) + local ovt = overflowTable(if old then RT1 else RT2) + local RT = if old then RT1 else RT2 + for b = 1, n do + for ci = 1, nch do + if q > lim then + return nil, "overrun" + end + local ks = ksum[ci] + local value + -- the overflow symbol (RangeDecodeFast(16) + the model) + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + local total = low // range + if total >= 65536 then + return nil, "bad range code" + end + local ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + if not old then + local pivot = math.max(ks // 32, 1) + while ov == 63 do + -- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal + local r = 0 + for _ = 1, 2 do + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + if range == 0 then + return nil, "bad range code" + end + r = r * 65536 + low // range + low %= range + end + ov = r + if ov == 1 then + pivot = 32768 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + total = low // range + if total >= 65536 then + return nil, "bad range code" + end + ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + else + break + end + end + local base + if pivot >= 65536 then + local pbits = 0 + while pivot // 2 ^ pbits > 0 do + pbits += 1 + end + local split = 2 ^ (if pbits >= 16 then pbits - 16 else 0) + local pa = pivot // split + 1 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pa + local ba = low // range + low %= range + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // split + local bb = low // range + low %= range + base = ba * split + bb + else + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pivot + base = low // range + low %= range + end + value = base + ov * pivot + else + -- 3.95 - 3.98: k bits (escape: k in 5 bits) + local rc = st.rc + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + local k + if ov == 63 then + k = rcBits(rc, S, 5) + ov = 0 + else + k = math.max(kk[ci] - 1, 0) + end + if k <= 16 or version < 3910 then + value = rcBits(rc, S, k) + else + local x1 = rcBits(rc, S, 16) + value = x1 + rcBits(rc, S, k - 16) * 65536 + end + value += ov * 2 ^ k + q = rc.q + low = rc.low + range = rc.range + prev = rc.prev + end + ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32 + ksum[ci] = ks + if old then + local k = kk[ci] + if ks < KMIN[k + 1] then + kk[ci] = k - 1 + elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then + kk[ci] = k + 1 + end + end + V[order[ci]][b] = if value % 2 == 1 then (value - 1) // 2 + 1 else -(value // 2) + end + end + return q, nil +end + +-- ------------------------------------------------------------------------------------------------ NN filters +-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) +local function negBit(v: number, p2: number, m: number): boolean + return band((v // p2) % TWO32, m) ~= 0 +end + +-- the int16 dot product of the weights and the inputs from byte b (span bytes) +local function dot16(M: buffer, I: buffer, b: number, span: number): number + local dot = 0 + for k = 0, span - 16, 16 do + local bb = b + k + dot += readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2) + + readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6) + + readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10) + + readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14) + end + return dot +end + +-- the same, adapting each weight after its use: M += D * dm (int16, wrapping) +local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number + local dot = 0 + for k = 0, span - 8, 8 do + local bb = b + k + local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6) + dot += readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3 + writei16(M, k, m0 + readi16(D, bb) * dm) + writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm) + writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm) + writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm) + end + return dot +end + +-- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of +-- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) + local order, M, I, D = f.order, f.M, f.I, f.D + local es = if wide then 4 else 2 + local shift = 2 ^ f.shift + local round = shift // 2 + buffer.fill(M, 0, 0, order * es) + buffer.fill(I, 0, 0, (order + 1) * es) + buffer.fill(D, 0, 0, (order + 1) * es) + local p = order -- the current element (0-based); its history is p - order .. p - 1 + local total = 512 + order + local avg = 0 + local span = order * 2 + for t = 1, n do + local x = v[t] + local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0 + local dot = 0 + if wide then + local b = (p - order) * 4 + for k = 0, order * 4 - 4, 4 do + local m = readi32(M, k) + local pr = readi32(I, b + k) * m + if pr >= TWO31 or pr < -TWO31 then + pr = (pr + TWO31) % TWO32 - TWO31 + end + dot += pr + if dm ~= 0 then + writei32(M, k, m + readi32(D, b + k) * dm) + end + end + else + local b = (p - order) * 2 + dot = if dm == 0 then dot16(M, I, b, span) else dotAdapt16(M, I, D, b, span, dm) + dot = wrap32(dot) + end + local o = x + (dot + round) // shift + if not wide then + o = wrap32(o) + end + local d = 0 + local a = if o < 0 then -o else o + if newDelta then + if a > avg * 3 then + d = if (if wide then negBit(o, 33554432, 64) else o < 0) then 32 else -32 + elseif a > (avg * 4) // 3 then + d = if (if wide then negBit(o, 67108864, 32) else o < 0) then 16 else -16 + elseif a > 0 then + d = if (if wide then negBit(o, 134217728, 16) else o < 0) then 8 else -8 + end + local dd = a - avg + avg += if dd >= 0 then dd // 16 else -((-dd) // 16) + else + d = if o == 0 then 0 elseif o < 0 then 4 else -4 + end + local sat = if o > 32767 then 32767 elseif o < -32768 then -32768 else o + if wide then + local q = p * 4 + writei32(D, q, d) + if newDelta then + writei32(D, q - 4, readi32(D, q - 4) // 2) + writei32(D, q - 8, readi32(D, q - 8) // 2) + else + writei32(D, q - 16, readi32(D, q - 16) // 2) + end + writei32(D, q - 32, readi32(D, q - 32) // 2) + writei32(I, q, sat) + else + local q = p * 2 + writei16(D, q, d) + if newDelta then + writei16(D, q - 2, readi16(D, q - 2) // 2) + writei16(D, q - 4, readi16(D, q - 4) // 2) + else + writei16(D, q - 8, readi16(D, q - 8) // 2) + end + writei16(D, q - 16, readi16(D, q - 16) // 2) + writei16(I, q, sat) + end + v[t] = o + p += 1 + if p == total then + buffer.copy(I, 0, I, (p - order) * es, order * es) + buffer.copy(D, 0, D, (p - order) * es, order * es) + p = order + end + end +end + +-- ------------------------------------------------------------------------------------------------ predictor +-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 +local function adaptWide(v: number): number + if v == 0 then + return 0 + end + return if (v // 1073741824) % 4 >= 2 then 1 else -1 +end + +-- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the +-- block, or 0), single-channel form; stereo uses predictStereo +local function predictOne(st: State, v: { number }, n: number) + local wide = st.bits >= 32 + local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 + local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 + local stage = 0 + for t = 1, n do + local nA = v[t] + local A0 = lastA + A3 = A2 + A2 = A1 + A1 = A0 - prevA0 + prevA0 = A0 + local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 + local cur + if wide then + cur = nA + predA // 1024 + else + cur = wrap32(nA + wrap32(predA) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + MA0 += adaptWide(A0) * s + MA1 += adaptWide(A1) * s + MA2 += adaptWide(A2) * s + MA3 += adaptWide(A3) * s + else + MA0 += sign(A0) * s + MA1 += sign(A1) * s + MA2 += sign(A2) * s + MA3 += sign(A3) * s + end + end + stage = wrap32(cur + (stage * 31) // 32) + lastA = cur + v[t] = stage + end +end + +-- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] +local function predictStereo(st: State, X: { number }, Y: { number }, n: number) + local wide = st.bits >= 32 + -- predictor 1 (Y) + local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 + local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0 + local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98 + local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0 + local yStage = 0 + -- predictor 0 (X) + local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0 + local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0 + local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98 + local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0 + local xStage = 0 + local lastX = 0 + for t = 1, n do + -- Y + local nA = Y[t] + local A0 = yLast + yA3 = yA2 + yA2 = yA1 + yA1 = A0 - yPrev + yPrev = A0 + local B0 = lastX - (yBin * 31) // 32 + yBin = lastX + yB4 = yB3 + yB3 = yB2 + yB2 = yB1 + yB1 = B0 - yBprev + yBprev = B0 + local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 + local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 + local cur + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + yMA0 += adaptWide(A0) * s + yMA1 += adaptWide(yA1) * s + yMA2 += adaptWide(yA2) * s + yMA3 += adaptWide(yA3) * s + yMB0 += adaptWide(B0) * s + yMB1 += adaptWide(yB1) * s + yMB2 += adaptWide(yB2) * s + yMB3 += adaptWide(yB3) * s + yMB4 += adaptWide(yB4) * s + else + yMA0 += sign(A0) * s + yMA1 += sign(yA1) * s + yMA2 += sign(yA2) * s + yMA3 += sign(yA3) * s + yMB0 += sign(B0) * s + yMB1 += sign(yB1) * s + yMB2 += sign(yB2) * s + yMB3 += sign(yB3) * s + yMB4 += sign(yB4) * s + end + end + yStage = wrap32(cur + (yStage * 31) // 32) + yLast = cur + local yv = yStage + -- X + nA = X[t] + A0 = xLast + xA3 = xA2 + xA2 = xA1 + xA1 = A0 - xPrev + xPrev = A0 + B0 = yv - (xBin * 31) // 32 + xBin = yv + xB4 = xB3 + xB3 = xB2 + xB2 = xB1 + xB1 = B0 - xBprev + xBprev = B0 + predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 + predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + s = sign(nA) + if s ~= 0 then + if wide then + s = -s + xMA0 += adaptWide(A0) * s + xMA1 += adaptWide(xA1) * s + xMA2 += adaptWide(xA2) * s + xMA3 += adaptWide(xA3) * s + xMB0 += adaptWide(B0) * s + xMB1 += adaptWide(xB1) * s + xMB2 += adaptWide(xB2) * s + xMB3 += adaptWide(xB3) * s + xMB4 += adaptWide(xB4) * s + else + xMA0 += sign(A0) * s + xMA1 += sign(xA1) * s + xMA2 += sign(xA2) * s + xMA3 += sign(xA3) * s + xMB0 += sign(B0) * s + xMB1 += sign(xB1) * s + xMB2 += sign(xB2) * s + xMB3 += sign(xB3) * s + xMB4 += sign(xB4) * s + end + end + xStage = wrap32(cur + (xStage * 31) // 32) + xLast = cur + lastX = xStage + X[t], Y[t] = xStage, yv + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first +-- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: +-- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) +function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) + local C, bits = st.channels, st.bits + local len = math.max(0, stop - at) + local words = (len + 3) // 4 + local S = st.S + if buffer.len(S) < words * 4 + PAD then + S = buffer.create(words * 4 + PAD + 4096) + st.S = S + end + buffer.fill(S, 0, 0, words * 4 + PAD) + -- the bit array: 32-bit little-endian words read MSB first + for w = 0, words - 1 do + local o = at + w * 4 + if o + 4 <= stop then + writeu32(S, w * 4, byteswap(readu32(buf, o))) + else + for k = 0, 3 do + if o + k < stop then + writeu8(S, w * 4 + 3 - k, readu8(buf, o + k)) + end + end + end + end + local function u32be(q: number): number + return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) + end + local q = rem + if q + 16 > words * 4 + PAD then + return nil, "truncated frame" + end + local stored = u32be(q) + q += 4 + local special = 0 + if st.version > 3820 then + if stored >= TWO31 then + special = u32be(q) + q += 4 + end + stored %= TWO31 + end + -- the values + local V = st.V + local order: { number } + local mode -- "silence", "pseudo", "stereo", "mono", "multi" + if C == 1 then + if band(special, 1) ~= 0 then + mode = "silence" + order = {} + else + mode = "mono" + order = { 1 } + end + elseif C == 2 then + if band(special, 3) == 3 then + mode = "silence" + order = {} + elseif band(special, 4) ~= 0 then + mode = "pseudo" + order = { 1 } + else + mode, order = "stereo", { 2, 1 } + end + else + mode = "multi" + order = {} + for c = 1, C do + order[c] = c + end + end + local lim = words * 4 + PAD - 40 + if #order > 0 then + local qe = values(st, q, lim, n, order, st.version < 3990) + if not qe or qe > words * 4 + 8 then + return nil, if cut then "truncated frame" else "bad frame: the values run over its data" + end + -- the NN filters (last level first), then the predictors + local newDelta = st.version >= 3980 + local filters = st.filters + for _, c in order do + for f = #filters, 1, -1 do + nnFilter(filters[f], V[c], n, newDelta, bits >= 32) + end + end + if mode == "stereo" then + predictStereo(st, V[1], V[2], n) + else + for _, c in order do + predictOne(st, V[c], n) + end + end + end + -- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them + local bps = bits // 8 + local cb = st.crcbuf + if buffer.len(cb) < n * C * bps then + cb = buffer.create(n * C * bps + 1024) + st.crcbuf = cb + end + local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair + if C == 2 and mode == "stereo" then + paired[0] = true + elseif C == 4 and (bits == 16 or bits == 24) then + paired[0], paired[2] = true, true + elseif C >= 6 and (bits == 16 or bits == 24) then + paired[0], paired[4] = true, true + if C >= 8 then + paired[6] = true + end + end + local o = 0 + local mono = mode == "mono" or mode == "pseudo" + local X = V[1] + for t = 1, n do + local base = (t - 1) * C + local c = 0 + while c < C do + local a: number, b2: number = 0, 0 + local pair = paired[c] + if mode == "silence" then + a = 0 + b2 = 0 + elseif mono then + a = X[t] + b2 = a + elseif pair then + local x, y = V[c + 1][t], V[c + 2][t] + a = x - half(y) + b2 = a + y + else + a = V[c + 1][t] + end + local width = if pair or (C == 2) then 2 else 1 + for k = 0, width - 1 do + local s: number = if k == 0 then a else b2 + if bits == 16 then + if s < -32768 or s > 32767 then + return nil, "sample out of range" + end + writei16(cb, o, s) + o += 2 + elseif bits == 8 then + s = (s + 128) % 256 - 128 + writeu8(cb, o, s + 128) + o += 1 + elseif bits == 24 then + s = (s + 8388608) % 16777216 - 8388608 + local u = s % 16777216 + writeu16(cb, o, u % 65536) + writeu8(cb, o + 2, u // 65536) + o += 3 + else + s = wrap32(s) + writei32(cb, o, s) + o += 4 + end + P[base + c + k + 1] = s + end + c += width + end + end + local crc = Crc32.of(cb, 0, o) + if crc // 2 ~= stored then + return nil, "checksum: frame CRC mismatch" + end + if float then + local sc = st.scratch + for k = 1, n * C do + local u = P[k] % TWO32 + local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF)) + if out >= TWO31 then + out = bor(bnot(out), 0x80000000) + end + writeu32(sc, 0, out) + P[k] = readf32(sc, 0) + end + end + return n, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Ape/init.luau b/src/Formats/codecs/audio/Ape/init.luau new file mode 100644 index 0000000..91faa36 --- /dev/null +++ b/src/Formats/codecs/audio/Ape/init.luau @@ -0,0 +1,229 @@ +--!strict +-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 +-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / +-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame +-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the +-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, +-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, +-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit +-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned +-- as numbers either way). +-- +-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table +-- local dec = Ape.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Decode = require("@formats/codecs/audio/Ape/Decode") + +local Ape = {} + +export type Info = { + version: number, -- file version * 1000 (3990) + programVersion: number, -- 13280 (0 when not stored) + level: number, -- 1000 (fast) .. 5000 (insane) + flags: number, + channels: number, + sampleRate: number, + bitsPerSample: number, + float: boolean, + blocksPerFrame: number, + finalFrameBlocks: number, + totalFrames: number, + totalBlocks: number, + frameStart: { number }, -- byte offset of each frame + firstFrame: number, -- byte offset of frame 1 (the word alignment origin) + dataEnd: number, -- the end of the frame data + limit: number, -- the end of the file data (frames past it are truncated) + md5: string?, +} + +local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 + +-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil +function Ape.find(buf: buffer, base: number, limit: number): number? + local at = base + if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then + local size = 0 + for i = 6, 9 do + size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127) + end + local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0 + at += size + (if footer then 20 else 10) + if not footer then + while at < limit and buffer.readu8(buf, at) == 0 do + at += 1 + end + end + end + if at + 4 > limit then + return nil + end + local id = buffer.readstring(buf, at, 4) + if id == "MAC " or id == "MACF" then + return at + end + local s = buffer.readstring(buf, at, math.min(limit - at, 1048576)) + local k = string.find(s, "MAC ", 1, true) + return if k then at + k - 1 else nil +end + +-- info(buf, base, limit) -> Info | nil, Err +function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) + local at = Ape.find(buf, base, limit) + if not at then + return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header") + end + local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2) + local r = Bytes.reader(buf, at, limit - at) + r:skip(4) + local version = r:u16le() + if r.err then + return nil, r.err + end + if version < 3950 then + return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)") + end + local info: any = { version = version, programVersion = 0 } + local seekCount, seekAt + if version >= 3980 then + info.programVersion = r:u16le() + local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le() + local md5 = r:string(16) + r:seek(descBytes) + info.level = r:u16le() + info.flags = r:u16le() + info.blocksPerFrame = r:u32le() + info.finalFrameBlocks = r:u32le() + info.totalFrames = r:u32le() + info.bitsPerSample = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + if r.err then + return nil, r.err + end + seekAt = at + descBytes + headBytes + seekCount = seekBytes // 4 + info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296 + local _ = termBytes + local hex = table.create(16, "") + local any = false + for k = 1, 16 do + local b = string.byte(md5, k) + any = any or b ~= 0 + hex[k] = string.format("%02x", b) + end + info.md5 = if any then table.concat(hex) else nil + else + info.level = r:u16le() + info.flags = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + local headerBytes = r:u32le() + r:u32le() -- terminating bytes + info.totalFrames = r:u32le() + info.finalFrameBlocks = r:u32le() + if bit32.band(info.flags, FLAG_PEAK) ~= 0 then + r:skip(4) + end + seekCount = info.totalFrames + if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then + seekCount = r:u32le() + end + if bit32.band(info.flags, FLAG_WAVHDR) == 0 then + r:skip(headerBytes) + end + if r.err then + return nil, r.err + end + info.blocksPerFrame = 73728 * 4 + info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16 + seekAt = r:tell() + info.dataEnd = limit + end + local C, bits = info.channels, info.bitsPerSample + if C < 1 or C > 32 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. C) + end + if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples") + end + if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then + return nil, Err.new(Err.CORRUPT, "bad header") + end + if info.totalFrames < 1 then + return nil, Err.new(Err.CORRUPT, "no frames") + end + info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32 + info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks + if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then + return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete") + end + local starts = table.create(info.totalFrames, 0) + local add, prev = 0, 0 + for i = 1, info.totalFrames do + local v = buffer.readu32(buf, seekAt + (i - 1) * 4) + if v < prev then + add += 4294967296 + end + prev = v + starts[i] = base + junk + add + v + end + for i = 1, info.totalFrames do + if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then + return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i) + end + end + info.frameStart = starts + info.firstFrame = starts[1] + info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit) + info.limit = limit + return info :: Info, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + info: Info, + pcm: { number }, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.totalFrames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local start = info.frameStart[i] + local rem = (start - info.firstFrame) % 4 + local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4 + local stop = math.min(want, info.limit, buffer.len(buf)) + if start + 8 > stop then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start) + end + local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks + local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4) + if not n2 then + return nil, Err.from(msg, start) + end + return n2, nil +end + +-- decoder(info) -> Decoder | nil, Err +function Ape.decoder(info: Info): (Decoder?, Err.Err?) + local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) + if not st then + return nil, Err.from(msg) + end + return { + info = info, + pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0), + frame = frame, + state = st, + }, nil +end + +return Ape diff --git a/src/Formats/codecs/audio/Stream.luau b/src/Formats/codecs/audio/Stream.luau index 33f08d0..63a0079 100644 --- a/src/Formats/codecs/audio/Stream.luau +++ b/src/Formats/codecs/audio/Stream.luau @@ -14,7 +14,9 @@ -- 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) --- }) +-- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) +-- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the +-- }) -- same frames as read() as i32 (bit-exact checks) -- -- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is -- returned by packets() as the open error. Never throws. @@ -32,6 +34,8 @@ export type Spec = { stop: number?, -- default start(count + 1) preroll: number?, -- default 0 cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) + scale: number?, -- read() writes pcm() values times this (default 1) + ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32 } -- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) @@ -75,12 +79,13 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) end end - function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local scale = spec.scale or 1 + local function pull(n: number, out: buffer?, asInt: boolean): (buffer, number) local want = math.max(0, math.floor(n)) local need = want * ch * 4 local ob = if out and buffer.len(out) >= need then out else buffer.create(need) local got = 0 - local writef32 = buffer.writef32 + local writef32, writei32 = buffer.writef32, buffer.writei32 while got < want do if pendPos >= pendN then if failed or not fill() then @@ -92,12 +97,34 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local q = got * ch * 4 local s = pendPos * ch if type(src) == "buffer" then - buffer.copy(ob, q, src, s * 4, take * ch * 4) - else + if scale == 1 and not asInt then + buffer.copy(ob, q, src, s * 4, take * ch * 4) + else + for k = 0, take * ch - 1 do + local v = buffer.readf32(src, (s + k) * 4) + if asInt then + writei32(ob, q, v) + else + writef32(ob, q, v * scale) + end + q += 4 + end + end + elseif asInt then + for k = 1, take * ch do + writei32(ob, q, src[s + k]) + q += 4 + end + elseif scale == 1 then for k = 1, take * ch do writef32(ob, q, src[s + k]) q += 4 end + else + for k = 1, take * ch do + writef32(ob, q, src[s + k] * scale) + q += 4 + end end pendPos += take got += take @@ -106,6 +133,15 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) return ob, got end + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, false) + end + if spec.ints then + function dec.readInt(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, true) + end + end + function dec.seek(_self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame diff --git a/src/Formats/codecs/audio/Tta/Decode.luau b/src/Formats/codecs/audio/Tta/Decode.luau new file mode 100644 index 0000000..1ce9094 --- /dev/null +++ b/src/Formats/codecs/audio/Tta/Decode.luau @@ -0,0 +1,259 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio +-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the +-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked +-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +local Crc32 = require("@formats/core/Crc32") + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, rshift = bit32.band, bit32.rshift +local min, max, floor = math.min, math.max, math.floor + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local INV31 = 1 / TWO31 +local PAD = 16 +local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k +for i = 0, 39 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the trailing 1 bits of the byte b +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v //= 2 + end + ONES[b + 1] = n +end + +-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) +local function longUnary(S: buffer, pos: number, lim: number): (number?, number) + local unary = 0 + while pos <= lim do + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + return unary + ones, pos + ones + 1 + end + unary += 8 + pos += 8 + end + return nil, pos +end + +export type State = { + channels: number, + bytes: number, -- 1 .. 3 + S: buffer, -- the frame's bits (+ PAD zeros) + -- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value + R: { number }, + Q: { number }, + X: { number }, + L: { number }, + E: { number }, + last: { number }, + cur: { number }, +} + +function Decode.state(channels: number, bytes: number): State + return { + channels = channels, + bytes = bytes, + S = buffer.create(4096), + R = table.create(channels * 4, 0), + Q = table.create(channels * 8, 0), + X = table.create(channels * 8, 0), + L = table.create(channels * 8, 0), + E = table.create(channels, 0), + last = table.create(channels, 0), + cur = table.create(channels, 0), + } +end + +-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per +-- channel, into P (interleaved integers) +function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) + if len < 4 then + return nil, "truncated frame" + end + local dlen = len - 4 + if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then + return nil, "checksum: frame CRC mismatch" + end + local S = st.S + if buffer.len(S) < dlen + PAD then + S = buffer.create(dlen + PAD + 4096) + st.S = S + end + buffer.copy(S, 0, buf, o, dlen) + buffer.fill(S, dlen, 0, PAD) + local C, bytes = st.channels, st.bytes + local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size + local fdiv = 2 ^ shift + local round = fdiv // 2 + local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk + local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur + for c = 0, C - 1 do + R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384 + E[c + 1], last[c + 1] = 0, 0 + for i = 1, 8 do + Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 + end + end + local pos = 0 -- bit position + local lim = dlen * 8 + local c = 0 -- the channel of the sample at idx + for idx = 1, n * C do + do + if pos > lim then + return nil, "truncated frame" + end + -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) + local unary + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + unary = ones + pos += ones + 1 + else + local u, p2 = longUnary(S, pos, lim) + if not u then + return nil, "truncated frame" + end + unary, pos = u, p2 + end + local rb = c * 4 + local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4] + local deep = unary > 0 + local k + if deep then + k = k1 + unary -= 1 + else + k = k0 + end + local value = unary + if k > 0 then + local bits + if k <= 24 then + bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1) + else + local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF) + local p2 = pos + 16 + bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536 + end + pos += k + value = unary * P2[k + 1] + bits + end + if deep then + s1 += value - s1 // 16 + if k1 > 0 and s1 < P2[k1 + 5] then + k1 -= 1 + elseif s1 > P2[k1 + 6] then + k1 += 1 + end + value += P2[k0 + 1] + end + s0 += value - s0 // 16 + if k0 > 0 and s0 < P2[k0 + 5] then + k0 -= 1 + elseif s0 > P2[k0 + 6] then + k0 += 1 + end + R[rb + 1] = math.min(k0, 31) + R[rb + 2] = math.min(k1, 31) + R[rb + 3] = s0 + R[rb + 4] = s1 + local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free) + value = (value + odd) // 2 * (2 * odd - 1) + -- the adaptive filter: the weights step toward the sign of the last residual + local fb = c * 8 + local err = E[c + 1] + -- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments) + local dq = max(-1, min(1, err)) + local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4] + local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8] + local q1 = Q[fb + 1] + x1 * dq + local q2 = Q[fb + 2] + x2 * dq + local q3 = Q[fb + 3] + x3 * dq + local q4 = Q[fb + 4] + x4 * dq + local q5 = Q[fb + 5] + x5 * dq + local q6 = Q[fb + 6] + x6 * dq + local q7 = Q[fb + 7] + x7 * dq + local q8 = Q[fb + 8] + x8 * dq + Q[fb + 1] = q1 + Q[fb + 2] = q2 + Q[fb + 3] = q3 + Q[fb + 4] = q4 + Q[fb + 5] = q5 + Q[fb + 6] = q6 + Q[fb + 7] = q7 + Q[fb + 8] = q8 + local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5] + local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8] + local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8 + if sum >= TWO31 or sum < -TWO31 then + sum = (sum + TWO31) % TWO32 - TWO31 + end + -- the steps follow the delay line's signs (x 1, 2, 2, 4) + X[fb + 1] = x2 + X[fb + 2] = x3 + X[fb + 3] = x4 + X[fb + 4] = x5 + X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free) + X[fb + 6] = 2 + 4 * floor(l6 * INV31) + X[fb + 7] = 2 + 4 * floor(l7 * INV31) + X[fb + 8] = 4 + 8 * floor(l8 * INV31) + E[c + 1] = value + value += sum // fdiv + -- the delay line: the last value and its first and second differences + local n7 = value - l8 + local n6 = n7 - l7 + L[fb + 1] = l2 + L[fb + 2] = l3 + L[fb + 3] = l4 + L[fb + 4] = l5 + L[fb + 5] = n6 - l6 + L[fb + 6] = n6 + L[fb + 7] = n7 + L[fb + 8] = value + -- the fixed predictor + value += (last[c + 1] * (pk - 1)) // pk + last[c + 1] = value + cur[c + 1] = value + end + c += 1 + if c == C then + -- inter-channel decorrelation: the last channel carries half the previous one, the others are differences + c = 0 + local o = idx - C + if C == 1 then + P[idx] = cur[1] + elseif C == 2 then + local a = cur[1] + local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2)) + P[o + 1], P[o + 2] = b - a, b + else + local a = cur[C - 1] + cur[C] += if a >= 0 then a // 2 else -((-a) // 2) + for r = C - 1, 1, -1 do + cur[r] = cur[r + 1] - cur[r] + end + for k = 1, C do + P[o + k] = cur[k] + end + end + end + end + if pos > lim then + return nil, "truncated frame" + end + return n, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Tta/init.luau b/src/Formats/codecs/audio/Tta/init.luau new file mode 100644 index 0000000..db0dc48 --- /dev/null +++ b/src/Formats/codecs/audio/Tta/init.luau @@ -0,0 +1,126 @@ +--!strict +-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description +-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); +-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain +-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 +-- (password-protected: UNSUPPORTED), TTA2. +-- +-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table +-- local dec = Tta.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Decode = require("@formats/codecs/audio/Tta/Decode") + +local Tta = {} + +export type Info = { + format: number, + channels: number, + bitsPerSample: number, + sampleRate: number, + samples: number, -- per channel + frameLength: number, -- samples per frame (256 * rate / 245) + frames: number, + offsets: { number }, -- each frame's byte offset + sizes: { number }, +} + +-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` +function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) + if at + 22 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + if buffer.readstring(buf, at, 4) ~= "TTA1" then + return nil, Err.new(Err.CORRUPT, "no TTA1 header") + end + if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at) + end + local format = buffer.readu16(buf, at + 4) + local info: Info = { + format = format, + channels = buffer.readu16(buf, at + 6), + bitsPerSample = buffer.readu16(buf, at + 8), + sampleRate = buffer.readu32(buf, at + 10), + samples = buffer.readu32(buf, at + 14), + frameLength = 0, + frames = 0, + offsets = {}, + sizes = {}, + } + if format == 2 then + return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA") + elseif format ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format) + end + local bits = info.bitsPerSample + if bits ~= 8 and bits ~= 16 and bits ~= 24 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA") + end + if info.channels < 1 or info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + info.frameLength = (256 * info.sampleRate) // 245 + if info.frameLength < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + local frames = (info.samples + info.frameLength - 1) // info.frameLength + info.frames = frames + local st = at + 22 + if st + frames * 4 + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated seek table") + end + if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then + return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st) + end + local o = st + frames * 4 + 4 + for i = 1, frames do + local size = buffer.readu32(buf, st + (i - 1) * 4) + info.offsets[i] = o + info.sizes[i] = size + o += size + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + info: Info, + pcm: { number }, + limit: number, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.frames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local o, size = info.offsets[i], info.sizes[i] + if o + size > self.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o) + end + local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength + local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm) + if not got then + return nil, Err.from(msg, o) + end + return got, nil +end + +-- decoder(info, limit) -> Decoder (limit: the end of the file data) +function Tta.decoder(info: Info, limit: number): Decoder + return { + info = info, + pcm = table.create(info.frameLength * info.channels, 0), + limit = limit, + frame = frame, + state = Decode.state(info.channels, info.bitsPerSample // 8), + } +end + +return Tta diff --git a/src/Formats/codecs/audio/WavPack/Block.luau b/src/Formats/codecs/audio/WavPack/Block.luau new file mode 100644 index 0000000..714d2d8 --- /dev/null +++ b/src/Formats/codecs/audio/WavPack/Block.luau @@ -0,0 +1,1483 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from +-- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint +-- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), +-- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, +-- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block +-- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. +-- Never throws: returns nil, message. +local Tables = require("@formats/codecs/audio/WavPack/Tables") + +local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 +local writeu32, readf32 = buffer.writeu32, buffer.readf32 +local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz +local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight +local sign, clamp = math.sign, math.clamp + +local Block = {} + +local TWO32 = 4294967296 +local P2: { number } = table.create(34, 0) -- P2[k + 1] = 2^k +for i = 0, 33 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the number of trailing 1 bits of the byte b +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v = v // 2 + end + ONES[b + 1] = n +end + +-- header flags +local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 +local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 +local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 +local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer +local MAX_SAMPLES = 2 ^ 20 -- per block +local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front + +-- ------------------------------------------------------------------------------------------------ metadata +export type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length + +-- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) +function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) + local m: Meta = {} + local q, stop = p + 32, p + size + while stop - q >= 2 do + local id = readu8(buf, q) + local len = readu8(buf, q + 1) * 2 + q += 2 + if band(id, 0x80) ~= 0 then + if stop - q < 2 then + return nil, "truncated metadata" + end + len += readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 + q += 2 + id -= 0x80 + end + local odd = 0 + if band(id, 0x40) ~= 0 then + if len == 0 then + return nil, "odd-sized empty metadata" + end + id -= 0x40 + len -= 1 + odd = 1 + end + if stop - q < len + odd then + return nil, "truncated metadata" + end + m[id] = q + m[id + 256] = len + q += len + odd + end + return m, nil +end + +-- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches +function Block.checksum(buf: buffer, p: number, m: Meta): boolean + local o = m[0x2F] + if not o then + return true + end + local len = m[0x2F + 256] + if len ~= 2 and len ~= 4 then + return false + end + local words = (o - 2 - p) // 2 + local csum = TWO32 - 1 + for i = 0, words - 1 do + csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 + end + if len == 4 then + return readu32(buf, o) == csum + end + csum = bit32.bxor(csum, rshift(csum, 16)) + return readu16(buf, o) == band(csum, 0xFFFF) +end + +-- ------------------------------------------------------------------------------------------------ state +export type Reader = { b: buffer, p: number, e: number, n: number } +export type State = { [string]: any } + +function Block.state(): State + return { + W = table.create(D2 + 2 * 4096, 0), + term = table.create(16, 0), + delta = table.create(16, 0), + wA = table.create(16, 0), + wB = table.create(16, 0), + sA = table.create(16 * 8, 0), + sB = table.create(16 * 8, 0), + med = table.create(6, 0), + slow = { 0, 0 }, + limit = { 0, 0 }, + bacc = { 0, 0 }, + bdelta = { 0, 0 }, + sacc = { 0, 0 }, + sdelta = { 0, 0 }, + err = { 0, 0 }, + R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + scratch = buffer.create(4), + } +end + +-- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them +local function openReader(R: Reader, buf: buffer, o: number, len: number) + if buffer.len(R.b) < len + PAD then + R.b = buffer.create(len + PAD + 1024) + else + buffer.fill(R.b, len, 0, PAD) + end + buffer.copy(R.b, 0, buf, o, len) + R.p = 0 + R.e = len * 8 + R.n = len + PAD +end + +-- ------------------------------------------------------------------------------------------------ bit reading +-- bits(R, n) -> the next n (<= 32) bits, LSB first +local function bits(R: Reader, n: number): number + if n <= 0 then + return 0 + end + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 -- overrun: the caller's end check fails + return 0 + end + local b = R.b + if n <= 25 then + R.p = p + n + return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) + end + local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) + p += 16 + R.p = p + n - 16 + return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 +end + +local function bit(R: Reader): number + return bits(R, 1) +end + +-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 +-- after them when fewer than max +local function trailing(R: Reader, max: number): number + local c = 0 + while c < max do + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 + return max + end + local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1] + if ones < 8 then + if c + ones >= max then + R.p = p + (max - c) + return max + end + R.p = p + ones + 1 + return c + ones + end + c += 8 + R.p = p + 8 + end + -- (max reached inside a run of 8: give back the extra ones) + R.p -= c - max + return max +end + +-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) +local function gamma(R: Reader): number? + local c = trailing(R, 33) + if c == 33 then + return nil + end + if c < 2 then + return c + end + return bits(R, c - 1) + P2[c] +end + +-- readCode(R, maxcode) -> 0 .. maxcode (read_code) +local function readCode(R: Reader, maxcode: number): number + if maxcode < 2 then + return if maxcode == 1 then bits(R, 1) else 0 + end + local bc = 32 - countlz(maxcode) + local extras = P2[bc + 1] - maxcode - 1 + local code = bits(R, bc - 1) + if code >= extras then + code = code * 2 - extras + bits(R, 1) + end + return code +end + +-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) +local function onesCount(R: Reader): number? + local c = trailing(R, 17) + if c == 17 then + return nil + end + if c == 16 then + local g = gamma(R) + if not g then + return nil + end + c = g + 16 + end + return c +end + +-- ------------------------------------------------------------------------------------------------ lossless entropy +-- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot +-- loop of get_words_lossless, with the bit reader in locals) +local function wordsLossless(st: State, count: number, d: number): boolean + local R: Reader = st.R1 + local b, pos, lim = R.b, R.p, R.e + local W = st.W + local med = st.med + local stereo = d == D2 + -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo + local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] + if not stereo then + a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 + end + local hz, ho, za = 0, 0, 0 + for idx = d, d + count - 1 do + if stereo then + a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 + end + if pos > lim then + return false + end + if hz ~= 0 then + hz = 0 + local maxcode = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local low, used = 0, 0 + if maxcode < 2 then + if maxcode == 1 then + low, used = band(w, 1), 1 + end + else + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low = readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + low = band(w, P2[bc] - 1) + if low >= extras then + low = low * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + continue + end + if a0 < 2 and ho == 0 and c0 < 2 then + if za > 0 then + za -= 1 + if za > 0 then + W[idx] = 0 + continue + end + else + R.p = pos + local g = gamma(R) + pos = R.p + if not g then + return false + end + za = g + if za > 0 then + a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 + W[idx] = 0 + continue + end + end + end + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones == 8 then + ones = 8 + ONES[band(rshift(w, 8), 255) + 1] + end + if ones < 16 then + pos += ones + 1 + else + if band(w, 0x10000) ~= 0 then + return false + end + R.p = pos + 17 + local g = gamma(R) + pos = R.p + if not g then + return false + end + ones = g + 16 + end + local hold = ho + ho = band(ones, 1) + hz = 1 - ho + ones = ones // 2 + hold + local low, high + if ones == 0 then + low = 0 + high = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + else + low = a0 // 16 + 1 + a0 += ((a0 + 128) // 128) * 5 + if ones == 1 then + high = low + a1 // 16 + a1 -= ((a1 + 62) // 64) * 2 + else + low += a1 // 16 + 1 + a1 += ((a1 + 64) // 64) * 5 + if ones == 2 then + high = low + a2 // 16 + a2 -= ((a2 + 30) // 32) * 2 + else + low += (ones - 2) * (a2 // 16 + 1) + high = low + a2 // 16 + a2 += ((a2 + 32) // 32) * 5 + end + end + end + local maxcode = high - low + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local used = 0 + if maxcode < 2 then + if maxcode == 1 then + low += band(w, 1) + used = 1 + end + else + if maxcode >= 536870912 then + return false + end + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low += readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + local code = band(w, P2[bc] - 1) + if code >= extras then + code = code * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + low += code + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + end + R.p = pos + return pos <= lim +end + +-- ------------------------------------------------------------------------------------------------ hybrid entropy +local function updateErrorLimit(st: State, flags: number, mono: boolean) + local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit + bacc[1] = (bacc[1] + bdelta[1]) % TWO32 + local br0 = bacc[1] // 65536 + if mono then + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + end + return + end + bacc[2] = (bacc[2] + bdelta[2]) % TWO32 + local br1 = bacc[2] // 65536 + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + local sl1 = (slow[2] + 128) // 256 + if band(flags, HBALANCE) ~= 0 then + local balance = (sl1 - sl0 + br1 + 1) // 2 + if balance > br0 then + br1 = br0 * 2 + br0 = 0 + elseif -balance > br0 then + br0 = br0 * 2 + br1 = 0 + else + br1 = br0 + balance + br0 = br0 - balance + end + end + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + limit[2] = if sl1 - br1 > -256 then exp2s(sl1 - br1 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + limit[2] = exp2s(br1) % TWO32 + end +end + +-- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) + local R: Reader = st.R1 + local med = st.med + local mb = chan * 3 + local correction = 0 + if R.p > R.e then + return nil, 0 + end + if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then + if st.za > 0 then + st.za -= 1 + if st.za > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + return 0, 0 + end + else + local g = gamma(R) + if not g then + return nil, 0 + end + st.za = g + if g > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + for k = 1, 6 do + med[k] = 0 + end + return 0, 0 + end + end + end + local ones + if st.hz ~= 0 then + ones = 0 + st.hz = 0 + else + local c = onesCount(R) + if not c then + return nil, 0 + end + ones = c + if st.ho ~= 0 then + st.ho = band(ones, 1) + ones = ones // 2 + 1 + else + st.ho = band(ones, 1) + ones = ones // 2 + end + st.hz = 1 - st.ho + end + if band(flags, HYBRID) ~= 0 and chan == 0 then + updateErrorLimit(st, flags, mono) + end + local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] + local low, high + if ones == 0 then + low = 0 + high = m0 // 16 + m0 -= ((m0 + 126) // 128) * 2 + else + low = m0 // 16 + 1 + m0 += ((m0 + 128) // 128) * 5 + if ones == 1 then + high = low + m1 // 16 + m1 -= ((m1 + 62) // 64) * 2 + else + low += m1 // 16 + 1 + m1 += ((m1 + 64) // 64) * 5 + if ones == 2 then + high = low + m2 // 16 + m2 -= ((m2 + 30) // 32) * 2 + else + low += (ones - 2) * (m2 // 16 + 1) + high = low + m2 // 16 + m2 += ((m2 + 32) // 32) * 5 + end + end + end + med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 + low = band(low % TWO32, 0x7FFFFFFF) + high = band(high % TWO32, 0x7FFFFFFF) + if low > high then + high = low + end + local mid = (high + low + 1) // 2 + local limit = st.limit[chan + 1] + if limit == 0 then + mid = readCode(R, high - low) + low + else + while high - low > limit do + if R.p > R.e then + return nil, 0 + end + if bits(R, 1) == 1 then + low = mid + mid = (high + low + 1) // 2 + else + high = mid - 1 + mid = (high + low + 1) // 2 + end + end + end + local sign = bits(R, 1) + if st.wvc and limit ~= 0 then + local value = readCode(st.R2, high - low) + low + correction = if sign == 1 then mid - value else value - mid + end + if band(flags, HBITRATE) ~= 0 then + local s = st.slow + s[chan + 1] = s[chan + 1] - (s[chan + 1] + 128) // 256 + log2(mid) + end + return if sign == 1 then -mid - 1 else mid, correction +end + +-- ------------------------------------------------------------------------------------------------ decorrelation +-- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass +local function passesStereo(st: State, n: number) + local W = st.W + local last = D2 + 2 * n - 2 + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + for t = 1, st.nterms do + local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D2, last, 2 do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + sam = b0 + (b0 - b1) // dv + x = W[i + 1] + o = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + b1, b0 = b0, o + W[i + 1] = o + end + elseif term > 0 then + for j = 0, term - 1 do + W[D2 + 2 * (j - term)] = sA[so + j + 1] + W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] + end + local back = 2 * term + for i = D2, last, 2 do + local sam = W[i - back] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + sam = W[i + 1 - back] + x = W[i + 1] + W[i + 1] = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + end + elseif term == -1 then + local sa = sA[so + 1] + for i = D2, last, 2 do + local x = W[i] + local sam = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + W[i] = sam + x = W[i + 1] + sa = x + (wB * sam + 512) // 1024 + wB = clamp(wB + delta * sign(sam * x), -1024, 1024) + W[i + 1] = sa + end + elseif term == -2 then + local sb = sB[so + 1] + for i = D2, last, 2 do + local x = W[i + 1] + local sam = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i + 1] = sam + x = W[i] + sb = x + (wA * sam + 512) // 1024 + wA = clamp(wA + delta * sign(sam * x), -1024, 1024) + W[i] = sb + end + else -- -3 + local sa, sb = sA[so + 1], sB[so + 1] + for i = D2, last, 2 do + local x = W[i] + local samA = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + x = W[i + 1] + local samB = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i], W[i + 1] = samA, samB + sa, sb = samB, samA + end + end + end +end + +-- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass +local function passesMono(st: State, n: number) + local W = st.W + local last = D1 + n - 1 + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + for t = 1, st.nterms do + local term, delta, wA = terms[t], deltas[t], wAs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1 = sA[so + 1], sA[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D1, last do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + end + else + for j = 0, term - 1 do + W[D1 + j - term] = sA[so + j + 1] + end + for i = D1, last do + local sam = W[i - term] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ hybrid lossless +local function shaped(st: State, c: number, flags: number, correction: number): number + -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) + local sacc, sdelta, err = st.sacc, st.sdelta, st.err + sacc[c] = (sacc[c] + sdelta[c]) % TWO32 + local sw = sacc[c] // 65536 + if sw >= 32768 then + sw -= 65536 + end + local temp = -((sw * err[c] + 512) // 1024) + if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then + if temp == err[c] then + temp = if temp < 0 then temp + 1 else temp - 1 + end + err[c] = temp - correction + else + err[c] = -correction + end + return temp +end + +local function hybridMono(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + for i = 0, n - 1 do + local word, corr = getWord(st, 0, flags, true) + if not word then + return false + end + local rw = word + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + local sam, k + if term > 8 then + sam = if term % 2 == 1 then 2 * sA[so + 1] - sA[so + 2] else (3 * sA[so + 1] - sA[so + 2]) // 2 + sA[so + 2] = sA[so + 1] + k = 0 + else + sam = sA[so + m + 1] + k = band(m + term, 7) + end + local temp = (wAs[t] * sam + 512) // 1024 + rw + wAs[t] += deltas[t] * sign(sam * rw) + sA[so + k + 1] = temp + rw = temp + end + m = band(m + 1, 7) + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, corr) + rw += corr - temp + else + rw += corr + end + crc = (crc * 3 + rw) % TWO32 + W[D1 + i] = rw + end + st.crcv = crc + return true +end + +local function hybridStereo(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + local cross = band(flags, CROSS) ~= 0 + local joint = band(flags, JOINT) ~= 0 + for i = 0, n - 1 do + local left, corr0 = getWord(st, 0, flags, false) + if not left then + return false + end + local right, corr1 = getWord(st, 1, flags, false) + if not right then + return false + end + local leftc, rightc = 0, 0 + if cross then + leftc, rightc = left + corr0, right + corr1 + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + if term > 0 then + local samA, samB + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + end + leftc += (wAs[t] * samA + 512) // 1024 + rightc += (wBs[t] * samB + 512) // 1024 + elseif term == -1 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + rightc += (wBs[t] * leftc + 512) // 1024 + else + rightc += (wBs[t] * sB[so + 1] + 512) // 1024 + if term == -3 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + else + leftc += (wAs[t] * rightc + 512) // 1024 + end + end + end + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + for t = 1, nterms do + local term, delta, so = terms[t], deltas[t], (t - 1) * 8 + if term > 0 then + local samA, samB, k + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + sA[so + 2] = sA[so + 1] + sB[so + 2] = sB[so + 1] + k = 0 + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + k = band(m + term, 7) + end + local left2 = (wAs[t] * samA + 512) // 1024 + left + local right2 = (wBs[t] * samB + 512) // 1024 + right + wAs[t] += delta * sign(samA * left) + wBs[t] += delta * sign(samB * right) + left, right = left2, right2 + sA[so + k + 1], sB[so + k + 1] = left, right + elseif term == -1 then + local sa = sA[so + 1] + local left2 = left + (wAs[t] * sa + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) + left = left2 + local right2 = right + (wBs[t] * left2 + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) + right = right2 + sA[so + 1] = right + else + local sb = sB[so + 1] + local right2 = right + (wBs[t] * sb + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) + right = right2 + if term == -3 then + right2 = sA[so + 1] + sA[so + 1] = right + end + local left2 = left + (wAs[t] * right2 + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) + left = left2 + sB[so + 1] = left + end + end + m = band(m + 1, 7) + if not cross then + leftc, rightc = left + corr0, right + corr1 + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + if joint then + right -= left // 2 + left += right + end + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, leftc - left) + left = leftc - temp + temp = shaped(st, 2, flags, rightc - right) + right = rightc - temp + else + left, right = leftc, rightc + end + crc = (crc * 9 + left * 3 + right) % TWO32 + W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right + end + st.crcv = crc + return true +end + +-- ------------------------------------------------------------------------------------------------ metadata -> state +local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local o = m[2] + if o then -- decorrelation terms + local cnt = m[2 + 256] + if cnt > 16 then + return "too many decorrelation terms" + end + st.nterms = cnt + for i = 0, cnt - 1 do + local v = readu8(buf, o + i) + local t = cnt - i + local term = band(v, 0x1F) - 5 + if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then + return "bad decorrelation term" + end + st.term[t] = term + st.delta[t] = band(rshift(v, 5), 7) + end + end + local nterms = st.nterms + o = m[3] + if o then -- weights, from the last pass back + for t = 1, nterms do + st.wA[t], st.wB[t] = 0, 0 + end + local cnt = m[3 + 256] + if not mono then + cnt //= 2 + end + if cnt > nterms then + return "too many decorrelation weights" + end + local q = o + for t = nterms, nterms - cnt + 1, -1 do + st.wA[t] = restoreWeight(readi8(buf, q)) + q += 1 + if not mono then + st.wB[t] = restoreWeight(readi8(buf, q)) + q += 1 + end + end + end + local sA, sB = st.sA, st.sB + o = m[4] + if o then -- decorrelation samples, from the last pass back + for k = 1, nterms * 8 do + sA[k], sB[k] = 0, 0 + end + local q, stop = o, o + m[4 + 256] + if version == 0x402 and band(flags, HYBRID) ~= 0 then + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + st.err[1] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + st.err[2] = exp2s(readi16(buf, q)) + q += 2 + end + end + local t = nterms + while t >= 1 and q < stop do + local term, so = st.term[t], (t - 1) * 8 + if term > 8 then + if q + (if mono then 4 else 8) > stop then + return "bad decorrelation samples" + end + sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + if not mono then + sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + end + elseif term < 0 then + if q + 4 > stop then + return "bad decorrelation samples" + end + sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + else + for k = 1, term do + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + sA[so + k] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + sB[so + k] = exp2s(readi16(buf, q)) + q += 2 + end + end + end + t -= 1 + end + if q ~= stop then + return "bad decorrelation samples" + end + end + o = m[5] + if o then -- entropy medians + if m[5 + 256] ~= (if mono then 6 else 12) then + return "bad entropy variables" + end + for k = 0, (if mono then 2 else 5) do + st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 + end + end + o = m[6] + if o then -- hybrid profile + local q, stop = o, o + m[6 + 256] + local w = if mono then 2 else 4 + if band(flags, HBITRATE) ~= 0 then + if q + w > stop then + return "bad hybrid profile" + end + st.slow[1] = exp2s(readu16(buf, q)) % TWO32 + if not mono then + st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 + end + q += w + end + if q + w > stop then + return "bad hybrid profile" + end + st.bacc[1] = readu16(buf, q) * 65536 + if not mono then + st.bacc[2] = readu16(buf, q + 2) * 65536 + end + q += w + if q < stop then + if q + w > stop then + return "bad hybrid profile" + end + st.bdelta[1] = exp2s(readi16(buf, q)) + if not mono then + st.bdelta[2] = exp2s(readi16(buf, q + 2)) + end + q += w + if q < stop then + return "bad hybrid profile" + end + end + end + o = m[7] + if o then -- noise shaping + local len = m[7 + 256] + if len == 2 then + st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 + st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 + elseif len >= (if mono then 4 else 8) then + st.err[1] = exp2s(readi16(buf, o)) + st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 + if not mono then + st.err[2] = exp2s(readi16(buf, o + 4)) + st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 + end + local q = o + (if mono then 4 else 8) + if len == (if mono then 6 else 12) then + st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 + if not mono then + st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 + end + end + else + return "bad shaping weights" + end + end + o = m[8] + if o then + if m[8 + 256] ~= 4 then + return "bad float info" + end + st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) + end + o = m[9] + if o then + if m[9 + 256] ~= 4 then + return "bad int32 info" + end + st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ fixup + output +-- the float conversion of one value (float_values; R = the wvx stream or nil) +local function floatValue(st: State, v: number, R: Reader?): number + local fflags, exp = st.fflags, st.fmaxexp + local mant, e, sign = 0, 0, 0 + if v == 0 then + if R then + if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + if exp >= 25 then + e = bits(R, 8) + end + sign = bits(R, 1) + elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then + sign = bits(R, 1) + end + end + end + else + v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 + if v >= 2147483648 then + v -= TWO32 + end + if v < 0 then + v = -v + sign = 1 + end + if R then + if v == 0x1000000 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + end + e = 255 + else + local shift = 0 + if exp > 0 then + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + end + shift = band(shift, 31) + if shift > 0 then + if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then + v += P2[shift + 1] - 1 + elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then + local mask = P2[shift + 1] - 1 + local zeros = 0 + local maxOnes, minZeros = st.fmaxones, st.fminzeros + if maxOnes > 0 and shift > maxOnes then + zeros = shift - maxOnes + end + if minZeros > zeros then + zeros = if minZeros > shift then shift else minZeros + end + local sc = shift - zeros + if sc > 0 then + v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) + end + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + else + if v >= 0x1000000 then + while band(v, 0xF000000) ~= 0 do + v //= 2 + exp += 1 + end + elseif exp > 0 then + local shift = 0 + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + shift = band(shift, 31) + if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then + v += P2[shift + 1] - 1 + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + end + if R then + st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 + end + local sc = st.scratch + writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) + return readf32(sc, 0) +end + +-- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) + local W = st.W + local s = if d == D2 then 2 else 1 + local count = n * s + local R: Reader? = if st.wvx then st.R3 else nil + if band(flags, FLOAT) ~= 0 then + for k = 0, count - 1 do + W[d + k] = floatValue(st, W[d + k], R) + end + else + local shift = band(rshift(flags, 13), 31) + if band(flags, INT32) ~= 0 then + local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) + if R then + local maxw = st.imaxw + local crc = st.crcx + for k = d, d + count - 1 do + local v = W[k] + if sent > 0 then + if maxw > 0 then + local pv = if v < 0 then -v - 1 else v + local width = (32 - countlz(pv)) + sent + local btr = sent + if width > maxw then + btr -= width - maxw + end + if width <= maxw or btr > 0 then + v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] + else + v *= P2[sent + 1] + end + else + v = v * P2[sent + 1] + bits(R, sent) + end + end + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + v %= TWO32 + if v >= 2147483648 then + v -= TWO32 + end + crc = (crc * 9 + (v % 65536) * 3 + (v // 65536) % 65536) % TWO32 + W[k] = v + end + st.crcx = crc + elseif sent == 0 and zeros + ones + dups > 0 then + while lossy and band(flags, 3) == 3 and shift < 8 do + if zeros > 0 then + zeros -= 1 + elseif ones > 0 then + ones -= 1 + elseif dups > 0 then + dups -= 1 + else + break + end + shift += 1 + end + for k = d, d + count - 1 do + local v = W[k] + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + W[k] = v + end + else + shift += zeros + sent + ones + dups + end + end + shift = band(shift, 31) + if lossy then + local bytes = band(flags, 3) + local top = if bytes == 0 then 127 elseif bytes == 1 then 32767 elseif bytes == 2 then 8388607 else 2147483647 + local minv, maxv = (-top - 1) // P2[shift + 1], top // P2[shift + 1] + local mul = P2[shift + 1] + for k = d, d + count - 1 do + local v = W[k] + if v < minv then + v = minv + elseif v > maxv then + v = maxv + end + W[k] = v * mul + end + elseif shift > 0 then + local mul = P2[shift + 1] + for k = d, d + count - 1 do + W[k] *= mul + end + end + end + -- interleave + if s == 2 then + if c0 == 0 and C == 2 then + for k = 0, count - 1 do + P[k + 1] = W[d + k] + end + elseif c0 + 2 <= C then + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + P[i * C + c0 + 2] = W[d + 2 * i + 1] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + end + end + elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then + for i = 0, n - 1 do + local v = W[d + i] + P[i * C + c0 + 1] = v + P[i * C + c0 + 2] = v + end + elseif C == 1 then + for k = 0, n - 1 do + P[k + 1] = W[d + k] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + i] + end + end +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p +-- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given +function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) + local version = readu16(buf, p + 8) + local n = readu32(buf, p + 20) + local flags = readu32(buf, p + 24) + local crcWant = readu32(buf, p + 28) + if band(flags, DSD) ~= 0 then + return nil, "unsupported: DSD audio" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. version + end + if n > MAX_SAMPLES then + return nil, "limit: block of " .. n .. " samples" + end + if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then + return nil, "bad block flags" + end + local mm, merr = Block.meta(buf, p, size) + if not mm then + return nil, merr + end + local m: Meta = mm + local cm: Meta = {} + local cb: buffer = buf + local hasC = false + if cbuf and cp and csize then + local cmeta, cerr = Block.meta(cbuf, cp, csize) + if not cmeta then + return nil, cerr + end + cm, cb, hasC = cmeta, cbuf, true + crcWant = readu32(cbuf, cp + 28) + end + -- reset + st.nterms = 0 + local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB + for k = 1, 128 do + sA[k], sB[k] = 0, 0 + end + for t = 1, 16 do + wA[t], wB[t] = 0, 0 + end + local med = st.med + for k = 1, 6 do + med[k] = 0 + end + st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 + st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 + st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 + st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 + st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 + st.hz, st.ho, st.za = 0, 0, 0 + st.crcx = TWO32 - 1 + st.wvc, st.wvx = false, false + local e = readMeta(st, buf, m, flags, version) + if e then + return nil, e + end + if hasC then + e = readMeta(st, cb, cm, flags, version) + if e then + return nil, e + end + end + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local out = if band(flags, MONO_FLAG) ~= 0 then 1 else 2 + if n == 0 then + return out, nil + end + -- bitstreams + local o = m[0xA] + if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then + return nil, "no audio bitstream" + end + openReader(st.R1, buf, o, m[0xA + 256]) + if hasC then + local co = cm[0xB] + if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then + openReader(st.R2, cb, co, cm[0xB + 256]) + st.wvc = true + end + end + -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) + local xb, xm = buf, m + if hasC and (cm[0xC] or cm[0x2C]) then + xb, xm = cb, cm + end + local xid = if xm[0x2C] then 0x2C elseif xm[0xC] then 0xC else nil + if xid then + local xo, xl = xm[xid], xm[xid + 256] + if xl <= 4 or xl % 2 == 1 then + return nil, "bad wvx bitstream" + end + st.crcwvx = readu32(xb, xo) + openReader(st.R3, xb, xo + 4, xl - 4) + st.wvx = true + if xid == 0x2C then + if band(flags, FLOAT) ~= 0 then + st.fminzeros = bits(st.R3, 5) + st.fmaxones = bits(st.R3, 5) + else + st.imaxw = bits(st.R3, 5) + end + end + end + local hybrid = band(flags, HYBRID) ~= 0 + local d = if mono then D1 else D2 + local W = st.W + if #W < d + 2 * n then + W = table.create(d + 2 * n + 64, 0) + st.W = W + end + local crc = TWO32 - 1 + if not st.wvc then + if hybrid then + if mono then + for i = 0, n - 1 do + local v = getWord(st, 0, flags, true) + if not v then + return nil, "bad audio bitstream" + end + W[d + i] = v + end + else + for i = 0, n - 1 do + local l = getWord(st, 0, flags, false) + local r = l and getWord(st, 1, flags, false) + if not l or not r then + return nil, "bad audio bitstream" + end + W[d + 2 * i], W[d + 2 * i + 1] = l, r + end + end + elseif not wordsLossless(st, if mono then n else 2 * n, d) then + return nil, "bad audio bitstream" + end + if mono then + passesMono(st, n) + for k = d, d + n - 1 do + crc = (crc * 3 + W[k]) % TWO32 + end + else + passesStereo(st, n) + local last = d + 2 * n - 2 + if band(flags, JOINT) ~= 0 then + for k = d, last, 2 do + local l = W[k] + local r = W[k + 1] - l // 2 + l += r + W[k], W[k + 1] = l, r + crc = (crc * 9 + l * 3 + r) % TWO32 + end + else + for k = d, last, 2 do + crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 + end + end + end + else + local ok = if mono then hybridMono(st, n, flags) else hybridStereo(st, n, flags) + if not ok then + return nil, "bad audio bitstream" + end + crc = st.crcv + end + if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then + return nil, "truncated audio bitstream" + end + if crc ~= crcWant then + return nil, "checksum: block CRC mismatch" + end + emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) + if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then + return nil, "checksum: wvx CRC mismatch" + end + return out, nil +end + +Block.bits = bits +Block.bit = bit + +return Block diff --git a/src/Formats/codecs/audio/WavPack/Tables.luau b/src/Formats/codecs/audio/WavPack/Tables.luau new file mode 100644 index 0000000..e06596d --- /dev/null +++ b/src/Formats/codecs/audio/WavPack/Tables.luau @@ -0,0 +1,65 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, +-- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz + +local Tables = {} + +-- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 +local LOG2: { number } = { + 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, + 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, + 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178, + 179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, + 207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, + 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255, +} +local EXP2: { number } = { + 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, + 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48, + 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, + 139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173, + 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, + 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, +} + +-- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) +function Tables.exp2s(lg: number): number + if lg < 0 then + local v = Tables.exp2s(-lg) + v = -(if v >= 2147483648 then v - 4294967296 else v) + return if v >= 2147483648 then v - 4294967296 else v + end + local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) + local k = lg // 256 + local r = if k <= 9 then rshift(value, 9 - k) else lshift(value, band(k - 9, 31)) + return if r >= 2147483648 then r - 4294967296 else r +end + +-- log2(v) -> wp_log2 of the uint32 v +function Tables.log2(v: number): number + v = (v + rshift(v, 9)) % 4294967296 + if v < 256 then + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1] + end + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] +end + +-- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) +function Tables.restoreWeight(w: number): number + local r = w * 8 + if r > 0 then + r += (r + 64) // 128 + end + return r +end + +return Tables diff --git a/src/Formats/codecs/audio/WavPack/init.luau b/src/Formats/codecs/audio/WavPack/init.luau new file mode 100644 index 0000000..e774a5f --- /dev/null +++ b/src/Formats/codecs/audio/WavPack/init.luau @@ -0,0 +1,238 @@ +--!strict +-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec +-- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in +-- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 +-- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo +-- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross +-- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). +-- +-- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) +-- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) +-- local dec = WavPack.decoder(info.channels) +-- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) +-- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Block = require("@formats/codecs/audio/WavPack/Block") + +local WavPack = {} + +export type Header = { + size: number, -- the whole block (ckSize + 8) + version: number, + index: number, -- the first sample of the block (40 bits) + total: number, -- total samples of the file (-1: unknown) + samples: number, + flags: number, + crc: number, +} + +local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 } +WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 +WavPack.DSD = 0x80000000 + +-- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit +function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?) + local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) + if at < 0 or at + 32 > lim then + return nil, "truncated block header" + end + if buffer.readstring(buf, at, 4) ~= "wvpk" then + return nil, "no block header" + end + local ck = buffer.readu32(buf, at + 4) + local version = buffer.readu16(buf, at + 8) + if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then + return nil, "bad block size" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. string.format("0x%x", version) + end + local total = buffer.readu32(buf, at + 12) + local tu8 = buffer.readu8(buf, at + 11) + local h: Header = { + size = ck + 8, + version = version, + index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, + total = if total == 0xFFFFFFFF then -1 else total + tu8 * 4294967296 - tu8, + samples = buffer.readu32(buf, at + 20), + flags = buffer.readu32(buf, at + 24), + crc = buffer.readu32(buf, at + 28), + } + if at + h.size > lim then + return nil, "truncated block" + end + return h, nil +end + +export type Info = { + channels: number, + channelMask: number, + sampleRate: number, + bitsPerSample: number, -- the source depth (container bytes * 8 - shift) + bytesPerSample: number, -- the container: 1 .. 4 + float: boolean, + hybrid: boolean, + md5: string?, -- 32 hex digits when stored + version: number, +} + +-- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` +function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) + local h, herr = WavPack.header(buf, at, limit) + if not h then + return nil, Err.from(herr, at) + end + local m, merr = Block.meta(buf, at, h.size) + if not m then + return nil, Err.from(merr, at) + end + local flags = h.flags + if bit32.band(flags, WavPack.DSD) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "DSD audio") + end + local bytes = bit32.band(flags, 3) + 1 + local info: Info = { + channels = if bit32.band(flags, WavPack.MONO) ~= 0 then 1 else 2, + channelMask = 0, + sampleRate = 44100, + bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31), + bytesPerSample = bytes, + float = bit32.band(flags, WavPack.FLOAT) ~= 0, + hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0, + version = h.version, + } + info.channelMask = if info.channels == 1 then 4 else 3 + local sr = bit32.band(bit32.rshift(flags, 23), 15) + if sr < 15 then + info.sampleRate = RATES[sr + 1] + end + local o = m[0x27] -- ID_SAMPLE_RATE + if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then + local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536 + if m[0x27 + 256] == 4 then + rate += bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216 + end + info.sampleRate = rate + end + o = m[0xD] -- ID_CHANNEL_INFO + if o then + local len = m[0xD + 256] + if len == 0 or len > 7 then + return nil, Err.new(Err.CORRUPT, "bad channel info", o) + end + local mask = 0 + if len >= 6 then + info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1 + mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536 + if len == 7 then + mask += buffer.readu8(buf, o + 6) * 16777216 + end + else + info.channels = buffer.readu8(buf, o) + for k = 1, len - 1 do + mask += buffer.readu8(buf, o + k) * 256 ^ (k - 1) + end + end + info.channelMask = mask + end + if info.channels < 1 then + return nil, Err.new(Err.CORRUPT, "no channels") + end + if info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + return info, nil +end + +-- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` +function WavPack.md5(buf: buffer, at: number, limit: number?): string? + local h = WavPack.header(buf, at, limit) + if not h then + return nil + end + local m = Block.meta(buf, at, h.size) + if not m then + return nil + end + local o = m[0x26] + if not o or m[0x26 + 256] ~= 16 then + return nil + end + local hex = table.create(16, "") + for k = 0, 15 do + hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k)) + end + return table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + channels: number, + pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats) + frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), + state: Block.State, +} + +-- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per +-- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) +local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) + local C = self.channels + local n = -1 + local c0 = 0 + for i, at in blocks do + if c0 >= C then + break + end + local h, herr = WavPack.header(buf, at) + if not h then + return nil, Err.from(herr, at) + end + if n < 0 then + n = h.samples + if n * C > 16777216 then + return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at) + end + if #self.pcm < n * C then + self.pcm = table.create(n * C, 0) + end + elseif h.samples ~= n then + return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at) + end + local cb, cp, cs = nil, nil, nil + if cbuf and cblocks and cblocks[i] then + local ch = WavPack.header(cbuf, cblocks[i]) + if ch and ch.samples == h.samples and ch.index == h.index then + cb, cp, cs = cbuf, cblocks[i], ch.size + end + end + local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs) + if not got then + return nil, Err.from(msg, at) + end + c0 += got + end + if n < 0 then + return 0, nil + end + if c0 < C then + return nil, Err.new(Err.CORRUPT, "a frame is missing channels") + end + return n, nil +end + +-- decoder(channels) -> Decoder +function WavPack.decoder(channels: number): Decoder + return { + channels = channels, + pcm = table.create(4096 * channels, 0), + frame = frame, + state = Block.state(), + } +end + +WavPack.checksum = Block.checksum +WavPack.meta = Block.meta + +return WavPack diff --git a/tests/audio/_lossless.luau b/tests/audio/_lossless.luau new file mode 100644 index 0000000..77174b7 --- /dev/null +++ b/tests/audio/_lossless.luau @@ -0,0 +1,136 @@ +-- Shared checks of the lossless audio format tests (wavpack, ape, tta): every fixture opened, decoded bit-exact +-- against the reference decoder's samples (readInt for integer streams, the f32 bytes for float ones), f32 scaling +-- and output reuse, seeking to sample-accurate positions, reading past the end, tags, sniff. A fixture is a table +-- { name, data, rate, channels, bits, float, frames, crc, tags?, partial? } (partial: a cut file whose decode stops +-- with an error; the reference decoded its first `frames` frames). +local T = require("@tests/T") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") + +local L = {} + +local f32buf = buffer.create(4) +local function f32(x: number): number + buffer.writef32(f32buf, 0, x) + return buffer.readf32(f32buf, 0) +end + +local function open(mod: any, b: any, opts: any?): (any, any) + return mod.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts) +end +L.open = open + +-- all(dec, fx) -> crc of every sample read (i32 for integer streams, f32 bytes for floats), frames, the values +function L.all(dec: any, fx: any): (number, number, { number }) + local ch = dec.channels + local vals = table.create(fx.frames * ch, 0) + local crc, n, k = 0, 0, 0 + local sizes = { 4096, 1, 777, 10000, 3 } + while true do + k += 1 + local out, got + if fx.float then + out, got = dec:read(sizes[k % #sizes + 1]) + else + out, got = dec:readInt(sizes[k % #sizes + 1]) + end + if got == 0 then + break + end + if fx.partial then -- a cut file: the reference decoded fx.frames (whole frames); the rest may decode too + got = math.min(got, fx.frames - n) + if got <= 0 then + continue + end + end + crc = Crc32.of(out, 0, got * ch * 4, crc) + for i = 0, got * ch - 1 do + vals[n * ch + i + 1] = if fx.float then buffer.readf32(out, i * 4) else buffer.readi32(out, i * 4) + end + n += got + end + return crc, n, vals +end + +-- cases(t, mod, cases, optsOf?) -> seeks checked: the per-fixture checks; optsOf(fx) gives the open options +function L.cases(t: any, mod: any, cases: { any }, optsOf: ((any) -> any)?): number + local seekChecks = 0 + for _, fx in cases do + local name = fx.name + local dec, err = open(mod, fx.data, optsOf and optsOf(fx)) + t:check(dec, name .. ": open: " .. tostring(err)) + t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels, name .. ": format") + if not fx.partial then + t:eq(dec.frames, fx.frames, name .. ": frames") + t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration") + end + t:eq(dec.float, fx.float, name .. ": float") + local crc, n, vals = L.all(dec, fx) + if fx.partial then + t:check(dec.error ~= nil, name .. ": the cut frame is reported") + else + t:eq(dec.error, nil, name .. ": no decode error") + end + t:eq(n, fx.frames, name .. ": decoded frames") + t:eq(crc, fx.crc, name .. ": samples identical to the reference decoder") + -- f32 scaling, output reuse + local ch = dec.channels + dec:seek(0) + local reuse = buffer.create(100 * ch * 4) + local f, gotf = dec:read(100, reuse) + t:check(f == reuse, name .. ": output buffer reused") + local scale = if fx.float then 1 else 2 ^ ((fx.container or fx.bits) - 1) + local bad = 0 + for i = 0, math.min(gotf, 100) * ch - 1 do + if buffer.readf32(f, i * 4) ~= f32(vals[i + 1] / scale) then + bad += 1 + end + end + t:eq(bad, 0, name .. ": f32 samples") + -- seeking (sample-accurate: seek(s / rate) lands on frame s) + local last = if fx.partial then fx.frames - 50 else fx.frames + local rand = T.rng(7) + local targets = { 0, 1, last - 1, last // 2, 22050, 22049, 73729, 73727 } + for _ = 1, 6 do + table.insert(targets, rand(math.max(last, 1))) + end + for _, s in targets do + if s >= 0 and s < last then + dec:seek(s / fx.rate) + t:check(math.abs(dec:position() * fx.rate - s) < 1e-6, name .. ": position after seek " .. s) + local out, got = dec:read(50) + t:eq(got, math.min(50, fx.frames - s), name .. ": read after seek " .. s) + local diff = 0 + for i = 0, got * ch - 1 do + if buffer.readf32(out, i * 4) ~= f32(vals[s * ch + i + 1] / scale) then + diff += 1 + end + end + t:eq(diff, 0, name .. ": samples after seek " .. s) + seekChecks += 1 + end + end + dec:seek(dec.duration + 5) + t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") + for key, v in fx.tags or {} do + t:eq(dec.tags[key], v, name .. ": tag " .. key) + end + t:eq(mod.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") + end + return seekChecks +end + +-- subrange(t, mod, fx, depth) : decode() from a Reader over a sub-range equals read(); meta.source +function L.subrange(t: any, mod: any, fx: any, format: string) + local name = fx.name + local big = buffer.create(#fx.data + 13) + buffer.writestring(big, 6, fx.data) + local a, err = mod.decode(Bytes.reader(big, 6, #fx.data)) + t:check(a and a.kind == "audio" and a.frames == fx.frames and a.channels == fx.channels, name .. ": decode: " .. tostring(err)) + local ref = open(mod, fx.data):read(fx.frames) + t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read") + t:eq(a.meta.source.format, format, name .. ": meta.source") + t:eq(a.meta.source.bitDepth, if fx.float then 32 else fx.bits, name .. ": bit depth") +end + +return L diff --git a/tests/audio/ape.luau b/tests/audio/ape.luau new file mode 100644 index 0000000..2d83725 --- /dev/null +++ b/tests/audio/ape.luau @@ -0,0 +1,90 @@ +-- audio/ape tests: every fixture from tools/fixtures/ape.py (mac -c1000 .. -c5000, 8 - 32-bit int and 32-bit float, +-- 1 - 8 channels, special frames (silence, pseudo stereo), odd rates and lengths, a second frame, APEv2 tags, the FATE +-- sample of an older 3.99 encoder cut mid-frame) decoded bit-exact against `mac -d`; seeking; f32 scaling and output +-- reuse; decode() from a sub-range Reader; an ID3v2 tag in front; the header facts; sniff; the api; a damaged frame +-- (CRC); the fuzz pass. Fixtures: tools/fixtures/ape.py. +local T = require("@tests/T") +local Ape = require("@formats/audio/ape") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/ape_cases") +local L = require("@tests/audio/_lossless") + +local t = T.suite("ape") +local byName = {} +for _, c in Cases do + byName[c.name] = c +end +local function open(b: any, opts: any?): (any, any) + return L.open(Ape, b, opts) +end + +t:eq(Ape.name, "ape", "name") +t:check(Ape.caps.decode and not Ape.caps.encode, "caps") + +local seekChecks = L.cases(t, Ape, Cases) +t:note("%d fixtures bit-exact against mac -d, %d seeks", #Cases, seekChecks) + +for _, name in { "s16_c2000", "tags", "f32", "ch6" } do + L.subrange(t, Ape, byName[name], "ape") +end + +-- header facts +do + local d = open(byName.s16_c5000.data) + t:eq(d.level, "insane", "level") + t:eq(d.bitsPerSample, 16, "bits") + t:check(d.version >= 3990, "version") + t:eq(open(byName.s24_c4000.data).level, "extra high", "level 4000") + t:eq(open(byName.s16_c1000.data).level, "fast", "level 1000") +end + +-- an ID3v2 tag in front of the descriptor (the seek table counts from the descriptor) +do + local fx = byName.s16_c3000 + local id3 = "ID3\4\0\0\0\0\0\20" .. "TIT2\0\0\0\10\0\0\3hello id3" + local b = buffer.fromstring(id3 .. fx.data) + t:eq(Ape.sniff(Bytes.reader(b)), 1, "sniff ID3 + MAC") + local dec = open(b) + t:check(dec and (L.all(dec, fx)) == fx.crc, "ID3v2 in front") +end + +-- the api +do + local fx = byName.s16_c2000 + local _ = fx + t:eq(F.detect(buffer.fromstring(fx.data)), "ape", "detect") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames and a.meta.source.format == "ape", "F.audio.load") +end + +-- errors: a damaged frame fails its CRC, bad headers +do + local fx = byName.s16_long -- two frames: the second is damaged + local b = buffer.fromstring(fx.data) + local at = #fx.data - 2000 + buffer.writeu8(b, at, bit32.bxor(buffer.readu8(b, at), 0x40)) + local dec = open(b) + local _, got = dec:read(fx.frames) + t:check(dec.error and (dec.error.code == Err.CHECKSUM or dec.error.code == Err.CORRUPT) and got == 73728, "damaged frame: " .. tostring(dec.error)) + local _, e0 = open(buffer.fromstring(string.sub(fx.data, 1, 2000) .. string.rep("\0", 100))) + t:check(e0 ~= nil, "a broken first frame fails open: " .. tostring(e0)) + local _, e1 = open("MAC ") + t:check(e1 and Err.is(e1), "too short: " .. tostring(e1)) + local old = buffer.fromstring(fx.data) + buffer.writeu16(old, 4, 3800) + local _, e2 = open(old) + t:check(e2 and e2.code == Err.UNSUPPORTED, "old version: " .. tostring(e2)) + t:eq(Ape.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") +end + +-- the fuzz pass +local samples = {} +for _, name in { "s16_c2000", "s16_c4000", "mono", "s24", "s32", "f32", "ch6", "silence", "pseudo_stereo" } do + table.insert(samples, buffer.fromstring(byName[name].data)) +end +t:fuzz("decode", function(b: buffer) + return Ape.decode(Bytes.reader(b)) +end, samples, { mutations = 50 }) +t:done() diff --git a/tests/audio/tta.luau b/tests/audio/tta.luau new file mode 100644 index 0000000..9a46b83 --- /dev/null +++ b/tests/audio/tta.luau @@ -0,0 +1,100 @@ +-- audio/tta tests: every fixture from tools/fixtures/tta.py (ttaenc 3.4.1: 8 / 16 / 24 bits, 1 - 6 channels, odd +-- rates and lengths, several frames, silence, noise; the FATE sample inside.tta cut mid-file) decoded bit-exact +-- against `ttaenc -d`; seeking; f32 scaling and output reuse; decode() from a sub-range Reader; an ID3v2 tag in front +-- and an APEv2 tag at the end; password-protected files (UNSUPPORTED); header / seek table / frame CRCs; sniff; the +-- api; the fuzz pass. Fixtures: tools/fixtures/tta.py. +local T = require("@tests/T") +local Tta = require("@formats/audio/tta") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/tta_cases") +local L = require("@tests/audio/_lossless") + +local t = T.suite("tta") +local byName = {} +for _, c in Cases do + byName[c.name] = c +end +local function open(b: any, opts: any?): (any, any) + return L.open(Tta, b, opts) +end + +t:eq(Tta.name, "tta", "name") +t:check(Tta.caps.decode and not Tta.caps.encode, "caps") + +local seekChecks = L.cases(t, Tta, Cases) +t:note("%d fixtures bit-exact against ttaenc -d, %d seeks", #Cases, seekChecks) + +for _, name in { "s16", "s24", "ch6", "u8" } do + L.subrange(t, Tta, byName[name], "tta") +end + +local function u32(v: number): string + return string.char(v % 256, (v // 256) % 256, (v // 65536) % 256, (v // 16777216) % 256) +end + +-- an ID3v2 tag in front, an APEv2 tag at the end +do + local fx = byName.s16 + local id3 = "ID3\4\0\0\0\0\0\20" .. "TIT2\0\0\0\10\0\0\3hello id3" + local item = u32(5) .. u32(0) .. "Title\0" .. "Hello" + local tail = item .. "APETAGEX" .. u32(2000) .. u32(#item + 32) .. u32(1) .. u32(0) .. string.rep("\0", 8) + local b = buffer.fromstring(id3 .. fx.data .. tail) + t:eq(Tta.sniff(Bytes.reader(b)), 1, "sniff ID3 + TTA1") + local dec = open(b) + t:check(dec and (L.all(dec, fx)) == fx.crc, "ID3v2 + APEv2 around the file") + t:eq(dec.tags.title, "Hello", "APEv2 title") +end + +-- errors: password protection, CRCs +do + local fx = byName.s16 + local b = buffer.fromstring(fx.data) + buffer.writeu16(b, 4, 2) + buffer.writeu32(b, 18, Crc32.of(b, 0, 18)) + local _, e1 = open(b) + t:check(e1 and e1.code == Err.UNSUPPORTED, "password-protected: " .. tostring(e1)) + local h = buffer.fromstring(fx.data) + buffer.writeu8(h, 10, 0x45) + local _, e2 = open(h) + t:check(e2 and e2.code == Err.CHECKSUM, "header CRC: " .. tostring(e2)) + local long = byName.s16_long + local d = buffer.fromstring(long.data) + local at = #long.data - 3000 + buffer.writeu8(d, at, bit32.bxor(buffer.readu8(d, at), 1)) + local dec = open(d) + local _, got = dec:read(long.frames) + t:check(dec.error and dec.error.code == Err.CHECKSUM and got == 2 * 46080, "frame CRC: " .. tostring(dec.error)) + local _, e3 = open("TTA1") + t:check(e3 and Err.is(e3), "too short: " .. tostring(e3)) + t:eq(Tta.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") +end + +-- the api +do + local fx = byName.s16 + t:eq(F.detect(buffer.fromstring(fx.data)), "tta", "detect") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames and a.meta.source.format == "tta", "F.audio.load") +end + +-- the fuzz pass (the frame CRC rejects most mutations; the second set skips it to reach the decoder) +local samples = {} +for _, name in { "s16", "mono", "s24", "u8", "ch6" } do + table.insert(samples, buffer.fromstring(byName[name].data)) +end +t:fuzz("decode", function(b: buffer) + return Tta.decode(Bytes.reader(b)) +end, samples, { mutations = 150 }) +local Decode = require("@formats/codecs/audio/Tta/Decode") +t:fuzz("frames without CRC", function(b: buffer) + local n = buffer.len(b) + local c = buffer.create(n + 4) + buffer.copy(c, 0, b) + buffer.writeu32(c, n, Crc32.of(b)) + local st = Decode.state(2, 2) + return Decode.frame(st, c, 0, n + 4, 2000, table.create(4000, 0)) +end, { buffer.fromstring(string.sub(byName.s16.data, 22 + 4 + 4 + 1, 22 + 4 + 4 + 3000)) }, { mutations = 300 }) +t:done() diff --git a/tests/audio/wavpack.luau b/tests/audio/wavpack.luau new file mode 100644 index 0000000..58acc7b --- /dev/null +++ b/tests/audio/wavpack.luau @@ -0,0 +1,116 @@ +-- audio/wavpack tests: every fixture from tools/fixtures/wavpack.py (wavpack -f / -g / -h / -hh / -x1..6, joint stereo +-- on / off, 8 - 32-bit int and 32-bit float, 1 - 8 channels, odd rates and lengths, hybrid lossy and hybrid lossless +-- with the .wvc, noise shaping, ffmpeg's encoder) decoded bit-exact against wvunpack; seeking; f32 scaling and output +-- reuse; decode() from a sub-range Reader; APEv2 tags and the MD5; the correction file through opts.resolve; sniff; +-- the api; damaged blocks; the fuzz pass. Fixtures: tools/fixtures/wavpack.py. +local T = require("@tests/T") +local WavPack = require("@formats/audio/wavpack") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/wavpack_cases") +local L = require("@tests/audio/_lossless") + +local t = T.suite("wavpack") + +local function open(b: any, opts: any?): (any, any) + return WavPack.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts) +end +local byName = {} +for _, c in Cases do + byName[c.name] = c +end + +t:eq(WavPack.name, "wavpack", "name") +t:check(WavPack.caps.decode and not WavPack.caps.encode, "caps") + +local all = L.all +local seekChecks = L.cases(t, WavPack, Cases, function(fx: any): any + return if fx.wvc then { correction = fx.wvc } else nil +end) +for _, fx in Cases do + local dec = open(fx.data, if fx.wvc then { correction = fx.wvc } else nil) + t:eq(dec.lossless, not fx.lossy, fx.name .. ": lossless") + if fx.wvc then + local lossy = open(fx.data) + t:eq(lossy.lossless, false, fx.name .. ": without wvc: lossy") + t:eq((all(lossy, fx)), fx.lossy_crc, fx.name .. ": without wvc: identical to wvunpack -i") + end +end +t:note("%d fixtures bit-exact against wvunpack, %d seeks", #Cases, seekChecks) + +-- decode() from a sub-range Reader +for _, name in { "s16_g", "md5_tags", "f32", "ch6" } do + L.subrange(t, WavPack, byName[name], "wavpack") +end + +-- tags, md5, the source facts +do + local dec = open(byName.md5_tags.data) + t:eq(#dec.md5, 32, "md5") + t:eq(dec.bitsPerSample, 16, "bitsPerSample") + t:eq(open(byName.s20.data).bitsPerSample, 20, "20-bit") + t:eq(open(byName.s12.data).bitsPerSample, 12, "12-bit") + t:eq(open(byName.hyb_c3.data).hybrid, true, "hybrid") + t:eq(open(byName.ch6.data).channelMask, 0x3F, "channel mask") +end + +-- the correction file through opts.resolve + opts.name (as the api passes them for paths) +do + local fx = byName.hyb_c3 + local asked = nil + local dec = open(fx.data, { + name = "music/song.wv", + resolve = function(uri: string): buffer? + asked = uri + return buffer.fromstring(fx.wvc) + end, + }) + t:eq(asked, "song.wvc", "resolve asks for the .wvc") + t:check(dec.lossless and (all(dec, fx)) == fx.crc, "resolve: lossless") + local dec2 = open(fx.data, { name = "x.wv", resolve = function(): buffer? return nil end }) + t:check(dec2 and not dec2.lossless, "resolve: no wvc -> lossy") +end + +-- the api +do + local fx = byName.s16_g + t:eq(F.detect(buffer.fromstring(fx.data)), "wavpack", "detect") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames and a.meta.source.format == "wavpack", "F.audio.load") + local d = F.audio.open(fx.data) + t:check(d and d.sampleRate == fx.rate, "F.audio.open") +end + +-- errors: damaged data, a bad CRC, no audio +do + local fx = byName.s16_g + local b = buffer.fromstring(fx.data) + buffer.writeu8(b, 200, bit32.bxor(buffer.readu8(b, 200), 0x55)) + local dec = open(b) + if dec then + local _, got = dec:read(fx.frames) + t:check(dec.error ~= nil or got < fx.frames, "damaged block reported") + else + t:check(true, "damaged block reported") + end + local _, e1 = open("wvpk") + t:check(e1 and Err.is(e1), "too short: " .. tostring(e1)) + local _, e2 = open(string.rep("\0", 100)) + t:check(e2 and e2.code == Err.CORRUPT, "no blocks: " .. tostring(e2)) + t:eq(WavPack.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") +end + +-- the fuzz pass +local samples = {} +for _, name in { "s16_g", "f32", "hyb_b3", "s32_hh", "ch6", "u8" } do + table.insert(samples, buffer.fromstring(byName[name].data)) +end +t:fuzz("decode", function(b: buffer) + return WavPack.decode(Bytes.reader(b)) +end, samples, { mutations = 150 }) +local fxw = byName.hyb_c3 +t:fuzz("decode with wvc", function(b: buffer) + return WavPack.decode(Bytes.reader(buffer.fromstring(fxw.data)), { correction = b }) +end, { buffer.fromstring(fxw.wvc) }, { mutations = 100 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index e7533fd..8b805f1 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1182,3 +1182,32 @@ do Qoa.decode(Bytes.reader(file)) end) end +-- ws-audio2: lossless +do + -- WavPack / Monkey's Audio / TTA decoders (tools/fixtures/wavpack.py, ape.py, tta.py): MB/s of f32 output + local function lossless(label: string, mod: any, data: string) + local b = buffer.fromstring(data) + local dec = assert(mod.open(Bytes.reader(b))) + bench(label, 5, dec.frames * dec.channels * 4, function() + mod.decode(Bytes.reader(b)) + end) + end + local Wv = require("@formats/audio/wavpack") + for _, c in require("@tests/gen/wavpack_cases") do + if c.name == "s16_long" or c.name == "s16_hh" or c.name == "s24_hh" or c.name == "f32" or c.name == "hyb_b3" then + lossless("wavpack " .. c.name, Wv, c.data) + end + end + local ApeF = require("@formats/audio/ape") + for _, c in require("@tests/gen/ape_cases") do + if c.name == "s16_long" or c.name == "s16_long_c4000" or c.name == "s16_c5000" or c.name == "s24" or c.name == "s16_c1000" then + lossless("ape " .. c.name, ApeF, c.data) + end + end + local TtaF = require("@formats/audio/tta") + for _, c in require("@tests/gen/tta_cases") do + if c.name == "s16_long" or c.name == "s24" or c.name == "ch6" then + lossless("tta " .. c.name, TtaF, c.data) + end + end +end diff --git a/tools/fixtures/ape.py b/tools/fixtures/ape.py new file mode 100644 index 0000000..2e80483 --- /dev/null +++ b/tools/fixtures/ape.py @@ -0,0 +1,137 @@ +# Monkey's Audio fixtures (tools/fixtures.py): audio/ape, codecs/audio/Ape. +# tests/gen/ape_cases.luau synthetic signals encoded by the reference encoder (mac 13.28: -c1000 .. -c5000, 8 / 16 / +# 24 / 32-bit int and 32-bit float, 1 / 2 / 3 / 4 / 6 / 8 channels, odd rates, short and +# odd lengths, silence (special frames), mono-in-stereo (pseudo stereo), APEv2 tags), and +# the ffmpeg FATE samples luckynight-partial.ape (an older 3.99 encoder, cut) and +# NoLegacy-cut.ape (downloaded at fixture time, not committed); each with the CRC-32 of +# `mac -d`'s samples (integers as i32 LE, floats as their f32 bytes) +import importlib.util, os, struct, tempfile, urllib.request, zlib + +_spec = importlib.util.spec_from_file_location("_wv", os.path.join(os.path.dirname(os.path.abspath(__file__)), "wavpack.py")) +WV = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(WV) + +CTX = None +TMP = None +CASES = [] +FATE = "https://fate-suite.ffmpeg.org/lossless-audio/" + + +def wav_samples(path): + """(rate, channels, bits, float, ints-or-raw-bytes) of a WAV file (PCM / float, plain or extensible)""" + d = open(path, "rb").read() + i = 12 + fmt = data = None + while i + 8 <= len(d): + cid, size = d[i:i + 4], struct.unpack_from(" the same files, for the snippets that load by path +import importlib.util, os, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/docs_inputs.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_lossless_" + name.replace("/", "_"), + os.path.join(ctx.root, "tools", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = load(ctx, "docs_check") + di = load(ctx, "fixtures/docs_inputs") + files = {} + with tempfile.TemporaryDirectory() as d: + wav = os.path.join(d, "tone.wav") + with open(wav, "wb") as f: + f.write(di.tone(44100, 1.0)) + tags = ["-w", "Title=Docs Tone", "-w", "Artist=formats-luau"] + ctx.nix("wavpack", ["wavpack", "-q", "-y", "-h"] + tags + [wav, "-o", os.path.join(d, "tone.wv")]) + ctx.nix("wavpack", ["wavpack", "-q", "-y", "-b3", "-c"] + tags + [wav, "-o", os.path.join(d, "tone_hybrid.wv")]) + ctx.nix("monkeys-audio", ["mac", wav, os.path.join(d, "tone.ape"), "-c2000", "-t", "Title=Docs Tone|Artist=formats-luau"]) + ctx.nix("ttaenc", ["ttaenc", "-e", wav, "-o", os.path.join(d, "tone.tta")]) + for name in ("tone.wv", "tone_hybrid.wv", "tone_hybrid.wvc", "tone.ape", "tone.tta"): + files[name] = open(os.path.join(d, name), "rb").read() + dc.emit_inputs(ctx, files, { + "wvBytes": "tone.wv", + "hybridWvBytes": "tone_hybrid.wv", + "hybridWvcBytes": "tone_hybrid.wvc", + "apeBytes": "tone.ape", + "ttaBytes": "tone.tta", + }) diff --git a/tools/fixtures/tta.py b/tools/fixtures/tta.py new file mode 100644 index 0000000..400924e --- /dev/null +++ b/tools/fixtures/tta.py @@ -0,0 +1,93 @@ +# TTA fixtures (tools/fixtures.py): audio/tta, codecs/audio/Tta. +# tests/gen/tta_cases.luau synthetic signals encoded by the reference encoder (ttaenc 3.4.1: 8 / 16 / 24 bits, +# 1 / 2 / 3 / 6 channels, odd rates, short and odd lengths, several frames, silence, noise, +# full scale) and the ffmpeg FATE sample inside.tta (downloaded at fixture time, cut after 2 +# frames, not committed); each with the CRC-32 of `ttaenc -d`'s samples (i32 LE) +import importlib.util, os, struct, tempfile, urllib.request, zlib + +_dir = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("_wv", os.path.join(_dir, "wavpack.py")) +WV = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(WV) +_spec = importlib.util.spec_from_file_location("_ape", os.path.join(_dir, "ape.py")) +APE = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(APE) + +CTX = None +TMP = None +CASES = [] +FATE = "https://fate-suite.ffmpeg.org/lossless-audio/" + + +def emit(name, tta, note, partial=False, keep=None): + out = tta + ".out.wav" + try: + CTX.nix("ttaenc", ["ttaenc", "-d", tta, "-o", out]) + except Exception: + if not partial: + raise + rate, ch, bits, fl, s = APE.wav_samples(out) + if keep is not None: # a cut file: ttaenc also writes the broken frame; keep the whole ones + s = s[:keep * ch] + CASES.append({"name": name, "note": note, "data": open(tta, "rb").read(), "rate": rate, "channels": ch, + "bits": bits, "float": False, "frames": len(s) // ch, + "crc": zlib.crc32(b"".join(struct.pack("