ws-audio2: Monkey's Audio: codecs/audio/Ape (port of the MAC SDK 13.28 decoder, BSD-3) + audio/ape

File versions 3.95+ (3.99+ verified; the 3.95-3.98 range-coder model is ported without a reference fixture), every
level (fast .. insane), 8/16/24/32-bit int and 32-bit float, 1-32 channels, special frames, frame CRCs, seeking,
APEv2 tags, ID3v2 in front. 35 fixtures (mac 13.28, the FATE luckynight sample) bit-exact against mac -d.
tests/audio/_lossless.luau: the per-fixture checks shared by the lossless format tests. tools/bench.luau: the
ws-audio2 lossless block.
This commit is contained in:
4DBug committed 2026-10-31 14:52:08 -05:00
1 parent 66c3819063
commit ae8ff9d6bf
12 files changed
+1543 -99

No files matched your search

+2
View File
@@ -18,6 +18,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` |
| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` |
| audio | 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 | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` |
| audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` |
@@ -89,6 +90,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/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/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
+1
View File
@@ -39,6 +39,7 @@
| `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) |
| `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").
+11
View File
@@ -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.
+12
View File
@@ -170,6 +170,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",
+134
View File
@@ -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 ^ 26 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
+758
View File
@@ -0,0 +1,758 @@
--!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, low, range, prev = rc.q, rc.low, rc.range, 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, A1 = A2, 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, yA1 = yA2, yA1, A0 - yPrev
yPrev = A0
local B0 = lastX - (yBin * 31) // 32
yBin = lastX
yB4, yB3, yB2, yB1 = yB3, yB2, 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, xA1 = xA2, xA1, A0 - xPrev
xPrev = A0
B0 = yv - (xBin * 31) // 32
xBin = yv
xB4, xB3, xB2, xB1 = xB3, xB2, 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, order = "silence", {}
else
mode, order = "mono", { 1 }
end
elseif C == 2 then
if band(special, 3) == 3 then
mode, order = "silence", {}
elseif band(special, 4) ~= 0 then
mode, order = "pseudo", { 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, b2 = 0, 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
+229
View File
@@ -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
+136
View File
@@ -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
+90
View File
@@ -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()
+10 -99
View File
@@ -6,21 +6,16 @@
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 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 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
@@ -29,108 +24,24 @@ 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
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 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")
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, name .. ": without wvc: lossy")
t:eq((all(lossy, fx)), fx.lossy_crc, name .. ": without wvc: identical to wvunpack -i")
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
-- 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")
L.subrange(t, WavPack, byName[name], "wavpack")
end
-- tags, md5, the source facts
+23
View File
@@ -1078,3 +1078,26 @@ do
jitTune(false)
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
end
+137
View File
@@ -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("<I", d, i + 4)[0]
if cid == b"fmt ":
fmt = d[i + 8:i + 8 + size]
elif cid == b"data":
data = d[i + 8:i + 8 + size]
break
i += 8 + size + (size & 1)
tag, ch, rate = struct.unpack_from("<HHI", fmt, 0)
bits = struct.unpack_from("<H", fmt, 14)[0]
fl = tag == 3 or (tag == 0xFFFE and fmt[24:26] == b"\x03\x00")
w = bits // 8
if fl:
return rate, ch, bits, True, data
if w == 1:
ints = [b - 128 for b in data]
else:
ints = [int.from_bytes(data[k:k + w], "little", signed=True) for k in range(0, len(data) - w + 1, w)]
return rate, ch, bits, False, ints
def emit(name, ape, note, tags=None, partial=False):
out = ape + ".out.wav"
try:
CTX.nix("monkeys-audio", ["mac", ape, out, "-d"])
except Exception:
if not partial: # a cut file: mac writes the whole frames before the cut, then fails
raise
rate, ch, bits, fl, s = wav_samples(out)
if fl:
crc, n = zlib.crc32(s), len(s) // 4
else:
crc, n = zlib.crc32(b"".join(struct.pack("<i", v) for v in s)), len(s)
c = {"name": name, "note": note, "data": open(ape, "rb").read(), "rate": rate, "channels": ch, "bits": bits,
"float": fl, "frames": n // ch, "crc": crc, "partial": partial}
if tags:
c["tags"] = tags
CASES.append(c)
def case(name, level, secs=0.3, rate=44100, ch=2, bits=16, fl=False, kind="music", seed=1, frames=None, note=None,
tags=None, mono_stereo=False):
if fl:
bits = 32
wav = os.path.join(TMP, name + ".wav")
ape = os.path.join(TMP, name + ".ape")
vals = WV.signal(secs, rate, 1 if mono_stereo else ch, kind, seed, frames)
if mono_stereo:
vals = [v for v in vals for _ in range(ch)]
WV.write_wav(wav, vals, ch, rate, bits, fl)
args = ["mac", wav, ape, "-c%d" % level]
if tags:
args += ["-t", "|".join("%s=%s" % kv for kv in tags.items())]
CTX.nix("monkeys-audio", args)
emit(name, ape, note or "mac -c%d, %d-bit%s, %d ch" % (level, bits, " float" if fl else "", ch),
tags={({"year": "date"}).get(k.lower(), k.lower()): v for k, v in tags.items()} if tags else None)
def fate(name, file, cut=None):
path = os.path.join(TMP, file)
try:
with urllib.request.urlopen(FATE + file, timeout=60) as r:
data = r.read()
if cut: # keep `cut` whole frames and a little of the next one
desc = struct.unpack_from("<I", data, 8)[0]
head = struct.unpack_from("<I", data, 12)[0]
data = data[:struct.unpack_from("<I", data, desc + head + 4 * cut)[0] + 64]
open(path, "wb").write(data)
except Exception as e: # offline: skip the FATE samples
print("ape: skipping %s (%s)" % (file, e))
return
emit(name, path, "ffmpeg FATE sample " + file, partial=True)
def generate(ctx):
global CTX, TMP
CTX = ctx
WV.CTX = ctx
TMP = tempfile.mkdtemp()
CASES.clear()
for level in (1000, 2000, 3000, 4000, 5000):
case("s16_c%d" % level, level, seed=level // 1000)
case("s16_long", 2000, secs=3.0, seed=2, note="mac -c2000, 3 s (bench + seek)")
case("s16_long_c4000", 4000, secs=1.5, seed=3, note="mac -c4000, 1.5 s (bench)")
case("mono", 2000, ch=1)
case("mono_c5000", 5000, ch=1, rate=22050, seed=4)
case("u8", 2000, bits=8, ch=1, rate=8000, kind="mixed")
case("u8_stereo", 3000, bits=8, rate=11025)
case("s24", 2000, bits=24, rate=48000, secs=0.2)
case("s24_c4000", 4000, bits=24, rate=96000, secs=0.15, kind="mixed")
case("s24_c5000", 5000, bits=24, rate=48000, secs=0.15, seed=5)
case("s24_mono", 3000, bits=24, ch=1, rate=48000, secs=0.2)
case("s32", 2000, bits=32, rate=48000, secs=0.15)
case("s32_c4000", 4000, bits=32, rate=48000, secs=0.15, kind="mixed")
case("f32", 2000, fl=True, rate=48000, secs=0.15)
case("f32_c3000", 3000, fl=True, rate=44100, secs=0.15, kind="mixed")
case("ch3", 2000, ch=3, secs=0.15)
case("ch4", 3000, ch=4, secs=0.15)
case("ch6", 2000, ch=6, rate=48000, secs=0.15)
case("ch6_24", 3000, ch=6, bits=24, rate=48000, secs=0.1)
case("ch8", 1000, ch=8, rate=48000, secs=0.1)
case("noise", 2000, kind="noise", secs=0.2)
case("noise_c5000", 5000, kind="noise", secs=0.1, seed=6)
case("silence", 2000, kind="silence")
case("mixed", 3000, kind="mixed", secs=0.4)
case("pseudo_stereo", 2000, mono_stereo=True, note="the same signal in both channels (pseudo-stereo frames)")
case("one_frame", 2000, frames=1)
case("seven_frames", 3000, frames=7, ch=1)
case("odd_len", 2000, frames=300001, rate=48000, seed=7, note="300001 frames: two APE frames")
case("rate37000", 2000, rate=37000, secs=0.2)
case("tags", 2000, tags={"Title": "Lossless Tone", "Artist": "formats-luau", "Year": "2026", "Track": "3"})
fate("fate_lucky", "luckynight-partial.ape", cut=2)
ctx.emit("ape_cases", CASES)