ws-audio2: WavPack: codecs/audio/WavPack (port of WavPack 5.9.0's decoder, BSD) + audio/wavpack
Lossless and hybrid (lossy, and lossless with the .wvc via opts.correction / opts.resolve), 8-32 bit int (int32 modes, wvx) and 32-bit float, 1-8+ channels, every decorrelation pass, joint stereo, cross decorrelation, noise shaping, block CRCs; APEv2 tags; sample-accurate seeking. 58 fixtures (wavpack -f..-hhx6, ffmpeg) bit-exact against wvunpack. codecs/audio/Stream (shared, backward compatible): Stream.packets takes optional spec.scale (read() writes pcm values times scale) and spec.ints (adds dec:readInt for bit-exact integer reads).
This commit is contained in:
1 parent
b7006dbbed
commit
967b91db91
11 files changed
+2435
-6
No files matched your search
@@ -27,6 +27,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| 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` |
|
||||
@@ -88,6 +89,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- **audio**
|
||||
- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
|
||||
- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
|
||||
- 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/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
|
||||
- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it:
|
||||
@@ -99,6 +101,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
|
||||
- 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
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
|
||||
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
|
||||
| `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/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) |
|
||||
|
||||
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").
|
||||
@@ -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.
|
||||
@@ -278,6 +278,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",
|
||||
|
||||
@@ -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("<name>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
|
||||
@@ -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
|
||||
@@ -91,9 +96,21 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
local src = pcmOf()
|
||||
local q = got * ch * 4
|
||||
local s = pendPos * ch
|
||||
for k = 1, take * ch do
|
||||
writef32(ob, q, src[s + k])
|
||||
q += 4
|
||||
if 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
|
||||
@@ -102,6 +119,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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -0,0 +1,235 @@
|
||||
--!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 #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
|
||||
@@ -0,0 +1,205 @@
|
||||
-- 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 Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local F = require("@formats")
|
||||
local Cases = require("@tests/gen/wavpack_cases")
|
||||
|
||||
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 f32buf = buffer.create(4)
|
||||
local function f32(x: number): number
|
||||
buffer.writef32(f32buf, 0, x)
|
||||
return buffer.readf32(f32buf, 0)
|
||||
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")
|
||||
|
||||
-- all(dec, fx) -> crc of every sample (i32 for integer streams, the f32 bytes for floats), frames, the values
|
||||
local function 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
|
||||
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
|
||||
|
||||
local seekChecks = 0
|
||||
for _, fx in Cases do
|
||||
local name = fx.name
|
||||
local opts = if fx.wvc then { correction = fx.wvc } else nil
|
||||
local dec, err = open(fx.data, opts)
|
||||
t:check(dec, name .. ": open: " .. tostring(err))
|
||||
t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels, name .. ": format")
|
||||
t:eq(dec.frames, fx.frames, name .. ": frames")
|
||||
t:eq(dec.float, fx.float, name .. ": float")
|
||||
t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration")
|
||||
local crc, n, vals = all(dec, fx)
|
||||
t:eq(dec.error, nil, name .. ": no decode error")
|
||||
t:eq(n, fx.frames, name .. ": decoded frames")
|
||||
t:eq(crc, fx.crc, name .. ": samples identical to wvunpack")
|
||||
t:eq(dec.lossless, not fx.lossy, name .. ": lossless")
|
||||
if fx.wvc then
|
||||
local lossy = open(fx.data)
|
||||
t:eq(lossy.lossless, false, name .. ": without wvc: lossy")
|
||||
t:eq((all(lossy, fx)), fx.lossy_crc, name .. ": without wvc: identical to wvunpack -i")
|
||||
end
|
||||
-- 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 - 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 rand = T.rng(7)
|
||||
local targets = { 0, 1, fx.frames - 1, fx.frames // 2, 22050, 22049, 22051 }
|
||||
for _ = 1, 6 do
|
||||
table.insert(targets, rand(fx.frames))
|
||||
end
|
||||
for _, s in targets do
|
||||
if s >= 0 and s < fx.frames 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")
|
||||
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(WavPack.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff")
|
||||
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
|
||||
local fx = byName[name]
|
||||
local big = buffer.create(#fx.data + 13)
|
||||
buffer.writestring(big, 6, fx.data)
|
||||
local a, err = WavPack.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(fx.data):read(fx.frames)
|
||||
t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read")
|
||||
t:eq(a.meta.source.format, "wavpack", name .. ": meta.source")
|
||||
t:eq(a.meta.source.bitDepth, if fx.float then 32 else fx.bits, name .. ": bit depth")
|
||||
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()
|
||||
@@ -0,0 +1,177 @@
|
||||
# WavPack fixtures (tools/fixtures.py): audio/wavpack, codecs/audio/WavPack.
|
||||
# tests/gen/wavpack_cases.luau synthetic signals encoded by the reference encoder (wavpack 5.9: -f / default / -h /
|
||||
# -hh / -x1..6, joint stereo on / off, 8 / 12 / 16 / 20 / 24 / 32-bit int and 32-bit
|
||||
# float, 1 / 2 / 3 / 6 / 8 channels, odd rates, short and odd lengths, small blocks,
|
||||
# hybrid lossy (-b, noise shaping) and hybrid lossless (+ the .wvc), APEv2 tags, MD5)
|
||||
# and by ffmpeg's encoder; each with the CRC-32 of wvunpack's raw output (integers as
|
||||
# i32 LE, floats as their f32 bytes)
|
||||
import math, os, random, struct, tempfile, zlib
|
||||
|
||||
CTX = None
|
||||
TMP = None
|
||||
CASES = []
|
||||
|
||||
|
||||
def signal(secs, rate, ch, kind="music", seed=1, frames=None):
|
||||
"""floats in -1..1, interleaved"""
|
||||
rnd = random.Random(seed)
|
||||
n = frames if frames is not None else int(secs * rate)
|
||||
out = []
|
||||
notes = [(rnd.uniform(80, 1500), rnd.uniform(0, max(n, 1)), rnd.uniform(0.1, 0.5) * rate) for _ in range(int(n / rate * 6) + 3)]
|
||||
for i in range(n):
|
||||
t = i / rate
|
||||
for c in range(ch):
|
||||
if kind == "noise":
|
||||
v = rnd.uniform(-0.95, 0.95)
|
||||
elif kind == "silence":
|
||||
v = 0.0
|
||||
elif kind == "mixed": # silence, a tone, noise bursts, full scale
|
||||
seg = (i * 8 // max(n, 1))
|
||||
if seg in (0, 4):
|
||||
v = 0.0
|
||||
elif seg == 5:
|
||||
v = rnd.uniform(-1, 1)
|
||||
elif seg == 6:
|
||||
v = 0.999 if (i // 37) % 2 else -1.0
|
||||
else:
|
||||
v = 0.7 * math.sin(2 * math.pi * (300 + 50 * c) * t)
|
||||
else:
|
||||
v = 0.0
|
||||
for f, st, dur in notes:
|
||||
if st <= i < st + dur:
|
||||
e = math.exp(-3 * (i - st) / dur) * min(1.0, (i - st) / 100)
|
||||
v += 0.25 * e * (math.sin(2 * math.pi * f * (1 + 0.002 * c) * t) + 0.3 * math.sin(6 * math.pi * f * t + c))
|
||||
v += 0.003 * (rnd.random() - 0.5) + 0.04 * math.sin(2 * math.pi * (60 + 7 * c) * t)
|
||||
out.append(max(-1.0, min(1.0, v)))
|
||||
return out
|
||||
|
||||
|
||||
def write_wav(path, vals, ch, rate, bits, fl=False):
|
||||
container = 32 if fl else (bits + 7) // 8 * 8
|
||||
data = bytearray()
|
||||
top = (1 << (bits - 1)) - 1
|
||||
for v in vals:
|
||||
if fl:
|
||||
data += struct.pack("<f", v)
|
||||
continue
|
||||
x = int(round(v * top)) if v < 1 else top
|
||||
x = max(-top - 1, min(top, x)) << (container - bits)
|
||||
if container == 8:
|
||||
data.append((x + 128) & 255)
|
||||
else:
|
||||
data += x.to_bytes(container // 8, "little", signed=True)
|
||||
sub = b"\x03\x00" if fl else b"\x01\x00"
|
||||
guid = sub + b"\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71"
|
||||
mask = {1: 4, 2: 3, 3: 7, 4: 0x33, 6: 0x3F, 8: 0x63F}.get(ch, 0)
|
||||
fmt = struct.pack("<HHIIHHHHI16s", 0xFFFE, ch, rate, rate * ch * container // 8, ch * container // 8, container,
|
||||
22, bits, mask, guid)
|
||||
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data)
|
||||
open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body)
|
||||
|
||||
|
||||
def reference(wv, container, fl, ignore_wvc=False):
|
||||
raw = wv + ".raw"
|
||||
CTX.nix("wavpack", ["wvunpack", "-q", "-y", "-r"] + (["-i"] if ignore_wvc else []) + [wv, "-o", raw])
|
||||
d = open(raw, "rb").read()
|
||||
if fl:
|
||||
return zlib.crc32(d), len(d) // 4
|
||||
w = container // 8
|
||||
if w == 1:
|
||||
ints = [b - 128 for b in d]
|
||||
else:
|
||||
ints = [int.from_bytes(d[i:i + w], "little", signed=True) for i in range(0, len(d), w)]
|
||||
return zlib.crc32(b"".join(struct.pack("<i", v) for v in ints)), len(ints)
|
||||
|
||||
|
||||
def case(name, args, secs=0.3, rate=44100, ch=2, bits=16, fl=False, kind="music", seed=1, frames=None, note=None,
|
||||
wvc=False, lossy=False, tags=None, ffmpeg=None):
|
||||
if fl:
|
||||
bits = 32
|
||||
wav = os.path.join(TMP, name + ".wav")
|
||||
wv = os.path.join(TMP, name + ".wv")
|
||||
write_wav(wav, signal(secs, rate, ch, kind, seed, frames), ch, rate, bits, fl)
|
||||
if ffmpeg is not None:
|
||||
CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + ffmpeg + [wv])
|
||||
else:
|
||||
CTX.nix("wavpack", ["wavpack", "-q", "-y"] + args + [wav, "-o", wv])
|
||||
data = open(wv, "rb").read()
|
||||
k = 0
|
||||
while struct.unpack_from("<I", data, k + 20)[0] == 0: # the first audio block's flags give the container
|
||||
k += 8 + struct.unpack_from("<I", data, k + 4)[0]
|
||||
flags = struct.unpack_from("<I", data, k + 24)[0]
|
||||
container = ((flags & 3) + 1) * 8
|
||||
crc, count = reference(wv, container, fl, ignore_wvc=lossy)
|
||||
c = {"name": name, "note": note or ("ffmpeg " + " ".join(ffmpeg) if ffmpeg is not None else "wavpack " + " ".join(args)),
|
||||
"data": data, "rate": rate, "channels": ch, "bits": bits, "container": container,
|
||||
"float": fl, "frames": count // ch, "crc": crc, "lossy": lossy}
|
||||
if wvc:
|
||||
c["wvc"] = open(wv + "c", "rb").read()
|
||||
c["lossy_crc"] = reference(wv, container, fl, ignore_wvc=True)[0]
|
||||
if tags:
|
||||
c["tags"] = tags
|
||||
CASES.append(c)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
global CTX, TMP
|
||||
CTX = ctx
|
||||
TMP = tempfile.mkdtemp()
|
||||
CASES.clear()
|
||||
for mode in ("-f", "-g", "-h", "-hh"):
|
||||
case("s16" + mode.replace("-", "_"), [mode])
|
||||
for x in range(1, 7):
|
||||
case("s16_x%d" % x, ["-x%d" % x], secs=0.2, seed=x)
|
||||
case("s16_hhx6", ["-hh", "-x6"], seed=7)
|
||||
case("s16_j0", ["-j0"], seed=8)
|
||||
case("s16_j1_hh", ["-j1", "-hh"], seed=9)
|
||||
case("s16_long", ["-h"], secs=3.0, seed=2, note="wavpack -h, 3 s (bench + seek)")
|
||||
case("mono16", ["-g"], ch=1)
|
||||
case("mono16_hh", ["-hh", "-x4"], ch=1, rate=22050)
|
||||
case("u8", ["-g"], bits=8, ch=1, rate=8000, kind="mixed")
|
||||
case("u8_stereo", ["-h"], bits=8, rate=11025)
|
||||
case("s12", ["-g"], bits=12, rate=32000)
|
||||
case("s20", ["-hh"], bits=20, rate=48000)
|
||||
case("s24", ["-g"], bits=24, rate=96000, secs=0.2)
|
||||
case("s24_hh", ["-hh", "-x3"], bits=24, rate=48000, kind="mixed")
|
||||
case("s32", ["-g"], bits=32, rate=48000, secs=0.2)
|
||||
case("s32_hh", ["-hh"], bits=32, rate=48000, secs=0.2, kind="mixed")
|
||||
case("s32_opt", ["--optimize-int32"], bits=32, rate=48000, secs=0.2)
|
||||
case("f32", ["-g"], fl=True, rate=48000, secs=0.2)
|
||||
case("f32_hh", ["-hh", "-x2"], fl=True, rate=44100, kind="mixed")
|
||||
case("f32_mono", ["-f"], fl=True, ch=1, rate=22050)
|
||||
case("ch3", ["-g"], ch=3, bits=24, secs=0.2)
|
||||
case("ch6", ["-h"], ch=6, rate=48000, secs=0.2)
|
||||
case("ch8", ["-f"], ch=8, rate=48000, secs=0.1)
|
||||
case("noise", ["-g"], kind="noise", secs=0.2)
|
||||
case("silence", ["-g"], kind="silence", secs=0.3)
|
||||
case("mixed", ["-hh"], kind="mixed", secs=0.4)
|
||||
case("one_frame", ["-g"], frames=1)
|
||||
case("seven_frames", ["-h"], frames=7, ch=1)
|
||||
case("odd_len", ["-g", "--blocksize=1001"], frames=12345, seed=3, note="block size 1001, 12345 frames")
|
||||
case("rate37000", ["-g"], rate=37000, secs=0.2, note="a rate without a header code")
|
||||
case("rate7", ["-g"], rate=7, frames=300, note="7 Hz")
|
||||
case("md5_tags", ["-g", "-m", "-w", "Title=Lossless Tone", "-w", "Artist=formats-luau", "-w", "Year=2026",
|
||||
"-w", "Track=3/9", "-w", "Album Artist=Some Band"],
|
||||
tags={"title": "Lossless Tone", "artist": "formats-luau", "date": "2026", "track": "3/9",
|
||||
"albumartist": "Some Band"})
|
||||
# hybrid: lossy (no correction file), and lossless with the .wvc
|
||||
case("hyb_b3", ["-b3"], lossy=True, note="hybrid lossy, 3 bits / sample")
|
||||
case("hyb_b2_mono", ["-b2.5", "-h"], ch=1, lossy=True)
|
||||
case("hyb_b4_s0", ["-b4", "-s0"], lossy=True, note="hybrid lossy, no noise shaping")
|
||||
case("hyb_b3_24", ["-b3.5", "-hh"], bits=24, rate=48000, lossy=True)
|
||||
case("hyb_c3", ["-b3", "-c"], wvc=True, note="hybrid lossless (wv + wvc)")
|
||||
case("hyb_c3_shape", ["-b3", "-c", "-s0.5"], wvc=True, seed=4, note="hybrid lossless, positive noise shaping")
|
||||
case("hyb_c3_neg", ["-b3", "-c", "-s-0.5"], wvc=True, seed=5, note="hybrid lossless, negative shaping (NEW_SHAPING)")
|
||||
case("hyb_cc", ["-b2.5", "-cc", "-h"], wvc=True, seed=6, note="hybrid lossless, max compression (cross decorr)")
|
||||
case("hyb_c_mono", ["-b3", "-c", "-hh"], ch=1, wvc=True)
|
||||
case("hyb_c_dns", ["-b3", "-c", "--use-dns"], wvc=True, seed=10, note="dynamic noise shaping")
|
||||
case("hyb_c_24", ["-b4", "-c", "-x3"], bits=24, rate=48000, wvc=True)
|
||||
case("hyb_c_f32", ["-b4", "-c"], fl=True, wvc=True, note="hybrid lossless float (wvx in the wvc)")
|
||||
case("hyb_c_ch6", ["-b3", "-c"], ch=6, rate=48000, secs=0.2, wvc=True)
|
||||
# ffmpeg's encoder
|
||||
case("ff_s16", [], ffmpeg=["-c:a", "wavpack"])
|
||||
case("ff_l8", [], ffmpeg=["-c:a", "wavpack", "-compression_level", "8"], seed=11)
|
||||
case("ff_s24", [], bits=24, ffmpeg=["-c:a", "wavpack", "-sample_fmt", "s32p"], seed=12)
|
||||
case("ff_f32", [], fl=True, ffmpeg=["-c:a", "wavpack"], seed=13)
|
||||
case("ff_mono", [], ch=1, ffmpeg=["-c:a", "wavpack", "-compression_level", "3"], seed=14)
|
||||
ctx.emit("wavpack_cases", CASES)
|
||||
Reference in new issue
Block a user